-
Notifications
You must be signed in to change notification settings - Fork 1
/
kiyoproctrls.py
executable file
·367 lines (297 loc) · 10.8 KB
/
kiyoproctrls.py
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
#!/usr/bin/env python3
import ctypes, logging, os.path, getopt, sys
from fcntl import ioctl
# ioctl
_IOC_NRBITS = 8
_IOC_TYPEBITS = 8
_IOC_SIZEBITS = 14
_IOC_NRSHIFT = 0
_IOC_TYPESHIFT = _IOC_NRSHIFT + _IOC_NRBITS
_IOC_SIZESHIFT = _IOC_TYPESHIFT + _IOC_TYPEBITS
_IOC_DIRSHIFT = _IOC_SIZESHIFT + _IOC_SIZEBITS
_IOC_WRITE = 1
_IOC_READ = 2
def _IOC(dir_, type_, nr, size):
return (
ctypes.c_int32(dir_ << _IOC_DIRSHIFT).value |
ctypes.c_int32(ord(type_) << _IOC_TYPESHIFT).value |
ctypes.c_int32(nr << _IOC_NRSHIFT).value |
ctypes.c_int32(size << _IOC_SIZESHIFT).value)
def _IOC_TYPECHECK(t):
return ctypes.sizeof(t)
def _IOR(type_, nr, size):
return _IOC(_IOC_READ, type_, nr, _IOC_TYPECHECK(size))
def _IOWR(type_, nr, size):
return _IOC(_IOC_READ | _IOC_WRITE, type_, nr, _IOC_TYPECHECK(size))
#
# ioctl structs, codes for UVC extensions
#
class v4l2_capability(ctypes.Structure):
_fields_ = [
('driver', ctypes.c_char * 16),
('card', ctypes.c_char * 32),
('bus_info', ctypes.c_char * 32),
('version', ctypes.c_uint32),
('capabilities', ctypes.c_uint32),
('device_caps', ctypes.c_uint32),
('reserved', ctypes.c_uint32 * 3),
]
V4L2_CAP_VIDEO_CAPTURE = 0x00000001
class uvc_xu_control_query(ctypes.Structure):
_fields_ = [
('unit', ctypes.c_uint8),
('selector', ctypes.c_uint8),
('query', ctypes.c_uint8), # Video Class-Specific Request Code,
# defined in linux/usb/video.h A.8.
('size', ctypes.c_uint16),
('data', ctypes.c_void_p),
]
VIDIOC_QUERYCAP = _IOR('V', 0, v4l2_capability)
UVCIOC_CTRL_QUERY = _IOWR('u', 0x21, uvc_xu_control_query)
# A.8. Video Class-Specific Request Codes
UVC_RC_UNDEFINED = 0x00
UVC_SET_CUR = 0x01
UVC_GET_CUR = 0x81
UVC_GET_MIN = 0x82
UVC_GET_MAX = 0x83
UVC_GET_RES = 0x84
UVC_GET_LEN = 0x85
UVC_GET_INFO = 0x86
UVC_GET_DEF = 0x87
EU1_SET_ISP = 0x01
EU1_GET_ISP_RESULT = 0x02
# UVC EU1 extension GUID 23e49ed0-1178-4f31-ae52-d2fb8a8d3b48
UVC_EU1_GUID = b'\xd0\x9e\xe4\x23\x78\x11\x31\x4f\xae\x52\xd2\xfb\x8a\x8d\x3b\x48'
# Razer Kiyo Pro specific registers and values
AF_RESPONSIVE = b'\xff\x06\x00\x00\x00\x00\x00\x00'
AF_PASSIVE = b'\xff\x06\x01\x00\x00\x00\x00\x00'
HDR_OFF = b'\xff\x02\x00\x00\x00\x00\x00\x00'
HDR_ON = b'\xff\x02\x01\x00\x00\x00\x00\x00'
HDR_DARK = b'\xff\x07\x00\x00\x00\x00\x00\x00'
HDR_BRIGHT = b'\xff\x07\x01\x00\x00\x00\x00\x00'
FOV_WIDE = b'\xff\x01\x00\x03\x00\x00\x00\x00'
FOV_MEDIUM_PRE = b'\xff\x01\x00\x03\x01\x00\x00\x00'
FOV_MEDIUM = b'\xff\x01\x01\x03\x01\x00\x00\x00'
FOV_NARROW_PRE = b'\xff\x01\x00\x03\x02\x00\x00\x00'
FOV_NARROW = b'\xff\x01\x01\x03\x02\x00\x00\x00'
# Unknown yet, the synapse sends it in start
UNKNOWN = b'\xff\x04\x00\x00\x00\x00\x00\x00'
# save previous values to the camera
SAVE = b'\xc0\x03\xa8\x00\x00\x00\x00\x00'
LOAD = b'\x00\x00\x00\x00\x00\x00\x00\x00'
def to_buf(b):
return ctypes.create_string_buffer(b)
def get_length_xu_control(fd, unit_id, selector):
length = ctypes.c_uint16(0)
xu_ctrl_query = uvc_xu_control_query()
xu_ctrl_query.unit = unit_id
xu_ctrl_query.selector = selector
xu_ctrl_query.query = UVC_GET_LEN
xu_ctrl_query.size = 2 # sizeof(length)
xu_ctrl_query.data = ctypes.cast(ctypes.pointer(length), ctypes.c_void_p)
try:
ioctl(fd, UVCIOC_CTRL_QUERY, xu_ctrl_query)
except Exception as e:
logging.warning(f'UVCIOC_CTRL_QUERY (GET_LEN) - Fd: {fd} - Error: {e}')
return length
def query_xu_control(fd, unit_id, selector, query, data):
len = get_length_xu_control(fd, unit_id, selector)
xu_ctrl_query = uvc_xu_control_query()
xu_ctrl_query.unit = unit_id
xu_ctrl_query.selector = selector
xu_ctrl_query.query = query
xu_ctrl_query.size = len
xu_ctrl_query.data = ctypes.cast(ctypes.pointer(data), ctypes.c_void_p)
try:
ioctl(fd, UVCIOC_CTRL_QUERY, xu_ctrl_query)
except Exception as e:
logging.warning(f'UVCIOC_CTRL_QUERY ({query}) - Fd: {fd} - Error: {e}')
# the usb device descriptors file contains the descriptors in a binary format
# the byte before the extension guid is the extension unit id
def find_unit_id_in_sysfs(device, guid):
if os.path.islink(device):
device = os.readlink(device)
device = os.path.basename(device)
descfile = f'/sys/class/video4linux/{device}/../../../descriptors'
if not os.path.isfile(descfile):
return 0
try:
with open(descfile, 'rb') as f:
descriptors = f.read()
guid_start = descriptors.find(guid)
if guid_start > 0:
return descriptors[guid_start - 1]
except Exception as e:
logging.warning(f'Failed to read uvc xu unit id from {descfile}: {e}')
return 0
def find_usb_ids_in_sysfs(device):
if os.path.islink(device):
device = os.readlink(device)
device = os.path.basename(device)
vendorfile = f'/sys/class/video4linux/{device}/../../../idVendor'
productfile = f'/sys/class/video4linux/{device}/../../../idProduct'
if not os.path.isfile(vendorfile) or not os.path.isfile(productfile):
return ''
vendor = read_usb_id_from_file(vendorfile)
product = read_usb_id_from_file(productfile)
return vendor + ':' + product
def read_usb_id_from_file(file):
id = ''
try:
with open(file, 'r') as f:
id = f.read().strip()
except Exception as e:
logging.warning(f'Failed to read usb id from {file}: {e}')
return id
def get_device_capabilities(device):
cap = v4l2_capability()
try:
fd = os.open(device, os.O_RDWR, 0)
ioctl(fd, VIDIOC_QUERYCAP, cap)
os.close(fd)
except Exception as e:
logging.error(f'get_device_capabilities({device}) failed: {e}')
return cap.device_caps
class KiyoProCtrls:
KIYO_PRO_USB_ID = '1532:0e05'
def __init__(self, device, fd):
self.device = device
self.fd = fd
self.unit_id = find_unit_id_in_sysfs(device, UVC_EU1_GUID)
self.usb_ids = find_usb_ids_in_sysfs(device)
self.get_device_controls()
def supported(self):
return self.unit_id != 0 and self.usb_ids == KiyoProCtrls.KIYO_PRO_USB_ID
def get_device_controls(self):
if not self.supported():
self.ctrls = []
return
# getting the values doesn't work in this way, maybe later in newer firmwares
#current = to_buf(LOAD)
#query_xu_control(self.fd, self.unit_id, EU1_GET_ISP_RESULT, UVC_GET_CUR, current)
#print('current:', list(current))
self.ctrls = [
Ctrl(
'af_mode',
{
AF_PASSIVE: 'passive',
AF_RESPONSIVE: 'responsive',
}
),
Ctrl(
'hdr',
{
HDR_OFF: 'off',
HDR_ON: 'on',
}
),
Ctrl(
'hdr_mode',
{
HDR_BRIGHT: 'bright',
HDR_DARK: 'dark',
}
),
Ctrl(
'fov',
{
FOV_WIDE: 'wide',
FOV_MEDIUM: 'medium',
FOV_NARROW: 'narrow',
}
),
]
self.befores = {
FOV_MEDIUM: FOV_MEDIUM_PRE,
FOV_NARROW: FOV_NARROW_PRE,
}
def print_ctrls(self):
for c in self.ctrls:
for k, v in c.menu.items():
print(f'{c.name}={v}')
def setup_ctrls(self, params):
for k, v in params.items():
ctrl = find_by_name(self.ctrls, k)
if ctrl == None:
logging.warning(f'KiyoProCtrls: can\'t find {k} control in {[c.name for c in self.ctrls]}')
continue
menukey = find_by_value(ctrl.menu, v)
if menukey == None:
logging.warning(f'KiyoProCtrls: can\'t find {v} in {list(ctrl.menu.values())}')
continue
ctrl.value = menukey
before = self.befores.get(ctrl.value)
if before:
query_xu_control(self.fd, self.unit_id, EU1_SET_ISP, UVC_SET_CUR, to_buf(before))
query_xu_control(self.fd, self.unit_id, EU1_SET_ISP, UVC_SET_CUR, to_buf(ctrl.value))
query_xu_control(self.fd, self.unit_id, EU1_SET_ISP, UVC_SET_CUR, to_buf(SAVE))
class Ctrl:
def __init__(self, name, menu = None):
self.name = name
self.value = None
self.menu = menu
def find_by_name(ctrls, name):
for c in ctrls:
if name == c.name:
return c
return None
def find_by_value(menu, value):
for k, v in menu.items():
if v == value:
return k
return None
def usage():
print(f'usage: {sys.argv[0]} [--help] [-d DEVICE] [--list] [-c CONTROLS]\n')
print(f'optional arguments:')
print(f' -h, --help show this help message and exit')
print(f' -d DEVICE use DEVICE, default /dev/video0')
print(f' -l, --list list the controls and values')
print(f' -c CONTROLS set CONTROLS (eg.: hdr=on,fov=wide)')
print()
print(f'example:')
print(f' {sys.argv[0]} -c hdr=on,hdr_mode=dark,af_mode=passive,fov=wide')
def main():
try:
arguments, values = getopt.getopt(sys.argv[1:], 'hd:lc:', ['help', 'list'])
except getopt.error as err:
print(err)
usage()
sys.exit(2)
if len(arguments) == 0:
usage()
sys.exit(0)
list_controls = False
device = '/dev/video0'
controls = ''
for current_argument, current_value in arguments:
if current_argument in ('-h', '--help'):
usage()
sys.exit(0)
elif current_argument in ('-d', '--device'):
device = current_value
elif current_argument in ('-l', '--list'):
list_controls = True
elif current_argument in ('-c'):
controls = current_value
try:
fd = os.open(device, os.O_RDWR, 0)
except Exception as e:
logging.error(f'os.open({device}, os.O_RDWR, 0) failed: {e}')
sys.exit(2)
kiyo_pro = KiyoProCtrls(device, fd)
if not kiyo_pro.supported():
logging.error(f'{device} is not a Kiyo Pro')
sys.exit(3)
if list_controls:
kiyo_pro.print_ctrls()
if controls != '':
ctrlsmap = {}
for control in controls.split(','):
kv = control.split('=', maxsplit=1)
if len(kv) != 2:
logging.warning(f'invalid value: {control}')
continue
ctrlsmap[kv[0]]=kv[1]
kiyo_pro.setup_ctrls(ctrlsmap)
if __name__ == '__main__':
main()