-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathcamera.go
276 lines (242 loc) · 6.19 KB
/
camera.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
271
272
273
274
275
276
package vidio
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"regexp"
"runtime"
"strings"
"syscall"
)
type Camera struct {
name string // Camera device name.
width int // Camera frame width.
height int // Camera frame height.
depth int // Camera frame depth.
fps float64 // Camera frame rate.
codec string // Camera codec.
framebuffer []byte // Raw frame data.
pipe io.ReadCloser // Stdout pipe for ffmpeg process streaming webcam.
cmd *exec.Cmd // ffmpeg command.
}
// Camera device name.
func (camera *Camera) Name() string {
return camera.name
}
func (camera *Camera) Width() int {
return camera.width
}
func (camera *Camera) Height() int {
return camera.height
}
// Channels of video frames.
func (camera *Camera) Depth() int {
return camera.depth
}
// Frames per second of video.
func (camera *Camera) FPS() float64 {
return camera.fps
}
func (camera *Camera) Codec() string {
return camera.codec
}
func (camera *Camera) FrameBuffer() []byte {
return camera.framebuffer
}
func (camera *Camera) SetFrameBuffer(buffer []byte) error {
size := camera.width * camera.height * camera.depth
if len(buffer) < size {
return fmt.Errorf("vidio: buffer size %d is smaller than frame size %d", len(buffer), size)
}
camera.framebuffer = buffer
return nil
}
// Creates a new camera struct that can read from the device with the given stream index.
func NewCamera(stream int) (*Camera, error) {
// Check if ffmpeg is installed on the users machine.
if err := installed("ffmpeg"); err != nil {
return nil, err
}
var device string
switch runtime.GOOS {
case "linux":
device = fmt.Sprintf("/dev/video%d", stream)
case "darwin":
device = fmt.Sprintf(`"%d"`, stream)
case "windows":
// If OS is windows, we need to parse the listed devices to find which corresponds to the
// given "stream" index.
devices, err := getDevicesWindows()
if err != nil {
return nil, err
}
if stream < 0 || stream >= len(devices) {
return nil, fmt.Errorf("vidio: could not find device with index: %d", stream)
}
device = fmt.Sprintf("video=%s", devices[stream])
default:
return nil, fmt.Errorf("vidio: unsupported OS: %s", runtime.GOOS)
}
camera := &Camera{name: device, depth: 4}
if err := camera.getCameraData(device); err != nil {
return nil, err
}
return camera, nil
}
// Parses the webcam metadata (width, height, fps, codec) from ffmpeg output.
func (camera *Camera) parseWebcamData(buffer string) {
index := strings.Index(buffer, "Stream #")
if index == -1 {
index++
}
buffer = buffer[index:]
// Dimensions. widthxheight.
regex := regexp.MustCompile(`\d{2,}x\d{2,}`)
match := regex.FindString(buffer)
if len(match) > 0 {
split := strings.Split(match, "x")
camera.width = int(parse(split[0]))
camera.height = int(parse(split[1]))
}
// FPS.
regex = regexp.MustCompile(`\d+(.\d+)? fps`)
match = regex.FindString(buffer)
if len(match) > 0 {
index = strings.Index(match, " fps")
if index != -1 {
match = match[:index]
}
camera.fps = parse(match)
}
// Codec.
regex = regexp.MustCompile("Video: .+,")
match = regex.FindString(buffer)
if len(match) > 0 {
match = match[len("Video: "):]
index = strings.Index(match, "(")
if index != -1 {
match = match[:index]
}
index = strings.Index(match, ",")
if index != -1 {
match = match[:index]
}
camera.codec = strings.TrimSpace(match)
}
}
// Get camera meta data such as width, height, fps and codec.
func (camera *Camera) getCameraData(device string) error {
// Run command to get camera data.
// Webcam will turn on and then off in quick succession.
webcamDeviceName, err := webcam()
if err != nil {
return err
}
cmd := exec.Command(
"ffmpeg",
"-hide_banner",
"-f", webcamDeviceName,
"-i", device,
)
// The command will fail since we do not give a file to write to, therefore
// it will write the meta data to Stderr.
pipe, err := cmd.StderrPipe()
if err != nil {
return err
}
// Start the command.
if err := cmd.Start(); err != nil {
return err
}
// Read ffmpeg output from Stdout.
builder := bytes.Buffer{}
buffer := make([]byte, 1024)
for {
n, err := pipe.Read(buffer)
builder.Write(buffer[:n])
if err == io.EOF {
break
}
}
// Wait for the command to finish.
cmd.Wait()
camera.parseWebcamData(builder.String())
return nil
}
// Once the user calls Read() for the first time on a Camera struct,
// the ffmpeg command which is used to read the camera device is started.
func (camera *Camera) init() error {
// If user exits with Ctrl+C, stop ffmpeg process.
camera.cleanup()
webcamDeviceName, err := webcam()
if err != nil {
return err
}
// Use ffmpeg to pipe webcam to stdout.
cmd := exec.Command(
"ffmpeg",
"-hide_banner",
"-loglevel", "quiet",
"-f", webcamDeviceName,
"-i", camera.name,
"-f", "image2pipe",
"-pix_fmt", "rgba",
"-vcodec", "rawvideo",
"-",
)
camera.cmd = cmd
pipe, err := cmd.StdoutPipe()
if err != nil {
return err
}
camera.pipe = pipe
if err := cmd.Start(); err != nil {
return err
}
if camera.framebuffer == nil {
camera.framebuffer = make([]byte, camera.width*camera.height*camera.depth)
}
return nil
}
// Reads the next frame from the webcam and stores in the framebuffer.
func (camera *Camera) Read() bool {
// If cmd is nil, video reading has not been initialized.
if camera.cmd == nil {
if err := camera.init(); err != nil {
return false
}
}
if _, err := io.ReadFull(camera.pipe, camera.framebuffer); err != nil {
camera.Close()
return false
}
return true
}
// Closes the pipe and stops the ffmpeg process.
func (camera *Camera) Close() {
if camera.pipe != nil {
camera.pipe.Close()
}
if camera.cmd != nil {
camera.cmd.Process.Kill()
}
}
// Stops the "cmd" process running when the user presses Ctrl+C.
// https://stackoverflow.com/questions/11268943/is-it-possible-to-capture-a-ctrlc-signal-and-run-a-cleanup-function-in-a-defe.
func (camera *Camera) cleanup() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
if camera.pipe != nil {
camera.pipe.Close()
}
if camera.cmd != nil {
camera.cmd.Process.Kill()
}
os.Exit(1)
}()
}