Fix issue 1) not recognizes some usb device, 2) reconnect when ffmpeg encoder error
[rtmpclient.git] / app / src / main / jni / libuvc-0.0.6 / src / device.c
1 /*********************************************************************
2 * Software License Agreement (BSD License)
3 *
4 *  Copyright (C) 2010-2012 Ken Tossell
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 *
11 *   * Redistributions of source code must retain the above copyright
12 *     notice, this list of conditions and the following disclaimer.
13 *   * Redistributions in binary form must reproduce the above
14 *     copyright notice, this list of conditions and the following
15 *     disclaimer in the documentation and/or other materials provided
16 *     with the distribution.
17 *   * Neither the name of the author nor other contributors may be
18 *     used to endorse or promote products derived from this software
19 *     without specific prior written permission.
20 *
21 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 *  POSSIBILITY OF SUCH DAMAGE.
33 *********************************************************************/
34 /**
35  * @defgroup device Device handling and enumeration
36  * @brief Support for finding, inspecting and opening UVC devices
37  */
38
39 #include "libuvc/libuvc.h"
40 #include "libuvc/libuvc_internal.h"
41
42 int uvc_already_open(uvc_context_t *ctx, struct libusb_device *usb_dev);
43 void uvc_free_devh(uvc_device_handle_t *devh);
44
45 uvc_error_t uvc_get_device_info(uvc_device_t *dev, uvc_device_info_t **info);
46 void uvc_free_device_info(uvc_device_info_t *info);
47
48 uvc_error_t uvc_scan_control(uvc_device_t *dev, uvc_device_info_t *info);
49 uvc_error_t uvc_parse_vc(uvc_device_t *dev,
50                          uvc_device_info_t *info,
51                          const unsigned char *block, size_t block_size);
52 uvc_error_t uvc_parse_vc_selector_unit(uvc_device_t *dev,
53                                         uvc_device_info_t *info,
54                                         const unsigned char *block, size_t block_size);
55 uvc_error_t uvc_parse_vc_extension_unit(uvc_device_t *dev,
56                                         uvc_device_info_t *info,
57                                         const unsigned char *block,
58                                         size_t block_size);
59 uvc_error_t uvc_parse_vc_header(uvc_device_t *dev,
60                                 uvc_device_info_t *info,
61                                 const unsigned char *block, size_t block_size);
62 uvc_error_t uvc_parse_vc_input_terminal(uvc_device_t *dev,
63                                         uvc_device_info_t *info,
64                                         const unsigned char *block,
65                                         size_t block_size);
66 uvc_error_t uvc_parse_vc_processing_unit(uvc_device_t *dev,
67                                          uvc_device_info_t *info,
68                                          const unsigned char *block,
69                                          size_t block_size);
70
71 uvc_error_t uvc_scan_streaming(uvc_device_t *dev,
72                                uvc_device_info_t *info,
73                                int interface_idx);
74 uvc_error_t uvc_parse_vs(uvc_device_t *dev,
75                          uvc_device_info_t *info,
76                          uvc_streaming_interface_t *stream_if,
77                          const unsigned char *block, size_t block_size);
78 uvc_error_t uvc_parse_vs_format_uncompressed(uvc_streaming_interface_t *stream_if,
79                                              const unsigned char *block,
80                                              size_t block_size);
81 uvc_error_t uvc_parse_vs_format_mjpeg(uvc_streaming_interface_t *stream_if,
82                                              const unsigned char *block,
83                                              size_t block_size);
84 uvc_error_t uvc_parse_vs_frame_uncompressed(uvc_streaming_interface_t *stream_if,
85                                             const unsigned char *block,
86                                             size_t block_size);
87 uvc_error_t uvc_parse_vs_frame_format(uvc_streaming_interface_t *stream_if,
88                                             const unsigned char *block,
89                                             size_t block_size);
90 uvc_error_t uvc_parse_vs_frame_frame(uvc_streaming_interface_t *stream_if,
91                                             const unsigned char *block,
92                                             size_t block_size);
93 uvc_error_t uvc_parse_vs_input_header(uvc_streaming_interface_t *stream_if,
94                                       const unsigned char *block,
95                                       size_t block_size);
96
97 void LIBUSB_CALL _uvc_status_callback(struct libusb_transfer *transfer);
98
99 /** @internal
100  * @brief Test whether the specified USB device has been opened as a UVC device
101  * @ingroup device
102  *
103  * @param ctx Context in which to search for the UVC device
104  * @param usb_dev USB device to find
105  * @return true if the device is open in this context
106  */
107 int uvc_already_open(uvc_context_t *ctx, struct libusb_device *usb_dev) {
108   uvc_device_handle_t *devh;
109
110   DL_FOREACH(ctx->open_devices, devh) {
111     if (usb_dev == devh->dev->usb_dev)
112       return 1;
113   }
114
115   return 0;
116 }
117
118 /** @brief Finds a camera identified by vendor, product and/or serial number
119  * @ingroup device
120  *
121  * @param[in] ctx UVC context in which to search for the camera
122  * @param[out] dev Reference to the camera, or NULL if not found
123  * @param[in] vid Vendor ID number, optional
124  * @param[in] pid Product ID number, optional
125  * @param[in] sn Serial number or NULL
126  * @return Error finding device or UVC_SUCCESS
127  */
128 uvc_error_t uvc_find_device(
129     uvc_context_t *ctx, uvc_device_t **dev,
130     int vid, int pid, const char *sn) {
131   uvc_error_t ret = UVC_SUCCESS;
132
133   uvc_device_t **list;
134   uvc_device_t *test_dev;
135   int dev_idx;
136   int found_dev;
137
138   UVC_ENTER();
139
140   ret = uvc_get_device_list(ctx, &list);
141
142   if (ret != UVC_SUCCESS) {
143     UVC_EXIT(ret);
144     return ret;
145   }
146
147   dev_idx = 0;
148   found_dev = 0;
149
150   while (!found_dev && (test_dev = list[dev_idx++]) != NULL) {
151     uvc_device_descriptor_t *desc;
152
153     if (uvc_get_device_descriptor(test_dev, &desc) != UVC_SUCCESS)
154       continue;
155
156     if ((!vid || desc->idVendor == vid)
157         && (!pid || desc->idProduct == pid)
158         && (!sn || (desc->serialNumber && !strcmp(desc->serialNumber, sn))))
159       found_dev = 1;
160
161     uvc_free_device_descriptor(desc);
162   }
163
164   if (found_dev)
165     uvc_ref_device(test_dev);
166
167   uvc_free_device_list(list, 1);
168
169   if (found_dev) {
170     *dev = test_dev;
171     UVC_EXIT(UVC_SUCCESS);
172     return UVC_SUCCESS;
173   } else {
174     UVC_EXIT(UVC_ERROR_NO_DEVICE);
175     return UVC_ERROR_NO_DEVICE;
176   }
177 }
178
179 /** @brief Finds all cameras identified by vendor, product and/or serial number
180  * @ingroup device
181  *
182  * @param[in] ctx UVC context in which to search for the camera
183  * @param[out] devs List of matching cameras
184  * @param[in] vid Vendor ID number, optional
185  * @param[in] pid Product ID number, optional
186  * @param[in] sn Serial number or NULL
187  * @return Error finding device or UVC_SUCCESS
188  */
189 uvc_error_t uvc_find_devices(
190     uvc_context_t *ctx, uvc_device_t ***devs,
191     int vid, int pid, const char *sn) {
192   uvc_error_t ret = UVC_SUCCESS;
193
194   uvc_device_t **list;
195   uvc_device_t *test_dev;
196   int dev_idx;
197   int found_dev;
198
199   uvc_device_t **list_internal;
200   int num_uvc_devices;
201
202   UVC_ENTER();
203
204   ret = uvc_get_device_list(ctx, &list);
205
206   if (ret != UVC_SUCCESS) {
207     UVC_EXIT(ret);
208     return ret;
209   }
210
211   num_uvc_devices = 0;
212   dev_idx = 0;
213   found_dev = 0;
214
215   list_internal = malloc(sizeof(*list_internal));
216   *list_internal = NULL;
217
218   while ((test_dev = list[dev_idx++]) != NULL) {
219     uvc_device_descriptor_t *desc;
220
221     if (uvc_get_device_descriptor(test_dev, &desc) != UVC_SUCCESS)
222       continue;
223
224     if ((!vid || desc->idVendor == vid)
225         && (!pid || desc->idProduct == pid)
226         && (!sn || (desc->serialNumber && !strcmp(desc->serialNumber, sn)))) {
227       found_dev = 1;
228       uvc_ref_device(test_dev);
229
230       num_uvc_devices++;
231       list_internal = realloc(list_internal, (num_uvc_devices + 1) * sizeof(*list_internal));
232
233       list_internal[num_uvc_devices - 1] = test_dev;
234       list_internal[num_uvc_devices] = NULL;
235     }
236
237     uvc_free_device_descriptor(desc);
238   }
239
240   uvc_free_device_list(list, 1);
241
242   if (found_dev) {
243     *devs = list_internal;
244     UVC_EXIT(UVC_SUCCESS);
245     return UVC_SUCCESS;
246   } else {
247     UVC_EXIT(UVC_ERROR_NO_DEVICE);
248     return UVC_ERROR_NO_DEVICE;
249   }
250 }
251
252 /** @brief Get the number of the bus to which the device is attached
253  * @ingroup device
254  */
255 uint8_t uvc_get_bus_number(uvc_device_t *dev) {
256   return libusb_get_bus_number(dev->usb_dev);
257 }
258
259 /** @brief Get the number assigned to the device within its bus
260  * @ingroup device
261  */
262 uint8_t uvc_get_device_address(uvc_device_t *dev) {
263   return libusb_get_device_address(dev->usb_dev);
264 }
265
266 /**
267  * XXX add for non-rooted Android device, >= Android7
268  * generate fake libusb_device according to specific params
269  * and set it to uvc_device_t to access UVC device on Android7 or later
270  */
271 uvc_error_t uvc_get_device_with_fd(uvc_context_t *ctx, uvc_device_t **device,
272                 int vid, int pid, const char *serial, int fd, int busnum, int devaddr) {
273
274
275         //LOGD("call libusb_get_device_with_fd");
276     UVC_DEBUG("call uvc_get_device_with_fd");
277         struct libusb_device *usb_dev = libusb_get_device_with_fd(ctx->usb_ctx, vid, pid, serial, fd, busnum, devaddr);
278
279         if (usb_dev != NULL) {
280                 *device = malloc(sizeof(uvc_device_t/* *device */));
281                 (*device)->ctx = ctx;
282                 (*device)->ref = 0;
283                 (*device)->usb_dev = usb_dev;
284 //              libusb_set_device_fd(usb_dev, fd);      // assign fd to libusb_device for non-rooted Android devices
285                 uvc_ref_device(*device);
286                 UVC_EXIT(UVC_SUCCESS);
287                 //RETURN(UVC_SUCCESS, int);
288         } else {
289         UVC_DEBUG("could not find specific device");
290                 *device = NULL;
291                 UVC_EXIT(UVC_ERROR_NO_DEVICE);
292                 //RETURN(UVC_ERROR_NO_DEVICE, int);
293         }
294 }
295
296
297 /** @brief Open a UVC device
298  * @ingroup device
299  *
300  * @param dev Device to open
301  * @param[out] devh Handle on opened device
302  * @return Error opening device or SUCCESS
303  */
304 uvc_error_t uvc_open(
305     uvc_device_t *dev,
306     uvc_device_handle_t **devh) {
307   uvc_error_t ret;
308   struct libusb_device_handle *usb_devh;
309   uvc_device_handle_t *internal_devh;
310   struct libusb_device_descriptor desc;
311
312   UVC_ENTER();
313
314   ret = libusb_open(dev->usb_dev, &usb_devh);
315   UVC_DEBUG("libusb_open() = %d", ret);
316
317   if (ret != UVC_SUCCESS) {
318     UVC_EXIT(ret);
319     return ret;
320   }
321
322   uvc_ref_device(dev);
323
324   internal_devh = calloc(1, sizeof(*internal_devh));
325   internal_devh->dev = dev;
326   internal_devh->usb_devh = usb_devh;
327
328   ret = uvc_get_device_info(dev, &(internal_devh->info));
329
330   if (ret != UVC_SUCCESS)
331     goto fail;
332
333   UVC_DEBUG("claiming control interface %d", internal_devh->info->ctrl_if.bInterfaceNumber);
334   ret = uvc_claim_if(internal_devh, internal_devh->info->ctrl_if.bInterfaceNumber);
335   if (ret != UVC_SUCCESS)
336     goto fail;
337
338   libusb_get_device_descriptor(dev->usb_dev, &desc);
339   internal_devh->is_isight = (desc.idVendor == 0x05ac && desc.idProduct == 0x8501);
340
341   if (internal_devh->info->ctrl_if.bEndpointAddress) {
342     internal_devh->status_xfer = libusb_alloc_transfer(0);
343     if (!internal_devh->status_xfer) {
344       ret = UVC_ERROR_NO_MEM;
345       goto fail;
346     }
347
348     libusb_fill_interrupt_transfer(internal_devh->status_xfer,
349                                    usb_devh,
350                                    internal_devh->info->ctrl_if.bEndpointAddress,
351                                    internal_devh->status_buf,
352                                    sizeof(internal_devh->status_buf),
353                                    _uvc_status_callback,
354                                    internal_devh,
355                                    0);
356     ret = libusb_submit_transfer(internal_devh->status_xfer);
357     UVC_DEBUG("libusb_submit_transfer() = %d", ret);
358
359     if (ret) {
360       fprintf(stderr,
361               "uvc: device has a status interrupt endpoint, but unable to read from it\n");
362       goto fail;
363     }
364   }
365
366   if (dev->ctx->own_usb_ctx && dev->ctx->open_devices == NULL) {
367     /* Since this is our first device, we need to spawn the event handler thread */
368     uvc_start_handler_thread(dev->ctx);
369   }
370
371   DL_APPEND(dev->ctx->open_devices, internal_devh);
372   *devh = internal_devh;
373
374   UVC_EXIT(ret);
375
376   return ret;
377
378  fail:
379   if ( internal_devh->info ) {
380     uvc_release_if(internal_devh, internal_devh->info->ctrl_if.bInterfaceNumber);
381   }
382   libusb_close(usb_devh);
383   uvc_unref_device(dev);
384   uvc_free_devh(internal_devh);
385
386   UVC_EXIT(ret);
387
388   return ret;
389 }
390
391 /**
392  * @internal
393  * @brief Parses the complete device descriptor for a device
394  * @ingroup device
395  * @note Free *info with uvc_free_device_info when you're done
396  *
397  * @param dev Device to parse descriptor for
398  * @param info Where to store a pointer to the new info struct
399  */
400 uvc_error_t uvc_get_device_info(uvc_device_t *dev,
401                                 uvc_device_info_t **info) {
402   uvc_error_t ret;
403   uvc_device_info_t *internal_info;
404
405   UVC_ENTER();
406
407   internal_info = calloc(1, sizeof(*internal_info));
408   if (!internal_info) {
409     UVC_EXIT(UVC_ERROR_NO_MEM);
410     return UVC_ERROR_NO_MEM;
411   }
412
413   if (libusb_get_config_descriptor(dev->usb_dev,
414                                    0,
415                                    &(internal_info->config)) != 0) {
416     free(internal_info);
417     UVC_EXIT(UVC_ERROR_IO);
418     return UVC_ERROR_IO;
419   }
420
421   ret = uvc_scan_control(dev, internal_info);
422   if (ret != UVC_SUCCESS) {
423     uvc_free_device_info(internal_info);
424     UVC_EXIT(ret);
425     return ret;
426   }
427
428   *info = internal_info;
429
430   UVC_EXIT(ret);
431   return ret;
432 }
433
434 /**
435  * @internal
436  * @brief Frees the device descriptor for a device
437  * @ingroup device
438  *
439  * @param info Which device info block to free
440  */
441 void uvc_free_device_info(uvc_device_info_t *info) {
442   uvc_input_terminal_t *input_term, *input_term_tmp;
443   uvc_processing_unit_t *proc_unit, *proc_unit_tmp;
444   uvc_extension_unit_t *ext_unit, *ext_unit_tmp;
445
446   uvc_streaming_interface_t *stream_if, *stream_if_tmp;
447   uvc_format_desc_t *format, *format_tmp;
448   uvc_frame_desc_t *frame, *frame_tmp;
449
450   UVC_ENTER();
451
452   DL_FOREACH_SAFE(info->ctrl_if.input_term_descs, input_term, input_term_tmp) {
453     DL_DELETE(info->ctrl_if.input_term_descs, input_term);
454     free(input_term);
455   }
456
457   DL_FOREACH_SAFE(info->ctrl_if.processing_unit_descs, proc_unit, proc_unit_tmp) {
458     DL_DELETE(info->ctrl_if.processing_unit_descs, proc_unit);
459     free(proc_unit);
460   }
461
462   DL_FOREACH_SAFE(info->ctrl_if.extension_unit_descs, ext_unit, ext_unit_tmp) {
463     DL_DELETE(info->ctrl_if.extension_unit_descs, ext_unit);
464     free(ext_unit);
465   }
466
467   DL_FOREACH_SAFE(info->stream_ifs, stream_if, stream_if_tmp) {
468     DL_FOREACH_SAFE(stream_if->format_descs, format, format_tmp) {
469       DL_FOREACH_SAFE(format->frame_descs, frame, frame_tmp) {
470         if (frame->intervals)
471           free(frame->intervals);
472
473         DL_DELETE(format->frame_descs, frame);
474         free(frame);
475       }
476
477       DL_DELETE(stream_if->format_descs, format);
478       free(format);
479     }
480
481     DL_DELETE(info->stream_ifs, stream_if);
482     free(stream_if);
483   }
484
485   if (info->config)
486     libusb_free_config_descriptor(info->config);
487
488   free(info);
489
490   UVC_EXIT_VOID();
491 }
492
493 /**
494  * @brief Get a descriptor that contains the general information about
495  * a device
496  * @ingroup device
497  *
498  * Free *desc with uvc_free_device_descriptor when you're done.
499  *
500  * @param dev Device to fetch information about
501  * @param[out] desc Descriptor structure
502  * @return Error if unable to fetch information, else SUCCESS
503  */
504 uvc_error_t uvc_get_device_descriptor(
505     uvc_device_t *dev,
506     uvc_device_descriptor_t **desc) {
507   uvc_device_descriptor_t *desc_internal;
508   struct libusb_device_descriptor usb_desc;
509   struct libusb_device_handle *usb_devh;
510   uvc_error_t ret;
511
512   UVC_ENTER();
513
514   ret = libusb_get_device_descriptor(dev->usb_dev, &usb_desc);
515
516   if (ret != UVC_SUCCESS) {
517     UVC_EXIT(ret);
518     return ret;
519   }
520
521   desc_internal = calloc(1, sizeof(*desc_internal));
522   desc_internal->idVendor = usb_desc.idVendor;
523   desc_internal->idProduct = usb_desc.idProduct;
524
525   if (libusb_open(dev->usb_dev, &usb_devh) == 0) {
526     unsigned char buf[64];
527
528     int bytes = libusb_get_string_descriptor_ascii(
529         usb_devh, usb_desc.iSerialNumber, buf, sizeof(buf));
530
531     if (bytes > 0)
532       desc_internal->serialNumber = strdup((const char*) buf);
533
534     bytes = libusb_get_string_descriptor_ascii(
535         usb_devh, usb_desc.iManufacturer, buf, sizeof(buf));
536
537     if (bytes > 0)
538       desc_internal->manufacturer = strdup((const char*) buf);
539
540     bytes = libusb_get_string_descriptor_ascii(
541         usb_devh, usb_desc.iProduct, buf, sizeof(buf));
542
543     if (bytes > 0)
544       desc_internal->product = strdup((const char*) buf);
545
546     libusb_close(usb_devh);
547   } else {
548     UVC_DEBUG("can't open device %04x:%04x, not fetching serial etc.",
549               usb_desc.idVendor, usb_desc.idProduct);
550   }
551
552   *desc = desc_internal;
553
554   UVC_EXIT(ret);
555   return ret;
556 }
557
558 /**
559  * @brief Frees a device descriptor created with uvc_get_device_descriptor
560  * @ingroup device
561  *
562  * @param desc Descriptor to free
563  */
564 void uvc_free_device_descriptor(
565     uvc_device_descriptor_t *desc) {
566   UVC_ENTER();
567
568   if (desc->serialNumber)
569     free((void*) desc->serialNumber);
570
571   if (desc->manufacturer)
572     free((void*) desc->manufacturer);
573
574   if (desc->product)
575     free((void*) desc->product);
576
577   free(desc);
578
579   UVC_EXIT_VOID();
580 }
581
582 /**
583  * @brief Get a list of the UVC devices attached to the system
584  * @ingroup device
585  *
586  * @note Free the list with uvc_free_device_list when you're done.
587  *
588  * @param ctx UVC context in which to list devices
589  * @param list List of uvc_device structures
590  * @return Error if unable to list devices, else SUCCESS
591  */
592 uvc_error_t uvc_get_device_list(
593     uvc_context_t *ctx,
594     uvc_device_t ***list) {
595   struct libusb_device **usb_dev_list;
596   struct libusb_device *usb_dev;
597   int num_usb_devices;
598
599   uvc_device_t **list_internal;
600   int num_uvc_devices;
601
602   /* per device */
603   int dev_idx;
604   struct libusb_config_descriptor *config;
605   struct libusb_device_descriptor desc;
606   uint8_t got_interface;
607
608   /* per interface */
609   int interface_idx;
610   const struct libusb_interface *interface;
611
612   /* per altsetting */
613   int altsetting_idx;
614   const struct libusb_interface_descriptor *if_desc;
615
616   UVC_ENTER();
617
618   num_usb_devices = libusb_get_device_list(ctx->usb_ctx, &usb_dev_list);
619
620   if (num_usb_devices < 0) {
621     UVC_EXIT(UVC_ERROR_IO);
622     return UVC_ERROR_IO;
623   }
624
625   list_internal = malloc(sizeof(*list_internal));
626   *list_internal = NULL;
627
628   num_uvc_devices = 0;
629   dev_idx = -1;
630
631   while ((usb_dev = usb_dev_list[++dev_idx]) != NULL) {
632     got_interface = 0;
633
634     if (libusb_get_config_descriptor(usb_dev, 0, &config) != 0)
635       continue;
636
637     if ( libusb_get_device_descriptor ( usb_dev, &desc ) != LIBUSB_SUCCESS )
638       continue;
639
640     for (interface_idx = 0;
641          !got_interface && interface_idx < config->bNumInterfaces;
642          ++interface_idx) {
643       interface = &config->interface[interface_idx];
644
645       for (altsetting_idx = 0;
646            !got_interface && altsetting_idx < interface->num_altsetting;
647            ++altsetting_idx) {
648         if_desc = &interface->altsetting[altsetting_idx];
649
650         // Skip TIS cameras that definitely aren't UVC even though they might
651         // look that way
652
653         if ( 0x199e == desc.idVendor && desc.idProduct  >= 0x8201 &&
654             desc.idProduct <= 0x8208 ) {
655           continue;
656         }
657
658         // Special case for Imaging Source cameras
659         /* Video, Streaming */
660         if ( 0x199e == desc.idVendor && ( 0x8101 == desc.idProduct ||
661             0x8102 == desc.idProduct ) &&
662             if_desc->bInterfaceClass == 255 &&
663             if_desc->bInterfaceSubClass == 2 ) {
664           got_interface = 1;
665         }
666
667         /* Video, Streaming */
668         if (if_desc->bInterfaceClass == 14 && if_desc->bInterfaceSubClass == 2) {
669           got_interface = 1;
670         }
671       }
672     }
673
674     libusb_free_config_descriptor(config);
675
676     if (got_interface) {
677       uvc_device_t *uvc_dev = malloc(sizeof(*uvc_dev));
678       uvc_dev->ctx = ctx;
679       uvc_dev->ref = 0;
680       uvc_dev->usb_dev = usb_dev;
681       uvc_ref_device(uvc_dev);
682
683       num_uvc_devices++;
684       list_internal = realloc(list_internal, (num_uvc_devices + 1) * sizeof(*list_internal));
685
686       list_internal[num_uvc_devices - 1] = uvc_dev;
687       list_internal[num_uvc_devices] = NULL;
688
689       UVC_DEBUG("    UVC: %d", dev_idx);
690     } else {
691       UVC_DEBUG("non-UVC: %d", dev_idx);
692     }
693   }
694
695   libusb_free_device_list(usb_dev_list, 1);
696
697   *list = list_internal;
698
699   UVC_EXIT(UVC_SUCCESS);
700   return UVC_SUCCESS;
701 }
702
703 /**
704  * @brief Frees a list of device structures created with uvc_get_device_list.
705  * @ingroup device
706  *
707  * @param list Device list to free
708  * @param unref_devices Decrement the reference counter for each device
709  * in the list, and destroy any entries that end up with zero references
710  */
711 void uvc_free_device_list(uvc_device_t **list, uint8_t unref_devices) {
712   uvc_device_t *dev;
713   int dev_idx = 0;
714
715   UVC_ENTER();
716
717   if (unref_devices) {
718     while ((dev = list[dev_idx++]) != NULL) {
719       uvc_unref_device(dev);
720     }
721   }
722
723   free(list);
724
725   UVC_EXIT_VOID();
726 }
727
728 /**
729  * @brief Get the uvc_device_t corresponding to an open device
730  * @ingroup device
731  *
732  * @note Unref the uvc_device_t when you're done with it
733  *
734  * @param devh Device handle to an open UVC device
735  */
736 uvc_device_t *uvc_get_device(uvc_device_handle_t *devh) {
737   uvc_ref_device(devh->dev);
738   return devh->dev;
739 }
740
741 /**
742  * @brief Get the underlying libusb device handle for an open device
743  * @ingroup device
744  *
745  * This can be used to access other interfaces on the same device, e.g.
746  * a webcam microphone.
747  *
748  * @note The libusb device handle is only valid while the UVC device is open;
749  * it will be invalidated upon calling uvc_close.
750  *
751  * @param devh UVC device handle to an open device
752  */
753 libusb_device_handle *uvc_get_libusb_handle(uvc_device_handle_t *devh) {
754   return devh->usb_devh;
755 }
756
757 /**
758  * @brief Get camera terminal descriptor for the open device.
759  *
760  * @note Do not modify the returned structure.
761  * @note The returned structure is part of a linked list, but iterating through
762  * it will make it no longer the camera terminal
763  *
764  * @param devh Device handle to an open UVC device
765  */
766 const uvc_input_terminal_t *uvc_get_camera_terminal(uvc_device_handle_t *devh) {
767   const uvc_input_terminal_t *term = uvc_get_input_terminals(devh);
768   while(term != NULL) {
769     if (term->wTerminalType == UVC_ITT_CAMERA) {
770       break;
771     }
772     else {
773       term = term->next;
774     }
775   }
776   return term;
777 }
778
779
780 /**
781  * @brief Get input terminal descriptors for the open device.
782  *
783  * @note Do not modify the returned structure.
784  * @note The returned structure is part of a linked list. Iterate through
785  *       it by using the 'next' pointers.
786  *
787  * @param devh Device handle to an open UVC device
788  */
789 const uvc_input_terminal_t *uvc_get_input_terminals(uvc_device_handle_t *devh) {
790   return devh->info->ctrl_if.input_term_descs;
791 }
792
793 /**
794  * @brief Get output terminal descriptors for the open device.
795  *
796  * @note Do not modify the returned structure.
797  * @note The returned structure is part of a linked list. Iterate through
798  *       it by using the 'next' pointers.
799  *
800  * @param devh Device handle to an open UVC device
801  */
802 const uvc_output_terminal_t *uvc_get_output_terminals(uvc_device_handle_t *devh) {
803   return NULL; /* @todo */
804 }
805
806 /**
807  * @brief Get selector unit descriptors for the open device.
808  *
809  * @note Do not modify the returned structure.
810  * @note The returned structure is part of a linked list. Iterate through
811  *       it by using the 'next' pointers.
812  *
813  * @param devh Device handle to an open UVC device
814  */
815 const uvc_selector_unit_t *uvc_get_selector_units(uvc_device_handle_t *devh) {
816   return devh->info->ctrl_if.selector_unit_descs;
817 }
818
819 /**
820  * @brief Get processing unit descriptors for the open device.
821  *
822  * @note Do not modify the returned structure.
823  * @note The returned structure is part of a linked list. Iterate through
824  *       it by using the 'next' pointers.
825  *
826  * @param devh Device handle to an open UVC device
827  */
828 const uvc_processing_unit_t *uvc_get_processing_units(uvc_device_handle_t *devh) {
829   return devh->info->ctrl_if.processing_unit_descs;
830 }
831
832 /**
833  * @brief Get extension unit descriptors for the open device.
834  *
835  * @note Do not modify the returned structure.
836  * @note The returned structure is part of a linked list. Iterate through
837  *       it by using the 'next' pointers.
838  *
839  * @param devh Device handle to an open UVC device
840  */
841 const uvc_extension_unit_t *uvc_get_extension_units(uvc_device_handle_t *devh) {
842   return devh->info->ctrl_if.extension_unit_descs;
843 }
844
845 /**
846  * @brief Increment the reference count for a device
847  * @ingroup device
848  *
849  * @param dev Device to reference
850  */
851 void uvc_ref_device(uvc_device_t *dev) {
852   UVC_ENTER();
853
854   dev->ref++;
855   libusb_ref_device(dev->usb_dev);
856
857   UVC_EXIT_VOID();
858 }
859
860 /**
861  * @brief Decrement the reference count for a device
862  * @ingropu device
863  * @note If the count reaches zero, the device will be discarded
864  *
865  * @param dev Device to unreference
866  */
867 void uvc_unref_device(uvc_device_t *dev) {
868   UVC_ENTER();
869
870   libusb_unref_device(dev->usb_dev);
871   dev->ref--;
872
873   if (dev->ref == 0)
874     free(dev);
875
876   UVC_EXIT_VOID();
877 }
878
879 /** @internal
880  * Claim a UVC interface, detaching the kernel driver if necessary.
881  * @ingroup device
882  *
883  * @param devh UVC device handle
884  * @param idx UVC interface index
885  */
886 uvc_error_t uvc_claim_if(uvc_device_handle_t *devh, int idx) {
887   int ret = UVC_SUCCESS;
888
889   UVC_ENTER();
890
891   if ( devh->claimed & ( 1 << idx )) {
892     fprintf ( stderr, "attempt to claim already-claimed interface %d\n", idx );
893     UVC_EXIT(ret);
894     return ret;
895   }
896
897   /* Tell libusb to detach any active kernel drivers. libusb will keep track of whether
898    * it found a kernel driver for this interface. */
899   ret = libusb_detach_kernel_driver(devh->usb_devh, idx);
900
901   if (ret == UVC_SUCCESS || ret == LIBUSB_ERROR_NOT_FOUND || ret == LIBUSB_ERROR_NOT_SUPPORTED) {
902     UVC_DEBUG("claiming interface %d", idx);
903     if (!( ret = libusb_claim_interface(devh->usb_devh, idx))) {
904       devh->claimed |= ( 1 << idx );
905     }
906   } else {
907     UVC_DEBUG("not claiming interface %d: unable to detach kernel driver (%s)",
908               idx, uvc_strerror(ret));
909   }
910
911   UVC_EXIT(ret);
912   return ret;
913 }
914
915 /** @internal
916  * Release a UVC interface.
917  * @ingroup device
918  *
919  * @param devh UVC device handle
920  * @param idx UVC interface index
921  */
922 uvc_error_t uvc_release_if(uvc_device_handle_t *devh, int idx) {
923   int ret = UVC_SUCCESS;
924
925   UVC_ENTER();
926   UVC_DEBUG("releasing interface %d", idx);
927   if (!( devh->claimed & ( 1 << idx ))) {
928     fprintf ( stderr, "attempt to release unclaimed interface %d\n", idx );
929     UVC_EXIT(ret);
930     return ret;
931   }
932
933   /* libusb_release_interface *should* reset the alternate setting to the first available,
934      but sometimes (e.g. on Darwin) it doesn't. Thus, we do it explicitly here.
935      This is needed to de-initialize certain cameras. */
936   libusb_set_interface_alt_setting(devh->usb_devh, idx, 0);
937   ret = libusb_release_interface(devh->usb_devh, idx);
938
939   if (UVC_SUCCESS == ret) {
940     devh->claimed &= ~( 1 << idx );
941     /* Reattach any kernel drivers that were disabled when we claimed this interface */
942     ret = libusb_attach_kernel_driver(devh->usb_devh, idx);
943
944     if (ret == UVC_SUCCESS) {
945       UVC_DEBUG("reattached kernel driver to interface %d", idx);
946     } else if (ret == LIBUSB_ERROR_NOT_FOUND || ret == LIBUSB_ERROR_NOT_SUPPORTED) {
947       ret = UVC_SUCCESS;  /* NOT_FOUND and NOT_SUPPORTED are OK: nothing to do */
948     } else {
949       UVC_DEBUG("error reattaching kernel driver to interface %d: %s",
950                 idx, uvc_strerror(ret));
951     }
952   }
953
954   UVC_EXIT(ret);
955   return ret;
956 }
957
958 /** @internal
959  * Find a device's VideoControl interface and process its descriptor
960  * @ingroup device
961  */
962 uvc_error_t uvc_scan_control(uvc_device_t *dev, uvc_device_info_t *info) {
963   const struct libusb_interface_descriptor *if_desc;
964   uvc_error_t parse_ret, ret;
965   int interface_idx;
966   const unsigned char *buffer;
967   size_t buffer_left, block_size;
968
969   UVC_ENTER();
970
971   ret = UVC_SUCCESS;
972   if_desc = NULL;
973
974   uvc_device_descriptor_t* dev_desc;
975   int haveTISCamera = 0;
976   uvc_get_device_descriptor ( dev, &dev_desc );
977   if ( 0x199e == dev_desc->idVendor && ( 0x8101 == dev_desc->idProduct ||
978       0x8102 == dev_desc->idProduct )) {
979     haveTISCamera = 1;
980   }
981   uvc_free_device_descriptor ( dev_desc );
982
983   for (interface_idx = 0; interface_idx < info->config->bNumInterfaces; ++interface_idx) {
984     if_desc = &info->config->interface[interface_idx].altsetting[0];
985
986     if ( haveTISCamera && if_desc->bInterfaceClass == 255 && if_desc->bInterfaceSubClass == 1) // Video, Control
987       break;
988
989     if (if_desc->bInterfaceClass == 14 && if_desc->bInterfaceSubClass == 1) // Video, Control
990       break;
991
992     if_desc = NULL;
993   }
994
995   if (if_desc == NULL) {
996     UVC_EXIT(UVC_ERROR_INVALID_DEVICE);
997     return UVC_ERROR_INVALID_DEVICE;
998   }
999
1000   info->ctrl_if.bInterfaceNumber = interface_idx;
1001   if (if_desc->bNumEndpoints != 0) {
1002     info->ctrl_if.bEndpointAddress = if_desc->endpoint[0].bEndpointAddress;
1003   }
1004
1005   buffer = if_desc->extra;
1006   buffer_left = if_desc->extra_length;
1007
1008   while (buffer_left >= 3) { // parseX needs to see buf[0,2] = length,type
1009     block_size = buffer[0];
1010     parse_ret = uvc_parse_vc(dev, info, buffer, block_size);
1011
1012     if (parse_ret != UVC_SUCCESS) {
1013       ret = parse_ret;
1014       break;
1015     }
1016
1017     buffer_left -= block_size;
1018     buffer += block_size;
1019   }
1020
1021   UVC_EXIT(ret);
1022   return ret;
1023 }
1024
1025 /** @internal
1026  * @brief Parse a VideoControl header.
1027  * @ingroup device
1028  */
1029 uvc_error_t uvc_parse_vc_header(uvc_device_t *dev,
1030                                 uvc_device_info_t *info,
1031                                 const unsigned char *block, size_t block_size) {
1032   size_t i;
1033   uvc_error_t scan_ret, ret = UVC_SUCCESS;
1034
1035   UVC_ENTER();
1036
1037   /*
1038   int uvc_version;
1039   uvc_version = (block[4] >> 4) * 1000 + (block[4] & 0x0f) * 100
1040     + (block[3] >> 4) * 10 + (block[3] & 0x0f);
1041   */
1042
1043   info->ctrl_if.bcdUVC = SW_TO_SHORT(&block[3]);
1044
1045   switch (info->ctrl_if.bcdUVC) {
1046   case 0x0100:
1047     info->ctrl_if.dwClockFrequency = DW_TO_INT(block + 7);
1048   case 0x010a:
1049     info->ctrl_if.dwClockFrequency = DW_TO_INT(block + 7);
1050   case 0x0110:
1051     break;
1052   default:
1053     UVC_EXIT(UVC_ERROR_NOT_SUPPORTED);
1054     return UVC_ERROR_NOT_SUPPORTED;
1055   }
1056
1057   for (i = 12; i < block_size; ++i) {
1058     scan_ret = uvc_scan_streaming(dev, info, block[i]);
1059     if (scan_ret != UVC_SUCCESS) {
1060       ret = scan_ret;
1061       break;
1062     }
1063   }
1064
1065   UVC_EXIT(ret);
1066   return ret;
1067 }
1068
1069 /** @internal
1070  * @brief Parse a VideoControl input terminal.
1071  * @ingroup device
1072  */
1073 uvc_error_t uvc_parse_vc_input_terminal(uvc_device_t *dev,
1074                                         uvc_device_info_t *info,
1075                                         const unsigned char *block, size_t block_size) {
1076   uvc_input_terminal_t *term;
1077   size_t i;
1078
1079   UVC_ENTER();
1080
1081   /* only supporting camera-type input terminals */
1082   if (SW_TO_SHORT(&block[4]) != UVC_ITT_CAMERA) {
1083     UVC_EXIT(UVC_SUCCESS);
1084     return UVC_SUCCESS;
1085   }
1086
1087   term = calloc(1, sizeof(*term));
1088
1089   term->bTerminalID = block[3];
1090   term->wTerminalType = SW_TO_SHORT(&block[4]);
1091   term->wObjectiveFocalLengthMin = SW_TO_SHORT(&block[8]);
1092   term->wObjectiveFocalLengthMax = SW_TO_SHORT(&block[10]);
1093   term->wOcularFocalLength = SW_TO_SHORT(&block[12]);
1094
1095   for (i = 14 + block[14]; i >= 15; --i)
1096     term->bmControls = block[i] + (term->bmControls << 8);
1097
1098   DL_APPEND(info->ctrl_if.input_term_descs, term);
1099
1100   UVC_EXIT(UVC_SUCCESS);
1101   return UVC_SUCCESS;
1102 }
1103
1104 /** @internal
1105  * @brief Parse a VideoControl processing unit.
1106  * @ingroup device
1107  */
1108 uvc_error_t uvc_parse_vc_processing_unit(uvc_device_t *dev,
1109                                          uvc_device_info_t *info,
1110                                          const unsigned char *block, size_t block_size) {
1111   uvc_processing_unit_t *unit;
1112   size_t i;
1113
1114   UVC_ENTER();
1115
1116   unit = calloc(1, sizeof(*unit));
1117   unit->bUnitID = block[3];
1118   unit->bSourceID = block[4];
1119
1120   for (i = 7 + block[7]; i >= 8; --i)
1121     unit->bmControls = block[i] + (unit->bmControls << 8);
1122
1123   DL_APPEND(info->ctrl_if.processing_unit_descs, unit);
1124
1125   UVC_EXIT(UVC_SUCCESS);
1126   return UVC_SUCCESS;
1127 }
1128
1129 /** @internal
1130  * @brief Parse a VideoControl selector unit.
1131  * @ingroup device
1132  */
1133 uvc_error_t uvc_parse_vc_selector_unit(uvc_device_t *dev,
1134                                          uvc_device_info_t *info,
1135                                          const unsigned char *block, size_t block_size) {
1136   uvc_selector_unit_t *unit;
1137
1138   UVC_ENTER();
1139
1140   unit = calloc(1, sizeof(*unit));
1141   unit->bUnitID = block[3];
1142
1143   DL_APPEND(info->ctrl_if.selector_unit_descs, unit);
1144
1145   UVC_EXIT(UVC_SUCCESS);
1146   return UVC_SUCCESS;
1147 }
1148
1149 /** @internal
1150  * @brief Parse a VideoControl extension unit.
1151  * @ingroup device
1152  */
1153 uvc_error_t uvc_parse_vc_extension_unit(uvc_device_t *dev,
1154                                         uvc_device_info_t *info,
1155                                         const unsigned char *block, size_t block_size) {
1156   uvc_extension_unit_t *unit = calloc(1, sizeof(*unit));
1157   const uint8_t *start_of_controls;
1158   int size_of_controls, num_in_pins;
1159   int i;
1160
1161   UVC_ENTER();
1162
1163   unit->bUnitID = block[3];
1164   memcpy(unit->guidExtensionCode, &block[4], 16);
1165
1166   num_in_pins = block[21];
1167   size_of_controls = block[22 + num_in_pins];
1168   start_of_controls = &block[23 + num_in_pins];
1169
1170   for (i = size_of_controls - 1; i >= 0; --i)
1171     unit->bmControls = start_of_controls[i] + (unit->bmControls << 8);
1172
1173   DL_APPEND(info->ctrl_if.extension_unit_descs, unit);
1174
1175   UVC_EXIT(UVC_SUCCESS);
1176   return UVC_SUCCESS;
1177 }
1178
1179 /** @internal
1180  * Process a single VideoControl descriptor block
1181  * @ingroup device
1182  */
1183 uvc_error_t uvc_parse_vc(
1184     uvc_device_t *dev,
1185     uvc_device_info_t *info,
1186     const unsigned char *block, size_t block_size) {
1187   int descriptor_subtype;
1188   uvc_error_t ret = UVC_SUCCESS;
1189
1190   UVC_ENTER();
1191
1192   if (block[1] != 36) { // not a CS_INTERFACE descriptor??
1193     UVC_EXIT(UVC_SUCCESS);
1194     return UVC_SUCCESS; // UVC_ERROR_INVALID_DEVICE;
1195   }
1196
1197   descriptor_subtype = block[2];
1198
1199   switch (descriptor_subtype) {
1200   case UVC_VC_HEADER:
1201     ret = uvc_parse_vc_header(dev, info, block, block_size);
1202     break;
1203   case UVC_VC_INPUT_TERMINAL:
1204     ret = uvc_parse_vc_input_terminal(dev, info, block, block_size);
1205     break;
1206   case UVC_VC_OUTPUT_TERMINAL:
1207     break;
1208   case UVC_VC_SELECTOR_UNIT:
1209     ret = uvc_parse_vc_selector_unit(dev, info, block, block_size);
1210     break;
1211   case UVC_VC_PROCESSING_UNIT:
1212     ret = uvc_parse_vc_processing_unit(dev, info, block, block_size);
1213     break;
1214   case UVC_VC_EXTENSION_UNIT:
1215     ret = uvc_parse_vc_extension_unit(dev, info, block, block_size);
1216     break;
1217   default:
1218     ret = UVC_ERROR_INVALID_DEVICE;
1219   }
1220
1221   UVC_EXIT(ret);
1222   return ret;
1223 }
1224
1225 /** @internal
1226  * Process a VideoStreaming interface
1227  * @ingroup device
1228  */
1229 uvc_error_t uvc_scan_streaming(uvc_device_t *dev,
1230                                uvc_device_info_t *info,
1231                                int interface_idx) {
1232   const struct libusb_interface_descriptor *if_desc;
1233   const unsigned char *buffer;
1234   size_t buffer_left, block_size;
1235   uvc_error_t ret, parse_ret;
1236   uvc_streaming_interface_t *stream_if;
1237
1238   UVC_ENTER();
1239
1240   ret = UVC_SUCCESS;
1241
1242   if_desc = &(info->config->interface[interface_idx].altsetting[0]);
1243   buffer = if_desc->extra;
1244   buffer_left = if_desc->extra_length;
1245
1246   stream_if = calloc(1, sizeof(*stream_if));
1247   stream_if->parent = info;
1248   stream_if->bInterfaceNumber = if_desc->bInterfaceNumber;
1249   DL_APPEND(info->stream_ifs, stream_if);
1250
1251   while (buffer_left >= 3) {
1252     block_size = buffer[0];
1253     parse_ret = uvc_parse_vs(dev, info, stream_if, buffer, block_size);
1254
1255     if (parse_ret != UVC_SUCCESS) {
1256       ret = parse_ret;
1257       break;
1258     }
1259
1260     buffer_left -= block_size;
1261     buffer += block_size;
1262   }
1263
1264   UVC_EXIT(ret);
1265   return ret;
1266 }
1267
1268 /** @internal
1269  * @brief Parse a VideoStreaming header block.
1270  * @ingroup device
1271  */
1272 uvc_error_t uvc_parse_vs_input_header(uvc_streaming_interface_t *stream_if,
1273                                       const unsigned char *block,
1274                                       size_t block_size) {
1275   UVC_ENTER();
1276
1277   stream_if->bEndpointAddress = block[6] & 0x8f;
1278   stream_if->bTerminalLink = block[8];
1279
1280   UVC_EXIT(UVC_SUCCESS);
1281   return UVC_SUCCESS;
1282 }
1283
1284 /** @internal
1285  * @brief Parse a VideoStreaming uncompressed format block.
1286  * @ingroup device
1287  */
1288 uvc_error_t uvc_parse_vs_format_uncompressed(uvc_streaming_interface_t *stream_if,
1289                                              const unsigned char *block,
1290                                              size_t block_size) {
1291   UVC_ENTER();
1292
1293   uvc_format_desc_t *format = calloc(1, sizeof(*format));
1294
1295   format->parent = stream_if;
1296   format->bDescriptorSubtype = block[2];
1297   format->bFormatIndex = block[3];
1298   //format->bmCapabilities = block[4];
1299   //format->bmFlags = block[5];
1300   memcpy(format->guidFormat, &block[5], 16);
1301   format->bBitsPerPixel = block[21];
1302   format->bDefaultFrameIndex = block[22];
1303   format->bAspectRatioX = block[23];
1304   format->bAspectRatioY = block[24];
1305   format->bmInterlaceFlags = block[25];
1306   format->bCopyProtect = block[26];
1307
1308   DL_APPEND(stream_if->format_descs, format);
1309
1310   UVC_EXIT(UVC_SUCCESS);
1311   return UVC_SUCCESS;
1312 }
1313
1314 /** @internal
1315  * @brief Parse a VideoStreaming frame format block.
1316  * @ingroup device
1317  */
1318 uvc_error_t uvc_parse_vs_frame_format(uvc_streaming_interface_t *stream_if,
1319                                              const unsigned char *block,
1320                                              size_t block_size) {
1321   UVC_ENTER();
1322
1323   uvc_format_desc_t *format = calloc(1, sizeof(*format));
1324
1325   format->parent = stream_if;
1326   format->bDescriptorSubtype = block[2];
1327   format->bFormatIndex = block[3];
1328   format->bNumFrameDescriptors = block[4];
1329   memcpy(format->guidFormat, &block[5], 16);
1330   format->bBitsPerPixel = block[21];
1331   format->bDefaultFrameIndex = block[22];
1332   format->bAspectRatioX = block[23];
1333   format->bAspectRatioY = block[24];
1334   format->bmInterlaceFlags = block[25];
1335   format->bCopyProtect = block[26];
1336   format->bVariableSize = block[27];
1337
1338   DL_APPEND(stream_if->format_descs, format);
1339
1340   UVC_EXIT(UVC_SUCCESS);
1341   return UVC_SUCCESS;
1342 }
1343
1344 /** @internal
1345  * @brief Parse a VideoStreaming MJPEG format block.
1346  * @ingroup device
1347  */
1348 uvc_error_t uvc_parse_vs_format_mjpeg(uvc_streaming_interface_t *stream_if,
1349                                              const unsigned char *block,
1350                                              size_t block_size) {
1351   UVC_ENTER();
1352
1353   uvc_format_desc_t *format = calloc(1, sizeof(*format));
1354
1355   format->parent = stream_if;
1356   format->bDescriptorSubtype = block[2];
1357   format->bFormatIndex = block[3];
1358   memcpy(format->fourccFormat, "MJPG", 4);
1359   format->bmFlags = block[5];
1360   format->bBitsPerPixel = 0;
1361   format->bDefaultFrameIndex = block[6];
1362   format->bAspectRatioX = block[7];
1363   format->bAspectRatioY = block[8];
1364   format->bmInterlaceFlags = block[9];
1365   format->bCopyProtect = block[10];
1366
1367   DL_APPEND(stream_if->format_descs, format);
1368
1369   UVC_EXIT(UVC_SUCCESS);
1370   return UVC_SUCCESS;
1371 }
1372
1373 /** @internal
1374  * @brief Parse a VideoStreaming uncompressed frame block.
1375  * @ingroup device
1376  */
1377 uvc_error_t uvc_parse_vs_frame_frame(uvc_streaming_interface_t *stream_if,
1378                                             const unsigned char *block,
1379                                             size_t block_size) {
1380   uvc_format_desc_t *format;
1381   uvc_frame_desc_t *frame;
1382
1383   const unsigned char *p;
1384   int i;
1385
1386   UVC_ENTER();
1387
1388   format = stream_if->format_descs->prev;
1389   frame = calloc(1, sizeof(*frame));
1390
1391   frame->parent = format;
1392
1393   frame->bDescriptorSubtype = block[2];
1394   frame->bFrameIndex = block[3];
1395   frame->bmCapabilities = block[4];
1396   frame->wWidth = block[5] + (block[6] << 8);
1397   frame->wHeight = block[7] + (block[8] << 8);
1398   frame->dwMinBitRate = DW_TO_INT(&block[9]);
1399   frame->dwMaxBitRate = DW_TO_INT(&block[13]);
1400   frame->dwDefaultFrameInterval = DW_TO_INT(&block[17]);
1401   frame->bFrameIntervalType = block[21];
1402   frame->dwBytesPerLine = DW_TO_INT(&block[22]);
1403
1404   if (block[21] == 0) {
1405     frame->dwMinFrameInterval = DW_TO_INT(&block[26]);
1406     frame->dwMaxFrameInterval = DW_TO_INT(&block[30]);
1407     frame->dwFrameIntervalStep = DW_TO_INT(&block[34]);
1408   } else {
1409     frame->intervals = calloc(block[21] + 1, sizeof(frame->intervals[0]));
1410     p = &block[26];
1411
1412     for (i = 0; i < block[21]; ++i) {
1413       frame->intervals[i] = DW_TO_INT(p);
1414       p += 4;
1415     }
1416     frame->intervals[block[21]] = 0;
1417   }
1418
1419   DL_APPEND(format->frame_descs, frame);
1420
1421   UVC_EXIT(UVC_SUCCESS);
1422   return UVC_SUCCESS;
1423 }
1424
1425 /** @internal
1426  * @brief Parse a VideoStreaming uncompressed frame block.
1427  * @ingroup device
1428  */
1429 uvc_error_t uvc_parse_vs_frame_uncompressed(uvc_streaming_interface_t *stream_if,
1430                                             const unsigned char *block,
1431                                             size_t block_size) {
1432   uvc_format_desc_t *format;
1433   uvc_frame_desc_t *frame;
1434
1435   const unsigned char *p;
1436   int i;
1437
1438   UVC_ENTER();
1439
1440   format = stream_if->format_descs->prev;
1441   frame = calloc(1, sizeof(*frame));
1442
1443   frame->parent = format;
1444
1445   frame->bDescriptorSubtype = block[2];
1446   frame->bFrameIndex = block[3];
1447   frame->bmCapabilities = block[4];
1448   frame->wWidth = block[5] + (block[6] << 8);
1449   frame->wHeight = block[7] + (block[8] << 8);
1450   frame->dwMinBitRate = DW_TO_INT(&block[9]);
1451   frame->dwMaxBitRate = DW_TO_INT(&block[13]);
1452   frame->dwMaxVideoFrameBufferSize = DW_TO_INT(&block[17]);
1453   frame->dwDefaultFrameInterval = DW_TO_INT(&block[21]);
1454   frame->bFrameIntervalType = block[25];
1455
1456   if (block[25] == 0) {
1457     frame->dwMinFrameInterval = DW_TO_INT(&block[26]);
1458     frame->dwMaxFrameInterval = DW_TO_INT(&block[30]);
1459     frame->dwFrameIntervalStep = DW_TO_INT(&block[34]);
1460   } else {
1461     frame->intervals = calloc(block[25] + 1, sizeof(frame->intervals[0]));
1462     p = &block[26];
1463
1464     for (i = 0; i < block[25]; ++i) {
1465       frame->intervals[i] = DW_TO_INT(p);
1466       p += 4;
1467     }
1468     frame->intervals[block[25]] = 0;
1469   }
1470
1471   DL_APPEND(format->frame_descs, frame);
1472
1473   UVC_EXIT(UVC_SUCCESS);
1474   return UVC_SUCCESS;
1475 }
1476
1477 /** @internal
1478  * Process a single VideoStreaming descriptor block
1479  * @ingroup device
1480  */
1481 uvc_error_t uvc_parse_vs(
1482     uvc_device_t *dev,
1483     uvc_device_info_t *info,
1484     uvc_streaming_interface_t *stream_if,
1485     const unsigned char *block, size_t block_size) {
1486   uvc_error_t ret;
1487   int descriptor_subtype;
1488
1489   UVC_ENTER();
1490
1491   ret = UVC_SUCCESS;
1492   descriptor_subtype = block[2];
1493
1494   switch (descriptor_subtype) {
1495   case UVC_VS_INPUT_HEADER:
1496     ret = uvc_parse_vs_input_header(stream_if, block, block_size);
1497     break;
1498   case UVC_VS_OUTPUT_HEADER:
1499     fprintf ( stderr, "unsupported descriptor subtype VS_OUTPUT_HEADER\n" );
1500     break;
1501   case UVC_VS_STILL_IMAGE_FRAME:
1502     fprintf ( stderr, "unsupported descriptor subtype VS_STILL_IMAGE_FRAME\n" );
1503     break;
1504   case UVC_VS_FORMAT_UNCOMPRESSED:
1505     ret = uvc_parse_vs_format_uncompressed(stream_if, block, block_size);
1506     break;
1507   case UVC_VS_FORMAT_MJPEG:
1508     ret = uvc_parse_vs_format_mjpeg(stream_if, block, block_size);
1509     break;
1510   case UVC_VS_FRAME_UNCOMPRESSED:
1511   case UVC_VS_FRAME_MJPEG:
1512     ret = uvc_parse_vs_frame_uncompressed(stream_if, block, block_size);
1513     break;
1514   case UVC_VS_FORMAT_MPEG2TS:
1515     fprintf ( stderr, "unsupported descriptor subtype VS_FORMAT_MPEG2TS\n" );
1516     break;
1517   case UVC_VS_FORMAT_DV:
1518     fprintf ( stderr, "unsupported descriptor subtype VS_FORMAT_DV\n" );
1519     break;
1520   case UVC_VS_COLORFORMAT:
1521     fprintf ( stderr, "unsupported descriptor subtype VS_COLORFORMAT\n" );
1522     break;
1523   case UVC_VS_FORMAT_FRAME_BASED:
1524     ret = uvc_parse_vs_frame_format ( stream_if, block, block_size );
1525     break;
1526   case UVC_VS_FRAME_FRAME_BASED:
1527     ret = uvc_parse_vs_frame_frame ( stream_if, block, block_size );
1528     break;
1529   case UVC_VS_FORMAT_STREAM_BASED:
1530     fprintf ( stderr, "unsupported descriptor subtype VS_FORMAT_STREAM_BASED\n" );
1531     break;
1532   default:
1533     /** @todo handle JPEG and maybe still frames or even DV... */
1534     //fprintf ( stderr, "unsupported descriptor subtype: %d\n",descriptor_subtype );
1535     break;
1536   }
1537
1538   UVC_EXIT(ret);
1539   return ret;
1540 }
1541
1542 /** @internal
1543  * @brief Free memory associated with a UVC device
1544  * @pre Streaming must be stopped, and threads must have died
1545  */
1546 void uvc_free_devh(uvc_device_handle_t *devh) {
1547   UVC_ENTER();
1548
1549   if (devh->info)
1550     uvc_free_device_info(devh->info);
1551
1552   if (devh->status_xfer)
1553     libusb_free_transfer(devh->status_xfer);
1554
1555   free(devh);
1556
1557   UVC_EXIT_VOID();
1558 }
1559
1560 /** @brief Close a device
1561  *
1562  * @ingroup device
1563  *
1564  * Ends any stream that's in progress.
1565  *
1566  * The device handle and frame structures will be invalidated.
1567  */
1568 void uvc_close(uvc_device_handle_t *devh) {
1569   UVC_ENTER();
1570   uvc_context_t *ctx = devh->dev->ctx;
1571
1572   if (devh->streams)
1573     uvc_stop_streaming(devh);
1574
1575   uvc_release_if(devh, devh->info->ctrl_if.bInterfaceNumber);
1576
1577   /* If we are managing the libusb context and this is the last open device,
1578    * then we need to cancel the handler thread. When we call libusb_close,
1579    * it'll cause a return from the thread's libusb_handle_events call, after
1580    * which the handler thread will check the flag we set and then exit. */
1581   if (ctx->own_usb_ctx && ctx->open_devices == devh && devh->next == NULL) {
1582     ctx->kill_handler_thread = 1;
1583     libusb_close(devh->usb_devh);
1584     pthread_join(ctx->handler_thread, NULL);
1585   } else {
1586     libusb_close(devh->usb_devh);
1587   }
1588
1589   DL_DELETE(ctx->open_devices, devh);
1590
1591   uvc_unref_device(devh->dev);
1592
1593   uvc_free_devh(devh);
1594
1595   UVC_EXIT_VOID();
1596 }
1597
1598 /** @internal
1599  * @brief Get number of open devices
1600  */
1601 size_t uvc_num_devices(uvc_context_t *ctx) {
1602   size_t count = 0;
1603
1604   uvc_device_handle_t *devh;
1605
1606   UVC_ENTER();
1607
1608   DL_FOREACH(ctx->open_devices, devh) {
1609     count++;
1610   }
1611
1612   UVC_EXIT((int) count);
1613   return count;
1614 }
1615
1616 void uvc_process_control_status(uvc_device_handle_t *devh, unsigned char *data, int len) {
1617   enum uvc_status_class status_class;
1618   uint8_t originator = 0, selector = 0, event = 0;
1619   enum uvc_status_attribute attribute = UVC_STATUS_ATTRIBUTE_UNKNOWN;
1620   void *content = NULL;
1621   size_t content_len = 0;
1622   int found_entity = 0;
1623   struct uvc_input_terminal *input_terminal;
1624   struct uvc_processing_unit *processing_unit;
1625
1626   UVC_ENTER();
1627
1628   if (len < 5) {
1629     UVC_DEBUG("Short read of VideoControl status update (%d bytes)", len);
1630     UVC_EXIT_VOID();
1631     return;
1632   }
1633
1634   originator = data[1];
1635   event = data[2];
1636   selector = data[3];
1637
1638   if (originator == 0) {
1639     UVC_DEBUG("Unhandled update from VC interface");
1640     UVC_EXIT_VOID();
1641     return;  /* @todo VideoControl virtual entity interface updates */
1642   }
1643
1644   if (event != 0) {
1645     UVC_DEBUG("Unhandled VC event %d", (int) event);
1646     UVC_EXIT_VOID();
1647     return;
1648   }
1649
1650   /* printf("bSelector: %d\n", selector); */
1651
1652   DL_FOREACH(devh->info->ctrl_if.input_term_descs, input_terminal) {
1653     if (input_terminal->bTerminalID == originator) {
1654       status_class = UVC_STATUS_CLASS_CONTROL_CAMERA;
1655       found_entity = 1;
1656       break;
1657     }
1658   }
1659
1660   if (!found_entity) {
1661     DL_FOREACH(devh->info->ctrl_if.processing_unit_descs, processing_unit) {
1662       if (processing_unit->bUnitID == originator) {
1663         status_class = UVC_STATUS_CLASS_CONTROL_PROCESSING;
1664         found_entity = 1;
1665         break;
1666       }
1667     }
1668   }
1669
1670   if (!found_entity) {
1671     UVC_DEBUG("Got status update for unknown VideoControl entity %d",
1672   (int) originator);
1673     UVC_EXIT_VOID();
1674     return;
1675   }
1676
1677   attribute = data[4];
1678   content = data + 5;
1679   content_len = len - 5;
1680
1681   UVC_DEBUG("Event: class=%d, event=%d, selector=%d, attribute=%d, content_len=%zd",
1682     status_class, event, selector, attribute, content_len);
1683
1684   if(devh->status_cb) {
1685     UVC_DEBUG("Running user-supplied status callback");
1686     devh->status_cb(status_class,
1687                     event,
1688                     selector,
1689                     attribute,
1690                     content, content_len,
1691                     devh->status_user_ptr);
1692   }
1693   
1694   UVC_EXIT_VOID();
1695 }
1696
1697 void uvc_process_streaming_status(uvc_device_handle_t *devh, unsigned char *data, int len) {
1698   
1699   UVC_ENTER();
1700
1701   if (len < 3) {
1702     UVC_DEBUG("Invalid streaming status event received.\n");
1703     UVC_EXIT_VOID();
1704     return;
1705   }
1706
1707   if (data[2] == 0) {
1708     if (len < 4) {
1709       UVC_DEBUG("Short read of status update (%d bytes)", len);
1710       UVC_EXIT_VOID();
1711       return;
1712     }
1713     UVC_DEBUG("Button (intf %u) %s len %d\n", data[1], data[3] ? "pressed" : "released", len);
1714     
1715     if(devh->button_cb) {
1716       UVC_DEBUG("Running user-supplied button callback");
1717       devh->button_cb(data[1],
1718                       data[3],
1719                       devh->button_user_ptr);
1720     }
1721   } else {
1722     UVC_DEBUG("Stream %u error event %02x %02x len %d.\n", data[1], data[2], data[3], len);
1723   }
1724
1725   UVC_EXIT_VOID();
1726 }
1727
1728 void uvc_process_status_xfer(uvc_device_handle_t *devh, struct libusb_transfer *transfer) {
1729   
1730   UVC_ENTER();
1731
1732   /* printf("Got transfer of aLen = %d\n", transfer->actual_length); */
1733
1734   if (transfer->actual_length > 0) {
1735     switch (transfer->buffer[0] & 0x0f) {
1736     case 1: /* VideoControl interface */
1737       uvc_process_control_status(devh, transfer->buffer, transfer->actual_length);
1738       break;
1739     case 2:  /* VideoStreaming interface */
1740       uvc_process_streaming_status(devh, transfer->buffer, transfer->actual_length);
1741       break;
1742     }
1743   }
1744
1745   UVC_EXIT_VOID();
1746 }
1747
1748 /** @internal
1749  * @brief Process asynchronous status updates from the device.
1750  */
1751 void LIBUSB_CALL _uvc_status_callback(struct libusb_transfer *transfer) {
1752   UVC_ENTER();
1753
1754   uvc_device_handle_t *devh = (uvc_device_handle_t *) transfer->user_data;
1755
1756   switch (transfer->status) {
1757   case LIBUSB_TRANSFER_ERROR:
1758   case LIBUSB_TRANSFER_CANCELLED:
1759   case LIBUSB_TRANSFER_NO_DEVICE:
1760     UVC_DEBUG("not processing/resubmitting, status = %d", transfer->status);
1761     UVC_EXIT_VOID();
1762     return;
1763   case LIBUSB_TRANSFER_COMPLETED:
1764     uvc_process_status_xfer(devh, transfer);
1765     break;
1766   case LIBUSB_TRANSFER_TIMED_OUT:
1767   case LIBUSB_TRANSFER_STALL:
1768   case LIBUSB_TRANSFER_OVERFLOW:
1769     UVC_DEBUG("retrying transfer, status = %d", transfer->status);
1770     break;
1771   }
1772
1773 #ifdef UVC_DEBUGGING
1774   uvc_error_t ret =
1775 #endif
1776       libusb_submit_transfer(transfer);
1777   UVC_DEBUG("libusb_submit_transfer() = %d", ret);
1778
1779   UVC_EXIT_VOID();
1780 }
1781
1782 /** @brief Set a callback function to receive status updates
1783  *
1784  * @ingroup device
1785  */
1786 void uvc_set_status_callback(uvc_device_handle_t *devh,
1787                              uvc_status_callback_t cb,
1788                              void *user_ptr) {
1789   UVC_ENTER();
1790
1791   devh->status_cb = cb;
1792   devh->status_user_ptr = user_ptr;
1793
1794   UVC_EXIT_VOID();
1795 }
1796
1797 /** @brief Set a callback function to receive button events
1798  *
1799  * @ingroup device
1800  */
1801 void uvc_set_button_callback(uvc_device_handle_t *devh,
1802                              uvc_button_callback_t cb,
1803                              void *user_ptr) {
1804   UVC_ENTER();
1805
1806   devh->button_cb = cb;
1807   devh->button_user_ptr = user_ptr;
1808
1809   UVC_EXIT_VOID();
1810 }
1811
1812 /**
1813  * @brief Get format descriptions for the open device.
1814  *
1815  * @note Do not modify the returned structure.
1816  *
1817  * @param devh Device handle to an open UVC device
1818  */
1819 const uvc_format_desc_t *uvc_get_format_descs(uvc_device_handle_t *devh) {
1820   return devh->info->stream_ifs->format_descs;
1821 }
1822