neko/internal/webrtc/manager.go

337 lines
8.1 KiB
Go
Raw Normal View History

package webrtc
import (
"fmt"
2021-02-14 14:40:17 +01:00
"strings"
2021-02-25 17:16:37 +01:00
"time"
2021-11-28 23:16:26 +01:00
"github.com/pion/rtcp"
2021-02-01 23:50:18 +01:00
"github.com/pion/webrtc/v3"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
2021-02-14 14:40:17 +01:00
"demodesk/neko/internal/config"
2020-10-28 19:15:48 +01:00
"demodesk/neko/internal/types"
2021-09-26 22:59:45 +02:00
"demodesk/neko/internal/types/codec"
2021-02-02 20:43:33 +01:00
"demodesk/neko/internal/types/event"
"demodesk/neko/internal/types/message"
"demodesk/neko/internal/webrtc/cursor"
)
2021-02-25 17:16:37 +01: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-06 20:41:44 +01:00
// send a PLI on an interval so that the publisher is pushing a keyframe every rtcpPLIInterval
const rtcpPLIInterval = 3 * time.Second
2020-11-01 16:09:48 +01:00
func New(desktop types.DesktopManager, capture types.CaptureManager, config *config.WebRTC) *WebRTCManagerCtx {
return &WebRTCManagerCtx{
2021-09-26 22:26:22 +02:00
logger: log.With().Str("module", "webrtc").Logger(),
config: config,
desktop: desktop,
capture: capture,
curImage: cursor.NewImage(desktop),
2021-10-21 22:53:54 +02:00
curPosition: cursor.NewPosition(),
}
}
2020-11-01 16:09:48 +01:00
type WebRTCManagerCtx struct {
2021-09-26 22:26:22 +02:00
logger zerolog.Logger
config *config.WebRTC
desktop types.DesktopManager
capture types.CaptureManager
curImage *cursor.ImageCtx
curPosition *cursor.PositionCtx
2022-01-06 22:28:34 +01:00
camStop, micStop *func()
}
2020-11-01 16:09:48 +01:00
func (manager *WebRTCManagerCtx) Start() {
2021-08-29 18:59:46 +02:00
manager.curImage.Start()
manager.logger.Info().
2021-08-03 11:06:34 +02:00
Bool("icelite", manager.config.ICELite).
Bool("icetrickle", manager.config.ICETrickle).
Interface("iceservers", manager.config.ICEServers).
2021-03-17 15:47:49 +01:00
Str("nat1to1", strings.Join(manager.config.NAT1To1IPs, ",")).
Str("epr", fmt.Sprintf("%d-%d", manager.config.EphemeralMin, manager.config.EphemeralMax)).
2021-08-03 11:06:34 +02:00
Msg("webrtc starting")
}
2020-11-01 16:09:48 +01:00
func (manager *WebRTCManagerCtx) Shutdown() error {
2021-09-02 00:00:29 +02:00
manager.logger.Info().Msg("shutdown")
2021-02-06 12:59:57 +01:00
manager.curImage.Shutdown()
manager.curPosition.Shutdown()
return nil
}
2021-03-17 15:47:49 +01:00
func (manager *WebRTCManagerCtx) ICEServers() []types.ICEServer {
2021-02-02 19:21:48 +01:00
return manager.config.ICEServers
}
2021-11-28 18:36:47 +01:00
func (manager *WebRTCManagerCtx) CreatePeer(session types.Session, videoID string) (types.WebRTCPeer, error) {
2021-08-29 18:59:46 +02:00
// add session id to logger context
2021-03-13 23:27:28 +01:00
logger := manager.logger.With().Str("session_id", session.ID()).Logger()
2021-08-29 18:59:46 +02:00
logger.Info().Msg("creating webrtc peer")
2021-02-02 20:43:33 +01:00
2021-09-27 00:50:49 +02:00
// all audios must have the same codec
audioStream := manager.capture.Audio()
2021-09-26 22:26:22 +02:00
// all videos must have the same codec
videoStream, ok := manager.capture.Video(videoID)
if !ok {
return nil, types.ErrWebRTCVideoNotFound
2021-03-23 13:46:54 +01:00
}
2021-09-26 22:59:45 +02:00
connection, err := manager.newPeerConnection([]codec.RTPCodec{
2021-09-27 00:50:49 +02:00
audioStream.Codec(),
2021-09-26 22:59:45 +02:00
videoStream.Codec(),
}, logger)
if err != nil {
2021-02-02 19:21:48 +01:00
return nil, err
}
2021-09-26 22:26:22 +02:00
// asynchronously send local ICE Candidates
2021-02-02 21:12:11 +01: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-02 20:43:33 +01:00
2021-09-01 21:58:39 +02:00
session.Send(
event.SIGNAL_CANDIDATE,
2021-02-02 21:12:11 +01:00
message.SignalCandidate{
2021-09-01 21:58:39 +02:00
ICECandidateInit: candidate.ToJSON(),
2021-02-02 21:12:11 +01:00
})
})
}
2021-02-02 20:43:33 +01:00
2021-09-27 00:50:49 +02:00
// audio track
2021-10-01 00:02:54 +02:00
audioTrack, err := manager.newPeerStreamTrack(audioStream, logger)
if err != nil {
return nil, err
}
2021-10-07 21:41:19 +02:00
if err := audioTrack.AddToConnection(connection); err != nil {
2021-09-27 00:50:49 +02:00
return nil, err
2021-02-14 18:16:24 +01:00
}
2021-09-27 00:50:49 +02:00
// video track
2021-02-14 14:40:17 +01:00
2021-10-01 00:02:54 +02:00
videoTrack, err := manager.newPeerStreamTrack(videoStream, logger)
if err != nil {
return nil, err
}
2021-10-07 21:41:19 +02:00
if err := videoTrack.AddToConnection(connection); err != nil {
return nil, err
}
2021-09-27 00:50:49 +02:00
// data channel
2021-02-12 23:45:16 +01:00
dataChannel, err := connection.CreateDataChannel("data", nil)
2021-02-05 17:57:33 +01:00
if err != nil {
2021-02-02 19:36:11 +01:00
return nil, err
}
2021-02-13 18:25:40 +01:00
peer := &WebRTCPeerCtx{
2021-08-29 18:59:46 +02:00
logger: logger,
2021-02-14 14:40:17 +01:00
connection: connection,
dataChannel: dataChannel,
2021-09-27 00:50:49 +02:00
changeVideo: func(videoID string) error {
videoStream, ok := manager.capture.Video(videoID)
if !ok {
return types.ErrWebRTCVideoNotFound
}
return videoTrack.SetStream(videoStream)
},
iceTrickle: manager.config.ICETrickle,
2021-02-13 18:25:40 +01:00
}
2021-11-28 23:16:26 +01:00
connection.OnTrack(func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
2021-12-09 23:22:24 +01:00
logger := logger.With().
2021-12-09 21:48:02 +01:00
Str("kind", track.Kind().String()).
2021-12-02 23:06:21 +01:00
Str("mime", track.Codec().RTPCodecCapability.MimeType).
2021-12-09 23:22:24 +01:00
Logger()
2022-01-06 20:41:44 +01:00
logger.Info().Msgf("received new remote track")
2021-12-09 23:22:24 +01:00
if !session.Profile().CanShareMedia {
2022-01-06 20:41:44 +01:00
logger.Warn().Msg("media sharing is disabled for this session")
2022-01-06 22:28:34 +01:00
receiver.Stop()
2021-12-09 23:22:24 +01:00
return
}
2021-11-28 23:16:26 +01:00
2022-01-06 20:41:44 +01:00
// parse codec from remote track
2021-12-01 22:36:45 +01:00
codec, ok := codec.ParseRTC(track.Codec())
if !ok {
2022-01-06 20:41:44 +01:00
logger.Warn().Msg("remote track with unknown codec")
2022-01-06 22:28:34 +01:00
receiver.Stop()
2021-11-28 23:16:26 +01:00
return
}
2021-12-02 23:06:21 +01:00
var srcManager types.StreamSrcManager
2022-01-06 22:28:34 +01:00
stopped := false
stopFn := func() {
if stopped {
return
}
stopped = true
receiver.Stop()
srcManager.Stop()
logger.Info().Msg("remote track stopped")
}
2021-12-02 23:06:21 +01:00
if track.Kind() == webrtc.RTPCodecTypeAudio {
// audio -> microphone
srcManager = manager.capture.Microphone()
2022-01-06 22:28:34 +01:00
defer stopFn()
if manager.micStop != nil {
(*manager.micStop)()
}
manager.micStop = &stopFn
2021-12-02 23:06:21 +01:00
} else if track.Kind() == webrtc.RTPCodecTypeVideo {
// video -> webcam
srcManager = manager.capture.Webcam()
2022-01-06 22:28:34 +01: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-02 23:06:21 +01:00
}
2021-12-02 23:35:38 +01:00
err := srcManager.Start(codec)
if err != nil {
logger.Err(err).Msg("failed to start pipeline")
return
}
2021-11-28 23:16:26 +01:00
2022-01-06 20:41:44 +01:00
ticker := time.NewTicker(rtcpPLIInterval)
2021-11-28 23:16:26 +01:00
defer ticker.Stop()
go func() {
for range ticker.C {
2021-12-09 23:22:24 +01:00
err := connection.WriteRTCP([]rtcp.Packet{&rtcp.PictureLossIndication{MediaSSRC: uint32(track.SSRC())}})
if err != nil {
2022-01-06 20:41:44 +01:00
logger.Err(err).Msg("remote track rtcp send err")
2021-11-28 23:16:26 +01:00
}
}
}()
buf := make([]byte, 1400)
for {
i, _, err := track.Read(buf)
if err != nil {
2022-01-06 20:41:44 +01:00
logger.Warn().Err(err).Msg("failed read from remote track")
2021-11-28 23:16:26 +01:00
break
}
2021-12-02 23:06:21 +01:00
srcManager.Push(buf[:i])
2021-11-28 23:16:26 +01:00
}
2021-12-01 22:36:45 +01:00
2022-01-06 20:41:44 +01:00
logger.Info().Msg("remote track data finished")
2021-11-25 23:46:06 +01:00
})
connection.OnDataChannel(func(dc *webrtc.DataChannel) {
logger.Info().Interface("data-channel", dc).Msg("got remote data channel")
})
2021-11-25 21:43:39 +01:00
connection.OnNegotiationNeeded(func() {
logger.Warn().Msg("negotiation is needed")
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,
})
})
2021-10-07 21:41:19 +02: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:
session.SetWebRTCConnected(peer, false)
videoTrack.RemoveStream()
audioTrack.RemoveStream()
}
})
cursorImage := func(entry *cursor.ImageEntry) {
if err := peer.SendCursorImage(entry.Cursor, entry.Image); err != nil {
2021-09-01 23:10:06 +02:00
logger.Err(err).Msg("could not send cursor image")
2021-02-13 18:25:40 +01:00
}
}
cursorPosition := func(x, y int) {
if session.IsHost() {
return
}
if err := peer.SendCursorPosition(x, y); err != nil {
2021-09-01 23:10:06 +02:00
logger.Err(err).Msg("could not send cursor position")
2021-02-13 18:25:40 +01:00
}
}
dataChannel.OnOpen(func() {
manager.curImage.AddListener(&cursorImage)
manager.curPosition.AddListener(&cursorPosition)
2021-02-17 21:55:21 +01:00
// send initial cursor image
2021-02-28 18:50:32 +01:00
entry, err := manager.curImage.Get()
if err == nil {
cursorImage(entry)
} else {
2021-09-01 23:10:06 +02:00
logger.Err(err).Msg("failed to get cursor image")
}
2021-02-21 00:41:04 +01:00
2021-02-17 21:55:21 +01:00
// send initial cursor position
2021-10-21 22:53:54 +02:00
x, y := manager.desktop.GetCursorPosition()
2021-02-17 21:55:21 +01:00
cursorPosition(x, y)
2021-02-13 18:25:40 +01:00
})
dataChannel.OnClose(func() {
manager.curImage.RemoveListener(&cursorImage)
manager.curPosition.RemoveListener(&cursorPosition)
})
2021-02-12 23:45:16 +01:00
dataChannel.OnMessage(func(message webrtc.DataChannelMessage) {
2021-10-07 21:41:19 +02:00
if err := manager.handle(message.Data, session); err != nil {
2021-09-01 23:10:06 +02:00
logger.Err(err).Msg("data handle failed")
2021-02-12 23:45:16 +01:00
}
})
2021-02-13 18:25:40 +01:00
session.SetWebRTCPeer(peer)
2021-11-28 18:36:47 +01:00
return peer, nil
2021-02-02 19:21:48 +01:00
}