binding to buffer and correctly forwarding

This commit is contained in:
David Zhao
2021-01-10 16:18:58 -08:00
parent 258f5add2d
commit 7dcb88343a
18 changed files with 751 additions and 338 deletions
+1 -1
View File
@@ -55,7 +55,7 @@ func (t *AccessToken) ToJWT() (string, error) {
validFor := defaultValidDuration
if t.validFor > 0 {
t.validFor = validFor
validFor = t.validFor
}
cl := jwt.Claims{
+1 -1
View File
@@ -21,7 +21,7 @@ type RTCConfig struct {
StunServers []string `yaml:"stun_servers"`
UseExternalIP bool `yaml:"use_external_ip"`
MaxBandwidth uint64 `yaml:"max_bandwidth"`
MaxBitrate uint64 `yaml:"max_bandwidth"`
MaxBufferTime int `yaml:"max_buffer_time"`
}
+4 -5
View File
@@ -11,12 +11,11 @@ import (
type WebRTCConfig struct {
Configuration webrtc.Configuration
SettingEngine webrtc.SettingEngine
receiver ReceiverConfig
Receiver ReceiverConfig
}
type ReceiverConfig struct {
maxBandwidth uint64
maxBitrate uint64
maxBufferTime int
}
@@ -48,8 +47,8 @@ func NewWebRTCConfig(conf *config.RTCConfig, externalIP string) (*WebRTCConfig,
return &WebRTCConfig{
Configuration: c,
SettingEngine: s,
receiver: ReceiverConfig{
maxBandwidth: conf.MaxBandwidth,
Receiver: ReceiverConfig{
maxBitrate: conf.MaxBitrate,
maxBufferTime: conf.MaxBufferTime,
},
}, nil
+2 -3
View File
@@ -7,7 +7,6 @@ import (
"github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
)
@@ -30,10 +29,10 @@ type DataTrack struct {
subscribers map[string]*DownDataChannel
}
func NewDataTrack(participantId string, dc *webrtc.DataChannel) *DataTrack {
func NewDataTrack(trackId, participantId string, dc *webrtc.DataChannel) *DataTrack {
t := &DataTrack{
//ctx: context.Background(),
id: utils.NewGuid(utils.TrackPrefix),
id: trackId,
name: dc.Label(),
participantId: participantId,
dataChannel: dc,
+6 -5
View File
@@ -3,9 +3,10 @@ package rtc
import "errors"
var (
ErrRoomIdMissing = errors.New("room is not passed in")
ErrInvalidRoomName = errors.New("room must have a unique name")
ErrRoomNotFound = errors.New("requested room does not exist")
ErrPermissionDenied = errors.New("no permissions to access the room")
ErrUnexpectedOffer = errors.New("expected answer SDP, received offer")
ErrRoomIdMissing = errors.New("room is not passed in")
ErrInvalidRoomName = errors.New("room must have a unique name")
ErrRoomNotFound = errors.New("requested room does not exist")
ErrPermissionDenied = errors.New("no permissions to access the room")
ErrUnexpectedOffer = errors.New("expected answer SDP, received offer")
ErrUnexpectedNegotiation = errors.New("client negotiation has not been granted")
)
+50 -8
View File
@@ -16,7 +16,6 @@ import (
"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"
)
@@ -54,10 +53,10 @@ type MediaTrack struct {
lastPLI time.Time
}
func NewMediaTrack(pId string, rtcpCh chan []rtcp.Packet, track *webrtc.TrackRemote, receiver types.Receiver) *MediaTrack {
func NewMediaTrack(trackId string, pId string, rtcpCh chan []rtcp.Packet, track *webrtc.TrackRemote, receiver types.Receiver) *MediaTrack {
t := &MediaTrack{
ctx: context.Background(),
id: utils.NewGuid(utils.TrackPrefix),
id: trackId,
participantId: pId,
ssrc: track.SSRC(),
name: track.StreamID(),
@@ -135,7 +134,7 @@ func (t *MediaTrack) AddSubscriber(participant types.Participant) error {
t.handleRTCP(outTrack, pkt)
})
}
//go sub.sendStreamDownTracksReports(recv.Name())
//go t.scheduleDownTrackBindingReports(recv.Name())
})
outTrack.OnCloseHandler(func() {
t.lock.Lock()
@@ -188,26 +187,69 @@ func (t *MediaTrack) RemoveAllSubscribers() {
t.downtracks = make(map[string]types.DownTrack)
}
// forwardRTPWorker reads from the receiver and writes to each sender
//func (t *MediaTrack) scheduleDownTrackBindingReports(streamId string) {
// var sd []rtcp.SourceDescriptionChunk
//
// p.lock.RLock()
// dts := p.subscribedTracks[streamId]
// for _, dt := range dts {
// if !dt.IsBound() {
// continue
// }
// chunks := dt.CreateSourceDescriptionChunks()
// if chunks != nil {
// sd = append(sd, chunks...)
// }
// }
// p.lock.RUnlock()
//
// pkts := []rtcp.Packet{
// &rtcp.SourceDescription{Chunks: sd},
// }
//
// go func() {
// batch := pkts
// i := 0
// for {
// if err := p.peerConn.WriteRTCP(batch); err != nil {
// logger.GetLogger().Debugw("error sending track binding reports",
// "participant", p.id,
// "err", err)
// }
// if i > 5 {
// return
// }
// i++
// time.Sleep(20 * time.Millisecond)
// }
// }()
//}
// b reads from the receiver and writes to each sender
func (t *MediaTrack) forwardRTPWorker() {
defer func() {
logger.GetLogger().Debugw("stopping forward RTP worker")
t.RemoveAllSubscribers()
// TODO: send unpublished events?
t.nackWorker.Stop()
}()
for pkt := range t.receiver.RTPChan() {
//logger.GetLogger().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 {
continue
}
//logger.GetLogger().Debugw("read packet from remoteTrack",
// "participantId", t.participantId,
// "remoteTrack", t.remoteTrack.ID())
t.lock.RLock()
for dstId, dt := range t.downtracks {
//logger.GetLogger().Debugw("read packet from remoteTrack",
// "srcParticipant", t.participantId,
// "destParticipant", dstId,
// "track", t.ID())
err := dt.WriteRTP(pkt)
if IsEOF(err) {
// this participant unsubscribed, remove it
+108 -38
View File
@@ -2,7 +2,6 @@ package rtc
import (
"context"
"fmt"
"io"
"sync"
"time"
@@ -25,10 +24,17 @@ const (
negotiationFrequency = 100 * time.Millisecond
)
const (
negotiationStateNone = iota
negotiationStateClient
negotiationStateServer
)
type ParticipantImpl struct {
id string
peerConn types.PeerConnection
sigConn types.SignalConnection
receiverConfig ReceiverConfig
ctx context.Context
cancel context.CancelFunc
mediaEngine *webrtc.MediaEngine
@@ -39,7 +45,10 @@ type ParticipantImpl struct {
// publishedTracks that participant is publishing
publishedTracks map[string]types.PublishedTrack
// client intended to publish, yet to be reconciled
pendingTracks map[string]*livekit.TrackInfo
pendingTracks map[string]*livekit.TrackInfo
negotiationCond *sync.Cond
negotiationState int
debouncedNegotiate func(func())
lock sync.RWMutex
@@ -63,7 +72,7 @@ func NewPeerConnection(conf *WebRTCConfig) (*webrtc.PeerConnection, error) {
return api.NewPeerConnection(conf.Configuration)
}
func NewParticipant(pc types.PeerConnection, sc types.SignalConnection, name string) (*ParticipantImpl, error) {
func NewParticipant(pc types.PeerConnection, sc types.SignalConnection, name string, receiverConfig ReceiverConfig) (*ParticipantImpl, error) {
me := &webrtc.MediaEngine{}
me.RegisterDefaultCodecs()
@@ -73,12 +82,14 @@ func NewParticipant(pc types.PeerConnection, sc types.SignalConnection, name str
name: name,
peerConn: pc,
sigConn: sc,
receiverConfig: receiverConfig,
ctx: ctx,
cancel: cancel,
rtcpCh: make(chan []rtcp.Packet, 10),
subscribedTracks: make(map[string][]*sfu.DownTrack),
state: livekit.ParticipantInfo_JOINING,
lock: sync.RWMutex{},
negotiationCond: sync.NewCond(&sync.Mutex{}),
publishedTracks: make(map[string]types.PublishedTrack, 0),
pendingTracks: make(map[string]*livekit.TrackInfo),
mediaEngine: me,
@@ -86,7 +97,6 @@ func NewParticipant(pc types.PeerConnection, sc types.SignalConnection, name str
}
log := logger.GetLogger()
pc.ConnectionState()
pc.OnTrack(participant.onMediaTrack)
pc.OnICECandidate(func(c *webrtc.ICECandidate) {
@@ -119,9 +129,18 @@ func NewParticipant(pc types.PeerConnection, sc types.SignalConnection, name str
}
})
// TODO: handle data channel
pc.OnDataChannel(participant.onDataChannel)
// only set after answered
pc.OnNegotiationNeeded(func() {
if participant.state != livekit.ParticipantInfo_JOINED && participant.state != livekit.ParticipantInfo_ACTIVE {
// ignore negotiation requests before connected
return
}
logger.GetLogger().Debugw("negotiation needed", "participantId", participant.ID())
participant.scheduleNegotiate()
})
return participant, nil
}
@@ -173,6 +192,12 @@ func (p *ParticipantImpl) OnClose(callback func(types.Participant)) {
// Answer an offer from remote participant, used when clients make the initial connection
func (p *ParticipantImpl) Answer(sdp webrtc.SessionDescription) (answer webrtc.SessionDescription, err error) {
if p.state != livekit.ParticipantInfo_JOINING && p.negotiationState != negotiationStateClient {
// not in a valid state to continue
err = ErrUnexpectedNegotiation
return
}
if err = p.peerConn.SetRemoteDescription(sdp); err != nil {
return
}
@@ -188,11 +213,13 @@ func (p *ParticipantImpl) Answer(sdp webrtc.SessionDescription) (answer webrtc.S
return
}
// only set after answered
p.peerConn.OnNegotiationNeeded(func() {
logger.GetLogger().Debugw("negotiation needed", "participantId", p.ID())
p.scheduleNegotiate()
})
// if this is a client initiated re-negotiation, we'll need to flip back our state
p.negotiationCond.L.Lock()
if p.negotiationState == negotiationStateClient {
p.negotiationState = negotiationStateNone
p.negotiationCond.Broadcast()
}
p.negotiationCond.L.Unlock()
err = p.sigConn.WriteResponse(&livekit.SignalResponse{
Message: &livekit.SignalResponse_Answer{
@@ -211,21 +238,29 @@ func (p *ParticipantImpl) AddTrack(clientId, name string, trackType livekit.Trac
p.lock.Lock()
defer p.lock.Unlock()
p.pendingTracks[clientId] = &livekit.TrackInfo{
ti := &livekit.TrackInfo{
Type: trackType,
Name: name,
Sid: utils.NewGuid(utils.TrackPrefix),
}
p.pendingTracks[clientId] = ti
p.scheduleNegotiate()
p.sigConn.WriteResponse(&livekit.SignalResponse{
Message: &livekit.SignalResponse_TrackPublished{
TrackPublished: &livekit.TrackPublishedResponse{
Cid: clientId,
Track: ti,
},
},
})
}
func (p *ParticipantImpl) RemoveTrack(sid string) error {
p.lock.Lock()
defer p.lock.Unlock()
//
// TODO: handle removal properly
p.scheduleNegotiate()
return nil
}
@@ -237,9 +272,31 @@ func (p *ParticipantImpl) HandleAnswer(sdp webrtc.SessionDescription) error {
if err := p.peerConn.SetRemoteDescription(sdp); err != nil {
return errors.Wrap(err, "could not set remote description")
}
// negotiated, reset flag
p.negotiationCond.L.Lock()
p.negotiationState = negotiationStateNone
p.negotiationCond.Broadcast()
p.negotiationCond.L.Unlock()
return nil
}
// client requested negotiation, when it's able to, send a signal to let it
func (p *ParticipantImpl) HandleClientNegotiation() {
// wait until client is able to request negotiation
p.negotiationCond.L.Lock()
for p.negotiationState != negotiationStateNone {
p.negotiationCond.Wait()
}
p.negotiationState = negotiationStateClient
p.negotiationCond.L.Unlock()
p.sigConn.WriteResponse(&livekit.SignalResponse{
Message: &livekit.SignalResponse_Negotiate{
Negotiate: &livekit.NegotiationResponse{},
},
})
}
// AddICECandidate adds candidates for remote peer
func (p *ParticipantImpl) AddICECandidate(candidate webrtc.ICECandidateInit) error {
if err := p.peerConn.AddICECandidate(candidate); err != nil {
@@ -346,9 +403,9 @@ func (p *ParticipantImpl) AddDownTrack(streamId string, dt *sfu.DownTrack) {
p.lock.Lock()
p.subscribedTracks[streamId] = append(p.subscribedTracks[streamId], dt)
p.lock.Unlock()
dt.OnBind(func() {
go p.scheduleDownTrackBindingReports(streamId)
})
//dt.OnBind(func() {
// go p.scheduleDownTrackBindingReports(streamId)
//})
}
func (p *ParticipantImpl) RemoveDownTrack(streamId string, dt *sfu.DownTrack) {
@@ -368,7 +425,16 @@ func (p *ParticipantImpl) scheduleNegotiate() {
p.debouncedNegotiate(p.negotiate)
}
// initiates server-driven negotiation by creating an offer
func (p *ParticipantImpl) negotiate() {
p.negotiationCond.L.Lock()
for p.negotiationState != negotiationStateNone {
p.negotiationCond.Wait()
p.negotiationState = negotiationStateServer
}
p.negotiationCond.L.Unlock()
logger.GetLogger().Debugw("starting negotiation", "participant", p.ID())
offer, err := p.peerConn.CreateOffer(nil)
if err != nil {
logger.GetLogger().Errorw("could not create offer", "err", err)
@@ -415,13 +481,18 @@ func (p *ParticipantImpl) updateState(state livekit.ParticipantInfo_State) {
// when a new remoteTrack is created, creates a Track and adds it to room
func (p *ParticipantImpl) onMediaTrack(track *webrtc.TrackRemote, rtpReceiver *webrtc.RTPReceiver) {
logger.GetLogger().Debugw("remoteTrack added", "participantId", p.ID(), "remoteTrack", track.ID())
logger.GetLogger().Debugw("mediaTrack added", "participantId", p.ID(), "remoteTrack", track.ID())
ti := p.popPendingTrack(track.ID())
if ti == nil {
return
}
// create ReceiverImpl
receiver := NewReceiver(p.rtcpCh, rtpReceiver, track)
mt := NewMediaTrack(p.id, p.rtcpCh, track, receiver)
receiver := NewReceiver(p.rtcpCh, rtpReceiver, track, p.receiverConfig)
mt := NewMediaTrack(ti.Sid, p.id, p.rtcpCh, track, receiver)
p.handleTrackPublished(track.ID(), mt)
p.handleTrackPublished(mt)
}
func (p *ParticipantImpl) onDataChannel(dc *webrtc.DataChannel) {
@@ -430,38 +501,37 @@ func (p *ParticipantImpl) onDataChannel(dc *webrtc.DataChannel) {
}
logger.GetLogger().Debugw("dataChannel added", "participantId", p.ID(), "label", dc.Label())
dt := NewDataTrack(p.id, dc)
p.lock.Lock()
p.publishedTracks[dt.id] = dt
p.lock.Unlock()
// data channels have numeric ids, so we use its label to identify
ti := p.popPendingTrack(dc.Label())
if ti == nil {
return
}
dt.Start()
dt := NewDataTrack(ti.Sid, p.id, dc)
cid := fmt.Sprintf("%d", dc.ID())
p.handleTrackPublished(cid, dt)
p.handleTrackPublished(dt)
}
func (p *ParticipantImpl) handleTrackPublished(clientId string, track types.PublishedTrack) {
// fill in
func (p *ParticipantImpl) popPendingTrack(clientId string) *livekit.TrackInfo {
p.lock.Lock()
defer p.lock.Unlock()
ti := p.pendingTracks[clientId]
if ti == nil {
logger.GetLogger().Errorw("track info not published prior to track", "clientId", clientId)
} else {
track.SetName(ti.Name)
delete(p.pendingTracks, clientId)
}
return ti
}
func (p *ParticipantImpl) handleTrackPublished(track types.PublishedTrack) {
// fill in
p.lock.Lock()
defer p.lock.Unlock()
p.publishedTracks[track.ID()] = track
track.Start()
// confirm publication
p.sigConn.WriteResponse(&livekit.SignalResponse{
Message: &livekit.SignalResponse_TrackPublished{
TrackPublished: ToProtoTrack(track),
},
})
if p.onTrackPublished != nil {
go p.onTrackPublished(p, track)
}
@@ -492,7 +562,7 @@ func (p *ParticipantImpl) scheduleDownTrackBindingReports(streamId string) {
i := 0
for {
if err := p.peerConn.WriteRTCP(batch); err != nil {
logger.GetLogger().Debugw("Sending track binding reports",
logger.GetLogger().Debugw("error sending track binding reports",
"participant", p.id,
"err", err)
}
+6 -1
View File
@@ -23,7 +23,7 @@ type ReceiverImpl struct {
rtcpChan chan []rtcp.Packet
}
func NewReceiver(rtcpCh chan []rtcp.Packet, rtpReceiver *webrtc.RTPReceiver, track *webrtc.TrackRemote) *ReceiverImpl {
func NewReceiver(rtcpCh chan []rtcp.Packet, rtpReceiver *webrtc.RTPReceiver, track *webrtc.TrackRemote, config ReceiverConfig) *ReceiverImpl {
r := &ReceiverImpl{
rtpReceiver: rtpReceiver,
rtcpChan: rtcpCh,
@@ -43,6 +43,11 @@ func NewReceiver(rtcpCh chan []rtcp.Packet, rtpReceiver *webrtc.RTPReceiver, tra
// TODO: figure out how to handle this
})
r.buffer.Bind(rtpReceiver.GetParameters(), buffer.Options{
BufferTime: config.maxBufferTime,
MaxBitRate: config.maxBitrate,
})
// received sender updates
r.rtcpReader.OnPacket(func(bytes []byte) {
pkts, err := rtcp.Unmarshal(bytes)
+7 -2
View File
@@ -68,7 +68,8 @@ func (r *Room) Join(participant types.Participant) error {
// it's important to set this before connection, we don't want to miss out on any publishedTracks
participant.OnTrackPublished(r.onTrackAdded)
participant.OnStateChange(func(p types.Participant, oldState livekit.ParticipantInfo_State) {
log.Debugw("participant state changed", "state", p.State(), "participant", p.ID())
log.Debugw("participant state changed", "state", p.State(), "participant", p.ID(),
"oldState", oldState)
r.broadcastParticipantState(p)
if oldState == livekit.ParticipantInfo_JOINING && p.State() == livekit.ParticipantInfo_JOINED {
@@ -140,10 +141,14 @@ func (r *Room) onTrackAdded(participant types.Participant, track types.Published
// skip publishing participant
continue
}
if existingParticipant.State() != livekit.ParticipantInfo_JOINED {
if existingParticipant.State() != livekit.ParticipantInfo_JOINED && existingParticipant.State() != livekit.ParticipantInfo_ACTIVE {
// not fully joined. don't subscribe yet
continue
}
logger.GetLogger().Debugw("subscribing to new track",
"srcParticipant", participant.ID(),
"remoteTrack", track.ID(),
"dstParticipant", existingParticipant.ID())
if err := track.AddSubscriber(existingParticipant); err != nil {
logger.GetLogger().Errorw("could not subscribe to remoteTrack",
"srcParticipant", participant.ID(),
+4 -2
View File
@@ -85,7 +85,7 @@ func (s *RTCService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
writeJSONError(w, http.StatusInternalServerError, "could not create peerConnection", err.Error())
return
}
participant, err := rtc.NewParticipant(pc, signalConn, pName)
participant, err := rtc.NewParticipant(pc, signalConn, pName, s.manager.Config().Receiver)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "could not create participant", err.Error())
return
@@ -149,6 +149,8 @@ func (s *RTCService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// jsonError(http.StatusInternalServerError, "could not handle negotiate", err.Error()))
return
}
case *livekit.SignalRequest_Negotiate:
participant.HandleClientNegotiation()
case *livekit.SignalRequest_Trickle:
if participant.State() == livekit.ParticipantInfo_JOINING {
log.Errorw("cannot trickle before peer offer", "participant", participant.ID())
@@ -185,7 +187,7 @@ func (s *RTCService) handleOffer(participant types.Participant, offer *livekit.S
func (s *RTCService) handleTrickle(participant types.Participant, trickle *livekit.TrickleRequest) error {
candidateInit := rtc.FromProtoTrickle(trickle)
logger.GetLogger().Debugw("adding peer candidate", "participant", participant.ID())
//logger.GetLogger().Debugw("adding peer candidate", "participant", participant.ID())
if err := participant.AddICECandidate(candidateInit); err != nil {
return err
}