mirror of
https://gitlab.crans.org/nounous/ghostream.git
synced 2025-07-06 14:53:58 +02:00
Compare commits
5 Commits
24478bdc7a
...
multi-qual
Author | SHA1 | Date | |
---|---|---|---|
86dac0f929 | |||
9e7e1ec0b8 | |||
cdb56c8bf5 | |||
ff2ebd76f1 | |||
4cbb1d8192 |
@ -10,6 +10,12 @@ import (
|
|||||||
// Quality holds a specific stream quality.
|
// Quality holds a specific stream quality.
|
||||||
// It makes packages able to subscribe to an incoming stream.
|
// It makes packages able to subscribe to an incoming stream.
|
||||||
type Quality struct {
|
type Quality struct {
|
||||||
|
// Type of the quality
|
||||||
|
Name string
|
||||||
|
|
||||||
|
// Source Stream
|
||||||
|
Stream *Stream
|
||||||
|
|
||||||
// Incoming data come from this channel
|
// Incoming data come from this channel
|
||||||
Broadcast chan<- []byte
|
Broadcast chan<- []byte
|
||||||
|
|
||||||
@ -27,8 +33,9 @@ type Quality struct {
|
|||||||
WebRtcRemoteSdp chan webrtc.SessionDescription
|
WebRtcRemoteSdp chan webrtc.SessionDescription
|
||||||
}
|
}
|
||||||
|
|
||||||
func newQuality() (q *Quality) {
|
func newQuality(name string, stream *Stream) (q *Quality) {
|
||||||
q = &Quality{}
|
q = &Quality{Name: name}
|
||||||
|
q.Stream = stream
|
||||||
broadcast := make(chan []byte, 1024)
|
broadcast := make(chan []byte, 1024)
|
||||||
q.Broadcast = broadcast
|
q.Broadcast = broadcast
|
||||||
q.outputs = make(map[chan []byte]struct{})
|
q.outputs = make(map[chan []byte]struct{})
|
||||||
|
@ -40,7 +40,7 @@ func (s *Stream) CreateQuality(name string) (quality *Quality, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
s.lockQualities.Lock()
|
s.lockQualities.Lock()
|
||||||
quality = newQuality()
|
quality = newQuality(name, s)
|
||||||
s.qualities[name] = quality
|
s.qualities[name] = quality
|
||||||
s.lockQualities.Unlock()
|
s.lockQualities.Unlock()
|
||||||
return quality, nil
|
return quality, nil
|
||||||
|
@ -24,6 +24,17 @@ func handleStreamer(socket *srtgo.SrtSocket, streams *messaging.Streams, name st
|
|||||||
socket.Close()
|
socket.Close()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Create sub-qualities
|
||||||
|
for _, qualityName := range []string{"audio", "480p", "360p", "240p"} {
|
||||||
|
_, err := stream.CreateQuality(qualityName)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error on quality creating: %s", err)
|
||||||
|
socket.Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
log.Printf("New SRT streamer for stream '%s' quality 'source'", name)
|
log.Printf("New SRT streamer for stream '%s' quality 'source'", name)
|
||||||
|
|
||||||
// Read RTP packets forever and send them to the WebRTC Client
|
// Read RTP packets forever and send them to the WebRTC Client
|
||||||
|
@ -14,33 +14,61 @@ import (
|
|||||||
|
|
||||||
func ingest(name string, q *messaging.Quality) {
|
func ingest(name string, q *messaging.Quality) {
|
||||||
// Register to get stream
|
// Register to get stream
|
||||||
videoInput := make(chan []byte, 1024)
|
input := make(chan []byte, 1024)
|
||||||
q.Register(videoInput)
|
// FIXME Stream data should already be transcoded
|
||||||
|
source, _ := q.Stream.GetQuality("source")
|
||||||
|
source.Register(input)
|
||||||
|
|
||||||
// Open a UDP Listener for RTP Packets on port 5004
|
// FIXME Bad code
|
||||||
videoListener, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 5004})
|
port := 5000
|
||||||
if err != nil {
|
var tracks map[string][]*webrtc.Track
|
||||||
log.Printf("Faited to open UDP listener %s", err)
|
qualityName := ""
|
||||||
return
|
switch q.Name {
|
||||||
|
case "audio":
|
||||||
|
port = 5004
|
||||||
|
tracks = audioTracks
|
||||||
|
break
|
||||||
|
case "source":
|
||||||
|
port = 5005
|
||||||
|
tracks = videoTracks
|
||||||
|
qualityName = "@source"
|
||||||
|
break
|
||||||
|
case "480p":
|
||||||
|
port = 5006
|
||||||
|
tracks = videoTracks
|
||||||
|
qualityName = "@480p"
|
||||||
|
break
|
||||||
|
case "360p":
|
||||||
|
port = 5007
|
||||||
|
tracks = videoTracks
|
||||||
|
qualityName = "@360p"
|
||||||
|
break
|
||||||
|
case "240p":
|
||||||
|
port = 5008
|
||||||
|
tracks = videoTracks
|
||||||
|
qualityName = "@240p"
|
||||||
|
break
|
||||||
}
|
}
|
||||||
audioListener, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 5005})
|
|
||||||
|
// Open a UDP Listener for RTP Packets
|
||||||
|
listener, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: port})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Faited to open UDP listener %s", err)
|
log.Printf("Faited to open UDP listener %s", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start ffmpag to convert videoInput to video and audio UDP
|
// Start ffmpag to convert input to video and audio UDP
|
||||||
ffmpeg, err := startFFmpeg(videoInput)
|
ffmpeg, err := startFFmpeg(q, input)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Error while starting ffmpeg: %s", err)
|
log.Printf("Error while starting ffmpeg: %s", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Receive video
|
// Receive stream
|
||||||
go func() {
|
go func() {
|
||||||
inboundRTPPacket := make([]byte, 1500) // UDP MTU
|
inboundRTPPacket := make([]byte, 1500) // UDP MTU
|
||||||
for {
|
for {
|
||||||
n, _, err := videoListener.ReadFromUDP(inboundRTPPacket)
|
n, _, err := listener.ReadFromUDP(inboundRTPPacket)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Failed to read from UDP: %s", err)
|
log.Printf("Failed to read from UDP: %s", err)
|
||||||
break
|
break
|
||||||
@ -51,49 +79,13 @@ func ingest(name string, q *messaging.Quality) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if videoTracks[name] == nil {
|
// Write RTP srtPacket to all tracks
|
||||||
videoTracks[name] = make([]*webrtc.Track, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write RTP srtPacket to all video tracks
|
|
||||||
// Adapt payload and SSRC to match destination
|
// Adapt payload and SSRC to match destination
|
||||||
for _, videoTrack := range videoTracks[name] {
|
for _, track := range tracks[name+qualityName] {
|
||||||
packet.Header.PayloadType = videoTrack.PayloadType()
|
packet.Header.PayloadType = track.PayloadType()
|
||||||
packet.Header.SSRC = videoTrack.SSRC()
|
packet.Header.SSRC = track.SSRC()
|
||||||
if writeErr := videoTrack.WriteRTP(packet); writeErr != nil {
|
if writeErr := track.WriteRTP(packet); writeErr != nil {
|
||||||
log.Printf("Failed to write to video track: %s", err)
|
log.Printf("Failed to write to track: %s", writeErr)
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// Receive audio
|
|
||||||
go func() {
|
|
||||||
inboundRTPPacket := make([]byte, 1500) // UDP MTU
|
|
||||||
for {
|
|
||||||
n, _, err := audioListener.ReadFromUDP(inboundRTPPacket)
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("Failed to read from UDP: %s", err)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
packet := &rtp.Packet{}
|
|
||||||
if err := packet.Unmarshal(inboundRTPPacket[:n]); err != nil {
|
|
||||||
log.Printf("Failed to unmarshal RTP srtPacket: %s", err)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if audioTracks[name] == nil {
|
|
||||||
audioTracks[name] = make([]*webrtc.Track, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write RTP srtPacket to all audio tracks
|
|
||||||
// Adapt payload and SSRC to match destination
|
|
||||||
for _, audioTrack := range audioTracks[name] {
|
|
||||||
packet.Header.PayloadType = audioTrack.PayloadType()
|
|
||||||
packet.Header.SSRC = audioTrack.SSRC()
|
|
||||||
if writeErr := audioTrack.WriteRTP(packet); writeErr != nil {
|
|
||||||
log.Printf("Failed to write to audio track: %s", err)
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -105,24 +97,47 @@ func ingest(name string, q *messaging.Quality) {
|
|||||||
log.Printf("Faited to wait for ffmpeg: %s", err)
|
log.Printf("Faited to wait for ffmpeg: %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close UDP listeners
|
// Close UDP listener
|
||||||
if err = videoListener.Close(); err != nil {
|
if err = listener.Close(); err != nil {
|
||||||
log.Printf("Faited to close UDP listener: %s", err)
|
log.Printf("Faited to close UDP listener: %s", err)
|
||||||
}
|
}
|
||||||
if err = audioListener.Close(); err != nil {
|
q.Unregister(input)
|
||||||
log.Printf("Faited to close UDP listener: %s", err)
|
|
||||||
}
|
|
||||||
q.Unregister(videoInput)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func startFFmpeg(in <-chan []byte) (ffmpeg *exec.Cmd, err error) {
|
func startFFmpeg(q *messaging.Quality, in <-chan []byte) (ffmpeg *exec.Cmd, err error) {
|
||||||
ffmpegArgs := []string{"-hide_banner", "-loglevel", "error", "-i", "pipe:0",
|
// FIXME Use transcoders to downscale, then remux in RTP
|
||||||
"-an", "-vcodec", "libvpx", "-crf", "10", "-cpu-used", "5", "-b:v", "6000k", "-maxrate", "8000k", "-bufsize", "12000k", // TODO Change bitrate when changing quality
|
ffmpegArgs := []string{"-hide_banner", "-loglevel", "error", "-i", "pipe:0"}
|
||||||
"-qmin", "10", "-qmax", "42", "-threads", "4", "-deadline", "1", "-error-resilient", "1",
|
switch q.Name {
|
||||||
"-auto-alt-ref", "1",
|
case "audio":
|
||||||
"-f", "rtp", "rtp://127.0.0.1:5004",
|
ffmpegArgs = append(ffmpegArgs, "-vn", "-c:a", "libopus", "-b:a", "160k",
|
||||||
"-vn", "-acodec", "libopus", "-cpu-used", "5", "-deadline", "1", "-qmin", "10", "-qmax", "42", "-error-resilient", "1", "-auto-alt-ref", "1",
|
"-f", "rtp", "rtp://127.0.0.1:5004")
|
||||||
"-f", "rtp", "rtp://127.0.0.1:5005"}
|
break
|
||||||
|
case "source":
|
||||||
|
ffmpegArgs = append(ffmpegArgs, "-an", "-c:v", "copy",
|
||||||
|
"-f", "rtp", "rtp://127.0.0.1:5005")
|
||||||
|
break
|
||||||
|
case "480p":
|
||||||
|
ffmpegArgs = append(ffmpegArgs,
|
||||||
|
"-an", "-c:v", "libx264", "-b:v", "1200k", "-maxrate", "2000k", "-bufsize", "3000k",
|
||||||
|
"-preset", "ultrafast", "-profile", "main", "-tune", "zerolatency",
|
||||||
|
"-vf", "scale=854:480",
|
||||||
|
"-f", "rtp", "rtp://127.0.0.1:5006")
|
||||||
|
break
|
||||||
|
case "360p":
|
||||||
|
ffmpegArgs = append(ffmpegArgs,
|
||||||
|
"-an", "-c:v", "libx264", "-b:v", "800k", "-maxrate", "1200k", "-bufsize", "1500k",
|
||||||
|
"-preset", "ultrafast", "-profile", "main", "-tune", "zerolatency",
|
||||||
|
"-vf", "scale=480:360",
|
||||||
|
"-f", "rtp", "rtp://127.0.0.1:5007")
|
||||||
|
break
|
||||||
|
case "240p":
|
||||||
|
ffmpegArgs = append(ffmpegArgs,
|
||||||
|
"-an", "-c:v", "libx264", "-b:v", "500k", "-maxrate", "800k", "-bufsize", "1000k",
|
||||||
|
"-preset", "ultrafast", "-profile", "main", "-tune", "zerolatency",
|
||||||
|
"-vf", "scale=360:240",
|
||||||
|
"-f", "rtp", "rtp://127.0.0.1:5008")
|
||||||
|
break
|
||||||
|
}
|
||||||
ffmpeg = exec.Command("ffmpeg", ffmpegArgs...)
|
ffmpeg = exec.Command("ffmpeg", ffmpegArgs...)
|
||||||
|
|
||||||
// Handle errors output
|
// Handle errors output
|
||||||
|
@ -40,7 +40,7 @@ func removeTrack(tracks []*webrtc.Track, track *webrtc.Track) []*webrtc.Track {
|
|||||||
|
|
||||||
// GetNumberConnectedSessions get the number of currently connected clients
|
// GetNumberConnectedSessions get the number of currently connected clients
|
||||||
func GetNumberConnectedSessions(streamID string) int {
|
func GetNumberConnectedSessions(streamID string) int {
|
||||||
return len(videoTracks[streamID])
|
return len(audioTracks[streamID])
|
||||||
}
|
}
|
||||||
|
|
||||||
// newPeerHandler is called when server receive a new session description
|
// newPeerHandler is called when server receive a new session description
|
||||||
@ -75,7 +75,7 @@ func newPeerHandler(name string, localSdpChan chan webrtc.SessionDescription, re
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Create video track
|
// Create video track
|
||||||
codec, payloadType := getPayloadType(mediaEngine, webrtc.RTPCodecTypeVideo, "VP8")
|
codec, payloadType := getPayloadType(mediaEngine, webrtc.RTPCodecTypeVideo, "H264")
|
||||||
videoTrack, err := webrtc.NewTrack(payloadType, rand.Uint32(), "video", "pion", codec)
|
videoTrack, err := webrtc.NewTrack(payloadType, rand.Uint32(), "video", "pion", codec)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("Failed to create new video track", err)
|
log.Println("Failed to create new video track", err)
|
||||||
@ -117,21 +117,20 @@ func newPeerHandler(name string, localSdpChan chan webrtc.SessionDescription, re
|
|||||||
quality = split[1]
|
quality = split[1]
|
||||||
}
|
}
|
||||||
log.Printf("New WebRTC session for stream %s, quality %s", streamID, quality)
|
log.Printf("New WebRTC session for stream %s, quality %s", streamID, quality)
|
||||||
// TODO Consider the quality
|
|
||||||
|
|
||||||
// Set the handler for ICE connection state
|
// Set the handler for ICE connection state
|
||||||
// This will notify you when the peer has connected/disconnected
|
// This will notify you when the peer has connected/disconnected
|
||||||
peerConnection.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {
|
peerConnection.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {
|
||||||
log.Printf("Connection State has changed %s \n", connectionState.String())
|
log.Printf("Connection State has changed %s \n", connectionState.String())
|
||||||
if videoTracks[streamID] == nil {
|
if videoTracks[streamID+"@"+quality] == nil {
|
||||||
videoTracks[streamID] = make([]*webrtc.Track, 0, 1)
|
videoTracks[streamID+"@"+quality] = make([]*webrtc.Track, 0, 1)
|
||||||
}
|
}
|
||||||
if audioTracks[streamID] == nil {
|
if audioTracks[streamID] == nil {
|
||||||
audioTracks[streamID] = make([]*webrtc.Track, 0, 1)
|
audioTracks[streamID] = make([]*webrtc.Track, 0, 1)
|
||||||
}
|
}
|
||||||
if connectionState == webrtc.ICEConnectionStateConnected {
|
if connectionState == webrtc.ICEConnectionStateConnected {
|
||||||
// Register tracks
|
// Register tracks
|
||||||
videoTracks[streamID] = append(videoTracks[streamID], videoTrack)
|
videoTracks[streamID+"@"+quality] = append(videoTracks[streamID+"@"+quality], videoTrack)
|
||||||
audioTracks[streamID] = append(audioTracks[streamID], audioTrack)
|
audioTracks[streamID] = append(audioTracks[streamID], audioTrack)
|
||||||
monitoring.WebRTCConnectedSessions.Inc()
|
monitoring.WebRTCConnectedSessions.Inc()
|
||||||
} else if connectionState == webrtc.ICEConnectionStateDisconnected {
|
} else if connectionState == webrtc.ICEConnectionStateDisconnected {
|
||||||
@ -205,16 +204,17 @@ func Serve(streams *messaging.Streams, cfg *Options) {
|
|||||||
|
|
||||||
// Get specific quality
|
// Get specific quality
|
||||||
// FIXME: make it possible to forward other qualities
|
// FIXME: make it possible to forward other qualities
|
||||||
qualityName := "source"
|
for _, qualityName := range []string{"source", "audio", "480p", "360p", "240p"} {
|
||||||
quality, err := stream.GetQuality(qualityName)
|
quality, err := stream.GetQuality(qualityName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Failed to get quality '%s'", qualityName)
|
log.Printf("Failed to get quality '%s'", qualityName)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start forwarding
|
// Start forwarding
|
||||||
log.Printf("Starting webrtc for '%s' quality '%s'", name, qualityName)
|
log.Printf("Starting webrtc for '%s' quality '%s'", name, qualityName)
|
||||||
go ingest(name, quality)
|
go ingest(name, quality)
|
||||||
go listenSdp(name, quality.WebRtcLocalSdp, quality.WebRtcRemoteSdp, cfg)
|
go listenSdp(name, quality.WebRtcLocalSdp, quality.WebRtcRemoteSdp, cfg)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -26,7 +26,7 @@ func TestServe(t *testing.T) {
|
|||||||
peerConnection, _ := api.NewPeerConnection(webrtc.Configuration{})
|
peerConnection, _ := api.NewPeerConnection(webrtc.Configuration{})
|
||||||
|
|
||||||
// Create video track
|
// Create video track
|
||||||
codec, payloadType := getPayloadType(mediaEngine, webrtc.RTPCodecTypeVideo, "VP8")
|
codec, payloadType := getPayloadType(mediaEngine, webrtc.RTPCodecTypeVideo, "H264")
|
||||||
videoTrack, err := webrtc.NewTrack(payloadType, rand.Uint32(), "video", "pion", codec)
|
videoTrack, err := webrtc.NewTrack(payloadType, rand.Uint32(), "video", "pion", codec)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error("Failed to create new video track", err)
|
t.Error("Failed to create new video track", err)
|
||||||
|
@ -3,10 +3,12 @@
|
|||||||
*/
|
*/
|
||||||
export class GsWebRTC {
|
export class GsWebRTC {
|
||||||
/**
|
/**
|
||||||
* @param {list} stunServers
|
* @param {list} stunServers STUN servers
|
||||||
* @param {HTMLElement} connectionIndicator
|
* @param {HTMLElement} viewer Video HTML element
|
||||||
|
* @param {HTMLElement} connectionIndicator Connection indicator element
|
||||||
*/
|
*/
|
||||||
constructor(stunServers, connectionIndicator) {
|
constructor(stunServers, viewer, connectionIndicator) {
|
||||||
|
this.viewer = viewer;
|
||||||
this.connectionIndicator = connectionIndicator;
|
this.connectionIndicator = connectionIndicator;
|
||||||
this.pc = new RTCPeerConnection({
|
this.pc = new RTCPeerConnection({
|
||||||
iceServers: [{ urls: stunServers }]
|
iceServers: [{ urls: stunServers }]
|
||||||
@ -26,7 +28,7 @@ export class GsWebRTC {
|
|||||||
* If connection closed or failed, try to reconnect.
|
* If connection closed or failed, try to reconnect.
|
||||||
*/
|
*/
|
||||||
_onConnectionStateChange() {
|
_onConnectionStateChange() {
|
||||||
console.log("ICE connection state changed to " + this.pc.iceConnectionState);
|
console.log("[WebRTC] ICE connection state changed to " + this.pc.iceConnectionState);
|
||||||
switch (this.pc.iceConnectionState) {
|
switch (this.pc.iceConnectionState) {
|
||||||
case "disconnected":
|
case "disconnected":
|
||||||
this.connectionIndicator.style.fill = "#dc3545";
|
this.connectionIndicator.style.fill = "#dc3545";
|
||||||
@ -39,7 +41,7 @@ export class GsWebRTC {
|
|||||||
break;
|
break;
|
||||||
case "closed":
|
case "closed":
|
||||||
case "failed":
|
case "failed":
|
||||||
console.log("Connection closed, restarting...");
|
console.log("[WebRTC] Connection closed, restarting...");
|
||||||
/*peerConnection.close();
|
/*peerConnection.close();
|
||||||
peerConnection = null;
|
peerConnection = null;
|
||||||
setTimeout(startPeerConnection, 1000);*/
|
setTimeout(startPeerConnection, 1000);*/
|
||||||
@ -52,10 +54,9 @@ export class GsWebRTC {
|
|||||||
* @param {Event} event
|
* @param {Event} event
|
||||||
*/
|
*/
|
||||||
_onTrack(event) {
|
_onTrack(event) {
|
||||||
console.log(`New ${event.track.kind} track`);
|
console.log(`[WebRTC] New ${event.track.kind} track`);
|
||||||
if (event.track.kind === "video") {
|
if (event.track.kind === "video") {
|
||||||
const viewer = document.getElementById("viewer");
|
this.viewer.srcObject = event.streams[0];
|
||||||
viewer.srcObject = event.streams[0];
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -66,7 +67,7 @@ export class GsWebRTC {
|
|||||||
createOffer() {
|
createOffer() {
|
||||||
this.pc.createOffer().then(offer => {
|
this.pc.createOffer().then(offer => {
|
||||||
this.pc.setLocalDescription(offer);
|
this.pc.setLocalDescription(offer);
|
||||||
console.log("WebRTC offer created");
|
console.log("[WebRTC] WebRTC offer created");
|
||||||
}).catch(console.log);
|
}).catch(console.log);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -81,7 +82,7 @@ export class GsWebRTC {
|
|||||||
this.pc.onicecandidate = event => {
|
this.pc.onicecandidate = event => {
|
||||||
if (event.candidate === null) {
|
if (event.candidate === null) {
|
||||||
// Send offer to server
|
// Send offer to server
|
||||||
console.log("Sending session description to server");
|
console.log("[WebRTC] Sending session description to server");
|
||||||
sendFunction(this.pc.localDescription);
|
sendFunction(this.pc.localDescription);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -5,44 +5,42 @@ export class GsWebSocket {
|
|||||||
constructor() {
|
constructor() {
|
||||||
const protocol = (window.location.protocol === "https:") ? "wss://" : "ws://";
|
const protocol = (window.location.protocol === "https:") ? "wss://" : "ws://";
|
||||||
this.url = protocol + window.location.host + "/_ws/";
|
this.url = protocol + window.location.host + "/_ws/";
|
||||||
|
|
||||||
|
// Open WebSocket
|
||||||
|
this._open();
|
||||||
|
|
||||||
|
// Configure events
|
||||||
|
this.socket.addEventListener("open", () => {
|
||||||
|
console.log("[WebSocket] Connection established");
|
||||||
|
});
|
||||||
|
this.socket.addEventListener("close", () => {
|
||||||
|
console.log("[WebSocket] Connection closed, retrying connection in 1s...");
|
||||||
|
setTimeout(() => this._open(), 1000);
|
||||||
|
});
|
||||||
|
this.socket.addEventListener("error", () => {
|
||||||
|
console.log("[WebSocket] Connection errored, retrying connection in 1s...");
|
||||||
|
setTimeout(() => this._open(), 1000);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
_open() {
|
_open() {
|
||||||
|
console.log(`[WebSocket] Connecting to ${this.url}...`);
|
||||||
this.socket = new WebSocket(this.url);
|
this.socket = new WebSocket(this.url);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Open websocket.
|
* Send local WebRTC session description to remote.
|
||||||
* @param {Function} openCallback Function called when connection is established.
|
|
||||||
* @param {Function} closeCallback Function called when connection is lost.
|
|
||||||
*/
|
|
||||||
open() {
|
|
||||||
this._open();
|
|
||||||
this.socket.addEventListener("open", () => {
|
|
||||||
console.log("WebSocket opened");
|
|
||||||
});
|
|
||||||
this.socket.addEventListener("close", () => {
|
|
||||||
console.log("WebSocket closed, retrying connection in 1s...");
|
|
||||||
setTimeout(() => this._open(), 1000);
|
|
||||||
});
|
|
||||||
this.socket.addEventListener("error", () => {
|
|
||||||
console.log("WebSocket errored, retrying connection in 1s...");
|
|
||||||
setTimeout(() => this._open(), 1000);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Exchange WebRTC session description with server.
|
|
||||||
* @param {SessionDescription} localDescription WebRTC local SDP
|
* @param {SessionDescription} localDescription WebRTC local SDP
|
||||||
* @param {string} stream Name of the stream
|
* @param {string} stream Name of the stream
|
||||||
* @param {string} quality Requested quality
|
* @param {string} quality Requested quality
|
||||||
*/
|
*/
|
||||||
sendDescription(localDescription, stream, quality) {
|
sendLocalDescription(localDescription, stream, quality) {
|
||||||
if (this.socket.readyState !== 1) {
|
if (this.socket.readyState !== 1) {
|
||||||
console.log("Waiting for WebSocket to send data...");
|
console.log("[WebSocket] Waiting for connection to send data...");
|
||||||
setTimeout(() => this.sendDescription(localDescription, stream, quality), 100);
|
setTimeout(() => this.sendLocalDescription(localDescription, stream, quality), 100);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
console.log(`[WebSocket] Sending WebRTC local session description for stream ${stream} quality ${quality}`);
|
||||||
this.socket.send(JSON.stringify({
|
this.socket.send(JSON.stringify({
|
||||||
"webRtcSdp": localDescription,
|
"webRtcSdp": localDescription,
|
||||||
"stream": stream,
|
"stream": stream,
|
||||||
@ -51,12 +49,12 @@ export class GsWebSocket {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set callback function on new session description.
|
* Set callback function on new remote session description.
|
||||||
* @param {Function} callback Function called when data is received
|
* @param {Function} callback Function called when data is received
|
||||||
*/
|
*/
|
||||||
onDescription(callback) {
|
onRemoteDescription(callback) {
|
||||||
this.socket.addEventListener("message", (event) => {
|
this.socket.addEventListener("message", (event) => {
|
||||||
console.log("Message from server ", event.data);
|
console.log("[WebSocket] Received WebRTC remote session description");
|
||||||
const sdp = new RTCSessionDescription(JSON.parse(event.data));
|
const sdp = new RTCSessionDescription(JSON.parse(event.data));
|
||||||
callback(sdp);
|
callback(sdp);
|
||||||
});
|
});
|
||||||
|
@ -10,28 +10,28 @@ import { GsWebRTC } from "./modules/webrtc.js";
|
|||||||
* @param {Number} viewersCounterRefreshPeriod
|
* @param {Number} viewersCounterRefreshPeriod
|
||||||
*/
|
*/
|
||||||
export function initViewerPage(stream, stunServers, viewersCounterRefreshPeriod) {
|
export function initViewerPage(stream, stunServers, viewersCounterRefreshPeriod) {
|
||||||
|
// Viewer element
|
||||||
|
const viewer = document.getElementById("viewer");
|
||||||
|
|
||||||
// Default quality
|
// Default quality
|
||||||
let quality = "source";
|
let quality = "240p";
|
||||||
|
|
||||||
// Create WebSocket
|
// Create WebSocket and WebRTC
|
||||||
const s = new GsWebSocket();
|
const websocket = new GsWebSocket();
|
||||||
s.open();
|
const webrtc = new GsWebRTC(
|
||||||
|
|
||||||
// Create WebRTC
|
|
||||||
const c = new GsWebRTC(
|
|
||||||
stunServers,
|
stunServers,
|
||||||
|
viewer,
|
||||||
document.getElementById("connectionIndicator"),
|
document.getElementById("connectionIndicator"),
|
||||||
);
|
);
|
||||||
c.createOffer();
|
webrtc.createOffer();
|
||||||
c.onICECandidate(localDescription => {
|
webrtc.onICECandidate(localDescription => {
|
||||||
s.sendDescription(localDescription, stream, quality);
|
websocket.sendLocalDescription(localDescription, stream, quality);
|
||||||
});
|
});
|
||||||
s.onDescription(sdp => {
|
websocket.onRemoteDescription(sdp => {
|
||||||
c.setRemoteDescription(sdp);
|
webrtc.setRemoteDescription(sdp);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Register keyboard events
|
// Register keyboard events
|
||||||
const viewer = document.getElementById("viewer");
|
|
||||||
window.addEventListener("keydown", (event) => {
|
window.addEventListener("keydown", (event) => {
|
||||||
switch (event.key) {
|
switch (event.key) {
|
||||||
case "f":
|
case "f":
|
||||||
@ -81,7 +81,7 @@ export function initViewerPage(stream, stunServers, viewersCounterRefreshPeriod)
|
|||||||
quality = event.target.value;
|
quality = event.target.value;
|
||||||
console.log(`Stream quality changed to ${quality}`);
|
console.log(`Stream quality changed to ${quality}`);
|
||||||
|
|
||||||
// Restart the connection with a new quality
|
// Restart WebRTC negociation
|
||||||
// FIXME
|
webrtc.createOffer();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -8,10 +8,10 @@
|
|||||||
<div class="controls">
|
<div class="controls">
|
||||||
<span class="control-quality">
|
<span class="control-quality">
|
||||||
<select id="quality">
|
<select id="quality">
|
||||||
<option value="">Source</option>
|
<option value="240p">Source</option>
|
||||||
<option value="@720p">720p</option>
|
<option value="480p">480p</option>
|
||||||
<option value="@480p">480p</option>
|
<option value="360p">360p</option>
|
||||||
<option value="@240p">240p</option>
|
<option value="240p">240p</option>
|
||||||
</select>
|
</select>
|
||||||
</span>
|
</span>
|
||||||
<code class="control-srt-link">srt://{{.Cfg.Hostname}}:{{.Cfg.SRTServerPort}}?streamid={{.Path}}</code>
|
<code class="control-srt-link">srt://{{.Cfg.Hostname}}:{{.Cfg.SRTServerPort}}?streamid={{.Path}}</code>
|
||||||
|
@ -36,21 +36,21 @@ func websocketHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
err = conn.ReadJSON(c)
|
err = conn.ReadJSON(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Failed to receive client description: %s", err)
|
log.Printf("Failed to receive client description: %s", err)
|
||||||
return
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get requested stream
|
// Get requested stream
|
||||||
stream, err := streams.Get(c.Stream)
|
stream, err := streams.Get(c.Stream)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Stream not found: %s", c.Stream)
|
log.Printf("Stream not found: %s", c.Stream)
|
||||||
return
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get requested quality
|
// Get requested quality
|
||||||
q, err := stream.GetQuality(c.Quality)
|
q, err := stream.GetQuality(c.Quality)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Quality not found: %s", c.Quality)
|
log.Printf("Quality not found: %s", c.Quality)
|
||||||
return
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Exchange session descriptions with WebRTC stream server
|
// Exchange session descriptions with WebRTC stream server
|
||||||
@ -61,7 +61,7 @@ func websocketHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
// Send new local description
|
// Send new local description
|
||||||
if err := conn.WriteJSON(localDescription); err != nil {
|
if err := conn.WriteJSON(localDescription); err != nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
return
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user