diff --git a/pkg/rtc/subscriptionmanager.go b/pkg/rtc/subscriptionmanager.go index 6a3b2756..5025a335 100644 --- a/pkg/rtc/subscriptionmanager.go +++ b/pkg/rtc/subscriptionmanager.go @@ -391,15 +391,14 @@ func (m *SubscriptionManager) reconcileSubscription(s *trackSubscription) { if s.needsUnsubscribe() { if err := m.unsubscribe(s); err != nil { s.logger.Warnw("failed to unsubscribe", err) - } else { - // successfully unsubscribed, remove from map - m.lock.Lock() - if !s.isDesired() { - s.logger.Debugw("unsubscribe removing subscription") - delete(m.subscriptions, s.trackID) - } - m.lock.Unlock() } + // 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 susbcribed 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 } @@ -414,14 +413,12 @@ func (m *SubscriptionManager) reconcileSubscription(s *trackSubscription) { } } + m.lock.Lock() if s.needsCleanup() { - m.lock.Lock() - if !s.isDesired() { - s.logger.Debugw("cleanup removing subscription") - delete(m.subscriptions, s.trackID) - } - m.lock.Unlock() + s.logger.Debugw("cleanup removing subscription") + delete(m.subscriptions, s.trackID) } + m.lock.Unlock() } // trigger an immediate reconciliation, when trackID is empty, will reconcile all subscriptions