Avoid reconnect loop for unsupported downtrack (#1754)

* Avoid reconnect loop for unsupported downtrack

If the client subscribes to a track which codec is unsupported by the
client, sfu will trigger negotiation failed and issue a full reconnect
after received client answer. If the client try to subscribe that track
then it will got full reconnect again. That will cause a infinite
reconnect loop until the client don't subscribe that track. This PR
will unsubscribe the error track for the client and send a
SubscriptionResponse that contain the reason to indicates the track's
codec is not supported to avoid the reconnect loop.
This commit is contained in:
cnderrauber
2023-05-31 11:41:22 +08:00
committed by GitHub
parent 13d599d2d9
commit c1842cb54f
14 changed files with 226 additions and 47 deletions
+2 -2
View File
@@ -18,8 +18,8 @@ require (
github.com/jxskiss/base62 v1.1.0 github.com/jxskiss/base62 v1.1.0
github.com/livekit/mageutil v0.0.0-20230125210925-54e8a70427c1 github.com/livekit/mageutil v0.0.0-20230125210925-54e8a70427c1
github.com/livekit/mediatransportutil v0.0.0-20230523035537-27577c4e1646 github.com/livekit/mediatransportutil v0.0.0-20230523035537-27577c4e1646
github.com/livekit/protocol v1.5.8-0.20230525225706-52cca4239cf2 github.com/livekit/protocol v1.5.8-0.20230531030840-2a4d1a607ba3
github.com/livekit/psrpc v0.3.1-0.20230518234341-6f6847e10b09 github.com/livekit/psrpc v0.3.1-0.20230528083849-53d664c6d912
github.com/mackerelio/go-osstat v0.2.4 github.com/mackerelio/go-osstat v0.2.4
github.com/magefile/mage v1.15.0 github.com/magefile/mage v1.15.0
github.com/maxbrunsfeld/counterfeiter/v6 v6.6.1 github.com/maxbrunsfeld/counterfeiter/v6 v6.6.1
+4 -4
View File
@@ -122,10 +122,10 @@ github.com/livekit/mageutil v0.0.0-20230125210925-54e8a70427c1 h1:jm09419p0lqTkD
github.com/livekit/mageutil v0.0.0-20230125210925-54e8a70427c1/go.mod h1:Rs3MhFwutWhGwmY1VQsygw28z5bWcnEYmS1OG9OxjOQ= github.com/livekit/mageutil v0.0.0-20230125210925-54e8a70427c1/go.mod h1:Rs3MhFwutWhGwmY1VQsygw28z5bWcnEYmS1OG9OxjOQ=
github.com/livekit/mediatransportutil v0.0.0-20230523035537-27577c4e1646 h1:acGSGkWJdut7TUWozCDheHu4dwWFDqqRzv+SBbIY9Xo= github.com/livekit/mediatransportutil v0.0.0-20230523035537-27577c4e1646 h1:acGSGkWJdut7TUWozCDheHu4dwWFDqqRzv+SBbIY9Xo=
github.com/livekit/mediatransportutil v0.0.0-20230523035537-27577c4e1646/go.mod h1:MRc0zSOSzXuFt0X218SgabzlaKevkvCckPgBEoHYc34= github.com/livekit/mediatransportutil v0.0.0-20230523035537-27577c4e1646/go.mod h1:MRc0zSOSzXuFt0X218SgabzlaKevkvCckPgBEoHYc34=
github.com/livekit/protocol v1.5.8-0.20230525225706-52cca4239cf2 h1:cE/OQiQyre2NFQlHwwZXGV97mTTFOHess37qkWt6Ctg= github.com/livekit/protocol v1.5.8-0.20230531030840-2a4d1a607ba3 h1:UtySLPpOMgT9D/t0MOOxHShAyQQ2WsGKrUJ0XZCJlcI=
github.com/livekit/protocol v1.5.8-0.20230525225706-52cca4239cf2/go.mod h1:ZaOnsvP+JS4s7vI1UO+JVdBagvvLp/lBXDAl2hkDS0I= github.com/livekit/protocol v1.5.8-0.20230531030840-2a4d1a607ba3/go.mod h1:ZaOnsvP+JS4s7vI1UO+JVdBagvvLp/lBXDAl2hkDS0I=
github.com/livekit/psrpc v0.3.1-0.20230518234341-6f6847e10b09 h1:mb6jRcg57U0HQ4tKRsueHHKcvTqBinL6+0Aa84vTtWk= github.com/livekit/psrpc v0.3.1-0.20230528083849-53d664c6d912 h1:q6i7ptxK6yZ220eyCWx5l1ZsUMQNyuYZ5feG91sM8EI=
github.com/livekit/psrpc v0.3.1-0.20230518234341-6f6847e10b09/go.mod h1:n6JntEg+zT6Ji8InoyTpV7wusPNwGqqtxmHlkNhDN0U= github.com/livekit/psrpc v0.3.1-0.20230528083849-53d664c6d912/go.mod h1:n6JntEg+zT6Ji8InoyTpV7wusPNwGqqtxmHlkNhDN0U=
github.com/mackerelio/go-osstat v0.2.4 h1:qxGbdPkFo65PXOb/F/nhDKpF2nGmGaCFDLXoZjJTtUs= github.com/mackerelio/go-osstat v0.2.4 h1:qxGbdPkFo65PXOb/F/nhDKpF2nGmGaCFDLXoZjJTtUs=
github.com/mackerelio/go-osstat v0.2.4/go.mod h1:Zy+qzGdZs3A9cuIqmgbJvwbmLQH9dJvtio5ZjJTbdlQ= github.com/mackerelio/go-osstat v0.2.4/go.mod h1:Zy+qzGdZs3A9cuIqmgbJvwbmLQH9dJvtio5ZjJTbdlQ=
github.com/magefile/mage v1.15.0 h1:BvGheCMAsG3bWUDbZ8AyXXpCNwU9u5CB6sM+HNb9HYg= github.com/magefile/mage v1.15.0 h1:BvGheCMAsG3bWUDbZ8AyXXpCNwU9u5CB6sM+HNb9HYg=
+6 -2
View File
@@ -128,7 +128,11 @@ func (t *MediaTrackSubscriptions) AddSubscriber(sub types.LocalParticipant, wr *
// Bind callback can happen from replaceTrack, so set it up early // Bind callback can happen from replaceTrack, so set it up early
var reusingTransceiver atomic.Bool var reusingTransceiver atomic.Bool
var dtState sfu.DownTrackState var dtState sfu.DownTrackState
downTrack.OnBinding(func() { downTrack.OnBinding(func(err error) {
if err != nil {
go subTrack.Bound(err)
return
}
wr.DetermineReceiver(downTrack.Codec()) wr.DetermineReceiver(downTrack.Codec())
if reusingTransceiver.Load() { if reusingTransceiver.Load() {
downTrack.SeedState(dtState) downTrack.SeedState(dtState)
@@ -142,7 +146,7 @@ func (t *MediaTrackSubscriptions) AddSubscriber(sub types.LocalParticipant, wr *
) )
} }
go subTrack.Bound() go subTrack.Bound(nil)
subTrack.SetPublisherMuted(t.params.MediaTrack.IsMuted()) subTrack.SetPublisherMuted(t.params.MediaTrack.IsMuted())
}) })
+23 -3
View File
@@ -997,7 +997,10 @@ func (p *ParticipantImpl) onTrackSubscribed(subTrack types.SubscribedTrack) {
subTrack.DownTrack().SetActivePaddingOnMuteUpTrack() subTrack.DownTrack().SetActivePaddingOnMuteUpTrack()
} }
subTrack.AddOnBind(func() { subTrack.AddOnBind(func(err error) {
if err != nil {
return
}
if p.TransportManager.HasSubscriberEverConnected() { if p.TransportManager.HasSubscriberEverConnected() {
subTrack.DownTrack().SetConnected() subTrack.DownTrack().SetConnected()
} }
@@ -2083,8 +2086,25 @@ func (p *ParticipantImpl) onPublicationError(trackID livekit.TrackID) {
} }
} }
func (p *ParticipantImpl) onSubscriptionError(trackID livekit.TrackID) { func (p *ParticipantImpl) onSubscriptionError(trackID livekit.TrackID, fatal bool, err error) {
if p.params.ReconnectOnSubscriptionError { signalErr := livekit.SubscriptionError_SE_UNKOWN
switch {
case errors.Is(err, webrtc.ErrUnsupportedCodec):
signalErr = livekit.SubscriptionError_SE_CODEC_UNSUPPORTED
case errors.Is(err, ErrTrackNotFound):
signalErr = livekit.SubscriptionError_SE_TRACK_NOTFOUND
}
_ = p.writeMessage(&livekit.SignalResponse{
Message: &livekit.SignalResponse_SubscriptionResponse{
SubscriptionResponse: &livekit.SubscriptionResponse{
TrackSid: string(trackID),
Err: signalErr,
},
},
})
if p.params.ReconnectOnSubscriptionError && fatal {
p.params.Logger.Infow("issuing full reconnect on subscription error", "trackID", trackID) p.params.Logger.Infow("issuing full reconnect on subscription error", "trackID", trackID)
p.IssueFullReconnect(types.ParticipantCloseReasonPublicationError) p.IssueFullReconnect(types.ParticipantCloseReasonPublicationError)
} }
+8 -6
View File
@@ -40,7 +40,7 @@ type SubscribedTrack struct {
needsNegotiation atomic.Bool needsNegotiation atomic.Bool
bindLock sync.Mutex bindLock sync.Mutex
onBindCallbacks []func() onBindCallbacks []func(error)
onClose atomic.Value // func(bool) onClose atomic.Value // func(bool)
bound atomic.Bool bound atomic.Bool
@@ -61,7 +61,7 @@ func NewSubscribedTrack(params SubscribedTrackParams) *SubscribedTrack {
return s return s
} }
func (t *SubscribedTrack) AddOnBind(f func()) { func (t *SubscribedTrack) AddOnBind(f func(error)) {
t.bindLock.Lock() t.bindLock.Lock()
bound := t.bound.Load() bound := t.bound.Load()
if !bound { if !bound {
@@ -71,19 +71,21 @@ func (t *SubscribedTrack) AddOnBind(f func()) {
if bound { if bound {
// fire immediately, do not need to persist since bind is a one time event // fire immediately, do not need to persist since bind is a one time event
go f() go f(nil)
} }
} }
// for DownTrack callback to notify us that it's bound // for DownTrack callback to notify us that it's bound
func (t *SubscribedTrack) Bound() { func (t *SubscribedTrack) Bound(err error) {
t.bindLock.Lock() t.bindLock.Lock()
if err == nil {
t.bound.Store(true) t.bound.Store(true)
}
callbacks := t.onBindCallbacks callbacks := t.onBindCallbacks
t.onBindCallbacks = nil t.onBindCallbacks = nil
t.bindLock.Unlock() t.bindLock.Unlock()
if t.MediaTrack().Kind() == livekit.TrackType_VIDEO { if err == nil && t.MediaTrack().Kind() == livekit.TrackType_VIDEO {
// When AdaptiveStream is enabled, default the subscriber to LOW quality stream // When AdaptiveStream is enabled, default the subscriber to LOW quality stream
// we would want LOW instead of OFF for a couple of reasons // we would want LOW instead of OFF for a couple of reasons
// 1. when a subscriber unsubscribes from a track, we would forget their previously defined settings // 1. when a subscriber unsubscribes from a track, we would forget their previously defined settings
@@ -107,7 +109,7 @@ func (t *SubscribedTrack) Bound() {
} }
for _, cb := range callbacks { for _, cb := range callbacks {
go cb() go cb(err)
} }
} }
+12 -4
View File
@@ -52,7 +52,7 @@ type SubscriptionManagerParams struct {
TrackResolver types.MediaTrackResolver TrackResolver types.MediaTrackResolver
OnTrackSubscribed func(subTrack types.SubscribedTrack) OnTrackSubscribed func(subTrack types.SubscribedTrack)
OnTrackUnsubscribed func(subTrack types.SubscribedTrack) OnTrackUnsubscribed func(subTrack types.SubscribedTrack)
OnSubscriptionError func(trackID livekit.TrackID) OnSubscriptionError func(trackID livekit.TrackID, fatal bool, err error)
Telemetry telemetry.TelemetryService Telemetry telemetry.TelemetryService
SubscriptionLimitVideo, SubscriptionLimitAudio int32 SubscriptionLimitVideo, SubscriptionLimitAudio int32
@@ -309,6 +309,7 @@ func (m *SubscriptionManager) reconcileSubscription(s *trackSubscription) {
s.logger.Infow("unsubscribing from track after notFoundTimeout", "error", err) s.logger.Infow("unsubscribing from track after notFoundTimeout", "error", err)
s.setDesired(false) s.setDesired(false)
m.queueReconcile(s.trackID) m.queueReconcile(s.trackID)
m.params.OnSubscriptionError(s.trackID, false, err)
} }
default: default:
// all other errors // all other errors
@@ -317,7 +318,7 @@ func (m *SubscriptionManager) reconcileSubscription(s *trackSubscription) {
"attempt", numAttempts, "attempt", numAttempts,
) )
s.maybeRecordError(m.params.Telemetry, m.params.Participant.ID(), err, false) s.maybeRecordError(m.params.Telemetry, m.params.Participant.ID(), err, false)
m.params.OnSubscriptionError(s.trackID) m.params.OnSubscriptionError(s.trackID, true, err)
} else { } else {
s.logger.Debugw("failed to subscribe, retrying", s.logger.Debugw("failed to subscribe, retrying",
"error", err, "error", err,
@@ -353,7 +354,7 @@ func (m *SubscriptionManager) reconcileSubscription(s *trackSubscription) {
if s.durationSinceStart() > subscriptionTimeout { if s.durationSinceStart() > subscriptionTimeout {
s.logger.Errorw("track not bound after timeout", nil) s.logger.Errorw("track not bound after timeout", nil)
s.maybeRecordError(m.params.Telemetry, m.params.Participant.ID(), ErrTrackNotBound, false) s.maybeRecordError(m.params.Telemetry, m.params.Participant.ID(), ErrTrackNotBound, false)
m.params.OnSubscriptionError(s.trackID) m.params.OnSubscriptionError(s.trackID, true, ErrTrackNotBound)
} }
} }
} }
@@ -470,7 +471,14 @@ func (m *SubscriptionManager) subscribe(s *trackSubscription) error {
subTrack.OnClose(func(willBeResumed bool) { subTrack.OnClose(func(willBeResumed bool) {
m.handleSubscribedTrackClose(s, willBeResumed) m.handleSubscribedTrackClose(s, willBeResumed)
}) })
subTrack.AddOnBind(func() { subTrack.AddOnBind(func(err error) {
if err != nil {
s.logger.Infow("failed to bind track", "err", err)
s.maybeRecordError(m.params.Telemetry, m.params.Participant.ID(), err, true)
m.UnsubscribeFromTrack(s.trackID)
m.params.OnSubscriptionError(s.trackID, false, err)
return
}
s.setBound() s.setBound()
s.maybeRecordSuccess(m.params.Telemetry, m.params.Participant.ID()) s.maybeRecordSuccess(m.params.Telemetry, m.params.Participant.ID())
}) })
+6 -6
View File
@@ -54,7 +54,7 @@ func TestSubscribe(t *testing.T) {
sm.params.OnTrackSubscribed = func(subTrack types.SubscribedTrack) { sm.params.OnTrackSubscribed = func(subTrack types.SubscribedTrack) {
subCount.Add(1) subCount.Add(1)
} }
sm.params.OnSubscriptionError = func(trackID livekit.TrackID) { sm.params.OnSubscriptionError = func(trackID livekit.TrackID, fatal bool, err error) {
failed.Store(true) failed.Store(true)
} }
numParticipantSubscribed := atomic.Int32{} numParticipantSubscribed := atomic.Int32{}
@@ -123,7 +123,7 @@ func TestSubscribe(t *testing.T) {
resolver := newTestResolver(false, true, "pub", "pubID") resolver := newTestResolver(false, true, "pub", "pubID")
sm.params.TrackResolver = resolver.Resolve sm.params.TrackResolver = resolver.Resolve
failed := atomic.Bool{} failed := atomic.Bool{}
sm.params.OnSubscriptionError = func(trackID livekit.TrackID) { sm.params.OnSubscriptionError = func(trackID livekit.TrackID, fatal bool, err error) {
failed.Store(true) failed.Store(true)
} }
@@ -164,7 +164,7 @@ func TestSubscribe(t *testing.T) {
resolver := newTestResolver(true, true, "pub", "pubID") resolver := newTestResolver(true, true, "pub", "pubID")
sm.params.TrackResolver = resolver.Resolve sm.params.TrackResolver = resolver.Resolve
failed := atomic.Bool{} failed := atomic.Bool{}
sm.params.OnSubscriptionError = func(trackID livekit.TrackID) { sm.params.OnSubscriptionError = func(trackID livekit.TrackID, fatal bool, err error) {
failed.Store(true) failed.Store(true)
} }
@@ -360,7 +360,7 @@ func TestSubscriptionLimits(t *testing.T) {
sm.params.OnTrackSubscribed = func(subTrack types.SubscribedTrack) { sm.params.OnTrackSubscribed = func(subTrack types.SubscribedTrack) {
subCount.Add(1) subCount.Add(1)
} }
sm.params.OnSubscriptionError = func(trackID livekit.TrackID) { sm.params.OnSubscriptionError = func(trackID livekit.TrackID, fatal bool, err error) {
failed.Store(true) failed.Store(true)
} }
numParticipantSubscribed := atomic.Int32{} numParticipantSubscribed := atomic.Int32{}
@@ -463,7 +463,7 @@ func newTestSubscriptionManagerWithParams(t *testing.T, params testSubscriptionP
Logger: logger.GetLogger(), Logger: logger.GetLogger(),
OnTrackSubscribed: func(subTrack types.SubscribedTrack) {}, OnTrackSubscribed: func(subTrack types.SubscribedTrack) {},
OnTrackUnsubscribed: func(subTrack types.SubscribedTrack) {}, OnTrackUnsubscribed: func(subTrack types.SubscribedTrack) {},
OnSubscriptionError: func(trackID livekit.TrackID) {}, OnSubscriptionError: func(trackID livekit.TrackID, fatal bool, err error) {},
TrackResolver: func(identity livekit.ParticipantIdentity, trackID livekit.TrackID) types.MediaResolverResult { TrackResolver: func(identity livekit.ParticipantIdentity, trackID livekit.TrackID) types.MediaResolverResult {
return types.MediaResolverResult{} return types.MediaResolverResult{}
}, },
@@ -526,7 +526,7 @@ func setTestSubscribedTrackBound(t *testing.T, st types.SubscribedTrack) {
require.True(t, ok) require.True(t, ok)
for i := 0; i < fst.AddOnBindCallCount(); i++ { for i := 0; i < fst.AddOnBindCallCount(); i++ {
fst.AddOnBindArgsForCall(i)() fst.AddOnBindArgsForCall(i)(nil)
} }
} }
+6
View File
@@ -1865,8 +1865,14 @@ func (t *PCTransport) handleRemoteOfferReceived(sd *webrtc.SessionDescription) e
func (t *PCTransport) handleRemoteAnswerReceived(sd *webrtc.SessionDescription) error { func (t *PCTransport) handleRemoteAnswerReceived(sd *webrtc.SessionDescription) error {
if err := t.setRemoteDescription(*sd); err != nil { if err := t.setRemoteDescription(*sd); err != nil {
// Pion will call RTPSender.Send method for each new added Downtrack, and return error if the DownTrack.Bind
// returns error. In case of Downtrack.Bind returns ErrUnsupportedCodec, the signal state will be stable as negotiation is aleady compelted
// before startRTPSenders, and the peerconnection state can be recovered by next negotiation which will be triggered
// by the SubscriptionManager unsubscribe the failure DownTrack. So don't treat this error as negotiation failure.
if !errors.Is(err, webrtc.ErrUnsupportedCodec) {
return err return err
} }
}
t.clearSignalStateCheckTimer() t.clearSignalStateCheckTimer()
+1 -1
View File
@@ -427,7 +427,7 @@ type LocalMediaTrack interface {
//counterfeiter:generate . SubscribedTrack //counterfeiter:generate . SubscribedTrack
type SubscribedTrack interface { type SubscribedTrack interface {
AddOnBind(f func()) AddOnBind(f func(error))
IsBound() bool IsBound() bool
Close(willBeResumed bool) Close(willBeResumed bool)
OnClose(f func(willBeResumed bool)) OnClose(f func(willBeResumed bool))
@@ -11,10 +11,10 @@ import (
) )
type FakeSubscribedTrack struct { type FakeSubscribedTrack struct {
AddOnBindStub func(func()) AddOnBindStub func(func(error))
addOnBindMutex sync.RWMutex addOnBindMutex sync.RWMutex
addOnBindArgsForCall []struct { addOnBindArgsForCall []struct {
arg1 func() arg1 func(error)
} }
CloseStub func(bool) CloseStub func(bool)
closeMutex sync.RWMutex closeMutex sync.RWMutex
@@ -174,10 +174,10 @@ type FakeSubscribedTrack struct {
invocationsMutex sync.RWMutex invocationsMutex sync.RWMutex
} }
func (fake *FakeSubscribedTrack) AddOnBind(arg1 func()) { func (fake *FakeSubscribedTrack) AddOnBind(arg1 func(error)) {
fake.addOnBindMutex.Lock() fake.addOnBindMutex.Lock()
fake.addOnBindArgsForCall = append(fake.addOnBindArgsForCall, struct { fake.addOnBindArgsForCall = append(fake.addOnBindArgsForCall, struct {
arg1 func() arg1 func(error)
}{arg1}) }{arg1})
stub := fake.AddOnBindStub stub := fake.AddOnBindStub
fake.recordInvocation("AddOnBind", []interface{}{arg1}) fake.recordInvocation("AddOnBind", []interface{}{arg1})
@@ -193,13 +193,13 @@ func (fake *FakeSubscribedTrack) AddOnBindCallCount() int {
return len(fake.addOnBindArgsForCall) return len(fake.addOnBindArgsForCall)
} }
func (fake *FakeSubscribedTrack) AddOnBindCalls(stub func(func())) { func (fake *FakeSubscribedTrack) AddOnBindCalls(stub func(func(error))) {
fake.addOnBindMutex.Lock() fake.addOnBindMutex.Lock()
defer fake.addOnBindMutex.Unlock() defer fake.addOnBindMutex.Unlock()
fake.AddOnBindStub = stub fake.AddOnBindStub = stub
} }
func (fake *FakeSubscribedTrack) AddOnBindArgsForCall(i int) func() { func (fake *FakeSubscribedTrack) AddOnBindArgsForCall(i int) func(error) {
fake.addOnBindMutex.RLock() fake.addOnBindMutex.RLock()
defer fake.addOnBindMutex.RUnlock() defer fake.addOnBindMutex.RUnlock()
argsForCall := fake.addOnBindArgsForCall[i] argsForCall := fake.addOnBindArgsForCall[i]
+10 -4
View File
@@ -199,7 +199,7 @@ type DownTrack struct {
writeStream webrtc.TrackLocalWriter writeStream webrtc.TrackLocalWriter
rtcpReader *buffer.RTCPReader rtcpReader *buffer.RTCPReader
onCloseHandler func(willBeResumed bool) onCloseHandler func(willBeResumed bool)
onBinding func() onBinding func(error)
listenerLock sync.RWMutex listenerLock sync.RWMutex
receiverReportListeners []ReceiverReportListener receiverReportListeners []ReceiverReportListener
@@ -336,8 +336,14 @@ func (d *DownTrack) Bind(t webrtc.TrackLocalContext) (webrtc.RTPCodecParameters,
} }
if codec.MimeType == "" { if codec.MimeType == "" {
err := webrtc.ErrUnsupportedCodec
onBinding := d.onBinding
d.bindLock.Unlock() d.bindLock.Unlock()
return webrtc.RTPCodecParameters{}, webrtc.ErrUnsupportedCodec d.logger.Infow("bind error for unsupported codec", "codecs", d.upstreamCodecs, "remoteParameters", t.CodecParameters())
if onBinding != nil {
onBinding(err)
}
return webrtc.RTPCodecParameters{}, err
} }
// if a downtrack is closed before bind, it already unsubscribed from client, don't do subsequent operation and return here. // if a downtrack is closed before bind, it already unsubscribed from client, don't do subsequent operation and return here.
@@ -367,7 +373,7 @@ func (d *DownTrack) Bind(t webrtc.TrackLocalContext) (webrtc.RTPCodecParameters,
d.codec = codec.RTPCodecCapability d.codec = codec.RTPCodecCapability
if d.onBinding != nil { if d.onBinding != nil {
d.onBinding() d.onBinding(nil)
} }
d.bound.Store(true) d.bound.Store(true)
d.bindLock.Unlock() d.bindLock.Unlock()
@@ -990,7 +996,7 @@ func (d *DownTrack) OnCloseHandler(fn func(willBeResumed bool)) {
d.onCloseHandler = fn d.onCloseHandler = fn
} }
func (d *DownTrack) OnBinding(fn func()) { func (d *DownTrack) OnBinding(fn func(error)) {
d.onBinding = fn d.onBinding = fn
} }
+27 -2
View File
@@ -8,6 +8,7 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"path/filepath" "path/filepath"
"strings"
"sync" "sync"
"time" "time"
@@ -61,6 +62,8 @@ type RTCClient struct {
// map of livekit.ParticipantID and last packet // map of livekit.ParticipantID and last packet
lastPackets map[livekit.ParticipantID]*rtp.Packet lastPackets map[livekit.ParticipantID]*rtp.Packet
bytesReceived map[livekit.ParticipantID]uint64 bytesReceived map[livekit.ParticipantID]uint64
subscriptionResponse atomic.Pointer[livekit.SubscriptionResponse]
} }
var ( var (
@@ -83,6 +86,7 @@ type Options struct {
AutoSubscribe bool AutoSubscribe bool
Publish string Publish string
ClientInfo *livekit.ClientInfo ClientInfo *livekit.ClientInfo
DisabledCodecs []webrtc.RTPCodecCapability
} }
func NewWebSocketConn(host, token string, opts *Options) (*websocket.Conn, error) { func NewWebSocketConn(host, token string, opts *Options) (*websocket.Conn, error) {
@@ -116,7 +120,7 @@ func SetAuthorizationToken(header http.Header, token string) {
header.Set("Authorization", "Bearer "+token) header.Set("Authorization", "Bearer "+token)
} }
func NewRTCClient(conn *websocket.Conn) (*RTCClient, error) { func NewRTCClient(conn *websocket.Conn, opts *Options) (*RTCClient, error) {
var err error var err error
c := &RTCClient{ c := &RTCClient{
@@ -139,7 +143,8 @@ func NewRTCClient(conn *websocket.Conn) (*RTCClient, error) {
} }
conf.SettingEngine.SetLite(false) conf.SettingEngine.SetLite(false)
conf.SettingEngine.SetAnsweringDTLSRole(webrtc.DTLSRoleClient) conf.SettingEngine.SetAnsweringDTLSRole(webrtc.DTLSRoleClient)
codecs := []*livekit.Codec{ var codecs []*livekit.Codec
for _, codec := range []*livekit.Codec{
{ {
Mime: "audio/opus", Mime: "audio/opus",
}, },
@@ -149,7 +154,21 @@ func NewRTCClient(conn *websocket.Conn) (*RTCClient, error) {
{ {
Mime: "video/h264", Mime: "video/h264",
}, },
} {
var disabled bool
if opts != nil {
for _, dc := range opts.DisabledCodecs {
if strings.EqualFold(dc.MimeType, codec.Mime) && (dc.SDPFmtpLine == "" || dc.SDPFmtpLine == codec.FmtpLine) {
disabled = true
break
} }
}
}
if !disabled {
codecs = append(codecs, codec)
}
}
// //
// The signal targets are from point of view of server. // The signal targets are from point of view of server.
// From client side, they are flipped, // From client side, they are flipped,
@@ -348,6 +367,8 @@ func (c *RTCClient) Run() error {
c.lock.Unlock() c.lock.Unlock()
case *livekit.SignalResponse_Pong: case *livekit.SignalResponse_Pong:
c.pongReceivedAt.Store(msg.Pong) c.pongReceivedAt.Store(msg.Pong)
case *livekit.SignalResponse_SubscriptionResponse:
c.subscriptionResponse.Store(msg.SubscriptionResponse)
} }
} }
} }
@@ -452,6 +473,10 @@ func (c *RTCClient) PongReceivedAt() int64 {
return c.pongReceivedAt.Load() return c.pongReceivedAt.Load()
} }
func (c *RTCClient) GetSubscriptionResponseAndClear() *livekit.SubscriptionResponse {
return c.subscriptionResponse.Swap(nil)
}
func (c *RTCClient) SendPing() error { func (c *RTCClient) SendPing() error {
return c.SendRequest(&livekit.SignalRequest{ return c.SendRequest(&livekit.SignalRequest{
Message: &livekit.SignalRequest_Ping{ Message: &livekit.SignalRequest_Ping{
+2 -2
View File
@@ -196,7 +196,7 @@ func createRTCClient(name string, port int, opts *testclient.Options) *testclien
panic(err) panic(err)
} }
c, err := testclient.NewRTCClient(ws) c, err := testclient.NewRTCClient(ws, opts)
if err != nil { if err != nil {
panic(err) panic(err)
} }
@@ -213,7 +213,7 @@ func createRTCClientWithToken(token string, port int, opts *testclient.Options)
panic(err) panic(err)
} }
c, err := testclient.NewRTCClient(ws) c, err := testclient.NewRTCClient(ws, opts)
if err != nil { if err != nil {
panic(err) panic(err)
} }
+108
View File
@@ -543,3 +543,111 @@ func TestDeviceCodecOverride(t *testing.T) {
} }
require.True(t, hasSeenVP8, "should have seen VP8 codec in SDP") require.True(t, hasSeenVP8, "should have seen VP8 codec in SDP")
} }
func TestSubscribeToCodecUnsupported(t *testing.T) {
if testing.Short() {
t.SkipNow()
return
}
_, finish := setupSingleNodeTest("TestSubscribeToCodecUnsupported")
defer finish()
c1 := createRTCClient("c1", defaultServerPort, nil)
// create a client that doesn't support H264
c2 := createRTCClient("c2", defaultServerPort, &testclient.Options{
AutoSubscribe: true,
DisabledCodecs: []webrtc.RTPCodecCapability{
{MimeType: "video/H264"},
},
})
waitUntilConnected(t, c1, c2)
// publish a vp8 video track and ensure c2 receives it ok
t1, err := c1.AddStaticTrack("audio/opus", "audio", "webcam")
require.NoError(t, err)
defer t1.Stop()
t2, err := c1.AddStaticTrack("video/vp8", "video", "webcam")
require.NoError(t, err)
defer t2.Stop()
testutils.WithTimeout(t, func() string {
if len(c2.SubscribedTracks()) == 0 {
return "c2 was not subscribed to anything"
}
// should have received two tracks
if len(c2.SubscribedTracks()[c1.ID()]) != 2 {
return "c2 was not subscribed to tracks from c1"
}
tracks := c2.SubscribedTracks()[c1.ID()]
for _, t := range tracks {
if strings.EqualFold(t.Codec().MimeType, "video/vp8") {
return ""
}
}
return "did not receive track with vp8"
})
require.Nil(t, c2.GetSubscriptionResponseAndClear())
// publish a h264 track and ensure c2 got subscription error
t3, err := c1.AddStaticTrackWithCodec(webrtc.RTPCodecCapability{
MimeType: "video/h264",
ClockRate: 90000,
SDPFmtpLine: "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",
}, "videoscreen", "screen")
defer t3.Stop()
require.NoError(t, err)
var h264TrackID string
require.Eventually(t, func() bool {
remoteC1 := c2.GetRemoteParticipant(c1.ID())
require.NotNil(t, remoteC1)
for _, track := range remoteC1.Tracks {
if strings.EqualFold(track.MimeType, "video/h264") {
h264TrackID = track.Sid
return true
}
}
return false
}, time.Second, 10*time.Millisecond, "did not receive track info with h264")
require.Eventually(t, func() bool {
sr := c2.GetSubscriptionResponseAndClear()
if sr == nil {
return false
}
require.Equal(t, h264TrackID, sr.TrackSid)
require.Equal(t, livekit.SubscriptionError_SE_CODEC_UNSUPPORTED, sr.Err)
return true
}, time.Second, 10*time.Millisecond, "did not receive subscription response")
// publish another vp8 track again, ensure the transport recovered by sfu and c2 can receive it
t4, err := c1.AddStaticTrack("video/vp8", "video2", "webcam2")
require.NoError(t, err)
defer t4.Stop()
testutils.WithTimeout(t, func() string {
if len(c2.SubscribedTracks()) == 0 {
return "c2 was not subscribed to anything"
}
// should have received two tracks
if len(c2.SubscribedTracks()[c1.ID()]) != 3 {
return "c2 was not subscribed to tracks from c1"
}
var vp8Count int
tracks := c2.SubscribedTracks()[c1.ID()]
for _, t := range tracks {
if strings.EqualFold(t.Codec().MimeType, "video/vp8") {
vp8Count++
}
}
if vp8Count == 2 {
return ""
}
return "did not 2 receive track with vp8"
})
require.Nil(t, c2.GetSubscriptionResponseAndClear())
}