Video prebuffer and chunked output

mail@pastecode.io avatar
unknown
golang
2 years ago
1.2 kB
2
Indexable
Never
package main

import (
	"bufio"
	"fmt"
	"io"
	"net/http"
	"os/exec"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "video/mp4")

		cmd := exec.Command("ffmpeg", "-i", "input.mp4", "-f", "mp4", "-movflags", "frag_keyframe+empty_moov", "-")
		stdout, err := cmd.StdoutPipe()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		if err := cmd.Start(); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		reader := bufio.NewReaderSize(stdout, 4096)
		cache := make([]byte, 1024)
		for {
			n, err := reader.Read(cache)
			if err != nil && err != io.EOF {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			if n == 0 {
				break
			}

			if _, err := w.Write(cache[:n]); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}

		if err := cmd.Wait(); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	})

	http.ListenAndServe(":8080", nil)
}