Following up on my previous question, I’d like to inquire about alternative methods for live video streaming using ffmpeg (WebRTC is not an option due to certain constraints I prefer not to discuss here).
Context:
I have a Go application where a goroutine launches ffmpeg to process a video stream, which is then delivered to the main goroutine via a chan []byte
. I tried using WebSocket, but encountered issues as described in the previous question. HLS also didn’t work well due to significant latency and artifacts like green squares on the video.
Based on a comment in the previous question, I attempted to stream the video via a simple GET request. Here’s the Go handler I implemented:
func stream(helperApp agent.Helper) func(rw http.ResponseWriter, rr *http.Request) {
a := atomic.Bool{}
return func(rw http.ResponseWriter, rr *http.Request) {
if !a.CAS(false, true) {
http.Error(rw, "already running", http.StatusInternalServerError)
return
}
rw.Header().Set("Access-Control-Allow-Origin", "*")
rw.Header().Set("Content-Type", "video/mp2t")
out := make(chan []byte)
// create StreamParam
go ScreenCaptureForLiveStream(StreamParam, out) // ffmpeg process starts inside
r, w := io.Pipe()
go func() {
for data := range out {
w.Write(data)
fmt.Println(len(data))
}
}()
io.Copy(rw, r)
}
}
On the client side (HTML):
<video id="video" muted="muted" src="https://localhost:8080/stream" controls></video>
In the browser console, I can see data being received, but the video doesn’t play.
FFmpeg is executed with these parameters:
-loglevel error -f avfoundation -framerate 5 -capture_cursor 1 -capture_mouse_clicks 1 -i 1 -c:v libx264 -pix_fmt yuv420p -vf pad='ceil(iw/2)*2:ceil(ih/2)*2' -threads 0 -preset veryfast -bf 2 -f mpegts pipe:1
For validation, I ran:
ffmpeg -i http://localhost:8080/stream -c copy out.mp4
The video was successfully saved and plays.
Question:
What alternative methods exist to implement live video streaming with ffmpeg, aside from WebRTC? Why does the current approach of streaming video via HTTP GET request not function correctly in the browser, and how can this be resolved?