-
Notifications
You must be signed in to change notification settings - Fork 110
/
webcam.go
495 lines (441 loc) · 13.8 KB
/
webcam.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
package videosource
import (
"context"
"image"
"path/filepath"
"strings"
"sync"
"time"
"github.com/edaniels/golog"
"github.com/edaniels/gostream"
"github.com/pion/mediadevices"
"github.com/pion/mediadevices/pkg/driver"
mediadevicescamera "github.com/pion/mediadevices/pkg/driver/camera"
"github.com/pion/mediadevices/pkg/frame"
"github.com/pion/mediadevices/pkg/prop"
"github.com/pkg/errors"
pb "go.viam.com/api/component/camera/v1"
goutils "go.viam.com/utils"
"go.viam.com/rdk/components/camera"
"go.viam.com/rdk/config"
"go.viam.com/rdk/discovery"
"go.viam.com/rdk/pointcloud"
"go.viam.com/rdk/registry"
"go.viam.com/rdk/resource"
"go.viam.com/rdk/rimage/transform"
"go.viam.com/rdk/utils"
)
var model = resource.NewDefaultModel("webcam")
func init() {
registry.RegisterComponent(
camera.Subtype,
model,
registry.Component{Constructor: func(
ctx context.Context,
_ registry.Dependencies,
config config.Component,
logger golog.Logger,
) (interface{}, error) {
attrs, ok := config.ConvertedAttributes.(*WebcamAttrs)
if !ok {
return nil, utils.NewUnexpectedTypeError(attrs, config.ConvertedAttributes)
}
return NewWebcamSource(ctx, config.Name, attrs, logger)
}})
config.RegisterComponentAttributeMapConverter(camera.Subtype, model,
func(attributes config.AttributeMap) (interface{}, error) {
var conf WebcamAttrs
attrs, err := config.TransformAttributeMapToStruct(&conf, attributes)
if err != nil {
return nil, err
}
result, ok := attrs.(*WebcamAttrs)
if !ok {
return nil, utils.NewUnexpectedTypeError(result, attrs)
}
return result, nil
}, &WebcamAttrs{})
registry.RegisterDiscoveryFunction(
discovery.NewQuery(camera.Subtype, model),
func(ctx context.Context) (interface{}, error) { return Discover(ctx, getVideoDrivers) },
)
}
func getVideoDrivers() []driver.Driver {
return driver.GetManager().Query(driver.FilterVideoRecorder())
}
// CameraConfig is collection of configuration options for a camera.
type CameraConfig struct {
Label string
Status driver.State
Properties []prop.Media
}
// Discover webcam attributes.
func Discover(ctx context.Context, getDrivers func() []driver.Driver) (*pb.Webcams, error) {
var webcams []*pb.Webcam
drivers := getDrivers()
for _, d := range drivers {
driverInfo := d.Info()
props, err := getProperties(d)
if len(props) == 0 {
golog.Global().Debugw("no properties detected for driver, skipping discovery...", "driver", driverInfo.Label)
continue
} else if err != nil {
golog.Global().Debugw("cannot access driver properties, skipping discovery...", "driver", driverInfo.Label, "error", err)
continue
}
if d.Status() == driver.StateRunning {
golog.Global().Debugw("driver is in use, skipping discovery...", "driver", driverInfo.Label)
continue
}
labelParts := strings.Split(driverInfo.Label, mediadevicescamera.LabelSeparator)
label := labelParts[len(labelParts)-1]
wc := &pb.Webcam{
Label: label,
Status: string(d.Status()),
Properties: make([]*pb.Property, 0, len(d.Properties())),
}
for _, prop := range props {
pbProp := &pb.Property{
WidthPx: int32(prop.Video.Width),
HeightPx: int32(prop.Video.Height),
FrameFormat: string(prop.Video.FrameFormat),
}
wc.Properties = append(wc.Properties, pbProp)
}
webcams = append(webcams, wc)
}
return &pb.Webcams{Webcams: webcams}, nil
}
func getProperties(d driver.Driver) (_ []prop.Media, err error) {
// Need to open driver to get properties
if d.Status() == driver.StateClosed {
errOpen := d.Open()
if errOpen != nil {
return nil, errOpen
}
defer func() {
if errClose := d.Close(); errClose != nil {
err = errClose
}
}()
}
return d.Properties(), err
}
// WebcamAttrs is the attribute struct for webcams.
type WebcamAttrs struct {
CameraParameters *transform.PinholeCameraIntrinsics `json:"intrinsic_parameters,omitempty"`
DistortionParameters *transform.BrownConrady `json:"distortion_parameters,omitempty"`
Debug bool `json:"debug,omitempty"`
Format string `json:"format,omitempty"`
Path string `json:"video_path,omitempty"`
Width int `json:"width_px,omitempty"`
Height int `json:"height_px,omitempty"`
}
func makeConstraints(attrs *WebcamAttrs, debug bool, logger golog.Logger) mediadevices.MediaStreamConstraints {
return mediadevices.MediaStreamConstraints{
Video: func(constraint *mediadevices.MediaTrackConstraints) {
if attrs.Width > 0 {
constraint.Width = prop.IntExact(attrs.Width)
} else {
constraint.Width = prop.IntRanged{Min: 0, Ideal: 640, Max: 4096}
}
if attrs.Height > 0 {
constraint.Height = prop.IntExact(attrs.Height)
} else {
constraint.Height = prop.IntRanged{Min: 0, Ideal: 480, Max: 2160}
}
constraint.FrameRate = prop.FloatRanged{0, 200, 60}
if attrs.Format == "" {
constraint.FrameFormat = prop.FrameFormatOneOf{
frame.FormatI420,
frame.FormatI444,
frame.FormatYUY2,
frame.FormatUYVY,
frame.FormatRGBA,
frame.FormatMJPEG,
frame.FormatNV12,
frame.FormatNV21,
}
} else {
constraint.FrameFormat = prop.FrameFormatExact(attrs.Format)
}
if debug {
logger.Debugf("constraints: %v", constraint)
}
},
}
}
// findAndMakeCamera finds a video device and returns a camera with that video device as the source.
func findAndMakeCamera(
ctx context.Context,
attrs *WebcamAttrs,
label string,
logger golog.Logger,
) (camera.Camera, error) {
debug := attrs.Debug
constraints := makeConstraints(attrs, debug, logger)
if label != "" {
cam, err := tryWebcamOpen(ctx, attrs, label, false, constraints, logger)
if err != nil {
return nil, errors.Wrap(err, "cannot open webcam")
}
return cam, nil
}
source, err := gostream.GetAnyVideoSource(constraints, logger)
if err != nil {
return nil, errors.Wrap(err, "found no webcams")
}
cam, err := makeCameraFromSource(ctx, source, attrs)
if err != nil {
return nil, errors.Wrap(err, "cannot make webcam from source")
}
return cam, nil
}
// getLabelFromCameraOrPath returns the path from the camera or an empty string if a path is not found.
func getLabelFromCamera(cam camera.Camera, logger golog.Logger) string {
src, err := camera.SourceFromCamera(cam)
if err != nil {
logger.Errorw("cannot get source from camera", "error", err)
return ""
}
labels, err := gostream.LabelsFromMediaSource[image.Image, prop.Video](src)
if err != nil || len(labels) == 0 {
logger.Errorw("could not get labels from media source", "error", err)
return ""
}
return labels[0]
}
// NewWebcamSource returns a new source based on a webcam discovered from the given attributes.
func NewWebcamSource(ctx context.Context, name string, attrs *WebcamAttrs, logger golog.Logger) (camera.Camera, error) {
cam, err := findAndMakeCamera(ctx, attrs, attrs.Path, logger)
if err != nil {
return nil, errors.Wrap(err, "cannot find video source for camera")
}
logger = logger.With("camera_name", name)
label := attrs.Path
if label == "" {
label = getLabelFromCamera(cam, logger)
logger = logger.With("camera_label", label)
}
cancelCtx, cancel := context.WithCancel(context.Background())
return &monitoredWebcam{
cam: cam,
label: label,
attrs: attrs,
cancelCtx: cancelCtx,
cancel: cancel,
logger: logger,
}, nil
}
// tryWebcamOpen uses getNamedVideoSource to try and find a video device (gostream.MediaSource).
// If successful, it will wrap that MediaSource in a camera.
func tryWebcamOpen(ctx context.Context,
attrs *WebcamAttrs,
path string,
fromLabel bool,
constraints mediadevices.MediaStreamConstraints,
logger golog.Logger,
) (camera.Camera, error) {
source, err := getNamedVideoSource(path, fromLabel, constraints, logger)
if err != nil {
return nil, err
}
if attrs.Width != 0 && attrs.Height != 0 {
img, release, err := gostream.ReadMedia(ctx, source)
if release != nil {
defer release()
}
if err != nil {
return nil, err
}
if img.Bounds().Dx() != attrs.Width || img.Bounds().Dy() != attrs.Height {
return nil, errors.Errorf("requested width and height (%dx%d) are not available for this webcam"+
" (closest driver found by gostream supports resolution %dx%d)",
attrs.Width, attrs.Height, img.Bounds().Dx(), img.Bounds().Dy())
}
}
return makeCameraFromSource(ctx, source, attrs)
}
// makeCameraFromSource takes a gostream.MediaSource and wraps it so that the return
// is an RDK camera object.
func makeCameraFromSource(ctx context.Context,
source gostream.MediaSource[image.Image],
attrs *WebcamAttrs,
) (camera.Camera, error) {
if source == nil {
return nil, errors.New("media source not found")
}
cameraModel := camera.NewPinholeModelWithBrownConradyDistortion(attrs.CameraParameters, attrs.DistortionParameters)
return camera.NewFromSource(
ctx,
source,
&cameraModel,
camera.ColorStream,
)
}
// getNamedVideoSource attempts to find a video device (not a screen) by the given name.
// First it will try to use the path name after evaluating any symbolic links. If
// evaluation fails, it will try to use the path name as provided.
func getNamedVideoSource(
path string,
fromLabel bool,
constraints mediadevices.MediaStreamConstraints,
logger golog.Logger,
) (gostream.MediaSource[image.Image], error) {
if !fromLabel {
resolvedPath, err := filepath.EvalSymlinks(path)
if err == nil {
path = resolvedPath
}
}
return gostream.GetNamedVideoSource(filepath.Base(path), constraints, logger)
}
var _ = camera.LivenessMonitor(&monitoredWebcam{})
// monitoredWebcam tries to ensure its underlying camera stays connected.
type monitoredWebcam struct {
mu sync.RWMutex
cam camera.Camera
label string
attrs *WebcamAttrs
cancelCtx context.Context
cancel func()
closed bool
disconnected bool
activeBackgroundWorkers sync.WaitGroup
logger golog.Logger
}
func (c *monitoredWebcam) isCameraConnected() (bool, error) {
c.mu.RLock()
defer c.mu.RUnlock()
src, err := camera.SourceFromCamera(c.cam)
if err != nil {
return true, errors.Wrap(err, "cannot get source from camera")
}
props, err := gostream.PropertiesFromMediaSource[image.Image, prop.Video](src)
if err != nil {
return true, errors.Wrap(err, "cannot get properties from media source")
}
// github.com/pion/mediadevices connects to the OS to get the props for a driver. On disconnect props will be empty.
// TODO(RSDK-1959): this only works for linux
return len(props) != 0, nil
}
func (c *monitoredWebcam) reconnectCamera(notifyReset func()) error {
c.logger.Debug("closing disconnected camera")
if err := c.cam.Close(c.cancelCtx); err != nil {
c.logger.Errorw("failed to close disconnected camera", "error", err)
}
newCam, err := findAndMakeCamera(c.cancelCtx, c.attrs, c.label, c.logger)
if err != nil {
return errors.Wrap(err, "failed to find camera")
}
c.mu.Lock()
c.cam = newCam
c.disconnected = false
c.closed = false
c.mu.Unlock()
notifyReset()
return nil
}
func (c *monitoredWebcam) Monitor(notifyReset func()) {
const wait = 500 * time.Millisecond
c.activeBackgroundWorkers.Add(1)
goutils.ManagedGo(func() {
for {
if !goutils.SelectContextOrWait(c.cancelCtx, wait) {
return
}
ok, err := c.isCameraConnected()
if err != nil {
c.logger.Debugw("cannot determine camera status", "error", err)
continue
}
if !ok {
c.mu.Lock()
c.disconnected = true
c.mu.Unlock()
c.logger.Error("camera no longer connected; reconnecting")
for {
if !goutils.SelectContextOrWait(c.cancelCtx, wait) {
return
}
if err := c.reconnectCamera(notifyReset); err != nil {
c.logger.Errorw("failed to reconnect camera", "error", err)
continue
}
c.logger.Infow("camera reconnected")
break
}
}
}
}, c.activeBackgroundWorkers.Done)
}
func (c *monitoredWebcam) DoCommand(ctx context.Context, cmd map[string]interface{}) (map[string]interface{}, error) {
c.mu.RLock()
defer c.mu.RUnlock()
if err := c.ensureActive(); err != nil {
return nil, err
}
return c.cam.DoCommand(ctx, cmd)
}
func (c *monitoredWebcam) Projector(ctx context.Context) (transform.Projector, error) {
c.mu.RLock()
defer c.mu.RUnlock()
if err := c.ensureActive(); err != nil {
return nil, err
}
return c.cam.Projector(ctx)
}
func (c *monitoredWebcam) Stream(ctx context.Context, errHandlers ...gostream.ErrorHandler) (gostream.VideoStream, error) {
c.mu.RLock()
defer c.mu.RUnlock()
if err := c.ensureActive(); err != nil {
return nil, err
}
return c.cam.Stream(ctx, errHandlers...)
}
func (c *monitoredWebcam) NextPointCloud(ctx context.Context) (pointcloud.PointCloud, error) {
c.mu.RLock()
defer c.mu.RUnlock()
if err := c.ensureActive(); err != nil {
return nil, err
}
return c.cam.NextPointCloud(ctx)
}
func (c *monitoredWebcam) Properties(ctx context.Context) (camera.Properties, error) {
c.mu.RLock()
defer c.mu.RUnlock()
if err := c.ensureActive(); err != nil {
return camera.Properties{}, err
}
return c.cam.Properties(ctx)
}
var (
errClosed = errors.New("camera has been closed")
errDisconnected = errors.New("camera is disconnected; please try again in a few moments")
)
func (c *monitoredWebcam) ensureActive() error {
if c.closed {
return errClosed
}
if c.disconnected {
return errDisconnected
}
return nil
}
func (c *monitoredWebcam) Close(ctx context.Context) error {
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return errors.New("webcam already closed")
}
c.closed = true
c.mu.Unlock()
c.cancel()
c.activeBackgroundWorkers.Wait()
return c.cam.Close(ctx)
}
func (c *monitoredWebcam) ProxyFor() interface{} {
c.mu.RLock()
defer c.mu.RUnlock()
return c.cam
}