From b5c023f9866e85c45a9a43a520f7fee684eb2813 Mon Sep 17 00:00:00 2001 From: Raja Subramanian Date: Mon, 15 Aug 2022 13:21:07 +0530 Subject: [PATCH] Connection quality changes (#913) * WIP commit * Connection quality changes - Fix Firefox showing poor quality o The issue was that we were using max available layer and calculating quality. The rationale being that even if server sends dynacast messages, client may not implement dynacast and still stream all layers. But, with Firefox (maybe a Firefox bug), it sends some small amount of data on layer 2 even when that layer is disabled. Guessing it is probing (or actually we might be using some small value for high layers as Firefox cannot turn off layers). That higher layer gets used in quality calculation. As the bit rate on that layer is extremely low, it yields low score. Fixed by considering the max expected layer. That is of most interest. Yes, clients may ignore dynacast and stream all layers, but, max expected is the one of interest. So, look for quality in the max expected layer and not max available layer. - Lots of clean up around connection quality stuff o Use a dynamic scaling thing to ensure that we do not get bitten by absolute values. Calculate best possible scenario score and map that to maximum MOS score. This will ensure that different codecs, different settings do not mess up the scoring. For example, a client might use 1 Mbps for 720p, but a different client could use 2 Mbps for 720p. As an SFU/infrastructure middlebox, we do not have control over quality at those rates. We can only ensure that streaming happens smoothly at those rates. So, in that example, for client 1, 1 Mbps will map to MOS 5.0 and for client 2, 2 Mbps will map to MOS 5.0. Any impairments after that will reflect in the score. o Penalise for missing target layer by one level for one layer missed. o Move tests to connection quality directory. The participant test was not super useful. * Add missed file * Remove debug code * use more constants and initialise normalisation factor * rtcscore pointer --- go.mod | 2 +- go.sum | 4 +- pkg/rtc/participant_internal_test.go | 283 ----------- pkg/rtc/wrappedreceiver.go | 14 +- pkg/sfu/connectionquality/connectionstats.go | 240 ++++++--- .../connectionquality/connectionstats_test.go | 478 ++++++++++++++++++ pkg/sfu/connectionquality/mos.go | 82 +-- pkg/sfu/downtrack.go | 23 +- pkg/sfu/forwarder.go | 24 + pkg/sfu/helpers.go | 9 - pkg/sfu/receiver.go | 25 +- pkg/sfu/streamtrackermanager.go | 27 +- 12 files changed, 762 insertions(+), 449 deletions(-) create mode 100644 pkg/sfu/connectionquality/connectionstats_test.go diff --git a/go.mod b/go.mod index a7d3c4d4..1457163b 100644 --- a/go.mod +++ b/go.mod @@ -17,7 +17,7 @@ require ( github.com/hashicorp/go-version v1.6.0 github.com/hashicorp/golang-lru v0.5.4 github.com/livekit/protocol v1.0.1-0.20220814074051-ac91aad4ad8c - github.com/livekit/rtcscore-go v0.0.0-20220524203225-dfd1ba40744a + github.com/livekit/rtcscore-go v0.0.0-20220815072451-20ee10ae1995 github.com/mackerelio/go-osstat v0.2.2 github.com/magefile/mage v1.13.0 github.com/maxbrunsfeld/counterfeiter/v6 v6.5.0 diff --git a/go.sum b/go.sum index 5cc336af..23d0f32c 100644 --- a/go.sum +++ b/go.sum @@ -242,8 +242,8 @@ github.com/lithammer/shortuuid/v3 v3.0.7 h1:trX0KTHy4Pbwo/6ia8fscyHoGA+mf1jWbPJV github.com/lithammer/shortuuid/v3 v3.0.7/go.mod h1:vMk8ke37EmiewwolSO1NLW8vP4ZaKlRuDIi8tWWmAts= github.com/livekit/protocol v1.0.1-0.20220814074051-ac91aad4ad8c h1:SX39A/GXStqvlDSAKIp8cxVkhdOEMAV+ufZrNpo2cPs= github.com/livekit/protocol v1.0.1-0.20220814074051-ac91aad4ad8c/go.mod h1:hN0rI0/QsnGXp3oYnFktdquU3FPetAl8/naweFo6oPs= -github.com/livekit/rtcscore-go v0.0.0-20220524203225-dfd1ba40744a h1:cENjhGfslLSDV07gt8ASy47Wd12Q0kBS7hsdunyQ62I= -github.com/livekit/rtcscore-go v0.0.0-20220524203225-dfd1ba40744a/go.mod h1:116ych8UaEs9vfIE8n6iZCZ30iagUFTls0vRmC+Ix5U= +github.com/livekit/rtcscore-go v0.0.0-20220815072451-20ee10ae1995 h1:vOaY2qvfLihDyeZtnGGN1Law9wRrw8BMGCr1TygTvMw= +github.com/livekit/rtcscore-go v0.0.0-20220815072451-20ee10ae1995/go.mod h1:116ych8UaEs9vfIE8n6iZCZ30iagUFTls0vRmC+Ix5U= github.com/mackerelio/go-osstat v0.2.2 h1:7jVyXGXTkQL3+6lDVUDBY+Fpo8VQPfyOkZeXxxsXX4c= github.com/mackerelio/go-osstat v0.2.2/go.mod h1:G2A1f01HIHVRhMdS1qnigXxS6C8ahppy5lCwBrbRp0s= github.com/magefile/mage v1.13.0 h1:XtLJl8bcCM7EFoO8FyH8XK3t7G5hQAeK+i4tq+veT9M= diff --git a/pkg/rtc/participant_internal_test.go b/pkg/rtc/participant_internal_test.go index a25a633b..263eab65 100644 --- a/pkg/rtc/participant_internal_test.go +++ b/pkg/rtc/participant_internal_test.go @@ -19,7 +19,6 @@ import ( "github.com/livekit/livekit-server/pkg/routing/routingfakes" "github.com/livekit/livekit-server/pkg/rtc/types" "github.com/livekit/livekit-server/pkg/rtc/types/typesfakes" - "github.com/livekit/livekit-server/pkg/sfu/connectionquality" "github.com/livekit/livekit-server/pkg/testutils" ) @@ -253,288 +252,6 @@ func TestMuteSetting(t *testing.T) { }) } -func TestConnectionQuality(t *testing.T) { - testPublishedVideoTrack := func(params connectionquality.TrackScoreParams) *typesfakes.FakeLocalMediaTrack { - tr := &typesfakes.FakeLocalMediaTrack{} - score := connectionquality.VideoTrackScore(params) - t.Log("video score: ", score) - tr.GetConnectionScoreReturns(score) - return tr - } - - testPublishedAudioTrack := func(params connectionquality.TrackScoreParams) *typesfakes.FakeLocalMediaTrack { - tr := &typesfakes.FakeLocalMediaTrack{} - score := connectionquality.AudioTrackScore(params) - t.Log("audio score: ", score) - tr.GetConnectionScoreReturns(score) - return tr - } - - testPublishedScreenshareTrack := func(params connectionquality.TrackScoreParams) *typesfakes.FakeLocalMediaTrack { - tr := &typesfakes.FakeLocalMediaTrack{} - score := connectionquality.ScreenshareTrackScore(params) - t.Log("screen share score: ", score) - tr.GetConnectionScoreReturns(score) - return tr - } - - // TODO: this test is rather limited since we cannot mock DownTrack's Target & Max spatial layers - // to improve this after split - - t.Run("smooth sailing", func(t *testing.T) { - p := newParticipantForTest("test") - - // >2Mbps, 30fps, expected/actual video size = 1280x720 - params := connectionquality.TrackScoreParams{ - Duration: 1 * time.Second, - PacketsExpected: 100, - PacketsLost: 0, - Bytes: 290000, - Frames: 30, - Jitter: 0.0, - Rtt: 0, - ExpectedWidth: 1280, - ExpectedHeight: 720, - ActualWidth: 1280, - ActualHeight: 720, - } - p.UpTrackManager.publishedTracks["video"] = testPublishedVideoTrack(params) - - // no packet loss - params = connectionquality.TrackScoreParams{ - Duration: 1 * time.Second, - Codec: "opus", - PacketsExpected: 100, - PacketsLost: 0, - Bytes: 1000, - Jitter: 0.0, - Rtt: 0, - DtxDisabled: false, - } - p.UpTrackManager.publishedTracks["audio"] = testPublishedAudioTrack(params) - - require.Equal(t, livekit.ConnectionQuality_EXCELLENT, p.GetConnectionQuality().GetQuality()) - }) - - t.Run("reduced publishing", func(t *testing.T) { - p := newParticipantForTest("test") - - // 1Mbps, 15fps, expected = 1280x720, actual = 640 x 480 - params := connectionquality.TrackScoreParams{ - Duration: 1 * time.Second, - PacketsExpected: 100, - PacketsLost: 0, - Bytes: 125000, - Frames: 15, - Jitter: 0.0, - Rtt: 0, - ExpectedWidth: 1280, - ExpectedHeight: 720, - ActualWidth: 640, - ActualHeight: 480, - } - p.UpTrackManager.publishedTracks["video"] = testPublishedVideoTrack(params) - - // packet loss of 5% - params = connectionquality.TrackScoreParams{ - Duration: 1 * time.Second, - Codec: "opus", - PacketsExpected: 100, - PacketsLost: 5, - Bytes: 1000, - Jitter: 0.0, - Rtt: 0, - DtxDisabled: false, - } - p.UpTrackManager.publishedTracks["audio"] = testPublishedAudioTrack(params) - - require.Equal(t, livekit.ConnectionQuality_GOOD, p.GetConnectionQuality().GetQuality()) - }) - - t.Run("audio smooth publishing", func(t *testing.T) { - p := newParticipantForTest("test") - // no packet loss - params := connectionquality.TrackScoreParams{ - Duration: 1 * time.Second, - Codec: "opus", - PacketsExpected: 100, - PacketsLost: 0, - Bytes: 1000, - Jitter: 0.0, - Rtt: 0, - DtxDisabled: false, - } - p.UpTrackManager.publishedTracks["audio"] = testPublishedAudioTrack(params) - - require.Equal(t, livekit.ConnectionQuality_EXCELLENT, p.GetConnectionQuality().GetQuality()) - }) - - t.Run("audio reduced publishing", func(t *testing.T) { - p := newParticipantForTest("test") - params := connectionquality.TrackScoreParams{ - Duration: 1 * time.Second, - Codec: "opus", - PacketsExpected: 100, - PacketsLost: 5, - Bytes: 1000, - Jitter: 0.0, - Rtt: 0, - DtxDisabled: false, - } - p.UpTrackManager.publishedTracks["audio"] = testPublishedAudioTrack(params) - - require.Equal(t, livekit.ConnectionQuality_GOOD, p.GetConnectionQuality().GetQuality()) - }) - - t.Run("audio bad publishing", func(t *testing.T) { - p := newParticipantForTest("test") - params := connectionquality.TrackScoreParams{ - Duration: 1 * time.Second, - Codec: "opus", - PacketsExpected: 100, - PacketsLost: 20, - Bytes: 1000, - Jitter: 0.0, - Rtt: 0, - DtxDisabled: false, - } - p.UpTrackManager.publishedTracks["audio"] = testPublishedAudioTrack(params) - - require.Equal(t, livekit.ConnectionQuality_POOR, p.GetConnectionQuality().GetQuality()) - }) - - t.Run("video smooth publishing", func(t *testing.T) { - p := newParticipantForTest("test") - - // >2Mbps, 30fps, expected/actual video size = 1280x720 - params := connectionquality.TrackScoreParams{ - Duration: 1 * time.Second, - PacketsExpected: 100, - PacketsLost: 0, - Bytes: 290000, - Frames: 30, - Jitter: 0.0, - Rtt: 0, - ExpectedWidth: 1280, - ExpectedHeight: 720, - ActualWidth: 1280, - ActualHeight: 720, - } - p.UpTrackManager.publishedTracks["video"] = testPublishedVideoTrack(params) - - require.Equal(t, livekit.ConnectionQuality_EXCELLENT, p.GetConnectionQuality().GetQuality()) - }) - - t.Run("video reduced publishing", func(t *testing.T) { - p := newParticipantForTest("test") - - // 1Mbps, 15fps, expected = 1280x720, actual = 640 x 480 - params := connectionquality.TrackScoreParams{ - Duration: 1 * time.Second, - PacketsExpected: 100, - PacketsLost: 0, - Bytes: 125000, - Frames: 15, - Jitter: 0.0, - Rtt: 0, - ExpectedWidth: 1280, - ExpectedHeight: 720, - ActualWidth: 640, - ActualHeight: 480, - } - p.UpTrackManager.publishedTracks["video"] = testPublishedVideoTrack(params) - - require.Equal(t, livekit.ConnectionQuality_GOOD, p.GetConnectionQuality().GetQuality()) - }) - - t.Run("video poor publishing", func(t *testing.T) { - p := newParticipantForTest("test") - - // 20kbps, 8fps, expected = 1280x720, actual = 240x426 - params := connectionquality.TrackScoreParams{ - Duration: 1 * time.Second, - PacketsExpected: 100, - PacketsLost: 0, - Bytes: 2500, - Frames: 8, - Jitter: 0.0, - Rtt: 0, - ExpectedWidth: 1280, - ExpectedHeight: 720, - ActualWidth: 240, - ActualHeight: 426, - } - p.UpTrackManager.publishedTracks["video"] = testPublishedVideoTrack(params) - - require.Equal(t, livekit.ConnectionQuality_POOR, p.GetConnectionQuality().GetQuality()) - }) - - t.Run("screen share no loss, not reduced quality, should be excellent", func(t *testing.T) { - p := newParticipantForTest("test") - - // 20kbps, 2fps - params := connectionquality.TrackScoreParams{ - Duration: 1 * time.Second, - PacketsExpected: 100, - PacketsLost: 0, - Bytes: 2500, - Frames: 2, - } - p.UpTrackManager.publishedTracks["ss"] = testPublishedScreenshareTrack(params) - - require.Equal(t, livekit.ConnectionQuality_EXCELLENT, p.GetConnectionQuality().GetQuality()) - }) - - t.Run("screen share low loss, not reduced quality, should be excellent", func(t *testing.T) { - p := newParticipantForTest("test") - - // 20kbps, 2fps - params := connectionquality.TrackScoreParams{ - Duration: 1 * time.Second, - PacketsExpected: 100, - PacketsLost: 1, - Bytes: 2500, - Frames: 2, - } - p.UpTrackManager.publishedTracks["ss"] = testPublishedScreenshareTrack(params) - - require.Equal(t, livekit.ConnectionQuality_EXCELLENT, p.GetConnectionQuality().GetQuality()) - }) - - t.Run("screen share high loss, not reduced quality, should be poor", func(t *testing.T) { - p := newParticipantForTest("test") - - // 20kbps, 2fps - params := connectionquality.TrackScoreParams{ - Duration: 1 * time.Second, - PacketsExpected: 100, - PacketsLost: 5, - Bytes: 2500, - Frames: 2, - } - p.UpTrackManager.publishedTracks["ss"] = testPublishedScreenshareTrack(params) - - require.Equal(t, livekit.ConnectionQuality_POOR, p.GetConnectionQuality().GetQuality()) - }) - - t.Run("screen share no loss, but reduced quality, should be good", func(t *testing.T) { - p := newParticipantForTest("test") - - // 20kbps, 2fps - params := connectionquality.TrackScoreParams{ - Duration: 1 * time.Second, - PacketsExpected: 100, - PacketsLost: 0, - Bytes: 2500, - Frames: 2, - IsReducedQuality: true, - } - p.UpTrackManager.publishedTracks["ss"] = testPublishedScreenshareTrack(params) - - require.Equal(t, livekit.ConnectionQuality_GOOD, p.GetConnectionQuality().GetQuality()) - }) -} - func TestSubscriberAsPrimary(t *testing.T) { t.Run("protocol 4 uses subs as primary", func(t *testing.T) { p := newParticipantForTestWithOpts("test", &participantOpts{ diff --git a/pkg/rtc/wrappedreceiver.go b/pkg/rtc/wrappedreceiver.go index 6a42600b..a215feb5 100644 --- a/pkg/rtc/wrappedreceiver.go +++ b/pkg/rtc/wrappedreceiver.go @@ -221,17 +221,9 @@ func (d *DummyReceiver) GetLayerDimension(quality int32) (uint32, uint32) { return 0, 0 } -func (d *DummyReceiver) IsDtxDisabled() bool { +func (d *DummyReceiver) TrackInfo() *livekit.TrackInfo { if r, ok := d.receiver.Load().(sfu.TrackReceiver); ok { - return r.IsDtxDisabled() + return r.TrackInfo() } - return false -} - -func (d *DummyReceiver) TrackSource() livekit.TrackSource { - if r, ok := d.receiver.Load().(sfu.TrackReceiver); ok { - return r.TrackSource() - } - - return livekit.TrackSource_UNKNOWN + return nil } diff --git a/pkg/sfu/connectionquality/connectionstats.go b/pkg/sfu/connectionquality/connectionstats.go index 828e2450..6242fe49 100644 --- a/pkg/sfu/connectionquality/connectionstats.go +++ b/pkg/sfu/connectionquality/connectionstats.go @@ -1,16 +1,17 @@ package connectionquality import ( + "strings" "sync" "time" - "github.com/pion/webrtc/v3" "go.uber.org/atomic" "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" "github.com/livekit/livekit-server/pkg/sfu/buffer" + "github.com/livekit/livekit-server/pkg/utils" ) const ( @@ -20,21 +21,19 @@ const ( type ConnectionStatsParams struct { UpdateInterval time.Duration - CodecType webrtc.RTPCodecType - CodecName string MimeType string GetDeltaStats func() map[uint32]*buffer.StreamStatsWithLayers - IsDtxDisabled func() bool - GetLayerDimension func(int32) (uint32, uint32) - GetMaxExpectedLayer func() (int32, uint32, uint32) + GetMaxExpectedLayer func() int32 GetCurrentLayerSpatial func() int32 - GetIsReducedQuality func() bool + GetIsReducedQuality func() (int32, bool) Logger logger.Logger } type ConnectionStats struct { params ConnectionStatsParams - trackSource livekit.TrackSource + codecName string + trackInfo *livekit.TrackInfo + normFactors [buffer.DefaultMaxLayerSpatial + 1]float32 onStatsUpdate func(cs *ConnectionStats, stat *livekit.AnalyticsStat) @@ -51,14 +50,60 @@ type ConnectionStats struct { func NewConnectionStats(params ConnectionStatsParams) *ConnectionStats { return &ConnectionStats{ params: params, - trackSource: livekit.TrackSource_UNKNOWN, - score: 5.0, + 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{}), } } -func (cs *ConnectionStats) Start() { +func (cs *ConnectionStats) Start(trackInfo *livekit.TrackInfo) { + cs.lock.Lock() + 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 := utils.SpatialLayerForQuality(layer.Quality) + // 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[utils.SpatialLayerForQuality(layer.Quality)] = MaxScore / VideoTrackScore(params, 1) + } + } + cs.lock.Unlock() + go cs.updateStatsWorker() } @@ -70,10 +115,6 @@ func (cs *ConnectionStats) Close() { close(cs.done) } -func (cs *ConnectionStats) SetTrackSource(trackSource livekit.TrackSource) { - cs.trackSource = trackSource -} - func (cs *ConnectionStats) OnStatsUpdate(fn func(cs *ConnectionStats, stat *livekit.AnalyticsStat)) { cs.onStatsUpdate = fn } @@ -85,6 +126,20 @@ func (cs *ConnectionStats) GetScore() float32 { return cs.score } +func (cs *ConnectionStats) getLayerDimensions(layer int32) (uint32, uint32) { + if cs.trackInfo == nil { + return 0, 0 + } + + for _, l := range cs.trackInfo.Layers { + if layer == utils.SpatialLayerForQuality(l.Quality) { + return l.Width, l.Height + } + } + + return 0, 0 +} + func (cs *ConnectionStats) updateScore(streams map[uint32]*buffer.StreamStatsWithLayers) float32 { cs.lock.Lock() defer cs.lock.Unlock() @@ -92,77 +147,102 @@ func (cs *ConnectionStats) updateScore(streams map[uint32]*buffer.StreamStatsWit // Initial interval will have partial data if cs.lastUpdate.IsZero() { cs.lastUpdate = time.Now() - cs.score = 5 + cs.score = MaxScore return cs.score } cs.lastUpdate = time.Now() - maxAvailableLayer, maxAvailableLayerStats := cs.getMaxAvailableLayerStats(streams) - if maxAvailableLayerStats == nil { - // retain old score as stats will not be available when muted - return cs.score - } - - params := TrackScoreParams{ - Duration: maxAvailableLayerStats.Duration, - Codec: cs.params.CodecName, - PacketsExpected: maxAvailableLayerStats.Packets + maxAvailableLayerStats.PacketsPadding, - PacketsLost: maxAvailableLayerStats.PacketsLost, - Bytes: maxAvailableLayerStats.Bytes - maxAvailableLayerStats.HeaderBytes, // only use media payload size - Frames: maxAvailableLayerStats.Frames, - Jitter: maxAvailableLayerStats.JitterMax, - Rtt: maxAvailableLayerStats.RttMax, - } switch { - case cs.trackSource == livekit.TrackSource_SCREEN_SHARE: - if cs.params.GetIsReducedQuality != nil { - params.IsReducedQuality = cs.params.GetIsReducedQuality() + 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 + return cs.score } - cs.score = ScreenshareTrackScore(params) - case cs.params.CodecType == webrtc.RTPCodecTypeAudio: + params := getTrackScoreParams(cs.codecName, maxAvailableLayerStats) packetRate := float64(params.PacketsExpected) / maxAvailableLayerStats.Duration.Seconds() - if packetRate > audioPacketRateThreshold { + 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. - if cs.params.IsDtxDisabled != nil { - params.DtxDisabled = cs.params.IsDtxDisabled() - } - cs.score = AudioTrackScore(params) + return cs.score } - case cs.params.CodecType == webrtc.RTPCodecTypeVideo: - // See note below about muxed tracks quality calculation challenged. + 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, expectedWidth, expectedHeight := cs.params.GetMaxExpectedLayer() - if maxExpectedLayer == buffer.InvalidLayerSpatial || expectedWidth == 0 || expectedHeight == 0 || maxExpectedLayer != cs.maxExpectedLayer { + // + 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 + } return cs.score } cs.maxExpectedLayer = maxExpectedLayer - if maxAvailableLayerStats != nil { - // 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() - } - params.ActualWidth, params.ActualHeight = cs.params.GetLayerDimension(maxAvailableLayer) + + maxAvailableLayer, maxAvailableLayerStats := getMaxAvailableLayerStats(streams, maxExpectedLayer) + if maxAvailableLayerStats == nil { + // retain old score as stats will not be available when muted + return cs.score } - params.ExpectedWidth = expectedWidth - params.ExpectedHeight = expectedHeight - cs.score = VideoTrackScore(params) + 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() + } + params.Width, params.Height = cs.getLayerDimensions(maxAvailableLayer) + if params.Width == 0 || params.Height == 0 { + cs.params.Logger.Warnw("could not get dimensions", nil, "maxAvailableLayer", maxAvailableLayer) + return cs.score + } + + if cs.trackInfo.Source == livekit.TrackSource_SCREEN_SHARE { + if cs.params.GetIsReducedQuality != nil { + _, params.IsReducedQuality = cs.params.GetIsReducedQuality() + } + + cs.score = ScreenshareTrackScore(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))) + } + } if cs.score < 3.5 { if !cs.isLowQuality.Swap(true) { @@ -189,16 +269,16 @@ func (cs *ConnectionStats) getStat() *livekit.AnalyticsStat { analyticsStreams := make([]*livekit.AnalyticsStream, 0, len(streams)) for ssrc, stream := range streams { - as := ToAnalyticsStream(ssrc, stream.RTPStats) + as := toAnalyticsStream(ssrc, stream.RTPStats) // // add video layer if either // 1. Simulcast - even if there is only one layer per stream as it provides layer id // 2. A stream has multiple layers // - if cs.params.CodecType == webrtc.RTPCodecTypeVideo && (len(streams) > 1 || len(stream.Layers) > 1) { + if cs.trackInfo.Type == livekit.TrackType_VIDEO && (len(streams) > 1 || len(stream.Layers) > 1) { for layer, layerStats := range stream.Layers { - as.VideoLayers = append(as.VideoLayers, ToAnalyticsVideoLayer(layer, layerStats)) + as.VideoLayers = append(as.VideoLayers, toAnalyticsVideoLayer(layer, layerStats)) } } @@ -241,7 +321,18 @@ func (cs *ConnectionStats) updateStatsWorker() { } } -func ToAnalyticsStream(ssrc uint32, deltaStats *buffer.RTPDeltaInfo) *livekit.AnalyticsStream { +// ----------------------------------------------------------------------- + +func getCodecNameFromMime(mime string) string { + codecName := "" + codecParsed := strings.Split(strings.ToLower(mime), "/") + if len(codecParsed) > 1 { + codecName = codecParsed[1] + } + return codecName +} + +func toAnalyticsStream(ssrc uint32, deltaStats *buffer.RTPDeltaInfo) *livekit.AnalyticsStream { return &livekit.AnalyticsStream{ Ssrc: ssrc, PrimaryPackets: deltaStats.Packets, @@ -260,7 +351,7 @@ func ToAnalyticsStream(ssrc uint32, deltaStats *buffer.RTPDeltaInfo) *livekit.An } } -func ToAnalyticsVideoLayer(layer int32, layerStats *buffer.RTPDeltaInfo) *livekit.AnalyticsVideoLayer { +func toAnalyticsVideoLayer(layer int32, layerStats *buffer.RTPDeltaInfo) *livekit.AnalyticsVideoLayer { return &livekit.AnalyticsVideoLayer{ Layer: layer, Packets: layerStats.Packets + layerStats.PacketsDuplicate + layerStats.PacketsPadding, @@ -269,11 +360,15 @@ func ToAnalyticsVideoLayer(layer int32, layerStats *buffer.RTPDeltaInfo) *liveki } } -func (cs *ConnectionStats) getMaxAvailableLayerStats(streams map[uint32]*buffer.StreamStatsWithLayers) (int32, *buffer.RTPDeltaInfo) { +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 @@ -283,3 +378,16 @@ func (cs *ConnectionStats) getMaxAvailableLayerStats(streams map[uint32]*buffer. 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 new file mode 100644 index 00000000..031d3110 --- /dev/null +++ b/pkg/sfu/connectionquality/connectionstats_test.go @@ -0,0 +1,478 @@ +package connectionquality + +import ( + "testing" + "time" + + "github.com/livekit/livekit-server/pkg/sfu/buffer" + "github.com/livekit/protocol/livekit" + "github.com/stretchr/testify/require" +) + +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}) + + // first update does nothing + 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: 20000 * 2 / 8, // 20 kbps + }, + }, + }, + } + 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: 18000 * 2 / 8, // 20 kbps - 2 kbps, i. e 10% lost + }, + }, + }, + } + 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) + require.Equal(t, lossQuality, cs.GetScore()) + + // setting RTT (i. e. adding delay) should reduce quality + 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 + }, + }, + }, + } + cs.updateScore(streams) + rttQuality := cs.GetScore() + require.Less(t, rttQuality, lossQuality) + + // adding jitter (i. e. more delay) should reduce quality + 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 + }, + }, + }, + } + 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, + }, + { + Quality: livekit.VideoQuality_MEDIUM, + Width: 640, + Height: 360, + Bitrate: 500_000, + }, + { + Quality: livekit.VideoQuality_LOW, + Width: 320, + Height: 180, + Bitrate: 150_000, + }, + }, + }) + + // 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{ + 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 + }, + }, + }, + } + 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()) + + // layer 1 at layer 0 bitrate should give lower score + 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 + }, + }, + }, + } + 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) + require.Equal(t, float32(5), cs.GetScore()) + + // a layer at higher than 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: 600_000 * 2 / 8, // 600 kbps, optimal is 500 kbps + Frames: 40, // 20 fps + }, + }, + }, + } + cs.updateScore(streams) + require.Equal(t, float32(5), cs.GetScore()) + + 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 + 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 + }, + }, + }, + } + cs.updateScore(streams) + require.Less(t, cs.GetScore(), float32(5)) + + // layer 2 at optimal bit rate should give max score + 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 + }, + }, + }, + } + cs.updateScore(streams) + require.Equal(t, float32(5), cs.GetScore()) + + // layer 2 at optimal bit rate, but with loss should give less score + 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 + }, + }, + }, + } + cs.updateScore(streams) + score := cs.GetScore() + require.Less(t, score, float32(5)) + + // adding rtt (i. e. delay) should reduce score further + 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 + }, + }, + }, + } + cs.updateScore(streams) + require.Less(t, cs.GetScore(), score) + score = cs.GetScore() + + // adding jitter (i. e. delay) should reduce score further + 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 + }, + }, + }, + } + 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 + 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) + require.Less(t, float32(4), cs.GetScore()) + + // layer 2 max expected, but max available is layer 0 should reduce two levels even if layer 0 is perfect + currentLayer = 0 + 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 + }, + }, + }, + } + cs.updateScore(streams) + require.Less(t, float32(3), cs.GetScore()) + }) + + 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 + }, + GetIsReducedQuality: func() (int32, bool) { + return 0, isReducedQuality + }, + }) + cs.Start(&livekit.TrackInfo{ + Type: livekit.TrackType_VIDEO, + Source: livekit.TrackSource_SCREEN_SHARE, + Layers: []*livekit.VideoLayer{ + { + Width: 1920, + Height: 1080, + }, + }, + }) + + // 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 + }, + }, + }, + } + 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 + }, + }, + }, + } + 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 + }, + }, + }, + } + 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 + }, + }, + }, + } + 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 + }, + }, + }, + } + 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 + }, + }, + }, + } + 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 index 9c40c565..7ecdd286 100644 --- a/pkg/sfu/connectionquality/mos.go +++ b/pkg/sfu/connectionquality/mos.go @@ -1,12 +1,18 @@ 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 @@ -18,12 +24,16 @@ func Score2Rating(score float32) livekit.ConnectionQuality { return livekit.ConnectionQuality_POOR } -func getBitRate(interval float64, bytes uint64) int32 { - return int32(float64(bytes*8) / interval) +func clamp(value, min, max float64) float64 { + return math.Max(min, math.Min(value, max)) } -func getFrameRate(interval float64, frames uint32) int32 { - return int32(float64(frames) / interval) +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 { @@ -38,67 +48,69 @@ 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 - Jitter float64 - Rtt uint32 - DtxDisabled bool - ActualWidth uint32 - ActualHeight uint32 - ExpectedWidth uint32 - ExpectedHeight uint32 - IsReducedQuality bool + 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: getBitRate(params.Duration.Seconds(), params.Bytes), + 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) float32 { +func AudioTrackScore(params TrackScoreParams, normFactor float32) float32 { stat := getRtcMosStat(params) stat.AudioConfig = &rtcmos.AudioConfig{} - if !params.DtxDisabled { - flag := true - stat.AudioConfig.Dtx = &flag - } + stat.AudioConfig.Dtx = ¶ms.DtxEnabled scores := rtcmos.Score([]rtcmos.Stat{stat}) if len(scores) == 1 { - return float32(scores[0].AudioScore) + return float32(clamp(float64(float32(scores[0].AudioScore)*normFactor), float64(MinScore), float64(MaxScore))) } return 0 } -func VideoTrackScore(params TrackScoreParams) float32 { +func VideoTrackScore(params TrackScoreParams, normFactor float32) float32 { stat := getRtcMosStat(params) stat.VideoConfig = &rtcmos.VideoConfig{ - FrameRate: int32Ptr(getFrameRate(params.Duration.Seconds(), params.Frames)), - Codec: params.Codec, - ExpectedWidth: int32Ptr(int32(params.ExpectedWidth)), - ExpectedHeight: int32Ptr(int32(params.ExpectedHeight)), - Width: int32Ptr(int32(params.ActualWidth)), - Height: int32Ptr(int32(params.ActualHeight)), + 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(scores[0].VideoScore) + 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. @@ -107,7 +119,7 @@ func ScreenshareTrackScore(params TrackScoreParams) float32 { pctLoss := getLossPercentage(params.PacketsExpected, params.PacketsLost) // No Loss, excellent if pctLoss == 0.0 && !params.IsReducedQuality { - return 5.0 + return MaxScore } // default when loss is minimal, but reducedQuality score := float32(3.5) @@ -115,7 +127,7 @@ func ScreenshareTrackScore(params TrackScoreParams) float32 { if pctLoss >= 4.0 { score = 2.0 } else if pctLoss <= 2.0 && !params.IsReducedQuality { - // loss is acceptable and at reduced quality + // loss is acceptable and not at reduced quality score = 4.5 } return score diff --git a/pkg/sfu/downtrack.go b/pkg/sfu/downtrack.go index f831d956..03584962 100644 --- a/pkg/sfu/downtrack.go +++ b/pkg/sfu/downtrack.go @@ -222,24 +222,16 @@ func NewDownTrack( d.forwarder = NewForwarder(d.kind, d.logger) d.connectionStats = connectionquality.NewConnectionStats(connectionquality.ConnectionStatsParams{ - CodecType: kind, - CodecName: getCodecNameFromMime(codecs[0].MimeType), // LK-TODO: have to notify on codec change - MimeType: codecs[0].MimeType, // LK-TODO have to notify on codec change - GetDeltaStats: d.getDeltaStats, - IsDtxDisabled: d.receiver.IsDtxDisabled, - GetLayerDimension: d.receiver.GetLayerDimension, - GetMaxExpectedLayer: func() (int32, uint32, uint32) { - maxLayer := d.forwarder.MaxLayers().Spatial - width, height := d.receiver.GetLayerDimension(maxLayer) - return maxLayer, width, height + MimeType: codecs[0].MimeType, // LK-TODO have to notify on codec change + GetDeltaStats: d.getDeltaStats, + GetMaxExpectedLayer: func() int32 { + return d.forwarder.MaxLayers().Spatial }, GetCurrentLayerSpatial: func() int32 { return d.forwarder.CurrentLayers().Spatial }, - GetIsReducedQuality: func() bool { - return d.GetForwardingStatus() != ForwardingStatusOptimal - }, - Logger: d.logger, + GetIsReducedQuality: d.forwarder.IsReducedQuality, + Logger: d.logger, }) d.connectionStats.OnStatsUpdate(func(_cs *connectionquality.ConnectionStats, stat *livekit.AnalyticsStat) { if d.onStatsUpdate != nil { @@ -309,8 +301,7 @@ func (d *DownTrack) Bind(t webrtc.TrackLocalContext) (webrtc.RTPCodecParameters, if d.onMaxLayerChanged != nil { d.onMaxLayerChanged(d, d.MaxLayers().Spatial) } - d.connectionStats.SetTrackSource(d.receiver.TrackSource()) - d.connectionStats.Start() + d.connectionStats.Start(d.receiver.TrackInfo()) d.logger.Debugw("downtrack bound") return codec, nil diff --git a/pkg/sfu/forwarder.go b/pkg/sfu/forwarder.go index 9685100b..40708ec0 100644 --- a/pkg/sfu/forwarder.go +++ b/pkg/sfu/forwarder.go @@ -364,6 +364,30 @@ func (f *Forwarder) GetForwardingStatus() ForwardingStatus { return ForwardingStatusOptimal } +func (f *Forwarder) IsReducedQuality() (int32, bool) { + f.lock.RLock() + defer f.lock.RUnlock() + + if f.muted || len(f.availableLayers) == 0 || 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.lastAllocation.state == VideoAllocationStateDeficient +} + func (f *Forwarder) UpTrackLayersChange(availableLayers []int32) { f.lock.Lock() defer f.lock.Unlock() diff --git a/pkg/sfu/helpers.go b/pkg/sfu/helpers.go index d34332ac..cc54c824 100644 --- a/pkg/sfu/helpers.go +++ b/pkg/sfu/helpers.go @@ -55,12 +55,3 @@ func getRttMs(report *rtcp.ReceptionReport) uint32 { ntpDiff := now - report.LastSenderReport - report.Delay return uint32(math.Ceil(float64(ntpDiff) * 1000.0 / 65536.0)) } - -func getCodecNameFromMime(mime string) string { - codecName := "" - codecParsed := strings.Split(strings.ToLower(mime), "/") - if len(codecParsed) > 1 { - codecName = codecParsed[1] - } - return codecName -} diff --git a/pkg/sfu/receiver.go b/pkg/sfu/receiver.go index cbfe061e..65d7d386 100644 --- a/pkg/sfu/receiver.go +++ b/pkg/sfu/receiver.go @@ -53,9 +53,8 @@ type TrackReceiver interface { DebugInfo() map[string]interface{} - TrackSource() livekit.TrackSource GetLayerDimension(layer int32) (uint32, uint32) - IsDtxDisabled() bool + TrackInfo() *livekit.TrackInfo } // WebRTCReceiver receives a media track @@ -203,33 +202,27 @@ func NewWebRTCReceiver( }) w.connectionStats = connectionquality.NewConnectionStats(connectionquality.ConnectionStatsParams{ - CodecType: w.kind, - CodecName: getCodecNameFromMime(w.codec.MimeType), MimeType: w.codec.MimeType, GetDeltaStats: w.getDeltaStats, - IsDtxDisabled: w.IsDtxDisabled, - GetLayerDimension: w.GetLayerDimension, GetMaxExpectedLayer: w.streamTrackerManager.GetMaxExpectedLayer, - GetIsReducedQuality: w.streamTrackerManager.IsReducedQuality, - Logger: w.logger, + GetIsReducedQuality: func() (int32, bool) { + distance := w.streamTrackerManager.DistanceToDesired() + return distance, distance > 0 + }, + Logger: w.logger, }) - w.connectionStats.SetTrackSource(w.trackInfo.Source) w.connectionStats.OnStatsUpdate(func(_cs *connectionquality.ConnectionStats, stat *livekit.AnalyticsStat) { if w.onStatsUpdate != nil { w.onStatsUpdate(w, stat) } }) - w.connectionStats.Start() + w.connectionStats.Start(w.trackInfo) return w } -func (w *WebRTCReceiver) TrackSource() livekit.TrackSource { - return w.trackInfo.Source -} - -func (w *WebRTCReceiver) IsDtxDisabled() bool { - return w.trackInfo.DisableDtx +func (w *WebRTCReceiver) TrackInfo() *livekit.TrackInfo { + return w.trackInfo } func (w *WebRTCReceiver) GetLayerDimension(layer int32) (uint32, uint32) { diff --git a/pkg/sfu/streamtrackermanager.go b/pkg/sfu/streamtrackermanager.go index d9596aa8..e3fb716e 100644 --- a/pkg/sfu/streamtrackermanager.go +++ b/pkg/sfu/streamtrackermanager.go @@ -256,11 +256,24 @@ func (s *StreamTrackerManager) SetMaxExpectedSpatialLayer(layer int32) { } } -func (s *StreamTrackerManager) IsReducedQuality() bool { +func (s *StreamTrackerManager) DistanceToDesired() int32 { s.lock.RLock() defer s.lock.RUnlock() - return int32(len(s.availableLayers)) < (s.maxExpectedLayer + 1) + if s.paused || s.maxExpectedLayer == DefaultMaxLayerSpatial { + return 0 + } + + if len(s.availableLayers) == 0 { + return s.maxExpectedLayer + 1 + } + + distance := s.maxExpectedLayer - s.availableLayers[len(s.availableLayers)-1] + if distance < 0 { + distance = 0 + } + + return distance } func (s *StreamTrackerManager) GetLayerDimension(layer int32) (uint32, uint32) { @@ -282,7 +295,7 @@ func (s *StreamTrackerManager) GetLayerDimension(layer int32) (uint32, uint32) { return width, height } -func (s *StreamTrackerManager) GetMaxExpectedLayer() (layer int32, width uint32, height uint32) { +func (s *StreamTrackerManager) GetMaxExpectedLayer() int32 { s.lock.RLock() defer s.lock.RUnlock() @@ -291,13 +304,7 @@ func (s *StreamTrackerManager) GetMaxExpectedLayer() (layer int32, width uint32, if maxExpectedLayer > s.maxPublishedLayer { maxExpectedLayer = s.maxPublishedLayer } - for _, layer := range s.trackInfo.Layers { - if maxExpectedLayer == utils.SpatialLayerForQuality(layer.Quality) { - return maxExpectedLayer, layer.Width, layer.Height - } - } - - return maxExpectedLayer, 0, 0 + return maxExpectedLayer } func (s *StreamTrackerManager) GetBitrateTemporalCumulative() Bitrates {