feat: playback of liked tracks with audio engine, queue and player bar
- ym-api: Track/Stream models, liked tracks, signed download URLs (full MP3 over AAC over previews, highest bitrate) and in-memory fetch - Audio thread on rodio, driven by commands and reporting through an iced subscription; generation ids drop stale events - Opens the default output with a buffer clamped to the device's range: rodio's 2048-frame default fails on Bluetooth headphones that cap at 1024 - Queue with shuffle, repeat off/all/one, back/advance and jump; player state machine with prefetch of the next track, replay from memory, and skipping unplayable tracks (stops after three in a row) - Working player bar (seek, volume, mute, quality badge), queue drawer, Collection screen with a lazily built liked-tracks list - audio_probe example lists and test-opens output devices
This commit is contained in:
1 parent
43e8f86a5d
commit
b73af1f870
20 files changed
+2135
-196
No files matched your search
Generated
+304
@@ -68,6 +68,12 @@ dependencies = [
|
|||||||
"memchr",
|
"memchr",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "aliasable"
|
||||||
|
version = "0.1.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "250f629c0161ad8107cf89319e990051fae62832fd343083bea452d93e2205fd"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "aligned"
|
name = "aligned"
|
||||||
version = "0.4.3"
|
version = "0.4.3"
|
||||||
@@ -86,6 +92,28 @@ dependencies = [
|
|||||||
"equator",
|
"equator",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "alsa"
|
||||||
|
version = "0.11.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "812947049edcd670a82cd5c73c3661d2e58468577ba8489de58e1a73c04cbd5d"
|
||||||
|
dependencies = [
|
||||||
|
"alsa-sys",
|
||||||
|
"bitflags 2.13.2",
|
||||||
|
"cfg-if",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "alsa-sys"
|
||||||
|
version = "0.4.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ad7569085a265dd3f607ebecce7458eaab2132a84393534c95b18dcbc3f31e04"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"pkg-config",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "android-activity"
|
name = "android-activity"
|
||||||
version = "0.6.1"
|
version = "0.6.1"
|
||||||
@@ -830,6 +858,20 @@ dependencies = [
|
|||||||
"libm",
|
"libm",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "coreaudio-rs"
|
||||||
|
version = "0.14.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7d5d7dca3ebcf65a035582c9ad4385371a9d9ee6537474d2a278f4e1e475bb58"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.2",
|
||||||
|
"libc",
|
||||||
|
"objc2-audio-toolbox",
|
||||||
|
"objc2-core-audio",
|
||||||
|
"objc2-core-audio-types",
|
||||||
|
"objc2-core-foundation",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cosmic-text"
|
name = "cosmic-text"
|
||||||
version = "0.15.0"
|
version = "0.15.0"
|
||||||
@@ -854,6 +896,36 @@ dependencies = [
|
|||||||
"unicode-segmentation",
|
"unicode-segmentation",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cpal"
|
||||||
|
version = "0.18.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6f02e8d0327b42d3e2e4ab2119af397344eb9fc54a34bf0ddeaa1277af8681f1"
|
||||||
|
dependencies = [
|
||||||
|
"alsa",
|
||||||
|
"block2 0.6.2",
|
||||||
|
"coreaudio-rs",
|
||||||
|
"dasp_sample",
|
||||||
|
"jni",
|
||||||
|
"js-sys",
|
||||||
|
"libc",
|
||||||
|
"mach2",
|
||||||
|
"ndk",
|
||||||
|
"ndk-context",
|
||||||
|
"num-derive",
|
||||||
|
"num-traits",
|
||||||
|
"objc2 0.6.5",
|
||||||
|
"objc2-audio-toolbox",
|
||||||
|
"objc2-avf-audio",
|
||||||
|
"objc2-core-audio",
|
||||||
|
"objc2-core-audio-types",
|
||||||
|
"objc2-core-foundation",
|
||||||
|
"objc2-foundation 0.3.2",
|
||||||
|
"web-sys",
|
||||||
|
"windows 0.62.2",
|
||||||
|
"windows-core 0.62.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cpubits"
|
name = "cpubits"
|
||||||
version = "0.1.1"
|
version = "0.1.1"
|
||||||
@@ -983,6 +1055,12 @@ version = "1.2.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
|
checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "dasp_sample"
|
||||||
|
version = "0.11.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "data-url"
|
name = "data-url"
|
||||||
version = "0.3.2"
|
version = "0.3.2"
|
||||||
@@ -1712,6 +1790,12 @@ version = "0.17.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "heck"
|
||||||
|
version = "0.4.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hermit-abi"
|
name = "hermit-abi"
|
||||||
version = "0.5.3"
|
version = "0.5.3"
|
||||||
@@ -2034,6 +2118,7 @@ dependencies = [
|
|||||||
"iced_renderer",
|
"iced_renderer",
|
||||||
"log",
|
"log",
|
||||||
"num-traits",
|
"num-traits",
|
||||||
|
"ouroboros",
|
||||||
"qrcode",
|
"qrcode",
|
||||||
"rustc-hash 2.1.3",
|
"rustc-hash 2.1.3",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
@@ -2436,6 +2521,12 @@ dependencies = [
|
|||||||
"smallvec",
|
"smallvec",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lazy_static"
|
||||||
|
version = "1.5.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lebe"
|
name = "lebe"
|
||||||
version = "0.5.3"
|
version = "0.5.3"
|
||||||
@@ -2613,6 +2704,12 @@ dependencies = [
|
|||||||
"num-traits",
|
"num-traits",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mach2"
|
||||||
|
version = "0.6.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "malloc_buf"
|
name = "malloc_buf"
|
||||||
version = "0.0.6"
|
version = "0.0.6"
|
||||||
@@ -2767,6 +2864,8 @@ dependencies = [
|
|||||||
"keyring",
|
"keyring",
|
||||||
"open",
|
"open",
|
||||||
"png 0.18.1",
|
"png 0.18.1",
|
||||||
|
"rand 0.9.5",
|
||||||
|
"rodio",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tokio",
|
"tokio",
|
||||||
"ym-api",
|
"ym-api",
|
||||||
@@ -3042,6 +3141,32 @@ dependencies = [
|
|||||||
"objc2-quartz-core 0.3.2",
|
"objc2-quartz-core 0.3.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "objc2-audio-toolbox"
|
||||||
|
version = "0.3.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.2",
|
||||||
|
"libc",
|
||||||
|
"objc2 0.6.5",
|
||||||
|
"objc2-core-audio",
|
||||||
|
"objc2-core-audio-types",
|
||||||
|
"objc2-core-foundation",
|
||||||
|
"objc2-foundation 0.3.2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "objc2-avf-audio"
|
||||||
|
version = "0.3.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.2",
|
||||||
|
"objc2 0.6.5",
|
||||||
|
"objc2-foundation 0.3.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "objc2-cloud-kit"
|
name = "objc2-cloud-kit"
|
||||||
version = "0.2.2"
|
version = "0.2.2"
|
||||||
@@ -3077,6 +3202,29 @@ dependencies = [
|
|||||||
"objc2-foundation 0.2.2",
|
"objc2-foundation 0.2.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "objc2-core-audio"
|
||||||
|
version = "0.3.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2"
|
||||||
|
dependencies = [
|
||||||
|
"dispatch2",
|
||||||
|
"objc2 0.6.5",
|
||||||
|
"objc2-core-audio-types",
|
||||||
|
"objc2-core-foundation",
|
||||||
|
"objc2-foundation 0.3.2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "objc2-core-audio-types"
|
||||||
|
version = "0.3.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.2",
|
||||||
|
"objc2 0.6.5",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "objc2-core-data"
|
name = "objc2-core-data"
|
||||||
version = "0.2.2"
|
version = "0.2.2"
|
||||||
@@ -3107,7 +3255,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
|
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bitflags 2.13.2",
|
"bitflags 2.13.2",
|
||||||
|
"block2 0.6.2",
|
||||||
"dispatch2",
|
"dispatch2",
|
||||||
|
"libc",
|
||||||
"objc2 0.6.5",
|
"objc2 0.6.5",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -3375,6 +3525,30 @@ dependencies = [
|
|||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ouroboros"
|
||||||
|
version = "0.18.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1e0f050db9c44b97a94723127e6be766ac5c340c48f2c4bb3ffa11713744be59"
|
||||||
|
dependencies = [
|
||||||
|
"aliasable",
|
||||||
|
"ouroboros_macro",
|
||||||
|
"static_assertions",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ouroboros_macro"
|
||||||
|
version = "0.18.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3c7028bdd3d43083f6d8d4d5187680d0d3560d54df4cc9d752005268b41e64d0"
|
||||||
|
dependencies = [
|
||||||
|
"heck",
|
||||||
|
"proc-macro2",
|
||||||
|
"proc-macro2-diagnostics",
|
||||||
|
"quote",
|
||||||
|
"syn 2.0.119",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "owned_ttf_parser"
|
name = "owned_ttf_parser"
|
||||||
version = "0.25.1"
|
version = "0.25.1"
|
||||||
@@ -3589,6 +3763,19 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "proc-macro2-diagnostics"
|
||||||
|
version = "0.10.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 2.0.119",
|
||||||
|
"version_check",
|
||||||
|
"yansi",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "profiling"
|
name = "profiling"
|
||||||
version = "1.0.18"
|
version = "1.0.18"
|
||||||
@@ -4070,6 +4257,19 @@ dependencies = [
|
|||||||
"windows-sys 0.52.0",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rodio"
|
||||||
|
version = "0.23.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "36e3ee0a5ca418bac59a15d5506e498ab138359edbb67257a6b8a3b93d411f39"
|
||||||
|
dependencies = [
|
||||||
|
"cpal",
|
||||||
|
"dasp_sample",
|
||||||
|
"num-rational",
|
||||||
|
"symphonia",
|
||||||
|
"thiserror 2.0.21",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "roxmltree"
|
name = "roxmltree"
|
||||||
version = "0.20.0"
|
version = "0.20.0"
|
||||||
@@ -4654,6 +4854,104 @@ dependencies = [
|
|||||||
"zeno",
|
"zeno",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5773a4c030a19d9bfaa090f49746ff35c75dfddfa700df7a5939d5e076a57039"
|
||||||
|
dependencies = [
|
||||||
|
"lazy_static",
|
||||||
|
"symphonia-bundle-flac",
|
||||||
|
"symphonia-bundle-mp3",
|
||||||
|
"symphonia-codec-aac",
|
||||||
|
"symphonia-core",
|
||||||
|
"symphonia-format-isomp4",
|
||||||
|
"symphonia-metadata",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia-bundle-flac"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c91565e180aea25d9b80a910c546802526ffd0072d0b8974e3ebe59b686c9976"
|
||||||
|
dependencies = [
|
||||||
|
"log",
|
||||||
|
"symphonia-core",
|
||||||
|
"symphonia-metadata",
|
||||||
|
"symphonia-utils-xiph",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia-bundle-mp3"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4872dd6bb56bf5eac799e3e957aa1981086c3e613b27e0ac23b176054f7c57ed"
|
||||||
|
dependencies = [
|
||||||
|
"lazy_static",
|
||||||
|
"log",
|
||||||
|
"symphonia-core",
|
||||||
|
"symphonia-metadata",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia-codec-aac"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4c263845aa86881416849c1729a54c7f55164f8b96111dba59de46849e73a790"
|
||||||
|
dependencies = [
|
||||||
|
"lazy_static",
|
||||||
|
"log",
|
||||||
|
"symphonia-core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia-core"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ea00cc4f79b7f6bb7ff87eddc065a1066f3a43fe1875979056672c9ef948c2af"
|
||||||
|
dependencies = [
|
||||||
|
"arrayvec",
|
||||||
|
"bitflags 1.3.2",
|
||||||
|
"bytemuck",
|
||||||
|
"lazy_static",
|
||||||
|
"log",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia-format-isomp4"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "243739585d11f81daf8dac8d9f3d18cc7898f6c09a259675fc364b382c30e0a5"
|
||||||
|
dependencies = [
|
||||||
|
"encoding_rs",
|
||||||
|
"log",
|
||||||
|
"symphonia-core",
|
||||||
|
"symphonia-metadata",
|
||||||
|
"symphonia-utils-xiph",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia-metadata"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "36306ff42b9ffe6e5afc99d49e121e0bd62fe79b9db7b9681d48e29fa19e6b16"
|
||||||
|
dependencies = [
|
||||||
|
"encoding_rs",
|
||||||
|
"lazy_static",
|
||||||
|
"log",
|
||||||
|
"symphonia-core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symphonia-utils-xiph"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ee27c85ab799a338446b68eec77abf42e1a6f1bb490656e121c6e27bfbab9f16"
|
||||||
|
dependencies = [
|
||||||
|
"symphonia-core",
|
||||||
|
"symphonia-metadata",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "syn"
|
name = "syn"
|
||||||
version = "2.0.119"
|
version = "2.0.119"
|
||||||
@@ -6074,6 +6372,12 @@ dependencies = [
|
|||||||
"tokio",
|
"tokio",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "yansi"
|
||||||
|
version = "1.0.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "yazi"
|
name = "yazi"
|
||||||
version = "0.2.1"
|
version = "0.2.1"
|
||||||
|
|||||||
@@ -48,6 +48,11 @@ MUSYX_SNAPSHOT=design/shots/home.png MUSYX_SNAPSHOT_ROUTE=home MUSYX_SNAPSHOT_TH
|
|||||||
route except signin renders with a sample signed-in account, so no network or keychain is needed.
|
route except signin renders with a sample signed-in account, so no network or keychain is needed.
|
||||||
`MUSYX_SNAPSHOT_DRAWER` takes queue or lyrics. `MUSYX_SNAPSHOT_THEME` takes light or dark.
|
`MUSYX_SNAPSHOT_DRAWER` takes queue or lyrics. `MUSYX_SNAPSHOT_THEME` takes light or dark.
|
||||||
|
|
||||||
|
### Audio
|
||||||
|
|
||||||
|
`cargo run -p musyx --example audio_probe` lists the output devices and checks that each one
|
||||||
|
opens. Use it when the player bar says no sound output was found.
|
||||||
|
|
||||||
## Licences
|
## Licences
|
||||||
|
|
||||||
Musyx is MIT. Onest and Unbounded are OFL (`crates/musyx/assets/fonts`), and Lucide icons
|
Musyx is MIT. Onest and Unbounded are OFL (`crates/musyx/assets/fonts`), and Lucide icons
|
||||||
|
|||||||
@@ -8,8 +8,10 @@ publish.workspace = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
ym-api = { path = "../ym-api" }
|
ym-api = { path = "../ym-api" }
|
||||||
iced = { version = "0.14.0", features = ["svg", "image", "tokio", "advanced", "qr_code"] }
|
iced = { version = "0.14.0", features = ["svg", "image", "tokio", "advanced", "qr_code", "lazy"] }
|
||||||
keyring = "4.2.0"
|
keyring = "4.2.0"
|
||||||
|
rodio = { version = "0.23.0", default-features = false, features = ["playback", "mp3", "mp4", "flac"] }
|
||||||
|
rand = "0.9"
|
||||||
open = "5.4.4"
|
open = "5.4.4"
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
tokio = { version = "1", features = ["time", "rt"] }
|
tokio = { version = "1", features = ["time", "rt"] }
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
//! Lists output devices and tries to open each one: `cargo run -p musyx --example audio_probe`.
|
||||||
|
use rodio::DeviceSinkBuilder;
|
||||||
|
use rodio::cpal::traits::{DeviceTrait, HostTrait};
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let host = rodio::cpal::default_host();
|
||||||
|
let default = host.default_output_device();
|
||||||
|
println!("default: {:?}", default.as_ref().and_then(|d| d.description().ok()).map(|d| d.name().to_string()));
|
||||||
|
for device in host.output_devices().expect("devices") {
|
||||||
|
let name = device.description().map(|d| d.name().to_string()).unwrap_or_default();
|
||||||
|
let config = device.default_output_config();
|
||||||
|
println!("\n{name}\n default config: {config:?}");
|
||||||
|
match DeviceSinkBuilder::from_device(device.clone()).map(|b| b.open_stream()) {
|
||||||
|
Ok(Ok(_)) => println!(" open (rodio defaults): ok"),
|
||||||
|
Ok(Err(e)) => println!(" open (rodio defaults): {e:?}"),
|
||||||
|
Err(e) => println!(" builder: {e:?}"),
|
||||||
|
}
|
||||||
|
if let Ok(config) = config {
|
||||||
|
let r = DeviceSinkBuilder::default().with_device(device.clone()).with_supported_config(&config).open_stream();
|
||||||
|
println!(" open (device default buffer): {:?}", r.map(|_| "ok"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+101
-13
@@ -6,12 +6,14 @@ use iced::{Element, Fill, Subscription, Task, Theme};
|
|||||||
use ym_api::auth::Credentials;
|
use ym_api::auth::Credentials;
|
||||||
use ym_api::{Account, Error, YmClient};
|
use ym_api::{Account, Error, YmClient};
|
||||||
|
|
||||||
|
use crate::player::{self, Audio, Effect, Player};
|
||||||
use crate::route::{Navigator, Route};
|
use crate::route::{Navigator, Route};
|
||||||
|
use crate::screens::collection::Liked;
|
||||||
use crate::screens::{self, sign_in};
|
use crate::screens::{self, sign_in};
|
||||||
use crate::session::{self, Restored};
|
use crate::session::{self, Restored};
|
||||||
use crate::ui::theme::{self, shell};
|
use crate::ui::theme::{self, shell};
|
||||||
use crate::widgets::drawer::{self, Panel};
|
use crate::widgets::drawer::{self, Panel};
|
||||||
use crate::widgets::player_bar::{self, PlayerUi};
|
use crate::widgets::player_bar;
|
||||||
use crate::widgets::{sidebar, topbar};
|
use crate::widgets::{sidebar, topbar};
|
||||||
|
|
||||||
/// Where sign-in stands. Everything but `SignedIn` takes the whole window.
|
/// Where sign-in stands. Everything but `SignedIn` takes the whole window.
|
||||||
@@ -33,7 +35,8 @@ pub struct App {
|
|||||||
nav: Navigator,
|
nav: Navigator,
|
||||||
search: String,
|
search: String,
|
||||||
drawer: Option<Panel>,
|
drawer: Option<Panel>,
|
||||||
player: PlayerUi,
|
player: Player,
|
||||||
|
liked: Liked,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -52,7 +55,10 @@ pub enum Message {
|
|||||||
SearchSubmitted,
|
SearchSubmitted,
|
||||||
ToggleDrawer(Panel),
|
ToggleDrawer(Panel),
|
||||||
CloseDrawer,
|
CloseDrawer,
|
||||||
Player(player_bar::Action),
|
Player(player::Msg),
|
||||||
|
LoadLiked,
|
||||||
|
LikedLoaded(Result<Vec<ym_api::Track>, Error>),
|
||||||
|
PlayLiked { start: usize, shuffle: bool },
|
||||||
}
|
}
|
||||||
|
|
||||||
impl App {
|
impl App {
|
||||||
@@ -64,7 +70,8 @@ impl App {
|
|||||||
nav: Navigator::new(Route::Home),
|
nav: Navigator::new(Route::Home),
|
||||||
search: String::new(),
|
search: String::new(),
|
||||||
drawer: None,
|
drawer: None,
|
||||||
player: PlayerUi::default(),
|
player: Player::default(),
|
||||||
|
liked: Liked::NotLoaded,
|
||||||
};
|
};
|
||||||
let appearance = iced::system::theme().map(Message::ThemeChanged);
|
let appearance = iced::system::theme().map(Message::ThemeChanged);
|
||||||
|
|
||||||
@@ -72,6 +79,7 @@ impl App {
|
|||||||
if let Some(config) = crate::snapshot::Config::from_env() {
|
if let Some(config) = crate::snapshot::Config::from_env() {
|
||||||
let mut app = app;
|
let mut app = app;
|
||||||
app.session = config.session();
|
app.session = config.session();
|
||||||
|
app.liked = Liked::loaded(config.sample_liked(), &Liked::NotLoaded);
|
||||||
if let Some(route) = config.route {
|
if let Some(route) = config.route {
|
||||||
app.nav = Navigator::new(route);
|
app.nav = Navigator::new(route);
|
||||||
}
|
}
|
||||||
@@ -101,11 +109,14 @@ impl App {
|
|||||||
|
|
||||||
pub fn subscription(&self) -> Subscription<Message> {
|
pub fn subscription(&self) -> Subscription<Message> {
|
||||||
let appearance = iced::system::theme_changes().map(Message::ThemeChanged);
|
let appearance = iced::system::theme_changes().map(Message::ThemeChanged);
|
||||||
|
let audio = player::engine::subscription().map(|e| Message::Player(player::Msg::Engine(e)));
|
||||||
match &self.session {
|
match &self.session {
|
||||||
Session::SignedOut(sign_in) => {
|
Session::SignedOut(sign_in) => Subscription::batch([
|
||||||
Subscription::batch([appearance, sign_in.subscription().map(Message::SignIn)])
|
appearance,
|
||||||
}
|
audio,
|
||||||
_ => appearance,
|
sign_in.subscription().map(Message::SignIn),
|
||||||
|
]),
|
||||||
|
_ => Subscription::batch([appearance, audio]),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,6 +135,7 @@ impl App {
|
|||||||
Restored::SignedOut => Session::SignedOut(Box::default()),
|
Restored::SignedOut => Session::SignedOut(Box::default()),
|
||||||
Restored::Unreachable => Session::Unreachable,
|
Restored::Unreachable => Session::Unreachable,
|
||||||
};
|
};
|
||||||
|
return self.update(Message::LoadLiked);
|
||||||
}
|
}
|
||||||
Message::SignIn(msg) => {
|
Message::SignIn(msg) => {
|
||||||
let Session::SignedOut(sign_in) = &mut self.session else {
|
let Session::SignedOut(sign_in) = &mut self.session else {
|
||||||
@@ -141,6 +153,7 @@ impl App {
|
|||||||
Message::Connected(Ok((client, account))) => {
|
Message::Connected(Ok((client, account))) => {
|
||||||
self.nav = Navigator::new(Route::Home);
|
self.nav = Navigator::new(Route::Home);
|
||||||
self.session = Session::SignedIn { client, account };
|
self.session = Session::SignedIn { client, account };
|
||||||
|
return self.update(Message::LoadLiked);
|
||||||
}
|
}
|
||||||
Message::Connected(Err(e)) => {
|
Message::Connected(Err(e)) => {
|
||||||
eprintln!("sign-in: {e}");
|
eprintln!("sign-in: {e}");
|
||||||
@@ -164,10 +177,14 @@ impl App {
|
|||||||
self.session = Session::SignedOut(Box::default());
|
self.session = Session::SignedOut(Box::default());
|
||||||
self.nav = Navigator::new(Route::Home);
|
self.nav = Navigator::new(Route::Home);
|
||||||
self.drawer = None;
|
self.drawer = None;
|
||||||
self.player = PlayerUi::default();
|
self.player.reset();
|
||||||
|
self.liked = Liked::NotLoaded;
|
||||||
}
|
}
|
||||||
Message::Navigate(route) => {
|
Message::Navigate(route) => {
|
||||||
self.nav.go(route);
|
self.nav.go(route);
|
||||||
|
if route == Route::Collection && matches!(self.liked, Liked::Failed(_)) {
|
||||||
|
return self.update(Message::LoadLiked);
|
||||||
|
}
|
||||||
// Settings shows the subscription, which can change outside the app.
|
// Settings shows the subscription, which can change outside the app.
|
||||||
if let (Route::Settings, Session::SignedIn { client, .. }) = (route, &self.session) {
|
if let (Route::Settings, Session::SignedIn { client, .. }) = (route, &self.session) {
|
||||||
let client = client.clone();
|
let client = client.clone();
|
||||||
@@ -192,7 +209,37 @@ impl App {
|
|||||||
self.drawer = if self.drawer == Some(panel) { None } else { Some(panel) };
|
self.drawer = if self.drawer == Some(panel) { None } else { Some(panel) };
|
||||||
}
|
}
|
||||||
Message::CloseDrawer => self.drawer = None,
|
Message::CloseDrawer => self.drawer = None,
|
||||||
Message::Player(action) => self.player.apply(action),
|
Message::Player(msg) => {
|
||||||
|
let effects = self.player.update(msg);
|
||||||
|
return self.run(effects);
|
||||||
|
}
|
||||||
|
Message::LoadLiked => {
|
||||||
|
let Session::SignedIn { client, .. } = &self.session else { return Task::none() };
|
||||||
|
if matches!(self.liked, Liked::Loading) {
|
||||||
|
return Task::none();
|
||||||
|
}
|
||||||
|
self.liked = Liked::Loading;
|
||||||
|
let client = client.clone();
|
||||||
|
return Task::future(async move { client.liked_tracks().await }).map(Message::LikedLoaded);
|
||||||
|
}
|
||||||
|
Message::LikedLoaded(Ok(tracks)) => self.liked = Liked::loaded(tracks, &self.liked),
|
||||||
|
Message::LikedLoaded(Err(Error::Unauthorized(e))) => {
|
||||||
|
eprintln!("token rejected: {e}");
|
||||||
|
return self.update(Message::SignOut);
|
||||||
|
}
|
||||||
|
Message::LikedLoaded(Err(e)) => {
|
||||||
|
eprintln!("liked tracks: {e}");
|
||||||
|
self.liked = Liked::Failed(e);
|
||||||
|
}
|
||||||
|
Message::PlayLiked { start, shuffle } => {
|
||||||
|
if let Some(tracks) = self.liked.tracks().cloned() {
|
||||||
|
return self.update(Message::Player(player::Msg::Play {
|
||||||
|
tracks,
|
||||||
|
start,
|
||||||
|
shuffle: shuffle.then_some(true),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Task::none()
|
Task::none()
|
||||||
}
|
}
|
||||||
@@ -214,7 +261,14 @@ impl App {
|
|||||||
|
|
||||||
let content = column![
|
let content = column![
|
||||||
topbar::view(t, self.nav.can_go_back(), &self.search),
|
topbar::view(t, self.nav.can_go_back(), &self.search),
|
||||||
scrollable(screens::view(t, route, &self.search, account))
|
scrollable(screens::view(screens::Ctx {
|
||||||
|
t,
|
||||||
|
route,
|
||||||
|
query: &self.search,
|
||||||
|
me: account,
|
||||||
|
liked: &self.liked,
|
||||||
|
playing: self.player.track().map(|tr| tr.id.as_str()),
|
||||||
|
}))
|
||||||
.height(Fill)
|
.height(Fill)
|
||||||
.style(theme::scroll),
|
.style(theme::scroll),
|
||||||
]
|
]
|
||||||
@@ -224,13 +278,18 @@ impl App {
|
|||||||
let mut body = row![sidebar::view(t, route, account), vline(), content].height(Fill);
|
let mut body = row![sidebar::view(t, route, account), vline(), content].height(Fill);
|
||||||
|
|
||||||
if let Some(panel) = self.drawer {
|
if let Some(panel) = self.drawer {
|
||||||
body = body.push(vline()).push(drawer::view(t, panel));
|
body = body.push(vline()).push(drawer::view(t, panel, &self.player));
|
||||||
}
|
}
|
||||||
|
|
||||||
let window = column![
|
let window = column![
|
||||||
body,
|
body,
|
||||||
hline(),
|
hline(),
|
||||||
container(player_bar::view(t, &self.player, self.drawer))
|
container(player_bar::view(
|
||||||
|
t,
|
||||||
|
&self.player,
|
||||||
|
self.player.track().is_some_and(|tr| self.liked.contains(&tr.id)),
|
||||||
|
self.drawer,
|
||||||
|
))
|
||||||
.height(shell::PLAYER)
|
.height(shell::PLAYER)
|
||||||
.style(theme::panel),
|
.style(theme::panel),
|
||||||
];
|
];
|
||||||
@@ -239,6 +298,35 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl App {
|
||||||
|
/// Runs the player's requests against the API.
|
||||||
|
fn run(&self, effects: Vec<Effect>) -> Task<Message> {
|
||||||
|
let Session::SignedIn { client, .. } = &self.session else { return Task::none() };
|
||||||
|
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 })
|
||||||
|
.map(move |result| Message::Player(player::Msg::Fetched { generation, result }))
|
||||||
|
}
|
||||||
|
Effect::Prefetch { track_id } => {
|
||||||
|
let client = client.clone();
|
||||||
|
Task::future(async move {
|
||||||
|
let result = fetch_audio(&client, &track_id).await;
|
||||||
|
(track_id, result)
|
||||||
|
})
|
||||||
|
.map(|(track_id, result)| Message::Player(player::Msg::Prefetched { track_id, result }))
|
||||||
|
}
|
||||||
|
Effect::SignedOut => Task::done(Message::SignOut),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_audio(client: &YmClient, track_id: &str) -> Result<Audio, Error> {
|
||||||
|
let stream = client.stream(track_id).await?;
|
||||||
|
let bytes = client.fetch(&stream).await?;
|
||||||
|
Ok(Audio { stream, bytes })
|
||||||
|
}
|
||||||
|
|
||||||
fn restore() -> Task<Message> {
|
fn restore() -> Task<Message> {
|
||||||
Task::future(session::restore()).map(Message::Restored)
|
Task::future(session::restore()).map(Message::Restored)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
mod app;
|
mod app;
|
||||||
|
mod player;
|
||||||
mod route;
|
mod route;
|
||||||
mod screens;
|
mod screens;
|
||||||
mod session;
|
mod session;
|
||||||
|
|||||||
@@ -0,0 +1,215 @@
|
|||||||
|
//! The audio thread. It owns the output device and a rodio `Player`, takes
|
||||||
|
//! [`Command`]s over a channel and reports [`Event`]s through an iced subscription.
|
||||||
|
//!
|
||||||
|
//! Everything here is about one loaded item at a time; the queue and fetching
|
||||||
|
//! live in the UI state. Each load carries a `generation` so stale events from a
|
||||||
|
//! previous track can be told apart.
|
||||||
|
|
||||||
|
use std::io::Cursor;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::mpsc::{self, RecvTimeoutError};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use iced::Subscription;
|
||||||
|
use iced::futures::{SinkExt, Stream};
|
||||||
|
use rodio::{Decoder, DeviceSinkBuilder, MixerDeviceSink, Player, Source};
|
||||||
|
|
||||||
|
/// How often position is reported while playing.
|
||||||
|
const TICK: Duration = Duration::from_millis(250);
|
||||||
|
|
||||||
|
pub enum Command {
|
||||||
|
Load { generation: u64, bytes: Arc<[u8]>, hint: String, play: bool },
|
||||||
|
Play,
|
||||||
|
Pause,
|
||||||
|
Seek(Duration),
|
||||||
|
Volume(f32),
|
||||||
|
Stop,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A cheap handle the UI keeps to send commands.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Handle(mpsc::Sender<Command>);
|
||||||
|
|
||||||
|
impl std::fmt::Debug for Handle {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str("engine::Handle")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Handle {
|
||||||
|
pub fn send(&self, command: Command) {
|
||||||
|
// The thread only stops with the subscription, i.e. when the app exits.
|
||||||
|
let _ = self.0.send(command);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum Event {
|
||||||
|
Ready(Handle),
|
||||||
|
Loaded { generation: u64, duration: Option<Duration> },
|
||||||
|
Position { generation: u64, position: Duration },
|
||||||
|
Ended { generation: u64 },
|
||||||
|
/// The bytes didn't decode (corrupt download, unsupported codec).
|
||||||
|
DecodeFailed { generation: u64, reason: String },
|
||||||
|
/// No output device, or it went away.
|
||||||
|
NoOutput(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn subscription() -> Subscription<Event> {
|
||||||
|
Subscription::run(events)
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
std::thread::Builder::new()
|
||||||
|
.name("musyx-audio".into())
|
||||||
|
.spawn(move || run(inbox, events))
|
||||||
|
.expect("spawn audio thread");
|
||||||
|
|
||||||
|
let _ = output.send(Event::Ready(Handle(commands))).await;
|
||||||
|
while let Some(event) = outbox.recv().await {
|
||||||
|
if output.send(event).await.is_err() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens the system's default output device.
|
||||||
|
///
|
||||||
|
/// rodio's own `open_default_sink` asks for a 50 ms buffer (2048 frames at
|
||||||
|
/// 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> {
|
||||||
|
use rodio::cpal::traits::{DeviceTrait, HostTrait};
|
||||||
|
use rodio::cpal::{BufferSize, SupportedBufferSize};
|
||||||
|
|
||||||
|
let device = rodio::cpal::default_host()
|
||||||
|
.default_output_device()
|
||||||
|
.ok_or_else(|| "no default output device".to_owned())?;
|
||||||
|
let config = device.default_output_config().map_err(|e| e.to_string())?;
|
||||||
|
let buffer = match config.buffer_size() {
|
||||||
|
SupportedBufferSize::Range { min, max } => {
|
||||||
|
BufferSize::Fixed(buffer_frames(config.sample_rate(), *min, *max))
|
||||||
|
}
|
||||||
|
SupportedBufferSize::Unknown => BufferSize::Default,
|
||||||
|
};
|
||||||
|
DeviceSinkBuilder::default()
|
||||||
|
.with_device(device)
|
||||||
|
.with_supported_config(&config)
|
||||||
|
.with_buffer_size(buffer)
|
||||||
|
.open_stream()
|
||||||
|
.or_else(|first| DeviceSinkBuilder::open_default_sink().map_err(|_| first.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// About 50 ms of audio, rounded to a power of two, within the device's limits.
|
||||||
|
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>) {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
emit(Event::NoOutput(e));
|
||||||
|
// Keep draining so senders never block or error; nothing can play.
|
||||||
|
while inbox.recv().is_ok() {}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let player = Player::connect_new(sink.mixer());
|
||||||
|
|
||||||
|
let mut loaded: Option<u64> = None;
|
||||||
|
let mut ended_sent = false;
|
||||||
|
let mut last_reported = None;
|
||||||
|
|
||||||
|
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 {
|
||||||
|
Ok(source) => {
|
||||||
|
let duration = source.total_duration();
|
||||||
|
player.append(source);
|
||||||
|
if play {
|
||||||
|
player.play();
|
||||||
|
}
|
||||||
|
loaded = Some(generation);
|
||||||
|
ended_sent = false;
|
||||||
|
last_reported = None;
|
||||||
|
emit(Event::Loaded { generation, duration });
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
loaded = None;
|
||||||
|
emit(Event::DecodeFailed { generation, reason: e.to_string() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Command::Play) => player.play(),
|
||||||
|
Ok(Command::Pause) => player.pause(),
|
||||||
|
Ok(Command::Seek(to)) => {
|
||||||
|
if let Some(generation) = loaded {
|
||||||
|
// 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() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Command::Volume(v)) => player.set_volume(v.clamp(0.0, 1.0)),
|
||||||
|
Ok(Command::Stop) => {
|
||||||
|
player.clear();
|
||||||
|
loaded = None;
|
||||||
|
}
|
||||||
|
Err(RecvTimeoutError::Timeout) => {}
|
||||||
|
Err(RecvTimeoutError::Disconnected) => break,
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(generation) = loaded else { continue };
|
||||||
|
if player.empty() {
|
||||||
|
if !ended_sent {
|
||||||
|
ended_sent = true;
|
||||||
|
emit(Event::Ended { generation });
|
||||||
|
}
|
||||||
|
} else if !player.is_paused() {
|
||||||
|
let position = 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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::buffer_frames;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn buffer_fits_bluetooth_limits() {
|
||||||
|
assert_eq!(buffer_frames(44_100, 14, 1024), 1024);
|
||||||
|
assert_eq!(buffer_frames(48_000, 15, 4096), 4096);
|
||||||
|
assert_eq!(buffer_frames(8_000, 512, 4096), 512);
|
||||||
|
assert_eq!(buffer_frames(44_100, 100, 50), 100, "a bogus range still yields the minimum");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,557 @@
|
|||||||
|
//! Playback state: the queue, what's loaded, and the rules for moving between
|
||||||
|
//! tracks. Network work is described as [`Effect`]s for the app to run, so this
|
||||||
|
//! module stays free of the API client and can be tested on its own.
|
||||||
|
|
||||||
|
pub mod engine;
|
||||||
|
pub mod queue;
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use ym_api::{Error, Stream, Track};
|
||||||
|
|
||||||
|
use engine::{Command, Event};
|
||||||
|
pub use queue::{Queue, Repeat};
|
||||||
|
|
||||||
|
/// Give up after this many unplayable tracks in a row instead of skipping forever.
|
||||||
|
const MAX_SKIPS: u8 = 3;
|
||||||
|
/// "Previous" restarts the current track once it has played this long.
|
||||||
|
const RESTART_AFTER: Duration = Duration::from_secs(3);
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Status {
|
||||||
|
Loading,
|
||||||
|
Playing,
|
||||||
|
Paused,
|
||||||
|
/// The queue ran out with repeat off. Play starts the last track again.
|
||||||
|
Ended,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Audio for one track, ready to hand to the engine.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Audio {
|
||||||
|
pub stream: Stream,
|
||||||
|
pub bytes: Arc<[u8]>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum Msg {
|
||||||
|
Engine(Event),
|
||||||
|
/// Replace the queue. `shuffle` sets shuffle first; with it on, `start` is ignored.
|
||||||
|
Play { tracks: Arc<[Track]>, start: usize, shuffle: Option<bool> },
|
||||||
|
Toggle,
|
||||||
|
Next,
|
||||||
|
Previous,
|
||||||
|
ToggleShuffle,
|
||||||
|
CycleRepeat,
|
||||||
|
/// The seek bar is being dragged; only the bar moves.
|
||||||
|
SeekPreview(f32),
|
||||||
|
SeekCommit,
|
||||||
|
SetVolume(f32),
|
||||||
|
ToggleMute,
|
||||||
|
JumpTo(usize),
|
||||||
|
Fetched { generation: u64, result: Result<Audio, Error> },
|
||||||
|
Prefetched { track_id: String, result: Result<Audio, Error> },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Work the app has to do on the player's behalf.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum Effect {
|
||||||
|
Fetch { generation: u64, track_id: String },
|
||||||
|
Prefetch { track_id: String },
|
||||||
|
/// The token stopped working mid-session.
|
||||||
|
SignedOut,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Player {
|
||||||
|
engine: Option<engine::Handle>,
|
||||||
|
queue: Option<Queue<Track>>,
|
||||||
|
pub repeat: Repeat,
|
||||||
|
shuffle: bool,
|
||||||
|
pub volume: f32,
|
||||||
|
pub muted: bool,
|
||||||
|
generation: u64,
|
||||||
|
status: Status,
|
||||||
|
position: Duration,
|
||||||
|
duration: Duration,
|
||||||
|
current: Option<Audio>,
|
||||||
|
/// Which track `current` holds, so a replay can reuse it.
|
||||||
|
current_track_id: Option<String>,
|
||||||
|
prefetched: Option<(String, Audio)>,
|
||||||
|
skips: u8,
|
||||||
|
seeking: Option<f32>,
|
||||||
|
/// One line for the player bar when something went wrong.
|
||||||
|
pub notice: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Player {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
engine: None,
|
||||||
|
queue: None,
|
||||||
|
repeat: Repeat::Off,
|
||||||
|
shuffle: false,
|
||||||
|
volume: 0.7,
|
||||||
|
muted: false,
|
||||||
|
generation: 0,
|
||||||
|
status: Status::Paused,
|
||||||
|
position: Duration::ZERO,
|
||||||
|
duration: Duration::ZERO,
|
||||||
|
current: None,
|
||||||
|
current_track_id: None,
|
||||||
|
prefetched: None,
|
||||||
|
skips: 0,
|
||||||
|
seeking: None,
|
||||||
|
notice: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Player {
|
||||||
|
/// Stops playback and forgets the queue (sign-out). The device and volume stay.
|
||||||
|
pub fn reset(&mut self) {
|
||||||
|
self.send(Command::Stop);
|
||||||
|
*self = Self { engine: self.engine.take(), volume: self.volume, muted: self.muted, ..Self::default() };
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn track(&self) -> Option<&Track> {
|
||||||
|
self.queue.as_ref().map(Queue::current)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn queue(&self) -> Option<&Queue<Track>> {
|
||||||
|
self.queue.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn status(&self) -> Status {
|
||||||
|
self.status
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn shuffle(&self) -> bool {
|
||||||
|
self.shuffle
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the seek bar should sit: the drag position while dragging.
|
||||||
|
pub fn position(&self) -> Duration {
|
||||||
|
self.seeking.map_or(self.position, Duration::from_secs_f32)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn duration(&self) -> Duration {
|
||||||
|
self.duration
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stream(&self) -> Option<&Stream> {
|
||||||
|
self.current.as_ref().map(|a| &a.stream)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send(&self, command: Command) {
|
||||||
|
if let Some(engine) = &self.engine {
|
||||||
|
engine.send(command);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn effective_volume(&self) -> f32 {
|
||||||
|
if self.muted { 0.0 } else { self.volume }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(&mut self, msg: Msg) -> Vec<Effect> {
|
||||||
|
match msg {
|
||||||
|
Msg::Engine(event) => return self.on_engine(event),
|
||||||
|
Msg::Play { tracks, start, shuffle } => {
|
||||||
|
if let Some(on) = shuffle {
|
||||||
|
self.shuffle = on;
|
||||||
|
}
|
||||||
|
let start = if shuffle == Some(true) && !tracks.is_empty() {
|
||||||
|
rand::random_range(0..tracks.len())
|
||||||
|
} else {
|
||||||
|
start
|
||||||
|
};
|
||||||
|
self.queue = Queue::new(tracks.to_vec(), start, self.shuffle);
|
||||||
|
self.skips = 0;
|
||||||
|
self.notice = None;
|
||||||
|
return self.load_current();
|
||||||
|
}
|
||||||
|
Msg::Toggle => match self.status {
|
||||||
|
Status::Playing => {
|
||||||
|
self.send(Command::Pause);
|
||||||
|
self.status = Status::Paused;
|
||||||
|
}
|
||||||
|
Status::Paused if self.current.is_some() => {
|
||||||
|
self.send(Command::Play);
|
||||||
|
self.status = Status::Playing;
|
||||||
|
}
|
||||||
|
Status::Paused if self.queue.is_some() => return self.load_current(),
|
||||||
|
Status::Ended => return self.load_current(),
|
||||||
|
Status::Paused | Status::Loading => {}
|
||||||
|
},
|
||||||
|
Msg::Next => return self.step(true, false),
|
||||||
|
Msg::Previous => {
|
||||||
|
if self.position >= RESTART_AFTER || !self.can_go_back() {
|
||||||
|
self.seek(Duration::ZERO);
|
||||||
|
} else if let Some(queue) = &mut self.queue {
|
||||||
|
queue.back(self.repeat);
|
||||||
|
return self.load_current();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Msg::ToggleShuffle => {
|
||||||
|
self.shuffle = !self.shuffle;
|
||||||
|
if let Some(queue) = &mut self.queue {
|
||||||
|
queue.set_shuffle(self.shuffle);
|
||||||
|
}
|
||||||
|
return self.prefetch_next();
|
||||||
|
}
|
||||||
|
Msg::CycleRepeat => {
|
||||||
|
self.repeat = self.repeat.next();
|
||||||
|
return self.prefetch_next();
|
||||||
|
}
|
||||||
|
Msg::SeekPreview(secs) => self.seeking = Some(secs),
|
||||||
|
Msg::SeekCommit => {
|
||||||
|
if let Some(secs) = self.seeking.take() {
|
||||||
|
self.seek(Duration::from_secs_f32(secs.max(0.0)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Msg::SetVolume(v) => {
|
||||||
|
self.volume = v.clamp(0.0, 1.0);
|
||||||
|
self.muted = self.volume == 0.0;
|
||||||
|
self.send(Command::Volume(self.effective_volume()));
|
||||||
|
}
|
||||||
|
Msg::ToggleMute => {
|
||||||
|
self.muted = !self.muted;
|
||||||
|
if !self.muted && self.volume == 0.0 {
|
||||||
|
self.volume = 0.5;
|
||||||
|
}
|
||||||
|
self.send(Command::Volume(self.effective_volume()));
|
||||||
|
}
|
||||||
|
Msg::JumpTo(pos) => {
|
||||||
|
if let Some(queue) = &mut self.queue {
|
||||||
|
queue.jump(pos);
|
||||||
|
return self.load_current();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Msg::Fetched { generation, result } => {
|
||||||
|
if generation != self.generation {
|
||||||
|
return vec![];
|
||||||
|
}
|
||||||
|
match result {
|
||||||
|
Ok(audio) => self.start(audio),
|
||||||
|
Err(Error::Unauthorized(_)) => return vec![Effect::SignedOut],
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("fetch: {e}");
|
||||||
|
return self.skip_unplayable();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Msg::Prefetched { track_id, result } => match result {
|
||||||
|
Ok(audio) => self.prefetched = Some((track_id, audio)),
|
||||||
|
Err(e) => eprintln!("prefetch {track_id}: {e}"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
vec![]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_engine(&mut self, event: Event) -> Vec<Effect> {
|
||||||
|
match event {
|
||||||
|
Event::Ready(handle) => {
|
||||||
|
handle.send(Command::Volume(self.effective_volume()));
|
||||||
|
self.engine = Some(handle);
|
||||||
|
}
|
||||||
|
Event::NoOutput(reason) => {
|
||||||
|
eprintln!("audio output: {reason}");
|
||||||
|
self.notice = Some(
|
||||||
|
"No sound output found. Connect speakers or headphones, then restart Musyx."
|
||||||
|
.into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Event::Loaded { generation, duration } if generation == self.generation => {
|
||||||
|
if let Some(d) = duration.filter(|d| !d.is_zero()) {
|
||||||
|
self.duration = d;
|
||||||
|
}
|
||||||
|
self.status = Status::Playing;
|
||||||
|
self.skips = 0;
|
||||||
|
return self.prefetch_next();
|
||||||
|
}
|
||||||
|
Event::Position { generation, position } if generation == self.generation => {
|
||||||
|
self.position = position;
|
||||||
|
}
|
||||||
|
Event::Ended { generation } if generation == self.generation => {
|
||||||
|
return self.step(false, true);
|
||||||
|
}
|
||||||
|
Event::DecodeFailed { generation, reason } if generation == self.generation => {
|
||||||
|
eprintln!("decode: {reason}");
|
||||||
|
return self.skip_unplayable();
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
vec![]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn can_go_back(&self) -> bool {
|
||||||
|
self.queue.as_ref().is_some_and(|q| q.len() > 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn seek(&mut self, to: Duration) {
|
||||||
|
let to = to.min(self.duration);
|
||||||
|
self.position = to;
|
||||||
|
if self.status == Status::Ended {
|
||||||
|
// The player is empty after the end; reload and play from `to`.
|
||||||
|
if let Some(audio) = self.current.clone() {
|
||||||
|
self.load_audio(audio, true);
|
||||||
|
self.send(Command::Seek(to));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.send(Command::Seek(to));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Next track. `finished` distinguishes a natural end (repeat-one replays)
|
||||||
|
/// from a skip; `user` skips always move on.
|
||||||
|
fn step(&mut self, user: bool, finished: bool) -> Vec<Effect> {
|
||||||
|
let Some(queue) = &mut self.queue else { return vec![] };
|
||||||
|
if queue.advance(self.repeat, finished && !user) {
|
||||||
|
self.load_current()
|
||||||
|
} else {
|
||||||
|
self.status = Status::Ended;
|
||||||
|
self.position = self.duration;
|
||||||
|
vec![]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_current(&mut self) -> Vec<Effect> {
|
||||||
|
let Some(track) = self.track().cloned() else { return vec![] };
|
||||||
|
self.generation += 1;
|
||||||
|
self.position = Duration::ZERO;
|
||||||
|
self.duration = track.duration;
|
||||||
|
self.seeking = None;
|
||||||
|
|
||||||
|
// Replaying the same track (repeat one, play after the end) reuses its bytes.
|
||||||
|
let reuse = match (&self.current, self.prefetched.take()) {
|
||||||
|
(_, Some((id, audio))) if id == track.id => Some(audio),
|
||||||
|
(Some(audio), other) => {
|
||||||
|
self.prefetched = other;
|
||||||
|
self.current_is(&track).then(|| audio.clone())
|
||||||
|
}
|
||||||
|
(None, other) => {
|
||||||
|
self.prefetched = other;
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match reuse {
|
||||||
|
Some(audio) => {
|
||||||
|
self.start(audio);
|
||||||
|
vec![]
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
self.status = Status::Loading;
|
||||||
|
self.current = None;
|
||||||
|
vec![Effect::Fetch { generation: self.generation, track_id: track.id }]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn current_is(&self, track: &Track) -> bool {
|
||||||
|
self.current_track_id.as_deref() == Some(track.id.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start(&mut self, audio: Audio) {
|
||||||
|
self.load_audio(audio, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_audio(&mut self, audio: Audio, play: bool) {
|
||||||
|
self.current_track_id = self.track().map(|t| t.id.clone());
|
||||||
|
self.status = Status::Loading;
|
||||||
|
self.send(Command::Load {
|
||||||
|
generation: self.generation,
|
||||||
|
bytes: audio.bytes.clone(),
|
||||||
|
hint: audio.stream.codec.clone(),
|
||||||
|
play,
|
||||||
|
});
|
||||||
|
self.current = Some(audio);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prefetch_next(&mut self) -> Vec<Effect> {
|
||||||
|
let Some(queue) = &self.queue else { return vec![] };
|
||||||
|
let Some(next) = queue.peek_next(self.repeat) else { return vec![] };
|
||||||
|
if self.current_is(next) {
|
||||||
|
return vec![];
|
||||||
|
}
|
||||||
|
if self.prefetched.as_ref().is_some_and(|(id, _)| *id == next.id) {
|
||||||
|
return vec![];
|
||||||
|
}
|
||||||
|
self.prefetched = None;
|
||||||
|
vec![Effect::Prefetch { track_id: next.id.clone() }]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn skip_unplayable(&mut self) -> Vec<Effect> {
|
||||||
|
let title = self.track().map(Track::full_title).unwrap_or_default();
|
||||||
|
self.skips += 1;
|
||||||
|
self.current = None;
|
||||||
|
if self.skips >= MAX_SKIPS {
|
||||||
|
self.status = Status::Paused;
|
||||||
|
self.notice = Some("Several tracks in a row couldn't be played. Check your connection and try again.".into());
|
||||||
|
return vec![];
|
||||||
|
}
|
||||||
|
self.notice = Some(format!("Couldn't play “{title}”, so it was skipped."));
|
||||||
|
self.step(true, false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn track(id: &str, secs: u64) -> Track {
|
||||||
|
let json = format!(r#"{{"id":"{id}","title":"T{id}","durationMs":{}}}"#, secs * 1000);
|
||||||
|
Track::from_json(&json).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn audio() -> Audio {
|
||||||
|
Audio {
|
||||||
|
stream: Stream { url: "u".into(), codec: "mp3".into(), bitrate_kbps: 320, preview: false },
|
||||||
|
bytes: Arc::from(vec![0u8; 4]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn playing(n: usize, start: usize) -> Player {
|
||||||
|
let mut p = Player::default();
|
||||||
|
let tracks: Arc<[Track]> = (0..n).map(|i| track(&i.to_string(), 100)).collect();
|
||||||
|
let effects = p.update(Msg::Play { tracks, start, shuffle: None });
|
||||||
|
let Some(Effect::Fetch { generation, .. }) = effects.first().cloned() else {
|
||||||
|
panic!("expected fetch, got {effects:?}");
|
||||||
|
};
|
||||||
|
p.update(Msg::Fetched { generation, result: Ok(audio()) });
|
||||||
|
p.update(Msg::Engine(Event::Loaded { generation, duration: None }));
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn play_fetches_then_plays_and_prefetches_next() {
|
||||||
|
let mut p = Player::default();
|
||||||
|
let tracks: Arc<[Track]> = vec![track("a", 10), track("b", 20)].into();
|
||||||
|
let effects = p.update(Msg::Play { tracks, start: 0, shuffle: None });
|
||||||
|
assert_eq!(effects, vec![Effect::Fetch { generation: 1, track_id: "a".into() }]);
|
||||||
|
assert_eq!(p.status(), Status::Loading);
|
||||||
|
assert!(p.update(Msg::Fetched { generation: 1, result: Ok(audio()) }).is_empty());
|
||||||
|
let effects = p.update(Msg::Engine(Event::Loaded { generation: 1, duration: None }));
|
||||||
|
assert_eq!(p.status(), Status::Playing);
|
||||||
|
assert_eq!(p.duration(), Duration::from_secs(10));
|
||||||
|
assert_eq!(effects, vec![Effect::Prefetch { track_id: "b".into() }]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prefetched_audio_is_used_without_another_fetch() {
|
||||||
|
let mut p = playing(3, 0);
|
||||||
|
p.update(Msg::Prefetched { track_id: "1".into(), result: Ok(audio()) });
|
||||||
|
let generation = p.generation;
|
||||||
|
let effects = p.update(Msg::Engine(Event::Ended { generation }));
|
||||||
|
assert!(!effects.iter().any(|e| matches!(e, Effect::Fetch { .. })), "{effects:?}");
|
||||||
|
assert_eq!(p.track().unwrap().id, "1");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stale_events_are_ignored() {
|
||||||
|
let mut p = playing(3, 0);
|
||||||
|
let old = p.generation;
|
||||||
|
p.update(Msg::Next);
|
||||||
|
p.update(Msg::Engine(Event::Position { generation: old, position: Duration::from_secs(50) }));
|
||||||
|
assert_eq!(p.position(), Duration::ZERO);
|
||||||
|
assert!(p.update(Msg::Fetched { generation: old, result: Ok(audio()) }).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn end_of_queue_stops_and_play_restarts_last_track() {
|
||||||
|
let mut p = playing(1, 0);
|
||||||
|
let generation = p.generation;
|
||||||
|
assert!(p.update(Msg::Engine(Event::Ended { generation })).is_empty());
|
||||||
|
assert_eq!(p.status(), Status::Ended);
|
||||||
|
let effects = p.update(Msg::Toggle);
|
||||||
|
assert!(effects.is_empty(), "replay comes from memory: {effects:?}");
|
||||||
|
assert_eq!(p.status(), Status::Loading);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn repeat_one_replays_from_memory() {
|
||||||
|
let mut p = playing(3, 1);
|
||||||
|
p.update(Msg::CycleRepeat);
|
||||||
|
p.update(Msg::CycleRepeat);
|
||||||
|
assert_eq!(p.repeat, Repeat::One);
|
||||||
|
let generation = p.generation;
|
||||||
|
let effects = p.update(Msg::Engine(Event::Ended { generation }));
|
||||||
|
assert!(effects.is_empty(), "{effects:?}");
|
||||||
|
assert_eq!(p.track().unwrap().id, "1");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn previous_restarts_after_three_seconds() {
|
||||||
|
let mut p = playing(3, 1);
|
||||||
|
let generation = p.generation;
|
||||||
|
p.update(Msg::Engine(Event::Position { generation, position: Duration::from_secs(10) }));
|
||||||
|
p.update(Msg::Previous);
|
||||||
|
assert_eq!(p.track().unwrap().id, "1");
|
||||||
|
assert_eq!(p.position(), Duration::ZERO);
|
||||||
|
p.update(Msg::Previous);
|
||||||
|
assert_eq!(p.track().unwrap().id, "0");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unplayable_tracks_are_skipped_then_given_up_on() {
|
||||||
|
let mut p = playing(5, 0);
|
||||||
|
for expected_skips in 1..MAX_SKIPS {
|
||||||
|
p.update(Msg::Next);
|
||||||
|
let generation = p.generation;
|
||||||
|
p.update(Msg::Fetched { generation, result: Err(Error::Api("gone".into())) });
|
||||||
|
assert_eq!(p.skips, expected_skips);
|
||||||
|
assert!(p.notice.as_deref().unwrap().contains("skipped"));
|
||||||
|
}
|
||||||
|
let generation = p.generation;
|
||||||
|
let effects = p.update(Msg::Fetched { generation, result: Err(Error::Api("gone".into())) });
|
||||||
|
assert!(effects.is_empty());
|
||||||
|
assert!(p.notice.as_deref().unwrap().contains("Several tracks"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn expired_token_signs_out() {
|
||||||
|
let mut p = Player::default();
|
||||||
|
let tracks: Arc<[Track]> = vec![track("a", 10)].into();
|
||||||
|
p.update(Msg::Play { tracks, start: 0, shuffle: None });
|
||||||
|
let effects =
|
||||||
|
p.update(Msg::Fetched { generation: 1, result: Err(Error::Unauthorized("401".into())) });
|
||||||
|
assert_eq!(effects, vec![Effect::SignedOut]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn seek_preview_moves_bar_until_commit() {
|
||||||
|
let mut p = playing(1, 0);
|
||||||
|
p.update(Msg::SeekPreview(42.0));
|
||||||
|
assert_eq!(p.position(), Duration::from_secs(42));
|
||||||
|
p.update(Msg::SeekCommit);
|
||||||
|
assert_eq!(p.position(), Duration::from_secs(42));
|
||||||
|
assert!(p.seeking.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shuffle_play_turns_shuffle_on() {
|
||||||
|
let mut p = Player::default();
|
||||||
|
let tracks: Arc<[Track]> = (0..20).map(|i| track(&i.to_string(), 10)).collect();
|
||||||
|
p.update(Msg::Play { tracks, start: 0, shuffle: Some(true) });
|
||||||
|
assert!(p.shuffle());
|
||||||
|
assert_eq!(p.queue().unwrap().upcoming().count(), 19);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reset_keeps_volume_but_drops_queue() {
|
||||||
|
let mut p = playing(3, 0);
|
||||||
|
p.update(Msg::SetVolume(0.3));
|
||||||
|
p.reset();
|
||||||
|
assert!(p.track().is_none());
|
||||||
|
assert_eq!(p.volume, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mute_and_volume() {
|
||||||
|
let mut p = Player::default();
|
||||||
|
p.update(Msg::SetVolume(0.0));
|
||||||
|
assert!(p.muted);
|
||||||
|
p.update(Msg::ToggleMute);
|
||||||
|
assert!(!p.muted);
|
||||||
|
assert_eq!(p.volume, 0.5);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
//! Play order over a fixed list of items: shuffle, repeat, next/previous.
|
||||||
|
//!
|
||||||
|
//! Generic so the rules can be tested with plain numbers; the app uses `Track`.
|
||||||
|
|
||||||
|
use rand::seq::SliceRandom;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||||
|
pub enum Repeat {
|
||||||
|
#[default]
|
||||||
|
Off,
|
||||||
|
All,
|
||||||
|
One,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Repeat {
|
||||||
|
pub fn next(self) -> Self {
|
||||||
|
match self {
|
||||||
|
Repeat::Off => Repeat::All,
|
||||||
|
Repeat::All => Repeat::One,
|
||||||
|
Repeat::One => Repeat::Off,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Queue<T> {
|
||||||
|
items: Vec<T>,
|
||||||
|
/// Indices into `items` in play order.
|
||||||
|
order: Vec<usize>,
|
||||||
|
/// Position in `order` of the current item.
|
||||||
|
pos: usize,
|
||||||
|
shuffle: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Queue<T> {
|
||||||
|
/// A queue over `items` starting at `start`. Returns `None` for an empty list.
|
||||||
|
pub fn new(items: Vec<T>, start: usize, shuffle: bool) -> Option<Self> {
|
||||||
|
if items.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let start = start.min(items.len() - 1);
|
||||||
|
let mut queue = Self { order: (0..items.len()).collect(), items, pos: start, shuffle: false };
|
||||||
|
if shuffle {
|
||||||
|
queue.set_shuffle(true);
|
||||||
|
}
|
||||||
|
Some(queue)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn current(&self) -> &T {
|
||||||
|
&self.items[self.order[self.pos]]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves on after a track. `finished` is true when it played to the end, in
|
||||||
|
/// which case `Repeat::One` replays it; a skip always advances. Returns
|
||||||
|
/// `false` at the end of the queue with repeat off.
|
||||||
|
pub fn advance(&mut self, repeat: Repeat, finished: bool) -> bool {
|
||||||
|
if finished && repeat == Repeat::One {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if self.pos + 1 < self.order.len() {
|
||||||
|
self.pos += 1;
|
||||||
|
true
|
||||||
|
} else if repeat != Repeat::Off {
|
||||||
|
self.pos = 0;
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Steps back one item, wrapping when repeat is on. Returns `false` at the start.
|
||||||
|
pub fn back(&mut self, repeat: Repeat) -> bool {
|
||||||
|
if self.pos > 0 {
|
||||||
|
self.pos -= 1;
|
||||||
|
true
|
||||||
|
} else if repeat != Repeat::Off {
|
||||||
|
self.pos = self.order.len() - 1;
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The item that `advance(repeat, true)` would move to, without moving.
|
||||||
|
pub fn peek_next(&self, repeat: Repeat) -> Option<&T> {
|
||||||
|
match repeat {
|
||||||
|
Repeat::One => Some(self.current()),
|
||||||
|
_ if self.pos + 1 < self.order.len() => Some(&self.items[self.order[self.pos + 1]]),
|
||||||
|
Repeat::All => Some(&self.items[self.order[0]]),
|
||||||
|
Repeat::Off => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Items after the current one, in play order (no wrap-around).
|
||||||
|
pub fn upcoming(&self) -> impl Iterator<Item = (usize, &T)> {
|
||||||
|
self.order[self.pos + 1..].iter().enumerate().map(move |(i, &ix)| (self.pos + 1 + i, &self.items[ix]))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Jumps to a play-order position from [`Queue::upcoming`].
|
||||||
|
pub fn jump(&mut self, order_pos: usize) {
|
||||||
|
if order_pos < self.order.len() {
|
||||||
|
self.pos = order_pos;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Turning shuffle on keeps the current item and shuffles everything after it;
|
||||||
|
/// turning it off restores list order at the current item.
|
||||||
|
pub fn set_shuffle(&mut self, on: bool) {
|
||||||
|
if on == self.shuffle {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let current = self.order[self.pos];
|
||||||
|
if on {
|
||||||
|
let mut rest: Vec<usize> = (0..self.items.len()).filter(|&i| i != current).collect();
|
||||||
|
rest.shuffle(&mut rand::rng());
|
||||||
|
self.order = std::iter::once(current).chain(rest).collect();
|
||||||
|
self.pos = 0;
|
||||||
|
} else {
|
||||||
|
self.order = (0..self.items.len()).collect();
|
||||||
|
self.pos = current;
|
||||||
|
}
|
||||||
|
self.shuffle = on;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.items.len()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn q(n: usize, start: usize) -> Queue<usize> {
|
||||||
|
Queue::new((0..n).collect(), start, false).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_list_has_no_queue() {
|
||||||
|
assert!(Queue::<u8>::new(vec![], 0, false).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn start_is_clamped() {
|
||||||
|
assert_eq!(*q(3, 99).current(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn advance_stops_at_end_without_repeat() {
|
||||||
|
let mut q = q(2, 0);
|
||||||
|
assert!(q.advance(Repeat::Off, true));
|
||||||
|
assert_eq!(*q.current(), 1);
|
||||||
|
assert!(!q.advance(Repeat::Off, true));
|
||||||
|
assert_eq!(*q.current(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn repeat_all_wraps_both_ways() {
|
||||||
|
let mut q = q(3, 2);
|
||||||
|
assert!(q.advance(Repeat::All, true));
|
||||||
|
assert_eq!(*q.current(), 0);
|
||||||
|
assert!(q.back(Repeat::All));
|
||||||
|
assert_eq!(*q.current(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn repeat_one_replays_on_finish_but_skip_moves_on() {
|
||||||
|
let mut q = q(3, 1);
|
||||||
|
assert!(q.advance(Repeat::One, true));
|
||||||
|
assert_eq!(*q.current(), 1);
|
||||||
|
assert!(q.advance(Repeat::One, false));
|
||||||
|
assert_eq!(*q.current(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn back_stops_at_start_without_repeat() {
|
||||||
|
let mut q = q(3, 0);
|
||||||
|
assert!(!q.back(Repeat::Off));
|
||||||
|
assert_eq!(*q.current(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn peek_matches_advance() {
|
||||||
|
for repeat in [Repeat::Off, Repeat::All, Repeat::One] {
|
||||||
|
for start in 0..3 {
|
||||||
|
let mut q = q(3, start);
|
||||||
|
let peeked = q.peek_next(repeat).copied();
|
||||||
|
let moved = q.advance(repeat, true);
|
||||||
|
assert_eq!(peeked, moved.then(|| *q.current()), "{repeat:?} from {start}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shuffle_keeps_current_and_covers_everything() {
|
||||||
|
let mut q = q(50, 17);
|
||||||
|
q.set_shuffle(true);
|
||||||
|
assert_eq!(*q.current(), 17);
|
||||||
|
let mut seen: Vec<usize> = std::iter::once(17).chain(q.upcoming().map(|(_, &x)| x)).collect();
|
||||||
|
seen.sort_unstable();
|
||||||
|
assert_eq!(seen, (0..50).collect::<Vec<_>>());
|
||||||
|
q.advance(Repeat::Off, false);
|
||||||
|
let now = *q.current();
|
||||||
|
q.set_shuffle(false);
|
||||||
|
assert_eq!(*q.current(), now, "unshuffling keeps the current item");
|
||||||
|
assert_eq!(q.upcoming().count(), 49 - now);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn jump_moves_to_upcoming_position() {
|
||||||
|
let mut q = q(5, 0);
|
||||||
|
let (pos, &item) = q.upcoming().nth(2).unwrap();
|
||||||
|
q.jump(pos);
|
||||||
|
assert_eq!(*q.current(), item);
|
||||||
|
q.jump(99);
|
||||||
|
assert_eq!(*q.current(), item);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
//! Collection: for now the liked tracks list, which is also the first thing
|
||||||
|
//! you can play.
|
||||||
|
|
||||||
|
use std::collections::HashSet;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use iced::widget::{Column, button, column, lazy, row};
|
||||||
|
use iced::{Alignment, Element, Fill};
|
||||||
|
use ym_api::{Error, Track};
|
||||||
|
|
||||||
|
use crate::app::Message;
|
||||||
|
use crate::ui::icons::{Icon, icon};
|
||||||
|
use crate::ui::theme::{self, Tokens, size};
|
||||||
|
use crate::ui::{line, para};
|
||||||
|
use crate::widgets::track_row;
|
||||||
|
|
||||||
|
/// The liked-tracks list as the app holds it.
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub enum Liked {
|
||||||
|
#[default]
|
||||||
|
NotLoaded,
|
||||||
|
Loading,
|
||||||
|
Loaded {
|
||||||
|
tracks: Arc<[Track]>,
|
||||||
|
ids: HashSet<String>,
|
||||||
|
/// Bumped on every reload so the cached rows rebuild.
|
||||||
|
version: u64,
|
||||||
|
},
|
||||||
|
Failed(Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Liked {
|
||||||
|
pub fn loaded(tracks: Vec<Track>, previous: &Liked) -> Self {
|
||||||
|
let version = match previous {
|
||||||
|
Liked::Loaded { version, .. } => version + 1,
|
||||||
|
_ => 0,
|
||||||
|
};
|
||||||
|
let ids = tracks.iter().map(|t| t.id.clone()).collect();
|
||||||
|
Liked::Loaded { tracks: tracks.into(), ids, version }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn contains(&self, track_id: &str) -> bool {
|
||||||
|
matches!(self, Liked::Loaded { ids, .. } if ids.contains(track_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tracks(&self) -> Option<&Arc<[Track]>> {
|
||||||
|
match self {
|
||||||
|
Liked::Loaded { tracks, .. } => Some(tracks),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What makes the list look different; anything else reuses the built rows.
|
||||||
|
#[derive(Hash)]
|
||||||
|
struct ListKey {
|
||||||
|
version: u64,
|
||||||
|
playing: Option<String>,
|
||||||
|
dark: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn view<'a>(t: &'static Tokens, liked: &'a Liked, playing: Option<&'a str>) -> Element<'a, Message> {
|
||||||
|
let title = line("Collection", theme::DISPLAY, size::DISPLAY_S, t.fg);
|
||||||
|
|
||||||
|
let body: Element<'a, Message> = match liked {
|
||||||
|
Liked::NotLoaded | Liked::Loading => para("Loading your liked tracks…", size::BODY, t.muted).into(),
|
||||||
|
Liked::Failed(err) => column![
|
||||||
|
para(
|
||||||
|
match err {
|
||||||
|
Error::Network(_) => "Couldn't load your liked tracks. Check your connection and try again.",
|
||||||
|
_ => "Couldn't load your liked tracks. Try again in a moment.",
|
||||||
|
},
|
||||||
|
size::BODY,
|
||||||
|
t.muted,
|
||||||
|
),
|
||||||
|
button(line("Try again", theme::SEMIBOLD, size::BODY, t.accent_ink))
|
||||||
|
.padding([11, 18])
|
||||||
|
.style(theme::primary)
|
||||||
|
.on_press(Message::LoadLiked),
|
||||||
|
]
|
||||||
|
.spacing(16)
|
||||||
|
.into(),
|
||||||
|
Liked::Loaded { tracks, .. } if tracks.is_empty() => para(
|
||||||
|
"No liked tracks yet. Tap the heart on any track and it lands here.",
|
||||||
|
size::BODY,
|
||||||
|
t.muted,
|
||||||
|
)
|
||||||
|
.into(),
|
||||||
|
Liked::Loaded { tracks, version, .. } => {
|
||||||
|
let key = ListKey { version: *version, playing: playing.map(str::to_owned), dark: t == &theme::DARK };
|
||||||
|
let tracks = tracks.clone();
|
||||||
|
let list = lazy(key, move |key: &ListKey| {
|
||||||
|
let rows = tracks.iter().enumerate().map(|(i, track)| {
|
||||||
|
let now = key.playing.as_deref() == Some(track.id.as_str());
|
||||||
|
track_row::view(t, i, track, now, true, Message::PlayLiked { start: i, shuffle: false })
|
||||||
|
});
|
||||||
|
Column::with_children(std::iter::once(track_row::header(t)).chain(rows)).spacing(2)
|
||||||
|
});
|
||||||
|
column![header(t, liked), list].spacing(22).into()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
column![title, body].spacing(28).width(Fill).into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn header<'a>(t: &'static Tokens, liked: &Liked) -> Element<'a, Message> {
|
||||||
|
let count = liked.tracks().map_or(0, |t| t.len());
|
||||||
|
let total: u64 = liked.tracks().map_or(0, |ts| ts.iter().map(|t| t.duration.as_secs()).sum());
|
||||||
|
let summary = format!(
|
||||||
|
"{} {} · {}",
|
||||||
|
count,
|
||||||
|
if count == 1 { "track" } else { "tracks" },
|
||||||
|
if total >= 3600 { format!("{} h {} min", total / 3600, (total % 3600) / 60) } else { format!("{} min", total / 60) },
|
||||||
|
);
|
||||||
|
|
||||||
|
let pill = |glyph: Icon, label: &'static str, ink, style: fn(&iced::Theme, button::Status) -> button::Style, msg| {
|
||||||
|
button(row![icon(glyph, ink), line(label, theme::SEMIBOLD, size::BODY, ink)].spacing(8).align_y(Alignment::Center))
|
||||||
|
.padding([10, 18])
|
||||||
|
.style(style)
|
||||||
|
.on_press(msg)
|
||||||
|
};
|
||||||
|
|
||||||
|
row![
|
||||||
|
column![
|
||||||
|
line("Liked tracks", theme::SEMIBOLD, size::SECTION, t.fg),
|
||||||
|
line(summary, theme::BODY, size::META, t.muted),
|
||||||
|
]
|
||||||
|
.spacing(4)
|
||||||
|
.width(Fill),
|
||||||
|
pill(Icon::Play, "Play", t.accent_ink, theme::primary, Message::PlayLiked { start: 0, shuffle: false }),
|
||||||
|
pill(Icon::Shuffle, "Shuffle", t.fg, theme::ghost, Message::PlayLiked { start: 0, shuffle: true }),
|
||||||
|
]
|
||||||
|
.spacing(10)
|
||||||
|
.align_y(Alignment::Center)
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn track(id: &str) -> Track {
|
||||||
|
Track::from_json(&format!(r#"{{"id":"{id}","title":"T"}}"#)).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reload_bumps_version_and_indexes_ids() {
|
||||||
|
let first = Liked::loaded(vec![track("1"), track("2")], &Liked::Loading);
|
||||||
|
assert!(first.contains("2") && !first.contains("3"));
|
||||||
|
let second = Liked::loaded(vec![track("3")], &first);
|
||||||
|
match second {
|
||||||
|
Liked::Loaded { version, .. } => assert_eq!(version, 1),
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
assert!(!Liked::Failed(Error::Denied).contains("1"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
//! Content for each route, plus the full-window screens shown outside a session.
|
//! Content for each route, plus the full-window screens shown outside a session.
|
||||||
|
|
||||||
|
pub mod collection;
|
||||||
pub mod sign_in;
|
pub mod sign_in;
|
||||||
|
|
||||||
use iced::widget::{Column, button, column, container, row, space};
|
use iced::widget::{Column, button, column, container, row, space};
|
||||||
@@ -13,7 +14,18 @@ use crate::ui::theme::{self, Tokens, radius, size, space as sp};
|
|||||||
use crate::ui::{line, para};
|
use crate::ui::{line, para};
|
||||||
use crate::widgets::sidebar;
|
use crate::widgets::sidebar;
|
||||||
|
|
||||||
pub fn view<'a>(t: &'static Tokens, route: Route, query: &str, me: &'a Account) -> Element<'a, Message> {
|
/// Everything a routed screen may need from app state.
|
||||||
|
pub struct Ctx<'a> {
|
||||||
|
pub t: &'static Tokens,
|
||||||
|
pub route: Route,
|
||||||
|
pub query: &'a str,
|
||||||
|
pub me: &'a Account,
|
||||||
|
pub liked: &'a collection::Liked,
|
||||||
|
pub playing: Option<&'a str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn view<'a>(ctx: Ctx<'a>) -> Element<'a, Message> {
|
||||||
|
let Ctx { t, route, query, me, liked, playing } = ctx;
|
||||||
let content: Column<'a, Message> = match route {
|
let content: Column<'a, Message> = match route {
|
||||||
Route::Home => column![
|
Route::Home => column![
|
||||||
wave_hero(t),
|
wave_hero(t),
|
||||||
@@ -31,10 +43,7 @@ pub fn view<'a>(t: &'static Tokens, route: Route, query: &str, me: &'a Account)
|
|||||||
}),
|
}),
|
||||||
upcoming(t, Icon::Search, "Search the whole catalogue", "Tracks, albums, artists, playlists and podcasts."),
|
upcoming(t, Icon::Search, "Search the whole catalogue", "Tracks, albums, artists, playlists and podcasts."),
|
||||||
],
|
],
|
||||||
Route::Collection => column![
|
Route::Collection => column![collection::view(t, liked, playing)],
|
||||||
title(t, "Collection"),
|
|
||||||
upcoming(t, Icon::HeartFilled, "Everything you've liked", "Liked tracks, albums, artists and playlists."),
|
|
||||||
],
|
|
||||||
Route::Podcasts => column![
|
Route::Podcasts => column![
|
||||||
title(t, "Podcasts and books"),
|
title(t, "Podcasts and books"),
|
||||||
upcoming(t, Icon::Podcast, "Pick up where you left off", "Podcasts and audiobooks you follow."),
|
upcoming(t, Icon::Podcast, "Pick up where you left off", "Podcasts and audiobooks you follow."),
|
||||||
|
|||||||
@@ -75,6 +75,28 @@ impl Config {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Sample liked tracks so the Collection list has rows.
|
||||||
|
pub fn sample_liked(&self) -> Vec<ym_api::Track> {
|
||||||
|
[
|
||||||
|
("1", "Звезда по имени Солнце", "Кино", 7, "Звезда по имени Солнце", 225),
|
||||||
|
("2", "Хочешь?", "Земфира", 3, "Прости меня моя любовь", 225),
|
||||||
|
("3", "Выхода нет", "Сплин", 25, "Гранатовый альбом", 230),
|
||||||
|
("4", "Полковнику никто не пишет", "Би-2", 280, "Би-2", 285),
|
||||||
|
("5", "Владивосток 2000", "Мумий Тролль", 185, "Морская", 165),
|
||||||
|
("6", "Город золотой", "Аквариум", 48, "Десять стрел", 205),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.map(|(id, title, artist, album, album_title, secs)| {
|
||||||
|
ym_api::Track::from_json(&format!(
|
||||||
|
r#"{{"id":"{id}","title":"{title}","durationMs":{ms},"artists":[{{"name":"{artist}"}}],
|
||||||
|
"albums":[{{"id":{album},"title":"{album_title}"}}]}}"#,
|
||||||
|
ms = secs * 1000
|
||||||
|
))
|
||||||
|
.expect("sample track")
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
/// Waits for fonts and the first frames, captures the window, writes the PNG, exits.
|
/// Waits for fonts and the first frames, captures the window, writes the PNG, exits.
|
||||||
pub fn capture<M: Send + 'static>(self) -> Task<M> {
|
pub fn capture<M: Send + 'static>(self) -> Task<M> {
|
||||||
Task::future(tokio::time::sleep(Duration::from_millis(1500)))
|
Task::future(tokio::time::sleep(Duration::from_millis(1500)))
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
//! Right-hand panel with the play queue and lyrics.
|
//! Right-hand panel with the play queue and lyrics.
|
||||||
|
|
||||||
use iced::widget::{button, column, container, row, space};
|
use iced::widget::{button, column, container, row, scrollable, space};
|
||||||
|
use ym_api::Track;
|
||||||
use iced::{Alignment, Element, Fill, Padding};
|
use iced::{Alignment, Element, Fill, Padding};
|
||||||
|
|
||||||
use crate::app::Message;
|
use crate::app::Message;
|
||||||
|
use crate::player::{Msg, Player, Queue};
|
||||||
use crate::ui::icons::{Icon, icon};
|
use crate::ui::icons::{Icon, icon};
|
||||||
use crate::ui::theme::{self, Tokens, shell, size};
|
use crate::ui::theme::{self, Tokens, radius, shell, size};
|
||||||
|
use crate::widgets::player_bar::clock;
|
||||||
use crate::ui::{line, para};
|
use crate::ui::{line, para};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
@@ -23,7 +26,7 @@ impl Panel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn view<'a>(t: &'static Tokens, panel: Panel) -> Element<'a, Message> {
|
pub fn view<'a>(t: &'static Tokens, panel: Panel, player: &'a Player) -> Element<'a, Message> {
|
||||||
let tabs = row![tab(t, Panel::Queue, panel), tab(t, Panel::Lyrics, panel)].spacing(4);
|
let tabs = row![tab(t, Panel::Queue, panel), tab(t, Panel::Lyrics, panel)].spacing(4);
|
||||||
|
|
||||||
let head = row![
|
let head = row![
|
||||||
@@ -37,26 +40,84 @@ pub fn view<'a>(t: &'static Tokens, panel: Panel) -> Element<'a, Message> {
|
|||||||
.align_y(Alignment::Center)
|
.align_y(Alignment::Center)
|
||||||
.padding(Padding::default().top(14).bottom(8).left(18).right(14));
|
.padding(Padding::default().top(14).bottom(8).left(18).right(14));
|
||||||
|
|
||||||
let body = match panel {
|
let body: Element<'a, Message> = match (panel, player.queue()) {
|
||||||
Panel::Queue => para(
|
(Panel::Queue, Some(queue)) => queue_list(t, queue),
|
||||||
|
(Panel::Queue, None) => container(para(
|
||||||
"Nothing queued yet. Tracks you play, and the ones lined up after them, show up here.",
|
"Nothing queued yet. Tracks you play, and the ones lined up after them, show up here.",
|
||||||
size::META,
|
size::META,
|
||||||
t.muted,
|
t.muted,
|
||||||
),
|
))
|
||||||
Panel::Lyrics => para(
|
.padding([4, 20])
|
||||||
"Play a track to see its lyrics. Synced lyrics follow playback, and clicking a line jumps to it.",
|
.into(),
|
||||||
|
(Panel::Lyrics, _) => container(para(
|
||||||
|
"Synced lyrics arrive in a later update. They'll follow playback, and clicking a line will jump to it.",
|
||||||
size::META,
|
size::META,
|
||||||
t.muted,
|
t.muted,
|
||||||
),
|
))
|
||||||
|
.padding([4, 20])
|
||||||
|
.into(),
|
||||||
};
|
};
|
||||||
|
|
||||||
container(column![head, container(body).padding([4, 20])])
|
container(column![head, body])
|
||||||
.width(shell::DRAWER)
|
.width(shell::DRAWER)
|
||||||
.height(Fill)
|
.height(Fill)
|
||||||
.style(theme::panel)
|
.style(theme::panel)
|
||||||
.into()
|
.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Upcoming items shown at once; a long liked list would otherwise build thousands of rows.
|
||||||
|
const SHOWN: usize = 100;
|
||||||
|
|
||||||
|
fn queue_list<'a>(t: &'static Tokens, queue: &'a Queue<Track>) -> Element<'a, Message> {
|
||||||
|
let heading = |s: String| {
|
||||||
|
container(line(s, theme::MEDIUM, size::SMALL, t.muted)).padding(Padding::default().top(14).bottom(8).left(8))
|
||||||
|
};
|
||||||
|
let item = |track: &Track, now: bool, msg: Option<Message>| {
|
||||||
|
let (h1, h2) = track.hues();
|
||||||
|
button(
|
||||||
|
row![
|
||||||
|
container(space()).width(40).height(40).style(theme::cover(h1, h2, radius::SMALL_COVER)),
|
||||||
|
column![
|
||||||
|
line(track.full_title(), theme::MEDIUM, size::BODY, if now { t.accent } else { t.fg }),
|
||||||
|
line(track.artist_line(), theme::BODY, size::SMALL, t.muted),
|
||||||
|
]
|
||||||
|
.spacing(1)
|
||||||
|
.width(Fill)
|
||||||
|
.clip(true),
|
||||||
|
line(clock(track.duration.as_secs_f32()), theme::BODY, size::SMALL, t.muted),
|
||||||
|
]
|
||||||
|
.spacing(10)
|
||||||
|
.align_y(Alignment::Center),
|
||||||
|
)
|
||||||
|
.width(Fill)
|
||||||
|
.padding([6, 8])
|
||||||
|
.style(theme::nav_item(false))
|
||||||
|
.on_press_maybe(msg)
|
||||||
|
};
|
||||||
|
|
||||||
|
let remaining = queue.upcoming().count();
|
||||||
|
let mut list = column![heading("Now playing".into()), item(queue.current(), true, None)];
|
||||||
|
list = list.push(heading(if remaining == 0 {
|
||||||
|
"Nothing after this".into()
|
||||||
|
} else {
|
||||||
|
format!("Next up · {remaining}")
|
||||||
|
}));
|
||||||
|
for (pos, track) in queue.upcoming().take(SHOWN) {
|
||||||
|
list = list.push(item(track, false, Some(Message::Player(Msg::JumpTo(pos)))));
|
||||||
|
}
|
||||||
|
if remaining > SHOWN {
|
||||||
|
list = list.push(
|
||||||
|
container(line(format!("and {} more", remaining - SHOWN), theme::BODY, size::SMALL, t.muted))
|
||||||
|
.padding([10, 8]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
scrollable(list.padding(Padding::default().left(10).right(10).bottom(18)))
|
||||||
|
.height(Fill)
|
||||||
|
.style(theme::scroll)
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
fn tab<'a>(t: &'static Tokens, panel: Panel, selected: Panel) -> Element<'a, Message> {
|
fn tab<'a>(t: &'static Tokens, panel: Panel, selected: Panel) -> Element<'a, Message> {
|
||||||
let on = panel == selected;
|
let on = panel == selected;
|
||||||
button(
|
button(
|
||||||
|
|||||||
@@ -2,3 +2,4 @@ pub mod drawer;
|
|||||||
pub mod player_bar;
|
pub mod player_bar;
|
||||||
pub mod sidebar;
|
pub mod sidebar;
|
||||||
pub mod topbar;
|
pub mod topbar;
|
||||||
|
pub mod track_row;
|
||||||
@@ -1,88 +1,22 @@
|
|||||||
//! The persistent bar along the bottom: now playing, transport, extras.
|
//! The persistent bar along the bottom: now playing, transport, extras.
|
||||||
//!
|
|
||||||
//! Until the audio engine lands the bar only knows its own toggles; `now` stays
|
|
||||||
//! `None`, so the transport renders disabled and the seek bar is static.
|
|
||||||
|
|
||||||
use iced::widget::{button, column, container, row, slider, space};
|
use iced::widget::{button, column, container, row, slider, space};
|
||||||
use iced::{Alignment, Element, Fill, Length};
|
use iced::{Alignment, Element, Fill, Length};
|
||||||
|
|
||||||
use crate::app::Message;
|
use crate::app::Message;
|
||||||
|
use crate::player::{Msg, Player, Repeat, Status};
|
||||||
use crate::ui::icons::{Icon, icon, sized};
|
use crate::ui::icons::{Icon, icon, sized};
|
||||||
use crate::ui::line;
|
use crate::ui::line;
|
||||||
use crate::ui::theme::{self, Tokens, radius, size};
|
use crate::ui::theme::{self, Tokens, radius, size};
|
||||||
use crate::widgets::drawer::Panel;
|
use crate::widgets::drawer::Panel;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
fn send(msg: Msg) -> Message {
|
||||||
pub enum Repeat {
|
Message::Player(msg)
|
||||||
#[default]
|
|
||||||
Off,
|
|
||||||
All,
|
|
||||||
One,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Repeat {
|
pub fn view<'a>(t: &'static Tokens, p: &'a Player, liked: bool, drawer: Option<Panel>) -> Element<'a, Message> {
|
||||||
fn next(self) -> Self {
|
|
||||||
match self {
|
|
||||||
Repeat::Off => Repeat::All,
|
|
||||||
Repeat::All => Repeat::One,
|
|
||||||
Repeat::One => Repeat::Off,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct NowPlaying {
|
|
||||||
pub title: String,
|
|
||||||
pub artists: String,
|
|
||||||
pub position: f32,
|
|
||||||
pub duration: f32,
|
|
||||||
pub playing: bool,
|
|
||||||
pub liked: bool,
|
|
||||||
pub quality: String,
|
|
||||||
/// Placeholder cover hues until artwork loads.
|
|
||||||
pub hues: (f32, f32),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct PlayerUi {
|
|
||||||
pub now: Option<NowPlaying>,
|
|
||||||
pub shuffle: bool,
|
|
||||||
pub repeat: Repeat,
|
|
||||||
pub volume: f32,
|
|
||||||
pub muted: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for PlayerUi {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self { now: None, shuffle: false, repeat: Repeat::Off, volume: 0.7, muted: false }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
|
||||||
pub enum Action {
|
|
||||||
ToggleShuffle,
|
|
||||||
CycleRepeat,
|
|
||||||
SetVolume(f32),
|
|
||||||
ToggleMute,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PlayerUi {
|
|
||||||
pub fn apply(&mut self, action: Action) {
|
|
||||||
match action {
|
|
||||||
Action::ToggleShuffle => self.shuffle = !self.shuffle,
|
|
||||||
Action::CycleRepeat => self.repeat = self.repeat.next(),
|
|
||||||
Action::SetVolume(v) => {
|
|
||||||
self.volume = v.clamp(0.0, 1.0);
|
|
||||||
self.muted = self.volume == 0.0;
|
|
||||||
}
|
|
||||||
Action::ToggleMute => self.muted = !self.muted,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn view<'a>(t: &'static Tokens, p: &'a PlayerUi, drawer: Option<Panel>) -> Element<'a, Message> {
|
|
||||||
row![
|
row![
|
||||||
container(now_playing(t, p.now.as_ref())).width(Length::FillPortion(2)),
|
container(now_playing(t, p, liked)).width(Length::FillPortion(2)),
|
||||||
container(transport(t, p)).width(Length::FillPortion(3)).center_x(Fill),
|
container(transport(t, p)).width(Length::FillPortion(3)).center_x(Fill),
|
||||||
container(extras(t, p, drawer)).width(Length::FillPortion(2)).align_right(Fill),
|
container(extras(t, p, drawer)).width(Length::FillPortion(2)).align_right(Fill),
|
||||||
]
|
]
|
||||||
@@ -93,48 +27,54 @@ pub fn view<'a>(t: &'static Tokens, p: &'a PlayerUi, drawer: Option<Panel>) -> E
|
|||||||
.into()
|
.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn now_playing<'a>(t: &'static Tokens, now: Option<&'a NowPlaying>) -> Element<'a, Message> {
|
fn now_playing<'a>(t: &'static Tokens, p: &'a Player, liked: bool) -> Element<'a, Message> {
|
||||||
let cover = container(space())
|
let Some(track) = p.track() else {
|
||||||
.width(52)
|
let blank = container(space()).width(52).height(52).style(move |_| container::Style {
|
||||||
.height(52)
|
|
||||||
.style(move |th| match now {
|
|
||||||
Some(n) => theme::cover(n.hues.0, n.hues.1, radius::CONTROL)(th),
|
|
||||||
None => iced::widget::container::Style {
|
|
||||||
background: Some(t.raised.into()),
|
background: Some(t.raised.into()),
|
||||||
border: iced::Border { radius: radius::CONTROL.into(), ..Default::default() },
|
border: iced::Border { radius: radius::CONTROL.into(), ..Default::default() },
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
let (title, sub) = match &p.notice {
|
||||||
let Some(now) = now else {
|
Some(notice) => ("Can't play", notice.as_str()),
|
||||||
|
None => ("Nothing playing", "Pick a track to start"),
|
||||||
|
};
|
||||||
return row![
|
return row![
|
||||||
cover,
|
blank,
|
||||||
column![
|
column![
|
||||||
line("Nothing playing", theme::MEDIUM, size::BODY, t.fg),
|
line(title, theme::MEDIUM, size::BODY, t.fg),
|
||||||
line("Pick a track to start", theme::BODY, size::META, t.muted),
|
line(sub, theme::BODY, size::META, t.muted),
|
||||||
]
|
]
|
||||||
.spacing(2),
|
.spacing(2),
|
||||||
]
|
]
|
||||||
.spacing(12)
|
.spacing(12)
|
||||||
.align_y(Alignment::Center)
|
.align_y(Alignment::Center)
|
||||||
|
.clip(true)
|
||||||
.into();
|
.into();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let (h1, h2) = track.hues();
|
||||||
|
let cover = container(space()).width(52).height(52).style(theme::cover(h1, h2, radius::CONTROL));
|
||||||
|
|
||||||
|
// A problem with the previous track shows in place of the artist line until the next one loads.
|
||||||
|
let (sub, sub_colour) = match (&p.notice, p.status()) {
|
||||||
|
(Some(notice), Status::Loading | Status::Paused) => (notice.clone(), t.like),
|
||||||
|
_ => (track.artist_line(), t.muted),
|
||||||
|
};
|
||||||
|
|
||||||
row![
|
row![
|
||||||
cover,
|
cover,
|
||||||
column![
|
column![
|
||||||
line(&now.title, theme::MEDIUM, size::BODY, t.fg),
|
line(track.full_title(), theme::MEDIUM, size::BODY, t.fg),
|
||||||
line(&now.artists, theme::BODY, size::META, t.muted),
|
line(sub, theme::BODY, size::META, sub_colour),
|
||||||
]
|
]
|
||||||
.spacing(2)
|
.spacing(2)
|
||||||
.width(Length::Shrink),
|
.width(Length::Shrink),
|
||||||
button(icon(
|
// Liking from here arrives with collection editing; the heart shows the current state.
|
||||||
if now.liked { Icon::HeartFilled } else { Icon::Heart },
|
container(icon(
|
||||||
if now.liked { t.like } else { t.muted },
|
if liked { Icon::HeartFilled } else { Icon::Heart },
|
||||||
|
if liked { t.like } else { t.muted },
|
||||||
))
|
))
|
||||||
.padding(8)
|
.padding(8),
|
||||||
.style(theme::icon_button(None)),
|
|
||||||
button(icon(Icon::Dislike, t.muted)).padding(8).style(theme::icon_button(None)),
|
|
||||||
]
|
]
|
||||||
.spacing(12)
|
.spacing(12)
|
||||||
.align_y(Alignment::Center)
|
.align_y(Alignment::Center)
|
||||||
@@ -142,81 +82,83 @@ fn now_playing<'a>(t: &'static Tokens, now: Option<&'a NowPlaying>) -> Element<'
|
|||||||
.into()
|
.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn transport<'a>(t: &'static Tokens, p: &'a PlayerUi) -> Element<'a, Message> {
|
fn transport<'a>(t: &'static Tokens, p: &'a Player) -> Element<'a, Message> {
|
||||||
let has_track = p.now.is_some();
|
let has_track = p.track().is_some();
|
||||||
let playing = p.now.as_ref().is_some_and(|n| n.playing);
|
|
||||||
|
|
||||||
let toggle = |glyph: Icon, on: bool, action: Action| {
|
let toggle = |glyph: Icon, on: bool, msg: Msg| {
|
||||||
button(icon(glyph, if on { t.accent } else { t.muted }))
|
button(icon(glyph, if on { t.accent } else { t.muted }))
|
||||||
.padding(8)
|
.padding(8)
|
||||||
.style(theme::icon_button(on.then_some(t.accent)))
|
.style(theme::icon_button(on.then_some(t.accent)))
|
||||||
.on_press(Message::Player(action))
|
.on_press(send(msg))
|
||||||
};
|
};
|
||||||
let skip = |glyph: Icon| {
|
let skip = |glyph: Icon, msg: Msg| {
|
||||||
button(icon(glyph, if has_track { t.fg } else { t.muted.scale_alpha(0.45) }))
|
button(icon(glyph, if has_track { t.fg } else { t.muted.scale_alpha(0.45) }))
|
||||||
.padding(8)
|
.padding(8)
|
||||||
.style(theme::icon_button(None))
|
.style(theme::icon_button(None))
|
||||||
|
.on_press_maybe(has_track.then_some(send(msg)))
|
||||||
};
|
};
|
||||||
let disc_tint = if has_track { t.bg } else { t.muted };
|
|
||||||
let disc = button(
|
let (glyph, tint) = match p.status() {
|
||||||
container(sized(if playing { Icon::Pause } else { Icon::Play }, 18.0, disc_tint)).center(40),
|
_ if !has_track => (Icon::Play, t.muted),
|
||||||
)
|
Status::Playing => (Icon::Pause, t.bg),
|
||||||
|
Status::Loading => (Icon::Pause, t.bg.scale_alpha(0.5)),
|
||||||
|
Status::Paused | Status::Ended => (Icon::Play, t.bg),
|
||||||
|
};
|
||||||
|
let disc = button(container(sized(glyph, 18.0, tint)).center(40))
|
||||||
.width(40)
|
.width(40)
|
||||||
.height(40)
|
.height(40)
|
||||||
.padding(0)
|
.padding(0)
|
||||||
.style(theme::play_disc);
|
.style(theme::play_disc)
|
||||||
|
.on_press_maybe(has_track.then_some(send(Msg::Toggle)));
|
||||||
|
|
||||||
let ctrls = row![
|
let ctrls = row![
|
||||||
toggle(Icon::Shuffle, p.shuffle, Action::ToggleShuffle),
|
toggle(Icon::Shuffle, p.shuffle(), Msg::ToggleShuffle),
|
||||||
skip(Icon::Previous),
|
skip(Icon::Previous, Msg::Previous),
|
||||||
disc,
|
disc,
|
||||||
skip(Icon::Next),
|
skip(Icon::Next, Msg::Next),
|
||||||
toggle(
|
toggle(
|
||||||
if p.repeat == Repeat::One { Icon::RepeatOne } else { Icon::Repeat },
|
if p.repeat == Repeat::One { Icon::RepeatOne } else { Icon::Repeat },
|
||||||
p.repeat != Repeat::Off,
|
p.repeat != Repeat::Off,
|
||||||
Action::CycleRepeat,
|
Msg::CycleRepeat,
|
||||||
),
|
),
|
||||||
]
|
]
|
||||||
.spacing(8)
|
.spacing(8)
|
||||||
.align_y(Alignment::Center);
|
.align_y(Alignment::Center);
|
||||||
|
|
||||||
let (pos, dur) = p.now.as_ref().map_or((0.0, 0.0), |n| (n.position, n.duration));
|
let duration = p.duration().as_secs_f32();
|
||||||
let fraction = if dur > 0.0 { (pos / dur).clamp(0.0, 1.0) } else { 0.0 };
|
let position = p.position().as_secs_f32().min(duration);
|
||||||
|
let bar: Element<'a, Message> = if has_track && duration > 0.0 {
|
||||||
|
slider(0.0..=duration, position, |v| send(Msg::SeekPreview(v)))
|
||||||
|
.on_release(send(Msg::SeekCommit))
|
||||||
|
.step(0.5_f32)
|
||||||
|
.width(Fill)
|
||||||
|
.style(theme::seek_bar)
|
||||||
|
.into()
|
||||||
|
} else {
|
||||||
|
container(space())
|
||||||
|
.width(Fill)
|
||||||
|
.height(4)
|
||||||
|
.style(move |_| container::Style {
|
||||||
|
background: Some(t.raised.into()),
|
||||||
|
border: iced::Border { radius: 2.0.into(), ..Default::default() },
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.into()
|
||||||
|
};
|
||||||
|
|
||||||
let seek = row![
|
let seek = row![
|
||||||
container(line(clock(pos), theme::BODY, 12.0, t.muted)).width(42).align_right(42),
|
container(line(clock(position), theme::BODY, 12.0, t.muted)).width(42).align_right(42),
|
||||||
static_bar(t, fraction),
|
bar,
|
||||||
container(line(clock(dur), theme::BODY, 12.0, t.muted)).width(42),
|
container(line(clock(duration), theme::BODY, 12.0, t.muted)).width(42),
|
||||||
]
|
]
|
||||||
.spacing(10)
|
.spacing(10)
|
||||||
.align_y(Alignment::Center)
|
.align_y(Alignment::Center)
|
||||||
.width(Fill);
|
.width(Fill);
|
||||||
|
|
||||||
column![ctrls, seek]
|
column![ctrls, seek].spacing(4).align_x(Alignment::Center).max_width(560).into()
|
||||||
.spacing(4)
|
|
||||||
.align_x(Alignment::Center)
|
|
||||||
.max_width(560)
|
|
||||||
.into()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Seek bar while there is nothing to seek; becomes a slider with the engine.
|
fn extras<'a>(t: &'static Tokens, p: &'a Player, drawer: Option<Panel>) -> Element<'a, Message> {
|
||||||
fn static_bar<'a>(t: &'static Tokens, fraction: f32) -> Element<'a, Message> {
|
|
||||||
let part = |portion: f32, colour: iced::Color| {
|
|
||||||
container(space())
|
|
||||||
.width(Length::FillPortion((portion * 1000.0).round().max(0.0) as u16))
|
|
||||||
.height(4)
|
|
||||||
.style(move |_| iced::widget::container::Style {
|
|
||||||
background: Some(colour.into()),
|
|
||||||
border: iced::Border { radius: 2.0.into(), ..Default::default() },
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
};
|
|
||||||
if fraction <= 0.0 {
|
|
||||||
return part(1.0, t.raised).width(Fill).into();
|
|
||||||
}
|
|
||||||
row![part(fraction, t.accent), part(1.0 - fraction, t.raised)].width(Fill).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn extras<'a>(t: &'static Tokens, p: &'a PlayerUi, drawer: Option<Panel>) -> Element<'a, Message> {
|
|
||||||
let panel_button = |glyph: Icon, panel: Panel| {
|
let panel_button = |glyph: Icon, panel: Panel| {
|
||||||
let on = drawer == Some(panel);
|
let on = drawer == Some(panel);
|
||||||
button(icon(glyph, if on { t.accent } else { t.muted }))
|
button(icon(glyph, if on { t.accent } else { t.muted }))
|
||||||
@@ -226,11 +168,10 @@ fn extras<'a>(t: &'static Tokens, p: &'a PlayerUi, drawer: Option<Panel>) -> Ele
|
|||||||
};
|
};
|
||||||
|
|
||||||
let mut items = row![].spacing(4).align_y(Alignment::Center);
|
let mut items = row![].spacing(4).align_y(Alignment::Center);
|
||||||
if let Some(now) = &p.now {
|
if let Some(stream) = p.stream() {
|
||||||
|
let label = if stream.preview { "Preview".to_owned() } else { stream.label() };
|
||||||
items = items.push(
|
items = items.push(
|
||||||
container(line(&now.quality, theme::MEDIUM, 11.5, t.muted))
|
container(line(label, theme::MEDIUM, 11.5, t.muted)).padding([2, 6]).style(theme::badge),
|
||||||
.padding([2, 6])
|
|
||||||
.style(theme::badge),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -242,10 +183,10 @@ fn extras<'a>(t: &'static Tokens, p: &'a PlayerUi, drawer: Option<Panel>) -> Ele
|
|||||||
button(icon(if p.muted { Icon::Muted } else { Icon::Volume }, t.muted))
|
button(icon(if p.muted { Icon::Muted } else { Icon::Volume }, t.muted))
|
||||||
.padding(8)
|
.padding(8)
|
||||||
.style(theme::icon_button(None))
|
.style(theme::icon_button(None))
|
||||||
.on_press(Message::Player(Action::ToggleMute)),
|
.on_press(send(Msg::ToggleMute)),
|
||||||
)
|
)
|
||||||
.push(
|
.push(
|
||||||
slider(0.0..=1.0, volume, |v| Message::Player(Action::SetVolume(v)))
|
slider(0.0..=1.0, volume, |v| send(Msg::SetVolume(v)))
|
||||||
.step(0.01_f32)
|
.step(0.01_f32)
|
||||||
.width(96)
|
.width(96)
|
||||||
.style(theme::volume_bar),
|
.style(theme::volume_bar),
|
||||||
@@ -262,7 +203,7 @@ pub fn clock(seconds: f32) -> String {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::clock;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn clock_formats() {
|
fn clock_formats() {
|
||||||
@@ -272,24 +213,4 @@ mod tests {
|
|||||||
assert_eq!(clock(3725.0), "1:02:05");
|
assert_eq!(clock(3725.0), "1:02:05");
|
||||||
assert_eq!(clock(-3.0), "0:00");
|
assert_eq!(clock(-3.0), "0:00");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn repeat_cycles_off_all_one() {
|
|
||||||
let mut p = PlayerUi::default();
|
|
||||||
p.apply(Action::CycleRepeat);
|
|
||||||
assert_eq!(p.repeat, Repeat::All);
|
|
||||||
p.apply(Action::CycleRepeat);
|
|
||||||
assert_eq!(p.repeat, Repeat::One);
|
|
||||||
p.apply(Action::CycleRepeat);
|
|
||||||
assert_eq!(p.repeat, Repeat::Off);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn volume_is_clamped_and_zero_means_muted() {
|
|
||||||
let mut p = PlayerUi::default();
|
|
||||||
p.apply(Action::SetVolume(1.4));
|
|
||||||
assert_eq!(p.volume, 1.0);
|
|
||||||
p.apply(Action::SetVolume(0.0));
|
|
||||||
assert!(p.muted);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
//! One row in a track list: number (or a playing marker), cover, title and
|
||||||
|
//! artists, album, like state, duration. Clicking anywhere plays it.
|
||||||
|
|
||||||
|
use iced::widget::{button, column, container, row, space};
|
||||||
|
use iced::{Alignment, Element, Fill, Length};
|
||||||
|
use ym_api::Track;
|
||||||
|
|
||||||
|
use crate::ui::icons::{Icon, icon, sized};
|
||||||
|
use crate::ui::line;
|
||||||
|
use crate::ui::theme::{self, Tokens, radius, size};
|
||||||
|
use crate::widgets::player_bar::clock;
|
||||||
|
|
||||||
|
pub const HEIGHT: f32 = 52.0;
|
||||||
|
|
||||||
|
/// Builds an owned (`'static`) row so lists can sit inside `lazy`.
|
||||||
|
pub fn view<M: Clone + 'static>(
|
||||||
|
t: &'static Tokens,
|
||||||
|
index: usize,
|
||||||
|
track: &Track,
|
||||||
|
playing: bool,
|
||||||
|
liked: bool,
|
||||||
|
on_press: M,
|
||||||
|
) -> Element<'static, M> {
|
||||||
|
let (h1, h2) = track.hues();
|
||||||
|
let accent = |c| if playing { t.accent } else { c };
|
||||||
|
|
||||||
|
let number: Element<'static, M> = if playing {
|
||||||
|
sized(Icon::Wave, 16.0, t.accent).into()
|
||||||
|
} else {
|
||||||
|
line((index + 1).to_string(), theme::BODY, size::META, t.muted).into()
|
||||||
|
};
|
||||||
|
|
||||||
|
let unavailable = !track.available;
|
||||||
|
let title_colour = if unavailable { t.muted } else { accent(t.fg) };
|
||||||
|
|
||||||
|
let content = row![
|
||||||
|
container(number).width(36).center_x(36),
|
||||||
|
container(space()).width(40).height(40).style(theme::cover(h1, h2, radius::SMALL_COVER)),
|
||||||
|
column![
|
||||||
|
line(track.full_title(), theme::MEDIUM, size::BODY, title_colour),
|
||||||
|
line(track.artist_line(), theme::BODY, size::META, t.muted),
|
||||||
|
]
|
||||||
|
.spacing(1)
|
||||||
|
.width(Length::FillPortion(22))
|
||||||
|
.clip(true),
|
||||||
|
container(line(
|
||||||
|
track.album.as_ref().map(|a| a.title.clone()).unwrap_or_default(),
|
||||||
|
theme::BODY,
|
||||||
|
size::META,
|
||||||
|
t.muted,
|
||||||
|
))
|
||||||
|
.width(Length::FillPortion(14))
|
||||||
|
.clip(true),
|
||||||
|
container(icon(
|
||||||
|
if liked { Icon::HeartFilled } else { Icon::Heart },
|
||||||
|
if liked { t.like } else { t.muted.scale_alpha(0.0) },
|
||||||
|
))
|
||||||
|
.width(34)
|
||||||
|
.center_x(34),
|
||||||
|
container(line(clock(track.duration.as_secs_f32()), theme::BODY, size::META, t.muted))
|
||||||
|
.width(52)
|
||||||
|
.align_right(52),
|
||||||
|
]
|
||||||
|
.spacing(12)
|
||||||
|
.align_y(Alignment::Center)
|
||||||
|
.height(HEIGHT);
|
||||||
|
|
||||||
|
button(content)
|
||||||
|
.width(Fill)
|
||||||
|
.padding([0, 10])
|
||||||
|
.style(theme::nav_item(false))
|
||||||
|
.on_press_maybe((!unavailable).then_some(on_press))
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Column headings above a track list, aligned with [`view`].
|
||||||
|
pub fn header<M: 'static>(t: &'static Tokens) -> Element<'static, M> {
|
||||||
|
let label = |s: &'static str| line(s, theme::BODY, size::SMALL, t.muted);
|
||||||
|
column![
|
||||||
|
row![
|
||||||
|
container(label("#")).width(36).center_x(36),
|
||||||
|
space().width(40),
|
||||||
|
container(label("Title")).width(Length::FillPortion(22)),
|
||||||
|
container(label("Album")).width(Length::FillPortion(14)),
|
||||||
|
space().width(34),
|
||||||
|
container(icon(Icon::Clock, t.muted)).width(52).align_right(52),
|
||||||
|
]
|
||||||
|
.spacing(12)
|
||||||
|
.align_y(Alignment::Center)
|
||||||
|
.padding([0, 10]),
|
||||||
|
container(space()).width(Fill).height(1).style(theme::divider),
|
||||||
|
]
|
||||||
|
.spacing(8)
|
||||||
|
.into()
|
||||||
|
}
|
||||||
@@ -10,9 +10,9 @@ publish.workspace = true
|
|||||||
yamuse = "0.3.2"
|
yamuse = "0.3.2"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
thiserror = "2"
|
thiserror = "2"
|
||||||
|
serde_json = "1"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
serde_json = "1"
|
|
||||||
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
use crate::Result;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use crate::auth::Credentials;
|
use crate::auth::Credentials;
|
||||||
|
use crate::models::{Stream, Track, best_variant};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
/// The signed-in user as the UI needs them.
|
/// The signed-in user as the UI needs them.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@@ -55,7 +58,7 @@ impl YmClient {
|
|||||||
let inner = yamuse::Client::builder().token(&credentials.access_token).build()?;
|
let inner = yamuse::Client::builder().token(&credentials.access_token).build()?;
|
||||||
let status = inner.refresh_account().await?;
|
let status = inner.refresh_account().await?;
|
||||||
let account = Account::from_status(status)
|
let account = Account::from_status(status)
|
||||||
.ok_or_else(|| crate::Error::Unauthorized("account status has no user".into()))?;
|
.ok_or_else(|| Error::Unauthorized("account status has no user".into()))?;
|
||||||
Ok((Self { inner }, account))
|
Ok((Self { inner }, account))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,11 +67,62 @@ impl YmClient {
|
|||||||
Ok(Self { inner: yamuse::Client::anonymous()? })
|
Ok(Self { inner: yamuse::Client::anonymous()? })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The user's liked tracks, newest like first, with full metadata.
|
||||||
|
pub async fn liked_tracks(&self) -> Result<Vec<Track>> {
|
||||||
|
let list = self.inner.liked_tracks(None).await?;
|
||||||
|
let ids: Vec<String> = list
|
||||||
|
.tracks
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|short| {
|
||||||
|
let id = match short.id? {
|
||||||
|
yamuse::models::Id::Number(n) => n.to_string(),
|
||||||
|
yamuse::models::Id::Text(s) => s,
|
||||||
|
};
|
||||||
|
Some(match short.album_id {
|
||||||
|
Some(album) if !id.contains(':') => format!("{id}:{album}"),
|
||||||
|
_ => id,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
self.tracks(ids).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Full metadata for `ids` (`"trackId"` or `"trackId:albumId"`), in the given order.
|
||||||
|
pub async fn tracks(&self, ids: Vec<String>) -> Result<Vec<Track>> {
|
||||||
|
if ids.is_empty() {
|
||||||
|
return Ok(Vec::new());
|
||||||
|
}
|
||||||
|
let tracks = self.inner.tracks(&ids).await?;
|
||||||
|
Ok(tracks.into_iter().filter_map(Track::from_yamuse).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves a signed, short-lived audio URL for a track.
|
||||||
|
pub async fn stream(&self, track_id: &str) -> Result<Stream> {
|
||||||
|
let variants = self.inner.track_download_info(track_id).await?;
|
||||||
|
let variant = best_variant(&variants)
|
||||||
|
.ok_or_else(|| Error::Api(format!("no playable variant for track {track_id}")))?;
|
||||||
|
let url = variant.direct_link(self.inner.transport()).await?;
|
||||||
|
Ok(Stream {
|
||||||
|
url,
|
||||||
|
codec: variant.codec.clone().unwrap_or_default(),
|
||||||
|
bitrate_kbps: variant.bitrate_in_kbps.unwrap_or(0).max(0) as u32,
|
||||||
|
preview: variant.preview.unwrap_or(false),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Downloads a whole stream into memory (a 320 kbps track is about 10 MB).
|
||||||
|
pub async fn fetch(&self, stream: &Stream) -> Result<Arc<[u8]>> {
|
||||||
|
let bytes = yamuse::download::Downloader::new(self.inner.transport(), [stream.url.clone()])
|
||||||
|
.to_bytes()
|
||||||
|
.await?;
|
||||||
|
Ok(bytes.into())
|
||||||
|
}
|
||||||
|
|
||||||
/// Re-reads the account, e.g. after a subscription may have changed.
|
/// Re-reads the account, e.g. after a subscription may have changed.
|
||||||
pub async fn account(&self) -> Result<Account> {
|
pub async fn account(&self) -> Result<Account> {
|
||||||
let status = self.inner.refresh_account().await?;
|
let status = self.inner.refresh_account().await?;
|
||||||
Account::from_status(status)
|
Account::from_status(status)
|
||||||
.ok_or_else(|| crate::Error::Unauthorized("account status has no user".into()))
|
.ok_or_else(|| Error::Unauthorized("account status has no user".into()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
pub mod auth;
|
pub mod auth;
|
||||||
mod client;
|
mod client;
|
||||||
mod error;
|
mod error;
|
||||||
|
mod models;
|
||||||
|
|
||||||
pub use client::{Account, YmClient};
|
pub use client::{Account, YmClient};
|
||||||
|
pub use models::{AlbumRef, ArtistRef, Stream, Track};
|
||||||
pub use error::{Error, Result};
|
pub use error::{Error, Result};
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
//! The app-facing shapes of API objects. Converted from `yamuse` models,
|
||||||
|
//! keeping only what the UI uses and resolving every `Option` once, here.
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct ArtistRef {
|
||||||
|
pub id: Option<i64>,
|
||||||
|
pub name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct AlbumRef {
|
||||||
|
pub id: i64,
|
||||||
|
pub title: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Track {
|
||||||
|
/// Numeric track id as a string; user-uploaded tracks use non-numeric ids.
|
||||||
|
pub id: String,
|
||||||
|
pub title: String,
|
||||||
|
/// "Remastered 2011", "Live" and the like.
|
||||||
|
pub version: Option<String>,
|
||||||
|
pub artists: Vec<ArtistRef>,
|
||||||
|
pub album: Option<AlbumRef>,
|
||||||
|
pub duration: Duration,
|
||||||
|
/// `%%`-templated image uri; see [`Track::cover_url`].
|
||||||
|
cover_uri: Option<String>,
|
||||||
|
/// False for tracks removed from the catalogue or blocked in the region.
|
||||||
|
pub available: bool,
|
||||||
|
pub explicit: bool,
|
||||||
|
pub lyrics_available: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Track {
|
||||||
|
pub(crate) fn from_yamuse(t: yamuse::models::Track) -> Option<Self> {
|
||||||
|
let id = match t.id? {
|
||||||
|
yamuse::models::Id::Number(n) => n.to_string(),
|
||||||
|
yamuse::models::Id::Text(s) if !s.is_empty() => s,
|
||||||
|
yamuse::models::Id::Text(_) => return None,
|
||||||
|
};
|
||||||
|
let album = t.albums.into_iter().find_map(|a| {
|
||||||
|
Some(AlbumRef { id: a.id?, title: a.title.unwrap_or_default() })
|
||||||
|
});
|
||||||
|
Some(Self {
|
||||||
|
id,
|
||||||
|
title: t.title.unwrap_or_else(|| "Untitled".into()),
|
||||||
|
version: t.version.filter(|v| !v.trim().is_empty()),
|
||||||
|
artists: t
|
||||||
|
.artists
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|a| {
|
||||||
|
Some(ArtistRef { id: a.id.and_then(|i| i.as_number()), name: a.name? })
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
album,
|
||||||
|
duration: Duration::from_millis(t.duration_ms.unwrap_or(0).max(0) as u64),
|
||||||
|
cover_uri: t.cover_uri.or(t.og_image),
|
||||||
|
available: t.available.unwrap_or(true),
|
||||||
|
explicit: t.explicit.unwrap_or(false)
|
||||||
|
|| t.content_warning.as_deref() == Some("explicit"),
|
||||||
|
lyrics_available: t.lyrics_available.unwrap_or(false),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes a track from the API's JSON, e.g. a recorded fixture.
|
||||||
|
pub fn from_json(json: &str) -> crate::Result<Self> {
|
||||||
|
let raw = serde_json::from_str(json).map_err(|e| crate::Error::Api(e.to_string()))?;
|
||||||
|
Self::from_yamuse(raw).ok_or_else(|| crate::Error::Api("track has no id".into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Artist A, Artist B", or "Unknown artist".
|
||||||
|
pub fn artist_line(&self) -> String {
|
||||||
|
if self.artists.is_empty() {
|
||||||
|
return "Unknown artist".into();
|
||||||
|
}
|
||||||
|
self.artists.iter().map(|a| a.name.as_str()).collect::<Vec<_>>().join(", ")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Title with its version: "Song (Live)".
|
||||||
|
pub fn full_title(&self) -> String {
|
||||||
|
match &self.version {
|
||||||
|
Some(v) => format!("{} ({v})", self.title),
|
||||||
|
None => self.title.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Absolute cover URL at `size`×`size` pixels.
|
||||||
|
pub fn cover_url(&self, size: u32) -> Option<String> {
|
||||||
|
let uri = self.cover_uri.as_deref()?;
|
||||||
|
Some(yamuse::models::normalize_image_url(uri, &format!("{size}x{size}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Two stable hues for placeholder art, derived from the album (or track) id.
|
||||||
|
pub fn hues(&self) -> (f32, f32) {
|
||||||
|
let seed = self.album.as_ref().map_or_else(
|
||||||
|
|| self.id.bytes().fold(7u64, |h, b| h.wrapping_mul(31).wrapping_add(u64::from(b))),
|
||||||
|
|a| a.id as u64,
|
||||||
|
);
|
||||||
|
((seed.wrapping_mul(47) % 360) as f32, (seed.wrapping_mul(131).wrapping_add(90) % 360) as f32)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a track's audio comes from.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Stream {
|
||||||
|
pub url: String,
|
||||||
|
/// "mp3" or "aac".
|
||||||
|
pub codec: String,
|
||||||
|
pub bitrate_kbps: u32,
|
||||||
|
/// True when only a 30-second preview is available (no Plus).
|
||||||
|
pub preview: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Stream {
|
||||||
|
/// "MP3 320", shown in the player bar.
|
||||||
|
pub fn label(&self) -> String {
|
||||||
|
format!("{} {}", self.codec.to_ascii_uppercase(), self.bitrate_kbps)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Picks the variant to play: full tracks over previews, MP3 over AAC (MP3 seeks
|
||||||
|
/// reliably), then the highest bitrate.
|
||||||
|
pub(crate) fn best_variant(
|
||||||
|
variants: &[yamuse::models::DownloadInfo],
|
||||||
|
) -> Option<&yamuse::models::DownloadInfo> {
|
||||||
|
variants
|
||||||
|
.iter()
|
||||||
|
.filter(|v| v.download_info_url.is_some())
|
||||||
|
.filter(|v| matches!(v.codec.as_deref(), Some("mp3" | "aac")))
|
||||||
|
.max_by_key(|v| {
|
||||||
|
(
|
||||||
|
!v.preview.unwrap_or(false),
|
||||||
|
v.codec.as_deref() == Some("mp3"),
|
||||||
|
v.bitrate_in_kbps.unwrap_or(0),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn track(json: &str) -> Track {
|
||||||
|
Track::from_yamuse(serde_json::from_str(json).unwrap()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn track_converts_with_artists_album_and_cover() {
|
||||||
|
let t = track(
|
||||||
|
r#"{"id":"12345","title":"Звезда по имени Солнце","durationMs":225000,
|
||||||
|
"artists":[{"id":1,"name":"Кино"}],
|
||||||
|
"albums":[{"id":77,"title":"Звезда по имени Солнце"}],
|
||||||
|
"coverUri":"avatars.yandex.net/get-music-content/x/%%","lyricsAvailable":true}"#,
|
||||||
|
);
|
||||||
|
assert_eq!(t.id, "12345");
|
||||||
|
assert_eq!(t.artist_line(), "Кино");
|
||||||
|
assert_eq!(t.album.as_ref().unwrap().id, 77);
|
||||||
|
assert_eq!(t.duration, Duration::from_secs(225));
|
||||||
|
assert_eq!(
|
||||||
|
t.cover_url(200).as_deref(),
|
||||||
|
Some("https://avatars.yandex.net/get-music-content/x/200x200")
|
||||||
|
);
|
||||||
|
assert!(t.available && t.lyrics_available && !t.explicit);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numeric_ids_and_versions() {
|
||||||
|
let t = track(r#"{"id":42,"title":"Song","version":"Live","artists":[]}"#);
|
||||||
|
assert_eq!(t.id, "42");
|
||||||
|
assert_eq!(t.full_title(), "Song (Live)");
|
||||||
|
assert_eq!(t.artist_line(), "Unknown artist");
|
||||||
|
assert!(Track::from_yamuse(serde_json::from_str(r#"{"title":"no id"}"#).unwrap()).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hues_are_stable_and_in_range() {
|
||||||
|
let a = track(r#"{"id":1,"albums":[{"id":5}]}"#);
|
||||||
|
let b = track(r#"{"id":2,"albums":[{"id":5}]}"#);
|
||||||
|
assert_eq!(a.hues(), b.hues(), "same album, same art");
|
||||||
|
let (h1, h2) = a.hues();
|
||||||
|
assert!((0.0..360.0).contains(&h1) && (0.0..360.0).contains(&h2));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn best_variant_prefers_full_mp3_at_top_bitrate() {
|
||||||
|
let v: Vec<yamuse::models::DownloadInfo> = serde_json::from_str(
|
||||||
|
r#"[{"codec":"aac","bitrateInKbps":256,"downloadInfoUrl":"a"},
|
||||||
|
{"codec":"mp3","bitrateInKbps":192,"downloadInfoUrl":"b"},
|
||||||
|
{"codec":"mp3","bitrateInKbps":320,"downloadInfoUrl":"c"},
|
||||||
|
{"codec":"mp3","bitrateInKbps":320,"downloadInfoUrl":"p","preview":true},
|
||||||
|
{"codec":"flac","bitrateInKbps":900,"downloadInfoUrl":"f"}]"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(best_variant(&v).unwrap().download_info_url.as_deref(), Some("c"));
|
||||||
|
let previews: Vec<yamuse::models::DownloadInfo> = serde_json::from_str(
|
||||||
|
r#"[{"codec":"mp3","bitrateInKbps":128,"downloadInfoUrl":"p","preview":true}]"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(best_variant(&previews).unwrap().preview.unwrap());
|
||||||
|
assert!(best_variant(&[]).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user