diff --git a/pkg/config/config.go b/pkg/config/config.go index bb57ca48..7b47d385 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -65,6 +65,8 @@ type RTCConfig struct { // Which side runs bandwidth estimation UseSendSideBWE bool `yaml:"send_side_bandwidth_estimation"` + + CongestionControl CongestionControlConfig `yaml:"congestion_control"` } type PLIThrottleConfig struct { @@ -73,6 +75,11 @@ type PLIThrottleConfig struct { HighQuality time.Duration `yaml:"high_quality"` } +type CongestionControlConfig struct { + Enabled bool `yaml:"enabled"` + AllowPause bool `yaml:"allow_pause"` +} + type AudioConfig struct { // minimum level to be considered active, 0-127, where 0 is loudest ActiveLevel uint8 `yaml:"active_level"` @@ -158,6 +165,10 @@ func NewConfig(confString string, c *cli.Context) (*Config, error) { MidQuality: time.Second, HighQuality: time.Second, }, + CongestionControl: CongestionControlConfig{ + Enabled: true, + AllowPause: true, + }, }, Audio: AudioConfig{ ActiveLevel: 30, // -30dBov = 0.03 diff --git a/pkg/rtc/participant.go b/pkg/rtc/participant.go index 32e3f477..ace91534 100644 --- a/pkg/rtc/participant.go +++ b/pkg/rtc/participant.go @@ -36,19 +36,20 @@ const ( ) type ParticipantParams struct { - Identity livekit.ParticipantIdentity - Name livekit.ParticipantName - SID livekit.ParticipantID - Config *WebRTCConfig - Sink routing.MessageSink - AudioConfig config.AudioConfig - ProtocolVersion types.ProtocolVersion - Telemetry telemetry.TelemetryService - ThrottleConfig config.PLIThrottleConfig - EnabledCodecs []*livekit.Codec - Hidden bool - Recorder bool - Logger logger.Logger + Identity livekit.ParticipantIdentity + Name livekit.ParticipantName + SID livekit.ParticipantID + Config *WebRTCConfig + Sink routing.MessageSink + AudioConfig config.AudioConfig + ProtocolVersion types.ProtocolVersion + Telemetry telemetry.TelemetryService + ThrottleConfig config.PLIThrottleConfig + CongestionControlConfig config.CongestionControlConfig + EnabledCodecs []*livekit.Codec + Hidden bool + Recorder bool + Logger logger.Logger } type ParticipantImpl struct { @@ -114,25 +115,27 @@ func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) { return nil, err } p.publisher, err = NewPCTransport(TransportParams{ - ParticipantID: p.params.SID, - ParticipantIdentity: p.params.Identity, - Target: livekit.SignalTarget_PUBLISHER, - Config: params.Config, - Telemetry: p.params.Telemetry, - EnabledCodecs: p.params.EnabledCodecs, - Logger: params.Logger, + ParticipantID: p.params.SID, + ParticipantIdentity: p.params.Identity, + Target: livekit.SignalTarget_PUBLISHER, + Config: params.Config, + CongestionControlConfig: params.CongestionControlConfig, + Telemetry: p.params.Telemetry, + EnabledCodecs: p.params.EnabledCodecs, + Logger: params.Logger, }) if err != nil { return nil, err } p.subscriber, err = NewPCTransport(TransportParams{ - ParticipantID: p.params.SID, - ParticipantIdentity: p.params.Identity, - Target: livekit.SignalTarget_SUBSCRIBER, - Config: params.Config, - Telemetry: p.params.Telemetry, - EnabledCodecs: p.params.EnabledCodecs, - Logger: params.Logger, + ParticipantID: p.params.SID, + ParticipantIdentity: p.params.Identity, + Target: livekit.SignalTarget_SUBSCRIBER, + Config: params.Config, + CongestionControlConfig: params.CongestionControlConfig, + Telemetry: p.params.Telemetry, + EnabledCodecs: p.params.EnabledCodecs, + Logger: params.Logger, }) if err != nil { return nil, err diff --git a/pkg/rtc/transport.go b/pkg/rtc/transport.go index 807e238d..c6814960 100644 --- a/pkg/rtc/transport.go +++ b/pkg/rtc/transport.go @@ -11,6 +11,7 @@ import ( "github.com/pion/sdp/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/sfu" "github.com/livekit/livekit-server/pkg/telemetry" @@ -48,13 +49,14 @@ type PCTransport struct { } type TransportParams struct { - ParticipantID livekit.ParticipantID - ParticipantIdentity livekit.ParticipantIdentity - Target livekit.SignalTarget - Config *WebRTCConfig - Telemetry telemetry.TelemetryService - EnabledCodecs []*livekit.Codec - Logger logger.Logger + ParticipantID livekit.ParticipantID + ParticipantIdentity livekit.ParticipantIdentity + Target livekit.SignalTarget + Config *WebRTCConfig + CongestionControlConfig config.CongestionControlConfig + Telemetry telemetry.TelemetryService + EnabledCodecs []*livekit.Codec + Logger logger.Logger } // 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 { t.streamAllocator = sfu.NewStreamAllocator(sfu.StreamAllocatorParams{ + Config: params.CongestionControlConfig, Logger: params.Logger, }) t.streamAllocator.Start() @@ -316,9 +319,10 @@ func (t *PCTransport) AddTrack(subTrack types.SubscribedTrack) { return } - source := subTrack.MediaTrack().Source() - isManaged := (source != livekit.TrackSource_SCREEN_SHARE && source != livekit.TrackSource_SCREEN_SHARE_AUDIO) || subTrack.MediaTrack().IsSimulcast() - t.streamAllocator.AddTrack(subTrack.DownTrack(), isManaged) + t.streamAllocator.AddTrack(subTrack.DownTrack(), sfu.AddTrackParams{ + Source: subTrack.MediaTrack().Source(), + IsSimulcast: subTrack.MediaTrack().IsSimulcast(), + }) } func (t *PCTransport) RemoveTrack(subTrack types.SubscribedTrack) { diff --git a/pkg/service/roommanager.go b/pkg/service/roommanager.go index b3181218..de3e0091 100644 --- a/pkg/service/roommanager.go +++ b/pkg/service/roommanager.go @@ -229,18 +229,19 @@ func (r *RoomManager) StartSession(ctx context.Context, roomName livekit.RoomNam sid := utils.NewGuid(utils.ParticipantPrefix) pLogger := rtc.LoggerWithParticipant(room.Logger, pi.Identity, sid) participant, err = rtc.NewParticipant(rtc.ParticipantParams{ - Identity: pi.Identity, - Name: pi.Name, - SID: sid, - Config: &rtcConf, - Sink: responseSink, - AudioConfig: r.config.Audio, - ProtocolVersion: pv, - Telemetry: r.telemetry, - ThrottleConfig: r.config.RTC.PLIThrottle, - EnabledCodecs: room.Room.EnabledCodecs, - Hidden: pi.Hidden, - Logger: pLogger, + Identity: pi.Identity, + Name: pi.Name, + SID: sid, + Config: &rtcConf, + Sink: responseSink, + AudioConfig: r.config.Audio, + ProtocolVersion: pv, + Telemetry: r.telemetry, + ThrottleConfig: r.config.RTC.PLIThrottle, + CongestionControlConfig: r.config.RTC.CongestionControl, + EnabledCodecs: room.Room.EnabledCodecs, + Hidden: pi.Hidden, + Logger: pLogger, }) if err != nil { diff --git a/pkg/sfu/downtrack.go b/pkg/sfu/downtrack.go index 347a9b31..0add39bc 100644 --- a/pkg/sfu/downtrack.go +++ b/pkg/sfu/downtrack.go @@ -4,13 +4,14 @@ import ( "encoding/binary" "errors" "fmt" - "github.com/livekit/livekit-server/pkg/sfu/connectionquality" "io" "strings" "sync" "sync/atomic" "time" + "github.com/livekit/livekit-server/pkg/sfu/connectionquality" + "github.com/pion/rtcp" "github.com/pion/rtp" "github.com/pion/sdp/v3" @@ -544,16 +545,16 @@ func (d *DownTrack) DistanceToDesired() int32 { return d.forwarder.DistanceToDesired() } -func (d *DownTrack) Allocate(availableChannelCapacity int64) VideoAllocation { - return d.forwarder.Allocate(availableChannelCapacity, d.receiver.GetBitrateTemporalCumulative()) +func (d *DownTrack) Allocate(availableChannelCapacity int64, allowPause bool) VideoAllocation { + return d.forwarder.Allocate(availableChannelCapacity, allowPause, d.receiver.GetBitrateTemporalCumulative()) } func (d *DownTrack) ProvisionalAllocatePrepare() { d.forwarder.ProvisionalAllocatePrepare(d.receiver.GetBitrateTemporalCumulative()) } -func (d *DownTrack) ProvisionalAllocate(availableChannelCapacity int64, layers VideoLayers) int64 { - return d.forwarder.ProvisionalAllocate(availableChannelCapacity, layers) +func (d *DownTrack) ProvisionalAllocate(availableChannelCapacity int64, layers VideoLayers, allowPause bool) int64 { + return d.forwarder.ProvisionalAllocate(availableChannelCapacity, layers, allowPause) } func (d *DownTrack) ProvisionalAllocateGetCooperativeTransition() VideoTransition { diff --git a/pkg/sfu/forwarder.go b/pkg/sfu/forwarder.go index d257a202..8a8155a4 100644 --- a/pkg/sfu/forwarder.go +++ b/pkg/sfu/forwarder.go @@ -360,7 +360,7 @@ func (f *Forwarder) DistanceToDesired() int32 { 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() defer f.lock.Unlock() @@ -399,14 +399,18 @@ func (f *Forwarder) Allocate(availableChannelCapacity int64, brs Bitrates) Video change = VideoStreamingChangeResuming } } else { - // disable forwarding as it is not known how big this stream is - // and if it will fit in the available channel capacity - f.currentLayers = InvalidLayers + if !allowPause { + // when pause is disallowed, pick the lowest available + 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 { state = VideoAllocationStateDeficient - if f.targetLayers != InvalidLayers { - change = VideoStreamingChangePausing + if !allowPause { + // 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() defer f.lock.Unlock() @@ -507,6 +538,12 @@ func (f *Forwarder) ProvisionalAllocate(availableChannelCapacity int64, layers V 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 } diff --git a/pkg/sfu/forwarder_test.go b/pkg/sfu/forwarder_test.go index c223466a..5d497bcd 100644 --- a/pkg/sfu/forwarder_test.go +++ b/pkg/sfu/forwarder_test.go @@ -157,7 +157,7 @@ func TestForwarderAllocate(t *testing.T) { targetLayers: InvalidLayers, distanceToDesired: 0, } - result := f.Allocate(ChannelCapacityInfinity, bitrates) + result := f.Allocate(ChannelCapacityInfinity, true, bitrates) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) @@ -175,7 +175,7 @@ func TestForwarderAllocate(t *testing.T) { targetLayers: InvalidLayers, distanceToDesired: 0, } - result = f.Allocate(ChannelCapacityInfinity, emptyBitrates) + result = f.Allocate(ChannelCapacityInfinity, true, emptyBitrates) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) @@ -197,13 +197,13 @@ func TestForwarderAllocate(t *testing.T) { targetLayers: expectedTargetLayers, distanceToDesired: 0, } - result = f.Allocate(ChannelCapacityInfinity, emptyBitrates) + result = f.Allocate(ChannelCapacityInfinity, true, emptyBitrates) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, expectedTargetLayers, f.TargetLayers()) 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{ state: VideoAllocationStateDeficient, change: VideoStreamingChangePausing, @@ -214,12 +214,33 @@ func TestForwarderAllocate(t *testing.T) { targetLayers: InvalidLayers, distanceToDesired: 0, } - result = f.Allocate(ChannelCapacityInfinity-1, emptyBitrates) + result = f.Allocate(ChannelCapacityInfinity-1, true, emptyBitrates) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, InvalidLayers, f.CurrentLayers()) 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 expectedTargetLayers = VideoLayers{ spatial: 2, @@ -227,7 +248,7 @@ func TestForwarderAllocate(t *testing.T) { } expectedResult = VideoAllocation{ state: VideoAllocationStateOptimal, - change: VideoStreamingChangeResuming, + change: VideoStreamingChangeNone, bandwidthRequested: bitrates[2][1], bandwidthDelta: bitrates[2][1], availableLayers: []uint16{0}, @@ -235,7 +256,7 @@ func TestForwarderAllocate(t *testing.T) { targetLayers: expectedTargetLayers, distanceToDesired: 0, } - result = f.Allocate(ChannelCapacityInfinity-1, bitrates) + result = f.Allocate(ChannelCapacityInfinity-1, true, bitrates) require.Equal(t, expectedResult, result) require.Equal(t, expectedResult, f.lastAllocation) require.Equal(t, InvalidLayers, f.CurrentLayers()) @@ -256,7 +277,7 @@ func TestForwarderAllocate(t *testing.T) { targetLayers: expectedTargetLayers, 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, f.lastAllocation) require.Equal(t, InvalidLayers, f.CurrentLayers()) @@ -273,11 +294,32 @@ func TestForwarderAllocate(t *testing.T) { targetLayers: InvalidLayers, 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, f.lastAllocation) require.Equal(t, InvalidLayers, f.CurrentLayers()) 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) { @@ -291,14 +333,14 @@ func TestForwarderProvisionalAllocate(t *testing.T) { 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) - 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) // 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) // 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, f.lastAllocation) 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) { @@ -334,10 +402,10 @@ func TestForwarderProvisionalAllocateMute(t *testing.T) { f.Mute(true) 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) - 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) // committing should set target to InvalidLayers as track is muted @@ -785,7 +853,7 @@ func TestForwarderPause(t *testing.T) { } 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) f.ProvisionalAllocateCommit() @@ -815,7 +883,7 @@ func TestForwarderPauseMute(t *testing.T) { } 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) f.ProvisionalAllocateCommit() diff --git a/pkg/sfu/streamallocator.go b/pkg/sfu/streamallocator.go index 76aa6c65..739930eb 100644 --- a/pkg/sfu/streamallocator.go +++ b/pkg/sfu/streamallocator.go @@ -7,6 +7,8 @@ import ( "sync" "time" + "github.com/livekit/livekit-server/pkg/config" + "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" "github.com/pion/rtcp" "github.com/pion/webrtc/v3" @@ -107,11 +109,12 @@ func (e Event) String() string { } type StreamAllocatorParams struct { + Config config.CongestionControlConfig Logger logger.Logger } type StreamAllocator struct { - logger logger.Logger + params StreamAllocatorParams onStreamStateChange func(update *StreamStateUpdate) error @@ -145,7 +148,7 @@ type StreamAllocator struct { func NewStreamAllocator(params StreamAllocatorParams) *StreamAllocator { s := &StreamAllocator{ - logger: params.Logger, + params: params, audioTracks: make(map[string]*Track), videoTracks: make(map[string]*Track), 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{ Signal: SignalAddTrack, DownTrack: downTrack, - Data: isManaged, + Data: params, }) if downTrack.Kind() == webrtc.RTPCodecTypeVideo { @@ -362,7 +370,8 @@ func (s *StreamAllocator) handleEvent(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) switch event.DownTrack.Kind() { @@ -470,7 +479,7 @@ func (s *StreamAllocator) handleSignalEstimate(event *Event) { } if !found { 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 } @@ -496,7 +505,7 @@ func (s *StreamAllocator) handleSignalEstimate(event *Event) { s.receivedEstimate = int64(remb.Bitrate) /* if s.prevReceivedEstimate != s.receivedEstimate { - s.logger.Debugw("received new estimate", + s.params.Logger.Debugw("received new estimate", "old(bps)", s.prevReceivedEstimate, "new(bps)", s.receivedEstimate, ) @@ -512,12 +521,14 @@ func (s *StreamAllocator) handleSignalTargetBitrate(event *Event) { receivedEstimate, _ := event.Data.(int) s.prevReceivedEstimate = s.receivedEstimate s.receivedEstimate = int64(receivedEstimate) - if s.prevReceivedEstimate != s.receivedEstimate { - s.logger.Debugw("received new estimate", - "old(bps)", s.prevReceivedEstimate, - "new(bps)", s.receivedEstimate, - ) - } + /* + if s.prevReceivedEstimate != s.receivedEstimate { + s.params.Logger.Debugw("received new estimate", + "old(bps)", s.prevReceivedEstimate, + "new(bps)", s.receivedEstimate, + ) + } + */ if s.maybeCommitEstimate() { s.allocateAllTracks() @@ -622,7 +633,7 @@ func (s *StreamAllocator) handleSignalSendProbe(event *Event) { func (s *StreamAllocator) setState(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 @@ -675,15 +686,15 @@ func (s *StreamAllocator) maybeCommitEstimate() (isDecreasing bool) { s.committedChannelCapacity = s.receivedEstimate 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 } func (s *StreamAllocator) allocateTrack(track *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() - allocation := track.Allocate(ChannelCapacityInfinity) + allocation := track.Allocate(ChannelCapacityInfinity, s.params.Config.AllowPause) update.HandleStreamingChange(allocation.change, track) s.maybeSendUpdate(update) return @@ -704,8 +715,13 @@ func (s *StreamAllocator) allocateTrack(track *Track) { 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() update := NewStreamStateUpdate() @@ -776,6 +792,11 @@ func (s *StreamAllocator) allocateTrack(track *Track) { } func (s *StreamAllocator) allocateAllTracks() { + if !s.params.Config.Enabled { + // nothing else to do when disabled + return + } + s.resetBoost() // @@ -799,7 +820,7 @@ func (s *StreamAllocator) allocateAllTracks() { // Infinite channel capacity is given so that exempt tracks do not stall // for _, track := range s.exemptVideoTracksSorted { - allocation := track.Allocate(ChannelCapacityInfinity) + allocation := track.Allocate(ChannelCapacityInfinity, s.params.Config.AllowPause) update.HandleStreamingChange(allocation.change, track) // 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 { - usedChannelCapacity := track.ProvisionalAllocate(availableChannelCapacity, layers) + usedChannelCapacity := track.ProvisionalAllocate(availableChannelCapacity, layers, s.params.Config.AllowPause) availableChannelCapacity -= usedChannelCapacity if availableChannelCapacity < 0 { availableChannelCapacity = 0 @@ -853,11 +874,11 @@ func (s *StreamAllocator) maybeSendUpdate(update *StreamStateUpdate) { return } - s.logger.Debugw("streamed tracks changed", "update", update) + s.params.Logger.Debugw("streamed tracks changed", "update", update) if s.onStreamStateChange != nil { err := s.onStreamStateChange(update) 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) } -func (t *Track) Allocate(availableChannelCapacity int64) VideoAllocation { - return t.downTrack.Allocate(availableChannelCapacity) +func (t *Track) Allocate(availableChannelCapacity int64, allowPause bool) VideoAllocation { + return t.downTrack.Allocate(availableChannelCapacity, allowPause) } func (t *Track) ProvisionalAllocatePrepare() { t.downTrack.ProvisionalAllocatePrepare() } -func (t *Track) ProvisionalAllocate(availableChannelCapacity int64, layers VideoLayers) int64 { - return t.downTrack.ProvisionalAllocate(availableChannelCapacity, layers) +func (t *Track) ProvisionalAllocate(availableChannelCapacity int64, layers VideoLayers, allowPause bool) int64 { + return t.downTrack.ProvisionalAllocate(availableChannelCapacity, layers, allowPause) } func (t *Track) ProvisionalAllocateGetCooperativeTransition() VideoTransition {