diff --git a/pkg/config/config.go b/pkg/config/config.go index c6b4d6fb..eb3388cc 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -93,6 +93,9 @@ type RTCConfig struct { // force a reconnect on a publication error ReconnectOnPublicationError *bool `yaml:"reconnect_on_publication_error,omitempty"` + + // force a reconnect on a subscription error + ReconnectOnSubscriptionError *bool `yaml:"reconnect_on_subscription_error,omitempty"` } type TURNServer struct { diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index 99e1ce9c..912aacc3 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -42,11 +42,12 @@ func TestGeneratedFlags(t *testing.T) { app.Flags = append(app.Flags, generatedFlags...) set := flag.NewFlagSet("test", 0) - set.Bool("rtc.use_ice_lite", true, "") // bool - set.String("redis.address", "localhost:6379", "") // string - set.Uint("prometheus_port", 9999, "") // uint32 - set.Bool("rtc.allow_tcp_fallback", true, "") // pointer - set.Bool("rtc.reconnect_on_publication_error", true, "") // pointer + set.Bool("rtc.use_ice_lite", true, "") // bool + set.String("redis.address", "localhost:6379", "") // string + set.Uint("prometheus_port", 9999, "") // uint32 + set.Bool("rtc.allow_tcp_fallback", true, "") // pointer + set.Bool("rtc.reconnect_on_publication_error", true, "") // pointer + set.Bool("rtc.reconnect_on_subscription_error", false, "") // pointer c := cli.NewContext(app, set, nil) conf, err := NewConfig("", true, c, nil) @@ -55,8 +56,13 @@ func TestGeneratedFlags(t *testing.T) { require.True(t, conf.RTC.UseICELite) require.Equal(t, "localhost:6379", conf.Redis.Address) require.Equal(t, uint32(9999), conf.PrometheusPort) + require.NotNil(t, conf.RTC.AllowTCPFallback) require.True(t, *conf.RTC.AllowTCPFallback) + require.NotNil(t, conf.RTC.ReconnectOnPublicationError) require.True(t, *conf.RTC.ReconnectOnPublicationError) + + require.NotNil(t, conf.RTC.ReconnectOnSubscriptionError) + require.False(t, *conf.RTC.ReconnectOnSubscriptionError) } diff --git a/pkg/rtc/mediatrackreceiver.go b/pkg/rtc/mediatrackreceiver.go index 824a2a5e..b95c2dc1 100644 --- a/pkg/rtc/mediatrackreceiver.go +++ b/pkg/rtc/mediatrackreceiver.go @@ -428,7 +428,7 @@ func (t *MediaTrackReceiver) removePendingSubscribeOp(subscriberID livekit.Parti // AddSubscriber subscribes sub to current mediaTrack func (t *MediaTrackReceiver) AddSubscriber(sub types.LocalParticipant) error { - if sub.EnqueueSubscribeTrack(t.ID(), t.params.IsRelayed, t.addSubscriber) { + if sub.EnqueueSubscribeTrack(t.ID(), t.params.MediaTrack, t.params.IsRelayed, t.addSubscriber) { t.addPendingSubscribeOp(sub.ID()) } return nil @@ -506,7 +506,7 @@ func (t *MediaTrackReceiver) RemoveSubscriber(subscriberID livekit.ParticipantID } sub := subTrack.Subscriber() - if sub.EnqueueUnsubscribeTrack(subTrack.ID(), t.params.IsRelayed, willBeResumed, t.removeSubscriber) { + if sub.EnqueueUnsubscribeTrack(subTrack.ID(), t.params.MediaTrack, t.params.IsRelayed, willBeResumed, t.removeSubscriber) { t.addPendingSubscribeOp(sub.ID()) } } diff --git a/pkg/rtc/mediatracksubscriptions.go b/pkg/rtc/mediatracksubscriptions.go index de6a94f5..0f9f8687 100644 --- a/pkg/rtc/mediatracksubscriptions.go +++ b/pkg/rtc/mediatracksubscriptions.go @@ -248,7 +248,7 @@ func (t *MediaTrackSubscriptions) AddSubscriber(sub types.LocalParticipant, wr * // since sub will lock, run it in a goroutine to avoid deadlocks go func() { - sub.AddSubscribedTrack(subTrack) + sub.AddSubscribedTrack(subTrack, t.params.MediaTrack) if !replacedTrack { sub.Negotiate(false) } @@ -424,7 +424,7 @@ func (t *MediaTrackSubscriptions) downTrackClosed( } } - sub.RemoveSubscribedTrack(subTrack) + sub.RemoveSubscribedTrack(subTrack, t.params.MediaTrack) if !willBeResumed { sub.Negotiate(false) } diff --git a/pkg/rtc/participant.go b/pkg/rtc/participant.go index 765f22d9..49ac9554 100644 --- a/pkg/rtc/participant.go +++ b/pkg/rtc/participant.go @@ -64,31 +64,32 @@ type SubscribeRequest struct { } type ParticipantParams struct { - Identity livekit.ParticipantIdentity - Name livekit.ParticipantName - SID livekit.ParticipantID - Config *WebRTCConfig - Sink routing.MessageSink - AudioConfig config.AudioConfig - VideoConfig config.VideoConfig - ProtocolVersion types.ProtocolVersion - Telemetry telemetry.TelemetryService - PLIThrottleConfig config.PLIThrottleConfig - CongestionControlConfig config.CongestionControlConfig - EnabledCodecs []*livekit.Codec - Logger logger.Logger - SimTracks map[uint32]SimulcastTrackInfo - Grants *auth.ClaimGrants - InitialVersion uint32 - ClientConf *livekit.ClientConfiguration - ClientInfo ClientInfo - Region string - Migration bool - AdaptiveStream bool - AllowTCPFallback bool - TURNSEnabled bool - GetParticipantInfo func(pID livekit.ParticipantID) *livekit.ParticipantInfo - ReconnectOnPublicationError bool + Identity livekit.ParticipantIdentity + Name livekit.ParticipantName + SID livekit.ParticipantID + Config *WebRTCConfig + Sink routing.MessageSink + AudioConfig config.AudioConfig + VideoConfig config.VideoConfig + ProtocolVersion types.ProtocolVersion + Telemetry telemetry.TelemetryService + PLIThrottleConfig config.PLIThrottleConfig + CongestionControlConfig config.CongestionControlConfig + EnabledCodecs []*livekit.Codec + Logger logger.Logger + SimTracks map[uint32]SimulcastTrackInfo + Grants *auth.ClaimGrants + InitialVersion uint32 + ClientConf *livekit.ClientConfiguration + ClientInfo ClientInfo + Region string + Migration bool + AdaptiveStream bool + AllowTCPFallback bool + TURNSEnabled bool + GetParticipantInfo func(pID livekit.ParticipantID) *livekit.ParticipantInfo + ReconnectOnPublicationError bool + ReconnectOnSubscriptionError bool } type ParticipantImpl struct { @@ -202,6 +203,7 @@ func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) { p.SetResponseSink(params.Sink) p.supervisor.OnPublicationError(p.onPublicationError) + p.supervisor.OnSubscriptionError(p.onSubscriptionError) var err error // keep last participants and when updates were sent @@ -919,9 +921,10 @@ func (p *ParticipantImpl) VerifySubscribeParticipantInfo(pID livekit.Participant } // AddSubscribedTrack adds a track to the participant's subscribed list -func (p *ParticipantImpl) AddSubscribedTrack(subTrack types.SubscribedTrack) { +func (p *ParticipantImpl) AddSubscribedTrack(subTrack types.SubscribedTrack, sourceTrack types.MediaTrack) { p.lock.Lock() if v, ok := p.trackPublisherVersion[subTrack.ID()]; ok && v > subTrack.PublisherVersion() { + p.supervisor.SetSubscribedTrack(subTrack.ID(), subTrack, sourceTrack) p.lock.Unlock() p.params.Logger.Infow("ignoring add subscribedTrack from older version", "current", v, @@ -939,7 +942,7 @@ func (p *ParticipantImpl) AddSubscribedTrack(subTrack types.SubscribedTrack) { onSubscribedTo := p.onSubscribedTo p.subscribedTracks[subTrack.ID()] = subTrack - p.supervisor.SetSubscribedTrack(subTrack.ID(), subTrack) + p.supervisor.SetSubscribedTrack(subTrack.ID(), subTrack, sourceTrack) settings := p.subscribedTracksSettings[subTrack.ID()] p.lock.Unlock() @@ -966,9 +969,10 @@ func (p *ParticipantImpl) AddSubscribedTrack(subTrack types.SubscribedTrack) { } // RemoveSubscribedTrack removes a track to the participant's subscribed list -func (p *ParticipantImpl) RemoveSubscribedTrack(subTrack types.SubscribedTrack) { +func (p *ParticipantImpl) RemoveSubscribedTrack(subTrack types.SubscribedTrack, sourceTrack types.MediaTrack) { p.lock.Lock() if v, ok := p.trackPublisherVersion[subTrack.ID()]; ok && v > subTrack.PublisherVersion() { + p.supervisor.ClearSubscribedTrack(subTrack.ID(), subTrack, sourceTrack) p.lock.Unlock() p.params.Logger.Infow("ignoring remove subscribedTrack from older version", "current", v, @@ -984,7 +988,7 @@ func (p *ParticipantImpl) RemoveSubscribedTrack(subTrack types.SubscribedTrack) p.trackPublisherVersion[subTrack.ID()] = subTrack.PublisherVersion() delete(p.subscribedTracks, subTrack.ID()) - p.supervisor.ClearSubscribedTrack(subTrack.ID(), subTrack) + p.supervisor.ClearSubscribedTrack(subTrack.ID(), subTrack, sourceTrack) // remove from subscribed map numRemaining := 0 @@ -2011,9 +2015,15 @@ func (p *ParticipantImpl) issueFullReconnect(reason types.ParticipantCloseReason } func (p *ParticipantImpl) onPublicationError(trackID livekit.TrackID) { - p.params.Logger.Infow("publication failed", "trackID", trackID) if p.params.ReconnectOnPublicationError { - p.params.Logger.Infow("starting full reconnect") + p.params.Logger.Infow("issuing full reconnect on publication error", "trackID", trackID) + p.issueFullReconnect(types.ParticipantCloseReasonPublicationError) + } +} + +func (p *ParticipantImpl) onSubscriptionError(trackID livekit.TrackID) { + if p.params.ReconnectOnSubscriptionError { + p.params.Logger.Infow("issuing full reconnect on subscription error", "trackID", trackID) p.issueFullReconnect(types.ParticipantCloseReasonPublicationError) } } @@ -2023,7 +2033,7 @@ func (p *ParticipantImpl) onAnyTransportNegotiationFailed() { p.issueFullReconnect(types.ParticipantCloseReasonNegotiateFailed) } -func (p *ParticipantImpl) EnqueueSubscribeTrack(trackID livekit.TrackID, isRelayed bool, f func(sub types.LocalParticipant) error) bool { +func (p *ParticipantImpl) EnqueueSubscribeTrack(trackID livekit.TrackID, sourceTrack types.MediaTrack, isRelayed bool, f func(sub types.LocalParticipant) error) bool { // do not queue subscription is participant is already closed/disconnected if p.isClosed.Load() || p.State() == livekit.ParticipantInfo_DISCONNECTED { return false @@ -2031,7 +2041,7 @@ func (p *ParticipantImpl) EnqueueSubscribeTrack(trackID livekit.TrackID, isRelay p.params.Logger.Debugw("queuing subscribe", "trackID", trackID, "relayed", isRelayed) - p.supervisor.UpdateSubscription(trackID, true) + p.supervisor.UpdateSubscription(trackID, true, sourceTrack) p.lock.Lock() p.subscriptionRequestsQueue[trackID] = append(p.subscriptionRequestsQueue[trackID], SubscribeRequest{ @@ -2046,13 +2056,14 @@ func (p *ParticipantImpl) EnqueueSubscribeTrack(trackID livekit.TrackID, isRelay func (p *ParticipantImpl) EnqueueUnsubscribeTrack( trackID livekit.TrackID, + sourceTrack types.MediaTrack, isRelayed bool, willBeResumed bool, f func(subscriberID livekit.ParticipantID, willBeResumed bool) error, ) bool { p.params.Logger.Debugw("queuing unsubscribe", "trackID", trackID, "relayed", isRelayed) - p.supervisor.UpdateSubscription(trackID, false) + p.supervisor.UpdateSubscription(trackID, false, sourceTrack) p.lock.Lock() p.subscriptionRequestsQueue[trackID] = append(p.subscriptionRequestsQueue[trackID], SubscribeRequest{ diff --git a/pkg/rtc/supervisor/participant_supervisor.go b/pkg/rtc/supervisor/participant_supervisor.go index b8e84723..9276a66d 100644 --- a/pkg/rtc/supervisor/participant_supervisor.go +++ b/pkg/rtc/supervisor/participant_supervisor.go @@ -18,24 +18,30 @@ type ParticipantSupervisorParams struct { Logger logger.Logger } +type trackMonitor struct { + opMon types.OperationMonitor + err error +} + type ParticipantSupervisor struct { params ParticipantSupervisorParams lock sync.RWMutex isPublisherConnected bool - publications map[livekit.TrackID]types.OperationMonitor - subscriptions map[livekit.TrackID]types.OperationMonitor + publications map[livekit.TrackID]*trackMonitor + subscriptions map[livekit.TrackID]*trackMonitor isStopped atomic.Bool - onPublicationError func(trackID livekit.TrackID) + onPublicationError func(trackID livekit.TrackID) + onSubscriptionError func(trackID livekit.TrackID) } func NewParticipantSupervisor(params ParticipantSupervisorParams) *ParticipantSupervisor { p := &ParticipantSupervisor{ params: params, - publications: make(map[livekit.TrackID]types.OperationMonitor), - subscriptions: make(map[livekit.TrackID]types.OperationMonitor), + publications: make(map[livekit.TrackID]*trackMonitor), + subscriptions: make(map[livekit.TrackID]*trackMonitor), } go p.checkState() @@ -61,12 +67,26 @@ func (p *ParticipantSupervisor) getOnPublicationError() func(trackID livekit.Tra return p.onPublicationError } +func (p *ParticipantSupervisor) OnSubscriptionError(f func(trackID livekit.TrackID)) { + p.lock.Lock() + defer p.lock.Unlock() + + p.onSubscriptionError = f +} + +func (p *ParticipantSupervisor) getOnSubscriptionError() func(trackID livekit.TrackID) { + p.lock.RLock() + defer p.lock.RUnlock() + + return p.onSubscriptionError +} + func (p *ParticipantSupervisor) SetPublisherPeerConnectionConnected(isConnected bool) { p.lock.Lock() p.isPublisherConnected = isConnected for _, pm := range p.publications { - pm.PostEvent(types.OperationMonitorEventPublisherPeerConnectionConnected, p.isPublisherConnected) + pm.opMon.PostEvent(types.OperationMonitorEventPublisherPeerConnectionConnected, p.isPublisherConnected) } p.lock.Unlock() } @@ -75,16 +95,18 @@ func (p *ParticipantSupervisor) AddPublication(trackID livekit.TrackID) { p.lock.Lock() pm, ok := p.publications[trackID] if !ok { - pm = NewPublicationMonitor( - PublicationMonitorParams{ - TrackID: trackID, - IsPeerConnectionConnected: p.isPublisherConnected, - Logger: p.params.Logger, - }, - ) + pm = &trackMonitor{ + opMon: NewPublicationMonitor( + PublicationMonitorParams{ + TrackID: trackID, + IsPeerConnectionConnected: p.isPublisherConnected, + Logger: p.params.Logger, + }, + ), + } p.publications[trackID] = pm } - pm.PostEvent(types.OperationMonitorEventAddPendingPublication, nil) + pm.opMon.PostEvent(types.OperationMonitorEventAddPendingPublication, nil) p.lock.Unlock() } @@ -92,7 +114,7 @@ func (p *ParticipantSupervisor) SetPublicationMute(trackID livekit.TrackID, isMu p.lock.Lock() pm, ok := p.publications[trackID] if ok { - pm.PostEvent(types.OperationMonitorEventSetPublicationMute, isMuted) + pm.opMon.PostEvent(types.OperationMonitorEventSetPublicationMute, isMuted) } p.lock.Unlock() } @@ -101,7 +123,7 @@ func (p *ParticipantSupervisor) SetPublishedTrack(trackID livekit.TrackID, pubTr p.lock.RLock() pm, ok := p.publications[trackID] if ok { - pm.PostEvent(types.OperationMonitorEventSetPublishedTrack, pubTrack) + pm.opMon.PostEvent(types.OperationMonitorEventSetPublishedTrack, pubTrack) } p.lock.RUnlock() } @@ -110,36 +132,56 @@ func (p *ParticipantSupervisor) ClearPublishedTrack(trackID livekit.TrackID, pub p.lock.RLock() pm, ok := p.publications[trackID] if ok { - pm.PostEvent(types.OperationMonitorEventClearPublishedTrack, pubTrack) + pm.opMon.PostEvent(types.OperationMonitorEventClearPublishedTrack, pubTrack) } p.lock.RUnlock() } -func (p *ParticipantSupervisor) UpdateSubscription(trackID livekit.TrackID, isSubscribed bool) { +func (p *ParticipantSupervisor) UpdateSubscription(trackID livekit.TrackID, isSubscribe bool, sourceTrack types.MediaTrack) { p.lock.Lock() sm, ok := p.subscriptions[trackID] if !ok { - sm = NewSubscriptionMonitor(SubscriptionMonitorParams{TrackID: trackID, Logger: p.params.Logger}) + sm = &trackMonitor{ + opMon: NewSubscriptionMonitor(SubscriptionMonitorParams{TrackID: trackID, Logger: p.params.Logger}), + } p.subscriptions[trackID] = sm } - sm.PostEvent(types.OperationMonitorEventUpdateSubscription, isSubscribed) + sm.opMon.PostEvent( + types.OperationMonitorEventUpdateSubscription, + SubscriptionOpParams{ + SourceTrack: sourceTrack, + IsSubscribe: isSubscribe, + }, + ) p.lock.Unlock() } -func (p *ParticipantSupervisor) SetSubscribedTrack(trackID livekit.TrackID, subTrack types.SubscribedTrack) { +func (p *ParticipantSupervisor) SetSubscribedTrack(trackID livekit.TrackID, subTrack types.SubscribedTrack, sourceTrack types.MediaTrack) { p.lock.RLock() sm, ok := p.subscriptions[trackID] if ok { - sm.PostEvent(types.OperationMonitorEventSetSubscribedTrack, subTrack) + sm.opMon.PostEvent( + types.OperationMonitorEventSetSubscribedTrack, + UpdateSubscribedTrackParams{ + SourceTrack: sourceTrack, + SubscribedTrack: subTrack, + }, + ) } p.lock.RUnlock() } -func (p *ParticipantSupervisor) ClearSubscribedTrack(trackID livekit.TrackID, subTrack types.SubscribedTrack) { +func (p *ParticipantSupervisor) ClearSubscribedTrack(trackID livekit.TrackID, subTrack types.SubscribedTrack, sourceTrack types.MediaTrack) { p.lock.RLock() sm, ok := p.subscriptions[trackID] if ok { - sm.PostEvent(types.OperationMonitorEventClearSubscribedTrack, subTrack) + sm.opMon.PostEvent( + types.OperationMonitorEventClearSubscribedTrack, + UpdateSubscribedTrackParams{ + SourceTrack: sourceTrack, + SubscribedTrack: subTrack, + }, + ) } p.lock.RUnlock() } @@ -161,11 +203,18 @@ func (p *ParticipantSupervisor) checkPublications() { var removablePublications []livekit.TrackID p.lock.RLock() for trackID, pm := range p.publications { - if err := pm.Check(); err != nil { - p.params.Logger.Errorw("supervisor error on publication", err, "trackID", trackID) - erroredPublications = append(erroredPublications, trackID) + if err := pm.opMon.Check(); err != nil { + if pm.err == nil { + p.params.Logger.Errorw("supervisor error on publication", err, "trackID", trackID) + pm.err = err + erroredPublications = append(erroredPublications, trackID) + } } else { - if pm.IsIdle() { + if pm.err != nil { + p.params.Logger.Infow("supervisor publication recovered", "trackID", trackID) + pm.err = err + } + if pm.opMon.IsIdle() { removablePublications = append(removablePublications, trackID) } } @@ -186,13 +235,22 @@ func (p *ParticipantSupervisor) checkPublications() { } func (p *ParticipantSupervisor) checkSubscriptions() { + var erroredSubscriptions []livekit.TrackID var removableSubscriptions []livekit.TrackID p.lock.RLock() for trackID, sm := range p.subscriptions { - if err := sm.Check(); err != nil { - p.params.Logger.Errorw("supervisor error on subscription", err, "trackID", trackID) + if err := sm.opMon.Check(); err != nil { + if sm.err == nil { + p.params.Logger.Errorw("supervisor error on subscription", err, "trackID", trackID) + sm.err = err + erroredSubscriptions = append(erroredSubscriptions, trackID) + } } else { - if sm.IsIdle() { + if sm.err != nil { + p.params.Logger.Infow("supervisor subscription recovered", "trackID", trackID) + sm.err = err + } + if sm.opMon.IsIdle() { removableSubscriptions = append(removableSubscriptions, trackID) } } @@ -204,4 +262,10 @@ func (p *ParticipantSupervisor) checkSubscriptions() { delete(p.subscriptions, trackID) } p.lock.Unlock() + + if onSubscriptionError := p.getOnSubscriptionError(); onSubscriptionError != nil { + for _, trackID := range erroredSubscriptions { + onSubscriptionError(trackID) + } + } } diff --git a/pkg/rtc/supervisor/publication_monitor.go b/pkg/rtc/supervisor/publication_monitor.go index 76876b12..c9050c48 100644 --- a/pkg/rtc/supervisor/publication_monitor.go +++ b/pkg/rtc/supervisor/publication_monitor.go @@ -40,8 +40,6 @@ type PublicationMonitor struct { publishedTrack types.LocalMediaTrack isMuted bool unmutedAt time.Time - - lastError error } func NewPublicationMonitor(params PublicationMonitorParams) *PublicationMonitor { @@ -118,7 +116,7 @@ func (p *PublicationMonitor) clearPublishedTrack(pubTrack types.LocalMediaTrack) if p.publishedTrack == pubTrack { p.publishedTrack = nil } else { - p.params.Logger.Errorw("mismatched published track on clear", nil, "trackID", p.params.TrackID) + p.params.Logger.Errorw("supervisor: mismatched published track on clear", nil, "trackID", p.params.TrackID) } p.update() @@ -127,12 +125,6 @@ func (p *PublicationMonitor) clearPublishedTrack(pubTrack types.LocalMediaTrack) func (p *PublicationMonitor) Check() error { p.lock.RLock() - if p.lastError != nil { - p.lock.RUnlock() - // return an error only once - return nil - } - var pub *publish if p.desiredPublishes.Len() > 0 { pub = p.desiredPublishes.Front().(*publish) @@ -148,10 +140,6 @@ func (p *PublicationMonitor) Check() error { if pub.isStart && !isMuted && !unmutedAt.IsZero() && time.Since(unmutedAt) > publishWaitDuration { // timed out waiting for publish - p.lock.Lock() - p.lastError = errPublishTimeout - p.lock.Unlock() - return errPublishTimeout } @@ -183,7 +171,5 @@ func (p *PublicationMonitor) update() { p.desiredPublishes.PushFront(pub) return } - - p.lastError = nil } } diff --git a/pkg/rtc/supervisor/subscription_monitor.go b/pkg/rtc/supervisor/subscription_monitor.go index 0edf5d43..866cf5b1 100644 --- a/pkg/rtc/supervisor/subscription_monitor.go +++ b/pkg/rtc/supervisor/subscription_monitor.go @@ -12,7 +12,7 @@ import ( ) const ( - transitionWaitDuration = 10 * time.Second + transitionWaitDuration = 20 * time.Second ) var ( @@ -25,6 +25,22 @@ type transition struct { at time.Time } +type subscriptionOps struct { + desiredTransitions deque.Deque + + subscribedTrack types.SubscribedTrack +} + +type SubscriptionOpParams struct { + SourceTrack types.MediaTrack + IsSubscribe bool +} + +type UpdateSubscribedTrackParams struct { + SourceTrack types.MediaTrack + SubscribedTrack types.SubscribedTrack +} + type SubscriptionMonitorParams struct { TrackID livekit.TrackID Logger logger.Logger @@ -33,38 +49,36 @@ type SubscriptionMonitorParams struct { type SubscriptionMonitor struct { params SubscriptionMonitorParams - lock sync.RWMutex - desiredTransitions deque.Deque - - subscribedTrack types.SubscribedTrack - - lastError error + lock sync.RWMutex + subscriptionOpsBySource map[types.MediaTrack]*subscriptionOps } func NewSubscriptionMonitor(params SubscriptionMonitorParams) *SubscriptionMonitor { s := &SubscriptionMonitor{ - params: params, + params: params, + subscriptionOpsBySource: make(map[types.MediaTrack]*subscriptionOps), } - s.desiredTransitions.SetMinCapacity(2) return s } func (s *SubscriptionMonitor) PostEvent(ome types.OperationMonitorEvent, omd types.OperationMonitorData) { switch ome { case types.OperationMonitorEventUpdateSubscription: - s.updateSubscription(omd.(bool)) + s.updateSubscription(omd.(SubscriptionOpParams)) case types.OperationMonitorEventSetSubscribedTrack: - s.setSubscribedTrack(omd.(types.SubscribedTrack)) + s.setSubscribedTrack(omd.(UpdateSubscribedTrackParams)) case types.OperationMonitorEventClearSubscribedTrack: - s.clearSubscribedTrack(omd.(types.SubscribedTrack)) + s.clearSubscribedTrack(omd.(UpdateSubscribedTrackParams)) } } -func (s *SubscriptionMonitor) updateSubscription(isSubscribe bool) { +func (s *SubscriptionMonitor) updateSubscription(params SubscriptionOpParams) { s.lock.Lock() - s.desiredTransitions.PushBack( + + so := s.getOrCreateSubscriptionOpsForSource(params.SourceTrack) + so.desiredTransitions.PushBack( &transition{ - isSubscribe: isSubscribe, + isSubscribe: params.IsSubscribe, at: time.Now(), }, ) @@ -72,19 +86,21 @@ func (s *SubscriptionMonitor) updateSubscription(isSubscribe bool) { s.lock.Unlock() } -func (s *SubscriptionMonitor) setSubscribedTrack(subTrack types.SubscribedTrack) { +func (s *SubscriptionMonitor) setSubscribedTrack(params UpdateSubscribedTrackParams) { s.lock.Lock() - s.subscribedTrack = subTrack + so := s.getOrCreateSubscriptionOpsForSource(params.SourceTrack) + so.subscribedTrack = params.SubscribedTrack s.update() s.lock.Unlock() } -func (s *SubscriptionMonitor) clearSubscribedTrack(subTrack types.SubscribedTrack) { +func (s *SubscriptionMonitor) clearSubscribedTrack(params UpdateSubscribedTrackParams) { s.lock.Lock() - if s.subscribedTrack == subTrack { - s.subscribedTrack = nil + so := s.getOrCreateSubscriptionOpsForSource(params.SourceTrack) + if so.subscribedTrack == params.SubscribedTrack { + so.subscribedTrack = nil } else { - s.params.Logger.Errorw("mismatched subscribed track on clear", nil, "trackID", s.params.TrackID) + s.params.Logger.Errorw("supervisor: mismatched subscribed track on clear", nil, "trackID", s.params.TrackID) } s.update() @@ -92,37 +108,27 @@ func (s *SubscriptionMonitor) clearSubscribedTrack(subTrack types.SubscribedTrac } func (s *SubscriptionMonitor) Check() error { - s.lock.RLock() - if s.lastError != nil { - s.lock.RUnlock() - // return an error only once - return nil - } + s.lock.Lock() + defer s.lock.Unlock() - var tx *transition - if s.desiredTransitions.Len() > 0 { - tx = s.desiredTransitions.Front().(*transition) - } - s.lock.RUnlock() - - if tx == nil { - return nil - } - - if time.Since(tx.at) > transitionWaitDuration { - // timed out waiting for transition - var err error - if tx.isSubscribe { - err = errSubscribeTimeout - } else { - err = errUnsubscribeTimeout + for _, so := range s.subscriptionOpsBySource { + var tx *transition + if so.desiredTransitions.Len() > 0 { + tx = so.desiredTransitions.Front().(*transition) } - s.lock.Lock() - s.lastError = err - s.lock.Unlock() + if tx == nil { + continue + } - return err + if time.Since(tx.at) > transitionWaitDuration { + // timed out waiting for transition + if tx.isSubscribe { + return errSubscribeTimeout + } else { + return errUnsubscribeTimeout + } + } } // give more time for transition to happen @@ -133,26 +139,41 @@ func (s *SubscriptionMonitor) IsIdle() bool { s.lock.RLock() defer s.lock.RUnlock() - return s.desiredTransitions.Len() == 0 && s.subscribedTrack == nil + return len(s.subscriptionOpsBySource) == 0 +} + +func (s *SubscriptionMonitor) getOrCreateSubscriptionOpsForSource(sourceTrack types.MediaTrack) *subscriptionOps { + so := s.subscriptionOpsBySource[sourceTrack] + if so == nil { + so = &subscriptionOps{} + so.desiredTransitions.SetMinCapacity(4) + s.subscriptionOpsBySource[sourceTrack] = so + } + + return so } func (s *SubscriptionMonitor) update() { - for { - var tx *transition - if s.desiredTransitions.Len() > 0 { - tx = s.desiredTransitions.PopFront().(*transition) - } + for sourceTrack, so := range s.subscriptionOpsBySource { + for { + var tx *transition + if so.desiredTransitions.Len() > 0 { + tx = so.desiredTransitions.PopFront().(*transition) + } - if tx == nil { - return - } + if tx == nil { + break + } - if (tx.isSubscribe && s.subscribedTrack == nil) || (!tx.isSubscribe && s.subscribedTrack != nil) { - // put it back as the condition is not satisfied - s.desiredTransitions.PushFront(tx) - return - } + if (tx.isSubscribe && so.subscribedTrack == nil) || (!tx.isSubscribe && so.subscribedTrack != nil) { + // put it back as the condition is not satisfied + so.desiredTransitions.PushFront(tx) + break + } - s.lastError = nil + if so.desiredTransitions.Len() == 0 && so.subscribedTrack == nil { + delete(s.subscriptionOpsBySource, sourceTrack) + } + } } } diff --git a/pkg/rtc/types/interfaces.go b/pkg/rtc/types/interfaces.go index f498718d..499293a1 100644 --- a/pkg/rtc/types/interfaces.go +++ b/pkg/rtc/types/interfaces.go @@ -262,8 +262,8 @@ type LocalParticipant interface { RemoveTrackFromSubscriber(sender *webrtc.RTPSender) error // subscriptions - AddSubscribedTrack(st SubscribedTrack) - RemoveSubscribedTrack(st SubscribedTrack) + AddSubscribedTrack(st SubscribedTrack, sourceTrack MediaTrack) + RemoveSubscribedTrack(st SubscribedTrack, sourceTrack MediaTrack) UpdateSubscribedTrackSettings(trackID livekit.TrackID, settings *livekit.UpdateTrackSettings) error GetSubscribedTracks() []SubscribedTrack VerifySubscribeParticipantInfo(pID livekit.ParticipantID, version uint32) @@ -312,9 +312,10 @@ type LocalParticipant interface { UncacheDownTrack(rtpTransceiver *webrtc.RTPTransceiver) GetCachedDownTrack(trackID livekit.TrackID) (*webrtc.RTPTransceiver, sfu.DownTrackState) - EnqueueSubscribeTrack(trackID livekit.TrackID, isRelayed bool, f func(sub LocalParticipant) error) bool + EnqueueSubscribeTrack(trackID livekit.TrackID, sourceTrack MediaTrack, isRelayed bool, f func(sub LocalParticipant) error) bool EnqueueUnsubscribeTrack( trackID livekit.TrackID, + sourceTrack MediaTrack, isRelayed bool, willBeResumed bool, f func(subscriberID livekit.ParticipantID, willBeResumed bool) error, diff --git a/pkg/rtc/types/typesfakes/fake_local_participant.go b/pkg/rtc/types/typesfakes/fake_local_participant.go index 1b439379..790c3f93 100644 --- a/pkg/rtc/types/typesfakes/fake_local_participant.go +++ b/pkg/rtc/types/typesfakes/fake_local_participant.go @@ -23,10 +23,11 @@ type FakeLocalParticipant struct { arg1 webrtc.ICECandidateInit arg2 livekit.SignalTarget } - AddSubscribedTrackStub func(types.SubscribedTrack) + AddSubscribedTrackStub func(types.SubscribedTrack, types.MediaTrack) addSubscribedTrackMutex sync.RWMutex addSubscribedTrackArgsForCall []struct { arg1 types.SubscribedTrack + arg2 types.MediaTrack } AddSubscriberStub func(types.LocalParticipant, types.AddSubscriberParams) (int, error) addSubscriberMutex sync.RWMutex @@ -167,12 +168,13 @@ type FakeLocalParticipant struct { debugInfoReturnsOnCall map[int]struct { result1 map[string]interface{} } - EnqueueSubscribeTrackStub func(livekit.TrackID, bool, func(sub types.LocalParticipant) error) bool + EnqueueSubscribeTrackStub func(livekit.TrackID, types.MediaTrack, bool, func(sub types.LocalParticipant) error) bool enqueueSubscribeTrackMutex sync.RWMutex enqueueSubscribeTrackArgsForCall []struct { arg1 livekit.TrackID - arg2 bool - arg3 func(sub types.LocalParticipant) error + arg2 types.MediaTrack + arg3 bool + arg4 func(sub types.LocalParticipant) error } enqueueSubscribeTrackReturns struct { result1 bool @@ -180,13 +182,14 @@ type FakeLocalParticipant struct { enqueueSubscribeTrackReturnsOnCall map[int]struct { result1 bool } - EnqueueUnsubscribeTrackStub func(livekit.TrackID, bool, bool, func(subscriberID livekit.ParticipantID, willBeResumed bool) error) bool + EnqueueUnsubscribeTrackStub func(livekit.TrackID, types.MediaTrack, bool, bool, func(subscriberID livekit.ParticipantID, willBeResumed bool) error) bool enqueueUnsubscribeTrackMutex sync.RWMutex enqueueUnsubscribeTrackArgsForCall []struct { arg1 livekit.TrackID - arg2 bool + arg2 types.MediaTrack arg3 bool - arg4 func(subscriberID livekit.ParticipantID, willBeResumed bool) error + arg4 bool + arg5 func(subscriberID livekit.ParticipantID, willBeResumed bool) error } enqueueUnsubscribeTrackReturns struct { result1 bool @@ -506,10 +509,11 @@ type FakeLocalParticipant struct { arg2 bool arg3 bool } - RemoveSubscribedTrackStub func(types.SubscribedTrack) + RemoveSubscribedTrackStub func(types.SubscribedTrack, types.MediaTrack) removeSubscribedTrackMutex sync.RWMutex removeSubscribedTrackArgsForCall []struct { arg1 types.SubscribedTrack + arg2 types.MediaTrack } RemoveSubscriberStub func(types.LocalParticipant, livekit.TrackID, bool) removeSubscriberMutex sync.RWMutex @@ -827,16 +831,17 @@ func (fake *FakeLocalParticipant) AddICECandidateArgsForCall(i int) (webrtc.ICEC return argsForCall.arg1, argsForCall.arg2 } -func (fake *FakeLocalParticipant) AddSubscribedTrack(arg1 types.SubscribedTrack) { +func (fake *FakeLocalParticipant) AddSubscribedTrack(arg1 types.SubscribedTrack, arg2 types.MediaTrack) { fake.addSubscribedTrackMutex.Lock() fake.addSubscribedTrackArgsForCall = append(fake.addSubscribedTrackArgsForCall, struct { arg1 types.SubscribedTrack - }{arg1}) + arg2 types.MediaTrack + }{arg1, arg2}) stub := fake.AddSubscribedTrackStub - fake.recordInvocation("AddSubscribedTrack", []interface{}{arg1}) + fake.recordInvocation("AddSubscribedTrack", []interface{}{arg1, arg2}) fake.addSubscribedTrackMutex.Unlock() if stub != nil { - fake.AddSubscribedTrackStub(arg1) + fake.AddSubscribedTrackStub(arg1, arg2) } } @@ -846,17 +851,17 @@ func (fake *FakeLocalParticipant) AddSubscribedTrackCallCount() int { return len(fake.addSubscribedTrackArgsForCall) } -func (fake *FakeLocalParticipant) AddSubscribedTrackCalls(stub func(types.SubscribedTrack)) { +func (fake *FakeLocalParticipant) AddSubscribedTrackCalls(stub func(types.SubscribedTrack, types.MediaTrack)) { fake.addSubscribedTrackMutex.Lock() defer fake.addSubscribedTrackMutex.Unlock() fake.AddSubscribedTrackStub = stub } -func (fake *FakeLocalParticipant) AddSubscribedTrackArgsForCall(i int) types.SubscribedTrack { +func (fake *FakeLocalParticipant) AddSubscribedTrackArgsForCall(i int) (types.SubscribedTrack, types.MediaTrack) { fake.addSubscribedTrackMutex.RLock() defer fake.addSubscribedTrackMutex.RUnlock() argsForCall := fake.addSubscribedTrackArgsForCall[i] - return argsForCall.arg1 + return argsForCall.arg1, argsForCall.arg2 } func (fake *FakeLocalParticipant) AddSubscriber(arg1 types.LocalParticipant, arg2 types.AddSubscriberParams) (int, error) { @@ -1562,20 +1567,21 @@ func (fake *FakeLocalParticipant) DebugInfoReturnsOnCall(i int, result1 map[stri }{result1} } -func (fake *FakeLocalParticipant) EnqueueSubscribeTrack(arg1 livekit.TrackID, arg2 bool, arg3 func(sub types.LocalParticipant) error) bool { +func (fake *FakeLocalParticipant) EnqueueSubscribeTrack(arg1 livekit.TrackID, arg2 types.MediaTrack, arg3 bool, arg4 func(sub types.LocalParticipant) error) bool { fake.enqueueSubscribeTrackMutex.Lock() ret, specificReturn := fake.enqueueSubscribeTrackReturnsOnCall[len(fake.enqueueSubscribeTrackArgsForCall)] fake.enqueueSubscribeTrackArgsForCall = append(fake.enqueueSubscribeTrackArgsForCall, struct { arg1 livekit.TrackID - arg2 bool - arg3 func(sub types.LocalParticipant) error - }{arg1, arg2, arg3}) + arg2 types.MediaTrack + arg3 bool + arg4 func(sub types.LocalParticipant) error + }{arg1, arg2, arg3, arg4}) stub := fake.EnqueueSubscribeTrackStub fakeReturns := fake.enqueueSubscribeTrackReturns - fake.recordInvocation("EnqueueSubscribeTrack", []interface{}{arg1, arg2, arg3}) + fake.recordInvocation("EnqueueSubscribeTrack", []interface{}{arg1, arg2, arg3, arg4}) fake.enqueueSubscribeTrackMutex.Unlock() if stub != nil { - return stub(arg1, arg2, arg3) + return stub(arg1, arg2, arg3, arg4) } if specificReturn { return ret.result1 @@ -1589,17 +1595,17 @@ func (fake *FakeLocalParticipant) EnqueueSubscribeTrackCallCount() int { return len(fake.enqueueSubscribeTrackArgsForCall) } -func (fake *FakeLocalParticipant) EnqueueSubscribeTrackCalls(stub func(livekit.TrackID, bool, func(sub types.LocalParticipant) error) bool) { +func (fake *FakeLocalParticipant) EnqueueSubscribeTrackCalls(stub func(livekit.TrackID, types.MediaTrack, bool, func(sub types.LocalParticipant) error) bool) { fake.enqueueSubscribeTrackMutex.Lock() defer fake.enqueueSubscribeTrackMutex.Unlock() fake.EnqueueSubscribeTrackStub = stub } -func (fake *FakeLocalParticipant) EnqueueSubscribeTrackArgsForCall(i int) (livekit.TrackID, bool, func(sub types.LocalParticipant) error) { +func (fake *FakeLocalParticipant) EnqueueSubscribeTrackArgsForCall(i int) (livekit.TrackID, types.MediaTrack, bool, func(sub types.LocalParticipant) error) { fake.enqueueSubscribeTrackMutex.RLock() defer fake.enqueueSubscribeTrackMutex.RUnlock() argsForCall := fake.enqueueSubscribeTrackArgsForCall[i] - return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 + return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4 } func (fake *FakeLocalParticipant) EnqueueSubscribeTrackReturns(result1 bool) { @@ -1625,21 +1631,22 @@ func (fake *FakeLocalParticipant) EnqueueSubscribeTrackReturnsOnCall(i int, resu }{result1} } -func (fake *FakeLocalParticipant) EnqueueUnsubscribeTrack(arg1 livekit.TrackID, arg2 bool, arg3 bool, arg4 func(subscriberID livekit.ParticipantID, willBeResumed bool) error) bool { +func (fake *FakeLocalParticipant) EnqueueUnsubscribeTrack(arg1 livekit.TrackID, arg2 types.MediaTrack, arg3 bool, arg4 bool, arg5 func(subscriberID livekit.ParticipantID, willBeResumed bool) error) bool { fake.enqueueUnsubscribeTrackMutex.Lock() ret, specificReturn := fake.enqueueUnsubscribeTrackReturnsOnCall[len(fake.enqueueUnsubscribeTrackArgsForCall)] fake.enqueueUnsubscribeTrackArgsForCall = append(fake.enqueueUnsubscribeTrackArgsForCall, struct { arg1 livekit.TrackID - arg2 bool + arg2 types.MediaTrack arg3 bool - arg4 func(subscriberID livekit.ParticipantID, willBeResumed bool) error - }{arg1, arg2, arg3, arg4}) + arg4 bool + arg5 func(subscriberID livekit.ParticipantID, willBeResumed bool) error + }{arg1, arg2, arg3, arg4, arg5}) stub := fake.EnqueueUnsubscribeTrackStub fakeReturns := fake.enqueueUnsubscribeTrackReturns - fake.recordInvocation("EnqueueUnsubscribeTrack", []interface{}{arg1, arg2, arg3, arg4}) + fake.recordInvocation("EnqueueUnsubscribeTrack", []interface{}{arg1, arg2, arg3, arg4, arg5}) fake.enqueueUnsubscribeTrackMutex.Unlock() if stub != nil { - return stub(arg1, arg2, arg3, arg4) + return stub(arg1, arg2, arg3, arg4, arg5) } if specificReturn { return ret.result1 @@ -1653,17 +1660,17 @@ func (fake *FakeLocalParticipant) EnqueueUnsubscribeTrackCallCount() int { return len(fake.enqueueUnsubscribeTrackArgsForCall) } -func (fake *FakeLocalParticipant) EnqueueUnsubscribeTrackCalls(stub func(livekit.TrackID, bool, bool, func(subscriberID livekit.ParticipantID, willBeResumed bool) error) bool) { +func (fake *FakeLocalParticipant) EnqueueUnsubscribeTrackCalls(stub func(livekit.TrackID, types.MediaTrack, bool, bool, func(subscriberID livekit.ParticipantID, willBeResumed bool) error) bool) { fake.enqueueUnsubscribeTrackMutex.Lock() defer fake.enqueueUnsubscribeTrackMutex.Unlock() fake.EnqueueUnsubscribeTrackStub = stub } -func (fake *FakeLocalParticipant) EnqueueUnsubscribeTrackArgsForCall(i int) (livekit.TrackID, bool, bool, func(subscriberID livekit.ParticipantID, willBeResumed bool) error) { +func (fake *FakeLocalParticipant) EnqueueUnsubscribeTrackArgsForCall(i int) (livekit.TrackID, types.MediaTrack, bool, bool, func(subscriberID livekit.ParticipantID, willBeResumed bool) error) { fake.enqueueUnsubscribeTrackMutex.RLock() defer fake.enqueueUnsubscribeTrackMutex.RUnlock() argsForCall := fake.enqueueUnsubscribeTrackArgsForCall[i] - return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4 + return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4, argsForCall.arg5 } func (fake *FakeLocalParticipant) EnqueueUnsubscribeTrackReturns(result1 bool) { @@ -3409,16 +3416,17 @@ func (fake *FakeLocalParticipant) RemovePublishedTrackArgsForCall(i int) (types. return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } -func (fake *FakeLocalParticipant) RemoveSubscribedTrack(arg1 types.SubscribedTrack) { +func (fake *FakeLocalParticipant) RemoveSubscribedTrack(arg1 types.SubscribedTrack, arg2 types.MediaTrack) { fake.removeSubscribedTrackMutex.Lock() fake.removeSubscribedTrackArgsForCall = append(fake.removeSubscribedTrackArgsForCall, struct { arg1 types.SubscribedTrack - }{arg1}) + arg2 types.MediaTrack + }{arg1, arg2}) stub := fake.RemoveSubscribedTrackStub - fake.recordInvocation("RemoveSubscribedTrack", []interface{}{arg1}) + fake.recordInvocation("RemoveSubscribedTrack", []interface{}{arg1, arg2}) fake.removeSubscribedTrackMutex.Unlock() if stub != nil { - fake.RemoveSubscribedTrackStub(arg1) + fake.RemoveSubscribedTrackStub(arg1, arg2) } } @@ -3428,17 +3436,17 @@ func (fake *FakeLocalParticipant) RemoveSubscribedTrackCallCount() int { return len(fake.removeSubscribedTrackArgsForCall) } -func (fake *FakeLocalParticipant) RemoveSubscribedTrackCalls(stub func(types.SubscribedTrack)) { +func (fake *FakeLocalParticipant) RemoveSubscribedTrackCalls(stub func(types.SubscribedTrack, types.MediaTrack)) { fake.removeSubscribedTrackMutex.Lock() defer fake.removeSubscribedTrackMutex.Unlock() fake.RemoveSubscribedTrackStub = stub } -func (fake *FakeLocalParticipant) RemoveSubscribedTrackArgsForCall(i int) types.SubscribedTrack { +func (fake *FakeLocalParticipant) RemoveSubscribedTrackArgsForCall(i int) (types.SubscribedTrack, types.MediaTrack) { fake.removeSubscribedTrackMutex.RLock() defer fake.removeSubscribedTrackMutex.RUnlock() argsForCall := fake.removeSubscribedTrackArgsForCall[i] - return argsForCall.arg1 + return argsForCall.arg1, argsForCall.arg2 } func (fake *FakeLocalParticipant) RemoveSubscriber(arg1 types.LocalParticipant, arg2 livekit.TrackID, arg3 bool) { diff --git a/pkg/service/roommanager.go b/pkg/service/roommanager.go index e3ec703e..f9337716 100644 --- a/pkg/service/roommanager.go +++ b/pkg/service/roommanager.go @@ -285,6 +285,11 @@ func (r *RoomManager) StartSession( if r.config.RTC.ReconnectOnPublicationError != nil { reconnectOnPublicationError = *r.config.RTC.ReconnectOnPublicationError } + // default do not force full reconnect on a subscription error + reconnectOnSubscriptionError := false + if r.config.RTC.ReconnectOnSubscriptionError != nil { + reconnectOnSubscriptionError = *r.config.RTC.ReconnectOnSubscriptionError + } participant, err = rtc.NewParticipant(rtc.ParticipantParams{ Identity: pi.Identity, Name: pi.Name, @@ -312,7 +317,8 @@ func (r *RoomManager) StartSession( } return nil }, - ReconnectOnPublicationError: reconnectOnPublicationError, + ReconnectOnPublicationError: reconnectOnPublicationError, + ReconnectOnSubscriptionError: reconnectOnSubscriptionError, }) if err != nil { return err