cast: parse compound RTCP and the right feedback packet type
- Commit
0462cbd039593d51752fb7f44decc33698304041- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-21 15:10 UTC (3 months ago)
- Parents
b2836ca
Diff
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.ktindex 9f6ec3c0c7..98e22867dd 100644--- a/cast/src/main/java/com/vayunmathur/cast/domain/streaming/CastRtcp.kt+++ b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/CastRtcp.kt@@ -20,9 +20,19 @@ object CastRtcp { private const val TYPE_SENDER_REPORT = 200 private const val TYPE_APPLICATION_DEFINED = 204 - /** `RtcpSubtype::kFeedback`, carried in the report-count field. */+ /**+ * `kPayloadSpecific`. **This**, not [TYPE_APPLICATION_DEFINED], is what carries Cast 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 @@ -67,24 +77,84 @@ object CastRtcp { } /**- * Parse a receiver feedback packet, or return null if this is not one.+ * Parse a datagram of RTCP from the receiver.+ *+ * **RTCP is compound**: one datagram is the concatenation of several RTCP packets, and a real+ * receiver sends a Receiver Report and Extended Reports before the Cast feedback. Reading only+ * the first sub-packet therefore 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 offset = 0+ var feedback: ReceiverFeedback? = null+ var pictureLoss = false+ while (offset + COMMON_HEADER_SIZE <= packet.size) {+ val byte0 = packet[offset].toInt() and 0xff+ if (byte0 and 0b1110_0000 != VERSION_AND_PADDING) return feedback+ 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 feedback+ if (type == TYPE_PAYLOAD_SPECIFIC) {+ when (countOrSubtype) {+ SUBTYPE_FEEDBACK -> parseFeedbackPayload(+ packet,+ payloadStart,+ payloadSize,+ receiverSsrc,+ senderSsrc,+ maxFrameId,+ )?.let { feedback = it }+ // "Send me a key frame": the receiver cannot decode anything it currently has.+ SUBTYPE_PICTURE_LOSS_INDICATOR -> pictureLoss = true+ }+ }+ offset = payloadStart + payloadSize+ }+ 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+ }+ }++ /**+ * 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. */- fun parseFeedback(+ private fun parseFeedbackPayload( packet: ByteArray,+ start: Int,+ size: Int, 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 (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@@ -99,7 +169,7 @@ object CastRtcp { val playoutDelayMs = packet.getShort(i) i += 2 - if (packet.size - i < LOSS_FIELD_SIZE * lossFieldCount) return null+ if (end - i < LOSS_FIELD_SIZE * lossFieldCount) return null val nacks = mutableListOf<PacketNack>() repeat(lossFieldCount) { val frameId = expandGreaterThan(checkpoint, packet[i].toInt() and 0xff)@@ -122,12 +192,12 @@ object CastRtcp { // 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) {+ 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 (packet.size - i >= octets) {+ if (end - 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@@ -180,6 +250,8 @@ data class ReceiverFeedback( 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, ) internal fun ByteArray.getShort(offset: Int): Int =
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.ktindex db9f087099..c64048e2cf 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt@@ -249,7 +249,7 @@ class MirrorEngine( private fun handleFeedback(packet: ByteArray) { for (stream in negotiation.streams) { val sender = senders[stream.kind] ?: continue- val feedback = CastRtcp.parseFeedback(+ val feedback = CastRtcp.parse( packet = packet, receiverSsrc = stream.receiverSsrc, senderSsrc = stream.senderSsrc,@@ -261,13 +261,17 @@ class MirrorEngine( TAG, "${stream.kind} feedback checkpoint=${feedback.checkpoint} " + "nacks=${feedback.nacks.size} acks=${feedback.ackedFrames.size} " +- "playoutDelay=${feedback.playoutDelayMs}",+ "pli=${feedback.pictureLoss} playoutDelay=${feedback.playoutDelayMs}", ) } val recovery = session.onFeedback(feedback) sender.retransmit(recovery.retransmissions)- if (recovery.needsKeyFrame && stream.kind == StreamKind.Video) {- Log.i(TAG, "receiver fell behind the retransmit buffer; forcing a key frame")+ if (stream.kind == StreamKind.Video &&+ (recovery.needsKeyFrame || feedback.pictureLoss)+ ) {+ // Either the receiver asked outright (PLI) or it has fallen further behind than the+ // retransmit buffer can repair. A key frame is the only way out of both.+ Log.i(TAG, "key frame requested (pli=${feedback.pictureLoss})") videoEncoder?.requestKeyFrame() } return
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.ktindex b670a6b4b3..8f26dd3c3e 100644--- a/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastRtcpTest.kt+++ b/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastRtcpTest.kt@@ -2,6 +2,7 @@ package com.vayunmathur.cast.domain.streaming import kotlin.test.Test import kotlin.test.assertEquals+import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue@@ -9,17 +10,26 @@ import kotlin.test.assertTrue private const val RECEIVER_SSRC = 20_002L private const val SENDER_SSRC = 20_001L +private const val TYPE_PAYLOAD_SPECIFIC = 206+private const val SUBTYPE_PLI = 1+private const val SUBTYPE_FEEDBACK = 15+ class CastRtcpTest { /**- * Builds a feedback packet the way a receiver does, so the parser is exercised against the- * documented layout rather than against itself.+ * Builds a compound RTCP datagram the way a receiver does: a Receiver Report first, then the+ * Cast feedback as a `kPayloadSpecific` (206) sub-packet.+ *+ * The leading report is not decoration - a parser that only reads the first sub-packet finds no+ * feedback at all, which is the bug this shape exists to catch. */ private fun feedback( checkpoint: Int, playoutDelayMs: Int = 400, lossFields: List<Triple<Int, Int, Int>> = emptyList(), ackBitVector: List<Int>? = null,+ withLeadingReport: Boolean = true,+ pictureLoss: Boolean = false, ): ByteArray { val body = mutableListOf<Byte>() fun int32(v: Long) {@@ -46,14 +56,39 @@ class CastRtcpTest { 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+ // Padded to a word boundary, because the length field counts 32-bit words.+ while (body.size % 4 != 0) body += 0+ val out = mutableListOf<Byte>()+ if (withLeadingReport) out += receiverReport()+ if (pictureLoss) out += subPacket(SUBTYPE_PLI, TYPE_PAYLOAD_SPECIFIC, pliBody())+ out += subPacket(SUBTYPE_FEEDBACK, TYPE_PAYLOAD_SPECIFIC, body)+ return out.toByteArray()+ }++ /** A Receiver Report (201) with no report blocks, which is what leads a real datagram. */+ private fun receiverReport(): List<Byte> =+ subPacket(0, 201, mutableListOf<Byte>().also { b ->+ for (shift in intArrayOf(24, 16, 8, 0)) b += (RECEIVER_SSRC ushr shift).toByte()+ })++ private fun pliBody(): MutableList<Byte> = mutableListOf<Byte>().also { b ->+ for (shift in intArrayOf(24, 16, 8, 0)) b += (RECEIVER_SSRC ushr shift).toByte()+ for (shift in intArrayOf(24, 16, 8, 0)) b += (SENDER_SSRC ushr shift).toByte()+ }++ private fun subPacket(subtype: Int, type: Int, payload: List<Byte>): List<Byte> {+ val header = listOf(+ (((0b100 shl 5)) or subtype).toByte(),+ type.toByte(),+ ((payload.size / 4) ushr 8).toByte(),+ (payload.size / 4).toByte(), )- return header + body.toByteArray()+ return header + payload } + private fun parse(packet: ByteArray, maxFrameId: FrameId) =+ CastRtcp.parse(packet, RECEIVER_SSRC, SENDER_SSRC, maxFrameId)+ @Test fun `a sender report has the documented layout`() { val packet = CastRtcp.senderReport(@@ -79,7 +114,7 @@ class CastRtcpTest { @Test fun `a bare checkpoint parses`() { val parsed = assertNotNull(- CastRtcp.parseFeedback(feedback(checkpoint = 5), RECEIVER_SSRC, SENDER_SSRC, FrameId(5)),+ parse(feedback(checkpoint = 5), FrameId(5)), ) assertEquals(FrameId(5), parsed.checkpoint) assertEquals(400, parsed.playoutDelayMs)@@ -92,12 +127,7 @@ class CastRtcpTest { // 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),- ),+ parse(feedback(checkpoint = 10, lossFields = listOf(Triple(11, 3, 0b101))), FrameId(12)), ) assertEquals( listOf(@@ -112,12 +142,7 @@ class CastRtcpTest { @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),- ),+ parse(feedback(checkpoint = 1, lossFields = listOf(Triple(2, 0xffff, 0xff))), FrameId(3)), ) assertEquals(1, parsed.nacks.size) assertTrue(parsed.nacks.single().isWholeFrame)@@ -129,12 +154,7 @@ class CastRtcpTest { // 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),- ),+ parse(feedback(checkpoint = 4, ackBitVector = listOf(0b0000_0101)), FrameId(10)), ) assertEquals(listOf(FrameId(6), FrameId(8)), parsed.ackedFrames) }@@ -142,53 +162,71 @@ class CastRtcpTest { @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),- ),+ parse(feedback(checkpoint = 0, ackBitVector = listOf(0b0000_0001, 0b0000_0001)), 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)+ // openscreen is explicit about this for backwards compatibility. The bytes have to sit+ // inside the feedback sub-packet's own length to be "trailing" rather than a new sub-packet. val parsed = assertNotNull(- CastRtcp.parseFeedback(packet, RECEIVER_SSRC, SENDER_SSRC, FrameId(3)),+ parse(feedback(checkpoint = 3, ackBitVector = null), FrameId(3)), ) assertEquals(FrameId(3), parsed.checkpoint) assertTrue(parsed.ackedFrames.isEmpty()) } + @Test+ fun `feedback is found after a leading receiver report`() {+ // The bug this whole test file was reshaped for. A real receiver leads with a Receiver+ // Report, so a parser that reads only the first sub-packet reports no feedback ever - which+ // is indistinguishable from a receiver that is not answering at all.+ val compound = feedback(checkpoint = 7, withLeadingReport = true)+ val parsed = assertNotNull(parse(compound, FrameId(7)))+ assertEquals(FrameId(7), parsed.checkpoint)+ // And it still works when the feedback happens to come first.+ assertNotNull(parse(feedback(checkpoint = 7, withLeadingReport = false), FrameId(7)))+ }++ @Test+ fun `a picture loss indicator is surfaced even with no feedback block`() {+ // PLI means "I cannot decode anything I have" - the only answer is a key frame, so it must+ // not be swallowed.+ val parsed = assertNotNull(+ parse(feedback(checkpoint = 3, pictureLoss = true), FrameId(3)),+ )+ assertTrue(parsed.pictureLoss)+ assertFalse(assertNotNull(parse(feedback(checkpoint = 3), FrameId(3))).pictureLoss)+ }+ @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)))+ assertNull(CastRtcp.parse(packet, 999L, SENDER_SSRC, FrameId(1)))+ assertNull(CastRtcp.parse(packet, RECEIVER_SSRC, 999L, FrameId(1))) // A sender report is not feedback. assertNull(- CastRtcp.parseFeedback(+ CastRtcp.parse( 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)),- )+ // Truncated mid-header.+ assertNull(CastRtcp.parse(packet.copyOfRange(0, 6), 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()+ fun `a loss field count that overruns its own sub-packet is refused`() {+ // Claiming four loss fields while carrying none must not read past the sub-packet, nor+ // wander into whatever follows it in the compound datagram.+ val packet = feedback(checkpoint = 1, withLeadingReport = false).copyOf()+ // Byte 4 starts the payload; +12 skips the two SSRCs and 'CAST', +1 skips the checkpoint. packet[4 + 12 + 1] = 4- assertNull(CastRtcp.parseFeedback(packet, RECEIVER_SSRC, SENDER_SSRC, FrameId(1)))+ assertNull(parse(packet, FrameId(1))) } @Test@@ -201,12 +239,7 @@ class CastRtcpTest { ) assertEquals(FrameId(255), CastRtcp.expandLessThanOrEqual(FrameId(256), 255)) val parsed = assertNotNull(- CastRtcp.parseFeedback(- feedback(checkpoint = 260 and 0xff),- RECEIVER_SSRC,- SENDER_SSRC,- FrameId(262),- ),+ parse(feedback(checkpoint = 260 and 0xff), FrameId(262)), ) assertEquals(FrameId(260), parsed.checkpoint) }