musicbrainz: new app
- Commit
f410094bd4725e09258e76f5464070a9f6535715- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-05 03:35 UTC (4 months ago)
- Parents
1602f9d
Diff
README.md
diff --git a/README.md b/README.mdindex ee86ad81d4..17d14b0379 100644--- a/README.md+++ b/README.md@@ -54,6 +54,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **Maps** | [Homepage](https://ma.vayunmathur.com/apps/maps) | In Progress | In Progress | | **Messages** | [Homepage](https://ma.vayunmathur.com/apps/messages) | In Progress | In Progress | | **Music** | [Homepage](https://ma.vayunmathur.com/apps/music) | [MA Repo](https://ma.vayunmathur.com/fdroid) | [](https://api.vayunmathur.com/obtainium-link?name=Music&packageName=com.vayunmathur.music&apk=music-release.apk) |+| **MusicBrainz** | [Homepage](https://ma.vayunmathur.com/apps/musicbrainz) | [MA Repo](https://ma.vayunmathur.com/fdroid) | [](https://api.vayunmathur.com/obtainium-link?name=MusicBrainz&packageName=com.vayunmathur.musicbrainz&apk=musicbrainz-release.apk) | | **Notes** | [Homepage](https://ma.vayunmathur.com/apps/notes) | [MA Repo](https://ma.vayunmathur.com/fdroid) | [](https://api.vayunmathur.com/obtainium-link?name=Notes&packageName=com.vayunmathur.notes&apk=notes-release.apk) | | **Office** | [Homepage](https://ma.vayunmathur.com/apps/office) | [](https://f-droid.org/packages/com.vayunmathur.office) | [](https://api.vayunmathur.com/obtainium-link?name=Office&packageName=com.vayunmathur.office&apk=office-release.apk) | | **Open Assistant** | [Homepage](https://ma.vayunmathur.com/apps/openassistant) | [](https://f-droid.org/packages/com.vayunmathur.openassistant) | [](https://api.vayunmathur.com/obtainium-link?name=OpenAssistant&packageName=com.vayunmathur.openassistant&apk=openassistant-release.apk) |
SUPPLY_CHAIN_RISKS.md
diff --git a/SUPPLY_CHAIN_RISKS.md b/SUPPLY_CHAIN_RISKS.mdindex f40f838b88..375d36447a 100644--- a/SUPPLY_CHAIN_RISKS.md+++ b/SUPPLY_CHAIN_RISKS.md@@ -27,6 +27,8 @@ These services are the raison d'être of the feature. If the service itself ceas | `email` | **Per-provider IMAP/SMTP + OAuth** | Gmail `imap.gmail.com:993` / `smtp.gmail.com:465`, Outlook `outlook.office365.com:993` / `smtp-mail.outlook.com:587` + `https://login.microsoftonline.com/common/oauth2/v2.0/authorize`, Yahoo, iCloud `imap.mail.me.com`, Fastmail, generic custom | Purpose is connecting to user's own email provider; provider IS the mailbox | That provider's account stops syncing. Microsoft identity outage blocks Outlook token refresh | `email/src/main/java/com/vayunmathur/email/data/ProviderPresets.kt`, `OutlookOAuth.kt` | | `everysync` | **Google Contacts/Calendar, Google Health, iCloud CalDAV/CardDAV, Generic DAV** | `https://accounts.google.com/o/oauth2/v2/auth`, `oauth2.googleapis.com/token`, `www.googleapis.com/carddav/v1`, `apidata.googleusercontent.com/caldav/v2`, `health.googleapis.com/v4/.../dataPoints`, `caldav.icloud.com`, `contacts.icloud.com`, generic `/.well-known/caldav` discovery via `DavClient.kt` PROPFIND/REPORT | Purpose is syncing user's external calendars/contacts/health from those providers. Generic DAV servers are user-provided (not third-party) | Google/iCloud sync stops; Health backfill (steps, HR, sleep etc) halts | `everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthConfig.kt`, `provider/impl/GoogleProvider.kt`, `remote/GoogleHealthClient.kt`, `provider/impl/DavProviders.kt`, `remote/DavClient.kt` | | `travel` | **Duffel (Flights + Stays) via self-hosted proxy** | `https://api.vayunmathur.com/api/travel/*` proxying Duffel token server-side: `/places`, `/flights`, `/flights-async`, `/offers`, `/airlines`, `/aircraft`, `/orders`, `/orders/{id}/pay`, etc. Stays: `https://api.vayunmathur.com/api/stays/*` `/search`, `/rates`, `/quote`, `/bookings` | Purpose is flight + hotel search/booking; Duffel is the inventory aggregator. Proxy itself is assumed indefinite, but upstream Duffel is third-party | Flight/hotel search, pricing, seat maps, booking, trips hub fails. Reference data (airlines/cities) cached partially | `travel/src/main/java/com/vayunmathur/travel/network/TravelApi.kt`, `StaysApi.kt` |+| `musicbrainz` | **MusicBrainz WS/2** | `https://musicbrainz.org/ws/2/{artist,release-group,release,recording}`, 1 req/sec limit, identifying User-Agent required | Product is a MusicBrainz browser; MusicBrainz is the catalogue | No search or browsing at all. The app has no other catalogue source | `musicbrainz/src/main/java/com/vayunmathur/musicbrainz/api/MusicBrainzApi.kt` |+| `musicbrainz` | **YouTube** | `*.googlevideo.com` progressive audio, resolved through the vendored NewPipe fork in `:youpipe:extractor` | MusicBrainz catalogues music but hosts none; YouTube is the audio source | Downloads fail; browsing and the on-device library scan still work. Breaks on anti-bot changes, same as `youpipe` | `musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/AudioResolver.kt`, `MbDownloader.kt` | Mitigation for purpose-aligned: pin UA versions (`Chrome/146`, Sec-CH-UA), isolate per-bridge circuit breaker, implement extractor/protocol version checks in CI, surface degraded state per account. @@ -41,6 +43,7 @@ These servers provide data/functionality that is NOT intrinsically tied to a sin | `maps` basemap (vector) | **Protomaps v4 + basemaps-assets now self-hosted ✅** | `https://data.vayunmathur.com/v4.pmtiles` (137 GB, was `https://demo-bucket.protomaps.com/v4.pmtiles`), zones `https://data.vayunmathur.com/zone_*.pmtiles` (64 via Morton/Z-order, `ZoneDownloadManager.kt:170`), styling sprites `https://data.vayunmathur.com/basemaps-assets/sprites/v4/light` + fonts `fonts/{fontstack}/{range}.pbf` (`style.json:3541-3542`, 1044 objects), offline routing `amenities.db`, `metadata.bin`, `road_names.bin` | Self-hosted on R2 bucket `maps` custom domain `data.vayunmathur.com` (Cloudflare, direct Range, free egress, `immutable` cache). PMTiles streams via HTTP Range by MapLibre; disk cache `MapTileCache.kt:36-39` SHA-256(URL+Range) 24h refresh + offline stale-serve with `.origin` migration marker. Attribution `Protomaps © OSM` preserved (`style.json` attribution, ODbL/BSD allowed) | If R2 down: previously-cached tilecache still serves Ultra; zone offline still works; fallback would require demo-bucket again (comment kept in vendor script) | Already vendored at `data.vayunmathur.com` — zero external vector dependency. APK only hits own domain for vector tiles | | `youpipe` extras | **SponsorBlock / DeArrow (community)** — data APIs now self-hosted | Segment + branding data served from `https://api.vayunmathur.com/api/skipSegments` and `/api/branding` (a local mirror of the SponsorBlock DB, no runtime call to ajay.app). DeArrow now self-hosted renderer `GET /api/dearrow/thumbnail?videoID=&time=` (`handlers/dearrow.rs`, own yt-dlp + ffmpeg impl inspired by `ajayyy/DeArrowThumbnailCache`) | Crowdsourced, best-effort extras, not core YouTube | Sponsor skips + DeArrow titles/branding + thumbnail frames now continue from local even if ajay.app is down | ✅ **Fully self-hosted** — SponsorBlock DB mirrored into `sponsorblock.db` (`sb_build.sh` rsyncs public dumps; served by `handlers/sponsorblock.rs`). DeArrow thumbnail proxy + render at `/api/dearrow/thumbnail` (`dearrow.rs`), clients rewired in `Extractor.kt:167` `DEARROW_THUMB_MIRROR` and `Wikidata.kt:10` `BASE_URL`. Wikidata proxy `GET /api/wikidata/items/:id` (`wikidata.rs`) — 73 server tests green | | `maps` / `travel` / `photos` / `weather` | **MapLibre rendering + Wikidata enrichment** | `org.maplibre.compose:maplibre-compose:0.13.0` → `libmaplibre.so`, self-hosted Wikidata `https://api.vayunmathur.com/api/wikidata/items/{id}` (`Wikidata.kt:10`) | Map renderer is FOSS community project (vs Mapbox), Wikidata is enrichment only (now also proxied/self-cached at `wikidata_cache/`) | Map rendering would need fork/mirror if MapLibre artifacts gone; Wikidata fail is graceful null | Vendor MapLibre AAR, or switch to OpenGL self-render; Wikidata proxy keeps attribution |+| `musicbrainz` extras | **Cover Art Archive / LRCLIB (community)** | `https://coverartarchive.org/release/{id}/front-500` and `/release-group/...` (redirects to `ia*.us.archive.org`, hence `TrustBundle.STANDARD`), `https://lrclib.net/api/get` | Artwork and lyrics are decoration on the download, not the feature. Both are optional and switchable off in settings | Downloads still succeed, just without embedded cover art or lyrics. Browsing shows placeholder tiles | Mirror covers on `data.vayunmathur.com`, or fall back to the artwork embedded in the source stream | `health` **no longer requests `android.permission.INTERNET` at all** — it is the first app here with no network access whatsoever. Its nutrition database ships inside the APK as a brotli-compressed columnar asset (`scripts/generate_food_db.py` → `health/src/main/assets/food.bin.br`, 10.9 MB for 465,000 products), which `FoodDatabase.kt` turns into a SQLite/FTS5 database on first launch. Upstream is the **Open Food Facts** daily CSV export (ODbL v1.0, attributed in-app) — a build-host dependency, not a runtime one: if it vanished the shipped database keeps working and only stops being refreshable. The older `/api/food/search` and `/api/food/data/:id` endpoints remain up for previously-shipped builds.
metadata_data/musicbrainz.md
diff --git a/metadata_data/musicbrainz.md b/metadata_data/musicbrainz.mdnew file mode 100644index 0000000000..8cecb9e1b5--- /dev/null+++ b/metadata_data/musicbrainz.md@@ -0,0 +1,16 @@+A search engine for music that can download what you find++Browse the MusicBrainz catalogue - the open music encyclopedia - and download anything+you do not already own.++Features:+- Search albums, artists and songs+- Browse an artist's full discography, every edition of an album, and its tracklist+- See at a glance which songs you already have on your device+- Download single songs or a whole album at once+- Downloads are tagged with title, artist, album, track number, cover art and lyrics+- Files are saved into a folder you choose, so any music player can see them++Which songs you already own is worked out by reading the tags on the files in your music+folder, not by tracking what this app downloaded. Music you ripped, bought or got+anywhere else counts too.
metadata_data/photos/musicbrainz/1.png
diff --git a/metadata_data/photos/musicbrainz/1.png b/metadata_data/photos/musicbrainz/1.pngnew file mode 100644index 0000000000..8ede04667fBinary files /dev/null and b/metadata_data/photos/musicbrainz/1.png differ
metadata_data/photos/musicbrainz/2.png
diff --git a/metadata_data/photos/musicbrainz/2.png b/metadata_data/photos/musicbrainz/2.pngnew file mode 100644index 0000000000..d41a8a97d4Binary files /dev/null and b/metadata_data/photos/musicbrainz/2.png differ
metadata_data/photos/musicbrainz/3.png
diff --git a/metadata_data/photos/musicbrainz/3.png b/metadata_data/photos/musicbrainz/3.pngnew file mode 100644index 0000000000..f11debcce4Binary files /dev/null and b/metadata_data/photos/musicbrainz/3.png differ
metadata_data/photos/musicbrainz/4.png
diff --git a/metadata_data/photos/musicbrainz/4.png b/metadata_data/photos/musicbrainz/4.pngnew file mode 100644index 0000000000..520bc24ef0Binary files /dev/null and b/metadata_data/photos/musicbrainz/4.png differ
musicbrainz/build.gradle.kts
diff --git a/musicbrainz/build.gradle.kts b/musicbrainz/build.gradle.ktsnew file mode 100644index 0000000000..c68bed4d8f--- /dev/null+++ b/musicbrainz/build.gradle.kts@@ -0,0 +1,28 @@+plugins {+ id("common-conventions-app")+ id("common-conventions-preview-metadata")+ alias(libs.plugins.ksp)+}++launcherIcon {+ symbol = "graphic_eq"+}++android {+ defaultConfig {+ applicationId = "com.vayunmathur.musicbrainz"+ }+}++dependencies {+ implementation(project(":library:network"))+ implementation(project(":library:image"))+ // The vendored NewPipe fork. Only the JVM extractor is used - the SABR/PO-token+ // machinery that needs QuickJS and a WebView lives in :youpipe itself, and audio+ // resolution works without it.+ implementation(project(":youpipe:extractor"))+ implementation(libs.androidx.work.runtime.ktx)+ implementation(libs.androidx.datastore.preferences)+ implementRoom(libs)+ implementation(project(":library:room"))+}
musicbrainz/src/main/AndroidManifest.xml
diff --git a/musicbrainz/src/main/AndroidManifest.xml b/musicbrainz/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..d101de39b4--- /dev/null+++ b/musicbrainz/src/main/AndroidManifest.xml@@ -0,0 +1,40 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <uses-permission android:name="android.permission.INTERNET" />+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />++ <application+ android:name=".MusicBrainzApplication"+ android:allowBackup="true"+ android:dataExtractionRules="@xml/data_extraction_rules"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher"+ android:supportsRtl="true"+ android:theme="@style/Theme.General">+ <activity+ android:name=".MainActivity"+ android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+ android:exported="true"+ android:theme="@style/Theme.General">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />++ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ <!-- musicbrainz.org links open straight into the matching page. -->+ <intent-filter android:autoVerify="true">+ <action android:name="android.intent.action.VIEW" />++ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />+ <data android:scheme="https" />+ <data android:host="musicbrainz.org" />+ <data android:host="beta.musicbrainz.org" />+ </intent-filter>+ </activity>+ </application>++</manifest>
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MainActivity.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MainActivity.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MainActivity.ktnew file mode 100644index 0000000000..cf0e535933--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MainActivity.kt@@ -0,0 +1,68 @@+package com.vayunmathur.musicbrainz++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import androidx.compose.runtime.Composable+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavKey+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.musicbrainz.ui.ArtistPage+import com.vayunmathur.musicbrainz.ui.DownloadsPage+import com.vayunmathur.musicbrainz.ui.ReleaseGroupPage+import com.vayunmathur.musicbrainz.ui.ReleasePage+import com.vayunmathur.musicbrainz.ui.SearchPage+import com.vayunmathur.musicbrainz.ui.SettingsPage+import com.vayunmathur.musicbrainz.util.MusicBrainzViewModel+import kotlinx.serialization.Serializable++class MainActivity : ComponentActivity() {+ private val viewModel: MusicBrainzViewModel by viewModels()++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ enableEdgeToEdge()+ setContent {+ DynamicTheme {+ Navigation(viewModel)+ }+ }+ }+}++@Serializable+sealed interface Route : NavKey {+ @Serializable+ data object Search : Route++ @Serializable+ data object Downloads : Route++ @Serializable+ data object Settings : Route++ @Serializable+ data class Artist(val artistId: String) : Route++ @Serializable+ data class ReleaseGroup(val releaseGroupId: String) : Route++ @Serializable+ data class Release(val releaseId: String) : Route+}++@Composable+fun Navigation(viewModel: MusicBrainzViewModel) {+ val backStack = rememberNavBackStack<Route>(Route.Search)+ MainNavigation(backStack) {+ entry<Route.Search> { SearchPage(backStack, viewModel) }+ entry<Route.Artist> { ArtistPage(backStack, viewModel, it.artistId) }+ entry<Route.ReleaseGroup> { ReleaseGroupPage(backStack, viewModel, it.releaseGroupId) }+ entry<Route.Release> { ReleasePage(backStack, viewModel, it.releaseId) }+ entry<Route.Downloads> { DownloadsPage(backStack, viewModel) }+ entry<Route.Settings> { SettingsPage(backStack, viewModel) }+ }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MusicBrainzApplication.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MusicBrainzApplication.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MusicBrainzApplication.ktnew file mode 100644index 0000000000..d2abd99ad4--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MusicBrainzApplication.kt@@ -0,0 +1,20 @@+package com.vayunmathur.musicbrainz++import android.app.Application+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.TrustBundle+import com.vayunmathur.musicbrainz.download.MbDownloader+import org.schabi.newpipe.extractor.NewPipe+import org.schabi.newpipe.extractor.localization.Localization+import java.util.Locale++class MusicBrainzApplication : Application() {+ override fun onCreate() {+ super.onCreate()+ // STANDARD rather than FIRST_PARTY: musicbrainz.org and lrclib.net are ISRG, but+ // coverartarchive.org redirects to ia*.us.archive.org, which chains to Amazon and+ // DigiCert roots that only STANDARD carries.+ NetworkClient.init(this, TrustBundle.STANDARD)+ NewPipe.init(MbDownloader(), Localization.fromLocale(Locale.getDefault()))+ }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/api/MusicBrainzApi.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/api/MusicBrainzApi.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/api/MusicBrainzApi.ktnew file mode 100644index 0000000000..6f2e38881e--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/api/MusicBrainzApi.kt@@ -0,0 +1,96 @@+package com.vayunmathur.musicbrainz.api++import com.vayunmathur.library.network.NetworkClient+import kotlinx.coroutines.delay+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import java.net.URLEncoder++/**+ * Client for the MusicBrainz WS/2 API.+ *+ * MusicBrainz allows one request per second per client and blocks callers that ignore+ * that, so every request funnels through [gate]. It also rejects requests without an+ * identifying User-Agent, which is why [USER_AGENT] names the app and links the source.+ */+object MusicBrainzApi {++ private const val BASE = "https://musicbrainz.org/ws/2"+ private const val USER_AGENT =+ "ModernAppsMusicBrainz/1.0 ( https://ma.vayunmathur.com/apps/musicbrainz )"+ private const val MIN_REQUEST_SPACING_MS = 1_100L++ private val rateLimit = Mutex()+ private var lastRequestAt = 0L++ private val headers = mapOf(+ "User-Agent" to USER_AGENT,+ "Accept" to "application/json",+ )++ /** Serialises requests and spaces them out so the shared rate limit is respected. */+ private suspend fun <T> gate(block: suspend () -> T): T = rateLimit.withLock {+ val since = System.currentTimeMillis() - lastRequestAt+ if (since < MIN_REQUEST_SPACING_MS) delay(MIN_REQUEST_SPACING_MS - since)+ try {+ block()+ } finally {+ lastRequestAt = System.currentTimeMillis()+ }+ }++ private suspend inline fun <reified T> get(path: String): T =+ gate { NetworkClient.getJson<T>("$BASE/$path", headers = headers) }++ private fun encode(value: String): String = URLEncoder.encode(value, "UTF-8")++ suspend fun searchArtists(query: String, limit: Int = 25): List<MbArtist> =+ get<MbArtistSearch>("artist?query=${encode(query)}&fmt=json&limit=$limit").artists++ suspend fun searchReleaseGroups(query: String, limit: Int = 25): List<MbReleaseGroup> =+ get<MbReleaseGroupSearch>(+ "release-group?query=${encode(query)}&fmt=json&limit=$limit",+ ).releaseGroups++ suspend fun searchRecordings(query: String, limit: Int = 25): List<MbRecording> =+ get<MbRecordingSearch>("recording?query=${encode(query)}&fmt=json&limit=$limit").recordings++ suspend fun artist(id: String): MbArtist = get("artist/$id?fmt=json")++ /** An artist's discography. Browse rather than lookup, because lookup caps the list. */+ suspend fun releaseGroupsOfArtist(id: String, limit: Int = 100): List<MbReleaseGroup> =+ get<MbReleaseGroupBrowse>(+ "release-group?artist=$id&fmt=json&limit=$limit&offset=0",+ ).releaseGroups++ suspend fun releaseGroup(id: String): MbReleaseGroup =+ get("release-group/$id?fmt=json&inc=artist-credits")++ /** Every edition of a release group, so the user can pick the pressing they want. */+ suspend fun releasesOfReleaseGroup(id: String, limit: Int = 100): List<MbReleaseSummary> =+ get<MbReleaseBrowse>(+ "release?release-group=$id&fmt=json&inc=media+artist-credits&limit=$limit&offset=0",+ ).releases++ /**+ * A full release with its tracklist.+ *+ * `artist-credits` is what makes per-track artists available; without it a+ * compilation collapses to the release artist, which for soundtracks is usually+ * just "Various Artists".+ */+ suspend fun release(id: String): MbRelease =+ get("release/$id?fmt=json&inc=recordings+artists+artist-credits+release-groups")++ suspend fun recording(id: String): MbRecording =+ get("recording/$id?fmt=json&inc=artists+artist-credits+releases")+}++/** Cover Art Archive image URLs. Both endpoints 404 when a release has no artwork. */+object CoverArt {+ fun release(id: String, size: Int = 500): String =+ "https://coverartarchive.org/release/$id/front-$size"++ fun releaseGroup(id: String, size: Int = 500): String =+ "https://coverartarchive.org/release-group/$id/front-$size"+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/api/MusicBrainzModels.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/api/MusicBrainzModels.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/api/MusicBrainzModels.ktnew file mode 100644index 0000000000..d53b3fd7f0--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/api/MusicBrainzModels.kt@@ -0,0 +1,170 @@+package com.vayunmathur.musicbrainz.api++import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++/**+ * Wire models for the MusicBrainz WS/2 JSON API.+ *+ * Only the fields the app actually draws are declared; the client decodes with+ * `ignoreUnknownKeys`, so the responses stay readable without mirroring the whole schema.+ */++@Serializable+data class MbArtistRef(+ val id: String = "",+ val name: String = "",+ val disambiguation: String? = null,+)++@Serializable+data class MbArtistCredit(+ val name: String = "",+ val joinphrase: String = "",+ val artist: MbArtistRef? = null,+)++/**+ * Flattens a credit list the way MusicBrainz intends it to be displayed, honouring the+ * join phrases so "A", " feat. ", "B" comes back as "A feat. B" rather than "A, B".+ */+fun List<MbArtistCredit>?.display(): String? {+ if (this.isNullOrEmpty()) return null+ return buildString {+ for (credit in this@display) {+ append(credit.name)+ append(credit.joinphrase)+ }+ }.trim().ifEmpty { null }+}++@Serializable+data class MbLifeSpan(+ val begin: String? = null,+ val end: String? = null,+ val ended: Boolean? = null,+)++@Serializable+data class MbArea(val name: String? = null)++@Serializable+data class MbArtist(+ val id: String = "",+ val name: String = "",+ val disambiguation: String? = null,+ val type: String? = null,+ val country: String? = null,+ val area: MbArea? = null,+ @SerialName("life-span") val lifeSpan: MbLifeSpan? = null,+)++@Serializable+data class MbReleaseGroup(+ val id: String = "",+ val title: String = "",+ @SerialName("primary-type") val primaryType: String? = null,+ @SerialName("secondary-types") val secondaryTypes: List<String> = emptyList(),+ @SerialName("first-release-date") val firstReleaseDate: String? = null,+ @SerialName("artist-credit") val artistCredit: List<MbArtistCredit> = emptyList(),+)++@Serializable+data class MbMediumSummary(+ val format: String? = null,+ @SerialName("track-count") val trackCount: Int = 0,+)++@Serializable+data class MbReleaseSummary(+ val id: String = "",+ val title: String = "",+ val status: String? = null,+ val date: String? = null,+ val country: String? = null,+ val disambiguation: String? = null,+ val media: List<MbMediumSummary> = emptyList(),+ @SerialName("artist-credit") val artistCredit: List<MbArtistCredit> = emptyList(),+ @SerialName("release-group") val releaseGroup: MbReleaseGroup? = null,+)++@Serializable+data class MbRecordingRef(+ val id: String = "",+ val title: String = "",+ val length: Int? = null,+ @SerialName("artist-credit") val artistCredit: List<MbArtistCredit> = emptyList(),+)++@Serializable+data class MbTrack(+ val id: String = "",+ val title: String = "",+ val number: String? = null,+ val position: Int = 0,+ val length: Int? = null,+ @SerialName("artist-credit") val artistCredit: List<MbArtistCredit> = emptyList(),+ val recording: MbRecordingRef? = null,+)++@Serializable+data class MbMedium(+ val position: Int = 1,+ val format: String? = null,+ val title: String? = null,+ @SerialName("track-count") val trackCount: Int = 0,+ val tracks: List<MbTrack> = emptyList(),+)++@Serializable+data class MbRelease(+ val id: String = "",+ val title: String = "",+ val status: String? = null,+ val date: String? = null,+ val country: String? = null,+ val disambiguation: String? = null,+ val media: List<MbMedium> = emptyList(),+ @SerialName("artist-credit") val artistCredit: List<MbArtistCredit> = emptyList(),+ @SerialName("release-group") val releaseGroup: MbReleaseGroup? = null,+)++@Serializable+data class MbRecording(+ val id: String = "",+ val title: String = "",+ val length: Int? = null,+ val disambiguation: String? = null,+ @SerialName("artist-credit") val artistCredit: List<MbArtistCredit> = emptyList(),+ val releases: List<MbReleaseSummary> = emptyList(),+)++@Serializable+data class MbArtistSearch(+ val count: Int = 0,+ val artists: List<MbArtist> = emptyList(),+)++@Serializable+data class MbReleaseGroupSearch(+ val count: Int = 0,+ @SerialName("release-groups") val releaseGroups: List<MbReleaseGroup> = emptyList(),+)++@Serializable+data class MbRecordingSearch(+ val count: Int = 0,+ val recordings: List<MbRecording> = emptyList(),+)++@Serializable+data class MbReleaseGroupBrowse(+ @SerialName("release-group-count") val count: Int = 0,+ @SerialName("release-groups") val releaseGroups: List<MbReleaseGroup> = emptyList(),+)++@Serializable+data class MbReleaseBrowse(+ @SerialName("release-count") val count: Int = 0,+ val releases: List<MbReleaseSummary> = emptyList(),+)
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/MusicBrainzDatabase.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/MusicBrainzDatabase.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/MusicBrainzDatabase.ktnew file mode 100644index 0000000000..0a591c2580--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/MusicBrainzDatabase.kt@@ -0,0 +1,65 @@+package com.vayunmathur.musicbrainz.data++import androidx.room.Dao+import androidx.room.Database+import androidx.room.Entity+import androidx.room.PrimaryKey+import androidx.room.Query+import androidx.room.RoomDatabase+import androidx.room.Upsert++/**+ * One audio file found in the user's music folder.+ *+ * Keyed by document URI so a rescan updates rows in place. [size] and [lastModified] are+ * kept so an unchanged file can be skipped on the next scan without reopening it.+ */+@Entity(tableName = "local_track")+data class LocalTrack(+ @PrimaryKey val documentUri: String,+ val fileName: String,+ val size: Long,+ val lastModified: Long,+ val recordingId: String? = null,+ val releaseId: String? = null,+ val releaseTrackId: String? = null,+ val title: String? = null,+ val artist: String? = null,+ val album: String? = null,+ /** Normalised "artist\u0000title", the fallback match for files with no MusicBrainz IDs. */+ val matchKey: String? = null,+ /** Normalised "album\u0000title", so compilations still match when the artist differs. */+ val albumKey: String? = null,+)++@Dao+interface LocalTrackDao {+ @Upsert+ suspend fun upsertAll(tracks: List<LocalTrack>)++ @Query("SELECT * FROM local_track")+ suspend fun all(): List<LocalTrack>++ @Query("SELECT documentUri, size, lastModified FROM local_track")+ suspend fun fingerprints(): List<TrackFingerprint>++ @Query("DELETE FROM local_track WHERE documentUri IN (:uris)")+ suspend fun deleteByUris(uris: List<String>)++ @Query("DELETE FROM local_track")+ suspend fun deleteAll()++ @Query("SELECT COUNT(*) FROM local_track")+ suspend fun count(): Int+}++data class TrackFingerprint(+ val documentUri: String,+ val size: Long,+ val lastModified: Long,+)++@Database(entities = [LocalTrack::class], version = 1, exportSchema = false)+abstract class MusicBrainzDatabase : RoomDatabase() {+ abstract fun localTrackDao(): LocalTrackDao+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/AudioResolver.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/AudioResolver.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/AudioResolver.ktnew file mode 100644index 0000000000..ab73f9f9c7--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/AudioResolver.kt@@ -0,0 +1,130 @@+package com.vayunmathur.musicbrainz.download++import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import org.schabi.newpipe.extractor.MediaFormat+import org.schabi.newpipe.extractor.ServiceList+import org.schabi.newpipe.extractor.stream.AudioStream+import org.schabi.newpipe.extractor.stream.DeliveryMethod+import org.schabi.newpipe.extractor.stream.StreamInfoItem+import kotlin.math.abs++/** A resolved, directly fetchable audio stream. */+data class ResolvedAudio(+ val url: String,+ val suffix: String,+ val mimeType: String,+ val bitrate: Int,+ val sourceTitle: String,+)++/**+ * Finds a downloadable audio stream for a MusicBrainz track.+ *+ * MusicBrainz catalogues music but hosts none of it, so the audio comes from YouTube via+ * the extractor YouPipe already vendors.+ *+ * Only progressive streams are used. YouTube also serves audio over SABR, which needs a+ * stateful session and the PO-token machinery that lives in the YouPipe app; a track that+ * is SABR-only is reported as unavailable rather than dragging that whole stack in here.+ */+object AudioResolver {++ private const val SEARCH_RESULTS_CONSIDERED = 8+ private const val DURATION_TOLERANCE_SECONDS = 12L++ /**+ * @param durationMs the MusicBrainz recording length, used to pick between candidates.+ * Search alone happily returns hour-long compilations and sped-up edits of the same+ * title, and duration is the one signal that separates them from the actual track.+ */+ suspend fun resolve(+ artist: String,+ title: String,+ album: String?,+ durationMs: Int?,+ ): ResolvedAudio? = withContext(Dispatchers.IO) {+ val candidates = search(buildQuery(artist, title, album))+ if (candidates.isEmpty()) return@withContext null+ val ordered = rank(candidates, durationMs)+ for (candidate in ordered) {+ val audio = audioFor(candidate.url) ?: continue+ return@withContext audio.copy(sourceTitle = candidate.name)+ }+ null+ }++ private fun buildQuery(artist: String, title: String, album: String?): String = buildString {+ append(artist)+ append(" - ")+ append(title)+ if (!album.isNullOrBlank() && !title.contains(album, ignoreCase = true)) {+ append(' ')+ append(album)+ }+ }++ private fun search(query: String): List<StreamInfoItem> = try {+ val extractor = ServiceList.YouTube.getSearchExtractor(query)+ extractor.fetchPage()+ extractor.getInitialPage()+ .getItems()+ .filterIsInstance<StreamInfoItem>()+ .take(SEARCH_RESULTS_CONSIDERED)+ } catch (_: Exception) {+ emptyList()+ }++ /**+ * Orders candidates by how close their runtime is to the catalogued one.+ *+ * Anything within a few seconds is treated as equally good and left in YouTube's own+ * relevance order, which is a better tie-breaker than an arbitrarily closer duration.+ */+ private fun rank(candidates: List<StreamInfoItem>, durationMs: Int?): List<StreamInfoItem> {+ if (durationMs == null || durationMs <= 0) return candidates+ val target = durationMs / 1000L+ return candidates+ .withIndex()+ .sortedWith(+ compareBy(+ { (_, item) ->+ val delta = abs(item.getDuration() - target)+ if (delta <= DURATION_TOLERANCE_SECONDS) 0L else delta+ },+ { (index, _) -> index },+ ),+ )+ .map { it.value }+ }++ private fun audioFor(videoUrl: String): ResolvedAudio? = try {+ val extractor = ServiceList.YouTube.getStreamExtractor(videoUrl)+ extractor.fetchPage()+ val progressive = extractor.getAudioStreams().filter {+ it.getDeliveryMethod() == DeliveryMethod.PROGRESSIVE_HTTP &&+ it.isUrl() &&+ it.getContent().isNotBlank()+ }+ // M4A first: it is an MP4 container, which is the one format the tag writer can+ // annotate, so preferring it is what lets downloads carry their MusicBrainz IDs.+ val best = progressive.filter { it.getFormat() == MediaFormat.M4A }+ .maxByOrNull { it.effectiveBitrate() }+ ?: progressive.maxByOrNull { it.effectiveBitrate() }+ best?.let {+ val format = it.getFormat()+ ResolvedAudio(+ url = it.getContent(),+ suffix = format?.getSuffix() ?: "m4a",+ mimeType = format?.mimeType ?: "audio/mp4",+ bitrate = it.effectiveBitrate(),+ sourceTitle = "",+ )+ }+ } catch (_: Exception) {+ null+ }++ private fun AudioStream.effectiveBitrate(): Int =+ getAverageBitrate().takeIf { it > 0 } ?: getBitrate()+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/DownloadQueue.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/DownloadQueue.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/DownloadQueue.ktnew file mode 100644index 0000000000..f23e7d99d4--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/DownloadQueue.kt@@ -0,0 +1,144 @@+package com.vayunmathur.musicbrainz.download++import android.content.Context+import androidx.work.Data+import androidx.work.ExistingWorkPolicy+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.WorkManager+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/** What a queued download is doing right now. */+enum class DownloadState { Queued, Searching, Downloading, Tagging, Done, Failed }++data class DownloadItem(+ val id: String,+ val title: String,+ val artist: String,+ val album: String?,+ val state: DownloadState,+ val progress: Float = 0f,+ val error: String? = null,+)++/** Everything the worker needs to fetch and tag one track. */+data class DownloadRequest(+ val recordingId: String?,+ val releaseTrackId: String?,+ val releaseId: String?,+ val releaseGroupId: String?,+ val title: String,+ val artist: String,+ val album: String?,+ val albumArtist: String?,+ val date: String?,+ val trackNumber: Int?,+ val trackTotal: Int?,+ val discNumber: Int?,+ val durationMs: Int?,+) {+ /**+ * Stable identity for the queue and for WorkManager's unique work name.+ *+ * Prefers the release track id so the same recording appearing on two albums is two+ * separate downloads rather than one silently replacing the other.+ */+ val key: String+ get() = releaseTrackId ?: recordingId ?: "$artist\u0000$album\u0000$title"+}++/**+ * Process-wide view of in-flight downloads.+ *+ * WorkManager owns the actual execution and survives process death; this only mirrors+ * progress for the UI, so it is intentionally not persisted.+ */+object DownloadQueue {+ private val _items = MutableStateFlow<Map<String, DownloadItem>>(emptyMap())+ val items: StateFlow<Map<String, DownloadItem>> = _items.asStateFlow()++ fun enqueue(context: Context, request: DownloadRequest) {+ val key = request.key+ if (_items.value[key]?.state in ACTIVE_STATES) return+ _items.update(+ DownloadItem(+ id = key,+ title = request.title,+ artist = request.artist,+ album = request.album,+ state = DownloadState.Queued,+ ),+ )+ WorkManager.getInstance(context).enqueueUniqueWork(+ "musicbrainz-download-$key",+ ExistingWorkPolicy.KEEP,+ OneTimeWorkRequestBuilder<DownloadWorker>().setInputData(request.toData()).build(),+ )+ }++ fun enqueueAll(context: Context, requests: List<DownloadRequest>) {+ requests.forEach { enqueue(context, it) }+ }++ fun cancel(context: Context, key: String) {+ WorkManager.getInstance(context).cancelUniqueWork("musicbrainz-download-$key")+ _items.value = _items.value - key+ }++ fun clearFinished() {+ _items.value = _items.value.filterValues { it.state in ACTIVE_STATES }+ }++ internal fun update(state: DownloadState, key: String, progress: Float = 0f, error: String? = null) {+ val existing = _items.value[key] ?: return+ _items.update(existing.copy(state = state, progress = progress, error = error))+ }++ private fun MutableStateFlow<Map<String, DownloadItem>>.update(item: DownloadItem) {+ value = value + (item.id to item)+ }++ private val ACTIVE_STATES = setOf(+ DownloadState.Queued,+ DownloadState.Searching,+ DownloadState.Downloading,+ DownloadState.Tagging,+ )+}++internal fun DownloadRequest.toData(): Data = Data.Builder()+ .putString("recordingId", recordingId)+ .putString("releaseTrackId", releaseTrackId)+ .putString("releaseId", releaseId)+ .putString("releaseGroupId", releaseGroupId)+ .putString("title", title)+ .putString("artist", artist)+ .putString("album", album)+ .putString("albumArtist", albumArtist)+ .putString("date", date)+ .putInt("trackNumber", trackNumber ?: 0)+ .putInt("trackTotal", trackTotal ?: 0)+ .putInt("discNumber", discNumber ?: 0)+ .putInt("durationMs", durationMs ?: 0)+ .build()++internal fun Data.toDownloadRequest(): DownloadRequest? {+ val title = getString("title") ?: return null+ val artist = getString("artist") ?: return null+ return DownloadRequest(+ recordingId = getString("recordingId"),+ releaseTrackId = getString("releaseTrackId"),+ releaseId = getString("releaseId"),+ releaseGroupId = getString("releaseGroupId"),+ title = title,+ artist = artist,+ album = getString("album"),+ albumArtist = getString("albumArtist"),+ date = getString("date"),+ trackNumber = getInt("trackNumber", 0).takeIf { it > 0 },+ trackTotal = getInt("trackTotal", 0).takeIf { it > 0 },+ discNumber = getInt("discNumber", 0).takeIf { it > 0 },+ durationMs = getInt("durationMs", 0).takeIf { it > 0 },+ )+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/DownloadWorker.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/DownloadWorker.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/DownloadWorker.ktnew file mode 100644index 0000000000..e7ed676588--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/DownloadWorker.kt@@ -0,0 +1,248 @@+package com.vayunmathur.musicbrainz.download++import android.content.Context+import androidx.core.net.toUri+import androidx.work.CoroutineWorker+import androidx.work.WorkerParameters+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.room.buildDatabase+import com.vayunmathur.musicbrainz.api.CoverArt+import com.vayunmathur.musicbrainz.data.LocalTrack+import com.vayunmathur.musicbrainz.data.MusicBrainzDatabase+import com.vayunmathur.musicbrainz.library.LibraryScanner+import com.vayunmathur.musicbrainz.library.MatchKeys+import com.vayunmathur.musicbrainz.library.SafTree+import com.vayunmathur.musicbrainz.util.MusicBrainzPrefs+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext+import java.io.ByteArrayOutputStream++/**+ * Fetches one track and files it into the user's music folder.+ *+ * Runs under WorkManager so an album's worth of downloads survives the app being+ * backgrounded, and so a failed track can be retried without redoing the rest.+ */+class DownloadWorker(context: Context, params: WorkerParameters) :+ CoroutineWorker(context, params) {++ override suspend fun doWork(): Result = withContext(Dispatchers.IO) {+ val request = inputData.toDownloadRequest() ?: return@withContext Result.failure()+ val key = request.key+ try {+ val prefs = MusicBrainzPrefs(applicationContext)+ val treeUri = prefs.musicFolderUri()+ ?: return@withContext fail(key, "No music folder selected")++ DownloadQueue.update(DownloadState.Searching, key)+ val audio = AudioResolver.resolve(+ artist = request.artist,+ title = request.title,+ album = request.album,+ durationMs = request.durationMs,+ ) ?: return@withContext fail(key, "No audio source found")++ DownloadQueue.update(DownloadState.Downloading, key)+ val raw = download(audio.url) { progress ->+ DownloadQueue.update(DownloadState.Downloading, key, progress)+ } ?: return@withContext fail(key, "Download failed")++ DownloadQueue.update(DownloadState.Tagging, key, 1f)+ val cover = if (prefs.embedCoverArt.first()) {+ CoverArtCache.get(request.releaseId, request.releaseGroupId)+ } else {+ null+ }+ val lyrics = if (prefs.fetchLyrics.first()) {+ Lyrics.fetch(request.artist, request.title, request.album, request.durationMs)+ } else {+ null+ }++ val tagged = if (audio.suffix == "m4a") {+ Mp4Tagger.tag(raw, request.toMp4Tags(cover, lyrics)) ?: raw+ } else {+ // Only MP4 can be annotated here, so anything else is stored as fetched.+ // It still gets found by the library scan, just on filename and path.+ raw+ }++ val written = writeToLibrary(treeUri, request, audio.suffix, tagged)+ ?: return@withContext fail(key, "Could not write to music folder")++ recordInIndex(written, request, tagged.size)+ DownloadQueue.update(DownloadState.Done, key, 1f)+ Result.success()+ } catch (e: Exception) {+ fail(key, e.message ?: "Download failed")+ }+ }++ private fun fail(key: String, message: String): Result {+ DownloadQueue.update(DownloadState.Failed, key, error = message)+ return Result.failure()+ }++ /**+ * Streams the audio into memory, reporting progress as it goes.+ *+ * Buffered rather than written straight to the destination because the tagger has to+ * rewrite the container before the file is filed away, and a partially written track+ * appearing in the user's music folder would be picked up by every other player on+ * the device.+ */+ private suspend fun download(url: String, onProgress: (Float) -> Unit): ByteArray? {+ val expected = NetworkClient.getContentLength(url) ?: 0L+ val buffer = ByteArrayOutputStream(if (expected > 0) expected.toInt() else DEFAULT_BUFFER)+ var lastReported = 0L+ val response = NetworkClient.stream(url) { stream, resp ->+ if (stream == null || !resp.isSuccess) return@stream+ val chunk = ByteArray(READ_BUFFER)+ while (!stream.isClosedForRead) {+ if (isStopped) return@stream+ val read = stream.read(chunk)+ if (read <= 0) break+ buffer.write(chunk, 0, read)+ if (expected > 0) {+ val now = System.currentTimeMillis()+ if (now - lastReported > PROGRESS_INTERVAL_MS) {+ lastReported = now+ onProgress((buffer.size().toFloat() / expected).coerceIn(0f, 1f))+ }+ }+ }+ }+ if (!response.isSuccess && buffer.size() == 0) return null+ return buffer.toByteArray().takeIf { it.isNotEmpty() }+ }++ /** Files the track as `<Album artist>/<Album>/NN Title.ext` under the chosen folder. */+ private fun writeToLibrary(+ treeUri: String,+ request: DownloadRequest,+ suffix: String,+ bytes: ByteArray,+ ): android.net.Uri? {+ val tree = treeUri.toUri()+ val folderArtist = SafTree.sanitize(request.albumArtist ?: request.artist)+ val folderAlbum = SafTree.sanitize(request.album ?: request.title)+ val parent = SafTree.ensurePath(applicationContext, tree, listOf(folderArtist, folderAlbum))+ ?: return null+ val prefix = request.trackNumber?.let { "%02d ".format(it) } ?: ""+ val fileName = "$prefix${SafTree.sanitize(request.title)}.$suffix"+ val target = SafTree.createFile(+ applicationContext,+ tree,+ parent,+ fileName,+ if (suffix == "m4a") "audio/mp4" else "audio/*",+ ) ?: return null+ applicationContext.contentResolver.openOutputStream(target, "wt").use { out ->+ if (out == null) return null+ out.write(bytes)+ out.flush()+ }+ return target+ }++ /**+ * Adds the new file to the index straight away.+ *+ * The values come from the tags just written, so this agrees with what a later rescan+ * would find - it only saves the user waiting for one.+ */+ private suspend fun recordInIndex(+ uri: android.net.Uri,+ request: DownloadRequest,+ size: Int,+ ) {+ val dao = applicationContext+ .buildDatabase<MusicBrainzDatabase>(dbName = LibraryScanner.DB_NAME)+ .localTrackDao()+ dao.upsertAll(+ listOf(+ LocalTrack(+ documentUri = uri.toString(),+ fileName = uri.lastPathSegment.orEmpty(),+ size = size.toLong(),+ lastModified = System.currentTimeMillis(),+ recordingId = request.recordingId,+ releaseId = request.releaseId,+ releaseTrackId = request.releaseTrackId,+ title = request.title,+ artist = request.artist,+ album = request.album,+ matchKey = MatchKeys.trackKey(request.artist, request.title),+ albumKey = MatchKeys.albumKey(request.album, request.title),+ ),+ ),+ )+ LibraryScanner.loadCached(applicationContext)+ }++ private companion object {+ const val READ_BUFFER = 64 * 1024+ const val DEFAULT_BUFFER = 8 * 1024 * 1024+ const val PROGRESS_INTERVAL_MS = 250L+ }+}++private fun DownloadRequest.toMp4Tags(cover: ByteArray?, lyrics: String?) = Mp4Tags(+ title = title,+ artist = artist,+ album = album,+ albumArtist = albumArtist,+ date = date,+ lyrics = lyrics,+ trackNumber = trackNumber,+ trackTotal = trackTotal,+ discNumber = discNumber,+ coverArt = cover,+ coverIsPng = cover != null && cover.size > 8 && cover[1] == 'P'.code.toByte(),+ freeform = buildMap {+ recordingId?.let { put("MusicBrainz Track Id", it) }+ releaseId?.let { put("MusicBrainz Album Id", it) }+ releaseTrackId?.let { put("MusicBrainz Release Track Id", it) }+ },+)++/**+ * Holds the last few covers fetched from the Cover Art Archive.+ *+ * An album is downloaded as one worker per track, and without this each of them would+ * pull the same several-hundred-kilobyte image again.+ */+private object CoverArtCache {+ private const val MAX_ENTRIES = 4+ private val lock = Mutex()+ private val entries = LinkedHashMap<String, ByteArray?>()++ suspend fun get(releaseId: String?, releaseGroupId: String?): ByteArray? {+ val cacheKey = releaseId ?: releaseGroupId ?: return null+ lock.withLock {+ if (entries.containsKey(cacheKey)) return entries[cacheKey]+ }+ val urls = listOfNotNull(+ releaseId?.let { CoverArt.release(it) },+ releaseGroupId?.let { CoverArt.releaseGroup(it) },+ )+ var image: ByteArray? = null+ for (url in urls) {+ image = runCatching {+ val response = NetworkClient.execute(url)+ response.bytes.takeIf { response.isSuccess && it.isNotEmpty() }+ }.getOrNull()+ if (image != null) break+ }+ lock.withLock {+ if (entries.size >= MAX_ENTRIES) {+ entries.keys.firstOrNull()?.let { entries.remove(it) }+ }+ entries[cacheKey] = image+ }+ return image+ }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/Lyrics.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/Lyrics.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/Lyrics.ktnew file mode 100644index 0000000000..e6e5115e99--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/Lyrics.kt@@ -0,0 +1,44 @@+package com.vayunmathur.musicbrainz.download++import com.vayunmathur.library.network.NetworkClient+import kotlinx.serialization.Serializable++@Serializable+private data class LrcLibResponse(+ val syncedLyrics: String? = null,+ val plainLyrics: String? = null,+)++/**+ * Fetches lyrics from LRCLIB.+ *+ * Synced lyrics are preferred so players that support them can follow along, with plain+ * text as the fallback. Failures are silent - lyrics are a nicety, and a missing set is+ * not a reason to fail a download.+ */+object Lyrics {++ private const val BASE = "https://lrclib.net/api/get"+ private val headers = mapOf(+ "User-Agent" to "ModernAppsMusicBrainz/1.0 ( https://ma.vayunmathur.com/apps/musicbrainz )",+ )++ suspend fun fetch(artist: String, title: String, album: String?, durationMs: Int?): String? {+ val url = buildString {+ append(BASE)+ append("?artist_name=").append(encode(artist))+ append("&track_name=").append(encode(title))+ if (!album.isNullOrBlank()) append("&album_name=").append(encode(album))+ if (durationMs != null && durationMs > 0) append("&duration=").append(durationMs / 1000)+ }+ return try {+ val response = NetworkClient.getJson<LrcLibResponse>(url, headers = headers)+ response.syncedLyrics?.takeIf { it.isNotBlank() }+ ?: response.plainLyrics?.takeIf { it.isNotBlank() }+ } catch (_: Exception) {+ null+ }+ }++ private fun encode(value: String): String = java.net.URLEncoder.encode(value, "UTF-8")+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/MbDownloader.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/MbDownloader.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/MbDownloader.ktnew file mode 100644index 0000000000..71400852a6--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/MbDownloader.kt@@ -0,0 +1,89 @@+package com.vayunmathur.musicbrainz.download++import com.vayunmathur.library.network.NetworkClient+import kotlinx.coroutines.runBlocking+import org.schabi.newpipe.extractor.downloader.Downloader+import org.schabi.newpipe.extractor.downloader.Request+import org.schabi.newpipe.extractor.downloader.Response+import org.schabi.newpipe.extractor.downloader.StreamingResponse+import org.schabi.newpipe.extractor.localization.Localization++/**+ * The [Downloader] the extractor calls out through, on top of `NetworkClient`.+ *+ * A near-copy of YouPipe's, kept here rather than shared because the two apps are+ * otherwise independent and `:youpipe:extractor` is the only thing they have in common.+ * The browser User-Agent is not cosmetic: the InnerTube endpoints reject the default.+ */+class MbDownloader : Downloader() {+ override fun execute(request: Request): Response = runBlocking {+ val response = NetworkClient.performRequest(+ url = request.url,+ method = request.httpMethod,+ headers = withDefaultHeaders(request.headers),+ body = request.dataToSend,+ )+ Response(+ response.status,+ response.statusMessage,+ response.headers,+ response.body,+ response.url,+ )+ }++ override fun getStreaming(+ url: String,+ headers: Map<String, List<String>>?,+ localization: Localization?,+ ): StreamingResponse = runBlocking { streaming(url, "GET", headers, null, null) }++ override fun getStreaming(+ url: String,+ headers: Map<String, List<String>>?,+ localization: Localization?,+ timeoutMs: Long,+ ): StreamingResponse = runBlocking {+ streaming(url, "GET", headers, null, timeoutMs.coerceAtLeast(1))+ }++ override fun postStreaming(+ url: String,+ headers: Map<String, List<String>>?,+ dataToSend: ByteArray?,+ localization: Localization?,+ ): StreamingResponse = runBlocking { streaming(url, "POST", headers, dataToSend, null) }++ private suspend fun streaming(+ url: String,+ method: String,+ headers: Map<String, List<String>>?,+ data: ByteArray?,+ timeoutMs: Long?,+ ): StreamingResponse {+ val (code, respHeaders, stream) = NetworkClient.performRequestInputStream(+ url = url,+ method = method,+ headers = withDefaultHeaders(headers),+ body = data,+ timeoutMs = timeoutMs,+ )+ return StreamingResponse(code, respHeaders, stream)+ }++ private fun withDefaultHeaders(+ headers: Map<String, List<String>>?,+ ): Map<String, List<String>> {+ val result = LinkedHashMap<String, List<String>>()+ if (headers != null) result.putAll(headers)+ if (result.keys.none { it.equals("User-Agent", ignoreCase = true) }) {+ result["User-Agent"] = listOf(DEFAULT_USER_AGENT)+ }+ return result+ }++ private companion object {+ const val DEFAULT_USER_AGENT =+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0"+ }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/Mp4Tagger.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/Mp4Tagger.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/Mp4Tagger.ktnew file mode 100644index 0000000000..f571273bb1--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/download/Mp4Tagger.kt@@ -0,0 +1,293 @@+package com.vayunmathur.musicbrainz.download++import java.io.ByteArrayOutputStream++/** Everything the tagger will write. Null fields are simply omitted. */+data class Mp4Tags(+ val title: String? = null,+ val artist: String? = null,+ val album: String? = null,+ val albumArtist: String? = null,+ val date: String? = null,+ val lyrics: String? = null,+ val trackNumber: Int? = null,+ val trackTotal: Int? = null,+ val discNumber: Int? = null,+ val discTotal: Int? = null,+ val coverArt: ByteArray? = null,+ val coverIsPng: Boolean = false,+ /** iTunes-style custom tags, which is where the MusicBrainz identifiers live. */+ val freeform: Map<String, String> = emptyMap(),+)++/**+ * Writes iTunes-style metadata into an MP4/M4A file.+ *+ * The repo deliberately ships no ffmpeg - it was removed because the prebuilt binary+ * blocks F-Droid publication - and Android's own `MediaMuxer` cannot write these atoms,+ * so the container is edited directly.+ *+ * This matters beyond cosmetics: the MusicBrainz IDs written here are exactly what the+ * library scan reads back, so a downloaded track is recognised as owned on the next scan+ * without the app keeping a private ledger.+ */+object Mp4Tagger {++ private const val MEAN_DOMAIN = "com.apple.iTunes"++ /** Text payloads are UTF-8; the well-known type codes for the others. */+ private const val TYPE_UTF8 = 1+ private const val TYPE_BINARY = 0+ private const val TYPE_JPEG = 13+ private const val TYPE_PNG = 14++ /**+ * Returns the tagged file, or null when the input is not an MP4 this can rewrite.+ *+ * Callers fall back to the untagged bytes: a file with poor metadata is still worth+ * keeping, and every non-MP4 container YouTube can serve lands here.+ */+ fun tag(source: ByteArray, tags: Mp4Tags): ByteArray? {+ val boxes = topLevelBoxes(source) ?: return null+ val moov = boxes.firstOrNull { it.type == "moov" } ?: return null+ val mdat = boxes.firstOrNull { it.type == "mdat" }++ val newMoov = rebuildMoov(source, moov, tags) ?: return null+ val delta = newMoov.size - (moov.end - moov.start)++ // Sample offsets in `stco`/`co64` are absolute file positions. Growing `moov`+ // pushes a following `mdat` further down the file, so every offset has to move+ // with it; when `moov` already sits after the audio, nothing has shifted.+ if (mdat != null && mdat.start > moov.start && delta != 0) {+ shiftChunkOffsets(newMoov, delta.toLong())+ }++ val out = ByteArrayOutputStream(source.size + newMoov.size)+ for (box in boxes) {+ if (box.type == "moov") out.write(newMoov) else out.write(source, box.start, box.end - box.start)+ }+ return out.toByteArray()+ }++ private class Box(val type: String, val start: Int, val contentStart: Int, val end: Int)++ private fun topLevelBoxes(buf: ByteArray): List<Box>? {+ val boxes = ArrayList<Box>()+ var offset = 0+ while (offset + 8 <= buf.size) {+ val declared = readInt(buf, offset).toLong() and 0xffffffffL+ val type = String(buf, offset + 4, 4, Charsets.ISO_8859_1)+ val (contentStart, end) = when {+ declared == 1L -> {+ if (offset + 16 > buf.size) return null+ offset + 16 to (offset + readLong(buf, offset + 8)).toInt()+ }+ declared == 0L -> offset + 8 to buf.size+ declared < 8L -> return null+ else -> offset + 8 to (offset + declared).toInt()+ }+ if (end <= offset || end > buf.size) return null+ boxes.add(Box(type, offset, contentStart, end))+ offset = end+ }+ return boxes.takeIf { it.isNotEmpty() }+ }++ /** Copies `moov` through, dropping any existing `udta` and appending a freshly built one. */+ private fun rebuildMoov(source: ByteArray, moov: Box, tags: Mp4Tags): ByteArray? {+ val children = childBoxes(source, moov.contentStart, moov.end) ?: return null+ val body = ByteArrayOutputStream()+ for (child in children) {+ if (child.type == "udta") continue+ body.write(source, child.start, child.end - child.start)+ }+ body.write(buildUdta(tags))+ return box("moov", body.toByteArray())+ }++ private fun childBoxes(buf: ByteArray, start: Int, end: Int): List<Box>? {+ val boxes = ArrayList<Box>()+ var offset = start+ while (offset + 8 <= end) {+ val declared = readInt(buf, offset)+ if (declared < 8 || offset + declared > end) return null+ boxes.add(+ Box(+ String(buf, offset + 4, 4, Charsets.ISO_8859_1),+ offset,+ offset + 8,+ offset + declared,+ ),+ )+ offset += declared+ }+ return boxes+ }++ // ------------------------------------------------------------------+ // Building+ // ------------------------------------------------------------------++ private fun buildUdta(tags: Mp4Tags): ByteArray {+ val meta = ByteArrayOutputStream()+ meta.write(byteArrayOf(0, 0, 0, 0)) // `meta` is a full box: version and flags.+ meta.write(handlerBox())+ meta.write(box("ilst", buildIlst(tags)))+ return box("udta", box("meta", meta.toByteArray()))+ }++ /**+ * The `mdir`/`appl` handler.+ *+ * Players use it to recognise the metadata as iTunes-style; without it several+ * ignore the `ilst` entirely.+ */+ private fun handlerBox(): ByteArray {+ val content = ByteArrayOutputStream()+ content.write(byteArrayOf(0, 0, 0, 0)) // version and flags+ content.write(byteArrayOf(0, 0, 0, 0)) // pre_defined+ content.write("mdir".toByteArray(Charsets.ISO_8859_1))+ content.write("appl".toByteArray(Charsets.ISO_8859_1))+ content.write(ByteArray(8)) // reserved+ content.write(0) // empty handler name+ return box("hdlr", content.toByteArray())+ }++ private fun buildIlst(tags: Mp4Tags): ByteArray {+ val ilst = ByteArrayOutputStream()+ fun text(atom: String, value: String?) {+ if (!value.isNullOrBlank()) {+ ilst.write(box(atom, dataBox(TYPE_UTF8, value.toByteArray(Charsets.UTF_8))))+ }+ }++ text("\u00A9nam", tags.title)+ text("\u00A9ART", tags.artist)+ text("\u00A9alb", tags.album)+ text("aART", tags.albumArtist)+ text("\u00A9day", tags.date)+ text("\u00A9lyr", tags.lyrics)++ tags.trackNumber?.let { number ->+ val payload = ByteArray(8)+ writeShort(payload, 2, number)+ writeShort(payload, 4, tags.trackTotal ?: 0)+ ilst.write(box("trkn", dataBox(TYPE_BINARY, payload)))+ }+ tags.discNumber?.let { number ->+ val payload = ByteArray(6)+ writeShort(payload, 2, number)+ writeShort(payload, 4, tags.discTotal ?: 0)+ ilst.write(box("disk", dataBox(TYPE_BINARY, payload)))+ }+ tags.coverArt?.let { cover ->+ val type = if (tags.coverIsPng) TYPE_PNG else TYPE_JPEG+ ilst.write(box("covr", dataBox(type, cover)))+ }+ for ((name, value) in tags.freeform) {+ if (value.isNotBlank()) ilst.write(freeformBox(name, value))+ }+ return ilst.toByteArray()+ }++ private fun dataBox(type: Int, payload: ByteArray): ByteArray {+ val content = ByteArrayOutputStream(payload.size + 8)+ content.write(intBytes(type)) // version and type indicator+ content.write(ByteArray(4)) // locale+ content.write(payload)+ return box("data", content.toByteArray())+ }++ /** A `----` box: the namespace, the tag name, then the value. */+ private fun freeformBox(name: String, value: String): ByteArray {+ val content = ByteArrayOutputStream()+ content.write(box("mean", ByteArray(4) + MEAN_DOMAIN.toByteArray(Charsets.UTF_8)))+ content.write(box("name", ByteArray(4) + name.toByteArray(Charsets.UTF_8)))+ content.write(dataBox(TYPE_UTF8, value.toByteArray(Charsets.UTF_8)))+ return box("----", content.toByteArray())+ }++ private fun box(type: String, content: ByteArray): ByteArray {+ val out = ByteArrayOutputStream(content.size + 8)+ out.write(intBytes(content.size + 8))+ out.write(type.toByteArray(Charsets.ISO_8859_1))+ out.write(content)+ return out.toByteArray()+ }++ // ------------------------------------------------------------------+ // Chunk offset fixups+ // ------------------------------------------------------------------++ /** Walks the rebuilt `moov` and adds [delta] to every sample chunk offset it holds. */+ private fun shiftChunkOffsets(moov: ByteArray, delta: Long) {+ fun walk(start: Int, end: Int) {+ var offset = start+ while (offset + 8 <= end) {+ val size = readInt(moov, offset)+ if (size < 8 || offset + size > end) return+ val type = String(moov, offset + 4, 4, Charsets.ISO_8859_1)+ when (type) {+ "stco" -> {+ val count = readInt(moov, offset + 12)+ for (i in 0 until count) {+ val at = offset + 16 + i * 4+ if (at + 4 > offset + size) break+ val shifted = (readInt(moov, at).toLong() and 0xffffffffL) + delta+ writeInt(moov, at, shifted.toInt())+ }+ }+ "co64" -> {+ val count = readInt(moov, offset + 12)+ for (i in 0 until count) {+ val at = offset + 16 + i * 8+ if (at + 8 > offset + size) break+ writeLong(moov, at, readLong(moov, at) + delta)+ }+ }+ // Only the containers on the path to `stbl` are worth descending into.+ "trak", "mdia", "minf", "stbl" -> walk(offset + 8, offset + size)+ }+ offset += size+ }+ }+ walk(8, moov.size)+ }++ // ------------------------------------------------------------------++ private fun intBytes(value: Int): ByteArray = byteArrayOf(+ (value ushr 24).toByte(),+ (value ushr 16).toByte(),+ (value ushr 8).toByte(),+ value.toByte(),+ )++ private fun readInt(buf: ByteArray, offset: Int): Int =+ ((buf[offset].toInt() and 0xff) shl 24) or+ ((buf[offset + 1].toInt() and 0xff) shl 16) or+ ((buf[offset + 2].toInt() and 0xff) shl 8) or+ (buf[offset + 3].toInt() and 0xff)++ private fun writeInt(buf: ByteArray, offset: Int, value: Int) {+ buf[offset] = (value ushr 24).toByte()+ buf[offset + 1] = (value ushr 16).toByte()+ buf[offset + 2] = (value ushr 8).toByte()+ buf[offset + 3] = value.toByte()+ }++ private fun readLong(buf: ByteArray, offset: Int): Long {+ var result = 0L+ for (i in 0 until 8) result = (result shl 8) or (buf[offset + i].toLong() and 0xff)+ return result+ }++ private fun writeLong(buf: ByteArray, offset: Int, value: Long) {+ for (i in 0 until 8) buf[offset + i] = (value ushr (56 - i * 8)).toByte()+ }++ private fun writeShort(buf: ByteArray, offset: Int, value: Int) {+ buf[offset] = (value ushr 8).toByte()+ buf[offset + 1] = value.toByte()+ }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/LibraryIndex.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/LibraryIndex.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/LibraryIndex.ktnew file mode 100644index 0000000000..b30262a171--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/LibraryIndex.kt@@ -0,0 +1,79 @@+package com.vayunmathur.musicbrainz.library++import com.vayunmathur.musicbrainz.data.LocalTrack+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/**+ * An immutable view of what the user already has, built from the scanned tags.+ *+ * Held as sets rather than queried per row because the browse screens ask about every+ * track on a release as they draw it.+ */+class LibrarySnapshot(+ private val recordingIds: Set<String> = emptySet(),+ private val releaseTrackIds: Set<String> = emptySet(),+ private val releaseIds: Set<String> = emptySet(),+ private val trackKeys: Set<String> = emptySet(),+ private val albumKeys: Set<String> = emptySet(),+ val trackCount: Int = 0,+) {+ /**+ * Whether a MusicBrainz track is already on device.+ *+ * The identifier checks come first and are exact. The text fallbacks exist because+ * music that was not tagged by Picard carries no MusicBrainz IDs at all, which is+ * most libraries - without them the app would report almost everything as missing.+ */+ fun hasTrack(+ recordingId: String?,+ releaseTrackId: String?,+ artist: String?,+ album: String?,+ title: String?,+ ): Boolean {+ if (releaseTrackId != null && releaseTrackId in releaseTrackIds) return true+ if (recordingId != null && recordingId in recordingIds) return true+ MatchKeys.trackKey(artist, title)?.let { if (it in trackKeys) return true }+ MatchKeys.albumKey(album, title)?.let { if (it in albumKeys) return true }+ return false+ }++ fun hasRelease(releaseId: String?): Boolean = releaseId != null && releaseId in releaseIds++ companion object {+ val Empty = LibrarySnapshot()++ fun from(tracks: List<LocalTrack>): LibrarySnapshot = LibrarySnapshot(+ recordingIds = tracks.mapNotNullTo(HashSet()) { it.recordingId },+ releaseTrackIds = tracks.mapNotNullTo(HashSet()) { it.releaseTrackId },+ releaseIds = tracks.mapNotNullTo(HashSet()) { it.releaseId },+ trackKeys = tracks.mapNotNullTo(HashSet()) { it.matchKey },+ albumKeys = tracks.mapNotNullTo(HashSet()) { it.albumKey },+ trackCount = tracks.size,+ )+ }+}++/**+ * Process-wide holder for the scanned library.+ *+ * A singleton so the scan worker and the UI share one copy: the scan runs outside the+ * ViewModel's lifetime and the browse screens need the result the moment it lands.+ */+object LibraryIndex {+ private val _snapshot = MutableStateFlow(LibrarySnapshot.Empty)+ val snapshot: StateFlow<LibrarySnapshot> = _snapshot.asStateFlow()++ private val _scanning = MutableStateFlow(false)+ val scanning: StateFlow<Boolean> = _scanning.asStateFlow()++ fun publish(tracks: List<LocalTrack>) {+ _snapshot.value = LibrarySnapshot.from(tracks)+ }++ fun setScanning(value: Boolean) {+ _scanning.value = value+ }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/LibraryScanner.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/LibraryScanner.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/LibraryScanner.ktnew file mode 100644index 0000000000..081d60cc9d--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/LibraryScanner.kt@@ -0,0 +1,97 @@+package com.vayunmathur.musicbrainz.library++import android.content.Context+import androidx.core.net.toUri+import com.vayunmathur.library.room.buildDatabase+import com.vayunmathur.musicbrainz.data.LocalTrack+import com.vayunmathur.musicbrainz.data.MusicBrainzDatabase+import com.vayunmathur.musicbrainz.util.MusicBrainzPrefs+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * Walks the user's music folder and records what is in it.+ *+ * Deliberately tag-driven rather than a ledger of what this app downloaded: the point is+ * to recognise music the user already had, however it got there.+ *+ * Files whose size and modification time are unchanged since the last scan are skipped+ * without being reopened, which is what keeps a rescan of a large library cheap.+ */+object LibraryScanner {++ suspend fun scan(context: Context): Int = withContext(Dispatchers.IO) {+ val treeUri = MusicBrainzPrefs(context).musicFolderUri() ?: return@withContext 0+ val dao = context.buildDatabase<MusicBrainzDatabase>(dbName = DB_NAME).localTrackDao()++ LibraryIndex.setScanning(true)+ try {+ val known = dao.fingerprints().associateBy { it.documentUri }+ val files = ArrayList<DocEntry>()+ SafTree.walkFiles(context, treeUri.toUri()) { entry ->+ if (TagReader.isAudioFile(entry.name)) files.add(entry)+ }++ val seen = HashSet<String>(files.size)+ val updates = ArrayList<LocalTrack>()+ for (entry in files) {+ val key = entry.uri.toString()+ seen.add(key)+ val previous = known[key]+ if (previous != null &&+ previous.size == entry.size &&+ previous.lastModified == entry.lastModified+ ) {+ continue+ }+ val tags = TagReader.read(context, entry.uri, entry.name)+ updates.add(+ LocalTrack(+ documentUri = key,+ fileName = entry.name,+ size = entry.size,+ lastModified = entry.lastModified,+ recordingId = tags.recordingId,+ releaseId = tags.releaseId,+ releaseTrackId = tags.releaseTrackId,+ title = tags.title,+ artist = tags.artist,+ album = tags.album,+ // Files with no usable tags still get a key from the filename, which+ // is the only thing an untagged rip has to identify it.+ matchKey = MatchKeys.trackKey(+ tags.artist ?: tags.albumArtist,+ tags.title ?: entry.name.substringBeforeLast('.'),+ ),+ albumKey = MatchKeys.albumKey(tags.album, tags.title),+ ),+ )+ // Flushed in batches so an interrupted scan still leaves progress behind.+ if (updates.size >= BATCH_SIZE) {+ dao.upsertAll(updates.toList())+ updates.clear()+ }+ }++ if (updates.isNotEmpty()) dao.upsertAll(updates)++ val removed = known.keys - seen+ if (removed.isNotEmpty()) dao.deleteByUris(removed.toList())++ val all = dao.all()+ LibraryIndex.publish(all)+ all.size+ } finally {+ LibraryIndex.setScanning(false)+ }+ }++ /** Loads the last scan result so the browse screens have data before a rescan finishes. */+ suspend fun loadCached(context: Context) = withContext(Dispatchers.IO) {+ val dao = context.buildDatabase<MusicBrainzDatabase>(dbName = DB_NAME).localTrackDao()+ LibraryIndex.publish(dao.all())+ }++ const val DB_NAME = "musicbrainz-db"+ private const val BATCH_SIZE = 200+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/MatchKeys.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/MatchKeys.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/MatchKeys.ktnew file mode 100644index 0000000000..9b69af3ee7--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/MatchKeys.kt@@ -0,0 +1,70 @@+package com.vayunmathur.musicbrainz.library++import java.text.Normalizer++/**+ * Turns titles and artist names into comparison keys.+ *+ * Only files tagged by Picard carry MusicBrainz IDs, so most of a real library has to be+ * matched on text. That means deciding which differences are the same recording and which+ * are not: reissue noise like "Remastered" is dropped, while "Live", "Remix" and+ * "Acoustic" are kept, because those genuinely are different recordings and folding them+ * together would mark tracks as owned that the user does not have.+ */+object MatchKeys {++ private val NOISE_QUALIFIERS = listOf(+ "remaster", "remastered", "remastered version", "deluxe", "deluxe edition",+ "bonus track", "bonus", "explicit", "clean", "album version", "single version",+ "original mix", "mono", "stereo", "digital remaster", "anniversary edition",+ )++ private val BRACKETED = Regex("[\\[(]([^\\[\\]()]*)[\\])]")+ /** Dropped outright rather than turned into a space, so "Don't" matches "Dont". */+ private val APOSTROPHES = Regex("['\u2019\u02BC\u055A`]")+ private val NON_ALPHANUMERIC = Regex("[^\\p{L}\\p{Nd} ]")+ private val WHITESPACE = Regex("\\s+")+ private val COMBINING_MARKS = Regex("\\p{Mn}+")++ /** Splits off collaborators so "A feat. B" and "A" compare equal. */+ private val ARTIST_SEPARATORS = Regex(+ "\\s+(?:feat\\.?|featuring|ft\\.?|with|vs\\.?|&|x|and)\\s+|,\\s*",+ RegexOption.IGNORE_CASE,+ )++ fun normalize(value: String?): String? {+ if (value.isNullOrBlank()) return null+ var text = value.lowercase()+ text = BRACKETED.replace(text) { match ->+ val inner = match.groupValues[1].trim()+ if (NOISE_QUALIFIERS.any { inner.contains(it) }) "" else " $inner "+ }+ text = Normalizer.normalize(text, Normalizer.Form.NFD)+ text = COMBINING_MARKS.replace(text, "")+ text = APOSTROPHES.replace(text, "")+ text = NON_ALPHANUMERIC.replace(text, " ")+ text = WHITESPACE.replace(text, " ").trim()+ for (qualifier in NOISE_QUALIFIERS) {+ if (text.endsWith(" $qualifier")) text = text.removeSuffix(" $qualifier").trim()+ }+ return text.ifEmpty { null }+ }++ /** The first credited artist, which is the part two taggings of a track agree on. */+ fun primaryArtist(artist: String?): String? {+ if (artist.isNullOrBlank()) return null+ return ARTIST_SEPARATORS.split(artist).firstOrNull { it.isNotBlank() }?.trim()+ }++ fun trackKey(artist: String?, title: String?): String? {+ val normalizedArtist = normalize(primaryArtist(artist)) ?: return null+ val normalizedTitle = normalize(title) ?: return null+ return "$normalizedArtist\u0000$normalizedTitle"+ }++ fun albumKey(album: String?, title: String?): String? {+ val normalizedAlbum = normalize(album) ?: return null+ val normalizedTitle = normalize(title) ?: return null+ return "$normalizedAlbum\u0000$normalizedTitle"+ }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/SafTree.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/SafTree.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/SafTree.ktnew file mode 100644index 0000000000..f9e6fb741d--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/SafTree.kt@@ -0,0 +1,148 @@+package com.vayunmathur.musicbrainz.library++import android.content.Context+import android.net.Uri+import android.provider.DocumentsContract++/** One entry in the user's music folder. */+data class DocEntry(+ val documentId: String,+ val name: String,+ val uri: Uri,+ val isDirectory: Boolean,+ val size: Long,+ val lastModified: Long,+)++/**+ * Storage Access Framework access to the folder the user nominated as their music library.+ *+ * Raw [DocumentsContract] queries rather than `DocumentFile`: a library scan reads every+ * file in the tree, and `DocumentFile` costs a separate query per attribute per file.+ * Everything here blocks on the content resolver, so callers stay off the main thread.+ */+object SafTree {++ private val PROJECTION = arrayOf(+ DocumentsContract.Document.COLUMN_DOCUMENT_ID,+ DocumentsContract.Document.COLUMN_DISPLAY_NAME,+ DocumentsContract.Document.COLUMN_MIME_TYPE,+ DocumentsContract.Document.COLUMN_SIZE,+ DocumentsContract.Document.COLUMN_LAST_MODIFIED,+ )++ fun listChildren(context: Context, treeUri: Uri, parentDocumentId: String): List<DocEntry> {+ val childrenUri =+ DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, parentDocumentId)+ val result = ArrayList<DocEntry>()+ context.contentResolver.query(childrenUri, PROJECTION, null, null, null)?.use { cursor ->+ val idCol = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)+ val nameCol =+ cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)+ val mimeCol = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)+ val sizeCol = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE)+ val modCol =+ cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)+ while (cursor.moveToNext()) {+ val docId = cursor.getString(idCol) ?: continue+ val name = cursor.getString(nameCol) ?: continue+ val mime = cursor.getString(mimeCol)+ result.add(+ DocEntry(+ documentId = docId,+ name = name,+ uri = DocumentsContract.buildDocumentUriUsingTree(treeUri, docId),+ isDirectory = mime == DocumentsContract.Document.MIME_TYPE_DIR,+ size = if (cursor.isNull(sizeCol)) 0L else cursor.getLong(sizeCol),+ lastModified = if (cursor.isNull(modCol)) 0L else cursor.getLong(modCol),+ ),+ )+ }+ }+ return result+ }++ fun rootDocumentId(treeUri: Uri): String = DocumentsContract.getTreeDocumentId(treeUri)++ /**+ * Every file in the tree, depth first.+ *+ * [onFile] is called as the walk proceeds rather than the whole list being returned,+ * so a large library does not have to be held in memory at once. Directories are+ * followed only as deep as [maxDepth]; a music folder nested deeper than that is+ * almost certainly a symlink loop or a misplaced pick like the storage root.+ */+ fun walkFiles(+ context: Context,+ treeUri: Uri,+ maxDepth: Int = 8,+ onFile: (DocEntry) -> Unit,+ ) {+ val queue = ArrayDeque<Pair<String, Int>>()+ queue.add(rootDocumentId(treeUri) to 0)+ while (queue.isNotEmpty()) {+ val (docId, depth) = queue.removeFirst()+ for (entry in listChildren(context, treeUri, docId)) {+ if (entry.isDirectory) {+ if (depth < maxDepth) queue.add(entry.documentId to depth + 1)+ } else {+ onFile(entry)+ }+ }+ }+ }++ /** Finds a direct child by name, or creates it as a directory. */+ fun findOrCreateDirectory(context: Context, treeUri: Uri, parentDocumentId: String, name: String): String? {+ val existing = listChildren(context, treeUri, parentDocumentId)+ .firstOrNull { it.isDirectory && it.name.equals(name, ignoreCase = true) }+ if (existing != null) return existing.documentId+ val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, parentDocumentId)+ val created = DocumentsContract.createDocument(+ context.contentResolver,+ parentUri,+ DocumentsContract.Document.MIME_TYPE_DIR,+ name,+ ) ?: return null+ return DocumentsContract.getDocumentId(created)+ }++ /** Resolves (creating as needed) a chain of nested directories under the tree root. */+ fun ensurePath(context: Context, treeUri: Uri, segments: List<String>): String? {+ var current = rootDocumentId(treeUri)+ for (segment in segments) {+ current = findOrCreateDirectory(context, treeUri, current, segment) ?: return null+ }+ return current+ }++ /**+ * Creates a file, replacing any existing one with the same name.+ *+ * The delete-first matters: providers append " (1)" to a clashing name rather than+ * overwriting, so re-downloading a track would otherwise pile up duplicates that the+ * library scan then reports as separate copies.+ */+ fun createFile(+ context: Context,+ treeUri: Uri,+ parentDocumentId: String,+ name: String,+ mimeType: String,+ ): Uri? {+ listChildren(context, treeUri, parentDocumentId)+ .firstOrNull { !it.isDirectory && it.name == name }+ ?.let { runCatching { DocumentsContract.deleteDocument(context.contentResolver, it.uri) } }+ val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, parentDocumentId)+ return DocumentsContract.createDocument(context.contentResolver, parentUri, mimeType, name)+ }++ /** Strips the characters document providers reject, so a title can become a filename. */+ fun sanitize(name: String): String =+ name.replace(Regex("[\\\\/:*?\"<>|\\u0000-\\u001f]"), "")+ .replace(Regex("\\s+"), " ")+ .trim()+ .trimEnd('.')+ .take(120)+ .ifEmpty { "Unknown" }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/TagReader.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/TagReader.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/TagReader.ktnew file mode 100644index 0000000000..68d5ef2f28--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/library/TagReader.kt@@ -0,0 +1,466 @@+package com.vayunmathur.musicbrainz.library++import android.content.Context+import android.net.Uri+import java.io.FileInputStream+import java.io.InputStream+import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.nio.channels.FileChannel++/** The tags the library index cares about. Every field is absent on files that lack it. */+data class AudioTags(+ val title: String? = null,+ val artist: String? = null,+ val album: String? = null,+ val albumArtist: String? = null,+ val recordingId: String? = null,+ val releaseId: String? = null,+ val releaseTrackId: String? = null,+) {+ val isEmpty: Boolean+ get() = title == null && artist == null && album == null &&+ recordingId == null && releaseId == null+}++/**+ * Reads identifying tags out of audio files, so the app can tell what the user already+ * owns without keeping its own download ledger.+ *+ * There is no tag library in the repo and adding one would pull in a large third-party+ * dependency for what amounts to four container formats, so the parsers are here. Each+ * one reads only the metadata region and stops - a library scan touches every file, and+ * reading whole albums of audio to find a title would make it unusable.+ *+ * MusicBrainz IDs are the reliable signal but only Picard-tagged files carry them, so+ * plain title/artist/album are read too and the matching falls back to those.+ */+object TagReader {++ private const val MAX_MOOV_BYTES = 16 * 1024 * 1024+ private const val MAX_ID3_BYTES = 4 * 1024 * 1024+ private const val OGG_SCAN_BYTES = 128 * 1024++ private val AUDIO_EXTENSIONS = setOf(+ "mp3", "m4a", "m4b", "mp4", "aac", "flac", "ogg", "oga", "opus", "wav", "wma",+ )++ fun isAudioFile(name: String): Boolean =+ name.substringAfterLast('.', "").lowercase() in AUDIO_EXTENSIONS++ /** Returns whatever could be read; a malformed or unsupported file yields empty tags. */+ fun read(context: Context, uri: Uri, fileName: String): AudioTags = try {+ context.contentResolver.openFileDescriptor(uri, "r")?.use { pfd ->+ FileInputStream(pfd.fileDescriptor).use { input ->+ when (fileName.substringAfterLast('.', "").lowercase()) {+ "mp3", "aac" -> readId3(input)+ "m4a", "m4b", "mp4" -> readMp4(input.channel)+ "flac" -> readFlac(input)+ "ogg", "oga", "opus" -> readOgg(input)+ else -> AudioTags()+ }+ }+ } ?: AudioTags()+ } catch (_: Exception) {+ AudioTags()+ }++ // ------------------------------------------------------------------+ // MP4 / M4A+ // ------------------------------------------------------------------++ /**+ * Pulls `moov` out of the file and parses its `udta.meta.ilst` in memory.+ *+ * `moov` is walked box by box from the channel rather than read wholesale because it+ * sits after the audio data in files that were never prepared for streaming, and in+ * an album-length track that means skipping tens of megabytes to reach it.+ */+ internal fun readMp4(channel: FileChannel): AudioTags {+ val size = channel.size()+ var position = 0L+ while (position < size) {+ val header = readBoxHeader(channel, position, size) ?: break+ if (header.type == "moov") {+ val payloadSize = header.end - header.contentStart+ if (payloadSize <= 0 || payloadSize > MAX_MOOV_BYTES) return AudioTags()+ val buffer = ByteBuffer.allocate(payloadSize.toInt())+ channel.position(header.contentStart)+ while (buffer.hasRemaining()) {+ if (channel.read(buffer) < 0) return AudioTags()+ }+ return parseIlst(findIlst(buffer.array()) ?: return AudioTags())+ }+ position = header.end+ }+ return AudioTags()+ }++ private class BoxHeader(val type: String, val contentStart: Long, val end: Long)++ private fun readBoxHeader(channel: FileChannel, position: Long, fileSize: Long): BoxHeader? {+ if (position + 8 > fileSize) return null+ val head = ByteBuffer.allocate(8)+ channel.position(position)+ while (head.hasRemaining()) {+ if (channel.read(head) < 0) return null+ }+ head.flip()+ val declared = head.int.toLong() and 0xffffffffL+ val type = String(ByteArray(4) { head.get() }, Charsets.ISO_8859_1)+ return when {+ declared == 1L -> {+ val ext = ByteBuffer.allocate(8)+ channel.position(position + 8)+ while (ext.hasRemaining()) {+ if (channel.read(ext) < 0) return null+ }+ ext.flip()+ val large = ext.long+ if (large < 16) null+ else BoxHeader(type, position + 16, (position + large).coerceAtMost(fileSize))+ }+ declared == 0L -> BoxHeader(type, position + 8, fileSize)+ declared < 8L -> null+ else -> BoxHeader(type, position + 8, (position + declared).coerceAtMost(fileSize))+ }+ }++ /**+ * Locates the `ilst` payload inside a `moov` blob.+ *+ * `meta` is a full box, so its four version/flags bytes have to be stepped over before+ * its children start - treating it like a plain container is the usual reason a tag+ * parser sees nothing here.+ */+ private fun findIlst(moov: ByteArray): ByteArray? {+ fun descend(start: Int, end: Int, path: List<String>): ByteArray? {+ var offset = start+ while (offset + 8 <= end) {+ val size = readInt(moov, offset)+ val type = String(moov, offset + 4, 4, Charsets.ISO_8859_1)+ val boxEnd = if (size == 0) end else offset + size+ if (size < 8 || boxEnd > end) return null+ if (type == path.first()) {+ val contentStart = if (type == "meta") offset + 12 else offset + 8+ if (path.size == 1) {+ return moov.copyOfRange(contentStart.coerceAtMost(boxEnd), boxEnd)+ }+ descend(contentStart, boxEnd, path.drop(1))?.let { return it }+ }+ offset = boxEnd+ }+ return null+ }+ return descend(0, moov.size, listOf("udta", "meta", "ilst"))+ }++ private fun parseIlst(ilst: ByteArray): AudioTags {+ val values = HashMap<String, String>()+ var offset = 0+ while (offset + 8 <= ilst.size) {+ val size = readInt(ilst, offset)+ if (size < 8 || offset + size > ilst.size) break+ val type = String(ilst, offset + 4, 4, Charsets.ISO_8859_1)+ val entryEnd = offset + size+ if (type == "----") {+ parseFreeform(ilst, offset + 8, entryEnd)?.let { (key, value) -> values[key] = value }+ } else {+ dataPayload(ilst, offset + 8, entryEnd)?.let { values[type] = it }+ }+ offset = entryEnd+ }+ return AudioTags(+ title = values["\u00A9nam"],+ artist = values["\u00A9ART"],+ album = values["\u00A9alb"],+ albumArtist = values["aART"],+ recordingId = values["MusicBrainz Track Id"],+ releaseId = values["MusicBrainz Album Id"],+ releaseTrackId = values["MusicBrainz Release Track Id"],+ )+ }++ /** Reads the `mean`/`name`/`data` triplet an iTunes-style custom tag is made of. */+ private fun parseFreeform(buf: ByteArray, start: Int, end: Int): Pair<String, String>? {+ var offset = start+ var name: String? = null+ var value: String? = null+ while (offset + 8 <= end) {+ val size = readInt(buf, offset)+ if (size < 8 || offset + size > end) break+ when (String(buf, offset + 4, 4, Charsets.ISO_8859_1)) {+ "name" -> if (offset + 12 <= offset + size) {+ name = String(buf, offset + 12, size - 12, Charsets.UTF_8)+ }+ "data" -> if (offset + 16 <= offset + size) {+ value = String(buf, offset + 16, size - 16, Charsets.UTF_8)+ }+ }+ offset += size+ }+ val key = name ?: return null+ val v = value ?: return null+ return key to v+ }++ private fun dataPayload(buf: ByteArray, start: Int, end: Int): String? {+ var offset = start+ while (offset + 8 <= end) {+ val size = readInt(buf, offset)+ if (size < 8 || offset + size > end) return null+ if (String(buf, offset + 4, 4, Charsets.ISO_8859_1) == "data") {+ val payloadStart = offset + 16+ val payloadEnd = offset + size+ if (payloadStart >= payloadEnd) return null+ return String(buf, payloadStart, payloadEnd - payloadStart, Charsets.UTF_8)+ .trim()+ .ifEmpty { null }+ }+ offset += size+ }+ return null+ }++ // ------------------------------------------------------------------+ // MP3 / ID3v2+ // ------------------------------------------------------------------++ internal fun readId3(input: InputStream): AudioTags {+ val header = input.readNBytesCompat(10)+ if (header.size < 10) return AudioTags()+ if (String(header, 0, 3, Charsets.ISO_8859_1) != "ID3") return AudioTags()+ val major = header[3].toInt() and 0xff+ if (major < 3) return AudioTags()+ val tagSize = synchsafe(header, 6)+ if (tagSize <= 0 || tagSize > MAX_ID3_BYTES) return AudioTags()+ val body = input.readNBytesCompat(tagSize)++ val values = HashMap<String, String>()+ var recordingId: String? = null+ var offset = 0+ while (offset + 10 <= body.size) {+ val id = String(body, offset, 4, Charsets.ISO_8859_1)+ if (id[0] == '\u0000') break+ // v2.4 made frame sizes synchsafe; v2.3 left them as plain big-endian ints.+ val frameSize = if (major >= 4) synchsafe(body, offset + 4) else readInt(body, offset + 4)+ if (frameSize <= 0 || offset + 10 + frameSize > body.size) break+ val frameStart = offset + 10+ when (id) {+ "TIT2", "TPE1", "TALB", "TPE2" ->+ decodeTextFrame(body, frameStart, frameSize)?.let { values[id] = it }+ "TXXX" -> decodeUserTextFrame(body, frameStart, frameSize)+ ?.let { (key, value) -> values[key] = value }+ "UFID" -> {+ val ownerEnd = body.indexOfZero(frameStart, frameStart + frameSize)+ if (ownerEnd > 0) {+ val owner = String(body, frameStart, ownerEnd - frameStart, Charsets.ISO_8859_1)+ if (owner.contains("musicbrainz.org")) {+ recordingId = String(+ body,+ ownerEnd + 1,+ frameStart + frameSize - ownerEnd - 1,+ Charsets.ISO_8859_1,+ ).trim().ifEmpty { null }+ }+ }+ }+ }+ offset = frameStart + frameSize+ }+ return AudioTags(+ title = values["TIT2"],+ artist = values["TPE1"],+ album = values["TALB"],+ albumArtist = values["TPE2"],+ recordingId = recordingId ?: values["MusicBrainz Track Id"],+ releaseId = values["MusicBrainz Album Id"],+ releaseTrackId = values["MusicBrainz Release Track Id"],+ )+ }++ private fun decodeTextFrame(buf: ByteArray, start: Int, size: Int): String? {+ if (size < 2) return null+ return decodeString(buf, start + 1, start + size, buf[start].toInt() and 0xff)+ .trimEnd('\u0000')+ .trim()+ .ifEmpty { null }+ }++ /** `TXXX` is a description and a value, both in the frame's declared encoding. */+ private fun decodeUserTextFrame(buf: ByteArray, start: Int, size: Int): Pair<String, String>? {+ if (size < 2) return null+ val encoding = buf[start].toInt() and 0xff+ val end = start + size+ val wide = encoding == 1 || encoding == 2+ var separator = -1+ var scan = start + 1+ while (scan < end) {+ if (wide) {+ if (scan + 1 < end && buf[scan].toInt() == 0 && buf[scan + 1].toInt() == 0) {+ separator = scan+ break+ }+ scan += 2+ } else {+ if (buf[scan].toInt() == 0) {+ separator = scan+ break+ }+ scan+++ }+ }+ if (separator < 0) return null+ val description = decodeString(buf, start + 1, separator, encoding).trim()+ val valueStart = separator + if (wide) 2 else 1+ val value = decodeString(buf, valueStart, end, encoding).trimEnd('\u0000').trim()+ if (description.isEmpty() || value.isEmpty()) return null+ return description to value+ }++ private fun decodeString(buf: ByteArray, start: Int, end: Int, encoding: Int): String {+ if (start >= end) return ""+ val charset = when (encoding) {+ 1 -> Charsets.UTF_16+ 2 -> Charsets.UTF_16BE+ 3 -> Charsets.UTF_8+ else -> Charsets.ISO_8859_1+ }+ return String(buf, start, end - start, charset)+ }++ // ------------------------------------------------------------------+ // FLAC / Ogg (Vorbis comments)+ // ------------------------------------------------------------------++ internal fun readFlac(input: InputStream): AudioTags {+ val magic = input.readNBytesCompat(4)+ if (magic.size < 4 || String(magic, Charsets.ISO_8859_1) != "fLaC") return AudioTags()+ while (true) {+ val header = input.readNBytesCompat(4)+ if (header.size < 4) return AudioTags()+ val flags = header[0].toInt() and 0xff+ val isLast = flags and 0x80 != 0+ val blockType = flags and 0x7f+ val length = ((header[1].toInt() and 0xff) shl 16) or+ ((header[2].toInt() and 0xff) shl 8) or+ (header[3].toInt() and 0xff)+ if (length < 0 || length > MAX_ID3_BYTES) return AudioTags()+ val block = input.readNBytesCompat(length)+ if (block.size < length) return AudioTags()+ if (blockType == 4) return parseVorbisComments(block, 0)+ if (isLast) return AudioTags()+ }+ }++ /**+ * Ogg keeps its comment header in the second packet, so the pages are reassembled+ * until that packet is complete. Only the head of the file is scanned - if the+ * comments are not there the file is not one we can read anyway.+ */+ internal fun readOgg(input: InputStream): AudioTags {+ val data = input.readNBytesCompat(OGG_SCAN_BYTES)+ var offset = 0+ var packetIndex = 0+ val packet = java.io.ByteArrayOutputStream()+ while (offset + 27 <= data.size) {+ if (String(data, offset, 4, Charsets.ISO_8859_1) != "OggS") break+ val segmentCount = data[offset + 26].toInt() and 0xff+ val tableStart = offset + 27+ if (tableStart + segmentCount > data.size) break+ var payloadSize = 0+ var packetEnds = false+ for (i in 0 until segmentCount) {+ val segment = data[tableStart + i].toInt() and 0xff+ payloadSize += segment+ if (segment < 255) packetEnds = true+ }+ val payloadStart = tableStart + segmentCount+ if (payloadStart + payloadSize > data.size) break+ packet.write(data, payloadStart, payloadSize)+ if (packetEnds) {+ val bytes = packet.toByteArray()+ packet.reset()+ if (packetIndex == 1) return parseOggCommentPacket(bytes)+ packetIndex+++ }+ offset = payloadStart + payloadSize+ }+ return AudioTags()+ }++ private fun parseOggCommentPacket(packet: ByteArray): AudioTags = when {+ packet.size > 8 && String(packet, 0, 8, Charsets.ISO_8859_1) == "OpusTags" ->+ parseVorbisComments(packet, 8)+ packet.size > 7 && String(packet, 1, 6, Charsets.ISO_8859_1) == "vorbis" ->+ parseVorbisComments(packet, 7)+ else -> AudioTags()+ }++ private fun parseVorbisComments(buf: ByteArray, start: Int): AudioTags {+ var offset = start+ if (offset + 4 > buf.size) return AudioTags()+ val vendorLength = readIntLe(buf, offset)+ offset += 4 + vendorLength+ if (offset + 4 > buf.size || vendorLength < 0) return AudioTags()+ val count = readIntLe(buf, offset)+ offset += 4+ if (count < 0 || count > 10_000) return AudioTags()+ val values = HashMap<String, String>()+ repeat(count) {+ if (offset + 4 > buf.size) return@repeat+ val length = readIntLe(buf, offset)+ offset += 4+ if (length < 0 || offset + length > buf.size) return@repeat+ val entry = String(buf, offset, length, Charsets.UTF_8)+ offset += length+ val separator = entry.indexOf('=')+ if (separator > 0) {+ values[entry.substring(0, separator).uppercase()] = entry.substring(separator + 1)+ }+ }+ return AudioTags(+ title = values["TITLE"],+ artist = values["ARTIST"],+ album = values["ALBUM"],+ albumArtist = values["ALBUMARTIST"],+ recordingId = values["MUSICBRAINZ_TRACKID"],+ releaseId = values["MUSICBRAINZ_ALBUMID"],+ releaseTrackId = values["MUSICBRAINZ_RELEASETRACKID"],+ )+ }++ // ------------------------------------------------------------------++ private fun readInt(buf: ByteArray, offset: Int): Int =+ ((buf[offset].toInt() and 0xff) shl 24) or+ ((buf[offset + 1].toInt() and 0xff) shl 16) or+ ((buf[offset + 2].toInt() and 0xff) shl 8) or+ (buf[offset + 3].toInt() and 0xff)++ private fun readIntLe(buf: ByteArray, offset: Int): Int =+ ByteBuffer.wrap(buf, offset, 4).order(ByteOrder.LITTLE_ENDIAN).int++ /** ID3 sizes drop the high bit of each byte so they can never look like a frame sync. */+ private fun synchsafe(buf: ByteArray, offset: Int): Int =+ ((buf[offset].toInt() and 0x7f) shl 21) or+ ((buf[offset + 1].toInt() and 0x7f) shl 14) or+ ((buf[offset + 2].toInt() and 0x7f) shl 7) or+ (buf[offset + 3].toInt() and 0x7f)++ private fun ByteArray.indexOfZero(from: Int, to: Int): Int {+ for (i in from until minOf(to, size)) if (this[i].toInt() == 0) return i+ return -1+ }++ private fun InputStream.readNBytesCompat(count: Int): ByteArray {+ val out = ByteArray(count)+ var read = 0+ while (read < count) {+ val n = read(out, read, count - read)+ if (n < 0) break+ read += n+ }+ return if (read == count) out else out.copyOf(read)+ }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ArtistScreen.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ArtistScreen.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ArtistScreen.ktnew file mode 100644index 0000000000..6174c169bf--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ArtistScreen.kt@@ -0,0 +1,171 @@+package com.vayunmathur.musicbrainz.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.ErrorState+import com.vayunmathur.library.ui.IconCheckCircle+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.LoadingState+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.musicbrainz.R+import com.vayunmathur.musicbrainz.Route+import com.vayunmathur.musicbrainz.util.ArtistUiState+import com.vayunmathur.musicbrainz.util.MusicBrainzActions+import com.vayunmathur.musicbrainz.util.MusicBrainzViewModel+import com.vayunmathur.musicbrainz.util.ReleaseGroupUiState++@Composable+fun ArtistPage(backStack: NavBackStack<Route>, viewModel: MusicBrainzViewModel, artistId: String) {+ LaunchedEffect(artistId) { viewModel.loadArtist(artistId) }+ val state by viewModel.artist.collectAsStateWithLifecycle()+ ArtistScreen(state, viewModel, backStack)+}++/** An artist's discography, newest first. */+@Composable+fun ArtistScreen(+ state: ArtistUiState,+ actions: MusicBrainzActions,+ backStack: NavBackStack<Route>,+) {+ AppScaffold(+ title = state.name.ifBlank { stringResource(R.string.artist) },+ backStack = backStack,+ ) { padding ->+ when {+ state.loading -> LoadingState(Modifier.fillMaxSize().padding(padding))+ state.error != null -> ErrorState(+ title = stringResource(R.string.load_failed),+ modifier = Modifier.fillMaxSize().padding(padding),+ message = state.error,+ )+ state.releaseGroups.isEmpty() -> EmptyState(+ title = stringResource(R.string.no_releases),+ modifier = Modifier.fillMaxSize().padding(padding),+ )+ else -> LazyColumn(+ Modifier.fillMaxSize(),+ contentPadding = PaddingValues(+ top = padding.calculateTopPadding(),+ bottom = padding.calculateBottomPadding() + 16.dp,+ ),+ ) {+ state.subtitle?.let { subtitle ->+ item {+ Text(+ subtitle,+ modifier = Modifier.fillMaxWidth().padding(16.dp),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ items(state.releaseGroups, key = { it.id }) { group ->+ ListItem(+ headlineContent = { Text(group.title) },+ modifier = Modifier+ .fillMaxWidth()+ .clickable { backStack.add(Route.ReleaseGroup(group.id)) },+ supportingContent = { SecondaryText(group.subtitle) },+ leadingContent = { CoverArtImage(group.coverUrl) },+ )+ }+ }+ }+ }+}++@Composable+fun ReleaseGroupPage(+ backStack: NavBackStack<Route>,+ viewModel: MusicBrainzViewModel,+ releaseGroupId: String,+) {+ LaunchedEffect(releaseGroupId) { viewModel.loadReleaseGroup(releaseGroupId) }+ val state by viewModel.releaseGroup.collectAsStateWithLifecycle()+ ReleaseGroupScreen(state, viewModel, backStack)+}++/**+ * The editions of one album.+ *+ * MusicBrainz models an album as a release group containing many releases - reissues,+ * regional pressings, deluxe editions - and their tracklists genuinely differ, so the+ * choice is the user's rather than a guess.+ */+@Composable+fun ReleaseGroupScreen(+ state: ReleaseGroupUiState,+ actions: MusicBrainzActions,+ backStack: NavBackStack<Route>,+) {+ AppScaffold(+ title = state.title.ifBlank { stringResource(R.string.album) },+ backStack = backStack,+ ) { padding ->+ when {+ state.loading -> LoadingState(Modifier.fillMaxSize().padding(padding))+ state.error != null -> ErrorState(+ title = stringResource(R.string.load_failed),+ modifier = Modifier.fillMaxSize().padding(padding),+ message = state.error,+ )+ else -> LazyColumn(+ Modifier.fillMaxSize(),+ contentPadding = PaddingValues(+ top = padding.calculateTopPadding(),+ bottom = padding.calculateBottomPadding() + 16.dp,+ ),+ ) {+ item {+ Column(Modifier.fillMaxWidth().padding(16.dp)) {+ CoverArtImage(state.coverUrl, size = 160)+ Text(state.artist, style = MaterialTheme.typography.titleMedium)+ Text(+ pluralStringResource(+ R.plurals.editions_count,+ state.releases.size,+ state.releases.size,+ ),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ items(state.releases, key = { it.id }) { release ->+ ListItem(+ headlineContent = { Text(release.title) },+ modifier = Modifier+ .fillMaxWidth()+ .clickable { backStack.add(Route.Release(release.id)) },+ supportingContent = { SecondaryText(release.subtitle) },+ leadingContent = { CoverArtImage(release.coverUrl) },+ trailingContent = if (release.onDevice) {+ { IconCheckCircle(tint = MaterialTheme.colorScheme.primary) }+ } else {+ null+ },+ )+ }+ }+ }+ }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/Components.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/Components.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/Components.ktnew file mode 100644index 0000000000..adccaf55b6--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/Components.kt@@ -0,0 +1,107 @@+package com.vayunmathur.musicbrainz.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalInspectionMode+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.IconAlbum+import com.vayunmathur.library.ui.IconCheckCircle+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconDownload+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text+import com.vayunmathur.musicbrainz.R+import com.vayunmathur.musicbrainz.download.DownloadItem+import com.vayunmathur.musicbrainz.download.DownloadState++/**+ * Cover art with a placeholder behind it.+ *+ * The Cover Art Archive has no image for a good share of releases, and the request that+ * finds that out is a redirect chain to archive.org, so the placeholder is what most+ * lists actually show while scrolling.+ */+@Composable+fun CoverArtImage(url: String?, modifier: Modifier = Modifier, size: Int = 56) {+ Surface(+ modifier = modifier.size(size.dp).clip(RoundedCornerShape(6.dp)),+ color = MaterialTheme.colorScheme.surfaceVariant,+ ) {+ Box(contentAlignment = Alignment.Center) {+ IconAlbum(tint = MaterialTheme.colorScheme.onSurfaceVariant)+ // Previews render without a network, and the loader would just log failures.+ if (url != null && !LocalInspectionMode.current) {+ AsyncImage(+ model = url,+ contentDescription = null,+ modifier = Modifier.size(size.dp),+ contentScale = ContentScale.Crop,+ )+ }+ }+ }+}++/**+ * The trailing control on a track row: a tick when it is already owned, a progress+ * spinner while it is being fetched, otherwise a download button.+ */+@Composable+fun TrackTrailing(+ onDevice: Boolean,+ download: DownloadItem?,+ onDownload: () -> Unit,+ onCancel: () -> Unit,+) {+ when {+ onDevice -> IconCheckCircle(tint = MaterialTheme.colorScheme.primary)+ download == null || download.state == DownloadState.Failed ->+ IconButton(onDownload) { IconDownload() }+ download.state == DownloadState.Done -> IconCheckCircle(tint = MaterialTheme.colorScheme.primary)+ else -> Row(verticalAlignment = Alignment.CenterVertically) {+ if (download.state == DownloadState.Downloading && download.progress > 0f) {+ CircularProgressIndicator({ download.progress }, modifier = Modifier.size(20.dp))+ } else {+ CircularProgressIndicator(modifier = Modifier.size(20.dp))+ }+ IconButton(onCancel) { IconClose() }+ }+ }+}++/** Formats a track length as `m:ss`, or blank when MusicBrainz has no duration on file. */+@Composable+fun durationLabel(durationMs: Int?): String {+ if (durationMs == null || durationMs <= 0) return ""+ val totalSeconds = durationMs / 1000+ return stringResource(+ R.string.duration_format,+ totalSeconds / 60,+ "%02d".format(totalSeconds % 60),+ )+}++@Composable+fun SecondaryText(text: String?, modifier: Modifier = Modifier) {+ if (!text.isNullOrBlank()) {+ Text(+ text,+ modifier = modifier,+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ maxLines = 2,+ )+ }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/DownloadsScreen.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/DownloadsScreen.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/DownloadsScreen.ktnew file mode 100644index 0000000000..9a73ed63ae--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/DownloadsScreen.kt@@ -0,0 +1,94 @@+package com.vayunmathur.musicbrainz.ui++import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconDownload+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.musicbrainz.R+import com.vayunmathur.musicbrainz.Route+import com.vayunmathur.musicbrainz.download.DownloadItem+import com.vayunmathur.musicbrainz.download.DownloadState+import com.vayunmathur.musicbrainz.util.MusicBrainzActions+import com.vayunmathur.musicbrainz.util.MusicBrainzViewModel++@Composable+fun DownloadsPage(backStack: NavBackStack<Route>, viewModel: MusicBrainzViewModel) {+ val downloads by viewModel.downloads.collectAsStateWithLifecycle()+ DownloadsScreen(downloads.values.toList(), viewModel, backStack)+}++/** The download queue, so a long album fetch is visible from anywhere in the app. */+@Composable+fun DownloadsScreen(+ downloads: List<DownloadItem>,+ actions: MusicBrainzActions,+ backStack: NavBackStack<Route>,+) {+ AppScaffold(+ title = stringResource(R.string.downloads),+ backStack = backStack,+ actions = {+ if (downloads.any { it.state == DownloadState.Done || it.state == DownloadState.Failed }) {+ IconButton(actions::clearFinishedDownloads) { IconDelete() }+ }+ },+ ) { padding ->+ if (downloads.isEmpty()) {+ EmptyState(+ title = stringResource(R.string.no_downloads),+ modifier = Modifier.fillMaxSize().padding(padding),+ message = stringResource(R.string.no_downloads_message),+ icon = { IconDownload() },+ )+ return@AppScaffold+ }+ LazyColumn(Modifier.fillMaxSize().padding(padding)) {+ items(downloads, key = { it.id }) { item ->+ ListItem(+ headlineContent = { Text(item.title) },+ modifier = Modifier.fillMaxWidth(),+ supportingContent = {+ SecondaryText(+ listOfNotNull(+ item.artist.ifBlank { null },+ item.album,+ item.error ?: stringResource(item.state.labelRes()),+ ).joinToString(" \u00B7 "),+ )+ },+ trailingContent = {+ TrackTrailing(+ onDevice = item.state == DownloadState.Done,+ download = item,+ onDownload = {},+ onCancel = { actions.cancelDownload(item.id) },+ )+ },+ )+ }+ }+ }+}++private fun DownloadState.labelRes(): Int = when (this) {+ DownloadState.Queued -> R.string.state_queued+ DownloadState.Searching -> R.string.state_searching+ DownloadState.Downloading -> R.string.state_downloading+ DownloadState.Tagging -> R.string.state_tagging+ DownloadState.Done -> R.string.state_done+ DownloadState.Failed -> R.string.state_failed+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ReleaseScreen.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ReleaseScreen.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ReleaseScreen.ktnew file mode 100644index 0000000000..8b4b102bf7--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ReleaseScreen.kt@@ -0,0 +1,131 @@+package com.vayunmathur.musicbrainz.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.ErrorState+import com.vayunmathur.library.ui.ExtendedFloatingActionButton+import com.vayunmathur.library.ui.IconDownload+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.LoadingState+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.musicbrainz.R+import com.vayunmathur.musicbrainz.Route+import com.vayunmathur.musicbrainz.util.MusicBrainzActions+import com.vayunmathur.musicbrainz.util.MusicBrainzViewModel+import com.vayunmathur.musicbrainz.util.ReleaseUiState++@Composable+fun ReleasePage(backStack: NavBackStack<Route>, viewModel: MusicBrainzViewModel, releaseId: String) {+ LaunchedEffect(releaseId) { viewModel.loadRelease(releaseId) }+ val state by viewModel.release.collectAsStateWithLifecycle()+ ReleaseScreen(state, viewModel, backStack)+}++/**+ * One release and its tracklist, with what the user already owns marked.+ *+ * The ownership marks come from the tags read off the user's own files, so music that+ * arrived from anywhere - ripped, bought, downloaded elsewhere - counts.+ */+@Composable+fun ReleaseScreen(+ state: ReleaseUiState,+ actions: MusicBrainzActions,+ backStack: NavBackStack<Route>,+) {+ val missing = state.tracks.size - state.ownedCount+ AppScaffold(+ title = state.title.ifBlank { stringResource(R.string.album) },+ backStack = backStack,+ floatingActionButton = {+ if (missing > 0) {+ ExtendedFloatingActionButton(+ text = {+ Text(pluralStringResource(R.plurals.download_missing, missing, missing))+ },+ icon = { IconDownload() },+ onClick = actions::downloadRelease,+ )+ }+ },+ ) { padding ->+ when {+ state.loading -> LoadingState(Modifier.fillMaxSize().padding(padding))+ state.error != null -> ErrorState(+ title = stringResource(R.string.load_failed),+ modifier = Modifier.fillMaxSize().padding(padding),+ message = state.error,+ )+ else -> LazyColumn(+ Modifier.fillMaxSize(),+ contentPadding = PaddingValues(+ top = padding.calculateTopPadding(),+ bottom = padding.calculateBottomPadding() + 88.dp,+ ),+ ) {+ item {+ Column(Modifier.fillMaxWidth().padding(16.dp)) {+ CoverArtImage(state.coverUrl, size = 160)+ Text(state.artist, style = MaterialTheme.typography.titleMedium)+ SecondaryText(state.subtitle)+ Text(+ stringResource(+ R.string.owned_count,+ state.ownedCount,+ state.tracks.size,+ ),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.primary,+ )+ }+ }+ items(state.tracks, key = { it.releaseTrackId }) { track ->+ ListItem(+ headlineContent = { Text(track.title) },+ modifier = Modifier.fillMaxWidth(),+ supportingContent = {+ SecondaryText(+ listOfNotNull(+ track.artist.ifBlank { null },+ durationLabel(track.durationMs).ifBlank { null },+ track.download?.error,+ ).joinToString(" \u00B7 "),+ )+ },+ leadingContent = {+ Text(+ track.position.toString(),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ },+ trailingContent = {+ TrackTrailing(+ onDevice = track.onDevice,+ download = track.download,+ onDownload = { actions.downloadTrack(track) },+ onCancel = { ac
Diff truncated.