-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtrack.go
1023 lines (799 loc) · 22.6 KB
/
track.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"
"errors"
"sync"
"sync/atomic"
"time"
"github.com/inlivedev/sfu/pkg/interceptors/voiceactivedetector"
"github.com/inlivedev/sfu/pkg/networkmonitor"
"github.com/inlivedev/sfu/pkg/rtppool"
"github.com/pion/interceptor"
"github.com/pion/interceptor/pkg/stats"
"github.com/pion/logging"
"github.com/pion/rtp"
"github.com/pion/webrtc/v4"
)
const (
TrackTypeMedia = "media"
TrackTypeScreen = "screen"
)
var (
ErrTrackExists = errors.New("client: error track already exists")
ErrTrackIsNotExists = errors.New("client: error track is not exists")
)
type TrackType string
func (t TrackType) String() string {
return string(t)
}
type baseTrack struct {
id string
msid string
streamid string
client *Client
isProcessed bool
kind webrtc.RTPCodecType
codec webrtc.RTPCodecParameters
isScreen *atomic.Bool // source of the track, can be media or screen
clientTracks *clientTrackList
pool *rtppool.RTPPool
}
type ITrack interface {
ID() string
StreamID() string
ClientID() string
IsSimulcast() bool
IsScaleable() bool
IsProcessed() bool
SetSourceType(TrackType)
SourceType() TrackType
SetAsProcessed()
OnRead(func(interceptor.Attributes, *rtp.Packet, QualityLevel))
IsScreen() bool
IsRelay() bool
Kind() webrtc.RTPCodecType
MimeType() string
TotalTracks() int
Context() context.Context
Relay(func(webrtc.SSRC, interceptor.Attributes, *rtp.Packet))
PayloadType() webrtc.PayloadType
OnEnded(func())
}
type Track struct {
context context.Context
mu sync.Mutex
base *baseTrack
remoteTrack *remoteTrack
onEndedCallbacks []func()
onReadCallbacks []func(interceptor.Attributes, *rtp.Packet, QualityLevel)
}
type AudioTrack struct {
*Track
vad *voiceactivedetector.VoiceDetector
vadCallbacks []func([]voiceactivedetector.VoicePacketData)
}
func newTrack(ctx context.Context, client *Client, trackRemote IRemoteTrack, minWait, maxWait, pliInterval time.Duration, onPLI func(), stats stats.Getter, onStatsUpdated func(*stats.Stats)) ITrack {
ctList := newClientTrackList()
pool := rtppool.New()
baseTrack := &baseTrack{
id: trackRemote.ID(),
isScreen: &atomic.Bool{},
msid: trackRemote.Msid(),
streamid: trackRemote.StreamID(),
client: client,
kind: trackRemote.Kind(),
codec: trackRemote.Codec(),
clientTracks: ctList,
pool: pool,
}
t := &Track{
mu: sync.Mutex{},
base: baseTrack,
onReadCallbacks: make([]func(interceptor.Attributes, *rtp.Packet, QualityLevel), 0),
onEndedCallbacks: make([]func(), 0),
}
onRead := func(attrs interceptor.Attributes, p *rtp.Packet) {
tracks := t.base.clientTracks.GetTracks()
for _, track := range tracks {
//nolint:ineffassign,staticcheck // packet is from the pool
packet := pool.NewPacket(&p.Header, p.Payload, attrs)
copyPacket := pool.GetPacket()
copyPacket.Header = *packet.Header()
copyPacket.Payload = packet.Payload()
track.push(copyPacket, QualityHigh)
pool.PutPacket(copyPacket)
packet.Release()
}
//nolint:ineffassign // this is required
packet := pool.NewPacket(&p.Header, p.Payload, attrs)
copyPacket := pool.GetPacket()
copyPacket.Header = *packet.Header()
copyPacket.Payload = packet.Payload()
t.onRead(attrs, copyPacket, QualityHigh)
pool.PutPacket(copyPacket)
packet.Release()
}
onNetworkConditionChanged := func(condition networkmonitor.NetworkConditionType) {
client.onNetworkConditionChanged(condition)
}
t.remoteTrack = newRemoteTrack(ctx, client.log, client.options.ReorderPackets, trackRemote, minWait, maxWait, pliInterval, onPLI, stats, onStatsUpdated, onRead, pool, onNetworkConditionChanged)
var cancel context.CancelFunc
t.context, cancel = context.WithCancel(client.Context())
t.remoteTrack.OnEnded(func() {
cancel()
t.onEnded()
})
if trackRemote.Kind() == webrtc.RTPCodecTypeAudio {
ta := &AudioTrack{
Track: t,
}
return ta
}
return t
}
func (t *Track) ClientID() string {
return t.base.client.id
}
func (t *Track) Context() context.Context {
return t.context
}
func (t *Track) createLocalTrack() *webrtc.TrackLocalStaticRTP {
track, newTrackErr := webrtc.NewTrackLocalStaticRTP(t.remoteTrack.track.Codec().RTPCodecCapability, t.base.id, t.base.streamid)
if newTrackErr != nil {
panic(newTrackErr)
}
return track
}
func (t *Track) createOpusLocalTrack() *webrtc.TrackLocalStaticRTP {
c := t.remoteTrack.track.Codec().RTPCodecCapability
c.MimeType = webrtc.MimeTypeOpus
c.SDPFmtpLine = "minptime=10;useinbandfec=1"
track, newTrackErr := webrtc.NewTrackLocalStaticRTP(c, t.base.id, t.base.streamid)
if newTrackErr != nil {
panic(newTrackErr)
}
return track
}
func (t *Track) ID() string {
return t.base.id
}
func (t *Track) StreamID() string {
return t.base.streamid
}
func (t *Track) SSRC() webrtc.SSRC {
return t.remoteTrack.track.SSRC()
}
func (t *AudioTrack) SetVAD(vad *voiceactivedetector.VoiceDetector) {
t.mu.Lock()
defer t.mu.Unlock()
t.vad = vad
vad.OnVoiceDetected(func(pkts []voiceactivedetector.VoicePacketData) {
// send through datachannel
t.onVoiceDetected(pkts)
})
}
func (t *AudioTrack) onVoiceDetected(pkts []voiceactivedetector.VoicePacketData) {
t.mu.Lock()
defer t.mu.Unlock()
for _, callback := range t.vadCallbacks {
callback(pkts)
}
}
func (t *AudioTrack) OnVoiceDetected(callback func(pkts []voiceactivedetector.VoicePacketData)) {
t.mu.Lock()
defer t.mu.Unlock()
t.vadCallbacks = append(t.vadCallbacks, callback)
}
func (t *AudioTrack) subscribe(c *Client) iClientTrack {
var ct iClientTrack
cta := newClientTrackAudio(c, t)
if t.PayloadType() == 63 {
t.base.client.log.Tracef("track: red enabled %v", c.receiveRED)
// TODO: detect if client supports RED and it's audio then send RED encoded packets
ct = newClientTrackRed(cta)
} else {
ct = cta
}
t.base.clientTracks.Add(ct)
return ct
}
func (t *Track) RemoteTrack() *remoteTrack {
t.mu.Lock()
defer t.mu.Unlock()
return t.remoteTrack
}
func (t *Track) IsScreen() bool {
return t.base.isScreen.Load()
}
func (t *Track) IsSimulcast() bool {
return false
}
func (t *Track) IsScaleable() bool {
return t.MimeType() == webrtc.MimeTypeVP9
}
func (t *Track) IsProcessed() bool {
t.mu.Lock()
defer t.mu.Unlock()
return t.base.isProcessed
}
func (t *Track) Kind() webrtc.RTPCodecType {
return t.base.kind
}
func (t *Track) MimeType() string {
return t.base.codec.MimeType
}
func (t *Track) SSRCHigh() webrtc.SSRC {
return t.remoteTrack.Track().SSRC()
}
func (t *Track) SSRCMid() webrtc.SSRC {
return t.remoteTrack.Track().SSRC()
}
func (t *Track) SSRCLow() webrtc.SSRC {
return t.remoteTrack.Track().SSRC()
}
func (t *Track) TotalTracks() int {
return 1
}
func (t *Track) subscribe(c *Client) iClientTrack {
var ct iClientTrack
if t.MimeType() == webrtc.MimeTypeVP9 {
ct = newScaleableClientTrack(c, t)
} else {
ct = newClientTrack(c, t, t.IsScreen(), nil)
}
if t.Kind() == webrtc.RTPCodecTypeVideo {
t.remoteTrack.SendPLI()
}
t.base.clientTracks.Add(ct)
return ct
}
func (t *Track) SetSourceType(sourceType TrackType) {
t.base.isScreen.Store(sourceType == TrackTypeScreen)
}
func (t *Track) SourceType() TrackType {
if t.base.isScreen.Load() {
return TrackTypeScreen
}
return TrackTypeMedia
}
func (t *Track) SetAsProcessed() {
t.mu.Lock()
defer t.mu.Unlock()
t.base.isProcessed = true
}
func (t *Track) OnRead(callback func(interceptor.Attributes, *rtp.Packet, QualityLevel)) {
t.mu.Lock()
defer t.mu.Unlock()
t.onReadCallbacks = append(t.onReadCallbacks, callback)
}
func (t *Track) onRead(attrs interceptor.Attributes, p *rtp.Packet, quality QualityLevel) {
callbacks := make([]func(interceptor.Attributes, *rtp.Packet, QualityLevel), 0)
t.mu.Lock()
callbacks = append(callbacks, t.onReadCallbacks...)
t.mu.Unlock()
for _, callback := range callbacks {
copyPacket := t.base.pool.GetPacket()
copyPacket.Header = p.Header
copyPacket.Payload = p.Payload
callback(attrs, p, quality)
t.base.pool.PutPacket(copyPacket)
}
}
func (t *Track) Relay(f func(webrtc.SSRC, interceptor.Attributes, *rtp.Packet)) {
t.OnRead(func(attrs interceptor.Attributes, p *rtp.Packet, quality QualityLevel) {
f(t.SSRC(), attrs, p)
})
}
func (t *Track) PayloadType() webrtc.PayloadType {
return t.base.codec.PayloadType
}
func (t *Track) IsRelay() bool {
return t.remoteTrack.IsRelay()
}
func (t *Track) OnEnded(f func()) {
t.mu.Lock()
defer t.mu.Unlock()
t.onEndedCallbacks = append(t.onEndedCallbacks, f)
}
func (t *Track) onEnded() {
t.mu.Lock()
defer t.mu.Unlock()
for _, f := range t.onEndedCallbacks {
f()
}
}
type SimulcastTrack struct {
context context.Context
cancel context.CancelFunc
mu sync.RWMutex
base *baseTrack
baseTS uint32
onTrackCompleteCallbacks []func()
remoteTrackHigh *remoteTrack
remoteTrackHighBaseTS uint32
highSequence uint16
lastHighSequence uint16
remoteTrackMid *remoteTrack
remoteTrackMidBaseTS uint32
midSequence uint16
lastMidSequence uint16
remoteTrackLow *remoteTrack
remoteTrackLowBaseTS uint32
lowSequence uint16
lastLowSequence uint16
lastReadHighTS *atomic.Int64
lastReadMidTS *atomic.Int64
lastReadLowTS *atomic.Int64
lastHighKeyframeTS *atomic.Int64
lastMidKeyframeTS *atomic.Int64
lastLowKeyframeTS *atomic.Int64
onAddedRemoteTrackCallbacks []func(*remoteTrack)
onReadCallbacks []func(interceptor.Attributes, *rtp.Packet, QualityLevel)
pliInterval time.Duration
onNetworkConditionChanged func(networkmonitor.NetworkConditionType)
reordered bool
onEndedCallbacks []func()
}
func newSimulcastTrack(client *Client, track IRemoteTrack, minWait, maxWait, pliInterval time.Duration, onPLI func(), stats stats.Getter, onStatsUpdated func(*stats.Stats)) ITrack {
t := &SimulcastTrack{
mu: sync.RWMutex{},
base: &baseTrack{
id: track.ID(),
isScreen: &atomic.Bool{},
msid: track.Msid(),
streamid: track.StreamID(),
client: client,
kind: track.Kind(),
codec: track.Codec(),
clientTracks: newClientTrackList(),
pool: rtppool.New(),
},
lastReadHighTS: &atomic.Int64{},
lastReadMidTS: &atomic.Int64{},
lastReadLowTS: &atomic.Int64{},
lastHighKeyframeTS: &atomic.Int64{},
lastMidKeyframeTS: &atomic.Int64{},
lastLowKeyframeTS: &atomic.Int64{},
onTrackCompleteCallbacks: make([]func(), 0),
onAddedRemoteTrackCallbacks: make([]func(*remoteTrack), 0),
onReadCallbacks: make([]func(interceptor.Attributes, *rtp.Packet, QualityLevel), 0),
pliInterval: pliInterval,
onNetworkConditionChanged: func(condition networkmonitor.NetworkConditionType) {
client.onNetworkConditionChanged(condition)
},
onEndedCallbacks: make([]func(), 0),
}
t.context, t.cancel = context.WithCancel(client.Context())
rt := t.AddRemoteTrack(track, minWait, maxWait, stats, onStatsUpdated, onPLI)
rt.OnEnded(func() {
t.cancel()
t.onEnded()
})
return t
}
func (t *SimulcastTrack) ClientID() string {
return t.base.client.id
}
func (t *SimulcastTrack) Context() context.Context {
return t.context
}
func (t *SimulcastTrack) onRemoteTrackAdded(f func(*remoteTrack)) {
t.mu.Lock()
defer t.mu.Unlock()
t.onAddedRemoteTrackCallbacks = append(t.onAddedRemoteTrackCallbacks, f)
}
func (t *SimulcastTrack) onRemoteTrackAddedCallbacks(track *remoteTrack) {
t.mu.Lock()
defer t.mu.Unlock()
for _, f := range t.onAddedRemoteTrackCallbacks {
f(track)
}
}
func (t *SimulcastTrack) OnTrackComplete(f func()) {
t.mu.Lock()
defer t.mu.Unlock()
t.onTrackCompleteCallbacks = append(t.onTrackCompleteCallbacks, f)
}
func (t *SimulcastTrack) onTrackComplete() {
t.mu.Lock()
defer t.mu.Unlock()
for _, f := range t.onTrackCompleteCallbacks {
f()
}
}
// TODO: this is contain multiple tracks, there is a possibility remote track high is not available yet
func (t *SimulcastTrack) ID() string {
return t.base.id
}
func (t *SimulcastTrack) StreamID() string {
return t.base.streamid
}
func (t *SimulcastTrack) IsSimulcast() bool {
return true
}
func (t *SimulcastTrack) IsScaleable() bool {
return false
}
func (t *SimulcastTrack) IsProcessed() bool {
t.mu.Lock()
defer t.mu.Unlock()
return t.base.isProcessed
}
func (t *SimulcastTrack) Kind() webrtc.RTPCodecType {
return t.base.kind
}
func (t *SimulcastTrack) AddRemoteTrack(track IRemoteTrack, minWait, maxWait time.Duration, stats stats.Getter, onStatsUpdated func(*stats.Stats), onPLI func()) *remoteTrack {
var remoteTrack *remoteTrack
quality := RIDToQuality(track.RID())
onRead := func(attrs interceptor.Attributes, p *rtp.Packet) {
// set the base timestamp for the track if it is not set yet
if t.baseTS == 0 {
t.baseTS = p.Timestamp
}
if quality == QualityHigh && t.remoteTrackHighBaseTS == 0 {
t.remoteTrackHighBaseTS = p.Timestamp
} else if quality == QualityMid && t.remoteTrackMidBaseTS == 0 {
t.remoteTrackMidBaseTS = p.Timestamp
} else if quality == QualityLow && t.remoteTrackLowBaseTS == 0 {
t.remoteTrackLowBaseTS = p.Timestamp
}
readTime := time.Now().UnixNano()
switch quality {
case QualityHigh:
t.lastReadHighTS.Store(readTime)
t.lastHighSequence = t.highSequence
t.highSequence = p.SequenceNumber
case QualityMid:
t.lastReadMidTS.Store(readTime)
t.lastMidSequence = t.midSequence
t.midSequence = p.SequenceNumber
case QualityLow:
t.lastReadLowTS.Store(readTime)
t.lastLowSequence = t.lowSequence
t.lowSequence = p.SequenceNumber
}
tracks := t.base.clientTracks.GetTracks()
for _, track := range tracks {
//nolint:ineffassign,staticcheck // packet is from the pool
packet := t.base.pool.NewPacket(&p.Header, p.Payload, attrs)
copyPacket := t.base.pool.GetPacket()
copyPacket.Header = *packet.Header()
copyPacket.Payload = packet.Payload()
track.push(copyPacket, quality)
t.base.pool.PutPacket(copyPacket)
packet.Release()
}
//nolint:ineffassign // this is required
packet := t.base.pool.NewPacket(&p.Header, p.Payload, attrs)
copyPacket := t.base.pool.GetPacket()
copyPacket.Header = *packet.Header()
copyPacket.Payload = packet.Payload()
t.onRead(attrs, copyPacket, quality)
t.base.pool.PutPacket(copyPacket)
packet.Release()
}
remoteTrack = newRemoteTrack(t.Context(), t.base.client.log, t.reordered, track, minWait, maxWait, t.pliInterval, onPLI, stats, onStatsUpdated, onRead, t.base.pool, t.onNetworkConditionChanged)
switch quality {
case QualityHigh:
t.mu.Lock()
t.remoteTrackHigh = remoteTrack
t.mu.Unlock()
remoteTrack.OnEnded(func() {
t.remoteTrackHigh = nil
t.cancel()
t.onEnded()
})
case QualityMid:
t.mu.Lock()
t.remoteTrackMid = remoteTrack
t.mu.Unlock()
remoteTrack.OnEnded(func() {
t.remoteTrackMid = nil
t.cancel()
t.onEnded()
})
case QualityLow:
t.mu.Lock()
t.remoteTrackLow = remoteTrack
t.mu.Unlock()
remoteTrack.OnEnded(func() {
t.remoteTrackLow = nil
t.cancel()
t.onEnded()
})
default:
t.base.client.log.Warnf("client: unknown track quality ", track.RID())
return nil
}
// check if all simulcast tracks are available
if t.remoteTrackHigh != nil && t.remoteTrackMid != nil && t.remoteTrackLow != nil {
t.onTrackComplete()
}
t.onRemoteTrackAddedCallbacks(remoteTrack)
return remoteTrack
}
func (t *SimulcastTrack) GetRemoteTrack(q QualityLevel) *remoteTrack {
t.mu.Lock()
defer t.mu.Unlock()
switch q {
case QualityHigh:
return t.remoteTrackHigh
case QualityMid:
return t.remoteTrackMid
case QualityLow:
return t.remoteTrackLow
}
return nil
}
func (t *SimulcastTrack) subscribe(client *Client) iClientTrack {
// Create a local track, all our SFU clients will be fed via this track
ct := newSimulcastClientTrack(client, t)
t.base.clientTracks.Add(ct)
return ct
}
func (t *SimulcastTrack) SetSourceType(sourceType TrackType) {
t.base.isScreen.Store(sourceType == TrackTypeScreen)
}
func (t *SimulcastTrack) SourceType() TrackType {
if t.base.isScreen.Load() {
return TrackTypeScreen
}
return TrackTypeMedia
}
func (t *SimulcastTrack) SetAsProcessed() {
t.mu.Lock()
defer t.mu.Unlock()
t.base.isProcessed = true
}
func (t *SimulcastTrack) IsScreen() bool {
return t.base.isScreen.Load()
}
func (t *SimulcastTrack) IsTrackComplete() bool {
return t.TotalTracks() == 3
}
func (t *SimulcastTrack) TotalTracks() int {
t.mu.Lock()
defer t.mu.Unlock()
total := 0
if t.remoteTrackHigh != nil {
total++
}
if t.remoteTrackMid != nil {
total++
}
if t.remoteTrackLow != nil {
total++
}
return total
}
// track is considered active if the track is not nil and the latest read operation was 500ms ago
func (t *SimulcastTrack) isTrackActive(quality QualityLevel) bool {
t.mu.RLock()
defer t.mu.RUnlock()
// set max active track threshold to 500ms
threshold := time.Duration(500) * time.Millisecond
switch quality {
case QualityHigh:
if t.remoteTrackHigh == nil {
t.base.client.log.Warnf("track: remote track high is nil")
return false
}
delta := time.Since(time.Unix(0, t.lastReadHighTS.Load()))
if delta > threshold {
t.base.client.log.Warnf("track: remote track %s high is not active, last read was %d ms ago", t.base.id, delta.Milliseconds())
return false
}
return true
case QualityMid:
if t.remoteTrackMid == nil {
t.base.client.log.Warnf("track: remote track medium is nil")
return false
}
delta := time.Since(time.Unix(0, t.lastReadMidTS.Load()))
if delta > threshold {
t.base.client.log.Warnf("track: remote track %s mid is not active, last read was %d ms ago", delta.Milliseconds())
return false
}
return true
case QualityLow:
if t.remoteTrackLow == nil {
t.base.client.log.Warnf("track: remote track low is nil")
return false
}
delta := time.Since(time.Unix(0, t.lastReadLowTS.Load()))
if delta > threshold {
t.base.client.log.Warnf("track: remote track %s low is not active, last read was %d ms ago", delta.Milliseconds())
return false
}
return true
}
return false
}
func (t *SimulcastTrack) sendPLI() {
t.mu.RLock()
defer t.mu.RUnlock()
if t.remoteTrackHigh != nil {
t.remoteTrackHigh.SendPLI()
} else {
t.base.client.log.Warnf("track: remote track high is nil")
}
if t.remoteTrackMid != nil {
t.remoteTrackMid.SendPLI()
} else {
t.base.client.log.Warnf("track: remote track mid is nil")
}
if t.remoteTrackLow != nil {
t.remoteTrackLow.SendPLI()
} else {
t.base.client.log.Warnf("track: remote track low is nil")
}
}
func (t *SimulcastTrack) MimeType() string {
return t.base.codec.MimeType
}
func (t *SimulcastTrack) OnRead(callback func(interceptor.Attributes, *rtp.Packet, QualityLevel)) {
t.mu.Lock()
defer t.mu.Unlock()
t.onReadCallbacks = append(t.onReadCallbacks, callback)
}
func (t *SimulcastTrack) onRead(attr interceptor.Attributes, p *rtp.Packet, quality QualityLevel) {
for _, callback := range t.onReadCallbacks {
callback(attr, p, quality)
}
}
func (t *SimulcastTrack) SSRCHigh() webrtc.SSRC {
t.mu.RLock()
defer t.mu.RUnlock()
if t.remoteTrackHigh == nil {
return 0
}
return t.remoteTrackHigh.Track().SSRC()
}
func (t *SimulcastTrack) SSRCMid() webrtc.SSRC {
t.mu.RLock()
defer t.mu.RUnlock()
if t.remoteTrackMid == nil {
return 0
}
return t.remoteTrackMid.Track().SSRC()
}
func (t *SimulcastTrack) SSRCLow() webrtc.SSRC {
t.mu.RLock()
defer t.mu.RUnlock()
if t.remoteTrackLow == nil {
return 0
}
return t.remoteTrackLow.Track().SSRC()
}
func (t *SimulcastTrack) RIDHigh() string {
t.mu.RLock()
defer t.mu.RUnlock()
if t.remoteTrackHigh == nil {
return ""
}
return t.remoteTrackHigh.track.RID()
}
func (t *SimulcastTrack) RIDMid() string {
t.mu.RLock()
defer t.mu.RUnlock()
if t.remoteTrackMid == nil {
return ""
}
return t.remoteTrackMid.track.RID()
}
func (t *SimulcastTrack) RIDLow() string {
t.mu.RLock()
defer t.mu.RUnlock()
if t.remoteTrackLow == nil {
return ""
}
return t.remoteTrackLow.track.RID()
}
func (t *SimulcastTrack) Relay(f func(webrtc.SSRC, interceptor.Attributes, *rtp.Packet)) {
t.OnRead(func(attrs interceptor.Attributes, p *rtp.Packet, quality QualityLevel) {
switch quality {
case QualityHigh:
f(t.SSRCHigh(), attrs, p)
case QualityMid:
f(t.SSRCMid(), attrs, p)
case QualityLow:
f(t.SSRCLow(), attrs, p)
}
})
}
func (t *SimulcastTrack) PayloadType() webrtc.PayloadType {
return t.base.codec.PayloadType
}
func (t *SimulcastTrack) IsRelay() bool {
t.mu.RLock()
defer t.mu.RUnlock()
if t.remoteTrackHigh != nil {
return t.remoteTrackHigh.IsRelay()
} else if t.remoteTrackMid != nil {
return t.remoteTrackMid.IsRelay()
} else if t.remoteTrackLow != nil {
return t.remoteTrackLow.IsRelay()
}
return false
}
func (t *SimulcastTrack) OnEnded(f func()) {
t.mu.Lock()
defer t.mu.Unlock()
t.onEndedCallbacks = append(t.onEndedCallbacks, f)
}
func (t *SimulcastTrack) onEnded() {
for _, f := range t.onEndedCallbacks {
f()
}
}
type SubscribeTrackRequest struct {
ClientID string `json:"client_id"`
TrackID string `json:"track_id"`
}
type trackList struct {
tracks map[string]ITrack
mu sync.RWMutex
log logging.LeveledLogger
}
func newTrackList(log logging.LeveledLogger) *trackList {
return &trackList{
tracks: make(map[string]ITrack),
log: log,
}
}
func (t *trackList) Add(track ITrack) error {
t.mu.Lock()
defer t.mu.Unlock()
id := track.ID()
if _, ok := t.tracks[id]; ok {
t.log.Warnf("tracklist: track %s already added", id)
return ErrTrackExists
}
t.tracks[id] = track
return nil
}
func (t *trackList) Get(ID string) (ITrack, error) {
t.mu.RLock()
defer t.mu.RUnlock()
if track, ok := t.tracks[ID]; ok {
return track, nil
}
return nil, ErrTrackIsNotExists
}
//nolint:copylocks // This is a read only operation
func (t *trackList) remove(ids []string) {
t.mu.Lock()
defer t.mu.Unlock()
for _, id := range ids {
delete(t.tracks, id)
}
}
func (t *trackList) Reset() {
t.mu.RLock()
defer t.mu.RUnlock()
t.tracks = make(map[string]ITrack)
}
func (t *trackList) GetTracks() []ITrack {
t.mu.RLock()
defer t.mu.RUnlock()
tracks := make([]ITrack, 0)
for _, track := range t.tracks {