add red codec for opus (#938)
* opus/red codec * panic * forward red track to nonred subscriber * config * clean code * solve comments
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
package rtc
|
||||
|
||||
import "github.com/livekit/protocol/livekit"
|
||||
|
||||
type ClientInfo struct {
|
||||
*livekit.ClientInfo
|
||||
}
|
||||
|
||||
func (c ClientInfo) SupportsAudioRED() bool {
|
||||
return c.ClientInfo.Browser != "firefox" && c.ClientInfo.Browser != "safari"
|
||||
}
|
||||
@@ -177,9 +177,6 @@ func NewWebRTCConfig(conf *config.Config, externalIP string) (*WebRTCConfig, err
|
||||
{Type: webrtc.TypeRTCPFBNACK},
|
||||
{Type: webrtc.TypeRTCPFBNACK, Parameter: "pli"},
|
||||
},
|
||||
Audio: []webrtc.RTCPFeedback{
|
||||
{Type: webrtc.TypeRTCPFBNACK},
|
||||
},
|
||||
},
|
||||
}
|
||||
if rtcConf.CongestionControl.UseSendSideBWE {
|
||||
|
||||
+18
-2
@@ -1,6 +1,7 @@
|
||||
package rtc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/pion/webrtc/v3"
|
||||
@@ -8,12 +9,27 @@ import (
|
||||
"github.com/livekit/protocol/livekit"
|
||||
)
|
||||
|
||||
var opusCodecCapability = webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeOpus, ClockRate: 48000, Channels: 2, SDPFmtpLine: "minptime=10;useinbandfec=1"}
|
||||
|
||||
func registerCodecs(me *webrtc.MediaEngine, codecs []*livekit.Codec, rtcpFeedback RTCPFeedbackConfig) error {
|
||||
opusCodec := webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeOpus, ClockRate: 48000, Channels: 2, SDPFmtpLine: "minptime=10;useinbandfec=1", RTCPFeedback: rtcpFeedback.Audio}
|
||||
opusCodec := opusCodecCapability
|
||||
opusCodec.RTCPFeedback = rtcpFeedback.Audio
|
||||
var opusPayload webrtc.PayloadType
|
||||
if isCodecEnabled(codecs, opusCodec) {
|
||||
opusPayload = 111
|
||||
if err := me.RegisterCodec(webrtc.RTPCodecParameters{
|
||||
RTPCodecCapability: opusCodec,
|
||||
PayloadType: 111,
|
||||
PayloadType: opusPayload,
|
||||
}, webrtc.RTPCodecTypeAudio); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
redCodec := webrtc.RTPCodecCapability{MimeType: "audio/red", ClockRate: 48000, Channels: 2}
|
||||
if opusPayload != 0 && isCodecEnabled(codecs, redCodec) {
|
||||
redCodec.SDPFmtpLine = fmt.Sprintf("%d/%d", opusPayload, opusPayload)
|
||||
if err := me.RegisterCodec(webrtc.RTPCodecParameters{
|
||||
RTPCodecCapability: redCodec,
|
||||
PayloadType: 63,
|
||||
}, webrtc.RTPCodecTypeAudio); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -79,6 +79,7 @@ type ParticipantParams struct {
|
||||
Grants *auth.ClaimGrants
|
||||
InitialVersion uint32
|
||||
ClientConf *livekit.ClientConfiguration
|
||||
ClientInfo ClientInfo
|
||||
Region string
|
||||
Migration bool
|
||||
AdaptiveStream bool
|
||||
@@ -405,6 +406,64 @@ func (p *ParticipantImpl) HandleOffer(offer webrtc.SessionDescription) error {
|
||||
}
|
||||
|
||||
func (p *ParticipantImpl) setCodecPreferencesForPublisher(offer webrtc.SessionDescription) webrtc.SessionDescription {
|
||||
offer = p.setCodecPreferencesOpusRedForPublisher(offer)
|
||||
offer = p.setCodecPreferencesVideoForPublisher(offer)
|
||||
return offer
|
||||
}
|
||||
|
||||
func (p *ParticipantImpl) setCodecPreferencesOpusRedForPublisher(offer webrtc.SessionDescription) webrtc.SessionDescription {
|
||||
parsed, lastAudio, err := p.TransportManager.GetLastUnmatchedMediaForOffer(offer, "audio")
|
||||
if err != nil || lastAudio == nil {
|
||||
return offer
|
||||
}
|
||||
|
||||
codecs, err := codecsFromMediaDescription(lastAudio)
|
||||
if err != nil {
|
||||
return offer
|
||||
}
|
||||
|
||||
var opusPayload uint8
|
||||
for _, codec := range codecs {
|
||||
if strings.EqualFold(codec.Name, "opus") {
|
||||
opusPayload = codec.PayloadType
|
||||
break
|
||||
}
|
||||
}
|
||||
if opusPayload == 0 {
|
||||
return offer
|
||||
}
|
||||
|
||||
var preferredCodecs, leftCodecs []string
|
||||
for _, codec := range codecs {
|
||||
// codec contain opus/red
|
||||
if strings.EqualFold(codec.Name, "red") && strings.Contains(codec.Fmtp, strconv.FormatInt(int64(opusPayload), 10)) {
|
||||
preferredCodecs = append(preferredCodecs, strconv.FormatInt(int64(codec.PayloadType), 10))
|
||||
} else {
|
||||
leftCodecs = append(leftCodecs, strconv.FormatInt(int64(codec.PayloadType), 10))
|
||||
}
|
||||
}
|
||||
|
||||
// no opus/red found
|
||||
if len(preferredCodecs) == 0 {
|
||||
return offer
|
||||
}
|
||||
|
||||
lastAudio.MediaName.Formats = append(lastAudio.MediaName.Formats[:0], preferredCodecs...)
|
||||
lastAudio.MediaName.Formats = append(lastAudio.MediaName.Formats, leftCodecs...)
|
||||
|
||||
bytes, err := parsed.Marshal()
|
||||
if err != nil {
|
||||
p.params.Logger.Errorw("failed to marshal offer", err)
|
||||
return offer
|
||||
}
|
||||
|
||||
return webrtc.SessionDescription{
|
||||
Type: offer.Type,
|
||||
SDP: string(bytes),
|
||||
}
|
||||
}
|
||||
|
||||
func (p *ParticipantImpl) setCodecPreferencesVideoForPublisher(offer webrtc.SessionDescription) webrtc.SessionDescription {
|
||||
parsed, lastVideo, err := p.TransportManager.GetLastUnmatchedMediaForOffer(offer, "video")
|
||||
if err != nil || lastVideo == nil {
|
||||
return offer
|
||||
@@ -977,6 +1036,7 @@ func (p *ParticipantImpl) setupTransportManager() error {
|
||||
EnabledCodecs: p.params.EnabledCodecs,
|
||||
SimTracks: p.params.SimTracks,
|
||||
ClientConf: p.params.ClientConf,
|
||||
ClientInfo: p.params.ClientInfo,
|
||||
Migration: p.params.Migration,
|
||||
AllowTCPFallback: p.params.AllowTCPFallback,
|
||||
Logger: p.params.Logger,
|
||||
|
||||
@@ -130,6 +130,7 @@ type TransportParams struct {
|
||||
EnabledCodecs []*livekit.Codec
|
||||
Logger logger.Logger
|
||||
SimTracks map[uint32]SimulcastTrackInfo
|
||||
ClientInfo ClientInfo
|
||||
}
|
||||
|
||||
func newPeerConnection(params TransportParams, onBandwidthEstimator func(estimator cc.BandwidthEstimator)) (*webrtc.PeerConnection, *webrtc.MediaEngine, error) {
|
||||
@@ -139,6 +140,12 @@ func newPeerConnection(params TransportParams, onBandwidthEstimator func(estimat
|
||||
} else {
|
||||
directionConfig = params.Config.Subscriber
|
||||
}
|
||||
|
||||
// enable nack if audio red is not support
|
||||
if !isCodecEnabled(params.EnabledCodecs, webrtc.RTPCodecCapability{MimeType: sfu.MimeTypeAudioRed}) || !params.ClientInfo.SupportsAudioRED() {
|
||||
directionConfig.RTCPFeedback.Audio = append(directionConfig.RTCPFeedback.Audio, webrtc.RTCPFeedback{Type: webrtc.TypeRTCPFBNACK})
|
||||
}
|
||||
|
||||
me, err := createMediaEngine(params.EnabledCodecs, directionConfig)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
|
||||
@@ -30,6 +30,7 @@ type TransportManagerParams struct {
|
||||
EnabledCodecs []*livekit.Codec
|
||||
SimTracks map[uint32]SimulcastTrackInfo
|
||||
ClientConf *livekit.ClientConfiguration
|
||||
ClientInfo ClientInfo
|
||||
Migration bool
|
||||
AllowTCPFallback bool
|
||||
Logger logger.Logger
|
||||
@@ -88,6 +89,7 @@ func NewTransportManager(params TransportManagerParams) (*TransportManager, erro
|
||||
EnabledCodecs: enabledCodecs,
|
||||
Logger: LoggerWithPCTarget(params.Logger, livekit.SignalTarget_PUBLISHER),
|
||||
SimTracks: params.SimTracks,
|
||||
ClientInfo: params.ClientInfo,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -119,6 +121,7 @@ func NewTransportManager(params TransportManagerParams) (*TransportManager, erro
|
||||
Telemetry: params.Telemetry,
|
||||
EnabledCodecs: enabledCodecs,
|
||||
Logger: LoggerWithPCTarget(params.Logger, livekit.SignalTarget_SUBSCRIBER),
|
||||
ClientInfo: params.ClientInfo,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -2,6 +2,7 @@ package rtc
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/pion/webrtc/v3"
|
||||
@@ -29,11 +30,20 @@ func NewWrappedReceiver(receivers []*simulcastReceiver, trackID livekit.TrackID,
|
||||
sfuReceivers = append(sfuReceivers, r.TrackReceiver)
|
||||
}
|
||||
|
||||
codecs := upstreamCodecs
|
||||
// if upstream is opus/red, then add opus to match clients that don't support red
|
||||
if len(codecs) == 1 && strings.EqualFold(codecs[0].MimeType, sfu.MimeTypeAudioRed) {
|
||||
codecs = append(codecs, webrtc.RTPCodecParameters{
|
||||
RTPCodecCapability: opusCodecCapability,
|
||||
PayloadType: 111,
|
||||
})
|
||||
}
|
||||
|
||||
return &WrappedReceiver{
|
||||
receivers: sfuReceivers,
|
||||
trackID: trackID,
|
||||
streamId: streamId,
|
||||
codecs: upstreamCodecs,
|
||||
codecs: codecs,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,15 +58,19 @@ func (r *WrappedReceiver) StreamID() string {
|
||||
func (r *WrappedReceiver) DetermineReceiver(codec webrtc.RTPCodecCapability) {
|
||||
r.determinedCodec = codec
|
||||
for _, receiver := range r.receivers {
|
||||
if receiver.Codec().MimeType == codec.MimeType {
|
||||
if c := receiver.Codec(); c.MimeType == codec.MimeType {
|
||||
r.TrackReceiver = receiver
|
||||
break
|
||||
} else if strings.EqualFold(c.MimeType, sfu.MimeTypeAudioRed) && strings.EqualFold(codec.MimeType, webrtc.MimeTypeOpus) {
|
||||
// audio opus/red can match opus only
|
||||
r.TrackReceiver = receiver.GetPrimaryReceiverForRed()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *WrappedReceiver) Codecs() []webrtc.RTPCodecParameters {
|
||||
codecs := make([]webrtc.RTPCodecParameters, len(r.receivers))
|
||||
codecs := make([]webrtc.RTPCodecParameters, len(r.codecs))
|
||||
copy(codecs, r.codecs)
|
||||
return codecs
|
||||
}
|
||||
@@ -231,3 +245,8 @@ func (d *DummyReceiver) TrackInfo() *livekit.TrackInfo {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DummyReceiver) GetPrimaryReceiverForRed() sfu.TrackReceiver {
|
||||
// DummyReceiver used for video, it should not have RED codec
|
||||
return d
|
||||
}
|
||||
|
||||
@@ -279,6 +279,7 @@ func (r *RoomManager) StartSession(
|
||||
Grants: pi.Grants,
|
||||
Logger: pLogger,
|
||||
ClientConf: clientConf,
|
||||
ClientInfo: rtc.ClientInfo{ClientInfo: pi.Client},
|
||||
Region: pi.Region,
|
||||
AdaptiveStream: pi.AdaptiveStream,
|
||||
AllowTCPFallback: r.config.RTC.AllowTCPFallback,
|
||||
|
||||
+33
-5
@@ -55,6 +55,9 @@ type TrackReceiver interface {
|
||||
|
||||
GetLayerDimension(layer int32) (uint32, uint32)
|
||||
TrackInfo() *livekit.TrackInfo
|
||||
|
||||
// Get primary receiver if this receiver represents a RED codec; otherwise it will return itself
|
||||
GetPrimaryReceiverForRed() TrackReceiver
|
||||
}
|
||||
|
||||
// WebRTCReceiver receives a media track
|
||||
@@ -71,6 +74,7 @@ type WebRTCReceiver struct {
|
||||
codec webrtc.RTPCodecParameters
|
||||
isSimulcast bool
|
||||
isSVC bool
|
||||
isRED bool
|
||||
onCloseHandler func()
|
||||
closeOnce sync.Once
|
||||
closed atomic.Bool
|
||||
@@ -101,6 +105,8 @@ type WebRTCReceiver struct {
|
||||
|
||||
// update layer info
|
||||
onMaxLayerChange func(maxLayer int32)
|
||||
|
||||
primaryReceiver atomic.Value // *RedPrimaryReceiver
|
||||
}
|
||||
|
||||
func RidToLayer(rid string) int32 {
|
||||
@@ -126,6 +132,10 @@ func IsSvcCodec(mime string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func IsRedCodec(mime string) bool {
|
||||
return strings.HasSuffix(strings.ToLower(mime), "red")
|
||||
}
|
||||
|
||||
type ReceiverOpts func(w *WebRTCReceiver) *WebRTCReceiver
|
||||
|
||||
// WithPliThrottleConfig indicates minimum time(ms) between sending PLIs
|
||||
@@ -186,6 +196,7 @@ func NewWebRTCReceiver(
|
||||
streamTrackerManager: NewStreamTrackerManager(logger, trackInfo),
|
||||
trackInfo: trackInfo,
|
||||
isSVC: IsSvcCodec(track.Codec().MimeType),
|
||||
isRED: IsRedCodec(track.Codec().MimeType),
|
||||
}
|
||||
|
||||
w.streamTrackerManager.OnMaxLayerChanged(w.onMaxLayerChange)
|
||||
@@ -376,7 +387,7 @@ func (w *WebRTCReceiver) AddDownTrack(track TrackSender) error {
|
||||
}
|
||||
}
|
||||
|
||||
w.storeDownTrack(track)
|
||||
w.downTrackSpreader.Store(track)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -533,6 +544,9 @@ func (w *WebRTCReceiver) forwardRTP(layer int32) {
|
||||
w.closeOnce.Do(func() {
|
||||
w.closed.Store(true)
|
||||
w.closeTracks()
|
||||
if pr := w.primaryReceiver.Load(); pr != nil {
|
||||
pr.(*RedPrimaryReceiver).Close()
|
||||
}
|
||||
})
|
||||
|
||||
w.streamTrackerManager.RemoveTracker(layer)
|
||||
@@ -565,6 +579,9 @@ func (w *WebRTCReceiver) forwardRTP(layer int32) {
|
||||
w.downTrackSpreader.Broadcast(func(dt TrackSender) {
|
||||
_ = dt.WriteRTP(pkt, spatialLayer)
|
||||
})
|
||||
if pr := w.primaryReceiver.Load(); pr != nil {
|
||||
pr.(*RedPrimaryReceiver).ForwardRTP(pkt, spatialLayer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -581,10 +598,6 @@ func (w *WebRTCReceiver) closeTracks() {
|
||||
}
|
||||
}
|
||||
|
||||
func (w *WebRTCReceiver) storeDownTrack(track TrackSender) {
|
||||
w.downTrackSpreader.Store(track)
|
||||
}
|
||||
|
||||
func (w *WebRTCReceiver) DebugInfo() map[string]interface{} {
|
||||
info := map[string]interface{}{
|
||||
"Simulcast": w.isSimulcast,
|
||||
@@ -607,3 +620,18 @@ func (w *WebRTCReceiver) DebugInfo() map[string]interface{} {
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
func (w *WebRTCReceiver) GetPrimaryReceiverForRed() TrackReceiver {
|
||||
if !w.isRED || w.closed.Load() {
|
||||
return w
|
||||
}
|
||||
|
||||
if w.primaryReceiver.Load() == nil {
|
||||
pr := NewRedPrimaryReceiver(w, DownTrackSpreaderParams{
|
||||
Threshold: w.lbThreshold,
|
||||
Logger: w.logger,
|
||||
})
|
||||
w.primaryReceiver.CompareAndSwap(nil, pr)
|
||||
}
|
||||
return w.primaryReceiver.Load().(*RedPrimaryReceiver)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package sfu
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
|
||||
"go.uber.org/atomic"
|
||||
|
||||
"github.com/pion/rtp"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/sfu/buffer"
|
||||
"github.com/livekit/protocol/livekit"
|
||||
"github.com/livekit/protocol/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
MimeTypeAudioRed = "audio/red"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrIncompleteRedHeader = errors.New("incomplete red block header")
|
||||
ErrIncompleteRedBlock = errors.New("incomplete red block payload")
|
||||
)
|
||||
|
||||
type RedPrimaryReceiver struct {
|
||||
TrackReceiver
|
||||
downTrackSpreader *DownTrackSpreader
|
||||
logger logger.Logger
|
||||
closed atomic.Bool
|
||||
}
|
||||
|
||||
func NewRedPrimaryReceiver(receiver TrackReceiver, dsp DownTrackSpreaderParams) *RedPrimaryReceiver {
|
||||
return &RedPrimaryReceiver{
|
||||
TrackReceiver: receiver,
|
||||
downTrackSpreader: NewDownTrackSpreader(dsp),
|
||||
logger: dsp.Logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RedPrimaryReceiver) ForwardRTP(pkt *buffer.ExtPacket, spatialLayer int32) {
|
||||
// extract primary payload from RED and forward to downtracks
|
||||
if r.downTrackSpreader.DownTrackCount() == 0 {
|
||||
return
|
||||
}
|
||||
payload, err := ExtractPrimaryEncodingForRED(pkt.Packet.Payload)
|
||||
if err != nil {
|
||||
r.logger.Errorw("get primary encoding for red failed", err, "payloadtype", pkt.Packet.PayloadType)
|
||||
return
|
||||
}
|
||||
|
||||
pPkt := *pkt
|
||||
primaryRtpPacket := *pkt.Packet
|
||||
primaryRtpPacket.Payload = payload
|
||||
pPkt.Packet = &primaryRtpPacket
|
||||
|
||||
// not modify the ExtPacket.RawPacket here for performance since it is not used by the DownTrack,
|
||||
// otherwise it should be set to the correct value (marshal the primary rtp packet)
|
||||
|
||||
r.downTrackSpreader.Broadcast(func(dt TrackSender) {
|
||||
_ = dt.WriteRTP(&pPkt, spatialLayer)
|
||||
})
|
||||
|
||||
// TODO : detect rtp packet lost, recover it from the redundant payload then send to downstreams.
|
||||
}
|
||||
|
||||
func (r *RedPrimaryReceiver) AddDownTrack(track TrackSender) error {
|
||||
if r.closed.Load() {
|
||||
return ErrReceiverClosed
|
||||
}
|
||||
|
||||
if r.downTrackSpreader.HasDownTrack(track.SubscriberID()) {
|
||||
r.logger.Infow("subscriberID already exists, replace the downtrack", "subscriberID", track.SubscriberID())
|
||||
}
|
||||
|
||||
r.downTrackSpreader.Store(track)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RedPrimaryReceiver) DeleteDownTrack(subscriberID livekit.ParticipantID) {
|
||||
if r.closed.Load() {
|
||||
return
|
||||
}
|
||||
|
||||
r.downTrackSpreader.Free(subscriberID)
|
||||
}
|
||||
|
||||
func (r *RedPrimaryReceiver) Close() {
|
||||
r.closed.Store(true)
|
||||
for _, dt := range r.downTrackSpreader.ResetAndGetDownTracks() {
|
||||
dt.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RedPrimaryReceiver) ReadRTP(buf []byte, layer uint8, sn uint16) (int, error) {
|
||||
n, err := r.TrackReceiver.ReadRTP(buf, layer, sn)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
|
||||
var pkt rtp.Packet
|
||||
pkt.Unmarshal(buf[:n])
|
||||
payload, err := ExtractPrimaryEncodingForRED(pkt.Payload)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
pkt.Payload = payload
|
||||
|
||||
return pkt.MarshalTo(buf)
|
||||
}
|
||||
|
||||
func ExtractPrimaryEncodingForRED(payload []byte) ([]byte, error) {
|
||||
|
||||
/* RED payload https://datatracker.ietf.org/doc/html/rfc2198#section-3
|
||||
0 1 2 3
|
||||
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
|F| block PT | timestamp offset | block length |
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
F: 1 bit First bit in header indicates whether another header block
|
||||
follows. If 1 further header blocks follow, if 0 this is the
|
||||
last header block.
|
||||
*/
|
||||
|
||||
var blockLength int
|
||||
for {
|
||||
if payload[0]&0x80 == 0 {
|
||||
// last block is primary encoding data
|
||||
payload = payload[1:]
|
||||
break
|
||||
} else {
|
||||
if len(payload) < 4 {
|
||||
// illegal data
|
||||
return nil, ErrIncompleteRedHeader
|
||||
}
|
||||
blockLength += int(binary.BigEndian.Uint16(payload[2:]) & 0x03FF)
|
||||
payload = payload[4:]
|
||||
}
|
||||
}
|
||||
|
||||
if len(payload) < blockLength {
|
||||
return nil, ErrIncompleteRedBlock
|
||||
}
|
||||
|
||||
return payload[blockLength:], nil
|
||||
}
|
||||
Reference in New Issue
Block a user