Refactor/cleanup of negotiation path

This commit is contained in:
David Zhao
2021-04-15 17:03:22 -07:00
parent 6c5bd4ce42
commit e4238890ff
20 changed files with 153 additions and 151 deletions
+1 -1
View File
@@ -19,7 +19,7 @@ type MessageSink interface {
//counterfeiter:generate . MessageSource
type MessageSource interface {
// source exposes a one way channel to make it easier to use with select
// ReadChan exposes a one way channel to make it easier to use with select
ReadChan() <-chan proto.Message
}
+3 -3
View File
@@ -128,7 +128,7 @@ func (r *RedisRouter) ListNodes() ([]*livekit.Node, error) {
return nodes, nil
}
// signal connection sets up paths to the RTC node, and starts to route messages to that message queue
// StartParticipantSignal signal connection sets up paths to the RTC node, and starts to route messages to that message queue
func (r *RedisRouter) StartParticipantSignal(roomName string, pi ParticipantInit) (connectionId string, reqSink MessageSink, resSource MessageSource, err error) {
// find the node where the room is hosted at
rtcNode, err := r.GetNodeForRoom(roomName)
@@ -248,8 +248,8 @@ func (r *RedisRouter) Stop() {
return
}
logger.Debugw("stopping RedisRouter")
r.pubsub.Close()
r.UnregisterNode()
_ = r.pubsub.Close()
_ = r.UnregisterNode()
r.cancel()
}
+1 -2
View File
@@ -58,8 +58,7 @@ func NewWebRTCConfig(conf *config.RTCConfig, externalIP string) (*WebRTCConfig,
bufferFactory := buffer.NewBufferFactory(conf.PacketBufferSize, zapr.NewLogger(logger.Desugar()))
s.BufferFactory = bufferFactory.GetOrNew
networkTypes := []webrtc.NetworkType{}
networkTypes := make([]webrtc.NetworkType, 0, 4)
if !conf.ForceTCP {
networkTypes = append(networkTypes,
webrtc.NetworkTypeUDP4,
+5 -8
View File
@@ -109,8 +109,7 @@ func (t *MediaTrack) OnClose(f func()) {
t.onClose = f
}
// subscribes participant to current remoteTrack
// creates and add necessary forwarders and starts them
// AddSubscriber subscribes sub to current mediaTrack
func (t *MediaTrack) AddSubscriber(sub types.Participant) error {
t.lock.Lock()
defer t.lock.Unlock()
@@ -200,7 +199,7 @@ func (t *MediaTrack) AddSubscriber(sub types.Participant) error {
return nil
}
// adds a new RTP receiver to the track, returns true if this is a new track
// AddReceiver 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, twcc *twcc.Responder) {
t.lock.Lock()
defer t.lock.Unlock()
@@ -263,8 +262,8 @@ func (t *MediaTrack) AddReceiver(receiver *webrtc.RTPReceiver, track *webrtc.Tra
})
}
// removes peer from subscription
// stop all forwarders to the peer
// RemoveSubscriber removes participant from subscription
// stop all forwarders to the client
func (t *MediaTrack) RemoveSubscriber(participantId string) {
t.lock.RLock()
defer t.lock.RUnlock()
@@ -301,9 +300,7 @@ func (t *MediaTrack) sendDownTrackBindingReports(participantId string, rtcpCh ch
if chunks == nil {
return
}
if chunks != nil {
sd = append(sd, chunks...)
}
sd = append(sd, chunks...)
pkts := []rtcp.Packet{
&rtcp.SourceDescription{Chunks: sd},
+27 -42
View File
@@ -112,8 +112,7 @@ func NewParticipant(identity string, conf *WebRTCConfig, rs routing.MessageSink,
p.publisher.pc.OnTrack(p.onMediaTrack)
p.subscriber.pc.OnDataChannel(p.onDataChannel)
p.subscriber.OnNegotiationNeeded(p.negotiate)
p.subscriber.OnOffer(p.onOffer)
return p, nil
}
@@ -139,7 +138,7 @@ func (p *ParticipantImpl) ConnectedAt() time.Time {
return p.connectedAt.Load().(time.Time)
}
// attach metadata to the participant
// SetMetadata attaches metadata to the participant
func (p *ParticipantImpl) SetMetadata(metadata string) {
p.metadata = metadata
@@ -334,7 +333,6 @@ func (p *ParticipantImpl) Close() error {
p.updateState(livekit.ParticipantInfo_DISCONNECTED)
p.subscriber.pc.OnDataChannel(nil)
p.subscriber.pc.OnICECandidate(nil)
p.subscriber.pc.OnNegotiationNeeded(nil)
p.subscriber.pc.OnTrack(nil)
p.publisher.pc.OnICECandidate(nil)
// ensure this is synchronized
@@ -352,7 +350,7 @@ func (p *ParticipantImpl) Close() error {
}
// Subscribes op to all publishedTracks
func (p *ParticipantImpl) AddSubscriber(op types.Participant) error {
func (p *ParticipantImpl) AddSubscriber(op types.Participant) (int, error) {
p.lock.RLock()
tracks := make([]types.PublishedTrack, 0, len(p.publishedTracks))
for _, t := range p.publishedTracks {
@@ -361,7 +359,7 @@ func (p *ParticipantImpl) AddSubscriber(op types.Participant) error {
defer p.lock.RUnlock()
if len(tracks) == 0 {
return nil
return 0, nil
}
logger.Debugw("subscribing new participant to tracks",
@@ -369,12 +367,14 @@ func (p *ParticipantImpl) AddSubscriber(op types.Participant) error {
"newParticipant", op.Identity(),
"numTracks", len(tracks))
n := 0
for _, track := range tracks {
if err := track.AddSubscriber(op); err != nil {
return err
return n, err
}
n += 1
}
return nil
return n, nil
}
func (p *ParticipantImpl) RemoveSubscriber(participantId string) {
@@ -533,40 +533,6 @@ func (p *ParticipantImpl) sendIceCandidate(c *webrtc.ICECandidate, target liveki
})
}
// initiates server-driven negotiation by creating an offer
func (p *ParticipantImpl) negotiate() {
if p.State() == livekit.ParticipantInfo_DISCONNECTED {
logger.Debugw("skipping server negotiation", "participant", p.Identity())
// skip when disconnected
return
}
logger.Debugw("starting server negotiation", "participant", p.Identity())
offer, err := p.subscriber.pc.CreateOffer(nil)
if err != nil {
logger.Errorw("could not create offer", "err", err)
return
}
err = p.subscriber.pc.SetLocalDescription(offer)
if err != nil {
logger.Errorw("could not set local description", "err", err)
return
}
logger.Debugw("sending offer to participant",
"participant", p.Identity(),
//"sdp", offer.SDP,
)
p.writeMessage(&livekit.SignalResponse{
Message: &livekit.SignalResponse_Offer{
Offer: ToProtoSessionDescription(offer),
},
})
}
func (p *ParticipantImpl) updateState(state livekit.ParticipantInfo_State) {
oldState := p.State()
if state == oldState {
@@ -599,6 +565,25 @@ func (p *ParticipantImpl) writeMessage(msg *livekit.SignalResponse) error {
return nil
}
// when the server has an offer for participant
func (p *ParticipantImpl) onOffer(sd webrtc.SessionDescription) {
if p.State() == livekit.ParticipantInfo_DISCONNECTED {
logger.Debugw("skipping server offer", "participant", p.Identity())
// skip when disconnected
return
}
logger.Debugw("sending server offer to participant",
"participant", p.Identity(),
//"sdp", offer.SDP,
)
_ = p.writeMessage(&livekit.SignalResponse{
Message: &livekit.SignalResponse_Offer{
Offer: ToProtoSessionDescription(sd),
},
})
}
// 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.Debugw("mediaTrack added",
+2 -3
View File
@@ -128,7 +128,7 @@ func TestTrackPublishing(t *testing.T) {
// after disconnection, things should continue to function and not panic
func TestDisconnectTiming(t *testing.T) {
t.Run("negotiate doesn't fail after channel closed", func(t *testing.T) {
t.Run("Negotiate doesn't panic after channel closed", func(t *testing.T) {
p := newParticipantForTest("test")
msg := routing.NewMessageChannel()
p.responseSink = msg
@@ -140,9 +140,8 @@ func TestDisconnectTiming(t *testing.T) {
track := &typesfakes.FakePublishedTrack{}
p.handleTrackPublished(track)
// close channel and then try to negotiate
// close channel and then try to Negotiate
msg.Close()
p.negotiate()
})
}
+27 -14
View File
@@ -141,20 +141,11 @@ func (r *Room) Join(participant types.Participant) error {
if p.State() == livekit.ParticipantInfo_ACTIVE {
// subscribe participant to existing publishedTracks
for _, op := range r.GetParticipants() {
if p.ID() == op.ID() {
// don't send to itself
continue
}
if err := op.AddSubscriber(p); err != nil {
// TODO: log error? or disconnect?
logger.Errorw("could not subscribe to participant",
"dest", p.Identity(),
"source", op.Identity())
}
}
r.subscribeToExistingTracks(p)
// start the workers once connectivity is established
p.Start()
} else if p.State() == livekit.ParticipantInfo_DISCONNECTED {
// remove participant from room
go r.RemoveParticipant(p.Identity())
@@ -244,7 +235,7 @@ func (r *Room) UpdateSubscriptions(participant types.Participant, subscription *
return nil
}
// Close the room if all participants had left, or it's still empty past timeout
// CloseIfEmpty closes the room if all participants had left, or it's still empty past timeout
func (r *Room) CloseIfEmpty() {
if r.isClosed.Get() {
return
@@ -304,6 +295,7 @@ func (r *Room) onTrackAdded(participant types.Participant, track types.Published
// not fully joined. don't subscribe yet
continue
}
logger.Debugw("subscribing to new track",
"source", participant.Identity(),
"remoteTrack", track.ID(),
@@ -336,6 +328,27 @@ func (r *Room) onParticipantMetadataUpdate(p types.Participant) {
}
}
func (r *Room) subscribeToExistingTracks(p types.Participant) {
tracksAdded := 0
for _, op := range r.GetParticipants() {
if p.ID() == op.ID() {
// don't send to itself
continue
}
if n, err := op.AddSubscriber(p); err != nil {
// TODO: log error? or disconnect?
logger.Errorw("could not subscribe to participant",
"dest", p.Identity(),
"source", op.Identity())
} else {
tracksAdded += n
}
}
if tracksAdded > 0 {
logger.Debugw("subscribed participants to existing tracks", "tracks", tracksAdded)
}
}
// broadcast an update about participant p
func (r *Room) broadcastParticipantState(p types.Participant, skipSource bool) {
updates := ToProtoParticipants([]types.Participant{p})
@@ -357,7 +370,7 @@ func (r *Room) broadcastParticipantState(p types.Participant, skipSource bool) {
func (r *Room) sendSpeakerUpdates(speakers []*livekit.SpeakerInfo) {
for _, p := range r.GetParticipants() {
p.SendActiveSpeakers(speakers)
_ = p.SendActiveSpeakers(speakers)
}
}
+41 -25
View File
@@ -20,8 +20,8 @@ const (
negotiationStateNone = iota
// waiting for client answer
negotiationStateClient
// need to negotiate again
negotiationStateServer
// need to Negotiate again
negotiationRetry
)
// PCTransport is a wrapper around PeerConnection, with some helper methods
@@ -32,7 +32,7 @@ type PCTransport struct {
lock sync.Mutex
pendingCandidates []webrtc.ICECandidateInit
debouncedNegotiate func(func())
onNegotiation func()
onOffer func(offer webrtc.SessionDescription)
negotiationState atomic.Value
}
@@ -68,7 +68,6 @@ func NewPCTransport(target livekit.SignalTarget, conf *WebRTCConfig) (*PCTranspo
debouncedNegotiate: debounce.New(negotiationFrequency),
}
t.negotiationState.Store(negotiationStateNone)
t.pc.OnNegotiationNeeded(t.negotiate)
return t, nil
@@ -90,7 +89,7 @@ func (t *PCTransport) PeerConnection() *webrtc.PeerConnection {
}
func (t *PCTransport) Close() {
t.pc.Close()
_ = t.pc.Close()
}
func (t *PCTransport) SetRemoteDescription(sd webrtc.SessionDescription) error {
@@ -110,33 +109,50 @@ func (t *PCTransport) SetRemoteDescription(sd webrtc.SessionDescription) error {
// negotiated, reset flag
state := t.negotiationState.Load().(int)
t.negotiationState.Store(negotiationStateNone)
if state == negotiationStateServer && t.onNegotiation != nil {
logger.Debugw("negotiating again")
// need to negotiate again
if state == negotiationRetry {
// need to Negotiate again
t.negotiate()
}
return nil
}
func (t *PCTransport) OnNegotiationNeeded(f func()) {
t.onNegotiation = f
// OnOffer is called when the PeerConnection starts negotiation and prepares an offer
func (t *PCTransport) OnOffer(f func(sd webrtc.SessionDescription)) {
t.onOffer = f
}
func (t *PCTransport) negotiate() {
t.debouncedNegotiate(func() {
state := t.negotiationState.Load().(int)
// when there's an ongoing negotiation, let it finish and not disrupt its state
if state == negotiationStateClient {
logger.Debugw("skipping negotiation, trying again later")
t.negotiationState.Store(negotiationStateServer)
return
}
if t.onNegotiation != nil {
t.onNegotiation()
// indicate waiting for client
t.negotiationState.Store(negotiationStateClient)
}
})
t.debouncedNegotiate(t.handleNegotiate)
}
func (t *PCTransport) handleNegotiate() {
if t.onOffer == nil {
return
}
state := t.negotiationState.Load().(int)
// when there's an ongoing negotiation, let it finish and not disrupt its state
if state == negotiationStateClient {
logger.Debugw("skipping negotiation, trying again later")
t.negotiationState.Store(negotiationRetry)
return
}
offer, err := t.pc.CreateOffer(nil)
if err != nil {
logger.Errorw("could not create offer", "err", err)
return
}
err = t.pc.SetLocalDescription(offer)
if err != nil {
logger.Errorw("could not set local description", "err", err)
return
}
t.onOffer(offer)
// indicate waiting for client
t.negotiationState.Store(negotiationStateClient)
}
+1 -1
View File
@@ -41,7 +41,7 @@ type Participant interface {
HandleOffer(sdp webrtc.SessionDescription) (answer webrtc.SessionDescription, err error)
HandleAnswer(sdp webrtc.SessionDescription) error
AddICECandidate(candidate webrtc.ICECandidateInit, target livekit.SignalTarget) error
AddSubscriber(op Participant) error
AddSubscriber(op Participant) (int, error)
RemoveSubscriber(peerId string)
SendJoinResponse(info *livekit.Room, otherParticipants []Participant, iceServers []*livekit.ICEServer) error
SendParticipantUpdate(participants []*livekit.ParticipantInfo) error
+19 -14
View File
@@ -31,16 +31,18 @@ type FakeParticipant struct {
arg1 string
arg2 types.SubscribedTrack
}
AddSubscriberStub func(types.Participant) error
AddSubscriberStub func(types.Participant) (int, error)
addSubscriberMutex sync.RWMutex
addSubscriberArgsForCall []struct {
arg1 types.Participant
}
addSubscriberReturns struct {
result1 error
result1 int
result2 error
}
addSubscriberReturnsOnCall map[int]struct {
result1 error
result1 int
result2 error
}
AddTrackStub func(string, string, livekit.TrackType)
addTrackMutex sync.RWMutex
@@ -430,7 +432,7 @@ func (fake *FakeParticipant) AddSubscribedTrackArgsForCall(i int) (string, types
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeParticipant) AddSubscriber(arg1 types.Participant) error {
func (fake *FakeParticipant) AddSubscriber(arg1 types.Participant) (int, error) {
fake.addSubscriberMutex.Lock()
ret, specificReturn := fake.addSubscriberReturnsOnCall[len(fake.addSubscriberArgsForCall)]
fake.addSubscriberArgsForCall = append(fake.addSubscriberArgsForCall, struct {
@@ -444,9 +446,9 @@ func (fake *FakeParticipant) AddSubscriber(arg1 types.Participant) error {
return stub(arg1)
}
if specificReturn {
return ret.result1
return ret.result1, ret.result2
}
return fakeReturns.result1
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeParticipant) AddSubscriberCallCount() int {
@@ -455,7 +457,7 @@ func (fake *FakeParticipant) AddSubscriberCallCount() int {
return len(fake.addSubscriberArgsForCall)
}
func (fake *FakeParticipant) AddSubscriberCalls(stub func(types.Participant) error) {
func (fake *FakeParticipant) AddSubscriberCalls(stub func(types.Participant) (int, error)) {
fake.addSubscriberMutex.Lock()
defer fake.addSubscriberMutex.Unlock()
fake.AddSubscriberStub = stub
@@ -468,27 +470,30 @@ func (fake *FakeParticipant) AddSubscriberArgsForCall(i int) types.Participant {
return argsForCall.arg1
}
func (fake *FakeParticipant) AddSubscriberReturns(result1 error) {
func (fake *FakeParticipant) AddSubscriberReturns(result1 int, result2 error) {
fake.addSubscriberMutex.Lock()
defer fake.addSubscriberMutex.Unlock()
fake.AddSubscriberStub = nil
fake.addSubscriberReturns = struct {
result1 error
}{result1}
result1 int
result2 error
}{result1, result2}
}
func (fake *FakeParticipant) AddSubscriberReturnsOnCall(i int, result1 error) {
func (fake *FakeParticipant) AddSubscriberReturnsOnCall(i int, result1 int, result2 error) {
fake.addSubscriberMutex.Lock()
defer fake.addSubscriberMutex.Unlock()
fake.AddSubscriberStub = nil
if fake.addSubscriberReturnsOnCall == nil {
fake.addSubscriberReturnsOnCall = make(map[int]struct {
result1 error
result1 int
result2 error
})
}
fake.addSubscriberReturnsOnCall[i] = struct {
result1 error
}{result1}
result1 int
result2 error
}{result1, result2}
}
func (fake *FakeParticipant) AddTrack(arg1 string, arg2 string, arg3 livekit.TrackType) {
+9 -7
View File
@@ -5,14 +5,13 @@ import (
"sync"
"time"
"github.com/livekit/protocol/utils"
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/rtc"
"github.com/livekit/livekit-server/pkg/rtc/types"
livekit "github.com/livekit/livekit-server/proto"
"github.com/livekit/protocol/utils"
)
const (
@@ -140,7 +139,7 @@ func (r *RoomManager) DeleteRoom(roomName string) error {
return err
}
// clean up after old rooms that have been around for awhile
// CleanupRooms cleans up after old rooms that have been around for awhile
func (r *RoomManager) CleanupRooms() error {
// cleanup rooms that have been left for over a day
rooms, err := r.roomStore.ListRooms()
@@ -172,7 +171,7 @@ func (r *RoomManager) CloseIdleRooms() {
}
}
// starts WebRTC session when a new participant is connected, takes place on RTC node
// StartSession starts WebRTC session when a new participant is connected, takes place on RTC node
func (r *RoomManager) StartSession(roomName string, pi routing.ParticipantInit, requestSource routing.MessageSource, responseSink routing.MessageSink) {
room, err := r.getOrCreateRoom(roomName)
if err != nil {
@@ -196,7 +195,6 @@ func (r *RoomManager) StartSession(roomName string, pi routing.ParticipantInit,
prevSink.Close()
}
participant.SetResponseSink(responseSink)
return
} else {
// we need to clean up the existing participant, so a new one can join
@@ -257,10 +255,14 @@ func (r *RoomManager) getOrCreateRoom(roomName string) (*rtc.Room, error) {
}
})
room.OnParticipantChanged(func(p types.Participant) {
var err error
if p.State() == livekit.ParticipantInfo_DISCONNECTED {
r.roomStore.DeleteParticipant(roomName, p.Identity())
err = r.roomStore.DeleteParticipant(roomName, p.Identity())
} else {
r.roomStore.PersistParticipant(roomName, p.ToProto())
err = r.roomStore.PersistParticipant(roomName, p.ToProto())
}
if err != nil {
logger.Errorw("could not handle participant change", "error", err)
}
})
r.lock.Lock()
+1 -1
View File
@@ -63,7 +63,7 @@ func (s *RTCService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
pi := routing.ParticipantInit{
Reconnect: reconnectParam == "1" || reconnectParam == "true",
Reconnect: boolValue(reconnectParam),
Identity: claims.Identity,
}
// only use permissions if any of them are set, default permissive
+5 -1
View File
@@ -25,5 +25,9 @@ func handleError(w http.ResponseWriter, status int, msg string) {
l := logger.Desugar().WithOptions(zap.AddCallerSkip(1))
l.Debug("error handling request", zap.String("error", msg), zap.Int("status", status))
w.WriteHeader(status)
w.Write([]byte(msg))
_, _ = w.Write([]byte(msg))
}
func boolValue(s string) bool {
return s == "1" || s == "true"
}