1
0
mirror of https://gitlab.crans.org/nounous/ghostream.git synced 2024-12-23 07:22:20 +00:00
ghostream/stream/webrtc/webrtc.go

229 lines
7.1 KiB
Go
Raw Normal View History

2020-10-09 20:36:02 +00:00
// Package webrtc provides the backend to simulate a WebRTC client to send stream
package webrtc
2020-09-24 09:24:13 +00:00
import (
2020-09-24 17:01:26 +00:00
"log"
2020-09-24 09:24:13 +00:00
"math/rand"
"strings"
2020-09-24 09:24:13 +00:00
"github.com/pion/webrtc/v3"
2020-09-29 16:17:55 +00:00
"gitlab.crans.org/nounous/ghostream/internal/monitoring"
"gitlab.crans.org/nounous/ghostream/messaging"
2020-09-24 09:24:13 +00:00
)
// Options holds web package configuration
type Options struct {
2020-10-09 20:06:30 +00:00
Enabled bool
MinPortUDP uint16
MaxPortUDP uint16
2020-09-29 15:27:19 +00:00
STUNServers []string
}
// SessionDescription contains SDP data
// to initiate a WebRTC connection between one client and this app
type SessionDescription = webrtc.SessionDescription
2020-09-24 17:01:26 +00:00
var (
videoTracks map[string][]*webrtc.Track
audioTracks map[string][]*webrtc.Track
2020-09-24 17:01:26 +00:00
)
2020-09-25 13:12:28 +00:00
// Helper to reslice tracks
func removeTrack(tracks []*webrtc.Track, track *webrtc.Track) []*webrtc.Track {
for i, t := range tracks {
if t == track {
return append(tracks[:i], tracks[i+1:]...)
}
}
return nil
}
2020-09-29 16:17:55 +00:00
// GetNumberConnectedSessions get the number of currently connected clients
2020-10-05 20:08:39 +00:00
func GetNumberConnectedSessions(streamID string) int {
return len(videoTracks[streamID])
2020-09-29 16:17:55 +00:00
}
2020-09-24 17:01:26 +00:00
// newPeerHandler is called when server receive a new session description
// this initiates a WebRTC connection and return server description
2020-10-19 19:45:23 +00:00
func newPeerHandler(name string, localSdpChan chan webrtc.SessionDescription, remoteSdp webrtc.SessionDescription, cfg *Options) {
2020-09-25 13:12:28 +00:00
// Create media engine using client SDP
mediaEngine := webrtc.MediaEngine{}
2020-10-19 19:45:23 +00:00
if err := mediaEngine.PopulateFromSDP(remoteSdp); err != nil {
2020-09-25 13:12:28 +00:00
log.Println("Failed to create new media engine", err)
2020-10-14 16:34:14 +00:00
localSdpChan <- webrtc.SessionDescription{}
return
2020-09-25 13:12:28 +00:00
}
2020-09-24 17:01:26 +00:00
// Create a new PeerConnection
2020-09-29 12:11:56 +00:00
settingsEngine := webrtc.SettingEngine{}
if err := settingsEngine.SetEphemeralUDPPortRange(cfg.MinPortUDP, cfg.MaxPortUDP); err != nil {
2020-09-29 12:11:56 +00:00
log.Println("Failed to set min/max UDP ports", err)
2020-10-14 16:34:14 +00:00
localSdpChan <- webrtc.SessionDescription{}
return
2020-09-29 12:11:56 +00:00
}
api := webrtc.NewAPI(
webrtc.WithMediaEngine(mediaEngine),
webrtc.WithSettingEngine(settingsEngine),
)
peerConnection, err := api.NewPeerConnection(webrtc.Configuration{
2020-09-29 15:27:19 +00:00
ICEServers: []webrtc.ICEServer{{URLs: cfg.STUNServers}},
})
2020-09-24 17:01:26 +00:00
if err != nil {
log.Println("Failed to initiate peer connection", err)
2020-10-14 16:34:14 +00:00
localSdpChan <- webrtc.SessionDescription{}
return
2020-09-24 17:01:26 +00:00
}
2020-09-25 13:12:28 +00:00
// Create video track
codec, payloadType := getPayloadType(mediaEngine, webrtc.RTPCodecTypeVideo, "VP8")
videoTrack, err := webrtc.NewTrack(payloadType, rand.Uint32(), "video", "pion", codec)
if err != nil {
log.Println("Failed to create new video track", err)
2020-10-14 16:34:14 +00:00
localSdpChan <- webrtc.SessionDescription{}
return
2020-09-24 17:01:26 +00:00
}
if _, err = peerConnection.AddTrack(videoTrack); err != nil {
log.Println("Failed to add video track", err)
2020-10-14 16:34:14 +00:00
localSdpChan <- webrtc.SessionDescription{}
return
2020-09-24 17:01:26 +00:00
}
2020-09-25 13:12:28 +00:00
// Create audio track
codec, payloadType = getPayloadType(mediaEngine, webrtc.RTPCodecTypeAudio, "opus")
audioTrack, err := webrtc.NewTrack(payloadType, rand.Uint32(), "audio", "pion", codec)
if err != nil {
log.Println("Failed to create new audio track", err)
2020-10-14 16:34:14 +00:00
localSdpChan <- webrtc.SessionDescription{}
return
2020-09-25 13:12:28 +00:00
}
if _, err = peerConnection.AddTrack(audioTrack); err != nil {
log.Println("Failed to add audio track", err)
2020-10-14 16:34:14 +00:00
localSdpChan <- webrtc.SessionDescription{}
return
2020-09-25 13:12:28 +00:00
}
2020-09-24 17:01:26 +00:00
// Set the remote SessionDescription
2020-10-19 19:45:23 +00:00
if err = peerConnection.SetRemoteDescription(remoteSdp); err != nil {
2020-09-24 17:01:26 +00:00
log.Println("Failed to set remote description", err)
2020-10-14 16:34:14 +00:00
localSdpChan <- webrtc.SessionDescription{}
return
2020-09-24 17:01:26 +00:00
}
2020-10-19 19:45:23 +00:00
streamID := name
split := strings.SplitN(streamID, "@", 2)
streamID = split[0]
quality := "source"
if len(split) == 2 {
quality = split[1]
}
log.Printf("New WebRTC session for stream %s, quality %s", streamID, quality)
// TODO Consider the quality
2020-09-25 13:12:28 +00:00
// Set the handler for ICE connection state
// This will notify you when the peer has connected/disconnected
peerConnection.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {
log.Printf("Connection State has changed %s \n", connectionState.String())
if videoTracks[streamID] == nil {
videoTracks[streamID] = make([]*webrtc.Track, 0, 1)
}
if audioTracks[streamID] == nil {
audioTracks[streamID] = make([]*webrtc.Track, 0, 1)
}
2020-09-25 13:12:28 +00:00
if connectionState == webrtc.ICEConnectionStateConnected {
// Register tracks
videoTracks[streamID] = append(videoTracks[streamID], videoTrack)
audioTracks[streamID] = append(audioTracks[streamID], audioTrack)
monitoring.WebRTCConnectedSessions.Inc()
2020-09-25 13:12:28 +00:00
} else if connectionState == webrtc.ICEConnectionStateDisconnected {
// Unregister tracks
videoTracks[streamID] = removeTrack(videoTracks[streamID], videoTrack)
audioTracks[streamID] = removeTrack(audioTracks[streamID], audioTrack)
monitoring.WebRTCConnectedSessions.Dec()
2020-09-25 13:12:28 +00:00
}
})
2020-10-14 16:34:14 +00:00
// Create answer
answer, err := peerConnection.CreateAnswer(nil)
if err != nil {
log.Println("Failed to create answer", err)
localSdpChan <- webrtc.SessionDescription{}
return
}
2020-10-14 16:37:51 +00:00
// Sets the LocalDescription
// Using GatheringCompletePromise disable trickle ICE
// FIXME: https://github.com/pion/webrtc/wiki/Release-WebRTC@v3.0.0
gatherComplete := webrtc.GatheringCompletePromise(peerConnection)
2020-10-14 16:34:14 +00:00
if err = peerConnection.SetLocalDescription(answer); err != nil {
log.Println("Failed to set local description", err)
localSdpChan <- webrtc.SessionDescription{}
return
}
2020-10-14 16:37:51 +00:00
<-gatherComplete
2020-09-24 17:01:26 +00:00
2020-10-14 16:34:14 +00:00
// Send answer to client
2020-10-14 16:57:37 +00:00
localSdpChan <- *peerConnection.LocalDescription()
2020-09-24 17:01:26 +00:00
}
2020-09-24 09:24:13 +00:00
// Search for Codec PayloadType
//
// Since we are answering we need to match the remote PayloadType
func getPayloadType(m webrtc.MediaEngine, codecType webrtc.RTPCodecType, codecName string) (*webrtc.RTPCodec, uint8) {
2020-09-24 09:24:13 +00:00
for _, codec := range m.GetCodecsByKind(codecType) {
if codec.Name == codecName {
return codec, codec.PayloadType
2020-09-24 09:24:13 +00:00
}
}
2020-10-14 16:57:37 +00:00
log.Printf("Remote peer does not support %s", codecName)
return nil, 0
2020-09-24 09:24:13 +00:00
}
2020-09-25 13:12:28 +00:00
// Serve WebRTC media streaming server
2020-10-19 19:45:23 +00:00
func Serve(streams *messaging.Streams, cfg *Options) {
2020-10-09 20:06:30 +00:00
if !cfg.Enabled {
// WebRTC is not enabled, ignore
2020-10-09 20:06:30 +00:00
return
}
2020-10-05 08:11:30 +00:00
log.Printf("WebRTC server using UDP from port %d to %d", cfg.MinPortUDP, cfg.MaxPortUDP)
2020-10-19 19:45:23 +00:00
// WebRTC ingested tracks
videoTracks = make(map[string][]*webrtc.Track)
audioTracks = make(map[string][]*webrtc.Track)
2020-10-19 19:45:23 +00:00
// Subscribe to new stream event
event := make(chan string, 8)
streams.Subscribe(event)
2020-09-25 13:12:28 +00:00
2020-10-19 19:45:23 +00:00
// For each new stream
for name := range event {
// Get stream
stream, err := streams.Get(name)
if err != nil {
log.Printf("Failed to get stream '%s'", name)
}
// Get specific quality
// FIXME: make it possible to forward other qualities
qualityName := "source"
quality, err := stream.GetQuality(qualityName)
if err != nil {
log.Printf("Failed to get quality '%s'", qualityName)
}
// Start forwarding
log.Printf("Starting webrtc for '%s' quality '%s'", name, qualityName)
go ingest(name, quality)
go listenSdp(name, quality.WebRtcLocalSdp, quality.WebRtcRemoteSdp, cfg)
}
}
func listenSdp(name string, localSdp, remoteSdp chan webrtc.SessionDescription, cfg *Options) {
2020-09-25 13:12:28 +00:00
// Handle new connections
for {
// Wait for incoming session description
// then send the local description to browser
2020-10-19 19:45:23 +00:00
newPeerHandler(name, localSdp, <-remoteSdp, cfg)
2020-09-25 13:12:28 +00:00
}
}