* WIP commit

* WIP commit

* WIP commit

* WIP commit

* WIP commit

* WIP commit

* Clean up

* Clean up

* Store RTT in stats

* spelling mistake

* Make tests compile

* Fix test compilation error

* fix tests

* clone

* latest protocol
This commit is contained in:
Raja Subramanian
2022-02-08 12:53:14 +05:30
committed by GitHub
parent a6eb4290d3
commit 36289bbca7
23 changed files with 913 additions and 639 deletions
+109 -83
View File
@@ -3,6 +3,7 @@ package buffer
import (
"encoding/binary"
"io"
"math/rand"
"strings"
"sync"
"sync/atomic"
@@ -36,7 +37,7 @@ type ExtPacket struct {
// Buffer contains all packets
type Buffer struct {
sync.Mutex
sync.RWMutex
bucket *Bucket
nacker *NackQueue
videoPool *sync.Pool
@@ -63,21 +64,20 @@ type Buffer struct {
latestTSForAudioLevelInitialized bool
latestTSForAudioLevel uint32
lastPacketRead int
bitrate atomic.Value
bitrateHelper [4]int64
lastSRNTPTime uint64
lastSRRTPTime uint32
lastSRRecv int64 // Represents wall clock of the most recent sender report arrival
cycle uint16
lastRtcpPacketTime int64 // Time the last RTCP packet was received.
lastRtcpSrTime int64 // Time the last RTCP SR was received. Required for DLSR computation.
lastTransit uint32
lastPacketRead int
bitrate atomic.Value
bitrateHelper [4]int64
lastSRNTPTime uint64
lastSRRTPTime uint32
lastSRRecv int64 // Represents wall clock of the most recent sender report arrival
lastTransit uint32
stats Stats
started bool
stats StreamStats
rrSnapshot *receiverReportSnapshot
highestSN uint16
cycle uint16
lastFractionLostToReport uint8 // Last fraction lost from subscribers, should report to publisher; Audio only
@@ -91,17 +91,10 @@ type Buffer struct {
logger logger.Logger
}
type Stats struct {
PacketCount uint32 // Number of packets received from this source.
TotalBytes uint64
Jitter float64 // An estimate of the statistical variance of the RTP data packet inter-arrival time.
}
type receiverReportSnapshot struct {
extSeqNum uint32
packetsReceived uint32
packetsLost uint32
lastLossRate float32
extHighestSeqNum uint32
packetsLost uint32
lastLossRate float32
}
// BufferOptions provides configuration options for the buffer
@@ -164,7 +157,7 @@ func (b *Buffer) Bind(params webrtc.RTPParameters, codec webrtc.RTPCodecCapabili
case webrtc.TypeRTCPFBNACK:
b.logger.Debugw("Setting feedback", "type", webrtc.TypeRTCPFBNACK)
b.nacker = NewNACKQueue()
b.nacker.SetRTT(70) // LK-TODO: sane default till we get better data
b.nacker.SetRTT(70) // default till it is updated
b.nack = true
}
}
@@ -271,6 +264,29 @@ func (b *Buffer) OnClose(fn func()) {
b.onClose = fn
}
func (b *Buffer) SendPLI() {
b.Lock()
b.stats.TotalPLIs++
b.Unlock()
pli := []rtcp.Packet{
&rtcp.PictureLossIndication{SenderSSRC: rand.Uint32(), MediaSSRC: b.mediaSSRC},
}
b.feedbackCB(pli)
}
func (b *Buffer) SetRTT(rtt uint32) {
b.Lock()
defer b.Unlock()
b.stats.RTT = rtt
if b.nacker != nil {
b.nacker.SetRTT(rtt)
}
}
func (b *Buffer) calc(pkt []byte, arrivalTime int64) {
isRTX := false
@@ -328,41 +344,58 @@ func (b *Buffer) calc(pkt []byte, arrivalTime int64) {
func (b *Buffer) updateStreamState(p *rtp.Packet, pktSize int, arrivalTime int64, isRTX bool) {
sn := p.SequenceNumber
if b.stats.PacketCount == 0 {
b.highestSN = sn - 1
if !b.started {
b.started = true
b.highestSN = sn
b.lastReport = arrivalTime
b.rrSnapshot = &receiverReportSnapshot{
extSeqNum: uint32(sn) - 1,
packetsReceived: 0,
packetsLost: 0,
lastLossRate: 0.0,
}
}
diff := sn - b.highestSN
if diff > (1 << 15) {
// out-of-order, remove it from nack queue
if b.nacker != nil {
b.nacker.Remove(sn)
extHighestSeqNum: uint32(sn) - 1,
packetsLost: 0,
lastLossRate: 0.0,
}
} else {
if b.nacker != nil && diff > 1 {
for lost := b.highestSN + 1; lost != sn; lost++ {
b.nacker.Push(lost)
diff := sn - b.highestSN
if diff > (1 << 15) {
if !isRTX && b.stats.TotalPacketsLost != 0 {
b.stats.TotalPacketsLost--
}
}
if sn < b.highestSN && b.stats.PacketCount > 0 {
b.cycle++
}
// out-of-order, remove it from nack queue
if b.nacker != nil {
b.nacker.Remove(sn)
}
} else {
b.stats.TotalPacketsLost += (uint32(diff) - 1)
if b.nacker != nil && diff > 1 {
for lost := b.highestSN + 1; lost != sn; lost++ {
b.nacker.Push(lost)
}
}
b.highestSN = sn
if sn < b.highestSN {
b.cycle++
}
b.highestSN = sn
}
}
b.stats.PacketCount++
b.stats.TotalBytes += uint64(pktSize)
switch {
case isRTX:
b.stats.TotalRetransmitPackets++
b.stats.TotalRetransmitBytes += uint64(pktSize)
case len(p.Payload) == 0:
b.stats.TotalPaddingPackets++
b.stats.TotalPaddingBytes += uint64(pktSize)
default:
b.stats.TotalPrimaryPackets++
b.stats.TotalPrimaryBytes += uint64(pktSize)
if p.Marker {
b.stats.TotalFrames++
}
}
if !isRTX {
// jitter
@@ -445,8 +478,9 @@ func (b *Buffer) doNACKs() {
return
}
if r := b.buildNACKPacket(); r != nil {
b.feedbackCB(r)
if r, numSeqNumsNacked := b.buildNACKPacket(); r != nil {
go b.feedbackCB(r)
b.stats.TotalNACKs += uint32(numSeqNumsNacked)
}
}
@@ -476,11 +510,11 @@ func (b *Buffer) doReports(arrivalTime int64) {
b.bitrate.Store(bitrates)
// RTCP reports
b.feedbackCB(b.getRTCP())
go b.feedbackCB(b.getRTCP())
}
func (b *Buffer) buildNACKPacket() []rtcp.Packet {
if nacks := b.nacker.Pairs(); len(nacks) > 0 {
func (b *Buffer) buildNACKPacket() ([]rtcp.Packet, int) {
if nacks, numSeqNumsNacked := b.nacker.Pairs(); len(nacks) > 0 {
var pkts []rtcp.Packet
if len(nacks) > 0 {
pkts = []rtcp.Packet{&rtcp.TransportLayerNack{
@@ -489,9 +523,9 @@ func (b *Buffer) buildNACKPacket() []rtcp.Packet {
}}
}
return pkts
return pkts, numSeqNumsNacked
}
return nil
return nil, 0
}
func (b *Buffer) buildREMBPacket() *rtcp.ReceiverEstimatedMaximumBitrate {
@@ -514,7 +548,6 @@ func (b *Buffer) buildREMBPacket() *rtcp.ReceiverEstimatedMaximumBitrate {
if br < 100000 {
br = 100000
}
b.stats.TotalBytes = 0
return &rtcp.ReceiverEstimatedMaximumBitrate{
Bitrate: float32(br),
@@ -527,14 +560,13 @@ func (b *Buffer) buildReceptionReport() *rtcp.ReceptionReport {
return nil
}
extMaxSeq := (uint32(b.cycle) << 16) | uint32(b.highestSN)
expectedInInterval := extMaxSeq - b.rrSnapshot.extSeqNum
extHighestSeqNum := (uint32(b.cycle) << 16) | uint32(b.highestSN)
expectedInInterval := extHighestSeqNum - b.rrSnapshot.extHighestSeqNum
if expectedInInterval == 0 {
return nil
}
receivedInInterval := b.stats.PacketCount - b.rrSnapshot.packetsReceived
lostInInterval := expectedInInterval - receivedInInterval
lostInInterval := b.stats.TotalPacketsLost - b.rrSnapshot.packetsLost
if int32(lostInInterval) < 0 {
// could happen if retransmitted packets arrive and make received greater than expected
lostInInterval = 0
@@ -547,8 +579,6 @@ func (b *Buffer) buildReceptionReport() *rtcp.ReceptionReport {
fracLost = b.lastFractionLostToReport
}
totalLost := b.rrSnapshot.packetsLost + lostInInterval
var dlsr uint32
if b.lastSRRecv != 0 {
delayMS := uint32((time.Now().UnixNano() - b.lastSRRecv) / 1e6)
@@ -557,17 +587,16 @@ func (b *Buffer) buildReceptionReport() *rtcp.ReceptionReport {
}
b.rrSnapshot = &receiverReportSnapshot{
extSeqNum: extMaxSeq,
packetsReceived: b.stats.PacketCount,
packetsLost: totalLost,
lastLossRate: lossRate,
extHighestSeqNum: extHighestSeqNum,
packetsLost: b.stats.TotalPacketsLost,
lastLossRate: lossRate,
}
return &rtcp.ReceptionReport{
SSRC: b.mediaSSRC,
FractionLost: fracLost,
TotalLost: totalLost,
LastSequenceNumber: extMaxSeq,
TotalLost: b.stats.TotalPacketsLost,
LastSequenceNumber: extHighestSeqNum,
Jitter: uint32(b.stats.Jitter),
LastSenderReport: uint32(b.lastSRNTPTime >> 16),
Delay: dlsr,
@@ -677,22 +706,19 @@ func (b *Buffer) GetSenderReportData() (rtpTime uint32, ntpTime uint64, lastRece
return rtpTime, ntpTime, lastReceivedTimeInNanosSinceEpoch
}
// GetStats returns the raw statistics about a particular buffer state
func (b *Buffer) GetStats() (stats Stats) {
b.Lock()
stats = b.stats
b.Unlock()
return
}
func (b *Buffer) GetStats() *StreamStatsWithLayers {
b.RLock()
defer b.RUnlock()
// Used only in tests
func (b *Buffer) SetStatsTestOnly(stats Stats) {
b.Lock()
b.stats = stats
b.Unlock()
}
layers := make(map[int]LayerStats)
layers[0] = LayerStats{
TotalPackets: b.stats.TotalPrimaryPackets + b.stats.TotalRetransmitPackets + b.stats.TotalPaddingPackets,
TotalBytes: b.stats.TotalPrimaryBytes + b.stats.TotalRetransmitBytes + b.stats.TotalPaddingBytes,
TotalFrames: b.stats.TotalFrames,
}
// IsLaterTimestamp returns true if timestamp1 is later in time than timestamp2 factoring in timestamp wrap-around
func IsLaterTimestamp(timestamp1 uint32, timestamp2 uint32) bool {
return (timestamp1 - timestamp2) < (1 << 31)
return &StreamStatsWithLayers{
StreamStats: b.stats,
Layers: layers,
}
}
-56
View File
@@ -244,59 +244,3 @@ func TestFractionLostReport(t *testing.T) {
}
wg.Wait()
}
/*
func TestSeqWrapHandler(t *testing.T) {
s := SeqWrapHandler{}
s.UpdateMaxSeq(1)
require.Equal(t, uint32(1), s.MaxSeqNo())
type caseInfo struct {
seqs []uint32 // {seq1, seq2, unwrap of seq2}
newer bool // seq2 is newer than seq1
}
// test normal case, name -> {seq1, seq2, unwrap of seq2}
cases := map[string]caseInfo{
"no wrap": {[]uint32{1, 4, 4}, true},
"no wrap backward": {[]uint32{4, 1, 1}, false},
"wrap around forward to zero": {[]uint32{65534, 0, 65536}, true},
"wrap around forward": {[]uint32{65534, 10, 65546}, true},
"wrap around forward 2": {[]uint32{65535 + 65536*2, 1, 1 + 65536*3}, true},
"wrap around backward ": {[]uint32{5, 65534, 65534}, false},
"wrap around backward less than zero": {[]uint32{5, 65534, 65534}, false},
}
for k, v := range cases {
t.Run(k, func(t *testing.T) {
s := SeqWrapHandler{}
s.UpdateMaxSeq(v.seqs[0])
extsn, newer := s.Unwrap(uint16(v.seqs[1]))
require.Equal(t, v.newer, newer)
require.Equal(t, v.seqs[2], extsn)
})
}
}
func TestIsTimestampWrap(t *testing.T) {
type caseInfo struct {
name string
ts1 uint32
ts2 uint32
later bool
}
cases := []caseInfo{
{"normal case 1 timestamp later ", 2, 1, true},
{"normal case 2 timestamp later", 0x1c000000, 0x10000000, true},
{"wrap case timestamp later", 0xffff, 0xfc000000, true},
{"wrap case timestamp early", 0xfc000000, 0xffff, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
require.Equal(t, c.later, IsLaterTimestamp(c.ts1, c.ts2))
})
}
}
*/
+6 -4
View File
@@ -26,7 +26,7 @@ func NewNACKQueue() *NackQueue {
}
}
func (n *NackQueue) SetRTT(rtt int) {
func (n *NackQueue) SetRTT(rtt uint32) {
n.rtt = time.Duration(rtt) * time.Millisecond
}
@@ -52,9 +52,9 @@ func (n *NackQueue) Push(sn uint16) {
n.nacks = append(n.nacks, &nack{seqNum: sn, nacked: 0, lastNackTime: time.Now()})
}
func (n *NackQueue) Pairs() []rtcp.NackPair {
func (n *NackQueue) Pairs() ([]rtcp.NackPair, int) {
if len(n.nacks) == 0 {
return nil
return nil, 0
}
now := time.Now()
@@ -64,6 +64,7 @@ func (n *NackQueue) Pairs() []rtcp.NackPair {
snsToPurge := []uint16{}
numSeqNumsNacked := 0
isPairActive := false
var np rtcp.NackPair
var nps []rtcp.NackPair
@@ -77,6 +78,7 @@ func (n *NackQueue) Pairs() []rtcp.NackPair {
nack.nacked++
nack.lastNackTime = now
numSeqNumsNacked++
if (nack.seqNum - baseSN) > 16 {
// need a new nack pair
@@ -104,5 +106,5 @@ func (n *NackQueue) Pairs() []rtcp.NackPair {
n.Remove(sn)
}
return nps
return nps, numSeqNumsNacked
}
+41 -23
View File
@@ -8,44 +8,61 @@ import (
)
func Test_nackQueue_pairs(t *testing.T) {
type PairsResult struct {
pairs []rtcp.NackPair
numSeqNumsNacked int
}
tests := []struct {
name string
args []uint16
want []rtcp.NackPair
want PairsResult
}{
{
name: "Must return correct single pairs pair",
args: []uint16{1, 2, 4, 5},
want: []rtcp.NackPair{{
PacketID: 1,
LostPackets: 13,
}},
want: PairsResult{
pairs: []rtcp.NackPair{
{
PacketID: 1,
LostPackets: 13,
},
},
numSeqNumsNacked: 4,
},
},
{
name: "Must return correct pair wrap",
args: []uint16{65533, 2, 4, 5, 30, 32},
want: []rtcp.NackPair{
{
PacketID: 65533,
LostPackets: 1<<7 + 1<<6 + 1<<4,
want: PairsResult{
pairs: []rtcp.NackPair{
{
PacketID: 65533,
LostPackets: 1<<7 + 1<<6 + 1<<4,
},
{
PacketID: 30,
LostPackets: 1 << 1,
},
},
{
PacketID: 30,
LostPackets: 1 << 1,
}},
numSeqNumsNacked: 6,
},
},
{
name: "Must return 2 pairs pair",
args: []uint16{1, 2, 4, 5, 20, 22, 24, 27},
want: []rtcp.NackPair{
{
PacketID: 1,
LostPackets: 13,
},
{
PacketID: 20,
LostPackets: 74,
want: PairsResult{
pairs: []rtcp.NackPair{
{
PacketID: 1,
LostPackets: 13,
},
{
PacketID: 20,
LostPackets: 74,
},
},
numSeqNumsNacked: 8,
},
},
}
@@ -56,8 +73,9 @@ func Test_nackQueue_pairs(t *testing.T) {
for _, sn := range tt.args {
n.Push(sn)
}
got := n.Pairs()
require.EqualValues(t, tt.want, got)
got, numSeqNumsNacked := n.Pairs()
require.EqualValues(t, tt.want.pairs, got)
require.Equal(t, tt.want.numSeqNumsNacked, numSeqNumsNacked)
})
}
}
+28
View File
@@ -0,0 +1,28 @@
package buffer
type LayerStats struct {
TotalPackets uint32
TotalBytes uint64
TotalFrames uint32
}
type StreamStats struct {
TotalPrimaryPackets uint32
TotalPrimaryBytes uint64
TotalRetransmitPackets uint32
TotalRetransmitBytes uint64
TotalPaddingPackets uint32
TotalPaddingBytes uint64
TotalPacketsLost uint32
TotalFrames uint32
RTT uint32
Jitter float64
TotalNACKs uint32
TotalPLIs uint32
TotalFIRs uint32
}
type StreamStatsWithLayers struct {
StreamStats StreamStats
Layers map[int]LayerStats
}