Transport refactor (#907)
* WIP commit * WIP commit * WIP commit * WIP commit * WIP commit * Clean up * fix tests * debug logs * Remove comments * Fix data channel creation on migration and clean up unused stuff * log offer/answer send/receive
This commit is contained in:
+158
-643
File diff suppressed because it is too large
Load Diff
@@ -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 {
|
||||
|
||||
@@ -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{
|
||||
|
||||
+467
-43
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user