forked from livekit/livekit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
forwarder.go
2116 lines (1826 loc) · 66.4 KB
/
forwarder.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
// 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 sfu
import (
"errors"
"fmt"
"math"
"math/rand"
"strings"
"sync"
"time"
"github.com/pion/rtp"
"github.com/pion/webrtc/v3"
"go.uber.org/zap/zapcore"
"github.com/livekit/protocol/logger"
"github.com/livekit/livekit-server/pkg/sfu/buffer"
"github.com/livekit/livekit-server/pkg/sfu/codecmunger"
dd "github.com/livekit/livekit-server/pkg/sfu/dependencydescriptor"
"github.com/livekit/livekit-server/pkg/sfu/videolayerselector"
"github.com/livekit/livekit-server/pkg/sfu/videolayerselector/temporallayerselector"
)
// Forwarder
const (
FlagPauseOnDowngrade = true
FlagFilterRTX = false
FlagFilterRTXLayers = true
TransitionCostSpatial = 10
ResumeBehindThresholdSeconds = float64(0.2) // 200ms
ResumeBehindHighThresholdSeconds = float64(2.0) // 2 seconds
LayerSwitchBehindThresholdSeconds = float64(0.05) // 50ms
SwitchAheadThresholdSeconds = float64(0.025) // 25ms
)
// -------------------------------------------------------------------
type VideoPauseReason int
const (
VideoPauseReasonNone VideoPauseReason = iota
VideoPauseReasonMuted
VideoPauseReasonPubMuted
VideoPauseReasonFeedDry
VideoPauseReasonBandwidth
)
func (v VideoPauseReason) String() string {
switch v {
case VideoPauseReasonNone:
return "NONE"
case VideoPauseReasonMuted:
return "MUTED"
case VideoPauseReasonPubMuted:
return "PUB_MUTED"
case VideoPauseReasonFeedDry:
return "FEED_DRY"
case VideoPauseReasonBandwidth:
return "BANDWIDTH"
default:
return fmt.Sprintf("%d", int(v))
}
}
// -------------------------------------------------------------------
type VideoAllocation struct {
PauseReason VideoPauseReason
IsDeficient bool
BandwidthRequested int64
BandwidthDelta int64
BandwidthNeeded int64
Bitrates Bitrates
TargetLayer buffer.VideoLayer
RequestLayerSpatial int32
MaxLayer buffer.VideoLayer
DistanceToDesired float64
}
func (v *VideoAllocation) String() string {
return fmt.Sprintf("VideoAllocation{pause: %s, def: %+v, bwr: %d, del: %d, bwn: %d, rates: %+v, target: %s, req: %d, max: %s, dist: %0.2f}",
v.PauseReason,
v.IsDeficient,
v.BandwidthRequested,
v.BandwidthDelta,
v.BandwidthNeeded,
v.Bitrates,
v.TargetLayer,
v.RequestLayerSpatial,
v.MaxLayer,
v.DistanceToDesired,
)
}
func (v *VideoAllocation) MarshalLogObject(e zapcore.ObjectEncoder) error {
if v == nil {
return nil
}
e.AddString("PauseReason", v.PauseReason.String())
e.AddBool("IsDeficient", v.IsDeficient)
e.AddInt64("BandwidthRquested", v.BandwidthRequested)
e.AddInt64("BandwidthDelta", v.BandwidthDelta)
e.AddInt64("BandwidthNeeded", v.BandwidthNeeded)
e.AddReflected("Bitrates", v.Bitrates)
e.AddReflected("TargetLayer", v.TargetLayer)
e.AddInt32("RequestLayerSpatial", v.RequestLayerSpatial)
e.AddReflected("MaxLayer", v.MaxLayer)
e.AddFloat64("DistanceToDesired", v.DistanceToDesired)
return nil
}
var (
VideoAllocationDefault = VideoAllocation{
PauseReason: VideoPauseReasonFeedDry, // start with no feed till feed is seen
TargetLayer: buffer.InvalidLayer,
RequestLayerSpatial: buffer.InvalidLayerSpatial,
MaxLayer: buffer.InvalidLayer,
}
)
// -------------------------------------------------------------------
type VideoAllocationProvisional struct {
muted bool
pubMuted bool
maxSeenLayer buffer.VideoLayer
availableLayers []int32
bitrates Bitrates
maxLayer buffer.VideoLayer
currentLayer buffer.VideoLayer
allocatedLayer buffer.VideoLayer
}
// -------------------------------------------------------------------
type VideoTransition struct {
From buffer.VideoLayer
To buffer.VideoLayer
BandwidthDelta int64
}
func (v *VideoTransition) String() string {
return fmt.Sprintf("VideoTransition{from: %s, to: %s, del: %d}", v.From, v.To, v.BandwidthDelta)
}
func (v *VideoTransition) MarshalLogObject(e zapcore.ObjectEncoder) error {
if v == nil {
return nil
}
e.AddReflected("From", v.From)
e.AddReflected("To", v.To)
e.AddInt64("BandwidthDelta", v.BandwidthDelta)
return nil
}
// -------------------------------------------------------------------
type TranslationParams struct {
shouldDrop bool
isResuming bool
isSwitching bool
rtp TranslationParamsRTP
ddBytes []byte
marker bool
}
// -------------------------------------------------------------------
type ForwarderState struct {
Started bool
ReferenceLayerSpatial int32
PreStartTime time.Time
ExtFirstTS uint64
RefTSOffset uint64
RTP RTPMungerState
Codec interface{}
}
func (f ForwarderState) String() string {
codecString := ""
switch codecState := f.Codec.(type) {
case codecmunger.VP8State:
codecString = codecState.String()
}
return fmt.Sprintf("ForwarderState{started: %v, referenceLayerSpatial: %d, preStartTime: %s, extFirstTS: %d, refTSOffset: %d, rtp: %s, codec: %s}",
f.Started,
f.ReferenceLayerSpatial,
f.PreStartTime.String(),
f.ExtFirstTS,
f.RefTSOffset,
f.RTP.String(),
codecString,
)
}
// -------------------------------------------------------------------
type Forwarder struct {
lock sync.RWMutex
codec webrtc.RTPCodecCapability
kind webrtc.RTPCodecType
logger logger.Logger
skipReferenceTS bool
getExpectedRTPTimestamp func(at time.Time) (uint64, error)
muted bool
pubMuted bool
resumeBehindThreshold float64
started bool
preStartTime time.Time
extFirstTS uint64
lastSSRC uint32
referenceLayerSpatial int32
refTSOffset uint64
refSenderReports [buffer.DefaultMaxLayerSpatial + 1]*buffer.RTCPSenderReportData
refIsSVC bool
provisional *VideoAllocationProvisional
lastAllocation VideoAllocation
rtpMunger *RTPMunger
vls videolayerselector.VideoLayerSelector
codecMunger codecmunger.CodecMunger
}
func NewForwarder(
kind webrtc.RTPCodecType,
logger logger.Logger,
skipReferenceTS bool,
getExpectedRTPTimestamp func(at time.Time) (uint64, error),
) *Forwarder {
f := &Forwarder{
kind: kind,
logger: logger,
skipReferenceTS: skipReferenceTS,
getExpectedRTPTimestamp: getExpectedRTPTimestamp,
referenceLayerSpatial: buffer.InvalidLayerSpatial,
lastAllocation: VideoAllocationDefault,
rtpMunger: NewRTPMunger(logger),
vls: videolayerselector.NewNull(logger),
codecMunger: codecmunger.NewNull(logger),
}
if f.kind == webrtc.RTPCodecTypeVideo {
f.vls.SetMaxTemporal(buffer.DefaultMaxLayerTemporal)
}
return f
}
func (f *Forwarder) SetMaxPublishedLayer(maxPublishedLayer int32) bool {
f.lock.Lock()
defer f.lock.Unlock()
existingMaxSeen := f.vls.GetMaxSeen()
if maxPublishedLayer <= existingMaxSeen.Spatial {
return false
}
f.vls.SetMaxSeenSpatial(maxPublishedLayer)
f.logger.Debugw("setting max published layer", "layer", maxPublishedLayer)
return true
}
func (f *Forwarder) SetMaxTemporalLayerSeen(maxTemporalLayerSeen int32) bool {
f.lock.Lock()
defer f.lock.Unlock()
existingMaxSeen := f.vls.GetMaxSeen()
if maxTemporalLayerSeen <= existingMaxSeen.Temporal {
return false
}
f.vls.SetMaxSeenTemporal(maxTemporalLayerSeen)
f.logger.Debugw("setting max temporal layer seen", "maxTemporalLayerSeen", maxTemporalLayerSeen)
return true
}
func (f *Forwarder) DetermineCodec(codec webrtc.RTPCodecCapability, extensions []webrtc.RTPHeaderExtensionParameter) {
f.lock.Lock()
defer f.lock.Unlock()
if f.codec.MimeType != "" {
return
}
f.codec = codec
ddAvailable := func(exts []webrtc.RTPHeaderExtensionParameter) bool {
for _, ext := range exts {
if ext.URI == dd.ExtensionURI {
return true
}
}
return false
}
switch strings.ToLower(codec.MimeType) {
case "video/vp8":
f.codecMunger = codecmunger.NewVP8FromNull(f.codecMunger, f.logger)
if f.vls != nil {
f.vls = videolayerselector.NewSimulcastFromNull(f.vls)
} else {
f.vls = videolayerselector.NewSimulcast(f.logger)
}
f.vls.SetTemporalLayerSelector(temporallayerselector.NewVP8(f.logger))
case "video/h264":
if f.vls != nil {
f.vls = videolayerselector.NewSimulcastFromNull(f.vls)
} else {
f.vls = videolayerselector.NewSimulcast(f.logger)
}
case "video/vp9":
isDDAvailable := ddAvailable(extensions)
if isDDAvailable {
if f.vls != nil {
f.vls = videolayerselector.NewDependencyDescriptorFromNull(f.vls)
} else {
f.vls = videolayerselector.NewDependencyDescriptor(f.logger)
}
} else {
if f.vls != nil {
f.vls = videolayerselector.NewVP9FromNull(f.vls)
} else {
f.vls = videolayerselector.NewVP9(f.logger)
}
}
// SVC-TODO: Support for VP9 simulcast. When DD is not available, have to pick selector based on VP9 SVC or Simulcast
case "video/av1":
// DD-TODO : we only enable dd layer selector for av1/vp9 now, in the future we can enable it for vp8 too
isDDAvailable := ddAvailable(extensions)
if isDDAvailable {
if f.vls != nil {
f.vls = videolayerselector.NewDependencyDescriptorFromNull(f.vls)
} else {
f.vls = videolayerselector.NewDependencyDescriptor(f.logger)
}
} else {
if f.vls != nil {
f.vls = videolayerselector.NewSimulcastFromNull(f.vls)
} else {
f.vls = videolayerselector.NewSimulcast(f.logger)
}
}
// SVC-TODO: Support for AV1 Simulcast
}
}
func (f *Forwarder) GetState() ForwarderState {
f.lock.RLock()
defer f.lock.RUnlock()
if !f.started {
return ForwarderState{}
}
return ForwarderState{
Started: f.started,
ReferenceLayerSpatial: f.referenceLayerSpatial,
PreStartTime: f.preStartTime,
ExtFirstTS: f.extFirstTS,
RefTSOffset: f.refTSOffset,
RTP: f.rtpMunger.GetLast(),
Codec: f.codecMunger.GetState(),
}
}
func (f *Forwarder) SeedState(state ForwarderState) {
if !state.Started {
return
}
f.lock.Lock()
defer f.lock.Unlock()
f.rtpMunger.SeedLast(state.RTP)
f.codecMunger.SeedState(state.Codec)
f.started = true
f.referenceLayerSpatial = state.ReferenceLayerSpatial
f.preStartTime = state.PreStartTime
f.extFirstTS = state.ExtFirstTS
f.refTSOffset = state.RefTSOffset
}
func (f *Forwarder) Mute(muted bool, isSubscribeMutable bool) bool {
f.lock.Lock()
defer f.lock.Unlock()
if f.muted == muted {
return false
}
// Do not mute when paused due to bandwidth limitation.
// There are two issues
// 1. Muting means probing cannot happen on this track.
// 2. Muting also triggers notification to publisher about layers this forwarder needs.
// If this forwarder does not need any layer, publisher could turn off all layers.
// So, muting could lead to not being able to restart the track.
// To avoid that, ignore mute when paused due to bandwidth limitations.
//
// NOTE: The above scenario refers to mute getting triggered due
// to video stream visibility changes. When a stream is paused, it is possible
// that the receiver hides the video tile triggering subscription mute.
// The work around here to ignore mute does ignore an intentional mute.
// It could result in some bandwidth consumed for stream without visibility in
// the case of intentional mute.
if muted && !isSubscribeMutable {
f.logger.Debugw("ignoring forwarder mute, paused due to congestion")
return false
}
f.logger.Debugw("setting forwarder mute", "muted", muted)
f.muted = muted
// resync when muted so that sequence numbers do not jump on unmute
if muted {
f.resyncLocked()
}
return true
}
func (f *Forwarder) IsMuted() bool {
f.lock.RLock()
defer f.lock.RUnlock()
return f.muted
}
func (f *Forwarder) PubMute(pubMuted bool) bool {
f.lock.Lock()
defer f.lock.Unlock()
if f.pubMuted == pubMuted {
return false
}
f.logger.Debugw("setting forwarder pub mute", "muted", pubMuted)
f.pubMuted = pubMuted
// resync when pub muted so that sequence numbers do not jump on unmute
if pubMuted {
f.resyncLocked()
}
return true
}
func (f *Forwarder) IsPubMuted() bool {
f.lock.RLock()
defer f.lock.RUnlock()
return f.pubMuted
}
func (f *Forwarder) IsAnyMuted() bool {
f.lock.RLock()
defer f.lock.RUnlock()
return f.muted || f.pubMuted
}
func (f *Forwarder) SetMaxSpatialLayer(spatialLayer int32) (bool, buffer.VideoLayer) {
f.lock.Lock()
defer f.lock.Unlock()
if f.kind == webrtc.RTPCodecTypeAudio {
return false, buffer.InvalidLayer
}
existingMax := f.vls.GetMax()
if spatialLayer == existingMax.Spatial {
return false, existingMax
}
f.logger.Debugw("setting max spatial layer", "layer", spatialLayer)
f.vls.SetMaxSpatial(spatialLayer)
return true, f.vls.GetMax()
}
func (f *Forwarder) SetMaxTemporalLayer(temporalLayer int32) (bool, buffer.VideoLayer) {
f.lock.Lock()
defer f.lock.Unlock()
if f.kind == webrtc.RTPCodecTypeAudio {
return false, buffer.InvalidLayer
}
existingMax := f.vls.GetMax()
if temporalLayer == existingMax.Temporal {
return false, existingMax
}
f.logger.Debugw("setting max temporal layer", "layer", temporalLayer)
f.vls.SetMaxTemporal(temporalLayer)
return true, f.vls.GetMax()
}
func (f *Forwarder) MaxLayer() buffer.VideoLayer {
f.lock.RLock()
defer f.lock.RUnlock()
return f.vls.GetMax()
}
func (f *Forwarder) CurrentLayer() buffer.VideoLayer {
f.lock.RLock()
defer f.lock.RUnlock()
return f.vls.GetCurrent()
}
func (f *Forwarder) TargetLayer() buffer.VideoLayer {
f.lock.RLock()
defer f.lock.RUnlock()
return f.vls.GetTarget()
}
func (f *Forwarder) GetMaxSubscribedSpatial() int32 {
f.lock.RLock()
defer f.lock.RUnlock()
layer := buffer.InvalidLayerSpatial // covers muted case
if !f.muted {
layer = f.vls.GetMax().Spatial
// If current is higher, mark the current layer as max subscribed layer
// to prevent the current layer from stopping before forwarder switches
// to the new and lower max layer,
if layer < f.vls.GetCurrent().Spatial {
layer = f.vls.GetCurrent().Spatial
}
}
return layer
}
func (f *Forwarder) SetRefSenderReport(isSVC bool, layer int32, srData *buffer.RTCPSenderReportData) {
f.lock.Lock()
defer f.lock.Unlock()
f.refIsSVC = isSVC
if isSVC {
layer = 0
}
if layer >= 0 && int(layer) < len(f.refSenderReports) {
f.refSenderReports[layer] = srData
}
}
func (f *Forwarder) clearRefSenderReportsLocked() {
// On (re)start of fowarding, clear any old publisher sender reports.
// This is done to prevent use of potentially stale publisher sender reports.
//
// It is possible to implement mute using pause/unpause
// which can implemented using a replaceTrack(null)/replaceTrack(track).
// In those cases, the RTP time stamp may not jump across
// the mute/pause valley (for the time it is replaced with null track).
// So, relying on a report that happened before unmute/unpause
// could result in incorrect RTCP sender report on subscriber side.
//
// It could happen like this
// 1. Normal operation: publisher sending sender reports and
// suscribers use reports from publisher to calculate and send
// RTCP sender report.
// 2. Publisher pauses: there are no more reports.
// 3. When paused, subscriber can still use the publisher side sender
// report to send reports. Although the time since last publisher
// sender report is increasing, the reports are correct though.
// 4. Publisher unpauses after 20 seconds. But, it may not have advanced
// RTP Timestamp by that much. Let us say, it advances only by 5 seconds.
// 5. When subscriber starts forwarding packets, it will calculate
// a new time stamp offset to adjust to the new time stamp of publisher.
// 6. But, when that same offset is used on an old publisher sender report
// (i. e. a report from before the pause), the subscriber side sender
// reports jumps ahead in time by 15 seconds.
//
// By clearing sender report on (re)start of a stream, subscribers will wait for a fresh report
// after unmute to send sender report.
for layer := int32(0); layer < buffer.DefaultMaxLayerSpatial+1; layer++ {
f.refSenderReports[layer] = nil
}
}
func (f *Forwarder) GetSenderReportParams() (int32, uint64, *buffer.RTCPSenderReportData) {
f.lock.RLock()
defer f.lock.RUnlock()
if f.kind == webrtc.RTPCodecTypeAudio {
return 0, f.rtpMunger.GetPinnedTSOffset(), f.refSenderReports[0]
}
currentLayerSpatial := f.vls.GetCurrent().Spatial
if currentLayerSpatial < 0 || currentLayerSpatial > buffer.DefaultMaxLayerSpatial {
return currentLayerSpatial, f.rtpMunger.GetPinnedTSOffset(), nil
}
refSenderReport := f.refSenderReports[currentLayerSpatial]
if f.refIsSVC {
refSenderReport = f.refSenderReports[0]
}
return currentLayerSpatial, f.rtpMunger.GetPinnedTSOffset(), refSenderReport
}
func (f *Forwarder) isDeficientLocked() bool {
return f.lastAllocation.IsDeficient
}
func (f *Forwarder) IsDeficient() bool {
f.lock.RLock()
defer f.lock.RUnlock()
return f.isDeficientLocked()
}
func (f *Forwarder) PauseReason() VideoPauseReason {
f.lock.RLock()
defer f.lock.RUnlock()
return f.lastAllocation.PauseReason
}
func (f *Forwarder) BandwidthRequested(brs Bitrates) int64 {
f.lock.RLock()
defer f.lock.RUnlock()
return getBandwidthNeeded(brs, f.vls.GetTarget(), f.lastAllocation.BandwidthRequested)
}
func (f *Forwarder) DistanceToDesired(availableLayers []int32, brs Bitrates) float64 {
f.lock.RLock()
defer f.lock.RUnlock()
return getDistanceToDesired(
f.muted,
f.pubMuted,
f.vls.GetMaxSeen(),
availableLayers,
brs,
f.vls.GetTarget(),
f.vls.GetMax(),
)
}
func (f *Forwarder) GetOptimalBandwidthNeeded(brs Bitrates) int64 {
f.lock.RLock()
defer f.lock.RUnlock()
return getOptimalBandwidthNeeded(f.muted, f.pubMuted, f.vls.GetMaxSeen().Spatial, brs, f.vls.GetMax())
}
func (f *Forwarder) AllocateOptimal(availableLayers []int32, brs Bitrates, allowOvershoot bool) VideoAllocation {
f.lock.Lock()
defer f.lock.Unlock()
if f.kind == webrtc.RTPCodecTypeAudio {
return f.lastAllocation
}
maxLayer := f.vls.GetMax()
maxSeenLayer := f.vls.GetMaxSeen()
currentLayer := f.vls.GetCurrent()
requestSpatial := f.vls.GetRequestSpatial()
alloc := VideoAllocation{
PauseReason: VideoPauseReasonNone,
Bitrates: brs,
TargetLayer: buffer.InvalidLayer,
RequestLayerSpatial: requestSpatial,
MaxLayer: maxLayer,
}
optimalBandwidthNeeded := getOptimalBandwidthNeeded(f.muted, f.pubMuted, maxSeenLayer.Spatial, brs, maxLayer)
if optimalBandwidthNeeded == 0 {
alloc.PauseReason = VideoPauseReasonFeedDry
}
alloc.BandwidthNeeded = optimalBandwidthNeeded
getMaxTemporal := func() int32 {
maxTemporal := maxLayer.Temporal
if maxSeenLayer.Temporal != buffer.InvalidLayerTemporal && maxSeenLayer.Temporal < maxTemporal {
maxTemporal = maxSeenLayer.Temporal
}
return maxTemporal
}
opportunisticAlloc := func() {
// opportunistically latch on to anything
maxSpatial := maxLayer.Spatial
if allowOvershoot && f.vls.IsOvershootOkay() && maxSeenLayer.Spatial > maxSpatial {
maxSpatial = maxSeenLayer.Spatial
}
alloc.TargetLayer = buffer.VideoLayer{
Spatial: int32(math.Min(float64(maxSeenLayer.Spatial), float64(maxSpatial))),
Temporal: getMaxTemporal(),
}
}
switch {
case !maxLayer.IsValid() || maxSeenLayer.Spatial == buffer.InvalidLayerSpatial:
// nothing to do when max layers are not valid OR max published layer is invalid
case f.muted:
alloc.PauseReason = VideoPauseReasonMuted
case f.pubMuted:
alloc.PauseReason = VideoPauseReasonPubMuted
default:
// lots of different events could end up here
// 1. Publisher side layer resuming/stopping
// 2. Bitrate becoming available
// 3. New max published spatial layer or max temporal layer seen
// 4. Subscriber layer changes
//
// to handle all of the above
// 1. Find highest that can be requested - takes into account available layers and overshoot.
// This should catch scenarios like layers resuming/stopping.
// 2. If current is a valid layer, check against currently available layers and continue at current
// if possible. Else, choose the highest available layer as the next target.
// 3. If current is not valid, set next target to be opportunistic.
maxLayerSpatialLimit := int32(math.Min(float64(maxLayer.Spatial), float64(maxSeenLayer.Spatial)))
highestAvailableLayer := buffer.InvalidLayerSpatial
requestLayerSpatial := buffer.InvalidLayerSpatial
for _, al := range availableLayers {
if al > requestLayerSpatial && al <= maxLayerSpatialLimit {
requestLayerSpatial = al
}
if al > highestAvailableLayer {
highestAvailableLayer = al
}
}
if requestLayerSpatial == buffer.InvalidLayerSpatial && highestAvailableLayer != buffer.InvalidLayerSpatial && allowOvershoot && f.vls.IsOvershootOkay() {
requestLayerSpatial = highestAvailableLayer
}
if currentLayer.IsValid() {
if (requestLayerSpatial == requestSpatial && currentLayer.Spatial == requestSpatial) || requestLayerSpatial == buffer.InvalidLayerSpatial {
// 1. current is locked to desired, stay there
// OR
// 2. feed may be dry, let it continue at current layer if valid.
// covers the cases of
// 1. mis-detection of layer stop - can continue streaming
// 2. current layer resuming - can latch on when it starts
alloc.TargetLayer = buffer.VideoLayer{
Spatial: currentLayer.Spatial,
Temporal: getMaxTemporal(),
}
} else {
// current layer has stopped, switch to highest available
alloc.TargetLayer = buffer.VideoLayer{
Spatial: requestLayerSpatial,
Temporal: getMaxTemporal(),
}
}
alloc.RequestLayerSpatial = alloc.TargetLayer.Spatial
} else {
// opportunistically latch on to anything
opportunisticAlloc()
if requestLayerSpatial == buffer.InvalidLayerSpatial {
alloc.RequestLayerSpatial = maxLayerSpatialLimit
} else {
alloc.RequestLayerSpatial = requestLayerSpatial
}
}
}
if !alloc.TargetLayer.IsValid() {
alloc.TargetLayer = buffer.InvalidLayer
alloc.RequestLayerSpatial = buffer.InvalidLayerSpatial
}
if alloc.TargetLayer.IsValid() {
alloc.BandwidthRequested = optimalBandwidthNeeded
}
alloc.BandwidthDelta = alloc.BandwidthRequested - getBandwidthNeeded(brs, f.vls.GetTarget(), f.lastAllocation.BandwidthRequested)
alloc.DistanceToDesired = getDistanceToDesired(
f.muted,
f.pubMuted,
f.vls.GetMaxSeen(),
availableLayers,
brs,
alloc.TargetLayer,
f.vls.GetMax(),
)
return f.updateAllocation(alloc, "optimal")
}
func (f *Forwarder) ProvisionalAllocatePrepare(availableLayers []int32, bitrates Bitrates) {
f.lock.Lock()
defer f.lock.Unlock()
f.provisional = &VideoAllocationProvisional{
allocatedLayer: buffer.InvalidLayer,
muted: f.muted,
pubMuted: f.pubMuted,
maxSeenLayer: f.vls.GetMaxSeen(),
bitrates: bitrates,
maxLayer: f.vls.GetMax(),
currentLayer: f.vls.GetCurrent(),
}
f.provisional.availableLayers = make([]int32, len(availableLayers))
copy(f.provisional.availableLayers, availableLayers)
}
func (f *Forwarder) ProvisionalAllocateReset() {
f.lock.Lock()
defer f.lock.Unlock()
f.provisional.allocatedLayer = buffer.InvalidLayer
}
func (f *Forwarder) ProvisionalAllocate(availableChannelCapacity int64, layer buffer.VideoLayer, allowPause bool, allowOvershoot bool) (bool, int64) {
f.lock.Lock()
defer f.lock.Unlock()
if f.provisional.muted ||
f.provisional.pubMuted ||
f.provisional.maxSeenLayer.Spatial == buffer.InvalidLayerSpatial ||
!f.provisional.maxLayer.IsValid() ||
((!allowOvershoot || !f.vls.IsOvershootOkay()) && layer.GreaterThan(f.provisional.maxLayer)) {
return false, 0
}
requiredBitrate := f.provisional.bitrates[layer.Spatial][layer.Temporal]
if requiredBitrate == 0 {
return false, 0
}
alreadyAllocatedBitrate := int64(0)
if f.provisional.allocatedLayer.IsValid() {
alreadyAllocatedBitrate = f.provisional.bitrates[f.provisional.allocatedLayer.Spatial][f.provisional.allocatedLayer.Temporal]
}
// a layer under maximum fits, take it
if !layer.GreaterThan(f.provisional.maxLayer) && requiredBitrate <= (availableChannelCapacity+alreadyAllocatedBitrate) {
f.provisional.allocatedLayer = layer
return true, requiredBitrate - alreadyAllocatedBitrate
}
//
// Given layer does not fit.
//
// Could be one of
// 1. a layer below maximum that does not fit
// 2. a layer above maximum which may or may not fit, but overshoot is allowed.
// In any of those cases, take the lowest possible layer if pause is not allowed
//
if !allowPause && (!f.provisional.allocatedLayer.IsValid() || !layer.GreaterThan(f.provisional.allocatedLayer)) {
f.provisional.allocatedLayer = layer
return true, requiredBitrate - alreadyAllocatedBitrate
}
return false, 0
}
func (f *Forwarder) ProvisionalAllocateGetCooperativeTransition(allowOvershoot bool) (VideoTransition, []int32, Bitrates) {
//
// This is called when a track needs a change (could be mute/unmute, subscribed layers changed, published layers changed)
// when channel is congested.
//
// The goal is to provide a co-operative transition. Co-operative stream allocation aims to keep all the streams active
// as much as possible.
//
// When channel is congested, effecting a transition which will consume more bits will lead to more congestion.
// So, this routine does the following
// 1. When muting, it is not going to increase consumption.
// 2. If the stream is currently active and the transition needs more bits (higher layers = more bits), do not make the up move.
// The higher layer requirement could be due to a new published layer becoming available or subscribed layers changing.
// 3. If the new target layers are lower than current target, take the move down and save bits.
// 4. If not currently streaming, find the minimum layers that can unpause the stream.
//
// To summarize, co-operative streaming means
// - Try to keep tracks streaming, i.e. no pauses at the expense of some streams not being at optimal layers
// - Do not make an upgrade as it could affect other tracks
//
f.lock.Lock()
defer f.lock.Unlock()
existingTargetLayer := f.vls.GetTarget()
if f.provisional.muted || f.provisional.pubMuted {
f.provisional.allocatedLayer = buffer.InvalidLayer
return VideoTransition{
From: existingTargetLayer,
To: f.provisional.allocatedLayer,
BandwidthDelta: -getBandwidthNeeded(f.provisional.bitrates, existingTargetLayer, f.lastAllocation.BandwidthRequested),
}, f.provisional.availableLayers, f.provisional.bitrates
}
// check if we should preserve current target
if existingTargetLayer.IsValid() {
// what is the highest that is available
maximalLayer := buffer.InvalidLayer
maximalBandwidthRequired := int64(0)
for s := f.provisional.maxLayer.Spatial; s >= 0; s-- {
for t := f.provisional.maxLayer.Temporal; t >= 0; t-- {
if f.provisional.bitrates[s][t] != 0 {
maximalLayer = buffer.VideoLayer{Spatial: s, Temporal: t}
maximalBandwidthRequired = f.provisional.bitrates[s][t]
break
}
}
if maximalBandwidthRequired != 0 {
break
}
}
if maximalLayer.IsValid() {
if !existingTargetLayer.GreaterThan(maximalLayer) && f.provisional.bitrates[existingTargetLayer.Spatial][existingTargetLayer.Temporal] != 0 {
// currently streaming and maybe wanting an upgrade (existingTargetLayer <= maximalLayer),
// just preserve current target in the cooperative scheme of things
f.provisional.allocatedLayer = existingTargetLayer
return VideoTransition{
From: existingTargetLayer,
To: existingTargetLayer,
BandwidthDelta: 0,
}, f.provisional.availableLayers, f.provisional.bitrates
}
if existingTargetLayer.GreaterThan(maximalLayer) {
// maximalLayer < existingTargetLayer, make the down move
f.provisional.allocatedLayer = maximalLayer
return VideoTransition{
From: existingTargetLayer,
To: maximalLayer,
BandwidthDelta: maximalBandwidthRequired - getBandwidthNeeded(f.provisional.bitrates, existingTargetLayer, f.lastAllocation.BandwidthRequested),
}, f.provisional.availableLayers, f.provisional.bitrates
}
}
}
findNextLayer := func(
minSpatial, maxSpatial int32,
minTemporal, maxTemporal int32,
) (buffer.VideoLayer, int64) {
layers := buffer.InvalidLayer
bw := int64(0)
for s := minSpatial; s <= maxSpatial; s++ {
for t := minTemporal; t <= maxTemporal; t++ {
if f.provisional.bitrates[s][t] != 0 {
layers = buffer.VideoLayer{Spatial: s, Temporal: t}
bw = f.provisional.bitrates[s][t]
break
}
}
if bw != 0 {
break
}
}
return layers, bw
}
targetLayer := buffer.InvalidLayer
bandwidthRequired := int64(0)
if !existingTargetLayer.IsValid() {
// currently not streaming, find minimal
// NOTE: a layer in feed could have paused and there could be other options than going back to minimal,
// but the cooperative scheme knocks things back to minimal
targetLayer, bandwidthRequired = findNextLayer(
0, f.provisional.maxLayer.Spatial,
0, f.provisional.maxLayer.Temporal,
)
// could not find a minimal layer, overshoot if allowed
if bandwidthRequired == 0 && f.provisional.maxLayer.IsValid() && allowOvershoot && f.vls.IsOvershootOkay() {
targetLayer, bandwidthRequired = findNextLayer(
f.provisional.maxLayer.Spatial+1, buffer.DefaultMaxLayerSpatial,
0, buffer.DefaultMaxLayerTemporal,
)
}
}
// if nothing available, just leave target at current to enable opportunistic forwarding in case current resumes