From 82f1b575f15d7e8b1a8708f69b360d4799401cae Mon Sep 17 00:00:00 2001 From: Muaz Ahmad Date: Fri, 27 Oct 2023 12:46:16 +0500 Subject: [PATCH] cursed mjpeg livestreaming --- http/server.go | 29 +++++++++++++++++++++++++++++ static/index.html | 3 ++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/http/server.go b/http/server.go index 5006760..603efb1 100644 --- a/http/server.go +++ b/http/server.go @@ -1,6 +1,10 @@ package http import ( + "time" + "mime/multipart" + "net/textproto" + "strconv" "net/http" "strings" "os" @@ -21,6 +25,7 @@ func server_setup(server *http.ServeMux) { server.HandleFunc("/list/", serve_live_playlist) // uri returns the playlist file for the given stream key server.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/")))) // returns static files (eventually for the local hls player implementation) server.HandleFunc("/vid/", serve_vid_segment) // serves the appropriate static video segment + server.HandleFunc("/img/", serve_img_loop) } func serve_vid_segment(w http.ResponseWriter, r *http.Request) { @@ -50,3 +55,27 @@ func serve_main_page(w http.ResponseWriter, r *http.Request) { stream_user := strings.TrimPrefix(r.URL.Path, "/live/") page.Execute(w, stream_user) // literally only to define the uri for playlist loading, should be a script but eh } + +func serve_img_loop(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-cache") + stream_id := strings.TrimPrefix(r.URL.Path, "/img/") + base_dir, _ := os.UserHomeDir() + img_path := base_dir + "/live/" + stream_id + "/out.jpg" + + writer := multipart.NewWriter(w) + w.Header().Set("Content-Type", "multipart/x-mixed-replace; boundary=" + writer.Boundary()) + for { + img, err := os.ReadFile(img_path) + if err != nil { + continue + } + part, err := writer.CreatePart(textproto.MIMEHeader{"Content-Type": {"image/jpeg"}, "Content-Length": {strconv.Itoa(len(img))}}) + if err != nil { + break + } + part.Write(img) + time.Sleep(33 * time.Millisecond) + } + writer.Close() + +} diff --git a/static/index.html b/static/index.html index c973553..71bdb4e 100644 --- a/static/index.html +++ b/static/index.html @@ -1,10 +1,11 @@ - Test + {{ . }} +