Modern Apps git

← Modern-Apps.git

cast: add the pure Cast Streaming core with JVM tests

Commit
bb6c7ed4ec825a65852e36df5423b5e945f06034
Author
vayun-mathur <[email protected]>
When
2026-08-21 06:38 UTC (3 months ago)
Parents
727d204

Diff

cast/src/main/java/com/vayunmathur/cast/domain/streaming/CastCrypto.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/domain/streaming/CastCrypto.kt b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/CastCrypto.ktnew file mode 100644index 0000000000..19bf0425c8--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/CastCrypto.kt@@ -0,0 +1,63 @@+package com.vayunmathur.cast.domain.streaming++import javax.crypto.Cipher+import javax.crypto.spec.IvParameterSpec+import javax.crypto.spec.SecretKeySpec++/**+ * Cast Streaming payload encryption: AES-128-CTR with a per-frame IV.+ *+ * From openscreen `cast/streaming/impl/frame_crypto.cc` (`FrameCrypto::Crypt`). The IV is *not*+ * random and *not* transmitted - both ends derive it from the frame id and the `aesIvMask` agreed+ * in the OFFER, 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 - this needs unauthenticated AES-128-CTR with a *derived*+ * IV and no framing overhead at all, because the receiver's parser expects the payload bytes to be+ * exactly the ciphertext. They are different contracts that happen to share the letters "AES", so+ * consolidating them would break the wire format.+ *+ * Note this means the stream is unauthenticated. That is the protocol's choice, not ours; there is+ * no way to interoperate and also add a MAC.+ */+class CastCrypto(key: ByteArray, private val ivMask: ByteArray) {++    init {+        require(key.size == 16) { "Cast Streaming uses AES-128; got a ${key.size}-byte key" }+        require(ivMask.size == 16) { "the IV mask is one AES block; got ${ivMask.size} bytes" }+    }++    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(16)+        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 one frame in place of a copy.+     *+     * CTR is its own inverse, so this is also the decrypt path - which is only used by tests, the+     * sender never decrypts.+     */+    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)+    }+}
cast/src/main/java/com/vayunmathur/cast/domain/streaming/CastRtcp.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/domain/streaming/CastRtcp.kt b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/CastRtcp.ktnew file mode 100644index 0000000000..9f6ec3c0c7--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/CastRtcp.kt@@ -0,0 +1,192 @@+package com.vayunmathur.cast.domain.streaming++/**+ * RTCP: sender reports out, receiver feedback in.+ *+ * From openscreen `cast/streaming/impl/rtcp_common.cc` (the common header and report block),+ * `impl/sender_report_builder.cc` (the sender report) and `impl/compound_rtcp_parser.cc`+ * (`ParseFeedback`, the Cast-specific 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 parsing+ * feedback nothing is ever retransmitted.+ */+object CastRtcp {++    /** 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+    private const val TYPE_APPLICATION_DEFINED = 204++    /** `RtcpSubtype::kFeedback`, carried in the report-count field. */+    private const val SUBTYPE_FEEDBACK = 15++    /** `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++    /**+     * 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(4 + 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+    }++    /**+     * Parse a receiver feedback packet, or return null if this is not one.+     *+     * [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.+     */+    fun parseFeedback(+        packet: ByteArray,+        receiverSsrc: Long,+        senderSsrc: Long,+        maxFrameId: FrameId,+    ): ReceiverFeedback? {+        if (packet.size < 4 + FEEDBACK_HEADER_SIZE) return null+        val byte0 = packet[0].toInt() and 0xff+        if (byte0 and 0b1110_0000 != VERSION_AND_PADDING) return null+        if (byte0 and 0b0001_1111 != SUBTYPE_FEEDBACK) return null+        if (packet[1].toInt() and 0xff != TYPE_APPLICATION_DEFINED) return null+        var i = 4+        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 (packet.size - 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 (packet.size - 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 (packet.size - i >= octets) {+                // "Plus two" because the checkpoint frame is implicitly acked and the bit vector+                // starts at the frame after the one following it - see rtp_defines.h.+                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)+    }++    /**+     * 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)+    }+}++/** One packet the receiver says it is missing. */+data class PacketNack(val frameId: FrameId, val packetId: Int) {+    val isWholeFrame: Boolean get() = packetId == CastRtcp.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>,+)++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/src/main/java/com/vayunmathur/cast/domain/streaming/CastRtpPacketizer.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/domain/streaming/CastRtpPacketizer.kt b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/CastRtpPacketizer.ktnew file mode 100644index 0000000000..59961306e1--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/CastRtpPacketizer.kt@@ -0,0 +1,143 @@+package com.vayunmathur.cast.domain.streaming++/**+ * The largest UDP payload that fits an Ethernet frame without fragmenting:+ * `kMaxRtpPacketSizeForIpv4UdpOnEthernet` in openscreen `cast/streaming/impl/rtp_defines.h`.+ */+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++/** `kAdaptiveLatencyHeaderSize`. Reserved even when unused, as openscreen reserves it. */+private const val ADAPTIVE_LATENCY_HEADER_SIZE = 4++private const val MAX_HEADER_SIZE = BASE_HEADER_SIZE + ADAPTIVE_LATENCY_HEADER_SIZE++/** `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++/** One encoded, already-encrypted frame, ready to be split into packets. */+data class EncryptedFrame(+    val frameId: FrameId,+    val referencedFrameId: FrameId,+    val rtpTimestamp: Long,+    val isKeyFrame: Boolean,+    val payload: ByteArray,+) {+    override fun equals(other: Any?): Boolean =+        other is EncryptedFrame &&+            frameId == other.frameId &&+            referencedFrameId == other.referencedFrameId &&+            rtpTimestamp == other.rtpTimestamp &&+            isKeyFrame == other.isKeyFrame &&+            payload.contentEquals(other.payload)++    override fun hashCode(): Int {+        var result = frameId.hashCode()+        result = 31 * result + referencedFrameId.hashCode()+        result = 31 * result + rtpTimestamp.hashCode()+        result = 31 * result + isKeyFrame.hashCode()+        result = 31 * result + payload.contentHashCode()+        return result+    }+}++/**+ * Splits an encrypted frame into Cast RTP packets.+ *+ * Wire format from openscreen `cast/streaming/impl/rtp_packetizer.cc` (`GeneratePacket`), with the+ * field diagram in `impl/rtp_defines.h`:+ *+ * ```+ *  0                   1                   2                   3+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1+ * |V=2|P|X|  CC   |M|     PT      |       sequence number         |+ * |                           RTP timestamp                       |+ * |                             sender SSRC                       |+ * |K|R|ext count  |   frame id    |          packet id            |+ * |      max packet id            | reference frame id            |+ * ```+ *+ * 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.+ */+class CastRtpPacketizer(+    private val payloadType: Int,+    private val senderSsrc: Long,+    private val maxPacketSize: Int = MAX_RTP_PACKET_SIZE,+    sequenceNumberStart: Int = 0,+) {++    private var sequenceNumber = sequenceNumberStart and 0xffff++    val maxPayloadSize: Int get() = maxPacketSize - MAX_HEADER_SIZE++    /**+     * How many packets [payloadSize] bytes will take.+     *+     * Always at least one: some audio codecs encode a silent period as zero bytes, and a frame+     * that produced no packets would stall the receiver's frame assembler waiting for it.+     */+    fun packetCount(payloadSize: Int): Int =+        maxOf(1, (payloadSize + maxPayloadSize - 1) / maxPayloadSize)++    /** Every packet for [frame], in order. */+    fun packetize(frame: EncryptedFrame): List<ByteArray> {+        val total = packetCount(frame.payload.size)+        return (0 until total).map { packet(frame, it, total) }+    }++    private fun packet(frame: EncryptedFrame, packetId: Int, total: Int): ByteArray {+        val start = maxPayloadSize * packetId+        val chunkSize = if (packetId == total - 1) frame.payload.size - start else maxPayloadSize+        val out = ByteArray(BASE_HEADER_SIZE + chunkSize)+        var i = 0++        // RTP header.+        out[i++] = RTP_FIRST_BYTE.toByte()+        val marker = if (packetId == total - 1) RTP_MARKER_BIT else 0+        out[i++] = (marker or payloadType).toByte()+        i = out.putShort(i, sequenceNumber)+        sequenceNumber = (sequenceNumber + 1) and 0xffff+        i = out.putInt(i, frame.rtpTimestamp and 0xffff_ffffL)+        i = out.putInt(i, senderSsrc and 0xffff_ffffL)++        // Cast header. The reference-frame-id bit is always set, which is what makes the header 19+        // bytes rather than 18.+        val keyBit = if (frame.isKeyFrame) CAST_KEY_FRAME_BIT else 0+        out[i++] = (keyBit or CAST_HAS_REFERENCE_FRAME_ID_BIT).toByte()+        out[i++] = frame.frameId.lower8.toByte()+        i = out.putShort(i, packetId)+        i = out.putShort(i, total - 1)+        out[i++] = frame.referencedFrameId.lower8.toByte()++        frame.payload.copyInto(out, i, start, start + chunkSize)+        return out+    }+}++internal fun ByteArray.putShort(offset: Int, value: Int): Int {+    this[offset] = (value ushr 8).toByte()+    this[offset + 1] = value.toByte()+    return offset + 2+}++internal fun ByteArray.putInt(offset: Int, value: Long): Int {+    this[offset] = (value ushr 24).toByte()+    this[offset + 1] = (value ushr 16).toByte()+    this[offset + 2] = (value ushr 8).toByte()+    this[offset + 3] = value.toByte()+    return offset + 4+}
cast/src/main/java/com/vayunmathur/cast/domain/streaming/FrameId.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/domain/streaming/FrameId.kt b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/FrameId.ktnew file mode 100644index 0000000000..6ec995bc62--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/FrameId.kt@@ -0,0 +1,39 @@+package com.vayunmathur.cast.domain.streaming++/**+ * A frame's identifier.+ *+ * **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+ * 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.+ *+ * `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.+ */+@JvmInline+value class FrameId(val value: Long) : Comparable<FrameId> {++    /** What goes in the RTP header's Frame ID and Reference Frame ID fields. */+    val lower8: Int get() = (value and 0xff).toInt()++    /** What the encryption IV is derived from. */+    val lower32: Long get() = value and 0xffff_ffffL++    operator fun plus(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)++    override fun toString(): String = value.toString()++    companion object {+        /** `FrameId::first()`. */+        val First = FrameId(0)++        /** `FrameId::leader()` - the reference for a frame that depends on nothing. */+        val Leader = FrameId(-1)+    }+}
cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamSelection.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamSelection.kt b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamSelection.ktnew file mode 100644index 0000000000..e397054677--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamSelection.kt@@ -0,0 +1,158 @@+package com.vayunmathur.cast.domain.streaming++import com.vayunmathur.cast.domain.CastDeviceKind+import java.security.SecureRandom++/**+ * What to offer a given device, and the keys and identifiers to offer it with.+ *+ * This is where the audio-only requirement lives. It is a correctness boundary rather than a+ * preference: Phase 0 established on real hardware that a receiver refuses a mismatched app id at+ * LAUNCH, and that a speaker answers with the audio stream index alone whatever was offered.+ *+ * Pure, so all of it is testable on the JVM.+ */+object StreamSelection {++    /** `kDefaultTargetPlayoutDelay` - openscreen `cast/streaming/public/constants.h`. */+    const val TARGET_DELAY_MS = 400++    /** The spec fixes video at 90 kHz; `kRtpVideoTimebase` in the same file. */+    const val VIDEO_TIMEBASE = 90_000++    /** `kAudioTimebase` - Chrome's `components/mirroring/service/mirror_settings.cc`. */+    const val AUDIO_TIMEBASE = 48_000++    const val AUDIO_CHANNELS = 2+    const val AUDIO_BITRATE = 128_000++    /** `kStartVideoBitrate` from `mirror_settings.cc`. */+    const val VIDEO_MAX_BITRATE = 5_000_000++    const val VIDEO_MAX_FRAME_RATE = 30++    /**+     * `kAudioHackForAndroidTV` and `kVideoHackForAndroidTV` -+     * openscreen `cast/streaming/impl/rtp_defines.h`. See [OfferStream.rtpPayloadType].+     */+    const val AUDIO_PAYLOAD_TYPE = 127+    const val VIDEO_PAYLOAD_TYPE = 96++    /**+     * SSRC ranges from openscreen `cast/streaming/ssrc.cc`. Audio is "high priority" and video is+     * "normal"; the ranges are arbitrary but long-established, and `ComparePriority` is a plain+     * numeric comparison, so staying inside them is what makes audio win under contention.+     */+    private const val AUDIO_SSRC_MIN = 1+    private const val AUDIO_SSRC_MAX = 50_000+    private const val VIDEO_SSRC_MIN = 50_001+    private const val VIDEO_SSRC_MAX = 100_000++    /**+     * Whether a device can take video at all.+     *+     * From the mDNS capability bitmask, so it is known before anything is negotiated - that is+     * what lets the UI say "audio only" while the receiver is still being joined.+     */+    fun isAudioOnly(kind: CastDeviceKind): Boolean = kind != CastDeviceKind.Tv++    /**+     * Build the OFFER for [kind].+     *+     * Stream indexes are load-bearing: `CreateMirroringOffer` in openscreen's `sender_session.cc`+     * puts audio at `[0..N-1]` and video at `[N..K]`, and the ANSWER's `sendIndexes` refers back+     * to them. Audio is therefore always index 0 and video, when present, index 1.+     */+    fun offer(kind: CastDeviceKind, random: SecureRandom = SecureRandom()): StreamPlan {+        val audio = StreamKeys(random.bytes16(), random.bytes16())+        val audioSsrc = random.ssrc(AUDIO_SSRC_MIN, AUDIO_SSRC_MAX)+        val audioStream = OfferStream(+            index = AUDIO_INDEX,+            type = "audio_source",+            codecName = "opus",+            rtpPayloadType = AUDIO_PAYLOAD_TYPE,+            ssrc = audioSsrc,+            channels = AUDIO_CHANNELS,+            targetDelay = TARGET_DELAY_MS,+            aesKey = audio.key.toHex(),+            aesIvMask = audio.ivMask.toHex(),+            timeBase = "1/$AUDIO_TIMEBASE",+            bitRate = AUDIO_BITRATE,+        )+        if (isAudioOnly(kind)) {+            return StreamPlan(+                streams = listOf(audioStream),+                audioKeys = audio,+                audioSsrc = audioSsrc,+            )+        }+        val video = StreamKeys(random.bytes16(), random.bytes16())+        val videoSsrc = random.ssrc(VIDEO_SSRC_MIN, VIDEO_SSRC_MAX)+        val videoStream = OfferStream(+            index = VIDEO_INDEX,+            type = "video_source",+            codecName = "h264",+            rtpPayloadType = VIDEO_PAYLOAD_TYPE,+            ssrc = videoSsrc,+            channels = 1,+            targetDelay = TARGET_DELAY_MS,+            aesKey = video.key.toHex(),+            aesIvMask = video.ivMask.toHex(),+            timeBase = "1/$VIDEO_TIMEBASE",+            maxFrameRate = "${VIDEO_MAX_FRAME_RATE * 1000}/1000",+            maxBitRate = VIDEO_MAX_BITRATE,+            // Only an upper bound. The TV answered `scaling: "sender"` with a 4K display, so the+            // capture resolution is ours to choose and this is what we promise not to exceed.+            resolutions = listOf(Resolution(1280, 720)),+        )+        return StreamPlan(+            streams = listOf(audioStream, videoStream),+            audioKeys = audio,+            audioSsrc = audioSsrc,+            videoKeys = video,+            videoSsrc = videoSsrc,+        )+    }++    const val AUDIO_INDEX = 0+    const val VIDEO_INDEX = 1++    private fun SecureRandom.bytes16(): ByteArray = ByteArray(16).also { nextBytes(it) }++    private fun SecureRandom.ssrc(min: Int, max: Int): Long =+        (min + nextInt(max - min + 1)).toLong()+}++/** The AES-128 key and the IV mask for one stream. Per-stream, never shared. */+data class StreamKeys(val key: ByteArray, val ivMask: ByteArray) {+    // Arrays, so the generated equals/hashCode would compare identity. Content comparison is what+    // a test asserting a round-trip 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()+}++/** An OFFER plus the sender-side secrets it commits us to. */+data class StreamPlan(+    val streams: List<OfferStream>,+    val audioKeys: StreamKeys,+    val audioSsrc: Long,+    val videoKeys: StreamKeys? = null,+    val videoSsrc: Long? = null,+) {+    val hasVideo: Boolean get() = videoKeys != null++    fun message(seqNum: Int): OfferMessage = OfferMessage(seqNum, Offer(streams))+}++internal fun ByteArray.toHex(): String {+    val out = StringBuilder(size * 2)+    for (b in this) {+        val v = b.toInt() and 0xff+        out.append(HEX[v ushr 4]).append(HEX[v and 0x0f])+    }+    return out.toString()+}++private const val HEX = "0123456789abcdef"
cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamingPayloads.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamingPayloads.kt b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamingPayloads.ktnew file mode 100644index 0000000000..e5ee363d07--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamingPayloads.kt@@ -0,0 +1,151 @@+package com.vayunmathur.cast.domain.streaming++import com.vayunmathur.cast.domain.CastJson+import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++/**+ * The OFFER/ANSWER wire types, transcribed from openscreen.+ *+ * Sources, checked rather than recalled:+ *  - the envelopes from `cast/streaming/sender_message.cc` and+ *    `cast/streaming/public/receiver_message.cc`+ *  - the offer body from `cast/streaming/public/offer_messages.cc` (`Offer::ToJson`,+ *    `Stream::ToJson`, `AudioStream::ToJson`, `VideoStream::ToJson`)+ *  - the answer body from `cast/streaming/public/answer_messages.cc` (`Answer::TryParse`)+ *+ * Reuses [CastJson], whose `explicitNulls = false` is what keeps absent optionals absent - the+ * receiver is not tolerant of `"codecParameter": null` where openscreen would have omitted it.+ */++/** `{"type":"OFFER","seqNum":N,"offer":{...}}`. */+@Serializable+data class OfferMessage(+    val seqNum: Int,+    val offer: Offer,+    val type: String = "OFFER",+)++@Serializable+data class Offer(+    val supportedStreams: List<OfferStream>,+    /** `"mirroring"` or `"remoting"`; only mirroring is used here. */+    val castMode: String = "mirroring",+)++/**+ * One stream descriptor. Audio and video share every field except the last few, so this is one+ * type with optionals rather than a sealed hierarchy - the wire format is one JSON object shape+ * discriminated by [type], and mirroring that keeps the serialiser honest.+ *+ * Field order here follows `Stream::ToJson` so a diff against openscreen stays readable.+ */+@Serializable+data class OfferStream(+    val index: Int,+    /** `audio_source` or `video_source`. */+    val type: String,+    val codecName: String,+    /** Always `cast`. Required by the spec even though it never varies. */+    val rtpProfile: String = "cast",+    /**+     * 127 for audio and 96 for video - the "Android TV hack" values from+     * `cast/streaming/impl/rtp_defines.h`. Not the obvious `kAudioOpus`/`kVideoH264`: openscreen's+     * `use_android_rtp_hack` defaults to true and Chrome never overrides it, so these are what a+     * receiver actually expects. 96 deliberately collides with `kAudioOpus`; the receiver+     * disambiguates by [index], not by payload type.+     */+    val rtpPayloadType: Int,+    val ssrc: Long,+    /** Audio is 2, video is 1 - `mirror_settings.cc`. */+    val channels: Int,+    val targetDelay: Int,+    /** Hex, 16 bytes. */+    val aesKey: String,+    /** Hex, 16 bytes. */+    val aesIvMask: String,+    val receiverRtcpEventLog: Boolean = true,+    /** A *string* of the form `1/90000`, not a number. */+    val timeBase: String,+    // Audio only.+    val bitRate: Int? = null,+    // Video only.+    /** A rational *string* such as `30000/1000`, not a number. */+    val maxFrameRate: String? = null,+    val maxBitRate: Int? = null,+    val resolutions: List<Resolution>? = null,+)++@Serializable+data class Resolution(val width: Int, val height: Int)++/**+ * `{"type":"ANSWER","seqNum":N,"result":"ok","answer":{...}}`, or `"result":"error"` with an+ * `error` object instead.+ */+@Serializable+data class AnswerMessage(+    val type: String = "",+    val seqNum: Int? = null,+    val result: String = "error",+    val answer: Answer? = null,+    val error: AnswerError? = null,+)++@Serializable+data class AnswerError(+    val code: Int = 0,+    val description: String = "",+)++/**+ * What the receiver agreed to.+ *+ * [sendIndexes] is the authoritative stream set: a speaker answers `[0]` however much was+ * offered, which is how the audio-only case is really decided. [ssrcs] are the *receiver's*+ * SSRCs, positionally matching [sendIndexes].+ *+ * Everything except those three is optional because the two receiver classes disagree about what+ * to send: a TV answered with `display` and nothing else, a speaker with `castMode`,+ * `receiverRtcpEventLog` and `rtpExtensions` but no `display` at all.+ */+@Serializable+data class Answer(+    val udpPort: Int,+    val sendIndexes: List<Int>,+    val ssrcs: List<Long>,+    /** Absent on a device with no screen, which is the natural "audio only" signal. */+    val display: DisplayDescription? = null,+    val castMode: String? = null,+    /**+     * An int array here, though the same-named OFFER field is a per-stream boolean. The asymmetry+     * is openscreen's: `answer_messages.cc` parses it with `TryParseIntArray`.+     */+    val receiverRtcpEventLog: List<Int>? = null,+    /** A *nested* array here - `TryParseNestedStringArray` in the same file. */+    val rtpExtensions: List<List<String>>? = null,+)++@Serializable+data class DisplayDescription(+    val dimensions: Dimensions? = null,+    /** `sender` means the receiver expects us to scale before encoding. */+    val scaling: String? = null,+)++@Serializable+data class Dimensions(+    val width: Int = 0,+    val height: Int = 0,+    /** A string, not a number. */+    @SerialName("frameRate") val frameRate: String? = null,+)++/** Serialise an OFFER for the wire. */+fun OfferMessage.encode(): String = CastJson.encodeToString(this)++/** Parse an ANSWER, or null when the payload is not one. */+fun parseAnswer(payload: String): AnswerMessage? =+    runCatching { CastJson.decodeFromString<AnswerMessage>(payload) }+        .getOrNull()+        ?.takeIf { it.type == "ANSWER" }
cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamingSession.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamingSession.kt b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamingSession.ktnew file mode 100644index 0000000000..2059beef14--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamingSession.kt@@ -0,0 +1,203 @@+package com.vayunmathur.cast.domain.streaming++/** Which half of the stream a packet belongs to. */+enum class StreamKind { Audio, Video }++/**+ * One negotiated stream: where to send, and what to encrypt with.+ *+ * [receiverSsrc] comes out of the ANSWER rather than being derived. The receiver happened to answer+ * with our SSRC plus one on every observed session, but that is its choice to make and nothing here+ * may assume it.+ */+data class NegotiatedStream(+    val kind: StreamKind,+    val index: Int,+    val senderSsrc: Long,+    val receiverSsrc: Long,+    val payloadType: Int,+    val timebase: Int,+    val keys: StreamKeys,+)++/** Everything the ANSWER settled. */+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+}++/** Why an ANSWER could not be used. */+sealed interface NegotiationFailure {+    /** The receiver said `"result":"error"`. */+    data class Refused(val code: Int, val description: String) : NegotiationFailure++    /** The receiver accepted nothing we offered, so there is nothing to send. */+    data object NoStreams : NegotiationFailure++    /** The ANSWER was not shaped the way the protocol says. */+    data class Malformed(val detail: String) : NegotiationFailure+}++/**+ * `CastSession`'s sibling: the OFFER/ANSWER and loss-recovery state machine, with no I/O.+ *+ * Kept free of sockets and encoders for the same reason `CastSession` is - loss recovery is the+ * part with the subtle rules, and this way every one of them is a JVM unit test.+ */+class StreamingSession(private val plan: StreamPlan) {++    var negotiation: Negotiation? = null+        private set++    /**+     * 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>()++    /**+     * Turn an ANSWER into routes.+     *+     * [Answer.sendIndexes] is authoritative, not what we offered: a speaker answers `[0]` even+     * though the audio-only OFFER also contained only index 0, and a TV could in principle accept+     * a subset. Anything we offered and it did not accept is simply not sent.+     */+    fun onAnswer(message: AnswerMessage): NegotiationFailure? {+        if (message.result != "ok") {+            val error = message.error+            return NegotiationFailure.Refused(error?.code ?: 0, error?.description ?: "")+        }+        val answer = message.answer ?: return NegotiationFailure.Malformed("no answer body")+        if (answer.sendIndexes.size != answer.ssrcs.size) {+            return NegotiationFailure.Malformed(+                "sendIndexes and ssrcs disagree: " ++                    "${answer.sendIndexes.size} vs ${answer.ssrcs.size}",+            )+        }+        if (answer.udpPort !in 1..65535) {+            return NegotiationFailure.Malformed("udpPort ${answer.udpPort}")+        }+        val streams = answer.sendIndexes.mapIndexedNotNull { position, index ->+            val receiverSsrc = answer.ssrcs[position]+            when (index) {+                StreamSelection.AUDIO_INDEX -> NegotiatedStream(+                    kind = StreamKind.Audio,+                    index = index,+                    senderSsrc = plan.audioSsrc,+                    receiverSsrc = receiverSsrc,+                    payloadType = StreamSelection.AUDIO_PAYLOAD_TYPE,+                    timebase = StreamSelection.AUDIO_TIMEBASE,+                    keys = plan.audioKeys,+                )+                StreamSelection.VIDEO_INDEX -> {+                    val keys = plan.videoKeys+                    val ssrc = plan.videoSsrc+                    // A receiver accepting an index we never offered is its bug, not a reason to+                    // abandon the session - drop the stream and carry on with the rest.+                    if (keys == null || ssrc == null) {+                        null+                    } else {+                        NegotiatedStream(+                            kind = StreamKind.Video,+                            index = index,+                            senderSsrc = ssrc,+                            receiverSsrc = receiverSsrc,+                            payloadType = StreamSelection.VIDEO_PAYLOAD_TYPE,+                            timebase = StreamSelection.VIDEO_TIMEBASE,+                            keys = keys,+                        )+                    }+                }+                else -> null+            }+        }+        if (streams.isEmpty()) return NegotiationFailure.NoStreams+        negotiation = Negotiation(answer.udpPort, streams)+        return null+    }++    /** 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 400 ms 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/src/test/java/com/vayunmathur/cast/domain/streaming/CastCryptoTest.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastCryptoTest.kt b/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastCryptoTest.ktnew file mode 100644index 0000000000..c2d4a4d280--- /dev/null+++ b/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastCryptoTest.kt@@ -0,0 +1,119 @@+package com.vayunmathur.cast.domain.streaming++import javax.crypto.Cipher+import javax.crypto.spec.SecretKeySpec+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class CastCryptoTest {++    private val key = "000102030405060708090a0b0c0d0e0f".hex()+    private val mask = "101112131415161718191a1b1c1d1e1f".hex()++    @Test+    fun `the iv is the frame id big-endian at offset eight, xored with the mask`() {+        // 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)+        assertContentEquals(mask, crypto.ivForFrame(FrameId.First))+        assertContentEquals(+            "101112131415161718191a1a1c1d1e1f".hex(),+            crypto.ivForFrame(FrameId(1)),+        )+        // 0x01020304 lands across bytes 8..11: 01^18=19, 02^19=1b, 03^1a=19, 04^1b=1f.+        assertContentEquals(+            "1011121314151617191b191f1c1d1e1f".hex(),+            crypto.ivForFrame(FrameId(0x01020304)),+        )+    }++    @Test+    fun `the iv uses the lower 32 bits, not the 8 bits that go on the wire`() {+        // 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)+        assertEquals(FrameId.First.lower8, FrameId(256).lower8)+        assertFalse(+            crypto.ivForFrame(FrameId.First).contentEquals(crypto.ivForFrame(FrameId(256))),+        )+    }++    @Test+    fun `ctr matches a keystream built independently from aes-ecb`() {+        // 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 frameId = FrameId(0x0000_1234)+        val plaintext = ByteArray(70) { it.toByte() }++        val actual = crypto.crypt(frameId, plaintext)+        val expected = referenceCtr(key, crypto.ivForFrame(frameId), plaintext)++        assertContentEquals(expected, actual)+        // And it is genuinely encrypting, not passing bytes through.+        assertFalse(plaintext.contentEquals(actual))+    }++    @Test+    fun `ctr is its own inverse`() {+        val crypto = CastCrypto(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))+    }++    @Test+    fun `two frames with the same payload encrypt differently`() {+        val crypto = CastCrypto(key, mask)+        val payload = ByteArray(32) { 7 }+        assertFalse(+            crypto.crypt(FrameId.First, payload).contentEquals(crypto.crypt(FrameId(1), payload)),+        )+    }++    @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)) }+    }++    @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())+    }++    /** Counter mode assembled from the raw block cipher, as an independent oracle. */+    private fun referenceCtr(key: ByteArray, iv: ByteArray, input: ByteArray): ByteArray {+        val ecb = Cipher.getInstance("AES/ECB/NoPadding")+        ecb.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"))+        val out = ByteArray(input.size)+        val counter = iv.copyOf()+        var offset = 0+        while (offset < input.size) {+            val block = ecb.doFinal(counter)+            val n = minOf(16, input.size - offset)+            for (i in 0 until n) {+                out[offset + i] = (input[offset + i].toInt() xor block[i].toInt()).toByte()+            }+            offset += n+            // Increment the whole 128-bit counter, big-endian, as AES_ctr128_encrypt does.+            for (i in 15 downTo 0) {+                counter[i] = (counter[i] + 1).toByte()+                if (counter[i] != 0.toByte()) break+            }+        }+        return out+    }+}++internal fun String.hex(): ByteArray =+    chunked(2).map { it.toInt(16).toByte() }.toByteArray()
cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastRtcpTest.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastRtcpTest.kt b/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastRtcpTest.ktnew file mode 100644index 0000000000..b670a6b4b3--- /dev/null+++ b/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastRtcpTest.kt@@ -0,0 +1,220 @@+package com.vayunmathur.cast.domain.streaming++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++private const val RECEIVER_SSRC = 20_002L+private const val SENDER_SSRC = 20_001L++class CastRtcpTest {++    /**+     * Builds a feedback packet the way a receiver does, so the parser is exercised against the+     * documented layout rather than against itself.+     */+    private fun feedback(+        checkpoint: Int,+        playoutDelayMs: Int = 400,+        lossFields: List<Triple<Int, Int, Int>> = emptyList(),+        ackBitVector: List<Int>? = null,+    ): ByteArray {+        val body = mutableListOf<Byte>()+        fun int32(v: Long) {+            body += (v ushr 24).toByte(); body += (v ushr 16).toByte()+            body += (v ushr 8).toByte(); body += v.toByte()+        }+        fun int16(v: Int) {+            body += (v ushr 8).toByte(); body += v.toByte()+        }+        int32(RECEIVER_SSRC)+        int32(SENDER_SSRC)+        int32(0x43_41_53_54) // 'CAST'+        body += checkpoint.toByte()+        body += lossFields.size.toByte()+        int16(playoutDelayMs)+        for ((frameId, packetId, bits) in lossFields) {+            body += frameId.toByte()+            int16(packetId)+            body += bits.toByte()+        }+        if (ackBitVector != null) {+            int32(0x43_53_54_32) // 'CST2'+            body += 0 // feedback count, unused+            body += ackBitVector.size.toByte()+            ackBitVector.forEach { body += it.toByte() }+        }+        val header = byteArrayOf(+            ((0b100 shl 5) or 15).toByte(), // version 2, subtype kFeedback+            204.toByte(), // kApplicationDefined+            0, 0, // length, unchecked by the parser+        )+        return header + body.toByteArray()+    }++    @Test+    fun `a sender report has the documented layout`() {+        val packet = CastRtcp.senderReport(+            senderSsrc = SENDER_SSRC,+            ntpTimestamp = 0x0192a3b4c5d6e7f8,+            rtpTimestamp = 0xAABBCCDD,+            packetCount = 7,+            octetCount = 4096,+        )+        assertEquals(28, packet.size)+        assertEquals(0x80, packet[0].toInt() and 0xff) // no report blocks+        assertEquals(200, packet[1].toInt() and 0xff)+        // The length field counts 32-bit words after the first, so 24/4 rather than 28/4.+        assertEquals(6, packet.getShort(2))+        assertEquals(SENDER_SSRC, packet.getInt(4))+        assertEquals(0x0192a3b4L, packet.getInt(8))+        assertEquals(0xc5d6e7f8L, packet.getInt(12))+        assertEquals(0xAABBCCDDL, packet.getInt(16))+        assertEquals(7L, packet.getInt(20))+        assertEquals(4096L, packet.getInt(24))+    }++    @Test+    fun `a bare checkpoint parses`() {+        val parsed = assertNotNull(+            CastRtcp.parseFeedback(feedback(checkpoint = 5), RECEIVER_SSRC, SENDER_SSRC, FrameId(5)),+        )+        assertEquals(FrameId(5), parsed.checkpoint)+        assertEquals(400, parsed.playoutDelayMs)+        assertTrue(parsed.nacks.isEmpty())+        assertTrue(parsed.ackedFrames.isEmpty())+    }++    @Test+    fun `a loss field's bit vector expands into further packet ids`() {+        // Each set bit is the next packet id up from the one named, so 0b101 after packet 3 means+        // 4 and 6 are also missing.+        val parsed = assertNotNull(+            CastRtcp.parseFeedback(+                feedback(checkpoint = 10, lossFields = listOf(Triple(11, 3, 0b101))),+                RECEIVER_SSRC,+                SENDER_SSRC,+                FrameId(12),+            ),+        )+        assertEquals(+            listOf(+                PacketNack(FrameId(11), 3),+                PacketNack(FrameId(11), 4),+                PacketNack(FrameId(11), 6),+            ),+            parsed.nacks,+        )+    }++    @Test+    fun `the all-packets-lost id means the whole frame and suppresses the bit vector`() {+        val parsed = assertNotNull(+            CastRtcp.parseFeedback(+                feedback(checkpoint = 1, lossFields = listOf(Triple(2, 0xffff, 0xff))),+                RECEIVER_SSRC,+                SENDER_SSRC,+                FrameId(3),+            ),+        )+        assertEquals(1, parsed.nacks.size)+        assertTrue(parsed.nacks.single().isWholeFrame)+        assertEquals(FrameId(2), parsed.nacks.single().frameId)+    }++    @Test+    fun `CST2 acks start two frames after the checkpoint`() {+        // The "plus two" is openscreen's, documented in rtp_defines.h: the checkpoint frame is+        // implicitly acked and the vector begins beyond the frame following it.+        val parsed = assertNotNull(+            CastRtcp.parseFeedback(+                feedback(checkpoint = 4, ackBitVector = listOf(0b0000_0101)),+                RECEIVER_SSRC,+                SENDER_SSRC,+                FrameId(10),+            ),+        )+        assertEquals(listOf(FrameId(6), FrameId(8)), parsed.ackedFrames)+    }++    @Test+    fun `a second ack octet continues eight frames further on`() {+        val parsed = assertNotNull(+            CastRtcp.parseFeedback(+                feedback(checkpoint = 0, ackBitVector = listOf(0b0000_0001, 0b0000_0001)),+                RECEIVER_SSRC,+                SENDER_SSRC,+                FrameId(20),+            ),+        )+        assertEquals(listOf(FrameId(2), FrameId(10)), parsed.ackedFrames)+    }++    @Test+    fun `trailing bytes that are not CST2 are tolerated rather than treated as corrupt`() {+        // openscreen is explicit about this for backwards compatibility.+        val packet = feedback(checkpoint = 3) + byteArrayOf(1, 2, 3, 4, 5, 6)+        val parsed = assertNotNull(+            CastRtcp.parseFeedback(packet, RECEIVER_SSRC, SENDER_SSRC, FrameId(3)),+        )+        assertEquals(FrameId(3), parsed.checkpoint)+        assertTrue(parsed.ackedFrames.isEmpty())+    }++    @Test+    fun `packets for another session or of another type are rejected`() {+        val packet = feedback(checkpoint = 1)+        assertNull(CastRtcp.parseFeedback(packet, 999L, SENDER_SSRC, FrameId(1)))+        assertNull(CastRtcp.parseFeedback(packet, RECEIVER_SSRC, 999L, FrameId(1)))+        // A sender report is not feedback.+        assertNull(+            CastRtcp.parseFeedback(+                CastRtcp.senderReport(SENDER_SSRC, 0, 0, 0, 0),+                RECEIVER_SSRC,+                SENDER_SSRC,+                FrameId(1),+            ),+        )+        // Truncated.+        assertNull(+            CastRtcp.parseFeedback(packet.copyOfRange(0, 8), RECEIVER_SSRC, SENDER_SSRC, FrameId(1)),+        )+    }++    @Test+    fun `a loss field count that overruns the packet is refused`() {+        // Claiming four loss fields while carrying none must not read past the end.+        val packet = feedback(checkpoint = 1).copyOf()+        packet[4 + 12 + 1] = 4+        assertNull(CastRtcp.parseFeedback(packet, RECEIVER_SSRC, SENDER_SSRC, FrameId(1)))+    }++    @Test+    fun `the checkpoint expands across an eight-bit wrap`() {+        // Frame 260 truncates to 4. Read naively the checkpoint would look like frame 4 and the+        // retransmit buffer would never be drained again.+        assertEquals(+            FrameId(260),+            CastRtcp.expandLessThanOrEqual(FrameId(262), 260 and 0xff),+        )+        assertEquals(FrameId(255), CastRtcp.expandLessThanOrEqual(FrameId(256), 255))+        val parsed = assertNotNull(+            CastRtcp.parseFeedback(+                feedback(checkpoint = 260 and 0xff),+                RECEIVER_SSRC,+                SENDER_SSRC,+                FrameId(262),+            ),+        )+        assertEquals(FrameId(260), parsed.checkpoint)+    }++    @Test+    fun `a nacked frame id above the checkpoint expands upwards`() {+        assertEquals(FrameId(257), CastRtcp.expandGreaterThan(FrameId(255), 1))+        // Equal truncations mean a full lap, not the same frame.+        assertEquals(FrameId(511), CastRtcp.expandGreaterThan(FrameId(255), 255))+    }+}
cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastRtpPacketizerTest.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastRtpPacketizerTest.kt b/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastRtpPacketizerTest.ktnew file mode 100644index 0000000000..3f84397db3--- /dev/null+++ b/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastRtpPacketizerTest.kt@@ -0,0 +1,121 @@+package com.vayunmathur.cast.domain.streaming++import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertTrue++private const val PAYLOAD_TYPE = 96+private const val SSRC = 50_001L++class CastRtpPacketizerTest {++    private fun packetizer(maxPacketSize: Int = MAX_RTP_PACKET_SIZE) =+        CastRtpPacketizer(PAYLOAD_TYPE, SSRC, maxPacketSize, sequenceNumberStart = 0x1234)++    private fun frame(+        size: Int,+        frameId: FrameId = FrameId(1),+        referenced: FrameId = FrameId.Leader,+        isKeyFrame: Boolean = true,+        rtpTimestamp: Long = 0xAABBCCDD,+    ) = EncryptedFrame(+        frameId = frameId,+        referencedFrameId = referenced,+        rtpTimestamp = rtpTimestamp,+        isKeyFrame = isKeyFrame,+        payload = ByteArray(size) { (it and 0xff).toByte() },+    )++    @Test+    fun `a single-packet key frame has the expected header, byte for byte`() {+        val packets = packetizer().packetize(frame(size = 4))+        assertEquals(1, packets.size)+        val p = packets.single()+        assertEquals(19 + 4, p.size)+        // RTP: V=2 with no padding/extension/CSRC; marker set because this is the last packet.+        assertEquals(0x80, p[0].toInt() and 0xff)+        assertEquals(0x80 or PAYLOAD_TYPE, p[1].toInt() and 0xff)+        assertEquals(0x1234, p.getShort(2))+        assertEquals(0xAABBCCDDL, p.getInt(4))+        assertEquals(SSRC, p.getInt(8))+        // Cast: key-frame bit and the always-present reference-frame-id bit, no extensions.+        assertEquals(0b1100_0000, p[12].toInt() and 0xff)+        assertEquals(1, p[13].toInt() and 0xff)+        assertEquals(0, p.getShort(14)) // packet id+        assertEquals(0, p.getShort(16)) // max packet id, i.e. count - 1+        assertEquals(0xff, p[18].toInt() and 0xff) // FrameId.Leader truncates to 0xff+        assertContentEquals(byteArrayOf(0, 1, 2, 3), p.copyOfRange(19, 23))+    }++    @Test+    fun `a delta frame clears the key-frame bit and keeps the reference bit`() {+        val p = packetizer()+            .packetize(frame(size = 1, frameId = FrameId(5), referenced = FrameId(4), isKeyFrame = false))+            .single()+        assertEquals(0b0100_0000, p[12].toInt() and 0xff)+        assertEquals(5, p[13].toInt() and 0xff)+        assertEquals(4, p[18].toInt() and 0xff)+    }++    @Test+    fun `the marker bit is set only on the last packet, and ids run in order`() {+        // 23 bytes of header reserved per packet even though only 19 are written, so with a 39-byte+        // limit each packet carries 16 payload bytes.+        val p = packetizer(maxPacketSize = 39)+        assertEquals(16, p.maxPayloadSize)+        val packets = p.packetize(frame(size = 40))+        assertEquals(3, packets.size)+        packets.forEachIndexed { index, packet ->+            val isLast = index == packets.size - 1+            assertEquals(if (isLast) 0x80 or PAYLOAD_TYPE else PAYLOAD_TYPE, packet[1].toInt() and 0xff)+            assertEquals(index, packet.getShort(14))+            assertEquals(2, packet.getShort(16))+            assertEquals(0x1234 + index, packet.getShort(2))+        }+        // 16 + 16 + 8, and the payload reassembles to the original.+        assertEquals(listOf(16, 16, 8), packets.map { it.size - 19 })+        val reassembled = packets.fold(ByteArray(0)) { acc, packet ->+            acc + packet.copyOfRange(19, packet.size)+        }+        assertContentEquals(ByteArray(40) { (it and 0xff).toByte() }, reassembled)+    }++    @Test+    fun `an empty payload still produces one packet`() {+        // A silent audio frame is zero bytes; producing no packets would stall the receiver's+        // frame assembler waiting for a frame that never arrives.+        val packets = packetizer().packetize(frame(size = 0))+        assertEquals(1, packets.size)+        assertEquals(19, packets.single().size)+        assertEquals(0, packets.single().getShort(16))+    }++    @Test+    fun `an exact multiple of the payload size does not produce a trailing empty packet`() {+        val p = packetizer(maxPacketSize = 39)+        assertEquals(2, p.packetCount(32))+        assertEquals(listOf(16, 16), p.packetize(frame(size = 32)).map { it.size - 19 })+    }++    @Test+    fun `the sequence number wraps at sixteen bits`() {+        val p = CastRtpPacketizer(PAYLOAD_TYPE, SSRC, sequenceNumberStart = 0xffff)+        val first = p.packetize(frame(size = 1)).single()+        val second = p.packetize(frame(size = 1)).single()+        assertEquals(0xffff, first.getShort(2))+        assertEquals(0, second.getShort(2))+    }++    @Test+    fun `frame id and rtp timestamp are truncated to the wire width`() {+        // The counter is 64-bit; only the low 8 bits go in the header and the low 32 in the+        // timestamp. Anything wider must not corrupt neighbouring fields.+        val p = packetizer()+            .packetize(frame(size = 1, frameId = FrameId(0x1_0002), rtpTimestamp = 0x1_2233_4455))+            .single()+        assertEquals(0x02, p[13].toInt() and 0xff)+        assertEquals(0x2233_4455L, p.getInt(4))+        assertTrue(p.getInt(8) == SSRC)+    }+}
cast/src/test/java/com/vayunmathur/cast/domain/streaming/StreamingPayloadsTest.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/domain/streaming/StreamingPayloadsTest.kt b/cast/src/test/java/com/vayunmathur/cast/domain/streaming/StreamingPayloadsTest.ktnew file mode 100644index 0000000000..9809623862--- /dev/null+++ b/cast/src/test/java/com/vayunmathur/cast/domain/streaming/StreamingPayloadsTest.kt@@ -0,0 +1,160 @@+package com.vayunmathur.cast.domain.streaming++import com.vayunmathur.cast.domain.CastDeviceKind+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** A real ANSWER from a Google TV, captured on hardware: both streams, and a display block. */+private val ANSWER_TV = """+    {"answer":{"display":{"dimensions":{"frameRate":"60","height":2160,"width":3840},+      "scaling":"sender"},"sendIndexes":[0,1],"ssrcs":[20002,50002],"udpPort":47505},+      "result":"ok","seqNum":2,"type":"ANSWER"}+""".trimIndent()++/**+ * A real ANSWER from a speaker: the audio index alone, no display block, and three optional fields+ * the TV omitted - including `receiverRtcpEventLog` as an int array where the OFFER's is a boolean.+ */+private val ANSWER_SPEAKER = """+    {"answer":{"castMode":"mirroring","receiverRtcpEventLog":[0],"rtpExtensions":[[]],+      "sendIndexes":[0],"ssrcs":[20002],"udpPort":10008},+      "result":"ok","seqNum":2,"type":"ANSWER"}+""".trimIndent()++class StreamingPayloadsTest {++    @Test+    fun `a tv offer carries audio at index zero and video at index one`() {+        // The order is load-bearing: CreateMirroringOffer puts audio first and the ANSWER's+        // sendIndexes refers back to these numbers.+        val plan = StreamSelection.offer(CastDeviceKind.Tv)+        assertEquals(2, plan.streams.size)+        assertEquals(listOf(0, 1), plan.streams.map { it.index })+        assertEquals(listOf("audio_source", "video_source"), plan.streams.map { it.type })+        assertEquals(listOf("opus", "h264"), plan.streams.map { it.codecName })+        assertTrue(plan.hasVideo)+    }++    @Test+    fun `a speaker and a group are offered audio only`() {+        for (kind in listOf(CastDeviceKind.Speaker, CastDeviceKind.Group)) {+            val plan = StreamSelection.offer(kind)+            assertEquals(listOf("audio_source"), plan.streams.map { it.type }, "$kind")+            assertNull(plan.videoKeys, "$kind")+            assertTrue(StreamSelection.isAudioOnly(kind), "$kind")+        }+    }++    @Test+    fun `payload types are the android hack values, not the obvious ones`() {+        // 96/127 rather than kAudioOpus/kVideoH264: use_android_rtp_hack defaults to true and+        // Chrome never overrides it, so this is what receivers expect.+        val plan = StreamSelection.offer(CastDeviceKind.Tv)+        assertEquals(127, plan.streams[0].rtpPayloadType)+        assertEquals(96, plan.streams[1].rtpPayloadType)+    }++    @Test+    fun `ssrcs come from the documented priority ranges`() {+        // Audio must sort below video so it wins under contention; ComparePriority is numeric.+        repeat(20) {+            val plan = StreamSelection.offer(CastDeviceKind.Tv)+            assertTrue(plan.audioSsrc in 1..50_000, "audio ssrc ${plan.audioSsrc}")+            assertTrue(plan.videoSsrc!! in 50_001..100_000, "video ssrc ${plan.videoSsrc}")+        }+    }++    @Test+    fun `keys are per-stream, sixteen bytes, and hex-encoded on the wire`() {+        val plan = StreamSelection.offer(CastDeviceKind.Tv)+        assertEquals(16, plan.audioKeys.key.size)+        assertEquals(16, plan.audioKeys.ivMask.size)+        // Sharing a key between streams would reuse a keystream across two frame-id sequences.+        assertTrue(plan.audioKeys != plan.videoKeys)+        for (stream in plan.streams) {+            assertEquals(32, stream.aesKey.length)+            assertEquals(32, stream.aesIvMask.length)+            assertTrue(stream.aesKey.all { it in "0123456789abcdef" }, stream.aesKey)+        }+    }++    @Test+    fun `the offer serialises with the field forms the receiver expects`() {+        val json = StreamSelection.offer(CastDeviceKind.Tv).message(seqNum = 2).encode()+        assertTrue(json.contains("\"type\":\"OFFER\""), json)+        assertTrue(json.contains("\"seqNum\":2"), json)+        assertTrue(json.contains("\"castMode\":\"mirroring\""), json)+        assertTrue(json.contains("\"rtpProfile\":\"cast\""), json)+        // Both timebases and the frame rate are rational *strings*, not numbers.+        assertTrue(json.contains("\"timeBase\":\"1/48000\""), json)+        assertTrue(json.contains("\"timeBase\":\"1/90000\""), json)+        assertTrue(json.contains("\"maxFrameRate\":\"30000/1000\""), json)+        // explicitNulls is off, so audio-only fields must be absent from the video stream and+        // vice versa rather than present as null.+        assertTrue(!json.contains("null"), json)+    }++    @Test+    fun `an audio-only offer omits every video field`() {+        val json = StreamSelection.offer(CastDeviceKind.Speaker).message(seqNum = 1).encode()+        assertTrue(!json.contains("maxFrameRate"), json)+        assertTrue(!json.contains("resolutions"), json)+        assertTrue(!json.contains("video_source"), json)+        assertTrue(json.contains("\"bitRate\":128000"), json)+    }++    @Test+    fun `the tv answer parses, including the display block`() {+        val message = assertNotNull(parseAnswer(ANSWER_TV))+        assertEquals("ok", message.result)+        val answer = assertNotNull(message.answer)+        assertEquals(47505, answer.udpPort)+        assertEquals(listOf(0, 1), answer.sendIndexes)+        assertEquals(listOf(20002L, 50002L), answer.ssrcs)+        assertEquals(3840, answer.display?.dimensions?.width)+        // A string, not a number - parsing it as Int would fail the whole ANSWER.+        assertEquals("60", answer.display?.dimensions?.frameRate)+        assertEquals("sender", answer.display?.scaling)+    }++    @Test+    fun `the speaker answer parses despite disagreeing with the tv about optional fields`() {+        val answer = assertNotNull(assertNotNull(parseAnswer(ANSWER_SPEAKER)).answer)+        assertEquals(10008, answer.udpPort)+        assertEquals(listOf(0), answer.sendIndexes)+        // No display block at all: that absence is how "this device has no screen" arrives.+        assertNull(answer.display)+        assertEquals(listOf(0), answer.receiverRtcpEventLog)+        assertEquals(listOf(emptyList<String>()), answer.rtpExtensions)+    }++    @Test+    fun `an error answer is parsed rather than discarded`() {+        val message = assertNotNull(+            parseAnswer(+                """{"type":"ANSWER","seqNum":2,"result":"error",+                   |"error":{"code":3,"description":"bad offer"}}""".trimMargin(),+            ),+        )+        assertEquals("error", message.result)+        assertEquals(3, message.error?.code)+        assertNull(message.answer)+    }++    @Test+    fun `something that is not an answer is not mistaken for one`() {+        assertNull(parseAnswer("""{"type":"STATUS_RESPONSE","seqNum":1}"""))+        assertNull(parseAnswer("not json"))+        // An unknown field must not break parsing; firmware adds them.+        assertIs<AnswerMessage>(+            parseAnswer(+                """{"type":"ANSWER","seqNum":1,"result":"ok","somethingNew":true,+                   |"answer":{"udpPort":1,"sendIndexes":[0],"ssrcs":[2]}}""".trimMargin(),+            ),+        )+    }+}
cast/src/test/java/com/vayunmathur/cast/domain/streaming/StreamingSessionTest.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/domain/streaming/StreamingSessionTest.kt b/cast/src/test/java/com/vayunmathur/cast/domain/streaming/StreamingSessionTest.ktnew file mode 100644index 0000000000..f486be5529--- /dev/null+++ b/cast/src/test/java/com/vayunmathur/cast/domain/streaming/StreamingSessionTest.kt@@ -0,0 +1,206 @@+package com.vayunmathur.cast.domain.streaming++import com.vayunmathur.cast.domain.CastDeviceKind+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++class StreamingSessionTest {++    private fun tvSession() = StreamingSession(StreamSelection.offer(CastDeviceKind.Tv))++    private fun speakerSession() = StreamingSession(StreamSelection.offer(CastDeviceKind.Speaker))++    private fun answer(+        udpPort: Int = 47505,+        sendIndexes: List<Int> = listOf(0, 1),+        ssrcs: List<Long> = listOf(20002, 50002),+    ) = AnswerMessage(+        type = "ANSWER",+        seqNum = 2,+        result = "ok",+        answer = Answer(udpPort = udpPort, sendIndexes = sendIndexes, ssrcs = ssrcs),+    )++    private fun frame(id: Long, size: Int = 4) = EncryptedFrame(+        frameId = FrameId(id),+        referencedFrameId = FrameId(id - 1),+        rtpTimestamp = id * 3000,+        isKeyFrame = id == 0L,+        payload = ByteArray(size),+    )++    @Test+    fun `a two-stream answer produces audio and video routes`() {+        val session = tvSession()+        assertNull(session.onAnswer(answer()))+        val negotiation = assertNotNull(session.negotiation)+        assertEquals(47505, negotiation.udpPort)+        assertEquals(2, negotiation.streams.size)+        assertTrue(negotiation.hasVideo)+        assertEquals(20002L, negotiation.audio?.receiverSsrc)+        assertEquals(50002L, negotiation.video?.receiverSsrc)+        assertEquals(StreamSelection.AUDIO_TIMEBASE, negotiation.audio?.timebase)+        assertEquals(StreamSelection.VIDEO_TIMEBASE, negotiation.video?.timebase)+    }++    @Test+    fun `the answer decides the stream set, not the offer`() {+        // A TV that accepts audio only is entitled to; sending video anyway would be sending to an+        // SSRC nobody is listening on.+        val session = tvSession()+        assertNull(session.onAnswer(answer(sendIndexes = listOf(0), ssrcs = listOf(20002))))+        val negotiation = assertNotNull(session.negotiation)+        assertFalse(negotiation.hasVideo)+        assertEquals(1, negotiation.streams.size)+    }++    @Test+    fun `receiver ssrcs are taken from the answer rather than derived`() {+        // They happened to be ours-plus-one on every observed session. That is the receiver's+        // choice and must not be assumed.+        val session = tvSession()+        session.onAnswer(answer(ssrcs = listOf(9001, 9002)))+        assertEquals(9001L, session.negotiation?.audio?.receiverSsrc)+        assertEquals(9002L, session.negotiation?.video?.receiverSsrc)+    }++    @Test+    fun `an error answer is reported and leaves no negotiation`() {+        val session = tvSession()+        val failure = session.onAnswer(+            AnswerMessage(type = "ANSWER", result = "error", error = AnswerError(3, "nope")),+        )+        val refused = assertIs<NegotiationFailure.Refused>(failure)+        assertEquals(3, refused.code)+        assertEquals("nope", refused.description)+        assertNull(session.negotiation)+    }++    @Test+    fun `an answer accepting nothing we can send fails rather than half-starting`() {+        val session = speakerSession()+        // Index 1 was never offered to a speaker, so there are no keys for it.+        val failure = session.onAnswer(answer(sendIndexes = listOf(1), ssrcs = listOf(50002)))+        assertIs<NegotiationFailure.NoStreams>(failure)+        assertNull(session.negotiation)+    }++    @Test+    fun `a malformed answer is refused`() {+        val session = tvSession()+        assertIs<NegotiationFailure.Malformed>(+            session.onAnswer(answer(sendIndexes = listOf(0, 1), ssrcs = listOf(20002))),+        )+        assertIs<NegotiationFailure.Malformed>(session.onAnswer(answer(udpPort = 0)))+        assertIs<NegotiationFailure.Malformed>(+            session.onAnswer(AnswerMessage(type = "ANSWER", result = "ok", answer = null)),+        )+    }++    @Test+    fun `a nacked packet is resent from the buffer`() {+        val session = tvSession()+        repeat(5) { session.record(frame(it.toLong())) }+        val recovery = session.onFeedback(+            ReceiverFeedback(+                checkpoint = FrameId(1),+                playoutDelayMs = 400,+                nacks = listOf(PacketNack(FrameId(3), 0)),+                ackedFrames = emptyList(),+            ),+        )+        assertEquals(1, recovery.retransmissions.size)+        assertEquals(FrameId(3), recovery.retransmissions.single().frame.frameId)+        assertEquals(listOf(0), recovery.retransmissions.single().packetIds)+        assertFalse(recovery.needsKeyFrame)+    }++    @Test+    fun `the checkpoint drops everything up to and including itself`() {+        val session = tvSession()+        repeat(5) { session.record(frame(it.toLong())) }+        // Frames 0..2 are acknowledged, so a later NACK for frame 2 cannot be answered.+        session.onFeedback(ReceiverFeedback(FrameId(2), 400, emptyList(), emptyList()))+        val recovery = session.onFeedback(+            ReceiverFeedback(FrameId(2), 400, listOf(PacketNack(FrameId(2), 0)), emptyList()),+        )+        assertTrue(recovery.retransmissions.isEmpty())+        // Frame 2 is at or below the checkpoint, so it is history rather than a gap - no key frame.+        assertFalse(recovery.needsKeyFrame)+    }++    @Test+    fun `a nack for a frame that has fallen out of the buffer asks for a key frame`() {+        val session = tvSession()+        // More than the buffer holds, so the earliest frames are gone.+        repeat(80) { session.record(frame(it.toLong())) }+        val recovery = session.onFeedback(+            ReceiverFeedback(FrameId(0), 400, listOf(PacketNack(FrameId(5), 0)), emptyList()),+        )+        assertTrue(recovery.retransmissions.isEmpty())+        assertTrue(recovery.needsKeyFrame)+    }++    @Test+    fun `a whole-frame nack subsumes individual packet nacks for that frame`() {+        val session = tvSession()+        session.record(frame(1, size = 4000))+        val recovery = session.onFeedback(+            ReceiverFeedback(+                checkpoint = FrameId(0),+                playoutDelayMs = 400,+                nacks = listOf(+                    PacketNack(FrameId(1), 1),+                    PacketNack(FrameId(1), CastRtcp.ALL_PACKETS_LOST),+                ),+                ackedFrames = emptyList(),+            ),+        )+        assertEquals(1, recovery.retransmissions.size)+        // null means "every packet", so the individual id must not survive alongside it.+        assertNull(recovery.retransmissions.single().packetIds)+    }++    @Test+    fun `several nacks for one frame are coalesced into a single retransmission`() {+        val session = tvSession()+        session.record(frame(1, size = 4000))+        val recovery = session.onFeedback(+            ReceiverFeedback(+                checkpoint = FrameId(0),+                playoutDelayMs = 400,+                nacks = listOf(PacketNack(FrameId(1), 2), PacketNack(FrameId(1), 0)),+                ackedFrames = emptyList(),+            ),+        )+        assertEquals(1, recovery.retransmissions.size)+        assertEquals(listOf(0, 2), recovery.retransmissions.single().packetIds)+    }++    @Test+    fun `the retransmit buffer is bounded`() {+        // A receiver that stops sending feedback must not be able to grow the heap without limit.+        val session = tvSession()+        repeat(500) { session.record(frame(it.toLong(), size = 1000)) }+        val recovery = session.onFeedback(+            ReceiverFeedback(+                checkpoint = FrameId(0),+                playoutDelayMs = 400,+                nacks = (440L until 500L).map { PacketNack(FrameId(it), 0) },+                ackedFrames = emptyList(),+            ),+        )+        // The most recent frames survive; the oldest are gone.+        assertTrue(recovery.retransmissions.isNotEmpty())+        assertEquals(FrameId(499), recovery.retransmissions.last().frame.frameId)+        assertTrue(+            recovery.retransmissions.none { it.frame.frameId < FrameId(440) },+            "the buffer kept frames it should have dropped",+        )+    }+}