react-native-audio-browser 0.2.0-next.44 → 0.2.0-next.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,26 +4,39 @@ package com.audiobrowser.browser
4
4
  * Token → resolved browse artwork, the [com.audiobrowser.util.ArtworkContentProvider]'s only data
5
5
  * source. Stores plain resolved data (no Track / Nitro handles), so unlike
6
6
  * [ArtworkResolutionRegistry] it pins no JS closures and can be sized generously. Cleared when the
7
- * browser config is replaced or content is invalidated. Thread-safe: written from browse
8
- * coroutines, read from the provider's IO scope.
7
+ * browser config is replaced or content is invalidated, except for the [pin]ned entries: browse
8
+ * items are rebuilt after a clear, but the media items already in the queue keep their URIs.
9
+ * Thread-safe: written from browse coroutines, read from the provider's IO scope.
9
10
  */
10
- class BrowseArtworkRegistry(private val maxEntries: Int = 2048) {
11
+ class BrowseArtworkRegistry(
12
+ private val maxEntries: Int = 2048,
13
+ private val maxPinnedEntries: Int = 2048,
14
+ ) {
11
15
 
12
- private val entries =
13
- object : LinkedHashMap<String, ResolvedArtwork>(16, 0.75f, true) {
14
- override fun removeEldestEntry(
15
- eldest: MutableMap.MutableEntry<String, ResolvedArtwork>
16
- ): Boolean = size > maxEntries
17
- }
16
+ private val entries = lruMap(maxEntries)
17
+ private val pinned = lruMap(maxPinnedEntries)
18
18
 
19
19
  @Synchronized
20
20
  fun register(token: String, artwork: ResolvedArtwork) {
21
21
  entries[token] = artwork
22
22
  }
23
23
 
24
- @Synchronized fun lookup(token: String): ResolvedArtwork? = entries[token]
24
+ /** Registers artwork that a [clear] keeps. */
25
+ @Synchronized
26
+ fun pin(token: String, artwork: ResolvedArtwork) {
27
+ pinned[token] = artwork
28
+ }
29
+
30
+ @Synchronized fun lookup(token: String): ResolvedArtwork? = entries[token] ?: pinned[token]
25
31
 
26
32
  @Synchronized fun clear() = entries.clear()
33
+
34
+ private fun lruMap(maxEntries: Int) =
35
+ object : LinkedHashMap<String, ResolvedArtwork>(16, 0.75f, true) {
36
+ override fun removeEldestEntry(
37
+ eldest: MutableMap.MutableEntry<String, ResolvedArtwork>
38
+ ): Boolean = size > maxEntries
39
+ }
27
40
  }
28
41
 
29
42
  /** Everything the provider needs to fetch one artwork, resolved at browse-build time. */
@@ -20,9 +20,11 @@ import com.audiobrowser.browser.untitledSection
20
20
  import com.audiobrowser.extension.indexOfTappedTrack
21
21
  import com.audiobrowser.extension.toTrack
22
22
  import com.audiobrowser.navigationErrorFor
23
+ import com.audiobrowser.util.Automotive
23
24
  import com.audiobrowser.util.BrowserPathHelper
24
25
  import com.audiobrowser.util.RatingFavorites
25
26
  import com.audiobrowser.util.TrackFactory
27
+ import com.audiobrowser.util.isAutomotive
26
28
  import com.google.common.collect.ImmutableList
27
29
  import com.google.common.util.concurrent.FutureCallback
28
30
  import com.google.common.util.concurrent.Futures
@@ -61,7 +63,7 @@ import timber.log.Timber
61
63
  */
62
64
  class MediaSessionCallback(private val player: Player) :
63
65
  MediaLibraryService.MediaLibrarySession.Callback {
64
- internal val commandManager = MediaSessionCommandManager()
66
+ internal val commandManager = MediaSessionCommandManager(player.context.isAutomotive)
65
67
  private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
66
68
 
67
69
  // Track which controllers are subscribed to which media IDs.
@@ -119,8 +121,8 @@ class MediaSessionCallback(private val player: Player) :
119
121
  /**
120
122
  * Builds the gate tile from a per-request chrome: while a gate is active, tabs stay visible but a
121
123
  * gated browse/search level serves this single tile (see the gate checks in [onGetChildren] /
122
- * [onGetSearchResult]). Same shape as the error tiles — non-browsable, non-playable — and
123
- * deliberately NOT accompanied by a SessionError: a gate is deliberate app state, not a failure.
124
+ * [onGetSearchResult]). Same shape as the error tiles, and deliberately NOT accompanied by a
125
+ * SessionError: a gate is deliberate app state, not a failure.
124
126
  */
125
127
  private fun createGateMediaItem(gate: Gate): MediaItem =
126
128
  createErrorMediaItem(
@@ -259,102 +261,126 @@ class MediaSessionCallback(private val player: Player) :
259
261
  "onGetChildren: {parentId: $parentId, page: $page, pageSize: $pageSize, isSpecialPath: ${BrowserPathHelper.isSpecialPath(parentId)} }"
260
262
  )
261
263
  return scope.future {
262
- val audioBrowser =
263
- player.awaitBrowser().also { Timber.d("Browser ready, proceeding with onGetChildren") }
264
- val browserManager = audioBrowser.browserManager
265
-
266
- // While a gate is active, tabs stay visible (the root keeps serving them below) but each
267
- // non-root level is resolved per request: a gated path — including re-queries of the gate
268
- // tile's own sentinel path — serves the single gate tile, so drilling into it re-shows the
269
- // message instead of dead-ending in "No items"; an allowed path falls through to real
270
- // children. Checked before the offline guard: gated content isn't coming back with
271
- // connectivity, so the gate copy is the truer message.
272
- if (parentId != BrowserPathHelper.ROOT_PATH) {
273
- val outcome =
274
- audioBrowser.gateDecision(
275
- NativeGateRequest(reason = GateReason.BROWSE, path = parentId, search = null)
276
- )
277
- if (outcome.gated) {
278
- audioBrowser.onGate(GateEvent(GateReason.BROWSE))
279
- // gateDecision guarantees non-null chrome on a gated decision (override → default →
280
- // built-in).
281
- return@future LibraryResult.ofItemList(
282
- ImmutableList.of(createGateMediaItem(outcome.chrome!!)),
283
- params,
284
- )
264
+ children(session, browser, parentId, page, pageSize, params).also {
265
+ if (parentId == BrowserPathHelper.ROOT_PATH && page == 0) {
266
+ rootTile = deadEndTileOf(it.value.orEmpty())
285
267
  }
286
268
  }
269
+ }
270
+ }
287
271
 
288
- // A drill-in on the error / offline / empty tile returns nothing (see isDeadEndPath). For
289
- // the offline tile, re-send the alert when still offline so a tap surfaces the explanation
290
- // again — but only then, since these paths are also re-queried by notifyChildrenChanged
291
- // (e.g. when connectivity returns) without any user action.
292
- if (BrowserPathHelper.isDeadEndPath(parentId)) {
293
- if (parentId == BrowserPathHelper.OFFLINE_PATH && !player.networkMonitor.isOnline.value) {
294
- sendBrowseError(session, browser, offline = true)
295
- }
296
- return@future LibraryResult.ofItemList(ImmutableList.of<MediaItem>(), params)
297
- }
272
+ /**
273
+ * The tile the root last served in place of its tabs, or null. Android Automotive OS shows such a
274
+ * root as one tab that drills into the tile's sentinel path (see [deadEndChildren]).
275
+ */
276
+ @Volatile private var rootTile: MediaItem? = null
298
277
 
299
- if (
300
- !player.networkMonitor.isOnline.value && browserManager.config.androidControllerOfflineError
301
- ) {
302
- Timber.w("Network offline - returning error message for: $parentId")
303
- sendBrowseError(session, browser, offline = true)
304
- return@future LibraryResult.ofItemList(
305
- ImmutableList.of(
306
- createOfflineMediaItem(audioBrowser.resolveFormattedError(offlineError(), parentId))
307
- ),
278
+ private suspend fun children(
279
+ session: MediaLibraryService.MediaLibrarySession,
280
+ browser: MediaSession.ControllerInfo,
281
+ parentId: String,
282
+ page: Int,
283
+ pageSize: Int,
284
+ params: MediaLibraryService.LibraryParams?,
285
+ ): LibraryResult<ImmutableList<MediaItem>> {
286
+ val audioBrowser =
287
+ player.awaitBrowser().also { Timber.d("Browser ready, proceeding with onGetChildren") }
288
+ val browserManager = audioBrowser.browserManager
289
+
290
+ // While a gate is active, tabs stay visible (the root keeps serving them below) but each
291
+ // non-root level is resolved per request: a gated path — including re-queries of the gate
292
+ // tile's own sentinel path — serves the single gate tile, so drilling into it re-shows the
293
+ // message instead of dead-ending in "No items"; an allowed path falls through to real
294
+ // children. Checked before the offline guard: gated content isn't coming back with
295
+ // connectivity, so the gate copy is the truer message.
296
+ if (parentId != BrowserPathHelper.ROOT_PATH) {
297
+ val outcome =
298
+ audioBrowser.gateDecision(
299
+ NativeGateRequest(reason = GateReason.BROWSE, path = parentId, search = null)
300
+ )
301
+ if (outcome.gated) {
302
+ audioBrowser.onGate(GateEvent(GateReason.BROWSE))
303
+ // gateDecision guarantees non-null chrome on a gated decision (override → default →
304
+ // built-in).
305
+ return LibraryResult.ofItemList(
306
+ ImmutableList.of(createGateMediaItem(outcome.chrome!!)),
308
307
  params,
309
308
  )
310
309
  }
310
+ }
311
311
 
312
- try {
313
- val children =
314
- if (parentId == BrowserPathHelper.ROOT_PATH) {
315
- // Disabled tabs hide (Track.disabled) — filtered before the four-tab cap so an
316
- // unavailable tab never costs an available one its slot.
317
- val tabs = browserManager.queryTabs().filterNot { it.disabled == true }
318
- if (tabs.size > 4) {
319
- Timber.w(
320
- "Root has ${tabs.size} tabs; dropping ${tabs.size - 4} (Android Auto root limit)"
321
- )
322
- }
323
- toFlatMediaItems(tabs.take(4))
324
- } else {
325
- // Section styles arrive page-folded (`section ?? page`, ADR 0011).
326
- val resolvedTrack = browserManager.resolve(parentId)
327
- val sections =
328
- resolvedTrack.styleResolvedSections()
329
- ?: throw IllegalStateException("Expected browsed ResolvedTrack to have sections")
330
- browserManager.warnIfGridPageLacksPromise(parentId, sections)
331
- // A page with no children resolved fine, so it raises no SessionError and no event —
332
- // notifyChildrenChanged re-queries these paths without any user action. It serves the
333
- // app's path-aware `empty-content` copy as one inert tile (ADR 0001) instead of
334
- // Android Auto's bare "No items".
335
- browseLevelItems(toMediaItems(sections)) {
336
- audioBrowser.resolveFormattedError(emptyContentError(), parentId)
337
- }
338
- }
312
+ // For the offline tile, re-send the alert when still offline so a tap surfaces the
313
+ // explanation again — but only then, since these paths are also re-queried by
314
+ // notifyChildrenChanged (e.g. when connectivity returns) without any user action.
315
+ if (BrowserPathHelper.isDeadEndPath(parentId)) {
316
+ val offline = !player.networkMonitor.isOnline.value
317
+ if (parentId == BrowserPathHelper.OFFLINE_PATH && offline) {
318
+ sendBrowseError(session, browser, offline = true)
319
+ }
320
+ return LibraryResult.ofItemList(
321
+ deadEndChildren(parentId, rootTile, Automotive.device, offline),
322
+ params,
323
+ )
324
+ }
339
325
 
340
- LibraryResult.ofItemList(ImmutableList.copyOf(children.paginate(page, pageSize)), params)
341
- } catch (e: Exception) {
342
- // A cancelled browse (controller disconnected) is not a failure — don't render it as an
343
- // error tile. awaitBrowser's TimeoutCancellationException IS a real failure, keep that.
344
- if (e is CancellationException && e !is TimeoutCancellationException) throw e
345
- Timber.e(e, "Error getting children for parentId: $parentId")
346
- // A tile rather than a bare ofError() — see createErrorMediaItem and
347
- // https://github.com/androidx/media/issues/2901
348
- sendBrowseError(session, browser, offline = false)
349
- LibraryResult.ofItemList(
350
- ImmutableList.of(
351
- createBrowseErrorMediaItem(
352
- audioBrowser.resolveFormattedError(navigationErrorFor(e), parentId)
326
+ if (
327
+ !player.networkMonitor.isOnline.value && browserManager.config.androidControllerOfflineError
328
+ ) {
329
+ Timber.w("Network offline - returning error message for: $parentId")
330
+ sendBrowseError(session, browser, offline = true)
331
+ return LibraryResult.ofItemList(
332
+ ImmutableList.of(
333
+ createOfflineMediaItem(audioBrowser.resolveFormattedError(offlineError(), parentId))
334
+ ),
335
+ params,
336
+ )
337
+ }
338
+
339
+ return try {
340
+ val children =
341
+ if (parentId == BrowserPathHelper.ROOT_PATH) {
342
+ // Disabled tabs hide (Track.disabled) — filtered before the four-tab cap so an
343
+ // unavailable tab never costs an available one its slot.
344
+ val tabs = browserManager.queryTabs().filterNot { it.disabled == true }
345
+ if (tabs.size > 4) {
346
+ Timber.w(
347
+ "Root has ${tabs.size} tabs; dropping ${tabs.size - 4} (Android Auto root limit)"
353
348
  )
354
- ),
355
- params,
356
- )
357
- }
349
+ }
350
+ toFlatMediaItems(tabs.take(4))
351
+ } else {
352
+ // Section styles arrive page-folded (`section ?? page`, ADR 0011).
353
+ val resolvedTrack = browserManager.resolve(parentId)
354
+ val sections =
355
+ resolvedTrack.styleResolvedSections()
356
+ ?: throw IllegalStateException("Expected browsed ResolvedTrack to have sections")
357
+ browserManager.warnIfGridPageLacksPromise(parentId, sections)
358
+ // A page with no children resolved fine, so it raises no SessionError and no event —
359
+ // notifyChildrenChanged re-queries these paths without any user action. It serves the
360
+ // app's path-aware `empty-content` copy as one inert tile (ADR 0001) instead of
361
+ // Android Auto's bare "No items".
362
+ browseLevelItems(toMediaItems(sections)) {
363
+ audioBrowser.resolveFormattedError(emptyContentError(), parentId)
364
+ }
365
+ }
366
+
367
+ LibraryResult.ofItemList(ImmutableList.copyOf(children.paginate(page, pageSize)), params)
368
+ } catch (e: Exception) {
369
+ // A cancelled browse (controller disconnected) is not a failure — don't render it as an
370
+ // error tile. awaitBrowser's TimeoutCancellationException IS a real failure, keep that.
371
+ if (e is CancellationException && e !is TimeoutCancellationException) throw e
372
+ Timber.e(e, "Error getting children for parentId: $parentId")
373
+ // A tile rather than a bare ofError() — see createErrorMediaItem and
374
+ // https://github.com/androidx/media/issues/2901
375
+ sendBrowseError(session, browser, offline = false)
376
+ LibraryResult.ofItemList(
377
+ ImmutableList.of(
378
+ createBrowseErrorMediaItem(
379
+ audioBrowser.resolveFormattedError(navigationErrorFor(e), parentId)
380
+ )
381
+ ),
382
+ params,
383
+ )
358
384
  }
359
385
  }
360
386
 
@@ -1020,10 +1046,35 @@ class MediaSessionCallback(private val player: Player) :
1020
1046
  }
1021
1047
 
1022
1048
  /**
1023
- * Builds a non-browsable, non-playable [MediaItem] used to surface an error inside an Android Auto
1024
- * / AAOS browse list. Rendered as a greyed-out, non-interactive tile, which is the only
1025
- * side-effect-free way to communicate a browse failure to legacy controllers (Media3 drops
1026
- * [LibraryResult.ofError] on the legacy browse bridge, leaving an empty "No items" screen).
1049
+ * What a drill-in on a tile's sentinel path serves. Nothing, so Android Auto, which drills into a
1050
+ * tile whatever its flags, dead-ends at "No items" rather than stacking error pages. On Android
1051
+ * Automotive OS, a root that serves only a tile shows as one tab that drills in here, and an empty
1052
+ * level as "Media isn't available for this list", so there the [rootTile] is served again, unless
1053
+ * it is the offline tile and the device is back online.
1054
+ */
1055
+ internal fun deadEndChildren(
1056
+ parentId: String,
1057
+ rootTile: MediaItem?,
1058
+ automotive: Boolean,
1059
+ offline: Boolean,
1060
+ ): List<MediaItem> =
1061
+ listOfNotNull(
1062
+ rootTile?.takeIf {
1063
+ automotive &&
1064
+ it.mediaId == parentId &&
1065
+ (parentId != BrowserPathHelper.OFFLINE_PATH || offline)
1066
+ }
1067
+ )
1068
+
1069
+ /** The single tile of a level that serves one in place of its items, or null. */
1070
+ internal fun deadEndTileOf(items: List<MediaItem>): MediaItem? =
1071
+ items.singleOrNull()?.takeIf { BrowserPathHelper.isDeadEndPath(it.mediaId) }
1072
+
1073
+ /**
1074
+ * Builds a non-playable [MediaItem] used to surface an error inside an Android Auto / AAOS browse
1075
+ * list. Rendered as a tile, which is the only side-effect-free way to communicate a browse failure
1076
+ * to legacy controllers (Media3 drops [LibraryResult.ofError] on the legacy browse bridge, leaving
1077
+ * an empty "No items" screen).
1027
1078
  *
1028
1079
  * Tiles are the only in-browse error signal that exists. Verified on a head unit (2026-06): the
1029
1080
  * Android Auto browse list renders no error text for a transient [SessionError], for sticky
@@ -1038,10 +1089,9 @@ internal fun createErrorMediaItem(mediaId: String, title: String, subtitle: Stri
1038
1089
  MediaMetadata.Builder()
1039
1090
  .setTitle(title)
1040
1091
  .setSubtitle(subtitle)
1041
- // Android Auto ignores these flags and drills into a tapped tile anyway; onGetChildren
1042
- // returns an empty list for the sentinel paths, so it dead-ends at "No Items" rather
1043
- // than stacking error pages.
1044
- .setIsBrowsable(false)
1092
+ // Android Automotive OS's car media app drops an item that is neither browsable nor
1093
+ // playable; Android Auto ignores these flags and drills in anyway (see deadEndChildren).
1094
+ .setIsBrowsable(Automotive.device)
1045
1095
  .setIsPlayable(false)
1046
1096
  .build()
1047
1097
  )
@@ -1061,8 +1111,7 @@ private fun createErrorMediaItem(mediaId: String, formatted: FormattedNavigation
1061
1111
  /**
1062
1112
  * Builds the empty tile from the app's formatted `empty-content` copy for the page's path, so an
1063
1113
  * empty Favorites tab and an empty search can be worded apart (ADR 0001). Same shape as the error
1064
- * tiles — non-browsable, non-playable — and deliberately NOT accompanied by a SessionError: an
1065
- * empty page is a successful resolve.
1114
+ * tiles, and deliberately NOT accompanied by a SessionError: an empty page is a successful resolve.
1066
1115
  */
1067
1116
  internal fun createEmptyMediaItem(formatted: FormattedNavigationError): MediaItem =
1068
1117
  createErrorMediaItem(BrowserPathHelper.EMPTY_PATH, formatted)
@@ -11,6 +11,12 @@ import com.margelo.nitro.audiobrowser.RemoteButton
11
11
  import com.margelo.nitro.audiobrowser.RemoteButtonLayout
12
12
  import timber.log.Timber
13
13
 
14
+ /** Previous in BACK or Next in FORWARD: where a controller draws its own skip buttons. */
15
+ private val SlottedButton.isStandardSkip: Boolean
16
+ get() =
17
+ (button == RemoteButton.SKIP_TO_PREVIOUS && slot == ButtonSlot.BACK) ||
18
+ (button == RemoteButton.SKIP_TO_NEXT && slot == ButtonSlot.FORWARD)
19
+
14
20
  /**
15
21
  * A slot's Media3 preference list: the requested slot, then OVERFLOW as a fallback.
16
22
  *
@@ -49,7 +55,7 @@ internal fun media3SlotsFor(slot: ButtonSlot): IntArray =
49
55
  * extras that Android Auto and the Android 13+ system media controls read. Publishing
50
56
  * per-controller instead would reach neither, since Android Auto connects as a legacy controller.
51
57
  */
52
- class MediaSessionCommandManager {
58
+ class MediaSessionCommandManager(private val automotive: Boolean) {
53
59
 
54
60
  companion object {
55
61
  private const val CUSTOM_ACTION_JUMP_BACKWARD = "JUMP_BACKWARD"
@@ -432,6 +438,10 @@ class MediaSessionCommandManager {
432
438
  * Assembles the CommandButtons for an already-derived slot layout (see [deriveButtonSlots] — the
433
439
  * slots are pre-filtered by Capability).
434
440
  *
441
+ * On Android Automotive OS, Previous in BACK and Next in FORWARD are left out, so Media3 keeps
442
+ * them as the PlaybackState's standard skip actions, which the car media app draws either side of
443
+ * play/pause. Sent as buttons they arrive as custom actions, which it places by its own rules.
444
+ *
435
445
  * Each button gets its requested slot followed by OVERFLOW as a fallback. `slots` is an ordered
436
446
  * preference list, and every surface caps how many buttons it renders — a head unit, the
437
447
  * collapsed notification, the Android 13+ media controls all truncate differently. Without a
@@ -441,7 +451,9 @@ class MediaSessionCommandManager {
441
451
  slots: List<SlottedButton>,
442
452
  favorited: Boolean?,
443
453
  ): List<CommandButton> =
444
- slots.map { (button, slot) ->
445
- buttonFor(button, favorited).setSlots(*media3SlotsFor(slot)).build()
446
- }
454
+ slots
455
+ .filterNot { automotive && it.isStandardSkip }
456
+ .map { (button, slot) ->
457
+ buttonFor(button, favorited).setSlots(*media3SlotsFor(slot)).build()
458
+ }
447
459
  }
@@ -107,9 +107,16 @@ class NowPlayingUpdater(private val surface: NowPlayingSurface, private val scop
107
107
  private var lastPublished: Published? = null
108
108
 
109
109
  /**
110
- * The track identity (id-or-src, falling back to path — same key as [Published]) whose
111
- * now-playing artwork has been resolved (or is being resolved), so a `nowPlayingArtwork` resolve
112
- * runs once per track — id-less tracks included — instead of on every render.
110
+ * The identity of the track whose formatter result the surface shows. While it is the rendering
111
+ * track's, [render] skips its interim default stamp, which would flash the track's own line over
112
+ * the formatter's until the async result lands.
113
+ */
114
+ private var formattedTrackId: String? = null
115
+
116
+ /**
117
+ * The track identity (id-or-src, falling back to path) whose now-playing artwork has been
118
+ * resolved (or is being resolved), so a `nowPlayingArtwork` resolve runs once per track — id-less
119
+ * tracks included — instead of on every render.
113
120
  */
114
121
  private var artworkResolvedForTrack: String? = null
115
122
 
@@ -153,30 +160,62 @@ class NowPlayingUpdater(private val surface: NowPlayingSurface, private val scop
153
160
  flash = null
154
161
  }
155
162
 
156
- /** Gets the current now playing metadata (flash/override if set, else track metadata). */
163
+ /**
164
+ * The lines the now-playing surface shows for the current track, formatter output included; until
165
+ * the track's first render, and while [enabled] is false, the flash, override or track fields.
166
+ */
157
167
  fun getNowPlaying(): NowPlayingMetadata? {
158
168
  val track = surface.currentTrack ?: return null
169
+ val published =
170
+ lastPublished?.takeIf { enabled && it.trackId == (track.identity ?: track.path) }
171
+ ?: return layered(track)
172
+ return metadata(track, published.title, published.secondaryLine, published.album)
173
+ }
174
+
175
+ private fun layered(track: Track): NowPlayingMetadata {
159
176
  val flash = flash
160
177
  val override = override
178
+ return metadata(
179
+ track,
180
+ flash?.title ?: override?.title ?: track.title,
181
+ flash?.artist ?: override?.artist ?: track.artist,
182
+ flash?.album ?: override?.album ?: track.album,
183
+ )
184
+ }
161
185
 
162
- return NowPlayingMetadata(
186
+ private fun metadata(track: Track, title: String?, artist: String?, album: String?) =
187
+ NowPlayingMetadata(
163
188
  elapsedTime = null,
164
- title = flash?.title ?: override?.title ?: track.title,
165
- album = flash?.album ?: override?.album ?: track.album,
166
- artist = flash?.artist ?: override?.artist ?: track.artist,
189
+ title = title,
190
+ album = album,
191
+ artist = artist,
167
192
  duration = track.duration,
168
193
  artwork = track.artwork?.url,
169
194
  description = track.description,
170
195
  mediaId = track.src ?: track.path,
171
196
  genre = track.genre,
172
197
  )
198
+
199
+ /**
200
+ * Forgets what the surface shows, so the next [render] stamps the lines and artwork in full: a
201
+ * media item that becomes current, or is replaced in place, carries its own default lines and
202
+ * artwork.
203
+ */
204
+ fun forgetPublished() {
205
+ lastPublished = null
206
+ formattedTrackId = null
207
+ artworkResolvedForTrack = null
173
208
  }
174
209
 
175
- /** Clears override, flash, and timed metadata on track change (PlayerListener transition). */
210
+ /**
211
+ * Clears override, flash, timed metadata and the published lines on track change (PlayerListener
212
+ * transition).
213
+ */
176
214
  fun clearOverride() {
177
215
  override = null
178
216
  cancelFlash()
179
217
  latestTimedMetadata = null
218
+ forgetPublished()
180
219
  }
181
220
 
182
221
  /**
@@ -193,8 +232,9 @@ class NowPlayingUpdater(private val surface: NowPlayingSurface, private val scop
193
232
  /**
194
233
  * Renders the current now playing metadata to the surface. Flash wins while active (formatter
195
234
  * skipped entirely so its async result can't land on top); otherwise the override-or-track
196
- * default is stamped immediately and a configured formatter customizes it asynchronously, guarded
197
- * by track identity and [renderGeneration].
235
+ * default is stamped immediately, unless a formatter result for the track is already up, and a
236
+ * configured formatter customizes it asynchronously, guarded by track identity and
237
+ * [renderGeneration].
198
238
  */
199
239
  fun render() {
200
240
  val index = surface.currentIndex ?: return
@@ -220,15 +260,19 @@ class NowPlayingUpdater(private val surface: NowPlayingSurface, private val scop
220
260
  activeFlash.artist ?: defaultSecondary,
221
261
  activeFlash.album ?: defaultAlbum,
222
262
  )
263
+ formattedTrackId = null
223
264
  return
224
265
  }
225
266
 
226
- // Apply the default immediately so the now-playing never lags a track/status change.
227
- applyFields(index, track, defaultTitle, defaultSecondary, defaultAlbum)
267
+ // Apply the default immediately so the now-playing never lags a track/status change, unless
268
+ // a formatter result for this track is on the surface.
269
+ val activeFormatter = if (enabled) formatter else null
270
+ if (activeFormatter == null || formattedTrackId != (track.identity ?: track.path)) {
271
+ applyFields(index, track, defaultTitle, defaultSecondary, defaultAlbum)
272
+ }
228
273
 
229
274
  // If a formatter is configured, let it customize the fields asynchronously. Falls back to the
230
275
  // default on null/throw.
231
- val activeFormatter = if (enabled) formatter else null
232
276
  if (activeFormatter != null) {
233
277
  val capturedId = track.src ?: track.path
234
278
  // Gate the raw load-control signal to the buffering state so `stalled` is correct on its
@@ -266,8 +310,7 @@ class NowPlayingUpdater(private val surface: NowPlayingSurface, private val scop
266
310
  val current = surface.currentTrack
267
311
  val currentIdx = surface.currentIndex
268
312
  if (
269
- formatted != null &&
270
- current != null &&
313
+ current != null &&
271
314
  currentIdx != null &&
272
315
  (current.src ?: current.path) == capturedId &&
273
316
  renderGeneration == generation
@@ -275,10 +318,11 @@ class NowPlayingUpdater(private val surface: NowPlayingSurface, private val scop
275
318
  applyFields(
276
319
  currentIdx,
277
320
  current,
278
- formatted.title ?: defaultTitle,
279
- formatted.artist ?: defaultSecondary,
280
- formatted.album ?: defaultAlbum,
321
+ formatted?.title ?: defaultTitle,
322
+ formatted?.artist ?: defaultSecondary,
323
+ formatted?.album ?: defaultAlbum,
281
324
  )
325
+ formattedTrackId = if (formatted != null) current.identity ?: current.path else null
282
326
  }
283
327
  }
284
328
  }
@@ -297,11 +341,14 @@ class NowPlayingUpdater(private val surface: NowPlayingSurface, private val scop
297
341
  // (and flicker Android Auto / now-playing) for no visible change. Keyed on the track identity
298
342
  // so a new track with a coincidentally identical line still publishes.
299
343
  val published = Published(index, track.identity ?: track.path, title, secondaryLine, album)
300
- if (published == lastPublished) return
344
+ val unchanged = published == lastPublished
301
345
  lastPublished = published
346
+ if (unchanged) return
302
347
 
303
348
  surface.stampFields(index, track, title, secondaryLine, album)
304
- getNowPlaying()?.let { surface.emitNowPlayingChanged(it) }
349
+ surface.emitNowPlayingChanged(
350
+ if (enabled) metadata(track, title, secondaryLine, album) else layered(track)
351
+ )
305
352
 
306
353
  // Resolve the now-playing-only artwork (lock screen / notification / Android Auto
307
354
  // now-playing), keyed on track id so it runs once per track and not on every render.