diff --git a/go.mod b/go.mod index e09d9f06..3697f001 100644 --- a/go.mod +++ b/go.mod @@ -23,7 +23,7 @@ require ( github.com/jxskiss/base62 v1.1.0 github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731 github.com/livekit/mediatransportutil v0.0.0-20250519131108-fb90f5acfded - github.com/livekit/protocol v1.39.2-0.20250612021623-821e6560dbf7 + github.com/livekit/protocol v1.39.2-0.20250612162213-de4c760d0eeb github.com/livekit/psrpc v0.6.1-0.20250511053145-465289d72c3c github.com/mackerelio/go-osstat v0.2.5 github.com/magefile/mage v1.15.0 @@ -64,8 +64,8 @@ require ( ) require ( - buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.6-20250603165357-b52ab10f4468.1 // indirect - buf.build/go/protovalidate v0.12.0 // indirect + buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.6-20250612022732-297b8109523d.1 // indirect + buf.build/go/protovalidate v0.13.0 // indirect buf.build/go/protoyaml v0.6.0 // indirect cel.dev/expr v0.24.0 // indirect dario.cat/mergo v1.0.0 // indirect diff --git a/go.sum b/go.sum index 200a67e2..84d53f59 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,11 @@ buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.6-20250603165357-b52ab10f4468.1 h1:uwSqFkn8DDTzNlaV9TxgSXY5OCaNdb4rH+Axd2FujkE= buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.6-20250603165357-b52ab10f4468.1/go.mod h1:avRlCjnFzl98VPaeCtJ24RrV/wwHFzB8sWXhj26+n/U= +buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.6-20250612022732-297b8109523d.1 h1:AGcXSSKkdfFsRk7qvOnl5VsaifpqL2Iwp9Xhmjchvpo= +buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.6-20250612022732-297b8109523d.1/go.mod h1:avRlCjnFzl98VPaeCtJ24RrV/wwHFzB8sWXhj26+n/U= buf.build/go/protovalidate v0.12.0 h1:4GKJotbspQjRCcqZMGVSuC8SjwZ/FmgtSuKDpKUTZew= buf.build/go/protovalidate v0.12.0/go.mod h1:q3PFfbzI05LeqxSwq+begW2syjy2Z6hLxZSkP1OH/D0= +buf.build/go/protovalidate v0.13.0 h1:t7nC2w79q8M2KaZfFTaXmyFhnYWTPbGFtZS2rebdIQM= +buf.build/go/protovalidate v0.13.0/go.mod h1:b0ZWMqcwgx2sa1IXTFT9EpJlMp03ESY4f8t9yulcykg= buf.build/go/protoyaml v0.6.0 h1:Nzz1lvcXF8YgNZXk+voPPwdU8FjDPTUV4ndNTXN0n2w= buf.build/go/protoyaml v0.6.0/go.mod h1:RgUOsBu/GYKLDSIRgQXniXbNgFlGEZnQpRAUdLAFV2Q= cel.dev/expr v0.24.0 h1:56OvJKSH3hDGL0ml5uSxZmz3/3Pq4tJ+fb1unVLAFcY= @@ -169,8 +173,8 @@ github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731 h1:9x+U2HGLrSw5AT github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731/go.mod h1:Rs3MhFwutWhGwmY1VQsygw28z5bWcnEYmS1OG9OxjOQ= github.com/livekit/mediatransportutil v0.0.0-20250519131108-fb90f5acfded h1:ylZPdnlX1RW9Z15SD4mp87vT2D2shsk0hpLJwSPcq3g= github.com/livekit/mediatransportutil v0.0.0-20250519131108-fb90f5acfded/go.mod h1:mSNtYzSf6iY9xM3UX42VEI+STHvMgHmrYzEHPcdhB8A= -github.com/livekit/protocol v1.39.2-0.20250612021623-821e6560dbf7 h1:JbsygjpjYid8KhUI3yka4djsigIFxmsB0AR65O0SQJw= -github.com/livekit/protocol v1.39.2-0.20250612021623-821e6560dbf7/go.mod h1:6HPISM0bkTXTk9RIaQTCe0IDbomBPz7Jwp+N3w5sqL0= +github.com/livekit/protocol v1.39.2-0.20250612162213-de4c760d0eeb h1:rDeauaLLiBOnhKxQzytVVv8nLSVs5LPijrAfuA/JXG0= +github.com/livekit/protocol v1.39.2-0.20250612162213-de4c760d0eeb/go.mod h1:6HPISM0bkTXTk9RIaQTCe0IDbomBPz7Jwp+N3w5sqL0= github.com/livekit/psrpc v0.6.1-0.20250511053145-465289d72c3c h1:WwEr0YBejYbKzk8LSaO9h8h0G9MnE7shyDu8yXQWmEc= github.com/livekit/psrpc v0.6.1-0.20250511053145-465289d72c3c/go.mod h1:kmD+AZPkWu0MaXIMv57jhNlbiSZZ/Jx4bzlxBDVmJes= github.com/mackerelio/go-osstat v0.2.5 h1:+MqTbZUhoIt4m8qzkVoXUJg1EuifwlAJSk4Yl2GXh+o= diff --git a/pkg/rtc/participant.go b/pkg/rtc/participant.go index 7eb611b3..d52babad 100644 --- a/pkg/rtc/participant.go +++ b/pkg/rtc/participant.go @@ -1034,8 +1034,13 @@ func (p *ParticipantImpl) updateRidsFromSDP(offer *webrtc.SessionDescription) { } // HandleOffer an offer from remote participant, used when clients make the initial connection -func (p *ParticipantImpl) HandleOffer(offer webrtc.SessionDescription) error { - p.pubLogger.Debugw("received offer", "transport", livekit.SignalTarget_PUBLISHER, "offer", offer) +func (p *ParticipantImpl) HandleOffer(offer webrtc.SessionDescription, offerId uint32) error { + p.pubLogger.Debugw( + "received offer", + "transport", livekit.SignalTarget_PUBLISHER, + "offer", offer, + "offerId", offerId, + ) if p.params.UseOneShotSignallingMode { if err := p.synthesizeAddTrackRequests(offer); err != nil { @@ -1050,7 +1055,7 @@ func (p *ParticipantImpl) HandleOffer(offer webrtc.SessionDescription) error { offer = p.setCodecPreferencesForPublisher(offer) p.updateRidsFromSDP(&offer) - err := p.TransportManager.HandleOffer(offer, shouldPend) + err := p.TransportManager.HandleOffer(offer, offerId, shouldPend) if p.params.UseOneShotSignallingMode { if onSubscriberReady := p.getOnSubscriberReady(); onSubscriberReady != nil { go onSubscriberReady(p) @@ -1059,16 +1064,21 @@ func (p *ParticipantImpl) HandleOffer(offer webrtc.SessionDescription) error { return err } -func (p *ParticipantImpl) onPublisherAnswer(answer webrtc.SessionDescription) error { +func (p *ParticipantImpl) onPublisherAnswer(answer webrtc.SessionDescription, answerId uint32) error { if p.IsClosed() || p.IsDisconnected() { return nil } answer = p.configurePublisherAnswer(answer) - p.pubLogger.Debugw("sending answer", "transport", livekit.SignalTarget_PUBLISHER, "answer", answer) + p.pubLogger.Debugw( + "sending answer", + "transport", livekit.SignalTarget_PUBLISHER, + "answer", answer, + "answerId", answerId, + ) return p.writeMessage(&livekit.SignalResponse{ Message: &livekit.SignalResponse_Answer{ - Answer: ToProtoSessionDescription(answer), + Answer: ToProtoSessionDescription(answer, answerId), }, }) } @@ -1090,8 +1100,13 @@ func (p *ParticipantImpl) GetAnswer() (webrtc.SessionDescription, error) { // HandleAnswer handles a client answer response, with subscriber PC, server initiates the // offer and client answers -func (p *ParticipantImpl) HandleAnswer(answer webrtc.SessionDescription) { - p.subLogger.Debugw("received answer", "transport", livekit.SignalTarget_SUBSCRIBER, "answer", answer) +func (p *ParticipantImpl) HandleAnswer(answer webrtc.SessionDescription, answerId uint32) { + p.subLogger.Debugw( + "received answer", + "transport", livekit.SignalTarget_SUBSCRIBER, + "answer", answer, + "answerId", answerId, + ) /* from server received join request to client answer * 1. server send join response & offer @@ -1101,7 +1116,7 @@ func (p *ParticipantImpl) HandleAnswer(answer webrtc.SessionDescription) { signalConnCost := time.Since(p.ConnectedAt()).Milliseconds() p.TransportManager.UpdateSignalingRTT(uint32(signalConnCost)) - p.TransportManager.HandleAnswer(answer) + p.TransportManager.HandleAnswer(answer, answerId) } func (p *ParticipantImpl) handleMigrateTracks() []*MediaTrack { @@ -1671,8 +1686,8 @@ type PublisherTransportHandler struct { AnyTransportHandler } -func (h PublisherTransportHandler) OnAnswer(sd webrtc.SessionDescription) error { - return h.p.onPublisherAnswer(sd) +func (h PublisherTransportHandler) OnAnswer(sd webrtc.SessionDescription, answerId uint32) error { + return h.p.onPublisherAnswer(sd, answerId) } func (h PublisherTransportHandler) OnTrack(track *webrtc.TrackRemote, rtpReceiver *webrtc.RTPReceiver) { @@ -1701,8 +1716,8 @@ type SubscriberTransportHandler struct { AnyTransportHandler } -func (h SubscriberTransportHandler) OnOffer(sd webrtc.SessionDescription) error { - return h.p.onSubscriberOffer(sd) +func (h SubscriberTransportHandler) OnOffer(sd webrtc.SessionDescription, offerId uint32) error { + return h.p.onSubscriberOffer(sd, offerId) } func (h SubscriberTransportHandler) OnStreamStateChange(update *streamallocator.StreamStateUpdate) error { @@ -1964,11 +1979,16 @@ func (p *ParticipantImpl) setIsPublisher(isPublisher bool) { } // when the server has an offer for participant -func (p *ParticipantImpl) onSubscriberOffer(offer webrtc.SessionDescription) error { - p.subLogger.Debugw("sending offer", "transport", livekit.SignalTarget_SUBSCRIBER, "offer", offer) +func (p *ParticipantImpl) onSubscriberOffer(offer webrtc.SessionDescription, offerId uint32) error { + p.subLogger.Debugw( + "sending offer", + "transport", livekit.SignalTarget_SUBSCRIBER, + "offer", offer, + "offerId", offerId, + ) return p.writeMessage(&livekit.SignalResponse{ Message: &livekit.SignalResponse_Offer{ - Offer: ToProtoSessionDescription(offer), + Offer: ToProtoSessionDescription(offer, offerId), }, }) } diff --git a/pkg/rtc/participant_internal_test.go b/pkg/rtc/participant_internal_test.go index 71ecf266..f8ee0e29 100644 --- a/pkg/rtc/participant_internal_test.go +++ b/pkg/rtc/participant_internal_test.go @@ -364,28 +364,32 @@ func TestDisableCodecs(t *testing.T) { } } require.True(t, found264) + offerId := uint32(42) // negotiated codec should not contain h264 sink := &routingfakes.FakeMessageSink{} participant.SetResponseSink(sink) var answer webrtc.SessionDescription + var answerId uint32 var answerReceived atomic.Bool + var answerIdReceived atomic.Uint32 sink.WriteMessageCalls(func(msg proto.Message) error { if res, ok := msg.(*livekit.SignalResponse); ok { if res.GetAnswer() != nil { - answer = FromProtoSessionDescription(res.GetAnswer()) + answer, answerId = FromProtoSessionDescription(res.GetAnswer()) answerReceived.Store(true) + answerIdReceived.Store(answerId) } } return nil }) - participant.HandleOffer(sdp) + participant.HandleOffer(sdp, offerId) testutils.WithTimeout(t, func() string { - if answerReceived.Load() { + if answerReceived.Load() && answerIdReceived.Load() == offerId { return "" } else { - return "answer not received" + return "answer not received OR answer id mismatch" } }) require.NoError(t, pc.SetRemoteDescription(answer), answer.SDP, sdp.SDP) @@ -510,24 +514,28 @@ func TestPreferVideoCodecForPublisher(t *testing.T) { sdp, err := pc.CreateOffer(nil) require.NoError(t, err) require.NoError(t, pc.SetLocalDescription(sdp)) + offerId := uint32(23) sink := &routingfakes.FakeMessageSink{} participant.SetResponseSink(sink) var answer webrtc.SessionDescription + var answerId uint32 var answerReceived atomic.Bool + var answerIdReceived atomic.Uint32 sink.WriteMessageCalls(func(msg proto.Message) error { if res, ok := msg.(*livekit.SignalResponse); ok { if res.GetAnswer() != nil { - answer = FromProtoSessionDescription(res.GetAnswer()) + answer, answerId = FromProtoSessionDescription(res.GetAnswer()) pc.SetRemoteDescription(answer) answerReceived.Store(true) + answerIdReceived.Store(answerId) } } return nil }) - participant.HandleOffer(sdp) + participant.HandleOffer(sdp, offerId) - require.Eventually(t, func() bool { return answerReceived.Load() }, 5*time.Second, 10*time.Millisecond) + require.Eventually(t, func() bool { return answerReceived.Load() && answerIdReceived.Load() == offerId }, 5*time.Second, 10*time.Millisecond) var h264Preferred bool parsed, err := answer.Unmarshal() @@ -594,24 +602,28 @@ func TestPreferAudioCodecForRed(t *testing.T) { pc.SetLocalDescription(sdp) // opus should be preferred require.Equal(t, codecs[0].MimeType, "audio/opus", sdp) + offerId := uint32(0xffffff) sink := &routingfakes.FakeMessageSink{} participant.SetResponseSink(sink) var answer webrtc.SessionDescription + var answerId uint32 var answerReceived atomic.Bool + var answerIdReceived atomic.Uint32 sink.WriteMessageCalls(func(msg proto.Message) error { if res, ok := msg.(*livekit.SignalResponse); ok { if res.GetAnswer() != nil { - answer = FromProtoSessionDescription(res.GetAnswer()) + answer, answerId = FromProtoSessionDescription(res.GetAnswer()) pc.SetRemoteDescription(answer) answerReceived.Store(true) + answerIdReceived.Store(answerId) } } return nil }) - participant.HandleOffer(sdp) + participant.HandleOffer(sdp, offerId) - require.Eventually(t, func() bool { return answerReceived.Load() }, 5*time.Second, 10*time.Millisecond) + require.Eventually(t, func() bool { return answerReceived.Load() && answerIdReceived.Load() == offerId }, 5*time.Second, 10*time.Millisecond) var redPreferred bool parsed, err := answer.Unmarshal() diff --git a/pkg/rtc/transport.go b/pkg/rtc/transport.go index 8b9afd4a..0c9e7b9e 100644 --- a/pkg/rtc/transport.go +++ b/pkg/rtc/transport.go @@ -17,6 +17,7 @@ package rtc import ( "fmt" "io" + "math/rand" "net" "strconv" "strings" @@ -247,6 +248,8 @@ type PCTransport struct { signalStateCheckTimer *time.Timer currentOfferIceCredential string // ice user:pwd, for publish side ice restart checking pendingRestartIceOffer *webrtc.SessionDescription + activeOfferId uint32 + activeAnswerId uint32 connectionDetails *types.ICEConnectionDetails selectedPair atomic.Pointer[webrtc.ICECandidatePair] @@ -482,6 +485,7 @@ func NewPCTransport(params TransportParams) (*PCTransport, error) { canReuseTransceiver: true, connectionDetails: types.NewICEConnectionDetails(params.Transport, params.Logger), lastNegotiate: time.Now(), + activeOfferId: uint32(rand.Intn(1 << 8)), } bwe, err := t.createPeerConnection() @@ -1287,7 +1291,7 @@ func (t *PCTransport) clearConnTimer() { } } -func (t *PCTransport) HandleRemoteDescription(sd webrtc.SessionDescription) error { +func (t *PCTransport) HandleRemoteDescription(sd webrtc.SessionDescription, remoteId uint32) error { if t.params.UseOneShotSignallingMode { // add remote candidates to ICE connection details parsed, err := sd.Unmarshal() @@ -1328,7 +1332,10 @@ func (t *PCTransport) HandleRemoteDescription(sd webrtc.SessionDescription) erro t.postEvent(event{ signal: signalRemoteDescriptionReceived, - data: &sd, + data: remoteDescriptionData{ + sessionDescription: &sd, + remoteId: remoteId, + }, }) return nil } @@ -2208,7 +2215,8 @@ func (t *PCTransport) createAndSendOffer(options *webrtc.OfferOptions) error { t.setupSignalStateCheckTimer() - if err := t.params.Handler.OnOffer(offer); err != nil { + t.activeOfferId++ + if err := t.params.Handler.OnOffer(offer, t.activeOfferId); err != nil { prometheus.ServiceOperationCounter.WithLabelValues("offer", "error", "write_message").Add(1) return errors.Wrap(err, "could not send offer") } @@ -2221,12 +2229,17 @@ func (t *PCTransport) handleSendOffer(_ event) error { return t.createAndSendOffer(nil) } +type remoteDescriptionData struct { + sessionDescription *webrtc.SessionDescription + remoteId uint32 +} + func (t *PCTransport) handleRemoteDescriptionReceived(e event) error { - sd := e.data.(*webrtc.SessionDescription) - if sd.Type == webrtc.SDPTypeOffer { - return t.handleRemoteOfferReceived(sd) + rdd := e.data.(remoteDescriptionData) + if rdd.sessionDescription.Type == webrtc.SDPTypeOffer { + return t.handleRemoteOfferReceived(rdd.sessionDescription, rdd.remoteId) } else { - return t.handleRemoteAnswerReceived(sd) + return t.handleRemoteAnswerReceived(rdd.sessionDescription, rdd.remoteId) } } @@ -2320,7 +2333,7 @@ func (t *PCTransport) createAndSendAnswer() error { t.params.Logger.Debugw("local answer (filtered)", "sdp", answer.SDP) } - if err := t.params.Handler.OnAnswer(answer); err != nil { + if err := t.params.Handler.OnAnswer(answer, t.activeAnswerId); err != nil { prometheus.ServiceOperationCounter.WithLabelValues("answer", "error", "write_message").Add(1) return errors.Wrap(err, "could not send answer") } @@ -2329,7 +2342,10 @@ func (t *PCTransport) createAndSendAnswer() error { return t.localDescriptionSent() } -func (t *PCTransport) handleRemoteOfferReceived(sd *webrtc.SessionDescription) error { +func (t *PCTransport) handleRemoteOfferReceived(sd *webrtc.SessionDescription, offerId uint32) error { + t.params.Logger.Debugw("processing offer", "offerId", offerId) + t.activeAnswerId = offerId + parsed, err := sd.Unmarshal() if err != nil { return nil @@ -2390,7 +2406,11 @@ func (t *PCTransport) handleRemoteOfferReceived(sd *webrtc.SessionDescription) e return t.createAndSendAnswer() } -func (t *PCTransport) handleRemoteAnswerReceived(sd *webrtc.SessionDescription) error { +func (t *PCTransport) handleRemoteAnswerReceived(sd *webrtc.SessionDescription, answerId uint32) error { + t.params.Logger.Debugw("processing answer", "answerId", answerId) + if answerId != 0 && answerId != t.activeOfferId { + t.params.Logger.Warnw("answer id mismatch", nil, "expected", t.activeOfferId, "got", answerId) + } t.clearSignalStateCheckTimer() if err := t.setRemoteDescription(*sd); err != nil { @@ -2455,7 +2475,8 @@ func (t *PCTransport) doICERestart() error { t.params.Logger.Infow("deferring ice restart to next offer") t.setNegotiationState(transport.NegotiationStateRetry) t.restartAtNextOffer = true - err := t.params.Handler.OnOffer(*offer) + t.activeOfferId++ + err := t.params.Handler.OnOffer(*offer, t.activeOfferId) if err != nil { prometheus.ServiceOperationCounter.WithLabelValues("offer", "error", "write_message").Add(1) } else { diff --git a/pkg/rtc/transport/handler.go b/pkg/rtc/transport/handler.go index 5fa6129e..e43e3bd7 100644 --- a/pkg/rtc/transport/handler.go +++ b/pkg/rtc/transport/handler.go @@ -42,8 +42,8 @@ type Handler interface { OnDataMessage(kind livekit.DataPacket_Kind, data []byte) OnDataMessageUnlabeled(data []byte) OnDataSendError(err error) - OnOffer(sd webrtc.SessionDescription) error - OnAnswer(sd webrtc.SessionDescription) error + OnOffer(sd webrtc.SessionDescription, offerId uint32) error + OnAnswer(sd webrtc.SessionDescription, answerId uint32) error OnNegotiationStateChanged(state NegotiationState) OnNegotiationFailed() OnStreamStateChange(update *streamallocator.StreamStateUpdate) error @@ -61,10 +61,10 @@ func (h UnimplementedHandler) OnTrack(track *webrtc.TrackRemote, rtpReceiver *we func (h UnimplementedHandler) OnDataMessage(kind livekit.DataPacket_Kind, data []byte) {} func (h UnimplementedHandler) OnDataMessageUnlabeled(data []byte) {} func (h UnimplementedHandler) OnDataSendError(err error) {} -func (h UnimplementedHandler) OnOffer(sd webrtc.SessionDescription) error { +func (h UnimplementedHandler) OnOffer(sd webrtc.SessionDescription, offerId uint32) error { return ErrNoOfferHandler } -func (h UnimplementedHandler) OnAnswer(sd webrtc.SessionDescription) error { +func (h UnimplementedHandler) OnAnswer(sd webrtc.SessionDescription, answerId uint32) error { return ErrNoAnswerHandler } func (h UnimplementedHandler) OnNegotiationStateChanged(state NegotiationState) {} diff --git a/pkg/rtc/transport/transportfakes/fake_handler.go b/pkg/rtc/transport/transportfakes/fake_handler.go index 5af37276..fd46b60b 100644 --- a/pkg/rtc/transport/transportfakes/fake_handler.go +++ b/pkg/rtc/transport/transportfakes/fake_handler.go @@ -12,10 +12,11 @@ import ( ) type FakeHandler struct { - OnAnswerStub func(webrtc.SessionDescription) error + OnAnswerStub func(webrtc.SessionDescription, uint32) error onAnswerMutex sync.RWMutex onAnswerArgsForCall []struct { arg1 webrtc.SessionDescription + arg2 uint32 } onAnswerReturns struct { result1 error @@ -74,10 +75,11 @@ type FakeHandler struct { onNegotiationStateChangedArgsForCall []struct { arg1 transport.NegotiationState } - OnOfferStub func(webrtc.SessionDescription) error + OnOfferStub func(webrtc.SessionDescription, uint32) error onOfferMutex sync.RWMutex onOfferArgsForCall []struct { arg1 webrtc.SessionDescription + arg2 uint32 } onOfferReturns struct { result1 error @@ -106,18 +108,19 @@ type FakeHandler struct { invocationsMutex sync.RWMutex } -func (fake *FakeHandler) OnAnswer(arg1 webrtc.SessionDescription) error { +func (fake *FakeHandler) OnAnswer(arg1 webrtc.SessionDescription, arg2 uint32) error { fake.onAnswerMutex.Lock() ret, specificReturn := fake.onAnswerReturnsOnCall[len(fake.onAnswerArgsForCall)] fake.onAnswerArgsForCall = append(fake.onAnswerArgsForCall, struct { arg1 webrtc.SessionDescription - }{arg1}) + arg2 uint32 + }{arg1, arg2}) stub := fake.OnAnswerStub fakeReturns := fake.onAnswerReturns - fake.recordInvocation("OnAnswer", []interface{}{arg1}) + fake.recordInvocation("OnAnswer", []interface{}{arg1, arg2}) fake.onAnswerMutex.Unlock() if stub != nil { - return stub(arg1) + return stub(arg1, arg2) } if specificReturn { return ret.result1 @@ -131,17 +134,17 @@ func (fake *FakeHandler) OnAnswerCallCount() int { return len(fake.onAnswerArgsForCall) } -func (fake *FakeHandler) OnAnswerCalls(stub func(webrtc.SessionDescription) error) { +func (fake *FakeHandler) OnAnswerCalls(stub func(webrtc.SessionDescription, uint32) error) { fake.onAnswerMutex.Lock() defer fake.onAnswerMutex.Unlock() fake.OnAnswerStub = stub } -func (fake *FakeHandler) OnAnswerArgsForCall(i int) webrtc.SessionDescription { +func (fake *FakeHandler) OnAnswerArgsForCall(i int) (webrtc.SessionDescription, uint32) { fake.onAnswerMutex.RLock() defer fake.onAnswerMutex.RUnlock() argsForCall := fake.onAnswerArgsForCall[i] - return argsForCall.arg1 + return argsForCall.arg1, argsForCall.arg2 } func (fake *FakeHandler) OnAnswerReturns(result1 error) { @@ -473,18 +476,19 @@ func (fake *FakeHandler) OnNegotiationStateChangedArgsForCall(i int) transport.N return argsForCall.arg1 } -func (fake *FakeHandler) OnOffer(arg1 webrtc.SessionDescription) error { +func (fake *FakeHandler) OnOffer(arg1 webrtc.SessionDescription, arg2 uint32) error { fake.onOfferMutex.Lock() ret, specificReturn := fake.onOfferReturnsOnCall[len(fake.onOfferArgsForCall)] fake.onOfferArgsForCall = append(fake.onOfferArgsForCall, struct { arg1 webrtc.SessionDescription - }{arg1}) + arg2 uint32 + }{arg1, arg2}) stub := fake.OnOfferStub fakeReturns := fake.onOfferReturns - fake.recordInvocation("OnOffer", []interface{}{arg1}) + fake.recordInvocation("OnOffer", []interface{}{arg1, arg2}) fake.onOfferMutex.Unlock() if stub != nil { - return stub(arg1) + return stub(arg1, arg2) } if specificReturn { return ret.result1 @@ -498,17 +502,17 @@ func (fake *FakeHandler) OnOfferCallCount() int { return len(fake.onOfferArgsForCall) } -func (fake *FakeHandler) OnOfferCalls(stub func(webrtc.SessionDescription) error) { +func (fake *FakeHandler) OnOfferCalls(stub func(webrtc.SessionDescription, uint32) error) { fake.onOfferMutex.Lock() defer fake.onOfferMutex.Unlock() fake.OnOfferStub = stub } -func (fake *FakeHandler) OnOfferArgsForCall(i int) webrtc.SessionDescription { +func (fake *FakeHandler) OnOfferArgsForCall(i int) (webrtc.SessionDescription, uint32) { fake.onOfferMutex.RLock() defer fake.onOfferMutex.RUnlock() argsForCall := fake.onOfferArgsForCall[i] - return argsForCall.arg1 + return argsForCall.arg1, argsForCall.arg2 } func (fake *FakeHandler) OnOfferReturns(result1 error) { diff --git a/pkg/rtc/transport_test.go b/pkg/rtc/transport_test.go index fb4ee17e..035058ec 100644 --- a/pkg/rtc/transport_test.go +++ b/pkg/rtc/transport_test.go @@ -68,7 +68,7 @@ func TestMissingAnswerDuringICERestart(t *testing.T) { // offer again, but missed var offerReceived atomic.Bool - handlerA.OnOfferCalls(func(sd webrtc.SessionDescription) error { + handlerA.OnOfferCalls(func(sd webrtc.SessionDescription, _offerId uint32) error { require.Equal(t, webrtc.SignalingStateHaveLocalOffer, transportA.pc.SignalingState()) require.Equal(t, transport.NegotiationStateRemote, negotiationState.Load().(transport.NegotiationState)) offerReceived.Store(true) @@ -113,7 +113,7 @@ func TestNegotiationTiming(t *testing.T) { handleICEExchange(t, transportA, transportB, handlerA, handlerB) offer := atomic.Value{} - handlerA.OnOfferCalls(func(sd webrtc.SessionDescription) error { + handlerA.OnOfferCalls(func(sd webrtc.SessionDescription, _offerId uint32) error { offer.Store(&sd) return nil }) @@ -161,11 +161,11 @@ func TestNegotiationTiming(t *testing.T) { actualOffer, ok := offer.Load().(*webrtc.SessionDescription) require.True(t, ok) - handlerB.OnAnswerCalls(func(answer webrtc.SessionDescription) error { - transportA.HandleRemoteDescription(answer) + handlerB.OnAnswerCalls(func(answer webrtc.SessionDescription, answerId uint32) error { + transportA.HandleRemoteDescription(answer, answerId) return nil }) - transportB.HandleRemoteDescription(*actualOffer) + transportB.HandleRemoteDescription(*actualOffer, 10) require.Eventually(t, func() bool { return transportA.IsEstablished() @@ -210,7 +210,7 @@ func TestFirstOfferMissedDuringICERestart(t *testing.T) { // first offer missed var firstOfferReceived atomic.Bool - handlerA.OnOfferCalls(func(sd webrtc.SessionDescription) error { + handlerA.OnOfferCalls(func(sd webrtc.SessionDescription, _offerId uint32) error { firstOfferReceived.Store(true) return nil }) @@ -222,13 +222,13 @@ func TestFirstOfferMissedDuringICERestart(t *testing.T) { // set offer/answer with restart ICE, will negotiate twice, // first one is recover from missed offer // second one is restartICE - handlerB.OnAnswerCalls(func(answer webrtc.SessionDescription) error { - transportA.HandleRemoteDescription(answer) + handlerB.OnAnswerCalls(func(answer webrtc.SessionDescription, answerId uint32) error { + transportA.HandleRemoteDescription(answer, answerId) return nil }) var offerCount atomic.Int32 - handlerA.OnOfferCalls(func(sd webrtc.SessionDescription) error { + handlerA.OnOfferCalls(func(sd webrtc.SessionDescription, offerId uint32) error { offerCount.Inc() // the second offer is a ice restart offer, so we wait transportB complete the ice gathering @@ -238,7 +238,7 @@ func TestFirstOfferMissedDuringICERestart(t *testing.T) { }, 10*time.Second, time.Millisecond*10) } - transportB.HandleRemoteDescription(sd) + transportB.HandleRemoteDescription(sd, offerId) return nil }) @@ -282,17 +282,17 @@ func TestFirstAnswerMissedDuringICERestart(t *testing.T) { // first answer missed var firstAnswerReceived atomic.Bool - handlerB.OnAnswerCalls(func(sd webrtc.SessionDescription) error { + handlerB.OnAnswerCalls(func(sd webrtc.SessionDescription, answerId uint32) error { if firstAnswerReceived.Load() { - transportA.HandleRemoteDescription(sd) + transportA.HandleRemoteDescription(sd, answerId) } else { // do not send first answer so that remote misses the first answer firstAnswerReceived.Store(true) } return nil }) - handlerA.OnOfferCalls(func(sd webrtc.SessionDescription) error { - transportB.HandleRemoteDescription(sd) + handlerA.OnOfferCalls(func(sd webrtc.SessionDescription, offerId uint32) error { + transportB.HandleRemoteDescription(sd, offerId) return nil }) @@ -305,7 +305,7 @@ func TestFirstAnswerMissedDuringICERestart(t *testing.T) { // first one is recover from missed offer // second one is restartICE var offerCount atomic.Int32 - handlerA.OnOfferCalls(func(sd webrtc.SessionDescription) error { + handlerA.OnOfferCalls(func(sd webrtc.SessionDescription, offerId uint32) error { offerCount.Inc() // the second offer is a ice restart offer, so we wait for transportB to complete ICE gathering @@ -315,7 +315,7 @@ func TestFirstAnswerMissedDuringICERestart(t *testing.T) { }, 10*time.Second, time.Millisecond*10) } - transportB.HandleRemoteDescription(sd) + transportB.HandleRemoteDescription(sd, offerId) return nil }) @@ -361,7 +361,7 @@ func TestNegotiationFailed(t *testing.T) { connectTransports(t, transportA, transportB, handlerA, handlerB, false, 1, 1) // reset OnOffer to force a negotiation failure - handlerA.OnOfferCalls(func(sd webrtc.SessionDescription) error { return nil }) + handlerA.OnOfferCalls(func(sd webrtc.SessionDescription, offerId uint32) error { return nil }) var failed atomic.Int32 handlerA.OnNegotiationFailedCalls(func() { failed.Inc() @@ -515,15 +515,15 @@ func handleICEExchange(t *testing.T, a, b *PCTransport, ah, bh *transportfakes.F func connectTransports(t *testing.T, offerer, answerer *PCTransport, offererHandler, answererHandler *transportfakes.FakeHandler, isICERestart bool, expectedOfferCount int32, expectedAnswerCount int32) { var offerCount atomic.Int32 var answerCount atomic.Int32 - answererHandler.OnAnswerCalls(func(answer webrtc.SessionDescription) error { + answererHandler.OnAnswerCalls(func(answer webrtc.SessionDescription, answerId uint32) error { answerCount.Inc() - offerer.HandleRemoteDescription(answer) + offerer.HandleRemoteDescription(answer, answerId) return nil }) - offererHandler.OnOfferCalls(func(offer webrtc.SessionDescription) error { + offererHandler.OnOfferCalls(func(offer webrtc.SessionDescription, offerId uint32) error { offerCount.Inc() - answerer.HandleRemoteDescription(offer) + answerer.HandleRemoteDescription(offer, offerId) return nil }) diff --git a/pkg/rtc/transportmanager.go b/pkg/rtc/transportmanager.go index 0baf2787..ec695961 100644 --- a/pkg/rtc/transportmanager.go +++ b/pkg/rtc/transportmanager.go @@ -75,9 +75,9 @@ type TransportManagerPublisherTransportHandler struct { TransportManagerTransportHandler } -func (h TransportManagerPublisherTransportHandler) OnAnswer(sd webrtc.SessionDescription) error { +func (h TransportManagerPublisherTransportHandler) OnAnswer(sd webrtc.SessionDescription, answerId uint32) error { h.t.lastPublisherAnswer.Store(sd) - return h.Handler.OnAnswer(sd) + return h.Handler.OnAnswer(sd, answerId) } // ------------------------------- @@ -122,6 +122,7 @@ type TransportManager struct { signalSourceValid atomic.Bool pendingOfferPublisher *webrtc.SessionDescription + pendingOfferIdPublisher uint32 pendingDataChannelsPublisher []*livekit.DataChannelInfo lastPublisherAnswer atomic.Value lastPublisherOffer atomic.Value @@ -440,17 +441,18 @@ func (t *TransportManager) LastPublisherOffer() webrtc.SessionDescription { return webrtc.SessionDescription{} } -func (t *TransportManager) HandleOffer(offer webrtc.SessionDescription, shouldPend bool) error { +func (t *TransportManager) HandleOffer(offer webrtc.SessionDescription, offerId uint32, shouldPend bool) error { t.lock.Lock() if shouldPend { t.pendingOfferPublisher = &offer + t.pendingOfferIdPublisher = offerId t.lock.Unlock() return nil } t.lock.Unlock() t.lastPublisherOffer.Store(offer) - return t.publisher.HandleRemoteDescription(offer) + return t.publisher.HandleRemoteDescription(offer, offerId) } func (t *TransportManager) GetAnswer() (webrtc.SessionDescription, error) { @@ -477,15 +479,18 @@ func (t *TransportManager) ProcessPendingPublisherOffer() { t.lock.Lock() pendingOffer := t.pendingOfferPublisher t.pendingOfferPublisher = nil + + pendingOfferId := t.pendingOfferIdPublisher + t.pendingOfferIdPublisher = 0 t.lock.Unlock() if pendingOffer != nil { - t.HandleOffer(*pendingOffer, false) + t.HandleOffer(*pendingOffer, pendingOfferId, false) } } -func (t *TransportManager) HandleAnswer(answer webrtc.SessionDescription) { - t.subscriber.HandleRemoteDescription(answer) +func (t *TransportManager) HandleAnswer(answer webrtc.SessionDescription, answerId uint32) { + t.subscriber.HandleRemoteDescription(answer, answerId) } // AddICECandidate adds candidates for remote peer diff --git a/pkg/rtc/types/interfaces.go b/pkg/rtc/types/interfaces.go index 7117733f..87adc1f3 100644 --- a/pkg/rtc/types/interfaces.go +++ b/pkg/rtc/types/interfaces.go @@ -399,14 +399,14 @@ type LocalParticipant interface { // PeerConnection AddICECandidate(candidate webrtc.ICECandidateInit, target livekit.SignalTarget) - HandleOffer(sdp webrtc.SessionDescription) error + HandleOffer(sdp webrtc.SessionDescription, offerId uint32) error GetAnswer() (webrtc.SessionDescription, error) HandleICETrickleSDPFragment(sdpFragment string) error HandleICERestartSDPFragment(sdpFragment string) (string, error) AddTrack(req *livekit.AddTrackRequest) SetTrackMuted(trackID livekit.TrackID, muted bool, fromAdmin bool) *livekit.TrackInfo - HandleAnswer(sdp webrtc.SessionDescription) + HandleAnswer(sdp webrtc.SessionDescription, answerId uint32) Negotiate(force bool) ICERestart(iceConfig *livekit.ICEConfig) AddTrackLocal(trackLocal webrtc.TrackLocal, params AddTrackParams) (*webrtc.RTPSender, *webrtc.RTPTransceiver, error) diff --git a/pkg/rtc/types/typesfakes/fake_local_participant.go b/pkg/rtc/types/typesfakes/fake_local_participant.go index 6a81a10a..3f7f79ba 100644 --- a/pkg/rtc/types/typesfakes/fake_local_participant.go +++ b/pkg/rtc/types/typesfakes/fake_local_participant.go @@ -474,10 +474,11 @@ type FakeLocalParticipant struct { getTrailerReturnsOnCall map[int]struct { result1 []byte } - HandleAnswerStub func(webrtc.SessionDescription) + HandleAnswerStub func(webrtc.SessionDescription, uint32) handleAnswerMutex sync.RWMutex handleAnswerArgsForCall []struct { arg1 webrtc.SessionDescription + arg2 uint32 } HandleICERestartSDPFragmentStub func(string) (string, error) handleICERestartSDPFragmentMutex sync.RWMutex @@ -515,10 +516,11 @@ type FakeLocalParticipant struct { handleMetricsReturnsOnCall map[int]struct { result1 error } - HandleOfferStub func(webrtc.SessionDescription) error + HandleOfferStub func(webrtc.SessionDescription, uint32) error handleOfferMutex sync.RWMutex handleOfferArgsForCall []struct { arg1 webrtc.SessionDescription + arg2 uint32 } handleOfferReturns struct { result1 error @@ -3673,16 +3675,17 @@ func (fake *FakeLocalParticipant) GetTrailerReturnsOnCall(i int, result1 []byte) }{result1} } -func (fake *FakeLocalParticipant) HandleAnswer(arg1 webrtc.SessionDescription) { +func (fake *FakeLocalParticipant) HandleAnswer(arg1 webrtc.SessionDescription, arg2 uint32) { fake.handleAnswerMutex.Lock() fake.handleAnswerArgsForCall = append(fake.handleAnswerArgsForCall, struct { arg1 webrtc.SessionDescription - }{arg1}) + arg2 uint32 + }{arg1, arg2}) stub := fake.HandleAnswerStub - fake.recordInvocation("HandleAnswer", []interface{}{arg1}) + fake.recordInvocation("HandleAnswer", []interface{}{arg1, arg2}) fake.handleAnswerMutex.Unlock() if stub != nil { - fake.HandleAnswerStub(arg1) + fake.HandleAnswerStub(arg1, arg2) } } @@ -3692,17 +3695,17 @@ func (fake *FakeLocalParticipant) HandleAnswerCallCount() int { return len(fake.handleAnswerArgsForCall) } -func (fake *FakeLocalParticipant) HandleAnswerCalls(stub func(webrtc.SessionDescription)) { +func (fake *FakeLocalParticipant) HandleAnswerCalls(stub func(webrtc.SessionDescription, uint32)) { fake.handleAnswerMutex.Lock() defer fake.handleAnswerMutex.Unlock() fake.HandleAnswerStub = stub } -func (fake *FakeLocalParticipant) HandleAnswerArgsForCall(i int) webrtc.SessionDescription { +func (fake *FakeLocalParticipant) HandleAnswerArgsForCall(i int) (webrtc.SessionDescription, uint32) { fake.handleAnswerMutex.RLock() defer fake.handleAnswerMutex.RUnlock() argsForCall := fake.handleAnswerArgsForCall[i] - return argsForCall.arg1 + return argsForCall.arg1, argsForCall.arg2 } func (fake *FakeLocalParticipant) HandleICERestartSDPFragment(arg1 string) (string, error) { @@ -3892,18 +3895,19 @@ func (fake *FakeLocalParticipant) HandleMetricsReturnsOnCall(i int, result1 erro }{result1} } -func (fake *FakeLocalParticipant) HandleOffer(arg1 webrtc.SessionDescription) error { +func (fake *FakeLocalParticipant) HandleOffer(arg1 webrtc.SessionDescription, arg2 uint32) error { fake.handleOfferMutex.Lock() ret, specificReturn := fake.handleOfferReturnsOnCall[len(fake.handleOfferArgsForCall)] fake.handleOfferArgsForCall = append(fake.handleOfferArgsForCall, struct { arg1 webrtc.SessionDescription - }{arg1}) + arg2 uint32 + }{arg1, arg2}) stub := fake.HandleOfferStub fakeReturns := fake.handleOfferReturns - fake.recordInvocation("HandleOffer", []interface{}{arg1}) + fake.recordInvocation("HandleOffer", []interface{}{arg1, arg2}) fake.handleOfferMutex.Unlock() if stub != nil { - return stub(arg1) + return stub(arg1, arg2) } if specificReturn { return ret.result1 @@ -3917,17 +3921,17 @@ func (fake *FakeLocalParticipant) HandleOfferCallCount() int { return len(fake.handleOfferArgsForCall) } -func (fake *FakeLocalParticipant) HandleOfferCalls(stub func(webrtc.SessionDescription) error) { +func (fake *FakeLocalParticipant) HandleOfferCalls(stub func(webrtc.SessionDescription, uint32) error) { fake.handleOfferMutex.Lock() defer fake.handleOfferMutex.Unlock() fake.HandleOfferStub = stub } -func (fake *FakeLocalParticipant) HandleOfferArgsForCall(i int) webrtc.SessionDescription { +func (fake *FakeLocalParticipant) HandleOfferArgsForCall(i int) (webrtc.SessionDescription, uint32) { fake.handleOfferMutex.RLock() defer fake.handleOfferMutex.RUnlock() argsForCall := fake.handleOfferArgsForCall[i] - return argsForCall.arg1 + return argsForCall.arg1, argsForCall.arg2 } func (fake *FakeLocalParticipant) HandleOfferReturns(result1 error) { diff --git a/pkg/rtc/utils.go b/pkg/rtc/utils.go index b6d0c29b..f0ed47b1 100644 --- a/pkg/rtc/utils.go +++ b/pkg/rtc/utils.go @@ -80,14 +80,15 @@ func UnpackDataTrackLabel(packed string) (participantID livekit.ParticipantID, t return } -func ToProtoSessionDescription(sd webrtc.SessionDescription) *livekit.SessionDescription { +func ToProtoSessionDescription(sd webrtc.SessionDescription, id uint32) *livekit.SessionDescription { return &livekit.SessionDescription{ Type: sd.Type.String(), Sdp: sd.SDP, + Id: id, } } -func FromProtoSessionDescription(sd *livekit.SessionDescription) webrtc.SessionDescription { +func FromProtoSessionDescription(sd *livekit.SessionDescription) (webrtc.SessionDescription, uint32) { var sdType webrtc.SDPType switch sd.Type { case webrtc.SDPTypeOffer.String(): @@ -102,7 +103,7 @@ func FromProtoSessionDescription(sd *livekit.SessionDescription) webrtc.SessionD return webrtc.SessionDescription{ Type: sdType, SDP: sd.Sdp, - } + }, sd.Id } func ToProtoTrickle(candidateInit webrtc.ICECandidateInit, target livekit.SignalTarget, final bool) *livekit.TrickleRequest { diff --git a/pkg/service/roommanager_service.go b/pkg/service/roommanager_service.go index b95b7e22..a962d3fa 100644 --- a/pkg/service/roommanager_service.go +++ b/pkg/service/roommanager_service.go @@ -53,7 +53,7 @@ func (s rtcRestService) Create(ctx context.Context, req *rpc.RTCRestCreateReques return nil, ErrParticipantNotFound } - if err := lp.HandleOffer(webrtc.SessionDescription{Type: webrtc.SDPTypeOffer, SDP: req.OfferSdp}); err != nil { + if err := lp.HandleOffer(webrtc.SessionDescription{Type: webrtc.SDPTypeOffer, SDP: req.OfferSdp}, 0); err != nil { lp.GetLogger().Errorw("rtcRest service: could not handle offer", err) return nil, err } diff --git a/test/client/client.go b/test/client/client.go index 68467c4b..5a921ecc 100644 --- a/test/client/client.go +++ b/test/client/client.go @@ -318,7 +318,7 @@ func NewRTCClient(conn *websocket.Conn, opts *Options) (*RTCClient, error) { logger.Debugw("subscriber fully established", "participant", c.localParticipant.Identity, "pID", c.localParticipant.Sid) c.subscriberFullyEstablished.Store(true) }) - subscriberHandler.OnAnswerCalls(func(answer webrtc.SessionDescription) error { + subscriberHandler.OnAnswerCalls(func(answer webrtc.SessionDescription, answerId uint32) error { // send remote an answer logger.Infow("sending subscriber answer", "participant", c.localParticipant.Identity, @@ -326,7 +326,7 @@ func NewRTCClient(conn *websocket.Conn, opts *Options) (*RTCClient, error) { ) return c.SendRequest(&livekit.SignalRequest{ Message: &livekit.SignalRequest_Answer{ - Answer: rtc.ToProtoSessionDescription(answer), + Answer: rtc.ToProtoSessionDescription(answer, answerId), }, }) }) @@ -355,7 +355,7 @@ func (c *RTCClient) Run() error { // run the session for { res, err := c.ReadResponse() - if errors.Is(io.EOF, err) { + if errors.Is(err, io.EOF) { return nil } else if err != nil { logger.Errorw("error while reading", err) @@ -400,8 +400,8 @@ func (c *RTCClient) handleSignalResponse(res *livekit.SignalResponse) error { logger.Infow("received server offer", "participant", c.localParticipant.Identity, ) - desc := rtc.FromProtoSessionDescription(msg.Offer) - c.handleOffer(desc) + desc, offerId := rtc.FromProtoSessionDescription(msg.Offer) + c.handleOffer(desc, offerId) case *livekit.SignalResponse_Trickle: candidateInit, err := rtc.FromProtoTrickle(msg.Trickle) if err != nil { @@ -827,26 +827,26 @@ func (c *RTCClient) handleDataMessageUnlabeled(data []byte) { } // handles a server initiated offer, handle on subscriber PC -func (c *RTCClient) handleOffer(desc webrtc.SessionDescription) { - c.subscriber.HandleRemoteDescription(desc) +func (c *RTCClient) handleOffer(desc webrtc.SessionDescription, offerId uint32) { + c.subscriber.HandleRemoteDescription(desc, offerId) } // the client handles answer on the publisher PC -func (c *RTCClient) handleAnswer(desc webrtc.SessionDescription) { +func (c *RTCClient) handleAnswer(desc webrtc.SessionDescription, answerId uint32) { logger.Infow("handling server answer", "participant", c.localParticipant.Identity) c.lastAnswer.Store(&desc) // remote answered the offer, establish connection - c.publisher.HandleRemoteDescription(desc) + c.publisher.HandleRemoteDescription(desc, answerId) } -func (c *RTCClient) onOffer(offer webrtc.SessionDescription) error { +func (c *RTCClient) onOffer(offer webrtc.SessionDescription, offerId uint32) error { if c.localParticipant != nil { logger.Infow("starting negotiation", "participant", c.localParticipant.Identity) } return c.SendRequest(&livekit.SignalRequest{ Message: &livekit.SignalRequest_Offer{ - Offer: rtc.ToProtoSessionDescription(offer), + Offer: rtc.ToProtoSessionDescription(offer, offerId), }, }) }