-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
270 lines (230 loc) · 5.61 KB
/
main.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
// BerryMSE: Low-latency live video via Media Source Extensions (MSE)
// Copyright (C) 2020 Chris Hiszpanski
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"bytes"
"flag"
"fmt"
"log"
"net"
"net/http"
"time"
"github.com/gorilla/websocket"
"github.com/markbates/pkger"
"github.com/thinkski/go-v4l2"
)
// Command line flag parameters
var (
flagListen string
)
func init() {
flag.StringVar(
&flagListen, "l", "localhost:2020", "listen on host:port",
)
}
const (
nalTypeNonIDRCodedSlice = 1
nalTypeIDRCodedSlice = 5
// Time allowed to write a message to the peer.
writeWait = 10 * time.Second
)
// Websocket parameters
var upgrader = websocket.Upgrader{
// Tune read buffers for short acknowledgement messages
ReadBufferSize: 256,
// Tune write buffers to comfortably fit most all B and P frames.
WriteBufferSize: 8192,
// Allow any origin for demo purposes
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// client structure
type client struct {
hub *hub
conn *websocket.Conn // Websocket connection
frags chan []byte // Buffered channel of outbound MP4 fragments
n int // Frame number
haveIDR bool // Received i-frame?
}
// hub maintains a set of active clients and broadcasts video to clients
type hub struct {
clients map[*client]bool // registered clients
nals chan []byte // NAL units from camera source
register chan *client // register requests from clients
unregister chan *client // unregister requests from clients
}
// newHub instantiates a new hub
func newHub() *hub {
return &hub{
clients: make(map[*client]bool),
nals: make(chan []byte),
register: make(chan *client),
unregister: make(chan *client),
}
}
// run processes register and unregister requests, and nal units
func (h *hub) run() {
for {
select {
// Register request
case c := <-h.register:
h.clients[c] = true
var frag bytes.Buffer
writeFTYP(&frag)
writeMOOV(&frag, 1280, 720)
c.frags <- frag.Bytes()
// Unregister request
case c := <-h.unregister:
if _, ok := h.clients[c]; ok {
delete(h.clients, c)
close(c.frags)
}
// New NAL from source
case nal := <-h.nals:
nal = bytes.TrimPrefix(nal, []byte{0, 0, 0, 1})
if len(nal) == 0 {
break
}
nalType := (nal[0] & 0x1F)
for c := range h.clients {
var frag bytes.Buffer
switch nalType {
case nalTypeIDRCodedSlice:
c.haveIDR = true
fallthrough
case nalTypeNonIDRCodedSlice:
if c.haveIDR {
writeMOOF(&frag, c.n, nal)
writeMDAT(&frag, nal)
c.n++
select {
// Write MP4 fragment
case c.frags <- frag.Bytes():
// Buffered channel full. Drop client.
default:
close(c.frags)
delete(h.clients, c)
}
}
default:
// noop
}
}
}
}
}
type source struct {
device *v4l2.Device
hub *hub
}
func newSource(h *hub) *source {
// Open device
dev, err := v4l2.Open("/dev/video0")
if nil != err {
log.Fatal(err)
}
// Set pixel format
if err := dev.SetPixelFormat(
1280,
720,
v4l2.V4L2_PIX_FMT_H264,
); nil != err {
log.Fatal(err)
}
// Set bitrate
if err := dev.SetBitrate(1500000); nil != err {
log.Fatal(err)
}
return &source{
device: dev,
hub: h,
}
}
func (s *source) run() {
// Start stream
if err := s.device.Start(); nil != err {
log.Fatal(err)
}
defer s.device.Stop()
for {
select {
case b := <-s.device.C:
s.hub.nals <- b.Data
b.Release()
}
}
}
// Handle websocket client connections
func serveWs(h *hub, w http.ResponseWriter, r *http.Request) {
// Upgrade websocket connection from HTTP to TCP
conn, err := upgrader.Upgrade(w, r, nil)
if nil != err {
log.Println(err)
return
}
// Instantiate client
c := &client{hub: h, conn: conn, frags: make(chan []byte, 30), n: 1}
c.hub.register <- c
// Go routine writes new MP4 fragment to client websocket
go func(c *client) {
defer func() {
c.conn.Close()
}()
for {
select {
case frag, ok := <-c.frags:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
// Hub closed the channel
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
// Write next segment
nw, err := c.conn.NextWriter(websocket.BinaryMessage)
if nil != err {
return
}
nw.Write(frag)
// Close writer
if err := nw.Close(); nil != err {
return
}
}
}
}(c)
}
func main() {
flag.Parse()
// Parse host:port into host and port
host, port, err := net.SplitHostPort(flagListen)
if nil != err {
log.Fatal(err)
}
// One-to-many hub broadcasts NAL units as MP4 fragments to clients
hub := newHub()
go hub.run()
// Open source
src := newSource(hub)
go src.run()
http.HandleFunc("/websocket", func(w http.ResponseWriter, r *http.Request) {
serveWs(hub, w, r)
})
http.Handle("/", http.FileServer(pkger.Dir("/web/static")))
// Start server
fmt.Printf("Listening on http://%v:%v\n", host, port)
log.Fatal(http.ListenAndServe(flagListen, nil))
}