diff --git a/pkg/sfu/buffer/bucket.go b/pkg/sfu/buffer/bucket.go index e844c851..f853de21 100644 --- a/pkg/sfu/buffer/bucket.go +++ b/pkg/sfu/buffer/bucket.go @@ -26,15 +26,17 @@ func NewBucket(buf *[]byte) *Bucket { } } -func (b *Bucket) AddPacket(pkt []byte, sn uint16, latest bool) ([]byte, error) { +func (b *Bucket) AddPacket(pkt []byte) ([]byte, error) { + sn := binary.BigEndian.Uint16(pkt[2:4]) if !b.init { b.headSN = sn - 1 b.init = true } - if !latest { + diff := sn - b.headSN + if diff > (1 << 15) { + // out-of-order return b.set(sn, pkt) } - diff := sn - b.headSN b.headSN = sn for i := uint16(1); i < diff; i++ { b.step++ diff --git a/pkg/sfu/buffer/bucket_test.go b/pkg/sfu/buffer/bucket_test.go index b9079f95..046aac9b 100644 --- a/pkg/sfu/buffer/bucket_test.go +++ b/pkg/sfu/buffer/bucket_test.go @@ -49,7 +49,7 @@ func Test_queue(t *testing.T) { buf, err := p.Marshal() assert.NoError(t, err) assert.NotPanics(t, func() { - _, _ = q.AddPacket(buf, p.SequenceNumber, true) + _, _ = q.AddPacket(buf) }) } var expectedSN uint16 @@ -70,14 +70,14 @@ func Test_queue(t *testing.T) { buf, err := np2.Marshal() assert.NoError(t, err) expectedSN = 8 - _, _ = q.AddPacket(buf, 8, false) + _, _ = q.AddPacket(buf) i, err = q.GetPacket(buff, expectedSN) assert.NoError(t, err) err = np.Unmarshal(buff[:i]) assert.NoError(t, err) assert.Equal(t, expectedSN, np.SequenceNumber) - _, err = q.AddPacket(buf, 8, false) + _, err = q.AddPacket(buf) assert.ErrorIs(t, err, ErrRTXPacket) } @@ -109,7 +109,7 @@ func Test_queue_edges(t *testing.T) { buf, err := p.Marshal() assert.NoError(t, err) assert.NotPanics(t, func() { - _, _ = q.AddPacket(buf, p.SequenceNumber, true) + _, _ = q.AddPacket(buf) }) }) } @@ -130,7 +130,7 @@ func Test_queue_edges(t *testing.T) { } buf, err := np2.Marshal() assert.NoError(t, err) - _, _ = q.AddPacket(buf, np2.SequenceNumber, false) + _, _ = q.AddPacket(buf) i, err = q.GetPacket(buff, expectedSN+1) assert.NoError(t, err) err = np.Unmarshal(buff[:i]) diff --git a/pkg/sfu/buffer/buffer.go b/pkg/sfu/buffer/buffer.go index ca177f1d..041e52f6 100644 --- a/pkg/sfu/buffer/buffer.go +++ b/pkg/sfu/buffer/buffer.go @@ -28,7 +28,7 @@ type pendingPacket struct { type ExtPacket struct { Head bool Arrival int64 - Packet rtp.Packet + Packet *rtp.Packet Payload interface{} KeyFrame bool RawPacket []byte @@ -56,10 +56,12 @@ type Buffer struct { mime string // supported feedbacks - remb bool - nack bool - twcc bool - audioLevel bool + remb bool + nack bool + twcc bool + audioLevel bool + latestTSForAudioLevelInitialized bool + latestTSForAudioLevel uint32 lastPacketRead int bitrate atomic.Value @@ -67,7 +69,6 @@ type Buffer struct { lastSRNTPTime uint64 lastSRRTPTime uint32 lastSRRecv int64 // Represents wall clock of the most recent sender report arrival - highestSN uint16 cycle uint16 lastRtcpPacketTime int64 // Time the last RTCP packet was received. lastRtcpSrTime int64 // Time the last RTCP SR was received. Required for DLSR computation. @@ -76,9 +77,9 @@ type Buffer struct { stats Stats rrSnapshot *receiverReportSnapshot - latestTimestamp uint32 // latest received RTP timestamp on packet - latestTimestampTime int64 // Time of the latest timestamp (in nanos since unix epoch) - lastFractionLostToReport uint8 // Last fraction lost from subscribers, should report to publisher; Audio only + highestSN uint16 + + lastFractionLostToReport uint8 // Last fraction lost from subscribers, should report to publisher; Audio only // callbacks onClose func() @@ -100,6 +101,7 @@ type receiverReportSnapshot struct { extSeqNum uint32 packetsReceived uint32 packetsLost uint32 + lastLossRate float32 } // BufferOptions provides configuration options for the buffer @@ -162,6 +164,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.nack = true } } @@ -269,16 +272,52 @@ func (b *Buffer) OnClose(fn func()) { } func (b *Buffer) calc(pkt []byte, arrivalTime int64) { - sn := binary.BigEndian.Uint16(pkt[2:4]) + pb, err := b.bucket.AddPacket(pkt) + if err != nil { + if err != ErrRTXPacket { + b.logger.Warnw("could not add RTP packet to bucket", err) + } + return + } + + var p rtp.Packet + if err := p.Unmarshal(pb); err != nil { + b.logger.Warnw("error unmarshaling RTP packet", err) + return + } + + b.updateStreamState(&p, len(pkt), arrivalTime) + + b.processHeaderExtensions(&p, arrivalTime) + + ep, temporalLayer := b.getExtPacket(pb, &p, arrivalTime) + if ep == nil { + return + } + b.extPackets.PushBack(ep) + + if temporalLayer >= 0 { + b.bitrateHelper[temporalLayer] += int64(len(pkt)) + } + + b.doNACKs() + + b.doReports(arrivalTime) +} + +func (b *Buffer) updateStreamState(p *rtp.Packet, pktSize int, arrivalTime int64) { + sn := p.SequenceNumber if b.stats.PacketCount == 0 { b.highestSN = sn - 1 + b.lastReport = arrivalTime b.rrSnapshot = &receiverReportSnapshot{ extSeqNum: uint32(sn) - 1, packetsReceived: 0, packetsLost: 0, + lastLossRate: 0.0, } } @@ -302,67 +341,10 @@ func (b *Buffer) calc(pkt []byte, arrivalTime int64) { b.highestSN = sn } - headPkt := sn == b.highestSN - var p rtp.Packet - pb, err := b.bucket.AddPacket(pkt, sn, headPkt) - if err != nil { - if err == ErrRTXPacket { - return - } - return - } - if err = p.Unmarshal(pb); err != nil { - return - } - - // submit to TWCC even if it is a padding only packet. Clients use padding only packets as probes - // for bandwidth estimation - if b.twcc { - if ext := p.GetExtension(b.twccExt); len(ext) > 1 { - b.feedbackTWCC(binary.BigEndian.Uint16(ext[0:2]), arrivalTime, p.Marker) - } - } - - b.stats.TotalBytes += uint64(len(pkt)) b.stats.PacketCount++ + b.stats.TotalBytes += uint64(pktSize) - ep := ExtPacket{ - Head: headPkt, - Packet: p, - Arrival: arrivalTime, - RawPacket: pb, - } - - if len(p.Payload) == 0 { - // padding only packet, nothing else to do - b.extPackets.PushBack(&ep) - return - } - - temporalLayer := int32(0) - switch b.mime { - case "video/vp8": - vp8Packet := VP8{} - if err := vp8Packet.Unmarshal(p.Payload); err != nil { - return - } - ep.Payload = vp8Packet - ep.KeyFrame = vp8Packet.IsKeyFrame - temporalLayer = int32(vp8Packet.TID) - case "video/h264": - ep.KeyFrame = IsH264Keyframe(p.Payload) - } - - b.extPackets.PushBack(&ep) - - // if first time update or the timestamp is later (factoring timestamp wrap around) - latestTimestamp := atomic.LoadUint32(&b.latestTimestamp) - latestTimestampTimeInNanosSinceEpoch := atomic.LoadInt64(&b.latestTimestampTime) - if (latestTimestampTimeInNanosSinceEpoch == 0) || IsLaterTimestamp(p.Timestamp, latestTimestamp) { - atomic.StoreUint32(&b.latestTimestamp, p.Timestamp) - atomic.StoreInt64(&b.latestTimestampTime, arrivalTime) - } - + // jitter arrival := uint32(arrivalTime / 1e6 * int64(b.clockRate/1e3)) transit := arrival - p.Timestamp if b.lastTransit != 0 { @@ -373,48 +355,106 @@ func (b *Buffer) calc(pkt []byte, arrivalTime int64) { b.stats.Jitter += (float64(d) - b.stats.Jitter) / 16 } b.lastTransit = transit +} + +func (b *Buffer) processHeaderExtensions(p *rtp.Packet, arrivalTime int64) { + // submit to TWCC even if it is a padding only packet. Clients use padding only packets as probes + // for bandwidth estimation + if b.twcc { + if ext := p.GetExtension(b.twccExt); len(ext) > 1 { + b.feedbackTWCC(binary.BigEndian.Uint16(ext[0:2]), arrivalTime, p.Marker) + } + } if b.audioLevel { + if !b.latestTSForAudioLevelInitialized { + b.latestTSForAudioLevelInitialized = true + b.latestTSForAudioLevel = p.Timestamp + } if e := p.GetExtension(b.audioExt); e != nil && b.onAudioLevel != nil { ext := rtp.AudioLevelExtension{} if err := ext.Unmarshal(e); err == nil { - duration := (int64(p.Timestamp) - int64(latestTimestamp)) * 1e3 / int64(b.clockRate) - if duration > 0 { - b.onAudioLevel(ext.Level, uint32(duration)) + if (p.Timestamp - b.latestTSForAudioLevel) < (1 << 31) { + duration := (int64(p.Timestamp) - int64(b.latestTSForAudioLevel)) * 1e3 / int64(b.clockRate) + if duration > 0 { + b.onAudioLevel(ext.Level, uint32(duration)) + } + + b.latestTSForAudioLevel = p.Timestamp } } } } +} - if b.nacker != nil { - if r := b.buildNACKPacket(); r != nil { - b.feedbackCB(r) - } +func (b *Buffer) getExtPacket(rawPacket []byte, rtpPacket *rtp.Packet, arrivalTime int64) (*ExtPacket, int32) { + ep := &ExtPacket{ + Head: rtpPacket.SequenceNumber == b.highestSN, + Packet: rtpPacket, + Arrival: arrivalTime, + RawPacket: rawPacket, } - b.bitrateHelper[temporalLayer] += int64(len(pkt)) + if len(rtpPacket.Payload) == 0 { + // padding only packet, nothing else to do + return ep, -1 + } + temporalLayer := int32(0) + switch b.mime { + case "video/vp8": + vp8Packet := VP8{} + if err := vp8Packet.Unmarshal(rtpPacket.Payload); err != nil { + b.logger.Warnw("could not unmarshal VP8 packet", err) + return nil, -1 + } + ep.Payload = vp8Packet + ep.KeyFrame = vp8Packet.IsKeyFrame + temporalLayer = int32(vp8Packet.TID) + case "video/h264": + ep.KeyFrame = IsH264Keyframe(rtpPacket.Payload) + } + + return ep, temporalLayer +} + +func (b *Buffer) doNACKs() { + if b.nacker == nil { + return + } + + if r := b.buildNACKPacket(); r != nil { + b.feedbackCB(r) + } +} + +func (b *Buffer) doReports(arrivalTime int64) { timeDiff := arrivalTime - b.lastReport - if timeDiff >= ReportDelta { - // - // As this happens in the data path, if there are no packets received - // in an interval, the bitrate will be stuck with the old value. - // GetBitrate() method in sfu.Receiver uses the availableLayers - // set by stream tracker to report 0 bitrate if a layer is not available. - // - bitrates, ok := b.bitrate.Load().([]int64) - if !ok { - bitrates = make([]int64, len(b.bitrateHelper)) - } - for i := 0; i < len(b.bitrateHelper); i++ { - br := (8 * b.bitrateHelper[i] * int64(ReportDelta)) / timeDiff - bitrates[i] = br - b.bitrateHelper[i] = 0 - } - b.bitrate.Store(bitrates) - b.feedbackCB(b.getRTCP()) - b.lastReport = arrivalTime + if timeDiff < ReportDelta { + return } + + b.lastReport = arrivalTime + + // + // As this happens in the data path, if there are no packets received + // in an interval, the bitrate will be stuck with the old value. + // GetBitrate() method in sfu.Receiver uses the availableLayers + // set by stream tracker to report 0 bitrate if a layer is not available. + // + bitrates, ok := b.bitrate.Load().([]int64) + if !ok { + bitrates = make([]int64, len(b.bitrateHelper)) + } + for i := 0; i < len(b.bitrateHelper); i++ { + br := (8 * b.bitrateHelper[i] * int64(ReportDelta)) / timeDiff + bitrates[i] = br + b.bitrateHelper[i] = 0 + } + b.bitrate.Store(bitrates) + + // RTCP reports + b.feedbackCB(b.getRTCP()) } func (b *Buffer) buildNACKPacket() []rtcp.Packet { @@ -435,17 +475,9 @@ func (b *Buffer) buildNACKPacket() []rtcp.Packet { func (b *Buffer) buildREMBPacket() *rtcp.ReceiverEstimatedMaximumBitrate { br := b.Bitrate() - extMaxSeq := (uint32(b.cycle) << 16) | uint32(b.highestSN) - expectedInInterval := extMaxSeq - b.rrSnapshot.extSeqNum - receivedInInterval := b.stats.PacketCount - b.rrSnapshot.packetsReceived - lostInInterval := expectedInInterval - receivedInInterval - if int(lostInInterval) < 0 { - // could happen if retransmitted packets arrive and make received greater than expected - lostInInterval = 0 - } lostRate := float32(0) - if expectedInInterval != 0 { - lostRate = float32(lostInInterval) / float32(expectedInInterval) + if b.rrSnapshot != nil { + lostRate = b.rrSnapshot.lastLossRate } if lostRate < 0.02 { @@ -481,12 +513,13 @@ func (b *Buffer) buildReceptionReport() *rtcp.ReceptionReport { receivedInInterval := b.stats.PacketCount - b.rrSnapshot.packetsReceived lostInInterval := expectedInInterval - receivedInInterval - if int(lostInInterval) < 0 { + if int32(lostInInterval) < 0 { // could happen if retransmitted packets arrive and make received greater than expected lostInInterval = 0 } - fracLost := uint8((float32(lostInInterval) / float32(expectedInInterval)) * 256.0) + lossRate := float32(lostInInterval) / float32(expectedInInterval) + fracLost := uint8(lossRate * 256.0) if b.lastFractionLostToReport > fracLost { // max of fraction lost from all subscribers is bigger than sfu received, use it. fracLost = b.lastFractionLostToReport @@ -505,6 +538,7 @@ func (b *Buffer) buildReceptionReport() *rtcp.ReceptionReport { extSeqNum: extMaxSeq, packetsReceived: b.stats.PacketCount, packetsLost: totalLost, + lastLossRate: lossRate, } return &rtcp.ReceptionReport{ diff --git a/pkg/sfu/buffer/buffer_test.go b/pkg/sfu/buffer/buffer_test.go index bb6816c1..0dd6376a 100644 --- a/pkg/sfu/buffer/buffer_test.go +++ b/pkg/sfu/buffer/buffer_test.go @@ -59,6 +59,7 @@ func TestNack(t *testing.T) { HeaderExtensions: nil, Codecs: []webrtc.RTPCodecParameters{vp8Codec}, }, vp8Codec.RTPCodecCapability, Options{}) + buff.nacker.SetRTT(0) for i := 0; i < 15; i++ { if i == 1 { continue @@ -104,10 +105,6 @@ func TestNack(t *testing.T) { }) } } - case *rtcp.PictureLossIndication: - if p.MediaSSRC == 123 { - // wg.Done() - } } } }) @@ -115,6 +112,7 @@ func TestNack(t *testing.T) { HeaderExtensions: nil, Codecs: []webrtc.RTPCodecParameters{vp8Codec}, }, vp8Codec.RTPCodecCapability, Options{}) + buff.nacker.SetRTT(0) for i := 0; i < 15; i++ { if i > 0 && i < 5 { continue diff --git a/pkg/sfu/downtrack.go b/pkg/sfu/downtrack.go index 17eeb5a7..650c3feb 100644 --- a/pkg/sfu/downtrack.go +++ b/pkg/sfu/downtrack.go @@ -312,7 +312,7 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) error { pool = PacketFactory.Get().(*[]byte) outbuf = pool } - payload, err = d.translateVP8PacketTo(&extPkt.Packet, &incomingVP8, tp.vp8.header, outbuf) + payload, err = d.translateVP8PacketTo(extPkt.Packet, &incomingVP8, tp.vp8.header, outbuf) if err != nil { d.pktsDropped.add(1) return err diff --git a/pkg/sfu/testutils/data.go b/pkg/sfu/testutils/data.go index e9dc81ea..cd96469e 100644 --- a/pkg/sfu/testutils/data.go +++ b/pkg/sfu/testutils/data.go @@ -48,7 +48,7 @@ func GetTestExtPacket(params *TestExtPacketParams) (*buffer.ExtPacket, error) { ep := &buffer.ExtPacket{ Head: params.IsHead, Arrival: params.ArrivalTime, - Packet: packet, + Packet: &packet, KeyFrame: params.IsKeyFrame, RawPacket: raw, }