* Prevent missing entry in pending tracks Problem: -------- A track received via signalling request `AddTrack` is stored in `pendingTracks` of participant. A MediaTrack is created when `onTrack` fires after `SetRemoteDescription`. At that time, pending tracks are searched to find a matching track and look up an already published MediaTrack. This is because `onTrack` fires once for every layer of Simulcast and MediaTrack abstraction is for a media track and not one for every layer of Simulcast track. To accomplish that, pending tracks are cleaned up 5 seconds after the MediaTrack is created. The theory there is that `onTrack` will fire on all layers within 5 seconds. But, have observed several instances on my slow machine of that firing after 5 seconds which results in the search failing and we end up creating a new MediaTrack. The above is probably the reason (I am guessing though) for subscriber PC having an extra m-line some times. Considered fix: --------------- One possible option is to increase that 5 seconds timeout to a very large value. But, it has another issue. `getPendingTrack` is given the track id which comes in the SDP. Entries are added to the pending tracks using track id received via the `AddTrack` signalling message. And those two need not be the same. Especially Firefox has different ids every time. Not sure if that is something we do on client side which causes that, but it does look like a real possibility. To handle that case, `getPendingTrack` looks up tracks by media kind (audio/video) if the look up by SDP client id fails. Here, it is possible that there are two pending tracks of type video (think camera and screen sharing as an example) and looking up by kind might end up picking the wrong one. Fix: ---- Store the signalled client id and SDP client id in the MediaTrack and look up the published tracks by SDP client id for a track match. If there is no match, create a new MediaTrack and add it to publishedTracks and delete the corresponding pending track all within the lock (yeah not great to have a lot of code within the lock, but this is probably worth it to have the correctness). This does solve the issue of deferred pending track removal causing issues. However, note that kind based look up may do some switching. In a scenario where there are two pending tracks of kind video and the look up has to rely on kind, it is possible that signalCid and sdpCid get cross matched (i. e. client might have sent a signalCid for a Simulcast track, but during kind based look up it gets assigned to a non-simulcast track). I think that is okay as there is no strong correlation between the two. Testing: -------- - Connect from Chrome, Firefox (both orders, Chrome joining first, Firefox joining first) and ensure that media subscriptions and publishing are correct - Ensure that DTX munging works properly too. * Fix tests Add back adding track to publishedTracks for testing purposes. * Add a test to check case of `AddTrack` rejecting already published track * Remove debug. * Address PR comments - do not need to return SDP cid from `getPendingTracks`.
461 lines
12 KiB
Go
461 lines
12 KiB
Go
package rtc
|
|
|
|
import (
|
|
"errors"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/livekit/protocol/logger"
|
|
livekit "github.com/livekit/protocol/proto"
|
|
"github.com/livekit/protocol/utils"
|
|
"github.com/pion/ion-sfu/pkg/buffer"
|
|
"github.com/pion/ion-sfu/pkg/sfu"
|
|
"github.com/pion/ion-sfu/pkg/twcc"
|
|
"github.com/pion/rtcp"
|
|
"github.com/pion/webrtc/v3"
|
|
"github.com/pion/webrtc/v3/pkg/rtcerr"
|
|
|
|
"github.com/livekit/livekit-server/pkg/config"
|
|
"github.com/livekit/livekit-server/pkg/rtc/types"
|
|
"github.com/livekit/livekit-server/pkg/utils/stats"
|
|
)
|
|
|
|
var (
|
|
feedbackTypes = []webrtc.RTCPFeedback{
|
|
{Type: webrtc.TypeRTCPFBGoogREMB},
|
|
{Type: webrtc.TypeRTCPFBNACK},
|
|
{Type: webrtc.TypeRTCPFBNACK, Parameter: "pli"}}
|
|
)
|
|
|
|
// MediaTrack represents a WebRTC track that needs to be forwarded
|
|
// Implements the PublishedTrack interface
|
|
type MediaTrack struct {
|
|
params MediaTrackParams
|
|
ssrc webrtc.SSRC
|
|
streamID string
|
|
codec webrtc.RTPCodecParameters
|
|
muted utils.AtomicFlag
|
|
numUpTracks uint32
|
|
simulcasted bool
|
|
|
|
// channel to send RTCP packets to the source
|
|
lock sync.RWMutex
|
|
// map of target participantId -> *SubscribedTrack
|
|
subscribedTracks map[string]*SubscribedTrack
|
|
twcc *twcc.Responder
|
|
audioLevel *AudioLevel
|
|
receiver sfu.Receiver
|
|
lastPLI time.Time
|
|
|
|
onClose func()
|
|
}
|
|
|
|
type MediaTrackParams struct {
|
|
TrackInfo *livekit.TrackInfo
|
|
SignalCid string
|
|
SdpCid string
|
|
ParticipantID string
|
|
RTCPChan chan []rtcp.Packet
|
|
BufferFactory *buffer.Factory
|
|
ReceiverConfig ReceiverConfig
|
|
AudioConfig config.AudioConfig
|
|
Stats *stats.RoomStatsReporter
|
|
}
|
|
|
|
func NewMediaTrack(track *webrtc.TrackRemote, params MediaTrackParams) *MediaTrack {
|
|
t := &MediaTrack{
|
|
params: params,
|
|
ssrc: track.SSRC(),
|
|
streamID: track.StreamID(),
|
|
codec: track.Codec(),
|
|
subscribedTracks: make(map[string]*SubscribedTrack),
|
|
}
|
|
|
|
if params.TrackInfo.Muted {
|
|
t.SetMuted(true)
|
|
}
|
|
return t
|
|
}
|
|
|
|
func (t *MediaTrack) Start() {
|
|
}
|
|
|
|
func (t *MediaTrack) ID() string {
|
|
return t.params.TrackInfo.Sid
|
|
}
|
|
|
|
func (t *MediaTrack) SignalCid() string {
|
|
return t.params.SignalCid
|
|
}
|
|
|
|
func (t *MediaTrack) SdpCid() string {
|
|
return t.params.SdpCid
|
|
}
|
|
|
|
func (t *MediaTrack) Kind() livekit.TrackType {
|
|
return t.params.TrackInfo.Type
|
|
}
|
|
|
|
func (t *MediaTrack) Name() string {
|
|
return t.params.TrackInfo.Name
|
|
}
|
|
|
|
func (t *MediaTrack) IsMuted() bool {
|
|
return t.muted.Get()
|
|
}
|
|
|
|
func (t *MediaTrack) SetMuted(muted bool) {
|
|
t.muted.TrySet(muted)
|
|
|
|
t.lock.RLock()
|
|
if t.receiver != nil {
|
|
t.receiver.SetUpTrackPaused(muted)
|
|
}
|
|
// mute all of the subscribedtracks
|
|
for _, st := range t.subscribedTracks {
|
|
st.SetPublisherMuted(muted)
|
|
}
|
|
t.lock.RUnlock()
|
|
}
|
|
|
|
func (t *MediaTrack) OnClose(f func()) {
|
|
t.onClose = f
|
|
}
|
|
|
|
func (t *MediaTrack) IsSubscriber(subId string) bool {
|
|
t.lock.RLock()
|
|
defer t.lock.RUnlock()
|
|
return t.subscribedTracks[subId] != nil
|
|
}
|
|
|
|
// AddSubscriber subscribes sub to current mediaTrack
|
|
func (t *MediaTrack) AddSubscriber(sub types.Participant) error {
|
|
if !sub.CanSubscribe() {
|
|
return ErrPermissionDenied
|
|
}
|
|
|
|
t.lock.Lock()
|
|
defer t.lock.Unlock()
|
|
existingSt := t.subscribedTracks[sub.ID()]
|
|
|
|
// don't subscribe to the same track multiple times
|
|
if existingSt != nil {
|
|
return nil
|
|
}
|
|
|
|
if t.receiver == nil {
|
|
// cannot add, no receiver
|
|
return errors.New("cannot subscribe without a receiver in place")
|
|
}
|
|
|
|
codec := t.receiver.Codec()
|
|
if err := sub.SubscriberMediaEngine().RegisterCodec(codec, t.receiver.Kind()); err != nil {
|
|
return err
|
|
}
|
|
|
|
// using DownTrack from ion-sfu
|
|
streamId := t.params.ParticipantID
|
|
if sub.ProtocolVersion().SupportsPackedStreamId() {
|
|
// when possible, pack both IDs in streamID to allow new streams to be generated
|
|
// react-native-webrtc still uses stream based APIs and require this
|
|
streamId = PackStreamID(t.params.ParticipantID, t.ID())
|
|
}
|
|
receiver := NewWrappedReceiver(t.receiver, t.ID(), streamId)
|
|
downTrack, err := sfu.NewDownTrack(webrtc.RTPCodecCapability{
|
|
MimeType: codec.MimeType,
|
|
ClockRate: codec.ClockRate,
|
|
Channels: codec.Channels,
|
|
SDPFmtpLine: codec.SDPFmtpLine,
|
|
RTCPFeedback: feedbackTypes,
|
|
}, receiver, t.params.BufferFactory, sub.ID(), t.params.ReceiverConfig.packetBufferSize)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
subTrack := NewSubscribedTrack(downTrack)
|
|
|
|
var transceiver *webrtc.RTPTransceiver
|
|
var sender *webrtc.RTPSender
|
|
if sub.ProtocolVersion().SupportsTransceiverReuse() {
|
|
//
|
|
// AddTrack will create a new transceiver or re-use an unused one
|
|
// if the attributes match. This prevents SDP from bloating
|
|
// because of dormant transceivers buidling up.
|
|
//
|
|
sender, err = sub.SubscriberPC().AddTrack(downTrack)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// as there is no way to get transceiver from sender, search
|
|
for _, tr := range sub.SubscriberPC().GetTransceivers() {
|
|
if tr.Sender() == sender {
|
|
transceiver = tr
|
|
break
|
|
}
|
|
}
|
|
if transceiver == nil {
|
|
// cannot add, no transceiver
|
|
return errors.New("cannot subscribe without a transceiver in place")
|
|
}
|
|
} else {
|
|
transceiver, err = sub.SubscriberPC().AddTransceiverFromTrack(downTrack, webrtc.RTPTransceiverInit{
|
|
Direction: webrtc.RTPTransceiverDirectionSendonly,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
sender = transceiver.Sender()
|
|
if sender == nil {
|
|
// cannot add, no sender
|
|
return errors.New("cannot subscribe without a sender in place")
|
|
}
|
|
}
|
|
|
|
sendParameters := sender.GetParameters()
|
|
downTrack.SetRTPHeaderExtensions(sendParameters.HeaderExtensions)
|
|
|
|
downTrack.SetTransceiver(transceiver)
|
|
// when outtrack is bound, start loop to send reports
|
|
downTrack.OnBind(func() {
|
|
go t.sendDownTrackBindingReports(sub)
|
|
})
|
|
|
|
downTrack.OnCloseHandler(func() {
|
|
go func() {
|
|
t.lock.Lock()
|
|
delete(t.subscribedTracks, sub.ID())
|
|
t.lock.Unlock()
|
|
|
|
t.params.Stats.SubSubscribedTrack(t.Kind().String())
|
|
|
|
// ignore if the subscribing sub is not connected
|
|
if sub.SubscriberPC().ConnectionState() == webrtc.PeerConnectionStateClosed {
|
|
return
|
|
}
|
|
|
|
// if the source has been terminated, we'll need to terminate all of the subscribedtracks
|
|
// however, if the dest sub has disconnected, then we can skip
|
|
if sender == nil {
|
|
return
|
|
}
|
|
logger.Debugw("removing peerconnection track",
|
|
"track", t.ID(),
|
|
"pIDs", []string{t.params.ParticipantID, sub.ID()},
|
|
"participant", sub.Identity(),
|
|
)
|
|
if err := sub.SubscriberPC().RemoveTrack(sender); err != nil {
|
|
if err == webrtc.ErrConnectionClosed {
|
|
// sub closing, can skip removing subscribedtracks
|
|
return
|
|
}
|
|
if _, ok := err.(*rtcerr.InvalidStateError); !ok {
|
|
logger.Warnw("could not remove remoteTrack from forwarder", err,
|
|
"participant", sub.Identity(), "pID", sub.ID())
|
|
}
|
|
}
|
|
|
|
sub.RemoveSubscribedTrack(t.params.ParticipantID, subTrack)
|
|
sub.Negotiate()
|
|
}()
|
|
})
|
|
|
|
t.subscribedTracks[sub.ID()] = subTrack
|
|
subTrack.SetPublisherMuted(t.IsMuted())
|
|
|
|
t.receiver.AddDownTrack(downTrack, t.shouldStartWithBestQuality())
|
|
// since sub will lock, run it in a goroutine to avoid deadlocks
|
|
go func() {
|
|
sub.AddSubscribedTrack(t.params.ParticipantID, subTrack)
|
|
sub.Negotiate()
|
|
}()
|
|
|
|
t.params.Stats.AddSubscribedTrack(t.Kind().String())
|
|
return nil
|
|
}
|
|
|
|
func (t *MediaTrack) NumUpTracks() uint32 {
|
|
return atomic.LoadUint32(&t.numUpTracks)
|
|
}
|
|
|
|
// AddReceiver adds a new RTP receiver to the track
|
|
func (t *MediaTrack) AddReceiver(receiver *webrtc.RTPReceiver, track *webrtc.TrackRemote, twcc *twcc.Responder) {
|
|
t.lock.Lock()
|
|
defer t.lock.Unlock()
|
|
|
|
buff, rtcpReader := t.params.BufferFactory.GetBufferPair(uint32(track.SSRC()))
|
|
buff.OnFeedback(func(fb []rtcp.Packet) {
|
|
if t.params.Stats != nil {
|
|
t.params.Stats.Incoming.HandleRTCP(fb)
|
|
}
|
|
// feedback for the source RTCP
|
|
t.params.RTCPChan <- fb
|
|
})
|
|
|
|
if t.Kind() == livekit.TrackType_AUDIO {
|
|
t.audioLevel = NewAudioLevel(t.params.AudioConfig.ActiveLevel, t.params.AudioConfig.MinPercentile)
|
|
buff.OnAudioLevel(func(level uint8) {
|
|
t.audioLevel.Observe(level)
|
|
})
|
|
} else if t.Kind() == livekit.TrackType_VIDEO {
|
|
if twcc != nil {
|
|
buff.OnTransportWideCC(func(sn uint16, timeNS int64, marker bool) {
|
|
twcc.Push(sn, timeNS, marker)
|
|
})
|
|
}
|
|
}
|
|
|
|
rtcpReader.OnPacket(func(bytes []byte) {
|
|
pkts, err := rtcp.Unmarshal(bytes)
|
|
if err != nil {
|
|
logger.Errorw("could not unmarshal RTCP", err)
|
|
return
|
|
}
|
|
|
|
for _, pkt := range pkts {
|
|
switch pkt := pkt.(type) {
|
|
case *rtcp.SourceDescription:
|
|
// do nothing for now
|
|
case *rtcp.SenderReport:
|
|
buff.SetSenderReportData(pkt.RTPTime, pkt.NTPTime)
|
|
}
|
|
}
|
|
})
|
|
|
|
if t.receiver == nil {
|
|
t.receiver = sfu.NewWebRTCReceiver(receiver, track, t.params.ParticipantID,
|
|
sfu.WithPliThrottle(0),
|
|
sfu.WithLoadBalanceThreshold(20),
|
|
sfu.WithStreamTrackers())
|
|
t.receiver.SetRTCPCh(t.params.RTCPChan)
|
|
t.receiver.OnCloseHandler(func() {
|
|
t.lock.Lock()
|
|
t.receiver = nil
|
|
onclose := t.onClose
|
|
t.lock.Unlock()
|
|
t.RemoveAllSubscribers()
|
|
t.params.Stats.SubPublishedTrack(t.Kind().String())
|
|
if onclose != nil {
|
|
onclose()
|
|
}
|
|
})
|
|
t.receiver.OnFractionLostFB(func(lost uint8) {
|
|
buff.SetLastFractionLostReport(lost)
|
|
})
|
|
t.params.Stats.AddPublishedTrack(t.Kind().String())
|
|
}
|
|
t.receiver.AddUpTrack(track, buff, t.shouldStartWithBestQuality())
|
|
// when RID is set, track is simulcasted
|
|
// TODO: how does this work with FF, SSRC based simulcast?
|
|
t.simulcasted = track.RID() != ""
|
|
atomic.AddUint32(&t.numUpTracks, 1)
|
|
|
|
buff.Bind(receiver.GetParameters(), buffer.Options{
|
|
MaxBitRate: t.params.ReceiverConfig.maxBitrate,
|
|
})
|
|
}
|
|
|
|
// RemoveSubscriber removes participant from subscription
|
|
// stop all forwarders to the client
|
|
func (t *MediaTrack) RemoveSubscriber(participantId string) {
|
|
t.lock.RLock()
|
|
defer t.lock.RUnlock()
|
|
|
|
if subTrack := t.subscribedTracks[participantId]; subTrack != nil {
|
|
go subTrack.DownTrack().Close()
|
|
}
|
|
}
|
|
|
|
func (t *MediaTrack) RemoveAllSubscribers() {
|
|
logger.Debugw("removing all subscribers", "track", t.ID())
|
|
t.lock.Lock()
|
|
defer t.lock.Unlock()
|
|
for _, subTrack := range t.subscribedTracks {
|
|
go subTrack.DownTrack().Close()
|
|
}
|
|
t.subscribedTracks = make(map[string]*SubscribedTrack)
|
|
}
|
|
|
|
func (t *MediaTrack) ToProto() *livekit.TrackInfo {
|
|
info := t.params.TrackInfo
|
|
info.Muted = t.IsMuted()
|
|
info.Simulcast = t.simulcasted
|
|
return info
|
|
}
|
|
|
|
// this function assumes caller holds lock
|
|
func (t *MediaTrack) shouldStartWithBestQuality() bool {
|
|
return len(t.subscribedTracks) < 10
|
|
}
|
|
|
|
// TODO: send for all downtracks from the source participant
|
|
// https://tools.ietf.org/html/rfc7941
|
|
func (t *MediaTrack) sendDownTrackBindingReports(sub types.Participant) {
|
|
var sd []rtcp.SourceDescriptionChunk
|
|
|
|
t.lock.RLock()
|
|
subTrack := t.subscribedTracks[sub.ID()]
|
|
t.lock.RUnlock()
|
|
|
|
if subTrack == nil {
|
|
return
|
|
}
|
|
|
|
chunks := subTrack.DownTrack().CreateSourceDescriptionChunks()
|
|
if chunks == nil {
|
|
return
|
|
}
|
|
sd = append(sd, chunks...)
|
|
|
|
pkts := []rtcp.Packet{
|
|
&rtcp.SourceDescription{Chunks: sd},
|
|
}
|
|
|
|
go func() {
|
|
defer RecoverSilent()
|
|
batch := pkts
|
|
i := 0
|
|
for {
|
|
if err := sub.SubscriberPC().WriteRTCP(batch); err != nil {
|
|
logger.Errorw("could not write RTCP", err)
|
|
return
|
|
}
|
|
if i > 5 {
|
|
return
|
|
}
|
|
i++
|
|
time.Sleep(20 * time.Millisecond)
|
|
}
|
|
}()
|
|
}
|
|
|
|
func (t *MediaTrack) DebugInfo() map[string]interface{} {
|
|
info := map[string]interface{}{
|
|
"ID": t.ID(),
|
|
"SSRC": t.ssrc,
|
|
"Kind": t.Kind().String(),
|
|
"PubMuted": t.muted.Get(),
|
|
}
|
|
|
|
subscribedTrackInfo := make([]map[string]interface{}, 0)
|
|
t.lock.RLock()
|
|
for _, track := range t.subscribedTracks {
|
|
dt := track.dt.DebugInfo()
|
|
dt["PubMuted"] = track.pubMuted.Get()
|
|
dt["SubMuted"] = track.subMuted.Get()
|
|
subscribedTrackInfo = append(subscribedTrackInfo, dt)
|
|
}
|
|
t.lock.RUnlock()
|
|
info["DownTracks"] = subscribedTrackInfo
|
|
|
|
if t.receiver != nil {
|
|
receiverInfo := t.receiver.DebugInfo()
|
|
for k, v := range receiverInfo {
|
|
info[k] = v
|
|
}
|
|
}
|
|
|
|
return info
|
|
}
|