-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathroom.go
More file actions
1326 lines (1152 loc) · 39.5 KB
/
room.go
File metadata and controls
1326 lines (1152 loc) · 39.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package lksdk
import (
"cmp"
"context"
"fmt"
"maps"
"reflect"
"slices"
"strings"
"sync"
"time"
"github.com/pion/interceptor"
"github.com/pion/rtcp"
"github.com/pion/webrtc/v4"
"golang.org/x/mod/semver"
"google.golang.org/protobuf/proto"
protoLogger "github.com/livekit/protocol/logger"
protosignalling "github.com/livekit/protocol/signalling"
"github.com/livekit/server-sdk-go/v2/signalling"
"github.com/livekit/mediatransportutil/pkg/pacer"
"github.com/livekit/protocol/auth"
protoCodecs "github.com/livekit/protocol/codecs"
"github.com/livekit/protocol/livekit"
dtlsElliptic "github.com/pion/dtls/v3/pkg/crypto/elliptic"
)
var (
_ engineHandler = (*Room)(nil)
)
// -----------------------------------------------
type SimulateScenario int
const (
SimulateSignalReconnect SimulateScenario = iota
SimulateForceTCP
SimulateForceTLS
SimulateSpeakerUpdate
SimulateMigration
SimulateServerLeave
SimulateNodeFailure
)
type ConnectionState string
const (
ConnectionStateConnected ConnectionState = "connected"
ConnectionStateReconnecting ConnectionState = "reconnecting"
ConnectionStateDisconnected ConnectionState = "disconnected"
)
// -----------------------------------------------
const (
SimulateSpeakerUpdateInterval = 5
)
type (
TrackPubCallback func(track Track, pub TrackPublication, participant *RemoteParticipant)
PubCallback func(pub TrackPublication, participant *RemoteParticipant)
)
type ParticipantKind int
const (
ParticipantStandard = ParticipantKind(livekit.ParticipantInfo_STANDARD)
ParticipantIngress = ParticipantKind(livekit.ParticipantInfo_INGRESS)
ParticipantEgress = ParticipantKind(livekit.ParticipantInfo_EGRESS)
ParticipantSIP = ParticipantKind(livekit.ParticipantInfo_SIP)
ParticipantAgent = ParticipantKind(livekit.ParticipantInfo_AGENT)
ParticipantConnector = ParticipantKind(livekit.ParticipantInfo_CONNECTOR)
)
type ConnectInfo struct {
APIKey string
APISecret string
RoomName string
ParticipantName string
ParticipantIdentity string
ParticipantKind ParticipantKind
ParticipantMetadata string
ParticipantAttributes map[string]string
}
type ConnectOption func(*signalling.ConnectParams)
func WithConnectTimeout(timeout time.Duration) ConnectOption {
return func(p *signalling.ConnectParams) {
p.ConnectTimeout = timeout
}
}
// WithAutoSubscribe sets whether the participant should automatically subscribe to tracks.
// Default is true.
func WithAutoSubscribe(val bool) ConnectOption {
return func(p *signalling.ConnectParams) {
p.AutoSubscribe = val
}
}
// WithRetransmitBufferSize sets the retransmit buffer size to respond to NACK requests.
// Must be one of: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768.
func WithRetransmitBufferSize(val uint16) ConnectOption {
return func(p *signalling.ConnectParams) {
p.RetransmitBufferSize = val
}
}
// WithPacer enables the use of a pacer on this connection
// A pacer helps to smooth out video packet rate to avoid overwhelming downstream. Learn more at: https://chromium.googlesource.com/external/webrtc/+/master/modules/pacing/g3doc/index.md
func WithPacer(pacer pacer.Factory) ConnectOption {
return func(p *signalling.ConnectParams) {
p.Pacer = pacer
}
}
// WithInterceptors sets custom RTP interceptors for the connection.
func WithInterceptors(interceptors []interceptor.Factory) ConnectOption {
return func(p *signalling.ConnectParams) {
p.Interceptors = interceptors
}
}
// WithIncludeDefaultInterceptors sets whether to register default interceptors
// along with custom interceptors.
func WithIncludeDefaultInterceptors(include bool) ConnectOption {
return func(p *signalling.ConnectParams) {
p.IncludeDefaultInterceptors = include
}
}
// WithICETransportPolicy sets the ICE transport policy (UDP, Relay, etc.).
func WithICETransportPolicy(iceTransportPolicy webrtc.ICETransportPolicy) ConnectOption {
return func(p *signalling.ConnectParams) {
p.ICETransportPolicy = iceTransportPolicy
}
}
// WithDisableRegionDiscovery disables automatic region discovery for LiveKit Cloud.
func WithDisableRegionDiscovery() ConnectOption {
return func(p *signalling.ConnectParams) {
p.DisableRegionDiscovery = true
}
}
// WithMetadata sets custom metadata for the participant.
func WithMetadata(metadata string) ConnectOption {
return func(p *signalling.ConnectParams) {
p.Metadata = metadata
}
}
// WithExtraAttributes sets additional key-value attributes for the participant.
// Empty string values will be ignored.
func WithExtraAttributes(attrs map[string]string) ConnectOption {
return func(p *signalling.ConnectParams) {
if len(attrs) != 0 && p.Attributes == nil {
p.Attributes = make(map[string]string, len(attrs))
}
for k, v := range attrs {
if v == "" {
continue
}
p.Attributes[k] = v
}
}
}
func WithCodecs(codecs []livekit.Codec) ConnectOption {
return func(p *signalling.ConnectParams) {
pCodecs := make([]webrtc.RTPCodecParameters, 0, len(codecs))
for i := range codecs {
pCodecs = append(pCodecs, protoCodecs.ToWebrtcCodecParameters(&codecs[i]))
}
p.Codecs = pCodecs
}
}
// WithDTLSEllipticCurves configures the DTLS elliptic curves used for key exchange.
// Use this on FIPS 140-enabled systems to specify NIST-approved curves (e.g. P-256, P-384)
// instead of the default X25519.
func WithDTLSEllipticCurves(curves ...dtlsElliptic.Curve) ConnectOption {
return func(p *signalling.ConnectParams) {
p.DTLSEllipticCurves = curves
}
}
func WithLogger(l protoLogger.Logger) ConnectOption {
return func(p *signalling.ConnectParams) {
p.Logger = l
}
}
type PLIWriter func(webrtc.SSRC)
type Room struct {
log protoLogger.Logger
useSinglePeerConnection bool
engine *RTCEngine
sid string
name string
LocalParticipant *LocalParticipant
callback *RoomCallback
connectionState ConnectionState
sidReady chan struct{}
remoteParticipants map[livekit.ParticipantIdentity]*RemoteParticipant
sidToIdentity map[livekit.ParticipantID]livekit.ParticipantIdentity
sidDefers map[livekit.ParticipantID]map[livekit.TrackID]func(p *RemoteParticipant)
metadata string
activeRecording bool
activeSpeakers []Participant
serverInfo *livekit.ServerInfo
regionURLProvider *regionURLProvider
sifTrailer []byte
byteStreamHandlers *sync.Map
byteStreamReaders *sync.Map
textStreamHandlers *sync.Map
textStreamReaders *sync.Map
rpcHandlers *sync.Map
lock sync.RWMutex
}
// NewRoom can be used to update callbacks before calling Join
func NewRoom(callback *RoomCallback) *Room {
r := &Room{
log: logger,
useSinglePeerConnection: semver.Compare("v"+Version, "v3.0.0") >= 0,
remoteParticipants: make(map[livekit.ParticipantIdentity]*RemoteParticipant),
sidToIdentity: make(map[livekit.ParticipantID]livekit.ParticipantIdentity),
sidDefers: make(map[livekit.ParticipantID]map[livekit.TrackID]func(*RemoteParticipant)),
callback: NewRoomCallback(),
sidReady: make(chan struct{}),
connectionState: ConnectionStateDisconnected,
regionURLProvider: newRegionURLProvider(),
byteStreamHandlers: &sync.Map{},
byteStreamReaders: &sync.Map{},
textStreamHandlers: &sync.Map{},
textStreamReaders: &sync.Map{},
rpcHandlers: &sync.Map{},
}
r.callback.Merge(callback)
r.engine = NewRTCEngine(r.useSinglePeerConnection, r, r.getLocalParticipantSID)
r.LocalParticipant = newLocalParticipant(r.engine, r.callback, r.serverInfo, r.log)
return r
}
// ConnectToRoom creates and joins the room
func ConnectToRoom(url string, info ConnectInfo, callback *RoomCallback, opts ...ConnectOption) (*Room, error) {
room := NewRoom(callback)
err := room.Join(url, info, opts...)
if err != nil {
return nil, err
}
return room, nil
}
// ConnectToRoomWithToken creates and joins the room
func ConnectToRoomWithToken(url, token string, callback *RoomCallback, opts ...ConnectOption) (*Room, error) {
room := NewRoom(callback)
err := room.JoinWithToken(url, token, opts...)
if err != nil {
return nil, err
}
return room, nil
}
// SetLogger overrides default logger.
func (r *Room) SetLogger(l protoLogger.Logger) {
r.log = l
r.engine.SetLogger(l)
r.LocalParticipant.SetLogger(l)
r.lock.RLock()
for _, rp := range r.remoteParticipants {
rp.SetLogger(l)
}
r.lock.RUnlock()
}
func (r *Room) Name() string {
r.lock.RLock()
defer r.lock.RUnlock()
return r.name
}
// SID returns the unique session ID of the room.
// This will block until session ID is available, which could take up to 2s after joining the room.
func (r *Room) SID() string {
<-r.sidReady
r.lock.RLock()
defer r.lock.RUnlock()
return r.sid
}
// PrepareConnection - with LiveKit Cloud, determine the best edge data center for the current client to connect to
func (r *Room) PrepareConnection(url, token string) error {
cloudHostname, _ := parseCloudURL(url)
if cloudHostname == "" {
return nil
}
return r.regionURLProvider.RefreshRegionSettings(cloudHostname, token)
}
// Join - joins the room with default permissions
func (r *Room) Join(url string, info ConnectInfo, opts ...ConnectOption) error {
return r.JoinWithContext(context.Background(), url, info, opts...)
}
// JoinWithContext - like Join, but accepts a context for cancellation/deadline.
func (r *Room) JoinWithContext(ctx context.Context, url string, info ConnectInfo, opts ...ConnectOption) error {
var params signalling.ConnectParams
for _, opt := range opts {
opt(¶ms)
}
// generate token
at := auth.NewAccessToken(info.APIKey, info.APISecret)
grant := &auth.VideoGrant{
RoomJoin: true,
Room: info.RoomName,
}
at.SetVideoGrant(grant).
SetIdentity(info.ParticipantIdentity).
SetMetadata(info.ParticipantMetadata).
SetAttributes(info.ParticipantAttributes).
SetName(info.ParticipantName).
SetKind(livekit.ParticipantInfo_Kind(info.ParticipantKind))
token, err := at.ToJWT()
if err != nil {
return err
}
return r.JoinWithContextAndToken(ctx, url, token, opts...)
}
// JoinWithToken - customize participant options by generating your own token
func (r *Room) JoinWithToken(url, token string, opts ...ConnectOption) error {
return r.JoinWithContextAndToken(context.Background(), url, token, opts...)
}
// JoinWithContextAndToken - like JoinWithToken, but accepts a context for cancellation/deadline.
func (r *Room) JoinWithContextAndToken(ctx context.Context, url, token string, opts ...ConnectOption) error {
params := &signalling.ConnectParams{
AutoSubscribe: true,
ConnectTimeout: 3 * time.Second,
}
for _, opt := range opts {
opt(params)
}
if params.Logger != nil {
r.SetLogger(params.Logger)
}
isSuccess := false
cloudHostname, _ := parseCloudURL(url)
if !params.DisableRegionDiscovery && cloudHostname != "" {
if err := r.regionURLProvider.RefreshRegionSettings(cloudHostname, token); err != nil {
r.log.Errorw("failed to get best url", err)
} else {
for tries := uint(0); !isSuccess; tries++ {
if ctx.Err() != nil {
return ctx.Err()
}
bestURL, err := r.regionURLProvider.PopBestURL(cloudHostname, token)
if err != nil {
r.log.Errorw("failed to get best url", err)
break
}
r.log.Debugw("RTC engine joining room", "url", bestURL, "connectTimeout", params.ConnectTimeout)
callCtx, cancelCallCtx := context.WithTimeout(ctx, params.ConnectTimeout)
isSuccess, err = r.engine.JoinContext(callCtx, bestURL, token, params)
cancelCallCtx()
if err != nil {
// try the next URL with exponential backoff
d := time.Duration(1<<min(tries, 6)) * 100 * time.Millisecond // max 6.4 seconds
r.log.Errorw(
"failed to join room", err,
"retrying in", d,
"url", bestURL,
)
select {
case <-time.After(d):
case <-ctx.Done():
return ctx.Err()
}
continue
}
}
}
}
if !isSuccess {
if _, err := r.engine.JoinContext(ctx, url, token, params); err != nil {
return err
}
}
return nil
}
// Disconnect leaves the room, indicating the client initiated the disconnect.
func (r *Room) Disconnect() {
r.DisconnectWithReason(livekit.DisconnectReason_CLIENT_INITIATED)
}
// DisconnectWithReason leaves the room with a specific disconnect reason.
func (r *Room) DisconnectWithReason(reason livekit.DisconnectReason) {
_ = r.engine.SendLeaveWithReason(reason)
r.cleanup()
}
// ConnectionState returns the current connection state of the room.
func (r *Room) ConnectionState() ConnectionState {
r.lock.RLock()
defer r.lock.RUnlock()
return r.connectionState
}
func (r *Room) setConnectionState(cs ConnectionState) {
r.lock.Lock()
r.connectionState = cs
r.lock.Unlock()
}
func (r *Room) deferParticipantUpdate(sid livekit.ParticipantID, trackID livekit.TrackID, fnc func(p *RemoteParticipant)) {
r.lock.Lock()
defer r.lock.Unlock()
if r.sidDefers[sid] == nil {
r.sidDefers[sid] = make(map[livekit.TrackID]func(p *RemoteParticipant))
}
r.sidDefers[sid][trackID] = fnc
}
func (r *Room) runParticipantDefers(sid livekit.ParticipantID, p *RemoteParticipant) {
r.lock.Lock()
fncs := r.sidDefers[sid]
delete(r.sidDefers, sid)
r.lock.Unlock()
if len(fncs) != 0 {
r.log.Infow(
"running deferred updates for participant",
"participant", p.Identity(),
"participantID", sid,
"numUpdates", len(fncs),
)
for _, fnc := range fncs {
fnc(p)
}
}
}
func (r *Room) clearParticipantDefers(sid livekit.ParticipantID, pi *livekit.ParticipantInfo) {
r.lock.Lock()
defer r.lock.Unlock()
for trackID := range r.sidDefers[sid] {
found := false
for _, ti := range pi.Tracks {
if livekit.TrackID(ti.GetSid()) == trackID {
found = true
break
}
}
if !found {
r.log.Infow(
"deleting deferred update for participant",
"participant", pi.Identity,
"participantID", sid,
"trackID", trackID,
)
delete(r.sidDefers[sid], trackID)
if len(r.sidDefers[sid]) == 0 {
delete(r.sidDefers, sid)
}
}
}
}
// GetParticipantByIdentity returns a remote participant by their identity.
// Returns nil if not found.
// Note: this represents the current view from the local participant's perspective
func (r *Room) GetParticipantByIdentity(identity string) *RemoteParticipant {
r.lock.RLock()
defer r.lock.RUnlock()
return r.remoteParticipants[livekit.ParticipantIdentity(identity)]
}
// GetParticipantBySID returns a remote participant by their session ID.
// Returns nil if not found.
// Note: this represents the current view from the local participant's perspective
func (r *Room) GetParticipantBySID(sid string) *RemoteParticipant {
r.lock.RLock()
defer r.lock.RUnlock()
if identity, ok := r.sidToIdentity[livekit.ParticipantID(sid)]; ok {
return r.remoteParticipants[identity]
}
return nil
}
// GetRemoteParticipants returns all remote participants in the room as seen by the local participant
// Note: this does not represent the exact state from the server's view. To get all participants that
// exists on the server, use [RoomServiceClient.ListParticipants] instead.
func (r *Room) GetRemoteParticipants() []*RemoteParticipant {
r.lock.RLock()
defer r.lock.RUnlock()
var participants []*RemoteParticipant
for _, rp := range r.remoteParticipants {
participants = append(participants, rp)
}
return participants
}
// ActiveSpeakers returns a list of currently active speakers.
// Speakers are ordered by audio level (loudest first).
func (r *Room) ActiveSpeakers() []Participant {
r.lock.RLock()
defer r.lock.RUnlock()
return r.activeSpeakers
}
func (r *Room) Metadata() string {
r.lock.RLock()
defer r.lock.RUnlock()
return r.metadata
}
// IsRecording returns true if the room is currently being recorded.
func (r *Room) IsRecording() bool {
r.lock.RLock()
defer r.lock.RUnlock()
return r.activeRecording
}
// ServerInfo returns information about the LiveKit server.
func (r *Room) ServerInfo() *livekit.ServerInfo {
r.lock.RLock()
defer r.lock.RUnlock()
return proto.Clone(r.serverInfo).(*livekit.ServerInfo)
}
// SifTrailer returns the SIF (Server Injected Frames) trailer data used by E2EE
func (r *Room) SifTrailer() []byte {
r.lock.RLock()
defer r.lock.RUnlock()
trailer := make([]byte, len(r.sifTrailer))
copy(trailer, r.sifTrailer)
return trailer
}
func (r *Room) addRemoteParticipant(pi *livekit.ParticipantInfo, updateExisting bool) *RemoteParticipant {
r.lock.Lock()
defer r.lock.Unlock()
rp, ok := r.remoteParticipants[livekit.ParticipantIdentity(pi.Identity)]
if ok {
if updateExisting {
rp.updateInfo(pi)
r.sidToIdentity[livekit.ParticipantID(pi.Sid)] = livekit.ParticipantIdentity(pi.Identity)
}
return rp
}
rp = newRemoteParticipant(pi, r.callback, r.engine, func(ssrc webrtc.SSRC) {
pli := []rtcp.Packet{
&rtcp.PictureLossIndication{SenderSSRC: uint32(ssrc), MediaSSRC: uint32(ssrc)},
}
if subscriber, ok := r.engine.Subscriber(); ok {
_ = subscriber.pc.WriteRTCP(pli)
}
}, r.log.WithValues("participant", pi.Identity))
r.remoteParticipants[livekit.ParticipantIdentity(pi.Identity)] = rp
r.sidToIdentity[livekit.ParticipantID(pi.Sid)] = livekit.ParticipantIdentity(pi.Identity)
return rp
}
func (r *Room) sendSyncState() {
var previousOffer *webrtc.SessionDescription
var previousAnswer *webrtc.SessionDescription
if r.useSinglePeerConnection {
publisher, ok := r.engine.Publisher()
if ok {
previousOffer = publisher.pc.RemoteDescription()
previousAnswer = publisher.pc.LocalDescription()
}
} else {
subscriber, ok := r.engine.Subscriber()
if ok {
previousOffer = subscriber.pc.RemoteDescription()
previousAnswer = subscriber.pc.LocalDescription()
}
}
if previousOffer == nil || previousAnswer == nil {
return
}
var trackSids []string
var trackSidsDisabled []string
sendUnsub := r.engine.connParams.AutoSubscribe
for _, rp := range r.GetRemoteParticipants() {
for _, t := range rp.TrackPublications() {
if t.IsSubscribed() != sendUnsub {
trackSids = append(trackSids, t.SID())
}
if rpub, ok := t.(*RemoteTrackPublication); ok {
if !rpub.IsEnabled() {
trackSidsDisabled = append(trackSidsDisabled, t.SID())
}
}
}
}
var publishedTracks []*livekit.TrackPublishedResponse
for _, t := range r.LocalParticipant.TrackPublications() {
if t.Track() != nil {
publishedTracks = append(publishedTracks, &livekit.TrackPublishedResponse{
Cid: t.Track().ID(),
Track: t.TrackInfo(),
})
}
}
var dataChannels []*livekit.DataChannelInfo
getDCinfo := func(dc *webrtc.DataChannel, target livekit.SignalTarget) {
if dc != nil && dc.ID() != nil {
dataChannels = append(dataChannels, &livekit.DataChannelInfo{
Label: dc.Label(),
Id: uint32(*dc.ID()),
Target: target,
})
}
}
getDCinfo(r.engine.GetDataChannel(livekit.DataPacket_RELIABLE), livekit.SignalTarget_PUBLISHER)
getDCinfo(r.engine.GetDataChannel(livekit.DataPacket_LOSSY), livekit.SignalTarget_PUBLISHER)
getDCinfo(r.engine.GetDataChannelSub(livekit.DataPacket_RELIABLE), livekit.SignalTarget_SUBSCRIBER)
getDCinfo(r.engine.GetDataChannelSub(livekit.DataPacket_LOSSY), livekit.SignalTarget_SUBSCRIBER)
r.engine.SendSyncState(&livekit.SyncState{
Offer: protosignalling.ToProtoSessionDescription(*previousOffer, 0, nil),
Answer: protosignalling.ToProtoSessionDescription(*previousAnswer, 0, nil),
Subscription: &livekit.UpdateSubscription{
TrackSids: trackSids,
Subscribe: !sendUnsub,
},
PublishTracks: publishedTracks,
DataChannels: dataChannels,
TrackSidsDisabled: trackSidsDisabled,
// MIGRATION-TODO DatachannelReceiveStates
})
}
func (r *Room) cleanup() {
r.setConnectionState(ConnectionStateDisconnected)
r.engine.Close()
r.LocalParticipant.closeTracks()
r.setSid("", true)
r.byteStreamHandlers.Clear()
r.byteStreamReaders.Range(func(key, value any) bool {
if reader, ok := value.(*ByteStreamReader); ok {
reader.close()
}
return true
})
r.byteStreamReaders.Clear()
r.textStreamHandlers.Clear()
r.textStreamReaders.Range(func(key, value any) bool {
if reader, ok := value.(*TextStreamReader); ok {
reader.close()
}
return true
})
r.textStreamReaders.Clear()
r.rpcHandlers.Clear()
r.LocalParticipant.cleanup()
}
func (r *Room) setSid(sid string, allowEmpty bool) {
r.lock.Lock()
if sid != "" || allowEmpty {
select {
case <-r.sidReady:
// already closed
default:
r.sid = sid
close(r.sidReady)
}
}
r.lock.Unlock()
}
// Simulate triggers various test scenarios for debugging and testing purposes.
// This is primarily used for development and testing.
func (r *Room) Simulate(scenario SimulateScenario) {
r.engine.Simulate(scenario)
}
func (r *Room) getLocalParticipantSID() string {
if r.LocalParticipant != nil {
return r.LocalParticipant.SID()
}
return ""
}
// Establishes the participant as a receiver for calls of the specified RPC method.
// Will overwrite any existing callback for the same method.
//
// - @param method - The name of the indicated RPC method
// - @param handler - Will be invoked when an RPC request for this method is received
// - @returns A promise that resolves when the method is successfully registered
//
// Example:
//
// room.LocalParticipant?.registerRpcMethod(
// "greet",
// func (data: RpcInvocationData) => {
// fmt.Println("Received greeting from ", data.callerIdentity, "with payload ", data.payload)
// return "Hello, " + data.callerIdentity + "!";
// }
// );
//
// The handler should return either a string or an error.
// If unable to respond within `responseTimeout`, the request will result in an error on the caller's side.
//
// You may throw errors of type `RpcError` with a string `message` in the handler,
// and they will be received on the caller's side with the message intact.
// Other errors thrown in your handler will not be transmitted as-is, and will instead arrive to the caller as `1500` ("Application Error").
func (r *Room) RegisterRpcMethod(method string, handler RpcHandlerFunc) error {
if _, loaded := r.rpcHandlers.LoadOrStore(method, handler); loaded {
return fmt.Errorf("rpc handler already registered for method: %s, unregisterRpcMethod before trying to register again", method)
}
return nil
}
// UnregisterRpcMethod unregisters a previously registered RPC method.
func (r *Room) UnregisterRpcMethod(method string) {
r.rpcHandlers.Delete(method)
}
// RegisterTextStreamHandler registers a handler for incoming text streams on a specific topic.
// The handler will be called when a text stream is received for the given topic.
// It returns an error if a handler is already registered for this topic.
func (r *Room) RegisterTextStreamHandler(topic string, handler TextStreamHandler) error {
if _, loaded := r.textStreamHandlers.LoadOrStore(topic, handler); loaded {
return fmt.Errorf("text stream handler already registered for topic: %s", topic)
}
return nil
}
// UnregisterTextStreamHandler removes a previously registered text stream handler.
func (r *Room) UnregisterTextStreamHandler(topic string) {
r.textStreamHandlers.Delete(topic)
}
// RegisterByteStreamHandler registers a handler for incoming byte streams on a specific topic.
// The handler will be called when a byte stream is received for the given topic.
// It returns an error if a handler is already registered for this topic.
func (r *Room) RegisterByteStreamHandler(topic string, handler ByteStreamHandler) error {
if _, loaded := r.byteStreamHandlers.LoadOrStore(topic, handler); loaded {
return fmt.Errorf("byte stream handler already registered for topic: %s", topic)
}
return nil
}
// UnregisterByteStreamHandler removes a previously registered byte stream handler.
func (r *Room) UnregisterByteStreamHandler(topic string) {
r.byteStreamHandlers.Delete(topic)
}
// engineHandler implementation
func (r *Room) OnMediaTrack(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
// ensure we have the participant
participantID, streamID := unpackStreamID(track.StreamID())
trackID := track.ID()
if strings.HasPrefix(streamID, "TR_") {
// backwards compatibility
trackID = streamID
}
update := func(p *RemoteParticipant) {
p.addSubscribedMediaTrack(track, trackID, receiver)
}
rp := r.GetParticipantBySID(participantID)
if rp == nil {
r.log.Infow(
"could not find participant, deferring track update",
"participantID", participantID,
"trackID", trackID,
"streamID", streamID,
)
r.deferParticipantUpdate(livekit.ParticipantID(participantID), livekit.TrackID(trackID), update)
return
}
update(rp)
r.runParticipantDefers(livekit.ParticipantID(participantID), rp)
}
func (r *Room) OnRoomJoined(
room *livekit.Room,
participant *livekit.ParticipantInfo,
otherParticipants []*livekit.ParticipantInfo,
serverInfo *livekit.ServerInfo,
sifTrailer []byte,
) {
r.lock.Lock()
r.name = room.Name
r.metadata = room.Metadata
r.activeRecording = room.ActiveRecording
r.serverInfo = serverInfo
r.connectionState = ConnectionStateConnected
r.sifTrailer = make([]byte, len(sifTrailer))
copy(r.sifTrailer, sifTrailer)
r.lock.Unlock()
r.setSid(room.Sid, false)
r.LocalParticipant.updateInfo(participant)
r.LocalParticipant.updateSubscriptionPermission()
for _, pi := range otherParticipants {
r.addRemoteParticipant(pi, true)
r.clearParticipantDefers(livekit.ParticipantID(pi.Sid), pi)
// no need to run participant defers here, since we are connected for the first time
}
}
func (r *Room) OnDisconnected(reason DisconnectionReason) {
r.callback.OnDisconnected()
r.callback.OnDisconnectedWithReason(reason)
r.cleanup()
}
func (r *Room) OnRestarting() {
r.setConnectionState(ConnectionStateReconnecting)
r.callback.OnReconnecting()
for _, rp := range r.GetRemoteParticipants() {
r.OnParticipantDisconnect(rp, livekit.DisconnectReason_UNKNOWN_REASON)
}
}
func (r *Room) OnRestarted(
room *livekit.Room,
participant *livekit.ParticipantInfo,
otherParticipants []*livekit.ParticipantInfo,
) {
r.OnRoomUpdate(room)
r.LocalParticipant.updateInfo(participant)
r.LocalParticipant.updateSubscriptionPermission()
r.OnParticipantUpdate(otherParticipants)
r.LocalParticipant.republishTracks()
r.setConnectionState(ConnectionStateConnected)
r.callback.OnReconnected()
}
func (r *Room) OnResuming() {
r.setConnectionState(ConnectionStateReconnecting)
r.callback.OnReconnecting()
}
func (r *Room) OnResumed() {
r.setConnectionState(ConnectionStateConnected)
r.callback.OnReconnected()
r.sendSyncState()
r.LocalParticipant.updateSubscriptionPermission()
}
func (r *Room) OnDataPacket(identity string, dataPacket DataPacket) {
if identity == r.LocalParticipant.Identity() {
// if sent by itself, do not handle data
return
}
p := r.GetParticipantByIdentity(identity)
params := DataReceiveParams{
SenderIdentity: identity,
Sender: p,
}
switch msg := dataPacket.(type) {
case *UserDataPacket: // compatibility
params.Topic = msg.Topic
if p != nil {
p.Callback.OnDataReceived(msg.Payload, params)
}
r.callback.OnDataReceived(msg.Payload, params)
}
if p != nil {
p.Callback.OnDataPacket(dataPacket, params)
}
r.callback.OnDataPacket(dataPacket, params)
}
func (r *Room) OnParticipantUpdate(participants []*livekit.ParticipantInfo) {
for _, pi := range participants {
if pi.Sid == r.LocalParticipant.SID() || pi.Identity == r.LocalParticipant.Identity() {
r.LocalParticipant.updateInfo(pi)
continue
}
rp := r.GetParticipantByIdentity(pi.Identity)
isNew := rp == nil
if pi.State == livekit.ParticipantInfo_DISCONNECTED {
r.OnParticipantDisconnect(rp, pi.GetDisconnectReason())
} else if isNew {
rp = r.addRemoteParticipant(pi, true)
r.clearParticipantDefers(livekit.ParticipantID(pi.Sid), pi)
r.runParticipantDefers(livekit.ParticipantID(pi.Sid), rp)
go r.callback.OnParticipantConnected(rp)
} else {
oldSid := livekit.ParticipantID(rp.SID())
rp.updateInfo(pi)
newSid := livekit.ParticipantID(rp.SID())
if oldSid != newSid {
r.log.Infow(
"participant sid update",
"participant", rp.Identity(),
"sid-old", oldSid,
"sid-new", newSid,
)
r.lock.Lock()
delete(r.sidDefers, oldSid)
delete(r.sidToIdentity, oldSid)
r.sidToIdentity[newSid] = livekit.ParticipantIdentity(rp.Identity())
r.lock.Unlock()
}
r.clearParticipantDefers(livekit.ParticipantID(pi.Sid), pi)
r.runParticipantDefers(newSid, rp)
}
}
}
func (r *Room) OnParticipantDisconnect(rp *RemoteParticipant, reason livekit.DisconnectReason) {
if rp == nil {
return
}
r.lock.Lock()
delete(r.remoteParticipants, livekit.ParticipantIdentity(rp.Identity()))
delete(r.sidToIdentity, livekit.ParticipantID(rp.SID()))
delete(r.sidDefers, livekit.ParticipantID(rp.SID()))
r.lock.Unlock()
rp.unpublishAllTracks()
r.LocalParticipant.handleParticipantDisconnected(rp.Identity())
rp.info.DisconnectReason = reason
go r.callback.OnParticipantDisconnected(rp)
}
func (r *Room) OnSpeakersChanged(speakerUpdates []*livekit.SpeakerInfo) {
speakerMap := make(map[string]Participant)
for _, p := range r.ActiveSpeakers() {
speakerMap[p.SID()] = p
}
for _, info := range speakerUpdates {
var participant Participant