diff --git a/pkg/rtc/participant.go b/pkg/rtc/participant.go index 85e6ee71..c22b3cd1 100644 --- a/pkg/rtc/participant.go +++ b/pkg/rtc/participant.go @@ -29,13 +29,9 @@ import ( ) const ( - LossyDataChannel = "_lossy" - ReliableDataChannel = "_reliable" - sdBatchSize = 20 rttUpdateInterval = 5 * time.Second - stateActiveCond = 3 // reliableDCOpen,lossyDCOpen,PeerConnectionStateConnected disconnectCleanupDuration = 15 * time.Second ) @@ -88,23 +84,15 @@ type ParticipantParams struct { } type ParticipantImpl struct { - params ParticipantParams - publisher *PCTransport - subscriber *PCTransport - isClosed atomic.Bool - state atomic.Value // livekit.ParticipantInfo_State - updateCache *lru.Cache - resSink atomic.Value // routing.MessageSink - resSinkValid atomic.Bool - subscriberAsPrimary bool - grants *auth.ClaimGrants - isPublisher atomic.Bool + params ParticipantParams - // reliable and unreliable data channels - reliableDC *webrtc.DataChannel - reliableDCSub *webrtc.DataChannel - lossyDC *webrtc.DataChannel - lossyDCSub *webrtc.DataChannel + isClosed atomic.Bool + state atomic.Value // livekit.ParticipantInfo_State + updateCache *lru.Cache + resSink atomic.Value // routing.MessageSink + resSinkValid atomic.Bool + grants *auth.ClaimGrants + isPublisher atomic.Bool // when first connected connectedAt time.Time @@ -120,6 +108,7 @@ type ParticipantImpl struct { pendingTracksLock sync.RWMutex pendingTracks map[string]*pendingTrackInfo + *TransportManager *UpTrackManager // tracks the current participant is subscribed to @@ -148,16 +137,11 @@ type ParticipantImpl struct { onDataPacket func(types.LocalParticipant, *livekit.DataPacket) onSubscribedTo func(types.LocalParticipant, livekit.ParticipantID) - migrateState atomic.Value // types.MigrateState - pendingOffer *webrtc.SessionDescription - pendingDataChannels []*livekit.DataChannelInfo - onClose func(types.LocalParticipant, map[livekit.TrackID]livekit.ParticipantID) - onClaimsChanged func(participant types.LocalParticipant) - onICEConfigChanged func(participant types.LocalParticipant, iceConfig types.IceConfig) + migrateState atomic.Value // types.MigrateState - activeCounter atomic.Int32 - firstConnected atomic.Bool - iceConfig types.IceConfig + onClose func(types.LocalParticipant, map[livekit.TrackID]livekit.ParticipantID) + onClaimsChanged func(participant types.LocalParticipant) + onICEConfigChanged func(participant types.LocalParticipant, iceConfig types.IceConfig) cachedDownTracks map[livekit.TrackID]*downTrackState @@ -203,162 +187,16 @@ func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) { return nil, err } - enabledCodecs := make([]*livekit.Codec, 0, len(p.params.EnabledCodecs)) - for _, c := range p.params.EnabledCodecs { - var disabled bool - for _, disableCodec := range p.params.ClientConf.GetDisabledCodecs().GetCodecs() { - // disable codec's fmtp is empty means disable this codec entirely - if strings.EqualFold(c.Mime, disableCodec.Mime) && (disableCodec.FmtpLine == "" || disableCodec.FmtpLine == c.FmtpLine) { - disabled = true - break - } - } - if !disabled { - enabledCodecs = append(enabledCodecs, c) - } - } - - p.publisher, err = NewPCTransport(TransportParams{ - ParticipantID: p.params.SID, - ParticipantIdentity: p.params.Identity, - ProtocolVersion: p.ProtocolVersion(), - Target: livekit.SignalTarget_PUBLISHER, - Config: params.Config, - CongestionControlConfig: params.CongestionControlConfig, - Telemetry: p.params.Telemetry, - EnabledCodecs: enabledCodecs, - Logger: LoggerWithPCTarget(params.Logger, livekit.SignalTarget_PUBLISHER), - SimTracks: params.SimTracks, - }) + err = p.setupTransportManager() if err != nil { return nil, err } - p.subscriber, err = NewPCTransport(TransportParams{ - ParticipantID: p.params.SID, - ParticipantIdentity: p.params.Identity, - ProtocolVersion: p.ProtocolVersion(), - Target: livekit.SignalTarget_SUBSCRIBER, - Config: params.Config, - CongestionControlConfig: params.CongestionControlConfig, - Telemetry: p.params.Telemetry, - EnabledCodecs: enabledCodecs, - Logger: LoggerWithPCTarget(params.Logger, livekit.SignalTarget_SUBSCRIBER), - }) - if err != nil { - return nil, err - } - - p.subscriber.OnNegotiationFailed(p.handleNegotiationFailed) - - p.publisher.pc.OnICECandidate(func(c *webrtc.ICECandidate) { - if c == nil || p.State() == livekit.ParticipantInfo_DISCONNECTED { - return - } - p.sendIceCandidate(c, livekit.SignalTarget_PUBLISHER) - }) - p.publisher.OnRemoteDescripitonSettled(p.createPublsiherAnswerAndSend) - p.subscriber.pc.OnICECandidate(func(c *webrtc.ICECandidate) { - if c == nil || p.State() == livekit.ParticipantInfo_DISCONNECTED || p.MigrateState() == types.MigrateStateInit { - return - } - p.sendIceCandidate(c, livekit.SignalTarget_SUBSCRIBER) - }) - - primaryPC := p.publisher.pc - secondaryPC := p.subscriber.pc - // primary connection does not change, canSubscribe can change if permission was updated - // after the participant has joined - p.subscriberAsPrimary = p.ProtocolVersion().SubscriberAsPrimary() && p.CanSubscribe() - if p.SubscriberAsPrimary() { - primaryPC = p.subscriber.pc - secondaryPC = p.publisher.pc - if !params.Migration { - if err := p.createDataChannelForSubscriberAsPrimary(nil); err != nil { - return nil, err - } - } - } else { - p.activeCounter.Add(2) - } - - primaryPC.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) { - p.handleICEStateChange(true, state) - }) - secondaryPC.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) { - p.handleICEStateChange(false, state) - }) - - primaryPC.OnConnectionStateChange(p.handlePrimaryStateChange) - secondaryPC.OnConnectionStateChange(p.handleSecondaryStateChange) - - p.publisher.pc.OnTrack(p.onMediaTrack) - p.publisher.pc.OnDataChannel(p.onDataChannel) - - p.subscriber.OnOffer(p.onOffer) - p.subscriber.OnStreamStateChange(p.onStreamStateChange) p.setupUpTrackManager() return p, nil } -func (p *ParticipantImpl) createDataChannelForSubscriberAsPrimary(pendingDataChannels []*livekit.DataChannelInfo) error { - primaryPC := p.subscriber.pc - ordered := true - var ( - reliableID, lossyID uint16 - reliableIDPtr, lossyIDPtr *uint16 - ) - // for old version migration clients, they don't send subscriber data channel info - // so we need to create data channels with default ID and don't negotiate as client already has - // data channels with default ID. - // for new version migration clients, we create data channels with new ID and negotiate with client - - for _, dc := range pendingDataChannels { - if dc.Target == livekit.SignalTarget_SUBSCRIBER { - if dc.Label == ReliableDataChannel { - // pion use step 2 for auto generated ID, so we need to add 4 to avoid conflict - reliableID = uint16(dc.Id) + 4 - reliableIDPtr = &reliableID - } else if dc.Label == LossyDataChannel { - lossyID = uint16(dc.Id) + 4 - lossyIDPtr = &lossyID - } - } - } - - p.lock.Lock() - var err error - negotiated := p.params.Migration && reliableIDPtr == nil - p.reliableDCSub, err = primaryPC.CreateDataChannel(ReliableDataChannel, &webrtc.DataChannelInit{ - Ordered: &ordered, - ID: reliableIDPtr, - Negotiated: &negotiated, - }) - if err != nil { - p.lock.Unlock() - return err - } - p.reliableDCSub.OnOpen(p.incActiveCounter) - - retransmits := uint16(0) - negotiated = p.params.Migration && lossyIDPtr == nil - p.lossyDCSub, err = primaryPC.CreateDataChannel(LossyDataChannel, &webrtc.DataChannelInit{ - Ordered: &ordered, - MaxRetransmits: &retransmits, - ID: lossyIDPtr, - Negotiated: &negotiated, - }) - if err != nil { - p.lock.Unlock() - return err - } - p.lossyDCSub.OnOpen(p.incActiveCounter) - p.lock.Unlock() - - return nil -} - func (p *ParticipantImpl) GetLogger() logger.Logger { return p.params.Logger } @@ -465,7 +303,7 @@ func (p *ParticipantImpl) SetPermission(permission *livekit.ParticipantPermissio } } // update isPublisher attribute - p.isPublisher.Store(canPublish && p.publisher.IsEstablished()) + p.isPublisher.Store(canPublish && p.TransportManager.IsPublisherEstablished()) if onParticipantUpdate != nil { onParticipantUpdate(p) @@ -496,10 +334,6 @@ func (p *ParticipantImpl) ToProto() *livekit.ParticipantInfo { return info } -func (p *ParticipantImpl) SubscriberMediaEngine() *webrtc.MediaEngine { - return p.subscriber.me -} - // callbacks for clients func (p *ParticipantImpl) OnTrackPublished(callback func(types.LocalParticipant, types.MediaTrack)) { @@ -552,75 +386,42 @@ func (p *ParticipantImpl) OnClaimsChanged(callback func(types.LocalParticipant)) // HandleOffer an offer from remote participant, used when clients make the initial connection func (p *ParticipantImpl) HandleOffer(offer webrtc.SessionDescription) error { - p.lock.Lock() + p.params.Logger.Infow("received offer", "transport", livekit.SignalTarget_PUBLISHER) + shouldPend := false if p.MigrateState() == types.MigrateStateInit { - p.pendingOffer = &offer - p.lock.Unlock() - return nil + shouldPend = true } - p.lock.Unlock() - // filter before setting remote description so that pion does not see filtered remote candidates - if p.iceConfig.PreferPubTcp { - p.publisher.Logger().Infow("remote offer (unfiltered)", "sdp", offer.SDP) - } - modifiedOffer := p.publisher.FilterCandidates(offer) - if p.iceConfig.PreferPubTcp { - p.publisher.Logger().Infow("remote offer (filtered)", "sdp", modifiedOffer.SDP) - } - if err := p.publisher.SetRemoteDescription(modifiedOffer); err != nil { - prometheus.ServiceOperationCounter.WithLabelValues("answer", "error", "remote_description").Add(1) + if err := p.TransportManager.HandleOffer(offer, shouldPend); err != nil { + prometheus.ServiceOperationCounter.WithLabelValues("offer", "error", "remote_description").Add(1) return err } return nil } -func (p *ParticipantImpl) createPublsiherAnswerAndSend() error { - p.lock.RLock() - onParticipantUpdate := p.onParticipantUpdate - p.lock.RUnlock() - p.configureReceiverDTX() - - answer, err := p.publisher.pc.CreateAnswer(nil) - if err != nil { - prometheus.ServiceOperationCounter.WithLabelValues("answer", "error", "create").Add(1) - return errors.Wrap(err, "could not create answer") - } - - if p.iceConfig.PreferPubTcp { - p.publisher.Logger().Infow("local answer (unfiltered)", "sdp", answer.SDP) - } - if err = p.publisher.pc.SetLocalDescription(answer); err != nil { - prometheus.ServiceOperationCounter.WithLabelValues("answer", "error", "local_description").Add(1) - return errors.Wrap(err, "could not set local description") - } - - // - // Filter after setting local description as pion expects the answer - // to match between CreateAnswer and SetLocalDescription. - // Filtered answer is sent to remote so that remote does not - // see filtered candidates. - // - answer = p.publisher.FilterCandidates(answer) - if p.iceConfig.PreferPubTcp { - p.publisher.Logger().Infow("local answer (filtered)", "sdp", answer.SDP) - } - err = p.writeMessage(&livekit.SignalResponse{ +func (p *ParticipantImpl) onPublisherAnswer(answer webrtc.SessionDescription) { + p.params.Logger.Infow("sending answer", "transport", livekit.SignalTarget_PUBLISHER) + if err := p.writeMessage(&livekit.SignalResponse{ Message: &livekit.SignalResponse_Answer{ Answer: ToProtoSessionDescription(answer), }, - }) - if err != nil { + }); err != nil { prometheus.ServiceOperationCounter.WithLabelValues("answer", "error", "write_message").Add(1) - return err + return } if p.isPublisher.Load() != p.CanPublish() { p.isPublisher.Store(p.CanPublish()) // trigger update as well if participant is already fully connected - if p.State() == livekit.ParticipantInfo_ACTIVE && onParticipantUpdate != nil { - onParticipantUpdate(p) + if p.State() == livekit.ParticipantInfo_ACTIVE { + p.lock.RLock() + onParticipantUpdate := p.onParticipantUpdate + p.lock.RUnlock() + + if onParticipantUpdate != nil { + onParticipantUpdate(p) + } } } @@ -629,8 +430,6 @@ func (p *ParticipantImpl) createPublsiherAnswerAndSend() error { if p.MigrateState() == types.MigrateStateSync { go p.handleMigrateMutedTrack() } - - return nil } func (p *ParticipantImpl) handleMigrateMutedTrack() { @@ -687,69 +486,9 @@ func (p *ParticipantImpl) SetMigrateInfo(previousAnswer *webrtc.SessionDescripti for _, t := range mediaTracks { p.pendingTracks[t.GetCid()] = &pendingTrackInfo{trackInfos: []*livekit.TrackInfo{t.GetTrack()}, migrated: true} } - p.pendingDataChannels = dataChannels p.pendingTracksLock.Unlock() - if p.SubscriberAsPrimary() { - if err := p.createDataChannelForSubscriberAsPrimary(dataChannels); err != nil { - p.params.Logger.Errorw("create data channel failed", err) - } - } - - p.subscriber.SetPreviousAnswer(previousAnswer) -} - -// HandleAnswer handles a client answer response, with subscriber PC, server initiates the -// offer and client answers -func (p *ParticipantImpl) HandleAnswer(answer webrtc.SessionDescription) error { - if answer.Type != webrtc.SDPTypeAnswer { - return ErrUnexpectedOffer - } - - // filter before setting remote description so that pion does not see filtered remote candidates - if p.iceConfig.PreferSubTcp { - p.subscriber.Logger().Infow("remote answer (unfiltered)", "sdp", answer.SDP) - } - modifiedAnswer := p.subscriber.FilterCandidates(answer) - if p.iceConfig.PreferSubTcp { - p.subscriber.Logger().Infow("remote answer (filtered)", "sdp", modifiedAnswer.SDP) - } - if err := p.subscriber.SetRemoteDescription(modifiedAnswer); err != nil { - return errors.Wrap(err, "could not set remote description") - } - - return nil -} - -// AddICECandidate adds candidates for remote peer -func (p *ParticipantImpl) AddICECandidate(candidate webrtc.ICECandidateInit, target livekit.SignalTarget) error { - var filterOut bool - var pcTransport *PCTransport - p.lock.RLock() - if target == livekit.SignalTarget_SUBSCRIBER { - if p.iceConfig.PreferSubTcp && !strings.Contains(candidate.Candidate, "tcp") { - filterOut = true - pcTransport = p.subscriber - } - } else if target == livekit.SignalTarget_PUBLISHER { - if p.iceConfig.PreferPubTcp && !strings.Contains(candidate.Candidate, "tcp") { - filterOut = true - pcTransport = p.publisher - } - } - p.lock.RUnlock() - if filterOut { - pcTransport.Logger().Infow("filtering out remote candidate", "candidate", candidate.Candidate) - return nil - } - - var err error - if target == livekit.SignalTarget_PUBLISHER { - err = p.publisher.AddICECandidate(candidate) - } else { - err = p.subscriber.AddICECandidate(candidate) - } - return err + p.TransportManager.SetMigrateInfo(previousAnswer, dataChannels) } func (p *ParticipantImpl) Start() { @@ -815,8 +554,7 @@ func (p *ParticipantImpl) Close(sendLeave bool, reason types.ParticipantCloseRea dt.CloseWithFlush(sendLeave) } - p.publisher.Close() - p.subscriber.Close() + p.TransportManager.Close() }() return nil } @@ -825,48 +563,31 @@ func (p *ParticipantImpl) Close(sendLeave bool, reason types.ParticipantCloseRea // negotiate task and negotiate immediately func (p *ParticipantImpl) Negotiate(force bool) { if p.MigrateState() != types.MigrateStateInit { - p.subscriber.Negotiate(force) + p.TransportManager.NegotiateSubscriber(force) } } -func (p *ParticipantImpl) AddNegotiationPending(publisherID livekit.ParticipantID) { - p.subscriber.AddNegotiationPending(publisherID) -} - -func (p *ParticipantImpl) IsNegotiationPending(publisherID livekit.ParticipantID) bool { - return p.subscriber.IsNegotiationPending(publisherID) -} - func (p *ParticipantImpl) SetMigrateState(s types.MigrateState) { - p.lock.Lock() preState := p.MigrateState() if preState == types.MigrateStateComplete || preState == s { - p.lock.Unlock() return } p.params.Logger.Debugw("SetMigrateState", "state", s) - var pendingOffer *webrtc.SessionDescription + processPendingOffer := false p.migrateState.Store(s) if s == types.MigrateStateSync { - pendingOffer = p.pendingOffer - p.pendingOffer = nil + processPendingOffer = true } - p.lock.Unlock() if s == types.MigrateStateComplete { - p.pendingTracksLock.Lock() - pendingDataChannels := p.pendingDataChannels - p.pendingDataChannels = nil - p.pendingTracksLock.Unlock() - - p.handlePendingPublisherDataChannels(pendingDataChannels) + p.TransportManager.ProcessPendingPublisherDataChannels() } - if pendingOffer != nil { - err := p.HandleOffer(*pendingOffer) + if processPendingOffer { + err := p.TransportManager.ProcessPendingPublisherOffer() if err != nil { - p.GetLogger().Errorw("could not handle offer", err) + p.params.Logger.Errorw("could not handle pending offer during migration", err) } } } @@ -877,22 +598,11 @@ func (p *ParticipantImpl) MigrateState() types.MigrateState { // ICERestart restarts subscriber ICE connections func (p *ParticipantImpl) ICERestart(iceConfig *types.IceConfig) error { - if iceConfig != nil { - p.SetICEConfig(*iceConfig) - } - - if p.subscriber.pc.RemoteDescription() == nil { - // not connected, skip - return nil - } - for _, t := range p.GetPublishedTracks() { t.(types.LocalMediaTrack).Restart() } - return p.subscriber.CreateAndSendOffer(&webrtc.OfferOptions{ - ICERestart: true, - }) + return p.TransportManager.ICERestart(iceConfig) } func (p *ParticipantImpl) OnICEConfigChanged(f func(participant types.LocalParticipant, iceConfig types.IceConfig)) { @@ -901,26 +611,6 @@ func (p *ParticipantImpl) OnICEConfigChanged(f func(participant types.LocalParti p.lock.Unlock() } -func (p *ParticipantImpl) SetICEConfig(iceConfig types.IceConfig) { - p.params.Logger.Infow("setting ICE config", "iceConfig", iceConfig) - p.lock.Lock() - p.iceConfig = iceConfig - if iceConfig.PreferPubTcp { - p.publisher.SetPreferTCP(true) - } - - if iceConfig.PreferSubTcp { - p.subscriber.SetPreferTCP(true) - } - - onICEConfigChanged := p.onICEConfigChanged - p.lock.Unlock() - - if onICEConfigChanged != nil { - onICEConfigChanged(p, iceConfig) - } -} - // // signal connection methods // @@ -1036,14 +726,6 @@ func (p *ParticipantImpl) IsRecorder() bool { return p.grants.Video.Recorder } -func (p *ParticipantImpl) SubscriberAsPrimary() bool { - return p.subscriberAsPrimary -} - -func (p *ParticipantImpl) SubscriberPC() *webrtc.PeerConnection { - return p.subscriber.pc -} - func (p *ParticipantImpl) UpdateSubscribedTrackSettings(trackID livekit.TrackID, settings *livekit.UpdateTrackSettings) error { p.lock.Lock() p.subscribedTracksSettings[trackID] = settings @@ -1083,10 +765,10 @@ func (p *ParticipantImpl) AddSubscribedTrack(subTrack types.SubscribedTrack) { p.lock.Unlock() subTrack.OnBind(func() { - if p.firstConnected.Load() { + if p.TransportManager.HasSubscriberEverConnected() { subTrack.DownTrack().SetConnected() } - p.subscriber.AddTrack(subTrack) + p.TransportManager.AddSubscribedTrack(subTrack) }) if settings != nil { @@ -1139,7 +821,7 @@ func (p *ParticipantImpl) RemoveSubscribedTrack(subTrack types.SubscribedTrack) } p.lock.Unlock() - p.subscriber.RemoveTrack(subTrack) + p.TransportManager.RemoveSubscribedTrack(subTrack) if numRemaining == 0 { // @@ -1206,6 +888,62 @@ func (p *ParticipantImpl) UpdateRTT(rtt uint32) { } } +func (p *ParticipantImpl) setupTransportManager() error { + tm, err := NewTransportManager(TransportManagerParams{ + Identity: p.params.Identity, + SID: p.params.SID, + // primary connection does not change, canSubscribe can change if permission was updated + // after the participant has joined + SubscriberAsPrimary: p.ProtocolVersion().SubscriberAsPrimary() && p.CanSubscribe(), + Config: p.params.Config, + ProtocolVersion: p.params.ProtocolVersion, + Telemetry: p.params.Telemetry, + CongestionControlConfig: p.params.CongestionControlConfig, + EnabledCodecs: p.params.EnabledCodecs, + SimTracks: p.params.SimTracks, + ClientConf: p.params.ClientConf, + Migration: p.params.Migration, + AllowTCPFallback: p.params.AllowTCPFallback, + Logger: p.params.Logger, + }) + if err != nil { + return err + } + + tm.OnICEConfigChanged(func(iceConfig types.IceConfig) { + p.lock.RLock() + onICEConfigChanged := p.onICEConfigChanged + p.lock.RUnlock() + + if onICEConfigChanged != nil { + onICEConfigChanged(p, iceConfig) + } + }) + + tm.OnPublisherICECandidate(func(c *webrtc.ICECandidate) { + p.onICECandidate(c, livekit.SignalTarget_PUBLISHER) + }) + tm.OnPublisherGetDTX(p.onPublisherGetDTX) + tm.OnPublisherAnswer(p.onPublisherAnswer) + tm.OnPublisherTrack(p.onMediaTrack) + + tm.OnSubscriberOffer(p.onSubscriberOffer) + tm.OnSubscriberICECandidate(func(c *webrtc.ICECandidate) { + p.onICECandidate(c, livekit.SignalTarget_SUBSCRIBER) + }) + tm.OnSubscriberInitialConnected(p.onSubscriberInitialConnected) + tm.OnSubscriberNegotiationFailed(p.handleSubscriberNegotiationFailed) + tm.OnSubscriberStreamStateChange(p.onStreamStateChange) + + tm.OnPrimaryTransportInitialConnected(p.onPrimaryTransportInitialConnected) + tm.OnPrimaryTransportFullyEstablished(p.onPrimaryTransportFullyEstablished) + tm.OnAnyTransportFailed(p.onAnyTransportFailed) + + tm.OnDataMessage(p.onDataMessage) + p.TransportManager = tm + return nil +} + func (p *ParticipantImpl) setupUpTrackManager() { p.UpTrackManager = NewUpTrackManager(UpTrackManagerParams{ SID: p.params.SID, @@ -1247,12 +985,13 @@ func (p *ParticipantImpl) updateState(state livekit.ParticipantInfo_State) { } // when the server has an offer for participant -func (p *ParticipantImpl) onOffer(offer webrtc.SessionDescription) { +func (p *ParticipantImpl) onSubscriberOffer(offer webrtc.SessionDescription) { if p.State() == livekit.ParticipantInfo_DISCONNECTED { // skip when disconnected return } + p.params.Logger.Infow("sending offer", "transport", livekit.SignalTarget_SUBSCRIBER) err := p.writeMessage(&livekit.SignalResponse{ Message: &livekit.SignalResponse_Offer{ Offer: ToProtoSessionDescription(offer), @@ -1302,35 +1041,11 @@ func (p *ParticipantImpl) onMediaTrack(track *webrtc.TrackRemote, rtpReceiver *w } } -func (p *ParticipantImpl) onDataChannel(dc *webrtc.DataChannel) { - if p.State() == livekit.ParticipantInfo_DISCONNECTED { +func (p *ParticipantImpl) onDataMessage(kind livekit.DataPacket_Kind, data []byte) { + if p.State() == livekit.ParticipantInfo_DISCONNECTED || !p.CanPublishData() { return } - switch dc.Label() { - case ReliableDataChannel: - p.lock.Lock() - p.reliableDC = dc - p.lock.Unlock() - dc.OnMessage(func(msg webrtc.DataChannelMessage) { - if p.CanPublishData() { - p.handleDataMessage(livekit.DataPacket_RELIABLE, msg.Data) - } - }) - case LossyDataChannel: - p.lock.Lock() - p.lossyDC = dc - p.lock.Unlock() - dc.OnMessage(func(msg webrtc.DataChannelMessage) { - if p.CanPublishData() { - p.handleDataMessage(livekit.DataPacket_LOSSY, msg.Data) - } - }) - default: - p.params.Logger.Warnw("unsupported datachannel added", nil, "label", dc.Label()) - } -} -func (p *ParticipantImpl) handleDataMessage(kind livekit.DataPacket_Kind, data []byte) { dp := livekit.DataPacket{} if err := proto.Unmarshal(data, &dp); err != nil { p.params.Logger.Warnw("could not parse data packet", err) @@ -1355,112 +1070,55 @@ func (p *ParticipantImpl) handleDataMessage(kind livekit.DataPacket_Kind, data [ } } -func (p *ParticipantImpl) getTransport(isPrimary bool) *PCTransport { - pcTransport := p.publisher - if (isPrimary && p.SubscriberAsPrimary()) || (!isPrimary && !p.SubscriberAsPrimary()) { - pcTransport = p.subscriber +func (p *ParticipantImpl) onICECandidate(c *webrtc.ICECandidate, target livekit.SignalTarget) { + if c == nil || p.State() == livekit.ParticipantInfo_DISCONNECTED { + return } - return pcTransport + if target == livekit.SignalTarget_SUBSCRIBER && p.MigrateState() == types.MigrateStateInit { + return + } + + p.sendIceCandidate(c, target) } -func (p *ParticipantImpl) handleICEConnected(isPrimary bool) { - pcTransport := p.getTransport(isPrimary) - pcTransport.SetICEConnectedAt(time.Now()) +func (p *ParticipantImpl) onSubscriberInitialConnected() { + p.setDowntracksConnected() +} - if pair, err := pcTransport.GetSelectedPair(); err != nil { - pcTransport.Logger().Errorw("error getting selected ICE candidate pair", err) - } else { - pcTransport.Logger().Infow("selected ICE candidate pair", "pair", pair) +func (p *ParticipantImpl) onPrimaryTransportInitialConnected() { + if !p.hasPendingMigratedTrack() && p.MigrateState() == types.MigrateStateSync { + p.SetMigrateState(types.MigrateStateComplete) } } -func (p *ParticipantImpl) handleConnectionFailed(isPrimary bool) { - pcTransport := p.getTransport(isPrimary) - isShort, duration := pcTransport.IsShortConnection(time.Now()) - if isShort { - // irrespective of which one fails, force TCP on both as the other one might - // fail at a different time and cause another disruption - pair, err := pcTransport.GetSelectedPair() - if err != nil { - pcTransport.Logger().Errorw("short ICE connection", err, "duration", duration) - } else { - pcTransport.Logger().Infow("short ICE connection", "pair", pair, "duration", duration) +func (p *ParticipantImpl) onPrimaryTransportFullyEstablished() { + p.updateState(livekit.ParticipantInfo_ACTIVE) +} + +func (p *ParticipantImpl) onAnyTransportFailed() { + // clients support resuming of connections when websocket becomes disconnected + p.closeSignalConnection() + + // detect when participant has actually left. + p.lock.Lock() + if p.disconnectTimer != nil { + p.disconnectTimer.Stop() + p.disconnectTimer = nil + } + p.disconnectTimer = time.AfterFunc(disconnectCleanupDuration, func() { + p.lock.Lock() + p.disconnectTimer.Stop() + p.disconnectTimer = nil + p.lock.Unlock() + + if p.isClosed.Load() || p.State() == livekit.ParticipantInfo_DISCONNECTED { + return } - if p.params.AllowTCPFallback { - pcTransport.Logger().Infow("restricting transport to TCP on both peer connections") - p.SetICEConfig(types.IceConfig{ - PreferPubTcp: true, - PreferSubTcp: true, - }) - } - } -} - -func (p *ParticipantImpl) handleICEStateChange(isPrimary bool, state webrtc.ICEConnectionState) { - if state == webrtc.ICEConnectionStateConnected { - p.handleICEConnected(isPrimary) - } else if state == webrtc.ICEConnectionStateFailed { - p.handleConnectionFailed(isPrimary) - } -} - -func (p *ParticipantImpl) handlePrimaryStateChange(state webrtc.PeerConnectionState) { - if state == webrtc.PeerConnectionStateConnected { - if !p.firstConnected.Swap(true) { - p.setDowntracksConnected() - } - prometheus.ServiceOperationCounter.WithLabelValues("ice_connection", "success", "").Add(1) - if !p.hasPendingMigratedTrack() && p.MigrateState() == types.MigrateStateSync { - p.SetMigrateState(types.MigrateStateComplete) - } - p.incActiveCounter() - } else if state == webrtc.PeerConnectionStateFailed { - p.handleConnectionFailed(true) - - // clients support resuming of connections when websocket becomes disconnected - p.closeSignalConnection() - - // detect when participant has actually left. - go func() { - p.lock.Lock() - if p.disconnectTimer != nil { - p.disconnectTimer.Stop() - p.disconnectTimer = nil - } - p.disconnectTimer = time.AfterFunc(disconnectCleanupDuration, func() { - p.lock.Lock() - p.disconnectTimer.Stop() - p.disconnectTimer = nil - p.lock.Unlock() - - if p.isClosed.Load() || p.State() == livekit.ParticipantInfo_DISCONNECTED { - return - } - primaryPC := p.publisher.pc - if p.SubscriberAsPrimary() { - primaryPC = p.subscriber.pc - } - if primaryPC.ConnectionState() != webrtc.PeerConnectionStateConnected { - p.params.Logger.Infow("closing disconnected participant") - _ = p.Close(true, types.ParticipantCloseReasonPeerConnectionDisconnected) - } - }) - p.lock.Unlock() - }() - - } -} - -// for the secondary peer connection, we still need to handle when they become disconnected -// instead of allowing them to silently fail. -func (p *ParticipantImpl) handleSecondaryStateChange(state webrtc.PeerConnectionState) { - if state == webrtc.PeerConnectionStateFailed { - p.handleConnectionFailed(false) - - // clients support resuming of connections when websocket becomes disconnected - p.closeSignalConnection() - } + p.params.Logger.Infow("closing disconnected participant") + _ = p.Close(true, types.ParticipantCloseReasonPeerConnectionDisconnected) + }) + p.lock.Unlock() } // downTracksRTCPWorker sends SenderReports periodically when the participant is subscribed to @@ -1473,9 +1131,6 @@ func (p *ParticipantImpl) downTracksRTCPWorker() { if p.State() == livekit.ParticipantInfo_DISCONNECTED { return } - if p.subscriber.pc.ConnectionState() != webrtc.PeerConnectionStateConnected { - continue - } var srs []rtcp.Packet var sd []rtcp.SourceDescriptionChunk @@ -1514,11 +1169,11 @@ func (p *ParticipantImpl) downTracksRTCPWorker() { batch = sd[:size] sd = sd[size:] pkts = append(pkts, &rtcp.SourceDescription{Chunks: batch}) - if err := p.subscriber.pc.WriteRTCP(pkts); err != nil { + if err := p.TransportManager.WriteSubscriberRTCP(pkts); err != nil { if err == io.EOF || err == io.ErrClosedPipe { return } - logger.Errorw("could not send down track reports", err) + p.params.Logger.Errorw("could not send down track reports", err) } } @@ -1528,90 +1183,6 @@ func (p *ParticipantImpl) downTracksRTCPWorker() { } } -func (p *ParticipantImpl) configureReceiverDTX() { - // - // DTX (Discontinuous Transmission) allows audio bandwidth saving - // by not sending packets during silence periods. - // - // Publisher side DTX can enabled by included `usedtx=1` in - // the `fmtp` line corresponding to audio codec (Opus) in SDP. - // By doing this in the SDP `answer`, it can be controlled from - // server side and avoid doing it in all the client SDKs. - // - // Ideally, a publisher should be able to specify per audio - // track if DTX should be enabled. But, translating the - // DTX preference of publisher to the correct transceiver - // is non-deterministic due to the lack of a synchronizing id - // like the track id. The codec preference to set DTX needs - // to be done - // - after calling `SetRemoteDescription` which sets up - // the transceivers, but there are no tracks in the - // transceiver yet - // - before calling `CreateAnswer` - // Due to the absence of tracks when it is required to set DTX, - // it is not possible to cross reference against a pending track - // with the same track id. - // - // Due to the restriction above and given that in practice - // most of the time there is going to be only one audio track - // that is published, do the following - // - if there is no pending audio track, no-op - // - if there are no audio transceivers without tracks, no-op - // - else, apply the DTX setting from pending audio track - // to the audio transceiver without no tracks - // - // NOTE: The above logic will fail if there is an `offer` SDP with - // multiple audio tracks. At that point, there might be a need to - // rely on something like order of tracks. TODO - // - enableDTX := p.getDTX() - transceivers := p.publisher.pc.GetTransceivers() - for _, transceiver := range transceivers { - if transceiver.Kind() != webrtc.RTPCodecTypeAudio { - continue - } - - receiver := transceiver.Receiver() - if receiver == nil || receiver.Track() != nil { - continue - } - - var modifiedReceiverCodecs []webrtc.RTPCodecParameters - - receiverCodecs := receiver.GetParameters().Codecs - for _, receiverCodec := range receiverCodecs { - if receiverCodec.MimeType == webrtc.MimeTypeOpus { - fmtpUseDTX := "usedtx=1" - // remove occurrence in the middle - sdpFmtpLine := strings.ReplaceAll(receiverCodec.SDPFmtpLine, fmtpUseDTX+";", "") - // remove occurrence at the end - sdpFmtpLine = strings.ReplaceAll(sdpFmtpLine, fmtpUseDTX, "") - if enableDTX { - sdpFmtpLine += ";" + fmtpUseDTX - } - receiverCodec.SDPFmtpLine = sdpFmtpLine - } - modifiedReceiverCodecs = append(modifiedReceiverCodecs, receiverCodec) - } - - // - // As `SetCodecPreferences` on a transceiver replaces all codecs, - // cycle through sender codecs also and add them before calling - // `SetCodecPreferences` - // - var senderCodecs []webrtc.RTPCodecParameters - sender := transceiver.Sender() - if sender != nil { - senderCodecs = sender.GetParameters().Codecs - } - - err := transceiver.SetCodecPreferences(append(modifiedReceiverCodecs, senderCodecs...)) - if err != nil { - p.params.Logger.Warnw("failed to SetCodecPreferences", err) - } - } -} - func (p *ParticipantImpl) onStreamStateChange(update *sfu.StreamStateUpdate) error { if len(update.StreamStates) == 0 { return nil @@ -1805,7 +1376,7 @@ func (p *ParticipantImpl) getPublisherConnectionQuality() map[livekit.TrackID]fl return scores } -func (p *ParticipantImpl) getDTX() bool { +func (p *ParticipantImpl) onPublisherGetDTX() bool { p.pendingTracksLock.RLock() defer p.pendingTracksLock.RUnlock() @@ -1834,13 +1405,12 @@ func (p *ParticipantImpl) mediaTrackReceived(track *webrtc.TrackRemote, rtpRecei newTrack := false p.params.Logger.Debugw("media track received", "trackID", track.ID(), "kind", track.Kind()) - var mid string - for _, tr := range p.publisher.pc.GetTransceivers() { - if tr.Receiver() == rtpReceiver { - mid = tr.Mid() - break - } + mid := p.TransportManager.GetPublisherMid(rtpReceiver) + if mid == "" { + p.params.Logger.Warnw("could not get mid for track", nil, "trackID", track.ID()) + return nil, false } + // use existing media track to handle simulcast mt, ok := p.getPublishedTrackBySdpCid(track.ID()).(*MediaTrack) if !ok { @@ -1872,13 +1442,7 @@ func (p *ParticipantImpl) mediaTrackReceived(track *webrtc.TrackRemote, rtpRecei func (p *ParticipantImpl) addMigrateMutedTrack(cid string, ti *livekit.TrackInfo) *MediaTrack { p.params.Logger.Debugw("add migrate muted track", "cid", cid, "track", ti.String()) - var rtpReceiver *webrtc.RTPReceiver - for _, tr := range p.publisher.pc.GetTransceivers() { - if tr.Mid() == ti.Mid { - rtpReceiver = tr.Receiver() - break - } - } + rtpReceiver := p.TransportManager.GetPublisherRTPReceiver(ti.Mid) if rtpReceiver == nil { p.params.Logger.Errorw("could not find receiver for migrated track", nil, "track", ti.Sid) return nil @@ -2121,7 +1685,7 @@ func (p *ParticipantImpl) rtcpSendWorker() { return } - if err := p.publisher.pc.WriteRTCP(pkts); err != nil { + if err := p.TransportManager.WritePublisherRTCP(pkts); err != nil { p.params.Logger.Errorw("could not write RTCP to participant", err) } } @@ -2164,49 +1728,6 @@ func (p *ParticipantImpl) DebugInfo() map[string]interface{} { return info } -func (p *ParticipantImpl) handlePendingPublisherDataChannels(pendingDataChannels []*livekit.DataChannelInfo) { - ordered := true - negotiated := true - - p.lock.RLock() - lossyDC := p.lossyDC - reliableDC := p.reliableDC - p.lock.RUnlock() - - for _, ci := range pendingDataChannels { - var ( - dc *webrtc.DataChannel - err error - ) - if ci.Target == livekit.SignalTarget_SUBSCRIBER { - continue - } - if ci.Label == LossyDataChannel && lossyDC == nil { - retransmits := uint16(0) - id := uint16(ci.GetId()) - dc, err = p.publisher.pc.CreateDataChannel(LossyDataChannel, &webrtc.DataChannelInit{ - Ordered: &ordered, - MaxRetransmits: &retransmits, - Negotiated: &negotiated, - ID: &id, - }) - } else if ci.Label == ReliableDataChannel && reliableDC == nil { - id := uint16(ci.GetId()) - dc, err = p.publisher.pc.CreateDataChannel(ReliableDataChannel, &webrtc.DataChannelInit{ - Ordered: &ordered, - Negotiated: &negotiated, - ID: &id, - }) - } - if err != nil { - p.params.Logger.Errorw("create migrated data channel failed", err, "label", ci.Label) - } else if dc != nil { - p.params.Logger.Debugw("create migrated data channel", "label", dc.Label(), "id", dc.ID()) - p.onDataChannel(dc) - } - } -} - func (p *ParticipantImpl) GetSubscribedTracks() []types.SubscribedTrack { p.lock.RLock() defer p.lock.RUnlock() @@ -2218,12 +1739,6 @@ func (p *ParticipantImpl) GetSubscribedTracks() []types.SubscribedTrack { return tracks } -func (p *ParticipantImpl) incActiveCounter() { - if p.activeCounter.Inc() == stateActiveCond { - p.updateState(livekit.ParticipantInfo_ACTIVE) - } -} - func (p *ParticipantImpl) postRtcp(pkts []rtcp.Packet) { select { case p.rtcpCh <- pkts: @@ -2275,8 +1790,8 @@ func (p *ParticipantImpl) GetCachedDownTrack(trackID livekit.TrackID) (*webrtc.R return nil, sfu.ForwarderState{} } -func (p *ParticipantImpl) handleNegotiationFailed() { - p.params.Logger.Infow("negotiation failed, starting full reconnect") +func (p *ParticipantImpl) handleSubscriberNegotiationFailed() { + p.params.Logger.Infow("subscriber negotiation failed, starting full reconnect") _ = p.writeMessage(&livekit.SignalResponse{ Message: &livekit.SignalResponse_Leave{ Leave: &livekit.LeaveRequest{ diff --git a/pkg/rtc/participant_internal_test.go b/pkg/rtc/participant_internal_test.go index 50c6bc2d..a25a633b 100644 --- a/pkg/rtc/participant_internal_test.go +++ b/pkg/rtc/participant_internal_test.go @@ -7,6 +7,7 @@ import ( "github.com/pion/webrtc/v3" "github.com/stretchr/testify/require" + "go.uber.org/atomic" "google.golang.org/protobuf/proto" "github.com/livekit/protocol/auth" @@ -19,6 +20,7 @@ import ( "github.com/livekit/livekit-server/pkg/rtc/types" "github.com/livekit/livekit-server/pkg/rtc/types/typesfakes" "github.com/livekit/livekit-server/pkg/sfu/connectionquality" + "github.com/livekit/livekit-server/pkg/testutils" ) func TestIsReady(t *testing.T) { @@ -678,17 +680,28 @@ func TestDisableCodecs(t *testing.T) { sink := &routingfakes.FakeMessageSink{} participant.SetResponseSink(sink) var answer webrtc.SessionDescription + var answerReceived atomic.Bool sink.WriteMessageStub = func(msg proto.Message) error { if res, ok := msg.(*livekit.SignalResponse); ok { if res.GetAnswer() != nil { answer = FromProtoSessionDescription(res.GetAnswer()) + answerReceived.Store(true) } } return nil } err = participant.HandleOffer(sdp) require.NoError(t, err) + + testutils.WithTimeout(t, func() string { + if answerReceived.Load() { + return "" + } else { + return "answer not received" + } + }) require.NoError(t, pc.SetRemoteDescription(answer), answer.SDP, sdp.SDP) + codecs = transceiver.Receiver().GetParameters().Codecs found264 = false for _, c := range codecs { diff --git a/pkg/rtc/participant_signal.go b/pkg/rtc/participant_signal.go index e416e6d4..d1670880 100644 --- a/pkg/rtc/participant_signal.go +++ b/pkg/rtc/participant_signal.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/pion/webrtc/v3" - "google.golang.org/protobuf/proto" "github.com/livekit/protocol/livekit" @@ -110,30 +109,7 @@ func (p *ParticipantImpl) SendDataPacket(dp *livekit.DataPacket) error { return ErrDataChannelUnavailable } - data, err := proto.Marshal(dp) - if err != nil { - return err - } - - var dc *webrtc.DataChannel - if dp.Kind == livekit.DataPacket_RELIABLE { - if p.SubscriberAsPrimary() { - dc = p.reliableDCSub - } else { - dc = p.reliableDC - } - } else { - if p.SubscriberAsPrimary() { - dc = p.lossyDCSub - } else { - dc = p.lossyDC - } - } - - if dc == nil { - return ErrDataChannelUnavailable - } - return dc.Send(data) + return p.TransportManager.SendDataPacket(dp) } func (p *ParticipantImpl) SendRoomUpdate(room *livekit.Room) error { @@ -163,32 +139,8 @@ func (p *ParticipantImpl) SendRefreshToken(token string) error { } func (p *ParticipantImpl) sendIceCandidate(c *webrtc.ICECandidate, target livekit.SignalTarget) { - var filterOut bool - var pcTransport *PCTransport - p.lock.RLock() - if target == livekit.SignalTarget_SUBSCRIBER { - if p.iceConfig.PreferSubTcp && c.Protocol != webrtc.ICEProtocolTCP { - filterOut = true - pcTransport = p.subscriber - } - } else if target == livekit.SignalTarget_PUBLISHER { - if p.iceConfig.PreferPubTcp && c.Protocol != webrtc.ICEProtocolTCP { - filterOut = true - pcTransport = p.publisher - } - } - p.lock.RUnlock() - if filterOut { - pcTransport.Logger().Infow("filtering out local candidate", "candidate", c) - return - } - - ci := c.ToJSON() - - // write candidate - p.params.Logger.Debugw("sending ice candidates", - "candidate", c.String(), "target", target) - trickle := ToProtoTrickle(ci) + p.params.Logger.Infow("sending ice candidate", "candidate", c.String(), "target", target) + trickle := ToProtoTrickle(c.ToJSON()) trickle.Target = target _ = p.writeMessage(&livekit.SignalResponse{ Message: &livekit.SignalResponse_Trickle{ diff --git a/pkg/rtc/transport.go b/pkg/rtc/transport.go index 0059c49e..4ea77c9f 100644 --- a/pkg/rtc/transport.go +++ b/pkg/rtc/transport.go @@ -13,9 +13,11 @@ import ( "github.com/pion/interceptor/pkg/cc" "github.com/pion/interceptor/pkg/gcc" "github.com/pion/interceptor/pkg/twcc" + "github.com/pion/rtcp" "github.com/pion/sdp/v3" "github.com/pion/webrtc/v3" "go.uber.org/atomic" + "google.golang.org/protobuf/proto" "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" @@ -29,6 +31,9 @@ import ( ) const ( + LossyDataChannel = "_lossy" + ReliableDataChannel = "_reliable" + negotiationFrequency = 150 * time.Millisecond negotiationFailedTimout = 15 * time.Second dtlsRetransmissionInterval = 100 * time.Millisecond @@ -63,13 +68,28 @@ type PCTransport struct { pc *webrtc.PeerConnection me *webrtc.MediaEngine - lock sync.RWMutex - iceConnectedAt time.Time + lock sync.RWMutex + + reliableDC *webrtc.DataChannel + reliableDCOpened bool + lossyDC *webrtc.DataChannel + lossyDCOpened bool + onDataPacket func(kind livekit.DataPacket_Kind, data []byte) + + iceConnectedAt time.Time + connectedAt time.Time + + onFullyEstablished func() + pendingCandidates []webrtc.ICECandidateInit debouncedNegotiate func(func()) negotiationPending map[livekit.ParticipantID]bool + onICECandidate func(c *webrtc.ICECandidate) onOffer func(offer webrtc.SessionDescription) - onRemoteDescripitonSettled func() error + onAnswer func(offer webrtc.SessionDescription) + onRemoteDescriptionSettled func() error + onInitialConnected func() + onFailed func(isShortLived bool) restartAfterGathering bool restartAtNextOffer bool negotiationState int @@ -226,7 +246,7 @@ func (t *PCTransport) Logger() logger.Logger { return t.params.Logger } -func (t *PCTransport) SetICEConnectedAt(at time.Time) { +func (t *PCTransport) setICEConnectedAt(at time.Time) { t.lock.Lock() if t.iceConnectedAt.IsZero() { // @@ -234,11 +254,12 @@ func (t *PCTransport) SetICEConnectedAt(at time.Time) { // This prevents reset of connected at time if ICE goes `Connected` -> `Disconnected` -> `Connected`. // t.iceConnectedAt = at + prometheus.ServiceOperationCounter.WithLabelValues("ice_connection", "success", "").Add(1) } t.lock.Unlock() } -func (t *PCTransport) IsShortConnection(at time.Time) (bool, time.Duration) { +func (t *PCTransport) isShortConnection(at time.Time) (bool, time.Duration) { t.lock.RLock() defer t.lock.RUnlock() @@ -250,7 +271,7 @@ func (t *PCTransport) IsShortConnection(at time.Time) (bool, time.Duration) { return duration < shortConnectionThreshold, duration } -func (t *PCTransport) GetSelectedPair() (*webrtc.ICECandidatePair, error) { +func (t *PCTransport) getSelectedPair() (*webrtc.ICECandidatePair, error) { sctp := t.pc.SCTP() if sctp == nil { return nil, errors.New("no SCTP") @@ -269,6 +290,151 @@ func (t *PCTransport) GetSelectedPair() (*webrtc.ICECandidatePair, error) { return iceTransport.GetSelectedCandidatePair() } +func (t *PCTransport) setConnectedAt(at time.Time) bool { + t.lock.Lock() + if !t.connectedAt.IsZero() { + t.lock.Unlock() + return false + } + + t.connectedAt = at + prometheus.ServiceOperationCounter.WithLabelValues("peer_connection", "success", "").Add(1) + t.lock.Unlock() + return true +} + +func (t *PCTransport) onICEGatheringStateChange(state webrtc.ICEGathererState) { + if state != webrtc.ICEGathererStateComplete { + return + } + + go func() { + t.lock.Lock() + if t.restartAfterGathering { + t.params.Logger.Debugw("restarting ICE after ICE gathering") + if err := t.createAndSendOffer(&webrtc.OfferOptions{ICERestart: true}); err != nil { + t.params.Logger.Warnw("could not restart ICE", err) + } + t.lock.Unlock() + } else if t.pendingRestartIceOffer != nil { + t.params.Logger.Debugw("accept remote restart ice offer after ICE gathering") + offer := t.pendingRestartIceOffer + t.pendingRestartIceOffer = nil + t.lock.Unlock() + if err := t.SetRemoteDescription(*offer); err != nil { + t.params.Logger.Warnw("could not accept remote restart ice offer", err) + } + } else { + t.lock.Unlock() + } + }() +} + +func (t *PCTransport) onICECandidateTrickle(c *webrtc.ICECandidate) { + t.lock.RLock() + if t.preferTCP && c != nil && c.Protocol != webrtc.ICEProtocolTCP { + t.params.Logger.Infow("filtering out local candidate", "candidate", c.String()) + t.lock.RUnlock() + return + } + t.lock.RUnlock() + + if t.onICECandidate != nil { + t.onICECandidate(c) + } +} + +func (t *PCTransport) handleConnectionFailed() { + isShort, duration := t.isShortConnection(time.Now()) + if isShort { + pair, err := t.getSelectedPair() + if err != nil { + t.params.Logger.Errorw("short ICE connection", err, "duration", duration) + } else { + t.params.Logger.Infow("short ICE connection", "pair", pair, "duration", duration) + } + } + + if t.onFailed != nil { + t.onFailed(isShort) + } +} + +func (t *PCTransport) onICEConnectionStateChange(state webrtc.ICEConnectionState) { + t.params.Logger.Infow("ice connection state change", "state", state.String()) + switch state { + case webrtc.ICEConnectionStateConnected: + t.setICEConnectedAt(time.Now()) + if pair, err := t.getSelectedPair(); err != nil { + t.params.Logger.Errorw("error getting selected ICE candidate pair", err) + } else { + t.params.Logger.Infow("selected ICE candidate pair", "pair", pair) + } + case webrtc.ICEConnectionStateFailed: + t.handleConnectionFailed() + } +} + +func (t *PCTransport) onPeerConnectionStateChange(state webrtc.PeerConnectionState) { + t.params.Logger.Infow("peer connection state change", "state", state.String()) + switch state { + case webrtc.PeerConnectionStateConnected: + isInitialConnection := t.setConnectedAt(time.Now()) + if isInitialConnection { + if t.onInitialConnected != nil { + t.onInitialConnected() + } + + t.maybeNotifyFullyEstablished() + } + case webrtc.PeerConnectionStateFailed: + t.handleConnectionFailed() + } +} + +func (t *PCTransport) onDataChannel(dc *webrtc.DataChannel) { + switch dc.Label() { + case ReliableDataChannel: + t.params.Logger.Debugw("reliable data channel open") + t.lock.Lock() + t.reliableDC = dc + t.reliableDCOpened = true + t.lock.Unlock() + dc.OnMessage(func(msg webrtc.DataChannelMessage) { + if t.onDataPacket != nil { + t.onDataPacket(livekit.DataPacket_RELIABLE, msg.Data) + } + }) + + t.maybeNotifyFullyEstablished() + case LossyDataChannel: + t.params.Logger.Debugw("lossy data channel open") + t.lock.Lock() + t.lossyDC = dc + t.lossyDCOpened = true + t.lock.Unlock() + dc.OnMessage(func(msg webrtc.DataChannelMessage) { + if t.onDataPacket != nil { + t.onDataPacket(livekit.DataPacket_LOSSY, msg.Data) + } + }) + + t.maybeNotifyFullyEstablished() + default: + t.params.Logger.Warnw("unsupported datachannel added", nil, "label", dc.Label()) + } +} + +func (t *PCTransport) maybeNotifyFullyEstablished() { + t.lock.RLock() + fullyEstablished := t.reliableDCOpened && t.lossyDCOpened && !t.connectedAt.IsZero() + t.lock.RUnlock() + + if fullyEstablished && t.onFullyEstablished != nil { + t.onFullyEstablished() + } +} + func (t *PCTransport) SetPreferTCP(preferTCP bool) { t.lock.Lock() t.preferTCP = preferTCP @@ -285,30 +451,13 @@ func (t *PCTransport) createPeerConnection() error { } t.pc = pc - t.pc.OnICEGatheringStateChange(func(state webrtc.ICEGathererState) { - if state == webrtc.ICEGathererStateComplete { - go func() { - t.lock.Lock() - if t.restartAfterGathering { - t.params.Logger.Debugw("restarting ICE after ICE gathering") - if err := t.createAndSendOffer(&webrtc.OfferOptions{ICERestart: true}); err != nil { - t.params.Logger.Warnw("could not restart ICE", err) - } - t.lock.Unlock() - } else if t.pendingRestartIceOffer != nil { - t.params.Logger.Debugw("accept remote restart ice offer after ICE gathering") - offer := t.pendingRestartIceOffer - t.pendingRestartIceOffer = nil - t.lock.Unlock() - if err := t.SetRemoteDescription(*offer); err != nil { - t.params.Logger.Warnw("could not accept remote restart ice offer", err) - } - } else { - t.lock.Unlock() - } - }() - } - }) + t.pc.OnICEGatheringStateChange(t.onICEGatheringStateChange) + t.pc.OnICEConnectionStateChange(t.onICEConnectionStateChange) + t.pc.OnICECandidate(t.onICECandidateTrickle) + + t.pc.OnConnectionStateChange(t.onPeerConnectionStateChange) + + t.pc.OnDataChannel(t.onDataChannel) t.me = me @@ -327,8 +476,15 @@ func (t *PCTransport) AddICECandidate(candidate webrtc.ICECandidateInit) error { return nil } - t.params.Logger.Infow("add candidate ", "candidate", candidate.Candidate) + t.lock.RLock() + if t.preferTCP && !strings.Contains(candidate.Candidate, "tcp") { + t.lock.RUnlock() + t.params.Logger.Infow("filtering out remote candidate", "candidate", candidate.Candidate) + return nil + } + t.lock.RUnlock() + t.params.Logger.Infow("add candidate ", "candidate", candidate.Candidate) return t.pc.AddICECandidate(candidate) } @@ -336,11 +492,130 @@ func (t *PCTransport) PeerConnection() *webrtc.PeerConnection { return t.pc } +func (t *PCTransport) GetMid(rtpReceiver *webrtc.RTPReceiver) string { + for _, tr := range t.pc.GetTransceivers() { + if tr.Receiver() == rtpReceiver { + return tr.Mid() + } + } + + return "" +} + +func (t *PCTransport) GetRTPReceiver(mid string) *webrtc.RTPReceiver { + for _, tr := range t.pc.GetTransceivers() { + if tr.Mid() == mid { + return tr.Receiver() + } + } + + return nil +} + +func (t *PCTransport) CreateDataChannel(label string, dci *webrtc.DataChannelInit) error { + dc, err := t.pc.CreateDataChannel(label, dci) + if err != nil { + return err + } + + t.lock.Lock() + switch dc.Label() { + case ReliableDataChannel: + t.reliableDC = dc + t.reliableDC.OnOpen(func() { + t.params.Logger.Debugw("reliable data channel open") + t.lock.Lock() + t.reliableDCOpened = true + t.lock.Unlock() + + t.maybeNotifyFullyEstablished() + }) + case LossyDataChannel: + t.lossyDC = dc + t.lossyDC.OnOpen(func() { + t.params.Logger.Debugw("lossy data channel open") + t.lock.Lock() + t.lossyDCOpened = true + t.lock.Unlock() + + t.maybeNotifyFullyEstablished() + }) + default: + t.params.Logger.Errorw("unknown data channel label", nil, "label", dc.Label()) + } + t.lock.Unlock() + + return nil +} + +func (t *PCTransport) CreateDataChannelIfEmpty(dcLabel string, dci *webrtc.DataChannelInit) (label string, id uint16, existing bool, err error) { + t.lock.RLock() + var dc *webrtc.DataChannel + switch dcLabel { + case ReliableDataChannel: + dc = t.reliableDC + case LossyDataChannel: + dc = t.lossyDC + default: + t.params.Logger.Errorw("unknown data channel label", nil, "label", label) + err = errors.New("unknown data channel label") + } + t.lock.RUnlock() + if err != nil { + return + } + + if dc != nil { + return dc.Label(), *dc.ID(), true, nil + } + + dc, err = t.pc.CreateDataChannel(dcLabel, dci) + if err != nil { + return + } + + t.onDataChannel(dc) + return dc.Label(), *dc.ID(), false, nil +} + // IsEstablished returns true if the PeerConnection has been established func (t *PCTransport) IsEstablished() bool { return t.pc.ConnectionState() != webrtc.PeerConnectionStateNew } +func (t *PCTransport) HasEverConnected() bool { + t.lock.RLock() + defer t.lock.RUnlock() + + return !t.connectedAt.IsZero() +} + +func (t *PCTransport) WriteRTCP(pkts []rtcp.Packet) error { + return t.pc.WriteRTCP(pkts) +} + +func (t *PCTransport) SendDataPacket(dp *livekit.DataPacket) error { + data, err := proto.Marshal(dp) + if err != nil { + return err + } + + var dc *webrtc.DataChannel + t.lock.RLock() + if dp.Kind == livekit.DataPacket_RELIABLE { + dc = t.reliableDC + } else { + dc = t.lossyDC + } + t.lock.RUnlock() + + if dc == nil { + return ErrDataChannelUnavailable + } + + return dc.Send(data) +} + func (t *PCTransport) Close() { t.lock.Lock() if t.signalStateCheckTimer != nil { @@ -380,6 +655,14 @@ func (t *PCTransport) SetRemoteDescription(sd webrtc.SessionDescription) error { return nil } + // filter before setting remote description so that pion does not see filtered remote candidates + if t.preferTCP { + t.params.Logger.Infow("remote description (unfiltered)", "type", sd.Type, "sdp", sd.SDP) + } + sd = t.filterCandidates(sd) + if t.preferTCP { + t.params.Logger.Infow("remote description (filtered)", "type", sd.Type, "sdp", sd.SDP) + } if err := t.pc.SetRemoteDescription(sd); err != nil { t.lock.Unlock() return err @@ -413,11 +696,11 @@ func (t *PCTransport) SetRemoteDescription(sd webrtc.SessionDescription) error { t.params.Logger.Errorw("could not negotiate", err) } } - onRemoteDescripitonSettled := t.onRemoteDescripitonSettled + onRemoteDescriptionSettled := t.onRemoteDescriptionSettled t.lock.Unlock() - if onRemoteDescripitonSettled != nil { - return onRemoteDescripitonSettled() + if onRemoteDescriptionSettled != nil { + return onRemoteDescriptionSettled() } return nil } @@ -438,14 +721,42 @@ func (t *PCTransport) isRemoteOfferRestartICE(sd webrtc.SessionDescription) (str return credential, restartICE, nil } +func (t *PCTransport) OnICECandidate(f func(c *webrtc.ICECandidate)) { + t.onICECandidate = f +} + +func (t *PCTransport) OnInitialConnected(f func()) { + t.onInitialConnected = f +} + +func (t *PCTransport) OnFullyEstablished(f func()) { + t.onFullyEstablished = f +} + +func (t *PCTransport) OnFailed(f func(isShortLived bool)) { + t.onFailed = f +} + +func (t *PCTransport) OnTrack(f func(track *webrtc.TrackRemote, rtpReceiver *webrtc.RTPReceiver)) { + t.pc.OnTrack(f) +} + +func (t *PCTransport) OnDataPacket(f func(kind livekit.DataPacket_Kind, data []byte)) { + t.onDataPacket = 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) OnAnswer(f func(sd webrtc.SessionDescription)) { + t.onAnswer = f +} + func (t *PCTransport) OnRemoteDescripitonSettled(f func() error) { t.lock.Lock() - t.onRemoteDescripitonSettled = f + t.onRemoteDescriptionSettled = f t.lock.Unlock() } @@ -482,6 +793,126 @@ func (t *PCTransport) IsNegotiationPending(publisherID livekit.ParticipantID) bo return t.negotiationPending[publisherID] } +func (t *PCTransport) configureReceiverDTX(enableDTX bool) { + // + // DTX (Discontinuous Transmission) allows audio bandwidth saving + // by not sending packets during silence periods. + // + // Publisher side DTX can enabled by including `usedtx=1` in + // the `fmtp` line corresponding to audio codec (Opus) in SDP. + // By doing this in the SDP `answer`, it can be controlled from + // server side and avoid doing it in all the client SDKs. + // + // Ideally, a publisher should be able to specify per audio + // track if DTX should be enabled. But, translating the + // DTX preference of publisher to the correct transceiver + // is non-deterministic due to the lack of a synchronizing id + // like the track id. + // + // The codec preference to set DTX needs to be done + // - after calling `SetRemoteDescription` which sets up + // the transceivers, but only if there are no tracks in the + // transceiver yet + // - before calling `CreateAnswer` + // Due to the absence of tracks when it is required to set DTX, + // it is not possible to cross reference against a pending track + // with the same track id. + // + // Due to the restriction above and given that in practice + // most of the time there is going to be only one audio track + // that is published, do the following + // - if there is no pending audio track, no-op + // - if there are no audio transceivers without tracks, no-op + // - else, apply the DTX setting from pending audio track + // to the audio transceiver without any track + // + // NOTE: The above logic will fail if there is an `offer` SDP with + // multiple audio tracks. At that point, there might be a need to + // rely on something like order of tracks. TODO + // + transceivers := t.pc.GetTransceivers() + for _, transceiver := range transceivers { + if transceiver.Kind() != webrtc.RTPCodecTypeAudio { + continue + } + + receiver := transceiver.Receiver() + if receiver == nil || receiver.Track() != nil { + continue + } + + var modifiedReceiverCodecs []webrtc.RTPCodecParameters + + receiverCodecs := receiver.GetParameters().Codecs + for _, receiverCodec := range receiverCodecs { + if receiverCodec.MimeType == webrtc.MimeTypeOpus { + fmtpUseDTX := "usedtx=1" + // remove occurrence in the middle + sdpFmtpLine := strings.ReplaceAll(receiverCodec.SDPFmtpLine, fmtpUseDTX+";", "") + // remove occurrence at the end + sdpFmtpLine = strings.ReplaceAll(sdpFmtpLine, fmtpUseDTX, "") + if enableDTX { + sdpFmtpLine += ";" + fmtpUseDTX + } + receiverCodec.SDPFmtpLine = sdpFmtpLine + } + modifiedReceiverCodecs = append(modifiedReceiverCodecs, receiverCodec) + } + + // + // As `SetCodecPreferences` on a transceiver replaces all codecs, + // cycle through sender codecs also and add them before calling + // `SetCodecPreferences` + // + var senderCodecs []webrtc.RTPCodecParameters + sender := transceiver.Sender() + if sender != nil { + senderCodecs = sender.GetParameters().Codecs + } + + err := transceiver.SetCodecPreferences(append(modifiedReceiverCodecs, senderCodecs...)) + if err != nil { + t.params.Logger.Warnw("failed to SetCodecPreferences", err) + } + } +} + +func (t *PCTransport) CreateAndSendAnswer(enableDTX bool) error { + t.lock.RLock() + defer t.lock.RUnlock() + + t.configureReceiverDTX(enableDTX) + + answer, err := t.pc.CreateAnswer(nil) + if err != nil { + return err + } + + if t.preferTCP { + t.params.Logger.Infow("local answer (unfiltered)", "sdp", answer.SDP) + } + if err = t.pc.SetLocalDescription(answer); err != nil { + return err + } + + // + // Filter after setting local description as pion expects the answer + // to match between CreateAnswer and SetLocalDescription. + // Filtered answer is sent to remote so that remote does not + // see filtered candidates. + // + answer = t.filterCandidates(answer) + if t.preferTCP { + t.params.Logger.Infow("local answer (filtered)", "sdp", answer.SDP) + } + + if t.onAnswer != nil { + go t.onAnswer(answer) + } + + return nil +} + func (t *PCTransport) CreateAndSendOffer(options *webrtc.OfferOptions) error { t.lock.Lock() defer t.lock.Unlock() @@ -512,7 +943,7 @@ func (t *PCTransport) createAndSendOffer(options *webrtc.OfferOptions) error { if iceRestart && t.negotiationState != negotiationStateNone { currentSD := t.pc.CurrentRemoteDescription() if currentSD == nil { - // restart without current remote description, sent current local description again to try recover + // restart without current remote description, send current local description again to try recover offer := t.pc.LocalDescription() if offer == nil { // it should not happen, log just in case @@ -765,13 +1196,6 @@ func (t *PCTransport) SetPreviousAnswer(answer *webrtc.SessionDescription) { } } -func (t *PCTransport) FilterCandidates(sd webrtc.SessionDescription) webrtc.SessionDescription { - t.lock.RLock() - defer t.lock.RUnlock() - - return t.filterCandidates(sd) -} - func (t *PCTransport) filterCandidates(sd webrtc.SessionDescription) webrtc.SessionDescription { parsed, err := sd.Unmarshal() if err != nil { diff --git a/pkg/rtc/transport_test.go b/pkg/rtc/transport_test.go index ff504642..21d6b798 100644 --- a/pkg/rtc/transport_test.go +++ b/pkg/rtc/transport_test.go @@ -304,7 +304,7 @@ func TestFilteringCandidates(t *testing.T) { // should not filter out UDP candidates if TCP is not preferred offer = *transport.pc.LocalDescription() - filteredOffer := transport.FilterCandidates(offer) + filteredOffer := transport.filterCandidates(offer) require.EqualValues(t, offer.SDP, filteredOffer.SDP) parsed, err := offer.Unmarshal() @@ -382,7 +382,7 @@ func TestFilteringCandidates(t *testing.T) { require.Equal(t, 2, tcp) transport.SetPreferTCP(true) - filteredOffer = transport.FilterCandidates(offer) + filteredOffer = transport.filterCandidates(offer) parsed, err = filteredOffer.Unmarshal() require.NoError(t, err) udp, tcp = getNumTransportTypeCandidates(parsed) diff --git a/pkg/rtc/transportmanager.go b/pkg/rtc/transportmanager.go new file mode 100644 index 00000000..b7b4af11 --- /dev/null +++ b/pkg/rtc/transportmanager.go @@ -0,0 +1,494 @@ +package rtc + +import ( + "strings" + "sync" + + "github.com/pion/rtcp" + "github.com/pion/webrtc/v3" + "github.com/pkg/errors" + + "github.com/livekit/livekit-server/pkg/config" + "github.com/livekit/livekit-server/pkg/rtc/types" + "github.com/livekit/livekit-server/pkg/sfu" + "github.com/livekit/livekit-server/pkg/telemetry" + "github.com/livekit/livekit-server/pkg/telemetry/prometheus" + "github.com/livekit/protocol/livekit" + "github.com/livekit/protocol/logger" +) + +type TransportManagerParams struct { + Identity livekit.ParticipantIdentity + SID livekit.ParticipantID + SubscriberAsPrimary bool + Config *WebRTCConfig + ProtocolVersion types.ProtocolVersion + Telemetry telemetry.TelemetryService + CongestionControlConfig config.CongestionControlConfig + EnabledCodecs []*livekit.Codec + SimTracks map[uint32]SimulcastTrackInfo + ClientConf *livekit.ClientConfiguration + Migration bool + AllowTCPFallback bool + Logger logger.Logger +} + +type TransportManager struct { + params TransportManagerParams + + publisher *PCTransport + subscriber *PCTransport + + lock sync.RWMutex + + pendingOfferPublisher *webrtc.SessionDescription + pendingDataChannelsPublisher []*livekit.DataChannelInfo + + onPublisherGetDTX func() bool + + onSubscriberInitialConnected func() + onPrimaryTransportInitialConnected func() + onAnyTransportFailed func() + + onICEConfigChanged func(iceConfig types.IceConfig) +} + +func NewTransportManager(params TransportManagerParams) (*TransportManager, error) { + t := &TransportManager{ + params: params, + } + + enabledCodecs := make([]*livekit.Codec, 0, len(params.EnabledCodecs)) + for _, c := range params.EnabledCodecs { + var disabled bool + for _, disableCodec := range params.ClientConf.GetDisabledCodecs().GetCodecs() { + // disable codec's fmtp is empty means disable this codec entirely + if strings.EqualFold(c.Mime, disableCodec.Mime) && (disableCodec.FmtpLine == "" || disableCodec.FmtpLine == c.FmtpLine) { + disabled = true + break + } + } + if !disabled { + enabledCodecs = append(enabledCodecs, c) + } + } + + publisher, err := NewPCTransport(TransportParams{ + ParticipantID: params.SID, + ParticipantIdentity: params.Identity, + ProtocolVersion: params.ProtocolVersion, + Target: livekit.SignalTarget_PUBLISHER, + Config: params.Config, + CongestionControlConfig: params.CongestionControlConfig, + Telemetry: params.Telemetry, + EnabledCodecs: enabledCodecs, + Logger: LoggerWithPCTarget(params.Logger, livekit.SignalTarget_PUBLISHER), + SimTracks: params.SimTracks, + }) + if err != nil { + return nil, err + } + t.publisher = publisher + t.publisher.OnRemoteDescripitonSettled(t.createPublisherAnswerAndSend) + t.publisher.OnInitialConnected(func() { + if !t.params.SubscriberAsPrimary && t.onPrimaryTransportInitialConnected != nil { + t.onPrimaryTransportInitialConnected() + } + }) + t.publisher.OnFailed(func(isShortLived bool) { + t.handleConnectionFailed(isShortLived) + if t.onAnyTransportFailed != nil { + t.onAnyTransportFailed() + } + }) + + subscriber, err := NewPCTransport(TransportParams{ + ParticipantID: params.SID, + ParticipantIdentity: params.Identity, + ProtocolVersion: params.ProtocolVersion, + Target: livekit.SignalTarget_SUBSCRIBER, + Config: params.Config, + CongestionControlConfig: params.CongestionControlConfig, + Telemetry: params.Telemetry, + EnabledCodecs: enabledCodecs, + Logger: LoggerWithPCTarget(params.Logger, livekit.SignalTarget_SUBSCRIBER), + }) + if err != nil { + return nil, err + } + t.subscriber = subscriber + t.subscriber.OnInitialConnected(func() { + if t.onSubscriberInitialConnected != nil { + t.onSubscriberInitialConnected() + } + if t.params.SubscriberAsPrimary && t.onPrimaryTransportInitialConnected != nil { + t.onPrimaryTransportInitialConnected() + } + }) + t.subscriber.OnFailed(func(isShortLived bool) { + t.handleConnectionFailed(isShortLived) + if t.onAnyTransportFailed != nil { + t.onAnyTransportFailed() + } + }) + if !t.params.Migration { + if err := t.createDataChannelsForSubscriber(nil); err != nil { + return nil, err + } + } + + return t, nil +} + +func (t *TransportManager) Close() { + t.publisher.Close() + t.subscriber.Close() +} + +func (t *TransportManager) OnPublisherICECandidate(f func(c *webrtc.ICECandidate)) { + t.publisher.OnICECandidate(f) +} + +func (t *TransportManager) OnPublisherGetDTX(f func() bool) { + t.onPublisherGetDTX = f +} + +func (t *TransportManager) OnPublisherAnswer(f func(answer webrtc.SessionDescription)) { + t.publisher.OnAnswer(f) +} + +func (t *TransportManager) OnPublisherTrack(f func(track *webrtc.TrackRemote, rtpReceiver *webrtc.RTPReceiver)) { + t.publisher.OnTrack(f) +} + +func (t *TransportManager) IsPublisherEstablished() bool { + return t.publisher.IsEstablished() +} + +func (t *TransportManager) GetPublisherMid(rtpReceiver *webrtc.RTPReceiver) string { + return t.publisher.GetMid(rtpReceiver) +} + +func (t *TransportManager) GetPublisherRTPReceiver(mid string) *webrtc.RTPReceiver { + return t.publisher.GetRTPReceiver(mid) +} + +func (t *TransportManager) WritePublisherRTCP(pkts []rtcp.Packet) error { + return t.publisher.WriteRTCP(pkts) +} + +func (t *TransportManager) OnSubscriberICECandidate(f func(c *webrtc.ICECandidate)) { + t.subscriber.OnICECandidate(f) +} + +func (t *TransportManager) OnSubscriberOffer(f func(offer webrtc.SessionDescription)) { + t.subscriber.OnOffer(f) +} + +func (t *TransportManager) OnSubscriberInitialConnected(f func()) { + t.onSubscriberInitialConnected = f +} + +func (t *TransportManager) OnSubscriberNegotiationFailed(f func()) { + t.subscriber.OnNegotiationFailed(f) +} + +func (t *TransportManager) OnSubscriberStreamStateChange(f func(update *sfu.StreamStateUpdate) error) { + t.subscriber.OnStreamStateChange(f) +} + +func (t *TransportManager) HasSubscriberEverConnected() bool { + return t.subscriber.HasEverConnected() +} + +func (t *TransportManager) WriteSubscriberRTCP(pkts []rtcp.Packet) error { + return t.subscriber.WriteRTCP(pkts) +} + +func (t *TransportManager) OnPrimaryTransportInitialConnected(f func()) { + t.onPrimaryTransportInitialConnected = f +} + +func (t *TransportManager) OnPrimaryTransportFullyEstablished(f func()) { + t.getTransport(true).OnFullyEstablished(f) +} + +func (t *TransportManager) OnAnyTransportFailed(f func()) { + t.onAnyTransportFailed = f +} + +func (t *TransportManager) AddSubscribedTrack(subTrack types.SubscribedTrack) { + t.subscriber.AddTrack(subTrack) +} + +func (t *TransportManager) RemoveSubscribedTrack(subTrack types.SubscribedTrack) { + t.subscriber.RemoveTrack(subTrack) +} + +func (t *TransportManager) OnDataMessage(f func(kind livekit.DataPacket_Kind, data []byte)) { + // upstream data is always comes in via publisher peer connection irrespective of which is primary + t.publisher.OnDataPacket(f) +} + +func (t *TransportManager) SendDataPacket(dp *livekit.DataPacket) error { + // downstream data is sent via primary peer connection + return t.getTransport(true).SendDataPacket(dp) +} + +func (t *TransportManager) createDataChannelsForSubscriber(pendingDataChannels []*livekit.DataChannelInfo) error { + var ( + reliableID, lossyID uint16 + reliableIDPtr, lossyIDPtr *uint16 + ) + + // + // For old version migration clients, they don't send subscriber data channel info + // so we need to create data channels with default ID and don't negotiate as client already has + // data channels with default ID. + // + // For new version migration clients, we create data channels with new ID and negotiate with client + // + for _, dc := range pendingDataChannels { + if dc.Label == ReliableDataChannel { + // pion use step 2 for auto generated ID, so we need to add 4 to avoid conflict + reliableID = uint16(dc.Id) + 4 + reliableIDPtr = &reliableID + } else if dc.Label == LossyDataChannel { + lossyID = uint16(dc.Id) + 4 + lossyIDPtr = &lossyID + } + } + + ordered := true + negotiated := t.params.Migration && reliableIDPtr == nil + if err := t.subscriber.CreateDataChannel(ReliableDataChannel, &webrtc.DataChannelInit{ + Ordered: &ordered, + ID: reliableIDPtr, + Negotiated: &negotiated, + }); err != nil { + return err + } + + retransmits := uint16(0) + negotiated = t.params.Migration && lossyIDPtr == nil + if err := t.subscriber.CreateDataChannel(LossyDataChannel, &webrtc.DataChannelInit{ + Ordered: &ordered, + MaxRetransmits: &retransmits, + ID: lossyIDPtr, + Negotiated: &negotiated, + }); err != nil { + return err + } + return nil +} + +func (t *TransportManager) HandleOffer(offer webrtc.SessionDescription, shouldPend bool) error { + t.lock.Lock() + if shouldPend { + t.pendingOfferPublisher = &offer + t.lock.Unlock() + return nil + } + t.lock.Unlock() + + return t.publisher.SetRemoteDescription(offer) +} + +func (t *TransportManager) ProcessPendingPublisherOffer() error { + t.lock.Lock() + pendingOffer := t.pendingOfferPublisher + t.pendingOfferPublisher = nil + t.lock.Unlock() + + if pendingOffer != nil { + return t.HandleOffer(*pendingOffer, false) + } + + return nil +} + +func (t *TransportManager) createPublisherAnswerAndSend() error { + enableDTX := false + if t.onPublisherGetDTX != nil { + enableDTX = t.onPublisherGetDTX() + } + err := t.publisher.CreateAndSendAnswer(enableDTX) + if err != nil { + prometheus.ServiceOperationCounter.WithLabelValues("answer", "error", "create").Add(1) + return errors.Wrap(err, "could not create answer") + } + + return nil +} + +// HandleAnswer handles a client answer response, with subscriber PC, server initiates the +// offer and client answers +func (t *TransportManager) HandleAnswer(answer webrtc.SessionDescription) error { + if answer.Type != webrtc.SDPTypeAnswer { + return ErrUnexpectedOffer + } + + t.params.Logger.Infow("received answer", "transport", livekit.SignalTarget_SUBSCRIBER) + if err := t.subscriber.SetRemoteDescription(answer); err != nil { + return errors.Wrap(err, "could not set answer") + } + + return nil +} + +// AddICECandidate adds candidates for remote peer +func (t *TransportManager) AddICECandidate(candidate webrtc.ICECandidateInit, target livekit.SignalTarget) error { + switch target { + case livekit.SignalTarget_PUBLISHER: + return t.publisher.AddICECandidate(candidate) + case livekit.SignalTarget_SUBSCRIBER: + return t.subscriber.AddICECandidate(candidate) + default: + err := errors.New("unknown signal target") + t.params.Logger.Errorw("ice candidate for unknown signal target", err, "target", target) + return err + } +} + +func (t *TransportManager) NegotiateSubscriber(force bool) { + t.subscriber.Negotiate(force) +} + +func (t *TransportManager) AddNegotiationPending(publisherID livekit.ParticipantID) { + t.subscriber.AddNegotiationPending(publisherID) +} + +func (t *TransportManager) IsNegotiationPending(publisherID livekit.ParticipantID) bool { + return t.subscriber.IsNegotiationPending(publisherID) +} + +func (t *TransportManager) ICERestart(iceConfig *types.IceConfig) error { + if iceConfig != nil { + t.SetICEConfig(*iceConfig) + } + + return t.subscriber.CreateAndSendOffer(&webrtc.OfferOptions{ + ICERestart: true, + }) +} + +func (t *TransportManager) OnICEConfigChanged(f func(iceConfig types.IceConfig)) { + t.lock.Lock() + t.onICEConfigChanged = f + t.lock.Unlock() +} + +func (t *TransportManager) SetICEConfig(iceConfig types.IceConfig) { + t.params.Logger.Infow("setting ICE config", "iceConfig", iceConfig) + if iceConfig.PreferPubTcp { + t.publisher.SetPreferTCP(true) + } + + if iceConfig.PreferSubTcp { + t.subscriber.SetPreferTCP(true) + } + + t.lock.RLock() + onICEConfigChanged := t.onICEConfigChanged + t.lock.RUnlock() + + if onICEConfigChanged != nil { + onICEConfigChanged(iceConfig) + } +} + +func (t *TransportManager) SubscriberAsPrimary() bool { + return t.params.SubscriberAsPrimary +} + +func (t *TransportManager) SubscriberPC() *webrtc.PeerConnection { + return t.subscriber.PeerConnection() +} + +func (t *TransportManager) getTransport(isPrimary bool) *PCTransport { + pcTransport := t.publisher + if (isPrimary && t.params.SubscriberAsPrimary) || (!isPrimary && !t.params.SubscriberAsPrimary) { + pcTransport = t.subscriber + } + + return pcTransport +} + +func (t *TransportManager) handleConnectionFailed(isShortLived bool) { + if !t.params.AllowTCPFallback || !isShortLived { + return + } + + // irrespective of which one fails, force TCP on both as the other one might + // fail at a different time and cause another disruption + t.params.Logger.Infow("restricting transport to TCP on both peer connections") + t.SetICEConfig(types.IceConfig{ + PreferPubTcp: true, + PreferSubTcp: true, + }) +} + +func (t *TransportManager) SetMigrateInfo(previousAnswer *webrtc.SessionDescription, dataChannels []*livekit.DataChannelInfo) { + t.lock.Lock() + t.pendingDataChannelsPublisher = make([]*livekit.DataChannelInfo, 0, len(dataChannels)) + pendingDataChannelsSubscriber := make([]*livekit.DataChannelInfo, 0, len(dataChannels)) + for _, dci := range dataChannels { + if dci.Target == livekit.SignalTarget_SUBSCRIBER { + pendingDataChannelsSubscriber = append(pendingDataChannelsSubscriber, dci) + } else { + t.pendingDataChannelsPublisher = append(t.pendingDataChannelsPublisher, dci) + } + } + t.lock.Unlock() + + if t.params.SubscriberAsPrimary { + if err := t.createDataChannelsForSubscriber(pendingDataChannelsSubscriber); err != nil { + t.params.Logger.Errorw("create subscriber data channels during migration failed", err) + } + } + + t.subscriber.SetPreviousAnswer(previousAnswer) +} + +func (t *TransportManager) ProcessPendingPublisherDataChannels() { + t.lock.Lock() + pendingDataChannels := t.pendingDataChannelsPublisher + t.pendingDataChannelsPublisher = nil + t.lock.Unlock() + + ordered := true + negotiated := true + + for _, ci := range pendingDataChannels { + var ( + dcLabel string + dcID uint16 + dcExisting bool + err error + ) + if ci.Label == LossyDataChannel { + retransmits := uint16(0) + id := uint16(ci.GetId()) + dcLabel, dcID, dcExisting, err = t.publisher.CreateDataChannelIfEmpty(LossyDataChannel, &webrtc.DataChannelInit{ + Ordered: &ordered, + MaxRetransmits: &retransmits, + Negotiated: &negotiated, + ID: &id, + }) + } else if ci.Label == ReliableDataChannel { + id := uint16(ci.GetId()) + dcLabel, dcID, dcExisting, err = t.publisher.CreateDataChannelIfEmpty(ReliableDataChannel, &webrtc.DataChannelInit{ + Ordered: &ordered, + Negotiated: &negotiated, + ID: &id, + }) + } + if err != nil { + t.params.Logger.Errorw("create migrated data channel failed", err, "label", ci.Label) + } else if dcExisting { + t.params.Logger.Debugw("existing data channel during migration", "label", dcLabel, "id", dcID) + } else { + t.params.Logger.Debugw("create migrated data channel", "label", dcLabel, "id", dcID) + } + } +} diff --git a/pkg/rtc/types/interfaces.go b/pkg/rtc/types/interfaces.go index 472cef52..57060f45 100644 --- a/pkg/rtc/types/interfaces.go +++ b/pkg/rtc/types/interfaces.go @@ -229,7 +229,7 @@ type LocalParticipant interface { HandleOffer(sdp webrtc.SessionDescription) error AddTrack(req *livekit.AddTrackRequest) SetTrackMuted(trackID livekit.TrackID, muted bool, fromAdmin bool) - SubscriberMediaEngine() *webrtc.MediaEngine + SubscriberPC() *webrtc.PeerConnection HandleAnswer(sdp webrtc.SessionDescription) error Negotiate(force bool) diff --git a/pkg/rtc/types/typesfakes/fake_local_participant.go b/pkg/rtc/types/typesfakes/fake_local_participant.go index 6a900aa8..7c17e225 100644 --- a/pkg/rtc/types/typesfakes/fake_local_participant.go +++ b/pkg/rtc/types/typesfakes/fake_local_participant.go @@ -617,16 +617,6 @@ type FakeLocalParticipant struct { subscriberAsPrimaryReturnsOnCall map[int]struct { result1 bool } - SubscriberMediaEngineStub func() *webrtc.MediaEngine - subscriberMediaEngineMutex sync.RWMutex - subscriberMediaEngineArgsForCall []struct { - } - subscriberMediaEngineReturns struct { - result1 *webrtc.MediaEngine - } - subscriberMediaEngineReturnsOnCall map[int]struct { - result1 *webrtc.MediaEngine - } SubscriberPCStub func() *webrtc.PeerConnection subscriberPCMutex sync.RWMutex subscriberPCArgsForCall []struct { @@ -4065,59 +4055,6 @@ func (fake *FakeLocalParticipant) SubscriberAsPrimaryReturnsOnCall(i int, result }{result1} } -func (fake *FakeLocalParticipant) SubscriberMediaEngine() *webrtc.MediaEngine { - fake.subscriberMediaEngineMutex.Lock() - ret, specificReturn := fake.subscriberMediaEngineReturnsOnCall[len(fake.subscriberMediaEngineArgsForCall)] - fake.subscriberMediaEngineArgsForCall = append(fake.subscriberMediaEngineArgsForCall, struct { - }{}) - stub := fake.SubscriberMediaEngineStub - fakeReturns := fake.subscriberMediaEngineReturns - fake.recordInvocation("SubscriberMediaEngine", []interface{}{}) - fake.subscriberMediaEngineMutex.Unlock() - if stub != nil { - return stub() - } - if specificReturn { - return ret.result1 - } - return fakeReturns.result1 -} - -func (fake *FakeLocalParticipant) SubscriberMediaEngineCallCount() int { - fake.subscriberMediaEngineMutex.RLock() - defer fake.subscriberMediaEngineMutex.RUnlock() - return len(fake.subscriberMediaEngineArgsForCall) -} - -func (fake *FakeLocalParticipant) SubscriberMediaEngineCalls(stub func() *webrtc.MediaEngine) { - fake.subscriberMediaEngineMutex.Lock() - defer fake.subscriberMediaEngineMutex.Unlock() - fake.SubscriberMediaEngineStub = stub -} - -func (fake *FakeLocalParticipant) SubscriberMediaEngineReturns(result1 *webrtc.MediaEngine) { - fake.subscriberMediaEngineMutex.Lock() - defer fake.subscriberMediaEngineMutex.Unlock() - fake.SubscriberMediaEngineStub = nil - fake.subscriberMediaEngineReturns = struct { - result1 *webrtc.MediaEngine - }{result1} -} - -func (fake *FakeLocalParticipant) SubscriberMediaEngineReturnsOnCall(i int, result1 *webrtc.MediaEngine) { - fake.subscriberMediaEngineMutex.Lock() - defer fake.subscriberMediaEngineMutex.Unlock() - fake.SubscriberMediaEngineStub = nil - if fake.subscriberMediaEngineReturnsOnCall == nil { - fake.subscriberMediaEngineReturnsOnCall = make(map[int]struct { - result1 *webrtc.MediaEngine - }) - } - fake.subscriberMediaEngineReturnsOnCall[i] = struct { - result1 *webrtc.MediaEngine - }{result1} -} - func (fake *FakeLocalParticipant) SubscriberPC() *webrtc.PeerConnection { fake.subscriberPCMutex.Lock() ret, specificReturn := fake.subscriberPCReturnsOnCall[len(fake.subscriberPCArgsForCall)] @@ -4839,8 +4776,6 @@ func (fake *FakeLocalParticipant) Invocations() map[string][][]interface{} { defer fake.stateMutex.RUnlock() fake.subscriberAsPrimaryMutex.RLock() defer fake.subscriberAsPrimaryMutex.RUnlock() - fake.subscriberMediaEngineMutex.RLock() - defer fake.subscriberMediaEngineMutex.RUnlock() fake.subscriberPCMutex.RLock() defer fake.subscriberPCMutex.RUnlock() fake.subscriptionPermissionMutex.RLock()