2020-10-23 03:54:50 +13:00
|
|
|
package webrtc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2022-02-10 09:45:03 +13:00
|
|
|
"net"
|
2021-02-15 02:40:17 +13:00
|
|
|
"strings"
|
2023-03-28 06:28:28 +13:00
|
|
|
"sync"
|
2022-02-13 06:55:56 +13:00
|
|
|
"sync/atomic"
|
2021-02-26 05:16:37 +13:00
|
|
|
"time"
|
2020-10-23 03:54:50 +13:00
|
|
|
|
2022-02-10 09:45:03 +13:00
|
|
|
"github.com/pion/ice/v2"
|
2022-10-18 00:39:31 +13:00
|
|
|
"github.com/pion/interceptor"
|
2023-02-07 07:45:51 +13:00
|
|
|
"github.com/pion/interceptor/pkg/cc"
|
|
|
|
"github.com/pion/interceptor/pkg/gcc"
|
2021-11-29 11:16:26 +13:00
|
|
|
"github.com/pion/rtcp"
|
2021-02-02 11:50:18 +13:00
|
|
|
"github.com/pion/webrtc/v3"
|
2020-10-23 03:54:50 +13:00
|
|
|
"github.com/rs/zerolog"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
|
2022-07-14 10:58:22 +12:00
|
|
|
"github.com/demodesk/neko/internal/config"
|
|
|
|
"github.com/demodesk/neko/internal/webrtc/cursor"
|
|
|
|
"github.com/demodesk/neko/internal/webrtc/pionlog"
|
|
|
|
"github.com/demodesk/neko/pkg/types"
|
|
|
|
"github.com/demodesk/neko/pkg/types/codec"
|
|
|
|
"github.com/demodesk/neko/pkg/types/event"
|
|
|
|
"github.com/demodesk/neko/pkg/types/message"
|
2020-10-23 03:54:50 +13:00
|
|
|
)
|
|
|
|
|
2021-02-26 05:16:37 +13:00
|
|
|
// the duration without network activity before a Agent is considered disconnected. Default is 5 Seconds
|
|
|
|
const disconnectedTimeout = 4 * time.Second
|
|
|
|
|
|
|
|
// the duration without network activity before a Agent is considered failed after disconnected. Default is 25 Seconds
|
|
|
|
const failedTimeout = 6 * time.Second
|
|
|
|
|
|
|
|
// how often the ICE Agent sends extra traffic if there is no activity, if media is flowing no traffic will be sent. Default is 2 seconds
|
|
|
|
const keepAliveInterval = 2 * time.Second
|
|
|
|
|
2022-01-07 08:41:44 +13:00
|
|
|
// send a PLI on an interval so that the publisher is pushing a keyframe every rtcpPLIInterval
|
|
|
|
const rtcpPLIInterval = 3 * time.Second
|
|
|
|
|
2023-02-07 07:45:51 +13:00
|
|
|
// how often we check the bitrate of each client. Default is 250ms
|
|
|
|
const bitrateCheckInterval = 250 * time.Millisecond
|
|
|
|
|
2020-11-02 04:09:48 +13:00
|
|
|
func New(desktop types.DesktopManager, capture types.CaptureManager, config *config.WebRTC) *WebRTCManagerCtx {
|
2022-10-18 00:39:31 +13:00
|
|
|
configuration := webrtc.Configuration{
|
|
|
|
SDPSemantics: webrtc.SDPSemanticsUnifiedPlanWithFallback,
|
|
|
|
}
|
|
|
|
|
|
|
|
if !config.ICELite {
|
|
|
|
ICEServers := []webrtc.ICEServer{}
|
2023-03-28 05:34:24 +13:00
|
|
|
for _, server := range config.ICEServersBackend {
|
2022-10-18 00:39:31 +13:00
|
|
|
var credential any
|
|
|
|
if server.Credential != "" {
|
|
|
|
credential = server.Credential
|
|
|
|
} else {
|
|
|
|
credential = false
|
|
|
|
}
|
|
|
|
|
|
|
|
ICEServers = append(ICEServers, webrtc.ICEServer{
|
|
|
|
URLs: server.URLs,
|
|
|
|
Username: server.Username,
|
|
|
|
Credential: credential,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
configuration.ICEServers = ICEServers
|
|
|
|
}
|
|
|
|
|
2020-11-02 04:09:48 +13:00
|
|
|
return &WebRTCManagerCtx{
|
2022-06-26 06:12:42 +12:00
|
|
|
logger: log.With().Str("module", "webrtc").Logger(),
|
|
|
|
config: config,
|
|
|
|
metrics: newMetrics(),
|
2021-09-27 09:26:22 +13:00
|
|
|
|
2022-10-18 00:39:31 +13:00
|
|
|
webrtcConfiguration: configuration,
|
|
|
|
|
2021-09-27 09:26:22 +13:00
|
|
|
desktop: desktop,
|
|
|
|
capture: capture,
|
|
|
|
curImage: cursor.NewImage(desktop),
|
2021-10-22 09:53:54 +13:00
|
|
|
curPosition: cursor.NewPosition(),
|
2020-10-23 03:54:50 +13:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-02 04:09:48 +13:00
|
|
|
type WebRTCManagerCtx struct {
|
2022-06-26 06:12:42 +12:00
|
|
|
logger zerolog.Logger
|
|
|
|
config *config.WebRTC
|
|
|
|
metrics *metricsCtx
|
|
|
|
peerId int32
|
2021-09-27 09:26:22 +13:00
|
|
|
|
|
|
|
desktop types.DesktopManager
|
|
|
|
capture types.CaptureManager
|
|
|
|
curImage *cursor.ImageCtx
|
|
|
|
curPosition *cursor.PositionCtx
|
2022-01-07 10:28:34 +13:00
|
|
|
|
2022-10-18 00:39:31 +13:00
|
|
|
webrtcConfiguration webrtc.Configuration
|
|
|
|
|
2022-02-10 09:45:03 +13:00
|
|
|
tcpMux ice.TCPMux
|
|
|
|
udpMux ice.UDPMux
|
|
|
|
|
2022-01-07 10:28:34 +13:00
|
|
|
camStop, micStop *func()
|
2020-10-23 03:54:50 +13:00
|
|
|
}
|
|
|
|
|
2020-11-02 04:09:48 +13:00
|
|
|
func (manager *WebRTCManagerCtx) Start() {
|
2021-08-30 04:59:46 +12:00
|
|
|
manager.curImage.Start()
|
|
|
|
|
2022-02-10 09:45:03 +13:00
|
|
|
logger := pionlog.New(manager.logger)
|
|
|
|
|
|
|
|
// add TCP Mux listener
|
|
|
|
if manager.config.TCPMux > 0 {
|
|
|
|
tcpListener, err := net.ListenTCP("tcp", &net.TCPAddr{
|
|
|
|
IP: net.IP{0, 0, 0, 0},
|
|
|
|
Port: manager.config.TCPMux,
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
manager.logger.Panic().Err(err).Msg("unable to setup ice TCP mux")
|
|
|
|
}
|
|
|
|
|
2022-12-13 23:35:03 +13:00
|
|
|
manager.tcpMux = ice.NewTCPMuxDefault(ice.TCPMuxParams{
|
|
|
|
Listener: tcpListener,
|
|
|
|
Logger: logger.NewLogger("ice-tcp"),
|
|
|
|
ReadBufferSize: 32, // receiving channel size
|
|
|
|
WriteBufferSize: 4 * 1024 * 1024, // write buffer size, 4MB
|
|
|
|
})
|
2022-02-10 09:45:03 +13:00
|
|
|
}
|
|
|
|
|
|
|
|
// add UDP Mux listener
|
|
|
|
if manager.config.UDPMux > 0 {
|
2022-12-13 23:35:03 +13:00
|
|
|
var err error
|
|
|
|
manager.udpMux, err = ice.NewMultiUDPMuxFromPort(manager.config.UDPMux,
|
|
|
|
ice.UDPMuxFromPortWithLogger(logger.NewLogger("ice-udp")),
|
|
|
|
)
|
2022-02-10 09:45:03 +13:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
manager.logger.Panic().Err(err).Msg("unable to setup ice UDP mux")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-23 03:54:50 +13:00
|
|
|
manager.logger.Info().
|
2021-08-03 21:06:34 +12:00
|
|
|
Bool("icelite", manager.config.ICELite).
|
|
|
|
Bool("icetrickle", manager.config.ICETrickle).
|
2023-03-28 05:34:24 +13:00
|
|
|
Interface("iceservers-frontend", manager.config.ICEServersFrontend).
|
|
|
|
Interface("iceservers-backend", manager.config.ICEServersBackend).
|
2021-03-18 03:47:49 +13:00
|
|
|
Str("nat1to1", strings.Join(manager.config.NAT1To1IPs, ",")).
|
|
|
|
Str("epr", fmt.Sprintf("%d-%d", manager.config.EphemeralMin, manager.config.EphemeralMax)).
|
2022-02-10 09:45:03 +13:00
|
|
|
Int("tcpmux", manager.config.TCPMux).
|
|
|
|
Int("udpmux", manager.config.UDPMux).
|
2021-08-03 21:06:34 +12:00
|
|
|
Msg("webrtc starting")
|
2020-10-23 03:54:50 +13:00
|
|
|
}
|
|
|
|
|
2020-11-02 04:09:48 +13:00
|
|
|
func (manager *WebRTCManagerCtx) Shutdown() error {
|
2021-09-02 10:00:29 +12:00
|
|
|
manager.logger.Info().Msg("shutdown")
|
2021-02-07 00:59:57 +13:00
|
|
|
|
2021-03-01 06:37:35 +13:00
|
|
|
manager.curImage.Shutdown()
|
|
|
|
manager.curPosition.Shutdown()
|
|
|
|
|
2020-10-23 03:54:50 +13:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-03-18 03:47:49 +13:00
|
|
|
func (manager *WebRTCManagerCtx) ICEServers() []types.ICEServer {
|
2023-03-28 05:34:24 +13:00
|
|
|
return manager.config.ICEServersFrontend
|
2021-02-03 07:21:48 +13:00
|
|
|
}
|
2020-10-23 03:54:50 +13:00
|
|
|
|
2023-02-07 07:45:51 +13:00
|
|
|
func (manager *WebRTCManagerCtx) newPeerConnection(bitrate int, codecs []codec.RTPCodec, logger zerolog.Logger) (*webrtc.PeerConnection, cc.BandwidthEstimator, error) {
|
2022-10-18 00:39:31 +13:00
|
|
|
// create media engine
|
|
|
|
engine := &webrtc.MediaEngine{}
|
|
|
|
for _, codec := range codecs {
|
|
|
|
if err := codec.Register(engine); err != nil {
|
2023-02-07 07:45:51 +13:00
|
|
|
return nil, nil, err
|
2022-10-18 00:39:31 +13:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// create setting engine
|
|
|
|
settings := webrtc.SettingEngine{
|
|
|
|
LoggerFactory: pionlog.New(logger),
|
|
|
|
}
|
|
|
|
|
|
|
|
settings.SetICETimeouts(disconnectedTimeout, failedTimeout, keepAliveInterval)
|
|
|
|
settings.SetNAT1To1IPs(manager.config.NAT1To1IPs, webrtc.ICECandidateTypeHost)
|
|
|
|
settings.SetLite(manager.config.ICELite)
|
2023-01-30 23:31:30 +13:00
|
|
|
// make sure server answer sdp setup as passive, to not force DTLS renegotiation
|
|
|
|
// otherwise iOS renegotiation fails with: Failed to set SSL role for the transport.
|
|
|
|
settings.SetAnsweringDTLSRole(webrtc.DTLSRoleServer)
|
2022-10-18 00:39:31 +13:00
|
|
|
|
|
|
|
var networkType []webrtc.NetworkType
|
|
|
|
|
|
|
|
// udp candidates
|
|
|
|
if manager.udpMux != nil {
|
|
|
|
settings.SetICEUDPMux(manager.udpMux)
|
|
|
|
networkType = append(networkType,
|
|
|
|
webrtc.NetworkTypeUDP4,
|
|
|
|
webrtc.NetworkTypeUDP6,
|
|
|
|
)
|
|
|
|
} else if manager.config.EphemeralMax != 0 {
|
|
|
|
_ = settings.SetEphemeralUDPPortRange(manager.config.EphemeralMin, manager.config.EphemeralMax)
|
|
|
|
networkType = append(networkType,
|
|
|
|
webrtc.NetworkTypeUDP4,
|
|
|
|
webrtc.NetworkTypeUDP6,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
// tcp candidates
|
|
|
|
if manager.tcpMux != nil {
|
|
|
|
settings.SetICETCPMux(manager.tcpMux)
|
|
|
|
networkType = append(networkType,
|
|
|
|
webrtc.NetworkTypeTCP4,
|
|
|
|
webrtc.NetworkTypeTCP6,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
// enable support for TCP and UDP ICE candidates
|
|
|
|
settings.SetNetworkTypes(networkType)
|
|
|
|
|
|
|
|
// create interceptor registry
|
|
|
|
registry := &interceptor.Registry{}
|
2023-02-07 07:45:51 +13:00
|
|
|
|
2023-02-27 09:54:10 +13:00
|
|
|
// create bandwidth estimator
|
|
|
|
estimatorChan := make(chan cc.BandwidthEstimator, 1)
|
|
|
|
if manager.config.EstimatorEnabled {
|
|
|
|
congestionController, err := cc.NewInterceptor(func() (cc.BandwidthEstimator, error) {
|
|
|
|
if bitrate == 0 {
|
|
|
|
bitrate = manager.config.EstimatorInitialBitrate
|
|
|
|
}
|
2023-02-15 09:19:14 +13:00
|
|
|
|
2023-02-27 09:54:10 +13:00
|
|
|
return gcc.NewSendSideBWE(
|
|
|
|
gcc.SendSideBWEInitialBitrate(bitrate),
|
|
|
|
gcc.SendSideBWEPacer(gcc.NewNoOpPacer()),
|
|
|
|
)
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
2023-02-07 07:45:51 +13:00
|
|
|
|
2023-02-27 09:54:10 +13:00
|
|
|
congestionController.OnNewPeerConnection(func(id string, estimator cc.BandwidthEstimator) {
|
|
|
|
estimatorChan <- estimator
|
|
|
|
})
|
2023-02-07 07:45:51 +13:00
|
|
|
|
2023-02-27 09:54:10 +13:00
|
|
|
registry.Add(congestionController)
|
|
|
|
if err = webrtc.ConfigureTWCCHeaderExtensionSender(engine, registry); err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// no estimator, send nil
|
|
|
|
estimatorChan <- nil
|
2023-02-07 07:45:51 +13:00
|
|
|
}
|
|
|
|
|
2022-10-18 00:39:31 +13:00
|
|
|
if err := webrtc.RegisterDefaultInterceptors(engine, registry); err != nil {
|
2023-02-07 07:45:51 +13:00
|
|
|
return nil, nil, err
|
2022-10-18 00:39:31 +13:00
|
|
|
}
|
|
|
|
|
|
|
|
// create new API
|
|
|
|
api := webrtc.NewAPI(
|
|
|
|
webrtc.WithMediaEngine(engine),
|
|
|
|
webrtc.WithSettingEngine(settings),
|
|
|
|
webrtc.WithInterceptorRegistry(registry),
|
|
|
|
)
|
|
|
|
|
|
|
|
// create new peer connection
|
2023-02-07 07:45:51 +13:00
|
|
|
configuration := manager.webrtcConfiguration
|
|
|
|
connection, err := api.NewPeerConnection(configuration)
|
|
|
|
return connection, <-estimatorChan, err
|
2022-10-18 00:39:31 +13:00
|
|
|
}
|
|
|
|
|
2023-02-07 07:45:51 +13:00
|
|
|
func (manager *WebRTCManagerCtx) CreatePeer(session types.Session, bitrate int, videoAuto bool) (*webrtc.SessionDescription, error) {
|
2022-02-13 06:55:56 +13:00
|
|
|
id := atomic.AddInt32(&manager.peerId, 1)
|
2022-06-26 06:12:42 +12:00
|
|
|
manager.metrics.NewConnection(session)
|
2022-02-13 06:55:56 +13:00
|
|
|
|
2021-08-30 04:59:46 +12:00
|
|
|
// add session id to logger context
|
2022-02-13 06:55:56 +13:00
|
|
|
logger := manager.logger.With().Str("session_id", session.ID()).Int32("peer_id", id).Logger()
|
2021-08-30 04:59:46 +12:00
|
|
|
logger.Info().Msg("creating webrtc peer")
|
2021-02-03 08:43:33 +13:00
|
|
|
|
2021-09-27 11:50:49 +13:00
|
|
|
// all audios must have the same codec
|
2022-10-18 00:39:31 +13:00
|
|
|
audio := manager.capture.Audio()
|
|
|
|
audioCodec := audio.Codec()
|
2021-09-27 11:50:49 +13:00
|
|
|
|
2021-09-27 09:26:22 +13:00
|
|
|
// all videos must have the same codec
|
2022-10-18 00:39:31 +13:00
|
|
|
video := manager.capture.Video()
|
|
|
|
videoCodec := video.Codec()
|
2022-07-04 09:21:25 +12:00
|
|
|
|
2023-02-07 07:45:51 +13:00
|
|
|
connection, estimator, err := manager.newPeerConnection(bitrate, []codec.RTPCodec{
|
2022-10-18 00:39:31 +13:00
|
|
|
audioCodec,
|
|
|
|
videoCodec,
|
2021-09-27 09:59:45 +13:00
|
|
|
}, logger)
|
2020-10-23 03:54:50 +13:00
|
|
|
if err != nil {
|
2021-02-03 07:21:48 +13:00
|
|
|
return nil, err
|
2020-10-23 03:54:50 +13:00
|
|
|
}
|
|
|
|
|
2023-02-27 09:54:10 +13:00
|
|
|
// if bitrate is 0, and estimator is enabled, use estimator bitrate
|
|
|
|
if bitrate == 0 && estimator != nil {
|
2023-02-07 07:45:51 +13:00
|
|
|
bitrate = estimator.GetTargetBitrate()
|
|
|
|
}
|
|
|
|
|
2021-09-27 09:26:22 +13:00
|
|
|
// asynchronously send local ICE Candidates
|
2021-02-03 09:12:11 +13:00
|
|
|
if manager.config.ICETrickle {
|
|
|
|
connection.OnICECandidate(func(candidate *webrtc.ICECandidate) {
|
|
|
|
if candidate == nil {
|
|
|
|
logger.Debug().Msg("all local ice candidates sent")
|
|
|
|
return
|
|
|
|
}
|
2021-02-03 08:43:33 +13:00
|
|
|
|
2021-09-02 07:58:39 +12:00
|
|
|
session.Send(
|
|
|
|
event.SIGNAL_CANDIDATE,
|
2021-02-03 09:12:11 +13:00
|
|
|
message.SignalCandidate{
|
2021-09-02 07:58:39 +12:00
|
|
|
ICECandidateInit: candidate.ToJSON(),
|
2021-02-03 09:12:11 +13:00
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
2021-02-03 08:43:33 +13:00
|
|
|
|
2021-09-27 11:50:49 +13:00
|
|
|
// audio track
|
|
|
|
|
2022-10-18 00:39:31 +13:00
|
|
|
audioTrack, err := NewTrack(logger, audioCodec, connection)
|
2021-02-07 06:16:24 +13:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-10-18 00:39:31 +13:00
|
|
|
// set stream for audio track
|
2023-02-07 07:45:51 +13:00
|
|
|
_, err = audioTrack.SetStream(audio)
|
2022-10-18 00:39:31 +13:00
|
|
|
if err != nil {
|
2021-09-27 11:50:49 +13:00
|
|
|
return nil, err
|
2021-02-15 06:16:24 +13:00
|
|
|
}
|
|
|
|
|
2023-03-14 05:55:52 +13:00
|
|
|
// if estimator is disabled, or in passive mode, disable video auto bitrate
|
|
|
|
if !manager.config.EstimatorEnabled || manager.config.EstimatorPassive {
|
2023-02-27 09:54:10 +13:00
|
|
|
videoAuto = false
|
|
|
|
}
|
|
|
|
|
2023-03-07 12:08:53 +13:00
|
|
|
videoRtcp := make(chan []rtcp.Packet, 1)
|
|
|
|
|
2021-09-27 11:50:49 +13:00
|
|
|
// video track
|
2023-03-07 12:08:53 +13:00
|
|
|
videoTrack, err := NewTrack(logger, videoCodec, connection,
|
|
|
|
WithVideoAuto(videoAuto),
|
|
|
|
WithRtcpChan(videoRtcp),
|
|
|
|
)
|
2021-02-05 09:39:48 +13:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-10-18 00:39:31 +13:00
|
|
|
// let video stream bucket manager handle stream subscriptions
|
2023-02-07 07:45:51 +13:00
|
|
|
video.SetReceiver(videoTrack)
|
|
|
|
|
|
|
|
changeVideoFromBitrate := func(peerBitrate int) {
|
|
|
|
// when switching from manual to auto bitrate estimation, in case the estimator is
|
|
|
|
// idle (lastBitrate > maxBitrate), we want to go back to the previous estimated bitrate
|
2023-03-14 05:55:52 +13:00
|
|
|
if peerBitrate == 0 && estimator != nil && !manager.config.EstimatorPassive {
|
2023-02-07 07:45:51 +13:00
|
|
|
peerBitrate = estimator.GetTargetBitrate()
|
|
|
|
manager.logger.Debug().
|
|
|
|
Int("peer_bitrate", peerBitrate).
|
|
|
|
Msg("evaluated bitrate")
|
|
|
|
}
|
|
|
|
|
|
|
|
ok, err := videoTrack.SetBitrate(peerBitrate)
|
|
|
|
if err != nil {
|
|
|
|
logger.Error().Err(err).
|
|
|
|
Int("peer_bitrate", peerBitrate).
|
|
|
|
Msg("unable to set video bitrate")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if !ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
videoID := videoTrack.stream.ID()
|
|
|
|
bitrate := videoTrack.stream.Bitrate()
|
|
|
|
|
|
|
|
manager.metrics.SetVideoID(session, videoID)
|
|
|
|
manager.logger.Debug().
|
|
|
|
Int("peer_bitrate", peerBitrate).
|
|
|
|
Int("video_bitrate", bitrate).
|
|
|
|
Str("video_id", videoID).
|
|
|
|
Msg("peer bitrate triggered video stream change")
|
|
|
|
|
|
|
|
go session.Send(
|
|
|
|
event.SIGNAL_VIDEO,
|
|
|
|
message.SignalVideo{
|
|
|
|
Video: videoID,
|
|
|
|
Bitrate: bitrate,
|
|
|
|
VideoAuto: videoTrack.VideoAuto(),
|
|
|
|
})
|
2021-02-05 09:39:48 +13:00
|
|
|
}
|
|
|
|
|
2023-02-07 07:45:51 +13:00
|
|
|
changeVideoFromID := func(videoID string) (bitrate int) {
|
|
|
|
changed, err := videoTrack.SetVideoID(videoID)
|
|
|
|
if err != nil {
|
|
|
|
logger.Error().Err(err).
|
|
|
|
Str("video_id", videoID).
|
|
|
|
Msg("unable to set video stream")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if !changed {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
bitrate = videoTrack.stream.Bitrate()
|
|
|
|
|
|
|
|
manager.logger.Debug().
|
|
|
|
Str("video_id", videoID).
|
|
|
|
Int("video_bitrate", bitrate).
|
|
|
|
Msg("peer video id triggered video stream change")
|
|
|
|
|
|
|
|
go session.Send(
|
|
|
|
event.SIGNAL_VIDEO,
|
|
|
|
message.SignalVideo{
|
|
|
|
Video: videoID,
|
|
|
|
Bitrate: bitrate,
|
|
|
|
VideoAuto: videoTrack.VideoAuto(),
|
|
|
|
})
|
|
|
|
|
|
|
|
return
|
2022-10-18 00:39:31 +13:00
|
|
|
}
|
2022-10-26 07:25:00 +13:00
|
|
|
|
2023-02-07 07:45:51 +13:00
|
|
|
manager.logger.Info().
|
|
|
|
Int("target_bitrate", bitrate).
|
|
|
|
Msg("estimated initial peer bitrate")
|
|
|
|
|
|
|
|
// set initial video bitrate
|
|
|
|
changeVideoFromBitrate(bitrate)
|
|
|
|
|
2023-02-27 09:54:10 +13:00
|
|
|
// if estimator is enabled, use it to change video stream
|
|
|
|
if estimator != nil {
|
|
|
|
go func() {
|
|
|
|
// use a ticker to get current client target bitrate
|
|
|
|
ticker := time.NewTicker(bitrateCheckInterval)
|
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
|
|
for range ticker.C {
|
|
|
|
targetBitrate := estimator.GetTargetBitrate()
|
2023-03-14 05:55:52 +13:00
|
|
|
manager.metrics.SetReceiverEstimatedTargetBitrate(session, float64(targetBitrate))
|
2023-02-27 09:54:10 +13:00
|
|
|
|
|
|
|
if connection.ConnectionState() == webrtc.PeerConnectionStateClosed {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if !videoTrack.VideoAuto() {
|
|
|
|
continue
|
|
|
|
}
|
2023-03-14 05:55:52 +13:00
|
|
|
if !manager.config.EstimatorPassive {
|
|
|
|
changeVideoFromBitrate(targetBitrate)
|
|
|
|
}
|
2023-02-07 07:45:51 +13:00
|
|
|
}
|
2023-02-27 09:54:10 +13:00
|
|
|
}()
|
|
|
|
}
|
2022-10-18 00:39:31 +13:00
|
|
|
|
2021-09-27 11:50:49 +13:00
|
|
|
// data channel
|
|
|
|
|
2021-02-13 11:45:16 +13:00
|
|
|
dataChannel, err := connection.CreateDataChannel("data", nil)
|
2021-02-06 05:57:33 +13:00
|
|
|
if err != nil {
|
2021-02-03 07:36:11 +13:00
|
|
|
return nil, err
|
|
|
|
}
|
2020-10-23 03:54:50 +13:00
|
|
|
|
2021-02-14 06:25:40 +13:00
|
|
|
peer := &WebRTCPeerCtx{
|
2023-02-07 07:45:51 +13:00
|
|
|
logger: logger,
|
|
|
|
connection: connection,
|
|
|
|
dataChannel: dataChannel,
|
|
|
|
changeVideoFromBitrate: changeVideoFromBitrate,
|
|
|
|
changeVideoFromID: changeVideoFromID,
|
2022-10-26 07:25:00 +13:00
|
|
|
// TODO: Refactor.
|
2023-02-07 07:45:51 +13:00
|
|
|
videoId: videoTrack.stream.ID,
|
2022-03-27 11:20:38 +13:00
|
|
|
setPaused: func(isPaused bool) {
|
|
|
|
videoTrack.SetPaused(isPaused)
|
|
|
|
audioTrack.SetPaused(isPaused)
|
|
|
|
},
|
2023-02-27 09:54:10 +13:00
|
|
|
iceTrickle: manager.config.ICETrickle,
|
|
|
|
setVideoAuto: func(videoAuto bool) {
|
2023-03-14 05:55:52 +13:00
|
|
|
// if estimator is enabled and not in passive mode, enable video auto bitrate
|
|
|
|
if manager.config.EstimatorEnabled && !manager.config.EstimatorPassive {
|
2023-02-27 09:54:10 +13:00
|
|
|
videoTrack.SetVideoAuto(videoAuto)
|
|
|
|
} else {
|
2023-03-14 05:55:52 +13:00
|
|
|
logger.Warn().Msg("estimator is disabled or in passive mode, cannot change video auto")
|
2023-02-27 09:54:10 +13:00
|
|
|
videoTrack.SetVideoAuto(false) // ensure video auto is disabled
|
|
|
|
}
|
|
|
|
},
|
2023-02-07 07:45:51 +13:00
|
|
|
getVideoAuto: videoTrack.VideoAuto,
|
2021-02-14 06:25:40 +13:00
|
|
|
}
|
|
|
|
|
2021-11-29 11:16:26 +13:00
|
|
|
connection.OnTrack(func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
|
2021-12-10 11:22:24 +13:00
|
|
|
logger := logger.With().
|
2021-12-10 09:48:02 +13:00
|
|
|
Str("kind", track.Kind().String()).
|
2021-12-03 11:06:21 +13:00
|
|
|
Str("mime", track.Codec().RTPCodecCapability.MimeType).
|
2021-12-10 11:22:24 +13:00
|
|
|
Logger()
|
|
|
|
|
2022-01-07 08:41:44 +13:00
|
|
|
logger.Info().Msgf("received new remote track")
|
2021-12-10 11:22:24 +13:00
|
|
|
|
|
|
|
if !session.Profile().CanShareMedia {
|
2022-01-07 08:41:44 +13:00
|
|
|
logger.Warn().Msg("media sharing is disabled for this session")
|
2022-01-07 10:28:34 +13:00
|
|
|
receiver.Stop()
|
2021-12-10 11:22:24 +13:00
|
|
|
return
|
|
|
|
}
|
2021-11-29 11:16:26 +13:00
|
|
|
|
2022-01-07 08:41:44 +13:00
|
|
|
// parse codec from remote track
|
2021-12-02 10:36:45 +13:00
|
|
|
codec, ok := codec.ParseRTC(track.Codec())
|
|
|
|
if !ok {
|
2022-01-07 08:41:44 +13:00
|
|
|
logger.Warn().Msg("remote track with unknown codec")
|
2022-01-07 10:28:34 +13:00
|
|
|
receiver.Stop()
|
2021-11-29 11:16:26 +13:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-12-03 11:06:21 +13:00
|
|
|
var srcManager types.StreamSrcManager
|
2022-01-07 10:28:34 +13:00
|
|
|
|
|
|
|
stopped := false
|
|
|
|
stopFn := func() {
|
|
|
|
if stopped {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
stopped = true
|
|
|
|
receiver.Stop()
|
|
|
|
srcManager.Stop()
|
|
|
|
logger.Info().Msg("remote track stopped")
|
|
|
|
}
|
|
|
|
|
2021-12-03 11:06:21 +13:00
|
|
|
if track.Kind() == webrtc.RTPCodecTypeAudio {
|
|
|
|
// audio -> microphone
|
|
|
|
srcManager = manager.capture.Microphone()
|
2022-01-07 10:28:34 +13:00
|
|
|
defer stopFn()
|
|
|
|
|
|
|
|
if manager.micStop != nil {
|
|
|
|
(*manager.micStop)()
|
|
|
|
}
|
|
|
|
manager.micStop = &stopFn
|
2021-12-03 11:06:21 +13:00
|
|
|
} else if track.Kind() == webrtc.RTPCodecTypeVideo {
|
|
|
|
// video -> webcam
|
|
|
|
srcManager = manager.capture.Webcam()
|
2022-01-07 10:28:34 +13:00
|
|
|
defer stopFn()
|
|
|
|
|
|
|
|
if manager.camStop != nil {
|
|
|
|
(*manager.camStop)()
|
|
|
|
}
|
|
|
|
manager.camStop = &stopFn
|
|
|
|
} else {
|
|
|
|
logger.Warn().Msg("remote track with unsupported codec type")
|
|
|
|
receiver.Stop()
|
|
|
|
return
|
2021-12-03 11:06:21 +13:00
|
|
|
}
|
|
|
|
|
2021-12-03 11:35:38 +13:00
|
|
|
err := srcManager.Start(codec)
|
|
|
|
if err != nil {
|
|
|
|
logger.Err(err).Msg("failed to start pipeline")
|
|
|
|
return
|
|
|
|
}
|
2021-11-29 11:16:26 +13:00
|
|
|
|
2022-01-07 08:41:44 +13:00
|
|
|
ticker := time.NewTicker(rtcpPLIInterval)
|
2021-11-29 11:16:26 +13:00
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
for range ticker.C {
|
2021-12-10 11:22:24 +13:00
|
|
|
err := connection.WriteRTCP([]rtcp.Packet{&rtcp.PictureLossIndication{MediaSSRC: uint32(track.SSRC())}})
|
|
|
|
if err != nil {
|
2022-01-07 08:41:44 +13:00
|
|
|
logger.Err(err).Msg("remote track rtcp send err")
|
2021-11-29 11:16:26 +13:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
buf := make([]byte, 1400)
|
|
|
|
for {
|
|
|
|
i, _, err := track.Read(buf)
|
|
|
|
if err != nil {
|
2022-01-07 08:41:44 +13:00
|
|
|
logger.Warn().Err(err).Msg("failed read from remote track")
|
2021-11-29 11:16:26 +13:00
|
|
|
break
|
|
|
|
}
|
|
|
|
|
2021-12-03 11:06:21 +13:00
|
|
|
srcManager.Push(buf[:i])
|
2021-11-29 11:16:26 +13:00
|
|
|
}
|
2021-12-02 10:36:45 +13:00
|
|
|
|
2022-01-07 08:41:44 +13:00
|
|
|
logger.Info().Msg("remote track data finished")
|
2021-11-26 11:46:06 +13:00
|
|
|
})
|
|
|
|
|
|
|
|
connection.OnDataChannel(func(dc *webrtc.DataChannel) {
|
2022-02-13 06:55:56 +13:00
|
|
|
logger.Info().Interface("data_channel", dc).Msg("got remote data channel")
|
2021-11-26 11:46:06 +13:00
|
|
|
})
|
|
|
|
|
2023-03-28 06:28:28 +13:00
|
|
|
var once sync.Once
|
2021-10-08 08:41:19 +13:00
|
|
|
connection.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
|
|
|
|
switch state {
|
|
|
|
case webrtc.PeerConnectionStateConnected:
|
|
|
|
session.SetWebRTCConnected(peer, true)
|
|
|
|
case webrtc.PeerConnectionStateDisconnected,
|
|
|
|
webrtc.PeerConnectionStateFailed:
|
|
|
|
connection.Close()
|
|
|
|
case webrtc.PeerConnectionStateClosed:
|
2023-03-28 06:28:28 +13:00
|
|
|
// ensure we only run this once
|
|
|
|
once.Do(func() {
|
|
|
|
session.SetWebRTCConnected(peer, false)
|
|
|
|
if err = video.RemoveReceiver(videoTrack); err != nil {
|
|
|
|
logger.Err(err).Msg("failed to remove video receiver")
|
|
|
|
}
|
|
|
|
audioTrack.Shutdown()
|
|
|
|
videoTrack.Shutdown()
|
|
|
|
close(videoRtcp)
|
|
|
|
})
|
2021-10-08 08:41:19 +13:00
|
|
|
}
|
2022-06-26 06:12:42 +12:00
|
|
|
|
|
|
|
manager.metrics.SetState(session, state)
|
2021-10-08 08:41:19 +13:00
|
|
|
})
|
|
|
|
|
2021-03-01 06:37:35 +13:00
|
|
|
cursorImage := func(entry *cursor.ImageEntry) {
|
|
|
|
if err := peer.SendCursorImage(entry.Cursor, entry.Image); err != nil {
|
2021-09-02 09:10:06 +12:00
|
|
|
logger.Err(err).Msg("could not send cursor image")
|
2021-02-14 06:25:40 +13:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
cursorPosition := func(x, y int) {
|
|
|
|
if session.IsHost() {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := peer.SendCursorPosition(x, y); err != nil {
|
2021-09-02 09:10:06 +12:00
|
|
|
logger.Err(err).Msg("could not send cursor position")
|
2021-02-14 06:25:40 +13:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
dataChannel.OnOpen(func() {
|
2021-03-01 06:37:35 +13:00
|
|
|
manager.curImage.AddListener(&cursorImage)
|
|
|
|
manager.curPosition.AddListener(&cursorPosition)
|
2021-02-18 09:55:21 +13:00
|
|
|
|
|
|
|
// send initial cursor image
|
2021-03-01 06:50:32 +13:00
|
|
|
entry, err := manager.curImage.Get()
|
2021-02-26 02:24:17 +13:00
|
|
|
if err == nil {
|
2021-03-01 06:37:35 +13:00
|
|
|
cursorImage(entry)
|
2021-02-26 02:24:17 +13:00
|
|
|
} else {
|
2021-09-02 09:10:06 +12:00
|
|
|
logger.Err(err).Msg("failed to get cursor image")
|
2021-02-26 02:24:17 +13:00
|
|
|
}
|
2021-02-21 12:41:04 +13:00
|
|
|
|
2021-02-18 09:55:21 +13:00
|
|
|
// send initial cursor position
|
2021-10-22 09:53:54 +13:00
|
|
|
x, y := manager.desktop.GetCursorPosition()
|
2021-02-18 09:55:21 +13:00
|
|
|
cursorPosition(x, y)
|
2021-02-14 06:25:40 +13:00
|
|
|
})
|
|
|
|
|
2021-03-01 06:37:35 +13:00
|
|
|
dataChannel.OnClose(func() {
|
|
|
|
manager.curImage.RemoveListener(&cursorImage)
|
|
|
|
manager.curPosition.RemoveListener(&cursorPosition)
|
|
|
|
})
|
|
|
|
|
2021-02-13 11:45:16 +13:00
|
|
|
dataChannel.OnMessage(func(message webrtc.DataChannelMessage) {
|
2023-01-21 11:08:27 +13:00
|
|
|
if err := manager.handle(message.Data, dataChannel, session); err != nil {
|
2021-09-02 09:10:06 +12:00
|
|
|
logger.Err(err).Msg("data handle failed")
|
2021-02-13 11:45:16 +13:00
|
|
|
}
|
|
|
|
})
|
2021-02-03 04:21:20 +13:00
|
|
|
|
2021-02-14 06:25:40 +13:00
|
|
|
session.SetWebRTCPeer(peer)
|
2022-02-11 11:39:52 +13:00
|
|
|
|
|
|
|
offer, err := peer.CreateOffer(false)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// on negotiation needed handler must be registered after creating initial
|
|
|
|
// offer, otherwise it can fire and intercept sucessful negotiation
|
|
|
|
|
|
|
|
connection.OnNegotiationNeeded(func() {
|
|
|
|
logger.Warn().Msg("negotiation is needed")
|
|
|
|
|
|
|
|
if connection.SignalingState() != webrtc.SignalingStateStable {
|
|
|
|
logger.Warn().Msg("connection isn't stable yet; postponing...")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
offer, err := peer.CreateOffer(false)
|
|
|
|
if err != nil {
|
|
|
|
logger.Err(err).Msg("sdp offer failed")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
session.Send(
|
|
|
|
event.SIGNAL_OFFER,
|
|
|
|
message.SignalDescription{
|
|
|
|
SDP: offer.SDP,
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
2023-03-07 12:08:53 +13:00
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
packets, ok := <-videoRtcp
|
|
|
|
if !ok {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, p := range packets {
|
2023-03-14 05:55:52 +13:00
|
|
|
switch rtcpPacket := p.(type) {
|
|
|
|
case *rtcp.ReceiverEstimatedMaximumBitrate: // TODO: Deprecated.
|
|
|
|
manager.metrics.SetReceiverEstimatedMaximumBitrate(session, rtcpPacket.Bitrate)
|
|
|
|
|
|
|
|
case *rtcp.ReceiverReport:
|
2023-03-07 12:08:53 +13:00
|
|
|
l := len(rtcpPacket.Reports)
|
|
|
|
if l > 0 {
|
|
|
|
// use only last report
|
|
|
|
manager.metrics.SetReceiverReport(session, rtcpPacket.Reports[l-1])
|
|
|
|
}
|
2023-02-15 09:19:14 +13:00
|
|
|
}
|
2022-07-04 11:01:03 +12:00
|
|
|
}
|
2022-07-04 10:38:46 +12:00
|
|
|
}
|
2023-03-07 12:08:53 +13:00
|
|
|
}()
|
2022-07-04 10:38:46 +12:00
|
|
|
|
2022-06-26 06:12:42 +12:00
|
|
|
go func() {
|
|
|
|
ticker := time.NewTicker(5 * time.Second)
|
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
|
|
for range ticker.C {
|
|
|
|
if connection.ConnectionState() == webrtc.PeerConnectionStateClosed {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
stats := connection.GetStats()
|
|
|
|
data, ok := stats["iceTransport"].(webrtc.TransportStats)
|
|
|
|
if ok {
|
2022-07-01 10:16:39 +12:00
|
|
|
manager.metrics.SetIceTransportStats(session, data)
|
|
|
|
}
|
|
|
|
|
|
|
|
data, ok = stats["sctpTransport"].(webrtc.TransportStats)
|
|
|
|
if ok {
|
|
|
|
manager.metrics.SetSctpTransportStats(session, data)
|
2022-06-26 06:12:42 +12:00
|
|
|
}
|
2022-07-01 09:50:47 +12:00
|
|
|
|
2022-12-17 01:49:51 +13:00
|
|
|
remoteCandidates := map[string]webrtc.ICECandidateStats{}
|
|
|
|
nominatedRemoteCandidates := map[string]struct{}{}
|
2022-07-01 09:50:47 +12:00
|
|
|
for _, entry := range stats {
|
|
|
|
// only remote ice candidate stats
|
|
|
|
candidate, ok := entry.(webrtc.ICECandidateStats)
|
|
|
|
if ok && candidate.Type == webrtc.StatsTypeRemoteCandidate {
|
2022-12-17 01:49:51 +13:00
|
|
|
manager.metrics.NewICECandidate(session, candidate)
|
|
|
|
remoteCandidates[candidate.ID] = candidate
|
|
|
|
}
|
|
|
|
|
|
|
|
// only nominated ice candidate pair stats
|
|
|
|
pair, ok := entry.(webrtc.ICECandidatePairStats)
|
|
|
|
if ok && pair.Nominated {
|
|
|
|
nominatedRemoteCandidates[pair.RemoteCandidateID] = struct{}{}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
iceCandidatesUsed := []webrtc.ICECandidateStats{}
|
|
|
|
for id := range nominatedRemoteCandidates {
|
|
|
|
if candidate, ok := remoteCandidates[id]; ok {
|
|
|
|
iceCandidatesUsed = append(iceCandidatesUsed, candidate)
|
2022-07-01 09:50:47 +12:00
|
|
|
}
|
|
|
|
}
|
2022-12-17 01:49:51 +13:00
|
|
|
|
|
|
|
manager.metrics.SetICECandidatesUsed(session, iceCandidatesUsed)
|
2022-06-26 06:12:42 +12:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2022-02-11 11:39:52 +13:00
|
|
|
return offer, nil
|
2021-02-03 07:21:48 +13:00
|
|
|
}
|
2022-07-22 04:28:51 +12:00
|
|
|
|
|
|
|
func (manager *WebRTCManagerCtx) SetCursorPosition(x, y int) {
|
|
|
|
manager.curPosition.Set(x, y)
|
|
|
|
}
|