From 9e327b1f3c721a84783d75a2e0f9f15f132c53f4 Mon Sep 17 00:00:00 2001 From: Raja Subramanian Date: Sun, 5 Mar 2023 12:55:04 +0530 Subject: [PATCH] Connection quality (#1490) * Make connection quality not too optimistic. With score normalization, the quality indicator showed good under conditions which should have normally showed some badness. So, a few things in this PR - Do not normalize scores - Pick the weakest link as the representative score (moving away from averaging) - For down track direction, when reporting delta stats, take the number of packets sent actually. If there are holes in the feed (upstream packet loss), down tracks should not be penalised for that loss. State of things in connection quality feature - Audio uses rtcscore-go (with a change to accommodate RED codec). This follows the E-model. - Camera uses rtcscore-go. No change here. NOTE: THe rtscore here is purely based on bits per pixel per frame (bpf). This has the following existing issues (no change, these were already there) o Does not take packet loss, jitter, rtt into account o Expected frame rate is not available. So, measured frame rate is used as expected frame rate also. If expected frame rate were available, the score could be reduced for lower frame rates. - Screen share tracks: No change. This uses the very old simple loss based thresholding for scoring. As the bit rate varies a lot based on content and rtcscore video algorithm used for camera relies on bits per pixel per frame, this could produce a very low value (large width/height encoded in a small number of bits because of static content) and hence a low score. So, the old loss based thresholding is used. * clean up * update rtcscore pointer * fix tests * log lines reformat * WIP commit * WIP commit * update mute of receiver * WIP commit * WIP commit * start adding tests * take min score if quality matches * start adding bytes based scoring * clean up * more clean up * Use Fuse * log quality drop * clean up debug log * - Use number of windows for wait to make things simpler - track no layer expected case - always update transition - always call updateScore --- go.mod | 3 +- go.sum | 2 - pkg/rtc/dynacastmanager.go | 5 +- pkg/rtc/dynacastquality.go | 5 +- pkg/rtc/mediatrack.go | 8 +- pkg/rtc/participant.go | 58 +- pkg/rtc/room.go | 8 +- pkg/rtc/types/interfaces.go | 2 +- .../typesfakes/fake_local_media_track.go | 83 +- pkg/rtc/wrappedreceiver.go | 7 - pkg/sfu/buffer/rtpstats.go | 22 +- pkg/sfu/connectionquality/connectionstats.go | 330 ++----- .../connectionquality/connectionstats_test.go | 833 ++++++++++-------- pkg/sfu/connectionquality/mos.go | 134 --- pkg/sfu/connectionquality/scorer.go | 471 ++++++++++ pkg/sfu/downtrack.go | 18 +- pkg/sfu/forwarder.go | 40 +- pkg/sfu/receiver.go | 71 +- pkg/sfu/streamtrackermanager.go | 56 -- 19 files changed, 1216 insertions(+), 940 deletions(-) delete mode 100644 pkg/sfu/connectionquality/mos.go create mode 100644 pkg/sfu/connectionquality/scorer.go diff --git a/go.mod b/go.mod index 718c7120..712406fd 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/dustin/go-humanize v1.0.1 github.com/elliotchance/orderedmap/v2 v2.2.0 github.com/florianl/go-tc v0.4.2 + github.com/frostbyte73/core v0.0.4 github.com/gammazero/deque v0.1.0 github.com/gammazero/workerpool v1.1.2 github.com/google/wire v0.5.0 @@ -19,7 +20,6 @@ require ( github.com/livekit/mediatransportutil v0.0.0-20230130133657-96cfb115473a github.com/livekit/protocol v1.4.3-0.20230303025609-c0705dbb696a github.com/livekit/psrpc v0.2.10-0.20230303054701-5853a56b4643 - github.com/livekit/rtcscore-go v0.0.0-20230224125650-6a6442ef9ebc github.com/mackerelio/go-osstat v0.2.3 github.com/magefile/mage v1.14.0 github.com/maxbrunsfeld/counterfeiter/v6 v6.6.1 @@ -61,7 +61,6 @@ require ( github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/eapache/channels v1.1.0 // indirect github.com/eapache/queue v1.1.0 // indirect - github.com/frostbyte73/core v0.0.4 // indirect github.com/go-logr/logr v1.2.3 // indirect github.com/golang/protobuf v1.5.2 // indirect github.com/google/go-cmp v0.5.9 // indirect diff --git a/go.sum b/go.sum index e3e48378..27e51360 100644 --- a/go.sum +++ b/go.sum @@ -236,8 +236,6 @@ github.com/livekit/protocol v1.4.3-0.20230303025609-c0705dbb696a h1:3yPLmATyLh6E github.com/livekit/protocol v1.4.3-0.20230303025609-c0705dbb696a/go.mod h1:hkK/G0wwFiLUGp9F5kxeQxq2CQuIzkmfBwKhTsc71us= github.com/livekit/psrpc v0.2.10-0.20230303054701-5853a56b4643 h1:ftDwqesgXMu0hUXFxf4KWAqqDIXz8BBdNnit3xc6RQA= github.com/livekit/psrpc v0.2.10-0.20230303054701-5853a56b4643/go.mod h1:K0j8f1PgLShR7Lx80KbmwFkDH2BvOnycXGV0OSRURKc= -github.com/livekit/rtcscore-go v0.0.0-20230224125650-6a6442ef9ebc h1:C8gL3pCjKmevR38PJ7+TsPS+Rm4Kbba8lwJmjNMqdUU= -github.com/livekit/rtcscore-go v0.0.0-20230224125650-6a6442ef9ebc/go.mod h1:116ych8UaEs9vfIE8n6iZCZ30iagUFTls0vRmC+Ix5U= github.com/mackerelio/go-osstat v0.2.3 h1:jAMXD5erlDE39kdX2CU7YwCGRcxIO33u/p8+Fhe5dJw= github.com/mackerelio/go-osstat v0.2.3/go.mod h1:DQbPOnsss9JHIXgBStc/dnhhir3gbd3YH+Dbdi7ptMA= github.com/magefile/mage v1.14.0 h1:6QDX3g6z1YvJ4olPhT1wksUcSa/V0a1B+pJb73fBjyo= diff --git a/pkg/rtc/dynacastmanager.go b/pkg/rtc/dynacastmanager.go index c16b6d3b..aed49e63 100644 --- a/pkg/rtc/dynacastmanager.go +++ b/pkg/rtc/dynacastmanager.go @@ -140,9 +140,8 @@ func (d *DynacastManager) getOrCreateDynacastQuality(mime string) *DynacastQuali } dq := NewDynacastQuality(DynacastQualityParams{ - MimeType: mime, - DynacastPauseDelay: d.params.DynacastPauseDelay, - Logger: d.params.Logger, + MimeType: mime, + Logger: d.params.Logger, }) dq.OnSubscribedMaxQualityChange(func(maxQuality livekit.VideoQuality) { d.updateMaxQualityForMime(mime, maxQuality) diff --git a/pkg/rtc/dynacastquality.go b/pkg/rtc/dynacastquality.go index 00d9734e..5be1e997 100644 --- a/pkg/rtc/dynacastquality.go +++ b/pkg/rtc/dynacastquality.go @@ -13,9 +13,8 @@ const ( ) type DynacastQualityParams struct { - MimeType string - DynacastPauseDelay time.Duration - Logger logger.Logger + MimeType string + Logger logger.Logger } // DynacastQuality manages max subscribed quality of a single receiver of a media track diff --git a/pkg/rtc/mediatrack.go b/pkg/rtc/mediatrack.go index 7cf5780d..ce117fbd 100644 --- a/pkg/rtc/mediatrack.go +++ b/pkg/rtc/mediatrack.go @@ -18,6 +18,7 @@ import ( "github.com/livekit/livekit-server/pkg/rtc/types" "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/telemetry" ) @@ -312,12 +313,13 @@ func (t *MediaTrack) AddReceiver(receiver *webrtc.RTPReceiver, track *webrtc.Tra return newCodec } -func (t *MediaTrack) GetConnectionScore() float32 { +func (t *MediaTrack) GetConnectionScoreAndQuality() (float32, livekit.ConnectionQuality) { receiver := t.PrimaryReceiver() if rtcReceiver, ok := receiver.(*sfu.WebRTCReceiver); ok { - return rtcReceiver.GetConnectionScore() + return rtcReceiver.GetConnectionScoreAndQuality() } - return 0.0 + + return connectionquality.MaxMOS, livekit.ConnectionQuality_EXCELLENT } func (t *MediaTrack) SetRTT(rtt uint32) { diff --git a/pkg/rtc/participant.go b/pkg/rtc/participant.go index e9bf9b5d..526e3062 100644 --- a/pkg/rtc/participant.go +++ b/pkg/rtc/participant.go @@ -23,7 +23,6 @@ import ( "github.com/livekit/livekit-server/pkg/rtc/types" "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/telemetry" "github.com/livekit/mediatransportutil/pkg/twcc" "github.com/livekit/protocol/auth" @@ -818,35 +817,45 @@ func (p *ParticipantImpl) GetAudioLevel() (level float64, active bool) { } func (p *ParticipantImpl) GetConnectionQuality() *livekit.ConnectionQualityInfo { - publisherScores := p.getPublisherConnectionQuality() + numTracks := 0 + minQuality := livekit.ConnectionQuality_EXCELLENT + minScore := float32(0.0) - numTracks := len(publisherScores) - totalScore := float32(0.0) - for _, score := range publisherScores { - totalScore += score + for _, pt := range p.GetPublishedTracks() { + numTracks++ + + score, quality := pt.(types.LocalMediaTrack).GetConnectionScoreAndQuality() + if quality < minQuality { + // WARNING NOTE: comparing protobuf enums directly + minQuality = quality + minScore = score + } else if quality == minQuality && score < minScore { + minScore = score + } } subscribedTracks := p.SubscriptionManager.GetSubscribedTracks() - subscriberScores := make(map[livekit.TrackID]float32, len(subscribedTracks)) for _, subTrack := range subscribedTracks { - if subTrack.IsMuted() || subTrack.MediaTrack().IsMuted() { - continue - } - score := subTrack.DownTrack().GetConnectionScore() - subscriberScores[subTrack.ID()] = score - totalScore += score numTracks++ + + score, quality := subTrack.DownTrack().GetConnectionScoreAndQuality() + if quality < minQuality { + // WARNING NOTE: comparing protobuf enums directly + minQuality = quality + minScore = score + } else if quality == minQuality && score < minScore { + minScore = score + } } - avgScore := float32(5.0) - if numTracks > 0 { - avgScore = totalScore / float32(numTracks) + if numTracks == 0 { + return nil } return &livekit.ConnectionQualityInfo{ ParticipantSid: string(p.ID()), - Quality: connectionquality.Score2Rating(avgScore), - Score: avgScore, + Quality: minQuality, + Score: minScore, } } @@ -1526,19 +1535,6 @@ func (p *ParticipantImpl) setTrackMuted(trackID livekit.TrackID, muted bool) { } } -func (p *ParticipantImpl) getPublisherConnectionQuality() map[livekit.TrackID]float32 { - publishedTracks := p.GetPublishedTracks() - scores := make(map[livekit.TrackID]float32, len(publishedTracks)) - for _, pt := range publishedTracks { - if pt.IsMuted() { - continue - } - scores[pt.ID()] = pt.(types.LocalMediaTrack).GetConnectionScore() - } - - return scores -} - func (p *ParticipantImpl) mediaTrackReceived(track *webrtc.TrackRemote, rtpReceiver *webrtc.RTPReceiver) (*MediaTrack, bool) { p.pendingTracksLock.Lock() newTrack := false diff --git a/pkg/rtc/room.go b/pkg/rtc/room.go index 1e70a089..3da30538 100644 --- a/pkg/rtc/room.go +++ b/pkg/rtc/room.go @@ -308,9 +308,11 @@ func (r *Room) Join(participant types.LocalParticipant, opts *ParticipantOptions }, false) } - update := &livekit.ConnectionQualityUpdate{} - update.Updates = append(update.Updates, pub.GetConnectionQuality()) - _ = participant.SendConnectionQualityUpdate(update) + if cq := pub.GetConnectionQuality(); cq != nil { + update := &livekit.ConnectionQualityUpdate{} + update.Updates = append(update.Updates, cq) + _ = participant.SendConnectionQualityUpdate(update) + } } } else { // no longer subscribed to the publisher, clear speaker status diff --git a/pkg/rtc/types/interfaces.go b/pkg/rtc/types/interfaces.go index 43ca2d25..6c160b6a 100644 --- a/pkg/rtc/types/interfaces.go +++ b/pkg/rtc/types/interfaces.go @@ -405,7 +405,7 @@ type LocalMediaTrack interface { HasSdpCid(cid string) bool GetAudioLevel() (level float64, active bool) - GetConnectionScore() float32 + GetConnectionScoreAndQuality() (float32, livekit.ConnectionQuality) SetRTT(rtt uint32) diff --git a/pkg/rtc/types/typesfakes/fake_local_media_track.go b/pkg/rtc/types/typesfakes/fake_local_media_track.go index 06071228..f6ee5b32 100644 --- a/pkg/rtc/types/typesfakes/fake_local_media_track.go +++ b/pkg/rtc/types/typesfakes/fake_local_media_track.go @@ -60,15 +60,17 @@ type FakeLocalMediaTrack struct { result1 float64 result2 bool } - GetConnectionScoreStub func() float32 - getConnectionScoreMutex sync.RWMutex - getConnectionScoreArgsForCall []struct { + GetConnectionScoreAndQualityStub func() (float32, livekit.ConnectionQuality) + getConnectionScoreAndQualityMutex sync.RWMutex + getConnectionScoreAndQualityArgsForCall []struct { } - getConnectionScoreReturns struct { + getConnectionScoreAndQualityReturns struct { result1 float32 + result2 livekit.ConnectionQuality } - getConnectionScoreReturnsOnCall map[int]struct { + getConnectionScoreAndQualityReturnsOnCall map[int]struct { result1 float32 + result2 livekit.ConnectionQuality } GetNumSubscribersStub func() int getNumSubscribersMutex sync.RWMutex @@ -578,57 +580,60 @@ func (fake *FakeLocalMediaTrack) GetAudioLevelReturnsOnCall(i int, result1 float }{result1, result2} } -func (fake *FakeLocalMediaTrack) GetConnectionScore() float32 { - fake.getConnectionScoreMutex.Lock() - ret, specificReturn := fake.getConnectionScoreReturnsOnCall[len(fake.getConnectionScoreArgsForCall)] - fake.getConnectionScoreArgsForCall = append(fake.getConnectionScoreArgsForCall, struct { +func (fake *FakeLocalMediaTrack) GetConnectionScoreAndQuality() (float32, livekit.ConnectionQuality) { + fake.getConnectionScoreAndQualityMutex.Lock() + ret, specificReturn := fake.getConnectionScoreAndQualityReturnsOnCall[len(fake.getConnectionScoreAndQualityArgsForCall)] + fake.getConnectionScoreAndQualityArgsForCall = append(fake.getConnectionScoreAndQualityArgsForCall, struct { }{}) - stub := fake.GetConnectionScoreStub - fakeReturns := fake.getConnectionScoreReturns - fake.recordInvocation("GetConnectionScore", []interface{}{}) - fake.getConnectionScoreMutex.Unlock() + stub := fake.GetConnectionScoreAndQualityStub + fakeReturns := fake.getConnectionScoreAndQualityReturns + fake.recordInvocation("GetConnectionScoreAndQuality", []interface{}{}) + fake.getConnectionScoreAndQualityMutex.Unlock() if stub != nil { return stub() } if specificReturn { - return ret.result1 + return ret.result1, ret.result2 } - return fakeReturns.result1 + return fakeReturns.result1, fakeReturns.result2 } -func (fake *FakeLocalMediaTrack) GetConnectionScoreCallCount() int { - fake.getConnectionScoreMutex.RLock() - defer fake.getConnectionScoreMutex.RUnlock() - return len(fake.getConnectionScoreArgsForCall) +func (fake *FakeLocalMediaTrack) GetConnectionScoreAndQualityCallCount() int { + fake.getConnectionScoreAndQualityMutex.RLock() + defer fake.getConnectionScoreAndQualityMutex.RUnlock() + return len(fake.getConnectionScoreAndQualityArgsForCall) } -func (fake *FakeLocalMediaTrack) GetConnectionScoreCalls(stub func() float32) { - fake.getConnectionScoreMutex.Lock() - defer fake.getConnectionScoreMutex.Unlock() - fake.GetConnectionScoreStub = stub +func (fake *FakeLocalMediaTrack) GetConnectionScoreAndQualityCalls(stub func() (float32, livekit.ConnectionQuality)) { + fake.getConnectionScoreAndQualityMutex.Lock() + defer fake.getConnectionScoreAndQualityMutex.Unlock() + fake.GetConnectionScoreAndQualityStub = stub } -func (fake *FakeLocalMediaTrack) GetConnectionScoreReturns(result1 float32) { - fake.getConnectionScoreMutex.Lock() - defer fake.getConnectionScoreMutex.Unlock() - fake.GetConnectionScoreStub = nil - fake.getConnectionScoreReturns = struct { +func (fake *FakeLocalMediaTrack) GetConnectionScoreAndQualityReturns(result1 float32, result2 livekit.ConnectionQuality) { + fake.getConnectionScoreAndQualityMutex.Lock() + defer fake.getConnectionScoreAndQualityMutex.Unlock() + fake.GetConnectionScoreAndQualityStub = nil + fake.getConnectionScoreAndQualityReturns = struct { result1 float32 - }{result1} + result2 livekit.ConnectionQuality + }{result1, result2} } -func (fake *FakeLocalMediaTrack) GetConnectionScoreReturnsOnCall(i int, result1 float32) { - fake.getConnectionScoreMutex.Lock() - defer fake.getConnectionScoreMutex.Unlock() - fake.GetConnectionScoreStub = nil - if fake.getConnectionScoreReturnsOnCall == nil { - fake.getConnectionScoreReturnsOnCall = make(map[int]struct { +func (fake *FakeLocalMediaTrack) GetConnectionScoreAndQualityReturnsOnCall(i int, result1 float32, result2 livekit.ConnectionQuality) { + fake.getConnectionScoreAndQualityMutex.Lock() + defer fake.getConnectionScoreAndQualityMutex.Unlock() + fake.GetConnectionScoreAndQualityStub = nil + if fake.getConnectionScoreAndQualityReturnsOnCall == nil { + fake.getConnectionScoreAndQualityReturnsOnCall = make(map[int]struct { result1 float32 + result2 livekit.ConnectionQuality }) } - fake.getConnectionScoreReturnsOnCall[i] = struct { + fake.getConnectionScoreAndQualityReturnsOnCall[i] = struct { result1 float32 - }{result1} + result2 livekit.ConnectionQuality + }{result1, result2} } func (fake *FakeLocalMediaTrack) GetNumSubscribers() int { @@ -1930,8 +1935,8 @@ func (fake *FakeLocalMediaTrack) Invocations() map[string][][]interface{} { defer fake.getAllSubscribersMutex.RUnlock() fake.getAudioLevelMutex.RLock() defer fake.getAudioLevelMutex.RUnlock() - fake.getConnectionScoreMutex.RLock() - defer fake.getConnectionScoreMutex.RUnlock() + fake.getConnectionScoreAndQualityMutex.RLock() + defer fake.getConnectionScoreAndQualityMutex.RUnlock() fake.getNumSubscribersMutex.RLock() defer fake.getNumSubscribersMutex.RUnlock() fake.getQualityForDimensionMutex.RLock() diff --git a/pkg/rtc/wrappedreceiver.go b/pkg/rtc/wrappedreceiver.go index 84ac7108..b962ba80 100644 --- a/pkg/rtc/wrappedreceiver.go +++ b/pkg/rtc/wrappedreceiver.go @@ -259,13 +259,6 @@ func (d *DummyReceiver) DebugInfo() map[string]interface{} { return nil } -func (d *DummyReceiver) GetLayerDimension(quality int32) (uint32, uint32) { - if r, ok := d.receiver.Load().(sfu.TrackReceiver); ok { - return r.GetLayerDimension(quality) - } - return 0, 0 -} - func (d *DummyReceiver) GetTemporalLayerFpsForSpatial(spatial int32) []float32 { if r, ok := d.receiver.Load().(sfu.TrackReceiver); ok { return r.GetTemporalLayerFpsForSpatial(spatial) diff --git a/pkg/sfu/buffer/rtpstats.go b/pkg/sfu/buffer/rtpstats.go index f0749f5c..0f093a2b 100644 --- a/pkg/sfu/buffer/rtpstats.go +++ b/pkg/sfu/buffer/rtpstats.go @@ -42,6 +42,7 @@ type IntervalStats struct { } type RTPDeltaInfo struct { + StartTime time.Time Duration time.Duration Packets uint32 Bytes uint64 @@ -270,7 +271,8 @@ func (r *RTPStats) Seed(from *RTPStats) { r.nextSnapshotId = from.nextSnapshotId for id, ss := range from.snapshots { - r.snapshots[id] = ss + ssCopy := *ss + r.snapshots[id] = &ssCopy } } @@ -331,7 +333,7 @@ func (r *RTPStats) Update(rtph *rtp.Header, payloadSize int, paddingSize int, pa // initialize snapshots if any for i := uint32(FirstSnapshotId); i < r.nextSnapshotId; i++ { - r.snapshots[i] = &Snapshot{extStartSN: r.extStartSN} + r.snapshots[i] = &Snapshot{startTime: r.startTime, extStartSN: r.extStartSN} } } @@ -868,10 +870,24 @@ func (r *RTPStats) DeltaInfo(snapshotId uint32) *RTPDeltaInfo { packetsLost := uint32(0) intervalStats := r.getIntervalStats(uint16(then.extStartSN), uint16(now.extStartSN)) if r.params.IsReceiverReportDriven { + // by taking number of packets from interval report, packets not sent (because of missing packets in feed) will be accounted for + packetsExpected = intervalStats.packets + intervalStats.packetsPadding + if packetsExpected == 0 { + return nil + } + packetsLost = now.packetsLostOverridden - then.packetsLostOverridden if int32(packetsLost) < 0 { packetsLost = 0 } + + if packetsLost > packetsExpected { + r.logger.Warnw( + "unexpected number of packets lost", + fmt.Errorf("start: %d, end: %d, expected: %d, lost: %d", then.extStartSN, now.extStartSN, packetsExpected, packetsLost), + ) + packetsLost = packetsExpected + } } else { packetsLost = intervalStats.packetsLost } @@ -883,6 +899,7 @@ func (r *RTPStats) DeltaInfo(snapshotId uint32) *RTPDeltaInfo { maxJitterTime := maxJitter / float64(r.params.ClockRate) * 1e6 return &RTPDeltaInfo{ + StartTime: then.startTime, Duration: now.startTime.Sub(then.startTime), Packets: packetsExpected - intervalStats.packetsPadding, Bytes: intervalStats.bytes, @@ -1254,6 +1271,7 @@ func (r *RTPStats) getAndResetSnapshot(snapshotId uint32) (*Snapshot, *Snapshot) then := r.snapshots[snapshotId] if then == nil { then = &Snapshot{ + startTime: r.startTime, extStartSN: r.extStartSN, } r.snapshots[snapshotId] = then diff --git a/pkg/sfu/connectionquality/connectionstats.go b/pkg/sfu/connectionquality/connectionstats.go index bb25d697..dd1c085b 100644 --- a/pkg/sfu/connectionquality/connectionstats.go +++ b/pkg/sfu/connectionquality/connectionstats.go @@ -2,13 +2,13 @@ package connectionquality import ( "strings" - "sync" "time" - "go.uber.org/atomic" + "github.com/frostbyte73/core" "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" + "github.com/pion/webrtc/v3" "github.com/livekit/livekit-server/pkg/sfu/buffer" ) @@ -19,240 +19,96 @@ const ( ) type ConnectionStatsParams struct { - UpdateInterval time.Duration - MimeType string - GetDeltaStats func() map[uint32]*buffer.StreamStatsWithLayers - GetMaxExpectedLayer func() int32 - GetCurrentLayerSpatial func() int32 - GetIsReducedQuality func() (int32, bool) - Logger logger.Logger + UpdateInterval time.Duration + MimeType string + IsFECEnabled bool + GetDeltaStats func() map[uint32]*buffer.StreamStatsWithLayers + Logger logger.Logger } type ConnectionStats struct { - params ConnectionStatsParams - codecName string - trackInfo *livekit.TrackInfo - normFactors [buffer.DefaultMaxLayerSpatial + 1]float32 + params ConnectionStatsParams + trackInfo *livekit.TrackInfo onStatsUpdate func(cs *ConnectionStats, stat *livekit.AnalyticsStat) - lock sync.RWMutex - score float32 - lastUpdate time.Time - maxExpectedLayer int32 + scorer *qualityScorer - done chan struct{} - isClosed atomic.Bool + done core.Fuse } func NewConnectionStats(params ConnectionStatsParams) *ConnectionStats { return &ConnectionStats{ - params: params, - codecName: getCodecNameFromMime(params.MimeType), // LK-TODO: have to notify on codec change - normFactors: [buffer.DefaultMaxLayerSpatial + 1]float32{1, 1, 1}, - score: MaxScore, - maxExpectedLayer: buffer.InvalidLayerSpatial, - done: make(chan struct{}), + params: params, + scorer: newQualityScorer(qualityScorerParams{ + PacketLossWeight: getPacketLossWeight(params.MimeType, params.IsFECEnabled), // LK-TODO: have to notify codec change? + Logger: params.Logger, + }), + done: core.NewFuse(), } } -func (cs *ConnectionStats) Start(trackInfo *livekit.TrackInfo) { - cs.lock.Lock() +func (cs *ConnectionStats) Start(trackInfo *livekit.TrackInfo, at time.Time) { cs.trackInfo = trackInfo - // - // get best score and calculate normalization factor. - // Raitonale: MOS modeling will yield a max score for a specific codec. - // That is outside the control of an SFU. SFU can impair quality due - // network issues. So, get the maximum for given codec and normalize - // it to the highest score. So, under perfect conditions, it will - // yield a MOS of 5 which is the highest rating. Any SFU induced impairment - // or network impairment will result in a lower score and that is - // the quality that is under SFU/infrastructure control. - // - if trackInfo.Type == livekit.TrackType_AUDIO { - // LK-TODO: would be good to have audio expected bitrate in Trackinfo - params := TrackScoreParams{ - Duration: time.Second, - Codec: cs.codecName, - Bytes: 20000 / 8, - } - cs.normFactors[0] = MaxScore / AudioTrackScore(params, 1) - } else { - for _, layer := range cs.trackInfo.Layers { - spatial := buffer.VideoQualityToSpatialLayer(layer.Quality, cs.trackInfo) - // LK-TODO: would be good to have expected frame rate in Trackinfo - frameRate := uint32(30) - switch spatial { - case 0: - frameRate = 15 - case 1: - frameRate = 20 - } - params := TrackScoreParams{ - Duration: time.Second, - Codec: cs.codecName, - Bytes: uint64(layer.Bitrate) / 8, - Width: layer.Width, - Height: layer.Height, - Frames: frameRate, - } - cs.normFactors[spatial] = MaxScore / VideoTrackScore(params, 1) - } - } - cs.lock.Unlock() + cs.scorer.Start(at) go cs.updateStatsWorker() } func (cs *ConnectionStats) Close() { - if cs.isClosed.Swap(true) { - return - } - - close(cs.done) + cs.done.Break() } func (cs *ConnectionStats) OnStatsUpdate(fn func(cs *ConnectionStats, stat *livekit.AnalyticsStat)) { cs.onStatsUpdate = fn } -func (cs *ConnectionStats) GetScore() float32 { - cs.lock.RLock() - defer cs.lock.RUnlock() - - return cs.score +func (cs *ConnectionStats) UpdateMute(isMuted bool, at time.Time) { + cs.scorer.UpdateMute(isMuted, at) } -func (cs *ConnectionStats) getLayerDimensions(layer int32) (uint32, uint32) { - if cs.trackInfo == nil { - return 0, 0 - } - - for _, l := range cs.trackInfo.Layers { - if layer == buffer.VideoQualityToSpatialLayer(l.Quality, cs.trackInfo) { - return l.Width, l.Height - } - } - - return 0, 0 +func (cs *ConnectionStats) AddTransition(bitrate int64, at time.Time) { + cs.scorer.AddTransition(bitrate, at) } -func (cs *ConnectionStats) updateScore(streams map[uint32]*buffer.StreamStatsWithLayers) float32 { - cs.lock.Lock() - defer cs.lock.Unlock() - - // Initial interval will have partial data - if cs.lastUpdate.IsZero() { - cs.lastUpdate = time.Now() - cs.score = MaxScore - return cs.score - } - - cs.lastUpdate = time.Now() - - var params TrackScoreParams - switch { - case cs.trackInfo.Type == livekit.TrackType_AUDIO: - maxAvailableLayer, maxAvailableLayerStats := getMaxAvailableLayerStats(streams, 0) - if maxAvailableLayerStats == nil { - // retain old score as stats will not be available when muted - break - } - - params = getTrackScoreParams(cs.codecName, maxAvailableLayerStats) - packetRate := float64(params.PacketsExpected) / maxAvailableLayerStats.Duration.Seconds() - if packetRate < audioPacketRateThreshold { - // With DTX, it is possible to have fewer packets per second. - // A loss with reduced packet rate has amplified negative effect on quality. - // Opus uses 20 ms packetisation (50 pps). Calculate score only if packet rate is at least half of that. - break - } - - normFactor := float32(1) - if int(maxAvailableLayer) < len(cs.normFactors) { - normFactor = cs.normFactors[maxAvailableLayer] - } - cs.score = AudioTrackScore(params, normFactor) - - case cs.trackInfo.Type == livekit.TrackType_VIDEO: - // - // See note below about muxed tracks quality calculation challenges. - // - // This part concerns simulcast + dynacast challeges. - // A sub-optimal solution is to measure only in windows where the max layer is stable. - // With adaptive stream, it is possible that subscription changes max layer. - // When expected layer changes from low -> high, the stats in that window - // (when the change happens) will correspond to lower layer at least partially. - // Using that to calculate against expected higher layer could result in lower score. - // - maxExpectedLayer := cs.params.GetMaxExpectedLayer() - if maxExpectedLayer == buffer.InvalidLayerSpatial || maxExpectedLayer != cs.maxExpectedLayer { - cs.maxExpectedLayer = maxExpectedLayer - if maxExpectedLayer == buffer.InvalidLayerSpatial { - // if not expecting data, reset the score to maximum - cs.score = MaxScore - } - break - } - - cs.maxExpectedLayer = maxExpectedLayer - - maxAvailableLayer, maxAvailableLayerStats := getMaxAvailableLayerStats(streams, maxExpectedLayer) - if maxAvailableLayerStats == nil { - // retain old score as stats will not be available when muted - break - } - - params = getTrackScoreParams(cs.codecName, maxAvailableLayerStats) - - // for muxed tracks, i. e. simulcast publisher muxed into a single track, - // use the current spatial layer. - // NOTE: This is still not perfect as muxing means layers could have changed - // in the analysis window. Needs a more complex design to keep track of all layer - // switches to be able to do precise calculations. As the window is small, - // using the current and maximum is a reasonable approximation. - if cs.params.GetCurrentLayerSpatial != nil { - maxAvailableLayer = cs.params.GetCurrentLayerSpatial() - if maxAvailableLayer == buffer.InvalidLayerSpatial { - // retain old score as stats will not be available if not forwarding - break - } - } - params.Width, params.Height = cs.getLayerDimensions(maxAvailableLayer) - if cs.trackInfo.Source == livekit.TrackSource_SCREEN_SHARE || params.Width == 0 || params.Height == 0 { - if cs.params.GetIsReducedQuality != nil { - _, params.IsReducedQuality = cs.params.GetIsReducedQuality() - } - - cs.score = LossBasedTrackScore(params) - } else { - normFactor := float32(1) - if int(maxAvailableLayer) < len(cs.normFactors) { - normFactor = cs.normFactors[maxAvailableLayer] - } - cs.score = VideoTrackScore(params, normFactor) - if cs.params.GetIsReducedQuality != nil { - // penalty of one level per layer away from desired/expected layer - distanceToDesired, isDeficient := cs.params.GetIsReducedQuality() - if isDeficient { - cs.score -= float32(distanceToDesired) - } - cs.score = float32(clamp(float64(cs.score), float64(MinScore), float64(MaxScore))) - } - } - } - - return cs.score +func (cs *ConnectionStats) GetScoreAndQuality() (float32, livekit.ConnectionQuality) { + return cs.scorer.GetMOSAndQuality() } -func (cs *ConnectionStats) getStat() *livekit.AnalyticsStat { +func (cs *ConnectionStats) updateScore(streams map[uint32]*buffer.StreamStatsWithLayers, at time.Time) float32 { + var stat windowStat + for _, s := range streams { + if stat.startedAt.IsZero() || stat.startedAt.After(s.RTPStats.StartTime) { + stat.startedAt = s.RTPStats.StartTime + } + if stat.duration < s.RTPStats.Duration { + stat.duration = s.RTPStats.Duration + } + stat.packetsExpected += s.RTPStats.Packets + s.RTPStats.PacketsPadding + stat.packetsLost += s.RTPStats.PacketsLost + if stat.rttMax < s.RTPStats.RttMax { + stat.rttMax = s.RTPStats.RttMax + } + if stat.jitterMax < s.RTPStats.JitterMax { + stat.jitterMax = s.RTPStats.JitterMax + } + stat.bytes += s.RTPStats.Bytes - s.RTPStats.HeaderBytes // only use media payload size + } + cs.scorer.Update(&stat, at) + + mos, _ := cs.scorer.GetMOSAndQuality() + return mos +} + +func (cs *ConnectionStats) getStat(at time.Time) *livekit.AnalyticsStat { if cs.params.GetDeltaStats == nil { return nil } streams := cs.params.GetDeltaStats() if len(streams) == 0 { + cs.updateScore(streams, at) return nil } @@ -274,7 +130,7 @@ func (cs *ConnectionStats) getStat() *livekit.AnalyticsStat { analyticsStreams = append(analyticsStreams, as) } - score := cs.updateScore(streams) + score := cs.updateScore(streams, at) return &livekit.AnalyticsStat{ Score: score, @@ -294,11 +150,15 @@ func (cs *ConnectionStats) updateStatsWorker() { for { select { - case <-cs.done: + case <-cs.done.Watch(): return case <-tk.C: - stat := cs.getStat() + if cs.done.IsClosed() { + return + } + + stat := cs.getStat(time.Now()) if stat == nil { continue } @@ -312,13 +172,39 @@ func (cs *ConnectionStats) updateStatsWorker() { // ----------------------------------------------------------------------- -func getCodecNameFromMime(mime string) string { - codecName := "" - codecParsed := strings.Split(strings.ToLower(mime), "/") - if len(codecParsed) > 1 { - codecName = codecParsed[1] +// how much weight to give to packet loss rate when calculating score. +// It is codec dependent. +// For audio: +// o Opus without FEC or RED suffers the most through packet loss, hence has the highest weight +// o RED with two packet redundancy can absorb two out of every three packets lost, so packet loss is not as detrimental and therefore lower weight +// +// For video: +// o No in-built codec repair available, hence same for all codecs +func getPacketLossWeight(mimeType string, isFecEnabled bool) float64 { + plw := float64(0.0) + switch { + case strings.EqualFold(mimeType, webrtc.MimeTypeOpus): + // 2.5%: fall to GOOD, 5%: fall to POOR + plw = 8.0 + if isFecEnabled { + // 3.75%: fall to GOOD, 7.5%: fall to POOR + plw /= 1.5 + } + + case strings.EqualFold(mimeType, "audio/red"): + // 6.66%: fall to GOOD, 13.33%: fall to POOR + plw = 3.0 + if isFecEnabled { + // 10%: fall to GOOD, 20%: fall to POOR + plw /= 1.5 + } + + case strings.HasPrefix(strings.ToLower(mimeType), "video/"): + // 2%: fall to GOOD, 4%: fall to POOR + plw = 10.0 } - return codecName + + return plw } func toAnalyticsStream(ssrc uint32, deltaStats *buffer.RTPDeltaInfo) *livekit.AnalyticsStream { @@ -348,35 +234,3 @@ func toAnalyticsVideoLayer(layer int32, layerStats *buffer.RTPDeltaInfo) *liveki Frames: layerStats.Frames, } } - -func getMaxAvailableLayerStats(streams map[uint32]*buffer.StreamStatsWithLayers, maxExpectedLayer int32) (int32, *buffer.RTPDeltaInfo) { - maxAvailableLayer := buffer.InvalidLayerSpatial - var maxAvailableLayerStats *buffer.RTPDeltaInfo - for _, stream := range streams { - for layer, layerStats := range stream.Layers { - if maxExpectedLayer == buffer.InvalidLayerSpatial || int32(layer) > maxExpectedLayer { - continue - } - - if int32(layer) > maxAvailableLayer { - maxAvailableLayer = int32(layer) - maxAvailableLayerStats = layerStats - } - } - } - - return maxAvailableLayer, maxAvailableLayerStats -} - -func getTrackScoreParams(codec string, layerStats *buffer.RTPDeltaInfo) TrackScoreParams { - return TrackScoreParams{ - Duration: layerStats.Duration, - Codec: codec, - PacketsExpected: layerStats.Packets + layerStats.PacketsPadding, - PacketsLost: layerStats.PacketsLost, - Bytes: layerStats.Bytes - layerStats.HeaderBytes, // only use media payload size - Frames: layerStats.Frames, - Jitter: layerStats.JitterMax, - Rtt: layerStats.RttMax, - } -} diff --git a/pkg/sfu/connectionquality/connectionstats_test.go b/pkg/sfu/connectionquality/connectionstats_test.go index 031d3110..7af09f19 100644 --- a/pkg/sfu/connectionquality/connectionstats_test.go +++ b/pkg/sfu/connectionquality/connectionstats_test.go @@ -6,473 +6,608 @@ import ( "github.com/livekit/livekit-server/pkg/sfu/buffer" "github.com/livekit/protocol/livekit" + "github.com/livekit/protocol/logger" "github.com/stretchr/testify/require" ) +func newConnectionStats(mimeType string, isFECEnabled bool) *ConnectionStats { + return NewConnectionStats(ConnectionStatsParams{ + MimeType: mimeType, + IsFECEnabled: isFECEnabled, + Logger: logger.GetLogger(), + }) +} + func TestConnectionQuality(t *testing.T) { - t.Run("audio quality changes over time", func(t *testing.T) { - cs := NewConnectionStats(ConnectionStatsParams{ - MimeType: "audio/opus", - }) - cs.Start(&livekit.TrackInfo{Type: livekit.TrackType_AUDIO}) + t.Run("quality scorer state machine", func(t *testing.T) { + cs := newConnectionStats("audio/opus", false) + + duration := 5 * time.Second + now := time.Now() + cs.Start(&livekit.TrackInfo{Type: livekit.TrackType_AUDIO}, now.Add(-duration)) + cs.UpdateMute(false, now.Add(-1*time.Second)) - // first update does nothing - cs.updateScore(nil) - require.Equal(t, float32(5), cs.GetScore()) + // no data and not enough unmute time should return default state which is EXCELLENT quality + cs.updateScore(nil, now) + mos, quality := cs.GetScoreAndQuality() + require.Greater(t, float32(4.6), mos) + require.Equal(t, livekit.ConnectionQuality_EXCELLENT, quality) - // perfect conditions should return a score of 5 + // best conditions (no loss, jitter/rtt = 0) - quality should stay EXCELLENT streams := map[uint32]*buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 0: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - Bytes: 20000 * 2 / 8, // 20 kbps - }, + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 250, }, }, } - cs.updateScore(streams) - require.Equal(t, float32(5), cs.GetScore()) + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(4.6), mos) + require.Equal(t, livekit.ConnectionQuality_EXCELLENT, quality) - // introduce loss and the score should drop + // introduce loss and the score should drop - 10% loss for Opus -> POOR + now = now.Add(duration) streams = map[uint32]*buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 0: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - PacketsLost: 10, - Bytes: 18000 * 2 / 8, // 20 kbps - 2 kbps, i. e 10% lost - }, + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 250, + PacketsLost: 25, }, }, } - cs.updateScore(streams) - lossQuality := cs.GetScore() - require.Less(t, lossQuality, float32(3.55)) - - // small packet rate, should avoid calculation as it does not meet DTX threshold - streams = map[uint32]*buffer.StreamStatsWithLayers{ - 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 0: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 44, - PacketsLost: 4, - Bytes: 1000 * 2 / 8, // 1 kbps, DTX + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(3.2), mos) + require.Equal(t, livekit.ConnectionQuality_POOR, quality) + + // should stay at POOR quality for poor threshold wait even if the conditions improve + for i := 0; i < 3; i++ { + now = now.Add(duration) + streams = map[uint32]*buffer.StreamStatsWithLayers{ + 1: &buffer.StreamStatsWithLayers{ + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 250, }, }, - }, + } + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(3.2), mos) + require.Equal(t, livekit.ConnectionQuality_POOR, quality) } - cs.updateScore(streams) - require.Equal(t, lossQuality, cs.GetScore()) - // setting RTT (i. e. adding delay) should reduce quality + // should return median quality which should be EXCELLENT as all windows in above loop have great conditions + now = now.Add(duration) streams = map[uint32]*buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 0: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - PacketsLost: 10, - Bytes: 18000 * 2 / 8, // 20 kbps - 2 kbps, i. e 10% lost - RttMax: 50, // ms - }, + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 250, }, }, } - cs.updateScore(streams) - rttQuality := cs.GetScore() - require.Less(t, rttQuality, lossQuality) + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(4.6), mos) + require.Equal(t, livekit.ConnectionQuality_EXCELLENT, quality) - // adding jitter (i. e. more delay) should reduce quality + // introduce loss and the score should drop - 3% loss for Opus -> GOOD + now = now.Add(duration) streams = map[uint32]*buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 0: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - PacketsLost: 10, - Bytes: 18000 * 2 / 8, // 20 kbps - 2 kbps, i. e 10% lost - RttMax: 50, // ms - JitterMax: 10000, // us - }, + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 250, + PacketsLost: 8, }, }, } - cs.updateScore(streams) - require.Less(t, cs.GetScore(), rttQuality) - }) - - t.Run("video quality changes over time", func(t *testing.T) { - maxExpectedLayer := int32(0) - currentLayer := int32(0) - isReducedQuality := false - - cs := NewConnectionStats(ConnectionStatsParams{ - MimeType: "video/VP8", - GetMaxExpectedLayer: func() int32 { - return maxExpectedLayer - }, - GetIsReducedQuality: func() (int32, bool) { - return maxExpectedLayer - currentLayer, isReducedQuality - }, - }) - cs.Start(&livekit.TrackInfo{ - Type: livekit.TrackType_VIDEO, - Source: livekit.TrackSource_CAMERA, - Layers: []*livekit.VideoLayer{ - { - Quality: livekit.VideoQuality_HIGH, - Width: 1280, - Height: 720, - Bitrate: 1_700_000, + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(4.1), mos) + require.Equal(t, livekit.ConnectionQuality_GOOD, quality) + + // should stay at GOOD quality for good threshold (which is shorter than poor threshold) wait even if the conditions improve + for i := 0; i < 1; i++ { + now = now.Add(duration) + streams = map[uint32]*buffer.StreamStatsWithLayers{ + 1: &buffer.StreamStatsWithLayers{ + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 250, + }, }, - { - Quality: livekit.VideoQuality_MEDIUM, - Width: 640, - Height: 360, - Bitrate: 500_000, - }, - { - Quality: livekit.VideoQuality_LOW, - Width: 320, - Height: 180, - Bitrate: 150_000, - }, - }, - }) + } + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(4.1), mos) + require.Equal(t, livekit.ConnectionQuality_GOOD, quality) + } - // first update does nothing - cs.updateScore(nil) - require.Equal(t, float32(5), cs.GetScore()) - - // second update locks to expected layer - cs.updateScore(nil) - require.Equal(t, float32(5), cs.GetScore()) - - // layer 0 perfect score - streams := map[uint32]*buffer.StreamStatsWithLayers{ + // should return median quality which should be EXCELLENT as all windows in above loop have great conditions + now = now.Add(duration) + streams = map[uint32]*buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 0: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - Bytes: 150_000 * 2 / 8, // 150 kbps - Frames: 30, // 15 fps - }, + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 250, }, }, } - cs.updateScore(streams) - require.Equal(t, float32(5), cs.GetScore()) - - maxExpectedLayer = 1 - currentLayer = 1 - // update locks to expected layer and returns previous score - cs.updateScore(nil) - require.Equal(t, float32(5), cs.GetScore()) + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(4.6), mos) + require.Equal(t, livekit.ConnectionQuality_EXCELLENT, quality) - // layer 1 at layer 0 bitrate should give lower score + // POOR -> GOOD -> EXCELLENT should take longer + now = now.Add(duration) streams = map[uint32]*buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 1: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - Bytes: 150_000 * 2 / 8, // 150 kbps - Frames: 30, // 15 fps - }, + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 250, + PacketsLost: 25, }, }, } - cs.updateScore(streams) - require.Less(t, cs.GetScore(), float32(5)) - - // layer 1 at optimal bit rate should give max score - streams = map[uint32]*buffer.StreamStatsWithLayers{ - 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 1: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - Bytes: 500_000 * 2 / 8, // 500 kbps - Frames: 40, // 20 fps + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(3.2), mos) + require.Equal(t, livekit.ConnectionQuality_POOR, quality) + + // should stay at POOR quality for poor threshold wait even if the conditions improve + for i := 0; i < 3; i++ { + now = now.Add(duration) + streams = map[uint32]*buffer.StreamStatsWithLayers{ + 1: &buffer.StreamStatsWithLayers{ + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 250, + PacketsLost: 8, }, }, - }, + } + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(3.2), mos) + require.Equal(t, livekit.ConnectionQuality_POOR, quality) } - cs.updateScore(streams) - require.Equal(t, float32(5), cs.GetScore()) - // a layer at higher than optimal bit rate should give max score + // should return median quality which should be GOOD as all windows in above loop have some loss (i. e. GOOD quality). + // although the below update has no loss (EXCELLENT quality), median should be at GOOO + now = now.Add(duration) streams = map[uint32]*buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 1: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - Bytes: 600_000 * 2 / 8, // 600 kbps, optimal is 500 kbps - Frames: 40, // 20 fps - }, + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 250, }, }, } - cs.updateScore(streams) - require.Equal(t, float32(5), cs.GetScore()) + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(4.1), mos) + require.Equal(t, livekit.ConnectionQuality_GOOD, quality) - maxExpectedLayer = 2 - currentLayer = 2 - // update locks to expected layer and returns previous score - cs.updateScore(nil) - require.Equal(t, float32(5), cs.GetScore()) - - // layer 2 at layer 1 bitrate should give lower score + // another EXCELLENT quality window and the median should switch to EXCELLENT + now = now.Add(duration) streams = map[uint32]*buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 2: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - Bytes: 500_000 * 2 / 8, // 500 kbps - Frames: 40, // 20 fps - }, + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 250, }, }, } - cs.updateScore(streams) - require.Less(t, cs.GetScore(), float32(5)) + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(4.6), mos) + require.Equal(t, livekit.ConnectionQuality_EXCELLENT, quality) - // layer 2 at optimal bit rate should give max score + // mute when quality is POOR should return quality to EXCELLENT + now = now.Add(duration) streams = map[uint32]*buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 2: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - Bytes: 1_700_000 * 2 / 8, // 1.7 Mbps - Frames: 60, // 30 fps - }, + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 250, + PacketsLost: 25, }, }, } - cs.updateScore(streams) - require.Equal(t, float32(5), cs.GetScore()) + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(3.2), mos) + require.Equal(t, livekit.ConnectionQuality_POOR, quality) - // layer 2 at optimal bit rate, but with loss should give less score + now = now.Add(duration) + cs.UpdateMute(true, now.Add(1*time.Second)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(4.6), mos) + require.Equal(t, livekit.ConnectionQuality_EXCELLENT, quality) + + // unmute at time so that next window does not satisfy the unmute time threshold. + // that means even if the next update has 0 packets, it should hold state and stay at EXCELLENT quality + cs.UpdateMute(false, now.Add(3*time.Second)) + streams = map[uint32]*buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 2: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - Bytes: 1_530_000 * 2 / 8, // 1.7 Mbps - 170 kbps, i. e. 10% loss - Frames: 60, // 30 fps - }, + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 0, }, }, } - cs.updateScore(streams) - score := cs.GetScore() - require.Less(t, score, float32(5)) + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(4.6), mos) + require.Equal(t, livekit.ConnectionQuality_EXCELLENT, quality) - // adding rtt (i. e. delay) should reduce score further + // next update with no packets should knock quality down + now = now.Add(duration) streams = map[uint32]*buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 2: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - Bytes: 1_530_000 * 2 / 8, // 1.7 Mbps - 170 kbps, i. e. 10% loss - Frames: 60, // 30 fps - RttMax: 50, // ms - }, + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 0, }, }, } - cs.updateScore(streams) - require.Less(t, cs.GetScore(), score) - score = cs.GetScore() - - // adding jitter (i. e. delay) should reduce score further + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(3.2), mos) + require.Equal(t, livekit.ConnectionQuality_POOR, quality) + + // mute/unmute to bring quality back up + now = now.Add(duration) + cs.UpdateMute(true, now.Add(1*time.Second)) + cs.UpdateMute(false, now.Add(2*time.Second)) + + // with lesser number of packet (simulating DTX). + // even higher loss (like 10%) should only knock down quality to GOOD, typically would be POOR at that loss rate streams = map[uint32]*buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 2: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - Bytes: 1_530_000 * 2 / 8, // 1.7 Mbps - 170 kbps, i. e. 10% loss - Frames: 60, // 30 fps - RttMax: 50, // ms - JitterMax: 10000, // us - }, + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 50, + PacketsLost: 5, }, }, } - cs.updateScore(streams) - require.Less(t, cs.GetScore(), score) - - // layer 2 max expected, but max available is layer 1 should reduce one level even if layer 1 is perfect - currentLayer = 1 + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(4.1), mos) + require.Equal(t, livekit.ConnectionQuality_GOOD, quality) + + // mute/unmute to bring quality back up + now = now.Add(duration) + cs.UpdateMute(true, now.Add(1*time.Second)) + cs.UpdateMute(false, now.Add(2*time.Second)) + + // RTT and jitter can knock quality down. + // at 2% loss, quality should stay at EXCELLENT purely based on loss, but with added RTT/jitter, should drop to GOOD streams = map[uint32]*buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 1: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - Bytes: 500_000 * 2 / 8, // 500 kbps - Frames: 40, // 20 fps - }, + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 250, + PacketsLost: 5, + RttMax: 300, + JitterMax: 30000, }, }, } - cs.updateScore(streams) - require.Less(t, float32(4), cs.GetScore()) + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(4.1), mos) + require.Equal(t, livekit.ConnectionQuality_GOOD, quality) + + // mute/unmute to bring quality back up + now = now.Add(duration) + cs.UpdateMute(true, now.Add(1*time.Second)) + cs.UpdateMute(false, now.Add(2*time.Second)) - // layer 2 max expected, but max available is layer 0 should reduce two levels even if layer 0 is perfect - currentLayer = 0 + // bitrate based calculation can drop quality even if there is no loss + cs.AddTransition(1_000_000, now) + cs.AddTransition(2_000_000, now.Add(2*time.Second)) + streams = map[uint32]*buffer.StreamStatsWithLayers{ - 0: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 0: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - Bytes: 150_000 * 2 / 8, // 150 kbps - Frames: 30, // 15 fps - }, + 1: &buffer.StreamStatsWithLayers{ + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 250, + Bytes: 8_000_000 / 8 / 4, }, }, } - cs.updateScore(streams) - require.Less(t, float32(3), cs.GetScore()) + cs.updateScore(streams, now.Add(duration)) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(4.1), mos) + require.Equal(t, livekit.ConnectionQuality_GOOD, quality) + + // a transition to 0 (all layers stopped) should flip quality to EXCELLENT + now = now.Add(duration) + cs.AddTransition(0, now) + mos, quality = cs.GetScoreAndQuality() + require.Greater(t, float32(4.6), mos) + require.Equal(t, livekit.ConnectionQuality_EXCELLENT, quality) }) - t.Run("screen share quality changes over time", func(t *testing.T) { - isReducedQuality := false - - cs := NewConnectionStats(ConnectionStatsParams{ - MimeType: "video/H264", - GetMaxExpectedLayer: func() int32 { - return 1 + t.Run("codecs - packets", func(t *testing.T) { + type expectedQuality struct { + packetLossPercentage float64 + expectedMOS float32 + expectedQuality livekit.ConnectionQuality + } + testCases := []struct { + name string + mimeType string + isFECEnabled bool + packetsExpected uint32 + expectedQualities []expectedQuality + }{ + // "audio/opus" - no fec - 0 <= loss < 2.5%: EXCELLENT, 2.5% <= loss < 5%: GOOD, >= 5%: POOR + { + name: "audio/opus - no fec", + mimeType: "audio/opus", + isFECEnabled: false, + packetsExpected: 200, + expectedQualities: []expectedQuality{ + { + packetLossPercentage: 1.0, + expectedMOS: 4.6, + expectedQuality: livekit.ConnectionQuality_EXCELLENT, + }, + { + packetLossPercentage: 4.0, + expectedMOS: 4.1, + expectedQuality: livekit.ConnectionQuality_GOOD, + }, + { + packetLossPercentage: 5.0, + expectedMOS: 3.2, + expectedQuality: livekit.ConnectionQuality_POOR, + }, + }, }, - GetIsReducedQuality: func() (int32, bool) { - return 0, isReducedQuality + // "audio/opus" - fec - 0 <= loss < 3.75%: EXCELLENT, 3.75% <= loss < 7.5%: GOOD, >= 7.5%: POOR + { + name: "audio/opus - fec", + mimeType: "audio/opus", + isFECEnabled: true, + packetsExpected: 200, + expectedQualities: []expectedQuality{ + { + packetLossPercentage: 3.0, + expectedMOS: 4.6, + expectedQuality: livekit.ConnectionQuality_EXCELLENT, + }, + { + packetLossPercentage: 4.0, + expectedMOS: 4.1, + expectedQuality: livekit.ConnectionQuality_GOOD, + }, + { + packetLossPercentage: 8.0, + expectedMOS: 3.2, + expectedQuality: livekit.ConnectionQuality_POOR, + }, + }, }, - }) - cs.Start(&livekit.TrackInfo{ - Type: livekit.TrackType_VIDEO, - Source: livekit.TrackSource_SCREEN_SHARE, - Layers: []*livekit.VideoLayer{ - { - Width: 1920, - Height: 1080, + // "audio/red" - no fec - 0 <= loss < 6.66%: EXCELLENT, 6.66% <= loss < 13.33%: GOOD, >= 13.33%: POOR + { + name: "audio/red - no fec", + mimeType: "audio/red", + isFECEnabled: false, + packetsExpected: 200, + expectedQualities: []expectedQuality{ + { + packetLossPercentage: 6.0, + expectedMOS: 4.6, + expectedQuality: livekit.ConnectionQuality_EXCELLENT, + }, + { + packetLossPercentage: 10.0, + expectedMOS: 4.1, + expectedQuality: livekit.ConnectionQuality_GOOD, + }, + { + packetLossPercentage: 16.0, + expectedMOS: 3.2, + expectedQuality: livekit.ConnectionQuality_POOR, + }, }, }, - }) - - // first update does nothing - cs.updateScore(nil) - require.Equal(t, float32(5), cs.GetScore()) - - // second update locks to expected layer - cs.updateScore(nil) - require.Equal(t, float32(5), cs.GetScore()) - - // perfect conditions should return a score of 5 - streams := map[uint32]*buffer.StreamStatsWithLayers{ - 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 0: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - Bytes: 100000 * 2 / 8, // 100 kbps + // "audio/red" - fec - 0 <= loss < 10%: EXCELLENT, 10% <= loss < 20%: GOOD, >= 20%: POOR + { + name: "audio/red - fec", + mimeType: "audio/red", + isFECEnabled: true, + packetsExpected: 200, + expectedQualities: []expectedQuality{ + { + packetLossPercentage: 8.0, + expectedMOS: 4.6, + expectedQuality: livekit.ConnectionQuality_EXCELLENT, + }, + { + packetLossPercentage: 18.0, + expectedMOS: 4.1, + expectedQuality: livekit.ConnectionQuality_GOOD, + }, + { + packetLossPercentage: 20.0, + expectedMOS: 3.2, + expectedQuality: livekit.ConnectionQuality_POOR, }, }, }, - } - cs.updateScore(streams) - require.Equal(t, float32(5), cs.GetScore()) - - // introduce loss and the score should drop - streams = map[uint32]*buffer.StreamStatsWithLayers{ - 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 0: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - PacketsLost: 10, - Bytes: 90000 * 2 / 8, // 100 kbps - 10 kbps, i. e 10% lost + // "video/*" - 0 <= loss < 2%: EXCELLENT, 2% <= loss < 4%: GOOD, >= 4%: POOR + { + name: "video/*", + mimeType: "video/vp8", + isFECEnabled: false, + packetsExpected: 200, + expectedQualities: []expectedQuality{ + { + packetLossPercentage: 1.0, + expectedMOS: 4.6, + expectedQuality: livekit.ConnectionQuality_EXCELLENT, + }, + { + packetLossPercentage: 2.0, + expectedMOS: 4.1, + expectedQuality: livekit.ConnectionQuality_GOOD, + }, + { + packetLossPercentage: 5.0, + expectedMOS: 3.2, + expectedQuality: livekit.ConnectionQuality_POOR, }, }, }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + cs := newConnectionStats(tc.mimeType, tc.isFECEnabled) + + duration := 5 * time.Second + now := time.Now() + cs.Start(&livekit.TrackInfo{Type: livekit.TrackType_AUDIO}, now.Add(-duration)) + + for _, eq := range tc.expectedQualities { + streams := map[uint32]*buffer.StreamStatsWithLayers{ + 123: &buffer.StreamStatsWithLayers{ + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: tc.packetsExpected, + PacketsLost: uint32(eq.packetLossPercentage * float64(tc.packetsExpected) / 100.0), + }, + }, + } + cs.updateScore(streams, now.Add(duration)) + mos, quality := cs.GetScoreAndQuality() + require.Greater(t, eq.expectedMOS, mos) + require.Equal(t, eq.expectedQuality, quality) + + now = now.Add(duration) + } + }) } - cs.updateScore(streams) - require.Equal(t, float32(2.0), cs.GetScore()) + }) - // small loss, but not reduced quality should give a fairly high score - streams = map[uint32]*buffer.StreamStatsWithLayers{ - 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 0: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - PacketsLost: 2, - Bytes: 98000 * 2 / 8, // 100 kbps - 2 kbps, i. e. 2% loss + t.Run("bytes", func(t *testing.T) { + type transition struct { + bitrate int64 + offset time.Duration + } + testCases := []struct { + name string + transitions []transition + bytes uint64 + expectedMOS float32 + expectedQuality livekit.ConnectionQuality + }{ + // 1.0 <= expectedBits / actualBits < ~2.7 = EXCELLENT + // ~2.7 <= expectedBits / actualBits < ~7.5 = GOOD + // expectedBits / actualBits >= ~7.5 = POOR + { + name: "excellent", + transitions: []transition{ + { + bitrate: 1_000_000, + }, + { + bitrate: 2_000_000, + offset: 3 * time.Second, }, }, + bytes: 6_000_000 / 8, + expectedMOS: 4.6, + expectedQuality: livekit.ConnectionQuality_EXCELLENT, }, - } - cs.updateScore(streams) - require.Equal(t, float32(4.5), cs.GetScore()) - - // medium level loss, but not reduced quality should give a mid level score - streams = map[uint32]*buffer.StreamStatsWithLayers{ - 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 0: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - PacketsLost: 3, - Bytes: 97000 * 2 / 8, // 100 kbps - 3 kbps, i. e 3% lost + { + name: "good", + transitions: []transition{ + { + bitrate: 1_000_000, + }, + { + bitrate: 2_000_000, + offset: 3 * time.Second, }, }, + bytes: 7_000_000 / 8 / 3, + expectedMOS: 4.1, + expectedQuality: livekit.ConnectionQuality_GOOD, }, - } - cs.updateScore(streams) - require.Equal(t, float32(3.5), cs.GetScore()) - - // medium level loss, reduced quality should give a mid level score - isReducedQuality = true - streams = map[uint32]*buffer.StreamStatsWithLayers{ - 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 0: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - PacketsLost: 3, - Bytes: 97000 * 2 / 8, // 100 kbps - 3 kbps, i. e 3% lost + { + name: "poor", + transitions: []transition{ + { + bitrate: 2_000_000, + }, + { + bitrate: 1_000_000, + offset: 3 * time.Second, }, }, + bytes: 8_000_000 / 8 / 8, + expectedMOS: 3.2, + expectedQuality: livekit.ConnectionQuality_POOR, }, } - cs.updateScore(streams) - require.Equal(t, float32(3.5), cs.GetScore()) - // small loss, reduced quality should give a mid level score - streams = map[uint32]*buffer.StreamStatsWithLayers{ - 1: &buffer.StreamStatsWithLayers{ - Layers: map[int32]*buffer.RTPDeltaInfo{ - 0: &buffer.RTPDeltaInfo{ - Duration: 2 * time.Second, - Packets: 100, - PacketsLost: 2, - Bytes: 99000 * 2 / 8, // 100 kbps - 1 kbps, i. e 1% lost + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + cs := newConnectionStats("video/vp8", false) + + duration := 5 * time.Second + now := time.Now() + cs.Start(&livekit.TrackInfo{Type: livekit.TrackType_VIDEO}, now) + + for _, tr := range tc.transitions { + cs.AddTransition(tr.bitrate, now.Add(tr.offset)) + } + + streams := map[uint32]*buffer.StreamStatsWithLayers{ + 123: &buffer.StreamStatsWithLayers{ + RTPStats: &buffer.RTPDeltaInfo{ + StartTime: now, + Duration: duration, + Packets: 100, + Bytes: tc.bytes, + }, }, - }, - }, + } + cs.updateScore(streams, now.Add(duration)) + mos, quality := cs.GetScoreAndQuality() + require.Greater(t, tc.expectedMOS, mos) + require.Equal(t, tc.expectedQuality, quality) + }) } - cs.updateScore(streams) - require.Equal(t, float32(3.5), cs.GetScore()) }) } diff --git a/pkg/sfu/connectionquality/mos.go b/pkg/sfu/connectionquality/mos.go deleted file mode 100644 index aca1a93f..00000000 --- a/pkg/sfu/connectionquality/mos.go +++ /dev/null @@ -1,134 +0,0 @@ -package connectionquality - -import ( - "math" - "time" - - "github.com/livekit/protocol/livekit" - "github.com/livekit/rtcscore-go/pkg/rtcmos" -) - -const ( - MinScore = float32(1) - MaxScore = float32(5) -) - -func Score2Rating(score float32) livekit.ConnectionQuality { - if score > 4.0 { - return livekit.ConnectionQuality_EXCELLENT - } - - if score > 3.0 { - return livekit.ConnectionQuality_GOOD - } - return livekit.ConnectionQuality_POOR -} - -func clamp(value, min, max float64) float64 { - return math.Max(min, math.Min(value, max)) -} - -func getBitRate(interval float64, bytes uint64) float64 { - return float64(bytes*8) / interval -} - -func getFrameRate(interval float64, frames uint32) float64 { - return float64(frames) / interval -} - -func getLossPercentage(expected uint32, lost uint32) float32 { - if expected == 0 { - return 0.0 - } - - return float32(lost) * 100.0 / float32(expected) -} - -func int32Ptr(x int32) *int32 { - return &x -} - -func float32Ptr(x float32) *float32 { - return &x -} - -type TrackScoreParams struct { - Duration time.Duration - Codec string - PacketsExpected uint32 - PacketsLost uint32 - Bytes uint64 - Frames uint32 - FrameRateExpected uint32 - Jitter float64 - Rtt uint32 - DtxEnabled bool - Width uint32 - Height uint32 - IsReducedQuality bool -} - -func getRtcMosStat(params TrackScoreParams) rtcmos.Stat { - return rtcmos.Stat{ - Bitrate: float32(getBitRate(params.Duration.Seconds(), params.Bytes)), - PacketLoss: getLossPercentage(params.PacketsExpected, params.PacketsLost), - RoundTripTime: int32Ptr(int32(params.Rtt)), - BufferDelay: int32Ptr(int32(params.Jitter / 1000.0)), - } -} - -func AudioTrackScore(params TrackScoreParams, normFactor float32) float32 { - stat := getRtcMosStat(params) - stat.AudioConfig = &rtcmos.AudioConfig{} - stat.AudioConfig.Dtx = ¶ms.DtxEnabled - - scores := rtcmos.Score([]rtcmos.Stat{stat}) - if len(scores) == 1 { - return float32(clamp(float64(float32(scores[0].AudioScore)*normFactor), float64(MinScore), float64(MaxScore))) - } - return 0 -} - -func VideoTrackScore(params TrackScoreParams, normFactor float32) float32 { - stat := getRtcMosStat(params) - stat.VideoConfig = &rtcmos.VideoConfig{ - FrameRate: float32Ptr(float32(getFrameRate(params.Duration.Seconds(), params.Frames))), - Codec: params.Codec, - Width: int32Ptr(int32(params.Width)), - Height: int32Ptr(int32(params.Height)), - } - if params.FrameRateExpected == 0 { - stat.VideoConfig.ExpectedFrameRate = stat.VideoConfig.FrameRate - } - - scores := rtcmos.Score([]rtcmos.Stat{stat}) - if len(scores) == 1 { - return float32(clamp(float64(float32(scores[0].VideoScore)*normFactor), float64(MinScore), float64(MaxScore))) - } - return 0 -} - -// -// rtcmos gives lower score when screen share content is static. -// That is due to use of bits / pixel / frame in the model. -// Even though the frame rate is low, the bit rate is also low and -// the resolution is high. Till rtcmos model can be adapted to that -// scenario, use loss based scoring. -// -func LossBasedTrackScore(params TrackScoreParams) float32 { - pctLoss := getLossPercentage(params.PacketsExpected, params.PacketsLost) - // No Loss, excellent - if pctLoss == 0.0 && !params.IsReducedQuality { - return MaxScore - } - // default when loss is minimal, but reducedQuality - score := float32(3.5) - // loss is bad - if pctLoss >= 4.0 { - score = 2.0 - } else if pctLoss <= 2.0 && !params.IsReducedQuality { - // loss is acceptable and not at reduced quality - score = 4.5 - } - return score -} diff --git a/pkg/sfu/connectionquality/scorer.go b/pkg/sfu/connectionquality/scorer.go new file mode 100644 index 00000000..bdd1b7ac --- /dev/null +++ b/pkg/sfu/connectionquality/scorer.go @@ -0,0 +1,471 @@ +package connectionquality + +import ( + "fmt" + "math" + "sort" + "sync" + "time" + + "github.com/livekit/protocol/livekit" + "github.com/livekit/protocol/logger" +) + +const ( + MaxMOS = float32(4.5) + + maxScore = float64(100.0) + poorScore = float64(50.0) + + waitForQualityPoor = 5 + waitForQualityGood = 3 + + unmuteTimeThreshold = float64(0.5) +) + +// ------------------------------------------ + +type windowStat struct { + startedAt time.Time + duration time.Duration + packetsExpected uint32 + packetsLost uint32 + bytes uint64 + rttMax uint32 + jitterMax float64 +} + +func (w *windowStat) calculatePacketScore(plw float64) float64 { + // this is based on simplified E-model based on packet loss, rtt, jitter as + // outlined at https://www.pingman.com/kb/article/how-is-mos-calculated-in-pingplotter-pro-50.html. + effectiveDelay := (float64(w.rttMax) / 2.0) + ((w.jitterMax * 2.0) / 1000.0) + delayEffect := effectiveDelay / 40.0 + if effectiveDelay > 160.0 { + delayEffect = (effectiveDelay - 120.0) / 10.0 + } + + lossEffect := float64(0.0) + if w.packetsExpected > 0 { + lossEffect = float64(w.packetsLost) * 100.0 / float64(w.packetsExpected) + } + lossEffect *= plw + + return maxScore - delayEffect - lossEffect +} + +func (w *windowStat) calculateByteScore(expectedBitrate int64) float64 { + if expectedBitrate == 0 { + // unsupported mode OR all layers stopped + return maxScore + } + + score := float64(0.0) + if w.bytes != 0 { + // using the ratio of expectedBitrate / actualBitrate + // the quality inflection points are approximately + // GOOD at ~2.7x, POOR at ~7.5x + score = maxScore - 20*math.Log(float64(expectedBitrate)/float64(w.bytes*8)) + if score > maxScore { + score = maxScore + } + if score < 0.0 { + score = 0.0 + } + } + + return score +} + +func (w *windowStat) String() string { + return fmt.Sprintf("start: %+v, dur: %+v, pe: %d, pl: %d, b: %d, rtt: %d, jitter: %0.2f", + w.startedAt, + w.duration, + w.packetsExpected, + w.packetsLost, + w.bytes, + w.rttMax, + w.jitterMax, + ) +} + +// ------------------------------------------ + +type windowScore struct { + stat *windowStat + score float64 +} + +func newWindowScorePacket(stat *windowStat, plw float64) *windowScore { + return &windowScore{ + stat: stat, + score: stat.calculatePacketScore(plw), + } +} + +func newWindowScoreByte(stat *windowStat, expectedBitrate int64) *windowScore { + return &windowScore{ + stat: stat, + score: stat.calculateByteScore(expectedBitrate), + } +} + +func newWindowScoreWithScore(stat *windowStat, score float64) *windowScore { + return &windowScore{ + stat: stat, + score: score, + } +} + +func (w *windowScore) getScore() float64 { + return w.score +} + +func (w *windowScore) String() string { + return fmt.Sprintf("stat: {%+v}, score: %0.2f", w.stat, w.score) +} + +// ------------------------------------------ + +type qualityScorerState int + +const ( + qualityScorerStateStable qualityScorerState = iota + qualityScorerStateRecovering +) + +func (q qualityScorerState) String() string { + switch q { + case qualityScorerStateStable: + return "STABLE" + case qualityScorerStateRecovering: + return "RECOVERING" + default: + return fmt.Sprintf("%d", int(q)) + } +} + +// ------------------------------------------ + +type layerTransition struct { + startedAt time.Time + bitrate int64 +} + +type qualityScorerParams struct { + PacketLossWeight float64 + Logger logger.Logger +} + +type qualityScorer struct { + params qualityScorerParams + + lock sync.RWMutex + lastUpdateAt time.Time + + score float64 + state qualityScorerState + windows []*windowScore + + mutedAt time.Time + unmutedAt time.Time + + layersMutedAt time.Time + layersUnmutedAt time.Time + + maxPPS float64 + + transitions []layerTransition +} + +func newQualityScorer(params qualityScorerParams) *qualityScorer { + return &qualityScorer{ + params: params, + score: maxScore, + state: qualityScorerStateStable, + } +} + +func (q *qualityScorer) Start(at time.Time) { + q.lock.Lock() + defer q.lock.Unlock() + + q.lastUpdateAt = at +} + +func (q *qualityScorer) UpdateMute(isMuted bool, at time.Time) { + q.lock.Lock() + defer q.lock.Unlock() + + if isMuted { + q.mutedAt = at + + // stable when muted + q.state = qualityScorerStateStable + q.windows = q.windows[:0] + q.score = maxScore + } else { + q.unmutedAt = at + } +} + +func (q *qualityScorer) AddTransition(bitrate int64, at time.Time) { + q.lock.Lock() + defer q.lock.Unlock() + + q.transitions = append(q.transitions, layerTransition{ + startedAt: at, + bitrate: bitrate, + }) + + if bitrate == 0 { + q.layersMutedAt = at + + // stable when no layers expected + q.state = qualityScorerStateStable + q.windows = q.windows[:0] + q.score = maxScore + } else { + if q.layersUnmutedAt.IsZero() || q.layersMutedAt.After(q.layersUnmutedAt) { + q.layersUnmutedAt = at + } + } +} + +func (q *qualityScorer) Update(stat *windowStat, at time.Time) { + q.lock.Lock() + defer q.lock.Unlock() + + // always update transitions + expectedBitrate := q.getExpectedBitsAndUpdateTransitions(at) + + // nothing to do when muted or not unmuted for long enough + // NOTE: it is possible that unmute -> mute -> unmute transition happens in the + // same analysis window. On a transition to mute, state immediately moves + // to stable and quality EXCELLENT for responsiveness. On an unmute, the + // entire window data is considered (as long as enough time has passed since + // unmute) including the data before mute. + if q.isMuted() || !q.isUnmutedEnough(at) || q.areLayersMuted() { + q.lastUpdateAt = at + return + } + + reason := "none" + var ws *windowScore + if stat == nil { + reason = "dry" + ws = newWindowScoreWithScore(&windowStat{ + startedAt: q.lastUpdateAt, + duration: at.Sub(q.lastUpdateAt), + }, poorScore) + } else { + if stat.packetsExpected == 0 { + reason = "dry" + ws = newWindowScoreWithScore(stat, poorScore) + } else { + wsPacket := newWindowScorePacket(stat, q.getPacketLossWeight(stat)) + wsByte := newWindowScoreByte(stat, expectedBitrate) + if wsPacket.getScore() < wsByte.getScore() { + reason = "packet" + ws = wsPacket + } else { + reason = "bitrate" + ws = wsByte + } + } + } + score := ws.getScore() + cq := scoreToConnectionQuality(score) + + q.lastUpdateAt = at + + // transition to start of recovering on any quality drop + // WARNING NOTE: comparing protobuf enum values directly (livekit.ConnectionQuality) + if scoreToConnectionQuality(q.score) > cq { + q.windows = []*windowScore{ws} + q.state = qualityScorerStateRecovering + q.score = score + q.params.Logger.Infow( + "quality drop", + "reaason", reason, + "score", q.score, + "quality", scoreToConnectionQuality(q.score), + "window", ws, + "expectedBitrate", expectedBitrate, + ) + return + } + + // if stable and quality continues to be EXCELLENT, stay there. + if q.state == qualityScorerStateStable && cq == livekit.ConnectionQuality_EXCELLENT { + q.score = score + return + } + + // when recovering, look at a longer window + q.windows = append(q.windows, ws) + if !q.prune(at) { + // minimum recovery duration not satisfied, hold at current quality + return + } + + // take median of scores in a longer window to prevent quality reporting oscillations + sort.Slice(q.windows, func(i, j int) bool { return q.windows[i].getScore() < q.windows[j].getScore() }) + mid := (len(q.windows)+1)/2 - 1 + q.score = q.windows[mid].getScore() + if scoreToConnectionQuality(q.score) == livekit.ConnectionQuality_EXCELLENT { + q.state = qualityScorerStateStable + q.windows = q.windows[:0] + } +} + +func (q *qualityScorer) isMuted() bool { + return !q.mutedAt.IsZero() && (q.unmutedAt.IsZero() || q.mutedAt.After(q.unmutedAt)) +} + +func (q *qualityScorer) isUnmutedEnough(at time.Time) bool { + var sinceUnmute time.Duration + if q.unmutedAt.IsZero() { + sinceUnmute = at.Sub(q.lastUpdateAt) + } else { + sinceUnmute = at.Sub(q.unmutedAt) + } + + var sinceLayersUnmute time.Duration + if q.layersUnmutedAt.IsZero() { + sinceLayersUnmute = at.Sub(q.lastUpdateAt) + } else { + sinceLayersUnmute = at.Sub(q.layersUnmutedAt) + } + + validDuration := sinceUnmute + if sinceLayersUnmute < validDuration { + validDuration = sinceLayersUnmute + } + + sinceLastUpdate := at.Sub(q.lastUpdateAt) + + return validDuration.Seconds()/sinceLastUpdate.Seconds() > unmuteTimeThreshold +} + +func (q *qualityScorer) areLayersMuted() bool { + return !q.layersMutedAt.IsZero() && (q.layersUnmutedAt.IsZero() || q.layersMutedAt.After(q.layersUnmutedAt)) +} + +func (q *qualityScorer) getPacketLossWeight(stat *windowStat) float64 { + if stat == nil { + return q.params.PacketLossWeight + } + + // packet loss is weighted by comparing against max packet rate seen. + // this is to handle situations like DTX in audio and variable bit rate tracks like screen share. + // and the effect of loss is not pronounced in those scenarios (audio silence, statis screen share). + // for example, DTX typically uses only 5% of packets of full packet rate. at that rate, + // packet loss weight is reduced to ~22% of configured weight (i. e. sqrt(0.05) * configured weight) + pps := float64(stat.packetsExpected) / stat.duration.Seconds() + if pps > q.maxPPS { + q.maxPPS = pps + } + + return math.Sqrt(pps/q.maxPPS) * q.params.PacketLossWeight +} + +func (q *qualityScorer) prune(at time.Time) bool { + cq := scoreToConnectionQuality(q.score) + + var wait int + if cq == livekit.ConnectionQuality_POOR { + wait = waitForQualityPoor + } else { + wait = waitForQualityGood + } + + oldest := len(q.windows) - wait + if oldest < 0 { + oldest = 0 + } + q.windows = q.windows[oldest:] + + return len(q.windows) >= wait +} + +func (q *qualityScorer) getExpectedBitsAndUpdateTransitions(at time.Time) int64 { + if len(q.transitions) == 0 { + return 0 + } + + var startedAt time.Time + totalBits := float64(0.0) + for idx := 0; idx < len(q.transitions)-1; idx++ { + lt := &q.transitions[idx] + ltNext := &q.transitions[idx+1] + + if lt.startedAt.After(q.lastUpdateAt) { + startedAt = lt.startedAt + } else { + startedAt = q.lastUpdateAt + } + totalBits += ltNext.startedAt.Sub(startedAt).Seconds() * float64(lt.bitrate) + } + // last transition + lt := &q.transitions[len(q.transitions)-1] + if lt.startedAt.After(q.lastUpdateAt) { + startedAt = lt.startedAt + } else { + startedAt = q.lastUpdateAt + } + totalBits += at.Sub(startedAt).Seconds() * float64(lt.bitrate) + + // set up last bit rate as the startig bit rate for next analysis window + q.transitions = []layerTransition{layerTransition{ + startedAt: at, + bitrate: lt.bitrate, + }} + + return int64(totalBits) +} + +func (q *qualityScorer) GetScoreAndQuality() (float32, livekit.ConnectionQuality) { + q.lock.RLock() + defer q.lock.RUnlock() + + return float32(q.score), scoreToConnectionQuality(q.score) +} + +func (q *qualityScorer) GetMOSAndQuality() (float32, livekit.ConnectionQuality) { + q.lock.RLock() + defer q.lock.RUnlock() + + return scoreToMOS(q.score), scoreToConnectionQuality(q.score) +} + +// ------------------------------------------ + +func scoreToConnectionQuality(score float64) livekit.ConnectionQuality { + // R-factor -> livekit.ConnectionQuality scale mapping based on + // https://www.itu.int/ITU-T/2005-2008/com12/emodelv1/tut.htm + if score > 80.0 { + return livekit.ConnectionQuality_EXCELLENT + } + + if score > 60.0 { + return livekit.ConnectionQuality_GOOD + } + + return livekit.ConnectionQuality_POOR +} + +// ------------------------------------------ + +func scoreToMOS(score float64) float32 { + if score <= 0.0 { + return 1.0 + } + + if score >= 100.0 { + return 4.5 + } + + return float32(1.0 + 0.035*score + (0.000007 * score * (score - 60.0) * (100.0 - score))) +} + +// ------------------------------------------ diff --git a/pkg/sfu/downtrack.go b/pkg/sfu/downtrack.go index 587e1b77..a2901f90 100644 --- a/pkg/sfu/downtrack.go +++ b/pkg/sfu/downtrack.go @@ -263,15 +263,9 @@ func NewDownTrack( d.connectionStats = connectionquality.NewConnectionStats(connectionquality.ConnectionStatsParams{ MimeType: codecs[0].MimeType, // LK-TODO have to notify on codec change + IsFECEnabled: strings.EqualFold(codecs[0].MimeType, webrtc.MimeTypeOpus) && strings.Contains(strings.ToLower(codecs[0].SDPFmtpLine), "fec"), GetDeltaStats: d.getDeltaStats, - GetMaxExpectedLayer: func() int32 { - return d.forwarder.MaxLayers().Spatial - }, - GetCurrentLayerSpatial: func() int32 { - return d.forwarder.CurrentLayers().Spatial - }, - GetIsReducedQuality: d.forwarder.IsReducedQuality, - Logger: d.logger, + Logger: d.logger, }) d.connectionStats.OnStatsUpdate(func(_cs *connectionquality.ConnectionStats, stat *livekit.AnalyticsStat) { if d.onStatsUpdate != nil { @@ -363,7 +357,7 @@ func (d *DownTrack) TrackInfoAvailable() { if ti == nil { return } - d.connectionStats.Start(ti) + d.connectionStats.Start(ti, time.Now()) } // ID is the unique identifier for this Track. This should be unique for the @@ -684,6 +678,8 @@ func (d *DownTrack) handleMute(muted bool, isPub bool, changed bool, maxLayers V return } + d.connectionStats.UpdateMute(d.forwarder.IsAnyMuted(), time.Now()) + // // Subscriber mute changes trigger a max layer notification. // That could result in encoding layers getting turned on/off on publisher side @@ -1554,8 +1550,8 @@ func (d *DownTrack) DebugInfo() map[string]interface{} { } } -func (d *DownTrack) GetConnectionScore() float32 { - return d.connectionStats.GetScore() +func (d *DownTrack) GetConnectionScoreAndQuality() (float32, livekit.ConnectionQuality) { + return d.connectionStats.GetScoreAndQuality() } func (d *DownTrack) GetTrackStats() *livekit.RTPStats { diff --git a/pkg/sfu/forwarder.go b/pkg/sfu/forwarder.go index 272fd80e..115b9f04 100644 --- a/pkg/sfu/forwarder.go +++ b/pkg/sfu/forwarder.go @@ -439,30 +439,6 @@ func (f *Forwarder) GetReferenceLayerSpatial() int32 { return f.referenceLayerSpatial } -func (f *Forwarder) IsReducedQuality() (int32, bool) { - f.lock.RLock() - defer f.lock.RUnlock() - - if f.muted || f.pubMuted || f.lastAllocation.pauseReason == VideoPauseReasonFeedDry || f.targetLayers.Spatial == InvalidLayerSpatial { - return 0, false - } - - if f.currentLayers.Spatial != f.targetLayers.Spatial { - // - // Waiting for layer lock, do not declare reduced quality. - // Note the target might actually be a lower layer than current. - // - return 0, false - } - - distance := f.maxLayers.Spatial - f.currentLayers.Spatial - if distance < 0 { - distance = 0 - } - - return distance, f.isDeficientLocked() -} - func (f *Forwarder) isDeficientLocked() bool { return f.lastAllocation.isDeficient } @@ -1419,7 +1395,13 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in return tp, nil } else if tp.isSwitchingToTargetLayer { // lock to target layer - f.logger.Infow("locking to target layer", "current", f.currentLayers, "target", f.targetLayers, "req", f.requestLayerSpatial, "feed", extPkt.Packet.SSRC) + f.logger.Infow( + "locking to target layer", + "current", f.currentLayers, + "target", f.targetLayers, + "req", f.requestLayerSpatial, + "feed", extPkt.Packet.SSRC, + ) f.currentLayers.Spatial = f.targetLayers.Spatial if !f.isTemporalSupported { f.currentLayers.Temporal = f.targetLayers.Temporal @@ -1442,7 +1424,13 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in found := false if f.parkedLayers.IsValid() { if f.parkedLayers.Spatial == layer { - f.logger.Infow("resuming at parked layer", "current", f.currentLayers, "target", f.targetLayers, "parked", f.parkedLayers, "feed", extPkt.Packet.SSRC) + f.logger.Infow( + "resuming at parked layer", + "current", f.currentLayers, + "target", f.targetLayers, + "parked", f.parkedLayers, + "feed", extPkt.Packet.SSRC, + ) f.currentLayers = f.parkedLayers found = true } diff --git a/pkg/sfu/receiver.go b/pkg/sfu/receiver.go index 1a5f0b2b..05bd9ebf 100644 --- a/pkg/sfu/receiver.go +++ b/pkg/sfu/receiver.go @@ -55,7 +55,6 @@ type TrackReceiver interface { DebugInfo() map[string]interface{} - GetLayerDimension(layer int32) (uint32, uint32) TrackInfo() *livekit.TrackInfo // Get primary receiver if this receiver represents a RED codec; otherwise it will return itself @@ -82,7 +81,6 @@ type WebRTCReceiver struct { kind webrtc.RTPCodecType receiver *webrtc.RTPReceiver codec webrtc.RTPCodecParameters - isSimulcast bool isSVC bool isRED bool onCloseHandler func() @@ -181,18 +179,16 @@ func NewWebRTCReceiver( opts ...ReceiverOpts, ) *WebRTCReceiver { w := &WebRTCReceiver{ - logger: logger, - receiver: receiver, - trackID: livekit.TrackID(track.ID()), - streamID: track.StreamID(), - codec: track.Codec(), - kind: track.Kind(), - // LK-TODO: this should be based on VideoLayers protocol message rather than RID based - isSimulcast: len(track.RID()) > 0, - twcc: twcc, - trackInfo: trackInfo, - isSVC: IsSvcCodec(track.Codec().MimeType), - isRED: IsRedCodec(track.Codec().MimeType), + logger: logger, + receiver: receiver, + trackID: livekit.TrackID(track.ID()), + streamID: track.StreamID(), + codec: track.Codec(), + kind: track.Kind(), + twcc: twcc, + trackInfo: trackInfo, + isSVC: IsSvcCodec(track.Codec().MimeType), + isRED: IsRedCodec(track.Codec().MimeType), } w.streamTrackerManager = NewStreamTrackerManager(logger, trackInfo, w.isSVC, w.codec.ClockRate, trackersConfig) @@ -210,21 +206,17 @@ func NewWebRTCReceiver( }) w.connectionStats = connectionquality.NewConnectionStats(connectionquality.ConnectionStatsParams{ - MimeType: w.codec.MimeType, - GetDeltaStats: w.getDeltaStats, - GetMaxExpectedLayer: w.streamTrackerManager.GetMaxExpectedLayer, - GetIsReducedQuality: func() (int32, bool) { - distance := w.streamTrackerManager.DistanceToDesired() - return distance, distance > 0 - }, - Logger: w.logger, + MimeType: w.codec.MimeType, + IsFECEnabled: strings.EqualFold(w.codec.MimeType, webrtc.MimeTypeOpus) && strings.Contains(strings.ToLower(w.codec.SDPFmtpLine), "fec"), + GetDeltaStats: w.getDeltaStats, + Logger: w.logger, }) w.connectionStats.OnStatsUpdate(func(_cs *connectionquality.ConnectionStats, stat *livekit.AnalyticsStat) { if w.onStatsUpdate != nil { w.onStatsUpdate(w, stat) } }) - w.connectionStats.Start(w.trackInfo) + w.connectionStats.Start(w.trackInfo, time.Now()) return w } @@ -233,10 +225,6 @@ func (w *WebRTCReceiver) TrackInfo() *livekit.TrackInfo { return w.trackInfo } -func (w *WebRTCReceiver) GetLayerDimension(layer int32) (uint32, uint32) { - return w.streamTrackerManager.GetLayerDimension(layer) -} - func (w *WebRTCReceiver) OnStatsUpdate(fn func(w *WebRTCReceiver, stat *livekit.AnalyticsStat)) { w.onStatsUpdate = fn } @@ -245,8 +233,8 @@ func (w *WebRTCReceiver) OnMaxLayerChange(fn func(maxLayer int32)) { w.streamTrackerManager.OnMaxLayerChanged(fn) } -func (w *WebRTCReceiver) GetConnectionScore() float32 { - return w.connectionStats.GetScore() +func (w *WebRTCReceiver) GetConnectionScoreAndQuality() (float32, livekit.ConnectionQuality) { + return w.connectionStats.GetScoreAndQuality() } func (w *WebRTCReceiver) IsClosed() bool { @@ -377,6 +365,8 @@ func (w *WebRTCReceiver) SetUpTrackPaused(paused bool) { buff.SetPaused(paused) } w.bufferMu.RUnlock() + + w.connectionStats.UpdateMute(paused, time.Now()) } func (w *WebRTCReceiver) AddDownTrack(track TrackSender) error { @@ -395,8 +385,26 @@ func (w *WebRTCReceiver) AddDownTrack(track TrackSender) error { return nil } +func (w *WebRTCReceiver) notifyMaxExpectedLayer(layer int32) { + if w.Kind() == webrtc.RTPCodecTypeAudio || w.trackInfo.Source == livekit.TrackSource_SCREEN_SHARE { + // screen share tracks have highly variable bitrate, do not use bit rate based quality for those + return + } + + expectedBitrate := int64(0) + for _, vl := range w.trackInfo.Layers { + l := buffer.VideoQualityToSpatialLayer(vl.Quality, w.trackInfo) + if l <= layer { + expectedBitrate += int64(vl.Bitrate) + } + } + + w.connectionStats.AddTransition(expectedBitrate, time.Now()) +} + func (w *WebRTCReceiver) SetMaxExpectedSpatialLayer(layer int32) { w.streamTrackerManager.SetMaxExpectedSpatialLayer(layer) + w.notifyMaxExpectedLayer(layer) } func (w *WebRTCReceiver) downTrackLayerChange() { @@ -415,6 +423,8 @@ func (w *WebRTCReceiver) downTrackMaxPublishedLayerChange(maxPublishedLayer int3 for _, dt := range w.downTrackSpreader.GetDownTracks() { dt.UpTrackMaxPublishedLayerChange(maxPublishedLayer) } + + w.notifyMaxExpectedLayer(maxPublishedLayer) } func (w *WebRTCReceiver) GetLayeredBitrate() ([]int32, Bitrates) { @@ -636,7 +646,8 @@ func (w *WebRTCReceiver) closeTracks() { func (w *WebRTCReceiver) DebugInfo() map[string]interface{} { info := map[string]interface{}{ - "Simulcast": w.isSimulcast, + "SVC": w.isSVC, + "Simulcast": !w.isSVC && len(w.trackInfo.Layers) > 1, } w.upTrackMu.RLock() diff --git a/pkg/sfu/streamtrackermanager.go b/pkg/sfu/streamtrackermanager.go index af7741d4..dd15e88e 100644 --- a/pkg/sfu/streamtrackermanager.go +++ b/pkg/sfu/streamtrackermanager.go @@ -264,62 +264,6 @@ func (s *StreamTrackerManager) SetMaxExpectedSpatialLayer(layer int32) int32 { return prev } -func (s *StreamTrackerManager) DistanceToDesired() int32 { - s.lock.RLock() - defer s.lock.RUnlock() - - if s.paused { - return 0 - } - - maxExpectedLayer := s.getMaxExpectedLayerLocked() - if len(s.availableLayers) == 0 { - return maxExpectedLayer + 1 - } - - distance := maxExpectedLayer - s.availableLayers[len(s.availableLayers)-1] - if distance < 0 { - distance = 0 - } - - return distance -} - -func (s *StreamTrackerManager) GetLayerDimension(layer int32) (uint32, uint32) { - height := uint32(0) - width := uint32(0) - if len(s.trackInfo.Layers) > 0 { - quality := buffer.SpatialLayerToVideoQuality(layer, s.trackInfo) - for _, layer := range s.trackInfo.Layers { - if layer.Quality == quality { - height = layer.Height - width = layer.Width - break - } - } - } else { - width = s.trackInfo.Width - height = s.trackInfo.Height - } - return width, height -} - -func (s *StreamTrackerManager) GetMaxExpectedLayer() int32 { - s.lock.RLock() - defer s.lock.RUnlock() - - return s.getMaxExpectedLayerLocked() -} - -func (s *StreamTrackerManager) getMaxExpectedLayerLocked() int32 { - // find min of layer - maxExpectedLayer := s.maxExpectedLayer - if maxExpectedLayer > s.maxPublishedLayer { - maxExpectedLayer = s.maxPublishedLayer - } - return maxExpectedLayer -} - func (s *StreamTrackerManager) GetMaxPublishedLayer() int32 { s.lock.RLock() defer s.lock.RUnlock()