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