-
Notifications
You must be signed in to change notification settings - Fork 9
/
device.go
134 lines (112 loc) · 2.23 KB
/
device.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
package v4l2
import (
"golang.org/x/sys/unix"
)
// Device represents a V4L2 (Video4Linux version 2) device.
type Device struct {
opened bool
capQueried bool
fileDescriptor int
cap internalCapability
}
// Open opens a V4L2 device.
//
// Example:
//
// device, err := v4l2.Open(v4l2.Video0)
// if nil != err {
// return err
// })
// defer device.Close()
func Open(name string) (*Device, error) {
var device Device
err := device.Open(name)
if nil != err {
return nil, err
}
return &device, nil
}
// MustOpen is like Open, except it panic()s if there is an error.
func MustOpen(name string) *Device {
datum, err := Open(name)
if nil != err {
panic(err)
}
return datum
}
// Open opens a V4L2 device.
//
// (This method exist so as not to create GC pressure.)
//
// Example:
//
// var device Device
//
// err := device.Open(v4l2.Video0)
// if nil != err {
// return err
// })
// defer device.Close()
func (receiver *Device) Open(name string) error {
if nil == receiver {
return errNilReceiver
}
if receiver.opened {
return errOpen
}
{
var err error
receiver.fileDescriptor, err = unix.Open(name, unix.O_RDWR|unix.O_NONBLOCK, 0666)
if nil != err {
return err
}
receiver.opened = true
}
if err := receiver.cap.QueryFd(receiver.fileDescriptor) ; nil != err {
return err
}
receiver.capQueried = true
return nil
}
// MustOpen is like Open, except it panic()s if there is an error.
func (receiver *Device) MustOpen(name string) {
if nil == receiver {
panic(errNilReceiver)
}
err := receiver.Open(name)
if nil != err {
panic(err)
}
}
// Close closes the device.
//
// You should always close a device after you finished with it, so that you do not create a resource leak.
func (receiver *Device) Close() error {
if nil == receiver {
return nil
}
if !receiver.opened {
return nil
}
err := unix.Close(receiver.fileDescriptor)
if nil != err {
return err
}
receiver.opened = false
return nil
}
// MustClose is like Close, except it panic()s if there is an error.
//
// Example:
//
// device := v4l2.MustOpen(v4l2.Video0)
// defer device.MustClose()
func (receiver *Device) MustClose() {
if nil == receiver {
panic(errNilReceiver)
}
err := receiver.Close()
if nil != err {
panic(err)
}
}