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
This commit is contained in:
@@ -24,6 +24,13 @@ var DefaultStunServers = []string{
|
|||||||
"stun1.l.google.com:19302",
|
"stun1.l.google.com:19302",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type CongestionControlProbeMode string
|
||||||
|
|
||||||
|
const (
|
||||||
|
CongestionControlProbeModePadding CongestionControlProbeMode = "padding"
|
||||||
|
CongestionControlProbeModeMedia = "media"
|
||||||
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Port uint32 `yaml:"port"`
|
Port uint32 `yaml:"port"`
|
||||||
PrometheusPort uint32 `yaml:"prometheus_port,omitempty"`
|
PrometheusPort uint32 `yaml:"prometheus_port,omitempty"`
|
||||||
@@ -89,6 +96,7 @@ type CongestionControlConfig struct {
|
|||||||
Enabled bool `yaml:"enabled"`
|
Enabled bool `yaml:"enabled"`
|
||||||
AllowPause bool `yaml:"allow_pause"`
|
AllowPause bool `yaml:"allow_pause"`
|
||||||
UseSendSideBWE bool `yaml:"send_side_bandwidth_estimation,omitempty"`
|
UseSendSideBWE bool `yaml:"send_side_bandwidth_estimation,omitempty"`
|
||||||
|
ProbeMode CongestionControlProbeMode `yaml:"padding_mode,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type AudioConfig struct {
|
type AudioConfig struct {
|
||||||
@@ -188,6 +196,7 @@ func NewConfig(confString string, c *cli.Context) (*Config, error) {
|
|||||||
CongestionControl: CongestionControlConfig{
|
CongestionControl: CongestionControlConfig{
|
||||||
Enabled: true,
|
Enabled: true,
|
||||||
AllowPause: true,
|
AllowPause: true,
|
||||||
|
ProbeMode: CongestionControlProbeModePadding,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
Audio: AudioConfig{
|
Audio: AudioConfig{
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ func (b *Bucket) AddPacket(pkt []byte) ([]byte, error) {
|
|||||||
}
|
}
|
||||||
diff := sn - b.headSN
|
diff := sn - b.headSN
|
||||||
if diff == 0 || diff > (1<<15) {
|
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)
|
return b.set(sn, pkt)
|
||||||
}
|
}
|
||||||
b.headSN = sn
|
b.headSN = sn
|
||||||
|
|||||||
@@ -510,11 +510,6 @@ func (b *Buffer) getExtPacket(rawPacket []byte, rtpPacket *rtp.Packet, arrivalTi
|
|||||||
ep.Payload = vp8Packet
|
ep.Payload = vp8Packet
|
||||||
ep.KeyFrame = vp8Packet.IsKeyFrame
|
ep.KeyFrame = vp8Packet.IsKeyFrame
|
||||||
temporalLayer = int32(vp8Packet.TID)
|
temporalLayer = int32(vp8Packet.TID)
|
||||||
/*
|
|
||||||
if ep.KeyFrame {
|
|
||||||
b.logger.Debugw("SA_DEBUG key frame", "ssrc", b.mediaSSRC) // REMOVE
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
case "video/h264":
|
case "video/h264":
|
||||||
ep.KeyFrame = IsH264Keyframe(rtpPacket.Payload)
|
ep.KeyFrame = IsH264Keyframe(rtpPacket.Payload)
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-5
@@ -302,7 +302,6 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) error {
|
|||||||
|
|
||||||
tp, err := d.forwarder.GetTranslationParams(extPkt, layer)
|
tp, err := d.forwarder.GetTranslationParams(extPkt, layer)
|
||||||
if tp.shouldSendPLI {
|
if tp.shouldSendPLI {
|
||||||
//d.logger.Debugw("SA_DEBUG Forwarder SendPLI", "layer", layer) // REMOVE
|
|
||||||
d.lastPli.set(time.Now().UnixNano())
|
d.lastPli.set(time.Now().UnixNano())
|
||||||
d.receiver.SendPLI(layer)
|
d.receiver.SendPLI(layer)
|
||||||
}
|
}
|
||||||
@@ -636,7 +635,7 @@ func (d *DownTrack) IsDeficient() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d *DownTrack) BandwidthRequested() int64 {
|
func (d *DownTrack) BandwidthRequested() int64 {
|
||||||
return d.forwarder.BandwidthRequested()
|
return d.forwarder.BandwidthRequested(d.receiver.GetBitrateTemporalCumulative())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DownTrack) DistanceToDesired() int32 {
|
func (d *DownTrack) DistanceToDesired() int32 {
|
||||||
@@ -671,8 +670,12 @@ func (d *DownTrack) FinalizeAllocate() VideoAllocation {
|
|||||||
return d.forwarder.FinalizeAllocate(d.receiver.GetBitrateTemporalCumulative())
|
return d.forwarder.FinalizeAllocate(d.receiver.GetBitrateTemporalCumulative())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DownTrack) AllocateNextHigher() (VideoAllocation, bool) {
|
func (d *DownTrack) AllocateNextHigher(availableChannelCapacity int64) (VideoAllocation, bool) {
|
||||||
return d.forwarder.AllocateNextHigher(d.receiver.GetBitrateTemporalCumulative())
|
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 {
|
func (d *DownTrack) Pause() VideoAllocation {
|
||||||
@@ -878,7 +881,6 @@ func (d *DownTrack) handleRTCP(bytes []byte) {
|
|||||||
targetLayers := d.forwarder.TargetLayers()
|
targetLayers := d.forwarder.TargetLayers()
|
||||||
if targetLayers != InvalidLayers {
|
if targetLayers != InvalidLayers {
|
||||||
d.lastPli.set(time.Now().UnixNano())
|
d.lastPli.set(time.Now().UnixNano())
|
||||||
//d.logger.Debugw("SA_DEBUG Subscriber RTCP SendPLI", "layer", targetLayers.spatial) // REMOVE
|
|
||||||
d.receiver.SendPLI(targetLayers.spatial)
|
d.receiver.SendPLI(targetLayers.spatial)
|
||||||
pliOnce = false
|
pliOnce = false
|
||||||
}
|
}
|
||||||
@@ -978,6 +980,10 @@ func (d *DownTrack) retransmitPackets(nackedPackets []packetMeta) {
|
|||||||
defer PacketFactory.Put(src)
|
defer PacketFactory.Put(src)
|
||||||
|
|
||||||
for _, meta := range nackedPackets {
|
for _, meta := range nackedPackets {
|
||||||
|
if !d.forwarder.IsRtxAllowed(int32(meta.layer)) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
if pool != nil {
|
if pool != nil {
|
||||||
PacketFactory.Put(pool)
|
PacketFactory.Put(pool)
|
||||||
pool = nil
|
pool = nil
|
||||||
|
|||||||
+119
-13
@@ -359,11 +359,15 @@ func (f *Forwarder) IsDeficient() bool {
|
|||||||
return f.lastAllocation.state == VideoAllocationStateDeficient
|
return f.lastAllocation.state == VideoAllocationStateDeficient
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Forwarder) BandwidthRequested() int64 {
|
func (f *Forwarder) BandwidthRequested(brs Bitrates) int64 {
|
||||||
f.lock.RLock()
|
f.lock.RLock()
|
||||||
defer f.lock.RUnlock()
|
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 {
|
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)
|
// This is called when a track needs a change (could be mute/unmute, subscribed layers changed, published layers changed)
|
||||||
// when channel is congested.
|
// 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.
|
// 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.
|
// 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
|
// Cost has two components
|
||||||
// a. Transition cost: Spatial layer switch is expensive due to key frame requirement, but temporal layer switch is free.
|
// 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.
|
// 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
|
return f.lastAllocation
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Forwarder) AllocateNextHigher(brs Bitrates) (VideoAllocation, bool) {
|
func (f *Forwarder) AllocateNextHigher(availableChannelCapacity int64, brs Bitrates) (VideoAllocation, bool) {
|
||||||
f.lock.Lock()
|
f.lock.Lock()
|
||||||
defer f.lock.Unlock()
|
defer f.lock.Unlock()
|
||||||
|
|
||||||
@@ -924,6 +928,11 @@ func (f *Forwarder) AllocateNextHigher(brs Bitrates) (VideoAllocation, bool) {
|
|||||||
return f.lastAllocation, false
|
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
|
// try moving temporal layer up in currently streaming spatial layer
|
||||||
if f.targetLayers != InvalidLayers {
|
if f.targetLayers != InvalidLayers {
|
||||||
for t := f.targetLayers.temporal + 1; t <= f.maxLayers.temporal; t++ {
|
for t := f.targetLayers.temporal + 1; t <= f.maxLayers.temporal; t++ {
|
||||||
@@ -932,6 +941,12 @@ func (f *Forwarder) AllocateNextHigher(brs Bitrates) (VideoAllocation, bool) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if bandwidthRequested-alreadyAllocated > availableChannelCapacity {
|
||||||
|
// next higher available layer does not fit, return
|
||||||
|
f.lastAllocation.change = VideoStreamingChangeNone
|
||||||
|
return f.lastAllocation, false
|
||||||
|
}
|
||||||
|
|
||||||
state := VideoAllocationStateOptimal
|
state := VideoAllocationStateOptimal
|
||||||
if bandwidthRequested != optimalBandwidthNeeded {
|
if bandwidthRequested != optimalBandwidthNeeded {
|
||||||
state = VideoAllocationStateDeficient
|
state = VideoAllocationStateDeficient
|
||||||
@@ -942,7 +957,7 @@ func (f *Forwarder) AllocateNextHigher(brs Bitrates) (VideoAllocation, bool) {
|
|||||||
state: state,
|
state: state,
|
||||||
change: VideoStreamingChangeNone,
|
change: VideoStreamingChangeNone,
|
||||||
bandwidthRequested: bandwidthRequested,
|
bandwidthRequested: bandwidthRequested,
|
||||||
bandwidthDelta: bandwidthRequested - f.lastAllocation.bandwidthRequested,
|
bandwidthDelta: bandwidthRequested - alreadyAllocated,
|
||||||
availableLayers: f.availableLayers,
|
availableLayers: f.availableLayers,
|
||||||
bitrates: brs,
|
bitrates: brs,
|
||||||
targetLayers: targetLayers,
|
targetLayers: targetLayers,
|
||||||
@@ -961,6 +976,12 @@ func (f *Forwarder) AllocateNextHigher(brs Bitrates) (VideoAllocation, bool) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if bandwidthRequested-alreadyAllocated > availableChannelCapacity {
|
||||||
|
// next higher available layer does not fit, return
|
||||||
|
f.lastAllocation.change = VideoStreamingChangeNone
|
||||||
|
return f.lastAllocation, false
|
||||||
|
}
|
||||||
|
|
||||||
state := VideoAllocationStateOptimal
|
state := VideoAllocationStateOptimal
|
||||||
if bandwidthRequested != optimalBandwidthNeeded {
|
if bandwidthRequested != optimalBandwidthNeeded {
|
||||||
state = VideoAllocationStateDeficient
|
state = VideoAllocationStateDeficient
|
||||||
@@ -976,7 +997,7 @@ func (f *Forwarder) AllocateNextHigher(brs Bitrates) (VideoAllocation, bool) {
|
|||||||
state: state,
|
state: state,
|
||||||
change: change,
|
change: change,
|
||||||
bandwidthRequested: bandwidthRequested,
|
bandwidthRequested: bandwidthRequested,
|
||||||
bandwidthDelta: bandwidthRequested - f.lastAllocation.bandwidthRequested,
|
bandwidthDelta: bandwidthRequested - alreadyAllocated,
|
||||||
availableLayers: f.availableLayers,
|
availableLayers: f.availableLayers,
|
||||||
bitrates: brs,
|
bitrates: brs,
|
||||||
targetLayers: targetLayers,
|
targetLayers: targetLayers,
|
||||||
@@ -991,6 +1012,74 @@ func (f *Forwarder) AllocateNextHigher(brs Bitrates) (VideoAllocation, bool) {
|
|||||||
return f.lastAllocation, false
|
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 {
|
func (f *Forwarder) Pause(brs Bitrates) VideoAllocation {
|
||||||
f.lock.Lock()
|
f.lock.Lock()
|
||||||
defer f.lock.Unlock()
|
defer f.lock.Unlock()
|
||||||
@@ -1049,6 +1138,27 @@ func (f *Forwarder) Resync() {
|
|||||||
f.lastSSRC = 0
|
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) {
|
func (f *Forwarder) GetTranslationParams(extPkt *buffer.ExtPacket, layer int32) (*TranslationParams, error) {
|
||||||
f.lock.Lock()
|
f.lock.Lock()
|
||||||
defer f.lock.Unlock()
|
defer f.lock.Unlock()
|
||||||
@@ -1128,7 +1238,6 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in
|
|||||||
if f.targetLayers.spatial == layer {
|
if f.targetLayers.spatial == layer {
|
||||||
if extPkt.KeyFrame {
|
if extPkt.KeyFrame {
|
||||||
// lock to target layer
|
// 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
|
f.currentLayers.spatial = f.targetLayers.spatial
|
||||||
if f.currentLayers.spatial == f.maxLayers.spatial {
|
if f.currentLayers.spatial == f.maxLayers.spatial {
|
||||||
tp.isSwitchingToMaxLayer = true
|
tp.isSwitchingToMaxLayer = true
|
||||||
@@ -1145,10 +1254,7 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in
|
|||||||
return tp, nil
|
return tp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if FlagPauseOnDowngrade &&
|
if FlagPauseOnDowngrade && f.targetLayers.spatial < f.currentLayers.spatial && f.lastAllocation.state == VideoAllocationStateDeficient {
|
||||||
f.targetLayers.spatial < f.currentLayers.spatial &&
|
|
||||||
f.targetLayers.spatial < f.maxLayers.spatial &&
|
|
||||||
f.lastAllocation.state == VideoAllocationStateDeficient {
|
|
||||||
//
|
//
|
||||||
// If target layer is lower than both the current and
|
// If target layer is lower than both the current and
|
||||||
// maximum subscribed layer, it is due to bandwidth
|
// maximum subscribed layer, it is due to bandwidth
|
||||||
|
|||||||
+28
-11
@@ -696,7 +696,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
|
|||||||
{0, 7, 0, 0},
|
{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.Equal(t, VideoAllocationDefault, result) // no layer for audio
|
||||||
require.False(t, boosted)
|
require.False(t, boosted)
|
||||||
|
|
||||||
@@ -704,7 +704,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
|
|||||||
|
|
||||||
// when not in deficient state, does not boost
|
// when not in deficient state, does not boost
|
||||||
f.lastAllocation.state = VideoAllocationStateNone
|
f.lastAllocation.state = VideoAllocationStateNone
|
||||||
result, boosted = f.AllocateNextHigher(bitrates)
|
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates)
|
||||||
require.Equal(t, VideoAllocationDefault, result)
|
require.Equal(t, VideoAllocationDefault, result)
|
||||||
require.False(t, boosted)
|
require.False(t, boosted)
|
||||||
|
|
||||||
@@ -721,14 +721,14 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
|
|||||||
targetLayers: InvalidLayers,
|
targetLayers: InvalidLayers,
|
||||||
distanceToDesired: 0,
|
distanceToDesired: 0,
|
||||||
}
|
}
|
||||||
result, boosted = f.AllocateNextHigher(bitrates)
|
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates)
|
||||||
require.Equal(t, expectedResult, result)
|
require.Equal(t, expectedResult, result)
|
||||||
require.Equal(t, expectedResult, f.lastAllocation)
|
require.Equal(t, expectedResult, f.lastAllocation)
|
||||||
require.False(t, boosted)
|
require.False(t, boosted)
|
||||||
f.currentLayers.spatial = 0
|
f.currentLayers.spatial = 0
|
||||||
|
|
||||||
f.targetLayers.temporal = 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, result)
|
||||||
require.Equal(t, expectedResult, f.lastAllocation)
|
require.Equal(t, expectedResult, f.lastAllocation)
|
||||||
require.False(t, boosted)
|
require.False(t, boosted)
|
||||||
@@ -747,7 +747,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
|
|||||||
targetLayers: InvalidLayers,
|
targetLayers: InvalidLayers,
|
||||||
distanceToDesired: 0,
|
distanceToDesired: 0,
|
||||||
}
|
}
|
||||||
result, boosted = f.AllocateNextHigher(emptyBitrates)
|
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, emptyBitrates)
|
||||||
require.Equal(t, expectedResult, result)
|
require.Equal(t, expectedResult, result)
|
||||||
require.Equal(t, expectedResult, f.lastAllocation)
|
require.Equal(t, expectedResult, f.lastAllocation)
|
||||||
require.False(t, boosted)
|
require.False(t, boosted)
|
||||||
@@ -767,7 +767,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
|
|||||||
targetLayers: expectedTargetLayers,
|
targetLayers: expectedTargetLayers,
|
||||||
distanceToDesired: 3,
|
distanceToDesired: 3,
|
||||||
}
|
}
|
||||||
result, boosted = f.AllocateNextHigher(bitrates)
|
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates)
|
||||||
require.Equal(t, expectedResult, result)
|
require.Equal(t, expectedResult, result)
|
||||||
require.Equal(t, expectedResult, f.lastAllocation)
|
require.Equal(t, expectedResult, f.lastAllocation)
|
||||||
require.Equal(t, expectedTargetLayers, f.TargetLayers())
|
require.Equal(t, expectedTargetLayers, f.TargetLayers())
|
||||||
@@ -789,7 +789,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
|
|||||||
targetLayers: expectedTargetLayers,
|
targetLayers: expectedTargetLayers,
|
||||||
distanceToDesired: 2,
|
distanceToDesired: 2,
|
||||||
}
|
}
|
||||||
result, boosted = f.AllocateNextHigher(bitrates)
|
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates)
|
||||||
require.Equal(t, expectedResult, result)
|
require.Equal(t, expectedResult, result)
|
||||||
require.Equal(t, expectedResult, f.lastAllocation)
|
require.Equal(t, expectedResult, f.lastAllocation)
|
||||||
require.Equal(t, expectedTargetLayers, f.TargetLayers())
|
require.Equal(t, expectedTargetLayers, f.TargetLayers())
|
||||||
@@ -812,7 +812,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
|
|||||||
targetLayers: expectedTargetLayers,
|
targetLayers: expectedTargetLayers,
|
||||||
distanceToDesired: 1,
|
distanceToDesired: 1,
|
||||||
}
|
}
|
||||||
result, boosted = f.AllocateNextHigher(bitrates)
|
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates)
|
||||||
require.Equal(t, expectedResult, result)
|
require.Equal(t, expectedResult, result)
|
||||||
require.Equal(t, expectedResult, f.lastAllocation)
|
require.Equal(t, expectedResult, f.lastAllocation)
|
||||||
require.Equal(t, expectedTargetLayers, f.TargetLayers())
|
require.Equal(t, expectedTargetLayers, f.TargetLayers())
|
||||||
@@ -834,7 +834,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
|
|||||||
targetLayers: expectedTargetLayers,
|
targetLayers: expectedTargetLayers,
|
||||||
distanceToDesired: 0,
|
distanceToDesired: 0,
|
||||||
}
|
}
|
||||||
result, boosted = f.AllocateNextHigher(bitrates)
|
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates)
|
||||||
require.Equal(t, expectedResult, result)
|
require.Equal(t, expectedResult, result)
|
||||||
require.Equal(t, expectedResult, f.lastAllocation)
|
require.Equal(t, expectedResult, f.lastAllocation)
|
||||||
require.Equal(t, expectedTargetLayers, f.TargetLayers())
|
require.Equal(t, expectedTargetLayers, f.TargetLayers())
|
||||||
@@ -843,7 +843,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
|
|||||||
// ask again, should return not boosted as there is no room to go higher
|
// ask again, should return not boosted as there is no room to go higher
|
||||||
f.currentLayers.spatial = 2
|
f.currentLayers.spatial = 2
|
||||||
f.currentLayers.temporal = 1
|
f.currentLayers.temporal = 1
|
||||||
result, boosted = f.AllocateNextHigher(bitrates)
|
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates)
|
||||||
require.Equal(t, expectedResult, result)
|
require.Equal(t, expectedResult, result)
|
||||||
require.Equal(t, expectedResult, f.lastAllocation)
|
require.Equal(t, expectedResult, f.lastAllocation)
|
||||||
require.Equal(t, expectedTargetLayers, f.TargetLayers())
|
require.Equal(t, expectedTargetLayers, f.TargetLayers())
|
||||||
@@ -868,11 +868,28 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
|
|||||||
targetLayers: expectedTargetLayers,
|
targetLayers: expectedTargetLayers,
|
||||||
distanceToDesired: 4,
|
distanceToDesired: 4,
|
||||||
}
|
}
|
||||||
result, boosted = f.AllocateNextHigher(bitrates)
|
result, boosted = f.AllocateNextHigher(ChannelCapacityInfinity, bitrates)
|
||||||
require.Equal(t, expectedResult, result)
|
require.Equal(t, expectedResult, result)
|
||||||
require.Equal(t, expectedResult, f.lastAllocation)
|
require.Equal(t, expectedResult, f.lastAllocation)
|
||||||
require.Equal(t, expectedTargetLayers, f.TargetLayers())
|
require.Equal(t, expectedTargetLayers, f.TargetLayers())
|
||||||
require.True(t, boosted)
|
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) {
|
func TestForwarderPause(t *testing.T) {
|
||||||
|
|||||||
+59
-11
@@ -109,6 +109,7 @@ package sfu
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"sync"
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gammazero/deque"
|
"github.com/gammazero/deque"
|
||||||
@@ -122,11 +123,14 @@ type ProberParams struct {
|
|||||||
type Prober struct {
|
type Prober struct {
|
||||||
logger logger.Logger
|
logger logger.Logger
|
||||||
|
|
||||||
|
clusterId uint32
|
||||||
|
|
||||||
clustersMu sync.RWMutex
|
clustersMu sync.RWMutex
|
||||||
clusters deque.Deque
|
clusters deque.Deque
|
||||||
activeCluster *Cluster
|
activeCluster *Cluster
|
||||||
|
|
||||||
onSendProbe func(bytesToSend int)
|
onSendProbe func(bytesToSend int)
|
||||||
|
onProbeClusterDone func(info ProbeClusterInfo)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProber(params ProberParams) *Prober {
|
func NewProber(params ProberParams) *Prober {
|
||||||
@@ -145,30 +149,43 @@ func (p *Prober) IsRunning() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *Prober) Reset() {
|
func (p *Prober) Reset() {
|
||||||
p.clustersMu.Lock()
|
var info ProbeClusterInfo
|
||||||
defer p.clustersMu.Unlock()
|
|
||||||
|
|
||||||
|
p.clustersMu.Lock()
|
||||||
if p.activeCluster != nil {
|
if p.activeCluster != nil {
|
||||||
p.logger.Debugw("resetting active cluster", "cluster", p.activeCluster.String())
|
p.logger.Debugw("resetting active cluster", "cluster", p.activeCluster.String())
|
||||||
|
info = p.activeCluster.GetInfo()
|
||||||
}
|
}
|
||||||
|
|
||||||
p.clusters.Clear()
|
p.clusters.Clear()
|
||||||
p.activeCluster = nil
|
p.activeCluster = nil
|
||||||
|
p.clustersMu.Unlock()
|
||||||
|
|
||||||
|
if p.onProbeClusterDone != nil && info.BytesSent != 0 {
|
||||||
|
p.onProbeClusterDone(info)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Prober) OnSendProbe(f func(bytesToSend int)) {
|
func (p *Prober) OnSendProbe(f func(bytesToSend int)) {
|
||||||
p.onSendProbe = f
|
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 {
|
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.logger.Debugw("cluster added", "cluster", cluster.String())
|
||||||
|
|
||||||
p.pushBackClusterAndMaybeStart(cluster)
|
p.pushBackClusterAndMaybeStart(cluster)
|
||||||
|
|
||||||
|
return clusterId
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Prober) PacketSent(size int) {
|
func (p *Prober) PacketSent(size int) {
|
||||||
@@ -251,10 +268,15 @@ func (p *Prober) run() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
cluster.Process(p)
|
cluster.Process(p.onSendProbe)
|
||||||
|
|
||||||
if cluster.IsFinished() {
|
if cluster.IsFinished() {
|
||||||
p.logger.Debugw("cluster finished", "cluster", cluster.String())
|
p.logger.Debugw("cluster finished", "cluster", cluster.String())
|
||||||
|
|
||||||
|
if p.onProbeClusterDone != nil {
|
||||||
|
p.onProbeClusterDone(cluster.GetInfo())
|
||||||
|
}
|
||||||
|
|
||||||
p.popFrontCluster(cluster)
|
p.popFrontCluster(cluster)
|
||||||
continue
|
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 {
|
type Cluster struct {
|
||||||
// LK-TODO-START
|
// LK-TODO-START
|
||||||
// Check if we can operate at cluster level without a lock.
|
// Check if we can operate at cluster level without a lock.
|
||||||
@@ -272,6 +306,7 @@ type Cluster struct {
|
|||||||
// LK-TODO-END
|
// LK-TODO-END
|
||||||
lock sync.RWMutex
|
lock sync.RWMutex
|
||||||
|
|
||||||
|
id ProbeClusterId
|
||||||
desiredBytes int
|
desiredBytes int
|
||||||
minDuration time.Duration
|
minDuration time.Duration
|
||||||
maxDuration time.Duration
|
maxDuration time.Duration
|
||||||
@@ -283,7 +318,7 @@ type Cluster struct {
|
|||||||
startTime time.Time
|
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()
|
minDurationMs := minDuration.Milliseconds()
|
||||||
desiredBytes := int((int64(desiredRateBps)*minDurationMs/time.Second.Milliseconds() + 7) / 8)
|
desiredBytes := int((int64(desiredRateBps)*minDurationMs/time.Second.Milliseconds() + 7) / 8)
|
||||||
expectedBytes := int((int64(expectedRateBps)*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
|
numProbes := (desiredBytes - expectedBytes + 999) / 1000
|
||||||
sleepDurationMicroSeconds := int(float64(minDurationMs*1000)/float64(numProbes) + 0.5)
|
sleepDurationMicroSeconds := int(float64(minDurationMs*1000)/float64(numProbes) + 0.5)
|
||||||
c := &Cluster{
|
c := &Cluster{
|
||||||
|
id: id,
|
||||||
desiredBytes: desiredBytes,
|
desiredBytes: desiredBytes,
|
||||||
minDuration: minDuration,
|
minDuration: minDuration,
|
||||||
maxDuration: maxDuration,
|
maxDuration: maxDuration,
|
||||||
@@ -349,7 +385,18 @@ func (c *Cluster) IsFinished() bool {
|
|||||||
return false
|
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()
|
c.lock.RLock()
|
||||||
|
|
||||||
timeElapsed := time.Since(c.startTime)
|
timeElapsed := time.Since(c.startTime)
|
||||||
@@ -379,8 +426,8 @@ func (c *Cluster) Process(p *Prober) {
|
|||||||
bytesShortFall = ((bytesShortFall + 274) / 275) * 275
|
bytesShortFall = ((bytesShortFall + 274) / 275) * 275
|
||||||
c.lock.RUnlock()
|
c.lock.RUnlock()
|
||||||
|
|
||||||
if bytesShortFall > 0 && p.onSendProbe != nil {
|
if bytesShortFall > 0 && onSendProbe != nil {
|
||||||
p.onSendProbe(bytesShortFall)
|
onSendProbe(bytesShortFall)
|
||||||
}
|
}
|
||||||
|
|
||||||
// LK-TODO look at adapting sleep time based on how many bytes and how much time is left
|
// 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()
|
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.desiredBytes,
|
||||||
c.bytesSentProbe,
|
c.bytesSentProbe,
|
||||||
c.bytesSentNonProbe,
|
c.bytesSentNonProbe,
|
||||||
|
|||||||
+3
-3
@@ -7,6 +7,7 @@ import (
|
|||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-logr/logr"
|
||||||
"github.com/livekit/protocol/livekit"
|
"github.com/livekit/protocol/livekit"
|
||||||
"github.com/livekit/protocol/logger"
|
"github.com/livekit/protocol/logger"
|
||||||
"github.com/pion/rtcp"
|
"github.com/pion/rtcp"
|
||||||
@@ -242,7 +243,8 @@ func (w *WebRTCReceiver) AddUpTrack(track *webrtc.TrackRemote, buff *buffer.Buff
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
buff.SetLogger(w.logger)
|
layer := RidToLayer(track.RID())
|
||||||
|
buff.SetLogger(logger.Logger(logr.Logger(w.logger).WithValues("layer", layer)))
|
||||||
buff.OnFeedback(w.sendRTCP)
|
buff.OnFeedback(w.sendRTCP)
|
||||||
|
|
||||||
var duration time.Duration
|
var duration time.Duration
|
||||||
@@ -260,7 +262,6 @@ func (w *WebRTCReceiver) AddUpTrack(track *webrtc.TrackRemote, buff *buffer.Buff
|
|||||||
buff.SetPLIThrottle(duration.Nanoseconds())
|
buff.SetPLIThrottle(duration.Nanoseconds())
|
||||||
}
|
}
|
||||||
|
|
||||||
layer := RidToLayer(track.RID())
|
|
||||||
w.upTrackMu.Lock()
|
w.upTrackMu.Lock()
|
||||||
w.upTracks[layer] = track
|
w.upTracks[layer] = track
|
||||||
w.upTrackMu.Unlock()
|
w.upTrackMu.Unlock()
|
||||||
@@ -391,7 +392,6 @@ func (w *WebRTCReceiver) SendPLI(layer int32) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
//w.logger.Debugw("SA_DEBUG, PLI request", "layer", layer) // REMOVE
|
|
||||||
buff.SendPLI()
|
buff.SendPLI()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -88,6 +88,7 @@ func (r *RTPMunger) PacketDropped(extPkt *buffer.ExtPacket) {
|
|||||||
|
|
||||||
r.highestIncomingSN = extPkt.Packet.SequenceNumber
|
r.highestIncomingSN = extPkt.Packet.SequenceNumber
|
||||||
r.snOffset += 1
|
r.snOffset += 1
|
||||||
|
r.lastSN = extPkt.Packet.SequenceNumber - r.snOffset
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *RTPMunger) UpdateAndGetSnTs(extPkt *buffer.ExtPacket) (*TranslationParamsRTP, error) {
|
func (r *RTPMunger) UpdateAndGetSnTs(extPkt *buffer.ExtPacket) (*TranslationParamsRTP, error) {
|
||||||
|
|||||||
@@ -85,9 +85,9 @@ func TestPacketDropped(t *testing.T) {
|
|||||||
}
|
}
|
||||||
extPkt, _ := testutils.GetTestExtPacket(params)
|
extPkt, _ := testutils.GetTestExtPacket(params)
|
||||||
r.SetLastSnTs(extPkt)
|
r.SetLastSnTs(extPkt)
|
||||||
require.True(t, r.highestIncomingSN == 23332)
|
require.Equal(t, r.highestIncomingSN, uint16(23332))
|
||||||
require.True(t, r.lastSN == 23333)
|
require.Equal(t, r.lastSN, uint16(23333))
|
||||||
require.True(t, r.lastTS == 0xabcdef)
|
require.Equal(t, r.lastTS, uint32(0xabcdef))
|
||||||
require.EqualValues(t, 0, r.snOffset)
|
require.EqualValues(t, 0, r.snOffset)
|
||||||
require.EqualValues(t, 0, r.tsOffset)
|
require.EqualValues(t, 0, r.tsOffset)
|
||||||
|
|
||||||
@@ -99,8 +99,8 @@ func TestPacketDropped(t *testing.T) {
|
|||||||
}
|
}
|
||||||
extPkt, _ = testutils.GetTestExtPacket(params)
|
extPkt, _ = testutils.GetTestExtPacket(params)
|
||||||
r.PacketDropped(extPkt)
|
r.PacketDropped(extPkt)
|
||||||
require.True(t, r.highestIncomingSN == 23332)
|
require.Equal(t, r.highestIncomingSN, uint16(23332))
|
||||||
require.True(t, r.lastSN == 23333)
|
require.Equal(t, r.lastSN, uint16(23333))
|
||||||
require.EqualValues(t, 0, r.snOffset)
|
require.EqualValues(t, 0, r.snOffset)
|
||||||
|
|
||||||
// drop a head packet and check offset increases
|
// drop a head packet and check offset increases
|
||||||
@@ -112,8 +112,8 @@ func TestPacketDropped(t *testing.T) {
|
|||||||
}
|
}
|
||||||
extPkt, _ = testutils.GetTestExtPacket(params)
|
extPkt, _ = testutils.GetTestExtPacket(params)
|
||||||
r.PacketDropped(extPkt)
|
r.PacketDropped(extPkt)
|
||||||
require.True(t, r.highestIncomingSN == 44444)
|
require.Equal(t, r.highestIncomingSN, uint16(44444))
|
||||||
require.True(t, r.lastSN == 23333)
|
require.Equal(t, r.lastSN, uint16(44443))
|
||||||
require.EqualValues(t, 1, r.snOffset)
|
require.EqualValues(t, 1, r.snOffset)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+442
-141
@@ -20,7 +20,19 @@ import (
|
|||||||
const (
|
const (
|
||||||
ChannelCapacityInfinity = 100 * 1000 * 1000 // 100 Mbps
|
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
|
GratuitousProbeHeadroomBps = 1 * 1000 * 1000 // if headroom > 1 Mbps, don't probe
|
||||||
GratuitousProbePct = 10
|
GratuitousProbePct = 10
|
||||||
@@ -31,16 +43,6 @@ const (
|
|||||||
|
|
||||||
AudioLossWeight = 0.75
|
AudioLossWeight = 0.75
|
||||||
VideoLossWeight = 0.25
|
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
|
type State int
|
||||||
@@ -74,6 +76,7 @@ const (
|
|||||||
SignalSubscribedLayersChange
|
SignalSubscribedLayersChange
|
||||||
SignalPeriodicPing
|
SignalPeriodicPing
|
||||||
SignalSendProbe
|
SignalSendProbe
|
||||||
|
SignalProbeClusterDone
|
||||||
)
|
)
|
||||||
|
|
||||||
func (s Signal) String() string {
|
func (s Signal) String() string {
|
||||||
@@ -96,6 +99,8 @@ func (s Signal) String() string {
|
|||||||
return "PERIODIC_PING"
|
return "PERIODIC_PING"
|
||||||
case SignalSendProbe:
|
case SignalSendProbe:
|
||||||
return "SEND_PROBE"
|
return "SEND_PROBE"
|
||||||
|
case SignalProbeClusterDone:
|
||||||
|
return "PROBE_CLUSTER_DONE"
|
||||||
default:
|
default:
|
||||||
return fmt.Sprintf("%d", int(s))
|
return fmt.Sprintf("%d", int(s))
|
||||||
}
|
}
|
||||||
@@ -125,23 +130,27 @@ type StreamAllocator struct {
|
|||||||
|
|
||||||
bwe cc.BandwidthEstimator
|
bwe cc.BandwidthEstimator
|
||||||
|
|
||||||
|
lastReceivedEstimate int64
|
||||||
|
estimator *Estimator
|
||||||
|
|
||||||
committedChannelCapacity int64
|
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
|
audioTracks map[livekit.TrackID]*Track
|
||||||
videoTracks map[livekit.TrackID]*Track
|
videoTracks map[livekit.TrackID]*Track
|
||||||
exemptVideoTracksSorted TrackSorter
|
exemptVideoTracksSorted TrackSorter
|
||||||
managedVideoTracksSorted TrackSorter
|
managedVideoTracksSorted TrackSorter
|
||||||
|
|
||||||
prober *Prober
|
|
||||||
|
|
||||||
state State
|
state State
|
||||||
|
|
||||||
eventChMu sync.RWMutex
|
eventChMu sync.RWMutex
|
||||||
@@ -153,6 +162,7 @@ type StreamAllocator struct {
|
|||||||
func NewStreamAllocator(params StreamAllocatorParams) *StreamAllocator {
|
func NewStreamAllocator(params StreamAllocatorParams) *StreamAllocator {
|
||||||
s := &StreamAllocator{
|
s := &StreamAllocator{
|
||||||
params: params,
|
params: params,
|
||||||
|
estimator: NewEstimator("non-probe", params.Logger, NumRequiredEstimatesNonProbe),
|
||||||
audioTracks: make(map[livekit.TrackID]*Track),
|
audioTracks: make(map[livekit.TrackID]*Track),
|
||||||
videoTracks: make(map[livekit.TrackID]*Track),
|
videoTracks: make(map[livekit.TrackID]*Track),
|
||||||
prober: NewProber(ProberParams{
|
prober: NewProber(ProberParams{
|
||||||
@@ -161,9 +171,10 @@ func NewStreamAllocator(params StreamAllocatorParams) *StreamAllocator {
|
|||||||
eventCh: make(chan Event, 20),
|
eventCh: make(chan Event, 20),
|
||||||
}
|
}
|
||||||
|
|
||||||
s.initializeEstimate()
|
s.resetState()
|
||||||
|
|
||||||
s.prober.OnSendProbe(s.onSendProbe)
|
s.prober.OnSendProbe(s.onSendProbe)
|
||||||
|
s.prober.OnProbeClusterDone(s.onProbeClusterDone)
|
||||||
|
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
@@ -226,11 +237,8 @@ func (s *StreamAllocator) RemoveTrack(downTrack *DownTrack) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *StreamAllocator) initializeEstimate() {
|
func (s *StreamAllocator) resetState() {
|
||||||
s.committedChannelCapacity = ChannelCapacityInfinity
|
s.resetProbe()
|
||||||
s.lastCommitTime = time.Now().Add(-EstimateCommit)
|
|
||||||
s.receivedEstimate = ChannelCapacityInfinity
|
|
||||||
s.lastEstimateDecreaseTime = time.Now()
|
|
||||||
|
|
||||||
s.state = StateStable
|
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) {
|
func (s *StreamAllocator) postEvent(event Event) {
|
||||||
s.eventChMu.RLock()
|
s.eventChMu.RLock()
|
||||||
if s.isStopped.Get() {
|
if s.isStopped.Get() {
|
||||||
@@ -360,6 +376,8 @@ func (s *StreamAllocator) handleEvent(event *Event) {
|
|||||||
s.handleSignalPeriodicPing(event)
|
s.handleSignalPeriodicPing(event)
|
||||||
case SignalSendProbe:
|
case SignalSendProbe:
|
||||||
s.handleSignalSendProbe(event)
|
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
|
// re-initialize estimate if all managed tracks are removed, let it get a fresh start
|
||||||
if len(s.managedVideoTracksSorted) == 0 {
|
if len(s.managedVideoTracksSorted) == 0 {
|
||||||
s.initializeEstimate()
|
s.resetState()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -438,7 +456,8 @@ func (s *StreamAllocator) handleSignalRemoveTrack(event *Event) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *StreamAllocator) handleSignalEstimate(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
|
// 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
|
// 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
|
// 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
|
// RTCP dispatch for same SSRC on different threads? If not, the tracking SSRC
|
||||||
// should prevent racing
|
// should prevent racing
|
||||||
// LK-TODO-END
|
// LK-TODO-END
|
||||||
|
//
|
||||||
|
|
||||||
// if there are no video tracks, ignore any straggler REMB
|
// if there are no video tracks, ignore any straggler REMB
|
||||||
if len(s.managedVideoTracksSorted) == 0 {
|
if len(s.managedVideoTracksSorted) == 0 {
|
||||||
@@ -497,38 +517,12 @@ func (s *StreamAllocator) handleSignalEstimate(event *Event) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
s.prevReceivedEstimate = s.receivedEstimate
|
s.handleNewEstimate(int64(remb.Bitrate))
|
||||||
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()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *StreamAllocator) handleSignalTargetBitrate(event *Event) {
|
func (s *StreamAllocator) handleSignalTargetBitrate(event *Event) {
|
||||||
receivedEstimate, _ := event.Data.(int)
|
receivedEstimate, _ := event.Data.(int)
|
||||||
s.prevReceivedEstimate = s.receivedEstimate
|
s.handleNewEstimate(int64(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()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// LK-TODO-START
|
// LK-TODO-START
|
||||||
@@ -596,13 +590,15 @@ func (s *StreamAllocator) handleSignalSubscribedLayersChange(event *Event) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *StreamAllocator) handleSignalPeriodicPing(event *Event) {
|
func (s *StreamAllocator) handleSignalPeriodicPing(event *Event) {
|
||||||
if s.maybeCommitEstimate() {
|
// finalize probe if necessary
|
||||||
s.allocateAllTracks()
|
if s.isInProbe() && !s.probeEndTime.IsZero() && time.Now().After(s.probeEndTime) {
|
||||||
|
s.finalizeProbe()
|
||||||
}
|
}
|
||||||
|
|
||||||
// catch up on all optimistically streamed tracks
|
// catch up on all optimistically streamed tracks
|
||||||
s.finalizeTracks()
|
s.finalizeTracks()
|
||||||
|
|
||||||
|
// probe if necessary and timing is right
|
||||||
if s.state == StateDeficient {
|
if s.state == StateDeficient {
|
||||||
s.maybeProbe()
|
s.maybeProbe()
|
||||||
}
|
}
|
||||||
@@ -629,12 +625,40 @@ func (s *StreamAllocator) handleSignalSendProbe(event *Event) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *StreamAllocator) setState(state State) {
|
func (s *StreamAllocator) handleSignalProbeClusterDone(event *Event) {
|
||||||
if s.state != state {
|
info, _ := event.Data.(ProbeClusterInfo)
|
||||||
s.params.Logger.Debugw("state change", "from", s.state, "to", state)
|
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
|
s.state = state
|
||||||
|
|
||||||
|
// reset probe to enforce a delay after state change before probing
|
||||||
|
s.lastProbeStartTime = time.Now()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *StreamAllocator) adjustState() {
|
func (s *StreamAllocator) adjustState() {
|
||||||
@@ -648,50 +672,67 @@ func (s *StreamAllocator) adjustState() {
|
|||||||
s.setState(StateStable)
|
s.setState(StateStable)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *StreamAllocator) maybeCommitEstimate() (isDecreasing bool) {
|
func (s *StreamAllocator) handleNewEstimate(receivedEstimate int64) {
|
||||||
// commit channel capacity estimate under following rules
|
s.lastReceivedEstimate = receivedEstimate
|
||||||
// 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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// don't commit too often even if the change is small.
|
// while probing, maintain estimate separately to enable keeping current committed estimate if probe fails
|
||||||
// Small changes will also get picked up during periodic check.
|
if s.isInProbe() {
|
||||||
if time.Since(s.lastCommitTime) < EstimateCommit {
|
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if s.receivedEstimate == s.committedChannelCapacity {
|
s.params.Logger.Infow(
|
||||||
// no change in estimate, no need to commit
|
"estimate trending down, updating channel capacity",
|
||||||
return
|
"old(bps)", s.committedChannelCapacity,
|
||||||
}
|
"new(bps)", s.lastReceivedEstimate,
|
||||||
|
)
|
||||||
|
s.committedChannelCapacity = s.lastReceivedEstimate
|
||||||
|
|
||||||
if s.committedChannelCapacity > s.receivedEstimate && s.committedChannelCapacity != ChannelCapacityInfinity {
|
// reset to get new set of samples for next trend
|
||||||
// this prevents declaring a decrease when coming out of init state.
|
s.estimator.Reset()
|
||||||
// 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
|
|
||||||
}
|
|
||||||
|
|
||||||
if s.committedChannelCapacity > s.receivedEstimate {
|
// reset probe to ensure it does not start too soon after a downward trend
|
||||||
s.params.Logger.Debugw("committing channel capacity(bps)", "from", s.committedChannelCapacity, "to", s.receivedEstimate)
|
s.resetProbe()
|
||||||
}
|
|
||||||
s.committedChannelCapacity = s.receivedEstimate
|
|
||||||
s.lastCommitTime = time.Now()
|
|
||||||
|
|
||||||
return
|
s.allocateAllTracks()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *StreamAllocator) allocateTrack(track *Track) {
|
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 not deficient, free pass allocate track
|
||||||
if !s.params.Config.Enabled || s.state == StateStable || !track.IsManaged() {
|
if !s.params.Config.Enabled || s.state == StateStable || !track.IsManaged() {
|
||||||
update := NewStreamStateUpdate()
|
update := NewStreamStateUpdate()
|
||||||
@@ -786,14 +827,89 @@ func (s *StreamAllocator) allocateTrack(track *Track) {
|
|||||||
s.adjustState()
|
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() {
|
func (s *StreamAllocator) allocateAllTracks() {
|
||||||
if !s.params.Config.Enabled {
|
if !s.params.Config.Enabled {
|
||||||
// nothing else to do when disabled
|
// nothing else to do when disabled
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
s.resetBoost()
|
|
||||||
|
|
||||||
//
|
//
|
||||||
// Goals:
|
// Goals:
|
||||||
// 1. Stream as many tracks as possible, i.e. no pauses.
|
// 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
|
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() {
|
func (s *StreamAllocator) maybeProbe() {
|
||||||
if !s.isTimeToBoost() {
|
if time.Since(s.lastProbeStartTime) < s.probeInterval || s.probeClusterId != ProbeClusterIdInvalid {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
s.maybeBoostLayer()
|
switch s.params.Config.ProbeMode {
|
||||||
|
case config.CongestionControlProbeModeMedia:
|
||||||
|
s.maybeProbeWithMedia()
|
||||||
s.adjustState()
|
s.adjustState()
|
||||||
|
case config.CongestionControlProbeModePadding:
|
||||||
|
s.maybeProbeWithPadding()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *StreamAllocator) maybeBoostLayer() {
|
func (s *StreamAllocator) maybeProbeWithMedia() {
|
||||||
var maxDistanceSorted MaxDistanceSorter
|
var maxDistanceSorted MaxDistanceSorter
|
||||||
for _, track := range s.managedVideoTracksSorted {
|
for _, track := range s.managedVideoTracksSorted {
|
||||||
maxDistanceSorted = append(maxDistanceSorted, track)
|
maxDistanceSorted = append(maxDistanceSorted, track)
|
||||||
}
|
}
|
||||||
sort.Sort(maxDistanceSorted)
|
sort.Sort(maxDistanceSorted)
|
||||||
|
|
||||||
// boost first deficient track in priority order
|
// boost deficient track farthest from desired layers
|
||||||
for _, track := range maxDistanceSorted {
|
for _, track := range maxDistanceSorted {
|
||||||
if !track.IsDeficient() {
|
if !track.IsDeficient() {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
allocation, boosted := track.AllocateNextHigher()
|
allocation, boosted := track.AllocateNextHigher(ChannelCapacityInfinity)
|
||||||
if boosted {
|
if !boosted {
|
||||||
s.lastBoostTime = time.Now()
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
update := NewStreamStateUpdate()
|
update := NewStreamStateUpdate()
|
||||||
update.HandleStreamingChange(allocation.change, track)
|
update.HandleStreamingChange(allocation.change, track)
|
||||||
s.maybeSendUpdate(update)
|
s.maybeSendUpdate(update)
|
||||||
|
|
||||||
|
s.lastProbeStartTime = time.Now()
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *StreamAllocator) isTimeToBoost() bool {
|
func (s *StreamAllocator) maybeProbeWithPadding() {
|
||||||
// if enough time has passed since last estimate drop or last estimate boost,
|
var maxDistanceSorted MaxDistanceSorter
|
||||||
// artificially boost estimate before allocating.
|
for _, track := range s.managedVideoTracksSorted {
|
||||||
// Checking against last estimate boost prevents multiple artificial boosts
|
maxDistanceSorted = append(maxDistanceSorted, track)
|
||||||
// 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
|
|
||||||
}
|
}
|
||||||
}
|
sort.Sort(maxDistanceSorted)
|
||||||
|
|
||||||
func (s *StreamAllocator) resetBoost() {
|
// use deficient track farthest from desired layers to find how much to probe
|
||||||
s.lastBoostTime = time.Time{}
|
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 {
|
func (s *StreamAllocator) maybeGratuitousProbe() bool {
|
||||||
if time.Since(s.lastEstimateDecreaseTime) < GratuitousProbeWait || len(s.managedVideoTracksSorted) == 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// don't gratuitously probe too often
|
// 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
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// use last received estimate for gratuitous probing base as
|
// use last received estimate for gratuitous probing base as
|
||||||
// more updates may have been received since the last commit
|
// more updates may have been received since the last commit
|
||||||
expectedRateBps := s.getExpectedBandwidthUsage()
|
expectedRateBps := s.getExpectedBandwidthUsage()
|
||||||
headroomBps := s.receivedEstimate - expectedRateBps
|
headroomBps := s.lastReceivedEstimate - expectedRateBps
|
||||||
if headroomBps > GratuitousProbeHeadroomBps {
|
if headroomBps > GratuitousProbeHeadroomBps {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
probeRateBps := (s.receivedEstimate * GratuitousProbePct) / 100
|
probeRateBps := (s.lastReceivedEstimate * GratuitousProbePct) / 100
|
||||||
if probeRateBps < GratuitousProbeMinBps {
|
if probeRateBps < GratuitousProbeMinBps {
|
||||||
probeRateBps = GratuitousProbeMinBps
|
probeRateBps = GratuitousProbeMinBps
|
||||||
}
|
}
|
||||||
@@ -1009,22 +1203,17 @@ func (s *StreamAllocator) maybeGratuitousProbe() bool {
|
|||||||
probeRateBps = GratuitousProbeMaxBps
|
probeRateBps = GratuitousProbeMaxBps
|
||||||
}
|
}
|
||||||
|
|
||||||
s.prober.AddCluster(
|
s.initProbe(expectedRateBps + probeRateBps)
|
||||||
int(s.receivedEstimate+probeRateBps),
|
s.probeClusterId = s.prober.AddCluster(
|
||||||
|
int(s.lastReceivedEstimate+probeRateBps),
|
||||||
int(expectedRateBps),
|
int(expectedRateBps),
|
||||||
GratuitousProbeMinDuration,
|
GratuitousProbeMinDuration,
|
||||||
GratuitousProbeMaxDuration,
|
GratuitousProbeMaxDuration,
|
||||||
)
|
)
|
||||||
|
|
||||||
s.lastGratuitousProbeTime = time.Now()
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *StreamAllocator) resetGratuitousProbe() {
|
|
||||||
s.prober.Reset()
|
|
||||||
s.lastGratuitousProbeTime = time.Now()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ------------------------------------------------
|
// ------------------------------------------------
|
||||||
|
|
||||||
type StreamState int
|
type StreamState int
|
||||||
@@ -1141,9 +1330,7 @@ func (t *Track) WritePaddingRTP(bytesToSend int) int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *Track) Allocate(availableChannelCapacity int64, allowPause bool) VideoAllocation {
|
func (t *Track) Allocate(availableChannelCapacity int64, allowPause bool) VideoAllocation {
|
||||||
allocation := t.downTrack.Allocate(availableChannelCapacity, allowPause)
|
return t.downTrack.Allocate(availableChannelCapacity, allowPause)
|
||||||
//t.logger.Debugw("SA_DEBUG Capacity allocation", "available", availableChannelCapacity, "alloc", allocation) // REMOVE
|
|
||||||
return allocation
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Track) ProvisionalAllocatePrepare() {
|
func (t *Track) ProvisionalAllocatePrepare() {
|
||||||
@@ -1163,15 +1350,15 @@ func (t *Track) ProvisionalAllocateGetBestWeightedTransition() VideoTransition {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *Track) ProvisionalAllocateCommit() VideoAllocation {
|
func (t *Track) ProvisionalAllocateCommit() VideoAllocation {
|
||||||
allocation := t.downTrack.ProvisionalAllocateCommit()
|
return t.downTrack.ProvisionalAllocateCommit()
|
||||||
//t.logger.Debugw("SA_DEBUG Provisional commit", "alloc", allocation) // REMOVE
|
|
||||||
return allocation
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Track) AllocateNextHigher() (VideoAllocation, bool) {
|
func (t *Track) AllocateNextHigher(availableChannelCapacity int64) (VideoAllocation, bool) {
|
||||||
allocation, boosted := t.downTrack.AllocateNextHigher()
|
return t.downTrack.AllocateNextHigher(availableChannelCapacity)
|
||||||
//t.logger.Debugw("SA_DEBUG Probe next higher layer", "alloc", allocation, "boosted", boosted) // REMOVE
|
}
|
||||||
return allocation, boosted
|
|
||||||
|
func (t *Track) GetNextHigherTransition() (VideoTransition, bool) {
|
||||||
|
return t.downTrack.GetNextHigherTransition()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Track) FinalizeAllocate() {
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------
|
||||||
|
|||||||
Reference in New Issue
Block a user