xref: /btstack/platform/windows/hci_transport_h2_winusb.c (revision be531a89d0481a658e92d75dc7d0a368c96e957d)
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 BLUEKITCHEN
24  * GMBH 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_winusb.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 <string.h>
58 #include <sys/types.h>
59 #include <inttypes.h>   // to print long long int (aka 64 bit ints)
60 
61 #include "btstack_config.h"
62 
63 #include "btstack_debug.h"
64 #include "hci.h"
65 #include "hci_transport.h"
66 #include "hci_transport_usb.h"
67 
68 #include <Windows.h>
69 #include <SetupAPI.h>
70 #include <Winusb.h>
71 
72 #ifdef ENABLE_SCO_OVER_HCI
73 
74 // Isochronous Add-On
75 
76 // Function signatures frome https://abi-laboratory.pro/compatibility/Windows_7.0_to_Windows_8.1/x86_64/info/winusb.dll/symbols.html
77 // MSDN documentation has multiple errors (Jan 2017), annotated below
78 
79 // As Isochochronous functions are provided by newer versions of ming64, we use a BTstack/BTSTACK prefix to prevent name collisions
80 
81 typedef PVOID BTSTACK_WINUSB_ISOCH_BUFFER_HANDLE, *BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE;
82 
83 typedef struct _BTSTACK_WINUSB_PIPE_INFORMATION_EX {
84   USBD_PIPE_TYPE PipeType;
85   UCHAR          PipeId;
86   USHORT         MaximumPacketSize;
87   UCHAR          Interval;
88   ULONG          MaximumBytesPerInterval;
89 } BTSTACK_WINUSB_PIPE_INFORMATION_EX, *BTSTACK_PWINUSB_PIPE_INFORMATION_EX;
90 
91 typedef WINBOOL (WINAPI * BTstack_WinUsb_QueryPipeEx_t) (
92 	WINUSB_INTERFACE_HANDLE 	InterfaceHandle,
93 	UCHAR						AlternateInterfaceNumber,
94 	UCHAR 						PipeIndex,
95 	BTSTACK_PWINUSB_PIPE_INFORMATION_EX PipeInformationEx
96 );
97 typedef WINBOOL (WINAPI * BTstack_WinUsb_RegisterIsochBuffer_t)(
98 	WINUSB_INTERFACE_HANDLE     InterfaceHandle,
99 	UCHAR                       PipeID,
100 	PVOID                       Buffer,
101 	ULONG                       BufferLength,
102 	BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle
103 );
104 typedef WINBOOL (WINAPI * BTstack_WinUsb_ReadIsochPipe_t)(
105     BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle,
106     ULONG                       Offset,
107     ULONG                       Length,
108     PULONG                      FrameNumber,
109     ULONG                       NumberOfPackets,        // MSDN lists PULONG
110     PUSBD_ISO_PACKET_DESCRIPTOR IsoPacketDescriptors,   // MSDN lists PULONG
111     LPOVERLAPPED                Overlapped
112 );
113 typedef WINBOOL (WINAPI * BTstack_WinUsb_ReadIsochPipeAsap_t)(
114     BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle,
115     ULONG                       Offset,
116     ULONG                       Length,
117     BOOL                        ContinueStream,
118     ULONG                      	NumberOfPackets,        // MSDN lists PULONG
119     PUSBD_ISO_PACKET_DESCRIPTOR IsoPacketDescriptors,
120  	LPOVERLAPPED                Overlapped
121 );
122 typedef WINBOOL (WINAPI * BTstack_WinUsb_WriteIsochPipe_t)(
123     BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle,
124     ULONG                       Offset,
125     ULONG                       Length,
126     PULONG                      FrameNumber,
127 	LPOVERLAPPED                Overlapped
128 );
129 typedef WINBOOL (WINAPI * BTstack_WinUsb_WriteIsochPipeAsap_t)(
130     BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle,
131     ULONG                       Offset,
132     ULONG                       Length,
133     BOOL                        ContinueStream,
134 	LPOVERLAPPED                Overlapped
135 );
136 typedef WINBOOL (WINAPI * BTstack_WinUsb_UnregisterIsochBuffer_t)(
137 	BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle
138 );
139 typedef WINBOOL (WINAPI * BTstack_WinUsb_GetCurrentFrameNumber_t)(
140     WINUSB_INTERFACE_HANDLE     InterfaceHandle,        // MSDN lists 'Device handle returned from CreateFile'
141     PULONG                      CurrentFrameNumber,
142     LARGE_INTEGER               *TimeStamp
143 );
144 
145 static BTstack_WinUsb_QueryPipeEx_t 			BTstack_WinUsb_QueryPipeEx;
146 static BTstack_WinUsb_RegisterIsochBuffer_t 	BTstack_WinUsb_RegisterIsochBuffer;
147 static BTstack_WinUsb_ReadIsochPipe_t 			BTstack_WinUsb_ReadIsochPipe;
148 static BTstack_WinUsb_ReadIsochPipeAsap_t 		BTstack_WinUsb_ReadIsochPipeAsap;
149 static BTstack_WinUsb_WriteIsochPipe_t 			BTstack_WinUsb_WriteIsochPipe;
150 static BTstack_WinUsb_WriteIsochPipeAsap_t 		BTstack_WinUsb_WriteIsochPipeAsap;
151 static BTstack_WinUsb_UnregisterIsochBuffer_t 	BTstack_WinUsb_UnregisterIsochBuffer;
152 static BTstack_WinUsb_GetCurrentFrameNumber_t   BTstack_WinUsb_GetCurrentFrameNumber;
153 #endif
154 
155 // Doesn't work as expected
156 // #define SCHEDULE_SCO_IN_TRANSFERS_MANUALLY
157 
158 // Not tested yet
159 // #define SCHEDULE_SCO_OUT_TRANSFERS_MANUALLY
160 
161 //
162 // Bluetooth USB Transport Alternate Settings:
163 //
164 // 0: No active voice channels (for USB compliance)
165 // 1: One 8 kHz voice channel with 8-bit encoding
166 // 2: Two 8 kHz voice channels with 8-bit encoding or one 8 kHz voice channel with 16-bit encoding
167 // 3: Three 8 kHz voice channels with 8-bit encoding
168 // 4: Two 8 kHz voice channels with 16-bit encoding or one 16 kHz voice channel with 16-bit encoding
169 // 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
170 // --> support only a single SCO connection
171 #define ALT_SETTING (1)
172 
173 // alt setting for 1-3 connections and 8/16 bit
174 const int alt_setting_8_bit[]  = {1,2,3};
175 const int alt_setting_16_bit[] = {2,4,5};
176 
177 // for ALT_SETTING >= 1 and 8-bit channel, we need the following isochronous packets
178 // One complete SCO packet with 24 frames every 3 frames (== 3 ms)
179 #define NUM_ISO_PACKETS (3)
180 
181 const uint16_t iso_packet_size_for_alt_setting[] = {
182     0,
183     9,
184     17,
185     25,
186     33,
187     49,
188     63,
189 };
190 
191 // 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)
192 // 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
193 #define SCO_PACKET_SIZE  (49 * NUM_ISO_PACKETS)
194 
195 #define ISOC_BUFFERS   8
196 
197 // Outgoing SCO packet queue
198 // simplified ring buffer implementation
199 #define SCO_RING_BUFFER_COUNT  (20)
200 #define SCO_RING_BUFFER_SIZE (SCO_RING_BUFFER_COUNT * SCO_PACKET_SIZE)
201 
202 /** Request type bits of the "bmRequestType" field in control transfers. */
203 enum usb_request_type {
204 	USB_REQUEST_TYPE_STANDARD = (0x00 << 5),
205 	USB_REQUEST_TYPE_CLASS = (0x01 << 5),
206 	USB_REQUEST_TYPE_VENDOR = (0x02 << 5),
207 };
208 
209 /** Recipient bits of the "bmRequestType" field in control transfers. Values 4 through 31 are reserved. */
210 enum usb_request_recipient {
211 	USB_RECIPIENT_DEVICE = 0x00,
212 	USB_RECIPIENT_INTERFACE = 0x01,
213 	USB_RECIPIENT_ENDPOINT = 0x02,
214 	USB_RECIPIENT_OTHER = 0x03,
215 };
216 
217 // This is the GUID for the USB device class
218 static GUID GUID_DEVINTERFACE_USB_DEVICE =
219 { 0xA5DCBF10L, 0x6530, 0x11D2, { 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } };
220 
221 static void usb_dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
222 
223 static void (*packet_handler)(uint8_t packet_type, uint8_t *packet, uint16_t size) = &usb_dummy_handler;
224 
225 // endpoint addresses
226 static int event_in_addr;
227 static int acl_in_addr;
228 static int acl_out_addr;
229 static int sco_in_addr;
230 static int sco_out_addr;
231 
232 //
233 static HANDLE usb_device_handle;
234 static WINUSB_INTERFACE_HANDLE usb_interface_0_handle;
235 static WINUSB_INTERFACE_HANDLE usb_interface_1_handle;
236 static OVERLAPPED usb_overlapped_event_in;
237 static OVERLAPPED usb_overlapped_command_out;
238 static OVERLAPPED usb_overlapped_acl_in;
239 static OVERLAPPED usb_overlapped_acl_out;
240 static btstack_data_source_t usb_data_source_event_in;
241 static btstack_data_source_t usb_data_source_command_out;
242 static btstack_data_source_t usb_data_source_acl_in;
243 static btstack_data_source_t usb_data_source_acl_out;
244 
245 //
246 static int usb_command_out_active;
247 static int usb_acl_out_active;
248 
249 // buffer for HCI Events and ACL Packets
250 static uint8_t hci_event_in_buffer[2 + 255];
251 static uint8_t hci_acl_in_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + HCI_ACL_BUFFER_SIZE];
252 
253 // transport interface state
254 static int usb_transport_open;
255 
256 #ifdef ENABLE_SCO_OVER_HCI
257 
258 typedef enum {
259     H2_W4_SCO_HEADER = 1,
260     H2_W4_PAYLOAD,
261 } H2_SCO_STATE;
262 
263 // SCO Incoming Windows
264 static uint8_t hci_sco_in_buffer[ISOC_BUFFERS * SCO_PACKET_SIZE];
265 static BTSTACK_WINUSB_ISOCH_BUFFER_HANDLE hci_sco_in_buffer_handle;
266 static USBD_ISO_PACKET_DESCRIPTOR hci_sco_packet_descriptors[ISOC_BUFFERS * NUM_ISO_PACKETS];
267 static OVERLAPPED usb_overlapped_sco_in[ISOC_BUFFERS];
268 static int usb_sco_in_expected_transfer;
269 
270 // SCO Incoming Run Loop
271 static btstack_data_source_t usb_data_source_sco_in[ISOC_BUFFERS];
272 
273 // SCO Incoming HCI
274 static H2_SCO_STATE sco_state;
275 static uint8_t  sco_buffer[SCO_PACKET_SIZE];
276 static uint16_t sco_read_pos;
277 static uint16_t sco_bytes_to_read;
278 
279 // SCO Outgoing Windows
280 static BTSTACK_WINUSB_ISOCH_BUFFER_HANDLE hci_sco_out_buffer_handle;
281 static OVERLAPPED usb_overlapped_sco_out[SCO_RING_BUFFER_COUNT];
282 static int        sco_ring_transfers_active;
283 static int        usb_sco_out_expected_transfer;
284 
285 #ifdef SCHEDULE_SCO_IN_TRANSFERS_MANUALLY
286 // next tranfer
287 static ULONG sco_next_transfer_at_frame;
288 #endif
289 
290 // SCO Outgoing Run Loop
291 static btstack_data_source_t usb_data_source_sco_out[SCO_RING_BUFFER_COUNT];
292 
293 // SCO Outgoing HCI
294 static uint8_t  sco_ring_buffer[SCO_RING_BUFFER_SIZE];
295 static int      sco_ring_write;  // packet idx
296 
297 // SCO Reconfiguration - pause/resume
298 static uint16_t sco_voice_setting;
299 static int      sco_num_connections;
300 static int      sco_shutdown;
301 
302 static uint16_t iso_packet_size;
303 #endif
304 
305 // list of known devices, using VendorID/ProductID tuples
306 static const uint16_t known_bluetooth_devices[] = {
307     // BCM20702A0 - DeLOCK Bluetooth 4.0
308     0x0a5c, 0x21e8,
309     // BCM20702A0 - Asus BT400
310     0x0b05, 0x17cb,
311     // BCM20702B0 - Generic USB Detuned Class 1 @ 20 MHz
312     0x0a5c, 0x22be,
313     // nRF5x Zephyr USB HCI, e.g nRF52840-PCA10056
314     0x2fe3, 0x0100,
315     0x2fe3, 0x000b,
316 };
317 
318 static int num_known_devices = sizeof(known_bluetooth_devices) / sizeof(uint16_t) / 2;
319 
320 // known devices
321 typedef struct {
322     btstack_linked_item_t next;
323     uint16_t vendor_id;
324     uint16_t product_id;
325 } usb_known_device_t;
326 
327 static btstack_linked_list_t usb_knwon_devices;
328 
329 void hci_transport_usb_add_device(uint16_t vendor_id, uint16_t product_id) {
330     usb_known_device_t * device = malloc(sizeof(usb_known_device_t));
331     if (device != NULL) {
332         device->vendor_id = vendor_id;
333         device->product_id = product_id;
334         btstack_linked_list_add(&usb_knwon_devices, (btstack_linked_item_t *) device);
335     }
336 }
337 
338 static bool usb_is_vmware_bluetooth_adapter(const char * device_path){
339     // VMware Vendor ID 0e0f
340     const char * pos = strstr(device_path, "\\usb#vid_0e0f&pid");
341     return (pos > 0);
342 }
343 
344 static bool usb_device_path_match(uint16_t vendor_id, uint16_t product_id){
345     // construct pid/vid substring
346     char substring[20];
347     sprintf(substring, "vid_%04x&pid_%04x", vendor_id, product_id);
348     const char * pos = strstr(device_path, substring);
349     log_info("check %s in %s -> %p", substring, device_path, pos);
350     return (pos > 0);
351 }
352 
353 static bool usb_is_known_bluetooth_device(const char * device_path){
354     int i;
355     for (i=0; i<num_known_devices; i++){
356         if (usb_device_path_match( known_bluetooth_devices[i*2], known_bluetooth_devices[i*2+1])){
357             return true;
358         }
359     }
360     btstack_linked_list_iterator_t it;
361     btstack_linked_list_iterator_init(&it, &usb_knwon_devices);
362     while (btstack_linked_list_iterator_has_next(&it)) {
363         usb_known_device_t * device = (usb_known_device_t *) btstack_linked_list_iterator_next(&it);
364         if (usb_device_path_match( device->vendor_id, device->product_id)){
365             return true;
366         }
367     }
368     return false;
369 }
370 
371 #ifdef ENABLE_SCO_OVER_HCI
372 static void sco_ring_init(void){
373     sco_ring_write = 0;
374     sco_ring_transfers_active = 0;
375 }
376 static int sco_ring_have_space(void){
377     return sco_ring_transfers_active < SCO_RING_BUFFER_COUNT;
378 }
379 static void usb_sco_register_buffers(void){
380     BOOL result;
381     result = BTstack_WinUsb_RegisterIsochBuffer(usb_interface_1_handle, sco_in_addr, hci_sco_in_buffer, sizeof(hci_sco_in_buffer), &hci_sco_in_buffer_handle);
382     if (!result) {
383         log_error("usb_sco_register_buffers: register in buffer failed, error %lu", GetLastError());
384     }
385     log_info("hci_sco_in_buffer_handle %p", hci_sco_in_buffer_handle);
386 
387     result = BTstack_WinUsb_RegisterIsochBuffer(usb_interface_1_handle, sco_out_addr, sco_ring_buffer, sizeof(sco_ring_buffer), &hci_sco_out_buffer_handle);
388     if (!result) {
389         log_error("usb_sco_unregister_buffers: register out buffer failed, error %lu", GetLastError());
390     }
391     log_info("hci_sco_out_buffer_handle %p", hci_sco_out_buffer_handle);
392 }
393 static void usb_sco_unregister_buffers(void){
394     if (hci_sco_in_buffer_handle){
395         BTstack_WinUsb_UnregisterIsochBuffer(hci_sco_in_buffer_handle);
396         hci_sco_in_buffer_handle = NULL;
397     }
398     if (hci_sco_out_buffer_handle){
399         BTstack_WinUsb_UnregisterIsochBuffer(hci_sco_out_buffer_handle);
400         hci_sco_out_buffer_handle = NULL;
401     }
402 }
403 #endif
404 
405 static void usb_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
406     log_info("registering packet handler");
407     packet_handler = handler;
408 }
409 
410 static void usb_dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
411 }
412 
413 static void usb_init(const void *transport_config){
414 }
415 
416 static void usb_free_resources(void){
417 	if (usb_interface_1_handle){
418 		WinUsb_Free(usb_interface_1_handle);
419 		usb_interface_1_handle = NULL;
420 	}
421 
422 	if (usb_interface_0_handle){
423 		WinUsb_Free(usb_interface_0_handle);
424 		usb_interface_0_handle = NULL;
425 	}
426 
427 	if (usb_device_handle) {
428 		CloseHandle(usb_device_handle);
429 		usb_device_handle = NULL;
430 	}
431 
432 #ifdef ENABLE_SCO_OVER_HCI
433     usb_sco_unregister_buffers();
434 #endif
435 }
436 
437 static void usb_submit_event_in_transfer(void){
438 	// submit transfer
439 	BOOL result = WinUsb_ReadPipe(usb_interface_0_handle, event_in_addr, hci_event_in_buffer, sizeof(hci_event_in_buffer), NULL, &usb_overlapped_event_in);
440 	if (!result) {
441 		if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
442 	}
443 
444     // IO_PENDING -> wait for completed
445     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_event_in, DATA_SOURCE_CALLBACK_READ);
446     return;
447 
448 exit_on_error:
449 	log_error("usb_submit_event_in_transfer: winusb last error %lu", GetLastError());
450 }
451 
452 static void usb_submit_acl_in_transfer(void){
453 	// submit transfer
454 	BOOL result = WinUsb_ReadPipe(usb_interface_0_handle, acl_in_addr, hci_acl_in_buffer, sizeof(hci_acl_in_buffer), NULL, &usb_overlapped_acl_in);
455 	if (!result) {
456 		if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
457 	}
458 
459     // IO_PENDING -> wait for completed
460     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_acl_in, DATA_SOURCE_CALLBACK_READ);
461     return;
462 
463 exit_on_error:
464 	log_error("usb_submit_acl_in_transfer: winusb last error %lu", GetLastError());
465 }
466 
467 #ifdef ENABLE_SCO_OVER_HCI
468 #ifdef SCHEDULE_SCO_IN_TRANSFERS_MANUALLY
469 
470 // frame number gets updated
471 static void usb_submit_sco_in_transfer_at_frame(int i, ULONG * frame_number){
472 
473     if (sco_shutdown){
474         log_info("USB SCO Shutdown:: usb_submit_sco_in_transfer_at_frame called");
475         return;
476     }
477 
478     LARGE_INTEGER timestamp;
479     ULONG current_frame_number;
480     WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
481 
482     ULONG frame_before = *frame_number;
483 
484     BOOL result = BTstack_WinUsb_ReadIsochPipe(hci_sco_in_buffer_handle, i * SCO_PACKET_SIZE, iso_packet_size * NUM_ISO_PACKETS,
485         frame_number, NUM_ISO_PACKETS, &hci_sco_packet_descriptors[i * NUM_ISO_PACKETS], &usb_overlapped_sco_in[i]);
486 
487     // log_info("BTstack_WinUsb_ReadIsochPipe #%02u: current %lu, planned %lu - buffer %lu", i, current_frame_number, frame_before, frame_before - current_frame_number);
488 
489     if (!result) {
490         if (GetLastError() == ERROR_IO_PENDING) {
491         } else {
492             goto exit_on_error;
493         }
494     }
495 
496     return;
497 
498 exit_on_error:
499     log_error("usb_submit_sco_in_transfer: winusb last error %lu", GetLastError());
500 }
501 
502 #else
503 
504 static void usb_submit_sco_in_transfer_asap(int i, int continue_stream){
505 
506     if (sco_shutdown){
507         log_info("USB SCO Shutdown:: usb_submit_sco_in_transfer_at_frame called");
508         return;
509     }
510 
511     LARGE_INTEGER timestamp;
512     ULONG current_frame_number;
513     BTstack_WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
514 
515     // log_info("usb_submit_sco_in_transfer[%02u]: current frame %lu", i, current_frame_number);
516 
517     BOOL result = BTstack_WinUsb_ReadIsochPipeAsap(hci_sco_in_buffer_handle, i * SCO_PACKET_SIZE, iso_packet_size * NUM_ISO_PACKETS,
518         continue_stream, NUM_ISO_PACKETS, &hci_sco_packet_descriptors[i * NUM_ISO_PACKETS], &usb_overlapped_sco_in[i]);
519 
520     if (!result) {
521         if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
522     }
523 
524     return;
525 
526 exit_on_error:
527     log_error("usb_submit_sco_in_transfer: winusb last error %lu", GetLastError());
528 }
529 #endif
530 #endif
531 
532 static void usb_process_event_in(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) {
533 
534     btstack_run_loop_disable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
535 
536     DWORD bytes_read;
537     BOOL ok = WinUsb_GetOverlappedResult(usb_interface_0_handle, &usb_overlapped_event_in, &bytes_read, FALSE);
538     if(!ok){
539         DWORD err = GetLastError();
540         if (err == ERROR_IO_INCOMPLETE){
541             // IO_INCOMPLETE -> wait for completed
542             btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
543         } else {
544             log_error("usb_process_event_in: error reading");
545         }
546         return;
547     }
548 
549     // notify uppper
550     packet_handler(HCI_EVENT_PACKET, hci_event_in_buffer, bytes_read);
551 
552 	// re-submit transfer
553 	usb_submit_event_in_transfer();
554 }
555 
556 static void usb_process_acl_in(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) {
557 
558     btstack_run_loop_disable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
559 
560     DWORD bytes_read;
561     BOOL ok = WinUsb_GetOverlappedResult(usb_interface_0_handle, &usb_overlapped_acl_in, &bytes_read, FALSE);
562     if(!ok){
563         DWORD err = GetLastError();
564         if (err == ERROR_IO_INCOMPLETE){
565             // IO_INCOMPLETE -> wait for completed
566             btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
567         } else {
568             log_error("usb_process_acl_in: error reading");
569 
570             // Reset Pipe
571             err = WinUsb_ResetPipe(usb_interface_0_handle, acl_in_addr);
572             log_info("WinUsb_ResetPipe: result %u", (int) err);
573             if (err){
574                 log_info("WinUsb_ResetPipe error %u", (int) GetLastError());
575             }
576 
577             // re-submit transfer
578             usb_submit_acl_in_transfer();
579         }
580         return;
581     }
582 
583     // notify uppper
584     packet_handler(HCI_ACL_DATA_PACKET, hci_acl_in_buffer, bytes_read);
585 
586 	// re-submit transfer
587 	usb_submit_acl_in_transfer();
588 }
589 
590 #ifdef ENABLE_SCO_OVER_HCI
591 static void sco_state_machine_init(void){
592     sco_state = H2_W4_SCO_HEADER;
593     sco_read_pos = 0;
594     sco_bytes_to_read = 3;
595 }
596 
597 static void sco_handle_data(uint8_t * buffer, uint16_t size){
598 	// printf("sco_handle_data: state %u, pos %u, to read %u, size %u", sco_state, sco_read_pos, sco_bytes_to_read, size);
599     while (size){
600         if (size < sco_bytes_to_read){
601             // just store incomplete data
602             memcpy(&sco_buffer[sco_read_pos], buffer, size);
603             sco_read_pos      += size;
604             sco_bytes_to_read -= size;
605             return;
606         }
607         // copy requested data
608         memcpy(&sco_buffer[sco_read_pos], buffer, sco_bytes_to_read);
609         sco_read_pos += sco_bytes_to_read;
610         buffer       += sco_bytes_to_read;
611         size         -= sco_bytes_to_read;
612 
613         // chunk read successfully, next action
614         switch (sco_state){
615             case H2_W4_SCO_HEADER:
616                 sco_state = H2_W4_PAYLOAD;
617                 sco_bytes_to_read = sco_buffer[2];
618                 if (sco_bytes_to_read > (sizeof(sco_buffer)-3)){
619                 	log_error("sco_handle_data: sco packet len > packet size");
620 	                sco_state_machine_init();
621                 }
622                 break;
623             case H2_W4_PAYLOAD:
624                 // packet complete
625                 packet_handler(HCI_SCO_DATA_PACKET, sco_buffer, sco_read_pos);
626                 sco_state_machine_init();
627                 break;
628         }
629     }
630 }
631 
632 static void usb_process_sco_out(btstack_data_source_t *ds,  btstack_data_source_callback_type_t callback_type){
633 
634     btstack_run_loop_disable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_WRITE);
635 
636     if (sco_shutdown){
637         log_info("USB SCO Shutdown:: usb_process_sco_out called");
638         return;
639     }
640 
641     // get current frame number
642     ULONG current_frame_number;
643     LARGE_INTEGER timestamp;
644     BTstack_WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
645 
646     // find index
647     int transfer_index;
648     for (transfer_index=0;transfer_index<SCO_RING_BUFFER_COUNT;transfer_index++){
649         if (ds == &usb_data_source_sco_out[transfer_index]) break;
650     }
651 
652     // log_info("usb_process_sco_out[%02u] -- current frame %lu", transfer_index, current_frame_number);
653 
654     DWORD bytes_transferred;
655     BOOL ok = WinUsb_GetOverlappedResult(usb_interface_0_handle, &usb_overlapped_sco_out[transfer_index], &bytes_transferred, FALSE);
656     // log_info("usb_process_sco_out_done: #%u result %u, bytes %u, state %u", transfer_index, ok, (int) bytes_transferred, sco_state);
657     if(!ok){
658         DWORD err = GetLastError();
659         if (err == ERROR_IO_INCOMPLETE){
660             // IO_INCOMPLETE -> wait for completed
661             btstack_run_loop_enable_data_source_callbacks(&usb_data_source_sco_out[transfer_index], DATA_SOURCE_CALLBACK_WRITE);
662             return;
663         }
664         log_error("usb_process_sco_out_done[%02u]: error writing %u, Internal %x", transfer_index, (int) err, (int) usb_overlapped_sco_out[transfer_index].Internal);
665     }
666 
667     // decrease tab
668     sco_ring_transfers_active--;
669 
670     // enable next data source callback
671     if (sco_ring_transfers_active){
672         // update expected and wait for completion
673         usb_sco_out_expected_transfer = (transfer_index+ 1) % SCO_RING_BUFFER_COUNT;
674         // log_info("usb_process_sco_out_done[%02u]: wait for transfer %02u", transfer_index, usb_sco_out_expected_transfer);
675         btstack_run_loop_enable_data_source_callbacks(&usb_data_source_sco_out[usb_sco_out_expected_transfer], DATA_SOURCE_CALLBACK_WRITE);
676     }
677 
678     // log_info("usb_process_sco_out_done: transfers active %u", sco_ring_transfers_active);
679 
680     // mark free
681     if (sco_ring_have_space()) {
682         uint8_t event[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
683         packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
684     }
685 }
686 
687 static void usb_process_sco_in(btstack_data_source_t *ds,  btstack_data_source_callback_type_t callback_type){
688 
689     btstack_run_loop_disable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
690 
691     if (sco_shutdown){
692         log_info("USB SCO Shutdown: usb_process_sco_out called");
693         return;
694     }
695 
696     // find index
697     int i;
698     for (i=0;i<ISOC_BUFFERS;i++){
699         if (ds == &usb_data_source_sco_in[i]) break;
700     }
701     int transfer_index = i;
702 
703     // ULONG current_frame_number;
704     // LARGE_INTEGER timestamp;
705     // BTstack_WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
706 
707     // log_info("usb_process_sco_in[%02u] -- current frame %lu", transfer_index, current_frame_number);
708 
709     DWORD bytes_transferred;
710     BOOL ok = WinUsb_GetOverlappedResult(usb_interface_0_handle, &usb_overlapped_sco_in[transfer_index], &bytes_transferred, FALSE);
711 
712     if(!ok) {
713         DWORD err = GetLastError();
714         if (err == ERROR_IO_INCOMPLETE) {
715             // IO_INCOMPLETE -> wait for completed
716             btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
717             return;
718         }
719         log_error("usb_process_sco_in[%02u]: error reading %u, Internal %x", transfer_index, (int) err, (int) usb_overlapped_sco_out[i].Internal);
720     }
721 
722     if (ok){
723         for (i=0;i<NUM_ISO_PACKETS;i++){
724             USBD_ISO_PACKET_DESCRIPTOR * packet_descriptor = &hci_sco_packet_descriptors[transfer_index * NUM_ISO_PACKETS + i];
725             if (packet_descriptor->Length){
726                 uint8_t * iso_data = &hci_sco_in_buffer[transfer_index * SCO_PACKET_SIZE + packet_descriptor->Offset];
727                 uint16_t  iso_len  = packet_descriptor->Length;
728                 sco_handle_data(iso_data, iso_len);
729             }
730         }
731     }
732 
733 #ifdef SCHEDULE_SCO_IN_TRANSFERS_MANUALLY
734     usb_submit_sco_in_transfer_at_frame(i, &sco_next_transfer_at_frame);
735 #else
736     usb_submit_sco_in_transfer_asap(transfer_index, 1);
737 #endif
738     // update expected and wait for completion
739     usb_sco_in_expected_transfer = (transfer_index+ 1) % ISOC_BUFFERS;
740 
741     // log_info("usb_process_sco_in[%02u]: enable data source %02u", transfer_index, usb_sco_in_expected_transfer);
742     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_sco_in[usb_sco_in_expected_transfer], DATA_SOURCE_CALLBACK_READ);
743 }
744 #endif
745 
746 static void usb_process_command_out(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type){
747 
748     btstack_run_loop_disable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_WRITE);
749 
750     // update stata before submitting transfer
751     usb_command_out_active = 0;
752 
753     // notify upper stack that provided buffer can be used again
754     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
755     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
756 }
757 
758 static void usb_process_acl_out(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type){
759 
760     btstack_run_loop_disable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_WRITE);
761 
762     // update stata before submitting transfer
763     usb_acl_out_active = 0;
764 
765     // notify upper stack that provided buffer can be used again
766     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
767     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
768 }
769 
770 static BOOL usb_scan_for_bluetooth_endpoints(void) {
771     int i;
772     USB_INTERFACE_DESCRIPTOR usb_interface_descriptor;
773 
774     // reset
775     event_in_addr = 0;
776     acl_in_addr = 0;
777     acl_out_addr = 0;
778 
779     log_info("Scanning USB Entpoints:");
780 
781     // look for Event and ACL pipes on Interface #0
782     BOOL result = WinUsb_QueryInterfaceSettings(usb_interface_0_handle, 0, &usb_interface_descriptor);
783     if (!result) goto exit_on_error;
784     for (i=0;i<usb_interface_descriptor.bNumEndpoints;i++){
785         WINUSB_PIPE_INFORMATION pipe;
786         result = WinUsb_QueryPipe(
787                      usb_interface_0_handle,
788                      0,
789                      (UCHAR) i,
790                      &pipe);
791         if (!result) goto exit_on_error;
792         log_info("Interface #0, Alt #0, Pipe idx #%u: type %u, id 0x%02x, max packet size %u,",
793             i, pipe.PipeType, pipe.PipeId, pipe.MaximumPacketSize);
794         switch (pipe.PipeType){
795             case USB_ENDPOINT_TYPE_INTERRUPT:
796                 if (event_in_addr) continue;
797                 event_in_addr = pipe.PipeId;
798                 log_info("-> using 0x%2.2X for HCI Events", event_in_addr);
799                 break;
800             case USB_ENDPOINT_TYPE_BULK:
801                 if (pipe.PipeId & 0x80) {
802                     if (acl_in_addr) continue;
803                     acl_in_addr = pipe.PipeId;
804                     log_info("-> using 0x%2.2X for ACL Data In", acl_in_addr);
805                 } else {
806                     if (acl_out_addr) continue;
807                     acl_out_addr = pipe.PipeId;
808                     log_info("-> using 0x%2.2X for ACL Data Out", acl_out_addr);
809                 }
810                 break;
811             default:
812                 break;
813         }
814     }
815 
816 #ifdef ENABLE_SCO_OVER_HCI
817     sco_out_addr = 0;
818     sco_in_addr = 0;
819 
820     // look for SCO pipes on Interface #1, Alt Setting 1
821     int alt_setting = 1;
822     result = WinUsb_QueryInterfaceSettings(usb_interface_1_handle, alt_setting, &usb_interface_descriptor);
823     if (!result) goto exit_on_error;
824     for (i=0;i<usb_interface_descriptor.bNumEndpoints;i++){
825         BTSTACK_WINUSB_PIPE_INFORMATION_EX pipe;
826         result = BTstack_WinUsb_QueryPipeEx(
827                      usb_interface_1_handle,
828                      alt_setting,
829                      (UCHAR) i,
830                      &pipe);
831         if (!result) goto exit_on_error;
832         log_info("Interface #1, Alt #%u, Pipe idx #%u: type %u, id 0x%02x, max packet size %u, interval %u, max bytes per interval %u",
833             alt_setting, i, pipe.PipeType, pipe.PipeId, pipe.MaximumPacketSize, pipe.Interval, (int) pipe.MaximumBytesPerInterval);
834         switch (pipe.PipeType){
835             case USB_ENDPOINT_TYPE_ISOCHRONOUS:
836                 if (pipe.PipeId & 0x80) {
837                     if (sco_in_addr) continue;
838                     sco_in_addr = pipe.PipeId;
839                     log_info("-> using 0x%2.2X for SCO Data In", sco_in_addr);
840                 } else {
841                     if (sco_out_addr) continue;
842                     sco_out_addr = pipe.PipeId;
843                     log_info("-> using 0x%2.2X for SCO Data Out", sco_out_addr);
844                 }
845                 break;
846             default:
847                 break;
848         }
849     }
850     if (!sco_in_addr){
851         log_error("Couldn't find pipe for SCO IN!");
852         return FALSE;
853     }
854     if (!sco_out_addr){
855         log_error("Couldn't find pipe for SCO IN!");
856         return FALSE;
857     }
858 #endif
859 
860     // check if all found
861     if (!event_in_addr){
862         log_error("Couldn't find pipe for Event IN!");
863         return FALSE;
864     }
865     if (!acl_in_addr){
866         log_error("Couldn't find pipe for ACL IN!");
867         return FALSE;
868     }
869     if (!acl_out_addr){
870         log_error("Couldn't find pipe for ACL OUT!");
871         return FALSE;
872     }
873 
874     // all clear
875     return TRUE;
876 
877 exit_on_error:
878     log_error("usb_scan_for_bluetooth_endpoints: last error %lu", GetLastError());
879     return FALSE;
880 }
881 
882 #ifdef ENABLE_SCO_OVER_HCI
883 
884 static int usb_sco_start(void){
885     printf("usb_sco_start\n");
886     log_info("usb_sco_start");
887 
888     sco_shutdown = 0;
889 
890     sco_state_machine_init();
891     sco_ring_init();
892 
893     // calc alt setting
894     int alt_setting;
895     if (sco_voice_setting & 0x0020){
896         // 16-bit PCM
897         alt_setting = alt_setting_16_bit[sco_num_connections-1];
898     } else {
899         // 8-bit PCM or mSBC
900         alt_setting = alt_setting_8_bit[sco_num_connections-1];
901     }
902 
903     log_info("Switching to setting %u on interface 1..", alt_setting);
904     // WinUsb_SetCurrentAlternateSetting returns TRUE if the operation succeeds.
905     BOOL result = WinUsb_SetCurrentAlternateSetting(usb_interface_1_handle, alt_setting);
906     if (!result) goto exit_on_error;
907 
908     // derive iso packet size from alt setting
909     iso_packet_size = iso_packet_size_for_alt_setting[alt_setting];
910 
911     // register isochronous buffer after setting alternate setting
912     usb_sco_register_buffers();
913 
914 #ifdef SCHEDULE_SCO_IN_TRANSFERS_MANUALLY
915     // get current frame number
916     ULONG current_frame_number;
917     LARGE_INTEGER timestamp;
918     BTstack_WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
919     // plan for next tranfer
920     sco_next_transfer_at_frame = current_frame_number + ISOC_BUFFERS * NUM_ISO_PACKETS;
921 #endif
922 
923     int i;
924     for (i=0;i<ISOC_BUFFERS;i++){
925 #ifdef SCHEDULE_SCO_IN_TRANSFERS_MANUALLY
926         usb_submit_sco_in_transfer_at_frame(i, &sco_next_transfer_at_frame);
927 #else
928         usb_submit_sco_in_transfer_asap(i, 0);
929 #endif
930     }
931 
932     usb_sco_in_expected_transfer = 0;
933 
934     // only await first transfer to return
935     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_sco_in[usb_sco_in_expected_transfer], DATA_SOURCE_CALLBACK_READ);
936     return 1;
937 
938 exit_on_error:
939     log_error("usb_sco_start: last error %lu", GetLastError());
940     usb_free_resources();
941     return 0;
942 }
943 
944 static void usb_sco_stop(void){
945     printf("usb_sco_stop\n");
946     log_info("usb_sco_stop");
947 
948     sco_shutdown = 1;
949 
950     // abort SCO transfers
951     WinUsb_AbortPipe(usb_interface_0_handle, sco_in_addr);
952     WinUsb_AbortPipe(usb_interface_0_handle, sco_out_addr);
953 
954     // unlock/free SCO buffers
955     usb_sco_unregister_buffers();
956 
957     int alt_setting = 0;
958     log_info("Switching to setting %u on interface 1..", alt_setting);
959     // WinUsb_SetCurrentAlternateSetting returns TRUE if the operation succeeds.
960     WinUsb_SetCurrentAlternateSetting(usb_interface_1_handle, alt_setting);
961 }
962 #endif
963 
964 // returns 0 if successful, -1 otherwise
965 static int usb_try_open_device(const char * device_path){
966 
967 	// open file
968 	usb_device_handle = CreateFile(device_path,
969 		GENERIC_WRITE | GENERIC_READ,
970         FILE_SHARE_WRITE | FILE_SHARE_READ,
971         NULL,
972         OPEN_EXISTING,
973         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
974         NULL);
975 	log_info("Opening USB device: %p", usb_device_handle);
976 	if (!usb_device_handle) goto exit_on_error;
977 
978 	// WinUsb_Initialize returns TRUE if the operation succeed
979 	BOOL result = WinUsb_Initialize(usb_device_handle, &usb_interface_0_handle);
980 	if (!result) goto exit_on_error;
981 
982     // Detect USB Dongle based Class, Subclass, and Protocol
983     // The class code (bDeviceClass) is 0xE0 – Wireless Controller.
984     // The SubClass code (bDeviceSubClass) is 0x01 – RF Controller.
985     // The Protocol code (bDeviceProtocol) is 0x01 – Bluetooth programming.
986     USB_INTERFACE_DESCRIPTOR usb_interface_descriptor;
987     result = WinUsb_QueryInterfaceSettings(usb_interface_0_handle, 0, &usb_interface_descriptor);
988     if (!result) goto exit_on_error;
989 
990     // ignore virtual Bluetooth adapter of VMware
991     if (usb_is_vmware_bluetooth_adapter(device_path)) {
992         log_info("Ignoring simulated VMware Bluetooth adapter");
993         usb_free_resources();
994         return -1;
995     }
996 
997     //
998     if (usb_interface_descriptor.bInterfaceClass    != 0xe0 ||
999         usb_interface_descriptor.bInterfaceSubClass != 0x01 ||
1000         usb_interface_descriptor.bInterfaceProtocol != 0x01){
1001 
1002         // check whitelist
1003         if (!usb_is_known_bluetooth_device(device_path)){
1004             log_info("Class, Subclass, Protocol does not match Bluetooth device");
1005             usb_free_resources();
1006             return 0;
1007         }
1008     }
1009 
1010 #ifdef ENABLE_SCO_OVER_HCI
1011 	log_info("Claiming interface 1...");
1012 	// WinUsb_GetAssociatedInterface returns TRUE if the operation succeeds.
1013 	// We use index 1 - assuming it refers to interface #1 with libusb
1014 	// A value of 0 indicates the first associated interface, a value of 1 indicates the second associated interface, and so on.
1015 	result = WinUsb_GetAssociatedInterface(usb_interface_0_handle, 0, &usb_interface_1_handle);
1016 	if (!result) goto exit_on_error;
1017 	log_info("Claiming interface 1: success");
1018 #endif
1019 
1020     result = usb_scan_for_bluetooth_endpoints();
1021     if (!result) {
1022         log_error("Could not find all Bluetooth Endpoints!");
1023         usb_free_resources();
1024         return 0;
1025     }
1026 
1027 #ifdef ENABLE_SCO_OVER_HCI
1028     int i;
1029 
1030 	memset(hci_sco_packet_descriptors, 0, sizeof(hci_sco_packet_descriptors));
1031 	log_info("Size of packet descriptors for SCO IN%u", (int) sizeof(hci_sco_packet_descriptors));
1032 
1033 	// setup async io && btstack handler
1034 	memset(&usb_overlapped_sco_in, 0, sizeof(usb_overlapped_sco_in));
1035 	for (i=0;i<ISOC_BUFFERS;i++){
1036 		usb_overlapped_sco_in[i].hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1037 		// log_info_hexdump(&usb_overlapped_sco_in[i], sizeof(OVERLAPPED));
1038         // log_info("data source SCO in %u, handle %p", i, usb_overlapped_sco_in[i].hEvent);
1039 		usb_data_source_sco_in[i].source.handle = usb_overlapped_sco_in[i].hEvent;
1040 	    btstack_run_loop_set_data_source_handler(&usb_data_source_sco_in[i], &usb_process_sco_in);
1041         btstack_run_loop_add_data_source(&usb_data_source_sco_in[i]);
1042 	}
1043 
1044     memset(&usb_overlapped_sco_out, 0, sizeof(usb_overlapped_sco_out));
1045     for (i=0;i<SCO_RING_BUFFER_COUNT;i++){
1046         usb_overlapped_sco_out[i].hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1047         // log_info("data source SCO out %u, handle %p", i, usb_overlapped_sco_out[i].hEvent);
1048         usb_data_source_sco_out[i].source.handle = usb_overlapped_sco_out[i].hEvent;
1049         btstack_run_loop_set_data_source_handler(&usb_data_source_sco_out[i], &usb_process_sco_out);
1050         btstack_run_loop_add_data_source(&usb_data_source_sco_out[i]);
1051     }
1052 #endif
1053 
1054 	// setup async io
1055     memset(&usb_overlapped_event_in,     0, sizeof(usb_overlapped_event_in));
1056     memset(&usb_overlapped_command_out,  0, sizeof(usb_overlapped_command_out));
1057     memset(&usb_overlapped_acl_out,      0, sizeof(usb_overlapped_acl_out));
1058     memset(&usb_overlapped_acl_in,       0, sizeof(usb_overlapped_acl_in));
1059     usb_overlapped_event_in.hEvent    = CreateEvent(NULL, TRUE, FALSE, NULL);
1060     usb_overlapped_command_out.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1061     usb_overlapped_acl_in.hEvent      = CreateEvent(NULL, TRUE, FALSE, NULL);
1062     usb_overlapped_acl_out.hEvent     = CreateEvent(NULL, TRUE, FALSE, NULL);
1063 
1064 	// setup btstack data soures
1065     usb_data_source_event_in.source.handle = usb_overlapped_event_in.hEvent;
1066     btstack_run_loop_set_data_source_handler(&usb_data_source_event_in, &usb_process_event_in);
1067     btstack_run_loop_add_data_source(&usb_data_source_event_in);
1068 
1069     usb_data_source_command_out.source.handle = usb_overlapped_command_out.hEvent;
1070     btstack_run_loop_set_data_source_handler(&usb_data_source_command_out, &usb_process_command_out);
1071     btstack_run_loop_add_data_source(&usb_data_source_command_out);
1072 
1073     usb_data_source_acl_in.source.handle = usb_overlapped_acl_in.hEvent;
1074     btstack_run_loop_set_data_source_handler(&usb_data_source_acl_in, &usb_process_acl_in);
1075     btstack_run_loop_add_data_source(&usb_data_source_acl_in);
1076 
1077     usb_data_source_acl_out.source.handle = usb_overlapped_acl_out.hEvent;
1078     btstack_run_loop_set_data_source_handler(&usb_data_source_acl_out, &usb_process_acl_out);
1079     btstack_run_loop_add_data_source(&usb_data_source_acl_out);
1080 
1081     // submit all incoming transfers
1082     usb_submit_event_in_transfer();
1083     usb_submit_acl_in_transfer();
1084 	return 1;
1085 
1086 exit_on_error:
1087 	log_error("usb_try_open_device: last error %lu", GetLastError());
1088 	usb_free_resources();
1089 	return 0;
1090 }
1091 
1092 #ifdef ENABLE_SCO_OVER_HCI
1093 
1094 #define WinUSB_Lookup(fn) do { BTstack_##fn = (BTstack_##fn##_t) GetProcAddress(h, #fn); log_info("%-30s %p", #fn, BTstack_##fn); if (!BTstack_##fn) return FALSE; } while(0)
1095 
1096 static BOOL usb_lookup_symbols(void){
1097 	// lookup runtime symbols missing in current mingw64 distribution
1098 	HMODULE h = GetModuleHandleA("WinUSB");
1099 	log_info("%-30s %p", "WinUSB", h);
1100 	WinUSB_Lookup(WinUsb_QueryPipeEx);
1101 	WinUSB_Lookup(WinUsb_RegisterIsochBuffer);
1102 	WinUSB_Lookup(WinUsb_ReadIsochPipe);
1103 	WinUSB_Lookup(WinUsb_ReadIsochPipeAsap);
1104 	WinUSB_Lookup(WinUsb_WriteIsochPipe);
1105 	WinUSB_Lookup(WinUsb_WriteIsochPipeAsap);
1106 	WinUSB_Lookup(WinUsb_UnregisterIsochBuffer);
1107     WinUSB_Lookup(WinUsb_GetCurrentFrameNumber);
1108     return TRUE;
1109 }
1110 #endif
1111 
1112 // returns 0 on success, -1 otherwise
1113 static int usb_open(void){
1114 
1115     if (usb_transport_open) return 0;
1116 
1117     int r = -1;
1118 
1119 #ifdef ENABLE_SCO_OVER_HCI
1120 	BOOL ok = usb_lookup_symbols();
1121     if (!ok){
1122         log_error("usb_open: Failed to lookup WinSUB ISOCHRONOUS functions. Please disable ENABLE_SCO_OVER_HCI or use Windows 8.1 or higher");
1123         return r;
1124     }
1125     sco_state_machine_init();
1126     sco_ring_init();
1127 #endif
1128 
1129 	HDEVINFO                         hDevInfo;
1130 	SP_DEVICE_INTERFACE_DATA         DevIntfData;
1131 	PSP_DEVICE_INTERFACE_DETAIL_DATA DevIntfDetailData;
1132 	SP_DEVINFO_DATA                  DevData;
1133 
1134 	DWORD dwSize;
1135 	DWORD dwMemberIdx;
1136 
1137     // default endpoint addresses
1138     event_in_addr = 0x81; // EP1, IN interrupt
1139     acl_in_addr =   0x82; // EP2, IN bulk
1140     acl_out_addr =  0x02; // EP2, OUT bulk
1141     sco_in_addr  =  0x83; // EP3, IN isochronous
1142     sco_out_addr =  0x03; // EP3, OUT isochronous
1143 
1144 	// We will try to get device information set for all USB devices that have a
1145 	// device interface and are currently present on the system (plugged in).
1146 	hDevInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_USB_DEVICE, NULL, 0, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
1147 
1148 	log_info("usb_open: SetupDiGetClassDevs -> %p", hDevInfo);
1149 	if (hDevInfo == INVALID_HANDLE_VALUE) return -1;
1150 
1151 	// Prepare to enumerate all device interfaces for the device information
1152 	// set that we retrieved with SetupDiGetClassDevs(..)
1153 	DevIntfData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
1154 	dwMemberIdx = 0;
1155 
1156 	// Next, we will keep calling this SetupDiEnumDeviceInterfaces(..) until this
1157 	// function causes GetLastError() to return  ERROR_NO_MORE_ITEMS. With each
1158 	// call the dwMemberIdx value needs to be incremented to retrieve the next
1159 	// device interface information.
1160 
1161 	SetupDiEnumDeviceInterfaces(hDevInfo, NULL, (LPGUID) &GUID_DEVINTERFACE_USB_DEVICE,
1162 		dwMemberIdx, &DevIntfData);
1163 
1164 	while(GetLastError() != ERROR_NO_MORE_ITEMS){
1165 
1166 		// As a last step we will need to get some more details for each
1167 		// of device interface information we are able to retrieve. This
1168 		// device interface detail gives us the information we need to identify
1169 		// the device (VID/PID), and decide if it's useful to us. It will also
1170 		// provide a DEVINFO_DATA structure which we can use to know the serial
1171 		// port name for a virtual com port.
1172 
1173 		DevData.cbSize = sizeof(DevData);
1174 
1175 		// Get the required buffer size. Call SetupDiGetDeviceInterfaceDetail with
1176 		// a NULL DevIntfDetailData pointer, a DevIntfDetailDataSize
1177 		// of zero, and a valid RequiredSize variable. In response to such a call,
1178 		// this function returns the required buffer size at dwSize.
1179 
1180 		SetupDiGetDeviceInterfaceDetail(
1181 			  hDevInfo, &DevIntfData, NULL, 0, &dwSize, NULL);
1182 
1183 		// Allocate memory for the DeviceInterfaceDetail struct. Don't forget to
1184 		// deallocate it later!
1185 		DevIntfDetailData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwSize);
1186 		DevIntfDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
1187 
1188 		if (SetupDiGetDeviceInterfaceDetail(hDevInfo, &DevIntfData,
1189 			DevIntfDetailData, dwSize, &dwSize, &DevData))
1190 		{
1191 			// Finally we can start checking if we've found a useable device,
1192 			// by inspecting the DevIntfDetailData->DevicePath variable.
1193 			// The DevicePath looks something like this:
1194 			//
1195 			// \\?\usb#vid_04d8&pid_0033#5&19f2438f&0&2#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
1196 			//
1197 
1198 			log_info("usb_open: Device Path: %s", DevIntfDetailData->DevicePath);
1199 
1200 #if 0
1201             // check for hard-coded vendor/product ids
1202 			char vid_pid_match[30];
1203 			uint16_t vid = 0x0a12;
1204 			uint16_t pid = 0x0001;
1205 			sprintf(vid_pid_match, "\\\\?\\usb#vid_%04x&pid_%04x", vid, pid);
1206 			if (strncmp(DevIntfDetailData->DevicePath, &vid_pid_match[0], strlen(vid_pid_match)) == 0 ){
1207 				log_info("Matched search string %s", vid_pid_match);
1208 
1209 				BOOL result = usb_try_open_device(DevIntfDetailData->DevicePath);
1210 				if (result){
1211 					log_info("usb_open: Device opened, stop scanning");
1212 					r = 0;
1213 				} else {
1214 					log_error("usb_open: Device open failed");
1215 				}
1216 			}
1217 #endif
1218 
1219             // try all devices
1220             BOOL result = usb_try_open_device(DevIntfDetailData->DevicePath);
1221             if (result){
1222                 log_info("usb_open: Device opened, stop scanning");
1223                 r = 0;
1224             } else {
1225                 log_error("usb_open: Device open failed");
1226             }
1227         }
1228 		HeapFree(GetProcessHeap(), 0, DevIntfDetailData);
1229 
1230 		if (r == 0) break;
1231 
1232 		// Continue looping
1233 		SetupDiEnumDeviceInterfaces(
1234 			hDevInfo, NULL, &GUID_DEVINTERFACE_USB_DEVICE, ++dwMemberIdx, &DevIntfData);
1235 	}
1236 
1237 	SetupDiDestroyDeviceInfoList(hDevInfo);
1238 
1239 	log_info("usb_open: done, r = %x", r);
1240 
1241     if (r == 0){
1242         // opened
1243         usb_transport_open = 1;
1244     }
1245 
1246     return r;
1247 }
1248 
1249 static int usb_close(void){
1250 
1251     if (!usb_transport_open) return 0;
1252 
1253     // remove data sources
1254     btstack_run_loop_remove_data_source(&usb_data_source_command_out);
1255     btstack_run_loop_remove_data_source(&usb_data_source_event_in);
1256     btstack_run_loop_remove_data_source(&usb_data_source_acl_in);
1257     btstack_run_loop_remove_data_source(&usb_data_source_acl_out);
1258 
1259 #ifdef ENABLE_SCO_OVER_HCI
1260     int i;
1261     for (i=0;i<ISOC_BUFFERS;i++){
1262         btstack_run_loop_remove_data_source(&usb_data_source_sco_in[i]);
1263     }
1264     for (i=0;i<SCO_RING_BUFFER_COUNT;i++){
1265         btstack_run_loop_remove_data_source(&usb_data_source_sco_out[i]);
1266     }
1267 #endif
1268 
1269     log_info("usb_close abort event and acl pipes");
1270 
1271     // stop transfers
1272     WinUsb_AbortPipe(usb_interface_0_handle, event_in_addr);
1273     WinUsb_AbortPipe(usb_interface_0_handle, acl_in_addr);
1274     WinUsb_AbortPipe(usb_interface_0_handle, acl_out_addr);
1275 #ifdef ENABLE_SCO_OVER_HCI
1276     usb_sco_stop();
1277 #endif
1278     usb_acl_out_active = 0;
1279 
1280     // control transfer cannot be stopped, just wait for completion
1281     if (usb_command_out_active){
1282         log_info("usb_close command out active, wait for complete");
1283         DWORD bytes_transferred;
1284         WinUsb_GetOverlappedResult(usb_interface_0_handle, &usb_overlapped_command_out, &bytes_transferred, TRUE);
1285         usb_command_out_active = 0;
1286     }
1287 
1288     log_info("usb_close free resources");
1289 
1290     // free everything
1291     usb_free_resources();
1292 
1293     // transport closed
1294     usb_transport_open = 0;
1295 
1296     return 0;
1297 }
1298 
1299 static int usb_can_send_packet_now(uint8_t packet_type){
1300     // return 0;
1301     switch (packet_type){
1302         case HCI_COMMAND_DATA_PACKET:
1303             return !usb_command_out_active;
1304         case HCI_ACL_DATA_PACKET:
1305             return !usb_acl_out_active;
1306 #ifdef ENABLE_SCO_OVER_HCI
1307         case HCI_SCO_DATA_PACKET:
1308             // return 0;
1309             return sco_ring_have_space();
1310 #endif
1311         default:
1312             return 0;
1313     }
1314 }
1315 
1316 static int usb_send_cmd_packet(uint8_t *packet, int size){
1317 
1318     // update stata before submitting transfer
1319     usb_command_out_active = 1;
1320 
1321 	// Start trasnsfer
1322 	WINUSB_SETUP_PACKET setup_packet;
1323 	memset(&setup_packet, 0, sizeof(setup_packet));
1324 	setup_packet.RequestType =  USB_REQUEST_TYPE_CLASS | USB_RECIPIENT_INTERFACE;
1325 	setup_packet.Length = sizeof(size);
1326 	BOOL result = WinUsb_ControlTransfer(usb_interface_0_handle, setup_packet, packet, size,  NULL, &usb_overlapped_command_out);
1327 	if (!result) {
1328 		if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
1329 	}
1330 
1331     // IO_PENDING -> wait for completed
1332     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_command_out, DATA_SOURCE_CALLBACK_WRITE);
1333 
1334     return 0;
1335 
1336 exit_on_error:
1337 	log_error("winusb: last error %lu", GetLastError());
1338 	return -1;
1339 }
1340 
1341 static int usb_send_acl_packet(uint8_t *packet, int size){
1342 
1343     // update stata before submitting transfer
1344     usb_acl_out_active = 1;
1345 
1346 	// Start trasnsfer
1347 	BOOL ok = WinUsb_WritePipe(usb_interface_0_handle, acl_out_addr, packet, size,  NULL, &usb_overlapped_acl_out);
1348 	if (!ok) {
1349 		if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
1350 	}
1351 
1352     // IO_PENDING -> wait for completed
1353     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_acl_out, DATA_SOURCE_CALLBACK_WRITE);
1354     return 0;
1355 
1356 exit_on_error:
1357 	log_error("winusb: last error %lu", GetLastError());
1358 	return -1;
1359 }
1360 
1361 #ifdef ENABLE_SCO_OVER_HCI
1362 static int usb_send_sco_packet(uint8_t *packet, int size){
1363 
1364     if (size > SCO_PACKET_SIZE){
1365         log_error("usb_send_sco_packet: size %u > SCO_PACKET_SIZE %u", size, SCO_PACKET_SIZE);
1366         return -1;
1367     }
1368 
1369     // get current frame number
1370     ULONG current_frame_number;
1371     LARGE_INTEGER timestamp;
1372     BTstack_WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
1373 
1374     // store packet in free slot
1375     int transfer_index = sco_ring_write;
1376     uint8_t * data = &sco_ring_buffer[transfer_index * SCO_PACKET_SIZE];
1377     memcpy(data, packet, size);
1378 
1379 
1380     // setup transfer
1381     int continue_stream = sco_ring_transfers_active > 0;
1382     BOOL ok = BTstack_WinUsb_WriteIsochPipeAsap(hci_sco_out_buffer_handle, transfer_index * SCO_PACKET_SIZE, size, continue_stream, &usb_overlapped_sco_out[transfer_index]);
1383     // log_info("usb_send_sco_packet: using slot #%02u, current frame %lu, continue stream %u, ok %u", transfer_index, current_frame_number, continue_stream, ok);
1384     if (!ok) {
1385         if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
1386     }
1387 
1388     // successful started transfer, enable data source callback if first active transfer
1389     if (sco_ring_transfers_active == 0){
1390         usb_sco_out_expected_transfer = transfer_index;
1391         btstack_run_loop_enable_data_source_callbacks(&usb_data_source_sco_out[transfer_index], DATA_SOURCE_CALLBACK_WRITE);
1392     }
1393 
1394     // mark slot as full
1395     sco_ring_write = (sco_ring_write + 1) % SCO_RING_BUFFER_COUNT;
1396     sco_ring_transfers_active++;
1397 
1398     // notify upper stack that provided buffer can be used again
1399     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
1400     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
1401 
1402     // log_info("usb_send_sco_packet: transfers active %u", sco_ring_transfers_active);
1403 
1404     // and if we have more space for SCO packets
1405     if (sco_ring_have_space()) {
1406         uint8_t event_sco[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
1407         packet_handler(HCI_EVENT_PACKET, &event_sco[0], sizeof(event_sco));
1408     }
1409     return 0;
1410 
1411 exit_on_error:
1412     log_error("usb_send_sco_packet: last error %lu", GetLastError());
1413     return -1;
1414 }
1415 #endif
1416 
1417 static int usb_send_packet(uint8_t packet_type, uint8_t * packet, int size){
1418     switch (packet_type){
1419         case HCI_COMMAND_DATA_PACKET:
1420             return usb_send_cmd_packet(packet, size);
1421         case HCI_ACL_DATA_PACKET:
1422             return usb_send_acl_packet(packet, size);
1423 #ifdef ENABLE_SCO_OVER_HCI
1424         case HCI_SCO_DATA_PACKET:
1425             return usb_send_sco_packet(packet, size);
1426 #endif
1427         default:
1428             return -1;
1429     }
1430 }
1431 
1432 #ifdef ENABLE_SCO_OVER_HCI
1433 static void usb_set_sco_config(uint16_t voice_setting, int num_connections){
1434     log_info("usb_set_sco_config: voice settings 0x%04x, num connections %u", voice_setting, num_connections);
1435 
1436     if (num_connections != sco_num_connections){
1437         sco_voice_setting = voice_setting;
1438         if (sco_num_connections){
1439            usb_sco_stop();
1440         }
1441         sco_num_connections = num_connections;
1442         if (num_connections){
1443            usb_sco_start();
1444         }
1445     }
1446 }
1447 #endif
1448 
1449 // get usb singleton
1450 static const hci_transport_t hci_transport_usb = {
1451     /* const char * name; */                                        "H2_WINUSB",
1452     /* void   (*init) (const void *transport_config); */            &usb_init,
1453     /* int    (*open)(void); */                                     &usb_open,
1454     /* int    (*close)(void); */                                    &usb_close,
1455     /* void   (*register_packet_handler)(void (*handler)(...); */   &usb_register_packet_handler,
1456     /* int    (*can_send_packet_now)(uint8_t packet_type); */       &usb_can_send_packet_now,
1457     /* int    (*send_packet)(...); */                               &usb_send_packet,
1458     /* int    (*set_baudrate)(uint32_t baudrate); */                NULL,
1459     /* void   (*reset_link)(void); */                               NULL,
1460 #ifdef ENABLE_SCO_OVER_HCI
1461     /* void   (*set_sco_config)(uint16_t voice_setting, int num_connections); */ usb_set_sco_config,
1462 #else
1463     /* void   (*set_sco_config)(uint16_t voice_setting, int num_connections); */ NULL,
1464 #endif
1465 };
1466 
1467 const hci_transport_t * hci_transport_usb_instance(void) {
1468     return &hci_transport_usb;
1469 }
1470