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 // This device is unknown to the developers
665 LIBMTP_ERROR("Device %d (VID=%04x and PID=%04x) is UNKNOWN.\n",
669 LIBMTP_ERROR("Please report this VID/PID and the device model to the libmtp development team\n");
671 * Trying to get iManufacturer or iProduct from the device at this
672 * point would require opening a device handle, that we don't want
673 * to do right now. (Takes time for no good enough reason.)
676 // Save the location on the bus
677 retdevs[i].bus_location = 0;
678 retdevs[i].devnum = openusb_get_devid(libmtp_openusb_handle, &dev->device);
684 free_mtpdevice_list(devlist);
685 return LIBMTP_ERROR_NONE;
689 * This routine just dumps out low-level
690 * USB information about the current device.
691 * @param ptp_usb the USB device to get information from.
693 void dump_usbinfo(PTP_USB *ptp_usb) {
694 struct usb_device_desc desc;
696 openusb_parse_device_desc(libmtp_openusb_handle, *ptp_usb->handle, NULL, 0, &desc);
698 LIBMTP_INFO(" bcdUSB: %d\n", desc.bcdUSB);
699 LIBMTP_INFO(" bDeviceClass: %d\n", desc.bDeviceClass);
700 LIBMTP_INFO(" bDeviceSubClass: %d\n", desc.bDeviceSubClass);
701 LIBMTP_INFO(" bDeviceProtocol: %d\n", desc.bDeviceProtocol);
702 LIBMTP_INFO(" idVendor: %04x\n", desc.idVendor);
703 LIBMTP_INFO(" idProduct: %04x\n", desc.idProduct);
704 LIBMTP_INFO(" IN endpoint maxpacket: %d bytes\n", ptp_usb->inep_maxpacket);
705 LIBMTP_INFO(" OUT endpoint maxpacket: %d bytes\n", ptp_usb->outep_maxpacket);
706 LIBMTP_INFO(" Raw device info:\n");
707 LIBMTP_INFO(" Bus location: %d\n", ptp_usb->rawdevice.bus_location);
708 LIBMTP_INFO(" Device number: %d\n", ptp_usb->rawdevice.devnum);
709 LIBMTP_INFO(" Device entry info:\n");
710 LIBMTP_INFO(" Vendor: %s\n", ptp_usb->rawdevice.device_entry.vendor);
711 LIBMTP_INFO(" Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.vendor_id);
712 LIBMTP_INFO(" Product: %s\n", ptp_usb->rawdevice.device_entry.product);
713 LIBMTP_INFO(" Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.product_id);
714 LIBMTP_INFO(" Device flags: 0x%08x\n", ptp_usb->rawdevice.device_entry.device_flags);
715 // TODO: (void) probe_device_descriptor(dev, stdout);
719 * Retrieve the apropriate playlist extension for this
720 * device. Rather hacky at the moment. This is probably
721 * desired by the managing software, but when creating
722 * lists on the device itself you notice certain preferences.
723 * @param ptp_usb the USB device to get suggestion for.
724 * @return the suggested playlist extension.
726 const char *get_playlist_extension(PTP_USB *ptp_usb) {
727 static char creative_pl_extension[] = ".zpl";
728 static char default_pl_extension[] = ".pla";
729 struct usb_device_desc desc;
730 openusb_parse_device_desc(libmtp_openusb_handle, *ptp_usb->handle, NULL, 0, &desc);
731 if (desc.idVendor == 0x041e)
732 return creative_pl_extension;
733 return default_pl_extension;
737 libusb_glue_debug(PTPParams *params, const char *format, ...) {
740 va_start(args, format);
741 if (params->debug_func != NULL)
742 params->debug_func(params->data, format, args);
744 vfprintf(stderr, format, args);
745 fprintf(stderr, "\n");
752 libusb_glue_error(PTPParams *params, const char *format, ...) {
755 va_start(args, format);
756 if (params->error_func != NULL)
757 params->error_func(params->data, format, args);
759 vfprintf(stderr, format, args);
760 fprintf(stderr, "\n");
768 * ptp_read_func() and ptp_write_func() are
769 * based on same functions usb.c in libgphoto2.
770 * Much reading packet logs and having fun with trials and errors
771 * reveals that WMP / Windows is probably using an algorithm like this
772 * for large transfers:
774 * 1. Send the command (0x0c bytes) if headers are split, else, send
775 * command plus sizeof(endpoint) - 0x0c bytes.
776 * 2. Send first packet, max size to be sizeof(endpoint) but only when using
777 * split headers. Else goto 3.
778 * 3. REPEAT send 0x10000 byte chunks UNTIL remaining bytes < 0x10000
779 * We call 0x10000 CONTEXT_BLOCK_SIZE.
780 * 4. Send remaining bytes MOD sizeof(endpoint)
781 * 5. Send remaining bytes. If this happens to be exactly sizeof(endpoint)
782 * then also send a zero-length package.
784 * Further there is some special quirks to handle zero reads from the
785 * device, since some devices can't do them at all due to shortcomings
786 * of the USB slave controller in the device.
788 #define CONTEXT_BLOCK_SIZE_1 0x3e00
789 #define CONTEXT_BLOCK_SIZE_2 0x200
790 #define CONTEXT_BLOCK_SIZE CONTEXT_BLOCK_SIZE_1+CONTEXT_BLOCK_SIZE_2
794 unsigned long size, PTPDataHandler *handler, void *data,
795 unsigned long *readbytes,
798 PTP_USB *ptp_usb = (PTP_USB *) data;
799 unsigned long toread = 0;
802 unsigned long curread = 0;
803 unsigned long written;
804 unsigned char *bytes;
805 int expect_terminator_byte = 0;
806 unsigned long usb_inep_maxpacket_size;
807 unsigned long context_block_size_1;
808 unsigned long context_block_size_2;
809 uint16_t ptp_dev_vendor_id = ptp_usb->rawdevice.device_entry.vendor_id;
811 //"iRiver" device special handling
812 if (ptp_dev_vendor_id == 0x4102 || ptp_dev_vendor_id == 0x1006) {
813 usb_inep_maxpacket_size = ptp_usb->inep_maxpacket;
814 if (usb_inep_maxpacket_size == 0x400) {
815 context_block_size_1 = CONTEXT_BLOCK_SIZE_1 - 0x200;
816 context_block_size_2 = CONTEXT_BLOCK_SIZE_2 + 0x200;
819 context_block_size_1 = CONTEXT_BLOCK_SIZE_1;
820 context_block_size_2 = CONTEXT_BLOCK_SIZE_2;
823 struct openusb_bulk_request bulk;
824 // This is the largest block we'll need to read in.
825 bytes = malloc(CONTEXT_BLOCK_SIZE);
826 while (curread < size) {
828 LIBMTP_USB_DEBUG("Remaining size to read: 0x%04lx bytes\n", size - curread);
830 // check equal to condition here
831 if (size - curread < CONTEXT_BLOCK_SIZE) {
832 // this is the last packet
833 toread = size - curread;
834 // this is equivalent to zero read for these devices
835 if (readzero && FLAG_NO_ZERO_READS(ptp_usb) && toread % 64 == 0) {
837 expect_terminator_byte = 1;
839 } else if (ptp_dev_vendor_id == 0x4102 || ptp_dev_vendor_id == 0x1006) {
840 //"iRiver" device special handling
842 // we are first packet, but not last packet
843 toread = context_block_size_1;
844 else if (toread == context_block_size_1)
845 toread = context_block_size_2;
846 else if (toread == context_block_size_2)
847 toread = context_block_size_1;
849 LIBMTP_INFO("unexpected toread size 0x%04x, 0x%04x remaining bytes\n",
850 (unsigned int) toread, (unsigned int) (size - curread));
853 toread = CONTEXT_BLOCK_SIZE;
855 LIBMTP_USB_DEBUG("Reading in 0x%04lx bytes\n", toread);
858 ret = USB_BULK_READ(ptp_usb->handle,
865 bulk.payload = bytes;
866 bulk.length = toread;
867 bulk.timeout = ptp_usb->timeout;
870 ret = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->inep, &bulk);
871 xread = bulk.result.transferred_bytes;
872 LIBMTP_USB_DEBUG("Result of read: 0x%04x (%d bytes)\n", ret, xread);
874 if (ret != OPENUSB_SUCCESS)
877 LIBMTP_USB_DEBUG("<==USB IN\n");
879 LIBMTP_USB_DEBUG("Zero Read\n");
881 LIBMTP_USB_DATA(bytes, xread, 16);
883 // want to discard extra byte
884 if (expect_terminator_byte && xread == toread) {
885 LIBMTP_USB_DEBUG("<==USB IN\nDiscarding extra byte\n");
890 int putfunc_ret = handler->putfunc(NULL, handler->priv, xread, bytes, &written);
891 LIBMTP_USB_DEBUG("handler->putfunc ret = 0x%x\n", putfunc_ret);
892 if (putfunc_ret != PTP_RC_OK)
895 ptp_usb->current_transfer_complete += xread;
898 // Increase counters, call callback
899 if (ptp_usb->callback_active) {
900 if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
901 // send last update and disable callback.
902 ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total;
903 ptp_usb->callback_active = 0;
905 if (ptp_usb->current_transfer_callback != NULL) {
907 ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete,
908 ptp_usb->current_transfer_total,
909 ptp_usb->current_transfer_callback_data);
911 return PTP_ERROR_CANCEL;
916 if (xread < toread) /* short reads are common */
919 if (readbytes) *readbytes = curread;
921 LIBMTP_USB_DEBUG("Pointer Updated\n");
922 // there might be a zero packet waiting for us...
924 !FLAG_NO_ZERO_READS(ptp_usb) &&
925 curread % ptp_usb->outep_maxpacket == 0) {
927 int zeroresult = 0, xread;
929 LIBMTP_USB_DEBUG("<==USB IN\n");
930 LIBMTP_USB_DEBUG("Zero Read\n");
933 zeroresult = USB_BULK_READ(ptp_usb->handle,
940 bulk.payload = &temp;
942 bulk.timeout = ptp_usb->timeout;
945 ret = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->inep, &bulk);
946 xread = bulk.result.transferred_bytes;
947 if (zeroresult != OPENUSB_SUCCESS)
948 LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult);
956 PTPDataHandler *handler,
958 unsigned long *written
960 PTP_USB *ptp_usb = (PTP_USB *) data;
961 unsigned long towrite = 0;
963 unsigned long curwrite = 0;
964 unsigned char *bytes;
966 struct openusb_bulk_request bulk;
968 // This is the largest block we'll need to read in.
969 bytes = malloc(CONTEXT_BLOCK_SIZE);
973 while (curwrite < size) {
974 unsigned long usbwritten = 0;
977 towrite = size - curwrite;
978 if (towrite > CONTEXT_BLOCK_SIZE) {
979 towrite = CONTEXT_BLOCK_SIZE;
981 // This magic makes packets the same size that WMP send them.
982 if (towrite > ptp_usb->outep_maxpacket && towrite % ptp_usb->outep_maxpacket != 0) {
983 towrite -= towrite % ptp_usb->outep_maxpacket;
986 int getfunc_ret = handler->getfunc(NULL, handler->priv, towrite, bytes, &towrite);
987 if (getfunc_ret != PTP_RC_OK)
989 while (usbwritten < towrite) {
991 ret = USB_BULK_WRITE(ptp_usb->handle,
994 towrite - usbwritten,
998 bulk.payload = bytes + usbwritten;
999 bulk.length = towrite - usbwritten;
1000 bulk.timeout = ptp_usb->timeout;
1003 ret = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->outep, &bulk);
1004 xwritten = bulk.result.transferred_bytes;
1006 LIBMTP_USB_DEBUG("USB OUT==>\n");
1008 if (ret != OPENUSB_SUCCESS) {
1009 return PTP_ERROR_IO;
1011 LIBMTP_USB_DATA(bytes + usbwritten, xwritten, 16);
1012 // check for result == 0 perhaps too.
1013 // Increase counters
1014 ptp_usb->current_transfer_complete += xwritten;
1015 curwrite += xwritten;
1016 usbwritten += xwritten;
1019 if (ptp_usb->callback_active) {
1020 if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
1021 // send last update and disable callback.
1022 ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total;
1023 ptp_usb->callback_active = 0;
1025 if (ptp_usb->current_transfer_callback != NULL) {
1027 ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete,
1028 ptp_usb->current_transfer_total,
1029 ptp_usb->current_transfer_callback_data);
1031 return PTP_ERROR_CANCEL;
1035 if (xwritten < towrite) /* short writes happen */
1040 *written = curwrite;
1043 // If this is the last transfer send a zero write if required
1044 if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
1045 if ((towrite % ptp_usb->outep_maxpacket) == 0) {
1048 LIBMTP_USB_DEBUG("USB OUT==>\n");
1049 LIBMTP_USB_DEBUG("Zero Write\n");
1052 ret = USB_BULK_WRITE(ptp_usb->handle,
1054 (unsigned char *) "x",
1059 bulk.payload = (unsigned char *) "x";
1061 bulk.timeout = ptp_usb->timeout;
1064 ret = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->outep, &bulk);
1065 xwritten = bulk.result.transferred_bytes;
1069 if (ret != OPENUSB_SUCCESS)
1070 return PTP_ERROR_IO;
1074 /* memory data get/put handler */
1076 unsigned char *data;
1077 unsigned long size, curoff;
1078 } PTPMemHandlerPrivate;
1081 memory_getfunc(PTPParams* params, void* private,
1082 unsigned long wantlen, unsigned char *data,
1083 unsigned long *gotlen
1085 PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*) private;
1086 unsigned long tocopy = wantlen;
1088 if (priv->curoff + tocopy > priv->size)
1089 tocopy = priv->size - priv->curoff;
1090 memcpy(data, priv->data + priv->curoff, tocopy);
1091 priv->curoff += tocopy;
1097 memory_putfunc(PTPParams* params, void* private,
1098 unsigned long sendlen, unsigned char *data,
1099 unsigned long *putlen
1101 PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*) private;
1103 if (priv->curoff + sendlen > priv->size) {
1104 priv->data = realloc(priv->data, priv->curoff + sendlen);
1105 priv->size = priv->curoff + sendlen;
1107 memcpy(priv->data + priv->curoff, data, sendlen);
1108 priv->curoff += sendlen;
1113 /* init private struct for receiving data. */
1115 ptp_init_recv_memory_handler(PTPDataHandler *handler) {
1116 PTPMemHandlerPrivate* priv;
1117 priv = malloc(sizeof (PTPMemHandlerPrivate));
1118 handler->priv = priv;
1119 handler->getfunc = memory_getfunc;
1120 handler->putfunc = memory_putfunc;
1127 /* init private struct and put data in for sending data.
1128 * data is still owned by caller.
1131 ptp_init_send_memory_handler(PTPDataHandler *handler,
1132 unsigned char *data, unsigned long len
1134 PTPMemHandlerPrivate* priv;
1135 priv = malloc(sizeof (PTPMemHandlerPrivate));
1137 return PTP_RC_GeneralError;
1139 handler->priv = priv;
1140 handler->getfunc = memory_getfunc;
1141 handler->putfunc = memory_putfunc;
1148 /* free private struct + data */
1150 ptp_exit_send_memory_handler(PTPDataHandler *handler) {
1151 PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*) handler->priv;
1152 /* data is owned by caller */
1157 /* hand over our internal data to caller */
1159 ptp_exit_recv_memory_handler(PTPDataHandler *handler,
1160 unsigned char **data, unsigned long *size
1162 PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*) handler->priv;
1169 /* send / receive functions */
1172 ptp_usb_sendreq(PTPParams* params, PTPContainer* req) {
1174 PTPUSBBulkContainer usbreq;
1175 PTPDataHandler memhandler;
1176 unsigned long written = 0;
1177 unsigned long towrite;
1181 (void) ptp_render_opcode(params, req->Code, sizeof (txt), txt);
1182 LIBMTP_USB_DEBUG("REQUEST: 0x%04x, %s\n", req->Code, txt);
1184 /* build appropriate USB container */
1185 usbreq.length = htod32(PTP_USB_BULK_REQ_LEN -
1186 (sizeof (uint32_t)*(5 - req->Nparam)));
1187 usbreq.type = htod16(PTP_USB_CONTAINER_COMMAND);
1188 usbreq.code = htod16(req->Code);
1189 usbreq.trans_id = htod32(req->Transaction_ID);
1190 usbreq.payload.params.param1 = htod32(req->Param1);
1191 usbreq.payload.params.param2 = htod32(req->Param2);
1192 usbreq.payload.params.param3 = htod32(req->Param3);
1193 usbreq.payload.params.param4 = htod32(req->Param4);
1194 usbreq.payload.params.param5 = htod32(req->Param5);
1195 /* send it to responder */
1196 towrite = PTP_USB_BULK_REQ_LEN - (sizeof (uint32_t)*(5 - req->Nparam));
1197 ptp_init_send_memory_handler(&memhandler, (unsigned char*) &usbreq, towrite);
1198 ret = ptp_write_func(
1204 ptp_exit_send_memory_handler(&memhandler);
1205 if (ret != PTP_RC_OK && ret != PTP_ERROR_CANCEL) {
1208 if (written != towrite && ret != PTP_ERROR_CANCEL && ret != PTP_ERROR_IO) {
1209 libusb_glue_error(params,
1210 "PTP: request code 0x%04x sending req wrote only %ld bytes instead of %d",
1211 req->Code, written, towrite
1219 ptp_usb_senddata(PTPParams* params, PTPContainer* ptp,
1220 uint64_t size, PTPDataHandler *handler
1224 unsigned long written;
1225 PTPUSBBulkContainer usbdata;
1226 uint64_t bytes_left_to_transfer;
1227 PTPDataHandler memhandler;
1229 LIBMTP_USB_DEBUG("SEND DATA PHASE\n");
1231 /* build appropriate USB container */
1232 usbdata.length = htod32(PTP_USB_BULK_HDR_LEN + size);
1233 usbdata.type = htod16(PTP_USB_CONTAINER_DATA);
1234 usbdata.code = htod16(ptp->Code);
1235 usbdata.trans_id = htod32(ptp->Transaction_ID);
1237 ((PTP_USB*) params->data)->current_transfer_complete = 0;
1238 ((PTP_USB*) params->data)->current_transfer_total = size + PTP_USB_BULK_HDR_LEN;
1240 if (params->split_header_data) {
1242 wlen = PTP_USB_BULK_HDR_LEN;
1244 unsigned long gotlen;
1245 /* For all camera devices. */
1246 datawlen = (size < PTP_USB_BULK_PAYLOAD_LEN_WRITE) ? size : PTP_USB_BULK_PAYLOAD_LEN_WRITE;
1247 wlen = PTP_USB_BULK_HDR_LEN + datawlen;
1249 ret = handler->getfunc(params, handler->priv, datawlen, usbdata.payload.data, &gotlen);
1250 if (ret != PTP_RC_OK){
1254 if (gotlen != datawlen){
1255 return PTP_RC_GeneralError;
1258 ptp_init_send_memory_handler(&memhandler, (unsigned char *) &usbdata, wlen);
1259 /* send first part of data */
1260 ret = ptp_write_func(wlen, &memhandler, params->data, &written);
1261 ptp_exit_send_memory_handler(&memhandler);
1262 if (ret != PTP_RC_OK) {
1265 if (size <= datawlen) return ret;
1266 /* if everything OK send the rest */
1267 bytes_left_to_transfer = size - datawlen;
1269 while (bytes_left_to_transfer > 0) {
1270 ret = ptp_write_func(bytes_left_to_transfer, handler, params->data, &written);
1271 if (ret != PTP_RC_OK){
1278 bytes_left_to_transfer -= written;
1280 if (ret != PTP_RC_OK && ret != PTP_ERROR_CANCEL)
1285 static uint16_t ptp_usb_getpacket(PTPParams *params,
1286 PTPUSBBulkContainer *packet, unsigned long *rlen) {
1287 PTPDataHandler memhandler;
1289 unsigned char *x = NULL;
1290 unsigned long packet_size;
1291 PTP_USB *ptp_usb = (PTP_USB *) params->data;
1293 packet_size = ptp_usb->inep_maxpacket;
1295 /* read the header and potentially the first data */
1296 if (params->response_packet_size > 0) {
1297 /* If there is a buffered packet, just use it. */
1298 memcpy(packet, params->response_packet, params->response_packet_size);
1299 *rlen = params->response_packet_size;
1300 free(params->response_packet);
1301 params->response_packet = NULL;
1302 params->response_packet_size = 0;
1303 /* Here this signifies a "virtual read" */
1306 ptp_init_recv_memory_handler(&memhandler);
1307 ret = ptp_read_func(packet_size, &memhandler, params->data, rlen, 0);
1308 ptp_exit_recv_memory_handler(&memhandler, &x, rlen);
1310 memcpy(packet, x, *rlen);
1317 ptp_usb_getdata(PTPParams* params, PTPContainer* ptp, PTPDataHandler *handler) {
1319 PTPUSBBulkContainer usbdata;
1320 unsigned long written;
1321 PTP_USB *ptp_usb = (PTP_USB *) params->data;
1324 LIBMTP_USB_DEBUG("GET DATA PHASE\n");
1326 struct openusb_bulk_request bulk;
1328 memset(&usbdata, 0, sizeof (usbdata));
1330 unsigned long len, rlen;
1332 ret = ptp_usb_getpacket(params, &usbdata, &rlen);
1333 if (ret != PTP_RC_OK) {
1337 if (dtoh16(usbdata.type) != PTP_USB_CONTAINER_DATA) {
1338 ret = PTP_ERROR_DATA_EXPECTED;
1341 if (dtoh16(usbdata.code) != ptp->Code) {
1342 if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) {
1343 libusb_glue_debug(params, "ptp2/ptp_usb_getdata: detected a broken "
1344 "PTP header, code field insane, expect problems! (But continuing)");
1345 // Repair the header, so it won't wreak more havoc, don't just ignore it.
1346 // Typically these two fields will be broken.
1347 usbdata.code = htod16(ptp->Code);
1348 usbdata.trans_id = htod32(ptp->Transaction_ID);
1351 ret = dtoh16(usbdata.code);
1352 // This filters entirely insane garbage return codes, but still
1353 // makes it possible to return error codes in the code field when
1354 // getting data. It appears Windows ignores the contents of this
1356 if (ret < PTP_RC_Undefined || ret > PTP_RC_SpecificationOfDestinationUnsupported) {
1357 libusb_glue_debug(params, "ptp2/ptp_usb_getdata: detected a broken "
1358 "PTP header, code field insane.");
1364 if (rlen == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ) {
1365 /* Copy first part of data to 'data' */
1368 params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN, usbdata.payload.data,
1371 if (putfunc_ret != PTP_RC_OK)
1374 /* stuff data directly to passed data handler */
1376 unsigned long readdata;
1379 xret = ptp_read_func(
1386 if (xret != PTP_RC_OK)
1388 if (readdata < 0x20000000)
1393 if (rlen > dtoh32(usbdata.length)) {
1395 * Buffer the surplus response packet if it is >=
1396 * PTP_USB_BULK_HDR_LEN
1397 * (i.e. it is probably an entire package)
1398 * else discard it as erroneous surplus data.
1399 * This will even work if more than 2 packets appear
1400 * in the same transaction, they will just be handled
1403 * Marcus observed stray bytes on iRiver devices;
1404 * these are still discarded.
1406 unsigned int packlen = dtoh32(usbdata.length);
1407 unsigned int surplen = rlen - packlen;
1409 if (surplen >= PTP_USB_BULK_HDR_LEN) {
1410 params->response_packet = malloc(surplen);
1411 memcpy(params->response_packet,
1412 (uint8_t *) & usbdata + packlen, surplen);
1413 params->response_packet_size = surplen;
1414 /* Ignore reading one extra byte if device flags have been set */
1415 } else if (!FLAG_NO_ZERO_READS(ptp_usb) &&
1416 (rlen - dtoh32(usbdata.length) == 1)) {
1417 libusb_glue_debug(params, "ptp2/ptp_usb_getdata: read %d bytes "
1418 "too much, expect problems!",
1419 rlen - dtoh32(usbdata.length));
1424 /* For most PTP devices rlen is 512 == sizeof(usbdata)
1425 * here. For MTP devices splitting header and data it might
1428 /* Evaluate full data length. */
1429 len = dtoh32(usbdata.length) - PTP_USB_BULK_HDR_LEN;
1431 /* autodetect split header/data MTP devices */
1432 if (dtoh32(usbdata.length) > 12 && (rlen == 12))
1433 params->split_header_data = 1;
1435 /* Copy first part of data to 'data' */
1438 params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN,
1439 usbdata.payload.data,
1442 if (putfunc_ret != PTP_RC_OK)
1445 if (FLAG_NO_ZERO_READS(ptp_usb) &&
1446 len + PTP_USB_BULK_HDR_LEN == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ) {
1448 LIBMTP_USB_DEBUG("Reading in extra terminating byte\n");
1450 // need to read in extra byte and discard it
1451 int result = 0, xread;
1452 unsigned char byte = 0;
1455 result = USB_BULK_READ(ptp_usb->handle,
1463 bulk.payload = &byte;
1465 bulk.timeout = ptp_usb->timeout;
1468 result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->inep, &bulk);
1469 xread = bulk.result.transferred_bytes;
1472 LIBMTP_INFO("Could not read in extra byte for PTP_USB_BULK_HS_MAX_PACKET_LEN_READ long file, return value 0x%04x\n", result);
1473 } else if (len + PTP_USB_BULK_HDR_LEN == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ && params->split_header_data == 0) {
1474 int zeroresult = 0, xread;
1475 unsigned char zerobyte = 0;
1477 LIBMTP_INFO("Reading in zero packet after header\n");
1479 zeroresult = USB_BULK_READ(ptp_usb->handle,
1487 bulk.payload = &zerobyte;
1489 bulk.timeout = ptp_usb->timeout;
1492 zeroresult = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->inep, &bulk);
1493 xread = bulk.result.transferred_bytes;
1495 if (zeroresult != 0)
1496 LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult);
1499 /* Is that all of data? */
1500 if (len + PTP_USB_BULK_HDR_LEN <= rlen) {
1504 ret = ptp_read_func(len - (rlen - PTP_USB_BULK_HDR_LEN),
1506 params->data, &rlen, 1);
1508 if (ret != PTP_RC_OK) {
1516 ptp_usb_getresp(PTPParams* params, PTPContainer* resp) {
1519 PTPUSBBulkContainer usbresp;
1520 PTP_USB *ptp_usb = (PTP_USB *) (params->data);
1523 LIBMTP_USB_DEBUG("RESPONSE: ");
1524 memset(&usbresp, 0, sizeof (usbresp));
1525 /* read response, it should never be longer than sizeof(usbresp) */
1526 ret = ptp_usb_getpacket(params, &usbresp, &rlen);
1527 // Fix for bevahiour reported by Scott Snyder on Samsung YP-U3. The player
1528 // sends a packet containing just zeroes of length 2 (up to 4 has been seen too)
1529 // after a NULL packet when it should send the response. This code ignores
1530 // such illegal packets.
1531 while (ret == PTP_RC_OK && rlen < PTP_USB_BULK_HDR_LEN && usbresp.length == 0) {
1532 libusb_glue_debug(params, "ptp_usb_getresp: detected short response "
1533 "of %d bytes, expect problems! (re-reading "
1535 ret = ptp_usb_getpacket(params, &usbresp, &rlen);
1537 if (ret != PTP_RC_OK) {
1540 if (dtoh16(usbresp.type) != PTP_USB_CONTAINER_RESPONSE) {
1541 ret = PTP_ERROR_RESP_EXPECTED;
1543 if (dtoh16(usbresp.code) != resp->Code) {
1544 ret = dtoh16(usbresp.code);
1547 LIBMTP_USB_DEBUG("%04x\n", ret);
1548 if (ret != PTP_RC_OK) {
1549 /* libusb_glue_error (params,
1550 "PTP: request code 0x%04x getting resp error 0x%04x",
1554 /* build an appropriate PTPContainer */
1555 resp->Code = dtoh16(usbresp.code);
1556 resp->SessionID = params->session_id;
1557 resp->Transaction_ID = dtoh32(usbresp.trans_id);
1558 if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) {
1559 if (resp->Transaction_ID != params->transaction_id - 1) {
1560 libusb_glue_debug(params, "ptp_usb_getresp: detected a broken "
1561 "PTP header, transaction ID insane, expect "
1562 "problems! (But continuing)");
1563 // Repair the header, so it won't wreak more havoc.
1564 resp->Transaction_ID = params->transaction_id - 1;
1567 resp->Param1 = dtoh32(usbresp.payload.params.param1);
1568 resp->Param2 = dtoh32(usbresp.payload.params.param2);
1569 resp->Param3 = dtoh32(usbresp.payload.params.param3);
1570 resp->Param4 = dtoh32(usbresp.payload.params.param4);
1571 resp->Param5 = dtoh32(usbresp.payload.params.param5);
1575 /* Event handling functions */
1577 /* PTP Events wait for or check mode */
1578 #define PTP_EVENT_CHECK 0x0000 /* waits for */
1579 #define PTP_EVENT_CHECK_FAST 0x0001 /* checks */
1581 static inline uint16_t
1582 ptp_usb_event(PTPParams* params, PTPContainer* event, int wait) {
1586 PTPUSBEventContainer usbevent;
1587 PTP_USB *ptp_usb = (PTP_USB *) (params->data);
1589 struct openusb_bulk_request bulk;
1591 memset(&usbevent, 0, sizeof (usbevent));
1593 if ((params == NULL) || (event == NULL))
1594 return PTP_ERROR_BADPARAM;
1597 case PTP_EVENT_CHECK:
1600 result = USB_BULK_READ(ptp_usb->handle,
1602 (unsigned char *) &usbevent,
1607 bulk.payload = (unsigned char *) &usbevent;
1608 bulk.length = sizeof (usbevent);
1609 bulk.timeout = ptp_usb->timeout;
1612 result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->intep, &bulk);
1613 xread = bulk.result.transferred_bytes;
1617 result = USB_BULK_READ(ptp_usb->handle,
1619 (unsigned char *) &usbevent,
1624 bulk.payload = (unsigned char *) &usbevent;
1625 bulk.length = sizeof (usbevent);
1626 bulk.timeout = ptp_usb->timeout;
1629 result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->intep, &bulk);
1630 xread = bulk.result.transferred_bytes;
1632 if (result < 0) ret = PTP_ERROR_IO;
1634 case PTP_EVENT_CHECK_FAST:
1636 result = USB_BULK_READ(ptp_usb->handle,
1638 (unsigned char *) &usbevent,
1643 bulk.payload = (unsigned char *) &usbevent;
1644 bulk.length = sizeof (usbevent);
1645 bulk.timeout = ptp_usb->timeout;
1648 result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->intep, &bulk);
1649 xread = bulk.result.transferred_bytes;
1653 result = USB_BULK_READ(ptp_usb->handle,
1655 (unsigned char *) &usbevent,
1660 bulk.payload = (unsigned char *) &usbevent;
1661 bulk.length = sizeof (usbevent);
1662 bulk.timeout = ptp_usb->timeout;
1665 result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->intep, &bulk);
1666 xread = bulk.result.transferred_bytes;
1668 if (result < 0) ret = PTP_ERROR_IO;
1671 ret = PTP_ERROR_BADPARAM;
1674 if (ret != PTP_RC_OK) {
1675 libusb_glue_error(params,
1676 "PTP: reading event an error 0x%04x occurred", ret);
1677 return PTP_ERROR_IO;
1681 libusb_glue_error(params,
1682 "PTP: reading event an short read of %ld bytes occurred", rlen);
1683 return PTP_ERROR_IO;
1685 /* if we read anything over interrupt endpoint it must be an event */
1686 /* build an appropriate PTPContainer */
1687 event->Code = dtoh16(usbevent.code);
1688 event->SessionID = params->session_id;
1689 event->Transaction_ID = dtoh32(usbevent.trans_id);
1690 event->Param1 = dtoh32(usbevent.param1);
1691 event->Param2 = dtoh32(usbevent.param2);
1692 event->Param3 = dtoh32(usbevent.param3);
1697 ptp_usb_event_check(PTPParams* params, PTPContainer* event) {
1699 return ptp_usb_event(params, event, PTP_EVENT_CHECK_FAST);
1703 ptp_usb_event_wait(PTPParams* params, PTPContainer* event) {
1705 return ptp_usb_event(params, event, PTP_EVENT_CHECK);
1709 ptp_usb_control_cancel_request(PTPParams *params, uint32_t transactionid) {
1710 PTP_USB *ptp_usb = (PTP_USB *) (params->data);
1712 unsigned char buffer[6];
1714 htod16a(&buffer[0], PTP_EC_CancelTransaction);
1715 htod32a(&buffer[2], transactionid);
1717 ret = libusb_control_transfer(ptp_usb->handle,
1718 LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
1719 0x64, 0x0000, 0x0000,
1724 struct openusb_ctrl_request ctrl;
1725 ctrl.setup.bmRequestType = USB_REQ_TYPE_CLASS | USB_RECIP_INTERFACE;
1726 ctrl.setup.bRequest = 0x64;
1727 ctrl.setup.wValue = 0;
1728 ctrl.setup.wIndex = 0;
1729 ctrl.payload = (unsigned char *)&buffer; // Out
1730 ctrl.length = sizeof (buffer);
1731 ctrl.timeout = ptp_usb->timeout;
1735 ret = openusb_ctrl_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->outep, &ctrl);
1736 if (ctrl.result.transferred_bytes < sizeof (buffer))
1737 return PTP_ERROR_IO;
1741 static int init_ptp_usb(PTPParams* params, PTP_USB* ptp_usb, openusb_dev_handle_t* dev) {
1742 openusb_dev_handle_t device_handle;
1743 unsigned char buf[255];
1746 params->sendreq_func = ptp_usb_sendreq;
1747 params->senddata_func = ptp_usb_senddata;
1748 params->getresp_func = ptp_usb_getresp;
1749 params->getdata_func = ptp_usb_getdata;
1750 params->cancelreq_func = ptp_usb_control_cancel_request;
1751 params->data = ptp_usb;
1752 params->transaction_id = 0;
1754 * This is hardcoded here since we have no devices whatsoever that are BE.
1755 * Change this the day we run into our first BE device (if ever).
1757 params->byteorder = PTP_DL_LE;
1759 ptp_usb->timeout = get_timeout(ptp_usb);
1761 ret = openusb_open_device(libmtp_openusb_handle, *dev, USB_INIT_DEFAULT, &device_handle);
1762 if (ret != OPENUSB_SUCCESS) {
1763 perror("usb_open()");
1766 ptp_usb->handle = malloc(sizeof(openusb_dev_handle_t));
1767 *ptp_usb->handle = device_handle;
1769 * If this device is known to be wrongfully claimed by other kernel
1770 * drivers (such as mass storage), then try to unload it to make it
1771 * accessible from user space.
1772 * Note: OpenUSB doesn't support this type of operation?
1775 if (FLAG_UNLOAD_DRIVER(ptp_usb) &&
1776 libusb_kernel_driver_active (device_handle, ptp_usb->interface)
1778 if (OPENUSB_SUCCESS != libusb_detach_kernel_driver (device_handle, ptp_usb->interface)) {
1783 // It seems like on kernel 2.6.31 if we already have it open on another
1784 // pthread in our app, we'll get an error if we try to claim it again,
1785 // but that error is harmless because our process already claimed the interface
1786 usbresult = openusb_claim_interface(device_handle, ptp_usb->interface, USB_INIT_DEFAULT);
1789 fprintf(stderr, "ignoring usb_claim_interface = %d", usbresult);
1791 if (FLAG_SWITCH_MODE_BLACKBERRY(ptp_usb)) {
1794 // FIXME : Only for BlackBerry Storm
1795 // What does it mean? Maybe switch mode...
1796 // This first control message is absolutely necessary
1799 ret = libusb_control_transfer(device_handle,
1800 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1801 0xaa, 0x00, 0x04, buf, 0x40, 1000);
1803 struct openusb_ctrl_request ctrl;
1804 ctrl.setup.bmRequestType = USB_REQ_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN;
1805 ctrl.setup.bRequest = 0xaa;
1806 ctrl.setup.wValue = 0;
1807 ctrl.setup.wIndex = 4;
1808 ctrl.payload = (unsigned char *)&buf; // Out
1810 ctrl.timeout = 1000;
1814 ret = openusb_ctrl_xfer(device_handle, ptp_usb->interface, ptp_usb->outep, &ctrl);
1815 LIBMTP_USB_DEBUG("BlackBerry magic part 1:\n");
1816 LIBMTP_USB_DATA(buf, ctrl.result.transferred_bytes, 16);
1819 // This control message is unnecessary
1821 ret = libusb_control_transfer(device_handle,
1822 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1823 0xa5, 0x00, 0x01, buf, 0x02, 1000);
1825 ctrl.setup.bmRequestType = USB_REQ_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN;
1826 ctrl.setup.bRequest = 0xa5;
1827 ctrl.setup.wValue = 0;
1828 ctrl.setup.wIndex = 1;
1829 ctrl.payload = (unsigned char *)&buf; // Out
1831 ctrl.timeout = 1000;
1835 ret = openusb_ctrl_xfer(device_handle, ptp_usb->interface, ptp_usb->outep, &ctrl);
1836 LIBMTP_USB_DEBUG("BlackBerry magic part 2:\n");
1837 LIBMTP_USB_DATA(buf, ctrl.result.transferred_bytes, 16);
1840 // This control message is unnecessary
1842 ret = libusb_control_transfer(device_handle,
1843 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1844 0xa8, 0x00, 0x01, buf, 0x05, 1000);
1846 ctrl.setup.bmRequestType = USB_REQ_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN;
1847 ctrl.setup.bRequest = 0xa8;
1848 ctrl.setup.wValue = 0;
1849 ctrl.setup.wIndex = 1;
1850 ctrl.payload = (unsigned char *)&buf; // Out
1852 ctrl.timeout = 1000;
1856 ret = openusb_ctrl_xfer(device_handle, ptp_usb->interface, ptp_usb->outep, &ctrl);
1857 LIBMTP_USB_DEBUG("BlackBerry magic part 3:\n");
1858 LIBMTP_USB_DATA(buf, ctrl.result.transferred_bytes, 16);
1861 // This control message is unnecessary
1863 ret = libusb_control_transfer(device_handle,
1864 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1865 0xa8, 0x00, 0x01, buf, 0x11, 1000);
1867 ctrl.setup.bmRequestType = USB_REQ_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN;
1868 ctrl.setup.bRequest = 0xa8;
1869 ctrl.setup.wValue = 0;
1870 ctrl.setup.wIndex = 1;
1871 ctrl.payload = (unsigned char *)&buf; // Out
1873 ctrl.timeout = 1000;
1877 ret = openusb_ctrl_xfer(device_handle, ptp_usb->interface, ptp_usb->outep, &ctrl);
1878 LIBMTP_USB_DEBUG("BlackBerry magic part 4:\n");
1879 LIBMTP_USB_DATA(buf, ctrl.result.transferred_bytes, 16);
1886 static void clear_stall(PTP_USB* ptp_usb) {
1890 /* check the inep status */
1893 ret = usb_get_endpoint_status(ptp_usb, ptp_usb->inep, &status);
1895 perror("inep: usb_get_endpoint_status()");
1896 } else if (status) {
1897 LIBMTP_INFO("Clearing stall on IN endpoint\n");
1898 ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->inep);
1899 if (ret != OPENUSB_SUCCESS) {
1900 perror("usb_clear_stall_feature()");
1904 /* check the outep status */
1906 ret = usb_get_endpoint_status(ptp_usb, ptp_usb->outep, &status);
1908 perror("outep: usb_get_endpoint_status()");
1909 } else if (status) {
1910 LIBMTP_INFO("Clearing stall on OUT endpoint\n");
1911 ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->outep);
1912 if (ret != OPENUSB_SUCCESS) {
1913 perror("usb_clear_stall_feature()");
1918 /* TODO: do we need this for INTERRUPT (ptp_usb->intep) too? */
1921 static void clear_halt(PTP_USB* ptp_usb) {
1925 ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->inep);
1927 perror("usb_clear_halt() on IN endpoint");
1929 ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->outep);
1931 perror("usb_clear_halt() on OUT endpoint");
1933 ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->intep);
1935 perror("usb_clear_halt() on INTERRUPT endpoint");
1940 static void close_usb(PTP_USB* ptp_usb) {
1941 if (!FLAG_NO_RELEASE_INTERFACE(ptp_usb)) {
1943 * Clear any stalled endpoints
1944 * On misbehaving devices designed for Windows/Mac, quote from:
1945 * http://www2.one-eyed-alien.net/~mdharm/linux-usb/target_offenses.txt
1946 * Device does Bad Things(tm) when it gets a GET_STATUS after CLEAR_HALT
1947 * (...) Windows, when clearing a stall, only sends the CLEAR_HALT command,
1948 * and presumes that the stall has cleared. Some devices actually choke
1949 * if the CLEAR_HALT is followed by a GET_STATUS (used to determine if the
1950 * STALL is persistant or not).
1952 clear_stall(ptp_usb);
1953 // Clear halts on any endpoints
1954 clear_halt(ptp_usb);
1955 // Added to clear some stuff on the OUT endpoint
1956 // TODO: is this good on the Mac too?
1957 // HINT: some devices may need that you comment these two out too.
1958 //libusb_clear_halt(ptp_usb->handle, ptp_usb->outep);
1959 //libusb_release_interface(ptp_usb->handle, (int) ptp_usb->interface);
1961 if (FLAG_FORCE_RESET_ON_CLOSE(ptp_usb)) {
1963 * Some devices really love to get reset after being
1964 * disconnected. Again, since Windows never disconnects
1965 * a device closing behaviour is seldom or never exercised
1966 * on devices when engineered and often error prone.
1967 * Reset may help some.
1969 openusb_reset(*ptp_usb->handle);
1971 openusb_close_device(*ptp_usb->handle);
1977 static int find_interface_and_endpoints(openusb_dev_handle_t *dev,
1980 uint8_t *altsetting,
1982 int* inep_maxpacket,
1984 int *outep_maxpacket,
1988 struct usb_device_desc desc;
1990 ret = openusb_parse_device_desc(libmtp_openusb_handle, *dev, NULL, 0, &desc);
1991 if (ret != OPENUSB_SUCCESS) return -1;
1993 // Loop over the device configurations
1994 for (i = 0; i < desc.bNumConfigurations; i++) {
1996 struct usb_config_desc config;
1998 ret = openusb_parse_config_desc(libmtp_openusb_handle, *dev, NULL, 0, i, &config);
1999 if (ret != OPENUSB_SUCCESS) continue;
2000 *conf = desc.bConfigurationValue;
2001 // Loop over each configurations interfaces
2002 for (j = 0; j < config.bNumInterfaces; j++) {
2006 int found_outep = 0;
2007 int found_intep = 0;
2008 struct usb_endpoint_desc ep;
2009 struct usb_interface_desc ifcdesc;
2010 openusb_parse_interface_desc(libmtp_openusb_handle, *dev, NULL, 0, i, j, 0, &ifcdesc);
2011 // MTP devices shall have 3 endpoints, ignore those interfaces
2013 no_ep = ifcdesc.bNumEndpoints;
2016 *interface = ifcdesc.bInterfaceNumber;
2017 *altsetting = ifcdesc.bAlternateSetting;
2018 // Loop over the three endpoints to locate two bulk and
2019 // one interrupt endpoint and FAIL if we cannot, and continue.
2020 for (k = 0; k < no_ep; k++) {
2021 openusb_parse_endpoint_desc(libmtp_openusb_handle, *dev, NULL, 0, i, j, 0, k, &ep);
2022 if (ep.bmAttributes == USB_ENDPOINT_TYPE_BULK) {
2023 if ((ep.bEndpointAddress & USB_ENDPOINT_DIR_MASK) ==
2024 USB_ENDPOINT_DIR_MASK) {
2025 *inep = ep.bEndpointAddress;
2026 *inep_maxpacket = ep.wMaxPacketSize;
2029 if ((ep.bEndpointAddress & USB_ENDPOINT_DIR_MASK) == 0) {
2030 *outep = ep.bEndpointAddress;
2031 *outep_maxpacket = ep.wMaxPacketSize;
2034 } else if (ep.bmAttributes == USB_ENDPOINT_TYPE_INTERRUPT) {
2035 if ((ep.bEndpointAddress & USB_ENDPOINT_DIR_MASK) ==
2036 USB_ENDPOINT_DIR_MASK) {
2037 *intep = ep.bEndpointAddress;
2042 if (found_inep && found_outep && found_intep) {
2043 // We assigned the endpoints so return here.
2046 // Else loop to next interface/config
2053 * This function assigns params and usbinfo given a raw device
2055 * @param device the device to be assigned.
2056 * @param usbinfo a pointer to the new usbinfo.
2057 * @return an error code.
2059 LIBMTP_error_number_t configure_usb_device(LIBMTP_raw_device_t *device,
2063 openusb_devid_t *ldevice;
2065 int err, found = 0, i;
2066 unsigned int nrofdevs;
2067 openusb_devid_t *devs = NULL;
2068 struct usb_device_desc desc;
2070 /* See if we can find this raw device again... */
2073 openusb_get_devids_by_bus(libmtp_openusb_handle, 0, &devs, &nrofdevs);
2074 for (i = 0; i < nrofdevs; i++) {
2076 if (libusb_get_bus_number(devs[i]) != device->bus_location)
2078 if (libusb_get_device_address(devs[i]) != device->devnum)
2082 ret = openusb_parse_device_desc(libmtp_openusb_handle, devs[i], NULL, 0, &desc);
2083 if (ret != OPENUSB_SUCCESS) continue;
2085 if (desc.idVendor == device->device_entry.vendor_id &&
2086 desc.idProduct == device->device_entry.product_id) {
2092 /* Device has gone since detecting raw devices! */
2094 openusb_free_devid_list(devs);
2095 return LIBMTP_ERROR_NO_DEVICE_ATTACHED;
2098 /* Allocate structs */
2099 ptp_usb = (PTP_USB *) malloc(sizeof (PTP_USB));
2100 if (ptp_usb == NULL) {
2101 openusb_free_devid_list(devs);
2102 return LIBMTP_ERROR_MEMORY_ALLOCATION;
2104 /* Start with a blank slate (includes setting device_flags to 0) */
2105 memset(ptp_usb, 0, sizeof (PTP_USB));
2107 /* Copy the raw device */
2108 memcpy(&ptp_usb->rawdevice, device, sizeof (LIBMTP_raw_device_t));
2111 * Some devices must have their "OS Descriptor" massaged in order
2114 if (FLAG_ALWAYS_PROBE_DESCRIPTOR(ptp_usb)) {
2115 // Massage the device descriptor
2116 (void) probe_device_descriptor(ldevice, NULL);
2120 /* Assign interface and endpoints to usbinfo... */
2121 err = find_interface_and_endpoints(ldevice,
2123 &ptp_usb->interface,
2124 &ptp_usb->altsetting,
2126 &ptp_usb->inep_maxpacket,
2128 &ptp_usb->outep_maxpacket,
2132 openusb_free_devid_list(devs);
2133 LIBMTP_ERROR("LIBMTP PANIC: Unable to find interface & endpoints of device\n");
2134 return LIBMTP_ERROR_CONNECTING;
2137 /* Copy USB version number */
2138 ptp_usb->bcdusb = desc.bcdUSB;
2140 /* Attempt to initialize this device */
2141 if (init_ptp_usb(params, ptp_usb, ldevice) < 0) {
2142 LIBMTP_ERROR("LIBMTP PANIC: Unable to initialize device\n");
2143 return LIBMTP_ERROR_CONNECTING;
2147 * This works in situations where previous bad applications
2148 * have not used LIBMTP_Release_Device on exit
2150 if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) {
2151 LIBMTP_ERROR("PTP_ERROR_IO: failed to open session, trying again after resetting USB interface\n");
2152 LIBMTP_ERROR("LIBMTP libusb: Attempt to reset device\n");
2153 openusb_reset(*ptp_usb->handle);
2156 if (init_ptp_usb(params, ptp_usb, ldevice) < 0) {
2157 LIBMTP_ERROR("LIBMTP PANIC: Could not init USB on second attempt\n");
2158 return LIBMTP_ERROR_CONNECTING;
2161 /* Device has been reset, try again */
2162 if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) {
2163 LIBMTP_ERROR("LIBMTP PANIC: failed to open session on second attempt\n");
2164 return LIBMTP_ERROR_CONNECTING;
2168 /* Was the transaction id invalid? Try again */
2169 if (ret == PTP_RC_InvalidTransactionID) {
2170 LIBMTP_ERROR("LIBMTP WARNING: Transaction ID was invalid, increment and try again\n");
2171 params->transaction_id += 10;
2172 ret = ptp_opensession(params, 1);
2175 if (ret != PTP_RC_SessionAlreadyOpened && ret != PTP_RC_OK) {
2176 LIBMTP_ERROR("LIBMTP PANIC: Could not open session! "
2177 "(Return code %d)\n Try to reset the device.\n",
2179 openusb_release_interface(*ptp_usb->handle, ptp_usb->interface);
2180 return LIBMTP_ERROR_CONNECTING;
2183 /* OK configured properly */
2184 *usbinfo = (void *) ptp_usb;
2185 return LIBMTP_ERROR_NONE;
2188 void close_device(PTP_USB *ptp_usb, PTPParams *params) {
2189 if (ptp_closesession(params) != PTP_RC_OK)
2190 LIBMTP_ERROR("ERROR: Could not close session!\n");
2194 void set_usb_device_timeout(PTP_USB *ptp_usb, int timeout) {
2195 ptp_usb->timeout = timeout;
2198 void get_usb_device_timeout(PTP_USB *ptp_usb, int *timeout) {
2199 *timeout = ptp_usb->timeout;
2202 int guess_usb_speed(PTP_USB *ptp_usb) {
2203 int bytes_per_second;
2206 * We don't know the actual speeds so these are rough guesses
2207 * from the info you can find here:
2208 * http://en.wikipedia.org/wiki/USB#Transfer_rates
2209 * http://www.barefeats.com/usb2.html
2211 switch (ptp_usb->bcdusb & 0xFF00) {
2213 /* 1.x USB versions let's say 1MiB/s */
2214 bytes_per_second = 1 * 1024 * 1024;
2218 /* USB 2.0 nominal speed 18MiB/s */
2219 /* USB 3.0 won't be worse? */
2220 bytes_per_second = 18 * 1024 * 1024;
2223 /* Half-guess something? */
2224 bytes_per_second = 1 * 1024 * 1024;
2227 return bytes_per_second;
2230 static int usb_get_endpoint_status(PTP_USB* ptp_usb, int ep, uint16_t* status) {
2232 return libusb_control_transfer(ptp_usb->handle,
2233 LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_ENDPOINT,
2234 LIBUSB_REQUEST_GET_STATUS,
2237 (unsigned char *) status,
2241 struct openusb_ctrl_request ctrl;
2244 ctrl.payload = (unsigned char *)status;
2245 ctrl.timeout = ptp_usb->timeout;
2247 ctrl.setup.bRequest = USB_REQ_GET_STATUS;
2248 ctrl.setup.bmRequestType = USB_ENDPOINT_IN | USB_RECIP_ENDPOINT;
2249 ctrl.setup.wIndex = ep;
2250 ctrl.setup.wValue = USB_FEATURE_HALT;
2251 openusb_ctrl_xfer(*ptp_usb->handle, ptp_usb->interface, ep, &ctrl);
2252 return ctrl.result.status;