3 * Low-level USB interface glue towards libusb.
5 * Copyright (C) 2005-2007 Richard A. Low <richard@wentnet.com>
6 * Copyright (C) 2005-2012 Linus Walleij <triad@df.lth.se>
7 * Copyright (C) 2006-2011 Marcus Meissner
8 * Copyright (C) 2007 Ted Bullock
9 * Copyright (C) 2008 Chris Bagwell <chris@cnpbagwell.com>
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the
23 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 * Boston, MA 02111-1307, USA.
26 * Created by Richard Low on 24/12/2005. (as mtp-utils.c)
27 * Modified by Linus Walleij 2006-03-06
28 * (Notice that Anglo-Saxons use little-endian dates and Swedes
29 * use big-endian dates.)
32 #include "../config.h"
34 #include "libusb-glue.h"
35 #include "device-flags.h"
48 /* Aha, older libusb does not have USB_CLASS_PTP */
50 #define USB_CLASS_PTP 6
54 * Default USB timeout length. This can be overridden as needed
55 * but should start with a reasonable value so most common
56 * requests can be completed. The original value of 4000 was
57 * not long enough for large file transfer. Also, players can
58 * spend a bit of time collecting data. Higher values also
59 * make connecting/disconnecting more reliable.
61 #define USB_TIMEOUT_DEFAULT 20000
62 #define USB_TIMEOUT_LONG 60000
64 static inline int get_timeout(PTP_USB* ptp_usb) {
65 if (FLAG_LONG_TIMEOUT(ptp_usb)) {
66 return USB_TIMEOUT_LONG;
68 return USB_TIMEOUT_DEFAULT;
71 /* USB Feature selector HALT */
72 #ifndef USB_FEATURE_HALT
73 #define USB_FEATURE_HALT 0x00
76 /* Internal data types */
77 struct mtpdevice_list_struct {
78 openusb_dev_handle_t device;
81 uint32_t bus_location;
82 struct mtpdevice_list_struct *next;
84 typedef struct mtpdevice_list_struct mtpdevice_list_t;
86 static const LIBMTP_device_entry_t mtp_device_table[] = {
87 /* We include an .h file which is shared between us and libgphoto2 */
88 #include "music-players.h"
90 static const int mtp_device_table_size = sizeof (mtp_device_table) / sizeof (LIBMTP_device_entry_t);
93 static void init_usb();
94 static void close_usb(PTP_USB* ptp_usb);
95 static int find_interface_and_endpoints(openusb_dev_handle_t *dev,
102 int* outep_maxpacket,
104 static void clear_stall(PTP_USB* ptp_usb);
105 static int init_ptp_usb(PTPParams* params, PTP_USB* ptp_usb, openusb_dev_handle_t * dev);
106 static short ptp_write_func(unsigned long, PTPDataHandler*, void *data, unsigned long*);
107 static short ptp_read_func(unsigned long, PTPDataHandler*, void *data, unsigned long*, int);
108 static int usb_get_endpoint_status(PTP_USB* ptp_usb, int ep, uint16_t* status);
110 // Local USB handles.
111 static openusb_handle_t libmtp_openusb_handle;
114 * Get a list of the supported USB devices.
116 * The developers depend on users of this library to constantly
117 * add in to the list of supported devices. What we need is the
118 * device name, USB Vendor ID (VID) and USB Product ID (PID).
119 * put this into a bug ticket at the project homepage, please.
120 * The VID/PID is used to let e.g. udev lift the device to
121 * console userspace access when it's plugged in.
123 * @param devices a pointer to a pointer that will hold a device
124 * list after the call to this function, if it was
126 * @param numdevs a pointer to an integer that will hold the number
127 * of devices in the device list if the call was successful.
128 * @return 0 if the list was successfull retrieved, any other
129 * value means failure.
131 int LIBMTP_Get_Supported_Devices_List(LIBMTP_device_entry_t * * const devices, int * const numdevs) {
132 *devices = (LIBMTP_device_entry_t *) & mtp_device_table;
133 *numdevs = mtp_device_table_size;
137 static void init_usb() {
138 openusb_init(NULL, &libmtp_openusb_handle);
142 * Small recursive function to append a new usb_device to the linked list of
144 * @param devlist dynamic linked list of pointers to usb devices with MTP
145 * properties, to be extended with new device.
146 * @param newdevice the new device to add.
147 * @param bus_location bus for this device.
148 * @return an extended array or NULL on failure.
150 static mtpdevice_list_t *append_to_mtpdevice_list(mtpdevice_list_t *devlist,
151 openusb_dev_handle_t *newdevice,
153 uint32_t bus_location) {
154 mtpdevice_list_t *new_list_entry;
156 new_list_entry = (mtpdevice_list_t *) malloc(sizeof (mtpdevice_list_t));
157 if (new_list_entry == NULL) {
160 // Fill in USB device, if we *HAVE* to make a copy of the device do it here.
161 new_list_entry->device = *newdevice;
162 new_list_entry->bus_location = bus_location;
163 new_list_entry->next = NULL;
165 if (devlist == NULL) {
166 return new_list_entry;
168 mtpdevice_list_t *tmp = devlist;
169 while (tmp->next != NULL) {
172 tmp->next = new_list_entry;
178 * Small recursive function to free dynamic memory allocated to the linked list
180 * @param devlist dynamic linked list of pointers to usb devices with MTP
184 static void free_mtpdevice_list(mtpdevice_list_t *devlist) {
185 mtpdevice_list_t *tmplist = devlist;
189 while (tmplist != NULL) {
190 mtpdevice_list_t *tmp = tmplist;
191 tmplist = tmplist->next;
192 // Do not free() the fields (ptp_usb, params)! These are used elsewhere.
199 * This checks if a device has an MTP descriptor. The descriptor was
200 * elaborated about in gPhoto bug 1482084, and some official documentation
201 * with no strings attached was published by Microsoft at
202 * http://www.microsoft.com/whdc/system/bus/USB/USBFAQ_intermed.mspx#E3HAC
204 * @param dev a device struct from libopenusb.
205 * @param dumpfile set to non-NULL to make the descriptors dump out
206 * to this file in human-readable hex so we can scruitinze them.
207 * @return 1 if the device is MTP compliant, 0 if not.
209 static int probe_device_descriptor(openusb_dev_handle_t *dev, FILE *dumpfile) {
210 openusb_dev_handle_t *devh = NULL;
211 unsigned char buf[1024], cmd;
212 uint8_t *bufptr = (uint8_t *) &buf;
213 unsigned int buffersize = sizeof(buf);
216 /* This is to indicate if we find some vendor interface */
217 int found_vendor_spec_interface = 0;
218 struct usb_device_desc desc;
219 struct usb_interface_desc ifcdesc;
221 ret = openusb_parse_device_desc(libmtp_openusb_handle, *dev, NULL, 0, &desc);
222 if (ret != OPENUSB_SUCCESS) return 0;
224 * Don't examine devices that are not likely to
225 * contain any MTP interface, update this the day
226 * you find some weird combination...
228 if (!(desc.bDeviceClass == USB_CLASS_PER_INTERFACE ||
229 desc.bDeviceClass == USB_CLASS_COMM ||
230 desc.bDeviceClass == USB_CLASS_PTP ||
231 desc.bDeviceClass == 0xEF || /* Intf. Association Desc.*/
232 desc.bDeviceClass == USB_CLASS_VENDOR_SPEC)) {
236 /* Attempt to open Device on this port */
237 ret = openusb_open_device(libmtp_openusb_handle, NULL, USB_INIT_DEFAULT, devh);
238 if (ret != OPENUSB_SUCCESS) {
239 /* Could not open this device */
244 * This sometimes crashes on the j for loop below
245 * I think it is because config is NULL yet
246 * dev->descriptor.bNumConfigurations > 0
247 * this check should stop this
250 * Loop over the device configurations and interfaces. Nokia MTP-capable
251 * handsets (possibly others) typically have the string "MTP" in their
252 * MTP interface descriptions, that's how they can be detected, before
253 * we try the more esoteric "OS descriptors" (below).
255 for (i = 0; i < desc.bNumConfigurations; i++) {
257 struct usb_config_desc config;
259 ret = openusb_parse_config_desc(libmtp_openusb_handle, *dev, NULL, 0, 0, &config);
260 if (ret != OPENUSB_SUCCESS) {
261 LIBMTP_INFO("configdescriptor %d get failed with ret %d in probe_device_descriptor yet dev->descriptor.bNumConfigurations > 0\n", i, ret);
265 for (j = 0; j < config.bNumInterfaces; j++) {
268 while (openusb_parse_interface_desc(libmtp_openusb_handle, *dev, NULL, 0, 0, j, k++, &ifcdesc) == 0) {
269 /* Current interface descriptor */
272 * MTP interfaces have three endpoints, two bulk and one
273 * interrupt. Don't probe anything else.
275 if (ifcdesc.bNumEndpoints != 3)
279 * We only want to probe for the OS descriptor if the
280 * device is LIBUSB_CLASS_VENDOR_SPEC or one of the interfaces
281 * in it is, so flag if we find an interface like this.
283 if (ifcdesc.bInterfaceClass == USB_CLASS_VENDOR_SPEC) {
284 found_vendor_spec_interface = 1;
288 * Check for Still Image Capture class with PIMA 15740 protocol,
293 * Next we search for the MTP substring in the interface name.
294 * For example : "RIM MS/MTP" should work.
297 // FIXME: DK: Find out how to get the string descriptor for an interface?
299 ret = libusb_get_string_descriptor_ascii(devh,
300 config->interface[j].altsetting[k].iInterface,
306 if (strstr((char *) buf, "MTP") != NULL) {
307 if (dumpfile != NULL) {
308 fprintf(dumpfile, "Configuration %d, interface %d, altsetting %d:\n", i, j, k);
309 fprintf(dumpfile, " Interface description contains the string \"MTP\"\n");
310 fprintf(dumpfile, " Device recognized as MTP, no further probing.\n");
312 //libusb_free_config_descriptor(config);
313 openusb_close_device(*devh);
321 * Only probe for OS descriptor if the device is vendor specific
322 * or one of the interfaces found is.
324 if (desc.bDeviceClass == USB_CLASS_VENDOR_SPEC ||
325 found_vendor_spec_interface) {
327 /* Read the special descriptor */
328 //ret = libusb_get_descriptor(devh, 0x03, 0xee, buf, sizeof (buf));
329 ret = openusb_get_raw_desc(libmtp_openusb_handle, *dev, USB_DESC_TYPE_STRING, 0xee, 0, &bufptr, (unsigned short *)&buffersize);
331 * If something failed we're probably stalled to we need
332 * to clear the stall off the endpoint and say this is not
336 /* EP0 is the default control endpoint */
337 //libusb_clear_halt (devh, 0);
338 openusb_close_device(*devh);
339 openusb_free_raw_desc(buf);
343 // Dump it, if requested
344 if (dumpfile != NULL && ret > 0) {
345 fprintf(dumpfile, "Microsoft device descriptor 0xee:\n");
346 data_dump_ascii(dumpfile, buf, ret, 16);
349 /* Check if descriptor length is at least 10 bytes */
351 openusb_close_device(*devh);
352 openusb_free_raw_desc(buf);
356 /* Check if this device has a Microsoft Descriptor */
357 if (!((buf[2] == 'M') && (buf[4] == 'S') &&
358 (buf[6] == 'F') && (buf[8] == 'T'))) {
359 openusb_close_device(*devh);
360 openusb_free_raw_desc(buf);
364 /* Check if device responds to control message 1 or if there is an error */
368 ret = libusb_control_transfer (devh,
369 LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_DEVICE | LIBUSB_REQUEST_TYPE_VENDOR,
375 USB_TIMEOUT_DEFAULT);
377 struct openusb_ctrl_request ctrl;
378 ctrl.setup.bmRequestType = USB_ENDPOINT_IN | USB_RECIP_DEVICE | USB_REQ_TYPE_VENDOR;
379 ctrl.setup.bRequest = cmd;
380 ctrl.setup.wValue = 0;
381 ctrl.setup.wIndex = 4;
382 ctrl.payload = bufptr; // Out
383 ctrl.length = sizeof (buf);
384 ctrl.timeout = USB_TIMEOUT_DEFAULT;
388 ret = openusb_ctrl_xfer(*devh, 0, USB_ENDPOINT_IN, &ctrl);
391 // Dump it, if requested
392 if (dumpfile != NULL && ctrl.result.transferred_bytes > 0) {
393 fprintf(dumpfile, "Microsoft device response to control message 1, CMD 0x%02x:\n", cmd);
394 data_dump_ascii(dumpfile, buf, ctrl.result.transferred_bytes, 16);
397 /* If this is true, the device either isn't MTP or there was an error */
398 if (ctrl.result.transferred_bytes <= 0x15) {
399 /* TODO: If there was an error, flag it and let the user know somehow */
400 /* if(ret == -1) {} */
401 openusb_close_device(*devh);
405 /* Check if device is MTP or if it is something like a USB Mass Storage
406 device with Janus DRM support */
407 if ((buf[0x12] != 'M') || (buf[0x13] != 'T') || (buf[0x14] != 'P')) {
408 openusb_close_device(*devh);
412 /* After this point we are probably dealing with an MTP device */
415 * Check if device responds to control message 2, which is
416 * the extended device parameters. Most devices will just
417 * respond with a copy of the same message as for the first
418 * message, some respond with zero-length (which is OK)
419 * and some with pure garbage. We're not parsing the result
420 * so this is not very important.
423 ret = libusb_control_transfer (devh,
424 LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_DEVICE | LIBUSB_REQUEST_TYPE_VENDOR,
430 USB_TIMEOUT_DEFAULT);
432 //struct openusb_ctrl_request ctrl;
433 ctrl.setup.bmRequestType = USB_ENDPOINT_IN | USB_RECIP_DEVICE | USB_REQ_TYPE_VENDOR;
434 ctrl.setup.bRequest = cmd;
435 ctrl.setup.wValue = 0;
436 ctrl.setup.wIndex = 5;
437 ctrl.payload = bufptr; // Out
438 ctrl.length = sizeof (buf);
439 ctrl.timeout = USB_TIMEOUT_DEFAULT;
443 ret = openusb_ctrl_xfer(*devh, 0, USB_ENDPOINT_IN, &ctrl);
445 // Dump it, if requested
446 if (dumpfile != NULL && ctrl.result.transferred_bytes > 0) {
447 fprintf(dumpfile, "Microsoft device response to control message 2, CMD 0x%02x:\n", cmd);
448 data_dump_ascii(dumpfile, buf, ret, 16);
451 /* If this is true, the device errored against control message 2 */
452 if (ctrl.result.transferred_bytes < 0) {
453 /* TODO: Implement callback function to let managing program know there
454 was a problem, along with description of the problem */
455 LIBMTP_ERROR("Potential MTP Device with VendorID:%04x and "
456 "ProductID:%04x encountered an error responding to "
457 "control message 2.\n"
458 "Problems may arrise but continuing\n",
459 desc.idVendor, desc.idProduct);
460 } else if (dumpfile != NULL && ctrl.result.transferred_bytes == 0) {
461 fprintf(dumpfile, "Zero-length response to control message 2 (OK)\n");
462 } else if (dumpfile != NULL) {
463 fprintf(dumpfile, "Device responds to control message 2 with some data.\n");
465 /* Close the USB device handle */
466 openusb_close_device(*devh);
470 /* Close the USB device handle */
471 openusb_close_device(*devh);
476 * This function scans through the connected usb devices on a machine and
477 * if they match known Vendor and Product identifiers appends them to the
478 * dynamic array mtp_device_list. Be sure to call
479 * <code>free_mtpdevice_list(mtp_device_list)</code> when you are done
480 * with it, assuming it is not NULL.
481 * @param mtp_device_list dynamic array of pointers to usb devices with MTP
482 * properties (if this list is not empty, new entries will be appended
484 * @return LIBMTP_ERROR_NONE implies that devices have been found, scan the list
485 * appropriately. LIBMTP_ERROR_NO_DEVICE_ATTACHED implies that no
486 * devices have been found.
488 static LIBMTP_error_number_t get_mtp_usb_device_list(mtpdevice_list_t ** mtp_device_list) {
490 openusb_devid_t *devs = NULL;
491 struct usb_device_desc desc;
495 ret = openusb_get_devids_by_bus(libmtp_openusb_handle, 0, &devs, &nrofdevs);
498 for (i = 0; i < nrofdevs; i++) {
499 openusb_devid_t dev = devs[i];
501 ret = openusb_parse_device_desc(libmtp_openusb_handle, dev, NULL, 0, &desc);
502 if (ret != OPENUSB_SUCCESS) continue;
504 if (desc.bDeviceClass != USB_CLASS_HUB) {
507 // First check if we know about the device already.
508 // Devices well known to us will not have their descriptors
509 // probed, it caused problems with some devices.
510 for (i = 0; i < mtp_device_table_size; i++) {
511 if (desc.idVendor == mtp_device_table[i].vendor_id &&
512 desc.idProduct == mtp_device_table[i].product_id) {
513 /* Append this usb device to the MTP device list */
514 *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list, &dev, 0);
519 // If we didn't know it, try probing the "OS Descriptor".
521 // if (probe_device_descriptor(&dev, NULL)) {
522 /* Append this usb device to the MTP USB Device List */
523 // *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list, &dev, 0);
526 * By thomas_-_s: Also append devices that are no MTP but PTP devices
527 * if this is commented out.
531 // Check whether the device is no USB hub but a PTP.
532 if ( dev->config != NULL &&dev->config->interface->altsetting->bInterfaceClass == LIBUSB_CLASS_PTP && dev->descriptor.bDeviceClass != LIBUSB_CLASS_HUB ) {
533 *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list, dev, bus->location);
541 /* If nothing was found we end up here. */
542 if (*mtp_device_list == NULL) {
543 return LIBMTP_ERROR_NO_DEVICE_ATTACHED;
545 return LIBMTP_ERROR_NONE;
549 * Checks if a specific device with a certain bus and device
550 * number has an MTP type device descriptor.
552 * @param busno the bus number of the device to check
553 * @param deviceno the device number of the device to check
554 * @return 1 if the device is MTP else 0
556 int LIBMTP_Check_Specific_Device(int busno, int devno) {
557 unsigned int nrofdevs;
558 openusb_devid_t **devs = NULL;
563 openusb_get_devids_by_bus(libmtp_openusb_handle, 0, devs, &nrofdevs);
564 for (i = 0; i < nrofdevs; i++) {
566 if (bus->location != busno)
568 if (dev->devnum != devno)
571 if (probe_device_descriptor(devs[i], NULL))
578 * Detect the raw MTP device descriptors and return a list of
579 * of the devices found.
581 * @param devices a pointer to a variable that will hold
582 * the list of raw devices found. This may be NULL
583 * on return if the number of detected devices is zero.
584 * The user shall simply <code>free()</code> this
585 * variable when finished with the raw devices,
586 * in order to release memory.
587 * @param numdevs a pointer to an integer that will hold
588 * the number of devices in the list. This may
590 * @return 0 if successful, any other value means failure.
592 LIBMTP_error_number_t LIBMTP_Detect_Raw_Devices(LIBMTP_raw_device_t ** devices,
594 mtpdevice_list_t *devlist = NULL;
595 mtpdevice_list_t *dev;
596 LIBMTP_error_number_t ret;
597 LIBMTP_raw_device_t *retdevs;
601 ret = get_mtp_usb_device_list(&devlist);
602 if (ret == LIBMTP_ERROR_NO_DEVICE_ATTACHED) {
606 } else if (ret != LIBMTP_ERROR_NONE) {
607 LIBMTP_ERROR("LIBMTP PANIC: get_mtp_usb_device_list() "
608 "error code: %d on line %d\n", ret, __LINE__);
614 while (dev != NULL) {
621 return LIBMTP_ERROR_NONE;
623 // Conjure a device list
624 retdevs = (LIBMTP_raw_device_t *) malloc(sizeof (LIBMTP_raw_device_t) * devs);
625 if (retdevs == NULL) {
629 return LIBMTP_ERROR_MEMORY_ALLOCATION;
633 while (dev != NULL) {
634 int device_known = 0;
635 struct usb_device_desc desc;
637 openusb_parse_device_desc(libmtp_openusb_handle, dev->device, NULL, 0, &desc);
638 // Assign default device info
639 retdevs[i].device_entry.vendor = NULL;
640 retdevs[i].device_entry.vendor_id = desc.idVendor;
641 retdevs[i].device_entry.product = NULL;
642 retdevs[i].device_entry.product_id = desc.idProduct;
643 retdevs[i].device_entry.device_flags = 0x00000000U;
644 // See if we can locate some additional vendor info and device flags
645 for (j = 0; j < mtp_device_table_size; j++) {
646 if (desc.idVendor == mtp_device_table[j].vendor_id &&
647 desc.idProduct == mtp_device_table[j].product_id) {
649 retdevs[i].device_entry.vendor = mtp_device_table[j].vendor;
650 retdevs[i].device_entry.product = mtp_device_table[j].product;
651 retdevs[i].device_entry.device_flags = mtp_device_table[j].device_flags;
653 // This device is known to the developers
654 LIBMTP_ERROR("Device %d (VID=%04x and PID=%04x) is a %s %s.\n",
658 mtp_device_table[j].vendor,
659 mtp_device_table[j].product);
664 device_unknown(i, desc.idVendor, desc.idProduct);
666 // Save the location on the bus
667 retdevs[i].bus_location = 0;
668 retdevs[i].devnum = openusb_get_devid(libmtp_openusb_handle, &dev->device);
674 free_mtpdevice_list(devlist);
675 return LIBMTP_ERROR_NONE;
679 * This routine just dumps out low-level
680 * USB information about the current device.
681 * @param ptp_usb the USB device to get information from.
683 void dump_usbinfo(PTP_USB *ptp_usb) {
684 struct usb_device_desc desc;
686 openusb_parse_device_desc(libmtp_openusb_handle, *ptp_usb->handle, NULL, 0, &desc);
688 LIBMTP_INFO(" bcdUSB: %d\n", desc.bcdUSB);
689 LIBMTP_INFO(" bDeviceClass: %d\n", desc.bDeviceClass);
690 LIBMTP_INFO(" bDeviceSubClass: %d\n", desc.bDeviceSubClass);
691 LIBMTP_INFO(" bDeviceProtocol: %d\n", desc.bDeviceProtocol);
692 LIBMTP_INFO(" idVendor: %04x\n", desc.idVendor);
693 LIBMTP_INFO(" idProduct: %04x\n", desc.idProduct);
694 LIBMTP_INFO(" IN endpoint maxpacket: %d bytes\n", ptp_usb->inep_maxpacket);
695 LIBMTP_INFO(" OUT endpoint maxpacket: %d bytes\n", ptp_usb->outep_maxpacket);
696 LIBMTP_INFO(" Raw device info:\n");
697 LIBMTP_INFO(" Bus location: %d\n", ptp_usb->rawdevice.bus_location);
698 LIBMTP_INFO(" Device number: %d\n", ptp_usb->rawdevice.devnum);
699 LIBMTP_INFO(" Device entry info:\n");
700 LIBMTP_INFO(" Vendor: %s\n", ptp_usb->rawdevice.device_entry.vendor);
701 LIBMTP_INFO(" Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.vendor_id);
702 LIBMTP_INFO(" Product: %s\n", ptp_usb->rawdevice.device_entry.product);
703 LIBMTP_INFO(" Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.product_id);
704 LIBMTP_INFO(" Device flags: 0x%08x\n", ptp_usb->rawdevice.device_entry.device_flags);
705 // TODO: (void) probe_device_descriptor(dev, stdout);
709 * Retrieve the apropriate playlist extension for this
710 * device. Rather hacky at the moment. This is probably
711 * desired by the managing software, but when creating
712 * lists on the device itself you notice certain preferences.
713 * @param ptp_usb the USB device to get suggestion for.
714 * @return the suggested playlist extension.
716 const char *get_playlist_extension(PTP_USB *ptp_usb) {
717 static char creative_pl_extension[] = ".zpl";
718 static char default_pl_extension[] = ".pla";
719 struct usb_device_desc desc;
720 openusb_parse_device_desc(libmtp_openusb_handle, *ptp_usb->handle, NULL, 0, &desc);
721 if (desc.idVendor == 0x041e)
722 return creative_pl_extension;
723 return default_pl_extension;
727 libusb_glue_debug(PTPParams *params, const char *format, ...) {
730 va_start(args, format);
731 if (params->debug_func != NULL)
732 params->debug_func(params->data, format, args);
734 vfprintf(stderr, format, args);
735 fprintf(stderr, "\n");
742 libusb_glue_error(PTPParams *params, const char *format, ...) {
745 va_start(args, format);
746 if (params->error_func != NULL)
747 params->error_func(params->data, format, args);
749 vfprintf(stderr, format, args);
750 fprintf(stderr, "\n");
758 * ptp_read_func() and ptp_write_func() are
759 * based on same functions usb.c in libgphoto2.
760 * Much reading packet logs and having fun with trials and errors
761 * reveals that WMP / Windows is probably using an algorithm like this
762 * for large transfers:
764 * 1. Send the command (0x0c bytes) if headers are split, else, send
765 * command plus sizeof(endpoint) - 0x0c bytes.
766 * 2. Send first packet, max size to be sizeof(endpoint) but only when using
767 * split headers. Else goto 3.
768 * 3. REPEAT send 0x10000 byte chunks UNTIL remaining bytes < 0x10000
769 * We call 0x10000 CONTEXT_BLOCK_SIZE.
770 * 4. Send remaining bytes MOD sizeof(endpoint)
771 * 5. Send remaining bytes. If this happens to be exactly sizeof(endpoint)
772 * then also send a zero-length package.
774 * Further there is some special quirks to handle zero reads from the
775 * device, since some devices can't do them at all due to shortcomings
776 * of the USB slave controller in the device.
778 #define CONTEXT_BLOCK_SIZE_1 0x3e00
779 #define CONTEXT_BLOCK_SIZE_2 0x200
780 #define CONTEXT_BLOCK_SIZE CONTEXT_BLOCK_SIZE_1+CONTEXT_BLOCK_SIZE_2
784 unsigned long size, PTPDataHandler *handler, void *data,
785 unsigned long *readbytes,
788 PTP_USB *ptp_usb = (PTP_USB *) data;
789 unsigned long toread = 0;
792 unsigned long curread = 0;
793 unsigned long written;
794 unsigned char *bytes;
795 int expect_terminator_byte = 0;
796 unsigned long usb_inep_maxpacket_size;
797 unsigned long context_block_size_1;
798 unsigned long context_block_size_2;
799 uint16_t ptp_dev_vendor_id = ptp_usb->rawdevice.device_entry.vendor_id;
801 //"iRiver" device special handling
802 if (ptp_dev_vendor_id == 0x4102 || ptp_dev_vendor_id == 0x1006) {
803 usb_inep_maxpacket_size = ptp_usb->inep_maxpacket;
804 if (usb_inep_maxpacket_size == 0x400) {
805 context_block_size_1 = CONTEXT_BLOCK_SIZE_1 - 0x200;
806 context_block_size_2 = CONTEXT_BLOCK_SIZE_2 + 0x200;
809 context_block_size_1 = CONTEXT_BLOCK_SIZE_1;
810 context_block_size_2 = CONTEXT_BLOCK_SIZE_2;
813 struct openusb_bulk_request bulk;
814 // This is the largest block we'll need to read in.
815 bytes = malloc(CONTEXT_BLOCK_SIZE);
816 while (curread < size) {
818 LIBMTP_USB_DEBUG("Remaining size to read: 0x%04lx bytes\n", size - curread);
820 // check equal to condition here
821 if (size - curread < CONTEXT_BLOCK_SIZE) {
822 // this is the last packet
823 toread = size - curread;
824 // this is equivalent to zero read for these devices
825 if (readzero && FLAG_NO_ZERO_READS(ptp_usb) && toread % 64 == 0) {
827 expect_terminator_byte = 1;
829 } else if (ptp_dev_vendor_id == 0x4102 || ptp_dev_vendor_id == 0x1006) {
830 //"iRiver" device special handling
832 // we are first packet, but not last packet
833 toread = context_block_size_1;
834 else if (toread == context_block_size_1)
835 toread = context_block_size_2;
836 else if (toread == context_block_size_2)
837 toread = context_block_size_1;
839 LIBMTP_INFO("unexpected toread size 0x%04x, 0x%04x remaining bytes\n",
840 (unsigned int) toread, (unsigned int) (size - curread));
843 toread = CONTEXT_BLOCK_SIZE;
845 LIBMTP_USB_DEBUG("Reading in 0x%04lx bytes\n", toread);
848 ret = USB_BULK_READ(ptp_usb->handle,
855 bulk.payload = bytes;
856 bulk.length = toread;
857 bulk.timeout = ptp_usb->timeout;
860 ret = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->inep, &bulk);
861 xread = bulk.result.transferred_bytes;
862 LIBMTP_USB_DEBUG("Result of read: 0x%04x (%d bytes)\n", ret, xread);
864 if (ret != OPENUSB_SUCCESS)
867 LIBMTP_USB_DEBUG("<==USB IN\n");
869 LIBMTP_USB_DEBUG("Zero Read\n");
871 LIBMTP_USB_DATA(bytes, xread, 16);
873 // want to discard extra byte
874 if (expect_terminator_byte && xread == toread) {
875 LIBMTP_USB_DEBUG("<==USB IN\nDiscarding extra byte\n");
880 int putfunc_ret = handler->putfunc(NULL, handler->priv, xread, bytes, &written);
881 LIBMTP_USB_DEBUG("handler->putfunc ret = 0x%x\n", putfunc_ret);
882 if (putfunc_ret != PTP_RC_OK)
885 ptp_usb->current_transfer_complete += xread;
888 // Increase counters, call callback
889 if (ptp_usb->callback_active) {
890 if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
891 // send last update and disable callback.
892 ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total;
893 ptp_usb->callback_active = 0;
895 if (ptp_usb->current_transfer_callback != NULL) {
897 ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete,
898 ptp_usb->current_transfer_total,
899 ptp_usb->current_transfer_callback_data);
901 return PTP_ERROR_CANCEL;
906 if (xread < toread) /* short reads are common */
909 if (readbytes) *readbytes = curread;
911 LIBMTP_USB_DEBUG("Pointer Updated\n");
912 // there might be a zero packet waiting for us...
914 !FLAG_NO_ZERO_READS(ptp_usb) &&
915 curread % ptp_usb->outep_maxpacket == 0) {
917 int zeroresult = 0, xread;
919 LIBMTP_USB_DEBUG("<==USB IN\n");
920 LIBMTP_USB_DEBUG("Zero Read\n");
923 zeroresult = USB_BULK_READ(ptp_usb->handle,
930 bulk.payload = &temp;
932 bulk.timeout = ptp_usb->timeout;
935 ret = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->inep, &bulk);
936 xread = bulk.result.transferred_bytes;
937 if (zeroresult != OPENUSB_SUCCESS)
938 LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult);
946 PTPDataHandler *handler,
948 unsigned long *written
950 PTP_USB *ptp_usb = (PTP_USB *) data;
951 unsigned long towrite = 0;
953 unsigned long curwrite = 0;
954 unsigned char *bytes;
956 struct openusb_bulk_request bulk;
958 // This is the largest block we'll need to read in.
959 bytes = malloc(CONTEXT_BLOCK_SIZE);
963 while (curwrite < size) {
964 unsigned long usbwritten = 0;
967 towrite = size - curwrite;
968 if (towrite > CONTEXT_BLOCK_SIZE) {
969 towrite = CONTEXT_BLOCK_SIZE;
971 // This magic makes packets the same size that WMP send them.
972 if (towrite > ptp_usb->outep_maxpacket && towrite % ptp_usb->outep_maxpacket != 0) {
973 towrite -= towrite % ptp_usb->outep_maxpacket;
976 int getfunc_ret = handler->getfunc(NULL, handler->priv, towrite, bytes, &towrite);
977 if (getfunc_ret != PTP_RC_OK)
979 while (usbwritten < towrite) {
981 ret = USB_BULK_WRITE(ptp_usb->handle,
984 towrite - usbwritten,
988 bulk.payload = bytes + usbwritten;
989 bulk.length = towrite - usbwritten;
990 bulk.timeout = ptp_usb->timeout;
993 ret = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->outep, &bulk);
994 xwritten = bulk.result.transferred_bytes;
996 LIBMTP_USB_DEBUG("USB OUT==>\n");
998 if (ret != OPENUSB_SUCCESS) {
1001 LIBMTP_USB_DATA(bytes + usbwritten, xwritten, 16);
1002 // check for result == 0 perhaps too.
1003 // Increase counters
1004 ptp_usb->current_transfer_complete += xwritten;
1005 curwrite += xwritten;
1006 usbwritten += xwritten;
1009 if (ptp_usb->callback_active) {
1010 if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
1011 // send last update and disable callback.
1012 ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total;
1013 ptp_usb->callback_active = 0;
1015 if (ptp_usb->current_transfer_callback != NULL) {
1017 ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete,
1018 ptp_usb->current_transfer_total,
1019 ptp_usb->current_transfer_callback_data);
1021 return PTP_ERROR_CANCEL;
1025 if (xwritten < towrite) /* short writes happen */
1030 *written = curwrite;
1033 // If this is the last transfer send a zero write if required
1034 if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
1035 if ((towrite % ptp_usb->outep_maxpacket) == 0) {
1038 LIBMTP_USB_DEBUG("USB OUT==>\n");
1039 LIBMTP_USB_DEBUG("Zero Write\n");
1042 ret = USB_BULK_WRITE(ptp_usb->handle,
1044 (unsigned char *) "x",
1049 bulk.payload = (unsigned char *) "x";
1051 bulk.timeout = ptp_usb->timeout;
1054 ret = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->outep, &bulk);
1055 xwritten = bulk.result.transferred_bytes;
1059 if (ret != OPENUSB_SUCCESS)
1060 return PTP_ERROR_IO;
1064 /* memory data get/put handler */
1066 unsigned char *data;
1067 unsigned long size, curoff;
1068 } PTPMemHandlerPrivate;
1071 memory_getfunc(PTPParams* params, void* private,
1072 unsigned long wantlen, unsigned char *data,
1073 unsigned long *gotlen
1075 PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*) private;
1076 unsigned long tocopy = wantlen;
1078 if (priv->curoff + tocopy > priv->size)
1079 tocopy = priv->size - priv->curoff;
1080 memcpy(data, priv->data + priv->curoff, tocopy);
1081 priv->curoff += tocopy;
1087 memory_putfunc(PTPParams* params, void* private,
1088 unsigned long sendlen, unsigned char *data,
1089 unsigned long *putlen
1091 PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*) private;
1093 if (priv->curoff + sendlen > priv->size) {
1094 priv->data = realloc(priv->data, priv->curoff + sendlen);
1095 priv->size = priv->curoff + sendlen;
1097 memcpy(priv->data + priv->curoff, data, sendlen);
1098 priv->curoff += sendlen;
1103 /* init private struct for receiving data. */
1105 ptp_init_recv_memory_handler(PTPDataHandler *handler) {
1106 PTPMemHandlerPrivate* priv;
1107 priv = malloc(sizeof (PTPMemHandlerPrivate));
1108 handler->priv = priv;
1109 handler->getfunc = memory_getfunc;
1110 handler->putfunc = memory_putfunc;
1117 /* init private struct and put data in for sending data.
1118 * data is still owned by caller.
1121 ptp_init_send_memory_handler(PTPDataHandler *handler,
1122 unsigned char *data, unsigned long len
1124 PTPMemHandlerPrivate* priv;
1125 priv = malloc(sizeof (PTPMemHandlerPrivate));
1127 return PTP_RC_GeneralError;
1129 handler->priv = priv;
1130 handler->getfunc = memory_getfunc;
1131 handler->putfunc = memory_putfunc;
1138 /* free private struct + data */
1140 ptp_exit_send_memory_handler(PTPDataHandler *handler) {
1141 PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*) handler->priv;
1142 /* data is owned by caller */
1147 /* hand over our internal data to caller */
1149 ptp_exit_recv_memory_handler(PTPDataHandler *handler,
1150 unsigned char **data, unsigned long *size
1152 PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*) handler->priv;
1159 /* send / receive functions */
1162 ptp_usb_sendreq(PTPParams* params, PTPContainer* req) {
1164 PTPUSBBulkContainer usbreq;
1165 PTPDataHandler memhandler;
1166 unsigned long written = 0;
1167 unsigned long towrite;
1171 (void) ptp_render_opcode(params, req->Code, sizeof (txt), txt);
1172 LIBMTP_USB_DEBUG("REQUEST: 0x%04x, %s\n", req->Code, txt);
1174 /* build appropriate USB container */
1175 usbreq.length = htod32(PTP_USB_BULK_REQ_LEN -
1176 (sizeof (uint32_t)*(5 - req->Nparam)));
1177 usbreq.type = htod16(PTP_USB_CONTAINER_COMMAND);
1178 usbreq.code = htod16(req->Code);
1179 usbreq.trans_id = htod32(req->Transaction_ID);
1180 usbreq.payload.params.param1 = htod32(req->Param1);
1181 usbreq.payload.params.param2 = htod32(req->Param2);
1182 usbreq.payload.params.param3 = htod32(req->Param3);
1183 usbreq.payload.params.param4 = htod32(req->Param4);
1184 usbreq.payload.params.param5 = htod32(req->Param5);
1185 /* send it to responder */
1186 towrite = PTP_USB_BULK_REQ_LEN - (sizeof (uint32_t)*(5 - req->Nparam));
1187 ptp_init_send_memory_handler(&memhandler, (unsigned char*) &usbreq, towrite);
1188 ret = ptp_write_func(
1194 ptp_exit_send_memory_handler(&memhandler);
1195 if (ret != PTP_RC_OK && ret != PTP_ERROR_CANCEL) {
1198 if (written != towrite && ret != PTP_ERROR_CANCEL && ret != PTP_ERROR_IO) {
1199 libusb_glue_error(params,
1200 "PTP: request code 0x%04x sending req wrote only %ld bytes instead of %d",
1201 req->Code, written, towrite
1209 ptp_usb_senddata(PTPParams* params, PTPContainer* ptp,
1210 uint64_t size, PTPDataHandler *handler
1214 unsigned long written;
1215 PTPUSBBulkContainer usbdata;
1216 uint64_t bytes_left_to_transfer;
1217 PTPDataHandler memhandler;
1219 LIBMTP_USB_DEBUG("SEND DATA PHASE\n");
1221 /* build appropriate USB container */
1222 usbdata.length = htod32(PTP_USB_BULK_HDR_LEN + size);
1223 usbdata.type = htod16(PTP_USB_CONTAINER_DATA);
1224 usbdata.code = htod16(ptp->Code);
1225 usbdata.trans_id = htod32(ptp->Transaction_ID);
1227 ((PTP_USB*) params->data)->current_transfer_complete = 0;
1228 ((PTP_USB*) params->data)->current_transfer_total = size + PTP_USB_BULK_HDR_LEN;
1230 if (params->split_header_data) {
1232 wlen = PTP_USB_BULK_HDR_LEN;
1234 unsigned long gotlen;
1235 /* For all camera devices. */
1236 datawlen = (size < PTP_USB_BULK_PAYLOAD_LEN_WRITE) ? size : PTP_USB_BULK_PAYLOAD_LEN_WRITE;
1237 wlen = PTP_USB_BULK_HDR_LEN + datawlen;
1239 ret = handler->getfunc(params, handler->priv, datawlen, usbdata.payload.data, &gotlen);
1240 if (ret != PTP_RC_OK){
1244 if (gotlen != datawlen){
1245 return PTP_RC_GeneralError;
1248 ptp_init_send_memory_handler(&memhandler, (unsigned char *) &usbdata, wlen);
1249 /* send first part of data */
1250 ret = ptp_write_func(wlen, &memhandler, params->data, &written);
1251 ptp_exit_send_memory_handler(&memhandler);
1252 if (ret != PTP_RC_OK) {
1255 if (size <= datawlen) return ret;
1256 /* if everything OK send the rest */
1257 bytes_left_to_transfer = size - datawlen;
1259 while (bytes_left_to_transfer > 0) {
1260 ret = ptp_write_func(bytes_left_to_transfer, handler, params->data, &written);
1261 if (ret != PTP_RC_OK){
1268 bytes_left_to_transfer -= written;
1270 if (ret != PTP_RC_OK && ret != PTP_ERROR_CANCEL)
1275 static uint16_t ptp_usb_getpacket(PTPParams *params,
1276 PTPUSBBulkContainer *packet, unsigned long *rlen) {
1277 PTPDataHandler memhandler;
1279 unsigned char *x = NULL;
1280 unsigned long packet_size;
1281 PTP_USB *ptp_usb = (PTP_USB *) params->data;
1283 packet_size = ptp_usb->inep_maxpacket;
1285 /* read the header and potentially the first data */
1286 if (params->response_packet_size > 0) {
1287 /* If there is a buffered packet, just use it. */
1288 memcpy(packet, params->response_packet, params->response_packet_size);
1289 *rlen = params->response_packet_size;
1290 free(params->response_packet);
1291 params->response_packet = NULL;
1292 params->response_packet_size = 0;
1293 /* Here this signifies a "virtual read" */
1296 ptp_init_recv_memory_handler(&memhandler);
1297 ret = ptp_read_func(packet_size, &memhandler, params->data, rlen, 0);
1298 ptp_exit_recv_memory_handler(&memhandler, &x, rlen);
1300 memcpy(packet, x, *rlen);
1307 ptp_usb_getdata(PTPParams* params, PTPContainer* ptp, PTPDataHandler *handler) {
1309 PTPUSBBulkContainer usbdata;
1310 unsigned long written;
1311 PTP_USB *ptp_usb = (PTP_USB *) params->data;
1314 LIBMTP_USB_DEBUG("GET DATA PHASE\n");
1316 struct openusb_bulk_request bulk;
1318 memset(&usbdata, 0, sizeof (usbdata));
1320 unsigned long len, rlen;
1322 ret = ptp_usb_getpacket(params, &usbdata, &rlen);
1323 if (ret != PTP_RC_OK) {
1327 if (dtoh16(usbdata.type) != PTP_USB_CONTAINER_DATA) {
1328 ret = PTP_ERROR_DATA_EXPECTED;
1331 if (dtoh16(usbdata.code) != ptp->Code) {
1332 if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) {
1333 libusb_glue_debug(params, "ptp2/ptp_usb_getdata: detected a broken "
1334 "PTP header, code field insane, expect problems! (But continuing)");
1335 // Repair the header, so it won't wreak more havoc, don't just ignore it.
1336 // Typically these two fields will be broken.
1337 usbdata.code = htod16(ptp->Code);
1338 usbdata.trans_id = htod32(ptp->Transaction_ID);
1341 ret = dtoh16(usbdata.code);
1342 // This filters entirely insane garbage return codes, but still
1343 // makes it possible to return error codes in the code field when
1344 // getting data. It appears Windows ignores the contents of this
1346 if (ret < PTP_RC_Undefined || ret > PTP_RC_SpecificationOfDestinationUnsupported) {
1347 libusb_glue_debug(params, "ptp2/ptp_usb_getdata: detected a broken "
1348 "PTP header, code field insane.");
1354 if (rlen == ptp_usb->inep_maxpacket) {
1355 /* Copy first part of data to 'data' */
1358 params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN, usbdata.payload.data,
1361 if (putfunc_ret != PTP_RC_OK)
1364 /* stuff data directly to passed data handler */
1366 unsigned long readdata;
1369 xret = ptp_read_func(
1376 if (xret != PTP_RC_OK)
1378 if (readdata < 0x20000000)
1383 if (rlen > dtoh32(usbdata.length)) {
1385 * Buffer the surplus response packet if it is >=
1386 * PTP_USB_BULK_HDR_LEN
1387 * (i.e. it is probably an entire package)
1388 * else discard it as erroneous surplus data.
1389 * This will even work if more than 2 packets appear
1390 * in the same transaction, they will just be handled
1393 * Marcus observed stray bytes on iRiver devices;
1394 * these are still discarded.
1396 unsigned int packlen = dtoh32(usbdata.length);
1397 unsigned int surplen = rlen - packlen;
1399 if (surplen >= PTP_USB_BULK_HDR_LEN) {
1400 params->response_packet = malloc(surplen);
1401 memcpy(params->response_packet,
1402 (uint8_t *) & usbdata + packlen, surplen);
1403 params->response_packet_size = surplen;
1404 /* Ignore reading one extra byte if device flags have been set */
1405 } else if (!FLAG_NO_ZERO_READS(ptp_usb) &&
1406 (rlen - dtoh32(usbdata.length) == 1)) {
1407 libusb_glue_debug(params, "ptp2/ptp_usb_getdata: read %d bytes "
1408 "too much, expect problems!",
1409 rlen - dtoh32(usbdata.length));
1414 /* For most PTP devices rlen is 512 == sizeof(usbdata)
1415 * here. For MTP devices splitting header and data it might
1418 /* Evaluate full data length. */
1419 len = dtoh32(usbdata.length) - PTP_USB_BULK_HDR_LEN;
1421 /* autodetect split header/data MTP devices */
1422 if (dtoh32(usbdata.length) > 12 && (rlen == 12))
1423 params->split_header_data = 1;
1425 /* Copy first part of data to 'data' */
1428 params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN,
1429 usbdata.payload.data,
1432 if (putfunc_ret != PTP_RC_OK)
1435 if (FLAG_NO_ZERO_READS(ptp_usb) &&
1436 len + PTP_USB_BULK_HDR_LEN == ptp_usb->inep_maxpacket) {
1438 LIBMTP_USB_DEBUG("Reading in extra terminating byte\n");
1440 // need to read in extra byte and discard it
1441 int result = 0, xread;
1442 unsigned char byte = 0;
1445 result = USB_BULK_READ(ptp_usb->handle,
1453 bulk.payload = &byte;
1455 bulk.timeout = ptp_usb->timeout;
1458 result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->inep, &bulk);
1459 xread = bulk.result.transferred_bytes;
1462 LIBMTP_INFO("Could not read in extra byte for %d bytes long file, return value 0x%04x\n", ptp_usb->inep_maxpacket, result);
1463 } else if (len + PTP_USB_BULK_HDR_LEN == ptp_usb->inep_maxpacket && params->split_header_data == 0) {
1464 int zeroresult = 0, xread;
1465 unsigned char zerobyte = 0;
1467 LIBMTP_INFO("Reading in zero packet after header\n");
1469 zeroresult = USB_BULK_READ(ptp_usb->handle,
1477 bulk.payload = &zerobyte;
1479 bulk.timeout = ptp_usb->timeout;
1482 zeroresult = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->inep, &bulk);
1483 xread = bulk.result.transferred_bytes;
1485 if (zeroresult != 0)
1486 LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult);
1489 /* Is that all of data? */
1490 if (len + PTP_USB_BULK_HDR_LEN <= rlen) {
1494 ret = ptp_read_func(len - (rlen - PTP_USB_BULK_HDR_LEN),
1496 params->data, &rlen, 1);
1498 if (ret != PTP_RC_OK) {
1506 ptp_usb_getresp(PTPParams* params, PTPContainer* resp) {
1509 PTPUSBBulkContainer usbresp;
1510 PTP_USB *ptp_usb = (PTP_USB *) (params->data);
1513 LIBMTP_USB_DEBUG("RESPONSE: ");
1514 memset(&usbresp, 0, sizeof (usbresp));
1515 /* read response, it should never be longer than sizeof(usbresp) */
1516 ret = ptp_usb_getpacket(params, &usbresp, &rlen);
1517 // Fix for bevahiour reported by Scott Snyder on Samsung YP-U3. The player
1518 // sends a packet containing just zeroes of length 2 (up to 4 has been seen too)
1519 // after a NULL packet when it should send the response. This code ignores
1520 // such illegal packets.
1521 while (ret == PTP_RC_OK && rlen < PTP_USB_BULK_HDR_LEN && usbresp.length == 0) {
1522 libusb_glue_debug(params, "ptp_usb_getresp: detected short response "
1523 "of %d bytes, expect problems! (re-reading "
1525 ret = ptp_usb_getpacket(params, &usbresp, &rlen);
1527 if (ret != PTP_RC_OK) {
1530 if (dtoh16(usbresp.type) != PTP_USB_CONTAINER_RESPONSE) {
1531 ret = PTP_ERROR_RESP_EXPECTED;
1533 if (dtoh16(usbresp.code) != resp->Code) {
1534 ret = dtoh16(usbresp.code);
1537 LIBMTP_USB_DEBUG("%04x\n", ret);
1538 if (ret != PTP_RC_OK) {
1539 /* libusb_glue_error (params,
1540 "PTP: request code 0x%04x getting resp error 0x%04x",
1544 /* build an appropriate PTPContainer */
1545 resp->Code = dtoh16(usbresp.code);
1546 resp->SessionID = params->session_id;
1547 resp->Transaction_ID = dtoh32(usbresp.trans_id);
1548 if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) {
1549 if (resp->Transaction_ID != params->transaction_id - 1) {
1550 libusb_glue_debug(params, "ptp_usb_getresp: detected a broken "
1551 "PTP header, transaction ID insane, expect "
1552 "problems! (But continuing)");
1553 // Repair the header, so it won't wreak more havoc.
1554 resp->Transaction_ID = params->transaction_id - 1;
1557 resp->Param1 = dtoh32(usbresp.payload.params.param1);
1558 resp->Param2 = dtoh32(usbresp.payload.params.param2);
1559 resp->Param3 = dtoh32(usbresp.payload.params.param3);
1560 resp->Param4 = dtoh32(usbresp.payload.params.param4);
1561 resp->Param5 = dtoh32(usbresp.payload.params.param5);
1565 /* Event handling functions */
1567 /* PTP Events wait for or check mode */
1568 #define PTP_EVENT_CHECK 0x0000 /* waits for */
1569 #define PTP_EVENT_CHECK_FAST 0x0001 /* checks */
1571 static inline uint16_t
1572 ptp_usb_event(PTPParams* params, PTPContainer* event, int wait) {
1576 PTPUSBEventContainer usbevent;
1577 PTP_USB *ptp_usb = (PTP_USB *) (params->data);
1579 struct openusb_bulk_request bulk;
1581 memset(&usbevent, 0, sizeof (usbevent));
1583 if ((params == NULL) || (event == NULL))
1584 return PTP_ERROR_BADPARAM;
1587 case PTP_EVENT_CHECK:
1590 result = USB_BULK_READ(ptp_usb->handle,
1592 (unsigned char *) &usbevent,
1597 bulk.payload = (unsigned char *) &usbevent;
1598 bulk.length = sizeof (usbevent);
1599 bulk.timeout = ptp_usb->timeout;
1602 result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->intep, &bulk);
1603 xread = bulk.result.transferred_bytes;
1607 result = USB_BULK_READ(ptp_usb->handle,
1609 (unsigned char *) &usbevent,
1614 bulk.payload = (unsigned char *) &usbevent;
1615 bulk.length = sizeof (usbevent);
1616 bulk.timeout = ptp_usb->timeout;
1619 result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->intep, &bulk);
1620 xread = bulk.result.transferred_bytes;
1622 if (result < 0) ret = PTP_ERROR_IO;
1624 case PTP_EVENT_CHECK_FAST:
1626 result = USB_BULK_READ(ptp_usb->handle,
1628 (unsigned char *) &usbevent,
1633 bulk.payload = (unsigned char *) &usbevent;
1634 bulk.length = sizeof (usbevent);
1635 bulk.timeout = ptp_usb->timeout;
1638 result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->intep, &bulk);
1639 xread = bulk.result.transferred_bytes;
1643 result = USB_BULK_READ(ptp_usb->handle,
1645 (unsigned char *) &usbevent,
1650 bulk.payload = (unsigned char *) &usbevent;
1651 bulk.length = sizeof (usbevent);
1652 bulk.timeout = ptp_usb->timeout;
1655 result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->intep, &bulk);
1656 xread = bulk.result.transferred_bytes;
1658 if (result < 0) ret = PTP_ERROR_IO;
1661 ret = PTP_ERROR_BADPARAM;
1664 if (ret != PTP_RC_OK) {
1665 libusb_glue_error(params,
1666 "PTP: reading event an error 0x%04x occurred", ret);
1667 return PTP_ERROR_IO;
1671 libusb_glue_error(params,
1672 "PTP: reading event an short read of %ld bytes occurred", rlen);
1673 return PTP_ERROR_IO;
1675 /* if we read anything over interrupt endpoint it must be an event */
1676 /* build an appropriate PTPContainer */
1677 event->Code = dtoh16(usbevent.code);
1678 event->SessionID = params->session_id;
1679 event->Transaction_ID = dtoh32(usbevent.trans_id);
1680 event->Param1 = dtoh32(usbevent.param1);
1681 event->Param2 = dtoh32(usbevent.param2);
1682 event->Param3 = dtoh32(usbevent.param3);
1687 ptp_usb_event_check(PTPParams* params, PTPContainer* event) {
1689 return ptp_usb_event(params, event, PTP_EVENT_CHECK_FAST);
1693 ptp_usb_event_wait(PTPParams* params, PTPContainer* event) {
1695 return ptp_usb_event(params, event, PTP_EVENT_CHECK);
1699 ptp_usb_control_cancel_request(PTPParams *params, uint32_t transactionid) {
1700 PTP_USB *ptp_usb = (PTP_USB *) (params->data);
1702 unsigned char buffer[6];
1704 htod16a(&buffer[0], PTP_EC_CancelTransaction);
1705 htod32a(&buffer[2], transactionid);
1707 ret = libusb_control_transfer(ptp_usb->handle,
1708 LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
1709 0x64, 0x0000, 0x0000,
1714 struct openusb_ctrl_request ctrl;
1715 ctrl.setup.bmRequestType = USB_REQ_TYPE_CLASS | USB_RECIP_INTERFACE;
1716 ctrl.setup.bRequest = 0x64;
1717 ctrl.setup.wValue = 0;
1718 ctrl.setup.wIndex = 0;
1719 ctrl.payload = (unsigned char *)&buffer; // Out
1720 ctrl.length = sizeof (buffer);
1721 ctrl.timeout = ptp_usb->timeout;
1725 ret = openusb_ctrl_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->outep, &ctrl);
1726 if (ctrl.result.transferred_bytes < sizeof (buffer))
1727 return PTP_ERROR_IO;
1731 static int init_ptp_usb(PTPParams* params, PTP_USB* ptp_usb, openusb_dev_handle_t* dev) {
1732 openusb_dev_handle_t device_handle;
1733 unsigned char buf[255];
1736 params->sendreq_func = ptp_usb_sendreq;
1737 params->senddata_func = ptp_usb_senddata;
1738 params->getresp_func = ptp_usb_getresp;
1739 params->getdata_func = ptp_usb_getdata;
1740 params->cancelreq_func = ptp_usb_control_cancel_request;
1741 params->data = ptp_usb;
1742 params->transaction_id = 0;
1744 * This is hardcoded here since we have no devices whatsoever that are BE.
1745 * Change this the day we run into our first BE device (if ever).
1747 params->byteorder = PTP_DL_LE;
1749 ptp_usb->timeout = get_timeout(ptp_usb);
1751 ret = openusb_open_device(libmtp_openusb_handle, *dev, USB_INIT_DEFAULT, &device_handle);
1752 if (ret != OPENUSB_SUCCESS) {
1753 perror("usb_open()");
1756 ptp_usb->handle = malloc(sizeof(openusb_dev_handle_t));
1757 *ptp_usb->handle = device_handle;
1759 * If this device is known to be wrongfully claimed by other kernel
1760 * drivers (such as mass storage), then try to unload it to make it
1761 * accessible from user space.
1762 * Note: OpenUSB doesn't support this type of operation?
1765 if (FLAG_UNLOAD_DRIVER(ptp_usb) &&
1766 libusb_kernel_driver_active (device_handle, ptp_usb->interface)
1768 if (OPENUSB_SUCCESS != libusb_detach_kernel_driver (device_handle, ptp_usb->interface)) {
1773 // It seems like on kernel 2.6.31 if we already have it open on another
1774 // pthread in our app, we'll get an error if we try to claim it again,
1775 // but that error is harmless because our process already claimed the interface
1776 usbresult = openusb_claim_interface(device_handle, ptp_usb->interface, USB_INIT_DEFAULT);
1779 fprintf(stderr, "ignoring usb_claim_interface = %d", usbresult);
1781 if (FLAG_SWITCH_MODE_BLACKBERRY(ptp_usb)) {
1784 // FIXME : Only for BlackBerry Storm
1785 // What does it mean? Maybe switch mode...
1786 // This first control message is absolutely necessary
1789 ret = libusb_control_transfer(device_handle,
1790 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1791 0xaa, 0x00, 0x04, buf, 0x40, 1000);
1793 struct openusb_ctrl_request ctrl;
1794 ctrl.setup.bmRequestType = USB_REQ_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN;
1795 ctrl.setup.bRequest = 0xaa;
1796 ctrl.setup.wValue = 0;
1797 ctrl.setup.wIndex = 4;
1798 ctrl.payload = (unsigned char *)&buf; // Out
1800 ctrl.timeout = 1000;
1804 ret = openusb_ctrl_xfer(device_handle, ptp_usb->interface, ptp_usb->outep, &ctrl);
1805 LIBMTP_USB_DEBUG("BlackBerry magic part 1:\n");
1806 LIBMTP_USB_DATA(buf, ctrl.result.transferred_bytes, 16);
1809 // This control message is unnecessary
1811 ret = libusb_control_transfer(device_handle,
1812 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1813 0xa5, 0x00, 0x01, buf, 0x02, 1000);
1815 ctrl.setup.bmRequestType = USB_REQ_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN;
1816 ctrl.setup.bRequest = 0xa5;
1817 ctrl.setup.wValue = 0;
1818 ctrl.setup.wIndex = 1;
1819 ctrl.payload = (unsigned char *)&buf; // Out
1821 ctrl.timeout = 1000;
1825 ret = openusb_ctrl_xfer(device_handle, ptp_usb->interface, ptp_usb->outep, &ctrl);
1826 LIBMTP_USB_DEBUG("BlackBerry magic part 2:\n");
1827 LIBMTP_USB_DATA(buf, ctrl.result.transferred_bytes, 16);
1830 // This control message is unnecessary
1832 ret = libusb_control_transfer(device_handle,
1833 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1834 0xa8, 0x00, 0x01, buf, 0x05, 1000);
1836 ctrl.setup.bmRequestType = USB_REQ_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN;
1837 ctrl.setup.bRequest = 0xa8;
1838 ctrl.setup.wValue = 0;
1839 ctrl.setup.wIndex = 1;
1840 ctrl.payload = (unsigned char *)&buf; // Out
1842 ctrl.timeout = 1000;
1846 ret = openusb_ctrl_xfer(device_handle, ptp_usb->interface, ptp_usb->outep, &ctrl);
1847 LIBMTP_USB_DEBUG("BlackBerry magic part 3:\n");
1848 LIBMTP_USB_DATA(buf, ctrl.result.transferred_bytes, 16);
1851 // This control message is unnecessary
1853 ret = libusb_control_transfer(device_handle,
1854 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1855 0xa8, 0x00, 0x01, buf, 0x11, 1000);
1857 ctrl.setup.bmRequestType = USB_REQ_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN;
1858 ctrl.setup.bRequest = 0xa8;
1859 ctrl.setup.wValue = 0;
1860 ctrl.setup.wIndex = 1;
1861 ctrl.payload = (unsigned char *)&buf; // Out
1863 ctrl.timeout = 1000;
1867 ret = openusb_ctrl_xfer(device_handle, ptp_usb->interface, ptp_usb->outep, &ctrl);
1868 LIBMTP_USB_DEBUG("BlackBerry magic part 4:\n");
1869 LIBMTP_USB_DATA(buf, ctrl.result.transferred_bytes, 16);
1876 static void clear_stall(PTP_USB* ptp_usb) {
1880 /* check the inep status */
1883 ret = usb_get_endpoint_status(ptp_usb, ptp_usb->inep, &status);
1885 perror("inep: usb_get_endpoint_status()");
1886 } else if (status) {
1887 LIBMTP_INFO("Clearing stall on IN endpoint\n");
1888 ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->inep);
1889 if (ret != OPENUSB_SUCCESS) {
1890 perror("usb_clear_stall_feature()");
1894 /* check the outep status */
1896 ret = usb_get_endpoint_status(ptp_usb, ptp_usb->outep, &status);
1898 perror("outep: usb_get_endpoint_status()");
1899 } else if (status) {
1900 LIBMTP_INFO("Clearing stall on OUT endpoint\n");
1901 ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->outep);
1902 if (ret != OPENUSB_SUCCESS) {
1903 perror("usb_clear_stall_feature()");
1908 /* TODO: do we need this for INTERRUPT (ptp_usb->intep) too? */
1911 static void clear_halt(PTP_USB* ptp_usb) {
1915 ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->inep);
1917 perror("usb_clear_halt() on IN endpoint");
1919 ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->outep);
1921 perror("usb_clear_halt() on OUT endpoint");
1923 ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->intep);
1925 perror("usb_clear_halt() on INTERRUPT endpoint");
1930 static void close_usb(PTP_USB* ptp_usb) {
1931 if (!FLAG_NO_RELEASE_INTERFACE(ptp_usb)) {
1933 * Clear any stalled endpoints
1934 * On misbehaving devices designed for Windows/Mac, quote from:
1935 * http://www2.one-eyed-alien.net/~mdharm/linux-usb/target_offenses.txt
1936 * Device does Bad Things(tm) when it gets a GET_STATUS after CLEAR_HALT
1937 * (...) Windows, when clearing a stall, only sends the CLEAR_HALT command,
1938 * and presumes that the stall has cleared. Some devices actually choke
1939 * if the CLEAR_HALT is followed by a GET_STATUS (used to determine if the
1940 * STALL is persistant or not).
1942 clear_stall(ptp_usb);
1943 // Clear halts on any endpoints
1944 clear_halt(ptp_usb);
1945 // Added to clear some stuff on the OUT endpoint
1946 // TODO: is this good on the Mac too?
1947 // HINT: some devices may need that you comment these two out too.
1948 //libusb_clear_halt(ptp_usb->handle, ptp_usb->outep);
1949 //libusb_release_interface(ptp_usb->handle, (int) ptp_usb->interface);
1951 if (FLAG_FORCE_RESET_ON_CLOSE(ptp_usb)) {
1953 * Some devices really love to get reset after being
1954 * disconnected. Again, since Windows never disconnects
1955 * a device closing behaviour is seldom or never exercised
1956 * on devices when engineered and often error prone.
1957 * Reset may help some.
1959 openusb_reset(*ptp_usb->handle);
1961 openusb_close_device(*ptp_usb->handle);
1967 static int find_interface_and_endpoints(openusb_dev_handle_t *dev,
1970 uint8_t *altsetting,
1972 int* inep_maxpacket,
1974 int *outep_maxpacket,
1978 struct usb_device_desc desc;
1980 ret = openusb_parse_device_desc(libmtp_openusb_handle, *dev, NULL, 0, &desc);
1981 if (ret != OPENUSB_SUCCESS) return -1;
1983 // Loop over the device configurations
1984 for (i = 0; i < desc.bNumConfigurations; i++) {
1986 struct usb_config_desc config;
1988 ret = openusb_parse_config_desc(libmtp_openusb_handle, *dev, NULL, 0, i, &config);
1989 if (ret != OPENUSB_SUCCESS) continue;
1990 *conf = desc.bConfigurationValue;
1991 // Loop over each configurations interfaces
1992 for (j = 0; j < config.bNumInterfaces; j++) {
1996 int found_outep = 0;
1997 int found_intep = 0;
1998 struct usb_endpoint_desc ep;
1999 struct usb_interface_desc ifcdesc;
2000 openusb_parse_interface_desc(libmtp_openusb_handle, *dev, NULL, 0, i, j, 0, &ifcdesc);
2001 // MTP devices shall have 3 endpoints, ignore those interfaces
2003 no_ep = ifcdesc.bNumEndpoints;
2006 *interface = ifcdesc.bInterfaceNumber;
2007 *altsetting = ifcdesc.bAlternateSetting;
2008 // Loop over the three endpoints to locate two bulk and
2009 // one interrupt endpoint and FAIL if we cannot, and continue.
2010 for (k = 0; k < no_ep; k++) {
2011 openusb_parse_endpoint_desc(libmtp_openusb_handle, *dev, NULL, 0, i, j, 0, k, &ep);
2012 if (ep.bmAttributes == USB_ENDPOINT_TYPE_BULK) {
2013 if ((ep.bEndpointAddress & USB_ENDPOINT_DIR_MASK) ==
2014 USB_ENDPOINT_DIR_MASK) {
2015 *inep = ep.bEndpointAddress;
2016 *inep_maxpacket = ep.wMaxPacketSize;
2019 if ((ep.bEndpointAddress & USB_ENDPOINT_DIR_MASK) == 0) {
2020 *outep = ep.bEndpointAddress;
2021 *outep_maxpacket = ep.wMaxPacketSize;
2024 } else if (ep.bmAttributes == USB_ENDPOINT_TYPE_INTERRUPT) {
2025 if ((ep.bEndpointAddress & USB_ENDPOINT_DIR_MASK) ==
2026 USB_ENDPOINT_DIR_MASK) {
2027 *intep = ep.bEndpointAddress;
2032 if (found_inep && found_outep && found_intep) {
2033 // We assigned the endpoints so return here.
2036 // Else loop to next interface/config
2043 * This function assigns params and usbinfo given a raw device
2045 * @param device the device to be assigned.
2046 * @param usbinfo a pointer to the new usbinfo.
2047 * @return an error code.
2049 LIBMTP_error_number_t configure_usb_device(LIBMTP_raw_device_t *device,
2053 openusb_devid_t *ldevice;
2055 int err, found = 0, i;
2056 unsigned int nrofdevs;
2057 openusb_devid_t *devs = NULL;
2058 struct usb_device_desc desc;
2060 /* See if we can find this raw device again... */
2063 openusb_get_devids_by_bus(libmtp_openusb_handle, 0, &devs, &nrofdevs);
2064 for (i = 0; i < nrofdevs; i++) {
2066 if (libusb_get_bus_number(devs[i]) != device->bus_location)
2068 if (libusb_get_device_address(devs[i]) != device->devnum)
2072 ret = openusb_parse_device_desc(libmtp_openusb_handle, devs[i], NULL, 0, &desc);
2073 if (ret != OPENUSB_SUCCESS) continue;
2075 if (desc.idVendor == device->device_entry.vendor_id &&
2076 desc.idProduct == device->device_entry.product_id) {
2082 /* Device has gone since detecting raw devices! */
2084 openusb_free_devid_list(devs);
2085 return LIBMTP_ERROR_NO_DEVICE_ATTACHED;
2088 /* Allocate structs */
2089 ptp_usb = (PTP_USB *) malloc(sizeof (PTP_USB));
2090 if (ptp_usb == NULL) {
2091 openusb_free_devid_list(devs);
2092 return LIBMTP_ERROR_MEMORY_ALLOCATION;
2094 /* Start with a blank slate (includes setting device_flags to 0) */
2095 memset(ptp_usb, 0, sizeof (PTP_USB));
2097 /* Copy the raw device */
2098 memcpy(&ptp_usb->rawdevice, device, sizeof (LIBMTP_raw_device_t));
2101 * Some devices must have their "OS Descriptor" massaged in order
2104 if (FLAG_ALWAYS_PROBE_DESCRIPTOR(ptp_usb)) {
2105 // Massage the device descriptor
2106 (void) probe_device_descriptor(ldevice, NULL);
2110 /* Assign interface and endpoints to usbinfo... */
2111 err = find_interface_and_endpoints(ldevice,
2113 &ptp_usb->interface,
2114 &ptp_usb->altsetting,
2116 &ptp_usb->inep_maxpacket,
2118 &ptp_usb->outep_maxpacket,
2122 openusb_free_devid_list(devs);
2123 LIBMTP_ERROR("LIBMTP PANIC: Unable to find interface & endpoints of device\n");
2124 return LIBMTP_ERROR_CONNECTING;
2127 /* Copy USB version number */
2128 ptp_usb->bcdusb = desc.bcdUSB;
2130 /* Attempt to initialize this device */
2131 if (init_ptp_usb(params, ptp_usb, ldevice) < 0) {
2132 LIBMTP_ERROR("LIBMTP PANIC: Unable to initialize device\n");
2133 return LIBMTP_ERROR_CONNECTING;
2137 * This works in situations where previous bad applications
2138 * have not used LIBMTP_Release_Device on exit
2140 if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) {
2141 LIBMTP_ERROR("PTP_ERROR_IO: failed to open session, trying again after resetting USB interface\n");
2142 LIBMTP_ERROR("LIBMTP libusb: Attempt to reset device\n");
2143 openusb_reset(*ptp_usb->handle);
2146 if (init_ptp_usb(params, ptp_usb, ldevice) < 0) {
2147 LIBMTP_ERROR("LIBMTP PANIC: Could not init USB on second attempt\n");
2148 return LIBMTP_ERROR_CONNECTING;
2151 /* Device has been reset, try again */
2152 if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) {
2153 LIBMTP_ERROR("LIBMTP PANIC: failed to open session on second attempt\n");
2154 return LIBMTP_ERROR_CONNECTING;
2158 /* Was the transaction id invalid? Try again */
2159 if (ret == PTP_RC_InvalidTransactionID) {
2160 LIBMTP_ERROR("LIBMTP WARNING: Transaction ID was invalid, increment and try again\n");
2161 params->transaction_id += 10;
2162 ret = ptp_opensession(params, 1);
2165 if (ret != PTP_RC_SessionAlreadyOpened && ret != PTP_RC_OK) {
2166 LIBMTP_ERROR("LIBMTP PANIC: Could not open session! "
2167 "(Return code %d)\n Try to reset the device.\n",
2169 openusb_release_interface(*ptp_usb->handle, ptp_usb->interface);
2170 return LIBMTP_ERROR_CONNECTING;
2173 /* OK configured properly */
2174 *usbinfo = (void *) ptp_usb;
2175 return LIBMTP_ERROR_NONE;
2178 void close_device(PTP_USB *ptp_usb, PTPParams *params) {
2179 if (ptp_closesession(params) != PTP_RC_OK)
2180 LIBMTP_ERROR("ERROR: Could not close session!\n");
2184 void set_usb_device_timeout(PTP_USB *ptp_usb, int timeout) {
2185 ptp_usb->timeout = timeout;
2188 void get_usb_device_timeout(PTP_USB *ptp_usb, int *timeout) {
2189 *timeout = ptp_usb->timeout;
2192 int guess_usb_speed(PTP_USB *ptp_usb) {
2193 int bytes_per_second;
2196 * We don't know the actual speeds so these are rough guesses
2197 * from the info you can find here:
2198 * http://en.wikipedia.org/wiki/USB#Transfer_rates
2199 * http://www.barefeats.com/usb2.html
2201 switch (ptp_usb->bcdusb & 0xFF00) {
2203 /* 1.x USB versions let's say 1MiB/s */
2204 bytes_per_second = 1 * 1024 * 1024;
2208 /* USB 2.0 nominal speed 18MiB/s */
2209 /* USB 3.0 won't be worse? */
2210 bytes_per_second = 18 * 1024 * 1024;
2213 /* Half-guess something? */
2214 bytes_per_second = 1 * 1024 * 1024;
2217 return bytes_per_second;
2220 static int usb_get_endpoint_status(PTP_USB* ptp_usb, int ep, uint16_t* status) {
2222 return libusb_control_transfer(ptp_usb->handle,
2223 LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_ENDPOINT,
2224 LIBUSB_REQUEST_GET_STATUS,
2227 (unsigned char *) status,
2231 struct openusb_ctrl_request ctrl;
2234 ctrl.payload = (unsigned char *)status;
2235 ctrl.timeout = ptp_usb->timeout;
2237 ctrl.setup.bRequest = USB_REQ_GET_STATUS;
2238 ctrl.setup.bmRequestType = USB_ENDPOINT_IN | USB_RECIP_ENDPOINT;
2239 ctrl.setup.wIndex = ep;
2240 ctrl.setup.wValue = USB_FEATURE_HALT;
2241 openusb_ctrl_xfer(*ptp_usb->handle, ptp_usb->interface, ep, &ctrl);
2242 return ctrl.result.status;