diff --git a/.changeset/single-pc-opus-nack.md b/.changeset/single-pc-opus-nack.md new file mode 100644 index 000000000..b289b26da --- /dev/null +++ b/.changeset/single-pc-opus-nack.md @@ -0,0 +1,5 @@ +--- +"client-sdk-android": patch +--- + +Negotiate Opus NACK on every audio section in single peer connection mode, including send-only offers created before any subscriptions, enabling retransmission of lost audio in both publish and subscribe directions when RED is disabled, such as with end-to-end encryption. Accept server-offered Opus NACK in dual peer connection subscriber answers, with fallback if the modified answer is rejected. diff --git a/livekit-android-sdk/src/main/java/io/livekit/android/room/DualPeerConnectionTransport.kt b/livekit-android-sdk/src/main/java/io/livekit/android/room/DualPeerConnectionTransport.kt index 909a37c3b..7b5d2510d 100644 --- a/livekit-android-sdk/src/main/java/io/livekit/android/room/DualPeerConnectionTransport.kt +++ b/livekit-android-sdk/src/main/java/io/livekit/android/room/DualPeerConnectionTransport.kt @@ -19,7 +19,6 @@ package io.livekit.android.room import io.livekit.android.room.util.MediaConstraintKeys import io.livekit.android.room.util.PeerConnectionStateObservable import io.livekit.android.room.util.createAnswer -import io.livekit.android.room.util.setLocalDescription import io.livekit.android.room.util.waitUntilConnected import io.livekit.android.util.Either import io.livekit.android.util.LKLog @@ -89,14 +88,7 @@ internal class DualPeerConnectionTransport( val answer = subscriber.withPeerConnection { createAnswer(MediaConstraints()) }.nullSafe() if (answer.isRight()) { return answer } - val outcome = subscriber.withPeerConnection { setLocalDescription(answer.value) }.nullSafe() - if (outcome.isRight()) { - // This is a failure - return outcome - } else { - // The caller wants the answer on success - return answer - } + return subscriber.setAnswerWithOpusNack(answer.value, offer) } override suspend fun applyServerAnswer( diff --git a/livekit-android-sdk/src/main/java/io/livekit/android/room/OpusNack.kt b/livekit-android-sdk/src/main/java/io/livekit/android/room/OpusNack.kt new file mode 100644 index 000000000..33b37859b --- /dev/null +++ b/livekit-android-sdk/src/main/java/io/livekit/android/room/OpusNack.kt @@ -0,0 +1,90 @@ +/* + * Copyright 2023-2026 LiveKit, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.livekit.android.room + +import android.gov.nist.javax.sdp.fields.AttributeField +import android.javax.sdp.MediaDescription +import android.javax.sdp.SdpFactory +import io.livekit.android.webrtc.getRtps + +/** + * Adds plain NACK feedback to every Opus payload in an audio section. + * + * The SFU negotiates audio feedback from the first audio section, so single-PC send-only + * sections must advertise it even before any subscriptions exist. Wildcard NACK already + * covers every payload; `nack pli` is separate feedback and does not imply plain NACK. + */ +internal fun ensureOpusNack(mediaDesc: MediaDescription) { + if (mediaDesc.media.mediaType != "audio") return + val opusPayloads = mediaDesc.opusPayloads() + if (opusPayloads.isEmpty()) return + val nackPayloads = mediaDesc.nackPayloads() + if ("*" in nackPayloads) return + + for (payload in opusPayloads - nackPayloads) { + mediaDesc.addAttribute( + AttributeField().apply { + name = "rtcp-fb" + value = "$payload nack" + }, + ) + } +} + +/** Restores offered Opus NACK in the corresponding answer sections, matched by MID. */ +internal fun mungeOpusNackForAnswer(answer: String, offer: String, factory: SdpFactory): String { + if (!offer.contains("a=rtcp-fb:")) return answer + val nackMids = factory.createSessionDescription(offer).getMediaDescriptions(true) + .filterIsInstance() + .filter { section -> + if (section.media.mediaType != "audio") return@filter false + val opus = section.opusPayloads() + val feedback = section.nackPayloads() + opus.isNotEmpty() && ("*" in feedback || opus.any { it in feedback }) + } + .mapNotNull { it.getAttribute("mid") } + .toSet() + if (nackMids.isEmpty()) return answer + val document = factory.createSessionDescription(answer) + var changed = false + for (section in document.getMediaDescriptions(true).filterIsInstance()) { + if (section.getAttribute("mid") !in nackMids) continue + val before = section.toString() + ensureOpusNack(section) + changed = changed || section.toString() != before + } + return if (changed) document.toString() else answer +} + +/** Returns all Opus payload types in this media section. */ +private fun MediaDescription.opusPayloads(): Set = getRtps() + .map { it.second } + .filter { it.codec.equals("opus", ignoreCase = true) } + .map { it.payload.toString() } + .toSet() + +/** Returns payload types with plain NACK feedback, including wildcard feedback. */ +private fun MediaDescription.nackPayloads(): Set = getAttributes(true) + .filterIsInstance() + .filter { it.attribute.name == "rtcp-fb" } + .mapNotNull { attribute -> + val fields = attribute.value?.trim()?.split(rtcpFeedbackWhitespace) ?: return@mapNotNull null + if (fields.size == 2 && fields[1] == "nack") fields[0] else null + } + .toSet() + +private val rtcpFeedbackWhitespace = "\\s+".toRegex() diff --git a/livekit-android-sdk/src/main/java/io/livekit/android/room/PeerConnectionTransport.kt b/livekit-android-sdk/src/main/java/io/livekit/android/room/PeerConnectionTransport.kt index e7ff05ed9..3455b519f 100644 --- a/livekit-android-sdk/src/main/java/io/livekit/android/room/PeerConnectionTransport.kt +++ b/livekit-android-sdk/src/main/java/io/livekit/android/room/PeerConnectionTransport.kt @@ -72,6 +72,7 @@ import kotlin.time.Duration.Companion.milliseconds */ internal class PeerConnectionTransport @AssistedInject +@Suppress("LongParameterList") // Dagger combines assisted settings with injected dependencies. constructor( @Assisted config: RTCConfiguration, @Assisted pcObserver: PeerConnection.Observer, @@ -81,6 +82,7 @@ constructor( connectionFactory: PeerConnectionFactory, private val sdpFactory: SdpFactory, private val rtcThreadToken: RTCThreadToken, + @Assisted private val singlePeerConnection: Boolean = false, ) { private val coroutineScope = CoroutineScope(ioDispatcher + SupervisorJob()) @@ -262,7 +264,9 @@ constructor( } for (mediaDesc in mediaDescs) { if (mediaDesc.media.mediaType == "audio") { - // TODO + if (singlePeerConnection) { + ensureOpusNack(mediaDesc) + } } else if (mediaDesc.media.mediaType == "video") { ensureVideoDDExtensionForSVC(mediaDesc) ensureCodecBitrates( @@ -296,6 +300,22 @@ constructor( } } + /** Applies an answer accepting Opus NACK only on the MIDs that offered it. */ + suspend fun setAnswerWithOpusNack(answer: SessionDescription, offer: SessionDescription): Either { + val munged = mungeOpusNackForAnswer(answer.description, offer.description, sdpFactory) + if (munged != answer.description) { + val description = SessionDescription(answer.type, munged) + val result = withPeerConnection { setLocalDescription(description) } + if (result is Either.Left) return Either.Left(description) + LKLog.w { "Opus NACK answer rejected, falling back to original SDP" } + } + return when (val result = withPeerConnection { setLocalDescription(answer) }) { + is Either.Left -> Either.Left(answer) + is Either.Right -> result + null -> Either.Right("PCT closed") + } + } + private suspend fun setMungedSdp(sdp: SessionDescription, mungedDescription: String, remote: Boolean = false): SessionDescription { val mungedSdp = SessionDescription(sdp.type, mungedDescription) @@ -482,6 +502,7 @@ constructor( config: RTCConfiguration, pcObserver: PeerConnection.Observer, listener: Listener?, + singlePeerConnection: Boolean = false, ): PeerConnectionTransport } } diff --git a/livekit-android-sdk/src/main/java/io/livekit/android/room/RTCEngine.kt b/livekit-android-sdk/src/main/java/io/livekit/android/room/RTCEngine.kt index c8d95b402..8216000b2 100644 --- a/livekit-android-sdk/src/main/java/io/livekit/android/room/RTCEngine.kt +++ b/livekit-android-sdk/src/main/java/io/livekit/android/room/RTCEngine.kt @@ -384,6 +384,7 @@ internal constructor( rtcConfig, publisherObserver, publisherObserver, + singlePeerConnection = connectOptions.singlePeerConnection, ) val connectionStateListener: PeerConnectionStateListener = { newState -> diff --git a/livekit-android-test/src/test/java/io/livekit/android/room/DualPeerConnectionTransportTest.kt b/livekit-android-test/src/test/java/io/livekit/android/room/DualPeerConnectionTransportTest.kt index 515379f92..291194fe7 100644 --- a/livekit-android-test/src/test/java/io/livekit/android/room/DualPeerConnectionTransportTest.kt +++ b/livekit-android-test/src/test/java/io/livekit/android/room/DualPeerConnectionTransportTest.kt @@ -34,12 +34,13 @@ import livekit.LivekitRtc.MediaSectionsRequirement import livekit.LivekitRtc.SignalTarget import livekit.org.webrtc.IceCandidate import livekit.org.webrtc.MediaStreamTrack -import livekit.org.webrtc.MockPeerConnectionFactory import livekit.org.webrtc.PeerConnection import livekit.org.webrtc.PeerConnection.IceConnectionState import livekit.org.webrtc.PeerConnection.PeerConnectionState import livekit.org.webrtc.PeerConnection.RTCConfiguration +import livekit.org.webrtc.PeerConnectionFactory import livekit.org.webrtc.RtpTransceiver +import livekit.org.webrtc.SdpObserver import livekit.org.webrtc.SessionDescription import livekit.org.webrtc.WebRTCInitializer import org.junit.Assert.assertEquals @@ -50,6 +51,7 @@ import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.mockito.kotlin.any +import org.mockito.kotlin.doAnswer import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.spy @@ -85,17 +87,23 @@ class DualPeerConnectionTransportTest { subscriber = createPeerConnectionTransport() } - private fun createPeerConnectionTransport(): PeerConnectionTransport = spy( - PeerConnectionTransport( - config = RTCConfiguration(emptyList()), - pcObserver = mock(), - listener = null, - ioDispatcher = Dispatchers.Unconfined, - connectionFactory = MockPeerConnectionFactory(), - sdpFactory = SdpFactory.getInstance(), - rtcThreadToken = MockRTCThreadToken(), - ), - ) + private fun createPeerConnectionTransport(): PeerConnectionTransport { + val observer = mock() + val pc = spy(MockPeerConnection(RTCConfiguration(emptyList()), observer)) + val factory = mock() + whenever(factory.createPeerConnection(any(), any())).thenReturn(pc) + return spy( + PeerConnectionTransport( + config = RTCConfiguration(emptyList()), + pcObserver = observer, + listener = null, + ioDispatcher = Dispatchers.Unconfined, + connectionFactory = factory, + sdpFactory = SdpFactory.getInstance(), + rtcThreadToken = MockRTCThreadToken(), + ), + ) + } private fun transport( subscriberPrimary: Boolean = true, @@ -226,6 +234,91 @@ class DualPeerConnectionTransportTest { assertSame(answer, subscriberPc.localDesc) } + @Test + fun answerAcceptsOnlyOfferedNackByMidWithReorderedSectionsAndDifferentPayloads() = runTest { + val offer = audioSdp("0", 111, "a=rtcp-fb:111 nack\r\n") + audioSection("1", 112) + val original = stubAudioAnswer(audioSdp("1", 109) + audioSection("0", 110)) + + val result = transport().answerServerOffer(SessionDescription(SessionDescription.Type.OFFER, offer), 7) + + assertTrue(result is Either.Left) + val answer = (result as Either.Left).value + assertSame(answer, subscriberPc.localDesc) + val sections = SdpFactory.getInstance().createSessionDescription(answer.description).getMediaDescriptions(true) + assertFalse(sections[0].toString().contains(" nack")) + assertTrue(sections[1].toString().contains("a=rtcp-fb:110 nack")) + assertFalse(original.description.contains(" nack")) + } + + @Test + fun answerWithoutOfferedNackIsAppliedUnchanged() = runTest { + val original = stubAudioAnswer(audioSdp("0", 109)) + val offer = SessionDescription(SessionDescription.Type.OFFER, audioSdp("0", 111, "a=rtcp-fb:111 nack pli\r\n")) + + val result = transport().answerServerOffer(offer, 7) + + assertTrue(result is Either.Left) + assertSame(original, (result as Either.Left).value) + assertSame(original, subscriberPc.localDesc) + } + + @Test + fun rejectedNackAnswerFallsBackAndReturnsTheAppliedOriginal() = runTest { + val original = stubAudioAnswer(audioSdp("0", 109)) + var rejected = false + val pc = subscriberPc + doAnswer { call -> + val description = call.getArgument(1) + if (description.description.contains("a=rtcp-fb:109 nack")) { + rejected = true + call.getArgument(0).onSetFailure("NACK rejected") + } else { + call.callRealMethod() + } + null + }.whenever(pc).setLocalDescription(any(), any()) + val offer = SessionDescription(SessionDescription.Type.OFFER, audioSdp("0", 111, "a=rtcp-fb:* nack\r\n")) + + val result = transport().answerServerOffer(offer, 7) + + assertTrue(rejected) + assertTrue(result is Either.Left) + assertSame(original, (result as Either.Left).value) + assertSame(original, subscriberPc.localDesc) + } + + @Test + fun failureOfBothAnswersIsReturnedInsteadOfSignalingAnUnappliedAnswer() = runTest { + stubAudioAnswer(audioSdp("0", 109)) + val pc = subscriberPc + doAnswer { call -> + call.getArgument(0).onSetFailure("All answers rejected") + null + }.whenever(pc).setLocalDescription(any(), any()) + val offer = SessionDescription(SessionDescription.Type.OFFER, audioSdp("0", 111, "a=rtcp-fb:111 nack\r\n")) + + val result = transport().answerServerOffer(offer, 7) + + assertTrue(result is Either.Right) + assertNull(subscriberPc.localDesc) + } + + private fun stubAudioAnswer(sdp: String): SessionDescription { + val answer = SessionDescription(SessionDescription.Type.ANSWER, sdp) + val pc = subscriberPc + doAnswer { call -> + call.getArgument(0).onCreateSuccess(answer) + null + }.whenever(pc).createAnswer(any(), any()) + return answer + } + + private fun audioSdp(mid: String, payload: Int, feedback: String = ""): String = + "v=0\r\no=- 1 1 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n" + audioSection(mid, payload, feedback) + + private fun audioSection(mid: String, payload: Int, feedback: String = ""): String = + "m=audio 9 UDP/TLS/RTP/SAVPF $payload\r\na=mid:$mid\r\na=rtpmap:$payload opus/48000/2\r\n$feedback" + @Test fun answerServerOfferPassesOfferId() = runTest { val offer = SessionDescription(SessionDescription.Type.OFFER, "remote_offer") diff --git a/livekit-android-test/src/test/java/io/livekit/android/room/OpusNackOfferTest.kt b/livekit-android-test/src/test/java/io/livekit/android/room/OpusNackOfferTest.kt new file mode 100644 index 000000000..46c939872 --- /dev/null +++ b/livekit-android-test/src/test/java/io/livekit/android/room/OpusNackOfferTest.kt @@ -0,0 +1,190 @@ +/* + * Copyright 2026 LiveKit, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.livekit.android.room + +import android.javax.sdp.MediaDescription +import android.javax.sdp.SdpFactory +import io.livekit.android.test.BaseTest +import io.livekit.android.test.mock.MockPeerConnection +import io.livekit.android.test.mock.MockRTCThreadToken +import io.livekit.android.webrtc.getRtps +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import livekit.org.webrtc.MediaConstraints +import livekit.org.webrtc.PeerConnection +import livekit.org.webrtc.PeerConnectionFactory +import livekit.org.webrtc.SdpObserver +import livekit.org.webrtc.SessionDescription +import livekit.org.webrtc.WebRTCInitializer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.any +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.mock +import org.mockito.kotlin.spy +import org.mockito.kotlin.whenever +import org.robolectric.RobolectricTestRunner + +@ExperimentalCoroutinesApi +@RunWith(RobolectricTestRunner::class) +class OpusNackOfferTest : BaseTest() { + @Before + fun setup() { + WebRTCInitializer.initialize() + } + + @Test + fun singlePeerConnectionOffersAdvertiseNackInEveryAudioDirection() = runTest { + withTransport(singlePeerConnection = true) { transport, _, offers -> + transport.negotiate(MediaConstraints()) + advanceUntilIdle() + + assertEquals(1, offers.size) + assertAudioNack(offers.single().description, expectedSections = 3, enabled = true) + } + } + + @Test + fun dualPeerConnectionOffersKeepNackDisabled() = runTest { + withTransport(singlePeerConnection = false) { transport, _, offers -> + transport.negotiate(MediaConstraints()) + advanceUntilIdle() + + assertEquals(1, offers.size) + assertAudioNack(offers.single().description, expectedSections = 3, enabled = false) + } + } + + @Test + fun sendOnlyOfferAdvertisesNackBeforeAnyReceiveSectionsExist() = runTest { + withTransport( + singlePeerConnection = true, + offerDescription = OFFER.substringBefore("m=audio 9 UDP/TLS/RTP/SAVPF 111"), + ) { transport, _, offers -> + transport.negotiate(MediaConstraints()) + advanceUntilIdle() + + assertEquals(1, offers.size) + assertAudioNack(offers.single().description, expectedSections = 1, enabled = true) + } + } + + @Test + fun rejectedNackMungeFallsBackToTheOriginalOffer() = runTest { + withTransport(singlePeerConnection = true) { transport, pc, offers -> + var rejectedMungedOffer = false + doAnswer { call -> + val observer = call.getArgument(0) + val description = call.getArgument(1) + if (description.description.lineSequence().any { it == "a=rtcp-fb:109 nack" }) { + rejectedMungedOffer = true + observer.onSetFailure("NACK munging rejected") + } else { + call.callRealMethod() + } + null + }.whenever(pc).setLocalDescription(any(), any()) + + transport.negotiate(MediaConstraints()) + advanceUntilIdle() + + assertEquals(1, offers.size) + assertTrue("the munged offer must have been tried first", rejectedMungedOffer) + assertEquals(OFFER, offers.single().description) + assertAudioNack(offers.single().description, expectedSections = 3, enabled = false) + } + } + + private suspend fun TestScope.withTransport( + singlePeerConnection: Boolean, + offerDescription: String = OFFER, + body: suspend TestScope.(PeerConnectionTransport, MockPeerConnection, List) -> Unit, + ) { + val pc = spy(MockPeerConnection(PeerConnection.RTCConfiguration(emptyList()), null)) + doAnswer { call -> + call.getArgument(0).onCreateSuccess(SessionDescription(SessionDescription.Type.OFFER, offerDescription)) + null + }.whenever(pc).createOffer(any(), any()) + val factory = mock() + whenever(factory.createPeerConnection(any(), any())).thenReturn(pc) + val offers = mutableListOf() + val transport = PeerConnectionTransport( + config = PeerConnection.RTCConfiguration(emptyList()), + pcObserver = mock(), + listener = object : PeerConnectionTransport.Listener { + override fun onOffer(sd: SessionDescription, offerId: Int) { + offers.add(sd) + } + }, + ioDispatcher = StandardTestDispatcher(testScheduler), + connectionFactory = factory, + sdpFactory = SdpFactory.getInstance(), + rtcThreadToken = MockRTCThreadToken(), + singlePeerConnection = singlePeerConnection, + ) + try { + body(transport, pc, offers) + assertNotNull(pc.localDesc) + assertEquals(offers.last(), pc.localDesc) + } finally { + transport.close() + } + } + + private fun assertAudioNack(sdp: String, expectedSections: Int, enabled: Boolean) { + val audio = SdpFactory.getInstance().createSessionDescription(sdp) + .getMediaDescriptions(true).filterIsInstance() + .filter { it.media.mediaType == "audio" } + assertEquals(expectedSections, audio.size) + for (section in audio) { + val opus = section.getRtps().map { it.second }.filter { it.codec.equals("opus", ignoreCase = true) } + assertFalse(opus.isEmpty()) + for (mapping in opus) { + val nack = "a=rtcp-fb:${mapping.payload} nack" + assertEquals(enabled, section.toString().lineSequence().any { it == nack }) + } + } + } + + companion object { + val OFFER = """ + v=0 + o=- 1 1 IN IP4 127.0.0.1 + s=- + t=0 0 + m=audio 9 UDP/TLS/RTP/SAVPF 109 + a=mid:0 + a=sendonly + a=rtpmap:109 opus/48000/2 + m=audio 9 UDP/TLS/RTP/SAVPF 111 + a=mid:1 + a=recvonly + a=rtpmap:111 opus/48000/2 + m=audio 9 UDP/TLS/RTP/SAVPF 112 + a=mid:2 + a=sendrecv + a=rtpmap:112 opus/48000/2 + """.trimIndent().replace("\n", "\r\n") + "\r\n" + } +} diff --git a/livekit-android-test/src/test/java/io/livekit/android/room/OpusNackSdpTest.kt b/livekit-android-test/src/test/java/io/livekit/android/room/OpusNackSdpTest.kt new file mode 100644 index 000000000..d2adc961f --- /dev/null +++ b/livekit-android-test/src/test/java/io/livekit/android/room/OpusNackSdpTest.kt @@ -0,0 +1,98 @@ +/* + * Copyright 2026 LiveKit, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.livekit.android.room + +import android.javax.sdp.MediaDescription +import android.javax.sdp.SdpFactory +import org.junit.Assert.assertEquals +import org.junit.Test + +class OpusNackSdpTest { + @Test + fun addsPlainNackToEveryOpusPayloadAndPreservesOtherSections() { + for (direction in listOf("sendonly", "recvonly", "sendrecv", "inactive")) { + for (eol in listOf("\n", "\r\n")) { + val offer = listOf( + "v=0", + "o=- 1 1 IN IP4 127.0.0.1", + "s=-", + "t=0 0", + "m=audio 9 UDP/TLS/RTP/SAVPF 109 112", + "a=$direction", + "a=rtpmap:109 OPUS/48000/2", + "a=rtpmap:112 opus/48000/2", + "a=rtcp-fb:109 nack pli", + "m=video 9 UDP/TLS/RTP/SAVPF 109", + "a=rtpmap:109 VP8/90000", + "m=audio 9 UDP/TLS/RTP/SAVPF 109", + "a=rtpmap:109 PCMU/8000", + "", + ).joinToString(eol) + val document = SdpFactory.getInstance().createSessionDescription(offer) + val sections = document.getMediaDescriptions(true).filterIsInstance() + val original = sections.map { it.toString() } + + sections.forEach(::ensureOpusNack) + + val audio = sections.first().toString().lineSequence().toList() + assertEquals(1, audio.count { it == "a=rtcp-fb:109 nack" }) + assertEquals(1, audio.count { it == "a=rtcp-fb:112 nack" }) + assertEquals(1, audio.count { it == "a=rtcp-fb:109 nack pli" }) + assertEquals(original.drop(1), sections.drop(1).map { it.toString() }) + val once = document.toString() + sections.forEach(::ensureOpusNack) + assertEquals(once, document.toString()) + } + } + } + + @Test + fun preservesExistingPlainAndWildcardNackIncludingWhitespace() { + for (feedback in listOf("109 nack", "* nack", "109 nack", "109\tnack")) { + val section = audioSection(feedback) + val original = section.toString() + + ensureOpusNack(section) + + assertEquals(original, section.toString()) + } + } + + @Test + fun addsNackOnlyToPayloadsNotAlreadyCovered() { + val section = SdpFactory.getInstance().createSessionDescription( + "m=audio 9 UDP/TLS/RTP/SAVPF 109 112\r\n" + + "a=rtpmap:109 opus/48000/2\r\n" + + "a=rtpmap:112 opus/48000/2\r\n" + + "a=rtcp-fb:112 nack\r\n", + ).getMediaDescriptions(true).filterIsInstance().single() + + ensureOpusNack(section) + + val lines = section.toString().lineSequence().toList() + assertEquals(1, lines.count { it == "a=rtcp-fb:109 nack" }) + assertEquals(1, lines.count { it == "a=rtcp-fb:112 nack" }) + } + + private fun audioSection(feedback: String): MediaDescription { + return SdpFactory.getInstance().createSessionDescription( + "m=audio 9 UDP/TLS/RTP/SAVPF 109\r\n" + + "a=rtpmap:109 opus/48000/2\r\n" + + "a=rtcp-fb:$feedback\r\n", + ).getMediaDescriptions(true).filterIsInstance().single() + } +}