feat: media keys, device recovery, settings and a macOS app bundle
- Media keys and Now Playing (souvlaki): title, artist, album, cover and position published on track and state changes; play/pause/toggle, next/previous and seeking from the OS controls - Audio engine reopens the default output when the device changes or disappears, reloading the current track at the same position; with no device it keeps looking and resumes when one appears. Underruns are ignored rather than treated as device loss - Settings screen: streaming quality (Best, Balanced <=192 kbps, Data saver <=128 kbps), appearance (system/light/dark), clear cover cache; quality, appearance and volume persist as JSON in the config folder - Bitrate cap chooses the best variant within it, or the smallest above - Lyrics failures get a retry button - App icon drawn by tool/make_icon.py; tool/bundle-macos.sh builds an ad-hoc signed Musyx.app (--install copies it to /Applications) - Release profile: thin LTO and stripped symbols
This commit is contained in:
1 parent
e2312f2d40
commit
60156aba94
19 files changed
+1039
-94
No files matched your search
@@ -14,6 +14,8 @@ rodio = { version = "0.23.0", default-features = false, features = ["playback",
|
||||
rand = "0.9"
|
||||
open = "5.4.4"
|
||||
serde_json = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
souvlaki = "0.8.3"
|
||||
tokio = { version = "1", features = ["time", "rt", "fs", "sync"] }
|
||||
directories = "6.0.0"
|
||||
png = { version = "0.18.1", optional = true }
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 68 KiB |
+111
-6
@@ -24,6 +24,7 @@ use crate::screens::wave::WaveScreen;
|
||||
use crate::screens::detail::{self, Page};
|
||||
use crate::screens::{self, Loadable, sign_in};
|
||||
use crate::session::{self, Restored};
|
||||
use crate::store::{self, Appearance, Quality, Settings};
|
||||
use crate::ui::theme::{self, shell};
|
||||
use crate::widgets::drawer::{self, Panel};
|
||||
use crate::widgets::player_bar;
|
||||
@@ -70,6 +71,13 @@ pub struct App {
|
||||
lyric_line: Option<usize>,
|
||||
/// The queue published to Yandex for the list playing now.
|
||||
server_queue: Option<String>,
|
||||
settings: Settings,
|
||||
/// The OS appearance, used when settings say "Match system".
|
||||
system_mode: Mode,
|
||||
/// Volume changed and not yet saved; saved once the slider settles.
|
||||
settings_dirty: Option<std::time::Instant>,
|
||||
/// Media keys and the system's Now Playing widget.
|
||||
media: crate::media::Media,
|
||||
/// A live snapshot run opens this route once signed in.
|
||||
#[cfg(feature = "snapshot")]
|
||||
snapshot_route: Option<Route>,
|
||||
@@ -114,6 +122,13 @@ pub enum Message {
|
||||
SetWaveSettings(WaveSettings),
|
||||
WaveSettingsSaved(WaveSettings, Result<(), Error>),
|
||||
WaveTick,
|
||||
SetQuality(Quality),
|
||||
SetAppearance(Appearance),
|
||||
SaveSettings,
|
||||
SettingsSaved(Result<(), String>),
|
||||
ClearCoverCache,
|
||||
CoverCacheCleared(Result<(), String>),
|
||||
Media(crate::media::Command),
|
||||
LoadLikedIds,
|
||||
LikedIdsLoaded(Result<LikedIds, Error>),
|
||||
LikeTrack(Track, bool),
|
||||
@@ -137,6 +152,7 @@ pub enum Message {
|
||||
MovePlaylistTrack { id: PlaylistId, track: Track, from: usize, to: usize },
|
||||
Edited(Box<edit::Edited>),
|
||||
LyricsLoaded(String, Result<Option<Arc<Lyrics>>, Error>),
|
||||
RetryLyrics,
|
||||
QueueCreated(Result<Option<String>, Error>),
|
||||
ToastTick,
|
||||
CoverWanted(String),
|
||||
@@ -167,9 +183,18 @@ impl App {
|
||||
lyrics: HashMap::new(),
|
||||
lyric_line: None,
|
||||
server_queue: None,
|
||||
settings: Settings::default(),
|
||||
system_mode: Mode::Dark,
|
||||
settings_dirty: None,
|
||||
media: crate::media::Media::new(),
|
||||
#[cfg(feature = "snapshot")]
|
||||
snapshot_route: None,
|
||||
};
|
||||
let mut app = app;
|
||||
app.settings = store::load();
|
||||
app.player.volume = app.settings.volume;
|
||||
app.apply_theme();
|
||||
let app = app;
|
||||
let appearance = iced::system::theme().map(Message::ThemeChanged);
|
||||
|
||||
#[cfg(feature = "snapshot")]
|
||||
@@ -209,10 +234,21 @@ impl App {
|
||||
self.theme.clone()
|
||||
}
|
||||
|
||||
/// Snapshot override, then the user's choice, then the system appearance.
|
||||
fn apply_theme(&mut self) {
|
||||
let mode = self.forced_mode.unwrap_or(match self.settings.appearance {
|
||||
Appearance::System => self.system_mode,
|
||||
Appearance::Light => Mode::Light,
|
||||
Appearance::Dark => Mode::Dark,
|
||||
});
|
||||
self.theme = theme::for_mode(mode);
|
||||
}
|
||||
|
||||
pub fn subscription(&self) -> Subscription<Message> {
|
||||
let appearance = iced::system::theme_changes().map(Message::ThemeChanged);
|
||||
let audio = player::engine::subscription().map(|e| Message::Player(player::Msg::Engine(e)));
|
||||
let mut subs = vec![appearance, audio];
|
||||
let keys = crate::media::subscription().map(Message::Media);
|
||||
let mut subs = vec![appearance, audio, keys];
|
||||
if let Session::SignedOut(sign_in) = &self.session {
|
||||
subs.push(sign_in.subscription().map(Message::SignIn));
|
||||
}
|
||||
@@ -223,6 +259,9 @@ impl App {
|
||||
if hero_visible && wave_playing && matches!(self.session, Session::SignedIn { .. }) {
|
||||
subs.push(iced::time::every(std::time::Duration::from_millis(33)).map(|_| Message::WaveTick));
|
||||
}
|
||||
if self.settings_dirty.is_some() {
|
||||
subs.push(iced::time::every(std::time::Duration::from_millis(500)).map(|_| Message::SaveSettings));
|
||||
}
|
||||
if self.toast.is_some() {
|
||||
subs.push(iced::time::every(std::time::Duration::from_millis(500)).map(|_| Message::ToastTick));
|
||||
}
|
||||
@@ -283,7 +322,40 @@ impl App {
|
||||
fn update_inner(&mut self, message: Message) -> Task<Message> {
|
||||
match message {
|
||||
Message::ThemeChanged(mode) => {
|
||||
self.theme = theme::for_mode(self.forced_mode.unwrap_or(mode));
|
||||
self.system_mode = mode;
|
||||
self.apply_theme();
|
||||
}
|
||||
Message::SetQuality(quality) => {
|
||||
self.settings.quality = quality;
|
||||
self.toast(format!("Streaming quality: {}. Applies from the next track.", quality.label()));
|
||||
return self.update(Message::SaveSettings);
|
||||
}
|
||||
Message::SetAppearance(appearance) => {
|
||||
self.settings.appearance = appearance;
|
||||
self.apply_theme();
|
||||
return self.update(Message::SaveSettings);
|
||||
}
|
||||
Message::SaveSettings => {
|
||||
// Wait for the volume slider to settle before writing.
|
||||
if self.settings_dirty.is_some_and(|at| at.elapsed() < std::time::Duration::from_millis(800)) {
|
||||
return Task::none();
|
||||
}
|
||||
self.settings_dirty = None;
|
||||
return Task::future(store::save(self.settings)).map(Message::SettingsSaved);
|
||||
}
|
||||
Message::SettingsSaved(result) => {
|
||||
if let Err(e) = result {
|
||||
eprintln!("settings: {e}");
|
||||
self.toast("Couldn't save your settings. They'll apply until Musyx quits.");
|
||||
}
|
||||
}
|
||||
Message::ClearCoverCache => {
|
||||
return self.covers.clear_disk().map(Message::CoverCacheCleared);
|
||||
}
|
||||
Message::CoverCacheCleared(Ok(())) => self.toast("Cover cache cleared"),
|
||||
Message::CoverCacheCleared(Err(e)) => {
|
||||
eprintln!("clear covers: {e}");
|
||||
self.toast("Couldn't clear the cover cache.");
|
||||
}
|
||||
Message::Restore => {
|
||||
self.session = Session::Restoring;
|
||||
@@ -379,7 +451,13 @@ impl App {
|
||||
Message::CloseDrawer => self.drawer = None,
|
||||
Message::Player(msg) => {
|
||||
let before = self.player.track().map(|t| t.id.clone());
|
||||
let seeked = matches!(msg, player::Msg::Seek(_) | player::Msg::SeekCommit);
|
||||
let effects = self.player.update(msg);
|
||||
self.media.update(self.player.track(), self.player.status(), self.player.position(), seeked);
|
||||
if self.player.volume != self.settings.volume {
|
||||
self.settings.volume = self.player.volume;
|
||||
self.settings_dirty = Some(std::time::Instant::now());
|
||||
}
|
||||
let run = self.run(effects);
|
||||
if self.player.track().map(|t| t.id.as_str()) != before.as_deref() {
|
||||
self.lyric_line = None;
|
||||
@@ -396,6 +474,24 @@ impl App {
|
||||
self.toast(format!("“{}” plays next", track.full_title()));
|
||||
return self.update(Message::Player(player::Msg::PlayNext(track)));
|
||||
}
|
||||
Message::Media(command) => {
|
||||
use crate::media::Command as C;
|
||||
let status = self.player.status();
|
||||
let msg = match command {
|
||||
C::Play if status != player::Status::Playing => player::Msg::Toggle,
|
||||
C::Pause if status == player::Status::Playing => player::Msg::Toggle,
|
||||
C::Play | C::Pause => return Task::none(),
|
||||
C::Toggle => player::Msg::Toggle,
|
||||
C::Next => player::Msg::Next,
|
||||
C::Previous => player::Msg::Previous,
|
||||
C::SeekTo(at) => player::Msg::Seek(at),
|
||||
C::SeekBy { forward, by } => {
|
||||
let now = self.player.position();
|
||||
player::Msg::Seek(if forward { now + by } else { now.saturating_sub(by) })
|
||||
}
|
||||
};
|
||||
return self.update(Message::Player(msg));
|
||||
}
|
||||
Message::SkipFromMenu => {
|
||||
self.sheet = None;
|
||||
return self.update(Message::Player(player::Msg::Next));
|
||||
@@ -436,6 +532,12 @@ impl App {
|
||||
}
|
||||
self.lyrics.insert(id, Loadable::from_result(result));
|
||||
}
|
||||
Message::RetryLyrics => {
|
||||
if let Some(id) = self.player.track().map(|t| t.id.clone()) {
|
||||
self.lyrics.remove(&id);
|
||||
}
|
||||
return self.want_lyrics();
|
||||
}
|
||||
Message::QueueCreated(Ok(id)) => self.server_queue = id,
|
||||
Message::QueueCreated(Err(e)) => {
|
||||
eprintln!("publish queue: {e}");
|
||||
@@ -784,6 +886,7 @@ impl App {
|
||||
player: &self.player,
|
||||
wave: &self.wave,
|
||||
wave_phase: self.wave_phase,
|
||||
settings: &self.settings,
|
||||
}))
|
||||
.height(Fill)
|
||||
.style(theme::scroll);
|
||||
@@ -859,13 +962,15 @@ impl App {
|
||||
Task::batch(effects.into_iter().map(|effect| match effect {
|
||||
Effect::Fetch { generation, track_id } => {
|
||||
let client = client.clone();
|
||||
Task::future(async move { fetch_audio(&client, &track_id).await })
|
||||
let cap = self.settings.quality.max_kbps();
|
||||
Task::future(async move { fetch_audio(&client, &track_id, cap).await })
|
||||
.map(move |result| Message::Player(player::Msg::Fetched { generation, result }))
|
||||
}
|
||||
Effect::Prefetch { track_id } => {
|
||||
let client = client.clone();
|
||||
let cap = self.settings.quality.max_kbps();
|
||||
Task::future(async move {
|
||||
let result = fetch_audio(&client, &track_id).await;
|
||||
let result = fetch_audio(&client, &track_id, cap).await;
|
||||
(track_id, result)
|
||||
})
|
||||
.map(|(track_id, result)| Message::Player(player::Msg::Prefetched { track_id, result }))
|
||||
@@ -919,8 +1024,8 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
async fn fetch_audio(client: &YmClient, track_id: &str) -> Result<Audio, Error> {
|
||||
let stream = client.stream(track_id).await?;
|
||||
async fn fetch_audio(client: &YmClient, track_id: &str, max_kbps: Option<u32>) -> Result<Audio, Error> {
|
||||
let stream = client.stream(track_id, max_kbps).await?;
|
||||
let bytes = client.fetch(&stream).await?;
|
||||
Ok(Audio { stream, bytes })
|
||||
}
|
||||
|
||||
@@ -84,6 +84,19 @@ impl Covers {
|
||||
})
|
||||
}
|
||||
|
||||
/// Deletes the on-disk cache and forgets failures; images in memory stay for this session.
|
||||
pub fn clear_disk(&mut self) -> Task<Result<(), String>> {
|
||||
self.failed.clear();
|
||||
let Some(dir) = self.dir.clone() else { return Task::done(Ok(())) };
|
||||
Task::future(async move {
|
||||
match tokio::fs::remove_dir_all(&dir).await {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn loaded(&mut self, url: String, bytes: Option<Arc<[u8]>>) {
|
||||
self.pending.remove(&url);
|
||||
match bytes {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
mod app;
|
||||
mod covers;
|
||||
mod media;
|
||||
mod player;
|
||||
mod route;
|
||||
mod screens;
|
||||
mod session;
|
||||
mod store;
|
||||
#[cfg(feature = "snapshot")]
|
||||
mod snapshot;
|
||||
mod ui;
|
||||
@@ -23,6 +25,7 @@ fn main() -> iced::Result {
|
||||
.window(window::Settings {
|
||||
size: Size::new(1280.0, 800.0),
|
||||
min_size: Some(Size::new(960.0, 620.0)),
|
||||
icon: window::icon::from_file_data(include_bytes!("../assets/icon/musyx.png"), None).ok(),
|
||||
..window::Settings::default()
|
||||
})
|
||||
.centered();
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
//! Media keys and the system's Now Playing widget (macOS Control Center,
|
||||
//! Windows media overlay, Linux MPRIS), through `souvlaki`.
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use iced::Subscription;
|
||||
use iced::futures::{SinkExt, Stream};
|
||||
use souvlaki::{MediaControlEvent, MediaControls, MediaMetadata, MediaPlayback, MediaPosition, PlatformConfig};
|
||||
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
|
||||
use ym_api::Track;
|
||||
|
||||
use crate::covers;
|
||||
use crate::player::Status;
|
||||
|
||||
/// What the media keys asked for, in player terms.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Command {
|
||||
Play,
|
||||
Pause,
|
||||
Toggle,
|
||||
Next,
|
||||
Previous,
|
||||
SeekTo(Duration),
|
||||
SeekBy { forward: bool, by: Duration },
|
||||
}
|
||||
|
||||
/// Without an amount, a seek key jumps this far.
|
||||
const SEEK_STEP: Duration = Duration::from_secs(10);
|
||||
|
||||
impl Command {
|
||||
fn from_event(event: MediaControlEvent) -> Option<Self> {
|
||||
use souvlaki::SeekDirection::Forward;
|
||||
Some(match event {
|
||||
MediaControlEvent::Play => Command::Play,
|
||||
MediaControlEvent::Pause | MediaControlEvent::Stop => Command::Pause,
|
||||
MediaControlEvent::Toggle => Command::Toggle,
|
||||
MediaControlEvent::Next => Command::Next,
|
||||
MediaControlEvent::Previous => Command::Previous,
|
||||
MediaControlEvent::SetPosition(MediaPosition(at)) => Command::SeekTo(at),
|
||||
MediaControlEvent::Seek(dir) => Command::SeekBy { forward: dir == Forward, by: SEEK_STEP },
|
||||
MediaControlEvent::SeekBy(dir, by) => Command::SeekBy { forward: dir == Forward, by },
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The OS calls back on its own thread; this hands commands to the subscription.
|
||||
static INBOX: Mutex<Option<UnboundedReceiver<Command>>> = Mutex::new(None);
|
||||
|
||||
/// Owns the OS integration. Created on the main thread at startup.
|
||||
pub struct Media {
|
||||
controls: Option<MediaControls>,
|
||||
/// What was last published, so unchanged state isn't sent again.
|
||||
shown: Option<(String, Status)>,
|
||||
}
|
||||
|
||||
impl Media {
|
||||
pub fn new() -> Self {
|
||||
let (tx, rx): (UnboundedSender<Command>, _) = unbounded_channel();
|
||||
let controls = MediaControls::new(PlatformConfig { display_name: "Musyx", dbus_name: "musyx", hwnd: None })
|
||||
.and_then(|mut c| {
|
||||
c.attach(move |event| {
|
||||
if let Some(command) = Command::from_event(event) {
|
||||
let _ = tx.send(command);
|
||||
}
|
||||
})?;
|
||||
Ok(c)
|
||||
});
|
||||
match controls {
|
||||
Ok(c) => {
|
||||
if let Ok(mut inbox) = INBOX.lock() {
|
||||
*inbox = Some(rx);
|
||||
}
|
||||
Self { controls: Some(c), shown: None }
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("media controls unavailable: {e:?}");
|
||||
Self { controls: None, shown: None }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Publishes the track and play state; `force` resends the position after a seek.
|
||||
pub fn update(&mut self, track: Option<&Track>, status: Status, position: Duration, force: bool) {
|
||||
let Some(controls) = &mut self.controls else { return };
|
||||
let Some(track) = track else {
|
||||
if self.shown.take().is_some() {
|
||||
let _ = controls.set_playback(MediaPlayback::Stopped);
|
||||
}
|
||||
return;
|
||||
};
|
||||
let new_track = self.shown.as_ref().is_none_or(|(id, _)| *id != track.id);
|
||||
let new_status = self.shown.as_ref().is_none_or(|(_, s)| *s != status);
|
||||
if !new_track && !new_status && !force {
|
||||
return;
|
||||
}
|
||||
if new_track {
|
||||
let title = track.full_title();
|
||||
let artist = track.artist_line();
|
||||
let album = track.album.as_ref().map(|a| a.title.clone());
|
||||
let cover = track.cover_url(covers::LARGE);
|
||||
let _ = controls.set_metadata(MediaMetadata {
|
||||
title: Some(&title),
|
||||
artist: Some(&artist),
|
||||
album: album.as_deref(),
|
||||
cover_url: cover.as_deref(),
|
||||
duration: Some(track.duration),
|
||||
});
|
||||
}
|
||||
let progress = Some(MediaPosition(position));
|
||||
let _ = controls.set_playback(match status {
|
||||
Status::Playing | Status::Loading => MediaPlayback::Playing { progress },
|
||||
Status::Paused | Status::Ended => MediaPlayback::Paused { progress },
|
||||
});
|
||||
self.shown = Some((track.id.clone(), status));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn subscription() -> Subscription<Command> {
|
||||
Subscription::run(commands)
|
||||
}
|
||||
|
||||
fn commands() -> impl Stream<Item = Command> {
|
||||
iced::stream::channel(16, async |mut output| {
|
||||
let inbox = INBOX.lock().ok().and_then(|mut i| i.take());
|
||||
let Some(mut inbox) = inbox else {
|
||||
// No OS integration: stay pending rather than ending the subscription.
|
||||
std::future::pending::<()>().await;
|
||||
return;
|
||||
};
|
||||
while let Some(command) = inbox.recv().await {
|
||||
if output.send(command).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use souvlaki::SeekDirection;
|
||||
|
||||
#[test]
|
||||
fn os_events_map_to_player_commands() {
|
||||
assert_eq!(Command::from_event(MediaControlEvent::Toggle), Some(Command::Toggle));
|
||||
assert_eq!(Command::from_event(MediaControlEvent::Stop), Some(Command::Pause));
|
||||
assert_eq!(
|
||||
Command::from_event(MediaControlEvent::SetPosition(MediaPosition(Duration::from_secs(42)))),
|
||||
Some(Command::SeekTo(Duration::from_secs(42)))
|
||||
);
|
||||
assert_eq!(
|
||||
Command::from_event(MediaControlEvent::Seek(SeekDirection::Backward)),
|
||||
Some(Command::SeekBy { forward: false, by: SEEK_STEP })
|
||||
);
|
||||
assert_eq!(Command::from_event(MediaControlEvent::Raise), None);
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
use std::io::Cursor;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{self, RecvTimeoutError};
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use iced::Subscription;
|
||||
use iced::futures::{SinkExt, Stream};
|
||||
@@ -24,6 +24,8 @@ pub enum Command {
|
||||
Seek(Duration),
|
||||
Volume(f32),
|
||||
Stop,
|
||||
/// The output device failed or changed; sent by the audio stream's error callback.
|
||||
Reopen,
|
||||
}
|
||||
|
||||
/// A cheap handle the UI keeps to send commands.
|
||||
@@ -51,8 +53,10 @@ pub enum Event {
|
||||
Ended { generation: u64 },
|
||||
/// The bytes didn't decode (corrupt download, unsupported codec).
|
||||
DecodeFailed { generation: u64, reason: String },
|
||||
/// No output device, or it went away.
|
||||
/// No output device, or it went away. Musyx keeps trying to reopen one.
|
||||
NoOutput(String),
|
||||
/// Sound is going to a device again after [`Event::NoOutput`].
|
||||
OutputReady,
|
||||
}
|
||||
|
||||
pub fn subscription() -> Subscription<Event> {
|
||||
@@ -63,9 +67,10 @@ fn events() -> impl Stream<Item = Event> {
|
||||
iced::stream::channel(64, async |mut output| {
|
||||
let (commands, inbox) = mpsc::channel();
|
||||
let (events, mut outbox) = tokio::sync::mpsc::unbounded_channel();
|
||||
let own = commands.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("musyx-audio".into())
|
||||
.spawn(move || run(inbox, events))
|
||||
.spawn(move || run(inbox, own, events))
|
||||
.expect("spawn audio thread");
|
||||
|
||||
let _ = output.send(Event::Ready(Handle(commands))).await;
|
||||
@@ -83,7 +88,7 @@ fn events() -> impl Stream<Item = Event> {
|
||||
/// 44.1 kHz), which Bluetooth headphones that cap at 1024 frames reject, and its
|
||||
/// fallback then filters out every macOS device. So pick the buffer here,
|
||||
/// clamped to what the device says it supports.
|
||||
fn open_output() -> Result<MixerDeviceSink, String> {
|
||||
fn open_output(on_error: impl FnMut(rodio::cpal::Error) + Send + Clone + 'static) -> Result<MixerDeviceSink, String> {
|
||||
use rodio::cpal::traits::{DeviceTrait, HostTrait};
|
||||
use rodio::cpal::{BufferSize, SupportedBufferSize};
|
||||
|
||||
@@ -101,6 +106,7 @@ fn open_output() -> Result<MixerDeviceSink, String> {
|
||||
.with_device(device)
|
||||
.with_supported_config(&config)
|
||||
.with_buffer_size(buffer)
|
||||
.with_error_callback(on_error)
|
||||
.open_stream()
|
||||
.or_else(|first| DeviceSinkBuilder::open_default_sink().map_err(|_| first.to_string()))
|
||||
}
|
||||
@@ -110,97 +116,211 @@ fn buffer_frames(sample_rate: u32, min: u32, max: u32) -> u32 {
|
||||
(sample_rate / 20).next_power_of_two().clamp(min, max.max(min))
|
||||
}
|
||||
|
||||
fn run(inbox: mpsc::Receiver<Command>, events: tokio::sync::mpsc::UnboundedSender<Event>) {
|
||||
/// An open device and the player feeding it. The sink must outlive the player:
|
||||
/// dropping it silences everything.
|
||||
struct Output {
|
||||
_sink: MixerDeviceSink,
|
||||
player: Player,
|
||||
}
|
||||
|
||||
/// The track loaded now, kept so it can be reloaded on a new device.
|
||||
struct Current {
|
||||
generation: u64,
|
||||
bytes: Arc<[u8]>,
|
||||
hint: String,
|
||||
}
|
||||
|
||||
/// Wait after a device change before reopening; macOS needs a moment to settle.
|
||||
const SETTLE: Duration = Duration::from_millis(400);
|
||||
/// How often to look for a device when there is none.
|
||||
const RETRY: Duration = Duration::from_secs(3);
|
||||
|
||||
fn open(commands: &mpsc::Sender<Command>) -> Result<Output, String> {
|
||||
let tx = commands.clone();
|
||||
let on_error = move |e: rodio::cpal::Error| {
|
||||
use rodio::cpal::ErrorKind;
|
||||
// Underruns are momentary glitches; only a lost or switched device needs a new stream.
|
||||
if matches!(e.kind(), ErrorKind::DeviceChanged | ErrorKind::DeviceNotAvailable) {
|
||||
let _ = tx.send(Command::Reopen);
|
||||
} else if !matches!(e.kind(), ErrorKind::Xrun) {
|
||||
eprintln!("audio stream error: {e}");
|
||||
}
|
||||
};
|
||||
let mut sink = open_output(on_error)?;
|
||||
sink.log_on_drop(false);
|
||||
let player = Player::connect_new(sink.mixer());
|
||||
Ok(Output { _sink: sink, player })
|
||||
}
|
||||
|
||||
fn decode(current: &Current) -> Result<Decoder<Cursor<Arc<[u8]>>>, String> {
|
||||
let len = current.bytes.len() as u64;
|
||||
Decoder::builder()
|
||||
.with_data(Cursor::new(current.bytes.clone()))
|
||||
.with_byte_len(len)
|
||||
.with_hint(¤t.hint)
|
||||
.with_seekable(true)
|
||||
.with_gapless(true)
|
||||
.build()
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn run(inbox: mpsc::Receiver<Command>, commands: mpsc::Sender<Command>, events: tokio::sync::mpsc::UnboundedSender<Event>) {
|
||||
let emit = |e: Event| {
|
||||
let _ = events.send(e);
|
||||
};
|
||||
|
||||
// The device sink must outlive the player: dropping it silences everything.
|
||||
let sink = match open_output() {
|
||||
Ok(mut sink) => {
|
||||
sink.log_on_drop(false);
|
||||
sink
|
||||
}
|
||||
let mut output = match open(&commands) {
|
||||
Ok(o) => Some(o),
|
||||
Err(e) => {
|
||||
emit(Event::NoOutput(e));
|
||||
// Keep draining so senders never block or error; nothing can play.
|
||||
while inbox.recv().is_ok() {}
|
||||
return;
|
||||
None
|
||||
}
|
||||
};
|
||||
let player = Player::connect_new(sink.mixer());
|
||||
|
||||
let mut loaded: Option<u64> = None;
|
||||
let mut volume = 1.0_f32;
|
||||
let mut playing = false;
|
||||
let mut current: Option<Current> = None;
|
||||
let mut ended_sent = false;
|
||||
let mut last_reported = None;
|
||||
let mut last_attempt = Instant::now();
|
||||
|
||||
loop {
|
||||
match inbox.recv_timeout(TICK) {
|
||||
Ok(Command::Load { generation, bytes, hint, play }) => {
|
||||
player.clear();
|
||||
let len = bytes.len() as u64;
|
||||
let decoder = Decoder::builder()
|
||||
.with_data(Cursor::new(bytes))
|
||||
.with_byte_len(len)
|
||||
.with_hint(&hint)
|
||||
.with_seekable(true)
|
||||
.with_gapless(true)
|
||||
.build();
|
||||
match decoder {
|
||||
let next = Current { generation, bytes, hint };
|
||||
match decode(&next) {
|
||||
Ok(source) => {
|
||||
let duration = source.total_duration();
|
||||
player.append(source);
|
||||
if play {
|
||||
player.play();
|
||||
if let Some(o) = &output {
|
||||
o.player.clear();
|
||||
o.player.append(source);
|
||||
if play {
|
||||
o.player.play();
|
||||
}
|
||||
}
|
||||
loaded = Some(generation);
|
||||
playing = play;
|
||||
current = Some(next);
|
||||
ended_sent = false;
|
||||
last_reported = None;
|
||||
emit(Event::Loaded { generation, duration });
|
||||
}
|
||||
Err(e) => {
|
||||
loaded = None;
|
||||
emit(Event::DecodeFailed { generation, reason: e.to_string() });
|
||||
Err(reason) => {
|
||||
current = None;
|
||||
emit(Event::DecodeFailed { generation, reason });
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Command::Play) => player.play(),
|
||||
Ok(Command::Pause) => player.pause(),
|
||||
Ok(Command::Play) => {
|
||||
playing = true;
|
||||
if let Some(o) = &output {
|
||||
o.player.play();
|
||||
}
|
||||
}
|
||||
Ok(Command::Pause) => {
|
||||
playing = false;
|
||||
if let Some(o) = &output {
|
||||
o.player.pause();
|
||||
}
|
||||
}
|
||||
Ok(Command::Seek(to)) => {
|
||||
if let Some(generation) = loaded {
|
||||
if let (Some(o), Some(c)) = (&output, ¤t)
|
||||
// A failed seek leaves playback where it was; the next tick reports that.
|
||||
if player.try_seek(to).is_ok() {
|
||||
emit(Event::Position { generation, position: player.get_pos() });
|
||||
}
|
||||
&& o.player.try_seek(to).is_ok()
|
||||
{
|
||||
emit(Event::Position { generation: c.generation, position: o.player.get_pos() });
|
||||
}
|
||||
}
|
||||
Ok(Command::Volume(v)) => {
|
||||
volume = v.clamp(0.0, 1.0);
|
||||
if let Some(o) = &output {
|
||||
o.player.set_volume(volume);
|
||||
}
|
||||
}
|
||||
Ok(Command::Volume(v)) => player.set_volume(v.clamp(0.0, 1.0)),
|
||||
Ok(Command::Stop) => {
|
||||
player.clear();
|
||||
loaded = None;
|
||||
if let Some(o) = &output {
|
||||
o.player.clear();
|
||||
}
|
||||
current = None;
|
||||
playing = false;
|
||||
}
|
||||
Ok(Command::Reopen) => {
|
||||
// Several errors arrive per change; one reopen covers them all.
|
||||
while let Ok(Command::Reopen) = inbox.try_recv() {}
|
||||
if last_attempt.elapsed() >= SETTLE {
|
||||
std::thread::sleep(SETTLE);
|
||||
while let Ok(Command::Reopen) = inbox.try_recv() {}
|
||||
output = reopen(output.take(), &commands, ¤t, volume, playing, &emit);
|
||||
last_attempt = Instant::now();
|
||||
}
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
Err(RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
|
||||
let Some(generation) = loaded else { continue };
|
||||
if player.empty() {
|
||||
// No device yet: look again now and then (headphones plugged in later).
|
||||
if output.is_none() && last_attempt.elapsed() >= RETRY {
|
||||
last_attempt = Instant::now();
|
||||
output = reopen(None, &commands, ¤t, volume, playing, &emit);
|
||||
}
|
||||
|
||||
let (Some(o), Some(c)) = (&output, ¤t) else { continue };
|
||||
if o.player.empty() {
|
||||
if !ended_sent {
|
||||
ended_sent = true;
|
||||
emit(Event::Ended { generation });
|
||||
emit(Event::Ended { generation: c.generation });
|
||||
}
|
||||
} else if !player.is_paused() {
|
||||
let position = player.get_pos();
|
||||
} else if !o.player.is_paused() {
|
||||
let position = o.player.get_pos();
|
||||
// Whole-tick resolution is plenty for a progress bar.
|
||||
let bucket = position.as_millis() / TICK.as_millis();
|
||||
if last_reported != Some(bucket) {
|
||||
last_reported = Some(bucket);
|
||||
emit(Event::Position { generation, position });
|
||||
emit(Event::Position { generation: c.generation, position });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the current default device and puts the loaded track back where it was.
|
||||
fn reopen(
|
||||
old: Option<Output>,
|
||||
commands: &mpsc::Sender<Command>,
|
||||
current: &Option<Current>,
|
||||
volume: f32,
|
||||
playing: bool,
|
||||
emit: &impl Fn(Event),
|
||||
) -> Option<Output> {
|
||||
let position = old.as_ref().map(|o| o.player.get_pos());
|
||||
let had_output = old.is_some();
|
||||
drop(old);
|
||||
let output = match open(commands) {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
if had_output {
|
||||
emit(Event::NoOutput(e));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
};
|
||||
output.player.set_volume(volume);
|
||||
if let Some(c) = current
|
||||
&& let Ok(source) = decode(c)
|
||||
{
|
||||
output.player.append(source);
|
||||
if let Some(at) = position {
|
||||
let _ = output.player.try_seek(at);
|
||||
}
|
||||
if playing {
|
||||
output.player.play();
|
||||
} else {
|
||||
output.player.pause();
|
||||
}
|
||||
}
|
||||
if !had_output {
|
||||
emit(Event::OutputReady);
|
||||
}
|
||||
Some(output)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::buffer_frames;
|
||||
|
||||
@@ -366,10 +366,10 @@ impl Player {
|
||||
Event::NoOutput(reason) => {
|
||||
eprintln!("audio output: {reason}");
|
||||
self.notice = Some(
|
||||
"No sound output found. Connect speakers or headphones, then restart Musyx."
|
||||
.into(),
|
||||
"No sound output found. Connect speakers or headphones and playback picks up.".into(),
|
||||
);
|
||||
}
|
||||
Event::OutputReady => self.notice = None,
|
||||
Event::Loaded { generation, duration } if generation == self.generation => {
|
||||
if let Some(d) = duration.filter(|d| !d.is_zero()) {
|
||||
self.duration = d;
|
||||
|
||||
@@ -4,6 +4,7 @@ pub mod browse;
|
||||
pub mod collection;
|
||||
pub mod detail;
|
||||
pub mod search;
|
||||
pub mod settings;
|
||||
pub mod sign_in;
|
||||
pub mod wave;
|
||||
|
||||
@@ -72,10 +73,11 @@ pub struct Ctx<'a> {
|
||||
pub player: &'a crate::player::Player,
|
||||
pub wave: &'a wave::WaveScreen,
|
||||
pub wave_phase: f32,
|
||||
pub settings: &'a crate::store::Settings,
|
||||
}
|
||||
|
||||
pub fn view<'a>(ctx: Ctx<'a>) -> Element<'a, Message> {
|
||||
let Ctx { env, route, search, me, library, pages, discover, genre_playlists, player, wave, wave_phase } = ctx;
|
||||
let Ctx { env, route, search, me, library, pages, discover, genre_playlists, player, wave, wave_phase, settings } = ctx;
|
||||
let t = env.t;
|
||||
let content: Column<'a, Message> = match route {
|
||||
Route::Home => {
|
||||
@@ -100,7 +102,7 @@ pub fn view<'a>(ctx: Ctx<'a>) -> Element<'a, Message> {
|
||||
column![detail::view(env, route, pages.get(&route).unwrap_or(&Loadable::Loading))]
|
||||
}
|
||||
Route::Podcasts => column![browse::podcasts(env, discover, &library.albums)],
|
||||
Route::Settings => column![title(t, "Settings"), account_card(t, me)],
|
||||
Route::Settings => column![settings::view(t, settings, account_card(t, me))],
|
||||
};
|
||||
|
||||
content
|
||||
@@ -110,10 +112,6 @@ pub fn view<'a>(ctx: Ctx<'a>) -> Element<'a, Message> {
|
||||
.into()
|
||||
}
|
||||
|
||||
fn title<'a>(t: &'static Tokens, text: impl Into<String>) -> Element<'a, Message> {
|
||||
line(text.into(), theme::DISPLAY, size::DISPLAY_S, t.fg).into()
|
||||
}
|
||||
|
||||
fn account_card<'a>(t: &'static Tokens, me: &'a Account) -> Element<'a, Message> {
|
||||
let avatar = container(line(me.initial().to_string(), theme::SEMIBOLD, 22.0, iced::Color::from_rgb8(0x1C, 0x1A, 0x22)))
|
||||
.center(56)
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Settings: account, streaming quality, appearance, storage.
|
||||
|
||||
use iced::widget::{Row, button, column, container, row};
|
||||
use iced::{Alignment, Element, Fill};
|
||||
use crate::app::Message;
|
||||
use crate::store::{Appearance, Quality, Settings};
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::theme::{self, Tokens, size};
|
||||
use crate::ui::{line, para};
|
||||
|
||||
pub fn view<'a>(t: &'static Tokens, settings: &Settings, account: Element<'a, Message>) -> Element<'a, Message> {
|
||||
let quality = Row::with_children(Quality::ALL.map(|q| chip(t, q.label(), q == settings.quality, Message::SetQuality(q))))
|
||||
.spacing(6);
|
||||
let appearance =
|
||||
Row::with_children(Appearance::ALL.map(|a| chip(t, a.label(), a == settings.appearance, Message::SetAppearance(a))))
|
||||
.spacing(6);
|
||||
|
||||
column![
|
||||
line("Settings", theme::DISPLAY, size::DISPLAY_S, t.fg),
|
||||
account,
|
||||
section(t, "Streaming quality", column![quality, para(settings.quality.detail(), size::META, t.muted)].spacing(10).into()),
|
||||
section(t, "Appearance", appearance.into()),
|
||||
section(
|
||||
t,
|
||||
"Storage",
|
||||
column![
|
||||
para(
|
||||
"Covers are kept on disk so pages open instantly next time. Clearing them frees the space; they download again as you browse.",
|
||||
size::META,
|
||||
t.muted,
|
||||
),
|
||||
button(row![icon(Icon::Trash, t.fg), line("Clear cover cache", theme::MEDIUM, size::BODY, t.fg)].spacing(8).align_y(Alignment::Center))
|
||||
.padding([9, 16])
|
||||
.style(theme::ghost)
|
||||
.on_press(Message::ClearCoverCache),
|
||||
]
|
||||
.spacing(12)
|
||||
.into(),
|
||||
),
|
||||
line(format!("Musyx {} · unofficial Yandex Music client", env!("CARGO_PKG_VERSION")), theme::BODY, size::SMALL, t.muted),
|
||||
]
|
||||
.spacing(28)
|
||||
.width(Fill)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn section<'a>(t: &'static Tokens, title: &'a str, body: Element<'a, Message>) -> Element<'a, Message> {
|
||||
container(column![line(title, theme::SEMIBOLD, size::SECTION, t.fg), body].spacing(14))
|
||||
.padding(24)
|
||||
.width(Fill)
|
||||
.style(theme::card)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn chip<'a>(t: &'static Tokens, label: &'static str, on: bool, msg: Message) -> Element<'a, Message> {
|
||||
button(line(label, theme::MEDIUM, 13.5, if on { t.accent_ink } else { t.fg }))
|
||||
.padding([7, 13])
|
||||
.style(theme::chip(on))
|
||||
.on_press_maybe((!on).then_some(msg))
|
||||
.into()
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//! Preferences kept between launches, as JSON in the platform config folder
|
||||
//! (`~/Library/Application Support/Musyx/settings.json` on macOS).
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Streaming quality, as a cap on the bitrate Musyx asks for.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Quality {
|
||||
/// The best Yandex offers (usually MP3 320).
|
||||
#[default]
|
||||
Best,
|
||||
/// Up to 192 kbps.
|
||||
Balanced,
|
||||
/// Up to 128 kbps, for slow or metered connections.
|
||||
DataSaver,
|
||||
}
|
||||
|
||||
impl Quality {
|
||||
pub const ALL: [Quality; 3] = [Quality::Best, Quality::Balanced, Quality::DataSaver];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Quality::Best => "Best",
|
||||
Quality::Balanced => "Balanced",
|
||||
Quality::DataSaver => "Data saver",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn detail(self) -> &'static str {
|
||||
match self {
|
||||
Quality::Best => "Highest bitrate available, usually MP3 320 kbps.",
|
||||
Quality::Balanced => "Up to 192 kbps. About 40% less data.",
|
||||
Quality::DataSaver => "Up to 128 kbps, for slow or metered connections.",
|
||||
}
|
||||
}
|
||||
|
||||
/// The bitrate cap passed to the API; `None` means no cap.
|
||||
pub fn max_kbps(self) -> Option<u32> {
|
||||
match self {
|
||||
Quality::Best => None,
|
||||
Quality::Balanced => Some(192),
|
||||
Quality::DataSaver => Some(128),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Appearance {
|
||||
/// Follow the system's light or dark setting.
|
||||
#[default]
|
||||
System,
|
||||
Light,
|
||||
Dark,
|
||||
}
|
||||
|
||||
impl Appearance {
|
||||
pub const ALL: [Appearance; 3] = [Appearance::System, Appearance::Light, Appearance::Dark];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Appearance::System => "Match system",
|
||||
Appearance::Light => "Light",
|
||||
Appearance::Dark => "Dark",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Settings {
|
||||
pub quality: Quality,
|
||||
pub appearance: Appearance,
|
||||
pub volume: f32,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self { quality: Quality::Best, appearance: Appearance::System, volume: 0.7 }
|
||||
}
|
||||
}
|
||||
|
||||
fn path() -> Option<PathBuf> {
|
||||
directories::ProjectDirs::from("", "", "Musyx").map(|d| d.config_dir().join("settings.json"))
|
||||
}
|
||||
|
||||
/// Saved settings, or defaults when there are none or the file is unreadable.
|
||||
/// Read once at startup, on the main thread; the file is tiny.
|
||||
pub fn load() -> Settings {
|
||||
path()
|
||||
.and_then(|p| std::fs::read_to_string(p).ok())
|
||||
.and_then(|s| serde_json::from_str(&s).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Writes atomically (temp file, then rename) so a crash can't leave half a file.
|
||||
pub async fn save(settings: Settings) -> Result<(), String> {
|
||||
let path = path().ok_or("no config folder on this system")?;
|
||||
let json = serde_json::to_vec_pretty(&settings).map_err(|e| e.to_string())?;
|
||||
if let Some(dir) = path.parent() {
|
||||
tokio::fs::create_dir_all(dir).await.map_err(|e| e.to_string())?;
|
||||
}
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
tokio::fs::write(&tmp, json).await.map_err(|e| e.to_string())?;
|
||||
tokio::fs::rename(&tmp, &path).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn settings_round_trip_and_tolerate_missing_fields() {
|
||||
let s = Settings { quality: Quality::DataSaver, appearance: Appearance::Dark, volume: 0.25 };
|
||||
let json = serde_json::to_string(&s).unwrap();
|
||||
assert!(json.contains("\"data-saver\""), "{json}");
|
||||
assert_eq!(serde_json::from_str::<Settings>(&json).unwrap(), s);
|
||||
let partial: Settings = serde_json::from_str(r#"{"appearance":"light"}"#).unwrap();
|
||||
assert_eq!(partial, Settings { appearance: Appearance::Light, ..Settings::default() });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quality_caps() {
|
||||
assert_eq!(Quality::Best.max_kbps(), None);
|
||||
assert_eq!(Quality::Balanced.max_kbps(), Some(192));
|
||||
assert_eq!(Quality::DataSaver.max_kbps(), Some(128));
|
||||
}
|
||||
}
|
||||
@@ -67,7 +67,18 @@ pub fn view<'a>(
|
||||
(Panel::Lyrics, Some(_)) => match lyrics {
|
||||
Some(Loadable::Loaded(Some(l))) => lyrics_view(t, l, player.position()),
|
||||
Some(Loadable::Loaded(None)) => note(t, "Yandex Music has no lyrics for this track."),
|
||||
Some(Loadable::Failed(_)) => note(t, "Couldn't load the lyrics. Close and reopen this panel to try again."),
|
||||
Some(Loadable::Failed(_)) => column![
|
||||
note(t, "Couldn't load the lyrics. Check your connection and try again."),
|
||||
container(
|
||||
button(line("Try again", theme::SEMIBOLD, size::BODY, t.accent_ink))
|
||||
.padding([9, 16])
|
||||
.style(theme::primary)
|
||||
.on_press(Message::RetryLyrics),
|
||||
)
|
||||
.padding([0, 20]),
|
||||
]
|
||||
.spacing(12)
|
||||
.into(),
|
||||
_ => note(t, "Loading lyrics…"),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -138,10 +138,10 @@ impl YmClient {
|
||||
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> {
|
||||
/// Resolves a signed, short-lived audio URL for a track, at most `max_kbps` when set.
|
||||
pub async fn stream(&self, track_id: &str, max_kbps: Option<u32>) -> Result<Stream> {
|
||||
let variants = self.inner.track_download_info(track_id).await?;
|
||||
let variant = best_variant(&variants)
|
||||
let variant = best_variant(&variants, max_kbps)
|
||||
.ok_or_else(|| Error::Api(format!("no playable variant for track {track_id}")))?;
|
||||
let url = variant.direct_link(self.inner.transport()).await?;
|
||||
Ok(Stream {
|
||||
|
||||
+14
-10
@@ -139,21 +139,23 @@ impl Stream {
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks the variant to play: full tracks over previews, MP3 over AAC (MP3 seeks
|
||||
/// reliably), then the highest bitrate.
|
||||
/// Picks the variant to play: full tracks over previews, then the highest bitrate
|
||||
/// within `max_kbps` (or the lowest there is, when everything is above it), then
|
||||
/// MP3 over AAC (MP3 seeks reliably).
|
||||
pub(crate) fn best_variant(
|
||||
variants: &[yamuse::models::DownloadInfo],
|
||||
max_kbps: Option<u32>,
|
||||
) -> Option<&yamuse::models::DownloadInfo> {
|
||||
let cap = max_kbps.map_or(i64::MAX, i64::from);
|
||||
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),
|
||||
)
|
||||
let kbps = v.bitrate_in_kbps.unwrap_or(0);
|
||||
// Within the cap, higher is better; above it, closer to the cap is better.
|
||||
let fit = if kbps <= cap { (1, kbps) } else { (0, -kbps) };
|
||||
(!v.preview.unwrap_or(false), fit, v.codec.as_deref() == Some("mp3"))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -212,12 +214,14 @@ mod tests {
|
||||
{"codec":"flac","bitrateInKbps":900,"downloadInfoUrl":"f"}]"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(best_variant(&v).unwrap().download_info_url.as_deref(), Some("c"));
|
||||
assert_eq!(best_variant(&v, None).unwrap().download_info_url.as_deref(), Some("c"));
|
||||
assert_eq!(best_variant(&v, Some(192)).unwrap().download_info_url.as_deref(), Some("b"));
|
||||
assert_eq!(best_variant(&v, Some(64)).unwrap().download_info_url.as_deref(), Some("b"), "nothing fits: take the smallest");
|
||||
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());
|
||||
assert!(best_variant(&previews, None).unwrap().preview.unwrap());
|
||||
assert!(best_variant(&[], None).is_none());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user