Populate SDP cid in track info when available. (#3845)

* Populate SDP cid in track info when available.

- Adding SDP cid to TrackInfo. Browsers like FF uses a different stream
  id for AddTrack and actual SDP offer. So, have to look up using both
  on server side. To make it easier, store both (only if different) in
  TrackInfo.
- Use a codec in TrackInfo for audio also. There is some discussion
  around doing simulcast codec for audio so that something like PSTN can
  use G.711 without any transcoding. So, just keep it consistent between
  audio and video.
- Populate SDP cid when SDP offer is received. It could populate a
  pending track or an already published track if the new offer is for a
  back up codec where the primary codec is already published.
- Passed around parsed offer to more places to avoid parsing multiple
  times.
- Clean up MediaTrack interface a bit and remove unneeded methods.

* WIP

* WIP

* deps

* stream allocator mime aware

* clean up

* populate SDP cid before munging

* interface methods
This commit is contained in:
Raja Subramanian
2025-08-13 10:53:16 +05:30
committed by GitHub
parent eed27885e5
commit fa5f4ef33c
34 changed files with 503 additions and 1051 deletions
+146 -75
View File
@@ -27,6 +27,7 @@ import (
"github.com/frostbyte73/core"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/pion/rtcp"
"github.com/pion/sdp/v3"
"github.com/pion/webrtc/v4"
"github.com/pkg/errors"
"go.uber.org/atomic"
@@ -1009,13 +1010,8 @@ func (p *ParticipantImpl) HandleSignalSourceClose() {
}
}
func (p *ParticipantImpl) synthesizeAddTrackRequests(offer webrtc.SessionDescription) error {
parsed, err := offer.Unmarshal()
if err != nil {
return err
}
for _, m := range parsed.MediaDescriptions {
func (p *ParticipantImpl) synthesizeAddTrackRequests(parsedOffer *sdp.SessionDescription) error {
for _, m := range parsedOffer.MediaDescriptions {
if !strings.EqualFold(m.MediaName.Media, "audio") && !strings.EqualFold(m.MediaName.Media, "video") {
continue
}
@@ -1068,18 +1064,9 @@ func (p *ParticipantImpl) synthesizeAddTrackRequests(offer webrtc.SessionDescrip
return nil
}
func (p *ParticipantImpl) updateRidsFromSDP(offer *webrtc.SessionDescription) {
if offer == nil {
return
}
parsed, err := offer.Unmarshal()
if err != nil {
return
}
func (p *ParticipantImpl) updateRidsFromSDP(parsed *sdp.SessionDescription, unmatchVideos []*sdp.MediaDescription) {
for _, m := range parsed.MediaDescriptions {
if m.MediaName.Media != "video" {
if m.MediaName.Media != "video" || !slices.Contains(unmatchVideos, m) {
continue
}
@@ -1088,33 +1075,75 @@ func (p *ParticipantImpl) updateRidsFromSDP(offer *webrtc.SessionDescription) {
continue
}
// SIMULCAST-CODEC-TODO - have to update published track's TrackInfo when backup codec starts publishing
p.pendingTracksLock.Lock()
pti := p.pendingTracks[mst]
if pti != nil {
getRids := func(inRids buffer.VideoLayersRid) buffer.VideoLayersRid {
var outRids buffer.VideoLayersRid
rids, ok := sdpHelper.GetSimulcastRids(m)
if ok {
// does not work for clients that use a different media stream track in SDP (e.g. Firefox)
// one option is to look up by track type, but that fails when there are multiple pending tracks
// of the same type
n := min(len(rids), len(pti.sdpRids))
n := min(len(rids), len(inRids))
for i := 0; i < n; i++ {
pti.sdpRids[i] = rids[i]
outRids[i] = rids[i]
}
for i := n; i < len(pti.sdpRids); i++ {
pti.sdpRids[i] = ""
for i := n; i < len(inRids); i++ {
outRids[i] = ""
}
pti.sdpRids = buffer.NormalizeVideoLayersRid(pti.sdpRids)
outRids = buffer.NormalizeVideoLayersRid(outRids)
} else {
for i := 0; i < len(inRids); i++ {
outRids[i] = ""
}
}
p.pubLogger.Debugw(
"pending track rids updated",
"trackID", pti.trackInfos[0].Sid,
"pendingTrack", pti,
)
return outRids
}
p.pendingTracksLock.Lock()
pti := p.getPendingTrackPrimaryBySdpCid(mst, true)
if pti != nil {
pti.sdpRids = getRids(pti.sdpRids)
p.pubLogger.Debugw(
"pending track rids updated",
"trackID", pti.trackInfos[0].Sid,
"pendingTrack", pti,
)
ti := pti.trackInfos[0]
for _, codec := range ti.Codecs {
if codec.Cid == mst || codec.SdpCid == mst {
mimeType := mime.NormalizeMimeType(codec.MimeType)
for _, layer := range codec.Layers {
layer.SpatialLayer = buffer.VideoQualityToSpatialLayer(mimeType, layer.Quality, ti)
layer.Rid = buffer.VideoQualityToRid(mimeType, layer.Quality, ti, pti.sdpRids)
}
}
}
}
p.pendingTracksLock.Unlock()
if pti == nil {
// track could already be published, but this could be back up codec offer,
// so check in published tracks also
mt := p.getPublishedTrackBySdpCid(mst)
if mt != nil {
mimeType := mt.(*MediaTrack).GetMimeTypeForSdpCid(mst)
if mimeType != mime.MimeTypeUnknown {
rids := getRids(buffer.DefaultVideoLayersRid)
mt.(*MediaTrack).UpdateCodecRids(mimeType, rids)
p.pubLogger.Debugw(
"published track rids updated",
"trackID", mt.ID(),
"mime", mimeType,
"track", logger.Proto(mt.ToProto()),
)
} else {
p.pubLogger.Warnw(
"could not get mime type for sdp cid", nil,
"trackID", mt.ID(),
"sdpCid", mst,
"track", logger.Proto(mt.ToProto()),
)
}
}
}
}
}
@@ -1127,25 +1156,50 @@ func (p *ParticipantImpl) HandleOffer(offer webrtc.SessionDescription, offerId u
"offerId", offerId,
)
parsedOffer, err := offer.Unmarshal()
if err != nil {
p.pubLogger.Warnw(
"could not parse offer", err,
"transport", livekit.SignalTarget_PUBLISHER,
"offer", offer,
"offerId", offerId,
)
return err
}
if p.params.UseOneShotSignallingMode {
if err := p.synthesizeAddTrackRequests(offer); err != nil {
if err := p.synthesizeAddTrackRequests(parsedOffer); err != nil {
return err
}
}
shouldPend := false
if p.MigrateState() == types.MigrateStateInit {
shouldPend = true
unmatchAudios, unmatchVideos := p.populateSdpCid(parsedOffer)
parsedOffer = p.setCodecPreferencesForPublisher(parsedOffer, unmatchAudios, unmatchVideos)
p.updateRidsFromSDP(parsedOffer, unmatchVideos)
// put together munged offer after setting codec preferences
bytes, err := parsedOffer.Marshal()
if err != nil {
p.pubLogger.Errorw("failed to marshal offer", err)
return err
}
offer = webrtc.SessionDescription{
Type: offer.Type,
SDP: string(bytes),
}
err = p.TransportManager.HandleOffer(offer, offerId, p.MigrateState() == types.MigrateStateInit)
if err != nil {
return err
}
offer = p.setCodecPreferencesForPublisher(offer)
p.updateRidsFromSDP(&offer)
err := p.TransportManager.HandleOffer(offer, offerId, shouldPend)
if p.params.UseOneShotSignallingMode {
if onSubscriberReady := p.getOnSubscriberReady(); onSubscriberReady != nil {
go onSubscriberReady(p)
}
}
return err
}
@@ -1217,7 +1271,12 @@ func (p *ParticipantImpl) handleMigrateTracks() []*MediaTrack {
}
if len(pti.trackInfos) > 1 {
p.pubLogger.Warnw("too many pending migrated tracks", nil, "trackID", pti.trackInfos[0].Sid, "count", len(pti.trackInfos), "cid", cid)
p.pubLogger.Warnw(
"too many pending migrated tracks", nil,
"trackID", pti.trackInfos[0].Sid,
"count", len(pti.trackInfos),
"cid", cid,
)
}
mt := p.addMigratedTrack(cid, pti.trackInfos[0])
@@ -1282,20 +1341,18 @@ func (p *ParticipantImpl) SetMigrateInfo(
p.pendingTracks[t.GetCid()] = &pendingTrackInfo{
trackInfos: []*livekit.TrackInfo{ti},
sdpRids: buffer.DefaultVideoLayersRid,
migrated: true,
createdAt: time.Now(),
}
p.pubLogger.Infow(
"pending track added (migration)",
"trackID", ti.Sid,
"cid", t.GetCid(),
"pendingTrack", p.pendingTracks[t.GetCid()],
)
}
p.pendingTracksLock.Unlock()
p.updateRidsFromSDP(previousOffer)
if len(mediaTracks) != 0 {
p.setIsPublisher(true)
}
@@ -2627,8 +2684,7 @@ func (p *ParticipantImpl) addPendingTrackLocked(req *livekit.AddTrackRequest) *l
}
track.(*MediaTrack).UpdateCodecInfo(req.SimulcastCodecs)
ti := track.ToProto()
return ti
return track.ToProto()
}
backupCodecPolicy := req.BackupCodecPolicy
@@ -2637,6 +2693,10 @@ func (p *ParticipantImpl) addPendingTrackLocked(req *livekit.AddTrackRequest) *l
}
cloneLayers := func(layers []*livekit.VideoLayer) []*livekit.VideoLayer {
if len(layers) == 0 {
return nil
}
clonedLayers := make([]*livekit.VideoLayer, 0, len(layers))
for _, l := range layers {
clonedLayers = append(clonedLayers, utils.CloneProto(l))
@@ -2672,13 +2732,11 @@ func (p *ParticipantImpl) addPendingTrackLocked(req *livekit.AddTrackRequest) *l
p.setTrackID(req.Cid, ti)
if len(req.SimulcastCodecs) == 0 {
if req.Type == livekit.TrackType_VIDEO {
// clients not supporting simulcast codecs, synthesise a codec
ti.Codecs = append(ti.Codecs, &livekit.SimulcastCodecInfo{
Cid: req.Cid,
Layers: cloneLayers(req.Layers),
})
}
// clients not supporting simulcast codecs, synthesise a codec
ti.Codecs = append(ti.Codecs, &livekit.SimulcastCodecInfo{
Cid: req.Cid,
Layers: cloneLayers(req.Layers),
})
} else {
seenCodecs := make(map[string]struct{})
for _, codec := range req.SimulcastCodecs {
@@ -2944,15 +3002,7 @@ func (p *ParticipantImpl) mediaTrackReceived(track sfu.TrackRemote, rtpReceiver
layer.Rid = buffer.VideoQualityToRid(mimeType, layer.Quality, ti, sdpRids)
}
for _, codec := range ti.Codecs {
mimeType := mime.NormalizeMimeType(codec.MimeType)
for _, layer := range codec.Layers {
layer.SpatialLayer = buffer.VideoQualityToSpatialLayer(mimeType, layer.Quality, ti)
layer.Rid = buffer.VideoQualityToRid(mimeType, layer.Quality, ti, sdpRids)
}
}
mt = p.addMediaTrack(signalCid, track.ID(), ti)
mt = p.addMediaTrack(signalCid, ti)
newTrack = true
// if the addTrackRequest is sent before participant active then it means the client tries to publish
@@ -2964,7 +3014,6 @@ func (p *ParticipantImpl) mediaTrackReceived(track sfu.TrackRemote, rtpReceiver
pubTime = time.Since(createdAt)
p.dirty.Store(true)
}
p.pendingTracksLock.Unlock()
_, isReceiverAdded := mt.AddReceiver(rtpReceiver, track, mid)
@@ -3011,11 +3060,15 @@ func (p *ParticipantImpl) addMigratedTrack(cid string, ti *livekit.TrackInfo) *M
p.pubLogger.Infow("add migrated track", "cid", cid, "trackID", ti.Sid, "track", logger.Proto(ti))
rtpReceiver := p.TransportManager.GetPublisherRTPReceiver(ti.Mid)
if rtpReceiver == nil {
p.pubLogger.Errorw("could not find receiver for migrated track", nil, "trackID", ti.Sid, "mid", ti.Mid)
p.pubLogger.Errorw(
"could not find receiver for migrated track", nil,
"trackID", ti.Sid,
"mid", ti.Mid,
)
return nil
}
mt := p.addMediaTrack(cid, cid, ti)
mt := p.addMediaTrack(cid, ti)
potentialCodecs := make([]webrtc.RTPCodecParameters, 0, len(ti.Codecs))
parameters := rtpReceiver.GetParameters()
@@ -3058,10 +3111,8 @@ func (p *ParticipantImpl) addMigratedTrack(cid string, ti *livekit.TrackInfo) *M
return mt
}
func (p *ParticipantImpl) addMediaTrack(signalCid string, sdpCid string, ti *livekit.TrackInfo) *MediaTrack {
func (p *ParticipantImpl) addMediaTrack(signalCid string, ti *livekit.TrackInfo) *MediaTrack {
mt := NewMediaTrack(MediaTrackParams{
SignalCid: signalCid,
SdpCid: sdpCid,
ParticipantID: p.ID,
ParticipantIdentity: p.params.Identity,
ParticipantVersion: p.version.Load(),
@@ -3112,12 +3163,12 @@ func (p *ParticipantImpl) addMediaTrack(signalCid string, sdpCid string, ti *liv
}
trackID := livekit.TrackID(ti.Sid)
mt.AddOnClose(func(isExpectedToRsume bool) {
mt.AddOnClose(func(isExpectedToResume bool) {
if p.supervisor != nil {
p.supervisor.ClearPublishedTrack(trackID, mt)
}
if !isExpectedToRsume {
if !isExpectedToResume {
p.params.Telemetry.TrackUnpublished(
context.Background(),
p.ID(),
@@ -3137,7 +3188,12 @@ func (p *ParticipantImpl) addMediaTrack(signalCid string, sdpCid string, ti *liv
p.dirty.Store(true)
p.pubLogger.Debugw("track unpublished", "trackID", ti.Sid, "expectedToRsume", isExpectedToRsume, "track", logger.Proto(ti))
p.pubLogger.Debugw(
"track unpublished",
"trackID", ti.Sid,
"expectedToResume", isExpectedToResume,
"track", logger.Proto(ti),
)
if onTrackUnpublished := p.getOnTrackUnpublished(); onTrackUnpublished != nil {
onTrackUnpublished(p, mt)
}
@@ -3232,6 +3288,20 @@ func (p *ParticipantImpl) getPendingTrack(clientId string, kind livekit.TrackTyp
return signalCid, utils.CloneProto(pendingInfo.trackInfos[0]), pendingInfo.sdpRids, pendingInfo.migrated, pendingInfo.createdAt
}
func (p *ParticipantImpl) getPendingTrackPrimaryBySdpCid(sdpCid string, skipQueued bool) *pendingTrackInfo {
for _, pti := range p.pendingTracks {
ti := pti.trackInfos[0]
if len(ti.Codecs) == 0 {
continue
}
if ti.Codecs[0].Cid == sdpCid || ti.Codecs[0].SdpCid == sdpCid {
return pti
}
}
return nil
}
// setTrackID either generates a new TrackID for an AddTrackRequest
func (p *ParticipantImpl) setTrackID(cid string, info *livekit.TrackInfo) {
var trackID string
@@ -3266,7 +3336,8 @@ func (p *ParticipantImpl) setTrackID(cid string, info *livekit.TrackInfo) {
func (p *ParticipantImpl) getPublishedTrackBySignalCid(clientId string) types.MediaTrack {
for _, publishedTrack := range p.GetPublishedTracks() {
if publishedTrack.(types.LocalMediaTrack).SignalCid() == clientId {
if publishedTrack.(types.LocalMediaTrack).HasSignalCid(clientId) {
p.pubLogger.Debugw("found track by signal cid", "signalCid", clientId, "trackID", publishedTrack.ID())
return publishedTrack
}
}