cast: various fixes
- Commit
42df528f5ccdf0f3612d3828b722c0da0de0200f- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-24 04:38 UTC (3 months ago)
- Parents
349aa65
Diff
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.ktindex 131c1b6ead..c2cd760449 100644--- a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt@@ -35,8 +35,19 @@ import kotlinx.serialization.json.Json * [PlayMedia.startPositionMs] arrive with it. A version-5 TV would drop every command and report no * state: a session that streams perfectly with a dead remote, which is worse than a refusal for * exactly the reason `MIN_CAST_VERSION_CODE`'s own KDoc gives.+ *+ * 7 gives the television something to *show*. [NowPlaying] carries the title, the author, an artwork+ * resource id and the lyrics that [PlayMedia] deliberately left on the phone, back when the phone was+ * the player. It is a new message rather than fields on [PlayMedia] because metadata is state and+ * [PlayMedia] is a command - see [NowPlaying] - and it is sent for a mirrored session as well as a+ * served one, because an encoded video was every bit as anonymous on screen as a served track.+ *+ * **This one cannot be additive**, which is the whole reason for the bump. [ControlCodec.decode]+ * collapses "a type this build does not know" into the same null as "malformed", and every caller+ * reads null as a dead session - so a version-6 television would not ignore `NOW_PLAYING`, it would+ * hang up mid-track. Refusing at the handshake is the honest version of that. */-const val PROTOCOL_VERSION = 6+const val PROTOCOL_VERSION = 7 /** The mDNS service type the TV registers and the phone browses for. */ const val MACAST_SERVICE_TYPE = "_macast._tcp"@@ -58,6 +69,7 @@ const val MACAST_SERVICE_TYPE = "_macast._tcp" * VIDEO_CODEC_CONFIG ─────────────────► (AV1 only, and repeated on every PLI) * … RTP over UDP … * PLAYBACK_STATE ─────────────────────► (app content only, ~2/s while it plays)+ * NOW_PLAYING ────────────────────────► (title and author; no resource id to name) * ◄───────────── PLAYBACK_COMMAND (the TV remote, whenever it is pressed) * BYE ─────────────────────────────────► * ```@@ -69,6 +81,7 @@ const val MACAST_SERVICE_TYPE = "_macast._tcp" * CONTENT_SESSION ─────────────────────► (proxy host, port, cert fingerprint, token) * ◄───────────── CONTENT_READY (accepted, or refused with a reason) * PLAY_MEDIA ──────────────────────────► (which resource, and from what position)+ * NOW_PLAYING ─────────────────────────► (title, author, cover id, lyrics; ≥1 per track) * … the TV fetches byte ranges over HTTPS and decodes them itself … * PLAYBACK_COMMAND ───────────────────► (the phone's transport, wherever it was pressed) * ◄───────────── PLAYBACK_STATE (the TV's own player, ~2/s while it plays)@@ -408,7 +421,10 @@ data class ContentReady( * * [resourceId] is the app's own name for it, appended to the proxy's path; the phone maps it back to * a file descriptor when the TV asks. Sent again for each new item, which is how a queue advances -- * the queue itself stays on the phone, because it owns the artwork, the metadata and the ordering.+ * the queue itself stays on the phone, because it owns the ordering.+ *+ * The artwork and the metadata used to stay there too, and no longer do: see [NowPlaying], which+ * carries them as a separate message correlated back to this one by [resourceId]. */ @Serializable @SerialName("PLAY_MEDIA")@@ -434,6 +450,92 @@ data class PlayMedia( val startPositionMs: Long = 0, ) : ControlMessage +/**+ * What is playing, for the screen the user is actually looking at.+ *+ * **A separate message rather than fields on [PlayMedia], because metadata is state and [PlayMedia]+ * is a command.** Welded onto the command, metadata could only change by re-issuing it - which+ * restarts the track, so late-arriving artwork or lyrics that took a moment to read could not be+ * delivered at all. Split, the text goes out at once (the phone already has it in hand when it+ * decides what to play) and the cover follows when its file exists. That sequencing is not a nicety:+ * an [artworkResourceId] cannot honestly be announced before the resource is registered and its+ * bytes are on disk, because the TV fetches it immediately and an unoffered id is a `404`.+ *+ * **Sent for either kind of session, which is why it is not part of [ContentSession] either.** A+ * served session and a mirrored one differ in who holds the player, and not at all in whether the+ * user would like to know what they are listening to: an encoded video is as anonymous on screen as+ * a served track was. So this is the one metadata message, and the two paths differ only in what they+ * can fill in - see [resourceId].+ *+ * A full snapshot that replaces wholesale, and sent more than once per item - the same discipline+ * [PlaybackState] follows, and for the same reason: there is nothing to resynchronise.+ */+@Serializable+@SerialName("NOW_PLAYING")+data class NowPlaying(+ /**+ * The [PlayMedia.resourceId] this describes, or empty when there is no resource to name.+ *+ * **A correlation key for a served session, and it is load-bearing there.** The channel is+ * ordered but the *producers* are not: a metadata job for track A can finish after track B's+ * [PlayMedia] has gone out, and a television that rendered whatever arrived last would paint A's+ * cover over B's audio and never correct itself. So the receiver renders a snapshot only while it+ * names the resource its player is actually playing, and the phone cancels the previous job as+ * well. Either measure alone leaves a window.+ *+ * **Empty for a mirrored session, where the race cannot happen.** Nothing is served, so there is+ * no id to correlate against - and nothing to correlate: the phone holds the player, so whatever+ * it last said is by definition what it is playing. Empty is therefore "render this" rather than+ * a missing field, and it is a distinct state from an id that does not match, which is discarded.+ */+ val resourceId: String = "",+ val title: String = "",+ /**+ * Who made it: a track's artist, or a video's channel.+ *+ * `author` rather than `artist` because this carries both, and a field named for one of the two+ * would be a name that lies about half of what it holds. `album` below is genuinely music-only+ * and stays empty for a video, which is a different thing from being misnamed.+ */+ val author: String = "",+ val album: String = "",+ /**+ * A resource id on the same media proxy, or empty when there is no cover.+ *+ * Artwork travels over the proxy rather than inline for the reason `MediaProxyServer`'s own KDoc+ * already names - "a worst case is video, audio, a caption track and artwork at once" - which+ * reuses a path the TV is making thousands of requests down anyway. Inline it would be a few+ * hundred kilobytes of Base64 through AES-GCM framing against a 1 MiB frame limit, per track, to+ * avoid one HTTP request.+ *+ * Always empty for a mirrored session: there is no proxy running to fetch it from, and a video+ * has its own picture on screen anyway.+ */+ val artworkResourceId: String = "",+ /**+ * Timed lyrics, already parsed, or empty.+ *+ * Parsed on the phone deliberately: a resource would put an LRC parser in the receiver as well,+ * and two parsers of a loosely-specified text format will disagree. Sixty lines of forty+ * characters is about four kilobytes, so the frame limit is not the argument - the argument is+ * that sending timed lines means the television never learns what LRC is.+ */+ val lyrics: List<LyricLine> = emptyList(),+ /**+ * Untimed lyrics as one block, or empty. Mutually exclusive with [lyrics], which wins.+ *+ * **Two fields rather than one list with a sentinel.** An untimed line carrying `atMs = -1`+ * looks tidy and is wrong: the highlight is `indexOfLast { it.atMs <= positionMs }`, so a list+ * where every timestamp is -1 selects the *last* line and pins the view to the bottom of the+ * song for ever. The case has to be branched on regardless, so it is better named than encoded.+ */+ val plainLyrics: String = "",+) : ControlMessage++/** One lyric line, and the position it belongs at. */+@Serializable+data class LyricLine(val atMs: Long, val text: String)+ /** * Stop playing and let go of the player - but keep this connection, phone to TV. *
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaProxyTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaProxyTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaProxyTest.ktindex 2dedd5f132..9df03ed06c 100644--- a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaProxyTest.kt+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaProxyTest.kt@@ -345,10 +345,48 @@ class MediaProxyTest { assertEquals(0, response.body.size, "a HEAD body would desynchronise the connection") } + // ------------------------------------------------------------------+ // Cover art, which travels the same path as the media+ // ------------------------------------------------------------------++ @Test+ fun `serves cover art whole with its own content type`() {+ // Artwork is an ordinary resource rather than a second mechanism, which is the whole argument+ // for sending it over the proxy - but only if the type it states is the resource's own and not+ // the audio type every other resource here happens to have.+ val response = artwork().get("/$token/art-1234")+ assertEquals(200, response.status)+ assertEquals("image/jpeg", response.headers["content-type"])+ assertEquals("5000", response.headers["content-length"])+ assertContentEquals(media, response.body)+ }++ @Test+ fun `serves a byte range of cover art`() {+ // Nothing asks for one today - the fetcher reads the whole body - but a cached resource states+ // a length and advertises ranges, so answering one wrongly would be a latent fault.+ val response = artwork().get("/$token/art-1234", "Range: bytes=100-199")+ assertEquals(206, response.status)+ assertEquals("image/jpeg", response.headers["content-type"])+ assertEquals("bytes 100-199/5000", response.headers["content-range"])+ assertContentEquals(media.copyOfRange(100, 200), response.body)+ }++ @Test+ fun `an artwork id that was never offered is a 404`() {+ // The failure mode the phone's ordering exists to prevent: an id named in a snapshot before its+ // bytes are on disk is fetched at once, and this is what it gets.+ assertEquals(404, exchange().get("/$token/art-1234").status)+ }+ // ------------------------------------------------------------------ // Helpers // ------------------------------------------------------------------ + private fun artwork() = MediaProxyExchange(token) { id ->+ if (id == "art-1234") FakeResource(media, contentType = "image/jpeg") else null+ }+ private fun exchange() = MediaProxyExchange(token) { id -> if (id == "track" || id.startsWith("251/")) FakeResource(media) else null }
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/NowPlayingTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/NowPlayingTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/NowPlayingTest.ktnew file mode 100644index 0000000000..68acb8a1a1--- /dev/null+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/NowPlayingTest.kt@@ -0,0 +1,120 @@+package com.vayunmathur.cast.protocol++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * The message that gives the television something to show.+ *+ * Round-trips first, because `encodeDefaults` and `explicitNulls = false` interact with an all-but-one+ * defaulted message in ways that are cheap to prove and expensive to discover on a panel. Then the+ * frame bound, which is the failure that would take the whole session with it rather than just the+ * lyrics: a control frame over [ControlFraming.MAX_FRAME_BYTES] is refused rather than sent.+ */+class NowPlayingTest {++ private val codec = ControlCodec()++ @Test+ fun `a full snapshot round-trips`() {+ val message = NowPlaying(+ resourceId = "1234",+ title = "Blue Monday",+ author = "New Order",+ album = "Substance",+ artworkResourceId = "art-1234",+ lyrics = listOf(+ LyricLine(0, "how does it feel"),+ LyricLine(4_120, "to treat me like you do"),+ ),+ )+ assertEquals(message, codec.decode(codec.encode(message)))+ }++ @Test+ fun `a mirrored session's snapshot round-trips with no resource id`() {+ // What an app drawing into a `Surface` sends: two strings and nothing else. Every other field+ // defaulted at once, which is the case `encodeDefaults` could quietly eat - and an absent+ // `resourceId` has to survive as an empty string rather than becoming a missing key, because+ // the receiver reads it as "render this now".+ val message = NowPlaying(title = "Blue Monday (Official Video)", author = "New Order")+ val decoded = assertNotNull(codec.decode(codec.encode(message))) as NowPlaying+ assertEquals(message, decoded)+ assertEquals("", decoded.resourceId)+ assertEquals("", decoded.album)+ assertEquals("", decoded.artworkResourceId)+ }++ @Test+ fun `a snapshot with nothing but a resource id round-trips`() {+ // The case a phone sends the instant it knows what it is playing, before it has read a cover+ // or a lyric tag - and the case every default at once, which `encodeDefaults` could eat.+ val message = NowPlaying(resourceId = "1234")+ val decoded = assertNotNull(codec.decode(codec.encode(message))) as NowPlaying+ assertEquals(message, decoded)+ assertTrue(decoded.lyrics.isEmpty())+ assertEquals("", decoded.plainLyrics)+ }++ @Test+ fun `untimed lyrics travel in their own field`() {+ // Two fields rather than a list of `atMs = -1` sentinels, which would pin the highlight to the+ // last line for the whole song. Proven here because it is the shape of the wire, not a UI+ // detail: nothing downstream can recover the distinction if it is lost.+ val message = NowPlaying(resourceId = "9", plainLyrics = "line one\nline two")+ val decoded = assertNotNull(codec.decode(codec.encode(message))) as NowPlaying+ assertTrue(decoded.lyrics.isEmpty())+ assertEquals("line one\nline two", decoded.plainLyrics)+ }++ @Test+ fun `a field this build does not know is ignored rather than fatal`() {+ // `ignoreUnknownKeys`, which is the only forward compatibility a refused-on-mismatch protocol+ // has - and the reason a newer phone adding a field does not hang up an older television.+ val json = """{"type":"NOW_PLAYING","resourceId":"7","title":"Ceremony","composer":"nobody"}"""+ val decoded = assertNotNull(+ ControlJson.decodeFromString<ControlMessage>(json),+ ) as NowPlaying+ assertEquals("7", decoded.resourceId)+ assertEquals("Ceremony", decoded.title)+ }++ @Test+ fun `a worst-case clamped lyric set fits in one control frame`() {+ // The numbers `:cast` clamps to, at their limit and then some: 400 lines whose total length is+ // the 16,000-character bound. If this ever exceeds the frame limit the session dies rather+ // than the lyrics, so the two constants have to be checked against each other somewhere.+ val perLine = 16_000 / 400+ val lines = List(400) { LyricLine(it * 3_000L, "x".repeat(perLine)) }+ val message = NowPlaying(+ resourceId = "1234",+ title = "x".repeat(200),+ author = "x".repeat(200),+ album = "x".repeat(200),+ artworkResourceId = "art-1234",+ lyrics = lines,+ )+ val encoded = codec.encode(message)+ assertTrue(+ encoded.size < ControlFraming.MAX_FRAME_BYTES,+ "a clamped lyric set encoded to ${encoded.size} bytes",+ )+ assertEquals(message, codec.decode(encoded))+ }++ @Test+ fun `the messages a served session already sent still round-trip`() {+ // The version bump reshaped nothing, and this is what says so: `NOW_PLAYING` is additive on+ // the wire even though the handshake refuses a peer that does not know it.+ val messages = listOf<ControlMessage>(+ Ping,+ PlayMedia(resourceId = "1234", mimeType = "audio/ogg", durationMs = 214_000),+ PlaybackState(positionMs = 1_000, durationMs = 214_000, playing = true, buffering = false),+ )+ for (message in messages) {+ assertEquals(message, codec.decode(codec.encode(message)), "$message did not round-trip")+ }+ }+}
cast/src/main/java/com/vayunmathur/cast/network/ControlSocket.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/network/ControlSocket.kt b/cast/src/main/java/com/vayunmathur/cast/network/ControlSocket.ktindex 64db2743b4..cdc49b7f72 100644--- a/cast/src/main/java/com/vayunmathur/cast/network/ControlSocket.kt+++ b/cast/src/main/java/com/vayunmathur/cast/network/ControlSocket.kt@@ -72,9 +72,17 @@ class ControlSocket(private val host: String, private val port: Int) { } } - /** Returns the body bytes, for the transcript. */- fun send(message: ControlMessage): ByteArray {- val stream = output ?: error("send before connect")+ /**+ * The body bytes for the transcript, or null when this socket is not connected.+ *+ * **Null rather than a throw, symmetrically with [receive].** A closed socket is a race, not a+ * caller's mistake: [close] is deliberately called from teardown without holding the mutex a+ * handshake holds - so a send already in flight can legitimately find its stream gone. Signalling+ * that with `IllegalStateException` made it look like a programming error and, because the+ * handshake path has nothing to catch such a thing, took the whole process with it.+ */+ fun send(message: ControlMessage): ByteArray? {+ val stream = output ?: return null val body = codec.encode(message) stream.write(ControlFraming.encode(body)) stream.flush()
cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.ktindex 4e17450587..69f2525619 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt@@ -25,6 +25,7 @@ import com.vayunmathur.cast.protocol.CodecNegotiation import com.vayunmathur.cast.protocol.CodecSelection import com.vayunmathur.cast.protocol.DecoderLimits import com.vayunmathur.cast.protocol.MediaResourceResolver+import com.vayunmathur.cast.protocol.NowPlaying import com.vayunmathur.cast.protocol.PING_INTERVAL_MS import com.vayunmathur.cast.protocol.PROTOCOL_VERSION import com.vayunmathur.cast.protocol.PlayMedia@@ -701,6 +702,17 @@ object CastController { scope.launch { mutex.withLock { activeClient.playMedia(media) } } } + /**+ * Tell the TV what the item it is playing actually is.+ *+ * Under [mutex] like [playMedia] and for the same reason. Silent with no session: this is+ * enrichment, and a snapshot that arrives a moment after a cast ended has nothing to enrich.+ */+ fun setNowPlaying(nowPlaying: NowPlaying) {+ val activeClient = client ?: return+ scope.launch { mutex.withLock { activeClient.sendNowPlaying(nowPlaying) } }+ }+ /** * Ask the TV to do something, in a served session. *@@ -848,6 +860,8 @@ object CastController { MirrorStopReason.ReceiverGone -> context.getString(R.string.cast_mirror_receiver_gone) MirrorStopReason.CodecConfig -> context.getString(R.string.cast_mirror_codec_config_failed)+ MirrorStopReason.NoVideoOutput ->+ context.getString(R.string.cast_mirror_no_video_output) } _mirrorPhase.value = MirrorPhase.Failed endContentSession(CastContract.REASON_FAILED)
cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt b/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.ktindex 5c68257697..7cf1f78452 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt@@ -12,6 +12,7 @@ import com.vayunmathur.cast.protocol.ContentSession import com.vayunmathur.cast.protocol.DecoderLimits import com.vayunmathur.cast.protocol.Hello import com.vayunmathur.cast.protocol.Negotiation+import com.vayunmathur.cast.protocol.NowPlaying import com.vayunmathur.cast.protocol.PROTOCOL_VERSION import com.vayunmathur.cast.protocol.PairCode import com.vayunmathur.cast.protocol.PairFailed@@ -127,15 +128,14 @@ class MirrorClient( * [HandshakeOutcome.Paired] when a remembered device key was enough. */ fun begin(): HandshakeOutcome {- transcript.add(- socket.send(- Hello(- senderName = senderName,- senderId = senderId,- paired = storedDeviceKey != null,- ),+ val hello = socket.send(+ Hello(+ senderName = senderName,+ senderId = senderId,+ paired = storedDeviceKey != null, ),- )+ ) ?: return HandshakeOutcome.Failed(ClientFailure.Unreachable)+ transcript.add(hello) val identityFrame = socket.receive() ?: return HandshakeOutcome.Failed(ClientFailure.Unreachable)@@ -168,7 +168,9 @@ class MirrorClient( val secret = SessionKeys.newSecret() val sealed = runCatching { SecretSealing.seal(bundle, secret) }.getOrNull() ?: return HandshakeOutcome.Failed(ClientFailure.Protocol)- transcript.add(socket.send(SealedSecret(sealed = ProtocolBase64.encode(sealed))))+ val sealedFrame = socket.send(SealedSecret(sealed = ProtocolBase64.encode(sealed)))+ ?: return HandshakeOutcome.Failed(ClientFailure.Unreachable)+ transcript.add(sealedFrame) val sessionKeys = SessionKeys.of(secret) keys = sessionKeys@@ -208,6 +210,7 @@ class MirrorClient( private fun proof(bytes: ByteArray): HandshakeOutcome { socket.send(PairProof(proof = ProtocolBase64.encode(bytes)))+ ?: return HandshakeOutcome.Failed(ClientFailure.Unreachable) val reply = socket.receive() ?: return HandshakeOutcome.Failed(ClientFailure.Unreachable) return when (val message = reply.message) { is PairOk -> {@@ -262,7 +265,10 @@ class MirrorClient( videoCodec = videoCodec, appLabel = appLabel, )- socket.send(config)+ // Null means the channel went away between choosing a codec and configuring it, which is+ // exactly what a teardown racing a fresh session does. Refused rather than thrown: the caller+ // has a failure branch for this and had nothing to catch an exception with.+ socket.send(config) ?: return HandshakeOutcome.Failed(ClientFailure.StreamRefused) val ready = socket.receive()?.message as? StreamReady ?: return HandshakeOutcome.Failed(ClientFailure.StreamRefused) if (ready.udpPort !in 1..65535) {@@ -293,7 +299,7 @@ class MirrorClient( video: Boolean, appLabel: String, ): ContentOutcome {- socket.send(+ val offered = socket.send( ContentSession( host = host, port = port,@@ -303,6 +309,7 @@ class MirrorClient( appLabel = appLabel, ), )+ if (offered == null) return ContentOutcome.Refused("the control channel had already closed") val ready = socket.receive()?.message as? ContentReady ?: return ContentOutcome.Refused("the TV did not answer") if (!ready.accepted) {@@ -325,6 +332,24 @@ class MirrorClient( .onFailure { Log.w(TAG, "could not send the play request", it) } } + /**+ * Tell the TV what the item it was asked to play actually is.+ *+ * Separate from [playMedia] because it is state rather than a command: the cover and the lyrics can+ * arrive after the audio has already started, and folding them into the play request would mean+ * restarting the track to change them. Non-throwing for [sendPlaybackState]'s reasons, and logged+ * without its payload - a lyric sheet in the log would bury everything else.+ */+ fun sendNowPlaying(nowPlaying: NowPlaying) {+ Log.i(+ TAG,+ "describing ${nowPlaying.resourceId} to the TV: '${nowPlaying.title}'" ++ if (nowPlaying.artworkResourceId.isEmpty()) ", no cover" else ", with a cover",+ )+ runCatching { socket.send(nowPlaying) }+ .onFailure { Log.w(TAG, "could not send the now-playing metadata", it) }+ }+ /** * Hand the TV the video codec configuration, for a codec that cannot carry it in-band. *
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.ktindex c7c172ed0b..cd11663821 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt@@ -59,6 +59,23 @@ private const val KEY_FRAME_REQUEST_INTERVAL_MS = 500L */ private const val CODEC_CONFIG_TIMEOUT_MS = 2_000L +/**+ * How long the video encoder has to produce **anything at all**, measured from `start()`.+ *+ * [CODEC_CONFIG_TIMEOUT_MS] deliberately cannot catch this: its clock begins at the first output, so+ * an encoder that emits nothing ever leaves it disarmed for the life of the session. What that looked+ * like was a cast with audio playing, a black picture, and no failure at either end - the receiver's+ * own 5 s bound only exists for a codec whose configuration travels out of band, so for H.265 there+ * was nothing anywhere to notice.+ *+ * **Deliberately longer than the receiver's bound**, so this never pre-empts it. For AV1 the TV still+ * says `BYE missing codec config` first and the codec is still demoted for that TV, which is the+ * correct attribution and the thing that makes the next session work. This is the net underneath, for+ * the cases the receiver structurally cannot see - and it is generous because a+ * [MirrorSource.Content] client hands its surface out over Binder and may legitimately be slow to draw.+ */+private const val NO_VIDEO_OUTPUT_TIMEOUT_MS = 12_000L+ /** What could not be started, so the UI can say so rather than looking broken. */ data class MirrorDegradation( val videoUnavailable: Boolean = false,@@ -78,6 +95,18 @@ enum class MirrorStopReason { * the thing at fault, and the recovery is to remember that and start the next session at H.265. */ CodecConfig,++ /**+ * The encoder started and then produced no output whatever.+ *+ * **Distinct from [CodecConfig], and the distinction is an attribution.** That one means frames are+ * flowing and the configuration did not come with them, which is the codec's fault and is+ * remembered against the TV. This one cannot say whose fault it is: an encoder that emits nothing+ * and a source that draws nothing look identical from here, and demoting a codec on that evidence+ * would eventually demote every codec and leave the device unable to cast at all. So it fails the+ * session, says so, and remembers nothing.+ */+ NoVideoOutput, } /**@@ -250,9 +279,24 @@ class MirrorEngine( // timed from. Zero until then, so a session whose content has not started drawing yet is // simply waiting rather than failing. var firstOutputAt = 0L+ val startedAt = SystemClock.elapsedRealtime() while (isActive) { val chunks = encoder.drain() if (chunks.isEmpty()) {+ // The one condition the codec-config watchdog below cannot reach, because its+ // clock never starts. See [NO_VIDEO_OUTPUT_TIMEOUT_MS].+ if (firstOutputAt == 0L &&+ SystemClock.elapsedRealtime() - startedAt >= NO_VIDEO_OUTPUT_TIMEOUT_MS+ ) {+ Log.w(+ TAG,+ "${videoCodec.label} produced no output at all in " ++ "${NO_VIDEO_OUTPUT_TIMEOUT_MS}ms; either the encoder is wedged or " ++ "nothing is being drawn into its surface",+ )+ onStopped(MirrorStopReason.NoVideoOutput)+ return@launch+ } delay(FRAME_POLL_MS) continue }
cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt b/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.ktindex cd480172d6..3af4fe3684 100644--- a/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt+++ b/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt@@ -13,6 +13,8 @@ import android.os.RemoteException import android.util.Log import com.vayunmathur.cast.platform.CastController import com.vayunmathur.cast.platform.ContentSessionResult+import com.vayunmathur.cast.protocol.LyricLine+import com.vayunmathur.cast.protocol.NowPlaying import com.vayunmathur.cast.protocol.PlayMedia import com.vayunmathur.cast.protocol.PlaybackAction import com.vayunmathur.cast.protocol.PlaybackCommand@@ -111,6 +113,14 @@ class ContentCastService : Service() { } true }+ CastContract.MSG_SET_NOW_PLAYING -> {+ // Dropped with no session, like its neighbours: there is no television to show it+ // on, and a client may send one a tick after the session ended.+ if (sessionOpen) {+ msg.data?.toNowPlaying()?.let { CastController.setNowPlaying(it) }+ }+ true+ } else -> false } },@@ -307,6 +317,83 @@ private fun Bundle.toPlayMedia(): PlayMedia = PlayMedia( startPositionMs = getLong(CastContract.KEY_START_POSITION_MS), ) +/**+ * The metadata a client sent, as the message the TV understands, or null when it was unusable.+ *+ * **This is the trust boundary, and it has to act like one.** A first-party app is trusted, but a bug+ * in one must not be able to end a session: these strings and lines end up in a single control frame,+ * and one over `ControlFraming.MAX_FRAME_BYTES` is refused rather than sent, which drops the+ * connection rather than the metadata. So the clamping is here, on the way in, and not left to a+ * caller to remember.+ *+ * The `Bundle` is unwrapped by [Bundle.toNowPlaying]; everything that *decides* anything is in this+ * function so it can be proved on a plain JVM - the same move `PlaybackAction.sdkAction` makes for+ * the other direction.+ */+internal fun nowPlayingOf(+ resourceId: String,+ title: String,+ author: String,+ album: String,+ artworkResourceId: String,+ lyricTimesMs: LongArray?,+ lyricTexts: Array<String>?,+ plainLyrics: String,+): NowPlaying? {+ // Nothing whatever to show, so there is no snapshot here - only a message that would blank the+ // television's headline. An empty [resourceId] on its own is fine and expected: that is what a+ // `Surface` session sends, because it has no resource to name.+ if (title.isEmpty() && author.isEmpty() && album.isEmpty() && artworkResourceId.isEmpty() &&+ lyricTexts.isNullOrEmpty() && plainLyrics.isEmpty()+ ) {+ return null+ }++ // Refused rather than truncated to the shorter: the two halves disagreeing means the sender is+ // confused about its own lyrics, and guessing would put the wrong words at the wrong times.+ val times = lyricTimesMs ?: LongArray(0)+ val texts = lyricTexts ?: emptyArray()+ val timed = if (times.size == texts.size) clampLyrics(times, texts) else emptyList()++ return NowPlaying(+ resourceId = resourceId,+ title = title.take(CastContract.MAX_LYRIC_CHARS),+ author = author.take(CastContract.MAX_LYRIC_CHARS),+ album = album.take(CastContract.MAX_LYRIC_CHARS),+ artworkResourceId = artworkResourceId,+ lyrics = timed,+ // Dropped when there are timed lines, so the two can never both be on screen and the+ // television needs no precedence rule of its own.+ plainLyrics = if (timed.isEmpty()) plainLyrics.take(CastContract.MAX_LYRIC_CHARS) else "",+ )+}++/** Both bounds, applied together: whichever runs out first ends the list. */+private fun clampLyrics(timesMs: LongArray, texts: Array<String>): List<LyricLine> {+ val lines = ArrayList<LyricLine>(minOf(texts.size, CastContract.MAX_LYRIC_LINES))+ var chars = 0+ for (i in texts.indices) {+ if (lines.size >= CastContract.MAX_LYRIC_LINES) break+ val text = texts[i]+ if (chars + text.length > CastContract.MAX_LYRIC_CHARS) break+ lines.add(LyricLine(atMs = timesMs[i], text = text))+ chars += text.length+ }+ return lines+}++/** See [nowPlayingOf], which is where everything this reads is actually decided. */+private fun Bundle.toNowPlaying(): NowPlaying? = nowPlayingOf(+ resourceId = getString(CastContract.KEY_RESOURCE_ID).orEmpty(),+ title = getString(CastContract.KEY_TITLE).orEmpty(),+ author = getString(CastContract.KEY_AUTHOR).orEmpty(),+ album = getString(CastContract.KEY_ALBUM).orEmpty(),+ artworkResourceId = getString(CastContract.KEY_ARTWORK_RESOURCE_ID).orEmpty(),+ lyricTimesMs = getLongArray(CastContract.KEY_LYRIC_TIMES),+ lyricTexts = getStringArray(CastContract.KEY_LYRIC_TEXTS),+ plainLyrics = getString(CastContract.KEY_PLAIN_LYRICS).orEmpty(),+)+ /** * The press a client sent, as the message the TV understands, or null for an action this build does * not know.
cast/src/main/res/values/strings.xml
diff --git a/cast/src/main/res/values/strings.xml b/cast/src/main/res/values/strings.xmlindex a5f28ed2bd..59202358b8 100644--- a/cast/src/main/res/values/strings.xml+++ b/cast/src/main/res/values/strings.xml@@ -59,6 +59,9 @@ <string name="cast_mirror_no_common_codec">This phone can send %1$s and this TV can decode %2$s, but nothing they share works at this screen size.</string> <string name="cast_mirror_codec_demoted">%1$s did not work with this TV before, and there is no other codec you both support. Pair with this TV again to retry it.</string> <string name="cast_mirror_codec_config_failed">The TV could not be given the video settings it needed. The next attempt will use a different codec.</string>+ <!-- The encoder started and then emitted nothing. Deliberately does not blame the codec: an+ encoder that produces nothing and a source that draws nothing are indistinguishable. -->+ <string name="cast_mirror_no_video_output">No video reached the TV. Try casting again.</string> <!-- Quick Settings tile --> <string name="cast_tile_label">Mirror screen</string>
cast/src/test/java/com/vayunmathur/cast/service/NowPlayingMappingTest.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/service/NowPlayingMappingTest.kt b/cast/src/test/java/com/vayunmathur/cast/service/NowPlayingMappingTest.ktnew file mode 100644index 0000000000..49861635fd--- /dev/null+++ b/cast/src/test/java/com/vayunmathur/cast/service/NowPlayingMappingTest.kt@@ -0,0 +1,151 @@+package com.vayunmathur.cast.service++import com.vayunmathur.sdk.cast.CastContract+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * The trust boundary between an app's now-playing metadata and the control channel.+ *+ * A first-party app is trusted, and that is exactly why this exists: a bug in one must not be able to+ * end a session by overflowing `ControlFraming.MAX_FRAME_BYTES`, because a frame over the bound is+ * refused rather than sent and the connection goes with it. The mapping is a `Bundle`-free function so+ * that every decision it makes is provable here rather than on a television.+ */+class NowPlayingMappingTest {++ private fun map(+ resourceId: String = "1234",+ title: String = "",+ author: String = "",+ album: String = "",+ artworkResourceId: String = "",+ times: LongArray? = null,+ texts: Array<String>? = null,+ plainLyrics: String = "",+ ) = nowPlayingOf(+ resourceId = resourceId,+ title = title,+ author = author,+ album = album,+ artworkResourceId = artworkResourceId,+ lyricTimesMs = times,+ lyricTexts = texts,+ plainLyrics = plainLyrics,+ )++ @Test+ fun `a well-formed snapshot passes through`() {+ val mapped = assertNotNull(+ map(+ title = "Blue Monday",+ author = "New Order",+ album = "Substance",+ artworkResourceId = "art-1234",+ times = longArrayOf(0, 4_120),+ texts = arrayOf("how does it feel", "to treat me like you do"),+ ),+ )+ assertEquals("1234", mapped.resourceId)+ assertEquals("New Order", mapped.author)+ assertEquals("art-1234", mapped.artworkResourceId)+ assertEquals(listOf(0L, 4_120L), mapped.lyrics.map { it.atMs })+ }++ @Test+ fun `a mirrored session's title and author pass through with no resource id`() {+ // The `Surface` case: no resource is being served, so there is no id to name - which used to be+ // refused here, back when a served session was the only one that could send metadata at all.+ val mapped = assertNotNull(+ map(resourceId = "", title = "Blue Monday (Official Video)", author = "New Order"),+ )+ assertEquals("", mapped.resourceId)+ assertEquals("Blue Monday (Official Video)", mapped.title)+ assertEquals("New Order", mapped.author)+ }++ @Test+ fun `a snapshot with nothing in it is refused`() {+ // Not a snapshot at all - forwarding it would blank the television's headline and replace a+ // title with nothing. Distinct from the case above, which has no *resource* but plenty to show.+ assertNull(map())+ assertNull(map(resourceId = ""))+ }++ @Test+ fun `an artwork id alone is enough to be worth sending`() {+ // The second of music's two snapshots per track can be nothing but a cover, if the file had no+ // readable tags beyond what the first one already carried.+ assertNotNull(map(artworkResourceId = "art-1234"))+ }++ @Test+ fun `mismatched array lengths drop the lyrics whole`() {+ // Refused rather than truncated to the shorter: the halves disagreeing means the sender is+ // confused about its own lyrics, and guessing would put the wrong words at the wrong times.+ val mapped = assertNotNull(+ map(title = "Blue Monday", times = longArrayOf(0, 1_000, 2_000), texts = arrayOf("one", "two")),+ )+ assertTrue(mapped.lyrics.isEmpty())+ }++ @Test+ fun `one array without the other is not lyrics`() {+ assertTrue(assertNotNull(map(title = "a", times = longArrayOf(0, 1_000))).lyrics.isEmpty())+ assertTrue(assertNotNull(map(title = "a", texts = arrayOf("one", "two"))).lyrics.isEmpty())+ }++ @Test+ fun `plain lyrics are dropped when there are timed ones`() {+ // So the two can never both be on screen, and the television needs no precedence rule of its+ // own to get wrong.+ val mapped = assertNotNull(+ map(+ times = longArrayOf(0),+ texts = arrayOf("how does it feel"),+ plainLyrics = "the whole song, untimed",+ ),+ )+ assertEquals(1, mapped.lyrics.size)+ assertEquals("", mapped.plainLyrics)+ }++ @Test+ fun `plain lyrics survive when there are no timed ones`() {+ val mapped = assertNotNull(map(plainLyrics = "the whole song, untimed"))+ assertEquals("the whole song, untimed", mapped.plainLyrics)+ }++ @Test+ fun `too many lines are clamped`() {+ val count = CastContract.MAX_LYRIC_LINES * 3+ val mapped = assertNotNull(+ map(times = LongArray(count) { it * 100L }, texts = Array(count) { "a" }),+ )+ assertEquals(CastContract.MAX_LYRIC_LINES, mapped.lyrics.size)+ }++ @Test+ fun `too many characters are clamped even in few lines`() {+ // The bound the line count cannot catch: ten lines of a megabyte each is well inside+ // MAX_LYRIC_LINES and well outside a control frame.+ val mapped = assertNotNull(+ map(times = LongArray(10), texts = Array(10) { "x".repeat(1_000_000) }),+ )+ assertTrue(+ mapped.lyrics.sumOf { it.text.length } <= CastContract.MAX_LYRIC_CHARS,+ "an oversize lyric set got through",+ )+ }++ @Test+ fun `an oversize title is clamped rather than refused`() {+ // Refusing would lose the whole snapshot, including the cover, over a field nothing can render+ // past a couple of lines anyway.+ val mapped = assertNotNull(map(title = "x".repeat(CastContract.MAX_LYRIC_CHARS * 4)))+ assertEquals(CastContract.MAX_LYRIC_CHARS, mapped.title.length)+ }+}
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ArtworkFetcher.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ArtworkFetcher.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ArtworkFetcher.ktnew file mode 100644index 0000000000..f9b820b350--- /dev/null+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ArtworkFetcher.kt@@ -0,0 +1,75 @@+package com.vayunmathur.cast.tv.platform++import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.util.Log+import com.vayunmathur.cast.protocol.ContentSession+import com.vayunmathur.cast.protocol.EphemeralTls+import com.vayunmathur.cast.protocol.MediaProxy+import com.vayunmathur.cast.protocol.ProtocolBase64+import java.net.URL+import javax.net.ssl.HttpsURLConnection++private const val TAG = "ArtworkFetcher"++/**+ * Fetches a cover from the phone's media proxy.+ *+ * Artwork travels as a resource rather than as bytes on the control channel, which reuses the whole+ * path the player already uses - `MediaProxyServer`'s own KDoc names this case: "a worst case is+ * video, audio, a caption track and artwork at once". The alternative would put a few hundred+ * kilobytes of Base64 through AES-GCM framing per track, against a 1 MiB frame limit, to avoid one+ * more HTTP request down a connection that is making thousands.+ *+ * **The pin is set on the connection, not inherited.** [ContentPlayer] installs one process-wide with+ * `HttpsURLConnection.setDefaultSSLSocketFactory`, because `DefaultHttpDataSource` takes its factory+ * from the static default - and relying on that here would be a bug that only appears sometimes: the+ * first snapshot can arrive before the player has been built, and this fetch would then validate a+ * self-signed ephemeral certificate against the platform's authorities and fail. So the factory is+ * built here and assigned to the connection. The session is needed for the host, the port and the+ * token anyway, so the fingerprint is already in hand.+ *+ * Every failure is null and a warning. A cover is enrichment: a session must not end because a JPEG+ * did not arrive, and the screen has a deliberate placeholder for exactly this.+ */+class ArtworkFetcher(private val session: ContentSession) {++ private val socketFactory = ProtocolBase64.decode(session.certificateFingerprint)+ ?.takeIf { it.size == FINGERPRINT_BYTES }+ ?.let { runCatching { EphemeralTls.client(it).socketFactory }.getOrNull() }++ /** Blocking. Call it off the main thread. */+ fun fetch(resourceId: String): Bitmap? {+ val factory = socketFactory ?: run {+ Log.w(TAG, "no usable certificate fingerprint, so no artwork will be fetched")+ return null+ }+ val url = MediaProxy.url(session.host, session.port, session.token, resourceId)+ return runCatching {+ val connection = URL(url).openConnection() as HttpsURLConnection+ connection.sslSocketFactory = factory+ connection.connectTimeout = CONNECT_TIMEOUT_MS+ connection.readTimeout = READ_TIMEOUT_MS+ try {+ if (connection.responseCode != HttpsURLConnection.HTTP_OK) {+ Log.w(TAG, "the proxy answered ${connection.responseCode} for '$resourceId'")+ return@runCatching null+ }+ // Read whole, then decode: the phone bounds a cover to 1280px on its longest edge,+ // so there is nothing here worth a pre-pass decode of the bounds to guard against.+ val bytes = connection.inputStream.use { it.readBytes() }+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size)+ } finally {+ connection.disconnect()+ }+ }.onFailure { Log.w(TAG, "could not fetch artwork '$resourceId'", it) }.getOrNull()+ }++ private companion object {+ const val FINGERPRINT_BYTES = 32++ /** The phone is on the same LAN, and a cover is not worth waiting on as long as media is. */+ const val CONNECT_TIMEOUT_MS = 5_000+ const val READ_TIMEOUT_MS = 8_000+ }+}
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ContentPlayer.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ContentPlayer.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ContentPlayer.ktindex a375785741..b43a84f198 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ContentPlayer.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ContentPlayer.kt@@ -143,8 +143,9 @@ class ContentPlayer( } // Process-wide because `DefaultHttpDataSource` is `HttpURLConnection`-backed and takes its- // socket factory from the default. Acceptable here and nowhere else: this app makes no other- // HTTPS request, so there is nothing else whose trust could be narrowed by accident.+ // socket factory from the default. Acceptable because every HTTPS request this app makes goes+ // to the same pinned proxy - but not relied upon: `ArtworkFetcher` sets the factory on its+ // own connection, because a snapshot can arrive before this has run. HttpsURLConnection.setDefaultSSLSocketFactory(EphemeralTls.client(fingerprint).socketFactory) val http = DefaultHttpDataSource.Factory()
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.ktindex d613987c61..3b2a658856 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt@@ -8,20 +8,30 @@ import android.view.SurfaceView import android.view.ViewGroup import android.widget.FrameLayout import androidx.activity.ComponentActivity+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ComposeView import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsControllerCompat import androidx.lifecycle.lifecycleScope+import androidx.tv.material3.MaterialTheme import com.vayunmathur.cast.protocol.PlaybackAction import com.vayunmathur.cast.protocol.PlaybackCommand import com.vayunmathur.cast.tv.ui.CastTvTheme+import com.vayunmathur.cast.tv.ui.NowPlayingScreen+import com.vayunmathur.cast.tv.ui.PlaybackClock import com.vayunmathur.cast.tv.ui.TransportOverlay import kotlinx.coroutines.Job import kotlinx.coroutines.delay@@ -174,10 +184,17 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback { } /**- * The controls, as a transparent layer above the picture.+ * The now-playing screen and the controls, as layers above the picture. *- * Composes to nothing at all until the phone reports playback, which is what keeps it off a+ * Composes to nothing at all until the phone reports playback, which is what keeps both off a * mirrored phone screen: screen mirroring has no transport, so it never sends a snapshot.+ *+ * **The now-playing screen is behind the controls and only for an audio session**, where there is+ * no `SurfaceView` in the window at all and this `ComposeView` is the whole of it. Over video it+ * would be an opaque rectangle across the film. It renders only the metadata that names what the+ * player is actually playing - see `ReceiverUiState.nowPlayingForCurrentItem` - so nothing appears+ * until the phone has described the track, and the existing headline in the overlay stays the+ * fallback for an old phone, a non-music app, and the moment before the first snapshot lands. */ private fun overlayView(): ComposeView = ComposeView(this).apply { setContent {@@ -193,12 +210,60 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback { scrubPreviewMs = NO_SCRUB } }- if (playback != null && overlayVisible) {- TransportOverlay(- snapshot = playback,- sourceName = (state.phase as? ReceiverPhase.Mirroring)?.sourceName.orEmpty(),- scrubPreviewMs = scrubPreviewMs.takeIf { it != NO_SCRUB },- )+ if (playback == null) return@CastTvTheme+ val mirroring = state.phase as? ReceiverPhase.Mirroring+ val nowPlaying = state.nowPlayingForCurrentItem+ // Read from the state rather than from `overlayPinned`, which is a plain field that+ // composition does not observe: the same condition, but one that recomposes when the+ // session's own answer to it changes.+ val audioOnly = mirroring?.hasVideo == false+ // One clock for both layers, passed down as a lambda so neither the artwork nor the+ // lyrics column ends up in a scope that invalidates per frame. See `PlaybackClock`.+ PlaybackClock(+ snapshot = playback,+ scrubPreviewMs = scrubPreviewMs.takeIf { it != NO_SCRUB },+ ) { positionMs ->+ val transport: @Composable (Modifier, Boolean) -> Unit = { m, scrim ->+ TransportOverlay(+ snapshot = playback,+ sourceName = mirroring?.sourceName.orEmpty(),+ nowPlaying = nowPlaying,+ positionMs = positionMs,+ scrubbing = scrubPreviewMs != NO_SCRUB,+ scrim = scrim,+ modifier = m,+ )+ }+ if (nowPlaying != null && audioOnly) {+ // **Stacked, not overlaid.** There is no picture for the bar to get out of the+ // way of, so it takes the height it needs and the lyrics take the rest -+ // which is the only way they can fill the panel without a reserved constant+ // that is wrong on every screen size but the one it was measured on.+ //+ // **And the background is painted here, once, for the whole window** - so the+ // transport sits on the same sheet of colour as the cover and the lyrics rather+ // than on a black band under them. Which is also why the bar is asked for no+ // scrim: with nothing behind it to see through, a gradient would draw exactly+ // the seam this is avoiding.+ Column(+ modifier = Modifier+ .fillMaxSize()+ .background(MaterialTheme.colorScheme.surface),+ ) {+ NowPlayingScreen(+ nowPlaying = nowPlaying,+ positionMs = positionMs,+ artwork = state.artwork,+ modifier = Modifier.weight(1f),+ )+ if (overlayVisible) transport(Modifier, false)+ }+ } else if (overlayVisible) {+ // Over the picture, where a scrim is the whole point.+ Box(modifier = Modifier.fillMaxSize()) {+ transport(Modifier.align(Alignment.BottomCenter), true)+ }+ } } } }
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.ktindex 5160ced8a7..abbcd7dfd8 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt@@ -13,6 +13,7 @@ import com.vayunmathur.cast.protocol.DecodableFrame import com.vayunmathur.cast.protocol.DecoderLimits import com.vayunmathur.cast.protocol.Hello import com.vayunmathur.cast.protocol.Negotiation+import com.vayunmathur.cast.protocol.NowPlaying import com.vayunmathur.cast.protocol.PROTOCOL_VERSION import com.vayunmathur.cast.protocol.PairCode import com.vayunmathur.cast.protocol.PairFailed@@ -279,10 +280,20 @@ object ReceiverController { * and resetting [castVolume] is what stops the *next* session inheriting this one's gain. Missing * the second is a quiet, nasty failure - a screen-mirroring session that follows a quiet cast would * play at that gain for ever, with no snapshot to change it and `nudgeVolume` declining to try.+ *+ * The metadata goes with them, and has to: it is not merely stale but wrong, and a cover left on+ * screen over the next session's audio would look deliberate. */ private fun forgetPlayback() { castVolume = 1f- _state.update { it.copy(playback = null) }+ _state.update {+ it.copy(+ playback = null,+ nowPlaying = null,+ playingResourceId = "",+ artwork = null,+ )+ } } /** Called by `MirrorActivity` once its `SurfaceView` has a surface to draw into. */@@ -477,10 +488,13 @@ object ReceiverController { return } // Echoed rather than treated as a surprise, so a keep-alive cannot end the very channel- // it exists to preserve. A snapshot or a command still in flight from the session that- // just ended is dropped for the same reason: there is no longer a player for either.+ // it exists to preserve. A snapshot, a command or a metadata update still in flight+ // from the session that just ended is dropped for the same reason: there is no longer+ // a player for the first two, and nothing on screen for the third. Metadata is the+ // likeliest of the three to land here, because the phone prepares it off the path that+ // ends the session - a cover read and re-compressed while the user closed the cast. is Ping -> runCatching { channel.send(Ping) }- is PlaybackState, is PlaybackCommand -> Unit+ is PlaybackState, is PlaybackCommand, is NowPlaying -> Unit else -> return } }@@ -493,7 +507,9 @@ object ReceiverController { * everything down through the same path. It is also where the codec configuration arrives, which * for AV1 is what the media loop is waiting on before it can start a decoder at all - it is * repeated on every key-frame request, so this handles it more than once. And it is where playback- * snapshots arrive, twice a second, for as long as an app is casting encoded content.+ * snapshots arrive, twice a second, for as long as an app is casting encoded content - as does the+ * metadata that says what that content *is*, which an encoded video needs quite as much as a+ * served track did. */ private suspend fun mirrorSession( channel: ControlChannel,@@ -509,6 +525,10 @@ object ReceiverController { } is VideoCodecConfig -> onVideoCodecConfig(message, config) is PlaybackState -> onPlaybackState(message)+ // What the encoded picture is of. Names no resource - nothing is being served here -+ // so the gate in `ReceiverUiState.nowPlayingForCurrentItem` passes it straight+ // through: this end holds no player, so the phone's latest word is the only word.+ is NowPlaying -> _state.update { it.copy(nowPlaying = message) } // As in the content-session loop below: echoed so the phone's read deadline moves // too. Screen mirroring never sends one, so this only fires for app content. is Ping -> runCatching { channel.send(Ping) }@@ -567,6 +587,9 @@ object ReceiverController { // none, and handing it one would put a black rectangle over the now-playing screen. if (session.video) surface?.let { withContext(Dispatchers.Main) { player.setSurface(it) } } channel.send(ContentReady(accepted = true))+ // Built outside the update, because `update` may retry its lambda under contention and+ // allocating a fetcher per attempt would be one object per lost race.+ val artworkFetcher = ArtworkFetcher(session) _state.update { it.copy( phase = ReceiverPhase.Mirroring(@@ -578,6 +601,10 @@ object ReceiverController { appLabel = session.appLabel, hasVideo = session.video, ),+ // In the state rather than a field of this object, because the now-playing screen+ // reads it during composition and a plain field is not something composition+ // observes - the same trap the `overlayPinned` comment in `MirrorActivity` names.+ artwork = artworkFetcher, ) } Log.i(TAG, "serving content from ${session.host}:${session.port} for '${session.appLabel}'")@@ -603,7 +630,17 @@ object ReceiverController { Log.i(TAG, "'$senderName' ended the content session") return true }- is PlayMedia -> withContext(Dispatchers.Main) { player.play(message) }+ is PlayMedia -> {+ withContext(Dispatchers.Main) { player.play(message) }+ // Published rather than only held on the player, because it is half of the+ // comparison `nowPlayingForCurrentItem` makes and the UI has to recompose on it.+ _state.update { it.copy(playingResourceId = message.resourceId) }+ }+ // What the item *is*, as opposed to which bytes it is. Stored whatever it names:+ // the gate is at read time, so a snapshot arriving before or after the play it+ // describes both work, and one for a track already skipped past is simply never+ // shown. See `ReceiverUiState.nowPlayingForCurrentItem`.+ is NowPlaying -> _state.update { it.copy(nowPlaying = message) } // The phone's transport, wherever it was pressed - its own screen, a notification, // a headset button, a car. Applied to the player that is actually making the // sound. `Next` and `Previous` are refused by the player and arrive as a fresh
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.ktindex 80c0e4b1c9..77674e3f66 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.kt@@ -1,5 +1,6 @@ package com.vayunmathur.cast.tv.platform +import com.vayunmathur.cast.protocol.NowPlaying import com.vayunmathur.cast.protocol.PlaybackState /** Where the receiver is, from the point of view of a screen. */@@ -122,7 +123,57 @@ data class ReceiverUiState( * overlay that only exists when this is non-null cannot appear over a mirrored phone screen. */ val playback: PlaybackSnapshot? = null,-)+ /**+ * The last thing the phone said about what is playing, whichever track it describes.+ *+ * Beside [phase] for [playback]'s reason, and stored unconditionally rather than filtered on+ * arrival - see [nowPlayingForCurrentItem], which is where it is actually decided whether this+ * describes the audio coming out of the speakers.+ */+ val nowPlaying: NowPlaying? = null,+ /**+ * The resource the player was last told to play, or empty before anything.+ *+ * **Here rather than only on the player, because it is half of a comparison the UI makes.** The+ * player's own copy is a plain field that nothing recomposes on; keeping it beside the snapshot+ * means the two are read from one immutable object and can never be compared across a moment in+ * which one of them changed.+ */+ val playingResourceId: String = "",+ /**+ * Where cover art for [nowPlaying] can be fetched from, while a served session is live.+ *+ * **In the state rather than a field of `ReceiverController`, because the screen reads it during+ * composition** - and composition does not observe a plain field, so a null read at the moment the+ * screen first mounts would be corrected only incidentally, the next time something else changed.+ * Null is the whole of "there is nothing to fetch from": screen mirroring, or a session that has+ * ended.+ */+ val artwork: ArtworkFetcher? = null,+) {+ /**+ * The metadata for what is actually playing, or null.+ *+ * **The correlation gate for a served session, and it is load-bearing there.** The control channel+ * is ordered but the phone's *producers* are not: a metadata job for one track can finish after+ * the next track's `PLAY_MEDIA` has gone out. A receiver that drew whatever arrived last would+ * paint the previous cover over this audio and never correct itself, because nothing further is+ * coming.+ *+ * Compared at read time rather than filtered on arrival, which also makes the two messages' order+ * irrelevant: a snapshot that lands before the play it describes is simply not shown yet, and+ * starts being shown the moment the play arrives.+ *+ * **A snapshot naming no resource is shown unconditionally**, which is the mirrored case rather+ * than a hole in the gate. Nothing is served, so there is no id to compare - and nothing to+ * compare: the phone holds the player there, so the last thing it said is what it is playing.+ * [playingResourceId] is empty for such a session too, so the comparison would in fact hold; it is+ * spelled out because relying on two unrelated blanks matching is the kind of coincidence that+ * stops being true the first time either side gains a default.+ */+ val nowPlayingForCurrentItem: NowPlaying?+ get() = nowPlaying?.takeIf { it.resourceId.isEmpty() || it.resourceId == playingResourceId }+} /** * One playback snapshot, with the moment it landed.
cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/NowPlaying.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/NowPlaying.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/NowPlaying.ktnew file mode 100644index 0000000000..eed717d65a--- /dev/null+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/NowPlaying.kt@@ -0,0 +1,296 @@+package com.vayunmathur.cast.tv.ui++import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxHeight+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.itemsIndexed+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawWithContent+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.CompositingStrategy+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.em+import androidx.compose.ui.unit.sp+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.vayunmathur.cast.protocol.LyricLine+import com.vayunmathur.cast.protocol.NowPlaying+import com.vayunmathur.cast.tv.R+import com.vayunmathur.cast.tv.platform.ArtworkFetcher+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * The cover and the lyrics, for a session with no picture.+ *+ * **Not part of `ReceiverContent`.** For an audio-only session `MirrorActivity` adds no `SurfaceView`+ * at all and fills its window with a `ComposeView`, so `ReceiverContent`'s mirroring arm is on screen+ * for a few milliseconds and then never again. This is drawn by `MirrorActivity.overlayView()`, above+ * the transport overlay that is already pinned permanently visible for audio.+ *+ * **The title, author and album are deliberately not here.** They live in [TransportOverlay]'s+ * headline, where they serve a video session too and where the space is already reserved for a line of+ * text. Drawing them in both places spent this screen's whole vertical budget on saying twice what the+ * bar underneath says once - which is what pushed the cover off the top of the panel.+ *+ * **Nothing on it is focusable, and the reason is not `TransportOverlay`'s.** That overlay avoids+ * focus so the compositor is never asked to redraw a video layer underneath it; an audio-only session+ * has no video layer, so that argument does not apply here. The reason here is simply that there is+ * no input model on this screen - the lyrics scroll from the clock, so a scrollable focus target would+ * be a thing the remote could move that changes nothing and takes the D-pad away from seeking.+ *+ * It does **not** paint a background. `MirrorActivity` paints the window once, behind both this and+ * the transport bar beneath it, so that the two are one continuous surface rather than a sheet of+ * colour with a differently-coloured strip under it. Painting here as well would be a second owner of+ * the same pixels and would put the seam back the moment either colour changed.+ *+ * [positionMs] is a lambda rather than a `Long` on purpose. It is read sixty times a second, and+ * passing the value would recompose the artwork and the entire lyrics column every frame on hardware+ * with no headroom to spare. Only the small subtree that derives the lyric index from it recomposes,+ * and that a few dozen times a song.+ */+@Composable+fun NowPlayingScreen(+ nowPlaying: NowPlaying,+ /** Where playback is right now, read per frame. See the note above about why it is a lambda. */+ positionMs: () -> Long,+ artwork: ArtworkFetcher?,+ modifier: Modifier = Modifier,+) {+ val cover = rememberArtwork(nowPlaying.artworkResourceId, artwork)+ val hasLyrics = nowPlaying.lyrics.isNotEmpty() || nowPlaying.plainLyrics.isNotEmpty()++ Box(+ modifier = modifier+ .fillMaxSize()+ .padding(horizontal = 48.dp, vertical = 32.dp),+ ) {+ if (hasLyrics) {+ Row(+ modifier = Modifier.fillMaxSize(),+ horizontalArrangement = Arrangement.spacedBy(48.dp),+ ) {+ // **Sized from the height it is given, never from a constant.** This panel is 540dp+ // tall, so a cover with a fixed edge overflows and - centred - runs off the top of the+ // screen rather than being clipped at the bottom where it would at least be obvious.+ // Squaring a filled height cannot overflow whatever the window turns out to be.+ Cover(cover, Modifier.fillMaxHeight())+ Lyrics(nowPlaying, positionMs, Modifier.weight(1f).fillMaxHeight())+ }+ } else {+ // The common case, not the exception - every MP3 reaches here, because the phone's lyrics+ // reader handles Vorbis and MP4 tags and not ID3. A centred cover with the bar naming it+ // looks deliberate; the split layout with one half empty looks unfinished.+ Box(+ modifier = Modifier.fillMaxSize(),+ contentAlignment = Alignment.Center,+ ) {+ Cover(cover, Modifier.fillMaxHeight())+ }+ }+ }+}++/**+ * The cover, or a drawn stand-in for one.+ *+ * **Never a broken image.** No artwork is by far the most likely outcome for a library of loose+ * files, and it is also what a failed fetch and a fetch still in flight look like - so all three land+ * on a tonal surface that says so in words rather than on anything that reads as an error.+ */+@Composable+private fun Cover(cover: ImageBitmap?, modifier: Modifier) {+ Box(+ modifier = modifier+ .aspectRatio(1f)+ .clip(RoundedCornerShape(16.dp))+ .background(MaterialTheme.colorScheme.surfaceVariant),+ contentAlignment = Alignment.Center,+ ) {+ if (cover != null) {+ Image(+ bitmap = cover,+ contentDescription = stringResource(R.string.tv_now_playing_artwork),+ modifier = Modifier.fillMaxSize(),+ contentScale = ContentScale.Crop,+ )+ } else {+ Text(+ text = stringResource(R.string.tv_now_playing_no_artwork),+ style = MaterialTheme.typography.titleMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ textAlign = TextAlign.Center,+ )+ }+ }+}++/**+ * Timed lyrics that follow the clock, or untimed ones as a block.+ *+ * `userScrollEnabled = false` and no focus: this list is driven entirely from [positionMs].+ *+ * The index comes from a `derivedStateOf` over that lambda, which is what keeps the cost of a per-frame+ * clock off this column - it recomputes every frame but only *invalidates* when the answer changes,+ * which is a few dozen times a song rather than sixty times a second.+ *+ * **The current line is scrolled to the top, and what is below it fades out.** Upcoming lyrics read+ * downward, so the gradient falls in the direction the eye is already travelling and the line being+ * sung is the most legible thing on the panel. It is a mask over the whole column rather than a+ * per-line alpha, because a line half in and half out of the fade should fade by the same amount as+ * the pixels around it.+ */+@Composable+private fun Lyrics(nowPlaying: NowPlaying, positionMs: () -> Long, modifier: Modifier) {+ if (nowPlaying.lyrics.isEmpty()) {+ // Nothing to highlight and nothing to scroll to, so it is a block the user reads at their own+ // pace. Scrollable would be a lie: there is no input for it.+ LazyColumn(modifier = modifier.fadingEdge(), userScrollEnabled = false) {+ item {+ Text(+ text = nowPlaying.plainLyrics,+ fontSize = LYRIC_SIZE_SP.sp,+ lineHeight = LYRIC_LINE_HEIGHT_EM.em,+ color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.8f),+ )+ }+ }+ return+ }++ val lines = nowPlaying.lyrics+ // `rememberUpdatedState`, and it is load-bearing. `PlaybackClock` builds a fresh lambda per+ // recomposition that closes over *that* composition's snapshot; a `remember` keyed only on the+ // lines would pin the first one for the whole track, so the highlight would keep extrapolating+ // from the first anchor and never see a pause, a seek or a scrub. Only `frameNowMs` is live+ // inside that lambda - everything else in it is captured by value.+ val clock by rememberUpdatedState(positionMs)+ val current by remember(lines) {+ derivedStateOf { currentLyricIndex(lines, clock()) }+ }+ val listState = rememberLazyListState()+ LaunchedEffect(current, lines) {+ if (current >= 0) runCatching { listState.animateScrollToItem(current) }+ }++ LazyColumn(+ state = listState,+ modifier = modifier.fadingEdge(),+ userScrollEnabled = false,+ // **Between items, and [LYRIC_LINE_HEIGHT_EM] within one.** A long lyric wraps, and spacing+ // alone leaves the wrapped halves of one line closer together than the default leading allows+ // - so two lines of one lyric collide while the gap to the next lyric looks generous.+ verticalArrangement = Arrangement.spacedBy(LYRIC_GAP_DP.dp),+ // Room to scroll the last lyric up to where the current one is read, instead of it stopping+ // part-way and leaving the highlight pinned at the bottom for the outro.+ contentPadding = PaddingValues(bottom = 240.dp),+ ) {+ itemsIndexed(lines) { index, line ->+ val isCurrent = index == current+ Text(+ text = line.text,+ fontSize = if (isCurrent) LYRIC_CURRENT_SIZE_SP.sp else LYRIC_SIZE_SP.sp,+ lineHeight = LYRIC_LINE_HEIGHT_EM.em,+ fontWeight = if (isCurrent) FontWeight.Bold else FontWeight.Normal,+ color = if (isCurrent) {+ MaterialTheme.colorScheme.primary+ } else {+ MaterialTheme.colorScheme.onSurface.copy(alpha = 0.55f)+ },+ )+ }+ }+}++/**+ * Fades the bottom of a column out to nothing.+ *+ * `DstIn` over an offscreen layer, which is the one way to make a *mask* rather than a scrim: a+ * gradient drawn in the background colour would be opaque over the cover beside it, and one drawn in+ * black would be a grey wash on any theme but this one. Offscreen compositing is required for the+ * blend to have the column's own alpha to work against.+ */+private fun Modifier.fadingEdge(): Modifier = this+ .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen }+ .drawWithContent {+ drawContent()+ drawRect(+ brush = Brush.verticalGradient(+ FADE_START to Color.White,+ 1f to Color.Transparent,+ ),+ blendMode = BlendMode.DstIn,+ )+ }++/**+ * Which line is current at [positionMs], or -1 before the first one.+ *+ * The same rule the phone applies, deliberately written out rather than shared: `:music` and this+ * module have no common dependency, and one `indexOfLast` is a smaller thing to duplicate than a+ * module boundary is to move. The boundary is inclusive - a line whose timestamp is exactly the+ * position is the line being sung.+ */+private fun currentLyricIndex(lines: List<LyricLine>, positionMs: Long): Int =+ lines.indexOfLast { it.atMs <= positionMs }++/**+ * The decoded cover for [resourceId], or null while it is being fetched and if it never arrives.+ *+ * Keyed on the resource id, so a track change starts a fresh fetch and - more importantly - drops the+ * previous cover the instant the id changes rather than leaving it on screen over the next track.+ */+@Composable+private fun rememberArtwork(resourceId: String, artwork: ArtworkFetcher?): ImageBitmap? {+ if (resourceId.isEmpty() || artwork == null) return null+ val bitmap by produceState<ImageBitmap?>(initialValue = null, resourceId, artwork) {+ value = withContext(Dispatchers.IO) { artwork.fetch(resourceId)?.asImageBitmap() }+ }+ return bitmap+}++/**+ * Lyric sizes, for a panel that reports 960x540dp.+ *+ * Legible across a room and small enough that half a dozen lines fit beside the cover, which is what+ * makes the highlight look like it is moving through a song rather than replacing the screen.+ */+private const val LYRIC_CURRENT_SIZE_SP = 28+private const val LYRIC_SIZE_SP = 22+private const val LYRIC_GAP_DP = 20++/** Leading within one wrapped lyric, as a multiple of its own size. */+private const val LYRIC_LINE_HEIGHT_EM = 1.35f++/** Where the fade begins, as a fraction of the column's height. */+private const val FADE_START = 0.55f
cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/TransportOverlay.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/TransportOverlay.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/TransportOverlay.ktindex 61fc0f158c..bb9ce1c80d 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/TransportOverlay.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/TransportOverlay.kt@@ -26,14 +26,50 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.tv.material3.MaterialTheme import androidx.tv.material3.Text+import com.vayunmathur.cast.protocol.NowPlaying import com.vayunmathur.cast.tv.R import com.vayunmathur.cast.tv.platform.PlaybackSnapshot /**- * The transport controls, over the picture.+ * Owns the one per-frame clock a served session needs, and hands it down as a lambda.+ *+ * [TransportOverlay] used to own its own `withFrameMillis` ticker, which was right while it was the+ * only thing on screen that moved. The now-playing screen's lyrics need the same interpolated+ * position and the same scrub-preview override, and two tickers would be two answers to one question.+ *+ * **Hoisted as a lambda, not as a value, and the distinction is the whole point.** Passing the number+ * down would put every reader of it in the recomposition scope that invalidates sixty times a second -+ * which on TV-class hardware means redrawing a bitmap and a full lyrics column per frame. Passing a+ * lambda leaves the invalidation here, where the state is read, and lets each reader decide how much+ * of itself depends on it.+ *+ * Keyed on the snapshot so every fresh one re-anchors, and the ticker stops while playback is paused:+ * a frame callback per frame for a still bar would keep the panel awake for nothing.+ */+@Composable+fun PlaybackClock(+ snapshot: PlaybackSnapshot,+ /** A scrub the user is composing, which overrides the clock entirely. Null when not scrubbing. */+ scrubPreviewMs: Long?,+ content: @Composable (positionMs: () -> Long) -> Unit,+) {+ var frameNowMs by remember { mutableLongStateOf(System.currentTimeMillis()) }+ LaunchedEffect(snapshot) {+ frameNowMs = System.currentTimeMillis()+ if (!snapshot.state.playing) return@LaunchedEffect+ while (true) {+ withFrameMillis { frameNowMs = System.currentTimeMillis() }+ }+ }+ content { scrubPreviewMs ?: snapshot.positionAt(frameNowMs) }+}++/**+ * The transport controls: a bar at the bottom of whatever it is given. * * **Nothing here is focusable, and that is deliberate rather than an omission.** A media overlay is * driven by the remote's dedicated keys and its D-pad as *gestures* - left seeks, up is volume - not by@@ -44,111 +80,165 @@ import com.vayunmathur.cast.tv.platform.PlaybackSnapshot * * Only mounted while the phone is reporting playback, so it cannot appear over a mirrored phone screen * - there would be no transport to control.+ *+ * **It sizes itself to its content and lets the caller place it, rather than filling the window.** Over+ * video it is aligned to the bottom of a `Box` and overlays the picture, which is the whole point of a+ * scrim. For audio there is no picture, so `MirrorActivity` stacks it under the now-playing screen in a+ * `Column` instead - and then the lyrics get exactly the height that is left, rather than the height+ * left over from a constant somebody guessed at. Filling the window made that impossible to express.+ *+ * **The clock is not its own any more.** [positionMs] is read per frame and supplied by+ * [PlaybackClock], which owns the ticker so that this and the now-playing screen's lyrics move against+ * one number. A lambda rather than a `Long` for the reason [PlaybackClock] gives. */ @Composable fun TransportOverlay( snapshot: PlaybackSnapshot,+ /** Who is casting, shown until the phone says what is playing. Usually the app's name. */ sourceName: String,- /** A scrub in progress, which has not been committed to the phone yet. Null when not scrubbing. */- scrubPreviewMs: Long?,+ /** What is playing, or null when the phone has not said - an old build, or the first moment. */+ nowPlaying: NowPlaying?,+ /** Where playback is right now, including any scrub preview. Read per frame. */+ positionMs: () -> Long,+ /** Whether a scrub is in progress, which thickens the bar. */+ scrubbing: Boolean,+ /**+ * Whether to darken behind itself.+ *+ * True over a picture, where the gradient is what keeps the frame visible through the controls and+ * the numbers legible against whatever happens to be behind them. **False for audio**, where there+ * is no picture to see through and the scrim would be a black band across the bottom of an+ * otherwise continuous surface - the caller has already painted the window, and the bar belongs to+ * the same sheet of colour as the cover and the lyrics above it.+ */+ scrim: Boolean = true, modifier: Modifier = Modifier, ) { val state = snapshot.state+ val position = positionMs() - // Redrawn with the panel rather than with the phone's reports. A bar plotted only when a snapshot- // landed would step twice a second; anchoring on the snapshot and advancing with the frame clock is- // what makes it move like a seek bar. Keyed on the snapshot so every fresh one re-anchors.- var frameNowMs by remember { mutableLongStateOf(System.currentTimeMillis()) }- LaunchedEffect(snapshot) {- frameNowMs = System.currentTimeMillis()- // Nothing to advance while paused, and a frame callback per frame for a still bar would keep- // the panel awake for no reason.- if (!state.playing) return@LaunchedEffect- while (true) {- withFrameMillis { frameNowMs = System.currentTimeMillis() }- }- }- val positionMs = scrubPreviewMs ?: snapshot.positionAt(frameNowMs)-- Box(modifier = modifier.fillMaxSize()) {- Column(- modifier = Modifier- .align(Alignment.BottomCenter)- .fillMaxWidth()- // A scrim rather than a panel: the picture stays visible behind the controls, which is- // what makes scrubbing usable at all.- .background(- Brush.verticalGradient(- listOf(Color.Transparent, Color.Black.copy(alpha = 0.85f)),- ),- )- .padding(horizontal = 48.dp, vertical = 32.dp),- verticalArrangement = Arrangement.spacedBy(12.dp),- ) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically,- ) {- Text(- text = sourceName,- style = MaterialTheme.typography.titleLarge,- color = Color.White,- )- if (state.speed != 1f) {- Text(- text = stringResource(R.string.tv_transport_speed, formatSpeed(state.speed)),- style = MaterialTheme.typography.titleMedium,- color = Color.White.copy(alpha = 0.8f),+ Column(+ modifier = modifier+ .fillMaxWidth()+ .then(+ if (scrim) {+ Modifier.background(+ Brush.verticalGradient(+ listOf(Color.Transparent, Color.Black.copy(alpha = 0.85f)),+ ), )- }- }-- SeekBar(- positionMs = positionMs,- durationMs = state.durationMs,- scrubbing = scrubPreviewMs != null,+ } else {+ Modifier+ }, )-- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- ) {- Text(- text = elapsed(positionMs),- style = MaterialTheme.typography.bodyLarge,- color = Color.White,- )- // **The action the centre key will take, not a description of the state.** Read as a- // status it would be the other way round, and both readings are defensible - which is- // exactly why it has to match the button it sits next to. Buffering is its own case:- // a stall and a pause look identical on a frozen picture, and only one of them is the- // user's own doing.- Text(- text = when {- state.buffering -> "…"- state.playing -> "❚❚"- else -> "▶"- },- style = MaterialTheme.typography.bodyLarge,- color = Color.White,- )+ .padding(horizontal = 48.dp, vertical = 24.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp),+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Headline(+ nowPlaying = nowPlaying,+ sourceName = sourceName,+ modifier = Modifier.weight(1f),+ )+ if (state.speed != 1f) { Text(- text = if (state.durationMs > 0) elapsed(state.durationMs) else "",- style = MaterialTheme.typography.bodyLarge,- color = Color.White,+ text = stringResource(R.string.tv_transport_speed, formatSpeed(state.speed)),+ style = MaterialTheme.typography.titleMedium,+ color = Color.White.copy(alpha = 0.8f), ) }+ }++ SeekBar(+ positionMs = position,+ durationMs = state.durationMs,+ scrubbing = scrubbing,+ ) + Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ ) {+ Text(+ text = elapsed(position),+ style = MaterialTheme.typography.bodyLarge,+ color = Color.White,+ )+ // **The action the centre key will take, not a description of the state.** Read as a+ // status it would be the other way round, and both readings are defensible - which is+ // exactly why it has to match the button it sits next to. Buffering is its own case:+ // a stall and a pause look identical on a frozen picture, and only one of them is the+ // user's own doing. Text(- text = stringResource(R.string.tv_transport_hint),- style = MaterialTheme.typography.bodySmall,- color = Color.White.copy(alpha = 0.6f),+ text = when {+ state.buffering -> "…"+ state.playing -> "❚❚"+ else -> "▶"+ },+ style = MaterialTheme.typography.bodyLarge,+ color = Color.White,+ )+ Text(+ text = if (state.durationMs > 0) elapsed(state.durationMs) else "",+ style = MaterialTheme.typography.bodyLarge,+ color = Color.White, ) }++ Text(+ text = stringResource(R.string.tv_transport_hint),+ style = MaterialTheme.typography.bodySmall,+ color = Color.White.copy(alpha = 0.6f),+ )+ }+}++/**+ * What is playing, or who is casting when that is all the television knows.+ *+ * **The title replaces the app's name rather than sitting beside it.** "Receiving from YouPipe" was+ * the most the receiver could say when nothing crossed the protocol but pixels; with a title in hand+ * it is the less useful of the two, and a user looking at a video already knows which app they+ * started. The fallback keeps it for an old phone, an app that sends no metadata, and the moment+ * before the first snapshot lands.+ *+ * **Every field it has, and no field it does not**, which is why there is no video-shaped branch here:+ * a track fills all three lines and a video fills two, because `album` is what a video has nothing to+ * put in. Stacked rather than joined onto one line - a video title is long and a channel name is+ * short, and one line holding both would truncate the title to fit something that is not the title.+ */+@Composable+private fun Headline(nowPlaying: NowPlaying?, sourceName: String, modifier: Modifier) {+ Column(modifier = modifier) {+ Text(+ text = nowPlaying?.title.orEmpty().ifBlank { sourceName },+ style = MaterialTheme.typography.titleLarge,+ color = Color.White,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ Subtitle(nowPlaying?.author.orEmpty(), alpha = 0.7f)+ Subtitle(nowPlaying?.album.orEmpty(), alpha = 0.5f) } } +/** One line beneath the title, or nothing at all when there is nothing to put on it. */+@Composable+private fun Subtitle(text: String, alpha: Float) {+ if (text.isBlank()) return+ Text(+ text = text,+ style = MaterialTheme.typography.titleMedium,+ color = Color.White.copy(alpha = alpha),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+}+ /** * The bar, drawn as nested boxes rather than as a `Slider`. *
cast/tv/src/main/res/values/strings.xml
diff --git a/cast/tv/src/main/res/values/strings.xml b/cast/tv/src/main/res/values/strings.xmlindex 801feb6e39..f4429e1629 100644--- a/cast/tv/src/main/res/values/strings.xml+++ b/cast/tv/src/main/res/values/strings.xml@@ -32,6 +32,10 @@ <string name="tv_transport_speed">%1$s×</string> <string name="tv_transport_hint">OK to play or pause · ◀ ▶ to seek · ▲ ▼ for volume</string> + <!-- Now playing, for an audio-only session where there is no picture -->+ <string name="tv_now_playing_no_artwork">No cover art</string>+ <string name="tv_now_playing_artwork">Cover art</string>+ <!-- Foreground service --> <string name="tv_notification_channel_name">Receiving</string> <string name="tv_notification_channel_desc">Shown while this TV is available to cast to</string>
music/src/main/java/com/vayunmathur/music/platform/CastPlayback.kt
diff --git a/music/src/main/java/com/vayunmathur/music/platform/CastPlayback.kt b/music/src/main/java/com/vayunmathur/music/platform/CastPlayback.ktindex 3692d87d63..f8e553c136 100644--- a/music/src/main/java/com/vayunmathur/music/platform/CastPlayback.kt+++ b/music/src/main/java/com/vayunmathur/music/platform/CastPlayback.kt@@ -1,8 +1,10 @@ package com.vayunmathur.music.platform +import android.content.ContentUris import android.content.Context import android.net.Uri import android.os.ParcelFileDescriptor+import android.provider.MediaStore import android.util.Log import androidx.core.net.toUri import com.vayunmathur.library.media.OpusTranscoder@@ -120,6 +122,18 @@ object CastPlayback { @Volatile private var transcodeJob: Job? = null + /**+ * The running metadata job, so a track change can cancel it.+ *+ * **Cancelled rather than left to lose a race.** Reading a cover out of a file and re-compressing+ * it takes long enough that a job for track A can finish after track B has started playing, and+ * its snapshot would then describe the wrong audio. The television refuses a snapshot that does+ * not name what it is playing as well - see `NowPlaying.resourceId` - because either measure alone+ * leaves a window: cancellation is not instantaneous, and a gate cannot stop wasted work.+ */+ @Volatile+ private var metadataJob: Job? = null+ /** * What the TV has been told about, by resource id. *@@ -211,6 +225,11 @@ object CastPlayback { // for. Skipped when the id matches, so replaying the current track does not kill its own. cancelTranscodeExcept(id) + // Above the three branches below, because the first of them returns early: a track replayed+ // within one session takes the `offered` fast path, and metadata launched inside it would+ // never run at all.+ startMetadata(context, active, song, id)+ val known = offered[id] if (known != null) { active.play(id, known.contentType, song.duration, startPositionMs)@@ -303,6 +322,117 @@ object CastPlayback { transcodeJob?.cancel() } + // ------------------------------------------------------------------+ // What the television shows while it plays+ // ------------------------------------------------------------------++ /**+ * Tell the TV what this track is, and then what it looks like.+ *+ * **Two sends, because the two halves are ready at different times.** The text is already in the+ * `Music` row the caller handed over, so it goes out at once and the television has a real+ * now-playing screen from the first moment. The cover has to be read out of the file and+ * re-compressed, and the lyrics out of its tag region, so those follow in a second snapshot -+ * which is exactly why this is not fields on `PLAY_MEDIA`, where changing them would mean+ * restarting the track.+ *+ * The artwork resource is registered in [offered] and its bytes are on disk **before** its id is+ * named, and that ordering is not stylistic: the TV fetches the id the moment it arrives, and an+ * unoffered one is a `404` it does not retry.+ */+ private fun startMetadata(context: Context, active: CastClient, song: Music, id: String) {+ metadataJob?.cancel()+ active.setNowPlaying(+ resourceId = id,+ title = song.title,+ author = song.artist,+ album = song.album,+ )+ metadataJob = scope.launch {+ val lyrics = classifyLyrics(EmbeddedLyrics.read(context, song.uri.toUri()))+ val timed = (lyrics as? Lyrics.Timed)?.lines.orEmpty()+ val artworkId = prepareArtwork(context, song)+ active.setNowPlaying(+ resourceId = id,+ title = song.title,+ author = song.artist,+ album = song.album,+ artworkResourceId = artworkId.orEmpty(),+ lyricTimesMs = LongArray(timed.size) { timed[it].timestamp },+ lyricTexts = Array(timed.size) { timed[it].text },+ plainLyrics = (lyrics as? Lyrics.Plain)?.text.orEmpty(),+ )+ }+ }++ /**+ * The resource id the cover can be fetched from, or null when the track has none.+ *+ * Cached on disk beside the converted audio, so a track cast twice - in this session or a later+ * one - is read, scaled and re-compressed only once. An ordinary [Source.Cached]: a real file with+ * a real length, so it needs no `resourceComplete` handshake and no new kind of source.+ *+ * **The file's extension carries the content type**, which is what makes the disk hit usable at+ * all: `offered` is emptied when a session ends, so a later cast finds only the file - and the+ * proxy has to state a type for it. Sniffing the bytes back would cost about as much as producing+ * them again.+ */+ private suspend fun prepareArtwork(context: Context, song: Music): String? =+ withContext(Dispatchers.IO) {+ val id = artworkResourceId(song.id)+ if (offered[id]?.let { hasBytes(it) } == true) return@withContext id++ // A file left by an earlier session, which `offered` knows nothing about.+ for ((extension, contentType) in ARTWORK_TYPES) {+ val existing = artworkFile(context, song.id, extension)+ if (existing.length() > 0) {+ offered[id] = Prepared(Source.Cached(existing), contentType)+ return@withContext id+ }+ }++ val artwork = runCatching {+ artworkBytes(context, song.uri.toUri(), albumArtUri(song.albumId))+ }.getOrNull() ?: return@withContext null+ val extension = ARTWORK_TYPES.entries.firstOrNull { it.value == artwork.contentType }?.key+ ?: return@withContext null+ val file = artworkFile(context, song.id, extension)+ val written = runCatching {+ file.parentFile?.mkdirs()+ file.writeBytes(artwork.bytes)+ true+ }.getOrDefault(false)+ if (!written) return@withContext null+ offered[id] = Prepared(Source.Cached(file), artwork.contentType)+ id+ }++ /** Whether an offered resource still has a file with something in it behind it. */+ private fun hasBytes(prepared: Prepared): Boolean =+ (prepared.source as? Source.Cached)?.file?.length()?.let { it > 0 } == true++ /**+ * The album's `MediaStore` entry, which is where the fallback thumbnail comes from.+ *+ * Built rather than looked up: this is the same URI `getAlbums` composes for `Album.uri`, so+ * reaching into the repository for it would be a database read to reconstruct an id we already+ * have.+ */+ private fun albumArtUri(albumId: Long): Uri? = runCatching {+ ContentUris.withAppendedId(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, albumId)+ }.getOrNull()++ /**+ * Prefixed, so an artwork id can never collide with a track id.+ *+ * Both live in one [offered] map and both are addressed on one proxy, and a track whose numeric id+ * happened to match another's would otherwise serve a JPEG as audio.+ */+ private fun artworkResourceId(songId: Long): String = "$ARTWORK_PREFIX$songId"++ private fun artworkFile(context: Context, songId: Long, extension: String): File =+ File(File(context.cacheDir, ARTWORK_CACHE_DIR), "$songId.$extension")+ fun close() { client?.close() clear()@@ -313,6 +443,8 @@ object CastPlayback { // `growing`, and letting it run on would leave it writing into a session that has gone. transcodeJob?.cancel() transcodeJob = null+ metadataJob?.cancel()+ metadataJob = null _growing.value = null client = null offered.clear()@@ -380,11 +512,21 @@ object CastPlayback { ?: return null CastResource(descriptor, descriptor.statSize, prepared.contentType) }- is Source.Cached -> CastResource(- ParcelFileDescriptor.open(source.file, ParcelFileDescriptor.MODE_READ_ONLY),- source.file.length(),- prepared.contentType,- )+ is Source.Cached -> {+ // Checked rather than assumed: these files outlive the session that wrote them,+ // and one the system has reclaimed under storage pressure should be a clean 404+ // rather than an exception on Cast's own thread.+ if (!source.file.isFile) {+ Log.w(TAG, "'$resourceId' was cached and is no longer on disk")+ offered.remove(resourceId)+ return null+ }+ CastResource(+ ParcelFileDescriptor.open(source.file, ParcelFileDescriptor.MODE_READ_ONLY),+ source.file.length(),+ prepared.contentType,+ )+ } is Source.Growing -> CastResource( ParcelFileDescriptor.open(source.file, ParcelFileDescriptor.MODE_READ_ONLY), // Not `file.length()`: the length now is a snapshot of a file still growing,@@ -418,13 +560,17 @@ object CastPlayback { File(File(context.cacheDir, CACHE_DIR), "$songId.opus") /**- * Clears converted tracks.+ * Clears converted tracks and cached cover art. * * The cache is what makes a second cast of the same track free, so it is kept across sessions - * but it is a cache, and 256 kbps Opus of a whole library would not be small.+ *+ * **Both directories, or the one it forgot leaks for ever**: nothing else ever deletes them, and+ * a user who clears the cache means all of it. */ fun clearCache(context: Context) { runCatching { File(context.cacheDir, CACHE_DIR).deleteRecursively() }+ runCatching { File(context.cacheDir, ARTWORK_CACHE_DIR).deleteRecursively() } } /** Enough to cover an Ogg page header and the `OpusHead` packet that follows it. */@@ -432,6 +578,24 @@ object CastPlayback { private const val CACHE_DIR = "cast-opus" + /** Its own directory rather than a suffix in [CACHE_DIR], so either can be cleared alone. */+ private const val ARTWORK_CACHE_DIR = "cast-art"++ private const val ARTWORK_PREFIX = "art-"++ /**+ * The image types a cover is stored and served as, by the extension it is stored under.+ *+ * The extension is how the type survives a session ending, and the map is also what decides+ * whether a picture can be passed through untouched: a type not named here is re-compressed to+ * JPEG by `artworkBytes`, so there is never a file on disk this cannot state a type for.+ */+ private val ARTWORK_TYPES = mapOf(+ "jpg" to "image/jpeg",+ "png" to "image/png",+ "webp" to "image/webp",+ )+ /** * The length reported for a track still being encoded: negative means "still being written, * final size unknown", which is what makes Cast wait at the end of the file instead of
music/src/main/java/com/vayunmathur/music/platform/Lyrics.kt
diff --git a/music/src/main/java/com/vayunmathur/music/platform/Lyrics.kt b/music/src/main/java/com/vayunmathur/music/platform/Lyrics.ktnew file mode 100644index 0000000000..d851edea89--- /dev/null+++ b/music/src/main/java/com/vayunmathur/music/platform/Lyrics.kt@@ -0,0 +1,101 @@+package com.vayunmathur.music.platform++import com.vayunmathur.sdk.cast.CastContract++/**+ * One lyric line, and the position it belongs at.+ *+ * Lived in `ui/LyricsView.kt` while the only reader was a composable. It moved because [CastPlayback]+ * needs it too, and platform code must not import from `ui` - the dependency runs the other way.+ */+data class LyricLine(val timestamp: Long, val text: String)++/**+ * What a track's lyrics turned out to be.+ *+ * **Three cases rather than a list that is empty when it fails**, which is what the old+ * [parseLyrics] gave its only caller: a file with unsynced lyrics parsed to nothing, so the phone+ * said "no lyrics available" about a track that plainly had them. Naming the third case fixes that+ * and is what lets the two wire fields of `NowPlaying` be filled unambiguously - see+ * [CastContract.KEY_PLAIN_LYRICS] for why a sentinel timestamp is not an option.+ */+sealed interface Lyrics {++ /** No lyrics in the file, or nothing readable in what was there. */+ data object None : Lyrics++ /** LRC with timestamps, sorted, so a highlight can follow the clock. */+ data class Timed(val lines: List<LyricLine>) : Lyrics++ /** Text with no timings. Shown as a block, with nothing highlighted. */+ data class Plain(val text: String) : Lyrics+}++/**+ * Classifies whatever `EmbeddedLyrics.read` came back with.+ *+ * Timed wins whenever a single timestamp was found: a file with a few `[00:12.00]` lines and a lot+ * of loose text is a synced file with untimed headers in it, not a plain one.+ */+fun classifyLyrics(raw: String?): Lyrics {+ if (raw.isNullOrBlank()) return Lyrics.None+ val timed = parseLyrics(raw)+ if (timed.isNotEmpty()) return Lyrics.Timed(timed)+ // LRC metadata tags - `[ar:...]`, `[length:...]` - are not lyrics, and a file that is nothing but+ // those would otherwise be shown as a block of them.+ val plain = raw.lines()+ .filterNot { it.isBlank() || METADATA_TAG.matches(it.trim()) }+ .joinToString("\n") { it.trim() }+ return if (plain.isBlank()) Lyrics.None else Lyrics.Plain(plain)+}++/**+ * Which line is current at [positionMs], or -1 before the first one.+ *+ * Lifted out of the composable it was written in so the phone and the television share one tested+ * function rather than two copies of an `indexOfLast`. The boundary is inclusive: a line whose+ * timestamp is exactly the position is the line being sung.+ */+fun currentLyricIndex(lines: List<LyricLine>, positionMs: Long): Int =+ lines.indexOfLast { it.timestamp <= positionMs }++/**+ * Parses LRC lyric content into timed lines, or an empty list when there are none.+ *+ * Truncated to [CastContract.MAX_LYRIC_LINES] and [CastContract.MAX_LYRIC_CHARS] because these+ * lines cross a control frame when the track is cast, and a pathological file must not be able to+ * overflow one. The bound applies on the phone too rather than only on the way out: a lyrics view+ * with ten thousand lines in it is nobody's intent either.+ *+ * Known limits, deliberately unchanged: a line with several timestamps yields one entry rather than+ * one per timestamp, and enhanced-LRC word tags are left inline. Both change what real files render+ * as and belong in their own change.+ */+fun parseLyrics(lrcContent: String): List<LyricLine> {+ val lines = mutableListOf<LyricLine>()+ var chars = 0+ for (line in lrcContent.lines()) {+ if (lines.size >= CastContract.MAX_LYRIC_LINES) break+ val match = LYRIC_PATTERN.find(line) ?: continue+ val fraction = match.groupValues[3]+ val text = match.groupValues[4].trim()+ if (text.isEmpty()) continue+ if (chars + text.length > CastContract.MAX_LYRIC_CHARS) break+ val minutes = match.groupValues[1].toLongOrNull() ?: continue+ val seconds = match.groupValues[2].toLongOrNull() ?: continue+ val fractionValue = fraction.toLongOrNull() ?: continue+ // Two digits are centiseconds and three are milliseconds, which is the one thing the LRC+ // format leaves to be inferred from the field's width.+ val timestamp = minutes * 60_000 + seconds * 1_000 ++ if (fraction.length == 2) fractionValue * 10 else fractionValue+ lines.add(LyricLine(timestamp, text))+ chars += text.length+ }+ return lines.sortedBy { it.timestamp }+}++/** `[mm:ss.xx] text`, with a two- or three-digit fraction. */+private val LYRIC_PATTERN = Regex("\\[(\\d{2}):(\\d{2})\\.(\\d{2,3})](.*)")++/** An LRC header such as `[ti:Title]`: a colon-separated tag rather than a timestamp. */+private val METADATA_TAG = Regex("\\[[a-zA-Z#]+:.*]")
music/src/main/java/com/vayunmathur/music/platform/Util.kt
diff --git a/music/src/main/java/com/vayunmathur/music/platform/Util.kt b/music/src/main/java/com/vayunmathur/music/platform/Util.ktindex aee9f14bef..bf5705585d 100644--- a/music/src/main/java/com/vayunmathur/music/platform/Util.kt+++ b/music/src/main/java/com/vayunmathur/music/platform/Util.kt@@ -3,6 +3,7 @@ import com.vayunmathur.music.R import android.content.ContentUris import android.content.Context import android.graphics.Bitmap+import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.Rect import android.media.MediaMetadataRetriever@@ -27,6 +28,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalInspectionMode import androidx.core.graphics.createBitmap+import androidx.core.graphics.scale import com.vayunmathur.library.image.compose.AsyncImage import com.vayunmathur.library.image.ImageRequest import com.vayunmathur.library.image.Size as CoilSize@@ -35,6 +37,7 @@ import com.vayunmathur.music.data.Artist import com.vayunmathur.music.data.Music import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext+import java.io.ByteArrayOutputStream import java.util.Locale import androidx.compose.ui.res.stringResource @@ -293,4 +296,95 @@ fun getAudioYear(context: Context, uri: Uri): Int = val raw = it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_YEAR) ?: it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DATE) raw?.let { value -> Regex("\\d{4}").find(value)?.value?.toIntOrNull() } ?: 0- }\ No newline at end of file+ }++/** Cover art bytes, with the type a server would have to state for them. */+class ArtworkBytes(val bytes: ByteArray, val contentType: String)++/**+ * The largest edge a cover is sent at.+ *+ * Bounding this on the phone is what keeps the receiver simple - it decodes whatever arrives with no+ * pre-pass - and stops a 6 MB scan of an LP sleeve competing with the initial audio buffer over+ * Wi-Fi. Generous for a television: 1280px fills the cover half of a 4K panel.+ */+private const val ARTWORK_MAX_EDGE = 1280++private const val ARTWORK_JPEG_QUALITY = 88++/**+ * A track's cover art as bytes, bounded in size, or null when it has none.+ *+ * The embedded picture first, because it is the original at full resolution and is common even on+ * MP3s, where nothing else about the file's tags is readable. [fallbackArtUri] is the album's+ * `MediaStore` entry, whose 300x300 thumbnail is small for a television panel but beats a+ * placeholder.+ *+ * **Re-compressed only when it has to be.** Bounds are decoded first, and a picture already inside+ * [ARTWORK_MAX_EDGE] is passed through untouched - so the common case costs one decode of a header+ * rather than a decode, a scale and a JPEG encode. The type is sniffed from the magic bytes rather+ * than assumed, because whoever serves these has to state it.+ */+fun artworkBytes(context: Context, uri: Uri, fallbackArtUri: Uri?): ArtworkBytes? {+ val embedded = withAudioMetadata(context, uri, null) { it.embeddedPicture }+ if (embedded != null) return boundedArtwork(embedded)+ val thumbnail = fallbackArtUri?.let { getThumbnail(context, it) } ?: return null+ return ArtworkBytes(compressToJpeg(thumbnail), "image/jpeg")+}++private fun boundedArtwork(source: ByteArray): ArtworkBytes? {+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }+ BitmapFactory.decodeByteArray(source, 0, source.size, bounds)+ val longest = maxOf(bounds.outWidth, bounds.outHeight)+ if (longest <= 0) return null+ val sniffed = sniffImageType(source)+ if (longest <= ARTWORK_MAX_EDGE && sniffed != null) return ArtworkBytes(source, sniffed)++ // `inSampleSize` only halves, so this lands at or below the bound and the scale below finishes+ // the job exactly - decoding at full size first is what a large cover must not be allowed to do.+ var sample = 1+ while (longest / (sample * 2) >= ARTWORK_MAX_EDGE) sample *= 2+ val decoded = BitmapFactory.decodeByteArray(+ source,+ 0,+ source.size,+ BitmapFactory.Options().apply { inSampleSize = sample },+ ) ?: return null+ val scaled = scaleWithin(decoded, ARTWORK_MAX_EDGE)+ val bytes = compressToJpeg(scaled)+ if (scaled !== decoded) scaled.recycle()+ decoded.recycle()+ return ArtworkBytes(bytes, "image/jpeg")+}++private fun scaleWithin(bitmap: Bitmap, maxEdge: Int): Bitmap {+ val longest = maxOf(bitmap.width, bitmap.height)+ if (longest <= maxEdge) return bitmap+ val scale = maxEdge.toDouble() / longest+ return bitmap.scale(+ (bitmap.width * scale).toInt().coerceAtLeast(1),+ (bitmap.height * scale).toInt().coerceAtLeast(1),+ )+}++private fun compressToJpeg(bitmap: Bitmap): ByteArray {+ val out = ByteArrayOutputStream()+ bitmap.compress(Bitmap.CompressFormat.JPEG, ARTWORK_JPEG_QUALITY, out)+ return out.toByteArray()+}++/**+ * The image type from its first bytes, or null for one nothing here can name.+ *+ * Null is what sends the picture through the re-compression path even when its size did not need it:+ * a type that cannot be stated honestly is worse than a JPEG, because a receiver is told what to+ * decode before it looks.+ */+private fun sniffImageType(bytes: ByteArray): String? = when {+ bytes.size < 12 -> null+ bytes[0] == 0xFF.toByte() && bytes[1] == 0xD8.toByte() -> "image/jpeg"+ bytes[0] == 0x89.toByte() && bytes[1] == 'P'.code.toByte() -> "image/png"+ String(bytes, 0, 4, Charsets.ISO_8859_1) == "RIFF" &&+ String(bytes, 8, 4, Charsets.ISO_8859_1) == "WEBP" -> "image/webp"+ else -> null+}\ No newline at end of file
music/src/main/java/com/vayunmathur/music/ui/LyricsView.kt
diff --git a/music/src/main/java/com/vayunmathur/music/ui/LyricsView.kt b/music/src/main/java/com/vayunmathur/music/ui/LyricsView.ktindex f8d7308465..e8e22d3fe6 100644--- a/music/src/main/java/com/vayunmathur/music/ui/LyricsView.kt+++ b/music/src/main/java/com/vayunmathur/music/ui/LyricsView.kt@@ -22,55 +22,70 @@ import androidx.compose.ui.unit.sp import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text import com.vayunmathur.music.R--// Data class to hold parsed lyric lines-data class LyricLine(val timestamp: Long, val text: String)-+import com.vayunmathur.music.platform.LyricLine+import com.vayunmathur.music.platform.Lyrics @Composable-fun LyricsView(lyrics: List<LyricLine>, currentIndex: Int) {- val listState = rememberLazyListState()-- // Auto-scroll to current lyric- LaunchedEffect(currentIndex) {- if (currentIndex >= 0) {- listState.animateScrollToItem(currentIndex)- }- }-+fun LyricsView(lyrics: Lyrics, currentIndex: Int) { Box( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.surfaceContainerHigh) .padding(16.dp) ) {- if (lyrics.isEmpty()) {- Text(+ when (lyrics) {+ Lyrics.None -> Text( stringResource(R.string.no_lyrics_available), color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.align(Alignment.Center), textAlign = TextAlign.Center )- } else {- LazyColumn(- state = listState,+ // Nothing to highlight and nothing to scroll to, so this is a block of text that the+ // user reads at their own pace. Previously these files read as "no lyrics available".+ is Lyrics.Plain -> LazyColumn( modifier = Modifier.fillMaxSize(),- verticalArrangement = Arrangement.spacedBy(12.dp), contentPadding = PaddingValues(vertical = 40.dp) ) {- itemsIndexed(lyrics) { index, line ->- val isCurrent = index == currentIndex+ item { Text(- text = line.text,- style = MaterialTheme.typography.titleLarge.copy(- fontWeight = if (isCurrent) FontWeight.Bold else FontWeight.Normal,- fontSize = if (isCurrent) 22.sp else 18.sp- ),- color = if (isCurrent) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,+ text = lyrics.text,+ style = MaterialTheme.typography.titleMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth() ) } }+ is Lyrics.Timed -> TimedLyrics(lyrics.lines, currentIndex)+ }+ }+}+@Composable+private fun TimedLyrics(lines: List<LyricLine>, currentIndex: Int) {+ val listState = rememberLazyListState()+ // Auto-scroll to current lyric+ LaunchedEffect(currentIndex) {+ if (currentIndex >= 0) {+ listState.animateScrollToItem(currentIndex)+ }+ }+ LazyColumn(+ state = listState,+ modifier = Modifier.fillMaxSize(),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ contentPadding = PaddingValues(vertical = 40.dp)+ ) {+ itemsIndexed(lines) { index, line ->+ val isCurrent = index == currentIndex+ Text(+ text = line.text,+ style = MaterialTheme.typography.titleLarge.copy(+ fontWeight = if (isCurrent) FontWeight.Bold else FontWeight.Normal,+ fontSize = if (isCurrent) 22.sp else 18.sp+ ),+ color = if (isCurrent) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth()+ ) } } }
music/src/main/java/com/vayunmathur/music/ui/NowPlayingScreen.kt
diff --git a/music/src/main/java/com/vayunmathur/music/ui/NowPlayingScreen.kt b/music/src/main/java/com/vayunmathur/music/ui/NowPlayingScreen.ktindex ab2c629a87..bd4c2cacc2 100644--- a/music/src/main/java/com/vayunmathur/music/ui/NowPlayingScreen.kt+++ b/music/src/main/java/com/vayunmathur/music/ui/NowPlayingScreen.kt@@ -10,7 +10,6 @@ import com.vayunmathur.music.platform.CastPlayback import com.vayunmathur.sdk.cast.CastClient import com.vayunmathur.sdk.cast.CastPickerContract import kotlinx.coroutines.launch-import android.util.Log import androidx.activity.compose.rememberLauncherForActivityResult import androidx.compose.animation.Crossfade import androidx.compose.foundation.background@@ -66,9 +65,12 @@ import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.music.R import com.vayunmathur.music.Route import com.vayunmathur.music.platform.AlbumArt+import com.vayunmathur.music.platform.Lyrics import com.vayunmathur.music.platform.MusicActions import com.vayunmathur.music.platform.NowPlayingUiState import com.vayunmathur.music.platform.PlaybackSource+import com.vayunmathur.music.platform.classifyLyrics+import com.vayunmathur.music.platform.currentLyricIndex import com.vayunmathur.music.platform.formatDuration @OptIn(ExperimentalMaterial3Api::class)@@ -81,12 +83,10 @@ fun NowPlayingScreen( // UI States var showLyrics by remember { mutableStateOf(false) } // Lyrics are read from the playing file's embedded tags (see EmbeddedLyrics); when a- // track carries none this is empty and the overlay shows "no lyrics" gracefully.- val rawLyrics = state.lyrics-- val parsedLyrics = remember(rawLyrics) { parseLyrics(rawLyrics) }- val currentLyricIndex = remember(parsedLyrics, state.positionMs) {- parsedLyrics.indexOfLast { it.timestamp <= state.positionMs }+ // track carries none this is Lyrics.None and the overlay says so gracefully.+ val lyrics = remember(state.lyrics) { classifyLyrics(state.lyrics) }+ val currentIndex = remember(lyrics, state.positionMs) {+ (lyrics as? Lyrics.Timed)?.let { currentLyricIndex(it.lines, state.positionMs) } ?: -1 } // RAW SCAFFOLD EXCEPTION: nested now-playing scaffold@@ -140,7 +140,7 @@ fun NowPlayingScreen( ) { Crossfade(targetState = showLyrics, label = "LyricsToggle") { isShowingLyrics -> if (isShowingLyrics) {- LyricsView(parsedLyrics, currentLyricIndex)+ LyricsView(lyrics, currentIndex) } else { Card( modifier = Modifier.fillMaxSize(),@@ -315,31 +315,3 @@ private fun CastButton(state: NowPlayingUiState) { } } }--/** Parses LRC lyric content. Public so [LyricsView] tests can reuse it if needed. */-fun parseLyrics(lrcContent: String): List<LyricLine> {- val lines = mutableListOf<LyricLine>()- // Regex to match [mm:ss.xx] text- val lyricPattern = Regex("\\[(\\d{2}):(\\d{2})\\.(\\d{2,3})](.*)")-- lrcContent.lines().forEach { line ->- try {- val match = lyricPattern.find(line)- if (match != null) {- val min = match.groupValues[1].toLong()- val sec = match.groupValues[2].toLong()- val ms = match.groupValues[3].toLong()- val text = match.groupValues[4].trim()-- // Convert to total milliseconds- val timestamp = (min * 60 * 1000) + (sec * 1000) + (if (match.groupValues[3].length == 2) ms * 10 else ms)- if (text.isNotEmpty()) {- lines.add(LyricLine(timestamp, text))- }- }- } catch (e: Exception) {- Log.e("SongScreen", "Error parsing lyric line: $line", e)- }- }- return lines.sortedBy { it.timestamp }-}
music/src/test/java/com/vayunmathur/music/platform/LyricsTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/platform/LyricsTest.kt b/music/src/test/java/com/vayunmathur/music/platform/LyricsTest.ktnew file mode 100644index 0000000000..156989abb4--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/platform/LyricsTest.kt@@ -0,0 +1,107 @@+package com.vayunmathur.music.platform++import com.vayunmathur.sdk.cast.CastContract+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertTrue++/**+ * The lyrics parser, now that two things read it.+ *+ * It moved out of `ui/NowPlayingScreen.kt` because `CastPlayback` needs it, and this is the first test+ * it has ever had. The existing behaviour is pinned as it is: the classification and the bound are+ * new, but nothing here is meant to change what a real LRC file renders as on the phone.+ */+class LyricsTest {++ private val synced = """+ [ti:Blue Monday]+ [ar:New Order]+ [00:12.00]how does it feel+ [00:16.12]to treat me like you do+ [01:04.5]+ [00:20.500]when you've laid your hands upon me+ """.trimIndent()++ @Test+ fun `a synced file classifies as timed, sorted, with empty lines dropped`() {+ val lyrics = assertIs<Lyrics.Timed>(classifyLyrics(synced))+ assertEquals(+ listOf(12_000L, 16_120L, 20_500L),+ lyrics.lines.map { it.timestamp },+ )+ assertEquals("how does it feel", lyrics.lines.first().text)+ }++ @Test+ fun `two fraction digits are centiseconds and three are milliseconds`() {+ // The one thing the LRC format leaves to be inferred from a field's width, and the one place a+ // mistake would be a uniform 900 ms of drift that reads as a bad file rather than a bug.+ val lines = parseLyrics("[00:01.05]a\n[00:01.050]b")+ assertEquals(listOf(1_050L, 1_050L), lines.map { it.timestamp })+ }++ @Test+ fun `lyrics with no timestamps classify as plain`() {+ // Previously the empty list from these was indistinguishable from a file with no lyrics at all,+ // so the phone said "no lyrics available" about a track that plainly had them.+ val lyrics = assertIs<Lyrics.Plain>(classifyLyrics("how does it feel\n\nto treat me like you do"))+ assertEquals("how does it feel\nto treat me like you do", lyrics.text)+ }++ @Test+ fun `metadata tags alone are not lyrics`() {+ assertIs<Lyrics.None>(classifyLyrics("[ti:Blue Monday]\n[length:07:29]"))+ }++ @Test+ fun `nothing, blank and whitespace all classify as none`() {+ assertIs<Lyrics.None>(classifyLyrics(null))+ assertIs<Lyrics.None>(classifyLyrics(""))+ assertIs<Lyrics.None>(classifyLyrics(" \n\n "))+ }++ @Test+ fun `a file with one timestamp among loose text is timed rather than plain`() {+ // A synced file with untimed headers in it, which is common - and the reason the classification+ // prefers timed whenever a single timestamp was found.+ val lyrics = assertIs<Lyrics.Timed>(classifyLyrics("written by somebody\n[00:03.00]the only timed line"))+ assertEquals(1, lyrics.lines.size)+ }++ @Test+ fun `the current index is exclusive before the first line and inclusive on a boundary`() {+ val lines = listOf(+ LyricLine(1_000, "one"),+ LyricLine(2_000, "two"),+ LyricLine(3_000, "three"),+ )+ // Before the first: -1 rather than
Diff truncated.