More v2 signalling changes (#3814)

* More v2 signalling changes

- Use wire message in relay signal
- Generate offerId for SDP for sync mode also
- more checks for SDP offer/answer state to see if there are cases of
  missed/duplicate messages

* clean up
This commit is contained in:
Raja Subramanian
2025-07-24 10:14:01 +05:30
committed by GitHub
parent b20db94dc9
commit a75295fcd5
14 changed files with 277 additions and 208 deletions
+24 -6
View File
@@ -363,6 +363,19 @@ func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) {
Logger: params.Logger,
Participant: p,
})
/* SIGNALLING-V2-TODO: instantiate these based on signalling version and signal transport
p.signalhandler = signalling.NewSignalHandlerv2(signalling.SignalHandlerv2Params{
Logger: params.Logger,
Participant: p,
})
p.signalling = signalling.NewSignallingv2(signalling.Signallingv2Params{
Logger: params.Logger,
})
p.signaller = signalling.NewSignallerv2Async(signalling.Signallerv2AsyncParams{
Logger: params.Logger,
Participant: p,
})
*/
p.id.Store(params.SID)
p.dataChannelStats = telemetry.NewBytesTrackStats(
@@ -1168,19 +1181,24 @@ func (p *ParticipantImpl) onPublisherAnswer(answer webrtc.SessionDescription, an
return p.sendSdpAnswer(answer, answerId)
}
func (p *ParticipantImpl) GetAnswer() (webrtc.SessionDescription, error) {
func (p *ParticipantImpl) GetAnswer() (webrtc.SessionDescription, uint32, error) {
if p.IsClosed() || p.IsDisconnected() {
return webrtc.SessionDescription{}, ErrParticipantSessionClosed
return webrtc.SessionDescription{}, 0, ErrParticipantSessionClosed
}
answer, err := p.TransportManager.GetAnswer()
answer, answerId, err := p.TransportManager.GetAnswer()
if err != nil {
return answer, err
return answer, answerId, err
}
answer = p.configurePublisherAnswer(answer)
p.pubLogger.Debugw("returning answer", "transport", livekit.SignalTarget_PUBLISHER, "answer", answer)
return answer, nil
p.pubLogger.Debugw(
"returning answer",
"transport", livekit.SignalTarget_PUBLISHER,
"answer", answer,
"answerId", answerId,
)
return answer, answerId, nil
}
// HandleAnswer handles a client answer response, with subscriber PC, server initiates the
+8 -23
View File
@@ -621,7 +621,7 @@ func (r *Room) Joinv2(
participant types.LocalParticipant,
opts *ParticipantOptions,
iceServers []*livekit.ICEServer,
) (*livekit.ConnectResponse, error) {
) error {
connectResponse, err := func() (*livekit.ConnectResponse, error) {
r.lock.Lock()
defer r.lock.Unlock()
@@ -782,7 +782,7 @@ func (r *Room) Joinv2(
return connectResponse, nil
}()
if err != nil {
return connectResponse, err
return err
}
// SIGNALLING-V2-TODO
@@ -791,37 +791,22 @@ func (r *Room) Joinv2(
// 3. HandleOffer and get answer (publisher)
r.subscribeToExistingTracks(participant, true)
offer, err := participant.GetOffer()
offer, offerId, err := participant.GetOffer()
if err != nil {
participant.GetLogger().Warnw("could not get offer", err)
prometheus.ServiceOperationCounter.WithLabelValues("participant_join", "error", "get_subscriber_offer").Add(1)
return nil, err
return err
}
connectResponse.SubscriberSdp = protosignalling.ToProtoSessionDescription(offer, 0) // SIGNALLING-V2-TODO - need to proper offerId?
// SIGNALLING-V2-TODO: when moving to envelope response, do SendSdpOffer after sending connect response
connectResponse.SubscriberSdp = protosignalling.ToProtoSessionDescription(offer, offerId)
// for sync response, this does not actually send, only generates messageId and caches the message
if err := participant.SendConnectResponse(connectResponse); err != nil {
prometheus.ServiceOperationCounter.WithLabelValues("participant_join", "error", "send_response").Add(1)
return nil, err
}
if wireMessage := participant.SignalPendingMessages(); wireMessage != nil {
if wireMessage, ok := wireMessage.(*livekit.Signalv2WireMessage); ok {
switch msg := wireMessage.GetMessage().(type) {
case *livekit.Signalv2WireMessage_Envelope:
got_connect_response:
for _, innerMsg := range msg.Envelope.GetServerMessages() {
switch serverMessage := innerMsg.GetMessage().(type) {
case *livekit.Signalv2ServerMessage_ConnectResponse:
connectResponse = serverMessage.ConnectResponse
break got_connect_response
}
}
}
}
return err
}
prometheus.ServiceOperationCounter.WithLabelValues("participant_join", "success", "").Add(1)
return connectResponse, nil
return nil
}
func (r *Room) ReplaceParticipantRequestSource(identity livekit.ParticipantIdentity, reqSource routing.MessageSource) {
+8
View File
@@ -105,6 +105,14 @@ func (s *signalhandlerv2) HandleRequest(msg proto.Message) error {
case *livekit.Signalv2ClientMessage_SubscriberSdp:
s.params.Participant.HandleAnswer(protosignalling.FromProtoSessionDescription(payload.SubscriberSdp))
case *livekit.Signalv2ClientMessage_Trickle:
candidateInit, err := protosignalling.FromProtoTrickle(payload.Trickle)
if err != nil {
s.params.Logger.Warnw("could not decode trickle", err)
return err
}
s.params.Participant.AddICECandidate(candidateInit, payload.Trickle.Target)
}
/* SIGNALLING-V2-TODO: uncomment once sequencer is implemented on both sides
+88 -22
View File
@@ -235,6 +235,14 @@ type PCTransport struct {
preferTCP atomic.Bool
isClosed atomic.Bool
// used to check for offer/answer pairing,
// i. e. every offer should have an answer before another offer can be sent
localOfferId atomic.Uint32
remoteAnswerId atomic.Uint32
remoteOfferId atomic.Uint32
localAnswerId atomic.Uint32
eventsQueue *utils.TypedOpsQueue[event]
// the following should be accessed only in event processing go routine
@@ -248,8 +256,6 @@ 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]
@@ -486,8 +492,8 @@ func NewPCTransport(params TransportParams) (*PCTransport, error) {
canReuseTransceiver: true,
connectionDetails: types.NewICEConnectionDetails(params.Transport, params.Logger),
lastNegotiate: time.Now(),
activeOfferId: uint32(rand.Intn(1<<8) + 1),
}
t.localOfferId.Store(uint32(rand.Intn(1<<8) + 1))
bwe, err := t.createPeerConnection()
if err != nil {
@@ -1294,6 +1300,24 @@ func (t *PCTransport) clearConnTimer() {
func (t *PCTransport) HandleRemoteDescription(sd webrtc.SessionDescription, remoteId uint32) error {
if t.params.UseOneShotSignallingMode || t.params.SynchronousLocalCandidatesMode {
if sd.Type == webrtc.SDPTypeOffer {
remoteOfferId := t.remoteOfferId.Load()
if remoteOfferId != 0 && remoteOfferId != t.localAnswerId.Load() {
t.params.Logger.Warnw(
"sdp state: multiple offers without answer", nil,
"remoteOfferId", remoteOfferId,
"localAnswerId", t.localAnswerId.Load(),
"receivedRemoteOfferId", remoteId,
)
}
t.remoteOfferId.Store(remoteId)
} else {
if remoteId != 0 && remoteId != t.localOfferId.Load() {
t.params.Logger.Warnw("sdp state: answer id mismatch", nil, "expected", t.localOfferId.Load(), "got", remoteId)
}
t.remoteAnswerId.Store(remoteId)
}
// SIGNALLING-V2-TODO: need to support filtering candidates for transport fallback
// add remote candidates to ICE connection details
parsed, err := sd.Unmarshal()
@@ -1342,23 +1366,23 @@ func (t *PCTransport) HandleRemoteDescription(sd webrtc.SessionDescription, remo
return nil
}
func (t *PCTransport) GetAnswer() (webrtc.SessionDescription, error) {
func (t *PCTransport) GetAnswer() (webrtc.SessionDescription, uint32, error) {
if !t.params.UseOneShotSignallingMode && !t.params.SynchronousLocalCandidatesMode {
return webrtc.SessionDescription{}, ErrNotSynchronousLocalCandidatesMode
return webrtc.SessionDescription{}, 0, ErrNotSynchronousLocalCandidatesMode
}
prd := t.pc.PendingRemoteDescription()
if prd == nil || prd.Type != webrtc.SDPTypeOffer {
return webrtc.SessionDescription{}, ErrNoRemoteDescription
return webrtc.SessionDescription{}, 0, ErrNoRemoteDescription
}
answer, err := t.pc.CreateAnswer(nil)
if err != nil {
return webrtc.SessionDescription{}, err
return webrtc.SessionDescription{}, 0, err
}
if err = t.pc.SetLocalDescription(answer); err != nil {
return webrtc.SessionDescription{}, err
return webrtc.SessionDescription{}, 0, err
}
// wait for gathering to complete to include all candidates in the answer
@@ -1387,21 +1411,24 @@ func (t *PCTransport) GetAnswer() (webrtc.SessionDescription, error) {
}
}
return *cld, nil
answerId := t.remoteOfferId.Load()
t.localAnswerId.Store(answerId)
return *cld, answerId, nil
}
func (t *PCTransport) GetOffer() (webrtc.SessionDescription, error) {
func (t *PCTransport) GetOffer() (webrtc.SessionDescription, uint32, error) {
if !t.params.SynchronousLocalCandidatesMode {
return webrtc.SessionDescription{}, ErrNotSynchronousLocalCandidatesMode
return webrtc.SessionDescription{}, 0, ErrNotSynchronousLocalCandidatesMode
}
offer, err := t.pc.CreateOffer(nil)
if err != nil {
return webrtc.SessionDescription{}, err
return webrtc.SessionDescription{}, 0, err
}
if err = t.pc.SetLocalDescription(offer); err != nil {
return webrtc.SessionDescription{}, err
return webrtc.SessionDescription{}, 0, err
}
// wait for gathering to complete to include all candidates in the answer
@@ -1430,7 +1457,7 @@ func (t *PCTransport) GetOffer() (webrtc.SessionDescription, error) {
}
}
return *pld, nil
return *pld, t.localOfferId.Inc(), nil
}
func (t *PCTransport) GetICESessionUfrag() (string, error) {
@@ -2260,8 +2287,16 @@ func (t *PCTransport) createAndSendOffer(options *webrtc.OfferOptions) error {
t.setupSignalStateCheckTimer()
t.activeOfferId++
if err := t.params.Handler.OnOffer(offer, t.activeOfferId); err != nil {
remoteAnswerId := t.remoteAnswerId.Load()
if remoteAnswerId != 0 && remoteAnswerId != t.localOfferId.Load() {
t.params.Logger.Warnw(
"sdp state: sending offer before receiving answer", nil,
"localOfferId", t.localOfferId.Load(),
"remoteAnswerId", remoteAnswerId,
)
}
if err := t.params.Handler.OnOffer(offer, t.localOfferId.Inc()); err != nil {
prometheus.ServiceOperationCounter.WithLabelValues("offer", "error", "write_message").Add(1)
return errors.Wrap(err, "could not send offer")
}
@@ -2378,10 +2413,21 @@ func (t *PCTransport) createAndSendAnswer() error {
t.params.Logger.Debugw("local answer (filtered)", "sdp", answer.SDP)
}
if err := t.params.Handler.OnAnswer(answer, t.activeAnswerId); err != nil {
localAnswerId := t.localAnswerId.Load()
if localAnswerId != 0 && localAnswerId >= t.remoteOfferId.Load() {
t.params.Logger.Warnw(
"sdp state: duplicate answer", nil,
"localAnswerId", localAnswerId,
"remoteOfferId", t.remoteOfferId.Load(),
)
}
answerId := t.remoteOfferId.Load()
if err := t.params.Handler.OnAnswer(answer, answerId); err != nil {
prometheus.ServiceOperationCounter.WithLabelValues("answer", "error", "write_message").Add(1)
return errors.Wrap(err, "could not send answer")
}
t.localAnswerId.Store(answerId)
prometheus.ServiceOperationCounter.WithLabelValues("answer", "success", "").Add(1)
return t.localDescriptionSent()
@@ -2389,7 +2435,16 @@ func (t *PCTransport) createAndSendAnswer() error {
func (t *PCTransport) handleRemoteOfferReceived(sd *webrtc.SessionDescription, offerId uint32) error {
t.params.Logger.Debugw("processing offer", "offerId", offerId)
t.activeAnswerId = offerId
remoteOfferId := t.remoteOfferId.Load()
if remoteOfferId != 0 && remoteOfferId != t.localAnswerId.Load() {
t.params.Logger.Warnw(
"sdp state: multiple offers without answer", nil,
"remoteOfferId", remoteOfferId,
"localAnswerId", t.localAnswerId.Load(),
"receivedRemoteOfferId", offerId,
)
}
t.remoteOfferId.Store(offerId)
parsed, err := sd.Unmarshal()
if err != nil {
@@ -2453,9 +2508,11 @@ func (t *PCTransport) handleRemoteOfferReceived(sd *webrtc.SessionDescription, o
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)
if answerId != 0 && answerId != t.localOfferId.Load() {
t.params.Logger.Warnw("sdp state: answer id mismatch", nil, "expected", t.localOfferId.Load(), "got", answerId)
}
t.remoteAnswerId.Store(answerId)
t.clearSignalStateCheckTimer()
if err := t.setRemoteDescription(*sd); err != nil {
@@ -2520,8 +2577,17 @@ func (t *PCTransport) doICERestart() error {
t.params.Logger.Infow("deferring ice restart to next offer")
t.setNegotiationState(transport.NegotiationStateRetry)
t.restartAtNextOffer = true
t.activeOfferId++
err := t.params.Handler.OnOffer(*offer, t.activeOfferId)
remoteAnswerId := t.remoteAnswerId.Load()
if remoteAnswerId != 0 && remoteAnswerId != t.localOfferId.Load() {
t.params.Logger.Warnw(
"sdp state: answer not received in ICE restart", nil,
"localOfferId", t.localOfferId.Load(),
"remoteAnswerId", remoteAnswerId,
)
}
err := t.params.Handler.OnOffer(*offer, t.localOfferId.Inc())
if err != nil {
prometheus.ServiceOperationCounter.WithLabelValues("offer", "error", "write_message").Add(1)
} else {
+4 -4
View File
@@ -458,12 +458,12 @@ func (t *TransportManager) HandleOffer(offer webrtc.SessionDescription, offerId
return t.publisher.HandleRemoteDescription(offer, offerId)
}
func (t *TransportManager) GetAnswer() (webrtc.SessionDescription, error) {
answer, err := t.publisher.GetAnswer()
func (t *TransportManager) GetAnswer() (webrtc.SessionDescription, uint32, error) {
answer, answerId, err := t.publisher.GetAnswer()
if err == nil {
t.lastPublisherAnswer.Store(answer)
}
return answer, err
return answer, answerId, err
}
func (t *TransportManager) GetPublisherICESessionUfrag() (string, error) {
@@ -496,7 +496,7 @@ func (t *TransportManager) HandleAnswer(answer webrtc.SessionDescription, answer
t.subscriber.HandleRemoteDescription(answer, answerId)
}
func (t *TransportManager) GetOffer() (webrtc.SessionDescription, error) {
func (t *TransportManager) GetOffer() (webrtc.SessionDescription, uint32, error) {
return t.subscriber.GetOffer()
}
+2 -2
View File
@@ -403,14 +403,14 @@ type LocalParticipant interface {
// PeerConnection
AddICECandidate(candidate webrtc.ICECandidateInit, target livekit.SignalTarget)
HandleOffer(sdp webrtc.SessionDescription, offerId uint32) error
GetAnswer() (webrtc.SessionDescription, error)
GetAnswer() (webrtc.SessionDescription, uint32, 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, answerId uint32)
GetOffer() (webrtc.SessionDescription, error)
GetOffer() (webrtc.SessionDescription, uint32, error)
Negotiate(force bool)
ICERestart(iceConfig *livekit.ICEConfig)
AddTrackLocal(trackLocal webrtc.TrackLocal, params AddTrackParams) (*webrtc.RTPSender, *webrtc.RTPTransceiver, error)
@@ -213,17 +213,19 @@ type FakeLocalParticipant struct {
getAdaptiveStreamReturnsOnCall map[int]struct {
result1 bool
}
GetAnswerStub func() (webrtc.SessionDescription, error)
GetAnswerStub func() (webrtc.SessionDescription, uint32, error)
getAnswerMutex sync.RWMutex
getAnswerArgsForCall []struct {
}
getAnswerReturns struct {
result1 webrtc.SessionDescription
result2 error
result2 uint32
result3 error
}
getAnswerReturnsOnCall map[int]struct {
result1 webrtc.SessionDescription
result2 error
result2 uint32
result3 error
}
GetAudioLevelStub func() (float64, bool)
getAudioLevelMutex sync.RWMutex
@@ -361,17 +363,19 @@ type FakeLocalParticipant struct {
getLoggerResolverReturnsOnCall map[int]struct {
result1 logger.DeferredFieldResolver
}
GetOfferStub func() (webrtc.SessionDescription, error)
GetOfferStub func() (webrtc.SessionDescription, uint32, error)
getOfferMutex sync.RWMutex
getOfferArgsForCall []struct {
}
getOfferReturns struct {
result1 webrtc.SessionDescription
result2 error
result2 uint32
result3 error
}
getOfferReturnsOnCall map[int]struct {
result1 webrtc.SessionDescription
result2 error
result2 uint32
result3 error
}
GetPacerStub func() pacer.Pacer
getPacerMutex sync.RWMutex
@@ -2437,7 +2441,7 @@ func (fake *FakeLocalParticipant) GetAdaptiveStreamReturnsOnCall(i int, result1
}{result1}
}
func (fake *FakeLocalParticipant) GetAnswer() (webrtc.SessionDescription, error) {
func (fake *FakeLocalParticipant) GetAnswer() (webrtc.SessionDescription, uint32, error) {
fake.getAnswerMutex.Lock()
ret, specificReturn := fake.getAnswerReturnsOnCall[len(fake.getAnswerArgsForCall)]
fake.getAnswerArgsForCall = append(fake.getAnswerArgsForCall, struct {
@@ -2450,9 +2454,9 @@ func (fake *FakeLocalParticipant) GetAnswer() (webrtc.SessionDescription, error)
return stub()
}
if specificReturn {
return ret.result1, ret.result2
return ret.result1, ret.result2, ret.result3
}
return fakeReturns.result1, fakeReturns.result2
return fakeReturns.result1, fakeReturns.result2, fakeReturns.result3
}
func (fake *FakeLocalParticipant) GetAnswerCallCount() int {
@@ -2461,36 +2465,39 @@ func (fake *FakeLocalParticipant) GetAnswerCallCount() int {
return len(fake.getAnswerArgsForCall)
}
func (fake *FakeLocalParticipant) GetAnswerCalls(stub func() (webrtc.SessionDescription, error)) {
func (fake *FakeLocalParticipant) GetAnswerCalls(stub func() (webrtc.SessionDescription, uint32, error)) {
fake.getAnswerMutex.Lock()
defer fake.getAnswerMutex.Unlock()
fake.GetAnswerStub = stub
}
func (fake *FakeLocalParticipant) GetAnswerReturns(result1 webrtc.SessionDescription, result2 error) {
func (fake *FakeLocalParticipant) GetAnswerReturns(result1 webrtc.SessionDescription, result2 uint32, result3 error) {
fake.getAnswerMutex.Lock()
defer fake.getAnswerMutex.Unlock()
fake.GetAnswerStub = nil
fake.getAnswerReturns = struct {
result1 webrtc.SessionDescription
result2 error
}{result1, result2}
result2 uint32
result3 error
}{result1, result2, result3}
}
func (fake *FakeLocalParticipant) GetAnswerReturnsOnCall(i int, result1 webrtc.SessionDescription, result2 error) {
func (fake *FakeLocalParticipant) GetAnswerReturnsOnCall(i int, result1 webrtc.SessionDescription, result2 uint32, result3 error) {
fake.getAnswerMutex.Lock()
defer fake.getAnswerMutex.Unlock()
fake.GetAnswerStub = nil
if fake.getAnswerReturnsOnCall == nil {
fake.getAnswerReturnsOnCall = make(map[int]struct {
result1 webrtc.SessionDescription
result2 error
result2 uint32
result3 error
})
}
fake.getAnswerReturnsOnCall[i] = struct {
result1 webrtc.SessionDescription
result2 error
}{result1, result2}
result2 uint32
result3 error
}{result1, result2, result3}
}
func (fake *FakeLocalParticipant) GetAudioLevel() (float64, bool) {
@@ -3204,7 +3211,7 @@ func (fake *FakeLocalParticipant) GetLoggerResolverReturnsOnCall(i int, result1
}{result1}
}
func (fake *FakeLocalParticipant) GetOffer() (webrtc.SessionDescription, error) {
func (fake *FakeLocalParticipant) GetOffer() (webrtc.SessionDescription, uint32, error) {
fake.getOfferMutex.Lock()
ret, specificReturn := fake.getOfferReturnsOnCall[len(fake.getOfferArgsForCall)]
fake.getOfferArgsForCall = append(fake.getOfferArgsForCall, struct {
@@ -3217,9 +3224,9 @@ func (fake *FakeLocalParticipant) GetOffer() (webrtc.SessionDescription, error)
return stub()
}
if specificReturn {
return ret.result1, ret.result2
return ret.result1, ret.result2, ret.result3
}
return fakeReturns.result1, fakeReturns.result2
return fakeReturns.result1, fakeReturns.result2, fakeReturns.result3
}
func (fake *FakeLocalParticipant) GetOfferCallCount() int {
@@ -3228,36 +3235,39 @@ func (fake *FakeLocalParticipant) GetOfferCallCount() int {
return len(fake.getOfferArgsForCall)
}
func (fake *FakeLocalParticipant) GetOfferCalls(stub func() (webrtc.SessionDescription, error)) {
func (fake *FakeLocalParticipant) GetOfferCalls(stub func() (webrtc.SessionDescription, uint32, error)) {
fake.getOfferMutex.Lock()
defer fake.getOfferMutex.Unlock()
fake.GetOfferStub = stub
}
func (fake *FakeLocalParticipant) GetOfferReturns(result1 webrtc.SessionDescription, result2 error) {
func (fake *FakeLocalParticipant) GetOfferReturns(result1 webrtc.SessionDescription, result2 uint32, result3 error) {
fake.getOfferMutex.Lock()
defer fake.getOfferMutex.Unlock()
fake.GetOfferStub = nil
fake.getOfferReturns = struct {
result1 webrtc.SessionDescription
result2 error
}{result1, result2}
result2 uint32
result3 error
}{result1, result2, result3}
}
func (fake *FakeLocalParticipant) GetOfferReturnsOnCall(i int, result1 webrtc.SessionDescription, result2 error) {
func (fake *FakeLocalParticipant) GetOfferReturnsOnCall(i int, result1 webrtc.SessionDescription, result2 uint32, result3 error) {
fake.getOfferMutex.Lock()
defer fake.getOfferMutex.Unlock()
fake.GetOfferStub = nil
if fake.getOfferReturnsOnCall == nil {
fake.getOfferReturnsOnCall = make(map[int]struct {
result1 webrtc.SessionDescription
result2 error
result2 uint32
result3 error
})
}
fake.getOfferReturnsOnCall[i] = struct {
result1 webrtc.SessionDescription
result2 error
}{result1, result2}
result2 uint32
result3 error
}{result1, result2, result3}
}
func (fake *FakeLocalParticipant) GetPacer() pacer.Pacer {