-
Notifications
You must be signed in to change notification settings - Fork 9
/
client.go
1924 lines (1556 loc) · 57.2 KB
/
client.go
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
package sfu
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"regexp"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/inlivedev/sfu/pkg/interceptors/playoutdelay"
"github.com/inlivedev/sfu/pkg/interceptors/voiceactivedetector"
"github.com/inlivedev/sfu/pkg/networkmonitor"
"github.com/pion/interceptor"
"github.com/pion/interceptor/pkg/cc"
"github.com/pion/interceptor/pkg/gcc"
"github.com/pion/interceptor/pkg/nack"
"github.com/pion/interceptor/pkg/stats"
"github.com/pion/logging"
"github.com/pion/rtcp"
"github.com/pion/webrtc/v4"
)
type ClientState int
type ClientType string
const (
ClientStateNew = 0
ClientStateActive = 1
ClientStateRestart = 2
ClientStateEnded = 3
ClientTypePeer = "peer"
ClientTypeUpBridge = "upbridge"
ClientTypeDownBridge = "downbridge"
QualityAudioRed = 11
QualityAudio = 10
QualityHigh = 9
QualityHighMid = 8
QualityHighLow = 7
QualityMid = 6
QualityMidMid = 5
QualityMidLow = 4
QualityLow = 3
QualityLowMid = 2
QualityLowLow = 1
QualityNone = 0
messageTypeVideoSize = "video_size"
messageTypeStats = "stats"
messageTypeVADStarted = "vad_started"
messageTypeVADEnded = "vad_ended"
)
type QualityLevel uint32
var (
ErrNegotiationIsNotRequested = errors.New("client: error negotiation is called before requested")
ErrRenegotiationCallback = errors.New("client: error renegotiation callback is not set")
ErrClientStoped = errors.New("client: error client already stopped")
)
type ClientOptions struct {
IceTrickle bool `json:"ice_trickle"`
IdleTimeout time.Duration `json:"idle_timeout"`
Type string `json:"type"`
EnableVoiceDetection bool `json:"enable_voice_detection"`
EnablePlayoutDelay bool `json:"enable_playout_delay"`
EnableOpusDTX bool `json:"enable_opus_dtx"`
EnableOpusInbandFEC bool `json:"enable_opus_inband_fec"`
// Configure the minimum playout delay that will be used by the client
// Recommendation:
// 0 ms: Certain gaming scenarios (likely without audio) where we will want to play the frame as soon as possible. Also, for remote desktop without audio where rendering a frame asap makes sense
// 100/150/200 ms: These could be the max target latency for interactive streaming use cases depending on the actual application (gaming, remoting with audio, interactive scenarios)
// 400 ms: Application that want to ensure a network glitch has very little chance of causing a freeze can start with a minimum delay target that is high enough to deal with network issues. Video streaming is one example.
MinPlayoutDelay uint16 `json:"min_playout_delay"`
// Configure the minimum playout delay that will be used by the client
// Recommendation:
// 0 ms: Certain gaming scenarios (likely without audio) where we will want to play the frame as soon as possible. Also, for remote desktop without audio where rendering a frame asap makes sense
// 100/150/200 ms: These could be the max target latency for interactive streaming use cases depending on the actual application (gaming, remoting with audio, interactive scenarios)
// 400 ms: Application that want to ensure a network glitch has very little chance of causing a freeze can start with a minimum delay target that is high enough to deal with network issues. Video streaming is one example.
MaxPlayoutDelay uint16 `json:"max_playout_delay"`
JitterBufferMinWait time.Duration `json:"jitter_buffer_min_wait"`
JitterBufferMaxWait time.Duration `json:"jitter_buffer_max_wait"`
// On unstable network, the packets can be arrived unordered which may affected the nack and packet loss counts, set this to true to allow the SFU to handle reordered packet
ReorderPackets bool `json:"reorder_packets"`
Log logging.LeveledLogger
settingEngine webrtc.SettingEngine
qualityLevels []QualityLevel
}
type internalDataMessage struct {
Type string `json:"type"`
Data interface{} `json:"data"`
}
type InternalDataVAD struct {
Type string `json:"type"`
Data voiceactivedetector.VoiceActivity `json:"data"`
}
type internalDataStats struct {
Type string `json:"type"`
Data remoteClientStats `json:"data"`
}
type internalDataVideoSize struct {
Type string `json:"type"`
Data videoSize `json:"data"`
}
type videoSize struct {
TrackID string `json:"track_id"`
Width uint32 `json:"width"`
Height uint32 `json:"height"`
}
type remoteClientStats struct {
AvailableOutgoingBitrate uint64 `json:"available_outgoing_bitrate"`
// this will be filled by the tracks stats
// possible value are "cpu","bandwidth","both","none"
QualityLimitationReason string `json:"quality_limitation_reason"`
}
type Client struct {
id string
name string
bitrateController *bitrateController
context context.Context
cancel context.CancelFunc
canAddCandidate *atomic.Bool
clientTracks map[string]iClientTrack
muTracks sync.Mutex
internalDataChannel *webrtc.DataChannel
dataChannels *DataChannelList
dataChannelsInitiated bool
estimator cc.BandwidthEstimator
initialReceiverCount atomic.Uint32
initialSenderCount atomic.Uint32
isInRenegotiation *atomic.Bool
isInRemoteNegotiation *atomic.Bool
idleTimeoutContext context.Context
idleTimeoutCancel context.CancelFunc
mu sync.Mutex
peerConnection *PeerConnection
// pending received tracks are the remote tracks from other clients that waiting to add when the client is connected
pendingReceivedTracks []SubscribeTrackRequest
// pending published tracks are the remote tracks that still state as unknown source, and can't be published until the client state the source media or screen
// the source can be set through client.SetTracksSourceType()
pendingPublishedTracks *trackList
// published tracks are the remote tracks from other clients that are published to this client
publishedTracks *trackList
pendingRemoteRenegotiation *atomic.Bool
receiveRED bool
state *atomic.Value
sfu *SFU
muCallback sync.Mutex
onConnectionStateChangedCallbacks []func(webrtc.PeerConnectionState)
onJoinedCallbacks []func()
onLeftCallbacks []func()
onVoiceSentDetectedCallbacks []func(voiceactivedetector.VoiceActivity)
onVoiceReceivedDetectedCallbacks []func(voiceactivedetector.VoiceActivity)
onTrackRemovedCallbacks []func(sourceType string, track *webrtc.TrackLocalStaticRTP)
onIceCandidate func(context.Context, *webrtc.ICECandidate)
onRenegotiation func(context.Context, webrtc.SessionDescription) (webrtc.SessionDescription, error)
onAllowedRemoteRenegotiation func()
onTracksAvailableCallbacks []func([]ITrack)
onTracksReadyCallbacks []func([]ITrack)
onNetworkConditionChangedFunc func(networkmonitor.NetworkConditionType)
// onTrack is used by SFU to take action when a new track is added to the client
onTrack func(ITrack)
onTracksAdded func([]ITrack)
options ClientOptions
statsGetter stats.Getter
stats *ClientStats
tracks *trackList
negotiationNeeded *atomic.Bool
pendingRemoteCandidates []webrtc.ICECandidateInit
pendingLocalCandidates []*webrtc.ICECandidate
quality *atomic.Uint32
receivingBandwidth *atomic.Uint32
egressBandwidth *atomic.Uint32
ingressBandwidth *atomic.Uint32
ingressQualityLimitationReason *atomic.Value
isDebug bool
vadInterceptor *voiceactivedetector.Interceptor
vads map[uint32]*voiceactivedetector.VoiceDetector
log logging.LeveledLogger
}
func DefaultClientOptions() ClientOptions {
return ClientOptions{
IceTrickle: true,
IdleTimeout: 5 * time.Minute,
Type: ClientTypePeer,
EnableVoiceDetection: true,
EnablePlayoutDelay: true,
EnableOpusDTX: true,
EnableOpusInbandFEC: true,
MinPlayoutDelay: 100,
MaxPlayoutDelay: 200,
JitterBufferMinWait: 20 * time.Millisecond,
JitterBufferMaxWait: 150 * time.Millisecond,
ReorderPackets: false,
Log: logging.NewDefaultLoggerFactory().NewLogger("sfu"),
}
}
func NewClient(s *SFU, id string, name string, peerConnectionConfig webrtc.Configuration, opts ClientOptions) *Client {
var client *Client
var vadInterceptor *voiceactivedetector.Interceptor
localCtx, cancel := context.WithCancel(s.context)
m := &webrtc.MediaEngine{}
if err := RegisterCodecs(m, s.codecs); err != nil {
panic(err)
}
// let the client knows that we're receiving simulcast tracks
RegisterSimulcastHeaderExtensions(m, webrtc.RTPCodecTypeVideo)
if opts.EnableVoiceDetection {
voiceactivedetector.RegisterAudioLevelHeaderExtension(m)
}
// // Create a InterceptorRegistry. This is the user configurable RTP/RTCP Pipeline.
// // This provides NACKs, RTCP Reports and other features. If you use `webrtc.NewPeerConnection`
// // this is enabled by default. If you are manually managing You MUST create a InterceptorRegistry
// // for each PeerConnection.
i := &interceptor.Registry{}
statsInterceptorFactory, err := stats.NewInterceptor()
if err != nil {
panic(err)
}
var statsGetter stats.Getter
statsInterceptorFactory.OnNewPeerConnection(func(_ string, g stats.Getter) {
statsGetter = g
})
i.Add(statsInterceptorFactory)
var vads = make(map[uint32]*voiceactivedetector.VoiceDetector)
if opts.EnableVoiceDetection {
opts.Log.Infof("client: voice detection is enabled")
vadInterceptorFactory := voiceactivedetector.NewInterceptor(localCtx, opts.Log)
// enable voice detector
vadInterceptorFactory.OnNew(func(i *voiceactivedetector.Interceptor) {
vadInterceptor = i
i.OnNewVAD(func(vad *voiceactivedetector.VoiceDetector) {
vads[vad.SSRC()] = vad
})
})
i.Add(vadInterceptorFactory)
}
estimatorChan := make(chan cc.BandwidthEstimator, 1)
// Create a Congestion Controller. This analyzes inbound and outbound data and provides
// suggestions on how much we should be sending.
//
// Passing `nil` means we use the default Estimation Algorithm which is Google Congestion Control.
// You can use the other ones that Pion provides, or write your own!
congestionController, err := cc.NewInterceptor(func() (cc.BandwidthEstimator, error) {
// if bw below 100_000, somehow the estimator will struggle to probe the bandwidth and will stuck there. So we set the min to 100_000
// TODO: we need to use packet loss based bandwidth adjuster when the bandwidth is below 100_000
return gcc.NewSendSideBWE(
gcc.SendSideBWEInitialBitrate(int(s.bitrateConfigs.InitialBandwidth)),
// gcc.SendSideBWEPacer(pacer.NewLeakyBucketPacer(opts.Log, int(s.bitrateConfigs.InitialBandwidth), true)),
gcc.SendSideBWEPacer(gcc.NewNoOpPacer()),
)
})
if err != nil {
panic(err)
}
congestionController.OnNewPeerConnection(func(id string, estimator cc.BandwidthEstimator) {
estimatorChan <- estimator
})
i.Add(congestionController)
if err = webrtc.ConfigureTWCCHeaderExtensionSender(m, i); err != nil {
panic(err)
}
if opts.EnablePlayoutDelay {
playoutdelay.RegisterPlayoutDelayHeaderExtension(m)
playoutDelayInterceptor := playoutdelay.NewInterceptor(opts.Log, opts.MinPlayoutDelay, opts.MaxPlayoutDelay)
i.Add(playoutDelayInterceptor)
}
// Use the default set of Interceptors
if err := registerInterceptors(m, i); err != nil {
panic(err)
}
// Create a new RTCPeerConnection
peerConnection, err := webrtc.NewAPI(webrtc.WithMediaEngine(m), webrtc.WithSettingEngine(opts.settingEngine), webrtc.WithInterceptorRegistry(i)).NewPeerConnection(peerConnectionConfig)
if err != nil {
panic(err)
}
var stateNew atomic.Value
stateNew.Store(ClientStateNew)
var quality atomic.Uint32
quality.Store(QualityHigh)
client = &Client{
id: id,
name: name,
context: localCtx,
cancel: cancel,
clientTracks: make(map[string]iClientTrack, 0),
canAddCandidate: &atomic.Bool{},
isInRenegotiation: &atomic.Bool{},
isInRemoteNegotiation: &atomic.Bool{},
dataChannels: NewDataChannelList(localCtx),
mu: sync.Mutex{},
negotiationNeeded: &atomic.Bool{},
peerConnection: newPeerConnection(peerConnection),
state: &stateNew,
tracks: newTrackList(opts.Log),
options: opts,
pendingReceivedTracks: make([]SubscribeTrackRequest, 0),
pendingPublishedTracks: newTrackList(opts.Log),
pendingRemoteRenegotiation: &atomic.Bool{},
publishedTracks: newTrackList(opts.Log),
sfu: s,
statsGetter: statsGetter,
quality: &quality,
receivingBandwidth: &atomic.Uint32{},
egressBandwidth: &atomic.Uint32{},
ingressBandwidth: &atomic.Uint32{},
ingressQualityLimitationReason: &atomic.Value{},
onTracksAvailableCallbacks: make([]func([]ITrack), 0),
vadInterceptor: vadInterceptor,
vads: vads,
log: opts.Log,
}
client.onTrack = func(track ITrack) {
if err := client.pendingPublishedTracks.Add(track); err == ErrTrackExists {
s.log.Errorf("client: client %s track already added ", track.ID())
// not an error could be because a simulcast track already added
return
}
// don't publish track when not all the tracks are received
// TODO:
// 1. need to handle simulcast track because it will be counted as single track
initialReceiverCount := client.initialReceiverCount.Load()
if client.Type() == ClientTypePeer && int(initialReceiverCount) > client.pendingPublishedTracks.Length() {
s.log.Infof("sfu: client %s pending published tracks: %d, initial tracks count: %d", id, client.pendingPublishedTracks.Length(), initialReceiverCount)
return
}
s.log.Infof("sfu: client %s publish tracks, initial tracks count: %d, pending published tracks: %d", id, initialReceiverCount, client.pendingPublishedTracks.Length())
addedTracks := client.pendingPublishedTracks.GetTracks()
if client.onTracksAdded != nil {
client.onTracksAdded(addedTracks)
}
}
client.peerConnection.PC().OnSignalingStateChange(func(state webrtc.SignalingState) {
if state == webrtc.SignalingStateStable && client.pendingRemoteRenegotiation.Load() {
client.pendingRemoteRenegotiation.Store(false)
client.allowRemoteRenegotiation()
}
})
peerConnection.OnConnectionStateChange(func(connectionState webrtc.PeerConnectionState) {
client.log.Infof("client: connection state changed %s", connectionState.String())
client.onConnectionStateChanged(connectionState)
switch connectionState {
case webrtc.PeerConnectionStateConnected:
if client.state.Load() == ClientStateNew {
client.state.Store(ClientStateActive)
client.onJoined()
// trigger available tracks from other clients
availableTracks := make([]ITrack, 0)
for _, c := range s.clients.GetClients() {
for _, track := range c.tracks.GetTracks() {
_, err := client.publishedTracks.Get(track.ID())
if track.ClientID() != client.ID() {
if err == ErrTrackIsNotExists {
availableTracks = append(availableTracks, track)
} else {
c.log.Errorf("client: track already exists")
}
}
}
}
// add relay tracks
for _, track := range s.relayTracks {
availableTracks = append(availableTracks, track)
}
if len(availableTracks) > 0 {
client.log.Infof("client: ", client.ID(), " available tracks ", len(availableTracks))
client.onTracksAvailable(availableTracks)
}
}
if len(client.pendingReceivedTracks) > 0 {
client.processPendingTracks()
}
case webrtc.PeerConnectionStateClosed:
client.afterClosed()
case webrtc.PeerConnectionStateFailed:
client.startIdleTimeout(5 * time.Second)
case webrtc.PeerConnectionStateConnecting:
client.cancelIdleTimeout()
case webrtc.PeerConnectionStateDisconnected:
// do nothing it will idle failed or connected after a while
case webrtc.PeerConnectionStateNew:
// do nothing
client.startIdleTimeout(opts.IdleTimeout)
case webrtc.PeerConnectionState(webrtc.PeerConnectionStateUnknown):
// clean up
client.afterClosed()
}
})
// setup internal data channel
if opts.EnableVoiceDetection {
client.enableSendVADToInternalDataChannel()
client.enableVADStatUpdate()
}
client.quality.Store(QualityHigh)
client.ingressQualityLimitationReason.Store("none")
client.stats = newClientStats(client)
client.bitrateController = newbitrateController(client, opts.qualityLevels)
go func() {
estimator := <-estimatorChan
client.mu.Lock()
defer client.mu.Unlock()
client.estimator = estimator
}()
// Set a handler for when a new remote track starts, this just distributes all our packets
// to connected peers
peerConnection.OnTrack(func(remoteTrack *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
var track ITrack
remoteTrackID := strings.ReplaceAll(strings.ReplaceAll(remoteTrack.ID(), "{", ""), "}", "")
defer client.log.Infof("client: new track id %s rid %s ssrc %d kind %s", remoteTrack.ID(), remoteTrack.RID(), remoteTrack.SSRC(), remoteTrack.Kind())
// make sure the remote track ID is not empty
if remoteTrackID == "" {
client.log.Errorf("client: error remote track id is empty")
return
}
onPLI := func() {
if client.peerConnection == nil || client.peerConnection.PC() == nil || client.peerConnection.PC().ConnectionState() != webrtc.PeerConnectionStateConnected {
return
}
if err := client.peerConnection.PC().WriteRTCP([]rtcp.Packet{
&rtcp.PictureLossIndication{MediaSSRC: uint32(remoteTrack.SSRC())},
}); err != nil {
client.log.Errorf("client: error write pli ", err)
}
}
onStatsUpdated := func(stats *stats.Stats) {
client.stats.SetReceiver(remoteTrack.ID(), remoteTrack.RID(), *stats)
}
if remoteTrack.RID() == "" {
// not simulcast
minWait := opts.JitterBufferMinWait
maxWait := opts.JitterBufferMaxWait
track = newTrack(client.context, client, remoteTrack, minWait, maxWait, s.pliInterval, onPLI, client.statsGetter, onStatsUpdated)
track.OnEnded(func() {
client.stats.removeReceiverStats(remoteTrack.ID() + remoteTrack.RID())
client.tracks.remove([]string{remoteTrack.ID()})
})
if opts.EnableVoiceDetection && remoteTrack.Kind() == webrtc.RTPCodecTypeAudio {
vad, ok := vads[uint32(remoteTrack.SSRC())]
if ok {
audioTrack := track.(*AudioTrack)
audioTrack.SetVAD(vad)
audioTrack.OnVoiceDetected(func(pkts []voiceactivedetector.VoicePacketData) {
activity := voiceactivedetector.VoiceActivity{
TrackID: track.ID(),
StreamID: track.StreamID(),
SSRC: uint32(audioTrack.SSRC()),
ClockRate: audioTrack.base.codec.ClockRate,
AudioLevels: pkts,
}
client.onVoiceReceiveDetected(activity)
})
} else {
client.log.Errorf("client: error voice detector not found")
}
}
if err := client.tracks.Add(track); err != nil {
client.log.Errorf("client: error add track ", err)
}
client.onTrack(track)
track.SetAsProcessed()
} else {
// simulcast
var simulcast *SimulcastTrack
var ok bool
id := remoteTrack.ID()
track, err = client.tracks.Get(id) // not found because the track is not added yet due to race condition
if err != nil {
// if track not found, add it
track = newSimulcastTrack(client, remoteTrack, opts.JitterBufferMinWait, opts.JitterBufferMaxWait, s.pliInterval, onPLI, client.statsGetter, onStatsUpdated)
if err := client.tracks.Add(track); err != nil {
client.log.Errorf("client: error add track ", err)
}
track.OnEnded(func() {
simulcastTrack := track.(*SimulcastTrack)
// simulcastTrack.mu.Lock()
// defer simulcastTrack.mu.Unlock()
if simulcastTrack.remoteTrackHigh != nil {
client.stats.removeReceiverStats(simulcastTrack.remoteTrackHigh.track.ID() + simulcastTrack.remoteTrackHigh.track.RID())
}
if simulcastTrack.remoteTrackMid != nil {
client.stats.removeReceiverStats(simulcastTrack.remoteTrackMid.track.ID() + simulcastTrack.remoteTrackMid.track.RID())
}
if simulcastTrack.remoteTrackLow != nil {
client.stats.removeReceiverStats(simulcastTrack.remoteTrackLow.track.ID() + simulcastTrack.remoteTrackLow.track.RID())
}
client.tracks.remove([]string{remoteTrack.ID()})
})
} else if simulcast, ok = track.(*SimulcastTrack); ok {
simulcast.AddRemoteTrack(remoteTrack, opts.JitterBufferMinWait, opts.JitterBufferMaxWait, client.statsGetter, onStatsUpdated, onPLI)
}
if !track.IsProcessed() {
client.onTrack(track)
track.SetAsProcessed()
}
}
})
peerConnection.OnICECandidate(func(candidate *webrtc.ICECandidate) {
// only sending candidate when the local description is set, means expecting the remote peer already has the remote description
if candidate != nil {
if client.canAddCandidate.Load() {
go client.onIceCandidateCallback(candidate)
return
}
client.mu.Lock()
client.pendingLocalCandidates = append(client.pendingLocalCandidates, candidate)
client.mu.Unlock()
}
})
peerConnection.OnNegotiationNeeded(func() {
client.renegotiate(false)
})
return client
}
func (c *Client) initDataChannel() {
// make sure the exisiting data channels is created on new clients
c.SFU().createExistingDataChannels(c)
var internalDataChannel *webrtc.DataChannel
var err error
if internalDataChannel, err = c.createInternalDataChannel("internal", c.onInternalMessage); err != nil {
c.log.Errorf("client: error create internal data channel %s", err.Error())
}
c.internalDataChannel = internalDataChannel
}
func (c *Client) ID() string {
return c.id
}
func (c *Client) Name() string {
return c.name
}
func (c *Client) Context() context.Context {
return c.context
}
// OnTrackAdded event is to confirmed the source type of the pending published tracks.
// If the event is not listened, the pending published tracks will be ignored and not published to other clients.
// Once received, respond with `client.SetTracksSourceType()“ to confirm the source type of the pending published tracks
func (c *Client) OnTracksAdded(callback func(addedTracks []ITrack)) {
c.muCallback.Lock()
defer c.muCallback.Unlock()
c.onTracksAdded = callback
}
// Init and Complete negotiation is used for bridging the room between servers
func (c *Client) InitNegotiation() *webrtc.SessionDescription {
offer, err := c.peerConnection.PC().CreateOffer(nil)
if err != nil {
panic(err)
}
err = c.peerConnection.PC().SetLocalDescription(offer)
if err != nil {
panic(err)
}
// allow add candidates once the local description is set
c.canAddCandidate.Store(true)
return c.peerConnection.PC().LocalDescription()
}
func (c *Client) CompleteNegotiation(answer webrtc.SessionDescription) {
err := c.peerConnection.PC().SetRemoteDescription(answer)
if err != nil {
panic(err)
}
}
// ask if allowed for remote negotiation is required before call negotiation to make sure there is no racing condition of negotiation between local and remote clients.
// return false means the negotiation is in process, the requester must have a mechanism to repeat the request once it's done.
// requesting this must be followed by calling Negotate() to make sure the state is completed. Failed on called Negotiate() will cause the client to be in inconsistent state.
func (c *Client) IsAllowNegotiation() bool {
if c.isInRenegotiation.Load() {
c.pendingRemoteRenegotiation.Store(true)
return false
}
c.isInRemoteNegotiation.Store(true)
return true
}
func (c *Client) Negotiate(offer webrtc.SessionDescription) (*webrtc.SessionDescription, error) {
c.isInRemoteNegotiation.Store(true)
defer func() {
c.isInRemoteNegotiation.Store(false)
if c.negotiationNeeded.Load() {
c.renegotiate(false)
}
}()
currentReceiversCount := 0
currentSendersCount := 0
for _, trscv := range c.peerConnection.PC().GetTransceivers() {
if trscv.Receiver() != nil {
currentReceiversCount++
}
if trscv.Sender() != nil {
currentSendersCount++
}
}
if !c.receiveRED {
match, err := regexp.MatchString(`a=rtpmap:63`, offer.SDP)
if err != nil {
c.log.Errorf("client: error on check RED support in SDP ", err)
} else {
c.receiveRED = match
}
}
// Set the remote SessionDescription
err := c.peerConnection.PC().SetRemoteDescription(offer)
if err != nil {
c.log.Errorf("client: error set remote description ", err)
return nil, err
}
// Create answer
answer, err := c.peerConnection.PC().CreateAnswer(nil)
if err != nil {
c.log.Errorf("client: error create answer ", err)
return nil, err
}
var gatherComplete <-chan struct{}
if !c.options.IceTrickle {
gatherComplete = webrtc.GatheringCompletePromise(c.peerConnection.PC())
}
// Sets the LocalDescription, and starts our UDP listeners
err = c.peerConnection.PC().SetLocalDescription(answer)
if err != nil {
c.log.Errorf("client: error set local description ", err)
return nil, err
}
if !c.options.IceTrickle {
<-gatherComplete
}
// allow add candidates once the local description is set
c.canAddCandidate.Store(true)
// process pending ice
for _, iceCandidate := range c.pendingRemoteCandidates {
err = c.peerConnection.PC().AddICECandidate(iceCandidate)
if err != nil {
c.log.Errorf("client: error add ice candidate ", err)
return nil, err
}
}
newReceiversCount := 0
newSenderCount := 0
for _, trscv := range c.peerConnection.PC().GetTransceivers() {
if trscv.Receiver() != nil {
newReceiversCount++
}
if trscv.Sender() != nil {
newSenderCount++
}
}
initialReceiverCount := newReceiversCount - currentReceiversCount
c.initialReceiverCount.Store(uint32(initialReceiverCount))
initialSenderCount := newSenderCount - currentSendersCount
c.initialSenderCount.Store(uint32(initialSenderCount))
// send pending local candidates if any
go c.sendPendingLocalCandidates()
c.pendingRemoteCandidates = nil
sdp := c.setOpusSDP(*c.peerConnection.PC().LocalDescription())
return &sdp, nil
}
func (c *Client) setOpusSDP(sdp webrtc.SessionDescription) webrtc.SessionDescription {
if c.options.EnableOpusDTX {
var regex, err = regexp.Compile(`a=rtpmap:(\d+) opus\/(\d+)\/(\d+)`)
if err != nil {
c.log.Errorf("client: error on compile regex ", err)
return sdp
}
var opusLine = regex.FindString(sdp.SDP)
if opusLine == "" {
c.log.Errorf("client: error opus line not found")
return sdp
}
regex, err = regexp.Compile(`(\d+)`)
if err != nil {
c.log.Errorf("client: error on compile regex ", err)
return sdp
}
var opusNo = regex.FindString(opusLine)
if opusNo == "" {
c.log.Errorf("client: error opus no not found")
return sdp
}
fmtpRegex, err := regexp.Compile(`a=fmtp:` + opusNo + ` .+`)
if err != nil {
c.log.Errorf("client: error on compile regex ", err)
return sdp
}
var fmtpLine = fmtpRegex.FindString(sdp.SDP)
if fmtpLine == "" {
c.log.Errorf("client: error fmtp line not found")
return sdp
}
var newFmtpLine = ""
if c.options.EnableOpusDTX && !strings.Contains(fmtpLine, "usedtx=1") {
newFmtpLine += ";usedtx=1"
}
if c.options.EnableOpusInbandFEC && !strings.Contains(fmtpLine, "useinbandfec=1") {
newFmtpLine += ";useinbandfec=1"
}
if newFmtpLine != "" {
sdp.SDP = strings.Replace(sdp.SDP, fmtpLine, fmtpLine+newFmtpLine, -1)
}
}
if !c.dataChannelsInitiated {
c.initDataChannel()
c.dataChannelsInitiated = true
}
return sdp
}
// OnRenegotiation event is called when the SFU is trying to renegotiate with the client.
// The callback will receive the SDP offer from the SFU that must be use to create the SDP answer from the client.
// The SDP answer then can be passed back to the SFU using `client.CompleteNegotiation()` method.
func (c *Client) OnRenegotiation(callback func(context.Context, webrtc.SessionDescription) (webrtc.SessionDescription, error)) {
c.muCallback.Lock()
defer c.muCallback.Unlock()
c.onRenegotiation = callback
}
func (c *Client) renegotiate(offerFlexFec bool) {
c.log.Debug("client: renegotiate")
c.negotiationNeeded.Store(true)
if c.onRenegotiation == nil {
c.log.Errorf("client: onRenegotiation is not set, can't do renegotiation")
return
}
if c.isInRemoteNegotiation.Load() {
c.log.Infof("sfu: renegotiation is delayed because the remote client %s is doing negotiation ", c.ID)
return
}
// no need to run another negotiation if it's already in progress, it will rerun because we mark the negotiationneeded to true
if c.isInRenegotiation.Load() {
c.log.Infof("sfu: renegotiation is delayed because the client %s is doing negotiation ", c.ID)
return
}
// mark negotiation is in progress to make sure no concurrent negotiation
c.isInRenegotiation.Store(true)
go func() {
defer func() {
c.isInRenegotiation.Store(false)
if c.pendingRemoteRenegotiation.Load() {
c.allowRemoteRenegotiation()
}
}()
for c.negotiationNeeded.Load() {
timout, cancel := context.WithTimeout(c.context, 100*time.Millisecond)
defer cancel()
<-timout.Done()
// mark negotiation is not needed after this done, so it will out of the loop
c.negotiationNeeded.Store(false)
// only renegotiate when client is connected
if c.state.Load() != ClientStateEnded &&
c.peerConnection.PC().SignalingState() == webrtc.SignalingStateStable &&
c.peerConnection.PC().ConnectionState() == webrtc.PeerConnectionStateConnected {
if c.onRenegotiation == nil {
return
}
offer, err := c.peerConnection.PC().CreateOffer(nil)
if err != nil {
c.log.Errorf("sfu: error create offer on renegotiation ", err)
return
}
if offerFlexFec {
// munge the offer to include FlexFEC
// get the payload code of video track
}
// Sets the LocalDescription, and starts our UDP listeners
err = c.peerConnection.PC().SetLocalDescription(offer)
if err != nil {
c.log.Errorf("sfu: error set local description on renegotiation ", err)
_ = c.stop()
return
}
// this will be blocking until the renegotiation is done
sdp := c.setOpusSDP(*c.peerConnection.PC().LocalDescription())
answer, err := c.onRenegotiation(c.context, sdp)
if err != nil {
//TODO: when this happen, we need to close the client and ask the remote client to reconnect
c.log.Errorf("sfu: error on renegotiation ", err)
_ = c.stop()
return
}
if answer.Type != webrtc.SDPTypeAnswer {
c.log.Errorf("sfu: error on renegotiation, the answer is not an answer type")
_ = c.stop()
return
}
err = c.peerConnection.PC().SetRemoteDescription(answer)
if err != nil {
_ = c.stop()
return
}
}
}
}()
}
// OnAllowedRemoteRenegotiation event is called when the SFU is done with the renegotiation
// and ready to receive the renegotiation from the client.
// Use this event to trigger the client to do renegotiation if needed.
func (c *Client) OnAllowedRemoteRenegotiation(callback func()) {
c.muCallback.Lock()
defer c.muCallback.Unlock()
c.onAllowedRemoteRenegotiation = callback
}
// inform to remote client that it's allowed to do renegotiation through event
func (c *Client) allowRemoteRenegotiation() {
if c.onAllowedRemoteRenegotiation != nil {
c.isInRemoteNegotiation.Store(true)
go c.onAllowedRemoteRenegotiation()
}
}
func (c *Client) setClientTrack(t ITrack) iClientTrack {
var outputTrack iClientTrack
err := c.publishedTracks.Add(t)
if err != nil {
return nil
}
if t.IsSimulcast() {
simulcastTrack := t.(*SimulcastTrack)
outputTrack = simulcastTrack.subscribe(c)
} else {
if t.Kind() == webrtc.RTPCodecTypeAudio {
singleTrack := t.(*AudioTrack)
outputTrack = singleTrack.subscribe(c)
} else {
singleTrack := t.(*Track)
outputTrack = singleTrack.subscribe(c)
}