ghostream/web/websocket_handler.go

69 lines
1.5 KiB
Go
Raw Normal View History

// Package web serves the JavaScript player and WebRTC negotiation
2020-10-20 17:12:15 +00:00
package web
import (
"log"
"net/http"
"github.com/gorilla/websocket"
"gitlab.crans.org/nounous/ghostream/stream/webrtc"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
// clientDescription is sent by new client
type clientDescription struct {
2020-10-22 06:19:01 +00:00
WebRtcSdp webrtc.SessionDescription
Stream string
Quality string
2020-10-20 17:12:15 +00:00
}
// websocketHandler exchanges WebRTC SDP and viewer count
func websocketHandler(w http.ResponseWriter, r *http.Request) {
// Upgrade client connection to WebSocket
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("Failed to upgrade client to websocket: %s", err)
return
}
for {
// Get client description
c := &clientDescription{}
err = conn.ReadJSON(c)
if err != nil {
log.Printf("Failed to receive client description: %s", err)
2020-11-07 14:00:33 +00:00
_ = conn.Close()
return
2020-10-20 17:12:15 +00:00
}
// Get requested stream
2020-10-22 06:19:01 +00:00
stream, err := streams.Get(c.Stream)
2020-10-20 17:12:15 +00:00
if err != nil {
2020-10-22 06:19:01 +00:00
log.Printf("Stream not found: %s", c.Stream)
2020-10-22 16:41:14 +00:00
continue
2020-10-20 17:12:15 +00:00
}
// Get requested quality
2020-10-22 06:19:01 +00:00
q, err := stream.GetQuality(c.Quality)
2020-10-20 17:12:15 +00:00
if err != nil {
2020-10-22 06:19:01 +00:00
log.Printf("Quality not found: %s", c.Quality)
2020-10-22 16:41:14 +00:00
continue
2020-10-20 17:12:15 +00:00
}
// Exchange session descriptions with WebRTC stream server
// FIXME: Add trickle ICE support
2020-10-22 06:19:01 +00:00
q.WebRtcRemoteSdp <- c.WebRtcSdp
2020-10-20 17:12:15 +00:00
localDescription := <-q.WebRtcLocalSdp
// Send new local description
if err := conn.WriteJSON(localDescription); err != nil {
log.Println(err)
2020-10-22 16:41:14 +00:00
continue
2020-10-20 17:12:15 +00:00
}
}
}