Handle edge case of no published layer (#1446)

* WIP commit

* set max published layer

* split target and request layer
This commit is contained in:
Raja Subramanian
2023-02-20 14:16:46 +05:30
committed by GitHub
parent 6b55742564
commit c51d083016
6 changed files with 603 additions and 486 deletions
+34 -21
View File
@@ -5,7 +5,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"math"
"strings" "strings"
"sync" "sync"
"time" "time"
@@ -29,6 +28,7 @@ import (
type TrackSender interface { type TrackSender interface {
UpTrackLayersChange() UpTrackLayersChange()
UpTrackBitrateAvailabilityChange() UpTrackBitrateAvailabilityChange()
UpTrackMaxPublishedLayerChange(maxPublishedLayer int32)
WriteRTP(p *buffer.ExtPacket, layer int32) error WriteRTP(p *buffer.ExtPacket, layer int32) error
Close() Close()
IsClosed() bool IsClosed() bool
@@ -190,11 +190,14 @@ type DownTrack struct {
onTransportCCFeedback func(dt *DownTrack, cc *rtcp.TransportLayerCC) onTransportCCFeedback func(dt *DownTrack, cc *rtcp.TransportLayerCC)
// simulcast layer availability change callback // simulcast layer availability change callback
onAvailableLayersChanged atomic.Value // func(dt *DownTrack) onAvailableLayersChanged func(dt *DownTrack)
// layer bitrate availability change callback // layer bitrate availability change callback
onBitrateAvailabilityChanged func(dt *DownTrack) onBitrateAvailabilityChanged func(dt *DownTrack)
// max published layer change callback
onMaxPublishedLayerChanged func(dt *DownTrack)
// subscription change callback // subscription change callback
onSubscriptionChanged func(dt *DownTrack) onSubscriptionChanged func(dt *DownTrack)
@@ -214,7 +217,7 @@ type DownTrack struct {
onStatsUpdate func(dt *DownTrack, stat *livekit.AnalyticsStat) onStatsUpdate func(dt *DownTrack, stat *livekit.AnalyticsStat)
// when max subscribed layer changes // when max subscribed layer changes
onMaxLayerChanged func(dt *DownTrack, layer int32) onMaxSubscribedLayerChanged func(dt *DownTrack, layer int32)
// update rtt // update rtt
onRttUpdate func(dt *DownTrack, rtt uint32) onRttUpdate func(dt *DownTrack, rtt uint32)
@@ -360,7 +363,6 @@ func (d *DownTrack) TrackInfoAvailable() {
if ti == nil { if ti == nil {
return return
} }
d.forwarder.SetNumAdvertisedLayers(int32(math.Max(1, float64(len(ti.Layers)))))
d.connectionStats.Start(ti) d.connectionStats.Start(ti)
} }
@@ -542,23 +544,22 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) error {
f(d, pktSize) f(d, pktSize)
} }
if tp.isSwitchingToMaxLayer && d.onMaxLayerChanged != nil && d.kind == webrtc.RTPCodecTypeVideo { if tp.isSwitchingToMaxLayer && d.onMaxSubscribedLayerChanged != nil && d.kind == webrtc.RTPCodecTypeVideo {
d.onMaxLayerChanged(d, layer) d.onMaxSubscribedLayerChanged(d, layer)
} }
if extPkt.KeyFrame || tp.isSwitchingToTargetLayer { if extPkt.KeyFrame || tp.isSwitchingToTargetLayer {
d.isNACKThrottled.Store(false) d.isNACKThrottled.Store(false)
d.rtpStats.UpdateKeyFrame(1) if extPkt.KeyFrame {
d.rtpStats.UpdateKeyFrame(1)
d.logger.Debugw("forwarding key frame", "layer", layer)
}
locked, _ := d.forwarder.CheckSync() locked, _ := d.forwarder.CheckSync()
if locked { if locked {
d.stopKeyFrameRequester() d.stopKeyFrameRequester()
} }
if extPkt.KeyFrame {
d.logger.Debugw("forwarding key frame", "layer", layer)
}
if tp.isSwitchingToTargetLayer && d.onTargetLayerFound != nil { if tp.isSwitchingToTargetLayer && d.onTargetLayerFound != nil {
d.onTargetLayerFound(d) d.onTargetLayerFound(d)
} }
@@ -703,7 +704,7 @@ func (d *DownTrack) handleMute(muted bool, isPub bool, changed bool, maxLayers V
// Note that while publisher mute is active, subscriber changes can also happen // Note that while publisher mute is active, subscriber changes can also happen
// and that could turn on/off layers on publisher side. // and that could turn on/off layers on publisher side.
// //
if !isPub && d.onMaxLayerChanged != nil && d.kind == webrtc.RTPCodecTypeVideo { if !isPub && d.onMaxSubscribedLayerChanged != nil && d.kind == webrtc.RTPCodecTypeVideo {
notifyLayer := InvalidLayerSpatial notifyLayer := InvalidLayerSpatial
if !muted { if !muted {
// //
@@ -713,7 +714,7 @@ func (d *DownTrack) handleMute(muted bool, isPub bool, changed bool, maxLayers V
// //
notifyLayer = maxLayers.Spatial notifyLayer = maxLayers.Spatial
} }
d.onMaxLayerChanged(d, notifyLayer) d.onMaxSubscribedLayerChanged(d, notifyLayer)
} }
if d.onSubscriptionChanged != nil { if d.onSubscriptionChanged != nil {
@@ -797,8 +798,8 @@ func (d *DownTrack) CloseWithFlush(flush bool) {
d.rtpStats.Stop() d.rtpStats.Stop()
d.logger.Infow("rtp stats", "direction", "downstream", "mime", d.mime, "ssrc", d.ssrc, "stats", d.rtpStats.ToString()) d.logger.Infow("rtp stats", "direction", "downstream", "mime", d.mime, "ssrc", d.ssrc, "stats", d.rtpStats.ToString())
if d.onMaxLayerChanged != nil && d.kind == webrtc.RTPCodecTypeVideo { if d.onMaxSubscribedLayerChanged != nil && d.kind == webrtc.RTPCodecTypeVideo {
d.onMaxLayerChanged(d, InvalidLayerSpatial) d.onMaxSubscribedLayerChanged(d, InvalidLayerSpatial)
} }
if d.onCloseHandler != nil { if d.onCloseHandler != nil {
@@ -814,7 +815,7 @@ func (d *DownTrack) SetMaxSpatialLayer(spatialLayer int32) {
return return
} }
if d.onMaxLayerChanged != nil && d.kind == webrtc.RTPCodecTypeVideo && maxLayers.SpatialGreaterThanOrEqual(currentLayers) { if d.onMaxSubscribedLayerChanged != nil && d.kind == webrtc.RTPCodecTypeVideo && maxLayers.SpatialGreaterThanOrEqual(currentLayers) {
// //
// Notify when new max is // Notify when new max is
// 1. Equal to current -> already locked to the new max // 1. Equal to current -> already locked to the new max
@@ -822,7 +823,7 @@ func (d *DownTrack) SetMaxSpatialLayer(spatialLayer int32) {
// a. is higher than previous max -> client may need to start higher layer before forwarder can lock // a. is higher than previous max -> client may need to start higher layer before forwarder can lock
// b. is lower than previous max -> client can stop higher layer(s) // b. is lower than previous max -> client can stop higher layer(s)
// //
d.onMaxLayerChanged(d, maxLayers.Spatial) d.onMaxSubscribedLayerChanged(d, maxLayers.Spatial)
} }
if d.onSubscribedLayersChanged != nil { if d.onSubscribedLayersChanged != nil {
@@ -860,8 +861,8 @@ func (d *DownTrack) SeedState(state DownTrackState) {
} }
func (d *DownTrack) UpTrackLayersChange() { func (d *DownTrack) UpTrackLayersChange() {
if onAvailableLayersChanged, ok := d.onAvailableLayersChanged.Load().(func(dt *DownTrack)); ok { if d.onAvailableLayersChanged != nil {
onAvailableLayersChanged(d) d.onAvailableLayersChanged(d)
} }
} }
@@ -871,6 +872,14 @@ func (d *DownTrack) UpTrackBitrateAvailabilityChange() {
} }
} }
func (d *DownTrack) UpTrackMaxPublishedLayerChange(maxPublishedLayer int32) {
d.forwarder.SetMaxPublishedLayer(maxPublishedLayer)
if d.onMaxPublishedLayerChanged != nil {
d.onMaxPublishedLayerChanged(d)
}
}
// OnCloseHandler method to be called on remote tracked removed // OnCloseHandler method to be called on remote tracked removed
func (d *DownTrack) OnCloseHandler(fn func(willBeResumed bool)) { func (d *DownTrack) OnCloseHandler(fn func(willBeResumed bool)) {
d.onCloseHandler = fn d.onCloseHandler = fn
@@ -896,13 +905,17 @@ func (d *DownTrack) AddReceiverReportListener(listener ReceiverReportListener) {
} }
func (d *DownTrack) OnAvailableLayersChanged(fn func(dt *DownTrack)) { func (d *DownTrack) OnAvailableLayersChanged(fn func(dt *DownTrack)) {
d.onAvailableLayersChanged.Store(fn) d.onAvailableLayersChanged = fn
} }
func (d *DownTrack) OnBitrateAvailabilityChanged(fn func(dt *DownTrack)) { func (d *DownTrack) OnBitrateAvailabilityChanged(fn func(dt *DownTrack)) {
d.onBitrateAvailabilityChanged = fn d.onBitrateAvailabilityChanged = fn
} }
func (d *DownTrack) OnMaxPublishedLayerChanged(fn func(dt *DownTrack)) {
d.onMaxPublishedLayerChanged = fn
}
func (d *DownTrack) OnSubscriptionChanged(fn func(dt *DownTrack)) { func (d *DownTrack) OnSubscriptionChanged(fn func(dt *DownTrack)) {
d.onSubscriptionChanged = fn d.onSubscriptionChanged = fn
@@ -935,7 +948,7 @@ func (d *DownTrack) OnRttUpdate(fn func(dt *DownTrack, rtt uint32)) {
} }
func (d *DownTrack) OnMaxLayerChanged(fn func(dt *DownTrack, layer int32)) { func (d *DownTrack) OnMaxLayerChanged(fn func(dt *DownTrack, layer int32)) {
d.onMaxLayerChanged = fn d.onMaxSubscribedLayerChanged = fn
} }
func (d *DownTrack) IsDeficient() bool { func (d *DownTrack) IsDeficient() bool {
+217 -167
View File
@@ -55,39 +55,42 @@ func (v VideoPauseReason) String() string {
// ------------------------------------------------------------------- // -------------------------------------------------------------------
type VideoAllocation struct { type VideoAllocation struct {
pauseReason VideoPauseReason pauseReason VideoPauseReason
isDeficient bool isDeficient bool
bandwidthRequested int64 bandwidthRequested int64
bandwidthDelta int64 bandwidthDelta int64
bitrates Bitrates bitrates Bitrates
targetLayers VideoLayers targetLayers VideoLayers
maxLayers VideoLayers requestLayerSpatial int32
distanceToDesired int32 maxLayers VideoLayers
distanceToDesired int32
} }
func (v VideoAllocation) String() string { func (v VideoAllocation) String() string {
return fmt.Sprintf("VideoAllocation{pause: %s, def: %+v, bw: %d, del: %d, rates: %+v, target: %s, max: %s, dist: %d}", return fmt.Sprintf("VideoAllocation{pause: %s, def: %+v, bw: %d, del: %d, rates: %+v, target: %s, req: %d, max: %s, dist: %d}",
v.pauseReason, v.isDeficient, v.bandwidthRequested, v.bandwidthDelta, v.bitrates, v.targetLayers, v.maxLayers, v.distanceToDesired) v.pauseReason, v.isDeficient, v.bandwidthRequested, v.bandwidthDelta, v.bitrates, v.targetLayers, v.requestLayerSpatial, v.maxLayers, v.distanceToDesired)
} }
var ( var (
VideoAllocationDefault = VideoAllocation{ VideoAllocationDefault = VideoAllocation{
pauseReason: VideoPauseReasonFeedDry, // start with no feed till feed is seen pauseReason: VideoPauseReasonFeedDry, // start with no feed till feed is seen
targetLayers: InvalidLayers, targetLayers: InvalidLayers,
maxLayers: InvalidLayers, requestLayerSpatial: InvalidLayerSpatial,
maxLayers: InvalidLayers,
} }
) )
// ------------------------------------------------------------------- // -------------------------------------------------------------------
type VideoAllocationProvisional struct { type VideoAllocationProvisional struct {
muted bool muted bool
pubMuted bool pubMuted bool
bitrates Bitrates maxPublishedLayer int32
maxLayers VideoLayers bitrates Bitrates
currentLayers VideoLayers maxLayers VideoLayers
parkedLayers VideoLayers currentLayers VideoLayers
allocatedLayers VideoLayers parkedLayers VideoLayers
allocatedLayers VideoLayers
} }
// ------------------------------------------------------------------- // -------------------------------------------------------------------
@@ -161,20 +164,21 @@ type Forwarder struct {
logger logger.Logger logger logger.Logger
getReferenceLayerRTPTimestamp func(ts uint32, layer int32, referenceLayer int32) (uint32, error) getReferenceLayerRTPTimestamp func(ts uint32, layer int32, referenceLayer int32) (uint32, error)
numAdvertisedLayers int32
muted bool muted bool
pubMuted bool pubMuted bool
maxPublishedLayer int32
started bool started bool
lastSSRC uint32 lastSSRC uint32
referenceLayerSpatial int32 referenceLayerSpatial int32
maxLayers VideoLayers maxLayers VideoLayers
currentLayers VideoLayers currentLayers VideoLayers
targetLayers VideoLayers targetLayers VideoLayers
parkedLayers VideoLayers // layers that can resume without key frame requestLayerSpatial int32
parkedLayersTimer *time.Timer parkedLayers VideoLayers // layers that can resume without key frame
parkedLayersTimer *time.Timer
provisional *VideoAllocationProvisional provisional *VideoAllocationProvisional
@@ -200,12 +204,15 @@ func NewForwarder(
logger: logger, logger: logger,
getReferenceLayerRTPTimestamp: getReferenceLayerRTPTimestamp, getReferenceLayerRTPTimestamp: getReferenceLayerRTPTimestamp,
maxPublishedLayer: InvalidLayerSpatial,
referenceLayerSpatial: InvalidLayerSpatial, referenceLayerSpatial: InvalidLayerSpatial,
// start off with nothing, let streamallocator/opportunistic forwarder set the target // start off with nothing, let streamallocator/opportunistic forwarder set the target
currentLayers: InvalidLayers, currentLayers: InvalidLayers,
targetLayers: InvalidLayers, targetLayers: InvalidLayers,
parkedLayers: InvalidLayers, requestLayerSpatial: InvalidLayerSpatial,
parkedLayers: InvalidLayers,
lastAllocation: VideoAllocationDefault, lastAllocation: VideoAllocationDefault,
@@ -221,11 +228,16 @@ func NewForwarder(
return f return f
} }
func (f *Forwarder) SetNumAdvertisedLayers(numAdvertisedLayers int32) { func (f *Forwarder) SetMaxPublishedLayer(maxPublishedLayer int32) {
f.lock.Lock() f.lock.Lock()
defer f.lock.Unlock() defer f.lock.Unlock()
f.numAdvertisedLayers = numAdvertisedLayers if maxPublishedLayer <= f.maxPublishedLayer {
return
}
f.maxPublishedLayer = maxPublishedLayer
f.logger.Infow("setting max published layer", "maxPublishedLayer", f.maxPublishedLayer)
} }
func (f *Forwarder) OnParkedLayersExpired(fn func()) { func (f *Forwarder) OnParkedLayersExpired(fn func()) {
@@ -443,70 +455,6 @@ func (f *Forwarder) IsReducedQuality() (int32, bool) {
return distance, f.isDeficientLocked() return distance, f.isDeficientLocked()
} }
func (f *Forwarder) getOptimalBandwidthNeeded(brs Bitrates, maxLayers VideoLayers) int64 {
if f.muted || f.pubMuted {
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]
}
}
// could be 0 due to either
// 1. publisher has stopped all layers ==> feed dry.
// 2. stream tracker has declared all layers stopped, functionally same as above.
// But, listed differently as this could be a mis-detection.
// 3. Bitrate measurement is pending.
return 0
}
func (f *Forwarder) getDistanceToDesired(brs Bitrates, targetLayers VideoLayers, maxLayers VideoLayers) int32 {
if f.muted || f.pubMuted {
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) isDeficientLocked() bool { func (f *Forwarder) isDeficientLocked() bool {
return f.lastAllocation.isDeficient return f.lastAllocation.isDeficient
} }
@@ -555,18 +503,32 @@ func (f *Forwarder) AllocateOptimal(availableLayers []int32, brs Bitrates, allow
} }
alloc := VideoAllocation{ alloc := VideoAllocation{
pauseReason: VideoPauseReasonNone, pauseReason: VideoPauseReasonNone,
bitrates: brs, bitrates: brs,
targetLayers: InvalidLayers, targetLayers: InvalidLayers,
maxLayers: f.maxLayers, requestLayerSpatial: f.requestLayerSpatial,
maxLayers: f.maxLayers,
} }
if f.getOptimalBandwidthNeeded(brs, f.maxLayers) == 0 { optimalBandwidthNeeded := getOptimalBandwidthNeeded(f.muted, f.pubMuted, f.maxPublishedLayer, brs, f.maxLayers)
if optimalBandwidthNeeded == 0 {
alloc.pauseReason = VideoPauseReasonFeedDry alloc.pauseReason = VideoPauseReasonFeedDry
} }
opportunisticAlloc := func() {
// opportunistically latch on to anything
maxSpatial := f.maxLayers.Spatial
if allowOvershoot && f.maxPublishedLayer > maxSpatial {
maxSpatial = f.maxPublishedLayer
}
alloc.targetLayers = VideoLayers{
Spatial: int32(math.Min(float64(f.maxPublishedLayer), float64(maxSpatial))),
Temporal: DefaultMaxLayerTemporal,
}
}
switch { switch {
case !f.maxLayers.IsValid(): case !f.maxLayers.IsValid() || f.maxPublishedLayer == InvalidLayerSpatial:
// nothing to do when max layers are not valid // nothing to do when max layers are not valid OR max publisher layer is invalid
case f.muted: case f.muted:
alloc.pauseReason = VideoPauseReasonMuted alloc.pauseReason = VideoPauseReasonMuted
@@ -575,13 +537,16 @@ func (f *Forwarder) AllocateOptimal(availableLayers []int32, brs Bitrates, allow
alloc.pauseReason = VideoPauseReasonPubMuted alloc.pauseReason = VideoPauseReasonPubMuted
// leave it at current layers for opportunistic resume // leave it at current layers for opportunistic resume
alloc.targetLayers = f.currentLayers alloc.targetLayers = f.currentLayers
alloc.requestLayerSpatial = alloc.targetLayers.Spatial
case f.parkedLayers.IsValid(): case f.parkedLayers.IsValid():
// if parked on a layer, let it continue // if parked on a layer, let it continue
alloc.targetLayers = f.parkedLayers alloc.targetLayers = f.parkedLayers
alloc.requestLayerSpatial = alloc.targetLayers.Spatial
case f.maxLayers != f.lastAllocation.maxLayers: case f.maxLayers != f.lastAllocation.maxLayers:
alloc.targetLayers = f.maxLayers opportunisticAlloc()
alloc.requestLayerSpatial = int32(math.Min(float64(f.maxLayers.Spatial), float64(f.maxPublishedLayer)))
case len(availableLayers) == 0: case len(availableLayers) == 0:
// feed may be dry // feed may be dry
@@ -591,16 +556,11 @@ func (f *Forwarder) AllocateOptimal(availableLayers []int32, brs Bitrates, allow
// 1. mis-detection of layer stop - can continue streaming // 1. mis-detection of layer stop - can continue streaming
// 2. current layer resuming - can latch on when it starts // 2. current layer resuming - can latch on when it starts
alloc.targetLayers = f.currentLayers alloc.targetLayers = f.currentLayers
alloc.requestLayerSpatial = alloc.targetLayers.Spatial
} else { } else {
// opportunistically latch on to anything // opportunistically latch on to anything
if allowOvershoot { opportunisticAlloc()
alloc.targetLayers = VideoLayers{ alloc.requestLayerSpatial = int32(math.Min(float64(f.maxLayers.Spatial), float64(f.maxPublishedLayer)))
Spatial: int32(math.Max(0, float64(f.numAdvertisedLayers-1))),
Temporal: DefaultMaxLayerTemporal,
}
} else {
alloc.targetLayers = f.maxLayers
}
} }
default: default:
@@ -623,30 +583,21 @@ func (f *Forwarder) AllocateOptimal(availableLayers []int32, brs Bitrates, allow
} }
alloc.targetLayers.Temporal = DefaultMaxLayerTemporal alloc.targetLayers.Temporal = DefaultMaxLayerTemporal
} else { } else {
if f.targetLayers.IsValid() { // opportunistically latch on to anything
alloc.targetLayers = f.targetLayers opportunisticAlloc()
} else {
// opportunistically latch on to anything
if allowOvershoot {
alloc.targetLayers = VideoLayers{
Spatial: int32(math.Max(0, float64(f.numAdvertisedLayers-1))),
Temporal: DefaultMaxLayerTemporal,
}
} else {
alloc.targetLayers = f.maxLayers
}
}
} }
alloc.requestLayerSpatial = int32(math.Min(float64(f.maxLayers.Spatial), float64(f.maxPublishedLayer)))
} }
if !alloc.targetLayers.IsValid() { if !alloc.targetLayers.IsValid() {
alloc.targetLayers = InvalidLayers alloc.targetLayers = InvalidLayers
alloc.requestLayerSpatial = InvalidLayerSpatial
} }
if alloc.targetLayers.IsValid() { if alloc.targetLayers.IsValid() {
alloc.bandwidthRequested = brs[alloc.targetLayers.Spatial][alloc.targetLayers.Temporal] alloc.bandwidthRequested = optimalBandwidthNeeded
} }
alloc.bandwidthDelta = alloc.bandwidthRequested - f.lastAllocation.bandwidthRequested alloc.bandwidthDelta = alloc.bandwidthRequested - f.lastAllocation.bandwidthRequested
alloc.distanceToDesired = f.getDistanceToDesired(brs, alloc.targetLayers, f.maxLayers) alloc.distanceToDesired = getDistanceToDesired(f.muted, f.pubMuted, f.maxPublishedLayer, brs, alloc.targetLayers, f.maxLayers)
return f.updateAllocation(alloc, "optimal") return f.updateAllocation(alloc, "optimal")
} }
@@ -656,13 +607,14 @@ func (f *Forwarder) ProvisionalAllocatePrepare(bitrates Bitrates) {
defer f.lock.Unlock() defer f.lock.Unlock()
f.provisional = &VideoAllocationProvisional{ f.provisional = &VideoAllocationProvisional{
allocatedLayers: InvalidLayers, allocatedLayers: InvalidLayers,
muted: f.muted, muted: f.muted,
pubMuted: f.pubMuted, pubMuted: f.pubMuted,
bitrates: bitrates, maxPublishedLayer: f.maxPublishedLayer,
maxLayers: f.maxLayers, bitrates: bitrates,
currentLayers: f.currentLayers, maxLayers: f.maxLayers,
parkedLayers: f.parkedLayers, currentLayers: f.currentLayers,
parkedLayers: f.parkedLayers,
} }
} }
@@ -670,7 +622,7 @@ func (f *Forwarder) ProvisionalAllocate(availableChannelCapacity int64, layers V
f.lock.Lock() f.lock.Lock()
defer f.lock.Unlock() defer f.lock.Unlock()
if f.provisional.muted || f.provisional.pubMuted || !f.provisional.maxLayers.IsValid() || (!allowOvershoot && layers.GreaterThan(f.provisional.maxLayers)) { if f.provisional.muted || f.provisional.pubMuted || f.provisional.maxPublishedLayer == InvalidLayerSpatial || !f.provisional.maxLayers.IsValid() || (!allowOvershoot && layers.GreaterThan(f.provisional.maxLayers)) {
return 0 return 0
} }
@@ -950,12 +902,20 @@ func (f *Forwarder) ProvisionalAllocateCommit() VideoAllocation {
defer f.lock.Unlock() defer f.lock.Unlock()
alloc := VideoAllocation{ alloc := VideoAllocation{
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: -f.lastAllocation.bandwidthRequested, bandwidthDelta: -f.lastAllocation.bandwidthRequested,
bitrates: f.provisional.bitrates, bitrates: f.provisional.bitrates,
targetLayers: f.provisional.allocatedLayers, targetLayers: f.provisional.allocatedLayers,
maxLayers: f.provisional.maxLayers, requestLayerSpatial: f.provisional.allocatedLayers.Spatial,
distanceToDesired: f.getDistanceToDesired(f.provisional.bitrates, f.provisional.allocatedLayers, f.provisional.maxLayers), maxLayers: f.provisional.maxLayers,
distanceToDesired: getDistanceToDesired(
f.provisional.muted,
f.provisional.pubMuted,
f.provisional.maxPublishedLayer,
f.provisional.bitrates,
f.provisional.allocatedLayers,
f.provisional.maxLayers,
),
} }
switch { switch {
@@ -965,7 +925,13 @@ func (f *Forwarder) ProvisionalAllocateCommit() VideoAllocation {
case f.provisional.pubMuted: case f.provisional.pubMuted:
alloc.pauseReason = VideoPauseReasonPubMuted alloc.pauseReason = VideoPauseReasonPubMuted
case f.getOptimalBandwidthNeeded(f.provisional.bitrates, f.provisional.maxLayers) == 0: case getOptimalBandwidthNeeded(
f.provisional.muted,
f.provisional.pubMuted,
f.provisional.maxPublishedLayer,
f.provisional.bitrates,
f.provisional.maxLayers,
) == 0:
if f.provisional.allocatedLayers.IsValid() { if f.provisional.allocatedLayers.IsValid() {
// overshoot // overshoot
alloc.bandwidthRequested = f.provisional.bitrates[f.provisional.allocatedLayers.Spatial][f.provisional.allocatedLayers.Temporal] alloc.bandwidthRequested = f.provisional.bitrates[f.provisional.allocatedLayers.Spatial][f.provisional.allocatedLayers.Temporal]
@@ -977,6 +943,7 @@ func (f *Forwarder) ProvisionalAllocateCommit() VideoAllocation {
if f.provisional.currentLayers.IsValid() && f.provisional.currentLayers.Spatial <= f.provisional.maxLayers.Spatial { if f.provisional.currentLayers.IsValid() && f.provisional.currentLayers.Spatial <= f.provisional.maxLayers.Spatial {
f.provisional.allocatedLayers = f.provisional.currentLayers f.provisional.allocatedLayers = f.provisional.currentLayers
alloc.targetLayers = f.provisional.allocatedLayers alloc.targetLayers = f.provisional.allocatedLayers
alloc.requestLayerSpatial = alloc.targetLayers.Spatial
} }
} }
@@ -987,7 +954,13 @@ func (f *Forwarder) ProvisionalAllocateCommit() VideoAllocation {
alloc.bandwidthDelta = alloc.bandwidthRequested - f.lastAllocation.bandwidthRequested alloc.bandwidthDelta = alloc.bandwidthRequested - f.lastAllocation.bandwidthRequested
if f.provisional.allocatedLayers.GreaterThan(f.provisional.maxLayers) || if f.provisional.allocatedLayers.GreaterThan(f.provisional.maxLayers) ||
alloc.bandwidthRequested >= f.getOptimalBandwidthNeeded(f.provisional.bitrates, f.provisional.maxLayers) { alloc.bandwidthRequested >= getOptimalBandwidthNeeded(
f.provisional.muted,
f.provisional.pubMuted,
f.provisional.maxPublishedLayer,
f.provisional.bitrates,
f.provisional.maxLayers,
) {
// could be greater than optimal if overshooting // could be greater than optimal if overshooting
alloc.isDeficient = false alloc.isDeficient = false
} else { } else {
@@ -1020,7 +993,7 @@ func (f *Forwarder) AllocateNextHigher(availableChannelCapacity int64, brs Bitra
return f.lastAllocation, false return f.lastAllocation, false
} }
optimalBandwidthNeeded := f.getOptimalBandwidthNeeded(brs, f.maxLayers) optimalBandwidthNeeded := getOptimalBandwidthNeeded(f.muted, f.pubMuted, f.maxPublishedLayer, brs, f.maxLayers)
alreadyAllocated := int64(0) alreadyAllocated := int64(0)
if f.targetLayers.IsValid() { if f.targetLayers.IsValid() {
@@ -1045,13 +1018,14 @@ func (f *Forwarder) AllocateNextHigher(availableChannelCapacity int64, brs Bitra
targetLayers := VideoLayers{Spatial: s, Temporal: t} targetLayers := VideoLayers{Spatial: s, Temporal: t}
alloc := VideoAllocation{ alloc := VideoAllocation{
isDeficient: true, isDeficient: true,
bandwidthRequested: bandwidthRequested, bandwidthRequested: bandwidthRequested,
bandwidthDelta: bandwidthRequested - alreadyAllocated, bandwidthDelta: bandwidthRequested - alreadyAllocated,
bitrates: brs, bitrates: brs,
targetLayers: targetLayers, targetLayers: targetLayers,
maxLayers: f.maxLayers, requestLayerSpatial: targetLayers.Spatial,
distanceToDesired: f.getDistanceToDesired(brs, targetLayers, f.maxLayers), maxLayers: f.maxLayers,
distanceToDesired: getDistanceToDesired(f.muted, f.pubMuted, f.maxPublishedLayer, brs, targetLayers, f.maxLayers),
} }
if targetLayers.GreaterThan(f.maxLayers) || bandwidthRequested >= optimalBandwidthNeeded { if targetLayers.GreaterThan(f.maxLayers) || bandwidthRequested >= optimalBandwidthNeeded {
alloc.isDeficient = false alloc.isDeficient = false
@@ -1190,12 +1164,13 @@ func (f *Forwarder) Pause(brs Bitrates) VideoAllocation {
defer f.lock.Unlock() defer f.lock.Unlock()
alloc := VideoAllocation{ alloc := VideoAllocation{
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested, bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested,
bitrates: brs, bitrates: brs,
targetLayers: InvalidLayers, targetLayers: InvalidLayers,
maxLayers: f.maxLayers, requestLayerSpatial: InvalidLayerSpatial,
distanceToDesired: f.getDistanceToDesired(brs, InvalidLayers, f.maxLayers), maxLayers: f.maxLayers,
distanceToDesired: getDistanceToDesired(f.muted, f.pubMuted, f.maxPublishedLayer, brs, InvalidLayers, f.maxLayers),
} }
switch { switch {
@@ -1205,7 +1180,7 @@ func (f *Forwarder) Pause(brs Bitrates) VideoAllocation {
case f.pubMuted: case f.pubMuted:
alloc.pauseReason = VideoPauseReasonPubMuted alloc.pauseReason = VideoPauseReasonPubMuted
case f.getOptimalBandwidthNeeded(brs, f.maxLayers) == 0: case getOptimalBandwidthNeeded(f.muted, f.pubMuted, f.maxPublishedLayer, brs, f.maxLayers) == 0:
alloc.pauseReason = VideoPauseReasonFeedDry alloc.pauseReason = VideoPauseReasonFeedDry
default: default:
@@ -1226,7 +1201,7 @@ func (f *Forwarder) updateAllocation(alloc VideoAllocation, reason string) Video
} }
f.lastAllocation = alloc f.lastAllocation = alloc
f.setTargetLayers(f.lastAllocation.targetLayers) f.setTargetLayers(f.lastAllocation.targetLayers, f.lastAllocation.requestLayerSpatial)
if !f.targetLayers.IsValid() { if !f.targetLayers.IsValid() {
f.resyncLocked() f.resyncLocked()
} }
@@ -1234,11 +1209,13 @@ func (f *Forwarder) updateAllocation(alloc VideoAllocation, reason string) Video
return f.lastAllocation return f.lastAllocation
} }
func (f *Forwarder) setTargetLayers(targetLayers VideoLayers) { func (f *Forwarder) setTargetLayers(targetLayers VideoLayers, requestLayerSpatial int32) {
f.targetLayers = targetLayers f.targetLayers = targetLayers
if f.ddLayerSelector != nil { if f.ddLayerSelector != nil {
f.ddLayerSelector.SelectLayer(targetLayers) f.ddLayerSelector.SelectLayer(targetLayers)
} }
f.requestLayerSpatial = requestLayerSpatial
} }
func (f *Forwarder) Resync() { func (f *Forwarder) Resync() {
@@ -1281,8 +1258,8 @@ func (f *Forwarder) CheckSync() (locked bool, layer int32) {
f.lock.RLock() f.lock.RLock()
defer f.lock.RUnlock() defer f.lock.RUnlock()
layer = f.targetLayers.Spatial layer = f.requestLayerSpatial
locked = f.targetLayers.Spatial == f.currentLayers.Spatial || f.parkedLayers.IsValid() locked = f.requestLayerSpatial == f.currentLayers.Spatial || f.parkedLayers.IsValid()
return return
} }
@@ -1428,7 +1405,7 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in
return tp, nil return tp, nil
} else if tp.isSwitchingToTargetLayer { } else if tp.isSwitchingToTargetLayer {
// lock to target layer // lock to target layer
f.logger.Infow("locking to target layer", "current", f.currentLayers, "target", f.targetLayers, "feed", extPkt.Packet.SSRC) f.logger.Infow("locking to target layer", "current", f.currentLayers, "target", f.targetLayers, "req", f.requestLayerSpatial, "feed", extPkt.Packet.SSRC)
f.currentLayers.Spatial = f.targetLayers.Spatial f.currentLayers.Spatial = f.targetLayers.Spatial
if !f.isTemporalSupported { if !f.isTemporalSupported {
f.currentLayers.Temporal = f.targetLayers.Temporal f.currentLayers.Temporal = f.targetLayers.Temporal
@@ -1438,7 +1415,7 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in
// if f.ddLayerSelector != nil { // if f.ddLayerSelector != nil {
// f.ddLayerSelector.SelectLayer(f.currentLayers) // f.ddLayerSelector.SelectLayer(f.currentLayers)
// } // }
if f.currentLayers.Spatial >= f.maxLayers.Spatial || f.currentLayers.Spatial == (f.numAdvertisedLayers-1) { if f.currentLayers.Spatial >= f.maxLayers.Spatial || f.currentLayers.Spatial == f.maxPublishedLayer {
tp.isSwitchingToMaxLayer = true tp.isSwitchingToMaxLayer = true
} }
} }
@@ -1479,7 +1456,7 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in
if found { if found {
tp.isSwitchingToTargetLayer = true tp.isSwitchingToTargetLayer = true
f.clearParkedLayers() f.clearParkedLayers()
if f.currentLayers.Spatial >= f.maxLayers.Spatial || f.currentLayers.Spatial == (f.numAdvertisedLayers-1) { if f.currentLayers.Spatial >= f.maxLayers.Spatial || f.currentLayers.Spatial == f.maxPublishedLayer {
tp.isSwitchingToMaxLayer = true tp.isSwitchingToMaxLayer = true
// if maximum is attained, adjust target to enable fast path layer check in per-packet path // if maximum is attained, adjust target to enable fast path layer check in per-packet path
@@ -1488,7 +1465,7 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in
"current", f.currentLayers, "current", f.currentLayers,
"target", f.targetLayers, "target", f.targetLayers,
"max", f.maxLayers, "max", f.maxLayers,
"advertised", f.numAdvertisedLayers, "maxPublished", f.maxPublishedLayer,
"feed", extPkt.Packet.SSRC, "feed", extPkt.Packet.SSRC,
) )
f.targetLayers.Spatial = f.currentLayers.Spatial f.targetLayers.Spatial = f.currentLayers.Spatial
@@ -1502,7 +1479,7 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in
f.currentLayers.Spatial = layer f.currentLayers.Spatial = layer
f.targetLayers.Spatial = layer f.targetLayers.Spatial = layer
if f.currentLayers.Spatial >= f.maxLayers.Spatial || f.currentLayers.Spatial == (f.numAdvertisedLayers-1) { if f.currentLayers.Spatial >= f.maxLayers.Spatial || f.currentLayers.Spatial == f.maxPublishedLayer {
tp.isSwitchingToMaxLayer = true tp.isSwitchingToMaxLayer = true
} }
} }
@@ -1618,3 +1595,76 @@ func (f *Forwarder) GetRTPMungerParams() RTPMungerParams {
return f.rtpMunger.GetParams() return f.rtpMunger.GetParams()
} }
// -----------------------------------------------------------------------------
func getOptimalBandwidthNeeded(muted bool, pubMuted bool, maxPublishedLayer int32, brs Bitrates, maxLayers VideoLayers) int64 {
if muted || pubMuted || maxPublishedLayer == InvalidLayerSpatial {
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]
}
}
// could be 0 due to either
// 1. publisher has stopped all layers ==> feed dry.
// 2. stream tracker has declared all layers stopped, functionally same as above.
// But, listed differently as this could be a mis-detection.
// 3. Bitrate measurement is pending.
return 0
}
func getDistanceToDesired(
muted bool,
pubMuted bool,
maxPublishedLayer int32,
brs Bitrates,
targetLayers VideoLayers,
maxLayers VideoLayers,
) int32 {
if muted || pubMuted || maxPublishedLayer == InvalidLayerSpatial {
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 > maxLayers.Spatial; s-- {
for t := maxLayers.Temporal; t >= 0; t-- {
if targetLayers.Temporal < t || brs[s][t] == 0 {
continue
}
distance--
}
}
}
return distance
}
+288 -278
View File
@@ -123,13 +123,14 @@ func TestForwarderAllocateOptimal(t *testing.T) {
// invalid max layers // invalid max layers
f.maxLayers = InvalidLayers f.maxLayers = InvalidLayers
expectedResult := VideoAllocation{ expectedResult := VideoAllocation{
pauseReason: VideoPauseReasonFeedDry, pauseReason: VideoPauseReasonFeedDry,
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0, bandwidthDelta: 0,
bitrates: bitrates, bitrates: bitrates,
targetLayers: InvalidLayers, targetLayers: InvalidLayers,
maxLayers: InvalidLayers, requestLayerSpatial: InvalidLayerSpatial,
distanceToDesired: 0, maxLayers: InvalidLayers,
distanceToDesired: 0,
} }
result := f.AllocateOptimal(nil, bitrates, true) result := f.AllocateOptimal(nil, bitrates, true)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -138,17 +139,35 @@ func TestForwarderAllocateOptimal(t *testing.T) {
f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) f.SetMaxSpatialLayer(DefaultMaxLayerSpatial)
f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) f.SetMaxTemporalLayer(DefaultMaxLayerTemporal)
// should still have target at InvalidLayers until max publisher layer is available
expectedResult = VideoAllocation{
pauseReason: VideoPauseReasonFeedDry,
bandwidthRequested: 0,
bandwidthDelta: 0,
bitrates: bitrates,
targetLayers: InvalidLayers,
requestLayerSpatial: InvalidLayerSpatial,
maxLayers: DefaultMaxLayers,
distanceToDesired: 0,
}
result = f.AllocateOptimal(nil, bitrates, true)
require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation)
f.SetMaxPublishedLayer(DefaultMaxLayerSpatial)
// muted should not consume any bandwidth // muted should not consume any bandwidth
f.Mute(true) f.Mute(true)
disable(f) disable(f)
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
pauseReason: VideoPauseReasonMuted, pauseReason: VideoPauseReasonMuted,
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0, bandwidthDelta: 0,
bitrates: bitrates, bitrates: bitrates,
targetLayers: InvalidLayers, targetLayers: InvalidLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: InvalidLayerSpatial,
distanceToDesired: 0, maxLayers: DefaultMaxLayers,
distanceToDesired: 0,
} }
result = f.AllocateOptimal(nil, bitrates, true) result = f.AllocateOptimal(nil, bitrates, true)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -160,13 +179,14 @@ func TestForwarderAllocateOptimal(t *testing.T) {
f.PubMute(true) f.PubMute(true)
disable(f) disable(f)
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
pauseReason: VideoPauseReasonPubMuted, pauseReason: VideoPauseReasonPubMuted,
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0, bandwidthDelta: 0,
bitrates: bitrates, bitrates: bitrates,
targetLayers: InvalidLayers, targetLayers: InvalidLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: InvalidLayerSpatial,
distanceToDesired: 0, maxLayers: DefaultMaxLayers,
distanceToDesired: 0,
} }
result = f.AllocateOptimal(nil, bitrates, true) result = f.AllocateOptimal(nil, bitrates, true)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -180,13 +200,14 @@ func TestForwarderAllocateOptimal(t *testing.T) {
Temporal: 1, Temporal: 1,
} }
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
pauseReason: VideoPauseReasonFeedDry, pauseReason: VideoPauseReasonFeedDry,
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0, bandwidthDelta: 0,
bitrates: emptyBitrates, bitrates: emptyBitrates,
targetLayers: f.parkedLayers, targetLayers: f.parkedLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: f.parkedLayers.Spatial,
distanceToDesired: 0, maxLayers: DefaultMaxLayers,
distanceToDesired: 0,
} }
result = f.AllocateOptimal(nil, emptyBitrates, true) result = f.AllocateOptimal(nil, emptyBitrates, true)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -197,38 +218,39 @@ func TestForwarderAllocateOptimal(t *testing.T) {
// when max layers changes, should switch to that // when max layers changes, should switch to that
f.maxLayers = VideoLayers{Spatial: 1, Temporal: 3} f.maxLayers = VideoLayers{Spatial: 1, Temporal: 3}
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
pauseReason: VideoPauseReasonFeedDry, pauseReason: VideoPauseReasonFeedDry,
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0, bandwidthDelta: 0,
bitrates: emptyBitrates, bitrates: emptyBitrates,
targetLayers: f.maxLayers, targetLayers: DefaultMaxLayers,
maxLayers: f.maxLayers, requestLayerSpatial: f.maxLayers.Spatial,
distanceToDesired: 0, maxLayers: f.maxLayers,
distanceToDesired: 0,
} }
result = f.AllocateOptimal(nil, emptyBitrates, true) result = f.AllocateOptimal(nil, emptyBitrates, true)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedResult, f.lastAllocation)
require.Equal(t, f.maxLayers, f.TargetLayers()) require.Equal(t, DefaultMaxLayers, f.TargetLayers())
// reset max layers for rest of the tests below // reset max layers for rest of the tests below
f.maxLayers = DefaultMaxLayers f.maxLayers = DefaultMaxLayers
f.lastAllocation.maxLayers = DefaultMaxLayers f.lastAllocation.maxLayers = DefaultMaxLayers
// when feed is dry and current is not valid, should set up for opportunistic forwarding // when feed is dry and current is not valid, should set up for opportunistic forwarding
f.SetNumAdvertisedLayers(3)
disable(f) disable(f)
expectedTargetLayers := VideoLayers{ expectedTargetLayers := VideoLayers{
Spatial: 2, Spatial: 2,
Temporal: DefaultMaxLayerTemporal, Temporal: DefaultMaxLayerTemporal,
} }
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
pauseReason: VideoPauseReasonFeedDry, pauseReason: VideoPauseReasonFeedDry,
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0, bandwidthDelta: 0,
bitrates: emptyBitrates, bitrates: emptyBitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: expectedTargetLayers.Spatial,
distanceToDesired: 0, maxLayers: DefaultMaxLayers,
distanceToDesired: 0,
} }
result = f.AllocateOptimal(nil, emptyBitrates, true) result = f.AllocateOptimal(nil, emptyBitrates, true)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -244,13 +266,14 @@ func TestForwarderAllocateOptimal(t *testing.T) {
Temporal: 3, Temporal: 3,
} }
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
pauseReason: VideoPauseReasonFeedDry, pauseReason: VideoPauseReasonFeedDry,
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0, bandwidthDelta: 0,
bitrates: emptyBitrates, bitrates: emptyBitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: expectedTargetLayers.Spatial,
distanceToDesired: 0, maxLayers: DefaultMaxLayers,
distanceToDesired: 0,
} }
result = f.AllocateOptimal(nil, emptyBitrates, true) result = f.AllocateOptimal(nil, emptyBitrates, true)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -270,44 +293,47 @@ func TestForwarderAllocateOptimal(t *testing.T) {
Temporal: DefaultMaxLayerTemporal, Temporal: DefaultMaxLayerTemporal,
} }
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
pauseReason: VideoPauseReasonFeedDry, pauseReason: VideoPauseReasonFeedDry,
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0, bandwidthDelta: 0,
bitrates: emptyBitrates, bitrates: emptyBitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: expectedMaxLayers, requestLayerSpatial: expectedTargetLayers.Spatial,
distanceToDesired: 0, maxLayers: expectedMaxLayers,
distanceToDesired: 0,
} }
result = f.AllocateOptimal(nil, emptyBitrates, false) result = f.AllocateOptimal(nil, emptyBitrates, false)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedResult, f.lastAllocation)
require.Equal(t, expectedTargetLayers, f.TargetLayers()) require.Equal(t, expectedTargetLayers, f.TargetLayers())
// stays at target if feed is not dry and current is not valid, i. e. not forwarding // opportunistic target if feed is not dry and current is not valid, i. e. not forwarding
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
pauseReason: VideoPauseReasonFeedDry, pauseReason: VideoPauseReasonFeedDry,
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0, bandwidthDelta: 0,
bitrates: emptyBitrates, bitrates: emptyBitrates,
targetLayers: expectedTargetLayers, targetLayers: DefaultMaxLayers,
maxLayers: expectedMaxLayers, requestLayerSpatial: 0,
distanceToDesired: 0, maxLayers: expectedMaxLayers,
distanceToDesired: 0,
} }
result = f.AllocateOptimal([]int32{0, 1}, emptyBitrates, true) result = f.AllocateOptimal([]int32{0, 1}, emptyBitrates, true)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedResult, f.lastAllocation)
require.Equal(t, expectedTargetLayers, f.TargetLayers()) require.Equal(t, DefaultMaxLayers, f.TargetLayers())
// if feed is not dry and target is not valid, should be opportunistic (with and without overshoot) // if feed is not dry and target is not valid, should be opportunistic (with and without overshoot)
f.targetLayers = InvalidLayers f.targetLayers = InvalidLayers
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
pauseReason: VideoPauseReasonFeedDry, pauseReason: VideoPauseReasonFeedDry,
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0, bandwidthDelta: 0,
bitrates: emptyBitrates, bitrates: emptyBitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: expectedMaxLayers, requestLayerSpatial: 0,
distanceToDesired: 0, maxLayers: expectedMaxLayers,
distanceToDesired: 0,
} }
result = f.AllocateOptimal([]int32{0, 1}, emptyBitrates, false) result = f.AllocateOptimal([]int32{0, 1}, emptyBitrates, false)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -319,50 +345,34 @@ func TestForwarderAllocateOptimal(t *testing.T) {
Temporal: DefaultMaxLayerTemporal, Temporal: DefaultMaxLayerTemporal,
} }
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
pauseReason: VideoPauseReasonFeedDry, pauseReason: VideoPauseReasonFeedDry,
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0, bandwidthDelta: 0,
bitrates: emptyBitrates, bitrates: emptyBitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: expectedMaxLayers, requestLayerSpatial: 0,
distanceToDesired: 0, maxLayers: expectedMaxLayers,
} distanceToDesired: 0,
result = f.AllocateOptimal([]int32{0, 1}, emptyBitrates, true)
require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation)
// stays at target if feed is not dry and current is valid and current is available
f.currentLayers = VideoLayers{Spatial: 0, Temporal: 1}
expectedTargetLayers = VideoLayers{
Spatial: 2,
Temporal: DefaultMaxLayerTemporal,
}
expectedResult = VideoAllocation{
pauseReason: VideoPauseReasonFeedDry,
bandwidthRequested: 0,
bandwidthDelta: 0,
bitrates: emptyBitrates,
targetLayers: expectedTargetLayers,
maxLayers: expectedMaxLayers,
distanceToDesired: 0,
} }
result = f.AllocateOptimal([]int32{0, 1}, emptyBitrates, true) result = f.AllocateOptimal([]int32{0, 1}, emptyBitrates, true)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedResult, f.lastAllocation)
// switches to highest available if feed is not dry and current is valid and current is not available // switches to highest available if feed is not dry and current is valid and current is not available
f.currentLayers = VideoLayers{Spatial: 0, Temporal: 1}
expectedTargetLayers = VideoLayers{ expectedTargetLayers = VideoLayers{
Spatial: 1, Spatial: 1,
Temporal: DefaultMaxLayerTemporal, Temporal: DefaultMaxLayerTemporal,
} }
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
pauseReason: VideoPauseReasonFeedDry, pauseReason: VideoPauseReasonFeedDry,
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0, bandwidthDelta: 0,
bitrates: emptyBitrates, bitrates: emptyBitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: expectedMaxLayers, requestLayerSpatial: 0,
distanceToDesired: 0, maxLayers: expectedMaxLayers,
distanceToDesired: 0,
} }
result = f.AllocateOptimal([]int32{1}, emptyBitrates, true) result = f.AllocateOptimal([]int32{1}, emptyBitrates, true)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -373,6 +383,7 @@ func TestForwarderProvisionalAllocate(t *testing.T) {
f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo)
f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) f.SetMaxSpatialLayer(DefaultMaxLayerSpatial)
f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) f.SetMaxTemporalLayer(DefaultMaxLayerTemporal)
f.SetMaxPublishedLayer(DefaultMaxLayerSpatial)
bitrates := Bitrates{ bitrates := Bitrates{
{1, 2, 3, 4}, {1, 2, 3, 4},
@@ -404,13 +415,14 @@ func TestForwarderProvisionalAllocate(t *testing.T) {
Temporal: 2, Temporal: 2,
} }
expectedResult := VideoAllocation{ expectedResult := VideoAllocation{
isDeficient: true, isDeficient: true,
bandwidthRequested: bitrates[1][2], bandwidthRequested: bitrates[1][2],
bandwidthDelta: bitrates[1][2], bandwidthDelta: bitrates[1][2],
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: expectedTargetLayers.Spatial,
distanceToDesired: 5, maxLayers: DefaultMaxLayers,
distanceToDesired: 5,
} }
result := f.ProvisionalAllocateCommit() result := f.ProvisionalAllocateCommit()
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -429,13 +441,14 @@ func TestForwarderProvisionalAllocate(t *testing.T) {
Temporal: 0, Temporal: 0,
} }
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
isDeficient: true, isDeficient: true,
bandwidthRequested: bitrates[0][0], bandwidthRequested: bitrates[0][0],
bandwidthDelta: bitrates[0][0] - bitrates[1][2], bandwidthDelta: bitrates[0][0] - bitrates[1][2],
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: expectedTargetLayers.Spatial,
distanceToDesired: 11, maxLayers: DefaultMaxLayers,
distanceToDesired: 11,
} }
result = f.ProvisionalAllocateCommit() result = f.ProvisionalAllocateCommit()
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -476,12 +489,13 @@ func TestForwarderProvisionalAllocate(t *testing.T) {
Temporal: 3, Temporal: 3,
} }
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
bandwidthRequested: bitrates[1][3], bandwidthRequested: bitrates[1][3],
bandwidthDelta: bitrates[1][3] - 1, // 1 is the last allocation bandwith requested bandwidthDelta: bitrates[1][3] - 1, // 1 is the last allocation bandwith requested
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: expectedMaxLayers, requestLayerSpatial: expectedTargetLayers.Spatial,
distanceToDesired: -4, maxLayers: expectedMaxLayers,
distanceToDesired: -4,
} }
result = f.ProvisionalAllocateCommit() result = f.ProvisionalAllocateCommit()
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -518,13 +532,14 @@ func TestForwarderProvisionalAllocate(t *testing.T) {
Temporal: 2, Temporal: 2,
} }
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
pauseReason: VideoPauseReasonFeedDry, pauseReason: VideoPauseReasonFeedDry,
bandwidthRequested: bitrates[0][2], bandwidthRequested: bitrates[0][2],
bandwidthDelta: bitrates[0][2] - 8, // 8 is the last allocation bandwith requested bandwidthDelta: bitrates[0][2] - 8, // 8 is the last allocation bandwith requested
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: expectedMaxLayers, requestLayerSpatial: expectedTargetLayers.Spatial,
distanceToDesired: 0, maxLayers: expectedMaxLayers,
distanceToDesired: 0,
} }
result = f.ProvisionalAllocateCommit() result = f.ProvisionalAllocateCommit()
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -550,13 +565,14 @@ func TestForwarderProvisionalAllocate(t *testing.T) {
require.Equal(t, int64(0), usedBitrate) require.Equal(t, int64(0), usedBitrate)
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
pauseReason: VideoPauseReasonFeedDry, pauseReason: VideoPauseReasonFeedDry,
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0, bandwidthDelta: 0,
bitrates: bitrates, bitrates: bitrates,
targetLayers: InvalidLayers, targetLayers: InvalidLayers,
maxLayers: expectedMaxLayers, requestLayerSpatial: InvalidLayerSpatial,
distanceToDesired: 0, maxLayers: expectedMaxLayers,
distanceToDesired: 0,
} }
result = f.ProvisionalAllocateCommit() result = f.ProvisionalAllocateCommit()
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -587,13 +603,14 @@ func TestForwarderProvisionalAllocateMute(t *testing.T) {
// committing should set target to InvalidLayers as track is muted // committing should set target to InvalidLayers as track is muted
expectedResult := VideoAllocation{ expectedResult := VideoAllocation{
pauseReason: VideoPauseReasonMuted, pauseReason: VideoPauseReasonMuted,
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0, bandwidthDelta: 0,
bitrates: bitrates, bitrates: bitrates,
targetLayers: InvalidLayers, targetLayers: InvalidLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: InvalidLayerSpatial,
distanceToDesired: 0, maxLayers: DefaultMaxLayers,
distanceToDesired: 0,
} }
result := f.ProvisionalAllocateCommit() result := f.ProvisionalAllocateCommit()
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -605,6 +622,7 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) {
f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo)
f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) f.SetMaxSpatialLayer(DefaultMaxLayerSpatial)
f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) f.SetMaxTemporalLayer(DefaultMaxLayerTemporal)
f.SetMaxPublishedLayer(DefaultMaxLayerSpatial)
bitrates := Bitrates{ bitrates := Bitrates{
{1, 2, 3, 4}, {1, 2, 3, 4},
@@ -626,13 +644,14 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) {
// committing should set target to (0, 0) // committing should set target to (0, 0)
expectedLayers := VideoLayers{Spatial: 0, Temporal: 0} expectedLayers := VideoLayers{Spatial: 0, Temporal: 0}
expectedResult := VideoAllocation{ expectedResult := VideoAllocation{
isDeficient: true, isDeficient: true,
bandwidthRequested: 1, bandwidthRequested: 1,
bandwidthDelta: 1, bandwidthDelta: 1,
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedLayers, targetLayers: expectedLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: expectedLayers.Spatial,
distanceToDesired: 9, maxLayers: DefaultMaxLayers,
distanceToDesired: 9,
} }
result := f.ProvisionalAllocateCommit() result := f.ProvisionalAllocateCommit()
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -654,12 +673,13 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) {
// committing should set target to (2, 1) // committing should set target to (2, 1)
expectedLayers = VideoLayers{Spatial: 2, Temporal: 1} expectedLayers = VideoLayers{Spatial: 2, Temporal: 1}
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
bandwidthRequested: 10, bandwidthRequested: 10,
bandwidthDelta: 0, bandwidthDelta: 0,
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedLayers, targetLayers: expectedLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: expectedLayers.Spatial,
distanceToDesired: 0, maxLayers: DefaultMaxLayers,
distanceToDesired: 0,
} }
result = f.ProvisionalAllocateCommit() result = f.ProvisionalAllocateCommit()
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -722,12 +742,13 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) {
expectedLayers = VideoLayers{Spatial: 1, Temporal: 0} expectedLayers = VideoLayers{Spatial: 1, Temporal: 0}
expectedMaxLayers := VideoLayers{Spatial: 0, Temporal: DefaultMaxLayerTemporal} expectedMaxLayers := VideoLayers{Spatial: 0, Temporal: DefaultMaxLayerTemporal}
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
bandwidthRequested: 5, bandwidthRequested: 5,
bandwidthDelta: 5, bandwidthDelta: 5,
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedLayers, targetLayers: expectedLayers,
maxLayers: expectedMaxLayers, requestLayerSpatial: expectedLayers.Spatial,
distanceToDesired: -1, maxLayers: expectedMaxLayers,
distanceToDesired: -1,
} }
result = f.ProvisionalAllocateCommit() result = f.ProvisionalAllocateCommit()
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -760,12 +781,13 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) {
// committing should set target to (0, 2) // committing should set target to (0, 2)
expectedLayers = VideoLayers{Spatial: 0, Temporal: 2} expectedLayers = VideoLayers{Spatial: 0, Temporal: 2}
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: -5, bandwidthDelta: -5,
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedLayers, targetLayers: expectedLayers,
maxLayers: expectedMaxLayers, requestLayerSpatial: expectedLayers.Spatial,
distanceToDesired: 0, maxLayers: expectedMaxLayers,
distanceToDesired: 0,
} }
result = f.ProvisionalAllocateCommit() result = f.ProvisionalAllocateCommit()
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -774,12 +796,13 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) {
// committing should set target to current layers to enable opportunistic forwarding // committing should set target to current layers to enable opportunistic forwarding
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0, bandwidthDelta: 0,
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedLayers, targetLayers: expectedLayers,
maxLayers: expectedMaxLayers, requestLayerSpatial: expectedLayers.Spatial,
distanceToDesired: 0, maxLayers: expectedMaxLayers,
distanceToDesired: 0,
} }
result = f.ProvisionalAllocateCommit() result = f.ProvisionalAllocateCommit()
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -815,6 +838,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
f := newForwarder(testutils.TestOpusCodec, webrtc.RTPCodecTypeAudio) f := newForwarder(testutils.TestOpusCodec, webrtc.RTPCodecTypeAudio)
f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) f.SetMaxSpatialLayer(DefaultMaxLayerSpatial)
f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) f.SetMaxTemporalLayer(DefaultMaxLayerTemporal)
f.SetMaxPublishedLayer(DefaultMaxLayerSpatial)
emptyBitrates := Bitrates{} emptyBitrates := Bitrates{}
bitrates := Bitrates{ bitrates := Bitrates{
@@ -830,6 +854,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
f = newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) f = newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo)
f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) f.SetMaxSpatialLayer(DefaultMaxLayerSpatial)
f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) f.SetMaxTemporalLayer(DefaultMaxLayerTemporal)
f.SetMaxPublishedLayer(DefaultMaxLayerSpatial)
// when not in deficient state, does not boost // when not in deficient state, does not boost
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false) result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false)
@@ -837,64 +862,34 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
require.False(t, boosted) require.False(t, boosted)
// if layers have not caught up, should not allocate next layer even if deficient // if layers have not caught up, should not allocate next layer even if deficient
f.lastAllocation.pauseReason = VideoPauseReasonNone
f.lastAllocation.isDeficient = true
f.targetLayers = VideoLayers{ f.targetLayers = VideoLayers{
Spatial: 0, Spatial: 0,
Temporal: 0, Temporal: 0,
} }
expectedResult := VideoAllocation{
isDeficient: true,
bandwidthRequested: 0,
bandwidthDelta: 0,
bitrates: emptyBitrates,
targetLayers: InvalidLayers,
maxLayers: InvalidLayers,
distanceToDesired: 0,
}
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false) result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false)
require.Equal(t, expectedResult, result) require.Equal(t, VideoAllocationDefault, result)
require.Equal(t, expectedResult, f.lastAllocation)
require.False(t, boosted) require.False(t, boosted)
f.currentLayers.Spatial = 0
f.targetLayers.Temporal = 0 f.lastAllocation.isDeficient = true
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false) f.currentLayers = VideoLayers{
require.Equal(t, expectedResult, result) Spatial: 0,
require.Equal(t, expectedResult, f.lastAllocation) Temporal: 0,
require.False(t, boosted)
f.currentLayers.Temporal = 0
f.lastAllocation.bandwidthRequested = bitrates[0][0]
// empty bitrates cannot increase layer
expectedResult = VideoAllocation{
isDeficient: true,
bandwidthRequested: 2,
bandwidthDelta: 0,
bitrates: emptyBitrates,
targetLayers: InvalidLayers,
maxLayers: InvalidLayers,
distanceToDesired: 0,
} }
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, emptyBitrates, false)
require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation)
require.False(t, boosted)
// move from (0, 0) -> (0, 1), i.e. a higher temporal layer is available in the same spatial layer // move from (0, 0) -> (0, 1), i.e. a higher temporal layer is available in the same spatial layer
expectedTargetLayers := VideoLayers{ expectedTargetLayers := VideoLayers{
Spatial: 0, Spatial: 0,
Temporal: 1, Temporal: 1,
} }
expectedResult = VideoAllocation{ expectedResult := VideoAllocation{
isDeficient: true, isDeficient: true,
bandwidthRequested: 3, bandwidthRequested: 3,
bandwidthDelta: 1, bandwidthDelta: 1,
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: expectedTargetLayers.Spatial,
distanceToDesired: 3, maxLayers: DefaultMaxLayers,
distanceToDesired: 3,
} }
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false) result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -902,6 +897,11 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
require.Equal(t, expectedTargetLayers, f.TargetLayers()) require.Equal(t, expectedTargetLayers, f.TargetLayers())
require.True(t, boosted) require.True(t, boosted)
// empty bitrates cannot increase layer, i. e. last allocation is left unchanged
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, emptyBitrates, false)
require.Equal(t, expectedResult, result)
require.False(t, boosted)
// move from (0, 1) -> (1, 0), i.e. a higher spatial layer is available // move from (0, 1) -> (1, 0), i.e. a higher spatial layer is available
f.currentLayers.Temporal = 1 f.currentLayers.Temporal = 1
expectedTargetLayers = VideoLayers{ expectedTargetLayers = VideoLayers{
@@ -909,13 +909,14 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
Temporal: 0, Temporal: 0,
} }
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
isDeficient: true, isDeficient: true,
bandwidthRequested: 4, bandwidthRequested: 4,
bandwidthDelta: 1, bandwidthDelta: 1,
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: expectedTargetLayers.Spatial,
distanceToDesired: 2, maxLayers: DefaultMaxLayers,
distanceToDesired: 2,
} }
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false) result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -931,13 +932,14 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
Temporal: 3, Temporal: 3,
} }
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
isDeficient: true, isDeficient: true,
bandwidthRequested: 5, bandwidthRequested: 5,
bandwidthDelta: 1, bandwidthDelta: 1,
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: expectedTargetLayers.Spatial,
distanceToDesired: 1, maxLayers: DefaultMaxLayers,
distanceToDesired: 1,
} }
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false) result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -952,12 +954,13 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
Temporal: 1, Temporal: 1,
} }
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
bandwidthRequested: 7, bandwidthRequested: 7,
bandwidthDelta: 2, bandwidthDelta: 2,
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: expectedTargetLayers.Spatial,
distanceToDesired: 0, maxLayers: DefaultMaxLayers,
distanceToDesired: 0,
} }
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false) result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -984,13 +987,14 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
Temporal: 0, Temporal: 0,
} }
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
isDeficient: true, isDeficient: true,
bandwidthRequested: 2, bandwidthRequested: 2,
bandwidthDelta: 2, bandwidthDelta: 2,
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: expectedTargetLayers.Spatial,
distanceToDesired: 4, maxLayers: DefaultMaxLayers,
distanceToDesired: 4,
} }
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false) result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -1000,13 +1004,14 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
// no new available capacity cannot bump up layer // no new available capacity cannot bump up layer
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
isDeficient: true, isDeficient: true,
bandwidthRequested: 2, bandwidthRequested: 2,
bandwidthDelta: 2, bandwidthDelta: 2,
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: expectedTargetLayers.Spatial,
distanceToDesired: 4, maxLayers: DefaultMaxLayers,
distanceToDesired: 4,
} }
result, boosted = f.AllocateNextHigher(0, bitrates, false) result, boosted = f.AllocateNextHigher(0, bitrates, false)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -1034,12 +1039,13 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
Temporal: DefaultMaxLayerTemporal, Temporal: DefaultMaxLayerTemporal,
} }
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
bandwidthRequested: bitrates[1][0], bandwidthRequested: bitrates[1][0],
bandwidthDelta: bitrates[1][0], bandwidthDelta: bitrates[1][0],
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
maxLayers: expectedMaxLayers, requestLayerSpatial: expectedTargetLayers.Spatial,
distanceToDesired: -1, maxLayers: expectedMaxLayers,
distanceToDesired: -1,
} }
// overshoot should return (1, 0) even if there is not enough capacity // overshoot should return (1, 0) even if there is not enough capacity
result, boosted = f.AllocateNextHigher(bitrates[1][0]-1, bitrates, true) result, boosted = f.AllocateNextHigher(bitrates[1][0]-1, bitrates, true)
@@ -1053,6 +1059,7 @@ func TestForwarderPause(t *testing.T) {
f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo)
f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) f.SetMaxSpatialLayer(DefaultMaxLayerSpatial)
f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) f.SetMaxTemporalLayer(DefaultMaxLayerTemporal)
f.SetMaxPublishedLayer(DefaultMaxLayerSpatial)
bitrates := Bitrates{ bitrates := Bitrates{
{1, 2, 3, 4}, {1, 2, 3, 4},
@@ -1066,14 +1073,15 @@ func TestForwarderPause(t *testing.T) {
f.ProvisionalAllocateCommit() f.ProvisionalAllocateCommit()
expectedResult := VideoAllocation{ expectedResult := VideoAllocation{
pauseReason: VideoPauseReasonBandwidth, pauseReason: VideoPauseReasonBandwidth,
isDeficient: true, isDeficient: true,
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0 - bitrates[0][0], bandwidthDelta: 0 - bitrates[0][0],
bitrates: bitrates, bitrates: bitrates,
targetLayers: InvalidLayers, targetLayers: InvalidLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: InvalidLayerSpatial,
distanceToDesired: 12, maxLayers: DefaultMaxLayers,
distanceToDesired: 12,
} }
result := f.Pause(bitrates) result := f.Pause(bitrates)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
@@ -1085,6 +1093,7 @@ func TestForwarderPauseMute(t *testing.T) {
f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo)
f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) f.SetMaxSpatialLayer(DefaultMaxLayerSpatial)
f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) f.SetMaxTemporalLayer(DefaultMaxLayerTemporal)
f.SetMaxPublishedLayer(DefaultMaxLayerSpatial)
bitrates := Bitrates{ bitrates := Bitrates{
{1, 2, 3, 4}, {1, 2, 3, 4},
@@ -1099,13 +1108,14 @@ func TestForwarderPauseMute(t *testing.T) {
f.Mute(true) f.Mute(true)
expectedResult := VideoAllocation{ expectedResult := VideoAllocation{
pauseReason: VideoPauseReasonMuted, pauseReason: VideoPauseReasonMuted,
bandwidthRequested: 0, bandwidthRequested: 0,
bandwidthDelta: 0 - bitrates[0][0], bandwidthDelta: 0 - bitrates[0][0],
bitrates: bitrates, bitrates: bitrates,
targetLayers: InvalidLayers, targetLayers: InvalidLayers,
maxLayers: DefaultMaxLayers, requestLayerSpatial: InvalidLayerSpatial,
distanceToDesired: 0, maxLayers: DefaultMaxLayers,
distanceToDesired: 0,
} }
result := f.Pause(bitrates) result := f.Pause(bitrates)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
+8
View File
@@ -198,6 +198,7 @@ func NewWebRTCReceiver(
w.streamTrackerManager = NewStreamTrackerManager(logger, trackInfo, w.isSVC, w.codec.ClockRate, trackersConfig) w.streamTrackerManager = NewStreamTrackerManager(logger, trackInfo, w.isSVC, w.codec.ClockRate, trackersConfig)
w.streamTrackerManager.OnAvailableLayersChanged(w.downTrackLayerChange) w.streamTrackerManager.OnAvailableLayersChanged(w.downTrackLayerChange)
w.streamTrackerManager.OnBitrateAvailabilityChanged(w.downTrackBitrateAvailabilityChange) w.streamTrackerManager.OnBitrateAvailabilityChanged(w.downTrackBitrateAvailabilityChange)
w.streamTrackerManager.OnMaxPublishedLayerChanged(w.downTrackMaxPublishedLayerChange)
for _, opt := range opts { for _, opt := range opts {
w = opt(w) w = opt(w)
@@ -382,6 +383,7 @@ func (w *WebRTCReceiver) AddDownTrack(track TrackSender) error {
} }
track.TrackInfoAvailable() track.TrackInfoAvailable()
track.UpTrackMaxPublishedLayerChange(w.streamTrackerManager.GetMaxPublishedLayer())
w.downTrackSpreader.Store(track) w.downTrackSpreader.Store(track)
return nil return nil
@@ -403,6 +405,12 @@ func (w *WebRTCReceiver) downTrackBitrateAvailabilityChange() {
} }
} }
func (w *WebRTCReceiver) downTrackMaxPublishedLayerChange(maxPublishedLayer int32) {
for _, dt := range w.downTrackSpreader.GetDownTracks() {
dt.UpTrackMaxPublishedLayerChange(maxPublishedLayer)
}
}
func (w *WebRTCReceiver) GetLayeredBitrate() ([]int32, Bitrates) { func (w *WebRTCReceiver) GetLayeredBitrate() ([]int32, Bitrates) {
return w.streamTrackerManager.GetLayeredBitrate() return w.streamTrackerManager.GetLayeredBitrate()
} }
+6
View File
@@ -240,6 +240,7 @@ func (s *StreamAllocator) AddTrack(downTrack *DownTrack, params AddTrackParams)
downTrack.OnTransportCCFeedback(s.onTransportCCFeedback) downTrack.OnTransportCCFeedback(s.onTransportCCFeedback)
downTrack.OnAvailableLayersChanged(s.onAvailableLayersChanged) downTrack.OnAvailableLayersChanged(s.onAvailableLayersChanged)
downTrack.OnBitrateAvailabilityChanged(s.onBitrateAvailabilityChanged) downTrack.OnBitrateAvailabilityChanged(s.onBitrateAvailabilityChanged)
downTrack.OnMaxPublishedLayerChanged(s.onMaxPublishedLayerChanged)
downTrack.OnSubscriptionChanged(s.onSubscriptionChanged) downTrack.OnSubscriptionChanged(s.onSubscriptionChanged)
downTrack.OnSubscribedLayersChanged(s.onSubscribedLayersChanged) downTrack.OnSubscribedLayersChanged(s.onSubscribedLayersChanged)
downTrack.OnPacketSent(s.onPacketSent) downTrack.OnPacketSent(s.onPacketSent)
@@ -388,6 +389,11 @@ func (s *StreamAllocator) onBitrateAvailabilityChanged(downTrack *DownTrack) {
s.maybePostEventAllocateTrack(downTrack) s.maybePostEventAllocateTrack(downTrack)
} }
// called when feeding track's max publisher layer changes
func (s *StreamAllocator) onMaxPublishedLayerChanged(downTrack *DownTrack) {
s.maybePostEventAllocateTrack(downTrack)
}
// called when subscription settings changes (muting/unmuting of track) // called when subscription settings changes (muting/unmuting of track)
func (s *StreamAllocator) onSubscriptionChanged(downTrack *DownTrack) { func (s *StreamAllocator) onSubscriptionChanged(downTrack *DownTrack) {
s.maybePostEventAllocateTrack(downTrack) s.maybePostEventAllocateTrack(downTrack)
+50 -20
View File
@@ -30,7 +30,8 @@ type StreamTrackerManager struct {
onAvailableLayersChanged func() onAvailableLayersChanged func()
onBitrateAvailabilityChanged func() onBitrateAvailabilityChanged func()
onMaxLayerChanged func(maxLayer int32) onMaxPublishedLayerChanged func(maxPublishedLayer int32)
onMaxAvailableLayerChanged func(maxAvailableLayer int32)
} }
func NewStreamTrackerManager( func NewStreamTrackerManager(
@@ -44,7 +45,7 @@ func NewStreamTrackerManager(
logger: logger, logger: logger,
trackInfo: trackInfo, trackInfo: trackInfo,
isSVC: isSVC, isSVC: isSVC,
maxPublishedLayer: 0, maxPublishedLayer: InvalidLayerSpatial,
clockRate: clockRate, clockRate: clockRate,
} }
@@ -57,14 +58,7 @@ func NewStreamTrackerManager(
s.trackerConfig = trackersConfig.Video s.trackerConfig = trackersConfig.Video
} }
for _, layer := range s.trackInfo.Layers { s.maxExpectedLayerFromTrackInfo()
spatialLayer := buffer.VideoQualityToSpatialLayer(layer.Quality, trackInfo)
if spatialLayer > s.maxPublishedLayer {
s.maxPublishedLayer = spatialLayer
}
}
s.maxExpectedLayer = s.maxPublishedLayer
return s return s
} }
@@ -76,8 +70,12 @@ func (s *StreamTrackerManager) OnBitrateAvailabilityChanged(f func()) {
s.onBitrateAvailabilityChanged = f s.onBitrateAvailabilityChanged = f
} }
func (s *StreamTrackerManager) OnMaxLayerChanged(f func(maxLayer int32)) { func (s *StreamTrackerManager) OnMaxPublishedLayerChanged(f func(maxPublishedLayer int32)) {
s.onMaxLayerChanged = f s.onMaxPublishedLayerChanged = f
}
func (s *StreamTrackerManager) OnMaxLayerChanged(f func(maxAvailableLayer int32)) {
s.onMaxAvailableLayerChanged = f
} }
func (s *StreamTrackerManager) createStreamTrackerPacket(layer int32) streamtracker.StreamTrackerImpl { func (s *StreamTrackerManager) createStreamTrackerPacket(layer int32) streamtracker.StreamTrackerImpl {
@@ -148,8 +146,18 @@ func (s *StreamTrackerManager) AddTracker(layer int32) *streamtracker.StreamTrac
s.lock.Lock() s.lock.Lock()
paused := s.paused paused := s.paused
s.trackers[layer] = tracker s.trackers[layer] = tracker
var onMaxPublishedLayerChanged func(maxPublishedLayer int32)
if layer > s.maxPublishedLayer {
s.maxPublishedLayer = layer
onMaxPublishedLayerChanged = s.onMaxPublishedLayerChanged
}
s.lock.Unlock() s.lock.Unlock()
if onMaxPublishedLayerChanged != nil {
onMaxPublishedLayerChanged(layer)
}
tracker.SetPaused(paused) tracker.SetPaused(paused)
tracker.Start() tracker.Start()
return tracker return tracker
@@ -173,7 +181,7 @@ func (s *StreamTrackerManager) RemoveAllTrackers() {
s.trackers[layer] = nil s.trackers[layer] = nil
} }
s.availableLayers = make([]int32, 0) s.availableLayers = make([]int32, 0)
s.maxExpectedLayer = DefaultMaxLayerSpatial s.maxExpectedLayerFromTrackInfo()
s.paused = false s.paused = false
s.lock.Unlock() s.lock.Unlock()
@@ -256,15 +264,16 @@ func (s *StreamTrackerManager) DistanceToDesired() int32 {
s.lock.RLock() s.lock.RLock()
defer s.lock.RUnlock() defer s.lock.RUnlock()
if s.paused || s.maxExpectedLayer == DefaultMaxLayerSpatial { if s.paused {
return 0 return 0
} }
maxExpectedLayer := s.getMaxExpectedLayerLocked()
if len(s.availableLayers) == 0 { if len(s.availableLayers) == 0 {
return s.maxExpectedLayer + 1 return maxExpectedLayer + 1
} }
distance := s.maxExpectedLayer - s.availableLayers[len(s.availableLayers)-1] distance := maxExpectedLayer - s.availableLayers[len(s.availableLayers)-1]
if distance < 0 { if distance < 0 {
distance = 0 distance = 0
} }
@@ -295,6 +304,10 @@ func (s *StreamTrackerManager) GetMaxExpectedLayer() int32 {
s.lock.RLock() s.lock.RLock()
defer s.lock.RUnlock() defer s.lock.RUnlock()
return s.getMaxExpectedLayerLocked()
}
func (s *StreamTrackerManager) getMaxExpectedLayerLocked() int32 {
// find min of <expected, published> layer // find min of <expected, published> layer
maxExpectedLayer := s.maxExpectedLayer maxExpectedLayer := s.maxExpectedLayer
if maxExpectedLayer > s.maxPublishedLayer { if maxExpectedLayer > s.maxPublishedLayer {
@@ -303,6 +316,13 @@ func (s *StreamTrackerManager) GetMaxExpectedLayer() int32 {
return maxExpectedLayer return maxExpectedLayer
} }
func (s *StreamTrackerManager) GetMaxPublishedLayer() int32 {
s.lock.RLock()
defer s.lock.RUnlock()
return s.maxPublishedLayer
}
func (s *StreamTrackerManager) GetLayeredBitrate() ([]int32, Bitrates) { func (s *StreamTrackerManager) GetLayeredBitrate() ([]int32, Bitrates) {
s.lock.RLock() s.lock.RLock()
defer s.lock.RUnlock() defer s.lock.RUnlock()
@@ -381,8 +401,8 @@ func (s *StreamTrackerManager) addAvailableLayer(layer int32) {
s.onAvailableLayersChanged() s.onAvailableLayersChanged()
} }
if isMaxLayerChange && s.onMaxLayerChanged != nil { if isMaxLayerChange && s.onMaxAvailableLayerChanged != nil {
s.onMaxLayerChanged(layer) s.onMaxAvailableLayerChanged(layer)
} }
} }
@@ -421,7 +441,17 @@ func (s *StreamTrackerManager) removeAvailableLayer(layer int32) {
} }
// if maxLayer was removed, send the new maxLayer // if maxLayer was removed, send the new maxLayer
if curMaxLayer != prevMaxLayer && s.onMaxLayerChanged != nil { if curMaxLayer != prevMaxLayer && s.onMaxAvailableLayerChanged != nil {
s.onMaxLayerChanged(curMaxLayer) s.onMaxAvailableLayerChanged(curMaxLayer)
}
}
func (s *StreamTrackerManager) maxExpectedLayerFromTrackInfo() {
s.maxExpectedLayer = InvalidLayerSpatial
for _, layer := range s.trackInfo.Layers {
spatialLayer := buffer.VideoQualityToSpatialLayer(layer.Quality, s.trackInfo)
if spatialLayer > s.maxExpectedLayer {
s.maxExpectedLayer = spatialLayer
}
} }
} }