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:
Yuriy Panov committed 2026-10-15 16:28:07 +06:00
1 parent e2312f2d40
commit 60156aba94
19 files changed
+1039 -94

No files matched your search

Generated
+190 -17
View File
@@ -740,6 +740,36 @@ version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
[[package]]
name = "cocoa"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f425db7937052c684daec3bd6375c8abe2d146dca4b8b143d6db777c39138f3a"
dependencies = [
"bitflags 1.3.2",
"block",
"cocoa-foundation",
"core-foundation 0.9.4",
"core-graphics 0.22.3",
"foreign-types 0.3.2",
"libc",
"objc",
]
[[package]]
name = "cocoa-foundation"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c6234cbb2e4c785b456c0644748b1ac416dd045799740356f8363dfe00c93f7"
dependencies = [
"bitflags 1.3.2",
"block",
"core-foundation 0.9.4",
"core-graphics-types 0.1.3",
"libc",
"objc",
]
[[package]]
name = "codespan-reporting"
version = "0.12.0"
@@ -808,6 +838,19 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "core-graphics"
version = "0.22.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2581bbab3b8ffc6fcbd550bf46c355135d16e9ff2a6ea032ad6b9bf1d7efe4fb"
dependencies = [
"bitflags 1.3.2",
"core-foundation 0.9.4",
"core-graphics-types 0.1.3",
"foreign-types 0.3.2",
"libc",
]
[[package]]
name = "core-graphics"
version = "0.23.2"
@@ -817,7 +860,7 @@ dependencies = [
"bitflags 1.3.2",
"core-foundation 0.9.4",
"core-graphics-types 0.1.3",
"foreign-types",
"foreign-types 0.5.0",
"libc",
]
@@ -1067,6 +1110,26 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
[[package]]
name = "dbus"
version = "0.9.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e"
dependencies = [
"libc",
"libdbus-sys",
"windows-sys 0.61.2",
]
[[package]]
name = "dbus-crossroads"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64bff0bd181fba667660276c6b7ebdc50cff37ce593e7adf9e734f89c8f444e8"
dependencies = [
"dbus",
]
[[package]]
name = "digest"
version = "0.10.7"
@@ -1428,6 +1491,15 @@ dependencies = [
"ttf-parser",
]
[[package]]
name = "foreign-types"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
dependencies = [
"foreign-types-shared 0.1.1",
]
[[package]]
name = "foreign-types"
version = "0.5.0"
@@ -1435,7 +1507,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
dependencies = [
"foreign-types-macros",
"foreign-types-shared",
"foreign-types-shared 0.3.1",
]
[[package]]
@@ -1449,6 +1521,12 @@ dependencies = [
"syn 3.0.9",
]
[[package]]
name = "foreign-types-shared"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
[[package]]
name = "foreign-types-shared"
version = "0.3.1"
@@ -2586,6 +2664,15 @@ version = "0.2.190"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
[[package]]
name = "libdbus-sys"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043"
dependencies = [
"pkg-config",
]
[[package]]
name = "libfuzzer-sys"
version = "0.4.13"
@@ -2819,7 +2906,7 @@ dependencies = [
"bitflags 2.13.2",
"block",
"core-graphics-types 0.2.0",
"foreign-types",
"foreign-types 0.5.0",
"log",
"objc",
"paste",
@@ -2915,7 +3002,9 @@ dependencies = [
"png 0.18.1",
"rand 0.9.5",
"rodio",
"serde",
"serde_json",
"souvlaki",
"tokio",
"ym-api",
]
@@ -4856,6 +4945,24 @@ dependencies = [
"x11rb",
]
[[package]]
name = "souvlaki"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5855c8f31521af07d896b852eaa9eca974ddd3211fc2ae292e58dda8eb129bc8"
dependencies = [
"base64 0.22.1",
"block",
"cocoa",
"core-graphics 0.22.3",
"dbus",
"dbus-crossroads",
"dispatch",
"objc",
"thiserror 1.0.69",
"windows 0.44.0",
]
[[package]]
name = "spirv"
version = "0.3.0+sdk-1.3.268.0"
@@ -5988,6 +6095,15 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "windows"
version = "0.44.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e745dab35a0c4c77aa3ce42d595e13d2003d6902d6b08c9ef5fc326d08da12b"
dependencies = [
"windows-targets 0.42.2",
]
[[package]]
name = "windows"
version = "0.58.0"
@@ -5995,7 +6111,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6"
dependencies = [
"windows-core 0.58.0",
"windows-targets",
"windows-targets 0.52.6",
]
[[package]]
@@ -6029,7 +6145,7 @@ dependencies = [
"windows-interface 0.58.0",
"windows-result 0.2.0",
"windows-strings 0.1.0",
"windows-targets",
"windows-targets 0.52.6",
]
[[package]]
@@ -6135,7 +6251,7 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e"
dependencies = [
"windows-targets",
"windows-targets 0.52.6",
]
[[package]]
@@ -6154,7 +6270,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10"
dependencies = [
"windows-result 0.2.0",
"windows-targets",
"windows-targets 0.52.6",
]
[[package]]
@@ -6172,7 +6288,7 @@ version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets",
"windows-targets 0.52.6",
]
[[package]]
@@ -6181,7 +6297,7 @@ version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets",
"windows-targets 0.52.6",
]
[[package]]
@@ -6193,20 +6309,35 @@ dependencies = [
"windows-link",
]
[[package]]
name = "windows-targets"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"
dependencies = [
"windows_aarch64_gnullvm 0.42.2",
"windows_aarch64_msvc 0.42.2",
"windows_i686_gnu 0.42.2",
"windows_i686_msvc 0.42.2",
"windows_x86_64_gnu 0.42.2",
"windows_x86_64_gnullvm 0.42.2",
"windows_x86_64_msvc 0.42.2",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
]
[[package]]
@@ -6218,18 +6349,36 @@ dependencies = [
"windows-link",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
@@ -6242,24 +6391,48 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
@@ -6282,7 +6455,7 @@ dependencies = [
"cfg_aliases",
"concurrent-queue",
"core-foundation 0.9.4",
"core-graphics",
"core-graphics 0.23.2",
"cursor-icon",
"dpi",
"js-sys",
+4
View File
@@ -10,3 +10,7 @@ publish = false
[workspace.lints.clippy]
all = { level = "warn", priority = -1 }
[profile.release]
lto = "thin"
strip = true
+17
View File
@@ -29,6 +29,23 @@ Sign-in uses the public OAuth client id of the official Android app (through
third-party apps. On macOS an unsigned dev build may ask for keychain access again after
each rebuild, because the keychain ties access to the binary's signature.
## Install on macOS
```sh
tool/bundle-macos.sh --install
```
This builds a release `Musyx.app` (ad-hoc signed) into `target/release/bundle/`. With
`--install`, it also copies the app to `/Applications`. The icon comes from
`crates/musyx/assets/icon/musyx.png`, which `tool/make_icon.py` draws. Each new build is a new
code identity to the keychain, so macOS asks once to allow access to the saved sign-in.
## Settings
Settings (streaming quality, appearance, volume) are kept in
`~/Library/Application Support/Musyx/settings.json`. Covers are cached under
`~/Library/Caches/Musyx/covers` and can be cleared from Settings.
## Check
```sh
+2
View File
@@ -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
View File
@@ -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 })
}
+13
View File
@@ -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 {
+3
View File
@@ -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();
+159
View File
@@ -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);
}
}
+169 -49
View File
@@ -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(&current.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, &current)
// 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, &current, 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, &current, volume, playing, &emit);
}
let (Some(o), Some(c)) = (&output, &current) 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;
+2 -2
View File
@@ -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
View File
@@ -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)
+61
View File
@@ -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()
}
+131
View File
@@ -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));
}
}
+12 -1
View File
@@ -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…"),
},
};
+3 -3
View File
@@ -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
View File
@@ -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());
}
}
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env bash
# Builds Musyx.app (release, ad-hoc signed) into target/release/bundle/.
# tool/bundle-macos.sh # build the bundle
# tool/bundle-macos.sh --install # and copy it to /Applications
set -euo pipefail
root="$(cd "$(dirname "$0")/.." && pwd)"
cd "$root"
version="$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)"
bundle="target/release/bundle/Musyx.app"
cargo build --release -p musyx
rm -rf "$bundle"
mkdir -p "$bundle/Contents/MacOS" "$bundle/Contents/Resources"
cp target/release/musyx "$bundle/Contents/MacOS/Musyx"
# Icon: every size macOS asks for, from the 1024px master.
iconset="$(mktemp -d)/Musyx.iconset"
mkdir -p "$iconset"
master="crates/musyx/assets/icon/musyx.png"
for size in 16 32 128 256 512; do
sips -z "$size" "$size" "$master" --out "$iconset/icon_${size}x${size}.png" >/dev/null
double=$((size * 2))
sips -z "$double" "$double" "$master" --out "$iconset/icon_${size}x${size}@2x.png" >/dev/null
done
iconutil -c icns "$iconset" -o "$bundle/Contents/Resources/Musyx.icns"
cat > "$bundle/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key><string>Musyx</string>
<key>CFBundleDisplayName</key><string>Musyx</string>
<key>CFBundleIdentifier</key><string>dev.musyx.desktop</string>
<key>CFBundleExecutable</key><string>Musyx</string>
<key>CFBundleIconFile</key><string>Musyx</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleShortVersionString</key><string>${version}</string>
<key>CFBundleVersion</key><string>${version}</string>
<key>LSMinimumSystemVersion</key><string>11.0</string>
<key>LSApplicationCategoryType</key><string>public.app-category.music</string>
<key>NSHighResolutionCapable</key><true/>
<key>NSHumanReadableCopyright</key><string>Unofficial Yandex Music client. Not affiliated with Yandex.</string>
</dict>
</plist>
PLIST
# Ad-hoc signature: enough to run locally. Each new build is a new identity to the
# keychain, so macOS may ask once to allow access to the saved sign-in.
codesign --force --deep --sign - "$bundle"
echo "Built $bundle ($version)"
if [[ "${1:-}" == "--install" ]]; then
rm -rf "/Applications/Musyx.app"
cp -R "$bundle" /Applications/
echo "Installed /Applications/Musyx.app"
fi
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""Draws the Musyx app icon (1024x1024 PNG) with no dependencies.
Aubergine squircle with amber wave lines, matching the My Wave hero.
Usage: python3 tool/make_icon.py crates/musyx/assets/icon/musyx.png
"""
import math
import struct
import sys
import zlib
SIZE = 1024
# macOS icon grid: the body is 824px, centred, with a ~185px corner radius.
BODY, RADIUS = 824, 185
OFF = (SIZE - BODY) / 2
TOP, BOTTOM = (0x35, 0x30, 0x42), (0x1C, 0x1A, 0x22)
AMBER = (0xF0, 0xB2, 0x3E)
LINES = 11
def rounded_alpha(x, y):
"""Coverage of the rounded square at pixel centre (x, y), anti-aliased."""
px, py = x + 0.5 - OFF, y + 0.5 - OFF
cx = min(max(px, RADIUS), BODY - RADIUS)
cy = min(max(py, RADIUS), BODY - RADIUS)
d = math.hypot(px - cx, py - cy) - RADIUS
if px < 0 or py < 0 or px > BODY or py > BODY:
d = max(d, 1.0)
return min(max(0.5 - d, 0.0), 1.0)
def wave(k, x):
"""Height of line k at x, and its slope, in pixels."""
u = (x - OFF) / BODY
base = OFF + BODY * (0.34 + k * 0.034)
amp = BODY * (0.045 + k * 0.006)
f = 1.5 + k * 0.08
ph = k * 0.55 + 1.1
a = u * math.pi * f + ph
b = u * math.pi * 4.2 - ph * 0.7
y = base + math.sin(a) * amp + math.sin(b) * amp * 0.35
dy = (math.cos(a) * amp * math.pi * f + math.cos(b) * amp * 0.35 * math.pi * 4.2) / BODY
return y, dy
def main(out):
rows = []
curves = [[wave(k, x + 0.5) for x in range(SIZE)] for k in range(LINES)]
for y in range(SIZE):
row = bytearray([0]) # filter: none
t = y / SIZE
bg = tuple(round(TOP[i] + (BOTTOM[i] - TOP[i]) * t) for i in range(3))
for x in range(SIZE):
cover = rounded_alpha(x, y)
if cover == 0.0:
row += b"\x00\x00\x00\x00"
continue
r, g, b = bg
for k in range(LINES):
cy, slope = curves[k][x]
dist = abs(y + 0.5 - cy) / math.sqrt(1 + slope * slope)
width = 4.0 + k * 0.9
a = min(max(width / 2 - dist + 0.5, 0.0), 1.0)
if a:
a *= 0.18 + 0.82 * (k / (LINES - 1))
r = r + (AMBER[0] - r) * a
g = g + (AMBER[1] - g) * a
b = b + (AMBER[2] - b) * a
row += bytes((round(r), round(g), round(b), round(cover * 255)))
rows.append(bytes(row))
def chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
png = b"\x89PNG\r\n\x1a\n"
png += chunk(b"IHDR", struct.pack(">IIBBBBB", SIZE, SIZE, 8, 6, 0, 0, 0))
png += chunk(b"IDAT", zlib.compress(b"".join(rows), 9))
png += chunk(b"IEND", b"")
with open(out, "wb") as f:
f.write(png)
if __name__ == "__main__":
main(sys.argv[1] if len(sys.argv) > 1 else "musyx.png")