@file:androidx.annotation.OptIn(markerClass = [androidx.media3.common.util.UnstableApi::class]) package link.roadio.riff.player.playback import android.app.Notification import android.app.NotificationManager import android.content.ComponentName import android.graphics.Bitmap import android.graphics.Color import android.graphics.drawable.BitmapDrawable import android.media.MediaMetadata import android.net.Uri import android.os.SystemClock import android.util.Log import androidx.media3.common.MediaItem import androidx.media3.common.Player import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.source.DefaultMediaSourceFactory import androidx.media3.exoplayer.source.MediaSource import androidx.media3.exoplayer.source.SilenceMediaSource import androidx.media3.session.MediaController import androidx.media3.session.SessionToken import androidx.test.platform.app.InstrumentationRegistry import link.roadio.riff.indexer.core.media.MediaId import link.roadio.riff.player.artwork.ArtworkResolution import link.roadio.riff.player.artwork.PlayerArtworkLoader import link.roadio.riff.player.library.PlaybackCatalogTrack import link.roadio.riff.player.library.PlayerLibraryProjection import link.roadio.riff.player.library.PlayerPlaybackCatalog import link.roadio.riff.player.storage.PlaybackCheckpoint import link.roadio.riff.player.storage.PlaybackQueueKind import link.roadio.riff.player.storage.PlaybackQueueOccurrence import link.roadio.riff.player.storage.PlaybackQueueSnapshot import link.roadio.riff.ui.ArtworkUiState import link.roadio.riff.ui.BrowserItem import link.roadio.riff.ui.BrowserKind import link.roadio.riff.ui.PlaybackSourceRef import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference import android.media.session.MediaController as PlatformController import android.media.session.MediaSession as PlatformSession /** Exercises Android's posted notification and its platform session token on the real playback service. */ class PlaybackNotificationInstrumentedTest { private val inst = InstrumentationRegistry.getInstrumentation() private val context = inst.targetContext private val titles = listOf("Riff Atlas", "Riff Orbit", "Riff Transit") private val albums = listOf("Atlas Album", "Orbit Album", "") private val source = titles.indices.map { PlaybackSourceRef(100L + it, 1, emptyList()) } private val artist = "Riff Ensemble" private fun field(name: String) = RiffPlaybackService::class.java.getDeclaredField(name).apply { isAccessible = true } private fun await( label: String, read: () -> Boolean, ) { val end = SystemClock.elapsedRealtime() + 12_000 do { var ready = false inst.runOnMainSync { ready = read() } if (ready) return SystemClock.sleep(30) } while (SystemClock.elapsedRealtime() < end) throw AssertionError(label) } private fun prepared(): PreparedQueue { val media = titles.indices.map { MediaId(40L + it) } val rows = titles.mapIndexed { i, title -> BrowserItem("track-$i", title, BrowserKind.TRACK, mediaId = media[i], artist = artist, album = albums[i]) } val catalog = object : PlayerPlaybackCatalog { override val generation = 0L override val projection = PlayerLibraryProjection() override fun lookup( mediaId: MediaId, contextKey: String?, ordinal: Int, ): PlaybackCatalogTrack { val i = media.indexOf(mediaId) return PlaybackCatalogTrack(rows[i], listOf(source[i]), emptyMap()) } } return prepareQueue( PlaybackQueueSnapshot( 17, PlaybackQueueKind.MANUAL, 1, false, media.mapIndexed { i, id -> PlaybackQueueOccurrence(21L + i, i, i, id) }, PlaybackCheckpoint(21), ), catalog, ) } private fun hold(stage: String) { Log.i("RiffNotificationProof", stage) val ms = InstrumentationRegistry.getArguments().getString("widgetHoldMs")?.toLongOrNull() ?: 0L SystemClock.sleep(ms.coerceIn(0L, 60_000L)) } @Suppress("DEPRECATION") private fun shows( index: Int, color: Int?, ): Boolean { val manager = context.getSystemService(NotificationManager::class.java) val notifications = manager.activeNotifications.filter { it.notification.extras.containsKey(Notification.EXTRA_MEDIA_SESSION) } val notice = notifications.singleOrNull()?.notification ?: return false val extras = notice.extras val token = extras.getParcelable(Notification.EXTRA_MEDIA_SESSION) ?: return false val controller = PlatformController(context, token) val metadata = controller.metadata ?: return false val cover = metadata.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART) ?: metadata.getBitmap(MediaMetadata.METADATA_KEY_ART) ?: metadata.getBitmap(MediaMetadata.METADATA_KEY_DISPLAY_ICON) val icon = (notice.getLargeIcon()?.loadDrawable(context) as? BitmapDrawable)?.bitmap return controller.packageName == context.packageName && extras.getCharSequence(Notification.EXTRA_TITLE)?.toString() == titles[index] && extras.getCharSequence(Notification.EXTRA_TEXT)?.toString() == artist && extras.getCharSequence(Notification.EXTRA_SUB_TEXT)?.toString().orEmpty() == albums[index] && metadata.getString(MediaMetadata.METADATA_KEY_TITLE) == titles[index] && metadata.getString(MediaMetadata.METADATA_KEY_ARTIST) == artist && metadata.getString(MediaMetadata.METADATA_KEY_ALBUM).orEmpty() == albums[index] && icon?.getPixel(icon.width / 2, icon.height / 2) == color && cover?.getPixel(cover.width / 2, cover.height / 2) == color && !notice.actions.isNullOrEmpty() } @Test fun lateCoverAndBufferedTransitionsReachTheSamePlatformNotification() { val future = MediaController .Builder( context, SessionToken(context, ComponentName(context, RiffPlaybackService::class.java)), ).buildAsync() future.get(15, TimeUnit.SECONDS) val owner = PlayerPlaybackBridge::class.java.getDeclaredField("owner").apply { isAccessible = true } val gates = listOf(CountDownLatch(1), CountDownLatch(1)) val bitmaps = listOf(Color.RED, Color.BLUE).map { color -> Bitmap.createBitmap(512, 320, Bitmap.Config.ARGB_8888).apply { eraseColor(color) } } try { await("Playback service initialization") { owner.get(PlayerPlaybackBridge) is RiffPlaybackService } val service = owner.get(PlayerPlaybackBridge) as RiffPlaybackService val exo = field("exoPlayer").get(service) as ExoPlayer val prepared = prepared() val factory = object : MediaSource.Factory by DefaultMediaSourceFactory(context) { override fun createMediaSource(mediaItem: MediaItem): MediaSource = SilenceMediaSource(180_000_000L) } val timeline = QueueMediaSource(prepared, factory) val loader = PlayerArtworkLoader( { selected, _ -> val i = source.indexOf(selected) val art = bitmaps.getOrNull(i) gates.getOrNull(i)?.await(30, TimeUnit.SECONDS) ArtworkResolution(ArtworkUiState(selected.bindingId, art)) }, timeoutMs = 35_000L, onSessionArtworkReady = service::sessionArtworkReady, ) val bindingType = RiffPlaybackService::class.java.declaredClasses.single { it.simpleName == "ResolvedBinding" } val constructor = bindingType.declaredConstructors.single().apply { isAccessible = true } val select = service.javaClass .getDeclaredMethod("selectArtwork", Long::class.javaObjectType, Long::class.javaObjectType) .apply { isAccessible = true } inst.runOnMainSync { (field("artworkLoader").get(service) as PlayerArtworkLoader).close() field("artworkLoader").set(service, loader) field("installingQueue").setBoolean(service, true) field("preparedQueue").set(service, prepared) field("queueMediaSource").set(service, timeline) @Suppress("UNCHECKED_CAST") (field("executionPlan").get(service) as AtomicReference).set(prepared.plan) @Suppress("UNCHECKED_CAST") val bindings = field("resolvedBindings").get(service) as ConcurrentHashMap for ((i, src) in source.withIndex()) { bindings[21L + i] = constructor.newInstance(17L, 21L + i, MediaId(40L + i), src, Uri.parse("content://fixture/$i")) } exo.setMediaSource(timeline) exo.prepare() exo.play() select.invoke(service, 17L, 21L) } await("Initial platform tags and blank cover") { shows(0, null) } gates[0].countDown() await("Late first cover in both notification and session") { shows(0, Color.RED) && exo.isPlaying } hold("atlas-red") inst.runOnMainSync { exo.seekTo(1, 0L) } await("Buffered transition cleared the previous cover") { shows(1, null) } gates[1].countDown() await("Second cover with the second title and album") { shows(1, Color.BLUE) } hold("orbit-blue") inst.runOnMainSync { exo.seekTo(2, 0L) } await("Track with neither album nor cover cleared both fields") { shows(2, null) } hold("transit-empty") inst.runOnMainSync { assertTrue(exo.isPlaying) assertEquals(2, exo.currentMediaItemIndex) exo.pause() } } finally { gates.forEach(CountDownLatch::countDown) inst.runOnMainSync { MediaController.releaseFuture(future) } } } }