From f17ed9b925b923300599902356df23f2b3444a06 Mon Sep 17 00:00:00 2001 From: cnderrauber Date: Mon, 4 Jul 2022 17:11:09 +0800 Subject: [PATCH] refine negotiation process (#807) * refine negotiation process * not restart during ice gathering * fix test case --- pkg/rtc/participant.go | 15 ++++ pkg/rtc/room.go | 4 +- pkg/rtc/transport.go | 69 +++++++++++++++--- pkg/rtc/transport_test.go | 135 +++++++++++++++++++++++++++++++++++- pkg/rtc/types/interfaces.go | 3 + 5 files changed, 213 insertions(+), 13 deletions(-) diff --git a/pkg/rtc/participant.go b/pkg/rtc/participant.go index 9f0a782e..3b3eeb66 100644 --- a/pkg/rtc/participant.go +++ b/pkg/rtc/participant.go @@ -225,6 +225,8 @@ func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) { return nil, err } + p.subscriber.OnNegotiationFailed(p.handleNegotiationFailed) + p.publisher.pc.OnICECandidate(func(c *webrtc.ICECandidate) { if c == nil || p.State() == livekit.ParticipantInfo_DISCONNECTED { return @@ -2055,3 +2057,16 @@ func (p *ParticipantImpl) GetCachedDownTrack(trackID livekit.TrackID) (*webrtc.R return nil, sfu.ForwarderState{} } + +func (p *ParticipantImpl) handleNegotiationFailed() { + p.params.Logger.Infow("negotiation failed, notify client do full reconnect") + _ = p.writeMessage(&livekit.SignalResponse{ + Message: &livekit.SignalResponse_Leave{ + Leave: &livekit.LeaveRequest{ + CanReconnect: true, + Reason: types.ParticipantCloseReasonNegotiateFailed.ToDisconnectReason(), + }, + }, + }) + p.closeSignalConnection() +} diff --git a/pkg/rtc/room.go b/pkg/rtc/room.go index 3dc10ce6..4407fa7a 100644 --- a/pkg/rtc/room.go +++ b/pkg/rtc/room.go @@ -964,7 +964,9 @@ func (r *Room) connectionQualityWorker() { continue } - nowConnectionInfos[p.ID()] = p.GetConnectionQuality() + if q := p.GetConnectionQuality(); q != nil { + nowConnectionInfos[p.ID()] = q + } } // send an update if there is a change diff --git a/pkg/rtc/transport.go b/pkg/rtc/transport.go index 7a508e37..102858e3 100644 --- a/pkg/rtc/transport.go +++ b/pkg/rtc/transport.go @@ -14,6 +14,7 @@ import ( "github.com/pion/interceptor/pkg/twcc" "github.com/pion/sdp/v3" "github.com/pion/webrtc/v3" + "go.uber.org/atomic" "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" @@ -28,6 +29,7 @@ import ( const ( negotiationFrequency = 150 * time.Millisecond + negotiationFailedTimout = 15 * time.Second dtlsRetransmissionInterval = 100 * time.Millisecond iceDisconnectedTimeout = 10 * time.Second // compatible for ice-lite with firefox client @@ -35,6 +37,10 @@ const ( iceKeepaliveInterval = 2 * time.Second // pion's default ) +var ( + ErrIceRestartWithoutLocalSDP = errors.New("ICE restart without local SDP settled") +) + const ( negotiationStateNone = iota // waiting for client answer @@ -54,12 +60,16 @@ type PCTransport struct { pc *webrtc.PeerConnection me *webrtc.MediaEngine - lock sync.Mutex + lock sync.RWMutex pendingCandidates []webrtc.ICECandidateInit debouncedNegotiate func(func()) onOffer func(offer webrtc.SessionDescription) restartAfterGathering bool + restartAtNextOffer bool negotiationState int + negotiateCounter atomic.Int32 + signalStateCheckTimer *time.Timer + onNegotiationFailed func() // stream allocator for subscriber PC streamAllocator *sfu.StreamAllocator @@ -276,6 +286,10 @@ func (t *PCTransport) SetRemoteDescription(sd webrtc.SessionDescription) error { lastState := t.negotiationState t.negotiationState = negotiationStateNone + if t.signalStateCheckTimer != nil { + t.signalStateCheckTimer.Stop() + } + for _, c := range t.pendingCandidates { if err := t.pc.AddICECandidate(c); err != nil { return err @@ -298,6 +312,10 @@ func (t *PCTransport) OnOffer(f func(sd webrtc.SessionDescription)) { t.onOffer = f } +func (t *PCTransport) OnNegotiationFailed(f func()) { + t.onNegotiationFailed = f +} + func (t *PCTransport) Negotiate(force bool) { if force { t.debouncedNegotiate(func() { @@ -330,7 +348,7 @@ func (t *PCTransport) createAndSendOffer(options *webrtc.OfferOptions) error { return nil } - iceRestart := options != nil && options.ICERestart + iceRestart := (options != nil && options.ICERestart) || t.restartAtNextOffer // if restart is requested, and we are not ready, then continue afterwards if iceRestart { @@ -345,14 +363,17 @@ func (t *PCTransport) createAndSendOffer(options *webrtc.OfferOptions) error { if iceRestart && t.negotiationState != negotiationStateNone { currentSD := t.pc.CurrentRemoteDescription() if currentSD == nil { - // never received an answer from client, create a new peer connection - t.params.Logger.Infow("no previous answer from client on ICE restart, creating a new PC") - t.pc.Close() - if err := t.createPeerConnection(); err != nil { - t.params.Logger.Errorw("could not create new PC on ICE restart", err) - return err + // restart without current remote description, sent current local description again to try recover + offer := t.pc.LocalDescription() + if offer == nil { + // it should not happend, check for safety + t.params.Logger.Infow("ice restart without local offer") + return ErrIceRestartWithoutLocalSDP } else { - options.ICERestart = false + t.negotiationState = negotiationRetry + t.restartAtNextOffer = true + go t.onOffer(*offer) + return nil } } else { // recover by re-applying the last answer @@ -374,12 +395,22 @@ func (t *PCTransport) createAndSendOffer(options *webrtc.OfferOptions) error { } } - if t.previousAnswer != nil { - t.previousAnswer = nil + ensureICERestart := func(options *webrtc.OfferOptions) *webrtc.OfferOptions { if options == nil { options = &webrtc.OfferOptions{} } options.ICERestart = true + return options + } + + if t.previousAnswer != nil { + t.previousAnswer = nil + options = ensureICERestart(options) + } + + if t.restartAtNextOffer { + t.restartAtNextOffer = false + options = ensureICERestart(options) } offer, err := t.pc.CreateOffer(options) @@ -400,6 +431,22 @@ func (t *PCTransport) createAndSendOffer(options *webrtc.OfferOptions) error { t.negotiationState = negotiationStateClient t.restartAfterGathering = false + negotiateVersion := t.negotiateCounter.Inc() + if t.signalStateCheckTimer != nil { + t.signalStateCheckTimer.Stop() + } + t.signalStateCheckTimer = time.AfterFunc(negotiationFailedTimout, func() { + t.lock.RLock() + failed := t.negotiationState != negotiationStateNone + t.lock.RUnlock() + if t.negotiateCounter.Load() == negotiateVersion && failed { + t.params.Logger.Infow("negotiation timeout") + if t.onNegotiationFailed != nil { + t.onNegotiationFailed() + } + } + }) + go t.onOffer(offer) return nil } diff --git a/pkg/rtc/transport_test.go b/pkg/rtc/transport_test.go index 9b45ef9b..b1626156 100644 --- a/pkg/rtc/transport_test.go +++ b/pkg/rtc/transport_test.go @@ -1,12 +1,12 @@ package rtc import ( + "sync/atomic" "testing" "time" "github.com/pion/webrtc/v3" "github.com/stretchr/testify/require" - "go.uber.org/atomic" "github.com/livekit/protocol/livekit" @@ -136,6 +136,139 @@ func TestNegotiationTiming(t *testing.T) { require.False(t, offer2 == actualOffer) } +func TestFirstOfferMissedDuringICERestart(t *testing.T) { + params := TransportParams{ + ParticipantID: "id", + ParticipantIdentity: "identity", + Target: livekit.SignalTarget_PUBLISHER, + Config: &WebRTCConfig{}, + } + transportA, err := NewPCTransport(params) + require.NoError(t, err) + _, err = transportA.pc.CreateDataChannel("test", nil) + require.NoError(t, err) + transportB, err := NewPCTransport(params) + require.NoError(t, err) + + //first offer missed + transportA.OnOffer(func(sd webrtc.SessionDescription) {}) + require.NoError(t, transportA.CreateAndSendOffer(nil)) + + // exchange ICE + handleICEExchange(t, transportA, transportB) + + // set offer/answer with restart ICE, will negotiate twice, + // first one is recover from missed offer + // second one is restartICE + handleOffer := handleOfferFunc(t, transportA, transportB) + var offerCount int32 + transportA.OnOffer(func(sd webrtc.SessionDescription) { + atomic.AddInt32(&offerCount, 1) + // the second offer is a ice restart offer, so we wait transportB complete the ice gathering + if transportB.pc.ICEGatheringState() == webrtc.ICEGatheringStateGathering { + require.Eventually(t, func() bool { + return transportB.pc.ICEGatheringState() == webrtc.ICEGatheringStateComplete + }, 10*time.Second, time.Millisecond*10) + } + handleOffer(sd) + }) + + // first establish connection + require.NoError(t, transportA.CreateAndSendOffer(&webrtc.OfferOptions{ + ICERestart: true, + })) + + // ensure we are connected + require.Eventually(t, func() bool { + return transportA.pc.ICEConnectionState() == webrtc.ICEConnectionStateConnected && + transportB.pc.ICEConnectionState() == webrtc.ICEConnectionStateConnected && + atomic.LoadInt32(&offerCount) == 2 + }, testutils.ConnectTimeout, 10*time.Millisecond, "transport did not connect") + transportA.Close() + transportB.Close() +} + +func TestFirstAnwserMissedDuringICERestart(t *testing.T) { + params := TransportParams{ + ParticipantID: "id", + ParticipantIdentity: "identity", + Target: livekit.SignalTarget_PUBLISHER, + Config: &WebRTCConfig{}, + } + transportA, err := NewPCTransport(params) + require.NoError(t, err) + _, err = transportA.pc.CreateDataChannel("test", nil) + require.NoError(t, err) + transportB, err := NewPCTransport(params) + require.NoError(t, err) + + //first anwser missed + transportA.OnOffer(func(sd webrtc.SessionDescription) { + require.NoError(t, transportB.SetRemoteDescription(sd)) + answer, err := transportB.pc.CreateAnswer(nil) + require.NoError(t, err) + require.NoError(t, transportB.pc.SetLocalDescription(answer)) + }) + // exchange ICE + handleICEExchange(t, transportA, transportB) + + require.NoError(t, transportA.CreateAndSendOffer(nil)) + require.Eventually(t, func() bool { + return transportB.pc.SignalingState() == webrtc.SignalingStateStable + }, time.Second, 10*time.Millisecond) + + // set offer/answer with restart ICE, will negotiate twice, + // first one is recover from missed offer + // second one is restartICE + handleOffer := handleOfferFunc(t, transportA, transportB) + var offerCount int32 + transportA.OnOffer(func(sd webrtc.SessionDescription) { + atomic.AddInt32(&offerCount, 1) + // the second offer is a ice restart offer, so we wait transportB complete the ice gathering + if transportB.pc.ICEGatheringState() == webrtc.ICEGatheringStateGathering { + require.Eventually(t, func() bool { + return transportB.pc.ICEGatheringState() == webrtc.ICEGatheringStateComplete + }, 10*time.Second, time.Millisecond*10) + } + handleOffer(sd) + }) + + // first establish connection + require.NoError(t, transportA.CreateAndSendOffer(&webrtc.OfferOptions{ + ICERestart: true, + })) + + // ensure we are connected + require.Eventually(t, func() bool { + return transportA.pc.ICEConnectionState() == webrtc.ICEConnectionStateConnected && + transportB.pc.ICEConnectionState() == webrtc.ICEConnectionStateConnected && + atomic.LoadInt32(&offerCount) == 2 + }, testutils.ConnectTimeout, 10*time.Millisecond, "transport did not connect") + transportA.Close() + transportB.Close() +} + +func TestNegotiationFailed(t *testing.T) { + params := TransportParams{ + ParticipantID: "id", + ParticipantIdentity: "identity", + Target: livekit.SignalTarget_PUBLISHER, + Config: &WebRTCConfig{}, + } + transportA, err := NewPCTransport(params) + require.NoError(t, err) + + transportA.OnOffer(func(sd webrtc.SessionDescription) {}) + var failed int32 + transportA.OnNegotiationFailed(func() { + atomic.AddInt32(&failed, 1) + }) + transportA.CreateAndSendOffer(nil) + require.Eventually(t, func() bool { + return atomic.LoadInt32(&failed) == 1 + }, negotiationFailedTimout+time.Second, 10*time.Millisecond, "negotiation failed") +} + func handleOfferFunc(t *testing.T, current, other *PCTransport) func(sd webrtc.SessionDescription) { return func(sd webrtc.SessionDescription) { t.Logf("handling offer") diff --git a/pkg/rtc/types/interfaces.go b/pkg/rtc/types/interfaces.go index c8dd746b..53bbc667 100644 --- a/pkg/rtc/types/interfaces.go +++ b/pkg/rtc/types/interfaces.go @@ -80,6 +80,7 @@ const ( ParticipantCloseReasonSimulateMigration ParticipantCloseReasonSimulateNodeFailure ParticipantCloseReasonSimulateServerLeave + ParticipantCloseReasonNegotiateFailed ) func (p ParticipantCloseReason) String() string { @@ -118,6 +119,8 @@ func (p ParticipantCloseReason) String() string { return "SIMULATE_NODE_FAILURE" case ParticipantCloseReasonSimulateServerLeave: return "SIMULATE_SERVER_LEAVE" + case ParticipantCloseReasonNegotiateFailed: + return "NEGOTIATE_FAILED" default: return fmt.Sprintf("%d", int(p)) }