From 7948fabce00579a0f6a0d0b4901ca46539a518e4 Mon Sep 17 00:00:00 2001 From: Raja Subramanian Date: Wed, 8 Dec 2021 21:56:07 +0530 Subject: [PATCH] StreamAllocator tweaks (#240) * WIP commit * test padding only with a gap scenario * Debug * Fix video corruption, need buffer to include payload and translated header size * Revert incorrect change * Fix VP8 translation to return buffer with proper length * Restore 7-bit mode * WIP commit * Clean up * More clean up and tests compiling again * Fix tests --- pkg/sfu/downtrack.go | 62 ++-- pkg/sfu/forwarder.go | 402 ++++++++++++++++---------- pkg/sfu/forwarder_test.go | 560 ++++++++++++++++++++++++------------- pkg/sfu/streamallocator.go | 107 +++---- 4 files changed, 712 insertions(+), 419 deletions(-) diff --git a/pkg/sfu/downtrack.go b/pkg/sfu/downtrack.go index 573a71d9..b00406d2 100644 --- a/pkg/sfu/downtrack.go +++ b/pkg/sfu/downtrack.go @@ -119,7 +119,7 @@ type DownTrack struct { onSubscriptionChanged func(dt *DownTrack) // max layer change callback - onSubscribedLayersChanged func(dt *DownTrack, layers VideoLayers) + onSubscribedLayersChanged func(dt *DownTrack, layers VideoLayers, layerPref LayerPreference) // packet sent callback onPacketSent []func(dt *DownTrack, size int) @@ -259,15 +259,16 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) error { return err } - payload := &extPkt.Packet.Payload + payload := extPkt.Packet.Payload if tp.vp8 != nil { incomingVP8, _ := extPkt.Payload.(buffer.VP8) + outbuf := &payload if incomingVP8.HeaderSize != tp.vp8.header.HeaderSize { pool = PacketFactory.Get().(*[]byte) - payload = pool + outbuf = pool } - err = d.translateVP8PacketTo(&extPkt.Packet, &incomingVP8, tp.vp8.header, payload) + payload, err = d.translateVP8PacketTo(&extPkt.Packet, &incomingVP8, tp.vp8.header, outbuf) if err != nil { d.pktsDropped.add(1) return err @@ -287,17 +288,17 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) error { return err } - _, err = d.writeStream.WriteRTP(hdr, *payload) + _, err = d.writeStream.WriteRTP(hdr, payload) if err == nil { for _, f := range d.onPacketSent { - f(d, hdr.MarshalSize()+len(*payload)) + f(d, hdr.MarshalSize()+len(payload)) } } else { d.pktsDropped.add(1) } // LK-TODO maybe include RTP header size also - d.UpdateStats(uint32(len(*payload))) + d.UpdateStats(uint32(len(payload))) return err } @@ -428,24 +429,24 @@ func (d *DownTrack) Close() { } func (d *DownTrack) SetMaxSpatialLayer(spatialLayer int32) { - changed, maxLayers := d.forwarder.SetMaxSpatialLayer(spatialLayer) + changed, maxLayers, layerPref := d.forwarder.SetMaxSpatialLayer(spatialLayer) if !changed { return } if d.onSubscribedLayersChanged != nil { - d.onSubscribedLayersChanged(d, maxLayers) + d.onSubscribedLayersChanged(d, maxLayers, layerPref) } } func (d *DownTrack) SetMaxTemporalLayer(temporalLayer int32) { - changed, maxLayers := d.forwarder.SetMaxTemporalLayer(temporalLayer) + changed, maxLayers, layerPref := d.forwarder.SetMaxTemporalLayer(temporalLayer) if !changed { return } if d.onSubscribedLayersChanged != nil { - d.onSubscribedLayersChanged(d, maxLayers) + d.onSubscribedLayersChanged(d, maxLayers, layerPref) } } @@ -453,6 +454,10 @@ func (d *DownTrack) MaxLayers() VideoLayers { return d.forwarder.MaxLayers() } +func (d *DownTrack) GetLayerPreference() LayerPreference { + return d.forwarder.GetLayerPreference() +} + func (d *DownTrack) GetForwardingStatus() ForwardingStatus { return d.forwarder.GetForwardingStatus() } @@ -500,7 +505,7 @@ func (d *DownTrack) OnSubscriptionChanged(fn func(dt *DownTrack)) { d.onSubscriptionChanged = fn } -func (d *DownTrack) OnSubscribedLayersChanged(fn func(dt *DownTrack, layers VideoLayers)) { +func (d *DownTrack) OnSubscribedLayersChanged(fn func(dt *DownTrack, layers VideoLayers, layerPref LayerPreference)) { d.onSubscribedLayersChanged = fn } @@ -508,28 +513,24 @@ func (d *DownTrack) OnPacketSent(fn func(dt *DownTrack, size int)) { d.onPacketSent = append(d.onPacketSent, fn) } -func (d *DownTrack) Allocate(availableChannelCapacity int64) VideoAllocationResult { +func (d *DownTrack) Allocate(availableChannelCapacity int64) VideoAllocation { return d.forwarder.Allocate(availableChannelCapacity, d.receiver.GetBitrateTemporalCumulative()) } -func (d *DownTrack) TryAllocate(additionalChannelCapacity int64) VideoAllocationResult { +func (d *DownTrack) TryAllocate(additionalChannelCapacity int64) VideoAllocation { return d.forwarder.TryAllocate(additionalChannelCapacity, d.receiver.GetBitrateTemporalCumulative()) } -func (d *DownTrack) FinalizeAllocate() { - d.forwarder.FinalizeAllocate(d.receiver.GetBitrateTemporalCumulative()) +func (d *DownTrack) FinalizeAllocate() VideoAllocation { + return d.forwarder.FinalizeAllocate(d.receiver.GetBitrateTemporalCumulative()) } -func (d *DownTrack) AllocateNextHigher() VideoAllocationResult { +func (d *DownTrack) AllocateNextHigher() (VideoAllocation, bool) { return d.forwarder.AllocateNextHigher(d.receiver.GetBitrateTemporalCumulative()) } -func (d *DownTrack) AllocationState() VideoAllocationState { - return d.forwarder.AllocationState() -} - -func (d *DownTrack) AllocationBandwidth() int64 { - return d.forwarder.AllocationBandwidth() +func (d *DownTrack) LastAllocation() VideoAllocation { + return d.forwarder.LastAllocation() } func (d *DownTrack) CreateSourceDescriptionChunks() []rtcp.SourceDescriptionChunk { @@ -780,7 +781,7 @@ func (d *DownTrack) retransmitPackets(nackedPackets []packetMeta) { pkt.Header.SSRC = d.ssrc pkt.Header.PayloadType = d.payloadType - payload := &pkt.Payload + payload := pkt.Payload if d.mime == "video/vp8" && len(pkt.Payload) > 0 { var incomingVP8 buffer.VP8 if err = incomingVP8.Unmarshal(pkt.Payload); err != nil { @@ -788,12 +789,13 @@ func (d *DownTrack) retransmitPackets(nackedPackets []packetMeta) { continue } + outbuf := &payload translatedVP8 := meta.unpackVP8() if incomingVP8.HeaderSize != translatedVP8.HeaderSize { pool = PacketFactory.Get().(*[]byte) - payload = pool + outbuf = pool } - err = d.translateVP8PacketTo(&pkt, &incomingVP8, translatedVP8, payload) + payload, err = d.translateVP8PacketTo(&pkt, &incomingVP8, translatedVP8, outbuf) if err != nil { Logger.Error(err, "translating VP8 packet err") continue @@ -806,7 +808,7 @@ func (d *DownTrack) retransmitPackets(nackedPackets []packetMeta) { continue } - if _, err = d.writeStream.WriteRTP(&pkt.Header, *payload); err != nil { + if _, err = d.writeStream.WriteRTP(&pkt.Header, payload); err != nil { Logger.Error(err, "Writing rtx packet err") } else { d.UpdateStats(uint32(n)) @@ -861,7 +863,7 @@ func (d *DownTrack) getTranslatedRTPHeader(extPkt *buffer.ExtPacket, tpRTP *Tran return &hdr, nil } -func (d *DownTrack) translateVP8PacketTo(pkt *rtp.Packet, incomingVP8 *buffer.VP8, translatedVP8 *buffer.VP8, outbuf *[]byte) error { +func (d *DownTrack) translateVP8PacketTo(pkt *rtp.Packet, incomingVP8 *buffer.VP8, translatedVP8 *buffer.VP8, outbuf *[]byte) ([]byte, error) { var buf []byte if outbuf == &pkt.Payload { buf = pkt.Payload @@ -873,8 +875,8 @@ func (d *DownTrack) translateVP8PacketTo(pkt *rtp.Packet, incomingVP8 *buffer.VP copy(dstPayload, srcPayload) } - hdr := buf[:translatedVP8.HeaderSize] - return translatedVP8.MarshalTo(hdr) + err := translatedVP8.MarshalTo(buf[:translatedVP8.HeaderSize]) + return buf, err } func (d *DownTrack) DebugInfo() map[string]interface{} { diff --git a/pkg/sfu/forwarder.go b/pkg/sfu/forwarder.go index bbf70e2a..dcfcb485 100644 --- a/pkg/sfu/forwarder.go +++ b/pkg/sfu/forwarder.go @@ -1,6 +1,7 @@ package sfu import ( + "fmt" "math" "strings" "sync" @@ -14,8 +15,7 @@ import ( // Forwarder // const ( - DefaultMaxSpatialLayer = int32(2) - DefaultMaxTemporalLayer = int32(3) + FlagPauseOnDowngrade = false ) type ForwardingStatus int @@ -36,7 +36,8 @@ const ( type LayerPreference int const ( - LayerPreferenceSpatial LayerPreference = iota + LayerPreferenceNone LayerPreference = iota + LayerPreferenceSpatial LayerPreferenceTemporal ) @@ -48,6 +49,19 @@ const ( VideoStreamingChangeResuming ) +func (v VideoStreamingChange) String() string { + switch v { + case VideoStreamingChangeNone: + return "NONE" + case VideoStreamingChangePausing: + return "PAUSING" + case VideoStreamingChangeResuming: + return "RESUMING" + default: + return fmt.Sprintf("%d", int(v)) + } +} + type VideoAllocationState int const ( @@ -59,14 +73,46 @@ const ( VideoAllocationStateDeficient ) -type VideoAllocationResult struct { - change VideoStreamingChange +func (v VideoAllocationState) String() string { + switch v { + case VideoAllocationStateNone: + return "NONE" + case VideoAllocationStateMuted: + return "MUTED" + case VideoAllocationStateFeedDry: + return "FEED_DRY" + case VideoAllocationStateAwaitingMeasurement: + return "AWAITING_MEASUREMENT" + case VideoAllocationStateOptimal: + return "OPTIMAL" + case VideoAllocationStateDeficient: + return "DEFICIENT" + default: + return fmt.Sprintf("%d", int(v)) + } +} + +type VideoAllocation struct { state VideoAllocationState + change VideoStreamingChange bandwidthRequested int64 bandwidthDelta int64 - layersChanged bool + availableLayers []uint16 + bitrates [3][4]int64 + targetLayers VideoLayers } +func (v VideoAllocation) String() string { + return fmt.Sprintf("VideoAllocation{state: %s, change: %s, bw: %d, del: %d, avail: %+v, rates: %+v, target: %s}", + v.state, v.change, v.bandwidthRequested, v.bandwidthDelta, v.availableLayers, v.bitrates, v.targetLayers) +} + +var ( + VideoAllocationDefault = VideoAllocation{ + targetLayers: InvalidLayers, + } +) + type TranslationParams struct { shouldDrop bool shouldSendPLI bool @@ -79,11 +125,30 @@ type VideoLayers struct { temporal int32 } +func (v VideoLayers) String() string { + return fmt.Sprintf("VideoLayers{s: %d, t: %d}", v.spatial, v.temporal) +} + +const ( + DefaultMaxLayerSpatial = int32(2) + DefaultMaxLayerTemporal = int32(3) +) + var ( InvalidLayers = VideoLayers{ spatial: -1, temporal: -1, } + + MinLayers = VideoLayers{ + spatial: 0, + temporal: 0, + } + + DefaultMaxLayers = VideoLayers{ + spatial: DefaultMaxLayerSpatial, + temporal: DefaultMaxLayerTemporal, + } ) type Forwarder struct { @@ -91,6 +156,8 @@ type Forwarder struct { codec webrtc.RTPCodecCapability kind webrtc.RTPCodecType + layerPref LayerPreference + muted bool started bool @@ -101,8 +168,7 @@ type Forwarder struct { currentLayers VideoLayers targetLayers VideoLayers - lastAllocationState VideoAllocationState - lastAllocationRequestBps int64 + lastAllocation VideoAllocation availableLayers []uint16 @@ -115,11 +181,13 @@ func NewForwarder(codec webrtc.RTPCodecCapability, kind webrtc.RTPCodecType) *Fo codec: codec, kind: kind, + layerPref: LayerPreferenceSpatial, + // start off with nothing, let streamallocator set things currentLayers: InvalidLayers, targetLayers: InvalidLayers, - lastAllocationState: VideoAllocationStateNone, + lastAllocation: VideoAllocationDefault, rtpMunger: NewRTPMunger(), } @@ -129,10 +197,7 @@ func NewForwarder(codec webrtc.RTPCodecCapability, kind webrtc.RTPCodecType) *Fo } if f.kind == webrtc.RTPCodecTypeVideo { - f.maxLayers = VideoLayers{ - spatial: DefaultMaxSpatialLayer, - temporal: DefaultMaxTemporalLayer, - } + f.maxLayers = DefaultMaxLayers } else { f.maxLayers = InvalidLayers } @@ -159,30 +224,30 @@ func (f *Forwarder) Muted() bool { return f.muted } -func (f *Forwarder) SetMaxSpatialLayer(spatialLayer int32) (bool, VideoLayers) { +func (f *Forwarder) SetMaxSpatialLayer(spatialLayer int32) (bool, VideoLayers, LayerPreference) { f.lock.Lock() defer f.lock.Unlock() if f.kind == webrtc.RTPCodecTypeAudio || spatialLayer == f.maxLayers.spatial { - return false, InvalidLayers + return false, InvalidLayers, LayerPreferenceNone } f.maxLayers.spatial = spatialLayer - return true, f.maxLayers + return true, f.maxLayers, f.layerPref } -func (f *Forwarder) SetMaxTemporalLayer(temporalLayer int32) (bool, VideoLayers) { +func (f *Forwarder) SetMaxTemporalLayer(temporalLayer int32) (bool, VideoLayers, LayerPreference) { f.lock.Lock() defer f.lock.Unlock() if f.kind == webrtc.RTPCodecTypeAudio || temporalLayer == f.maxLayers.temporal { - return false, InvalidLayers + return false, InvalidLayers, LayerPreferenceNone } f.maxLayers.temporal = temporalLayer - return true, f.maxLayers + return true, f.maxLayers, f.layerPref } func (f *Forwarder) MaxLayers() VideoLayers { @@ -192,6 +257,13 @@ func (f *Forwarder) MaxLayers() VideoLayers { return f.maxLayers } +func (f *Forwarder) GetLayerPreference() LayerPreference { + f.lock.RLock() + defer f.lock.RUnlock() + + return f.layerPref +} + func (f *Forwarder) CurrentLayers() VideoLayers { f.lock.RLock() defer f.lock.RUnlock() @@ -247,57 +319,6 @@ func (f *Forwarder) getOptimalBandwidthNeeded(brs [3][4]int64) int64 { return 0 } -func (f *Forwarder) toVideoAllocationResult(targetLayers VideoLayers, brs [3][4]int64, optimalBandwidthNeeded int64, canPause bool) (result VideoAllocationResult) { - if targetLayers == InvalidLayers && !canPause { - // do not pause if preserving even if allocation does not fit in available channel capacity. - // although preserving, currently streamed layers could have a different bitrate compared to - // when the allocation was done. But not updating to prevent entropy. Let channel - // changes catch up and update state on a fresh allocation. - result.state = f.lastAllocationState - result.bandwidthRequested = f.lastAllocationRequestBps - return - } - - // change in streaming state? - switch { - case f.targetLayers != InvalidLayers && targetLayers == InvalidLayers: - result.change = VideoStreamingChangePausing - case f.targetLayers == InvalidLayers && targetLayers != InvalidLayers: - result.change = VideoStreamingChangeResuming - } - - // how much bandwidth is needed and delta from previous allocation - if targetLayers == InvalidLayers { - result.bandwidthRequested = 0 - } else { - result.bandwidthRequested = brs[targetLayers.spatial][targetLayers.temporal] - } - result.bandwidthDelta = result.bandwidthRequested - f.lastAllocationRequestBps - - // state of allocation - if result.bandwidthRequested == optimalBandwidthNeeded { - result.state = VideoAllocationStateOptimal - } else { - result.state = VideoAllocationStateDeficient - } - - // have allocated layers changed? - if f.targetLayers != targetLayers { - result.layersChanged = true - } - - return -} - -func (f *Forwarder) updateAllocationState(targetLayers VideoLayers, result VideoAllocationResult) { - f.lastAllocationState = result.state - f.lastAllocationRequestBps = result.bandwidthRequested - - if result.layersChanged { - f.targetLayers = targetLayers - } -} - func (f *Forwarder) findBestLayers( minLayers VideoLayers, maxLayers VideoLayers, @@ -307,7 +328,7 @@ func (f *Forwarder) findBestLayers( preference LayerPreference, availableChannelCapacity int64, canPause bool, -) (result VideoAllocationResult) { +) VideoAllocation { targetLayers := InvalidLayers switch direction { @@ -316,7 +337,7 @@ func (f *Forwarder) findBestLayers( case LayerPreferenceSpatial: for i := minLayers.spatial; i <= maxLayers.spatial; i++ { for j := minLayers.temporal; j <= maxLayers.temporal; j++ { - if brs[i][j] != 0 && brs[i][j] < availableChannelCapacity { + if brs[i][j] != 0 && brs[i][j] <= availableChannelCapacity { targetLayers = VideoLayers{ spatial: i, temporal: j, @@ -331,7 +352,7 @@ func (f *Forwarder) findBestLayers( case LayerPreferenceTemporal: for i := minLayers.temporal; i <= maxLayers.temporal; i++ { for j := minLayers.spatial; j <= maxLayers.spatial; j++ { - if brs[j][i] != 0 && brs[j][i] < availableChannelCapacity { + if brs[j][i] != 0 && brs[j][i] <= availableChannelCapacity { targetLayers = VideoLayers{ spatial: j, temporal: i, @@ -349,7 +370,7 @@ func (f *Forwarder) findBestLayers( case LayerPreferenceSpatial: for i := maxLayers.spatial; i >= minLayers.spatial; i-- { for j := maxLayers.temporal; j >= minLayers.temporal; j-- { - if brs[i][j] != 0 && brs[i][j] < availableChannelCapacity { + if brs[i][j] != 0 && brs[i][j] <= availableChannelCapacity { targetLayers = VideoLayers{ spatial: i, temporal: j, @@ -364,7 +385,7 @@ func (f *Forwarder) findBestLayers( case LayerPreferenceTemporal: for i := maxLayers.temporal; i >= minLayers.temporal; i-- { for j := maxLayers.spatial; j >= minLayers.spatial; j-- { - if brs[j][i] != 0 && brs[j][i] < availableChannelCapacity { + if brs[j][i] != 0 && brs[j][i] <= availableChannelCapacity { targetLayers = VideoLayers{ spatial: j, temporal: i, @@ -379,24 +400,66 @@ func (f *Forwarder) findBestLayers( } } - result = f.toVideoAllocationResult(targetLayers, brs, optimalBandwidthNeeded, canPause) - f.updateAllocationState(targetLayers, result) - return + if targetLayers == InvalidLayers && !canPause { + // + // Do not pause if preserving even if allocation does not fit in available channel capacity. + // + // Note that currently streamed layers could have a different bitrate compared to + // when the allocation was done. But not updating to avoid any unnecessary perturbation + // in the allocation system. Let channel changes happen and update state as needed via + // a fresh allocation. + // + return f.lastAllocation + } + + var allocation VideoAllocation + + // change in streaming state? + switch { + case f.targetLayers != InvalidLayers && targetLayers == InvalidLayers: + allocation.change = VideoStreamingChangePausing + case f.targetLayers == InvalidLayers && targetLayers != InvalidLayers: + allocation.change = VideoStreamingChangeResuming + } + + // how much bandwidth is needed and delta from previous allocation + if targetLayers == InvalidLayers { + allocation.bandwidthRequested = 0 + } else { + allocation.bandwidthRequested = brs[targetLayers.spatial][targetLayers.temporal] + } + allocation.bandwidthDelta = allocation.bandwidthRequested - f.lastAllocation.bandwidthRequested + + // state of allocation + if allocation.bandwidthRequested == optimalBandwidthNeeded { + allocation.state = VideoAllocationStateOptimal + } else { + allocation.state = VideoAllocationStateDeficient + } + + allocation.availableLayers = f.availableLayers + allocation.bitrates = brs + allocation.targetLayers = targetLayers + + return allocation } -func (f *Forwarder) allocate(availableChannelCapacity int64, canPause bool, brs [3][4]int64) (result VideoAllocationResult) { +func (f *Forwarder) allocate(availableChannelCapacity int64, canPause bool, brs [3][4]int64) { // should never get called on audio tracks, just for safety if f.kind == webrtc.RTPCodecTypeAudio { return } if f.muted { - result.state = VideoAllocationStateMuted - result.bandwidthRequested = 0 - result.bandwidthDelta = result.bandwidthRequested - f.lastAllocationRequestBps - - f.lastAllocationState = result.state - f.lastAllocationRequestBps = result.bandwidthRequested + f.lastAllocation = VideoAllocation{ + state: VideoAllocationStateMuted, + change: VideoStreamingChangeNone, + bandwidthRequested: 0, + bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested, + availableLayers: f.availableLayers, + bitrates: brs, + targetLayers: f.targetLayers, + } return } @@ -404,25 +467,28 @@ func (f *Forwarder) allocate(availableChannelCapacity int64, canPause bool, brs if optimalBandwidthNeeded == 0 { if len(f.availableLayers) == 0 { // feed is dry - result.state = VideoAllocationStateFeedDry - result.bandwidthRequested = 0 - result.bandwidthDelta = result.bandwidthRequested - f.lastAllocationRequestBps - - f.lastAllocationState = result.state - f.lastAllocationRequestBps = result.bandwidthRequested + f.lastAllocation = VideoAllocation{ + state: VideoAllocationStateFeedDry, + change: VideoStreamingChangeNone, + bandwidthRequested: 0, + bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested, + availableLayers: f.availableLayers, + bitrates: brs, + targetLayers: f.targetLayers, + } return } // feed bitrate is not yet calculated - result.state = VideoAllocationStateAwaitingMeasurement - f.lastAllocationState = result.state - if availableChannelCapacity == ChannelCapacityInfinity { - // channel capacity allows a free pass. + // + // Channel capacity allows a free pass. // So, resume with the highest layer available <= max subscribed layer // If already resumed, move allocation to the highest available layer <= max subscribed layer + // + change := VideoStreamingChangeNone if f.targetLayers == InvalidLayers { - result.change = VideoStreamingChangeResuming + change = VideoStreamingChangeResuming } f.targetLayers.spatial = int32(f.availableLayers[len(f.availableLayers)-1]) @@ -431,120 +497,139 @@ func (f *Forwarder) allocate(availableChannelCapacity int64, canPause bool, brs } f.targetLayers.temporal = int32(math.Max(0, float64(f.maxLayers.temporal))) + + f.lastAllocation = VideoAllocation{ + state: VideoAllocationStateAwaitingMeasurement, + change: change, + bandwidthRequested: 0, // unavailable yet + bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested, + availableLayers: f.availableLayers, + bitrates: brs, + targetLayers: f.targetLayers, + } } else { // if not optimistically started, nothing else to do if f.targetLayers == InvalidLayers { - return - } - - if canPause { + f.lastAllocation = VideoAllocation{ + state: VideoAllocationStateDeficient, + change: VideoStreamingChangeNone, + bandwidthRequested: 0, // unavailable yet + bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested, + availableLayers: f.availableLayers, + bitrates: brs, + targetLayers: f.targetLayers, + } + } else if canPause { // disable it as it is not known how big this stream is // and if it will fit in the available channel capacity - result.change = VideoStreamingChangePausing - result.state = VideoAllocationStateDeficient - result.bandwidthRequested = 0 - result.bandwidthDelta = result.bandwidthRequested - f.lastAllocationRequestBps - - f.lastAllocationState = result.state - f.lastAllocationRequestBps = result.bandwidthRequested - f.disable() + + f.lastAllocation = VideoAllocation{ + state: VideoAllocationStateDeficient, + change: VideoStreamingChangePausing, + bandwidthRequested: 0, // unavailable yet + bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested, + availableLayers: f.availableLayers, + bitrates: brs, + targetLayers: f.targetLayers, + } } } return } - minLayers := VideoLayers{ - spatial: 0, - temporal: 0, - } - result = f.findBestLayers( - minLayers, + f.lastAllocation = f.findBestLayers( + MinLayers, f.maxLayers, brs, optimalBandwidthNeeded, LayerDirectionHighToLow, - LayerPreferenceSpatial, + f.layerPref, availableChannelCapacity, canPause, ) - return + f.targetLayers = f.lastAllocation.targetLayers } -func (f *Forwarder) Allocate(availableChannelCapacity int64, brs [3][4]int64) VideoAllocationResult { +func (f *Forwarder) Allocate(availableChannelCapacity int64, brs [3][4]int64) VideoAllocation { f.lock.Lock() defer f.lock.Unlock() - return f.allocate(availableChannelCapacity, true, brs) + f.allocate(availableChannelCapacity, true, brs) + return f.lastAllocation } -func (f *Forwarder) TryAllocate(additionalChannelCapacity int64, brs [3][4]int64) VideoAllocationResult { +func (f *Forwarder) TryAllocate(additionalChannelCapacity int64, brs [3][4]int64) VideoAllocation { f.lock.Lock() defer f.lock.Unlock() - return f.allocate(f.lastAllocationRequestBps+additionalChannelCapacity, false, brs) + f.allocate(f.lastAllocation.bandwidthRequested+additionalChannelCapacity, false, brs) + return f.lastAllocation } -func (f *Forwarder) FinalizeAllocate(brs [3][4]int64) { +func (f *Forwarder) FinalizeAllocate(brs [3][4]int64) VideoAllocation { f.lock.Lock() defer f.lock.Unlock() - if f.lastAllocationState != VideoAllocationStateAwaitingMeasurement { - return + if f.lastAllocation.state != VideoAllocationStateAwaitingMeasurement { + return f.lastAllocation } optimalBandwidthNeeded := f.getOptimalBandwidthNeeded(brs) if optimalBandwidthNeeded == 0 { if len(f.availableLayers) == 0 { // feed dry - f.lastAllocationState = VideoAllocationStateFeedDry - f.lastAllocationRequestBps = 0 + f.lastAllocation = VideoAllocation{ + state: VideoAllocationStateFeedDry, + change: VideoStreamingChangeNone, + bandwidthRequested: 0, + bandwidthDelta: 0 - f.lastAllocation.bandwidthRequested, + availableLayers: f.availableLayers, + bitrates: brs, + targetLayers: f.targetLayers, + } } // still awaiting measurement - return + return f.lastAllocation } - minLayers := VideoLayers{ - spatial: 0, - temporal: 0, - } - f.findBestLayers( - minLayers, + f.lastAllocation = f.findBestLayers( + MinLayers, f.maxLayers, brs, optimalBandwidthNeeded, LayerDirectionHighToLow, - LayerPreferenceSpatial, + f.layerPref, ChannelCapacityInfinity, false, ) + f.targetLayers = f.lastAllocation.targetLayers + return f.lastAllocation } -func (f *Forwarder) AllocateNextHigher(brs [3][4]int64) (result VideoAllocationResult) { +func (f *Forwarder) AllocateNextHigher(brs [3][4]int64) (VideoAllocation, bool) { f.lock.Lock() defer f.lock.Unlock() if f.kind == webrtc.RTPCodecTypeAudio { - return + return f.lastAllocation, false } // if not deficient, nothing to do - if f.lastAllocationState != VideoAllocationStateDeficient { - return + if f.lastAllocation.state != VideoAllocationStateDeficient { + return f.lastAllocation, false } // if targets are still pending, don't increase - if f.targetLayers != InvalidLayers { - if f.targetLayers != f.currentLayers { - return - } + if f.targetLayers != InvalidLayers && f.targetLayers != f.currentLayers { + return f.lastAllocation, false } optimalBandwidthNeeded := f.getOptimalBandwidthNeeded(brs) if optimalBandwidthNeeded == 0 { // either feed is dry or awaiting measurement, don't hunt for higher - return + return f.lastAllocation, false } // try moving temporal layer up in currently streaming spatial layer @@ -557,18 +642,20 @@ func (f *Forwarder) AllocateNextHigher(brs [3][4]int64) (result VideoAllocationR spatial: f.targetLayers.spatial, temporal: f.maxLayers.temporal, } - result = f.findBestLayers( + allocation := f.findBestLayers( minLayers, maxLayers, brs, optimalBandwidthNeeded, LayerDirectionLowToHigh, - LayerPreferenceSpatial, + f.layerPref, ChannelCapacityInfinity, false, ) - if result.layersChanged { - return + if allocation.targetLayers != f.targetLayers { + f.lastAllocation = allocation + f.targetLayers = allocation.targetLayers + return f.lastAllocation, true } } @@ -581,20 +668,26 @@ func (f *Forwarder) AllocateNextHigher(brs [3][4]int64) (result VideoAllocationR spatial: f.maxLayers.spatial, temporal: f.maxLayers.temporal, } - result = f.findBestLayers( + allocation := f.findBestLayers( minLayers, maxLayers, brs, optimalBandwidthNeeded, LayerDirectionLowToHigh, - LayerPreferenceSpatial, + f.layerPref, ChannelCapacityInfinity, false, ) + if allocation.targetLayers != f.targetLayers { + f.lastAllocation = allocation + f.targetLayers = allocation.targetLayers + return f.lastAllocation, true + } - return + return f.lastAllocation, false } +/* func (f *Forwarder) AllocationState() VideoAllocationState { f.lock.RLock() defer f.lock.RUnlock() @@ -608,6 +701,13 @@ func (f *Forwarder) AllocationBandwidth() int64 { return f.lastAllocationRequestBps } +*/ +func (f *Forwarder) LastAllocation() VideoAllocation { + f.lock.RLock() + defer f.lock.RUnlock() + + return f.lastAllocation +} func (f *Forwarder) GetTranslationParams(extPkt *buffer.ExtPacket, layer int32) (*TranslationParams, error) { f.lock.Lock() @@ -692,7 +792,7 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in return tp, nil } - if f.targetLayers.spatial < f.currentLayers.spatial && f.targetLayers.spatial < f.maxLayers.spatial { + if FlagPauseOnDowngrade && f.targetLayers.spatial < f.currentLayers.spatial && f.targetLayers.spatial < f.maxLayers.spatial { // // If target layer is lower than both the current and // maximum subscribed layer, it is due to bandwidth @@ -764,7 +864,7 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in return tp, err } - if f.vp8Munger == nil { + if f.vp8Munger == nil || len(extPkt.Packet.Payload) == 0 { tp.rtp = tpRTP return tp, nil } diff --git a/pkg/sfu/forwarder_test.go b/pkg/sfu/forwarder_test.go index b213dac2..02f58ab5 100644 --- a/pkg/sfu/forwarder_test.go +++ b/pkg/sfu/forwarder_test.go @@ -31,11 +31,11 @@ func TestForwarderLayersAudio(t *testing.T) { require.Equal(t, InvalidLayers, f.CurrentLayers()) require.Equal(t, InvalidLayers, f.TargetLayers()) - changed, layers := f.SetMaxSpatialLayer(1) + changed, layers, _ := f.SetMaxSpatialLayer(1) require.False(t, changed) require.Equal(t, InvalidLayers, layers) - changed, layers = f.SetMaxTemporalLayer(1) + changed, layers, _ = f.SetMaxTemporalLayer(1) require.False(t, changed) require.Equal(t, InvalidLayers, layers) @@ -47,36 +47,36 @@ func TestForwarderLayersVideo(t *testing.T) { maxLayers := f.MaxLayers() expectedLayers := VideoLayers{ - spatial: DefaultMaxSpatialLayer, - temporal: DefaultMaxTemporalLayer, + spatial: DefaultMaxLayerSpatial, + temporal: DefaultMaxLayerTemporal, } require.Equal(t, expectedLayers, maxLayers) require.Equal(t, InvalidLayers, f.CurrentLayers()) require.Equal(t, InvalidLayers, f.TargetLayers()) - changed, layers := f.SetMaxSpatialLayer(DefaultMaxSpatialLayer) + changed, layers, _ := f.SetMaxSpatialLayer(DefaultMaxLayerSpatial) require.False(t, changed) require.Equal(t, InvalidLayers, layers) - changed, layers = f.SetMaxSpatialLayer(DefaultMaxSpatialLayer - 1) + changed, layers, _ = f.SetMaxSpatialLayer(DefaultMaxLayerSpatial - 1) require.True(t, changed) expectedLayers = VideoLayers{ - spatial: DefaultMaxSpatialLayer - 1, - temporal: DefaultMaxTemporalLayer, + spatial: DefaultMaxLayerSpatial - 1, + temporal: DefaultMaxLayerTemporal, } require.Equal(t, expectedLayers, layers) require.Equal(t, expectedLayers, f.MaxLayers()) - changed, layers = f.SetMaxTemporalLayer(DefaultMaxTemporalLayer) + changed, layers, _ = f.SetMaxTemporalLayer(DefaultMaxLayerTemporal) require.False(t, changed) require.Equal(t, InvalidLayers, layers) - changed, layers = f.SetMaxTemporalLayer(DefaultMaxTemporalLayer - 1) + changed, layers, _ = f.SetMaxTemporalLayer(DefaultMaxLayerTemporal - 1) require.True(t, changed) expectedLayers = VideoLayers{ - spatial: DefaultMaxSpatialLayer - 1, - temporal: DefaultMaxTemporalLayer - 1, + spatial: DefaultMaxLayerSpatial - 1, + temporal: DefaultMaxLayerTemporal - 1, } require.Equal(t, expectedLayers, layers) require.Equal(t, expectedLayers, f.MaxLayers()) @@ -87,10 +87,10 @@ func TestForwarderGetForwardingStatus(t *testing.T) { require.Equal(t, ForwardingStatusOff, f.GetForwardingStatus()) - f.targetLayers.spatial = DefaultMaxSpatialLayer - 1 + f.targetLayers.spatial = DefaultMaxLayerSpatial - 1 require.Equal(t, ForwardingStatusPartial, f.GetForwardingStatus()) - f.targetLayers.spatial = DefaultMaxSpatialLayer + f.targetLayers.spatial = DefaultMaxLayerSpatial require.Equal(t, ForwardingStatusOptimal, f.GetForwardingStatus()) } @@ -115,8 +115,8 @@ func TestForwarderUptrackLayersChange(t *testing.T) { func TestForwarderAllocate(t *testing.T) { f := NewForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) - emptyBitrates := [DefaultMaxSpatialLayer + 1][DefaultMaxTemporalLayer + 1]int64{} - bitrates := [DefaultMaxSpatialLayer + 1][DefaultMaxTemporalLayer + 1]int64{ + emptyBitrates := [DefaultMaxLayerSpatial + 1][DefaultMaxLayerTemporal + 1]int64{} + bitrates := [DefaultMaxLayerSpatial + 1][DefaultMaxLayerTemporal + 1]int64{ {2, 3, 0, 0}, {4, 0, 0, 5}, {0, 7, 0, 0}, @@ -125,117 +125,128 @@ func TestForwarderAllocate(t *testing.T) { // muted should not consume any bandwidth f.Mute(true) f.disable() - expectedResult := VideoAllocationResult{ + expectedResult := VideoAllocation{ change: VideoStreamingChangeNone, state: VideoAllocationStateMuted, bandwidthRequested: 0, bandwidthDelta: 0, + availableLayers: nil, + bitrates: bitrates, + targetLayers: InvalidLayers, } result := f.Allocate(ChannelCapacityInfinity, bitrates) require.Equal(t, expectedResult, result) - require.Equal(t, VideoAllocationStateMuted, f.lastAllocationState) - require.Equal(t, int64(0), f.lastAllocationRequestBps) + require.Equal(t, expectedResult, f.lastAllocation) // feed dry state f.Mute(false) - f.lastAllocationState = VideoAllocationStateNone + f.lastAllocation.state = VideoAllocationStateNone f.disable() - expectedResult = VideoAllocationResult{ + expectedResult = VideoAllocation{ change: VideoStreamingChangeNone, state: VideoAllocationStateFeedDry, bandwidthRequested: 0, bandwidthDelta: 0, + availableLayers: nil, + bitrates: emptyBitrates, + targetLayers: InvalidLayers, } result = f.Allocate(ChannelCapacityInfinity, emptyBitrates) require.Equal(t, expectedResult, result) - require.Equal(t, VideoAllocationStateFeedDry, f.lastAllocationState) - require.Equal(t, int64(0), f.lastAllocationRequestBps) + require.Equal(t, expectedResult, f.lastAllocation) // awaiting measurement, i. e. bitrates are not available, but layers available - f.lastAllocationState = VideoAllocationStateNone + f.lastAllocation.state = VideoAllocationStateNone f.disable() f.UptrackLayersChange([]uint16{0}) - expectedResult = VideoAllocationResult{ + expectedTargetLayers := VideoLayers{ + spatial: 0, + temporal: DefaultMaxLayerTemporal, + } + expectedResult = VideoAllocation{ change: VideoStreamingChangeResuming, state: VideoAllocationStateAwaitingMeasurement, bandwidthRequested: 0, bandwidthDelta: 0, + availableLayers: []uint16{0}, + bitrates: emptyBitrates, + targetLayers: expectedTargetLayers, } result = f.Allocate(ChannelCapacityInfinity, emptyBitrates) require.Equal(t, expectedResult, result) - require.Equal(t, VideoAllocationStateAwaitingMeasurement, f.lastAllocationState) - require.Equal(t, int64(0), f.lastAllocationRequestBps) - expectedTargetLayers := VideoLayers{ - spatial: 0, - temporal: DefaultMaxTemporalLayer, - } + require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) require.Equal(t, InvalidLayers, f.CurrentLayers()) // while awaiting measurement, less than infinite channel capacity should pause the stream - expectedResult = VideoAllocationResult{ + expectedResult = VideoAllocation{ change: VideoStreamingChangePausing, state: VideoAllocationStateDeficient, bandwidthRequested: 0, bandwidthDelta: 0, + availableLayers: []uint16{0}, + bitrates: emptyBitrates, + targetLayers: InvalidLayers, } result = f.Allocate(ChannelCapacityInfinity-1, emptyBitrates) require.Equal(t, expectedResult, result) - require.Equal(t, VideoAllocationStateDeficient, f.lastAllocationState) - require.Equal(t, int64(0), f.lastAllocationRequestBps) + require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, InvalidLayers, f.CurrentLayers()) require.Equal(t, InvalidLayers, f.TargetLayers()) // allocate using bitrates and less than infinite channel capacity, but enough for optimal - expectedResult = VideoAllocationResult{ - change: VideoStreamingChangeResuming, - state: VideoAllocationStateOptimal, - bandwidthRequested: bitrates[2][1], - bandwidthDelta: bitrates[2][1], - layersChanged: true, - } - result = f.Allocate(ChannelCapacityInfinity-1, bitrates) - require.Equal(t, expectedResult, result) - require.Equal(t, VideoAllocationStateOptimal, f.lastAllocationState) - require.Equal(t, bitrates[2][1], f.lastAllocationRequestBps) - require.Equal(t, InvalidLayers, f.CurrentLayers()) expectedTargetLayers = VideoLayers{ spatial: 2, temporal: 1, } + expectedResult = VideoAllocation{ + change: VideoStreamingChangeResuming, + state: VideoAllocationStateOptimal, + bandwidthRequested: bitrates[2][1], + bandwidthDelta: bitrates[2][1], + availableLayers: []uint16{0}, + bitrates: bitrates, + targetLayers: expectedTargetLayers, + } + result = f.Allocate(ChannelCapacityInfinity-1, bitrates) + require.Equal(t, expectedResult, result) + require.Equal(t, expectedResult, f.lastAllocation) + require.Equal(t, InvalidLayers, f.CurrentLayers()) require.Equal(t, expectedTargetLayers, f.TargetLayers()) // give it a bitrate that is less than optimal - expectedResult = VideoAllocationResult{ - change: VideoStreamingChangeNone, - state: VideoAllocationStateDeficient, - bandwidthRequested: bitrates[1][3], - bandwidthDelta: bitrates[1][3] - bitrates[2][1], - layersChanged: true, - } - result = f.Allocate(bitrates[2][1]-1, bitrates) - require.Equal(t, expectedResult, result) - require.Equal(t, VideoAllocationStateDeficient, f.lastAllocationState) - require.Equal(t, bitrates[1][3], f.lastAllocationRequestBps) - require.Equal(t, InvalidLayers, f.CurrentLayers()) expectedTargetLayers = VideoLayers{ spatial: 1, temporal: 3, } + expectedResult = VideoAllocation{ + change: VideoStreamingChangeNone, + state: VideoAllocationStateDeficient, + bandwidthRequested: bitrates[1][3], + bandwidthDelta: bitrates[1][3] - bitrates[2][1], + availableLayers: []uint16{0}, + bitrates: bitrates, + targetLayers: expectedTargetLayers, + } + result = f.Allocate(bitrates[2][1]-1, bitrates) + require.Equal(t, expectedResult, result) + require.Equal(t, expectedResult, f.lastAllocation) + require.Equal(t, InvalidLayers, f.CurrentLayers()) require.Equal(t, expectedTargetLayers, f.TargetLayers()) // give it a bitrate that cannot fit any layer - expectedResult = VideoAllocationResult{ + expectedResult = VideoAllocation{ change: VideoStreamingChangePausing, state: VideoAllocationStateDeficient, bandwidthRequested: 0, bandwidthDelta: 0 - bitrates[1][3], - layersChanged: true, + availableLayers: []uint16{0}, + bitrates: bitrates, + targetLayers: InvalidLayers, } result = f.Allocate(bitrates[0][0]-1, bitrates) require.Equal(t, expectedResult, result) - require.Equal(t, VideoAllocationStateDeficient, f.lastAllocationState) - require.Equal(t, int64(0), f.lastAllocationRequestBps) + require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, InvalidLayers, f.CurrentLayers()) require.Equal(t, InvalidLayers, f.TargetLayers()) } @@ -244,274 +255,364 @@ func TestForwarderTryAllocate(t *testing.T) { f := NewForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) // adjust target layers per given additional channel capacity (which can be negative), - bitrates := [DefaultMaxSpatialLayer + 1][DefaultMaxTemporalLayer + 1]int64{ + bitrates := [DefaultMaxLayerSpatial + 1][DefaultMaxLayerTemporal + 1]int64{ {2, 3, 0, 0}, {4, 0, 0, 5}, {0, 7, 0, 0}, } - f.lastAllocationState = VideoAllocationStateDeficient - f.lastAllocationRequestBps = bitrates[1][3] + f.lastAllocation.state = VideoAllocationStateDeficient + f.lastAllocation.bandwidthRequested = bitrates[1][3] f.targetLayers = VideoLayers{ spatial: 1, temporal: 3, } - expectedResult := VideoAllocationResult{ + expectedTargetLayers := VideoLayers{ + spatial: 1, + temporal: 0, + } + expectedResult := VideoAllocation{ change: VideoStreamingChangeNone, state: VideoAllocationStateDeficient, - bandwidthRequested: bitrates[0][1], - bandwidthDelta: bitrates[0][1] - bitrates[1][3], - layersChanged: true, + bandwidthRequested: bitrates[1][0], + bandwidthDelta: bitrates[1][0] - bitrates[1][3], + availableLayers: nil, + bitrates: bitrates, + targetLayers: expectedTargetLayers, } result := f.TryAllocate(-1, bitrates) require.Equal(t, expectedResult, result) - require.Equal(t, VideoAllocationStateDeficient, f.lastAllocationState) - require.Equal(t, bitrates[0][1], f.lastAllocationRequestBps) + require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, InvalidLayers, f.CurrentLayers()) - expectedTargetLayers := VideoLayers{ - spatial: 0, - temporal: 1, - } require.Equal(t, expectedTargetLayers, f.TargetLayers()) // but should not pause even if no layer fits, i. e. preserve current - expectedResult = VideoAllocationResult{ + expectedResult = VideoAllocation{ change: VideoStreamingChangeNone, state: VideoAllocationStateDeficient, - bandwidthRequested: bitrates[0][1], - bandwidthDelta: 0, + bandwidthRequested: bitrates[1][0], + bandwidthDelta: -1, + availableLayers: nil, + bitrates: bitrates, + targetLayers: expectedTargetLayers, } - result = f.TryAllocate(-2, bitrates) + result = f.TryAllocate(-3, bitrates) require.Equal(t, expectedResult, result) - require.Equal(t, VideoAllocationStateDeficient, f.lastAllocationState) - require.Equal(t, bitrates[0][1], f.lastAllocationRequestBps) + require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, InvalidLayers, f.CurrentLayers()) require.Equal(t, expectedTargetLayers, f.TargetLayers()) // can catch up to optimal given enough additional channel capacity - expectedResult = VideoAllocationResult{ - change: VideoStreamingChangeNone, - state: VideoAllocationStateOptimal, - bandwidthRequested: bitrates[2][1], - bandwidthDelta: bitrates[2][1] - bitrates[0][1], - layersChanged: true, - } - result = f.TryAllocate(10, bitrates) - require.Equal(t, expectedResult, result) - require.Equal(t, VideoAllocationStateOptimal, f.lastAllocationState) - require.Equal(t, bitrates[2][1], f.lastAllocationRequestBps) - require.Equal(t, InvalidLayers, f.CurrentLayers()) expectedTargetLayers = VideoLayers{ spatial: 2, temporal: 1, } + expectedResult = VideoAllocation{ + change: VideoStreamingChangeNone, + state: VideoAllocationStateOptimal, + bandwidthRequested: bitrates[2][1], + bandwidthDelta: bitrates[2][1] - bitrates[1][0], + availableLayers: nil, + bitrates: bitrates, + targetLayers: expectedTargetLayers, + } + result = f.TryAllocate(10, bitrates) + require.Equal(t, expectedResult, result) + require.Equal(t, expectedResult, f.lastAllocation) + require.Equal(t, InvalidLayers, f.CurrentLayers()) require.Equal(t, expectedTargetLayers, f.TargetLayers()) } func TestForwarderFinalizeAllocate(t *testing.T) { f := NewForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) - bitrates := [DefaultMaxSpatialLayer + 1][DefaultMaxTemporalLayer + 1]int64{ + bitrates := [DefaultMaxLayerSpatial + 1][DefaultMaxLayerTemporal + 1]int64{ {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, } // FinalizeAllocate should do nothing unless Forwarder allocation state is VideoAllocationStateAwaitingMeasurement - f.FinalizeAllocate(bitrates) - require.Equal(t, VideoAllocationStateNone, f.lastAllocationState) + result := f.FinalizeAllocate(bitrates) + require.Equal(t, VideoAllocationDefault, result) + require.Equal(t, VideoAllocationDefault, f.lastAllocation) - f.lastAllocationState = VideoAllocationStateMuted + f.lastAllocation.state = VideoAllocationStateMuted f.disable() - f.FinalizeAllocate(bitrates) - require.Equal(t, VideoAllocationStateMuted, f.lastAllocationState) + expectedResult := VideoAllocation{ + change: VideoStreamingChangeNone, + state: VideoAllocationStateMuted, + bandwidthRequested: 0, + bandwidthDelta: 0, + availableLayers: nil, + bitrates: [3][4]int64{}, + targetLayers: InvalidLayers, + } + result = f.FinalizeAllocate(bitrates) + require.Equal(t, expectedResult, result) + require.Equal(t, expectedResult, f.lastAllocation) - f.lastAllocationState = VideoAllocationStateAwaitingMeasurement + f.lastAllocation.state = VideoAllocationStateAwaitingMeasurement f.disable() - f.FinalizeAllocate(bitrates) - require.Equal(t, VideoAllocationStateOptimal, f.lastAllocationState) - require.Equal(t, InvalidLayers, f.CurrentLayers()) expectedTargetLayers := VideoLayers{ spatial: 2, temporal: 3, } + expectedResult = VideoAllocation{ + change: VideoStreamingChangeResuming, + state: VideoAllocationStateOptimal, + bandwidthRequested: bitrates[2][3], + bandwidthDelta: bitrates[2][3], + availableLayers: nil, + bitrates: bitrates, + targetLayers: expectedTargetLayers, + } + result = f.FinalizeAllocate(bitrates) + require.Equal(t, expectedResult, result) + require.Equal(t, expectedResult, f.lastAllocation) + require.Equal(t, InvalidLayers, f.CurrentLayers()) require.Equal(t, expectedTargetLayers, f.TargetLayers()) // no layers available => feed dry - f.lastAllocationState = VideoAllocationStateAwaitingMeasurement + f.lastAllocation.state = VideoAllocationStateAwaitingMeasurement f.disable() - f.FinalizeAllocate([DefaultMaxSpatialLayer + 1][DefaultMaxTemporalLayer + 1]int64{}) - require.Equal(t, VideoAllocationStateFeedDry, f.lastAllocationState) + expectedResult = VideoAllocation{ + change: VideoStreamingChangeNone, + state: VideoAllocationStateFeedDry, + bandwidthRequested: 0, + bandwidthDelta: 0 - bitrates[2][3], + availableLayers: nil, + bitrates: [DefaultMaxLayerSpatial + 1][DefaultMaxLayerTemporal + 1]int64{}, + targetLayers: InvalidLayers, + } + result = f.FinalizeAllocate([DefaultMaxLayerSpatial + 1][DefaultMaxLayerTemporal + 1]int64{}) + require.Equal(t, expectedResult, result) + require.Equal(t, expectedResult, f.lastAllocation) // layers available, but still awaiting measurement - f.lastAllocationState = VideoAllocationStateAwaitingMeasurement + f.lastAllocation.state = VideoAllocationStateAwaitingMeasurement f.disable() f.UptrackLayersChange([]uint16{0, 1}) - f.FinalizeAllocate([DefaultMaxSpatialLayer + 1][DefaultMaxTemporalLayer + 1]int64{}) - require.Equal(t, VideoAllocationStateAwaitingMeasurement, f.lastAllocationState) + expectedResult = VideoAllocation{ + change: VideoStreamingChangeNone, + state: VideoAllocationStateAwaitingMeasurement, + bandwidthRequested: 0, + bandwidthDelta: -12, + availableLayers: nil, + bitrates: [DefaultMaxLayerSpatial + 1][DefaultMaxLayerTemporal + 1]int64{}, + targetLayers: InvalidLayers, + } + result = f.FinalizeAllocate([DefaultMaxLayerSpatial + 1][DefaultMaxLayerTemporal + 1]int64{}) + require.Equal(t, expectedResult, result) + require.Equal(t, expectedResult, f.lastAllocation) // sparse layers - bitrates = [DefaultMaxSpatialLayer + 1][DefaultMaxTemporalLayer + 1]int64{ + bitrates = [DefaultMaxLayerSpatial + 1][DefaultMaxLayerTemporal + 1]int64{ {1, 2, 0, 0}, {5, 0, 0, 6}, {0, 0, 0, 0}, } - f.lastAllocationState = VideoAllocationStateAwaitingMeasurement f.disable() - f.FinalizeAllocate(bitrates) - require.Equal(t, VideoAllocationStateOptimal, f.lastAllocationState) - require.Equal(t, InvalidLayers, f.CurrentLayers()) expectedTargetLayers = VideoLayers{ spatial: 1, temporal: 3, } + expectedResult = VideoAllocation{ + change: VideoStreamingChangeResuming, + state: VideoAllocationStateOptimal, + bandwidthRequested: bitrates[1][3], + bandwidthDelta: bitrates[1][3], + availableLayers: []uint16{0, 1}, + bitrates: bitrates, + targetLayers: expectedTargetLayers, + } + result = f.FinalizeAllocate(bitrates) + require.Equal(t, expectedResult, result) + require.Equal(t, expectedResult, f.lastAllocation) + require.Equal(t, InvalidLayers, f.CurrentLayers()) require.Equal(t, expectedTargetLayers, f.TargetLayers()) } func TestForwarderAllocateNextHigher(t *testing.T) { f := NewForwarder(testutils.TestOpusCodec, webrtc.RTPCodecTypeAudio) - emptyBitrates := [DefaultMaxSpatialLayer + 1][DefaultMaxTemporalLayer + 1]int64{} - bitrates := [DefaultMaxSpatialLayer + 1][DefaultMaxTemporalLayer + 1]int64{ + emptyBitrates := [DefaultMaxLayerSpatial + 1][DefaultMaxLayerTemporal + 1]int64{} + bitrates := [DefaultMaxLayerSpatial + 1][DefaultMaxLayerTemporal + 1]int64{ {2, 3, 0, 0}, {4, 0, 0, 5}, {0, 7, 0, 0}, } - result := f.AllocateNextHigher(bitrates) - require.Equal(t, VideoAllocationResult{}, result) // no layer for audio + result, boosted := f.AllocateNextHigher(bitrates) + require.Equal(t, VideoAllocationDefault, result) // no layer for audio + require.False(t, boosted) f = NewForwarder(testutils.TestVP8Codec, webrtc.RTPCodecTypeVideo) // when not in deficient state, does not boost - f.lastAllocationState = VideoAllocationStateNone - result = f.AllocateNextHigher(bitrates) - require.Equal(t, VideoAllocationResult{}, result) + f.lastAllocation.state = VideoAllocationStateNone + result, boosted = f.AllocateNextHigher(bitrates) + require.Equal(t, VideoAllocationDefault, result) + require.False(t, boosted) // if layers have not caught up, should not allocate next layer - f.lastAllocationState = VideoAllocationStateDeficient + f.lastAllocation.state = VideoAllocationStateDeficient f.targetLayers.spatial = 0 - result = f.AllocateNextHigher(bitrates) - require.Equal(t, VideoAllocationResult{}, result) + expectedResult := VideoAllocation{ + change: VideoStreamingChangeNone, + state: VideoAllocationStateDeficient, + bandwidthRequested: 0, + bandwidthDelta: 0, + availableLayers: nil, + bitrates: emptyBitrates, + targetLayers: InvalidLayers, + } + result, boosted = f.AllocateNextHigher(bitrates) + require.Equal(t, expectedResult, result) + require.Equal(t, expectedResult, f.lastAllocation) + require.False(t, boosted) f.currentLayers.spatial = 0 f.targetLayers.temporal = 0 - result = f.AllocateNextHigher(bitrates) - require.Equal(t, VideoAllocationResult{}, result) + result, boosted = f.AllocateNextHigher(bitrates) + require.Equal(t, expectedResult, result) + require.Equal(t, expectedResult, f.lastAllocation) + require.False(t, boosted) f.currentLayers.temporal = 0 - f.lastAllocationRequestBps = bitrates[0][0] + f.lastAllocation.bandwidthRequested = bitrates[0][0] // empty bitrates cannot increase layer - result = f.AllocateNextHigher(emptyBitrates) - require.Equal(t, VideoAllocationResult{}, result) - - // move from (0, 0) -> (0, 1), i. e. a higher temporal layer is available in the same spatial layer - expectedResult := VideoAllocationResult{ + expectedResult = VideoAllocation{ change: VideoStreamingChangeNone, state: VideoAllocationStateDeficient, - bandwidthRequested: 3, - bandwidthDelta: 1, - layersChanged: true, + bandwidthRequested: 2, + bandwidthDelta: 0, + availableLayers: nil, + bitrates: emptyBitrates, + targetLayers: InvalidLayers, } - result = f.AllocateNextHigher(bitrates) + result, boosted = f.AllocateNextHigher(emptyBitrates) require.Equal(t, expectedResult, result) - require.Equal(t, VideoAllocationStateDeficient, f.lastAllocationState) - require.Equal(t, bitrates[0][1], f.lastAllocationRequestBps) + require.Equal(t, expectedResult, f.lastAllocation) + require.False(t, boosted) + + // move from (0, 0) -> (0, 1), i. e. a higher temporal layer is available in the same spatial layer expectedTargetLayers := VideoLayers{ spatial: 0, temporal: 1, } + expectedResult = VideoAllocation{ + change: VideoStreamingChangeNone, + state: VideoAllocationStateDeficient, + bandwidthRequested: 3, + bandwidthDelta: 1, + availableLayers: nil, + bitrates: bitrates, + targetLayers: expectedTargetLayers, + } + result, boosted = f.AllocateNextHigher(bitrates) + require.Equal(t, expectedResult, result) + require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) + require.True(t, boosted) // move from (0, 1) -> (1, 0), i. e. a higher spatial layer is available f.currentLayers.temporal = 1 - expectedResult = VideoAllocationResult{ + expectedTargetLayers = VideoLayers{ + spatial: 1, + temporal: 0, + } + expectedResult = VideoAllocation{ change: VideoStreamingChangeNone, state: VideoAllocationStateDeficient, bandwidthRequested: 4, bandwidthDelta: 1, - layersChanged: true, + availableLayers: nil, + bitrates: bitrates, + targetLayers: expectedTargetLayers, } - result = f.AllocateNextHigher(bitrates) + result, boosted = f.AllocateNextHigher(bitrates) require.Equal(t, expectedResult, result) - require.Equal(t, VideoAllocationStateDeficient, f.lastAllocationState) - require.Equal(t, bitrates[1][0], f.lastAllocationRequestBps) - expectedTargetLayers = VideoLayers{ - spatial: 1, - temporal: 0, - } + require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) + require.True(t, boosted) // next higher, move from (1, 0) -> (1, 3), still deficient though f.currentLayers.spatial = 1 f.currentLayers.temporal = 0 - expectedResult = VideoAllocationResult{ - change: VideoStreamingChangeNone, - state: VideoAllocationStateDeficient, - bandwidthRequested: 5, - bandwidthDelta: 1, - layersChanged: true, - } - result = f.AllocateNextHigher(bitrates) - require.Equal(t, expectedResult, result) - require.Equal(t, VideoAllocationStateDeficient, f.lastAllocationState) - require.Equal(t, bitrates[1][3], f.lastAllocationRequestBps) expectedTargetLayers = VideoLayers{ spatial: 1, temporal: 3, } + expectedResult = VideoAllocation{ + change: VideoStreamingChangeNone, + state: VideoAllocationStateDeficient, + bandwidthRequested: 5, + bandwidthDelta: 1, + availableLayers: nil, + bitrates: bitrates, + targetLayers: expectedTargetLayers, + } + result, boosted = f.AllocateNextHigher(bitrates) + require.Equal(t, expectedResult, result) + require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) + require.True(t, boosted) // next higher, move from (1, 3) -> (2, 1), optimal allocation f.currentLayers.temporal = 3 - expectedResult = VideoAllocationResult{ - change: VideoStreamingChangeNone, - state: VideoAllocationStateOptimal, - bandwidthRequested: 7, - bandwidthDelta: 2, - layersChanged: true, - } - result = f.AllocateNextHigher(bitrates) - require.Equal(t, expectedResult, result) - require.Equal(t, VideoAllocationStateOptimal, f.lastAllocationState) - require.Equal(t, bitrates[2][1], f.lastAllocationRequestBps) expectedTargetLayers = VideoLayers{ spatial: 2, temporal: 1, } + expectedResult = VideoAllocation{ + change: VideoStreamingChangeNone, + state: VideoAllocationStateOptimal, + bandwidthRequested: 7, + bandwidthDelta: 2, + availableLayers: nil, + bitrates: bitrates, + targetLayers: expectedTargetLayers, + } + result, boosted = f.AllocateNextHigher(bitrates) + require.Equal(t, expectedResult, result) + require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) + require.True(t, boosted) - // ask again, should return false as there is no where to go higher + // ask again, should return not boosted as there is no room to go higher f.currentLayers.spatial = 2 f.currentLayers.temporal = 1 - result = f.AllocateNextHigher(bitrates) - require.Equal(t, VideoAllocationResult{}, result) - require.Equal(t, VideoAllocationStateOptimal, f.lastAllocationState) - require.Equal(t, bitrates[2][1], f.lastAllocationRequestBps) + result, boosted = f.AllocateNextHigher(bitrates) + require.Equal(t, expectedResult, result) + require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) + require.False(t, boosted) // turn off everything, allocating next layer should result f.disable() - f.lastAllocationState = VideoAllocationStateDeficient - f.lastAllocationRequestBps = 0 + f.lastAllocation.state = VideoAllocationStateDeficient + f.lastAllocation.bandwidthRequested = 0 - expectedResult = VideoAllocationResult{ - change: VideoStreamingChangeResuming, - state: VideoAllocationStateDeficient, - bandwidthRequested: 2, - bandwidthDelta: 2, - layersChanged: true, - } - result = f.AllocateNextHigher(bitrates) - require.Equal(t, expectedResult, result) - require.Equal(t, VideoAllocationStateDeficient, f.lastAllocationState) - require.Equal(t, bitrates[0][0], f.lastAllocationRequestBps) expectedTargetLayers = VideoLayers{ spatial: 0, temporal: 0, } + expectedResult = VideoAllocation{ + change: VideoStreamingChangeResuming, + state: VideoAllocationStateDeficient, + bandwidthRequested: 2, + bandwidthDelta: 2, + availableLayers: nil, + bitrates: bitrates, + targetLayers: expectedTargetLayers, + } + result, boosted = f.AllocateNextHigher(bitrates) + require.Equal(t, expectedResult, result) + require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) + require.True(t, boosted) } func TestForwarderGetTranslationParamsMuted(t *testing.T) { @@ -622,6 +723,47 @@ func TestForwarderGetTranslationParamsAudio(t *testing.T) { require.NoError(t, err) require.True(t, reflect.DeepEqual(expectedTP, *actualTP)) + // padding only packet after a gap should be forwarded + params = &testutils.TestExtPacketParams{ + IsHead: true, + SequenceNumber: 23337, + Timestamp: 0xabcdef, + SSRC: 0x12345678, + } + extPkt, err = testutils.GetTestExtPacket(params) + + expectedTP = TranslationParams{ + rtp: &TranslationParamsRTP{ + snOrdering: SequenceNumberOrderingGap, + sequenceNumber: 23336, + timestamp: 0xabcdef, + }, + } + actualTP, err = f.GetTranslationParams(extPkt, 0) + require.NoError(t, err) + require.True(t, reflect.DeepEqual(expectedTP, *actualTP)) + + // out-of-order should be forwarded using cache + params = &testutils.TestExtPacketParams{ + IsHead: false, + SequenceNumber: 23336, + Timestamp: 0xabcdef, + SSRC: 0x12345678, + PayloadSize: 20, + } + extPkt, err = testutils.GetTestExtPacket(params) + + expectedTP = TranslationParams{ + rtp: &TranslationParamsRTP{ + snOrdering: SequenceNumberOrderingOutOfOrder, + sequenceNumber: 23335, + timestamp: 0xabcdef, + }, + } + actualTP, err = f.GetTranslationParams(extPkt, 0) + require.NoError(t, err) + require.True(t, reflect.DeepEqual(expectedTP, *actualTP)) + // switching source should lock onto the new source, but sequence number should be contiguous params = &testutils.TestExtPacketParams{ IsHead: true, @@ -635,7 +777,7 @@ func TestForwarderGetTranslationParamsAudio(t *testing.T) { expectedTP = TranslationParams{ rtp: &TranslationParamsRTP{ snOrdering: SequenceNumberOrderingContiguous, - sequenceNumber: 23335, + sequenceNumber: 23337, timestamp: 0xabcdf0, }, } @@ -898,6 +1040,46 @@ func TestForwarderGetTranslationParamsVideo(t *testing.T) { require.NoError(t, err) require.True(t, reflect.DeepEqual(expectedTP, *actualTP)) + // padding only packet after a gap should be forwarded + params = &testutils.TestExtPacketParams{ + IsHead: true, + SequenceNumber: 23339, + Timestamp: 0xabcdef, + SSRC: 0x12345678, + } + extPkt, err = testutils.GetTestExtPacket(params) + + expectedTP = TranslationParams{ + rtp: &TranslationParamsRTP{ + snOrdering: SequenceNumberOrderingGap, + sequenceNumber: 23337, + timestamp: 0xabcdef, + }, + } + actualTP, err = f.GetTranslationParams(extPkt, 0) + require.NoError(t, err) + require.True(t, reflect.DeepEqual(expectedTP, *actualTP)) + + // out-of-order should be forwarded using cache, even if it is padding only + params = &testutils.TestExtPacketParams{ + IsHead: false, + SequenceNumber: 23338, + Timestamp: 0xabcdef, + SSRC: 0x12345678, + } + extPkt, err = testutils.GetTestExtPacket(params) + + expectedTP = TranslationParams{ + rtp: &TranslationParamsRTP{ + snOrdering: SequenceNumberOrderingOutOfOrder, + sequenceNumber: 23336, + timestamp: 0xabcdef, + }, + } + actualTP, err = f.GetTranslationParams(extPkt, 0) + require.NoError(t, err) + require.True(t, reflect.DeepEqual(expectedTP, *actualTP)) + // 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{ @@ -932,7 +1114,7 @@ func TestForwarderGetTranslationParamsVideo(t *testing.T) { expectedTP = TranslationParams{ rtp: &TranslationParamsRTP{ snOrdering: SequenceNumberOrderingContiguous, - sequenceNumber: 23336, + sequenceNumber: 23338, timestamp: 0xabcdf0, }, vp8: &TranslationParamsVP8{ diff --git a/pkg/sfu/streamallocator.go b/pkg/sfu/streamallocator.go index bd95d92d..9949ccfd 100644 --- a/pkg/sfu/streamallocator.go +++ b/pkg/sfu/streamallocator.go @@ -337,11 +337,17 @@ func (s *StreamAllocator) onSubscriptionChanged(downTrack *DownTrack) { } // called when subscribed layers changes (limiting max layers) -func (s *StreamAllocator) onSubscribedLayersChanged(downTrack *DownTrack, layers VideoLayers) { +func (s *StreamAllocator) onSubscribedLayersChanged(downTrack *DownTrack, layers VideoLayers, layerPref LayerPreference) { s.postEvent(Event{ Signal: SignalSubscribedLayersChange, DownTrack: downTrack, - Data: layers, + Data: struct { + layers VideoLayers + layerPref LayerPreference + }{ + layers: layers, + layerPref: layerPref, + }, }) } @@ -595,8 +601,11 @@ func (s *StreamAllocator) handleSignalSubscribedLayersChange(event *Event) { return } - layers := event.Data.(VideoLayers) - track.UpdateMaxLayers(layers) + data := event.Data.(struct { + layers VideoLayers + layerPref LayerPreference + }) + track.UpdatePriority(data.layers, data.layerPref) sort.Sort(s.videoTracksSorted) s.allocateTrack(track) @@ -638,7 +647,7 @@ func (s *StreamAllocator) handleSignalSendProbe(event *Event) { func (s *StreamAllocator) setState(state State) { if s.state != state { - s.logger.Infow("state change", "participant", s.participantID, "from", s.state.String(), "to", state.String()) + s.logger.Infow("state change", "participant", s.participantID, "from", s.state, "to", state) } s.state = state @@ -699,8 +708,8 @@ func (s *StreamAllocator) allocateTrack(track *Track) { // if not deficient, free pass allocate track if s.state == StateStable { update := NewStreamStateUpdate() - result := track.Allocate(ChannelCapacityInfinity) - update.HandleStreamingChange(result.change, track) + allocation := track.Allocate(ChannelCapacityInfinity) + update.HandleStreamingChange(allocation.change, track) s.maybeSendUpdate(update) return } @@ -712,6 +721,7 @@ func (s *StreamAllocator) allocateTrack(track *Track) { if t == track { hpTracks = s.videoTracksSorted[:idx] lpTracks = s.videoTracksSorted[idx+1:] + break } } @@ -729,11 +739,11 @@ func (s *StreamAllocator) allocateTrack(track *Track) { // update := NewStreamStateUpdate() - result := track.TryAllocate(lpExpectedBps) + allocation := track.TryAllocate(lpExpectedBps) - update.HandleStreamingChange(result.change, track) + update.HandleStreamingChange(allocation.change, track) - delta := lpExpectedBps - result.bandwidthDelta + delta := lpExpectedBps - allocation.bandwidthDelta if delta > 0 { // gotten some bits back, check if any deficient higher priority track can make use of it delta = s.tryAllocateTracks(hpTracks, delta, update) @@ -746,10 +756,10 @@ func (s *StreamAllocator) allocateTrack(track *Track) { } for _, t := range lpTracks { - result := t.Allocate(delta) - update.HandleStreamingChange(result.change, t) + allocation := t.Allocate(delta) + update.HandleStreamingChange(allocation.change, t) - delta -= result.bandwidthRequested + delta -= allocation.bandwidthRequested if delta < 0 { delta = 0 } @@ -783,10 +793,10 @@ func (s *StreamAllocator) tryAllocateTracks(tracks []*Track, additionalBps int64 continue } - result := t.TryAllocate(additionalBps) - update.HandleStreamingChange(result.change, t) + allocation := t.TryAllocate(additionalBps) + update.HandleStreamingChange(allocation.change, t) - additionalBps -= result.bandwidthDelta + additionalBps -= allocation.bandwidthDelta if additionalBps <= 0 { // used up all the extra bits break @@ -831,12 +841,12 @@ func (s *StreamAllocator) allocateAllTracks() { // - adjust layers up or down // - pause if there is not enough capacity for any layer // - result := track.Allocate(availableChannelCapacity) + allocation := track.Allocate(availableChannelCapacity) - update.HandleStreamingChange(result.change, track) + update.HandleStreamingChange(allocation.change, track) - availableChannelCapacity -= result.bandwidthRequested - if availableChannelCapacity < 0 || result.state == VideoAllocationStateDeficient { + availableChannelCapacity -= allocation.bandwidthRequested + if availableChannelCapacity < 0 || allocation.state == VideoAllocationStateDeficient { // // This is walking down tracks in priortized order. // Once one of those streams do not fit, set @@ -939,12 +949,12 @@ func (s *StreamAllocator) maybeBoostLayer() { continue } - result := track.AllocateNextHigher() - if result.layersChanged { + allocation, boosted := track.AllocateNextHigher() + if boosted { s.lastBoostTime = time.Now() update := NewStreamStateUpdate() - update.HandleStreamingChange(result.change, track) + update.HandleStreamingChange(allocation.change, track) s.maybeSendUpdate(update) break @@ -1088,14 +1098,16 @@ type Track struct { lastHighestSN uint32 lastPacketsLost uint32 - maxLayers VideoLayers + priority int32 } func newTrack(downTrack *DownTrack) *Track { - return &Track{ + t := &Track{ downTrack: downTrack, - maxLayers: downTrack.MaxLayers(), } + t.UpdatePriority(downTrack.MaxLayers(), downTrack.GetLayerPreference()) + + return t } func (t *Track) DownTrack() *DownTrack { @@ -1125,8 +1137,17 @@ func (t *Track) UpdatePacketStats(rr *rtcp.ReceiverReport) { } } -func (t *Track) UpdateMaxLayers(layers VideoLayers) { - t.maxLayers = layers +func (t *Track) UpdatePriority(layers VideoLayers, pref LayerPreference) { + switch pref { + case LayerPreferenceSpatial: + t.priority = layers.spatial*10 + layers.temporal + case LayerPreferenceTemporal: + t.priority = layers.temporal*10 + layers.spatial + } +} + +func (t *Track) Priority() int32 { + return t.priority } func (t *Track) GetPacketStats() (uint32, uint32) { @@ -1137,11 +1158,11 @@ func (t *Track) WritePaddingRTP(bytesToSend int) int { return t.downTrack.WritePaddingRTP(bytesToSend) } -func (t *Track) Allocate(availableChannelCapacity int64) VideoAllocationResult { +func (t *Track) Allocate(availableChannelCapacity int64) VideoAllocation { return t.downTrack.Allocate(availableChannelCapacity) } -func (t *Track) TryAllocate(additionalChannelCapacity int64) VideoAllocationResult { +func (t *Track) TryAllocate(additionalChannelCapacity int64) VideoAllocation { return t.downTrack.TryAllocate(additionalChannelCapacity) } @@ -1149,16 +1170,16 @@ func (t *Track) FinalizeAllocate() { t.downTrack.FinalizeAllocate() } -func (t *Track) AllocateNextHigher() VideoAllocationResult { +func (t *Track) AllocateNextHigher() (VideoAllocation, bool) { return t.downTrack.AllocateNextHigher() } func (t *Track) IsDeficient() bool { - return t.downTrack.AllocationState() == VideoAllocationStateDeficient + return t.downTrack.LastAllocation().state == VideoAllocationStateDeficient } func (t *Track) BandwidthRequested() int64 { - return t.downTrack.AllocationBandwidth() + return t.downTrack.LastAllocation().bandwidthRequested } //------------------------------------------------ @@ -1172,9 +1193,9 @@ func (t *Track) BandwidthRequested() int64 { // OR // It is left up to the clients to subscribe explicitly to the quality they want. // -// This sorter is prioritizing tracks by max layer subscribed. But, with simple -// tracks, there is only one layer. But, it is possible they should be higher -// priority, for e.g. screen share track. +// This sorter is prioritizing tracks by max layer subscribed and layer preference. +// But, with simple tracks, there is only one layer. But, it is possible they should +// be higher priority, for e.g. screen share track. // LK-TODO-END type TrackSorter []*Track @@ -1187,19 +1208,7 @@ func (t TrackSorter) Swap(i, j int) { } func (t TrackSorter) Less(i, j int) bool { - // highest spatial layers have higher priority - if t[i].maxLayers.spatial != t[j].maxLayers.spatial { - return t[i].maxLayers.spatial > t[j].maxLayers.spatial - } - - // highest temporal layers have priority if max spatial layers match - if t[i].maxLayers.temporal != t[j].maxLayers.temporal { - return t[i].maxLayers.temporal > t[j].maxLayers.temporal - } - - // use track id to keep ordering if nothing else changes - // LK-TODO: ideally should be sorting, compare and then re-allocate only if order changed - return t[i].ID() < t[j].ID() + return t[i].priority > t[j].priority } //------------------------------------------------