-
Notifications
You must be signed in to change notification settings - Fork 8
/
server.go
114 lines (93 loc) · 2.33 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package server
import (
"bytes"
"encoding/json"
"fmt"
"image"
"image/jpeg"
"net/http"
"sync"
"github.com/jo-m/trainbot/pkg/vid"
"github.com/mattn/go-mjpeg"
"github.com/rs/zerolog/log"
)
// Server is a simple MJPEG HTTP streaming server.
// Use NewServer to initiate an instance.
type Server struct {
mux *http.ServeMux
stream *mjpeg.Stream
lastFrameLock sync.Mutex
lastFrame []byte
}
// NewServer creates a new server.
func NewServer(embed bool) (*Server, error) {
mux := http.NewServeMux()
s := Server{
mux: mux,
stream: mjpeg.NewStream(),
}
wwwRoot, err := getDataRoot(embed)
if err != nil {
return nil, err
}
mux.HandleFunc("/cameras", s.handleCameras)
mux.HandleFunc("/stream.mjpeg", s.stream.ServeHTTP)
mux.HandleFunc("/stream.jpeg", s.handleStreamSnapshot)
mux.Handle("/", http.FileServer(wwwRoot))
return &s, nil
}
// handleCameras detects v4l cameras and returns them as JSON.
// Test via
//
// http localhost:8080/cameras
func (s *Server) handleCameras(resp http.ResponseWriter, _ *http.Request) {
cams, err := vid.DetectCams()
if err != nil {
log.Err(err).Send()
resp.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(resp, err.Error())
return
}
resp.Header().Add("content-type", "application/json")
resp.WriteHeader(http.StatusOK)
err = json.NewEncoder(resp).Encode(cams)
if err != nil {
log.Err(err).Send()
}
}
// handleStreamSnapshot returns a JPEG of the last frame.
// Test via
//
// http localhost:8080/stream.jpeg
func (s *Server) handleStreamSnapshot(resp http.ResponseWriter, _ *http.Request) {
resp.Header().Add("content-type", "image/jpeg")
resp.WriteHeader(http.StatusOK)
s.lastFrameLock.Lock()
ref := s.lastFrame
s.lastFrameLock.Unlock()
_, err := resp.Write(ref)
if err != nil {
log.Err(err).Send()
}
}
// GetMux returns the router.
func (s *Server) GetMux() *http.ServeMux {
return s.mux
}
// SetFrame encodes an image as JPEG and streams it.
func (s *Server) SetFrame(frame image.Image) error {
buf := bytes.Buffer{}
err := jpeg.Encode(&buf, frame, nil)
if err != nil {
return err
}
return s.stream.Update(buf.Bytes())
}
// SetFrameRawJPEG streams a raw encoded JPEG frame.
func (s *Server) SetFrameRawJPEG(frame []byte) error {
cp := append([]byte(nil), frame...)
s.lastFrameLock.Lock()
s.lastFrame = cp
s.lastFrameLock.Unlock()
return s.stream.Update(cp)
}