DownTrack scoring when RR is not received. (#1664)

This commit is contained in:
Raja Subramanian
2023-04-28 14:50:06 +05:30
committed by GitHub
parent 3f3b02357c
commit 50ab72a5f8
4 changed files with 249 additions and 180 deletions
+114 -64
View File
@@ -66,6 +66,7 @@ type RTPDeltaInfo struct {
type Snapshot struct { type Snapshot struct {
startTime time.Time startTime time.Time
extStartSN uint32 extStartSN uint32
extStartSNOverridden uint32
packetsDuplicate uint32 packetsDuplicate uint32
bytesDuplicate uint64 bytesDuplicate uint64
headerBytesDuplicate uint64 headerBytesDuplicate uint64
@@ -294,7 +295,11 @@ func (r *RTPStats) NewSnapshotId() uint32 {
id := r.nextSnapshotId id := r.nextSnapshotId
if r.initialized { if r.initialized {
r.snapshots[id] = &Snapshot{startTime: time.Now(), extStartSN: r.extStartSN} r.snapshots[id] = &Snapshot{
startTime: time.Now(),
extStartSN: r.extStartSN,
extStartSNOverridden: r.extStartSN,
}
} }
r.nextSnapshotId++ r.nextSnapshotId++
@@ -334,7 +339,11 @@ 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{startTime: r.startTime, extStartSN: r.extStartSN} r.snapshots[i] = &Snapshot{
startTime: r.startTime,
extStartSN: r.extStartSN,
extStartSNOverridden: r.extStartSN,
}
} }
} }
@@ -526,6 +535,13 @@ func (r *RTPStats) UpdateFromReceiverReport(rr rtcp.ReceptionReport) (rtt uint32
return return
} }
func (r *RTPStats) LastReceiverReport() time.Time {
r.lock.RLock()
defer r.lock.RUnlock()
return r.lastRRTime
}
func (r *RTPStats) UpdateNack(nackCount uint32) { func (r *RTPStats) UpdateNack(nackCount uint32) {
r.lock.Lock() r.lock.Lock()
defer r.lock.Unlock() defer r.lock.Unlock()
@@ -777,7 +793,7 @@ func (r *RTPStats) GetRtcpSenderReport(ssrc uint32, srDataExt *RTCPSenderReportD
func (r *RTPStats) SnapshotRtcpReceptionReport(ssrc uint32, proxyFracLost uint8, snapshotId uint32) *rtcp.ReceptionReport { func (r *RTPStats) SnapshotRtcpReceptionReport(ssrc uint32, proxyFracLost uint8, snapshotId uint32) *rtcp.ReceptionReport {
r.lock.Lock() r.lock.Lock()
then, now := r.getAndResetSnapshot(snapshotId) then, now := r.getAndResetSnapshot(snapshotId, false)
r.lock.Unlock() r.lock.Unlock()
if now == nil || then == nil { if now == nil || then == nil {
@@ -799,17 +815,8 @@ func (r *RTPStats) SnapshotRtcpReceptionReport(ssrc uint32, proxyFracLost uint8,
return nil return nil
} }
packetsLost := uint32(0) intervalStats := r.getIntervalStats(uint16(then.extStartSN), uint16(now.extStartSN))
if r.params.IsReceiverReportDriven { packetsLost := intervalStats.packetsLost
// receiver report driven should not be set for streams that need to generate reception report, but including code here for consistency
packetsLost = now.packetsLostOverridden - then.packetsLostOverridden
if int32(packetsLost) < 0 {
packetsLost = 0
}
} else {
intervalStats := r.getIntervalStats(uint16(then.extStartSN), uint16(now.extStartSN))
packetsLost = intervalStats.packetsLost
}
lossRate := float32(packetsLost) / float32(packetsExpected) lossRate := float32(packetsLost) / float32(packetsExpected)
fracLost := uint8(lossRate * 256.0) fracLost := uint8(lossRate * 256.0)
if proxyFracLost > fracLost { if proxyFracLost > fracLost {
@@ -823,12 +830,6 @@ func (r *RTPStats) SnapshotRtcpReceptionReport(ssrc uint32, proxyFracLost uint8,
dlsr |= (delayMS % 1e3) * 65536 / 1000 dlsr |= (delayMS % 1e3) * 65536 / 1000
} }
jitter := r.jitter
if r.params.IsReceiverReportDriven {
// receiver report driven should not be set for streams that need to generate reception report, but including code here for consistency
jitter = r.jitterOverridden
}
lastSR := uint32(0) lastSR := uint32(0)
if r.srDataExt != nil { if r.srDataExt != nil {
lastSR = uint32(r.srDataExt.SenderReportData.NTPTimestamp >> 16) lastSR = uint32(r.srDataExt.SenderReportData.NTPTimestamp >> 16)
@@ -838,7 +839,7 @@ func (r *RTPStats) SnapshotRtcpReceptionReport(ssrc uint32, proxyFracLost uint8,
FractionLost: fracLost, FractionLost: fracLost,
TotalLost: r.packetsLost, TotalLost: r.packetsLost,
LastSequenceNumber: now.extStartSN, LastSequenceNumber: now.extStartSN,
Jitter: uint32(jitter), Jitter: uint32(r.jitter),
LastSenderReport: lastSR, LastSenderReport: lastSR,
Delay: dlsr, Delay: dlsr,
} }
@@ -846,7 +847,7 @@ func (r *RTPStats) SnapshotRtcpReceptionReport(ssrc uint32, proxyFracLost uint8,
func (r *RTPStats) DeltaInfo(snapshotId uint32) *RTPDeltaInfo { func (r *RTPStats) DeltaInfo(snapshotId uint32) *RTPDeltaInfo {
r.lock.Lock() r.lock.Lock()
then, now := r.getAndResetSnapshot(snapshotId) then, now := r.getAndResetSnapshot(snapshotId, false)
r.lock.Unlock() r.lock.Unlock()
if now == nil || then == nil { if now == nil || then == nil {
@@ -868,53 +869,93 @@ func (r *RTPStats) DeltaInfo(snapshotId uint32) *RTPDeltaInfo {
return nil return nil
} }
if packetsExpected == 0 { if packetsExpected == 0 {
if r.params.IsReceiverReportDriven {
// not received RTCP RR (OR) publisher is not producing any data
return nil
}
return &RTPDeltaInfo{ return &RTPDeltaInfo{
StartTime: startTime, StartTime: startTime,
Duration: endTime.Sub(startTime), Duration: endTime.Sub(startTime),
} }
} }
packetsLost := uint32(0)
packetsMissing := uint32(0)
intervalStats := r.getIntervalStats(uint16(then.extStartSN), uint16(now.extStartSN)) intervalStats := r.getIntervalStats(uint16(then.extStartSN), uint16(now.extStartSN))
if r.params.IsReceiverReportDriven { return &RTPDeltaInfo{
packetsMissing = intervalStats.packetsLost StartTime: startTime,
Duration: endTime.Sub(startTime),
Packets: packetsExpected - intervalStats.packetsPadding,
Bytes: intervalStats.bytes,
HeaderBytes: intervalStats.headerBytes,
PacketsDuplicate: now.packetsDuplicate - then.packetsDuplicate,
BytesDuplicate: now.bytesDuplicate - then.bytesDuplicate,
HeaderBytesDuplicate: now.headerBytesDuplicate - then.headerBytesDuplicate,
PacketsPadding: intervalStats.packetsPadding,
BytesPadding: intervalStats.bytesPadding,
HeaderBytesPadding: intervalStats.headerBytesPadding,
PacketsLost: intervalStats.packetsLost,
Frames: intervalStats.frames,
RttMax: then.maxRtt,
JitterMax: then.maxJitter / float64(r.params.ClockRate) * 1e6,
Nacks: now.nacks - then.nacks,
Plis: now.plis - then.plis,
Firs: now.firs - then.firs,
}
}
packetsLost = now.packetsLostOverridden - then.packetsLostOverridden func (r *RTPStats) DeltaInfoOverridden(snapshotId uint32) *RTPDeltaInfo {
if int32(packetsLost) < 0 { if !r.params.IsReceiverReportDriven {
packetsLost = 0 return nil
}
if packetsLost > packetsExpected {
r.logger.Warnw(
"unexpected number of packets lost",
fmt.Errorf(
"start: %d, end: %d, expected: %d, lost: report: %d, interval: %d",
then.extStartSN,
now.extStartSN,
packetsExpected,
now.packetsLostOverridden-then.packetsLostOverridden,
intervalStats.packetsLost,
),
)
packetsLost = packetsExpected
}
} else {
packetsLost = intervalStats.packetsLost
} }
maxJitter := then.maxJitter r.lock.Lock()
if r.params.IsReceiverReportDriven { then, now := r.getAndResetSnapshot(snapshotId, true)
// discount jitter from publisher side + internal processing r.lock.Unlock()
maxJitter = then.maxJitterOverridden - maxJitter
if maxJitter < 0.0 { if now == nil || then == nil {
maxJitter = 0.0 return nil
} }
r.lock.RLock()
defer r.lock.RUnlock()
startTime := then.startTime
endTime := now.startTime
packetsExpected := now.extStartSNOverridden - then.extStartSNOverridden
if packetsExpected > NumSequenceNumbers {
r.logger.Warnw(
"too many packets expected in delta",
fmt.Errorf("start: %d, end: %d, expected: %d", then.extStartSNOverridden, now.extStartSNOverridden, packetsExpected),
)
return nil
}
if packetsExpected == 0 {
// not received RTCP RR (OR) publisher is not producing any data
return nil
}
intervalStats := r.getIntervalStats(uint16(then.extStartSNOverridden), uint16(now.extStartSNOverridden))
packetsMissing := intervalStats.packetsLost
packetsLost := now.packetsLostOverridden - then.packetsLostOverridden
if int32(packetsLost) < 0 {
packetsLost = 0
}
if packetsLost > packetsExpected {
r.logger.Warnw(
"unexpected number of packets lost",
fmt.Errorf(
"start: %d, end: %d, expected: %d, lost: report: %d, interval: %d",
then.extStartSNOverridden,
now.extStartSNOverridden,
packetsExpected,
now.packetsLostOverridden-then.packetsLostOverridden,
intervalStats.packetsLost,
),
)
packetsLost = packetsExpected
}
// discount jitter from publisher side + internal processing
maxJitter := then.maxJitterOverridden - then.maxJitter
if maxJitter < 0.0 {
maxJitter = 0.0
} }
maxJitterTime := maxJitter / float64(r.params.ClockRate) * 1e6 maxJitterTime := maxJitter / float64(r.params.ClockRate) * 1e6
@@ -1288,7 +1329,7 @@ func (r *RTPStats) updateGapHistogram(gap int) {
} }
} }
func (r *RTPStats) getAndResetSnapshot(snapshotId uint32) (*Snapshot, *Snapshot) { func (r *RTPStats) getAndResetSnapshot(snapshotId uint32, override bool) (*Snapshot, *Snapshot) {
if !r.initialized || (r.params.IsReceiverReportDriven && r.lastRRTime.IsZero()) { if !r.initialized || (r.params.IsReceiverReportDriven && r.lastRRTime.IsZero()) {
return nil, nil return nil, nil
} }
@@ -1296,16 +1337,25 @@ 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, startTime: r.startTime,
extStartSN: r.extStartSN, extStartSN: r.extStartSN,
extStartSNOverridden: r.extStartSN,
} }
r.snapshots[snapshotId] = then r.snapshots[snapshotId] = then
} }
var startTime time.Time
if override && r.params.IsReceiverReportDriven {
startTime = r.lastRRTime
} else {
startTime = time.Now()
}
// snapshot now // snapshot now
r.snapshots[snapshotId] = &Snapshot{ r.snapshots[snapshotId] = &Snapshot{
startTime: time.Now(), startTime: startTime,
extStartSN: r.getExtHighestSNAdjusted() + 1, extStartSN: r.getExtHighestSN() + 1,
extStartSNOverridden: r.getExtHighestSNAdjusted() + 1,
packetsDuplicate: r.packetsDuplicate, packetsDuplicate: r.packetsDuplicate,
bytesDuplicate: r.bytesDuplicate, bytesDuplicate: r.bytesDuplicate,
headerBytesDuplicate: r.headerBytesDuplicate, headerBytesDuplicate: r.headerBytesDuplicate,
+90 -85
View File
@@ -18,17 +18,19 @@ const (
UpdateInterval = 5 * time.Second UpdateInterval = 5 * time.Second
processThreshold = 0.95 processThreshold = 0.95
noStatsTooLongMultiplier = 2 noStatsTooLongMultiplier = 2
noReceiverReportTooLongThreshold = 10 * time.Second noReceiverReportTooLongThreshold = 30 * time.Second
) )
type ConnectionStatsParams struct { type ConnectionStatsParams struct {
UpdateInterval time.Duration UpdateInterval time.Duration
MimeType string MimeType string
IsFECEnabled bool IsFECEnabled bool
IsDependentRTT bool IsDependentRTT bool
IsDependentJitter bool IsDependentJitter bool
GetDeltaStats func() map[uint32]*buffer.StreamStatsWithLayers GetDeltaStats func() map[uint32]*buffer.StreamStatsWithLayers
Logger logger.Logger GetDeltaStatsOverridden func() map[uint32]*buffer.StreamStatsWithLayers
GetLastReceiverReportTime func() time.Time
Logger logger.Logger
} }
type ConnectionStats struct { type ConnectionStats struct {
@@ -39,10 +41,8 @@ type ConnectionStats struct {
onStatsUpdate func(cs *ConnectionStats, stat *livekit.AnalyticsStat) onStatsUpdate func(cs *ConnectionStats, stat *livekit.AnalyticsStat)
lock sync.RWMutex lock sync.RWMutex
lastStatsAt time.Time streamingStartedAt time.Time
statsInProcess bool
lastReceiverReportAt time.Time
scorer *qualityScorer scorer *qualityScorer
@@ -69,8 +69,6 @@ func (cs *ConnectionStats) Start(trackInfo *livekit.TrackInfo, at time.Time) {
cs.isVideo.Store(trackInfo.Type == livekit.TrackType_VIDEO) cs.isVideo.Store(trackInfo.Type == livekit.TrackType_VIDEO)
cs.updateLastStatsAt(time.Now()) // force an initial wait
cs.scorer.Start(at) cs.scorer.Start(at)
go cs.updateStatsWorker() go cs.updateStatsWorker()
@@ -104,21 +102,7 @@ func (cs *ConnectionStats) GetScoreAndQuality() (float32, livekit.ConnectionQual
return cs.scorer.GetMOSAndQuality() return cs.scorer.GetMOSAndQuality()
} }
func (cs *ConnectionStats) ReceiverReportReceived(at time.Time) { func (cs *ConnectionStats) updateScoreWithAggregate(agg *buffer.RTPDeltaInfo, at time.Time) float32 {
cs.lock.Lock()
cs.lastReceiverReportAt = time.Now()
cs.lock.Unlock()
cs.getStat(at)
}
func (cs *ConnectionStats) updateScore(streams map[uint32]*buffer.StreamStatsWithLayers, at time.Time) float32 {
deltaInfoList := make([]*buffer.RTPDeltaInfo, 0, len(streams))
for _, s := range streams {
deltaInfoList = append(deltaInfoList, s.RTPStats)
}
agg := buffer.AggregateRTPDeltaInfo(deltaInfoList)
var stat windowStat var stat windowStat
if agg != nil { if agg != nil {
stat.startedAt = agg.StartTime stat.startedAt = agg.StartTime
@@ -136,58 +120,86 @@ func (cs *ConnectionStats) updateScore(streams map[uint32]*buffer.StreamStatsWit
return mos return mos
} }
func (cs *ConnectionStats) maybeMarkInProcess() bool { func (cs *ConnectionStats) updateScoreFromReceiverReport(at time.Time) float32 {
cs.lock.Lock() if cs.params.GetDeltaStatsOverridden == nil || cs.params.GetLastReceiverReportTime == nil {
defer cs.lock.Unlock() return MinMOS
if cs.statsInProcess {
// already running
return false
} }
interval := cs.params.UpdateInterval
if interval == 0 {
interval = UpdateInterval
}
if cs.isStarted.Load() && time.Since(cs.lastStatsAt) > time.Duration(processThreshold*float64(interval)) {
cs.statsInProcess = true
return true
}
return false
}
func (cs *ConnectionStats) updateLastStatsAt(at time.Time) {
cs.lock.Lock()
defer cs.lock.Unlock()
cs.lastStatsAt = at
}
func (cs *ConnectionStats) isTooLongSinceLastStats() bool {
cs.lock.RLock() cs.lock.RLock()
defer cs.lock.RUnlock() streamingStartedAt := cs.streamingStartedAt
cs.lock.RUnlock()
interval := cs.params.UpdateInterval if streamingStartedAt.IsZero() {
if interval == 0 { // not streaming, just return current score
interval = UpdateInterval mos, _ := cs.scorer.GetMOSAndQuality()
return mos
} }
return !cs.lastStatsAt.IsZero() && time.Since(cs.lastStatsAt) > interval*noStatsTooLongMultiplier
streams := cs.params.GetDeltaStatsOverridden()
if len(streams) == 0 {
// check for receiver report not received for a while
marker := cs.params.GetLastReceiverReportTime()
if marker.IsZero() || streamingStartedAt.After(marker) {
marker = streamingStartedAt
}
if time.Since(marker) > noReceiverReportTooLongThreshold {
// have not received receiver report for a long time when streaming, run with nil stat
return cs.updateScoreWithAggregate(nil, at)
}
// wait for receiver report, return current score
mos, _ := cs.scorer.GetMOSAndQuality()
return mos
}
// delta stat duration could be large due to not receiving receiver report for a long time (for example, due to mute),
// adjust to streaming start if necessary
agg := toAggregateDeltaInfo(streams)
if streamingStartedAt.After(cs.params.GetLastReceiverReportTime()) {
// last receiver report was before streaming started, wait for next one
mos, _ := cs.scorer.GetMOSAndQuality()
return mos
}
if streamingStartedAt.After(agg.StartTime) {
agg.Duration = agg.StartTime.Add(agg.Duration).Sub(streamingStartedAt)
agg.StartTime = streamingStartedAt
}
return cs.updateScoreWithAggregate(agg, at)
} }
func (cs *ConnectionStats) isTooLongSinceLastReceiverReport() bool { func (cs *ConnectionStats) updateScore(streams map[uint32]*buffer.StreamStatsWithLayers, at time.Time) float32 {
cs.lock.RLock() deltaInfoList := make([]*buffer.RTPDeltaInfo, 0, len(streams))
defer cs.lock.RUnlock() for _, s := range streams {
deltaInfoList = append(deltaInfoList, s.RTPStats)
}
agg := buffer.AggregateRTPDeltaInfo(deltaInfoList)
if agg != nil && agg.Packets > 0 {
// not very accurate as streaming could have started part way in the window, but don't need accurate time
cs.maybeSetStreamingStart(agg.StartTime)
} else {
cs.clearStreamingStart()
}
return !cs.lastReceiverReportAt.IsZero() && time.Since(cs.lastReceiverReportAt) > noReceiverReportTooLongThreshold if cs.params.GetDeltaStatsOverridden != nil {
// receiver report based quality scoring, use stats from receiver report for scoring
return cs.updateScoreFromReceiverReport(at)
}
return cs.updateScoreWithAggregate(agg, at)
} }
func (cs *ConnectionStats) clearInProcess() { func (cs *ConnectionStats) maybeSetStreamingStart(at time.Time) {
cs.lock.Lock() cs.lock.Lock()
defer cs.lock.Unlock() if cs.streamingStartedAt.IsZero() {
cs.streamingStartedAt = at
}
cs.lock.Unlock()
}
cs.statsInProcess = false func (cs *ConnectionStats) clearStreamingStart() {
cs.lock.Lock()
cs.streamingStartedAt = time.Time{}
cs.lock.Unlock()
} }
func (cs *ConnectionStats) getStat(at time.Time) { func (cs *ConnectionStats) getStat(at time.Time) {
@@ -195,24 +207,11 @@ func (cs *ConnectionStats) getStat(at time.Time) {
return return
} }
if !cs.maybeMarkInProcess() {
// not yet time to process
return
}
streams := cs.params.GetDeltaStats() streams := cs.params.GetDeltaStats()
if len(streams) == 0 { if len(streams) == 0 {
if cs.isTooLongSinceLastStats() && cs.isTooLongSinceLastReceiverReport() {
cs.updateLastStatsAt(at)
cs.updateScore(streams, at)
}
cs.clearInProcess()
return return
} }
// stats available, update last stats time
cs.updateLastStatsAt(at)
score := cs.updateScore(streams, at) score := cs.updateScore(streams, at)
if cs.onStatsUpdate != nil { if cs.onStatsUpdate != nil {
@@ -240,8 +239,6 @@ func (cs *ConnectionStats) getStat(at time.Time) {
Mime: cs.params.MimeType, Mime: cs.params.MimeType,
}) })
} }
cs.clearInProcess()
} }
func (cs *ConnectionStats) updateStatsWorker() { func (cs *ConnectionStats) updateStatsWorker() {
@@ -308,6 +305,14 @@ func getPacketLossWeight(mimeType string, isFecEnabled bool) float64 {
return plw return plw
} }
func toAggregateDeltaInfo(streams map[uint32]*buffer.StreamStatsWithLayers) *buffer.RTPDeltaInfo {
deltaInfoList := make([]*buffer.RTPDeltaInfo, 0, len(streams))
for _, s := range streams {
deltaInfoList = append(deltaInfoList, s.RTPStats)
}
return buffer.AggregateRTPDeltaInfo(deltaInfoList)
}
func toAnalyticsStream(ssrc uint32, deltaStats *buffer.RTPDeltaInfo) *livekit.AnalyticsStream { func toAnalyticsStream(ssrc uint32, deltaStats *buffer.RTPDeltaInfo) *livekit.AnalyticsStream {
return &livekit.AnalyticsStream{ return &livekit.AnalyticsStream{
Ssrc: ssrc, Ssrc: ssrc,
+2
View File
@@ -12,6 +12,7 @@ import (
const ( const (
MaxMOS = float32(4.5) MaxMOS = float32(4.5)
MinMOS = float32(1.0)
maxScore = float64(100.0) maxScore = float64(100.0)
poorScore = float64(30.0) poorScore = float64(30.0)
@@ -362,6 +363,7 @@ func (q *qualityScorer) getPacketLossWeight(stat *windowStat) float64 {
pps := float64(stat.packetsExpected) / stat.duration.Seconds() pps := float64(stat.packetsExpected) / stat.duration.Seconds()
if pps > q.maxPPS { if pps > q.maxPPS {
q.maxPPS = pps q.maxPPS = pps
q.params.Logger.Debugw("updating maxPPS", "expected", stat.packetsExpected, "duration", stat.duration.Seconds(), "pps", pps)
} }
if q.maxPPS == 0 { if q.maxPPS == 0 {
+43 -31
View File
@@ -107,9 +107,10 @@ var (
// ------------------------------------------------------------------- // -------------------------------------------------------------------
type DownTrackState struct { type DownTrackState struct {
RTPStats *buffer.RTPStats RTPStats *buffer.RTPStats
DeltaStatsSnapshotId uint32 DeltaStatsSnapshotId uint32
ForwarderState ForwarderState DeltaStatsOverriddenSnapshotId uint32
ForwarderState ForwarderState
} }
func (d DownTrackState) String() string { func (d DownTrackState) String() string {
@@ -216,8 +217,9 @@ type DownTrack struct {
blankFramesGeneration atomic.Uint32 blankFramesGeneration atomic.Uint32
connectionStats *connectionquality.ConnectionStats connectionStats *connectionquality.ConnectionStats
deltaStatsSnapshotId uint32 deltaStatsSnapshotId uint32
deltaStatsOverriddenSnapshotId uint32
// for throttling error logs // for throttling error logs
writeIOErrors atomic.Uint32 writeIOErrors atomic.Uint32
@@ -281,25 +283,28 @@ func NewDownTrack(
} }
}) })
d.connectionStats = connectionquality.NewConnectionStats(connectionquality.ConnectionStatsParams{
MimeType: codecs[0].MimeType, // LK-TODO have to notify on codec change
IsFECEnabled: strings.EqualFold(codecs[0].MimeType, webrtc.MimeTypeOpus) && strings.Contains(strings.ToLower(codecs[0].SDPFmtpLine), "fec"),
IsDependentJitter: true,
GetDeltaStats: d.getDeltaStats,
Logger: d.logger.WithValues("direction", "down"),
})
d.connectionStats.OnStatsUpdate(func(_cs *connectionquality.ConnectionStats, stat *livekit.AnalyticsStat) {
if d.onStatsUpdate != nil {
d.onStatsUpdate(d, stat)
}
})
d.rtpStats = buffer.NewRTPStats(buffer.RTPStatsParams{ d.rtpStats = buffer.NewRTPStats(buffer.RTPStatsParams{
ClockRate: d.codec.ClockRate, ClockRate: d.codec.ClockRate,
IsReceiverReportDriven: true, IsReceiverReportDriven: true,
Logger: d.logger, Logger: d.logger,
}) })
d.deltaStatsSnapshotId = d.rtpStats.NewSnapshotId() d.deltaStatsSnapshotId = d.rtpStats.NewSnapshotId()
d.deltaStatsOverriddenSnapshotId = d.rtpStats.NewSnapshotId()
d.connectionStats = connectionquality.NewConnectionStats(connectionquality.ConnectionStatsParams{
MimeType: codecs[0].MimeType, // LK-TODO have to notify on codec change
IsFECEnabled: strings.EqualFold(codecs[0].MimeType, webrtc.MimeTypeOpus) && strings.Contains(strings.ToLower(codecs[0].SDPFmtpLine), "fec"),
IsDependentJitter: true,
GetDeltaStats: d.getDeltaStats,
GetDeltaStatsOverridden: d.getDeltaStatsOverridden,
GetLastReceiverReportTime: func() time.Time { return d.rtpStats.LastReceiverReport() },
Logger: d.logger.WithValues("direction", "down"),
})
d.connectionStats.OnStatsUpdate(func(_cs *connectionquality.ConnectionStats, stat *livekit.AnalyticsStat) {
if d.onStatsUpdate != nil {
d.onStatsUpdate(d, stat)
}
})
return d, nil return d, nil
} }
@@ -913,16 +918,19 @@ func (d *DownTrack) MaxLayer() buffer.VideoLayer {
} }
func (d *DownTrack) GetState() DownTrackState { func (d *DownTrack) GetState() DownTrackState {
return DownTrackState{ dts := DownTrackState{
RTPStats: d.rtpStats, RTPStats: d.rtpStats,
DeltaStatsSnapshotId: d.deltaStatsSnapshotId, DeltaStatsSnapshotId: d.deltaStatsSnapshotId,
ForwarderState: d.forwarder.GetState(), DeltaStatsOverriddenSnapshotId: d.deltaStatsOverriddenSnapshotId,
ForwarderState: d.forwarder.GetState(),
} }
return dts
} }
func (d *DownTrack) SeedState(state DownTrackState) { func (d *DownTrack) SeedState(state DownTrackState) {
d.rtpStats.Seed(state.RTPStats) d.rtpStats.Seed(state.RTPStats)
d.deltaStatsSnapshotId = state.DeltaStatsSnapshotId d.deltaStatsSnapshotId = state.DeltaStatsSnapshotId
d.deltaStatsOverriddenSnapshotId = state.DeltaStatsOverriddenSnapshotId
d.forwarder.SeedState(state.ForwarderState) d.forwarder.SeedState(state.ForwarderState)
} }
@@ -1341,8 +1349,6 @@ func (d *DownTrack) handleRTCP(bytes []byte) {
l(d, rr) l(d, rr)
} }
d.listenerLock.RUnlock() d.listenerLock.RUnlock()
d.connectionStats.ReceiverReportReceived(time.Now())
} }
case *rtcp.TransportLayerNack: case *rtcp.TransportLayerNack:
@@ -1626,24 +1632,30 @@ func (d *DownTrack) GetTrackStats() *livekit.RTPStats {
return d.rtpStats.ToProto() return d.rtpStats.ToProto()
} }
func (d *DownTrack) getDeltaStats() map[uint32]*buffer.StreamStatsWithLayers { func (d *DownTrack) deltaStats(ds *buffer.RTPDeltaInfo) map[uint32]*buffer.StreamStatsWithLayers {
streamStats := make(map[uint32]*buffer.StreamStatsWithLayers, 1) if ds == nil {
deltaStats := d.rtpStats.DeltaInfo(d.deltaStatsSnapshotId)
if deltaStats == nil {
return nil return nil
} }
streamStats := make(map[uint32]*buffer.StreamStatsWithLayers, 1)
streamStats[d.ssrc] = &buffer.StreamStatsWithLayers{ streamStats[d.ssrc] = &buffer.StreamStatsWithLayers{
RTPStats: deltaStats, RTPStats: ds,
Layers: map[int32]*buffer.RTPDeltaInfo{ Layers: map[int32]*buffer.RTPDeltaInfo{
0: deltaStats, 0: ds,
}, },
} }
return streamStats return streamStats
} }
func (d *DownTrack) getDeltaStats() map[uint32]*buffer.StreamStatsWithLayers {
return d.deltaStats(d.rtpStats.DeltaInfo(d.deltaStatsSnapshotId))
}
func (d *DownTrack) getDeltaStatsOverridden() map[uint32]*buffer.StreamStatsWithLayers {
return d.deltaStats(d.rtpStats.DeltaInfoOverridden(d.deltaStatsOverriddenSnapshotId))
}
func (d *DownTrack) GetNackStats() (totalPackets uint32, totalRepeatedNACKs uint32) { func (d *DownTrack) GetNackStats() (totalPackets uint32, totalRepeatedNACKs uint32) {
totalPackets = d.rtpStats.GetTotalPacketsPrimary() totalPackets = d.rtpStats.GetTotalPacketsPrimary()
totalRepeatedNACKs = d.totalRepeatedNACKs.Load() totalRepeatedNACKs = d.totalRepeatedNACKs.Load()