Signalling V2 protocol implementation start (#3794)

* WIP

* name

* refactor validate

* WIP

* WIP

* signal cache initial impl

* HandleConnect in room manager

* generate subscriber offer

* handle ConnectRequest as stand alone

* segmentation, reassembly

* clean up

* rearrange

* lock scope

* support metadata in connect request

* prom

* add SifTrailer to ConnectResponse

* prom for get offer error counter

* RtcInit counter

* Jie feedback

* signal client

* consolidate v1 and v2 into SignalClient

* clean up

* comment

* deps

* mage generate

* fix tests

* pass around roomName and participantIdentity

* mage generate
This commit is contained in:
Raja Subramanian
2025-07-18 00:01:21 +05:30
committed by GitHub
parent ba702a5323
commit b9a44c3fbf
32 changed files with 2299 additions and 394 deletions
+234 -16
View File
@@ -143,7 +143,7 @@ type Room struct {
userPacketDeduper *UserPacketDeduper
dataMessagecache *utils.TimeSizeCache[types.DataMessageCache]
dataMessageCache *utils.TimeSizeCache[types.DataMessageCache]
}
type ParticipantOptions struct {
@@ -273,7 +273,7 @@ func NewRoom(
disconnectSignalOnResumeParticipants: make(map[livekit.ParticipantIdentity]time.Time),
disconnectSignalOnResumeNoMessagesParticipants: make(map[livekit.ParticipantIdentity]*disconnectSignalOnResumeNoMessages),
userPacketDeduper: NewUserPacketDeduper(),
dataMessagecache: utils.NewTimeSizeCache[types.DataMessageCache](utils.TimeSizeCacheParams{
dataMessageCache: utils.NewTimeSizeCache[types.DataMessageCache](utils.TimeSizeCacheParams{
TTL: dataMessageCacheTTL,
MaxSize: dataMessageCacheSize,
}),
@@ -426,7 +426,12 @@ func (r *Room) Release() {
r.holds.Dec()
}
func (r *Room) Join(participant types.LocalParticipant, requestSource routing.MessageSource, opts *ParticipantOptions, iceServers []*livekit.ICEServer) error {
func (r *Room) Join(
participant types.LocalParticipant,
requestSource routing.MessageSource,
opts *ParticipantOptions,
iceServers []*livekit.ICEServer,
) error {
r.lock.Lock()
defer r.lock.Unlock()
@@ -464,7 +469,7 @@ func (r *Room) Join(participant types.LocalParticipant, requestSource routing.Me
defer onStateChangeMu.Unlock()
if state := p.State(); state == livekit.ParticipantInfo_ACTIVE {
// subscribe participant to existing published tracks
r.subscribeToExistingTracks(p)
r.subscribeToExistingTracks(p, false)
connectTime := time.Since(p.ConnectedAt())
meta := &livekit.AnalyticsClientMeta{
@@ -503,7 +508,7 @@ func (r *Room) Join(participant types.LocalParticipant, requestSource routing.Me
}
})
participant.OnSubscriberReady(func(p types.LocalParticipant) {
r.subscribeToExistingTracks(p)
r.subscribeToExistingTracks(p, false)
})
// it's important to set this before connection, we don't want to miss out on any published tracks
participant.OnTrackPublished(r.onTrackPublished)
@@ -550,7 +555,8 @@ func (r *Room) Join(participant types.LocalParticipant, requestSource routing.Me
r.launchTargetAgents(maps.Values(r.agentDispatches), participant, livekit.JobType_JT_PARTICIPANT)
r.logger.Debugw("new participant joined",
r.logger.Debugw(
"new participant joined",
"pID", participant.ID(),
"participant", participant.Identity(),
"clientInfo", logger.Proto(participant.GetClientInfo()),
@@ -591,7 +597,7 @@ func (r *Room) Join(participant types.LocalParticipant, requestSource routing.Me
// initiates sub connection as primary
if participant.ProtocolVersion().SupportFastStart() {
go func() {
r.subscribeToExistingTracks(participant)
r.subscribeToExistingTracks(participant, false)
participant.Negotiate(true)
}()
} else {
@@ -604,6 +610,193 @@ func (r *Room) Join(participant types.LocalParticipant, requestSource routing.Me
return nil
}
// SIGNALLING-V2-TODO: consolidate common parts between this function and Join()
func (r *Room) Joinv2(
participant types.LocalParticipant,
opts *ParticipantOptions,
iceServers []*livekit.ICEServer,
) (*livekit.ConnectResponse, error) {
connectResponse, err := func() (*livekit.ConnectResponse, error) {
r.lock.Lock()
defer r.lock.Unlock()
if r.IsClosed() {
return nil, ErrRoomClosed
}
if r.participants[participant.Identity()] != nil {
return nil, ErrAlreadyJoined
}
if r.protoRoom.MaxParticipants > 0 && !participant.IsDependent() {
numParticipants := uint32(0)
for _, p := range r.participants {
if !p.IsDependent() {
numParticipants++
}
}
if numParticipants >= r.protoRoom.MaxParticipants {
return nil, ErrMaxParticipantsExceeded
}
}
if r.FirstJoinedAt() == 0 && !participant.IsDependent() {
r.joinedAt.Store(time.Now().Unix())
}
var onStateChangeMu sync.Mutex
participant.OnStateChange(func(p types.LocalParticipant) {
if r.onParticipantChanged != nil {
r.onParticipantChanged(p)
}
r.broadcastParticipantState(p, broadcastOptions{skipSource: true})
onStateChangeMu.Lock()
defer onStateChangeMu.Unlock()
if state := p.State(); state == livekit.ParticipantInfo_ACTIVE {
// subscribe participant to existing published tracks
r.subscribeToExistingTracks(p, false)
connectTime := time.Since(p.ConnectedAt())
meta := &livekit.AnalyticsClientMeta{
ClientConnectTime: uint32(connectTime.Milliseconds()),
}
infos := p.GetICEConnectionInfo()
var connectionType roomobs.ConnectionType
for _, info := range infos {
if info.Type != types.ICEConnectionTypeUnknown {
meta.ConnectionType = info.Type.String()
connectionType = info.Type.ReporterType()
break
}
}
r.telemetry.ParticipantActive(context.Background(),
r.ToProto(),
p.ToProto(),
meta,
false,
)
participant.GetReporter().Tx(func(tx roomobs.ParticipantSessionTx) {
tx.ReportClientConnectTime(uint16(connectTime.Milliseconds()))
tx.ReportConnectResult(roomobs.ConnectionResultSuccess)
tx.ReportConnectionType(connectionType)
})
fields := append(
connectionDetailsFields(infos),
"clientInfo", logger.Proto(sutils.ClientInfoWithoutAddress(p.GetClientInfo())),
)
p.GetLogger().Infow("participant active", fields...)
} else if state == livekit.ParticipantInfo_DISCONNECTED {
// remove participant from room
go r.RemoveParticipant(p.Identity(), p.ID(), p.CloseReason())
}
})
participant.OnSubscriberReady(func(p types.LocalParticipant) {
r.subscribeToExistingTracks(p, false)
})
// it's important to set this before connection, we don't want to miss out on any published tracks
participant.OnTrackPublished(r.onTrackPublished)
participant.OnTrackUpdated(r.onTrackUpdated)
participant.OnTrackUnpublished(r.onTrackUnpublished)
participant.OnParticipantUpdate(r.onParticipantUpdate)
participant.OnDataPacket(r.onDataPacket)
participant.OnDataMessage(r.onDataMessage)
participant.OnMetrics(r.onMetrics)
participant.OnSubscribeStatusChanged(func(publisherID livekit.ParticipantID, subscribed bool) {
if subscribed {
pub := r.GetParticipantByID(publisherID)
if pub != nil && pub.State() == livekit.ParticipantInfo_ACTIVE {
// when a participant subscribes to another participant,
// send speaker update if the subscribed to participant is active.
level, active := pub.GetAudioLevel()
if active {
_ = participant.SendSpeakerUpdate([]*livekit.SpeakerInfo{
{
Sid: string(pub.ID()),
Level: float32(level),
Active: active,
},
}, false)
}
if cq := pub.GetConnectionQuality(); cq != nil {
update := &livekit.ConnectionQualityUpdate{}
update.Updates = append(update.Updates, cq)
_ = participant.SendConnectionQualityUpdate(update)
}
}
} else {
// no longer subscribed to the publisher, clear speaker status
_ = participant.SendSpeakerUpdate([]*livekit.SpeakerInfo{
{
Sid: string(publisherID),
Level: 0,
Active: false,
},
}, true)
}
})
r.launchTargetAgents(maps.Values(r.agentDispatches), participant, livekit.JobType_JT_PARTICIPANT)
r.logger.Debugw(
"new participant joined",
"pID", participant.ID(),
"participant", participant.Identity(),
"clientInfo", logger.Proto(participant.GetClientInfo()),
"options", opts,
"numParticipants", len(r.participants),
)
if participant.IsRecorder() && !r.protoRoom.ActiveRecording {
r.protoRoom.ActiveRecording = true
r.protoProxy.MarkDirty(true)
} else {
r.protoProxy.MarkDirty(false)
}
r.participants[participant.Identity()] = participant
r.participantOpts[participant.Identity()] = opts
if r.onParticipantChanged != nil {
r.onParticipantChanged(participant)
}
time.AfterFunc(time.Minute, func() {
if !participant.Verify() {
r.RemoveParticipant(participant.Identity(), participant.ID(), types.ParticipantCloseReasonJoinTimeout)
}
})
connectResponse := r.createConnectResponseLocked(participant, iceServers)
participant.SetMigrateState(types.MigrateStateComplete)
return connectResponse, nil
}()
if err != nil {
return connectResponse, err
}
// SIGNALLING-V2-TODO
// 1. process published audio_tracks
// 2. process published video_tracks
// 3. HandleOffer and get answer (publisher)
r.subscribeToExistingTracks(participant, true)
offer, 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
}
connectResponse.SubscriberSdp = ToProtoSessionDescription(offer, 0) // SIGNALLING-V2-TODO - need to proper offerId?
prometheus.ServiceOperationCounter.WithLabelValues("participant_join", "success", "").Add(1)
return connectResponse, nil
}
func (r *Room) ReplaceParticipantRequestSource(identity livekit.ParticipantIdentity, reqSource routing.MessageSource) {
r.lock.Lock()
if rs, ok := r.participantRequestSources[identity]; ok {
@@ -790,7 +983,7 @@ func (r *Room) UpdateSubscriptions(
// handle subscription changes
for _, trackID := range trackIDs {
if subscribe {
participant.SubscribeToTrack(trackID)
participant.SubscribeToTrack(trackID, false)
} else {
participant.UnsubscribeFromTrack(trackID)
}
@@ -799,7 +992,7 @@ func (r *Room) UpdateSubscriptions(
for _, pt := range participantTracks {
for _, trackID := range livekit.StringsAsIDs[livekit.TrackID](pt.TrackSids) {
if subscribe {
participant.SubscribeToTrack(trackID)
participant.SubscribeToTrack(trackID, false)
} else {
participant.UnsubscribeFromTrack(trackID)
}
@@ -1193,6 +1386,30 @@ func (r *Room) createJoinResponseLocked(participant types.LocalParticipant, iceS
}
}
func (r *Room) createConnectResponseLocked(
participant types.LocalParticipant,
iceServers []*livekit.ICEServer,
) *livekit.ConnectResponse {
iceConfig := participant.GetICEConfig()
hasICEFallback := iceConfig.GetPreferencePublisher() != livekit.ICECandidateType_ICT_NONE || iceConfig.GetPreferenceSubscriber() != livekit.ICECandidateType_ICT_NONE
return &livekit.ConnectResponse{
Room: r.ToProto(),
Participant: participant.ToProto(),
OtherParticipants: GetOtherParticipantInfo(
participant,
false, // isMigratingIn
toParticipants(maps.Values(r.participants)),
false, // skipSubscriberBroadcast
),
IceServers: iceServers,
ClientConfiguration: participant.GetClientConfiguration(),
ServerInfo: r.serverInfo,
SifTrailer: r.trailer,
EnabledPublishCodecs: participant.GetEnabledPublishCodecs(),
FastPublish: participant.CanPublish() && !hasICEFallback,
}
}
// a ParticipantImpl in the room added a new track, subscribe other participants to it
func (r *Room) onTrackPublished(participant types.LocalParticipant, track types.MediaTrack) {
// publish participant update, since track state is changed
@@ -1213,13 +1430,14 @@ func (r *Room) onTrackPublished(participant types.LocalParticipant, track types.
continue
}
r.logger.Debugw("subscribing to new track",
r.logger.Debugw(
"subscribing to new track",
"participant", existingParticipant.Identity(),
"pID", existingParticipant.ID(),
"publisher", participant.Identity(),
"publisherID", participant.ID(),
"trackID", track.ID())
existingParticipant.SubscribeToTrack(track.ID())
existingParticipant.SubscribeToTrack(track.ID(), false)
}
onParticipantChanged := r.onParticipantChanged
r.lock.RUnlock()
@@ -1307,7 +1525,7 @@ func (r *Room) onDataPacket(source types.LocalParticipant, kind livekit.DataPack
r.logger.Errorw("failed to marshal data packet for cache", err, "participant", source.Identity(), "seq", dp.GetSequence())
return
}
r.dataMessagecache.Add(&types.DataMessageCache{
r.dataMessageCache.Add(&types.DataMessageCache{
SenderID: source.ID(),
Seq: dp.GetSequence(),
Data: data,
@@ -1325,7 +1543,7 @@ func (r *Room) onMetrics(source types.Participant, dp *livekit.DataPacket) {
BroadcastMetricsForRoom(r, source, dp, r.logger)
}
func (r *Room) subscribeToExistingTracks(p types.LocalParticipant) {
func (r *Room) subscribeToExistingTracks(p types.LocalParticipant, isSync bool) {
r.lock.RLock()
shouldSubscribe := r.autoSubscribe(p)
r.lock.RUnlock()
@@ -1343,7 +1561,7 @@ func (r *Room) subscribeToExistingTracks(p types.LocalParticipant) {
// subscribe to all
for _, track := range op.GetPublishedTracks() {
trackIDs = append(trackIDs, track.ID())
p.SubscribeToTrack(track.ID())
p.SubscribeToTrack(track.ID(), isSync)
}
}
if len(trackIDs) > 0 {
@@ -1447,7 +1665,7 @@ func (r *Room) changeUpdateWorker() {
SendParticipantUpdates(maps.Values(updatesMap), r.GetParticipants())
case <-cleanDataMessageTicker.C:
r.dataMessagecache.Prune()
r.dataMessageCache.Prune()
}
}
}
@@ -1723,7 +1941,7 @@ func (r *Room) IsDataMessageUserPacketDuplicate(up *livekit.UserPacket) bool {
func (r *Room) GetCachedReliableDataMessage(seqs map[livekit.ParticipantID]uint32) []*types.DataMessageCache {
msgs := make([]*types.DataMessageCache, 0, len(seqs)*10)
for _, msg := range r.dataMessagecache.Get() {
for _, msg := range r.dataMessageCache.Get() {
seq, ok := seqs[msg.SenderID]
if ok && msg.Seq >= seq {
msgs = append(msgs, msg)