cast: stream the Opus transcode so the TV plays immediately
- Commit
ca253b8937434cd21e73303ca75cb0a20ab76b63- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-23 22:04 UTC (3 months ago)
- Parents
43af18c
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 05e62044e2..a0b93e52df 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@@ -25,6 +25,8 @@ import kotlinx.serialization.json.Json * and the TV decodes them, so no video is encoded, seeking is a byte offset and audio-only becomes * expressible at all. Screen mirroring keeps the RTP path unchanged, because it has no file to serve. * [StreamConfig.videoCodec] became optional in the same bump, and [DecoderLimits] grew an audio half.+ * [Ping] arrived in the same version, once a served session turned out to be able to go quiet for+ * longer than either end's read timeout allows. */ const val PROTOCOL_VERSION = 5 @@ -60,6 +62,8 @@ const val MACAST_SERVICE_TYPE = "_macast._tcp" * ◄───────────── CONTENT_READY (accepted, or refused with a reason) * PLAY_MEDIA ──────────────────────────► (which resource, and what is in it) * … the TV fetches byte ranges over HTTPS and decodes them itself …+ * PING ────────────────────────────────► (every 20 s, so neither read deadline expires)+ * ◄───────────── PING (echoed straight back) * BYE ─────────────────────────────────► * ``` *@@ -547,6 +551,37 @@ enum class PlaybackAction { SetVolume, } +/**+ * Nothing to say, said out loud.+ *+ * **A read timeout is the only liveness check either end has, and it cannot tell a quiet session+ * from a dead one.** Both ends give a read 60 seconds, which was sized for the longest legitimate+ * wait in a handshake - a human reading six digits off a screen. A live content session has no such+ * guarantee: the phone may have nothing whatever to say for minutes, because the TV is fetching the+ * media over HTTPS on its own and owns its own clock. So a perfectly healthy session used to be+ * torn down a minute in, by whichever end read first.+ *+ * Sent by the phone every [PING_INTERVAL_MS] while a content session is live, and **echoed straight+ * back by the receiver**. The echo is not politeness: `SO_TIMEOUT` is a *read* timeout, so the+ * phone's own outbound ping does nothing for the phone's deadline, and without the reply the phone+ * would drop the session at 60 seconds exactly as the TV used to.+ *+ * Carries no payload. Anything worth knowing is already in [PlaybackState], and a keep-alive that+ * grew fields would become a second, competing source of truth about the same session.+ */+@Serializable+@SerialName("PING")+data object Ping : ControlMessage++/**+ * How often a ping goes out, at a third of the 60 s read timeout.+ *+ * A third rather than a half so that two consecutive pings can be lost - to a stall, a scheduler+ * that did not run the coroutine, a moment of packet loss - before either end concludes the other+ * has gone.+ */+const val PING_INTERVAL_MS = 20_000L+ /** * Either end, at any point after the secret is established. *
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/MediaProxy.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/MediaProxy.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/MediaProxy.ktindex fdad5f0ec3..b8e5a78fef 100644--- a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/MediaProxy.kt+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/MediaProxy.kt@@ -1,5 +1,6 @@ package com.vayunmathur.cast.protocol +import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.security.MessageDigest@@ -49,23 +50,46 @@ object MediaProxy { expected.toByteArray(Charsets.US_ASCII), offered.toByteArray(Charsets.US_ASCII), )++ /**+ * A [MediaResource.length] below zero: still being written, final size unknown.+ *+ * A descriptor to a growing file reports EOF at the current end of file, and there is no way+ * to tell "not yet" from "done" by reading it - so the length is what the producer says, and+ * this is how it says it does not know yet.+ */+ const val UNKNOWN_LENGTH = -1L } -/** A resource the proxy can serve: a known length and a stream that can start part-way in. */+/** A resource the proxy can serve: a length that may not be known yet, and a stream that can start part-way in. */ interface MediaResource { /**- * Total length in bytes.+ * Total length in bytes, or negative for [MediaProxy.UNKNOWN_LENGTH]. * * Known up front even when the bytes are not all present yet - a SABR segment still on its * way down has a length from its index. That is why [open] is allowed to end early and why * the caller has to notice when it does.+ *+ * Negative is the stronger case: the producer does not know the final size either, because it+ * is still encoding. The proxy then states no `Content-Length`, honours no `Range`, and+ * expects [open]'s stream to wait at the current end of file rather than report it. */ val length: Long + /** Whether [length] can be stated to a client, and therefore whether a `Range` can be answered. */+ val hasKnownLength: Boolean get() = length >= 0+ val contentType: String - /** A stream positioned at [offset]. The caller closes it. */+ /**+ * A stream positioned at [offset]. The caller closes it.+ *+ * For an unknown length the stream must block at the current end of file until either more+ * bytes arrive or the producer is finished, and signal a producer that stopped without+ * finishing by throwing [IOException] rather than by returning `-1`, which would be+ * indistinguishable from a clean end.+ */ fun open(offset: Long): InputStream } @@ -103,6 +127,10 @@ sealed interface ExchangeOutcome { * The response has already been committed with a `Content-Length` by then, so there is no * way to turn this into an error status; the connection must be closed so the client sees a * truncated body instead of waiting for bytes that are not coming.+ *+ * [expected] is [MediaProxy.UNKNOWN_LENGTH] when the resource never had a length to fall+ * short of and its producer stopped without finishing - a transcode that died part-way. The+ * answer is the same either way, because a closed connection is the only signal left. */ data class Truncated(val resourceId: String, val expected: Long, val actual: Long) : ExchangeOutcome @@ -166,6 +194,12 @@ class MediaProxyExchange( return Result(ExchangeOutcome.Rejected(404, "no resource '${path.resourceId}'"), reusable = true) } + // Before the `Range` is even parsed: with no total there is nothing to interpret one+ // against, and `parseRange` would call every range unsatisfiable and answer `416`.+ if (!resource.hasKnownLength) {+ return serveUnknownLength(path.resourceId, resource, method, output)+ }+ val range = parseRange(headers["range"], resource.length) if (range is RangeSpec.Unsatisfiable) { respondError(@@ -213,6 +247,52 @@ class MediaProxyExchange( data class Result(val outcome: ExchangeOutcome, val reusable: Boolean) + /**+ * Answers a resource whose final size nobody knows yet.+ *+ * `200`, no `Content-Length`, and the body delimited by closing the connection - which+ * HTTP/1.1 permits and `HttpURLConnection` reads as an unset length. `Accept-Ranges` is+ * omitted rather than advertised, because there is no total to answer a `Range` against.+ *+ * **A `Range` on such a resource is ignored and the whole thing is served**, which is the+ * answer the multi-range branch already establishes for a range this proxy declines. The+ * consequence is worth stating plainly: the first play of a resource still being written+ * cannot be seeked. The alternative is predicting the final size of a VBR stream before+ * encoding it, which cannot be done exactly, and being wrong shows up as a seek bar that+ * lies or a body cut short.+ */+ private fun serveUnknownLength(+ resourceId: String,+ resource: MediaResource,+ method: String,+ output: OutputStream,+ ): Result {+ val head = StringBuilder()+ head.append("HTTP/1.1 200 OK\r\n")+ head.append("Content-Type: ").append(resource.contentType).append("\r\n")+ head.append("Connection: close\r\n")+ head.append("\r\n")+ output.write(head.toString().toByteArray(Charsets.ISO_8859_1))++ if (method == "HEAD") {+ output.flush()+ // Not reusable even though no body was sent: the client has been told this connection+ // closes, and answering a second request down it would contradict that.+ return Result(ExchangeOutcome.Served(resourceId, RangeSpec.Whole, 0), reusable = false)+ }++ val transfer = resource.open(0).use { body -> copyUntilEnd(body, output) }+ output.flush()+ return if (transfer.complete) {+ Result(ExchangeOutcome.Served(resourceId, RangeSpec.Whole, transfer.written), reusable = false)+ } else {+ Result(+ ExchangeOutcome.Truncated(resourceId, MediaProxy.UNKNOWN_LENGTH, transfer.written),+ reusable = false,+ )+ }+ }+ // ------------------------------------------------------------------ // Request reading // ------------------------------------------------------------------@@ -264,6 +344,32 @@ class MediaProxyExchange( return limit - remaining } + /**+ * Copies until the resource ends, with no length to stop at.+ *+ * The distinction the return value carries is the whole point. A stream over a resource still+ * being written waits at the current end of file, so `-1` means the producer genuinely+ * finished; a producer that died is expected to throw instead, because a `-1` for that case+ * would be indistinguishable from success and would serve a silently half-length track.+ */+ private fun copyUntilEnd(from: InputStream, to: OutputStream): Transfer {+ val buffer = ByteArray(COPY_BUFFER_BYTES)+ var written = 0L+ while (true) {+ val read = try {+ from.read(buffer, 0, buffer.size)+ } catch (_: IOException) {+ return Transfer(written, complete = false)+ }+ if (read == -1) return Transfer(written, complete = true)+ to.write(buffer, 0, read)+ written += read+ }+ }++ /** How much of an unknown-length body was sent, and whether it was all of it. */+ private class Transfer(val written: Long, val complete: Boolean)+ private fun respondError(output: OutputStream, status: Int, extraHeaders: List<String> = emptyList()) { val head = StringBuilder() head.append("HTTP/1.1 ").append(status).append(' ').append(reasonPhrase(status)).append("\r\n")
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/ContentSessionTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/ContentSessionTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/ContentSessionTest.ktindex 5fc2f76870..a6254d213c 100644--- a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/ContentSessionTest.kt+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/ContentSessionTest.kt@@ -99,6 +99,25 @@ class ContentSessionTest { ControlJson.encodeToString(PlayMedia("a", "audio/ogg") as ControlMessage) .contains("\"PLAY_MEDIA\""), )+ assertTrue(ControlJson.encodeToString(Ping as ControlMessage).contains("\"PING\""))+ }++ @Test+ fun `a ping survives the trip and carries nothing`() {+ // The keep-alive has to decode on both ends or it is worse than useless: an unknown `type`+ // is treated exactly like a dead socket, so a ping a build did not recognise would end the+ // very session it was sent to preserve.+ assertIs<Ping>(roundTrip(Ping))+ }++ @Test+ fun `a ping goes out often enough to beat the read timeout`() {+ // 60 s is what both ends give a read. At a third of that, two consecutive pings can be lost+ // before either end concludes the other has gone.+ assertTrue(+ PING_INTERVAL_MS * 2 < 60_000L,+ "a single lost ping should not be able to end a healthy session",+ ) } private fun roundTrip(message: ControlMessage): ControlMessage =
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 3a8dda8b9a..2dedd5f132 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@@ -2,6 +2,7 @@ package com.vayunmathur.cast.protocol import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream+import java.io.IOException import java.io.InputStream import kotlin.test.Test import kotlin.test.assertContentEquals@@ -223,6 +224,90 @@ class MediaProxyTest { assertContentEquals(media.copyOfRange(4000, 4501), response.body) } + // ------------------------------------------------------------------+ // Resources still being written+ // ------------------------------------------------------------------++ @Test+ fun `serves an unknown length with no Content-Length and closes to end the body`() {+ // A live transcode has no total to state, so the body is delimited by the connection+ // closing - which is what HttpURLConnection reads as an unset length.+ val response = growing().get("/$token/track")+ assertEquals(200, response.status)+ assertNull(+ response.headers["content-length"],+ "stating a length for a file still being written would cut the track off",+ )+ assertEquals("close", response.headers["connection"])+ assertNull(+ response.headers["accept-ranges"],+ "advertising ranges with no total to answer them against would invite a 416",+ )+ assertContentEquals(media, response.body)+ }++ @Test+ fun `ignores a Range on an unknown length rather than refusing it`() {+ // 416 here would end playback outright. Serving the whole thing is a permitted answer, and+ // the same one the multi-range branch already gives.+ val response = growing().get("/$token/track", "Range: bytes=100-199")+ assertEquals(200, response.status)+ assertNull(response.headers["content-range"])+ assertContentEquals(media, response.body)+ }++ @Test+ fun `never reuses a connection it said would close`() {+ val result = growing().serve("GET /$token/track HTTP/1.1\r\n\r\n")+ assertTrue(!result.first.reusable, "the body's only delimiter is the close")+ }++ @Test+ fun `answers a HEAD on an unknown length with no length either`() {+ val response = growing().request("HEAD /$token/track HTTP/1.1\r\n\r\n")+ assertEquals(200, response.status)+ assertNull(response.headers["content-length"])+ assertEquals(0, response.body.size)+ }++ @Test+ fun `reports a producer that stopped without finishing as truncated`() {+ // The failure this has to be distinguishable from is success. A reader that gave up gets an+ // IOException, and reporting it as Served would mean a half-length track logged as fine.+ val died = GrowingResource(media, availableBytes = 2_000, everFinishes = false)+ val result = MediaProxyExchange(token) { died }.serve("GET /$token/track HTTP/1.1\r\n\r\n")++ val outcome = assertIs<ExchangeOutcome.Truncated>(result.first.outcome)+ assertEquals(MediaProxy.UNKNOWN_LENGTH, outcome.expected, "there was never a length to fall short of")+ assertEquals(2_000, outcome.actual)+ assertTrue(!result.first.reusable)+ }++ @Test+ fun `serves the bytes that arrive after a reader has caught up`() {+ // The encoder runs ahead of the player, but not by a fixed margin: a reader that reaches the+ // current end of file has to wait and then carry on, not report the end of the track.+ val late = GrowingResource(media, availableBytes = 1_000, growsBy = 1_500)+ val response = MediaProxyExchange(token) { late }.get("/$token/track")+ assertEquals(200, response.status)+ assertContentEquals(media, response.body, "the reader stopped at the first end of file")+ }++ @Test+ fun `answers the same resource with a real length once it is finished`() {+ // What makes a re-cast seekable: the resource reports a length as soon as the transcode has+ // finished, and from then on it is an ordinary range serve.+ val resource = GrowingResource(media, availableBytes = media.size)+ val exchange = MediaProxyExchange(token) { resource }+ assertNull(exchange.get("/$token/track").headers["content-length"])++ resource.finish()+ val response = exchange.get("/$token/track", "Range: bytes=100-199")+ assertEquals(206, response.status)+ assertEquals("bytes 100-199/5000", response.headers["content-range"])+ assertContentEquals(media.copyOfRange(100, 200), response.body)+ }+ // ------------------------------------------------------------------ // Connection reuse // ------------------------------------------------------------------@@ -285,6 +370,69 @@ class MediaProxyTest { private class Response(val status: Int, val headers: Map<String, String>, val body: ByteArray) + private fun growing() = MediaProxyExchange(token) { GrowingResource(media) }++ /**+ * A resource still being written, standing in for a live transcode.+ *+ * Models the two things the real one does that a plain `ByteArrayInputStream` cannot: a read+ * that reaches the current end of file waits rather than reporting it, and a producer that dies+ * throws rather than returning `-1` - which is the only way the proxy can tell a short body from+ * a complete one when there was never a length.+ */+ private class GrowingResource(+ private val bytes: ByteArray,+ override val contentType: String = "audio/ogg",+ /** How much has been written when the request arrives. */+ private val availableBytes: Int = 0,+ /** How much more appears the first time a reader catches up. */+ private val growsBy: Int = 0,+ /** False for a producer that stops without ever completing. */+ private val everFinishes: Boolean = true,+ ) : MediaResource {++ private var written = availableBytes+ private var complete = false++ override val length: Long+ get() = if (complete) bytes.size.toLong() else MediaProxy.UNKNOWN_LENGTH++ fun finish() {+ written = bytes.size+ complete = true+ }++ override fun open(offset: Long): InputStream = object : InputStream() {+ private var position = offset.toInt()++ override fun read(): Int {+ val one = ByteArray(1)+ return if (read(one, 0, 1) == 1) one[0].toInt() and 0xff else -1+ }++ override fun read(b: ByteArray, off: Int, len: Int): Int {+ while (position >= written) {+ // Caught up with the producer. Grow once, then finish - or never, for the+ // producer that died.+ when {+ growsBy > 0 && written < bytes.size ->+ written = (written + growsBy).coerceAtMost(bytes.size)+ !everFinishes -> throw IOException("the producer stopped")+ written < bytes.size -> written = bytes.size+ else -> {+ complete = true+ return -1+ }+ }+ }+ val count = minOf(len, written - position)+ bytes.copyInto(b, off, position, position + count)+ position += count+ return count+ }+ }+ }+ private fun MediaProxyExchange.get(target: String, vararg headers: String): Response = request("GET $target HTTP/1.1\r\n" + headers.joinToString("") { "$it\r\n" } + "\r\n")
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 395ea7cbe8..833a77ff89 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.PING_INTERVAL_MS import com.vayunmathur.cast.protocol.PROTOCOL_VERSION import com.vayunmathur.cast.protocol.PlayMedia import com.vayunmathur.cast.protocol.PlaybackCommand@@ -40,6 +41,7 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow@@ -130,6 +132,14 @@ object CastController { private var client: MirrorClient? = null private var watchJob: Job? = null + /**+ * The keep-alive on a served session's control channel.+ *+ * Its own job rather than part of [watchJob], because that one is parked in a blocking read for+ * the whole session and has nowhere to run a timer.+ */+ private var pingJob: Job? = null+ /** The running mirror. Its retransmit buffers live per-stream inside it. */ private var engine: MirrorEngine? = null @@ -578,7 +588,7 @@ object CastController { _sessionState.update { it.copy(phase = ClientPhase.Streaming, negotiation = ready.negotiation) }- startWatch(appContext, activeClient, device, codec.codec, transportControls = true)+ startWatch(appContext, activeClient, device, codec.codec, transportControls = true, keepAlive = true) ContentSessionResult.Started( surface = surface, audioWriteEnd = newEngine.audioWriteEnd,@@ -669,7 +679,7 @@ object CastController { _mirrorPhase.value = MirrorPhase.Mirroring _sessionState.update { it.copy(phase = ClientPhase.Streaming) }- startWatch(context, activeClient, device, codec = null, transportControls = true)+ startWatch(context, activeClient, device, codec = null, transportControls = true, keepAlive = true) return ContentSessionResult.Serving( receiverName = activeClient.receiverName ?: device.friendlyName, hasVideo = wantVideo,@@ -689,7 +699,15 @@ object CastController { /** Null for a served session, where nothing was encoded and there is no codec to demote. */ codec: VideoCodec?, transportControls: Boolean = false,+ /**+ * Whether to keep the control channel warm, which only a served session needs.+ *+ * Screen mirroring is left alone: its traffic is RTP, and adding a heartbeat to it would be+ * changing a path this work has no business touching.+ */+ keepAlive: Boolean = false, ) {+ if (keepAlive) startKeepAlive(activeClient) watchJob = scope.launch { // Read late rather than captured: `ContentCastService` registers its callback only after // `startContentSession` returns, which is after this job has already started - the same@@ -731,6 +749,28 @@ object CastController { } } + /**+ * Sends a keep-alive every [PING_INTERVAL_MS] for as long as a content session is live.+ *+ * A content session is the case where the control channel can go completely silent while+ * everything is working: the TV fetches the media over HTTPS and owns its own clock, so unless+ * the app volunteers playback snapshots there is nothing for the phone to say. Both ends give a+ * read 60 seconds, so silence used to end the session on whichever side read first - which is+ * what tore a session down a minute in while a track was still being encoded.+ *+ * Under [mutex] like every other writer, because this is one more thread writing one socket.+ */+ private fun startKeepAlive(activeClient: MirrorClient) {+ pingJob?.cancel()+ pingJob = scope.launch {+ while (isActive) {+ delay(PING_INTERVAL_MS)+ if (!isActive) return@launch+ mutex.withLock { activeClient.sendPing() }+ }+ }+ }+ fun stopMirroring(context: Context) { val appContext = context.applicationContext scope.launch {@@ -911,6 +951,11 @@ object CastController { // would serve a token that is no longer anybody's. proxy?.stop() proxy = null+ // Cancelled here rather than only in `teardown`: `stopMirroring` deliberately leaves the+ // control channel and `watchJob` alive, so a ping loop left running would keep pinging on+ // behalf of a session that has ended.+ pingJob?.cancel()+ pingJob = null } /**
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 2e39dcb4cd..8a2a685a4c 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt@@ -17,6 +17,7 @@ import com.vayunmathur.cast.protocol.PairFailed import com.vayunmathur.cast.protocol.PairOk import com.vayunmathur.cast.protocol.PairProof import com.vayunmathur.cast.protocol.PairRequired+import com.vayunmathur.cast.protocol.Ping import com.vayunmathur.cast.protocol.PlayMedia import com.vayunmathur.cast.protocol.PlaybackCommand import com.vayunmathur.cast.protocol.PlaybackState@@ -352,6 +353,19 @@ class MirrorClient( .onFailure { Log.w(TAG, "could not send the playback state", it) } } + /**+ * Put a keep-alive on the control channel, so the TV's read deadline does not expire.+ *+ * Non-throwing and unlogged for exactly [sendPlaybackState]'s reasons - it is a timer loop, and+ * a socket that has really died is [awaitEnd]'s to report. The reply is absorbed by+ * [awaitEnd]'s `else` branch, which is where it wants to be handled: the point of the echo is+ * that a read happened at all, not what was in it.+ */+ fun sendPing() {+ runCatching { socket.send(Ping) }+ .onFailure { Log.w(TAG, "could not send a keep-alive", it) }+ }+ /** * Wait for the TV to say goodbye, or for the socket to die, acting on anything else it sends. *@@ -389,6 +403,9 @@ class MirrorClient( onCommand(message) } }+ // The echo of our own keep-alive. Nothing to do with it: having read it is the+ // whole effect, because that is what pushed this socket's read deadline out.+ is Ping -> {} else -> {} } }
cast/src/main/java/com/vayunmathur/cast/service/ClientResourceResolver.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/service/ClientResourceResolver.kt b/cast/src/main/java/com/vayunmathur/cast/service/ClientResourceResolver.ktindex 3df4c921e8..537e30154e 100644--- a/cast/src/main/java/com/vayunmathur/cast/service/ClientResourceResolver.kt+++ b/cast/src/main/java/com/vayunmathur/cast/service/ClientResourceResolver.kt@@ -7,6 +7,7 @@ import android.util.Log import com.vayunmathur.cast.protocol.MediaResource import com.vayunmathur.cast.protocol.MediaResourceResolver import com.vayunmathur.sdk.cast.CastContract+import java.io.IOException import java.io.InputStream import java.nio.ByteBuffer import java.nio.channels.FileChannel@@ -27,6 +28,21 @@ private const val TAG = "ClientResources" */ private const val REQUEST_TIMEOUT_MS = 5_000L +/**+ * How long a read on a growing resource waits at end of file before giving up.+ *+ * The producer is a transcode running several times faster than real time, so a healthy one+ * never comes close to this: it exists for the one that died without saying so. Bounded because+ * the waiter is a thread serving an HTTP request, and waiting for ever there is how a dead+ * encoder turns into a television holding an open connection with nothing on screen. Reaching it+ * surfaces as a truncated body, which the player reports as a load failure - the honest outcome,+ * and a much better one than a spinner nothing ever resolves.+ */+private const val GROWING_READ_TIMEOUT_MS = 10_000L++/** How long to sleep between looks at a file that has not grown yet. */+private const val GROWING_POLL_MS = 25L+ /** * Gets the bytes for the media proxy from the app being cast. *@@ -110,6 +126,9 @@ class ClientResourceResolver( val resource = descriptor?.let { DescriptorResource( descriptor = it,+ // A negative length is the app saying it is still writing this and does not know+ // the final size, which is passed through rather than corrected: the proxy serves+ // it without a `Content-Length` and reads it as it grows. length = data.getLong(CastContract.KEY_RESOURCE_LENGTH), contentType = data.getString(CastContract.KEY_RESOURCE_TYPE) ?: "application/octet-stream",@@ -118,6 +137,32 @@ class ClientResourceResolver( if (!mailbox.offer(Answer(resource))) resource?.close() } + /**+ * Records that a resource offered with an unknown length has finished being written.+ *+ * This is what releases a reader parked at the end of a growing file: without it the only way+ * out is the wait bound, which would report a complete track as truncated. A message with no+ * length means the producer failed, and readers are released with an error instead - the+ * failure has to travel, because a transcode that died leaves a file that simply stops growing+ * and looks exactly like one that is briefly behind.+ */+ fun onComplete(data: Bundle?) {+ val resourceId = data?.getString(CastContract.KEY_RESOURCE_ID) ?: return+ val resource = cache[resourceId]+ if (resource == null) {+ Log.w(TAG, "'$resourceId' was completed but was never handed over")+ return+ }+ if (data.containsKey(CastContract.KEY_RESOURCE_LENGTH)) {+ val length = data.getLong(CastContract.KEY_RESOURCE_LENGTH)+ resource.complete(length)+ Log.i(TAG, "'$resourceId' finished at $length bytes")+ } else {+ resource.fail()+ Log.w(TAG, "the app could not finish producing '$resourceId'")+ }+ }+ /** Closes every descriptor the app handed over. Called when the session ends. */ fun close() { cache.values.forEach { it.close() }@@ -132,17 +177,54 @@ class ClientResourceResolver( * its file offset with the app's original, so moving the offset would move the app's too, and * two ranges being served at once would each read from where the other left off. * [FileChannel.read] with an explicit position touches neither.+ *+ * A resource may also still be being written, in which case its length is negative until the+ * app says otherwise. The end of such a file is not the end of the resource, so reads on it+ * wait rather than report one - see [GrowingStream]. */ private class DescriptorResource( descriptor: ParcelFileDescriptor,- override val length: Long,+ length: Long, override val contentType: String, ) : MediaResource { private val stream = ParcelFileDescriptor.AutoCloseInputStream(descriptor) private val channel: FileChannel = stream.channel - override fun open(offset: Long): InputStream = PositionalStream(channel, offset)+ /**+ * Volatile, and no longer fixed at construction: the app can finish writing a resource+ * mid-session. Written from the service's main looper and read by every HTTP thread+ * serving it, which is exactly the case a non-volatile field gets wrong.+ */+ @Volatile+ override var length: Long = length+ private set++ /** Set when the app said it could not finish, so waiting readers fail instead of hanging. */+ @Volatile+ var hasFailed: Boolean = false+ private set++ /**+ * A growing resource gets a stream that waits; a finished one gets a plain positional read.+ *+ * Decided per [open] rather than once, so a request arriving after the transcode finished+ * takes the ordinary path - and gets a `Content-Length` and working seeks with it.+ */+ override fun open(offset: Long): InputStream =+ if (hasKnownLength) {+ PositionalStream(channel, offset)+ } else {+ GrowingStream(this, channel, offset)+ }++ fun complete(finalLength: Long) {+ length = finalLength+ }++ fun fail() {+ hasFailed = true+ } fun close() { // Closes the descriptor with it, which is the point of AutoCloseInputStream.@@ -173,4 +255,67 @@ class ClientResourceResolver( */ override fun close() = Unit }++ /**+ * Reads a file that is still being written, waiting at the end instead of reporting it.+ *+ * The problem this solves has no solution at the file layer: a descriptor to a growing file+ * reports EOF at whatever the current end of file is, and nothing distinguishes "the producer+ * has not got here yet" from "there is no more". So the answer comes from the producer instead,+ * and until it arrives a read that catches up simply waits.+ *+ * Three ways out, and each has to be its own: more bytes appear and are returned; the app says+ * it finished, and the real end of file becomes the end of the stream; or the app says it+ * failed, or says nothing at all for [GROWING_READ_TIMEOUT_MS], and the read throws - which the+ * proxy turns into a closed connection and a short body rather than a stall.+ */+ private class GrowingStream(+ private val resource: DescriptorResource,+ private val channel: FileChannel,+ private var position: Long,+ ) : InputStream() {++ override fun read(): Int {+ val one = ByteArray(1)+ return if (read(one, 0, 1) == 1) one[0].toInt() and 0xff else -1+ }++ override fun read(b: ByteArray, off: Int, len: Int): Int {+ if (len == 0) return 0+ val deadline = System.currentTimeMillis() + GROWING_READ_TIMEOUT_MS+ while (true) {+ val read = channel.read(ByteBuffer.wrap(b, off, len), position)+ if (read > 0) {+ position += read+ return read+ }++ // At the current end of file, so the producer's own state decides what that means.+ if (resource.hasFailed) throw IOException("the app failed to produce this resource")+ if (resource.hasKnownLength) {+ // Read once more before believing it: the last bytes and the completion travel+ // by different routes, so they can land in either order, and trusting the flag+ // alone would drop whatever arrived in between.+ val last = channel.read(ByteBuffer.wrap(b, off, len), position)+ if (last > 0) {+ position += last+ return last+ }+ return -1+ }+ if (System.currentTimeMillis() >= deadline) {+ throw IOException("no new bytes for ${GROWING_READ_TIMEOUT_MS}ms at $position")+ }+ try {+ Thread.sleep(GROWING_POLL_MS)+ } catch (e: InterruptedException) {+ Thread.currentThread().interrupt()+ throw IOException("interrupted waiting for more of this resource", e)+ }+ }+ }++ /** The channel is the resource's, exactly as in [PositionalStream]. */+ override fun close() = Unit+ } }
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 635753f6db..9ea1b8c1ff 100644--- a/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt+++ b/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt@@ -87,6 +87,13 @@ class ContentCastService : Service() { resources.onResponse(msg.data) true }+ CastContract.MSG_RESOURCE_COMPLETE -> {+ // Not gated on `sessionOpen`, unlike the two below: this releases a reader that+ // may be parked on a growing file, and dropping it during teardown would leave+ // that reader to wait out its own bound for no reason.+ resources.onComplete(msg.data)+ true+ } CastContract.MSG_PLAY_MEDIA -> { // Dropped with no session, for the same reason a state snapshot is: there is no // TV to play it on, and a client may send one a tick after the session ended.
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 326d872a0b..0f754ea3f1 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@@ -20,6 +20,7 @@ import com.vayunmathur.cast.protocol.PairProof import com.vayunmathur.cast.protocol.PairRequired import com.vayunmathur.cast.protocol.PairResult import com.vayunmathur.cast.protocol.PairingGate+import com.vayunmathur.cast.protocol.Ping import com.vayunmathur.cast.protocol.PlayMedia import com.vayunmathur.cast.protocol.PlaybackAction import com.vayunmathur.cast.protocol.PlaybackCommand@@ -445,6 +446,9 @@ object ReceiverController { } is VideoCodecConfig -> onVideoCodecConfig(message, config) is PlaybackState -> onPlaybackState(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) } else -> Unit } }@@ -517,6 +521,10 @@ object ReceiverController { } is PlayMedia -> withContext(Dispatchers.Main) { player.play(message) } is PlaybackState -> onPlaybackState(message)+ // Echoed straight back, which is the whole of the keep-alive. Reading it has+ // already pushed this end's deadline out; replying is what pushes the phone's,+ // since a read timeout is not reset by anything that end sends.+ is Ping -> runCatching { channel.send(Ping) } else -> Unit } }
library/media/src/main/java/com/vayunmathur/library/media/OggStreamWriter.kt
diff --git a/library/media/src/main/java/com/vayunmathur/library/media/OggStreamWriter.kt b/library/media/src/main/java/com/vayunmathur/library/media/OggStreamWriter.ktindex dcba845755..a37c10b3c7 100644--- a/library/media/src/main/java/com/vayunmathur/library/media/OggStreamWriter.kt+++ b/library/media/src/main/java/com/vayunmathur/library/media/OggStreamWriter.kt@@ -1,6 +1,7 @@ package com.vayunmathur.library.media import java.io.ByteArrayOutputStream+import java.io.OutputStream /** * Ogg page construction: lacing tables, the Ogg CRC-32, and splitting a packet across pages.@@ -162,10 +163,23 @@ internal object OggPages { * Header packets each get their own page, as the Opus mapping requires. Audio packets are * grouped so a page holds up to about a second of audio, which is the usual trade between * page overhead and how much a reader loses to a corrupt page.+ *+ * **Pages go straight to [sink] as they are completed, and no byte is ever revisited.** Each+ * page is built whole - lacing table, granule position, CRC - and only then written, and+ * nothing discovered later reaches back into one already gone: [finish]'s final granule+ * position lands on the *pending* page, and the header packets are fixed in size when written.+ * So the same code serves a file being accumulated in memory and a stream being read while it+ * is still being encoded, which is what lets a transcode start playing before it has finished. */-internal class OggStreamWriter(private val serialNumber: Int) {+internal class OggStreamWriter(+ private val serialNumber: Int,+ /**+ * Where the pages go. Pass a `ByteArrayOutputStream` to accumulate the whole stream, or a+ * file for a reader to follow along behind.+ */+ private val sink: OutputStream,+) { - private val out = ByteArrayOutputStream(INITIAL_CAPACITY) private var sequence = 0 private var headerWritten = false @@ -182,7 +196,7 @@ internal class OggStreamWriter(private val serialNumber: Int) { granulePosition = 0L, firstHeaderType = if (headerWritten) 0 else OggPages.FLAG_BEGIN_OF_STREAM, )- pages.forEach { out.write(it) }+ pages.forEach { writePage(it) } sequence += pages.size headerWritten = true }@@ -206,15 +220,16 @@ internal class OggStreamWriter(private val serialNumber: Int) { } /**- * Closes the stream and returns the bytes.+ * Writes the last page, flagged end of stream. * * [finalGranulePosition] overrides the last page's granule position so it reports the * stream's true length: the encoder pads its final packet out to a whole frame, and a- * decoder trims that padding by comparing what it decoded against this number.+ * decoder trims that padding by comparing what it decoded against this number. It only+ * ever affects the page still pending, which is why nothing already written has to be+ * revisited and why the stream can be read as it is produced. */- fun finish(finalGranulePosition: Long): ByteArray {+ fun finish(finalGranulePosition: Long) { flushPage(endOfStream = true, granulePosition = finalGranulePosition)- return out.toByteArray() } private fun flushPage(endOfStream: Boolean, granulePosition: Long) {@@ -231,7 +246,7 @@ internal class OggStreamWriter(private val serialNumber: Int) { packet.copyInto(payload, at) at += packet.size }- out.write(+ writePage( OggPages.build( headerType = if (endOfStream) OggPages.FLAG_END_OF_STREAM else 0, granulePosition = granulePosition,@@ -248,9 +263,20 @@ internal class OggStreamWriter(private val serialNumber: Int) { pendingSegments = 0 } - private companion object {- const val INITIAL_CAPACITY = 1 * 1024 * 1024+ /**+ * Flushed per page rather than left to the sink's own buffering.+ *+ * A reader following a live transcode can only see bytes that have actually been written,+ * so a page held back in a buffer is a page the player does not have - and with a page+ * carrying about a second of audio, buffering a few of them is the difference between+ * playback starting and the TV waiting.+ */+ private fun writePage(page: ByteArray) {+ sink.write(page)+ sink.flush()+ } + private companion object { /** Fifty 20 ms Opus packets, so a page carries about one second. */ const val MAX_PACKETS_PER_PAGE = 50 }
library/media/src/main/java/com/vayunmathur/library/media/OpusTranscoder.kt
diff --git a/library/media/src/main/java/com/vayunmathur/library/media/OpusTranscoder.kt b/library/media/src/main/java/com/vayunmathur/library/media/OpusTranscoder.ktindex 199c22fb2f..6437cc1535 100644--- a/library/media/src/main/java/com/vayunmathur/library/media/OpusTranscoder.kt+++ b/library/media/src/main/java/com/vayunmathur/library/media/OpusTranscoder.kt@@ -6,6 +6,8 @@ import android.media.MediaCodecInfo import android.media.MediaExtractor import android.media.MediaFormat import android.util.Log+import java.io.ByteArrayOutputStream+import java.io.OutputStream import java.nio.ByteBuffer import kotlin.random.Random @@ -47,19 +49,49 @@ object OpusTranscoder { * platform codecs refuse it. A null fails the download: writing one of the formats the * user asked to be rid of would be worse than reporting the failure. *+ * Accumulates the whole stream in memory, which is what a caller wanting a `ByteArray`+ * asked for. [transcodeTo] is the same work without that: prefer it for anything with a+ * file or a socket on the other end.+ */+ fun transcode(+ source: ByteArray,+ isStopped: () -> Boolean = { false },+ onProgress: (Float) -> Unit = {},+ ): ByteArray? {+ val buffer = ByteArrayOutputStream(INITIAL_CAPACITY)+ transcodeTo(source, buffer, isStopped, onProgress) ?: return null+ return buffer.toByteArray().takeIf { it.isNotEmpty() }+ }++ /**+ * Encodes [source] into [sink] as it goes, returning the bytes written or null on failure.+ *+ * **The stream is servable before it is finished**, which is the point: pages reach [sink]+ * about a second of audio at a time, so a reader following behind can start playing while+ * the rest is still being encoded. Encoding runs several times faster than real time, so a+ * player that starts at the first page stays behind the encoder rather than catching it.+ *+ * A null means the bytes already in [sink] are a partial stream with no end-of-stream page,+ * and the caller has to say so to whatever is reading: unlike [transcode], a failure here+ * cannot be undone by discarding a buffer, because the bytes have already left.+ * * [onProgress] is called with the fraction of the track encoded so far. Re-encoding a * track takes seconds rather than milliseconds, so a caller with a progress indicator * has to be able to move it; without that a slow transcode is indistinguishable from a * hang, which is what the user sees as a spinner that never finishes.+ *+ * [sink] is not closed - it belongs to the caller, who may well want its length afterwards. */- fun transcode(+ fun transcodeTo( source: ByteArray,+ sink: OutputStream, isStopped: () -> Boolean = { false }, onProgress: (Float) -> Unit = {},- ): ByteArray? {+ ): Long? { var extractor: MediaExtractor? = null var decoder: MediaCodec? = null var pump: OpusPump? = null+ val counted = CountingSink(sink) try { extractor = MediaExtractor().apply { setDataSource(ByteArrayMediaDataSource(source)) } val track = audioTrack(extractor) ?: return null@@ -74,17 +106,25 @@ object OpusTranscoder { decoder.configure(format, null, null, 0) decoder.start() - pump = OpusPump(extractor, decoder, isStopped, ::createEncoder, durationUs(format), onProgress)- val output = pump.run()+ pump = OpusPump(+ extractor,+ decoder,+ isStopped,+ ::createEncoder,+ durationUs(format),+ onProgress,+ counted,+ )+ val completed = pump.run() // A cancel and a codec failure both used to log the same `out=0`, which is // indistinguishable in a bug report and reads as a broken encoder either way. val outcome = when {- output != null -> "out=${output.size}"+ completed -> "out=${counted.count}" isStopped() -> "cancelled" else -> "failed" } Log.i(TAG, "transcode $mime: in=${source.size} $outcome")- return output?.takeIf { it.isNotEmpty() }+ return if (completed) counted.count else null } catch (e: Exception) { Log.w(TAG, "transcode threw: ${e.javaClass.simpleName}: ${e.message}", e) return null@@ -130,6 +170,37 @@ object OpusTranscoder { start() } }++ /** A megabyte, which covers a few minutes of 256 kbps Opus without regrowing. */+ private const val INITIAL_CAPACITY = 1 * 1024 * 1024+}++/**+ * Counts what passes through, so a transcode can report its own size.+ *+ * The streaming path has no buffer to measure at the end, and the size is what a caller has to+ * hand on: a reader waiting on a growing resource is told the final length, and a log line+ * saying only "finished" is what makes a truncated encode look like a successful one.+ */+private class CountingSink(private val sink: OutputStream) : OutputStream() {++ var count = 0L+ private set++ override fun write(b: Int) {+ sink.write(b)+ count+++ }++ override fun write(b: ByteArray, off: Int, len: Int) {+ sink.write(b, off, len)+ count += len+ }++ override fun flush() = sink.flush()++ /** Deliberately not closing [sink]: it is the caller's, and they may still want its length. */+ override fun close() = Unit } /**@@ -154,6 +225,7 @@ private class OpusPump( private val createEncoder: (Int) -> MediaCodec, private val durationUs: Long, private val onProgress: (Float) -> Unit,+ sink: OutputStream, ) { /** Exposed only so the caller can release it; created once the decoder's format is known. */ var encoder: MediaCodec? = null@@ -164,7 +236,7 @@ private class OpusPump( private val decoderInfo = MediaCodec.BufferInfo() private val encoderInfo = MediaCodec.BufferInfo() private val queue = PcmQueue()- private val writer = OggStreamWriter(Random.nextInt())+ private val writer = OggStreamWriter(Random.nextInt(), sink) private var resampler: PolyphaseResampler? = null @@ -193,11 +265,12 @@ private class OpusPump( private var lastProgressAt = 0L - fun run(): ByteArray? {+ /** Whether a complete stream, end-of-stream page and all, reached the sink. */+ fun run(): Boolean { while (!encoderDone) { // A hi-res transcode runs for many seconds, so a cancelled download has to be // able to stop part-way rather than only between tracks.- if (isStopped()) return null+ if (isStopped()) return false var moved = false while (!extractorDone && feedDecoder(POLL_US)) moved = true@@ -207,7 +280,7 @@ private class OpusPump( if (active == null) { // The decoder finished without ever producing PCM, so there is nothing to // encode and no format to configure an encoder from.- if (decoderDone) return null+ if (decoderDone) return false if (!moved) drainDecoder(TIMEOUT_US) continue }@@ -229,8 +302,9 @@ private class OpusPump( } // An encoder that reported end of stream without ever emitting a packet leaves a // container with no audio in it, which is a failure however valid the framing is.- if (encoded == 0L) return null- return writer.finish(preSkip + frames)+ if (encoded == 0L) return false+ writer.finish(preSkip + frames)+ return true } /**
library/media/src/test/java/com/vayunmathur/library/media/OggStreamWriterTest.kt
diff --git a/library/media/src/test/java/com/vayunmathur/library/media/OggStreamWriterTest.kt b/library/media/src/test/java/com/vayunmathur/library/media/OggStreamWriterTest.ktindex 5f2e81c237..3589747819 100644--- a/library/media/src/test/java/com/vayunmathur/library/media/OggStreamWriterTest.kt+++ b/library/media/src/test/java/com/vayunmathur/library/media/OggStreamWriterTest.kt@@ -1,6 +1,9 @@ package com.vayunmathur.library.media +import java.io.ByteArrayOutputStream+import java.io.OutputStream import kotlin.test.Test+import kotlin.test.assertContentEquals import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull@@ -102,7 +105,8 @@ class OggStreamWriterTest { * the pre-skip samples are the first ones it decodes and then discards. */ private fun stream(packets: Int, packetSize: Int = 640, channels: Int = 2): ByteArray {- val writer = OggStreamWriter(serial)+ val sink = ByteArrayOutputStream()+ val writer = OggStreamWriter(serial, sink) writer.writeHeaderPacket(OpusHead.build(channels, OpusHead.DEFAULT_PRE_SKIP, 48_000)) writer.writeHeaderPacket(OggOpusTagger.buildOpusTagsPacket(VorbisTags())) var samples = 0L@@ -110,7 +114,8 @@ class OggStreamWriterTest { samples += 960 writer.writeAudioPacket(opusPacket(packetSize), samples) }- return writer.finish(samples)+ writer.finish(samples)+ return sink.toByteArray() } // ------------------------------------------------------------------@@ -208,10 +213,12 @@ class OggStreamWriterTest { fun `pages a packet that will not fit in one page`() { // 255 segments hold 65025 bytes at most, so this has to be continued onto a second // page - the case embedded cover art hits in the comment header.- val writer = OggStreamWriter(serial)+ val sink = ByteArrayOutputStream()+ val writer = OggStreamWriter(serial, sink) val big = ByteArray(70_000) { (it % 251).toByte() } writer.writeHeaderPacket(big)- val pages = parse(writer.finish(0L))+ writer.finish(0L)+ val pages = parse(sink.toByteArray()) assertTrue(pages.size > 1, "an oversized packet must span pages") assertEquals(OggPages.FLAG_BEGIN_OF_STREAM, pages[0].headerType)@@ -229,12 +236,14 @@ class OggStreamWriterTest { // The encoder pads its last frame out to a whole 20 ms, so the last page reports the // real length instead of the padded one and a decoder drops the difference. Reporting // the padded length is how a track ends with a fraction of a second of silence.- val writer = OggStreamWriter(serial)+ val sink = ByteArrayOutputStream()+ val writer = OggStreamWriter(serial, sink) writer.writeHeaderPacket(OpusHead.build(2, OpusHead.DEFAULT_PRE_SKIP, 48_000)) writer.writeHeaderPacket(OggOpusTagger.buildOpusTagsPacket(VorbisTags())) repeat(3) { writer.writeAudioPacket(opusPacket(640), (it + 1) * 960L) } val trimmed = 2_400L- val pages = parse(writer.finish(trimmed))+ writer.finish(trimmed)+ val pages = parse(sink.toByteArray()) assertEquals(trimmed, pages.last().granulePosition) assertTrue(@@ -287,4 +296,79 @@ class OggStreamWriterTest { fun `refuses to retag something that is not an ogg stream`() { assertNull(OggOpusTagger.tag(ByteArray(100), VorbisTags(title = "x"))) }++ // ------------------------------------------------------------------+ // Streaming+ // ------------------------------------------------------------------++ @Test+ fun `writes pages to the sink before finish is ever called`() {+ // The property the whole streaming transcode rests on. If pages only landed at `finish`,+ // a reader following a live encode would have nothing to play until it had all of it,+ // which is the 69-second wait this replaced.+ val sink = ByteArrayOutputStream()+ val writer = OggStreamWriter(serial, sink)+ writer.writeHeaderPacket(OpusHead.build(2, OpusHead.DEFAULT_PRE_SKIP, 48_000))+ writer.writeHeaderPacket(OggOpusTagger.buildOpusTagsPacket(VorbisTags()))+ assertTrue(sink.size() > 0, "the header pages should be readable at once")++ val afterHeaders = sink.size()+ var samples = 0L+ // Two pages' worth, so a page boundary is certainly crossed.+ repeat(120) {+ samples += 960+ writer.writeAudioPacket(opusPacket(640), samples)+ }+ assertTrue(+ sink.size() > afterHeaders,+ "a full page of audio should have been flushed without waiting for finish",+ )++ // And what was already flushed has to be complete, valid pages rather than a part-written+ // one: a reader gets whatever is there, so a half page would be a corrupt stream.+ parse(sink.toByteArray()).forEachIndexed { index, page ->+ assertTrue(page.checksumValid, "page $index was flushed with a bad CRC")+ assertEquals(index, page.sequence, "page $index was flushed out of sequence")+ }+ }++ @Test+ fun `hands the sink one whole page at a time`() {+ // The equivalence that matters now that there is only one writer: a sink written to+ // incrementally must end up with exactly the bytes a buffer would have collected, and each+ // write must be a complete page. A page delivered in two writes would let a reader that is+ // keeping up read a half-written page and see a corrupt stream.+ val chunks = ArrayList<ByteArray>()+ val recording = object : OutputStream() {+ override fun write(b: Int) = chunks.add(byteArrayOf(b.toByte())).let { }+ override fun write(b: ByteArray, off: Int, len: Int) {+ chunks.add(b.copyOfRange(off, off + len))+ }+ }++ val buffered = ByteArrayOutputStream()+ for (sink in listOf<OutputStream>(recording, buffered)) {+ val writer = OggStreamWriter(serial, sink)+ writer.writeHeaderPacket(OpusHead.build(2, OpusHead.DEFAULT_PRE_SKIP, 48_000))+ writer.writeHeaderPacket(OggOpusTagger.buildOpusTagsPacket(VorbisTags()))+ var samples = 0L+ repeat(200) {+ samples += 960+ writer.writeAudioPacket(opusPacket(640), samples)+ }+ writer.finish(samples)+ }++ val rejoined = chunks.fold(ByteArray(0)) { acc, chunk -> acc + chunk }+ assertContentEquals(+ buffered.toByteArray(),+ rejoined,+ "a streamed sink must receive exactly what a buffered one collects",+ )+ assertEquals(+ parse(buffered.toByteArray()).size,+ chunks.size,+ "one write per page, so a reader never sees half of one",+ )+ } }
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 f6f00c7cd7..6677f9c7df 100644--- a/music/src/main/java/com/vayunmathur/music/platform/CastPlayback.kt+++ b/music/src/main/java/com/vayunmathur/music/platform/CastPlayback.kt@@ -10,13 +10,20 @@ import com.vayunmathur.music.data.Music import com.vayunmathur.sdk.cast.CastClient import com.vayunmathur.sdk.cast.CastException import com.vayunmathur.sdk.cast.CastResource+import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.NonCancellable+import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File+import java.io.FileOutputStream import java.util.concurrent.ConcurrentHashMap private const val TAG = "CastPlayback"@@ -29,10 +36,15 @@ private const val TAG = "CastPlayback" * an HTTPS proxy, asks this app for a descriptor per track, and the TV decodes the original bytes. * So the phone starts no encoder, and the one thing it does encode is Opus, once per file. *- * **Preparation happens before the TV is told to play, deliberately.** Cast's proxy holds an HTTP- * request open while it waits for a descriptor, so transcoding inside that wait would turn a slow- * conversion into a stalled fetch. Doing it first makes the delay this app's own, where it can be- * shown as one.+ * **The TV is told to play a track before it has finished being encoded, deliberately.** Waiting for+ * the whole transcode first left the television holding an idle control channel for over a minute,+ * and it tore the session down before a note played. Now the resource is offered with an unknown+ * length, `PLAY_MEDIA` goes out at once, and the encoder - which runs several times faster than real+ * time - stays comfortably ahead of the TV's reader.+ *+ * The price is one thing a user can notice: **a track being encoded for the first time cannot be+ * seeked**, because a stream with no known length has nothing to answer a byte range with. It is+ * cached as it goes, so every later play of it is instant and seekable both. */ object CastPlayback { @@ -46,10 +58,11 @@ object CastPlayback { data class Casting( val receiverName: String, /**- * A track is being converted to Opus.+ * A track is still being encoded in the background. *- * Worth a state of its own because it is the only part of casting that takes visible- * time, and a first play with no explanation looks like a hang.+ * No longer "you are waiting": playback has already started, and this only says the+ * encoder is still working behind it. Worth showing anyway, because it is the window+ * in which seeking does not work and in which a failure can still appear. */ val preparing: Boolean = false, ) : State@@ -58,8 +71,29 @@ object CastPlayback { private val _state = MutableStateFlow<State>(State.Idle) val state: StateFlow<State> = _state.asStateFlow() + /**+ * Owns the background transcodes, and is why they are not launched in the caller's scope.+ *+ * The one caller is a composable's `rememberCoroutineScope`, which is cancelled the moment the+ * now-playing screen leaves composition - so a transcode launched there would be abandoned+ * mid-track by a user simply navigating away, leaving the TV reading a file nothing is writing.+ */+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private var client: CastClient? = null + /**+ * The running transcode and the resource it is producing, so a track change can cancel it.+ *+ * Volatile because they are written from the transcode's own completion on `Dispatchers.IO` and+ * read by [play] on the main thread.+ */+ @Volatile+ private var transcodeJob: Job? = null++ @Volatile+ private var transcodingId: String? = null+ /** * What the TV has been told about, by resource id. *@@ -81,6 +115,14 @@ object CastPlayback { /** Converted once and cached, keyed by track id. */ class Cached(val file: File) : Source++ /**+ * Being converted right now, into a file the TV is already reading.+ *+ * Served with an unknown length, which is what lets it be offered before it exists. Becomes+ * a [Cached] the moment the transcode finishes, so the next play of it is seekable.+ */+ class Growing(val file: File) : Source } fun support(context: Context): CastClient.Support = CastClient(context).support()@@ -121,30 +163,98 @@ object CastPlayback { } /**- * Put [song] on the TV, converting it first if it is not already Opus.+ * Put [song] on the TV, encoding it in the background if it is not already Opus. *- * Suspends for as long as the conversion takes, which is why the state carries a `preparing`- * flag: a four-minute track is a second or two the first time and nothing at all afterwards.+ * Returns as soon as the TV has been told to play, which for a track needing conversion is+ * before any of it has been encoded. [State.Casting.preparing] is what says the encoder is+ * still running behind the playback. */ suspend fun play(context: Context, song: Music) { val active = client ?: return val id = song.id.toString()+ // A transcode for a track the TV has moved on from is a minute of CPU nobody is waiting+ // for. Skipped when the id matches, so replaying the current track does not kill its own.+ cancelTranscodeExcept(id)+ val known = offered[id] if (known != null) { active.play(id, known.contentType, song.duration) return } - _state.update { if (it is State.Casting) it.copy(preparing = true) else it }- val prepared = withContext(Dispatchers.IO) { prepare(context, song) }- _state.update { if (it is State.Casting) it.copy(preparing = false) else it }+ val uri = song.uri.toUri()+ val ready = withContext(Dispatchers.IO) { alreadyPlayable(context, uri, song) }+ if (ready != null) {+ offered[id] = ready+ active.play(id, ready.contentType, song.duration)+ return+ } - if (prepared == null) {- Log.w(TAG, "'${song.title}' could not be prepared for casting")+ // Everything else is encoded as the TV plays it. The empty cache file has to exist and the+ // resource has to be registered *before* PLAY_MEDIA: the TV asks for bytes before any have+ // been written, and a resource this app has not offered - or a file that is not there yet -+ // is answered with a 404 rather than a wait.+ val cached = cacheFile(context, song.id)+ val source = withContext(Dispatchers.IO) { readSource(context, uri, cached) }+ if (source == null) {+ Log.w(TAG, "'${song.title}' could not be read for casting") return }- offered[id] = prepared- active.play(id, prepared.contentType, song.duration)+ offered[id] = Prepared(Source.Growing(cached), CONTENT_TYPE)+ active.play(id, CONTENT_TYPE, song.duration)+ startTranscode(active, song, id, cached, source)+ }++ /**+ * Encodes into the file the TV is already reading, and says so when it stops.+ *+ * The completion is not optional on either path. A reader that has caught up with the encoder is+ * parked waiting for more bytes, and the only things that release it are a real length or a+ * failure - so a transcode that ended without reporting either would hold an HTTP connection+ * open until the proxy's own bound expired.+ */+ private fun startTranscode(+ active: CastClient,+ song: Music,+ id: String,+ cached: File,+ source: ByteArray,+ ) {+ _state.update { if (it is State.Casting) it.copy(preparing = true) else it }+ transcodingId = id+ transcodeJob = scope.launch {+ val length = runCatching {+ FileOutputStream(cached).use { sink ->+ OpusTranscoder.transcodeTo(source, sink, isStopped = { !isActive })+ }+ }.getOrNull()++ // NonCancellable because this is what a cancelled transcode owes its reader: the+ // failure has to travel even though the work was abandoned on purpose.+ withContext(NonCancellable) {+ if (length != null) {+ // Now a real file with a real length, so the next play of it can be seeked.+ offered[id] = Prepared(Source.Cached(cached), CONTENT_TYPE)+ Log.i(TAG, "encoded '${song.title}' to $length bytes of Opus")+ } else {+ // A part-written file has no end-of-stream page, so it must not be mistaken for+ // a cached track on the next cast.+ offered.remove(id)+ runCatching { cached.delete() }+ Log.w(TAG, "could not encode '${song.title}' for casting")+ }+ active.resourceComplete(id, length ?: PRODUCER_FAILED)+ if (transcodingId == id) {+ transcodingId = null+ _state.update { if (it is State.Casting) it.copy(preparing = false) else it }+ }+ }+ }+ }++ private fun cancelTranscodeExcept(id: String) {+ if (transcodingId == null || transcodingId == id) return+ transcodeJob?.cancel() } fun close() {@@ -153,6 +263,11 @@ object CastPlayback { } private fun clear() {+ // Cancelled before the state is published: the transcode's own completion clears+ // `preparing`, and letting it run on would leave it writing into a session that has gone.+ transcodeJob?.cancel()+ transcodeJob = null+ transcodingId = null client = null offered.clear() _state.value = State.Idle@@ -163,14 +278,12 @@ object CastPlayback { // ------------------------------------------------------------------ /**- * Serve an Opus file as it is; convert anything else, once.+ * Whichever of the two no-work cases applies, or null when the track has to be encoded. *- * Converting to a file rather than streaming a live encode is the whole reason scrubbing works: a- * live transcode has no length and no seekable offsets, so `Range` - and therefore the seek bar -- * would have nothing to answer with.+ * An Opus file is served as it is, and a track converted on an earlier cast is served from the+ * cache - both with a real length, so both are seekable from the first moment. */- private fun prepare(context: Context, song: Music): Prepared? {- val uri = song.uri.toUri()+ private fun alreadyPlayable(context: Context, uri: Uri, song: Music): Prepared? { if (isOpus(context, uri)) { Log.i(TAG, "'${song.title}' is already Opus; serving it unchanged") return Prepared(Source.Original(uri), CONTENT_TYPE)@@ -181,26 +294,32 @@ object CastPlayback { Log.i(TAG, "'${song.title}' was converted on an earlier cast; reusing it") return Prepared(Source.Cached(cached), CONTENT_TYPE) }-- val source = runCatching {- context.contentResolver.openInputStream(uri)?.use { it.readBytes() }- }.getOrNull() ?: return null-- val encoded = OpusTranscoder.transcode(source, isStopped = { false }) {} ?: return null- return runCatching {- cached.parentFile?.mkdirs()- cached.writeBytes(encoded)- Log.i(TAG, "converted '${song.title}' to ${encoded.size} bytes of Opus")- Prepared(Source.Cached(cached), CONTENT_TYPE)- }.getOrNull()+ return null } + /**+ * Reads the track's bytes and creates the empty file its Opus will be written into.+ *+ * The file is created here rather than by the transcode, because it has to exist before the TV+ * is told to play: the first fetch arrives within moments, and opening a descriptor to a file+ * that is not there yet is a `404` the player treats as a failed load.+ */+ private fun readSource(context: Context, uri: Uri, cached: File): ByteArray? = runCatching {+ val source = context.contentResolver.openInputStream(uri)?.use { it.readBytes() }+ ?: return null+ cached.parentFile?.mkdirs()+ // Truncating, so a file left behind by a transcode that died is not read as a head start.+ FileOutputStream(cached).close()+ source+ }.getOrNull()+ /** * Answers Cast's request for a track's bytes. *- * Called on Cast's own background thread and expected to be quick, which it is: everything slow- * already happened in [prepare]. The descriptor must be seekable, because the TV asks for byte- * ranges - both branches here give a real file, and neither is a pipe.+ * Called on Cast's own background thread, and quick in every branch: even a track still being+ * encoded is answered immediately, with a descriptor to the file being written and a negative+ * length that tells Cast to wait at the end of it rather than report one. The descriptor is+ * always a real file, so a completed resource is seekable. */ private fun openResource(context: Context, resourceId: String): CastResource? { val prepared = offered[resourceId] ?: run {@@ -219,6 +338,13 @@ object CastPlayback { 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,+ // and stating it would cut the track off wherever the encoder happened to be.+ UNKNOWN_LENGTH,+ prepared.contentType,+ ) } }.onFailure { Log.w(TAG, "could not open '$resourceId'", it) }.getOrNull() }@@ -259,6 +385,16 @@ object CastPlayback { private const val CACHE_DIR = "cast-opus" + /**+ * 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+ * reporting it.+ */+ private const val UNKNOWN_LENGTH = -1L++ /** Sent as the completed length when the transcode failed, which releases readers with an error. */+ private const val PRODUCER_FAILED = -1L+ /** * `audio/ogg` rather than `audio/opus`: the container is Ogg, and that is what decides which * extractor the TV's player reaches for.
sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt
diff --git a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.ktindex 6b93ad5428..9ed7a2fc9f 100644--- a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt+++ b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt@@ -353,6 +353,33 @@ class CastClient(context: Context) { } } + /**+ * Say that a resource offered with an unknown length has finished being written.+ *+ * Only for a [CastResource] whose `length` was negative. [length] is the real size now that it+ * is known, or negative to say the producer **failed** - which releases whatever is reading it+ * with an error instead of leaving it to wait out its own bound. Both outcomes must be+ * reported: a reader that has caught up with the writer is parked until one of them arrives.+ *+ * Silent and non-throwing, like [play], and for the same reason.+ */+ fun resourceComplete(resourceId: String, length: Long) {+ if (!open) return+ val remote = service ?: return+ val message = Message.obtain(null, CastContract.MSG_RESOURCE_COMPLETE).apply {+ data = Bundle().apply {+ putString(CastContract.KEY_RESOURCE_ID, resourceId)+ // Absent rather than negative is what the service reads as a failure, so a failure+ // is the absence of a length rather than a second flag that could disagree with it.+ if (length >= 0) putLong(CastContract.KEY_RESOURCE_LENGTH, length)+ }+ }+ try {+ remote.send(message)+ } catch (_: RemoteException) {+ }+ }+ /** * End the session and unbind. Idempotent, and safe if [openSession] never succeeded. *
sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt
diff --git a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.ktindex a1e0fe8796..10682ad73c 100644--- a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt+++ b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt@@ -37,6 +37,15 @@ package com.vayunmathur.sdk.cast * … Cast serves byte ranges of that fd to the TV, which decodes them itself … * ``` *+ * A resource may also be offered while it is still being written, with a negative length - which+ * is what lets an app start playback before it has finished encoding:+ *+ * ```+ * MSG_RESOURCE_RESPONSE ─► (a growing fd, length = -1, MIME type)+ * … Cast serves it with no Content-Length and waits at end of file rather than reporting one …+ * MSG_RESOURCE_COMPLETE ─► (the real length, or none if it failed)+ * ```+ * * Which is what lets an app cast with no encoder on the phone at all - and what lets an audio-only * app cast, which the `Surface` path could not do in any form. */@@ -127,6 +136,21 @@ object CastContract { */ const val MSG_PLAY_MEDIA = 9 + /**+ * A resource that was offered with an unknown length has finished being written.+ *+ * Carries [KEY_RESOURCE_ID] and, on success, [KEY_RESOURCE_LENGTH]. Only meaningful for a+ * resource whose length was negative in its [MSG_RESOURCE_RESPONSE]: a file descriptor to a+ * file still being written reports EOF at the current end of file, and Cast cannot tell "not+ * yet" from "done", so a reader that has caught up with the writer waits for this.+ *+ * **An absent [KEY_RESOURCE_LENGTH] means the producer failed**, and is what releases a+ * waiting reader with an error rather than leaving it blocked until its own bound expires.+ * A client that offers an unknown length and then never sends this turns a fetch into a+ * stall, so it must send one on both paths.+ */+ const val MSG_RESOURCE_COMPLETE = 10+ // ---- service → client ---- /**@@ -257,7 +281,18 @@ object CastContract { */ const val KEY_RESOURCE_FD = "resourceFd" - /** The resource's total length in bytes, stated by the app rather than measured. */+ /**+ * The resource's total length in bytes, stated by the app rather than measured.+ *+ * **Negative means "still being written, final size unknown"**, which is how an app offers a+ * resource it is producing as the TV fetches it. Cast then serves the whole resource with no+ * `Content-Length`, ends the body by closing the connection, and waits at end of file rather+ * than reporting one - until [MSG_RESOURCE_COMPLETE] arrives with the real length.+ *+ * The cost of that is honest and unavoidable: with no total there is nothing to answer a+ * `Range` against, so the first play of such a resource cannot be seeked. Once it has been+ * completed the same resource reports a real length and behaves like any other.+ */ const val KEY_RESOURCE_LENGTH = "resourceLength" /** The resource's MIME type, which decides which extractor the TV's player reaches for. */
sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastResource.kt
diff --git a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastResource.kt b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastResource.ktindex 580d721f16..9b4d8f10c7 100644--- a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastResource.kt+++ b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastResource.kt@@ -27,11 +27,21 @@ class CastResource( */ val descriptor: ParcelFileDescriptor, /**- * Total length in bytes.+ * Total length in bytes, or **negative when the resource is still being written and the final+ * size is not known yet**. * * Stated by the app rather than measured, because a file still being written has a length its * author knows and `fstat` does not yet agree with. Cast reports it as the resource's length * and serves ranges against it.+ *+ * A negative length is how an app serves something it is producing as the TV fetches it - a+ * live transcode, say. Cast then serves the whole resource with no `Content-Length` and, when a+ * read reaches the current end of file, waits for more bytes instead of reporting the end. The+ * app must finish with [CastClient.resourceComplete], on failure as well as on success: a+ * reader that is never told turns into a stalled fetch.+ *+ * The price is that a resource with no length cannot answer a `Range`, so **the first play of+ * one cannot be seeked**. Offer a real length whenever there is one. */ val length: Long, /**
sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.kt
diff --git a/sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.kt b/sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.ktindex 0f01c22f59..94465d543f 100644--- a/sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.kt+++ b/sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.kt@@ -45,6 +45,7 @@ class CastContractTest { CastContract.MSG_RESOURCE_REQUEST, CastContract.MSG_RESOURCE_RESPONSE, CastContract.MSG_PLAY_MEDIA,+ CastContract.MSG_RESOURCE_COMPLETE, ) assertEquals(codes.size, codes.toSet().size, "two Messenger `what` codes are the same") }@@ -114,6 +115,17 @@ class CastContractTest { assertEquals(2, CastContract.AUDIO_CHANNELS) } + @Test+ fun `the completion message reuses the resource keys rather than inventing new ones`() {+ // MSG_RESOURCE_COMPLETE names a resource and states its final length, which are the two+ // things MSG_RESOURCE_RESPONSE already has keys for. A second spelling of either would be a+ // message the service reads as being about no resource at all.+ assertEquals("resourceId", CastContract.KEY_RESOURCE_ID)+ assertEquals("resourceLength", CastContract.KEY_RESOURCE_LENGTH)+ // Distinct from MSG_PLAY_MEDIA, which is the code it was added next to.+ assertTrue(CastContract.MSG_RESOURCE_COMPLETE != CastContract.MSG_PLAY_MEDIA)+ }+ // ---- transport controls ---- @Test