diff --git a/pkg/rtc/mediatrackreceiver.go b/pkg/rtc/mediatrackreceiver.go index e1b54c1e..0ae04a97 100644 --- a/pkg/rtc/mediatrackreceiver.go +++ b/pkg/rtc/mediatrackreceiver.go @@ -240,7 +240,7 @@ func (t *MediaTrackReceiver) SetLayerSsrc(mime string, rid string, ssrc uint32) defer t.lock.Unlock() layer := buffer.RidToSpatialLayer(rid, t.params.TrackInfo) - if layer == sfu.InvalidLayerSpatial { + if layer == buffer.InvalidLayerSpatial { // non-simulcast case will not have `rid` layer = 0 } diff --git a/pkg/rtc/participant.go b/pkg/rtc/participant.go index 61f3eb3f..7838f853 100644 --- a/pkg/rtc/participant.go +++ b/pkg/rtc/participant.go @@ -24,6 +24,7 @@ import ( "github.com/livekit/livekit-server/pkg/sfu" "github.com/livekit/livekit-server/pkg/sfu/buffer" "github.com/livekit/livekit-server/pkg/sfu/connectionquality" + "github.com/livekit/livekit-server/pkg/sfu/streamallocator" "github.com/livekit/livekit-server/pkg/telemetry" "github.com/livekit/mediatransportutil/pkg/twcc" "github.com/livekit/protocol/auth" @@ -1338,7 +1339,7 @@ func (p *ParticipantImpl) subscriberRTCPWorker() { } } -func (p *ParticipantImpl) onStreamStateChange(update *sfu.StreamStateUpdate) error { +func (p *ParticipantImpl) onStreamStateChange(update *streamallocator.StreamStateUpdate) error { if len(update.StreamStates) == 0 { return nil } @@ -1346,7 +1347,7 @@ func (p *ParticipantImpl) onStreamStateChange(update *sfu.StreamStateUpdate) err streamStateUpdate := &livekit.StreamStateUpdate{} for _, streamStateInfo := range update.StreamStates { state := livekit.StreamState_ACTIVE - if streamStateInfo.State == sfu.StreamStatePaused { + if streamStateInfo.State == streamallocator.StreamStatePaused { state = livekit.StreamState_PAUSED } streamStateUpdate.StreamStates = append(streamStateUpdate.StreamStates, &livekit.StreamStateInfo{ diff --git a/pkg/rtc/transport.go b/pkg/rtc/transport.go index 14055d0a..379ac5be 100644 --- a/pkg/rtc/transport.go +++ b/pkg/rtc/transport.go @@ -26,7 +26,7 @@ import ( "github.com/livekit/livekit-server/pkg/config" serverlogger "github.com/livekit/livekit-server/pkg/logger" "github.com/livekit/livekit-server/pkg/rtc/types" - "github.com/livekit/livekit-server/pkg/sfu" + "github.com/livekit/livekit-server/pkg/sfu/streamallocator" "github.com/livekit/livekit-server/pkg/telemetry" "github.com/livekit/livekit-server/pkg/telemetry/prometheus" ) @@ -182,7 +182,7 @@ type PCTransport struct { onNegotiationFailed func() // stream allocator for subscriber PC - streamAllocator *sfu.StreamAllocator + streamAllocator *streamallocator.StreamAllocator previousAnswer *webrtc.SessionDescription // track id -> description map in previous offer sdp @@ -366,7 +366,7 @@ func NewPCTransport(params TransportParams) (*PCTransport, error) { canReuseTransceiver: true, } if params.IsSendSide { - t.streamAllocator = sfu.NewStreamAllocator(sfu.StreamAllocatorParams{ + t.streamAllocator = streamallocator.NewStreamAllocator(streamallocator.StreamAllocatorParams{ Config: params.CongestionControlConfig, Logger: params.Logger, }) @@ -1085,7 +1085,7 @@ func (t *PCTransport) ResetShortConnOnICERestart() { t.resetShortConnOnICERestart.Store(true) } -func (t *PCTransport) OnStreamStateChange(f func(update *sfu.StreamStateUpdate) error) { +func (t *PCTransport) OnStreamStateChange(f func(update *streamallocator.StreamStateUpdate) error) { if t.streamAllocator == nil { return } @@ -1098,7 +1098,7 @@ func (t *PCTransport) AddTrackToStreamAllocator(subTrack types.SubscribedTrack) return } - t.streamAllocator.AddTrack(subTrack.DownTrack(), sfu.AddTrackParams{ + t.streamAllocator.AddTrack(subTrack.DownTrack(), streamallocator.AddTrackParams{ Source: subTrack.MediaTrack().Source(), IsSimulcast: subTrack.MediaTrack().IsSimulcast(), PublisherID: subTrack.MediaTrack().PublisherID(), diff --git a/pkg/rtc/transportmanager.go b/pkg/rtc/transportmanager.go index cee3c366..cc883a1b 100644 --- a/pkg/rtc/transportmanager.go +++ b/pkg/rtc/transportmanager.go @@ -17,6 +17,7 @@ import ( "github.com/livekit/livekit-server/pkg/config" "github.com/livekit/livekit-server/pkg/rtc/types" "github.com/livekit/livekit-server/pkg/sfu" + "github.com/livekit/livekit-server/pkg/sfu/streamallocator" "github.com/livekit/livekit-server/pkg/telemetry" "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" @@ -243,7 +244,7 @@ func (t *TransportManager) OnSubscriberInitialConnected(f func()) { t.onSubscriberInitialConnected = f } -func (t *TransportManager) OnSubscriberStreamStateChange(f func(update *sfu.StreamStateUpdate) error) { +func (t *TransportManager) OnSubscriberStreamStateChange(f func(update *streamallocator.StreamStateUpdate) error) { t.subscriber.OnStreamStateChange(f) } diff --git a/pkg/sfu/buffer/videolayer.go b/pkg/sfu/buffer/videolayer.go index dce60597..15dd655f 100644 --- a/pkg/sfu/buffer/videolayer.go +++ b/pkg/sfu/buffer/videolayer.go @@ -15,6 +15,11 @@ var ( Spatial: InvalidLayerSpatial, Temporal: InvalidLayerTemporal, } + + DefaultMaxLayers = VideoLayer{ + Spatial: DefaultMaxLayerSpatial, + Temporal: DefaultMaxLayerTemporal, + } ) type VideoLayer struct { diff --git a/pkg/sfu/downtrack.go b/pkg/sfu/downtrack.go index 9a4507fa..c1d72f28 100644 --- a/pkg/sfu/downtrack.go +++ b/pkg/sfu/downtrack.go @@ -141,7 +141,7 @@ type DownTrackStreamAllocatorListener interface { OnSubscriptionChanged(dt *DownTrack) // subscribed max video layer changed - OnSubscribedLayersChanged(dt *DownTrack, layers VideoLayers) + OnSubscribedLayersChanged(dt *DownTrack, layers buffer.VideoLayer) // target video layer reached OnTargetLayerReached(dt *DownTrack) @@ -508,7 +508,7 @@ func (d *DownTrack) stopKeyFrameRequester() { } func (d *DownTrack) keyFrameRequester(generation uint32, layer int32) { - if d.IsClosed() || layer == InvalidLayerSpatial { + if d.IsClosed() || layer == buffer.InvalidLayerSpatial { return } interval := 2 * d.rtpStats.GetRtt() @@ -739,7 +739,7 @@ func (d *DownTrack) PubMute(pubMuted bool) { d.handleMute(pubMuted, true, changed, maxLayers) } -func (d *DownTrack) handleMute(muted bool, isPub bool, changed bool, maxLayers VideoLayers) { +func (d *DownTrack) handleMute(muted bool, isPub bool, changed bool, maxLayers buffer.VideoLayer) { if !changed { return } @@ -767,7 +767,7 @@ func (d *DownTrack) handleMute(muted bool, isPub bool, changed bool, maxLayers V // and that could turn on/off layers on publisher side. // if !isPub && d.onMaxSubscribedLayerChanged != nil && d.kind == webrtc.RTPCodecTypeVideo { - notifyLayer := InvalidLayerSpatial + notifyLayer := buffer.InvalidLayerSpatial if !muted { // // When unmuting, don't wait for layer lock as @@ -861,7 +861,7 @@ func (d *DownTrack) CloseWithFlush(flush bool) { d.logger.Infow("rtp stats", "direction", "downstream", "mime", d.mime, "ssrc", d.ssrc, "stats", d.rtpStats.ToString()) if d.onMaxSubscribedLayerChanged != nil && d.kind == webrtc.RTPCodecTypeVideo { - d.onMaxSubscribedLayerChanged(d, InvalidLayerSpatial) + d.onMaxSubscribedLayerChanged(d, buffer.InvalidLayerSpatial) } if d.onCloseHandler != nil { @@ -905,7 +905,7 @@ func (d *DownTrack) SetMaxTemporalLayer(temporalLayer int32) { } } -func (d *DownTrack) MaxLayers() VideoLayers { +func (d *DownTrack) MaxLayers() buffer.VideoLayer { return d.forwarder.MaxLayers() } @@ -1008,7 +1008,7 @@ func (d *DownTrack) AllocateOptimal(allowOvershoot bool) VideoAllocation { al, brs := d.receiver.GetLayeredBitrate() allocation := d.forwarder.AllocateOptimal(al, brs, allowOvershoot) d.maybeStartKeyFrameRequester() - d.maybeAddTransition(allocation.bandwidthNeeded, allocation.distanceToDesired) + d.maybeAddTransition(allocation.BandwidthNeeded, allocation.DistanceToDesired) return allocation } @@ -1017,7 +1017,7 @@ func (d *DownTrack) ProvisionalAllocatePrepare() { d.forwarder.ProvisionalAllocatePrepare(al, brs) } -func (d *DownTrack) ProvisionalAllocate(availableChannelCapacity int64, layers VideoLayers, allowPause bool, allowOvershoot bool) int64 { +func (d *DownTrack) ProvisionalAllocate(availableChannelCapacity int64, layers buffer.VideoLayer, allowPause bool, allowOvershoot bool) int64 { return d.forwarder.ProvisionalAllocate(availableChannelCapacity, layers, allowPause, allowOvershoot) } @@ -1036,7 +1036,7 @@ func (d *DownTrack) ProvisionalAllocateGetBestWeightedTransition() VideoTransiti func (d *DownTrack) ProvisionalAllocateCommit() VideoAllocation { allocation := d.forwarder.ProvisionalAllocateCommit() d.maybeStartKeyFrameRequester() - d.maybeAddTransition(allocation.bandwidthNeeded, allocation.distanceToDesired) + d.maybeAddTransition(allocation.BandwidthNeeded, allocation.DistanceToDesired) return allocation } @@ -1044,7 +1044,7 @@ func (d *DownTrack) AllocateNextHigher(availableChannelCapacity int64, allowOver al, brs := d.receiver.GetLayeredBitrate() allocation, available := d.forwarder.AllocateNextHigher(availableChannelCapacity, al, brs, allowOvershoot) d.maybeStartKeyFrameRequester() - d.maybeAddTransition(allocation.bandwidthNeeded, allocation.distanceToDesired) + d.maybeAddTransition(allocation.BandwidthNeeded, allocation.DistanceToDesired) return allocation, available } @@ -1059,7 +1059,7 @@ func (d *DownTrack) Pause() VideoAllocation { al, brs := d.receiver.GetLayeredBitrate() allocation := d.forwarder.Pause(al, brs) d.maybeStartKeyFrameRequester() - d.maybeAddTransition(allocation.bandwidthNeeded, allocation.distanceToDesired) + d.maybeAddTransition(allocation.BandwidthNeeded, allocation.DistanceToDesired) return allocation } @@ -1278,7 +1278,7 @@ func (d *DownTrack) handleRTCP(bytes []byte) { sendPliOnce := func() { if pliOnce { _, layer := d.forwarder.CheckSync() - if layer != InvalidLayerSpatial && !d.forwarder.IsAnyMuted() { + if layer != buffer.InvalidLayerSpatial && !d.forwarder.IsAnyMuted() { d.logger.Debugw("sending PLI RTCP", "layer", layer) d.receiver.SendPLI(layer, false) d.isNACKThrottled.Store(true) @@ -1637,7 +1637,7 @@ func (d *DownTrack) onBindAndConnected() { if d.connected.Load() && d.bound.Load() && !d.bindAndConnectedOnce.Swap(true) { if d.kind == webrtc.RTPCodecTypeVideo { _, layer := d.forwarder.CheckSync() - if layer != InvalidLayerSpatial { + if layer != buffer.InvalidLayerSpatial { d.receiver.SendPLI(layer, true) } } diff --git a/pkg/sfu/forwarder.go b/pkg/sfu/forwarder.go index 7cb65dcb..fde7e1cc 100644 --- a/pkg/sfu/forwarder.go +++ b/pkg/sfu/forwarder.go @@ -55,39 +55,39 @@ func (v VideoPauseReason) String() string { // ------------------------------------------------------------------- type VideoAllocation struct { - pauseReason VideoPauseReason - isDeficient bool - bandwidthRequested int64 - bandwidthDelta int64 - bandwidthNeeded int64 - bitrates Bitrates - targetLayers VideoLayers - requestLayerSpatial int32 - maxLayers VideoLayers - distanceToDesired float64 + PauseReason VideoPauseReason + IsDeficient bool + BandwidthRequested int64 + BandwidthDelta int64 + BandwidthNeeded int64 + Bitrates Bitrates + TargetLayers buffer.VideoLayer + RequestLayerSpatial int32 + MaxLayers buffer.VideoLayer + DistanceToDesired float64 } func (v VideoAllocation) String() string { return fmt.Sprintf("VideoAllocation{pause: %s, def: %+v, bwr: %d, del: %d, bwn: %d, rates: %+v, target: %s, req: %d, max: %s, dist: %0.2f}", - v.pauseReason, - v.isDeficient, - v.bandwidthRequested, - v.bandwidthDelta, - v.bandwidthNeeded, - v.bitrates, - v.targetLayers, - v.requestLayerSpatial, - v.maxLayers, - v.distanceToDesired, + v.PauseReason, + v.IsDeficient, + v.BandwidthRequested, + v.BandwidthDelta, + v.BandwidthNeeded, + 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, - requestLayerSpatial: InvalidLayerSpatial, - maxLayers: InvalidLayers, + PauseReason: VideoPauseReasonFeedDry, // start with no feed till feed is seen + TargetLayers: buffer.InvalidLayers, + RequestLayerSpatial: buffer.InvalidLayerSpatial, + MaxLayers: buffer.InvalidLayers, } ) @@ -99,23 +99,23 @@ type VideoAllocationProvisional struct { maxPublishedLayer int32 maxTemporalLayerSeen int32 availableLayers []int32 - bitrates Bitrates - maxLayers VideoLayers - currentLayers VideoLayers - parkedLayers VideoLayers - allocatedLayers VideoLayers + Bitrates Bitrates + maxLayers buffer.VideoLayer + currentLayers buffer.VideoLayer + parkedLayers buffer.VideoLayer + allocatedLayers buffer.VideoLayer } // ------------------------------------------------------------------- type VideoTransition struct { - from VideoLayers - to VideoLayers - bandwidthDelta int64 + From buffer.VideoLayer + To buffer.VideoLayer + BandwidthDelta int64 } func (v VideoTransition) String() string { - return fmt.Sprintf("VideoTransition{from: %s, to: %s, del: %d}", v.from, v.to, v.bandwidthDelta) + return fmt.Sprintf("VideoTransition{from: %s, to: %s, del: %d}", v.From, v.To, v.BandwidthDelta) } // ------------------------------------------------------------------- @@ -137,27 +137,6 @@ type TranslationParams struct { // ------------------------------------------------------------------- -type VideoLayers = buffer.VideoLayer - -const ( - InvalidLayerSpatial = buffer.InvalidLayerSpatial - InvalidLayerTemporal = buffer.InvalidLayerTemporal - - DefaultMaxLayerSpatial = buffer.DefaultMaxLayerSpatial - DefaultMaxLayerTemporal = buffer.DefaultMaxLayerTemporal -) - -var ( - InvalidLayers = buffer.InvalidLayers - - DefaultMaxLayers = VideoLayers{ - Spatial: DefaultMaxLayerSpatial, - Temporal: DefaultMaxLayerTemporal, - } -) - -// ------------------------------------------------------------------- - type ForwarderState struct { Started bool RTP RTPMungerState @@ -187,11 +166,11 @@ type Forwarder struct { lastSSRC uint32 referenceLayerSpatial int32 - maxLayers VideoLayers - currentLayers VideoLayers - targetLayers VideoLayers + maxLayers buffer.VideoLayer + currentLayers buffer.VideoLayer + targetLayers buffer.VideoLayer requestLayerSpatial int32 - parkedLayers VideoLayers // layers that can resume without key frame + parkedLayers buffer.VideoLayer // layers that can resume without key frame parkedLayersTimer *time.Timer provisional *VideoAllocationProvisional @@ -218,16 +197,16 @@ func NewForwarder( logger: logger, getReferenceLayerRTPTimestamp: getReferenceLayerRTPTimestamp, - maxPublishedLayer: InvalidLayerSpatial, - maxTemporalLayerSeen: InvalidLayerTemporal, + maxPublishedLayer: buffer.InvalidLayerSpatial, + maxTemporalLayerSeen: buffer.InvalidLayerTemporal, - referenceLayerSpatial: InvalidLayerSpatial, + referenceLayerSpatial: buffer.InvalidLayerSpatial, // start off with nothing, let streamallocator/opportunistic forwarder set the target - currentLayers: InvalidLayers, - targetLayers: InvalidLayers, - requestLayerSpatial: InvalidLayerSpatial, - parkedLayers: InvalidLayers, + currentLayers: buffer.InvalidLayers, + targetLayers: buffer.InvalidLayers, + requestLayerSpatial: buffer.InvalidLayerSpatial, + parkedLayers: buffer.InvalidLayers, lastAllocation: VideoAllocationDefault, @@ -235,9 +214,9 @@ func NewForwarder( } if f.kind == webrtc.RTPCodecTypeVideo { - f.maxLayers = VideoLayers{Spatial: InvalidLayerSpatial, Temporal: DefaultMaxLayerTemporal} + f.maxLayers = buffer.VideoLayer{Spatial: buffer.InvalidLayerSpatial, Temporal: buffer.DefaultMaxLayerTemporal} } else { - f.maxLayers = InvalidLayers + f.maxLayers = buffer.InvalidLayers } return f @@ -337,7 +316,7 @@ func (f *Forwarder) SeedState(state ForwarderState) { f.started = true } -func (f *Forwarder) Mute(muted bool) (bool, VideoLayers) { +func (f *Forwarder) Mute(muted bool) (bool, buffer.VideoLayer) { f.lock.Lock() defer f.lock.Unlock() @@ -363,7 +342,7 @@ func (f *Forwarder) IsMuted() bool { return f.muted } -func (f *Forwarder) PubMute(pubMuted bool) (bool, VideoLayers) { +func (f *Forwarder) PubMute(pubMuted bool) (bool, buffer.VideoLayer) { f.lock.Lock() defer f.lock.Unlock() @@ -385,7 +364,7 @@ func (f *Forwarder) PubMute(pubMuted bool) (bool, VideoLayers) { // On unmute, park current layers as streaming can continue without a key frame when publisher starts the stream. if !pubMuted && f.targetLayers.IsValid() && f.currentLayers.Spatial == f.targetLayers.Spatial { f.setupParkedLayers(f.targetLayers) - f.currentLayers = InvalidLayers + f.currentLayers = buffer.InvalidLayers } } @@ -406,7 +385,7 @@ func (f *Forwarder) IsAnyMuted() bool { return f.muted || f.pubMuted } -func (f *Forwarder) SetMaxSpatialLayer(spatialLayer int32) (bool, VideoLayers, VideoLayers) { +func (f *Forwarder) SetMaxSpatialLayer(spatialLayer int32) (bool, buffer.VideoLayer, buffer.VideoLayer) { f.lock.Lock() defer f.lock.Unlock() @@ -422,7 +401,7 @@ func (f *Forwarder) SetMaxSpatialLayer(spatialLayer int32) (bool, VideoLayers, V return true, f.maxLayers, f.currentLayers } -func (f *Forwarder) SetMaxTemporalLayer(temporalLayer int32) (bool, VideoLayers, VideoLayers) { +func (f *Forwarder) SetMaxTemporalLayer(temporalLayer int32) (bool, buffer.VideoLayer, buffer.VideoLayer) { f.lock.Lock() defer f.lock.Unlock() @@ -438,21 +417,21 @@ func (f *Forwarder) SetMaxTemporalLayer(temporalLayer int32) (bool, VideoLayers, return true, f.maxLayers, f.currentLayers } -func (f *Forwarder) MaxLayers() VideoLayers { +func (f *Forwarder) MaxLayers() buffer.VideoLayer { f.lock.RLock() defer f.lock.RUnlock() return f.maxLayers } -func (f *Forwarder) CurrentLayers() VideoLayers { +func (f *Forwarder) CurrentLayers() buffer.VideoLayer { f.lock.RLock() defer f.lock.RUnlock() return f.currentLayers } -func (f *Forwarder) TargetLayers() VideoLayers { +func (f *Forwarder) TargetLayers() buffer.VideoLayer { f.lock.RLock() defer f.lock.RUnlock() @@ -467,7 +446,7 @@ func (f *Forwarder) GetReferenceLayerSpatial() int32 { } func (f *Forwarder) isDeficientLocked() bool { - return f.lastAllocation.isDeficient + return f.lastAllocation.IsDeficient } func (f *Forwarder) IsDeficient() bool { @@ -482,7 +461,7 @@ func (f *Forwarder) BandwidthRequested(brs Bitrates) int64 { defer f.lock.RUnlock() if !f.targetLayers.IsValid() { - if f.targetLayers != InvalidLayers { + if f.targetLayers != buffer.InvalidLayers { f.logger.Warnw( "unexpected target layers", nil, "target", f.targetLayers, @@ -530,17 +509,17 @@ func (f *Forwarder) AllocateOptimal(availableLayers []int32, brs Bitrates, allow } alloc := VideoAllocation{ - pauseReason: VideoPauseReasonNone, - bitrates: brs, - targetLayers: InvalidLayers, - requestLayerSpatial: f.requestLayerSpatial, - maxLayers: f.maxLayers, + PauseReason: VideoPauseReasonNone, + Bitrates: brs, + TargetLayers: buffer.InvalidLayers, + RequestLayerSpatial: f.requestLayerSpatial, + MaxLayers: f.maxLayers, } optimalBandwidthNeeded := getOptimalBandwidthNeeded(f.muted, f.pubMuted, f.maxPublishedLayer, brs, f.maxLayers) if optimalBandwidthNeeded == 0 { - alloc.pauseReason = VideoPauseReasonFeedDry + alloc.PauseReason = VideoPauseReasonFeedDry } - alloc.bandwidthNeeded = optimalBandwidthNeeded + alloc.BandwidthNeeded = optimalBandwidthNeeded opportunisticAlloc := func() { // opportunistically latch on to anything @@ -548,29 +527,29 @@ func (f *Forwarder) AllocateOptimal(availableLayers []int32, brs Bitrates, allow if allowOvershoot && f.maxPublishedLayer > maxSpatial { maxSpatial = f.maxPublishedLayer } - alloc.targetLayers = VideoLayers{ + alloc.TargetLayers = buffer.VideoLayer{ Spatial: int32(math.Min(float64(f.maxPublishedLayer), float64(maxSpatial))), - Temporal: DefaultMaxLayerTemporal, + Temporal: buffer.DefaultMaxLayerTemporal, } } switch { - case !f.maxLayers.IsValid() || f.maxPublishedLayer == InvalidLayerSpatial: + case !f.maxLayers.IsValid() || f.maxPublishedLayer == buffer.InvalidLayerSpatial: // nothing to do when max layers are not valid OR max publisher layer is invalid case f.muted: - alloc.pauseReason = VideoPauseReasonMuted + alloc.PauseReason = VideoPauseReasonMuted case f.pubMuted: - alloc.pauseReason = VideoPauseReasonPubMuted + alloc.PauseReason = VideoPauseReasonPubMuted // leave it at current layers for opportunistic resume - alloc.targetLayers = f.currentLayers - alloc.requestLayerSpatial = alloc.targetLayers.Spatial + 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 + alloc.TargetLayers = f.parkedLayers + alloc.RequestLayerSpatial = alloc.TargetLayers.Spatial case len(availableLayers) == 0: // feed may be dry @@ -579,12 +558,12 @@ func (f *Forwarder) AllocateOptimal(availableLayers []int32, brs Bitrates, allow // Covers the cases of // 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 + alloc.TargetLayers = f.currentLayers + alloc.RequestLayerSpatial = alloc.TargetLayers.Spatial } else { // opportunistically latch on to anything opportunisticAlloc() - alloc.requestLayerSpatial = int32(math.Min(float64(f.maxLayers.Spatial), float64(f.maxPublishedLayer))) + alloc.RequestLayerSpatial = int32(math.Min(float64(f.maxLayers.Spatial), float64(f.maxPublishedLayer))) } default: @@ -601,60 +580,60 @@ func (f *Forwarder) AllocateOptimal(availableLayers []int32, brs Bitrates, allow if !isCurrentLayerAvailable && f.currentLayers.IsValid() { // current layer maybe stopped, move to highest available for _, l := range availableLayers { - if l > alloc.targetLayers.Spatial { - alloc.targetLayers.Spatial = l + if l > alloc.TargetLayers.Spatial { + alloc.TargetLayers.Spatial = l } } - alloc.targetLayers.Temporal = DefaultMaxLayerTemporal + alloc.TargetLayers.Temporal = buffer.DefaultMaxLayerTemporal - alloc.requestLayerSpatial = alloc.targetLayers.Spatial + alloc.RequestLayerSpatial = alloc.TargetLayers.Spatial } else { requestLayerSpatial := int32(math.Min(float64(f.maxLayers.Spatial), float64(f.maxPublishedLayer))) if f.currentLayers.IsValid() && requestLayerSpatial == f.requestLayerSpatial && f.currentLayers.Spatial == f.requestLayerSpatial { // current is locked to desired, stay there - alloc.targetLayers = f.currentLayers - alloc.requestLayerSpatial = f.requestLayerSpatial + alloc.TargetLayers = f.currentLayers + alloc.RequestLayerSpatial = f.requestLayerSpatial } else { // opportunistically latch on to anything opportunisticAlloc() - alloc.requestLayerSpatial = requestLayerSpatial + alloc.RequestLayerSpatial = requestLayerSpatial } } } - if !alloc.targetLayers.IsValid() { - alloc.targetLayers = InvalidLayers - alloc.requestLayerSpatial = InvalidLayerSpatial + if !alloc.TargetLayers.IsValid() { + alloc.TargetLayers = buffer.InvalidLayers + alloc.RequestLayerSpatial = buffer.InvalidLayerSpatial } - if alloc.targetLayers.IsValid() { - alloc.bandwidthRequested = optimalBandwidthNeeded + if alloc.TargetLayers.IsValid() { + alloc.BandwidthRequested = optimalBandwidthNeeded } - alloc.bandwidthDelta = alloc.bandwidthRequested - f.lastAllocation.bandwidthRequested - alloc.distanceToDesired = getDistanceToDesired( + alloc.BandwidthDelta = alloc.BandwidthRequested - f.lastAllocation.BandwidthRequested + alloc.DistanceToDesired = getDistanceToDesired( f.muted, f.pubMuted, f.maxPublishedLayer, f.maxTemporalLayerSeen, availableLayers, brs, - alloc.targetLayers, + alloc.TargetLayers, f.maxLayers, ) return f.updateAllocation(alloc, "optimal") } -func (f *Forwarder) ProvisionalAllocatePrepare(availableLayers []int32, bitrates Bitrates) { +func (f *Forwarder) ProvisionalAllocatePrepare(availableLayers []int32, Bitrates Bitrates) { f.lock.Lock() defer f.lock.Unlock() f.provisional = &VideoAllocationProvisional{ - allocatedLayers: InvalidLayers, + allocatedLayers: buffer.InvalidLayers, muted: f.muted, pubMuted: f.pubMuted, maxPublishedLayer: f.maxPublishedLayer, maxTemporalLayerSeen: f.maxTemporalLayerSeen, - bitrates: bitrates, + Bitrates: Bitrates, maxLayers: f.maxLayers, currentLayers: f.currentLayers, parkedLayers: f.parkedLayers, @@ -664,22 +643,22 @@ func (f *Forwarder) ProvisionalAllocatePrepare(availableLayers []int32, bitrates copy(f.provisional.availableLayers, availableLayers) } -func (f *Forwarder) ProvisionalAllocate(availableChannelCapacity int64, layers VideoLayers, allowPause bool, allowOvershoot bool) int64 { +func (f *Forwarder) ProvisionalAllocate(availableChannelCapacity int64, layers buffer.VideoLayer, allowPause bool, allowOvershoot bool) int64 { f.lock.Lock() defer f.lock.Unlock() - if f.provisional.muted || f.provisional.pubMuted || f.provisional.maxPublishedLayer == InvalidLayerSpatial || !f.provisional.maxLayers.IsValid() || (!allowOvershoot && layers.GreaterThan(f.provisional.maxLayers)) { + if f.provisional.muted || f.provisional.pubMuted || f.provisional.maxPublishedLayer == buffer.InvalidLayerSpatial || !f.provisional.maxLayers.IsValid() || (!allowOvershoot && layers.GreaterThan(f.provisional.maxLayers)) { return 0 } - requiredBitrate := f.provisional.bitrates[layers.Spatial][layers.Temporal] + requiredBitrate := f.provisional.Bitrates[layers.Spatial][layers.Temporal] if requiredBitrate == 0 { return 0 } alreadyAllocatedBitrate := int64(0) if f.provisional.allocatedLayers.IsValid() { - alreadyAllocatedBitrate = f.provisional.bitrates[f.provisional.allocatedLayers.Spatial][f.provisional.allocatedLayers.Temporal] + alreadyAllocatedBitrate = f.provisional.Bitrates[f.provisional.allocatedLayers.Spatial][f.provisional.allocatedLayers.Temporal] } // a layer under maximum fits, take it @@ -727,28 +706,28 @@ func (f *Forwarder) ProvisionalAllocateGetCooperativeTransition(allowOvershoot b defer f.lock.Unlock() if f.provisional.muted || f.provisional.pubMuted { - f.provisional.allocatedLayers = InvalidLayers + f.provisional.allocatedLayers = buffer.InvalidLayers if f.provisional.pubMuted { // leave it at current for opportunistic forwarding, there is still bandwidth saving with publisher mute f.provisional.allocatedLayers = f.provisional.currentLayers } return VideoTransition{ - from: f.targetLayers, - to: f.provisional.allocatedLayers, - bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested, + From: f.targetLayers, + To: f.provisional.allocatedLayers, + BandwidthDelta: 0 - f.lastAllocation.BandwidthRequested, } } // check if we should preserve current target if f.targetLayers.IsValid() { // what is the highest that is available - maximalLayers := InvalidLayers + maximalLayers := buffer.InvalidLayers maximalBandwidthRequired := int64(0) for s := f.provisional.maxLayers.Spatial; s >= 0; s-- { for t := f.provisional.maxLayers.Temporal; t >= 0; t-- { - if f.provisional.bitrates[s][t] != 0 { - maximalLayers = VideoLayers{Spatial: s, Temporal: t} - maximalBandwidthRequired = f.provisional.bitrates[s][t] + if f.provisional.Bitrates[s][t] != 0 { + maximalLayers = buffer.VideoLayer{Spatial: s, Temporal: t} + maximalBandwidthRequired = f.provisional.Bitrates[s][t] break } } @@ -759,14 +738,14 @@ func (f *Forwarder) ProvisionalAllocateGetCooperativeTransition(allowOvershoot b } if maximalLayers.IsValid() { - if !f.targetLayers.GreaterThan(maximalLayers) && f.provisional.bitrates[f.targetLayers.Spatial][f.targetLayers.Temporal] != 0 { + if !f.targetLayers.GreaterThan(maximalLayers) && f.provisional.Bitrates[f.targetLayers.Spatial][f.targetLayers.Temporal] != 0 { // currently streaming and maybe wanting an upgrade (f.targetLayers <= maximalLayers), // just preserve current target in the cooperative scheme of things f.provisional.allocatedLayers = f.targetLayers return VideoTransition{ - from: f.targetLayers, - to: f.targetLayers, - bandwidthDelta: 0, + From: f.targetLayers, + To: f.targetLayers, + BandwidthDelta: 0, } } @@ -774,9 +753,9 @@ func (f *Forwarder) ProvisionalAllocateGetCooperativeTransition(allowOvershoot b // maximalLayers < f.targetLayers, make the down move f.provisional.allocatedLayers = maximalLayers return VideoTransition{ - from: f.targetLayers, - to: maximalLayers, - bandwidthDelta: maximalBandwidthRequired - f.lastAllocation.bandwidthRequested, + From: f.targetLayers, + To: maximalLayers, + BandwidthDelta: maximalBandwidthRequired - f.lastAllocation.BandwidthRequested, } } } @@ -785,14 +764,14 @@ func (f *Forwarder) ProvisionalAllocateGetCooperativeTransition(allowOvershoot b findNextLayer := func( minSpatial, maxSpatial int32, minTemporal, maxTemporal int32, - ) (VideoLayers, int64) { - layers := InvalidLayers + ) (buffer.VideoLayer, int64) { + layers := buffer.InvalidLayers bw := int64(0) for s := minSpatial; s <= maxSpatial; s++ { for t := minTemporal; t <= maxTemporal; t++ { - if f.provisional.bitrates[s][t] != 0 { - layers = VideoLayers{Spatial: s, Temporal: t} - bw = f.provisional.bitrates[s][t] + if f.provisional.Bitrates[s][t] != 0 { + layers = buffer.VideoLayer{Spatial: s, Temporal: t} + bw = f.provisional.Bitrates[s][t] break } } @@ -819,8 +798,8 @@ func (f *Forwarder) ProvisionalAllocateGetCooperativeTransition(allowOvershoot b // could not find a minimal layer, overshoot if allowed if bandwidthRequired == 0 && f.provisional.maxLayers.IsValid() && allowOvershoot { targetLayers, bandwidthRequired = findNextLayer( - f.provisional.maxLayers.Spatial+1, DefaultMaxLayerSpatial, - 0, DefaultMaxLayerTemporal, + f.provisional.maxLayers.Spatial+1, buffer.DefaultMaxLayerSpatial, + 0, buffer.DefaultMaxLayerTemporal, ) } } @@ -836,9 +815,9 @@ func (f *Forwarder) ProvisionalAllocateGetCooperativeTransition(allowOvershoot b f.provisional.allocatedLayers = targetLayers return VideoTransition{ - from: f.targetLayers, - to: targetLayers, - bandwidthDelta: bandwidthRequired - f.lastAllocation.bandwidthRequested, + From: f.targetLayers, + To: targetLayers, + BandwidthDelta: bandwidthRequired - f.lastAllocation.BandwidthRequested, } } @@ -862,32 +841,32 @@ func (f *Forwarder) ProvisionalAllocateGetBestWeightedTransition() VideoTransiti defer f.lock.Unlock() if f.provisional.muted || f.provisional.pubMuted { - f.provisional.allocatedLayers = InvalidLayers + f.provisional.allocatedLayers = buffer.InvalidLayers if f.provisional.pubMuted { // leave it at current for opportunistic forwarding, there is still bandwidth saving with publisher mute f.provisional.allocatedLayers = f.provisional.currentLayers } return VideoTransition{ - from: f.targetLayers, - to: f.provisional.allocatedLayers, - bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested, + From: f.targetLayers, + To: f.provisional.allocatedLayers, + BandwidthDelta: 0 - f.lastAllocation.BandwidthRequested, } } - maxReachableLayerTemporal := InvalidLayerTemporal + maxReachableLayerTemporal := buffer.InvalidLayerTemporal for t := f.provisional.maxLayers.Temporal; t >= 0; t-- { for s := f.provisional.maxLayers.Spatial; s >= 0; s-- { - if f.provisional.bitrates[s][t] != 0 { + if f.provisional.Bitrates[s][t] != 0 { maxReachableLayerTemporal = t break } } - if maxReachableLayerTemporal != InvalidLayerTemporal { + if maxReachableLayerTemporal != buffer.InvalidLayerTemporal { break } } - if maxReachableLayerTemporal == InvalidLayerTemporal { + if maxReachableLayerTemporal == buffer.InvalidLayerTemporal { // feed has gone dry, just leave target at current to enable opportunistic forwarding in case current resumes. // Note that this is giving back bits and opportunistic forwarding resuming might trigger congestion again, // but that should be handled by stream allocator. @@ -897,15 +876,15 @@ func (f *Forwarder) ProvisionalAllocateGetBestWeightedTransition() VideoTransiti f.provisional.allocatedLayers = f.provisional.currentLayers } return VideoTransition{ - from: f.targetLayers, - to: f.provisional.allocatedLayers, - bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested, + From: f.targetLayers, + To: f.provisional.allocatedLayers, + BandwidthDelta: 0 - f.lastAllocation.BandwidthRequested, } } // starting from minimum to target, find transition which gives the best // transition taking into account bits saved vs cost of such a transition - bestLayers := InvalidLayers + bestLayers := buffer.InvalidLayers bestBandwidthDelta := int64(0) bestValue := float32(0) for s := int32(0); s <= f.targetLayers.Spatial; s++ { @@ -914,7 +893,7 @@ func (f *Forwarder) ProvisionalAllocateGetBestWeightedTransition() VideoTransiti break } - bandwidthDelta := int64(math.Max(float64(0), float64(f.lastAllocation.bandwidthRequested-f.provisional.bitrates[s][t]))) + BandwidthDelta := int64(math.Max(float64(0), float64(f.lastAllocation.BandwidthRequested-f.provisional.Bitrates[s][t]))) transitionCost := int32(0) if f.targetLayers.Spatial != s { @@ -925,21 +904,21 @@ func (f *Forwarder) ProvisionalAllocateGetBestWeightedTransition() VideoTransiti value := float32(0) if (transitionCost + qualityCost) != 0 { - value = float32(bandwidthDelta) / float32(transitionCost+qualityCost) + value = float32(BandwidthDelta) / float32(transitionCost+qualityCost) } - if value > bestValue || (value == bestValue && bandwidthDelta > bestBandwidthDelta) { + if value > bestValue || (value == bestValue && BandwidthDelta > bestBandwidthDelta) { bestValue = value - bestBandwidthDelta = bandwidthDelta - bestLayers = VideoLayers{Spatial: s, Temporal: t} + bestBandwidthDelta = BandwidthDelta + bestLayers = buffer.VideoLayer{Spatial: s, Temporal: t} } } } f.provisional.allocatedLayers = bestLayers return VideoTransition{ - from: f.targetLayers, - to: bestLayers, - bandwidthDelta: bestBandwidthDelta, + From: f.targetLayers, + To: bestLayers, + BandwidthDelta: bestBandwidthDelta, } } @@ -951,24 +930,24 @@ func (f *Forwarder) ProvisionalAllocateCommit() VideoAllocation { f.provisional.muted, f.provisional.pubMuted, f.provisional.maxPublishedLayer, - f.provisional.bitrates, + f.provisional.Bitrates, f.provisional.maxLayers, ) alloc := VideoAllocation{ - bandwidthRequested: 0, - bandwidthDelta: -f.lastAllocation.bandwidthRequested, - bitrates: f.provisional.bitrates, - bandwidthNeeded: optimalBandwidthNeeded, - targetLayers: f.provisional.allocatedLayers, - requestLayerSpatial: f.provisional.allocatedLayers.Spatial, - maxLayers: f.provisional.maxLayers, - distanceToDesired: getDistanceToDesired( + BandwidthRequested: 0, + BandwidthDelta: -f.lastAllocation.BandwidthRequested, + Bitrates: f.provisional.Bitrates, + BandwidthNeeded: optimalBandwidthNeeded, + 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.maxTemporalLayerSeen, f.provisional.availableLayers, - f.provisional.bitrates, + f.provisional.Bitrates, f.provisional.allocatedLayers, f.provisional.maxLayers, ), @@ -976,47 +955,47 @@ func (f *Forwarder) ProvisionalAllocateCommit() VideoAllocation { switch { case f.provisional.muted: - alloc.pauseReason = VideoPauseReasonMuted + alloc.PauseReason = VideoPauseReasonMuted case f.provisional.pubMuted: - alloc.pauseReason = VideoPauseReasonPubMuted + alloc.PauseReason = VideoPauseReasonPubMuted case optimalBandwidthNeeded == 0: if f.provisional.allocatedLayers.IsValid() { // overshoot - alloc.bandwidthRequested = f.provisional.bitrates[f.provisional.allocatedLayers.Spatial][f.provisional.allocatedLayers.Temporal] - alloc.bandwidthDelta = alloc.bandwidthRequested - f.lastAllocation.bandwidthRequested + alloc.BandwidthRequested = f.provisional.Bitrates[f.provisional.allocatedLayers.Spatial][f.provisional.allocatedLayers.Temporal] + alloc.BandwidthDelta = alloc.BandwidthRequested - f.lastAllocation.BandwidthRequested } else { - alloc.pauseReason = VideoPauseReasonFeedDry + alloc.PauseReason = VideoPauseReasonFeedDry // leave target at current for opportunistic forwarding 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 + alloc.TargetLayers = f.provisional.allocatedLayers + alloc.RequestLayerSpatial = alloc.TargetLayers.Spatial } } default: if f.provisional.allocatedLayers.IsValid() { - 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] } - alloc.bandwidthDelta = alloc.bandwidthRequested - f.lastAllocation.bandwidthRequested + alloc.BandwidthDelta = alloc.BandwidthRequested - f.lastAllocation.BandwidthRequested if f.provisional.allocatedLayers.GreaterThan(f.provisional.maxLayers) || - alloc.bandwidthRequested >= getOptimalBandwidthNeeded( + alloc.BandwidthRequested >= getOptimalBandwidthNeeded( f.provisional.muted, f.provisional.pubMuted, f.provisional.maxPublishedLayer, - f.provisional.bitrates, + f.provisional.Bitrates, f.provisional.maxLayers, ) { // could be greater than optimal if overshooting - alloc.isDeficient = false + alloc.IsDeficient = false } else { - alloc.isDeficient = true + alloc.IsDeficient = true if !f.provisional.allocatedLayers.IsValid() { - alloc.pauseReason = VideoPauseReasonBandwidth + alloc.PauseReason = VideoPauseReasonBandwidth } } } @@ -1056,27 +1035,27 @@ func (f *Forwarder) AllocateNextHigher(availableChannelCapacity int64, available ) (bool, VideoAllocation, bool) { for s := minSpatial; s <= maxSpatial; s++ { for t := minTemporal; t <= maxTemporal; t++ { - bandwidthRequested := brs[s][t] - if bandwidthRequested == 0 { + BandwidthRequested := brs[s][t] + if BandwidthRequested == 0 { continue } - if !allowOvershoot && bandwidthRequested-alreadyAllocated > availableChannelCapacity { + if !allowOvershoot && BandwidthRequested-alreadyAllocated > availableChannelCapacity { // next higher available layer does not fit, return return true, f.lastAllocation, false } - targetLayers := VideoLayers{Spatial: s, Temporal: t} + targetLayers := buffer.VideoLayer{Spatial: s, Temporal: t} alloc := VideoAllocation{ - isDeficient: true, - bandwidthRequested: bandwidthRequested, - bandwidthDelta: bandwidthRequested - alreadyAllocated, - bandwidthNeeded: optimalBandwidthNeeded, - bitrates: brs, - targetLayers: targetLayers, - requestLayerSpatial: targetLayers.Spatial, - maxLayers: f.maxLayers, - distanceToDesired: getDistanceToDesired( + IsDeficient: true, + BandwidthRequested: BandwidthRequested, + BandwidthDelta: BandwidthRequested - alreadyAllocated, + BandwidthNeeded: optimalBandwidthNeeded, + Bitrates: brs, + TargetLayers: targetLayers, + RequestLayerSpatial: targetLayers.Spatial, + MaxLayers: f.maxLayers, + DistanceToDesired: getDistanceToDesired( f.muted, f.pubMuted, f.maxPublishedLayer, @@ -1087,8 +1066,8 @@ func (f *Forwarder) AllocateNextHigher(availableChannelCapacity int64, available f.maxLayers, ), } - if targetLayers.GreaterThan(f.maxLayers) || bandwidthRequested >= optimalBandwidthNeeded { - alloc.isDeficient = false + if targetLayers.GreaterThan(f.maxLayers) || BandwidthRequested >= optimalBandwidthNeeded { + alloc.IsDeficient = false } return true, f.updateAllocation(alloc, "next-higher"), true @@ -1124,8 +1103,8 @@ func (f *Forwarder) AllocateNextHigher(availableChannelCapacity int64, available if allowOvershoot && f.maxLayers.IsValid() { done, allocation, boosted = doAllocation( - f.maxLayers.Spatial+1, DefaultMaxLayerSpatial, - 0, DefaultMaxLayerTemporal, + f.maxLayers.Spatial+1, buffer.DefaultMaxLayerSpatial, + 0, buffer.DefaultMaxLayerTemporal, ) if done { return allocation, boosted @@ -1164,15 +1143,15 @@ func (f *Forwarder) GetNextHigherTransition(brs Bitrates, allowOvershoot bool) ( ) (bool, VideoTransition, bool) { for s := minSpatial; s <= maxSpatial; s++ { for t := minTemporal; t <= maxTemporal; t++ { - bandwidthRequested := brs[s][t] - if bandwidthRequested == 0 { + BandwidthRequested := brs[s][t] + if BandwidthRequested == 0 { continue } transition := VideoTransition{ - from: f.targetLayers, - to: VideoLayers{Spatial: s, Temporal: t}, - bandwidthDelta: bandwidthRequested - alreadyAllocated, + From: f.targetLayers, + To: buffer.VideoLayer{Spatial: s, Temporal: t}, + BandwidthDelta: BandwidthRequested - alreadyAllocated, } return true, transition, true @@ -1208,8 +1187,8 @@ func (f *Forwarder) GetNextHigherTransition(brs Bitrates, allowOvershoot bool) ( if allowOvershoot && f.maxLayers.IsValid() { done, transition, isAvailable = findNextHigher( - f.maxLayers.Spatial+1, DefaultMaxLayerSpatial, - 0, DefaultMaxLayerTemporal, + f.maxLayers.Spatial+1, buffer.DefaultMaxLayerSpatial, + 0, buffer.DefaultMaxLayerTemporal, ) if done { return transition, isAvailable @@ -1225,39 +1204,39 @@ func (f *Forwarder) Pause(availableLayers []int32, brs Bitrates) VideoAllocation optimalBandwidthNeeded := getOptimalBandwidthNeeded(f.muted, f.pubMuted, f.maxPublishedLayer, brs, f.maxLayers) alloc := VideoAllocation{ - bandwidthRequested: 0, - bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested, - bitrates: brs, - bandwidthNeeded: optimalBandwidthNeeded, - targetLayers: InvalidLayers, - requestLayerSpatial: InvalidLayerSpatial, - maxLayers: f.maxLayers, - distanceToDesired: getDistanceToDesired( + BandwidthRequested: 0, + BandwidthDelta: 0 - f.lastAllocation.BandwidthRequested, + Bitrates: brs, + BandwidthNeeded: optimalBandwidthNeeded, + TargetLayers: buffer.InvalidLayers, + RequestLayerSpatial: buffer.InvalidLayerSpatial, + MaxLayers: f.maxLayers, + DistanceToDesired: getDistanceToDesired( f.muted, f.pubMuted, f.maxPublishedLayer, f.maxTemporalLayerSeen, availableLayers, brs, - InvalidLayers, + buffer.InvalidLayers, f.maxLayers, ), } switch { case f.muted: - alloc.pauseReason = VideoPauseReasonMuted + alloc.PauseReason = VideoPauseReasonMuted case f.pubMuted: - alloc.pauseReason = VideoPauseReasonPubMuted + alloc.PauseReason = VideoPauseReasonPubMuted case optimalBandwidthNeeded == 0: - alloc.pauseReason = VideoPauseReasonFeedDry + alloc.PauseReason = VideoPauseReasonFeedDry default: // pausing due to lack of bandwidth - alloc.isDeficient = true - alloc.pauseReason = VideoPauseReasonBandwidth + alloc.IsDeficient = true + alloc.PauseReason = VideoPauseReasonBandwidth } f.clearParkedLayers() @@ -1265,10 +1244,10 @@ func (f *Forwarder) Pause(availableLayers []int32, brs Bitrates) VideoAllocation } func (f *Forwarder) updateAllocation(alloc VideoAllocation, reason string) VideoAllocation { - if alloc.isDeficient != f.lastAllocation.isDeficient || - alloc.pauseReason != f.lastAllocation.pauseReason || - alloc.targetLayers != f.lastAllocation.targetLayers || - alloc.requestLayerSpatial != f.lastAllocation.requestLayerSpatial { + if alloc.IsDeficient != f.lastAllocation.IsDeficient || + alloc.PauseReason != f.lastAllocation.PauseReason || + alloc.TargetLayers != f.lastAllocation.TargetLayers || + alloc.RequestLayerSpatial != f.lastAllocation.RequestLayerSpatial { if reason == "optimal" { f.logger.Debugw(fmt.Sprintf("stream allocation: %s", reason), "allocation", alloc) } else { @@ -1277,7 +1256,7 @@ func (f *Forwarder) updateAllocation(alloc VideoAllocation, reason string) Video } f.lastAllocation = alloc - f.setTargetLayers(f.lastAllocation.targetLayers, f.lastAllocation.requestLayerSpatial) + f.setTargetLayers(f.lastAllocation.TargetLayers, f.lastAllocation.RequestLayerSpatial) if !f.targetLayers.IsValid() { f.resyncLocked() } @@ -1285,7 +1264,7 @@ func (f *Forwarder) updateAllocation(alloc VideoAllocation, reason string) Video return f.lastAllocation } -func (f *Forwarder) setTargetLayers(targetLayers VideoLayers, requestLayerSpatial int32) { +func (f *Forwarder) setTargetLayers(targetLayers buffer.VideoLayer, requestLayerSpatial int32) { f.targetLayers = targetLayers if f.ddLayerSelector != nil { f.ddLayerSelector.SelectLayer(targetLayers) @@ -1302,20 +1281,20 @@ func (f *Forwarder) Resync() { } func (f *Forwarder) resyncLocked() { - f.currentLayers = InvalidLayers + f.currentLayers = buffer.InvalidLayers f.lastSSRC = 0 f.clearParkedLayers() } func (f *Forwarder) clearParkedLayers() { - f.parkedLayers = InvalidLayers + f.parkedLayers = buffer.InvalidLayers if f.parkedLayersTimer != nil { f.parkedLayersTimer.Stop() f.parkedLayersTimer = nil } } -func (f *Forwarder) setupParkedLayers(parkedLayers VideoLayers) { +func (f *Forwarder) setupParkedLayers(parkedLayers buffer.VideoLayer) { f.clearParkedLayers() f.parkedLayers = parkedLayers @@ -1339,7 +1318,7 @@ func (f *Forwarder) CheckSync() (locked bool, layer int32) { return } -func (f *Forwarder) FilterRTX(nacks []uint16) (filtered []uint16, disallowedLayers [DefaultMaxLayerSpatial + 1]bool) { +func (f *Forwarder) FilterRTX(nacks []uint16) (filtered []uint16, disallowedLayers [buffer.DefaultMaxLayerSpatial + 1]bool) { if !FlagFilterRTX { filtered = nacks return @@ -1358,7 +1337,7 @@ func (f *Forwarder) FilterRTX(nacks []uint16) (filtered []uint16, disallowedLaye // // Without the curb, when congestion hits, RTX rate could be so high that it further congests the channel. // - for layer := int32(0); layer < DefaultMaxLayerSpatial+1; layer++ { + for layer := int32(0); layer < buffer.DefaultMaxLayerSpatial+1; layer++ { if f.isDeficientLocked() && (f.targetLayers.Spatial < f.currentLayers.Spatial || layer > f.currentLayers.Spatial) { disallowedLayers[layer] = true } @@ -1406,7 +1385,7 @@ func (f *Forwarder) getTranslationParamsCommon(extPkt *buffer.ExtPacket, layer i f.vp8Munger.SetLast(extPkt) } } else { - if f.referenceLayerSpatial == InvalidLayerSpatial { + if f.referenceLayerSpatial == buffer.InvalidLayerSpatial { // on a resume, reference layer may not be set, so only set when it is invalid f.referenceLayerSpatial = layer } @@ -1715,8 +1694,8 @@ func (f *Forwarder) GetRTPMungerParams() RTPMungerParams { // ----------------------------------------------------------------------------- -func getOptimalBandwidthNeeded(muted bool, pubMuted bool, maxPublishedLayer int32, brs Bitrates, maxLayers VideoLayers) int64 { - if muted || pubMuted || maxPublishedLayer == InvalidLayerSpatial { +func getOptimalBandwidthNeeded(muted bool, pubMuted bool, maxPublishedLayer int32, brs Bitrates, maxLayers buffer.VideoLayer) int64 { + if muted || pubMuted || maxPublishedLayer == buffer.InvalidLayerSpatial { return 0 } @@ -1745,17 +1724,17 @@ func getDistanceToDesired( maxTemporalLayerSeen int32, availableLayers []int32, brs Bitrates, - targetLayers VideoLayers, - maxLayers VideoLayers, + targetLayers buffer.VideoLayer, + maxLayers buffer.VideoLayer, ) float64 { - if muted || pubMuted || maxPublishedLayer == InvalidLayerSpatial || maxTemporalLayerSeen == InvalidLayerTemporal || !maxLayers.IsValid() { + if muted || pubMuted || maxPublishedLayer == buffer.InvalidLayerSpatial || maxTemporalLayerSeen == buffer.InvalidLayerTemporal || !maxLayers.IsValid() { return 0.0 } adjustedMaxLayers := maxLayers - maxAvailableSpatial := InvalidLayerSpatial - maxAvailableTemporal := InvalidLayerTemporal + maxAvailableSpatial := buffer.InvalidLayerSpatial + maxAvailableTemporal := buffer.InvalidLayerTemporal // max available spatial is min(subscribedMax, publishedMax, availableMax) // subscribedMax = subscriber requested max spatial layer @@ -1791,7 +1770,7 @@ done: // subscribedMax = subscriber requested max temporal layer // temporalLayerSeenMax = max temporal layer ever published/seen // availableMax = based on bit rate measurement, available max temporal in the adjusted max spatial layer - if adjustedMaxLayers.Spatial != InvalidLayerSpatial { + if adjustedMaxLayers.Spatial != buffer.InvalidLayerSpatial { for t := int32(len(brs[0])) - 1; t >= 0; t-- { if brs[adjustedMaxLayers.Spatial][t] != 0 { maxAvailableTemporal = t @@ -1808,13 +1787,13 @@ done: } if !adjustedMaxLayers.IsValid() { - adjustedMaxLayers = VideoLayers{Spatial: 0, Temporal: 0} + adjustedMaxLayers = buffer.VideoLayer{Spatial: 0, Temporal: 0} } // adjust target layers if they are invalid, i. e. not streaming adjustedTargetLayers := targetLayers if !targetLayers.IsValid() { - adjustedTargetLayers = VideoLayers{Spatial: 0, Temporal: 0} + adjustedTargetLayers = buffer.VideoLayer{Spatial: 0, Temporal: 0} } distance := diff --git a/pkg/sfu/forwarder_test.go b/pkg/sfu/forwarder_test.go index 5d0695a1..81778ada 100644 --- a/pkg/sfu/forwarder_test.go +++ b/pkg/sfu/forwarder_test.go @@ -13,8 +13,8 @@ import ( ) func disable(f *Forwarder) { - f.currentLayers = InvalidLayers - f.targetLayers = InvalidLayers + f.currentLayers = buffer.InvalidLayers + f.targetLayers = buffer.InvalidLayers } func newForwarder(codec webrtc.RTPCodecCapability, kind webrtc.RTPCodecType) *Forwarder { @@ -40,74 +40,74 @@ func TestForwarderMute(t *testing.T) { func TestForwarderLayersAudio(t *testing.T) { f := newForwarder(testutils.TestOpusCodec, webrtc.RTPCodecTypeAudio) - require.Equal(t, InvalidLayers, f.MaxLayers()) + require.Equal(t, buffer.InvalidLayers, f.MaxLayers()) - require.Equal(t, InvalidLayers, f.CurrentLayers()) - require.Equal(t, InvalidLayers, f.TargetLayers()) + require.Equal(t, buffer.InvalidLayers, f.CurrentLayers()) + require.Equal(t, buffer.InvalidLayers, f.TargetLayers()) changed, maxLayers, currentLayers := f.SetMaxSpatialLayer(1) require.False(t, changed) - require.Equal(t, InvalidLayers, maxLayers) - require.Equal(t, InvalidLayers, currentLayers) + require.Equal(t, buffer.InvalidLayers, maxLayers) + require.Equal(t, buffer.InvalidLayers, currentLayers) changed, maxLayers, currentLayers = f.SetMaxTemporalLayer(1) require.False(t, changed) - require.Equal(t, InvalidLayers, maxLayers) - require.Equal(t, InvalidLayers, currentLayers) + require.Equal(t, buffer.InvalidLayers, maxLayers) + require.Equal(t, buffer.InvalidLayers, currentLayers) - require.Equal(t, InvalidLayers, f.MaxLayers()) + require.Equal(t, buffer.InvalidLayers, f.MaxLayers()) } func TestForwarderLayersVideo(t *testing.T) { f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) maxLayers := f.MaxLayers() - expectedLayers := VideoLayers{Spatial: InvalidLayerSpatial, Temporal: DefaultMaxLayerTemporal} + expectedLayers := buffer.VideoLayer{Spatial: buffer.InvalidLayerSpatial, Temporal: buffer.DefaultMaxLayerTemporal} require.Equal(t, expectedLayers, maxLayers) - require.Equal(t, InvalidLayers, f.CurrentLayers()) - require.Equal(t, InvalidLayers, f.TargetLayers()) + require.Equal(t, buffer.InvalidLayers, f.CurrentLayers()) + require.Equal(t, buffer.InvalidLayers, f.TargetLayers()) - expectedLayers = VideoLayers{ - Spatial: DefaultMaxLayerSpatial, - Temporal: DefaultMaxLayerTemporal, + expectedLayers = buffer.VideoLayer{ + Spatial: buffer.DefaultMaxLayerSpatial, + Temporal: buffer.DefaultMaxLayerTemporal, } - changed, maxLayers, currentLayers := f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) + changed, maxLayers, currentLayers := f.SetMaxSpatialLayer(buffer.DefaultMaxLayerSpatial) require.True(t, changed) require.Equal(t, expectedLayers, maxLayers) - require.Equal(t, InvalidLayers, currentLayers) + require.Equal(t, buffer.InvalidLayers, currentLayers) - changed, maxLayers, currentLayers = f.SetMaxSpatialLayer(DefaultMaxLayerSpatial - 1) + changed, maxLayers, currentLayers = f.SetMaxSpatialLayer(buffer.DefaultMaxLayerSpatial - 1) require.True(t, changed) - expectedLayers = VideoLayers{ - Spatial: DefaultMaxLayerSpatial - 1, - Temporal: DefaultMaxLayerTemporal, + expectedLayers = buffer.VideoLayer{ + Spatial: buffer.DefaultMaxLayerSpatial - 1, + Temporal: buffer.DefaultMaxLayerTemporal, } require.Equal(t, expectedLayers, maxLayers) require.Equal(t, expectedLayers, f.MaxLayers()) - require.Equal(t, InvalidLayers, currentLayers) + require.Equal(t, buffer.InvalidLayers, currentLayers) - f.currentLayers = VideoLayers{Spatial: 0, Temporal: 1} - changed, maxLayers, currentLayers = f.SetMaxSpatialLayer(DefaultMaxLayerSpatial - 1) + f.currentLayers = buffer.VideoLayer{Spatial: 0, Temporal: 1} + changed, maxLayers, currentLayers = f.SetMaxSpatialLayer(buffer.DefaultMaxLayerSpatial - 1) require.False(t, changed) require.Equal(t, expectedLayers, maxLayers) require.Equal(t, expectedLayers, f.MaxLayers()) - require.Equal(t, VideoLayers{Spatial: 0, Temporal: 1}, currentLayers) + require.Equal(t, buffer.VideoLayer{Spatial: 0, Temporal: 1}, currentLayers) - changed, maxLayers, currentLayers = f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) + changed, maxLayers, currentLayers = f.SetMaxTemporalLayer(buffer.DefaultMaxLayerTemporal) require.False(t, changed) require.Equal(t, expectedLayers, maxLayers) - require.Equal(t, VideoLayers{Spatial: 0, Temporal: 1}, currentLayers) + require.Equal(t, buffer.VideoLayer{Spatial: 0, Temporal: 1}, currentLayers) - changed, maxLayers, currentLayers = f.SetMaxTemporalLayer(DefaultMaxLayerTemporal - 1) + changed, maxLayers, currentLayers = f.SetMaxTemporalLayer(buffer.DefaultMaxLayerTemporal - 1) require.True(t, changed) - expectedLayers = VideoLayers{ - Spatial: DefaultMaxLayerSpatial - 1, - Temporal: DefaultMaxLayerTemporal - 1, + expectedLayers = buffer.VideoLayer{ + Spatial: buffer.DefaultMaxLayerSpatial - 1, + Temporal: buffer.DefaultMaxLayerTemporal - 1, } require.Equal(t, expectedLayers, maxLayers) require.Equal(t, expectedLayers, f.MaxLayers()) - require.Equal(t, VideoLayers{Spatial: 0, Temporal: 1}, currentLayers) + require.Equal(t, buffer.VideoLayer{Spatial: 0, Temporal: 1}, currentLayers) } func TestForwarderAllocateOptimal(t *testing.T) { @@ -121,53 +121,53 @@ func TestForwarderAllocateOptimal(t *testing.T) { } // invalid max layers - f.maxLayers = InvalidLayers + f.maxLayers = buffer.InvalidLayers expectedResult := VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: bitrates, - targetLayers: InvalidLayers, - requestLayerSpatial: InvalidLayerSpatial, - maxLayers: InvalidLayers, - distanceToDesired: 0, + PauseReason: VideoPauseReasonFeedDry, + BandwidthRequested: 0, + BandwidthDelta: 0, + Bitrates: bitrates, + TargetLayers: buffer.InvalidLayers, + RequestLayerSpatial: buffer.InvalidLayerSpatial, + MaxLayers: buffer.InvalidLayers, + DistanceToDesired: 0, } result := f.AllocateOptimal(nil, bitrates, true) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) - f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) - f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) + f.SetMaxSpatialLayer(buffer.DefaultMaxLayerSpatial) + f.SetMaxTemporalLayer(buffer.DefaultMaxLayerTemporal) - // should still have target at InvalidLayers until max publisher layer is available + // should still have target at buffer.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, + PauseReason: VideoPauseReasonFeedDry, + BandwidthRequested: 0, + BandwidthDelta: 0, + Bitrates: bitrates, + TargetLayers: buffer.InvalidLayers, + RequestLayerSpatial: buffer.InvalidLayerSpatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 0, } result = f.AllocateOptimal(nil, bitrates, true) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) - f.SetMaxPublishedLayer(DefaultMaxLayerSpatial) + f.SetMaxPublishedLayer(buffer.DefaultMaxLayerSpatial) // muted should not consume any bandwidth f.Mute(true) disable(f) expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonMuted, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: bitrates, - targetLayers: InvalidLayers, - requestLayerSpatial: InvalidLayerSpatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0, + PauseReason: VideoPauseReasonMuted, + BandwidthRequested: 0, + BandwidthDelta: 0, + Bitrates: bitrates, + TargetLayers: buffer.InvalidLayers, + RequestLayerSpatial: buffer.InvalidLayerSpatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 0, } result = f.AllocateOptimal(nil, bitrates, true) require.Equal(t, expectedResult, result) @@ -179,14 +179,14 @@ func TestForwarderAllocateOptimal(t *testing.T) { f.PubMute(true) disable(f) expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonPubMuted, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: bitrates, - targetLayers: InvalidLayers, - requestLayerSpatial: InvalidLayerSpatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0, + PauseReason: VideoPauseReasonPubMuted, + BandwidthRequested: 0, + BandwidthDelta: 0, + Bitrates: bitrates, + TargetLayers: buffer.InvalidLayers, + RequestLayerSpatial: buffer.InvalidLayerSpatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 0, } result = f.AllocateOptimal(nil, bitrates, true) require.Equal(t, expectedResult, result) @@ -195,209 +195,209 @@ func TestForwarderAllocateOptimal(t *testing.T) { f.PubMute(false) // when parked layers valid, should stay there - f.parkedLayers = VideoLayers{ + f.parkedLayers = buffer.VideoLayer{ Spatial: 0, Temporal: 1, } expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: emptyBitrates, - targetLayers: f.parkedLayers, - requestLayerSpatial: f.parkedLayers.Spatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0, + PauseReason: VideoPauseReasonFeedDry, + BandwidthRequested: 0, + BandwidthDelta: 0, + Bitrates: emptyBitrates, + TargetLayers: f.parkedLayers, + RequestLayerSpatial: f.parkedLayers.Spatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 0, } result = f.AllocateOptimal(nil, emptyBitrates, true) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, f.parkedLayers, f.TargetLayers()) - f.parkedLayers = InvalidLayers + f.parkedLayers = buffer.InvalidLayers // when max layers changes, target is opportunistic, but requested spatial layer should be at max f.SetMaxTemporalLayerSeen(3) - f.maxLayers = VideoLayers{Spatial: 1, Temporal: 3} + f.maxLayers = buffer.VideoLayer{Spatial: 1, Temporal: 3} expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonNone, - bandwidthRequested: bitrates[1][3], - bandwidthDelta: bitrates[1][3], - bandwidthNeeded: bitrates[1][3], - bitrates: bitrates, - targetLayers: DefaultMaxLayers, - requestLayerSpatial: f.maxLayers.Spatial, - maxLayers: f.maxLayers, - distanceToDesired: -1, + PauseReason: VideoPauseReasonNone, + BandwidthRequested: bitrates[1][3], + BandwidthDelta: bitrates[1][3], + BandwidthNeeded: bitrates[1][3], + Bitrates: bitrates, + TargetLayers: buffer.DefaultMaxLayers, + RequestLayerSpatial: f.maxLayers.Spatial, + MaxLayers: f.maxLayers, + DistanceToDesired: -1, } result = f.AllocateOptimal(nil, bitrates, true) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) - require.Equal(t, DefaultMaxLayers, f.TargetLayers()) + require.Equal(t, buffer.DefaultMaxLayers, f.TargetLayers()) // reset max layers for rest of the tests below - f.maxLayers = DefaultMaxLayers + f.maxLayers = buffer.DefaultMaxLayers // when feed is dry and current is not valid, should set up for opportunistic forwarding // NOTE: feed is dry due to availableLayers = nil, some valid bitrates may be passed in here for testing purposes only disable(f) - expectedTargetLayers := VideoLayers{ + expectedTargetLayers := buffer.VideoLayer{ Spatial: 2, - Temporal: DefaultMaxLayerTemporal, + Temporal: buffer.DefaultMaxLayerTemporal, } expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonNone, - bandwidthRequested: bitrates[2][1], - bandwidthDelta: bitrates[2][1] - bitrates[1][3], - bandwidthNeeded: bitrates[2][1], - bitrates: bitrates, - targetLayers: expectedTargetLayers, - requestLayerSpatial: expectedTargetLayers.Spatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: -0.5, + PauseReason: VideoPauseReasonNone, + BandwidthRequested: bitrates[2][1], + BandwidthDelta: bitrates[2][1] - bitrates[1][3], + BandwidthNeeded: bitrates[2][1], + Bitrates: bitrates, + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: expectedTargetLayers.Spatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: -0.5, } result = f.AllocateOptimal(nil, bitrates, true) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) - f.targetLayers = VideoLayers{Spatial: 0, Temporal: 0} // set to valid to trigger paths in tests below - f.currentLayers = VideoLayers{Spatial: 0, Temporal: 3} // set to valid to trigger paths in tests below + f.targetLayers = buffer.VideoLayer{Spatial: 0, Temporal: 0} // set to valid to trigger paths in tests below + f.currentLayers = buffer.VideoLayer{Spatial: 0, Temporal: 3} // set to valid to trigger paths in tests below // when feed is dry and current is valid, should stay at current - expectedTargetLayers = VideoLayers{ + expectedTargetLayers = buffer.VideoLayer{ Spatial: 0, Temporal: 3, } expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0 - bitrates[2][1], - bitrates: emptyBitrates, - targetLayers: expectedTargetLayers, - requestLayerSpatial: expectedTargetLayers.Spatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: -0.75, + PauseReason: VideoPauseReasonFeedDry, + BandwidthRequested: 0, + BandwidthDelta: 0 - bitrates[2][1], + Bitrates: emptyBitrates, + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: expectedTargetLayers.Spatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: -0.75, } result = f.AllocateOptimal(nil, emptyBitrates, true) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) - f.currentLayers = InvalidLayers + f.currentLayers = buffer.InvalidLayers // opportunistic target if feed is not dry and current is not valid, i. e. not forwarding expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonNone, - bandwidthRequested: bitrates[2][1], - bandwidthDelta: bitrates[2][1], - bandwidthNeeded: bitrates[2][1], - bitrates: bitrates, - targetLayers: DefaultMaxLayers, - requestLayerSpatial: 2, - maxLayers: DefaultMaxLayers, - distanceToDesired: -0.5, + PauseReason: VideoPauseReasonNone, + BandwidthRequested: bitrates[2][1], + BandwidthDelta: bitrates[2][1], + BandwidthNeeded: bitrates[2][1], + Bitrates: bitrates, + TargetLayers: buffer.DefaultMaxLayers, + RequestLayerSpatial: 2, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: -0.5, } result = f.AllocateOptimal([]int32{0, 1}, bitrates, true) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) - require.Equal(t, DefaultMaxLayers, f.TargetLayers()) + require.Equal(t, buffer.DefaultMaxLayers, f.TargetLayers()) // if feed is not dry and current is not locked, should be opportunistic (with and without overshoot) - f.targetLayers = InvalidLayers + f.targetLayers = buffer.InvalidLayers expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0 - bitrates[2][1], - bitrates: emptyBitrates, - targetLayers: DefaultMaxLayers, - requestLayerSpatial: 2, - maxLayers: DefaultMaxLayers, - distanceToDesired: -1.0, + PauseReason: VideoPauseReasonFeedDry, + BandwidthRequested: 0, + BandwidthDelta: 0 - bitrates[2][1], + Bitrates: emptyBitrates, + TargetLayers: buffer.DefaultMaxLayers, + RequestLayerSpatial: 2, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: -1.0, } result = f.AllocateOptimal([]int32{0, 1}, emptyBitrates, false) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) - f.targetLayers = InvalidLayers - expectedTargetLayers = VideoLayers{ + f.targetLayers = buffer.InvalidLayers + expectedTargetLayers = buffer.VideoLayer{ Spatial: 2, - Temporal: DefaultMaxLayerTemporal, + Temporal: buffer.DefaultMaxLayerTemporal, } expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonNone, - bandwidthRequested: bitrates[2][1], - bandwidthDelta: bitrates[2][1], - bandwidthNeeded: bitrates[2][1], - bitrates: bitrates, - targetLayers: expectedTargetLayers, - requestLayerSpatial: 2, - maxLayers: DefaultMaxLayers, - distanceToDesired: -0.5, + PauseReason: VideoPauseReasonNone, + BandwidthRequested: bitrates[2][1], + BandwidthDelta: bitrates[2][1], + BandwidthNeeded: bitrates[2][1], + Bitrates: bitrates, + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: 2, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: -0.5, } result = f.AllocateOptimal([]int32{0, 1}, bitrates, 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{ + f.currentLayers = buffer.VideoLayer{Spatial: 0, Temporal: 1} + expectedTargetLayers = buffer.VideoLayer{ Spatial: 1, - Temporal: DefaultMaxLayerTemporal, + Temporal: buffer.DefaultMaxLayerTemporal, } expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonNone, - bandwidthRequested: bitrates[2][1], - bandwidthDelta: 0, - bandwidthNeeded: bitrates[2][1], - bitrates: bitrates, - targetLayers: expectedTargetLayers, - requestLayerSpatial: 1, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0.5, + PauseReason: VideoPauseReasonNone, + BandwidthRequested: bitrates[2][1], + BandwidthDelta: 0, + BandwidthNeeded: bitrates[2][1], + Bitrates: bitrates, + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: 1, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 0.5, } result = f.AllocateOptimal([]int32{1}, bitrates, true) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) // stays the same if feed is not dry and current is valid, available and locked - f.maxLayers = VideoLayers{Spatial: 0, Temporal: 1} - f.currentLayers = VideoLayers{Spatial: 0, Temporal: 1} + f.maxLayers = buffer.VideoLayer{Spatial: 0, Temporal: 1} + f.currentLayers = buffer.VideoLayer{Spatial: 0, Temporal: 1} f.requestLayerSpatial = 0 - expectedTargetLayers = VideoLayers{ + expectedTargetLayers = buffer.VideoLayer{ Spatial: 0, Temporal: 1, } expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0 - bitrates[2][1], - bitrates: emptyBitrates, - targetLayers: expectedTargetLayers, - requestLayerSpatial: 0, - maxLayers: f.maxLayers, - distanceToDesired: 0.0, + PauseReason: VideoPauseReasonFeedDry, + BandwidthRequested: 0, + BandwidthDelta: 0 - bitrates[2][1], + Bitrates: emptyBitrates, + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: 0, + MaxLayers: f.maxLayers, + DistanceToDesired: 0.0, } result = f.AllocateOptimal([]int32{0, 1}, emptyBitrates, true) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) // opportunistic if feed is not dry and current is valid, but request layer has changed - f.maxLayers = VideoLayers{Spatial: 2, Temporal: 1} - f.currentLayers = VideoLayers{Spatial: 0, Temporal: 1} + f.maxLayers = buffer.VideoLayer{Spatial: 2, Temporal: 1} + f.currentLayers = buffer.VideoLayer{Spatial: 0, Temporal: 1} f.requestLayerSpatial = 0 - expectedTargetLayers = VideoLayers{ + expectedTargetLayers = buffer.VideoLayer{ Spatial: 2, Temporal: 3, } expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: emptyBitrates, - targetLayers: expectedTargetLayers, - requestLayerSpatial: 2, - maxLayers: f.maxLayers, - distanceToDesired: -1.5, + PauseReason: VideoPauseReasonFeedDry, + BandwidthRequested: 0, + BandwidthDelta: 0, + Bitrates: emptyBitrates, + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: 2, + MaxLayers: f.maxLayers, + DistanceToDesired: -1.5, } result = f.AllocateOptimal([]int32{0, 1}, emptyBitrates, true) require.Equal(t, expectedResult, result) @@ -406,10 +406,10 @@ func TestForwarderAllocateOptimal(t *testing.T) { func TestForwarderProvisionalAllocate(t *testing.T) { f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) - f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) - f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) - f.SetMaxPublishedLayer(DefaultMaxLayerSpatial) - f.SetMaxTemporalLayerSeen(DefaultMaxLayerTemporal) + f.SetMaxSpatialLayer(buffer.DefaultMaxLayerSpatial) + f.SetMaxTemporalLayer(buffer.DefaultMaxLayerTemporal) + f.SetMaxPublishedLayer(buffer.DefaultMaxLayerSpatial) + f.SetMaxTemporalLayerSeen(buffer.DefaultMaxLayerTemporal) bitrates := Bitrates{ {1, 2, 3, 4}, @@ -419,37 +419,37 @@ func TestForwarderProvisionalAllocate(t *testing.T) { f.ProvisionalAllocatePrepare(nil, bitrates) - usedBitrate := f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 0, Temporal: 0}, true, false) + usedBitrate := f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 0, Temporal: 0}, true, false) require.Equal(t, bitrates[0][0], usedBitrate) - usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 2, Temporal: 3}, true, false) + usedBitrate = f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 2, Temporal: 3}, true, false) require.Equal(t, bitrates[2][3]-bitrates[0][0], usedBitrate) - usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 0, Temporal: 3}, true, false) + usedBitrate = f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 0, Temporal: 3}, true, false) require.Equal(t, bitrates[0][3]-bitrates[2][3], usedBitrate) - usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 1, Temporal: 2}, true, false) + usedBitrate = f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 1, Temporal: 2}, true, false) require.Equal(t, bitrates[1][2]-bitrates[0][3], usedBitrate) // available not enough to reach (2, 2), allocating at (2, 2) should not succeed - usedBitrate = f.ProvisionalAllocate(bitrates[2][2]-bitrates[1][2]-1, VideoLayers{Spatial: 2, Temporal: 2}, true, false) + usedBitrate = f.ProvisionalAllocate(bitrates[2][2]-bitrates[1][2]-1, buffer.VideoLayer{Spatial: 2, Temporal: 2}, true, false) require.Equal(t, int64(0), usedBitrate) // committing should set target to (1, 2) - expectedTargetLayers := VideoLayers{ + expectedTargetLayers := buffer.VideoLayer{ Spatial: 1, Temporal: 2, } expectedResult := VideoAllocation{ - isDeficient: true, - bandwidthRequested: bitrates[1][2], - bandwidthDelta: bitrates[1][2], - bandwidthNeeded: bitrates[2][3], - bitrates: bitrates, - targetLayers: expectedTargetLayers, - requestLayerSpatial: expectedTargetLayers.Spatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: 1.25, + IsDeficient: true, + BandwidthRequested: bitrates[1][2], + BandwidthDelta: bitrates[1][2], + BandwidthNeeded: bitrates[2][3], + Bitrates: bitrates, + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: expectedTargetLayers.Spatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 1.25, } result := f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -457,26 +457,26 @@ func TestForwarderProvisionalAllocate(t *testing.T) { require.Equal(t, expectedTargetLayers, f.TargetLayers()) // when nothing fits and pausing disallowed, should allocate (0, 0) - f.targetLayers = InvalidLayers + f.targetLayers = buffer.InvalidLayers f.ProvisionalAllocatePrepare(nil, bitrates) - usedBitrate = f.ProvisionalAllocate(0, VideoLayers{Spatial: 0, Temporal: 0}, false, false) + usedBitrate = f.ProvisionalAllocate(0, buffer.VideoLayer{Spatial: 0, Temporal: 0}, false, false) require.Equal(t, int64(1), usedBitrate) // committing should set target to (0, 0) - expectedTargetLayers = VideoLayers{ + expectedTargetLayers = buffer.VideoLayer{ Spatial: 0, Temporal: 0, } expectedResult = VideoAllocation{ - isDeficient: true, - bandwidthRequested: bitrates[0][0], - bandwidthDelta: bitrates[0][0] - bitrates[1][2], - bandwidthNeeded: bitrates[2][3], - bitrates: bitrates, - targetLayers: expectedTargetLayers, - requestLayerSpatial: expectedTargetLayers.Spatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: 2.75, + IsDeficient: true, + BandwidthRequested: bitrates[0][0], + BandwidthDelta: bitrates[0][0] - bitrates[1][2], + BandwidthNeeded: bitrates[2][3], + Bitrates: bitrates, + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: expectedTargetLayers.Spatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 2.75, } result = f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -496,34 +496,34 @@ func TestForwarderProvisionalAllocate(t *testing.T) { f.ProvisionalAllocatePrepare(nil, bitrates) - usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 0, Temporal: 0}, false, true) + usedBitrate = f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 0, Temporal: 0}, false, true) require.Equal(t, int64(0), usedBitrate) // overshoot should succeed - usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 2, Temporal: 3}, false, true) + usedBitrate = f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 2, Temporal: 3}, false, true) require.Equal(t, bitrates[2][3], usedBitrate) // overshoot should succeed - this should win as this is lesser overshoot - usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 1, Temporal: 3}, false, true) + usedBitrate = f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 1, Temporal: 3}, false, true) require.Equal(t, bitrates[1][3]-bitrates[2][3], usedBitrate) // committing should set target to (1, 3) - expectedTargetLayers = VideoLayers{ + expectedTargetLayers = buffer.VideoLayer{ Spatial: 1, Temporal: 3, } - expectedMaxLayers := VideoLayers{ + expectedMaxLayers := buffer.VideoLayer{ Spatial: 0, Temporal: 3, } expectedResult = VideoAllocation{ - bandwidthRequested: bitrates[1][3], - bandwidthDelta: bitrates[1][3] - 1, // 1 is the last allocation bandwidth requested - bitrates: bitrates, - targetLayers: expectedTargetLayers, - requestLayerSpatial: expectedTargetLayers.Spatial, - maxLayers: expectedMaxLayers, - distanceToDesired: -1.75, + BandwidthRequested: bitrates[1][3], + BandwidthDelta: bitrates[1][3] - 1, // 1 is the last allocation bandwidth requested + Bitrates: bitrates, + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: expectedTargetLayers.Spatial, + MaxLayers: expectedMaxLayers, + DistanceToDesired: -1.75, } result = f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -539,35 +539,35 @@ func TestForwarderProvisionalAllocate(t *testing.T) { {0, 0, 0, 0}, } - f.currentLayers = VideoLayers{Spatial: 0, Temporal: 2} + f.currentLayers = buffer.VideoLayer{Spatial: 0, Temporal: 2} f.ProvisionalAllocatePrepare(nil, bitrates) // all the provisional allocations should not succeed because the feed is dry - usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 0, Temporal: 0}, false, true) + usedBitrate = f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 0, Temporal: 0}, false, true) require.Equal(t, int64(0), usedBitrate) // overshoot should not succeed - usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 2, Temporal: 3}, false, true) + usedBitrate = f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 2, Temporal: 3}, false, true) require.Equal(t, int64(0), usedBitrate) // overshoot should not succeed - usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 1, Temporal: 3}, false, true) + usedBitrate = f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 1, Temporal: 3}, false, true) require.Equal(t, int64(0), usedBitrate) // committing should set target to (0, 2), i. e. leave it at current for opportunistic forwarding - expectedTargetLayers = VideoLayers{ + expectedTargetLayers = buffer.VideoLayer{ Spatial: 0, Temporal: 2, } expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: bitrates[0][2], - bandwidthDelta: bitrates[0][2] - 8, // 8 is the last allocation bandwidth requested - bitrates: bitrates, - targetLayers: expectedTargetLayers, - requestLayerSpatial: expectedTargetLayers.Spatial, - maxLayers: expectedMaxLayers, - distanceToDesired: 0.25, + PauseReason: VideoPauseReasonFeedDry, + BandwidthRequested: bitrates[0][2], + BandwidthDelta: bitrates[0][2] - 8, // 8 is the last allocation bandwidth requested + Bitrates: bitrates, + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: expectedTargetLayers.Spatial, + MaxLayers: expectedMaxLayers, + DistanceToDesired: 0.25, } result = f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -577,42 +577,42 @@ func TestForwarderProvisionalAllocate(t *testing.T) { // // Same case as above, but current is above max, so target should go to invalid // - f.currentLayers = VideoLayers{Spatial: 1, Temporal: 2} + f.currentLayers = buffer.VideoLayer{Spatial: 1, Temporal: 2} f.ProvisionalAllocatePrepare(nil, bitrates) // all the provisional allocations below should not succeed because the feed is dry - usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 0, Temporal: 0}, false, true) + usedBitrate = f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 0, Temporal: 0}, false, true) require.Equal(t, int64(0), usedBitrate) // overshoot should not succeed - usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 2, Temporal: 3}, false, true) + usedBitrate = f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 2, Temporal: 3}, false, true) require.Equal(t, int64(0), usedBitrate) // overshoot should not succeed - usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 1, Temporal: 3}, false, true) + usedBitrate = f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 1, Temporal: 3}, false, true) require.Equal(t, int64(0), usedBitrate) expectedResult = VideoAllocation{ - pauseReason: VideoPauseReasonFeedDry, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: bitrates, - targetLayers: InvalidLayers, - requestLayerSpatial: InvalidLayerSpatial, - maxLayers: expectedMaxLayers, - distanceToDesired: 0.25, + PauseReason: VideoPauseReasonFeedDry, + BandwidthRequested: 0, + BandwidthDelta: 0, + Bitrates: bitrates, + TargetLayers: buffer.InvalidLayers, + RequestLayerSpatial: buffer.InvalidLayerSpatial, + MaxLayers: expectedMaxLayers, + DistanceToDesired: 0.25, } result = f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) - require.Equal(t, InvalidLayers, f.TargetLayers()) - require.Equal(t, InvalidLayers, f.CurrentLayers()) + require.Equal(t, buffer.InvalidLayers, f.TargetLayers()) + require.Equal(t, buffer.InvalidLayers, f.CurrentLayers()) } func TestForwarderProvisionalAllocateMute(t *testing.T) { f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) - f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) - f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) + f.SetMaxSpatialLayer(buffer.DefaultMaxLayerSpatial) + f.SetMaxTemporalLayer(buffer.DefaultMaxLayerTemporal) bitrates := Bitrates{ {1, 2, 3, 4}, @@ -623,35 +623,35 @@ func TestForwarderProvisionalAllocateMute(t *testing.T) { f.Mute(true) f.ProvisionalAllocatePrepare(nil, bitrates) - usedBitrate := f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 0, Temporal: 0}, true, false) + usedBitrate := f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 0, Temporal: 0}, true, false) require.Equal(t, int64(0), usedBitrate) - usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 1, Temporal: 2}, true, true) + usedBitrate = f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 1, Temporal: 2}, true, true) require.Equal(t, int64(0), usedBitrate) - // committing should set target to InvalidLayers as track is muted + // committing should set target to buffer.InvalidLayers as track is muted expectedResult := VideoAllocation{ - pauseReason: VideoPauseReasonMuted, - bandwidthRequested: 0, - bandwidthDelta: 0, - bitrates: bitrates, - targetLayers: InvalidLayers, - requestLayerSpatial: InvalidLayerSpatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0, + PauseReason: VideoPauseReasonMuted, + BandwidthRequested: 0, + BandwidthDelta: 0, + Bitrates: bitrates, + TargetLayers: buffer.InvalidLayers, + RequestLayerSpatial: buffer.InvalidLayerSpatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 0, } result := f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) - require.Equal(t, InvalidLayers, f.TargetLayers()) + require.Equal(t, buffer.InvalidLayers, f.TargetLayers()) } func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) { f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) - f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) - f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) - f.SetMaxPublishedLayer(DefaultMaxLayerSpatial) - f.SetMaxTemporalLayerSeen(DefaultMaxLayerTemporal) + f.SetMaxSpatialLayer(buffer.DefaultMaxLayerSpatial) + f.SetMaxTemporalLayer(buffer.DefaultMaxLayerTemporal) + f.SetMaxPublishedLayer(buffer.DefaultMaxLayerSpatial) + f.SetMaxTemporalLayerSeen(buffer.DefaultMaxLayerTemporal) bitrates := Bitrates{ {1, 2, 3, 4}, @@ -661,27 +661,27 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) { f.ProvisionalAllocatePrepare(nil, bitrates) - // from scratch (InvalidLayers) should give back layer (0, 0) + // from scratch (buffer.InvalidLayers) should give back layer (0, 0) expectedTransition := VideoTransition{ - from: InvalidLayers, - to: VideoLayers{Spatial: 0, Temporal: 0}, - bandwidthDelta: 1, + From: buffer.InvalidLayers, + To: buffer.VideoLayer{Spatial: 0, Temporal: 0}, + BandwidthDelta: 1, } transition := f.ProvisionalAllocateGetCooperativeTransition(false) require.Equal(t, expectedTransition, transition) // committing should set target to (0, 0) - expectedLayers := VideoLayers{Spatial: 0, Temporal: 0} + expectedLayers := buffer.VideoLayer{Spatial: 0, Temporal: 0} expectedResult := VideoAllocation{ - isDeficient: true, - bandwidthRequested: 1, - bandwidthDelta: 1, - bandwidthNeeded: bitrates[2][1], - bitrates: bitrates, - targetLayers: expectedLayers, - requestLayerSpatial: expectedLayers.Spatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: 2.25, + IsDeficient: true, + BandwidthRequested: 1, + BandwidthDelta: 1, + BandwidthNeeded: bitrates[2][1], + Bitrates: bitrates, + TargetLayers: expectedLayers, + RequestLayerSpatial: expectedLayers.Spatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 2.25, } result := f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -689,28 +689,28 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) { require.Equal(t, expectedLayers, f.TargetLayers()) // a higher target that is already streaming, just maintain it - targetLayers := VideoLayers{Spatial: 2, Temporal: 1} + targetLayers := buffer.VideoLayer{Spatial: 2, Temporal: 1} f.targetLayers = targetLayers - f.lastAllocation.bandwidthRequested = 10 + f.lastAllocation.BandwidthRequested = 10 expectedTransition = VideoTransition{ - from: targetLayers, - to: targetLayers, - bandwidthDelta: 0, + From: targetLayers, + To: targetLayers, + BandwidthDelta: 0, } transition = f.ProvisionalAllocateGetCooperativeTransition(false) require.Equal(t, expectedTransition, transition) // committing should set target to (2, 1) - expectedLayers = VideoLayers{Spatial: 2, Temporal: 1} + expectedLayers = buffer.VideoLayer{Spatial: 2, Temporal: 1} expectedResult = VideoAllocation{ - bandwidthRequested: 10, - bandwidthDelta: 0, - bitrates: bitrates, - bandwidthNeeded: bitrates[2][1], - targetLayers: expectedLayers, - requestLayerSpatial: expectedLayers.Spatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0.0, + BandwidthRequested: 10, + BandwidthDelta: 0, + Bitrates: bitrates, + BandwidthNeeded: bitrates[2][1], + TargetLayers: expectedLayers, + RequestLayerSpatial: expectedLayers.Spatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 0.0, } result = f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -718,12 +718,12 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) { require.Equal(t, expectedLayers, f.TargetLayers()) // from a target that has become unavailable, should switch to lower available layer - targetLayers = VideoLayers{Spatial: 2, Temporal: 2} + targetLayers = buffer.VideoLayer{Spatial: 2, Temporal: 2} f.targetLayers = targetLayers expectedTransition = VideoTransition{ - from: targetLayers, - to: VideoLayers{Spatial: 2, Temporal: 1}, - bandwidthDelta: 0, + From: targetLayers, + To: buffer.VideoLayer{Spatial: 2, Temporal: 1}, + BandwidthDelta: 0, } transition = f.ProvisionalAllocateGetCooperativeTransition(false) require.Equal(t, expectedTransition, transition) @@ -734,11 +734,11 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) { f.Mute(true) f.ProvisionalAllocatePrepare(nil, bitrates) - // mute should send target to InvalidLayers + // mute should send target to buffer.InvalidLayers expectedTransition = VideoTransition{ - from: VideoLayers{Spatial: 2, Temporal: 1}, - to: InvalidLayers, - bandwidthDelta: -10, + From: buffer.VideoLayer{Spatial: 2, Temporal: 1}, + To: buffer.InvalidLayers, + BandwidthDelta: -10, } transition = f.ProvisionalAllocateGetCooperativeTransition(false) require.Equal(t, expectedTransition, transition) @@ -757,29 +757,29 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) { {9, 10, 0, 0}, } - f.targetLayers = InvalidLayers + f.targetLayers = buffer.InvalidLayers f.ProvisionalAllocatePrepare(nil, bitrates) - // from scratch (InvalidLayers) should go to a layer past maximum as overshoot is allowed + // from scratch (buffer.InvalidLayers) should go to a layer past maximum as overshoot is allowed expectedTransition = VideoTransition{ - from: InvalidLayers, - to: VideoLayers{Spatial: 1, Temporal: 0}, - bandwidthDelta: 5, + From: buffer.InvalidLayers, + To: buffer.VideoLayer{Spatial: 1, Temporal: 0}, + BandwidthDelta: 5, } transition = f.ProvisionalAllocateGetCooperativeTransition(true) require.Equal(t, expectedTransition, transition) // committing should set target to (1, 0) - expectedLayers = VideoLayers{Spatial: 1, Temporal: 0} - expectedMaxLayers := VideoLayers{Spatial: 0, Temporal: DefaultMaxLayerTemporal} + expectedLayers = buffer.VideoLayer{Spatial: 1, Temporal: 0} + expectedMaxLayers := buffer.VideoLayer{Spatial: 0, Temporal: buffer.DefaultMaxLayerTemporal} expectedResult = VideoAllocation{ - bandwidthRequested: 5, - bandwidthDelta: 5, - bitrates: bitrates, - targetLayers: expectedLayers, - requestLayerSpatial: expectedLayers.Spatial, - maxLayers: expectedMaxLayers, - distanceToDesired: -1.0, + BandwidthRequested: 5, + BandwidthDelta: 5, + Bitrates: bitrates, + TargetLayers: expectedLayers, + RequestLayerSpatial: expectedLayers.Spatial, + MaxLayers: expectedMaxLayers, + DistanceToDesired: -1.0, } result = f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -795,30 +795,30 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) { {0, 0, 0, 0}, } - f.currentLayers = VideoLayers{Spatial: 0, Temporal: 2} - f.targetLayers = InvalidLayers + f.currentLayers = buffer.VideoLayer{Spatial: 0, Temporal: 2} + f.targetLayers = buffer.InvalidLayers f.ProvisionalAllocatePrepare(nil, bitrates) - // from scratch (InvalidLayers) should go to current layer - // NOTE: targetLayer is set to InvalidLayers for testing, but in practice current layers valid and target layers invalid should not happen + // from scratch (buffer.InvalidLayers) should go to current layer + // NOTE: targetLayer is set to buffer.InvalidLayers for testing, but in practice current layers valid and target layers invalid should not happen expectedTransition = VideoTransition{ - from: InvalidLayers, - to: VideoLayers{Spatial: 0, Temporal: 2}, - bandwidthDelta: -5, // 5 was the bandwidth needed for the last allocation + From: buffer.InvalidLayers, + To: buffer.VideoLayer{Spatial: 0, Temporal: 2}, + BandwidthDelta: -5, // 5 was the bandwidth needed for the last allocation } transition = f.ProvisionalAllocateGetCooperativeTransition(true) require.Equal(t, expectedTransition, transition) // committing should set target to (0, 2) - expectedLayers = VideoLayers{Spatial: 0, Temporal: 2} + expectedLayers = buffer.VideoLayer{Spatial: 0, Temporal: 2} expectedResult = VideoAllocation{ - bandwidthRequested: 0, - bandwidthDelta: -5, - bitrates: bitrates, - targetLayers: expectedLayers, - requestLayerSpatial: expectedLayers.Spatial, - maxLayers: expectedMaxLayers, - distanceToDesired: -0.5, + BandwidthRequested: 0, + BandwidthDelta: -5, + Bitrates: bitrates, + TargetLayers: expectedLayers, + RequestLayerSpatial: expectedLayers.Spatial, + MaxLayers: expectedMaxLayers, + DistanceToDesired: -0.5, } result = f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -827,13 +827,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, - requestLayerSpatial: expectedLayers.Spatial, - maxLayers: expectedMaxLayers, - distanceToDesired: -0.5, + BandwidthRequested: 0, + BandwidthDelta: 0, + Bitrates: bitrates, + TargetLayers: expectedLayers, + RequestLayerSpatial: expectedLayers.Spatial, + MaxLayers: expectedMaxLayers, + DistanceToDesired: -0.5, } result = f.ProvisionalAllocateCommit() require.Equal(t, expectedResult, result) @@ -843,8 +843,8 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) { func TestForwarderProvisionalAllocateGetBestWeightedTransition(t *testing.T) { f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) - f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) - f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) + f.SetMaxSpatialLayer(buffer.DefaultMaxLayerSpatial) + f.SetMaxTemporalLayer(buffer.DefaultMaxLayerTemporal) bitrates := Bitrates{ {1, 2, 3, 4}, @@ -854,12 +854,12 @@ func TestForwarderProvisionalAllocateGetBestWeightedTransition(t *testing.T) { f.ProvisionalAllocatePrepare(nil, bitrates) - f.targetLayers = VideoLayers{Spatial: 2, Temporal: 2} - f.lastAllocation.bandwidthRequested = bitrates[2][2] + f.targetLayers = buffer.VideoLayer{Spatial: 2, Temporal: 2} + f.lastAllocation.BandwidthRequested = bitrates[2][2] expectedTransition := VideoTransition{ - from: f.targetLayers, - to: VideoLayers{Spatial: 2, Temporal: 0}, - bandwidthDelta: 2, + From: f.targetLayers, + To: buffer.VideoLayer{Spatial: 2, Temporal: 0}, + BandwidthDelta: 2, } transition := f.ProvisionalAllocateGetBestWeightedTransition() require.Equal(t, expectedTransition, transition) @@ -867,9 +867,9 @@ func TestForwarderProvisionalAllocateGetBestWeightedTransition(t *testing.T) { func TestForwarderAllocateNextHigher(t *testing.T) { f := newForwarder(testutils.TestOpusCodec, webrtc.RTPCodecTypeAudio) - f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) - f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) - f.SetMaxPublishedLayer(DefaultMaxLayerSpatial) + f.SetMaxSpatialLayer(buffer.DefaultMaxLayerSpatial) + f.SetMaxTemporalLayer(buffer.DefaultMaxLayerTemporal) + f.SetMaxPublishedLayer(buffer.DefaultMaxLayerSpatial) emptyBitrates := Bitrates{} bitrates := Bitrates{ @@ -878,81 +878,81 @@ func TestForwarderAllocateNextHigher(t *testing.T) { {0, 7, 0, 0}, } - result, boosted := f.AllocateNextHigher(ChannelCapacityInfinity, nil, bitrates, false) + result, boosted := f.AllocateNextHigher(100_000_000, nil, bitrates, false) require.Equal(t, VideoAllocationDefault, result) // no layer for audio require.False(t, boosted) f = newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) - f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) - f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) - f.SetMaxPublishedLayer(DefaultMaxLayerSpatial) - f.SetMaxTemporalLayerSeen(DefaultMaxLayerTemporal) + f.SetMaxSpatialLayer(buffer.DefaultMaxLayerSpatial) + f.SetMaxTemporalLayer(buffer.DefaultMaxLayerTemporal) + f.SetMaxPublishedLayer(buffer.DefaultMaxLayerSpatial) + f.SetMaxTemporalLayerSeen(buffer.DefaultMaxLayerTemporal) // when not in deficient state, does not boost - result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, nil, bitrates, false) + result, boosted = f.AllocateNextHigher(100_000_000, nil, bitrates, false) require.Equal(t, VideoAllocationDefault, result) require.False(t, boosted) // if layers have not caught up, should not allocate next layer even if deficient - f.targetLayers = VideoLayers{ + f.targetLayers = buffer.VideoLayer{ Spatial: 0, Temporal: 0, } - result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, nil, bitrates, false) + result, boosted = f.AllocateNextHigher(100_000_000, nil, bitrates, false) require.Equal(t, VideoAllocationDefault, result) require.False(t, boosted) - f.lastAllocation.isDeficient = true - f.currentLayers = VideoLayers{ + f.lastAllocation.IsDeficient = true + f.currentLayers = buffer.VideoLayer{ Spatial: 0, Temporal: 0, } // move from (0, 0) -> (0, 1), i.e. a higher temporal layer is available in the same spatial layer - expectedTargetLayers := VideoLayers{ + expectedTargetLayers := buffer.VideoLayer{ Spatial: 0, Temporal: 1, } expectedResult := VideoAllocation{ - isDeficient: true, - bandwidthRequested: 3, - bandwidthDelta: 1, - bandwidthNeeded: bitrates[2][1], - bitrates: bitrates, - targetLayers: expectedTargetLayers, - requestLayerSpatial: expectedTargetLayers.Spatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: 2.0, + IsDeficient: true, + BandwidthRequested: 3, + BandwidthDelta: 1, + BandwidthNeeded: bitrates[2][1], + Bitrates: bitrates, + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: expectedTargetLayers.Spatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 2.0, } - result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, nil, bitrates, false) + result, boosted = f.AllocateNextHigher(100_000_000, nil, bitrates, false) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) 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, nil, emptyBitrates, false) + result, boosted = f.AllocateNextHigher(100_000_000, nil, 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{ + expectedTargetLayers = buffer.VideoLayer{ Spatial: 1, Temporal: 0, } expectedResult = VideoAllocation{ - isDeficient: true, - bandwidthRequested: 4, - bandwidthDelta: 1, - bandwidthNeeded: bitrates[2][1], - bitrates: bitrates, - targetLayers: expectedTargetLayers, - requestLayerSpatial: expectedTargetLayers.Spatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: 1.25, + IsDeficient: true, + BandwidthRequested: 4, + BandwidthDelta: 1, + BandwidthNeeded: bitrates[2][1], + Bitrates: bitrates, + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: expectedTargetLayers.Spatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 1.25, } - result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, nil, bitrates, false) + result, boosted = f.AllocateNextHigher(100_000_000, nil, bitrates, false) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) @@ -961,22 +961,22 @@ func TestForwarderAllocateNextHigher(t *testing.T) { // next higher, move from (1, 0) -> (1, 3), still deficient though f.currentLayers.Spatial = 1 f.currentLayers.Temporal = 0 - expectedTargetLayers = VideoLayers{ + expectedTargetLayers = buffer.VideoLayer{ Spatial: 1, Temporal: 3, } expectedResult = VideoAllocation{ - isDeficient: true, - bandwidthRequested: 5, - bandwidthDelta: 1, - bandwidthNeeded: bitrates[2][1], - bitrates: bitrates, - targetLayers: expectedTargetLayers, - requestLayerSpatial: expectedTargetLayers.Spatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0.5, + IsDeficient: true, + BandwidthRequested: 5, + BandwidthDelta: 1, + BandwidthNeeded: bitrates[2][1], + Bitrates: bitrates, + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: expectedTargetLayers.Spatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 0.5, } - result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, nil, bitrates, false) + result, boosted = f.AllocateNextHigher(100_000_000, nil, bitrates, false) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) @@ -984,21 +984,21 @@ func TestForwarderAllocateNextHigher(t *testing.T) { // next higher, move from (1, 3) -> (2, 1), optimal allocation f.currentLayers.Temporal = 3 - expectedTargetLayers = VideoLayers{ + expectedTargetLayers = buffer.VideoLayer{ Spatial: 2, Temporal: 1, } expectedResult = VideoAllocation{ - bandwidthRequested: 7, - bandwidthDelta: 2, - bitrates: bitrates, - bandwidthNeeded: bitrates[2][1], - targetLayers: expectedTargetLayers, - requestLayerSpatial: expectedTargetLayers.Spatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0.0, + BandwidthRequested: 7, + BandwidthDelta: 2, + Bitrates: bitrates, + BandwidthNeeded: bitrates[2][1], + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: expectedTargetLayers.Spatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 0.0, } - result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, nil, bitrates, false) + result, boosted = f.AllocateNextHigher(100_000_000, nil, bitrates, false) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) @@ -1007,7 +1007,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) { // ask again, should return not boosted as there is no room to go higher f.currentLayers.Spatial = 2 f.currentLayers.Temporal = 1 - result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, nil, bitrates, false) + result, boosted = f.AllocateNextHigher(100_000_000, nil, bitrates, false) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) @@ -1015,25 +1015,25 @@ func TestForwarderAllocateNextHigher(t *testing.T) { // turn off everything, allocating next layer should result in streaming lowest layers disable(f) - f.lastAllocation.isDeficient = true - f.lastAllocation.bandwidthRequested = 0 + f.lastAllocation.IsDeficient = true + f.lastAllocation.BandwidthRequested = 0 - expectedTargetLayers = VideoLayers{ + expectedTargetLayers = buffer.VideoLayer{ Spatial: 0, Temporal: 0, } expectedResult = VideoAllocation{ - isDeficient: true, - bandwidthRequested: 2, - bandwidthDelta: 2, - bandwidthNeeded: bitrates[2][1], - bitrates: bitrates, - targetLayers: expectedTargetLayers, - requestLayerSpatial: expectedTargetLayers.Spatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: 2.25, + IsDeficient: true, + BandwidthRequested: 2, + BandwidthDelta: 2, + BandwidthNeeded: bitrates[2][1], + Bitrates: bitrates, + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: expectedTargetLayers.Spatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 2.25, } - result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, nil, bitrates, false) + result, boosted = f.AllocateNextHigher(100_000_000, nil, bitrates, false) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) @@ -1041,15 +1041,15 @@ func TestForwarderAllocateNextHigher(t *testing.T) { // no new available capacity cannot bump up layer expectedResult = VideoAllocation{ - isDeficient: true, - bandwidthRequested: 2, - bandwidthDelta: 2, - bandwidthNeeded: bitrates[2][1], - bitrates: bitrates, - targetLayers: expectedTargetLayers, - requestLayerSpatial: expectedTargetLayers.Spatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: 2.25, + IsDeficient: true, + BandwidthRequested: 2, + BandwidthDelta: 2, + BandwidthNeeded: bitrates[2][1], + Bitrates: bitrates, + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: expectedTargetLayers.Spatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 2.25, } result, boosted = f.AllocateNextHigher(0, nil, bitrates, false) require.Equal(t, expectedResult, result) @@ -1068,22 +1068,22 @@ func TestForwarderAllocateNextHigher(t *testing.T) { f.currentLayers = f.targetLayers - expectedTargetLayers = VideoLayers{ + expectedTargetLayers = buffer.VideoLayer{ Spatial: 1, Temporal: 0, } - expectedMaxLayers := VideoLayers{ + expectedMaxLayers := buffer.VideoLayer{ Spatial: 0, - Temporal: DefaultMaxLayerTemporal, + Temporal: buffer.DefaultMaxLayerTemporal, } expectedResult = VideoAllocation{ - bandwidthRequested: bitrates[1][0], - bandwidthDelta: bitrates[1][0], - bitrates: bitrates, - targetLayers: expectedTargetLayers, - requestLayerSpatial: expectedTargetLayers.Spatial, - maxLayers: expectedMaxLayers, - distanceToDesired: -1.0, + BandwidthRequested: bitrates[1][0], + BandwidthDelta: bitrates[1][0], + Bitrates: bitrates, + TargetLayers: expectedTargetLayers, + RequestLayerSpatial: expectedTargetLayers.Spatial, + MaxLayers: expectedMaxLayers, + DistanceToDesired: -1.0, } // overshoot should return (1, 0) even if there is not enough capacity result, boosted = f.AllocateNextHigher(bitrates[1][0]-1, nil, bitrates, true) @@ -1095,10 +1095,10 @@ func TestForwarderAllocateNextHigher(t *testing.T) { func TestForwarderPause(t *testing.T) { f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) - f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) - f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) - f.SetMaxPublishedLayer(DefaultMaxLayerSpatial) - f.SetMaxTemporalLayerSeen(DefaultMaxLayerTemporal) + f.SetMaxSpatialLayer(buffer.DefaultMaxLayerSpatial) + f.SetMaxTemporalLayer(buffer.DefaultMaxLayerTemporal) + f.SetMaxPublishedLayer(buffer.DefaultMaxLayerSpatial) + f.SetMaxTemporalLayerSeen(buffer.DefaultMaxLayerTemporal) bitrates := Bitrates{ {1, 2, 3, 4}, @@ -1107,33 +1107,33 @@ func TestForwarderPause(t *testing.T) { } f.ProvisionalAllocatePrepare(nil, bitrates) - f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 0, Temporal: 0}, true, false) + f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 0, Temporal: 0}, true, false) // should have set target at (0, 0) f.ProvisionalAllocateCommit() expectedResult := VideoAllocation{ - pauseReason: VideoPauseReasonBandwidth, - isDeficient: true, - bandwidthRequested: 0, - bandwidthDelta: 0 - bitrates[0][0], - bandwidthNeeded: bitrates[2][3], - bitrates: bitrates, - targetLayers: InvalidLayers, - requestLayerSpatial: InvalidLayerSpatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: 3, + PauseReason: VideoPauseReasonBandwidth, + IsDeficient: true, + BandwidthRequested: 0, + BandwidthDelta: 0 - bitrates[0][0], + BandwidthNeeded: bitrates[2][3], + Bitrates: bitrates, + TargetLayers: buffer.InvalidLayers, + RequestLayerSpatial: buffer.InvalidLayerSpatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 3, } result := f.Pause(nil, bitrates) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) - require.Equal(t, InvalidLayers, f.TargetLayers()) + require.Equal(t, buffer.InvalidLayers, f.TargetLayers()) } func TestForwarderPauseMute(t *testing.T) { f := newForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) - f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) - f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) - f.SetMaxPublishedLayer(DefaultMaxLayerSpatial) + f.SetMaxSpatialLayer(buffer.DefaultMaxLayerSpatial) + f.SetMaxTemporalLayer(buffer.DefaultMaxLayerTemporal) + f.SetMaxPublishedLayer(buffer.DefaultMaxLayerSpatial) bitrates := Bitrates{ {1, 2, 3, 4}, @@ -1142,25 +1142,25 @@ func TestForwarderPauseMute(t *testing.T) { } f.ProvisionalAllocatePrepare(nil, bitrates) - f.ProvisionalAllocate(bitrates[2][3], VideoLayers{Spatial: 0, Temporal: 0}, true, true) + f.ProvisionalAllocate(bitrates[2][3], buffer.VideoLayer{Spatial: 0, Temporal: 0}, true, true) // should have set target at (0, 0) f.ProvisionalAllocateCommit() f.Mute(true) expectedResult := VideoAllocation{ - pauseReason: VideoPauseReasonMuted, - bandwidthRequested: 0, - bandwidthDelta: 0 - bitrates[0][0], - bitrates: bitrates, - targetLayers: InvalidLayers, - requestLayerSpatial: InvalidLayerSpatial, - maxLayers: DefaultMaxLayers, - distanceToDesired: 0, + PauseReason: VideoPauseReasonMuted, + BandwidthRequested: 0, + BandwidthDelta: 0 - bitrates[0][0], + Bitrates: bitrates, + TargetLayers: buffer.InvalidLayers, + RequestLayerSpatial: buffer.InvalidLayerSpatial, + MaxLayers: buffer.DefaultMaxLayers, + DistanceToDesired: 0, } result := f.Pause(nil, bitrates) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) - require.Equal(t, InvalidLayers, f.TargetLayers()) + require.Equal(t, buffer.InvalidLayers, f.TargetLayers()) } func TestForwarderGetTranslationParamsMuted(t *testing.T) { @@ -1365,7 +1365,7 @@ func TestForwarderGetTranslationParamsVideo(t *testing.T) { require.Equal(t, expectedTP, *actualTP) // although target layer matches, not a key frame, so should drop - f.targetLayers = VideoLayers{ + f.targetLayers = buffer.VideoLayer{ Spatial: 0, Temporal: 1, } @@ -1620,7 +1620,7 @@ func TestForwarderGetTranslationParamsVideo(t *testing.T) { // switching SSRC (happens for new layer or new track source) // should lock onto the new source, but sequence number should be contiguous - f.targetLayers = VideoLayers{ + f.targetLayers = buffer.VideoLayer{ Spatial: 1, Temporal: 1, } @@ -1706,11 +1706,11 @@ func TestForwardGetSnTsForPadding(t *testing.T) { } extPkt, _ := testutils.GetTestExtPacketVP8(params, vp8) - f.targetLayers = VideoLayers{ + f.targetLayers = buffer.VideoLayer{ Spatial: 0, Temporal: 1, } - f.currentLayers = InvalidLayers + f.currentLayers = buffer.InvalidLayers // send it through so that forwarder locks onto stream _, _ = f.GetTranslationParams(extPkt, 0) @@ -1773,11 +1773,11 @@ func TestForwardGetSnTsForBlankFrames(t *testing.T) { } extPkt, _ := testutils.GetTestExtPacketVP8(params, vp8) - f.targetLayers = VideoLayers{ + f.targetLayers = buffer.VideoLayer{ Spatial: 0, Temporal: 1, } - f.currentLayers = InvalidLayers + f.currentLayers = buffer.InvalidLayers // send it through so that forwarder locks onto stream _, _ = f.GetTranslationParams(extPkt, 0) @@ -1843,11 +1843,11 @@ func TestForwardGetPaddingVP8(t *testing.T) { } extPkt, _ := testutils.GetTestExtPacketVP8(params, vp8) - f.targetLayers = VideoLayers{ + f.targetLayers = buffer.VideoLayer{ Spatial: 0, Temporal: 1, } - f.currentLayers = InvalidLayers + f.currentLayers = buffer.InvalidLayers // send it through so that forwarder locks onto stream _, _ = f.GetTranslationParams(extPkt, 0) diff --git a/pkg/sfu/receiver.go b/pkg/sfu/receiver.go index c8c5d9a6..3d2cc9c3 100644 --- a/pkg/sfu/receiver.go +++ b/pkg/sfu/receiver.go @@ -30,7 +30,7 @@ var ( type AudioLevelHandle func(level uint8, duration uint32) -type Bitrates [DefaultMaxLayerSpatial + 1][DefaultMaxLayerTemporal + 1]int64 +type Bitrates [buffer.DefaultMaxLayerSpatial + 1][buffer.DefaultMaxLayerTemporal + 1]int64 // TrackReceiver defines an interface receive media from remote peer type TrackReceiver interface { @@ -94,11 +94,11 @@ type WebRTCReceiver struct { twcc *twcc.Responder bufferMu sync.RWMutex - buffers [DefaultMaxLayerSpatial + 1]*buffer.Buffer + buffers [buffer.DefaultMaxLayerSpatial + 1]*buffer.Buffer rtt uint32 upTrackMu sync.RWMutex - upTracks [DefaultMaxLayerSpatial + 1]*webrtc.TrackRemote + upTracks [buffer.DefaultMaxLayerSpatial + 1]*webrtc.TrackRemote lbThreshold int @@ -391,7 +391,7 @@ func (w *WebRTCReceiver) SetMaxExpectedSpatialLayer(layer int32) { w.streamTrackerManager.SetMaxExpectedSpatialLayer(layer) now := time.Now() - if layer == InvalidLayerSpatial { + if layer == buffer.InvalidLayerSpatial { w.connectionStats.UpdateLayerMute(true, now) } else { w.connectionStats.UpdateLayerMute(false, now) diff --git a/pkg/sfu/streamallocator/channelobserver.go b/pkg/sfu/streamallocator/channelobserver.go new file mode 100644 index 00000000..f19bbb69 --- /dev/null +++ b/pkg/sfu/streamallocator/channelobserver.go @@ -0,0 +1,181 @@ +package streamallocator + +import ( + "fmt" + "time" + + "github.com/livekit/protocol/logger" +) + +// ------------------------------------------------ + +type ChannelTrend int + +const ( + ChannelTrendNeutral ChannelTrend = iota + ChannelTrendClearing + ChannelTrendCongesting +) + +func (c ChannelTrend) String() string { + switch c { + case ChannelTrendNeutral: + return "NEUTRAL" + case ChannelTrendClearing: + return "CLEARING" + case ChannelTrendCongesting: + return "CONGESTING" + default: + return fmt.Sprintf("%d", int(c)) + } +} + +// ------------------------------------------------ + +type ChannelCongestionReason int + +const ( + ChannelCongestionReasonNone ChannelCongestionReason = iota + ChannelCongestionReasonEstimate + ChannelCongestionReasonLoss +) + +func (c ChannelCongestionReason) String() string { + switch c { + case ChannelCongestionReasonNone: + return "NONE" + case ChannelCongestionReasonEstimate: + return "ESTIMATE" + case ChannelCongestionReasonLoss: + return "LOSS" + default: + return fmt.Sprintf("%d", int(c)) + } +} + +// ------------------------------------------------ + +type ChannelObserverParams struct { + Name string + EstimateRequiredSamples int + EstimateDownwardTrendThreshold float64 + EstimateCollapseValues bool + NackWindowMinDuration time.Duration + NackWindowMaxDuration time.Duration + NackRatioThreshold float64 +} + +type ChannelObserver struct { + params ChannelObserverParams + logger logger.Logger + + estimateTrend *TrendDetector + + nackWindowStartTime time.Time + packets uint32 + repeatedNacks uint32 +} + +func NewChannelObserver(params ChannelObserverParams, logger logger.Logger) *ChannelObserver { + return &ChannelObserver{ + params: params, + logger: logger, + estimateTrend: NewTrendDetector(TrendDetectorParams{ + Name: params.Name + "-estimate", + Logger: logger, + RequiredSamples: params.EstimateRequiredSamples, + DownwardTrendThreshold: params.EstimateDownwardTrendThreshold, + CollapseValues: params.EstimateCollapseValues, + }), + } +} + +func (c *ChannelObserver) SeedEstimate(estimate int64) { + c.estimateTrend.Seed(estimate) +} + +func (c *ChannelObserver) SeedNack(packets uint32, repeatedNacks uint32) { + c.packets = packets + c.repeatedNacks = repeatedNacks +} + +func (c *ChannelObserver) AddEstimate(estimate int64) { + c.estimateTrend.AddValue(estimate) +} + +func (c *ChannelObserver) AddNack(packets uint32, repeatedNacks uint32) { + if c.params.NackWindowMaxDuration != 0 && !c.nackWindowStartTime.IsZero() && time.Since(c.nackWindowStartTime) > c.params.NackWindowMaxDuration { + c.nackWindowStartTime = time.Time{} + c.packets = 0 + c.repeatedNacks = 0 + } + + // + // Start NACK monitoring window only when a repeated NACK happens. + // This allows locking tightly to when NACKs start happening and + // check if the NACKs keep adding up (potentially a sign of congestion) + // or isolated losses + // + if c.repeatedNacks == 0 && repeatedNacks != 0 { + c.nackWindowStartTime = time.Now() + } + + if !c.nackWindowStartTime.IsZero() { + c.packets += packets + c.repeatedNacks += repeatedNacks + } +} + +func (c *ChannelObserver) GetLowestEstimate() int64 { + return c.estimateTrend.GetLowest() +} + +func (c *ChannelObserver) GetHighestEstimate() int64 { + return c.estimateTrend.GetHighest() +} + +func (c *ChannelObserver) GetNackRatio() (uint32, uint32, float64) { + ratio := 0.0 + if c.packets != 0 { + ratio = float64(c.repeatedNacks) / float64(c.packets) + if ratio > 1.0 { + ratio = 1.0 + } + } + + return c.packets, c.repeatedNacks, ratio +} + +func (c *ChannelObserver) GetTrend() (ChannelTrend, ChannelCongestionReason) { + estimateDirection := c.estimateTrend.GetDirection() + packets, repeatedNacks, nackRatio := c.GetNackRatio() + + switch { + case estimateDirection == TrendDirectionDownward: + c.logger.Debugw( + "stream allocator: channel observer: estimate is trending downward", + "name", c.params.Name, + "estimate", c.estimateTrend.ToString(), + "packets", packets, + "repeatedNacks", repeatedNacks, + "ratio", nackRatio, + ) + return ChannelTrendCongesting, ChannelCongestionReasonEstimate + case c.params.NackWindowMinDuration != 0 && !c.nackWindowStartTime.IsZero() && time.Since(c.nackWindowStartTime) > c.params.NackWindowMinDuration && nackRatio > c.params.NackRatioThreshold: + c.logger.Debugw( + "stream allocator: channel observer: high rate of repeated NACKs", + "name", c.params.Name, + "estimate", c.estimateTrend.ToString(), + "packets", packets, + "repeatedNacks", repeatedNacks, + "ratio", nackRatio, + ) + return ChannelTrendCongesting, ChannelCongestionReasonLoss + case estimateDirection == TrendDirectionUpward: + return ChannelTrendClearing, ChannelCongestionReasonNone + } + + return ChannelTrendNeutral, ChannelCongestionReasonNone +} + +// ------------------------------------------------ diff --git a/pkg/sfu/prober.go b/pkg/sfu/streamallocator/prober.go similarity index 99% rename from pkg/sfu/prober.go rename to pkg/sfu/streamallocator/prober.go index 05bacd34..0e3661bf 100644 --- a/pkg/sfu/prober.go +++ b/pkg/sfu/streamallocator/prober.go @@ -103,7 +103,7 @@ // window being long(ish). But, RTT should be much shorter especially if // the subscriber peer connection of the client is able to connect to // the nearest data center. -package sfu +package streamallocator import ( "fmt" diff --git a/pkg/sfu/streamallocator.go b/pkg/sfu/streamallocator/streamallocator.go similarity index 65% rename from pkg/sfu/streamallocator.go rename to pkg/sfu/streamallocator/streamallocator.go index bf5ba725..329b3f2c 100644 --- a/pkg/sfu/streamallocator.go +++ b/pkg/sfu/streamallocator/streamallocator.go @@ -1,4 +1,4 @@ -package sfu +package streamallocator import ( "fmt" @@ -16,6 +16,8 @@ import ( "github.com/livekit/protocol/logger" "github.com/livekit/livekit-server/pkg/config" + "github.com/livekit/livekit-server/pkg/sfu" + "github.com/livekit/livekit-server/pkg/sfu/buffer" ) const ( @@ -223,12 +225,12 @@ type AddTrackParams struct { PublisherID livekit.ParticipantID } -func (s *StreamAllocator) AddTrack(downTrack *DownTrack, params AddTrackParams) { +func (s *StreamAllocator) AddTrack(downTrack *sfu.DownTrack, params AddTrackParams) { if downTrack.Kind() != webrtc.RTPCodecTypeVideo { return } - track := newTrack(downTrack, params.Source, params.IsSimulcast, params.PublisherID, s.params.Logger) + track := NewTrack(downTrack, params.Source, params.IsSimulcast, params.PublisherID, s.params.Logger) track.SetPriority(params.Priority) s.videoTracksMu.Lock() @@ -244,7 +246,7 @@ func (s *StreamAllocator) AddTrack(downTrack *DownTrack, params AddTrackParams) s.maybePostEventAllocateTrack(downTrack) } -func (s *StreamAllocator) RemoveTrack(downTrack *DownTrack) { +func (s *StreamAllocator) RemoveTrack(downTrack *sfu.DownTrack) { s.videoTracksMu.Lock() if existing := s.videoTracks[livekit.TrackID(downTrack.ID())]; existing != nil && existing.DownTrack() == downTrack { delete(s.videoTracks, livekit.TrackID(downTrack.ID())) @@ -257,7 +259,7 @@ func (s *StreamAllocator) RemoveTrack(downTrack *DownTrack) { }) } -func (s *StreamAllocator) SetTrackPriority(downTrack *DownTrack, priority uint8) { +func (s *StreamAllocator) SetTrackPriority(downTrack *sfu.DownTrack, priority uint8) { s.videoTracksMu.Lock() if track := s.videoTracks[livekit.TrackID(downTrack.ID())]; track != nil { changed := track.SetPriority(priority) @@ -280,7 +282,7 @@ func (s *StreamAllocator) resetState() { } // called when a new REMB is received (receive side bandwidth estimation) -func (s *StreamAllocator) OnREMB(downTrack *DownTrack, remb *rtcp.ReceiverEstimatedMaximumBitrate) { +func (s *StreamAllocator) OnREMB(downTrack *sfu.DownTrack, remb *rtcp.ReceiverEstimatedMaximumBitrate) { // // Channel capacity is estimated at a peer connection level. All down tracks // in the peer connection will end up calling this for a REMB report with @@ -360,7 +362,7 @@ func (s *StreamAllocator) OnREMB(downTrack *DownTrack, remb *rtcp.ReceiverEstima } // called when a new transport-cc feedback is received -func (s *StreamAllocator) OnTransportCCFeedback(downTrack *DownTrack, fb *rtcp.TransportLayerCC) { +func (s *StreamAllocator) OnTransportCCFeedback(downTrack *sfu.DownTrack, fb *rtcp.TransportLayerCC) { if s.bwe != nil { s.bwe.WriteRTCP([]rtcp.Packet{fb}, nil) } @@ -375,27 +377,27 @@ func (s *StreamAllocator) onTargetBitrateChange(bitrate int) { } // called when feeding track's layer availability changes -func (s *StreamAllocator) OnAvailableLayersChanged(downTrack *DownTrack) { +func (s *StreamAllocator) OnAvailableLayersChanged(downTrack *sfu.DownTrack) { s.maybePostEventAllocateTrack(downTrack) } // called when feeding track's bitrate measurement of any layer is available -func (s *StreamAllocator) OnBitrateAvailabilityChanged(downTrack *DownTrack) { +func (s *StreamAllocator) OnBitrateAvailabilityChanged(downTrack *sfu.DownTrack) { s.maybePostEventAllocateTrack(downTrack) } // called when feeding track's max publisher layer changes -func (s *StreamAllocator) OnMaxPublishedLayerChanged(downTrack *DownTrack) { +func (s *StreamAllocator) OnMaxPublishedLayerChanged(downTrack *sfu.DownTrack) { s.maybePostEventAllocateTrack(downTrack) } // called when subscription settings changes (muting/unmuting of track) -func (s *StreamAllocator) OnSubscriptionChanged(downTrack *DownTrack) { +func (s *StreamAllocator) OnSubscriptionChanged(downTrack *sfu.DownTrack) { s.maybePostEventAllocateTrack(downTrack) } // called when subscribed layers changes (limiting max layers) -func (s *StreamAllocator) OnSubscribedLayersChanged(downTrack *DownTrack, layers VideoLayers) { +func (s *StreamAllocator) OnSubscribedLayersChanged(downTrack *sfu.DownTrack, layers buffer.VideoLayer) { shouldPost := false s.videoTracksMu.Lock() if track := s.videoTracks[livekit.TrackID(downTrack.ID())]; track != nil { @@ -414,7 +416,7 @@ func (s *StreamAllocator) OnSubscribedLayersChanged(downTrack *DownTrack, layers } // called when forwarder finds a target layer -func (s *StreamAllocator) OnTargetLayerReached(downTrack *DownTrack) { +func (s *StreamAllocator) OnTargetLayerReached(downTrack *sfu.DownTrack) { s.postEvent(Event{ Signal: streamAllocatorSignalTargetLayerFound, TrackID: livekit.TrackID(downTrack.ID()), @@ -422,7 +424,7 @@ func (s *StreamAllocator) OnTargetLayerReached(downTrack *DownTrack) { } // called when a video DownTrack sends a packet -func (s *StreamAllocator) OnPacketsSent(downTrack *DownTrack, size int) { +func (s *StreamAllocator) OnPacketsSent(downTrack *sfu.DownTrack, size int) { s.prober.PacketsSent(size) } @@ -454,7 +456,7 @@ func (s *StreamAllocator) OnActiveChanged(isActive bool) { } } -func (s *StreamAllocator) maybePostEventAllocateTrack(downTrack *DownTrack) { +func (s *StreamAllocator) maybePostEventAllocateTrack(downTrack *sfu.DownTrack) { shouldPost := false s.videoTracksMu.Lock() if track := s.videoTracks[livekit.TrackID(downTrack.ID())]; track != nil { @@ -762,7 +764,7 @@ func (s *StreamAllocator) allocateTrack(track *Track) { if !s.params.Config.Enabled || s.state == streamAllocatorStateStable || !track.IsManaged() { update := NewStreamStateUpdate() allocation := track.AllocateOptimal(FlagAllowOvershootWhileOptimal) - if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) { + if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) { update.HandleStreamingChange(true, track) } s.maybeSendUpdate(update) @@ -780,16 +782,16 @@ func (s *StreamAllocator) allocateTrack(track *Track) { transition := track.ProvisionalAllocateGetCooperativeTransition(FlagAllowOvershootWhileDeficient) // track is currently streaming at minimum - if transition.bandwidthDelta == 0 { + if transition.BandwidthDelta == 0 { return } // downgrade, giving back bits - if transition.from.GreaterThan(transition.to) { + if transition.From.GreaterThan(transition.To) { allocation := track.ProvisionalAllocateCommit() update := NewStreamStateUpdate() - if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) { + if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) { update.HandleStreamingChange(true, track) } s.maybeSendUpdate(update) @@ -817,22 +819,22 @@ func (s *StreamAllocator) allocateTrack(track *Track) { for _, t := range minDistanceSorted { tx := t.ProvisionalAllocateGetBestWeightedTransition() - if tx.bandwidthDelta < 0 { + if tx.BandwidthDelta < 0 { contributingTracks = append(contributingTracks, t) - bandwidthAcquired += -tx.bandwidthDelta - if bandwidthAcquired >= transition.bandwidthDelta { + bandwidthAcquired += -tx.BandwidthDelta + if bandwidthAcquired >= transition.BandwidthDelta { break } } } update := NewStreamStateUpdate() - if bandwidthAcquired >= transition.bandwidthDelta { + if bandwidthAcquired >= transition.BandwidthDelta { // commit the tracks that contributed for _, t := range contributingTracks { allocation := t.ProvisionalAllocateCommit() - if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) { + if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) { update.HandleStreamingChange(true, t) } } @@ -841,9 +843,9 @@ func (s *StreamAllocator) allocateTrack(track *Track) { } // commit the track that needs change if enough could be acquired or pause not allowed - if !s.params.Config.AllowPause || bandwidthAcquired >= transition.bandwidthDelta { + if !s.params.Config.AllowPause || bandwidthAcquired >= transition.BandwidthDelta { allocation := track.ProvisionalAllocateCommit() - if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) { + if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) { update.HandleStreamingChange(true, track) } } @@ -915,11 +917,11 @@ func (s *StreamAllocator) maybeBoostDeficientTracks() { continue } - if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) { + if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) { update.HandleStreamingChange(true, track) } - availableChannelCapacity -= allocation.bandwidthDelta + availableChannelCapacity -= allocation.BandwidthDelta if availableChannelCapacity <= 0 { break } @@ -971,12 +973,12 @@ func (s *StreamAllocator) allocateAllTracks() { } allocation := track.AllocateOptimal(FlagAllowOvershootExemptTrackWhileDeficient) - if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) { + if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) { update.HandleStreamingChange(true, track) } // LK-TODO: optimistic allocation before bitrate is available will return 0. How to account for that? - availableChannelCapacity -= allocation.bandwidthRequested + availableChannelCapacity -= allocation.BandwidthRequested } if availableChannelCapacity < 0 { @@ -990,7 +992,7 @@ func (s *StreamAllocator) allocateAllTracks() { } allocation := track.Pause() - if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) { + if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) { update.HandleStreamingChange(true, track) } } @@ -1000,9 +1002,9 @@ func (s *StreamAllocator) allocateAllTracks() { track.ProvisionalAllocatePrepare() } - for spatial := int32(0); spatial <= DefaultMaxLayerSpatial; spatial++ { - for temporal := int32(0); temporal <= DefaultMaxLayerTemporal; temporal++ { - layers := VideoLayers{ + for spatial := int32(0); spatial <= buffer.DefaultMaxLayerSpatial; spatial++ { + for temporal := int32(0); temporal <= buffer.DefaultMaxLayerTemporal; temporal++ { + layers := buffer.VideoLayer{ Spatial: spatial, Temporal: temporal, } @@ -1019,7 +1021,7 @@ func (s *StreamAllocator) allocateAllTracks() { for _, track := range sorted { allocation := track.ProvisionalAllocateCommit() - if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) { + if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) { update.HandleStreamingChange(true, track) } } @@ -1172,7 +1174,7 @@ func (s *StreamAllocator) maybeProbeWithMedia() { } update := NewStreamStateUpdate() - if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) { + if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) { update.HandleStreamingChange(true, track) } s.maybeSendUpdate(update) @@ -1186,11 +1188,11 @@ func (s *StreamAllocator) maybeProbeWithPadding() { // use deficient track farthest from desired layers to find how much to probe for _, track := range s.getMaxDistanceSortedDeficient() { transition, available := track.GetNextHigherTransition(FlagAllowOvershootInProbe) - if !available || transition.bandwidthDelta < 0 { + if !available || transition.BandwidthDelta < 0 { continue } - probeRateBps := (transition.bandwidthDelta * ProbePct) / 100 + probeRateBps := (transition.BandwidthDelta * ProbePct) / 100 if probeRateBps < ProbeMinBps { probeRateBps = ProbeMinBps } @@ -1263,615 +1265,3 @@ func (s *StreamAllocator) getMaxDistanceSortedDeficient() MaxDistanceSorter { } // ------------------------------------------------ - -type StreamState int - -const ( - StreamStateActive StreamState = iota - StreamStatePaused -) - -func (s StreamState) String() string { - switch s { - case StreamStateActive: - return "active" - case StreamStatePaused: - return "paused" - default: - return "unknown" - } -} - -type StreamStateInfo struct { - ParticipantID livekit.ParticipantID - TrackID livekit.TrackID - State StreamState -} - -type StreamStateUpdate struct { - StreamStates []*StreamStateInfo -} - -func NewStreamStateUpdate() *StreamStateUpdate { - return &StreamStateUpdate{} -} - -func (s *StreamStateUpdate) HandleStreamingChange(isPaused bool, track *Track) { - if isPaused { - s.StreamStates = append(s.StreamStates, &StreamStateInfo{ - ParticipantID: track.PublisherID(), - TrackID: track.ID(), - State: StreamStatePaused, - }) - } else { - s.StreamStates = append(s.StreamStates, &StreamStateInfo{ - ParticipantID: track.PublisherID(), - TrackID: track.ID(), - State: StreamStateActive, - }) - } -} - -func (s *StreamStateUpdate) Empty() bool { - return len(s.StreamStates) == 0 -} - -// ------------------------------------------------ - -type Track struct { - downTrack *DownTrack - source livekit.TrackSource - isSimulcast bool - priority uint8 - publisherID livekit.ParticipantID - logger logger.Logger - - maxLayers VideoLayers - - totalPackets uint32 - totalRepeatedNacks uint32 - - isDirty bool - - isPaused bool -} - -func newTrack( - downTrack *DownTrack, - source livekit.TrackSource, - isSimulcast bool, - publisherID livekit.ParticipantID, - logger logger.Logger, -) *Track { - t := &Track{ - downTrack: downTrack, - source: source, - isSimulcast: isSimulcast, - publisherID: publisherID, - logger: logger, - isPaused: true, - } - t.SetPriority(0) - t.SetMaxLayers(downTrack.MaxLayers()) - - return t -} - -func (t *Track) SetDirty(isDirty bool) bool { - if t.isDirty == isDirty { - return false - } - - t.isDirty = isDirty - return true -} - -func (t *Track) SetPaused(isPaused bool) bool { - if t.isPaused == isPaused { - return false - } - - t.isPaused = isPaused - return true -} - -func (t *Track) SetPriority(priority uint8) bool { - if priority == 0 { - switch t.source { - case livekit.TrackSource_SCREEN_SHARE: - priority = PriorityDefaultScreenshare - default: - priority = PriorityDefaultVideo - } - } - - if t.priority == priority { - return false - } - - t.priority = priority - return true -} - -func (t *Track) Priority() uint8 { - return t.priority -} - -func (t *Track) DownTrack() *DownTrack { - return t.downTrack -} - -func (t *Track) IsManaged() bool { - return t.source != livekit.TrackSource_SCREEN_SHARE || t.isSimulcast -} - -func (t *Track) ID() livekit.TrackID { - return livekit.TrackID(t.downTrack.ID()) -} - -func (t *Track) PublisherID() livekit.ParticipantID { - return t.publisherID -} - -func (t *Track) SetMaxLayers(layers VideoLayers) bool { - if t.maxLayers == layers { - return false - } - - t.maxLayers = layers - return true -} - -func (t *Track) WritePaddingRTP(bytesToSend int) int { - return t.downTrack.WritePaddingRTP(bytesToSend, false) -} - -func (t *Track) AllocateOptimal(allowOvershoot bool) VideoAllocation { - return t.downTrack.AllocateOptimal(allowOvershoot) -} - -func (t *Track) ProvisionalAllocatePrepare() { - t.downTrack.ProvisionalAllocatePrepare() -} - -func (t *Track) ProvisionalAllocate(availableChannelCapacity int64, layers VideoLayers, allowPause bool, allowOvershoot bool) int64 { - return t.downTrack.ProvisionalAllocate(availableChannelCapacity, layers, allowPause, allowOvershoot) -} - -func (t *Track) ProvisionalAllocateGetCooperativeTransition(allowOvershoot bool) VideoTransition { - return t.downTrack.ProvisionalAllocateGetCooperativeTransition(allowOvershoot) -} - -func (t *Track) ProvisionalAllocateGetBestWeightedTransition() VideoTransition { - return t.downTrack.ProvisionalAllocateGetBestWeightedTransition() -} - -func (t *Track) ProvisionalAllocateCommit() VideoAllocation { - return t.downTrack.ProvisionalAllocateCommit() -} - -func (t *Track) AllocateNextHigher(availableChannelCapacity int64, allowOvershoot bool) (VideoAllocation, bool) { - return t.downTrack.AllocateNextHigher(availableChannelCapacity, allowOvershoot) -} - -func (t *Track) GetNextHigherTransition(allowOvershoot bool) (VideoTransition, bool) { - return t.downTrack.GetNextHigherTransition(allowOvershoot) -} - -func (t *Track) Pause() VideoAllocation { - return t.downTrack.Pause() -} - -func (t *Track) IsDeficient() bool { - return t.downTrack.IsDeficient() -} - -func (t *Track) BandwidthRequested() int64 { - return t.downTrack.BandwidthRequested() -} - -func (t *Track) DistanceToDesired() float64 { - return t.downTrack.DistanceToDesired() -} - -func (t *Track) GetNackDelta() (uint32, uint32) { - totalPackets, totalRepeatedNacks := t.downTrack.GetNackStats() - - packetDelta := totalPackets - t.totalPackets - t.totalPackets = totalPackets - - nackDelta := totalRepeatedNacks - t.totalRepeatedNacks - t.totalRepeatedNacks = totalRepeatedNacks - - return packetDelta, nackDelta -} - -// ------------------------------------------------ - -type TrackSorter []*Track - -func (t TrackSorter) Len() int { - return len(t) -} - -func (t TrackSorter) Swap(i, j int) { - t[i], t[j] = t[j], t[i] -} - -func (t TrackSorter) Less(i, j int) bool { - // - // TrackSorter is used to allocate layer-by-layer. - // So, higher priority track should come earlier so that it gets an earlier shot at each layer - // - if t[i].priority != t[j].priority { - return t[i].priority > t[j].priority - } - - if t[i].maxLayers.Spatial != t[j].maxLayers.Spatial { - return t[i].maxLayers.Spatial > t[j].maxLayers.Spatial - } - - return t[i].maxLayers.Temporal > t[j].maxLayers.Temporal -} - -// ------------------------------------------------ - -type MaxDistanceSorter []*Track - -func (m MaxDistanceSorter) Len() int { - return len(m) -} - -func (m MaxDistanceSorter) Swap(i, j int) { - m[i], m[j] = m[j], m[i] -} - -func (m MaxDistanceSorter) Less(i, j int) bool { - // - // MaxDistanceSorter is used to find a deficient track to use for probing during recovery from congestion. - // So, higher priority track should come earlier so that they have a chance to recover sooner. - // - if m[i].priority != m[j].priority { - return m[i].priority > m[j].priority - } - - return m[i].DistanceToDesired() > m[j].DistanceToDesired() -} - -// ------------------------------------------------ - -type MinDistanceSorter []*Track - -func (m MinDistanceSorter) Len() int { - return len(m) -} - -func (m MinDistanceSorter) Swap(i, j int) { - m[i], m[j] = m[j], m[i] -} - -func (m MinDistanceSorter) Less(i, j int) bool { - // - // MinDistanceSorter is used to find excess bandwidth in cooperative allocation. - // So, lower priority track should come earlier so that they contribute bandwidth to higher priority tracks. - // - if m[i].priority != m[j].priority { - return m[i].priority < m[j].priority - } - - return m[i].DistanceToDesired() < m[j].DistanceToDesired() -} - -// ------------------------------------------------ - -type ChannelTrend int - -const ( - ChannelTrendNeutral ChannelTrend = iota - ChannelTrendClearing - ChannelTrendCongesting -) - -func (c ChannelTrend) String() string { - switch c { - case ChannelTrendNeutral: - return "NEUTRAL" - case ChannelTrendClearing: - return "CLEARING" - case ChannelTrendCongesting: - return "CONGESTING" - default: - return fmt.Sprintf("%d", int(c)) - } -} - -type ChannelCongestionReason int - -const ( - ChannelCongestionReasonNone ChannelCongestionReason = iota - ChannelCongestionReasonEstimate - ChannelCongestionReasonLoss -) - -func (c ChannelCongestionReason) String() string { - switch c { - case ChannelCongestionReasonNone: - return "NONE" - case ChannelCongestionReasonEstimate: - return "ESTIMATE" - case ChannelCongestionReasonLoss: - return "LOSS" - default: - return fmt.Sprintf("%d", int(c)) - } -} - -type ChannelObserverParams struct { - Name string - EstimateRequiredSamples int - EstimateDownwardTrendThreshold float64 - EstimateCollapseValues bool - NackWindowMinDuration time.Duration - NackWindowMaxDuration time.Duration - NackRatioThreshold float64 -} - -type ChannelObserver struct { - params ChannelObserverParams - logger logger.Logger - - estimateTrend *TrendDetector - - nackWindowStartTime time.Time - packets uint32 - repeatedNacks uint32 -} - -func NewChannelObserver(params ChannelObserverParams, logger logger.Logger) *ChannelObserver { - return &ChannelObserver{ - params: params, - logger: logger, - estimateTrend: NewTrendDetector(TrendDetectorParams{ - Name: params.Name + "-estimate", - Logger: logger, - RequiredSamples: params.EstimateRequiredSamples, - DownwardTrendThreshold: params.EstimateDownwardTrendThreshold, - CollapseValues: params.EstimateCollapseValues, - }), - } -} - -func (c *ChannelObserver) SeedEstimate(estimate int64) { - c.estimateTrend.Seed(estimate) -} - -func (c *ChannelObserver) SeedNack(packets uint32, repeatedNacks uint32) { - c.packets = packets - c.repeatedNacks = repeatedNacks -} - -func (c *ChannelObserver) AddEstimate(estimate int64) { - c.estimateTrend.AddValue(estimate) -} - -func (c *ChannelObserver) AddNack(packets uint32, repeatedNacks uint32) { - if c.params.NackWindowMaxDuration != 0 && !c.nackWindowStartTime.IsZero() && time.Since(c.nackWindowStartTime) > c.params.NackWindowMaxDuration { - c.nackWindowStartTime = time.Time{} - c.packets = 0 - c.repeatedNacks = 0 - } - - // - // Start NACK monitoring window only when a repeated NACK happens. - // This allows locking tightly to when NACKs start happening and - // check if the NACKs keep adding up (potentially a sign of congestion) - // or isolated losses - // - if c.repeatedNacks == 0 && repeatedNacks != 0 { - c.nackWindowStartTime = time.Now() - } - - if !c.nackWindowStartTime.IsZero() { - c.packets += packets - c.repeatedNacks += repeatedNacks - } -} - -func (c *ChannelObserver) GetLowestEstimate() int64 { - return c.estimateTrend.GetLowest() -} - -func (c *ChannelObserver) GetHighestEstimate() int64 { - return c.estimateTrend.GetHighest() -} - -func (c *ChannelObserver) GetNackRatio() (uint32, uint32, float64) { - ratio := 0.0 - if c.packets != 0 { - ratio = float64(c.repeatedNacks) / float64(c.packets) - if ratio > 1.0 { - ratio = 1.0 - } - } - - return c.packets, c.repeatedNacks, ratio -} - -func (c *ChannelObserver) GetTrend() (ChannelTrend, ChannelCongestionReason) { - estimateDirection := c.estimateTrend.GetDirection() - packets, repeatedNacks, nackRatio := c.GetNackRatio() - - switch { - case estimateDirection == TrendDirectionDownward: - c.logger.Debugw( - "stream allocator: channel observer: estimate is trending downward", - "name", c.params.Name, - "estimate", c.estimateTrend.ToString(), - "packets", packets, - "repeatedNacks", repeatedNacks, - "ratio", nackRatio, - ) - return ChannelTrendCongesting, ChannelCongestionReasonEstimate - case c.params.NackWindowMinDuration != 0 && !c.nackWindowStartTime.IsZero() && time.Since(c.nackWindowStartTime) > c.params.NackWindowMinDuration && nackRatio > c.params.NackRatioThreshold: - c.logger.Debugw( - "stream allocator: channel observer: high rate of repeated NACKs", - "name", c.params.Name, - "estimate", c.estimateTrend.ToString(), - "packets", packets, - "repeatedNacks", repeatedNacks, - "ratio", nackRatio, - ) - return ChannelTrendCongesting, ChannelCongestionReasonLoss - case estimateDirection == TrendDirectionUpward: - return ChannelTrendClearing, ChannelCongestionReasonNone - } - - return ChannelTrendNeutral, ChannelCongestionReasonNone -} - -// ------------------------------------------------ - -type TrendDirection int - -const ( - TrendDirectionNeutral TrendDirection = iota - TrendDirectionUpward - TrendDirectionDownward -) - -func (t TrendDirection) String() string { - switch t { - case TrendDirectionNeutral: - return "NEUTRAL" - case TrendDirectionUpward: - return "UPWARD" - case TrendDirectionDownward: - return "DOWNWARD" - default: - return fmt.Sprintf("%d", int(t)) - } -} - -type TrendDetectorParams struct { - Name string - Logger logger.Logger - RequiredSamples int - DownwardTrendThreshold float64 - CollapseValues bool -} - -type TrendDetector struct { - params TrendDetectorParams - - startTime time.Time - numSamples int - values []int64 - lowestValue int64 - highestValue int64 - - direction TrendDirection -} - -func NewTrendDetector(params TrendDetectorParams) *TrendDetector { - return &TrendDetector{ - params: params, - startTime: time.Now(), - direction: TrendDirectionNeutral, - } -} - -func (t *TrendDetector) Seed(value int64) { - if len(t.values) != 0 { - return - } - - t.values = append(t.values, value) -} - -func (t *TrendDetector) AddValue(value int64) { - t.numSamples++ - if t.lowestValue == 0 || value < t.lowestValue { - t.lowestValue = value - } - if value > t.highestValue { - t.highestValue = value - } - - // ignore duplicate values - if t.params.CollapseValues && len(t.values) != 0 && t.values[len(t.values)-1] == value { - return - } - - if len(t.values) == t.params.RequiredSamples { - t.values = t.values[1:] - } - t.values = append(t.values, value) - - t.updateDirection() -} - -func (t *TrendDetector) GetLowest() int64 { - return t.lowestValue -} - -func (t *TrendDetector) GetHighest() int64 { - return t.highestValue -} - -func (t *TrendDetector) GetValues() []int64 { - return t.values -} - -func (t *TrendDetector) GetDirection() TrendDirection { - return t.direction -} - -func (t *TrendDetector) ToString() string { - now := time.Now() - elapsed := now.Sub(t.startTime).Seconds() - str := fmt.Sprintf("n: %s", t.params.Name) - str += fmt.Sprintf(", t: %+v|%+v|%.2fs", t.startTime.Format(time.UnixDate), now.Format(time.UnixDate), elapsed) - str += fmt.Sprintf(", v: %d|%d|%d|%+v|%.2f", t.numSamples, t.lowestValue, t.highestValue, t.values, kendallsTau(t.values)) - return str -} - -func (t *TrendDetector) updateDirection() { - if len(t.values) < t.params.RequiredSamples { - t.direction = TrendDirectionNeutral - return - } - - // using Kendall's Tau to find trend - kt := kendallsTau(t.values) - - t.direction = TrendDirectionNeutral - switch { - case kt > 0: - t.direction = TrendDirectionUpward - case kt < t.params.DownwardTrendThreshold: - t.direction = TrendDirectionDownward - } -} - -// ------------------------------------------------ - -func kendallsTau(values []int64) float64 { - concordantPairs := 0 - discordantPairs := 0 - - for i := 0; i < len(values)-1; i++ { - for j := i + 1; j < len(values); j++ { - if values[i] < values[j] { - concordantPairs++ - } else if values[i] > values[j] { - discordantPairs++ - } - } - } - - if (concordantPairs + discordantPairs) == 0 { - return 0.0 - } - - return (float64(concordantPairs) - float64(discordantPairs)) / (float64(concordantPairs) + float64(discordantPairs)) -} diff --git a/pkg/sfu/streamallocator/streamstateupdate.go b/pkg/sfu/streamallocator/streamstateupdate.go new file mode 100644 index 00000000..e5b3156f --- /dev/null +++ b/pkg/sfu/streamallocator/streamstateupdate.go @@ -0,0 +1,63 @@ +package streamallocator + +import ( + "github.com/livekit/protocol/livekit" +) + +// ------------------------------------------------ + +type StreamState int + +const ( + StreamStateActive StreamState = iota + StreamStatePaused +) + +func (s StreamState) String() string { + switch s { + case StreamStateActive: + return "active" + case StreamStatePaused: + return "paused" + default: + return "unknown" + } +} + +// ------------------------------------------------ + +type StreamStateInfo struct { + ParticipantID livekit.ParticipantID + TrackID livekit.TrackID + State StreamState +} + +type StreamStateUpdate struct { + StreamStates []*StreamStateInfo +} + +func NewStreamStateUpdate() *StreamStateUpdate { + return &StreamStateUpdate{} +} + +func (s *StreamStateUpdate) HandleStreamingChange(isPaused bool, track *Track) { + if isPaused { + s.StreamStates = append(s.StreamStates, &StreamStateInfo{ + ParticipantID: track.PublisherID(), + TrackID: track.ID(), + State: StreamStatePaused, + }) + } else { + s.StreamStates = append(s.StreamStates, &StreamStateInfo{ + ParticipantID: track.PublisherID(), + TrackID: track.ID(), + State: StreamStateActive, + }) + } +} + +func (s *StreamStateUpdate) Empty() bool { + return len(s.StreamStates) == 0 +} + +// ------------------------------------------------ diff --git a/pkg/sfu/streamallocator/track.go b/pkg/sfu/streamallocator/track.go new file mode 100644 index 00000000..70df5499 --- /dev/null +++ b/pkg/sfu/streamallocator/track.go @@ -0,0 +1,255 @@ +package streamallocator + +import ( + "github.com/livekit/protocol/livekit" + "github.com/livekit/protocol/logger" + + "github.com/livekit/livekit-server/pkg/sfu" + "github.com/livekit/livekit-server/pkg/sfu/buffer" +) + +type Track struct { + downTrack *sfu.DownTrack + source livekit.TrackSource + isSimulcast bool + priority uint8 + publisherID livekit.ParticipantID + logger logger.Logger + + maxLayers buffer.VideoLayer + + totalPackets uint32 + totalRepeatedNacks uint32 + + isDirty bool + + isPaused bool +} + +func NewTrack( + downTrack *sfu.DownTrack, + source livekit.TrackSource, + isSimulcast bool, + publisherID livekit.ParticipantID, + logger logger.Logger, +) *Track { + t := &Track{ + downTrack: downTrack, + source: source, + isSimulcast: isSimulcast, + publisherID: publisherID, + logger: logger, + isPaused: true, + } + t.SetPriority(0) + t.SetMaxLayers(downTrack.MaxLayers()) + + return t +} + +func (t *Track) SetDirty(isDirty bool) bool { + if t.isDirty == isDirty { + return false + } + + t.isDirty = isDirty + return true +} + +func (t *Track) SetPaused(isPaused bool) bool { + if t.isPaused == isPaused { + return false + } + + t.isPaused = isPaused + return true +} + +func (t *Track) SetPriority(priority uint8) bool { + if priority == 0 { + switch t.source { + case livekit.TrackSource_SCREEN_SHARE: + priority = PriorityDefaultScreenshare + default: + priority = PriorityDefaultVideo + } + } + + if t.priority == priority { + return false + } + + t.priority = priority + return true +} + +func (t *Track) Priority() uint8 { + return t.priority +} + +func (t *Track) DownTrack() *sfu.DownTrack { + return t.downTrack +} + +func (t *Track) IsManaged() bool { + return t.source != livekit.TrackSource_SCREEN_SHARE || t.isSimulcast +} + +func (t *Track) ID() livekit.TrackID { + return livekit.TrackID(t.downTrack.ID()) +} + +func (t *Track) PublisherID() livekit.ParticipantID { + return t.publisherID +} + +func (t *Track) SetMaxLayers(layers buffer.VideoLayer) bool { + if t.maxLayers == layers { + return false + } + + t.maxLayers = layers + return true +} + +func (t *Track) WritePaddingRTP(bytesToSend int) int { + return t.downTrack.WritePaddingRTP(bytesToSend, false) +} + +func (t *Track) AllocateOptimal(allowOvershoot bool) sfu.VideoAllocation { + return t.downTrack.AllocateOptimal(allowOvershoot) +} + +func (t *Track) ProvisionalAllocatePrepare() { + t.downTrack.ProvisionalAllocatePrepare() +} + +func (t *Track) ProvisionalAllocate(availableChannelCapacity int64, layers buffer.VideoLayer, allowPause bool, allowOvershoot bool) int64 { + return t.downTrack.ProvisionalAllocate(availableChannelCapacity, layers, allowPause, allowOvershoot) +} + +func (t *Track) ProvisionalAllocateGetCooperativeTransition(allowOvershoot bool) sfu.VideoTransition { + return t.downTrack.ProvisionalAllocateGetCooperativeTransition(allowOvershoot) +} + +func (t *Track) ProvisionalAllocateGetBestWeightedTransition() sfu.VideoTransition { + return t.downTrack.ProvisionalAllocateGetBestWeightedTransition() +} + +func (t *Track) ProvisionalAllocateCommit() sfu.VideoAllocation { + return t.downTrack.ProvisionalAllocateCommit() +} + +func (t *Track) AllocateNextHigher(availableChannelCapacity int64, allowOvershoot bool) (sfu.VideoAllocation, bool) { + return t.downTrack.AllocateNextHigher(availableChannelCapacity, allowOvershoot) +} + +func (t *Track) GetNextHigherTransition(allowOvershoot bool) (sfu.VideoTransition, bool) { + return t.downTrack.GetNextHigherTransition(allowOvershoot) +} + +func (t *Track) Pause() sfu.VideoAllocation { + return t.downTrack.Pause() +} + +func (t *Track) IsDeficient() bool { + return t.downTrack.IsDeficient() +} + +func (t *Track) BandwidthRequested() int64 { + return t.downTrack.BandwidthRequested() +} + +func (t *Track) DistanceToDesired() float64 { + return t.downTrack.DistanceToDesired() +} + +func (t *Track) GetNackDelta() (uint32, uint32) { + totalPackets, totalRepeatedNacks := t.downTrack.GetNackStats() + + packetDelta := totalPackets - t.totalPackets + t.totalPackets = totalPackets + + nackDelta := totalRepeatedNacks - t.totalRepeatedNacks + t.totalRepeatedNacks = totalRepeatedNacks + + return packetDelta, nackDelta +} + +// ------------------------------------------------ + +type TrackSorter []*Track + +func (t TrackSorter) Len() int { + return len(t) +} + +func (t TrackSorter) Swap(i, j int) { + t[i], t[j] = t[j], t[i] +} + +func (t TrackSorter) Less(i, j int) bool { + // + // TrackSorter is used to allocate layer-by-layer. + // So, higher priority track should come earlier so that it gets an earlier shot at each layer + // + if t[i].priority != t[j].priority { + return t[i].priority > t[j].priority + } + + if t[i].maxLayers.Spatial != t[j].maxLayers.Spatial { + return t[i].maxLayers.Spatial > t[j].maxLayers.Spatial + } + + return t[i].maxLayers.Temporal > t[j].maxLayers.Temporal +} + +// ------------------------------------------------ + +type MaxDistanceSorter []*Track + +func (m MaxDistanceSorter) Len() int { + return len(m) +} + +func (m MaxDistanceSorter) Swap(i, j int) { + m[i], m[j] = m[j], m[i] +} + +func (m MaxDistanceSorter) Less(i, j int) bool { + // + // MaxDistanceSorter is used to find a deficient track to use for probing during recovery from congestion. + // So, higher priority track should come earlier so that they have a chance to recover sooner. + // + if m[i].priority != m[j].priority { + return m[i].priority > m[j].priority + } + + return m[i].DistanceToDesired() > m[j].DistanceToDesired() +} + +// ------------------------------------------------ + +type MinDistanceSorter []*Track + +func (m MinDistanceSorter) Len() int { + return len(m) +} + +func (m MinDistanceSorter) Swap(i, j int) { + m[i], m[j] = m[j], m[i] +} + +func (m MinDistanceSorter) Less(i, j int) bool { + // + // MinDistanceSorter is used to find excess bandwidth in cooperative allocation. + // So, lower priority track should come earlier so that they contribute bandwidth to higher priority tracks. + // + if m[i].priority != m[j].priority { + return m[i].priority < m[j].priority + } + + return m[i].DistanceToDesired() < m[j].DistanceToDesired() +} + +// ------------------------------------------------ diff --git a/pkg/sfu/streamallocator/trenddetector.go b/pkg/sfu/streamallocator/trenddetector.go new file mode 100644 index 00000000..959b7d9d --- /dev/null +++ b/pkg/sfu/streamallocator/trenddetector.go @@ -0,0 +1,157 @@ +package streamallocator + +import ( + "fmt" + "time" + + "github.com/livekit/protocol/logger" +) + +// ------------------------------------------------ + +type TrendDirection int + +const ( + TrendDirectionNeutral TrendDirection = iota + TrendDirectionUpward + TrendDirectionDownward +) + +func (t TrendDirection) String() string { + switch t { + case TrendDirectionNeutral: + return "NEUTRAL" + case TrendDirectionUpward: + return "UPWARD" + case TrendDirectionDownward: + return "DOWNWARD" + default: + return fmt.Sprintf("%d", int(t)) + } +} + +// ------------------------------------------------ + +type TrendDetectorParams struct { + Name string + Logger logger.Logger + RequiredSamples int + DownwardTrendThreshold float64 + CollapseValues bool +} + +type TrendDetector struct { + params TrendDetectorParams + + startTime time.Time + numSamples int + values []int64 + lowestValue int64 + highestValue int64 + + direction TrendDirection +} + +func NewTrendDetector(params TrendDetectorParams) *TrendDetector { + return &TrendDetector{ + params: params, + startTime: time.Now(), + direction: TrendDirectionNeutral, + } +} + +func (t *TrendDetector) Seed(value int64) { + if len(t.values) != 0 { + return + } + + t.values = append(t.values, value) +} + +func (t *TrendDetector) AddValue(value int64) { + t.numSamples++ + if t.lowestValue == 0 || value < t.lowestValue { + t.lowestValue = value + } + if value > t.highestValue { + t.highestValue = value + } + + // ignore duplicate values + if t.params.CollapseValues && len(t.values) != 0 && t.values[len(t.values)-1] == value { + return + } + + if len(t.values) == t.params.RequiredSamples { + t.values = t.values[1:] + } + t.values = append(t.values, value) + + t.updateDirection() +} + +func (t *TrendDetector) GetLowest() int64 { + return t.lowestValue +} + +func (t *TrendDetector) GetHighest() int64 { + return t.highestValue +} + +func (t *TrendDetector) GetValues() []int64 { + return t.values +} + +func (t *TrendDetector) GetDirection() TrendDirection { + return t.direction +} + +func (t *TrendDetector) ToString() string { + now := time.Now() + elapsed := now.Sub(t.startTime).Seconds() + str := fmt.Sprintf("n: %s", t.params.Name) + str += fmt.Sprintf(", t: %+v|%+v|%.2fs", t.startTime.Format(time.UnixDate), now.Format(time.UnixDate), elapsed) + str += fmt.Sprintf(", v: %d|%d|%d|%+v|%.2f", t.numSamples, t.lowestValue, t.highestValue, t.values, kendallsTau(t.values)) + return str +} + +func (t *TrendDetector) updateDirection() { + if len(t.values) < t.params.RequiredSamples { + t.direction = TrendDirectionNeutral + return + } + + // using Kendall's Tau to find trend + kt := kendallsTau(t.values) + + t.direction = TrendDirectionNeutral + switch { + case kt > 0: + t.direction = TrendDirectionUpward + case kt < t.params.DownwardTrendThreshold: + t.direction = TrendDirectionDownward + } +} + +// ------------------------------------------------ + +func kendallsTau(values []int64) float64 { + concordantPairs := 0 + discordantPairs := 0 + + for i := 0; i < len(values)-1; i++ { + for j := i + 1; j < len(values); j++ { + if values[i] < values[j] { + concordantPairs++ + } else if values[i] > values[j] { + discordantPairs++ + } + } + } + + if (concordantPairs + discordantPairs) == 0 { + return 0.0 + } + + return (float64(concordantPairs) - float64(discordantPairs)) / (float64(concordantPairs) + float64(discordantPairs)) +} diff --git a/pkg/sfu/streamtrackermanager.go b/pkg/sfu/streamtrackermanager.go index 62c4f82e..abd4a955 100644 --- a/pkg/sfu/streamtrackermanager.go +++ b/pkg/sfu/streamtrackermanager.go @@ -36,14 +36,14 @@ type StreamTrackerManager struct { maxPublishedLayer int32 maxTemporalLayerSeen int32 - trackers [DefaultMaxLayerSpatial + 1]*streamtracker.StreamTracker + trackers [buffer.DefaultMaxLayerSpatial + 1]*streamtracker.StreamTracker availableLayers []int32 maxExpectedLayer int32 paused bool senderReportMu sync.RWMutex - senderReports [DefaultMaxLayerSpatial + 1]*buffer.RTCPSenderReportDataExt + senderReports [buffer.DefaultMaxLayerSpatial + 1]*buffer.RTCPSenderReportDataExt closed core.Fuse @@ -61,8 +61,8 @@ func NewStreamTrackerManager( logger: logger, trackInfo: trackInfo, isSVC: isSVC, - maxPublishedLayer: InvalidLayerSpatial, - maxTemporalLayerSeen: InvalidLayerTemporal, + maxPublishedLayer: buffer.InvalidLayerSpatial, + maxTemporalLayerSeen: buffer.InvalidLayerTemporal, clockRate: clockRate, closed: core.NewFuse(), } @@ -295,12 +295,12 @@ func (s *StreamTrackerManager) DistanceToDesired() float64 { al, brs := s.getLayeredBitrateLocked() - maxLayers := InvalidLayers + maxLayers := buffer.InvalidLayers done: for s := int32(len(brs)) - 1; s >= 0; s-- { for t := int32(len(brs[0])) - 1; t >= 0; t-- { if brs[s][t] != 0 { - maxLayers = VideoLayers{ + maxLayers = buffer.VideoLayer{ Spatial: s, Temporal: t, } @@ -319,7 +319,7 @@ done: adjustedMaxLayers := maxLayers if !maxLayers.IsValid() { - adjustedMaxLayers = VideoLayers{Spatial: 0, Temporal: 0} + adjustedMaxLayers = buffer.VideoLayer{Spatial: 0, Temporal: 0} } distance := @@ -351,7 +351,7 @@ func (s *StreamTrackerManager) getLayeredBitrateLocked() ([]int32, Bitrates) { for i, tracker := range s.trackers { if tracker != nil { - tls := make([]int64, DefaultMaxLayerTemporal+1) + tls := make([]int64, buffer.DefaultMaxLayerTemporal+1) if s.hasSpatialLayerLocked(int32(i)) { tls = tracker.BitrateTemporalCumulative() } @@ -428,12 +428,12 @@ func (s *StreamTrackerManager) addAvailableLayer(layer int32) { func (s *StreamTrackerManager) removeAvailableLayer(layer int32) { s.lock.Lock() - prevMaxLayer := InvalidLayerSpatial + prevMaxLayer := buffer.InvalidLayerSpatial if len(s.availableLayers) > 0 { prevMaxLayer = s.availableLayers[len(s.availableLayers)-1] } - newLayers := make([]int32, 0, DefaultMaxLayerSpatial+1) + newLayers := make([]int32, 0, buffer.DefaultMaxLayerSpatial+1) for _, l := range s.availableLayers { if l != layer { newLayers = append(newLayers, l) @@ -448,7 +448,7 @@ func (s *StreamTrackerManager) removeAvailableLayer(layer int32) { "availableLayers", newLayers, ) - curMaxLayer := InvalidLayerSpatial + curMaxLayer := buffer.InvalidLayerSpatial if len(s.availableLayers) > 0 { curMaxLayer = s.availableLayers[len(s.availableLayers)-1] } @@ -466,7 +466,7 @@ func (s *StreamTrackerManager) removeAvailableLayer(layer int32) { } func (s *StreamTrackerManager) maxExpectedLayerFromTrackInfo() { - s.maxExpectedLayer = InvalidLayerSpatial + s.maxExpectedLayer = buffer.InvalidLayerSpatial for _, layer := range s.trackInfo.Layers { spatialLayer := buffer.VideoQualityToSpatialLayer(layer.Quality, s.trackInfo) if spatialLayer > s.maxExpectedLayer { @@ -547,7 +547,7 @@ func (s *StreamTrackerManager) GetMaxTemporalLayerSeen() int32 { } func (s *StreamTrackerManager) updateMaxTemporalLayerSeen(brs Bitrates) { - maxTemporalLayerSeen := InvalidLayerTemporal + maxTemporalLayerSeen := buffer.InvalidLayerTemporal done: for t := int32(len(brs[0])) - 1; t >= 0; t-- { for s := int32(len(brs)) - 1; s >= 0; s-- { diff --git a/pkg/sfu/videolayerselector.go b/pkg/sfu/videolayerselector.go index ec08065a..1368bc87 100644 --- a/pkg/sfu/videolayerselector.go +++ b/pkg/sfu/videolayerselector.go @@ -11,7 +11,7 @@ import ( type targetLayer struct { Target int - Layer VideoLayers + Layer buffer.VideoLayer } type DDVideoLayerSelector struct { @@ -22,7 +22,7 @@ type DDVideoLayerSelector struct { // expectKeyFrame bool decodeTargetLayer []targetLayer - layer VideoLayers + layer buffer.VideoLayer activeDecodeTargetsBitmask *uint32 structure *dd.FrameDependencyStructure } @@ -30,7 +30,7 @@ type DDVideoLayerSelector struct { func NewDDVideoLayerSelector(logger logger.Logger) *DDVideoLayerSelector { return &DDVideoLayerSelector{ logger: logger, - layer: VideoLayers{Spatial: 2, Temporal: 2}, + layer: buffer.VideoLayer{Spatial: 2, Temporal: 2}, } } @@ -48,7 +48,7 @@ func (s *DDVideoLayerSelector) Select(expPkt *buffer.ExtPacket, tp *TranslationP } // forward all packets before locking - if s.layer == InvalidLayers { + if s.layer == buffer.InvalidLayers { return true } @@ -122,8 +122,8 @@ func (s *DDVideoLayerSelector) Select(expPkt *buffer.ExtPacket, tp *TranslationP return true } -func (s *DDVideoLayerSelector) SelectLayer(layer VideoLayers) { - // layer = VideoLayers{1, 1} +func (s *DDVideoLayerSelector) SelectLayer(layer buffer.VideoLayer) { + // layer = buffer.VideoLayer{1, 1} s.layer = layer activeBitMask := uint32(0) var maxSpatial, maxTemporal int32 @@ -152,7 +152,7 @@ func (s *DDVideoLayerSelector) updateDependencyStructure(structure *dd.FrameDepe s.decodeTargetLayer = s.decodeTargetLayer[:0] for target := 0; target < structure.NumDecodeTargets; target++ { - layer := VideoLayers{Spatial: 0, Temporal: 0} + layer := buffer.VideoLayer{Spatial: 0, Temporal: 0} for _, t := range structure.Templates { if t.DecodeTargetIndications[target] != dd.DecodeTargetNotPresent { if layer.Spatial < int32(t.SpatialId) {