Session migration (#319)

* migrate between nodes

* session migration

* bug fix

* use version instead of query parameter

* clean code

* clean

* merge master

* solve comments

* solve comment

* update go.mod

Co-authored-by: cnderrauber <zengjie9004@gmail.com>
This commit is contained in:
cnderrauber
2022-01-08 18:54:23 +08:00
committed by GitHub
co-authored by cnderrauber
parent ecf9590d56
commit 8582ca4c9b
21 changed files with 896 additions and 62 deletions
+171
View File
@@ -1,6 +1,8 @@
package rtc
import (
"errors"
"strings"
"sync"
"time"
@@ -30,6 +32,11 @@ const (
negotiationRetry
)
type SimulcastTrackInfo struct {
Mid string
Rid string
}
// PCTransport is a wrapper around PeerConnection, with some helper methods
type PCTransport struct {
pc *webrtc.PeerConnection
@@ -46,6 +53,8 @@ type PCTransport struct {
streamAllocator *sfu.StreamAllocator
logger logger.Logger
previousAnswer *webrtc.SessionDescription
}
type TransportParams struct {
@@ -57,6 +66,7 @@ type TransportParams struct {
Telemetry telemetry.TelemetryService
EnabledCodecs []*livekit.Codec
Logger logger.Logger
SimTracks map[uint32]SimulcastTrackInfo
}
// LK-TODO-SSBWE func newPeerConnection(params TransportParams, onBandwidthEstimator func(estimator cc.BandwidthEstimator)) (*webrtc.PeerConnection, *webrtc.MediaEngine, error) {
@@ -115,6 +125,14 @@ func newPeerConnection(params TransportParams) (*webrtc.PeerConnection, *webrtc.
*/
}
}
if len(params.SimTracks) > 0 {
f, err := NewUnhandleSimulcastInterceptorFactory(UnhandleSimulcastTracks(params.SimTracks))
if err != nil {
params.Logger.Errorw("NewUnhandleSimulcastInterceptorFactory failed", err)
} else {
ir.Add(f)
}
}
api := webrtc.NewAPI(
webrtc.WithMediaEngine(me),
webrtc.WithSettingEngine(se),
@@ -181,6 +199,8 @@ func (t *PCTransport) AddICECandidate(candidate webrtc.ICECandidateInit) error {
return nil
}
t.logger.Debugw("add candidate ", "candidate", candidate.Candidate)
return t.pc.AddICECandidate(candidate)
}
@@ -284,6 +304,14 @@ func (t *PCTransport) createAndSendOffer(options *webrtc.OfferOptions) error {
return nil
}
if t.previousAnswer != nil {
t.previousAnswer = nil
if options == nil {
options = &webrtc.OfferOptions{}
}
options.ICERestart = true
}
offer, err := t.pc.CreateOffer(options)
if err != nil {
prometheus.ServiceOperationCounter.WithLabelValues("offer", "error", "create").Add(1)
@@ -306,6 +334,101 @@ func (t *PCTransport) createAndSendOffer(options *webrtc.OfferOptions) error {
return nil
}
func (t *PCTransport) preparePC(previousAnswer webrtc.SessionDescription) error {
// sticky data channel to first m-lines, if someday we don't send sdp without media streams to
// client's subscribe pc after joining, should change this step
parsed, err := previousAnswer.Unmarshal()
if err != nil {
return err
}
fp, fpHahs, err := extractFingerprint(parsed)
if err != nil {
return err
}
// for pion generate unmatched sdp, it always append data channel to last m-lines,
// that is not consistent with our subscribe offer which data channel is first m-lines,
// so use a dumb pc to negotiate sdp with only data channel then the data channel will
// sticky to first m-lines(subsequent sdp negotiation will keep m-lines's sequence)
offer, err := t.pc.CreateOffer(nil)
if err != nil {
return err
}
t.pc.SetLocalDescription(offer)
pc2, err := webrtc.NewPeerConnection(webrtc.Configuration{})
if err != nil {
return err
}
defer pc2.Close()
pc2.SetRemoteDescription(offer)
ans, err := pc2.CreateAnswer(nil)
if err != nil {
return err
}
// replace client's fingerprint into dump pc's answer, for pion's dtls process, it will
// keep the firgerprint at first call of SetRemoteDescription, if dumb pc and client pc use
// different fingerprint, that will cause pion denied dtls data after handshake with client
// complete (can't pass fingerprint change).
// in this step, we don't established connection with dump pc(no candidate swap), just use
// sdp negotiation to sticky data channel and keep client's fingerprint
parsedAns, _ := ans.Unmarshal()
fpLine := fpHahs + " " + fp
replaceFP := func(attrs []sdp.Attribute, fpLine string) {
for k := range attrs {
if attrs[k].Key == "fingerprint" {
attrs[k].Value = fpLine
}
}
}
replaceFP(parsedAns.Attributes, fpLine)
for _, m := range parsedAns.MediaDescriptions {
replaceFP(m.Attributes, fpLine)
}
bytes, err := parsedAns.Marshal()
if err != nil {
return err
}
ans.SDP = string(bytes)
return t.pc.SetRemoteDescription(ans)
}
func (t *PCTransport) initPCWithPreviousAnswer(previousOffer webrtc.SessionDescription) error {
if err := t.preparePC(previousOffer); err != nil {
return err
}
parsed, err := previousOffer.Unmarshal()
if err != nil {
return err
}
for _, m := range parsed.MediaDescriptions {
var codecType webrtc.RTPCodecType
switch m.MediaName.Media {
case "video":
codecType = webrtc.RTPCodecTypeVideo
case "audio":
codecType = webrtc.RTPCodecTypeAudio
default:
continue
}
tr, err := t.pc.AddTransceiverFromKind(codecType, webrtc.RTPTransceiverInit{Direction: webrtc.RTPTransceiverDirectionRecvonly})
if err != nil {
return err
}
tr.Stop()
mid := getMidValue(m)
if mid == "" {
return errors.New("mid value not found")
}
tr.SetMid(mid)
}
return nil
}
func (t *PCTransport) OnStreamStateChange(f func(update *sfu.StreamStateUpdate) error) {
if t.streamAllocator == nil {
return
@@ -332,3 +455,51 @@ func (t *PCTransport) RemoveTrack(subTrack types.SubscribedTrack) {
t.streamAllocator.RemoveTrack(subTrack.DownTrack())
}
func (t *PCTransport) SetPreviousAnswer(offer *webrtc.SessionDescription) {
t.lock.Lock()
defer t.lock.Unlock()
if t.pc.RemoteDescription() == nil && t.previousAnswer == nil {
t.previousAnswer = offer
t.initPCWithPreviousAnswer(*t.previousAnswer)
}
}
func getMidValue(media *sdp.MediaDescription) string {
for _, attr := range media.Attributes {
if attr.Key == "mid" {
return attr.Value
}
}
return ""
}
func extractFingerprint(desc *sdp.SessionDescription) (string, string, error) {
fingerprints := []string{}
if fingerprint, haveFingerprint := desc.Attribute("fingerprint"); haveFingerprint {
fingerprints = append(fingerprints, fingerprint)
}
for _, m := range desc.MediaDescriptions {
if fingerprint, haveFingerprint := m.Attribute("fingerprint"); haveFingerprint {
fingerprints = append(fingerprints, fingerprint)
}
}
if len(fingerprints) < 1 {
return "", "", webrtc.ErrSessionDescriptionNoFingerprint
}
for _, m := range fingerprints {
if m != fingerprints[0] {
return "", "", webrtc.ErrSessionDescriptionConflictingFingerprints
}
}
parts := strings.Split(fingerprints[0], " ")
if len(parts) != 2 {
return "", "", webrtc.ErrSessionDescriptionInvalidFingerprint
}
return parts[1], parts[0], nil
}