xref: /openbsd/sys/dev/usb/utvfu.c (revision 8a8057a7)
1 /*	$OpenBSD: utvfu.c,v 1.22 2025/01/15 20:34:50 kirill Exp $ */
2 /*
3  * Copyright (c) 2013 Lubomir Rintel
4  * Copyright (c) 2013 Federico Simoncelli
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions, and the following disclaimer,
12  *    without modification.
13  * 2. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * Alternatively, this software may be distributed under the terms of the
17  * GNU General Public License ("GPL").
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31 /*
32  * Fushicai USBTV007 Audio-Video Grabber Driver
33  *
34  * Product web site:
35  * http://www.fushicai.com/products_detail/&productId=d05449ee-b690-42f9-a661-aa7353894bed.html
36  *
37  * Following LWN articles were very useful in construction of this driver:
38  * Video4Linux2 API series: http://lwn.net/Articles/203924/
39  * videobuf2 API explanation: http://lwn.net/Articles/447435/
40  * Thanks go to Jonathan Corbet for providing this quality documentation.
41  * He is awesome.
42  *
43  * No physical hardware was harmed running Windows during the
44  * reverse-engineering activity
45  */
46 
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/fcntl.h>
50 #include <sys/kthread.h>
51 #include <sys/malloc.h>
52 #include <sys/device.h>
53 
54 #include <uvm/uvm_extern.h>
55 
56 #include <machine/bus.h>
57 
58 #include <dev/usb/usb.h>
59 #include <dev/usb/usbdi.h>
60 #include <dev/usb/usbdivar.h>
61 #include <dev/usb/usb_mem.h>
62 #include <dev/usb/usbdi_util.h>
63 #include <dev/usb/usbdevs.h>
64 #include <dev/usb/utvfu.h>
65 
66 #include <dev/audio_if.h>
67 #include <dev/video_if.h>
68 
69 #ifdef UTVFU_DEBUG
70 int utvfu_debug = 1;
71 #define DPRINTF(l, x...) do { if ((l) <= utvfu_debug) printf(x); } while (0)
72 #else
73 #define DPRINTF(l, x...)
74 #endif
75 
76 #define DEVNAME(_s) ((_s)->sc_dev.dv_xname)
77 
78 struct utvfu_norm_params utvfu_norm_params[] = {
79 	{
80 		.norm = V4L2_STD_525_60,
81 		.cap_width = 720,
82 		.cap_height = 480,
83 		/* 4 bytes/2 pixel YUYV/YUV 4:2:2 */
84 		.frame_len = (720 * 480 * 2),
85 	},
86 	{
87 		.norm = V4L2_STD_PAL,
88 		.cap_width = 720,
89 		.cap_height = 576,
90 		/* 4 bytes/2 pixel YUYV/YUV 4:2:2 */
91 		.frame_len = (720 * 576 * 2),
92 	}
93 };
94 
95 int
utvfu_set_regs(struct utvfu_softc * sc,const uint16_t regs[][2],int size)96 utvfu_set_regs(struct utvfu_softc *sc, const uint16_t regs[][2], int size)
97 {
98 	int i;
99 	usbd_status error;
100 	usb_device_request_t req;
101 
102 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
103 	req.bRequest = UTVFU_REQUEST_REG;
104 	USETW(req.wLength, 0);
105 
106 	for (i = 0; i < size; i++) {
107 		USETW(req.wIndex, regs[i][0]);
108 		USETW(req.wValue, regs[i][1]);
109 
110 		error = usbd_do_request(sc->sc_udev, &req, NULL);
111 		if (error != USBD_NORMAL_COMPLETION) {
112 			DPRINTF(1, "%s: %s: exit EINVAL\n",
113 			    DEVNAME(sc), __func__);
114 			return (EINVAL);
115 		}
116 	}
117 
118 	return (0);
119 }
120 
121 int
utvfu_max_frame_size(void)122 utvfu_max_frame_size(void)
123 {
124 	int i, sz = 0;
125 
126 	for (i = 0; i < nitems(utvfu_norm_params); i++) {
127 		if (sz < utvfu_norm_params[i].frame_len)
128 			sz = utvfu_norm_params[i].frame_len;
129 	}
130 
131 	return (sz);
132 }
133 
134 int
utvfu_configure_for_norm(struct utvfu_softc * sc,v4l2_std_id norm)135 utvfu_configure_for_norm(struct utvfu_softc *sc, v4l2_std_id norm)
136 {
137 	int i, ret = EINVAL;
138 	struct utvfu_norm_params *params = NULL;
139 
140 	for (i = 0; i < nitems(utvfu_norm_params); i++) {
141 		if (utvfu_norm_params[i].norm & norm) {
142 			params = &utvfu_norm_params[i];
143 			break;
144 		}
145 	}
146 
147 	if (params != NULL) {
148 		sc->sc_normi = i;
149 		sc->sc_nchunks = params->cap_width * params->cap_height
150 		    / 4 / UTVFU_CHUNK;
151 		ret = 0;
152 	}
153 
154 	return (ret);
155 }
156 
157 int
utvfu_select_input(struct utvfu_softc * sc,int input)158 utvfu_select_input(struct utvfu_softc *sc, int input)
159 {
160 	int ret;
161 
162 	static const uint16_t composite[][2] = {
163 		{ UTVFU_BASE + 0x0105, 0x0060 },
164 		{ UTVFU_BASE + 0x011f, 0x00f2 },
165 		{ UTVFU_BASE + 0x0127, 0x0060 },
166 		{ UTVFU_BASE + 0x00ae, 0x0010 },
167 		{ UTVFU_BASE + 0x0239, 0x0060 },
168 	};
169 
170 	static const uint16_t svideo[][2] = {
171 		{ UTVFU_BASE + 0x0105, 0x0010 },
172 		{ UTVFU_BASE + 0x011f, 0x00ff },
173 		{ UTVFU_BASE + 0x0127, 0x0060 },
174 		{ UTVFU_BASE + 0x00ae, 0x0030 },
175 		{ UTVFU_BASE + 0x0239, 0x0060 },
176 	};
177 
178 	switch (input) {
179 	case UTVFU_COMPOSITE_INPUT:
180 		ret = utvfu_set_regs(sc, composite, nitems(composite));
181 		break;
182 	case UTVFU_SVIDEO_INPUT:
183 		ret = utvfu_set_regs(sc, svideo, nitems(svideo));
184 		break;
185 	default:
186 		ret = EINVAL;
187 	}
188 
189 	if (ret == 0)
190 		sc->sc_input = input;
191 
192 	return (ret);
193 }
194 
195 int
utvfu_select_norm(struct utvfu_softc * sc,v4l2_std_id norm)196 utvfu_select_norm(struct utvfu_softc *sc, v4l2_std_id norm)
197 {
198 	int ret;
199 	static const uint16_t pal[][2] = {
200 		{ UTVFU_BASE + 0x001a, 0x0068 },
201 		{ UTVFU_BASE + 0x010e, 0x0072 },
202 		{ UTVFU_BASE + 0x010f, 0x00a2 },
203 		{ UTVFU_BASE + 0x0112, 0x00b0 },
204 		{ UTVFU_BASE + 0x0117, 0x0001 },
205 		{ UTVFU_BASE + 0x0118, 0x002c },
206 		{ UTVFU_BASE + 0x012d, 0x0010 },
207 		{ UTVFU_BASE + 0x012f, 0x0020 },
208 		{ UTVFU_BASE + 0x024f, 0x0002 },
209 		{ UTVFU_BASE + 0x0254, 0x0059 },
210 		{ UTVFU_BASE + 0x025a, 0x0016 },
211 		{ UTVFU_BASE + 0x025b, 0x0035 },
212 		{ UTVFU_BASE + 0x0263, 0x0017 },
213 		{ UTVFU_BASE + 0x0266, 0x0016 },
214 		{ UTVFU_BASE + 0x0267, 0x0036 }
215 	};
216 
217 	static const uint16_t ntsc[][2] = {
218 		{ UTVFU_BASE + 0x001a, 0x0079 },
219 		{ UTVFU_BASE + 0x010e, 0x0068 },
220 		{ UTVFU_BASE + 0x010f, 0x009c },
221 		{ UTVFU_BASE + 0x0112, 0x00f0 },
222 		{ UTVFU_BASE + 0x0117, 0x0000 },
223 		{ UTVFU_BASE + 0x0118, 0x00fc },
224 		{ UTVFU_BASE + 0x012d, 0x0004 },
225 		{ UTVFU_BASE + 0x012f, 0x0008 },
226 		{ UTVFU_BASE + 0x024f, 0x0001 },
227 		{ UTVFU_BASE + 0x0254, 0x005f },
228 		{ UTVFU_BASE + 0x025a, 0x0012 },
229 		{ UTVFU_BASE + 0x025b, 0x0001 },
230 		{ UTVFU_BASE + 0x0263, 0x001c },
231 		{ UTVFU_BASE + 0x0266, 0x0011 },
232 		{ UTVFU_BASE + 0x0267, 0x0005 }
233 	};
234 
235 	ret = utvfu_configure_for_norm(sc, norm);
236 
237 	if (ret == 0) {
238 		if (norm & V4L2_STD_525_60)
239 			ret = utvfu_set_regs(sc, ntsc, nitems(ntsc));
240 		else if (norm & V4L2_STD_PAL)
241 			ret = utvfu_set_regs(sc, pal, nitems(pal));
242 	}
243 
244 	return (ret);
245 }
246 
247 int
utvfu_setup_capture(struct utvfu_softc * sc)248 utvfu_setup_capture(struct utvfu_softc *sc)
249 {
250 	int ret;
251 	static const uint16_t setup[][2] = {
252 		/* These seem to enable the device. */
253 		{ UTVFU_BASE + 0x0008, 0x0001 },
254 		{ UTVFU_BASE + 0x01d0, 0x00ff },
255 		{ UTVFU_BASE + 0x01d9, 0x0002 },
256 
257 		/*
258 		 * These seem to influence color parameters, such as
259 		 * brightness, etc.
260 		 */
261 		{ UTVFU_BASE + 0x0239, 0x0040 },
262 		{ UTVFU_BASE + 0x0240, 0x0000 },
263 		{ UTVFU_BASE + 0x0241, 0x0000 },
264 		{ UTVFU_BASE + 0x0242, 0x0002 },
265 		{ UTVFU_BASE + 0x0243, 0x0080 },
266 		{ UTVFU_BASE + 0x0244, 0x0012 },
267 		{ UTVFU_BASE + 0x0245, 0x0090 },
268 		{ UTVFU_BASE + 0x0246, 0x0000 },
269 
270 		{ UTVFU_BASE + 0x0278, 0x002d },
271 		{ UTVFU_BASE + 0x0279, 0x000a },
272 		{ UTVFU_BASE + 0x027a, 0x0032 },
273 		{ 0xf890, 0x000c },
274 		{ 0xf894, 0x0086 },
275 
276 		{ UTVFU_BASE + 0x00ac, 0x00c0 },
277 		{ UTVFU_BASE + 0x00ad, 0x0000 },
278 		{ UTVFU_BASE + 0x00a2, 0x0012 },
279 		{ UTVFU_BASE + 0x00a3, 0x00e0 },
280 		{ UTVFU_BASE + 0x00a4, 0x0028 },
281 		{ UTVFU_BASE + 0x00a5, 0x0082 },
282 		{ UTVFU_BASE + 0x00a7, 0x0080 },
283 		{ UTVFU_BASE + 0x0000, 0x0014 },
284 		{ UTVFU_BASE + 0x0006, 0x0003 },
285 		{ UTVFU_BASE + 0x0090, 0x0099 },
286 		{ UTVFU_BASE + 0x0091, 0x0090 },
287 		{ UTVFU_BASE + 0x0094, 0x0068 },
288 		{ UTVFU_BASE + 0x0095, 0x0070 },
289 		{ UTVFU_BASE + 0x009c, 0x0030 },
290 		{ UTVFU_BASE + 0x009d, 0x00c0 },
291 		{ UTVFU_BASE + 0x009e, 0x00e0 },
292 		{ UTVFU_BASE + 0x0019, 0x0006 },
293 		{ UTVFU_BASE + 0x008c, 0x00ba },
294 		{ UTVFU_BASE + 0x0101, 0x00ff },
295 		{ UTVFU_BASE + 0x010c, 0x00b3 },
296 		{ UTVFU_BASE + 0x01b2, 0x0080 },
297 		{ UTVFU_BASE + 0x01b4, 0x00a0 },
298 		{ UTVFU_BASE + 0x014c, 0x00ff },
299 		{ UTVFU_BASE + 0x014d, 0x00ca },
300 		{ UTVFU_BASE + 0x0113, 0x0053 },
301 		{ UTVFU_BASE + 0x0119, 0x008a },
302 		{ UTVFU_BASE + 0x013c, 0x0003 },
303 		{ UTVFU_BASE + 0x0150, 0x009c },
304 		{ UTVFU_BASE + 0x0151, 0x0071 },
305 		{ UTVFU_BASE + 0x0152, 0x00c6 },
306 		{ UTVFU_BASE + 0x0153, 0x0084 },
307 		{ UTVFU_BASE + 0x0154, 0x00bc },
308 		{ UTVFU_BASE + 0x0155, 0x00a0 },
309 		{ UTVFU_BASE + 0x0156, 0x00a0 },
310 		{ UTVFU_BASE + 0x0157, 0x009c },
311 		{ UTVFU_BASE + 0x0158, 0x001f },
312 		{ UTVFU_BASE + 0x0159, 0x0006 },
313 		{ UTVFU_BASE + 0x015d, 0x0000 },
314 
315 		{ UTVFU_BASE + 0x0003, 0x0004 },
316 		{ UTVFU_BASE + 0x0100, 0x00d3 },
317 		{ UTVFU_BASE + 0x0115, 0x0015 },
318 		{ UTVFU_BASE + 0x0220, 0x002e },
319 		{ UTVFU_BASE + 0x0225, 0x0008 },
320 		{ UTVFU_BASE + 0x024e, 0x0002 },
321 		{ UTVFU_BASE + 0x024e, 0x0002 },
322 		{ UTVFU_BASE + 0x024f, 0x0002 },
323 	};
324 
325 	ret = utvfu_set_regs(sc, setup, nitems(setup));
326 	if (ret)
327 		return (ret);
328 
329 	ret = utvfu_select_norm(sc, utvfu_norm_params[sc->sc_normi].norm);
330 	if (ret)
331 		return (ret);
332 
333 	ret = utvfu_select_input(sc, sc->sc_input);
334 	if (ret)
335 		return (ret);
336 
337 	return (0);
338 }
339 
340 /*
341  * Copy data from chunk into a frame buffer, deinterlacing the data
342  * into every second line. Unfortunately, they don't align nicely into
343  * 720 pixel lines, as the chunk is 240 words long, which is 480 pixels.
344  * Therefore, we break down the chunk into two halves before copying,
345  * so that we can interleave a line if needed.
346  *
347  * Each "chunk" is 240 words; a word in this context equals 4 bytes.
348  * Image format is YUYV/YUV 4:2:2, consisting of Y Cr Y Cb, defining two
349  * pixels, the Cr and Cb shared between the two pixels, but each having
350  * separate Y values. Thus, the 240 words equal 480 pixels. It therefore,
351  * takes 1.5 chunks to make a 720 pixel-wide line for the frame.
352  * The image is interlaced, so there is a "scan" of odd lines, followed
353  * by "scan" of even numbered lines.
354  *
355  * Following code is writing the chunks in correct sequence, skipping
356  * the rows based on "odd" value.
357  * line 1: chunk[0][  0..479] chunk[0][480..959] chunk[1][  0..479]
358  * line 3: chunk[1][480..959] chunk[2][  0..479] chunk[2][480..959]
359  * ...etc
360  */
361 void
utvfu_chunk_to_vbuf(uint8_t * frame,uint8_t * src,int chunk_no,int odd)362 utvfu_chunk_to_vbuf(uint8_t *frame, uint8_t *src, int chunk_no, int odd)
363 {
364 	uint8_t *dst;
365 	int half, line, part_no, part_index;
366 	#define	UTVFU_STRIDE	(UTVFU_CHUNK/2 * 4)
367 
368 	for (half = 0; half < 2; half++) {
369 		part_no = chunk_no * 2 + half;
370 		line = part_no / 3;
371 		part_index = (line * 2 + !odd) * 3 + (part_no % 3);
372 
373 		dst = &frame[part_index * UTVFU_STRIDE];
374 
375 		memcpy(dst, src, UTVFU_STRIDE);
376 		src += UTVFU_STRIDE;
377 	}
378 	#undef	UTVFU_STRIDE
379 }
380 
381 /*
382  * Called for each 256-byte image chunk.
383  * First word identifies the chunk, followed by 240 words of image
384  * data and padding.
385  */
386 void
utvfu_image_chunk(struct utvfu_softc * sc,u_char * chunk)387 utvfu_image_chunk(struct utvfu_softc *sc, u_char *chunk)
388 {
389 	int frame_id, odd, chunk_no, frame_len;
390 	uint32_t hdr;
391 
392 	memcpy(&hdr, chunk, sizeof(hdr));
393 	chunk += sizeof(hdr);
394 	hdr = be32toh(hdr);
395 
396 	/* Ignore corrupted lines. */
397 	if (!UTVFU_MAGIC_OK(hdr)) {
398 		DPRINTF(2, "%s: bad magic=0x%08x\n",
399 		    DEVNAME(sc), UTVFU_MAGIC(hdr));
400 		return;
401 	}
402 
403 	frame_id = UTVFU_FRAME_ID(hdr);
404 	odd = UTVFU_ODD(hdr);
405 	chunk_no = UTVFU_CHUNK_NO(hdr);
406 	if (chunk_no >= sc->sc_nchunks) {
407 		DPRINTF(2, "%s: chunk_no=%d >= sc_nchunks=%d\n",
408 		    DEVNAME(sc), chunk_no, sc->sc_nchunks);
409 		return;
410 	}
411 
412 	/* Beginning of a frame. */
413 	if (chunk_no == 0) {
414 		sc->sc_fb.fid = frame_id;
415 		sc->sc_fb.chunks_done = 0;
416 	}
417 	else if (sc->sc_fb.fid != frame_id) {
418 		DPRINTF(2, "%s: frame id mismatch expecting=%d got=%d\n",
419 		    DEVNAME(sc), sc->sc_fb.fid, frame_id);
420 		return;
421 	}
422 
423 	frame_len = utvfu_norm_params[sc->sc_normi].frame_len;
424 
425 	/* Copy the chunk data. */
426 	utvfu_chunk_to_vbuf(sc->sc_fb.buf, chunk, chunk_no, odd);
427 	sc->sc_fb.chunks_done++;
428 
429 	/* Last chunk in a field */
430 	if (chunk_no == sc->sc_nchunks-1) {
431 		/* Last chunk in a frame, signalling an end */
432 		if (odd && !sc->sc_fb.last_odd) {
433 			if (sc->sc_fb.chunks_done != sc->sc_nchunks) {
434 				DPRINTF(1, "%s: chunks_done=%d != nchunks=%d\n",
435 				    DEVNAME(sc),
436 				    sc->sc_fb.chunks_done, sc->sc_nchunks);
437 			}
438 
439 			if (sc->sc_flags & UTVFU_FLAG_MMAP) {
440 				utvfu_mmap_queue(sc, sc->sc_fb.buf, frame_len);
441 			}
442 			else {
443 				utvfu_read(sc, sc->sc_fb.buf, frame_len);
444 			}
445 		}
446 		sc->sc_fb.last_odd = odd;
447 	}
448 }
449 
450 int
utvfu_start_capture(struct utvfu_softc * sc)451 utvfu_start_capture(struct utvfu_softc *sc)
452 {
453 	usbd_status error;
454 	int restart_au;
455 
456 	DPRINTF(1, "%s: %s\n", DEVNAME(sc), __func__);
457 
458 	restart_au = ISSET(sc->sc_flags, UTVFU_FLAG_AS_RUNNING);
459 	utvfu_audio_stop(sc);
460 
461 	/* default video stream interface */
462 	error = usbd_set_interface(sc->sc_uifaceh, UTVFU_DFLT_IFACE_IDX);
463 	if (error != USBD_NORMAL_COMPLETION)
464 		return (EINVAL);
465 
466 	if (utvfu_setup_capture(sc) != 0)
467 		return (EINVAL);
468 
469 	/* alt setting */
470 	error = usbd_set_interface(sc->sc_uifaceh, UTVFU_ALT_IFACE_IDX);
471 	if (error != USBD_NORMAL_COMPLETION)
472 		return (EINVAL);
473 
474 	if (restart_au)
475 		utvfu_audio_start(sc);
476 
477 	return (0);
478 }
479 
480 int
utvfu_querycap(void * v,struct v4l2_capability * cap)481 utvfu_querycap(void *v, struct v4l2_capability *cap)
482 {
483 	struct utvfu_softc *sc = v;
484 
485 	memset(cap, 0, sizeof(*cap));
486 	strlcpy(cap->driver, DEVNAME(sc), sizeof(cap->driver));
487 	strlcpy(cap->card, "utvfu", sizeof(cap->card));
488 	strlcpy(cap->bus_info, "usb", sizeof(cap->bus_info));
489 	cap->device_caps = V4L2_CAP_VIDEO_CAPTURE;
490 	cap->device_caps |= V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
491 	cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
492 
493 	return (0);
494 }
495 
496 int
utvfu_enum_input(void * v,struct v4l2_input * i)497 utvfu_enum_input(void *v, struct v4l2_input *i)
498 {
499 	struct utvfu_softc *sc = v;
500 
501 	switch (i->index) {
502 	case UTVFU_COMPOSITE_INPUT:
503 		strlcpy(i->name, "Composite", sizeof(i->name));
504 		break;
505 	case UTVFU_SVIDEO_INPUT:
506 		strlcpy(i->name, "S-Video", sizeof(i->name));
507 		break;
508 	default:
509 		return (EINVAL);
510 	}
511 
512 	i->type = V4L2_INPUT_TYPE_CAMERA;
513 	i->std = utvfu_norm_params[sc->sc_normi].norm;
514 
515 	return (0);
516 }
517 
518 int
utvfu_enum_fmt_vid_cap(void * v,struct v4l2_fmtdesc * f)519 utvfu_enum_fmt_vid_cap(void *v, struct v4l2_fmtdesc *f)
520 {
521 	if (f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE || f->index != 0)
522 		return (EINVAL);
523 
524 	strlcpy(f->description, "16 bpp YUY2, 4:2:2, packed",
525 					sizeof(f->description));
526 	f->pixelformat = V4L2_PIX_FMT_YUYV;
527 
528 	return (0);
529 }
530 
531 int
utvfu_enum_fsizes(void * v,struct v4l2_frmsizeenum * fsizes)532 utvfu_enum_fsizes(void *v, struct v4l2_frmsizeenum *fsizes)
533 {
534 	struct utvfu_softc *sc = v;
535 
536 	if (fsizes->pixel_format != V4L2_PIX_FMT_YUYV)
537 		return (EINVAL);
538 
539 	/* The device only supports one frame size. */
540 	if (fsizes->index >= 1)
541 		return (EINVAL);
542 
543 	fsizes->type = V4L2_FRMSIZE_TYPE_DISCRETE;
544 	fsizes->discrete.width = utvfu_norm_params[sc->sc_normi].cap_width;
545 	fsizes->discrete.height = utvfu_norm_params[sc->sc_normi].cap_height;
546 
547 	return (0);
548 }
549 
550 int
utvfu_g_fmt(void * v,struct v4l2_format * f)551 utvfu_g_fmt(void *v, struct v4l2_format *f)
552 {
553 	struct utvfu_softc *sc = v;
554 
555 	f->fmt.pix.width = utvfu_norm_params[sc->sc_normi].cap_width;
556 	f->fmt.pix.height = utvfu_norm_params[sc->sc_normi].cap_height;
557 	f->fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
558 	f->fmt.pix.field = V4L2_FIELD_INTERLACED;
559 	f->fmt.pix.bytesperline = f->fmt.pix.width * 2;
560 	f->fmt.pix.sizeimage = (f->fmt.pix.bytesperline * f->fmt.pix.height);
561 	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
562 
563 	return (0);
564 }
565 
566 int
utvfu_s_fmt(void * v,struct v4l2_format * f)567 utvfu_s_fmt(void *v, struct v4l2_format *f)
568 {
569 	if (f->fmt.pix.pixelformat != V4L2_PIX_FMT_YUYV)
570 		return (EINVAL);
571 
572 	return (0);
573 }
574 
575 int
utvfu_g_std(void * v,v4l2_std_id * norm)576 utvfu_g_std(void *v, v4l2_std_id *norm)
577 {
578 	struct utvfu_softc *sc = v;
579 
580 	*norm = utvfu_norm_params[sc->sc_normi].norm;
581 
582 	return (0);
583 }
584 
585 int
utvfu_s_std(void * v,v4l2_std_id norm)586 utvfu_s_std(void *v, v4l2_std_id norm)
587 {
588 	int ret = EINVAL;
589 	struct utvfu_softc *sc = v;
590 
591 	if ((norm & V4L2_STD_525_60) || (norm & V4L2_STD_PAL))
592 		ret = utvfu_select_norm(sc, norm);
593 
594 	return (ret);
595 }
596 
597 int
utvfu_g_input(void * v,int * i)598 utvfu_g_input(void *v, int *i)
599 {
600 	struct utvfu_softc *sc = v;
601 
602 	*i = sc->sc_input;
603 
604 	return (0);
605 }
606 
607 int
utvfu_s_input(void * v,int i)608 utvfu_s_input(void *v, int i)
609 {
610 	return utvfu_select_input(v, i);
611 }
612 
613 /* A U D I O */
614 
615 void
utvfu_audio_decode(struct utvfu_softc * sc,int len)616 utvfu_audio_decode(struct utvfu_softc *sc, int len)
617 {
618 	uint8_t *dst, *src;
619 	int n, chunk, ncopied;
620 
621 	if (sc->sc_audio.blksize == 0)
622 		return;
623 
624 	src = KERNADDR(&sc->sc_audio.iface.xfer->dmabuf, 0);
625 	dst = sc->sc_audio.cur;
626 	ncopied = sc->sc_audio.cur - sc->sc_audio.start;
627 	/* b/c region start->end is a multiple blksize chunks */
628 	ncopied %= sc->sc_audio.blksize;
629 
630 	while (len >= UTVFU_CHUNK_SIZE) {
631 		/*
632 		 * The header, skipped here, ranges from 0xdd000000 to
633 		 * 0xdd0003ff.  The 0xdd seems to be the "magic" and
634 		 * 0x3ff masks the chunk number.
635 		 */
636 		src += UTVFU_AUDIO_HDRSIZE;
637 		chunk = UTVFU_CHUNK;
638 		while (chunk > 0) {
639 			n = min(chunk, sc->sc_audio.blksize - ncopied);
640 			memcpy(dst, src, n);
641 			dst += n;
642 			src += n;
643 			chunk -= n;
644 			ncopied += n;
645 			if (ncopied >= sc->sc_audio.blksize) {
646 				mtx_enter(&audio_lock);
647 				(*sc->sc_audio.intr)(sc->sc_audio.intr_arg);
648 				mtx_leave(&audio_lock);
649 				ncopied -= sc->sc_audio.blksize;
650 			}
651 			if (dst > sc->sc_audio.end)
652 				dst = sc->sc_audio.start;
653 		}
654 		len -= UTVFU_CHUNK_SIZE; /* _CHUNK + _AUDIO_HDRSIZE */
655 	}
656 	sc->sc_audio.cur = dst;
657 }
658 
659 int
utvfu_audio_start_chip(struct utvfu_softc * sc)660 utvfu_audio_start_chip(struct utvfu_softc *sc)
661 {
662 	static const uint16_t setup[][2] = {
663 		/* These seem to enable the device. */
664 		{ UTVFU_BASE + 0x0008, 0x0001 },
665 		{ UTVFU_BASE + 0x01d0, 0x00ff },
666 		{ UTVFU_BASE + 0x01d9, 0x0002 },
667 
668 		{ UTVFU_BASE + 0x01da, 0x0013 },
669 		{ UTVFU_BASE + 0x01db, 0x0012 },
670 		{ UTVFU_BASE + 0x01e9, 0x0002 },
671 		{ UTVFU_BASE + 0x01ec, 0x006c },
672 		{ UTVFU_BASE + 0x0294, 0x0020 },
673 		{ UTVFU_BASE + 0x0255, 0x00cf },
674 		{ UTVFU_BASE + 0x0256, 0x0020 },
675 		{ UTVFU_BASE + 0x01eb, 0x0030 },
676 		{ UTVFU_BASE + 0x027d, 0x00a6 },
677 		{ UTVFU_BASE + 0x0280, 0x0011 },
678 		{ UTVFU_BASE + 0x0281, 0x0040 },
679 		{ UTVFU_BASE + 0x0282, 0x0011 },
680 		{ UTVFU_BASE + 0x0283, 0x0040 },
681 		{ 0xf891, 0x0010 },
682 
683 		/* this sets the input from composite */
684 		{ UTVFU_BASE + 0x0284, 0x00aa },
685 	};
686 
687 	/* starting the stream */
688 	utvfu_set_regs(sc, setup, nitems(setup));
689 
690 	return (0);
691 }
692 
693 int
utvfu_audio_stop_chip(struct utvfu_softc * sc)694 utvfu_audio_stop_chip(struct utvfu_softc *sc)
695 {
696 	static const uint16_t setup[][2] = {
697 	/*
698 	 * The original windows driver sometimes sends also:
699 	 *   { UTVFU_BASE + 0x00a2, 0x0013 }
700 	 * but it seems useless and its real effects are untested at
701 	 * the moment.
702 	 */
703 		{ UTVFU_BASE + 0x027d, 0x0000 },
704 		{ UTVFU_BASE + 0x0280, 0x0010 },
705 		{ UTVFU_BASE + 0x0282, 0x0010 },
706 	};
707 
708 	utvfu_set_regs(sc, setup, nitems(setup));
709 
710 	return (0);
711 }
712 
713 /*
714  * Copyright (c) 2008 Robert Nagy <robert@openbsd.org>
715  * Copyright (c) 2008 Marcus Glocker <mglocker@openbsd.org>
716  * Copyright (c) 2016 Patrick Keshishian <patrick@boxsoft.com>
717  *
718  * Permission to use, copy, modify, and distribute this software for any
719  * purpose with or without fee is hereby granted, provided that the above
720  * copyright notice and this permission notice appear in all copies.
721  *
722  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
723  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
724  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
725  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
726  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
727  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
728  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
729  */
730 /*
731  * Heavily based on uvideo.c source.
732  */
733 
734 int		utvfu_match(struct device *, void *, void *);
735 void		utvfu_attach(struct device *, struct device *, void *);
736 int		utvfu_detach(struct device *, int);
737 
738 usbd_status	utvfu_parse_desc(struct utvfu_softc *);
739 
740 void		utvfu_vs_close(struct utvfu_softc *);
741 void		utvfu_vs_free_frame(struct utvfu_softc *);
742 void		utvfu_vs_free_isoc(struct utvfu_softc *);
743 void		utvfu_vs_start_isoc_ixfer(struct utvfu_softc *,
744 		    struct utvfu_isoc_xfer *);
745 void		utvfu_vs_cb(struct usbd_xfer *, void *, usbd_status);
746 
747 void		utvfu_vs_free(struct utvfu_softc *);
748 int		utvfu_vs_init(struct utvfu_softc *);
749 int		utvfu_vs_alloc_frame(struct utvfu_softc *);
750 usbd_status	utvfu_vs_alloc_isoc(struct utvfu_softc *);
751 
752 int		utvfu_open(void *, int, int *, uint8_t *,
753 		    void (*)(void *), void *);
754 int		utvfu_close(void *);
755 int		utvfu_querycap(void *, struct v4l2_capability *);
756 int		utvfu_enum_fmt_vid_cap(void *, struct v4l2_fmtdesc *);
757 int		utvfu_enum_fsizes(void *, struct v4l2_frmsizeenum *);
758 int		utvfu_g_fmt(void *, struct v4l2_format *);
759 int		utvfu_s_fmt(void *, struct v4l2_format *);
760 int		utvfu_g_parm(void *, struct v4l2_streamparm *);
761 int		utvfu_s_parm(void *, struct v4l2_streamparm *);
762 int		utvfu_enum_input(void *, struct v4l2_input *);
763 int		utvfu_s_input(void *, int);
764 int		utvfu_g_input(void *, int *);
765 
766 int		utvfu_reqbufs(void *, struct v4l2_requestbuffers *);
767 int		utvfu_querybuf(void *, struct v4l2_buffer *);
768 int		utvfu_qbuf(void *, struct v4l2_buffer *);
769 int		utvfu_dqbuf(void *, struct v4l2_buffer *);
770 int		utvfu_streamon(void *, int);
771 int		utvfu_streamoff(void *, int);
772 int		utvfu_queryctrl(void *, struct v4l2_queryctrl *);
773 caddr_t		utvfu_mappage(void *, off_t, int);
774 int		utvfu_get_bufsize(void *);
775 int		utvfu_start_read(void *);
776 
777 int		utvfu_as_init(struct utvfu_softc *);
778 void		utvfu_as_free(struct utvfu_softc *);
779 
780 usbd_status	utvfu_as_open(struct utvfu_softc *);
781 int		utvfu_as_alloc_bulk(struct utvfu_softc *);
782 void		utvfu_as_free_bulk(struct utvfu_softc *);
783 int		utvfu_as_start_bulk(struct utvfu_softc *);
784 void		utvfu_as_bulk_thread(void *);
785 
786 int		utvfu_audio_open(void *, int);
787 void		utvfu_audio_close(void *);
788 int		utvfu_audio_set_params(void *, int, int,
789 		    struct audio_params *, struct audio_params *);
790 int		utvfu_audio_halt_out(void *);
791 int		utvfu_audio_halt_in(void *);
792 int		utvfu_audio_mixer_set_port(void *, struct mixer_ctrl *);
793 int		utvfu_audio_mixer_get_port(void *, struct mixer_ctrl *);
794 int		utvfu_audio_query_devinfo(void *, struct mixer_devinfo *);
795 int		utvfu_audio_trigger_output(void *, void *, void *, int,
796 		    void (*)(void *), void *, struct audio_params *);
797 int		utvfu_audio_trigger_input(void *, void *, void *, int,
798 		    void (*)(void *), void *, struct audio_params *);
799 
800 struct cfdriver utvfu_cd = {
801 	NULL, "utvfu", DV_DULL
802 };
803 
804 const struct cfattach utvfu_ca = {
805 	sizeof(struct utvfu_softc),
806 	utvfu_match,
807 	utvfu_attach,
808 	utvfu_detach,
809 	NULL
810 };
811 
812 const struct video_hw_if utvfu_vid_hw_if = {
813 	utvfu_open,		/* open */
814 	utvfu_close,		/* close */
815 	utvfu_querycap,		/* VIDIOC_QUERYCAP */
816 	utvfu_enum_fmt_vid_cap,	/* VIDIOC_ENUM_FMT */
817 	utvfu_enum_fsizes,	/* VIDIOC_ENUM_FRAMESIZES */
818 	NULL,			/* VIDIOC_ENUM_FRAMEINTERVALS */
819 	utvfu_s_fmt,		/* VIDIOC_S_FMT */
820 	utvfu_g_fmt,		/* VIDIOC_G_FMT */
821 	utvfu_s_parm,		/* VIDIOC_S_PARM */
822 	utvfu_g_parm,		/* VIDIOC_G_PARM */
823 	utvfu_enum_input,	/* VIDIOC_ENUMINPUT */
824 	utvfu_s_input,		/* VIDIOC_S_INPUT */
825 	utvfu_g_input,		/* VIDIOC_G_INPUT */
826 	utvfu_reqbufs,		/* VIDIOC_REQBUFS */
827 	utvfu_querybuf,		/* VIDIOC_QUERYBUF */
828 	utvfu_qbuf,		/* VIDIOC_QBUF */
829 	utvfu_dqbuf,		/* VIDIOC_DQBUF */
830 	utvfu_streamon,		/* VIDIOC_STREAMON */
831 	utvfu_streamoff,	/* VIDIOC_STREAMOFF */
832 	NULL,			/* VIDIOC_TRY_FMT */
833 	utvfu_queryctrl,	/* VIDIOC_QUERYCTRL */
834 	NULL,			/* VIDIOC_G_CTRL */
835 	NULL,			/* VIDIOC_S_CTRL */
836 	utvfu_mappage,		/* mmap */
837 	utvfu_get_bufsize,	/* read */
838 	utvfu_start_read	/* start stream for read */
839 };
840 
841 const struct audio_hw_if utvfu_au_hw_if = {
842 	.open = utvfu_audio_open,
843 	.close = utvfu_audio_close,
844 	.set_params = utvfu_audio_set_params,
845 	.halt_output = utvfu_audio_halt_out,
846 	.halt_input = utvfu_audio_halt_in,
847 	.set_port = utvfu_audio_mixer_set_port,
848 	.get_port = utvfu_audio_mixer_get_port,
849 	.query_devinfo = utvfu_audio_query_devinfo,
850 	.trigger_output = utvfu_audio_trigger_output,
851 	.trigger_input = utvfu_audio_trigger_input,
852 };
853 
854 int
utvfu_match(struct device * parent,void * match,void * aux)855 utvfu_match(struct device *parent, void *match, void *aux)
856 {
857 	struct usb_attach_arg *uaa = aux;
858 	const struct usb_descriptor *ud;
859 	struct usbd_desc_iter iter;
860 	struct usb_interface_descriptor *uid = NULL;
861 	const struct usb_endpoint_descriptor *ued = NULL;
862 	usb_device_descriptor_t *dd;
863 	int ret = UMATCH_NONE;
864 	int nep, nalt;
865 	uint16_t psize = 0;
866 
867 	if (uaa->iface == NULL)
868 		return ret;
869 
870 	dd = usbd_get_device_descriptor(uaa->device);
871 
872 	if (UGETW(dd->idVendor) == USB_VENDOR_FUSHICAI &&
873 	    UGETW(dd->idProduct) == USB_PRODUCT_FUSHICAI_USBTV007)
874 		ret = UMATCH_VENDOR_PRODUCT;
875 	/*
876 	 * This seems like a fragile check, but the original driver ensures
877 	 * there are two alternate settings for the interface, and alternate
878 	 * setting 1 has four endpoints.
879 	 *
880 	 * Comment says "Checks that the device is what we think it is."
881 	 *
882 	 * Adding check that wMaxPacketSize for the video endpoint is > 0.
883 	 */
884 	nep = nalt = 0;
885 	usbd_desc_iter_init(uaa->device, &iter);
886 	while ((ud = usbd_desc_iter_next(&iter)) != NULL) {
887 		switch (ud->bDescriptorType) {
888 		default:
889 			break;
890 		case UDESC_INTERFACE:
891 			uid = (void *)ud;
892 			if (uid->bInterfaceNumber == 0)
893 				nalt++;
894 			break;
895 		case UDESC_ENDPOINT:
896 			if (uid->bAlternateSetting == 1) {
897 				ued = (void *)ud;
898 				if (ued->bEndpointAddress == UTVFU_VIDEO_ENDP)
899 					psize = UGETW(ued->wMaxPacketSize);
900 				nep++;
901 			}
902 			break;
903 		}
904 		if (uid != NULL && uid->bInterfaceNumber > 0)
905 			break;
906 	}
907 
908 	if (nalt != 2 || nep != 4 || psize == 0)
909 		ret = UMATCH_NONE;
910 
911 	return (ret);
912 }
913 
914 void
utvfu_attach(struct device * parent,struct device * self,void * aux)915 utvfu_attach(struct device *parent, struct device *self, void *aux)
916 {
917 	int i;
918 	struct utvfu_softc *sc = (struct utvfu_softc *)self;
919 	struct usb_attach_arg *uaa = aux;
920 
921 	sc->sc_udev = uaa->device;
922 	for (i = 0; i < uaa->nifaces; i++) {
923 		if (usbd_iface_claimed(sc->sc_udev, i))
924 			continue;
925 		usbd_claim_iface(sc->sc_udev, i);
926 	}
927 
928 	utvfu_parse_desc(sc);
929 
930 	/* init mmap queue */
931 	SIMPLEQ_INIT(&sc->sc_mmap_q);
932 	sc->sc_mmap_count = 0;
933 
934 	sc->sc_max_frame_sz = utvfu_max_frame_size();
935 
936 	/* calculate optimal isoc xfer size */
937 	sc->sc_nframes = (sc->sc_max_frame_sz + sc->sc_iface.psize - 1)
938 	    / sc->sc_iface.psize;
939 	if (sc->sc_nframes > UTVFU_NFRAMES_MAX)
940 		sc->sc_nframes = UTVFU_NFRAMES_MAX;
941 	DPRINTF(1, "%s: nframes=%d\n", DEVNAME(sc), sc->sc_nframes);
942 
943 	rw_init(&sc->sc_audio.rwlock, "audiorwl");
944 
945 	sc->sc_audiodev = audio_attach_mi(&utvfu_au_hw_if, sc, NULL, &sc->sc_dev);
946 	sc->sc_videodev = video_attach_mi(&utvfu_vid_hw_if, sc, &sc->sc_dev);
947 }
948 
949 int
utvfu_detach(struct device * self,int flags)950 utvfu_detach(struct device *self, int flags)
951 {
952 	struct utvfu_softc *sc = (struct utvfu_softc *)self;
953 	int rv = 0;
954 
955 	/* Wait for outstanding requests to complete */
956 	usbd_delay_ms(sc->sc_udev, UTVFU_NFRAMES_MAX); /* XXX meh? */
957 
958 	if (sc->sc_videodev != NULL)
959 		rv = config_detach(sc->sc_videodev, flags);
960 
961 	if (sc->sc_audiodev != NULL)
962 		rv += config_detach(sc->sc_audiodev, flags);
963 
964 	utvfu_as_free(sc);
965 	utvfu_vs_free(sc);
966 
967 	sc->sc_flags = 0;
968 
969 	return (rv);
970 }
971 
972 usbd_status
utvfu_parse_desc(struct utvfu_softc * sc)973 utvfu_parse_desc(struct utvfu_softc *sc)
974 {
975 	int nif, nep;
976 	uint32_t psize;
977 	struct usbd_desc_iter iter;
978 	const struct usb_descriptor *ud;
979 	struct usb_endpoint_descriptor *ued;
980 	struct usb_interface_descriptor *uid = NULL;
981 
982 	nif = nep = 0;
983 	usbd_desc_iter_init(sc->sc_udev, &iter);
984 	while ((ud = usbd_desc_iter_next(&iter)) != NULL) {
985 		if (ud->bDescriptorType != UDESC_INTERFACE)
986 			continue;
987 		/* looking for interface 0, alt-setting 1 */
988 		uid = (void *)ud;
989 		if (uid->bInterfaceNumber > 0)
990 			break;
991 		if (uid->bAlternateSetting == 1)
992 			break;
993 	}
994 
995 	/* this should not fail as it was ensured during match */
996 	if (uid == NULL || uid->bInterfaceNumber != 0 ||
997 	    uid->bAlternateSetting != 1) {
998 		printf("%s: no valid alternate interface found!\n",
999 		    DEVNAME(sc));
1000 		return (USBD_INVAL);
1001 	}
1002 
1003 	/* bInterfaceNumber = 0 */
1004 	sc->sc_uifaceh = &sc->sc_udev->ifaces[0];
1005 
1006 	/* looking for video endpoint to on alternate setting 1 */
1007 	while ((ud = usbd_desc_iter_next(&iter)) != NULL) {
1008 		if (ud->bDescriptorType != UDESC_ENDPOINT)
1009 			break;
1010 
1011 		ued = (void *)ud;
1012 		if (ued->bEndpointAddress != UTVFU_VIDEO_ENDP)
1013 			continue;
1014 
1015 		psize = UGETW(ued->wMaxPacketSize);
1016 		psize = UE_GET_SIZE(psize) * (1 + UE_GET_TRANS(psize));
1017 		sc->sc_iface.psize = psize;
1018 		break;
1019 	}
1020 
1021 	return (USBD_NORMAL_COMPLETION);
1022 }
1023 
1024 int
utvfu_open(void * addr,int flags,int * size,uint8_t * buffer,void (* intr)(void *),void * arg)1025 utvfu_open(void *addr, int flags, int *size, uint8_t *buffer,
1026     void (*intr)(void *), void *arg)
1027 {
1028 	struct utvfu_softc *sc = addr;
1029 	int rv;
1030 
1031 	DPRINTF(1, "%s: utvfu_open: sc=%p\n", DEVNAME(sc), sc);
1032 
1033 	if (usbd_is_dying(sc->sc_udev))
1034 		return (EIO);
1035 
1036 	if ((rv = utvfu_vs_init(sc)) != 0)
1037 		return (rv);
1038 
1039 	/* pointers to upper video layer */
1040 	sc->sc_uplayer_arg = arg;
1041 	sc->sc_uplayer_fsize = size;
1042 	sc->sc_uplayer_fbuffer = buffer;
1043 	sc->sc_uplayer_intr = intr;
1044 
1045 	sc->sc_flags &= ~UTVFU_FLAG_MMAP;
1046 
1047 	return (0);
1048 }
1049 
1050 int
utvfu_close(void * addr)1051 utvfu_close(void *addr)
1052 {
1053 	struct utvfu_softc *sc = addr;
1054 
1055 	DPRINTF(1, "%s: utvfu_close: sc=%p\n", DEVNAME(sc), sc);
1056 
1057 	/* free & clean up video stream */
1058 	utvfu_vs_free(sc);
1059 
1060 	return (0);
1061 }
1062 
1063 usbd_status
utvfu_as_open(struct utvfu_softc * sc)1064 utvfu_as_open(struct utvfu_softc *sc)
1065 {
1066 	usb_endpoint_descriptor_t *ed;
1067 	usbd_status error;
1068 
1069 	DPRINTF(1, "%s: %s\n", DEVNAME(sc), __func__);
1070 
1071 	if (sc->sc_audio.iface.pipeh != NULL) {
1072 		printf("%s: %s called while sc_audio.iface.pipeh not NULL\n",
1073 		    DEVNAME(sc), __func__);
1074 		return (USBD_INVAL);
1075 	}
1076 
1077 	ed = usbd_get_endpoint_descriptor(sc->sc_uifaceh, UTVFU_AUDIO_ENDP);
1078 	if (ed == NULL) {
1079 		printf("%s: no endpoint descriptor for AS iface\n",
1080 		    DEVNAME(sc));
1081 		return (USBD_INVAL);
1082 	}
1083 	DPRINTF(1, "%s: open pipe for ", DEVNAME(sc));
1084 	DPRINTF(1, "bEndpointAddress=0x%02x (0x%02x), wMaxPacketSize="
1085 	    "0x%04x (%d)\n",
1086 	    UE_GET_ADDR(ed->bEndpointAddress),
1087 	    UTVFU_AUDIO_ENDP,
1088 	    UGETW(ed->wMaxPacketSize),
1089 	    UE_GET_SIZE(UGETW(ed->wMaxPacketSize))
1090 	    * (1 + UE_GET_TRANS(UGETW(ed->wMaxPacketSize))));
1091 
1092 	error = usbd_open_pipe(
1093 	    sc->sc_uifaceh,
1094 	    UTVFU_AUDIO_ENDP,
1095 	    USBD_EXCLUSIVE_USE,
1096 	    &sc->sc_audio.iface.pipeh);
1097 	if (error != USBD_NORMAL_COMPLETION) {
1098 		printf("%s: could not open AS pipe: %s\n",
1099 		    DEVNAME(sc), usbd_errstr(error));
1100 	}
1101 
1102 	return (error);
1103 }
1104 
1105 usbd_status
utvfu_vs_open(struct utvfu_softc * sc)1106 utvfu_vs_open(struct utvfu_softc *sc)
1107 {
1108 	usb_endpoint_descriptor_t *ed;
1109 	usbd_status error;
1110 
1111 	DPRINTF(1, "%s: %s\n", DEVNAME(sc), __func__);
1112 
1113 	if (sc->sc_iface.pipeh != NULL) {
1114 		printf("%s: %s called while sc_iface.pipeh not NULL\n",
1115 		    DEVNAME(sc), __func__);
1116 		return (USBD_INVAL);
1117 	}
1118 
1119 	ed = usbd_get_endpoint_descriptor(sc->sc_uifaceh, UTVFU_VIDEO_ENDP);
1120 	if (ed == NULL) {
1121 		printf("%s: no endpoint descriptor for VS iface\n",
1122 		    DEVNAME(sc));
1123 		return (USBD_INVAL);
1124 	}
1125 	DPRINTF(1, "%s: open pipe for ", DEVNAME(sc));
1126 	DPRINTF(1, "bEndpointAddress=0x%02x (0x%02x), wMaxPacketSize="
1127 	    "0x%04x (%d)\n",
1128 	    UE_GET_ADDR(ed->bEndpointAddress),
1129 	    UTVFU_VIDEO_ENDP,
1130 	    UGETW(ed->wMaxPacketSize),
1131 	    sc->sc_iface.psize);
1132 
1133 	error = usbd_open_pipe(
1134 	    sc->sc_uifaceh,
1135 	    UTVFU_VIDEO_ENDP,
1136 	    USBD_EXCLUSIVE_USE,
1137 	    &sc->sc_iface.pipeh);
1138 	if (error != USBD_NORMAL_COMPLETION) {
1139 		printf("%s: could not open VS pipe: %s\n",
1140 		    DEVNAME(sc), usbd_errstr(error));
1141 	}
1142 
1143 	return (error);
1144 }
1145 
1146 void
utvfu_as_close(struct utvfu_softc * sc)1147 utvfu_as_close(struct utvfu_softc *sc)
1148 {
1149 	DPRINTF(1, "%s: %s\n", DEVNAME(sc), __func__);
1150 
1151 	CLR(sc->sc_flags, UTVFU_FLAG_AS_RUNNING);
1152 
1153 	if (sc->sc_audio.iface.pipeh != NULL) {
1154 		usbd_abort_pipe(sc->sc_audio.iface.pipeh);
1155 
1156 		usbd_ref_wait(sc->sc_udev);
1157 
1158 		usbd_close_pipe(sc->sc_audio.iface.pipeh);
1159 		sc->sc_audio.iface.pipeh = NULL;
1160 	}
1161 }
1162 
1163 void
utvfu_vs_close(struct utvfu_softc * sc)1164 utvfu_vs_close(struct utvfu_softc *sc)
1165 {
1166 	if (sc->sc_iface.pipeh != NULL) {
1167 		usbd_close_pipe(sc->sc_iface.pipeh);
1168 		sc->sc_iface.pipeh = NULL;
1169 	}
1170 
1171 	/*
1172 	 * Some devices need time to shutdown before we switch back to
1173 	 * the default interface (0).  Not doing so can leave the device
1174 	 * back in a undefined condition.
1175 	 */
1176 	usbd_delay_ms(sc->sc_udev, 100);
1177 
1178 	/* switch back to default interface (turns off cam LED) */
1179 	(void)usbd_set_interface(sc->sc_uifaceh, UTVFU_DFLT_IFACE_IDX);
1180 }
1181 
1182 void
utvfu_read(struct utvfu_softc * sc,uint8_t * buf,int len)1183 utvfu_read(struct utvfu_softc *sc, uint8_t *buf, int len)
1184 {
1185 	/*
1186 	 * Copy video frame to upper layer buffer and call
1187 	 * upper layer interrupt.
1188 	 */
1189 	*sc->sc_uplayer_fsize = len;
1190 	memcpy(sc->sc_uplayer_fbuffer, buf, len);
1191 	(*sc->sc_uplayer_intr)(sc->sc_uplayer_arg);
1192 }
1193 
1194 int
utvfu_as_start_bulk(struct utvfu_softc * sc)1195 utvfu_as_start_bulk(struct utvfu_softc *sc)
1196 {
1197 	int error;
1198 
1199 	if (ISSET(sc->sc_flags, UTVFU_FLAG_AS_RUNNING))
1200 		return (0);
1201 	if (sc->sc_audio.iface.pipeh == NULL)
1202 		return (ENXIO);
1203 
1204 	SET(sc->sc_flags, UTVFU_FLAG_AS_RUNNING);
1205 	error = kthread_create(utvfu_as_bulk_thread, sc, NULL, DEVNAME(sc));
1206 	if (error) {
1207 		CLR(sc->sc_flags, UTVFU_FLAG_AS_RUNNING);
1208 		printf("%s: can't create kernel thread!", DEVNAME(sc));
1209 	}
1210 
1211 	return (error);
1212 }
1213 
1214 void
utvfu_as_bulk_thread(void * arg)1215 utvfu_as_bulk_thread(void *arg)
1216 {
1217 	struct utvfu_softc *sc = arg;
1218 	struct utvfu_as_iface *iface;
1219 	usbd_status error;
1220 	uint32_t actlen;
1221 
1222 	DPRINTF(1, "%s %s\n", DEVNAME(sc), __func__);
1223 
1224 	iface = &sc->sc_audio.iface;
1225 	usbd_ref_incr(sc->sc_udev);
1226 	while (ISSET(sc->sc_flags, UTVFU_FLAG_AS_RUNNING)) {
1227 		usbd_setup_xfer(
1228 		    iface->xfer,
1229 		    iface->pipeh,
1230 		    0,
1231 		    NULL,
1232 		    UTVFU_AUDIO_URBSIZE,
1233 		    USBD_NO_COPY | USBD_SHORT_XFER_OK | USBD_SYNCHRONOUS,
1234 		    0,
1235 		    NULL);
1236 		error = usbd_transfer(iface->xfer);
1237 
1238 		if (error != USBD_NORMAL_COMPLETION) {
1239 			DPRINTF(1, "%s: error in bulk xfer: %s!\n",
1240 			    DEVNAME(sc), usbd_errstr(error));
1241 			break;
1242 		}
1243 
1244 		usbd_get_xfer_status(iface->xfer, NULL, NULL, &actlen,
1245 		    NULL);
1246 		DPRINTF(2, "%s: *** buffer len = %d\n", DEVNAME(sc), actlen);
1247 
1248 		rw_enter_read(&sc->sc_audio.rwlock);
1249 		utvfu_audio_decode(sc, actlen);
1250 		rw_exit_read(&sc->sc_audio.rwlock);
1251 	}
1252 
1253 	CLR(sc->sc_flags, UTVFU_FLAG_AS_RUNNING);
1254 	usbd_ref_decr(sc->sc_udev);
1255 
1256 	DPRINTF(1, "%s %s: exiting\n", DEVNAME(sc), __func__);
1257 
1258 	kthread_exit(0);
1259 }
1260 
1261 void
utvfu_vs_start_isoc(struct utvfu_softc * sc)1262 utvfu_vs_start_isoc(struct utvfu_softc *sc)
1263 {
1264 	int i;
1265 
1266 	for (i = 0; i < UTVFU_ISOC_TRANSFERS; i++)
1267 		utvfu_vs_start_isoc_ixfer(sc, &sc->sc_iface.ixfer[i]);
1268 }
1269 
1270 void
utvfu_vs_start_isoc_ixfer(struct utvfu_softc * sc,struct utvfu_isoc_xfer * ixfer)1271 utvfu_vs_start_isoc_ixfer(struct utvfu_softc *sc,
1272 	struct utvfu_isoc_xfer *ixfer)
1273 {
1274 	int i;
1275 	usbd_status error;
1276 
1277 	DPRINTF(2, "%s: %s\n", DEVNAME(sc), __func__);
1278 
1279 	if (usbd_is_dying(sc->sc_udev))
1280 		return;
1281 
1282 	for (i = 0; i < sc->sc_nframes; i++)
1283 		ixfer->size[i] = sc->sc_iface.psize;
1284 
1285 	usbd_setup_isoc_xfer(
1286 	    ixfer->xfer,
1287 	    sc->sc_iface.pipeh,
1288 	    ixfer,
1289 	    ixfer->size,
1290 	    sc->sc_nframes,
1291 	    USBD_NO_COPY | USBD_SHORT_XFER_OK,
1292 	    utvfu_vs_cb);
1293 
1294 	error = usbd_transfer(ixfer->xfer);
1295 	if (error && error != USBD_IN_PROGRESS) {
1296 		DPRINTF(1, "%s: usbd_transfer error=%s!\n",
1297 		    DEVNAME(sc), usbd_errstr(error));
1298 	}
1299 }
1300 
1301 /*
1302  * Each packet contains a number of 256-byte chunks composing the image frame.
1303  */
1304 void
utvfu_vs_cb(struct usbd_xfer * xfer,void * priv,usbd_status status)1305 utvfu_vs_cb(struct usbd_xfer *xfer, void *priv, usbd_status status)
1306 {
1307 	struct utvfu_isoc_xfer *ixfer = priv;
1308 	struct utvfu_softc *sc = ixfer->sc;
1309 	int i, off, frame_size;
1310 	uint32_t actlen;
1311 	uint8_t *frame;
1312 
1313 	DPRINTF(2, "%s: %s\n", DEVNAME(sc), __func__);
1314 
1315 	if (status != USBD_NORMAL_COMPLETION) {
1316 		DPRINTF(1, "%s: %s: %s\n", DEVNAME(sc), __func__,
1317 		    usbd_errstr(status));
1318 		return;
1319 	}
1320 	usbd_get_xfer_status(xfer, NULL, NULL, &actlen, NULL);
1321 
1322 	DPRINTF(2, "%s: *** buffer len = %d\n", DEVNAME(sc), actlen);
1323 	if (actlen == 0)
1324 		goto skip;
1325 
1326 	frame = KERNADDR(&xfer->dmabuf, 0);
1327 	for (i = 0; i < sc->sc_nframes; i++, frame += sc->sc_iface.psize) {
1328 		frame_size = ixfer->size[i];
1329 
1330 		if (frame_size == 0)
1331 			/* frame is empty */
1332 			continue;
1333 
1334 		#define	CHUNK_STRIDE	(UTVFU_CHUNK_SIZE*4)
1335 		for (off = 0; off + CHUNK_STRIDE <= frame_size;
1336 		     off += CHUNK_STRIDE) {
1337 			utvfu_image_chunk(sc, frame + off);
1338 		}
1339 		#undef	CHUNK_STRIDE
1340 	}
1341 
1342 skip:	/* setup new transfer */
1343 	utvfu_vs_start_isoc_ixfer(sc, ixfer);
1344 }
1345 
1346 int
utvfu_find_queued(struct utvfu_softc * sc)1347 utvfu_find_queued(struct utvfu_softc *sc)
1348 {
1349 	int i;
1350 
1351 	/* find a buffer which is ready for queueing */
1352 	for (i = 0; i < sc->sc_mmap_count; i++) {
1353 		if (sc->sc_mmap[i].v4l2_buf.flags & V4L2_BUF_FLAG_DONE)
1354 			continue;
1355 		if (sc->sc_mmap[i].v4l2_buf.flags & V4L2_BUF_FLAG_QUEUED)
1356 			return (i);
1357 	}
1358 
1359 	return (-1);
1360 }
1361 
1362 int
utvfu_mmap_queue(struct utvfu_softc * sc,uint8_t * buf,int len)1363 utvfu_mmap_queue(struct utvfu_softc *sc, uint8_t *buf, int len)
1364 {
1365 	int i;
1366 
1367 	if (sc->sc_mmap_count == 0 || sc->sc_mmap_buffer == NULL)
1368 		panic("%s: mmap buffers not allocated", __func__);
1369 
1370 	/* find a buffer which is ready for queueing */
1371 	if ((i = utvfu_find_queued(sc)) == -1) {
1372 		DPRINTF(2, "%s: mmap queue is full!\n", DEVNAME(sc));
1373 		return (ENOMEM);
1374 	}
1375 
1376 	/* copy frame to mmap buffer and report length */
1377 	memcpy(sc->sc_mmap[i].buf, buf, len);
1378 	sc->sc_mmap[i].v4l2_buf.bytesused = len;
1379 
1380 	/* timestamp it */
1381 	getmicrotime(&sc->sc_mmap[i].v4l2_buf.timestamp);
1382 
1383 	/* appropriately set/clear flags */
1384 	sc->sc_mmap[i].v4l2_buf.flags &= ~V4L2_BUF_FLAG_QUEUED;
1385 	sc->sc_mmap[i].v4l2_buf.flags |= V4L2_BUF_FLAG_DONE;
1386 
1387 	/* queue it */
1388 	SIMPLEQ_INSERT_TAIL(&sc->sc_mmap_q, &sc->sc_mmap[i], q_frames);
1389 	DPRINTF(2, "%s: %s: frame queued on index %d\n",
1390 	    DEVNAME(sc), __func__, i);
1391 
1392 	wakeup(sc);
1393 
1394 	/*
1395 	 * In case userland uses poll(2), signal that we have a frame
1396 	 * ready to dequeue.
1397 	 */
1398 	(*sc->sc_uplayer_intr)(sc->sc_uplayer_arg);
1399 
1400 	return (0);
1401 }
1402 
1403 caddr_t
utvfu_mappage(void * v,off_t off,int prot)1404 utvfu_mappage(void *v, off_t off, int prot)
1405 {
1406 	struct utvfu_softc *sc = v;
1407 	caddr_t p = NULL;
1408 
1409 	if (off < sc->sc_mmap_bufsz) {
1410 		if ((sc->sc_flags & UTVFU_FLAG_MMAP) == 0)
1411 			sc->sc_flags |= UTVFU_FLAG_MMAP;
1412 
1413 		p = sc->sc_mmap_buffer + off;
1414 	}
1415 
1416 	return (p);
1417 }
1418 
1419 int
utvfu_get_bufsize(void * v)1420 utvfu_get_bufsize(void *v)
1421 {
1422 	struct utvfu_softc *sc = v;
1423 
1424 	/* YUYV/YUV-422: 4 bytes/2 pixel */
1425 	return (utvfu_norm_params[sc->sc_normi].cap_width *
1426 	    utvfu_norm_params[sc->sc_normi].cap_height * 2);
1427 }
1428 
1429 int
utvfu_start_read(void * v)1430 utvfu_start_read(void *v)
1431 {
1432 	struct utvfu_softc *sc = v;
1433 	usbd_status error;
1434 
1435 	if (sc->sc_flags & UTVFU_FLAG_MMAP)
1436 		sc->sc_flags &= ~UTVFU_FLAG_MMAP;
1437 
1438 	/* open video stream pipe */
1439 	error = utvfu_vs_open(sc);
1440 	if (error != USBD_NORMAL_COMPLETION)
1441 		return (EINVAL);
1442 
1443 	utvfu_vs_start_isoc(sc);
1444 
1445 	return (0);
1446 }
1447 
1448 void
utvfu_audio_clear_client(struct utvfu_softc * sc)1449 utvfu_audio_clear_client(struct utvfu_softc *sc)
1450 {
1451 	rw_enter_write(&sc->sc_audio.rwlock);
1452 
1453 	sc->sc_audio.intr = NULL;
1454 	sc->sc_audio.intr_arg = NULL;
1455 	sc->sc_audio.start = NULL;
1456 	sc->sc_audio.end = NULL;
1457 	sc->sc_audio.cur = NULL;
1458 	sc->sc_audio.blksize = 0;
1459 
1460 	rw_exit_write(&sc->sc_audio.rwlock);
1461 }
1462 
1463 void
utvfu_as_free(struct utvfu_softc * sc)1464 utvfu_as_free(struct utvfu_softc *sc)
1465 {
1466 	DPRINTF(1, "%s: %s\n", DEVNAME(sc), __func__);
1467 
1468 	utvfu_as_close(sc);
1469 	utvfu_as_free_bulk(sc);
1470 }
1471 
1472 void
utvfu_vs_free(struct utvfu_softc * sc)1473 utvfu_vs_free(struct utvfu_softc *sc)
1474 {
1475 	DPRINTF(1, "%s: %s\n", DEVNAME(sc), __func__);
1476 	utvfu_vs_close(sc);
1477 	utvfu_vs_free_isoc(sc);
1478 	utvfu_vs_free_frame(sc);
1479 }
1480 
1481 int
utvfu_as_init(struct utvfu_softc * sc)1482 utvfu_as_init(struct utvfu_softc *sc)
1483 {
1484 	DPRINTF(1, "%s: %s\n", DEVNAME(sc), __func__);
1485 
1486 	if (sc->sc_audio.iface.xfer != NULL)
1487 		return (0);
1488 
1489 	/* allocate audio and video stream xfer buffer */
1490 	return utvfu_as_alloc_bulk(sc);
1491 }
1492 
1493 int
utvfu_vs_init(struct utvfu_softc * sc)1494 utvfu_vs_init(struct utvfu_softc *sc)
1495 {
1496 	DPRINTF(1, "%s: %s\n", DEVNAME(sc), __func__);
1497 
1498 	if (utvfu_start_capture(sc) != 0)
1499 		return (EINVAL);
1500 
1501 	if (utvfu_vs_alloc_isoc(sc) != 0 || utvfu_vs_alloc_frame(sc) != 0)
1502 		return (ENOMEM);
1503 
1504 	return (0);
1505 }
1506 
1507 int
utvfu_vs_alloc_frame(struct utvfu_softc * sc)1508 utvfu_vs_alloc_frame(struct utvfu_softc *sc)
1509 {
1510 	struct utvfu_frame_buf *fb = &sc->sc_fb;
1511 
1512 	fb->size = sc->sc_max_frame_sz;
1513 	fb->buf = malloc(fb->size, M_USBDEV, M_NOWAIT);
1514 	if (fb->buf == NULL) {
1515 		printf("%s: can't allocate frame buffer!\n", DEVNAME(sc));
1516 		return (ENOMEM);
1517 	}
1518 
1519 	DPRINTF(1, "%s: %s: allocated %d bytes frame buffer\n",
1520 	    DEVNAME(sc), __func__, fb->size);
1521 
1522 	fb->chunks_done = 0;
1523 	fb->fid = 0;
1524 	fb->last_odd = 1;
1525 
1526 	return (0);
1527 }
1528 
1529 void
utvfu_vs_free_frame(struct utvfu_softc * sc)1530 utvfu_vs_free_frame(struct utvfu_softc *sc)
1531 {
1532 	struct utvfu_frame_buf *fb = &sc->sc_fb;
1533 
1534 	if (fb->buf != NULL) {
1535 		free(fb->buf, M_USBDEV, fb->size);
1536 		fb->buf = NULL;
1537 	}
1538 
1539 	if (sc->sc_mmap_buffer != NULL) {
1540 		free(sc->sc_mmap_buffer, M_USBDEV, sc->sc_mmap_bufsz);
1541 		sc->sc_mmap_buffer = NULL;
1542 		memset(sc->sc_mmap, 0, sizeof(sc->sc_mmap));
1543 	}
1544 
1545 	while (!SIMPLEQ_EMPTY(&sc->sc_mmap_q))
1546 		SIMPLEQ_REMOVE_HEAD(&sc->sc_mmap_q, q_frames);
1547 
1548 	sc->sc_mmap_count = 0;
1549 }
1550 
1551 usbd_status
utvfu_vs_alloc_isoc(struct utvfu_softc * sc)1552 utvfu_vs_alloc_isoc(struct utvfu_softc *sc)
1553 {
1554 	int size, i;
1555 	void *buf;
1556 
1557 	DPRINTF(1, "%s: %s\n", DEVNAME(sc), __func__);
1558 
1559 	for (i = 0; i < UTVFU_ISOC_TRANSFERS; i++) {
1560 		sc->sc_iface.ixfer[i].sc = sc;
1561 		sc->sc_iface.ixfer[i].xfer = usbd_alloc_xfer(sc->sc_udev);
1562 		if (sc->sc_iface.ixfer[i].xfer == NULL) {
1563 			printf("%s: could not allocate isoc VS xfer!\n",
1564 			    DEVNAME(sc));
1565 			return (USBD_NOMEM);
1566 		}
1567 
1568 		size = sc->sc_iface.psize * sc->sc_nframes;
1569 
1570 		buf = usbd_alloc_buffer(sc->sc_iface.ixfer[i].xfer, size);
1571 		if (buf == NULL) {
1572 			printf("%s: could not allocate isoc VS buffer!\n",
1573 			    DEVNAME(sc));
1574 			return (USBD_NOMEM);
1575 		}
1576 		DPRINTF(1, "%s: allocated %d bytes isoc VS xfer buffer\n",
1577 		    DEVNAME(sc), size);
1578 	}
1579 
1580 	return (USBD_NORMAL_COMPLETION);
1581 }
1582 
1583 int
utvfu_as_alloc_bulk(struct utvfu_softc * sc)1584 utvfu_as_alloc_bulk(struct utvfu_softc *sc)
1585 {
1586 	struct usbd_xfer *xfer;
1587 
1588 	xfer = usbd_alloc_xfer(sc->sc_udev);
1589 	if (xfer == NULL) {
1590 		printf("%s: could not allocate bulk AUDIO xfer!\n",
1591 		    DEVNAME(sc));
1592 		return (ENOMEM);
1593 	}
1594 
1595 	if (usbd_alloc_buffer(xfer, UTVFU_AUDIO_URBSIZE) == NULL) {
1596 		usbd_free_xfer(xfer);
1597 		printf("%s: could not allocate bulk AUDIO buffer!\n",
1598 		    DEVNAME(sc));
1599 		return (ENOMEM);
1600 	}
1601 	DPRINTF(1, "%s: allocated %d bytes bulk AUDIO xfer buffer\n",
1602 	    DEVNAME(sc), UTVFU_AUDIO_URBSIZE);
1603 
1604 	sc->sc_audio.iface.xfer = xfer;
1605 
1606 	return (0);
1607 }
1608 
1609 void
utvfu_vs_free_isoc(struct utvfu_softc * sc)1610 utvfu_vs_free_isoc(struct utvfu_softc *sc)
1611 {
1612 	int i;
1613 
1614 	DPRINTF(1, "%s: %s\n", DEVNAME(sc), __func__);
1615 
1616 	for (i = 0; i < UTVFU_ISOC_TRANSFERS; i++) {
1617 		if (sc->sc_iface.ixfer[i].xfer != NULL) {
1618 			usbd_free_xfer(sc->sc_iface.ixfer[i].xfer);
1619 			sc->sc_iface.ixfer[i].xfer = NULL;
1620 		}
1621 	}
1622 }
1623 
1624 void
utvfu_as_free_bulk(struct utvfu_softc * sc)1625 utvfu_as_free_bulk(struct utvfu_softc *sc)
1626 {
1627 	DPRINTF(1, "%s: %s\n", DEVNAME(sc), __func__);
1628 
1629 	if (sc->sc_audio.iface.xfer != NULL) {
1630 		usbd_free_xfer(sc->sc_audio.iface.xfer);
1631 		sc->sc_audio.iface.xfer = NULL;
1632 	}
1633 }
1634 
1635 int
utvfu_reqbufs(void * v,struct v4l2_requestbuffers * rb)1636 utvfu_reqbufs(void *v, struct v4l2_requestbuffers *rb)
1637 {
1638 	struct utvfu_softc *sc = v;
1639 	int i;
1640 
1641 	DPRINTF(1, "%s: %s: count=%d\n", DEVNAME(sc), __func__, rb->count);
1642 
1643 	/* We do not support freeing buffers via reqbufs(0) */
1644 	if (rb->count == 0)
1645 		return (EINVAL);
1646 
1647 	if (sc->sc_mmap_count > 0 || sc->sc_mmap_buffer != NULL) {
1648 		DPRINTF(1, "%s: %s: mmap buffers already allocated\n",
1649 		    DEVNAME(sc), __func__);
1650 		return (EINVAL);
1651 	}
1652 
1653 	/* limit the buffers */
1654 	if (rb->count > UTVFU_MAX_BUFFERS)
1655 		sc->sc_mmap_count = UTVFU_MAX_BUFFERS;
1656 	else
1657 		sc->sc_mmap_count = rb->count;
1658 
1659 	/* allocate the total mmap buffer */
1660 	sc->sc_mmap_bufsz = sc->sc_max_frame_sz;
1661 	if (INT_MAX / sc->sc_mmap_count < sc->sc_max_frame_sz) /* overflow */
1662 		return (ENOMEM);
1663 	sc->sc_mmap_bufsz *= sc->sc_mmap_count;
1664 	sc->sc_mmap_bufsz = round_page(sc->sc_mmap_bufsz); /* page align */
1665 	sc->sc_mmap_buffer = malloc(sc->sc_mmap_bufsz, M_USBDEV, M_NOWAIT);
1666 	if (sc->sc_mmap_buffer == NULL) {
1667 		printf("%s: can't allocate mmap buffer!\n", DEVNAME(sc));
1668 		return (ENOMEM);
1669 	}
1670 	DPRINTF(1, "%s: allocated %d bytes mmap buffer\n",
1671 	    DEVNAME(sc), sc->sc_mmap_bufsz);
1672 
1673 	/* fill the v4l2_buffer structure */
1674 	for (i = 0; i < sc->sc_mmap_count; i++) {
1675 		sc->sc_mmap[i].buf = sc->sc_mmap_buffer
1676 		    + (i * sc->sc_max_frame_sz);
1677 		sc->sc_mmap[i].v4l2_buf.index = i;
1678 		sc->sc_mmap[i].v4l2_buf.m.offset = i * sc->sc_max_frame_sz;
1679 		sc->sc_mmap[i].v4l2_buf.length = sc->sc_max_frame_sz;
1680 		sc->sc_mmap[i].v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1681 		sc->sc_mmap[i].v4l2_buf.sequence = 0;
1682 		sc->sc_mmap[i].v4l2_buf.field = V4L2_FIELD_NONE;
1683 		sc->sc_mmap[i].v4l2_buf.memory = V4L2_MEMORY_MMAP;
1684 		sc->sc_mmap[i].v4l2_buf.flags = V4L2_BUF_FLAG_MAPPED;
1685 
1686 		DPRINTF(1, "%s: %s: index=%d, offset=%d, length=%d\n",
1687 		    DEVNAME(sc), __func__,
1688 		    sc->sc_mmap[i].v4l2_buf.index,
1689 		    sc->sc_mmap[i].v4l2_buf.m.offset,
1690 		    sc->sc_mmap[i].v4l2_buf.length);
1691 	}
1692 
1693 	/* tell how many buffers we have really allocated */
1694 	rb->count = sc->sc_mmap_count;
1695 
1696 	rb->capabilities = V4L2_BUF_CAP_SUPPORTS_MMAP;
1697 
1698 	return (0);
1699 }
1700 
1701 int
utvfu_querybuf(void * v,struct v4l2_buffer * qb)1702 utvfu_querybuf(void *v, struct v4l2_buffer *qb)
1703 {
1704 	struct utvfu_softc *sc = v;
1705 
1706 	if (qb->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1707 	    qb->memory != V4L2_MEMORY_MMAP ||
1708 	    qb->index >= sc->sc_mmap_count)
1709 		return (EINVAL);
1710 
1711 	memcpy(qb, &sc->sc_mmap[qb->index].v4l2_buf,
1712 	    sizeof(struct v4l2_buffer));
1713 
1714 	DPRINTF(1, "%s: %s: index=%d, offset=%d, length=%d\n",
1715 	    DEVNAME(sc), __func__, qb->index, qb->m.offset, qb->length);
1716 
1717 	return (0);
1718 }
1719 
1720 int
utvfu_qbuf(void * v,struct v4l2_buffer * qb)1721 utvfu_qbuf(void *v, struct v4l2_buffer *qb)
1722 {
1723 	struct utvfu_softc *sc = v;
1724 
1725 	if (qb->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1726 	    qb->memory != V4L2_MEMORY_MMAP ||
1727 	    qb->index >= sc->sc_mmap_count)
1728 		return (EINVAL);
1729 
1730 	sc->sc_mmap[qb->index].v4l2_buf.flags &= ~V4L2_BUF_FLAG_DONE;
1731 	sc->sc_mmap[qb->index].v4l2_buf.flags |= V4L2_BUF_FLAG_MAPPED;
1732 	sc->sc_mmap[qb->index].v4l2_buf.flags |= V4L2_BUF_FLAG_QUEUED;
1733 
1734 	DPRINTF(2, "%s: %s: buffer on index %d ready for queueing\n",
1735 	    DEVNAME(sc), __func__, qb->index);
1736 
1737 	return (0);
1738 }
1739 
1740 int
utvfu_dqbuf(void * v,struct v4l2_buffer * dqb)1741 utvfu_dqbuf(void *v, struct v4l2_buffer *dqb)
1742 {
1743 	struct utvfu_softc *sc = v;
1744 	struct utvfu_mmap *mmap;
1745 	int error;
1746 
1747 	if (dqb->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1748 	    dqb->memory != V4L2_MEMORY_MMAP)
1749 		return (EINVAL);
1750 
1751 	if (SIMPLEQ_EMPTY(&sc->sc_mmap_q)) {
1752 		/* mmap queue is empty, block until first frame is queued */
1753 		error = tsleep_nsec(sc, 0, "vid_mmap", SEC_TO_NSEC(10));
1754 		if (error)
1755 			return (EINVAL);
1756 	}
1757 
1758 	mmap = SIMPLEQ_FIRST(&sc->sc_mmap_q);
1759 	if (mmap == NULL)
1760 		panic("utvfu_dqbuf: NULL pointer!");
1761 
1762 	memcpy(dqb, &mmap->v4l2_buf, sizeof(struct v4l2_buffer));
1763 
1764 	mmap->v4l2_buf.flags &= ~(V4L2_BUF_FLAG_DONE|V4L2_BUF_FLAG_QUEUED);
1765 	mmap->v4l2_buf.flags |= V4L2_BUF_FLAG_MAPPED;
1766 
1767 	DPRINTF(2, "%s: %s: frame dequeued from index %d\n",
1768 	    DEVNAME(sc), __func__, mmap->v4l2_buf.index);
1769 	SIMPLEQ_REMOVE_HEAD(&sc->sc_mmap_q, q_frames);
1770 
1771 	return (0);
1772 }
1773 
1774 int
utvfu_streamon(void * v,int type)1775 utvfu_streamon(void *v, int type)
1776 {
1777 	struct utvfu_softc *sc = v;
1778 	usbd_status error;
1779 
1780 	/* open video stream pipe */
1781 	error = utvfu_vs_open(sc);
1782 	if (error != USBD_NORMAL_COMPLETION)
1783 		return (EINVAL);
1784 
1785 	utvfu_vs_start_isoc(sc);
1786 
1787 	return (0);
1788 }
1789 
1790 int
utvfu_streamoff(void * v,int type)1791 utvfu_streamoff(void *v, int type)
1792 {
1793 	utvfu_vs_close(v);
1794 
1795 	return (0);
1796 }
1797 
1798 int
utvfu_queryctrl(void * v,struct v4l2_queryctrl * qctrl)1799 utvfu_queryctrl(void *v, struct v4l2_queryctrl *qctrl)
1800 {
1801 	qctrl->flags = V4L2_CTRL_FLAG_DISABLED;
1802 
1803 	return (0);
1804 }
1805 
1806 int
utvfu_g_parm(void * v,struct v4l2_streamparm * parm)1807 utvfu_g_parm(void *v, struct v4l2_streamparm *parm)
1808 {
1809 	struct utvfu_softc *sc = v;
1810 
1811 	if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1812 		return (EINVAL);
1813 
1814 	/*
1815 	 * XXX Unsure whether there is a way to negotiate this with the
1816 	 * device, but returning 0 will allow xenocara's video to run
1817 	 */
1818 	switch (utvfu_norm_params[sc->sc_normi].norm) {
1819 	default:
1820 		return (EINVAL);
1821 	case V4L2_STD_525_60:
1822 		parm->parm.capture.capability = V4L2_CAP_TIMEPERFRAME;
1823 		parm->parm.capture.capturemode = 0;
1824 		parm->parm.capture.timeperframe.numerator = 30;
1825 		parm->parm.capture.timeperframe.denominator = 1;
1826 		break;
1827 	case V4L2_STD_PAL:
1828 		parm->parm.capture.capability = V4L2_CAP_TIMEPERFRAME;
1829 		parm->parm.capture.capturemode = 0;
1830 		parm->parm.capture.timeperframe.numerator = 25;
1831 		parm->parm.capture.timeperframe.denominator = 1;
1832 		break;
1833 	}
1834 
1835 	return (0);
1836 }
1837 
1838 int
utvfu_s_parm(void * v,struct v4l2_streamparm * parm)1839 utvfu_s_parm(void *v, struct v4l2_streamparm *parm)
1840 {
1841 	if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1842 		return (EINVAL);
1843 
1844 	return (0);
1845 }
1846 
1847 /*
1848  * A U D I O   O P S
1849  */
1850 
1851 int
utvfu_audio_open(void * v,int flags)1852 utvfu_audio_open(void *v, int flags)
1853 {
1854 	struct utvfu_softc *sc = v;
1855 
1856 	if (usbd_is_dying(sc->sc_udev))
1857 		return (EIO);
1858 
1859 	if ((flags & FWRITE))
1860 		return (ENXIO);
1861 
1862 	if (ISSET(sc->sc_flags, UTVFU_FLAG_AS_RUNNING))
1863 		return (EBUSY);
1864 
1865 	return utvfu_as_init(sc);
1866 }
1867 
1868 void
utvfu_audio_close(void * v)1869 utvfu_audio_close(void *v)
1870 {
1871 	struct utvfu_softc *sc = v;
1872 
1873 	DPRINTF(1, "%s: %s\n", DEVNAME(sc), __func__);
1874 
1875 	utvfu_audio_stop(sc);
1876 	utvfu_audio_clear_client(sc);
1877 }
1878 
1879 int
utvfu_audio_set_params(void * v,int setmode,int usemode,struct audio_params * play,struct audio_params * rec)1880 utvfu_audio_set_params(void *v, int setmode, int usemode,
1881     struct audio_params *play, struct audio_params *rec)
1882 {
1883 	struct utvfu_softc *sc = v;
1884 
1885 	if (usbd_is_dying(sc->sc_udev))
1886 		return (EIO);
1887 
1888 	DPRINTF(1, "%s %s\n", DEVNAME(sc), __func__);
1889 
1890 	/* XXX ? */
1891 	play->sample_rate = 0;
1892 	play->encoding = AUDIO_ENCODING_NONE;
1893 
1894 	rec->sample_rate = 48000;
1895 	rec->encoding = AUDIO_ENCODING_SLINEAR_LE;
1896 	rec->precision = 16;
1897 	rec->bps = 2;
1898 	rec->msb = 1;
1899 	rec->channels = 2;
1900 
1901 	return (0);
1902 }
1903 
1904 int
utvfu_audio_halt_out(void * v)1905 utvfu_audio_halt_out(void *v)
1906 {
1907 	return (EIO);
1908 }
1909 
1910 int
utvfu_audio_halt_in(void * v)1911 utvfu_audio_halt_in(void *v)
1912 {
1913 	struct utvfu_softc *sc = v;
1914 
1915 	if (usbd_is_dying(sc->sc_udev))
1916 		return (EIO);
1917 
1918 	DPRINTF(1, "%s: %s\n", DEVNAME(sc), __func__);
1919 
1920 	utvfu_audio_stop(sc);
1921 	utvfu_audio_clear_client(sc);
1922 
1923 	return (0);
1924 }
1925 
1926 int
utvfu_audio_mixer_set_port(void * v,struct mixer_ctrl * cp)1927 utvfu_audio_mixer_set_port(void *v, struct mixer_ctrl *cp)
1928 {
1929 	struct utvfu_softc *sc = v;
1930 
1931 	if (usbd_is_dying(sc->sc_udev))
1932 		return (EIO);
1933 
1934 	DPRINTF(1, "%s %s\n", DEVNAME(sc), __func__);
1935 
1936 	if (cp->type != AUDIO_MIXER_ENUM ||
1937 	    cp->un.ord < 0 || cp->un.ord > 1)
1938 		return (EINVAL);
1939 
1940 	/* XXX TODO */
1941 
1942 	DPRINTF(1, "%s %s: cp->un.ord=%d\n", DEVNAME(sc), __func__, cp->un.ord);
1943 
1944 	return (0);
1945 }
1946 
1947 int
utvfu_audio_mixer_get_port(void * v,struct mixer_ctrl * cp)1948 utvfu_audio_mixer_get_port(void *v, struct mixer_ctrl *cp)
1949 {
1950 	struct utvfu_softc *sc = v;
1951 
1952 	if (usbd_is_dying(sc->sc_udev))
1953 		return (EIO);
1954 
1955 	DPRINTF(1, "%s %s\n", DEVNAME(sc), __func__);
1956 
1957 	if (cp->type != AUDIO_MIXER_ENUM ||
1958 	    cp->un.ord < 0 || cp->un.ord > 1)
1959 		return (EINVAL);
1960 
1961 	/* XXX TODO */
1962 
1963 	DPRINTF(1, "%s %s: cp->un.ord=%d\n", DEVNAME(sc), __func__, cp->un.ord);
1964 
1965 	return (0);
1966 }
1967 
1968 int
utvfu_audio_query_devinfo(void * v,struct mixer_devinfo * mi)1969 utvfu_audio_query_devinfo(void *v, struct mixer_devinfo *mi)
1970 {
1971 	struct utvfu_softc *sc = v;
1972 
1973 	if (usbd_is_dying(sc->sc_udev))
1974 		return (EIO);
1975 
1976 	DPRINTF(1, "%s %s\n", DEVNAME(sc), __func__);
1977 
1978 	if (mi->index != 0)
1979 		return (EINVAL);
1980 
1981 	/* XXX SOMEONE WITH AUDIO EXPERTIZE NEEDS TO HELP HERE */
1982 	strlcpy(mi->label.name, "mix0-i0", sizeof(mi->label.name));
1983 	mi->type = AUDIO_MIXER_ENUM;
1984 	mi->un.e.num_mem = 2;
1985 	mi->un.e.member[0].ord = 0;
1986 	strlcpy(mi->un.e.member[0].label.name, AudioNoff,
1987 	    sizeof(mi->un.e.member[0].label.name));
1988 	mi->un.e.member[1].ord = 1;
1989 	strlcpy(mi->un.e.member[1].label.name, AudioNon,
1990 	    sizeof(mi->un.e.member[1].label.name));
1991 
1992 	return (0);
1993 }
1994 
1995 int
utvfu_audio_trigger_output(void * v,void * start,void * end,int blksize,void (* intr)(void *),void * arg,struct audio_params * param)1996 utvfu_audio_trigger_output(void *v, void *start, void *end, int blksize,
1997     void (*intr)(void *), void *arg, struct audio_params *param)
1998 {
1999 	return (EIO);
2000 }
2001 
2002 int
utvfu_audio_trigger_input(void * v,void * start,void * end,int blksize,void (* intr)(void *),void * arg,struct audio_params * param)2003 utvfu_audio_trigger_input(void *v, void *start, void *end, int blksize,
2004     void (*intr)(void *), void *arg, struct audio_params *param)
2005 {
2006 	struct utvfu_softc *sc = v;
2007 
2008 	if (usbd_is_dying(sc->sc_udev))
2009 		return (EIO);
2010 
2011 	rw_enter_write(&sc->sc_audio.rwlock);
2012 
2013 	sc->sc_audio.intr_arg = arg;
2014 	sc->sc_audio.intr = intr;
2015 	sc->sc_audio.start = start;
2016 	sc->sc_audio.end = end;
2017 	sc->sc_audio.cur = start;
2018 	sc->sc_audio.blksize = blksize;
2019 
2020 	rw_exit_write(&sc->sc_audio.rwlock);
2021 
2022 	DPRINTF(1, "%s %s: start=%p end=%p diff=%lu blksize=%d\n",
2023 	    DEVNAME(sc), __func__, start, end,
2024 	    ((u_char *)end - (u_char *)start), blksize);
2025 
2026 	return utvfu_audio_start(sc);
2027 }
2028 
2029 int
utvfu_audio_start(struct utvfu_softc * sc)2030 utvfu_audio_start(struct utvfu_softc *sc)
2031 {
2032 	DPRINTF(1, "%s: %s\n", DEVNAME(sc), __func__);
2033 
2034 	if (ISSET(sc->sc_flags, UTVFU_FLAG_AS_RUNNING))
2035 		return (0);
2036 
2037 	utvfu_audio_start_chip(sc);
2038 
2039 	if (utvfu_as_init(sc) != 0)
2040 		return (ENOMEM);
2041 	if (sc->sc_audio.iface.pipeh == NULL) {
2042 		if (utvfu_as_open(sc) != USBD_NORMAL_COMPLETION)
2043 			return (ENOMEM);
2044 	}
2045 
2046 	return utvfu_as_start_bulk(sc);
2047 }
2048 
2049 int
utvfu_audio_stop(struct utvfu_softc * sc)2050 utvfu_audio_stop(struct utvfu_softc *sc)
2051 {
2052 	DPRINTF(1, "%s: %s\n", DEVNAME(sc), __func__);
2053 
2054 	utvfu_audio_stop_chip(sc);
2055 	utvfu_as_free(sc);
2056 
2057 	return (0);
2058 }
2059