Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/flexfec-subscription.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"client-sdk-android": minor
---

Add `LiveKit.enableFlexFec` to negotiate FlexFEC, and `RemoteTrackPublication.setFecProtection` to request FlexFEC repair packets from the server for a subscribed video track, with disabled, adaptive, fixed and minimum modes and low, medium and high levels.
5 changes: 5 additions & 0 deletions .changeset/webrtc-150-7871-08.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"client-sdk-android": patch
---

Update libwebrtc to 150.7871.08.
2 changes: 1 addition & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[versions]
webrtc = "150.7871.04"
webrtc = "150.7871.08"

androidJainSipRi = "1.3.0-91"
androidx-activity = "1.9.0"
Expand Down
21 changes: 21 additions & 0 deletions livekit-android-sdk/src/main/java/io/livekit/android/LiveKit.kt
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,27 @@ object LiveKit {
@JvmStatic
var enableWebRTCLogging: Boolean = false

/**
* Enables FlexFEC forward error correction for video.
*
* When enabled, connections negotiate `flexfec-03`, which lets subscribed video tracks
* receive repair packets from the server, see
* [io.livekit.android.room.track.RemoteTrackPublication.setFecProtection].
* Video tracks published without simulcast also send FlexFEC, at a rate WebRTC adapts to the
* reported loss; WebRTC does not protect simulcast tracks with FlexFEC.
* Disabled by default.
*
* This is a process-wide WebRTC setting, so it must be set before the first [Room] is
* created or [init] is called; later changes have no effect.
*
* ```
* LiveKit.enableFlexFec = true
* val room = LiveKit.create(appContext)
* ```
*/
@JvmStatic
var enableFlexFec: Boolean = false

/**
* Certain WebRTC classes need to be initialized prior to use.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,10 @@ internal object RTCModule {
* it.
*/
private const val DEFAULT_FIELD_TRIALS = "WebRTC-IceHandshakeDtls/Enabled/"
private const val FLEXFEC_FIELD_TRIALS = "WebRTC-FlexFEC-03-Advertised/Enabled/WebRTC-FlexFEC-03/Enabled/"

private val fieldTrials: String
get() = if (LiveKit.enableFlexFec) DEFAULT_FIELD_TRIALS + FLEXFEC_FIELD_TRIALS else DEFAULT_FIELD_TRIALS
Comment on lines +96 to +97

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Downstream FlexFEC bypasses opt-in

With enableFlexFec off, libwebrtc still accepts flexfec-03 in receive-only video offers. On a downstream-enabled server, setFecProtection can start repair traffic despite the app leaving the flag off.

Learn more

In the pinned libwebrtc build, GetDefaultSupportedFormats adds flexfec-03 for decoders even when the advertisement trial is unset. CodecVendor::GetVideoCodecsForAnswer uses that receive codec list for receive-only answers on the default SDP path. WebRtcVideoReceiveChannel::ConfigureReceiverRtp also accepts a negotiated repair stream when the trial is unset. The SDK's answerServerOffer applies the native answer unchanged, and the track settings request sends FEC without checking the flag latched at initialization.

Example: Leave the flag at its default, join a two-peer-connection room on a server that offers downstream FlexFEC, and request Fixed(HIGH) on a subscribed video. The downstream codec can negotiate and the request can activate repairs instead of being a no-op.

Recommended fix: If the flag is meant to gate negotiation, exclude flexfec-03 from the subscriber's negotiated codecs when disabled. If receive negotiation is intentionally native-default, document that distinction and gate outgoing FEC requests on the latched opt-in if they must remain a no-op. Cover the default-off receive case with an integration test.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.


/**
* Certain classes require libwebrtc to be initialized prior to use.
Expand Down Expand Up @@ -122,7 +126,7 @@ internal object RTCModule {
PeerConnectionFactory.InitializationOptions
.builder(appContext)
.setNativeLibraryName("lkjingle_peerconnection_so")
.setFieldTrials(DEFAULT_FIELD_TRIALS)
.setFieldTrials(fieldTrials)
.setInjectableLogger(
{ s, severity, s2 ->
if (!LiveKit.enableWebRTCLogging) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -529,12 +529,14 @@ constructor(
sendRequest(request)
}

@Suppress("LongParameterList")
fun sendUpdateTrackSettings(
sid: String,
disabled: Boolean,
videoDimensions: Track.Dimensions?,
videoQuality: LivekitModels.VideoQuality?,
fps: Int?,
fecProtection: LivekitRtc.FECProtection? = null,
) {
val trackSettings = LivekitRtc.UpdateTrackSettings.newBuilder()
.addTrackSids(sid)
Expand All @@ -553,6 +555,10 @@ constructor(
if (fps != null) {
setFps(fps)
}

if (fecProtection != null) {
fec = fecProtection
}
}

val request = LivekitRtc.SignalRequest.newBuilder()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* 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.track

import livekit.LivekitRtc

/**
* Proactive FlexFEC protection the server adds to a subscribed video track.
*
* The server sends repair packets alongside the track's media, so the receiver can recover lost
* packets without waiting for a retransmission.
*
* @see RemoteTrackPublication.setFecProtection
*/
sealed class FecProtection {
/** No repair packets. This is the default. */
data object Disabled : FecProtection()

/**
* Protection follows the observed packet loss, using the same algorithm as libwebrtc.
*/
data object Adaptive : FecProtection()

/**
* Constant protection at [level], regardless of packet loss.
*/
data class Fixed(val level: FecProtectionLevel) : FecProtection()

/**
* Protection never drops below [level]. It rises adaptively under higher packet loss, and
* returns to [level] once the loss subsides.
*/
data class Minimum(val level: FecProtectionLevel) : FecProtection()

internal fun toProto(): LivekitRtc.FECProtection {
val builder = LivekitRtc.FECProtection.newBuilder()
when (this) {
Disabled -> builder.mode = LivekitRtc.FECProtectionMode.FEC_MODE_DISABLED
Adaptive -> builder.mode = LivekitRtc.FECProtectionMode.FEC_MODE_ADAPTIVE
is Fixed -> {
builder.mode = LivekitRtc.FECProtectionMode.FEC_MODE_FIXED
builder.level = level.toProto()
}

is Minimum -> {
builder.mode = LivekitRtc.FECProtectionMode.FEC_MODE_MINIMUM
builder.level = level.toProto()
}
}
return builder.build()
}
}

/**
* The share of packets spent on FlexFEC repairs, used by [FecProtection.Fixed] and
* [FecProtection.Minimum].
*
* Frames that span only a few packets get proportionally more repairs.
*/
enum class FecProtectionLevel {
/** Approximately 15% repair packet overhead. */
LOW,

/** Approximately 25% repair packet overhead. */
MEDIUM,

/** Approximately 35% repair packet overhead. */
HIGH,
;

internal fun toProto(): LivekitRtc.FECProtectionLevel {
return when (this) {
LOW -> LivekitRtc.FECProtectionLevel.FEC_LEVEL_LOW
MEDIUM -> LivekitRtc.FECProtectionLevel.FEC_LEVEL_MEDIUM
HIGH -> LivekitRtc.FECProtectionLevel.FEC_LEVEL_HIGH
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2023-2025 LiveKit, Inc.
* 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.
Expand Down Expand Up @@ -75,6 +75,15 @@ class RemoteTrackPublication(
private var videoDimensions: Track.Dimensions? = null
private var fps: Int? = null

/**
* The FlexFEC protection requested with [setFecProtection].
*/
val fecProtection: FecProtection
get() = requestedFecProtection ?: FecProtection.Disabled

// null until requested, so updates leave the server's setting unchanged
private var requestedFecProtection: FecProtection? = null

var subscriptionAllowed: Boolean = true
internal set

Expand Down Expand Up @@ -204,6 +213,29 @@ class RemoteTrackPublication(
sendUpdateTrackSettings.invoke()
}

/**
* Requests proactive FlexFEC repair packets from the server for this video track.
*
* Repairs let the receiver recover lost packets without waiting for a retransmission, at the
* cost of extra bandwidth. The protection changes without renegotiation, and is applied even
* when the track's quality is managed by adaptive stream.
*
* Repairs are only sent when the server has downstream FlexFEC enabled and FlexFEC was
* negotiated, which requires [io.livekit.android.LiveKit.enableFlexFec]. Otherwise the request
* has no effect.
*
* ```
* publication.setFecProtection(FecProtection.Minimum(FecProtectionLevel.MEDIUM))
* ```
*/
fun setFecProtection(protection: FecProtection) {
if (!subscribed || track !is VideoTrack || protection == requestedFecProtection) {
return
}
requestedFecProtection = protection
sendUpdateTrackSettings.invoke()
Comment on lines +231 to +236

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Lost FlexFEC protection after resubscribe

After a completed unsubscribe, setFecProtection drops an identical request when the app resubscribes without adaptive stream. The server starts the new subscription with repairs off, but fecProtection still reports the previous request.

Learn more

The server deletes the subscription and its settings when an explicit unsubscribe finishes. In the companion server implementation, SubscriptionManager.reconcileMediaTrackSubscriptions removes subscriptions once needsCleanup reports that the closed track is no longer desired. However, setSubscribed leaves the client's publication and its cached request intact. On resubscribe, addSubscribedMediaTrack looks up the same publication by SID and attaches the track. With adaptive stream off, the track setter does not send settings, and repeating the request hits the equality check.

Example: Set Fixed(HIGH) on a subscribed camera. Unsubscribe long enough for the server to finish removing the subscription, then resubscribe and apply Fixed(HIGH) again. The getter still reports Fixed(HIGH), but the new subscription gets no repair packets until another setting sends the cached request.

Recommended fix: Replay a non-null FEC request when resubscribing, including with adaptive stream disabled, or scope request deduplication to the current subscription. Add a test that unsubscribes and resubscribes to the same SID, then checks that the prior mode and level are sent again.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

}

private fun handleVisibilityChanged(isVisible: Boolean) {
disabled = !isVisible
sendUpdateTrackSettings.invoke()
Expand Down Expand Up @@ -237,6 +269,7 @@ class RemoteTrackPublication(
videoDimensions,
videoQuality?.toProto(),
fps,
requestedFecProtection?.toProto(),
)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2024 LiveKit, Inc.
* Copyright 2024-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.
Expand All @@ -23,7 +23,8 @@ class MockRtpParameters(
headerExtensions: MutableList<HeaderExtension>?,
encodings: MutableList<Encoding>?,
codecs: MutableList<Codec>?,
) : RtpParameters(transactionId, degradationPreference, rtcp, headerExtensions, encodings, codecs) {
fecProtection: FecProtection? = null,
) : RtpParameters(transactionId, degradationPreference, fecProtection, rtcp, headerExtensions, encodings, codecs) {
class MockRtcp(cname: String?, reducedSize: Boolean) : Rtcp(cname, reducedSize)
class MockHeaderExtension(uri: String?, id: Int, encrypted: Boolean) : HeaderExtension(uri, id, encrypted)
class MockCodec(payloadType: Int, name: String?, kind: MediaStreamTrack.MediaType?, clockRate: Int?, numChannels: Int?, parameters: MutableMap<String, String>?) :
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2023-2025 LiveKit, Inc.
* 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.
Expand Down Expand Up @@ -84,6 +84,104 @@ class RemoteTrackPublicationTest : MockE2ETest() {
assertEquals(VideoQuality.LOW, lastRequest.trackSetting.quality)
}

private suspend fun subscribeRemoteVideo(): RemoteTrackPublication {
connect()

wsFactory.listener.onMessage(
wsFactory.ws,
TestData.PARTICIPANT_JOIN.toOkioByteString(),
)

room.onAddTrack(
MockRtpReceiver.create(),
MockVideoStreamTrack(),
arrayOf(
MockMediaStream(
id = createMediaStreamId(
TestData.REMOTE_PARTICIPANT.sid,
TestData.REMOTE_VIDEO_TRACK.sid,
),
),
),
)

return room.remoteParticipants.values.first()
.videoTrackPublications.first()
.first as RemoteTrackPublication
}

private fun lastTrackSetting(): LivekitRtc.UpdateTrackSettings {
val requests = wsFactory.ws.sentRequests.map {
LivekitRtc.SignalRequest.newBuilder().mergeFrom(it.toPBByteString()).build()
}
val lastTrackSetting = requests.lastOrNull { it.hasTrackSetting() }
assertTrue("no track setting sent", lastTrackSetting != null)
return lastTrackSetting!!.trackSetting
}

@Test
fun fecProtectionOmittedUntilRequested() = runTest {
room.adaptiveStream = false
val remoteVideoPub = subscribeRemoteVideo()
advanceUntilIdle()
wsFactory.ws.clearRequests()

remoteVideoPub.setVideoFps(30)
advanceUntilIdle()

assertFalse(lastTrackSetting().hasFec())
assertEquals(FecProtection.Disabled, remoteVideoPub.fecProtection)
}

@Test
fun fecProtectionSentAndKept() = runTest {
room.adaptiveStream = false
val remoteVideoPub = subscribeRemoteVideo()
advanceUntilIdle()
wsFactory.ws.clearRequests()

remoteVideoPub.setFecProtection(FecProtection.Fixed(FecProtectionLevel.HIGH))
advanceUntilIdle()

assertEquals(FecProtection.Fixed(FecProtectionLevel.HIGH), remoteVideoPub.fecProtection)
assertTrue(lastTrackSetting().hasFec())
assertEquals(LivekitRtc.FECProtectionMode.FEC_MODE_FIXED, lastTrackSetting().fec.mode)
assertEquals(LivekitRtc.FECProtectionLevel.FEC_LEVEL_HIGH, lastTrackSetting().fec.level)

// later settings updates keep the requested level
remoteVideoPub.setVideoFps(30)
advanceUntilIdle()
assertEquals(30, lastTrackSetting().fps)
assertEquals(LivekitRtc.FECProtectionMode.FEC_MODE_FIXED, lastTrackSetting().fec.mode)
assertEquals(LivekitRtc.FECProtectionLevel.FEC_LEVEL_HIGH, lastTrackSetting().fec.level)

remoteVideoPub.setFecProtection(FecProtection.Adaptive)
advanceUntilIdle()
assertEquals(LivekitRtc.FECProtectionMode.FEC_MODE_ADAPTIVE, lastTrackSetting().fec.mode)
assertEquals(LivekitRtc.FECProtectionLevel.FEC_LEVEL_UNSPECIFIED, lastTrackSetting().fec.level)

// disabling is sent explicitly rather than omitted
remoteVideoPub.setFecProtection(FecProtection.Disabled)
advanceUntilIdle()
assertTrue(lastTrackSetting().hasFec())
assertEquals(LivekitRtc.FECProtectionMode.FEC_MODE_DISABLED, lastTrackSetting().fec.mode)
}

@Test
fun fecProtectionWithAdaptiveStream() = runTest {
room.adaptiveStream = true
val remoteVideoPub = subscribeRemoteVideo()
advanceUntilIdle()
wsFactory.ws.clearRequests()

// applies even when adaptive stream manages the track's quality
remoteVideoPub.setFecProtection(FecProtection.Minimum(FecProtectionLevel.MEDIUM))
advanceUntilIdle()

assertEquals(LivekitRtc.FECProtectionMode.FEC_MODE_MINIMUM, lastTrackSetting().fec.mode)
assertEquals(LivekitRtc.FECProtectionLevel.FEC_LEVEL_MEDIUM, lastTrackSetting().fec.level)
}

@Test
fun subscriptionStatus() = runTest {
connect()
Expand Down
2 changes: 1 addition & 1 deletion protocol
Loading