forked from livekit/livekit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
forwarder.go
1587 lines (1322 loc) · 44.8 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
package sfu
import (
"fmt"
"math"
"strings"
"sync"
"time"
"github.com/pion/webrtc/v3"
"github.com/abdulhaseeb08/protocol/logger"
"github.com/abdulhaseeb08/livekit-server/pkg/sfu/buffer"
dd "github.com/abdulhaseeb08/livekit-server/pkg/sfu/dependencydescriptor"
)
//
// Forwarder
//
const (
FlagPauseOnDowngrade = true
FlagFilterRTX = true
TransitionCostSpatial = 10
)
// -------------------------------------------------------------------
type ForwardingStatus int
const (
ForwardingStatusOff ForwardingStatus = iota
ForwardingStatusPartial
ForwardingStatusOptimal
)
// -------------------------------------------------------------------
type VideoStreamingChange int
const (
VideoStreamingChangeNone VideoStreamingChange = iota
VideoStreamingChangePausing
VideoStreamingChangeResuming
)
func (v VideoStreamingChange) String() string {
switch v {
case VideoStreamingChangeNone:
return "NONE"
case VideoStreamingChangePausing:
return "PAUSING"
case VideoStreamingChangeResuming:
return "RESUMING"
default:
return fmt.Sprintf("%d", int(v))
}
}
// -------------------------------------------------------------------
type VideoAllocationState int
const (
VideoAllocationStateNone VideoAllocationState = iota
VideoAllocationStateMuted
VideoAllocationStateFeedDry
VideoAllocationStateAwaitingMeasurement
VideoAllocationStateOptimal
VideoAllocationStateDeficient
)
func (v VideoAllocationState) String() string {
switch v {
case VideoAllocationStateNone:
return "NONE"
case VideoAllocationStateMuted:
return "MUTED"
case VideoAllocationStateFeedDry:
return "FEED_DRY"
case VideoAllocationStateAwaitingMeasurement:
return "AWAITING_MEASUREMENT"
case VideoAllocationStateOptimal:
return "OPTIMAL"
case VideoAllocationStateDeficient:
return "DEFICIENT"
default:
return fmt.Sprintf("%d", int(v))
}
}
type VideoAllocation struct {
state VideoAllocationState
change VideoStreamingChange
bandwidthRequested int64
bandwidthDelta int64
availableLayers []int32
exemptedLayers []int32
bitrates Bitrates
targetLayers VideoLayers
distanceToDesired int32
}
func (v VideoAllocation) String() string {
return fmt.Sprintf("VideoAllocation{state: %s, change: %s, bw: %d, del: %d, avail: %+v, exempt: %+v, rates: %+v, target: %s, dist: %d}",
v.state, v.change, v.bandwidthRequested, v.bandwidthDelta, v.availableLayers, v.exemptedLayers, v.bitrates, v.targetLayers, v.distanceToDesired)
}
var (
VideoAllocationDefault = VideoAllocation{
targetLayers: InvalidLayers,
}
)
// -------------------------------------------------------------------
type VideoAllocationProvisional struct {
muted bool
bitrates Bitrates
availableLayers []int32
exemptedLayers []int32
maxLayers VideoLayers
allocatedLayers VideoLayers
}
// -------------------------------------------------------------------
type VideoTransition struct {
from VideoLayers
to VideoLayers
bandwidthDelta int64
}
func (v VideoTransition) String() string {
return fmt.Sprintf("VideoTransition{from: %s, to: %s, del: %d}", v.from, v.to, v.bandwidthDelta)
}
// -------------------------------------------------------------------
type TranslationParams struct {
shouldDrop bool
isDroppingRelevant bool
isSwitchingToMaxLayer bool
rtp *TranslationParamsRTP
vp8 *TranslationParamsVP8
ddExtension *dd.DependencyDescriptorExtension
marker bool
// indicates this frame has 'Switch' decode indication for target layer
// TODO : in theory, we need check frame chain is not broken for the target
// but we don't have frame queue now, so just use decode target indication
switchingToTargetLayer bool
}
// -------------------------------------------------------------------
type VideoLayers = buffer.VideoLayer
const (
InvalidLayerSpatial = buffer.InvalidLayerSpatial
InvalidLayerTemporal = buffer.InvalidLayerTemporal
DefaultMaxLayerSpatial = buffer.DefaultMaxLayerSpatial
DefaultMaxLayerTemporal = buffer.DefaultMaxLayerTemporal
)
var (
InvalidLayers = buffer.InvalidLayers
)
// -------------------------------------------------------------------
type ForwarderState struct {
LastTSCalc int64
RTP RTPMungerState
VP8 VP8MungerState
}
func (f ForwarderState) String() string {
return fmt.Sprintf("ForwarderState{lTSCalc: %d, rtp: %s, vp8: %s}",
f.LastTSCalc, f.RTP.String(), f.VP8.String())
}
// -------------------------------------------------------------------
type Forwarder struct {
lock sync.RWMutex
codec webrtc.RTPCodecCapability
kind webrtc.RTPCodecType
logger logger.Logger
muted bool
started bool
lastSSRC uint32
lTSCalc int64
maxLayers VideoLayers
currentLayers VideoLayers
targetLayers VideoLayers
provisional *VideoAllocationProvisional
lastAllocation VideoAllocation
availableLayers []int32
exemptedLayers []int32
rtpMunger *RTPMunger
vp8Munger *VP8Munger
isTemporalSupported bool
ddLayerSelector *DDVideoLayerSelector
}
func NewForwarder(kind webrtc.RTPCodecType, logger logger.Logger) *Forwarder {
f := &Forwarder{
kind: kind,
logger: logger,
// start off with nothing, let streamallocator set things
currentLayers: InvalidLayers,
targetLayers: InvalidLayers,
lastAllocation: VideoAllocationDefault,
rtpMunger: NewRTPMunger(logger),
}
if f.kind == webrtc.RTPCodecTypeVideo {
f.maxLayers = VideoLayers{Spatial: InvalidLayerSpatial, Temporal: DefaultMaxLayerTemporal}
} else {
f.maxLayers = InvalidLayers
}
return f
}
func (f *Forwarder) DetermineCodec(codec webrtc.RTPCodecCapability) {
f.lock.Lock()
defer f.lock.Unlock()
if f.codec.MimeType != "" {
return
}
f.codec = codec
switch strings.ToLower(codec.MimeType) {
case "video/vp8":
f.isTemporalSupported = true
f.vp8Munger = NewVP8Munger(f.logger)
case "video/av1":
// TODO : we only enable dd layer selector for av1 now, at future we can
// enable it for vp9 too
f.ddLayerSelector = NewDDVideoLayerSelector(f.logger)
}
}
func (f *Forwarder) GetState() ForwarderState {
f.lock.RLock()
defer f.lock.RUnlock()
state := ForwarderState{
LastTSCalc: f.lTSCalc,
RTP: f.rtpMunger.GetLast(),
}
if f.vp8Munger != nil {
state.VP8 = f.vp8Munger.GetLast()
}
return state
}
func (f *Forwarder) SeedState(state ForwarderState) {
f.lock.Lock()
defer f.lock.Unlock()
f.lTSCalc = state.LastTSCalc
f.rtpMunger.SeedLast(state.RTP)
if f.vp8Munger != nil {
f.vp8Munger.SeedLast(state.VP8)
}
f.started = true
}
func (f *Forwarder) Mute(muted bool) (bool, VideoLayers) {
f.lock.Lock()
defer f.lock.Unlock()
if f.muted == muted {
return false, f.maxLayers
}
f.logger.Infow("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, f.maxLayers
}
func (f *Forwarder) IsMuted() bool {
f.lock.RLock()
defer f.lock.RUnlock()
return f.muted
}
func (f *Forwarder) SetMaxSpatialLayer(spatialLayer int32) (bool, VideoLayers, VideoLayers) {
f.lock.Lock()
defer f.lock.Unlock()
if f.kind == webrtc.RTPCodecTypeAudio || spatialLayer == f.maxLayers.Spatial {
return false, f.maxLayers, f.currentLayers
}
f.logger.Infow("setting max spatial layer", "layer", spatialLayer)
f.maxLayers.Spatial = spatialLayer
return true, f.maxLayers, f.currentLayers
}
func (f *Forwarder) SetMaxTemporalLayer(temporalLayer int32) (bool, VideoLayers, VideoLayers) {
f.lock.Lock()
defer f.lock.Unlock()
if f.kind == webrtc.RTPCodecTypeAudio || temporalLayer == f.maxLayers.Temporal {
return false, f.maxLayers, f.currentLayers
}
f.logger.Infow("setting max temporal layer", "layer", temporalLayer)
f.maxLayers.Temporal = temporalLayer
return true, f.maxLayers, f.currentLayers
}
func (f *Forwarder) MaxLayers() VideoLayers {
f.lock.RLock()
defer f.lock.RUnlock()
return f.maxLayers
}
func (f *Forwarder) CurrentLayers() VideoLayers {
f.lock.RLock()
defer f.lock.RUnlock()
return f.currentLayers
}
func (f *Forwarder) TargetLayers() VideoLayers {
f.lock.RLock()
defer f.lock.RUnlock()
return f.targetLayers
}
func (f *Forwarder) GetForwardingStatus() ForwardingStatus {
f.lock.RLock()
defer f.lock.RUnlock()
if f.muted || len(f.availableLayers) == 0 {
return ForwardingStatusOptimal
}
if f.targetLayers == InvalidLayers {
return ForwardingStatusOff
}
if f.targetLayers.Spatial < f.maxLayers.Spatial && f.targetLayers.Spatial < f.availableLayers[len(f.availableLayers)-1] {
return ForwardingStatusPartial
}
return ForwardingStatusOptimal
}
func (f *Forwarder) IsReducedQuality() (int32, bool) {
f.lock.RLock()
defer f.lock.RUnlock()
if f.muted || len(f.availableLayers) == 0 || f.targetLayers.Spatial == InvalidLayerSpatial {
return 0, false
}
if f.currentLayers.Spatial != f.targetLayers.Spatial {
//
// Waiting for layer lock, do not declare reduced quality.
// Note the target might actually be a lower layer than current.
//
return 0, false
}
distance := f.maxLayers.Spatial - f.currentLayers.Spatial
if distance < 0 {
distance = 0
}
return distance, f.lastAllocation.state == VideoAllocationStateDeficient
}
func (f *Forwarder) UpTrackLayersChange(availableLayers []int32, exemptedLayers []int32) {
f.lock.Lock()
defer f.lock.Unlock()
if len(availableLayers) > 0 {
f.availableLayers = make([]int32, len(availableLayers))
copy(f.availableLayers, availableLayers)
} else {
f.availableLayers = nil
}
if len(exemptedLayers) > 0 {
f.exemptedLayers = make([]int32, len(exemptedLayers))
copy(f.exemptedLayers, exemptedLayers)
} else {
f.exemptedLayers = nil
}
}
func (f *Forwarder) getOptimalBandwidthNeeded(brs Bitrates, maxLayers VideoLayers) int64 {
if f.muted {
return 0
}
for i := maxLayers.Spatial; i >= 0; i-- {
for j := maxLayers.Temporal; j >= 0; j-- {
if brs[i][j] == 0 {
continue
}
return brs[i][j]
}
}
return 0
}
func (f *Forwarder) bitrateAvailable(brs Bitrates) bool {
neededLayers := 0
bitrateAvailableLayers := 0
for _, layer := range f.availableLayers {
if layer > f.maxLayers.Spatial {
continue
}
//
// Layers could be exempted from stream tracker.
// If such a layer actually stops, it will not
// be removed from available layers as it is exempt.
// But, it could have zero bit rate as it actually stopped.
// So, do not take exempt layers into bitrate availability condition.
//
exempt := false
for _, el := range f.exemptedLayers {
if layer == el {
exempt = true
break
}
}
if exempt {
continue
}
neededLayers++
for t := f.maxLayers.Temporal; t >= 0; t-- {
if brs[layer][t] != 0 {
bitrateAvailableLayers++
break
}
}
}
return bitrateAvailableLayers == neededLayers
}
func (f *Forwarder) getDistanceToDesired(brs Bitrates, targetLayers VideoLayers, maxLayers VideoLayers) int32 {
if f.muted {
return 0
}
found := false
distance := int32(0)
for s := maxLayers.Spatial; s >= 0; s-- {
for t := maxLayers.Temporal; t >= 0; t-- {
if brs[s][t] == 0 {
continue
}
if s == targetLayers.Spatial && t == targetLayers.Temporal {
found = true
break
}
distance++
}
if found {
break
}
}
// maybe overshooting
if !found && targetLayers.IsValid() {
distance = 0
for s := targetLayers.Spatial; s > f.maxLayers.Spatial; s-- {
for t := f.maxLayers.Temporal; t >= 0; t-- {
if targetLayers.Temporal < t || brs[s][t] == 0 {
continue
}
distance--
}
}
}
return distance
}
func (f *Forwarder) IsDeficient() bool {
f.lock.RLock()
defer f.lock.RUnlock()
return f.lastAllocation.state == VideoAllocationStateDeficient
}
func (f *Forwarder) BandwidthRequested(brs Bitrates) int64 {
f.lock.RLock()
defer f.lock.RUnlock()
if f.targetLayers == InvalidLayers {
return 0
}
return brs[f.targetLayers.Spatial][f.targetLayers.Temporal]
}
func (f *Forwarder) DistanceToDesired() int32 {
f.lock.RLock()
defer f.lock.RUnlock()
return f.lastAllocation.distanceToDesired
}
func (f *Forwarder) AllocateOptimal(brs Bitrates, allowOvershoot bool) VideoAllocation {
f.lock.Lock()
defer f.lock.Unlock()
if f.kind == webrtc.RTPCodecTypeAudio {
return f.lastAllocation
}
alloc := VideoAllocation{
availableLayers: f.availableLayers,
exemptedLayers: f.exemptedLayers,
bitrates: brs,
targetLayers: InvalidLayers,
}
switch {
case f.muted:
alloc.state = VideoAllocationStateMuted
case len(f.availableLayers) == 0:
// feed is dry
alloc.state = VideoAllocationStateFeedDry
case !f.bitrateAvailable(brs):
// feed bitrate not yet calculated for all available layers
alloc.state = VideoAllocationStateAwaitingMeasurement
//
// Resume with the highest layer available <= max subscribed layer
// If already resumed, move allocation to the highest available layer <= max subscribed layer
//
alloc.targetLayers = VideoLayers{
Spatial: int32(math.Min(float64(f.maxLayers.Spatial), float64(f.availableLayers[len(f.availableLayers)-1]))),
Temporal: int32(math.Max(0, float64(f.maxLayers.Temporal))),
}
default:
// allocate best layer available
for s := f.maxLayers.Spatial; s >= 0; s-- {
for t := f.maxLayers.Temporal; t >= 0; t-- {
if brs[s][t] == 0 {
continue
}
alloc.targetLayers = VideoLayers{
Spatial: s,
Temporal: t,
}
alloc.bandwidthRequested = brs[s][t]
alloc.state = VideoAllocationStateOptimal
break
}
if alloc.bandwidthRequested != 0 {
break
}
}
if alloc.bandwidthRequested == 0 && f.maxLayers.IsValid() && allowOvershoot {
// if we cannot allocate anything below max layer,
// look for a layer above. It is okay to overshoot
// in optimal allocation (i.e. no bandwidth restrictions).
// It is possible that clients send only a higher layer.
// To accommodate cases like that, try finding a layer
// above the requested maximum to ensure streaming
for s := f.maxLayers.Spatial + 1; s <= DefaultMaxLayerSpatial; s++ {
for t := int32(0); t <= DefaultMaxLayerTemporal; t++ {
if brs[s][t] == 0 {
continue
}
alloc.targetLayers = VideoLayers{
Spatial: s,
Temporal: t,
}
alloc.bandwidthRequested = brs[s][t]
alloc.state = VideoAllocationStateOptimal
f.logger.Infow("allowing overshoot", "maxLayer", f.maxLayers, "targetLayers", alloc.targetLayers)
break
}
if alloc.bandwidthRequested != 0 {
break
}
}
}
if alloc.bandwidthRequested == 0 && f.maxLayers.IsValid() {
// if overshoot was allowed and it did not also find a layer,
// keep target at exempted layer (if available) and the current layer is at that level.
// i. e. exempted layer may really have stopped, so a layer switch to an exempted layer should
// not happen as layer switch will send PLI requests. Just letting it continue at the current
// layer if the current is exempted will protect against any stream tracker misdetects
// OR latch on to the layer quicker when it restarts
if f.currentLayers.IsValid() {
for _, s := range f.exemptedLayers {
if s <= f.maxLayers.Spatial && f.currentLayers.Spatial == s {
alloc.targetLayers = f.currentLayers
alloc.bandwidthRequested = brs[alloc.targetLayers.Spatial][alloc.targetLayers.Temporal]
alloc.state = VideoAllocationStateDeficient
break
}
}
}
}
if !alloc.targetLayers.IsValid() && f.maxLayers.IsValid() {
alloc.state = VideoAllocationStateDeficient
}
}
if !alloc.targetLayers.IsValid() {
alloc.targetLayers = InvalidLayers
}
alloc.bandwidthDelta = alloc.bandwidthRequested - f.lastAllocation.bandwidthRequested
alloc.distanceToDesired = f.getDistanceToDesired(brs, alloc.targetLayers, f.maxLayers)
return f.updateAllocation(alloc, "optimal")
}
func (f *Forwarder) ProvisionalAllocatePrepare(bitrates Bitrates) {
f.lock.Lock()
defer f.lock.Unlock()
f.provisional = &VideoAllocationProvisional{
allocatedLayers: InvalidLayers,
muted: f.muted,
bitrates: bitrates,
maxLayers: f.maxLayers,
}
if len(f.availableLayers) > 0 {
f.provisional.availableLayers = make([]int32, len(f.availableLayers))
copy(f.provisional.availableLayers, f.availableLayers)
}
if len(f.exemptedLayers) > 0 {
f.provisional.exemptedLayers = make([]int32, len(f.exemptedLayers))
copy(f.provisional.exemptedLayers, f.exemptedLayers)
}
}
func (f *Forwarder) ProvisionalAllocate(availableChannelCapacity int64, layers VideoLayers, allowPause bool, allowOvershoot bool) int64 {
f.lock.Lock()
defer f.lock.Unlock()
if f.provisional.muted || !f.provisional.maxLayers.IsValid() || (!allowOvershoot && layers.GreaterThan(f.provisional.maxLayers)) {
return 0
}
maybeAdoptExempted := func() int64 {
br := int64(0)
if f.currentLayers.IsValid() {
for _, s := range f.provisional.exemptedLayers {
if s <= f.provisional.maxLayers.Spatial && f.currentLayers.Spatial == s {
f.provisional.allocatedLayers = f.currentLayers
br = f.provisional.bitrates[f.provisional.allocatedLayers.Spatial][f.provisional.allocatedLayers.Temporal]
break
}
}
}
return br
}
requiredBitrate := f.provisional.bitrates[layers.Spatial][layers.Temporal]
if requiredBitrate == 0 {
return maybeAdoptExempted()
}
alreadyAllocatedBitrate := int64(0)
if f.provisional.allocatedLayers != InvalidLayers {
alreadyAllocatedBitrate = f.provisional.bitrates[f.provisional.allocatedLayers.Spatial][f.provisional.allocatedLayers.Temporal]
}
// a layer under maximum fits, take it
if !layers.GreaterThan(f.provisional.maxLayers) && requiredBitrate <= (availableChannelCapacity+alreadyAllocatedBitrate) {
f.provisional.allocatedLayers = layers
return requiredBitrate - alreadyAllocatedBitrate
}
//
// Given layer does not fit. But overshoot is allowed.
// Could be one of
// 1. a layer below maximum that does not fit
// 2. a layer above maximum which may or may not fit.
// In any of those cases, take the lowest possible layer if pause is not allowed
//
if !allowPause && (f.provisional.allocatedLayers == InvalidLayers || !layers.GreaterThan(f.provisional.allocatedLayers)) {
f.provisional.allocatedLayers = layers
return requiredBitrate - alreadyAllocatedBitrate
}
return maybeAdoptExempted()
}
func (f *Forwarder) ProvisionalAllocateGetCooperativeTransition(allowOvershoot bool) VideoTransition {
//
// 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()
if f.provisional.muted {
f.provisional.allocatedLayers = InvalidLayers
return VideoTransition{
from: f.targetLayers,
to: InvalidLayers,
bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested,
// LK-TODO should this take current bitrate of current target layers?
}
}
// check if we should preserve current target
if f.targetLayers != InvalidLayers {
// what is the highest that is available
maximalLayers := InvalidLayers
maximalBandwidthRequired := int64(0)
for s := f.provisional.maxLayers.Spatial; s >= 0; s-- {
for t := f.provisional.maxLayers.Temporal; t >= 0; t-- {
if f.provisional.bitrates[s][t] != 0 {
maximalLayers = VideoLayers{Spatial: s, Temporal: t}
maximalBandwidthRequired = f.provisional.bitrates[s][t]
break
}
}
if maximalBandwidthRequired != 0 {
break
}
}
if maximalLayers != InvalidLayers {
if !f.targetLayers.GreaterThan(maximalLayers) && f.provisional.bitrates[f.targetLayers.Spatial][f.targetLayers.Temporal] != 0 {
// currently streaming and wanting an upgrade, just preserve current target in the cooperative scheme of things
f.provisional.allocatedLayers = f.targetLayers
return VideoTransition{
from: f.targetLayers,
to: f.targetLayers,
bandwidthDelta: 0,
}
}
if f.targetLayers.GreaterThan(maximalLayers) {
// maximalLayers <= f.targetLayers, make the down move
f.provisional.allocatedLayers = maximalLayers
return VideoTransition{
from: f.targetLayers,
to: maximalLayers,
bandwidthDelta: maximalBandwidthRequired - f.lastAllocation.bandwidthRequested,
}
}
}
}
findNextLayer := func(
minSpatial, maxSpatial int32,
minTemporal, maxTemporal int32,
) (VideoLayers, int64) {
layers := InvalidLayers
bw := int64(0)
for s := minSpatial; s <= maxSpatial; s++ {
for t := minTemporal; t <= maxTemporal; t++ {
if f.provisional.bitrates[s][t] != 0 {
layers = VideoLayers{Spatial: s, Temporal: t}
bw = f.provisional.bitrates[s][t]
break
}
}
if bw != 0 {
break
}
}
return layers, bw
}
targetLayers := f.targetLayers
bandwidthRequired := int64(0)
if targetLayers == InvalidLayers {
// 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
targetLayers, bandwidthRequired = findNextLayer(
0, f.provisional.maxLayers.Spatial,
0, f.provisional.maxLayers.Temporal,
)
}
// could not find a minimal layer, overshoot if allowed
if bandwidthRequired == 0 && f.provisional.maxLayers.IsValid() && allowOvershoot {
targetLayers, bandwidthRequired = findNextLayer(
f.provisional.maxLayers.Spatial+1, DefaultMaxLayerSpatial,
0, DefaultMaxLayerTemporal,
)
}
// adopt exempted layer if current is at one of the exempted layers below maximum
if bandwidthRequired == 0 && f.provisional.maxLayers.IsValid() && f.currentLayers.IsValid() {
for _, s := range f.provisional.exemptedLayers {
if s <= f.provisional.maxLayers.Spatial && f.currentLayers.Spatial == s {
targetLayers = f.currentLayers
bandwidthRequired = f.provisional.bitrates[targetLayers.Spatial][targetLayers.Temporal]
break
}
}
}
// turn off if nothing found, not even an exempted layer to continue with
if bandwidthRequired == 0 && (!f.currentLayers.IsValid() || f.currentLayers != targetLayers) {
targetLayers = InvalidLayers
}
f.provisional.allocatedLayers = targetLayers
return VideoTransition{
from: f.targetLayers,
to: targetLayers,
bandwidthDelta: bandwidthRequired - f.lastAllocation.bandwidthRequested,
}
}
func (f *Forwarder) ProvisionalAllocateGetBestWeightedTransition() VideoTransition {
//
// 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 keep all tracks streaming as much as possible. So, the track that needs a change needs bandwidth to be unpaused.
//
// This tries to figure out how much this track can contribute back to the pool to enable the track that needs to be unpaused.
// 1. Track muted OR feed dry - can contribute everything back in case it was using bandwidth.
// 2. Look at all possible down transitions from current target and find the best offer.
// Best offer is calculated as bandwidth saved moving to a down layer divided by cost.
// Cost has two components
// a. Transition cost: Spatial layer switch is expensive due to key frame requirement, but temporal layer switch is free.
// b. Quality cost: The farther away from desired layers, the higher the quality cost.
//
f.lock.Lock()
defer f.lock.Unlock()
if f.provisional.muted {
f.provisional.allocatedLayers = InvalidLayers
return VideoTransition{
from: f.targetLayers,
to: InvalidLayers,
bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested,
// LK-TODO should this take current bitrate of current target layers?
}
}
maxReachableLayerTemporal := InvalidLayerTemporal
for t := f.provisional.maxLayers.Temporal; t >= 0; t-- {
for s := f.provisional.maxLayers.Spatial; s >= 0; s-- {
if f.provisional.bitrates[s][t] != 0 {
maxReachableLayerTemporal = t
break
}
}
if maxReachableLayerTemporal != InvalidLayerTemporal {
break
}
}
if maxReachableLayerTemporal == InvalidLayerTemporal {
// stick to an exempted layer if available
if f.currentLayers.IsValid() {
for _, s := range f.provisional.exemptedLayers {
if s <= f.provisional.maxLayers.Spatial && f.currentLayers.Spatial == s {
f.provisional.allocatedLayers = f.currentLayers
return VideoTransition{
from: f.targetLayers,
to: f.provisional.allocatedLayers,
bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested,
// LK-TODO should this take current bitrate of current target layers?
}
}
}
}
// feed has gone dry,
f.provisional.allocatedLayers = InvalidLayers
return VideoTransition{
from: f.targetLayers,
to: InvalidLayers,
bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested,
// LK-TODO should this take current bitrate of current target layers?
}
}
// starting from minimum to target, find transition which gives the best
// transition taking into account bits saved vs cost of such a transition
bestLayers := InvalidLayers
bestBandwidthDelta := int64(0)
bestValue := float32(0)
for s := int32(0); s <= f.targetLayers.Spatial; s++ {
for t := int32(0); t <= f.targetLayers.Temporal; t++ {
if s == f.targetLayers.Spatial && t == f.targetLayers.Temporal {
break
}
bandwidthDelta := int64(math.Max(float64(0), float64(f.lastAllocation.bandwidthRequested-f.provisional.bitrates[s][t])))
transitionCost := int32(0)
if f.targetLayers.Spatial != s {
transitionCost = TransitionCostSpatial
}
qualityCost := (maxReachableLayerTemporal+1)*(f.targetLayers.Spatial-s) + (f.targetLayers.Temporal - t)
value := float32(0)
if (transitionCost + qualityCost) != 0 {
value = float32(bandwidthDelta) / float32(transitionCost+qualityCost)
}
if value > bestValue || (value == bestValue && bandwidthDelta > bestBandwidthDelta) {
bestValue = value
bestBandwidthDelta = bandwidthDelta
bestLayers = VideoLayers{Spatial: s, Temporal: t}
}
}
}
f.provisional.allocatedLayers = bestLayers
return VideoTransition{
from: f.targetLayers,
to: bestLayers,
bandwidthDelta: bestBandwidthDelta,
}
}
func (f *Forwarder) ProvisionalAllocateCommit() VideoAllocation {
f.lock.Lock()
defer f.lock.Unlock()
alloc := VideoAllocation{
bandwidthRequested: 0,
bandwidthDelta: -f.lastAllocation.bandwidthRequested,
availableLayers: f.provisional.availableLayers,
exemptedLayers: f.provisional.exemptedLayers,