Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func init() {
- RouteHandler{
- function: func(w http.ResponseWriter, r *http.Request) {
- // Create multipart handler
- mpw := multipart.NewWriter(w)
- hdr := make(textproto.MIMEHeader)
- hdr.Add("Content-Type", "image/png")
- // Write initial response
- w.Header().Set("Content-Type", "multipart/x-mixed-replace; boundary="+mpw.Boundary())
- w.WriteHeader(200)
- // Create a flusher to send frames
- flusher, ok := w.(http.Flusher)
- if !ok {
- return
- }
- // If the request contains a token and the token maps to a valid "brain", start consuming frames from
- // the brain and returning them to the client
- params := r.URL.Query()
- if val, ok := params["token"]; ok && len(val) > 0 {
- if b, ok := SharedMemory["brains"].(map[string]*brain.Brain)[val[0]]; ok && !b.CheckHasExit() {
- // Keep a checksum of the previous frame to avoid sending frames which haven't changed. Frames cannot
- // be compared directly (at least efficiently) as they are slices not arrays
- previousFrameChecksum := [16]byte{}
- for {
- if !b.CheckHasExit() {
- frame, err := b.GetNextFrame(SharedMemory["conf"].(map[string]interface{})["DISPLAY_COL"].(color.Color))
- if err == nil && md5.Sum(frame) != previousFrameChecksum {
- // Only write the frame if we succesfully read it and it's different to the previous
- part, err := mpw.CreatePart(hdr)
- if err != nil {
- log.Println(err)
- return
- }
- part.Write(frame)
- //mpw.Close()
- // Update the checksum to this frame
- previousFrameChecksum = md5.Sum(frame)
- // Flush the buffer to make sure the frame is sent ASAP
- flusher.Flush()
- }
- // Limit the framerate to reduce CPU usage
- <-time.After(time.Duration(SharedMemory["conf"].(map[string]interface{})["FPS_LIMITER_INTERVAL"].(int)) * time.Millisecond)
- } else {
- // The brain has exit so there is no more we can do - we are braindead :P
- return
- }
- }
- }
- }
- },
- }.Register("/stream", "/stream.png")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement