cast: replace Google Cast with a first-party protocol and a TV receiver
- Commit
1365973f0338cb163924adde03648f1d23f519b4- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-21 17:56 UTC (3 months ago)
- Parents
fa38241
Diff
README.md
diff --git a/README.md b/README.mdindex dc442801a1..b23e94d752 100644--- a/README.md+++ b/README.md@@ -32,6 +32,8 @@ Every released and planned app is listed here: Though some apps may have exceptions, generally a 64-bit device running at least Android 12 is required. +**Cast (Android TV receiver)** is the one app that is not for a phone: it runs on an Android TV or Google TV and is what the Cast app mirrors to. It is listed in the table below like any other app, but it will not appear on a phone's launcher and is not installable on one.+ **THE RECOMMENDED INSTALLATION METHOD IS MA APP STORE.** It is the most secure way to download MA apps. **FOR F-DROID USERS, ADD THIS REPO TO YOUR CLIENT: [https://ma.vayunmathur.com/fdroid](https://ma.vayunmathur.com/fdroid)** (for faster updates and apps unavailable on the main repo)@@ -44,6 +46,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **Calendar** | [Homepage](https://ma.vayunmathur.com/apps/calendar) | [](https://f-droid.org/packages/com.vayunmathur.calendar/) | [](https://api.vayunmathur.com/obtainium-link?name=Calendar&packageName=com.vayunmathur.calendar&apk=calendar-release.apk) | | **Camera** | [Homepage](https://ma.vayunmathur.com/apps/camera) | [](https://f-droid.org/packages/com.vayunmathur.camera/) | [](https://api.vayunmathur.com/obtainium-link?name=Camera&packageName=com.vayunmathur.camera&apk=camera-release.apk) | | **Cast** | [Homepage](https://ma.vayunmathur.com/apps/cast) | In Progress | In Progress |+| **Cast (Android TV receiver)** | [Homepage](https://ma.vayunmathur.com/apps/cast-tv) | In Progress | In Progress | | **Clock** | [Homepage](https://ma.vayunmathur.com/apps/clock) | [](https://f-droid.org/packages/com.vayunmathur.clock/) | [](https://api.vayunmathur.com/obtainium-link?name=Clock&packageName=com.vayunmathur.clock&apk=clock-release.apk) | | **Code** | [Homepage](https://ma.vayunmathur.com/apps/code) | [](https://f-droid.org/packages/com.vayunmathur.code/) | [](https://api.vayunmathur.com/obtainium-link?name=Code&packageName=com.vayunmathur.code&apk=code-release.apk) | | **Contacts** | [Homepage](https://ma.vayunmathur.com/apps/contacts) | [](https://f-droid.org/packages/com.vayunmathur.contacts/) | [](https://api.vayunmathur.com/obtainium-link?name=Contacts&packageName=com.vayunmathur.contacts&apk=contacts-release.apk) |
backup/src/main/java/com/vayunmathur/backup/platform/crypto/KeyManager.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/platform/crypto/KeyManager.kt b/backup/src/main/java/com/vayunmathur/backup/platform/crypto/KeyManager.ktindex 83c6e343bc..6457f8b18e 100644--- a/backup/src/main/java/com/vayunmathur/backup/platform/crypto/KeyManager.kt+++ b/backup/src/main/java/com/vayunmathur/backup/platform/crypto/KeyManager.kt@@ -2,8 +2,8 @@ package com.vayunmathur.backup.platform.crypto import android.content.Context import android.util.Base64-import com.vayunmathur.backup.domain.crypto.Hkdf import com.vayunmathur.library.util.DatabaseHelper+import com.vayunmathur.library.util.Hkdf /** * Persists the AES-256 master backup key, wrapped by an AndroidKeyStore key, reusing
cast/build.gradle.kts
diff --git a/cast/build.gradle.kts b/cast/build.gradle.ktsindex 0346dd8885..70ee5efdd1 100644--- a/cast/build.gradle.kts+++ b/cast/build.gradle.kts@@ -13,7 +13,10 @@ android { } } -// No Rust crate, unlike :share. CastV2 needs a TLS client socket and the root Cargo.toml-// forbids network stacks in Rust, so the socket has to be Kotlin either way - and once it-// is, CastMessage's seven scalar protobuf fields are cheaper to hand-roll in Kotlin than-// to bridge over JNI. See cast/src/main/java/.../network/CastMessageCodec.kt.+dependencies {+ // The wire format, shared verbatim with the TV receiver. Nothing here re-implements it.+ implementation(project(":cast:protocol"))+}++// No Rust crate. The protocol module already reaches ML-KEM through :library:e2ee-p2p, and+// everything left here is Android platform work: MediaProjection, MediaCodec, sockets.
cast/protocol/build.gradle.kts
diff --git a/cast/protocol/build.gradle.kts b/cast/protocol/build.gradle.ktsnew file mode 100644index 0000000000..1df36b3774--- /dev/null+++ b/cast/protocol/build.gradle.kts@@ -0,0 +1,18 @@+plugins {+ id("common-conventions-library")+}++// Deliberately NOT common-conventions-jvm, even though every test here runs on the JVM:+// SecretSealing reaches ML-KEM through :library:e2ee-p2p, whose implementation is a Rust+// .so, so this has to be an Android library to consume it. Nothing else in the module+// touches the Android framework, which is what keeps the round-trip suite host-runnable.+//+// No `defaultConfig {` block: release.sh sed-injects versionCode/versionName after that+// literal in every build.gradle.kts it finds, and a library has no such properties.++dependencies {+ // Hkdf: the whole key schedule expands from one 32-byte session secret.+ implementation(project(":library"))+ // Pqc.encryptTo / PqcIdentity.decrypt, used only by SecretSealing.+ implementation(project(":library:e2ee-p2p"))+}
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/ControlFraming.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/ControlFraming.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/ControlFraming.ktnew file mode 100644index 0000000000..905216b7d4--- /dev/null+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/ControlFraming.kt@@ -0,0 +1,112 @@+package com.vayunmathur.cast.protocol++import com.vayunmathur.e2ee.E2ee+import java.io.DataInput+import java.io.EOFException+import java.util.Base64++/**+ * `int32be(len) ‖ payload` on a TCP stream.+ *+ * The same idiom the old `CastChannel` used, minus its permissive TLS - we have our own handshake,+ * so there is no PKI problem to work around and no reason for a socket in this app to trust+ * anything it is handed.+ */+object ControlFraming {++ /**+ * A frame larger than this is refused rather than allocated.+ *+ * `TV_IDENTITY` carries a Base64 ML-KEM + ML-DSA bundle, a few kilobytes, so this is orders of+ * magnitude of headroom; the point is only that a corrupt or hostile length prefix cannot ask+ * for a gigabyte.+ */+ const val MAX_FRAME_BYTES = 1 shl 20++ fun encode(body: ByteArray): ByteArray {+ val out = ByteArray(4 + body.size)+ out[0] = (body.size ushr 24).toByte()+ out[1] = (body.size ushr 16).toByte()+ out[2] = (body.size ushr 8).toByte()+ out[3] = body.size.toByte()+ body.copyInto(out, 4)+ return out+ }++ /**+ * One frame's body, or null at a clean end of stream.+ *+ * Throws on a length prefix outside the bound: the stream cannot be resynchronised after one, so+ * carrying on would read a payload as a length forever.+ */+ fun read(input: DataInput): ByteArray? {+ val length = try {+ input.readInt()+ } catch (_: EOFException) {+ return null+ }+ require(length in 1..MAX_FRAME_BYTES) { "refusing a $length byte control frame" }+ return ByteArray(length).also { input.readFully(it) }+ }+}++/**+ * Turns [ControlMessage]s into frame bodies and back, encrypting once the session key is known.+ *+ * The cipher is installed by [useSessionKey] at exactly one point in the sequence - immediately+ * after `SEALED_SECRET` - on both ends. That is what keeps them in step: there is no per-frame flag+ * saying whether a body is encrypted, because a flag an attacker can clear is a downgrade.+ *+ * AES-256-GCM via `E2ee.aesEncrypt`, so the control channel *is* authenticated even though the media+ * payload is not. A tampered control frame fails its tag and closes the session, which is why+ * unauthenticated media cannot be used to hijack one.+ */+class ControlCodec {++ private var sessionKey: ByteArray? = null++ /** True once [useSessionKey] has been called, i.e. from `PAIR_REQUIRED` onward. */+ val isEncrypting: Boolean get() = sessionKey != null++ fun useSessionKey(key: ByteArray) {+ sessionKey = key+ }++ /** The frame body for [message]: JSON, then encrypted if the key is installed. */+ fun encode(message: ControlMessage): ByteArray {+ val json = ControlJson.encodeToString(message).toByteArray(Charsets.UTF_8)+ val key = sessionKey ?: return json+ return E2ee.aesEncrypt(key, json)+ }++ /**+ * The message in [body], or null when it is not one.+ *+ * Null covers a failed GCM tag, a payload that is not JSON, and a `type` this build does not+ * know. All three are handled the same way by both ends - close the session - because after the+ * cipher is installed there is no benign reason for any of them.+ */+ fun decode(body: ByteArray): ControlMessage? {+ val key = sessionKey+ val json = if (key == null) {+ body+ } else {+ runCatching { E2ee.aesDecrypt(key, body) }.getOrNull() ?: return null+ }+ return runCatching {+ ControlJson.decodeFromString<ControlMessage>(json.toString(Charsets.UTF_8))+ }.getOrNull()+ }+}++/**+ * Base64 for the byte fields the handshake carries as strings.+ *+ * `java.util.Base64` rather than `android.util.Base64` so the handshake round-trips in a plain JVM+ * test, which is the whole verification strategy while there is no TV to try it on.+ */+object ProtocolBase64 {+ fun encode(bytes: ByteArray): String = Base64.getEncoder().encodeToString(bytes)++ fun decode(text: String): ByteArray? = runCatching { Base64.getDecoder().decode(text) }.getOrNull()+}
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Crypto.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Crypto.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Crypto.ktnew file mode 100644index 0000000000..787396c09e--- /dev/null+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Crypto.kt@@ -0,0 +1,69 @@+package com.vayunmathur.cast.protocol++import javax.crypto.Cipher+import javax.crypto.spec.IvParameterSpec+import javax.crypto.spec.SecretKeySpec++/**+ * Media payload encryption: AES-128-CTR with a per-frame IV.+ *+ * Kept exactly as it was written against openscreen `cast/streaming/impl/frame_crypto.cc`+ * (`FrameCrypto::Crypt`), because it is golden-byte tested and now has a decrypting half in this+ * same module. The IV is *not* random and *not* transmitted - both ends derive it from the frame id+ * and the mask agreed in the handshake, which is why a wrong derivation shows up as a picture of+ * pure noise rather than as an error.+ *+ * **Deliberately not routed through `library/e2ee-p2p`'s `E2ee.kt`.** That is AES-256-GCM with a+ * random IV prepended to the ciphertext: authenticated, larger key, self-describing nonce. Every+ * one of those properties is wrong here - a derived IV costs no bytes on the wire, and CTR lets a+ * frame be decrypted from its id alone, without the packets having to arrive in order.+ *+ * **This leaves the media stream unauthenticated, and that is a real limitation.** Confidentiality+ * is delivered; integrity is not, so an attacker able to inject UDP could corrupt the picture+ * without being detected. The *control* channel is AES-256-GCM (see [ControlCodec]), so this cannot+ * be used to hijack a session or force a downgrade. Moving to per-packet AEAD is a contained change+ * if that trade stops being acceptable - roughly 16 bytes per packet, about 1% overhead.+ */+class Crypto(key: ByteArray, private val ivMask: ByteArray) {++ init {+ require(key.size == KEY_BYTES) { "AES-128 needs a 16-byte key; got ${key.size}" }+ require(ivMask.size == KEY_BYTES) { "the IV mask is one AES block; got ${ivMask.size}" }+ }++ private val keySpec = SecretKeySpec(key, "AES")++ /**+ * The counter block for [frameId].+ *+ * Sixteen zero bytes, the frame id's lower 32 bits written big-endian at offset 8, then the+ * whole thing XORed with the mask. The offset is what makes the counter increment within a+ * frame without colliding with the next frame's blocks.+ */+ fun ivForFrame(frameId: FrameId): ByteArray {+ val iv = ByteArray(KEY_BYTES)+ val lower32 = frameId.lower32+ iv[8] = (lower32 ushr 24).toByte()+ iv[9] = (lower32 ushr 16).toByte()+ iv[10] = (lower32 ushr 8).toByte()+ iv[11] = lower32.toByte()+ for (i in iv.indices) iv[i] = (iv[i].toInt() xor ivMask[i].toInt()).toByte()+ return iv+ }++ /**+ * Encrypt or decrypt one frame.+ *+ * CTR is its own inverse, so the sender and the receiver call the identical method - which is+ * also why a round-trip test proving `crypt(crypt(x)) == x` genuinely covers both ends.+ */+ fun crypt(frameId: FrameId, payload: ByteArray): ByteArray {+ val cipher = Cipher.getInstance("AES/CTR/NoPadding")+ cipher.init(Cipher.ENCRYPT_MODE, keySpec, IvParameterSpec(ivForFrame(frameId)))+ return cipher.doFinal(payload)+ }++ private companion object {+ const val KEY_BYTES = 16+ }+}
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/FrameAssembler.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/FrameAssembler.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/FrameAssembler.ktnew file mode 100644index 0000000000..20854fdc0a--- /dev/null+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/FrameAssembler.kt@@ -0,0 +1,192 @@+package com.vayunmathur.cast.protocol++/**+ * Packets in, whole frames out - the exact inverse of [RtpPacketizer].+ *+ * Three things make this the hard half of the receiver, and all three are here rather than spread+ * around:+ *+ * 1. **Frame ids arrive truncated to 8 bits.** They are expanded against the last frame completed,+ * nearest-first, because an arriving frame is usually just ahead of it while a *retransmission*+ * is behind - and neither one-sided expansion can produce both.+ * 2. **Packets arrive out of order, duplicated, or not at all.** A frame is only emitted once every+ * one of its packets is in hand, and a duplicate is dropped rather than counted twice.+ * 3. **It has to be bounded.** A sender that keeps producing while one frame stays permanently+ * incomplete must not be able to grow the heap, so the oldest partial goes when the buffer is+ * full.+ *+ * Emits [EncryptedFrame] - the same type the packetizer consumes - so a round-trip assertion is one+ * `==` rather than a field-by-field comparison. The payload is still encrypted at this point;+ * decryption belongs to [ReceiverSession], which is the thing that knows the keys.+ */+class FrameAssembler(private val maxPending: Int = MAX_PENDING_FRAMES) {++ private val pending = LinkedHashMap<Long, Partial>()++ /**+ * What truncated ids are expanded against.+ *+ * Starts null, so the very first packet's 8-bit id is taken literally: a sender always begins a+ * session at [FrameId.First], but a receiver that came up a few frames late would otherwise+ * expand 250 to -6.+ */+ private var reference: FrameId? = null++ /** The highest frame id seen, complete or not. The top of the range worth NACKing. */+ var highest: FrameId = FrameId.First+ private set++ /**+ * Feed one packet in; get a frame back when that packet completed one.+ *+ * Packets belonging to a frame at or below [floor] are dropped: those are retransmissions of+ * frames already delivered, and re-emitting one would hand the decoder a frame it has decoded.+ */+ fun add(packet: RtpPacket, floor: FrameId = FrameId.Leader): EncryptedFrame? {+ val frameId = expand(packet.frameId8)+ if (frameId <= floor) return null+ if (frameId > highest) highest = frameId++ val partial = pending.getOrPut(frameId.value) {+ Partial(+ frameId = frameId,+ maxPacketId = packet.maxPacketId,+ rtpTimestamp = packet.rtpTimestamp,+ isKeyFrame = packet.isKeyFrame,+ // A frame references itself or something earlier, never a later one, so the+ // one-sided expansion is the right one here.+ referencedFrameId = Rtcp.expandLessThanOrEqual(frameId, packet.referenceFrameId8),+ )+ }+ evictOldest()+ // Already emitted. Its packets keep arriving - the sender answers a NACK it may already have+ // answered - and re-emitting would hand the decoder a frame it has decoded.+ if (partial.isEmitted) return null+ // A packet that disagrees with the rest of its frame about how many packets there are is+ // corrupt or from a different frame that happened to truncate to the same id. Either way the+ // partial cannot be trusted, so it is restarted rather than mixed.+ if (partial.maxPacketId != packet.maxPacketId) {+ pending.remove(frameId.value)+ return null+ }+ if (!partial.put(packet.packetId, packet.payload)) return null+ if (!partial.isComplete) return null+ // Kept rather than removed, so the duplicates that follow are absorbed by the check above.+ // discardUpTo and the eviction bound are what free it.+ return partial.emit()+ }++ /** Forget everything at or below [frameId]; it has been delivered and cannot be needed again. */+ fun discardUpTo(frameId: FrameId) {+ pending.keys.removeAll { it <= frameId.value }+ }++ /**+ * What to ask for, for the frames in `(after, highest]`.+ *+ * A frame with a partial contributes its missing packet ids; a frame with nothing at all+ * contributes a whole-frame NACK, which is the only thing that can be said about a frame whose+ * packet count is not yet known. Capped, because a NACK list long enough to fragment its own+ * datagram makes the loss worse.+ */+ fun missingPackets(after: FrameId): List<PacketNack> {+ val out = mutableListOf<PacketNack>()+ var id = after + 1+ while (id <= highest && out.size < Rtcp.MAX_LOSS_FIELDS) {+ val partial = pending[id.value]+ if (partial == null) {+ out += PacketNack.wholeFrame(id)+ } else {+ for (packetId in partial.missing()) out += PacketNack(id, packetId)+ }+ id += 1+ }+ return out+ }++ fun reset() {+ pending.clear()+ reference = null+ highest = FrameId.First+ }++ private fun expand(truncated: Int): FrameId {+ val current = reference+ val expanded = if (current == null) FrameId(truncated.toLong()) else {+ Rtcp.expandNearest(current, truncated)+ }+ // Tracked forward only: expanding against a retransmission's older id would then make the+ // *next* live frame look like a lap ahead.+ if (current == null || expanded > current) reference = expanded+ return expanded+ }++ /** Dropping the oldest is right: a frame nobody completed is a frame nobody can decode. */+ private fun evictOldest() {+ while (pending.size > maxPending) {+ pending.remove(pending.keys.first())+ }+ }++ private class Partial(+ val frameId: FrameId,+ val maxPacketId: Int,+ val rtpTimestamp: Long,+ val isKeyFrame: Boolean,+ val referencedFrameId: FrameId,+ ) {+ private val chunks = arrayOfNulls<ByteArray>(maxPacketId + 1)+ private var received = 0++ val isComplete: Boolean get() = received == chunks.size++ /** True once [emit] has handed this frame over, which is what makes duplicates cheap. */+ var isEmitted: Boolean = false+ private set++ /** False when [packetId] was already held, i.e. this is a duplicate or a retransmission. */+ fun put(packetId: Int, payload: ByteArray): Boolean {+ if (packetId !in chunks.indices) return false+ if (chunks[packetId] != null) return false+ chunks[packetId] = payload+ received+++ return true+ }++ /** Empty once emitted: NACKing packets of a frame already delivered would ask for nothing. */+ fun missing(): List<Int> =+ if (isEmitted) emptyList() else chunks.indices.filter { chunks[it] == null }++ /**+ * The assembled frame, once. The chunks are released afterwards: a completed frame's bytes+ * are the caller's now, and holding a second copy of two seconds of video is the difference+ * between a bounded buffer and a large one.+ */+ fun emit(): EncryptedFrame {+ val payload = ByteArray(chunks.sumOf { it?.size ?: 0 })+ var offset = 0+ for (chunk in chunks) {+ val bytes = chunk ?: continue+ bytes.copyInto(payload, offset)+ offset += bytes.size+ }+ chunks.fill(null)+ isEmitted = true+ return EncryptedFrame(+ frameId = frameId,+ referencedFrameId = referencedFrameId,+ rtpTimestamp = rtpTimestamp,+ isKeyFrame = isKeyFrame,+ payload = payload,+ )+ }+ }++ private companion object {+ /**+ * Two seconds of video at 30 fps, matching the sender's retransmit buffer: holding a partial+ * for longer than the sender can still repair it is holding it for nothing.+ */+ const val MAX_PENDING_FRAMES = 60+ }+}
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/FrameId.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/domain/streaming/FrameId.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/FrameId.ktsimilarity index 86%rename from cast/src/main/java/com/vayunmathur/cast/domain/streaming/FrameId.ktrename to cast/protocol/src/main/java/com/vayunmathur/cast/protocol/FrameId.ktindex 6ec995bc62..7b27bc71ea 100644--- a/cast/src/main/java/com/vayunmathur/cast/domain/streaming/FrameId.kt+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/FrameId.kt@@ -1,4 +1,4 @@-package com.vayunmathur.cast.domain.streaming+package com.vayunmathur.cast.protocol /** * A frame's identifier.@@ -6,8 +6,9 @@ package com.vayunmathur.cast.domain.streaming * **Not an 8-bit wrapping value**, which is the trap here. openscreen's `FrameId` * (`cast/streaming/public/frame_id.h`) extends `ExpandedValueBase<int64_t>`: the counter is 64-bit * and only *truncated* to 8 bits for the RTP header, with the receiver re-expanding it. Modelling+ * Modelling * the counter itself as a byte would still produce correct headers but the wrong encryption IV- * from frame 256 onward, because [CastCrypto] derives the IV from [lower32] of the full value.+ * from frame 256 onward, because [Crypto] derives the IV from [lower32] of the full value. * * `first()` is 0 and `leader()` is -1 ("the frame before the first"), both verbatim from * openscreen; `leader` is what a key frame references, since it has no real predecessor.@@ -23,6 +24,8 @@ value class FrameId(val value: Long) : Comparable<FrameId> { operator fun plus(delta: Long): FrameId = FrameId(value + delta) + operator fun minus(delta: Long): FrameId = FrameId(value - delta)+ operator fun minus(other: FrameId): Long = value - other.value override fun compareTo(other: FrameId): Int = value.compareTo(other.value)
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.ktnew file mode 100644index 0000000000..5a9c312314--- /dev/null+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt@@ -0,0 +1,198 @@+package com.vayunmathur.cast.protocol++import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * The protocol version in every `HELLO` and `TV_IDENTITY`.+ *+ * Checked on both sides and refused on mismatch, rather than negotiated down. Two of our own builds+ * that disagree about the wire format are a bug to fix, not a compatibility matrix to maintain -+ * both halves ship from this repo at the same version.+ */+const val PROTOCOL_VERSION = 1++/** The mDNS service type the TV registers and the phone browses for. */+const val MACAST_SERVICE_TYPE = "_macast._tcp"++/**+ * The control-channel sequence, in the order it happens:+ *+ * ```+ * phone HELLO ─────────────────────────────────►+ * ◄───────────── TV_IDENTITY (public bundle + decoder limits)+ * SEALED_SECRET ────────────────────────► (session secret, sealed to that bundle)+ *+ * ◄───────────── PAIR_REQUIRED (code, or "prove the key you hold")+ * PAIR_PROOF ──────────────────────────►+ * ◄───────────── PAIR_OK / PAIR_FAILED+ *+ * STREAM_CONFIG ───────────────────────► (chosen to fit the reported limits)+ * ◄───────────── STREAM_READY (udp port + receiver SSRCs)+ * … RTP over UDP …+ * BYE ─────────────────────────────────►+ * ```+ *+ * Everything from `PAIR_REQUIRED` onward is AES-256-GCM under the derived control key; the first+ * three messages cannot be, because they are what establishes it. Both ends install the cipher at+ * the same point in the sequence, so they can never disagree about which frames are encrypted.+ */+@Serializable+sealed interface ControlMessage++/** Who is calling, and whether it expects to be remembered. */+@Serializable+@SerialName("HELLO")+data class Hello(+ val version: Int = PROTOCOL_VERSION,+ val senderName: String,+ /**+ * A stable id for this phone, so the TV can look up a remembered device key before it knows+ * anything else. Not a secret: it only decides whether a code will be asked for.+ */+ val senderId: String,+ /**+ * True when the phone holds a device key for this TV.+ *+ * The TV still decides - it may have forgotten the phone, or been factory reset - but this is+ * what lets it avoid putting a pair code on screen for a phone that does not need one.+ */+ val paired: Boolean = false,+) : ControlMessage++/** What the TV is, what it can decode, and the key to seal a secret to. */+@Serializable+@SerialName("TV_IDENTITY")+data class TvIdentity(+ val version: Int = PROTOCOL_VERSION,+ val receiverName: String,+ val receiverId: String,+ /** Base64 ML-KEM + ML-DSA public bundle, from `PqcIdentity.publicBundle`. */+ val publicBundle: String,+ val limits: DecoderLimits,+) : ControlMessage++/**+ * What the TV's decoder will actually accept.+ *+ * **The single clearest benefit of owning the receiver.** The old sender had to guess, settled on+ * 1080p because that was Chrome's mirroring policy, and letterboxed a portrait phone screen into it+ * by hand - wasting most of the frame. These come from the TV's real+ * `MediaCodecInfo.VideoCapabilities`, so the sender can send the phone's own aspect ratio at+ * whatever size fits and let the TV pad it.+ */+@Serializable+data class DecoderLimits(+ val maxWidth: Int,+ val maxHeight: Int,+ val maxFrameRate: Int,+ val maxBitRate: Int,+)++/** The session secret, sealed to [TvIdentity.publicBundle]. Base64 of [SecretSealing.seal]. */+@Serializable+@SerialName("SEALED_SECRET")+data class SealedSecret(val sealed: String) : ControlMessage++/**+ * The TV's answer to `SEALED_SECRET`, and always exactly one message so the sequence has no branch+ * the phone has to guess at.+ *+ * [code] false means the TV remembers this phone and wants only a proof of the device key it holds;+ * true means it does not, and six digits are on screen. Making this explicit rather than letting the+ * phone infer it from its own stored state matters: the TV may have been factory reset, and a phone+ * that guessed wrong would spend one of three pair attempts finding out.+ */+@Serializable+@SerialName("PAIR_REQUIRED")+data class PairRequired(+ val code: Boolean,+ val attemptsLeft: Int = PairCode.MAX_ATTEMPTS,+) : ControlMessage++/**+ * Either the code proof or the remembered-device proof - the TV knows which it asked for, so one+ * message carries both cases.+ */+@Serializable+@SerialName("PAIR_PROOF")+data class PairProof(val proof: String) : ControlMessage++/**+ * Paired.+ *+ * [deviceKey] is a fresh random key, present only when this was a code pairing; both ends persist it+ * and later sessions authenticate with it instead of a code. Absent when the phone had already+ * proved possession of one.+ */+@Serializable+@SerialName("PAIR_OK")+data class PairOk(val deviceKey: String? = null) : ControlMessage++/**+ * Wrong proof.+ *+ * [attemptsLeft] is how many tries remain against the code currently on screen. [codeChanged] means+ * the allowance ran out and the TV has replaced the code, so the user has to look at the screen again+ * rather than retype what they had - stated outright rather than left to be inferred from a full+ * allowance coming back from a failure.+ */+@Serializable+@SerialName("PAIR_FAILED")+data class PairFailed(+ val attemptsLeft: Int,+ val codeChanged: Boolean = false,+) : ControlMessage++/**+ * What the phone is about to send.+ *+ * The SSRCs are the phone's own. The receiver answers with its own in [StreamReady]; neither may+ * derive the other's, because the pair is what identifies a stream in every RTCP packet.+ */+@Serializable+@SerialName("STREAM_CONFIG")+data class StreamConfig(+ val width: Int,+ val height: Int,+ val frameRate: Int,+ val bitRate: Int,+ val audio: Boolean,+ val video: Boolean,+ val audioSsrc: Long,+ val videoSsrc: Long,+) : ControlMessage++/** Where to send it, and which SSRCs the feedback will come from. */+@Serializable+@SerialName("STREAM_READY")+data class StreamReady(+ val udpPort: Int,+ val audioSsrc: Long,+ val videoSsrc: Long,+) : ControlMessage++/**+ * Either end, at any point after the secret is established.+ *+ * Sent rather than just closing the socket, so the TV can return to its idle screen instead of+ * holding the last frame while it waits for a read to time out.+ */+@Serializable+@SerialName("BYE")+data class Bye(val reason: String = "") : ControlMessage++/**+ * Strict on the way in, complete on the way out.+ *+ * `ignoreUnknownKeys` because a field added by a newer build must not kill a session outright, and+ * `encodeDefaults` because the discriminator and the version are defaulted constants that the peer+ * genuinely needs. `explicitNulls` off so an absent `deviceKey` stays absent.+ */+val ControlJson: Json = Json {+ ignoreUnknownKeys = true+ encodeDefaults = true+ explicitNulls = false+ classDiscriminator = "type"+}
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/KeySchedule.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/KeySchedule.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/KeySchedule.ktnew file mode 100644index 0000000000..48f4a18970--- /dev/null+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/KeySchedule.kt@@ -0,0 +1,145 @@+package com.vayunmathur.cast.protocol++import com.vayunmathur.library.util.Hkdf+import java.security.MessageDigest+import java.security.SecureRandom+import javax.crypto.Mac+import javax.crypto.spec.SecretKeySpec++/**+ * Everything derived from the one 32-byte session secret.+ *+ * The secret is generated by the phone and sealed to the TV's ML-KEM public key, so it is the only+ * thing that crosses the wire; every key below is expanded from it by HKDF-SHA256 with a distinct+ * `info` string. Nothing is ever transmitted, which means a wrong derivation on either side shows up+ * as a black screen rather than as a rejected message - hence the round-trip test asserting the two+ * ends produce identical schedules from the same secret.+ *+ * **No Android or PQC dependency**: this whole file runs on the JVM, which is what makes the pairing+ * rules testable without a TV. Sealing the secret is [SecretSealing]'s job precisely so that the+ * native ML-KEM library stays out of here.+ */+class SessionKeys private constructor(secret: ByteArray) {++ /** AES-256-GCM key for the control channel, from `SEALED_SECRET` onward. */+ val control: ByteArray = derive(secret, "control", CONTROL_KEY_BYTES)++ val audio: StreamKeys = StreamKeys(+ key = derive(secret, "audio key", MEDIA_KEY_BYTES),+ ivMask = derive(secret, "audio iv", MEDIA_KEY_BYTES),+ )++ val video: StreamKeys = StreamKeys(+ key = derive(secret, "video key", MEDIA_KEY_BYTES),+ ivMask = derive(secret, "video iv", MEDIA_KEY_BYTES),+ )++ /** HMAC key for the six-digit pair proof. */+ private val pairKey: ByteArray = derive(secret, "pair", CONTROL_KEY_BYTES)++ /** HMAC key for proving possession of a remembered device key. */+ private val deviceKeyProofKey: ByteArray = derive(secret, "device", CONTROL_KEY_BYTES)++ /**+ * `HMAC(HKDF(secret, "pair"), code ‖ transcript)`.+ *+ * **Binding the code to the transcript is what makes six digits sufficient.** The transcript+ * covers the TV's public bundle, so a man in the middle - which necessarily substituted its own+ * bundle - is proving a transcript it did not create, and cannot. Without that binding, six+ * digits would be six digits of entropy against an attacker who can replay; with it, the code+ * only has to survive the online attempt limit the receiver enforces.+ */+ fun pairProof(code: String, transcript: ByteArray): ByteArray =+ hmac(pairKey, code.toByteArray(Charsets.UTF_8) + transcript)++ /**+ * The same shape for a device the user already paired: possession of [deviceKey] replaces the+ * code, so a second session shows nothing on screen.+ */+ fun deviceProof(deviceKey: ByteArray, transcript: ByteArray): ByteArray =+ hmac(deviceKeyProofKey, deviceKey + transcript)++ companion object {+ const val SECRET_BYTES = 32+ private const val CONTROL_KEY_BYTES = 32+ private const val MEDIA_KEY_BYTES = 16++ /** Namespaced so this secret can never collide with another feature's HKDF output. */+ private const val INFO_PREFIX = "com.vayunmathur.cast/"++ fun of(secret: ByteArray): SessionKeys {+ require(secret.size == SECRET_BYTES) {+ "the session secret is $SECRET_BYTES bytes; got ${secret.size}"+ }+ return SessionKeys(secret)+ }++ /** A fresh session secret. Generated by the phone, once per session. */+ fun newSecret(random: SecureRandom = SecureRandom()): ByteArray =+ ByteArray(SECRET_BYTES).also { random.nextBytes(it) }++ private fun derive(secret: ByteArray, purpose: String, length: Int): ByteArray =+ Hkdf.derive(secret, "$INFO_PREFIX$purpose".toByteArray(Charsets.UTF_8), length)++ private fun hmac(key: ByteArray, data: ByteArray): ByteArray =+ Mac.getInstance("HmacSHA256")+ .apply { init(SecretKeySpec(key, "HmacSHA256")) }+ .doFinal(data)+ }+}++/**+ * The six digits the TV shows and the user types on the phone.+ *+ * Six is enough only because the proof is transcript-bound and the receiver limits attempts - see+ * [SessionKeys.pairProof]. **`SecurityCode.compute` from `:library:e2ee-p2p` is not usable here**:+ * it is 4000 SHA-256 iterations over concatenated key hashes producing a 30-digit *comparison*+ * number for two humans to read to each other. Stretching gives a low-entropy shared secret no+ * protection at all against an online attacker, which is the only attacker this faces.+ */+object PairCode {++ const val DIGITS = 6++ /**+ * How many wrong codes before the displayed one is thrown away.+ *+ * Three, then a new code: this is what removes the offline-guessing objection to six digits, so+ * it is a correctness boundary rather than a nicety.+ */+ const val MAX_ATTEMPTS = 3++ private const val RANGE = 1_000_000++ fun random(random: SecureRandom = SecureRandom()): String =+ random.nextInt(RANGE).toString().padStart(DIGITS, '0')++ /** True when [entered] could be a code at all, so a typo is refused without an HMAC. */+ fun isWellFormed(entered: String): Boolean =+ entered.length == DIGITS && entered.all { it in '0'..'9' }+}++/**+ * The running hash of the handshake, up to and including `SEALED_SECRET`.+ *+ * Fed the **exact bytes that crossed the wire**, not re-encoded objects: JSON round-tripping is not+ * guaranteed to be byte-stable, and a transcript that differs by a key order is a transcript the two+ * ends disagree on - which would fail every pair attempt with no clue as to why.+ */+class Transcript {++ private val bodies = mutableListOf<ByteArray>()++ fun add(body: ByteArray) {+ bodies += body+ }++ fun value(): ByteArray {+ val digest = MessageDigest.getInstance("SHA-256")+ for (body in bodies) digest.update(body)+ return digest.digest()+ }+}++/** Constant-time comparison, so a wrong proof leaks nothing about how wrong it was. */+fun proofsMatch(a: ByteArray, b: ByteArray): Boolean = MessageDigest.isEqual(a, b)
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Pairing.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Pairing.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Pairing.ktnew file mode 100644index 0000000000..1bcfcb02a8--- /dev/null+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Pairing.kt@@ -0,0 +1,94 @@+package com.vayunmathur.cast.protocol++import java.security.SecureRandom++/** Whether a pair attempt was accepted, and what the user should be told if it was not. */+sealed interface PairResult {++ /** Paired. [deviceKey] is non-null when this was a code pairing and is what both ends persist. */+ data class Ok(val deviceKey: ByteArray?) : PairResult++ /**+ * Wrong proof.+ *+ * [codeChanged] means the attempt limit was reached and the code on screen has been replaced, so+ * the phone has to say "look at the TV again" rather than "try again".+ */+ data class Wrong(val attemptsLeft: Int, val codeChanged: Boolean) : PairResult+}++/**+ * The receiver's side of trust: the code on screen, the attempt limit, and proof verification.+ *+ * The attempt limit is what makes six digits defensible. Bound to the transcript, a proof cannot be+ * produced by a man in the middle at all (see [SessionKeys.pairProof]); the only attack left is+ * guessing, and one in a million per attempt with three attempts and then a fresh code is not a+ * guessing attack worth mounting. Deliberately **not** a PAKE: a PAKE would let the limit go away,+ * nothing in this repo has one, and SPAKE2 for this threat model is not worth its own sub-project.+ *+ * Pure, so all of it - correct code, wrong code, lockout, and a remembered device - is a JVM test.+ * [newCode] is injectable for exactly that reason.+ */+class PairingGate(private val newCode: () -> String = { PairCode.random() }) {++ /** The six digits currently on screen. */+ var code: String = newCode()+ private set++ var attemptsLeft: Int = PairCode.MAX_ATTEMPTS+ private set++ /**+ * Verify a proof of the displayed code.+ *+ * On success a fresh device key is minted and returned, so later sessions can skip the code+ * entirely. On the third failure the code is thrown away and a new one generated; anything the+ * attacker learned about the old one is worth nothing.+ */+ fun verifyCode(keys: SessionKeys, transcript: ByteArray, proof: ByteArray): PairResult {+ val expected = keys.pairProof(code, transcript)+ if (proofsMatch(expected, proof)) {+ reset()+ return PairResult.Ok(newDeviceKey())+ }+ attemptsLeft--+ if (attemptsLeft > 0) return PairResult.Wrong(attemptsLeft, codeChanged = false)+ reset()+ return PairResult.Wrong(attemptsLeft = PairCode.MAX_ATTEMPTS, codeChanged = true)+ }++ /**+ * Verify a proof of possession of a remembered [deviceKey].+ *+ * No attempt limit and no lockout: [deviceKey] is 32 random bytes, so there is nothing here worth+ * rate-limiting, and locking out on failure would let anyone on the LAN deny a paired phone+ * access by sending rubbish. A failure just means this phone is not the one we remember, and it+ * falls back to the code.+ */+ fun verifyDevice(+ keys: SessionKeys,+ transcript: ByteArray,+ deviceKey: ByteArray,+ proof: ByteArray,+ ): PairResult =+ if (proofsMatch(keys.deviceProof(deviceKey, transcript), proof)) {+ // Nothing new to persist - the phone already holds the key it just proved.+ PairResult.Ok(deviceKey = null)+ } else {+ PairResult.Wrong(attemptsLeft = attemptsLeft, codeChanged = false)+ }++ /** Put a new code on screen, e.g. when a session ends without pairing. */+ fun reset() {+ code = newCode()+ attemptsLeft = PairCode.MAX_ATTEMPTS+ }++ companion object {+ const val DEVICE_KEY_BYTES = 32++ /** The long-term secret a paired phone keeps. Random, never derived from the code. */+ fun newDeviceKey(random: SecureRandom = SecureRandom()): ByteArray =+ ByteArray(DEVICE_KEY_BYTES).also { random.nextBytes(it) }+ }+}
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/ReceiverSession.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/ReceiverSession.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/ReceiverSession.ktnew file mode 100644index 0000000000..b390b1b656--- /dev/null+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/ReceiverSession.kt@@ -0,0 +1,201 @@+package com.vayunmathur.cast.protocol++/** One frame, decrypted and in order, ready for a decoder. */+data class DecodableFrame(+ val frameId: FrameId,+ val rtpTimestamp: Long,+ val isKeyFrame: Boolean,+ val payload: ByteArray,+) {+ override fun equals(other: Any?): Boolean =+ other is DecodableFrame &&+ frameId == other.frameId &&+ rtpTimestamp == other.rtpTimestamp &&+ isKeyFrame == other.isKeyFrame &&+ payload.contentEquals(other.payload)++ override fun hashCode(): Int {+ var result = frameId.hashCode()+ result = 31 * result + rtpTimestamp.hashCode()+ result = 31 * result + isKeyFrame.hashCode()+ result = 31 * result + payload.contentHashCode()+ return result+ }+}++/**+ * [StreamingSession]'s mirror image: datagrams in, decodable frames out, feedback back.+ *+ * Free of sockets and codecs for the same reason the sender's half is - the ordering and recovery+ * rules are the part that is easy to get wrong, and this way every one of them is a JVM unit test.+ * The receiver app wires this to a `DatagramChannel` on one side and `MediaCodec` on the other.+ *+ * Two rules carry the whole design:+ *+ * 1. **Nothing is released before the first key frame.** A delta frame references a predecessor, so+ * feeding one to a decoder that never had it produces a green smear rather than an error. Until+ * a key frame arrives the session asks for one and drops everything else.+ * 2. **Frames are released strictly in order.** [checkpoint] is the highest frame delivered, and a+ * gap blocks everything behind it - which is exactly what makes retransmission worth doing. A+ * gap that outlives the sender's ability to repair it is escaped by asking for a key frame and+ * resynchronising on it.+ */+class ReceiverSession(+ private val stream: NegotiatedStream,+ private val playoutDelayMs: Int = StreamConstants.TARGET_DELAY_MS,+) {++ private val crypto = Crypto(stream.keys.key, stream.keys.ivMask)+ private val assembler = FrameAssembler()++ /** Complete but not yet releasable, because something before them has not arrived. */+ private val ready = sortedMapOf<Long, EncryptedFrame>()++ /**+ * The highest frame delivered to the decoder.+ *+ * [FrameId.Leader] - "the frame before the first" - until something is, so that+ * `checkpoint + 1` is [FrameId.First] from the start.+ */+ var checkpoint: FrameId = FrameId.Leader+ private set++ /** False until a key frame has been delivered, i.e. until the decoder has any reference at all. */+ private var synchronised = false++ /** Feedback rounds where a gap blocked delivery while frames beyond it kept arriving. */+ private var stalledRounds = 0++ /** Counters, so the receiver's log can be read against the sender's. */+ var packetsReceived: Long = 0+ private set+ var packetsIgnored: Long = 0+ private set+ var framesDelivered: Long = 0+ private set++ /**+ * One datagram in; whatever it made deliverable out.+ *+ * Usually empty - most packets are a fragment of a frame that is not finished - and occasionally+ * several frames at once, when the packet that arrived was the one plugging a gap.+ *+ * A datagram that is not RTP for *this* stream is counted and dropped. That is the normal case+ * for a shared socket carrying both halves of the mirror, so it must not be logged per packet.+ */+ fun onPacket(datagram: ByteArray): List<DecodableFrame> {+ val packet = RtpDepacketizer.parse(datagram)+ if (packet == null || packet.ssrc != stream.senderSsrc) {+ packetsIgnored+++ return emptyList()+ }+ packetsReceived+++ val frame = assembler.add(packet, floor = checkpoint) ?: return emptyList()+ // **Before the first key frame, a delta frame is dropped rather than held.** It cannot be+ // decoded - its reference never arrived - so holding it would grow the buffer for the whole+ // pre-sync period and put frames in the ACK vector that are never going to be played.+ if (!synchronised && !frame.isKeyFrame) return emptyList()+ ready[frame.frameId.value] = frame+ return drain()+ }++ /**+ * The RTCP to send back: what has been received, what is missing, and whether a key frame is+ * needed.+ *+ * Called on a timer rather than per packet, because feedback is only useful at about the rate the+ * sender can act on it. A PLI rides in the same datagram as the feedback block - RTCP is compound+ * by design, and sending them separately doubles the chance of losing the one that mattered.+ */+ fun feedback(): ByteArray {+ val nacks = assembler.missingPackets(after = checkpoint)+ val needsKeyFrame = !synchronised || isStalled()+ if (needsKeyFrame && synchronised) {+ // The gap has outlived the sender's retransmit buffer. Nothing else will unblock it, so+ // give up on it: resynchronise on the next key frame rather than stalling for ever.+ synchronised = false+ ready.clear()+ assembler.reset()+ stalledRounds = 0+ }+ val block = Rtcp.feedback(+ receiverSsrc = stream.receiverSsrc,+ senderSsrc = stream.senderSsrc,+ checkpoint = checkpoint,+ playoutDelayMs = playoutDelayMs,+ nacks = nacks,+ ackedFrames = ready.keys.map { FrameId(it) },+ )+ return if (needsKeyFrame) {+ Rtcp.compound(+ Rtcp.pictureLossIndicator(stream.receiverSsrc, stream.senderSsrc),+ block,+ )+ } else {+ block+ }+ }++ /** The sender's clock, when a datagram carries a report for this stream. */+ fun onSenderReport(datagram: ByteArray): SenderReport? =+ Rtcp.parseSenderReport(datagram, stream.senderSsrc)++ /**+ * A gap is blocking delivery while frames beyond it keep arriving.+ *+ * Counted in feedback rounds rather than milliseconds: the count only advances when feedback goes+ * out, so it measures "the sender has been told this three times and nothing came back", which is+ * the condition a key frame actually answers.+ */+ private fun isStalled(): Boolean {+ if (ready.isEmpty()) {+ stalledRounds = 0+ return false+ }+ stalledRounds+++ return stalledRounds > STALL_ROUNDS+ }++ /**+ * Release everything now deliverable, oldest first.+ *+ * Decryption happens here, once per frame, keyed by the frame id - which is why a frame can be+ * reassembled from packets that arrived in any order and still decrypt: the counter block comes+ * from the id, not from arrival order.+ */+ private fun drain(): List<DecodableFrame> {+ val out = mutableListOf<DecodableFrame>()+ while (true) {+ if (!synchronised) {+ // Wait for a key frame, then treat everything before it as never having existed.+ val key = ready.values.firstOrNull { it.isKeyFrame } ?: return out+ ready.keys.removeAll { it < key.frameId.value }+ checkpoint = key.frameId - 1+ assembler.discardUpTo(checkpoint)+ synchronised = true+ stalledRounds = 0+ }+ val next = checkpoint + 1+ val frame = ready.remove(next.value) ?: return out+ checkpoint = next+ framesDelivered+++ stalledRounds = 0+ assembler.discardUpTo(next)+ out += DecodableFrame(+ frameId = next,+ rtpTimestamp = frame.rtpTimestamp,+ isKeyFrame = frame.isKeyFrame,+ payload = crypto.crypt(next, frame.payload),+ )+ }+ }++ private companion object {+ /**+ * Three rounds at the sender's feedback cadence is comfortably longer than one round trip on+ * a LAN, so a NACK has genuinely had its chance before a key frame is demanded - and short+ * enough that a picture never freezes for a noticeable time.+ */+ const val STALL_ROUNDS = 3+ }+}
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Rtcp.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Rtcp.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Rtcp.ktnew file mode 100644index 0000000000..59d8ad487f--- /dev/null+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Rtcp.kt@@ -0,0 +1,498 @@+package com.vayunmathur.cast.protocol++/**+ * RTCP, both directions.+ *+ * The sender builds sender reports and parses feedback; the receiver builds feedback and parses+ * sender reports. Every builder here has its parser in the same file **on purpose** - that pairing+ * is what makes a disagreement about the wire format a failing unit test instead of a black screen+ * on a TV across the room.+ *+ * The layouts come from openscreen `cast/streaming/impl/rtcp_common.cc` (the common header),+ * `impl/sender_report_builder.cc` (the sender report) and `impl/compound_rtcp_parser.cc`+ * (`ParseFeedback`, the ACK/NACK). The wire diagrams are in `impl/rtp_defines.h`.+ *+ * Getting this wrong does not look like an error: the picture renders and then freezes, because+ * without sender reports the receiver has no clock to schedule against, and without feedback+ * nothing is ever retransmitted.+ */+object Rtcp {++ /** Version 2, no padding, in the top three bits of byte 0. */+ private const val VERSION_AND_PADDING = 0b100 shl 5++ /** `RtcpPacketType` values. */+ private const val TYPE_SENDER_REPORT = 200++ /**+ * `kPayloadSpecific`. **This**, not the application-defined 204, is what carries feedback:+ * `CompoundRtcpParser::Parse` dispatches `kFeedback` and `kPictureLossIndicator` from 206, and+ * uses 204 only for receiver log messages.+ */+ private const val TYPE_PAYLOAD_SPECIFIC = 206++ /** `RtcpSubtype` values, carried in the low five bits of byte 0. */+ private const val SUBTYPE_PICTURE_LOSS_INDICATOR = 1+ private const val SUBTYPE_FEEDBACK = 15++ private const val COMMON_HEADER_SIZE = 4++ /** `kRtcpSenderReportSize`, excluding the 4-byte common header. */+ private const val SENDER_REPORT_SIZE = 24++ /** `'CAST'` and `'CST2'` as big-endian ASCII words. */+ private const val CAST_WORD = 0x43_41_53_54L+ private const val CST2_WORD = 0x43_53_54_32L++ private const val FEEDBACK_HEADER_SIZE = 16+ private const val FEEDBACK_ACK_HEADER_SIZE = 6+ private const val LOSS_FIELD_SIZE = 4++ /** `kAllPacketsLost` - a NACK for a whole frame rather than for one packet. */+ const val ALL_PACKETS_LOST = 0xffff++ /**+ * How many loss fields one feedback packet may carry.+ *+ * The wire allows 255, but a receiver in a bad moment can be missing far more than that, and a+ * NACK list long enough to fragment the datagram makes the loss worse rather than better. The+ * frames nearest the checkpoint are the ones blocking playout, so those are the ones that fit.+ */+ const val MAX_LOSS_FIELDS = 32++ // ---- sender -> receiver ----++ /**+ * A sender report: our clock, and how much we have sent.+ *+ * [ntpTimestamp] is the 64-bit NTP form of the moment [rtpTimestamp] was captured; the pair is+ * what lets the receiver relate our media clock to wall time.+ */+ fun senderReport(+ senderSsrc: Long,+ ntpTimestamp: Long,+ rtpTimestamp: Long,+ packetCount: Long,+ octetCount: Long,+ ): ByteArray {+ val out = ByteArray(COMMON_HEADER_SIZE + SENDER_REPORT_SIZE)+ var i = 0+ out[i++] = VERSION_AND_PADDING.toByte() // report_count = 0: we send no report blocks+ out[i++] = TYPE_SENDER_REPORT.toByte()+ // The length field counts 32-bit words *after* the first, which is what dividing by 4+ // without adding one expresses.+ i = out.putShort(i, SENDER_REPORT_SIZE / 4)+ i = out.putInt(i, senderSsrc and 0xffff_ffffL)+ i = out.putInt(i, (ntpTimestamp ushr 32) and 0xffff_ffffL)+ i = out.putInt(i, ntpTimestamp and 0xffff_ffffL)+ i = out.putInt(i, rtpTimestamp and 0xffff_ffffL)+ i = out.putInt(i, packetCount and 0xffff_ffffL)+ out.putInt(i, octetCount and 0xffff_ffffL)+ return out+ }++ /**+ * The receiver's half of [senderReport].+ *+ * Walks the compound datagram rather than reading only the first sub-packet, for the same+ * reason [parse] does. Returns null when nothing in it is a sender report for [senderSsrc].+ */+ fun parseSenderReport(packet: ByteArray, senderSsrc: Long): SenderReport? {+ forEachSubPacket(packet) { type, _, start, size ->+ if (type == TYPE_SENDER_REPORT && size >= SENDER_REPORT_SIZE) {+ if (packet.getInt(start) == senderSsrc and 0xffff_ffffL) {+ return SenderReport(+ ntpTimestamp = (packet.getInt(start + 4) shl 32) or packet.getInt(start + 8),+ rtpTimestamp = packet.getInt(start + 12),+ packetCount = packet.getInt(start + 16),+ octetCount = packet.getInt(start + 20),+ )+ }+ }+ }+ return null+ }++ // ---- receiver -> sender ----++ /**+ * The feedback [parse] reads: what the receiver has, and what it is missing.+ *+ * [nacks] is a flat list of individual missing packets; coalescing them into loss fields and+ * their 8-bit follow-on vectors happens here, so a caller never has to know that the wire has a+ * bit vector at all. [ackedFrames] must all be above [checkpoint], since everything up to it is+ * acknowledged by the checkpoint itself.+ */+ fun feedback(+ receiverSsrc: Long,+ senderSsrc: Long,+ checkpoint: FrameId,+ playoutDelayMs: Int,+ nacks: List<PacketNack> = emptyList(),+ ackedFrames: List<FrameId> = emptyList(),+ ): ByteArray {+ val lossFields = lossFields(nacks)+ val ackOctets = ackOctets(checkpoint, ackedFrames)+ val bodySize = FEEDBACK_HEADER_SIZE ++ LOSS_FIELD_SIZE * lossFields.size ++ if (ackOctets.isEmpty()) 0 else FEEDBACK_ACK_HEADER_SIZE + ackOctets.size+ // The length field counts whole 32-bit words, so the body is padded up to one.+ val padded = (bodySize + 3) / 4 * 4+ val out = ByteArray(COMMON_HEADER_SIZE + padded)+ var i = 0+ out[i++] = (VERSION_AND_PADDING or SUBTYPE_FEEDBACK).toByte()+ out[i++] = TYPE_PAYLOAD_SPECIFIC.toByte()+ i = out.putShort(i, padded / 4)+ i = out.putInt(i, receiverSsrc and 0xffff_ffffL)+ i = out.putInt(i, senderSsrc and 0xffff_ffffL)+ i = out.putInt(i, CAST_WORD)+ out[i++] = checkpoint.lower8.toByte()+ out[i++] = lossFields.size.toByte()+ i = out.putShort(i, playoutDelayMs)+ for (field in lossFields) {+ out[i++] = field.frameId.lower8.toByte()+ i = out.putShort(i, field.packetId)+ out[i++] = field.followingBits.toByte()+ }+ if (ackOctets.isNotEmpty()) {+ i = out.putInt(i, CST2_WORD)+ out[i++] = 0 // Feedback Count: openscreen sends a counter here; nothing reads it.+ out[i++] = ackOctets.size.toByte()+ for (octet in ackOctets) out[i++] = octet+ }+ return out+ }++ /**+ * "Send me a key frame": the receiver cannot decode anything it currently holds.+ *+ * A separate sub-packet rather than a flag on [feedback], because that is where+ * `CompoundRtcpParser` looks for it - and because it is the one message worth sending on its own+ * when there is no useful checkpoint to report yet.+ */+ fun pictureLossIndicator(receiverSsrc: Long, senderSsrc: Long): ByteArray {+ val out = ByteArray(COMMON_HEADER_SIZE + 8)+ var i = 0+ out[i++] = (VERSION_AND_PADDING or SUBTYPE_PICTURE_LOSS_INDICATOR).toByte()+ out[i++] = TYPE_PAYLOAD_SPECIFIC.toByte()+ i = out.putShort(i, 2)+ i = out.putInt(i, receiverSsrc and 0xffff_ffffL)+ out.putInt(i, senderSsrc and 0xffff_ffffL)+ return out+ }++ /**+ * Concatenate sub-packets into one datagram.+ *+ * RTCP is compound by design, and sending a PLI and a feedback block as two datagrams doubles+ * the chance of losing the one that mattered.+ */+ fun compound(vararg packets: ByteArray): ByteArray {+ val out = ByteArray(packets.sumOf { it.size })+ var offset = 0+ for (packet in packets) {+ packet.copyInto(out, offset)+ offset += packet.size+ }+ return out+ }++ /**+ * Turn individual missing packets into loss fields.+ *+ * Each field names one packet id and then carries eight bits for the eight ids after it, so a+ * run of loss inside one frame costs four bytes rather than four per packet. A whole-frame NACK+ * is one field with [ALL_PACKETS_LOST] and no vector, and it subsumes anything else for that+ * frame - which is also exactly how `StreamingSession` reads it back.+ */+ private fun lossFields(nacks: List<PacketNack>): List<LossField> {+ if (nacks.isEmpty()) return emptyList()+ val out = mutableListOf<LossField>()+ // Grouped and sorted so the frames closest to the checkpoint - the ones actually blocking+ // playout - are the ones that survive MAX_LOSS_FIELDS.+ val byFrame = nacks.groupBy { it.frameId }.toSortedMap()+ for ((frameId, forFrame) in byFrame) {+ if (out.size >= MAX_LOSS_FIELDS) break+ if (forFrame.any { it.isWholeFrame }) {+ out += LossField(frameId, ALL_PACKETS_LOST, 0)+ continue+ }+ val ids = forFrame.map { it.packetId }.distinct().sorted()+ var index = 0+ while (index < ids.size && out.size < MAX_LOSS_FIELDS) {+ val base = ids[index]+ var bits = 0+ var next = index + 1+ while (next < ids.size && ids[next] - base <= 8) {+ bits = bits or (1 shl (ids[next] - base - 1))+ next+++ }+ out += LossField(frameId, base, bits)+ index = next+ }+ }+ return out+ }++ /**+ * The CST2 frame-ACK bit vector.+ *+ * Bit *i* of octet *j* is frame `checkpoint + 2 + 8*j + i`: the "plus two" is openscreen's,+ * documented in `rtp_defines.h`, because the checkpoint frame is implicitly acked and the vector+ * begins beyond the frame following it.+ */+ private fun ackOctets(checkpoint: FrameId, ackedFrames: List<FrameId>): ByteArray {+ val offsets = ackedFrames+ .map { it - checkpoint - 2 }+ // The vector's length is written into a single byte, so a frame further ahead than it can+ // reach simply is not acked. Nothing is lost by that: an ack is an optimisation, and the+ // checkpoint already says everything that has definitely been played.+ .filter { it in 0 until MAX_ACK_OCTETS * 8 }+ val highest = offsets.maxOrNull() ?: return ByteArray(0)+ val out = ByteArray((highest / 8 + 1).toInt())+ for (offset in offsets) {+ val octet = (offset / 8).toInt()+ val bit = (offset % 8).toInt()+ out[octet] = (out[octet].toInt() or (1 shl bit)).toByte()+ }+ return out+ }++ /** The ACK bit vector's length field is one byte. */+ private const val MAX_ACK_OCTETS = 255++ private data class LossField(val frameId: FrameId, val packetId: Int, val followingBits: Int)++ // ---- parsing feedback (the sender's side) ----++ /**+ * Parse a datagram of RTCP from the receiver.+ *+ * **RTCP is compound**: one datagram is the concatenation of several RTCP packets, so reading+ * only the first sub-packet finds feedback essentially never - which looks exactly like a+ * receiver that is not talking to us at all.+ *+ * [maxFrameId] is the highest frame we have sent; the checkpoint arrives truncated to 8 bits+ * and is expanded against it, exactly as `ExpandLessThanOrEqual` does. Without that the+ * checkpoint would appear to jump backwards every 256 frames.+ *+ * Returns null when the datagram contains nothing addressed to this stream.+ */+ fun parse(+ packet: ByteArray,+ receiverSsrc: Long,+ senderSsrc: Long,+ maxFrameId: FrameId,+ ): ReceiverFeedback? {+ var feedback: ReceiverFeedback? = null+ var pictureLoss = false+ forEachSubPacket(packet) { type, countOrSubtype, start, size ->+ if (type == TYPE_PAYLOAD_SPECIFIC) {+ when (countOrSubtype) {+ SUBTYPE_FEEDBACK -> parseFeedbackPayload(+ packet,+ start,+ size,+ receiverSsrc,+ senderSsrc,+ maxFrameId,+ )?.let { feedback = it }+ SUBTYPE_PICTURE_LOSS_INDICATOR -> pictureLoss = true+ }+ }+ }+ val parsed = feedback+ return when {+ parsed != null -> parsed.copy(pictureLoss = parsed.pictureLoss || pictureLoss)+ // A bare PLI with no feedback block still has to reach the encoder.+ pictureLoss -> ReceiverFeedback(+ checkpoint = maxFrameId,+ playoutDelayMs = 0,+ nacks = emptyList(),+ ackedFrames = emptyList(),+ pictureLoss = true,+ )+ else -> null+ }+ }++ /**+ * Walk a compound datagram, calling [block] with each sub-packet's type, count-or-subtype+ * nibble, payload offset and payload size.+ *+ * Stops at the first byte that is not a valid common header rather than throwing: trailing+ * padding and sub-packet types we know nothing about both end up here.+ */+ private inline fun forEachSubPacket(+ packet: ByteArray,+ block: (type: Int, countOrSubtype: Int, start: Int, size: Int) -> Unit,+ ) {+ var offset = 0+ while (offset + COMMON_HEADER_SIZE <= packet.size) {+ val byte0 = packet[offset].toInt() and 0xff+ if (byte0 and 0b1110_0000 != VERSION_AND_PADDING) return+ val countOrSubtype = byte0 and 0b0001_1111+ val type = packet[offset + 1].toInt() and 0xff+ val payloadSize = packet.getShort(offset + 2) * 4+ val payloadStart = offset + COMMON_HEADER_SIZE+ if (payloadStart + payloadSize > packet.size) return+ block(type, countOrSubtype, payloadStart, payloadSize)+ offset = payloadStart + payloadSize+ }+ }++ /**+ * One `kFeedback` payload, i.e. the bytes after its 4-byte common header.+ *+ * Returns null when the SSRC pair names another stream, which is normal: a compound datagram+ * carries feedback for whichever stream the receiver is reporting on.+ */+ private fun parseFeedbackPayload(+ packet: ByteArray,+ start: Int,+ size: Int,+ receiverSsrc: Long,+ senderSsrc: Long,+ maxFrameId: FrameId,+ ): ReceiverFeedback? {+ if (size < FEEDBACK_HEADER_SIZE) return null+ val end = start + size+ var i = start+ if (packet.getInt(i) != receiverSsrc and 0xffff_ffffL) return null+ i += 4+ if (packet.getInt(i) != senderSsrc and 0xffff_ffffL) return null+ i += 4+ if (packet.getInt(i) != CAST_WORD) return null+ i += 4++ val checkpoint = expandLessThanOrEqual(maxFrameId, packet[i].toInt() and 0xff)+ i+++ val lossFieldCount = packet[i].toInt() and 0xff+ i+++ val playoutDelayMs = packet.getShort(i)+ i += 2++ if (end - i < LOSS_FIELD_SIZE * lossFieldCount) return null+ val nacks = mutableListOf<PacketNack>()+ repeat(lossFieldCount) {+ val frameId = expandGreaterThan(checkpoint, packet[i].toInt() and 0xff)+ i+++ var packetId = packet.getShort(i)+ i += 2+ var bits = packet[i].toInt() and 0xff+ i+++ nacks += PacketNack(frameId, packetId)+ if (packetId != ALL_PACKETS_LOST) {+ // Each set bit is another missing packet, counting up from packetId.+ while (bits != 0) {+ packetId+++ if (bits and 1 != 0) nacks += PacketNack(frameId, packetId)+ bits = bits ushr 1+ }+ }+ }++ // CST2 frame-level ACKs are optional, and openscreen deliberately tolerates trailing bytes+ // that are not 'CST2' rather than calling the packet corrupt.+ val acked = mutableListOf<FrameId>()+ if (end - i >= FEEDBACK_ACK_HEADER_SIZE && packet.getInt(i) == CST2_WORD) {+ i += 4+ i++ // Feedback Count, unused.+ val octets = packet[i].toInt() and 0xff+ i+++ if (end - i >= octets) {+ var frameId = checkpoint + 2+ repeat(octets) {+ var bits = packet[i].toInt() and 0xff+ var id = frameId+ while (bits != 0) {+ if (bits and 1 != 0) acked += id+ bits = bits ushr 1+ id += 1+ }+ i+++ frameId += 8+ }+ }+ }+ return ReceiverFeedback(checkpoint, playoutDelayMs, nacks, acked)+ }++ // ---- id expansion ----++ /**+ * Re-expand a truncated 8-bit id, knowing the result is at most [reference].+ *+ * openscreen `impl/expanded_value_base.h`, `ExpandLessThanOrEqual`.+ */+ internal fun expandLessThanOrEqual(reference: FrameId, truncated: Int): FrameId {+ val delta = (reference.lower8 - truncated) and 0xff+ return FrameId(reference.value - delta)+ }++ /** The mirror of the above, for an id known to be greater than [reference]. */+ internal fun expandGreaterThan(reference: FrameId, truncated: Int): FrameId {+ val delta = (truncated - reference.lower8) and 0xff+ return FrameId(reference.value + if (delta == 0) 256 else delta)+ }++ /**+ * Expand to whichever full id is *nearest* [reference], in either direction.+ *+ * `ExpandNearest`. This is the one the receiver needs: an arriving frame is usually just ahead+ * of the last one completed, but a retransmission is behind it, and neither of the one-sided+ * expansions above can produce both.+ */+ internal fun expandNearest(reference: FrameId, truncated: Int): FrameId {+ val delta = ((((truncated - reference.lower8) and 0xff) + 128) and 0xff) - 128+ return FrameId(reference.value + delta)+ }+}++/** One packet the receiver says it is missing. */+data class PacketNack(val frameId: FrameId, val packetId: Int) {+ val isWholeFrame: Boolean get() = packetId == Rtcp.ALL_PACKETS_LOST++ companion object {+ /** Nothing at all arrived for this frame, so every packet of it is missing. */+ fun wholeFrame(frameId: FrameId): PacketNack = PacketNack(frameId, Rtcp.ALL_PACKETS_LOST)+ }+}++/**+ * What the receiver told us.+ *+ * [checkpoint] is the highest frame it has completely received, so everything up to and including+ * it can be dropped from the retransmit buffer. [nacks] is what to resend.+ */+data class ReceiverFeedback(+ val checkpoint: FrameId,+ val playoutDelayMs: Int,+ val nacks: List<PacketNack>,+ val ackedFrames: List<FrameId>,+ /** The receiver sent a Picture Loss Indicator: it needs a key frame to decode anything. */+ val pictureLoss: Boolean = false,+)++/**+ * What the sender told us.+ *+ * The [ntpTimestamp]/[rtpTimestamp] pair is the only thing that relates the sender's media clock to+ * wall time, which is what a receiver needs to schedule playout rather than render as fast as+ * packets arrive.+ */+data class SenderReport(+ val ntpTimestamp: Long,+ val rtpTimestamp: Long,+ val packetCount: Long,+ val octetCount: Long,+)++internal fun ByteArray.getShort(offset: Int): Int =+ ((this[offset].toInt() and 0xff) shl 8) or (this[offset + 1].toInt() and 0xff)++internal fun ByteArray.getInt(offset: Int): Long =+ ((this[offset].toLong() and 0xff) shl 24) or+ ((this[offset + 1].toLong() and 0xff) shl 16) or+ ((this[offset + 2].toLong() and 0xff) shl 8) or+ (this[offset + 3].toLong() and 0xff)
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/RtpDepacketizer.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/RtpDepacketizer.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/RtpDepacketizer.ktnew file mode 100644index 0000000000..e537f61fab--- /dev/null+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/RtpDepacketizer.kt@@ -0,0 +1,110 @@+package com.vayunmathur.cast.protocol++/**+ * One parsed RTP packet: the header fields, and this packet's slice of the frame.+ *+ * [frameId8] and [referenceFrameId8] are the **truncated** ids straight off the wire. Expanding+ * them needs a reference point the packet itself does not carry, so that is [FrameAssembler]'s job+ * rather than this one's - a depacketizer that guessed would be the same class of bug as reading+ * the frame counter as a byte.+ */+data class RtpPacket(+ val payloadType: Int,+ val sequenceNumber: Int,+ /** Set on the last packet of a frame. Redundant with [packetId] == [maxPacketId], and checked. */+ val marker: Boolean,+ val rtpTimestamp: Long,+ val ssrc: Long,+ val isKeyFrame: Boolean,+ val frameId8: Int,+ val packetId: Int,+ val maxPacketId: Int,+ val referenceFrameId8: Int,+ val payload: ByteArray,+) {+ val packetCount: Int get() = maxPacketId + 1++ override fun equals(other: Any?): Boolean =+ other is RtpPacket &&+ payloadType == other.payloadType &&+ sequenceNumber == other.sequenceNumber &&+ marker == other.marker &&+ rtpTimestamp == other.rtpTimestamp &&+ ssrc == other.ssrc &&+ isKeyFrame == other.isKeyFrame &&+ frameId8 == other.frameId8 &&+ packetId == other.packetId &&+ maxPacketId == other.maxPacketId &&+ referenceFrameId8 == other.referenceFrameId8 &&+ payload.contentEquals(other.payload)++ override fun hashCode(): Int {+ var result = payloadType+ result = 31 * result + sequenceNumber+ result = 31 * result + marker.hashCode()+ result = 31 * result + rtpTimestamp.hashCode()+ result = 31 * result + ssrc.hashCode()+ result = 31 * result + isKeyFrame.hashCode()+ result = 31 * result + frameId8+ result = 31 * result + packetId+ result = 31 * result + maxPacketId+ result = 31 * result + referenceFrameId8+ result = 31 * result + payload.contentHashCode()+ return result+ }+}++/**+ * The exact inverse of [RtpPacketizer]: bytes off the socket back into header fields and a payload+ * slice.+ *+ * Every rejection below is a shape [RtpPacketizer] cannot produce, which is the whole reason this+ * can afford to be strict where a Cast receiver could not. A malformed datagram is dropped by+ * returning null rather than throwing: UDP is open to anything on the LAN, and a stray packet must+ * cost one branch rather than an exception per datagram.+ */+object RtpDepacketizer {++ fun parse(packet: ByteArray): RtpPacket? {+ if (packet.size < BASE_HEADER_SIZE) return null++ val byte0 = packet[0].toInt() and 0xff+ // Version 2, no padding, no extension, no CSRCs - `kRtpRequiredFirstByte`. Padding and+ // header extensions would change where the payload starts, and we never write either.+ if (byte0 != 0b1000_0000) return null++ val byte1 = packet[1].toInt() and 0xff+ val marker = byte1 and RTP_MARKER_BIT != 0+ val payloadType = byte1 and 0b0111_1111++ val castByte = packet[12].toInt() and 0xff+ val isKeyFrame = castByte and CAST_KEY_FRAME_BIT != 0+ // The reference frame id is what makes the header 19 bytes rather than 18. Our packetizer+ // always writes it, so a packet without it did not come from us.+ if (castByte and CAST_HAS_REFERENCE_FRAME_ID_BIT == 0) return null+ // Extension count. We never emit the adaptive-latency extension, so anything here would+ // shift the payload by an amount this parser has no rule for.+ if (castByte and 0b0011_1111 != 0) return null++ val packetId = packet.getShort(14)+ val maxPacketId = packet.getShort(16)+ if (packetId > maxPacketId) return null+ // The marker bit and the packet ids have to agree; disagreeing means corruption, and+ // trusting one over the other is how a frame ends up assembled from the wrong pieces.+ if (marker != (packetId == maxPacketId)) return null++ return RtpPacket(+ payloadType = payloadType,+ sequenceNumber = packet.getShort(2),+ marker = marker,+ rtpTimestamp = packet.getInt(4),+ ssrc = packet.getInt(8),+ isKeyFrame = isKeyFrame,+ frameId8 = packet[13].toInt() and 0xff,+ packetId = packetId,+ maxPacketId = maxPacketId,+ referenceFrameId8 = packet[18].toInt() and 0xff,+ payload = packet.copyOfRange(BASE_HEADER_SIZE, packet.size),+ )+ }+}
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/RtpPacketizer.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/domain/streaming/CastRtpPacketizer.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/RtpPacketizer.ktsimilarity index 78%rename from cast/src/main/java/com/vayunmathur/cast/domain/streaming/CastRtpPacketizer.ktrename to cast/protocol/src/main/java/com/vayunmathur/cast/protocol/RtpPacketizer.ktindex 59961306e1..58f3cf695d 100644--- a/cast/src/main/java/com/vayunmathur/cast/domain/streaming/CastRtpPacketizer.kt+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/RtpPacketizer.kt@@ -1,4 +1,4 @@-package com.vayunmathur.cast.domain.streaming+package com.vayunmathur.cast.protocol /** * The largest UDP payload that fits an Ethernet frame without fragmenting:@@ -10,7 +10,7 @@ const val MAX_RTP_PACKET_SIZE = 1500 - 20 - 8 * RTP header (12) + Cast header (7). `kBaseRtpHeaderSize`, which openscreen writes as * `kRtpPacketMinValidSize + 1` because this implementation always includes the reference frame id. */-private const val BASE_HEADER_SIZE = 19+const val BASE_HEADER_SIZE = 19 /** `kAdaptiveLatencyHeaderSize`. Reserved even when unused, as openscreen reserves it. */ private const val ADAPTIVE_LATENCY_HEADER_SIZE = 4@@ -20,11 +20,17 @@ private const val MAX_HEADER_SIZE = BASE_HEADER_SIZE + ADAPTIVE_LATENCY_HEADER_S /** `kRtpRequiredFirstByte` - version 2, no padding, no extension, no CSRCs. */ private const val RTP_FIRST_BYTE = 0b1000_0000 -private const val RTP_MARKER_BIT = 0b1000_0000-private const val CAST_KEY_FRAME_BIT = 0b1000_0000-private const val CAST_HAS_REFERENCE_FRAME_ID_BIT = 0b0100_0000+internal const val RTP_MARKER_BIT = 0b1000_0000+internal const val CAST_KEY_FRAME_BIT = 0b1000_0000+internal const val CAST_HAS_REFERENCE_FRAME_ID_BIT = 0b0100_0000 -/** One encoded, already-encrypted frame, ready to be split into packets. */+/**+ * One encoded, already-encrypted frame - either about to be split into packets, or just+ * reassembled from them.+ *+ * The same type on both ends deliberately: [RtpPacketizer] turns one of these into packets and+ * [FrameAssembler] turns packets back into one, so the round-trip assertion is a single `==`.+ */ data class EncryptedFrame( val frameId: FrameId, val referencedFrameId: FrameId,@@ -51,10 +57,10 @@ data class EncryptedFrame( } /**- * Splits an encrypted frame into Cast RTP packets.+ * Splits an encrypted frame into RTP packets. *- * Wire format from openscreen `cast/streaming/impl/rtp_packetizer.cc` (`GeneratePacket`), with the- * field diagram in `impl/rtp_defines.h`:+ * The wire format is openscreen's `cast/streaming/impl/rtp_packetizer.cc` (`GeneratePacket`), with+ * the field diagram in `impl/rtp_defines.h`: * * ``` * 0 1 2 3@@ -66,14 +72,19 @@ data class EncryptedFrame( * | max packet id | reference frame id | * ``` *+ * **Kept byte-identical to Cast Streaming even though nothing requires it any more.** Both ends of+ * this protocol are ours, so the format is now only a choice - but it is a written, golden-byte+ * tested choice with a matching depacketizer, and inventing a second one would buy nothing.+ * * The sequence number starts at a random value: openscreen says the reason is unclear but that * every implementation has done it for years, so it is copied rather than rationalised. *- * The adaptive-latency extension is not emitted - it only carries a mid-stream playout-delay- * change, which nothing here asks for - but its 4 bytes stay reserved so the payload size matches- * openscreen's and a frame never has to be re-split.+ * The adaptive-latency extension is never emitted - it only carries a mid-stream playout-delay+ * change, which nothing here asks for - but its 4 bytes stay reserved so a frame never has to be+ * re-split. [RtpDepacketizer] refuses a packet that does declare extensions, since we never write+ * one and a peer that did would not be us. */-class CastRtpPacketizer(+class RtpPacketizer( private val payloadType: Int, private val senderSsrc: Long, private val maxPacketSize: Int = MAX_RTP_PACKET_SIZE,
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/SecretSealing.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/SecretSealing.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/SecretSealing.ktnew file mode 100644index 0000000000..abd72a2c01--- /dev/null+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/SecretSealing.kt@@ -0,0 +1,35 @@+package com.vayunmathur.cast.protocol++import com.vayunmathur.e2ee.Pqc+import com.vayunmathur.e2ee.PqcIdentity++/**+ * Getting the session secret to the TV, and nothing else.+ *+ * Isolated in its own file because it is the only thing in `:cast:protocol` that reaches native+ * code: `Pqc` is backed by a Rust `.so` (fips203 ML-KEM-768), so anything that touches it cannot run+ * in a host unit test. Every rule that *can* be tested on the JVM - the key schedule, the pairing+ * proofs, the framing, the whole media round trip - is therefore kept out of here.+ *+ * `Pqc.encryptTo` is used exactly as written, which is the point: it already does ML-KEM+ * encapsulation followed by AES-256-GCM under the encapsulated secret, so there is no raw KEM+ * plumbing to get wrong here. The TV's half is `PqcIdentity.decrypt`.+ */+object SecretSealing {++ /** Seal [secret] to a TV's public bundle. Only that TV's ML-KEM private key can open it. */+ fun seal(publicBundle: ByteArray, secret: ByteArray): ByteArray =+ Pqc.encryptTo(publicBundle, secret)++ /**+ * Open a sealed secret with this TV's identity, or null when it was not sealed to us.+ *+ * Null rather than an exception because a phone that sealed to a stale bundle - one from before+ * a factory reset - is a routine outcome, and the answer is to close the session and let it+ * re-read the identity.+ */+ fun open(identity: PqcIdentity, sealed: ByteArray): ByteArray? =+ runCatching { identity.decrypt(sealed) }+ .getOrNull()+ ?.takeIf { it.size == SessionKeys.SECRET_BYTES }+}
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/StreamingSession.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/StreamingSession.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/StreamingSession.ktnew file mode 100644index 0000000000..ac00d823b3--- /dev/null+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/StreamingSession.kt@@ -0,0 +1,101 @@+package com.vayunmathur.cast.protocol++/**+ * The sender's loss-recovery state machine, with no I/O.+ *+ * Kept free of sockets and encoders because recovery is the part with the subtle rules, and this way+ * every one of them is a JVM unit test. [ReceiverSession] is its mirror image on the TV.+ *+ * Smaller than it used to be: OFFER/ANSWER negotiation lived here when the peer was a Cast receiver+ * and had to be asked what it would accept. The handshake settles that now, so what is left is the+ * one thing feedback is actually for - deciding what to resend.+ */+class StreamingSession {++ /**+ * Frames we may still be asked to resend, newest last.+ *+ * Bounded, because a receiver that stops sending feedback must not be able to make the sender+ * grow without limit. Dropping the oldest is right: a NACK for a frame we no longer hold is+ * answered by the next key frame anyway.+ */+ private val retransmitBuffer = LinkedHashMap<Long, EncryptedFrame>()++ /** Remember a frame in case it has to be resent. */+ fun record(frame: EncryptedFrame) {+ retransmitBuffer[frame.frameId.value] = frame+ while (retransmitBuffer.size > RETRANSMIT_BUFFER_FRAMES) {+ val oldest = retransmitBuffer.keys.first()+ retransmitBuffer.remove(oldest)+ }+ }++ /**+ * What to do about one feedback packet.+ *+ * Everything up to the checkpoint is forgotten, then the NACKs are turned into frames to+ * resend. A NACK naming a frame that has already been dropped cannot be answered, so it asks+ * for a key frame instead - which is the only thing that lets a receiver recover without the+ * exact bytes it missed.+ */+ fun onFeedback(feedback: ReceiverFeedback): Recovery {+ retransmitBuffer.keys.removeAll { it <= feedback.checkpoint.value }+ val resend = mutableListOf<Retransmission>()+ var needKeyFrame = false+ for (nack in feedback.nacks) {+ val frame = retransmitBuffer[nack.frameId.value]+ if (frame == null) {+ // Either already acknowledged and dropped, or older than the buffer. Only the+ // second case needs a key frame, and telling them apart is not worth the state:+ // asking for one when it was not needed costs a single extra key frame.+ if (nack.frameId > feedback.checkpoint) needKeyFrame = true+ continue+ }+ resend += if (nack.isWholeFrame) {+ Retransmission(frame, packetIds = null)+ } else {+ Retransmission(frame, packetIds = listOf(nack.packetId))+ }+ }+ return Recovery(mergePacketIds(resend), needKeyFrame)+ }++ /** A single frame's worth of NACKs, coalesced. */+ private fun mergePacketIds(items: List<Retransmission>): List<Retransmission> {+ if (items.size <= 1) return items+ val byFrame = LinkedHashMap<Long, Retransmission>()+ for (item in items) {+ val key = item.frame.frameId.value+ val existing = byFrame[key]+ byFrame[key] = when {+ existing == null -> item+ // A whole-frame NACK subsumes any individual packet ids for that frame.+ existing.packetIds == null || item.packetIds == null ->+ Retransmission(item.frame, packetIds = null)+ else -> Retransmission(+ item.frame,+ (existing.packetIds + item.packetIds).distinct().sorted(),+ )+ }+ }+ return byFrame.values.toList()+ }++ private companion object {+ /**+ * Two seconds of video at 30 fps. Comfortably more than the target playout delay a NACK+ * could reasonably refer to, and bounded so a silent receiver cannot grow the heap.+ */+ const val RETRANSMIT_BUFFER_FRAMES = 60+ }+}++/** One frame to resend; [packetIds] null means every packet of it. */+data class Retransmission(val frame: EncryptedFrame, val packetIds: List<Int>?)++/** What the sender should do in response to feedback. */+data class Recovery(+ val retransmissions: List<Retransmission>,+ /** True when a receiver has fallen behind further than the buffer can repair. */+ val needsKeyFrame: Boolean,+)
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Streams.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Streams.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Streams.ktnew file mode 100644index 0000000000..6f1593fe9a--- /dev/null+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Streams.kt@@ -0,0 +1,127 @@+package com.vayunmathur.cast.protocol++/** Which half of the stream a packet belongs to. */+enum class StreamKind { Audio, Video }++/**+ * Fixed parameters both ends agree on without negotiating them.+ *+ * These are the values that used to travel in the Cast OFFER, kept because they are still real+ * constraints - the Opus timebase has to match what `AudioEncoder` produces, and the payload types+ * have to match what the depacketizer routes on - just no longer things a peer gets a say in.+ */+object StreamConstants {++ /** The RTP payload type that marks each half of the stream. Ours to choose; these are Cast's. */+ const val AUDIO_PAYLOAD_TYPE = 127+ const val VIDEO_PAYLOAD_TYPE = 96++ /** Video RTP timestamps are 90 kHz, by long convention rather than by necessity. */+ const val VIDEO_TIMEBASE = 90_000++ /** Audio is timestamped in samples, so the timebase *is* the sample rate. */+ const val AUDIO_TIMEBASE = 48_000++ const val AUDIO_CHANNELS = 2+ const val AUDIO_BITRATE = 128_000++ const val VIDEO_MAX_FRAME_RATE = 30++ /**+ * How long the receiver buffers before playing, in ms.+ *+ * `kDefaultTargetPlayoutDelay` from openscreen. It is the budget a retransmission has to arrive+ * within to still be useful, which is why the sender's retransmit buffer is sized against it.+ */+ const val TARGET_DELAY_MS = 400++ /**+ * SSRC ranges from openscreen `cast/streaming/ssrc.cc`. Audio is "high priority" and video is+ * "normal"; the ranges are arbitrary but keeping them apart means an SSRC alone says which+ * stream a stray datagram was meant for.+ */+ const val AUDIO_SSRC_MIN = 1+ const val AUDIO_SSRC_MAX = 50_000+ const val VIDEO_SSRC_MIN = 50_001+ const val VIDEO_SSRC_MAX = 100_000+}++/**+ * The AES-128 key and the IV mask for one stream.+ *+ * Per-stream and never shared: audio and video are independent frame-id sequences, so one key+ * across both would reuse a counter block for two different plaintexts.+ */+class StreamKeys(val key: ByteArray, val ivMask: ByteArray) {+ // Arrays, so a generated equals would compare identity. Content comparison is what a test+ // asserting the two ends derived the same schedule means.+ override fun equals(other: Any?): Boolean =+ other is StreamKeys && key.contentEquals(other.key) && ivMask.contentEquals(other.ivMask)++ override fun hashCode(): Int = 31 * key.contentHashCode() + ivMask.contentHashCode()+}++/**+ * One agreed stream: whose SSRC is whose, and what to encrypt with.+ *+ * Both SSRCs are carried rather than derived. The sender picks its own in `STREAM_CONFIG` and the+ * receiver picks its own in `STREAM_READY`, so neither end may assume anything about the other's -+ * the pair is what identifies a stream in every RTCP packet.+ */+data class NegotiatedStream(+ val kind: StreamKind,+ val senderSsrc: Long,+ val receiverSsrc: Long,+ val payloadType: Int,+ val timebase: Int,+ val keys: StreamKeys,+)++/** Everything the handshake settled about the media flow. */+data class Negotiation(+ val udpPort: Int,+ val streams: List<NegotiatedStream>,+) {+ val audio: NegotiatedStream? get() = streams.firstOrNull { it.kind == StreamKind.Audio }+ val video: NegotiatedStream? get() = streams.firstOrNull { it.kind == StreamKind.Video }+ val hasVideo: Boolean get() = video != null++ companion object {+ /**+ * Build the routes both ends will use, from the two halves of the handshake.+ *+ * Called on the sender *and* the receiver with the same three inputs, which is the point:+ * the keys are derived rather than sent, so if either end computed a different schedule the+ * picture would be noise. A round-trip test asserts the two agree.+ */+ fun of(config: StreamConfig, ready: StreamReady, keys: SessionKeys): Negotiation {+ val streams = buildList {+ if (config.audio) {+ add(+ NegotiatedStream(+ kind = StreamKind.Audio,+ senderSsrc = config.audioSsrc,+ receiverSsrc = ready.audioSsrc,+ payloadType = StreamConstants.AUDIO_PAYLOAD_TYPE,+ timebase = StreamConstants.AUDIO_TIMEBASE,+ keys = keys.audio,+ ),+ )+ }+ if (config.video) {+ add(+ NegotiatedStream(+ kind = StreamKind.Video,+ senderSsrc = config.videoSsrc,+ receiverSsrc = ready.videoSsrc,+ payloadType = StreamConstants.VIDEO_PAYLOAD_TYPE,+ timebase = StreamConstants.VIDEO_TIMEBASE,+ keys = keys.video,+ ),+ )+ }+ }+ return Negotiation(ready.udpPort, streams)+ }+ }+}
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/CryptoTest.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastCryptoTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/CryptoTest.ktsimilarity index 89%rename from cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastCryptoTest.ktrename to cast/protocol/src/test/java/com/vayunmathur/cast/protocol/CryptoTest.ktindex c2d4a4d280..c9dbbcc0f8 100644--- a/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastCryptoTest.kt+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/CryptoTest.kt@@ -1,4 +1,4 @@-package com.vayunmathur.cast.domain.streaming+package com.vayunmathur.cast.protocol import javax.crypto.Cipher import javax.crypto.spec.SecretKeySpec@@ -9,7 +9,7 @@ import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue -class CastCryptoTest {+class CryptoTest { private val key = "000102030405060708090a0b0c0d0e0f".hex() private val mask = "101112131415161718191a1b1c1d1e1f".hex()@@ -19,7 +19,7 @@ class CastCryptoTest { // Hand-computed from FrameCrypto::Crypt: a zeroed block, the frame id's lower 32 bits // written big-endian at byte 8, then the whole block xored with the mask. Frame 1 differs // from the mask in exactly byte 11.- val crypto = CastCrypto(key, mask)+ val crypto = Crypto(key, mask) assertContentEquals(mask, crypto.ivForFrame(FrameId.First)) assertContentEquals( "101112131415161718191a1a1c1d1e1f".hex(),@@ -37,7 +37,7 @@ class CastCryptoTest { // The trap this file exists to catch. Frame 0 and frame 256 share a wire frame id, so an // implementation that derived the IV from the truncated value would reuse a keystream - // which with CTR leaks the xor of two frames outright.- val crypto = CastCrypto(key, mask)+ val crypto = Crypto(key, mask) assertEquals(FrameId.First.lower8, FrameId(256).lower8) assertFalse( crypto.ivForFrame(FrameId.First).contentEquals(crypto.ivForFrame(FrameId(256))),@@ -49,7 +49,7 @@ class CastCryptoTest { // Not a round-trip test: a wrong-but-symmetric implementation passes those. This builds // counter mode by hand out of the AES block cipher - incrementing the 16-byte counter and // xoring - and requires the Cipher-based path to agree byte for byte.- val crypto = CastCrypto(key, mask)+ val crypto = Crypto(key, mask) val frameId = FrameId(0x0000_1234) val plaintext = ByteArray(70) { it.toByte() } @@ -63,7 +63,7 @@ class CastCryptoTest { @Test fun `ctr is its own inverse`() {- val crypto = CastCrypto(key, mask)+ val crypto = Crypto(key, mask) val plaintext = "The quick brown fox jumps over the lazy dog.".toByteArray() val encrypted = crypto.crypt(FrameId(9), plaintext) assertContentEquals(plaintext, crypto.crypt(FrameId(9), encrypted))@@ -71,7 +71,7 @@ class CastCryptoTest { @Test fun `two frames with the same payload encrypt differently`() {- val crypto = CastCrypto(key, mask)+ val crypto = Crypto(key, mask) val payload = ByteArray(32) { 7 } assertFalse( crypto.crypt(FrameId.First, payload).contentEquals(crypto.crypt(FrameId(1), payload)),@@ -81,14 +81,14 @@ class CastCryptoTest { @Test fun `a key of the wrong length is refused rather than silently truncated`() { // AES-256 keys are what the rest of the repo uses, so handing one over is a live mistake.- assertFailsWith<IllegalArgumentException> { CastCrypto(ByteArray(32), mask) }- assertFailsWith<IllegalArgumentException> { CastCrypto(key, ByteArray(12)) }+ assertFailsWith<IllegalArgumentException> { Crypto(ByteArray(32), mask) }+ assertFailsWith<IllegalArgumentException> { Crypto(key, ByteArray(12)) } } @Test fun `an empty payload encrypts to nothing rather than throwing`() { // Some audio codecs emit zero bytes for silence, and the packetizer still sends a packet.- assertTrue(CastCrypto(key, mask).crypt(FrameId(3), ByteArray(0)).isEmpty())+ assertTrue(Crypto(key, mask).crypt(FrameId(3), ByteArray(0)).isEmpty()) } /** Counter mode assembled from the raw block cipher, as an independent oracle. */
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.ktnew file mode 100644index 0000000000..178edd1479--- /dev/null+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.kt@@ -0,0 +1,406 @@+package com.vayunmathur.cast.protocol++import java.io.ByteArrayInputStream+import java.io.DataInputStream+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * The control channel, from framing up to a paired session.+ *+ * Everything here runs on the JVM because the one part that cannot - sealing the secret to the TV's+ * ML-KEM bundle - is isolated in [SecretSealing] and takes no part in these rules. The secret is+ * therefore handed over directly, which is exactly what the real handshake produces anyway.+ */+class HandshakeTest {++ private val secret = ByteArray(SessionKeys.SECRET_BYTES) { (it * 5 + 1).toByte() }++ private val limits = DecoderLimits(+ maxWidth = 3840,+ maxHeight = 2160,+ maxFrameRate = 60,+ maxBitRate = 40_000_000,+ )++ // ---- framing ----++ @Test+ fun `a framed body reads back as the same bytes`() {+ val bodies = listOf(+ "hello".toByteArray(),+ ByteArray(1),+ ByteArray(70_000) { it.toByte() },+ )+ val stream = bodies.fold(ByteArray(0)) { acc, body -> acc + ControlFraming.encode(body) }+ val input = DataInputStream(ByteArrayInputStream(stream))+ for (expected in bodies) {+ assertContentEquals(expected, ControlFraming.read(input))+ }+ // Clean end of stream, not an exception.+ assertNull(ControlFraming.read(input))+ }++ @Test+ fun `an absurd length prefix is refused rather than allocated`() {+ // A stream cannot be resynchronised after one, so carrying on would read payload as length+ // for ever - and allocating what it asked for is a one-packet denial of service.+ val hostile = byteArrayOf(0x7f, -1, -1, -1)+ assertFailsWith<IllegalArgumentException> {+ ControlFraming.read(DataInputStream(ByteArrayInputStream(hostile)))+ }+ assertFailsWith<IllegalArgumentException> {+ ControlFraming.read(DataInputStream(ByteArrayInputStream(ByteArray(4))))+ }+ }++ // ---- message round trip ----++ @Test+ fun `every handshake message round-trips through the codec`() {+ val messages = listOf<ControlMessage>(+ Hello(senderName = "Pixel 9", senderId = "phone-1", paired = true),+ TvIdentity(+ receiverName = "Living Room TV",+ receiverId = "tv-1",+ publicBundle = ProtocolBase64.encode(ByteArray(2_400) { it.toByte() }),+ limits = limits,+ ),+ SealedSecret(sealed = ProtocolBase64.encode(ByteArray(1_200) { (-it).toByte() })),+ PairRequired(code = true, attemptsLeft = 3),+ PairRequired(code = false),+ PairProof(proof = ProtocolBase64.encode(ByteArray(32))),+ PairOk(deviceKey = ProtocolBase64.encode(ByteArray(32) { 9 })),+ PairOk(deviceKey = null),+ PairFailed(attemptsLeft = 2),+ StreamConfig(+ width = 1440,+ height = 3120,+ frameRate = 30,+ bitRate = 12_000_000,+ audio = true,+ video = true,+ audioSsrc = 1_234,+ videoSsrc = 50_002,+ ),+ StreamReady(udpPort = 47_505, audioSsrc = 4_321, videoSsrc = 50_009),+ Bye(reason = "user stopped"),+ )+ val codec = ControlCodec()+ for (message in messages) {+ assertEquals(message, codec.decode(codec.encode(message)), "$message did not round-trip")+ }+ }++ @Test+ fun `the discriminator is the type field, so the wire is readable`() {+ // Not cosmetic: a wire format nobody can read in a log is the reason five rounds of+ // debugging never found the packet that was wrong.+ val body = ControlCodec().encode(Bye("done")).toString(Charsets.UTF_8)+ assertTrue(body.contains("\"type\":\"BYE\""), body)+ }++ @Test+ fun `an absent device key stays absent rather than becoming null`() {+ val body = ControlCodec().encode(PairOk(deviceKey = null)).toString(Charsets.UTF_8)+ assertFalse(body.contains("deviceKey"), body)+ }++ @Test+ fun `a message from a newer build with extra fields still parses`() {+ val codec = ControlCodec()+ val withExtra = """{"type":"STREAM_READY","udpPort":9,"audioSsrc":1,"videoSsrc":2,"hdr":true}"""+ assertEquals(+ StreamReady(udpPort = 9, audioSsrc = 1, videoSsrc = 2),+ codec.decode(withExtra.toByteArray()),+ )+ }++ @Test+ fun `a type this build does not know decodes to null rather than throwing`() {+ assertNull(ControlCodec().decode("""{"type":"TELEPORT"}""".toByteArray()))+ assertNull(ControlCodec().decode("not json at all".toByteArray()))+ }++ // ---- encryption ----++ @Test+ fun `messages after the secret is established are encrypted and still round-trip`() {+ val keys = SessionKeys.of(secret)+ val sender = ControlCodec()+ val receiver = ControlCodec()+ assertFalse(sender.isEncrypting)+ sender.useSessionKey(keys.control)+ receiver.useSessionKey(keys.control)+ assertTrue(sender.isEncrypting)++ val message = StreamReady(udpPort = 47_505, audioSsrc = 1, videoSsrc = 2)+ val body = sender.encode(message)+ // Genuinely encrypted: the plaintext would have said so.+ assertFalse(body.toString(Charsets.UTF_8).contains("STREAM_READY"))+ assertEquals(message, receiver.decode(body))+ }++ @Test+ fun `a tampered control frame fails its tag rather than being accepted`() {+ // This is what stops unauthenticated media from being usable to hijack a session: the+ // control channel is AES-256-GCM, so a flipped bit closes the session.+ val keys = SessionKeys.of(secret)+ val codec = ControlCodec().apply { useSessionKey(keys.control) }+ val body = codec.encode(Bye("bye"))+ body[body.size - 1] = (body[body.size - 1].toInt() xor 1).toByte()+ assertNull(codec.decode(body))+ }++ @Test+ fun `a frame encrypted under another secret is refused`() {+ val mine = ControlCodec().apply { useSessionKey(SessionKeys.of(secret).control) }+ val theirs = ControlCodec().apply {+ useSessionKey(SessionKeys.of(ByteArray(SessionKeys.SECRET_BYTES) { 42 }).control)+ }+ assertNull(mine.decode(theirs.encode(Bye("hi"))))+ }++ // ---- key schedule ----++ @Test+ fun `both ends derive the same schedule from the same secret`() {+ // Keys are derived, never sent, so this is the only thing that makes the media decryptable+ // at all. A mismatch would show as a picture of pure noise with nothing logged anywhere.+ val phone = SessionKeys.of(secret)+ val tv = SessionKeys.of(secret.copyOf())+ assertContentEquals(phone.control, tv.control)+ assertEquals(phone.audio, tv.audio)+ assertEquals(phone.video, tv.video)+ }++ @Test+ fun `every derived key is distinct and correctly sized`() {+ val keys = SessionKeys.of(secret)+ assertEquals(32, keys.control.size)+ assertEquals(16, keys.audio.key.size)+ assertEquals(16, keys.audio.ivMask.size)+ // Audio and video are separate frame-id sequences, so a shared key would reuse a counter+ // block across two different plaintexts.+ assertFalse(keys.audio.key.contentEquals(keys.video.key))+ assertFalse(keys.audio.key.contentEquals(keys.audio.ivMask))+ assertFalse(keys.control.contentEquals(keys.audio.key + keys.audio.ivMask))+ }++ @Test+ fun `a secret of the wrong size is refused`() {+ assertFailsWith<IllegalArgumentException> { SessionKeys.of(ByteArray(16)) }+ }++ @Test+ fun `newSecret produces the documented length`() {+ assertEquals(SessionKeys.SECRET_BYTES, SessionKeys.newSecret().size)+ }++ // ---- pairing ----++ @Test+ fun `the right code pairs and yields a device key`() {+ val keys = SessionKeys.of(secret)+ val transcript = transcript()+ val gate = PairingGate { "123456" }+ val result = gate.verifyCode(keys, transcript, keys.pairProof("123456", transcript))+ val ok = assertIs<PairResult.Ok>(result)+ assertEquals(PairingGate.DEVICE_KEY_BYTES, assertNotNull(ok.deviceKey).size)+ }++ @Test+ fun `a wrong code fails without spending the whole allowance`() {+ val keys = SessionKeys.of(secret)+ val transcript = transcript()+ val gate = PairingGate { "123456" }+ val wrong = assertIs<PairResult.Wrong>(+ gate.verifyCode(keys, transcript, keys.pairProof("000000", transcript)),+ )+ assertEquals(PairCode.MAX_ATTEMPTS - 1, wrong.attemptsLeft)+ assertFalse(wrong.codeChanged)+ // The code is still the one on screen, so the user can simply try again.+ assertEquals("123456", gate.code)+ // And the right one still works afterwards.+ assertIs<PairResult.Ok>(gate.verifyCode(keys, transcript, keys.pairProof("123456", transcript)))+ }++ @Test+ fun `three wrong codes throw the code away and put a new one on screen`() {+ // The attempt limit is what makes six digits defensible, so it is a correctness boundary+ // rather than a nicety.+ val keys = SessionKeys.of(secret)+ val transcript = transcript()+ val codes = listOf("111111", "222222", "333333").iterator()+ val gate = PairingGate { codes.next() }+ assertEquals("111111", gate.code)+ val bad = keys.pairProof("999999", transcript)+ assertEquals(2, assertIs<PairResult.Wrong>(gate.verifyCode(keys, transcript, bad)).attemptsLeft)+ assertEquals(1, assertIs<PairResult.Wrong>(gate.verifyCode(keys, transcript, bad)).attemptsLeft)+ val third = assertIs<PairResult.Wrong>(gate.verifyCode(keys, transcript, bad))+ assertTrue(third.codeChanged)+ assertEquals(PairCode.MAX_ATTEMPTS, third.attemptsLeft)+ assertEquals("222222", gate.code)+ // The old code is worth nothing now, whatever the attacker learned about it.+ assertIs<PairResult.Wrong>(gate.verifyCode(keys, transcript, keys.pairProof("111111", transcript)))+ assertIs<PairResult.Ok>(gate.verifyCode(keys, transcript, keys.pairProof("222222", transcript)))+ }++ @Test+ fun `a proof for another transcript is refused, which is what defeats a man in the middle`() {+ // The whole reason six digits suffice. An attacker relaying the session substituted its own+ // public bundle, so its transcript differs from the one the user's code was proved against -+ // and it cannot produce a proof for a transcript it did not create.+ val keys = SessionKeys.of(secret)+ val gate = PairingGate { "424242" }+ val proofForOther = keys.pairProof("424242", transcript(bundle = "an attacker's bundle"))+ assertIs<PairResult.Wrong>(gate.verifyCode(keys, transcript(), proofForOther))+ }++ @Test+ fun `a remembered device pairs silently and with no attempt limit`() {+ val keys = SessionKeys.of(secret)+ val transcript = transcript()+ val deviceKey = PairingGate.newDeviceKey()+ val gate = PairingGate { "123456" }+ val ok = assertIs<PairResult.Ok>(+ gate.verifyDevice(keys, transcript, deviceKey, keys.deviceProof(deviceKey, transcript)),+ )+ // Nothing new to persist: the phone already holds the key it just proved.+ assertNull(ok.deviceKey)++ // A wrong device proof does not lock anything out - otherwise anyone on the LAN could deny+ // a paired phone access by sending rubbish.+ val wrongKey = PairingGate.newDeviceKey()+ assertIs<PairResult.Wrong>(+ gate.verifyDevice(keys, transcript, deviceKey, keys.deviceProof(wrongKey, transcript)),+ )+ assertEquals(PairCode.MAX_ATTEMPTS, gate.attemptsLeft)+ assertEquals("123456", gate.code)+ }++ @Test+ fun `every reply to a proof is one the sender knows how to read`() {+ // The desynchronisation this guards against: the receiver has three possible answers to a+ // PAIR_PROOF - accepted, wrong, or "I have forgotten you, here is a code" - and it must send+ // exactly one. A second message would sit in the phone's buffer and be read as the answer to+ // whatever it sent next, turning a recoverable reinstall into a dead session.+ val codec = ControlCodec()+ val replies = listOf<ControlMessage>(+ PairOk(deviceKey = ProtocolBase64.encode(ByteArray(32))),+ PairOk(deviceKey = null),+ PairFailed(attemptsLeft = 2, codeChanged = false),+ PairFailed(attemptsLeft = PairCode.MAX_ATTEMPTS, codeChanged = true),+ PairRequired(code = true, attemptsLeft = PairCode.MAX_ATTEMPTS),+ )+ for (reply in replies) {+ assertEquals(reply, codec.decode(codec.encode(reply)), "$reply did not round-trip")+ }+ // codeChanged is carried rather than inferred from a full allowance coming back, so the two+ // cases the phone renders differently are distinguishable even when the count matches.+ assertEquals(+ PairFailed(attemptsLeft = PairCode.MAX_ATTEMPTS, codeChanged = true),+ codec.decode(+ codec.encode(PairFailed(attemptsLeft = PairCode.MAX_ATTEMPTS, codeChanged = true)),+ ),+ )+ }++ @Test+ fun `a device proof is not a code proof`() {+ // Distinct HKDF labels, so a proof captured from one exchange cannot be replayed into the+ // other.+ val keys = SessionKeys.of(secret)+ val transcript = transcript()+ val deviceKey = ByteArray(32) { 3 }+ assertFalse(+ keys.deviceProof(deviceKey, transcript)+ .contentEquals(keys.pairProof(deviceKey.toString(Charsets.UTF_8), transcript)),+ )+ }++ @Test+ fun `a pair code is six digits, zero-padded`() {+ repeat(200) {+ val code = PairCode.random()+ assertEquals(PairCode.DIGITS, code.length)+ assertTrue(PairCode.isWellFormed(code), code)+ }+ assertTrue(PairCode.isWellFormed("000000"))+ assertFalse(PairCode.isWellFormed("12345"))+ assertFalse(PairCode.isWellFormed("1234567"))+ assertFalse(PairCode.isWellFormed("12345a"))+ }++ // ---- negotiation ----++ @Test+ fun `both ends build the same routes from the same handshake`() {+ val keys = SessionKeys.of(secret)+ val config = StreamConfig(+ width = 1440,+ height = 3120,+ frameRate = 30,+ bitRate = 12_000_000,+ audio = true,+ video = true,+ audioSsrc = 1_234,+ videoSsrc = 50_002,+ )+ val ready = StreamReady(udpPort = 47_505, audioSsrc = 4_321, videoSsrc = 50_009)+ val negotiation = Negotiation.of(config, ready, keys)+ assertEquals(47_505, negotiation.udpPort)+ assertEquals(2, negotiation.streams.size)+ assertTrue(negotiation.hasVideo)+ // Each end keeps its own SSRC and learns the other's; neither derives it.+ assertEquals(1_234L, assertNotNull(negotiation.audio).senderSsrc)+ assertEquals(4_321L, assertNotNull(negotiation.audio).receiverSsrc)+ assertEquals(50_002L, assertNotNull(negotiation.video).senderSsrc)+ assertEquals(50_009L, assertNotNull(negotiation.video).receiverSsrc)+ assertEquals(keys.video, assertNotNull(negotiation.video).keys)+ assertEquals(StreamConstants.AUDIO_TIMEBASE, assertNotNull(negotiation.audio).timebase)+ assertEquals(StreamConstants.VIDEO_TIMEBASE, assertNotNull(negotiation.video).timebase)++ // Audio-only, which is what a phone with no usable video encoder sends.+ val audioOnly = Negotiation.of(config.copy(video = false), ready, keys)+ assertFalse(audioOnly.hasVideo)+ assertEquals(1, audioOnly.streams.size)+ }++ // ---- transcript ----++ @Test+ fun `the transcript covers the bytes that crossed the wire, in order`() {+ assertContentEquals(transcript(), transcript())+ assertFalse(transcript().contentEquals(transcript(bundle = "other")))+ // Order matters: two ends that fed the same bodies in different orders have not agreed.+ val forward = Transcript().apply { add("a".toByteArray()); add("b".toByteArray()) }+ val backward = Transcript().apply { add("b".toByteArray()); add("a".toByteArray()) }+ assertFalse(forward.value().contentEquals(backward.value()))+ }++ private fun transcript(bundle: String = "the tv's real bundle"): ByteArray {+ val codec = ControlCodec()+ return Transcript().apply {+ add(codec.encode(Hello(senderName = "Pixel 9", senderId = "phone-1")))+ add(+ codec.encode(+ TvIdentity(+ receiverName = "Living Room TV",+ receiverId = "tv-1",+ publicBundle = ProtocolBase64.encode(bundle.toByteArray()),+ limits = limits,+ ),+ ),+ )+ add(codec.encode(SealedSecret(sealed = ProtocolBase64.encode(ByteArray(16)))))+ }.value()+ }+}
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaRoundTripTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaRoundTripTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaRoundTripTest.ktnew file mode 100644index 0000000000..ac95df069e--- /dev/null+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaRoundTripTest.kt@@ -0,0 +1,300 @@+package com.vayunmathur.cast.protocol++import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * **The suite the whole project rests on while there is no TV.**+ *+ * Every hardware bug that cost this project a session was the same shape: we inferred a format from+ * someone else's source, and a receiver we could not instrument silently refused the stream. Both+ * ends are ours now, so the equivalent question - "do the packetizer and the depacketizer agree?" -+ * is answerable here, in milliseconds, with no device involved.+ *+ * So the assertions are deliberately end-to-end rather than per-field: encrypt, packetize,+ * depacketize, reassemble, decrypt, and require the original bytes back. A wrong-but-symmetric+ * format would pass that, which is exactly the point - the format only has to be self-consistent+ * now, and [RtpPacketizerTest] still pins the bytes themselves.+ */+class MediaRoundTripTest {++ private val keys = StreamKeys(+ key = ByteArray(16) { (it * 7).toByte() },+ ivMask = ByteArray(16) { (it * 11 + 3).toByte() },+ )++ private val crypto = Crypto(keys.key, keys.ivMask)++ private fun packetizer(maxPacketSize: Int = MAX_RTP_PACKET_SIZE) =+ RtpPacketizer(+ StreamConstants.VIDEO_PAYLOAD_TYPE,+ SENDER_SSRC,+ maxPacketSize,+ sequenceNumberStart = 0x5f2a,+ )++ /** A frame as the sender would build it: encrypted payload, key frame referencing itself. */+ private fun frame(id: Long, size: Int, isKeyFrame: Boolean = id == 0L): EncryptedFrame {+ val plaintext = ByteArray(size) { ((it * 31 + id) and 0xff).toByte() }+ return EncryptedFrame(+ frameId = FrameId(id),+ referencedFrameId = if (isKeyFrame) FrameId(id) else FrameId(id - 1),+ rtpTimestamp = id * 3000,+ isKeyFrame = isKeyFrame,+ payload = crypto.crypt(FrameId(id), plaintext),+ )+ }++ private fun plaintextOf(id: Long, size: Int) = ByteArray(size) { ((it * 31 + id) and 0xff).toByte() }++ @Test+ fun `a single-packet frame survives the round trip byte for byte`() {+ val original = frame(id = 0, size = 40)+ val packets = packetizer().packetize(original)+ assertEquals(1, packets.size)+ val assembler = FrameAssembler()+ val assembled = assertNotNull(assembler.add(assertNotNull(RtpDepacketizer.parse(packets[0]))))+ assertEquals(original, assembled)+ assertContentEquals(plaintextOf(0, 40), crypto.crypt(assembled.frameId, assembled.payload))+ }++ @Test+ fun `a multi-packet frame reassembles in the right order`() {+ // 1080p key frames run to tens of packets; a frame that reassembles its chunks in the wrong+ // order decodes to garbage with no error anywhere, which is the failure this catches.+ val original = frame(id = 0, size = 120_000)+ val packets = packetizer().packetize(original)+ assertTrue(packets.size > 80, "expected a genuinely fragmented frame, got ${packets.size}")+ assertEquals(original, assemble(packets))+ }++ @Test+ fun `packets arriving in reverse order still reassemble`() {+ val original = frame(id = 0, size = 9_000)+ assertEquals(original, assemble(packetizer().packetize(original).reversed()))+ }++ @Test+ fun `packets arriving shuffled still reassemble`() {+ val original = frame(id = 0, size = 60_000)+ val shuffled = packetizer().packetize(original).shuffled(Random(20260821))+ assertEquals(original, assemble(shuffled))+ }++ @Test+ fun `duplicated packets are absorbed rather than corrupting the frame`() {+ // A retransmission of a packet that already arrived is the normal case, not an edge case:+ // the sender resends on a NACK it may already have answered.+ val original = frame(id = 0, size = 9_000)+ val packets = packetizer().packetize(original)+ val withDuplicates = packets + packets + packets.first()+ val assembler = FrameAssembler()+ var completed: EncryptedFrame? = null+ var completions = 0+ for (bytes in withDuplicates) {+ val frame = assembler.add(assertNotNull(RtpDepacketizer.parse(bytes)))+ if (frame != null) {+ completed = frame+ completions+++ }+ }+ assertEquals(1, completions, "a frame must only ever be emitted once")+ assertEquals(original, completed)+ }++ @Test+ fun `a lost packet leaves the frame incomplete until it is retransmitted`() {+ val original = frame(id = 0, size = 9_000)+ val packets = packetizer().packetize(original)+ val assembler = FrameAssembler()+ val dropped = packets.size / 2+ for ((index, bytes) in packets.withIndex()) {+ if (index == dropped) continue+ assertNull(+ assembler.add(assertNotNull(RtpDepacketizer.parse(bytes))),+ "the frame completed while a packet was still missing",+ )+ }+ // And the receiver can say exactly which packet it wants.+ assertEquals(+ listOf(PacketNack(FrameId(0), dropped)),+ assembler.missingPackets(after = FrameId.Leader),+ )+ val recovered = assembler.add(assertNotNull(RtpDepacketizer.parse(packets[dropped])))+ assertEquals(original, recovered)+ }++ @Test+ fun `frame ids round-trip across the eight-bit wrap`() {+ // The bug that would otherwise appear only after eight and a half seconds of mirroring: the+ // wire carries eight bits of a 64-bit counter, and an id expanded wrongly decrypts to noise+ // because the IV comes from the full value.+ val assembler = FrameAssembler()+ for (id in 0L..600L) {+ val original = frame(id = id, size = 500, isKeyFrame = id % 30 == 0L)+ val packets = packetizer().packetize(original)+ var assembled: EncryptedFrame? = null+ for (bytes in packets) {+ assembler.add(assertNotNull(RtpDepacketizer.parse(bytes)))?.let { assembled = it }+ }+ assertEquals(original, assembled, "frame $id did not survive")+ assertContentEquals(+ plaintextOf(id, 500),+ crypto.crypt(assertNotNull(assembled).frameId, assertNotNull(assembled).payload),+ "frame $id decrypted wrongly, which means its id was expanded wrongly",+ )+ assembler.discardUpTo(FrameId(id))+ }+ }++ @Test+ fun `an empty frame round-trips as an empty frame`() {+ // Opus encodes a silent period as zero bytes and the packetizer still emits one packet; a+ // receiver that dropped it would stall waiting for a frame that had in fact arrived.+ val original = frame(id = 0, size = 0)+ assertEquals(original, assemble(packetizer().packetize(original)))+ }++ @Test+ fun `a whole stream survives loss, reordering and retransmission`() {+ // The closest thing to a live session that runs without hardware: 200 frames over a lossy,+ // reordering link, with the sender answering NACKs from its retransmit buffer, and every+ // delivered frame required to be byte-identical to what was captured.+ val random = Random(4242)+ val stream = NegotiatedStream(+ kind = StreamKind.Video,+ senderSsrc = SENDER_SSRC,+ receiverSsrc = RECEIVER_SSRC,+ payloadType = StreamConstants.VIDEO_PAYLOAD_TYPE,+ timebase = StreamConstants.VIDEO_TIMEBASE,+ keys = keys,+ )+ val receiver = ReceiverSession(stream)+ val sender = StreamingSession()+ val packetizer = packetizer()+ val delivered = mutableMapOf<Long, ByteArray>()+ val inFlight = mutableListOf<ByteArray>()++ for (id in 0L until 200L) {+ val isKeyFrame = id == 0L+ val original = frame(id, size = 3_000, isKeyFrame = isKeyFrame)+ sender.record(original)+ for (packet in packetizer.packetize(original)) {+ // 10% loss, which is far worse than a real LAN and therefore the point.+ if (random.nextInt(10) == 0) continue+ inFlight += packet+ }+ // Reordering: the link delivers what it has in an arbitrary order.+ inFlight.shuffle(random)+ for (packet in inFlight) {+ for (frame in receiver.onPacket(packet)) delivered[frame.frameId.value] = frame.payload+ }+ inFlight.clear()++ // The receiver reports, and the sender answers from its buffer - the loop that makes+ // loss survivable.+ val feedback = assertNotNull(+ Rtcp.parse(receiver.feedback(), RECEIVER_SSRC, SENDER_SSRC, FrameId(id)),+ )+ for (item in sender.onFeedback(feedback).retransmissions) {+ val packets = packetizer.packetize(item.frame)+ val ids = item.packetIds ?: packets.indices.toList()+ for (packetId in ids) inFlight += packets[packetId]+ }+ }+ // Flush whatever the last round put in flight.+ for (packet in inFlight) {+ for (frame in receiver.onPacket(packet)) delivered[frame.frameId.value] = frame.payload+ }++ assertTrue(+ delivered.size > 150,+ "only ${delivered.size} of 200 frames were recovered; retransmission is not working",+ )+ for ((id, payload) in delivered) {+ assertContentEquals(plaintextOf(id, 3_000), payload, "frame $id was corrupted")+ }+ // Delivery is contiguous from the first key frame: a gap would mean a frame was released+ // before the one it references.+ val ids = delivered.keys.sorted()+ assertEquals((ids.first()..ids.last()).toList(), ids, "frames were delivered out of order")+ }++ @Test+ fun `nothing is released before a key frame arrives`() {+ // A delta frame handed to a decoder that never had its reference is a green smear, not an+ // error, so it must not be released at all.+ val stream = videoStream()+ val receiver = ReceiverSession(stream)+ val packetizer = packetizer()+ for (id in 1L..5L) {+ for (packet in packetizer.packetize(frame(id, size = 400, isKeyFrame = false))) {+ assertTrue(receiver.onPacket(packet).isEmpty())+ }+ }+ // And it says so: a PLI rides with the feedback until there is something decodable.+ val parsed = assertNotNull(+ Rtcp.parse(receiver.feedback(), RECEIVER_SSRC, SENDER_SSRC, FrameId(5)),+ )+ assertTrue(parsed.pictureLoss)++ // The key frame resynchronises, and the undecodable frames before it are dropped rather+ // than delivered late.+ val key = frame(6, size = 400, isKeyFrame = true)+ val released = packetizer.packetize(key).flatMap { receiver.onPacket(it) }+ assertEquals(listOf(FrameId(6)), released.map { it.frameId })+ assertEquals(FrameId(6), receiver.checkpoint)+ }++ @Test+ fun `a datagram for another stream is ignored rather than misparsed`() {+ // Audio and video share one socket, so most of what arrives on it is not ours.+ val receiver = ReceiverSession(videoStream())+ val other = RtpPacketizer(StreamConstants.AUDIO_PAYLOAD_TYPE, 12_345L)+ assertTrue(receiver.onPacket(other.packetize(frame(0, size = 100)).single()).isEmpty())+ assertEquals(1, receiver.packetsIgnored)+ assertEquals(0, receiver.packetsReceived)+ }++ @Test+ fun `a truncated or malformed datagram is dropped without throwing`() {+ val receiver = ReceiverSession(videoStream())+ val good = packetizer().packetize(frame(0, size = 100)).single()+ assertTrue(receiver.onPacket(ByteArray(0)).isEmpty())+ assertTrue(receiver.onPacket(good.copyOfRange(0, 10)).isEmpty())+ // Version bits other than 2.+ assertTrue(receiver.onPacket(good.copyOf().also { it[0] = 0 }).isEmpty())+ // A declared
Diff truncated.