downstream allocator (#155)
* WIP branch to hash out down stream allocator. * Plug more bits of stream allocator * update protocol * remove SignalRequest_Simulcast (#154) * Plug more bits of stream allocator * Handle simulcast track available layers change * WIP branch to hash out down stream allocator. * Plug more bits of stream allocator * Handle simulcast track available layers change * Adopt signature of call to AdjustAllocation * Move StreamAllocator to PCTransport and allocate only for subscriber. * Move streamallocator to ion-sfu * Start/Stop of streamallocator * Use StreamAllocator for subscriber bandwidth management. * Do not allocate in ADD_TRACK * Set payload in constructor * - Add some logging - Protocol message to notify clients of paused/resumed streams * named return * oops correct sense of isPausing * Update pkg/sfu/streamallocator.go Committing David's suggestion. Co-authored-by: David Zhao <david@davidzhao.com> * - Log estimate changes/commits. - Catch more than epsilon change oscillating for long time. Co-authored-by: David Colburn <xero73@gmail.com> Co-authored-by: David Zhao <david@davidzhao.com>
This commit is contained in:
co-authored by
David Colburn
David Zhao
parent
9aff9af690
commit
98695cdd22
+4
-16
@@ -293,7 +293,7 @@ func (t *MediaTrack) AddSubscriber(sub types.Participant) error {
|
||||
t.subscribedTracks[sub.ID()] = subTrack
|
||||
subTrack.SetPublisherMuted(t.IsMuted())
|
||||
|
||||
t.receiver.AddDownTrack(downTrack, t.shouldStartWithBestQuality())
|
||||
t.receiver.AddDownTrack(downTrack)
|
||||
// since sub will lock, run it in a goroutine to avoid deadlocks
|
||||
go func() {
|
||||
sub.AddSubscribedTrack(subTrack)
|
||||
@@ -306,16 +306,10 @@ func (t *MediaTrack) AddSubscriber(sub types.Participant) error {
|
||||
|
||||
func (t *MediaTrack) NumUpTracks() (uint32, uint32) {
|
||||
numRegistered := atomic.LoadUint32(&t.numUpTracks)
|
||||
numPublishing := uint32(0)
|
||||
var numPublishing uint32
|
||||
if t.simulcasted.Get() {
|
||||
t.lock.RLock()
|
||||
if t.receiver != nil {
|
||||
for i := int32(0); i < 3; i++ {
|
||||
if t.receiver.HasSpatialLayer(i) {
|
||||
numPublishing += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
numPublishing = uint32(t.receiver.NumAvailableSpatialLayers())
|
||||
t.lock.RUnlock()
|
||||
} else {
|
||||
numPublishing = 1
|
||||
@@ -392,7 +386,7 @@ func (t *MediaTrack) AddReceiver(receiver *webrtc.RTPReceiver, track *webrtc.Tra
|
||||
}
|
||||
}
|
||||
|
||||
t.receiver.AddUpTrack(track, buff, t.shouldStartWithBestQuality())
|
||||
t.receiver.AddUpTrack(track, buff)
|
||||
t.params.Telemetry.AddUpTrack(t.params.ParticipantID, buff)
|
||||
|
||||
atomic.AddUint32(&t.numUpTracks, 1)
|
||||
@@ -463,12 +457,6 @@ func (t *MediaTrack) GetQualityForDimension(width, height uint32) livekit.VideoQ
|
||||
return quality
|
||||
}
|
||||
|
||||
// LK-TODO: this should probably left up to auto size management and StreamAllocator
|
||||
// this function assumes caller holds lock
|
||||
func (t *MediaTrack) shouldStartWithBestQuality() bool {
|
||||
return len(t.subscribedTracks) < 10
|
||||
}
|
||||
|
||||
// TODO: send for all downtracks from the source participant
|
||||
// https://tools.ietf.org/html/rfc7941
|
||||
func (t *MediaTrack) sendDownTrackBindingReports(sub types.Participant) {
|
||||
|
||||
@@ -180,6 +180,8 @@ func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) {
|
||||
|
||||
p.subscriber.OnOffer(p.onOffer)
|
||||
|
||||
p.subscriber.OnStreamedTracksChange(p.onStreamedTracksChange)
|
||||
|
||||
return p, nil
|
||||
}
|
||||
|
||||
@@ -804,6 +806,8 @@ func (p *ParticipantImpl) AddSubscribedTrack(subTrack types.SubscribedTrack) {
|
||||
p.lock.Lock()
|
||||
p.subscribedTracks[subTrack.ID()] = subTrack
|
||||
p.lock.Unlock()
|
||||
|
||||
p.subscriber.AddTrack(subTrack)
|
||||
p.subscribedTo.Store(subTrack.PublisherIdentity(), struct{}{})
|
||||
}
|
||||
|
||||
@@ -811,6 +815,9 @@ func (p *ParticipantImpl) AddSubscribedTrack(subTrack types.SubscribedTrack) {
|
||||
func (p *ParticipantImpl) RemoveSubscribedTrack(subTrack types.SubscribedTrack) {
|
||||
p.params.Logger.Debugw("removed subscribedTrack", "publisher", subTrack.PublisherIdentity(),
|
||||
"participant", p.Identity(), "track", subTrack.ID(), "kind", subTrack.DownTrack().Kind())
|
||||
|
||||
p.subscriber.RemoveTrack(subTrack)
|
||||
|
||||
p.lock.Lock()
|
||||
delete(p.subscribedTracks, subTrack.ID())
|
||||
// remove from subscribed map
|
||||
@@ -1307,6 +1314,40 @@ func (p *ParticipantImpl) configureReceiverDTX() {
|
||||
}
|
||||
}
|
||||
|
||||
func (p *ParticipantImpl) onStreamedTracksChange(paused map[string][]string, resumed map[string][]string) error {
|
||||
if len(paused) == 0 && len(resumed) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
streamedTracksUpdate := &livekit.StreamedTracksUpdate{}
|
||||
if len(paused) != 0 {
|
||||
for participantId, trackIds := range paused {
|
||||
for _, trackId := range trackIds {
|
||||
streamedTracksUpdate.Paused = append(streamedTracksUpdate.Paused, &livekit.StreamedTrack{
|
||||
ParticipantSid: participantId,
|
||||
TrackSid: trackId,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(resumed) != 0 {
|
||||
for participantId, trackIds := range paused {
|
||||
for _, trackId := range trackIds {
|
||||
streamedTracksUpdate.Resumed = append(streamedTracksUpdate.Resumed, &livekit.StreamedTrack{
|
||||
ParticipantSid: participantId,
|
||||
TrackSid: trackId,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return p.writeMessage(&livekit.SignalResponse{
|
||||
Message: &livekit.SignalResponse_StreamedTracksUpdate{
|
||||
StreamedTracksUpdate: streamedTracksUpdate,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (p *ParticipantImpl) DebugInfo() map[string]interface{} {
|
||||
info := map[string]interface{}{
|
||||
"ID": p.id,
|
||||
|
||||
@@ -62,18 +62,7 @@ func (t *SubscribedTrack) UpdateSubscriberSettings(enabled bool, quality livekit
|
||||
t.subMuted.TrySet(!enabled)
|
||||
t.updateDownTrackMute()
|
||||
if enabled && t.dt.Kind() == webrtc.RTPCodecTypeVideo {
|
||||
err := t.dt.SetMaxSpatialLayer(spatialLayerForQuality(quality))
|
||||
// LK-TODO-START
|
||||
// For now, this set max calls into switchSpatialLayer and returns the result.
|
||||
// When StreamAllocator becomes the one true way to allocate layers,
|
||||
// there will not a ErrSpatialLayerNotFound error as the allocation
|
||||
// logic will automatically the best available layer under the max layer.
|
||||
// So, this check should be removed when enabling StreamAllocator
|
||||
// LK-TODO-END
|
||||
if err == sfu.ErrSpatialLayerNotFound && quality != livekit.VideoQuality_MEDIUM {
|
||||
// try to switch to middle layer
|
||||
_ = t.dt.SetMaxSpatialLayer(spatialLayerForQuality(livekit.VideoQuality_MEDIUM))
|
||||
}
|
||||
t.dt.SetMaxSpatialLayer(spatialLayerForQuality(quality))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+42
-1
@@ -10,6 +10,8 @@ import (
|
||||
"github.com/pion/interceptor"
|
||||
"github.com/pion/webrtc/v3"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/rtc/types"
|
||||
"github.com/livekit/livekit-server/pkg/sfu"
|
||||
"github.com/livekit/livekit-server/pkg/telemetry"
|
||||
"github.com/livekit/livekit-server/pkg/telemetry/prometheus"
|
||||
)
|
||||
@@ -37,7 +39,11 @@ type PCTransport struct {
|
||||
onOffer func(offer webrtc.SessionDescription)
|
||||
restartAfterGathering bool
|
||||
negotiationState int
|
||||
logger logger.Logger
|
||||
|
||||
// stream allocator for subscriber PC
|
||||
streamAllocator *sfu.StreamAllocator
|
||||
|
||||
logger logger.Logger
|
||||
}
|
||||
|
||||
type TransportParams struct {
|
||||
@@ -92,6 +98,13 @@ func NewPCTransport(params TransportParams) (*PCTransport, error) {
|
||||
negotiationState: negotiationStateNone,
|
||||
logger: params.Logger,
|
||||
}
|
||||
if params.Target == livekit.SignalTarget_SUBSCRIBER {
|
||||
t.streamAllocator = sfu.NewStreamAllocator(sfu.StreamAllocatorParams{
|
||||
ParticipantID: params.ParticipantID,
|
||||
Logger: params.Logger,
|
||||
})
|
||||
t.streamAllocator.Start()
|
||||
}
|
||||
t.pc.OnICEGatheringStateChange(func(state webrtc.ICEGathererState) {
|
||||
if state == webrtc.ICEGathererStateComplete {
|
||||
go func() {
|
||||
@@ -126,6 +139,10 @@ func (t *PCTransport) PeerConnection() *webrtc.PeerConnection {
|
||||
}
|
||||
|
||||
func (t *PCTransport) Close() {
|
||||
if t.streamAllocator != nil {
|
||||
t.streamAllocator.Stop()
|
||||
}
|
||||
|
||||
_ = t.pc.Close()
|
||||
}
|
||||
|
||||
@@ -238,3 +255,27 @@ func (t *PCTransport) createAndSendOffer(options *webrtc.OfferOptions) error {
|
||||
go t.onOffer(offer)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *PCTransport) OnStreamedTracksChange(f func(paused map[string][]string, resumed map[string][]string) error) {
|
||||
if t.streamAllocator == nil {
|
||||
return
|
||||
}
|
||||
|
||||
t.streamAllocator.OnStreamedTracksChange(f)
|
||||
}
|
||||
|
||||
func (t *PCTransport) AddTrack(subTrack types.SubscribedTrack) {
|
||||
if t.streamAllocator == nil {
|
||||
return
|
||||
}
|
||||
|
||||
t.streamAllocator.AddTrack(subTrack.DownTrack(), subTrack.PublisherIdentity())
|
||||
}
|
||||
|
||||
func (t *PCTransport) RemoveTrack(subTrack types.SubscribedTrack) {
|
||||
if t.streamAllocator == nil {
|
||||
return
|
||||
}
|
||||
|
||||
t.streamAllocator.RemoveTrack(subTrack.DownTrack())
|
||||
}
|
||||
|
||||
+13
-36
@@ -68,7 +68,6 @@ type Buffer struct {
|
||||
|
||||
minPacketProbe int
|
||||
lastPacketRead int
|
||||
maxTemporalLayer int32
|
||||
bitrate atomic.Value
|
||||
bitrateHelper [4]uint64
|
||||
lastSRNTPTime uint64
|
||||
@@ -345,18 +344,18 @@ func (b *Buffer) calc(pkt []byte, arrivalTime int64) {
|
||||
}
|
||||
|
||||
if b.minPacketProbe < 25 {
|
||||
// LK-TODO-START
|
||||
// This should check for proper wrap around.
|
||||
// Probably remove this probe section of code as
|
||||
// the only place this baseSN is used at is where
|
||||
// RTCP receiver reports are generated. If there
|
||||
// are some out-of-order packets right at the start
|
||||
// the stat is going to be off by a bit. Not a big deal.
|
||||
// LK-TODO-END
|
||||
if sn < b.baseSN {
|
||||
b.baseSN = sn
|
||||
}
|
||||
|
||||
if b.mime == "video/vp8" {
|
||||
pld := ep.Payload.(VP8)
|
||||
mtl := atomic.LoadInt32(&b.maxTemporalLayer)
|
||||
if mtl < int32(pld.TID) {
|
||||
atomic.StoreInt32(&b.maxTemporalLayer, int32(pld.TID))
|
||||
}
|
||||
}
|
||||
|
||||
b.minPacketProbe++
|
||||
}
|
||||
|
||||
@@ -403,16 +402,12 @@ func (b *Buffer) calc(pkt []byte, arrivalTime int64) {
|
||||
|
||||
diff := arrivalTime - b.lastReport
|
||||
if diff >= reportDelta {
|
||||
// LK-TODO-START
|
||||
//
|
||||
// As this happens in the data path, if there are no packets received
|
||||
// in an interval, the bitrate is stuck with the old value. GetBitrate()
|
||||
// method in sfu.Receiver uses the availableLayers set by stream
|
||||
// tracker to report 0 bitrate if a layer is not available. But, stream
|
||||
// tracker is not run for the lowest layer. So, if the lowest layer stops,
|
||||
// stale bitrate will be reported. The simplest thing might be to run the
|
||||
// stream tracker on all layers to address this. Another option to look at
|
||||
// is some monitoring loop running at low frequency and reporting bitrate.
|
||||
// LK-TODO-END
|
||||
// in an interval, the bitrate will be stuck with the old value.
|
||||
// GetBitrate() method in sfu.Receiver uses the availableLayers
|
||||
// set by stream tracker to report 0 bitrate if a layer is not available.
|
||||
//
|
||||
bitrates, ok := b.bitrate.Load().([]uint64)
|
||||
if !ok {
|
||||
bitrates = make([]uint64, len(b.bitrateHelper))
|
||||
@@ -561,20 +556,6 @@ func (b *Buffer) Bitrate() uint64 {
|
||||
return bitrate
|
||||
}
|
||||
|
||||
// BitrateTemporal returns the current publisher stream bitrate temporal layer wise.
|
||||
func (b *Buffer) BitrateTemporal() []uint64 {
|
||||
bitrates, ok := b.bitrate.Load().([]uint64)
|
||||
if !ok {
|
||||
return make([]uint64, len(b.bitrateHelper))
|
||||
}
|
||||
|
||||
// copy and return
|
||||
brs := make([]uint64, len(bitrates))
|
||||
copy(brs, bitrates)
|
||||
|
||||
return brs
|
||||
}
|
||||
|
||||
// BitrateTemporalCumulative returns the current publisher stream bitrate temporal layer accumulated with lower temporal layers.
|
||||
func (b *Buffer) BitrateTemporalCumulative() []uint64 {
|
||||
bitrates, ok := b.bitrate.Load().([]uint64)
|
||||
@@ -597,10 +578,6 @@ func (b *Buffer) BitrateTemporalCumulative() []uint64 {
|
||||
return brs
|
||||
}
|
||||
|
||||
func (b *Buffer) MaxTemporalLayer() int32 {
|
||||
return atomic.LoadInt32(&b.maxTemporalLayer)
|
||||
}
|
||||
|
||||
func (b *Buffer) OnTransportWideCC(fn func(sn uint16, timeNS int64, marker bool)) {
|
||||
b.feedbackTWCC = fn
|
||||
}
|
||||
|
||||
+39
-91
@@ -163,6 +163,7 @@ func NewDownTrack(c webrtc.RTPCodecCapability, r Receiver, bf *buffer.Factory, p
|
||||
|
||||
if strings.ToLower(c.MimeType) == "video/vp8" {
|
||||
d.vp8Munger = NewVP8Munger()
|
||||
d.payload = packetFactory.Get().(*[]byte)
|
||||
}
|
||||
|
||||
if d.Kind() == webrtc.RTPCodecTypeVideo {
|
||||
@@ -176,6 +177,14 @@ func NewDownTrack(c webrtc.RTPCodecCapability, r Receiver, bf *buffer.Factory, p
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (d *DownTrack) SetTrackType(isSimulcast bool) {
|
||||
if isSimulcast {
|
||||
d.trackType = SimulcastDownTrack
|
||||
} else {
|
||||
d.trackType = SimpleDownTrack
|
||||
}
|
||||
}
|
||||
|
||||
// Bind is called by the PeerConnection after negotiation is complete
|
||||
// This asserts that the code requested is supported by the remote peer.
|
||||
// If so it setups all the state (SSRC and PayloadType) to have a call
|
||||
@@ -268,7 +277,7 @@ func (d *DownTrack) MaybeTranslateVP8(pkt *rtp.Packet, meta packetMeta) error {
|
||||
}
|
||||
|
||||
translatedVP8 := meta.unpackVP8()
|
||||
payload, err := d.translateVP8Packet(pkt, &incomingVP8, translatedVP8)
|
||||
payload, err := d.translateVP8Packet(pkt, &incomingVP8, translatedVP8, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -470,12 +479,6 @@ func (d *DownTrack) Close() {
|
||||
})
|
||||
}
|
||||
|
||||
func (d *DownTrack) SetInitialLayers(spatialLayer, temporalLayer int32) {
|
||||
d.currentSpatialLayer.set(spatialLayer)
|
||||
d.targetSpatialLayer.set(spatialLayer)
|
||||
d.temporalLayer.set((temporalLayer << 16) | temporalLayer)
|
||||
}
|
||||
|
||||
func (d *DownTrack) CurrentSpatialLayer() int32 {
|
||||
return d.currentSpatialLayer.get()
|
||||
}
|
||||
@@ -500,8 +503,7 @@ func (d *DownTrack) SetMaxSpatialLayer(spatialLayer int32) error {
|
||||
d.onSubscribedLayersChanged(d, spatialLayer, d.MaxTemporalLayer())
|
||||
}
|
||||
|
||||
// LK-TODO: Remove the following when StreamAllocator is the default way
|
||||
return d.switchSpatialLayer(spatialLayer)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DownTrack) MaxSpatialLayer() int32 {
|
||||
@@ -529,9 +531,7 @@ func (d *DownTrack) switchSpatialLayer(targetLayer int32) error {
|
||||
if d.trackType != SimulcastDownTrack {
|
||||
return ErrSpatialNotSupported
|
||||
}
|
||||
if !d.receiver.HasSpatialLayer(targetLayer) {
|
||||
return ErrSpatialLayerNotFound
|
||||
}
|
||||
|
||||
// already set
|
||||
if d.CurrentSpatialLayer() == targetLayer {
|
||||
return nil
|
||||
@@ -647,13 +647,18 @@ func (d *DownTrack) OnPacketSent(fn func(dt *DownTrack, size int)) {
|
||||
d.onPacketSent = append(d.onPacketSent, fn)
|
||||
}
|
||||
|
||||
func (d *DownTrack) AdjustAllocation(availableChannelCapacity uint64) (uint64, uint64) {
|
||||
func (d *DownTrack) AdjustAllocation(availableChannelCapacity uint64) (isPausing, isResuming bool, bandwidthRequested, optimalBandwidthNeeded uint64) {
|
||||
isPausing = false
|
||||
isResuming = false
|
||||
bandwidthRequested = 0
|
||||
optimalBandwidthNeeded = 0
|
||||
|
||||
if d.Kind() == webrtc.RTPCodecTypeAudio || !d.enabled.get() {
|
||||
return 0, 0
|
||||
return
|
||||
}
|
||||
|
||||
// LK-TODO for temporal preference, traverse the bitrates array the other way
|
||||
optimalBandwidthNeeded := uint64(0)
|
||||
optimalBandwidthNeeded = uint64(0)
|
||||
brs := d.receiver.GetBitrateTemporalCumulative()
|
||||
for i := d.maxSpatialLayer.get(); i >= 0; i-- {
|
||||
for j := d.maxTemporalLayer.get(); j >= 0; j-- {
|
||||
@@ -664,21 +669,22 @@ func (d *DownTrack) AdjustAllocation(availableChannelCapacity uint64) (uint64, u
|
||||
optimalBandwidthNeeded = brs[i][j]
|
||||
}
|
||||
if brs[i][j] < availableChannelCapacity {
|
||||
isResuming = d.bandwidthConstrainedMuted.get()
|
||||
bandwidthRequested = brs[i][j]
|
||||
|
||||
d.bandwidthConstrainedMute(false) // just in case it was muted
|
||||
d.switchSpatialLayer(int32(i))
|
||||
d.switchTemporalLayer(int32(j))
|
||||
|
||||
return brs[i][j], optimalBandwidthNeeded
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// no layer fits in the available channel capacity, disable the track
|
||||
// LK-TODO - this should fire some callback to notify an observer that a
|
||||
// track has been disabled/muted due to bandwidth constraints
|
||||
isPausing = !d.bandwidthConstrainedMuted.get()
|
||||
d.bandwidthConstrainedMute(true)
|
||||
|
||||
return 0, optimalBandwidthNeeded
|
||||
return
|
||||
}
|
||||
|
||||
func (d *DownTrack) IncreaseAllocation() (bool, uint64, uint64) {
|
||||
@@ -901,7 +907,7 @@ func (d *DownTrack) writeSimpleRTP(extPkt *buffer.ExtPacket) error {
|
||||
return ErrNotVP8
|
||||
}
|
||||
|
||||
payload, err = d.translateVP8Packet(&extPkt.Packet, &incomingVP8, translatedVP8)
|
||||
payload, err = d.translateVP8Packet(&extPkt.Packet, &incomingVP8, translatedVP8, ordering != SequenceNumberOrderingOutOfOrder)
|
||||
if err != nil {
|
||||
d.pktsDropped.add(1)
|
||||
return err
|
||||
@@ -1089,7 +1095,7 @@ func (d *DownTrack) writeSimulcastRTP(extPkt *buffer.ExtPacket, layer int32) err
|
||||
return ErrNotVP8
|
||||
}
|
||||
|
||||
payload, err = d.translateVP8Packet(&extPkt.Packet, &incomingVP8, translatedVP8)
|
||||
payload, err = d.translateVP8Packet(&extPkt.Packet, &incomingVP8, translatedVP8, ordering != SequenceNumberOrderingOutOfOrder)
|
||||
if err != nil {
|
||||
d.pktsDropped.add(1)
|
||||
return err
|
||||
@@ -1259,8 +1265,7 @@ func (d *DownTrack) handleRTCP(bytes []byte) {
|
||||
firOnce := true
|
||||
|
||||
var (
|
||||
maxRatePacketLoss uint8
|
||||
expectedMinBitrate uint64
|
||||
maxRatePacketLoss uint8
|
||||
)
|
||||
|
||||
ssrc := d.lastSSRC.get()
|
||||
@@ -1286,13 +1291,6 @@ func (d *DownTrack) handleRTCP(bytes []byte) {
|
||||
firOnce = false
|
||||
}
|
||||
case *rtcp.ReceiverEstimatedMaximumBitrate:
|
||||
// LK-TODO-START
|
||||
// Remove expectedMinBitrate calculation when switching code
|
||||
// to StreamAllocator based layer control
|
||||
// LK-TODO-END
|
||||
if expectedMinBitrate == 0 || expectedMinBitrate > uint64(p.Bitrate) {
|
||||
expectedMinBitrate = uint64(p.Bitrate)
|
||||
}
|
||||
if d.onREMB != nil {
|
||||
d.onREMB(d, p)
|
||||
}
|
||||
@@ -1330,75 +1328,25 @@ func (d *DownTrack) handleRTCP(bytes []byte) {
|
||||
}
|
||||
}
|
||||
|
||||
// LK-TODO: Remove when switching to StreamAllocator based layer control
|
||||
if d.trackType == SimulcastDownTrack && (maxRatePacketLoss != 0 || expectedMinBitrate != 0) {
|
||||
d.handleLayerChange(maxRatePacketLoss, expectedMinBitrate)
|
||||
}
|
||||
|
||||
if len(fwdPkts) > 0 {
|
||||
d.receiver.SendRTCP(fwdPkts)
|
||||
}
|
||||
}
|
||||
|
||||
// LK-TODO: Remove when switching to StreamAllocator based layer control
|
||||
func (d *DownTrack) handleLayerChange(maxRatePacketLoss uint8, expectedMinBitrate uint64) {
|
||||
currentSpatialLayer := d.CurrentSpatialLayer()
|
||||
targetSpatialLayer := d.TargetSpatialLayer()
|
||||
|
||||
temporalLayer := d.temporalLayer.get()
|
||||
currentTemporalLayer := temporalLayer & 0x0f
|
||||
targetTemporalLayer := temporalLayer >> 16
|
||||
|
||||
if targetSpatialLayer == currentSpatialLayer && currentTemporalLayer == targetTemporalLayer {
|
||||
if time.Now().After(d.simulcast.switchDelay) {
|
||||
brs := d.receiver.GetBitrate()
|
||||
cbr := brs[currentSpatialLayer]
|
||||
mtl := d.receiver.GetMaxTemporalLayer()
|
||||
mctl := mtl[currentSpatialLayer]
|
||||
|
||||
if maxRatePacketLoss <= 5 {
|
||||
if currentTemporalLayer < mctl && currentTemporalLayer+1 <= d.maxTemporalLayer.get() &&
|
||||
expectedMinBitrate >= 3*cbr/4 {
|
||||
d.switchTemporalLayer(currentTemporalLayer + 1)
|
||||
d.simulcast.switchDelay = time.Now().Add(3 * time.Second)
|
||||
}
|
||||
if currentTemporalLayer >= mctl && expectedMinBitrate >= 3*cbr/2 && currentSpatialLayer+1 <= d.maxSpatialLayer.get() &&
|
||||
currentSpatialLayer+1 <= 2 {
|
||||
if err := d.switchSpatialLayer(currentSpatialLayer + 1); err == nil {
|
||||
d.switchTemporalLayer(0)
|
||||
}
|
||||
d.simulcast.switchDelay = time.Now().Add(5 * time.Second)
|
||||
}
|
||||
}
|
||||
if maxRatePacketLoss >= 25 {
|
||||
if (expectedMinBitrate <= 5*cbr/8 || currentTemporalLayer == 0) &&
|
||||
currentSpatialLayer > 0 &&
|
||||
brs[currentSpatialLayer-1] != 0 {
|
||||
if err := d.switchSpatialLayer(currentSpatialLayer - 1); err != nil {
|
||||
d.switchTemporalLayer(mtl[currentSpatialLayer-1])
|
||||
}
|
||||
d.simulcast.switchDelay = time.Now().Add(10 * time.Second)
|
||||
} else {
|
||||
d.switchTemporalLayer(currentTemporalLayer - 1)
|
||||
d.simulcast.switchDelay = time.Now().Add(5 * time.Second)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *DownTrack) getSRStats() (octets, packets uint32) {
|
||||
return d.octetCount.get(), d.packetCount.get()
|
||||
}
|
||||
|
||||
func (d *DownTrack) translateVP8Packet(pkt *rtp.Packet, incomingVP8 *buffer.VP8, translatedVP8 *buffer.VP8) (buf []byte, err error) {
|
||||
temporalLayer := d.temporalLayer.get()
|
||||
currentLayer := uint16(temporalLayer)
|
||||
currentTargetLayer := uint16(temporalLayer >> 16)
|
||||
// catch up temporal layer if necessary
|
||||
if currentTargetLayer != currentLayer {
|
||||
if incomingVP8.TIDPresent == 1 && incomingVP8.TID <= uint8(currentTargetLayer) {
|
||||
d.temporalLayer.set(int32(currentTargetLayer)<<16 | int32(currentTargetLayer))
|
||||
func (d *DownTrack) translateVP8Packet(pkt *rtp.Packet, incomingVP8 *buffer.VP8, translatedVP8 *buffer.VP8, adjustTemporal bool) (buf []byte, err error) {
|
||||
if adjustTemporal {
|
||||
temporalLayer := d.temporalLayer.get()
|
||||
currentLayer := uint16(temporalLayer)
|
||||
currentTargetLayer := uint16(temporalLayer >> 16)
|
||||
// catch up temporal layer if necessary
|
||||
if currentTargetLayer != currentLayer {
|
||||
if incomingVP8.TIDPresent == 1 && incomingVP8.TID <= uint8(currentTargetLayer) {
|
||||
d.temporalLayer.set(int32(currentTargetLayer)<<16 | int32(currentTargetLayer))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+42
-6
@@ -107,13 +107,24 @@
|
||||
package sfu
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gammazero/deque"
|
||||
|
||||
"github.com/livekit/protocol/logger"
|
||||
)
|
||||
|
||||
type ProberParams struct {
|
||||
ParticipantID string
|
||||
Logger logger.Logger
|
||||
}
|
||||
|
||||
type Prober struct {
|
||||
participantID string
|
||||
logger logger.Logger
|
||||
|
||||
clustersMu sync.RWMutex
|
||||
clusters deque.Deque
|
||||
activeCluster *Cluster
|
||||
@@ -121,8 +132,11 @@ type Prober struct {
|
||||
onSendProbe func(bytesToSend int) int
|
||||
}
|
||||
|
||||
func NewProber() *Prober {
|
||||
p := &Prober{}
|
||||
func NewProber(params ProberParams) *Prober {
|
||||
p := &Prober{
|
||||
participantID: params.ParticipantID,
|
||||
logger: params.Logger,
|
||||
}
|
||||
p.clusters.SetMinCapacity(2)
|
||||
return p
|
||||
}
|
||||
@@ -136,9 +150,14 @@ func (p *Prober) IsRunning() bool {
|
||||
|
||||
func (p *Prober) Reset() {
|
||||
p.clustersMu.Lock()
|
||||
// LK-TODO - log if active cluster is getting reset, maybe log state of all clusters
|
||||
defer p.clustersMu.Unlock()
|
||||
|
||||
if p.activeCluster != nil {
|
||||
p.logger.Debugw("resetting active cluster", "participant", p.participantID, "cluster", p.activeCluster.String())
|
||||
}
|
||||
|
||||
p.clusters.Clear()
|
||||
p.activeCluster = nil
|
||||
}
|
||||
|
||||
func (p *Prober) OnSendProbe(f func(bytesToSend int) int) {
|
||||
@@ -151,7 +170,7 @@ func (p *Prober) AddCluster(desiredRateBps int, expectedRateBps int, minDuration
|
||||
}
|
||||
|
||||
cluster := NewCluster(desiredRateBps, expectedRateBps, minDuration, maxDuration)
|
||||
// LK-TODO - log information about added cluster
|
||||
p.logger.Debugw("cluster added", "participant", p.participantID, "cluster", cluster.String())
|
||||
|
||||
p.pushBackClusterAndMaybeStart(cluster)
|
||||
}
|
||||
@@ -228,12 +247,15 @@ func (p *Prober) run() {
|
||||
}
|
||||
|
||||
if !cluster.Process(p) {
|
||||
p.logger.Debugw("cluster finished", "participant", p.participantID, "cluster", cluster.String())
|
||||
p.popFrontCluster(cluster)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//---------------------------------
|
||||
|
||||
type Cluster struct {
|
||||
// LK-TODO-START
|
||||
// Check if we can operate at cluster level without a lock.
|
||||
@@ -300,7 +322,6 @@ func (c *Cluster) Process(p *Prober) bool {
|
||||
// if already past deadline, end the cluster
|
||||
timeElapsed := time.Since(c.startTime)
|
||||
if timeElapsed > c.maxDuration {
|
||||
// LK-TODO log information about short fall in probing
|
||||
c.lock.RUnlock()
|
||||
return false
|
||||
}
|
||||
@@ -341,7 +362,6 @@ func (c *Cluster) Process(p *Prober) bool {
|
||||
// do not end cluster until minDuration elapses even if rate is achieved.
|
||||
// Ensures that the next cluster (if any) does not start early.
|
||||
if (c.bytesSentProbe+c.bytesSentNonProbe) >= c.desiredBytes && timeElapsed >= c.minDuration {
|
||||
// LK-TODO - log data about how much time the probe finished compared to min/max
|
||||
c.lock.Unlock()
|
||||
return false
|
||||
}
|
||||
@@ -350,3 +370,19 @@ func (c *Cluster) Process(p *Prober) bool {
|
||||
c.lock.Unlock()
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *Cluster) String() string {
|
||||
activeTimeMs := time.Duration(0)
|
||||
if !c.startTime.IsZero() {
|
||||
activeTimeMs = time.Since(c.startTime) * time.Millisecond
|
||||
}
|
||||
|
||||
return fmt.Sprintf("bytes: desired %d / probe %d / non-probe %d / remaining: %d, time(ms): active %d / min %d / max %d",
|
||||
c.desiredBytes,
|
||||
c.bytesSentProbe,
|
||||
c.bytesSentNonProbe,
|
||||
c.desiredBytes-c.bytesSentProbe-c.bytesSentNonProbe,
|
||||
activeTimeMs,
|
||||
c.minDuration*time.Millisecond,
|
||||
c.maxDuration*time.Millisecond)
|
||||
}
|
||||
|
||||
+67
-120
@@ -25,14 +25,11 @@ type Receiver interface {
|
||||
Kind() webrtc.RTPCodecType
|
||||
SSRC(layer int) uint32
|
||||
SetTrackMeta(trackID, streamID string)
|
||||
AddUpTrack(track *webrtc.TrackRemote, buffer *buffer.Buffer, bestQualityFirst bool)
|
||||
AddDownTrack(track *DownTrack, bestQualityFirst bool)
|
||||
AddUpTrack(track *webrtc.TrackRemote, buffer *buffer.Buffer)
|
||||
AddDownTrack(track *DownTrack)
|
||||
SetUpTrackPaused(paused bool)
|
||||
HasSpatialLayer(layer int32) bool
|
||||
GetBitrate() [3]uint64
|
||||
GetBitrateTemporal() [3][4]uint64
|
||||
NumAvailableSpatialLayers() int
|
||||
GetBitrateTemporalCumulative() [3][4]uint64
|
||||
GetMaxTemporalLayer() [3]int32
|
||||
RetransmitPackets(track *DownTrack, packets []packetMeta) error
|
||||
DeleteDownTrack(peerID string)
|
||||
OnCloseHandler(fn func())
|
||||
@@ -48,6 +45,10 @@ const (
|
||||
lostUpdateDelta = 1e9
|
||||
)
|
||||
|
||||
var (
|
||||
defaultBitratesCumulative = [][]uint64{{60000, 90000, 150000, 0}, {200000, 300000, 500000, 0}, {400000, 600000, 1000000, 0}}
|
||||
)
|
||||
|
||||
// WebRTCReceiver receives a video track
|
||||
type WebRTCReceiver struct {
|
||||
peerID string
|
||||
@@ -176,7 +177,7 @@ func (w *WebRTCReceiver) Kind() webrtc.RTPCodecType {
|
||||
return w.kind
|
||||
}
|
||||
|
||||
func (w *WebRTCReceiver) AddUpTrack(track *webrtc.TrackRemote, buff *buffer.Buffer, bestQualityFirst bool) {
|
||||
func (w *WebRTCReceiver) AddUpTrack(track *webrtc.TrackRemote, buff *buffer.Buffer) {
|
||||
if w.closed.get() {
|
||||
return
|
||||
}
|
||||
@@ -199,42 +200,17 @@ func (w *WebRTCReceiver) AddUpTrack(track *webrtc.TrackRemote, buff *buffer.Buff
|
||||
w.buffers[layer] = buff
|
||||
w.bufferMu.Unlock()
|
||||
|
||||
if w.isSimulcast {
|
||||
w.addAvailableLayer(uint16(layer), false)
|
||||
|
||||
w.downTrackMu.RLock()
|
||||
// LK-TODO-START
|
||||
// DownTrack layer change should not happen directly from here.
|
||||
// Layer switching should be controlled by StreamAllocator. So, this
|
||||
// should call into DownTrack to notify availability of a new layer.
|
||||
// One challenge to think about is that the layer bitrate is not available
|
||||
// for a second after start up as sfu.Buffer reports at that cadence.
|
||||
// One possibility is to initialize sfu.Buffer with default bitrate
|
||||
// based on layer.
|
||||
// LK-TODO-END
|
||||
for _, dt := range w.downTracks {
|
||||
if dt != nil {
|
||||
if (bestQualityFirst && layer > dt.CurrentSpatialLayer()) ||
|
||||
(!bestQualityFirst && layer < dt.CurrentSpatialLayer()) {
|
||||
_ = dt.switchSpatialLayer(layer)
|
||||
}
|
||||
if w.isSimulcast && w.useTrackers {
|
||||
tracker := NewStreamTracker()
|
||||
w.trackers[layer] = tracker
|
||||
tracker.OnStatusChanged = func(status StreamStatus) {
|
||||
if status == StreamStatusStopped {
|
||||
w.removeAvailableLayer(uint16(layer))
|
||||
} else {
|
||||
w.addAvailableLayer(uint16(layer))
|
||||
}
|
||||
}
|
||||
w.downTrackMu.RUnlock()
|
||||
|
||||
// always publish lowest layer
|
||||
if layer != 0 && w.useTrackers {
|
||||
tracker := NewStreamTracker()
|
||||
w.trackers[layer] = tracker
|
||||
tracker.OnStatusChanged = func(status StreamStatus) {
|
||||
if status == StreamStatusStopped {
|
||||
w.removeAvailableLayer(uint16(layer))
|
||||
} else {
|
||||
w.addAvailableLayer(uint16(layer), true)
|
||||
}
|
||||
}
|
||||
tracker.Start()
|
||||
}
|
||||
tracker.Start()
|
||||
}
|
||||
go w.forwardRTP(layer)
|
||||
}
|
||||
@@ -255,13 +231,11 @@ func (w *WebRTCReceiver) SetUpTrackPaused(paused bool) {
|
||||
}
|
||||
}
|
||||
|
||||
func (w *WebRTCReceiver) AddDownTrack(track *DownTrack, bestQualityFirst bool) {
|
||||
func (w *WebRTCReceiver) AddDownTrack(track *DownTrack) {
|
||||
if w.closed.get() {
|
||||
return
|
||||
}
|
||||
|
||||
layer := 0
|
||||
|
||||
w.downTrackMu.RLock()
|
||||
_, ok := w.index[track.peerID]
|
||||
w.downTrackMu.RUnlock()
|
||||
@@ -270,37 +244,23 @@ func (w *WebRTCReceiver) AddDownTrack(track *DownTrack, bestQualityFirst bool) {
|
||||
}
|
||||
|
||||
if w.isSimulcast {
|
||||
w.upTrackMu.RLock()
|
||||
for i, t := range w.upTracks {
|
||||
if t != nil && w.HasSpatialLayer(int32(i)) {
|
||||
layer = i
|
||||
if !bestQualityFirst {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
w.upTrackMu.RUnlock()
|
||||
track.SetTrackType(true)
|
||||
|
||||
track.SetInitialLayers(int32(layer), 2)
|
||||
track.lastSSRC.set(w.SSRC(layer))
|
||||
track.trackType = SimulcastDownTrack
|
||||
track.payload = packetFactory.Get().(*[]byte)
|
||||
// notify added downtrack of available layers
|
||||
w.upTrackMu.RLock()
|
||||
layers, ok := w.availableLayers.Load().([]uint16)
|
||||
w.upTrackMu.RUnlock()
|
||||
if ok && len(layers) != 0 {
|
||||
_, _ = track.UptrackLayersChange(layers, true)
|
||||
}
|
||||
} else {
|
||||
// LK-TODO-START
|
||||
// check if any webrtc client does more than one temporal layer when not simulcasting.
|
||||
// Maybe okay to just set the max temporal layer to 2 even in this case.
|
||||
// Don't think there is any harm is setting it at 2 if the upper layers are
|
||||
// not going to be there.
|
||||
// LK-TODO-END
|
||||
track.SetInitialLayers(0, 0)
|
||||
track.trackType = SimpleDownTrack
|
||||
track.payload = packetFactory.Get().(*[]byte)
|
||||
track.SetTrackType(false)
|
||||
}
|
||||
|
||||
w.storeDownTrack(track)
|
||||
}
|
||||
|
||||
func (w *WebRTCReceiver) HasSpatialLayer(layer int32) bool {
|
||||
func (w *WebRTCReceiver) hasSpatialLayer(layer int32) bool {
|
||||
layers, ok := w.availableLayers.Load().([]uint16)
|
||||
if !ok {
|
||||
return false
|
||||
@@ -314,6 +274,15 @@ func (w *WebRTCReceiver) HasSpatialLayer(layer int32) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (w *WebRTCReceiver) NumAvailableSpatialLayers() int {
|
||||
layers, ok := w.availableLayers.Load().([]uint16)
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
|
||||
return len(layers)
|
||||
}
|
||||
|
||||
func (w *WebRTCReceiver) downtrackLayerChange(layers []uint16, layerAdded bool) {
|
||||
w.downTrackMu.RLock()
|
||||
defer w.downTrackMu.RUnlock()
|
||||
@@ -324,7 +293,7 @@ func (w *WebRTCReceiver) downtrackLayerChange(layers []uint16, layerAdded bool)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *WebRTCReceiver) addAvailableLayer(layer uint16, updateDownTrack bool) {
|
||||
func (w *WebRTCReceiver) addAvailableLayer(layer uint16) {
|
||||
w.upTrackMu.Lock()
|
||||
layers, ok := w.availableLayers.Load().([]uint16)
|
||||
if !ok {
|
||||
@@ -343,9 +312,7 @@ func (w *WebRTCReceiver) addAvailableLayer(layer uint16, updateDownTrack bool) {
|
||||
w.availableLayers.Store(layers)
|
||||
w.upTrackMu.Unlock()
|
||||
|
||||
if updateDownTrack {
|
||||
w.downtrackLayerChange(layers, true)
|
||||
}
|
||||
w.downtrackLayerChange(layers, true)
|
||||
}
|
||||
|
||||
func (w *WebRTCReceiver) removeAvailableLayer(layer uint16) {
|
||||
@@ -367,41 +334,6 @@ func (w *WebRTCReceiver) removeAvailableLayer(layer uint16) {
|
||||
w.downtrackLayerChange(newLayers, false)
|
||||
}
|
||||
|
||||
func (w *WebRTCReceiver) GetBitrate() [3]uint64 {
|
||||
var br [3]uint64
|
||||
w.bufferMu.RLock()
|
||||
defer w.bufferMu.RUnlock()
|
||||
for i, buff := range w.buffers {
|
||||
if buff != nil {
|
||||
if w.HasSpatialLayer(int32(i)) {
|
||||
br[i] = buff.Bitrate()
|
||||
} else {
|
||||
br[i] = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
return br
|
||||
}
|
||||
|
||||
func (w *WebRTCReceiver) GetBitrateTemporal() [3][4]uint64 {
|
||||
var br [3][4]uint64
|
||||
w.bufferMu.RLock()
|
||||
defer w.bufferMu.RUnlock()
|
||||
for i, buff := range w.buffers {
|
||||
if buff != nil {
|
||||
tls := make([]uint64, 4)
|
||||
if w.HasSpatialLayer(int32(i)) {
|
||||
tls = buff.BitrateTemporal()
|
||||
}
|
||||
|
||||
for j := 0; j < len(br[i]); j++ {
|
||||
br[i][j] = tls[j]
|
||||
}
|
||||
}
|
||||
}
|
||||
return br
|
||||
}
|
||||
|
||||
func (w *WebRTCReceiver) GetBitrateTemporalCumulative() [3][4]uint64 {
|
||||
// LK-TODO: For SVC tracks, need to accumulate across spatial layers also
|
||||
var br [3][4]uint64
|
||||
@@ -410,8 +342,9 @@ func (w *WebRTCReceiver) GetBitrateTemporalCumulative() [3][4]uint64 {
|
||||
for i, buff := range w.buffers {
|
||||
if buff != nil {
|
||||
tls := make([]uint64, 4)
|
||||
if w.HasSpatialLayer(int32(i)) {
|
||||
if w.hasSpatialLayer(int32(i)) {
|
||||
tls = buff.BitrateTemporalCumulative()
|
||||
w.maybeUseDefaultBitrate(tls, i)
|
||||
}
|
||||
|
||||
for j := 0; j < len(br[i]); j++ {
|
||||
@@ -422,18 +355,6 @@ func (w *WebRTCReceiver) GetBitrateTemporalCumulative() [3][4]uint64 {
|
||||
return br
|
||||
}
|
||||
|
||||
func (w *WebRTCReceiver) GetMaxTemporalLayer() [3]int32 {
|
||||
var tls [3]int32
|
||||
w.bufferMu.RLock()
|
||||
defer w.bufferMu.RUnlock()
|
||||
for i, buff := range w.buffers {
|
||||
if buff != nil {
|
||||
tls[i] = buff.MaxTemporalLayer()
|
||||
}
|
||||
}
|
||||
return tls
|
||||
}
|
||||
|
||||
// OnCloseHandler method to be called on remote tracked removed
|
||||
func (w *WebRTCReceiver) OnCloseHandler(fn func()) {
|
||||
w.onCloseHandler = fn
|
||||
@@ -655,6 +576,32 @@ func (w *WebRTCReceiver) storeDownTrack(track *DownTrack) {
|
||||
w.downTracks = append(w.downTracks, track)
|
||||
}
|
||||
|
||||
func (w *WebRTCReceiver) maybeUseDefaultBitrate(tlbs []uint64, layer int) {
|
||||
for _, tlb := range tlbs {
|
||||
if tlb != uint64(0) {
|
||||
// some layer has data
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Before measured bitrate is available, initialize with some sane default values.
|
||||
// Note that not all clients send temporal layers or have same number of temporal layers.
|
||||
// o Safari 15 - does not do temporal layers
|
||||
// o Chrome 95 - does two temporal layers
|
||||
// o Firefox 94 - does three temporal layers
|
||||
// Default initialization is to ensure that StreamAllocator has some data and can
|
||||
// forward tracks as soon as available.
|
||||
//
|
||||
// Measured bitrate will be available periodically starting shortly after stream
|
||||
// starts flowing (see `reportDelta` in buffer.go). Once that information becomes
|
||||
// available, it will be used for stream allocation.
|
||||
//
|
||||
for i := 0; i < len(tlbs); i++ {
|
||||
tlbs[i] = defaultBitratesCumulative[layer][i]
|
||||
}
|
||||
}
|
||||
|
||||
func (w *WebRTCReceiver) DebugInfo() map[string]interface{} {
|
||||
info := map[string]interface{}{
|
||||
"Simulcast": w.isSimulcast,
|
||||
|
||||
+168
-31
@@ -99,11 +99,14 @@
|
||||
package sfu
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/livekit/protocol/logger"
|
||||
|
||||
"github.com/pion/rtcp"
|
||||
"github.com/pion/webrtc/v3"
|
||||
)
|
||||
@@ -136,6 +139,21 @@ const (
|
||||
State_GRATUITOUS_PROBING
|
||||
)
|
||||
|
||||
func (s State) String() string {
|
||||
switch s {
|
||||
case State_PRE_COMMIT:
|
||||
return "PRE_COMMIT"
|
||||
case State_STABLE:
|
||||
return "STABLE"
|
||||
case State_DEFICIENT:
|
||||
return "DEFICIENT"
|
||||
case State_GRATUITOUS_PROBING:
|
||||
return "GRATUITOUS_PROBING"
|
||||
default:
|
||||
return fmt.Sprintf("%d", int(s))
|
||||
}
|
||||
}
|
||||
|
||||
type Signal int
|
||||
|
||||
const (
|
||||
@@ -152,6 +170,35 @@ const (
|
||||
Signal_PERIODIC_PING
|
||||
)
|
||||
|
||||
func (s Signal) String() string {
|
||||
switch s {
|
||||
case Signal_NONE:
|
||||
return "NONE"
|
||||
case Signal_ADD_TRACK:
|
||||
return "ADD_TRACK"
|
||||
case Signal_REMOVE_TRACK:
|
||||
return "REMOVE_TRACK"
|
||||
case Signal_ESTIMATE_INCREASE:
|
||||
return "ESTIMATE_INCREASE"
|
||||
case Signal_ESTIMATE_DECREASE:
|
||||
return "ESTIMATE_DECREASE"
|
||||
case Signal_RECEIVER_REPORT:
|
||||
return "RECEIVER_REPORT"
|
||||
case Signal_AVAILABLE_LAYERS_ADD:
|
||||
return "AVAILABLE_LAYERS_ADD"
|
||||
case Signal_AVAILABLE_LAYERS_REMOVE:
|
||||
return "AVAILABLE_LAYERS_REMOVE"
|
||||
case Signal_SUBSCRIPTION_CHANGE:
|
||||
return "SUBSCRIPTION_CHANGE"
|
||||
case Signal_SUBSCRIBED_LAYERS_CHANGE:
|
||||
return "SUBSCRIBED_LAYERS_CHANGE"
|
||||
case Signal_PERIODIC_PING:
|
||||
return "PERIODIC_PING"
|
||||
default:
|
||||
return fmt.Sprintf("%d", int(s))
|
||||
}
|
||||
}
|
||||
|
||||
type BoostMode int
|
||||
|
||||
const (
|
||||
@@ -159,6 +206,17 @@ const (
|
||||
BoostMode_BANDWIDTH
|
||||
)
|
||||
|
||||
func (b BoostMode) String() string {
|
||||
switch b {
|
||||
case BoostMode_LAYER:
|
||||
return "LAYER"
|
||||
case BoostMode_BANDWIDTH:
|
||||
return "BANDWIDTH"
|
||||
default:
|
||||
return fmt.Sprintf("%d", int(b))
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
// LK-TODO-START
|
||||
// These constants will definitely require more tweaking.
|
||||
@@ -170,8 +228,17 @@ var (
|
||||
BoostWaitMs = 3 * 1000 * time.Millisecond // 3 seconds
|
||||
)
|
||||
|
||||
// LK-TODO add logger and log interesting events
|
||||
type StreamAllocatorParams struct {
|
||||
ParticipantID string
|
||||
Logger logger.Logger
|
||||
}
|
||||
|
||||
type StreamAllocator struct {
|
||||
participantID string
|
||||
logger logger.Logger
|
||||
|
||||
onStreamedTracksChange func(paused map[string][]string, resumed map[string][]string) error
|
||||
|
||||
estimateMu sync.RWMutex
|
||||
trackingSSRC uint32
|
||||
committedChannelCapacity uint64
|
||||
@@ -202,18 +269,23 @@ type Event struct {
|
||||
DownTrack *DownTrack
|
||||
}
|
||||
|
||||
func NewStreamAllocator() *StreamAllocator {
|
||||
func NewStreamAllocator(params StreamAllocatorParams) *StreamAllocator {
|
||||
s := &StreamAllocator{
|
||||
participantID: params.ParticipantID,
|
||||
logger: params.Logger,
|
||||
committedChannelCapacity: InitialChannelCapacity,
|
||||
lastCommitTime: time.Now(),
|
||||
receivedEstimate: InitialChannelCapacity,
|
||||
lastEstimateDecreaseTime: time.Now(),
|
||||
boostMode: BoostMode_LAYER,
|
||||
tracks: make(map[string]*Track),
|
||||
prober: NewProber(),
|
||||
state: State_PRE_COMMIT,
|
||||
eventCh: make(chan []Event, 10),
|
||||
runningCh: make(chan struct{}),
|
||||
prober: NewProber(ProberParams{
|
||||
ParticipantID: params.ParticipantID,
|
||||
Logger: params.Logger,
|
||||
}),
|
||||
state: State_PRE_COMMIT,
|
||||
eventCh: make(chan []Event, 10),
|
||||
runningCh: make(chan struct{}),
|
||||
}
|
||||
s.prober.OnSendProbe(s.onSendProbe)
|
||||
|
||||
@@ -233,7 +305,11 @@ func (s *StreamAllocator) Stop() {
|
||||
close(s.eventCh)
|
||||
}
|
||||
|
||||
func (s *StreamAllocator) AddTrack(downTrack *DownTrack) {
|
||||
func (s *StreamAllocator) OnStreamedTracksChange(f func(paused map[string][]string, resumed map[string][]string) error) {
|
||||
s.onStreamedTracksChange = f
|
||||
}
|
||||
|
||||
func (s *StreamAllocator) AddTrack(downTrack *DownTrack, peerID string) {
|
||||
downTrack.OnREMB(s.onREMB)
|
||||
downTrack.AddReceiverReportListener(s.onReceiverReport)
|
||||
downTrack.OnAvailableLayersChanged(s.onAvailableLayersChanged)
|
||||
@@ -242,7 +318,7 @@ func (s *StreamAllocator) AddTrack(downTrack *DownTrack) {
|
||||
downTrack.OnPacketSent(s.onPacketSent)
|
||||
|
||||
s.tracksMu.Lock()
|
||||
track := newTrack(downTrack)
|
||||
track := newTrack(downTrack, peerID)
|
||||
s.tracks[downTrack.ID()] = track
|
||||
|
||||
s.tracksSorted = append(s.tracksSorted, track)
|
||||
@@ -315,8 +391,8 @@ func (s *StreamAllocator) onREMB(downTrack *DownTrack, remb *rtcp.ReceiverEstima
|
||||
}
|
||||
if !found {
|
||||
if len(remb.SSRCs) == 0 {
|
||||
// LK-TODO - log about REMB wihtout SSRCs
|
||||
s.estimateMu.Unlock()
|
||||
s.logger.Warnw("no SSRC to track REMB", nil, "participant", s.participantID)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -341,6 +417,9 @@ func (s *StreamAllocator) onREMB(downTrack *DownTrack, remb *rtcp.ReceiverEstima
|
||||
|
||||
s.prevReceivedEstimate = s.receivedEstimate
|
||||
s.receivedEstimate = uint64(remb.Bitrate)
|
||||
if s.prevReceivedEstimate != s.receivedEstimate {
|
||||
s.logger.Debugw("received new estimate", "pariticpant", s.participantID, "old(bps)", s.prevReceivedEstimate, "new(bps)", s.receivedEstimate)
|
||||
}
|
||||
signal := s.maybeCommitEstimate()
|
||||
s.estimateMu.Unlock()
|
||||
|
||||
@@ -546,7 +625,7 @@ func (s *StreamAllocator) runStateMachine(event Event) {
|
||||
func (s *StreamAllocator) runStatePreCommit(event Event) {
|
||||
switch event.Signal {
|
||||
case Signal_ADD_TRACK:
|
||||
s.allocate()
|
||||
// wait for layers add/remove signal
|
||||
case Signal_REMOVE_TRACK:
|
||||
s.allocate()
|
||||
case Signal_ESTIMATE_INCREASE:
|
||||
@@ -569,7 +648,7 @@ func (s *StreamAllocator) runStatePreCommit(event Event) {
|
||||
func (s *StreamAllocator) runStateStable(event Event) {
|
||||
switch event.Signal {
|
||||
case Signal_ADD_TRACK:
|
||||
s.allocate()
|
||||
// wait for layers add/remove signal
|
||||
case Signal_REMOVE_TRACK:
|
||||
// LK-TODO - may want to re-calculate channel usage?
|
||||
case Signal_ESTIMATE_INCREASE:
|
||||
@@ -607,7 +686,7 @@ func (s *StreamAllocator) runStateStable(event Event) {
|
||||
func (s *StreamAllocator) runStateDeficient(event Event) {
|
||||
switch event.Signal {
|
||||
case Signal_ADD_TRACK:
|
||||
s.maybeProbe()
|
||||
// wait for layers add/remove signal
|
||||
case Signal_REMOVE_TRACK:
|
||||
s.allocate()
|
||||
case Signal_ESTIMATE_INCREASE:
|
||||
@@ -623,6 +702,8 @@ func (s *StreamAllocator) runStateDeficient(event Event) {
|
||||
s.allocate()
|
||||
case Signal_RECEIVER_REPORT:
|
||||
case Signal_AVAILABLE_LAYERS_ADD:
|
||||
// new track coming online will trigger this.
|
||||
// LK-TODO: probe using the new track rather than trying with existing tracks.
|
||||
s.maybeProbe()
|
||||
case Signal_AVAILABLE_LAYERS_REMOVE:
|
||||
s.allocate()
|
||||
@@ -642,8 +723,7 @@ func (s *StreamAllocator) runStateGratuitousProbing(event Event) {
|
||||
// to avoid any self-inflicted damaage
|
||||
switch event.Signal {
|
||||
case Signal_ADD_TRACK:
|
||||
s.prober.Reset()
|
||||
s.allocate()
|
||||
// wait for layers add/remove signal
|
||||
case Signal_REMOVE_TRACK:
|
||||
// LK-TODO - may want to re-calculate channel usage?
|
||||
case Signal_ESTIMATE_INCREASE:
|
||||
@@ -667,17 +747,16 @@ func (s *StreamAllocator) runStateGratuitousProbing(event Event) {
|
||||
s.prober.Reset()
|
||||
s.allocate()
|
||||
case Signal_PERIODIC_PING:
|
||||
if !s.prober.IsRunning() {
|
||||
// try for more
|
||||
s.maybeGratuitousProbe()
|
||||
// LK-TODO - log about more probing here
|
||||
// try for more
|
||||
if !s.prober.IsRunning() && s.maybeGratuitousProbe() {
|
||||
s.logger.Infow("trying more gratuitous probing", "participant", s.participantID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StreamAllocator) setState(state State) {
|
||||
if s.state != state {
|
||||
// LK-TODO log state changes
|
||||
s.logger.Infow("state change", "participant", s.participantID, "from", s.state.String(), "to", state.String())
|
||||
}
|
||||
|
||||
s.state = state
|
||||
@@ -688,12 +767,16 @@ func (s *StreamAllocator) maybeCommitEstimate() Signal {
|
||||
// 1. Abs(receivedEstimate - prevReceivedEstimate) < EstimateEpsilon => estimate stable
|
||||
// 2. time.Since(lastCommitTime) > EstimateCommitMs => to catch long oscillating estimate
|
||||
if math.Abs(float64(s.receivedEstimate)-float64(s.prevReceivedEstimate)) > EstimateEpsilon {
|
||||
// too large a change, wait for estimate to settle
|
||||
return Signal_NONE
|
||||
// too large a change, wait for estimate to settle.
|
||||
// Unless estimate has been oscillating for too long.
|
||||
if time.Since(s.lastCommitTime) < EstimateCommitMs {
|
||||
return Signal_NONE
|
||||
}
|
||||
}
|
||||
|
||||
// don't commit too often even if the change is small.
|
||||
// Small changes will also get picked up during periodic check.
|
||||
if time.Since(s.lastCommitTime) < EstimateCommitMs {
|
||||
// don't commit too often
|
||||
return Signal_NONE
|
||||
}
|
||||
|
||||
@@ -710,6 +793,7 @@ func (s *StreamAllocator) maybeCommitEstimate() Signal {
|
||||
|
||||
s.committedChannelCapacity = s.receivedEstimate
|
||||
s.lastCommitTime = time.Now()
|
||||
s.logger.Debugw("committing channel capacity", "participant", s.participantID, "capacity(bps)", s.committedChannelCapacity)
|
||||
|
||||
return signal
|
||||
}
|
||||
@@ -808,6 +892,9 @@ func (s *StreamAllocator) allocate() {
|
||||
// So, track total requested bandwidth and mark DEFICIENT state if the total is
|
||||
// above the estimated channel capacity even if the optimal signal is true.
|
||||
//
|
||||
var pausedTracks map[string][]string
|
||||
var resumedTracks map[string][]string
|
||||
|
||||
isOptimal := true
|
||||
totalBandwidthRequested := uint64(0)
|
||||
committedChannelCapacity := s.getChannelCapacity()
|
||||
@@ -833,7 +920,7 @@ func (s *StreamAllocator) allocate() {
|
||||
// be stopped immediately to not further congest the channel.
|
||||
//
|
||||
//
|
||||
bandwidthRequested, optimalBandwidthNeeded := track.AdjustAllocation(availableChannelCapacity)
|
||||
isPausing, isResuming, bandwidthRequested, optimalBandwidthNeeded := track.AdjustAllocation(availableChannelCapacity)
|
||||
totalBandwidthRequested += bandwidthRequested
|
||||
if optimalBandwidthNeeded > 0 && bandwidthRequested < optimalBandwidthNeeded {
|
||||
//
|
||||
@@ -855,6 +942,14 @@ func (s *StreamAllocator) allocate() {
|
||||
} else {
|
||||
availableChannelCapacity -= bandwidthRequested
|
||||
}
|
||||
|
||||
if isPausing {
|
||||
appendTrack(track, &pausedTracks)
|
||||
}
|
||||
|
||||
if isResuming {
|
||||
appendTrack(track, &resumedTracks)
|
||||
}
|
||||
}
|
||||
s.tracksMu.RUnlock()
|
||||
|
||||
@@ -867,6 +962,16 @@ func (s *StreamAllocator) allocate() {
|
||||
}
|
||||
}
|
||||
|
||||
if len(pausedTracks) != 0 || len(resumedTracks) != 0 {
|
||||
s.logger.Debugw("streamed tracks changed", "participant", s.participantID, "paused", pausedTracks, "resumed", resumedTracks)
|
||||
if s.onStreamedTracksChange != nil {
|
||||
err := s.onStreamedTracksChange(pausedTracks, resumedTracks)
|
||||
if err != nil {
|
||||
s.logger.Errorw("could not send streamed tracks update", err, "participant", s.participantID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// The above loop may become a concern. In a typical conference
|
||||
// kind of scenario, there are probably not that many people, so
|
||||
@@ -1010,16 +1115,16 @@ func (s *StreamAllocator) resetBoost() {
|
||||
s.boostedChannelCapacity = 0
|
||||
}
|
||||
|
||||
func (s *StreamAllocator) maybeGratuitousProbe() {
|
||||
func (s *StreamAllocator) maybeGratuitousProbe() bool {
|
||||
if time.Since(s.lastEstimateDecreaseTime) < GratuitousProbeWaitMs {
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
committedChannelCapacity := s.getChannelCapacity()
|
||||
expectedRateBps := s.getExpectedBandwidthUsage()
|
||||
headroomBps := committedChannelCapacity - expectedRateBps
|
||||
if headroomBps > GratuitousProbeHeadroomBps {
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
probeRateBps := (committedChannelCapacity * GratuitousProbePct) / 100
|
||||
@@ -1030,6 +1135,24 @@ func (s *StreamAllocator) maybeGratuitousProbe() {
|
||||
s.prober.AddCluster(int(committedChannelCapacity+probeRateBps), int(expectedRateBps), GratuitousProbeMinDurationMs, GratuitousProbeMaxDurationMs)
|
||||
|
||||
s.setState(State_GRATUITOUS_PROBING)
|
||||
return true
|
||||
}
|
||||
|
||||
//------------------------------------------------
|
||||
|
||||
func appendTrack(t *Track, m *map[string][]string) {
|
||||
if *m == nil {
|
||||
*m = make(map[string][]string)
|
||||
}
|
||||
|
||||
peerID := t.PeerID()
|
||||
trackID := t.ID()
|
||||
peer, ok := (*m)[peerID]
|
||||
if !ok {
|
||||
peer = make([]string, 0, 2)
|
||||
}
|
||||
peer = append(peer, trackID)
|
||||
(*m)[peerID] = peer
|
||||
}
|
||||
|
||||
//------------------------------------------------
|
||||
@@ -1045,6 +1168,7 @@ type Track struct {
|
||||
lock sync.RWMutex
|
||||
|
||||
downTrack *DownTrack
|
||||
peerID string
|
||||
|
||||
highestSN uint32
|
||||
packetsLost uint32
|
||||
@@ -1058,9 +1182,10 @@ type Track struct {
|
||||
maxTemporalLayer int32
|
||||
}
|
||||
|
||||
func newTrack(downTrack *DownTrack) *Track {
|
||||
func newTrack(downTrack *DownTrack, peerID string) *Track {
|
||||
return &Track{
|
||||
downTrack: downTrack,
|
||||
peerID: peerID,
|
||||
maxSpatialLayer: downTrack.MaxSpatialLayer(),
|
||||
maxTemporalLayer: downTrack.MaxTemporalLayer(),
|
||||
}
|
||||
@@ -1070,6 +1195,14 @@ func (t *Track) DownTrack() *DownTrack {
|
||||
return t.downTrack
|
||||
}
|
||||
|
||||
func (t *Track) ID() string {
|
||||
return t.downTrack.ID()
|
||||
}
|
||||
|
||||
func (t *Track) PeerID() string {
|
||||
return t.peerID
|
||||
}
|
||||
|
||||
// LK-TODO this should probably be maintained in downTrack and this module can query what it needs
|
||||
func (t *Track) UpdatePacketStats(rr *rtcp.ReceiverReport) {
|
||||
t.lock.Lock()
|
||||
@@ -1104,9 +1237,13 @@ func (t *Track) WritePaddingRTP(bytesToSend int) int {
|
||||
return t.downTrack.WritePaddingRTP(bytesToSend)
|
||||
}
|
||||
|
||||
func (t *Track) AdjustAllocation(availableChannelCapacity uint64) (uint64, uint64) {
|
||||
t.bandwidthRequested, t.optimalBandwidthNeeded = t.downTrack.AdjustAllocation(availableChannelCapacity)
|
||||
return t.bandwidthRequested, t.optimalBandwidthNeeded
|
||||
func (t *Track) AdjustAllocation(availableChannelCapacity uint64) (bool, bool, uint64, uint64) {
|
||||
isPausing, isResuming, bandwidthRequested, optimalBandwidthNeeded := t.downTrack.AdjustAllocation(availableChannelCapacity)
|
||||
|
||||
t.bandwidthRequested = bandwidthRequested
|
||||
t.optimalBandwidthNeeded = optimalBandwidthNeeded
|
||||
|
||||
return isPausing, isResuming, bandwidthRequested, optimalBandwidthNeeded
|
||||
}
|
||||
|
||||
func (t *Track) IncreaseAllocation() (bool, uint64) {
|
||||
@@ -1158,7 +1295,7 @@ func (t TrackSorter) Less(i, j int) bool {
|
||||
|
||||
// use track id to keep ordering if nothing else changes
|
||||
// LK-TODO: ideally should be sorting, compare and then re-allocate only if order changed
|
||||
return t[i].downTrack.ID() < t[j].downTrack.ID()
|
||||
return t[i].ID() < t[j].ID()
|
||||
}
|
||||
|
||||
//------------------------------------------------
|
||||
|
||||
@@ -32,6 +32,7 @@ type StreamTracker struct {
|
||||
CyclesRequired uint64
|
||||
CycleDuration time.Duration
|
||||
OnStatusChanged func(StreamStatus)
|
||||
initialized atomicBool
|
||||
paused atomicBool
|
||||
status atomicInt32 // stores StreamStatus
|
||||
countSinceLast uint32 // number of packets received since last check
|
||||
@@ -50,7 +51,7 @@ func NewStreamTracker() *StreamTracker {
|
||||
CyclesRequired: 60, // 30s of continuous stream
|
||||
CycleDuration: 500 * time.Millisecond,
|
||||
}
|
||||
s.status.set(int32(StreamStatusActive))
|
||||
s.status.set(int32(StreamStatusStopped))
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -103,6 +104,13 @@ func (s *StreamTracker) Observe(sn uint16) {
|
||||
if s.paused.get() {
|
||||
return
|
||||
}
|
||||
|
||||
if !s.initialized.get() {
|
||||
s.initialized.set(true)
|
||||
// first packet
|
||||
go s.setStatus(StreamStatusActive)
|
||||
}
|
||||
|
||||
// ignore out-of-order SNs
|
||||
if (sn - s.lastSN) > uint16(1<<15) {
|
||||
return
|
||||
@@ -125,7 +133,7 @@ func (s *StreamTracker) detectWorker() {
|
||||
}
|
||||
|
||||
func (s *StreamTracker) detectChanges() {
|
||||
if s.paused.get() {
|
||||
if s.paused.get() || !s.initialized.get() {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -3,16 +3,44 @@ package sfu
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/testutils"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestStreamTracker(t *testing.T) {
|
||||
t.Run("flips to inactive immediately", func(t *testing.T) {
|
||||
t.Run("flips to active on first observe", func(t *testing.T) {
|
||||
callbackCalled := atomicBool(0)
|
||||
tracker := NewStreamTracker()
|
||||
tracker.OnStatusChanged = func(status StreamStatus) {
|
||||
callbackCalled.set(true)
|
||||
}
|
||||
require.Equal(t, StreamStatusStopped, tracker.Status())
|
||||
|
||||
// observe first packet
|
||||
tracker.Observe(1)
|
||||
|
||||
testutils.WithTimeout(t, "first packet makes stream active", func() bool {
|
||||
return callbackCalled.get()
|
||||
})
|
||||
|
||||
require.Equal(t, StreamStatusActive, tracker.Status())
|
||||
require.True(t, callbackCalled.get())
|
||||
})
|
||||
|
||||
t.Run("flips to inactive immediately", func(t *testing.T) {
|
||||
tracker := NewStreamTracker()
|
||||
require.Equal(t, StreamStatusStopped, tracker.Status())
|
||||
|
||||
tracker.Observe(1)
|
||||
testutils.WithTimeout(t, "first packet makes stream active", func() bool {
|
||||
return tracker.Status() == StreamStatusActive
|
||||
})
|
||||
|
||||
callbackCalled := atomicBool(0)
|
||||
tracker.OnStatusChanged = func(status StreamStatus) {
|
||||
callbackCalled.set(true)
|
||||
}
|
||||
require.Equal(t, StreamStatusActive, tracker.Status())
|
||||
|
||||
// run a single interation
|
||||
@@ -23,21 +51,33 @@ func TestStreamTracker(t *testing.T) {
|
||||
|
||||
t.Run("flips back to active after iterations", func(t *testing.T) {
|
||||
tracker := NewStreamTracker()
|
||||
require.Equal(t, StreamStatusStopped, tracker.Status())
|
||||
|
||||
tracker.Observe(1)
|
||||
testutils.WithTimeout(t, "first packet makes stream active", func() bool {
|
||||
return tracker.Status() == StreamStatusActive
|
||||
})
|
||||
|
||||
tracker.CyclesRequired = 2
|
||||
tracker.SamplesRequired = 1
|
||||
tracker.setStatus(StreamStatusStopped)
|
||||
|
||||
tracker.Observe(1)
|
||||
tracker.Observe(2)
|
||||
tracker.detectChanges()
|
||||
require.Equal(t, StreamStatusStopped, tracker.Status())
|
||||
|
||||
tracker.Observe(2)
|
||||
tracker.Observe(3)
|
||||
tracker.detectChanges()
|
||||
require.Equal(t, StreamStatusActive, tracker.Status())
|
||||
})
|
||||
|
||||
t.Run("does not change to inactive when paused", func(t *testing.T) {
|
||||
tracker := NewStreamTracker()
|
||||
tracker.Observe(1)
|
||||
testutils.WithTimeout(t, "first packet makes stream active", func() bool {
|
||||
return tracker.Status() == StreamStatusActive
|
||||
})
|
||||
|
||||
tracker.SetPaused(true)
|
||||
tracker.detectChanges()
|
||||
require.Equal(t, StreamStatusActive, tracker.Status())
|
||||
|
||||
Reference in New Issue
Block a user