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
This commit is contained in:
Raja Subramanian
2023-03-05 12:55:04 +05:30
committed by GitHub
parent e22de045ba
commit 9e327b1f3c
19 changed files with 1216 additions and 940 deletions
+1 -2
View File
@@ -8,6 +8,7 @@ require (
github.com/dustin/go-humanize v1.0.1 github.com/dustin/go-humanize v1.0.1
github.com/elliotchance/orderedmap/v2 v2.2.0 github.com/elliotchance/orderedmap/v2 v2.2.0
github.com/florianl/go-tc v0.4.2 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/deque v0.1.0
github.com/gammazero/workerpool v1.1.2 github.com/gammazero/workerpool v1.1.2
github.com/google/wire v0.5.0 github.com/google/wire v0.5.0
@@ -19,7 +20,6 @@ require (
github.com/livekit/mediatransportutil v0.0.0-20230130133657-96cfb115473a github.com/livekit/mediatransportutil v0.0.0-20230130133657-96cfb115473a
github.com/livekit/protocol v1.4.3-0.20230303025609-c0705dbb696a github.com/livekit/protocol v1.4.3-0.20230303025609-c0705dbb696a
github.com/livekit/psrpc v0.2.10-0.20230303054701-5853a56b4643 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/mackerelio/go-osstat v0.2.3
github.com/magefile/mage v1.14.0 github.com/magefile/mage v1.14.0
github.com/maxbrunsfeld/counterfeiter/v6 v6.6.1 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/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/eapache/channels v1.1.0 // indirect github.com/eapache/channels v1.1.0 // indirect
github.com/eapache/queue 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/go-logr/logr v1.2.3 // indirect
github.com/golang/protobuf v1.5.2 // indirect github.com/golang/protobuf v1.5.2 // indirect
github.com/google/go-cmp v0.5.9 // indirect github.com/google/go-cmp v0.5.9 // indirect
-2
View File
@@ -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/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 h1:ftDwqesgXMu0hUXFxf4KWAqqDIXz8BBdNnit3xc6RQA=
github.com/livekit/psrpc v0.2.10-0.20230303054701-5853a56b4643/go.mod h1:K0j8f1PgLShR7Lx80KbmwFkDH2BvOnycXGV0OSRURKc= 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 h1:jAMXD5erlDE39kdX2CU7YwCGRcxIO33u/p8+Fhe5dJw=
github.com/mackerelio/go-osstat v0.2.3/go.mod h1:DQbPOnsss9JHIXgBStc/dnhhir3gbd3YH+Dbdi7ptMA= 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= github.com/magefile/mage v1.14.0 h1:6QDX3g6z1YvJ4olPhT1wksUcSa/V0a1B+pJb73fBjyo=
+2 -3
View File
@@ -140,9 +140,8 @@ func (d *DynacastManager) getOrCreateDynacastQuality(mime string) *DynacastQuali
} }
dq := NewDynacastQuality(DynacastQualityParams{ dq := NewDynacastQuality(DynacastQualityParams{
MimeType: mime, MimeType: mime,
DynacastPauseDelay: d.params.DynacastPauseDelay, Logger: d.params.Logger,
Logger: d.params.Logger,
}) })
dq.OnSubscribedMaxQualityChange(func(maxQuality livekit.VideoQuality) { dq.OnSubscribedMaxQualityChange(func(maxQuality livekit.VideoQuality) {
d.updateMaxQualityForMime(mime, maxQuality) d.updateMaxQualityForMime(mime, maxQuality)
+2 -3
View File
@@ -13,9 +13,8 @@ const (
) )
type DynacastQualityParams struct { type DynacastQualityParams struct {
MimeType string MimeType string
DynacastPauseDelay time.Duration Logger logger.Logger
Logger logger.Logger
} }
// DynacastQuality manages max subscribed quality of a single receiver of a media track // DynacastQuality manages max subscribed quality of a single receiver of a media track
+5 -3
View File
@@ -18,6 +18,7 @@ import (
"github.com/livekit/livekit-server/pkg/rtc/types" "github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/sfu" "github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/livekit-server/pkg/sfu/buffer" "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/livekit-server/pkg/telemetry"
) )
@@ -312,12 +313,13 @@ func (t *MediaTrack) AddReceiver(receiver *webrtc.RTPReceiver, track *webrtc.Tra
return newCodec return newCodec
} }
func (t *MediaTrack) GetConnectionScore() float32 { func (t *MediaTrack) GetConnectionScoreAndQuality() (float32, livekit.ConnectionQuality) {
receiver := t.PrimaryReceiver() receiver := t.PrimaryReceiver()
if rtcReceiver, ok := receiver.(*sfu.WebRTCReceiver); ok { 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) { func (t *MediaTrack) SetRTT(rtt uint32) {
+27 -31
View File
@@ -23,7 +23,6 @@ import (
"github.com/livekit/livekit-server/pkg/rtc/types" "github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/sfu" "github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/livekit-server/pkg/sfu/buffer" "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/livekit-server/pkg/telemetry"
"github.com/livekit/mediatransportutil/pkg/twcc" "github.com/livekit/mediatransportutil/pkg/twcc"
"github.com/livekit/protocol/auth" "github.com/livekit/protocol/auth"
@@ -818,35 +817,45 @@ func (p *ParticipantImpl) GetAudioLevel() (level float64, active bool) {
} }
func (p *ParticipantImpl) GetConnectionQuality() *livekit.ConnectionQualityInfo { func (p *ParticipantImpl) GetConnectionQuality() *livekit.ConnectionQualityInfo {
publisherScores := p.getPublisherConnectionQuality() numTracks := 0
minQuality := livekit.ConnectionQuality_EXCELLENT
minScore := float32(0.0)
numTracks := len(publisherScores) for _, pt := range p.GetPublishedTracks() {
totalScore := float32(0.0) numTracks++
for _, score := range publisherScores {
totalScore += score 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() subscribedTracks := p.SubscriptionManager.GetSubscribedTracks()
subscriberScores := make(map[livekit.TrackID]float32, len(subscribedTracks))
for _, subTrack := range subscribedTracks { for _, subTrack := range subscribedTracks {
if subTrack.IsMuted() || subTrack.MediaTrack().IsMuted() {
continue
}
score := subTrack.DownTrack().GetConnectionScore()
subscriberScores[subTrack.ID()] = score
totalScore += score
numTracks++ 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 {
if numTracks > 0 { return nil
avgScore = totalScore / float32(numTracks)
} }
return &livekit.ConnectionQualityInfo{ return &livekit.ConnectionQualityInfo{
ParticipantSid: string(p.ID()), ParticipantSid: string(p.ID()),
Quality: connectionquality.Score2Rating(avgScore), Quality: minQuality,
Score: avgScore, 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) { func (p *ParticipantImpl) mediaTrackReceived(track *webrtc.TrackRemote, rtpReceiver *webrtc.RTPReceiver) (*MediaTrack, bool) {
p.pendingTracksLock.Lock() p.pendingTracksLock.Lock()
newTrack := false newTrack := false
+5 -3
View File
@@ -308,9 +308,11 @@ func (r *Room) Join(participant types.LocalParticipant, opts *ParticipantOptions
}, false) }, false)
} }
update := &livekit.ConnectionQualityUpdate{} if cq := pub.GetConnectionQuality(); cq != nil {
update.Updates = append(update.Updates, pub.GetConnectionQuality()) update := &livekit.ConnectionQualityUpdate{}
_ = participant.SendConnectionQualityUpdate(update) update.Updates = append(update.Updates, cq)
_ = participant.SendConnectionQualityUpdate(update)
}
} }
} else { } else {
// no longer subscribed to the publisher, clear speaker status // no longer subscribed to the publisher, clear speaker status
+1 -1
View File
@@ -405,7 +405,7 @@ type LocalMediaTrack interface {
HasSdpCid(cid string) bool HasSdpCid(cid string) bool
GetAudioLevel() (level float64, active bool) GetAudioLevel() (level float64, active bool)
GetConnectionScore() float32 GetConnectionScoreAndQuality() (float32, livekit.ConnectionQuality)
SetRTT(rtt uint32) SetRTT(rtt uint32)
@@ -60,15 +60,17 @@ type FakeLocalMediaTrack struct {
result1 float64 result1 float64
result2 bool result2 bool
} }
GetConnectionScoreStub func() float32 GetConnectionScoreAndQualityStub func() (float32, livekit.ConnectionQuality)
getConnectionScoreMutex sync.RWMutex getConnectionScoreAndQualityMutex sync.RWMutex
getConnectionScoreArgsForCall []struct { getConnectionScoreAndQualityArgsForCall []struct {
} }
getConnectionScoreReturns struct { getConnectionScoreAndQualityReturns struct {
result1 float32 result1 float32
result2 livekit.ConnectionQuality
} }
getConnectionScoreReturnsOnCall map[int]struct { getConnectionScoreAndQualityReturnsOnCall map[int]struct {
result1 float32 result1 float32
result2 livekit.ConnectionQuality
} }
GetNumSubscribersStub func() int GetNumSubscribersStub func() int
getNumSubscribersMutex sync.RWMutex getNumSubscribersMutex sync.RWMutex
@@ -578,57 +580,60 @@ func (fake *FakeLocalMediaTrack) GetAudioLevelReturnsOnCall(i int, result1 float
}{result1, result2} }{result1, result2}
} }
func (fake *FakeLocalMediaTrack) GetConnectionScore() float32 { func (fake *FakeLocalMediaTrack) GetConnectionScoreAndQuality() (float32, livekit.ConnectionQuality) {
fake.getConnectionScoreMutex.Lock() fake.getConnectionScoreAndQualityMutex.Lock()
ret, specificReturn := fake.getConnectionScoreReturnsOnCall[len(fake.getConnectionScoreArgsForCall)] ret, specificReturn := fake.getConnectionScoreAndQualityReturnsOnCall[len(fake.getConnectionScoreAndQualityArgsForCall)]
fake.getConnectionScoreArgsForCall = append(fake.getConnectionScoreArgsForCall, struct { fake.getConnectionScoreAndQualityArgsForCall = append(fake.getConnectionScoreAndQualityArgsForCall, struct {
}{}) }{})
stub := fake.GetConnectionScoreStub stub := fake.GetConnectionScoreAndQualityStub
fakeReturns := fake.getConnectionScoreReturns fakeReturns := fake.getConnectionScoreAndQualityReturns
fake.recordInvocation("GetConnectionScore", []interface{}{}) fake.recordInvocation("GetConnectionScoreAndQuality", []interface{}{})
fake.getConnectionScoreMutex.Unlock() fake.getConnectionScoreAndQualityMutex.Unlock()
if stub != nil { if stub != nil {
return stub() return stub()
} }
if specificReturn { if specificReturn {
return ret.result1 return ret.result1, ret.result2
} }
return fakeReturns.result1 return fakeReturns.result1, fakeReturns.result2
} }
func (fake *FakeLocalMediaTrack) GetConnectionScoreCallCount() int { func (fake *FakeLocalMediaTrack) GetConnectionScoreAndQualityCallCount() int {
fake.getConnectionScoreMutex.RLock() fake.getConnectionScoreAndQualityMutex.RLock()
defer fake.getConnectionScoreMutex.RUnlock() defer fake.getConnectionScoreAndQualityMutex.RUnlock()
return len(fake.getConnectionScoreArgsForCall) return len(fake.getConnectionScoreAndQualityArgsForCall)
} }
func (fake *FakeLocalMediaTrack) GetConnectionScoreCalls(stub func() float32) { func (fake *FakeLocalMediaTrack) GetConnectionScoreAndQualityCalls(stub func() (float32, livekit.ConnectionQuality)) {
fake.getConnectionScoreMutex.Lock() fake.getConnectionScoreAndQualityMutex.Lock()
defer fake.getConnectionScoreMutex.Unlock() defer fake.getConnectionScoreAndQualityMutex.Unlock()
fake.GetConnectionScoreStub = stub fake.GetConnectionScoreAndQualityStub = stub
} }
func (fake *FakeLocalMediaTrack) GetConnectionScoreReturns(result1 float32) { func (fake *FakeLocalMediaTrack) GetConnectionScoreAndQualityReturns(result1 float32, result2 livekit.ConnectionQuality) {
fake.getConnectionScoreMutex.Lock() fake.getConnectionScoreAndQualityMutex.Lock()
defer fake.getConnectionScoreMutex.Unlock() defer fake.getConnectionScoreAndQualityMutex.Unlock()
fake.GetConnectionScoreStub = nil fake.GetConnectionScoreAndQualityStub = nil
fake.getConnectionScoreReturns = struct { fake.getConnectionScoreAndQualityReturns = struct {
result1 float32 result1 float32
}{result1} result2 livekit.ConnectionQuality
}{result1, result2}
} }
func (fake *FakeLocalMediaTrack) GetConnectionScoreReturnsOnCall(i int, result1 float32) { func (fake *FakeLocalMediaTrack) GetConnectionScoreAndQualityReturnsOnCall(i int, result1 float32, result2 livekit.ConnectionQuality) {
fake.getConnectionScoreMutex.Lock() fake.getConnectionScoreAndQualityMutex.Lock()
defer fake.getConnectionScoreMutex.Unlock() defer fake.getConnectionScoreAndQualityMutex.Unlock()
fake.GetConnectionScoreStub = nil fake.GetConnectionScoreAndQualityStub = nil
if fake.getConnectionScoreReturnsOnCall == nil { if fake.getConnectionScoreAndQualityReturnsOnCall == nil {
fake.getConnectionScoreReturnsOnCall = make(map[int]struct { fake.getConnectionScoreAndQualityReturnsOnCall = make(map[int]struct {
result1 float32 result1 float32
result2 livekit.ConnectionQuality
}) })
} }
fake.getConnectionScoreReturnsOnCall[i] = struct { fake.getConnectionScoreAndQualityReturnsOnCall[i] = struct {
result1 float32 result1 float32
}{result1} result2 livekit.ConnectionQuality
}{result1, result2}
} }
func (fake *FakeLocalMediaTrack) GetNumSubscribers() int { func (fake *FakeLocalMediaTrack) GetNumSubscribers() int {
@@ -1930,8 +1935,8 @@ func (fake *FakeLocalMediaTrack) Invocations() map[string][][]interface{} {
defer fake.getAllSubscribersMutex.RUnlock() defer fake.getAllSubscribersMutex.RUnlock()
fake.getAudioLevelMutex.RLock() fake.getAudioLevelMutex.RLock()
defer fake.getAudioLevelMutex.RUnlock() defer fake.getAudioLevelMutex.RUnlock()
fake.getConnectionScoreMutex.RLock() fake.getConnectionScoreAndQualityMutex.RLock()
defer fake.getConnectionScoreMutex.RUnlock() defer fake.getConnectionScoreAndQualityMutex.RUnlock()
fake.getNumSubscribersMutex.RLock() fake.getNumSubscribersMutex.RLock()
defer fake.getNumSubscribersMutex.RUnlock() defer fake.getNumSubscribersMutex.RUnlock()
fake.getQualityForDimensionMutex.RLock() fake.getQualityForDimensionMutex.RLock()
-7
View File
@@ -259,13 +259,6 @@ func (d *DummyReceiver) DebugInfo() map[string]interface{} {
return nil 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 { func (d *DummyReceiver) GetTemporalLayerFpsForSpatial(spatial int32) []float32 {
if r, ok := d.receiver.Load().(sfu.TrackReceiver); ok { if r, ok := d.receiver.Load().(sfu.TrackReceiver); ok {
return r.GetTemporalLayerFpsForSpatial(spatial) return r.GetTemporalLayerFpsForSpatial(spatial)
+20 -2
View File
@@ -42,6 +42,7 @@ type IntervalStats struct {
} }
type RTPDeltaInfo struct { type RTPDeltaInfo struct {
StartTime time.Time
Duration time.Duration Duration time.Duration
Packets uint32 Packets uint32
Bytes uint64 Bytes uint64
@@ -270,7 +271,8 @@ func (r *RTPStats) Seed(from *RTPStats) {
r.nextSnapshotId = from.nextSnapshotId r.nextSnapshotId = from.nextSnapshotId
for id, ss := range from.snapshots { 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 // initialize snapshots if any
for i := uint32(FirstSnapshotId); i < r.nextSnapshotId; i++ { 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) packetsLost := uint32(0)
intervalStats := r.getIntervalStats(uint16(then.extStartSN), uint16(now.extStartSN)) intervalStats := r.getIntervalStats(uint16(then.extStartSN), uint16(now.extStartSN))
if r.params.IsReceiverReportDriven { 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 packetsLost = now.packetsLostOverridden - then.packetsLostOverridden
if int32(packetsLost) < 0 { if int32(packetsLost) < 0 {
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 { } else {
packetsLost = intervalStats.packetsLost packetsLost = intervalStats.packetsLost
} }
@@ -883,6 +899,7 @@ func (r *RTPStats) DeltaInfo(snapshotId uint32) *RTPDeltaInfo {
maxJitterTime := maxJitter / float64(r.params.ClockRate) * 1e6 maxJitterTime := maxJitter / float64(r.params.ClockRate) * 1e6
return &RTPDeltaInfo{ return &RTPDeltaInfo{
StartTime: then.startTime,
Duration: now.startTime.Sub(then.startTime), Duration: now.startTime.Sub(then.startTime),
Packets: packetsExpected - intervalStats.packetsPadding, Packets: packetsExpected - intervalStats.packetsPadding,
Bytes: intervalStats.bytes, Bytes: intervalStats.bytes,
@@ -1254,6 +1271,7 @@ func (r *RTPStats) getAndResetSnapshot(snapshotId uint32) (*Snapshot, *Snapshot)
then := r.snapshots[snapshotId] then := r.snapshots[snapshotId]
if then == nil { if then == nil {
then = &Snapshot{ then = &Snapshot{
startTime: r.startTime,
extStartSN: r.extStartSN, extStartSN: r.extStartSN,
} }
r.snapshots[snapshotId] = then r.snapshots[snapshotId] = then
+92 -238
View File
@@ -2,13 +2,13 @@ package connectionquality
import ( import (
"strings" "strings"
"sync"
"time" "time"
"go.uber.org/atomic" "github.com/frostbyte73/core"
"github.com/livekit/protocol/livekit" "github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger" "github.com/livekit/protocol/logger"
"github.com/pion/webrtc/v3"
"github.com/livekit/livekit-server/pkg/sfu/buffer" "github.com/livekit/livekit-server/pkg/sfu/buffer"
) )
@@ -19,240 +19,96 @@ const (
) )
type ConnectionStatsParams struct { type ConnectionStatsParams struct {
UpdateInterval time.Duration UpdateInterval time.Duration
MimeType string MimeType string
GetDeltaStats func() map[uint32]*buffer.StreamStatsWithLayers IsFECEnabled bool
GetMaxExpectedLayer func() int32 GetDeltaStats func() map[uint32]*buffer.StreamStatsWithLayers
GetCurrentLayerSpatial func() int32 Logger logger.Logger
GetIsReducedQuality func() (int32, bool)
Logger logger.Logger
} }
type ConnectionStats struct { type ConnectionStats struct {
params ConnectionStatsParams params ConnectionStatsParams
codecName string trackInfo *livekit.TrackInfo
trackInfo *livekit.TrackInfo
normFactors [buffer.DefaultMaxLayerSpatial + 1]float32
onStatsUpdate func(cs *ConnectionStats, stat *livekit.AnalyticsStat) onStatsUpdate func(cs *ConnectionStats, stat *livekit.AnalyticsStat)
lock sync.RWMutex scorer *qualityScorer
score float32
lastUpdate time.Time
maxExpectedLayer int32
done chan struct{} done core.Fuse
isClosed atomic.Bool
} }
func NewConnectionStats(params ConnectionStatsParams) *ConnectionStats { func NewConnectionStats(params ConnectionStatsParams) *ConnectionStats {
return &ConnectionStats{ return &ConnectionStats{
params: params, params: params,
codecName: getCodecNameFromMime(params.MimeType), // LK-TODO: have to notify on codec change scorer: newQualityScorer(qualityScorerParams{
normFactors: [buffer.DefaultMaxLayerSpatial + 1]float32{1, 1, 1}, PacketLossWeight: getPacketLossWeight(params.MimeType, params.IsFECEnabled), // LK-TODO: have to notify codec change?
score: MaxScore, Logger: params.Logger,
maxExpectedLayer: buffer.InvalidLayerSpatial, }),
done: make(chan struct{}), done: core.NewFuse(),
} }
} }
func (cs *ConnectionStats) Start(trackInfo *livekit.TrackInfo) { func (cs *ConnectionStats) Start(trackInfo *livekit.TrackInfo, at time.Time) {
cs.lock.Lock()
cs.trackInfo = trackInfo cs.trackInfo = trackInfo
// cs.scorer.Start(at)
// 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()
go cs.updateStatsWorker() go cs.updateStatsWorker()
} }
func (cs *ConnectionStats) Close() { func (cs *ConnectionStats) Close() {
if cs.isClosed.Swap(true) { cs.done.Break()
return
}
close(cs.done)
} }
func (cs *ConnectionStats) OnStatsUpdate(fn func(cs *ConnectionStats, stat *livekit.AnalyticsStat)) { func (cs *ConnectionStats) OnStatsUpdate(fn func(cs *ConnectionStats, stat *livekit.AnalyticsStat)) {
cs.onStatsUpdate = fn cs.onStatsUpdate = fn
} }
func (cs *ConnectionStats) GetScore() float32 { func (cs *ConnectionStats) UpdateMute(isMuted bool, at time.Time) {
cs.lock.RLock() cs.scorer.UpdateMute(isMuted, at)
defer cs.lock.RUnlock()
return cs.score
} }
func (cs *ConnectionStats) getLayerDimensions(layer int32) (uint32, uint32) { func (cs *ConnectionStats) AddTransition(bitrate int64, at time.Time) {
if cs.trackInfo == nil { cs.scorer.AddTransition(bitrate, at)
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) updateScore(streams map[uint32]*buffer.StreamStatsWithLayers) float32 { func (cs *ConnectionStats) GetScoreAndQuality() (float32, livekit.ConnectionQuality) {
cs.lock.Lock() return cs.scorer.GetMOSAndQuality()
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) 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 { if cs.params.GetDeltaStats == nil {
return nil return nil
} }
streams := cs.params.GetDeltaStats() streams := cs.params.GetDeltaStats()
if len(streams) == 0 { if len(streams) == 0 {
cs.updateScore(streams, at)
return nil return nil
} }
@@ -274,7 +130,7 @@ func (cs *ConnectionStats) getStat() *livekit.AnalyticsStat {
analyticsStreams = append(analyticsStreams, as) analyticsStreams = append(analyticsStreams, as)
} }
score := cs.updateScore(streams) score := cs.updateScore(streams, at)
return &livekit.AnalyticsStat{ return &livekit.AnalyticsStat{
Score: score, Score: score,
@@ -294,11 +150,15 @@ func (cs *ConnectionStats) updateStatsWorker() {
for { for {
select { select {
case <-cs.done: case <-cs.done.Watch():
return return
case <-tk.C: case <-tk.C:
stat := cs.getStat() if cs.done.IsClosed() {
return
}
stat := cs.getStat(time.Now())
if stat == nil { if stat == nil {
continue continue
} }
@@ -312,13 +172,39 @@ func (cs *ConnectionStats) updateStatsWorker() {
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
func getCodecNameFromMime(mime string) string { // how much weight to give to packet loss rate when calculating score.
codecName := "" // It is codec dependent.
codecParsed := strings.Split(strings.ToLower(mime), "/") // For audio:
if len(codecParsed) > 1 { // o Opus without FEC or RED suffers the most through packet loss, hence has the highest weight
codecName = codecParsed[1] // 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 { func toAnalyticsStream(ssrc uint32, deltaStats *buffer.RTPDeltaInfo) *livekit.AnalyticsStream {
@@ -348,35 +234,3 @@ func toAnalyticsVideoLayer(layer int32, layerStats *buffer.RTPDeltaInfo) *liveki
Frames: layerStats.Frames, 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,
}
}
+484 -349
View File
@@ -6,473 +6,608 @@ import (
"github.com/livekit/livekit-server/pkg/sfu/buffer" "github.com/livekit/livekit-server/pkg/sfu/buffer"
"github.com/livekit/protocol/livekit" "github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
"github.com/stretchr/testify/require" "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) { func TestConnectionQuality(t *testing.T) {
t.Run("audio quality changes over time", func(t *testing.T) { t.Run("quality scorer state machine", func(t *testing.T) {
cs := NewConnectionStats(ConnectionStatsParams{ cs := newConnectionStats("audio/opus", false)
MimeType: "audio/opus",
}) duration := 5 * time.Second
cs.Start(&livekit.TrackInfo{Type: livekit.TrackType_AUDIO}) 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 // no data and not enough unmute time should return default state which is EXCELLENT quality
cs.updateScore(nil) cs.updateScore(nil, now)
require.Equal(t, float32(5), cs.GetScore()) 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{ streams := map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{
Layers: map[int32]*buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
0: &buffer.RTPDeltaInfo{ StartTime: now,
Duration: 2 * time.Second, Duration: duration,
Packets: 100, Packets: 250,
Bytes: 20000 * 2 / 8, // 20 kbps
},
}, },
}, },
} }
cs.updateScore(streams) cs.updateScore(streams, now.Add(duration))
require.Equal(t, float32(5), cs.GetScore()) 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{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{
Layers: map[int32]*buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
0: &buffer.RTPDeltaInfo{ StartTime: now,
Duration: 2 * time.Second, Duration: duration,
Packets: 100, Packets: 250,
PacketsLost: 10, PacketsLost: 25,
Bytes: 18000 * 2 / 8, // 20 kbps - 2 kbps, i. e 10% lost
},
}, },
}, },
} }
cs.updateScore(streams) cs.updateScore(streams, now.Add(duration))
lossQuality := cs.GetScore() mos, quality = cs.GetScoreAndQuality()
require.Less(t, lossQuality, float32(3.55)) require.Greater(t, float32(3.2), mos)
require.Equal(t, livekit.ConnectionQuality_POOR, quality)
// small packet rate, should avoid calculation as it does not meet DTX threshold
streams = map[uint32]*buffer.StreamStatsWithLayers{ // should stay at POOR quality for poor threshold wait even if the conditions improve
1: &buffer.StreamStatsWithLayers{ for i := 0; i < 3; i++ {
Layers: map[int32]*buffer.RTPDeltaInfo{ now = now.Add(duration)
0: &buffer.RTPDeltaInfo{ streams = map[uint32]*buffer.StreamStatsWithLayers{
Duration: 2 * time.Second, 1: &buffer.StreamStatsWithLayers{
Packets: 44, RTPStats: &buffer.RTPDeltaInfo{
PacketsLost: 4, StartTime: now,
Bytes: 1000 * 2 / 8, // 1 kbps, DTX 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{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{
Layers: map[int32]*buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
0: &buffer.RTPDeltaInfo{ StartTime: now,
Duration: 2 * time.Second, Duration: duration,
Packets: 100, Packets: 250,
PacketsLost: 10,
Bytes: 18000 * 2 / 8, // 20 kbps - 2 kbps, i. e 10% lost
RttMax: 50, // ms
},
}, },
}, },
} }
cs.updateScore(streams) cs.updateScore(streams, now.Add(duration))
rttQuality := cs.GetScore() mos, quality = cs.GetScoreAndQuality()
require.Less(t, rttQuality, lossQuality) 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{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{
Layers: map[int32]*buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
0: &buffer.RTPDeltaInfo{ StartTime: now,
Duration: 2 * time.Second, Duration: duration,
Packets: 100, Packets: 250,
PacketsLost: 10, PacketsLost: 8,
Bytes: 18000 * 2 / 8, // 20 kbps - 2 kbps, i. e 10% lost
RttMax: 50, // ms
JitterMax: 10000, // us
},
}, },
}, },
} }
cs.updateScore(streams) cs.updateScore(streams, now.Add(duration))
require.Less(t, cs.GetScore(), rttQuality) mos, quality = cs.GetScoreAndQuality()
}) require.Greater(t, float32(4.1), mos)
require.Equal(t, livekit.ConnectionQuality_GOOD, quality)
t.Run("video quality changes over time", func(t *testing.T) {
maxExpectedLayer := int32(0) // should stay at GOOD quality for good threshold (which is shorter than poor threshold) wait even if the conditions improve
currentLayer := int32(0) for i := 0; i < 1; i++ {
isReducedQuality := false now = now.Add(duration)
streams = map[uint32]*buffer.StreamStatsWithLayers{
cs := NewConnectionStats(ConnectionStatsParams{ 1: &buffer.StreamStatsWithLayers{
MimeType: "video/VP8", RTPStats: &buffer.RTPDeltaInfo{
GetMaxExpectedLayer: func() int32 { StartTime: now,
return maxExpectedLayer Duration: duration,
}, Packets: 250,
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, cs.updateScore(streams, now.Add(duration))
Width: 640, mos, quality = cs.GetScoreAndQuality()
Height: 360, require.Greater(t, float32(4.1), mos)
Bitrate: 500_000, require.Equal(t, livekit.ConnectionQuality_GOOD, quality)
}, }
{
Quality: livekit.VideoQuality_LOW,
Width: 320,
Height: 180,
Bitrate: 150_000,
},
},
})
// first update does nothing // should return median quality which should be EXCELLENT as all windows in above loop have great conditions
cs.updateScore(nil) now = now.Add(duration)
require.Equal(t, float32(5), cs.GetScore()) streams = map[uint32]*buffer.StreamStatsWithLayers{
// 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{ 1: &buffer.StreamStatsWithLayers{
Layers: map[int32]*buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
0: &buffer.RTPDeltaInfo{ StartTime: now,
Duration: 2 * time.Second, Duration: duration,
Packets: 100, Packets: 250,
Bytes: 150_000 * 2 / 8, // 150 kbps
Frames: 30, // 15 fps
},
}, },
}, },
} }
cs.updateScore(streams) cs.updateScore(streams, now.Add(duration))
require.Equal(t, float32(5), cs.GetScore()) mos, quality = cs.GetScoreAndQuality()
require.Greater(t, float32(4.6), mos)
maxExpectedLayer = 1 require.Equal(t, livekit.ConnectionQuality_EXCELLENT, quality)
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 // POOR -> GOOD -> EXCELLENT should take longer
now = now.Add(duration)
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{
Layers: map[int32]*buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
1: &buffer.RTPDeltaInfo{ StartTime: now,
Duration: 2 * time.Second, Duration: duration,
Packets: 100, Packets: 250,
Bytes: 150_000 * 2 / 8, // 150 kbps PacketsLost: 25,
Frames: 30, // 15 fps
},
}, },
}, },
} }
cs.updateScore(streams) cs.updateScore(streams, now.Add(duration))
require.Less(t, cs.GetScore(), float32(5)) mos, quality = cs.GetScoreAndQuality()
require.Greater(t, float32(3.2), mos)
// layer 1 at optimal bit rate should give max score require.Equal(t, livekit.ConnectionQuality_POOR, quality)
streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ // should stay at POOR quality for poor threshold wait even if the conditions improve
Layers: map[int32]*buffer.RTPDeltaInfo{ for i := 0; i < 3; i++ {
1: &buffer.RTPDeltaInfo{ now = now.Add(duration)
Duration: 2 * time.Second, streams = map[uint32]*buffer.StreamStatsWithLayers{
Packets: 100, 1: &buffer.StreamStatsWithLayers{
Bytes: 500_000 * 2 / 8, // 500 kbps RTPStats: &buffer.RTPDeltaInfo{
Frames: 40, // 20 fps 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{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{
Layers: map[int32]*buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
1: &buffer.RTPDeltaInfo{ StartTime: now,
Duration: 2 * time.Second, Duration: duration,
Packets: 100, Packets: 250,
Bytes: 600_000 * 2 / 8, // 600 kbps, optimal is 500 kbps
Frames: 40, // 20 fps
},
}, },
}, },
} }
cs.updateScore(streams) cs.updateScore(streams, now.Add(duration))
require.Equal(t, float32(5), cs.GetScore()) mos, quality = cs.GetScoreAndQuality()
require.Greater(t, float32(4.1), mos)
require.Equal(t, livekit.ConnectionQuality_GOOD, quality)
maxExpectedLayer = 2 // another EXCELLENT quality window and the median should switch to EXCELLENT
currentLayer = 2 now = now.Add(duration)
// 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{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{
Layers: map[int32]*buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
2: &buffer.RTPDeltaInfo{ StartTime: now,
Duration: 2 * time.Second, Duration: duration,
Packets: 100, Packets: 250,
Bytes: 500_000 * 2 / 8, // 500 kbps
Frames: 40, // 20 fps
},
}, },
}, },
} }
cs.updateScore(streams) cs.updateScore(streams, now.Add(duration))
require.Less(t, cs.GetScore(), float32(5)) 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{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{
Layers: map[int32]*buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
2: &buffer.RTPDeltaInfo{ StartTime: now,
Duration: 2 * time.Second, Duration: duration,
Packets: 100, Packets: 250,
Bytes: 1_700_000 * 2 / 8, // 1.7 Mbps PacketsLost: 25,
Frames: 60, // 30 fps
},
}, },
}, },
} }
cs.updateScore(streams) cs.updateScore(streams, now.Add(duration))
require.Equal(t, float32(5), cs.GetScore()) 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{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{
Layers: map[int32]*buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
2: &buffer.RTPDeltaInfo{ StartTime: now,
Duration: 2 * time.Second, Duration: duration,
Packets: 100, Packets: 0,
Bytes: 1_530_000 * 2 / 8, // 1.7 Mbps - 170 kbps, i. e. 10% loss
Frames: 60, // 30 fps
},
}, },
}, },
} }
cs.updateScore(streams) cs.updateScore(streams, now.Add(duration))
score := cs.GetScore() mos, quality = cs.GetScoreAndQuality()
require.Less(t, score, float32(5)) 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{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{
Layers: map[int32]*buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
2: &buffer.RTPDeltaInfo{ StartTime: now,
Duration: 2 * time.Second, Duration: duration,
Packets: 100, Packets: 0,
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) cs.updateScore(streams, now.Add(duration))
require.Less(t, cs.GetScore(), score) mos, quality = cs.GetScoreAndQuality()
score = cs.GetScore() require.Greater(t, float32(3.2), mos)
require.Equal(t, livekit.ConnectionQuality_POOR, quality)
// adding jitter (i. e. delay) should reduce score further
// 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{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{
Layers: map[int32]*buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
2: &buffer.RTPDeltaInfo{ StartTime: now,
Duration: 2 * time.Second, Duration: duration,
Packets: 100, Packets: 50,
Bytes: 1_530_000 * 2 / 8, // 1.7 Mbps - 170 kbps, i. e. 10% loss PacketsLost: 5,
Frames: 60, // 30 fps
RttMax: 50, // ms
JitterMax: 10000, // us
},
}, },
}, },
} }
cs.updateScore(streams) cs.updateScore(streams, now.Add(duration))
require.Less(t, cs.GetScore(), score) mos, quality = cs.GetScoreAndQuality()
require.Greater(t, float32(4.1), mos)
// layer 2 max expected, but max available is layer 1 should reduce one level even if layer 1 is perfect require.Equal(t, livekit.ConnectionQuality_GOOD, quality)
currentLayer = 1
// 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{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{
Layers: map[int32]*buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
1: &buffer.RTPDeltaInfo{ StartTime: now,
Duration: 2 * time.Second, Duration: duration,
Packets: 100, Packets: 250,
Bytes: 500_000 * 2 / 8, // 500 kbps PacketsLost: 5,
Frames: 40, // 20 fps RttMax: 300,
}, JitterMax: 30000,
}, },
}, },
} }
cs.updateScore(streams) cs.updateScore(streams, now.Add(duration))
require.Less(t, float32(4), cs.GetScore()) 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 // bitrate based calculation can drop quality even if there is no loss
currentLayer = 0 cs.AddTransition(1_000_000, now)
cs.AddTransition(2_000_000, now.Add(2*time.Second))
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
0: &buffer.StreamStatsWithLayers{ 1: &buffer.StreamStatsWithLayers{
Layers: map[int32]*buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
0: &buffer.RTPDeltaInfo{ StartTime: now,
Duration: 2 * time.Second, Duration: duration,
Packets: 100, Packets: 250,
Bytes: 150_000 * 2 / 8, // 150 kbps Bytes: 8_000_000 / 8 / 4,
Frames: 30, // 15 fps
},
}, },
}, },
} }
cs.updateScore(streams) cs.updateScore(streams, now.Add(duration))
require.Less(t, float32(3), cs.GetScore()) 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) { t.Run("codecs - packets", func(t *testing.T) {
isReducedQuality := false type expectedQuality struct {
packetLossPercentage float64
cs := NewConnectionStats(ConnectionStatsParams{ expectedMOS float32
MimeType: "video/H264", expectedQuality livekit.ConnectionQuality
GetMaxExpectedLayer: func() int32 { }
return 1 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) { // "audio/opus" - fec - 0 <= loss < 3.75%: EXCELLENT, 3.75% <= loss < 7.5%: GOOD, >= 7.5%: POOR
return 0, isReducedQuality {
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,
},
},
}, },
}) // "audio/red" - no fec - 0 <= loss < 6.66%: EXCELLENT, 6.66% <= loss < 13.33%: GOOD, >= 13.33%: POOR
cs.Start(&livekit.TrackInfo{ {
Type: livekit.TrackType_VIDEO, name: "audio/red - no fec",
Source: livekit.TrackSource_SCREEN_SHARE, mimeType: "audio/red",
Layers: []*livekit.VideoLayer{ isFECEnabled: false,
{ packetsExpected: 200,
Width: 1920, expectedQualities: []expectedQuality{
Height: 1080, {
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,
},
}, },
}, },
}) // "audio/red" - fec - 0 <= loss < 10%: EXCELLENT, 10% <= loss < 20%: GOOD, >= 20%: POOR
{
// first update does nothing name: "audio/red - fec",
cs.updateScore(nil) mimeType: "audio/red",
require.Equal(t, float32(5), cs.GetScore()) isFECEnabled: true,
packetsExpected: 200,
// second update locks to expected layer expectedQualities: []expectedQuality{
cs.updateScore(nil) {
require.Equal(t, float32(5), cs.GetScore()) packetLossPercentage: 8.0,
expectedMOS: 4.6,
// perfect conditions should return a score of 5 expectedQuality: livekit.ConnectionQuality_EXCELLENT,
streams := map[uint32]*buffer.StreamStatsWithLayers{ },
1: &buffer.StreamStatsWithLayers{ {
Layers: map[int32]*buffer.RTPDeltaInfo{ packetLossPercentage: 18.0,
0: &buffer.RTPDeltaInfo{ expectedMOS: 4.1,
Duration: 2 * time.Second, expectedQuality: livekit.ConnectionQuality_GOOD,
Packets: 100, },
Bytes: 100000 * 2 / 8, // 100 kbps {
packetLossPercentage: 20.0,
expectedMOS: 3.2,
expectedQuality: livekit.ConnectionQuality_POOR,
}, },
}, },
}, },
} // "video/*" - 0 <= loss < 2%: EXCELLENT, 2% <= loss < 4%: GOOD, >= 4%: POOR
cs.updateScore(streams) {
require.Equal(t, float32(5), cs.GetScore()) name: "video/*",
mimeType: "video/vp8",
// introduce loss and the score should drop isFECEnabled: false,
streams = map[uint32]*buffer.StreamStatsWithLayers{ packetsExpected: 200,
1: &buffer.StreamStatsWithLayers{ expectedQualities: []expectedQuality{
Layers: map[int32]*buffer.RTPDeltaInfo{ {
0: &buffer.RTPDeltaInfo{ packetLossPercentage: 1.0,
Duration: 2 * time.Second, expectedMOS: 4.6,
Packets: 100, expectedQuality: livekit.ConnectionQuality_EXCELLENT,
PacketsLost: 10, },
Bytes: 90000 * 2 / 8, // 100 kbps - 10 kbps, i. e 10% lost {
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 t.Run("bytes", func(t *testing.T) {
streams = map[uint32]*buffer.StreamStatsWithLayers{ type transition struct {
1: &buffer.StreamStatsWithLayers{ bitrate int64
Layers: map[int32]*buffer.RTPDeltaInfo{ offset time.Duration
0: &buffer.RTPDeltaInfo{ }
Duration: 2 * time.Second, testCases := []struct {
Packets: 100, name string
PacketsLost: 2, transitions []transition
Bytes: 98000 * 2 / 8, // 100 kbps - 2 kbps, i. e. 2% loss 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) name: "good",
require.Equal(t, float32(4.5), cs.GetScore()) transitions: []transition{
{
// medium level loss, but not reduced quality should give a mid level score bitrate: 1_000_000,
streams = map[uint32]*buffer.StreamStatsWithLayers{ },
1: &buffer.StreamStatsWithLayers{ {
Layers: map[int32]*buffer.RTPDeltaInfo{ bitrate: 2_000_000,
0: &buffer.RTPDeltaInfo{ offset: 3 * time.Second,
Duration: 2 * time.Second,
Packets: 100,
PacketsLost: 3,
Bytes: 97000 * 2 / 8, // 100 kbps - 3 kbps, i. e 3% lost
}, },
}, },
bytes: 7_000_000 / 8 / 3,
expectedMOS: 4.1,
expectedQuality: livekit.ConnectionQuality_GOOD,
}, },
} {
cs.updateScore(streams) name: "poor",
require.Equal(t, float32(3.5), cs.GetScore()) transitions: []transition{
{
// medium level loss, reduced quality should give a mid level score bitrate: 2_000_000,
isReducedQuality = true },
streams = map[uint32]*buffer.StreamStatsWithLayers{ {
1: &buffer.StreamStatsWithLayers{ bitrate: 1_000_000,
Layers: map[int32]*buffer.RTPDeltaInfo{ offset: 3 * time.Second,
0: &buffer.RTPDeltaInfo{
Duration: 2 * time.Second,
Packets: 100,
PacketsLost: 3,
Bytes: 97000 * 2 / 8, // 100 kbps - 3 kbps, i. e 3% lost
}, },
}, },
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 for _, tc := range testCases {
streams = map[uint32]*buffer.StreamStatsWithLayers{ t.Run(tc.name, func(t *testing.T) {
1: &buffer.StreamStatsWithLayers{ cs := newConnectionStats("video/vp8", false)
Layers: map[int32]*buffer.RTPDeltaInfo{
0: &buffer.RTPDeltaInfo{ duration := 5 * time.Second
Duration: 2 * time.Second, now := time.Now()
Packets: 100, cs.Start(&livekit.TrackInfo{Type: livekit.TrackType_VIDEO}, now)
PacketsLost: 2,
Bytes: 99000 * 2 / 8, // 100 kbps - 1 kbps, i. e 1% lost 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())
}) })
} }
-134
View File
@@ -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 = &params.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
}
+471
View File
@@ -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)))
}
// ------------------------------------------
+7 -11
View File
@@ -263,15 +263,9 @@ func NewDownTrack(
d.connectionStats = connectionquality.NewConnectionStats(connectionquality.ConnectionStatsParams{ d.connectionStats = connectionquality.NewConnectionStats(connectionquality.ConnectionStatsParams{
MimeType: codecs[0].MimeType, // LK-TODO have to notify on codec change 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, GetDeltaStats: d.getDeltaStats,
GetMaxExpectedLayer: func() int32 { Logger: d.logger,
return d.forwarder.MaxLayers().Spatial
},
GetCurrentLayerSpatial: func() int32 {
return d.forwarder.CurrentLayers().Spatial
},
GetIsReducedQuality: d.forwarder.IsReducedQuality,
Logger: d.logger,
}) })
d.connectionStats.OnStatsUpdate(func(_cs *connectionquality.ConnectionStats, stat *livekit.AnalyticsStat) { d.connectionStats.OnStatsUpdate(func(_cs *connectionquality.ConnectionStats, stat *livekit.AnalyticsStat) {
if d.onStatsUpdate != nil { if d.onStatsUpdate != nil {
@@ -363,7 +357,7 @@ func (d *DownTrack) TrackInfoAvailable() {
if ti == nil { if ti == nil {
return 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 // 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 return
} }
d.connectionStats.UpdateMute(d.forwarder.IsAnyMuted(), time.Now())
// //
// Subscriber mute changes trigger a max layer notification. // Subscriber mute changes trigger a max layer notification.
// That could result in encoding layers getting turned on/off on publisher side // 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 { func (d *DownTrack) GetConnectionScoreAndQuality() (float32, livekit.ConnectionQuality) {
return d.connectionStats.GetScore() return d.connectionStats.GetScoreAndQuality()
} }
func (d *DownTrack) GetTrackStats() *livekit.RTPStats { func (d *DownTrack) GetTrackStats() *livekit.RTPStats {
+14 -26
View File
@@ -439,30 +439,6 @@ func (f *Forwarder) GetReferenceLayerSpatial() int32 {
return f.referenceLayerSpatial 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 { func (f *Forwarder) isDeficientLocked() bool {
return f.lastAllocation.isDeficient return f.lastAllocation.isDeficient
} }
@@ -1419,7 +1395,13 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in
return tp, nil return tp, nil
} else if tp.isSwitchingToTargetLayer { } else if tp.isSwitchingToTargetLayer {
// lock to target layer // 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 f.currentLayers.Spatial = f.targetLayers.Spatial
if !f.isTemporalSupported { if !f.isTemporalSupported {
f.currentLayers.Temporal = f.targetLayers.Temporal f.currentLayers.Temporal = f.targetLayers.Temporal
@@ -1442,7 +1424,13 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in
found := false found := false
if f.parkedLayers.IsValid() { if f.parkedLayers.IsValid() {
if f.parkedLayers.Spatial == layer { 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 f.currentLayers = f.parkedLayers
found = true found = true
} }
+41 -30
View File
@@ -55,7 +55,6 @@ type TrackReceiver interface {
DebugInfo() map[string]interface{} DebugInfo() map[string]interface{}
GetLayerDimension(layer int32) (uint32, uint32)
TrackInfo() *livekit.TrackInfo TrackInfo() *livekit.TrackInfo
// Get primary receiver if this receiver represents a RED codec; otherwise it will return itself // 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 kind webrtc.RTPCodecType
receiver *webrtc.RTPReceiver receiver *webrtc.RTPReceiver
codec webrtc.RTPCodecParameters codec webrtc.RTPCodecParameters
isSimulcast bool
isSVC bool isSVC bool
isRED bool isRED bool
onCloseHandler func() onCloseHandler func()
@@ -181,18 +179,16 @@ func NewWebRTCReceiver(
opts ...ReceiverOpts, opts ...ReceiverOpts,
) *WebRTCReceiver { ) *WebRTCReceiver {
w := &WebRTCReceiver{ w := &WebRTCReceiver{
logger: logger, logger: logger,
receiver: receiver, receiver: receiver,
trackID: livekit.TrackID(track.ID()), trackID: livekit.TrackID(track.ID()),
streamID: track.StreamID(), streamID: track.StreamID(),
codec: track.Codec(), codec: track.Codec(),
kind: track.Kind(), kind: track.Kind(),
// LK-TODO: this should be based on VideoLayers protocol message rather than RID based twcc: twcc,
isSimulcast: len(track.RID()) > 0, trackInfo: trackInfo,
twcc: twcc, isSVC: IsSvcCodec(track.Codec().MimeType),
trackInfo: trackInfo, isRED: IsRedCodec(track.Codec().MimeType),
isSVC: IsSvcCodec(track.Codec().MimeType),
isRED: IsRedCodec(track.Codec().MimeType),
} }
w.streamTrackerManager = NewStreamTrackerManager(logger, trackInfo, w.isSVC, w.codec.ClockRate, trackersConfig) w.streamTrackerManager = NewStreamTrackerManager(logger, trackInfo, w.isSVC, w.codec.ClockRate, trackersConfig)
@@ -210,21 +206,17 @@ func NewWebRTCReceiver(
}) })
w.connectionStats = connectionquality.NewConnectionStats(connectionquality.ConnectionStatsParams{ w.connectionStats = connectionquality.NewConnectionStats(connectionquality.ConnectionStatsParams{
MimeType: w.codec.MimeType, MimeType: w.codec.MimeType,
GetDeltaStats: w.getDeltaStats, IsFECEnabled: strings.EqualFold(w.codec.MimeType, webrtc.MimeTypeOpus) && strings.Contains(strings.ToLower(w.codec.SDPFmtpLine), "fec"),
GetMaxExpectedLayer: w.streamTrackerManager.GetMaxExpectedLayer, GetDeltaStats: w.getDeltaStats,
GetIsReducedQuality: func() (int32, bool) { Logger: w.logger,
distance := w.streamTrackerManager.DistanceToDesired()
return distance, distance > 0
},
Logger: w.logger,
}) })
w.connectionStats.OnStatsUpdate(func(_cs *connectionquality.ConnectionStats, stat *livekit.AnalyticsStat) { w.connectionStats.OnStatsUpdate(func(_cs *connectionquality.ConnectionStats, stat *livekit.AnalyticsStat) {
if w.onStatsUpdate != nil { if w.onStatsUpdate != nil {
w.onStatsUpdate(w, stat) w.onStatsUpdate(w, stat)
} }
}) })
w.connectionStats.Start(w.trackInfo) w.connectionStats.Start(w.trackInfo, time.Now())
return w return w
} }
@@ -233,10 +225,6 @@ func (w *WebRTCReceiver) TrackInfo() *livekit.TrackInfo {
return w.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)) { func (w *WebRTCReceiver) OnStatsUpdate(fn func(w *WebRTCReceiver, stat *livekit.AnalyticsStat)) {
w.onStatsUpdate = fn w.onStatsUpdate = fn
} }
@@ -245,8 +233,8 @@ func (w *WebRTCReceiver) OnMaxLayerChange(fn func(maxLayer int32)) {
w.streamTrackerManager.OnMaxLayerChanged(fn) w.streamTrackerManager.OnMaxLayerChanged(fn)
} }
func (w *WebRTCReceiver) GetConnectionScore() float32 { func (w *WebRTCReceiver) GetConnectionScoreAndQuality() (float32, livekit.ConnectionQuality) {
return w.connectionStats.GetScore() return w.connectionStats.GetScoreAndQuality()
} }
func (w *WebRTCReceiver) IsClosed() bool { func (w *WebRTCReceiver) IsClosed() bool {
@@ -377,6 +365,8 @@ func (w *WebRTCReceiver) SetUpTrackPaused(paused bool) {
buff.SetPaused(paused) buff.SetPaused(paused)
} }
w.bufferMu.RUnlock() w.bufferMu.RUnlock()
w.connectionStats.UpdateMute(paused, time.Now())
} }
func (w *WebRTCReceiver) AddDownTrack(track TrackSender) error { func (w *WebRTCReceiver) AddDownTrack(track TrackSender) error {
@@ -395,8 +385,26 @@ func (w *WebRTCReceiver) AddDownTrack(track TrackSender) error {
return nil 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) { func (w *WebRTCReceiver) SetMaxExpectedSpatialLayer(layer int32) {
w.streamTrackerManager.SetMaxExpectedSpatialLayer(layer) w.streamTrackerManager.SetMaxExpectedSpatialLayer(layer)
w.notifyMaxExpectedLayer(layer)
} }
func (w *WebRTCReceiver) downTrackLayerChange() { func (w *WebRTCReceiver) downTrackLayerChange() {
@@ -415,6 +423,8 @@ func (w *WebRTCReceiver) downTrackMaxPublishedLayerChange(maxPublishedLayer int3
for _, dt := range w.downTrackSpreader.GetDownTracks() { for _, dt := range w.downTrackSpreader.GetDownTracks() {
dt.UpTrackMaxPublishedLayerChange(maxPublishedLayer) dt.UpTrackMaxPublishedLayerChange(maxPublishedLayer)
} }
w.notifyMaxExpectedLayer(maxPublishedLayer)
} }
func (w *WebRTCReceiver) GetLayeredBitrate() ([]int32, Bitrates) { func (w *WebRTCReceiver) GetLayeredBitrate() ([]int32, Bitrates) {
@@ -636,7 +646,8 @@ func (w *WebRTCReceiver) closeTracks() {
func (w *WebRTCReceiver) DebugInfo() map[string]interface{} { func (w *WebRTCReceiver) DebugInfo() map[string]interface{} {
info := map[string]interface{}{ info := map[string]interface{}{
"Simulcast": w.isSimulcast, "SVC": w.isSVC,
"Simulcast": !w.isSVC && len(w.trackInfo.Layers) > 1,
} }
w.upTrackMu.RLock() w.upTrackMu.RLock()
-56
View File
@@ -264,62 +264,6 @@ func (s *StreamTrackerManager) SetMaxExpectedSpatialLayer(layer int32) int32 {
return prev 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 <expected, published> layer
maxExpectedLayer := s.maxExpectedLayer
if maxExpectedLayer > s.maxPublishedLayer {
maxExpectedLayer = s.maxPublishedLayer
}
return maxExpectedLayer
}
func (s *StreamTrackerManager) GetMaxPublishedLayer() int32 { func (s *StreamTrackerManager) GetMaxPublishedLayer() int32 {
s.lock.RLock() s.lock.RLock()
defer s.lock.RUnlock() defer s.lock.RUnlock()