Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.
Kotlin alternativeandroidandroid-applicationclientglassmorphisminnertubelibrespotliquid-glassspotifyspotify-connectspotifyapiyoutube-musicyoutube-playerytdlnis
A playlist's local files play in its queue, between the streamed tracks
Leloniocc9b110ec8f3
diff --git a/app/src/main/java/dev/lelonio/square/data/Catalog.kt b/app/src/main/java/dev/lelonio/square/data/Catalog.ktindex 23bbad4..734201a 100644--- a/app/src/main/java/dev/lelonio/square/data/Catalog.kt+++ b/app/src/main/java/dev/lelonio/square/data/Catalog.kt@@ -60,6 +60,15 @@ data class CatalogTrack(* and sorting by it then leaves the list in playlist order.*/val addedAt: String? = null,+ /**+ * The file on this phone that plays for this entry, where there is one.+ *+ * Set for the phone's own music, and for a local file a Spotify playlist+ * names once a file here has been matched to it (see+ * LocalLibrary.match). Null on a `spotify:local:` entry means this phone+ * has nothing to play for it.+ */+ val localFile: String? = null,)/**diff --git a/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt b/app/src/main/java/dev/lelonio/square/data/LocalLibrary.ktindex 8d952d9..b0eecb9 100644--- a/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt+++ b/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt@@ -146,6 +146,10 @@ object LocalLibrary {MediaStore.Audio.Media.ALBUM_ID,MediaStore.Audio.Media.DURATION,MediaStore.Audio.Media.DATE_ADDED,+ // The path, for Spotify's engine, which opens local files itself.+ // Readable with the audio permission on every version this app+ // runs on.+ @Suppress("DEPRECATION") MediaStore.Audio.Media.DATA,)runCatching {@@ -165,6 +169,8 @@ object LocalLibrary {val albumId = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)val duration = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)val added = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATE_ADDED)+ @Suppress("DEPRECATION")+ val data = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)buildList {while (cursor.moveToNext()) {@@ -185,6 +191,7 @@ object LocalLibrary {// index counts in seconds; everything else in// this app reads an ISO-8601 stamp.addedAt = isoStamp(cursor.getLong(added)),+ localFile = cursor.getString(data),),)}diff --git a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.ktindex 4d179a9..6f97a8f 100644--- a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt+++ b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt@@ -203,6 +203,13 @@ object NativeBridge {*/fun setSleepTimer(value: Long) = nativeSetSleepTimer(value)+ /**+ * Which file on this phone each local entry of a Spotify playlist is, as a+ * JSON object of `spotify:local:` URIs to paths. The engine plays those+ * entries from the files; see MainViewModel.withDeviceFiles.+ */+ fun setLocalFiles(json: String) = nativeSetLocalFiles(json)+/*** How long a track the listener changes away from dissolves into the one* they asked for, in milliseconds. Zero cuts, as it always did.@@ -498,6 +505,7 @@ object NativeBridge {private external fun nativeSetTrimSilence(enabled: Boolean)private external fun nativeSetHoldEnd(enabled: Boolean)private external fun nativeSetSleepTimer(value: Long)+ private external fun nativeSetLocalFiles(json: String)private external fun nativeSetSkipFade(ms: Int)private external fun nativeSetLanguage(language: String, rebuild: Int)diff --git a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt b/app/src/main/java/dev/lelonio/square/ui/MainActivity.ktindex 8dc46bd..fc08f75 100644--- a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt+++ b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt@@ -330,16 +330,19 @@ class MainActivity : ComponentActivity() {} else {val here = (application as dev.lelonio.square.SquareApplication).downloads.files.value- tracks.filter { it.uri.startsWith("local:") || it.uri in here }+ tracks.filter { it.uri.startsWith("local:") || it.localFile != null || it.uri in here }}// One player plays a queue: Spotify's engine or the phone's own files,- // not both. A Spotify playlist with local files in it plays whichever- // kind was tapped, and the other kind waits for its own tap; an entry- // with no file on this phone plays as neither.+ // not both. A Spotify playlist's local entries are Spotify's to play —+ // the engine opens the matched file between the streamed tracks — and+ // an entry with no file on this phone is left out, as the engine could+ // only skip it. The phone's own shelf plays on the files' own player.val local = dev.lelonio.square.data.LocalLibraryval tappedLocal = tracks.getOrNull(index)?.uri?.let(local::isLocal) == true- val playable = reachable.filter { !local.isSpotifyLocal(it.uri) && local.isLocal(it.uri) == tappedLocal }+ val playable = reachable.filter {+ local.isLocal(it.uri) == tappedLocal && (!local.isSpotifyLocal(it.uri) || it.localFile != null)+ }if (playable.isEmpty()) return// The song that was tapped keeps its place, wherever the filtering leftdiff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.ktindex 4c332e0..6e91155 100644--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt@@ -3436,22 +3436,40 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {private var deviceFiles: List<CatalogTrack> = emptyList()/**- * A playlist's local entries, swapped for the files on this phone they- * describe. The playlist's own name for each is kept, and the file's URI- * is what plays; an entry with no file here stays as it came, and the page- * shows it greyed out, as Spotify's own apps do.+ * A playlist's local entries, each given the file on this phone it+ * describes. The entry keeps its `spotify:local:` URI, so it stays in the+ * playlist's queue and Spotify's engine plays it from the file, between the+ * streamed tracks; an entry with no file here is left without one, and the+ * page shows it greyed out, as Spotify's own apps do.*/private fun withDeviceFiles(tracks: List<CatalogTrack>): List<CatalogTrack> {if (tracks.none { LocalLibrary.isSpotifyLocal(it.uri) }) return tracksval files = deviceFiles- return tracks.map { track ->+ val matched = tracks.map { track ->if (!LocalLibrary.isSpotifyLocal(track.uri)) return@map track- LocalLibrary.match(track, files)- ?.let { file -> track.copy(uri = file.uri, artworkUrl = track.artworkUrl ?: file.artworkUrl) }- ?: track+ val file = LocalLibrary.match(track, files)+ track.copy(+ localFile = file?.localFile,+ artworkUrl = track.artworkUrl ?: file?.artworkUrl,+ )+ }+ // Told to the engine as they are found, and kept: a queue started on+ // one page plays on while another is open.+ matched.forEach { track ->+ val path = track.localFile ?: return@forEach+ if (LocalLibrary.isSpotifyLocal(track.uri)) engineLocalFiles[track.uri] = path+ }+ runCatching {+ dev.lelonio.square.nativecore.NativeBridge.setLocalFiles(+ org.json.JSONObject(engineLocalFiles.toMap()).toString(),+ )}+ return matched}+ /** Every local entry matched so far, as the engine is told them. */+ private val engineLocalFiles = java.util.concurrent.ConcurrentHashMap<String, String>()+fun openPlaylist(playlist: CatalogPlaylist) {// Read again on every page: a file copied to the phone since the last// one should be found the next time its playlist is opened.diff --git a/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt b/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.ktindex fb48362..bc7f77b 100644--- a/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt@@ -937,7 +937,8 @@ fun PlaylistScreen(// else — they were never coming over the network.// A local file the playlist names and this phone// does not have is greyed out, as on Spotify.- unavailable = dev.lelonio.square.data.LocalLibrary.isSpotifyLocal(track.uri) ||+ unavailable = (dev.lelonio.square.data.LocalLibrary.isSpotifyLocal(track.uri) &&+ track.localFile == null) ||offline &&!track.uri.startsWith("local:") &&trackDownload(track) !=diff --git a/native/Cargo.lock b/native/Cargo.lockindex 4659dda..06e06dd 100644--- a/native/Cargo.lock+++ b/native/Cargo.lock@@ -2376,8 +2376,10 @@ dependencies = ["lazy_static","symphonia-bundle-flac","symphonia-bundle-mp3",+ "symphonia-codec-aac","symphonia-codec-vorbis","symphonia-core",+ "symphonia-format-isomp4","symphonia-format-ogg","symphonia-metadata",]@@ -2406,6 +2408,17 @@ dependencies = ["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-codec-vorbis"version = "0.5.5"@@ -2430,6 +2443,19 @@ dependencies = ["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-format-ogg"version = "0.5.5"diff --git a/native/src/engine.rs b/native/src/engine.rsindex 9537a19..5114a31 100644--- a/native/src/engine.rs+++ b/native/src/engine.rs@@ -1060,6 +1060,20 @@ pub fn set_sleep_timer(value: i64) -> EngineResult<()> {Ok(())}+/// Which file on the phone each local entry of a playlist is, as the app+/// matched it: a JSON object of `spotify:local:` URIs to file paths. Replaces+/// what was set before; see librespot-playback's local_file.+pub fn set_local_files(json: &str) -> EngineResult<()> {+ let files: std::collections::HashMap<String, String> =+ serde_json::from_str(json).map_err(|e| format!("local files: {e}"))?;+ let files = files+ .into_iter()+ .filter_map(|(uri, path)| Some((SpotifyUri::from_uri(&uri).ok()?, std::path::PathBuf::from(path))))+ .collect();+ librespot_playback::local_file::set_app_files(files);+ Ok(())+}+/// How long a track the listener changes away from dissolves into the one they/// asked for; see `PlayerConfig::skip_fade_ms`. Kept in the recipe, so a/// rebuilt player still fades.diff --git a/native/src/ffi.rs b/native/src/ffi.rsindex eba3f97..c520889 100644--- a/native/src/ffi.rs+++ b/native/src/ffi.rs@@ -575,6 +575,19 @@ pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSetguard(&mut env, "SetHoldEnd", || engine::set_hold_end(enabled != 0));}+#[no_mangle]+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSetLocalFiles(+ mut env: JNIEnv,+ _class: JClass,+ json: JString,+) {+ let json = match env.get_string(&json) {+ Ok(value) => String::from(value),+ Err(_) => return,+ };+ guard(&mut env, "SetLocalFiles", || engine::set_local_files(&json));+}+#[no_mangle]pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSetSleepTimer(mut env: JNIEnv,diff --git a/native/vendor/librespot-playback/Cargo.toml b/native/vendor/librespot-playback/Cargo.tomlindex 4de3abe..f24bd49 100644--- a/native/vendor/librespot-playback/Cargo.toml+++ b/native/vendor/librespot-playback/Cargo.toml@@ -169,6 +169,9 @@ features = ["ogg","vorbis","flac",+ # LOCAL PATCH: local files on a phone are as often AAC in MP4 as MP3.+ "aac",+ "isomp4",]default-features = falsediff --git a/native/vendor/librespot-playback/src/lib.rs b/native/vendor/librespot-playback/src/lib.rsindex a637f00..6adc239 100644--- a/native/vendor/librespot-playback/src/lib.rs+++ b/native/vendor/librespot-playback/src/lib.rs@@ -10,7 +10,8 @@ pub mod config;pub mod convert;pub mod decoder;pub mod dither;-mod local_file;+/// LOCAL PATCH: public for `local_file::set_app_files`.+pub mod local_file;pub mod mixer;pub mod player;mod symphonia_util;diff --git a/native/vendor/librespot-playback/src/local_file.rs b/native/vendor/librespot-playback/src/local_file.rsindex f25c658..92544dc 100644--- a/native/vendor/librespot-playback/src/local_file.rs+++ b/native/vendor/librespot-playback/src/local_file.rs@@ -29,6 +29,31 @@ impl LocalFileLookup {pub fn get(&self, uri: &SpotifyUri) -> Option<&Path> {self.0.get(uri).map(|p| p.as_path())}++ /// LOCAL PATCH: the app's own match first, then the scanned directories.+ pub fn path_for(&self, uri: &SpotifyUri) -> Option<PathBuf> {+ APP_FILES+ .read()+ .ok()+ .and_then(|files| files.as_ref()?.get(uri).cloned())+ .or_else(|| self.get(uri).map(Path::to_path_buf))+ }+}++/// LOCAL PATCH: which file each local entry of a playlist is, as the app+/// matched it.+///+/// The scan below wants a file's tags to spell out the entry exactly, which a+/// copy on a phone rarely does; the app matches more forgivingly and with the+/// phone's own media index, and hands the result over here.+static APP_FILES: std::sync::RwLock<Option<HashMap<SpotifyUri, PathBuf>>> =+ std::sync::RwLock::new(None);++/// LOCAL PATCH: replaces the app's matches; see [APP_FILES].+pub fn set_app_files(files: HashMap<SpotifyUri, PathBuf>) {+ if let Ok(mut current) = APP_FILES.write() {+ *current = Some(files);+ }}pub fn create_local_file_lookup(directories: &[PathBuf]) -> LocalFileLookup {diff --git a/native/vendor/librespot-playback/src/player.rs b/native/vendor/librespot-playback/src/player.rsindex c81e1dc..a064fd4 100644--- a/native/vendor/librespot-playback/src/player.rs+++ b/native/vendor/librespot-playback/src/player.rs@@ -1710,14 +1710,15 @@ impl PlayerTrackLoader {return None;};- let entry = self.local_file_lookup.get(&track_uri);+ // LOCAL PATCH: the app's matches too; see local_file::set_app_files.+ let entry = self.local_file_lookup.path_for(&track_uri);let Some(path) = entry else {error!("Unable to find file path for local file <{track_uri}>");return None;};- let src = match File::open(path) {+ let src = match File::open(&path) {Ok(src) => src,Err(e) => {error!("Failed to open local file: {e}");@@ -1756,7 +1757,7 @@ impl PlayerTrackLoader {}};- let file_size = fs::metadata(path).ok()?.len();+ let file_size = fs::metadata(&path).ok()?.len();let bytes_per_second = (file_size / duration.as_secs()) as usize;let stream_loader_controller = StreamLoaderController::from_local_file(file_size);