Files
livekit/pkg/rtc/subscriptionmanager.go
T
ee75008bea Generate downstream FlexFEC with per-track protection modes (#5195)
* Do not recover FlexFEC from RTX repaired packets

A packet repaired from RTX takes its header from the RTX packet: libwebrtc
adds a MID to retransmissions until the RTX SSRC is acknowledged, and sets
abs-send-time and transport-cc at send time. The stored packet therefore
differs from the media the publisher protected, so using it as a protected
packet recovered the wrong length, failing with "invalid recovered packet
size", or silently corrupted the recovered packet's header extensions when
the length happened to match.

Like libwebrtc's FlexfecReceiver, which skips packets recovered by RTX, mark
RTX repaired sequence numbers and treat them as missing for FEC recovery.
They are still forwarded and update NACK state as before.

With a libwebrtc publisher at 10% upstream loss, every recovery attempt in a
block containing a retransmitted packet failed; with retransmissions excluded
recoveries succeed.

* Move RTX repair tracking into BufferBase

Keep the RTX repaired history, its lookup and the publisher sequence number
extension in BufferBase, so every buffer built on it, such as the relay, can
exclude RTX repaired packets from FlexFEC recovery the same way. The history
is now cleared with the rest of the sequence number state when the stream
restarts.

Buffer only marks repaired packets from writeRTX. Packets recovered by FEC
also enter with isRTX set, but they are exact reconstructions and stay
usable, so marking is explicit rather than tied to that flag.

* Keep RTX-repaired history safe with large packet caches

The RTX repair history had 512 fixed slots. With a larger video packet
cache, e.g. packet_buffer_size_video: 1500, two cached repairs could share
a slot, the earlier mark was lost, and FlexFEC could recover from the
altered retransmission.

- Size the history from the video packet cache, at least 512 slots, and
  allocate it on the first repair.
- When a later repair reuses a slot, the earlier packet counts as repaired:
  losing a recovery is better than corrupting one.
- Do not mark a retransmission of a packet that is already cached. The
  bucket rejects it as a duplicate and keeps the exact packet, which stays
  usable for recovery.
- Mark a repair before ingesting it and do not feed RTX repaired packets to
  the FEC decoder, as BufferBase now feeds ingested media to the decoder.

* Generate downstream FlexFEC with per-track protection presets

Generate FlexFEC-03 repairs for subscribed video tracks. Subscribers select
none (default), low, medium or high through UpdateTrackSettings.fec; repairs
require rtc.flexfec.downstream_enabled and negotiated flexfec-03 support.

Generate repairs at each frame marker, splitting large frames into blocks of
at most 48 packets, with upstream Q8 repair-count rounding and at least one
repair per block. Reserve measured repair overhead during layer allocation
and charge repair traffic to pacing, bandwidth estimation and metrics.

Carry repair sequence state through the DownTrack GetState/SeedState handoff,
apply subscriber settings from immutable snapshots, and preserve upstream FEC
on shared sendrecv codec lists when downstream generation is disabled.

This squashes the three commits of dc/feature/fec_down (38a67502, d269ac59,
7b02897c) and rebases them onto master. Conflict resolution:
- pacer.Packet keeps master's held-extension scratch next to the FEC field,
  and the DownTrack sets FEC on the pacer packet master now creates before
  adding extensions
- DownTrackParams and subscriber config keep master's RTXBudget
- configureSenderParams uses master's enableFlexFEC name
- tests follow master: pion/transport v5 packetio, mid-less receivers skipped
  when restricting codecs, and settings compared by value since they are
  stored as merged snapshots

Requires the UpdateTrackSettings.fec field from livekit/protocol#1794, which
is not in the pinned protocol version yet.

* Add end-to-end tests for downstream FlexFEC

Publish a VP8 track through the SFU to a FlexFEC-capable subscriber,
simulate downstream loss before the subscriber's receive buffer, and recover
the dropped packets from the repairs actually sent, using the same FlexFEC-03
decoder as upstream recovery. RTX is dropped meanwhile so retransmissions
cannot fill the gaps.

The test checks that no repairs are sent before a preset is selected, that
every preset recovers isolated losses bit-exactly, that presets change
without renegotiation, and that a subscriber which declines flexfec-03
receives media but no repairs. Frames alternate between one and five
packets, so repair counts match the Q8 rounding for both block sizes.

The test client gains a subscriber RTP filter to simulate loss and accessors
for the subscriber descriptions. The tests use their own ports so they can
run next to a local server on the default ports.

* Support downstream FEC protection modes

Adopt the FECProtection message from livekit/protocol#1987: subscribers
select a mode (disabled, adaptive, fixed, minimum) and a level (low,
medium, high; unspecified is low) per track. As before, an update that
omits fec keeps the previous setting. Unknown modes disable FEC and
unknown levels are treated as unspecified.

The modes follow libwebrtc's RtpParameters::fec_protection
(webrtc-sdk/webrtc#329):
- adaptive ports VCMNackFecMethod: the kFecRateTable lookup with a 10
  second max-window loss filter, key frame boost, ConvertFECRate, NACK
  only delta frames below 20ms RTT, and BitRateTooLowForFec. Inputs are
  the subscriber's receiver reports, the sent bit and frame rates, and
  the forwarded layer's dimensions.
- fixed uses the level for delta and key frames.
- minimum uses the larger of the adaptive rate and the level.
- the adaptive state is updated in every mode, so switching to adaptive
  or minimum starts from the current loss history, and a protection
  change keeps the group that is accumulating and protects it at the
  new rate.

Key frames get their own protection factor, so pacer packets carry a
key frame flag. Repairs are still generated per frame; multi-frame
blocks (max_fec_frames) are not supported.

The end-to-end tests report the simulated loss in receiver reports,
since the test client sends none, and check that adaptive protection
sends no repairs without loss and protects with loss, and that minimum
protection matches its level without loss and rises with loss.

Requires livekit/protocol#1987, which is not in the pinned protocol
version yet.

* Point protocol at livekit/protocol#1987

* Report loss before repair in receiver reports to publishers

Receiver reports counted packets restored by RTX or recovered by FlexFEC
as received, so as long as repairs kept up the reported fraction lost
stayed at zero, even with 20% upstream loss. libwebrtc receivers exclude
recovered packets from their receive statistics, and a publisher's
loss-based protection depends on that: with no reported loss, FlexFEC
backs off to almost no repairs.

Packets that fill a loss through a repair are now counted separately, and
receiver reports include them in the fraction and cumulative loss.
Reordered packets that arrive on their own still cancel the loss. The
fraction is also capped at 255, so a full loss no longer wraps to zero.

With 20% simulated upstream loss from an Android publisher, the reported
fraction lost goes from 0 to about 0.15, the FEC packets received over 30
seconds go from 64 to 204, and the packets recovered by FEC from 11 to 61.

* Protect zeroed abs-send-time and TWCC in downstream FlexFEC

The pacer encoded FEC after it had filled in abs-send-time and the
transport-wide sequence number. libwebrtc generates FEC before its sender
fills them in, and its FlexFEC receiver zeroes both in media packets before
recovery. Packets recovered from SFU repairs therefore got wrong bytes in
those extensions, and in the payload when the header lengths within a group
differed, for example when only the first packet carried abs-capture-time.

Zero both extensions after the media packet is written and before it is
fed to the encoder.

* Aggregate receiver report loss for adaptive FEC protection

Adaptive and minimum protection fed the fraction lost of every reception
report into the max-window loss filter. libwebrtc receivers can send a
report with each NACK, so a report often covers only a few packets and its
fraction lost is very noisy. With 10% random loss, single reports read up
to 70%, and the filter kept the maximum.

Derive loss from the cumulative counters instead and produce a sample only
once it covers at least 20 expected packets, like libwebrtc's
SendSideBandwidthEstimation::UpdatePacketsLost. The end-to-end tests now
report cumulative loss and the extended highest sequence number in their
receiver reports.

* Report loss before repair only to FlexFEC publishers

Counting repaired packets as lost in receiver reports applied to every
publisher, so any publisher whose loss RTX repaired started to see that loss
and its bandwidth estimate could back off sooner. Only FlexFEC protection
needs loss before repair to choose its rate.

Count repairs only for streams that negotiated flexfec-03, which requires
FlexFEC to be enabled on the server. Other publishers keep receiving loss
after repair, as before.

* Keep the newest RTX repair mark of a history slot

A late retransmission of an older packet that has aged out of the cache
overwrote the slot of a newer repair sharing it. The newer repair, which
carries the RTX packet's header, could then be used for FlexFEC recovery and
corrupt the recovered packet.

Keep the highest extended sequence number written to a slot until the stream
restarts. isRTXRepairedLocked already treats an older packet in a slot with a
newer mark as repaired.

* Measure FEC overhead against all media

The allocator scales the whole media bitrate by the measured repair
overhead, but the overhead was measured against protected media only. With
adaptive protection below 20 ms RTT only key frames are protected, so the
ratio of key frame repairs to key frame media was applied to every frame,
and the reservation could make the allocator lower the layer or pause the
track although the bandwidth was sufficient.

Count all non-padding media while any protection is active.

* Keep the loss sample that closes a filter window

The max-window loss filter, ported from libwebrtc, dropped the report that
closes a one-second window when the window already had a maximum, so a loss
spike arriving on the boundary never reached adaptive protection. Store the
larger of the window's maximum and that sample.

* Skip the encoder allocation check under the race detector

CI runs the tests with -race and swaps sync.Mutex for go-deadlock, whose
Lock allocates, so Encode allocated about once per call there. Check
allocations only without the race detector, like the other allocation tests.

* Bump protocol to v1.55.0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sfu: reserve measured FEC overhead only on the forwarded layer

The measured repair overhead comes from the spatial layer being
forwarded. On a low layer with one or two packets per frame it can be
60-100%, and applying it to every layer reserved the high layer at
nearly twice its cost, so the allocator could stay on the low layer.

Attribute measurements to the forwarded spatial layer, restarting them
when forwarding starts, resumes or switches layers, and reserve the
configured rate for the other layers.

Also reallocate only when a reserved overhead moves by 5 points or
more, or turns on or off, so that per-second measurements and adaptive
protection do not re-run allocation on every receiver report.

* buffer: gate upstream FlexFEC on an explicit flag

A publisher PC registers flexfec-03 when only downstream FEC is enabled,
because it can also carry subscriptions. Its buffers then got a FEC
payload type, which reported loss before repair to the publisher and
let the decoder start from the observed repair SSRC, although upstream
FEC was disabled.

Buffers now ignore the negotiated FlexFEC payload type unless the buffer
factory enables upstream FlexFEC.

* pacer: protect interceptor-written transport-cc as zeros in FEC

With UseSendSideBWEInterceptor, Pion's TWCC header extension
interceptor writes transport-cc during WriteRTP while the DownTrack
leaves TransportWideExtID at zero. The extension was then protected
with its non-zero value, which the receiver zeroes before recovery, so
recovered packets got wrong bytes there.

Pass the negotiated transport-cc ID to the pacer for FEC and zero it
before encoding as well.

* sfu: skip the FEC encoder while protection is disabled

The encoder was attached whenever flexfec-03 was negotiated, including
in the default disabled mode, so every forwarded packet took the
encoder lock and updated the adaptive state without generating repairs.

Pass the encoder to the pacer only while protection is enabled. Receiver
reports still keep the loss history; adaptive protection measures media
rates again once enabled.

* sfu: account sent FEC repairs in the down track RTP stats

Repairs were counted only in the aggregate Prometheus counter, so the
down track's stats under-counted what the subscriber receives. Record
them in the sender's FEC packet and byte counters, separate from media,
and export the FEC counters in RTPStats for both directions.

* rtc: merge subscriber FEC settings in one place

The subscription merged and normalized settings, and the subscribed
track merged and normalized them again, while the DownTrack mapped
unknown modes and levels a third time.

Merge only in the subscription, store the merged settings in the
subscribed track as is, and leave unknown values to the DownTrack.

* prometheus: resolve fixed-label FEC counters once

RecordFECDownstream runs on the pacer path for every repair batch and
looked up both counter vectors by label each time.

* rtpstats: seed a sender without holding both locks

Seed took the receiving sender's lock and then the source's, so two
senders seeding from each other at the same time could deadlock. Copy
the source's state under its own lock first, then apply the copy under
the receiving sender's lock.

* telemetry: count FlexFEC repairs in traffic totals

Retransmissions and padding count towards node and participant
traffic, but FEC repairs, which are also on the wire, did not. Add
repairs sent and received to the node packet and byte totals, and to
the packets and bytes of TrafficStats.

Analytics streams are unchanged: AnalyticsStream has no FEC field.

* sfu: read the FEC transport-cc ID atomically

setRTPHeaderExtensions runs again when the stream allocator listener is
set, which can happen while media is already forwarded, and WriteRTP
read the ID without synchronization. Store it atomically once the
extensions are processed.

* telemetry: count only FEC repairs sent in node traffic

Media recovered from FEC repairs is counted as received media, so
adding the repairs received to node ingress counted recovered packets
twice. Node traffic feeds room admission against limit.bytes_per_sec,
so ingress must not be inflated. Keep repairs sent in node egress,
where nothing is synthesized, and leave ingress as before.

TrafficStats is derived from RTPStats without a direction, so it cannot
tell repairs sent from repairs received; leave it without FEC.

* rtc: add WebRTCConfig.SetFlexFEC for per-session FlexFEC settings

* rtc: apply a session's upstream FlexFEC to its buffers

SetFlexFEC changed what a session negotiates with its publisher, but the
publisher's buffers still followed the node config: the room's buffer
factory read it once. A session with upstream on and a node with it off
negotiated flexfec-03, so the publisher sent repairs that its buffers
ignored; the reverse turned on upstream recovery and loss reported before
repair for a session that asked for neither.

The session's buffer factory now follows the session's upstream setting,
whichever of SetFlexFEC and SetBufferFactory comes first. Without a
SetFlexFEC call it follows the node config, as before. The setting applies
to buffers the factory creates afterwards, so SetFlexFEC is meant to be
called while the session is set up, before any track is published.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Jules Testard <jules.testard@livekit.io>
Co-authored-by: David Chen <chenosaurus@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 14:55:27 +01:00

1769 lines
50 KiB
Go

/*
* Copyright 2023 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 rtc
import (
"context"
"errors"
"maps"
"slices"
"sync"
"time"
"github.com/pion/webrtc/v4/pkg/rtcerr"
"go.uber.org/atomic"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/livekit-server/pkg/telemetry/prometheus"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/utils"
)
// using var instead of const to override in tests
var (
reconcileInterval = 3 * time.Second
// amount of time to give up if a track or publisher isn't found
// ensuring this is longer than iceFailedTimeout so we are certain the participant won't return
notFoundTimeout = time.Minute
// amount of time to try otherwise before flagging subscription as failed
subscriptionTimeout = iceFailedTimeoutTotal
maxUnsubscribeWait = time.Second
)
const (
trackIDForReconcileSubscriptions = livekit.TrackID("subscriptions_reconcile")
)
type SubscriptionManagerParams struct {
Logger logger.Logger
Participant types.LocalParticipant
TrackResolver types.MediaTrackResolver
OnTrackSubscribed func(subTrack types.SubscribedTrack)
OnTrackUnsubscribed func(subTrack types.SubscribedTrack)
OnSubscriptionError func(trackID livekit.TrackID, fatal bool, err error)
SubscriptionLimitVideo, SubscriptionLimitAudio int32
SubscribePacer *SubscribePacer
DataTrackResolver types.DataTrackResolver
UseOneShotSignallingMode bool
}
// SubscriptionManager manages a participant's subscriptions
type SubscriptionManager struct {
params SubscriptionManagerParams
lock sync.RWMutex
subscriptions map[livekit.TrackID]*mediaTrackSubscription
pendingUnsubscribes atomic.Int32
subscribedVideoCount, subscribedAudioCount atomic.Int32
subscribedTo map[livekit.ParticipantID]map[livekit.TrackID]struct{}
reconcileCh chan livekit.TrackID
reconcileDataTrackCh chan livekit.TrackID
closeCh chan struct{}
doneCh chan struct{}
// set when a queued reconcile is dropped, the worker then reconciles everything
reconcileOverflow atomic.Bool
reconcileDataTrackOverflow atomic.Bool
onSubscribeStatusChanged func(publisherID livekit.ParticipantID, subscribed bool)
dataTrackSubscriptions map[livekit.TrackID]*dataTrackSubscription
}
func NewSubscriptionManager(params SubscriptionManagerParams) *SubscriptionManager {
m := &SubscriptionManager{
params: params,
subscriptions: make(map[livekit.TrackID]*mediaTrackSubscription),
subscribedTo: make(map[livekit.ParticipantID]map[livekit.TrackID]struct{}),
reconcileCh: make(chan livekit.TrackID, 50),
reconcileDataTrackCh: make(chan livekit.TrackID, 5),
closeCh: make(chan struct{}),
doneCh: make(chan struct{}),
dataTrackSubscriptions: make(map[livekit.TrackID]*dataTrackSubscription),
}
go m.reconcileWorker()
return m
}
func (m *SubscriptionManager) Close(isExpectedToResume bool) {
m.lock.Lock()
if m.isClosed() {
m.lock.Unlock()
return
}
close(m.closeCh)
m.lock.Unlock()
<-m.doneCh
prometheus.RecordTrackSubscribeCancels(int32(m.getNumCancellations()))
// Remove observer closures from track change/remove notifiers to allow
// this participant and its transports to be garbage collected.
m.lock.Lock()
subs := maps.Clone(m.subscriptions)
dataTrackSubs := maps.Clone(m.dataTrackSubscriptions)
m.lock.Unlock()
for _, sub := range subs {
sub.setChangedNotifier(nil)
sub.setRemovedNotifier(nil)
}
for _, dataTrackSub := range dataTrackSubs {
dataTrackSub.setChangedNotifier(nil)
dataTrackSub.setRemovedNotifier(nil)
}
subTracks := m.GetSubscribedTracks()
downTracksToClose := make([]*sfu.DownTrack, 0, len(subTracks))
for _, st := range subTracks {
m.setDesired(st.ID(), false)
dt := st.DownTrack()
// nil check exists primarily for tests
if dt != nil {
downTracksToClose = append(downTracksToClose, st.DownTrack())
}
}
if isExpectedToResume {
for _, dt := range downTracksToClose {
dt.CloseWithFlush(false, true)
}
} else {
// flush blocks, so execute in parallel
for _, dt := range downTracksToClose {
go dt.CloseWithFlush(true, true)
}
}
for trackID, sub := range dataTrackSubs {
m.setDataTrackDesired(trackID, false)
dataDownTrack := sub.getDataDownTrack()
if dataDownTrack == nil {
// already unsubscribed
continue
}
dataTrack := dataDownTrack.PublishDataTrack()
if dataTrack == nil {
continue
}
dataTrack.RemoveSubscriber(sub.subscriberID)
}
m.notifyDataTrackSubscriberHandles()
}
func (m *SubscriptionManager) isClosed() bool {
select {
case <-m.closeCh:
return true
default:
return false
}
}
func (m *SubscriptionManager) SubscribeToTrack(trackID livekit.TrackID, isSync bool) {
if m.isClosed() {
return
}
if m.params.UseOneShotSignallingMode || isSync {
m.subscribeSynchronous(trackID)
return
}
// find or create and set desired under one lock, so that a concurrent subscribe,
// settings update or cleanup cannot replace or remove the subscription in between
m.lock.Lock()
sub, ok := m.subscriptions[trackID]
if !ok {
sLogger := m.params.Logger.WithValues(
"trackID", trackID,
)
sub = newMediaTrackSubscription(m.params.Participant.ID(), trackID, sLogger)
m.subscriptions[trackID] = sub
}
desireChanged := sub.setDesired(true)
m.lock.Unlock()
if desireChanged {
sub.logger.Debugw("subscribing to track")
}
// always reconcile, since SubscribeToTrack could be called when the track is ready
m.queueReconcile(trackID)
}
func (m *SubscriptionManager) UnsubscribeFromTrack(trackID livekit.TrackID) {
if m.params.UseOneShotSignallingMode {
m.unsubscribeSynchronous(trackID)
return
}
sub, desireChanged := m.setDesired(trackID, false)
if sub == nil || !desireChanged {
return
}
if sub.isCanceled() {
prometheus.RecordTrackSubscribeCancels(1)
}
sub.logger.Debugw("unsubscribing from track")
m.queueReconcile(trackID)
}
func (m *SubscriptionManager) SubscribeToDataTrack(trackID livekit.TrackID) {
if m.isClosed() {
return
}
// same as SubscribeToTrack, find or create and set desired under one lock
m.lock.Lock()
sub, ok := m.dataTrackSubscriptions[trackID]
if !ok {
sLogger := m.params.Logger.WithValues(
"trackID", trackID,
)
sub = newDataTrackSubscription(m.params.Participant.ID(), trackID, sLogger)
m.dataTrackSubscriptions[trackID] = sub
}
desireChanged := sub.setDesired(true)
m.lock.Unlock()
if desireChanged {
sub.logger.Debugw("subscribing to data track")
}
m.queueReconcileDataTrack(trackID)
}
func (m *SubscriptionManager) UnsubscribeFromDataTrack(trackID livekit.TrackID) {
sub, desireChanged := m.setDataTrackDesired(trackID, false)
if sub == nil || !desireChanged {
return
}
sub.logger.Debugw("unsubscribing from data track")
m.queueReconcileDataTrack(trackID)
}
func (m *SubscriptionManager) ClearAllSubscriptions() {
m.params.Logger.Debugw("clearing all subscriptions")
if m.params.UseOneShotSignallingMode {
for _, track := range m.GetSubscribedTracks() {
m.unsubscribeSynchronous(track.ID())
}
// no synchronous data tracks
}
numCancellations := 0
m.lock.RLock()
for _, sub := range m.subscriptions {
if sub.isCanceled() {
numCancellations++
}
sub.setDesired(false)
}
for _, sub := range m.dataTrackSubscriptions {
sub.setDesired(false)
}
m.lock.RUnlock()
prometheus.RecordTrackSubscribeCancels(int32(numCancellations))
m.ReconcileAll()
}
// FailTrackBind ends a subscription whose track cannot bind, the same way a bind error does
func (m *SubscriptionManager) FailTrackBind(trackID livekit.TrackID, err error) {
m.lock.RLock()
sub := m.subscriptions[trackID]
m.lock.RUnlock()
if sub != nil {
m.handleBindFailure(sub, err)
}
}
func (m *SubscriptionManager) handleBindFailure(sub *mediaTrackSubscription, err error) {
sub.logger.Infow("failed to bind track", "err", err)
sub.maybeRecordError(m.params.Participant.GetTelemetryListener(), err, true)
m.UnsubscribeFromTrack(sub.trackID)
m.params.OnSubscriptionError(sub.trackID, false, err)
}
func (m *SubscriptionManager) GetSubscribedTracks() []types.SubscribedTrack {
m.lock.RLock()
defer m.lock.RUnlock()
tracks := make([]types.SubscribedTrack, 0, len(m.subscriptions))
for _, t := range m.subscriptions {
st := t.getSubscribedTrack()
if st != nil {
tracks = append(tracks, st)
}
}
return tracks
}
func (m *SubscriptionManager) GetSubscribedDataTracks() []types.DataDownTrack {
m.lock.RLock()
defer m.lock.RUnlock()
tracks := make([]types.DataDownTrack, 0, len(m.dataTrackSubscriptions))
for _, s := range m.dataTrackSubscriptions {
if dt := s.getDataDownTrack(); dt != nil {
tracks = append(tracks, dt)
}
}
return tracks
}
func (m *SubscriptionManager) IsTrackNameSubscribed(publisherIdentity livekit.ParticipantIdentity, trackName string) bool {
m.lock.RLock()
defer m.lock.RUnlock()
for _, s := range m.subscriptions {
st := s.getSubscribedTrack()
if st != nil && st.PublisherIdentity() == publisherIdentity && st.MediaTrack() != nil && st.MediaTrack().Name() == trackName {
return true
}
}
return false
}
func (m *SubscriptionManager) StopAndGetSubscribedTracksForwarderState() map[livekit.TrackID]*livekit.RTPForwarderState {
m.lock.RLock()
defer m.lock.RUnlock()
states := make(map[livekit.TrackID]*livekit.RTPForwarderState, len(m.subscriptions))
for trackID, t := range m.subscriptions {
st := t.getSubscribedTrack()
if st != nil {
dt := st.DownTrack()
if dt != nil {
state := dt.StopWriteAndGetState()
if state.ForwarderState != nil {
states[trackID] = state.ForwarderState
}
}
}
}
return states
}
func (m *SubscriptionManager) HasSubscriptions() bool {
m.lock.RLock()
defer m.lock.RUnlock()
for _, s := range m.subscriptions {
if s.isDesired() {
return true
}
}
return false
}
func (m *SubscriptionManager) GetSubscribedParticipants() []livekit.ParticipantID {
m.lock.RLock()
defer m.lock.RUnlock()
return slices.Collect(maps.Keys(m.subscribedTo))
}
func (m *SubscriptionManager) IsSubscribedTo(participantID livekit.ParticipantID) bool {
m.lock.RLock()
defer m.lock.RUnlock()
_, ok := m.subscribedTo[participantID]
return ok
}
func (m *SubscriptionManager) UpdateSubscribedTrackSettings(trackID livekit.TrackID, settings *livekit.UpdateTrackSettings) {
m.lock.Lock()
sub, ok := m.subscriptions[trackID]
if !ok {
sLogger := m.params.Logger.WithValues(
"trackID", trackID,
)
sub = newMediaTrackSubscription(m.params.Participant.ID(), trackID, sLogger)
m.subscriptions[trackID] = sub
}
sub.keepForSubscribe()
m.lock.Unlock()
sub.setSettings(settings)
}
func (m *SubscriptionManager) UpdateDataTrackSubscriptionOptions(trackID livekit.TrackID, subscriptionOptions *livekit.DataTrackSubscriptionOptions) {
m.lock.Lock()
sub, ok := m.dataTrackSubscriptions[trackID]
if !ok {
sLogger := m.params.Logger.WithValues(
"trackID", trackID,
)
sub = newDataTrackSubscription(m.params.Participant.ID(), trackID, sLogger)
m.dataTrackSubscriptions[trackID] = sub
}
sub.keepForSubscribe()
m.lock.Unlock()
sub.setSubscriptionOptions(subscriptionOptions)
}
// OnSubscribeStatusChanged callback will be notified when a participant subscribes or unsubscribes to another participant
// it will only fire once per publisher. If current participant is subscribed to multiple tracks from another, this
// callback will only fire once.
func (m *SubscriptionManager) OnSubscribeStatusChanged(fn func(publisherID livekit.ParticipantID, subscribed bool)) {
m.lock.Lock()
m.onSubscribeStatusChanged = fn
m.lock.Unlock()
}
func (m *SubscriptionManager) WaitUntilSubscribed(timeout time.Duration) error {
expiresAt := time.Now().Add(timeout)
for expiresAt.After(time.Now()) {
allSubscribed := true
m.lock.RLock()
for _, sub := range m.subscriptions {
if sub.needsSubscribe() {
allSubscribed = false
break
}
}
if allSubscribed {
for _, sub := range m.dataTrackSubscriptions {
if sub.needsSubscribe() {
allSubscribed = false
break
}
}
}
m.lock.RUnlock()
if allSubscribed {
return nil
}
time.Sleep(50 * time.Millisecond)
}
return context.DeadlineExceeded
}
func (m *SubscriptionManager) ReconcileAll() {
m.queueReconcile(trackIDForReconcileSubscriptions)
m.queueReconcileDataTrack(trackIDForReconcileSubscriptions)
}
func (m *SubscriptionManager) setDesired(trackID livekit.TrackID, desired bool) (*mediaTrackSubscription, bool) {
m.lock.RLock()
defer m.lock.RUnlock()
sub, ok := m.subscriptions[trackID]
if !ok {
return nil, false
}
return sub, sub.setDesired(desired)
}
func (m *SubscriptionManager) setDataTrackDesired(trackID livekit.TrackID, desired bool) (*dataTrackSubscription, bool) {
m.lock.RLock()
defer m.lock.RUnlock()
sub, ok := m.dataTrackSubscriptions[trackID]
if !ok {
return nil, false
}
return sub, sub.setDesired(desired)
}
func (m *SubscriptionManager) canReconcile() bool {
p := m.params.Participant
if m.isClosed() || p.IsClosed() || p.IsDisconnected() {
return false
}
return true
}
func (m *SubscriptionManager) reconcileSubscriptions() {
var needsToReconcile []*mediaTrackSubscription
m.lock.RLock()
for _, sub := range m.subscriptions {
if sub.needsSubscribe() || sub.needsUnsubscribe() || sub.needsBind() || sub.needsCleanup() {
needsToReconcile = append(needsToReconcile, sub)
}
}
m.lock.RUnlock()
for _, s := range needsToReconcile {
m.reconcileSubscription(s)
}
}
func (m *SubscriptionManager) reconcileSubscription(s *mediaTrackSubscription) {
if !m.canReconcile() {
return
}
if s.needsSubscribe() {
if m.pendingUnsubscribes.Load() != 0 && s.durationSinceStart() < maxUnsubscribeWait {
// enqueue this in a bit, after pending unsubscribes are complete
go func() {
time.Sleep(time.Duration(sfu.RTPBlankFramesCloseSeconds * float32(time.Second)))
m.queueReconcile(s.trackID)
}()
return
}
numAttempts := s.getNumAttempts()
if numAttempts == 0 {
m.params.Participant.GetTelemetryListener().OnTrackSubscribeRequested(
s.subscriberID,
&livekit.TrackInfo{
Sid: string(s.trackID),
},
)
}
if err := m.subscribe(s); err != nil {
s.recordAttempt(false)
switch err {
case ErrNoTrackPermission, ErrNoSubscribePermission, ErrNoReceiver, ErrNotOpen, ErrSubscriptionLimitExceeded:
// these are errors that are outside of our control, so we'll keep trying
// - ErrNoTrackPermission: publisher did not grant subscriber permission, may change any moment
// - ErrNoSubscribePermission: participant was not granted canSubscribe, may change any moment
// - ErrNoReceiver: Track is in the process of closing (another local track published to the same instance)
// - ErrNotOpen: Track is closing or already closed
// - ErrSubscriptionLimitExceeded: the participant have reached the limit of subscriptions, wait for the other subscription to be unsubscribed
// We'll still log an event to reflect this in telemetry since it's been too long
if s.durationSinceStart() > subscriptionTimeout {
s.maybeRecordError(m.params.Participant.GetTelemetryListener(), err, true)
}
case ErrTrackNotFound:
// source track was never published or closed
// if after timeout we'd unsubscribe from it.
// this is the *only* case we'd change desired state
if s.durationSinceStart() > notFoundTimeout {
s.maybeRecordError(m.params.Participant.GetTelemetryListener(), err, true)
s.logger.Infow("unsubscribing from track after notFoundTimeout", "error", err)
s.setDesired(false)
m.queueReconcile(s.trackID)
m.params.OnSubscriptionError(s.trackID, false, err)
}
default:
// all other errors
if s.durationSinceStart() > subscriptionTimeout {
s.logger.Warnw(
"failed to subscribe, triggering error handler", err,
"attempt", s.getNumAttempts(),
)
s.maybeRecordError(m.params.Participant.GetTelemetryListener(), err, false)
m.params.OnSubscriptionError(s.trackID, true, err)
} else {
s.logger.Debugw(
"failed to subscribe, retrying",
"error", err,
"attempt", s.getNumAttempts(),
)
}
}
} else {
s.recordAttempt(true)
}
return
}
if s.needsUnsubscribe() {
if err := m.unsubscribe(s); err != nil {
s.logger.Warnw("failed to unsubscribe", err)
}
// do not remove subscription from map. Wait for subscribed track to close
// and the callback (handleSubscribedTrackClose) to set the subscribedTrack to nil
// and the clean up path to handle removing subscription from the subscription map.
// It is possible that the track is re-published before subscribed track is closed.
// That could create a new subscription and a duplicate entry in SDP.
// Waiting for subscribed track close would ensure that the track is removed from
// the peer connection before re-published track is re-subscribed and added back to the SDP.
return
}
if s.needsBind() {
// check bound status, notify error callback if it's not bound
// if a publisher leaves or closes the source track, SubscribedTrack will be closed as well and it will go
// back to needsSubscribe state
if activeAt := m.params.Participant.ActiveAt(); !activeAt.IsZero() {
wait := min(time.Since(activeAt), s.durationSinceStart())
if wait > subscriptionTimeout {
s.logger.Warnw("track not bound after timeout", nil)
s.maybeRecordError(m.params.Participant.GetTelemetryListener(), ErrTrackNotBound, false)
m.params.OnSubscriptionError(s.trackID, true, ErrTrackNotBound)
}
}
}
m.lock.Lock()
if m.subscriptions[s.trackID] == s && s.cleanup(func() bool { return s.subscribedTrack != nil }) {
s.logger.Debugw("cleanup removing subscription")
delete(m.subscriptions, s.trackID)
}
m.lock.Unlock()
}
func (m *SubscriptionManager) reconcileDataTrackSubscriptions() {
var needsToReconcile []*dataTrackSubscription
m.lock.RLock()
for _, sub := range m.dataTrackSubscriptions {
if sub.needsSubscribe() || sub.needsUnsubscribe() || sub.needsCleanup() {
needsToReconcile = append(needsToReconcile, sub)
}
}
m.lock.RUnlock()
for _, s := range needsToReconcile {
m.reconcileDataTrackSubscription(s)
}
}
func (m *SubscriptionManager) reconcileDataTrackSubscription(s *dataTrackSubscription) {
if !m.canReconcile() {
return
}
if s.needsSubscribe() {
if err := m.subscribeDataTrack(s); err != nil {
s.recordAttempt(false)
switch err {
case ErrNoTrackPermission, ErrNoSubscribePermission:
// these are errors that are outside of our control, so we'll keep trying
// - ErrNoTrackPermission: publisher did not grant subscriber permission, may change any moment
// - ErrNoSubscribePermission: participant was not granted canSubscribe, may change any moment
case ErrTrackNotFound:
// source track was never published or closed
// if after timeout we'd unsubscribe from it.
// this is the *only* case we'd change desired state
if s.durationSinceStart() > notFoundTimeout {
s.logger.Infow("unsubscribing from data track after notFoundTimeout", "error", err)
s.setDesired(false)
m.queueReconcileDataTrack(s.trackID)
}
default:
// all other errors
if s.durationSinceStart() > subscriptionTimeout {
s.logger.Warnw(
"failed to subscribe, triggering error handler", err,
"attempt", s.getNumAttempts(),
)
} else {
s.logger.Debugw(
"failed to subscribe, retrying",
"error", err,
"attempt", s.getNumAttempts(),
)
}
}
} else {
s.recordAttempt(true)
m.notifyDataTrackSubscriberHandles()
}
return
}
if s.needsUnsubscribe() {
if err := m.unsubscribeDataTrack(s); err != nil {
s.logger.Warnw("failed to unsubscribe", err)
}
}
m.lock.Lock()
cleanedUp := m.dataTrackSubscriptions[s.trackID] == s && s.cleanup(func() bool { return s.dataDownTrack != nil })
if cleanedUp {
s.logger.Debugw("cleanup removing data track subscription")
delete(m.dataTrackSubscriptions, s.trackID)
}
m.lock.Unlock()
if cleanedUp {
m.notifyDataTrackSubscriberHandles()
}
}
// trigger an immediate reconciliation, when trackID is empty, will reconcile all subscriptions
func (m *SubscriptionManager) queueReconcile(trackID livekit.TrackID) {
select {
case m.reconcileCh <- trackID:
default:
// queue is full, the worker reconciles everything after its next queued item
m.reconcileOverflow.Store(true)
}
}
func (m *SubscriptionManager) queueReconcileDataTrack(trackID livekit.TrackID) {
select {
case m.reconcileDataTrackCh <- trackID:
default:
m.reconcileDataTrackOverflow.Store(true)
}
}
func (m *SubscriptionManager) reconcileWorker() {
defer close(m.doneCh)
reconcileTicker := time.NewTicker(reconcileInterval)
defer reconcileTicker.Stop()
for {
select {
case <-m.closeCh:
return
case <-reconcileTicker.C:
m.reconcileSubscriptions()
m.reconcileDataTrackSubscriptions()
case trackID := <-m.reconcileCh:
m.lock.Lock()
s := m.subscriptions[trackID]
m.lock.Unlock()
if s != nil {
m.reconcileSubscription(s)
} else {
m.reconcileSubscriptions()
}
if m.reconcileOverflow.Swap(false) {
m.reconcileSubscriptions()
}
case trackID := <-m.reconcileDataTrackCh:
m.lock.Lock()
s := m.dataTrackSubscriptions[trackID]
m.lock.Unlock()
if s != nil {
m.reconcileDataTrackSubscription(s)
} else {
m.reconcileDataTrackSubscriptions()
}
if m.reconcileDataTrackOverflow.Swap(false) {
m.reconcileDataTrackSubscriptions()
}
}
}
}
func (m *SubscriptionManager) hasCapacityForSubscription(kind livekit.TrackType) bool {
switch kind {
case livekit.TrackType_VIDEO:
if m.params.SubscriptionLimitVideo > 0 && m.subscribedVideoCount.Load() >= m.params.SubscriptionLimitVideo {
m.params.Logger.Debugw("subscription limit exceeded for video", "limit", m.params.SubscriptionLimitVideo, "subscriptions", m.subscribedVideoCount.Load())
return false
}
case livekit.TrackType_AUDIO:
if m.params.SubscriptionLimitAudio > 0 && m.subscribedAudioCount.Load() >= m.params.SubscriptionLimitAudio {
m.params.Logger.Debugw("subscription limit exceeded for audio", "limit", m.params.SubscriptionLimitAudio, "subscriptions", m.subscribedAudioCount.Load())
return false
}
}
return true
}
func (m *SubscriptionManager) subscribe(sub *mediaTrackSubscription) error {
sub.logger.Debugw("executing subscribe")
if !m.params.Participant.CanSubscribe() {
return ErrNoSubscribePermission
}
if kind, ok := sub.getKind(); ok && !m.hasCapacityForSubscription(kind) {
return ErrSubscriptionLimitExceeded
}
trackID := sub.trackID
res := m.params.TrackResolver(m.params.Participant, trackID)
sub.logger.Debugw("resolved track", "result", res)
if res.TrackChangedNotifier != nil && sub.setChangedNotifier(res.TrackChangedNotifier) {
// set callback only when we haven't done it before
// we set the observer before checking for existence of track, so that we may get notified
// when the track becomes available
res.TrackChangedNotifier.AddObserver(string(sub.subscriberID), func() {
m.queueReconcile(trackID)
})
}
if res.TrackRemovedNotifier != nil && sub.setRemovedNotifier(res.TrackRemovedNotifier) {
res.TrackRemovedNotifier.AddObserver(string(sub.subscriberID), func() {
// re-resolve the track in case the same track had been re-published
res := m.params.TrackResolver(m.params.Participant, trackID)
if res.Track != nil {
// do not unsubscribe, track is still available
return
}
m.handleSourceTrackRemoved(trackID)
})
}
track := res.Track
if track == nil {
return ErrTrackNotFound
}
sub.trySetKind(track.Kind())
if !m.hasCapacityForSubscription(track.Kind()) {
return ErrSubscriptionLimitExceeded
}
sub.setPublisher(res.PublisherIdentity, res.PublisherID)
permChanged := sub.setHasPermission(res.HasPermission)
if permChanged {
m.params.Participant.SendSubscriptionPermissionUpdate(sub.getPublisherID(), trackID, res.HasPermission)
}
if !res.HasPermission {
return ErrNoTrackPermission
}
return m.addSubscriber(sub, track, false)
}
func (m *SubscriptionManager) subscribeSynchronous(trackID livekit.TrackID) error {
m.params.Logger.Debugw("executing subscribe synchronous", "trackID", trackID)
if !m.params.Participant.CanSubscribe() {
return ErrNoSubscribePermission
}
res := m.params.TrackResolver(m.params.Participant, trackID)
m.params.Logger.Debugw("resolved track", "trackID", trackID, " result", res)
track := res.Track
if track == nil {
return ErrTrackNotFound
}
m.lock.Lock()
sub, ok := m.subscriptions[trackID]
if !ok {
sLogger := m.params.Logger.WithValues(
"trackID", trackID,
)
sub = newMediaTrackSubscription(m.params.Participant.ID(), trackID, sLogger)
m.subscriptions[trackID] = sub
}
m.lock.Unlock()
sub.setDesired(true)
return m.addSubscriber(sub, track, true)
}
func (m *SubscriptionManager) addSubscriber(sub *mediaTrackSubscription, track types.MediaTrack, isSync bool) error {
trackID := track.ID()
// take the shadow token before setup, so tokens go out in arrival order
var paceShadowDelays map[string]time.Duration
if track.Kind() == livekit.TrackType_VIDEO && !isSync {
paceShadowDelays = m.params.SubscribePacer.Delays(time.Now())
}
subTrack, err := track.AddSubscriber(m.params.Participant)
if err != nil && !errors.Is(err, errAlreadySubscribed) {
// ignore error(s): already subscribed
if !utils.ErrorIsOneOf(err, ErrNoReceiver) {
// as track resolution could take some time, not logging errors due to waiting for track resolution
m.params.Logger.Warnw("add subscriber failed", err, "trackID", trackID)
}
return err
}
if err == errAlreadySubscribed {
sub.logger.Debugw(
"already subscribed to track",
"subscribedAudioCount", m.subscribedAudioCount.Load(),
"subscribedVideoCount", m.subscribedVideoCount.Load(),
)
}
if err == nil && subTrack != nil { // subTrack could be nil if already subscribed
if paceShadowDelays != nil {
prometheus.RecordSubscribePaceShadow(paceShadowDelays)
}
subTrack.OnSubscribeStreamStarted(sub.recordStreamStartLatency)
// Install the close callback after both the subscribed track and publisher mark.
// OnClose also delivers an earlier close synchronously, so it must run
// after installation even when a permission recheck returns an error.
defer subTrack.OnClose(func(isExpectedToResume bool) {
m.handleSubscribedTrackClose(sub, isExpectedToResume)
if isSync {
m.lock.Lock()
delete(m.subscriptions, trackID)
m.lock.Unlock()
}
})
subTrack.AddOnBind(func(err error) {
if err != nil {
m.handleBindFailure(sub, err)
return
}
sub.setBound()
sub.maybeRecordSuccess(m.params.Participant.GetTelemetryListener())
})
sub.setSubscribedTrack(subTrack)
switch track.Kind() {
case livekit.TrackType_VIDEO:
m.subscribedVideoCount.Inc()
case livekit.TrackType_AUDIO:
m.subscribedAudioCount.Inc()
}
// a canSubscribe revoke only removes recorded subscriptions, so one that landed while
// this subscribe was in flight missed it; now that it is recorded, check again
if !m.params.Participant.CanSubscribe() {
track.RemoveSubscriber(m.params.Participant.ID(), false)
return ErrNoSubscribePermission
}
// same for the publisher revoking this track's permission, which only removes
// subscribers already recorded on the track
if !isSync {
if res := m.params.TrackResolver(m.params.Participant, trackID); res.Track == track && !res.HasPermission {
track.RemoveSubscriber(m.params.Participant.ID(), false)
return ErrNoTrackPermission
}
}
if !isSync && subTrack.NeedsNegotiation() {
m.params.Participant.Negotiate(false)
}
go m.params.OnTrackSubscribed(subTrack)
sub.logger.Debugw(
"subscribed to track",
"subscribedAudioCount", m.subscribedAudioCount.Load(),
"subscribedVideoCount", m.subscribedVideoCount.Load(),
)
}
if !isSync {
m.markSubscribedTo(sub.getPublisherID(), sub.trackID)
}
return nil
}
func (m *SubscriptionManager) unsubscribe(s *mediaTrackSubscription) error {
s.logger.Debugw("executing unsubscribe")
subTrack := s.getSubscribedTrack()
if subTrack == nil {
// already unsubscribed
return nil
}
track := subTrack.MediaTrack()
pID := s.subscriberID
m.pendingUnsubscribes.Inc()
go func() {
defer m.pendingUnsubscribes.Dec()
track.RemoveSubscriber(pID, false)
}()
return nil
}
func (m *SubscriptionManager) unsubscribeSynchronous(trackID livekit.TrackID) error {
m.lock.Lock()
sub := m.subscriptions[trackID]
delete(m.subscriptions, trackID)
m.lock.Unlock()
if sub == nil {
// already unsubscribed or not subscribed
return nil
}
sub.logger.Debugw("executing unsubscribe synchronous")
if sub.isCanceled() {
prometheus.RecordTrackSubscribeCancels(1)
}
subTrack := sub.getSubscribedTrack()
if subTrack == nil {
// already unsubscribed
return nil
}
track := subTrack.MediaTrack()
track.RemoveSubscriber(sub.subscriberID, false)
return nil
}
func (m *SubscriptionManager) handleSourceTrackRemoved(trackID livekit.TrackID) {
m.lock.Lock()
sub := m.subscriptions[trackID]
m.lock.Unlock()
if sub != nil {
if sub.isCanceled() {
prometheus.RecordTrackSubscribeCancels(1)
}
sub.handleSourceTrackRemoved()
}
}
// DownTrack closing is how the publisher signifies that the subscription is no longer fulfilled
// this could be due to a few reasons:
// - subscriber-initiated unsubscribe
// - UpTrack was closed
// - publisher revoked permissions for the participant
func (m *SubscriptionManager) handleSubscribedTrackClose(s *mediaTrackSubscription, isExpectedToResume bool) {
s.logger.Debugw(
"subscribed track closed",
"isExpectedToResume", isExpectedToResume,
)
wasBound := s.isBound()
subTrack := s.getSubscribedTrack()
if subTrack == nil {
return
}
s.setChangedNotifier(nil)
s.setRemovedNotifier(nil)
s.setSubscribedTrack(nil)
var relieveFromLimits bool
switch subTrack.MediaTrack().Kind() {
case livekit.TrackType_VIDEO:
videoCount := m.subscribedVideoCount.Dec()
relieveFromLimits = m.params.SubscriptionLimitVideo > 0 && videoCount == m.params.SubscriptionLimitVideo-1
case livekit.TrackType_AUDIO:
audioCount := m.subscribedAudioCount.Dec()
relieveFromLimits = m.params.SubscriptionLimitAudio > 0 && audioCount == m.params.SubscriptionLimitAudio-1
}
m.unmarkSubscribedTo(s.getPublisherID(), s.trackID)
go m.params.OnTrackUnsubscribed(subTrack)
// trigger to decrement unsubscribed counter as long as track has been bound
// Only log an analytics event when
// * the participant isn't closing
// * it's not a migration
if wasBound {
m.params.Participant.GetTelemetryListener().OnTrackUnsubscribed(
s.subscriberID,
&livekit.TrackInfo{Sid: string(s.trackID), Type: subTrack.MediaTrack().Kind()},
!isExpectedToResume,
)
dt := subTrack.DownTrack()
if dt != nil {
stats := dt.GetTrackStats()
if stats != nil {
m.params.Participant.GetTelemetryListener().OnTrackSubscribeRTPStats(
s.subscriberID,
s.trackID,
dt.Mime(),
stats,
)
}
}
}
if !isExpectedToResume {
sender := subTrack.RTPSender()
if sender != nil {
s.logger.Debugw("removing PeerConnection track",
"kind", subTrack.MediaTrack().Kind(),
)
if err := m.params.Participant.RemoveTrackLocal(sender); err != nil {
if _, ok := err.(*rtcerr.InvalidStateError); !ok {
// most of these are safe to ignore, since the track state might have already
// been set to Inactive
m.params.Logger.Debugw("could not remove remoteTrack from forwarder",
"error", err,
"publisher", subTrack.PublisherIdentity(),
"publisherID", subTrack.PublisherID(),
)
}
}
}
m.params.Participant.Negotiate(false)
} else {
t := time.Now()
s.subscribeAt.Store(&t)
}
if !m.params.UseOneShotSignallingMode {
if relieveFromLimits {
m.queueReconcile(trackIDForReconcileSubscriptions)
} else {
m.queueReconcile(s.trackID)
}
}
}
func (m *SubscriptionManager) subscribeDataTrack(sub *dataTrackSubscription) error {
sub.logger.Debugw("executing subscribe")
if !m.params.Participant.CanSubscribe() {
return ErrNoSubscribePermission
}
trackID := sub.trackID
res := m.params.DataTrackResolver(m.params.Participant, trackID)
sub.logger.Debugw("resolved data track", "result", res)
if res.TrackChangedNotifier != nil && sub.setChangedNotifier(res.TrackChangedNotifier) {
// set callback only when we haven't done it before
// we set the observer before checking for existence of track, so that we may get notified
// when the track becomes available
res.TrackChangedNotifier.AddObserver(string(sub.subscriberID), func() {
m.queueReconcileDataTrack(trackID)
})
}
if res.TrackRemovedNotifier != nil && sub.setRemovedNotifier(res.TrackRemovedNotifier) {
res.TrackRemovedNotifier.AddObserver(string(sub.subscriberID), func() {
// re-resolve the track in case the same track had been re-published
res := m.params.DataTrackResolver(m.params.Participant, trackID)
if res.DataTrack != nil {
// do not unsubscribe, track is still available
return
}
m.handleSourceDataTrackRemoved(trackID)
})
}
dataTrack := res.DataTrack
if dataTrack == nil {
return ErrTrackNotFound
}
sub.setPublisher(res.PublisherIdentity, res.PublisherID)
permChanged := sub.setHasPermission(res.HasPermission)
if permChanged {
m.params.Participant.SendSubscriptionPermissionUpdate(sub.getPublisherID(), trackID, res.HasPermission)
}
if !res.HasPermission {
return ErrNoTrackPermission
}
dataDownTrack, err := dataTrack.AddSubscriber(m.params.Participant)
if err != nil && !errors.Is(err, errAlreadySubscribed) {
return err
}
if err == errAlreadySubscribed {
sub.logger.Debugw("already subscribed to data track")
}
if err == nil && dataDownTrack != nil { // subTrack could be nil if already subscribed
// Install the close callback after both the downtrack and publisher mark.
// OnClose also delivers an earlier close synchronously, so it must run
// after installation even when a permission recheck returns an error.
defer dataDownTrack.OnClose(func() {
m.handleDataDownTrackClose(sub)
})
sub.setDataDownTrack(dataDownTrack)
// a canSubscribe revoke only removes recorded subscriptions, so one that landed while
// this subscribe was in flight missed it; now that it is recorded, check again
if !m.params.Participant.CanSubscribe() {
dataTrack.RemoveSubscriber(m.params.Participant.ID())
return ErrNoSubscribePermission
}
// same for the publisher revoking this track's permission, which only removes
// subscribers already recorded on the track
if res := m.params.DataTrackResolver(m.params.Participant, trackID); res.DataTrack == dataTrack && !res.HasPermission {
dataTrack.RemoveSubscriber(m.params.Participant.ID())
return ErrNoTrackPermission
}
sub.logger.Debugw("subscribed to data track")
}
m.markSubscribedTo(sub.getPublisherID(), trackID)
return nil
}
func (m *SubscriptionManager) unsubscribeDataTrack(s *dataTrackSubscription) error {
s.logger.Debugw("executing unsubscribe")
dataDownTrack := s.getDataDownTrack()
if dataDownTrack == nil {
// already unsubscribed
return nil
}
dataTrack := dataDownTrack.PublishDataTrack()
dataTrack.RemoveSubscriber(s.subscriberID)
return nil
}
// DataDownTrack closing is how the publisher signifies that the subscription is no longer fulfilled
// this could be due to a few reasons:
// - subscriber-initiated unsubscribe
// - data track was unpublished
// - publisher revoked permissions for the participant
func (m *SubscriptionManager) handleDataDownTrackClose(s *dataTrackSubscription) {
s.logger.Debugw("data down track closed")
if s.getDataDownTrack() == nil {
return
}
s.setChangedNotifier(nil)
s.setRemovedNotifier(nil)
s.setDataDownTrack(nil)
m.unmarkSubscribedTo(s.getPublisherID(), s.trackID)
m.notifyDataTrackSubscriberHandles()
m.queueReconcileDataTrack(s.trackID)
}
func (m *SubscriptionManager) notifyDataTrackSubscriberHandles() {
m.lock.Lock()
handles := make(map[uint32]*livekit.DataTrackSubscriberHandles_PublishedDataTrack, len(m.dataTrackSubscriptions))
for _, sub := range m.dataTrackSubscriptions {
if !sub.isDesired() {
continue
}
dataDownTrack := sub.getDataDownTrack()
if dataDownTrack == nil {
continue
}
handles[uint32(dataDownTrack.Handle())] = &livekit.DataTrackSubscriberHandles_PublishedDataTrack{
PublisherIdentity: string(sub.publisherIdentity),
PublisherSid: string(sub.publisherID),
TrackSid: string(sub.trackID),
}
}
m.lock.Unlock()
m.params.Participant.SendDataTrackSubscriberHandles(handles)
}
func (m *SubscriptionManager) handleSourceDataTrackRemoved(trackID livekit.TrackID) {
m.lock.Lock()
sub := m.dataTrackSubscriptions[trackID]
m.lock.Unlock()
if sub != nil {
sub.handleSourceTrackRemoved()
}
}
func (m *SubscriptionManager) markSubscribedTo(publisherID livekit.ParticipantID, trackID livekit.TrackID) {
// add mark the participant as someone we've subscribed to
firstSubscribe := false
m.lock.Lock()
pTracks := m.subscribedTo[publisherID]
changedCB := m.onSubscribeStatusChanged
if pTracks == nil {
pTracks = make(map[livekit.TrackID]struct{})
m.subscribedTo[publisherID] = pTracks
firstSubscribe = true
}
pTracks[trackID] = struct{}{}
m.lock.Unlock()
if changedCB != nil && firstSubscribe {
changedCB(publisherID, true)
}
}
func (m *SubscriptionManager) unmarkSubscribedTo(publisherID livekit.ParticipantID, trackID livekit.TrackID) {
// remove from subscribedTo
lastSubscription := false
m.lock.Lock()
changedCB := m.onSubscribeStatusChanged
pTracks := m.subscribedTo[publisherID]
if pTracks != nil {
delete(pTracks, trackID)
if len(pTracks) == 0 {
delete(m.subscribedTo, publisherID)
lastSubscription = true
}
}
m.lock.Unlock()
if changedCB != nil && lastSubscription {
changedCB(publisherID, false)
}
}
func (m *SubscriptionManager) getNumCancellations() int {
m.lock.RLock()
defer m.lock.RUnlock()
numCancellations := 0
for _, sub := range m.subscriptions {
if sub.isCanceled() {
numCancellations++
}
}
return numCancellations
}
// --------------------------------------------------------------------------------------
type trackSubscription struct {
subscriberID livekit.ParticipantID
trackID livekit.TrackID
logger logger.Logger
lock sync.RWMutex
desired bool
publisherID livekit.ParticipantID
publisherIdentity livekit.ParticipantIdentity
changedNotifier types.ChangeNotifier
removedNotifier types.ChangeNotifier
hasPermissionInitialized bool
hasPermission bool
numAttempts atomic.Int32
// the later of when subscription was requested OR when the first failure was encountered OR when permission is granted
// this timestamp determines when failures are reported
subStartedAt atomic.Pointer[time.Time]
// the timestamp when the subscription was started, will be reset when downtrack is closed with expected resume
subscribeAt atomic.Pointer[time.Time]
// an entry that is not desired is not cleaned up before this time,
// so that settings sent before a subscribe are there when the subscribe comes
keepUntil time.Time
}
// set permission and return true if it has changed
func (s *trackSubscription) setHasPermission(perm bool) bool {
s.lock.Lock()
defer s.lock.Unlock()
if s.hasPermissionInitialized && s.hasPermission == perm {
return false
}
s.hasPermissionInitialized = true
s.hasPermission = perm
if s.hasPermission {
// when permission is granted, reset the timer so it has sufficient time to reconcile
t := time.Now()
s.subStartedAt.Store(&t)
s.subscribeAt.Store(&t)
}
return true
}
func (s *trackSubscription) getHasPermission() bool {
s.lock.RLock()
defer s.lock.RUnlock()
return s.hasPermission
}
func (s *trackSubscription) setPublisher(publisherIdentity livekit.ParticipantIdentity, publisherID livekit.ParticipantID) {
s.lock.Lock()
defer s.lock.Unlock()
s.publisherID = publisherID
s.publisherIdentity = publisherIdentity
}
func (s *trackSubscription) getPublisherID() livekit.ParticipantID {
s.lock.RLock()
defer s.lock.RUnlock()
return s.publisherID
}
func (s *trackSubscription) setDesired(desired bool) bool {
s.lock.Lock()
defer s.lock.Unlock()
if desired {
// as long as user explicitly set it to desired
// we'll reset the timer so it has sufficient time to reconcile
t := time.Now()
s.subStartedAt.Store(&t)
s.subscribeAt.Store(&t)
s.keepUntil = time.Time{}
}
if s.desired == desired {
return false
}
s.desired = desired
// Keep observers until teardown: an unsubscribe may be canceled before reconciliation.
if desired {
// reset attempts
s.numAttempts.Store(0)
}
return true
}
func (s *trackSubscription) isDesired() bool {
s.lock.RLock()
defer s.lock.RUnlock()
return s.desired
}
func (s *trackSubscription) recordAttempt(success bool) {
if !success {
if s.numAttempts.Load() == 0 {
// on first failure, we'd want to start the timer
t := time.Now()
s.subStartedAt.Store(&t)
}
s.numAttempts.Add(1)
} else {
s.numAttempts.Store(0)
}
}
func (s *trackSubscription) getNumAttempts() int32 {
return s.numAttempts.Load()
}
func (s *trackSubscription) keepForSubscribe() {
s.lock.Lock()
defer s.lock.Unlock()
if !s.desired {
s.keepUntil = time.Now().Add(notFoundTimeout)
}
}
func (s *trackSubscription) isKeptLocked() bool {
return time.Now().Before(s.keepUntil)
}
func (s *trackSubscription) durationSinceStart() time.Duration {
t := s.subStartedAt.Load()
if t == nil {
return 0
}
return time.Since(*t)
}
func (s *trackSubscription) setChangedNotifier(notifier types.ChangeNotifier) bool {
s.lock.Lock()
defer s.lock.Unlock()
return s.setChangedNotifierLocked(notifier)
}
func (s *trackSubscription) setChangedNotifierLocked(notifier types.ChangeNotifier) bool {
if s.changedNotifier == notifier {
return false
}
existing := s.changedNotifier
s.changedNotifier = notifier
if existing != nil {
existing.RemoveObserver(string(s.subscriberID))
}
return true
}
func (s *trackSubscription) setRemovedNotifier(notifier types.ChangeNotifier) bool {
s.lock.Lock()
defer s.lock.Unlock()
return s.setRemovedNotifierLocked(notifier)
}
func (s *trackSubscription) setRemovedNotifierLocked(notifier types.ChangeNotifier) bool {
if s.removedNotifier == notifier {
return false
}
existing := s.removedNotifier
s.removedNotifier = notifier
if existing != nil {
existing.RemoveObserver(string(s.subscriberID))
}
return true
}
// The full scan also selects attached, undesired tracks for unsubscribe.
// Among trackless entries, skip a settings hold only if it has no observers.
func (s *trackSubscription) needsCleanup() bool {
s.lock.RLock()
defer s.lock.RUnlock()
return !s.desired && (s.changedNotifier != nil || s.removedNotifier != nil || !s.isKeptLocked())
}
// Called with the manager lock held. A settings hold keeps the entry, not its observers.
func (s *trackSubscription) cleanup(hasTrackLocked func() bool) bool {
s.lock.Lock()
defer s.lock.Unlock()
if s.desired || hasTrackLocked() {
return false
}
s.setChangedNotifierLocked(nil)
s.setRemovedNotifierLocked(nil)
return !s.isKeptLocked()
}
func (s *trackSubscription) handleSourceTrackRemoved() {
s.lock.Lock()
defer s.lock.Unlock()
// source track removed, we would unsubscribe
s.logger.Debugw("unsubscribing from track since source track was removed")
s.desired = false
s.setChangedNotifierLocked(nil)
s.setRemovedNotifierLocked(nil)
}
// --------------------------------------------------------------------------------------
type mediaTrackSubscription struct {
trackSubscription
settings *livekit.UpdateTrackSettings
subscribedTrack types.SubscribedTrack
eventSent atomic.Bool
bound bool
kind atomic.Pointer[livekit.TrackType]
succRecordCounter atomic.Int32
}
func newMediaTrackSubscription(subscriberID livekit.ParticipantID, trackID livekit.TrackID, l logger.Logger) *mediaTrackSubscription {
s := &mediaTrackSubscription{
trackSubscription: trackSubscription{
subscriberID: subscriberID,
trackID: trackID,
logger: l,
},
}
t := time.Now()
s.subscribeAt.Store(&t)
return s
}
func (s *mediaTrackSubscription) setSubscribedTrack(track types.SubscribedTrack) {
s.lock.Lock()
oldTrack := s.subscribedTrack
s.subscribedTrack = track
s.bound = false
settings := s.settings
s.lock.Unlock()
if settings != nil && track != nil {
s.logger.Debugw("restoring subscriber settings", "settings", logger.Proto(settings))
track.UpdateSubscriberSettings(settings, true)
}
if oldTrack != nil {
oldTrack.OnClose(nil)
}
}
func (s *mediaTrackSubscription) getSubscribedTrack() types.SubscribedTrack {
s.lock.RLock()
defer s.lock.RUnlock()
return s.subscribedTrack
}
func (s *mediaTrackSubscription) trySetKind(kind livekit.TrackType) {
s.kind.CompareAndSwap(nil, &kind)
}
func (s *mediaTrackSubscription) getKind() (livekit.TrackType, bool) {
kind := s.kind.Load()
if kind == nil {
return livekit.TrackType_AUDIO, false
}
return *kind, true
}
func (s *mediaTrackSubscription) setSettings(settings *livekit.UpdateTrackSettings) {
s.lock.Lock()
settings = mergeSubscriberSettings(s.settings, settings)
s.settings = settings
subTrack := s.subscribedTrack
s.lock.Unlock()
if subTrack != nil {
subTrack.UpdateSubscriberSettings(settings, false)
}
}
// mark the subscription as bound - when we've received the client's answer
func (s *mediaTrackSubscription) setBound() {
s.lock.Lock()
defer s.lock.Unlock()
s.bound = true
}
func (s *mediaTrackSubscription) isBound() bool {
s.lock.RLock()
defer s.lock.RUnlock()
return s.bound
}
func (s *mediaTrackSubscription) maybeRecordError(tl types.ParticipantTelemetryListener, err error, isUserError bool) {
if s.eventSent.Swap(true) {
return
}
tl.OnTrackSubscribeFailed(s.subscriberID, s.trackID, err, isUserError)
}
func (s *mediaTrackSubscription) maybeRecordSuccess(tl types.ParticipantTelemetryListener) {
subTrack := s.getSubscribedTrack()
if subTrack == nil {
return
}
mediaTrack := subTrack.MediaTrack()
if mediaTrack == nil {
return
}
d := time.Since(*s.subscribeAt.Load())
s.logger.Debugw("track subscribed", "cost", d.Milliseconds())
subscriber := subTrack.Subscriber()
prometheus.RecordSubscribeTime(
subscriber.GetCountry(),
mediaTrack.Source(),
mediaTrack.Kind(),
d,
subscriber.GetClientInfo().GetSdk(),
subscriber.Kind(),
int(s.succRecordCounter.Inc()),
)
eventSent := s.eventSent.Swap(true)
pi := &livekit.ParticipantInfo{
Identity: string(subTrack.PublisherIdentity()),
Sid: string(subTrack.PublisherID()),
}
tl.OnTrackSubscribed(s.subscriberID, mediaTrack.ToProto(), pi, !eventSent)
}
func (s *mediaTrackSubscription) recordStreamStartLatency(elapsed time.Duration) {
subTrack := s.getSubscribedTrack()
if subTrack == nil {
return
}
mediaTrack := subTrack.MediaTrack()
if mediaTrack == nil {
return
}
s.logger.Debugw("track subscribe stream started", "cost", elapsed.Milliseconds())
subscriber := subTrack.Subscriber()
prometheus.RecordSubscribeStreamStartTime(
subscriber.GetCountry(),
mediaTrack.Source(),
mediaTrack.Kind(),
elapsed,
subscriber.GetClientInfo().GetSdk(),
subscriber.Kind(),
)
}
func (s *mediaTrackSubscription) isCanceled() bool {
return !s.eventSent.Load() && s.isDesired()
}
func (s *mediaTrackSubscription) needsSubscribe() bool {
s.lock.RLock()
defer s.lock.RUnlock()
return s.desired && s.subscribedTrack == nil
}
func (s *mediaTrackSubscription) needsUnsubscribe() bool {
s.lock.RLock()
defer s.lock.RUnlock()
return !s.desired && s.subscribedTrack != nil
}
func (s *mediaTrackSubscription) needsBind() bool {
s.lock.RLock()
defer s.lock.RUnlock()
return s.desired && s.subscribedTrack != nil && !s.bound
}
// -----------------------------------------------------------------
type dataTrackSubscription struct {
trackSubscription
subscriptionOptions *livekit.DataTrackSubscriptionOptions
dataDownTrack types.DataDownTrack
}
func newDataTrackSubscription(subscriberID livekit.ParticipantID, trackID livekit.TrackID, l logger.Logger) *dataTrackSubscription {
s := &dataTrackSubscription{
trackSubscription: trackSubscription{
subscriberID: subscriberID,
trackID: trackID,
logger: l,
},
}
t := time.Now()
s.subscribeAt.Store(&t)
return s
}
func (s *dataTrackSubscription) needsSubscribe() bool {
s.lock.RLock()
defer s.lock.RUnlock()
return s.desired && s.dataDownTrack == nil
}
func (s *dataTrackSubscription) needsUnsubscribe() bool {
s.lock.RLock()
defer s.lock.RUnlock()
return !s.desired && s.dataDownTrack != nil
}
func (s *dataTrackSubscription) setDataDownTrack(dataDownTrack types.DataDownTrack) {
s.lock.Lock()
oldDataDownTrack := s.dataDownTrack
s.dataDownTrack = dataDownTrack
subscriptionOptions := s.subscriptionOptions
s.lock.Unlock()
if dataDownTrack != nil {
s.logger.Debugw("restoring data track subscription options", "subscriptionOptions", logger.Proto(subscriptionOptions))
dataDownTrack.UpdateSubscriptionOptions(subscriptionOptions)
}
if oldDataDownTrack != nil {
oldDataDownTrack.OnClose(nil)
}
}
func (s *dataTrackSubscription) getDataDownTrack() types.DataDownTrack {
s.lock.RLock()
defer s.lock.RUnlock()
return s.dataDownTrack
}
func (s *dataTrackSubscription) setSubscriptionOptions(subscriptionOptions *livekit.DataTrackSubscriptionOptions) {
s.lock.Lock()
s.subscriptionOptions = subscriptionOptions
dataDownTrack := s.dataDownTrack
s.lock.Unlock()
if dataDownTrack != nil {
dataDownTrack.UpdateSubscriptionOptions(subscriptionOptions)
}
}