diff --git a/wish-server/.env b/wish-server/.env index aa4c0f3..7372838 100644 --- a/wish-server/.env +++ b/wish-server/.env @@ -1,2 +1,4 @@ HTTP_ADDRESS=127.0.0.1:3001 DATABASE_URL=./streams.db +UDP_MUX_PORT=3478 +TCP_MUX_ADDR=0.0.0.0:3478 diff --git a/wish-server/main.go b/wish-server/main.go index 4ae1c78..d6a69d3 100644 --- a/wish-server/main.go +++ b/wish-server/main.go @@ -5,14 +5,17 @@ import ( "fmt" "io" "log" + "net" "net/http" "os" + "strconv" "strings" "sync" "database/sql" "github.com/joho/godotenv" + "github.com/pion/ice/v2" "github.com/pion/interceptor" "github.com/pion/webrtc/v3" @@ -72,6 +75,7 @@ func setupWebRTC() *webrtc.API { } settingEngine := webrtc.SettingEngine{} + setupICE(&settingEngine) return webrtc.NewAPI( webrtc.WithMediaEngine(mediaEngine), @@ -80,6 +84,40 @@ func setupWebRTC() *webrtc.API { ) } +func setupICE(settingEngine *webrtc.SettingEngine) { + settingEngine.SetNetworkTypes([]webrtc.NetworkType{ + webrtc.NetworkTypeUDP4, // webrtc.NetworkTypeUDP6, + webrtc.NetworkTypeTCP4, // webrtc.NetworkTypeTCP6, + }) + + if udpPort := os.Getenv("UDP_MUX_PORT"); udpPort != "" { + port, err := strconv.Atoi(udpPort) + if err != nil { + log.Fatal(err) + } + mux, err := ice.NewMultiUDPMuxFromPort(port) + if err != nil { + log.Fatal(err) + } + settingEngine.SetICEUDPMux(mux) + } + + if tcpAddr := os.Getenv("TCP_MUX_ADDR"); tcpAddr != "" { + addr, err := net.ResolveTCPAddr("tcp", tcpAddr) + if err != nil { + log.Fatal(err) + } + + listener, err := net.ListenTCP("tcp", addr) + if err != nil { + log.Fatal(err) + } + + mux := webrtc.NewICETCPMux(nil, listener, 8) + settingEngine.SetICETCPMux(mux) + } +} + func withCors(next func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc { return func(res http.ResponseWriter, req *http.Request) { res.Header().Set("Access-Control-Allow-Origin", "*") @@ -149,7 +187,16 @@ func HandleWHIP(res http.ResponseWriter, req *http.Request) { return } - peerConnection, err := api.NewPeerConnection(webrtc.Configuration{}) + peerConnection, err := api.NewPeerConnection(webrtc.Configuration{ + ICEServers: []webrtc.ICEServer{ + { + URLs: []string{"stun:stun.cloudflare.com:3478"}, + }, + { + URLs: []string{"stun:stun.l.google.com:19302"}, + }, + }, + }) if err != nil { logHTTPError(res, err.Error(), http.StatusInternalServerError) return