diff --git a/pkg/sfu/downtrack.go b/pkg/sfu/downtrack.go index 24429f38..33fa429a 100644 --- a/pkg/sfu/downtrack.go +++ b/pkg/sfu/downtrack.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "io" - "math" "strings" "sync" "time" @@ -29,6 +28,7 @@ import ( type TrackSender interface { UpTrackLayersChange() UpTrackBitrateAvailabilityChange() + UpTrackMaxPublishedLayerChange(maxPublishedLayer int32) WriteRTP(p *buffer.ExtPacket, layer int32) error Close() IsClosed() bool @@ -190,11 +190,14 @@ type DownTrack struct { onTransportCCFeedback func(dt *DownTrack, cc *rtcp.TransportLayerCC) // simulcast layer availability change callback - onAvailableLayersChanged atomic.Value // func(dt *DownTrack) + onAvailableLayersChanged func(dt *DownTrack) // layer bitrate availability change callback onBitrateAvailabilityChanged func(dt *DownTrack) + // max published layer change callback + onMaxPublishedLayerChanged func(dt *DownTrack) + // subscription change callback onSubscriptionChanged func(dt *DownTrack) @@ -214,7 +217,7 @@ type DownTrack struct { onStatsUpdate func(dt *DownTrack, stat *livekit.AnalyticsStat) // when max subscribed layer changes - onMaxLayerChanged func(dt *DownTrack, layer int32) + onMaxSubscribedLayerChanged func(dt *DownTrack, layer int32) // update rtt onRttUpdate func(dt *DownTrack, rtt uint32) @@ -360,7 +363,6 @@ func (d *DownTrack) TrackInfoAvailable() { if ti == nil { return } - d.forwarder.SetNumAdvertisedLayers(int32(math.Max(1, float64(len(ti.Layers))))) d.connectionStats.Start(ti) } @@ -542,23 +544,22 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) error { f(d, pktSize) } - if tp.isSwitchingToMaxLayer && d.onMaxLayerChanged != nil && d.kind == webrtc.RTPCodecTypeVideo { - d.onMaxLayerChanged(d, layer) + if tp.isSwitchingToMaxLayer && d.onMaxSubscribedLayerChanged != nil && d.kind == webrtc.RTPCodecTypeVideo { + d.onMaxSubscribedLayerChanged(d, layer) } if extPkt.KeyFrame || tp.isSwitchingToTargetLayer { 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() if locked { d.stopKeyFrameRequester() } - if extPkt.KeyFrame { - d.logger.Debugw("forwarding key frame", "layer", layer) - } - if tp.isSwitchingToTargetLayer && d.onTargetLayerFound != nil { 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 // 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 if !muted { // @@ -713,7 +714,7 @@ func (d *DownTrack) handleMute(muted bool, isPub bool, changed bool, maxLayers V // notifyLayer = maxLayers.Spatial } - d.onMaxLayerChanged(d, notifyLayer) + d.onMaxSubscribedLayerChanged(d, notifyLayer) } if d.onSubscriptionChanged != nil { @@ -797,8 +798,8 @@ func (d *DownTrack) CloseWithFlush(flush bool) { d.rtpStats.Stop() 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 { - d.onMaxLayerChanged(d, InvalidLayerSpatial) + if d.onMaxSubscribedLayerChanged != nil && d.kind == webrtc.RTPCodecTypeVideo { + d.onMaxSubscribedLayerChanged(d, InvalidLayerSpatial) } if d.onCloseHandler != nil { @@ -814,7 +815,7 @@ func (d *DownTrack) SetMaxSpatialLayer(spatialLayer int32) { 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 // 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 // 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 { @@ -860,8 +861,8 @@ func (d *DownTrack) SeedState(state DownTrackState) { } func (d *DownTrack) UpTrackLayersChange() { - if onAvailableLayersChanged, ok := d.onAvailableLayersChanged.Load().(func(dt *DownTrack)); ok { - onAvailableLayersChanged(d) + if d.onAvailableLayersChanged != nil { + 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 func (d *DownTrack) OnCloseHandler(fn func(willBeResumed bool)) { d.onCloseHandler = fn @@ -896,13 +905,17 @@ func (d *DownTrack) AddReceiverReportListener(listener ReceiverReportListener) { } func (d *DownTrack) OnAvailableLayersChanged(fn func(dt *DownTrack)) { - d.onAvailableLayersChanged.Store(fn) + d.onAvailableLayersChanged = fn } func (d *DownTrack) OnBitrateAvailabilityChanged(fn func(dt *DownTrack)) { d.onBitrateAvailabilityChanged = fn } +func (d *DownTrack) OnMaxPublishedLayerChanged(fn func(dt *DownTrack)) { + d.onMaxPublishedLayerChanged = fn +} + func (d *DownTrack) OnSubscriptionChanged(fn func(dt *DownTrack)) { 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)) { - d.onMaxLayerChanged = fn + d.onMaxSubscribedLayerChanged = fn } func (d *DownTrack) IsDeficient() bool { diff --git a/pkg/sfu/forwarder.go b/pkg/sfu/forwarder.go index 6f196b38..26e980b1 100644 --- a/pkg/sfu/forwarder.go +++ b/pkg/sfu/forwarder.go @@ -55,39 +55,42 @@ func (v VideoPauseReason) String() string { // ------------------------------------------------------------------- type VideoAllocation struct { - pauseReason VideoPauseReason - isDeficient bool - bandwidthRequested int64 - bandwidthDelta int64 - bitrates Bitrates - targetLayers VideoLayers - maxLayers VideoLayers - distanceToDesired int32 + pauseReason VideoPauseReason + isDeficient bool + bandwidthRequested int64 + bandwidthDelta int64 + bitrates Bitrates + targetLayers VideoLayers + requestLayerSpatial int32 + maxLayers VideoLayers + distanceToDesired int32 } 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}", - v.pauseReason, v.isDeficient, v.bandwidthRequested, v.bandwidthDelta, v.bitrates, v.targetLayers, v.maxLayers, v.distanceToDesired) + 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.requestLayerSpatial, v.maxLayers, v.distanceToDesired) } var ( VideoAllocationDefault = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, // start with no feed till feed is seen - targetLayers: InvalidLayers, - maxLayers: InvalidLayers, + pauseReason: VideoPauseReasonFeedDry, // start with no feed till feed is seen + targetLayers: InvalidLayers, + requestLayerSpatial: InvalidLayerSpatial, + maxLayers: InvalidLayers, } ) // ------------------------------------------------------------------- type VideoAllocationProvisional struct { - muted bool - pubMuted bool - bitrates Bitrates - maxLayers VideoLayers - currentLayers VideoLayers - parkedLayers VideoLayers - allocatedLayers VideoLayers + muted bool + pubMuted bool + maxPublishedLayer int32 + bitrates Bitrates + maxLayers VideoLayers + currentLayers VideoLayers + parkedLayers VideoLayers + allocatedLayers VideoLayers } // ------------------------------------------------------------------- @@ -161,20 +164,21 @@ type Forwarder struct { logger logger.Logger getReferenceLayerRTPTimestamp func(ts uint32, layer int32, referenceLayer int32) (uint32, error) - numAdvertisedLayers int32 - muted bool pubMuted bool + maxPublishedLayer int32 + started bool lastSSRC uint32 referenceLayerSpatial int32 - maxLayers VideoLayers - currentLayers VideoLayers - targetLayers VideoLayers - parkedLayers VideoLayers // layers that can resume without key frame - parkedLayersTimer *time.Timer + maxLayers VideoLayers + currentLayers VideoLayers + targetLayers VideoLayers + requestLayerSpatial int32 + parkedLayers VideoLayers // layers that can resume without key frame + parkedLayersTimer *time.Timer provisional *VideoAllocationProvisional @@ -200,12 +204,15 @@ func NewForwarder( logger: logger, getReferenceLayerRTPTimestamp: getReferenceLayerRTPTimestamp, + maxPublishedLayer: InvalidLayerSpatial, + referenceLayerSpatial: InvalidLayerSpatial, // start off with nothing, let streamallocator/opportunistic forwarder set the target - currentLayers: InvalidLayers, - targetLayers: InvalidLayers, - parkedLayers: InvalidLayers, + currentLayers: InvalidLayers, + targetLayers: InvalidLayers, + requestLayerSpatial: InvalidLayerSpatial, + parkedLayers: InvalidLayers, lastAllocation: VideoAllocationDefault, @@ -221,11 +228,16 @@ func NewForwarder( return f } -func (f *Forwarder) SetNumAdvertisedLayers(numAdvertisedLayers int32) { +func (f *Forwarder) SetMaxPublishedLayer(maxPublishedLayer int32) { f.lock.Lock() 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()) { @@ -443,70 +455,6 @@ func (f *Forwarder) IsReducedQuality() (int32, bool) { 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 { return f.lastAllocation.isDeficient } @@ -555,18 +503,32 @@ func (f *Forwarder) AllocateOptimal(availableLayers []int32, brs Bitrates, allow } alloc := VideoAllocation{ - pauseReason: VideoPauseReasonNone, - bitrates: brs, - targetLayers: InvalidLayers, - maxLayers: f.maxLayers, + pauseReason: VideoPauseReasonNone, + bitrates: brs, + targetLayers: InvalidLayers, + 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 } + 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 { - case !f.maxLayers.IsValid(): - // nothing to do when max layers are not valid + case !f.maxLayers.IsValid() || f.maxPublishedLayer == InvalidLayerSpatial: + // nothing to do when max layers are not valid OR max publisher layer is invalid case f.muted: alloc.pauseReason = VideoPauseReasonMuted @@ -575,13 +537,16 @@ func (f *Forwarder) AllocateOptimal(availableLayers []int32, brs Bitrates, allow alloc.pauseReason = VideoPauseReasonPubMuted // leave it at current layers for opportunistic resume alloc.targetLayers = f.currentLayers + alloc.requestLayerSpatial = alloc.targetLayers.Spatial case f.parkedLayers.IsValid(): // if parked on a layer, let it continue alloc.targetLayers = f.parkedLayers + alloc.requestLayerSpatial = alloc.targetLayers.Spatial 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: // 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 // 2. current layer resuming - can latch on when it starts alloc.targetLayers = f.currentLayers + alloc.requestLayerSpatial = alloc.targetLayers.Spatial } 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 - } + opportunisticAlloc() + alloc.requestLayerSpatial = int32(math.Min(float64(f.maxLayers.Spatial), float64(f.maxPublishedLayer))) } default: @@ -623,30 +583,21 @@ func (f *Forwarder) AllocateOptimal(availableLayers []int32, brs Bitrates, allow } alloc.targetLayers.Temporal = DefaultMaxLayerTemporal } else { - if f.targetLayers.IsValid() { - alloc.targetLayers = f.targetLayers - } 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 - } - } + // opportunistically latch on to anything + opportunisticAlloc() } + alloc.requestLayerSpatial = int32(math.Min(float64(f.maxLayers.Spatial), float64(f.maxPublishedLayer))) } if !alloc.targetLayers.IsValid() { alloc.targetLayers = InvalidLayers + alloc.requestLayerSpatial = InvalidLayerSpatial } if alloc.targetLayers.IsValid() { - alloc.bandwidthRequested = brs[alloc.targetLayers.Spatial][alloc.targetLayers.Temporal] + alloc.bandwidthRequested = optimalBandwidthNeeded } 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") } @@ -656,13 +607,14 @@ func (f *Forwarder) ProvisionalAllocatePrepare(bitrates Bitrates) { defer f.lock.Unlock() f.provisional = &VideoAllocationProvisional{ - allocatedLayers: InvalidLayers, - muted: f.muted, - pubMuted: f.pubMuted, - bitrates: bitrates, - maxLayers: f.maxLayers, - currentLayers: f.currentLayers, - parkedLayers: f.parkedLayers, + allocatedLayers: InvalidLayers, + muted: f.muted, + pubMuted: f.pubMuted, + maxPublishedLayer: f.maxPublishedLayer, + bitrates: bitrates, + maxLayers: f.maxLayers, + currentLayers: f.currentLayers, + parkedLayers: f.parkedLayers, } } @@ -670,7 +622,7 @@ func (f *Forwarder) ProvisionalAllocate(availableChannelCapacity int64, layers V f.lock.Lock() 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 } @@ -950,12 +902,20 @@ func (f *Forwarder) ProvisionalAllocateCommit() VideoAllocation { defer f.lock.Unlock() alloc := VideoAllocation{ - bandwidthRequested: 0, - bandwidthDelta: -f.lastAllocation.bandwidthRequested, - bitrates: f.provisional.bitrates, - targetLayers: f.provisional.allocatedLayers, - maxLayers: f.provisional.maxLayers, - distanceToDesired: f.getDistanceToDesired(f.provisional.bitrates, f.provisional.allocatedLayers, f.provisional.maxLayers), + bandwidthRequested: 0, + bandwidthDelta: -f.lastAllocation.bandwidthRequested, + bitrates: f.provisional.bitrates, + targetLayers: f.provisional.allocatedLayers, + requestLayerSpatial: f.provisional.allocatedLayers.Spatial, + 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 { @@ -965,7 +925,13 @@ func (f *Forwarder) ProvisionalAllocateCommit() VideoAllocation { case f.provisional.pubMuted: 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() { // overshoot 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 { f.provisional.allocatedLayers = f.provisional.currentLayers 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 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 alloc.isDeficient = false } else { @@ -1020,7 +993,7 @@ func (f *Forwarder) AllocateNextHigher(availableChannelCapacity int64, brs Bitra return f.lastAllocation, false } - optimalBandwidthNeeded := f.getOptimalBandwidthNeeded(brs, f.maxLayers) + optimalBandwidthNeeded := getOptimalBandwidthNeeded(f.muted, f.pubMuted, f.maxPublishedLayer, brs, f.maxLayers) alreadyAllocated := int64(0) if f.targetLayers.IsValid() { @@ -1045,13 +1018,14 @@ func (f *Forwarder) AllocateNextHigher(availableChannelCapacity int64, brs Bitra targetLayers := VideoLayers{Spatial: s, Temporal: t} alloc := VideoAllocation{ - isDeficient: true, - bandwidthRequested: bandwidthRequested, - bandwidthDelta: bandwidthRequested - alreadyAllocated, - bitrates: brs, - targetLayers: targetLayers, - maxLayers: f.maxLayers, - distanceToDesired: f.getDistanceToDesired(brs, targetLayers, f.maxLayers), + isDeficient: true, + bandwidthRequested: bandwidthRequested, + bandwidthDelta: bandwidthRequested - alreadyAllocated, + bitrates: brs, + targetLayers: targetLayers, + requestLayerSpatial: targetLayers.Spatial, + maxLayers: f.maxLayers, + distanceToDesired: getDistanceToDesired(f.muted, f.pubMuted, f.maxPublishedLayer, brs, targetLayers, f.maxLayers), } if targetLayers.GreaterThan(f.maxLayers) || bandwidthRequested >= optimalBandwidthNeeded { alloc.isDeficient = false @@ -1190,12 +1164,13 @@ func (f *Forwarder) Pause(brs Bitrates) VideoAllocation { defer f.lock.Unlock() alloc := VideoAllocation{ - bandwidthRequested: 0, - bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested, - bitrates: brs, - targetLayers: InvalidLayers, - maxLayers: f.maxLayers, - distanceToDesired: f.getDistanceToDesired(brs, InvalidLayers, f.maxLayers), + bandwidthRequested: 0, + bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested, + bitrates: brs, + targetLayers: InvalidLayers, + requestLayerSpatial: InvalidLayerSpatial, + maxLayers: f.maxLayers, + distanceToDesired: getDistanceToDesired(f.muted, f.pubMuted, f.maxPublishedLayer, brs, InvalidLayers, f.maxLayers), } switch { @@ -1205,7 +1180,7 @@ func (f *Forwarder) Pause(brs Bitrates) VideoAllocation { case f.pubMuted: 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 default: @@ -1226,7 +1201,7 @@ func (f *Forwarder) updateAllocation(alloc VideoAllocation, reason string) Video } f.lastAllocation = alloc - f.setTargetLayers(f.lastAllocation.targetLayers) + f.setTargetLayers(f.lastAllocation.targetLayers, f.lastAllocation.requestLayerSpatial) if !f.targetLayers.IsValid() { f.resyncLocked() } @@ -1234,11 +1209,13 @@ func (f *Forwarder) updateAllocation(alloc VideoAllocation, reason string) Video return f.lastAllocation } -func (f *Forwarder) setTargetLayers(targetLayers VideoLayers) { +func (f *Forwarder) setTargetLayers(targetLayers VideoLayers, requestLayerSpatial int32) { f.targetLayers = targetLayers if f.ddLayerSelector != nil { f.ddLayerSelector.SelectLayer(targetLayers) } + + f.requestLayerSpatial = requestLayerSpatial } func (f *Forwarder) Resync() { @@ -1281,8 +1258,8 @@ func (f *Forwarder) CheckSync() (locked bool, layer int32) { f.lock.RLock() defer f.lock.RUnlock() - layer = f.targetLayers.Spatial - locked = f.targetLayers.Spatial == f.currentLayers.Spatial || f.parkedLayers.IsValid() + layer = f.requestLayerSpatial + locked = f.requestLayerSpatial == f.currentLayers.Spatial || f.parkedLayers.IsValid() return } @@ -1428,7 +1405,7 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in return tp, nil } else if tp.isSwitchingToTargetLayer { // 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 if !f.isTemporalSupported { f.currentLayers.Temporal = f.targetLayers.Temporal @@ -1438,7 +1415,7 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in // if f.ddLayerSelector != nil { // 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 } } @@ -1479,7 +1456,7 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in if found { tp.isSwitchingToTargetLayer = true 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 // 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, "target", f.targetLayers, "max", f.maxLayers, - "advertised", f.numAdvertisedLayers, + "maxPublished", f.maxPublishedLayer, "feed", extPkt.Packet.SSRC, ) f.targetLayers.Spatial = f.currentLayers.Spatial @@ -1502,7 +1479,7 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in f.currentLayers.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 } } @@ -1618,3 +1595,76 @@ func (f *Forwarder) GetRTPMungerParams() RTPMungerParams { 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 +} diff --git a/pkg/sfu/forwarder_test.go b/pkg/sfu/forwarder_test.go index f7fa0bfc..78d82f26 100644 --- a/pkg/sfu/forwarder_test.go +++ b/pkg/sfu/forwarder_test.go @@ -123,13 +123,14 @@ func TestForwarderAllocateOptimal(t *testing.T) { // invalid max layers f.maxLayers = InvalidLayers expectedResult := VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: bitrates, - targetLayers: InvalidLayers, - maxLayers: InvalidLayers, - distanceToDesired: 0, + pauseReason: VideoPauseReasonFeedDry, + bandwidthRequested: 0, + bandwidthDelta: 0, + bitrates: bitrates, + targetLayers: InvalidLayers, + requestLayerSpatial: InvalidLayerSpatial, + maxLayers: InvalidLayers, + distanceToDesired: 0, } result := f.AllocateOptimal(nil, bitrates, true) require.Equal(t, expectedResult, result) @@ -138,17 +139,35 @@ func TestForwarderAllocateOptimal(t *testing.T) { f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) 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 f.Mute(true) disable(f) expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonMuted, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: bitrates, - targetLayers: InvalidLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0, + pauseReason: VideoPauseReasonMuted, + 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) @@ -160,13 +179,14 @@ func TestForwarderAllocateOptimal(t *testing.T) { f.PubMute(true) disable(f) expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonPubMuted, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: bitrates, - targetLayers: InvalidLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0, + pauseReason: VideoPauseReasonPubMuted, + 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) @@ -180,13 +200,14 @@ func TestForwarderAllocateOptimal(t *testing.T) { Temporal: 1, } expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: emptyBitrates, - targetLayers: f.parkedLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0, + pauseReason: VideoPauseReasonFeedDry, + bandwidthRequested: 0, + bandwidthDelta: 0, + bitrates: emptyBitrates, + targetLayers: f.parkedLayers, + requestLayerSpatial: f.parkedLayers.Spatial, + maxLayers: DefaultMaxLayers, + distanceToDesired: 0, } result = f.AllocateOptimal(nil, emptyBitrates, true) require.Equal(t, expectedResult, result) @@ -197,38 +218,39 @@ func TestForwarderAllocateOptimal(t *testing.T) { // when max layers changes, should switch to that f.maxLayers = VideoLayers{Spatial: 1, Temporal: 3} expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: emptyBitrates, - targetLayers: f.maxLayers, - maxLayers: f.maxLayers, - distanceToDesired: 0, + pauseReason: VideoPauseReasonFeedDry, + bandwidthRequested: 0, + bandwidthDelta: 0, + bitrates: emptyBitrates, + targetLayers: DefaultMaxLayers, + requestLayerSpatial: f.maxLayers.Spatial, + maxLayers: f.maxLayers, + distanceToDesired: 0, } result = f.AllocateOptimal(nil, emptyBitrates, true) require.Equal(t, expectedResult, result) 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 f.maxLayers = DefaultMaxLayers f.lastAllocation.maxLayers = DefaultMaxLayers // when feed is dry and current is not valid, should set up for opportunistic forwarding - f.SetNumAdvertisedLayers(3) disable(f) expectedTargetLayers := VideoLayers{ Spatial: 2, Temporal: DefaultMaxLayerTemporal, } expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: emptyBitrates, - targetLayers: expectedTargetLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0, + pauseReason: VideoPauseReasonFeedDry, + bandwidthRequested: 0, + bandwidthDelta: 0, + bitrates: emptyBitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: expectedTargetLayers.Spatial, + maxLayers: DefaultMaxLayers, + distanceToDesired: 0, } result = f.AllocateOptimal(nil, emptyBitrates, true) require.Equal(t, expectedResult, result) @@ -244,13 +266,14 @@ func TestForwarderAllocateOptimal(t *testing.T) { Temporal: 3, } expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: emptyBitrates, - targetLayers: expectedTargetLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0, + pauseReason: VideoPauseReasonFeedDry, + bandwidthRequested: 0, + bandwidthDelta: 0, + bitrates: emptyBitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: expectedTargetLayers.Spatial, + maxLayers: DefaultMaxLayers, + distanceToDesired: 0, } result = f.AllocateOptimal(nil, emptyBitrates, true) require.Equal(t, expectedResult, result) @@ -270,44 +293,47 @@ func TestForwarderAllocateOptimal(t *testing.T) { Temporal: DefaultMaxLayerTemporal, } expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: emptyBitrates, - targetLayers: expectedTargetLayers, - maxLayers: expectedMaxLayers, - distanceToDesired: 0, + pauseReason: VideoPauseReasonFeedDry, + bandwidthRequested: 0, + bandwidthDelta: 0, + bitrates: emptyBitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: expectedTargetLayers.Spatial, + maxLayers: expectedMaxLayers, + distanceToDesired: 0, } result = f.AllocateOptimal(nil, emptyBitrates, false) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) 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{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: emptyBitrates, - targetLayers: expectedTargetLayers, - maxLayers: expectedMaxLayers, - distanceToDesired: 0, + pauseReason: VideoPauseReasonFeedDry, + bandwidthRequested: 0, + bandwidthDelta: 0, + bitrates: emptyBitrates, + targetLayers: DefaultMaxLayers, + requestLayerSpatial: 0, + maxLayers: expectedMaxLayers, + distanceToDesired: 0, } result = f.AllocateOptimal([]int32{0, 1}, emptyBitrates, true) require.Equal(t, expectedResult, result) 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) f.targetLayers = InvalidLayers expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: emptyBitrates, - targetLayers: expectedTargetLayers, - maxLayers: expectedMaxLayers, - distanceToDesired: 0, + pauseReason: VideoPauseReasonFeedDry, + bandwidthRequested: 0, + bandwidthDelta: 0, + bitrates: emptyBitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: 0, + maxLayers: expectedMaxLayers, + distanceToDesired: 0, } result = f.AllocateOptimal([]int32{0, 1}, emptyBitrates, false) require.Equal(t, expectedResult, result) @@ -319,50 +345,34 @@ func TestForwarderAllocateOptimal(t *testing.T) { 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) - 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, + pauseReason: VideoPauseReasonFeedDry, + bandwidthRequested: 0, + bandwidthDelta: 0, + bitrates: emptyBitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: 0, + maxLayers: expectedMaxLayers, + distanceToDesired: 0, } result = f.AllocateOptimal([]int32{0, 1}, emptyBitrates, true) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) // 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{ Spatial: 1, Temporal: DefaultMaxLayerTemporal, } expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: emptyBitrates, - targetLayers: expectedTargetLayers, - maxLayers: expectedMaxLayers, - distanceToDesired: 0, + pauseReason: VideoPauseReasonFeedDry, + bandwidthRequested: 0, + bandwidthDelta: 0, + bitrates: emptyBitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: 0, + maxLayers: expectedMaxLayers, + distanceToDesired: 0, } result = f.AllocateOptimal([]int32{1}, emptyBitrates, true) require.Equal(t, expectedResult, result) @@ -373,6 +383,7 @@ func TestForwarderProvisionalAllocate(t *testing.T) { f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) + f.SetMaxPublishedLayer(DefaultMaxLayerSpatial) bitrates := Bitrates{ {1, 2, 3, 4}, @@ -404,13 +415,14 @@ func TestForwarderProvisionalAllocate(t *testing.T) { Temporal: 2, } expectedResult := VideoAllocation{ - isDeficient: true, - bandwidthRequested: bitrates[1][2], - bandwidthDelta: bitrates[1][2], - bitrates: bitrates, - targetLayers: expectedTargetLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 5, + isDeficient: true, + bandwidthRequested: bitrates[1][2], + bandwidthDelta: bitrates[1][2], + bitrates: bitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: expectedTargetLayers.Spatial, + maxLayers: DefaultMaxLayers, + distanceToDesired: 5, } result := f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -429,13 +441,14 @@ func TestForwarderProvisionalAllocate(t *testing.T) { Temporal: 0, } expectedResult = VideoAllocation{ - isDeficient: true, - bandwidthRequested: bitrates[0][0], - bandwidthDelta: bitrates[0][0] - bitrates[1][2], - bitrates: bitrates, - targetLayers: expectedTargetLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 11, + isDeficient: true, + bandwidthRequested: bitrates[0][0], + bandwidthDelta: bitrates[0][0] - bitrates[1][2], + bitrates: bitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: expectedTargetLayers.Spatial, + maxLayers: DefaultMaxLayers, + distanceToDesired: 11, } result = f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -476,12 +489,13 @@ func TestForwarderProvisionalAllocate(t *testing.T) { Temporal: 3, } expectedResult = VideoAllocation{ - bandwidthRequested: bitrates[1][3], - bandwidthDelta: bitrates[1][3] - 1, // 1 is the last allocation bandwith requested - bitrates: bitrates, - targetLayers: expectedTargetLayers, - maxLayers: expectedMaxLayers, - distanceToDesired: -4, + bandwidthRequested: bitrates[1][3], + bandwidthDelta: bitrates[1][3] - 1, // 1 is the last allocation bandwith requested + bitrates: bitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: expectedTargetLayers.Spatial, + maxLayers: expectedMaxLayers, + distanceToDesired: -4, } result = f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -518,13 +532,14 @@ func TestForwarderProvisionalAllocate(t *testing.T) { Temporal: 2, } expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: bitrates[0][2], - bandwidthDelta: bitrates[0][2] - 8, // 8 is the last allocation bandwith requested - bitrates: bitrates, - targetLayers: expectedTargetLayers, - maxLayers: expectedMaxLayers, - distanceToDesired: 0, + pauseReason: VideoPauseReasonFeedDry, + bandwidthRequested: bitrates[0][2], + bandwidthDelta: bitrates[0][2] - 8, // 8 is the last allocation bandwith requested + bitrates: bitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: expectedTargetLayers.Spatial, + maxLayers: expectedMaxLayers, + distanceToDesired: 0, } result = f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -550,13 +565,14 @@ func TestForwarderProvisionalAllocate(t *testing.T) { require.Equal(t, int64(0), usedBitrate) expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: bitrates, - targetLayers: InvalidLayers, - maxLayers: expectedMaxLayers, - distanceToDesired: 0, + pauseReason: VideoPauseReasonFeedDry, + bandwidthRequested: 0, + bandwidthDelta: 0, + bitrates: bitrates, + targetLayers: InvalidLayers, + requestLayerSpatial: InvalidLayerSpatial, + maxLayers: expectedMaxLayers, + distanceToDesired: 0, } result = f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -587,13 +603,14 @@ func TestForwarderProvisionalAllocateMute(t *testing.T) { // committing should set target to InvalidLayers as track is muted expectedResult := VideoAllocation{ - pauseReason: VideoPauseReasonMuted, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: bitrates, - targetLayers: InvalidLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0, + pauseReason: VideoPauseReasonMuted, + bandwidthRequested: 0, + bandwidthDelta: 0, + bitrates: bitrates, + targetLayers: InvalidLayers, + requestLayerSpatial: InvalidLayerSpatial, + maxLayers: DefaultMaxLayers, + distanceToDesired: 0, } result := f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -605,6 +622,7 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) { f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) + f.SetMaxPublishedLayer(DefaultMaxLayerSpatial) bitrates := Bitrates{ {1, 2, 3, 4}, @@ -626,13 +644,14 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) { // committing should set target to (0, 0) expectedLayers := VideoLayers{Spatial: 0, Temporal: 0} expectedResult := VideoAllocation{ - isDeficient: true, - bandwidthRequested: 1, - bandwidthDelta: 1, - bitrates: bitrates, - targetLayers: expectedLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 9, + isDeficient: true, + bandwidthRequested: 1, + bandwidthDelta: 1, + bitrates: bitrates, + targetLayers: expectedLayers, + requestLayerSpatial: expectedLayers.Spatial, + maxLayers: DefaultMaxLayers, + distanceToDesired: 9, } result := f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -654,12 +673,13 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) { // committing should set target to (2, 1) expectedLayers = VideoLayers{Spatial: 2, Temporal: 1} expectedResult = VideoAllocation{ - bandwidthRequested: 10, - bandwidthDelta: 0, - bitrates: bitrates, - targetLayers: expectedLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0, + bandwidthRequested: 10, + bandwidthDelta: 0, + bitrates: bitrates, + targetLayers: expectedLayers, + requestLayerSpatial: expectedLayers.Spatial, + maxLayers: DefaultMaxLayers, + distanceToDesired: 0, } result = f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -722,12 +742,13 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) { expectedLayers = VideoLayers{Spatial: 1, Temporal: 0} expectedMaxLayers := VideoLayers{Spatial: 0, Temporal: DefaultMaxLayerTemporal} expectedResult = VideoAllocation{ - bandwidthRequested: 5, - bandwidthDelta: 5, - bitrates: bitrates, - targetLayers: expectedLayers, - maxLayers: expectedMaxLayers, - distanceToDesired: -1, + bandwidthRequested: 5, + bandwidthDelta: 5, + bitrates: bitrates, + targetLayers: expectedLayers, + requestLayerSpatial: expectedLayers.Spatial, + maxLayers: expectedMaxLayers, + distanceToDesired: -1, } result = f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -760,12 +781,13 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) { // committing should set target to (0, 2) expectedLayers = VideoLayers{Spatial: 0, Temporal: 2} expectedResult = VideoAllocation{ - bandwidthRequested: 0, - bandwidthDelta: -5, - bitrates: bitrates, - targetLayers: expectedLayers, - maxLayers: expectedMaxLayers, - distanceToDesired: 0, + bandwidthRequested: 0, + bandwidthDelta: -5, + bitrates: bitrates, + targetLayers: expectedLayers, + requestLayerSpatial: expectedLayers.Spatial, + maxLayers: expectedMaxLayers, + distanceToDesired: 0, } result = f.ProvisionalAllocateCommit() 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 expectedResult = VideoAllocation{ - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: bitrates, - targetLayers: expectedLayers, - maxLayers: expectedMaxLayers, - distanceToDesired: 0, + bandwidthRequested: 0, + bandwidthDelta: 0, + bitrates: bitrates, + targetLayers: expectedLayers, + requestLayerSpatial: expectedLayers.Spatial, + maxLayers: expectedMaxLayers, + distanceToDesired: 0, } result = f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -815,6 +838,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) { f := newForwarder(testutils.TestOpusCodec, webrtc.RTPCodecTypeAudio) f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) + f.SetMaxPublishedLayer(DefaultMaxLayerSpatial) emptyBitrates := Bitrates{} bitrates := Bitrates{ @@ -830,6 +854,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) { f = newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) + f.SetMaxPublishedLayer(DefaultMaxLayerSpatial) // when not in deficient state, does not boost result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false) @@ -837,64 +862,34 @@ func TestForwarderAllocateNextHigher(t *testing.T) { require.False(t, boosted) // 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{ Spatial: 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) - require.Equal(t, expectedResult, result) - require.Equal(t, expectedResult, f.lastAllocation) + require.Equal(t, VideoAllocationDefault, result) require.False(t, boosted) - f.currentLayers.Spatial = 0 - f.targetLayers.Temporal = 0 - result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false) - require.Equal(t, expectedResult, result) - require.Equal(t, expectedResult, f.lastAllocation) - 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, + f.lastAllocation.isDeficient = true + f.currentLayers = VideoLayers{ + Spatial: 0, + Temporal: 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 expectedTargetLayers := VideoLayers{ Spatial: 0, Temporal: 1, } - expectedResult = VideoAllocation{ - isDeficient: true, - bandwidthRequested: 3, - bandwidthDelta: 1, - bitrates: bitrates, - targetLayers: expectedTargetLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 3, + expectedResult := VideoAllocation{ + isDeficient: true, + bandwidthRequested: 3, + bandwidthDelta: 1, + bitrates: bitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: expectedTargetLayers.Spatial, + maxLayers: DefaultMaxLayers, + distanceToDesired: 3, } result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false) require.Equal(t, expectedResult, result) @@ -902,6 +897,11 @@ func TestForwarderAllocateNextHigher(t *testing.T) { require.Equal(t, expectedTargetLayers, f.TargetLayers()) 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 f.currentLayers.Temporal = 1 expectedTargetLayers = VideoLayers{ @@ -909,13 +909,14 @@ func TestForwarderAllocateNextHigher(t *testing.T) { Temporal: 0, } expectedResult = VideoAllocation{ - isDeficient: true, - bandwidthRequested: 4, - bandwidthDelta: 1, - bitrates: bitrates, - targetLayers: expectedTargetLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 2, + isDeficient: true, + bandwidthRequested: 4, + bandwidthDelta: 1, + bitrates: bitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: expectedTargetLayers.Spatial, + maxLayers: DefaultMaxLayers, + distanceToDesired: 2, } result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false) require.Equal(t, expectedResult, result) @@ -931,13 +932,14 @@ func TestForwarderAllocateNextHigher(t *testing.T) { Temporal: 3, } expectedResult = VideoAllocation{ - isDeficient: true, - bandwidthRequested: 5, - bandwidthDelta: 1, - bitrates: bitrates, - targetLayers: expectedTargetLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 1, + isDeficient: true, + bandwidthRequested: 5, + bandwidthDelta: 1, + bitrates: bitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: expectedTargetLayers.Spatial, + maxLayers: DefaultMaxLayers, + distanceToDesired: 1, } result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false) require.Equal(t, expectedResult, result) @@ -952,12 +954,13 @@ func TestForwarderAllocateNextHigher(t *testing.T) { Temporal: 1, } expectedResult = VideoAllocation{ - bandwidthRequested: 7, - bandwidthDelta: 2, - bitrates: bitrates, - targetLayers: expectedTargetLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0, + bandwidthRequested: 7, + bandwidthDelta: 2, + bitrates: bitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: expectedTargetLayers.Spatial, + maxLayers: DefaultMaxLayers, + distanceToDesired: 0, } result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false) require.Equal(t, expectedResult, result) @@ -984,13 +987,14 @@ func TestForwarderAllocateNextHigher(t *testing.T) { Temporal: 0, } expectedResult = VideoAllocation{ - isDeficient: true, - bandwidthRequested: 2, - bandwidthDelta: 2, - bitrates: bitrates, - targetLayers: expectedTargetLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 4, + isDeficient: true, + bandwidthRequested: 2, + bandwidthDelta: 2, + bitrates: bitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: expectedTargetLayers.Spatial, + maxLayers: DefaultMaxLayers, + distanceToDesired: 4, } result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates, false) require.Equal(t, expectedResult, result) @@ -1000,13 +1004,14 @@ func TestForwarderAllocateNextHigher(t *testing.T) { // no new available capacity cannot bump up layer expectedResult = VideoAllocation{ - isDeficient: true, - bandwidthRequested: 2, - bandwidthDelta: 2, - bitrates: bitrates, - targetLayers: expectedTargetLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 4, + isDeficient: true, + bandwidthRequested: 2, + bandwidthDelta: 2, + bitrates: bitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: expectedTargetLayers.Spatial, + maxLayers: DefaultMaxLayers, + distanceToDesired: 4, } result, boosted = f.AllocateNextHigher(0, bitrates, false) require.Equal(t, expectedResult, result) @@ -1034,12 +1039,13 @@ func TestForwarderAllocateNextHigher(t *testing.T) { Temporal: DefaultMaxLayerTemporal, } expectedResult = VideoAllocation{ - bandwidthRequested: bitrates[1][0], - bandwidthDelta: bitrates[1][0], - bitrates: bitrates, - targetLayers: expectedTargetLayers, - maxLayers: expectedMaxLayers, - distanceToDesired: -1, + bandwidthRequested: bitrates[1][0], + bandwidthDelta: bitrates[1][0], + bitrates: bitrates, + targetLayers: expectedTargetLayers, + requestLayerSpatial: expectedTargetLayers.Spatial, + maxLayers: expectedMaxLayers, + distanceToDesired: -1, } // overshoot should return (1, 0) even if there is not enough capacity 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.SetMaxSpatialLayer(DefaultMaxLayerSpatial) f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) + f.SetMaxPublishedLayer(DefaultMaxLayerSpatial) bitrates := Bitrates{ {1, 2, 3, 4}, @@ -1066,14 +1073,15 @@ func TestForwarderPause(t *testing.T) { f.ProvisionalAllocateCommit() expectedResult := VideoAllocation{ - pauseReason: VideoPauseReasonBandwidth, - isDeficient: true, - bandwidthRequested: 0, - bandwidthDelta: 0 - bitrates[0][0], - bitrates: bitrates, - targetLayers: InvalidLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 12, + pauseReason: VideoPauseReasonBandwidth, + isDeficient: true, + bandwidthRequested: 0, + bandwidthDelta: 0 - bitrates[0][0], + bitrates: bitrates, + targetLayers: InvalidLayers, + requestLayerSpatial: InvalidLayerSpatial, + maxLayers: DefaultMaxLayers, + distanceToDesired: 12, } result := f.Pause(bitrates) require.Equal(t, expectedResult, result) @@ -1085,6 +1093,7 @@ func TestForwarderPauseMute(t *testing.T) { f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) + f.SetMaxPublishedLayer(DefaultMaxLayerSpatial) bitrates := Bitrates{ {1, 2, 3, 4}, @@ -1099,13 +1108,14 @@ func TestForwarderPauseMute(t *testing.T) { f.Mute(true) expectedResult := VideoAllocation{ - pauseReason: VideoPauseReasonMuted, - bandwidthRequested: 0, - bandwidthDelta: 0 - bitrates[0][0], - bitrates: bitrates, - targetLayers: InvalidLayers, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0, + pauseReason: VideoPauseReasonMuted, + bandwidthRequested: 0, + bandwidthDelta: 0 - bitrates[0][0], + bitrates: bitrates, + targetLayers: InvalidLayers, + requestLayerSpatial: InvalidLayerSpatial, + maxLayers: DefaultMaxLayers, + distanceToDesired: 0, } result := f.Pause(bitrates) require.Equal(t, expectedResult, result) diff --git a/pkg/sfu/receiver.go b/pkg/sfu/receiver.go index ea7f8b5b..2ec94bff 100644 --- a/pkg/sfu/receiver.go +++ b/pkg/sfu/receiver.go @@ -198,6 +198,7 @@ func NewWebRTCReceiver( w.streamTrackerManager = NewStreamTrackerManager(logger, trackInfo, w.isSVC, w.codec.ClockRate, trackersConfig) w.streamTrackerManager.OnAvailableLayersChanged(w.downTrackLayerChange) w.streamTrackerManager.OnBitrateAvailabilityChanged(w.downTrackBitrateAvailabilityChange) + w.streamTrackerManager.OnMaxPublishedLayerChanged(w.downTrackMaxPublishedLayerChange) for _, opt := range opts { w = opt(w) @@ -382,6 +383,7 @@ func (w *WebRTCReceiver) AddDownTrack(track TrackSender) error { } track.TrackInfoAvailable() + track.UpTrackMaxPublishedLayerChange(w.streamTrackerManager.GetMaxPublishedLayer()) w.downTrackSpreader.Store(track) 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) { return w.streamTrackerManager.GetLayeredBitrate() } diff --git a/pkg/sfu/streamallocator.go b/pkg/sfu/streamallocator.go index 83a1c244..3885158e 100644 --- a/pkg/sfu/streamallocator.go +++ b/pkg/sfu/streamallocator.go @@ -240,6 +240,7 @@ func (s *StreamAllocator) AddTrack(downTrack *DownTrack, params AddTrackParams) downTrack.OnTransportCCFeedback(s.onTransportCCFeedback) downTrack.OnAvailableLayersChanged(s.onAvailableLayersChanged) downTrack.OnBitrateAvailabilityChanged(s.onBitrateAvailabilityChanged) + downTrack.OnMaxPublishedLayerChanged(s.onMaxPublishedLayerChanged) downTrack.OnSubscriptionChanged(s.onSubscriptionChanged) downTrack.OnSubscribedLayersChanged(s.onSubscribedLayersChanged) downTrack.OnPacketSent(s.onPacketSent) @@ -388,6 +389,11 @@ func (s *StreamAllocator) onBitrateAvailabilityChanged(downTrack *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) func (s *StreamAllocator) onSubscriptionChanged(downTrack *DownTrack) { s.maybePostEventAllocateTrack(downTrack) diff --git a/pkg/sfu/streamtrackermanager.go b/pkg/sfu/streamtrackermanager.go index ca381e60..9684fd04 100644 --- a/pkg/sfu/streamtrackermanager.go +++ b/pkg/sfu/streamtrackermanager.go @@ -30,7 +30,8 @@ type StreamTrackerManager struct { onAvailableLayersChanged func() onBitrateAvailabilityChanged func() - onMaxLayerChanged func(maxLayer int32) + onMaxPublishedLayerChanged func(maxPublishedLayer int32) + onMaxAvailableLayerChanged func(maxAvailableLayer int32) } func NewStreamTrackerManager( @@ -44,7 +45,7 @@ func NewStreamTrackerManager( logger: logger, trackInfo: trackInfo, isSVC: isSVC, - maxPublishedLayer: 0, + maxPublishedLayer: InvalidLayerSpatial, clockRate: clockRate, } @@ -57,14 +58,7 @@ func NewStreamTrackerManager( s.trackerConfig = trackersConfig.Video } - for _, layer := range s.trackInfo.Layers { - spatialLayer := buffer.VideoQualityToSpatialLayer(layer.Quality, trackInfo) - if spatialLayer > s.maxPublishedLayer { - s.maxPublishedLayer = spatialLayer - } - } - s.maxExpectedLayer = s.maxPublishedLayer - + s.maxExpectedLayerFromTrackInfo() return s } @@ -76,8 +70,12 @@ func (s *StreamTrackerManager) OnBitrateAvailabilityChanged(f func()) { s.onBitrateAvailabilityChanged = f } -func (s *StreamTrackerManager) OnMaxLayerChanged(f func(maxLayer int32)) { - s.onMaxLayerChanged = f +func (s *StreamTrackerManager) OnMaxPublishedLayerChanged(f func(maxPublishedLayer int32)) { + s.onMaxPublishedLayerChanged = f +} + +func (s *StreamTrackerManager) OnMaxLayerChanged(f func(maxAvailableLayer int32)) { + s.onMaxAvailableLayerChanged = f } func (s *StreamTrackerManager) createStreamTrackerPacket(layer int32) streamtracker.StreamTrackerImpl { @@ -148,8 +146,18 @@ func (s *StreamTrackerManager) AddTracker(layer int32) *streamtracker.StreamTrac s.lock.Lock() paused := s.paused s.trackers[layer] = tracker + + var onMaxPublishedLayerChanged func(maxPublishedLayer int32) + if layer > s.maxPublishedLayer { + s.maxPublishedLayer = layer + onMaxPublishedLayerChanged = s.onMaxPublishedLayerChanged + } s.lock.Unlock() + if onMaxPublishedLayerChanged != nil { + onMaxPublishedLayerChanged(layer) + } + tracker.SetPaused(paused) tracker.Start() return tracker @@ -173,7 +181,7 @@ func (s *StreamTrackerManager) RemoveAllTrackers() { s.trackers[layer] = nil } s.availableLayers = make([]int32, 0) - s.maxExpectedLayer = DefaultMaxLayerSpatial + s.maxExpectedLayerFromTrackInfo() s.paused = false s.lock.Unlock() @@ -256,15 +264,16 @@ func (s *StreamTrackerManager) DistanceToDesired() int32 { s.lock.RLock() defer s.lock.RUnlock() - if s.paused || s.maxExpectedLayer == DefaultMaxLayerSpatial { + if s.paused { return 0 } + maxExpectedLayer := s.getMaxExpectedLayerLocked() 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 { distance = 0 } @@ -295,6 +304,10 @@ func (s *StreamTrackerManager) GetMaxExpectedLayer() int32 { s.lock.RLock() defer s.lock.RUnlock() + return s.getMaxExpectedLayerLocked() +} + +func (s *StreamTrackerManager) getMaxExpectedLayerLocked() int32 { // find min of layer maxExpectedLayer := s.maxExpectedLayer if maxExpectedLayer > s.maxPublishedLayer { @@ -303,6 +316,13 @@ func (s *StreamTrackerManager) GetMaxExpectedLayer() int32 { return maxExpectedLayer } +func (s *StreamTrackerManager) GetMaxPublishedLayer() int32 { + s.lock.RLock() + defer s.lock.RUnlock() + + return s.maxPublishedLayer +} + func (s *StreamTrackerManager) GetLayeredBitrate() ([]int32, Bitrates) { s.lock.RLock() defer s.lock.RUnlock() @@ -381,8 +401,8 @@ func (s *StreamTrackerManager) addAvailableLayer(layer int32) { s.onAvailableLayersChanged() } - if isMaxLayerChange && s.onMaxLayerChanged != nil { - s.onMaxLayerChanged(layer) + if isMaxLayerChange && s.onMaxAvailableLayerChanged != nil { + s.onMaxAvailableLayerChanged(layer) } } @@ -421,7 +441,17 @@ func (s *StreamTrackerManager) removeAvailableLayer(layer int32) { } // if maxLayer was removed, send the new maxLayer - if curMaxLayer != prevMaxLayer && s.onMaxLayerChanged != nil { - s.onMaxLayerChanged(curMaxLayer) + if curMaxLayer != prevMaxLayer && s.onMaxAvailableLayerChanged != nil { + 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 + } } }