From cfd3777f47423345e9065207671e72466b80e411 Mon Sep 17 00:00:00 2001 From: Raja Subramanian Date: Wed, 5 Jun 2024 21:54:22 +0530 Subject: [PATCH] Use a safety net OnClose to remove track from peer connection. (#2758) --- pkg/rtc/mediatracksubscriptions.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/pkg/rtc/mediatracksubscriptions.go b/pkg/rtc/mediatracksubscriptions.go index aaf5b02a1..e2f4d5b00 100644 --- a/pkg/rtc/mediatracksubscriptions.go +++ b/pkg/rtc/mediatracksubscriptions.go @@ -289,6 +289,20 @@ func (t *MediaTrackSubscriptions) AddSubscriber(sub types.LocalParticipant, wr * // negotiation isn't required if we've replaced track subTrack.SetNeedsNegotiation(!replacedTrack) subTrack.SetRTPSender(sender) + // it is possible that subscribed track is closed before subscription manager sets + // the `OnClose` callback. That handler in subscription manager removes the track + // from the peer connection. + // + // But, the subscription could be removed early if the published track is closed + // while adding subscription. In those cases, subscription manager would not have set + // the `OnClose` callback. So, set it here to handle cases of early close. + subTrack.OnClose(func(willBeResumed bool) { + if !willBeResumed { + if err := sub.RemoveTrackFromSubscriber(sender); err != nil { + t.params.Logger.Warnw("could not remove track from peer connection", err) + } + } + }) downTrack.SetTransceiver(transceiver)