TWCC probing (#3234)

* WIP

* WIP

* WIP

* make it compile

* typo

* clean up

* fmt

* fixes
This commit is contained in:
Raja Subramanian
2024-12-06 00:13:36 +05:30
committed by GitHub
parent d862917249
commit 94488d434d
16 changed files with 911 additions and 454 deletions
-277
View File
@@ -1,277 +0,0 @@
// Copyright 2023 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package streamallocator
import (
"fmt"
"sync"
"time"
"github.com/livekit/livekit-server/pkg/sfu/bwe"
"github.com/livekit/livekit-server/pkg/sfu/ccutils"
"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/utils/mono"
)
const (
cDefaultRTT = float64(0.070) // 70 ms
cRTTSmoothingFactor = float64(0.5)
)
// ---------------------------------------------------------------------------
type ProbeControllerState int
const (
ProbeControllerStateNone ProbeControllerState = iota
ProbeControllerStateProbing
ProbeControllerStateHangover
)
func (p ProbeControllerState) String() string {
switch p {
case ProbeControllerStateNone:
return "NONE"
case ProbeControllerStateProbing:
return "PROBING"
case ProbeControllerStateHangover:
return "HANGOVER"
default:
return fmt.Sprintf("%d", int(p))
}
}
// ------------------------------------------------
type ProbeControllerConfig struct {
BaseInterval time.Duration `yaml:"base_interval,omitempty"`
BackoffFactor float64 `yaml:"backoff_factor,omitempty"`
MaxInterval time.Duration `yaml:"max_interval,omitempty"`
SettleWaitNumRTT uint32 `yaml:"settle_wait_num_rtt,omitempty"`
SettleWaitMin time.Duration `yaml:"settle_wait_min,omitempty"`
SettleWaitMax time.Duration `yaml:"settle_wait_max,omitempty"`
OveragePct int64 `yaml:"overage_pct,omitempty"`
MinBps int64 `yaml:"min_bps,omitempty"`
MinDuration time.Duration `yaml:"min_duration,omitempty"`
MaxDuration time.Duration `yaml:"max_duration,omitempty"`
DurationIncreaseFactor float64 `yaml:"duration_increase_factor,omitempty"`
}
var (
DefaultProbeControllerConfig = ProbeControllerConfig{
BaseInterval: 3 * time.Second,
BackoffFactor: 1.5,
MaxInterval: 2 * time.Minute,
SettleWaitNumRTT: 10,
SettleWaitMin: 500 * time.Millisecond,
SettleWaitMax: 10 * time.Second,
OveragePct: 120,
MinBps: 200_000,
MinDuration: 200 * time.Millisecond,
MaxDuration: 20 * time.Second,
DurationIncreaseFactor: 1.5,
}
)
// ---------------------------------------------------------------------------
type ProbeControllerParams struct {
Config ProbeControllerConfig
Logger logger.Logger
}
type ProbeController struct {
params ProbeControllerParams
lock sync.RWMutex
state ProbeControllerState
stateSwitchedAt time.Time
pci ccutils.ProbeClusterInfo
rtt float64
probeInterval time.Duration
probeDuration time.Duration
nextProbeEarliestAt time.Time
}
func NewProbeController(params ProbeControllerParams) *ProbeController {
p := &ProbeController{
params: params,
rtt: cDefaultRTT,
}
p.Reset()
return p
}
func (p *ProbeController) Reset() {
p.lock.Lock()
defer p.lock.Unlock()
p.state = ProbeControllerStateNone
p.stateSwitchedAt = mono.Now()
p.pci = ccutils.ProbeClusterInfoInvalid
p.probeInterval = p.params.Config.BaseInterval
p.probeDuration = p.params.Config.MinDuration
p.nextProbeEarliestAt = mono.Now()
}
func (p *ProbeController) UpdateRTT(rtt float64) {
if rtt == 0 {
p.rtt = cDefaultRTT
} else {
if p.rtt == 0 {
p.rtt = rtt
} else {
p.rtt = cRTTSmoothingFactor*rtt + (1.0-cRTTSmoothingFactor)*p.rtt
}
}
}
func (p *ProbeController) CanProbe() bool {
p.lock.RLock()
defer p.lock.RUnlock()
return p.state == ProbeControllerStateNone && mono.Now().After(p.nextProbeEarliestAt)
}
func (p *ProbeController) MaybeInitiateProbe(availableBandwidthBps int64, probeGoalDeltaBps int64, expectedBandwidthUsage int64) (ccutils.ProbeClusterGoal, bool) {
p.lock.RLock()
defer p.lock.RUnlock()
if p.state != ProbeControllerStateNone {
// already probing or in probe hangover, don't start a new one
return ccutils.ProbeClusterGoal{}, false
}
if mono.Now().Before(p.nextProbeEarliestAt) {
return ccutils.ProbeClusterGoal{}, false
}
// overshoot a bit to account for noise (in measurement/estimate etc)
desiredIncreaseBps := (probeGoalDeltaBps * p.params.Config.OveragePct) / 100
if desiredIncreaseBps < p.params.Config.MinBps {
desiredIncreaseBps = p.params.Config.MinBps
}
return ccutils.ProbeClusterGoal{
AvailableBandwidthBps: int(availableBandwidthBps),
ExpectedUsageBps: int(expectedBandwidthUsage),
DesiredBps: int(expectedBandwidthUsage + desiredIncreaseBps),
Duration: p.probeDuration,
}, true
}
func (p *ProbeController) ProbeClusterStarting(pci ccutils.ProbeClusterInfo) {
p.lock.Lock()
defer p.lock.Unlock()
if p.state != ProbeControllerStateNone {
p.params.Logger.Warnw("unexpected probe controller state", nil, "state", p.state)
}
p.setState(ProbeControllerStateProbing)
p.pci = pci
}
func (p *ProbeController) ProbeClusterDone(pci ccutils.ProbeClusterInfo) {
p.lock.Lock()
defer p.lock.Unlock()
if p.pci.Id == pci.Id {
p.pci.Result = pci.Result
p.setState(ProbeControllerStateHangover)
}
}
func (p *ProbeController) MaybeFinalizeProbe() (ccutils.ProbeClusterInfo, bool) {
p.lock.Lock()
defer p.lock.Unlock()
if p.state != ProbeControllerStateHangover {
return ccutils.ProbeClusterInfoInvalid, false
}
settleWait := time.Duration(float64(p.params.Config.SettleWaitNumRTT) * p.rtt * float64(time.Second))
if settleWait < p.params.Config.SettleWaitMin {
settleWait = p.params.Config.SettleWaitMin
}
if settleWait > p.params.Config.SettleWaitMax {
settleWait = p.params.Config.SettleWaitMax
}
if time.Since(p.stateSwitchedAt) < settleWait {
return ccutils.ProbeClusterInfoInvalid, false
}
p.setState(ProbeControllerStateNone)
return p.pci, true
}
func (p *ProbeController) ProbeSignal(probeSignal bwe.ProbeSignal) {
if probeSignal == bwe.ProbeSignalCongesting {
// wait longer till next probe
p.probeInterval = time.Duration(p.probeInterval.Seconds()*p.params.Config.BackoffFactor) * time.Second
if p.probeInterval > p.params.Config.MaxInterval {
p.probeInterval = p.params.Config.MaxInterval
}
// revert back to starting with shortest probe
p.probeDuration = p.params.Config.MinDuration
} else {
// probe can be started again after minimal interval as previous congestion signal indicated congestion clearing
p.probeInterval = p.params.Config.BaseInterval
// can do longer probe after a good probe
p.probeDuration = time.Duration(float64(p.probeDuration.Milliseconds())*p.params.Config.DurationIncreaseFactor) * time.Millisecond
if p.probeDuration > p.params.Config.MaxDuration {
p.probeDuration = p.params.Config.MaxDuration
}
}
if p.pci.CreatedAt.IsZero() {
p.nextProbeEarliestAt = mono.Now().Add(p.probeInterval)
} else {
p.nextProbeEarliestAt = p.pci.CreatedAt.Add(p.probeInterval)
}
}
func (p *ProbeController) GetActiveProbeClusterId() ccutils.ProbeClusterId {
p.lock.RLock()
defer p.lock.RUnlock()
if p.state == ProbeControllerStateNone {
return ccutils.ProbeClusterIdInvalid
}
return p.pci.Id
}
func (p *ProbeController) setState(state ProbeControllerState) {
if state == p.state {
return
}
p.state = state
p.stateSwitchedAt = mono.Now()
}
// ------------------------------------------------
+72 -53
View File
@@ -157,16 +157,20 @@ const (
)
type StreamAllocatorConfig struct {
ProbeMode ProbeMode `yaml:"probe_mode,omitempty"`
MinChannelCapacity int64 `yaml:"min_channel_capacity,omitempty"`
ProbeController ProbeControllerConfig `yaml:"probe_controller,omitempty"`
DisableEstimationUnmanagedTracks bool `yaml:"disable_etimation_unmanaged_tracks,omitempty"`
ProbeMode ProbeMode `yaml:"probe_mode,omitempty"`
MinChannelCapacity int64 `yaml:"min_channel_capacity,omitempty"`
DisableEstimationUnmanagedTracks bool `yaml:"disable_etimation_unmanaged_tracks,omitempty"`
ProbeOveragePct int64 `yaml:"probe_overage_pct,omitempty"`
ProbeMinBps int64 `yaml:"probe_min_bps,omitempty"`
}
var (
DefaultStreamAllocatorConfig = StreamAllocatorConfig{
ProbeMode: ProbeModePadding,
ProbeController: DefaultProbeControllerConfig,
ProbeMode: ProbeModePadding,
ProbeOveragePct: 120,
ProbeMinBps: 200_000,
}
)
@@ -193,8 +197,7 @@ type StreamAllocator struct {
committedChannelCapacity int64
overriddenChannelCapacity int64
probeController *ProbeController
prober *ccutils.Prober
prober *ccutils.Prober
// STREAM-ALLOCATOR-DATA rateMonitor *RateMonitor
@@ -203,8 +206,9 @@ type StreamAllocator struct {
isAllocateAllPending bool
rembTrackingSSRC uint32
state streamAllocatorState
isHolding bool
state streamAllocatorState
isHolding bool
activeProbeClusterId ccutils.ProbeClusterId
eventsQueue *utils.TypedOpsQueue[Event]
@@ -219,8 +223,9 @@ func NewStreamAllocator(params StreamAllocatorParams, enabled bool, allowPause b
enabled: enabled,
allowPause: allowPause,
// STREAM-ALLOCATOR-DATA rateMonitor: NewRateMonitor(),
videoTracks: make(map[livekit.TrackID]*Track),
state: streamAllocatorStateStable,
videoTracks: make(map[livekit.TrackID]*Track),
state: streamAllocatorStateStable,
activeProbeClusterId: ccutils.ProbeClusterIdInvalid,
eventsQueue: utils.NewTypedOpsQueue[Event](utils.OpsQueueParams{
Name: "stream-allocator",
MinSize: 64,
@@ -234,11 +239,6 @@ func NewStreamAllocator(params StreamAllocatorParams, enabled bool, allowPause b
Logger: params.Logger,
})
s.probeController = NewProbeController(ProbeControllerParams{
Config: s.params.Config.ProbeController,
Logger: params.Logger,
})
s.params.BWE.SetBWEListener(s)
s.params.Pacer.SetPacerProbeObserverListener(s)
@@ -298,7 +298,7 @@ func (s *StreamAllocator) AddTrack(downTrack *sfu.DownTrack, params AddTrackPara
}
downTrack.SetStreamAllocatorListener(s)
downTrack.SetProbeClusterId(s.prober.GetActiveClusterId())
downTrack.SetProbeClusterId(s.activeProbeClusterId)
s.maybePostEventAllocateTrack(downTrack)
}
@@ -694,22 +694,25 @@ func (s *StreamAllocator) handleSignalEstimate(event Event) {
func (s *StreamAllocator) handleSignalPeriodicPing(Event) {
// finalize any probe that may have finished/aborted
if pci, ok := s.probeController.MaybeFinalizeProbe(); ok {
probeSignal, channelCapacity := s.params.BWE.ProbeClusterDone(pci)
s.params.Logger.Debugw(
"stream allocator: probe result",
"probeSignal", probeSignal,
"channelCapacity", channelCapacity,
)
if probeSignal != bwe.ProbeSignalCongesting {
if channelCapacity > s.committedChannelCapacity {
s.committedChannelCapacity = channelCapacity
if s.activeProbeClusterId != ccutils.ProbeClusterIdInvalid {
if probeSignal, channelCapacity, isFinalized := s.params.BWE.ProbeClusterFinalize(); isFinalized {
s.params.Logger.Debugw(
"stream allocator: probe result",
"probeClusterId", s.activeProbeClusterId,
"probeSignal", probeSignal,
"channelCapacity", channelCapacity,
)
s.activeProbeClusterId = ccutils.ProbeClusterIdInvalid
if probeSignal != ccutils.ProbeSignalCongesting {
if channelCapacity > s.committedChannelCapacity {
s.committedChannelCapacity = channelCapacity
}
s.maybeBoostDeficientTracks()
}
s.maybeBoostDeficientTracks()
}
s.probeController.ProbeSignal(probeSignal)
}
// probe if necessary and timing is right
@@ -722,7 +725,7 @@ func (s *StreamAllocator) handleSignalPeriodicPing(Event) {
if s.params.RTTGetter != nil {
if rtt, ok := s.params.RTTGetter(); ok {
s.probeController.UpdateRTT(rtt)
s.params.BWE.UpdateRTT(rtt)
}
}
}
@@ -735,7 +738,8 @@ func (s *StreamAllocator) handleSignalPeriodicPing(Event) {
func (s *StreamAllocator) handleSignalProbeClusterSwitch(event Event) {
pci := event.Data.(ccutils.ProbeClusterInfo)
s.probeController.ProbeClusterStarting(pci)
s.activeProbeClusterId = pci.Id
s.params.BWE.ProbeClusterStarting(pci)
s.params.Pacer.StartProbeCluster(pci)
@@ -765,7 +769,12 @@ func (s *StreamAllocator) handleSignalSendProbe(event Event) {
func (s *StreamAllocator) handleSignalPacerProbeObserverClusterComplete(event Event) {
probeClusterId, _ := event.Data.(ccutils.ProbeClusterId)
pci := s.params.Pacer.EndProbeCluster(probeClusterId)
s.probeController.ProbeClusterDone(pci)
for _, t := range s.getTracks() {
t.DownTrack().SwapProbeClusterId(pci.Id, ccutils.ProbeClusterIdInvalid)
}
s.params.BWE.ProbeClusterDone(pci)
s.prober.ClusterDone(pci)
}
@@ -850,7 +859,7 @@ func (s *StreamAllocator) handleSignalCongestionStateChange(event Event) {
}
if cscd.congestionState == bwe.CongestionStateCongested {
if s.probeController.GetActiveProbeClusterId() != ccutils.ProbeClusterIdInvalid {
if s.activeProbeClusterId != ccutils.ProbeClusterIdInvalid {
s.params.Logger.Infow(
"stream allocator: channel congestion detected, not updating channel capacity in active probe",
"old(bps)", s.committedChannelCapacity,
@@ -887,12 +896,10 @@ func (s *StreamAllocator) setState(state streamAllocatorState) {
s.params.Logger.Infow("stream allocator: state change", "from", s.state, "to", state)
s.state = state
// restart everything when when state is stable
// restart everything when state is STABLE
if state == streamAllocatorStateStable {
s.maybeStopProbe()
s.probeController.Reset()
s.params.BWE.Reset()
}
}
@@ -1064,12 +1071,13 @@ func (s *StreamAllocator) allocateTrack(track *Track) {
}
func (s *StreamAllocator) maybeStopProbe() {
activeProbeClusterId := s.probeController.GetActiveProbeClusterId()
if activeProbeClusterId != ccutils.ProbeClusterIdInvalid {
pci := s.params.Pacer.EndProbeCluster(activeProbeClusterId)
s.probeController.ProbeClusterDone(pci)
s.prober.Reset(pci)
if s.activeProbeClusterId == ccutils.ProbeClusterIdInvalid {
return
}
pci := s.params.Pacer.EndProbeCluster(s.activeProbeClusterId)
s.params.BWE.ProbeClusterDone(pci)
s.prober.Reset(pci)
}
func (s *StreamAllocator) maybeBoostDeficientTracks() {
@@ -1296,7 +1304,7 @@ func (s *StreamAllocator) maybeProbe() {
return
}
if s.params.BWE.CongestionState() != bwe.CongestionStateNone || !s.probeController.CanProbe() {
if !s.params.BWE.CanProbe() {
return
}
@@ -1321,7 +1329,7 @@ func (s *StreamAllocator) maybeProbeWithMedia() {
updateStreamStateChange(track, allocation, update)
s.maybeSendUpdate(update)
s.probeController.Reset()
s.params.BWE.Reset()
break
}
}
@@ -1334,14 +1342,25 @@ func (s *StreamAllocator) maybeProbeWithPadding() {
continue
}
pcg, ok := s.probeController.MaybeInitiateProbe(s.committedChannelCapacity, transition.BandwidthDelta, s.getExpectedBandwidthUsage())
if ok {
pci := s.prober.AddCluster(ccutils.ProbeClusterModeUniform, pcg)
s.params.Logger.Debugw(
"stream allocator: starting probe",
"probeClusterInfo", pci,
)
// overshoot a bit to account for noise (in measurement/estimate etc)
desiredIncreaseBps := (transition.BandwidthDelta * s.params.Config.ProbeOveragePct) / 100
if desiredIncreaseBps < s.params.Config.ProbeMinBps {
desiredIncreaseBps = s.params.Config.ProbeMinBps
}
expectedBandwidthUsage := s.getExpectedBandwidthUsage()
pci := s.prober.AddCluster(
ccutils.ProbeClusterModeUniform,
ccutils.ProbeClusterGoal{
AvailableBandwidthBps: int(s.committedChannelCapacity),
ExpectedUsageBps: int(expectedBandwidthUsage),
DesiredBps: int(expectedBandwidthUsage + desiredIncreaseBps),
Duration: s.params.BWE.ProbeDuration(),
},
)
s.params.Logger.Debugw(
"stream allocator: adding probe",
"probeClusterInfo", pci,
)
break
}
}