A simple configuration for congestion control. (#305)

This commit is contained in:
Raja Subramanian
2021-12-31 00:26:29 +05:30
committed by GitHub
parent 107e7bbb39
commit 98586c2490
8 changed files with 254 additions and 108 deletions
+11
View File
@@ -65,6 +65,8 @@ type RTCConfig struct {
// Which side runs bandwidth estimation // Which side runs bandwidth estimation
UseSendSideBWE bool `yaml:"send_side_bandwidth_estimation"` UseSendSideBWE bool `yaml:"send_side_bandwidth_estimation"`
CongestionControl CongestionControlConfig `yaml:"congestion_control"`
} }
type PLIThrottleConfig struct { type PLIThrottleConfig struct {
@@ -73,6 +75,11 @@ type PLIThrottleConfig struct {
HighQuality time.Duration `yaml:"high_quality"` HighQuality time.Duration `yaml:"high_quality"`
} }
type CongestionControlConfig struct {
Enabled bool `yaml:"enabled"`
AllowPause bool `yaml:"allow_pause"`
}
type AudioConfig struct { type AudioConfig struct {
// minimum level to be considered active, 0-127, where 0 is loudest // minimum level to be considered active, 0-127, where 0 is loudest
ActiveLevel uint8 `yaml:"active_level"` ActiveLevel uint8 `yaml:"active_level"`
@@ -158,6 +165,10 @@ func NewConfig(confString string, c *cli.Context) (*Config, error) {
MidQuality: time.Second, MidQuality: time.Second,
HighQuality: time.Second, HighQuality: time.Second,
}, },
CongestionControl: CongestionControlConfig{
Enabled: true,
AllowPause: true,
},
}, },
Audio: AudioConfig{ Audio: AudioConfig{
ActiveLevel: 30, // -30dBov = 0.03 ActiveLevel: 30, // -30dBov = 0.03
+30 -27
View File
@@ -36,19 +36,20 @@ const (
) )
type ParticipantParams struct { type ParticipantParams struct {
Identity livekit.ParticipantIdentity Identity livekit.ParticipantIdentity
Name livekit.ParticipantName Name livekit.ParticipantName
SID livekit.ParticipantID SID livekit.ParticipantID
Config *WebRTCConfig Config *WebRTCConfig
Sink routing.MessageSink Sink routing.MessageSink
AudioConfig config.AudioConfig AudioConfig config.AudioConfig
ProtocolVersion types.ProtocolVersion ProtocolVersion types.ProtocolVersion
Telemetry telemetry.TelemetryService Telemetry telemetry.TelemetryService
ThrottleConfig config.PLIThrottleConfig ThrottleConfig config.PLIThrottleConfig
EnabledCodecs []*livekit.Codec CongestionControlConfig config.CongestionControlConfig
Hidden bool EnabledCodecs []*livekit.Codec
Recorder bool Hidden bool
Logger logger.Logger Recorder bool
Logger logger.Logger
} }
type ParticipantImpl struct { type ParticipantImpl struct {
@@ -114,25 +115,27 @@ func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) {
return nil, err return nil, err
} }
p.publisher, err = NewPCTransport(TransportParams{ p.publisher, err = NewPCTransport(TransportParams{
ParticipantID: p.params.SID, ParticipantID: p.params.SID,
ParticipantIdentity: p.params.Identity, ParticipantIdentity: p.params.Identity,
Target: livekit.SignalTarget_PUBLISHER, Target: livekit.SignalTarget_PUBLISHER,
Config: params.Config, Config: params.Config,
Telemetry: p.params.Telemetry, CongestionControlConfig: params.CongestionControlConfig,
EnabledCodecs: p.params.EnabledCodecs, Telemetry: p.params.Telemetry,
Logger: params.Logger, EnabledCodecs: p.params.EnabledCodecs,
Logger: params.Logger,
}) })
if err != nil { if err != nil {
return nil, err return nil, err
} }
p.subscriber, err = NewPCTransport(TransportParams{ p.subscriber, err = NewPCTransport(TransportParams{
ParticipantID: p.params.SID, ParticipantID: p.params.SID,
ParticipantIdentity: p.params.Identity, ParticipantIdentity: p.params.Identity,
Target: livekit.SignalTarget_SUBSCRIBER, Target: livekit.SignalTarget_SUBSCRIBER,
Config: params.Config, Config: params.Config,
Telemetry: p.params.Telemetry, CongestionControlConfig: params.CongestionControlConfig,
EnabledCodecs: p.params.EnabledCodecs, Telemetry: p.params.Telemetry,
Logger: params.Logger, EnabledCodecs: p.params.EnabledCodecs,
Logger: params.Logger,
}) })
if err != nil { if err != nil {
return nil, err return nil, err
+14 -10
View File
@@ -11,6 +11,7 @@ import (
"github.com/pion/sdp/v3" "github.com/pion/sdp/v3"
"github.com/pion/webrtc/v3" "github.com/pion/webrtc/v3"
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/rtc/types" "github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/sfu" "github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/livekit-server/pkg/telemetry" "github.com/livekit/livekit-server/pkg/telemetry"
@@ -48,13 +49,14 @@ type PCTransport struct {
} }
type TransportParams struct { type TransportParams struct {
ParticipantID livekit.ParticipantID ParticipantID livekit.ParticipantID
ParticipantIdentity livekit.ParticipantIdentity ParticipantIdentity livekit.ParticipantIdentity
Target livekit.SignalTarget Target livekit.SignalTarget
Config *WebRTCConfig Config *WebRTCConfig
Telemetry telemetry.TelemetryService CongestionControlConfig config.CongestionControlConfig
EnabledCodecs []*livekit.Codec Telemetry telemetry.TelemetryService
Logger logger.Logger EnabledCodecs []*livekit.Codec
Logger logger.Logger
} }
// LK-TODO-SSBWE func newPeerConnection(params TransportParams, onBandwidthEstimator func(estimator cc.BandwidthEstimator)) (*webrtc.PeerConnection, *webrtc.MediaEngine, error) { // LK-TODO-SSBWE func newPeerConnection(params TransportParams, onBandwidthEstimator func(estimator cc.BandwidthEstimator)) (*webrtc.PeerConnection, *webrtc.MediaEngine, error) {
@@ -143,6 +145,7 @@ func NewPCTransport(params TransportParams) (*PCTransport, error) {
} }
if params.Target == livekit.SignalTarget_SUBSCRIBER { if params.Target == livekit.SignalTarget_SUBSCRIBER {
t.streamAllocator = sfu.NewStreamAllocator(sfu.StreamAllocatorParams{ t.streamAllocator = sfu.NewStreamAllocator(sfu.StreamAllocatorParams{
Config: params.CongestionControlConfig,
Logger: params.Logger, Logger: params.Logger,
}) })
t.streamAllocator.Start() t.streamAllocator.Start()
@@ -316,9 +319,10 @@ func (t *PCTransport) AddTrack(subTrack types.SubscribedTrack) {
return return
} }
source := subTrack.MediaTrack().Source() t.streamAllocator.AddTrack(subTrack.DownTrack(), sfu.AddTrackParams{
isManaged := (source != livekit.TrackSource_SCREEN_SHARE && source != livekit.TrackSource_SCREEN_SHARE_AUDIO) || subTrack.MediaTrack().IsSimulcast() Source: subTrack.MediaTrack().Source(),
t.streamAllocator.AddTrack(subTrack.DownTrack(), isManaged) IsSimulcast: subTrack.MediaTrack().IsSimulcast(),
})
} }
func (t *PCTransport) RemoveTrack(subTrack types.SubscribedTrack) { func (t *PCTransport) RemoveTrack(subTrack types.SubscribedTrack) {
+13 -12
View File
@@ -229,18 +229,19 @@ func (r *RoomManager) StartSession(ctx context.Context, roomName livekit.RoomNam
sid := utils.NewGuid(utils.ParticipantPrefix) sid := utils.NewGuid(utils.ParticipantPrefix)
pLogger := rtc.LoggerWithParticipant(room.Logger, pi.Identity, sid) pLogger := rtc.LoggerWithParticipant(room.Logger, pi.Identity, sid)
participant, err = rtc.NewParticipant(rtc.ParticipantParams{ participant, err = rtc.NewParticipant(rtc.ParticipantParams{
Identity: pi.Identity, Identity: pi.Identity,
Name: pi.Name, Name: pi.Name,
SID: sid, SID: sid,
Config: &rtcConf, Config: &rtcConf,
Sink: responseSink, Sink: responseSink,
AudioConfig: r.config.Audio, AudioConfig: r.config.Audio,
ProtocolVersion: pv, ProtocolVersion: pv,
Telemetry: r.telemetry, Telemetry: r.telemetry,
ThrottleConfig: r.config.RTC.PLIThrottle, ThrottleConfig: r.config.RTC.PLIThrottle,
EnabledCodecs: room.Room.EnabledCodecs, CongestionControlConfig: r.config.RTC.CongestionControl,
Hidden: pi.Hidden, EnabledCodecs: room.Room.EnabledCodecs,
Logger: pLogger, Hidden: pi.Hidden,
Logger: pLogger,
}) })
if err != nil { if err != nil {
+6 -5
View File
@@ -4,13 +4,14 @@ import (
"encoding/binary" "encoding/binary"
"errors" "errors"
"fmt" "fmt"
"github.com/livekit/livekit-server/pkg/sfu/connectionquality"
"io" "io"
"strings" "strings"
"sync" "sync"
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/livekit/livekit-server/pkg/sfu/connectionquality"
"github.com/pion/rtcp" "github.com/pion/rtcp"
"github.com/pion/rtp" "github.com/pion/rtp"
"github.com/pion/sdp/v3" "github.com/pion/sdp/v3"
@@ -544,16 +545,16 @@ func (d *DownTrack) DistanceToDesired() int32 {
return d.forwarder.DistanceToDesired() return d.forwarder.DistanceToDesired()
} }
func (d *DownTrack) Allocate(availableChannelCapacity int64) VideoAllocation { func (d *DownTrack) Allocate(availableChannelCapacity int64, allowPause bool) VideoAllocation {
return d.forwarder.Allocate(availableChannelCapacity, d.receiver.GetBitrateTemporalCumulative()) return d.forwarder.Allocate(availableChannelCapacity, allowPause, d.receiver.GetBitrateTemporalCumulative())
} }
func (d *DownTrack) ProvisionalAllocatePrepare() { func (d *DownTrack) ProvisionalAllocatePrepare() {
d.forwarder.ProvisionalAllocatePrepare(d.receiver.GetBitrateTemporalCumulative()) d.forwarder.ProvisionalAllocatePrepare(d.receiver.GetBitrateTemporalCumulative())
} }
func (d *DownTrack) ProvisionalAllocate(availableChannelCapacity int64, layers VideoLayers) int64 { func (d *DownTrack) ProvisionalAllocate(availableChannelCapacity int64, layers VideoLayers, allowPause bool) int64 {
return d.forwarder.ProvisionalAllocate(availableChannelCapacity, layers) return d.forwarder.ProvisionalAllocate(availableChannelCapacity, layers, allowPause)
} }
func (d *DownTrack) ProvisionalAllocateGetCooperativeTransition() VideoTransition { func (d *DownTrack) ProvisionalAllocateGetCooperativeTransition() VideoTransition {
+48 -11
View File
@@ -360,7 +360,7 @@ func (f *Forwarder) DistanceToDesired() int32 {
return f.lastAllocation.distanceToDesired return f.lastAllocation.distanceToDesired
} }
func (f *Forwarder) Allocate(availableChannelCapacity int64, brs Bitrates) VideoAllocation { func (f *Forwarder) Allocate(availableChannelCapacity int64, allowPause bool, brs Bitrates) VideoAllocation {
f.lock.Lock() f.lock.Lock()
defer f.lock.Unlock() defer f.lock.Unlock()
@@ -399,14 +399,18 @@ func (f *Forwarder) Allocate(availableChannelCapacity int64, brs Bitrates) Video
change = VideoStreamingChangeResuming change = VideoStreamingChangeResuming
} }
} else { } else {
// disable forwarding as it is not known how big this stream is if !allowPause {
// and if it will fit in the available channel capacity // when pause is disallowed, pick the lowest available
f.currentLayers = InvalidLayers targetLayers.spatial = int32(math.Min(float64(f.maxLayers.spatial), float64(f.availableLayers[0])))
targetLayers.temporal = int32(math.Min(0, float64(f.maxLayers.temporal)))
} else {
// disable forwarding as it is not known how big this stream is
// and if it will fit in the available channel capacity
state = VideoAllocationStateDeficient
state = VideoAllocationStateDeficient if f.targetLayers != InvalidLayers {
change = VideoStreamingChangePausing
if f.targetLayers != InvalidLayers { }
change = VideoStreamingChangePausing
} }
} }
} }
@@ -445,8 +449,35 @@ func (f *Forwarder) Allocate(availableChannelCapacity int64, brs Bitrates) Video
if bandwidthRequested == 0 { if bandwidthRequested == 0 {
state = VideoAllocationStateDeficient state = VideoAllocationStateDeficient
if f.targetLayers != InvalidLayers { if !allowPause {
change = VideoStreamingChangePausing // find the lowest layer to prevent pausing
for s := int32(0); s <= f.maxLayers.spatial; s++ {
for t := int32(0); t <= f.maxLayers.temporal; t++ {
if brs[s][t] == 0 {
continue
}
targetLayers = VideoLayers{
spatial: s,
temporal: t,
}
bandwidthRequested = brs[s][t]
if f.targetLayers == InvalidLayers {
change = VideoStreamingChangeResuming
}
break
}
if bandwidthRequested != 0 {
break
}
}
} else {
if f.targetLayers != InvalidLayers {
change = VideoStreamingChangePausing
}
} }
} }
} }
@@ -480,7 +511,7 @@ func (f *Forwarder) ProvisionalAllocatePrepare(bitrates Bitrates) {
} }
} }
func (f *Forwarder) ProvisionalAllocate(availableChannelCapacity int64, layers VideoLayers) int64 { func (f *Forwarder) ProvisionalAllocate(availableChannelCapacity int64, layers VideoLayers, allowPause bool) int64 {
f.lock.Lock() f.lock.Lock()
defer f.lock.Unlock() defer f.lock.Unlock()
@@ -507,6 +538,12 @@ func (f *Forwarder) ProvisionalAllocate(availableChannelCapacity int64, layers V
return requiredBitrate return requiredBitrate
} }
// when pause is disallowed, pick the layer if none allocated already or something lower is available
if !allowPause && (f.provisional.layers == InvalidLayers || !layers.GreaterThan(f.provisional.layers)) {
f.provisional.layers = layers
return requiredBitrate
}
return 0 return 0
} }
+84 -16
View File
@@ -157,7 +157,7 @@ func TestForwarderAllocate(t *testing.T) {
targetLayers: InvalidLayers, targetLayers: InvalidLayers,
distanceToDesired: 0, distanceToDesired: 0,
} }
result := f.Allocate(ChannelCapacityInfinity, bitrates) result := f.Allocate(ChannelCapacityInfinity, true, bitrates)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedResult, f.lastAllocation)
@@ -175,7 +175,7 @@ func TestForwarderAllocate(t *testing.T) {
targetLayers: InvalidLayers, targetLayers: InvalidLayers,
distanceToDesired: 0, distanceToDesired: 0,
} }
result = f.Allocate(ChannelCapacityInfinity, emptyBitrates) result = f.Allocate(ChannelCapacityInfinity, true, emptyBitrates)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedResult, f.lastAllocation)
@@ -197,13 +197,13 @@ func TestForwarderAllocate(t *testing.T) {
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
distanceToDesired: 0, distanceToDesired: 0,
} }
result = f.Allocate(ChannelCapacityInfinity, emptyBitrates) result = f.Allocate(ChannelCapacityInfinity, true, emptyBitrates)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedResult, f.lastAllocation)
require.Equal(t, expectedTargetLayers, f.TargetLayers()) require.Equal(t, expectedTargetLayers, f.TargetLayers())
require.Equal(t, InvalidLayers, f.CurrentLayers()) require.Equal(t, InvalidLayers, f.CurrentLayers())
// while awaiting measurement, less than infinite channel capacity should pause the stream // while awaiting measurement, less than infinite channel capacity should pause the stream when pause is allowed
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
state: VideoAllocationStateDeficient, state: VideoAllocationStateDeficient,
change: VideoStreamingChangePausing, change: VideoStreamingChangePausing,
@@ -214,12 +214,33 @@ func TestForwarderAllocate(t *testing.T) {
targetLayers: InvalidLayers, targetLayers: InvalidLayers,
distanceToDesired: 0, distanceToDesired: 0,
} }
result = f.Allocate(ChannelCapacityInfinity-1, emptyBitrates) result = f.Allocate(ChannelCapacityInfinity-1, true, emptyBitrates)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedResult, f.lastAllocation)
require.Equal(t, InvalidLayers, f.CurrentLayers()) require.Equal(t, InvalidLayers, f.CurrentLayers())
require.Equal(t, InvalidLayers, f.TargetLayers()) require.Equal(t, InvalidLayers, f.TargetLayers())
// while awaiting measurement, less than infinite channel capacity should not pause the stream when pause is not allowed
expectedTargetLayers = VideoLayers{
spatial: 0,
temporal: 0,
}
expectedResult = VideoAllocation{
state: VideoAllocationStateAwaitingMeasurement,
change: VideoStreamingChangeNone,
bandwidthRequested: 0,
bandwidthDelta: 0,
availableLayers: []uint16{0},
bitrates: emptyBitrates,
targetLayers: expectedTargetLayers,
distanceToDesired: 0,
}
result = f.Allocate(ChannelCapacityInfinity-1, false, emptyBitrates)
require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation)
require.Equal(t, InvalidLayers, f.CurrentLayers())
require.Equal(t, expectedTargetLayers, f.TargetLayers())
// allocate using bitrates and less than infinite channel capacity, but enough for optimal // allocate using bitrates and less than infinite channel capacity, but enough for optimal
expectedTargetLayers = VideoLayers{ expectedTargetLayers = VideoLayers{
spatial: 2, spatial: 2,
@@ -227,7 +248,7 @@ func TestForwarderAllocate(t *testing.T) {
} }
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
state: VideoAllocationStateOptimal, state: VideoAllocationStateOptimal,
change: VideoStreamingChangeResuming, change: VideoStreamingChangeNone,
bandwidthRequested: bitrates[2][1], bandwidthRequested: bitrates[2][1],
bandwidthDelta: bitrates[2][1], bandwidthDelta: bitrates[2][1],
availableLayers: []uint16{0}, availableLayers: []uint16{0},
@@ -235,7 +256,7 @@ func TestForwarderAllocate(t *testing.T) {
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
distanceToDesired: 0, distanceToDesired: 0,
} }
result = f.Allocate(ChannelCapacityInfinity-1, bitrates) result = f.Allocate(ChannelCapacityInfinity-1, true, bitrates)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedResult, f.lastAllocation)
require.Equal(t, InvalidLayers, f.CurrentLayers()) require.Equal(t, InvalidLayers, f.CurrentLayers())
@@ -256,7 +277,7 @@ func TestForwarderAllocate(t *testing.T) {
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
distanceToDesired: 1, distanceToDesired: 1,
} }
result = f.Allocate(bitrates[2][1]-1, bitrates) result = f.Allocate(bitrates[2][1]-1, true, bitrates)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedResult, f.lastAllocation)
require.Equal(t, InvalidLayers, f.CurrentLayers()) require.Equal(t, InvalidLayers, f.CurrentLayers())
@@ -273,11 +294,32 @@ func TestForwarderAllocate(t *testing.T) {
targetLayers: InvalidLayers, targetLayers: InvalidLayers,
distanceToDesired: 5, distanceToDesired: 5,
} }
result = f.Allocate(bitrates[0][0]-1, bitrates) result = f.Allocate(bitrates[0][0]-1, true, bitrates)
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedResult, f.lastAllocation)
require.Equal(t, InvalidLayers, f.CurrentLayers()) require.Equal(t, InvalidLayers, f.CurrentLayers())
require.Equal(t, InvalidLayers, f.TargetLayers()) require.Equal(t, InvalidLayers, f.TargetLayers())
// give it a bitrate that cannot fit any layer, but disallow pause, should allocate the lowest available layer
expectedTargetLayers = VideoLayers{
spatial: 0,
temporal: 0,
}
expectedResult = VideoAllocation{
state: VideoAllocationStateDeficient,
change: VideoStreamingChangeResuming,
bandwidthRequested: bitrates[0][0],
bandwidthDelta: bitrates[0][0],
availableLayers: []uint16{0},
bitrates: bitrates,
targetLayers: expectedTargetLayers,
distanceToDesired: 4,
}
result = f.Allocate(bitrates[0][0]-1, false, bitrates)
require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation)
require.Equal(t, InvalidLayers, f.CurrentLayers())
require.Equal(t, expectedTargetLayers, f.TargetLayers())
} }
func TestForwarderProvisionalAllocate(t *testing.T) { func TestForwarderProvisionalAllocate(t *testing.T) {
@@ -291,14 +333,14 @@ func TestForwarderProvisionalAllocate(t *testing.T) {
f.ProvisionalAllocatePrepare(bitrates) f.ProvisionalAllocatePrepare(bitrates)
usedBitrate := f.ProvisionalAllocate(bitrates[2][3], VideoLayers{spatial: 0, temporal: 0}) usedBitrate := f.ProvisionalAllocate(bitrates[2][3], VideoLayers{spatial: 0, temporal: 0}, true)
require.Equal(t, bitrates[0][0], usedBitrate) require.Equal(t, bitrates[0][0], usedBitrate)
usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{spatial: 1, temporal: 2}) usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{spatial: 1, temporal: 2}, true)
require.Equal(t, bitrates[1][2], usedBitrate) require.Equal(t, bitrates[1][2], usedBitrate)
// available not enough to reach (2, 2), allocating at (2, 2) should not succeed // available not enough to reach (2, 2), allocating at (2, 2) should not succeed
usedBitrate = f.ProvisionalAllocate(bitrates[2][2]-bitrates[1][2]-1, VideoLayers{spatial: 2, temporal: 2}) usedBitrate = f.ProvisionalAllocate(bitrates[2][2]-bitrates[1][2]-1, VideoLayers{spatial: 2, temporal: 2}, true)
require.Equal(t, int64(0), usedBitrate) require.Equal(t, int64(0), usedBitrate)
// committing should set target to (1, 2) // committing should set target to (1, 2)
@@ -320,6 +362,32 @@ func TestForwarderProvisionalAllocate(t *testing.T) {
require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedResult, f.lastAllocation)
require.Equal(t, expectedTargetLayers, f.TargetLayers()) require.Equal(t, expectedTargetLayers, f.TargetLayers())
// when nothing fits and pausing disallowed, should allocate (0, 0)
f.targetLayers = InvalidLayers
f.ProvisionalAllocatePrepare(bitrates)
usedBitrate = f.ProvisionalAllocate(0, VideoLayers{spatial: 0, temporal: 0}, false)
require.Equal(t, int64(1), usedBitrate)
// committing should set target to (0, 0)
expectedTargetLayers = VideoLayers{
spatial: 0,
temporal: 0,
}
expectedResult = VideoAllocation{
state: VideoAllocationStateDeficient,
change: VideoStreamingChangeResuming,
bandwidthRequested: bitrates[0][0],
bandwidthDelta: bitrates[0][0] - bitrates[1][2],
availableLayers: nil,
bitrates: bitrates,
targetLayers: expectedTargetLayers,
distanceToDesired: 11,
}
result = f.ProvisionalAllocateCommit()
require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation)
require.Equal(t, expectedTargetLayers, f.TargetLayers())
} }
func TestForwarderProvisionalAllocateMute(t *testing.T) { func TestForwarderProvisionalAllocateMute(t *testing.T) {
@@ -334,10 +402,10 @@ func TestForwarderProvisionalAllocateMute(t *testing.T) {
f.Mute(true) f.Mute(true)
f.ProvisionalAllocatePrepare(bitrates) f.ProvisionalAllocatePrepare(bitrates)
usedBitrate := f.ProvisionalAllocate(bitrates[2][3], VideoLayers{spatial: 0, temporal: 0}) usedBitrate := f.ProvisionalAllocate(bitrates[2][3], VideoLayers{spatial: 0, temporal: 0}, true)
require.Equal(t, int64(0), usedBitrate) require.Equal(t, int64(0), usedBitrate)
usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{spatial: 1, temporal: 2}) usedBitrate = f.ProvisionalAllocate(bitrates[2][3], VideoLayers{spatial: 1, temporal: 2}, true)
require.Equal(t, int64(0), usedBitrate) require.Equal(t, int64(0), usedBitrate)
// committing should set target to InvalidLayers as track is muted // committing should set target to InvalidLayers as track is muted
@@ -785,7 +853,7 @@ func TestForwarderPause(t *testing.T) {
} }
f.ProvisionalAllocatePrepare(bitrates) f.ProvisionalAllocatePrepare(bitrates)
f.ProvisionalAllocate(bitrates[2][3], VideoLayers{spatial: 0, temporal: 0}) f.ProvisionalAllocate(bitrates[2][3], VideoLayers{spatial: 0, temporal: 0}, true)
// should have set target at (0, 0) // should have set target at (0, 0)
f.ProvisionalAllocateCommit() f.ProvisionalAllocateCommit()
@@ -815,7 +883,7 @@ func TestForwarderPauseMute(t *testing.T) {
} }
f.ProvisionalAllocatePrepare(bitrates) f.ProvisionalAllocatePrepare(bitrates)
f.ProvisionalAllocate(bitrates[2][3], VideoLayers{spatial: 0, temporal: 0}) f.ProvisionalAllocate(bitrates[2][3], VideoLayers{spatial: 0, temporal: 0}, true)
// should have set target at (0, 0) // should have set target at (0, 0)
f.ProvisionalAllocateCommit() f.ProvisionalAllocateCommit()
+48 -27
View File
@@ -7,6 +7,8 @@ import (
"sync" "sync"
"time" "time"
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger" "github.com/livekit/protocol/logger"
"github.com/pion/rtcp" "github.com/pion/rtcp"
"github.com/pion/webrtc/v3" "github.com/pion/webrtc/v3"
@@ -107,11 +109,12 @@ func (e Event) String() string {
} }
type StreamAllocatorParams struct { type StreamAllocatorParams struct {
Config config.CongestionControlConfig
Logger logger.Logger Logger logger.Logger
} }
type StreamAllocator struct { type StreamAllocator struct {
logger logger.Logger params StreamAllocatorParams
onStreamStateChange func(update *StreamStateUpdate) error onStreamStateChange func(update *StreamStateUpdate) error
@@ -145,7 +148,7 @@ type StreamAllocator struct {
func NewStreamAllocator(params StreamAllocatorParams) *StreamAllocator { func NewStreamAllocator(params StreamAllocatorParams) *StreamAllocator {
s := &StreamAllocator{ s := &StreamAllocator{
logger: params.Logger, params: params,
audioTracks: make(map[string]*Track), audioTracks: make(map[string]*Track),
videoTracks: make(map[string]*Track), videoTracks: make(map[string]*Track),
prober: NewProber(ProberParams{ prober: NewProber(ProberParams{
@@ -188,11 +191,16 @@ func (s *StreamAllocator) SetBandwidthEstimator(bwe cc.BandwidthEstimator) {
} }
*/ */
func (s *StreamAllocator) AddTrack(downTrack *DownTrack, isManaged bool) { type AddTrackParams struct {
Source livekit.TrackSource
IsSimulcast bool
}
func (s *StreamAllocator) AddTrack(downTrack *DownTrack, params AddTrackParams) {
s.postEvent(Event{ s.postEvent(Event{
Signal: SignalAddTrack, Signal: SignalAddTrack,
DownTrack: downTrack, DownTrack: downTrack,
Data: isManaged, Data: params,
}) })
if downTrack.Kind() == webrtc.RTPCodecTypeVideo { if downTrack.Kind() == webrtc.RTPCodecTypeVideo {
@@ -362,7 +370,8 @@ func (s *StreamAllocator) handleEvent(event *Event) {
} }
func (s *StreamAllocator) handleSignalAddTrack(event *Event) { func (s *StreamAllocator) handleSignalAddTrack(event *Event) {
isManaged, _ := event.Data.(bool) params, _ := event.Data.(AddTrackParams)
isManaged := (params.Source != livekit.TrackSource_SCREEN_SHARE && params.Source != livekit.TrackSource_SCREEN_SHARE_AUDIO) || params.IsSimulcast
track := newTrack(event.DownTrack, isManaged) track := newTrack(event.DownTrack, isManaged)
switch event.DownTrack.Kind() { switch event.DownTrack.Kind() {
@@ -470,7 +479,7 @@ func (s *StreamAllocator) handleSignalEstimate(event *Event) {
} }
if !found { if !found {
if len(remb.SSRCs) == 0 { if len(remb.SSRCs) == 0 {
s.logger.Warnw("no SSRC to track REMB", nil) s.params.Logger.Warnw("no SSRC to track REMB", nil)
return return
} }
@@ -496,7 +505,7 @@ func (s *StreamAllocator) handleSignalEstimate(event *Event) {
s.receivedEstimate = int64(remb.Bitrate) s.receivedEstimate = int64(remb.Bitrate)
/* /*
if s.prevReceivedEstimate != s.receivedEstimate { if s.prevReceivedEstimate != s.receivedEstimate {
s.logger.Debugw("received new estimate", s.params.Logger.Debugw("received new estimate",
"old(bps)", s.prevReceivedEstimate, "old(bps)", s.prevReceivedEstimate,
"new(bps)", s.receivedEstimate, "new(bps)", s.receivedEstimate,
) )
@@ -512,12 +521,14 @@ func (s *StreamAllocator) handleSignalTargetBitrate(event *Event) {
receivedEstimate, _ := event.Data.(int) receivedEstimate, _ := event.Data.(int)
s.prevReceivedEstimate = s.receivedEstimate s.prevReceivedEstimate = s.receivedEstimate
s.receivedEstimate = int64(receivedEstimate) s.receivedEstimate = int64(receivedEstimate)
if s.prevReceivedEstimate != s.receivedEstimate { /*
s.logger.Debugw("received new estimate", if s.prevReceivedEstimate != s.receivedEstimate {
"old(bps)", s.prevReceivedEstimate, s.params.Logger.Debugw("received new estimate",
"new(bps)", s.receivedEstimate, "old(bps)", s.prevReceivedEstimate,
) "new(bps)", s.receivedEstimate,
} )
}
*/
if s.maybeCommitEstimate() { if s.maybeCommitEstimate() {
s.allocateAllTracks() s.allocateAllTracks()
@@ -622,7 +633,7 @@ func (s *StreamAllocator) handleSignalSendProbe(event *Event) {
func (s *StreamAllocator) setState(state State) { func (s *StreamAllocator) setState(state State) {
if s.state != state { if s.state != state {
s.logger.Infow("state change", "from", s.state, "to", state) s.params.Logger.Infow("state change", "from", s.state, "to", state)
} }
s.state = state s.state = state
@@ -675,15 +686,15 @@ func (s *StreamAllocator) maybeCommitEstimate() (isDecreasing bool) {
s.committedChannelCapacity = s.receivedEstimate s.committedChannelCapacity = s.receivedEstimate
s.lastCommitTime = time.Now() s.lastCommitTime = time.Now()
s.logger.Debugw("committing channel capacity", "capacity(bps)", s.committedChannelCapacity) s.params.Logger.Debugw("committing channel capacity", "capacity(bps)", s.committedChannelCapacity)
return return
} }
func (s *StreamAllocator) allocateTrack(track *Track) { func (s *StreamAllocator) allocateTrack(track *Track) {
// if not deficient, free pass allocate track // if not deficient, free pass allocate track
if s.state == StateStable || !track.IsManaged() { if !s.params.Config.Enabled || s.state == StateStable || !track.IsManaged() {
update := NewStreamStateUpdate() update := NewStreamStateUpdate()
allocation := track.Allocate(ChannelCapacityInfinity) allocation := track.Allocate(ChannelCapacityInfinity, s.params.Config.AllowPause)
update.HandleStreamingChange(allocation.change, track) update.HandleStreamingChange(allocation.change, track)
s.maybeSendUpdate(update) s.maybeSendUpdate(update)
return return
@@ -704,8 +715,13 @@ func (s *StreamAllocator) allocateTrack(track *Track) {
return return
} }
// downgrade, giving back bits //
if transition.from.GreaterThan(transition.to) { // One of
// - downgrade, giving back bits, commit the allocation.
// - if not a downgrade, the stream was paused and trying to restart.
// If pause is disallowed, commit the allocation to get stream started again.
//
if !s.params.Config.AllowPause || transition.from.GreaterThan(transition.to) {
allocation := track.ProvisionalAllocateCommit() allocation := track.ProvisionalAllocateCommit()
update := NewStreamStateUpdate() update := NewStreamStateUpdate()
@@ -776,6 +792,11 @@ func (s *StreamAllocator) allocateTrack(track *Track) {
} }
func (s *StreamAllocator) allocateAllTracks() { func (s *StreamAllocator) allocateAllTracks() {
if !s.params.Config.Enabled {
// nothing else to do when disabled
return
}
s.resetBoost() s.resetBoost()
// //
@@ -799,7 +820,7 @@ func (s *StreamAllocator) allocateAllTracks() {
// Infinite channel capacity is given so that exempt tracks do not stall // Infinite channel capacity is given so that exempt tracks do not stall
// //
for _, track := range s.exemptVideoTracksSorted { for _, track := range s.exemptVideoTracksSorted {
allocation := track.Allocate(ChannelCapacityInfinity) allocation := track.Allocate(ChannelCapacityInfinity, s.params.Config.AllowPause)
update.HandleStreamingChange(allocation.change, track) update.HandleStreamingChange(allocation.change, track)
// LK-TODO: optimistic allocation before bitrate is available will return 0. How to account for that? // LK-TODO: optimistic allocation before bitrate is available will return 0. How to account for that?
@@ -828,7 +849,7 @@ func (s *StreamAllocator) allocateAllTracks() {
} }
for _, track := range s.managedVideoTracksSorted { for _, track := range s.managedVideoTracksSorted {
usedChannelCapacity := track.ProvisionalAllocate(availableChannelCapacity, layers) usedChannelCapacity := track.ProvisionalAllocate(availableChannelCapacity, layers, s.params.Config.AllowPause)
availableChannelCapacity -= usedChannelCapacity availableChannelCapacity -= usedChannelCapacity
if availableChannelCapacity < 0 { if availableChannelCapacity < 0 {
availableChannelCapacity = 0 availableChannelCapacity = 0
@@ -853,11 +874,11 @@ func (s *StreamAllocator) maybeSendUpdate(update *StreamStateUpdate) {
return return
} }
s.logger.Debugw("streamed tracks changed", "update", update) s.params.Logger.Debugw("streamed tracks changed", "update", update)
if s.onStreamStateChange != nil { if s.onStreamStateChange != nil {
err := s.onStreamStateChange(update) err := s.onStreamStateChange(update)
if err != nil { if err != nil {
s.logger.Errorw("could not send streamed tracks update", err) s.params.Logger.Errorw("could not send streamed tracks update", err)
} }
} }
} }
@@ -1120,16 +1141,16 @@ func (t *Track) WritePaddingRTP(bytesToSend int) int {
return t.downTrack.WritePaddingRTP(bytesToSend) return t.downTrack.WritePaddingRTP(bytesToSend)
} }
func (t *Track) Allocate(availableChannelCapacity int64) VideoAllocation { func (t *Track) Allocate(availableChannelCapacity int64, allowPause bool) VideoAllocation {
return t.downTrack.Allocate(availableChannelCapacity) return t.downTrack.Allocate(availableChannelCapacity, allowPause)
} }
func (t *Track) ProvisionalAllocatePrepare() { func (t *Track) ProvisionalAllocatePrepare() {
t.downTrack.ProvisionalAllocatePrepare() t.downTrack.ProvisionalAllocatePrepare()
} }
func (t *Track) ProvisionalAllocate(availableChannelCapacity int64, layers VideoLayers) int64 { func (t *Track) ProvisionalAllocate(availableChannelCapacity int64, layers VideoLayers, allowPause bool) int64 {
return t.downTrack.ProvisionalAllocate(availableChannelCapacity, layers) return t.downTrack.ProvisionalAllocate(availableChannelCapacity, layers, allowPause)
} }
func (t *Track) ProvisionalAllocateGetCooperativeTransition() VideoTransition { func (t *Track) ProvisionalAllocateGetCooperativeTransition() VideoTransition {