StreamAllocator (congestion controller) refactor (#3180)

* refactor WIP

* WIP

* compiling

* runlock

* fixes

* fmt

* stringer and unlikely logger

* clean up
This commit is contained in:
Raja Subramanian
2024-11-16 03:06:37 +05:30
committed by GitHub
parent eceada8b31
commit 6509cdb5ea
21 changed files with 832 additions and 514 deletions
@@ -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
}
}
}
+296
View File
@@ -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
}
+50
View File
@@ -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
}
+132
View File
@@ -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
}
+104
View File
@@ -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)
}
// ------------------------------------------------
+156
View File
@@ -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
}
+130
View File
@@ -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
}