| 1 |
// Package v4l, a facade to the Video4Linux video capture interface |
| 2 |
// Copyright (C) 2016 Zoltán Korándi <[email protected]> |
| 3 |
// |
| 4 |
// This program is free software: you can redistribute it and/or modify |
| 5 |
// it under the terms of the GNU General Public License as published by |
| 6 |
// the Free Software Foundation, either version 3 of the License, or |
| 7 |
// (at your option) any later version. |
| 8 |
// |
| 9 |
// This program is distributed in the hope that it will be useful, |
| 10 |
// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
// GNU General Public License for more details. |
| 13 |
// |
| 14 |
// You should have received a copy of the GNU General Public License |
| 15 |
// along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
|
| 17 |
// Command streamcam streams MJPEG from a V4L device over HTTP. |
| 18 |
// |
| 19 |
// Command Line |
| 20 |
// |
| 21 |
// Usage: |
| 22 |
// streamcam [flags] |
| 23 |
// |
| 24 |
// Flags: |
| 25 |
// -a string |
| 26 |
// address to listen on (default ":8080") |
| 27 |
// -d string |
| 28 |
// path to the capture device |
| 29 |
// -f int |
| 30 |
// frame rate |
| 31 |
// -h int |
| 32 |
// image height |
| 33 |
// -l |
| 34 |
// print supported device configs and quit |
| 35 |
// -r |
| 36 |
// reset all controls to default |
| 37 |
// -w int |
| 38 |
// image width |
| 39 |
package main |
| 40 |
|
| 41 |
import ( |
| 42 |
"bytes" |
| 43 |
"flag" |
| 44 |
"fmt" |
| 45 |
"image" |
| 46 |
"image/jpeg" |
| 47 |
"log" |
| 48 |
"net/http" |
| 49 |
"os" |
| 50 |
"os/signal" |
| 51 |
"sync" |
| 52 |
"time" |
| 53 |
|
| 54 |
"github.com/korandiz/v4l" |
| 55 |
"github.com/korandiz/v4l/fmt/mjpeg" |
| 56 |
) |
| 57 |
|
| 58 |
func main() { |
| 59 |
var ( |
| 60 |
d = flag.String("d", "", "path to the capture device") |
| 61 |
w = flag.Int("w", 0, "image width") |
| 62 |
h = flag.Int("h", 0, "image height") |
| 63 |
f = flag.Int("f", 0, "frame rate") |
| 64 |
a = flag.String("a", ":8080", "address to listen on") |
| 65 |
l = flag.Bool("l", false, "print supported device configs and quit") |
| 66 |
r = flag.Bool("r", false, "reset all controls to default") |
| 67 |
) |
| 68 |
flag.Parse() |
| 69 |
|
| 70 |
if *d == "" { |
| 71 |
devs := v4l.FindDevices() |
| 72 |
if len(devs) != 1 { |
| 73 |
fmt.Fprintln(os.Stderr, "Use -d to select device.") |
| 74 |
for _, info := range devs { |
| 75 |
fmt.Fprintln(os.Stderr, " ", info.Path) |
| 76 |
} |
| 77 |
os.Exit(1) |
| 78 |
} |
| 79 |
*d = devs[0].Path |
| 80 |
} |
| 81 |
fmt.Fprintln(os.Stderr, "Using device", *d) |
| 82 |
cam, err := v4l.Open(*d) |
| 83 |
fatal("Open", err) |
| 84 |
|
| 85 |
if *l { |
| 86 |
configs, err := cam.ListConfigs() |
| 87 |
fatal("ListConfigs", err) |
| 88 |
fmt.Fprintln(os.Stderr, "Supported device configs:") |
| 89 |
found := false |
| 90 |
for _, cfg := range configs { |
| 91 |
if cfg.Format != mjpeg.FourCC { |
| 92 |
continue |
| 93 |
} |
| 94 |
found = true |
| 95 |
fmt.Fprintln(os.Stderr, " ", cfg2str(cfg)) |
| 96 |
} |
| 97 |
if !found { |
| 98 |
fmt.Fprintln(os.Stderr, " (none)") |
| 99 |
} |
| 100 |
os.Exit(0) |
| 101 |
} |
| 102 |
|
| 103 |
cfg, err := cam.GetConfig() |
| 104 |
fatal("GetConfig", err) |
| 105 |
cfg.Format = mjpeg.FourCC |
| 106 |
if *w > 0 { |
| 107 |
cfg.Width = *w |
| 108 |
} |
| 109 |
if *h > 0 { |
| 110 |
cfg.Height = *h |
| 111 |
} |
| 112 |
if *f > 0 { |
| 113 |
cfg.FPS = v4l.Frac{uint32(*f), 1} |
| 114 |
} |
| 115 |
fmt.Fprintln(os.Stderr, "Requested config:", cfg2str(cfg)) |
| 116 |
err = cam.SetConfig(cfg) |
| 117 |
fatal("SetConfig", err) |
| 118 |
err = cam.TurnOn() |
| 119 |
fatal("TurnOn", err) |
| 120 |
cfg, err = cam.GetConfig() |
| 121 |
fatal("GetConfig", err) |
| 122 |
if cfg.Format != mjpeg.FourCC { |
| 123 |
fmt.Fprintln(os.Stderr, "Failed to set MJPEG format.") |
| 124 |
os.Exit(1) |
| 125 |
} |
| 126 |
fmt.Fprintln(os.Stderr, "Actual device config:", cfg2str(cfg)) |
| 127 |
|
| 128 |
if *r { |
| 129 |
ctrls, err := cam.ListControls() |
| 130 |
fatal("ListControls", err) |
| 131 |
for _, ctrl := range ctrls { |
| 132 |
cam.SetControl(ctrl.CID, ctrl.Default) |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
blankImg := image.NewRGBA(image.Rect(0, 0, cfg.Width, cfg.Height)) |
| 137 |
buf := new(bytes.Buffer) |
| 138 |
jpeg.Encode(buf, blankImg, nil) |
| 139 |
blank = buf.Bytes() |
| 140 |
|
| 141 |
go handleInterrupt() |
| 142 |
go stream(cam) |
| 143 |
|
| 144 |
log.Println("Listening on address", *a) |
| 145 |
srv := http.Server{ |
| 146 |
Addr: *a, |
| 147 |
Handler: http.HandlerFunc(serveHTTP), |
| 148 |
} |
| 149 |
err = srv.ListenAndServe() |
| 150 |
fatal("ListenAndServe", err) |
| 151 |
} |
| 152 |
|
| 153 |
func cfg2str(cfg v4l.DeviceConfig) string { |
| 154 |
return fmt.Sprintf("%dx%d @ %.4g FPS", cfg.Width, cfg.Height, |
| 155 |
float64(cfg.FPS.N)/float64(cfg.FPS.D)) |
| 156 |
} |
| 157 |
|
| 158 |
var ( |
| 159 |
mu sync.Mutex |
| 160 |
clients []*client |
| 161 |
stopped bool |
| 162 |
quit = make(chan int, 1) |
| 163 |
blank []byte |
| 164 |
) |
| 165 |
|
| 166 |
type client struct { |
| 167 |
i int |
| 168 |
ch chan []byte |
| 169 |
} |
| 170 |
|
| 171 |
func newClient() *client { |
| 172 |
mu.Lock() |
| 173 |
defer mu.Unlock() |
| 174 |
if stopped { |
| 175 |
return nil |
| 176 |
} |
| 177 |
clt := &client{ |
| 178 |
i: len(clients), |
| 179 |
ch: make(chan []byte, 1), |
| 180 |
} |
| 181 |
clt.ch <- blank |
| 182 |
clients = append(clients, clt) |
| 183 |
return clt |
| 184 |
} |
| 185 |
|
| 186 |
func (clt *client) remove() { |
| 187 |
mu.Lock() |
| 188 |
defer mu.Unlock() |
| 189 |
i := clt.i |
| 190 |
last := len(clients) - 1 |
| 191 |
clients[i] = clients[last] |
| 192 |
clients[i].i = i |
| 193 |
clients[last] = nil |
| 194 |
clients = clients[:last] |
| 195 |
clt.i = -1 |
| 196 |
if stopped && len(clients) == 0 { |
| 197 |
quit <- 1 |
| 198 |
} |
| 199 |
} |
| 200 |
|
| 201 |
func handleInterrupt() { |
| 202 |
ch := make(chan os.Signal, 1) |
| 203 |
signal.Notify(ch, os.Interrupt) |
| 204 |
<-ch |
| 205 |
log.Println("Stopping...") |
| 206 |
mu.Lock() |
| 207 |
stopped = true |
| 208 |
if len(clients) == 0 { |
| 209 |
quit <- 1 |
| 210 |
} else { |
| 211 |
for _, clt := range clients { |
| 212 |
close(clt.ch) |
| 213 |
} |
| 214 |
} |
| 215 |
mu.Unlock() |
| 216 |
<-quit |
| 217 |
os.Exit(0) |
| 218 |
} |
| 219 |
|
| 220 |
func stream(cam *v4l.Device) { |
| 221 |
for { |
| 222 |
buf, err := cam.Capture() |
| 223 |
if err != nil { |
| 224 |
log.Println("Capture:", err) |
| 225 |
proc, _ := os.FindProcess(os.Getpid()) |
| 226 |
proc.Signal(os.Interrupt) |
| 227 |
break |
| 228 |
} |
| 229 |
b := make([]byte, buf.Size()) |
| 230 |
buf.ReadAt(b, 0) |
| 231 |
mu.Lock() |
| 232 |
if stopped { |
| 233 |
mu.Unlock() |
| 234 |
break |
| 235 |
} |
| 236 |
for _, clt := range clients { |
| 237 |
select { |
| 238 |
case clt.ch <- b: |
| 239 |
case <-clt.ch: |
| 240 |
clt.ch <- b |
| 241 |
} |
| 242 |
} |
| 243 |
mu.Unlock() |
| 244 |
} |
| 245 |
} |
| 246 |
|
| 247 |
func serveHTTP(w http.ResponseWriter, r *http.Request) { |
| 248 |
log.Printf("[%s] New connection\n", r.RemoteAddr) |
| 249 |
hj, ok := w.(http.Hijacker) |
| 250 |
if !ok { |
| 251 |
log.Printf("[%s] ResponseWrite is not a Hijacker", r.RemoteAddr) |
| 252 |
http.Error(w, "Internal Server Error", 500) |
| 253 |
return |
| 254 |
} |
| 255 |
conn, _, err := hj.Hijack() |
| 256 |
if err != nil { |
| 257 |
log.Printf("[%s] Hijack: %v\n", r.RemoteAddr, err) |
| 258 |
http.Error(w, "Internal Server Error", 500) |
| 259 |
return |
| 260 |
} |
| 261 |
defer conn.Close() |
| 262 |
|
| 263 |
clt := newClient() |
| 264 |
if clt == nil { |
| 265 |
return |
| 266 |
} |
| 267 |
defer clt.remove() |
| 268 |
|
| 269 |
const B = "45c7pIy0cxa4vWtwGuVuAkbzKAQGpRjz9eyhyHTv" |
| 270 |
|
| 271 |
_, err = conn.Write([]byte("HTTP/1.1 200 OK\r\n" + |
| 272 |
"Date: " + time.Now().UTC().Format(http.TimeFormat) + "\r\n" + |
| 273 |
"Content-Type: multipart/x-mixed-replace; boundary=" + B + "\r\n" + |
| 274 |
"Cache-Control: no-cache, no-store, max-age=0, must-revalidate\r\n" + |
| 275 |
"Pragma: no-cache\r\n" + |
| 276 |
"\r\n" + |
| 277 |
"--" + B + "\r\n")) |
| 278 |
if err != nil { |
| 279 |
log.Printf("[%s] %v\n", r.RemoteAddr, err) |
| 280 |
return |
| 281 |
} |
| 282 |
|
| 283 |
for { |
| 284 |
buf := <-clt.ch |
| 285 |
conn.SetDeadline(time.Now().Add(time.Second)) |
| 286 |
_, err := conn.Write([]byte("Content-Type: image/jpeg\r\n\r\n")) |
| 287 |
if err != nil { |
| 288 |
log.Printf("[%s] %v\n", r.RemoteAddr, err) |
| 289 |
return |
| 290 |
} |
| 291 |
if buf == nil { |
| 292 |
_, err := conn.Write(blank) |
| 293 |
if err == nil { |
| 294 |
conn.Write([]byte("--" + B + "--\r\n")) |
| 295 |
} else { |
| 296 |
log.Printf("[%s] %v\n", r.RemoteAddr, err) |
| 297 |
} |
| 298 |
log.Printf("[%s] Quitting\n", r.RemoteAddr) |
| 299 |
return |
| 300 |
} |
| 301 |
_, err = conn.Write(buf) |
| 302 |
if err != nil { |
| 303 |
log.Printf("[%s] %v\n", r.RemoteAddr, err) |
| 304 |
return |
| 305 |
} |
| 306 |
_, err = conn.Write([]byte("--" + B + "\r\n")) |
| 307 |
if err != nil { |
| 308 |
log.Printf("[%s] %v\n", r.RemoteAddr, err) |
| 309 |
return |
| 310 |
} |
| 311 |
} |
| 312 |
} |
| 313 |
|
| 314 |
func fatal(p string, err error) { |
| 315 |
if err != nil { |
| 316 |
fmt.Fprintf(os.Stderr, "%s: %v\n", p, err) |
| 317 |
os.Exit(1) |
| 318 |
} |
| 319 |
} |