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
+92 -238
View File
@@ -2,13 +2,13 @@ package connectionquality
import (
"strings"
"sync"
"time"
"go.uber.org/atomic"
"github.com/frostbyte73/core"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
"github.com/pion/webrtc/v3"
"github.com/livekit/livekit-server/pkg/sfu/buffer"
)
@@ -19,240 +19,96 @@ const (
)
type ConnectionStatsParams struct {
UpdateInterval time.Duration
MimeType string
GetDeltaStats func() map[uint32]*buffer.StreamStatsWithLayers
GetMaxExpectedLayer func() int32
GetCurrentLayerSpatial func() int32
GetIsReducedQuality func() (int32, bool)
Logger logger.Logger
UpdateInterval time.Duration
MimeType string
IsFECEnabled bool
GetDeltaStats func() map[uint32]*buffer.StreamStatsWithLayers
Logger logger.Logger
}
type ConnectionStats struct {
params ConnectionStatsParams
codecName string
trackInfo *livekit.TrackInfo
normFactors [buffer.DefaultMaxLayerSpatial + 1]float32
params ConnectionStatsParams
trackInfo *livekit.TrackInfo
onStatsUpdate func(cs *ConnectionStats, stat *livekit.AnalyticsStat)
lock sync.RWMutex
score float32
lastUpdate time.Time
maxExpectedLayer int32
scorer *qualityScorer
done chan struct{}
isClosed atomic.Bool
done core.Fuse
}
func NewConnectionStats(params ConnectionStatsParams) *ConnectionStats {
return &ConnectionStats{
params: params,
codecName: getCodecNameFromMime(params.MimeType), // LK-TODO: have to notify on codec change
normFactors: [buffer.DefaultMaxLayerSpatial + 1]float32{1, 1, 1},
score: MaxScore,
maxExpectedLayer: buffer.InvalidLayerSpatial,
done: make(chan struct{}),
params: params,
scorer: newQualityScorer(qualityScorerParams{
PacketLossWeight: getPacketLossWeight(params.MimeType, params.IsFECEnabled), // LK-TODO: have to notify codec change?
Logger: params.Logger,
}),
done: core.NewFuse(),
}
}
func (cs *ConnectionStats) Start(trackInfo *livekit.TrackInfo) {
cs.lock.Lock()
func (cs *ConnectionStats) Start(trackInfo *livekit.TrackInfo, at time.Time) {
cs.trackInfo = trackInfo
//
// get best score and calculate normalization factor.
// Raitonale: MOS modeling will yield a max score for a specific codec.
// That is outside the control of an SFU. SFU can impair quality due
// network issues. So, get the maximum for given codec and normalize
// it to the highest score. So, under perfect conditions, it will
// yield a MOS of 5 which is the highest rating. Any SFU induced impairment
// or network impairment will result in a lower score and that is
// the quality that is under SFU/infrastructure control.
//
if trackInfo.Type == livekit.TrackType_AUDIO {
// LK-TODO: would be good to have audio expected bitrate in Trackinfo
params := TrackScoreParams{
Duration: time.Second,
Codec: cs.codecName,
Bytes: 20000 / 8,
}
cs.normFactors[0] = MaxScore / AudioTrackScore(params, 1)
} else {
for _, layer := range cs.trackInfo.Layers {
spatial := buffer.VideoQualityToSpatialLayer(layer.Quality, cs.trackInfo)
// LK-TODO: would be good to have expected frame rate in Trackinfo
frameRate := uint32(30)
switch spatial {
case 0:
frameRate = 15
case 1:
frameRate = 20
}
params := TrackScoreParams{
Duration: time.Second,
Codec: cs.codecName,
Bytes: uint64(layer.Bitrate) / 8,
Width: layer.Width,
Height: layer.Height,
Frames: frameRate,
}
cs.normFactors[spatial] = MaxScore / VideoTrackScore(params, 1)
}
}
cs.lock.Unlock()
cs.scorer.Start(at)
go cs.updateStatsWorker()
}
func (cs *ConnectionStats) Close() {
if cs.isClosed.Swap(true) {
return
}
close(cs.done)
cs.done.Break()
}
func (cs *ConnectionStats) OnStatsUpdate(fn func(cs *ConnectionStats, stat *livekit.AnalyticsStat)) {
cs.onStatsUpdate = fn
}
func (cs *ConnectionStats) GetScore() float32 {
cs.lock.RLock()
defer cs.lock.RUnlock()
return cs.score
func (cs *ConnectionStats) UpdateMute(isMuted bool, at time.Time) {
cs.scorer.UpdateMute(isMuted, at)
}
func (cs *ConnectionStats) getLayerDimensions(layer int32) (uint32, uint32) {
if cs.trackInfo == nil {
return 0, 0
}
for _, l := range cs.trackInfo.Layers {
if layer == buffer.VideoQualityToSpatialLayer(l.Quality, cs.trackInfo) {
return l.Width, l.Height
}
}
return 0, 0
func (cs *ConnectionStats) AddTransition(bitrate int64, at time.Time) {
cs.scorer.AddTransition(bitrate, at)
}
func (cs *ConnectionStats) updateScore(streams map[uint32]*buffer.StreamStatsWithLayers) float32 {
cs.lock.Lock()
defer cs.lock.Unlock()
// Initial interval will have partial data
if cs.lastUpdate.IsZero() {
cs.lastUpdate = time.Now()
cs.score = MaxScore
return cs.score
}
cs.lastUpdate = time.Now()
var params TrackScoreParams
switch {
case cs.trackInfo.Type == livekit.TrackType_AUDIO:
maxAvailableLayer, maxAvailableLayerStats := getMaxAvailableLayerStats(streams, 0)
if maxAvailableLayerStats == nil {
// retain old score as stats will not be available when muted
break
}
params = getTrackScoreParams(cs.codecName, maxAvailableLayerStats)
packetRate := float64(params.PacketsExpected) / maxAvailableLayerStats.Duration.Seconds()
if packetRate < audioPacketRateThreshold {
// With DTX, it is possible to have fewer packets per second.
// A loss with reduced packet rate has amplified negative effect on quality.
// Opus uses 20 ms packetisation (50 pps). Calculate score only if packet rate is at least half of that.
break
}
normFactor := float32(1)
if int(maxAvailableLayer) < len(cs.normFactors) {
normFactor = cs.normFactors[maxAvailableLayer]
}
cs.score = AudioTrackScore(params, normFactor)
case cs.trackInfo.Type == livekit.TrackType_VIDEO:
//
// See note below about muxed tracks quality calculation challenges.
//
// This part concerns simulcast + dynacast challeges.
// A sub-optimal solution is to measure only in windows where the max layer is stable.
// With adaptive stream, it is possible that subscription changes max layer.
// When expected layer changes from low -> high, the stats in that window
// (when the change happens) will correspond to lower layer at least partially.
// Using that to calculate against expected higher layer could result in lower score.
//
maxExpectedLayer := cs.params.GetMaxExpectedLayer()
if maxExpectedLayer == buffer.InvalidLayerSpatial || maxExpectedLayer != cs.maxExpectedLayer {
cs.maxExpectedLayer = maxExpectedLayer
if maxExpectedLayer == buffer.InvalidLayerSpatial {
// if not expecting data, reset the score to maximum
cs.score = MaxScore
}
break
}
cs.maxExpectedLayer = maxExpectedLayer
maxAvailableLayer, maxAvailableLayerStats := getMaxAvailableLayerStats(streams, maxExpectedLayer)
if maxAvailableLayerStats == nil {
// retain old score as stats will not be available when muted
break
}
params = getTrackScoreParams(cs.codecName, maxAvailableLayerStats)
// for muxed tracks, i. e. simulcast publisher muxed into a single track,
// use the current spatial layer.
// NOTE: This is still not perfect as muxing means layers could have changed
// in the analysis window. Needs a more complex design to keep track of all layer
// switches to be able to do precise calculations. As the window is small,
// using the current and maximum is a reasonable approximation.
if cs.params.GetCurrentLayerSpatial != nil {
maxAvailableLayer = cs.params.GetCurrentLayerSpatial()
if maxAvailableLayer == buffer.InvalidLayerSpatial {
// retain old score as stats will not be available if not forwarding
break
}
}
params.Width, params.Height = cs.getLayerDimensions(maxAvailableLayer)
if cs.trackInfo.Source == livekit.TrackSource_SCREEN_SHARE || params.Width == 0 || params.Height == 0 {
if cs.params.GetIsReducedQuality != nil {
_, params.IsReducedQuality = cs.params.GetIsReducedQuality()
}
cs.score = LossBasedTrackScore(params)
} else {
normFactor := float32(1)
if int(maxAvailableLayer) < len(cs.normFactors) {
normFactor = cs.normFactors[maxAvailableLayer]
}
cs.score = VideoTrackScore(params, normFactor)
if cs.params.GetIsReducedQuality != nil {
// penalty of one level per layer away from desired/expected layer
distanceToDesired, isDeficient := cs.params.GetIsReducedQuality()
if isDeficient {
cs.score -= float32(distanceToDesired)
}
cs.score = float32(clamp(float64(cs.score), float64(MinScore), float64(MaxScore)))
}
}
}
return cs.score
func (cs *ConnectionStats) GetScoreAndQuality() (float32, livekit.ConnectionQuality) {
return cs.scorer.GetMOSAndQuality()
}
func (cs *ConnectionStats) getStat() *livekit.AnalyticsStat {
func (cs *ConnectionStats) updateScore(streams map[uint32]*buffer.StreamStatsWithLayers, at time.Time) float32 {
var stat windowStat
for _, s := range streams {
if stat.startedAt.IsZero() || stat.startedAt.After(s.RTPStats.StartTime) {
stat.startedAt = s.RTPStats.StartTime
}
if stat.duration < s.RTPStats.Duration {
stat.duration = s.RTPStats.Duration
}
stat.packetsExpected += s.RTPStats.Packets + s.RTPStats.PacketsPadding
stat.packetsLost += s.RTPStats.PacketsLost
if stat.rttMax < s.RTPStats.RttMax {
stat.rttMax = s.RTPStats.RttMax
}
if stat.jitterMax < s.RTPStats.JitterMax {
stat.jitterMax = s.RTPStats.JitterMax
}
stat.bytes += s.RTPStats.Bytes - s.RTPStats.HeaderBytes // only use media payload size
}
cs.scorer.Update(&stat, at)
mos, _ := cs.scorer.GetMOSAndQuality()
return mos
}
func (cs *ConnectionStats) getStat(at time.Time) *livekit.AnalyticsStat {
if cs.params.GetDeltaStats == nil {
return nil
}
streams := cs.params.GetDeltaStats()
if len(streams) == 0 {
cs.updateScore(streams, at)
return nil
}
@@ -274,7 +130,7 @@ func (cs *ConnectionStats) getStat() *livekit.AnalyticsStat {
analyticsStreams = append(analyticsStreams, as)
}
score := cs.updateScore(streams)
score := cs.updateScore(streams, at)
return &livekit.AnalyticsStat{
Score: score,
@@ -294,11 +150,15 @@ func (cs *ConnectionStats) updateStatsWorker() {
for {
select {
case <-cs.done:
case <-cs.done.Watch():
return
case <-tk.C:
stat := cs.getStat()
if cs.done.IsClosed() {
return
}
stat := cs.getStat(time.Now())
if stat == nil {
continue
}
@@ -312,13 +172,39 @@ func (cs *ConnectionStats) updateStatsWorker() {
// -----------------------------------------------------------------------
func getCodecNameFromMime(mime string) string {
codecName := ""
codecParsed := strings.Split(strings.ToLower(mime), "/")
if len(codecParsed) > 1 {
codecName = codecParsed[1]
// how much weight to give to packet loss rate when calculating score.
// It is codec dependent.
// For audio:
// o Opus without FEC or RED suffers the most through packet loss, hence has the highest weight
// o RED with two packet redundancy can absorb two out of every three packets lost, so packet loss is not as detrimental and therefore lower weight
//
// For video:
// o No in-built codec repair available, hence same for all codecs
func getPacketLossWeight(mimeType string, isFecEnabled bool) float64 {
plw := float64(0.0)
switch {
case strings.EqualFold(mimeType, webrtc.MimeTypeOpus):
// 2.5%: fall to GOOD, 5%: fall to POOR
plw = 8.0
if isFecEnabled {
// 3.75%: fall to GOOD, 7.5%: fall to POOR
plw /= 1.5
}
case strings.EqualFold(mimeType, "audio/red"):
// 6.66%: fall to GOOD, 13.33%: fall to POOR
plw = 3.0
if isFecEnabled {
// 10%: fall to GOOD, 20%: fall to POOR
plw /= 1.5
}
case strings.HasPrefix(strings.ToLower(mimeType), "video/"):
// 2%: fall to GOOD, 4%: fall to POOR
plw = 10.0
}
return codecName
return plw
}
func toAnalyticsStream(ssrc uint32, deltaStats *buffer.RTPDeltaInfo) *livekit.AnalyticsStream {
@@ -348,35 +234,3 @@ func toAnalyticsVideoLayer(layer int32, layerStats *buffer.RTPDeltaInfo) *liveki
Frames: layerStats.Frames,
}
}
func getMaxAvailableLayerStats(streams map[uint32]*buffer.StreamStatsWithLayers, maxExpectedLayer int32) (int32, *buffer.RTPDeltaInfo) {
maxAvailableLayer := buffer.InvalidLayerSpatial
var maxAvailableLayerStats *buffer.RTPDeltaInfo
for _, stream := range streams {
for layer, layerStats := range stream.Layers {
if maxExpectedLayer == buffer.InvalidLayerSpatial || int32(layer) > maxExpectedLayer {
continue
}
if int32(layer) > maxAvailableLayer {
maxAvailableLayer = int32(layer)
maxAvailableLayerStats = layerStats
}
}
}
return maxAvailableLayer, maxAvailableLayerStats
}
func getTrackScoreParams(codec string, layerStats *buffer.RTPDeltaInfo) TrackScoreParams {
return TrackScoreParams{
Duration: layerStats.Duration,
Codec: codec,
PacketsExpected: layerStats.Packets + layerStats.PacketsPadding,
PacketsLost: layerStats.PacketsLost,
Bytes: layerStats.Bytes - layerStats.HeaderBytes, // only use media payload size
Frames: layerStats.Frames,
Jitter: layerStats.JitterMax,
Rtt: layerStats.RttMax,
}
}