Pure code movement (#1552)

This commit is contained in:
Raja Subramanian
2023-03-26 23:13:17 +05:30
committed by GitHub
parent afdae26972
commit f63962c2cc
17 changed files with 1450 additions and 1418 deletions
+1 -1
View File
@@ -240,7 +240,7 @@ func (t *MediaTrackReceiver) SetLayerSsrc(mime string, rid string, ssrc uint32)
defer t.lock.Unlock()
layer := buffer.RidToSpatialLayer(rid, t.params.TrackInfo)
if layer == sfu.InvalidLayerSpatial {
if layer == buffer.InvalidLayerSpatial {
// non-simulcast case will not have `rid`
layer = 0
}
+3 -2
View File
@@ -24,6 +24,7 @@ import (
"github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/livekit-server/pkg/sfu/buffer"
"github.com/livekit/livekit-server/pkg/sfu/connectionquality"
"github.com/livekit/livekit-server/pkg/sfu/streamallocator"
"github.com/livekit/livekit-server/pkg/telemetry"
"github.com/livekit/mediatransportutil/pkg/twcc"
"github.com/livekit/protocol/auth"
@@ -1338,7 +1339,7 @@ func (p *ParticipantImpl) subscriberRTCPWorker() {
}
}
func (p *ParticipantImpl) onStreamStateChange(update *sfu.StreamStateUpdate) error {
func (p *ParticipantImpl) onStreamStateChange(update *streamallocator.StreamStateUpdate) error {
if len(update.StreamStates) == 0 {
return nil
}
@@ -1346,7 +1347,7 @@ func (p *ParticipantImpl) onStreamStateChange(update *sfu.StreamStateUpdate) err
streamStateUpdate := &livekit.StreamStateUpdate{}
for _, streamStateInfo := range update.StreamStates {
state := livekit.StreamState_ACTIVE
if streamStateInfo.State == sfu.StreamStatePaused {
if streamStateInfo.State == streamallocator.StreamStatePaused {
state = livekit.StreamState_PAUSED
}
streamStateUpdate.StreamStates = append(streamStateUpdate.StreamStates, &livekit.StreamStateInfo{
+5 -5
View File
@@ -26,7 +26,7 @@ import (
"github.com/livekit/livekit-server/pkg/config"
serverlogger "github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/livekit-server/pkg/sfu/streamallocator"
"github.com/livekit/livekit-server/pkg/telemetry"
"github.com/livekit/livekit-server/pkg/telemetry/prometheus"
)
@@ -182,7 +182,7 @@ type PCTransport struct {
onNegotiationFailed func()
// stream allocator for subscriber PC
streamAllocator *sfu.StreamAllocator
streamAllocator *streamallocator.StreamAllocator
previousAnswer *webrtc.SessionDescription
// track id -> description map in previous offer sdp
@@ -366,7 +366,7 @@ func NewPCTransport(params TransportParams) (*PCTransport, error) {
canReuseTransceiver: true,
}
if params.IsSendSide {
t.streamAllocator = sfu.NewStreamAllocator(sfu.StreamAllocatorParams{
t.streamAllocator = streamallocator.NewStreamAllocator(streamallocator.StreamAllocatorParams{
Config: params.CongestionControlConfig,
Logger: params.Logger,
})
@@ -1085,7 +1085,7 @@ func (t *PCTransport) ResetShortConnOnICERestart() {
t.resetShortConnOnICERestart.Store(true)
}
func (t *PCTransport) OnStreamStateChange(f func(update *sfu.StreamStateUpdate) error) {
func (t *PCTransport) OnStreamStateChange(f func(update *streamallocator.StreamStateUpdate) error) {
if t.streamAllocator == nil {
return
}
@@ -1098,7 +1098,7 @@ func (t *PCTransport) AddTrackToStreamAllocator(subTrack types.SubscribedTrack)
return
}
t.streamAllocator.AddTrack(subTrack.DownTrack(), sfu.AddTrackParams{
t.streamAllocator.AddTrack(subTrack.DownTrack(), streamallocator.AddTrackParams{
Source: subTrack.MediaTrack().Source(),
IsSimulcast: subTrack.MediaTrack().IsSimulcast(),
PublisherID: subTrack.MediaTrack().PublisherID(),
+2 -1
View File
@@ -17,6 +17,7 @@ import (
"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/sfu/streamallocator"
"github.com/livekit/livekit-server/pkg/telemetry"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
@@ -243,7 +244,7 @@ func (t *TransportManager) OnSubscriberInitialConnected(f func()) {
t.onSubscriberInitialConnected = f
}
func (t *TransportManager) OnSubscriberStreamStateChange(f func(update *sfu.StreamStateUpdate) error) {
func (t *TransportManager) OnSubscriberStreamStateChange(f func(update *streamallocator.StreamStateUpdate) error) {
t.subscriber.OnStreamStateChange(f)
}
+5
View File
@@ -15,6 +15,11 @@ var (
Spatial: InvalidLayerSpatial,
Temporal: InvalidLayerTemporal,
}
DefaultMaxLayers = VideoLayer{
Spatial: DefaultMaxLayerSpatial,
Temporal: DefaultMaxLayerTemporal,
}
)
type VideoLayer struct {
+13 -13
View File
@@ -141,7 +141,7 @@ type DownTrackStreamAllocatorListener interface {
OnSubscriptionChanged(dt *DownTrack)
// subscribed max video layer changed
OnSubscribedLayersChanged(dt *DownTrack, layers VideoLayers)
OnSubscribedLayersChanged(dt *DownTrack, layers buffer.VideoLayer)
// target video layer reached
OnTargetLayerReached(dt *DownTrack)
@@ -508,7 +508,7 @@ func (d *DownTrack) stopKeyFrameRequester() {
}
func (d *DownTrack) keyFrameRequester(generation uint32, layer int32) {
if d.IsClosed() || layer == InvalidLayerSpatial {
if d.IsClosed() || layer == buffer.InvalidLayerSpatial {
return
}
interval := 2 * d.rtpStats.GetRtt()
@@ -739,7 +739,7 @@ func (d *DownTrack) PubMute(pubMuted bool) {
d.handleMute(pubMuted, true, changed, maxLayers)
}
func (d *DownTrack) handleMute(muted bool, isPub bool, changed bool, maxLayers VideoLayers) {
func (d *DownTrack) handleMute(muted bool, isPub bool, changed bool, maxLayers buffer.VideoLayer) {
if !changed {
return
}
@@ -767,7 +767,7 @@ func (d *DownTrack) handleMute(muted bool, isPub bool, changed bool, maxLayers V
// and that could turn on/off layers on publisher side.
//
if !isPub && d.onMaxSubscribedLayerChanged != nil && d.kind == webrtc.RTPCodecTypeVideo {
notifyLayer := InvalidLayerSpatial
notifyLayer := buffer.InvalidLayerSpatial
if !muted {
//
// When unmuting, don't wait for layer lock as
@@ -861,7 +861,7 @@ func (d *DownTrack) CloseWithFlush(flush bool) {
d.logger.Infow("rtp stats", "direction", "downstream", "mime", d.mime, "ssrc", d.ssrc, "stats", d.rtpStats.ToString())
if d.onMaxSubscribedLayerChanged != nil && d.kind == webrtc.RTPCodecTypeVideo {
d.onMaxSubscribedLayerChanged(d, InvalidLayerSpatial)
d.onMaxSubscribedLayerChanged(d, buffer.InvalidLayerSpatial)
}
if d.onCloseHandler != nil {
@@ -905,7 +905,7 @@ func (d *DownTrack) SetMaxTemporalLayer(temporalLayer int32) {
}
}
func (d *DownTrack) MaxLayers() VideoLayers {
func (d *DownTrack) MaxLayers() buffer.VideoLayer {
return d.forwarder.MaxLayers()
}
@@ -1008,7 +1008,7 @@ func (d *DownTrack) AllocateOptimal(allowOvershoot bool) VideoAllocation {
al, brs := d.receiver.GetLayeredBitrate()
allocation := d.forwarder.AllocateOptimal(al, brs, allowOvershoot)
d.maybeStartKeyFrameRequester()
d.maybeAddTransition(allocation.bandwidthNeeded, allocation.distanceToDesired)
d.maybeAddTransition(allocation.BandwidthNeeded, allocation.DistanceToDesired)
return allocation
}
@@ -1017,7 +1017,7 @@ func (d *DownTrack) ProvisionalAllocatePrepare() {
d.forwarder.ProvisionalAllocatePrepare(al, brs)
}
func (d *DownTrack) ProvisionalAllocate(availableChannelCapacity int64, layers VideoLayers, allowPause bool, allowOvershoot bool) int64 {
func (d *DownTrack) ProvisionalAllocate(availableChannelCapacity int64, layers buffer.VideoLayer, allowPause bool, allowOvershoot bool) int64 {
return d.forwarder.ProvisionalAllocate(availableChannelCapacity, layers, allowPause, allowOvershoot)
}
@@ -1036,7 +1036,7 @@ func (d *DownTrack) ProvisionalAllocateGetBestWeightedTransition() VideoTransiti
func (d *DownTrack) ProvisionalAllocateCommit() VideoAllocation {
allocation := d.forwarder.ProvisionalAllocateCommit()
d.maybeStartKeyFrameRequester()
d.maybeAddTransition(allocation.bandwidthNeeded, allocation.distanceToDesired)
d.maybeAddTransition(allocation.BandwidthNeeded, allocation.DistanceToDesired)
return allocation
}
@@ -1044,7 +1044,7 @@ func (d *DownTrack) AllocateNextHigher(availableChannelCapacity int64, allowOver
al, brs := d.receiver.GetLayeredBitrate()
allocation, available := d.forwarder.AllocateNextHigher(availableChannelCapacity, al, brs, allowOvershoot)
d.maybeStartKeyFrameRequester()
d.maybeAddTransition(allocation.bandwidthNeeded, allocation.distanceToDesired)
d.maybeAddTransition(allocation.BandwidthNeeded, allocation.DistanceToDesired)
return allocation, available
}
@@ -1059,7 +1059,7 @@ func (d *DownTrack) Pause() VideoAllocation {
al, brs := d.receiver.GetLayeredBitrate()
allocation := d.forwarder.Pause(al, brs)
d.maybeStartKeyFrameRequester()
d.maybeAddTransition(allocation.bandwidthNeeded, allocation.distanceToDesired)
d.maybeAddTransition(allocation.BandwidthNeeded, allocation.DistanceToDesired)
return allocation
}
@@ -1278,7 +1278,7 @@ func (d *DownTrack) handleRTCP(bytes []byte) {
sendPliOnce := func() {
if pliOnce {
_, layer := d.forwarder.CheckSync()
if layer != InvalidLayerSpatial && !d.forwarder.IsAnyMuted() {
if layer != buffer.InvalidLayerSpatial && !d.forwarder.IsAnyMuted() {
d.logger.Debugw("sending PLI RTCP", "layer", layer)
d.receiver.SendPLI(layer, false)
d.isNACKThrottled.Store(true)
@@ -1637,7 +1637,7 @@ func (d *DownTrack) onBindAndConnected() {
if d.connected.Load() && d.bound.Load() && !d.bindAndConnectedOnce.Swap(true) {
if d.kind == webrtc.RTPCodecTypeVideo {
_, layer := d.forwarder.CheckSync()
if layer != InvalidLayerSpatial {
if layer != buffer.InvalidLayerSpatial {
d.receiver.SendPLI(layer, true)
}
}
+226 -247
View File
File diff suppressed because it is too large Load Diff
+474 -474
View File
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -30,7 +30,7 @@ var (
type AudioLevelHandle func(level uint8, duration uint32)
type Bitrates [DefaultMaxLayerSpatial + 1][DefaultMaxLayerTemporal + 1]int64
type Bitrates [buffer.DefaultMaxLayerSpatial + 1][buffer.DefaultMaxLayerTemporal + 1]int64
// TrackReceiver defines an interface receive media from remote peer
type TrackReceiver interface {
@@ -94,11 +94,11 @@ type WebRTCReceiver struct {
twcc *twcc.Responder
bufferMu sync.RWMutex
buffers [DefaultMaxLayerSpatial + 1]*buffer.Buffer
buffers [buffer.DefaultMaxLayerSpatial + 1]*buffer.Buffer
rtt uint32
upTrackMu sync.RWMutex
upTracks [DefaultMaxLayerSpatial + 1]*webrtc.TrackRemote
upTracks [buffer.DefaultMaxLayerSpatial + 1]*webrtc.TrackRemote
lbThreshold int
@@ -391,7 +391,7 @@ func (w *WebRTCReceiver) SetMaxExpectedSpatialLayer(layer int32) {
w.streamTrackerManager.SetMaxExpectedSpatialLayer(layer)
now := time.Now()
if layer == InvalidLayerSpatial {
if layer == buffer.InvalidLayerSpatial {
w.connectionStats.UpdateLayerMute(true, now)
} else {
w.connectionStats.UpdateLayerMute(false, now)
+181
View File
@@ -0,0 +1,181 @@
package streamallocator
import (
"fmt"
"time"
"github.com/livekit/protocol/logger"
)
// ------------------------------------------------
type ChannelTrend int
const (
ChannelTrendNeutral ChannelTrend = iota
ChannelTrendClearing
ChannelTrendCongesting
)
func (c ChannelTrend) String() string {
switch c {
case ChannelTrendNeutral:
return "NEUTRAL"
case ChannelTrendClearing:
return "CLEARING"
case ChannelTrendCongesting:
return "CONGESTING"
default:
return fmt.Sprintf("%d", int(c))
}
}
// ------------------------------------------------
type ChannelCongestionReason int
const (
ChannelCongestionReasonNone ChannelCongestionReason = iota
ChannelCongestionReasonEstimate
ChannelCongestionReasonLoss
)
func (c ChannelCongestionReason) String() string {
switch c {
case ChannelCongestionReasonNone:
return "NONE"
case ChannelCongestionReasonEstimate:
return "ESTIMATE"
case ChannelCongestionReasonLoss:
return "LOSS"
default:
return fmt.Sprintf("%d", int(c))
}
}
// ------------------------------------------------
type ChannelObserverParams struct {
Name string
EstimateRequiredSamples int
EstimateDownwardTrendThreshold float64
EstimateCollapseValues bool
NackWindowMinDuration time.Duration
NackWindowMaxDuration time.Duration
NackRatioThreshold float64
}
type ChannelObserver struct {
params ChannelObserverParams
logger logger.Logger
estimateTrend *TrendDetector
nackWindowStartTime time.Time
packets uint32
repeatedNacks uint32
}
func NewChannelObserver(params ChannelObserverParams, logger logger.Logger) *ChannelObserver {
return &ChannelObserver{
params: params,
logger: logger,
estimateTrend: NewTrendDetector(TrendDetectorParams{
Name: params.Name + "-estimate",
Logger: logger,
RequiredSamples: params.EstimateRequiredSamples,
DownwardTrendThreshold: params.EstimateDownwardTrendThreshold,
CollapseValues: params.EstimateCollapseValues,
}),
}
}
func (c *ChannelObserver) SeedEstimate(estimate int64) {
c.estimateTrend.Seed(estimate)
}
func (c *ChannelObserver) SeedNack(packets uint32, repeatedNacks uint32) {
c.packets = packets
c.repeatedNacks = repeatedNacks
}
func (c *ChannelObserver) AddEstimate(estimate int64) {
c.estimateTrend.AddValue(estimate)
}
func (c *ChannelObserver) AddNack(packets uint32, repeatedNacks uint32) {
if c.params.NackWindowMaxDuration != 0 && !c.nackWindowStartTime.IsZero() && time.Since(c.nackWindowStartTime) > c.params.NackWindowMaxDuration {
c.nackWindowStartTime = time.Time{}
c.packets = 0
c.repeatedNacks = 0
}
//
// Start NACK monitoring window only when a repeated NACK happens.
// This allows locking tightly to when NACKs start happening and
// check if the NACKs keep adding up (potentially a sign of congestion)
// or isolated losses
//
if c.repeatedNacks == 0 && repeatedNacks != 0 {
c.nackWindowStartTime = time.Now()
}
if !c.nackWindowStartTime.IsZero() {
c.packets += packets
c.repeatedNacks += repeatedNacks
}
}
func (c *ChannelObserver) GetLowestEstimate() int64 {
return c.estimateTrend.GetLowest()
}
func (c *ChannelObserver) GetHighestEstimate() int64 {
return c.estimateTrend.GetHighest()
}
func (c *ChannelObserver) GetNackRatio() (uint32, uint32, float64) {
ratio := 0.0
if c.packets != 0 {
ratio = float64(c.repeatedNacks) / float64(c.packets)
if ratio > 1.0 {
ratio = 1.0
}
}
return c.packets, c.repeatedNacks, ratio
}
func (c *ChannelObserver) GetTrend() (ChannelTrend, ChannelCongestionReason) {
estimateDirection := c.estimateTrend.GetDirection()
packets, repeatedNacks, nackRatio := c.GetNackRatio()
switch {
case estimateDirection == TrendDirectionDownward:
c.logger.Debugw(
"stream allocator: channel observer: estimate is trending downward",
"name", c.params.Name,
"estimate", c.estimateTrend.ToString(),
"packets", packets,
"repeatedNacks", repeatedNacks,
"ratio", nackRatio,
)
return ChannelTrendCongesting, ChannelCongestionReasonEstimate
case c.params.NackWindowMinDuration != 0 && !c.nackWindowStartTime.IsZero() && time.Since(c.nackWindowStartTime) > c.params.NackWindowMinDuration && nackRatio > c.params.NackRatioThreshold:
c.logger.Debugw(
"stream allocator: channel observer: high rate of repeated NACKs",
"name", c.params.Name,
"estimate", c.estimateTrend.ToString(),
"packets", packets,
"repeatedNacks", repeatedNacks,
"ratio", nackRatio,
)
return ChannelTrendCongesting, ChannelCongestionReasonLoss
case estimateDirection == TrendDirectionUpward:
return ChannelTrendClearing, ChannelCongestionReasonNone
}
return ChannelTrendNeutral, ChannelCongestionReasonNone
}
// ------------------------------------------------
@@ -103,7 +103,7 @@
// window being long(ish). But, RTT should be much shorter especially if
// the subscriber peer connection of the client is able to connect to
// the nearest data center.
package sfu
package streamallocator
import (
"fmt"
@@ -1,4 +1,4 @@
package sfu
package streamallocator
import (
"fmt"
@@ -16,6 +16,8 @@ import (
"github.com/livekit/protocol/logger"
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/livekit-server/pkg/sfu/buffer"
)
const (
@@ -223,12 +225,12 @@ type AddTrackParams struct {
PublisherID livekit.ParticipantID
}
func (s *StreamAllocator) AddTrack(downTrack *DownTrack, params AddTrackParams) {
func (s *StreamAllocator) AddTrack(downTrack *sfu.DownTrack, params AddTrackParams) {
if downTrack.Kind() != webrtc.RTPCodecTypeVideo {
return
}
track := newTrack(downTrack, params.Source, params.IsSimulcast, params.PublisherID, s.params.Logger)
track := NewTrack(downTrack, params.Source, params.IsSimulcast, params.PublisherID, s.params.Logger)
track.SetPriority(params.Priority)
s.videoTracksMu.Lock()
@@ -244,7 +246,7 @@ func (s *StreamAllocator) AddTrack(downTrack *DownTrack, params AddTrackParams)
s.maybePostEventAllocateTrack(downTrack)
}
func (s *StreamAllocator) RemoveTrack(downTrack *DownTrack) {
func (s *StreamAllocator) RemoveTrack(downTrack *sfu.DownTrack) {
s.videoTracksMu.Lock()
if existing := s.videoTracks[livekit.TrackID(downTrack.ID())]; existing != nil && existing.DownTrack() == downTrack {
delete(s.videoTracks, livekit.TrackID(downTrack.ID()))
@@ -257,7 +259,7 @@ func (s *StreamAllocator) RemoveTrack(downTrack *DownTrack) {
})
}
func (s *StreamAllocator) SetTrackPriority(downTrack *DownTrack, priority uint8) {
func (s *StreamAllocator) SetTrackPriority(downTrack *sfu.DownTrack, priority uint8) {
s.videoTracksMu.Lock()
if track := s.videoTracks[livekit.TrackID(downTrack.ID())]; track != nil {
changed := track.SetPriority(priority)
@@ -280,7 +282,7 @@ func (s *StreamAllocator) resetState() {
}
// called when a new REMB is received (receive side bandwidth estimation)
func (s *StreamAllocator) OnREMB(downTrack *DownTrack, remb *rtcp.ReceiverEstimatedMaximumBitrate) {
func (s *StreamAllocator) OnREMB(downTrack *sfu.DownTrack, remb *rtcp.ReceiverEstimatedMaximumBitrate) {
//
// Channel capacity is estimated at a peer connection level. All down tracks
// in the peer connection will end up calling this for a REMB report with
@@ -360,7 +362,7 @@ func (s *StreamAllocator) OnREMB(downTrack *DownTrack, remb *rtcp.ReceiverEstima
}
// called when a new transport-cc feedback is received
func (s *StreamAllocator) OnTransportCCFeedback(downTrack *DownTrack, fb *rtcp.TransportLayerCC) {
func (s *StreamAllocator) OnTransportCCFeedback(downTrack *sfu.DownTrack, fb *rtcp.TransportLayerCC) {
if s.bwe != nil {
s.bwe.WriteRTCP([]rtcp.Packet{fb}, nil)
}
@@ -375,27 +377,27 @@ func (s *StreamAllocator) onTargetBitrateChange(bitrate int) {
}
// called when feeding track's layer availability changes
func (s *StreamAllocator) OnAvailableLayersChanged(downTrack *DownTrack) {
func (s *StreamAllocator) OnAvailableLayersChanged(downTrack *sfu.DownTrack) {
s.maybePostEventAllocateTrack(downTrack)
}
// called when feeding track's bitrate measurement of any layer is available
func (s *StreamAllocator) OnBitrateAvailabilityChanged(downTrack *DownTrack) {
func (s *StreamAllocator) OnBitrateAvailabilityChanged(downTrack *sfu.DownTrack) {
s.maybePostEventAllocateTrack(downTrack)
}
// called when feeding track's max publisher layer changes
func (s *StreamAllocator) OnMaxPublishedLayerChanged(downTrack *DownTrack) {
func (s *StreamAllocator) OnMaxPublishedLayerChanged(downTrack *sfu.DownTrack) {
s.maybePostEventAllocateTrack(downTrack)
}
// called when subscription settings changes (muting/unmuting of track)
func (s *StreamAllocator) OnSubscriptionChanged(downTrack *DownTrack) {
func (s *StreamAllocator) OnSubscriptionChanged(downTrack *sfu.DownTrack) {
s.maybePostEventAllocateTrack(downTrack)
}
// called when subscribed layers changes (limiting max layers)
func (s *StreamAllocator) OnSubscribedLayersChanged(downTrack *DownTrack, layers VideoLayers) {
func (s *StreamAllocator) OnSubscribedLayersChanged(downTrack *sfu.DownTrack, layers buffer.VideoLayer) {
shouldPost := false
s.videoTracksMu.Lock()
if track := s.videoTracks[livekit.TrackID(downTrack.ID())]; track != nil {
@@ -414,7 +416,7 @@ func (s *StreamAllocator) OnSubscribedLayersChanged(downTrack *DownTrack, layers
}
// called when forwarder finds a target layer
func (s *StreamAllocator) OnTargetLayerReached(downTrack *DownTrack) {
func (s *StreamAllocator) OnTargetLayerReached(downTrack *sfu.DownTrack) {
s.postEvent(Event{
Signal: streamAllocatorSignalTargetLayerFound,
TrackID: livekit.TrackID(downTrack.ID()),
@@ -422,7 +424,7 @@ func (s *StreamAllocator) OnTargetLayerReached(downTrack *DownTrack) {
}
// called when a video DownTrack sends a packet
func (s *StreamAllocator) OnPacketsSent(downTrack *DownTrack, size int) {
func (s *StreamAllocator) OnPacketsSent(downTrack *sfu.DownTrack, size int) {
s.prober.PacketsSent(size)
}
@@ -454,7 +456,7 @@ func (s *StreamAllocator) OnActiveChanged(isActive bool) {
}
}
func (s *StreamAllocator) maybePostEventAllocateTrack(downTrack *DownTrack) {
func (s *StreamAllocator) maybePostEventAllocateTrack(downTrack *sfu.DownTrack) {
shouldPost := false
s.videoTracksMu.Lock()
if track := s.videoTracks[livekit.TrackID(downTrack.ID())]; track != nil {
@@ -762,7 +764,7 @@ func (s *StreamAllocator) allocateTrack(track *Track) {
if !s.params.Config.Enabled || s.state == streamAllocatorStateStable || !track.IsManaged() {
update := NewStreamStateUpdate()
allocation := track.AllocateOptimal(FlagAllowOvershootWhileOptimal)
if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) {
if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) {
update.HandleStreamingChange(true, track)
}
s.maybeSendUpdate(update)
@@ -780,16 +782,16 @@ func (s *StreamAllocator) allocateTrack(track *Track) {
transition := track.ProvisionalAllocateGetCooperativeTransition(FlagAllowOvershootWhileDeficient)
// track is currently streaming at minimum
if transition.bandwidthDelta == 0 {
if transition.BandwidthDelta == 0 {
return
}
// downgrade, giving back bits
if transition.from.GreaterThan(transition.to) {
if transition.From.GreaterThan(transition.To) {
allocation := track.ProvisionalAllocateCommit()
update := NewStreamStateUpdate()
if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) {
if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) {
update.HandleStreamingChange(true, track)
}
s.maybeSendUpdate(update)
@@ -817,22 +819,22 @@ func (s *StreamAllocator) allocateTrack(track *Track) {
for _, t := range minDistanceSorted {
tx := t.ProvisionalAllocateGetBestWeightedTransition()
if tx.bandwidthDelta < 0 {
if tx.BandwidthDelta < 0 {
contributingTracks = append(contributingTracks, t)
bandwidthAcquired += -tx.bandwidthDelta
if bandwidthAcquired >= transition.bandwidthDelta {
bandwidthAcquired += -tx.BandwidthDelta
if bandwidthAcquired >= transition.BandwidthDelta {
break
}
}
}
update := NewStreamStateUpdate()
if bandwidthAcquired >= transition.bandwidthDelta {
if bandwidthAcquired >= transition.BandwidthDelta {
// commit the tracks that contributed
for _, t := range contributingTracks {
allocation := t.ProvisionalAllocateCommit()
if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) {
if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) {
update.HandleStreamingChange(true, t)
}
}
@@ -841,9 +843,9 @@ func (s *StreamAllocator) allocateTrack(track *Track) {
}
// commit the track that needs change if enough could be acquired or pause not allowed
if !s.params.Config.AllowPause || bandwidthAcquired >= transition.bandwidthDelta {
if !s.params.Config.AllowPause || bandwidthAcquired >= transition.BandwidthDelta {
allocation := track.ProvisionalAllocateCommit()
if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) {
if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) {
update.HandleStreamingChange(true, track)
}
}
@@ -915,11 +917,11 @@ func (s *StreamAllocator) maybeBoostDeficientTracks() {
continue
}
if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) {
if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) {
update.HandleStreamingChange(true, track)
}
availableChannelCapacity -= allocation.bandwidthDelta
availableChannelCapacity -= allocation.BandwidthDelta
if availableChannelCapacity <= 0 {
break
}
@@ -971,12 +973,12 @@ func (s *StreamAllocator) allocateAllTracks() {
}
allocation := track.AllocateOptimal(FlagAllowOvershootExemptTrackWhileDeficient)
if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) {
if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) {
update.HandleStreamingChange(true, track)
}
// LK-TODO: optimistic allocation before bitrate is available will return 0. How to account for that?
availableChannelCapacity -= allocation.bandwidthRequested
availableChannelCapacity -= allocation.BandwidthRequested
}
if availableChannelCapacity < 0 {
@@ -990,7 +992,7 @@ func (s *StreamAllocator) allocateAllTracks() {
}
allocation := track.Pause()
if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) {
if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) {
update.HandleStreamingChange(true, track)
}
}
@@ -1000,9 +1002,9 @@ func (s *StreamAllocator) allocateAllTracks() {
track.ProvisionalAllocatePrepare()
}
for spatial := int32(0); spatial <= DefaultMaxLayerSpatial; spatial++ {
for temporal := int32(0); temporal <= DefaultMaxLayerTemporal; temporal++ {
layers := VideoLayers{
for spatial := int32(0); spatial <= buffer.DefaultMaxLayerSpatial; spatial++ {
for temporal := int32(0); temporal <= buffer.DefaultMaxLayerTemporal; temporal++ {
layers := buffer.VideoLayer{
Spatial: spatial,
Temporal: temporal,
}
@@ -1019,7 +1021,7 @@ func (s *StreamAllocator) allocateAllTracks() {
for _, track := range sorted {
allocation := track.ProvisionalAllocateCommit()
if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) {
if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) {
update.HandleStreamingChange(true, track)
}
}
@@ -1172,7 +1174,7 @@ func (s *StreamAllocator) maybeProbeWithMedia() {
}
update := NewStreamStateUpdate()
if allocation.pauseReason == VideoPauseReasonBandwidth && track.SetPaused(true) {
if allocation.PauseReason == sfu.VideoPauseReasonBandwidth && track.SetPaused(true) {
update.HandleStreamingChange(true, track)
}
s.maybeSendUpdate(update)
@@ -1186,11 +1188,11 @@ func (s *StreamAllocator) maybeProbeWithPadding() {
// use deficient track farthest from desired layers to find how much to probe
for _, track := range s.getMaxDistanceSortedDeficient() {
transition, available := track.GetNextHigherTransition(FlagAllowOvershootInProbe)
if !available || transition.bandwidthDelta < 0 {
if !available || transition.BandwidthDelta < 0 {
continue
}
probeRateBps := (transition.bandwidthDelta * ProbePct) / 100
probeRateBps := (transition.BandwidthDelta * ProbePct) / 100
if probeRateBps < ProbeMinBps {
probeRateBps = ProbeMinBps
}
@@ -1263,615 +1265,3 @@ func (s *StreamAllocator) getMaxDistanceSortedDeficient() MaxDistanceSorter {
}
// ------------------------------------------------
type StreamState int
const (
StreamStateActive StreamState = iota
StreamStatePaused
)
func (s StreamState) String() string {
switch s {
case StreamStateActive:
return "active"
case StreamStatePaused:
return "paused"
default:
return "unknown"
}
}
type StreamStateInfo struct {
ParticipantID livekit.ParticipantID
TrackID livekit.TrackID
State StreamState
}
type StreamStateUpdate struct {
StreamStates []*StreamStateInfo
}
func NewStreamStateUpdate() *StreamStateUpdate {
return &StreamStateUpdate{}
}
func (s *StreamStateUpdate) HandleStreamingChange(isPaused bool, track *Track) {
if isPaused {
s.StreamStates = append(s.StreamStates, &StreamStateInfo{
ParticipantID: track.PublisherID(),
TrackID: track.ID(),
State: StreamStatePaused,
})
} else {
s.StreamStates = append(s.StreamStates, &StreamStateInfo{
ParticipantID: track.PublisherID(),
TrackID: track.ID(),
State: StreamStateActive,
})
}
}
func (s *StreamStateUpdate) Empty() bool {
return len(s.StreamStates) == 0
}
// ------------------------------------------------
type Track struct {
downTrack *DownTrack
source livekit.TrackSource
isSimulcast bool
priority uint8
publisherID livekit.ParticipantID
logger logger.Logger
maxLayers VideoLayers
totalPackets uint32
totalRepeatedNacks uint32
isDirty bool
isPaused bool
}
func newTrack(
downTrack *DownTrack,
source livekit.TrackSource,
isSimulcast bool,
publisherID livekit.ParticipantID,
logger logger.Logger,
) *Track {
t := &Track{
downTrack: downTrack,
source: source,
isSimulcast: isSimulcast,
publisherID: publisherID,
logger: logger,
isPaused: true,
}
t.SetPriority(0)
t.SetMaxLayers(downTrack.MaxLayers())
return t
}
func (t *Track) SetDirty(isDirty bool) bool {
if t.isDirty == isDirty {
return false
}
t.isDirty = isDirty
return true
}
func (t *Track) SetPaused(isPaused bool) bool {
if t.isPaused == isPaused {
return false
}
t.isPaused = isPaused
return true
}
func (t *Track) SetPriority(priority uint8) bool {
if priority == 0 {
switch t.source {
case livekit.TrackSource_SCREEN_SHARE:
priority = PriorityDefaultScreenshare
default:
priority = PriorityDefaultVideo
}
}
if t.priority == priority {
return false
}
t.priority = priority
return true
}
func (t *Track) Priority() uint8 {
return t.priority
}
func (t *Track) DownTrack() *DownTrack {
return t.downTrack
}
func (t *Track) IsManaged() bool {
return t.source != livekit.TrackSource_SCREEN_SHARE || t.isSimulcast
}
func (t *Track) ID() livekit.TrackID {
return livekit.TrackID(t.downTrack.ID())
}
func (t *Track) PublisherID() livekit.ParticipantID {
return t.publisherID
}
func (t *Track) SetMaxLayers(layers VideoLayers) bool {
if t.maxLayers == layers {
return false
}
t.maxLayers = layers
return true
}
func (t *Track) WritePaddingRTP(bytesToSend int) int {
return t.downTrack.WritePaddingRTP(bytesToSend, false)
}
func (t *Track) AllocateOptimal(allowOvershoot bool) VideoAllocation {
return t.downTrack.AllocateOptimal(allowOvershoot)
}
func (t *Track) ProvisionalAllocatePrepare() {
t.downTrack.ProvisionalAllocatePrepare()
}
func (t *Track) ProvisionalAllocate(availableChannelCapacity int64, layers VideoLayers, allowPause bool, allowOvershoot bool) int64 {
return t.downTrack.ProvisionalAllocate(availableChannelCapacity, layers, allowPause, allowOvershoot)
}
func (t *Track) ProvisionalAllocateGetCooperativeTransition(allowOvershoot bool) VideoTransition {
return t.downTrack.ProvisionalAllocateGetCooperativeTransition(allowOvershoot)
}
func (t *Track) ProvisionalAllocateGetBestWeightedTransition() VideoTransition {
return t.downTrack.ProvisionalAllocateGetBestWeightedTransition()
}
func (t *Track) ProvisionalAllocateCommit() VideoAllocation {
return t.downTrack.ProvisionalAllocateCommit()
}
func (t *Track) AllocateNextHigher(availableChannelCapacity int64, allowOvershoot bool) (VideoAllocation, bool) {
return t.downTrack.AllocateNextHigher(availableChannelCapacity, allowOvershoot)
}
func (t *Track) GetNextHigherTransition(allowOvershoot bool) (VideoTransition, bool) {
return t.downTrack.GetNextHigherTransition(allowOvershoot)
}
func (t *Track) Pause() VideoAllocation {
return t.downTrack.Pause()
}
func (t *Track) IsDeficient() bool {
return t.downTrack.IsDeficient()
}
func (t *Track) BandwidthRequested() int64 {
return t.downTrack.BandwidthRequested()
}
func (t *Track) DistanceToDesired() float64 {
return t.downTrack.DistanceToDesired()
}
func (t *Track) GetNackDelta() (uint32, uint32) {
totalPackets, totalRepeatedNacks := t.downTrack.GetNackStats()
packetDelta := totalPackets - t.totalPackets
t.totalPackets = totalPackets
nackDelta := totalRepeatedNacks - t.totalRepeatedNacks
t.totalRepeatedNacks = totalRepeatedNacks
return packetDelta, nackDelta
}
// ------------------------------------------------
type TrackSorter []*Track
func (t TrackSorter) Len() int {
return len(t)
}
func (t TrackSorter) Swap(i, j int) {
t[i], t[j] = t[j], t[i]
}
func (t TrackSorter) Less(i, j int) bool {
//
// TrackSorter is used to allocate layer-by-layer.
// So, higher priority track should come earlier so that it gets an earlier shot at each layer
//
if t[i].priority != t[j].priority {
return t[i].priority > t[j].priority
}
if t[i].maxLayers.Spatial != t[j].maxLayers.Spatial {
return t[i].maxLayers.Spatial > t[j].maxLayers.Spatial
}
return t[i].maxLayers.Temporal > t[j].maxLayers.Temporal
}
// ------------------------------------------------
type MaxDistanceSorter []*Track
func (m MaxDistanceSorter) Len() int {
return len(m)
}
func (m MaxDistanceSorter) Swap(i, j int) {
m[i], m[j] = m[j], m[i]
}
func (m MaxDistanceSorter) Less(i, j int) bool {
//
// MaxDistanceSorter is used to find a deficient track to use for probing during recovery from congestion.
// So, higher priority track should come earlier so that they have a chance to recover sooner.
//
if m[i].priority != m[j].priority {
return m[i].priority > m[j].priority
}
return m[i].DistanceToDesired() > m[j].DistanceToDesired()
}
// ------------------------------------------------
type MinDistanceSorter []*Track
func (m MinDistanceSorter) Len() int {
return len(m)
}
func (m MinDistanceSorter) Swap(i, j int) {
m[i], m[j] = m[j], m[i]
}
func (m MinDistanceSorter) Less(i, j int) bool {
//
// MinDistanceSorter is used to find excess bandwidth in cooperative allocation.
// So, lower priority track should come earlier so that they contribute bandwidth to higher priority tracks.
//
if m[i].priority != m[j].priority {
return m[i].priority < m[j].priority
}
return m[i].DistanceToDesired() < m[j].DistanceToDesired()
}
// ------------------------------------------------
type ChannelTrend int
const (
ChannelTrendNeutral ChannelTrend = iota
ChannelTrendClearing
ChannelTrendCongesting
)
func (c ChannelTrend) String() string {
switch c {
case ChannelTrendNeutral:
return "NEUTRAL"
case ChannelTrendClearing:
return "CLEARING"
case ChannelTrendCongesting:
return "CONGESTING"
default:
return fmt.Sprintf("%d", int(c))
}
}
type ChannelCongestionReason int
const (
ChannelCongestionReasonNone ChannelCongestionReason = iota
ChannelCongestionReasonEstimate
ChannelCongestionReasonLoss
)
func (c ChannelCongestionReason) String() string {
switch c {
case ChannelCongestionReasonNone:
return "NONE"
case ChannelCongestionReasonEstimate:
return "ESTIMATE"
case ChannelCongestionReasonLoss:
return "LOSS"
default:
return fmt.Sprintf("%d", int(c))
}
}
type ChannelObserverParams struct {
Name string
EstimateRequiredSamples int
EstimateDownwardTrendThreshold float64
EstimateCollapseValues bool
NackWindowMinDuration time.Duration
NackWindowMaxDuration time.Duration
NackRatioThreshold float64
}
type ChannelObserver struct {
params ChannelObserverParams
logger logger.Logger
estimateTrend *TrendDetector
nackWindowStartTime time.Time
packets uint32
repeatedNacks uint32
}
func NewChannelObserver(params ChannelObserverParams, logger logger.Logger) *ChannelObserver {
return &ChannelObserver{
params: params,
logger: logger,
estimateTrend: NewTrendDetector(TrendDetectorParams{
Name: params.Name + "-estimate",
Logger: logger,
RequiredSamples: params.EstimateRequiredSamples,
DownwardTrendThreshold: params.EstimateDownwardTrendThreshold,
CollapseValues: params.EstimateCollapseValues,
}),
}
}
func (c *ChannelObserver) SeedEstimate(estimate int64) {
c.estimateTrend.Seed(estimate)
}
func (c *ChannelObserver) SeedNack(packets uint32, repeatedNacks uint32) {
c.packets = packets
c.repeatedNacks = repeatedNacks
}
func (c *ChannelObserver) AddEstimate(estimate int64) {
c.estimateTrend.AddValue(estimate)
}
func (c *ChannelObserver) AddNack(packets uint32, repeatedNacks uint32) {
if c.params.NackWindowMaxDuration != 0 && !c.nackWindowStartTime.IsZero() && time.Since(c.nackWindowStartTime) > c.params.NackWindowMaxDuration {
c.nackWindowStartTime = time.Time{}
c.packets = 0
c.repeatedNacks = 0
}
//
// Start NACK monitoring window only when a repeated NACK happens.
// This allows locking tightly to when NACKs start happening and
// check if the NACKs keep adding up (potentially a sign of congestion)
// or isolated losses
//
if c.repeatedNacks == 0 && repeatedNacks != 0 {
c.nackWindowStartTime = time.Now()
}
if !c.nackWindowStartTime.IsZero() {
c.packets += packets
c.repeatedNacks += repeatedNacks
}
}
func (c *ChannelObserver) GetLowestEstimate() int64 {
return c.estimateTrend.GetLowest()
}
func (c *ChannelObserver) GetHighestEstimate() int64 {
return c.estimateTrend.GetHighest()
}
func (c *ChannelObserver) GetNackRatio() (uint32, uint32, float64) {
ratio := 0.0
if c.packets != 0 {
ratio = float64(c.repeatedNacks) / float64(c.packets)
if ratio > 1.0 {
ratio = 1.0
}
}
return c.packets, c.repeatedNacks, ratio
}
func (c *ChannelObserver) GetTrend() (ChannelTrend, ChannelCongestionReason) {
estimateDirection := c.estimateTrend.GetDirection()
packets, repeatedNacks, nackRatio := c.GetNackRatio()
switch {
case estimateDirection == TrendDirectionDownward:
c.logger.Debugw(
"stream allocator: channel observer: estimate is trending downward",
"name", c.params.Name,
"estimate", c.estimateTrend.ToString(),
"packets", packets,
"repeatedNacks", repeatedNacks,
"ratio", nackRatio,
)
return ChannelTrendCongesting, ChannelCongestionReasonEstimate
case c.params.NackWindowMinDuration != 0 && !c.nackWindowStartTime.IsZero() && time.Since(c.nackWindowStartTime) > c.params.NackWindowMinDuration && nackRatio > c.params.NackRatioThreshold:
c.logger.Debugw(
"stream allocator: channel observer: high rate of repeated NACKs",
"name", c.params.Name,
"estimate", c.estimateTrend.ToString(),
"packets", packets,
"repeatedNacks", repeatedNacks,
"ratio", nackRatio,
)
return ChannelTrendCongesting, ChannelCongestionReasonLoss
case estimateDirection == TrendDirectionUpward:
return ChannelTrendClearing, ChannelCongestionReasonNone
}
return ChannelTrendNeutral, ChannelCongestionReasonNone
}
// ------------------------------------------------
type TrendDirection int
const (
TrendDirectionNeutral TrendDirection = iota
TrendDirectionUpward
TrendDirectionDownward
)
func (t TrendDirection) String() string {
switch t {
case TrendDirectionNeutral:
return "NEUTRAL"
case TrendDirectionUpward:
return "UPWARD"
case TrendDirectionDownward:
return "DOWNWARD"
default:
return fmt.Sprintf("%d", int(t))
}
}
type TrendDetectorParams struct {
Name string
Logger logger.Logger
RequiredSamples int
DownwardTrendThreshold float64
CollapseValues bool
}
type TrendDetector struct {
params TrendDetectorParams
startTime time.Time
numSamples int
values []int64
lowestValue int64
highestValue int64
direction TrendDirection
}
func NewTrendDetector(params TrendDetectorParams) *TrendDetector {
return &TrendDetector{
params: params,
startTime: time.Now(),
direction: TrendDirectionNeutral,
}
}
func (t *TrendDetector) Seed(value int64) {
if len(t.values) != 0 {
return
}
t.values = append(t.values, value)
}
func (t *TrendDetector) AddValue(value int64) {
t.numSamples++
if t.lowestValue == 0 || value < t.lowestValue {
t.lowestValue = value
}
if value > t.highestValue {
t.highestValue = value
}
// ignore duplicate values
if t.params.CollapseValues && len(t.values) != 0 && t.values[len(t.values)-1] == value {
return
}
if len(t.values) == t.params.RequiredSamples {
t.values = t.values[1:]
}
t.values = append(t.values, value)
t.updateDirection()
}
func (t *TrendDetector) GetLowest() int64 {
return t.lowestValue
}
func (t *TrendDetector) GetHighest() int64 {
return t.highestValue
}
func (t *TrendDetector) GetValues() []int64 {
return t.values
}
func (t *TrendDetector) GetDirection() TrendDirection {
return t.direction
}
func (t *TrendDetector) ToString() string {
now := time.Now()
elapsed := now.Sub(t.startTime).Seconds()
str := fmt.Sprintf("n: %s", t.params.Name)
str += fmt.Sprintf(", t: %+v|%+v|%.2fs", t.startTime.Format(time.UnixDate), now.Format(time.UnixDate), elapsed)
str += fmt.Sprintf(", v: %d|%d|%d|%+v|%.2f", t.numSamples, t.lowestValue, t.highestValue, t.values, kendallsTau(t.values))
return str
}
func (t *TrendDetector) updateDirection() {
if len(t.values) < t.params.RequiredSamples {
t.direction = TrendDirectionNeutral
return
}
// using Kendall's Tau to find trend
kt := kendallsTau(t.values)
t.direction = TrendDirectionNeutral
switch {
case kt > 0:
t.direction = TrendDirectionUpward
case kt < t.params.DownwardTrendThreshold:
t.direction = TrendDirectionDownward
}
}
// ------------------------------------------------
func kendallsTau(values []int64) float64 {
concordantPairs := 0
discordantPairs := 0
for i := 0; i < len(values)-1; i++ {
for j := i + 1; j < len(values); j++ {
if values[i] < values[j] {
concordantPairs++
} else if values[i] > values[j] {
discordantPairs++
}
}
}
if (concordantPairs + discordantPairs) == 0 {
return 0.0
}
return (float64(concordantPairs) - float64(discordantPairs)) / (float64(concordantPairs) + float64(discordantPairs))
}
@@ -0,0 +1,63 @@
package streamallocator
import (
"github.com/livekit/protocol/livekit"
)
// ------------------------------------------------
type StreamState int
const (
StreamStateActive StreamState = iota
StreamStatePaused
)
func (s StreamState) String() string {
switch s {
case StreamStateActive:
return "active"
case StreamStatePaused:
return "paused"
default:
return "unknown"
}
}
// ------------------------------------------------
type StreamStateInfo struct {
ParticipantID livekit.ParticipantID
TrackID livekit.TrackID
State StreamState
}
type StreamStateUpdate struct {
StreamStates []*StreamStateInfo
}
func NewStreamStateUpdate() *StreamStateUpdate {
return &StreamStateUpdate{}
}
func (s *StreamStateUpdate) HandleStreamingChange(isPaused bool, track *Track) {
if isPaused {
s.StreamStates = append(s.StreamStates, &StreamStateInfo{
ParticipantID: track.PublisherID(),
TrackID: track.ID(),
State: StreamStatePaused,
})
} else {
s.StreamStates = append(s.StreamStates, &StreamStateInfo{
ParticipantID: track.PublisherID(),
TrackID: track.ID(),
State: StreamStateActive,
})
}
}
func (s *StreamStateUpdate) Empty() bool {
return len(s.StreamStates) == 0
}
// ------------------------------------------------
+255
View File
@@ -0,0 +1,255 @@
package streamallocator
import (
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
"github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/livekit-server/pkg/sfu/buffer"
)
type Track struct {
downTrack *sfu.DownTrack
source livekit.TrackSource
isSimulcast bool
priority uint8
publisherID livekit.ParticipantID
logger logger.Logger
maxLayers buffer.VideoLayer
totalPackets uint32
totalRepeatedNacks uint32
isDirty bool
isPaused bool
}
func NewTrack(
downTrack *sfu.DownTrack,
source livekit.TrackSource,
isSimulcast bool,
publisherID livekit.ParticipantID,
logger logger.Logger,
) *Track {
t := &Track{
downTrack: downTrack,
source: source,
isSimulcast: isSimulcast,
publisherID: publisherID,
logger: logger,
isPaused: true,
}
t.SetPriority(0)
t.SetMaxLayers(downTrack.MaxLayers())
return t
}
func (t *Track) SetDirty(isDirty bool) bool {
if t.isDirty == isDirty {
return false
}
t.isDirty = isDirty
return true
}
func (t *Track) SetPaused(isPaused bool) bool {
if t.isPaused == isPaused {
return false
}
t.isPaused = isPaused
return true
}
func (t *Track) SetPriority(priority uint8) bool {
if priority == 0 {
switch t.source {
case livekit.TrackSource_SCREEN_SHARE:
priority = PriorityDefaultScreenshare
default:
priority = PriorityDefaultVideo
}
}
if t.priority == priority {
return false
}
t.priority = priority
return true
}
func (t *Track) Priority() uint8 {
return t.priority
}
func (t *Track) DownTrack() *sfu.DownTrack {
return t.downTrack
}
func (t *Track) IsManaged() bool {
return t.source != livekit.TrackSource_SCREEN_SHARE || t.isSimulcast
}
func (t *Track) ID() livekit.TrackID {
return livekit.TrackID(t.downTrack.ID())
}
func (t *Track) PublisherID() livekit.ParticipantID {
return t.publisherID
}
func (t *Track) SetMaxLayers(layers buffer.VideoLayer) bool {
if t.maxLayers == layers {
return false
}
t.maxLayers = layers
return true
}
func (t *Track) WritePaddingRTP(bytesToSend int) int {
return t.downTrack.WritePaddingRTP(bytesToSend, false)
}
func (t *Track) AllocateOptimal(allowOvershoot bool) sfu.VideoAllocation {
return t.downTrack.AllocateOptimal(allowOvershoot)
}
func (t *Track) ProvisionalAllocatePrepare() {
t.downTrack.ProvisionalAllocatePrepare()
}
func (t *Track) ProvisionalAllocate(availableChannelCapacity int64, layers buffer.VideoLayer, allowPause bool, allowOvershoot bool) int64 {
return t.downTrack.ProvisionalAllocate(availableChannelCapacity, layers, allowPause, allowOvershoot)
}
func (t *Track) ProvisionalAllocateGetCooperativeTransition(allowOvershoot bool) sfu.VideoTransition {
return t.downTrack.ProvisionalAllocateGetCooperativeTransition(allowOvershoot)
}
func (t *Track) ProvisionalAllocateGetBestWeightedTransition() sfu.VideoTransition {
return t.downTrack.ProvisionalAllocateGetBestWeightedTransition()
}
func (t *Track) ProvisionalAllocateCommit() sfu.VideoAllocation {
return t.downTrack.ProvisionalAllocateCommit()
}
func (t *Track) AllocateNextHigher(availableChannelCapacity int64, allowOvershoot bool) (sfu.VideoAllocation, bool) {
return t.downTrack.AllocateNextHigher(availableChannelCapacity, allowOvershoot)
}
func (t *Track) GetNextHigherTransition(allowOvershoot bool) (sfu.VideoTransition, bool) {
return t.downTrack.GetNextHigherTransition(allowOvershoot)
}
func (t *Track) Pause() sfu.VideoAllocation {
return t.downTrack.Pause()
}
func (t *Track) IsDeficient() bool {
return t.downTrack.IsDeficient()
}
func (t *Track) BandwidthRequested() int64 {
return t.downTrack.BandwidthRequested()
}
func (t *Track) DistanceToDesired() float64 {
return t.downTrack.DistanceToDesired()
}
func (t *Track) GetNackDelta() (uint32, uint32) {
totalPackets, totalRepeatedNacks := t.downTrack.GetNackStats()
packetDelta := totalPackets - t.totalPackets
t.totalPackets = totalPackets
nackDelta := totalRepeatedNacks - t.totalRepeatedNacks
t.totalRepeatedNacks = totalRepeatedNacks
return packetDelta, nackDelta
}
// ------------------------------------------------
type TrackSorter []*Track
func (t TrackSorter) Len() int {
return len(t)
}
func (t TrackSorter) Swap(i, j int) {
t[i], t[j] = t[j], t[i]
}
func (t TrackSorter) Less(i, j int) bool {
//
// TrackSorter is used to allocate layer-by-layer.
// So, higher priority track should come earlier so that it gets an earlier shot at each layer
//
if t[i].priority != t[j].priority {
return t[i].priority > t[j].priority
}
if t[i].maxLayers.Spatial != t[j].maxLayers.Spatial {
return t[i].maxLayers.Spatial > t[j].maxLayers.Spatial
}
return t[i].maxLayers.Temporal > t[j].maxLayers.Temporal
}
// ------------------------------------------------
type MaxDistanceSorter []*Track
func (m MaxDistanceSorter) Len() int {
return len(m)
}
func (m MaxDistanceSorter) Swap(i, j int) {
m[i], m[j] = m[j], m[i]
}
func (m MaxDistanceSorter) Less(i, j int) bool {
//
// MaxDistanceSorter is used to find a deficient track to use for probing during recovery from congestion.
// So, higher priority track should come earlier so that they have a chance to recover sooner.
//
if m[i].priority != m[j].priority {
return m[i].priority > m[j].priority
}
return m[i].DistanceToDesired() > m[j].DistanceToDesired()
}
// ------------------------------------------------
type MinDistanceSorter []*Track
func (m MinDistanceSorter) Len() int {
return len(m)
}
func (m MinDistanceSorter) Swap(i, j int) {
m[i], m[j] = m[j], m[i]
}
func (m MinDistanceSorter) Less(i, j int) bool {
//
// MinDistanceSorter is used to find excess bandwidth in cooperative allocation.
// So, lower priority track should come earlier so that they contribute bandwidth to higher priority tracks.
//
if m[i].priority != m[j].priority {
return m[i].priority < m[j].priority
}
return m[i].DistanceToDesired() < m[j].DistanceToDesired()
}
// ------------------------------------------------
+157
View File
@@ -0,0 +1,157 @@
package streamallocator
import (
"fmt"
"time"
"github.com/livekit/protocol/logger"
)
// ------------------------------------------------
type TrendDirection int
const (
TrendDirectionNeutral TrendDirection = iota
TrendDirectionUpward
TrendDirectionDownward
)
func (t TrendDirection) String() string {
switch t {
case TrendDirectionNeutral:
return "NEUTRAL"
case TrendDirectionUpward:
return "UPWARD"
case TrendDirectionDownward:
return "DOWNWARD"
default:
return fmt.Sprintf("%d", int(t))
}
}
// ------------------------------------------------
type TrendDetectorParams struct {
Name string
Logger logger.Logger
RequiredSamples int
DownwardTrendThreshold float64
CollapseValues bool
}
type TrendDetector struct {
params TrendDetectorParams
startTime time.Time
numSamples int
values []int64
lowestValue int64
highestValue int64
direction TrendDirection
}
func NewTrendDetector(params TrendDetectorParams) *TrendDetector {
return &TrendDetector{
params: params,
startTime: time.Now(),
direction: TrendDirectionNeutral,
}
}
func (t *TrendDetector) Seed(value int64) {
if len(t.values) != 0 {
return
}
t.values = append(t.values, value)
}
func (t *TrendDetector) AddValue(value int64) {
t.numSamples++
if t.lowestValue == 0 || value < t.lowestValue {
t.lowestValue = value
}
if value > t.highestValue {
t.highestValue = value
}
// ignore duplicate values
if t.params.CollapseValues && len(t.values) != 0 && t.values[len(t.values)-1] == value {
return
}
if len(t.values) == t.params.RequiredSamples {
t.values = t.values[1:]
}
t.values = append(t.values, value)
t.updateDirection()
}
func (t *TrendDetector) GetLowest() int64 {
return t.lowestValue
}
func (t *TrendDetector) GetHighest() int64 {
return t.highestValue
}
func (t *TrendDetector) GetValues() []int64 {
return t.values
}
func (t *TrendDetector) GetDirection() TrendDirection {
return t.direction
}
func (t *TrendDetector) ToString() string {
now := time.Now()
elapsed := now.Sub(t.startTime).Seconds()
str := fmt.Sprintf("n: %s", t.params.Name)
str += fmt.Sprintf(", t: %+v|%+v|%.2fs", t.startTime.Format(time.UnixDate), now.Format(time.UnixDate), elapsed)
str += fmt.Sprintf(", v: %d|%d|%d|%+v|%.2f", t.numSamples, t.lowestValue, t.highestValue, t.values, kendallsTau(t.values))
return str
}
func (t *TrendDetector) updateDirection() {
if len(t.values) < t.params.RequiredSamples {
t.direction = TrendDirectionNeutral
return
}
// using Kendall's Tau to find trend
kt := kendallsTau(t.values)
t.direction = TrendDirectionNeutral
switch {
case kt > 0:
t.direction = TrendDirectionUpward
case kt < t.params.DownwardTrendThreshold:
t.direction = TrendDirectionDownward
}
}
// ------------------------------------------------
func kendallsTau(values []int64) float64 {
concordantPairs := 0
discordantPairs := 0
for i := 0; i < len(values)-1; i++ {
for j := i + 1; j < len(values); j++ {
if values[i] < values[j] {
concordantPairs++
} else if values[i] > values[j] {
discordantPairs++
}
}
}
if (concordantPairs + discordantPairs) == 0 {
return 0.0
}
return (float64(concordantPairs) - float64(discordantPairs)) / (float64(concordantPairs) + float64(discordantPairs))
}
+13 -13
View File
@@ -36,14 +36,14 @@ type StreamTrackerManager struct {
maxPublishedLayer int32
maxTemporalLayerSeen int32
trackers [DefaultMaxLayerSpatial + 1]*streamtracker.StreamTracker
trackers [buffer.DefaultMaxLayerSpatial + 1]*streamtracker.StreamTracker
availableLayers []int32
maxExpectedLayer int32
paused bool
senderReportMu sync.RWMutex
senderReports [DefaultMaxLayerSpatial + 1]*buffer.RTCPSenderReportDataExt
senderReports [buffer.DefaultMaxLayerSpatial + 1]*buffer.RTCPSenderReportDataExt
closed core.Fuse
@@ -61,8 +61,8 @@ func NewStreamTrackerManager(
logger: logger,
trackInfo: trackInfo,
isSVC: isSVC,
maxPublishedLayer: InvalidLayerSpatial,
maxTemporalLayerSeen: InvalidLayerTemporal,
maxPublishedLayer: buffer.InvalidLayerSpatial,
maxTemporalLayerSeen: buffer.InvalidLayerTemporal,
clockRate: clockRate,
closed: core.NewFuse(),
}
@@ -295,12 +295,12 @@ func (s *StreamTrackerManager) DistanceToDesired() float64 {
al, brs := s.getLayeredBitrateLocked()
maxLayers := InvalidLayers
maxLayers := buffer.InvalidLayers
done:
for s := int32(len(brs)) - 1; s >= 0; s-- {
for t := int32(len(brs[0])) - 1; t >= 0; t-- {
if brs[s][t] != 0 {
maxLayers = VideoLayers{
maxLayers = buffer.VideoLayer{
Spatial: s,
Temporal: t,
}
@@ -319,7 +319,7 @@ done:
adjustedMaxLayers := maxLayers
if !maxLayers.IsValid() {
adjustedMaxLayers = VideoLayers{Spatial: 0, Temporal: 0}
adjustedMaxLayers = buffer.VideoLayer{Spatial: 0, Temporal: 0}
}
distance :=
@@ -351,7 +351,7 @@ func (s *StreamTrackerManager) getLayeredBitrateLocked() ([]int32, Bitrates) {
for i, tracker := range s.trackers {
if tracker != nil {
tls := make([]int64, DefaultMaxLayerTemporal+1)
tls := make([]int64, buffer.DefaultMaxLayerTemporal+1)
if s.hasSpatialLayerLocked(int32(i)) {
tls = tracker.BitrateTemporalCumulative()
}
@@ -428,12 +428,12 @@ func (s *StreamTrackerManager) addAvailableLayer(layer int32) {
func (s *StreamTrackerManager) removeAvailableLayer(layer int32) {
s.lock.Lock()
prevMaxLayer := InvalidLayerSpatial
prevMaxLayer := buffer.InvalidLayerSpatial
if len(s.availableLayers) > 0 {
prevMaxLayer = s.availableLayers[len(s.availableLayers)-1]
}
newLayers := make([]int32, 0, DefaultMaxLayerSpatial+1)
newLayers := make([]int32, 0, buffer.DefaultMaxLayerSpatial+1)
for _, l := range s.availableLayers {
if l != layer {
newLayers = append(newLayers, l)
@@ -448,7 +448,7 @@ func (s *StreamTrackerManager) removeAvailableLayer(layer int32) {
"availableLayers", newLayers,
)
curMaxLayer := InvalidLayerSpatial
curMaxLayer := buffer.InvalidLayerSpatial
if len(s.availableLayers) > 0 {
curMaxLayer = s.availableLayers[len(s.availableLayers)-1]
}
@@ -466,7 +466,7 @@ func (s *StreamTrackerManager) removeAvailableLayer(layer int32) {
}
func (s *StreamTrackerManager) maxExpectedLayerFromTrackInfo() {
s.maxExpectedLayer = InvalidLayerSpatial
s.maxExpectedLayer = buffer.InvalidLayerSpatial
for _, layer := range s.trackInfo.Layers {
spatialLayer := buffer.VideoQualityToSpatialLayer(layer.Quality, s.trackInfo)
if spatialLayer > s.maxExpectedLayer {
@@ -547,7 +547,7 @@ func (s *StreamTrackerManager) GetMaxTemporalLayerSeen() int32 {
}
func (s *StreamTrackerManager) updateMaxTemporalLayerSeen(brs Bitrates) {
maxTemporalLayerSeen := InvalidLayerTemporal
maxTemporalLayerSeen := buffer.InvalidLayerTemporal
done:
for t := int32(len(brs[0])) - 1; t >= 0; t-- {
for s := int32(len(brs)) - 1; s >= 0; s-- {
+7 -7
View File
@@ -11,7 +11,7 @@ import (
type targetLayer struct {
Target int
Layer VideoLayers
Layer buffer.VideoLayer
}
type DDVideoLayerSelector struct {
@@ -22,7 +22,7 @@ type DDVideoLayerSelector struct {
// expectKeyFrame bool
decodeTargetLayer []targetLayer
layer VideoLayers
layer buffer.VideoLayer
activeDecodeTargetsBitmask *uint32
structure *dd.FrameDependencyStructure
}
@@ -30,7 +30,7 @@ type DDVideoLayerSelector struct {
func NewDDVideoLayerSelector(logger logger.Logger) *DDVideoLayerSelector {
return &DDVideoLayerSelector{
logger: logger,
layer: VideoLayers{Spatial: 2, Temporal: 2},
layer: buffer.VideoLayer{Spatial: 2, Temporal: 2},
}
}
@@ -48,7 +48,7 @@ func (s *DDVideoLayerSelector) Select(expPkt *buffer.ExtPacket, tp *TranslationP
}
// forward all packets before locking
if s.layer == InvalidLayers {
if s.layer == buffer.InvalidLayers {
return true
}
@@ -122,8 +122,8 @@ func (s *DDVideoLayerSelector) Select(expPkt *buffer.ExtPacket, tp *TranslationP
return true
}
func (s *DDVideoLayerSelector) SelectLayer(layer VideoLayers) {
// layer = VideoLayers{1, 1}
func (s *DDVideoLayerSelector) SelectLayer(layer buffer.VideoLayer) {
// layer = buffer.VideoLayer{1, 1}
s.layer = layer
activeBitMask := uint32(0)
var maxSpatial, maxTemporal int32
@@ -152,7 +152,7 @@ func (s *DDVideoLayerSelector) updateDependencyStructure(structure *dd.FrameDepe
s.decodeTargetLayer = s.decodeTargetLayer[:0]
for target := 0; target < structure.NumDecodeTargets; target++ {
layer := VideoLayers{Spatial: 0, Temporal: 0}
layer := buffer.VideoLayer{Spatial: 0, Temporal: 0}
for _, t := range structure.Templates {
if t.DecodeTargetIndications[target] != dd.DecodeTargetNotPresent {
if layer.Spatial < int32(t.SpatialId) {