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
+3 -1
View File
@@ -21,7 +21,7 @@ require (
github.com/pion/rtp v1.6.2
github.com/pion/stun v0.3.5
github.com/pion/transport v0.12.2
github.com/pion/webrtc/v3 v3.0.4
github.com/pion/webrtc/v3 v3.0.5
github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.7.0
github.com/thoas/go-funk v0.7.0
@@ -35,3 +35,5 @@ require (
gopkg.in/square/go-jose.v2 v2.5.1
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776
)
replace github.com/pion/ion-sfu => github.com/davidzhao/ion-sfu v1.8.3-0.20210205014052-b5e378606cec
+14
View File
@@ -38,6 +38,7 @@ github.com/aws/aws-sdk-go v1.27.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN
github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bep/debounce v1.2.0 h1:wXds8Kq8qRfwAOpAxHrJDbCXgC5aHSzgQb/0gKsHQqo=
github.com/bep/debounce v1.2.0/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0=
@@ -70,6 +71,10 @@ github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7Do
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davidzhao/ion-sfu v1.8.3-0.20210205010743-13f2b5e71196 h1:lYSupwHjpNUtXO3GEHjhX9S1F3efREDs4FpTAjf+Frc=
github.com/davidzhao/ion-sfu v1.8.3-0.20210205010743-13f2b5e71196/go.mod h1:MKDh4JSLpBA/hFeYAYALb6nYpe6Ruknd3pmxPMbdpM8=
github.com/davidzhao/ion-sfu v1.8.3-0.20210205014052-b5e378606cec h1:HjyyD0TXuCVheKu7HyWdye3jQ2/+dE/f2q7I+u3X2oA=
github.com/davidzhao/ion-sfu v1.8.3-0.20210205014052-b5e378606cec/go.mod h1:MKDh4JSLpBA/hFeYAYALb6nYpe6Ruknd3pmxPMbdpM8=
github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
@@ -235,6 +240,7 @@ github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-b
github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4=
github.com/lithammer/shortuuid/v3 v3.0.4 h1:uj4xhotfY92Y1Oa6n6HUiFn87CdoEHYUlTy0+IgbLrs=
github.com/lithammer/shortuuid/v3 v3.0.4/go.mod h1:RviRjexKqIzx/7r1peoAITm6m7gnif/h+0zmolKJjzw=
github.com/lucsky/cuid v1.0.2 h1:z4XlExeoderxoPj2/dxKOyPxe9RCOu7yNq9/XWxIUMQ=
github.com/lucsky/cuid v1.0.2/go.mod h1:QaaJqckboimOmhRSJXSx/+IT+VTfxfPGSo/6mfgUfmE=
github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ=
github.com/lytics/base62 v0.0.0-20180808010106-0ee4de5a5d6d h1:HONlVR8gkr5QibYNVFtj8ajfqRAKt21DmdzeZXZl6VQ=
@@ -249,6 +255,7 @@ github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNx
github.com/mattn/go-isatty v0.0.4 h1:bnP0vzxcAdeI1zdubAl5PjU6zsERjGZb7raWodagDYs=
github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/maxbrunsfeld/counterfeiter/v6 v6.3.0 h1:8E6DrFvII6QR4eJ3PkFvV+lc03P+2qwqTPLm1ax7694=
github.com/maxbrunsfeld/counterfeiter/v6 v6.3.0/go.mod h1:fcEyUyXZXoV4Abw8DX0t7wyL8mCDxXyU4iAFZfT3IHw=
@@ -362,6 +369,8 @@ github.com/pion/udp v0.1.0 h1:uGxQsNyrqG3GLINv36Ff60covYmfrLoxzwnCsIYspXI=
github.com/pion/udp v0.1.0/go.mod h1:BPELIjbwE9PRbd/zxI/KYBnbo7B6+oA6YuEaNE8lths=
github.com/pion/webrtc/v3 v3.0.4 h1:Tiw3H9fpfcwkvaxonB+Gv1DG9tmgYBQaM1vBagDHP40=
github.com/pion/webrtc/v3 v3.0.4/go.mod h1:1TmFSLpPYFTFXFHPtoq9eGP1ASTa9LC6FBh7sUY8cd4=
github.com/pion/webrtc/v3 v3.0.5 h1:utennp7RwX+2mtyMzoOXE03IUIckiHBigjarRJZ2DqY=
github.com/pion/webrtc/v3 v3.0.5/go.mod h1:/EDCREM8y+JrJSkoCRHpoz//qtuBCOYV4E96vEK3bz0=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
@@ -376,12 +385,14 @@ github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDf
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og=
github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M=
github.com/prometheus/client_golang v1.9.0 h1:Rrch9mh17XcxvEu9D9DEpb4isxjGBtcevQjKvxPRQIU=
github.com/prometheus/client_golang v1.9.0/go.mod h1:FqZLKOZnGdFAhOK4nqGHa7D66IdsO+O441Eve7ptJDU=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/client_model v0.1.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M=
github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
@@ -397,6 +408,7 @@ github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7z
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A=
github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
github.com/prometheus/procfs v0.2.0 h1:wH4vA7pcjKuZzjF7lM8awk4fnuJO6idemZXoKnULUx4=
github.com/prometheus/procfs v0.2.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
@@ -555,6 +567,8 @@ golang.org/x/net v0.0.0-20201201195509-5d6afe98e0b7/go.mod h1:sp8m0HH+o8qH0wwXwY
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20201224014010-6772e930b67b h1:iFwSg7t5GZmB/Q5TjiEAsdoLDrdJRC1RiF2WhuV29Qw=
golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210119194325-5f4716e94777 h1:003p0dJM77cxMSyCPFphvZf/Y5/NXf5fzg6ufd1/Oew=
golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
+4
View File
@@ -80,6 +80,10 @@ func (t *DataTrack) IsMuted() bool {
return false
}
func (t *DataTrack) SetMuted(muted bool) {
}
func (t *DataTrack) OnClose(f func()) {
t.onClose = f
}
+123 -182
View File
@@ -1,20 +1,18 @@
package rtc
import (
"io"
"sync"
"time"
"github.com/gammazero/workerpool"
"github.com/pion/ion-sfu/pkg/buffer"
"github.com/pion/ion-sfu/pkg/sfu"
"github.com/pion/ion-sfu/pkg/twcc"
"github.com/pion/rtcp"
"github.com/pion/transport/packetio"
"github.com/pion/webrtc/v3"
"github.com/pion/webrtc/v3/pkg/rtcerr"
"github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
)
@@ -40,21 +38,21 @@ type MediaTrack struct {
streamID string
kind livekit.TrackType
codec webrtc.RTPCodecParameters
conf ReceiverConfig
onClose func()
// channel to send RTCP packets to the source
rtcpCh *utils.CalmChannel
rtcpCh chan []rtcp.Packet
lock sync.RWMutex
once sync.Once
// map of target participantId -> DownTrack
downtracks map[string]types.DownTrack
receiver types.Receiver
nackWorker *workerpool.WorkerPool
downtracks map[string]*sfu.DownTrack
twcc *twcc.Responder
receiver sfu.Receiver
//lastNack int64
lastPLI time.Time
}
func NewMediaTrack(trackId string, pId string, rtcpCh *utils.CalmChannel, track *webrtc.TrackRemote, receiver types.Receiver) *MediaTrack {
func NewMediaTrack(trackId string, pId string, rtcpCh chan []rtcp.Packet, conf ReceiverConfig, track *webrtc.TrackRemote) *MediaTrack {
t := &MediaTrack{
id: trackId,
participantId: pId,
@@ -62,22 +60,16 @@ func NewMediaTrack(trackId string, pId string, rtcpCh *utils.CalmChannel, track
streamID: track.StreamID(),
kind: ToProtoTrackKind(track.Kind()),
codec: track.Codec(),
conf: conf,
rtcpCh: rtcpCh,
lock: sync.RWMutex{},
once: sync.Once{},
downtracks: make(map[string]types.DownTrack),
receiver: receiver,
nackWorker: workerpool.New(1),
downtracks: make(map[string]*sfu.DownTrack),
}
return t
}
func (t *MediaTrack) Start() {
t.once.Do(func() {
// start worker
go t.forwardRTPWorker()
})
}
func (t *MediaTrack) ID() string {
@@ -96,6 +88,18 @@ func (t *MediaTrack) IsMuted() bool {
return t.muted.Get()
}
func (t *MediaTrack) SetMuted(muted bool) {
if !t.muted.TrySet(muted) {
return
}
// mute all of the downtracks
t.lock.RLock()
for _, dt := range t.downtracks {
dt.Mute(muted)
}
t.lock.RUnlock()
}
func (t *MediaTrack) OnClose(f func()) {
t.onClose = f
}
@@ -116,80 +120,142 @@ func (t *MediaTrack) AddSubscriber(participant types.Participant) error {
}
codec := t.codec
// pack ID to identify all publishedTracks
packedId := PackTrackId(t.participantId, t.id)
// using DownTrack from ion-sfu
outTrack, err := sfu.NewDownTrack(webrtc.RTPCodecCapability{
downTrack, err := sfu.NewDownTrack(webrtc.RTPCodecCapability{
MimeType: codec.MimeType,
ClockRate: codec.ClockRate,
Channels: codec.Channels,
SDPFmtpLine: codec.SDPFmtpLine,
RTCPFeedback: feedbackTypes,
}, packedId, t.streamID)
}, t.receiver, t.participantId)
if err != nil {
return err
}
transceiver, err := participant.PeerConnection().AddTransceiverFromTrack(outTrack, webrtc.RTPTransceiverInit{
transceiver, err := participant.PeerConnection().AddTransceiverFromTrack(downTrack, webrtc.RTPTransceiverInit{
Direction: webrtc.RTPTransceiverDirectionSendrecv,
})
if err != nil {
return err
}
outTrack.SetTransceiver(transceiver)
downTrack.SetTransceiver(transceiver)
// when outtrack is bound, start loop to send reports
outTrack.OnBind(func() {
if rr := bufferFactory.GetOrNew(packetio.RTCPBufferPacket, outTrack.SSRC()).(*buffer.RTCPReader); rr != nil {
rr.OnPacket(func(pkt []byte) {
t.handleRTCP(outTrack, participant.Identity(), pkt)
})
}
downTrack.OnBind(func() {
t.sendDownTrackBindingReports(participant.ID(), participant.RTCPChan())
})
outTrack.OnCloseHandler(func() {
downTrack.OnCloseHandler(func() {
t.lock.Lock()
delete(t.downtracks, participant.ID())
t.lock.Unlock()
// ignore if the subscribing participant is not connected
if participant.PeerConnection().ConnectionState() != webrtc.PeerConnectionStateConnected {
if participant.PeerConnection().ConnectionState() == webrtc.PeerConnectionStateClosed {
return
}
// if the source has been terminated, we'll need to terminate all of the downtracks
// however, if the dest participant has disconnected, then we can skip
sender := transceiver.Sender()
if sender != nil {
logger.Debugw("removing peerconnection track",
"track", t.id,
"participantId", t.participantId,
"destParticipant", participant.Identity())
if err := participant.PeerConnection().RemoveTrack(sender); err != nil {
if err == webrtc.ErrConnectionClosed {
// participant closing, can skip removing downtracks
return
}
if _, ok := err.(*rtcerr.InvalidStateError); !ok {
logger.Warnw("could not remove remoteTrack from forwarder",
"participant", participant.Identity(),
"err", err)
}
if sender == nil {
return
}
logger.Debugw("removing peerconnection track",
"track", t.id,
"participantId", t.participantId,
"destParticipant", participant.Identity())
if err := participant.PeerConnection().RemoveTrack(sender); err != nil {
if err == webrtc.ErrConnectionClosed {
// participant closing, can skip removing downtracks
return
}
if _, ok := err.(*rtcerr.InvalidStateError); !ok {
logger.Warnw("could not remove remoteTrack from forwarder",
"participant", participant.Identity(),
"err", err)
}
}
participant.RemoveDownTrack(t.streamID, outTrack)
participant.RemoveDownTrack(t.streamID, downTrack)
})
participant.AddDownTrack(t.streamID, outTrack)
t.lock.Lock()
defer t.lock.Unlock()
t.downtracks[participant.ID()] = outTrack
downTrack.Mute(t.muted.Get())
t.downtracks[participant.ID()] = downTrack
t.lock.Unlock()
participant.AddDownTrack(t.streamID, downTrack)
t.receiver.AddDownTrack(downTrack, true)
return nil
}
// adds a new RTP receiver to the track, returns true if this is a new track
func (t *MediaTrack) AddReceiver(receiver *webrtc.RTPReceiver, track *webrtc.TrackRemote) {
//rid := track.RID()
buff, rtcpReader := bufferFactory.GetBufferPair(uint32(track.SSRC()))
buff.OnFeedback(func(fb []rtcp.Packet) {
t.rtcpCh <- fb
})
if t.Kind() == livekit.TrackType_AUDIO {
// TODO: audio level stuff
} else if t.Kind() == livekit.TrackType_VIDEO {
if t.twcc == nil {
t.twcc = twcc.NewTransportWideCCResponder(uint32(track.SSRC()))
t.twcc.OnFeedback(func(p rtcp.RawPacket) {
t.rtcpCh <- []rtcp.Packet{&p}
})
}
buff.OnTransportWideCC(func(sn uint16, timeNS int64, marker bool) {
t.twcc.Push(sn, timeNS, marker)
})
}
rtcpReader.OnPacket(func(bytes []byte) {
pkts, err := rtcp.Unmarshal(bytes)
if err != nil {
logger.Errorw("could not unmarshal RTCP", "error", err)
return
}
for _, pkt := range pkts {
switch pkt := pkt.(type) {
case *rtcp.SourceDescription:
// do nothing for now
case *rtcp.SenderReport:
buff.SetSenderReportData(pkt.RTPTime, pkt.NTPTime)
}
}
})
if t.receiver == nil {
// pack ID to identify all publishedTracks
packedId := PackTrackId(t.participantId, track.ID())
t.lock.Lock()
t.receiver = NewWrappedReceiver(sfu.NewWebRTCReceiver(receiver, track, t.participantId), packedId)
t.lock.Unlock()
t.receiver.SetRTCPCh(t.rtcpCh)
t.receiver.OnCloseHandler(func() {
// source track closed
if t.Kind() == livekit.TrackType_AUDIO {
// TODO: remove audio level observer
}
t.lock.Lock()
t.receiver = nil
t.lock.Unlock()
})
}
t.receiver.AddUpTrack(track, buff)
buff.Bind(receiver.GetParameters(), buffer.Options{
BufferTime: t.conf.maxBufferTime,
MaxBitRate: t.conf.maxBitrate,
})
}
// removes peer from subscription
// stop all forwarders to the peer
func (t *MediaTrack) RemoveSubscriber(participantId string) {
@@ -208,19 +274,20 @@ func (t *MediaTrack) RemoveAllSubscribers() {
for _, dt := range t.downtracks {
go dt.Close()
}
t.downtracks = make(map[string]types.DownTrack)
t.downtracks = make(map[string]*sfu.DownTrack)
}
func (t *MediaTrack) sendDownTrackBindingReports(participantId string, rtcpCh *utils.CalmChannel) {
func (t *MediaTrack) sendDownTrackBindingReports(participantId string, rtcpCh chan []rtcp.Packet) {
var sd []rtcp.SourceDescriptionChunk
t.lock.RLock()
dt := t.downtracks[participantId]
t.lock.RUnlock()
if !dt.IsBound() {
chunks := dt.CreateSourceDescriptionChunks()
if chunks == nil {
return
}
chunks := dt.CreateSourceDescriptionChunks()
if chunks != nil {
sd = append(sd, chunks...)
}
@@ -234,7 +301,7 @@ func (t *MediaTrack) sendDownTrackBindingReports(participantId string, rtcpCh *u
batch := pkts
i := 0
for {
rtcpCh.Write(batch)
rtcpCh <- batch
if i > 5 {
return
}
@@ -243,129 +310,3 @@ func (t *MediaTrack) sendDownTrackBindingReports(participantId string, rtcpCh *u
}
}()
}
// b reads from the receiver and writes to each sender
func (t *MediaTrack) forwardRTPWorker() {
defer Recover()
defer func() {
t.RemoveAllSubscribers()
// TODO: send unpublished events?
t.nackWorker.Stop()
if t.onClose != nil {
t.onClose()
}
}()
for pkt := range t.receiver.RTPChan() {
//logger.Debugw("read packet from remoteTrack",
// "participant", t.participantId,
// "track", t.ID())
// when track is muted, it's "disabled" on the client side, and will still be sending black frames
// when our metadata is updated as such, we shortcircuit forwarding of black frames
if t.muted.Get() {
continue
}
t.lock.RLock()
for dstId, dt := range t.downtracks {
//logger.Debugw("read packet from remoteTrack",
// "srcParticipant", t.participantId,
// "destParticipant", dstId,
// "track", t.ID())
err := dt.WriteRTP(pkt.Packet)
if IsEOF(err) {
// this participant unsubscribed, remove it
t.RemoveSubscriber(dstId)
continue
}
if err == sfu.ErrRequiresKeyFrame {
delta := time.Now().Sub(t.lastPLI)
if delta < maxPLIFrequency {
continue
}
logger.Infow("keyframe required, sending PLI",
"srcParticipant", t.participantId)
rtcpPkts := []rtcp.Packet{
&rtcp.PictureLossIndication{SenderSSRC: uint32(t.ssrc), MediaSSRC: pkt.Packet.SSRC},
}
t.rtcpCh.Write(rtcpPkts)
t.lastPLI = time.Now()
} else if err != nil {
logger.Warnw("could not forward packet to participant",
"src", t.participantId,
"dest", dstId,
"remoteTrack", t.id,
"err", err)
}
}
t.lock.RUnlock()
}
}
func (t *MediaTrack) handleRTCP(dt *sfu.DownTrack, identity string, rtcpBuf []byte) {
defer Recover()
pkts, err := rtcp.Unmarshal(rtcpBuf)
if err != nil {
logger.Warnw("could not decode RTCP packet", "err", err)
}
var fwdPkts []rtcp.Packet
// sufficient to send this only once
pliOnce := true
firOnce := true
for _, pkt := range pkts {
switch p := pkt.(type) {
case *rtcp.PictureLossIndication:
if pliOnce {
p.MediaSSRC = dt.LastSSRC()
p.SenderSSRC = dt.SSRC()
fwdPkts = append(fwdPkts, p)
pliOnce = false
}
case *rtcp.FullIntraRequest:
if firOnce {
p.MediaSSRC = dt.LastSSRC()
p.SenderSSRC = dt.SSRC()
fwdPkts = append(fwdPkts, p)
firOnce = false
}
case *rtcp.ReceiverReport:
if len(p.Reports) > 0 && p.Reports[0].FractionLost > 25 {
//log.Tracef("Slow link for sender %s, fraction packet lost %.2f", f.track.peerID, float64(p.Reports[0].FractionLost)/256)
}
case *rtcp.TransportLayerNack:
logger.Debugw("forwarder got nack",
"participant", identity,
"packet", p)
var nackedPackets []uint16
for _, pair := range p.Nacks {
nackedPackets = append(nackedPackets, dt.GetNACKSeqNo(pair.PacketList())...)
}
if t.nackWorker.Stopped() {
return
}
t.nackWorker.Submit(func() {
pktBuf := packetFactory.Get().([]byte)
for _, sn := range nackedPackets {
pkt, err := t.receiver.GetBufferedPacket(pktBuf, sn, dt.SnOffset())
if err == io.EOF {
break
} else if err != nil {
logger.Warnw("error getting buffered packet", "error", err)
continue
}
// what about handling write errors such as no packet found
dt.WriteRTP(pkt)
}
packetFactory.Put(pktBuf)
})
}
}
if len(fwdPkts) > 0 {
t.rtcpCh.Write(fwdPkts)
}
}
-112
View File
@@ -1,112 +0,0 @@
package rtc
import (
"sync"
"testing"
"time"
"github.com/gammazero/workerpool"
"github.com/pion/ion-sfu/pkg/buffer"
"github.com/pion/rtcp"
"github.com/pion/webrtc/v3"
"github.com/stretchr/testify/assert"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/rtc/types/typesfakes"
"github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
)
const (
testWaitDuration = 10 * time.Millisecond
)
func TestForwardRTP(t *testing.T) {
t.Run("ensure that forwarders are getting packets", func(t *testing.T) {
mt := newMediaTrackWithReceiver()
receiver := mt.receiver.(*typesfakes.FakeReceiver)
packet := buffer.ExtPacket{}
receiver.RTPChanReturns(packetGenerator(packet))
dt := &typesfakes.FakeDownTrack{}
mt.downtracks["test"] = dt
mt.Start()
time.Sleep(testWaitDuration)
assert.Equal(t, 1, dt.WriteRTPCallCount(), "WriteRTP wasn't called on Forwarder")
assert.EqualValues(t, packet.Packet, dt.WriteRTPArgsForCall(0))
})
t.Run("muted tracks do not forward data", func(t *testing.T) {
mt := newMediaTrackWithReceiver()
mt.muted.TrySet(true)
dt := &typesfakes.FakeDownTrack{}
mt.downtracks["test"] = dt
mt.Start()
time.Sleep(testWaitDuration)
assert.Zero(t, dt.WriteRTPCallCount())
})
}
func TestMissingKeyFrames(t *testing.T) {
t.Run("PLI packet is sent when forwarder misses keyframe", func(t *testing.T) {
mt := newMediaTrackWithReceiver()
dt := &typesfakes.FakeDownTrack{}
mt.downtracks["test"] = dt
dt.WriteRTPReturns(sfu.ErrRequiresKeyFrame)
mt.Start()
time.Sleep(testWaitDuration)
select {
case o := <-mt.rtcpCh.ReadChan():
if o == nil {
return
}
pkts, ok := o.([]rtcp.Packet)
assert.True(t, ok)
assert.Len(t, pkts, 1, "a single RTCP packet should be returned")
assert.IsType(t, &rtcp.PictureLossIndication{}, pkts[0])
default:
t.Fatalf("did not receive RTCP packets")
}
})
}
// returns a receiver that reads a packet then returns EOF
func newMediaTrackWithReceiver() *MediaTrack {
packet := buffer.ExtPacket{}
receiver := &typesfakes.FakeReceiver{
RTPChanStub: func() <-chan buffer.ExtPacket {
return packetGenerator(packet)
},
}
return &MediaTrack{
id: utils.NewGuid(utils.TrackPrefix),
participantId: "PAtest",
kind: livekit.TrackType_VIDEO,
codec: webrtc.RTPCodecParameters{},
rtcpCh: utils.NewCalmChannel(5),
lock: sync.RWMutex{},
once: sync.Once{},
downtracks: map[string]types.DownTrack{},
receiver: receiver,
nackWorker: workerpool.New(1),
}
}
func packetGenerator(packets ...buffer.ExtPacket) <-chan buffer.ExtPacket {
pc := make(chan buffer.ExtPacket)
go func() {
defer close(pc)
for _, p := range packets {
pc <- p
}
}()
return pc
}
+32 -20
View File
@@ -7,6 +7,7 @@ import (
"time"
"github.com/bep/debounce"
"github.com/pion/ion-sfu/pkg/sfu"
"github.com/pion/rtcp"
"github.com/pion/webrtc/v3"
"github.com/pkg/errors"
@@ -15,7 +16,6 @@ import (
"github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
)
@@ -41,7 +41,7 @@ type ParticipantImpl struct {
mediaEngine *webrtc.MediaEngine
identity string
state atomic.Value // livekit.ParticipantInfo_State
rtcpCh *utils.CalmChannel
rtcpCh chan []rtcp.Packet
subscribedTracks map[string][]*sfu.DownTrack
// publishedTracks that participant is publishing
publishedTracks map[string]types.PublishedTrack
@@ -85,7 +85,7 @@ func NewParticipant(identity string, pc types.PeerConnection, rs routing.Message
peerConn: pc,
responseSink: rs,
receiverConfig: receiverConfig,
rtcpCh: utils.NewCalmChannel(50),
rtcpCh: make(chan []rtcp.Packet, 50),
subscribedTracks: make(map[string][]*sfu.DownTrack),
lock: sync.RWMutex{},
negotiationCond: sync.NewCond(&sync.Mutex{}),
@@ -162,7 +162,7 @@ func (p *ParticipantImpl) IsReady() bool {
return state == livekit.ParticipantInfo_JOINED || state == livekit.ParticipantInfo_ACTIVE
}
func (p *ParticipantImpl) RTCPChan() *utils.CalmChannel {
func (p *ParticipantImpl) RTCPChan() chan []rtcp.Packet {
return p.rtcpCh
}
@@ -361,7 +361,7 @@ func (p *ParticipantImpl) Close() error {
p.onClose(p)
}
p.peerConn.Close()
p.rtcpCh.Close()
close(p.rtcpCh)
return nil
}
@@ -538,11 +538,28 @@ func (p *ParticipantImpl) onMediaTrack(track *webrtc.TrackRemote, rtpReceiver *w
}
// create ReceiverImpl
receiver := NewReceiver(p.rtcpCh, rtpReceiver, track, p.receiverConfig)
mt := NewMediaTrack(ti.Sid, p.id, p.rtcpCh, track, receiver)
mt.name = ti.Name
//receiver := NewReceiver(p.rtcpCh, rtpReceiver, track, p.receiverConfig)
p.handleTrackPublished(mt)
// use existing mediatrack to handle simulcast
p.lock.RLock()
ptrack := p.publishedTracks[ti.Sid]
p.lock.RUnlock()
var mt *MediaTrack
var newTrack bool
if trk, ok := ptrack.(*MediaTrack); ok {
mt = trk
} else {
mt = NewMediaTrack(ti.Sid, p.id, p.rtcpCh, p.receiverConfig, track)
mt.name = ti.Name
newTrack = true
}
mt.AddReceiver(rtpReceiver, track)
if newTrack {
p.handleTrackPublished(mt)
}
}
func (p *ParticipantImpl) onDataChannel(dc *webrtc.DataChannel) {
@@ -625,14 +642,13 @@ func (p *ParticipantImpl) downTracksRTCPWorker() {
p.lock.RLock()
for _, dts := range p.subscribedTracks {
for _, dt := range dts {
if !dt.IsBound() {
sr := dt.CreateSenderReport()
chunks := dt.CreateSourceDescriptionChunks()
if sr == nil || chunks == nil {
continue
}
pkts = append(pkts, dt.CreateSenderReport())
chunks := dt.CreateSourceDescriptionChunks()
if chunks != nil {
sd = append(sd, chunks...)
}
sd = append(sd, chunks...)
}
}
p.lock.RUnlock()
@@ -664,14 +680,10 @@ func (p *ParticipantImpl) downTracksRTCPWorker() {
func (p *ParticipantImpl) rtcpSendWorker() {
defer Recover()
// read from rtcpChan
for o := range p.rtcpCh.ReadChan() {
if o == nil {
for pkts := range p.rtcpCh {
if pkts == nil {
return
}
pkts, ok := o.([]rtcp.Packet)
if !ok {
logger.Errorw("unexpected obj from rtcpCh", "object", o)
}
//for _, pkt := range pkts {
// logger.Debugw("writing RTCP", "packet", pkt)
//}
+3 -3
View File
@@ -4,13 +4,12 @@ import (
"time"
"github.com/pion/ion-sfu/pkg/buffer"
"github.com/pion/ion-sfu/pkg/sfu"
"github.com/pion/rtcp"
"github.com/pion/rtp"
"github.com/pion/webrtc/v3"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
)
@@ -54,7 +53,7 @@ type Participant interface {
State() livekit.ParticipantInfo_State
IsReady() bool
ToProto() *livekit.ParticipantInfo
RTCPChan() *utils.CalmChannel
RTCPChan() chan []rtcp.Packet
GetResponseSink() routing.MessageSink
SetResponseSink(sink routing.MessageSink)
@@ -97,6 +96,7 @@ type PublishedTrack interface {
Kind() livekit.TrackType
Name() string
IsMuted() bool
SetMuted(muted bool)
AddSubscriber(participant Participant) error
RemoveSubscriber(participantId string)
RemoveAllSubscribers()
+12 -12
View File
@@ -6,9 +6,9 @@ import (
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
"github.com/pion/ion-sfu/pkg/sfu"
"github.com/pion/rtcp"
webrtc "github.com/pion/webrtc/v3"
)
@@ -161,15 +161,15 @@ type FakeParticipant struct {
peerConnectionReturnsOnCall map[int]struct {
result1 types.PeerConnection
}
RTCPChanStub func() *utils.CalmChannel
RTCPChanStub func() chan []rtcp.Packet
rTCPChanMutex sync.RWMutex
rTCPChanArgsForCall []struct {
}
rTCPChanReturns struct {
result1 *utils.CalmChannel
result1 chan []rtcp.Packet
}
rTCPChanReturnsOnCall map[int]struct {
result1 *utils.CalmChannel
result1 chan []rtcp.Packet
}
RemoveDownTrackStub func(string, *sfu.DownTrack)
removeDownTrackMutex sync.RWMutex
@@ -1060,7 +1060,7 @@ func (fake *FakeParticipant) PeerConnectionReturnsOnCall(i int, result1 types.Pe
}{result1}
}
func (fake *FakeParticipant) RTCPChan() *utils.CalmChannel {
func (fake *FakeParticipant) RTCPChan() chan []rtcp.Packet {
fake.rTCPChanMutex.Lock()
ret, specificReturn := fake.rTCPChanReturnsOnCall[len(fake.rTCPChanArgsForCall)]
fake.rTCPChanArgsForCall = append(fake.rTCPChanArgsForCall, struct {
@@ -1084,32 +1084,32 @@ func (fake *FakeParticipant) RTCPChanCallCount() int {
return len(fake.rTCPChanArgsForCall)
}
func (fake *FakeParticipant) RTCPChanCalls(stub func() *utils.CalmChannel) {
func (fake *FakeParticipant) RTCPChanCalls(stub func() chan []rtcp.Packet) {
fake.rTCPChanMutex.Lock()
defer fake.rTCPChanMutex.Unlock()
fake.RTCPChanStub = stub
}
func (fake *FakeParticipant) RTCPChanReturns(result1 *utils.CalmChannel) {
func (fake *FakeParticipant) RTCPChanReturns(result1 chan []rtcp.Packet) {
fake.rTCPChanMutex.Lock()
defer fake.rTCPChanMutex.Unlock()
fake.RTCPChanStub = nil
fake.rTCPChanReturns = struct {
result1 *utils.CalmChannel
result1 chan []rtcp.Packet
}{result1}
}
func (fake *FakeParticipant) RTCPChanReturnsOnCall(i int, result1 *utils.CalmChannel) {
func (fake *FakeParticipant) RTCPChanReturnsOnCall(i int, result1 chan []rtcp.Packet) {
fake.rTCPChanMutex.Lock()
defer fake.rTCPChanMutex.Unlock()
fake.RTCPChanStub = nil
if fake.rTCPChanReturnsOnCall == nil {
fake.rTCPChanReturnsOnCall = make(map[int]struct {
result1 *utils.CalmChannel
result1 chan []rtcp.Packet
})
}
fake.rTCPChanReturnsOnCall[i] = struct {
result1 *utils.CalmChannel
result1 chan []rtcp.Packet
}{result1}
}
@@ -74,6 +74,11 @@ type FakePublishedTrack struct {
removeSubscriberArgsForCall []struct {
arg1 string
}
SetMutedStub func(bool)
setMutedMutex sync.RWMutex
setMutedArgsForCall []struct {
arg1 bool
}
StartStub func()
startMutex sync.RWMutex
startArgsForCall []struct {
@@ -443,6 +448,38 @@ func (fake *FakePublishedTrack) RemoveSubscriberArgsForCall(i int) string {
return argsForCall.arg1
}
func (fake *FakePublishedTrack) SetMuted(arg1 bool) {
fake.setMutedMutex.Lock()
fake.setMutedArgsForCall = append(fake.setMutedArgsForCall, struct {
arg1 bool
}{arg1})
stub := fake.SetMutedStub
fake.recordInvocation("SetMuted", []interface{}{arg1})
fake.setMutedMutex.Unlock()
if stub != nil {
fake.SetMutedStub(arg1)
}
}
func (fake *FakePublishedTrack) SetMutedCallCount() int {
fake.setMutedMutex.RLock()
defer fake.setMutedMutex.RUnlock()
return len(fake.setMutedArgsForCall)
}
func (fake *FakePublishedTrack) SetMutedCalls(stub func(bool)) {
fake.setMutedMutex.Lock()
defer fake.setMutedMutex.Unlock()
fake.SetMutedStub = stub
}
func (fake *FakePublishedTrack) SetMutedArgsForCall(i int) bool {
fake.setMutedMutex.RLock()
defer fake.setMutedMutex.RUnlock()
argsForCall := fake.setMutedArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakePublishedTrack) Start() {
fake.startMutex.Lock()
fake.startArgsForCall = append(fake.startArgsForCall, struct {
@@ -486,6 +523,8 @@ func (fake *FakePublishedTrack) Invocations() map[string][][]interface{} {
defer fake.removeAllSubscribersMutex.RUnlock()
fake.removeSubscriberMutex.RLock()
defer fake.removeSubscriberMutex.RUnlock()
fake.setMutedMutex.RLock()
defer fake.setMutedMutex.RUnlock()
fake.startMutex.RLock()
defer fake.startMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
+23
View File
@@ -0,0 +1,23 @@
package rtc
import (
"github.com/pion/ion-sfu/pkg/sfu"
)
// wrapper around WebRTC receiver, overriding its ID
type WrappedReceiver struct {
sfu.Receiver
trackId string
}
func NewWrappedReceiver(receiver sfu.Receiver, trackId string) WrappedReceiver {
return WrappedReceiver{
Receiver: receiver,
trackId: trackId,
}
}
func (r WrappedReceiver) TrackID() string {
return r.trackId
}
-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
}