xref: /btstack/platform/libusb/hci_transport_h2_libusb.c (revision ab2c6ae4b737d5e801d3defe4117331eb244ebb7)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define __BTSTACK_FILE__ "hci_transport_h2_libusb.c"
39 
40 /*
41  *  hci_transport_usb.c
42  *
43  *  HCI Transport API implementation for USB
44  *
45  *  Created by Matthias Ringwald on 7/5/09.
46  */
47 
48 // Interface Number - Alternate Setting - suggested Endpoint Address - Endpoint Type - Suggested Max Packet Size
49 // HCI Commands 0 0 0x00 Control 8/16/32/64
50 // HCI Events   0 0 0x81 Interrupt (IN) 16
51 // ACL Data     0 0 0x82 Bulk (IN) 32/64
52 // ACL Data     0 0 0x02 Bulk (OUT) 32/64
53 // SCO Data     0 0 0x83 Isochronous (IN)
54 // SCO Data     0 0 0x03 Isochronous (Out)
55 
56 #include <stdio.h>
57 #include <strings.h>
58 #include <string.h>
59 #include <unistd.h>   /* UNIX standard function definitions */
60 #include <sys/types.h>
61 
62 #include <libusb.h>
63 
64 #include "btstack_config.h"
65 
66 #include "btstack_debug.h"
67 #include "hci.h"
68 #include "hci_transport.h"
69 
70 #if (USB_VENDOR_ID != 0) && (USB_PRODUCT_ID != 0)
71 #define HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
72 #endif
73 
74 #define ACL_IN_BUFFER_COUNT    3
75 #define EVENT_IN_BUFFER_COUNT  3
76 #define SCO_IN_BUFFER_COUNT   10
77 
78 #define ASYNC_POLLING_INTERVAL_MS 1
79 
80 //
81 // Bluetooth USB Transport Alternate Settings:
82 //
83 // 0: No active voice channels (for USB compliance)
84 // 1: One 8 kHz voice channel with 8-bit encoding
85 // 2: Two 8 kHz voice channels with 8-bit encoding or one 8 kHz voice channel with 16-bit encoding
86 // 3: Three 8 kHz voice channels with 8-bit encoding
87 // 4: Two 8 kHz voice channels with 16-bit encoding or one 16 kHz voice channel with 16-bit encoding
88 // 5: Three 8 kHz voice channels with 16-bit encoding or one 8 kHz voice channel with 16-bit encoding and one 16 kHz voice channel with 16-bit encoding
89 // --> support only a single SCO connection
90 // #define ALT_SETTING (1)
91 
92 // alt setting for 1-3 connections and 8/16 bit
93 static const int alt_setting_8_bit[]  = {1,2,3};
94 static const int alt_setting_16_bit[] = {2,4,5};
95 
96 // for ALT_SETTING >= 1 and 8-bit channel, we need the following isochronous packets
97 // One complete SCO packet with 24 frames every 3 frames (== 3 ms)
98 #define NUM_ISO_PACKETS (3)
99 
100 const uint16_t iso_packet_size_for_alt_setting[] = {
101     0,
102     9,
103     17,
104     25,
105     33,
106     49,
107     63,
108 };
109 
110 // 49 bytes is the max usb packet size for alternate setting 5 (Three 8 kHz 16-bit channels or one 8 kHz 16-bit channel and one 16 kHz 16-bit channel)
111 // note: alt setting 6 has max packet size of 63 every 7.5 ms = 472.5 bytes / HCI packet, while max SCO packet has 255 byte payload
112 #define SCO_PACKET_SIZE  (49 * NUM_ISO_PACKETS)
113 
114 // Outgoing SCO packet queue
115 // simplified ring buffer implementation
116 #define SCO_OUT_BUFFER_COUNT  (8)
117 #define SCO_OUT_BUFFER_SIZE (SCO_OUT_BUFFER_COUNT * SCO_PACKET_SIZE)
118 
119 // seems to be the max depth for USB 3
120 #define USB_MAX_PATH_LEN 7
121 
122 // prototypes
123 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
124 static int usb_close(void);
125 
126 typedef enum {
127     LIB_USB_CLOSED = 0,
128     LIB_USB_OPENED,
129     LIB_USB_DEVICE_OPENDED,
130     LIB_USB_INTERFACE_CLAIMED,
131     LIB_USB_TRANSFERS_ALLOCATED
132 } libusb_state_t;
133 
134 // SCO packet state machine
135 typedef enum {
136     H2_W4_SCO_HEADER = 1,
137     H2_W4_PAYLOAD,
138 } H2_SCO_STATE;
139 
140 static libusb_state_t libusb_state = LIB_USB_CLOSED;
141 
142 // single instance
143 static hci_transport_t * hci_transport_usb = NULL;
144 
145 static void (*packet_handler)(uint8_t packet_type, uint8_t *packet, uint16_t size) = dummy_handler;
146 
147 // libusb
148 #ifndef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
149 static struct libusb_device_descriptor desc;
150 static libusb_device        * dev;
151 #endif
152 static libusb_device_handle * handle;
153 
154 static struct libusb_transfer *command_out_transfer;
155 static struct libusb_transfer *acl_out_transfer;
156 static struct libusb_transfer *event_in_transfer[EVENT_IN_BUFFER_COUNT];
157 static struct libusb_transfer *acl_in_transfer[ACL_IN_BUFFER_COUNT];
158 
159 #ifdef ENABLE_SCO_OVER_HCI
160 
161 #ifdef _WIN32
162 #error "SCO not working on Win32 (Windows 8, libusb 1.0.19, Zadic WinUSB), please uncomment ENABLE_SCO_OVER_HCI in btstack-config.h for now"
163 #endif
164 
165 // incoming SCO
166 static H2_SCO_STATE sco_state;
167 static uint8_t  sco_buffer[255+3 + SCO_PACKET_SIZE];
168 static uint16_t sco_read_pos;
169 static uint16_t sco_bytes_to_read;
170 static struct  libusb_transfer *sco_in_transfer[SCO_IN_BUFFER_COUNT];
171 static uint8_t hci_sco_in_buffer[SCO_IN_BUFFER_COUNT][SCO_PACKET_SIZE];
172 
173 // outgoing SCO
174 static uint8_t  sco_out_ring_buffer[SCO_OUT_BUFFER_SIZE];
175 static int      sco_ring_write;  // packet idx
176 static int      sco_out_transfers_active;
177 static struct libusb_transfer *sco_out_transfers[SCO_OUT_BUFFER_COUNT];
178 static int      sco_out_transfers_in_flight[SCO_OUT_BUFFER_COUNT];
179 
180 // pause/resume
181 static uint16_t sco_voice_setting;
182 static int      sco_num_connections;
183 static int      sco_shutdown;
184 
185 // dynamic SCO configuration
186 static uint16_t iso_packet_size;
187 
188 #endif
189 
190 // outgoing buffer for HCI Command packets
191 static uint8_t hci_cmd_buffer[3 + 256 + LIBUSB_CONTROL_SETUP_SIZE];
192 
193 // incoming buffer for HCI Events and ACL Packets
194 static uint8_t hci_event_in_buffer[EVENT_IN_BUFFER_COUNT][HCI_ACL_BUFFER_SIZE]; // bigger than largest packet
195 static uint8_t hci_acl_in_buffer[ACL_IN_BUFFER_COUNT][HCI_INCOMING_PRE_BUFFER_SIZE + HCI_ACL_BUFFER_SIZE];
196 
197 // For (ab)use as a linked list of received packets
198 static struct libusb_transfer *handle_packet;
199 
200 static int doing_pollfds;
201 static int num_pollfds;
202 static btstack_data_source_t * pollfd_data_sources;
203 static btstack_timer_source_t usb_timer;
204 static int usb_timer_active;
205 
206 static int usb_acl_out_active = 0;
207 static int usb_command_active = 0;
208 
209 // endpoint addresses
210 static int event_in_addr;
211 static int acl_in_addr;
212 static int acl_out_addr;
213 static int sco_in_addr;
214 static int sco_out_addr;
215 
216 // device path
217 static int usb_path_len;
218 static uint8_t usb_path[USB_MAX_PATH_LEN];
219 
220 
221 #ifdef ENABLE_SCO_OVER_HCI
222 static void sco_ring_init(void){
223     sco_ring_write = 0;
224     sco_out_transfers_active = 0;
225 }
226 static int sco_ring_have_space(void){
227     return sco_out_transfers_active < SCO_OUT_BUFFER_COUNT;
228 }
229 #endif
230 
231 void hci_transport_usb_set_path(int len, uint8_t * port_numbers){
232     if (len > USB_MAX_PATH_LEN || !port_numbers){
233         log_error("hci_transport_usb_set_path: len or port numbers invalid");
234         return;
235     }
236     usb_path_len = len;
237     memcpy(usb_path, port_numbers, len);
238 }
239 
240 //
241 static void queue_transfer(struct libusb_transfer *transfer){
242 
243     // log_info("queue_transfer %p, endpoint %x size %u", transfer, transfer->endpoint, transfer->actual_length);
244 
245     transfer->user_data = NULL;
246 
247     // insert first element
248     if (handle_packet == NULL) {
249         handle_packet = transfer;
250         return;
251     }
252 
253     // Walk to end of list and add current packet there
254     struct libusb_transfer *temp = handle_packet;
255     while (temp->user_data) {
256         temp = (struct libusb_transfer*)temp->user_data;
257     }
258     temp->user_data = transfer;
259 }
260 
261 LIBUSB_CALL static void async_callback(struct libusb_transfer *transfer){
262 
263     int c;
264 
265     // identify and free transfers as part of shutdown
266 #ifdef ENABLE_SCO_OVER_HCI
267     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED || sco_shutdown) {
268         for (c=0;c<SCO_IN_BUFFER_COUNT;c++){
269             if (transfer == sco_in_transfer[c]){
270                 libusb_free_transfer(transfer);
271                 sco_in_transfer[c] = 0;
272                 return;
273             }
274         }
275 
276         for (c=0;c<SCO_OUT_BUFFER_COUNT;c++){
277             if (transfer == sco_out_transfers[c]){
278                 sco_out_transfers_in_flight[c] = 0;
279                 libusb_free_transfer(transfer);
280                 sco_out_transfers[c] = 0;
281                 return;
282             }
283         }
284     }
285 #endif
286 
287     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) {
288         for (c=0;c<EVENT_IN_BUFFER_COUNT;c++){
289             if (transfer == event_in_transfer[c]){
290                 libusb_free_transfer(transfer);
291                 event_in_transfer[c] = 0;
292                 return;
293             }
294         }
295         for (c=0;c<ACL_IN_BUFFER_COUNT;c++){
296             if (transfer == acl_in_transfer[c]){
297                 libusb_free_transfer(transfer);
298                 acl_in_transfer[c] = 0;
299                 return;
300             }
301         }
302         return;
303     }
304 
305 #ifdef ENABLE_SCO_OVER_HCI
306     // mark SCO OUT transfer as done
307     for (c=0;c<SCO_OUT_BUFFER_COUNT;c++){
308         if (transfer == sco_out_transfers[c]){
309             sco_out_transfers_in_flight[c] = 0;
310         }
311     }
312 #endif
313 
314     int r;
315     // log_info("begin async_callback endpoint %x, status %x, actual length %u", transfer->endpoint, transfer->status, transfer->actual_length );
316 
317     if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
318         queue_transfer(transfer);
319     } else if (transfer->status == LIBUSB_TRANSFER_STALL){
320         log_info("-> Transfer stalled, trying again");
321         r = libusb_clear_halt(handle, transfer->endpoint);
322         if (r) {
323             log_error("Error rclearing halt %d", r);
324         }
325         r = libusb_submit_transfer(transfer);
326         if (r) {
327             log_error("Error re-submitting transfer %d", r);
328         }
329     } else {
330         log_info("async_callback. not data -> resubmit transfer, endpoint %x, status %x, length %u", transfer->endpoint, transfer->status, transfer->actual_length);
331         // No usable data, just resubmit packet
332         r = libusb_submit_transfer(transfer);
333         if (r) {
334             log_error("Error re-submitting transfer %d", r);
335         }
336     }
337     // log_info("end async_callback");
338 }
339 
340 
341 #ifdef ENABLE_SCO_OVER_HCI
342 static int usb_send_sco_packet(uint8_t *packet, int size){
343     int r;
344 
345     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
346 
347     // log_info("usb_send_acl_packet enter, size %u", size);
348 
349     // store packet in free slot
350     int tranfer_index = sco_ring_write;
351     uint8_t * data = &sco_out_ring_buffer[tranfer_index * SCO_PACKET_SIZE];
352     memcpy(data, packet, size);
353 
354     // setup transfer
355     // log_info("usb_send_sco_packet: size %u, max size %u, iso packet size %u", size, NUM_ISO_PACKETS * iso_packet_size, iso_packet_size);
356     struct libusb_transfer * sco_transfer = sco_out_transfers[tranfer_index];
357     libusb_fill_iso_transfer(sco_transfer, handle, sco_out_addr, data, NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, NULL, 0);
358     libusb_set_iso_packet_lengths(sco_transfer, iso_packet_size);
359     r = libusb_submit_transfer(sco_transfer);
360     if (r < 0) {
361         log_error("Error submitting sco transfer, %d", r);
362         return -1;
363     }
364 
365     // mark slot as full
366     sco_ring_write++;
367     if (sco_ring_write == SCO_OUT_BUFFER_COUNT){
368         sco_ring_write = 0;
369     }
370     sco_out_transfers_active++;
371     sco_out_transfers_in_flight[tranfer_index] = 1;
372 
373     // log_info("H2: queued packet at index %u, num active %u", tranfer_index, sco_out_transfers_active);
374 
375     // notify upper stack that provided buffer can be used again
376     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
377     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
378 
379     // and if we have more space for SCO packets
380     if (sco_ring_have_space()) {
381         uint8_t event_sco[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
382         packet_handler(HCI_EVENT_PACKET, &event_sco[0], sizeof(event_sco));
383     }
384     return 0;
385 }
386 
387 static void sco_state_machine_init(void){
388     sco_state = H2_W4_SCO_HEADER;
389     sco_read_pos = 0;
390     sco_bytes_to_read = 3;
391 }
392 
393 static void handle_isochronous_data(uint8_t * buffer, uint16_t size){
394     while (size){
395         if (size < sco_bytes_to_read){
396             // just store incomplete data
397             memcpy(&sco_buffer[sco_read_pos], buffer, size);
398             sco_read_pos      += size;
399             sco_bytes_to_read -= size;
400             return;
401         }
402         // copy requested data
403         memcpy(&sco_buffer[sco_read_pos], buffer, sco_bytes_to_read);
404         sco_read_pos += sco_bytes_to_read;
405         buffer       += sco_bytes_to_read;
406         size         -= sco_bytes_to_read;
407 
408         // chunk read successfully, next action
409         switch (sco_state){
410             case H2_W4_SCO_HEADER:
411                 sco_state = H2_W4_PAYLOAD;
412                 sco_bytes_to_read = sco_buffer[2];
413                 break;
414             case H2_W4_PAYLOAD:
415                 // packet complete
416                 packet_handler(HCI_SCO_DATA_PACKET, sco_buffer, sco_read_pos);
417                 sco_state_machine_init();
418                 break;
419         }
420     }
421 }
422 #endif
423 
424 static void handle_completed_transfer(struct libusb_transfer *transfer){
425 
426     int resubmit = 0;
427     int signal_done = 0;
428 
429     if (transfer->endpoint == event_in_addr) {
430         packet_handler(HCI_EVENT_PACKET, transfer-> buffer, transfer->actual_length);
431         resubmit = 1;
432     } else if (transfer->endpoint == acl_in_addr) {
433         // log_info("-> acl");
434         packet_handler(HCI_ACL_DATA_PACKET, transfer-> buffer, transfer->actual_length);
435         resubmit = 1;
436     } else if (transfer->endpoint == 0){
437         // log_info("command done, size %u", transfer->actual_length);
438         usb_command_active = 0;
439         signal_done = 1;
440     } else if (transfer->endpoint == acl_out_addr){
441         // log_info("acl out done, size %u", transfer->actual_length);
442         usb_acl_out_active = 0;
443         signal_done = 1;
444 #ifdef ENABLE_SCO_OVER_HCI
445     } else if (transfer->endpoint == sco_in_addr) {
446         // log_info("handle_completed_transfer for SCO IN! num packets %u", transfer->NUM_ISO_PACKETS);
447         int i;
448         for (i = 0; i < transfer->num_iso_packets; i++) {
449             struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i];
450             if (pack->status != LIBUSB_TRANSFER_COMPLETED) {
451                 log_error("Error: pack %u status %d\n", i, pack->status);
452                 continue;
453             }
454             if (!pack->actual_length) continue;
455             uint8_t * data = libusb_get_iso_packet_buffer_simple(transfer, i);
456             // printf_hexdump(data, pack->actual_length);
457             // log_info("handle_isochronous_data,size %u/%u", pack->length, pack->actual_length);
458             handle_isochronous_data(data, pack->actual_length);
459         }
460         resubmit = 1;
461     } else if (transfer->endpoint == sco_out_addr){
462         int i;
463         for (i = 0; i < transfer->num_iso_packets; i++) {
464             struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i];
465             if (pack->status != LIBUSB_TRANSFER_COMPLETED) {
466                 log_error("Error: pack %u status %d\n", i, pack->status);
467             }
468         }
469         // log_info("sco out done, {{ %u/%u (%x)}, { %u/%u (%x)}, { %u/%u (%x)}}",
470         //     transfer->iso_packet_desc[0].actual_length, transfer->iso_packet_desc[0].length, transfer->iso_packet_desc[0].status,
471         //     transfer->iso_packet_desc[1].actual_length, transfer->iso_packet_desc[1].length, transfer->iso_packet_desc[1].status,
472         //     transfer->iso_packet_desc[2].actual_length, transfer->iso_packet_desc[2].length, transfer->iso_packet_desc[2].status);
473         // notify upper layer if there's space for new SCO packets
474 
475         if (sco_ring_have_space()) {
476             uint8_t event[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
477             packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
478         }
479         // decrease tab
480         sco_out_transfers_active--;
481         // log_info("H2: sco out complete, num active num active %u", sco_out_transfers_active);
482 #endif
483     } else {
484         log_info("usb_process_ds endpoint unknown %x", transfer->endpoint);
485     }
486 
487     if (signal_done){
488         // notify upper stack that provided buffer can be used again
489         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
490         packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
491     }
492 
493     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
494 
495     if (resubmit){
496         // Re-submit transfer
497         transfer->user_data = NULL;
498         int r = libusb_submit_transfer(transfer);
499         if (r) {
500             log_error("Error re-submitting transfer %d", r);
501         }
502     }
503 }
504 
505 static void usb_process_ds(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) {
506 
507     UNUSED(ds);
508     UNUSED(callback_type);
509 
510     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
511 
512     // log_info("begin usb_process_ds");
513     // always handling an event as we're called when data is ready
514     struct timeval tv;
515     memset(&tv, 0, sizeof(struct timeval));
516     libusb_handle_events_timeout(NULL, &tv);
517 
518     // Handle any packet in the order that they were received
519     while (handle_packet) {
520         // log_info("handle packet %p, endpoint %x, status %x", handle_packet, handle_packet->endpoint, handle_packet->status);
521         void * next = handle_packet->user_data;
522         handle_completed_transfer(handle_packet);
523         // handle case where libusb_close might be called by hci packet handler
524         if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
525 
526         // Move to next in the list of packets to handle
527         if (next) {
528             handle_packet = (struct libusb_transfer*)next;
529         } else {
530             handle_packet = NULL;
531         }
532     }
533     // log_info("end usb_process_ds");
534 }
535 
536 static void usb_process_ts(btstack_timer_source_t *timer) {
537 
538     UNUSED(timer);
539 
540     // log_info("in usb_process_ts");
541 
542     // timer is deactive, when timer callback gets called
543     usb_timer_active = 0;
544 
545     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
546 
547     // actually handled the packet in the pollfds function
548     usb_process_ds((struct btstack_data_source *) NULL, DATA_SOURCE_CALLBACK_READ);
549 
550     // Get the amount of time until next event is due
551     long msec = ASYNC_POLLING_INTERVAL_MS;
552 
553     // Activate timer
554     btstack_run_loop_set_timer(&usb_timer, msec);
555     btstack_run_loop_add_timer(&usb_timer);
556     usb_timer_active = 1;
557 
558     return;
559 }
560 
561 #ifndef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
562 
563 // list of known devices, using VendorID/ProductID tuples
564 static const uint16_t known_bt_devices[] = {
565     // DeLOCK Bluetooth 4.0
566     0x0a5c, 0x21e8,
567     // Asus BT400
568     0x0b05, 0x17cb,
569 };
570 
571 static int num_known_devices = sizeof(known_bt_devices) / sizeof(uint16_t) / 2;
572 
573 static int is_known_bt_device(uint16_t vendor_id, uint16_t product_id){
574     int i;
575     for (i=0; i<num_known_devices; i++){
576         if (known_bt_devices[i*2] == vendor_id && known_bt_devices[i*2+1] == product_id){
577             return 1;
578         }
579     }
580     return 0;
581 }
582 
583 static void scan_for_bt_endpoints(void) {
584     int r;
585 
586     event_in_addr = 0;
587     acl_in_addr = 0;
588     acl_out_addr = 0;
589     sco_out_addr = 0;
590     sco_in_addr = 0;
591 
592     // get endpoints from interface descriptor
593     struct libusb_config_descriptor *config_descriptor;
594     r = libusb_get_active_config_descriptor(dev, &config_descriptor);
595 
596     int num_interfaces = config_descriptor->bNumInterfaces;
597     log_info("active configuration has %u interfaces", num_interfaces);
598 
599     int i;
600     for (i = 0; i < num_interfaces ; i++){
601         const struct libusb_interface *interface = &config_descriptor->interface[i];
602         const struct libusb_interface_descriptor * interface_descriptor = interface->altsetting;
603         log_info("interface %u: %u endpoints", i, interface_descriptor->bNumEndpoints);
604 
605         const struct libusb_endpoint_descriptor *endpoint = interface_descriptor->endpoint;
606 
607         for (r=0;r<interface_descriptor->bNumEndpoints;r++,endpoint++){
608             log_info("- endpoint %x, attributes %x", endpoint->bEndpointAddress, endpoint->bmAttributes);
609 
610             switch (endpoint->bmAttributes & 0x3){
611                 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
612                     if (event_in_addr) continue;
613                     event_in_addr = endpoint->bEndpointAddress;
614                     log_info("-> using 0x%2.2X for HCI Events", event_in_addr);
615                     break;
616                 case LIBUSB_TRANSFER_TYPE_BULK:
617                     if (endpoint->bEndpointAddress & 0x80) {
618                         if (acl_in_addr) continue;
619                         acl_in_addr = endpoint->bEndpointAddress;
620                         log_info("-> using 0x%2.2X for ACL Data In", acl_in_addr);
621                     } else {
622                         if (acl_out_addr) continue;
623                         acl_out_addr = endpoint->bEndpointAddress;
624                         log_info("-> using 0x%2.2X for ACL Data Out", acl_out_addr);
625                     }
626                     break;
627                 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
628                     if (endpoint->bEndpointAddress & 0x80) {
629                         if (sco_in_addr) continue;
630                         sco_in_addr = endpoint->bEndpointAddress;
631                         log_info("-> using 0x%2.2X for SCO Data In", sco_in_addr);
632                     } else {
633                         if (sco_out_addr) continue;
634                         sco_out_addr = endpoint->bEndpointAddress;
635                         log_info("-> using 0x%2.2X for SCO Data Out", sco_out_addr);
636                     }
637                     break;
638                 default:
639                     break;
640             }
641         }
642     }
643     libusb_free_config_descriptor(config_descriptor);
644 }
645 
646 // returns index of found device or -1
647 static int scan_for_bt_device(libusb_device **devs, int start_index) {
648     int i;
649     for (i = start_index; devs[i] ; i++){
650         dev = devs[i];
651         int r = libusb_get_device_descriptor(dev, &desc);
652         if (r < 0) {
653             log_error("failed to get device descriptor");
654             return 0;
655         }
656 
657         log_info("%04x:%04x (bus %d, device %d) - class %x subclass %x protocol %x ",
658                desc.idVendor, desc.idProduct,
659                libusb_get_bus_number(dev), libusb_get_device_address(dev),
660                desc.bDeviceClass, desc.bDeviceSubClass, desc.bDeviceProtocol);
661 
662         // Detect USB Dongle based Class, Subclass, and Protocol
663         // The class code (bDeviceClass) is 0xE0 – Wireless Controller.
664         // The SubClass code (bDeviceSubClass) is 0x01 – RF Controller.
665         // The Protocol code (bDeviceProtocol) is 0x01 – Bluetooth programming.
666         // if (desc.bDeviceClass == 0xe0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01){
667         if (desc.bDeviceClass == 0xE0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01) {
668             return i;
669         }
670 
671         // Detect USB Dongle based on whitelist
672         if (is_known_bt_device(desc.idVendor, desc.idProduct)) {
673             return i;
674         }
675     }
676     return -1;
677 }
678 #endif
679 
680 static int prepare_device(libusb_device_handle * aHandle){
681 
682     // print device path
683     uint8_t port_numbers[USB_MAX_PATH_LEN];
684     libusb_device * device = libusb_get_device(aHandle);
685     int path_len = libusb_get_port_numbers(device, port_numbers, USB_MAX_PATH_LEN);
686     printf("USB Path: ");
687     int i;
688     for (i=0;i<path_len;i++){
689         if (i) printf("-");
690         printf("%02x", port_numbers[i]);
691     }
692     printf("\n");
693 
694     int r;
695     int kernel_driver_detached = 0;
696 
697     // Detach OS driver (not possible for OS X and WIN32)
698 #if !defined(__APPLE__) && !defined(_WIN32)
699     r = libusb_kernel_driver_active(aHandle, 0);
700     if (r < 0) {
701         log_error("libusb_kernel_driver_active error %d", r);
702         libusb_close(aHandle);
703         return r;
704     }
705 
706     if (r == 1) {
707         r = libusb_detach_kernel_driver(aHandle, 0);
708         if (r < 0) {
709             log_error("libusb_detach_kernel_driver error %d", r);
710             libusb_close(aHandle);
711             return r;
712         }
713         kernel_driver_detached = 1;
714     }
715     log_info("libusb_detach_kernel_driver");
716 #endif
717 
718     const int configuration = 1;
719     log_info("setting configuration %d...", configuration);
720     r = libusb_set_configuration(aHandle, configuration);
721     if (r < 0) {
722         log_error("Error libusb_set_configuration: %d", r);
723         if (kernel_driver_detached){
724             libusb_attach_kernel_driver(aHandle, 0);
725         }
726         libusb_close(aHandle);
727         return r;
728     }
729 
730     // reserve access to device
731     log_info("claiming interface 0...");
732     r = libusb_claim_interface(aHandle, 0);
733     if (r < 0) {
734         log_error("Error claiming interface %d", r);
735         if (kernel_driver_detached){
736             libusb_attach_kernel_driver(aHandle, 0);
737         }
738         libusb_close(aHandle);
739         return r;
740     }
741 
742 #ifdef ENABLE_SCO_OVER_HCI
743     log_info("claiming interface 1...");
744     r = libusb_claim_interface(aHandle, 1);
745     if (r < 0) {
746         log_error("Error claiming interface %d", r);
747         if (kernel_driver_detached){
748             libusb_attach_kernel_driver(aHandle, 0);
749         }
750         libusb_close(aHandle);
751         return r;
752     }
753 #endif
754 
755     return 0;
756 }
757 
758 static libusb_device_handle * try_open_device(libusb_device * device){
759     int r;
760 
761     libusb_device_handle * dev_handle;
762     r = libusb_open(device, &dev_handle);
763 
764     if (r < 0) {
765         log_error("libusb_open failed!");
766         dev_handle = NULL;
767         return NULL;
768     }
769 
770     log_info("libusb open %d, handle %p", r, dev_handle);
771 
772     // reset device
773     libusb_reset_device(dev_handle);
774     if (r < 0) {
775         log_error("libusb_reset_device failed!");
776         libusb_close(dev_handle);
777         return NULL;
778     }
779     return dev_handle;
780 }
781 
782 #ifdef ENABLE_SCO_OVER_HCI
783 
784 static int usb_sco_start(void){
785 
786     printf("usb_sco_start\n");
787     log_info("usb_sco_start");
788 
789     sco_state_machine_init();
790     sco_ring_init();
791 
792     int alt_setting;
793     if (sco_voice_setting & 0x0020){
794         // 16-bit PCM
795         alt_setting = alt_setting_16_bit[sco_num_connections-1];
796     } else {
797         // 8-bit PCM or mSBC
798         alt_setting = alt_setting_8_bit[sco_num_connections-1];
799     }
800     // derive iso packet size from alt setting
801     iso_packet_size = iso_packet_size_for_alt_setting[alt_setting];
802 
803     log_info("Switching to setting %u on interface 1..", alt_setting);
804     int r = libusb_set_interface_alt_setting(handle, 1, alt_setting);
805     if (r < 0) {
806         log_error("Error setting alternative setting %u for interface 1: %s\n", alt_setting, libusb_error_name(r));
807         return r;
808     }
809 
810     // incoming
811     int c;
812     for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
813         sco_in_transfer[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // isochronous transfers SCO in
814         if (!sco_in_transfer[c]) {
815             usb_close();
816             return LIBUSB_ERROR_NO_MEM;
817         }
818         // configure sco_in handlers
819         libusb_fill_iso_transfer(sco_in_transfer[c], handle, sco_in_addr,
820             hci_sco_in_buffer[c], NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, NULL, 0);
821         libusb_set_iso_packet_lengths(sco_in_transfer[c], iso_packet_size);
822         r = libusb_submit_transfer(sco_in_transfer[c]);
823         if (r) {
824             log_error("Error submitting isochronous in transfer %d", r);
825             usb_close();
826             return r;
827         }
828     }
829 
830     // outgoing
831     for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
832         sco_out_transfers[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // 1 isochronous transfers SCO out - up to 3 parts
833         sco_out_transfers_in_flight[c] = 0;
834     }
835     return 0;
836 }
837 
838 static void usb_sco_stop(void){
839 
840     printf("usb_sco_stop\n");
841 
842     log_info("usb_sco_stop");
843     sco_shutdown = 1;
844 
845     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_ERROR);
846 
847     int c;
848     for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
849         libusb_cancel_transfer(sco_in_transfer[c]);
850     }
851 
852     for (c = 0; c < SCO_OUT_BUFFER_COUNT ; c++){
853         if (sco_out_transfers_in_flight[c]) {
854             libusb_cancel_transfer(sco_out_transfers[c]);
855         } else {
856             libusb_free_transfer(sco_out_transfers[c]);
857             sco_out_transfers[c] = 0;
858         }
859     }
860 
861     // wait until all transfers are completed
862     int completed = 0;
863     while (!completed){
864         struct timeval tv;
865         memset(&tv, 0, sizeof(struct timeval));
866         libusb_handle_events_timeout(NULL, &tv);
867         // check if all done
868         completed = 1;
869 
870         // Cancel all synchronous transfer
871         for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
872             if (sco_in_transfer[c]){
873                 completed = 0;
874                 break;
875             }
876         }
877 
878         if (!completed) continue;
879 
880         for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
881             if (sco_out_transfers[c]){
882                 completed = 0;
883                 break;
884             }
885         }
886     }
887     sco_shutdown = 0;
888     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
889 
890     log_info("Switching to setting %u on interface 1..", 0);
891     int r = libusb_set_interface_alt_setting(handle, 1, 0);
892     if (r < 0) {
893         log_error("Error setting alternative setting %u for interface 1: %s", 0, libusb_error_name(r));
894         return;
895     }
896 
897     printf("usb_sco_stop done\n");
898 }
899 
900 
901 
902 #endif
903 
904 static int usb_open(void){
905     int r;
906 
907     handle_packet = NULL;
908 
909     // default endpoint addresses
910     event_in_addr = 0x81; // EP1, IN interrupt
911     acl_in_addr =   0x82; // EP2, IN bulk
912     acl_out_addr =  0x02; // EP2, OUT bulk
913     sco_in_addr  =  0x83; // EP3, IN isochronous
914     sco_out_addr =  0x03; // EP3, OUT isochronous
915 
916     // USB init
917     r = libusb_init(NULL);
918     if (r < 0) return -1;
919 
920     libusb_state = LIB_USB_OPENED;
921 
922     // configure debug level
923     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
924 
925 #ifdef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
926 
927     // Use a specified device
928     log_info("Want vend: %04x, prod: %04x", USB_VENDOR_ID, USB_PRODUCT_ID);
929     handle = libusb_open_device_with_vid_pid(NULL, USB_VENDOR_ID, USB_PRODUCT_ID);
930 
931     if (!handle){
932         log_error("libusb_open_device_with_vid_pid failed!");
933         usb_close();
934         return -1;
935     }
936     log_info("libusb open %d, handle %p", r, handle);
937 
938     r = prepare_device(handle);
939     if (r < 0){
940         usb_close();
941         return -1;
942     }
943 
944 #else
945     // Scan system for an appropriate devices
946     libusb_device **devs;
947     ssize_t num_devices;
948 
949     log_info("Scanning for USB Bluetooth device");
950     num_devices = libusb_get_device_list(NULL, &devs);
951     if (num_devices < 0) {
952         usb_close();
953         return -1;
954     }
955 
956     dev = NULL;
957 
958     if (usb_path_len){
959         int i;
960         for (i=0;i<num_devices;i++){
961             uint8_t port_numbers[USB_MAX_PATH_LEN];
962             int len = libusb_get_port_numbers(devs[i], port_numbers, USB_MAX_PATH_LEN);
963             if (len != usb_path_len) continue;
964             if (memcmp(usb_path, port_numbers, len) == 0){
965                 log_info("USB device found at specified path");
966                 handle = try_open_device(devs[i]);
967                 if (!handle) continue;
968 
969                 r = prepare_device(handle);
970                 if (r < 0) continue;
971 
972                 dev = devs[i];
973                 libusb_state = LIB_USB_INTERFACE_CLAIMED;
974                 break;
975             };
976         }
977         if (!handle){
978             log_error("USB device with given path not found");
979             printf("USB device with given path not found\n");
980             return -1;
981         }
982     } else {
983 
984         int deviceIndex = -1;
985         while (1){
986             // look for next Bluetooth dongle
987             deviceIndex = scan_for_bt_device(devs, deviceIndex+1);
988             if (deviceIndex < 0) break;
989 
990             log_info("USB Bluetooth device found, index %u", deviceIndex);
991 
992             handle = try_open_device(devs[deviceIndex]);
993             if (!handle) continue;
994 
995             r = prepare_device(handle);
996             if (r < 0) continue;
997 
998             dev = devs[deviceIndex];
999             libusb_state = LIB_USB_INTERFACE_CLAIMED;
1000             break;
1001         }
1002     }
1003 
1004     libusb_free_device_list(devs, 1);
1005 
1006     if (handle == 0){
1007         log_error("No USB Bluetooth device found");
1008         return -1;
1009     }
1010 
1011     scan_for_bt_endpoints();
1012 
1013 #endif
1014 
1015     // allocate transfer handlers
1016     int c;
1017     for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1018         event_in_transfer[c] = libusb_alloc_transfer(0); // 0 isochronous transfers Events
1019         if (!event_in_transfer[c]) {
1020             usb_close();
1021             return LIBUSB_ERROR_NO_MEM;
1022         }
1023     }
1024     for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1025         acl_in_transfer[c]  =  libusb_alloc_transfer(0); // 0 isochronous transfers ACL in
1026         if (!acl_in_transfer[c]) {
1027             usb_close();
1028             return LIBUSB_ERROR_NO_MEM;
1029         }
1030     }
1031 
1032     command_out_transfer = libusb_alloc_transfer(0);
1033     acl_out_transfer     = libusb_alloc_transfer(0);
1034 
1035     // TODO check for error
1036 
1037     libusb_state = LIB_USB_TRANSFERS_ALLOCATED;
1038 
1039     for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1040         // configure event_in handlers
1041         libusb_fill_interrupt_transfer(event_in_transfer[c], handle, event_in_addr,
1042                 hci_event_in_buffer[c], HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ;
1043         r = libusb_submit_transfer(event_in_transfer[c]);
1044         if (r) {
1045             log_error("Error submitting interrupt transfer %d", r);
1046             usb_close();
1047             return r;
1048         }
1049     }
1050 
1051     for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1052         // configure acl_in handlers
1053         libusb_fill_bulk_transfer(acl_in_transfer[c], handle, acl_in_addr,
1054                 hci_acl_in_buffer[c] + HCI_INCOMING_PRE_BUFFER_SIZE, HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ;
1055         r = libusb_submit_transfer(acl_in_transfer[c]);
1056         if (r) {
1057             log_error("Error submitting bulk in transfer %d", r);
1058             usb_close();
1059             return r;
1060         }
1061 
1062      }
1063 
1064     // Check for pollfds functionality
1065     doing_pollfds = libusb_pollfds_handle_timeouts(NULL);
1066 
1067     // NOTE: using pollfds doesn't work on Linux, so it is disable until further investigation here
1068     doing_pollfds = 0;
1069 
1070     if (doing_pollfds) {
1071         log_info("Async using pollfds:");
1072 
1073         const struct libusb_pollfd ** pollfd = libusb_get_pollfds(NULL);
1074         for (num_pollfds = 0 ; pollfd[num_pollfds] ; num_pollfds++);
1075         pollfd_data_sources = malloc(sizeof(btstack_data_source_t) * num_pollfds);
1076         if (!pollfd_data_sources){
1077             log_error("Cannot allocate data sources for pollfds");
1078             usb_close();
1079             return 1;
1080         }
1081         for (r = 0 ; r < num_pollfds ; r++) {
1082             btstack_data_source_t *ds = &pollfd_data_sources[r];
1083             btstack_run_loop_set_data_source_fd(ds, pollfd[r]->fd);
1084             btstack_run_loop_set_data_source_handler(ds, &usb_process_ds);
1085             btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
1086             btstack_run_loop_add_data_source(ds);
1087             log_info("%u: %p fd: %u, events %x", r, pollfd[r], pollfd[r]->fd, pollfd[r]->events);
1088         }
1089         free(pollfd);
1090     } else {
1091         log_info("Async using timers:");
1092 
1093         usb_timer.process = usb_process_ts;
1094         btstack_run_loop_set_timer(&usb_timer, ASYNC_POLLING_INTERVAL_MS);
1095         btstack_run_loop_add_timer(&usb_timer);
1096         usb_timer_active = 1;
1097     }
1098 
1099     return 0;
1100 }
1101 
1102 static int usb_close(void){
1103     int c;
1104     switch (libusb_state){
1105         case LIB_USB_CLOSED:
1106             break;
1107 
1108         case LIB_USB_TRANSFERS_ALLOCATED:
1109             libusb_state = LIB_USB_INTERFACE_CLAIMED;
1110 
1111             if(usb_timer_active) {
1112                 btstack_run_loop_remove_timer(&usb_timer);
1113                 usb_timer_active = 0;
1114             }
1115 
1116             if (doing_pollfds){
1117                 int r;
1118                 for (r = 0 ; r < num_pollfds ; r++) {
1119                     btstack_data_source_t *ds = &pollfd_data_sources[r];
1120                     btstack_run_loop_remove_data_source(ds);
1121                 }
1122                 free(pollfd_data_sources);
1123                 pollfd_data_sources = NULL;
1124                 num_pollfds = 0;
1125                 doing_pollfds = 0;
1126             }
1127 
1128         case LIB_USB_INTERFACE_CLAIMED:
1129             // Cancel all transfers, ignore warnings for this
1130             libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_ERROR);
1131             for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1132                 libusb_cancel_transfer(event_in_transfer[c]);
1133             }
1134             for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1135                 libusb_cancel_transfer(acl_in_transfer[c]);
1136             }
1137 #ifdef ENABLE_SCO_OVER_HCI
1138             for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
1139                 libusb_cancel_transfer(sco_in_transfer[c]);
1140             }
1141             for (c = 0; c < SCO_OUT_BUFFER_COUNT ; c++){
1142                 if (sco_out_transfers_in_flight[c]) {
1143                     libusb_cancel_transfer(sco_out_transfers[c]);
1144                 } else {
1145                     libusb_free_transfer(sco_out_transfers[c]);
1146                     sco_out_transfers[c] = 0;
1147                 }
1148             }
1149 #endif
1150             libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
1151 
1152             // wait until all transfers are completed
1153             int completed = 0;
1154             while (!completed){
1155                 struct timeval tv;
1156                 memset(&tv, 0, sizeof(struct timeval));
1157                 libusb_handle_events_timeout(NULL, &tv);
1158                 // check if all done
1159                 completed = 1;
1160                 for (c=0;c<EVENT_IN_BUFFER_COUNT;c++){
1161                     if (event_in_transfer[c]) {
1162                         completed = 0;
1163                         break;
1164                     }
1165                 }
1166 
1167                 if (!completed) continue;
1168 
1169                 for (c=0;c<ACL_IN_BUFFER_COUNT;c++){
1170                     if (acl_in_transfer[c]) {
1171                         completed = 0;
1172                         break;
1173                     }
1174                 }
1175 
1176 #ifdef ENABLE_SCO_OVER_HCI
1177                 if (!completed) continue;
1178 
1179                 // Cancel all synchronous transfer
1180                 for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
1181                     if (sco_in_transfer[c]){
1182                         completed = 0;
1183                         break;
1184                     }
1185                 }
1186 
1187                 if (!completed) continue;
1188 
1189                 for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
1190                     if (sco_out_transfers[c]){
1191                         completed = 0;
1192                         break;
1193                     }
1194                 }
1195 #endif
1196             }
1197 
1198             // finally release interface
1199             libusb_release_interface(handle, 0);
1200 #ifdef ENABLE_SCO_OVER_HCI
1201             libusb_release_interface(handle, 1);
1202 #endif
1203             log_info("Libusb shutdown complete");
1204 
1205         case LIB_USB_DEVICE_OPENDED:
1206             libusb_close(handle);
1207 
1208         case LIB_USB_OPENED:
1209             libusb_exit(NULL);
1210     }
1211 
1212     libusb_state = LIB_USB_CLOSED;
1213     handle = NULL;
1214 
1215     return 0;
1216 }
1217 
1218 static int usb_send_cmd_packet(uint8_t *packet, int size){
1219     int r;
1220 
1221     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1222 
1223     // async
1224     libusb_fill_control_setup(hci_cmd_buffer, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0, 0, 0, size);
1225     memcpy(hci_cmd_buffer + LIBUSB_CONTROL_SETUP_SIZE, packet, size);
1226 
1227     // prepare transfer
1228     int completed = 0;
1229     libusb_fill_control_transfer(command_out_transfer, handle, hci_cmd_buffer, async_callback, &completed, 0);
1230     command_out_transfer->flags = LIBUSB_TRANSFER_FREE_BUFFER;
1231 
1232     // update stata before submitting transfer
1233     usb_command_active = 1;
1234 
1235     // submit transfer
1236     r = libusb_submit_transfer(command_out_transfer);
1237 
1238     if (r < 0) {
1239         usb_command_active = 0;
1240         log_error("Error submitting cmd transfer %d", r);
1241         return -1;
1242     }
1243 
1244     return 0;
1245 }
1246 
1247 static int usb_send_acl_packet(uint8_t *packet, int size){
1248     int r;
1249 
1250     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1251 
1252     // log_info("usb_send_acl_packet enter, size %u", size);
1253 
1254     // prepare transfer
1255     int completed = 0;
1256     libusb_fill_bulk_transfer(acl_out_transfer, handle, acl_out_addr, packet, size,
1257         async_callback, &completed, 0);
1258     acl_out_transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1259 
1260     // update stata before submitting transfer
1261     usb_acl_out_active = 1;
1262 
1263     r = libusb_submit_transfer(acl_out_transfer);
1264     if (r < 0) {
1265         usb_acl_out_active = 0;
1266         log_error("Error submitting acl transfer, %d", r);
1267         return -1;
1268     }
1269 
1270     return 0;
1271 }
1272 
1273 static int usb_can_send_packet_now(uint8_t packet_type){
1274     switch (packet_type){
1275         case HCI_COMMAND_DATA_PACKET:
1276             return !usb_command_active;
1277         case HCI_ACL_DATA_PACKET:
1278             return !usb_acl_out_active;
1279 #ifdef ENABLE_SCO_OVER_HCI
1280         case HCI_SCO_DATA_PACKET:
1281             return sco_ring_have_space();
1282 #endif
1283         default:
1284             return 0;
1285     }
1286 }
1287 
1288 static int usb_send_packet(uint8_t packet_type, uint8_t * packet, int size){
1289     switch (packet_type){
1290         case HCI_COMMAND_DATA_PACKET:
1291             return usb_send_cmd_packet(packet, size);
1292         case HCI_ACL_DATA_PACKET:
1293             return usb_send_acl_packet(packet, size);
1294 #ifdef ENABLE_SCO_OVER_HCI
1295         case HCI_SCO_DATA_PACKET:
1296             return usb_send_sco_packet(packet, size);
1297 #endif
1298         default:
1299             return -1;
1300     }
1301 }
1302 
1303 #ifdef ENABLE_SCO_OVER_HCI
1304 static void usb_set_sco_config(uint16_t voice_setting, int num_connections){
1305     log_info("usb_set_sco_config: voice settings 0x%04x, num connections %u", voice_setting, num_connections);
1306 
1307     if (num_connections != sco_num_connections){
1308         sco_voice_setting = voice_setting;
1309         if (sco_num_connections){
1310             usb_sco_stop();
1311         }
1312         sco_num_connections = num_connections;
1313         if (num_connections){
1314             usb_sco_start();
1315         }
1316     }
1317 }
1318 #endif
1319 
1320 static void usb_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1321     log_info("registering packet handler");
1322     packet_handler = handler;
1323 }
1324 
1325 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1326     UNUSED(packet_type);
1327     UNUSED(packet);
1328     UNUSED(size);
1329 }
1330 
1331 // get usb singleton
1332 const hci_transport_t * hci_transport_usb_instance(void) {
1333     if (!hci_transport_usb) {
1334         hci_transport_usb = (hci_transport_t*) malloc( sizeof(hci_transport_t));
1335         memset(hci_transport_usb, 0, sizeof(hci_transport_t));
1336         hci_transport_usb->name                          = "H2_LIBUSB";
1337         hci_transport_usb->open                          = usb_open;
1338         hci_transport_usb->close                         = usb_close;
1339         hci_transport_usb->register_packet_handler       = usb_register_packet_handler;
1340         hci_transport_usb->can_send_packet_now           = usb_can_send_packet_now;
1341         hci_transport_usb->send_packet                   = usb_send_packet;
1342 #ifdef ENABLE_SCO_OVER_HCI
1343         hci_transport_usb->set_sco_config                = usb_set_sco_config;
1344 #endif
1345     }
1346     return hci_transport_usb;
1347 }
1348