From 0bbed7f0bd71d53144bee36f741667a21a900611 Mon Sep 17 00:00:00 2001 From: Raja Subramanian Date: Thu, 17 Feb 2022 11:03:23 +0530 Subject: [PATCH] Use padding for probing (#434) * WIP commit * WIP commit * WIP commit * WIP commit * WIP commit * WIP commit * WIP commit * WIP commit * Clean up * Remove debug * Remove unneeded change * fix test * Remove incorrect comment * Reset probe after estimate trends down --- pkg/config/config.go | 15 +- pkg/sfu/buffer/bucket.go | 2 +- pkg/sfu/buffer/buffer.go | 5 - pkg/sfu/downtrack.go | 16 +- pkg/sfu/forwarder.go | 132 +++++++- pkg/sfu/forwarder_test.go | 39 ++- pkg/sfu/prober.go | 72 ++++- pkg/sfu/receiver.go | 6 +- pkg/sfu/rtpmunger.go | 1 + pkg/sfu/rtpmunger_test.go | 14 +- pkg/sfu/streamallocator.go | 595 ++++++++++++++++++++++++++++--------- 11 files changed, 690 insertions(+), 207 deletions(-) diff --git a/pkg/config/config.go b/pkg/config/config.go index 3170fffd..78bd55f7 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -24,6 +24,13 @@ var DefaultStunServers = []string{ "stun1.l.google.com:19302", } +type CongestionControlProbeMode string + +const ( + CongestionControlProbeModePadding CongestionControlProbeMode = "padding" + CongestionControlProbeModeMedia = "media" +) + type Config struct { Port uint32 `yaml:"port"` PrometheusPort uint32 `yaml:"prometheus_port,omitempty"` @@ -86,9 +93,10 @@ type PLIThrottleConfig struct { } type CongestionControlConfig struct { - Enabled bool `yaml:"enabled"` - AllowPause bool `yaml:"allow_pause"` - UseSendSideBWE bool `yaml:"send_side_bandwidth_estimation,omitempty"` + Enabled bool `yaml:"enabled"` + AllowPause bool `yaml:"allow_pause"` + UseSendSideBWE bool `yaml:"send_side_bandwidth_estimation,omitempty"` + ProbeMode CongestionControlProbeMode `yaml:"padding_mode,omitempty"` } type AudioConfig struct { @@ -188,6 +196,7 @@ func NewConfig(confString string, c *cli.Context) (*Config, error) { CongestionControl: CongestionControlConfig{ Enabled: true, AllowPause: true, + ProbeMode: CongestionControlProbeModePadding, }, }, Audio: AudioConfig{ diff --git a/pkg/sfu/buffer/bucket.go b/pkg/sfu/buffer/bucket.go index 9c9dee3d..094df8b4 100644 --- a/pkg/sfu/buffer/bucket.go +++ b/pkg/sfu/buffer/bucket.go @@ -34,7 +34,7 @@ func (b *Bucket) AddPacket(pkt []byte) ([]byte, error) { } diff := sn - b.headSN if diff == 0 || diff > (1<<15) { - // duplicate of lsat packet or out-of-order + // duplicate of last packet or out-of-order return b.set(sn, pkt) } b.headSN = sn diff --git a/pkg/sfu/buffer/buffer.go b/pkg/sfu/buffer/buffer.go index 4bd866cd..45c6f1c9 100644 --- a/pkg/sfu/buffer/buffer.go +++ b/pkg/sfu/buffer/buffer.go @@ -510,11 +510,6 @@ func (b *Buffer) getExtPacket(rawPacket []byte, rtpPacket *rtp.Packet, arrivalTi ep.Payload = vp8Packet ep.KeyFrame = vp8Packet.IsKeyFrame temporalLayer = int32(vp8Packet.TID) - /* - if ep.KeyFrame { - b.logger.Debugw("SA_DEBUG key frame", "ssrc", b.mediaSSRC) // REMOVE - } - */ case "video/h264": ep.KeyFrame = IsH264Keyframe(rtpPacket.Payload) } diff --git a/pkg/sfu/downtrack.go b/pkg/sfu/downtrack.go index 12acb75f..aeaca9b0 100644 --- a/pkg/sfu/downtrack.go +++ b/pkg/sfu/downtrack.go @@ -302,7 +302,6 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) error { tp, err := d.forwarder.GetTranslationParams(extPkt, layer) if tp.shouldSendPLI { - //d.logger.Debugw("SA_DEBUG Forwarder SendPLI", "layer", layer) // REMOVE d.lastPli.set(time.Now().UnixNano()) d.receiver.SendPLI(layer) } @@ -636,7 +635,7 @@ func (d *DownTrack) IsDeficient() bool { } func (d *DownTrack) BandwidthRequested() int64 { - return d.forwarder.BandwidthRequested() + return d.forwarder.BandwidthRequested(d.receiver.GetBitrateTemporalCumulative()) } func (d *DownTrack) DistanceToDesired() int32 { @@ -671,8 +670,12 @@ func (d *DownTrack) FinalizeAllocate() VideoAllocation { return d.forwarder.FinalizeAllocate(d.receiver.GetBitrateTemporalCumulative()) } -func (d *DownTrack) AllocateNextHigher() (VideoAllocation, bool) { - return d.forwarder.AllocateNextHigher(d.receiver.GetBitrateTemporalCumulative()) +func (d *DownTrack) AllocateNextHigher(availableChannelCapacity int64) (VideoAllocation, bool) { + return d.forwarder.AllocateNextHigher(availableChannelCapacity, d.receiver.GetBitrateTemporalCumulative()) +} + +func (d *DownTrack) GetNextHigherTransition() (VideoTransition, bool) { + return d.forwarder.GetNextHigherTransition(d.receiver.GetBitrateTemporalCumulative()) } func (d *DownTrack) Pause() VideoAllocation { @@ -878,7 +881,6 @@ func (d *DownTrack) handleRTCP(bytes []byte) { targetLayers := d.forwarder.TargetLayers() if targetLayers != InvalidLayers { d.lastPli.set(time.Now().UnixNano()) - //d.logger.Debugw("SA_DEBUG Subscriber RTCP SendPLI", "layer", targetLayers.spatial) // REMOVE d.receiver.SendPLI(targetLayers.spatial) pliOnce = false } @@ -978,6 +980,10 @@ func (d *DownTrack) retransmitPackets(nackedPackets []packetMeta) { defer PacketFactory.Put(src) for _, meta := range nackedPackets { + if !d.forwarder.IsRtxAllowed(int32(meta.layer)) { + continue + } + if pool != nil { PacketFactory.Put(pool) pool = nil diff --git a/pkg/sfu/forwarder.go b/pkg/sfu/forwarder.go index 974d5efb..7b303d1c 100644 --- a/pkg/sfu/forwarder.go +++ b/pkg/sfu/forwarder.go @@ -359,11 +359,15 @@ func (f *Forwarder) IsDeficient() bool { return f.lastAllocation.state == VideoAllocationStateDeficient } -func (f *Forwarder) BandwidthRequested() int64 { +func (f *Forwarder) BandwidthRequested(brs Bitrates) int64 { f.lock.RLock() defer f.lock.RUnlock() - return f.lastAllocation.bandwidthRequested + if f.targetLayers == InvalidLayers { + return 0 + } + + return brs[f.targetLayers.spatial][f.targetLayers.temporal] } func (f *Forwarder) DistanceToDesired() int32 { @@ -675,12 +679,12 @@ func (f *Forwarder) ProvisionalAllocateGetBestWeightedTransition() VideoTransiti // This is called when a track needs a change (could be mute/unmute, subscribed layers changed, published layers changed) // when channel is congested. // - // The goal is to keep all tracks streaming as much as possible. So, the track that needs a change needs bits to be unpaused. + // The goal is to keep all tracks streaming as much as possible. So, the track that needs a change needs bandwidth to be unpaused. // // This tries to figure out how much this track can contribute back to the pool to enable the track that needs to be unpaused. - // 1. Track muted OR feed dry - can contribute everything back in case it was using bits. + // 1. Track muted OR feed dry - can contribute everything back in case it was using bandwidth. // 2. Look at all possible down transitions from current target and find the best offer. - // Best offer is calculated as bits saved moving to a down layer divided by cost. + // Best offer is calculated as bandwidth saved moving to a down layer divided by cost. // Cost has two components // a. Transition cost: Spatial layer switch is expensive due to key frame requirement, but temporal layer switch is free. // b. Quality cost: The farther away from desired layers, the higher the quality cost. @@ -896,7 +900,7 @@ func (f *Forwarder) FinalizeAllocate(brs Bitrates) VideoAllocation { return f.lastAllocation } -func (f *Forwarder) AllocateNextHigher(brs Bitrates) (VideoAllocation, bool) { +func (f *Forwarder) AllocateNextHigher(availableChannelCapacity int64, brs Bitrates) (VideoAllocation, bool) { f.lock.Lock() defer f.lock.Unlock() @@ -924,6 +928,11 @@ func (f *Forwarder) AllocateNextHigher(brs Bitrates) (VideoAllocation, bool) { return f.lastAllocation, false } + alreadyAllocated := int64(0) + if f.targetLayers != InvalidLayers { + alreadyAllocated = brs[f.targetLayers.spatial][f.targetLayers.temporal] + } + // try moving temporal layer up in currently streaming spatial layer if f.targetLayers != InvalidLayers { for t := f.targetLayers.temporal + 1; t <= f.maxLayers.temporal; t++ { @@ -932,6 +941,12 @@ func (f *Forwarder) AllocateNextHigher(brs Bitrates) (VideoAllocation, bool) { continue } + if bandwidthRequested-alreadyAllocated > availableChannelCapacity { + // next higher available layer does not fit, return + f.lastAllocation.change = VideoStreamingChangeNone + return f.lastAllocation, false + } + state := VideoAllocationStateOptimal if bandwidthRequested != optimalBandwidthNeeded { state = VideoAllocationStateDeficient @@ -942,7 +957,7 @@ func (f *Forwarder) AllocateNextHigher(brs Bitrates) (VideoAllocation, bool) { state: state, change: VideoStreamingChangeNone, bandwidthRequested: bandwidthRequested, - bandwidthDelta: bandwidthRequested - f.lastAllocation.bandwidthRequested, + bandwidthDelta: bandwidthRequested - alreadyAllocated, availableLayers: f.availableLayers, bitrates: brs, targetLayers: targetLayers, @@ -961,6 +976,12 @@ func (f *Forwarder) AllocateNextHigher(brs Bitrates) (VideoAllocation, bool) { continue } + if bandwidthRequested-alreadyAllocated > availableChannelCapacity { + // next higher available layer does not fit, return + f.lastAllocation.change = VideoStreamingChangeNone + return f.lastAllocation, false + } + state := VideoAllocationStateOptimal if bandwidthRequested != optimalBandwidthNeeded { state = VideoAllocationStateDeficient @@ -976,7 +997,7 @@ func (f *Forwarder) AllocateNextHigher(brs Bitrates) (VideoAllocation, bool) { state: state, change: change, bandwidthRequested: bandwidthRequested, - bandwidthDelta: bandwidthRequested - f.lastAllocation.bandwidthRequested, + bandwidthDelta: bandwidthRequested - alreadyAllocated, availableLayers: f.availableLayers, bitrates: brs, targetLayers: targetLayers, @@ -991,6 +1012,74 @@ func (f *Forwarder) AllocateNextHigher(brs Bitrates) (VideoAllocation, bool) { return f.lastAllocation, false } +func (f *Forwarder) GetNextHigherTransition(brs Bitrates) (VideoTransition, bool) { + f.lock.Lock() + defer f.lock.Unlock() + + if f.kind == webrtc.RTPCodecTypeAudio { + return VideoTransition{}, false + } + + // if not deficient, nothing to do + if f.lastAllocation.state != VideoAllocationStateDeficient { + return VideoTransition{}, false + } + + // if targets are still pending, don't increase + if f.targetLayers != InvalidLayers && f.targetLayers != f.currentLayers { + return VideoTransition{}, false + } + + optimalBandwidthNeeded := f.getOptimalBandwidthNeeded(brs) + if optimalBandwidthNeeded == 0 { + // either feed is dry or awaiting measurement, don't hunt for higher + return VideoTransition{}, false + } + + alreadyAllocated := int64(0) + if f.targetLayers != InvalidLayers { + alreadyAllocated = brs[f.targetLayers.spatial][f.targetLayers.temporal] + } + + // try moving temporal layer up in currently streaming spatial layer + if f.targetLayers != InvalidLayers { + for t := f.targetLayers.temporal + 1; t <= f.maxLayers.temporal; t++ { + bandwidthRequested := brs[f.targetLayers.spatial][t] + if bandwidthRequested == 0 { + continue + } + + transition := VideoTransition{ + from: f.targetLayers, + to: VideoLayers{spatial: f.targetLayers.spatial, temporal: t}, + bandwidthDelta: bandwidthRequested - alreadyAllocated, + } + + return transition, true + } + } + + // try moving spatial layer up if temporal layer move up is not available + for s := f.targetLayers.spatial + 1; s <= f.maxLayers.spatial; s++ { + for t := int32(0); t <= f.maxLayers.temporal; t++ { + bandwidthRequested := brs[s][t] + if bandwidthRequested == 0 { + continue + } + + transition := VideoTransition{ + from: f.targetLayers, + to: VideoLayers{spatial: s, temporal: t}, + bandwidthDelta: bandwidthRequested - alreadyAllocated, + } + + return transition, true + } + } + + return VideoTransition{}, false +} + func (f *Forwarder) Pause(brs Bitrates) VideoAllocation { f.lock.Lock() defer f.lock.Unlock() @@ -1049,6 +1138,27 @@ func (f *Forwarder) Resync() { f.lastSSRC = 0 } +func (f *Forwarder) IsRtxAllowed(layer int32) bool { + f.lock.RLock() + defer f.lock.RUnlock() + + // + // Curb RTX when deficient for two cases + // 1. Target layer is lower than current layer. When current hits target, a key frame should flush the decoder. + // 2. Requested layer is higher than current. Current layer's key frame should have flushed encoder. + // Remote might ask for older layer because of its jitter buffer, but let it starve as channel is already congested. + // + // Without the curb, when congestion hits, RTX rate could be so high that it further congests the channel. + // + if FlagPauseOnDowngrade && + f.lastAllocation.state == VideoAllocationStateDeficient && + (f.targetLayers.spatial < f.currentLayers.spatial || layer > f.currentLayers.spatial) { + return false + } + + return true +} + func (f *Forwarder) GetTranslationParams(extPkt *buffer.ExtPacket, layer int32) (*TranslationParams, error) { f.lock.Lock() defer f.lock.Unlock() @@ -1128,7 +1238,6 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in if f.targetLayers.spatial == layer { if extPkt.KeyFrame { // lock to target layer - //f.logger.Debugw("SA_DEBUG locking to target", "current", f.currentLayers, "target", f.targetLayers) // REMOVE f.currentLayers.spatial = f.targetLayers.spatial if f.currentLayers.spatial == f.maxLayers.spatial { tp.isSwitchingToMaxLayer = true @@ -1145,10 +1254,7 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in return tp, nil } - if FlagPauseOnDowngrade && - f.targetLayers.spatial < f.currentLayers.spatial && - f.targetLayers.spatial < f.maxLayers.spatial && - f.lastAllocation.state == VideoAllocationStateDeficient { + if FlagPauseOnDowngrade && f.targetLayers.spatial < f.currentLayers.spatial && f.lastAllocation.state == VideoAllocationStateDeficient { // // If target layer is lower than both the current and // maximum subscribed layer, it is due to bandwidth diff --git a/pkg/sfu/forwarder_test.go b/pkg/sfu/forwarder_test.go index 841b3fba..4ca99678 100644 --- a/pkg/sfu/forwarder_test.go +++ b/pkg/sfu/forwarder_test.go @@ -696,7 +696,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) { {0, 7, 0, 0}, } - result, boosted := f.AllocateNextHigher(bitrates) + result, boosted := f.AllocateNextHigher(ChannelCapacityInfinity, bitrates) require.Equal(t, VideoAllocationDefault, result) // no layer for audio require.False(t, boosted) @@ -704,7 +704,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) { // when not in deficient state, does not boost f.lastAllocation.state = VideoAllocationStateNone - result, boosted = f.AllocateNextHigher(bitrates) + result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates) require.Equal(t, VideoAllocationDefault, result) require.False(t, boosted) @@ -721,14 +721,14 @@ func TestForwarderAllocateNextHigher(t *testing.T) { targetLayers: InvalidLayers, distanceToDesired: 0, } - result, boosted = f.AllocateNextHigher(bitrates) + result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, 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, boosted = f.AllocateNextHigher(bitrates) + result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.False(t, boosted) @@ -747,7 +747,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) { targetLayers: InvalidLayers, distanceToDesired: 0, } - result, boosted = f.AllocateNextHigher(emptyBitrates) + result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, emptyBitrates) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.False(t, boosted) @@ -767,7 +767,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) { targetLayers: expectedTargetLayers, distanceToDesired: 3, } - result, boosted = f.AllocateNextHigher(bitrates) + result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) @@ -789,7 +789,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) { targetLayers: expectedTargetLayers, distanceToDesired: 2, } - result, boosted = f.AllocateNextHigher(bitrates) + result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) @@ -812,7 +812,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) { targetLayers: expectedTargetLayers, distanceToDesired: 1, } - result, boosted = f.AllocateNextHigher(bitrates) + result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) @@ -834,7 +834,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) { targetLayers: expectedTargetLayers, distanceToDesired: 0, } - result, boosted = f.AllocateNextHigher(bitrates) + result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) @@ -843,7 +843,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(bitrates) + result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) @@ -868,11 +868,28 @@ func TestForwarderAllocateNextHigher(t *testing.T) { targetLayers: expectedTargetLayers, distanceToDesired: 4, } - result, boosted = f.AllocateNextHigher(bitrates) + result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) require.True(t, boosted) + + // no new available capacity cannot bump up layer + expectedResult = VideoAllocation{ + state: VideoAllocationStateDeficient, + change: VideoStreamingChangeNone, + bandwidthRequested: 2, + bandwidthDelta: 2, + availableLayers: nil, + bitrates: bitrates, + targetLayers: expectedTargetLayers, + distanceToDesired: 4, + } + result, boosted = f.AllocateNextHigher(0, bitrates) + require.Equal(t, expectedResult, result) + require.Equal(t, expectedResult, f.lastAllocation) + require.Equal(t, expectedTargetLayers, f.TargetLayers()) + require.False(t, boosted) } func TestForwarderPause(t *testing.T) { diff --git a/pkg/sfu/prober.go b/pkg/sfu/prober.go index 63d39cce..893f35da 100644 --- a/pkg/sfu/prober.go +++ b/pkg/sfu/prober.go @@ -109,6 +109,7 @@ package sfu import ( "fmt" "sync" + "sync/atomic" "time" "github.com/gammazero/deque" @@ -122,11 +123,14 @@ type ProberParams struct { type Prober struct { logger logger.Logger + clusterId uint32 + clustersMu sync.RWMutex clusters deque.Deque activeCluster *Cluster - onSendProbe func(bytesToSend int) + onSendProbe func(bytesToSend int) + onProbeClusterDone func(info ProbeClusterInfo) } func NewProber(params ProberParams) *Prober { @@ -145,30 +149,43 @@ func (p *Prober) IsRunning() bool { } func (p *Prober) Reset() { - p.clustersMu.Lock() - defer p.clustersMu.Unlock() + var info ProbeClusterInfo + p.clustersMu.Lock() if p.activeCluster != nil { p.logger.Debugw("resetting active cluster", "cluster", p.activeCluster.String()) + info = p.activeCluster.GetInfo() } p.clusters.Clear() p.activeCluster = nil + p.clustersMu.Unlock() + + if p.onProbeClusterDone != nil && info.BytesSent != 0 { + p.onProbeClusterDone(info) + } } func (p *Prober) OnSendProbe(f func(bytesToSend int)) { p.onSendProbe = f } -func (p *Prober) AddCluster(desiredRateBps int, expectedRateBps int, minDuration time.Duration, maxDuration time.Duration) { +func (p *Prober) OnProbeClusterDone(f func(info ProbeClusterInfo)) { + p.onProbeClusterDone = f +} + +func (p *Prober) AddCluster(desiredRateBps int, expectedRateBps int, minDuration time.Duration, maxDuration time.Duration) ProbeClusterId { if desiredRateBps <= 0 { - return + return ProbeClusterIdInvalid } - cluster := NewCluster(desiredRateBps, expectedRateBps, minDuration, maxDuration) + clusterId := ProbeClusterId(atomic.AddUint32(&p.clusterId, 1)) + cluster := NewCluster(clusterId, desiredRateBps, expectedRateBps, minDuration, maxDuration) p.logger.Debugw("cluster added", "cluster", cluster.String()) p.pushBackClusterAndMaybeStart(cluster) + + return clusterId } func (p *Prober) PacketSent(size int) { @@ -251,10 +268,15 @@ func (p *Prober) run() { return } - cluster.Process(p) + cluster.Process(p.onSendProbe) if cluster.IsFinished() { p.logger.Debugw("cluster finished", "cluster", cluster.String()) + + if p.onProbeClusterDone != nil { + p.onProbeClusterDone(cluster.GetInfo()) + } + p.popFrontCluster(cluster) continue } @@ -263,6 +285,18 @@ func (p *Prober) run() { // --------------------------------- +type ProbeClusterId uint32 + +const ( + ProbeClusterIdInvalid ProbeClusterId = 0 +) + +type ProbeClusterInfo struct { + Id ProbeClusterId + BytesSent int + Duration time.Duration +} + type Cluster struct { // LK-TODO-START // Check if we can operate at cluster level without a lock. @@ -272,6 +306,7 @@ type Cluster struct { // LK-TODO-END lock sync.RWMutex + id ProbeClusterId desiredBytes int minDuration time.Duration maxDuration time.Duration @@ -283,7 +318,7 @@ type Cluster struct { startTime time.Time } -func NewCluster(desiredRateBps int, expectedRateBps int, minDuration time.Duration, maxDuration time.Duration) *Cluster { +func NewCluster(id ProbeClusterId, desiredRateBps int, expectedRateBps int, minDuration time.Duration, maxDuration time.Duration) *Cluster { minDurationMs := minDuration.Milliseconds() desiredBytes := int((int64(desiredRateBps)*minDurationMs/time.Second.Milliseconds() + 7) / 8) expectedBytes := int((int64(expectedRateBps)*minDurationMs/time.Second.Milliseconds() + 7) / 8) @@ -292,6 +327,7 @@ func NewCluster(desiredRateBps int, expectedRateBps int, minDuration time.Durati numProbes := (desiredBytes - expectedBytes + 999) / 1000 sleepDurationMicroSeconds := int(float64(minDurationMs*1000)/float64(numProbes) + 0.5) c := &Cluster{ + id: id, desiredBytes: desiredBytes, minDuration: minDuration, maxDuration: maxDuration, @@ -349,7 +385,18 @@ func (c *Cluster) IsFinished() bool { return false } -func (c *Cluster) Process(p *Prober) { +func (c *Cluster) GetInfo() ProbeClusterInfo { + c.lock.RLock() + defer c.lock.RUnlock() + + return ProbeClusterInfo{ + Id: c.id, + BytesSent: c.bytesSentProbe + c.bytesSentNonProbe, + Duration: time.Since(c.startTime), + } +} + +func (c *Cluster) Process(onSendProbe func(bytesToSend int)) { c.lock.RLock() timeElapsed := time.Since(c.startTime) @@ -379,8 +426,8 @@ func (c *Cluster) Process(p *Prober) { bytesShortFall = ((bytesShortFall + 274) / 275) * 275 c.lock.RUnlock() - if bytesShortFall > 0 && p.onSendProbe != nil { - p.onSendProbe(bytesShortFall) + if bytesShortFall > 0 && onSendProbe != nil { + onSendProbe(bytesShortFall) } // LK-TODO look at adapting sleep time based on how many bytes and how much time is left @@ -392,7 +439,8 @@ func (c *Cluster) String() string { activeTimeMs = time.Since(c.startTime).Milliseconds() } - return fmt.Sprintf("bytes: desired %d / probe %d / non-probe %d / remaining: %d, time(ms): active %d / min %d / max %d", + return fmt.Sprintf("id: %d, bytes: desired %d / probe %d / non-probe %d / remaining: %d, time(ms): active %d / min %d / max %d", + c.id, c.desiredBytes, c.bytesSentProbe, c.bytesSentNonProbe, diff --git a/pkg/sfu/receiver.go b/pkg/sfu/receiver.go index d96be04d..9b58e477 100644 --- a/pkg/sfu/receiver.go +++ b/pkg/sfu/receiver.go @@ -7,6 +7,7 @@ import ( "sync/atomic" "time" + "github.com/go-logr/logr" "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" "github.com/pion/rtcp" @@ -242,7 +243,8 @@ func (w *WebRTCReceiver) AddUpTrack(track *webrtc.TrackRemote, buff *buffer.Buff return } - buff.SetLogger(w.logger) + layer := RidToLayer(track.RID()) + buff.SetLogger(logger.Logger(logr.Logger(w.logger).WithValues("layer", layer))) buff.OnFeedback(w.sendRTCP) var duration time.Duration @@ -260,7 +262,6 @@ func (w *WebRTCReceiver) AddUpTrack(track *webrtc.TrackRemote, buff *buffer.Buff buff.SetPLIThrottle(duration.Nanoseconds()) } - layer := RidToLayer(track.RID()) w.upTrackMu.Lock() w.upTracks[layer] = track w.upTrackMu.Unlock() @@ -391,7 +392,6 @@ func (w *WebRTCReceiver) SendPLI(layer int32) { return } - //w.logger.Debugw("SA_DEBUG, PLI request", "layer", layer) // REMOVE buff.SendPLI() } diff --git a/pkg/sfu/rtpmunger.go b/pkg/sfu/rtpmunger.go index 095ebfd0..938d2ef8 100644 --- a/pkg/sfu/rtpmunger.go +++ b/pkg/sfu/rtpmunger.go @@ -88,6 +88,7 @@ func (r *RTPMunger) PacketDropped(extPkt *buffer.ExtPacket) { r.highestIncomingSN = extPkt.Packet.SequenceNumber r.snOffset += 1 + r.lastSN = extPkt.Packet.SequenceNumber - r.snOffset } func (r *RTPMunger) UpdateAndGetSnTs(extPkt *buffer.ExtPacket) (*TranslationParamsRTP, error) { diff --git a/pkg/sfu/rtpmunger_test.go b/pkg/sfu/rtpmunger_test.go index 1e4d175d..203729da 100644 --- a/pkg/sfu/rtpmunger_test.go +++ b/pkg/sfu/rtpmunger_test.go @@ -85,9 +85,9 @@ func TestPacketDropped(t *testing.T) { } extPkt, _ := testutils.GetTestExtPacket(params) r.SetLastSnTs(extPkt) - require.True(t, r.highestIncomingSN == 23332) - require.True(t, r.lastSN == 23333) - require.True(t, r.lastTS == 0xabcdef) + require.Equal(t, r.highestIncomingSN, uint16(23332)) + require.Equal(t, r.lastSN, uint16(23333)) + require.Equal(t, r.lastTS, uint32(0xabcdef)) require.EqualValues(t, 0, r.snOffset) require.EqualValues(t, 0, r.tsOffset) @@ -99,8 +99,8 @@ func TestPacketDropped(t *testing.T) { } extPkt, _ = testutils.GetTestExtPacket(params) r.PacketDropped(extPkt) - require.True(t, r.highestIncomingSN == 23332) - require.True(t, r.lastSN == 23333) + require.Equal(t, r.highestIncomingSN, uint16(23332)) + require.Equal(t, r.lastSN, uint16(23333)) require.EqualValues(t, 0, r.snOffset) // drop a head packet and check offset increases @@ -112,8 +112,8 @@ func TestPacketDropped(t *testing.T) { } extPkt, _ = testutils.GetTestExtPacket(params) r.PacketDropped(extPkt) - require.True(t, r.highestIncomingSN == 44444) - require.True(t, r.lastSN == 23333) + require.Equal(t, r.highestIncomingSN, uint16(44444)) + require.Equal(t, r.lastSN, uint16(44443)) require.EqualValues(t, 1, r.snOffset) } diff --git a/pkg/sfu/streamallocator.go b/pkg/sfu/streamallocator.go index d9545f3d..44c988f1 100644 --- a/pkg/sfu/streamallocator.go +++ b/pkg/sfu/streamallocator.go @@ -20,7 +20,19 @@ import ( const ( ChannelCapacityInfinity = 100 * 1000 * 1000 // 100 Mbps - EstimateEpsilon = 2000 // 2 kbps + NumRequiredEstimatesNonProbe = 8 + NumRequiredEstimatesProbe = 3 + + ProbeWaitBase = 5 * time.Second + ProbeBackoffFactor = 1.5 + ProbeWaitMax = 30 * time.Second + ProbeSettleWait = 250 + ProbeTrendWait = 2 * time.Second + + ProbePct = 120 + ProbeMinBps = 200 * 1000 // 200 kbps + ProbeMinDuration = 20 * time.Second + ProbeMaxDuration = 21 * time.Second GratuitousProbeHeadroomBps = 1 * 1000 * 1000 // if headroom > 1 Mbps, don't probe GratuitousProbePct = 10 @@ -31,16 +43,6 @@ const ( AudioLossWeight = 0.75 VideoLossWeight = 0.25 - - // LK-TODO-START - // These constants will definitely require more tweaking. - // In fact, simple time threshold rules most probably will not be enough. - // LK-TODO-END - EstimateCommit = 2 * 1000 * time.Millisecond // 2 seconds - ProbeWait = 8 * 1000 * time.Millisecond // 8 seconds - BoostWait = 5 * 1000 * time.Millisecond // 5 seconds - GratuitousProbeWait = 8 * 1000 * time.Millisecond // 8 seconds - GratuitousProbeMoreWait = 5 * 1000 * time.Millisecond // 5 seconds ) type State int @@ -74,6 +76,7 @@ const ( SignalSubscribedLayersChange SignalPeriodicPing SignalSendProbe + SignalProbeClusterDone ) func (s Signal) String() string { @@ -96,6 +99,8 @@ func (s Signal) String() string { return "PERIODIC_PING" case SignalSendProbe: return "SEND_PROBE" + case SignalProbeClusterDone: + return "PROBE_CLUSTER_DONE" default: return fmt.Sprintf("%d", int(s)) } @@ -125,23 +130,27 @@ type StreamAllocator struct { bwe cc.BandwidthEstimator + lastReceivedEstimate int64 + estimator *Estimator + committedChannelCapacity int64 - lastCommitTime time.Time - prevReceivedEstimate int64 - receivedEstimate int64 - lastEstimateDecreaseTime time.Time - lastBoostTime time.Time + probeInterval time.Duration + lastProbeStartTime time.Time + probeGoalBps int64 + probeClusterId ProbeClusterId + abortedProbeClusterId ProbeClusterId + probeTrendObserved bool + probeEndTime time.Time + probeEstimator *Estimator - lastGratuitousProbeTime time.Time + prober *Prober audioTracks map[livekit.TrackID]*Track videoTracks map[livekit.TrackID]*Track exemptVideoTracksSorted TrackSorter managedVideoTracksSorted TrackSorter - prober *Prober - state State eventChMu sync.RWMutex @@ -153,6 +162,7 @@ type StreamAllocator struct { func NewStreamAllocator(params StreamAllocatorParams) *StreamAllocator { s := &StreamAllocator{ params: params, + estimator: NewEstimator("non-probe", params.Logger, NumRequiredEstimatesNonProbe), audioTracks: make(map[livekit.TrackID]*Track), videoTracks: make(map[livekit.TrackID]*Track), prober: NewProber(ProberParams{ @@ -161,9 +171,10 @@ func NewStreamAllocator(params StreamAllocatorParams) *StreamAllocator { eventCh: make(chan Event, 20), } - s.initializeEstimate() + s.resetState() s.prober.OnSendProbe(s.onSendProbe) + s.prober.OnProbeClusterDone(s.onProbeClusterDone) return s } @@ -226,11 +237,8 @@ func (s *StreamAllocator) RemoveTrack(downTrack *DownTrack) { }) } -func (s *StreamAllocator) initializeEstimate() { - s.committedChannelCapacity = ChannelCapacityInfinity - s.lastCommitTime = time.Now().Add(-EstimateCommit) - s.receivedEstimate = ChannelCapacityInfinity - s.lastEstimateDecreaseTime = time.Now() +func (s *StreamAllocator) resetState() { + s.resetProbe() s.state = StateStable } @@ -306,6 +314,14 @@ func (s *StreamAllocator) onSendProbe(bytesToSend int) { }) } +// called when prober wants to send packet(s) +func (s *StreamAllocator) onProbeClusterDone(info ProbeClusterInfo) { + s.postEvent(Event{ + Signal: SignalProbeClusterDone, + Data: info, + }) +} + func (s *StreamAllocator) postEvent(event Event) { s.eventChMu.RLock() if s.isStopped.Get() { @@ -360,6 +376,8 @@ func (s *StreamAllocator) handleEvent(event *Event) { s.handleSignalPeriodicPing(event) case SignalSendProbe: s.handleSignalSendProbe(event) + case SignalProbeClusterDone: + s.handleSignalProbeClusterDone(event) } } @@ -428,7 +446,7 @@ func (s *StreamAllocator) handleSignalRemoveTrack(event *Event) { // re-initialize estimate if all managed tracks are removed, let it get a fresh start if len(s.managedVideoTracksSorted) == 0 { - s.initializeEstimate() + s.resetState() return } @@ -438,7 +456,8 @@ func (s *StreamAllocator) handleSignalRemoveTrack(event *Event) { } func (s *StreamAllocator) handleSignalEstimate(event *Event) { - // the channel capacity is estimated at a peer connection level. All down tracks + // + // 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 // the same estimated channel capacity. Use a tracking SSRC to lock onto to // one report. As SSRCs can be dropped over time, update tracking SSRC as needed @@ -458,6 +477,7 @@ func (s *StreamAllocator) handleSignalEstimate(event *Event) { // RTCP dispatch for same SSRC on different threads? If not, the tracking SSRC // should prevent racing // LK-TODO-END + // // if there are no video tracks, ignore any straggler REMB if len(s.managedVideoTracksSorted) == 0 { @@ -497,38 +517,12 @@ func (s *StreamAllocator) handleSignalEstimate(event *Event) { return } - s.prevReceivedEstimate = s.receivedEstimate - s.receivedEstimate = int64(remb.Bitrate) - /* - if s.prevReceivedEstimate != s.receivedEstimate { - s.params.Logger.Debugw("received new estimate", - "old(bps)", s.prevReceivedEstimate, - "new(bps)", s.receivedEstimate, - ) - } - */ - - if s.maybeCommitEstimate() { - s.allocateAllTracks() - } + s.handleNewEstimate(int64(remb.Bitrate)) } func (s *StreamAllocator) handleSignalTargetBitrate(event *Event) { receivedEstimate, _ := event.Data.(int) - s.prevReceivedEstimate = s.receivedEstimate - s.receivedEstimate = int64(receivedEstimate) - /* - if s.prevReceivedEstimate != s.receivedEstimate { - s.params.Logger.Debugw("received new send side estimate", - "old(bps)", s.prevReceivedEstimate, - "new(bps)", s.receivedEstimate, - ) - } - */ - - if s.maybeCommitEstimate() { - s.allocateAllTracks() - } + s.handleNewEstimate(int64(receivedEstimate)) } // LK-TODO-START @@ -596,13 +590,15 @@ func (s *StreamAllocator) handleSignalSubscribedLayersChange(event *Event) { } func (s *StreamAllocator) handleSignalPeriodicPing(event *Event) { - if s.maybeCommitEstimate() { - s.allocateAllTracks() + // finalize probe if necessary + if s.isInProbe() && !s.probeEndTime.IsZero() && time.Now().After(s.probeEndTime) { + s.finalizeProbe() } // catch up on all optimistically streamed tracks s.finalizeTracks() + // probe if necessary and timing is right if s.state == StateDeficient { s.maybeProbe() } @@ -629,12 +625,40 @@ func (s *StreamAllocator) handleSignalSendProbe(event *Event) { } } -func (s *StreamAllocator) setState(state State) { - if s.state != state { - s.params.Logger.Debugw("state change", "from", s.state, "to", state) +func (s *StreamAllocator) handleSignalProbeClusterDone(event *Event) { + info, _ := event.Data.(ProbeClusterInfo) + if s.probeClusterId != info.Id { + return } + if s.abortedProbeClusterId == ProbeClusterIdInvalid { + // successful probe, finalize + s.finalizeProbe() + return + } + + // ensure probe queue is flushed + // LK-TODO: ProbeSettleWait should actually be a certain number of RTTs. + lowestEstimate := int64(math.Min(float64(s.committedChannelCapacity), float64(s.probeEstimator.GetLowest()))) + expectedDuration := float64(info.BytesSent*8*1000) / float64(lowestEstimate) + queueTime := expectedDuration - float64(info.Duration.Milliseconds()) + if queueTime < 0.0 { + queueTime = 0.0 + } + queueWait := time.Duration(queueTime+float64(ProbeSettleWait)) * time.Millisecond + s.probeEndTime = s.lastProbeStartTime.Add(queueWait) +} + +func (s *StreamAllocator) setState(state State) { + if s.state == state { + return + } + + s.params.Logger.Debugw("state change", "from", s.state, "to", state) s.state = state + + // reset probe to enforce a delay after state change before probing + s.lastProbeStartTime = time.Now() } func (s *StreamAllocator) adjustState() { @@ -648,50 +672,67 @@ func (s *StreamAllocator) adjustState() { s.setState(StateStable) } -func (s *StreamAllocator) maybeCommitEstimate() (isDecreasing bool) { - // commit channel capacity estimate under following rules - // 1. Abs(receivedEstimate - prevReceivedEstimate) < EstimateEpsilon => estimate stable - // 2. time.Since(lastCommitTime) > EstimateCommitMs => to catch long oscillating estimate - if math.Abs(float64(s.receivedEstimate)-float64(s.prevReceivedEstimate)) > EstimateEpsilon { - // too large a change, wait for estimate to settle. - // Unless estimate has been oscillating for too long. - if time.Since(s.lastCommitTime) < EstimateCommit { - return - } - } +func (s *StreamAllocator) handleNewEstimate(receivedEstimate int64) { + s.lastReceivedEstimate = receivedEstimate - // don't commit too often even if the change is small. - // Small changes will also get picked up during periodic check. - if time.Since(s.lastCommitTime) < EstimateCommit { + // while probing, maintain estimate separately to enable keeping current committed estimate if probe fails + if s.isInProbe() { + s.handleNewEstimateInProbe() + } else { + s.handleNewEstimateInNonProbe() + } +} + +func (s *StreamAllocator) handleNewEstimateInProbe() { + trend := s.probeEstimator.AddEstimate(s.lastReceivedEstimate) + if trend != EstimateTrendNeutral { + s.probeTrendObserved = true + } + switch { + case s.abortedProbeClusterId != ProbeClusterIdInvalid: + return + case !s.probeTrendObserved && time.Since(s.lastProbeStartTime) > ProbeTrendWait: + // + // More of a safety net. + // In rare cases, the estimate gets stuck. Prevent from probe running amok + // LK-TODO: Need more testing this here and ensure that probe does not cause a lot of damage + // + s.abortProbe() + case trend == EstimateTrendDownward: + // stop immediately if estimate falls below the previously committed estimate, the probe is congesting channel more + s.abortProbe() + case s.probeEstimator.GetHighest() > s.probeGoalBps: + // reached goal, stop probing + s.stopProbe() + } +} + +func (s *StreamAllocator) handleNewEstimateInNonProbe() { + trend := s.estimator.AddEstimate(s.lastReceivedEstimate) + if trend != EstimateTrendDownward { return } - if s.receivedEstimate == s.committedChannelCapacity { - // no change in estimate, no need to commit - return - } + s.params.Logger.Infow( + "estimate trending down, updating channel capacity", + "old(bps)", s.committedChannelCapacity, + "new(bps)", s.lastReceivedEstimate, + ) + s.committedChannelCapacity = s.lastReceivedEstimate - if s.committedChannelCapacity > s.receivedEstimate && s.committedChannelCapacity != ChannelCapacityInfinity { - // this prevents declaring a decrease when coming out of init state. - // But, this bypasses the case where streaming starts on a bunch of - // tracks simultaneously (imagine a participant joining a large room - // with a lot of video tracks). In that case, it is possible that the - // channel is hitting congestion. It will be caught on the next estimate - // decrease. - s.lastEstimateDecreaseTime = time.Now() - isDecreasing = true - } + // reset to get new set of samples for next trend + s.estimator.Reset() - if s.committedChannelCapacity > s.receivedEstimate { - s.params.Logger.Debugw("committing channel capacity(bps)", "from", s.committedChannelCapacity, "to", s.receivedEstimate) - } - s.committedChannelCapacity = s.receivedEstimate - s.lastCommitTime = time.Now() + // reset probe to ensure it does not start too soon after a downward trend + s.resetProbe() - return + s.allocateAllTracks() } func (s *StreamAllocator) allocateTrack(track *Track) { + // abort any probe that may be running when a track specific change needs allocation + s.abortProbe() + // if not deficient, free pass allocate track if !s.params.Config.Enabled || s.state == StateStable || !track.IsManaged() { update := NewStreamStateUpdate() @@ -786,14 +827,89 @@ func (s *StreamAllocator) allocateTrack(track *Track) { s.adjustState() } +func (s *StreamAllocator) finalizeProbe() { + aborted := s.probeClusterId == s.abortedProbeClusterId + highestEstimateInProbe := s.probeEstimator.GetHighest() + + s.clearProbe() + + // + // Reset estimator at the end of a probe irrespective of probe result to get fresh readings. + // With a failed probe, the latest estimate would be lower than committed estimate. + // As bandwidth estimator (remote in REMB case, local in TWCC case) holds state, + // subsequent estimates could start from the lower point. That should not trigger a + // downward trend and get latched to committed estimate as that would trigger a re-allocation. + // With fresh readings, as long as the trend is not going downward, it will not get latched. + // + // NOTE: With TWCC, it is possible to reset bandwidth estimation to clean state as + // the send side is in full control of bandwidth estimation. + // + s.estimator.Reset() + + if aborted { + // failed probe, backoff + s.backoffProbeInterval() + return + } + + // reset probe interval on a successful probe + s.resetProbeInterval() + + if s.committedChannelCapacity == highestEstimateInProbe { + // no increase for whatever reason, don't backoff though + return + } + + // probe estimate is higher, commit it and try allocate deficient tracks + s.params.Logger.Infow( + "successful probe, updating channel capacity", + "old(bps)", s.committedChannelCapacity, + "new(bps)", highestEstimateInProbe, + ) + s.committedChannelCapacity = highestEstimateInProbe + + availableChannelCapacity := s.committedChannelCapacity - s.getExpectedBandwidthUsage() + if availableChannelCapacity <= 0 { + return + } + + var maxDistanceSorted MaxDistanceSorter + for _, track := range s.managedVideoTracksSorted { + maxDistanceSorted = append(maxDistanceSorted, track) + } + sort.Sort(maxDistanceSorted) + + update := NewStreamStateUpdate() + + for _, track := range maxDistanceSorted { + if !track.IsDeficient() { + continue + } + + allocation, boosted := track.AllocateNextHigher(availableChannelCapacity) + if !boosted { + continue + } + + update.HandleStreamingChange(allocation.change, track) + + availableChannelCapacity -= allocation.bandwidthDelta + if availableChannelCapacity <= 0 { + break + } + } + + s.maybeSendUpdate(update) + + s.adjustState() +} + func (s *StreamAllocator) allocateAllTracks() { if !s.params.Config.Enabled { // nothing else to do when disabled return } - s.resetBoost() - // // Goals: // 1. Stream as many tracks as possible, i.e. no pauses. @@ -932,76 +1048,154 @@ func (s *StreamAllocator) calculateLoss() float32 { return AudioLossWeight*audioLossPct + VideoLossWeight*videoLossPct } +func (s *StreamAllocator) initProbe(goalBps int64) { + s.lastProbeStartTime = time.Now() + + s.probeGoalBps = goalBps + + s.abortedProbeClusterId = ProbeClusterIdInvalid + + s.probeTrendObserved = false + + s.probeEndTime = time.Time{} + + s.probeEstimator = NewEstimator("probe", s.params.Logger, NumRequiredEstimatesProbe) + s.probeEstimator.Seed(s.lastReceivedEstimate) +} + +func (s *StreamAllocator) resetProbe() { + s.lastProbeStartTime = time.Now() + + s.resetProbeInterval() + + s.clearProbe() +} + +func (s *StreamAllocator) clearProbe() { + s.probeClusterId = ProbeClusterIdInvalid + s.abortedProbeClusterId = ProbeClusterIdInvalid + + s.probeTrendObserved = false + + s.probeEndTime = time.Time{} + + s.probeEstimator = nil +} + +func (s *StreamAllocator) backoffProbeInterval() { + s.probeInterval = time.Duration(s.probeInterval.Seconds()*ProbeBackoffFactor) * time.Second + if s.probeInterval > ProbeWaitMax { + s.probeInterval = ProbeWaitMax + } +} + +func (s *StreamAllocator) resetProbeInterval() { + s.probeInterval = ProbeWaitBase +} + +func (s *StreamAllocator) stopProbe() { + s.prober.Reset() +} + +func (s *StreamAllocator) abortProbe() { + s.abortedProbeClusterId = s.probeClusterId + s.stopProbe() +} + +func (s *StreamAllocator) isInProbe() bool { + return s.probeClusterId != ProbeClusterIdInvalid +} + func (s *StreamAllocator) maybeProbe() { - if !s.isTimeToBoost() { + if time.Since(s.lastProbeStartTime) < s.probeInterval || s.probeClusterId != ProbeClusterIdInvalid { return } - s.maybeBoostLayer() - s.adjustState() + switch s.params.Config.ProbeMode { + case config.CongestionControlProbeModeMedia: + s.maybeProbeWithMedia() + s.adjustState() + case config.CongestionControlProbeModePadding: + s.maybeProbeWithPadding() + } } -func (s *StreamAllocator) maybeBoostLayer() { +func (s *StreamAllocator) maybeProbeWithMedia() { var maxDistanceSorted MaxDistanceSorter for _, track := range s.managedVideoTracksSorted { maxDistanceSorted = append(maxDistanceSorted, track) } sort.Sort(maxDistanceSorted) - // boost first deficient track in priority order + // boost deficient track farthest from desired layers for _, track := range maxDistanceSorted { if !track.IsDeficient() { continue } - allocation, boosted := track.AllocateNextHigher() - if boosted { - s.lastBoostTime = time.Now() - - update := NewStreamStateUpdate() - update.HandleStreamingChange(allocation.change, track) - s.maybeSendUpdate(update) - - break + allocation, boosted := track.AllocateNextHigher(ChannelCapacityInfinity) + if !boosted { + continue } + + update := NewStreamStateUpdate() + update.HandleStreamingChange(allocation.change, track) + s.maybeSendUpdate(update) + + s.lastProbeStartTime = time.Now() + break } } -func (s *StreamAllocator) isTimeToBoost() bool { - // if enough time has passed since last estimate drop or last estimate boost, - // artificially boost estimate before allocating. - // Checking against last estimate boost prevents multiple artificial boosts - // in situations where multiple tracks become available in a short span. - if !s.lastBoostTime.IsZero() { - return time.Since(s.lastBoostTime) > BoostWait - } else { - return time.Since(s.lastEstimateDecreaseTime) > ProbeWait +func (s *StreamAllocator) maybeProbeWithPadding() { + var maxDistanceSorted MaxDistanceSorter + for _, track := range s.managedVideoTracksSorted { + maxDistanceSorted = append(maxDistanceSorted, track) } -} + sort.Sort(maxDistanceSorted) -func (s *StreamAllocator) resetBoost() { - s.lastBoostTime = time.Time{} + // use deficient track farthest from desired layers to find how much to probe + for _, track := range maxDistanceSorted { + if !track.IsDeficient() { + continue + } + + transition, available := track.GetNextHigherTransition() + if !available || transition.bandwidthDelta < 0 { + continue + } + + probeRateBps := (transition.bandwidthDelta * ProbePct) / 100 + if probeRateBps < ProbeMinBps { + probeRateBps = ProbeMinBps + } + + s.initProbe(s.getExpectedBandwidthUsage() + probeRateBps) + s.probeClusterId = s.prober.AddCluster( + int(s.committedChannelCapacity+probeRateBps), + int(s.getExpectedBandwidthUsage()), + ProbeMinDuration, + ProbeMaxDuration, + ) + break + } } func (s *StreamAllocator) maybeGratuitousProbe() bool { - if time.Since(s.lastEstimateDecreaseTime) < GratuitousProbeWait || len(s.managedVideoTracksSorted) == 0 { - return false - } - // don't gratuitously probe too often - if time.Since(s.lastGratuitousProbeTime) < GratuitousProbeMoreWait { + if time.Since(s.lastProbeStartTime) < s.probeInterval || len(s.managedVideoTracksSorted) == 0 || s.probeClusterId != ProbeClusterIdInvalid { return false } // use last received estimate for gratuitous probing base as // more updates may have been received since the last commit expectedRateBps := s.getExpectedBandwidthUsage() - headroomBps := s.receivedEstimate - expectedRateBps + headroomBps := s.lastReceivedEstimate - expectedRateBps if headroomBps > GratuitousProbeHeadroomBps { return false } - probeRateBps := (s.receivedEstimate * GratuitousProbePct) / 100 + probeRateBps := (s.lastReceivedEstimate * GratuitousProbePct) / 100 if probeRateBps < GratuitousProbeMinBps { probeRateBps = GratuitousProbeMinBps } @@ -1009,22 +1203,17 @@ func (s *StreamAllocator) maybeGratuitousProbe() bool { probeRateBps = GratuitousProbeMaxBps } - s.prober.AddCluster( - int(s.receivedEstimate+probeRateBps), + s.initProbe(expectedRateBps + probeRateBps) + s.probeClusterId = s.prober.AddCluster( + int(s.lastReceivedEstimate+probeRateBps), int(expectedRateBps), GratuitousProbeMinDuration, GratuitousProbeMaxDuration, ) - s.lastGratuitousProbeTime = time.Now() return true } -func (s *StreamAllocator) resetGratuitousProbe() { - s.prober.Reset() - s.lastGratuitousProbeTime = time.Now() -} - // ------------------------------------------------ type StreamState int @@ -1141,9 +1330,7 @@ func (t *Track) WritePaddingRTP(bytesToSend int) int { } func (t *Track) Allocate(availableChannelCapacity int64, allowPause bool) VideoAllocation { - allocation := t.downTrack.Allocate(availableChannelCapacity, allowPause) - //t.logger.Debugw("SA_DEBUG Capacity allocation", "available", availableChannelCapacity, "alloc", allocation) // REMOVE - return allocation + return t.downTrack.Allocate(availableChannelCapacity, allowPause) } func (t *Track) ProvisionalAllocatePrepare() { @@ -1163,15 +1350,15 @@ func (t *Track) ProvisionalAllocateGetBestWeightedTransition() VideoTransition { } func (t *Track) ProvisionalAllocateCommit() VideoAllocation { - allocation := t.downTrack.ProvisionalAllocateCommit() - //t.logger.Debugw("SA_DEBUG Provisional commit", "alloc", allocation) // REMOVE - return allocation + return t.downTrack.ProvisionalAllocateCommit() } -func (t *Track) AllocateNextHigher() (VideoAllocation, bool) { - allocation, boosted := t.downTrack.AllocateNextHigher() - //t.logger.Debugw("SA_DEBUG Probe next higher layer", "alloc", allocation, "boosted", boosted) // REMOVE - return allocation, boosted +func (t *Track) AllocateNextHigher(availableChannelCapacity int64) (VideoAllocation, bool) { + return t.downTrack.AllocateNextHigher(availableChannelCapacity) +} + +func (t *Track) GetNextHigherTransition() (VideoTransition, bool) { + return t.downTrack.GetNextHigherTransition() } func (t *Track) FinalizeAllocate() { @@ -1247,3 +1434,117 @@ func (m MinDistanceSorter) Less(i, j int) bool { } // ------------------------------------------------ + +type EstimateTrend int + +const ( + EstimateTrendNeutral EstimateTrend = iota + EstimateTrendUpward + EstimateTrendDownward +) + +func (e EstimateTrend) String() string { + switch e { + case EstimateTrendNeutral: + return "NEUTRAL" + case EstimateTrendUpward: + return "UPWARD" + case EstimateTrendDownward: + return "DOWNWARD" + default: + return fmt.Sprintf("%d", int(e)) + } +} + +type Estimator struct { + name string + logger logger.Logger + requiredSamples int + + estimates []int64 + lowestEstimate int64 + highestEstimate int64 +} + +func NewEstimator(name string, logger logger.Logger, requiredSamples int) *Estimator { + return &Estimator{ + name: name, + logger: logger, + requiredSamples: requiredSamples, + } +} + +func (e *Estimator) Reset() { + e.estimates = nil + e.lowestEstimate = int64(0) + e.highestEstimate = int64(0) +} + +func (e *Estimator) Seed(estimate int64) { + if len(e.estimates) != 0 { + return + } + + e.estimates = append(e.estimates, estimate) +} + +func (e *Estimator) AddEstimate(estimate int64) EstimateTrend { + if e.lowestEstimate == 0 || estimate < e.lowestEstimate { + e.lowestEstimate = estimate + } + if estimate > e.highestEstimate { + e.highestEstimate = estimate + } + + if len(e.estimates) == e.requiredSamples { + e.estimates = e.estimates[1:] + } + e.estimates = append(e.estimates, estimate) + + return e.updateTrend() +} + +func (e *Estimator) GetLowest() int64 { + return e.lowestEstimate +} + +func (e *Estimator) GetHighest() int64 { + return e.highestEstimate +} + +func (e *Estimator) updateTrend() EstimateTrend { + if len(e.estimates) < e.requiredSamples { + return EstimateTrendNeutral + } + + // using Kendall's Tau to find trend + concordantPairs := 0 + discordantPairs := 0 + + for i := 0; i < len(e.estimates)-1; i++ { + for j := i + 1; j < len(e.estimates); j++ { + if e.estimates[i] < e.estimates[j] { + concordantPairs++ + } else if e.estimates[i] > e.estimates[j] { + discordantPairs++ + } + } + } + + if (concordantPairs + discordantPairs) == 0 { + return EstimateTrendNeutral + } + + trend := EstimateTrendNeutral + kt := (float64(concordantPairs) - float64(discordantPairs)) / (float64(concordantPairs) + float64(discordantPairs)) + switch { + case kt > 0: + trend = EstimateTrendUpward + case kt < 0: + trend = EstimateTrendDownward + } + + return trend +} + +// ------------------------------------------------