updated server to webrtc v3 (untested)

This commit is contained in:
David Zhao
2020-12-11 20:15:04 -08:00
parent d4f30c126f
commit 7d7787590c
19 changed files with 1011 additions and 1436 deletions
+1 -1
View File
@@ -2,4 +2,4 @@ This package is largely files from the wonderful ion-sfu project.
https://github.com/pion/ion-sfu
It's duplicated here since we needed to access a private method in the Buffer class
It's duplicated here since we needed to access a private method in various helper classes
-454
View File
@@ -1,454 +0,0 @@
package sfu
// file from ion-sfu project
import (
"math"
"sort"
"sync"
"time"
"github.com/gammazero/deque"
"github.com/pion/rtcp"
"github.com/pion/rtp"
"github.com/pion/webrtc/v3"
)
const (
maxSN = 1 << 16
// default buffer time by ms
defaultBufferTime = 1000
)
type rtpExtInfo struct {
ExtTSN uint32
Timestamp int64
}
// Buffer contains all packets
type Buffer struct {
mu sync.RWMutex
pktQueue queue
codecType webrtc.RTPCodecType
simulcast bool
clockRate uint32
maxBitrate uint64
// supported feedbacks
remb bool
nack bool
tcc bool
lastSRNTPTime uint64
lastSRRTPTime uint32
lastSRRecv int64 // Represents wall clock of the most recent sender report arrival
baseSN uint16
cycles uint32
lastExpected uint32
lastReceived uint32
lostRate float32
ssrc uint32
lastPacketTime int64 // Time the last RTP packet from this source was received
lastRtcpPacketTime int64 // Time the last RTCP packet was received.
lastRtcpSrTime int64 // Time the last RTCP SR was received. Required for DLSR computation.
packetCount uint32 // Number of packets received from this source.
lastTransit uint32
maxSeqNo uint16 // The highest sequence number received in an RTP data packet
jitter float64 // An estimate of the statistical variance of the RTP data packet inter-arrival time.
totalByte uint64
// remb
rembSteps uint8
// transport-cc
tccExt uint8
tccExtInfo []rtpExtInfo
tccCycles uint32
tccLastExtSN uint32
tccPktCtn uint8
tccLastSn uint16
lastExtInfo uint16
}
// BufferOptions provides configuration options for the buffer
type BufferOptions struct {
TCCExt int
BufferTime int
MaxBitRate uint64
}
// NewBuffer constructs a new Buffer
func NewBuffer(track *webrtc.Track, o BufferOptions) *Buffer {
b := &Buffer{
ssrc: track.SSRC(),
clockRate: track.Codec().ClockRate,
codecType: track.Codec().Type,
maxBitrate: o.MaxBitRate,
simulcast: len(track.RID()) > 0,
rembSteps: 4,
}
if o.BufferTime <= 0 {
o.BufferTime = defaultBufferTime
}
b.pktQueue.duration = uint32(o.BufferTime) * b.clockRate / 1000
b.pktQueue.ssrc = track.SSRC()
b.tccExt = uint8(o.TCCExt)
for _, fb := range track.Codec().RTCPFeedback {
switch fb.Type {
case webrtc.TypeRTCPFBGoogREMB:
//log.Debugf("Setting feedback %s", webrtc.TypeRTCPFBGoogREMB)
b.remb = true
case webrtc.TypeRTCPFBTransportCC:
//log.Debugf("Setting feedback %s", webrtc.TypeRTCPFBTransportCC)
b.tccExtInfo = make([]rtpExtInfo, 1<<8)
b.tcc = true
case webrtc.TypeRTCPFBNACK:
//log.Debugf("Setting feedback %s", webrtc.TypeRTCPFBNACK)
b.nack = true
}
}
//log.Debugf("NewBuffer BufferOptions=%v", o)
return b
}
// Push adds a RTP Packet, out of order, new packet may be arrived later
func (b *Buffer) Push(p *rtp.Packet) {
b.mu.Lock()
defer b.mu.Unlock()
b.totalByte += uint64(p.MarshalSize())
if b.packetCount == 0 {
b.baseSN = p.SequenceNumber
b.maxSeqNo = p.SequenceNumber
b.pktQueue.headSN = p.SequenceNumber - 1
} else if snDiff(b.maxSeqNo, p.SequenceNumber) <= 0 {
if p.SequenceNumber < b.maxSeqNo {
b.cycles += maxSN
}
b.maxSeqNo = p.SequenceNumber
}
b.packetCount++
b.lastPacketTime = time.Now().UnixNano()
arrival := uint32(b.lastPacketTime / 1e6 * int64(b.clockRate/1e3))
transit := arrival - p.Timestamp
if b.lastTransit != 0 {
d := int32(transit - b.lastTransit)
if d < 0 {
d = -d
}
b.jitter += (float64(d) - b.jitter) / 16
}
b.lastTransit = transit
if b.codecType == webrtc.RTPCodecTypeVideo {
b.pktQueue.AddPacket(p, p.SequenceNumber == b.maxSeqNo)
}
if b.tcc {
rtpTCC := rtp.TransportCCExtension{}
if err := rtpTCC.Unmarshal(p.GetExtension(b.tccExt)); err == nil {
if rtpTCC.TransportSequence < 0x0fff && (b.tccLastSn&0xffff) > 0xf000 {
b.tccCycles += maxSN
}
b.tccExtInfo = append(b.tccExtInfo, rtpExtInfo{
ExtTSN: b.tccCycles | uint32(rtpTCC.TransportSequence),
Timestamp: b.lastPacketTime / 1e3,
})
}
}
}
func (b *Buffer) buildREMBPacket() *rtcp.ReceiverEstimatedMaximumBitrate {
br := b.maxBitrate
if b.rembSteps > 0 {
br /= uint64(b.rembSteps)
b.rembSteps--
}
return &rtcp.ReceiverEstimatedMaximumBitrate{
SenderSSRC: b.ssrc,
Bitrate: br,
SSRCs: []uint32{b.ssrc},
}
}
func (b *Buffer) buildTransportCCPacket() *rtcp.TransportLayerCC {
if len(b.tccExtInfo) == 0 {
return nil
}
sort.Slice(b.tccExtInfo, func(i, j int) bool {
return b.tccExtInfo[i].ExtTSN < b.tccExtInfo[j].ExtTSN
})
tccPkts := make([]rtpExtInfo, 0, int(float64(len(b.tccExtInfo))*1.2))
for _, tccExtInfo := range b.tccExtInfo {
if tccExtInfo.ExtTSN < b.tccLastExtSN {
continue
}
if b.tccLastExtSN != 0 {
for j := b.tccLastExtSN + 1; j < tccExtInfo.ExtTSN; j++ {
tccPkts = append(tccPkts, rtpExtInfo{ExtTSN: j})
}
}
b.tccLastExtSN = tccExtInfo.ExtTSN
tccPkts = append(tccPkts, tccExtInfo)
}
b.tccExtInfo = b.tccExtInfo[:0]
rtcpTCC := &rtcp.TransportLayerCC{
Header: rtcp.Header{
Padding: true,
Count: rtcp.FormatTCC,
Type: rtcp.TypeTransportSpecificFeedback,
},
MediaSSRC: b.ssrc,
BaseSequenceNumber: uint16(tccPkts[0].ExtTSN),
PacketStatusCount: uint16(len(tccPkts)),
FbPktCount: b.tccPktCtn,
}
b.tccPktCtn++
firstRecv := false
allSame := true
timestamp := int64(0)
deltaLen := 0
lastStatus := rtcp.TypeTCCPacketReceivedWithoutDelta
maxStatus := rtcp.TypeTCCPacketNotReceived
var statusList deque.Deque
for _, stat := range tccPkts {
status := rtcp.TypeTCCPacketNotReceived
if stat.Timestamp != 0 {
var delta int64
if !firstRecv {
firstRecv = true
timestamp = stat.Timestamp
rtcpTCC.ReferenceTime = uint32(stat.Timestamp / 64000)
}
delta = (stat.Timestamp - timestamp) / 250
if delta < 0 || delta > 255 {
status = rtcp.TypeTCCPacketReceivedLargeDelta
rDelta := int16(delta)
if int64(rDelta) != delta {
if rDelta > 0 {
rDelta = math.MaxInt16
} else {
rDelta = math.MinInt16
}
}
rtcpTCC.RecvDeltas = append(rtcpTCC.RecvDeltas, &rtcp.RecvDelta{
Type: status,
Delta: int64(rDelta) * 250,
})
deltaLen += 2
} else {
status = rtcp.TypeTCCPacketReceivedSmallDelta
rtcpTCC.RecvDeltas = append(rtcpTCC.RecvDeltas, &rtcp.RecvDelta{
Type: status,
Delta: delta * 250,
})
deltaLen++
}
timestamp = stat.Timestamp
}
if allSame && lastStatus != rtcp.TypeTCCPacketReceivedWithoutDelta && status != lastStatus {
if statusList.Len() > 7 {
rtcpTCC.PacketChunks = append(rtcpTCC.PacketChunks, &rtcp.RunLengthChunk{
PacketStatusSymbol: lastStatus,
RunLength: uint16(statusList.Len()),
})
statusList.Clear()
lastStatus = rtcp.TypeTCCPacketReceivedWithoutDelta
maxStatus = rtcp.TypeTCCPacketNotReceived
allSame = true
} else {
allSame = false
}
}
statusList.PushBack(status)
if status > maxStatus {
maxStatus = status
}
lastStatus = status
if !allSame {
if maxStatus == rtcp.TypeTCCPacketReceivedLargeDelta && statusList.Len() > 6 {
symbolList := make([]uint16, 7)
for i := 0; i < 7; i++ {
symbolList[i] = statusList.PopFront().(uint16)
}
rtcpTCC.PacketChunks = append(rtcpTCC.PacketChunks, &rtcp.StatusVectorChunk{
SymbolSize: rtcp.TypeTCCSymbolSizeTwoBit,
SymbolList: symbolList,
})
lastStatus = rtcp.TypeTCCPacketReceivedWithoutDelta
maxStatus = rtcp.TypeTCCPacketNotReceived
allSame = true
for i := 0; i < statusList.Len(); i++ {
status = statusList.At(i).(uint16)
if status > maxStatus {
maxStatus = status
}
if allSame && lastStatus != rtcp.TypeTCCPacketReceivedWithoutDelta && status != lastStatus {
allSame = false
}
lastStatus = status
}
} else if statusList.Len() > 13 {
symbolList := make([]uint16, 14)
for i := 0; i < 14; i++ {
symbolList[i] = statusList.PopFront().(uint16)
}
rtcpTCC.PacketChunks = append(rtcpTCC.PacketChunks, &rtcp.StatusVectorChunk{
SymbolSize: rtcp.TypeTCCSymbolSizeOneBit,
SymbolList: symbolList,
})
lastStatus = rtcp.TypeTCCPacketReceivedWithoutDelta
maxStatus = rtcp.TypeTCCPacketNotReceived
allSame = true
}
}
}
if statusList.Len() > 0 {
if allSame {
rtcpTCC.PacketChunks = append(rtcpTCC.PacketChunks, &rtcp.RunLengthChunk{
PacketStatusSymbol: lastStatus,
RunLength: uint16(statusList.Len()),
})
} else if maxStatus == rtcp.TypeTCCPacketReceivedLargeDelta {
symbolList := make([]uint16, statusList.Len())
for i := 0; i < statusList.Len(); i++ {
symbolList[i] = statusList.PopFront().(uint16)
}
rtcpTCC.PacketChunks = append(rtcpTCC.PacketChunks, &rtcp.StatusVectorChunk{
SymbolSize: rtcp.TypeTCCSymbolSizeTwoBit,
SymbolList: symbolList,
})
} else {
symbolList := make([]uint16, statusList.Len())
for i := 0; i < statusList.Len(); i++ {
symbolList[i] = statusList.PopFront().(uint16)
}
rtcpTCC.PacketChunks = append(rtcpTCC.PacketChunks, &rtcp.StatusVectorChunk{
SymbolSize: rtcp.TypeTCCSymbolSizeOneBit,
SymbolList: symbolList,
})
}
}
pLen := uint16(20 + len(rtcpTCC.PacketChunks)*2 + deltaLen)
rtcpTCC.Header.Padding = pLen%4 != 0
for pLen%4 != 0 {
pLen++
}
rtcpTCC.Header.Length = (pLen / 4) - 1
return rtcpTCC
}
func (b *Buffer) BuildReceptionReport() rtcp.ReceptionReport {
extMaxSeq := b.cycles | uint32(b.maxSeqNo)
expected := extMaxSeq - uint32(b.baseSN) + 1
lost := expected - b.packetCount
if b.packetCount == 0 {
lost = 0
}
expectedInterval := expected - b.lastExpected
b.lastExpected = expected
receivedInterval := b.packetCount - b.lastReceived
b.lastReceived = b.packetCount
lostInterval := expectedInterval - receivedInterval
b.lostRate = float32(lostInterval) / float32(expectedInterval)
var fracLost uint8
if expectedInterval != 0 && lostInterval > 0 {
fracLost = uint8((lostInterval << 8) / expectedInterval)
}
var dlsr uint32
if b.lastSRRecv != 0 {
delayMS := uint32((time.Now().UnixNano() - b.lastSRRecv) / 1e6)
dlsr = (delayMS / 1e3) << 16
dlsr |= (delayMS % 1e3) * 65536 / 1000
}
rr := rtcp.ReceptionReport{
SSRC: b.ssrc,
FractionLost: fracLost,
TotalLost: lost,
LastSequenceNumber: extMaxSeq,
Jitter: uint32(b.jitter),
LastSenderReport: uint32(b.lastSRNTPTime >> 16),
Delay: dlsr,
}
return rr
}
func (b *Buffer) SetSenderReportData(rtpTime uint32, ntpTime uint64) {
b.mu.Lock()
defer b.mu.Unlock()
b.lastSRRTPTime = rtpTime
b.lastSRNTPTime = ntpTime
b.lastSRRecv = time.Now().UnixNano()
}
func (b *Buffer) BuildRTCP() (rtcp.ReceptionReport, []rtcp.Packet) {
b.mu.RLock()
defer b.mu.RUnlock()
var pkts []rtcp.Packet
var report rtcp.ReceptionReport
report = b.BuildReceptionReport()
if b.remb {
pkts = append(pkts, b.buildREMBPacket())
}
if b.tcc {
if tccPkt := b.buildTransportCCPacket(); tccPkt != nil {
pkts = append(pkts, tccPkt)
}
}
return report, pkts
}
// WritePacket write buffer packet to requested track. and modify headers
func (b *Buffer) WritePacket(sn uint16, track *webrtc.Track, snOffset uint16, tsOffset, ssrc uint32) error {
b.mu.RLock()
defer b.mu.RUnlock()
if bufferPkt := b.pktQueue.GetPacket(sn); bufferPkt != nil {
bSsrc := bufferPkt.SSRC
bufferPkt.SequenceNumber -= snOffset
bufferPkt.Timestamp -= tsOffset
bufferPkt.SSRC = ssrc
err := track.WriteRTP(bufferPkt)
bufferPkt.Timestamp += tsOffset
bufferPkt.SequenceNumber += snOffset
bufferPkt.SSRC = bSsrc
return err
}
return ErrPacketNotFound
}
func (b *Buffer) onLostHandler(fn func(nack *rtcp.TransportLayerNack)) {
if b.nack {
b.pktQueue.onLost = fn
}
}
type BufferStats struct {
TotalBytes uint64
LastPacketTime int64
}
func (b *Buffer) Stats() BufferStats {
return BufferStats{
TotalBytes: b.totalByte,
LastPacketTime: b.lastPacketTime,
}
}
+273
View File
@@ -0,0 +1,273 @@
package sfu
import (
"bytes"
"encoding/binary"
"strings"
"sync"
"sync/atomic"
"time"
log "github.com/pion/ion-log"
"github.com/pion/rtcp"
"github.com/pion/rtp"
"github.com/pion/webrtc/v3"
)
// DownTrack implements TrackLocal, is the track used to write packets
// to SFU Subscriber, the track handle the packets for simple, simulcast
// and SVC Publisher.
type DownTrack struct {
id string
bound atomicBool
mime string
nList *nackList
ssrc uint32
payload uint8
streamID string
//enabled atomicBool
reSync atomicBool
snOffset uint16
tsOffset uint32
lastSSRC uint32
lastSN uint16
lastTS uint32
codec webrtc.RTPCodecCapability
transceiver *webrtc.RTPTransceiver
writeStream webrtc.TrackLocalWriter
onCloseHandler func()
onBind func()
closeOnce sync.Once
// Report helpers
octetCount uint32
packetCount uint32
maxPacketTs uint32
lastPacketMs int64
}
// NewDownTrack returns a DownTrack.
func NewDownTrack(c webrtc.RTPCodecCapability, id, streamID string) (*DownTrack, error) {
return &DownTrack{
id: id,
nList: newNACKList(),
codec: c,
streamID: streamID,
}, nil
}
// Bind is called by the PeerConnection after negotiation is complete
// This asserts that the code requested is supported by the remote peer.
// If so it setups all the state (SSRC and PayloadType) to have a call
func (d *DownTrack) Bind(t webrtc.TrackLocalContext) (webrtc.RTPCodecParameters, error) {
parameters := webrtc.RTPCodecParameters{RTPCodecCapability: d.codec}
if codec, err := codecParametersFuzzySearch(parameters, t.CodecParameters()); err == nil {
d.ssrc = uint32(t.SSRC())
d.payload = uint8(codec.PayloadType)
d.writeStream = t.WriteStream()
d.mime = strings.ToLower(codec.MimeType)
d.bound.set(true)
d.reSync.set(true)
if d.onBind != nil {
d.onBind()
}
return codec, nil
}
return webrtc.RTPCodecParameters{}, webrtc.ErrUnsupportedCodec
}
// Unbind implements the teardown logic when the track is no longer needed. This happens
// because a track has been stopped.
func (d *DownTrack) Unbind(_ webrtc.TrackLocalContext) error {
d.bound.set(false)
return nil
}
func (d *DownTrack) IsBound() bool {
return d.bound.get()
}
// ID is the unique identifier for this Track. This should be unique for the
// stream, but doesn't have to globally unique. A common example would be 'audio' or 'video'
// and StreamID would be 'desktop' or 'webcam'
func (d *DownTrack) ID() string { return d.id }
// Codec returns current track codec capability
func (d *DownTrack) Codec() webrtc.RTPCodecCapability { return d.codec }
// StreamID is the group this track belongs too. This must be unique
func (d *DownTrack) StreamID() string { return d.streamID }
// Kind controls if this TrackLocal is audio or video
func (d *DownTrack) Kind() webrtc.RTPCodecType {
switch {
case strings.HasPrefix(d.codec.MimeType, "audio/"):
return webrtc.RTPCodecTypeAudio
case strings.HasPrefix(d.codec.MimeType, "video/"):
return webrtc.RTPCodecTypeVideo
default:
return webrtc.RTPCodecType(0)
}
}
// WriteRTP writes a RTP Packet to the DownTrack
func (d *DownTrack) WriteRTP(p *rtp.Packet) error {
if !d.IsBound() {
return nil
}
return d.writeSimpleRTP(*p)
}
func (d *DownTrack) CreateSourceDescriptionChunks() []rtcp.SourceDescriptionChunk {
if !d.IsBound() {
return nil
}
return []rtcp.SourceDescriptionChunk{
{
Source: d.ssrc,
Items: []rtcp.SourceDescriptionItem{{
Type: rtcp.SDESCNAME,
Text: d.streamID,
}},
}, {
Source: d.ssrc,
Items: []rtcp.SourceDescriptionItem{{
Type: rtcp.SDESType(15),
Text: d.transceiver.Mid(),
}},
},
}
}
func (d *DownTrack) CreateSenderReport() *rtcp.SenderReport {
now := time.Now().UnixNano()
nowNTP := timeToNtp(now)
lastPktMs := atomic.LoadInt64(&d.lastPacketMs)
maxPktTs := atomic.LoadUint32(&d.lastTS)
diffTs := uint32((now/1e6)-lastPktMs) * d.codec.ClockRate / 1000
octets, packets := d.getSRStats()
return &rtcp.SenderReport{
SSRC: d.ssrc,
NTPTime: nowNTP,
RTPTime: maxPktTs + diffTs,
PacketCount: packets,
OctetCount: octets,
}
}
// Close track
func (d *DownTrack) Close() {
d.closeOnce.Do(func() {
if d.onCloseHandler != nil {
d.onCloseHandler()
}
})
}
// OnCloseHandler method to be called on remote tracked removed
func (d *DownTrack) OnCloseHandler(fn func()) {
d.onCloseHandler = fn
}
func (d *DownTrack) OnBind(fn func()) {
d.onBind = fn
}
// -- start -- accessors to avoid accessing private vars
func (d *DownTrack) SetTransceiver(transceiver *webrtc.RTPTransceiver) {
d.transceiver = transceiver
}
func (d *DownTrack) RTPSender() *webrtc.RTPSender {
return d.transceiver.Sender()
}
func (d *DownTrack) SSRC() uint32 {
return d.ssrc
}
func (d *DownTrack) LastSSRC() uint32 {
return d.lastSSRC
}
func (d *DownTrack) SnOffset() uint16 {
return d.snOffset
}
func (d *DownTrack) TsOffset() uint32 {
return d.tsOffset
}
func (d *DownTrack) GetNACKSeqNo(seqNo []uint16) []uint16 {
return d.nList.getNACKSeqNo(seqNo)
}
// -- end -- accessors to avoid accessing private vars
func (d *DownTrack) writeSimpleRTP(pkt rtp.Packet) error {
if d.reSync.get() {
if d.Kind() == webrtc.RTPCodecTypeVideo {
relay := false
// Wait for a keyframe to sync new source
switch d.mime {
case "video/vp8":
vp8Packet := VP8Helper{}
if err := vp8Packet.Unmarshal(pkt.Payload); err == nil {
relay = vp8Packet.IsKeyFrame
}
case "video/h264":
var word uint32
payload := bytes.NewReader(pkt.Payload)
err := binary.Read(payload, binary.BigEndian, &word)
if err != nil || (word&0x1F000000)>>24 != 24 {
relay = false
} else {
relay = word&0x1F == 7
}
}
if !relay {
// TODO: how do we sent PLI to the source?
//d.receiver.SendRTCP([]rtcp.Packet{
// &rtcp.PictureLossIndication{SenderSSRC: d.ssrc, MediaSSRC: pkt.SSRC},
//})
return ErrRequiresKeyFrame
}
}
d.snOffset = pkt.SequenceNumber - d.lastSN - 1
d.tsOffset = pkt.Timestamp - d.lastTS - 1
d.lastSSRC = pkt.SSRC
d.reSync.set(false)
}
atomic.AddUint32(&d.octetCount, uint32(len(pkt.Payload)))
atomic.AddUint32(&d.packetCount, 1)
d.lastSSRC = pkt.SSRC
newSN := pkt.SequenceNumber - d.snOffset
newTS := pkt.Timestamp - d.tsOffset
if (newSN-d.lastSN)&0x8000 == 0 || d.lastSN == 0 {
d.lastSN = newSN
atomic.StoreInt64(&d.lastPacketMs, time.Now().UnixNano()/1e6)
atomic.StoreUint32(&d.lastTS, newTS)
}
pkt.PayloadType = d.payload
pkt.Timestamp = d.lastTS
pkt.SequenceNumber = d.lastSN
pkt.SSRC = d.ssrc
_, err := d.writeStream.WriteRTP(&pkt.Header, pkt.Payload)
if err != nil {
log.Errorf("Write packet err %v", err)
}
return err
}
func (d *DownTrack) getSRStats() (octets, packets uint32) {
octets = atomic.LoadUint32(&d.octetCount)
packets = atomic.LoadUint32(&d.packetCount)
return
}
+4 -1
View File
@@ -5,12 +5,15 @@ import "errors"
var (
errPeerConnectionInitFailed = errors.New("pc init failed")
errPtNotSupported = errors.New("payload type not supported")
errCreatingDataChannel = errors.New("failed to create data channel")
// router errors
errNoReceiverFound = errors.New("no receiver found")
// Helpers errors
errShortPacket = errors.New("packet is not large enough")
errNilPacket = errors.New("invalid nil packet")
// buffer errors
ErrPacketNotFound = errors.New("packet not found in cache")
errPacketNotFound = errors.New("packet not found in cache")
errPacketTooOld = errors.New("packet not found in cache, too old")
ErrRequiresKeyFrame = errors.New("requires a keyframe to send down first")
)
+34 -20
View File
@@ -2,7 +2,10 @@ package sfu
import (
"encoding/binary"
"strings"
"sync/atomic"
"github.com/pion/webrtc/v3"
)
const ntpEpoch = 2208988800
@@ -71,11 +74,13 @@ func (p *VP8Helper) Unmarshal(payload []byte) error {
}
var idx uint8
S := payload[idx]&0x10 > 0
// Check for extended bit control
if payload[idx]&0x80 > 0 {
idx++
// Check if T is present, if not, no temporal layer is available
p.TemporalSupported = payload[idx]&0x20 > 0
K := payload[idx]&0x10 > 0
L := payload[idx]&0x40 > 0
// Check for PictureID
if payload[idx]&0x80 > 0 {
@@ -97,38 +102,47 @@ func (p *VP8Helper) Unmarshal(payload []byte) error {
p.tlzIdx = idx
p.TL0PICIDX = payload[idx]
}
idx++
// Set TID
p.TID = (payload[idx] & 0xc0) >> 6
idx++
if p.TemporalSupported || K {
idx++
p.TID = (payload[idx] & 0xc0) >> 6
}
if int(idx) >= payloadLen {
return errShortPacket
}
idx++
// Check is packet is a keyframe by looking at P bit in vp8 payload
p.IsKeyFrame = payload[idx]&0x01 == 0
p.IsKeyFrame = payload[idx]&0x01 == 0 && S
} else {
idx++
// Check is packet is a keyframe by looking at P bit in vp8 payload
p.IsKeyFrame = payload[idx]&0x01 == 0 && S
}
return nil
}
func snDiff(sn1, sn2 uint16) int {
if sn1 == sn2 {
return 0
}
if ((sn2 - sn1) & 0x8000) != 0 {
return 1
}
return -1
}
func timeToNtp(ns int64) uint64 {
seconds := uint64(ns/1e9 + ntpEpoch)
fraction := uint64(((ns % 1e9) << 32) / 1e9)
return seconds<<32 | fraction
}
// fromNtp converts a NTP timestamp into GO time
func fromNtp(seconds, fraction uint32) (tm int64) {
n := (int64(fraction) * 1e9) >> 32
tm = (int64(seconds)-ntpEpoch)*1e9 + n
return
// Do a fuzzy find for a codec in the list of codecs
// Used for lookup up a codec in an existing list to find a match
func codecParametersFuzzySearch(needle webrtc.RTPCodecParameters, haystack []webrtc.RTPCodecParameters) (webrtc.RTPCodecParameters, error) {
// First attempt to match on MimeType + SDPFmtpLine
for _, c := range haystack {
if strings.EqualFold(c.RTPCodecCapability.MimeType, needle.RTPCodecCapability.MimeType) &&
c.RTPCodecCapability.SDPFmtpLine == needle.RTPCodecCapability.SDPFmtpLine {
return c, nil
}
}
// Fallback to just MimeType
for _, c := range haystack {
if strings.EqualFold(c.RTPCodecCapability.MimeType, needle.RTPCodecCapability.MimeType) {
return c, nil
}
}
return webrtc.RTPCodecParameters{}, webrtc.ErrCodecNotFound
}
-129
View File
@@ -1,129 +0,0 @@
package sfu
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestVP8Helper_Unmarshal(t *testing.T) {
type args struct {
payload []byte
}
tests := []struct {
name string
args args
wantErr bool
checkTemporal bool
temporalSupport bool
checkKeyFrame bool
keyFrame bool
checkPictureID bool
pictureID uint16
checkTlzIdx bool
tlzIdx uint8
checkTempID bool
temporalID uint8
}{
{
name: "Empty or nil payload must return error",
args: args{payload: []byte{}},
wantErr: true,
},
{
name: "Small payloads must return errors",
args: args{payload: []byte{0x0, 0x1, 0x2}},
wantErr: true,
},
{
name: "Temporal must be supported by setting T bit to 1",
args: args{payload: []byte{0xff, 0x20, 0x1, 0x2, 0x3, 0x4}},
checkTemporal: true,
temporalSupport: true,
},
{
name: "Picture must be ID 7 bits by setting M bit to 0 and present by I bit set to 1",
args: args{payload: []byte{0xff, 0xff, 0x11, 0x2, 0x3, 0x4}},
checkPictureID: true,
pictureID: 17,
},
{
name: "Picture ID must be 15 bits by setting M bit to 1 and present by I bit set to 1",
args: args{payload: []byte{0xff, 0xff, 0x92, 0x67, 0x3, 0x4, 0x5}},
checkPictureID: true,
pictureID: 4711,
},
{
name: "Temporal level zero index must be present if L set to 1",
args: args{payload: []byte{0xff, 0xff, 0xff, 0xfd, 0xb4, 0x4, 0x5}},
checkTlzIdx: true,
tlzIdx: 180,
},
{
name: "Temporal index must be present and used if T bit set to 1",
args: args{payload: []byte{0xff, 0xff, 0xff, 0xfd, 0xb4, 0x9f, 0x5, 0x6}},
checkTempID: true,
temporalID: 2,
},
{
name: "Check if packet is a keyframe by looking at P bit set to 0",
args: args{payload: []byte{0xff, 0xff, 0xff, 0xfd, 0xb4, 0x9f, 0x94, 0x1}},
checkKeyFrame: true,
keyFrame: true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
p := &VP8Helper{}
if err := p.Unmarshal(tt.args.payload); (err != nil) != tt.wantErr {
t.Errorf("Unmarshal() error = %v, wantErr %v", err, tt.wantErr)
}
if tt.checkTemporal {
assert.Equal(t, tt.temporalSupport, p.TemporalSupported)
}
if tt.checkKeyFrame {
assert.Equal(t, tt.keyFrame, p.IsKeyFrame)
}
if tt.checkPictureID {
assert.Equal(t, tt.pictureID, p.PictureID)
}
if tt.checkTlzIdx {
assert.Equal(t, tt.tlzIdx, p.TL0PICIDX)
}
if tt.checkTempID {
assert.Equal(t, tt.temporalID, p.TID)
}
})
}
}
func Test_timeToNtp(t *testing.T) {
type args struct {
ns int64
}
tests := []struct {
name string
args args
wantNTP uint64
}{
{
name: "Must return correct NTP time",
args: args{
ns: time.Unix(1602391458, 1234).UnixNano(),
},
wantNTP: 16369753560730047667,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
gotNTP := timeToNtp(tt.args.ns)
if gotNTP != tt.wantNTP {
t.Errorf("timeToNtp() gotFraction = %v, want %v", gotNTP, tt.wantNTP)
}
println(gotNTP >> 16)
})
}
}
+49
View File
@@ -0,0 +1,49 @@
package sfu
import (
"container/list"
"time"
)
const (
ignoreRetransmission = 5e8 // Ignore packet retransmission after ignoreRetransmission milliseconds
maxNackQueue = 100
)
type NACK struct {
SN uint16
LRX int64
}
type nackList struct {
nacks map[uint16]*list.Element
ll *list.List
}
func newNACKList() *nackList {
return &nackList{
nacks: make(map[uint16]*list.Element),
ll: list.New(),
}
}
func (n *nackList) getNACKSeqNo(seqno []uint16) []uint16 {
packets := make([]uint16, 0, 17)
for _, sn := range seqno {
if nack, ok := n.nacks[sn]; !ok {
n.nacks[sn] = n.ll.PushBack(NACK{sn, time.Now().UnixNano()})
packets = append(packets, sn)
} else if time.Now().UnixNano()-nack.Value.(NACK).LRX > ignoreRetransmission {
nack.Value = NACK{sn, time.Now().UnixNano()}
packets = append(packets, sn)
}
}
for len(n.nacks) > maxNackQueue {
el := n.ll.Back()
delete(n.nacks, el.Value.(NACK).SN)
n.ll.Remove(el)
}
return packets
}
-124
View File
@@ -1,124 +0,0 @@
package sfu
import (
//"github.com/pion/ion-sfu/pkg/log"
"github.com/pion/rtcp"
"github.com/pion/rtp"
)
type queue struct {
pkts []*rtp.Packet
ssrc uint32
head int
tail int
size int
headSN uint16
counter int
duration uint32
onLost func(nack *rtcp.TransportLayerNack)
}
func (q *queue) AddPacket(pkt *rtp.Packet, latest bool) {
if !latest {
q.set(int(q.headSN-pkt.SequenceNumber), pkt)
return
}
diff := pkt.SequenceNumber - q.headSN
q.headSN = pkt.SequenceNumber
for i := uint16(1); i < diff; i++ {
q.push(nil)
q.counter++
}
q.counter++
q.push(pkt)
if q.counter >= 7 {
if n := q.nack(); n != nil && q.onLost != nil {
q.onLost(&rtcp.TransportLayerNack{
MediaSSRC: q.ssrc,
Nacks: []rtcp.NackPair{*n},
})
}
q.clean()
q.counter -= 5
}
}
func (q *queue) GetPacket(sn uint16) *rtp.Packet {
return q.get(int(q.headSN - sn))
}
func (q *queue) push(pkt *rtp.Packet) {
q.resize()
q.head = (q.head - 1) & (len(q.pkts) - 1)
q.pkts[q.head] = pkt
q.size++
}
func (q *queue) shift() {
if q.size <= 0 {
return
}
q.tail = (q.tail - 1) & (len(q.pkts) - 1)
q.pkts[q.tail] = nil
q.size--
}
func (q *queue) last() *rtp.Packet {
return q.pkts[(q.tail-1)&(len(q.pkts)-1)]
}
func (q *queue) get(i int) *rtp.Packet {
if i < 0 || i >= q.size {
return nil
}
return q.pkts[(q.head+i)&(len(q.pkts)-1)]
}
func (q *queue) set(i int, pkt *rtp.Packet) {
if i < 0 || i >= q.size {
//log.Warnf("warn: %v:", errPacketTooOld)
return
}
q.pkts[(q.head+i)&(len(q.pkts)-1)] = pkt
}
func (q *queue) resize() {
if len(q.pkts) == 0 {
q.pkts = make([]*rtp.Packet, 128)
return
}
if q.size == len(q.pkts) {
newBuf := make([]*rtp.Packet, q.size<<1)
if q.tail > q.head {
copy(newBuf, q.pkts[q.head:q.tail])
} else {
n := copy(newBuf, q.pkts[q.head:])
copy(newBuf[n:], q.pkts[:q.tail])
}
q.head = 0
q.tail = q.size
q.pkts = newBuf
}
}
func (q *queue) nack() *rtcp.NackPair {
for i := 0; i < 5; i++ {
if q.get(q.counter-i-1) == nil {
blp := uint16(0)
for j := 1; j < q.counter-i; j++ {
if q.get(q.counter-i-j-1) == nil {
blp |= 1 << (j - 1)
}
}
return &rtcp.NackPair{PacketID: q.headSN - uint16(q.counter-i-1), LostPackets: rtcp.PacketBitmap(blp)}
}
}
return nil
}
func (q *queue) clean() {
last := q.last()
for q.size > 120 && (last == nil || q.pkts[q.head].Timestamp-last.Timestamp > q.duration) {
q.shift()
}
}
-147
View File
@@ -1,147 +0,0 @@
package sfu
import (
"reflect"
"testing"
"github.com/stretchr/testify/assert"
"github.com/pion/rtcp"
"github.com/pion/rtp"
)
var TestPackets = []*rtp.Packet{
{
Header: rtp.Header{
SequenceNumber: 1,
},
},
{
Header: rtp.Header{
SequenceNumber: 3,
},
},
{
Header: rtp.Header{
SequenceNumber: 4,
},
},
{
Header: rtp.Header{
SequenceNumber: 6,
},
},
{
Header: rtp.Header{
SequenceNumber: 7,
},
},
{
Header: rtp.Header{
SequenceNumber: 10,
},
},
}
func Test_queue_nack(t *testing.T) {
type fields struct {
headSN uint16
}
tests := []struct {
name string
fields fields
want *rtcp.NackPair
}{
{
name: "Most generate correct nack packet",
fields: fields{},
want: &rtcp.NackPair{
PacketID: 2,
LostPackets: 100,
},
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
q := &queue{
headSN: tt.fields.headSN,
}
for _, p := range TestPackets {
diff := p.SequenceNumber - q.headSN
for i := 1; i < int(diff); i++ {
q.push(nil)
q.counter++
}
q.headSN = p.SequenceNumber
q.counter++
q.push(p)
}
if got := q.nack(); !reflect.DeepEqual(got, tt.want) {
t.Errorf("nack() = %v, want %v", got, tt.want)
}
})
}
}
func Test_queue(t *testing.T) {
q := &queue{}
for _, p := range TestPackets {
p := p
assert.NotPanics(t, func() {
q.AddPacket(p, true)
})
}
var expectedSN uint16
expectedSN = 6
assert.Equal(t, expectedSN, q.GetPacket(6).SequenceNumber)
np := &rtp.Packet{
Header: rtp.Header{
SequenceNumber: 8,
},
}
expectedSN = 8
q.AddPacket(np, false)
assert.Equal(t, expectedSN, q.GetPacket(8).SequenceNumber)
}
func Test_queue_edges(t *testing.T) {
var TestPackets = []*rtp.Packet{
{
Header: rtp.Header{
SequenceNumber: 65533,
},
},
{
Header: rtp.Header{
SequenceNumber: 65534,
},
},
{
Header: rtp.Header{
SequenceNumber: 2,
},
},
}
q := &queue{}
q.headSN = 65532
for _, p := range TestPackets {
p := p
assert.NotPanics(t, func() {
q.AddPacket(p, true)
})
}
assert.Equal(t, 6, q.size)
var expectedSN uint16
expectedSN = 65534
assert.Equal(t, expectedSN, q.GetPacket(expectedSN).SequenceNumber)
np := &rtp.Packet{
Header: rtp.Header{
SequenceNumber: 65535,
},
}
q.AddPacket(np, false)
assert.Equal(t, expectedSN+1, q.GetPacket(expectedSN+1).SequenceNumber)
}