StreamAllocator (congestion controller) refactor (#3180)
* refactor WIP * WIP * compiling * runlock * fixes * fmt * stringer and unlikely logger * clean up
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
// 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 bwe
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/pion/rtcp"
|
||||
)
|
||||
|
||||
// ------------------------------------------------
|
||||
|
||||
type CongestionState int
|
||||
|
||||
const (
|
||||
CongestionStateNone CongestionState = iota
|
||||
CongestionStateEarlyWarning
|
||||
CongestionStateEarlyWarningHangover
|
||||
CongestionStateCongested
|
||||
CongestionStateCongestedHangover
|
||||
)
|
||||
|
||||
func (c CongestionState) String() string {
|
||||
switch c {
|
||||
case CongestionStateNone:
|
||||
return "NONE"
|
||||
case CongestionStateEarlyWarning:
|
||||
return "EARLY_WARNING"
|
||||
case CongestionStateEarlyWarningHangover:
|
||||
return "EARLY_WARNING_HANGOVER"
|
||||
case CongestionStateCongested:
|
||||
return "CONGESTED"
|
||||
case CongestionStateCongestedHangover:
|
||||
return "CONGESTED_HANGOVER"
|
||||
default:
|
||||
return fmt.Sprintf("%d", int(c))
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------
|
||||
|
||||
type ChannelTrend int
|
||||
|
||||
const (
|
||||
ChannelTrendNeutral ChannelTrend = iota
|
||||
ChannelTrendClearing
|
||||
ChannelTrendCongesting
|
||||
)
|
||||
|
||||
func (c ChannelTrend) String() string {
|
||||
switch c {
|
||||
case ChannelTrendNeutral:
|
||||
return "NEUTRAL"
|
||||
case ChannelTrendClearing:
|
||||
return "CLEARING"
|
||||
case ChannelTrendCongesting:
|
||||
return "CONGESTING"
|
||||
default:
|
||||
return fmt.Sprintf("%d", int(c))
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------
|
||||
|
||||
type BWE interface {
|
||||
SetBWEListener(bweListner BWEListener)
|
||||
|
||||
Reset()
|
||||
|
||||
Stop()
|
||||
|
||||
HandleREMB(
|
||||
receivedEstimate int64,
|
||||
isProbeFinalizing bool,
|
||||
expectedBandwidthUsage int64,
|
||||
sentPackets uint32,
|
||||
repeatedNacks uint32,
|
||||
)
|
||||
|
||||
HandleTWCCFeedback(report *rtcp.TransportLayerCC)
|
||||
|
||||
ProbingStart(expectedBandwidthUsage int64)
|
||||
ProbingEnd(isNotFailing bool, isGoalReached bool)
|
||||
GetProbeStatus() (isValidSignal bool, trend ChannelTrend, lowestEstimate int64, highestEstimate int64)
|
||||
}
|
||||
|
||||
// ------------------------------------------------
|
||||
|
||||
type BWEListener interface {
|
||||
OnCongestionStateChange(congestionState CongestionState, estimatedAvailableChannelCapacity int64)
|
||||
}
|
||||
|
||||
// ------------------------------------------------
|
||||
@@ -0,0 +1,47 @@
|
||||
// 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 bwe
|
||||
|
||||
import "github.com/pion/rtcp"
|
||||
|
||||
type NullBWE struct {
|
||||
}
|
||||
|
||||
func (n *NullBWE) SetBWEListener(_bweListener BWEListener) {}
|
||||
|
||||
func (n *NullBWE) Reset() {}
|
||||
|
||||
func (n *NullBWE) Stop() {}
|
||||
|
||||
func (n *NullBWE) HandleREMB(
|
||||
_receivedEstimate int64,
|
||||
_isProbeFinalizing bool,
|
||||
_expectedBandwidthUsage int64,
|
||||
_sentPackets uint32,
|
||||
_repeatedNacks uint32,
|
||||
) {
|
||||
}
|
||||
|
||||
func (n *NullBWE) HandleTWCCFeedback(_report *rtcp.TransportLayerCC) {}
|
||||
|
||||
func (n *NullBWE) ProbingStart(_expectedBandwidthUsage int64) {}
|
||||
|
||||
func (n *NullBWE) ProbingEnd(_isNotFailing bool, _isGoalReached bool) {}
|
||||
|
||||
func (n *NullBWE) GetProbeStatus() (bool, ChannelTrend, int64, int64) {
|
||||
return false, ChannelTrendNeutral, 0, 0
|
||||
}
|
||||
|
||||
// ------------------------------------------------
|
||||
@@ -0,0 +1,175 @@
|
||||
// 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 remotebwe
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/sfu/bwe"
|
||||
"github.com/livekit/livekit-server/pkg/sfu/ccutils"
|
||||
"github.com/livekit/protocol/logger"
|
||||
)
|
||||
|
||||
// ------------------------------------------------
|
||||
|
||||
type channelCongestionReason int
|
||||
|
||||
const (
|
||||
channelCongestionReasonNone channelCongestionReason = iota
|
||||
channelCongestionReasonEstimate
|
||||
channelCongestionReasonLoss
|
||||
)
|
||||
|
||||
func (c channelCongestionReason) String() string {
|
||||
switch c {
|
||||
case channelCongestionReasonNone:
|
||||
return "NONE"
|
||||
case channelCongestionReasonEstimate:
|
||||
return "ESTIMATE"
|
||||
case channelCongestionReasonLoss:
|
||||
return "LOSS"
|
||||
default:
|
||||
return fmt.Sprintf("%d", int(c))
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------
|
||||
|
||||
type ChannelObserverConfig struct {
|
||||
Estimate ccutils.TrendDetectorConfig `yaml:"estimate,omitempty"`
|
||||
Nack NackTrackerConfig `yaml:"nack,omitempty"`
|
||||
}
|
||||
|
||||
var (
|
||||
defaultTrendDetectorConfigProbe = ccutils.TrendDetectorConfig{
|
||||
RequiredSamples: 3,
|
||||
RequiredSamplesMin: 3,
|
||||
DownwardTrendThreshold: 0.0,
|
||||
DownwardTrendMaxWait: 5 * time.Second,
|
||||
CollapseThreshold: 0,
|
||||
ValidityWindow: 10 * time.Second,
|
||||
}
|
||||
|
||||
defaultChannelObserverConfigProbe = ChannelObserverConfig{
|
||||
Estimate: defaultTrendDetectorConfigProbe,
|
||||
Nack: defaultNackTrackerConfigProbe,
|
||||
}
|
||||
|
||||
defaultTrendDetectorConfigNonProbe = ccutils.TrendDetectorConfig{
|
||||
RequiredSamples: 12,
|
||||
RequiredSamplesMin: 8,
|
||||
DownwardTrendThreshold: -0.6,
|
||||
DownwardTrendMaxWait: 5 * time.Second,
|
||||
CollapseThreshold: 500 * time.Millisecond,
|
||||
ValidityWindow: 10 * time.Second,
|
||||
}
|
||||
|
||||
defaultChannelObserverConfigNonProbe = ChannelObserverConfig{
|
||||
Estimate: defaultTrendDetectorConfigNonProbe,
|
||||
Nack: defaultNackTrackerConfigNonProbe,
|
||||
}
|
||||
)
|
||||
|
||||
// ------------------------------------------------
|
||||
|
||||
type channelObserverParams struct {
|
||||
Name string
|
||||
Config ChannelObserverConfig
|
||||
}
|
||||
|
||||
type channelObserver struct {
|
||||
params channelObserverParams
|
||||
logger logger.Logger
|
||||
|
||||
estimateTrend *ccutils.TrendDetector[int64]
|
||||
nackTracker *nackTracker
|
||||
}
|
||||
|
||||
func newChannelObserver(params channelObserverParams, logger logger.Logger) *channelObserver {
|
||||
return &channelObserver{
|
||||
params: params,
|
||||
logger: logger,
|
||||
estimateTrend: ccutils.NewTrendDetector[int64](ccutils.TrendDetectorParams{
|
||||
Name: params.Name + "-estimate",
|
||||
Logger: logger,
|
||||
Config: params.Config.Estimate,
|
||||
}),
|
||||
nackTracker: newNackTracker(nackTrackerParams{
|
||||
Name: params.Name + "-nack",
|
||||
Logger: logger,
|
||||
Config: params.Config.Nack,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *channelObserver) SeedEstimate(estimate int64) {
|
||||
c.estimateTrend.Seed(estimate)
|
||||
}
|
||||
|
||||
func (c *channelObserver) AddEstimate(estimate int64) {
|
||||
c.estimateTrend.AddValue(estimate)
|
||||
}
|
||||
|
||||
func (c *channelObserver) AddNack(packets uint32, repeatedNacks uint32) {
|
||||
c.nackTracker.Add(packets, repeatedNacks)
|
||||
}
|
||||
|
||||
func (c *channelObserver) GetLowestEstimate() int64 {
|
||||
return c.estimateTrend.GetLowest()
|
||||
}
|
||||
|
||||
func (c *channelObserver) GetHighestEstimate() int64 {
|
||||
return c.estimateTrend.GetHighest()
|
||||
}
|
||||
|
||||
func (c *channelObserver) HasEnoughEstimateSamples() bool {
|
||||
return c.estimateTrend.HasEnoughSamples()
|
||||
}
|
||||
|
||||
func (c *channelObserver) GetNackRatio() float64 {
|
||||
return c.nackTracker.GetRatio()
|
||||
}
|
||||
|
||||
/* REMOTE-BWE-DATA
|
||||
func (c *channelObserver) GetNackHistory() []string {
|
||||
return c.nackTracker.GetHistory()
|
||||
}
|
||||
*/
|
||||
|
||||
func (c *channelObserver) GetTrend() (bwe.ChannelTrend, channelCongestionReason) {
|
||||
estimateDirection := c.estimateTrend.GetDirection()
|
||||
|
||||
switch {
|
||||
case estimateDirection == ccutils.TrendDirectionDownward:
|
||||
c.logger.Debugw("stream allocator: channel observer: estimate is trending downward", "channel", c)
|
||||
return bwe.ChannelTrendCongesting, channelCongestionReasonEstimate
|
||||
|
||||
case c.nackTracker.IsTriggered():
|
||||
c.logger.Debugw("stream allocator: channel observer: high rate of repeated NACKs", "channel", c)
|
||||
return bwe.ChannelTrendCongesting, channelCongestionReasonLoss
|
||||
|
||||
case estimateDirection == ccutils.TrendDirectionUpward:
|
||||
return bwe.ChannelTrendClearing, channelCongestionReasonNone
|
||||
}
|
||||
|
||||
return bwe.ChannelTrendNeutral, channelCongestionReasonNone
|
||||
}
|
||||
|
||||
func (c *channelObserver) String() string {
|
||||
return fmt.Sprintf("name: %s, estimate: {%v}, nack {%v}", c.params.Name, c.estimateTrend, c.nackTracker)
|
||||
}
|
||||
|
||||
// ------------------------------------------------
|
||||
@@ -0,0 +1,143 @@
|
||||
// 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 remotebwe
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/livekit/protocol/logger"
|
||||
)
|
||||
|
||||
// ------------------------------------------------
|
||||
|
||||
type NackTrackerConfig struct {
|
||||
WindowMinDuration time.Duration `yaml:"window_min_duration,omitempty"`
|
||||
WindowMaxDuration time.Duration `yaml:"window_max_duration,omitempty"`
|
||||
RatioThreshold float64 `yaml:"ratio_threshold,omitempty"`
|
||||
}
|
||||
|
||||
var (
|
||||
defaultNackTrackerConfigProbe = NackTrackerConfig{
|
||||
WindowMinDuration: 500 * time.Millisecond,
|
||||
WindowMaxDuration: 1 * time.Second,
|
||||
RatioThreshold: 0.04,
|
||||
}
|
||||
|
||||
defaultNackTrackerConfigNonProbe = NackTrackerConfig{
|
||||
WindowMinDuration: 2 * time.Second,
|
||||
WindowMaxDuration: 3 * time.Second,
|
||||
RatioThreshold: 0.08,
|
||||
}
|
||||
)
|
||||
|
||||
// ------------------------------------------------
|
||||
|
||||
type nackTrackerParams struct {
|
||||
Name string
|
||||
Logger logger.Logger
|
||||
Config NackTrackerConfig
|
||||
}
|
||||
|
||||
type nackTracker struct {
|
||||
params nackTrackerParams
|
||||
|
||||
windowStartTime time.Time
|
||||
packets uint32
|
||||
repeatedNacks uint32
|
||||
|
||||
/* REMOTE-BWE-DATA
|
||||
// REMOTE-BWE-EXPERIMENTAL-TODO: remove when cleaning up experimental stuff
|
||||
history []string
|
||||
*/
|
||||
}
|
||||
|
||||
func newNackTracker(params nackTrackerParams) *nackTracker {
|
||||
return &nackTracker{
|
||||
params: params,
|
||||
// REMOTE-BWE-DATA history: make([]string, 0, 10),
|
||||
}
|
||||
}
|
||||
|
||||
func (n *nackTracker) Add(packets uint32, repeatedNacks uint32) {
|
||||
if n.params.Config.WindowMaxDuration != 0 && !n.windowStartTime.IsZero() && time.Since(n.windowStartTime) > n.params.Config.WindowMaxDuration {
|
||||
// REMOTE-BWE-DATA n.updateHistory()
|
||||
|
||||
n.windowStartTime = time.Time{}
|
||||
n.packets = 0
|
||||
n.repeatedNacks = 0
|
||||
}
|
||||
|
||||
//
|
||||
// Start NACK monitoring window only when a repeated NACK happens.
|
||||
// This allows locking tightly to when NACKs start happening and
|
||||
// check if the NACKs keep adding up (potentially a sign of congestion)
|
||||
// or isolated losses
|
||||
//
|
||||
if n.repeatedNacks == 0 && repeatedNacks != 0 {
|
||||
n.windowStartTime = time.Now()
|
||||
}
|
||||
|
||||
if !n.windowStartTime.IsZero() {
|
||||
n.packets += packets
|
||||
n.repeatedNacks += repeatedNacks
|
||||
}
|
||||
}
|
||||
|
||||
func (n *nackTracker) GetRatio() float64 {
|
||||
ratio := 0.0
|
||||
if n.packets != 0 {
|
||||
ratio = float64(n.repeatedNacks) / float64(n.packets)
|
||||
if ratio > 1.0 {
|
||||
ratio = 1.0
|
||||
}
|
||||
}
|
||||
|
||||
return ratio
|
||||
}
|
||||
|
||||
func (n *nackTracker) IsTriggered() bool {
|
||||
if n.params.Config.WindowMinDuration != 0 && !n.windowStartTime.IsZero() && time.Since(n.windowStartTime) > n.params.Config.WindowMinDuration {
|
||||
return n.GetRatio() > n.params.Config.RatioThreshold
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (n *nackTracker) ToString() string {
|
||||
window := ""
|
||||
if !n.windowStartTime.IsZero() {
|
||||
now := time.Now()
|
||||
elapsed := now.Sub(n.windowStartTime).Seconds()
|
||||
window = fmt.Sprintf("t: %+v|%+v|%.2fs", n.windowStartTime.Format(time.UnixDate), now.Format(time.UnixDate), elapsed)
|
||||
}
|
||||
return fmt.Sprintf("n: %s, %s, p: %d, rn: %d, rn/p: %.2f", n.params.Name, window, n.packets, n.repeatedNacks, n.GetRatio())
|
||||
}
|
||||
|
||||
/* REMOTE-BWE-DATA
|
||||
func (n *nackTracker) GetHistory() []string {
|
||||
return n.history
|
||||
}
|
||||
|
||||
func (n *nackTracker) updateHistory() {
|
||||
if len(n.history) >= 10 {
|
||||
n.history = n.history[1:]
|
||||
}
|
||||
|
||||
n.history = append(n.history, n.ToString())
|
||||
}
|
||||
*/
|
||||
|
||||
// ------------------------------------------------
|
||||
@@ -0,0 +1,369 @@
|
||||
// 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 remotebwe
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/frostbyte73/core"
|
||||
"github.com/livekit/livekit-server/pkg/sfu/bwe"
|
||||
"github.com/livekit/protocol/logger"
|
||||
"github.com/livekit/protocol/utils/mono"
|
||||
)
|
||||
|
||||
const (
|
||||
ChannelCapacityInfinity = 100 * 1000 * 1000 // 100 Mbps
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type RemoteBWEConfig struct {
|
||||
NackRatioAttenuator float64 `yaml:"nack_ratio_attenuator,omitempty"`
|
||||
ExpectedUsageThreshold float64 `yaml:"expected_usage_threshold,omitempty"`
|
||||
ChannelObserverProbe ChannelObserverConfig `yaml:"channel_observer_probe,omitempty"`
|
||||
ChannelObserverNonProbe ChannelObserverConfig `yaml:"channel_observer_non_probe,omitempty"`
|
||||
CongestedMinDuration time.Duration `yaml:"congested_min_duration,omitempty"`
|
||||
|
||||
PeriodicCheckInterval time.Duration `yaml:"periodic_check_interval,omitempty"`
|
||||
PeriodicCheckIntervalCongested time.Duration `yaml:"periodic_check_interval_congested,omitempty"`
|
||||
}
|
||||
|
||||
var (
|
||||
DefaultRemoteBWEConfig = RemoteBWEConfig{
|
||||
NackRatioAttenuator: 0.4,
|
||||
ExpectedUsageThreshold: 0.95,
|
||||
ChannelObserverProbe: defaultChannelObserverConfigProbe,
|
||||
ChannelObserverNonProbe: defaultChannelObserverConfigNonProbe,
|
||||
CongestedMinDuration: 3 * time.Second,
|
||||
PeriodicCheckInterval: 2 * time.Second,
|
||||
PeriodicCheckIntervalCongested: 200 * time.Millisecond,
|
||||
}
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type RemoteBWEParams struct {
|
||||
Config RemoteBWEConfig
|
||||
Logger logger.Logger
|
||||
}
|
||||
|
||||
type RemoteBWE struct {
|
||||
bwe.NullBWE
|
||||
|
||||
params RemoteBWEParams
|
||||
|
||||
lock sync.RWMutex
|
||||
|
||||
lastReceivedEstimate int64
|
||||
lastExpectedBandwidthUsage int64
|
||||
isInProbe bool
|
||||
committedChannelCapacity int64
|
||||
|
||||
channelObserver *channelObserver
|
||||
|
||||
congestionState bwe.CongestionState
|
||||
congestionStateSwitchedAt time.Time
|
||||
|
||||
wake chan struct{}
|
||||
stop core.Fuse
|
||||
|
||||
bweListener bwe.BWEListener
|
||||
}
|
||||
|
||||
func NewRemoteBWE(params RemoteBWEParams) *RemoteBWE {
|
||||
r := &RemoteBWE{
|
||||
params: params,
|
||||
}
|
||||
r.channelObserver = r.newChannelObserverNonProbe()
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *RemoteBWE) SetBWEListener(bweListener bwe.BWEListener) {
|
||||
r.lock.Lock()
|
||||
defer r.lock.Unlock()
|
||||
|
||||
r.bweListener = bweListener
|
||||
}
|
||||
|
||||
func (r *RemoteBWE) getBWEListener() bwe.BWEListener {
|
||||
r.lock.RLock()
|
||||
defer r.lock.RUnlock()
|
||||
|
||||
return r.bweListener
|
||||
}
|
||||
|
||||
func (r *RemoteBWE) Reset() {
|
||||
r.lock.Lock()
|
||||
defer r.lock.Unlock()
|
||||
|
||||
r.channelObserver = r.newChannelObserverNonProbe()
|
||||
}
|
||||
|
||||
func (r *RemoteBWE) Stop() {
|
||||
r.stop.Break()
|
||||
}
|
||||
|
||||
func (r *RemoteBWE) HandleREMB(
|
||||
receivedEstimate int64,
|
||||
isProbeFinalizing bool,
|
||||
expectedBandwidthUsage int64,
|
||||
sentPackets uint32,
|
||||
repeatedNacks uint32,
|
||||
) {
|
||||
r.lock.Lock()
|
||||
r.lastReceivedEstimate = receivedEstimate
|
||||
r.lastExpectedBandwidthUsage = expectedBandwidthUsage
|
||||
|
||||
if !isProbeFinalizing {
|
||||
r.channelObserver.AddEstimate(r.lastReceivedEstimate)
|
||||
r.channelObserver.AddNack(sentPackets, repeatedNacks)
|
||||
}
|
||||
|
||||
var (
|
||||
shouldNotify bool
|
||||
state bwe.CongestionState
|
||||
committedChannelCapacity int64
|
||||
)
|
||||
if !r.isInProbe {
|
||||
shouldNotify, state, committedChannelCapacity = r.congestionDetectionStateMachine()
|
||||
}
|
||||
r.lock.Unlock()
|
||||
|
||||
if shouldNotify {
|
||||
if bweListener := r.getBWEListener(); bweListener != nil {
|
||||
bweListener.OnCongestionStateChange(state, committedChannelCapacity)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RemoteBWE) congestionDetectionStateMachine() (bool, bwe.CongestionState, int64) {
|
||||
newState := r.congestionState
|
||||
update := false
|
||||
trend, reason := r.channelObserver.GetTrend()
|
||||
switch r.congestionState {
|
||||
case bwe.CongestionStateNone:
|
||||
if trend == bwe.ChannelTrendCongesting {
|
||||
if r.estimateAvailableChannelCapacity(reason) {
|
||||
newState = bwe.CongestionStateCongested
|
||||
}
|
||||
}
|
||||
|
||||
case bwe.CongestionStateCongested:
|
||||
if trend == bwe.ChannelTrendCongesting {
|
||||
if r.estimateAvailableChannelCapacity(reason) {
|
||||
// update state sa this needs to reset switch time to wait for congestion min duration again
|
||||
update = true
|
||||
}
|
||||
} else if time.Since(r.congestionStateSwitchedAt) >= r.params.Config.CongestedMinDuration {
|
||||
newState = bwe.CongestionStateNone
|
||||
}
|
||||
}
|
||||
|
||||
shouldNotify := false
|
||||
if newState != r.congestionState || update {
|
||||
r.updateCongestionState(newState, reason)
|
||||
shouldNotify = true
|
||||
}
|
||||
|
||||
return shouldNotify, r.congestionState, r.committedChannelCapacity
|
||||
}
|
||||
|
||||
func (r *RemoteBWE) estimateAvailableChannelCapacity(reason channelCongestionReason) bool {
|
||||
var estimateToCommit int64
|
||||
switch reason {
|
||||
case channelCongestionReasonLoss:
|
||||
estimateToCommit = int64(float64(r.lastExpectedBandwidthUsage) * (1.0 - r.params.Config.NackRatioAttenuator*r.channelObserver.GetNackRatio()))
|
||||
default:
|
||||
estimateToCommit = r.lastReceivedEstimate
|
||||
}
|
||||
if estimateToCommit > r.lastReceivedEstimate {
|
||||
estimateToCommit = r.lastReceivedEstimate
|
||||
}
|
||||
|
||||
commitThreshold := int64(r.params.Config.ExpectedUsageThreshold * float64(r.lastExpectedBandwidthUsage))
|
||||
|
||||
ulgr := r.params.Logger.WithUnlikelyValues(
|
||||
"reason", reason,
|
||||
"old(bps)", r.committedChannelCapacity,
|
||||
"new(bps)", estimateToCommit,
|
||||
"lastReceived(bps)", r.lastReceivedEstimate,
|
||||
"expectedUsage(bps)", r.lastExpectedBandwidthUsage,
|
||||
"commitThreshold(bps)", commitThreshold,
|
||||
"channel", r.channelObserver,
|
||||
)
|
||||
if estimateToCommit > commitThreshold {
|
||||
ulgr.Debugw("remote bwe: channel congestion detected, skipping above commit threshold channel capacity update")
|
||||
return false
|
||||
}
|
||||
|
||||
ulgr.Infow("remote bwe: channel congestion detected, applying channel capacity update")
|
||||
/* REMOTE-BWE-DATA
|
||||
r.params.Logger.Debugw(
|
||||
fmt.Sprintf("remote bwe: channel congestion detected, %s channel capacity: experimental", action),
|
||||
"nackHistory", r.channelObserver.GetNackHistory(),
|
||||
)
|
||||
*/
|
||||
|
||||
r.committedChannelCapacity = estimateToCommit
|
||||
|
||||
// reset to get new set of samples for next trend
|
||||
r.channelObserver = r.newChannelObserverNonProbe()
|
||||
return true
|
||||
}
|
||||
|
||||
func (r *RemoteBWE) updateCongestionState(state bwe.CongestionState, reason channelCongestionReason) {
|
||||
r.params.Logger.Infow(
|
||||
"remote bwe: congestion state change",
|
||||
"from", r.congestionState,
|
||||
"to", state,
|
||||
"reason", reason,
|
||||
"committedChannelCapacity", r.committedChannelCapacity,
|
||||
)
|
||||
|
||||
if state != r.congestionState {
|
||||
// notify worker for ticker interval management based on state
|
||||
select {
|
||||
case r.wake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
r.congestionState = state
|
||||
r.congestionStateSwitchedAt = mono.Now()
|
||||
}
|
||||
|
||||
func (r *RemoteBWE) newChannelObserverNonProbe() *channelObserver {
|
||||
return newChannelObserver(
|
||||
channelObserverParams{
|
||||
Name: "non-probe",
|
||||
Config: r.params.Config.ChannelObserverNonProbe,
|
||||
},
|
||||
r.params.Logger,
|
||||
)
|
||||
}
|
||||
|
||||
func (r *RemoteBWE) ProbingStart(expectedBandwidthUsage int64) {
|
||||
r.lock.Lock()
|
||||
defer r.lock.Unlock()
|
||||
|
||||
r.isInProbe = true
|
||||
r.lastExpectedBandwidthUsage = expectedBandwidthUsage
|
||||
|
||||
r.params.Logger.Debugw(
|
||||
"stream allocator: starting probe",
|
||||
"lastReceived", r.lastReceivedEstimate,
|
||||
"expectedBandwidthUsage", expectedBandwidthUsage,
|
||||
"channel", r.channelObserver,
|
||||
)
|
||||
|
||||
r.channelObserver = newChannelObserver(
|
||||
channelObserverParams{
|
||||
Name: "probe",
|
||||
Config: r.params.Config.ChannelObserverProbe,
|
||||
},
|
||||
r.params.Logger,
|
||||
)
|
||||
r.channelObserver.SeedEstimate(r.lastReceivedEstimate)
|
||||
}
|
||||
|
||||
func (r *RemoteBWE) ProbingEnd(isNotFailing bool, isGoalReached bool) {
|
||||
r.lock.Lock()
|
||||
defer r.lock.Unlock()
|
||||
|
||||
highestEstimateInProbe := r.channelObserver.GetHighestEstimate()
|
||||
|
||||
//
|
||||
// Reset estimator at the end of a probe irrespective of probe result to get fresh readings.
|
||||
// With a failed probe, the latest estimate could 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.
|
||||
//
|
||||
// BWE-TODO: clean up this comment after implementing probing in TWCC case
|
||||
// NOTE: With TWCC, it is possible to reset bandwidth estimation to clean state as
|
||||
// the send side is in full control of bandwidth estimation.
|
||||
//
|
||||
r.params.Logger.Debugw(
|
||||
"probe done",
|
||||
"isNotFailing", isNotFailing,
|
||||
"isGoalReached", isGoalReached,
|
||||
"committedEstimate", r.committedChannelCapacity,
|
||||
"highestEstimate", highestEstimateInProbe,
|
||||
"channel", r.channelObserver,
|
||||
)
|
||||
r.channelObserver = r.newChannelObserverNonProbe()
|
||||
if !isNotFailing {
|
||||
return
|
||||
}
|
||||
|
||||
if highestEstimateInProbe > r.committedChannelCapacity {
|
||||
r.committedChannelCapacity = highestEstimateInProbe
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RemoteBWE) GetProbeStatus() (bool, bwe.ChannelTrend, int64, int64) {
|
||||
r.lock.RLock()
|
||||
defer r.lock.RUnlock()
|
||||
|
||||
if !r.isInProbe {
|
||||
return false, bwe.ChannelTrendNeutral, 0, 0
|
||||
}
|
||||
|
||||
trend, _ := r.channelObserver.GetTrend()
|
||||
return r.channelObserver.HasEnoughEstimateSamples(),
|
||||
trend,
|
||||
r.channelObserver.GetLowestEstimate(),
|
||||
r.channelObserver.GetHighestEstimate()
|
||||
}
|
||||
|
||||
func (r *RemoteBWE) worker() {
|
||||
ticker := time.NewTicker(r.params.Config.PeriodicCheckInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-r.wake:
|
||||
r.lock.RLock()
|
||||
state := r.congestionState
|
||||
r.lock.RUnlock()
|
||||
if state == bwe.CongestionStateCongested {
|
||||
ticker.Reset(r.params.Config.PeriodicCheckIntervalCongested)
|
||||
} else {
|
||||
ticker.Reset(r.params.Config.PeriodicCheckInterval)
|
||||
}
|
||||
|
||||
case <-ticker.C:
|
||||
var (
|
||||
shouldNotify bool
|
||||
state bwe.CongestionState
|
||||
committedChannelCapacity int64
|
||||
)
|
||||
r.lock.Lock()
|
||||
shouldNotify, state, committedChannelCapacity = r.congestionDetectionStateMachine()
|
||||
r.lock.Unlock()
|
||||
|
||||
if shouldNotify {
|
||||
if bweListener := r.getBWEListener(); bweListener != nil {
|
||||
bweListener.OnCongestionStateChange(state, committedChannelCapacity)
|
||||
}
|
||||
}
|
||||
|
||||
case <-r.stop.Watch():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,796 @@
|
||||
// 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 sendsidebwe
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/frostbyte73/core"
|
||||
"github.com/gammazero/deque"
|
||||
"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"
|
||||
"github.com/pion/rtcp"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
// -------------------------------------------------------------------------------
|
||||
|
||||
type CongestionSignalConfig struct {
|
||||
MinNumberOfGroups int `yaml:"min_number_of_groups,omitempty"`
|
||||
MinDuration time.Duration `yaml:"min_duration,omitempty"`
|
||||
}
|
||||
|
||||
func (c CongestionSignalConfig) IsTriggered(numGroups int, duration int64) bool {
|
||||
return numGroups >= c.MinNumberOfGroups && duration >= c.MinDuration.Microseconds()
|
||||
}
|
||||
|
||||
var (
|
||||
DefaultQueuingDelayEarlyWarningCongestionSignalConfig = CongestionSignalConfig{
|
||||
MinNumberOfGroups: 1,
|
||||
MinDuration: 100 * time.Millisecond,
|
||||
}
|
||||
|
||||
DefaultLossEarlyWarningCongestionSignalConfig = CongestionSignalConfig{
|
||||
MinNumberOfGroups: 2,
|
||||
MinDuration: 200 * time.Millisecond,
|
||||
}
|
||||
|
||||
DefaultQueuingDelayCongestedCongestionSignalConfig = CongestionSignalConfig{
|
||||
MinNumberOfGroups: 3,
|
||||
MinDuration: 300 * time.Millisecond,
|
||||
}
|
||||
|
||||
DefaultLossCongestedCongestionSignalConfig = CongestionSignalConfig{
|
||||
MinNumberOfGroups: 5,
|
||||
MinDuration: 600 * time.Millisecond,
|
||||
}
|
||||
)
|
||||
|
||||
// -------------------------------------------------------------------------------
|
||||
|
||||
type qdMeasurement struct {
|
||||
earlyWarningConfig CongestionSignalConfig
|
||||
congestedConfig CongestionSignalConfig
|
||||
jqrMin int64
|
||||
dqrMax int64
|
||||
|
||||
numGroups int
|
||||
minSendTime int64
|
||||
maxSendTime int64
|
||||
isSealed bool
|
||||
}
|
||||
|
||||
func newQdMeasurement(
|
||||
earlyWarningConfig CongestionSignalConfig,
|
||||
congestedConfig CongestionSignalConfig,
|
||||
jqrMin int64,
|
||||
dqrMax int64,
|
||||
) *qdMeasurement {
|
||||
return &qdMeasurement{
|
||||
earlyWarningConfig: earlyWarningConfig,
|
||||
congestedConfig: congestedConfig,
|
||||
jqrMin: jqrMin,
|
||||
dqrMax: dqrMax,
|
||||
}
|
||||
}
|
||||
|
||||
func (q *qdMeasurement) ProcessPacketGroup(pg *packetGroup) {
|
||||
if q.isSealed {
|
||||
return
|
||||
}
|
||||
|
||||
pqd, pqdOk := pg.PropagatedQueuingDelay()
|
||||
if !pqdOk {
|
||||
return
|
||||
}
|
||||
|
||||
if pqd < q.dqrMax {
|
||||
// a DQR breaks continuity
|
||||
q.isSealed = true
|
||||
return
|
||||
}
|
||||
|
||||
if pqd > q.jqrMin {
|
||||
q.numGroups++
|
||||
minSendTime, maxSendTime := pg.SendWindow()
|
||||
if q.minSendTime == 0 || minSendTime < q.minSendTime {
|
||||
q.minSendTime = minSendTime
|
||||
}
|
||||
if maxSendTime > q.maxSendTime {
|
||||
q.maxSendTime = maxSendTime
|
||||
}
|
||||
}
|
||||
|
||||
// can seal if congested config thresholds are met as they are longer
|
||||
if q.congestedConfig.IsTriggered(q.numGroups, q.maxSendTime-q.minSendTime) {
|
||||
q.isSealed = true
|
||||
}
|
||||
}
|
||||
|
||||
func (q *qdMeasurement) IsSealed() bool {
|
||||
return q.isSealed
|
||||
}
|
||||
|
||||
func (q *qdMeasurement) IsEarlyWarningTriggered() bool {
|
||||
return q.earlyWarningConfig.IsTriggered(q.numGroups, q.maxSendTime-q.minSendTime)
|
||||
}
|
||||
|
||||
func (q *qdMeasurement) IsCongestedTriggered() bool {
|
||||
return q.congestedConfig.IsTriggered(q.numGroups, q.maxSendTime-q.minSendTime)
|
||||
}
|
||||
|
||||
func (q *qdMeasurement) MarshalLogObject(e zapcore.ObjectEncoder) error {
|
||||
if q == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
e.AddInt("numGroups", q.numGroups)
|
||||
e.AddInt64("minSendTime", q.minSendTime)
|
||||
e.AddInt64("maxSendTime", q.maxSendTime)
|
||||
e.AddDuration("duration", time.Duration((q.maxSendTime-q.minSendTime)*1000))
|
||||
e.AddBool("isSealed", q.isSealed)
|
||||
e.AddBool("isEarlyWarningTriggered", q.IsEarlyWarningTriggered())
|
||||
e.AddBool("isCongestedTriggered", q.IsCongestedTriggered())
|
||||
return nil
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------
|
||||
|
||||
type lossMeasurement struct {
|
||||
earlyWarningConfig CongestionSignalConfig
|
||||
congestedConfig CongestionSignalConfig
|
||||
congestionMinLoss float64
|
||||
|
||||
numGroups int
|
||||
ts *trafficStats
|
||||
|
||||
earlyWarningWeightedLoss float64
|
||||
congestedWeightedLoss float64
|
||||
|
||||
isSealed bool
|
||||
}
|
||||
|
||||
func newLossMeasurement(
|
||||
earlyWarningConfig CongestionSignalConfig,
|
||||
congestedConfig CongestionSignalConfig,
|
||||
weightedLossConfig WeightedLossConfig,
|
||||
congestionMinLoss float64,
|
||||
logger logger.Logger,
|
||||
) *lossMeasurement {
|
||||
return &lossMeasurement{
|
||||
earlyWarningConfig: earlyWarningConfig,
|
||||
congestedConfig: congestedConfig,
|
||||
congestionMinLoss: congestionMinLoss,
|
||||
ts: newTrafficStats(trafficStatsParams{
|
||||
Config: weightedLossConfig,
|
||||
Logger: logger,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
func (l *lossMeasurement) ProcessPacketGroup(pg *packetGroup) {
|
||||
if l.isSealed {
|
||||
return
|
||||
}
|
||||
|
||||
l.numGroups++
|
||||
l.ts.Merge(pg.Traffic())
|
||||
|
||||
duration := l.ts.Duration()
|
||||
if l.earlyWarningConfig.IsTriggered(l.numGroups, duration) {
|
||||
l.earlyWarningWeightedLoss = l.ts.WeightedLoss()
|
||||
}
|
||||
if l.congestedConfig.IsTriggered(l.numGroups, duration) {
|
||||
l.congestedWeightedLoss = l.ts.WeightedLoss()
|
||||
l.isSealed = true // can seal if congested thresholds are satisfied as those should be higher
|
||||
}
|
||||
}
|
||||
|
||||
func (l *lossMeasurement) IsSealed() bool {
|
||||
return l.isSealed
|
||||
}
|
||||
|
||||
func (l *lossMeasurement) IsEarlyWarningTriggered() bool {
|
||||
return l.earlyWarningWeightedLoss > l.congestionMinLoss
|
||||
}
|
||||
|
||||
func (l *lossMeasurement) IsCongestedTriggered() bool {
|
||||
return l.congestedWeightedLoss > l.congestionMinLoss
|
||||
}
|
||||
|
||||
func (l *lossMeasurement) MarshalLogObject(e zapcore.ObjectEncoder) error {
|
||||
if l == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
e.AddInt("numGroups", l.numGroups)
|
||||
e.AddObject("ts", l.ts)
|
||||
e.AddFloat64("earlyWarningWeightedLoss", l.earlyWarningWeightedLoss)
|
||||
e.AddFloat64("congestedWeightedLoss", l.congestedWeightedLoss)
|
||||
e.AddBool("isSealed", l.isSealed)
|
||||
e.AddBool("isEarlyWarningTriggered", l.IsEarlyWarningTriggered())
|
||||
e.AddBool("isCongestedTriggered", l.IsCongestedTriggered())
|
||||
return nil
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------
|
||||
|
||||
type CongestionDetectorConfig struct {
|
||||
PacketGroup PacketGroupConfig `yaml:"packet_group,omitempty"`
|
||||
PacketGroupMaxAge time.Duration `yaml:"packet_group_max_age,omitempty"`
|
||||
|
||||
JQRMinDelay time.Duration `yaml:"jqr_min_delay,omitempty"`
|
||||
DQRMaxDelay time.Duration `yaml:"dqr_max_delay,omitempty"`
|
||||
|
||||
WeightedLoss WeightedLossConfig `yaml:"weighted_loss,omitempty"`
|
||||
CongestionMinLoss float64 `yaml:"congestion_min_loss,omitempty"`
|
||||
|
||||
QueuingDelayEarlyWarning CongestionSignalConfig `yaml:"queuing_delay_early_warning,omitempty"`
|
||||
LossEarlyWarning CongestionSignalConfig `yaml:"loss_early_warning,omitempty"`
|
||||
EarlyWarningHangover time.Duration `yaml:"early_warning_hangover,omitempty"`
|
||||
|
||||
QueuingDelayCongested CongestionSignalConfig `yaml:"queuing_delay_congested,omitempty"`
|
||||
LossCongested CongestionSignalConfig `yaml:"loss_congested,omitempty"`
|
||||
CongestedHangover time.Duration `yaml:"congested_hangover,omitempty"`
|
||||
|
||||
RateMeasurementWindowDurationMin time.Duration `yaml:"rate_measurement_window_duration_min,omitempty"`
|
||||
RateMeasurementWindowDurationMax time.Duration `yaml:"rate_measurement_window_duration_max,omitempty"`
|
||||
|
||||
PeriodicCheckInterval time.Duration `yaml:"periodic_check_interval,omitempty"`
|
||||
PeriodicCheckIntervalCongested time.Duration `yaml:"periodic_check_interval_congested,omitempty"`
|
||||
CongestedCTRTrend ccutils.TrendDetectorConfig `yaml:"congested_ctr_trend,omitempty"`
|
||||
CongestedCTREpsilon float64 `yaml:"congested_ctr_epsilon,omitempty"`
|
||||
}
|
||||
|
||||
var (
|
||||
defaultTrendDetectorConfigCongestedCTR = ccutils.TrendDetectorConfig{
|
||||
RequiredSamples: 5,
|
||||
RequiredSamplesMin: 2,
|
||||
DownwardTrendThreshold: -0.5,
|
||||
DownwardTrendMaxWait: 5 * time.Second,
|
||||
CollapseThreshold: 500 * time.Millisecond,
|
||||
ValidityWindow: 10 * time.Second,
|
||||
}
|
||||
|
||||
DefaultCongestionDetectorConfig = CongestionDetectorConfig{
|
||||
PacketGroup: DefaultPacketGroupConfig,
|
||||
PacketGroupMaxAge: 15 * time.Second,
|
||||
JQRMinDelay: 15 * time.Millisecond,
|
||||
DQRMaxDelay: 5 * time.Millisecond,
|
||||
WeightedLoss: defaultWeightedLossConfig,
|
||||
CongestionMinLoss: 0.25,
|
||||
QueuingDelayEarlyWarning: DefaultQueuingDelayEarlyWarningCongestionSignalConfig,
|
||||
LossEarlyWarning: DefaultLossEarlyWarningCongestionSignalConfig,
|
||||
EarlyWarningHangover: 500 * time.Millisecond,
|
||||
QueuingDelayCongested: DefaultQueuingDelayCongestedCongestionSignalConfig,
|
||||
LossCongested: DefaultLossCongestedCongestionSignalConfig,
|
||||
CongestedHangover: 3 * time.Second,
|
||||
RateMeasurementWindowDurationMin: 800 * time.Millisecond,
|
||||
RateMeasurementWindowDurationMax: 2 * time.Second,
|
||||
PeriodicCheckInterval: 2 * time.Second,
|
||||
PeriodicCheckIntervalCongested: 200 * time.Millisecond,
|
||||
CongestedCTRTrend: defaultTrendDetectorConfigCongestedCTR,
|
||||
CongestedCTREpsilon: 0.05,
|
||||
}
|
||||
)
|
||||
|
||||
// -------------------------------------------------------------------------------
|
||||
|
||||
type feedbackReport struct {
|
||||
at time.Time
|
||||
report *rtcp.TransportLayerCC
|
||||
}
|
||||
|
||||
type congestionDetectorParams struct {
|
||||
Config CongestionDetectorConfig
|
||||
Logger logger.Logger
|
||||
}
|
||||
|
||||
type congestionDetector struct {
|
||||
params congestionDetectorParams
|
||||
|
||||
lock sync.RWMutex
|
||||
feedbackReports deque.Deque[feedbackReport]
|
||||
|
||||
*packetTracker
|
||||
twccFeedback *twccFeedback
|
||||
|
||||
packetGroups []*packetGroup
|
||||
|
||||
wake chan struct{}
|
||||
stop core.Fuse
|
||||
|
||||
estimatedAvailableChannelCapacity int64
|
||||
congestionState bwe.CongestionState
|
||||
congestionStateSwitchedAt time.Time
|
||||
congestedCTRTrend *ccutils.TrendDetector[float64]
|
||||
congestedTrafficStats *trafficStats
|
||||
|
||||
bweListener bwe.BWEListener
|
||||
}
|
||||
|
||||
func newCongestionDetector(params congestionDetectorParams) *congestionDetector {
|
||||
c := &congestionDetector{
|
||||
params: params,
|
||||
packetTracker: newPacketTracker(packetTrackerParams{Logger: params.Logger}),
|
||||
twccFeedback: newTWCCFeedback(twccFeedbackParams{Logger: params.Logger}),
|
||||
wake: make(chan struct{}, 1),
|
||||
estimatedAvailableChannelCapacity: 100_000_000,
|
||||
}
|
||||
|
||||
c.feedbackReports.SetMinCapacity(3)
|
||||
|
||||
go c.worker()
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *congestionDetector) Reset() {
|
||||
// SSBWE-TODO
|
||||
// 1. may be clear all packet groups?
|
||||
// 2. reset congestion state to none
|
||||
// 3. reset estimate to 100 Mbps
|
||||
// 4. reset packet_tracker?? maybe only the probe state??
|
||||
}
|
||||
|
||||
func (c *congestionDetector) Stop() {
|
||||
c.stop.Break()
|
||||
}
|
||||
|
||||
func (c *congestionDetector) SetBWEListener(bweListener bwe.BWEListener) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
c.bweListener = bweListener
|
||||
}
|
||||
|
||||
func (c *congestionDetector) getBWEListener() bwe.BWEListener {
|
||||
c.lock.RLock()
|
||||
defer c.lock.RUnlock()
|
||||
|
||||
return c.bweListener
|
||||
}
|
||||
|
||||
func (c *congestionDetector) HandleTWCCFeedback(report *rtcp.TransportLayerCC) {
|
||||
c.lock.Lock()
|
||||
c.feedbackReports.PushBack(feedbackReport{mono.Now(), report})
|
||||
c.lock.Unlock()
|
||||
|
||||
// notify worker of a new feedback
|
||||
select {
|
||||
case c.wake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func (c *congestionDetector) prunePacketGroups() {
|
||||
if len(c.packetGroups) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
threshold, ok := c.packetTracker.BaseSendTimeThreshold(c.params.Config.PacketGroupMaxAge.Microseconds())
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
for idx, pg := range c.packetGroups {
|
||||
if mst := pg.MinSendTime(); mst > threshold {
|
||||
c.packetGroups = c.packetGroups[idx:]
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *congestionDetector) isCongestionSignalTriggered() (bool, string, bool, string, int) {
|
||||
qdMeasurement := newQdMeasurement(
|
||||
c.params.Config.QueuingDelayEarlyWarning,
|
||||
c.params.Config.QueuingDelayCongested,
|
||||
c.params.Config.JQRMinDelay.Microseconds(),
|
||||
c.params.Config.DQRMaxDelay.Microseconds(),
|
||||
)
|
||||
lossMeasurement := newLossMeasurement(
|
||||
c.params.Config.LossEarlyWarning,
|
||||
c.params.Config.LossCongested,
|
||||
c.params.Config.WeightedLoss,
|
||||
c.params.Config.CongestionMinLoss,
|
||||
c.params.Logger,
|
||||
)
|
||||
|
||||
var idx int
|
||||
for idx = len(c.packetGroups) - 1; idx >= 0; idx-- {
|
||||
pg := c.packetGroups[idx]
|
||||
qdMeasurement.ProcessPacketGroup(pg)
|
||||
lossMeasurement.ProcessPacketGroup(pg)
|
||||
|
||||
// if both measurements have enough data to make a decision, stop processing groups
|
||||
if qdMeasurement.IsSealed() && lossMeasurement.IsSealed() {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
earlyWarningReason := ""
|
||||
earlyWarningTriggered := qdMeasurement.IsEarlyWarningTriggered()
|
||||
if earlyWarningTriggered {
|
||||
earlyWarningReason = "queuing-delay"
|
||||
} else {
|
||||
earlyWarningTriggered = lossMeasurement.IsEarlyWarningTriggered()
|
||||
if earlyWarningTriggered {
|
||||
earlyWarningReason = "loss"
|
||||
}
|
||||
}
|
||||
|
||||
congestedReason := ""
|
||||
congestedTriggered := qdMeasurement.IsCongestedTriggered()
|
||||
if congestedTriggered {
|
||||
congestedReason = "queuing-delay"
|
||||
} else {
|
||||
congestedTriggered = lossMeasurement.IsCongestedTriggered()
|
||||
if congestedTriggered {
|
||||
congestedReason = "loss"
|
||||
}
|
||||
}
|
||||
|
||||
return earlyWarningTriggered, earlyWarningReason, congestedTriggered, congestedReason, max(0, idx)
|
||||
}
|
||||
|
||||
func (c *congestionDetector) congestionDetectionStateMachine() {
|
||||
state := c.congestionState
|
||||
newState := c.congestionState
|
||||
reason := ""
|
||||
|
||||
earlyWarningTriggered, earlyWarningReason, congestedTriggered, congestedReason, oldestContributingGroup := c.isCongestionSignalTriggered()
|
||||
|
||||
switch state {
|
||||
case bwe.CongestionStateNone:
|
||||
if congestedTriggered {
|
||||
c.params.Logger.Warnw("invalid congested state transition", nil, "from", state, "reason", congestedReason)
|
||||
}
|
||||
if earlyWarningTriggered {
|
||||
newState = bwe.CongestionStateEarlyWarning
|
||||
reason = earlyWarningReason
|
||||
}
|
||||
|
||||
case bwe.CongestionStateEarlyWarning:
|
||||
if congestedTriggered {
|
||||
newState = bwe.CongestionStateCongested
|
||||
reason = congestedReason
|
||||
} else if !earlyWarningTriggered {
|
||||
newState = bwe.CongestionStateEarlyWarningHangover
|
||||
}
|
||||
|
||||
case bwe.CongestionStateEarlyWarningHangover:
|
||||
if congestedTriggered {
|
||||
c.params.Logger.Warnw("invalid congested state transition", nil, "from", state, "reason", congestedReason)
|
||||
}
|
||||
if earlyWarningTriggered {
|
||||
newState = bwe.CongestionStateEarlyWarning
|
||||
reason = earlyWarningReason
|
||||
} else if time.Since(c.congestionStateSwitchedAt) >= c.params.Config.EarlyWarningHangover {
|
||||
newState = bwe.CongestionStateNone
|
||||
}
|
||||
|
||||
case bwe.CongestionStateCongested:
|
||||
if !congestedTriggered {
|
||||
newState = bwe.CongestionStateCongestedHangover
|
||||
}
|
||||
|
||||
case bwe.CongestionStateCongestedHangover:
|
||||
if congestedTriggered {
|
||||
c.params.Logger.Warnw("invalid congested state transition", nil, "from", state, "reason", congestedReason)
|
||||
}
|
||||
if earlyWarningTriggered {
|
||||
newState = bwe.CongestionStateEarlyWarning
|
||||
reason = earlyWarningReason
|
||||
} else if time.Since(c.congestionStateSwitchedAt) >= c.params.Config.CongestedHangover {
|
||||
newState = bwe.CongestionStateNone
|
||||
}
|
||||
}
|
||||
|
||||
c.estimateAvailableChannelCapacity()
|
||||
|
||||
// update after running the above estimate as state change callback includes the estimated available channel capacity
|
||||
if newState != state {
|
||||
c.updateCongestionState(newState, reason, oldestContributingGroup)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *congestionDetector) resetCTRTrend() {
|
||||
c.congestedCTRTrend = ccutils.NewTrendDetector[float64](ccutils.TrendDetectorParams{
|
||||
Name: "ssbwe-ctr",
|
||||
Logger: c.params.Logger,
|
||||
Config: c.params.Config.CongestedCTRTrend,
|
||||
})
|
||||
c.congestedTrafficStats = newTrafficStats(trafficStatsParams{
|
||||
Config: c.params.Config.WeightedLoss,
|
||||
Logger: c.params.Logger,
|
||||
})
|
||||
}
|
||||
|
||||
func (c *congestionDetector) clearCTRTrend() {
|
||||
c.congestedCTRTrend = nil
|
||||
c.congestedTrafficStats = nil
|
||||
}
|
||||
|
||||
func (c *congestionDetector) updateCTRTrend(pg *packetGroup) {
|
||||
if c.congestedCTRTrend == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// progressively keep increasing the window and make measurements over longer windows,
|
||||
// if congestion is not relieving, CTR will trend down
|
||||
c.congestedTrafficStats.Merge(pg.Traffic())
|
||||
ctr := c.congestedTrafficStats.CapturedTrafficRatio()
|
||||
|
||||
// quantise CTR to filter out small changes
|
||||
c.congestedCTRTrend.AddValue(float64(int((ctr+(c.params.Config.CongestedCTREpsilon/2))/c.params.Config.CongestedCTREpsilon)) * c.params.Config.CongestedCTREpsilon)
|
||||
|
||||
if c.congestedCTRTrend.GetDirection() != ccutils.TrendDirectionDownward {
|
||||
return
|
||||
}
|
||||
|
||||
c.params.Logger.Infow("captured traffic ratio is trending downward", "channel", c.congestedCTRTrend)
|
||||
|
||||
if bweListener := c.getBWEListener(); bweListener != nil {
|
||||
bweListener.OnCongestionStateChange(c.congestionState, c.estimatedAvailableChannelCapacity)
|
||||
}
|
||||
|
||||
// reset to get new set of samples for next trend
|
||||
c.resetCTRTrend()
|
||||
}
|
||||
|
||||
func (c *congestionDetector) estimateAvailableChannelCapacity() {
|
||||
if len(c.packetGroups) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
threshold, ok := c.packetTracker.BaseSendTimeThreshold(c.params.Config.RateMeasurementWindowDurationMax.Microseconds())
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
agg := newTrafficStats(trafficStatsParams{
|
||||
Config: c.params.Config.WeightedLoss,
|
||||
Logger: c.params.Logger,
|
||||
})
|
||||
var idx int
|
||||
for idx = len(c.packetGroups) - 1; idx >= 0; idx-- {
|
||||
pg := c.packetGroups[idx]
|
||||
if mst := pg.MinSendTime(); mst != 0 && mst < threshold {
|
||||
break
|
||||
}
|
||||
|
||||
agg.Merge(pg.Traffic())
|
||||
}
|
||||
|
||||
if agg.Duration() < c.params.Config.RateMeasurementWindowDurationMin.Microseconds() {
|
||||
c.params.Logger.Infow(
|
||||
"not enough data to estimate available channel capacity",
|
||||
"duration", agg.Duration(),
|
||||
"numGroups", len(c.packetGroups),
|
||||
"oldestUsed", max(0, idx),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
c.estimatedAvailableChannelCapacity = agg.AcknowledgedBitrate()
|
||||
}
|
||||
|
||||
func (c *congestionDetector) updateCongestionState(state bwe.CongestionState, reason string, oldestContributingGroup int) {
|
||||
c.params.Logger.Infow(
|
||||
"congestion state change",
|
||||
"from", c.congestionState,
|
||||
"to", state,
|
||||
"reason", reason,
|
||||
"numPacketGroups", len(c.packetGroups),
|
||||
"numContributingGroups", len(c.packetGroups[oldestContributingGroup:]),
|
||||
"contributingGroups", logger.ObjectSlice(c.packetGroups[oldestContributingGroup:]),
|
||||
"estimatedAvailableChannelCapacity", c.estimatedAvailableChannelCapacity,
|
||||
)
|
||||
|
||||
if state != c.congestionState {
|
||||
c.congestionStateSwitchedAt = mono.Now()
|
||||
}
|
||||
|
||||
prevState := c.congestionState
|
||||
c.congestionState = state
|
||||
|
||||
if bweListener := c.getBWEListener(); bweListener != nil {
|
||||
bweListener.OnCongestionStateChange(state, c.estimatedAvailableChannelCapacity)
|
||||
}
|
||||
|
||||
// when in congested state, monitor changes in captured traffic ratio (CTR)
|
||||
// to ensure allocations are in line with latest estimates, it is possible that
|
||||
// the estimate is incorrect when congestion starts and the allocation may be
|
||||
// sub-optimal and not enough to reduce/relieve congestion, by monitoing CTR
|
||||
// on a continuous basis allocations can be adjusted in the direction of
|
||||
// reducing/relieving congestion
|
||||
if state == bwe.CongestionStateCongested && prevState != bwe.CongestionStateCongested {
|
||||
c.resetCTRTrend()
|
||||
} else if state != bwe.CongestionStateCongested {
|
||||
c.clearCTRTrend()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *congestionDetector) processFeedbackReport(fbr feedbackReport) {
|
||||
recvRefTime, isOutOfOrder := c.twccFeedback.ProcessReport(fbr.report, fbr.at)
|
||||
if isOutOfOrder {
|
||||
c.params.Logger.Infow("received out-of-order feedback report")
|
||||
}
|
||||
|
||||
if len(c.packetGroups) == 0 {
|
||||
c.packetGroups = append(
|
||||
c.packetGroups,
|
||||
newPacketGroup(
|
||||
packetGroupParams{
|
||||
Config: c.params.Config.PacketGroup,
|
||||
WeightedLoss: c.params.Config.WeightedLoss,
|
||||
Logger: c.params.Logger,
|
||||
},
|
||||
0,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
pg := c.packetGroups[len(c.packetGroups)-1]
|
||||
trackPacketGroup := func(pi *packetInfo, sendDelta, recvDelta int64, isLost bool) {
|
||||
if pi == nil {
|
||||
return
|
||||
}
|
||||
|
||||
err := pg.Add(pi, sendDelta, recvDelta, isLost)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err == errGroupFinalized {
|
||||
// previous group ended, start a new group
|
||||
c.updateCTRTrend(pg)
|
||||
|
||||
// SSBWE-REMOVE c.params.Logger.Infow("packet group done", "group", pg, "numGroups", len(c.packetGroups)) // SSBWE-REMOVE
|
||||
pqd, _ := pg.PropagatedQueuingDelay()
|
||||
pg = newPacketGroup(
|
||||
packetGroupParams{
|
||||
Config: c.params.Config.PacketGroup,
|
||||
WeightedLoss: c.params.Config.WeightedLoss,
|
||||
Logger: c.params.Logger,
|
||||
},
|
||||
pqd,
|
||||
)
|
||||
c.packetGroups = append(c.packetGroups, pg)
|
||||
|
||||
pg.Add(pi, sendDelta, recvDelta, isLost)
|
||||
return
|
||||
}
|
||||
|
||||
// try an older group
|
||||
for idx := len(c.packetGroups) - 2; idx >= 0; idx-- {
|
||||
opg := c.packetGroups[idx]
|
||||
if err := opg.Add(pi, sendDelta, recvDelta, isLost); err == nil {
|
||||
return
|
||||
} else if err == errGroupFinalized {
|
||||
c.params.Logger.Infow("unpected finalized group", "packetInfo", pi, "packetGroup", opg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 1. go through the TWCC feedback report and record recive time as reported by remote
|
||||
// 2. process acknowledged packet and group them
|
||||
//
|
||||
// losses are not recorded if a feedback report is completely lost.
|
||||
// RFC recommends treating lost reports by ignoring packets that would have been in it.
|
||||
// -----------------------------------------------------------------------------------
|
||||
// | From a congestion control perspective, lost feedback messages are |
|
||||
// | handled by ignoring packets which would have been reported as lost or |
|
||||
// | received in the lost feedback messages. This behavior is similar to |
|
||||
// | how a lost RTCP receiver report is handled. |
|
||||
// -----------------------------------------------------------------------------------
|
||||
// Reference: https://datatracker.ietf.org/doc/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#page-4
|
||||
sequenceNumber := fbr.report.BaseSequenceNumber
|
||||
endSequenceNumberExclusive := sequenceNumber + fbr.report.PacketStatusCount
|
||||
deltaIdx := 0
|
||||
for _, chunk := range fbr.report.PacketChunks {
|
||||
if sequenceNumber == endSequenceNumberExclusive {
|
||||
break
|
||||
}
|
||||
|
||||
switch chunk := chunk.(type) {
|
||||
case *rtcp.RunLengthChunk:
|
||||
for i := uint16(0); i < chunk.RunLength; i++ {
|
||||
if sequenceNumber == endSequenceNumberExclusive {
|
||||
break
|
||||
}
|
||||
|
||||
recvTime := int64(0)
|
||||
isLost := false
|
||||
if chunk.PacketStatusSymbol != rtcp.TypeTCCPacketNotReceived {
|
||||
recvRefTime += fbr.report.RecvDeltas[deltaIdx].Delta
|
||||
deltaIdx++
|
||||
|
||||
recvTime = recvRefTime
|
||||
} else {
|
||||
isLost = true
|
||||
}
|
||||
pi, sendDelta, recvDelta := c.packetTracker.RecordPacketIndicationFromRemote(sequenceNumber, recvTime)
|
||||
if pi.sendTime != 0 {
|
||||
trackPacketGroup(&pi, sendDelta, recvDelta, isLost)
|
||||
}
|
||||
sequenceNumber++
|
||||
}
|
||||
|
||||
case *rtcp.StatusVectorChunk:
|
||||
for _, symbol := range chunk.SymbolList {
|
||||
if sequenceNumber == endSequenceNumberExclusive {
|
||||
break
|
||||
}
|
||||
|
||||
recvTime := int64(0)
|
||||
isLost := false
|
||||
if symbol != rtcp.TypeTCCPacketNotReceived {
|
||||
recvRefTime += fbr.report.RecvDeltas[deltaIdx].Delta
|
||||
deltaIdx++
|
||||
|
||||
recvTime = recvRefTime
|
||||
} else {
|
||||
isLost = true
|
||||
}
|
||||
pi, sendDelta, recvDelta := c.packetTracker.RecordPacketIndicationFromRemote(sequenceNumber, recvTime)
|
||||
if pi.sendTime != 0 {
|
||||
trackPacketGroup(&pi, sendDelta, recvDelta, isLost)
|
||||
}
|
||||
sequenceNumber++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.prunePacketGroups()
|
||||
c.congestionDetectionStateMachine()
|
||||
}
|
||||
|
||||
func (c *congestionDetector) worker() {
|
||||
ticker := time.NewTicker(c.params.Config.PeriodicCheckInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-c.wake:
|
||||
for {
|
||||
c.lock.Lock()
|
||||
if c.feedbackReports.Len() == 0 {
|
||||
c.lock.Unlock()
|
||||
break
|
||||
}
|
||||
fbReport := c.feedbackReports.PopFront()
|
||||
c.lock.Unlock()
|
||||
|
||||
c.processFeedbackReport(fbReport)
|
||||
}
|
||||
|
||||
if c.congestionState == bwe.CongestionStateCongested {
|
||||
ticker.Reset(c.params.Config.PeriodicCheckIntervalCongested)
|
||||
} else {
|
||||
ticker.Reset(c.params.Config.PeriodicCheckInterval)
|
||||
}
|
||||
|
||||
case <-ticker.C:
|
||||
c.prunePacketGroups()
|
||||
c.congestionDetectionStateMachine()
|
||||
|
||||
case <-c.stop.Watch():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
// 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 sendsidebwe
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/livekit/protocol/logger"
|
||||
"github.com/livekit/protocol/utils"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
// -------------------------------------------------------------
|
||||
|
||||
var (
|
||||
errGroupFinalized = errors.New("packet group is finalized")
|
||||
errOldPacket = errors.New("packet is older than packet group start")
|
||||
)
|
||||
|
||||
// -------------------------------------------------------------
|
||||
|
||||
type PacketGroupConfig struct {
|
||||
MinPackets int `yaml:"min_packets,omitempty"`
|
||||
MaxWindowDuration time.Duration `yaml:"max_window_duration,omitempty"`
|
||||
}
|
||||
|
||||
var (
|
||||
DefaultPacketGroupConfig = PacketGroupConfig{
|
||||
MinPackets: 20,
|
||||
MaxWindowDuration: 500 * time.Millisecond,
|
||||
}
|
||||
)
|
||||
|
||||
// -------------------------------------------------------------
|
||||
|
||||
type stat struct {
|
||||
numPackets int
|
||||
numBytes int
|
||||
}
|
||||
|
||||
func (s *stat) add(size int) {
|
||||
s.numPackets++
|
||||
s.numBytes += size
|
||||
}
|
||||
|
||||
func (s *stat) remove(size int) {
|
||||
s.numPackets--
|
||||
s.numBytes -= size
|
||||
}
|
||||
|
||||
func (s *stat) getNumPackets() int {
|
||||
return s.numPackets
|
||||
}
|
||||
|
||||
func (s *stat) getNumBytes() int {
|
||||
return s.numBytes
|
||||
}
|
||||
|
||||
func (s stat) MarshalLogObject(e zapcore.ObjectEncoder) error {
|
||||
e.AddInt("numPackets", s.numPackets)
|
||||
e.AddInt("numBytes", s.numBytes)
|
||||
return nil
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
|
||||
type classStat struct {
|
||||
primary stat
|
||||
rtx stat
|
||||
}
|
||||
|
||||
func (c *classStat) add(size int, isRTX bool) {
|
||||
if isRTX {
|
||||
c.rtx.add(size)
|
||||
} else {
|
||||
c.primary.add(size)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *classStat) remove(size int, isRTX bool) {
|
||||
if isRTX {
|
||||
c.rtx.remove(size)
|
||||
} else {
|
||||
c.primary.remove(size)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *classStat) numPackets() int {
|
||||
return c.primary.getNumPackets() + c.rtx.getNumPackets()
|
||||
}
|
||||
|
||||
func (c *classStat) numBytes() int {
|
||||
return c.primary.getNumBytes() + c.rtx.getNumBytes()
|
||||
}
|
||||
|
||||
func (c classStat) MarshalLogObject(e zapcore.ObjectEncoder) error {
|
||||
e.AddObject("primary", c.primary)
|
||||
e.AddObject("rtx", c.rtx)
|
||||
return nil
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
|
||||
type packetGroupParams struct {
|
||||
Config PacketGroupConfig
|
||||
WeightedLoss WeightedLossConfig
|
||||
Logger logger.Logger
|
||||
}
|
||||
|
||||
type packetGroup struct {
|
||||
params packetGroupParams
|
||||
|
||||
minSequenceNumber uint64
|
||||
maxSequenceNumber uint64
|
||||
|
||||
minSendTime int64
|
||||
maxSendTime int64
|
||||
|
||||
minRecvTime int64 // for information only
|
||||
maxRecvTime int64 // for information only
|
||||
|
||||
acked classStat
|
||||
lost classStat
|
||||
snBitmap *utils.Bitmap[uint64]
|
||||
|
||||
aggregateSendDelta int64
|
||||
aggregateRecvDelta int64
|
||||
queuingDelay int64
|
||||
|
||||
isFinalized bool
|
||||
}
|
||||
|
||||
func newPacketGroup(params packetGroupParams, queuingDelay int64) *packetGroup {
|
||||
return &packetGroup{
|
||||
params: params,
|
||||
queuingDelay: queuingDelay,
|
||||
snBitmap: utils.NewBitmap[uint64](params.Config.MinPackets),
|
||||
}
|
||||
}
|
||||
|
||||
func (p *packetGroup) Add(pi *packetInfo, sendDelta, recvDelta int64, isLost bool) error {
|
||||
if isLost {
|
||||
return p.lostPacket(pi)
|
||||
}
|
||||
|
||||
if err := p.inGroup(pi.sequenceNumber); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if p.minSequenceNumber == 0 || pi.sequenceNumber < p.minSequenceNumber {
|
||||
p.minSequenceNumber = pi.sequenceNumber
|
||||
}
|
||||
p.maxSequenceNumber = max(p.maxSequenceNumber, pi.sequenceNumber)
|
||||
|
||||
if p.minSendTime == 0 || (pi.sendTime-sendDelta) < p.minSendTime {
|
||||
p.minSendTime = pi.sendTime - sendDelta
|
||||
}
|
||||
p.maxSendTime = max(p.maxSendTime, pi.sendTime)
|
||||
|
||||
if p.minRecvTime == 0 || (pi.recvTime-recvDelta) < p.minRecvTime {
|
||||
p.minRecvTime = pi.recvTime - recvDelta
|
||||
}
|
||||
p.maxRecvTime = max(p.maxRecvTime, pi.recvTime)
|
||||
|
||||
p.acked.add(int(pi.size), pi.isRTX)
|
||||
if p.snBitmap.IsSet(pi.sequenceNumber - p.minSequenceNumber) {
|
||||
// an earlier packet reported as lost has been received
|
||||
p.snBitmap.Clear(pi.sequenceNumber - p.minSequenceNumber)
|
||||
p.lost.remove(int(pi.size), pi.isRTX)
|
||||
}
|
||||
|
||||
// note that out-of-order deliveries will amplify the queueing delay.
|
||||
// for e.g. a, b, c getting delivered as a, c, b.
|
||||
// let us say packets are delivered with interval of `x`
|
||||
// send delta aggregate will go up by x((a, c) = 2x + (c, b) -1x)
|
||||
// recv delta aggregate will go up by 3x((a, c) = 2x + (c, b) 1x)
|
||||
p.aggregateSendDelta += sendDelta
|
||||
p.aggregateRecvDelta += recvDelta
|
||||
|
||||
if p.acked.numPackets() == p.params.Config.MinPackets || (pi.sendTime-p.minSendTime) > p.params.Config.MaxWindowDuration.Microseconds() {
|
||||
p.isFinalized = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *packetGroup) lostPacket(pi *packetInfo) error {
|
||||
if pi.recvTime != 0 {
|
||||
// previously received packet, so not lost
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := p.inGroup(pi.sequenceNumber); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if p.minSequenceNumber == 0 || pi.sequenceNumber < p.minSequenceNumber {
|
||||
p.minSequenceNumber = pi.sequenceNumber
|
||||
}
|
||||
p.maxSequenceNumber = max(p.maxSequenceNumber, pi.sequenceNumber)
|
||||
p.snBitmap.Set(pi.sequenceNumber - p.minSequenceNumber)
|
||||
|
||||
p.lost.add(int(pi.size), pi.isRTX)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *packetGroup) MinSendTime() int64 {
|
||||
return p.minSendTime
|
||||
}
|
||||
|
||||
func (p *packetGroup) SendWindow() (int64, int64) {
|
||||
return p.minSendTime, p.maxSendTime
|
||||
}
|
||||
|
||||
func (p *packetGroup) PropagatedQueuingDelay() (int64, bool) {
|
||||
if !p.isFinalized {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
if p.queuingDelay+p.aggregateRecvDelta-p.aggregateSendDelta > 0 {
|
||||
return p.queuingDelay + p.aggregateRecvDelta - p.aggregateSendDelta, true
|
||||
}
|
||||
|
||||
return max(0, p.aggregateRecvDelta-p.aggregateSendDelta), true
|
||||
}
|
||||
|
||||
func (p *packetGroup) Traffic() *trafficStats {
|
||||
return &trafficStats{
|
||||
minSendTime: p.minSendTime,
|
||||
maxSendTime: p.maxSendTime,
|
||||
sendDelta: p.aggregateSendDelta,
|
||||
recvDelta: p.aggregateRecvDelta,
|
||||
ackedPackets: p.acked.numPackets(),
|
||||
ackedBytes: p.acked.numBytes(),
|
||||
lostPackets: p.lost.numPackets(),
|
||||
}
|
||||
}
|
||||
|
||||
func (p *packetGroup) MarshalLogObject(e zapcore.ObjectEncoder) error {
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
e.AddUint64("minSequenceNumber", p.minSequenceNumber)
|
||||
e.AddUint64("maxSequenceNumber", p.maxSequenceNumber)
|
||||
e.AddObject("acked", p.acked)
|
||||
e.AddObject("lost", p.lost)
|
||||
|
||||
e.AddInt64("minRecvTime", p.minRecvTime)
|
||||
e.AddInt64("maxRecvTime", p.maxRecvTime)
|
||||
recvDuration := time.Duration((p.maxRecvTime - p.minRecvTime) * 1000)
|
||||
e.AddDuration("recvDuration", recvDuration)
|
||||
|
||||
recvBitrate := float64(0)
|
||||
if recvDuration != 0 {
|
||||
recvBitrate = float64(p.acked.numBytes()*8) / recvDuration.Seconds()
|
||||
e.AddFloat64("recvBitrate", recvBitrate)
|
||||
}
|
||||
|
||||
ts := newTrafficStats(trafficStatsParams{
|
||||
Config: p.params.WeightedLoss,
|
||||
Logger: p.params.Logger,
|
||||
})
|
||||
ts.Merge(p.Traffic())
|
||||
e.AddObject("trafficStats", ts)
|
||||
e.AddInt64("queuingDelay", p.queuingDelay)
|
||||
pqd, _ := p.PropagatedQueuingDelay()
|
||||
e.AddInt64("propagatedQueuingDelay", pqd)
|
||||
|
||||
e.AddBool("isFinalized", p.isFinalized)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *packetGroup) inGroup(sequenceNumber uint64) error {
|
||||
if p.isFinalized && sequenceNumber > p.maxSequenceNumber {
|
||||
return errGroupFinalized
|
||||
}
|
||||
|
||||
if sequenceNumber < p.minSequenceNumber {
|
||||
return errOldPacket
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// 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 sendsidebwe
|
||||
|
||||
import (
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
type packetInfo struct {
|
||||
sequenceNumber uint64
|
||||
sendTime int64
|
||||
recvTime int64
|
||||
size uint16
|
||||
isRTX bool
|
||||
// SSBWE-TODO: possibly add the following fields - pertaining to this packet,
|
||||
// idea is to be able to figure out probe start/end and check for bitrate in that window
|
||||
}
|
||||
|
||||
func (pi *packetInfo) Reset(sequenceNumber uint64) {
|
||||
pi.sequenceNumber = sequenceNumber
|
||||
pi.sendTime = 0
|
||||
pi.recvTime = 0
|
||||
pi.size = 0
|
||||
pi.isRTX = false
|
||||
}
|
||||
|
||||
func (pi *packetInfo) MarshalLogObject(e zapcore.ObjectEncoder) error {
|
||||
if pi == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
e.AddUint64("sequenceNumber", pi.sequenceNumber)
|
||||
e.AddInt64("sendTime", pi.sendTime)
|
||||
e.AddInt64("recvTime", pi.recvTime)
|
||||
e.AddUint16("size", pi.size)
|
||||
e.AddBool("isRTX", pi.isRTX)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
// 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 sendsidebwe
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/livekit/protocol/logger"
|
||||
"github.com/livekit/protocol/utils/mono"
|
||||
)
|
||||
|
||||
// -------------------------------------------------------------------------------
|
||||
|
||||
type packetTrackerParams struct {
|
||||
Logger logger.Logger
|
||||
}
|
||||
|
||||
type packetTracker struct {
|
||||
params packetTrackerParams
|
||||
|
||||
lock sync.Mutex
|
||||
|
||||
sequenceNumber uint64
|
||||
|
||||
baseSendTime int64
|
||||
packetInfos [2048]packetInfo
|
||||
|
||||
baseRecvTime int64
|
||||
piLastRecv *packetInfo
|
||||
}
|
||||
|
||||
func newPacketTracker(params packetTrackerParams) *packetTracker {
|
||||
return &packetTracker{
|
||||
params: params,
|
||||
sequenceNumber: uint64(rand.Intn(1<<14)) + uint64(1<<15), // a random number in third quartile of sequence number space
|
||||
}
|
||||
}
|
||||
|
||||
// SSBWE-TODO: this potentially needs to take isProbe as argument?
|
||||
func (p *packetTracker) RecordPacketSendAndGetSequenceNumber(at time.Time, size int, isRTX bool) uint16 {
|
||||
p.lock.Lock()
|
||||
defer p.lock.Unlock()
|
||||
|
||||
sendTime := at.UnixMicro()
|
||||
if p.baseSendTime == 0 {
|
||||
p.baseSendTime = sendTime
|
||||
}
|
||||
|
||||
pi := p.getPacketInfo(uint16(p.sequenceNumber))
|
||||
pi.sequenceNumber = p.sequenceNumber
|
||||
pi.sendTime = sendTime - p.baseSendTime
|
||||
pi.recvTime = 0
|
||||
pi.size = uint16(size)
|
||||
pi.isRTX = isRTX
|
||||
// SSBWE-REMOVE p.params.Logger.Infow("packet sent", "packetInfo", pi) // SSBWE-REMOVE
|
||||
|
||||
p.sequenceNumber++
|
||||
|
||||
// extreme case of wrap around before receiving any feedback
|
||||
if pi == p.piLastRecv {
|
||||
p.piLastRecv = nil
|
||||
}
|
||||
|
||||
return uint16(pi.sequenceNumber)
|
||||
}
|
||||
|
||||
func (p *packetTracker) BaseSendTimeThreshold(threshold int64) (int64, bool) {
|
||||
p.lock.Lock()
|
||||
defer p.lock.Unlock()
|
||||
|
||||
if p.baseSendTime == 0 {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
return mono.UnixMicro() - p.baseSendTime - threshold, true
|
||||
}
|
||||
|
||||
func (p *packetTracker) RecordPacketIndicationFromRemote(sn uint16, recvTime int64) (piRecv packetInfo, sendDelta, recvDelta int64) {
|
||||
p.lock.Lock()
|
||||
defer p.lock.Unlock()
|
||||
|
||||
pi := p.getPacketInfoExisting(sn)
|
||||
if pi == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if recvTime == 0 {
|
||||
// maybe lost OR already receied but reported lost in a later report
|
||||
piRecv = *pi
|
||||
return
|
||||
}
|
||||
|
||||
if p.baseRecvTime == 0 {
|
||||
p.baseRecvTime = recvTime
|
||||
p.piLastRecv = pi
|
||||
}
|
||||
|
||||
pi.recvTime = recvTime - p.baseRecvTime
|
||||
piRecv = *pi
|
||||
if p.piLastRecv != nil {
|
||||
sendDelta, recvDelta = pi.sendTime-p.piLastRecv.sendTime, pi.recvTime-p.piLastRecv.recvTime
|
||||
}
|
||||
p.piLastRecv = pi
|
||||
return
|
||||
}
|
||||
|
||||
func (p *packetTracker) getPacketInfo(sn uint16) *packetInfo {
|
||||
return &p.packetInfos[int(sn)%len(p.packetInfos)]
|
||||
}
|
||||
|
||||
func (p *packetTracker) getPacketInfoExisting(sn uint16) *packetInfo {
|
||||
pi := &p.packetInfos[int(sn)%len(p.packetInfos)]
|
||||
if uint16(pi.sequenceNumber) == sn {
|
||||
return pi
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// 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 sendsidebwe
|
||||
|
||||
import (
|
||||
"github.com/livekit/livekit-server/pkg/sfu/bwe"
|
||||
"github.com/livekit/protocol/logger"
|
||||
"github.com/pion/rtcp"
|
||||
)
|
||||
|
||||
//
|
||||
// Based on a simplified/modified version of JitterPath paper
|
||||
// (https://homepage.iis.sinica.edu.tw/papers/lcs/2114-F.pdf)
|
||||
//
|
||||
// TWCC feedback is uesed to calcualte delta one-way-delay.
|
||||
// It is accumulated/propagated to determine in which region
|
||||
// groups of packets are operating in.
|
||||
//
|
||||
// In simplified terms,
|
||||
// o JQR (Join Queuing Region) is when channel is congested.
|
||||
// o DQR (Disjoint Queuing Region) is when channel is not.
|
||||
//
|
||||
// Packets are grouped and thresholds applied to smooth over
|
||||
// small variations. For example, in the paper,
|
||||
// if propagated_queuing_delay + delta_one_way_delay > 0 {
|
||||
// possibly_operating_in_jqr
|
||||
// }
|
||||
// But, in this implementation it is checked at packet group level,
|
||||
// i. e. using queuing delay and aggreated delta one-way-delay of
|
||||
// the group and a minimum value threshold is applied before declaring
|
||||
// that a group is in JQR.
|
||||
//
|
||||
// There is also hysteresis to make transisitons smoother, i.e. if the
|
||||
// metric is above a certain threshold, it is JQR and it is DQR only if it
|
||||
// is below a certain value and the gap in between those two thresholds
|
||||
// are treated as interdeterminate groups.
|
||||
//
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type SendSideBWEConfig struct {
|
||||
CongestionDetector CongestionDetectorConfig `yaml:"congestion_detector,omitempty"`
|
||||
}
|
||||
|
||||
var (
|
||||
DefaultSendSideBWEConfig = SendSideBWEConfig{
|
||||
CongestionDetector: DefaultCongestionDetectorConfig,
|
||||
}
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type SendSideBWEParams struct {
|
||||
Config SendSideBWEConfig
|
||||
Logger logger.Logger
|
||||
}
|
||||
|
||||
type SendSideBWE struct {
|
||||
bwe.NullBWE
|
||||
|
||||
params SendSideBWEParams
|
||||
|
||||
*congestionDetector
|
||||
}
|
||||
|
||||
func NewSendSideBWE(params SendSideBWEParams) *SendSideBWE {
|
||||
return &SendSideBWE{
|
||||
params: params,
|
||||
congestionDetector: newCongestionDetector(congestionDetectorParams{
|
||||
Config: params.Config.CongestionDetector,
|
||||
Logger: params.Logger,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SendSideBWE) SetBWEListener(bweListener bwe.BWEListener) {
|
||||
s.congestionDetector.SetBWEListener(bweListener)
|
||||
}
|
||||
|
||||
func (s *SendSideBWE) Reset() {
|
||||
s.congestionDetector.Reset()
|
||||
}
|
||||
|
||||
func (s *SendSideBWE) Stop() {
|
||||
s.congestionDetector.Stop()
|
||||
}
|
||||
|
||||
func (s *SendSideBWE) HandleTWCCFeedback(report *rtcp.TransportLayerCC) {
|
||||
s.congestionDetector.HandleTWCCFeedback(report)
|
||||
}
|
||||
|
||||
// ------------------------------------------------
|
||||
@@ -0,0 +1,156 @@
|
||||
// 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 sendsidebwe
|
||||
|
||||
import (
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/livekit/protocol/logger"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
// -----------------------------------------------------------
|
||||
|
||||
type WeightedLossConfig struct {
|
||||
MinPacketsForLossValidity int `yaml:"min_packets_for_loss_validity,omitempty"`
|
||||
LossPenaltyFactor float64 `yaml:"loss_penalty_factor,omitempty"`
|
||||
}
|
||||
|
||||
var (
|
||||
defaultWeightedLossConfig = WeightedLossConfig{
|
||||
MinPacketsForLossValidity: 20,
|
||||
LossPenaltyFactor: 0.25,
|
||||
}
|
||||
)
|
||||
|
||||
// -----------------------------------------------------------
|
||||
|
||||
type trafficStatsParams struct {
|
||||
Config WeightedLossConfig
|
||||
Logger logger.Logger
|
||||
}
|
||||
|
||||
type trafficStats struct {
|
||||
params trafficStatsParams
|
||||
|
||||
minSendTime int64
|
||||
maxSendTime int64
|
||||
sendDelta int64
|
||||
recvDelta int64
|
||||
ackedPackets int
|
||||
ackedBytes int
|
||||
lostPackets int
|
||||
}
|
||||
|
||||
func newTrafficStats(params trafficStatsParams) *trafficStats {
|
||||
return &trafficStats{
|
||||
params: params,
|
||||
}
|
||||
}
|
||||
|
||||
func (ts *trafficStats) Merge(rhs *trafficStats) {
|
||||
if ts.minSendTime == 0 || rhs.minSendTime < ts.minSendTime {
|
||||
ts.minSendTime = rhs.minSendTime
|
||||
}
|
||||
if rhs.maxSendTime > ts.maxSendTime {
|
||||
ts.maxSendTime = rhs.maxSendTime
|
||||
}
|
||||
ts.sendDelta += rhs.sendDelta
|
||||
ts.recvDelta += rhs.recvDelta
|
||||
ts.ackedPackets += rhs.ackedPackets
|
||||
ts.ackedBytes += rhs.ackedBytes
|
||||
ts.lostPackets += rhs.lostPackets
|
||||
}
|
||||
|
||||
func (ts *trafficStats) Duration() int64 {
|
||||
return ts.maxSendTime - ts.minSendTime
|
||||
}
|
||||
|
||||
func (ts *trafficStats) AcknowledgedBitrate() int64 {
|
||||
ackedBitrate := int64(ts.ackedBytes) * 8 * 1e6 / ts.Duration()
|
||||
return int64(float64(ackedBitrate) * ts.CapturedTrafficRatio())
|
||||
}
|
||||
|
||||
func (ts *trafficStats) CapturedTrafficRatio() float64 {
|
||||
if ts.recvDelta == 0 {
|
||||
return 0.0
|
||||
}
|
||||
|
||||
// apply a penalty for lost packets,
|
||||
// tha rationale being packet dropping is a strategy to relieve congestion
|
||||
// and if they were not dropped, they would have increased queuing delay,
|
||||
// as it is not possible to know the reason for the losses,
|
||||
// apply a small penalty to receive delta aggregate to simulate those packets
|
||||
// building up queuing delay.
|
||||
return min(1.0, float64(ts.sendDelta)/float64(ts.recvDelta+ts.lossPenalty()))
|
||||
}
|
||||
|
||||
func (ts *trafficStats) WeightedLoss() float64 {
|
||||
totalPackets := float64(ts.lostPackets + ts.ackedPackets)
|
||||
if int(totalPackets) < ts.params.Config.MinPacketsForLossValidity {
|
||||
return 0.0
|
||||
}
|
||||
|
||||
lossRatio := float64(0.0)
|
||||
if totalPackets != 0 {
|
||||
lossRatio = float64(ts.lostPackets) / totalPackets
|
||||
}
|
||||
|
||||
pps := totalPackets * 1e6 / float64(ts.Duration())
|
||||
|
||||
// Log10 is used to give higher weight for the same loss ratio at higher packet rates,
|
||||
// for e.g. with a penalty factor of 0.25
|
||||
// - 10% loss at 20 pps = 0.1 * log10(20) * 0.25 = 0.032
|
||||
// - 10% loss at 100 pps = 0.1 * log10(100) * 0.25 = 0.05
|
||||
// - 10% loss at 1000 pps = 0.1 * log10(1000) * 0.25 = 0.075
|
||||
return lossRatio * math.Log10(pps)
|
||||
}
|
||||
|
||||
func (ts *trafficStats) lossPenalty() int64 {
|
||||
return int64(float64(ts.recvDelta) * ts.WeightedLoss() * ts.params.Config.LossPenaltyFactor)
|
||||
}
|
||||
|
||||
func (ts *trafficStats) MarshalLogObject(e zapcore.ObjectEncoder) error {
|
||||
if ts == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
e.AddInt64("minSendTime", ts.minSendTime)
|
||||
e.AddInt64("maxSendTime", ts.maxSendTime)
|
||||
duration := time.Duration(ts.Duration() * 1000)
|
||||
e.AddDuration("duration", duration)
|
||||
|
||||
bitrate := float64(0)
|
||||
if duration != 0 {
|
||||
bitrate = float64(ts.ackedBytes*8) / duration.Seconds()
|
||||
e.AddFloat64("bitrate", bitrate)
|
||||
}
|
||||
|
||||
e.AddInt64("sendDelta", ts.sendDelta)
|
||||
e.AddInt64("recvDelta", ts.recvDelta)
|
||||
e.AddInt64("groupDelay", ts.recvDelta-ts.sendDelta)
|
||||
|
||||
e.AddFloat64("weightedLoss", ts.WeightedLoss())
|
||||
if (ts.ackedPackets + ts.lostPackets) != 0 {
|
||||
e.AddFloat64("rawLoss", float64(ts.lostPackets)/float64(ts.ackedPackets+ts.lostPackets))
|
||||
}
|
||||
e.AddInt64("lossPenalty", ts.lossPenalty())
|
||||
|
||||
capturedTrafficRatio := ts.CapturedTrafficRatio()
|
||||
e.AddFloat64("capturedTrafficRatio", capturedTrafficRatio)
|
||||
e.AddFloat64("estimatedAvailableChannelCapacity", bitrate*capturedTrafficRatio)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// 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 sendsidebwe
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/livekit/protocol/logger"
|
||||
"github.com/pion/rtcp"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
// ------------------------------------------------------
|
||||
|
||||
const (
|
||||
cOutlierReportFactor = 3
|
||||
cEstimatedFeedbackIntervalAlpha = float64(0.9)
|
||||
|
||||
cReferenceTimeMask = (1 << 24) - 1
|
||||
cReferenceTimeResolution = 64 // 64 ms
|
||||
)
|
||||
|
||||
// ------------------------------------------------------
|
||||
|
||||
var (
|
||||
errFeedbackReportOutOfOrder = errors.New("feedback report out-of-order")
|
||||
)
|
||||
|
||||
// ------------------------------------------------------
|
||||
|
||||
type twccFeedbackParams struct {
|
||||
Logger logger.Logger
|
||||
}
|
||||
|
||||
type twccFeedback struct {
|
||||
params twccFeedbackParams
|
||||
|
||||
lastFeedbackTime time.Time
|
||||
estimatedFeedbackInterval time.Duration
|
||||
numReports int
|
||||
numReportsOutOfOrder int
|
||||
|
||||
highestFeedbackCount uint8
|
||||
|
||||
cycles int64
|
||||
highestReferenceTime uint32
|
||||
}
|
||||
|
||||
func newTWCCFeedback(params twccFeedbackParams) *twccFeedback {
|
||||
return &twccFeedback{
|
||||
params: params,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *twccFeedback) ProcessReport(report *rtcp.TransportLayerCC, at time.Time) (int64, bool) {
|
||||
// SSBWE-REMOVE t.params.Logger.Infow("TWCC feedback", "report", report.String()) // SSBWE-REMOVE
|
||||
t.numReports++
|
||||
if t.lastFeedbackTime.IsZero() {
|
||||
t.lastFeedbackTime = at
|
||||
t.highestReferenceTime = report.ReferenceTime
|
||||
t.highestFeedbackCount = report.FbPktCount
|
||||
return (t.cycles + int64(report.ReferenceTime)) * cReferenceTimeResolution * 1000, false
|
||||
}
|
||||
|
||||
isOutOfOrder := false
|
||||
if (report.FbPktCount - t.highestFeedbackCount) > (1 << 7) {
|
||||
t.numReportsOutOfOrder++
|
||||
isOutOfOrder = true
|
||||
}
|
||||
|
||||
// reference time wrap around handling
|
||||
var referenceTime int64
|
||||
if (report.ReferenceTime-t.highestReferenceTime)&cReferenceTimeMask < (1 << 23) {
|
||||
if report.ReferenceTime < t.highestReferenceTime {
|
||||
t.cycles += (1 << 24)
|
||||
}
|
||||
t.highestReferenceTime = report.ReferenceTime
|
||||
referenceTime = t.cycles + int64(report.ReferenceTime)
|
||||
} else {
|
||||
cycles := t.cycles
|
||||
if report.ReferenceTime > t.highestReferenceTime && cycles >= (1<<24) {
|
||||
cycles -= (1 << 24)
|
||||
}
|
||||
referenceTime = cycles + int64(report.ReferenceTime)
|
||||
}
|
||||
|
||||
if !isOutOfOrder {
|
||||
sinceLast := at.Sub(t.lastFeedbackTime)
|
||||
// SSBWE-REMOVE t.params.Logger.Infow("report received", "at", at, "sinceLast", sinceLast, "pktCount", report.FbPktCount) // SSBWE-REMOVE
|
||||
if t.estimatedFeedbackInterval == 0 {
|
||||
t.estimatedFeedbackInterval = sinceLast
|
||||
} else {
|
||||
// filter out outliers from estimate
|
||||
if sinceLast > t.estimatedFeedbackInterval/cOutlierReportFactor && sinceLast < cOutlierReportFactor*t.estimatedFeedbackInterval {
|
||||
// smoothed version of inter feedback interval
|
||||
t.estimatedFeedbackInterval = time.Duration(cEstimatedFeedbackIntervalAlpha*float64(t.estimatedFeedbackInterval) + (1.0-cEstimatedFeedbackIntervalAlpha)*float64(sinceLast))
|
||||
}
|
||||
}
|
||||
t.lastFeedbackTime = at
|
||||
t.highestFeedbackCount = report.FbPktCount
|
||||
}
|
||||
|
||||
return referenceTime * cReferenceTimeResolution * 1000, isOutOfOrder
|
||||
}
|
||||
|
||||
func (t *twccFeedback) MarshalLogObject(e zapcore.ObjectEncoder) error {
|
||||
if t == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
e.AddTime("lastFeedbackTime", t.lastFeedbackTime)
|
||||
e.AddDuration("estimatedFeedbackInterval", t.estimatedFeedbackInterval)
|
||||
e.AddInt("numReports", t.numReports)
|
||||
e.AddInt("numReportsOutOfOrder", t.numReportsOutOfOrder)
|
||||
e.AddInt64("cycles", t.cycles/(1<<24))
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user