move to ion-SFU's receiver and downtrack

This commit is contained in:
David Zhao
2021-02-04 21:57:40 -08:00
parent c015e267b0
commit c978a9cb1f
15 changed files with 253 additions and 822 deletions
-5
View File
@@ -1,5 +0,0 @@
This package is largely files from the wonderful ion-sfu project.
https://github.com/pion/ion-sfu
It's duplicated here with modifications to reference only classes that we need
-271
View File
@@ -1,271 +0,0 @@
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 {
// when we are writing to a new client and there isn't a keyframe, it makes it impossible
// for clients to render a frame. we'll send an error for the track writer.
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
}
-19
View File
@@ -1,19 +0,0 @@
package sfu
import "errors"
var (
errPeerConnectionInitFailed = errors.New("pc init failed")
errPtNotSupported = errors.New("payload type not supported")
errCreatingDataChannel = errors.New("failed to create data channel")
// routing 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")
errPacketTooOld = errors.New("packet not found in cache, too old")
ErrRequiresKeyFrame = errors.New("requires a keyframe to send down first")
)
-148
View File
@@ -1,148 +0,0 @@
package sfu
import (
"encoding/binary"
"strings"
"sync/atomic"
"github.com/pion/webrtc/v3"
)
const ntpEpoch = 2208988800
type atomicBool struct {
val int32
}
func (b *atomicBool) set(value bool) { // nolint: unparam
var i int32
if value {
i = 1
}
atomic.StoreInt32(&(b.val), i)
}
func (b *atomicBool) get() bool {
return atomic.LoadInt32(&(b.val)) != 0
}
// VP8Helper is a helper to get temporal data from VP8 packet header
/*
VP8Helper Payload Descriptor
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
|X|R|N|S|R| PID | (REQUIRED) |X|R|N|S|R| PID | (REQUIRED)
+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
X: |I|L|T|K| RSV | (OPTIONAL) X: |I|L|T|K| RSV | (OPTIONAL)
+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
I: |M| PictureID | (OPTIONAL) I: |M| PictureID | (OPTIONAL)
+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
L: | TL0PICIDX | (OPTIONAL) | PictureID |
+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
T/K:|TID|Y| KEYIDX | (OPTIONAL) L: | TL0PICIDX | (OPTIONAL)
+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
T/K:|TID|Y| KEYIDX | (OPTIONAL)
+-+-+-+-+-+-+-+-+
*/
type VP8Helper struct {
TemporalSupported bool
// Optional Header
PictureID uint16 /* 8 or 16 bits, picture ID */
picIDIdx uint8
mBit bool
TL0PICIDX uint8 /* 8 bits temporal level zero index */
tlzIdx uint8
// Optional Header If either of the T or K bits are set to 1,
// the TID/Y/KEYIDX extension field MUST be present.
TID uint8 /* 2 bits temporal layer idx*/
// IsKeyFrame is a helper to detect if current packet is a keyframe
IsKeyFrame bool
}
// Unmarshal parses the passed byte slice and stores the result in the VP8Helper this method is called upon
func (p *VP8Helper) Unmarshal(payload []byte) error {
if payload == nil {
return errNilPacket
}
payloadLen := len(payload)
if payloadLen < 4 {
return errShortPacket
}
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 {
idx++
p.picIDIdx = idx
pid := payload[idx] & 0x7f
// Check if m is 1, then Picture ID is 15 bits
if payload[idx]&0x80 > 0 {
idx++
p.mBit = true
p.PictureID = binary.BigEndian.Uint16([]byte{pid, payload[idx]})
} else {
p.PictureID = uint16(pid)
}
}
// Check if TL0PICIDX is present
if L {
idx++
p.tlzIdx = idx
p.TL0PICIDX = payload[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 && 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 timeToNtp(ns int64) uint64 {
seconds := uint64(ns/1e9 + ntpEpoch)
fraction := uint64(((ns % 1e9) << 32) / 1e9)
return seconds<<32 | fraction
}
// 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
}
-49
View File
@@ -1,49 +0,0 @@
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
}