libmtp-1.1.6-20-g1b9f164/0000775000175000017500000000000012205614637014712 5ustar glowwormglowwormlibmtp-1.1.6-20-g1b9f164/ChangeLog0000664000175000017500000030165612205614637016477 0ustar glowwormglowworm2011-01-19 Linus Walleij RETIRING THIS FILE! WE HAVE MIGRATED TO GIT WHICH PROVIDES EASY ACCESS TO THE CHANGELOG, LETS GET RID OF THIS ANCIENT CRUFT 2011-01-09 Linus Walleij * configure.ac: bump to 1.0.4 * src/Makefile.am: bump interface to libmtp.so.8.3.4 * Release libmtp 1.0.4 2010-12-07 Linus Walleij * configure.ac: make sure the prober only compiles for Linux. * src/ptp.c: update to match upstream. * src/ptp.h: dito. * src/ptp-pack.c: dito. 2010-12-05 Linus Walleij * utils/mtp-probe.c: enhanced to use libmtp intrinsics and e.g. OS descriptor to probe new devices from udev. * utils/mtp-hotplug.c: utilize mtp-probe. * src/libmtp.h.in: add new interface used by the mtp-probe utility to probe a certain device in a certain bus. * src/libusb-glue.c: introduce new function to probe a certain bus and device. * examples/Makefile.am: reform the way of making all executable examples prefixed with "mtp-*" just set this name in the make target! * configure.ac: drop the default "mtp-*" prefixing of all programs, instead I have renamed the executables. * Makefile.am: install the mtp-probe script in the libexecdir, and FORCE this to be /lib/udev. We now also install the udev rules to $libexecdir/rules.d, which is thus also forced to be /lib/udev/rules.d. 2010-12-01 Linus Walleij * examples/hotplug.c: drop old udev style somewhat. * utils/: move out mtp-hotplug into its own subdir, intend to put programs to probe devices here too. * utils/mtp-hotplug.c: moved the hotplug program here. * utils/check_mtp_device.sh: tentative script for checking MTP devices. * utils/mtp-probe.c: C program intended to check if devices are MTP. 2010-11-24 Linus Walleij * examples/hotplug.c: set the music player environment variable for userspace programs watching udev output to determine what device is plugged in. 2010-10-31 Linus Walleij * src/libusb-glue.c: only reset the device if a connection fails, then retry. We were resetting the device on every close() - not good. 2010-10-17 Linus Walleij * src/libmtp.c: Windows file open fixes from Jelle Geerts. * examples/sendfile.c: exit with 1 on error. * examples/*: condensed connect subprograms to a single header and propagate error codes. 2010-09-18 Linus Walleij * src/libmtp.c: NULL check on abstract lists, drop unused folder variable. 2010-07-25 Linus Walleij * src/libmtp.c: if the Ogg or FLAC filetypes have been flagged as being stored as "unknown" and the device now indicates it supports them: remove the flag. * src/libmtp.c: parse device extensions. * src/libmtp.h.in: stack up device extensions in the device struct. 2010-06-19 Richard Low * src/music-players.h: add Apple devices as supported by PwnTunes 2010-05-23 Linus Walleij * src/libusb-glue.c: don't probe HID equipment for device descriptors, some Kensington mice don't like that and there generally is not point either * src/Makefile.am: interface libmtp.so.8.3.3 * configure.ac: libmtp 1.0.3 * Release 1.0.3 2010-05-16 Richard Low * src/libusb-glue.c: usb bus location fix for Mac and disable usb_set_altinterface on Mac 2010-04-25 Linus Walleij * src/ptp.c: sync to upstream. * src/ptp.h: dito. * src/playlist-spl.c: fix an issue with Samsung playlists disappearing since they were using a custom MTP type. * src/libmtp.c: moan about PTP devices without MTP extension 2010-04-05 Linus Walleij * src/ptp.c: sync to upstream. * src/ptp.h: dito. * src/ptp-pack.c: dito. 2010-02-01 Linus Walleij * src/Makefile.am: interface libmtp.so.8.3.2 * configure.ac: libmtp 1.0.2 * Release 1.0.2. 2010-01-30 Linus Walleij * examples/connect.c: bad prototype for sendtrack_. * examples/sentr.c: bad prototype. * src/ptp.c: sync to upstream. * src/ptp.h: dito. * src/ptp-pack.c: dito. 2010-01-19 Linus Walleij * src/libmtp.c: handle a root folder with a number of 0xffffffffU (-1), even if the spec says that 0x00000000 is the root folder. Add some warnings. * src/libmtp.c: patch from Kevin Hester to fix the erroneous setting of genre or release date to NULL on some devices. * src/libusb-glue.c: patch to fix a bug in some multithread contexts affecting e.g. Rhythmbox, also by Kevin Hester. * examples/Makefile.am: fix the bad prefixing that came in as part of the Windows fixes. Keep $(EXEEXT). 2010-01-07 Linus Walleij * src/libmtp.c: detect "My_Foo" default folders as well as "My Foo" (underscore) as well. 2010-01-01 Linus Walleij * src/libmtp.h.in: we use time_t so include 2009-12-16 Linus Walleij * src/libusb-glue.c: don't complain so much about the response to command 2. 2009-11-30 Linus Walleij * src/libusb-glue.c: bus detection fix for libusb - bus->location was not properly initialized. 2009-10-10 Linus Walleij * src/libmtp.h.in: move debugmacros to util.h * src/util.h: dito * libmtp.pc.in: erroneouse Libs.private, lacking ":" 2009-09-28 Nicolas VIVIEN * examples/albumart.c : add d option, to enable or not debug ouput. * examples/albums.c : dito. * examples/detect.c : dito. * src/libmtp.c : Add LIBMTP_Set_Debug function. * src/libmtp.h.in : Add LIBMTP_Set_Debug function to API. * src/libmtp.sym : Add LIBMTP_Set_Debug function to exported symbol. * src/libusb-glue.h : Add LIBMTP_USB_DEBUG / LIBMTP_DATA_DEBUG macros. * src/libusb-glue.c : Use previous macros inside of printf. * src/playlist-spl.c : Add LIBMTP_PLST_DEBUG macro. 2009-09-25 Linus Walleij * src/libusb-glue.c: some more BlackBerry fixing from Nicolas. * examples/albumart.c: add p and s switches, to support storage and parent ID:s. (Nicolas) * examples/newplaylist.c: dito. (Nicolas) 2009-09-23 Linus Walleij * src/libmtp.c: patch from Nyall Dawson to make all filenames unique if the device requires this. * src/libusb-glue.h: dito. * src/device-flags.h: dito. * src/music-players.h: dito. 2009-09-23 Linus Walleij * src/libusb-glue.c: several patches from Nicolas Vivien to support the BlackBerry Storm. * src/device-flags.h: add special flag for the BlackBerry "switch mode" command. * src/libusb-glue.h: dito. * src/music-players.h: tag the BlackBerry with this flag. 2009-09-21 Linus Walleij * examples/sendtr.c: patch from Andrea Grillini to support quiet mode operation. 2009-09-12 Linus Walleij * src/libusb-glue.c: skip interfaces with != 3 endpoints and make sure we locate 1 bulk in, 1 bulk out and 1 interrupt endpoint on the interface, else SKIP IT. Based on a patch from Nicolas Vivien . 2009-09-12 Linus Walleij * configure.ac: bump version to libmtp 1.0.1 and release! * src/Makefile.am: bump soversion to libmtp.so.8.3.1 2009-09-11 Linus Walleij * src/music-players.h: tag all SONY NWZ walkmen with DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST. 2009-08-27 Linus Walleij * src/libmtp.c: modernize the album retrieveal functions so they work just as nicely as the track/playlist etc functions. Triggered by Nyalls excellent bug report that showed how libmtp tried to get "composer" info for an album eventhough the device didn't support it. 2009-08-27 Linus Walleij * src/libmtp.c: bugfixes again... 2009-08-25 Linus Walleij * src/libmtp.c: fix a bug where the metadata was cached twice, thx to Marcus for the patch! 2009-08-23 Linus Walleij * src/ptp.c: sync to upstream * src/ptp.h: dito. * src/libmtp.c: patch from Thomas Schweitzer to not use C++ reserved words like "private" and "new", this was changed to "priv" and "newlist" making C++ happy. * src/libusb-glue.h: inclusion guard, export functions to C++ (whoever wants to do that...) * src/libusb-glue.c: define USB_CLASS_PTP unless defined, out-commented code to detect all PTP devices as MTP devices as well. 2009-08-12 Linus Walleij * src/libusb-glue.c: patch from Simon Berg to detect PTP interface descriptors. * src/ptp.c: sync to upstream with correct MTP interface detection in accordance with MTP spec. * src/ptp.h: dito. 2009-08-02 Linus Walleij * configure.ac: tag for libmtp 1.0.0! * src/Makefile.am: bump to compatible API/ABI result = libmtp.so.8.3.0 * src/libmtp.c: missing flag fix from Marcus. 2009-07-24 Linus Walleij * src/device-flags.h: add a flag for unknown FLAC type. * src/music-players.h: tag the Cowon iAudio S9 with this. * src/libmtp.c: implement unknown FLAC type. 2009-07-24 Linus Walleij * src/music-players.h: a number of new devices. * src/ptp.c: sync to upstream. * src/ptp.h: sync to upstream. * src/ptp-pack.c: sync to upstream. 2009-06-24 Linus Walleij * src/music-players.h: tag most all Samsung devices with the UNLOAD_DRIVER flag. Broken GET_ALL info in all Creative devices. 2009-06-20 Linus Walleij * examples/pathutils.c: detect VCF files too. 2009-06-15 Marcus Meissner * configure.ac: use the AC_SYS_LARGEFILE macro instead of the ugly largefile hacks. * src/libmtp.c: fix use of largefile back to the simple functions instead. * examples/albumart.c: dito. * examples/sendfile.c: dito. * examples/sendtr.c: dito. * examples/thumb.c: dito. 2009-06-15 Linus Walleij * configure.ac: some buildsystem updates. * INSTALL: some doc updates. 2009-06-15 Marcus Meissner * src/libmtp.c: synced to new libgphoto2 code. * src/device-flags.h: dito. * src/ptp.h: sync to upstream. * src/ptp.c: dito. * src/ptp-pack.c: dito. The handles, the PTPObjectInfo and the MTP proplists are now consolidated into "PTPObject"s. This and abstraction and the resulting helper functions allow implementation of easier dynamic operations like I need for libgphoto2. Some corner stones: - PTPParams now contains the device flags itself. (from device-flags.h) This is needed due to ptp_object_want() needing to decide whether it can call GetObjPropList, and it makes it cleaner. So the ptp-bugs and device-flags handling are unified. - PTPObjects are sorted by object handle. This allows binary search by handle. - New generic helper functions. * uint16_t ptp_object_find (PTPParams *params, uint32_t handle, PTPObject **retob) binary searches the handle in the object list and returns a pointer to the object. * uint16_t ptp_object_find_or_insert (PTPParams *params, uint32_t handle, PTPObject **retob) binary searches the handle in the object list, inserts it if not there yet, and returns a pointer to the object. * uint16_t ptp_object_want (PTPParams *params, uint32_t handle, int want, PTPObject **retob) The most magic function, which does the "on demand" loading of objectinfos, mtp proplists (and more). want is a flag mask of PTPOBJECT_*_LOADED PTPOBJECT_OBJECTINFO_LOADED clear PTPOBJECT_CANONFLAGS_LOADED (special canon flags) PTPOBJECT_MTPPROPLIST_LOADED mtp properties for this object loaded PTPOBJECT_DIRECTORY_LOADED (only used by libgphoto2 currently) PTPOBJECT_PARENTOBJECT_LOADED this and storageid are interesting for directory based lookups PTPOBJECT_STORAGEID_LOADED and can be filled out by directory loading * void ptp_objects_sort (PTPParams *params); Sort the objects list if you did any modification of your own on it and the order of object handles might not be linear anymore. - Multiple object information loading strategies are possible. libmtp uses getobjecthandles() /getobjectinfo() and getobjectproplist() loading strategies for initial setup. This stays of course, it will just fill out the PTPObject array. libgphoto2 now uses a per-directory getobjecthandles() / getobjectinfo() loading approach, and I will readd the getobjectproplist() approach. It is open what you chose to use here. For libmtp the "load all handles at startup" is good, dynamic loading is better for libgphoto2. Only rule is: The objectlist must be in order of objecthandles! (ptp_object_sort()). 2009-06-02 Linus Walleij * examples/hotplug.c: change the udev match rule from ATTR{dev}!="?*" to ENV{MAJOR}!="?*" at the suggestion of Alan Jenkins, this should be faster. * src/libusb-glue.c: include config.h (Marcus Meissner found this is needed when you're not using iconv().) 2009-05-09 Linus Walleij * src/libmtp.c: include for iconv() compatibility. * src/unicode.c: dito. NOTE: this file needs fixing to work without iconv! * src/ptp.h: sync to upstream and get all the embedded support for FREE! * src/ptp.c: dito. * src/ptp-pack.c: dito. 2009-05-06 Linus Walleij * src/ptp.h: sync to upstream. * src/ptp.c: dito. * src/ptp-pack.c: dito. 2009-05-06 Linus Walleij A host of Windows fixes from Carlo Bramini With this patch everything works fine with cygwin and Debian 5.0. Unfortunately, with MSys the "make install" still fails at the very last actions. It happens that everything is re-linked (strange, but not a big problem) and for some unknown reason it loops forever when executing "examples/hotplug > libmtp.usermap". But hopefully the simple "make" completes without errors. * configure.ac: * iconv is now detected with autotools, this makes libmtp linkable on cygwin too (previously it was not). * the presence of Microsoft LIB.EXE is checked; if it is absent then the MSVC libraries won't be generated. * Added checking for some include files not available on Windows: arpa/inet.h, byteswap.h, sys/uio.h. * Check for presence of mkstemp: a replacement has been written for Windows. * examples/Makefile.am: the creation of the links failed: I added source path and $(EXEEXT) extension for executables. This is tested and working with Mingw+MSys, Cygwin, Debian 5.0. * examples/albumart.c: include sys/uio.h only if it's available. * examples/trexist.c: u_int32_t does not exists, into almost all other parts libmtp is using uint32_t so I fixed it in that manner. (Same for u_int64_t/uint64_t). * examples/getfile.c: dito. * examples/pathutils.c: dito, plus rindex() does not exist under Windows, we must user strrchr() instead. * examples/pathutils.h: fixes for prototypes changes made into examples/pathutils.c * examples/thumb.c: include sys/uio.h only if it's available. * src/Makefile.am: * Several fixes because the check on the presence of LIB.EXE libmtp.sym is now prefixed by $(srcdir), this allows to configure libmtp outside the source tree in Windows too. * Libraries are put into LIBADD instead of LDFLAGS, this is the right place. * Previously the linker crashed because there was -ws2_32 instead of -lws2_32. * src/playlist-spl.c: * include sys/uio.h only if it's available. * include replacement for mkstemp() function. 2009-05-03 Richard Low * src/libmtp.c: add external property types just like file types so any property can be retrieved/set. Add function LIBMTP_Is_Property_Supported to determine if a property is supported for a given object type. Add function LIBMTP_Get_Allowed_Property_Values to get alowed range/enum of a property value. Make LIBMTP_Get_Representative_Sample_Format get the size parameter to allow us to determine the maximum size for a representative sample. * src/libmtp.h.in: ditto * src/libusb-glue.c: update to check the handler function return value so the handler can return PTP_ERROR_CANCEL to cancel the transfer. 2009-05-02 Richard Low * src/ptp-pack.c: add a NULL check 2009-04-18 Richard Low * src/ptp-pack.c: add terminating NULL character 2009-04-11 Richard Low * src/libusb-glue.c: Make get_playlist_extension return type const char * * src/libusb-glue.h: ditto * src/libusb-glue.c: In probe_device_descriptor, check to see if dev->config is NULL before going round the first loop * src/libmtp.c: Add LIBMTP_Get_File_To_Handler, LIBMTP_Send_File_From_Handler, LIBMTP_Get_Track_To_Handler, LIBMTP_Send_Track_From_Handler functions to get/send files/tracks from/to handler functions. Add modificationdate to file and track structs. Add LIBMTP_FILETYPE_ALBUM and LIBMTP_FILETYPE_PLAYLIST filetypes. 2009-03-17 Linus Walleij * src/device-flags.h: discovered a new device that cannot even read out battery level but still claims to be able to. Sigh. * src/libusb-glue.h: flag macro. * src/music-players.h: flag the Slacker. * src/libmtp.c: avoid battery level getting on these devices. * configure.ac: preparing for 0.3.7. * src/Makefile.am: preparing for 0.3.7 (libmtp.so.8.2.2) * Release libmtp 0.3.7. 2009-03-08 Linus Walleij * src/libmtp.c: refactored OGG extenstion check again, same code in three places, broke it out and made it foolproof (hopefully) in one single spot. 2009-03-04 Linus Walleij * src/libusb-glue.c: patch from Marcus to fix an issue with retransmit originally reported by Florent Pillet. 2009-02-21 Linus Walleij * src/libmtp.c: some additional NULL checks from Florent Pillet. 2009-02-18 Linus Walleij * src/libmtp.c: error report from RedHat BZ http://bugzilla.redhat.com/show_bug.cgi?id=485627 led to strange code for detecting anonymous OGG files being rewritten to handle NULL filenames and filenames that do not exceed 4 chars. 2009-01-30 Linus Walleij * src/libmtp.c: store albums and playlists in the default music folder if no default folder for albums resp. playlists has been detected. 2009-01-22 Linus Walleij * configure.ac: bump to 0.3.6 and release. * src/Makefile.am: interface bump to libmtp.so.8.2.1 2009-01-16 Linus Walleij * src/ptp.c: sync to upstream. * src/ptp.h: dito. 2009-01-15 Linus Walleij * src/libmtp.c: include fixes from Yuri Pankov for *BSD. * src/playlist-spl.c: dito. * examples/*.c: (more or less) dito. 2009-01-14 Linus Walleij * src/device-flags.h: new device flag for broken SendObjectPropList, as found broken in MEU202 * src/music-players.h: use the new flag. * src/libmtp.c: implement this device flag. * src/libusb-glue.h: dito. 2009-01-10 Linus Walleij * src/libmtp.h.in: mingw32 fixes from James Ravenscroft. * src/libmtp.c: dito. Replaced "rindex" with "strrchr" * src/Makefile.am: dito. * examples/albumart.c: dito. 2009-01-06 Linus Walleij * src/Makefile.am: patch from Rafael Laboissiere removing a build artifact in distclean. 2009-01-02 Linus Walleij * examples/connect.c: usage patch from Riley Patterson. * examples/sendtr.c: dito. Plus only try to add track to an album if and only if an album name was given. * examples/newfolder.c: real bad bug fixed, didn't even work due to bad args check. * examples/sendfile.c: another bad bug... * examples/common.h: include not "config.h" * src/unicode.h: no reason for this to include config.h! 2008-12-21 Linus Walleij * Release libmtp 0.3.5. 2008-12-15 Nathan Bullock * src/libmtp.c: get folders to a flat list and we get O(n) searching instead of the previous O(n^2) algorithm! 2008-12-13 Linus Walleij * examples/detect.c: make mtp-detect dump out default-capabilities.xml if such a file exists on the device. * m4/stdint.m4: update to newer macro from libgphoto2. * m4/byteorder.m4: update to newer macro from libgphoto2. We find these here: http://gphoto.svn.sourceforge.net/viewvc/gphoto/trunk/m4/ * configure.ac: fix the renamed _stdint.h too. * Doxyfile.in: some config option got obsolete. * libmtp.c: start to use PTP error redirection to the libmtp error stack. This also makes it possible to stop the annoying debug prints. * libusb-glue.c: dito. * ptp.c: sync to upstream. * ptp.h: sync to upstream. 2008-12-02 Linus Walleij * examples/util.c: another NULL check. 2008-11-25 Linus Walleij * src/libmtp.c: fix a bug on handling folder children with an illegal ID of 0. Occured in the ZEN Xi-Fi in the "Recordings" folder, when that is created on the device. 2008-11-17 Alistair Boyle * configure.ac: change release to 0.3.5. * libmtp.c: change metadata const*const to *const to allow playlist_id to be modified by LIBMTP_Update_Playlist. (Samsung playlists) * libmtp.h.in: match libmtp.c 2008-11-11 Linus Walleij * src/libmtp.c: allow for playlists with zero tracks on them, also in update. 2008-11-09 Linus Walleij * src/ptp.h: sync from upstream. * src/ptp.c: sync from upstream. * src/ptp-pack.c: sync from upstream. 2008-11-07 Linus Walleij * Release libmtp 0.3.4. * configure.ac: let's release 0.3.4. * src/Makefile.am: compatible API and ABI. 2008-11-05 Linus Walleij * src/libmtp.c: fix the association type problem on LIBMTP_Create_Folder(). This causes folders not to work properly on some devices!! 2008-11-01 Linus Walleij * src/ptp.h: sync to upstream. * src/ptp.c: sync to upstream. * src/ptp-pack.c: introduce Richards bugfix on top of upstream and take advantage of the ptp_debug() function. * src/libusb-glue.c: make ptp_debug() non-static since ptp-pack.c needs it. 2008-10-21 Linus Walleij * src/device-flags.h: actually the SanDisks cannot handle PTP_OPC_DateModified at ALL, not even as part of the initial update so rename the flag to something sensible. * src/music-players.h: consequental changes. * src/libmtp.c: disable all use of PTP_OPC_DateModified if flag is set, not just updates. 2008-10-16 Linus Walleij * src/device-flags.h: new flag for broken updates of PTP_OPC_DateModified. * src/music-players.h: tag all SanDisk devices with this flag. Bug appeared in them. * libmtp.c: avoid updating PTP_OPC_DateModified on broken devices. 2008-09-28 Alvin * src/libmtp.c: fix several bugs in Ogg filetype support. 2008-09-26 Richard Low * src/libmtp.c: check propdesc before setting props in create_new_abstract_list() 2008-09-25 Linus Walleij * configure.ac: bump to 0.3.3. * src/Makefile.am: interface to .so.8.1.0 * Release as 0.3.3. 2008-09-24 Linus Walleij * src/libmtp.h.in: add new filename setting functions, patch from Florent Mertens . * src/libmtp.c: implementation. * src/playlist-spl.c: consequental changes. * src/libmtp.sym: consequental changes. * Fixup patch from Alvin later this day. * Note to self: remember to bump soname to .so.8.1.0. 2008-09-23 Richard Low * src/libmtp.c: check for NULL storage * src/libusb-glue.c: return PTP_RC_OK on zero read * src/music-players.h: give Samsung YP-10 DEVICE_FLAG_NO_ZERO_READS 2008-09-22 Linus Walleij * src/libmtp.c: make sure we don't try to fit a new file onto a ROM storage. Add some pretty-print to FourCC codecs so you can actually understand the enumerations. 2008-09-20 Joe Nahmias * examples/sendtr.c: added option to specify which storage_id the track should be copied. 2008-09-20 Linus Walleij * configure.ac: bump to 0.3.2. * src/Makefile.am: bump to libmtp.so.8.0.2, compatible interface. * Release this as 0.3.2 mainly to get the Creative fixes out. 2008-09-17 Linus Walleij * src/libmtp.h.in: new helper macros from Alvin plus some docs. 2008-09-12 Linus Walleij * src/music-players.h: drop bug flags off the Creative devices. I am confident that the bugs they were masking have been fixed now. 2008-09-07 Richard Low * src/music-players.h: added Panasonic P905i 2008-09-05 Marcus Meissner * src/libmtp.sym: update symbol export table. * src/Makefile.am: fix up some magic for symbol export. 2008-09-04 Linus Walleij * src/libmtp.c: look up the filename for playlists if the name is missing or not properly set. Not doing the same for albums - these must have proper metadata. * src/music-players.h: more players as usual. * examples/sendtr.c: more warnings. 2008-08-31 Linus Walleij * src/ptp.h: sync to upstream. * src/ptp.c: sync to upstream. 2008-08-30 Chris Bagwell * src/libusb-glue.c: make it possible to have per-command or otherwise altered timeout values for different PTP request/response sequences. * src/libusb-glue.h: dito. * src/libmtp.c: increase USB timeout to 30s when getting a complete track listing off the device. * src/music-players.h: as a consequence, the Sirus Stiletto no longer needs any brokenness flag. 2008-08-30 Linus Walleij * src/ptp.c: sync to upstream. 2008-08-28 Linus Walleij * examples/sendtr.c: fix non-strdup():ed strings to be copied, patch courtesy of Juanan Pereira. 2008-08-25 Linus Walleij * src/Makefile.am: bump interface a patchlevel. (Fully compatible.) * configure.ac: bump version to 0.3.1. * Release as libmtp 0.3.1. 2008-08-18 Linus Walleij * src/libusb-glue.c: some vartype and return flunkies. * configure.ac: check for locale.h * examples/util.c: set locale to pick up environment. 2008-08-17 Linus Walleij * src/libusb-glue.c: some handling of ptp_usb_getdata() when passed in data size was 0xffffffffU, data sent in first transaction was ignored, fix by Rob Woolley. * src/ptp-pack.c: sync in from upstream libgphoto2. * src/README: move relevant stuff to README. * README: see above. 2008-08-15 Alistair Boyle * src/playlist-spl.c: added handling of Samsung's proprietary .spl playlist format. * src/playlist-spl.h: dito. * src/device-flags.h: new flags for Samsung playlists. * src/music-players.h: assign flags. * src/libusb-glue.h: convenience macros. * src/libmtp.c: integrate Samsung playlists. 2008-08-15 Linus Walleij * examples/Makefile.am: break out utility functions (currently only checklang()) to a separate file. * examples/util.h: dito. * examples/util.c: dito. * examples/detect.c: dito. * examples/sendtr.c: dito. * examples/connect.c: dito. 2008-08-14 Linus Walleij * src/libmtp.c: add some documentation to file and track listing functions to that it's clear that you have to inspect storage_id and parent_id in order to group files into storages and/or folders. 2008-07-31 Linus Walleij * src/music-players.h: several new devices and flags. 2008-06-24 Linus Walleij * TODO: updates. * src/Makefile.am: bump interface to libmtp.so.8.0.0. It's NOT compatible! * RELEASE libmtp 0.3.0 and let the apps developers have their apps fixed! 2008-06-22 Linus Walleij * src/libmtp.h.in: removed the parenthandle argument from LIBMTP_Send_File_From_File(), LIBMTP_Send_File_From_File_Descriptor(), LIBMTP_Send_Track_From_File(), LIBMTP_Send_Track_From_File_Descriptor(), LIBMTP_Create_New_Playlist() and LIBMTP_Create_New_Album() Now you must pass in parent ID from a metadata or filedata set. Use the respective field of the file, track, playlist or album struct to pass in a parent handle when calling these functions from now on. The bonus for changing your code is that you can now also pass in a storage_id with any metadata set! Consequently LIBMTP_Create_Folder() was altered to accept THREE metadata arguments: name, parent_id and storage_id. All calls to any of these functions in any referring code need to be altered to use this scheme. It should be quite self-evident for most code and easy to perform. * src/libmtp.c: changed outlined above were implemented. * examples/newfolder.c: consequental changes. * examples/sendfile.c: consequental changes. * examples/sendtr.c: consequental changes. * examples/albumart.c: consequental changes. * examples/newplaylist.c: consequental changes. * examples/files.c: consequental changes. * examples/tracks.c: correct misleading strings. 2008-06-15 Linus Walleij * src/libmtp.c: only look for default folders in the root folder on the primary storage, even. 2008-06-14 Linus Walleij * src/libmtp.c: only look for default folders in the primary storage, and only try to put files there if they are targetting the primary storage. 2008-06-08 Linus Walleij * configure.ac: check for the langinfo.h header. * examples/connect.c: check charset properly. * examples/sendtr.c: dito. * src/music-players.h: new devices galore. 2008-06-03 Linus Walleij * src/device-flags.h: new device flag for devices that always need to have their device descriptor probed. * src/music-players.h: generously add this flag to all SanDisk devices. The e280v2 and Fuze are known to be especially problematic. * src/libusb-glue.h: helper macro. * src/libusb-glue.c: massage "OS Descriptor" on demand when opening the device. * src/music-players.h: detailed info and flags for the SanDisk Sansa players. More to be done, probably. 2008-06-02 Linus Walleij * src/libusb-glue.c: refactor PTP_USB to use the raw device and its contained deviceinfo to store and retrieve the device flags. (This is starting to look object oriented...) * src/libusb-glue.h: accessor functions to simplify switching on the device flags and increase the code readability. * src/libmtp.c: use the new accessor functions. 2008-06-01 Linus Walleij * src/libmtp.c: use LIBMTP_Detect_Raw_Devices() and LIBMTP_Open_Raw_Device() inside LIBMTP_Get_First_Device() refactoring. Move params creation into this file. * src/libusb-glue.c: move params creation away from here. 2008-05-30 Linus Walleij * src/libusb-glue.c: unused variable. * examples/detect.c: switch to using raw device interface for opening devices. 2008-05-28 Linus Walleij * src/libmtp.c: internally using the raw devices to get a list of devices. * src/ptp.c: sync to upstream. * src/ptp.h: dito. * src/ptp-pack.c: dito. * src/libmtp.h.in: move raw device detection to use error codes. Add interface to open a raw device! * src/libusb-glue.h: make the old device list internal, use raw device in interface for configuring USB. * src/libusb-glue.c: fix up error messages. Move the raw device detection interface to use error codes. * examples/detect.c: fix up error messages. Use error codes for raw devices. 2008-05-23 Linus Walleij * src/libmtp.c: after sending a file, look up the resulting file metadata from the cache to make sure that parent_id is identical to that the file actually gets on the device. If root folder (0) is selected, we hardcode thing to 0xffffffffu to be used as parent, but it will probably end up being 0 for example. Also fix an issue with ptp_mtp_getobjectproplist() sometimes returning a NULL pointer while still claiming there are props in the list. * src/libusb-glue.h: add a function to get the preferred playlist extension. * src/libusb-glue.c: "written" variable in ptp_usb_sendreq() may end up uninitialized if ptp_write_func() fails. Initialize it to 0. Get the prefered playlist extension. 2008-05-18 Richard Low * src/device-flags.h: added DEVICE_FLAG_BROKEN_SET_SAMPLE_DIMENSIONS device flag * src/music-players.h: ditto. Also set Samsung YH-999 to DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL based on users experience. * src/libmtp.c: added DEVICE_FLAG_BROKEN_SET_SAMPLE_DIMENSIONS device flag 2008-05-05 Linus Walleij * src/libusb-glue.c: assign device name and flags to detected raw devices, slowly preparing to move to using the raw device detection internally as well. 2008-05-04 Linus Walleij * src/libmtp.h.in: move useful filetype macros here so external programs can use them. * src/libmtp.c: consequental changes. * examples/sendtr.c: use the new macro to detect track content. 2008-05-03 Johannes Huber * src/libmtp.h.in: add interface for setting album composer, needed for classical albums, on abstract albums. * src/libmtp.c: implement it. * examples/albums.c: consequental changes. * examples/connect.c: dito. * examples/sendtr.c: dito. * examples/tracks.c: dito. * AUTHORS: new contributor. 2008-04-27 Linus Walleij * src/libmtp.c: recognize audio files as tracks, since this is what WMP does. (e.g. it sets playlength on movies to enable skip bar) also define macros for audio/video/both types and tidy up a bit. 2008-04-24 Linus Walleij * src/libmtp.h.in: added preliminary interface for getting raw devices. * src/libusb-glue.c: the implementation is all here! * src/libusb-glue.h: add some bus and device fields to the internal device list. * examples/detect.c: exercise the raw device detection code. 2008-03-26 Linus Walleij * examples/pathutils.c: fix a folder identification bug, courtesy of Dr Nicholas Jacobs. 2008-03-12 Linus Walleij * configure.ac: bad mailing list address. (Marcus) Bump to version 0.3.0. * examples/hotplug.c: switch from using "info.bus" to using "info.subsystem" to identify USB events. (Marcus). * src/libmtp.c: add parent_id to albums and playlists, based on a patch by Ali Shah. * src/libmtp.h.in: dito. * examples/playlists.c: consequental changes. * examples/albums.c: consequental changes. * This will be a new major revision of the API/ABI no matter what. 2008-03-08 Linus Walleij * src/libusb-glue.c: left debug prints on :-( * configure.ac: set to 0.2.6.1 * Release as 0.2.6.1 2008-03-02 Linus Walleij * configure.ac: prepare 0.2.6 release. * src/Makefile.am: bump to compatible interface, * src/ptp.c: sync in upstream, a Sansa fix! * src/ptp.h: sync in upstream. * doc/Doxyfile.in: retire obsoleted parameters. * Release this as 0.2.6! 2008-02-24 Richard Low * src/music-players.h: add DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL for a broken Philips player. 2008-02-18 Linus Walleij * examples/pathutils.c: fix up item ID typing to uint32_t, handle file names passed in as arguments at suggestion from anonymous mail list user. * examples/pathutils.h: move a function static. 2008-02-12 Nicolas Pennequin * examples/sendtr.c: add transferred tracks to albums if possible. 2008-02-10 Scott Snyder * src/libusb-glue.c: finally fix up the short header detection to skip over zero packets when encountered. * examples/pathutils.c: fix a problem where all files sent has to include a "." (period). 2008-02-06 Linus Walleij * src/libusb-glue.c: wait for response > 0 instead of > 2. 2008-01-28 Linus Walleij * src/libmtp.c: LIBMTP_Get_Filemetadata() return metadata for folders (associations) too. There is really no reason why it shouldn't and it's good for use internally. LIBMTP_Get_Filelisting_With_Callback() will still not return any associations however. We want to use the folder functions for that. 2008-01-28 Linus Walleij * src/libmtp.h.in: withdraw LIBMTP_Set_Object_Parent() function, no known devices will support this. * src/libmtp.c: dito. Fix up some problems with the LIBMTP_Set_Object_Filename() function. 2008-01-27 Linus Walleij * src/libmtp.c: fix up some minor things and documentation on the object handling functions. 2008-01-27 Florent Mertens * src/libmtp.h.in: new functions to rename object filenames and change object parents. Good when modifying the device as a file system, LIBMTP_Set_Object_Filename(), LIBMTP_Set_Object_Parent(). * src/libmtp.c: implementation. 2008-01-27 Linus Walleij * src/libusb-glue.c: re-read response from device until it atleast exceeds two bytes. This fixes a problem with the Samsung YP-U3 when populated with many, many songs. 2008-01-21 Richard Low * src/music-players.h: add Thomson Lyrca HC308A, remove incorrect ID for Creative Zen 8GB 2008-01-20 Richard Low * src/libmtp.c: add LIBMTP_Get_Representative_Sample() * src/libmtp.h.in: ditto 2008-01-14 Linus Walleij * src/libmtp.c: add LIBMTP_Get_Manufacturername(). Remember to bump soname (compatible) in 0.2.6 (or whatever we name it). 0.3.0 perhaps? * src/libmtp.h.in: dito. * src/libmtp.c: detect default folders named "Datacasts" and "Texts". 2008-01-11 Linus Walleij * examples/pathutils.c: recognize .bin files as firmware, used by e.g. RockBox developers. Doesn't cost anything to add. 2008-01-08 Linus Walleij * configure.ac: bump to 0.2.5. * src/Makefile.am: interface to libmtp.so.7.0.2 (compatible). * Release as libmtp 0.2.5. Why not? 2007-12-28 Linus Walleij * src/libmtp.c: make libmtp use PTP_OPC_AlbumArtist on albums, instead of the (seldom present) PTP_OPC_Artist tag. Use both if both are supported. We're not setting AlbumArtist on regular tracks though, what's the point, and what does it mean if this differs from Artist?? 2007-11-30 Linus Walleij * src/music-players.h: new flag for the YP-T10. * src/device-flags.h: define the new flag, that is needed to support Ogg files on these devices. * src/libmtp.c: recognize and report Ogg support, set type to unknown when transferring. 2007-11-22 Linus Walleij * configure.ac: bump to 0.2.4. * src/Makefile.am: bump age of soversion (compatible). * RELEASE 0.2.4 mainly to get some new device support out there. 2007-11-09 Linus Walleij * src/libusb-glue.c: avoid probing deeper into interfaces that have a string describing them as "MTP" after a suggested patch from Alexander Kanavin . * examples/albumart.c: patch from Chris Waters replacing calls to atoi() with calls to strtoul(). Since object ID:s are unsigned long, atoi() would reject too high object IDs. The patch also fix a few memory leaks. THANKS DEBIAN! We love our downstream! * examples/newplaylist.c: dito. * examples/pathutils.c: dito. * examples/thumb.c: dito. 2007-11-05 Linus Walleij * src/libmtp.c: use OPFF codes instead of DPFF codes, we're dealing with objects, not device props. * src/ptp.c: silence some OPFF freeing warnings. 2007-11-02 Linus Walleij * src/libusb-glue.c: try to repair header here instead of ignoring error in ptp.c. * src/music-players.h: flag some more Creative devices as broken getting all files. * src/Makefile.am: reference the 2 new .h files. 2007-10-31 Linus Walleij * src/ptp.c: bring cache handling into this file. * src/ptp.h: dito. * src/libmtp.c: consequential changes. 2007-10-30 Linus Walleij * src/music-players.h: split this off as a shared file between us and libgphoto2 so we get out of the syncing nightmare. * src/device-flags.h: split out this as well, Marcus might want it. * src/libusb-glue.c: consequential movement. * src/libmtp.c: reference new flag file. * src/ptp.c: sync in upstream. * src/ptp.h: dito. 2007-10-25 Linus Walleij * Release 0.2.3. Nice bunch of cleaned-up code, sad we had too bump soversion but such is life. 2007-10-23 Linus Walleij * src/libmtp.c: make LIBMTP_Send_File_From_File_Descriptor() survive the case where device->storage is NULL. This happens on the Nokia 3110c. 2007-10-19 Linus Walleij * src/libmtp.c: bring the cache handling code together at the end of the file, refactor so as to avoid code duplication, do things in one place only and looking good. Get folder list recursively instead, this works better with fast dir retrieveal I think. 2007-10-18 Linus Walleij * src/libmtp.c: fix the deletion of cached properties when removing objects. This code was seriously broken. 2007-10-16 Jeff Mitchell * src/libusb-glue.c: remove the previously-concatenated vendor and product string "name" field as it's now redundant * src/Makefile.am: interface to libmtp.so.7.0.0 (incompatible, device_entry_struct members changed) * examples/hotplug.c: port to use vendor and product instead of name, also some useful commenting in the fdi file 2007-10-15 Linus Walleij * src/libusb-glue.c: repair headers, don't just ignore them. Add support for broken set object proplist devices. Motorola RAZR2 V8 has this problem. * src/libusb-glue.h: flag for broken set object proplist. * libmtp.c: avoid broken set object proplist. 2007-10-09 Jeff Mitchell * src/libusb-glue.c: add separate vendor and product strings in device entry structs * src/libmtp.h.in: update device entry structs to reflect this 2007-10-04 Linus Walleij * src/libusb-glue.c: rm some pointless confusing defines inherited from libgphoto2. * configure.ac: bump to 0.2.2 * src/Makefile.am: interface to libmtp.so.6.0.2 (compatible) * Release as 0.2.2. Now is as good time as ever. Release early and release often. 2007-10-03 Linus Walleij * src/libusb-glue.c: tag the OLD Creative devices with DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL, after clear indications that it was broken when retrieveing folders on all those devices. The newer devices (those supporting 32bit object size) presumably does not have this limitation. 2007-10-02 Linus Walleij * src/libmtp.c: devices which represented file size with a 32bit value (some Creative devices) would return a bananas file size. Fixed it up by... * src/libmtp.h.in: recycling the uint8_t "interface" field in the device struct as a holder of the object size for the device. This will make the new library binary compatible with version 0.2.1 since no-one should *ever* dereference that value (which used to be the USB interface number and is now the object size). * examples/files.c: display 64bit file sizes in hex correctly. 2007-09-29 Richard Low * src/libmtp.c: avoid crash on failed connect 2007-09-28 Linus Walleij * src/libusb-glue.h: introduce a new device flag for devices that have broken PTP headers, first encountered on the Creative ZEN 8GB. * src/libusb-glue.c: attempt to begin to work around the broken PTP headers. 2007-09-25 Linus Walleij * src/libusb-glue.h: add a new device flag for devices that don't like it if you release the interface (or try to clear endpoints). * src/libusb-glue.c: dito, implement this flag, tag all SanDisk Sansa devices with it except for the Linux-based Sansa Connect. 2007-09-23 Richard Low * src/libusb-glue.c: updated some device flags, removed second call to ptp_getdeviceinfo * src/libmtp.c: property cache fixes 2007-09-23 Linus Walleij * src/libmtp.c: wrapped updating of playlists and albums into an abstract function so we do it consistently. Added support for tagging on modification date to files, tracks, playlists and albums. 2007-09-21 Linus Walleij * src/libusb-glue.c: flag the Samsung YH-820 with DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL after tests by Stephan Fabel. 2007-09-18 Linus Walleij * src/libusb-glue.c: stop the endpoint unhalting/unstalling when closing the USB device. It was AYBABTU the Samsungs (and others). 2007-09-17 Linus Walleij * src/libusb-glue.c: silenced weirdo error message. 2007-09-16 Linus Walleij * src/ptp.c: cancellation working *as it should* * src/ptp.h: dito. * src/libusb-glue.c: dito. * src/libusb-glue.h: dito. * src/libmtp.c: dito. * src/libmtp.h.in: new error code for cancellation. 2007-09-16 Richard Low * src/libusb-glue.c: only read descriptors for devices we don't know since it breaks on some devices * src/libmtp.c: a couple of bugs fixed in metadata retreival 2007-09-15 Linus Walleij * src/ptp.c: get cancellation of xfers working. * src/libusb-glue.c: dito. * src/libusb-glue.h: dito. * src/libmtp.c: dito. 2007-09-14 Linus Walleij * src/ptp.h: sync in upstream to get cancellation prototypes. * src/libusb-glue.c: first try to implement cancellation. * src/libmtp.c: dito. Bugfix to one of Marcus' realloc():s. 2007-09-12 Marcus Meissner * src/ptp-pack.c: sync to upstream, rewrote packing to use a static array to be qsort():ed when reading in proplists. * src/ptp.c: reflect changes. * src/ptp.h: reflect changes. * src/libmtp.c: reflect changes. 2007-09-06 Linus Walleij * examples/hotplug.c: edit up into a udev ruleset that is inexorably complicated but probably compatible with most udev versions out there. Now please DON'T update udev styles again! 2007-09-05 Richard Low * src/libmtp.c: album fixups 2007-09-05 Linus Walleij * examples/hotplug.c: use old udev style by default, use new if requested explicitly by a -U switch. 2007-09-04 Linus Walleij * src/libmtp.c: make sure we query recursively supplying each storage ID in turn, so we spin over storages. Also check what storage may be available to store a file, if the first one fails, try the next! 2007-09-01 Linus Walleij * src/ptp-pack.c: make the resulting MTP proplist sorted by object ID. * hotplug.sh.in: explicitly call BASH instead of just sh. Warn if script is not run as root. 2007-08-29 Linus Walleij * examples/Makefile.am: move include define from AM_CFLAGS to AM_CPPFLAGS (as it should be) bug found by Petar Petrov . * src/libusb-glue.c: strange misleading message corrected. Fix up the horrid interface passing back-and-forward and confusing. * src/libusb-glue.h: dito. * src/libmtp.c: rid interface references, that's a USB issue! * src/libmtp.h.in: flag interface number in device struct as retired. 2007-08-28 Linus Walleij * src/libmtp.c: retire the horrid, broken, stream send facility that does not work on any device since they all want to know the file size in advance. Add in some code to fall back on the recursive metadata retrieveal if getting the whole long list fails. * src/libusb-glue.c: tag all Sansas as having broken GetObjectPropList when all tags for all objects are requested. Scan each INTERFACE of the device for device descriptors. 2007-08-24 Linus Walleij * src/libusb-glue.h: new device flag to strip all non-7bit chars from filenames on some lame devices. * src/libusb-glue.c: tag the Philips Shoqbox with this flag. * src/libmtp.c: strip the non-7bit chars from filenames if that flag is set. * src/unicode.h: introduce a 7bit-strip helper function. * src/unicode.c: dito. 2007-08-22 Linus Walleij * src/libmtp.c: deal with setting of metadata sets for u16/u32:s that are ranges or enums, rounding and twiddling if need be. This is needed because some new devices (like the TrekStor Sweez, has duration defined as a range: MIN 0, MAX 65535000, STEP 1 and Sandisk Sansa c240 has duration as range: MIN 0, MAX 2147483000, STEP 1000) whereas old devices would just accept any value. 2007-08-16 Richard Low * src/ptp-pack.c: allow packing of NULL strings 2007-08-15 Robert Reardon * src/libmtp.c: return device max values for representative samples. 2007-08-15 Richard Low * src/libusb-glue.c: added Philips Shoqbox 2007-08-13 Linus Walleij * src/ptp.c: sync to upstream. 2007-08-07 Linus Walleij * configure.ac: bump to 0.2.1. * src/Makefile.am: interface to libmtp.so.6.0.1. * Release libmtp 0.2.1! 2007-08-06 Linus Walleij * configure.ac: tag on the large file support compilation flag. * src/libmtp.c: smack up the data file transfer function so it works again and *finally* should support 64bit sizes! Then wrapped the track sending function around the file sending function so there is no more pointless code duplication giving rise to ever more bugs. Enable LFS, Large File Support so we can handle 64bit files properly. * examples/sendtr.c: shape up print-outs, LFS support. * examples/sendfile.c: dito. 2007-08-06 Linus Walleij * src/ptp.c: fixed a stray error print bug. * src/libmtp.c: overhaul of all proplist setting to follow the same design pattern. Probably fixed a few opd memory leaks along the road. 2007-08-05 Richard Low * src/libmtp.c: send 64 bit filesize 2007-08-04 Linus Walleij * src/libmtp.c: fix up the 64bit filesize and tracksize support. There were some bugs... * src/Makefile.am: tweak interface revision so that we produce libmtp.so.6 now. * configure.ac: bump library revision to 0.2.0. * examples/hotplug.c: switch to use ATTR{} instead of SYSFS{} * Release libmtp 0.2.0! 2007-08-04 Richard Low * src/libusb-glue.c: add Sansa m240 (a different ID to before) Give the Toshiba Gigabeat S DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL. 2007-08-03 Marcus Meissner * m4/byteorder.m4: byteorder fixes. 2007-07-30 Richard Low * src/ptp-pack.c: fix up array packing 2007-07-30 Linus Walleij * src/ptp-pack.c: try to get a uniform 64 bit support, use some old macro code. 2007-07-29 Richard Low * src/libmtp.c: 64 bit filesize support for tracks * src/ptp-pack.c: ditto * src/ptp.h: ditto 2007-07-27 Richard Low * src/libmtp.c: Some better NULL checks 2007-07-27 Linus Walleij * examples/hotplug.c: changed subsystem from "usb_device" to "usb". Presumably a change in the kernel some time ago. 2007-07-21 Richard Low * src/libmtp.c: Correctly bail out of LIBMTP_Get_Storage 2007-07-17 Linus Walleij * examples/reset.c: Add a device reset program. * src/libmtp.c: Add reset command. * src/ptp.c: dito, and sync in upstream changes. * src/ptp.h: dito, and sync in upstream changes. * src/ptp-pack.c: sync in upstream changes. 2007-07-17 Richard Low * src/libmtp.c: Added some more (paranoid) NULL checks 2007-07-14 Richard Low * src/libmtp.c: Add a NULL check 2007-07-13 Richard Low * src/libusb-glue.c: add Disney MixMax 2007-07-11 Linus Walleij * src/libmtp.c: put in Tero's name in the preamble. * src/libusb-glue.c: make the dump function sump out the zuper zecret devize dezcriptorz in clear text hex. 2007-07-10 Linus Walleij * examples/hotplug.c: force HAL OGG support on iriver devices. They all have it! Also force for two other devices that does this. 2007-07-07 Linus Walleij * src/libusb-glue.h: new flag for the case when getting the object property list of all metadata for all objects is broken. * src/libusb-glue.c: tentatively tag a Philips device with this flag. * src/libmtp.c: fixed usage of returned pointers from realloc(), introduce new flag. 2007-07-05 Tero Saarni * src/libmtp.c: update cache when manipulating objects instead of always flushing the whole cache. 2007-07-03 Linus Walleij * src/libmtp.c: use the params->proplist metadata cache. Help rid all flush_handles() you can in order to add even more to the efficiency of the cache. 2007-07-01 Linus Walleij * src/ptp.c: sync to upstream gPhoto source. * src/ptp.h: dito. * src/ptp-pack.c: dito. * src/libmtp.c: use the params->objectinfo object info cache to speed things up considerably. This is exactly what libgphoto2 does so now we move closer to upstream. I believe this also fixes quite a few memory leaks because we weren't freeing the strings inside the objectinfo previously. 2007-05-29 Linus Walleij * src/libmtp.c: use the set object prop list command to set album props if available. Follow metadata set design pattern used for tracks; check first if the object type can set name/artist/genre. 2007-05-24 Jeff Mitchell * hotplug.sh.in: Properly install the HAL FDI rules if the user so chooses to when prompted. 2007-05-24 Jeff Mitchell * examples/hotplug.c: Fix/update HAL output to conform to new specs. Fix whitespacing to be consistent. 2007-05-17 Richard Low * src/libusb-glue.c: added Samsung YH-920 2007-05-11 Linus Walleij * examples/hotplug.c: output a usb.ids map if need be. * sync-usbids.sh: script to assist in comparing our device database to the linux-usb database so we can submit new entries to it more easily. Please extend this until it creates automated diff:s if you can! 2007-05-10 Linus Walleij * src/libusb-glue.c: some new devices, some rewording etc. 2007-05-05 Linus Walleij * src/libusb-glue.h: removed the DUALMODE flag, it's pointless and equal to the problem solved by the UNLOAD_DRIVER flag. * src/libusb-glue.c: dito, move the only DUALMODE flag into an UNLOAD_DRIVER flag. Added Archos Gmini. 2007-05-05 Richard Low * src/libusb-glue.c: added Philips PSA610 * src/libmtp.c: code to recursively get object handles for each assoc. * src/ptp.h: ditto 2007-04-28 Richard Low * src/libusb-glue.c: new device 2007-04-26 Linus Walleij * src/libusb-glue.c: memory leak: dangling, unused pointer killed. 2007-04-23 Linus Walleij * src/libmtp.h.in: extend LIBMTP_album_t to include fields for artist and genre. This is sort of required so we must change the API to have it working properly. * src/libmtp.c: dito. Reflect changes in implementation. 2007-04-18 Linus Walleij * src/ptp.c: sync to upstream gPhoto source. * src/ptp.h: dito. 2007-04-17 Richard Low * src/libusb-glue.c: new device 2007-04-13 Richard Low * src/libusb-glue.c: new devices 2007-04-12 Linus Walleij * examples/hotplug.c: fix GOTO style in udev map. 2007-04-02 Linus Walleij * examples/files.c: some WIN32 64bit prefix fixup. * examples/tracks.c: dito. 2007-03-28 Ted Bullock * examples/*.c: Print library version number on execution of examples. * src/libmtp.h.in: New version number string to aid version echoing. 2007-03-26 Linus Walleij * configure.ac: bump version to 0.1.5, release 0.1.5! * src/Makefile.am: bump lib interface revision to libmtp.so.5.2.1, backwards compatible to libmtp.so.5. 2007-03-24 Richard Low * src/libusb-glue.c: fixed bug in zero read code 2007-03-23 Linus Walleij * src/libmtp.c: refactored MTP property list handling code to make things simple. Removed the flag for MTP enhanced: there are devices that will not work without MTP enhanced (for example the Samsung YP-K5 will only support setting object property lists, not individual object properties, leaving out parts of the MTP basic subset), thus we are allowed to reverse-engineer and implement this for interoperability. I also made the output from LIBMTP_Dump_Device_Info() considerably more verbose, plotting out the ranges and possible enumerated values of all object properties For example you can see that the secret values associated with Audible.com property 0xda01 is an enumerated value that can be 2, 3 or 4 (etc). 2007-03-22 Richard Low * src/ptp.c: PTP_OC_MTP_SetObjPropList implementation * src/ptp.h: ditto * src/libmtp.c: Use PTP_OC_MTP_SetObjPropList when updating track metadata. 2007-03-18 Richard Low * src/libusb-glue.c: new devices. Some of the Samsung players may need DEVICE_FLAG_NO_ZERO_READS to be set - I only know the YP-K5 needs it. 2007-03-16 Linus Walleij * src/libusb-glue.h: introducing yet another device flag for the irivers bugged firmwares, this is for the Alzheimer disease that cause irivers to forget that OGG files are OGG files. * src/libmtp.c: dito. * src/libusb-glue.c: introduce this flag for all iriver devices. * examples/pathutils.c: found a (small) bug. 2007-03-12 Linus Walleij * Makefile.am: cleanup patch from Rafael Laboissiere. * src/libusb-glue.c: refactored device detection code to immediately test if the device is in the known devices list if it does not feature a MTP device descriptor. This fixes the problem of not being able to mix devices with proper descriptors and non-detected devices. 2007-03-07 Linus Walleij * src/libusb-glue.c: remove libgphoto2 functions that we don't use. * src/libusb-glue.h: export the free_mtpdevice_list() function, new signature of find_usb_devices(). * src/libmtp.c: shrink code, pass as list of devices instead of several huge arrays between libmtp.c and USB glue layer in libusb-glue.c using the nifty list struct defined in libusb-glue.h. * Eventually release libmtp 0.1.4. 2007-03-06 Linus Walleij * src/libusb-glue.c: rewrote one more function to be non-recursive, perhaps I found the remaining bug, just cannot see that right now, will test tomorrow. 2007-03-05 Linus Walleij * src/libmtp.c: rewrite recursive function to linear. * src/libusb-glue.h: create a wrapper type for the device list instead of abusing the libusb device "next" field in our code. * src/libusb-glue.c: rewrite all recursive functions to linear, use wrapper objects, don't copy the libusb device struct, instead just store a pointer to it. This magically solved a bug... 2007-03-04 Linus Walleij * src/Makefile.am: bump library interface to libmtp.so.5.2.0 backwards compatible with any libmtp.so.5 interface, for imminent libmtp 0.1.4 release. 2007-03-03 Ted Bullock * src/libusb-glue.c: Don't echo warnings about reading a single extra byte on devices in which DEVICE_FLAG_NO_ZERO_READS has been set * src/libmtp.c: New API function to retrieve the number of devices in a list of connected devices * src/libmtp.h: New API function to retrieve the number of devices in a list of connected devices * examples/detect.c: Use new API function to count number of devices that were detected 2007-03-03 Linus Walleij * src/libusb-glue.h: Tiresome ramblings to explain exactly what the (now renamed) device flag DEVICE_FLAG_NO_ZERO_READS really means. * src/libusb-glue.c: Renamed flag. Indent code :-) Reading the code and being impressed by our ability to iron out the root cause of this kinda weird thing... Fix a few compile warnings. 2007-03-03 Richard Low * src/libusb-glue.c: (hopefully) fixed iRiver read errors. Enabled get object prop lists for Clix since it appears to work. * src/libusb-glue.h: ditto * src/ptp.h: ditto 2007-02-28 Linus Walleij * src/ptp.h: Upstream accepted our patch so synced it in. 2007-02-27 Linus Walleij * src/ptp.c: Synced in upstream version which removes the offending line. * src/libmtp.c: replaces strcmp() for strcasecmp() in folder detection since Windows and some devices (such as iRivers) ignore case and user capital letters for default folders. 2007-02-22 Ted Bullock * src/ptp.c: Comment out line in ptp_exit_fd_handler that was closing a file descriptor. This is not the responsibility of the PTP Layer. Defect and solution found by Rob Reardon 2007-02-26 Linus Walleij * src/libmtp.c: Implement a check for PTP_OC_MTP_SetObjectPropValue in the LIBMTP_Update_Track_Metadata() function, there are obviously devices that do not support this, but only PTP_OC_MTP_SetObjPropList instead (such as the Samsung YH 925-GS), but we haven't implemented that yet. Problems are atleast reported correctly now. 2007-02-24 Richard Low * src/libusb-glue.c: Fix incorrect transfer sizes causing zero write issues 2007-02-23 Linus Walleij * src/libmtp.c: Undeprecate getting first device code. 2007-02-23 Richard Low * src/libmtp.c: Fix crash when no devices connected 2007-02-23 Ted Bullock * examples/detect.c: Stub out probe functionality * src/libusb-glue.c: Remove old uni-device cruft code * src/libusb-glue.h: Remove old uni-device cruft code * Replace LIBMTP_ERROR_N0_DEVICE_ATTACHED with LIBMTP_ERROR_NO_DEVICE_ATTACHED across entire project 2007-02-22 Ted Bullock * examples/albums.c: Updated to use new multi device code * examples/tracks.c: Updated to use new multi device code * examples/files.c: Updated to use new multi device code 2007-02-18 Ted Bullock * src/libmtp.c: Altered the function LIBMTP_Get_First_Device to wrap around the multi device API. Also added deprecation warnings to avoid using this function 2007-02-17 Richard Low * src/libusb-glue.c: Debug output fixes and read/write sizes changed * src/libmtp.c: memset params to 0 to avoid freeing unalloced memory * src/ptp.h: read/write sizes changed 2007-02-15 Robert Reardon * src/libmtp.c: Fix a segfault in new error handling code. 2007-02-15 Linus Walleij * src/libmtp.c: Adding some sanity checks to error stack code. * examples/newplaylist.c: LGPL boilerplate, crediting Robert. * examples/playlists.c: LGPL boilerplate. * examples/sendfile.c: LGPL boilerplate, crediting me and Chris. * examples/sendtr.c: LGPL boilerplate, crediting me, Chris, Shaun, Enrique. * examples/thumb.c: LGPL boilerplate, crediting Robert. * examples/tracks.c: LGPL boilerplate. * examples/trexist.c: LGPL boilerplate, crediting noone. 2007-02-15 Ted Bullock * examples/folders.c: Updated to use new multi device code * src/libmtp.c: Fixed potential memory leaks * src/libusb-glue.c: Fixed potential memory leaks and fixed device release segfault for multiple devices 2007-02-14 Ted Bullock * src/libusb-glue.c: Wrote three new recursive functions to avoid extreme levels of multiple indirection and to clean the code up a bit for multiple devices. * examples/detect.c: Adjusted function calls to use new multiple device code. * src/libmtp.h.in: Added prototype for LIBMTP_Release_Device_List 2007-02-12 Ted Bullock * src/libmtp.c: Two new functions (create_usb_mtp_devices and LIBMTP_Get_Connected_Devices) to add support for multiple devices to client applications * src/libmtp.h: Added LIBMTP_Get_Connected_Devices as a publicly accessible function *libusb-glue.c: Renamed connect_mtp_devices to find_usb_devices *libusb-glue.h: Renamed connect_mtp_devices to find_usb_devices 2007-02-09 Ted Bullock * src/libusb-glue.c: Addressed a number of potential memory leaks in the new multiple device code 2007-02-05 Linus Walleij * src/libmtp.h.in: LGPL boilerplate. * src/libusb-glue.h: LGPL boilerplate. * src/unicode.h: LGPL boilerplate. * src/util.h: LGPL boilerplate. * examples/albumart.c: LGPL boilerplate, crediting Andy. * examples/pathutils.h: LGPL boilerplate, crediting Chris. * examples/pathutils.c: LGPL boilerplate, crediting me and Chris. * examples/common.h: LGPL boilerplate. * examples/albums.c: LGPL boilerplate, crediting Chris. * examples/connect.c: LGPL boilerplate, crediting Chris. * examples/delfile.c: LGPL boilerplate, crediting me and Chris. * examples/detect.c: LGPL boilerplate. * examples/emptyfolders.c: LGPL boilerplate, crediting Andy. * examples/files.c: LGPL boilerplate. * examples/folders.c: LGPL boilerplate. * examples/format.c: LGPL boilerplate. * examples/getfile.c: LGPL boilerplate, crediting me and Chris. * examples/getplaylist.c: LGPL boilerplate. * examples/hotplug.c: LGPL boilerplate, crediting me and Marcus. * examples/newfolder.c: LGPL boilerplate, crediting me and Chris. 2007-02-02 Linus Walleij * src/ptp.c: sync upstream. * src/ptp.h: dito. * src/ptp-pack.c: dito. * src/libmtp.c: make changes necessary to handle the new iconv(3) code in ptp-pack.c. People will have to use recent stdlibc, glibc or libiconv. Also call new memory clean-up functions. Fix LGPL boilerplate text. * src/unicode.c: Fix LGPL boilerplate text. * src/utils.c: Fix LGPL boilerplate text. * src/libusb-glue.c: Fix LGPL boilerplate text. 2007-01-24 Ted Bullock * src/libusb-glue.c: new function to retrieve multiple device instances. * src/libusb-glue.h: dito. * src/libmtp.h.in: new error codes. 2007-01-22 Linus Walleij * examples/albumart.c: use the new errostack. * examples/delfile.c: dito. * examples/detect.c: dito. * examples/emptyfolders.c: dito. * examples/format.c: dito. * examples/getfile.c: dito. * examples/getplaylist.c: dito. * examples/newfolder.c: dito. * examples/newplaylist.c: dito. * examples/playlists.c: dito. * examples/sendfile.c: dito. * examples/sendtr.c: dito. * examples/thumb.c: dito. * src/libmtp.c: add some errors to the stack so we can see how it's to be used. (Just a first try...) * src/libusb-glue.c: move the LIBMTP_Get_Supported_Devices() function into this file cause it only return USB devices anyway and could be renamed LIBMTP_Get_Supported_USB_Devices() (but let's not do that renaming since it would break the API). For now let's understand this is a USB-only function by simply putting it in the libusb-glue.c file. 2007-01-22 Ted Bullock * src/libusb-glue.c: first hack at creating an interface to retrieve multiple devices. * src/libmtp.h.in: new error codes related to multiple devices. 2007-01-21 Richard Low * src/libusb-glue.c: more new devices 2007-01-20 Linus Walleij * src/libmtp.h.in: error stack handling like in libnjb. just bare bones implementation as of now but the idea should be clearly visible. TODO: add a plethora of errors and adjust examples to make use of the error stack. * src/libmtp.c: dito. 2007-01-20 Richard Low * src/libusb-glue.c: new device 'Philips PSA235' 2007-01-16 Linus Walleij * configure.ac: bump and release 0.1.3. * src/Makefile.am: bump interface REVISION. Nothing changed externally really. 2007-01-11 Linus Walleij * src/libmtp.sym: updated symbol table for mingw32 but does anyone use this? Also I believe one could auto-generate this some way, just haven't figured out how... Perhaps with a funky script that massage libmtp.h if nothing else. 2007-01-11 Richard Low * src/libusb-glue.c: a zero read fix * src/libmtp.c: fix spelling mistake 2007-01-09 Linus Walleij * src/libusb-glue.c: repair callbacks, structure the code just a little bit. * src/libmtp.c: don't assign values to writes or reads, use the PTP transport intrinsics instead. 2007-01-07 Orson Teodoro * src/ptp.h: Encoding profile. * src/ptp.c: Dito. 2006-01-07 Linus Walleij * src/libusb-glue.c: (re)introduce de-halting of endpoints as this is needed by VMWare emulation. Must check whether this causes problems for other archs! Problem was reported by Orson Teodoro under i686 Gentoo, with a suggested patch. 2006-01-07 Marcus Meissner * src/ptp.c: sync to upstream libgphoto2. * src/ptp.h: dito. * src/ptp-pack.c: dito. * libusb-glue.c: fixes to move low-level functions out of ptp.c and into this libmtp-specific portion. libgphoto2 has been similarly altered to use a usb.c file for the low-level stuff. (This was a long needed split anyway.) 2007-01-03 Richard Low * src/libusb-glue.c: fix zero write bug * src/ptp.c: ditto 2007-01-02 Linus Walleij * src/libusb-glue.c: fix up comments, remove things refering to stuff we don't have. 2007-01-02 Richard Low * src/libmtp.c: another try at split headers/packet sizes * src/ptp.c: ditto * src/libusb-glue.c: ditto 2007-01-01 Linus Walleij * src/libmtp.c: move default setting of split headers off to ptp.c open session. * src/ptp.c: dito. 2007-01-01 Richard Low * src/libmtp.c: split headers/packet size fix * src/ptp.c: ditto * src/ptp.h: ditto * src/libusb-glue.c: ditto 2007-01-01 Orson Teodoro * src/ptp.h: changed some WMDRMND def codes to AAVT def codes. addition of AAVT error codes. * src/ptp.c: changes to reflect modifications done in ptp.h 2006-12-31 Linus Walleij * configure.ac: bump to 0.1.2. * src/Makefile.am: bump interface revision. (Compatible.) * RELEASE 0.1.2. 2006-12-30 Linus Walleij * examples/pathutils.c: reflect new filetypes. * examples/sendtr.c: dito. 2006-12-30 Orson Teodoro * src/ptp.h: added WMDRMPD, WMDRMND, WMPPD, WPDWCN extension codes. added more format object codes flac, m4a, 3gp, aac, xml, xls, ppt, etc. 0x9101-0x910B identfiers are infixed with WMDRMPD. Added more object properties codes (0xDCD3-0xDD72). Added more device property codes. Changed PTP_OFC_MTP_WindowsImageFormat to 0xb881 reflect spec. * src/ptp.c: added changes to reflect new extensions, object codes, device property codes. * src/libmtp.c: modified mp4 to reflect it is a container format not a codec. Added more descriptions in init_filemap(). mp4 container format is ambiguous in LIBMTP_Send_File_From_File_Descriptor(). Audio? video? both?. mp4 searched in video by default. Added comments about this. Added support for the new format object types. * src/libmtp.h.in: added constants to reflect changes to init_filemap(). 2006-12-30 Richard Low * src/libusb-glue.c: fixed bug in debug printing 2006-12-29 Richard Low * src/libmtp.c: Made abstract list creation to be more WMP like * src/libusb-glue.c: added Philips GoGear SA9200 * src/ptp-pack.c: fixed packing bug in ptp_pack_OI 2006-12-29 Marcus Meissner * src/ptp.h: API changes for libgphoto2 to use the file retrieveal functions. * src/ptp.c: dito. * src/libusb-glue.c: changes in libmtp reflecting the new API for libgphoto2. 2006-12-28 Linus Walleij * configure.ac: making older autotools happy. Bump to 0.1.1. * src/Makefile.am: bump interface for release, also autotools. * RELEASE libmtp 0.1.1. 2006-12-19 Matthew Wilcox * src/ptp.c: fix a (serious) short file bug. 2006-12-17 Richard Low * src/libmtp.c: don't bail out on failures when setting metadata. 2006-12-16 Linus Walleij * src/ptp.c: sync to upstream. * src/ptp.h: dito. * src/ptp-pack.c: dito. 2006-12-15 Linus Walleij * src/libmtp.h.in: make the format function take a storage as parameter. Add comments to device storage. * src/libmtp.c: dito, fix up some code and docs. * examples/format.c: make the format command comply with the new API. 2006-12-14 Linus Walleij * src/libmtp.c: make get_first_storage_freespace() always query the first storage when the space is requested. And some other janitorial stuff. 2006-12-13 Linus Walleij * src/libusb-glue.c: one more device. * examples/detect.c: compilation warnings fixed. 2006-12-13 Robert Reardon * src/ptp.c: add 0xD901 flag as BuyNow property of objects. * src/ptp.h: ditto. 2006-12-12 Daniel Williams * src/libmtp.h.in: revamped storage API. * src/libmtp.c: dito. * examples/detect.c: dito. 2006-12-12 Robert Reardon * src/libmtp.c: Send_Representative_Sample() updated to set image height and width, or audio duration and size. 2006-12-07 Linus Walleij * src/libmtp.h.in: support firmware object type. (Dangerous.) * src/libmtp.c: dito. 2006-12-07 Linus Walleij * src/libmtp.c: default text folder detection (used in Samsung Yepp T9) also add a few "My Foo" folder strings, remove the "remaining directories" kludge. * src/libmtp.h.in: default text folder. 2006-12-06 Linus Walleij * src/libmtp.h.in: extend the respresentative sample API a bit. * src/libmtp.c: dito. * examples/albumart.c: free memory after use. * examples/thumb.c: dito. * RELEASE this as libmtp 0.1.0! 2006-12-04 Linus Walleij * src/ptp.c: enable split headers on sending object lists again. 2006-12-04 Robert Reardon * src/libmtp.c: abstract Send_Representative_Sample() so it can send samples for any format that supports it * src/libmtp.h.in: same as above * examples/albumart.c: altered to use new abstract function above * example/thumb.c: sample program to upload thumbnails * example/Makefile.am: add sample thumbnail program 2006-12-03 Linus Walleij * src/libmtp.c: check space on disk before sending tracks or files. * src/libmtp.h.in: refactor LIBMTP_Send_Album_Art() into LIBMTP_Send_Representative_Sample(). * src/libmtp.c: dito. * examples/albumart.c: dito. 2006-12-02 Marcus Meissner * examples/Makefile.am: make sure symlinks really end up in the correct dir. 2006-11-30 Linus Walleij * src/ptp.c: make Matthews patch thread-safe and fix it so it will handle more than one surplus packet. * src/ptp.h: dito. 2006-11-30 Richard Low * src/libmtp.c: memset PTPObjectInfo structs to 0 2006-11-30 Matthew Wilcox * src/ptp.c: on some devices, surplus packet data is sometimes returned during read, i.e. a header of the next package is typically attacked to the incoming data, as if someone was sending several packets at once. If this happens we buffer the surplus packet. * src/libusb-glue.c: revert my own mistakes by making them Windows-only. 2006-11-30 Linus Walleij * configure.ac: this *is* gonna be libmtp 0.1.0! * src/Makefile.am: age interface to 4-0-0 to indicate that intefaces have been removed. * src/libmtp.h.in: removed external object interface. * src/libmtp.c: dito. Made all object manipulation functions static. 2006-11-29 Richard Low * src/libusb-glue.c: added new devices 2006-11-29 Linus Walleij * src/libusb-glue.c: remove some pointless #include <> clutter, call usb_set_configuration() as needed by Windows. * src/libmtp.c: various fixups to enable use of Windows include file. * README.windows.txt: added a quick porting guide for MSVC by Farooq Zaman. 2006-11-28 Linus Walleij * src/libmtp.h.in: removed filetype mapping API. We can handle everything inside of libmtp now so no need for this. * src/libmtp.c: dito. 2006-11-27 Linus Walleij * examples/files.c: unsigned int sized printout. * examples/tracks.c: sort of the same. * Makefile.am: HAL style map output by default. 2006-11-26 Richard Low * src/libmtp.c: object handles for proplists * src/ptp-pack.c: ditto * src/ptp.c: ditto * src/ptp.h: ditto 2006-11-25 Marcus Meissner * examples/hotplug.c: adding HAL style XML output for the devices. * examples/Makefile.am: fixing a bug in the automake file (pathutils.h missing!) * Makefile.am: fix the problem with re-making sources (you had to run ./autogen.sh before!) 2006-11-23 Linus Walleij * src/libusb-glue.h: add a new bug flag for devices that have broken PTP_OC_MTP_GetObjPropList implementations. * src/libusb-glue.c: state that all iRivers have this problem. * src/libmtp.c: disable the user of ptp_mtp_getobjectproplist() for these devices. 2006-11-21 Robert Reardon * src/libmtp.c: set handle ids for new objects to 0 when creating new albums and playlists. 2006-11-21 Linus Walleij * src/libmtp.c: enabled enhanced mode for metadata retrieval by default. * src/libmtp.c: fixed the problem with sending files using enhanced commands. 2006-11-20 Linus Walleij * src/ptp.h: sync to upstream libgphoto2 * src/ptp.c: dito. * src/ptp-pack.c: dito. * src/libmtp.c: check for zerolength files/tracks. 2006-11-20 Andy Kelk * src/libmtp.h.in: add "parent_id" property to LIBMTP_track_struct. * src/libmtp.c: get "parent_id" property when reading tracks. * examples/emptyfolders.c: new example program for pruning empty folders. (does a dummy run by default). 2006-11-19 Robert Reardon * src/libmtp.c: use enhanced MTP commands to create playlists and send files * examples/newplaylist.c: demo program for creating new playlists * examples/Makefile.am: add demo newplaylists program 2006-11-19 Daniel Williams * src/libusb-glue.c: fix error on reconnect. 2006-11-18 Richard Low * src/ptp.c: tidy up ptp_usb_getdata 2006-11-17 Richard Low * src/libmtp.c: fixed parent handle for uploaded tracks 2006-11-17 Robert Reardon * src/libmtp.c: fixed up album art using enhanced commands. 2006-11-16 Richard Low * src/libmtp.c: a crude implementation of ptp_mtp_getobjectproplist * src/ptp.c: ditto * src/ptp.h: ditto * src/ptp-pack.c: ditto 2006-11-16 Robert Reardon * src/libmtp.c: use enhanced MTP commands to create albums and add detection of the default album folder. * src/libmtp.h.in: add a holder for album default folder. 2006-11-15 Richard Low * src/ptp-pack.c: set string buffer to correct size. 2006-11-14 Richard Low * examples/tracks.c: really use undeprecated API entry. 2006-11-13 Richard Low , Linus Walleij * src/libmtp.h.in: add LIBMTP_Get_Tracklisting_With_Callback() and LIBMTP_Get_Filelisting_With_Callback() * src/libmtp.c: dito, deprecate LIBMTP_Get_Tracklisting() and LIBMTP_Get_Filelisting() * examples/tracks.c: use undeprecated API entry. * examples/connect.c: ditto. * examples/detect.c: ditto. * examples/files.c: ditto. * src/ptp.c: working on getting object prop lists. * src/ptp.h: dito. 2006-11-12 Richard Low * src/libusb-glue.c: added Zen Vision W to devices 2006-11-07 Richard Low * src/libmtp.c: added checks for supported properties 2006-11-06 Richard Low * src/libmtp.c: added a check for NULL filenames in LIBMTP_Get_Folder_List. 2006-11-01 Linus Walleij * src/libmtp.h.in: set/get uint8 to/from objects * src/libmtp.c: send object property list. * src/ptp.c: dito. * src/ptp.h: dito. * src/ptp-pack.c: dito. 2006-10-29 Andy Kelk * examples/albumart.c: simple tool for adding album art. * src/libmtp.c: graceful handling of players not supporting abstract album objects. 2006-10-27 Linus Walleij * src/Makefile.am: bump library interface to reflect the new album methods. * configure.ac: bump to 0.0.22 for the next release. 2006-10-27 Andy Kelk * src/libmtp.c: add support form abstract audio/video albums. * src/libmtp.h.in: dito. 2006-10-23 Linus Walleij * src/libmtp.c: retire opcode rendering (moved to ptp.c) * src/ptp.c: sync to upstream. * src/ptp.h: dito. * src/ptp-pack.c: dito. 2006-10-20 Linus Walleij * Release 0.0.21 to get all the new device support out. 2006-10-16 Linus Walleij * configure.ac: bump to 0.0.21. * src/libusb-glue.c: add code to unload a kernel driver for the primary interface if it is already in use under Linux. * src/libusb-glue.h: add a device flag to make this possible. 2006-10-11 Linus Walleij * examples/delfile.c: patch from Chris Debenham straingtening out the command-line interface a bit more. 2006-10-10 Linus Walleij * examples/delfile.c: patch from Chris Debenham to make this command take an optional filename as parameter instead of file ID. 2006-09-26 Linus Walleij * libmtp.pc.in: require libusb instead of just linking it. * configure.ac: bump release to 0.0.20 and release. 2006-09-25 Linus Walleij * examples/evolution-sync.sh: example script to illustrate to to transfer calendar, task and contact information to a device supporting this. 2006-09-19 Linus Walleij * src/libmtp.h.in: fixed attribute IDs to be 16bit. * src/libmtp.c: dito. * examples/sendfile.c: support vcard3. 2006-09-16 Linus Walleij * configure.ac: bump to 0.0.19 and release. There are some new devices as well. * src/unicode.c: retire unused code. 2006-09-13 Linus Walleij * examples/format.c: formatting test program. * examples.Makefile.am: added format. 2006-09-13 Andy Kelk * src/libmtp.h.in: added interface to format storage. * src/libmtp.c: dito. * src/ptp.c: dito. * src/ptp.h: dito. 2006-09-12 Linus Walleij * configure.ac: bump release. Released 0.0.18 yesterday. * src/libmtp.c: do not try to read battery max level unless the device supports it. (Bug occurred on Toshiba Gigabeat P10.) 2006-09-11 Linus Walleij * src/libusb-glue.c: messed around a bit with device descriptor detection so as to bring closer to libgphoto2 detection algorithm. I've seen things that might be false positives, possibly USB mass storage devices with additional MSFT descriptors to indicate they have Janus DRM. * src/libmtp.c: use UCS-2-INTERNAL if we're not on glibc. glibc knows that UCS-2 is in machine endianness but Darwin and *BSD does not. Detect C library and switch accordingly. * src/unicode.c: retire old unicode code only keep things we cannot live without. Remove the own internal UCS-2 conversion engine and the internal iconv() engine and use the one already available in PTPParams. * src/unicode.h: dito. 2006-09-07 Linus Walleij * src/libusb-glue.h: added device flags so we can make the code behave differently on certain devices. * src/libusb-glue.c: dito, plus removed some debug prints. * src/libmtp.c: docs. * src/libmtp.h.in: added device_flags to device list struct. * src/Makefile.am: bumped to compatible library interface. * configure.ac: bump version to 0.0.18 (0.0.17 released yesterday). 2006-09-06 Richard Low * src/libusb-glue.c: changed packet sizes to improve transfer speeds. * src/libmtp.c: changed packet sizes to improve transfer transfer speeds. Also stopped extra ptp_getobjectinfo calls when getting directories on connect. 2006-09-06 Linus Walleij * src/libusb-glue.c: fixed some endpoint size detection and sending special file sizes stuff. Real hairy bug... Also messed around a bit with the callbacks. * src/libmtp.c: changes for callback size detection. 2006-09-04 Linus Walleij * src/libmtp.c: bug in streaming code, use defined USB_BULK_HDR_SIZE instead of magic values. 2006-09-02 Linus Walleij * src/libmtp.c: add some code to have LIBMTP_Send_File_From_File_Descriptor() accept a stream if size is set to (uint64_t) -1, plus documentation fixes. I don't think the streaming code will work but whoever want to experiment with it has a place to start. * examples/refactortest.c: removed. Who uses this? 2006-08-30 Linus Walleij * configure.ac: version bump. * src/libmtp.c: more debug prints. * src/libusb-glue.c: new iRiver device called Clix. By the way I released libmtp 0.0.16 yesterday. 2006-08-28 Linus Walleij * configure.ac: version bump. * src/ptp-pack.c: upstream has committed my patch giving full unicode support in libgphoto2 ptp2 camlib. No need for any more ugly workarounds, plus we now have full unicode filenames! * src/ptp.c: dito. * src/ptp.h: dito. * src/libmtp.c: revamp to use the new unicode support in libgphoto2. * src/unicode.c: remove unused functionality. * src/unicode.h: dito. 2006-08-27 Linus Walleij * configure.ac: version bump. Release all these fixes as 0.0.15. * src/libusb-glue.c: fixed sucky errors. Added callback code when reading files. * src/libusb-glue.h: const correctness. * src/libmtp.h.in: finally fixup the type on the callbacks. * src/libmtp.c: more accurate sending callbacks. Callbacks when getting files also, working correctly. Typeing of callbacks now OK. * examples/getfile.c: some display bar cosmetic fixup. * TODO: lots of the things todo are now done. 2006-08-26 Linus Walleij * configure.ac: version bump. * src/libmtp.c: fix bug and reinstate callbacks. * src/libusb-glue.h: dito. * src/libusb-glue.c: dito. 2006-08-25 Linus Walleij * src/libmtp.c: use the new file descriptor sender function. Going to release this as 0.0.13. * src/ptp.c: upstream accepted patches synced in. * src/ptp.h: dito. 2006-08-22 Linus Walleij * src/libusb-glue.c: found a real nasty endpoint bug, code from libgphoto2 was assuming max packet size of 512 bytes while it is 64 when a USB 2.0 device is plugged into an UHCI hub. 2006-08-22 Linus Walleij * configure.ac: bump to 0.0.13, also released 0.0.12 now. 2006-08-21 Linus Walleij * src/libmtp.c: fixup mmap() usage and add madvise() as result of experiments by Gavin McCullagh. Upstream accept patch to get files directly to file descriptor. Move iconv() converters into device struct for thread safety. * src/ptp.c: sync to upstream which merges patch to get file directly to file descriptor. * src/ptp.h: dito. * src/unicode.c: move iconv() converters into the device struct for thread safety. * src/unicode.h: dito. 2006-08-20 Linus Walleij * src/libmtp.h.in: set friendly name and sync partner, rename ownername to friendlyname. * src/libmtp.c: dito. * examples/detect.c: reflect changes. * src/Makefile.am: interface is incompatible so age it. 2006-08-19 Linus Walleij * src/libmtp.h.in: add function to get syncronization partner for the device. * src/libmtp.c: dito. * examples/detect.c: use that function. * src/Makefile.am: backward-compatible interface bump. 2006-08-17 Linus Walleij * configure.ac: bump to 0.0.12 and require iconv.h. 2006-08-16 Linus Walleij * src/unicode.c: remove bigendian weirdness and switch to using iconv() instead. * src/unicode.h: dito. * src/libmtp.c: reflect changes. 2006-08-09 Linus Walleij * Release libmtp 0.0.11. 2006-08-04 Linus Walleij * src/libmtp.c: patch from Dan Aloni to make sendfile use mmap and avoid memory drainage. * src/libusb-glue.c: patch from Andy Kelk to avoid exit():ing when the interface cannot be claimed. * configure.ac: version bump. 2006-07-27 Linus Walleij * Release libmtp 0.0.10. 2006-07-26 Linus Walleij * src/libusb-glue.c: new SanDisk devices. * src/libmtp.c: only set metdata properties supported by the device, duh. * src/ptp.c: sync to upstream. * src/ptp.h: sync to upstream. * configure.ac: bump to 0.0.10. 2006-06-22 Linus Walleij * Release libmtp 0.0.9. 2006-06-21 Linus Walleij * src/libmtp.h.in: added function to retrieve supported filetypes. * src/libmtp.c: ditto. * examples/detect.c: use that function. 2006-06-19 Linus Walleij * src/unicode.c: support all endianness, detect byte-order-mark * src/unicode.h: ditto. * src/libmtp.c: ditto. * examples/detect.c: use proper tempfile function. * src/libmtp.h.in: add some more track properties. * src/libmtp.c: ditto. * examples/tracks.c: ditto. 2006-06-16 Linus Walleij * src/libmtp.h.in: new interfaces for single metadata post retrieveal. * src/libmtp.c: ditto. * examples/playlists.c: display track info using the new individual track metadata retrieveal method. * examples/getplaylist.c: ditto. 2006-06-13 Linus Walleij * src/libmtp.h.in: added default folders to device struct. Add some new function prototypes. * src/libmtp.c: discover and use the default folders if we can find them. Retrieve device secure time and cert out of sheer curiosity. * src/ptp.c: sync to libgphoto2 with my patches. * src/ptp.h: ditto. 2006-06-07 Linus Walleij * src/libmtp.h.in: new playlist API and refactorings. * src/libmtp.c: ditto, and refactorings. * src/unicode.h: const correctness. * src/unicode.c: ditto. * examples/playlists.c: new example program. * configure.ac: bump to 0.0.9 * src/Makefile.am: bump library interface. 2006-06-05 Linus Walleij * examples/sendtr.c: fixed annoying bug that made this program totally useless. * src/libmtp.c: cosmetics. * configure.ac: bump to 0.0.8. 2006-06-03 Linus Walleij * src/libmtp.c: metadata bugs, album name and genre confused. Fixe it and released libmtp 0.0.7. 2006-06-01 Linus Walleij * Released libmtp 0.0.6. 2006-05-31 Linus Walleij * src/libmtp.c: fixed mapping for JPEG vs JFIF * src/libmtp.h.in: added proper type for JPEG * examples/sendfile.c: send proper JPEG type 2006-05-30 Flavien Lebarbe * src/libmtp.c: fixed a bug in update metadata due to bad use of return code. * src/libusb-glue.c: fixed a loop exiting problem with good 'ol GOTO. 2006-05-29 Linus Walleij * src/libusb-glue.c: one more device. * doc/examples.h: produce correct documentation. * configure.ac: bump to 0.0.6. * src/ptp.c: sync to libgphoto2. * src/ptp.h: ditto. * src/ptp-pack.c: ditto. * src/libmtp.c: fixed all filetype API related functions not to use any PTP intrinsic defines at all, made all parameters to functions use the internal libmtp interface enumerations and definitions. Removed LIBMTP_Release(): we can live with the memory lost during init. You're not supposed to re-initialize the device. Consequently removed the delete function that cleaned the filetype assoc list. * examples/refactortest.c: reflect changes. 2006-05-26 Dave Kelly * src/libmtp.c: refactored object handling to be more generic * src/libmtp.h.in: ditto * examples/refactortest.c: Added simple example to use refactoring * examples/getplaylist.c: Added example to extract playlist data * src/ptp.c: Re-added ptp_get/set_objectreferences to allow for playlist handling * src/ptp.h: ditto 2006-05-08 Linus Walleij * src/libmtp.h.in: add simple detection function. * src/libusb-glue.c: implement MTP "OS descriptor" for looking for MTP devices. * examples/detect.c: make it possible to do very rudimentary detection with "detect -p". * configure.ac: bump to 0.0.5. 2006-05-07 Linus Walleij * COPYING: since we no longer use any parts of libptp2 and only files from libgphoto2, we switch to the GNU Lesser General Public License (GNU LGPL). libptp2 is a derived work from libgphoto2, and so is libmtp, there are no remnants of libptp2 in libmtp anymore. 2006-05-04 Linus Walleij * examples/sendfile.c: fixes some more filetypes. * src/libmtp.c: respectfully rearranged to use a filetype mapping table. * src/ptp-pack.c: real nasty unicode packing bug. * Release libmtp 0.0.4. 2006-05-02 Linus Walleij * src/libmtp.c: general shaping up for release. All track and file sending functions now respects a parent ID to be sent along with files and tracks. * src/libmtp.h.in: dito. * src/libusb-glue.c: dito. * examples/sendfile.c: interface dependency changes. * examples/sendtr.c: dito. 2006-04-30 Linus Walleij * src/ptp.c: sync upstream. * src/ptp.h: dito. 2006-04-27 Linus Walleij * examples/sendfile.c: first file sender program based on API implementation and changes by Chris Allegretta. * examples/Makefile.am: new program, new entry. * src/libmtp.c: reflect this new functionality. * src/libmtp.h.in: dito. 2006-04-25 Linus Walleij * Rebased the sources around libgphoto2 instead. This was a major revision... * src/ptp.c: imported libgphoto2 version verbatim. * src/ptp.h: imported libgphoto2 version, minor patch. * src/ptp-pack.c: imported libgphoto2 version, minor patch. * src/ptp-pack.h: dropped, libgphoto2 does not use it. * src/mtp.c: dropped, since all functions are now in ptp.c * src/mtp-pack.c: dropped, same reason. * src/mtp.h: dropped, same reason. * src/mtp-pack.h: dropped, same reason. 2006-04-21 Linus Walleij * Released libmtp 0.0.3 * Bumped source to 0.0.4 2006-04-21 Linus Walleij * src/ptp-pack.c: GCC 4.x compilation patch from Diego Pettenò. * src/libusb-glue.c: New Samsung device and some from libgphoto2. * src/ptp.h: some defines from libgphoto2 to get a bit more compatible. * src/libmtp.c: Added a folder API implementation by Dave "ravelox" Kelly. * src/libmtp.h.in: dito. * examples/folders.c: dito. * examples/newfolder.c: dito. * examples/trexist.c: dito. 2006-03-28 Linus Walleij * m4/*: updated macros to work with GCC 4.1.0. * examples/hotplug.c: new program to create device ID lists. * libmtp.rules: now an auto-generated file. * libmtp.usermap: now an auto-generated file. 2006-03-24 Linus Walleij * Beginning a file API, fixed some example program names and such. 2006-03-18 Linus Walleij * Fixed up callback interface to a simpler version, the old one was bloated stuff from libnjb anyway. Bump to 0.0.2. 2006-03-16 Linus Walleij * Fixed the .h file and implementation so you really only need this one .h file to interface the library. 2006-03-15 Linus Walleij * Added three device information retrieval functions. 2006-03-06 Linus Walleij * Moving some things around to structure the source. More will be needed... 2006-02-27 Linus Walleij * Release libmtp 0.0.1 so people have something to play with, what the heck. Probably saves someones day. 2006-02-24 Linus Walleij * Deltr example program to delete tracks, plus corresponding interface call. 2006-02-23 Linus Walleij * Fixed up sendtr program and metadata tagging function that is used after sending files. 2006-02-22 Linus Walleij * Untested gettr.c and sendtr.c programs to get and send tracks created. 2006-01-30 Linus Walleij * Created the initial GNU source directory structure. * Added the most basic files. libmtp-1.1.6-20-g1b9f164/COPYING0000664000175000017500000006347212205614637015761 0ustar glowwormglowworm GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright © 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright © This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! libmtp-1.1.6-20-g1b9f164/libmtp.pc.in0000664000175000017500000000053112205614637017131 0ustar glowwormglowworm# libmtp pkg-config source file prefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: libmtp Description: libmtp is a library for accessing Media Transfer Protocol devices Version: @VERSION@ Requires: @LIBUSB_REQUIRES@ Conflicts: Libs: -L${libdir} -lmtp Libs.private: @LIBS@ Cflags: -I${includedir} @OSFLAGS@ libmtp-1.1.6-20-g1b9f164/Makefile.am0000664000175000017500000000121112205614637016741 0ustar glowwormglowwormSUBDIRS=src examples util doc ACLOCAL_AMFLAGS=-I m4 pkgconfigdir=$(libdir)/pkgconfig pkgconfig_DATA=libmtp.pc EXTRA_DIST=libmtp.pc libmtp.sh COPYING README.windows.txt # This stuff only makes sense on Linux so only # build and ship it on Linux. if USE_LINUX udevrulesdir=@UDEV@/rules.d udevrules_DATA=@UDEV_RULES@ noinst_DATA=libmtp.usermap libmtp.fdi libmtp.usermap: util/mtp-hotplug util/mtp-hotplug > libmtp.usermap @UDEV_RULES@: util/mtp-hotplug util/mtp-hotplug -u -p"@UDEV@" @UDEV_GROUP@ @UDEV_MODE@ > @UDEV_RULES@ libmtp.fdi: util/mtp-hotplug util/mtp-hotplug -H > libmtp.fdi CLEANFILES = libmtp.usermap @UDEV_RULES@ libmtp.fdi endif libmtp-1.1.6-20-g1b9f164/sync-usbids.sh0000775000175000017500000000055512205614637017521 0ustar glowwormglowworm#!/bin/sh # Script to compare the USB ID list from linux-usb # with the internal list of libmtp. WGET=`which wget` if [ "x$WGET" != "x" ]; then wget -O usb.ids http://www.linux-usb.org/usb.ids examples/hotplug -i > usb.ids-libmtp echo "OK now compare usb.ids and usb.ids-libmtp..." else echo "Could not sync to linux-usb USB ID list. No WGET." fi libmtp-1.1.6-20-g1b9f164/README.windows.txt0000664000175000017500000000547612205614637020115 0ustar glowwormglowwormThis file was created by James Ravenscroft as a direct revision of Farooq Zaman's work with LibMTP on Windows. CHANGELOG ---------------- 14th January 2009: Created the first revision of this file taking information from the work of Farooq Zaman. 1.0 Compilation of LibMTP on Windows 2000/XP/NT ----------------------------------------------------------- LibMTP currently compiles under Windows using MingW/MSys. The source relies upon the __WIN32__ macro which is defined by MinGW by default. Libraries: LibMTP currently depends on LibUSB and libiconv. There are currently projects that port both of these libraries to Windows. Binary files can be obtained from: LibUSB Win32 - http://libusb-win32.sourceforge.net/ LibIconv - http://gnuwin32.sourceforge.net/packages/libiconv.htm With both of these libraries extracted and placed in MinGW's search path, you can compile the library by opening the Msys prompt, navigating to the path where the extracted LibMTP source files can be found and typing: ./configure make all make install 2.0 LibUSB and Driver Issues for Windows ---------------------------------------------- Unfortunately, Windows does not have abstract USB support and depends upon specific drivers for each and every device you use. Fortunately, LibUSB-Win32 provide a solution to this problem. LibMTP takes advantage of the LibUSB-Win32 Device Driver package. 1. Download the latest device driver binary package (libusb-win32-device-bin-x.x.x.x.tar.gz) from http://sourceforge.net/project/showfiles.php?group_id=78138 2. Upon extraction, plug in your music device and run bin/inf-wizard.exe. Selecting your device and saving the inf file in the project root directory. 3. Copy the files "bin/libusb0.dll" and "libusb0.sys" or "libusb0_x64.dll" and "libusb0_x64.sys" for 32-bit or 64-bit operating systems respectively. 4. Goto Start -> Run, type "devmgmt.msc" and press "ok". 5. Select your music device from the list and click Action -> Update Driver, Choose "No, not this time" if prompted to connect to microsoft. 6. Choose "Install from a list or specific location". 7. Choose "Don't search, I will choose the driver to install 8. Click the "Have Disk..." button in the bottom right corner of the prompt 9. Browse to your .inf file and select it. Press Ok 10. The name of your music device should appear in the prompt, click it and click "Next>" (Ignore any prompts about Driver Signing, continuing installation of the selected driver). 11. Click finish to end the driver install process. To get your old driver back: 1. Goto Start -> Run, type "devmgmt.msc" and press "ok". 2. Select your music device, right click on it and click "Properties" 3. Go to the "Driver" pane and select "Roll Back Driver". 3.0 ---------------------------------------------- libmtp-1.1.6-20-g1b9f164/INSTALL0000664000175000017500000002605412205614637015752 0ustar glowwormglowwormINSTALLATION OVERVIEW ===================== Once libmtp is built and installed, you will have the following files ($PREFIX is the --prefix option given to the "configure" script and defaults to /usr/local/): $PREFIX/lib/libmtp.a Static C library $PREFIX/lib/libmtp.so.x.y.z Dynamic C library $PREFIX/lib/libmtp.so.x A link to the library $PREFIX/lib/libmtp.so A link to the library $PREFIX/include/libmtp.h C header file for libmtp API $PREFIX/lib/pkgconfig/libmtp.pc pkg-config configuration file Sample programs will be built in the "example" directory, and should help you get used to using the libmtp API, as well as provide some immediate gratification. Links to other programs using the libmtp API may be found at the homepage: http://libmtp.sourceforge.net/ Install From Distribution ------------------------- You should probably prefer to install libmtp from the distribution source you're using. Last time we checked, libmtp was part of Ubuntu, Fedora, OpenSUSE, Debian testing, Gentoo, FreeBSD ports and OpenBSD packages/ports. Dependencies ------------ To build libmtp you should only need development files for libusb. (Often named libusb-devel or similar.) For working with CVS versions you may need autoconf, automake, libtool, gettext(-devel). To enable the optional MTPZ support using libgcrypt you need the libgcrypt library installed as well. Shared Library Support ---------------------- Shared library linking is supported. You will need to 'make install' the library before you can execute the sample binaries, and add the libmtp install directory to your shared library search path. On Linux, you would add the line "/usr/local/lib" to your "/etc/ld.so.conf" or as a oneliner in for example a "/etc/ld.so.conf.d/local.conf" file and run the program "ldconfig" to scan in the shared libraries at the new path. This is a part of the Linux shared library loader actually. To access the library from real odd locations you can use the LD_LIBRARY_PATH environment variable by setting it before you run your program, for example: % export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib % my_program To check whether you need to do something this: % ldd /usr/lib/rhytmbox/plugins/mtpdevice/libmtpdevice.so | grep mtp % ldd /usr/bin/gnomad2 | grep mtp If the program is linking to a packaged version of libmtp it will likely say something like this: libmtp.so.N => /usr/lib/libmtp.so.N (0xb4e4b000) In this case you may have your freshly compiled library in /usr/local/lib or something like that, and you need to do the LD_LIBRARY_PATH trick. Verify by using "ldd" again. This way of enabling the library to link is a workaround hack. Note that the LD_LIBRARY_PATH is actually supposed to be used for testing, not production systems or distributions. It is commonly used as a workaround when a user is installing libraries in her/his home directory however. Read more about this environment variable here: http://www.visi.com/~barr/ldpath.html The shared library comes with different interface version numbers, for example libmtp.so.4, libmtp.so.5 and so forth. This is used so that both old and new libmtp libraries shall be able to coexist on the same system. When you compile your programs they will typically bind to the latest version of the shared library. A link to the latest version is always provided as $PREFIX/lib/libmtp.so. libusb support -------------- This package depends on libusb. Get libusb from sourceforge at: http://www.sourceforge.net/projects/libusb/ libusb 1.0 and later is preferred for libmtp, but currently also older 0.1.x versions of libusb are supported. libgcrypt support ----------------- The MTPZ extension to libmtp requires libgcrypt to be installed. http://www.gnu.org/software/libgcrypt/ MTPZ support will not be built unless the configure script finds libgcrypt. BASIC BUILD PROCEDURE ===================== To build the package: % ./configure % make % make install By default, libmtp will add the program-prefix "mtp-" to all the example programs prior to installation. The program-prefix option makes libmtp sample programs avoid collision with other programs like sox' "play" program. If the default prefix for some reason fail, try to tag on "--program-prefix=mtp-" to the "configure" command. The "libexedir" in the configure file is hardcoded to /lib/udev to make the mtp-probe (which is built for Linux only) install into that directory. This is the only location that makes sens for this executable. if you want to install the documentation type: % make install-docs if you checked out the sources from CVS, you must first run the autogen.sh script that generates all the GNU autotools files. Notice that this requires GNU autoconf, automake and libtool and possibly some other packages like gettext, readline, intltool and other M4 macro sources. This is done with: % ./autogen.sh Linux hotplugging ----------------- After compilation and installation you may (and should) add hotplugging support by running the hotplug script, if your distribution supports hotplugging (all do). This typically means you have something in /etc/hotplug and that hotplugging is started when you boot your machine in a script named /etc/init.d/hotplug or similar. Activate hotplugging by running: %./hotplug.sh Hotplug will (typically) use the device map file installed by hotplug.sh at /etc/hotplug/usb/libmtp.usermap to lift the device to userspace for the current user by running the script /etc/hotplug/usb/libmtp.sh. If you have the program "resmgr" installed (currently used only by SuSE to our knowledge) that program will be used for enabling desktop user access, otherwise the current user of the desktop will be determined from files in /var/run. (See the script "libmtp.sh" for details.) Linux udev hotplugging ---------------------- Newer Linux distributions have dropped support for the old hotplug system and rely solely on udev, and rules stored below /etc/udev/rules.d to handle permissions and actions on device connections. It's quite solid but the whole thing is rather shaky when it comes to such things as custom devices handled solely by libusb, which is what libmtp and for example SANE backends use. The libmtp.rules file that comes with libmtp can be used as a starter. This will set the environment variables ID_MEDIA_PLAYER and ID_MTP_DEVICE to "1" and the former one will be recognized by the scripts distributed by recent versions of udev to be a console-writable device that should be accessible for all users. Ancient udev, HAL, libusb ------------------------- The old script for udev used to set the device access to "666" which is rather nasty (not that big security issue, unless you think someone will break into your jukebox) some systems used to let PAM do this by placing a configuration file in /etc/security/ somewhere. Then it was replaced with simple udev rules. At one point HAL was used to take devices detected by udev and signal to userspace that they were available and provide some information about them. This was unnecessary middleware, it has been killed and most userspace applications now get their information directly from udev instead. In old libusb first you need a crazy rule that creates a device node in the /dev/bus/usb hierarchy whenever any USB device is connected. The script has this at the top, you can comment it in if your distribution does not already create these device nodes. Then libusb may need to be patched to recognize this hierarchy. The 0.1.12 version is the first which is properly fixed. If you cannot run hotplugging ----------------------------- If you have a distro without hotplugging enabled try this as root: % chmod -R a+w /dev/bus/usb Or if it's *really* ancient you could try: % chmod -R a+w /proc/bus/usb You have to do this again every time you unplug/replug your USB cable or restart the jukebox, every time you quit libnjb and restart it, etc etc etc an alternative is to run libmtp as root which works just fine. The problem is to somehow assure that you (ie the current user) always has write access to these files. You can find the Linux hotplug project at: http://linux-hotplug.sourceforge.net/ Compilation for embedded devices -------------------------------- Problems with Autoconf complaining about a missing malloc() function during cross-compilation can be solved with this hack if you're using glibc: % export ac_cv_func_malloc_0_nonnull=yes % ./configure If you're using uclibc you may have to smack in a custom rpl_malloc() function in your program, see the Autoconf texinfo documentation. See further: http://wiki.buici.com/wiki/Autoconf_and_RPL_MALLOC Compilation for Solaris/SunOS ----------------------------- libmtp builds on Solaris/SunOS with either gcc or SunStudio 12. It does require GNU Make (aka gmake) to be installed. Building libmtp on Solaris 10 and Solaris 11 differ slightly, so alternate instructions are provided for each Solaris version. For Solaris 10 -------------- To build using GCC: % CFLAGS="I/usr/sfw/lib -L/usr/sfw/lib -R/usr/sfw/lib" MAKE=gmake \ INSTALL=/usr/ucb/install ./configure % gmake % gmake install Custom CLFAGS are required for libusb.so as it lives in /usr/sfw/lib, and this path is not in the default search path for ld. If these CFLAGS are not set, several components of ./configure will fail leading to a failed build. To build using SunStudio 12: % CFLAGS="I/usr/sfw/lib -L/usr/sfw/lib -R/usr/sfw/lib" MAKE=gmake \ INSTALL=/usr/ucb/install CC=cc ./configure % gmake % gmake install General Notes: All MTP devices on Solaris 10u2+ are driven by the usb_mid driver, which will automatically export ugen device interfaces with the correct device permissions. No special configuration is required. See the usb_mid(7D) and ugen(7D) manpages and /usr/sfw/share/doc/libusb/libusb.txt for more information. For Solaris 11 -------------- Building libmtp on Solaris 11 is very similar to those instructions for Solaris 10, however libusb now lives in /usr/lib, and openusb is also available as an alternative USB library. Oracle does not provide a libusb v1.0 API compatible version of libusb, instead providing the older v0.1 API interface version of libusb. As mentioned, Oracle also provides the OpenUSB USB library as an alternate to libusb v1.0, however OpenUSB is not source or binary compatible with libusb. Before building/installing libmtp there are some components missing from the base Solaris 11 installation, and are required to be installed prior to building/installing libmtp. The 'libusbugen' package must be installed before libusb itself is usable on Solaris 11, alternatively the 'openusb' package may be used. To build using GCC: % ./configure % gmake % sudo gmake install To build using SunStudio 12: % CC=cc ./configure % gmake % sudo gmake install General Notes: All MTP devices on Solaris 11+ are driven by the usb_mid driver, which will automatically export ugen device interfaces with the correct device permissions. No special configuration is required. See the usb_mid(7D) and ugen(7D) manpages and /usr/share/doc/libusb/libusb.txt for more information. libmtp-1.1.6-20-g1b9f164/AUTHORS0000664000175000017500000000313012205614637015757 0ustar glowwormglowwormlibmtp was invented by: Richard Low Linus Walleij We both came to do libmtp after working on the libnjb project, which was all about Creative Technology devices implementing the OASiS and PDE protocols. libmtp is however largely based on libptp2, which was created by Mariusz Woloszyn as part of gPhoto2 then derived into its own project. We later started to use libgphoto2 which is also based on the same code as libptp2 but with large contributions from Marcus Meissner . Marcus is also a contributor on libmtp from time to time and we're great friends. Other contributors to libmtp include: Andy Kelk Chris A. Debenham Daniel Williams Dave Kelly Matthew Wilcox Robert Reardon Orson Teodoro Ted Bullock Sean Kellogg Tero Saarni Jeff Mitchell Johannes Huber Alistair Boyle Chris Bagwell Joseph Nahmias Florent Mertens Alvin James Ravenscroft Thomas Schweitzer Nyall Dawson Nicolas VIVIEN Andrea Grillini Yavor Goulishev Jonas Salling Sajid Anwar libmtp-1.1.6-20-g1b9f164/src/0000775000175000017500000000000012205614637015501 5ustar glowwormglowwormlibmtp-1.1.6-20-g1b9f164/src/unicode.h0000664000175000017500000000301212205614637017274 0ustar glowwormglowworm/** * \file unicode.h * * This file contains general Unicode string manipulation functions. * It mainly consist of functions for converting between UCS-2 (used on * the devices) and UTF-8 (used by several applications). * * For a deeper understanding of Unicode encoding formats see the * Wikipedia entries for * UTF-16/UCS-2 * and UTF-8. * * Copyright (C) 2005-2007 Linus Walleij * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * */ #ifndef __MTP__UNICODE__H #define __MTP__UNICODE__H int ucs2_strlen(uint16_t const * const); char *utf16_to_utf8(LIBMTP_mtpdevice_t*,const uint16_t*); uint16_t *utf8_to_utf16(LIBMTP_mtpdevice_t*, const char*); void strip_7bit_from_utf8(char *str); #endif /* __MTP__UNICODE__H */ libmtp-1.1.6-20-g1b9f164/src/libopenusb1-glue.c0000664000175000017500000023752112205614637021034 0ustar glowwormglowworm/* * \file libusb1-glue.c * Low-level USB interface glue towards libusb. * * Copyright (C) 2005-2007 Richard A. Low * Copyright (C) 2005-2012 Linus Walleij * Copyright (C) 2006-2011 Marcus Meissner * Copyright (C) 2007 Ted Bullock * Copyright (C) 2008 Chris Bagwell * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Created by Richard Low on 24/12/2005. (as mtp-utils.c) * Modified by Linus Walleij 2006-03-06 * (Notice that Anglo-Saxons use little-endian dates and Swedes * use big-endian dates.) * */ #include "../config.h" #include "libmtp.h" #include "libusb-glue.h" #include "device-flags.h" #include "util.h" #include "ptp.h" #include #include #include #include #include #include #include "ptp-pack.c" /* Aha, older libusb does not have USB_CLASS_PTP */ #ifndef USB_CLASS_PTP #define USB_CLASS_PTP 6 #endif /* * Default USB timeout length. This can be overridden as needed * but should start with a reasonable value so most common * requests can be completed. The original value of 4000 was * not long enough for large file transfer. Also, players can * spend a bit of time collecting data. Higher values also * make connecting/disconnecting more reliable. */ #define USB_TIMEOUT_DEFAULT 20000 #define USB_TIMEOUT_LONG 60000 static inline int get_timeout(PTP_USB* ptp_usb) { if (FLAG_LONG_TIMEOUT(ptp_usb)) { return USB_TIMEOUT_LONG; } return USB_TIMEOUT_DEFAULT; } /* USB Feature selector HALT */ #ifndef USB_FEATURE_HALT #define USB_FEATURE_HALT 0x00 #endif /* Internal data types */ struct mtpdevice_list_struct { openusb_dev_handle_t device; PTPParams *params; PTP_USB *ptp_usb; uint32_t bus_location; struct mtpdevice_list_struct *next; }; typedef struct mtpdevice_list_struct mtpdevice_list_t; static const LIBMTP_device_entry_t mtp_device_table[] = { /* We include an .h file which is shared between us and libgphoto2 */ #include "music-players.h" }; static const int mtp_device_table_size = sizeof (mtp_device_table) / sizeof (LIBMTP_device_entry_t); // Local functions static void init_usb(); static void close_usb(PTP_USB* ptp_usb); static int find_interface_and_endpoints(openusb_dev_handle_t *dev, uint8_t *conf, uint8_t *interface, uint8_t *altsetting, int* inep, int* inep_maxpacket, int* outep, int* outep_maxpacket, int* intep); static void clear_stall(PTP_USB* ptp_usb); static int init_ptp_usb(PTPParams* params, PTP_USB* ptp_usb, openusb_dev_handle_t * dev); static short ptp_write_func(unsigned long, PTPDataHandler*, void *data, unsigned long*); static short ptp_read_func(unsigned long, PTPDataHandler*, void *data, unsigned long*, int); static int usb_get_endpoint_status(PTP_USB* ptp_usb, int ep, uint16_t* status); // Local USB handles. static openusb_handle_t libmtp_openusb_handle; /** * Get a list of the supported USB devices. * * The developers depend on users of this library to constantly * add in to the list of supported devices. What we need is the * device name, USB Vendor ID (VID) and USB Product ID (PID). * put this into a bug ticket at the project homepage, please. * The VID/PID is used to let e.g. udev lift the device to * console userspace access when it's plugged in. * * @param devices a pointer to a pointer that will hold a device * list after the call to this function, if it was * successful. * @param numdevs a pointer to an integer that will hold the number * of devices in the device list if the call was successful. * @return 0 if the list was successfull retrieved, any other * value means failure. */ int LIBMTP_Get_Supported_Devices_List(LIBMTP_device_entry_t * * const devices, int * const numdevs) { *devices = (LIBMTP_device_entry_t *) & mtp_device_table; *numdevs = mtp_device_table_size; return 0; } static void init_usb() { openusb_init(NULL, &libmtp_openusb_handle); } /** * Small recursive function to append a new usb_device to the linked list of * USB MTP devices * @param devlist dynamic linked list of pointers to usb devices with MTP * properties, to be extended with new device. * @param newdevice the new device to add. * @param bus_location bus for this device. * @return an extended array or NULL on failure. */ static mtpdevice_list_t *append_to_mtpdevice_list(mtpdevice_list_t *devlist, openusb_dev_handle_t *newdevice, uint32_t bus_location) { mtpdevice_list_t *new_list_entry; new_list_entry = (mtpdevice_list_t *) malloc(sizeof (mtpdevice_list_t)); if (new_list_entry == NULL) { return NULL; } // Fill in USB device, if we *HAVE* to make a copy of the device do it here. new_list_entry->device = *newdevice; new_list_entry->bus_location = bus_location; new_list_entry->next = NULL; if (devlist == NULL) { return new_list_entry; } else { mtpdevice_list_t *tmp = devlist; while (tmp->next != NULL) { tmp = tmp->next; } tmp->next = new_list_entry; } return devlist; } /** * Small recursive function to free dynamic memory allocated to the linked list * of USB MTP devices * @param devlist dynamic linked list of pointers to usb devices with MTP * properties. * @return nothing */ static void free_mtpdevice_list(mtpdevice_list_t *devlist) { mtpdevice_list_t *tmplist = devlist; if (devlist == NULL) return; while (tmplist != NULL) { mtpdevice_list_t *tmp = tmplist; tmplist = tmplist->next; // Do not free() the fields (ptp_usb, params)! These are used elsewhere. free(tmp); } return; } /** * This checks if a device has an MTP descriptor. The descriptor was * elaborated about in gPhoto bug 1482084, and some official documentation * with no strings attached was published by Microsoft at * http://www.microsoft.com/whdc/system/bus/USB/USBFAQ_intermed.mspx#E3HAC * * @param dev a device struct from libopenusb. * @param dumpfile set to non-NULL to make the descriptors dump out * to this file in human-readable hex so we can scruitinze them. * @return 1 if the device is MTP compliant, 0 if not. */ static int probe_device_descriptor(openusb_dev_handle_t *dev, FILE *dumpfile) { openusb_dev_handle_t *devh = NULL; unsigned char buf[1024], cmd; uint8_t *bufptr = (uint8_t *) &buf; unsigned int buffersize = sizeof(buf); int i; int ret; /* This is to indicate if we find some vendor interface */ int found_vendor_spec_interface = 0; struct usb_device_desc desc; struct usb_interface_desc ifcdesc; ret = openusb_parse_device_desc(libmtp_openusb_handle, *dev, NULL, 0, &desc); if (ret != OPENUSB_SUCCESS) return 0; /* * Don't examine devices that are not likely to * contain any MTP interface, update this the day * you find some weird combination... */ if (!(desc.bDeviceClass == USB_CLASS_PER_INTERFACE || desc.bDeviceClass == USB_CLASS_COMM || desc.bDeviceClass == USB_CLASS_PTP || desc.bDeviceClass == 0xEF || /* Intf. Association Desc.*/ desc.bDeviceClass == USB_CLASS_VENDOR_SPEC)) { return 0; } /* Attempt to open Device on this port */ ret = openusb_open_device(libmtp_openusb_handle, NULL, USB_INIT_DEFAULT, devh); if (ret != OPENUSB_SUCCESS) { /* Could not open this device */ return 0; } /* * This sometimes crashes on the j for loop below * I think it is because config is NULL yet * dev->descriptor.bNumConfigurations > 0 * this check should stop this */ /* * Loop over the device configurations and interfaces. Nokia MTP-capable * handsets (possibly others) typically have the string "MTP" in their * MTP interface descriptions, that's how they can be detected, before * we try the more esoteric "OS descriptors" (below). */ for (i = 0; i < desc.bNumConfigurations; i++) { uint8_t j; struct usb_config_desc config; ret = openusb_parse_config_desc(libmtp_openusb_handle, *dev, NULL, 0, 0, &config); if (ret != OPENUSB_SUCCESS) { LIBMTP_INFO("configdescriptor %d get failed with ret %d in probe_device_descriptor yet dev->descriptor.bNumConfigurations > 0\n", i, ret); continue; } for (j = 0; j < config.bNumInterfaces; j++) { int k = 0; while (openusb_parse_interface_desc(libmtp_openusb_handle, *dev, NULL, 0, 0, j, k++, &ifcdesc) == 0) { /* Current interface descriptor */ /* * MTP interfaces have three endpoints, two bulk and one * interrupt. Don't probe anything else. */ if (ifcdesc.bNumEndpoints != 3) continue; /* * We only want to probe for the OS descriptor if the * device is LIBUSB_CLASS_VENDOR_SPEC or one of the interfaces * in it is, so flag if we find an interface like this. */ if (ifcdesc.bInterfaceClass == USB_CLASS_VENDOR_SPEC) { found_vendor_spec_interface = 1; } /* * Check for Still Image Capture class with PIMA 15740 protocol, * also known as PTP */ /* * Next we search for the MTP substring in the interface name. * For example : "RIM MS/MTP" should work. */ buf[0] = '\0'; // FIXME: DK: Find out how to get the string descriptor for an interface? /* ret = libusb_get_string_descriptor_ascii(devh, config->interface[j].altsetting[k].iInterface, buf, 1024); */ if (ret < 3) continue; if (strstr((char *) buf, "MTP") != NULL) { if (dumpfile != NULL) { fprintf(dumpfile, "Configuration %d, interface %d, altsetting %d:\n", i, j, k); fprintf(dumpfile, " Interface description contains the string \"MTP\"\n"); fprintf(dumpfile, " Device recognized as MTP, no further probing.\n"); } //libusb_free_config_descriptor(config); openusb_close_device(*devh); return 1; } } } } /* * Only probe for OS descriptor if the device is vendor specific * or one of the interfaces found is. */ if (desc.bDeviceClass == USB_CLASS_VENDOR_SPEC || found_vendor_spec_interface) { /* Read the special descriptor */ //ret = libusb_get_descriptor(devh, 0x03, 0xee, buf, sizeof (buf)); ret = openusb_get_raw_desc(libmtp_openusb_handle, *dev, USB_DESC_TYPE_STRING, 0xee, 0, &bufptr, (unsigned short *)&buffersize); /* * If something failed we're probably stalled to we need * to clear the stall off the endpoint and say this is not * MTP. */ if (ret < 0) { /* EP0 is the default control endpoint */ //libusb_clear_halt (devh, 0); openusb_close_device(*devh); openusb_free_raw_desc(buf); return 0; } // Dump it, if requested if (dumpfile != NULL && ret > 0) { fprintf(dumpfile, "Microsoft device descriptor 0xee:\n"); data_dump_ascii(dumpfile, buf, ret, 16); } /* Check if descriptor length is at least 10 bytes */ if (ret < 10) { openusb_close_device(*devh); openusb_free_raw_desc(buf); return 0; } /* Check if this device has a Microsoft Descriptor */ if (!((buf[2] == 'M') && (buf[4] == 'S') && (buf[6] == 'F') && (buf[8] == 'T'))) { openusb_close_device(*devh); openusb_free_raw_desc(buf); return 0; } /* Check if device responds to control message 1 or if there is an error */ cmd = buf[16]; /* ret = libusb_control_transfer (devh, LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_DEVICE | LIBUSB_REQUEST_TYPE_VENDOR, cmd, 0, 4, buf, sizeof(buf), USB_TIMEOUT_DEFAULT); */ struct openusb_ctrl_request ctrl; ctrl.setup.bmRequestType = USB_ENDPOINT_IN | USB_RECIP_DEVICE | USB_REQ_TYPE_VENDOR; ctrl.setup.bRequest = cmd; ctrl.setup.wValue = 0; ctrl.setup.wIndex = 4; ctrl.payload = bufptr; // Out ctrl.length = sizeof (buf); ctrl.timeout = USB_TIMEOUT_DEFAULT; ctrl.next = NULL; ctrl.flags = 0; ret = openusb_ctrl_xfer(*devh, 0, USB_ENDPOINT_IN, &ctrl); // Dump it, if requested if (dumpfile != NULL && ctrl.result.transferred_bytes > 0) { fprintf(dumpfile, "Microsoft device response to control message 1, CMD 0x%02x:\n", cmd); data_dump_ascii(dumpfile, buf, ctrl.result.transferred_bytes, 16); } /* If this is true, the device either isn't MTP or there was an error */ if (ctrl.result.transferred_bytes <= 0x15) { /* TODO: If there was an error, flag it and let the user know somehow */ /* if(ret == -1) {} */ openusb_close_device(*devh); return 0; } /* Check if device is MTP or if it is something like a USB Mass Storage device with Janus DRM support */ if ((buf[0x12] != 'M') || (buf[0x13] != 'T') || (buf[0x14] != 'P')) { openusb_close_device(*devh); return 0; } /* After this point we are probably dealing with an MTP device */ /* * Check if device responds to control message 2, which is * the extended device parameters. Most devices will just * respond with a copy of the same message as for the first * message, some respond with zero-length (which is OK) * and some with pure garbage. We're not parsing the result * so this is not very important. */ /* ret = libusb_control_transfer (devh, LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_DEVICE | LIBUSB_REQUEST_TYPE_VENDOR, cmd, 0, 5, buf, sizeof(buf), USB_TIMEOUT_DEFAULT); */ //struct openusb_ctrl_request ctrl; ctrl.setup.bmRequestType = USB_ENDPOINT_IN | USB_RECIP_DEVICE | USB_REQ_TYPE_VENDOR; ctrl.setup.bRequest = cmd; ctrl.setup.wValue = 0; ctrl.setup.wIndex = 5; ctrl.payload = bufptr; // Out ctrl.length = sizeof (buf); ctrl.timeout = USB_TIMEOUT_DEFAULT; ctrl.next = NULL; ctrl.flags = 0; ret = openusb_ctrl_xfer(*devh, 0, USB_ENDPOINT_IN, &ctrl); // Dump it, if requested if (dumpfile != NULL && ctrl.result.transferred_bytes > 0) { fprintf(dumpfile, "Microsoft device response to control message 2, CMD 0x%02x:\n", cmd); data_dump_ascii(dumpfile, buf, ret, 16); } /* If this is true, the device errored against control message 2 */ if (ctrl.result.transferred_bytes < 0) { /* TODO: Implement callback function to let managing program know there was a problem, along with description of the problem */ LIBMTP_ERROR("Potential MTP Device with VendorID:%04x and " "ProductID:%04x encountered an error responding to " "control message 2.\n" "Problems may arrise but continuing\n", desc.idVendor, desc.idProduct); } else if (dumpfile != NULL && ctrl.result.transferred_bytes == 0) { fprintf(dumpfile, "Zero-length response to control message 2 (OK)\n"); } else if (dumpfile != NULL) { fprintf(dumpfile, "Device responds to control message 2 with some data.\n"); } /* Close the USB device handle */ openusb_close_device(*devh); return 1; } /* Close the USB device handle */ openusb_close_device(*devh); return 0; } /** * This function scans through the connected usb devices on a machine and * if they match known Vendor and Product identifiers appends them to the * dynamic array mtp_device_list. Be sure to call * free_mtpdevice_list(mtp_device_list) when you are done * with it, assuming it is not NULL. * @param mtp_device_list dynamic array of pointers to usb devices with MTP * properties (if this list is not empty, new entries will be appended * to the list). * @return LIBMTP_ERROR_NONE implies that devices have been found, scan the list * appropriately. LIBMTP_ERROR_NO_DEVICE_ATTACHED implies that no * devices have been found. */ static LIBMTP_error_number_t get_mtp_usb_device_list(mtpdevice_list_t ** mtp_device_list) { int nrofdevs = 0; openusb_devid_t *devs = NULL; struct usb_device_desc desc; int ret, i; init_usb(); ret = openusb_get_devids_by_bus(libmtp_openusb_handle, 0, &devs, &nrofdevs); for (i = 0; i < nrofdevs; i++) { openusb_devid_t dev = devs[i]; ret = openusb_parse_device_desc(libmtp_openusb_handle, dev, NULL, 0, &desc); if (ret != OPENUSB_SUCCESS) continue; if (desc.bDeviceClass != USB_CLASS_HUB) { int i; int found = 0; // First check if we know about the device already. // Devices well known to us will not have their descriptors // probed, it caused problems with some devices. for (i = 0; i < mtp_device_table_size; i++) { if (desc.idVendor == mtp_device_table[i].vendor_id && desc.idProduct == mtp_device_table[i].product_id) { /* Append this usb device to the MTP device list */ *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list, &dev, 0); found = 1; break; } } // If we didn't know it, try probing the "OS Descriptor". //if (!found) { // if (probe_device_descriptor(&dev, NULL)) { /* Append this usb device to the MTP USB Device List */ // *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list, &dev, 0); // } /* * By thomas_-_s: Also append devices that are no MTP but PTP devices * if this is commented out. */ /* else { // Check whether the device is no USB hub but a PTP. if ( dev->config != NULL &&dev->config->interface->altsetting->bInterfaceClass == LIBUSB_CLASS_PTP && dev->descriptor.bDeviceClass != LIBUSB_CLASS_HUB ) { *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list, dev, bus->location); } } */ //} } } /* If nothing was found we end up here. */ if (*mtp_device_list == NULL) { return LIBMTP_ERROR_NO_DEVICE_ATTACHED; } return LIBMTP_ERROR_NONE; } /** * Checks if a specific device with a certain bus and device * number has an MTP type device descriptor. * * @param busno the bus number of the device to check * @param deviceno the device number of the device to check * @return 1 if the device is MTP else 0 */ int LIBMTP_Check_Specific_Device(int busno, int devno) { unsigned int nrofdevs; openusb_devid_t **devs = NULL; int i; init_usb(); openusb_get_devids_by_bus(libmtp_openusb_handle, 0, devs, &nrofdevs); for (i = 0; i < nrofdevs; i++) { /* if (bus->location != busno) continue; if (dev->devnum != devno) continue; */ if (probe_device_descriptor(devs[i], NULL)) return 1; } return 0; } /** * Detect the raw MTP device descriptors and return a list of * of the devices found. * * @param devices a pointer to a variable that will hold * the list of raw devices found. This may be NULL * on return if the number of detected devices is zero. * The user shall simply free() this * variable when finished with the raw devices, * in order to release memory. * @param numdevs a pointer to an integer that will hold * the number of devices in the list. This may * be 0. * @return 0 if successful, any other value means failure. */ LIBMTP_error_number_t LIBMTP_Detect_Raw_Devices(LIBMTP_raw_device_t ** devices, int * numdevs) { mtpdevice_list_t *devlist = NULL; mtpdevice_list_t *dev; LIBMTP_error_number_t ret; LIBMTP_raw_device_t *retdevs; int devs = 0; int i, j; ret = get_mtp_usb_device_list(&devlist); if (ret == LIBMTP_ERROR_NO_DEVICE_ATTACHED) { *devices = NULL; *numdevs = 0; return ret; } else if (ret != LIBMTP_ERROR_NONE) { LIBMTP_ERROR("LIBMTP PANIC: get_mtp_usb_device_list() " "error code: %d on line %d\n", ret, __LINE__); return ret; } // Get list size dev = devlist; while (dev != NULL) { devs++; dev = dev->next; } if (devs == 0) { *devices = NULL; *numdevs = 0; return LIBMTP_ERROR_NONE; } // Conjure a device list retdevs = (LIBMTP_raw_device_t *) malloc(sizeof (LIBMTP_raw_device_t) * devs); if (retdevs == NULL) { // Out of memory *devices = NULL; *numdevs = 0; return LIBMTP_ERROR_MEMORY_ALLOCATION; } dev = devlist; i = 0; while (dev != NULL) { int device_known = 0; struct usb_device_desc desc; openusb_parse_device_desc(libmtp_openusb_handle, dev->device, NULL, 0, &desc); // Assign default device info retdevs[i].device_entry.vendor = NULL; retdevs[i].device_entry.vendor_id = desc.idVendor; retdevs[i].device_entry.product = NULL; retdevs[i].device_entry.product_id = desc.idProduct; retdevs[i].device_entry.device_flags = 0x00000000U; // See if we can locate some additional vendor info and device flags for (j = 0; j < mtp_device_table_size; j++) { if (desc.idVendor == mtp_device_table[j].vendor_id && desc.idProduct == mtp_device_table[j].product_id) { device_known = 1; retdevs[i].device_entry.vendor = mtp_device_table[j].vendor; retdevs[i].device_entry.product = mtp_device_table[j].product; retdevs[i].device_entry.device_flags = mtp_device_table[j].device_flags; // This device is known to the developers LIBMTP_ERROR("Device %d (VID=%04x and PID=%04x) is a %s %s.\n", i, desc.idVendor, desc.idProduct, mtp_device_table[j].vendor, mtp_device_table[j].product); break; } } if (!device_known) { // This device is unknown to the developers LIBMTP_ERROR("Device %d (VID=%04x and PID=%04x) is UNKNOWN.\n", i, desc.idVendor, desc.idProduct); LIBMTP_ERROR("Please report this VID/PID and the device model to the libmtp development team\n"); /* * Trying to get iManufacturer or iProduct from the device at this * point would require opening a device handle, that we don't want * to do right now. (Takes time for no good enough reason.) */ } // Save the location on the bus retdevs[i].bus_location = 0; retdevs[i].devnum = openusb_get_devid(libmtp_openusb_handle, &dev->device); i++; dev = dev->next; } *devices = retdevs; *numdevs = i; free_mtpdevice_list(devlist); return LIBMTP_ERROR_NONE; } /** * This routine just dumps out low-level * USB information about the current device. * @param ptp_usb the USB device to get information from. */ void dump_usbinfo(PTP_USB *ptp_usb) { struct usb_device_desc desc; openusb_parse_device_desc(libmtp_openusb_handle, *ptp_usb->handle, NULL, 0, &desc); LIBMTP_INFO(" bcdUSB: %d\n", desc.bcdUSB); LIBMTP_INFO(" bDeviceClass: %d\n", desc.bDeviceClass); LIBMTP_INFO(" bDeviceSubClass: %d\n", desc.bDeviceSubClass); LIBMTP_INFO(" bDeviceProtocol: %d\n", desc.bDeviceProtocol); LIBMTP_INFO(" idVendor: %04x\n", desc.idVendor); LIBMTP_INFO(" idProduct: %04x\n", desc.idProduct); LIBMTP_INFO(" IN endpoint maxpacket: %d bytes\n", ptp_usb->inep_maxpacket); LIBMTP_INFO(" OUT endpoint maxpacket: %d bytes\n", ptp_usb->outep_maxpacket); LIBMTP_INFO(" Raw device info:\n"); LIBMTP_INFO(" Bus location: %d\n", ptp_usb->rawdevice.bus_location); LIBMTP_INFO(" Device number: %d\n", ptp_usb->rawdevice.devnum); LIBMTP_INFO(" Device entry info:\n"); LIBMTP_INFO(" Vendor: %s\n", ptp_usb->rawdevice.device_entry.vendor); LIBMTP_INFO(" Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.vendor_id); LIBMTP_INFO(" Product: %s\n", ptp_usb->rawdevice.device_entry.product); LIBMTP_INFO(" Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.product_id); LIBMTP_INFO(" Device flags: 0x%08x\n", ptp_usb->rawdevice.device_entry.device_flags); // TODO: (void) probe_device_descriptor(dev, stdout); } /** * Retrieve the apropriate playlist extension for this * device. Rather hacky at the moment. This is probably * desired by the managing software, but when creating * lists on the device itself you notice certain preferences. * @param ptp_usb the USB device to get suggestion for. * @return the suggested playlist extension. */ const char *get_playlist_extension(PTP_USB *ptp_usb) { static char creative_pl_extension[] = ".zpl"; static char default_pl_extension[] = ".pla"; struct usb_device_desc desc; openusb_parse_device_desc(libmtp_openusb_handle, *ptp_usb->handle, NULL, 0, &desc); if (desc.idVendor == 0x041e) return creative_pl_extension; return default_pl_extension; } static void libusb_glue_debug(PTPParams *params, const char *format, ...) { va_list args; va_start(args, format); if (params->debug_func != NULL) params->debug_func(params->data, format, args); else { vfprintf(stderr, format, args); fprintf(stderr, "\n"); fflush(stderr); } va_end(args); } static void libusb_glue_error(PTPParams *params, const char *format, ...) { va_list args; va_start(args, format); if (params->error_func != NULL) params->error_func(params->data, format, args); else { vfprintf(stderr, format, args); fprintf(stderr, "\n"); fflush(stderr); } va_end(args); } /* * ptp_read_func() and ptp_write_func() are * based on same functions usb.c in libgphoto2. * Much reading packet logs and having fun with trials and errors * reveals that WMP / Windows is probably using an algorithm like this * for large transfers: * * 1. Send the command (0x0c bytes) if headers are split, else, send * command plus sizeof(endpoint) - 0x0c bytes. * 2. Send first packet, max size to be sizeof(endpoint) but only when using * split headers. Else goto 3. * 3. REPEAT send 0x10000 byte chunks UNTIL remaining bytes < 0x10000 * We call 0x10000 CONTEXT_BLOCK_SIZE. * 4. Send remaining bytes MOD sizeof(endpoint) * 5. Send remaining bytes. If this happens to be exactly sizeof(endpoint) * then also send a zero-length package. * * Further there is some special quirks to handle zero reads from the * device, since some devices can't do them at all due to shortcomings * of the USB slave controller in the device. */ #define CONTEXT_BLOCK_SIZE_1 0x3e00 #define CONTEXT_BLOCK_SIZE_2 0x200 #define CONTEXT_BLOCK_SIZE CONTEXT_BLOCK_SIZE_1+CONTEXT_BLOCK_SIZE_2 static short ptp_read_func( unsigned long size, PTPDataHandler *handler, void *data, unsigned long *readbytes, int readzero ) { PTP_USB *ptp_usb = (PTP_USB *) data; unsigned long toread = 0; int ret = 0; int xread; unsigned long curread = 0; unsigned long written; unsigned char *bytes; int expect_terminator_byte = 0; struct openusb_bulk_request bulk; // This is the largest block we'll need to read in. bytes = malloc(CONTEXT_BLOCK_SIZE); while (curread < size) { LIBMTP_USB_DEBUG("Remaining size to read: 0x%04lx bytes\n", size - curread); // check equal to condition here if (size - curread < CONTEXT_BLOCK_SIZE) { // this is the last packet toread = size - curread; // this is equivalent to zero read for these devices if (readzero && FLAG_NO_ZERO_READS(ptp_usb) && toread % 64 == 0) { toread += 1; expect_terminator_byte = 1; } } else if (curread == 0) // we are first packet, but not last packet toread = CONTEXT_BLOCK_SIZE_1; else if (toread == CONTEXT_BLOCK_SIZE_1) toread = CONTEXT_BLOCK_SIZE_2; else if (toread == CONTEXT_BLOCK_SIZE_2) toread = CONTEXT_BLOCK_SIZE_1; else LIBMTP_INFO("unexpected toread size 0x%04x, 0x%04x remaining bytes\n", (unsigned int) toread, (unsigned int) (size - curread)); LIBMTP_USB_DEBUG("Reading in 0x%04lx bytes\n", toread); /* ret = USB_BULK_READ(ptp_usb->handle, ptp_usb->inep, bytes, toread, &xread, ptp_usb->timeout); */ bulk.payload = bytes; bulk.length = toread; bulk.timeout = ptp_usb->timeout; bulk.flags = 0; bulk.next = NULL; ret = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->inep, &bulk); xread = bulk.result.transferred_bytes; LIBMTP_USB_DEBUG("Result of read: 0x%04x (%d bytes)\n", ret, xread); if (ret != OPENUSB_SUCCESS) return PTP_ERROR_IO; LIBMTP_USB_DEBUG("<==USB IN\n"); if (xread == 0) LIBMTP_USB_DEBUG("Zero Read\n"); else LIBMTP_USB_DATA(bytes, xread, 16); // want to discard extra byte if (expect_terminator_byte && xread == toread) { LIBMTP_USB_DEBUG("<==USB IN\nDiscarding extra byte\n"); xread--; } int putfunc_ret = handler->putfunc(NULL, handler->priv, xread, bytes, &written); LIBMTP_USB_DEBUG("handler->putfunc ret = 0x%x\n", putfunc_ret); if (putfunc_ret != PTP_RC_OK) return putfunc_ret; ptp_usb->current_transfer_complete += xread; curread += xread; // Increase counters, call callback if (ptp_usb->callback_active) { if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) { // send last update and disable callback. ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total; ptp_usb->callback_active = 0; } if (ptp_usb->current_transfer_callback != NULL) { int ret; ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete, ptp_usb->current_transfer_total, ptp_usb->current_transfer_callback_data); if (ret != 0) { return PTP_ERROR_CANCEL; } } } if (xread < toread) /* short reads are common */ break; } if (readbytes) *readbytes = curread; free(bytes); LIBMTP_USB_DEBUG("Pointer Updated\n"); // there might be a zero packet waiting for us... if (readzero && !FLAG_NO_ZERO_READS(ptp_usb) && curread % ptp_usb->outep_maxpacket == 0) { unsigned char temp; int zeroresult = 0, xread; LIBMTP_USB_DEBUG("<==USB IN\n"); LIBMTP_USB_DEBUG("Zero Read\n"); /* zeroresult = USB_BULK_READ(ptp_usb->handle, ptp_usb->inep, &temp, 0, &xread, ptp_usb->timeout); */ bulk.payload = &temp; bulk.length = 0; bulk.timeout = ptp_usb->timeout; bulk.flags = 0; bulk.next = NULL; ret = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->inep, &bulk); xread = bulk.result.transferred_bytes; if (zeroresult != OPENUSB_SUCCESS) LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult); } return PTP_RC_OK; } static short ptp_write_func( unsigned long size, PTPDataHandler *handler, void *data, unsigned long *written ) { PTP_USB *ptp_usb = (PTP_USB *) data; unsigned long towrite = 0; int ret = 0; unsigned long curwrite = 0; unsigned char *bytes; struct openusb_bulk_request bulk; // This is the largest block we'll need to read in. bytes = malloc(CONTEXT_BLOCK_SIZE); if (!bytes) { return PTP_ERROR_IO; } while (curwrite < size) { unsigned long usbwritten = 0; int xwritten; towrite = size - curwrite; if (towrite > CONTEXT_BLOCK_SIZE) { towrite = CONTEXT_BLOCK_SIZE; } else { // This magic makes packets the same size that WMP send them. if (towrite > ptp_usb->outep_maxpacket && towrite % ptp_usb->outep_maxpacket != 0) { towrite -= towrite % ptp_usb->outep_maxpacket; } } int getfunc_ret = handler->getfunc(NULL, handler->priv, towrite, bytes, &towrite); if (getfunc_ret != PTP_RC_OK) return getfunc_ret; while (usbwritten < towrite) { /* ret = USB_BULK_WRITE(ptp_usb->handle, ptp_usb->outep, bytes + usbwritten, towrite - usbwritten, &xwritten, ptp_usb->timeout); */ bulk.payload = bytes + usbwritten; bulk.length = towrite - usbwritten; bulk.timeout = ptp_usb->timeout; bulk.flags = 0; bulk.next = NULL; ret = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->outep, &bulk); xwritten = bulk.result.transferred_bytes; LIBMTP_USB_DEBUG("USB OUT==>\n"); if (ret != OPENUSB_SUCCESS) { return PTP_ERROR_IO; } LIBMTP_USB_DATA(bytes + usbwritten, xwritten, 16); // check for result == 0 perhaps too. // Increase counters ptp_usb->current_transfer_complete += xwritten; curwrite += xwritten; usbwritten += xwritten; } // call callback if (ptp_usb->callback_active) { if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) { // send last update and disable callback. ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total; ptp_usb->callback_active = 0; } if (ptp_usb->current_transfer_callback != NULL) { int ret; ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete, ptp_usb->current_transfer_total, ptp_usb->current_transfer_callback_data); if (ret != 0) { return PTP_ERROR_CANCEL; } } } if (xwritten < towrite) /* short writes happen */ break; } free(bytes); if (written) { *written = curwrite; } // If this is the last transfer send a zero write if required if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) { if ((towrite % ptp_usb->outep_maxpacket) == 0) { int xwritten; LIBMTP_USB_DEBUG("USB OUT==>\n"); LIBMTP_USB_DEBUG("Zero Write\n"); /* ret = USB_BULK_WRITE(ptp_usb->handle, ptp_usb->outep, (unsigned char *) "x", 0, &xwritten, ptp_usb->timeout); */ bulk.payload = (unsigned char *) "x"; bulk.length = 0; bulk.timeout = ptp_usb->timeout; bulk.flags = 0; bulk.next = NULL; ret = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->outep, &bulk); xwritten = bulk.result.transferred_bytes; } } if (ret != OPENUSB_SUCCESS) return PTP_ERROR_IO; return PTP_RC_OK; } /* memory data get/put handler */ typedef struct { unsigned char *data; unsigned long size, curoff; } PTPMemHandlerPrivate; static uint16_t memory_getfunc(PTPParams* params, void* private, unsigned long wantlen, unsigned char *data, unsigned long *gotlen ) { PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*) private; unsigned long tocopy = wantlen; if (priv->curoff + tocopy > priv->size) tocopy = priv->size - priv->curoff; memcpy(data, priv->data + priv->curoff, tocopy); priv->curoff += tocopy; *gotlen = tocopy; return PTP_RC_OK; } static uint16_t memory_putfunc(PTPParams* params, void* private, unsigned long sendlen, unsigned char *data, unsigned long *putlen ) { PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*) private; if (priv->curoff + sendlen > priv->size) { priv->data = realloc(priv->data, priv->curoff + sendlen); priv->size = priv->curoff + sendlen; } memcpy(priv->data + priv->curoff, data, sendlen); priv->curoff += sendlen; *putlen = sendlen; return PTP_RC_OK; } /* init private struct for receiving data. */ static uint16_t ptp_init_recv_memory_handler(PTPDataHandler *handler) { PTPMemHandlerPrivate* priv; priv = malloc(sizeof (PTPMemHandlerPrivate)); handler->priv = priv; handler->getfunc = memory_getfunc; handler->putfunc = memory_putfunc; priv->data = NULL; priv->size = 0; priv->curoff = 0; return PTP_RC_OK; } /* init private struct and put data in for sending data. * data is still owned by caller. */ static uint16_t ptp_init_send_memory_handler(PTPDataHandler *handler, unsigned char *data, unsigned long len ) { PTPMemHandlerPrivate* priv; priv = malloc(sizeof (PTPMemHandlerPrivate)); if (!priv){ return PTP_RC_GeneralError; } handler->priv = priv; handler->getfunc = memory_getfunc; handler->putfunc = memory_putfunc; priv->data = data; priv->size = len; priv->curoff = 0; return PTP_RC_OK; } /* free private struct + data */ static uint16_t ptp_exit_send_memory_handler(PTPDataHandler *handler) { PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*) handler->priv; /* data is owned by caller */ free(priv); return PTP_RC_OK; } /* hand over our internal data to caller */ static uint16_t ptp_exit_recv_memory_handler(PTPDataHandler *handler, unsigned char **data, unsigned long *size ) { PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*) handler->priv; *data = priv->data; *size = priv->size; free(priv); return PTP_RC_OK; } /* send / receive functions */ uint16_t ptp_usb_sendreq(PTPParams* params, PTPContainer* req) { uint16_t ret; PTPUSBBulkContainer usbreq; PTPDataHandler memhandler; unsigned long written = 0; unsigned long towrite; char txt[256]; (void) ptp_render_opcode(params, req->Code, sizeof (txt), txt); LIBMTP_USB_DEBUG("REQUEST: 0x%04x, %s\n", req->Code, txt); /* build appropriate USB container */ usbreq.length = htod32(PTP_USB_BULK_REQ_LEN - (sizeof (uint32_t)*(5 - req->Nparam))); usbreq.type = htod16(PTP_USB_CONTAINER_COMMAND); usbreq.code = htod16(req->Code); usbreq.trans_id = htod32(req->Transaction_ID); usbreq.payload.params.param1 = htod32(req->Param1); usbreq.payload.params.param2 = htod32(req->Param2); usbreq.payload.params.param3 = htod32(req->Param3); usbreq.payload.params.param4 = htod32(req->Param4); usbreq.payload.params.param5 = htod32(req->Param5); /* send it to responder */ towrite = PTP_USB_BULK_REQ_LEN - (sizeof (uint32_t)*(5 - req->Nparam)); ptp_init_send_memory_handler(&memhandler, (unsigned char*) &usbreq, towrite); ret = ptp_write_func( towrite, &memhandler, params->data, &written ); ptp_exit_send_memory_handler(&memhandler); if (ret != PTP_RC_OK && ret != PTP_ERROR_CANCEL) { ret = PTP_ERROR_IO; } if (written != towrite && ret != PTP_ERROR_CANCEL && ret != PTP_ERROR_IO) { libusb_glue_error(params, "PTP: request code 0x%04x sending req wrote only %ld bytes instead of %d", req->Code, written, towrite ); ret = PTP_ERROR_IO; } return ret; } uint16_t ptp_usb_senddata(PTPParams* params, PTPContainer* ptp, uint64_t size, PTPDataHandler *handler ) { uint16_t ret; int wlen, datawlen; unsigned long written; PTPUSBBulkContainer usbdata; uint64_t bytes_left_to_transfer; PTPDataHandler memhandler; LIBMTP_USB_DEBUG("SEND DATA PHASE\n"); /* build appropriate USB container */ usbdata.length = htod32(PTP_USB_BULK_HDR_LEN + size); usbdata.type = htod16(PTP_USB_CONTAINER_DATA); usbdata.code = htod16(ptp->Code); usbdata.trans_id = htod32(ptp->Transaction_ID); ((PTP_USB*) params->data)->current_transfer_complete = 0; ((PTP_USB*) params->data)->current_transfer_total = size + PTP_USB_BULK_HDR_LEN; if (params->split_header_data) { datawlen = 0; wlen = PTP_USB_BULK_HDR_LEN; } else { unsigned long gotlen; /* For all camera devices. */ datawlen = (size < PTP_USB_BULK_PAYLOAD_LEN_WRITE) ? size : PTP_USB_BULK_PAYLOAD_LEN_WRITE; wlen = PTP_USB_BULK_HDR_LEN + datawlen; ret = handler->getfunc(params, handler->priv, datawlen, usbdata.payload.data, &gotlen); if (ret != PTP_RC_OK){ return ret; } if (gotlen != datawlen){ return PTP_RC_GeneralError; } } ptp_init_send_memory_handler(&memhandler, (unsigned char *) &usbdata, wlen); /* send first part of data */ ret = ptp_write_func(wlen, &memhandler, params->data, &written); ptp_exit_send_memory_handler(&memhandler); if (ret != PTP_RC_OK) { return ret; } if (size <= datawlen) return ret; /* if everything OK send the rest */ bytes_left_to_transfer = size - datawlen; ret = PTP_RC_OK; while (bytes_left_to_transfer > 0) { ret = ptp_write_func(bytes_left_to_transfer, handler, params->data, &written); if (ret != PTP_RC_OK){ break; } if (written == 0) { ret = PTP_ERROR_IO; break; } bytes_left_to_transfer -= written; } if (ret != PTP_RC_OK && ret != PTP_ERROR_CANCEL) ret = PTP_ERROR_IO; return ret; } static uint16_t ptp_usb_getpacket(PTPParams *params, PTPUSBBulkContainer *packet, unsigned long *rlen) { PTPDataHandler memhandler; uint16_t ret; unsigned char *x = NULL; /* read the header and potentially the first data */ if (params->response_packet_size > 0) { /* If there is a buffered packet, just use it. */ memcpy(packet, params->response_packet, params->response_packet_size); *rlen = params->response_packet_size; free(params->response_packet); params->response_packet = NULL; params->response_packet_size = 0; /* Here this signifies a "virtual read" */ return PTP_RC_OK; } ptp_init_recv_memory_handler(&memhandler); ret = ptp_read_func(PTP_USB_BULK_HS_MAX_PACKET_LEN_READ, &memhandler, params->data, rlen, 0); ptp_exit_recv_memory_handler(&memhandler, &x, rlen); if (x) { memcpy(packet, x, *rlen); free(x); } return ret; } uint16_t ptp_usb_getdata(PTPParams* params, PTPContainer* ptp, PTPDataHandler *handler) { uint16_t ret; PTPUSBBulkContainer usbdata; unsigned long written; PTP_USB *ptp_usb = (PTP_USB *) params->data; int putfunc_ret; LIBMTP_USB_DEBUG("GET DATA PHASE\n"); struct openusb_bulk_request bulk; memset(&usbdata, 0, sizeof (usbdata)); do { unsigned long len, rlen; ret = ptp_usb_getpacket(params, &usbdata, &rlen); if (ret != PTP_RC_OK) { ret = PTP_ERROR_IO; break; } if (dtoh16(usbdata.type) != PTP_USB_CONTAINER_DATA) { ret = PTP_ERROR_DATA_EXPECTED; break; } if (dtoh16(usbdata.code) != ptp->Code) { if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) { libusb_glue_debug(params, "ptp2/ptp_usb_getdata: detected a broken " "PTP header, code field insane, expect problems! (But continuing)"); // Repair the header, so it won't wreak more havoc, don't just ignore it. // Typically these two fields will be broken. usbdata.code = htod16(ptp->Code); usbdata.trans_id = htod32(ptp->Transaction_ID); ret = PTP_RC_OK; } else { ret = dtoh16(usbdata.code); // This filters entirely insane garbage return codes, but still // makes it possible to return error codes in the code field when // getting data. It appears Windows ignores the contents of this // field entirely. if (ret < PTP_RC_Undefined || ret > PTP_RC_SpecificationOfDestinationUnsupported) { libusb_glue_debug(params, "ptp2/ptp_usb_getdata: detected a broken " "PTP header, code field insane."); ret = PTP_ERROR_IO; } break; } } if (rlen == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ) { /* Copy first part of data to 'data' */ putfunc_ret = handler->putfunc( params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN, usbdata.payload.data, &written ); if (putfunc_ret != PTP_RC_OK) return putfunc_ret; /* stuff data directly to passed data handler */ while (1) { unsigned long readdata; uint16_t xret; xret = ptp_read_func( 0x20000000, handler, params->data, &readdata, 0 ); if (xret != PTP_RC_OK) return xret; if (readdata < 0x20000000) break; } return PTP_RC_OK; } if (rlen > dtoh32(usbdata.length)) { /* * Buffer the surplus response packet if it is >= * PTP_USB_BULK_HDR_LEN * (i.e. it is probably an entire package) * else discard it as erroneous surplus data. * This will even work if more than 2 packets appear * in the same transaction, they will just be handled * iteratively. * * Marcus observed stray bytes on iRiver devices; * these are still discarded. */ unsigned int packlen = dtoh32(usbdata.length); unsigned int surplen = rlen - packlen; if (surplen >= PTP_USB_BULK_HDR_LEN) { params->response_packet = malloc(surplen); memcpy(params->response_packet, (uint8_t *) & usbdata + packlen, surplen); params->response_packet_size = surplen; /* Ignore reading one extra byte if device flags have been set */ } else if (!FLAG_NO_ZERO_READS(ptp_usb) && (rlen - dtoh32(usbdata.length) == 1)) { libusb_glue_debug(params, "ptp2/ptp_usb_getdata: read %d bytes " "too much, expect problems!", rlen - dtoh32(usbdata.length)); } rlen = packlen; } /* For most PTP devices rlen is 512 == sizeof(usbdata) * here. For MTP devices splitting header and data it might * be 12. */ /* Evaluate full data length. */ len = dtoh32(usbdata.length) - PTP_USB_BULK_HDR_LEN; /* autodetect split header/data MTP devices */ if (dtoh32(usbdata.length) > 12 && (rlen == 12)) params->split_header_data = 1; /* Copy first part of data to 'data' */ putfunc_ret = handler->putfunc( params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN, usbdata.payload.data, &written ); if (putfunc_ret != PTP_RC_OK) return putfunc_ret; if (FLAG_NO_ZERO_READS(ptp_usb) && len + PTP_USB_BULK_HDR_LEN == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ) { LIBMTP_USB_DEBUG("Reading in extra terminating byte\n"); // need to read in extra byte and discard it int result = 0, xread; unsigned char byte = 0; /* result = USB_BULK_READ(ptp_usb->handle, ptp_usb->inep, &byte, 1, &xread, ptp_usb->timeout); */ bulk.payload = &byte; bulk.length = 1; bulk.timeout = ptp_usb->timeout; bulk.flags = 0; bulk.next = NULL; result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->inep, &bulk); xread = bulk.result.transferred_bytes; if (result != 1) 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); } else if (len + PTP_USB_BULK_HDR_LEN == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ && params->split_header_data == 0) { int zeroresult = 0, xread; unsigned char zerobyte = 0; LIBMTP_INFO("Reading in zero packet after header\n"); /* zeroresult = USB_BULK_READ(ptp_usb->handle, ptp_usb->inep, &zerobyte, 0, &xread, ptp_usb->timeout); */ bulk.payload = &zerobyte; bulk.length = 0; bulk.timeout = ptp_usb->timeout; bulk.flags = 0; bulk.next = NULL; zeroresult = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->inep, &bulk); xread = bulk.result.transferred_bytes; if (zeroresult != 0) LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult); } /* Is that all of data? */ if (len + PTP_USB_BULK_HDR_LEN <= rlen) { break; } ret = ptp_read_func(len - (rlen - PTP_USB_BULK_HDR_LEN), handler, params->data, &rlen, 1); if (ret != PTP_RC_OK) { break; } } while (0); return ret; } uint16_t ptp_usb_getresp(PTPParams* params, PTPContainer* resp) { uint16_t ret; unsigned long rlen; PTPUSBBulkContainer usbresp; PTP_USB *ptp_usb = (PTP_USB *) (params->data); LIBMTP_USB_DEBUG("RESPONSE: "); memset(&usbresp, 0, sizeof (usbresp)); /* read response, it should never be longer than sizeof(usbresp) */ ret = ptp_usb_getpacket(params, &usbresp, &rlen); // Fix for bevahiour reported by Scott Snyder on Samsung YP-U3. The player // sends a packet containing just zeroes of length 2 (up to 4 has been seen too) // after a NULL packet when it should send the response. This code ignores // such illegal packets. while (ret == PTP_RC_OK && rlen < PTP_USB_BULK_HDR_LEN && usbresp.length == 0) { libusb_glue_debug(params, "ptp_usb_getresp: detected short response " "of %d bytes, expect problems! (re-reading " "response), rlen"); ret = ptp_usb_getpacket(params, &usbresp, &rlen); } if (ret != PTP_RC_OK) { ret = PTP_ERROR_IO; } else if (dtoh16(usbresp.type) != PTP_USB_CONTAINER_RESPONSE) { ret = PTP_ERROR_RESP_EXPECTED; } else if (dtoh16(usbresp.code) != resp->Code) { ret = dtoh16(usbresp.code); } LIBMTP_USB_DEBUG("%04x\n", ret); if (ret != PTP_RC_OK) { /* libusb_glue_error (params, "PTP: request code 0x%04x getting resp error 0x%04x", resp->Code, ret);*/ return ret; } /* build an appropriate PTPContainer */ resp->Code = dtoh16(usbresp.code); resp->SessionID = params->session_id; resp->Transaction_ID = dtoh32(usbresp.trans_id); if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) { if (resp->Transaction_ID != params->transaction_id - 1) { libusb_glue_debug(params, "ptp_usb_getresp: detected a broken " "PTP header, transaction ID insane, expect " "problems! (But continuing)"); // Repair the header, so it won't wreak more havoc. resp->Transaction_ID = params->transaction_id - 1; } } resp->Param1 = dtoh32(usbresp.payload.params.param1); resp->Param2 = dtoh32(usbresp.payload.params.param2); resp->Param3 = dtoh32(usbresp.payload.params.param3); resp->Param4 = dtoh32(usbresp.payload.params.param4); resp->Param5 = dtoh32(usbresp.payload.params.param5); return ret; } /* Event handling functions */ /* PTP Events wait for or check mode */ #define PTP_EVENT_CHECK 0x0000 /* waits for */ #define PTP_EVENT_CHECK_FAST 0x0001 /* checks */ static inline uint16_t ptp_usb_event(PTPParams* params, PTPContainer* event, int wait) { uint16_t ret; int result, xread; unsigned long rlen; PTPUSBEventContainer usbevent; PTP_USB *ptp_usb = (PTP_USB *) (params->data); struct openusb_bulk_request bulk; memset(&usbevent, 0, sizeof (usbevent)); if ((params == NULL) || (event == NULL)) return PTP_ERROR_BADPARAM; ret = PTP_RC_OK; switch (wait) { case PTP_EVENT_CHECK: /* result = USB_BULK_READ(ptp_usb->handle, ptp_usb->intep, (unsigned char *) &usbevent, sizeof (usbevent), &xread, 0); */ bulk.payload = (unsigned char *) &usbevent; bulk.length = sizeof (usbevent); bulk.timeout = ptp_usb->timeout; bulk.flags = 0; bulk.next = NULL; result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->intep, &bulk); xread = bulk.result.transferred_bytes; if (result == 0) { /* result = USB_BULK_READ(ptp_usb->handle, ptp_usb->intep, (unsigned char *) &usbevent, sizeof (usbevent), &xread, 0); */ bulk.payload = (unsigned char *) &usbevent; bulk.length = sizeof (usbevent); bulk.timeout = ptp_usb->timeout; bulk.flags = 0; bulk.next = NULL; result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->intep, &bulk); xread = bulk.result.transferred_bytes; } if (result < 0) ret = PTP_ERROR_IO; break; case PTP_EVENT_CHECK_FAST: /* result = USB_BULK_READ(ptp_usb->handle, ptp_usb->intep, (unsigned char *) &usbevent, sizeof (usbevent), &xread, ptp_usb->timeout); */ bulk.payload = (unsigned char *) &usbevent; bulk.length = sizeof (usbevent); bulk.timeout = ptp_usb->timeout; bulk.flags = 0; bulk.next = NULL; result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->intep, &bulk); xread = bulk.result.transferred_bytes; if (result == 0) { /* result = USB_BULK_READ(ptp_usb->handle, ptp_usb->intep, (unsigned char *) &usbevent, sizeof (usbevent), &xread, ptp_usb->timeout); */ bulk.payload = (unsigned char *) &usbevent; bulk.length = sizeof (usbevent); bulk.timeout = ptp_usb->timeout; bulk.flags = 0; bulk.next = NULL; result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->intep, &bulk); xread = bulk.result.transferred_bytes; } if (result < 0) ret = PTP_ERROR_IO; break; default: ret = PTP_ERROR_BADPARAM; break; } if (ret != PTP_RC_OK) { libusb_glue_error(params, "PTP: reading event an error 0x%04x occurred", ret); return PTP_ERROR_IO; } rlen = result; if (rlen < 8) { libusb_glue_error(params, "PTP: reading event an short read of %ld bytes occurred", rlen); return PTP_ERROR_IO; } /* if we read anything over interrupt endpoint it must be an event */ /* build an appropriate PTPContainer */ event->Code = dtoh16(usbevent.code); event->SessionID = params->session_id; event->Transaction_ID = dtoh32(usbevent.trans_id); event->Param1 = dtoh32(usbevent.param1); event->Param2 = dtoh32(usbevent.param2); event->Param3 = dtoh32(usbevent.param3); return ret; } uint16_t ptp_usb_event_check(PTPParams* params, PTPContainer* event) { return ptp_usb_event(params, event, PTP_EVENT_CHECK_FAST); } uint16_t ptp_usb_event_wait(PTPParams* params, PTPContainer* event) { return ptp_usb_event(params, event, PTP_EVENT_CHECK); } uint16_t ptp_usb_control_cancel_request(PTPParams *params, uint32_t transactionid) { PTP_USB *ptp_usb = (PTP_USB *) (params->data); int ret; unsigned char buffer[6]; htod16a(&buffer[0], PTP_EC_CancelTransaction); htod32a(&buffer[2], transactionid); /* ret = libusb_control_transfer(ptp_usb->handle, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0x64, 0x0000, 0x0000, buffer, sizeof(buffer), ptp_usb->timeout); */ struct openusb_ctrl_request ctrl; ctrl.setup.bmRequestType = USB_REQ_TYPE_CLASS | USB_RECIP_INTERFACE; ctrl.setup.bRequest = 0x64; ctrl.setup.wValue = 0; ctrl.setup.wIndex = 0; ctrl.payload = (unsigned char *)&buffer; // Out ctrl.length = sizeof (buffer); ctrl.timeout = ptp_usb->timeout; ctrl.next = NULL; ctrl.flags = 0; ret = openusb_ctrl_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->outep, &ctrl); if (ctrl.result.transferred_bytes < sizeof (buffer)) return PTP_ERROR_IO; return PTP_RC_OK; } static int init_ptp_usb(PTPParams* params, PTP_USB* ptp_usb, openusb_dev_handle_t* dev) { openusb_dev_handle_t device_handle; unsigned char buf[255]; int ret, usbresult; params->sendreq_func = ptp_usb_sendreq; params->senddata_func = ptp_usb_senddata; params->getresp_func = ptp_usb_getresp; params->getdata_func = ptp_usb_getdata; params->cancelreq_func = ptp_usb_control_cancel_request; params->data = ptp_usb; params->transaction_id = 0; /* * This is hardcoded here since we have no devices whatsoever that are BE. * Change this the day we run into our first BE device (if ever). */ params->byteorder = PTP_DL_LE; ptp_usb->timeout = get_timeout(ptp_usb); ret = openusb_open_device(libmtp_openusb_handle, *dev, USB_INIT_DEFAULT, &device_handle); if (ret != OPENUSB_SUCCESS) { perror("usb_open()"); return -1; } ptp_usb->handle = malloc(sizeof(openusb_dev_handle_t)); *ptp_usb->handle = device_handle; /* * If this device is known to be wrongfully claimed by other kernel * drivers (such as mass storage), then try to unload it to make it * accessible from user space. * Note: OpenUSB doesn't support this type of operation? */ /* if (FLAG_UNLOAD_DRIVER(ptp_usb) && libusb_kernel_driver_active (device_handle, ptp_usb->interface) ) { if (OPENUSB_SUCCESS != libusb_detach_kernel_driver (device_handle, ptp_usb->interface)) { return -1; } } */ // It seems like on kernel 2.6.31 if we already have it open on another // pthread in our app, we'll get an error if we try to claim it again, // but that error is harmless because our process already claimed the interface usbresult = openusb_claim_interface(device_handle, ptp_usb->interface, USB_INIT_DEFAULT); if (usbresult != 0) fprintf(stderr, "ignoring usb_claim_interface = %d", usbresult); if (FLAG_SWITCH_MODE_BLACKBERRY(ptp_usb)) { int ret; // FIXME : Only for BlackBerry Storm // What does it mean? Maybe switch mode... // This first control message is absolutely necessary usleep(1000); /* ret = libusb_control_transfer(device_handle, LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN, 0xaa, 0x00, 0x04, buf, 0x40, 1000); */ struct openusb_ctrl_request ctrl; ctrl.setup.bmRequestType = USB_REQ_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN; ctrl.setup.bRequest = 0xaa; ctrl.setup.wValue = 0; ctrl.setup.wIndex = 4; ctrl.payload = (unsigned char *)&buf; // Out ctrl.length = 0x40; ctrl.timeout = 1000; ctrl.next = NULL; ctrl.flags = 0; ret = openusb_ctrl_xfer(device_handle, ptp_usb->interface, ptp_usb->outep, &ctrl); LIBMTP_USB_DEBUG("BlackBerry magic part 1:\n"); LIBMTP_USB_DATA(buf, ctrl.result.transferred_bytes, 16); usleep(1000); // This control message is unnecessary /* ret = libusb_control_transfer(device_handle, LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN, 0xa5, 0x00, 0x01, buf, 0x02, 1000); */ ctrl.setup.bmRequestType = USB_REQ_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN; ctrl.setup.bRequest = 0xa5; ctrl.setup.wValue = 0; ctrl.setup.wIndex = 1; ctrl.payload = (unsigned char *)&buf; // Out ctrl.length = 0x02; ctrl.timeout = 1000; ctrl.next = NULL; ctrl.flags = 0; ret = openusb_ctrl_xfer(device_handle, ptp_usb->interface, ptp_usb->outep, &ctrl); LIBMTP_USB_DEBUG("BlackBerry magic part 2:\n"); LIBMTP_USB_DATA(buf, ctrl.result.transferred_bytes, 16); usleep(1000); // This control message is unnecessary /* ret = libusb_control_transfer(device_handle, LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN, 0xa8, 0x00, 0x01, buf, 0x05, 1000); */ ctrl.setup.bmRequestType = USB_REQ_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN; ctrl.setup.bRequest = 0xa8; ctrl.setup.wValue = 0; ctrl.setup.wIndex = 1; ctrl.payload = (unsigned char *)&buf; // Out ctrl.length = 0x05; ctrl.timeout = 1000; ctrl.next = NULL; ctrl.flags = 0; ret = openusb_ctrl_xfer(device_handle, ptp_usb->interface, ptp_usb->outep, &ctrl); LIBMTP_USB_DEBUG("BlackBerry magic part 3:\n"); LIBMTP_USB_DATA(buf, ctrl.result.transferred_bytes, 16); usleep(1000); // This control message is unnecessary /* ret = libusb_control_transfer(device_handle, LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN, 0xa8, 0x00, 0x01, buf, 0x11, 1000); */ ctrl.setup.bmRequestType = USB_REQ_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN; ctrl.setup.bRequest = 0xa8; ctrl.setup.wValue = 0; ctrl.setup.wIndex = 1; ctrl.payload = (unsigned char *)&buf; // Out ctrl.length = 0x11; ctrl.timeout = 1000; ctrl.next = NULL; ctrl.flags = 0; ret = openusb_ctrl_xfer(device_handle, ptp_usb->interface, ptp_usb->outep, &ctrl); LIBMTP_USB_DEBUG("BlackBerry magic part 4:\n"); LIBMTP_USB_DATA(buf, ctrl.result.transferred_bytes, 16); usleep(1000); } return 0; } static void clear_stall(PTP_USB* ptp_usb) { uint16_t status; int ret; /* check the inep status */ /* status = 0; ret = usb_get_endpoint_status(ptp_usb, ptp_usb->inep, &status); if (ret < 0) { perror("inep: usb_get_endpoint_status()"); } else if (status) { LIBMTP_INFO("Clearing stall on IN endpoint\n"); ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->inep); if (ret != OPENUSB_SUCCESS) { perror("usb_clear_stall_feature()"); } } /* check the outep status */ /*status = 0; ret = usb_get_endpoint_status(ptp_usb, ptp_usb->outep, &status); if (ret < 0) { perror("outep: usb_get_endpoint_status()"); } else if (status) { LIBMTP_INFO("Clearing stall on OUT endpoint\n"); ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->outep); if (ret != OPENUSB_SUCCESS) { perror("usb_clear_stall_feature()"); } } */ /* TODO: do we need this for INTERRUPT (ptp_usb->intep) too? */ } static void clear_halt(PTP_USB* ptp_usb) { int ret; /* ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->inep); if (ret < 0) { perror("usb_clear_halt() on IN endpoint"); } ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->outep); if (ret < 0) { perror("usb_clear_halt() on OUT endpoint"); } ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->intep); if (ret < 0) { perror("usb_clear_halt() on INTERRUPT endpoint"); } */ } static void close_usb(PTP_USB* ptp_usb) { if (!FLAG_NO_RELEASE_INTERFACE(ptp_usb)) { /* * Clear any stalled endpoints * On misbehaving devices designed for Windows/Mac, quote from: * http://www2.one-eyed-alien.net/~mdharm/linux-usb/target_offenses.txt * Device does Bad Things(tm) when it gets a GET_STATUS after CLEAR_HALT * (...) Windows, when clearing a stall, only sends the CLEAR_HALT command, * and presumes that the stall has cleared. Some devices actually choke * if the CLEAR_HALT is followed by a GET_STATUS (used to determine if the * STALL is persistant or not). */ clear_stall(ptp_usb); // Clear halts on any endpoints clear_halt(ptp_usb); // Added to clear some stuff on the OUT endpoint // TODO: is this good on the Mac too? // HINT: some devices may need that you comment these two out too. //libusb_clear_halt(ptp_usb->handle, ptp_usb->outep); //libusb_release_interface(ptp_usb->handle, (int) ptp_usb->interface); } if (FLAG_FORCE_RESET_ON_CLOSE(ptp_usb)) { /* * Some devices really love to get reset after being * disconnected. Again, since Windows never disconnects * a device closing behaviour is seldom or never exercised * on devices when engineered and often error prone. * Reset may help some. */ openusb_reset(*ptp_usb->handle); } openusb_close_device(*ptp_usb->handle); } /** * Self-explanatory? */ static int find_interface_and_endpoints(openusb_dev_handle_t *dev, uint8_t *conf, uint8_t *interface, uint8_t *altsetting, int* inep, int* inep_maxpacket, int* outep, int *outep_maxpacket, int* intep) { uint8_t i; int ret; struct usb_device_desc desc; ret = openusb_parse_device_desc(libmtp_openusb_handle, *dev, NULL, 0, &desc); if (ret != OPENUSB_SUCCESS) return -1; // Loop over the device configurations for (i = 0; i < desc.bNumConfigurations; i++) { uint8_t j; struct usb_config_desc config; ret = openusb_parse_config_desc(libmtp_openusb_handle, *dev, NULL, 0, i, &config); if (ret != OPENUSB_SUCCESS) continue; *conf = desc.bConfigurationValue; // Loop over each configurations interfaces for (j = 0; j < config.bNumInterfaces; j++) { uint8_t k; uint8_t no_ep; int found_inep = 0; int found_outep = 0; int found_intep = 0; struct usb_endpoint_desc ep; struct usb_interface_desc ifcdesc; openusb_parse_interface_desc(libmtp_openusb_handle, *dev, NULL, 0, i, j, 0, &ifcdesc); // MTP devices shall have 3 endpoints, ignore those interfaces // that haven't. no_ep = ifcdesc.bNumEndpoints; if (no_ep != 3) continue; *interface = ifcdesc.bInterfaceNumber; *altsetting = ifcdesc.bAlternateSetting; // Loop over the three endpoints to locate two bulk and // one interrupt endpoint and FAIL if we cannot, and continue. for (k = 0; k < no_ep; k++) { openusb_parse_endpoint_desc(libmtp_openusb_handle, *dev, NULL, 0, i, j, 0, k, &ep); if (ep.bmAttributes == USB_ENDPOINT_TYPE_BULK) { if ((ep.bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_MASK) { *inep = ep.bEndpointAddress; *inep_maxpacket = ep.wMaxPacketSize; found_inep = 1; } if ((ep.bEndpointAddress & USB_ENDPOINT_DIR_MASK) == 0) { *outep = ep.bEndpointAddress; *outep_maxpacket = ep.wMaxPacketSize; found_outep = 1; } } else if (ep.bmAttributes == USB_ENDPOINT_TYPE_INTERRUPT) { if ((ep.bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_MASK) { *intep = ep.bEndpointAddress; found_intep = 1; } } } if (found_inep && found_outep && found_intep) { // We assigned the endpoints so return here. return 0; } // Else loop to next interface/config } } return -1; } /** * This function assigns params and usbinfo given a raw device * as input. * @param device the device to be assigned. * @param usbinfo a pointer to the new usbinfo. * @return an error code. */ LIBMTP_error_number_t configure_usb_device(LIBMTP_raw_device_t *device, PTPParams *params, void **usbinfo) { PTP_USB *ptp_usb; openusb_devid_t *ldevice; uint16_t ret = 0; int err, found = 0, i; unsigned int nrofdevs; openusb_devid_t *devs = NULL; struct usb_device_desc desc; /* See if we can find this raw device again... */ init_usb(); openusb_get_devids_by_bus(libmtp_openusb_handle, 0, &devs, &nrofdevs); for (i = 0; i < nrofdevs; i++) { /* if (libusb_get_bus_number(devs[i]) != device->bus_location) continue; if (libusb_get_device_address(devs[i]) != device->devnum) continue; */ ret = openusb_parse_device_desc(libmtp_openusb_handle, devs[i], NULL, 0, &desc); if (ret != OPENUSB_SUCCESS) continue; if (desc.idVendor == device->device_entry.vendor_id && desc.idProduct == device->device_entry.product_id) { ldevice = &devs[i]; found = 1; break; } } /* Device has gone since detecting raw devices! */ if (!found) { openusb_free_devid_list(devs); return LIBMTP_ERROR_NO_DEVICE_ATTACHED; } /* Allocate structs */ ptp_usb = (PTP_USB *) malloc(sizeof (PTP_USB)); if (ptp_usb == NULL) { openusb_free_devid_list(devs); return LIBMTP_ERROR_MEMORY_ALLOCATION; } /* Start with a blank slate (includes setting device_flags to 0) */ memset(ptp_usb, 0, sizeof (PTP_USB)); /* Copy the raw device */ memcpy(&ptp_usb->rawdevice, device, sizeof (LIBMTP_raw_device_t)); /* * Some devices must have their "OS Descriptor" massaged in order * to work. */ if (FLAG_ALWAYS_PROBE_DESCRIPTOR(ptp_usb)) { // Massage the device descriptor (void) probe_device_descriptor(ldevice, NULL); } /* Assign interface and endpoints to usbinfo... */ err = find_interface_and_endpoints(ldevice, &ptp_usb->conf, &ptp_usb->interface, &ptp_usb->altsetting, &ptp_usb->inep, &ptp_usb->inep_maxpacket, &ptp_usb->outep, &ptp_usb->outep_maxpacket, &ptp_usb->intep); if (err) { openusb_free_devid_list(devs); LIBMTP_ERROR("LIBMTP PANIC: Unable to find interface & endpoints of device\n"); return LIBMTP_ERROR_CONNECTING; } /* Copy USB version number */ ptp_usb->bcdusb = desc.bcdUSB; /* Attempt to initialize this device */ if (init_ptp_usb(params, ptp_usb, ldevice) < 0) { LIBMTP_ERROR("LIBMTP PANIC: Unable to initialize device\n"); return LIBMTP_ERROR_CONNECTING; } /* * This works in situations where previous bad applications * have not used LIBMTP_Release_Device on exit */ if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) { LIBMTP_ERROR("PTP_ERROR_IO: failed to open session, trying again after resetting USB interface\n"); LIBMTP_ERROR("LIBMTP libusb: Attempt to reset device\n"); openusb_reset(*ptp_usb->handle); close_usb(ptp_usb); if (init_ptp_usb(params, ptp_usb, ldevice) < 0) { LIBMTP_ERROR("LIBMTP PANIC: Could not init USB on second attempt\n"); return LIBMTP_ERROR_CONNECTING; } /* Device has been reset, try again */ if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) { LIBMTP_ERROR("LIBMTP PANIC: failed to open session on second attempt\n"); return LIBMTP_ERROR_CONNECTING; } } /* Was the transaction id invalid? Try again */ if (ret == PTP_RC_InvalidTransactionID) { LIBMTP_ERROR("LIBMTP WARNING: Transaction ID was invalid, increment and try again\n"); params->transaction_id += 10; ret = ptp_opensession(params, 1); } if (ret != PTP_RC_SessionAlreadyOpened && ret != PTP_RC_OK) { LIBMTP_ERROR("LIBMTP PANIC: Could not open session! " "(Return code %d)\n Try to reset the device.\n", ret); openusb_release_interface(*ptp_usb->handle, ptp_usb->interface); return LIBMTP_ERROR_CONNECTING; } /* OK configured properly */ *usbinfo = (void *) ptp_usb; return LIBMTP_ERROR_NONE; } void close_device(PTP_USB *ptp_usb, PTPParams *params) { if (ptp_closesession(params) != PTP_RC_OK) LIBMTP_ERROR("ERROR: Could not close session!\n"); close_usb(ptp_usb); } void set_usb_device_timeout(PTP_USB *ptp_usb, int timeout) { ptp_usb->timeout = timeout; } void get_usb_device_timeout(PTP_USB *ptp_usb, int *timeout) { *timeout = ptp_usb->timeout; } int guess_usb_speed(PTP_USB *ptp_usb) { int bytes_per_second; /* * We don't know the actual speeds so these are rough guesses * from the info you can find here: * http://en.wikipedia.org/wiki/USB#Transfer_rates * http://www.barefeats.com/usb2.html */ switch (ptp_usb->bcdusb & 0xFF00) { case 0x0100: /* 1.x USB versions let's say 1MiB/s */ bytes_per_second = 1 * 1024 * 1024; break; case 0x0200: case 0x0300: /* USB 2.0 nominal speed 18MiB/s */ /* USB 3.0 won't be worse? */ bytes_per_second = 18 * 1024 * 1024; break; default: /* Half-guess something? */ bytes_per_second = 1 * 1024 * 1024; break; } return bytes_per_second; } static int usb_get_endpoint_status(PTP_USB* ptp_usb, int ep, uint16_t* status) { /* return libusb_control_transfer(ptp_usb->handle, LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_ENDPOINT, LIBUSB_REQUEST_GET_STATUS, USB_FEATURE_HALT, ep, (unsigned char *) status, 2, ptp_usb->timeout); */ struct openusb_ctrl_request ctrl; ctrl.flags = 0; ctrl.length = 2; ctrl.payload = (unsigned char *)status; ctrl.timeout = ptp_usb->timeout; ctrl.next = NULL; ctrl.setup.bRequest = USB_REQ_GET_STATUS; ctrl.setup.bmRequestType = USB_ENDPOINT_IN | USB_RECIP_ENDPOINT; ctrl.setup.wIndex = ep; ctrl.setup.wValue = USB_FEATURE_HALT; openusb_ctrl_xfer(*ptp_usb->handle, ptp_usb->interface, ep, &ctrl); return ctrl.result.status; } libmtp-1.1.6-20-g1b9f164/src/Makefile.am0000664000175000017500000000544112205614637017541 0ustar glowwormglowwormlib_LTLIBRARIES = libmtp.la libmtp_la_CFLAGS = @LIBUSB_CFLAGS@ libmtp_la_SOURCES = libmtp.c unicode.c unicode.h util.c util.h playlist-spl.c \ gphoto2-endian.h _stdint.h ptp.c ptp.h libusb-glue.h \ music-players.h device-flags.h playlist-spl.h mtpz.h if MTPZ_COMPILE libmtp_la_SOURCES += mtpz.c endif if LIBUSB1_COMPILE libmtp_la_SOURCES += libusb1-glue.c endif if LIBUSB0_COMPILE libmtp_la_SOURCES += libusb-glue.c endif if LIBOPENUSB_COMPILE libmtp_la_SOURCES += libopenusb1-glue.c endif include_HEADERS=libmtp.h EXTRA_DIST=libmtp.h.in libmtp.sym ptp-pack.c # --------------------------------------------------------------------------- # Advanced information about versioning: # * "Writing shared libraries" by Mike Hearn # http://plan99.net/~mike/writing-shared-libraries.html # * libtool.info chapter "Versioning" # * libtool.info chapter "Updating library version information" # --------------------------------------------------------------------------- # Versioning: # - CURRENT (Major): Increment if the interface has changes. AGE is always # *changed* at the same time. # - AGE (Micro): Increment if any interfaces have been added; set to 0 # if any interfaces have been removed. Removal has # precedence over adding, so set to 0 if both happened. # It denotes upward compatibility. # - REVISION (Minor): Increment any time the source changes; set to # 0 if you incremented CURRENT. # # To summarize. Any interface *change* increment CURRENT. If that interface # change does not break upward compatibility (ie it is an addition), # increment AGE, Otherwise AGE is reset to 0. If CURRENT has changed, # REVISION is set to 0, otherwise REVISION is incremented. # --------------------------------------------------------------------------- CURRENT=10 AGE=1 REVISION=0 SOVERSION=$(CURRENT):$(REVISION):$(AGE) LT_CURRENT_MINUS_AGE=`expr $(CURRENT) - $(AGE)` if COMPILE_MINGW32 W32_LIBS=-lws2_32 W32_LDFLAGS=-export-dynamic if MS_LIB_EXE noinst_DATA=libmtp.lib libmtp.def: $(srcdir)/libmtp.sym echo "LIBRARY \"@PACKAGE@\"" > libmtp.def echo "DESCRIPTION \"Media Transfer Protocol (MTP) library\"" >> libmtp.def echo "VERSION @VERSION@" >> libmtp.def echo >> libmtp.def echo "EXPORTS" >> libmtp.def cat $< >> libmtp.def libmtp.lib: libmtp.la libmtp.def lib -name:libmtp-$(LT_CURRENT_MINUS_AGE).dll -def:libmtp.def -out:$@ install-data-local: libmtp.lib libmtp.def $(INSTALL) libmtp.def $(DESTDIR)$(libdir) $(INSTALL) libmtp.lib $(DESTDIR)$(libdir) endif endif libmtp_la_LDFLAGS=@LDFLAGS@ -no-undefined -export-symbols $(srcdir)/libmtp.sym -version-info $(SOVERSION) $(W32_LDFLAGS) libmtp_la_LIBADD=$(W32_LIBS) $(LTLIBICONV) @LIBUSB_LIBS@ libmtp_la_DEPENDENCIES=$(srcdir)/libmtp.sym DISTCLEANFILES = _stdint.h gphoto2-endian.h libmtp-1.1.6-20-g1b9f164/src/playlist-spl.h0000664000175000017500000000252712205614637020315 0ustar glowwormglowworm/* * \file playlist-spl.h * Playlist to .spl conversion functions. * * Copyright (C) 2008 Alistair Boyle * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef __MTP__PLAYLIST_SPL__H #define __MTP__PLAYLIST_SPL__H int is_spl_playlist(PTPObjectInfo *oi); void spl_to_playlist_t(LIBMTP_mtpdevice_t* device, PTPObjectInfo *oi, const uint32_t id, LIBMTP_playlist_t * const pl); int playlist_t_to_spl(LIBMTP_mtpdevice_t *device, LIBMTP_playlist_t * const metadata); int update_spl_playlist(LIBMTP_mtpdevice_t *device, LIBMTP_playlist_t * const newlist); #endif //__MTP__PLAYLIST_SPL__H libmtp-1.1.6-20-g1b9f164/src/ptp.c0000664000175000017500000056476612205614637016500 0ustar glowwormglowworm/* ptp.c * * Copyright (C) 2001-2004 Mariusz Woloszyn * Copyright (C) 2003-2012 Marcus Meissner * Copyright (C) 2006-2008 Linus Walleij * Copyright (C) 2007 Tero Saarni * Copyright (C) 2009 Axel Waggershauser * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #define _BSD_SOURCE #include "config.h" #include "ptp.h" #include #include #include #include #include #ifdef ENABLE_NLS # include # undef _ # define _(String) dgettext (PACKAGE, String) # ifdef gettext_noop # define N_(String) gettext_noop (String) # else # define N_(String) (String) # endif #else # define textdomain(String) (String) # define gettext(String) (String) # define dgettext(Domain,Message) (Message) # define dcgettext(Domain,Message,Type) (Message) # define bindtextdomain(Domain,Directory) (Domain) # define _(String) (String) # define N_(String) (String) #endif #define CHECK_PTP_RC(result) {uint16_t r=(result); if (r!=PTP_RC_OK) return r;} #define PTP_CNT_INIT(cnt) {memset(&cnt,0,sizeof(cnt));} static uint16_t ptp_exit_recv_memory_handler (PTPDataHandler*,unsigned char**,unsigned long*); static uint16_t ptp_init_recv_memory_handler(PTPDataHandler*); static uint16_t ptp_init_send_memory_handler(PTPDataHandler*,unsigned char*,unsigned long len); static uint16_t ptp_exit_send_memory_handler (PTPDataHandler *handler); void ptp_debug (PTPParams *params, const char *format, ...) { va_list args; va_start (args, format); if (params->debug_func!=NULL) params->debug_func (params->data, format, args); else { vfprintf (stderr, format, args); fprintf (stderr,"\n"); fflush (stderr); } va_end (args); } void ptp_error (PTPParams *params, const char *format, ...) { va_list args; va_start (args, format); if (params->error_func!=NULL) params->error_func (params->data, format, args); else { vfprintf (stderr, format, args); fprintf (stderr,"\n"); fflush (stderr); } va_end (args); } /* Pack / unpack functions */ #include "ptp-pack.c" /* major PTP functions */ /* Transaction data phase description */ #define PTP_DP_NODATA 0x0000 /* no data phase */ #define PTP_DP_SENDDATA 0x0001 /* sending data */ #define PTP_DP_GETDATA 0x0002 /* receiving data */ #define PTP_DP_DATA_MASK 0x00ff /* data phase mask */ /** * ptp_transaction: * params: PTPParams* * PTPContainer* ptp - general ptp container * uint16_t flags - lower 8 bits - data phase description * unsigned int sendlen - senddata phase data length * char** data - send or receive data buffer pointer * int* recvlen - receive data length * * Performs PTP transaction. ptp is a PTPContainer with appropriate fields * filled in (i.e. operation code and parameters). It's up to caller to do * so. * The flags decide thether the transaction has a data phase and what is its * direction (send or receive). * If transaction is sending data the sendlen should contain its length in * bytes, otherwise it's ignored. * The data should contain an address of a pointer to data going to be sent * or is filled with such a pointer address if data are received depending * od dataphase direction (send or received) or is beeing ignored (no * dataphase). * The memory for a pointer should be preserved by the caller, if data are * beeing retreived the appropriate amount of memory is beeing allocated * (the caller should handle that!). * * Return values: Some PTP_RC_* code. * Upon success PTPContainer* ptp contains PTP Response Phase container with * all fields filled in. **/ uint16_t ptp_transaction_new (PTPParams* params, PTPContainer* ptp, uint16_t flags, uint64_t sendlen, PTPDataHandler *handler ) { int tries; uint16_t cmd; if ((params==NULL) || (ptp==NULL)) return PTP_ERROR_BADPARAM; cmd = ptp->Code; ptp->Transaction_ID=params->transaction_id++; ptp->SessionID=params->session_id; /* send request */ CHECK_PTP_RC(params->sendreq_func (params, ptp)); /* is there a dataphase? */ switch (flags&PTP_DP_DATA_MASK) { case PTP_DP_SENDDATA: { uint16_t ret; ret = params->senddata_func(params, ptp, sendlen, handler); if (ret == PTP_ERROR_CANCEL) { ret = params->cancelreq_func(params, params->transaction_id-1); if (ret == PTP_RC_OK) ret = PTP_ERROR_CANCEL; } if (ret != PTP_RC_OK) return ret; } break; case PTP_DP_GETDATA: { uint16_t ret; ret = params->getdata_func(params, ptp, handler); if (ret == PTP_ERROR_CANCEL) { ret = params->cancelreq_func(params, params->transaction_id-1); if (ret == PTP_RC_OK) ret = PTP_ERROR_CANCEL; } if (ret != PTP_RC_OK) return ret; } break; case PTP_DP_NODATA: break; default: return PTP_ERROR_BADPARAM; } tries = 3; while (tries--) { uint16_t ret; /* get response */ ret = params->getresp_func(params, ptp); if (ret == PTP_ERROR_RESP_EXPECTED) { ptp_debug (params,"PTP: response expected but not got, retrying."); tries++; continue; } if (ret != PTP_RC_OK) return ret; if (ptp->Transaction_ID < params->transaction_id-1) { tries++; ptp_debug (params, "PTP: Sequence number mismatch %d vs expected %d, suspecting old reply.", ptp->Transaction_ID, params->transaction_id-1 ); continue; } if (ptp->Transaction_ID != params->transaction_id-1) { /* try to clean up potential left overs from previous session */ if ((cmd == PTP_OC_OpenSession) && tries) continue; ptp_error (params, "PTP: Sequence number mismatch %d vs expected %d.", ptp->Transaction_ID, params->transaction_id-1 ); return PTP_ERROR_BADPARAM; } break; } return ptp->Code; } /* memory data get/put handler */ typedef struct { unsigned char *data; unsigned long size, curoff; } PTPMemHandlerPrivate; static uint16_t memory_getfunc(PTPParams* params, void* private, unsigned long wantlen, unsigned char *data, unsigned long *gotlen ) { PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)private; unsigned long tocopy = wantlen; if (priv->curoff + tocopy > priv->size) tocopy = priv->size - priv->curoff; memcpy (data, priv->data + priv->curoff, tocopy); priv->curoff += tocopy; *gotlen = tocopy; return PTP_RC_OK; } static uint16_t memory_putfunc(PTPParams* params, void* private, unsigned long sendlen, unsigned char *data, unsigned long *putlen ) { PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)private; if (priv->curoff + sendlen > priv->size) { priv->data = realloc (priv->data, priv->curoff+sendlen); if (!priv->data) return PTP_RC_GeneralError; priv->size = priv->curoff + sendlen; } memcpy (priv->data + priv->curoff, data, sendlen); priv->curoff += sendlen; *putlen = sendlen; return PTP_RC_OK; } /* init private struct for receiving data. */ static uint16_t ptp_init_recv_memory_handler(PTPDataHandler *handler) { PTPMemHandlerPrivate* priv; priv = malloc (sizeof(PTPMemHandlerPrivate)); if (!priv) return PTP_RC_GeneralError; handler->priv = priv; handler->getfunc = memory_getfunc; handler->putfunc = memory_putfunc; priv->data = NULL; priv->size = 0; priv->curoff = 0; return PTP_RC_OK; } /* init private struct and put data in for sending data. * data is still owned by caller. */ static uint16_t ptp_init_send_memory_handler(PTPDataHandler *handler, unsigned char *data, unsigned long len ) { PTPMemHandlerPrivate* priv; priv = malloc (sizeof(PTPMemHandlerPrivate)); if (!priv) return PTP_RC_GeneralError; handler->priv = priv; handler->getfunc = memory_getfunc; handler->putfunc = memory_putfunc; priv->data = data; priv->size = len; priv->curoff = 0; return PTP_RC_OK; } /* free private struct + data */ static uint16_t ptp_exit_send_memory_handler (PTPDataHandler *handler) { PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)handler->priv; /* data is owned by caller */ free (priv); return PTP_RC_OK; } /* hand over our internal data to caller */ static uint16_t ptp_exit_recv_memory_handler (PTPDataHandler *handler, unsigned char **data, unsigned long *size ) { PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)handler->priv; *data = priv->data; *size = priv->size; free (priv); return PTP_RC_OK; } /* fd data get/put handler */ typedef struct { int fd; } PTPFDHandlerPrivate; static uint16_t fd_getfunc(PTPParams* params, void* private, unsigned long wantlen, unsigned char *data, unsigned long *gotlen ) { PTPFDHandlerPrivate* priv = (PTPFDHandlerPrivate*)private; int got; got = read (priv->fd, data, wantlen); if (got != -1) *gotlen = got; else return PTP_RC_GeneralError; return PTP_RC_OK; } static uint16_t fd_putfunc(PTPParams* params, void* private, unsigned long sendlen, unsigned char *data, unsigned long *putlen ) { int written; PTPFDHandlerPrivate* priv = (PTPFDHandlerPrivate*)private; written = write (priv->fd, data, sendlen); if (written != -1) *putlen = written; else return PTP_RC_GeneralError; return PTP_RC_OK; } static uint16_t ptp_init_fd_handler(PTPDataHandler *handler, int fd) { PTPFDHandlerPrivate* priv; priv = malloc (sizeof(PTPFDHandlerPrivate)); if (!priv) return PTP_RC_GeneralError; handler->priv = priv; handler->getfunc = fd_getfunc; handler->putfunc = fd_putfunc; priv->fd = fd; return PTP_RC_OK; } static uint16_t ptp_exit_fd_handler (PTPDataHandler *handler) { PTPFDHandlerPrivate* priv = (PTPFDHandlerPrivate*)handler->priv; free (priv); return PTP_RC_OK; } /* Old style transaction, based on memory */ uint16_t ptp_transaction (PTPParams* params, PTPContainer* ptp, uint16_t flags, uint64_t sendlen, unsigned char **data, unsigned int *recvlen ) { PTPDataHandler handler; uint16_t ret; switch (flags & PTP_DP_DATA_MASK) { case PTP_DP_SENDDATA: ret = ptp_init_send_memory_handler (&handler, *data, sendlen); if (ret != PTP_RC_OK) return ret; break; case PTP_DP_GETDATA: ret = ptp_init_recv_memory_handler (&handler); if (ret != PTP_RC_OK) return ret; break; default:break; } ret = ptp_transaction_new (params, ptp, flags, sendlen, &handler); switch (flags & PTP_DP_DATA_MASK) { case PTP_DP_SENDDATA: ptp_exit_send_memory_handler (&handler); break; case PTP_DP_GETDATA: { unsigned long len; ptp_exit_recv_memory_handler (&handler, data, &len); if (recvlen) *recvlen = len; break; } default:break; } return ret; } /** * PTP operation functions * * all ptp_ functions should take integer parameters * in host byte order! **/ /** * ptp_getdeviceinfo: * params: PTPParams* * * Gets device info dataset and fills deviceinfo structure. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_getdeviceinfo (PTPParams* params, PTPDeviceInfo* deviceinfo) { uint16_t ret; unsigned long len; PTPContainer ptp; unsigned char* di=NULL; PTPDataHandler handler; ptp_init_recv_memory_handler (&handler); PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_GetDeviceInfo; ptp.Nparam=0; len=0; ret=ptp_transaction_new(params, &ptp, PTP_DP_GETDATA, 0, &handler); ptp_exit_recv_memory_handler (&handler, &di, &len); if (!di) ret = PTP_RC_GeneralError; if (ret == PTP_RC_OK) ptp_unpack_DI(params, di, deviceinfo, len); free(di); return ret; } uint16_t ptp_canon_eos_getdeviceinfo (PTPParams* params, PTPCanonEOSDeviceInfo*di) { uint16_t ret; PTPContainer ptp; PTPDataHandler handler; unsigned long len; unsigned char *data; ptp_init_recv_memory_handler (&handler); PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CANON_EOS_GetDeviceInfoEx; ptp.Nparam=0; len=0; data=NULL; ret=ptp_transaction_new(params, &ptp, PTP_DP_GETDATA, 0, &handler); ptp_exit_recv_memory_handler (&handler, &data, &len); if (ret == PTP_RC_OK) ptp_unpack_EOS_DI(params, data, di, len); free (data); return ret; } /** * ptp_generic_no_data: * params: PTPParams* * code PTP OP Code * n_param count of parameters * ... variable argument list ... * * Emits a generic PTP command without any data transfer. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_generic_no_data (PTPParams* params, uint16_t code, unsigned int n_param, ...) { PTPContainer ptp; va_list args; int i; if( n_param > 5 ) return PTP_RC_InvalidParameter; PTP_CNT_INIT(ptp); ptp.Code=code; ptp.Nparam=n_param; va_start(args, n_param); for( i=0; isession_id=0x00000000; /* TransactionID should be set to 0 also! */ params->transaction_id=0x0000000; /* zero out response packet buffer */ params->response_packet = NULL; params->response_packet_size = 0; /* no split headers */ params->split_header_data = 0; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_OpenSession; ptp.Param1=session; ptp.Nparam=1; ret=ptp_transaction_new(params, &ptp, PTP_DP_NODATA, 0, NULL); /* now set the global session id to current session number */ params->session_id=session; return ret; } /** * ptp_free_params: * params: PTPParams* * * Frees all data within the PTPParams struct. * * Return values: Some PTP_RC_* code. **/ void ptp_free_params (PTPParams *params) { int i; if (params->cameraname) free (params->cameraname); if (params->wifi_profiles) free (params->wifi_profiles); for (i=0;inrofobjects;i++) ptp_free_object (¶ms->objects[i]); free (params->objects); free (params->events); for (i=0;inrofcanon_props;i++) { free (params->canon_props[i].data); ptp_free_devicepropdesc (¶ms->canon_props[i].dpd); } free (params->canon_props); free (params->backlogentries); ptp_free_DI (¶ms->deviceinfo); } /** * ptp_getststorageids: * params: PTPParams* * * Gets array of StorageIDs and fills the storageids structure. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_getstorageids (PTPParams* params, PTPStorageIDs* storageids) { uint16_t ret; PTPContainer ptp; unsigned int len; unsigned char* sids=NULL; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_GetStorageIDs; ptp.Nparam=0; len=0; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &sids, &len); if (ret == PTP_RC_OK) ptp_unpack_SIDs(params, sids, storageids, len); free(sids); return ret; } /** * ptp_getststorageinfo: * params: PTPParams* * storageid - StorageID * * Gets StorageInfo dataset of desired storage and fills storageinfo * structure. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_getstorageinfo (PTPParams* params, uint32_t storageid, PTPStorageInfo* storageinfo) { uint16_t ret; PTPContainer ptp; unsigned char* si=NULL; unsigned int len; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_GetStorageInfo; ptp.Param1=storageid; ptp.Nparam=1; len=0; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &si, &len); if (ret == PTP_RC_OK) ptp_unpack_SI(params, si, storageinfo, len); free(si); return ret; } /** * ptp_getobjecthandles: * params: PTPParams* * storage - StorageID * objectformatcode - ObjectFormatCode (optional) * associationOH - ObjectHandle of Association for * wich a list of children is desired * (optional) * objecthandles - pointer to structute * * Fills objecthandles with structure returned by device. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_getobjecthandles (PTPParams* params, uint32_t storage, uint32_t objectformatcode, uint32_t associationOH, PTPObjectHandles* objecthandles) { uint16_t ret; PTPContainer ptp; unsigned char* oh=NULL; unsigned int len; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_GetObjectHandles; ptp.Param1=storage; ptp.Param2=objectformatcode; ptp.Param3=associationOH; ptp.Nparam=3; len=0; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &oh, &len); if (ret == PTP_RC_OK) { ptp_unpack_OH(params, oh, objecthandles, len); } else { if ( (storage == 0xffffffff) && (objectformatcode == 0) && (associationOH == 0) ) { /* When we query all object handles on all stores and * get an error -> just handle it as "0 handles". */ objecthandles->Handler = NULL; objecthandles->n = 0; ret = PTP_RC_OK; } } free(oh); return ret; } uint16_t ptp_getfilesystemmanifest (PTPParams* params, uint32_t storage, uint32_t objectformatcode, uint32_t associationOH, unsigned char** data) { uint16_t ret; PTPContainer ptp; unsigned int len; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_GetFilesystemManifest; ptp.Param1=storage; ptp.Param2=objectformatcode; ptp.Param3=associationOH; ptp.Nparam=3; len=0; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, data, &len); return ret; } /** * ptp_getnumobjects: * params: PTPParams* * storage - StorageID * objectformatcode - ObjectFormatCode (optional) * associationOH - ObjectHandle of Association for * wich a list of children is desired * (optional) * numobs - pointer to uint32_t that takes number of objects * * Fills numobs with number of objects on device. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_getnumobjects (PTPParams* params, uint32_t storage, uint32_t objectformatcode, uint32_t associationOH, uint32_t* numobs) { uint16_t ret; PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_GetNumObjects; ptp.Param1=storage; ptp.Param2=objectformatcode; ptp.Param3=associationOH; ptp.Nparam=3; ret=ptp_transaction(params, &ptp, PTP_DP_NODATA, 0, NULL, NULL); if (ret == PTP_RC_OK) { if (ptp.Nparam >= 1) *numobs = ptp.Param1; else ret = PTP_RC_GeneralError; } return ret; } /** * ptp_eos_bulbstart: * params: PTPParams* * * Starts EOS Bulb capture. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_canon_eos_bulbstart (PTPParams* params) { uint16_t ret; PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_CANON_EOS_BulbStart; ptp.Nparam = 0; ret = ptp_transaction(params, &ptp, PTP_DP_NODATA, 0, NULL, NULL); if ((ret == PTP_RC_OK) && (ptp.Nparam >= 1) && ((ptp.Param1 & 0x7000) == 0x2000)) ret = ptp.Param1; return ret; } /** * ptp_eos_capture: * params: PTPParams* * uint32_t* result * * This starts a EOS400D style capture. You have to use the * get_eos_events to find out what resulted. * The return value is "0" for all OK, and "1" for capture failed. (not fully confirmed) * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_canon_eos_capture (PTPParams* params, uint32_t *result) { uint16_t ret; PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_CANON_EOS_RemoteRelease; ptp.Nparam = 0; *result = 0; ret = ptp_transaction(params, &ptp, PTP_DP_NODATA, 0, NULL, NULL); if ((ret == PTP_RC_OK) && (ptp.Nparam >= 1)) *result = ptp.Param1; return ret; } /** * ptp_canon_eos_bulbend: * params: PTPParams* * * Starts EOS Bulb capture. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_canon_eos_bulbend (PTPParams* params) { uint16_t ret; PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_CANON_EOS_BulbEnd; ptp.Nparam = 0; ret = ptp_transaction(params, &ptp, PTP_DP_NODATA, 0, NULL, NULL); if ((ret == PTP_RC_OK) && (ptp.Nparam >= 1) && ((ptp.Param1 & 0x7000) == 0x2000)) ret = ptp.Param1; return ret; } /** * ptp_getobjectinfo: * params: PTPParams* * handle - Object handle * objectinfo - pointer to objectinfo that is returned * * Get objectinfo structure for handle from device. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_getobjectinfo (PTPParams* params, uint32_t handle, PTPObjectInfo* objectinfo) { uint16_t ret; PTPContainer ptp; unsigned char* oi=NULL; unsigned int len; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_GetObjectInfo; ptp.Param1=handle; ptp.Nparam=1; len=0; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &oi, &len); if (ret == PTP_RC_OK) ptp_unpack_OI(params, oi, objectinfo, len); free(oi); return ret; } /** * ptp_getobject: * params: PTPParams* * handle - Object handle * object - pointer to data area * * Get object 'handle' from device and store the data in newly * allocated 'object'. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_getobject (PTPParams* params, uint32_t handle, unsigned char** object) { PTPContainer ptp; unsigned int len; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_GetObject; ptp.Param1=handle; ptp.Nparam=1; len=0; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, object, &len); } /** * ptp_getobject_to_handler: * params: PTPParams* * handle - Object handle * PTPDataHandler* - pointer datahandler * * Get object 'handle' from device and store the data in newly * allocated 'object'. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_getobject_to_handler (PTPParams* params, uint32_t handle, PTPDataHandler *handler) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_GetObject; ptp.Param1=handle; ptp.Nparam=1; return ptp_transaction_new(params, &ptp, PTP_DP_GETDATA, 0, handler); } /** * ptp_getobject_tofd: * params: PTPParams* * handle - Object handle * fd - File descriptor to write() to * * Get object 'handle' from device and write the data to the * given file descriptor. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_getobject_tofd (PTPParams* params, uint32_t handle, int fd) { PTPContainer ptp; PTPDataHandler handler; uint16_t ret; ptp_init_fd_handler (&handler, fd); PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_GetObject; ptp.Param1=handle; ptp.Nparam=1; ret = ptp_transaction_new(params, &ptp, PTP_DP_GETDATA, 0, &handler); ptp_exit_fd_handler (&handler); return ret; } /** * ptp_getpartialobject: * params: PTPParams* * handle - Object handle * offset - Offset into object * maxbytes - Maximum of bytes to read * object - pointer to data area * len - pointer to returned length * * Get object 'handle' from device and store the data in newly * allocated 'object'. Start from offset and read at most maxbytes. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_getpartialobject (PTPParams* params, uint32_t handle, uint32_t offset, uint32_t maxbytes, unsigned char** object, uint32_t *len) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_GetPartialObject; ptp.Param1=handle; ptp.Param2=offset; ptp.Param3=maxbytes; ptp.Nparam=3; *len=0; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, object, len); } /** * ptp_getthumb: * params: PTPParams* * handle - Object handle * object - pointer to data area * * Get thumb for object 'handle' from device and store the data in newly * allocated 'object'. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_getthumb (PTPParams* params, uint32_t handle, unsigned char** object, unsigned int *len) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_GetThumb; ptp.Param1=handle; ptp.Nparam=1; *len = 0; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, object, len); } /** * ptp_deleteobject: * params: PTPParams* * handle - object handle * ofc - object format code (optional) * * Deletes desired objects. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_deleteobject (PTPParams* params, uint32_t handle, uint32_t ofc) { PTPContainer ptp; uint16_t ret; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_DeleteObject; ptp.Param1=handle; ptp.Param2=ofc; ptp.Nparam=2; ret = ptp_transaction(params, &ptp, PTP_DP_NODATA, 0, NULL, NULL); if (ret != PTP_RC_OK) { return ret; } /* If the object is cached and could be removed, cleanse cache. */ ptp_remove_object_from_cache(params, handle); return PTP_RC_OK; } /** * ptp_sendobjectinfo: * params: PTPParams* * uint32_t* store - destination StorageID on Responder * uint32_t* parenthandle - Parent ObjectHandle on responder * uint32_t* handle - see Return values * PTPObjectInfo* objectinfo- ObjectInfo that is to be sent * * Sends ObjectInfo of file that is to be sent via SendFileObject. * * Return values: Some PTP_RC_* code. * Upon success : uint32_t* store - Responder StorageID in which * object will be stored * uint32_t* parenthandle- Responder Parent ObjectHandle * in which the object will be stored * uint32_t* handle - Responder's reserved ObjectHandle * for the incoming object **/ uint16_t ptp_sendobjectinfo (PTPParams* params, uint32_t* store, uint32_t* parenthandle, uint32_t* handle, PTPObjectInfo* objectinfo) { uint16_t ret; PTPContainer ptp; unsigned char* oidata=NULL; uint32_t size; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_SendObjectInfo; ptp.Param1=*store; ptp.Param2=*parenthandle; ptp.Nparam=2; size=ptp_pack_OI(params, objectinfo, &oidata); ret = ptp_transaction(params, &ptp, PTP_DP_SENDDATA, size, &oidata, NULL); free(oidata); *store=ptp.Param1; *parenthandle=ptp.Param2; *handle=ptp.Param3; return ret; } /** * ptp_sendobject: * params: PTPParams* * char* object - contains the object that is to be sent * uint64_t size - object size * * Sends object to Responder. * * Return values: Some PTP_RC_* code. * */ uint16_t ptp_sendobject (PTPParams* params, unsigned char* object, uint64_t size) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_SendObject; ptp.Nparam=0; return ptp_transaction(params, &ptp, PTP_DP_SENDDATA, size, &object, NULL); } /** * ptp_sendobject_from_handler: * params: PTPParams* * PTPDataHandler* - File descriptor to read() object from * uint64_t size - File/object size * * Sends object from file descriptor by consecutive reads from this * descriptor. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_sendobject_from_handler (PTPParams* params, PTPDataHandler *handler, uint64_t size) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_SendObject; ptp.Nparam=0; return ptp_transaction_new(params, &ptp, PTP_DP_SENDDATA, size, handler); } /** * ptp_sendobject_fromfd: * params: PTPParams* * fd - File descriptor to read() object from * uint64_t size - File/object size * * Sends object from file descriptor by consecutive reads from this * descriptor. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_sendobject_fromfd (PTPParams* params, int fd, uint64_t size) { PTPContainer ptp; PTPDataHandler handler; uint16_t ret; ptp_init_fd_handler (&handler, fd); PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_SendObject; ptp.Nparam=0; ret = ptp_transaction_new(params, &ptp, PTP_DP_SENDDATA, size, &handler); ptp_exit_fd_handler (&handler); return ret; } uint16_t ptp_getdevicepropdesc (PTPParams* params, uint16_t propcode, PTPDevicePropDesc* devicepropertydesc) { PTPContainer ptp; uint16_t ret; unsigned int len; unsigned char* dpd=NULL; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_GetDevicePropDesc; ptp.Param1=propcode; ptp.Nparam=1; len=0; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &dpd, &len); if (ret == PTP_RC_OK) ptp_unpack_DPD(params, dpd, devicepropertydesc, len); free(dpd); return ret; } uint16_t ptp_getdevicepropvalue (PTPParams* params, uint16_t propcode, PTPPropertyValue* value, uint16_t datatype) { PTPContainer ptp; uint16_t ret; unsigned int len; int offset; unsigned char* dpv=NULL; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_GetDevicePropValue; ptp.Param1=propcode; ptp.Nparam=1; len=offset=0; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &dpv, &len); if (ret == PTP_RC_OK) ptp_unpack_DPV(params, dpv, &offset, len, value, datatype); free(dpv); return ret; } uint16_t ptp_setdevicepropvalue (PTPParams* params, uint16_t propcode, PTPPropertyValue *value, uint16_t datatype) { PTPContainer ptp; uint16_t ret; uint32_t size; unsigned char* dpv=NULL; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_SetDevicePropValue; ptp.Param1=propcode; ptp.Nparam=1; size=ptp_pack_DPV(params, value, &dpv, datatype); ret=ptp_transaction(params, &ptp, PTP_DP_SENDDATA, size, &dpv, NULL); free(dpv); return ret; } /** * ptp_ek_sendfileobjectinfo: * params: PTPParams* * uint32_t* store - destination StorageID on Responder * uint32_t* parenthandle - Parent ObjectHandle on responder * uint32_t* handle - see Return values * PTPObjectInfo* objectinfo- ObjectInfo that is to be sent * * Sends ObjectInfo of file that is to be sent via SendFileObject. * * Return values: Some PTP_RC_* code. * Upon success : uint32_t* store - Responder StorageID in which * object will be stored * uint32_t* parenthandle- Responder Parent ObjectHandle * in which the object will be stored * uint32_t* handle - Responder's reserved ObjectHandle * for the incoming object **/ uint16_t ptp_ek_sendfileobjectinfo (PTPParams* params, uint32_t* store, uint32_t* parenthandle, uint32_t* handle, PTPObjectInfo* objectinfo) { uint16_t ret; PTPContainer ptp; unsigned char* oidata=NULL; uint32_t size; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_EK_SendFileObjectInfo; ptp.Param1=*store; ptp.Param2=*parenthandle; ptp.Nparam=2; size=ptp_pack_OI(params, objectinfo, &oidata); ret=ptp_transaction(params, &ptp, PTP_DP_SENDDATA, size, &oidata, NULL); free(oidata); *store=ptp.Param1; *parenthandle=ptp.Param2; *handle=ptp.Param3; return ret; } /** * ptp_ek_getserial: * params: PTPParams* * char** serial - contains the serial number of the camera * uint32_t* size - contains the string length * * Gets the serial number from the device. (ptp serial) * * Return values: Some PTP_RC_* code. * */ uint16_t ptp_ek_getserial (PTPParams* params, unsigned char **data, unsigned int *size) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_EK_GetSerial; ptp.Nparam = 0; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, data, size); } /** * ptp_ek_setserial: * params: PTPParams* * char* serial - contains the new serial number * uint32_t size - string length * * Sets the serial number of the device. (ptp serial) * * Return values: Some PTP_RC_* code. * */ uint16_t ptp_ek_setserial (PTPParams* params, unsigned char *data, unsigned int size) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_EK_SetSerial; ptp.Nparam = 0; return ptp_transaction(params, &ptp, PTP_DP_SENDDATA, size, &data, NULL); } /* unclear what it does yet */ uint16_t ptp_ek_9007 (PTPParams* params, unsigned char **data, unsigned int *size) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code = 0x9007; ptp.Nparam = 0; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, data, size); } /* unclear what it does yet */ uint16_t ptp_ek_9009 (PTPParams* params, uint32_t *p1, uint32_t *p2) { PTPContainer ptp; uint16_t ret; PTP_CNT_INIT(ptp); ptp.Code = 0x9009; ptp.Nparam = 0; ret = ptp_transaction(params, &ptp, PTP_DP_NODATA, 0, NULL, NULL); *p1 = ptp.Param1; *p2 = ptp.Param2; return ret; } /* unclear yet, but I guess it returns the info from 9008 */ uint16_t ptp_ek_900c (PTPParams* params, unsigned char **data, unsigned int *size) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code = 0x900c; ptp.Nparam = 0; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, data, size); /* returned data is 16bit,16bit,32bit,32bit */ } /** * ptp_ek_settext: * params: PTPParams* * PTPEKTextParams* - contains the texts to display. * * Displays the specified texts on the TFT of the camera. * * Return values: Some PTP_RC_* code. * */ uint16_t ptp_ek_settext (PTPParams* params, PTPEKTextParams *text) { PTPContainer ptp; uint16_t ret; unsigned int size; unsigned char *data; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_EK_SetText; ptp.Nparam = 0; if (0 == (size = ptp_pack_EK_text(params, text, &data))) return PTP_ERROR_BADPARAM; ret = ptp_transaction(params, &ptp, PTP_DP_SENDDATA, size, &data, NULL); free(data); return ret; } /** * ptp_ek_sendfileobject: * params: PTPParams* * char* object - contains the object that is to be sent * uint32_t size - object size * * Sends object to Responder. * * Return values: Some PTP_RC_* code. * */ uint16_t ptp_ek_sendfileobject (PTPParams* params, unsigned char* object, uint32_t size) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_EK_SendFileObject; ptp.Nparam=0; return ptp_transaction(params, &ptp, PTP_DP_SENDDATA, size, &object, NULL); } /** * ptp_ek_sendfileobject_from_handler: * params: PTPParams* * PTPDataHandler* handler - contains the handler of the object that is to be sent * uint32_t size - object size * * Sends object to Responder. * * Return values: Some PTP_RC_* code. * */ uint16_t ptp_ek_sendfileobject_from_handler (PTPParams* params, PTPDataHandler*handler, uint32_t size) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_EK_SendFileObject; ptp.Nparam=0; return ptp_transaction_new(params, &ptp, PTP_DP_SENDDATA, size, handler); } /************************************************************************* * * Canon PTP extensions support * * (C) Nikolai Kopanygin 2003 * *************************************************************************/ /** * ptp_canon_getpartialobjectinfo: * params: PTPParams* * uint32_t handle - ObjectHandle * uint32_t p2 - Not fully understood parameter * 0 - returns full size * 1 - returns thumbnail size (or EXIF?) * * Gets form the responder the size of the specified object. * * Return values: Some PTP_RC_* code. * Upon success : uint32_t* size - The object size * uint32_t* rp2 - Still unknown return parameter * (perhaps upper 32bit of size) * * **/ uint16_t ptp_canon_getpartialobjectinfo (PTPParams* params, uint32_t handle, uint32_t p2, uint32_t* size, uint32_t* rp2) { uint16_t ret; PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CANON_GetPartialObjectInfo; ptp.Param1=handle; ptp.Param2=p2; ptp.Nparam=2; ret=ptp_transaction(params, &ptp, PTP_DP_NODATA, 0, NULL, NULL); *size=ptp.Param1; *rp2=ptp.Param2; return ret; } /** * ptp_canon_get_mac_address: * params: PTPParams* * value 0 works. * Gets the MAC address of the wireless transmitter. * * Return values: Some PTP_RC_* code. * Upon success : unsigned char* mac - The MAC address * **/ uint16_t ptp_canon_get_mac_address (PTPParams* params, unsigned char **mac) { PTPContainer ptp; unsigned int size = 0; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CANON_GetMACAddress; ptp.Nparam=0; *mac = NULL; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, mac, &size); } /** * ptp_canon_get_directory: * params: PTPParams* * Gets the full directory of the camera. * * Return values: Some PTP_RC_* code. * Upon success : PTPObjectHandles *handles - filled out with handles * PTPObjectInfo **oinfos - allocated array of PTP Object Infos * uint32_t **flags - allocated array of CANON Flags * **/ uint16_t ptp_canon_get_directory (PTPParams* params, PTPObjectHandles *handles, PTPObjectInfo **oinfos, /* size(handles->n) */ uint32_t **flags /* size(handles->n) */ ) { PTPContainer ptp; unsigned char *dir = NULL; unsigned int size = 0; uint16_t ret; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CANON_GetDirectory; ptp.Nparam=0; ret = ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &dir, &size); if (ret != PTP_RC_OK) return ret; ret = ptp_unpack_canon_directory(params, dir, ptp.Param1, handles, oinfos, flags); free (dir); return ret; } /** * ptp_canon_gettreeinfo: * params: PTPParams* * uint32_t *out * * Switches the camera display to on and lets the user * select what to transfer. Sends a 0xc011 event when started * and 0xc013 if direct transfer aborted. * * Return values: Some PTP_RC_* code. * **/ uint16_t ptp_canon_gettreeinfo (PTPParams* params, uint32_t *out) { PTPContainer ptp; uint16_t ret; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_CANON_GetTreeInfo; ptp.Nparam = 1; ptp.Param1 = 0xf; ret = ptp_transaction(params, &ptp, PTP_DP_NODATA, 0, NULL, NULL); if ((ret == PTP_RC_OK) && (ptp.Nparam>0)) *out = ptp.Param1; return ret; } /** * ptp_canon_getpairinginfo: * params: PTPParams* * int nr * * Get the pairing information. * * Return values: Some PTP_RC_* code. * **/ uint16_t ptp_canon_getpairinginfo (PTPParams* params, uint32_t nr, unsigned char **data, unsigned int *size) { PTPContainer ptp; uint16_t ret; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_CANON_GetPairingInfo; ptp.Nparam = 1; ptp.Param1 = nr; *data = NULL; *size = 0; ret = ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, data, size); if (ret != PTP_RC_OK) return ret; return PTP_RC_OK; } /** * ptp_canon_get_target_handles: * params: PTPParams* * PTPCanon_directtransfer_entry **out * unsigned int *outsize * * Retrieves direct transfer entries specifying the images to transfer * from the camera (to be retrieved after 0xc011 event). * * Return values: Some PTP_RC_* code. * **/ uint16_t ptp_canon_gettreesize (PTPParams* params, PTPCanon_directtransfer_entry **entries, unsigned int *cnt) { PTPContainer ptp; uint16_t ret; unsigned char *out = NULL, *cur; int i; unsigned int size; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_CANON_GetTreeSize; ptp.Nparam = 0; ret = ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &out, &size); if (ret != PTP_RC_OK) return ret; *cnt = dtoh32a(out); *entries = malloc(sizeof(PTPCanon_directtransfer_entry)*(*cnt)); if (!*entries) { free (out); return PTP_RC_GeneralError; } cur = out+4; for (i=0;i<*cnt;i++) { unsigned char len; (*entries)[i].oid = dtoh32a(cur); (*entries)[i].str = ptp_unpack_string(params, cur, 4, &len); cur += 4+(cur[4]*2+1); } free (out); return PTP_RC_OK; } /** * ptp_canon_checkevent: * params: PTPParams* * * The camera has a FIFO stack, in which it accumulates events. * Partially these events are communicated also via the USB interrupt pipe * according to the PTP USB specification, partially not. * This operation returns from the device a block of data, empty, * if the event stack is empty, or filled with an event's data otherwise. * The event is removed from the stack in the latter case. * The Remote Capture app sends this command to the camera all the time * of connection, filling with it the gaps between other operations. * * Return values: Some PTP_RC_* code. * Upon success : PTPUSBEventContainer* event - is filled with the event data * if any * int *isevent - returns 1 in case of event * or 0 otherwise **/ uint16_t ptp_canon_checkevent (PTPParams* params, PTPContainer* event, int* isevent) { uint16_t ret; PTPContainer ptp; unsigned char *evdata = NULL; unsigned int len; *isevent=0; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CANON_CheckEvent; ptp.Nparam=0; len=0; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &evdata, &len); if (evdata!=NULL) { if (ret == PTP_RC_OK) { ptp_unpack_EC(params, evdata, event, len); *isevent=1; } free(evdata); } return ret; } uint16_t ptp_check_event (PTPParams *params) { PTPContainer event; uint16_t ret; if ( (params->deviceinfo.VendorExtensionID == PTP_VENDOR_NIKON) && ptp_operation_issupported(params, PTP_OC_NIKON_CheckEvent) ) { int evtcnt; PTPContainer *xevent = NULL; ret = ptp_nikon_check_event(params, &xevent, &evtcnt); if (ret != PTP_RC_OK) return ret; if (evtcnt) { if (params->nrofevents) params->events = realloc(params->events, sizeof(PTPContainer)*(evtcnt+params->nrofevents)); else params->events = malloc(sizeof(PTPContainer)*evtcnt); memcpy (¶ms->events[params->nrofevents],xevent,evtcnt*sizeof(PTPContainer)); params->nrofevents += evtcnt; free (xevent); } return PTP_RC_OK; } /* should not get here ... EOS has no normal PTP events and another queue handling. */ if ( (params->deviceinfo.VendorExtensionID == PTP_VENDOR_CANON) && ptp_operation_issupported(params, PTP_OC_CANON_EOS_GetEvent) ) { return PTP_RC_OK; } if ( (params->deviceinfo.VendorExtensionID == PTP_VENDOR_CANON) && ptp_operation_issupported(params, PTP_OC_CANON_CheckEvent) ) { int isevent; ret = ptp_canon_checkevent (params,&event,&isevent); if (ret!=PTP_RC_OK) return ret; if (isevent) goto store_event; /* Event Emulate Mode 0 (unset) and 1-5 get interrupt events. 6-7 does not. */ if (params->canon_event_mode > 5) return ret; /* FIXME: fallthrough or return? */ #ifdef __APPLE__ /* the libusb 1 on darwin currently does not like polling * for interrupts, they have no timeout for it. 2010/08/23 * Check back in 2011 or so. -Marcus */ return ret; #endif } ret = params->event_check(params,&event); store_event: if (ret == PTP_RC_OK) { ptp_debug (params, "event: nparams=0x%X, code=0x%X, trans_id=0x%X, p1=0x%X, p2=0x%X, p3=0x%X", event.Nparam,event.Code,event.Transaction_ID, event.Param1, event.Param2, event.Param3); if (params->nrofevents) params->events = realloc(params->events, sizeof(PTPContainer)*(params->nrofevents+1)); else params->events = malloc(sizeof(PTPContainer)*1); memcpy (¶ms->events[params->nrofevents],&event,1*sizeof(PTPContainer)); params->nrofevents += 1; } if (ret == PTP_ERROR_TIMEOUT) /* ok, just new events */ ret = PTP_RC_OK; return ret; } int ptp_get_one_event(PTPParams *params, PTPContainer *event) { if (!params->nrofevents) return 0; memcpy (event, params->events, sizeof(PTPContainer)); memmove (params->events, params->events+1, sizeof(PTPContainer)*(params->nrofevents-1)); /* do not realloc on shrink. */ params->nrofevents--; if (!params->nrofevents) { free (params->events); params->events = NULL; } return 1; } /** * ptp_canon_eos_getevent: * * This retrieves configuration status/updates/changes * on EOS cameras. It reads a datablock which has a list of variable * sized structures. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ uint16_t ptp_canon_eos_getevent (PTPParams* params, PTPCanon_changes_entry **entries, int *nrofentries) { PTPContainer ptp; uint16_t ret; unsigned int size = 0; unsigned char *data = NULL; *nrofentries = 0; *entries = NULL; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_CANON_EOS_GetEvent; ptp.Nparam = 0; ret = ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &data, &size); if (ret != PTP_RC_OK) return ret; *nrofentries = ptp_unpack_CANON_changes(params,data,size,entries); free (data); return PTP_RC_OK; } uint16_t ptp_check_eos_events (PTPParams *params) { uint16_t ret; PTPCanon_changes_entry *entries = NULL, *nentries; int nrofentries = 0; while (1) { /* call it repeatedly until the camera does not report any */ ret = ptp_canon_eos_getevent (params, &entries, &nrofentries); if (ret != PTP_RC_OK) return ret; if (!nrofentries) return PTP_RC_OK; if (params->nrofbacklogentries) { nentries = realloc(params->backlogentries,sizeof(entries[0])*(params->nrofbacklogentries+nrofentries)); if (!nentries) return PTP_RC_GeneralError; params->backlogentries = nentries; memcpy (nentries+params->nrofbacklogentries, entries, nrofentries*sizeof(entries[0])); params->nrofbacklogentries += nrofentries; free (entries); } else { params->backlogentries = entries; params->nrofbacklogentries = nrofentries; } } return PTP_RC_OK; } int ptp_get_one_eos_event (PTPParams *params, PTPCanon_changes_entry *entry) { if (!params->nrofbacklogentries) return 0; memcpy (entry, params->backlogentries, sizeof(*entry)); if (params->nrofbacklogentries > 1) { memmove (params->backlogentries,params->backlogentries+1,sizeof(*entry)*(params->nrofbacklogentries-1)); params->nrofbacklogentries--; } else { free (params->backlogentries); params->backlogentries = NULL; params->nrofbacklogentries = 0; } return 1; } uint16_t ptp_canon_eos_getdevicepropdesc (PTPParams* params, uint16_t propcode, PTPDevicePropDesc *dpd) { int i; for (i=0;inrofcanon_props;i++) if (params->canon_props[i].proptype == propcode) break; if (params->nrofcanon_props == i) return PTP_RC_Undefined; memcpy (dpd, ¶ms->canon_props[i].dpd, sizeof (*dpd)); if (dpd->FormFlag == PTP_DPFF_Enumeration) { /* need to duplicate the Enumeration alloc */ dpd->FORM.Enum.SupportedValue = malloc (sizeof (PTPPropertyValue)*dpd->FORM.Enum.NumberOfValues); memcpy (dpd->FORM.Enum.SupportedValue, params->canon_props[i].dpd.FORM.Enum.SupportedValue, sizeof (PTPPropertyValue)*dpd->FORM.Enum.NumberOfValues ); } if (dpd->DataType == PTP_DTC_STR) { dpd->FactoryDefaultValue.str = strdup( params->canon_props[i].dpd.FactoryDefaultValue.str ); dpd->CurrentValue.str = strdup( params->canon_props[i].dpd.CurrentValue.str ); } return PTP_RC_OK; } uint16_t ptp_canon_eos_getstorageids (PTPParams* params, PTPStorageIDs* storageids) { PTPContainer ptp; unsigned int len = 0; uint16_t ret; unsigned char* sids=NULL; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_CANON_EOS_GetStorageIDs; ptp.Nparam = 0; ret = ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &sids, &len); if (ret == PTP_RC_OK) ptp_unpack_SIDs(params, sids, storageids, len); free(sids); return ret; } uint16_t ptp_canon_eos_getstorageinfo (PTPParams* params, uint32_t p1, unsigned char **data, unsigned int *size) { PTPContainer ptp; uint16_t ret; *size = 0; *data = NULL; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_CANON_EOS_GetStorageInfo; ptp.Nparam = 1; ptp.Param1 = p1; ret = ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, data, size); /* FIXME: do stuff with data */ return ret; } uint16_t ptp_canon_eos_getobjectinfoex ( PTPParams* params, uint32_t storageid, uint32_t oid, uint32_t unk, PTPCANONFolderEntry **entries, unsigned int *nrofentries ) { PTPContainer ptp; unsigned int i, size = 0; unsigned char *data, *xdata; uint16_t ret; data = NULL; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_CANON_EOS_GetObjectInfoEx; ptp.Nparam = 3; ptp.Param1 = storageid; ptp.Param2 = oid; ptp.Param3 = unk; ret = ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &data, &size); if (ret != PTP_RC_OK) return ret; *nrofentries = dtoh32a(data); *entries = malloc(*nrofentries * sizeof(PTPCANONFolderEntry)); if (!*entries) return PTP_RC_GeneralError; xdata = data+sizeof(uint32_t); for (i=0;i<*nrofentries;i++) { ptp_unpack_Canon_EOS_FE (params, &xdata[4], &((*entries)[i])); xdata += dtoh32a(xdata); } return PTP_RC_OK; } /** * ptp_canon_eos_getpartialobject: * * This retrieves a part of an PTP object which you specify as object id. * The id originates from 0x9116 call. * After finishing it, we seem to need to call ptp_canon_eos_enddirecttransfer. * * params: PTPParams* * oid Object ID * offset The offset where to start the data transfer * xsize Size in bytes of the transfer to do * data Pointer that receives the malloc()ed memory of the transfer. * * Return values: Some PTP_RC_* code. * */ uint16_t ptp_canon_eos_getpartialobject (PTPParams* params, uint32_t oid, uint32_t offset, uint32_t xsize, unsigned char**data) { PTPContainer ptp; unsigned int size = 0; *data = NULL; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_CANON_EOS_GetPartialObject; ptp.Nparam = 3; ptp.Param1 = oid; ptp.Param2 = offset; ptp.Param3 = xsize; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, data, &size); } uint16_t ptp_canon_eos_setdevicepropvalueex (PTPParams* params, unsigned char* data, unsigned int size) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_CANON_EOS_SetDevicePropValueEx; ptp.Nparam = 0; return ptp_transaction(params, &ptp, PTP_DP_SENDDATA, size, &data, NULL); } uint16_t ptp_canon_eos_setdevicepropvalue (PTPParams* params, uint16_t propcode, PTPPropertyValue *value, uint16_t datatype ) { PTPContainer ptp; uint16_t ret; int i; unsigned char *data; unsigned int size; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_CANON_EOS_SetDevicePropValueEx; ptp.Nparam = 0; for (i=0;inrofcanon_props;i++) if (params->canon_props[i].proptype == propcode) break; if (params->nrofcanon_props == i) return PTP_RC_Undefined; switch (propcode) { case PTP_DPC_CANON_EOS_ImageFormat: case PTP_DPC_CANON_EOS_ImageFormatCF: case PTP_DPC_CANON_EOS_ImageFormatSD: case PTP_DPC_CANON_EOS_ImageFormatExtHD: /* special handling of ImageFormat properties */ size = 8 + ptp_pack_EOS_ImageFormat( params, NULL, value->u16 ); data = malloc( size ); if (!data) return PTP_RC_GeneralError; params->canon_props[i].dpd.CurrentValue.u16 = value->u16; ptp_pack_EOS_ImageFormat( params, data + 8, value->u16 ); break; case PTP_DPC_CANON_EOS_CustomFuncEx: /* special handling of CustomFuncEx properties */ ptp_debug (params, "ptp2/ptp_canon_eos_setdevicepropvalue: setting EOS prop %x to %s",propcode,value->str); size = 8 + ptp_pack_EOS_CustomFuncEx( params, NULL, value->str ); data = malloc( size ); if (!data) return PTP_RC_GeneralError; params->canon_props[i].dpd.CurrentValue.str = strdup( value->str ); ptp_pack_EOS_CustomFuncEx( params, data + 8, value->str ); break; default: if (datatype != PTP_DTC_STR) { data = calloc(sizeof(uint32_t),3); if (!data) return PTP_RC_GeneralError; size = sizeof(uint32_t)*3; } else { size = strlen(value->str) + 1 + 8; data = calloc(sizeof(char),size); if (!data) return PTP_RC_GeneralError; } switch (datatype) { case PTP_DTC_INT8: case PTP_DTC_UINT8: /*fprintf (stderr, "%x -> %d\n", propcode, value->u8);*/ htod8a(&data[8], value->u8); params->canon_props[i].dpd.CurrentValue.u8 = value->u8; break; case PTP_DTC_UINT16: case PTP_DTC_INT16: /*fprintf (stderr, "%x -> %d\n", propcode, value->u16);*/ htod16a(&data[8], value->u16); params->canon_props[i].dpd.CurrentValue.u16 = value->u16; break; case PTP_DTC_INT32: case PTP_DTC_UINT32: /*fprintf (stderr, "%x -> %d\n", propcode, value->u32);*/ htod32a(&data[8], value->u32); params->canon_props[i].dpd.CurrentValue.u32 = value->u32; break; case PTP_DTC_STR: strcpy((char*)data + 8, value->str); free (params->canon_props[i].dpd.CurrentValue.str); params->canon_props[i].dpd.CurrentValue.str = strdup(value->str); break; } } htod32a(&data[0], size); htod32a(&data[4], propcode); ret = ptp_transaction(params, &ptp, PTP_DP_SENDDATA, size, &data, NULL); free (data); return ret; } /** * ptp_canon_getpartialobject: * * This operation is used to read from the device a data * block of an object from a specified offset. * * params: PTPParams* * uint32_t handle - the handle of the requested object * uint32_t offset - the offset in bytes from the beginning of the object * uint32_t size - the requested size of data block to read * uint32_t pos - 1 for the first block, 2 - for a block in the middle, * 3 - for the last block * * Return values: Some PTP_RC_* code. * char **block - the pointer to the block of data read * uint32_t* readnum - the number of bytes read * **/ uint16_t ptp_canon_getpartialobject (PTPParams* params, uint32_t handle, uint32_t offset, uint32_t size, uint32_t pos, unsigned char** block, uint32_t* readnum) { uint16_t ret; PTPContainer ptp; unsigned char *data=NULL; unsigned int len; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CANON_GetPartialObjectEx; ptp.Param1=handle; ptp.Param2=offset; ptp.Param3=size; ptp.Param4=pos; ptp.Nparam=4; len=0; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &data, &len); if (ret==PTP_RC_OK) { *block=data; *readnum=ptp.Param1; } return ret; } /** * ptp_canon_getviewfinderimage: * * This operation can be used to read the image which is currently * in the camera's viewfinder. The image size is 320x240, format is JPEG. * Of course, prior to calling this operation, one must turn the viewfinder * on with the CANON_ViewfinderOn command. * Invoking this operation many times, one can get live video from the camera! * * params: PTPParams* * * Return values: Some PTP_RC_* code. * char **image - the pointer to the read image * unit32_t *size - the size of the image in bytes * **/ uint16_t ptp_canon_getviewfinderimage (PTPParams* params, unsigned char** image, uint32_t* size) { uint16_t ret; PTPContainer ptp; unsigned int len; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CANON_GetViewfinderImage; ptp.Nparam=0; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, image, &len); if (ret==PTP_RC_OK) *size=ptp.Param1; return ret; } /** * ptp_canon_getchanges: * * This is an interesting operation, about the effect of which I am not sure. * This command is called every time when a device property has been changed * with the SetDevicePropValue operation, and after some other operations. * This operation reads the array of Device Properties which have been changed * by the previous operation. * Probably, this operation is even required to make those changes work. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * uint16_t** props - the pointer to the array of changed properties * uint32_t* propnum - the number of elements in the *props array * **/ uint16_t ptp_canon_getchanges (PTPParams* params, uint16_t** props, uint32_t* propnum) { uint16_t ret; PTPContainer ptp; unsigned char* data=NULL; unsigned int len; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CANON_GetChanges; ptp.Nparam=0; len=0; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &data, &len); if (ret == PTP_RC_OK) *propnum=ptp_unpack_uint16_t_array(params,data,0,props); free(data); return ret; } /** * ptp_canon_getobjectinfo: * * This command reads a specified object's record in a device's filesystem, * or the records of all objects belonging to a specified folder (association). * * params: PTPParams* * uint32_t store - StorageID, * uint32_t p2 - Yet unknown (0 value works OK) * uint32_t parent - Parent Object Handle * # If Parent Object Handle is 0xffffffff, * # the Parent Object is the top level folder. * uint32_t handle - Object Handle * # If Object Handle is 0, the records of all objects * # belonging to the Parent Object are read. * # If Object Handle is not 0, only the record of this * # Object is read. * * Return values: Some PTP_RC_* code. * PTPCANONFolderEntry** entries - the pointer to the folder entry array * uint32_t* entnum - the number of elements of the array * **/ uint16_t ptp_canon_getobjectinfo (PTPParams* params, uint32_t store, uint32_t p2, uint32_t parent, uint32_t handle, PTPCANONFolderEntry** entries, uint32_t* entnum) { uint16_t ret; PTPContainer ptp; unsigned char *data = NULL; unsigned int len; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CANON_GetObjectInfoEx; ptp.Param1=store; ptp.Param2=p2; ptp.Param3=parent; ptp.Param4=handle; ptp.Nparam=4; len=0; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &data, &len); if (ret == PTP_RC_OK) { int i; *entnum=ptp.Param1; *entries=calloc(*entnum, sizeof(PTPCANONFolderEntry)); if (*entries!=NULL) { for(i=0; i<(*entnum); i++) ptp_unpack_Canon_FE(params, data+i*PTP_CANON_FolderEntryLen, &((*entries)[i]) ); } else { ret=PTP_ERROR_IO; /* Cannot allocate memory */ } } free(data); return ret; } /** * ptp_canon_get_objecthandle_by_name: * * This command looks up the specified object on the camera. * * Format is "A:\\PATH". * * The 'A' is the VolumeLabel from GetStorageInfo, * my IXUS has "A" for the card and "V" for internal memory. * * params: PTPParams* * char* name - path name * * Return values: Some PTP_RC_* code. * uint32_t *oid - PTP object id. * **/ uint16_t ptp_canon_get_objecthandle_by_name (PTPParams* params, char* name, uint32_t* objectid) { uint16_t ret; PTPContainer ptp; unsigned char *data = NULL; uint8_t len; PTP_CNT_INIT (ptp); ptp.Code=PTP_OC_CANON_GetObjectHandleByName; ptp.Nparam=0; len=0; data = malloc (2*(strlen(name)+1)+2); memset (data, 0, 2*(strlen(name)+1)+2); ptp_pack_string (params, name, data, 0, &len); ret=ptp_transaction (params, &ptp, PTP_DP_SENDDATA, (len+1)*2+1, &data, NULL); free (data); *objectid = ptp.Param1; return ret; } /** * ptp_canon_get_customize_data: * * This command downloads the specified theme slot, including jpegs * and wav files. * * params: PTPParams* * uint32_t themenr - nr of theme * * Return values: Some PTP_RC_* code. * unsigned char **data - pointer to data pointer * unsigned int *size - size of data returned * **/ uint16_t ptp_canon_get_customize_data (PTPParams* params, uint32_t themenr, unsigned char **data, unsigned int *size) { PTPContainer ptp; *data = NULL; *size = 0; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_CANON_GetCustomizeData; ptp.Param1 = themenr; ptp.Nparam = 1; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, data, size); } uint16_t ptp_nikon_curve_download (PTPParams* params, unsigned char **data, unsigned int *size) { PTPContainer ptp; *data = NULL; *size = 0; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_NIKON_CurveDownload; ptp.Nparam = 0; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, data, size); } /** * ptp_canon_get_vendorpropcodes: * * This command downloads the vendor specific property codes. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * unsigned char **data - pointer to data pointer * unsigned int *size - size of data returned * **/ uint16_t ptp_nikon_get_vendorpropcodes (PTPParams* params, uint16_t **props, unsigned int *size) { PTPContainer ptp; uint16_t ret; unsigned char *xdata = NULL; unsigned int xsize; *props = NULL; *size = 0; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_NIKON_GetVendorPropCodes; ptp.Nparam = 0; ret = ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &xdata, &xsize); if (ret == PTP_RC_OK) *size = ptp_unpack_uint16_t_array(params,xdata,0,props); free (xdata); return ret; } uint16_t ptp_nikon_getfileinfoinblock ( PTPParams* params, uint32_t p1, uint32_t p2, uint32_t p3, unsigned char **data, unsigned int *size ) { PTPContainer ptp; *data = NULL; *size = 0; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_NIKON_GetFileInfoInBlock; ptp.Nparam = 3; ptp.Param1 = p1; ptp.Param2 = p2; ptp.Param3 = p3; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, data, size); } /** * ptp_nikon_get_liveview_image: * * This command gets a LiveView image from newer Nikons DSLRs. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ uint16_t ptp_nikon_get_liveview_image (PTPParams* params, unsigned char **data, unsigned int *size) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_NIKON_GetLiveViewImg; ptp.Nparam=0; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, data, size); } /** * ptp_nikon_get_preview_image: * * This command gets a Preview image from newer Nikons DSLRs. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ uint16_t ptp_nikon_get_preview_image (PTPParams* params, unsigned char **xdata, unsigned int *xsize, uint32_t *handle) { PTPContainer ptp; uint16_t ret; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_NIKON_GetPreviewImg; ptp.Nparam=0; ret = ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, xdata, xsize); if (ret == PTP_RC_OK) { if (ptp.Nparam > 0) *handle = ptp.Param1; } return ret; } /** * ptp_canon_eos_get_viewfinder_image: * * This command gets a Viewfinder image from newer Nikons DSLRs. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ uint16_t ptp_canon_eos_get_viewfinder_image (PTPParams* params, unsigned char **data, unsigned int *size) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CANON_EOS_GetViewFinderData; ptp.Nparam=1; ptp.Param1=0x00100000; /* from trace */ return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, data, size); } uint16_t ptp_canon_eos_get_viewfinder_image_handler (PTPParams* params, PTPDataHandler*handler) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CANON_EOS_GetViewFinderData; ptp.Nparam=1; ptp.Param1=0x00100000; /* from trace */ return ptp_transaction_new(params, &ptp, PTP_DP_GETDATA, 0, handler); } /** * ptp_nikon_check_event: * * This command checks the event queue on the Nikon. * * params: PTPParams* * PTPUSBEventContainer **event - list of usb events. * int *evtcnt - number of usb events in event structure. * * Return values: Some PTP_RC_* code. * **/ uint16_t ptp_nikon_check_event (PTPParams* params, PTPContainer** event, int* evtcnt) { PTPContainer ptp; uint16_t ret; unsigned char *data = NULL; unsigned int size = 0; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_NIKON_CheckEvent; ptp.Nparam=0; *evtcnt = 0; ret = ptp_transaction (params, &ptp, PTP_DP_GETDATA, 0, &data, &size); if (ret == PTP_RC_OK) { ptp_unpack_Nikon_EC (params, data, size, event, evtcnt); free (data); } return ret; } /** * ptp_nikon_getptpipinfo: * * This command gets the ptpip info data. * * params: PTPParams* * unsigned char *data - data * unsigned int size - size of returned data * * Return values: Some PTP_RC_* code. * **/ uint16_t ptp_nikon_getptpipinfo (PTPParams* params, unsigned char **data, unsigned int *size) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_NIKON_GetDevicePTPIPInfo; ptp.Nparam=0; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, data, size); } /** * ptp_nikon_getwifiprofilelist: * * This command gets the wifi profile list. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ uint16_t ptp_nikon_getwifiprofilelist (PTPParams* params) { PTPContainer ptp; unsigned char* data; unsigned int size; unsigned int pos; unsigned int profn; unsigned int n; char* buffer; uint8_t len; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_NIKON_GetProfileAllData; ptp.Nparam=0; size = 0; data = NULL; CHECK_PTP_RC(ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &data, &size)); if (size < 2) return PTP_RC_Undefined; /* FIXME: Add more precise error code */ params->wifi_profiles_version = data[0]; params->wifi_profiles_number = data[1]; if (params->wifi_profiles) free(params->wifi_profiles); params->wifi_profiles = malloc(params->wifi_profiles_number*sizeof(PTPNIKONWifiProfile)); memset(params->wifi_profiles, 0, params->wifi_profiles_number*sizeof(PTPNIKONWifiProfile)); pos = 2; profn = 0; while (profn < params->wifi_profiles_number && pos < size) { if (pos+6 >= size) return PTP_RC_Undefined; params->wifi_profiles[profn].id = data[pos++]; params->wifi_profiles[profn].valid = data[pos++]; n = dtoh32a(&data[pos]); pos += 4; if (pos+n+4 >= size) return PTP_RC_Undefined; strncpy(params->wifi_profiles[profn].profile_name, (char*)&data[pos], n); params->wifi_profiles[profn].profile_name[16] = '\0'; pos += n; params->wifi_profiles[profn].display_order = data[pos++]; params->wifi_profiles[profn].device_type = data[pos++]; params->wifi_profiles[profn].icon_type = data[pos++]; buffer = ptp_unpack_string(params, data, pos, &len); strncpy(params->wifi_profiles[profn].creation_date, buffer, sizeof(params->wifi_profiles[profn].creation_date)); free (buffer); pos += (len*2+1); if (pos+1 >= size) return PTP_RC_Undefined; /* FIXME: check if it is really last usage date */ buffer = ptp_unpack_string(params, data, pos, &len); strncpy(params->wifi_profiles[profn].lastusage_date, buffer, sizeof(params->wifi_profiles[profn].lastusage_date)); free (buffer); pos += (len*2+1); if (pos+5 >= size) return PTP_RC_Undefined; n = dtoh32a(&data[pos]); pos += 4; if (pos+n >= size) return PTP_RC_Undefined; strncpy(params->wifi_profiles[profn].essid, (char*)&data[pos], n); params->wifi_profiles[profn].essid[32] = '\0'; pos += n; pos += 1; profn++; } #if 0 PTPNIKONWifiProfile test; memset(&test, 0, sizeof(PTPNIKONWifiProfile)); strcpy(test.profile_name, "MyTest"); test.icon_type = 1; strcpy(test.essid, "nikon"); test.ip_address = 10 + 11 << 16 + 11 << 24; test.subnet_mask = 24; test.access_mode = 1; test.wifi_channel = 1; test.key_nr = 1; ptp_nikon_writewifiprofile(params, &test); #endif return PTP_RC_OK; } /** * ptp_nikon_writewifiprofile: * * This command gets the ptpip info data. * * params: PTPParams* * unsigned int profilenr - profile number * unsigned char *data - data * unsigned int size - size of returned data * * Return values: Some PTP_RC_* code. * **/ uint16_t ptp_nikon_writewifiprofile (PTPParams* params, PTPNIKONWifiProfile* profile) { unsigned char guid[16]; PTPContainer ptp; unsigned char buffer[1024]; unsigned char* data = buffer; int size = 0; int i; uint8_t len; int profilenr = -1; ptp_nikon_getptpipguid(guid); if (!params->wifi_profiles) CHECK_PTP_RC(ptp_nikon_getwifiprofilelist(params)); for (i = 0; i < params->wifi_profiles_number; i++) { if (!params->wifi_profiles[i].valid) { profilenr = params->wifi_profiles[i].id; break; } } if (profilenr == -1) { /* No free profile! */ return PTP_RC_StoreFull; } memset(buffer, 0, 1024); buffer[0x00] = 0x64; /* Version */ /* Profile name */ htod32a(&buffer[0x01], 17); /* 16 as third parameter, so there will always be a null-byte in the end */ strncpy((char*)&buffer[0x05], profile->profile_name, 16); buffer[0x16] = 0x00; /* Display order */ buffer[0x17] = profile->device_type; buffer[0x18] = profile->icon_type; /* FIXME: Creation date: put a real date here */ ptp_pack_string(params, "19990909T090909", data, 0x19, &len); /* IP parameters */ *((unsigned int*)&buffer[0x3A]) = profile->ip_address; /* Do not reverse bytes */ buffer[0x3E] = profile->subnet_mask; *((unsigned int*)&buffer[0x3F]) = profile->gateway_address; /* Do not reverse bytes */ buffer[0x43] = profile->address_mode; /* Wifi parameters */ buffer[0x44] = profile->access_mode; buffer[0x45] = profile->wifi_channel; htod32a(&buffer[0x46], 33); /* essid */ /* 32 as third parameter, so there will always be a null-byte in the end */ strncpy((char*)&buffer[0x4A], profile->essid, 32); buffer[0x6B] = profile->authentification; buffer[0x6C] = profile->encryption; htod32a(&buffer[0x6D], 64); for (i = 0; i < 64; i++) { buffer[0x71+i] = profile->key[i]; } buffer[0xB1] = profile->key_nr; memcpy(&buffer[0xB2], guid, 16); switch(profile->encryption) { case 1: /* WEP 64bit */ htod16a(&buffer[0xC2], 5); /* (64-24)/8 = 5 */ break; case 2: /* WEP 128bit */ htod16a(&buffer[0xC2], 13); /* (128-24)/8 = 13 */ break; default: htod16a(&buffer[0xC2], 0); } size = 0xC4; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_NIKON_SendProfileData; ptp.Nparam=1; ptp.Param1=profilenr; return ptp_transaction(params, &ptp, PTP_DP_SENDDATA, size, &data, NULL); } /** * ptp_mtp_getobjectpropssupported: * * This command gets the object properties possible from the device. * * params: PTPParams* * uint ofc - object format code * unsigned int *propnum - number of elements in returned array * uint16_t *props - array of supported properties * * Return values: Some PTP_RC_* code. * **/ uint16_t ptp_mtp_getobjectpropssupported (PTPParams* params, uint16_t ofc, uint32_t *propnum, uint16_t **props ) { PTPContainer ptp; uint16_t ret; unsigned char *data = NULL; unsigned int size = 0; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_MTP_GetObjectPropsSupported; ptp.Nparam = 1; ptp.Param1 = ofc; ret = ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &data, &size); if (ret == PTP_RC_OK) *propnum=ptp_unpack_uint16_t_array(params,data,0,props); free(data); return ret; } /** * ptp_mtp_getobjectpropdesc: * * This command gets the object property description. * * params: PTPParams* * uint16_t opc - object property code * uint16_t ofc - object format code * * Return values: Some PTP_RC_* code. * **/ uint16_t ptp_mtp_getobjectpropdesc ( PTPParams* params, uint16_t opc, uint16_t ofc, PTPObjectPropDesc *opd ) { PTPContainer ptp; uint16_t ret; unsigned char *data = NULL; unsigned int size = 0; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_MTP_GetObjectPropDesc; ptp.Nparam = 2; ptp.Param1 = opc; ptp.Param2 = ofc; ret = ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &data, &size); if (ret == PTP_RC_OK) ptp_unpack_OPD (params, data, opd, size); free(data); return ret; } /** * ptp_mtp_getobjectpropvalue: * * This command gets the object properties of an object handle. * * params: PTPParams* * uint32_t objectid - object format code * uint16_t opc - object prop code * * Return values: Some PTP_RC_* code. * **/ uint16_t ptp_mtp_getobjectpropvalue ( PTPParams* params, uint32_t oid, uint16_t opc, PTPPropertyValue *value, uint16_t datatype ) { PTPContainer ptp; uint16_t ret; unsigned char *data = NULL; unsigned int size = 0; int offset = 0; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_MTP_GetObjectPropValue; ptp.Nparam = 2; ptp.Param1 = oid; ptp.Param2 = opc; ret = ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &data, &size); if (ret == PTP_RC_OK) ptp_unpack_DPV(params, data, &offset, size, value, datatype); free(data); return ret; } /** * ptp_mtp_setobjectpropvalue: * * This command gets the object properties of an object handle. * * params: PTPParams* * uint32_t objectid - object format code * uint16_t opc - object prop code * * Return values: Some PTP_RC_* code. * **/ uint16_t ptp_mtp_setobjectpropvalue ( PTPParams* params, uint32_t oid, uint16_t opc, PTPPropertyValue *value, uint16_t datatype ) { PTPContainer ptp; uint16_t ret; unsigned char *data = NULL; unsigned int size ; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_MTP_SetObjectPropValue; ptp.Nparam = 2; ptp.Param1 = oid; ptp.Param2 = opc; size = ptp_pack_DPV(params, value, &data, datatype); ret = ptp_transaction(params, &ptp, PTP_DP_SENDDATA, size, &data, NULL); free(data); return ret; } uint16_t ptp_mtp_getobjectreferences (PTPParams* params, uint32_t handle, uint32_t** ohArray, uint32_t* arraylen) { PTPContainer ptp; uint16_t ret; unsigned char* dpv=NULL; unsigned int dpvlen = 0; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_MTP_GetObjectReferences; ptp.Param1=handle; ptp.Nparam=1; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &dpv, &dpvlen); if (ret == PTP_RC_OK) { /* Sandisk Sansa skips the DATA phase, but returns OK as response. * this will gives us a NULL here. Handle it. -Marcus */ if ((dpv == NULL) || (dpvlen == 0)) { *arraylen = 0; *ohArray = NULL; } else { *arraylen = ptp_unpack_uint32_t_array(params, dpv, 0, ohArray); } } free(dpv); return ret; } uint16_t ptp_mtp_setobjectreferences (PTPParams* params, uint32_t handle, uint32_t* ohArray, uint32_t arraylen) { PTPContainer ptp; uint16_t ret; uint32_t size; unsigned char* dpv=NULL; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_MTP_SetObjectReferences; ptp.Param1 = handle; ptp.Nparam = 1; size = ptp_pack_uint32_t_array(params, ohArray, arraylen, &dpv); ret = ptp_transaction(params, &ptp, PTP_DP_SENDDATA, size, (unsigned char **)&dpv, NULL); free(dpv); return ret; } uint16_t ptp_mtp_getobjectproplist (PTPParams* params, uint32_t handle, MTPProperties **props, int *nrofprops) { uint16_t ret; PTPContainer ptp; unsigned char* opldata = NULL; unsigned int oplsize; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_MTP_GetObjPropList; ptp.Param1 = handle; ptp.Param2 = 0x00000000U; /* 0x00000000U should be "all formats" */ ptp.Param3 = 0xFFFFFFFFU; /* 0xFFFFFFFFU should be "all properties" */ ptp.Param4 = 0x00000000U; ptp.Param5 = 0xFFFFFFFFU; /* means - return full tree below the Param1 handle */ ptp.Nparam = 5; ret = ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &opldata, &oplsize); if (ret == PTP_RC_OK) *nrofprops = ptp_unpack_OPL(params, opldata, props, oplsize); if (opldata != NULL) free(opldata); return ret; } uint16_t ptp_mtp_getobjectproplist_single (PTPParams* params, uint32_t handle, MTPProperties **props, int *nrofprops) { uint16_t ret; PTPContainer ptp; unsigned char* opldata = NULL; unsigned int oplsize; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_MTP_GetObjPropList; ptp.Param1 = handle; ptp.Param2 = 0x00000000U; /* 0x00000000U should be "all formats" */ ptp.Param3 = 0xFFFFFFFFU; /* 0xFFFFFFFFU should be "all properties" */ ptp.Param4 = 0x00000000U; ptp.Param5 = 0x00000000U; /* means - return single tree below the Param1 handle */ ptp.Nparam = 5; ret = ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &opldata, &oplsize); if (ret == PTP_RC_OK) *nrofprops = ptp_unpack_OPL(params, opldata, props, oplsize); if (opldata != NULL) free(opldata); return ret; } uint16_t ptp_mtp_sendobjectproplist (PTPParams* params, uint32_t* store, uint32_t* parenthandle, uint32_t* handle, uint16_t objecttype, uint64_t objectsize, MTPProperties *props, int nrofprops) { uint16_t ret; PTPContainer ptp; unsigned char* opldata=NULL; uint32_t oplsize; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_MTP_SendObjectPropList; ptp.Param1 = *store; ptp.Param2 = *parenthandle; ptp.Param3 = (uint32_t) objecttype; ptp.Param4 = (uint32_t) (objectsize >> 32); ptp.Param5 = (uint32_t) (objectsize & 0xffffffffU); ptp.Nparam = 5; /* Set object handle to 0 for a new object */ oplsize = ptp_pack_OPL(params,props,nrofprops,&opldata); ret = ptp_transaction(params, &ptp, PTP_DP_SENDDATA, oplsize, &opldata, NULL); free(opldata); *store = ptp.Param1; *parenthandle = ptp.Param2; *handle = ptp.Param3; return ret; } uint16_t ptp_mtp_setobjectproplist (PTPParams* params, MTPProperties *props, int nrofprops) { uint16_t ret; PTPContainer ptp; unsigned char* opldata=NULL; uint32_t oplsize; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_MTP_SetObjPropList; ptp.Nparam = 0; oplsize = ptp_pack_OPL(params,props,nrofprops,&opldata); ret = ptp_transaction(params, &ptp, PTP_DP_SENDDATA, oplsize, &opldata, NULL); free(opldata); return ret; } uint16_t ptp_mtpz_sendwmdrmpdapprequest (PTPParams* params, unsigned char *appcertmsg, uint32_t size) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_MTP_WMDRMPD_SendWMDRMPDAppRequest; return ptp_transaction (params, &ptp, PTP_DP_SENDDATA, size, &appcertmsg, NULL); } uint16_t ptp_mtpz_getwmdrmpdappresponse (PTPParams* params, unsigned char **response, uint32_t *size) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code = PTP_OC_MTP_WMDRMPD_GetWMDRMPDAppResponse; *size = 0; *response = NULL; return ptp_transaction (params, &ptp, PTP_DP_GETDATA, 0, response, size); } /****** CHDK interface ******/ uint16_t ptp_chdk_get_memory(PTPParams* params, int start, int num, unsigned char **buf ) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CHDK; ptp.Nparam=3; ptp.Param1=PTP_CHDK_GetMemory; ptp.Param2=start; ptp.Param3=num; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, buf, NULL); } uint16_t ptp_chdk_call(PTPParams* params, int *args, int size, int *ret) { uint16_t r; PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CHDK; ptp.Nparam=1; ptp.Param1=PTP_CHDK_CallFunction; /* FIXME: check int packing */ r=ptp_transaction(params, &ptp, PTP_DP_SENDDATA, size*sizeof(int), (unsigned char **) &args, NULL); if ( r == PTP_RC_OK ) return r; if ( ret ) *ret = ptp.Param1; return r; } uint16_t ptp_chdk_get_propcase(PTPParams* params, int start, int num, int* ints) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CHDK; ptp.Nparam=3; ptp.Param1=PTP_CHDK_GetPropCase; ptp.Param2=start; ptp.Param3=num; /* FIXME: unpack ints correctly */ return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, (unsigned char**)ints, NULL); } uint16_t ptp_chdk_get_paramdata(PTPParams* params, int start, int num, unsigned char **buf) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CHDK; ptp.Nparam=3; ptp.Param1=PTP_CHDK_GetParamData; ptp.Param2=start; ptp.Param3=num; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, buf, NULL); } #if 0 int ptp_chdk_upload(char *local_fn, char *remote_fn, PTPParams* params, PTPDeviceInfo* deviceinfo) { uint16_t ret; PTPContainer ptp; char *buf = NULL; FILE *f; int s,l; struct stat st_buf; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CHDK; ptp.Nparam=2; ptp.Param1=PTP_CHDK_UploadFile; if (stat(local_fn, &st_buf)==0) ptp.Param2=st_buf.st_mtime-_timezone-_daylight; else ptp.Param2=0; f = fopen(local_fn,"rb"); if ( f == NULL ) { ptp_error(params,"could not open file \'%s\'",local_fn); return 0; } fseek(f,0,SEEK_END); s = ftell(f); fseek(f,0,SEEK_SET); l = strlen(remote_fn); buf = malloc(4+l+s); memcpy(buf,&l,4); memcpy(buf+4,remote_fn,l); fread(buf+4+l,1,s,f); fclose(f); ret=ptp_transaction(params, &ptp, PTP_DP_SENDDATA, 4+l+s, &buf); free(buf); if ( ret != 0x2001 ) { ptp_error(params,"unexpected return code 0x%x",ret); return 0; } return 1; } int ptp_chdk_download(char *remote_fn, char *local_fn, PTPParams* params, PTPDeviceInfo* deviceinfo) { uint16_t ret; PTPContainer ptp; char *buf = NULL; FILE *f; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CHDK; ptp.Nparam=1; ptp.Param1=PTP_CHDK_TempData; ret=ptp_transaction(params, &ptp, PTP_DP_SENDDATA, strlen(remote_fn), &remote_fn); if ( ret != 0x2001 ) { ptp_error(params,"unexpected return code 0x%x",ret); return 0; } PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CHDK; ptp.Nparam=1; ptp.Param1=PTP_CHDK_DownloadFile; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &buf); if ( ret != 0x2001 ) { ptp_error(params,"unexpected return code 0x%x",ret); return 0; } f = fopen(local_fn,"wb"); if ( f == NULL ) { ptp_error(params,"could not open file \'%s\'",local_fn); free(buf); return 0; } fwrite(buf,1,ptp.Param1,f); fclose(f); free(buf); return 1; } #endif uint16_t ptp_chdk_exec_lua(PTPParams* params, char *script, uint32_t *ret) { uint16_t r; PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CHDK; ptp.Nparam=1; ptp.Param1=PTP_CHDK_ExecuteLUA; r=ptp_transaction(params, &ptp, PTP_DP_SENDDATA, strlen(script)+1, (unsigned char**)&script, NULL); if ( r != PTP_RC_OK ) return r; *ret = ptp.Param1; return r; } uint16_t ptp_chdk_get_script_output(PTPParams* params, char** scriptoutput) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CHDK; ptp.Nparam=1; ptp.Param1=PTP_CHDK_GetScriptOutput; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, (unsigned char **)scriptoutput, NULL); } #if 0 void ptp_chdk_opendir(char *dir, PTPParams* params, PTPDeviceInfo* deviceinfo){ uint16_t ret; PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CHDK; ptp.Nparam=1; ptp.Param1=PTP_CHDK_OpenDir; ret=ptp_transaction(params, &ptp, PTP_DP_SENDDATA, strlen(dir)+1, (char*)&dir); if ( ret != 0x2001 ) { ptp_error(params,"unexpected return code 0x%x",ret); return; } } void ptp_chdk_closedir(PTPParams* params, PTPDeviceInfo* deviceinfo){ uint16_t ret; PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CHDK; ptp.Nparam=1; ptp.Param1=PTP_CHDK_CloseDir; ret=ptp_transaction(params, &ptp, PTP_DP_NODATA, 0, NULL); if ( ret != 0x2001 ) { ptp_error(params,"unexpected return code 0x%x",ret); return; } } struct fileinfo* ptp_chdk_readdir(PTPParams* params, PTPDeviceInfo* deviceinfo){ uint16_t ret; PTPContainer ptp; char* buf=NULL; static struct fileinfo fi; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CHDK; ptp.Nparam=1; ptp.Param1=PTP_CHDK_ReadDir; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &buf); if ( ret != 0x2001 ) { ptp_error(params,"unexpected return code 0x%x",ret); return NULL; } if (buf){ memcpy(&fi, buf, sizeof(fi)); free(buf); } return &fi; } void ptp_chdk_download_alt_end(PTPParams* params, PTPDeviceInfo* deviceinfo){ // internal use uint16_t ret; PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CHDK; ptp.Nparam=1; ptp.Param1=PTP_CHDK_EndDownloadFile; ret=ptp_transaction(params, &ptp, PTP_DP_NODATA, 0, NULL); if ( ret != 0x2001 ) ptp_error(params,"unexpected return code 0x%x",ret); } int ptp_chdk_download_alt(char *remote_fn, char *local_fn, PTPParams* params, PTPDeviceInfo* deviceinfo) { uint16_t ret; PTPContainer ptp; char *buf = NULL; FILE *f; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CHDK; ptp.Nparam=1; ptp.Param1=PTP_CHDK_StartDownloadFile; ret=ptp_transaction(params, &ptp, PTP_DP_SENDDATA, strlen(remote_fn)+1, &remote_fn); if ( ret != 0x2001 ) { ptp_error(params,"unexpected return code 0x%x",ret); return 0; } f = fopen(local_fn,"wb"); if ( f == NULL ) { ptp_error(params,"could not open file \'%s\'",local_fn); return 0; } while(1) { PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CHDK; ptp.Nparam=1; ptp.Param1=PTP_CHDK_ResumeDownloadFile; buf=NULL; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &buf); if ( ret != 0x2001 ) { ptp_error(params,"unexpected return code 0x%x",ret); ptp_chdk_download_alt_end(params, deviceinfo); fclose(f); return 0; } if (ptp.Param1<=0){free(buf); break;} fwrite(buf, 1, ptp.Param1, f); free(buf); } fclose(f); ptp_chdk_download_alt_end(params, deviceinfo); return 1; } #endif uint16_t ptp_chdk_get_video_settings(PTPParams* params, ptp_chdk_videosettings* vsettings) { uint16_t ret; PTPContainer ptp; unsigned char* buf=NULL; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_CHDK; ptp.Nparam=1; ptp.Param1=PTP_CHDK_GetVideoSettings; ret=ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, &buf, NULL); if ( ret != PTP_RC_OK ) return ret; if (buf) { /* FIXME: endian convert */ memcpy(vsettings, buf, sizeof(ptp_chdk_videosettings)); free(buf); } return ret; } /** * Android MTP Extensions */ /** * ptp_android_getpartialobject64: * params: PTPParams* * handle - Object handle * offset - Offset into object * maxbytes - Maximum of bytes to read * object - pointer to data area * len - pointer to returned length * * Get object 'handle' from device and store the data in newly * allocated 'object'. Start from offset and read at most maxbytes. * * This is a 64bit offset version of the standard GetPartialObject. * * Return values: Some PTP_RC_* code. **/ uint16_t ptp_android_getpartialobject64 (PTPParams* params, uint32_t handle, uint64_t offset, uint32_t maxbytes, unsigned char** object, uint32_t *len) { PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_ANDROID_GetPartialObject64; ptp.Param1=handle; ptp.Param2=offset & 0xFFFFFFFF; ptp.Param3=offset >> 32; ptp.Param4=maxbytes; ptp.Nparam=4; *len=0; return ptp_transaction(params, &ptp, PTP_DP_GETDATA, 0, object, len); } uint16_t ptp_android_sendpartialobject (PTPParams* params, uint32_t handle, uint64_t offset, unsigned char* object, uint32_t len) { uint32_t err; PTPContainer ptp; PTP_CNT_INIT(ptp); ptp.Code=PTP_OC_ANDROID_SendPartialObject; ptp.Param1=handle; ptp.Param2=offset & 0xFFFFFFFF; ptp.Param3=offset >> 32; ptp.Param4=len; ptp.Nparam=4; /* * MtpServer.cpp is buggy: it uses write() without offset * rather than pwrite to send the data for data coming with * the header packet */ params->split_header_data = 1; err=ptp_transaction(params, &ptp, PTP_DP_SENDDATA, len, &object, NULL); params->split_header_data = 0; return err; } /* Non PTP protocol functions */ /* devinfo testing functions */ int ptp_event_issupported(PTPParams* params, uint16_t event) { int i=0; for (;ideviceinfo.EventsSupported_len;i++) { if (params->deviceinfo.EventsSupported[i]==event) return 1; } return 0; } int ptp_property_issupported(PTPParams* params, uint16_t property) { int i; for (i=0;ideviceinfo.DevicePropertiesSupported_len;i++) if (params->deviceinfo.DevicePropertiesSupported[i]==property) return 1; return 0; } /* ptp structures freeing functions */ void ptp_free_devicepropvalue(uint16_t dt, PTPPropertyValue* dpd) { switch (dt) { case PTP_DTC_INT8: case PTP_DTC_UINT8: case PTP_DTC_UINT16: case PTP_DTC_INT16: case PTP_DTC_UINT32: case PTP_DTC_INT32: case PTP_DTC_UINT64: case PTP_DTC_INT64: case PTP_DTC_UINT128: case PTP_DTC_INT128: /* Nothing to free */ break; case PTP_DTC_AINT8: case PTP_DTC_AUINT8: case PTP_DTC_AUINT16: case PTP_DTC_AINT16: case PTP_DTC_AUINT32: case PTP_DTC_AINT32: case PTP_DTC_AUINT64: case PTP_DTC_AINT64: case PTP_DTC_AUINT128: case PTP_DTC_AINT128: if (dpd->a.v) free(dpd->a.v); break; case PTP_DTC_STR: if (dpd->str) free(dpd->str); break; } } void ptp_free_devicepropdesc(PTPDevicePropDesc* dpd) { uint16_t i; ptp_free_devicepropvalue (dpd->DataType, &dpd->FactoryDefaultValue); ptp_free_devicepropvalue (dpd->DataType, &dpd->CurrentValue); switch (dpd->FormFlag) { case PTP_DPFF_Range: ptp_free_devicepropvalue (dpd->DataType, &dpd->FORM.Range.MinimumValue); ptp_free_devicepropvalue (dpd->DataType, &dpd->FORM.Range.MaximumValue); ptp_free_devicepropvalue (dpd->DataType, &dpd->FORM.Range.StepSize); break; case PTP_DPFF_Enumeration: if (dpd->FORM.Enum.SupportedValue) { for (i=0;iFORM.Enum.NumberOfValues;i++) ptp_free_devicepropvalue (dpd->DataType, dpd->FORM.Enum.SupportedValue+i); free (dpd->FORM.Enum.SupportedValue); } } } void ptp_free_objectpropdesc(PTPObjectPropDesc* opd) { uint16_t i; ptp_free_devicepropvalue (opd->DataType, &opd->FactoryDefaultValue); switch (opd->FormFlag) { case PTP_OPFF_None: break; case PTP_OPFF_Range: ptp_free_devicepropvalue (opd->DataType, &opd->FORM.Range.MinimumValue); ptp_free_devicepropvalue (opd->DataType, &opd->FORM.Range.MaximumValue); ptp_free_devicepropvalue (opd->DataType, &opd->FORM.Range.StepSize); break; case PTP_OPFF_Enumeration: if (opd->FORM.Enum.SupportedValue) { for (i=0;iFORM.Enum.NumberOfValues;i++) ptp_free_devicepropvalue (opd->DataType, opd->FORM.Enum.SupportedValue+i); free (opd->FORM.Enum.SupportedValue); } break; case PTP_OPFF_DateTime: case PTP_OPFF_FixedLengthArray: case PTP_OPFF_RegularExpression: case PTP_OPFF_ByteArray: case PTP_OPFF_LongString: /* Ignore these presently, we cannot unpack them, so there is nothing to be freed. */ break; default: fprintf (stderr, "Unknown OPFF type %d\n", opd->FormFlag); break; } } void ptp_free_objectinfo (PTPObjectInfo *oi) { if (!oi) return; free (oi->Filename); oi->Filename = NULL; free (oi->Keywords); oi->Keywords = NULL; } void ptp_free_object (PTPObject *ob) { int i; if (!ob) return; ptp_free_objectinfo (&ob->oi); for (i=0;inrofmtpprops;i++) ptp_destroy_object_prop(&ob->mtpprops[i]); ob->flags = 0; } const char * ptp_strerror(uint16_t error) { int i; /* PTP error descriptions */ static struct { short n; const char *txt; } ptp_errors[] = { {PTP_RC_Undefined, N_("PTP: Undefined Error")}, {PTP_RC_OK, N_("PTP: OK!")}, {PTP_RC_GeneralError, N_("PTP: General Error")}, {PTP_RC_SessionNotOpen, N_("PTP: Session Not Open")}, {PTP_RC_InvalidTransactionID, N_("PTP: Invalid Transaction ID")}, {PTP_RC_OperationNotSupported, N_("PTP: Operation Not Supported")}, {PTP_RC_ParameterNotSupported, N_("PTP: Parameter Not Supported")}, {PTP_RC_IncompleteTransfer, N_("PTP: Incomplete Transfer")}, {PTP_RC_InvalidStorageId, N_("PTP: Invalid Storage ID")}, {PTP_RC_InvalidObjectHandle, N_("PTP: Invalid Object Handle")}, {PTP_RC_DevicePropNotSupported, N_("PTP: Device Prop Not Supported")}, {PTP_RC_InvalidObjectFormatCode, N_("PTP: Invalid Object Format Code")}, {PTP_RC_StoreFull, N_("PTP: Store Full")}, {PTP_RC_ObjectWriteProtected, N_("PTP: Object Write Protected")}, {PTP_RC_StoreReadOnly, N_("PTP: Store Read Only")}, {PTP_RC_AccessDenied, N_("PTP: Access Denied")}, {PTP_RC_NoThumbnailPresent, N_("PTP: No Thumbnail Present")}, {PTP_RC_SelfTestFailed, N_("PTP: Self Test Failed")}, {PTP_RC_PartialDeletion, N_("PTP: Partial Deletion")}, {PTP_RC_StoreNotAvailable, N_("PTP: Store Not Available")}, {PTP_RC_SpecificationByFormatUnsupported, N_("PTP: Specification By Format Unsupported")}, {PTP_RC_NoValidObjectInfo, N_("PTP: No Valid Object Info")}, {PTP_RC_InvalidCodeFormat, N_("PTP: Invalid Code Format")}, {PTP_RC_UnknownVendorCode, N_("PTP: Unknown Vendor Code")}, {PTP_RC_CaptureAlreadyTerminated, N_("PTP: Capture Already Terminated")}, {PTP_RC_DeviceBusy, N_("PTP: Device Busy")}, {PTP_RC_InvalidParentObject, N_("PTP: Invalid Parent Object")}, {PTP_RC_InvalidDevicePropFormat, N_("PTP: Invalid Device Prop Format")}, {PTP_RC_InvalidDevicePropValue, N_("PTP: Invalid Device Prop Value")}, {PTP_RC_InvalidParameter, N_("PTP: Invalid Parameter")}, {PTP_RC_SessionAlreadyOpened, N_("PTP: Session Already Opened")}, {PTP_RC_TransactionCanceled, N_("PTP: Transaction Canceled")}, {PTP_RC_SpecificationOfDestinationUnsupported, N_("PTP: Specification Of Destination Unsupported")}, {PTP_RC_EK_FilenameRequired, N_("PTP: EK Filename Required")}, {PTP_RC_EK_FilenameConflicts, N_("PTP: EK Filename Conflicts")}, {PTP_RC_EK_FilenameInvalid, N_("PTP: EK Filename Invalid")}, {PTP_ERROR_IO, N_("PTP: I/O error")}, {PTP_ERROR_BADPARAM, N_("PTP: Error: bad parameter")}, {PTP_ERROR_DATA_EXPECTED, N_("PTP: Protocol error, data expected")}, {PTP_ERROR_RESP_EXPECTED, N_("PTP: Protocol error, response expected")}, {0, NULL} }; for (i=0; ptp_errors[i].txt!=NULL; i++) if (ptp_errors[i].n == error) return ptp_errors[i].txt; return NULL; } void ptp_perror(PTPParams* params, uint16_t error) { const char *txt = ptp_strerror(error); if (txt != NULL) ptp_error(params, txt); } const char* ptp_get_property_description(PTPParams* params, uint16_t dpc) { int i; /* Device Property descriptions */ struct { uint16_t dpc; const char *txt; } ptp_device_properties[] = { {PTP_DPC_Undefined, N_("Undefined PTP Property")}, {PTP_DPC_BatteryLevel, N_("Battery Level")}, {PTP_DPC_FunctionalMode, N_("Functional Mode")}, {PTP_DPC_ImageSize, N_("Image Size")}, {PTP_DPC_CompressionSetting, N_("Compression Setting")}, {PTP_DPC_WhiteBalance, N_("White Balance")}, {PTP_DPC_RGBGain, N_("RGB Gain")}, {PTP_DPC_FNumber, N_("F-Number")}, {PTP_DPC_FocalLength, N_("Focal Length")}, {PTP_DPC_FocusDistance, N_("Focus Distance")}, {PTP_DPC_FocusMode, N_("Focus Mode")}, {PTP_DPC_ExposureMeteringMode, N_("Exposure Metering Mode")}, {PTP_DPC_FlashMode, N_("Flash Mode")}, {PTP_DPC_ExposureTime, N_("Exposure Time")}, {PTP_DPC_ExposureProgramMode, N_("Exposure Program Mode")}, {PTP_DPC_ExposureIndex, N_("Exposure Index (film speed ISO)")}, {PTP_DPC_ExposureBiasCompensation, N_("Exposure Bias Compensation")}, {PTP_DPC_DateTime, N_("Date & Time")}, {PTP_DPC_CaptureDelay, N_("Pre-Capture Delay")}, {PTP_DPC_StillCaptureMode, N_("Still Capture Mode")}, {PTP_DPC_Contrast, N_("Contrast")}, {PTP_DPC_Sharpness, N_("Sharpness")}, {PTP_DPC_DigitalZoom, N_("Digital Zoom")}, {PTP_DPC_EffectMode, N_("Effect Mode")}, {PTP_DPC_BurstNumber, N_("Burst Number")}, {PTP_DPC_BurstInterval, N_("Burst Interval")}, {PTP_DPC_TimelapseNumber, N_("Timelapse Number")}, {PTP_DPC_TimelapseInterval, N_("Timelapse Interval")}, {PTP_DPC_FocusMeteringMode, N_("Focus Metering Mode")}, {PTP_DPC_UploadURL, N_("Upload URL")}, {PTP_DPC_Artist, N_("Artist")}, {PTP_DPC_CopyrightInfo, N_("Copyright Info")}, {0,NULL} }; struct { uint16_t dpc; const char *txt; } ptp_device_properties_EK[] = { {PTP_DPC_EK_ColorTemperature, N_("Color Temperature")}, {PTP_DPC_EK_DateTimeStampFormat, N_("Date Time Stamp Format")}, {PTP_DPC_EK_BeepMode, N_("Beep Mode")}, {PTP_DPC_EK_VideoOut, N_("Video Out")}, {PTP_DPC_EK_PowerSaving, N_("Power Saving")}, {PTP_DPC_EK_UI_Language, N_("UI Language")}, {0,NULL} }; struct { uint16_t dpc; const char *txt; } ptp_device_properties_Canon[] = { {PTP_DPC_CANON_BeepMode, N_("Beep Mode")}, {PTP_DPC_CANON_BatteryKind, N_("Battery Type")}, {PTP_DPC_CANON_BatteryStatus, N_("Battery Mode")}, {PTP_DPC_CANON_UILockType, N_("UILockType")}, {PTP_DPC_CANON_CameraMode, N_("Camera Mode")}, {PTP_DPC_CANON_ImageQuality, N_("Image Quality")}, {PTP_DPC_CANON_FullViewFileFormat, N_("Full View File Format")}, {PTP_DPC_CANON_ImageSize, N_("Image Size")}, {PTP_DPC_CANON_SelfTime, N_("Self Time")}, {PTP_DPC_CANON_FlashMode, N_("Flash Mode")}, {PTP_DPC_CANON_Beep, N_("Beep")}, {PTP_DPC_CANON_ShootingMode, N_("Shooting Mode")}, {PTP_DPC_CANON_ImageMode, N_("Image Mode")}, {PTP_DPC_CANON_DriveMode, N_("Drive Mode")}, {PTP_DPC_CANON_EZoom, N_("Zoom")}, {PTP_DPC_CANON_MeteringMode, N_("Metering Mode")}, {PTP_DPC_CANON_AFDistance, N_("AF Distance")}, {PTP_DPC_CANON_FocusingPoint, N_("Focusing Point")}, {PTP_DPC_CANON_WhiteBalance, N_("White Balance")}, {PTP_DPC_CANON_SlowShutterSetting, N_("Slow Shutter Setting")}, {PTP_DPC_CANON_AFMode, N_("AF Mode")}, {PTP_DPC_CANON_ImageStabilization, N_("Image Stabilization")}, {PTP_DPC_CANON_Contrast, N_("Contrast")}, {PTP_DPC_CANON_ColorGain, N_("Color Gain")}, {PTP_DPC_CANON_Sharpness, N_("Sharpness")}, {PTP_DPC_CANON_Sensitivity, N_("Sensitivity")}, {PTP_DPC_CANON_ParameterSet, N_("Parameter Set")}, {PTP_DPC_CANON_ISOSpeed, N_("ISO Speed")}, {PTP_DPC_CANON_Aperture, N_("Aperture")}, {PTP_DPC_CANON_ShutterSpeed, N_("Shutter Speed")}, {PTP_DPC_CANON_ExpCompensation, N_("Exposure Compensation")}, {PTP_DPC_CANON_FlashCompensation, N_("Flash Compensation")}, {PTP_DPC_CANON_AEBExposureCompensation, N_("AEB Exposure Compensation")}, {PTP_DPC_CANON_AvOpen, N_("Av Open")}, {PTP_DPC_CANON_AvMax, N_("Av Max")}, {PTP_DPC_CANON_FocalLength, N_("Focal Length")}, {PTP_DPC_CANON_FocalLengthTele, N_("Focal Length Tele")}, {PTP_DPC_CANON_FocalLengthWide, N_("Focal Length Wide")}, {PTP_DPC_CANON_FocalLengthDenominator, N_("Focal Length Denominator")}, {PTP_DPC_CANON_CaptureTransferMode, N_("Capture Transfer Mode")}, {PTP_DPC_CANON_Zoom, N_("Zoom")}, {PTP_DPC_CANON_NamePrefix, N_("Name Prefix")}, {PTP_DPC_CANON_SizeQualityMode, N_("Size Quality Mode")}, {PTP_DPC_CANON_SupportedThumbSize, N_("Supported Thumb Size")}, {PTP_DPC_CANON_SizeOfOutputDataFromCamera, N_("Size of Output Data from Camera")}, {PTP_DPC_CANON_SizeOfInputDataToCamera, N_("Size of Input Data to Camera")}, {PTP_DPC_CANON_RemoteAPIVersion,N_("Remote API Version")}, {PTP_DPC_CANON_FirmwareVersion, N_("Firmware Version")}, {PTP_DPC_CANON_CameraModel, N_("Camera Model")}, {PTP_DPC_CANON_CameraOwner, N_("Camera Owner")}, {PTP_DPC_CANON_UnixTime, N_("UNIX Time")}, {PTP_DPC_CANON_CameraBodyID, N_("Camera Body ID")}, {PTP_DPC_CANON_CameraOutput, N_("Camera Output")}, {PTP_DPC_CANON_DispAv, N_("Disp Av")}, {PTP_DPC_CANON_AvOpenApex, N_("Av Open Apex")}, {PTP_DPC_CANON_DZoomMagnification, N_("Digital Zoom Magnification")}, {PTP_DPC_CANON_MlSpotPos, N_("Ml Spot Position")}, {PTP_DPC_CANON_DispAvMax, N_("Disp Av Max")}, {PTP_DPC_CANON_AvMaxApex, N_("Av Max Apex")}, {PTP_DPC_CANON_EZoomStartPosition, N_("EZoom Start Position")}, {PTP_DPC_CANON_FocalLengthOfTele, N_("Focal Length Tele")}, {PTP_DPC_CANON_EZoomSizeOfTele, N_("EZoom Size of Tele")}, {PTP_DPC_CANON_PhotoEffect, N_("Photo Effect")}, {PTP_DPC_CANON_AssistLight, N_("Assist Light")}, {PTP_DPC_CANON_FlashQuantityCount, N_("Flash Quantity Count")}, {PTP_DPC_CANON_RotationAngle, N_("Rotation Angle")}, {PTP_DPC_CANON_RotationScene, N_("Rotation Scene")}, {PTP_DPC_CANON_EventEmulateMode,N_("Event Emulate Mode")}, {PTP_DPC_CANON_DPOFVersion, N_("DPOF Version")}, {PTP_DPC_CANON_TypeOfSupportedSlideShow, N_("Type of Slideshow")}, {PTP_DPC_CANON_AverageFilesizes,N_("Average Filesizes")}, {PTP_DPC_CANON_ModelID, N_("Model ID")}, {0,NULL} }; struct { uint16_t dpc; const char *txt; } ptp_device_properties_Nikon[] = { {PTP_DPC_NIKON_ShootingBank, /* 0xD010 */ N_("Shooting Bank")}, {PTP_DPC_NIKON_ShootingBankNameA, /* 0xD011 */ N_("Shooting Bank Name A")}, {PTP_DPC_NIKON_ShootingBankNameB, /* 0xD012 */ N_("Shooting Bank Name B")}, {PTP_DPC_NIKON_ShootingBankNameC, /* 0xD013 */ N_("Shooting Bank Name C")}, {PTP_DPC_NIKON_ShootingBankNameD, /* 0xD014 */ N_("Shooting Bank Name D")}, {PTP_DPC_NIKON_ResetBank0, /* 0xD015 */ N_("Reset Bank 0")}, {PTP_DPC_NIKON_RawCompression, /* 0xD016 */ N_("Raw Compression")}, {PTP_DPC_NIKON_WhiteBalanceAutoBias, /* 0xD017 */ N_("Auto White Balance Bias")}, {PTP_DPC_NIKON_WhiteBalanceTungstenBias, /* 0xD018 */ N_("Tungsten White Balance Bias")}, {PTP_DPC_NIKON_WhiteBalanceFluorescentBias, /* 0xD019 */ N_("Fluorescent White Balance Bias")}, {PTP_DPC_NIKON_WhiteBalanceDaylightBias, /* 0xD01a */ N_("Daylight White Balance Bias")}, {PTP_DPC_NIKON_WhiteBalanceFlashBias, /* 0xD01b */ N_("Flash White Balance Bias")}, {PTP_DPC_NIKON_WhiteBalanceCloudyBias, /* 0xD01c */ N_("Cloudy White Balance Bias")}, {PTP_DPC_NIKON_WhiteBalanceShadeBias, /* 0xD01d */ N_("Shady White Balance Bias")}, {PTP_DPC_NIKON_WhiteBalanceColorTemperature, /* 0xD01e */ N_("White Balance Colour Temperature")}, {PTP_DPC_NIKON_WhiteBalancePresetNo, /* 0xD01f */ N_("White Balance Preset Number")}, {PTP_DPC_NIKON_WhiteBalancePresetName0, /* 0xD020 */ N_("White Balance Preset Name 0")}, {PTP_DPC_NIKON_WhiteBalancePresetName1, /* 0xD021 */ N_("White Balance Preset Name 1")}, {PTP_DPC_NIKON_WhiteBalancePresetName2, /* 0xD022 */ N_("White Balance Preset Name 2")}, {PTP_DPC_NIKON_WhiteBalancePresetName3, /* 0xD023 */ N_("White Balance Preset Name 3")}, {PTP_DPC_NIKON_WhiteBalancePresetName4, /* 0xD024 */ N_("White Balance Preset Name 4")}, {PTP_DPC_NIKON_WhiteBalancePresetVal0, /* 0xD025 */ N_("White Balance Preset Value 0")}, {PTP_DPC_NIKON_WhiteBalancePresetVal1, /* 0xD026 */ N_("White Balance Preset Value 1")}, {PTP_DPC_NIKON_WhiteBalancePresetVal2, /* 0xD027 */ N_("White Balance Preset Value 2")}, {PTP_DPC_NIKON_WhiteBalancePresetVal3, /* 0xD028 */ N_("White Balance Preset Value 3")}, {PTP_DPC_NIKON_WhiteBalancePresetVal4, /* 0xD029 */ N_("White Balance Preset Value 4")}, {PTP_DPC_NIKON_ImageSharpening, /* 0xD02a */ N_("Sharpening")}, {PTP_DPC_NIKON_ToneCompensation, /* 0xD02b */ N_("Tone Compensation")}, {PTP_DPC_NIKON_ColorModel, /* 0xD02c */ N_("Color Model")}, {PTP_DPC_NIKON_HueAdjustment, /* 0xD02d */ N_("Hue Adjustment")}, {PTP_DPC_NIKON_NonCPULensDataFocalLength, /* 0xD02e */ N_("Lens Focal Length (Non CPU)")}, {PTP_DPC_NIKON_NonCPULensDataMaximumAperture, /* 0xD02f */ N_("Lens Maximum Aperture (Non CPU)")}, {PTP_DPC_NIKON_ShootingMode, /* 0xD030 */ N_("Shooting Mode")}, {PTP_DPC_NIKON_JPEG_Compression_Policy, /* 0xD031 */ N_("JPEG Compression Policy")}, {PTP_DPC_NIKON_ColorSpace, /* 0xD032 */ N_("Color Space")}, {PTP_DPC_NIKON_AutoDXCrop, /* 0xD033 */ N_("Auto DX Crop")}, {PTP_DPC_NIKON_FlickerReduction, /* 0xD034 */ N_("Flicker Reduction")}, {PTP_DPC_NIKON_RemoteMode, /* 0xD035 */ N_("Remote Mode")}, {PTP_DPC_NIKON_VideoMode, /* 0xD036 */ N_("Video Mode")}, {PTP_DPC_NIKON_EffectMode, /* 0xD037 */ N_("Effect Mode")}, {PTP_DPC_NIKON_CSMMenuBankSelect, /* 0xD040 */ "PTP_DPC_NIKON_CSMMenuBankSelect"}, {PTP_DPC_NIKON_MenuBankNameA, /* 0xD041 */ N_("Menu Bank Name A")}, {PTP_DPC_NIKON_MenuBankNameB, /* 0xD042 */ N_("Menu Bank Name B")}, {PTP_DPC_NIKON_MenuBankNameC, /* 0xD043 */ N_("Menu Bank Name C")}, {PTP_DPC_NIKON_MenuBankNameD, /* 0xD044 */ N_("Menu Bank Name D")}, {PTP_DPC_NIKON_ResetBank, /* 0xD045 */ N_("Reset Menu Bank")}, {PTP_DPC_NIKON_A1AFCModePriority, /* 0xD048 */ "PTP_DPC_NIKON_A1AFCModePriority"}, {PTP_DPC_NIKON_A2AFSModePriority, /* 0xD049 */ "PTP_DPC_NIKON_A2AFSModePriority"}, {PTP_DPC_NIKON_A3GroupDynamicAF, /* 0xD04a */ "PTP_DPC_NIKON_A3GroupDynamicAF"}, {PTP_DPC_NIKON_A4AFActivation, /* 0xD04b */ "PTP_DPC_NIKON_A4AFActivation"}, {PTP_DPC_NIKON_FocusAreaIllumManualFocus, /* 0xD04c */ "PTP_DPC_NIKON_FocusAreaIllumManualFocus"}, {PTP_DPC_NIKON_FocusAreaIllumContinuous, /* 0xD04d */ "PTP_DPC_NIKON_FocusAreaIllumContinuous"}, {PTP_DPC_NIKON_FocusAreaIllumWhenSelected, /* 0xD04e */ "PTP_DPC_NIKON_FocusAreaIllumWhenSelected"}, {PTP_DPC_NIKON_FocusAreaWrap, /* 0xD04f */ N_("Focus Area Wrap")}, {PTP_DPC_NIKON_VerticalAFON, /* 0xD050 */ N_("Vertical AF On")}, {PTP_DPC_NIKON_AFLockOn, /* 0xD051 */ N_("AF Lock On")}, {PTP_DPC_NIKON_FocusAreaZone, /* 0xD052 */ N_("Focus Area Zone")}, {PTP_DPC_NIKON_EnableCopyright, /* 0xD053 */ N_("Enable Copyright")}, {PTP_DPC_NIKON_ISOAuto, /* 0xD054 */ N_("Auto ISO")}, {PTP_DPC_NIKON_EVISOStep, /* 0xD055 */ N_("Exposure ISO Step")}, {PTP_DPC_NIKON_EVStep, /* 0xD056 */ N_("Exposure Step")}, {PTP_DPC_NIKON_EVStepExposureComp, /* 0xD057 */ N_("Exposure Compensation (EV)")}, {PTP_DPC_NIKON_ExposureCompensation, /* 0xD058 */ N_("Exposure Compensation")}, {PTP_DPC_NIKON_CenterWeightArea, /* 0xD059 */ N_("Centre Weight Area")}, {PTP_DPC_NIKON_ExposureBaseMatrix, /* 0xD05A */ N_("Exposure Base Matrix")}, {PTP_DPC_NIKON_ExposureBaseCenter, /* 0xD05B */ N_("Exposure Base Center")}, {PTP_DPC_NIKON_ExposureBaseSpot, /* 0xD05C */ N_("Exposure Base Spot")}, {PTP_DPC_NIKON_LiveViewAFArea, /* 0xD05D */ N_("Live View AF Area")}, {PTP_DPC_NIKON_AELockMode, /* 0xD05E */ N_("Exposure Lock")}, {PTP_DPC_NIKON_AELAFLMode, /* 0xD05F */ N_("Focus Lock")}, {PTP_DPC_NIKON_LiveViewAFFocus, /* 0xD061 */ N_("Live View AF Focus")}, {PTP_DPC_NIKON_MeterOff, /* 0xD062 */ N_("Auto Meter Off Time")}, {PTP_DPC_NIKON_SelfTimer, /* 0xD063 */ N_("Self Timer Delay")}, {PTP_DPC_NIKON_MonitorOff, /* 0xD064 */ N_("LCD Off Time")}, {PTP_DPC_NIKON_ImgConfTime, /* 0xD065 */ N_("Img Conf Time")}, {PTP_DPC_NIKON_AutoOffTimers, /* 0xD066 */ N_("Auto Off Timers")}, {PTP_DPC_NIKON_AngleLevel, /* 0xD067 */ N_("Angle Level")}, {PTP_DPC_NIKON_D1ShootingSpeed, /* 0xD068 */ N_("Shooting Speed")}, {PTP_DPC_NIKON_D2MaximumShots, /* 0xD069 */ N_("Maximum Shots")}, {PTP_DPC_NIKON_ExposureDelayMode, /* 0xD06A */ N_("Exposure delay mode")}, {PTP_DPC_NIKON_LongExposureNoiseReduction, /* 0xD06B */ N_("Long Exposure Noise Reduction")}, {PTP_DPC_NIKON_FileNumberSequence, /* 0xD06C */ N_("File Number Sequencing")}, {PTP_DPC_NIKON_ControlPanelFinderRearControl, /* 0xD06D */ "PTP_DPC_NIKON_ControlPanelFinderRearControl"}, {PTP_DPC_NIKON_ControlPanelFinderViewfinder, /* 0xD06E */ "PTP_DPC_NIKON_ControlPanelFinderViewfinder"}, {PTP_DPC_NIKON_D7Illumination, /* 0xD06F */ N_("LCD Illumination")}, {PTP_DPC_NIKON_NrHighISO, /* 0xD070 */ N_("High ISO noise reduction")}, {PTP_DPC_NIKON_SHSET_CH_GUID_DISP, /* 0xD071 */ N_("On screen tips")}, {PTP_DPC_NIKON_ArtistName, /* 0xD072 */ N_("Artist Name")}, {PTP_DPC_NIKON_CopyrightInfo, /* 0xD073 */ N_("Copyright Information")}, {PTP_DPC_NIKON_FlashSyncSpeed, /* 0xD074 */ N_("Flash Sync. Speed")}, {PTP_DPC_NIKON_FlashShutterSpeed, /* 0xD075 */ N_("Flash Shutter Speed")}, {PTP_DPC_NIKON_E3AAFlashMode, /* 0xD076 */ N_("Flash Mode")}, {PTP_DPC_NIKON_E4ModelingFlash, /* 0xD077 */ N_("Modeling Flash")}, {PTP_DPC_NIKON_BracketSet, /* 0xD078 */ N_("Bracket Set")}, {PTP_DPC_NIKON_E6ManualModeBracketing, /* 0xD079 */ N_("Manual Mode Bracketing")}, {PTP_DPC_NIKON_BracketOrder, /* 0xD07A */ N_("Bracket Order")}, {PTP_DPC_NIKON_E8AutoBracketSelection, /* 0xD07B */ N_("Auto Bracket Selection")}, {PTP_DPC_NIKON_BracketingSet, N_("NIKON Auto Bracketing Set")}, /* 0xD07C */ {PTP_DPC_NIKON_F1CenterButtonShootingMode, /* 0xD080 */ N_("Center Button Shooting Mode")}, {PTP_DPC_NIKON_CenterButtonPlaybackMode, /* 0xD081 */ N_("Center Button Playback Mode")}, {PTP_DPC_NIKON_F2Multiselector, /* 0xD082 */ N_("Multiselector")}, {PTP_DPC_NIKON_F3PhotoInfoPlayback, /* 0xD083 */ N_("Photo Info. Playback")}, {PTP_DPC_NIKON_F4AssignFuncButton, /* 0xD084 */ N_("Assign Func. Button")}, {PTP_DPC_NIKON_F5CustomizeCommDials, /* 0xD085 */ N_("Customise Command Dials")}, {PTP_DPC_NIKON_ReverseCommandDial, /* 0xD086 */ N_("Reverse Command Dial")}, {PTP_DPC_NIKON_ApertureSetting, /* 0xD087 */ N_("Aperture Setting")}, {PTP_DPC_NIKON_MenusAndPlayback, /* 0xD088 */ N_("Menus and Playback")}, {PTP_DPC_NIKON_F6ButtonsAndDials, /* 0xD089 */ N_("Buttons and Dials")}, {PTP_DPC_NIKON_NoCFCard, /* 0xD08A */ N_("No CF Card Release")}, {PTP_DPC_NIKON_CenterButtonZoomRatio, /* 0xD08B */ N_("Center Button Zoom Ratio")}, {PTP_DPC_NIKON_FunctionButton2, /* 0xD08C */ N_("Function Button 2")}, {PTP_DPC_NIKON_AFAreaPoint, /* 0xD08D */ N_("AF Area Point")}, {PTP_DPC_NIKON_NormalAFOn, /* 0xD08E */ N_("Normal AF On")}, {PTP_DPC_NIKON_CleanImageSensor, /* 0xD08F */ N_("Clean Image Sensor")}, {PTP_DPC_NIKON_ImageCommentString, /* 0xD090 */ N_("Image Comment String")}, {PTP_DPC_NIKON_ImageCommentEnable, /* 0xD091 */ N_("Image Comment Enable")}, {PTP_DPC_NIKON_ImageRotation, /* 0xD092 */ N_("Image Rotation")}, {PTP_DPC_NIKON_ManualSetLensNo, /* 0xD093 */ N_("Manual Set Lens Number")}, {PTP_DPC_NIKON_MovScreenSize, /* 0xD0A0 */ N_("Movie Screen Size")}, {PTP_DPC_NIKON_MovVoice, /* 0xD0A1 */ N_("Movie Voice")}, {PTP_DPC_NIKON_MovMicrophone, /* 0xD0A2 */ N_("Movie Microphone")}, {PTP_DPC_NIKON_MovFileSlot, /* 0xD0A3 */ N_("Movie Card Slot")}, {PTP_DPC_NIKON_ManualMovieSetting, /* 0xD0A6 */ N_("Manual Movie Setting")}, {PTP_DPC_NIKON_MonitorOffDelay, /* 0xD0B3 */ N_("Monitor Off Delay")}, {PTP_DPC_NIKON_Bracketing, /* 0xD0C0 */ N_("Bracketing Enable")}, {PTP_DPC_NIKON_AutoExposureBracketStep, /* 0xD0C1 */ N_("Exposure Bracketing Step")}, {PTP_DPC_NIKON_AutoExposureBracketProgram, /* 0xD0C2 */ N_("Exposure Bracketing Program")}, {PTP_DPC_NIKON_AutoExposureBracketCount, /* 0xD0C3 */ N_("Auto Exposure Bracket Count")}, {PTP_DPC_NIKON_WhiteBalanceBracketStep, N_("White Balance Bracket Step")}, /* 0xD0C4 */ {PTP_DPC_NIKON_WhiteBalanceBracketProgram, N_("White Balance Bracket Program")}, /* 0xD0C5 */ {PTP_DPC_NIKON_LensID, /* 0xD0E0 */ N_("Lens ID")}, {PTP_DPC_NIKON_LensSort, /* 0xD0E1 */ N_("Lens Sort")}, {PTP_DPC_NIKON_LensType, /* 0xD0E2 */ N_("Lens Type")}, {PTP_DPC_NIKON_FocalLengthMin, /* 0xD0E3 */ N_("Min. Focal Length")}, {PTP_DPC_NIKON_FocalLengthMax, /* 0xD0E4 */ N_("Max. Focal Length")}, {PTP_DPC_NIKON_MaxApAtMinFocalLength, /* 0xD0E5 */ N_("Max. Aperture at Min. Focal Length")}, {PTP_DPC_NIKON_MaxApAtMaxFocalLength, /* 0xD0E6 */ N_("Max. Aperture at Max. Focal Length")}, {PTP_DPC_NIKON_FinderISODisp, /* 0xD0F0 */ N_("Finder ISO Display")}, {PTP_DPC_NIKON_AutoOffPhoto, /* 0xD0F2 */ N_("Auto Off Photo")}, {PTP_DPC_NIKON_AutoOffMenu, /* 0xD0F3 */ N_("Auto Off Menu")}, {PTP_DPC_NIKON_AutoOffInfo, /* 0xD0F4 */ N_("Auto Off Info")}, {PTP_DPC_NIKON_SelfTimerShootNum, /* 0xD0F5 */ N_("Self Timer Shot Number")}, {PTP_DPC_NIKON_VignetteCtrl, /* 0xD0F7 */ N_("Vignette Control")}, {PTP_DPC_NIKON_AutoDistortionControl, /* 0xD0F8 */ N_("Auto Distortion Control")}, {PTP_DPC_NIKON_SceneMode, /* 0xD0F9 */ N_("Scene Mode")}, {PTP_DPC_NIKON_ExposureTime, /* 0xD100 */ N_("Nikon Exposure Time")}, {PTP_DPC_NIKON_ACPower, N_("AC Power")}, /* 0xD101 */ {PTP_DPC_NIKON_WarningStatus, N_("Warning Status")},/* 0xD102 */ {PTP_DPC_NIKON_MaximumShots, /* 0xD103 */ N_("Maximum Shots")}, {PTP_DPC_NIKON_AFLockStatus, N_("AF Locked")},/* 0xD104 */ {PTP_DPC_NIKON_AELockStatus, N_("AE Locked")},/* 0xD105 */ {PTP_DPC_NIKON_FVLockStatus, N_("FV Locked")},/* 0xD106 */ {PTP_DPC_NIKON_AutofocusLCDTopMode2, /* 0xD107 */ N_("AF LCD Top Mode 2")}, {PTP_DPC_NIKON_AutofocusArea, /* 0xD108 */ N_("Active AF Sensor")}, {PTP_DPC_NIKON_FlexibleProgram, /* 0xD109 */ N_("Flexible Program")}, {PTP_DPC_NIKON_LightMeter, /* 0xD10A */ N_("Exposure Meter")}, {PTP_DPC_NIKON_RecordingMedia, /* 0xD10B */ N_("Recording Media")}, {PTP_DPC_NIKON_USBSpeed, /* 0xD10C */ N_("USB Speed")}, {PTP_DPC_NIKON_CCDNumber, /* 0xD10D */ N_("CCD Serial Number")}, {PTP_DPC_NIKON_CameraOrientation, /* 0xD10E */ N_("Camera Orientation")}, {PTP_DPC_NIKON_GroupPtnType, /* 0xD10F */ N_("Group PTN Type")}, {PTP_DPC_NIKON_FNumberLock, /* 0xD110 */ N_("FNumber Lock")}, {PTP_DPC_NIKON_ExposureApertureLock, /* 0xD111 */ N_("Exposure Aperture Lock")}, {PTP_DPC_NIKON_TVLockSetting, /* 0xD112 */ N_("TV Lock Setting")}, {PTP_DPC_NIKON_AVLockSetting, /* 0xD113 */ N_("AV Lock Setting")}, {PTP_DPC_NIKON_IllumSetting, /* 0xD114 */ N_("Illum Setting")}, {PTP_DPC_NIKON_FocusPointBright, /* 0xD115 */ N_("Focus Point Bright")}, {PTP_DPC_NIKON_ExternalFlashAttached, /* 0xD120 */ N_("External Flash Attached")}, {PTP_DPC_NIKON_ExternalFlashStatus, /* 0xD121 */ N_("External Flash Status")}, {PTP_DPC_NIKON_ExternalFlashSort, /* 0xD122 */ N_("External Flash Sort")}, {PTP_DPC_NIKON_ExternalFlashMode, /* 0xD123 */ N_("External Flash Mode")}, {PTP_DPC_NIKON_ExternalFlashCompensation, /* 0xD124 */ N_("External Flash Compensation")}, {PTP_DPC_NIKON_NewExternalFlashMode, /* 0xD125 */ N_("External Flash Mode")}, {PTP_DPC_NIKON_FlashExposureCompensation, /* 0xD126 */ N_("Flash Exposure Compensation")}, {PTP_DPC_NIKON_HDRMode, /* 0xD130 */ N_("HDR Mode")}, {PTP_DPC_NIKON_HDRHighDynamic, /* 0xD131 */ N_("HDR High Dynamic")}, {PTP_DPC_NIKON_HDRSmoothing, /* 0xD132 */ N_("HDR Smoothing")}, {PTP_DPC_NIKON_OptimizeImage, /* 0xD140 */ N_("Optimize Image")}, {PTP_DPC_NIKON_Saturation, /* 0xD142 */ N_("Saturation")}, {PTP_DPC_NIKON_BW_FillerEffect, /* 0xD143 */ N_("BW Filler Effect")}, {PTP_DPC_NIKON_BW_Sharpness, /* 0xD144 */ N_("BW Sharpness")}, {PTP_DPC_NIKON_BW_Contrast, /* 0xD145 */ N_("BW Contrast")}, {PTP_DPC_NIKON_BW_Setting_Type, /* 0xD146 */ N_("BW Setting Type")}, {PTP_DPC_NIKON_Slot2SaveMode, /* 0xD148 */ N_("Slot 2 Save Mode")}, {PTP_DPC_NIKON_RawBitMode, /* 0xD149 */ N_("Raw Bit Mode")}, {PTP_DPC_NIKON_ISOAutoTime, /* 0xD14E */ N_("ISO Auto Time")}, {PTP_DPC_NIKON_FlourescentType, /* 0xD14F */ N_("Flourescent Type")}, {PTP_DPC_NIKON_TuneColourTemperature, /* 0xD150 */ N_("Tune Colour Temperature")}, {PTP_DPC_NIKON_TunePreset0, /* 0xD151 */ N_("Tune Preset 0")}, {PTP_DPC_NIKON_TunePreset1, /* 0xD152 */ N_("Tune Preset 1")}, {PTP_DPC_NIKON_TunePreset2, /* 0xD153 */ N_("Tune Preset 2")}, {PTP_DPC_NIKON_TunePreset3, /* 0xD154 */ N_("Tune Preset 3")}, {PTP_DPC_NIKON_TunePreset4, /* 0xD155 */ N_("Tune Preset 4")}, {PTP_DPC_NIKON_BeepOff, /* 0xD160 */ N_("AF Beep Mode")}, {PTP_DPC_NIKON_AutofocusMode, /* 0xD161 */ N_("Autofocus Mode")}, {PTP_DPC_NIKON_AFAssist, /* 0xD163 */ N_("AF Assist Lamp")}, {PTP_DPC_NIKON_PADVPMode, /* 0xD164 */ N_("Auto ISO P/A/DVP Setting")}, {PTP_DPC_NIKON_ImageReview, /* 0xD165 */ N_("Image Review")}, {PTP_DPC_NIKON_AFAreaIllumination, /* 0xD166 */ N_("AF Area Illumination")}, {PTP_DPC_NIKON_FlashMode, /* 0xD167 */ N_("Flash Mode")}, {PTP_DPC_NIKON_FlashCommanderMode, /* 0xD168 */ N_("Flash Commander Mode")}, {PTP_DPC_NIKON_FlashSign, /* 0xD169 */ N_("Flash Sign")}, {PTP_DPC_NIKON_ISO_Auto, /* 0xD16A */ N_("ISO Auto")}, {PTP_DPC_NIKON_RemoteTimeout, /* 0xD16B */ N_("Remote Timeout")}, {PTP_DPC_NIKON_GridDisplay, /* 0xD16C */ N_("Viewfinder Grid Display")}, {PTP_DPC_NIKON_FlashModeManualPower, /* 0xD16D */ N_("Flash Mode Manual Power")}, {PTP_DPC_NIKON_FlashModeCommanderPower, /* 0xD16E */ N_("Flash Mode Commander Power")}, {PTP_DPC_NIKON_AutoFP, /* 0xD16F */ N_("Auto FP")}, {PTP_DPC_NIKON_CSMMenu, /* 0xD180 */ N_("CSM Menu")}, {PTP_DPC_NIKON_WarningDisplay, /* 0xD181 */ N_("Warning Display")}, {PTP_DPC_NIKON_BatteryCellKind, /* 0xD182 */ N_("Battery Cell Kind")}, {PTP_DPC_NIKON_ISOAutoHiLimit, /* 0xD183 */ N_("ISO Auto High Limit")}, {PTP_DPC_NIKON_DynamicAFArea, /* 0xD184 */ N_("Dynamic AF Area")}, {PTP_DPC_NIKON_ContinuousSpeedHigh, /* 0xD186 */ N_("Continuous Speed High")}, {PTP_DPC_NIKON_InfoDispSetting, /* 0xD187 */ N_("Info Disp Setting")}, {PTP_DPC_NIKON_PreviewButton, /* 0xD189 */ N_("Preview Button")}, {PTP_DPC_NIKON_PreviewButton2, /* 0xD18A */ N_("Preview Button 2")}, {PTP_DPC_NIKON_AEAFLockButton2, /* 0xD18B */ N_("AEAF Lock Button 2")}, {PTP_DPC_NIKON_IndicatorDisp, /* 0xD18D */ N_("Indicator Display")}, {PTP_DPC_NIKON_CellKindPriority, /* 0xD18E */ N_("Cell Kind Priority")}, {PTP_DPC_NIKON_BracketingFramesAndSteps, /* 0xD190 */ N_("Bracketing Frames and Steps")}, {PTP_DPC_NIKON_LiveViewMode, /* 0xD1A0 */ N_("Live View Mode")}, {PTP_DPC_NIKON_LiveViewDriveMode, /* 0xD1A1 */ N_("Live View Drive Mode")}, {PTP_DPC_NIKON_LiveViewStatus, /* 0xD1A2 */ N_("Live View Status")}, {PTP_DPC_NIKON_LiveViewImageZoomRatio, /* 0xD1A3 */ N_("Live View Image Zoom Ratio")}, {PTP_DPC_NIKON_LiveViewProhibitCondition, /* 0xD1A4 */ N_("Live View Prohibit Condition")}, {PTP_DPC_NIKON_ExposureDisplayStatus, /* 0xD1B0 */ N_("Exposure Display Status")}, {PTP_DPC_NIKON_ExposureIndicateStatus, /* 0xD1B1 */ N_("Exposure Indicate Status")}, {PTP_DPC_NIKON_InfoDispErrStatus, /* 0xD1B2 */ N_("Info Display Error Status")}, {PTP_DPC_NIKON_ExposureIndicateLightup, /* 0xD1B3 */ N_("Exposure Indicate Lightup")}, {PTP_DPC_NIKON_FlashOpen, /* 0xD1C0 */ N_("Flash Open")}, {PTP_DPC_NIKON_FlashCharged, /* 0xD1C1 */ N_("Flash Charged")}, {PTP_DPC_NIKON_FlashMRepeatValue, /* 0xD1D0 */ N_("Flash MRepeat Value")}, {PTP_DPC_NIKON_FlashMRepeatCount, /* 0xD1D1 */ N_("Flash MRepeat Count")}, {PTP_DPC_NIKON_FlashMRepeatInterval, /* 0xD1D2 */ N_("Flash MRepeat Interval")}, {PTP_DPC_NIKON_FlashCommandChannel, /* 0xD1D3 */ N_("Flash Command Channel")}, {PTP_DPC_NIKON_FlashCommandSelfMode, /* 0xD1D4 */ N_("Flash Command Self Mode")}, {PTP_DPC_NIKON_FlashCommandSelfCompensation, /* 0xD1D5 */ N_("Flash Command Self Compensation")}, {PTP_DPC_NIKON_FlashCommandSelfValue, /* 0xD1D6 */ N_("Flash Command Self Value")}, {PTP_DPC_NIKON_FlashCommandAMode, /* 0xD1D7 */ N_("Flash Command A Mode")}, {PTP_DPC_NIKON_FlashCommandACompensation, /* 0xD1D8 */ N_("Flash Command A Compensation")}, {PTP_DPC_NIKON_FlashCommandAValue, /* 0xD1D9 */ N_("Flash Command A Value")}, {PTP_DPC_NIKON_FlashCommandBMode, /* 0xD1DA */ N_("Flash Command B Mode")}, {PTP_DPC_NIKON_FlashCommandBCompensation, /* 0xD1DB */ N_("Flash Command B Compensation")}, {PTP_DPC_NIKON_FlashCommandBValue, /* 0xD1DC */ N_("Flash Command B Value")}, {PTP_DPC_NIKON_ActivePicCtrlItem, /* 0xD200 */ N_("Active Pic Ctrl Item")}, {PTP_DPC_NIKON_ChangePicCtrlItem, /* 0xD201 */ N_("Change Pic Ctrl Item")}, {0,NULL} }; struct { uint16_t dpc; const char *txt; } ptp_device_properties_MTP[] = { {PTP_DPC_MTP_SecureTime, N_("Secure Time")}, /* D101 */ {PTP_DPC_MTP_DeviceCertificate, N_("Device Certificate")}, /* D102 */ {PTP_DPC_MTP_RevocationInfo, N_("Revocation Info")}, /* D103 */ {PTP_DPC_MTP_SynchronizationPartner, /* D401 */ N_("Synchronization Partner")}, {PTP_DPC_MTP_DeviceFriendlyName, /* D402 */ N_("Friendly Device Name")}, {PTP_DPC_MTP_VolumeLevel, N_("Volume Level")}, /* D403 */ {PTP_DPC_MTP_DeviceIcon, N_("Device Icon")}, /* D405 */ {PTP_DPC_MTP_SessionInitiatorInfo, N_("Session Initiator Info")},/* D406 */ {PTP_DPC_MTP_PerceivedDeviceType, N_("Perceived Device Type")},/* D407 */ {PTP_DPC_MTP_PlaybackRate, N_("Playback Rate")}, /* D410 */ {PTP_DPC_MTP_PlaybackObject, N_("Playback Object")}, /* D411 */ {PTP_DPC_MTP_PlaybackContainerIndex, /* D412 */ N_("Playback Container Index")}, {PTP_DPC_MTP_PlaybackPosition, N_("Playback Position")}, /* D413 */ {PTP_DPC_MTP_PlaysForSureID, N_("PlaysForSure ID")}, /* D131 (?) */ {0,NULL} }; struct { uint16_t dpc; const char *txt; } ptp_device_properties_FUJI[] = { {PTP_DPC_FUJI_ColorTemperature, N_("Color Temperature")}, /* 0xD017 */ {PTP_DPC_FUJI_Quality, N_("Quality")}, /* 0xD018 */ {PTP_DPC_FUJI_Quality, N_("Release Mode")}, /* 0xD201 */ {PTP_DPC_FUJI_Quality, N_("Focus Areas")}, /* 0xD206 */ {PTP_DPC_FUJI_Quality, N_("AE Lock")}, /* 0xD213 */ {PTP_DPC_FUJI_Quality, N_("Aperture")}, /* 0xD218 */ {PTP_DPC_FUJI_Quality, N_("Shutter Speed")}, /* 0xD219 */ {0,NULL} }; for (i=0; ptp_device_properties[i].txt!=NULL; i++) if (ptp_device_properties[i].dpc==dpc) return (ptp_device_properties[i].txt); if (params->deviceinfo.VendorExtensionID==PTP_VENDOR_MICROSOFT || params->deviceinfo.VendorExtensionID==PTP_VENDOR_MTP) for (i=0; ptp_device_properties_MTP[i].txt!=NULL; i++) if (ptp_device_properties_MTP[i].dpc==dpc) return (ptp_device_properties_MTP[i].txt); if (params->deviceinfo.VendorExtensionID==PTP_VENDOR_EASTMAN_KODAK) for (i=0; ptp_device_properties_EK[i].txt!=NULL; i++) if (ptp_device_properties_EK[i].dpc==dpc) return (ptp_device_properties_EK[i].txt); if (params->deviceinfo.VendorExtensionID==PTP_VENDOR_CANON) for (i=0; ptp_device_properties_Canon[i].txt!=NULL; i++) if (ptp_device_properties_Canon[i].dpc==dpc) return (ptp_device_properties_Canon[i].txt); if (params->deviceinfo.VendorExtensionID==PTP_VENDOR_NIKON) for (i=0; ptp_device_properties_Nikon[i].txt!=NULL; i++) if (ptp_device_properties_Nikon[i].dpc==dpc) return (ptp_device_properties_Nikon[i].txt); if (params->deviceinfo.VendorExtensionID==PTP_VENDOR_FUJI) for (i=0; ptp_device_properties_FUJI[i].txt!=NULL; i++) if (ptp_device_properties_FUJI[i].dpc==dpc) return (ptp_device_properties_FUJI[i].txt); return NULL; } static int64_t _value_to_num(PTPPropertyValue *data, uint16_t dt) { if (dt == PTP_DTC_STR) { if (!data->str) return 0; return atol(data->str); } if (dt & PTP_DTC_ARRAY_MASK) { return 0; } else { switch (dt) { case PTP_DTC_UNDEF: return 0; case PTP_DTC_INT8: return data->i8; case PTP_DTC_UINT8: return data->u8; case PTP_DTC_INT16: return data->i16; case PTP_DTC_UINT16: return data->u16; case PTP_DTC_INT32: return data->i32; case PTP_DTC_UINT32: return data->u32; /* PTP_DTC_INT64 PTP_DTC_UINT64 PTP_DTC_INT128 PTP_DTC_UINT128 */ default: return 0; } } return 0; } #define PTP_VAL_BOOL(dpc) {dpc, 0, N_("Off")}, {dpc, 1, N_("On")} #define PTP_VENDOR_VAL_BOOL(dpc,vendor) {dpc, vendor, 0, N_("Off")}, {dpc, vendor, 1, N_("On")} #define PTP_VENDOR_VAL_RBOOL(dpc,vendor) {dpc, vendor, 0, N_("On")}, {dpc, vendor, 1, N_("Off")} #define PTP_VENDOR_VAL_YN(dpc,vendor) {dpc, vendor, 0, N_("No")}, {dpc, vendor, 1, N_("Yes")} int ptp_render_property_value(PTPParams* params, uint16_t dpc, PTPDevicePropDesc *dpd, int length, char *out) { int i; int64_t kval; struct { uint16_t dpc; uint16_t vendor; double coef; double bias; const char *format; } ptp_value_trans[] = { {PTP_DPC_BatteryLevel, 0, 1.0, 0.0, "%.0f%%"}, /* 5001 */ {PTP_DPC_FNumber, 0, 0.01, 0.0, "f/%.2g"}, /* 5007 */ {PTP_DPC_FocalLength, 0, 0.01, 0.0, "%.0f mm"}, /* 5008 */ {PTP_DPC_FocusDistance, 0, 0.01, 0.0, "%.0f mm"}, /* 5009 */ {PTP_DPC_ExposureTime, 0, 0.00001, 0.0, "%.2g sec"}, /* 500D */ {PTP_DPC_ExposureIndex, 0, 1.0, 0.0, "ISO %.0f"}, /* 500F */ {PTP_DPC_ExposureBiasCompensation, 0, 0.001, 0.0, N_("%.1f stops")},/* 5010 */ {PTP_DPC_CaptureDelay, 0, 0.001, 0.0, "%.1fs"}, /* 5012 */ {PTP_DPC_DigitalZoom, 0, 0.1, 0.0, "%.1f"}, /* 5016 */ {PTP_DPC_BurstInterval, 0, 0.001, 0.0, "%.1fs"}, /* 5019 */ /* Nikon device properties */ {PTP_DPC_NIKON_LightMeter, PTP_VENDOR_NIKON, 0.08333, 0.0, N_("%.1f stops")},/* D10A */ {PTP_DPC_NIKON_FlashExposureCompensation, PTP_VENDOR_NIKON, 0.16666, 0.0, N_("%.1f stops")}, /* D126 */ {PTP_DPC_NIKON_CenterWeightArea, PTP_VENDOR_NIKON, 2.0, 6.0, N_("%.0f mm")},/* D059 */ {PTP_DPC_NIKON_FocalLengthMin, PTP_VENDOR_NIKON, 0.01, 0.0, "%.0f mm"}, /* D0E3 */ {PTP_DPC_NIKON_FocalLengthMax, PTP_VENDOR_NIKON, 0.01, 0.0, "%.0f mm"}, /* D0E4 */ {PTP_DPC_NIKON_MaxApAtMinFocalLength, PTP_VENDOR_NIKON, 0.01, 0.0, "f/%.2g"}, /* D0E5 */ {PTP_DPC_NIKON_MaxApAtMaxFocalLength, PTP_VENDOR_NIKON, 0.01, 0.0, "f/%.2g"}, /* D0E6 */ {PTP_DPC_NIKON_ExternalFlashCompensation, PTP_VENDOR_NIKON, 1.0/6.0, 0.0,"%.0f"}, /* D124 */ {PTP_DPC_NIKON_ExposureIndicateStatus, PTP_VENDOR_NIKON, 0.08333, 0.0, N_("%.1f stops")},/* D1B1 - FIXME: check if correct. */ {PTP_DPC_NIKON_AngleLevel, PTP_VENDOR_NIKON, 1.0/65536, 0.0, "%.1f'"},/* 0xD067 */ {0, 0, 0.0, 0.0, NULL} }; struct { uint16_t dpc; uint16_t vendor; int64_t key; char *value; } ptp_value_list[] = { {PTP_DPC_CompressionSetting, 0, 0, N_("JPEG Basic")}, /* 5004 */ {PTP_DPC_CompressionSetting, 0, 1, N_("JPEG Norm")}, {PTP_DPC_CompressionSetting, 0, 2, N_("JPEG Fine")}, {PTP_DPC_CompressionSetting, 0, 4, N_("RAW")}, {PTP_DPC_CompressionSetting, 0, 5, N_("RAW + JPEG Basic")}, {PTP_DPC_WhiteBalance, 0, 1, N_("Manual")}, {PTP_DPC_WhiteBalance, 0, 2, N_("Automatic")}, /* 5005 */ {PTP_DPC_WhiteBalance, 0, 3, N_("One-push Automatic")}, {PTP_DPC_WhiteBalance, 0, 4, N_("Daylight")}, {PTP_DPC_WhiteBalance, 0, 5, N_("Fluorescent")}, {PTP_DPC_WhiteBalance, 0, 6, N_("Incandescent")}, {PTP_DPC_WhiteBalance, 0, 7, N_("Flash")}, {PTP_DPC_WhiteBalance, PTP_VENDOR_NIKON, 32784, N_("Cloudy")}, {PTP_DPC_WhiteBalance, PTP_VENDOR_NIKON, 32785, N_("Shade")}, {PTP_DPC_WhiteBalance, PTP_VENDOR_NIKON, 32786, N_("Color Temperature")}, {PTP_DPC_WhiteBalance, PTP_VENDOR_NIKON, 32787, N_("Preset")}, {PTP_DPC_FocusMode, 0, 1, N_("Manual Focus")}, /* 500A */ {PTP_DPC_FocusMode, 0, 2, N_("Automatic")}, {PTP_DPC_FocusMode, 0, 3, N_("Automatic Macro (close-up)")}, {PTP_DPC_FocusMode, PTP_VENDOR_NIKON, 32784, "AF-S"}, {PTP_DPC_FocusMode, PTP_VENDOR_NIKON, 32785, "AF-C"}, {PTP_DPC_FocusMode, PTP_VENDOR_NIKON, 32786, "AF-A"}, {PTP_DPC_ExposureMeteringMode, 0, 1, N_("Average")}, /* 500B */ {PTP_DPC_ExposureMeteringMode, 0, 2, N_("Center Weighted Average")}, {PTP_DPC_ExposureMeteringMode, 0, 3, N_("Multi-spot")}, {PTP_DPC_ExposureMeteringMode, 0, 4, N_("Center-spot")}, {PTP_DPC_FlashMode, 0, 0, N_("Undefined")}, /* 500C */ {PTP_DPC_FlashMode, 0, 1, N_("Automatic flash")}, {PTP_DPC_FlashMode, 0, 2, N_("Flash off")}, {PTP_DPC_FlashMode, 0, 3, N_("Fill flash")}, {PTP_DPC_FlashMode, 0, 4, N_("Automatic Red-eye Reduction")}, {PTP_DPC_FlashMode, 0, 5, N_("Red-eye fill flash")}, {PTP_DPC_FlashMode, 0, 6, N_("External sync")}, {PTP_DPC_FlashMode, PTP_VENDOR_NIKON, 32784, N_("Auto")}, {PTP_DPC_FlashMode, PTP_VENDOR_NIKON, 32785, N_("Auto Slow Sync")}, {PTP_DPC_FlashMode, PTP_VENDOR_NIKON, 32786, N_("Rear Curtain Sync + Slow Sync")}, {PTP_DPC_FlashMode, PTP_VENDOR_NIKON, 32787, N_("Red-eye Reduction + Slow Sync")}, {PTP_DPC_ExposureProgramMode, 0, 1, "M"}, /* 500E */ {PTP_DPC_ExposureProgramMode, 0, 3, "A"}, {PTP_DPC_ExposureProgramMode, 0, 4, "S"}, {PTP_DPC_ExposureProgramMode, 0, 2, "P"}, {PTP_DPC_ExposureProgramMode, PTP_VENDOR_NIKON, 32784, N_("Auto")}, {PTP_DPC_ExposureProgramMode, PTP_VENDOR_NIKON, 32785, N_("Portrait")}, {PTP_DPC_ExposureProgramMode, PTP_VENDOR_NIKON, 32786, N_("Landscape")}, {PTP_DPC_ExposureProgramMode, PTP_VENDOR_NIKON, 32787, N_("Macro")}, {PTP_DPC_ExposureProgramMode, PTP_VENDOR_NIKON, 32788, N_("Sports")}, {PTP_DPC_ExposureProgramMode, PTP_VENDOR_NIKON, 32790, N_("Night Landscape")}, {PTP_DPC_ExposureProgramMode, PTP_VENDOR_NIKON, 32789, N_("Night Portrait")}, {PTP_DPC_StillCaptureMode, 0, 1, N_("Single Shot")}, /* 5013 */ {PTP_DPC_StillCaptureMode, 0, 2, N_("Power Wind")}, {PTP_DPC_StillCaptureMode, 0, 3, N_("Timelapse")}, {PTP_DPC_StillCaptureMode, PTP_VENDOR_NIKON, 32784, N_("Continuous Low Speed")}, {PTP_DPC_StillCaptureMode, PTP_VENDOR_NIKON, 32785, N_("Timer")}, {PTP_DPC_StillCaptureMode, PTP_VENDOR_NIKON, 32787, N_("Remote")}, {PTP_DPC_StillCaptureMode, PTP_VENDOR_NIKON, 32787, N_("Mirror Up")}, {PTP_DPC_StillCaptureMode, PTP_VENDOR_NIKON, 32788, N_("Timer + Remote")}, {PTP_DPC_FocusMeteringMode, 0, 1, N_("Centre-spot")}, /* 501C */ {PTP_DPC_FocusMeteringMode, 0, 2, N_("Multi-spot")}, {PTP_DPC_FocusMeteringMode, PTP_VENDOR_NIKON, 32784, N_("Single Area")}, {PTP_DPC_FocusMeteringMode, PTP_VENDOR_NIKON, 32785, N_("Closest Subject")}, {PTP_DPC_FocusMeteringMode, PTP_VENDOR_NIKON, 32786, N_("Group Dynamic")}, /* Nikon specific device properties */ {PTP_DPC_NIKON_ImageSharpening, PTP_VENDOR_NIKON, 0, N_("Auto")}, /* D02A */ {PTP_DPC_NIKON_ImageSharpening, PTP_VENDOR_NIKON, 1, N_("Normal")}, {PTP_DPC_NIKON_ImageSharpening, PTP_VENDOR_NIKON, 2, N_("Low")}, {PTP_DPC_NIKON_ImageSharpening, PTP_VENDOR_NIKON, 3, N_("Medium Low")}, {PTP_DPC_NIKON_ImageSharpening, PTP_VENDOR_NIKON, 4, N_("Medium high")}, {PTP_DPC_NIKON_ImageSharpening, PTP_VENDOR_NIKON, 5, N_("High")}, {PTP_DPC_NIKON_ImageSharpening, PTP_VENDOR_NIKON, 6, N_("None")}, {PTP_DPC_NIKON_ToneCompensation, PTP_VENDOR_NIKON, 0, N_("Auto")}, /* D02B */ {PTP_DPC_NIKON_ToneCompensation, PTP_VENDOR_NIKON, 1, N_("Normal")}, {PTP_DPC_NIKON_ToneCompensation, PTP_VENDOR_NIKON, 2, N_("Low contrast")}, {PTP_DPC_NIKON_ToneCompensation, PTP_VENDOR_NIKON, 3, N_("Medium Low")}, {PTP_DPC_NIKON_ToneCompensation, PTP_VENDOR_NIKON, 4, N_("Medium High")}, {PTP_DPC_NIKON_ToneCompensation, PTP_VENDOR_NIKON, 5, N_("High control")}, {PTP_DPC_NIKON_ToneCompensation, PTP_VENDOR_NIKON, 6, N_("Custom")}, {PTP_DPC_NIKON_ColorModel, PTP_VENDOR_NIKON, 0, "sRGB"}, /* D02C */ {PTP_DPC_NIKON_ColorModel, PTP_VENDOR_NIKON, 1, "AdobeRGB"}, {PTP_DPC_NIKON_ColorModel, PTP_VENDOR_NIKON, 2, "sRGB"}, PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_AutoDXCrop,PTP_VENDOR_NIKON), /* D033 */ PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_FocusAreaWrap,PTP_VENDOR_NIKON), /* D04F */ PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_EnableCopyright,PTP_VENDOR_NIKON), /* D053 */ PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_ISOAuto,PTP_VENDOR_NIKON), /* D054 */ /* FIXME! this is not ISO Auto (which is a bool) Perhaps ISO Auto Time?*/ {PTP_DPC_NIKON_ISOAuto, PTP_VENDOR_NIKON, 0, "1/125"}, /* D054 */ {PTP_DPC_NIKON_ISOAuto, PTP_VENDOR_NIKON, 1, "1/60"}, {PTP_DPC_NIKON_ISOAuto, PTP_VENDOR_NIKON, 2, "1/30"}, {PTP_DPC_NIKON_ISOAuto, PTP_VENDOR_NIKON, 3, "1/15"}, {PTP_DPC_NIKON_ISOAuto, PTP_VENDOR_NIKON, 4, "1/8"}, {PTP_DPC_NIKON_ISOAuto, PTP_VENDOR_NIKON, 5, "1/4"}, {PTP_DPC_NIKON_ISOAuto, PTP_VENDOR_NIKON, 6, "1/2"}, {PTP_DPC_NIKON_ISOAuto, PTP_VENDOR_NIKON, 7, "1"}, {PTP_DPC_NIKON_ISOAuto, PTP_VENDOR_NIKON, 8, "2"}, {PTP_DPC_NIKON_ISOAuto, PTP_VENDOR_NIKON, 9, "4"}, {PTP_DPC_NIKON_ISOAuto, PTP_VENDOR_NIKON, 10, "8"}, {PTP_DPC_NIKON_ISOAuto, PTP_VENDOR_NIKON, 11, "15"}, {PTP_DPC_NIKON_ISOAuto, PTP_VENDOR_NIKON, 12, "30"}, {PTP_DPC_NIKON_EVStep, PTP_VENDOR_NIKON, 0, "1/3"}, /* D056 */ {PTP_DPC_NIKON_EVStep, PTP_VENDOR_NIKON, 1, "1/2"}, PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_ExposureCompensation,PTP_VENDOR_NIKON),/*D058 */ PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_AELockMode,PTP_VENDOR_NIKON), /* D05E */ {PTP_DPC_NIKON_AELAFLMode, PTP_VENDOR_NIKON, 0, N_("AE/AF Lock")}, /* D05F */ {PTP_DPC_NIKON_AELAFLMode, PTP_VENDOR_NIKON, 1, N_("AF Lock only")}, {PTP_DPC_NIKON_AELAFLMode, PTP_VENDOR_NIKON, 2, N_("AE Lock only")}, {PTP_DPC_NIKON_AELAFLMode, PTP_VENDOR_NIKON, 3, N_("AF Lock Hold")}, {PTP_DPC_NIKON_AELAFLMode, PTP_VENDOR_NIKON, 4, N_("AF On")}, {PTP_DPC_NIKON_AELAFLMode, PTP_VENDOR_NIKON, 5, N_("Flash Lock")}, {PTP_DPC_NIKON_MeterOff, PTP_VENDOR_NIKON, 0, N_("4 seconds")}, /* D062 */ {PTP_DPC_NIKON_MeterOff, PTP_VENDOR_NIKON, 1, N_("6 seconds")}, {PTP_DPC_NIKON_MeterOff, PTP_VENDOR_NIKON, 2, N_("8 seconds")}, {PTP_DPC_NIKON_MeterOff, PTP_VENDOR_NIKON, 3, N_("16 seconds")}, {PTP_DPC_NIKON_MeterOff, PTP_VENDOR_NIKON, 4, N_("30 minutes")}, {PTP_DPC_NIKON_MeterOff, PTP_VENDOR_NIKON, 5, N_("30 seconds")}, {PTP_DPC_NIKON_SelfTimer, PTP_VENDOR_NIKON, 0, N_("2 seconds")}, /* D063 */ {PTP_DPC_NIKON_SelfTimer, PTP_VENDOR_NIKON, 1, N_("5 seconds")}, {PTP_DPC_NIKON_SelfTimer, PTP_VENDOR_NIKON, 2, N_("10 seconds")}, {PTP_DPC_NIKON_SelfTimer, PTP_VENDOR_NIKON, 3, N_("20 seconds")}, {PTP_DPC_NIKON_MonitorOff, PTP_VENDOR_NIKON, 0, N_("10 seconds")}, /* D064 */ {PTP_DPC_NIKON_MonitorOff, PTP_VENDOR_NIKON, 1, N_("20 seconds")}, {PTP_DPC_NIKON_MonitorOff, PTP_VENDOR_NIKON, 2, N_("1 minute")}, {PTP_DPC_NIKON_MonitorOff, PTP_VENDOR_NIKON, 3, N_("5 minutes")}, {PTP_DPC_NIKON_MonitorOff, PTP_VENDOR_NIKON, 4, N_("10 minutes")}, {PTP_DPC_NIKON_MonitorOff, PTP_VENDOR_NIKON, 5, N_("5 seconds")}, /* d80 observed */ PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_ExposureDelayMode,PTP_VENDOR_NIKON), /* D06A */ PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_LongExposureNoiseReduction,PTP_VENDOR_NIKON), /* D06B */ PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_FileNumberSequence,PTP_VENDOR_NIKON), /* D06C */ PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_D7Illumination,PTP_VENDOR_NIKON), /* D06F */ PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_SHSET_CH_GUID_DISP,PTP_VENDOR_NIKON), /* D071 */ {PTP_DPC_NIKON_FlashShutterSpeed, PTP_VENDOR_NIKON, 0, "1/60s"}, /* D075 */ {PTP_DPC_NIKON_FlashShutterSpeed, PTP_VENDOR_NIKON, 1, "1/30s"}, {PTP_DPC_NIKON_FlashShutterSpeed, PTP_VENDOR_NIKON, 2, "1/15s"}, {PTP_DPC_NIKON_FlashShutterSpeed, PTP_VENDOR_NIKON, 3, "1/8s"}, {PTP_DPC_NIKON_FlashShutterSpeed, PTP_VENDOR_NIKON, 4, "1/4s"}, {PTP_DPC_NIKON_FlashShutterSpeed, PTP_VENDOR_NIKON, 5, "1/2s"}, {PTP_DPC_NIKON_FlashShutterSpeed, PTP_VENDOR_NIKON, 6, "1s"}, {PTP_DPC_NIKON_FlashShutterSpeed, PTP_VENDOR_NIKON, 7, "2s"}, {PTP_DPC_NIKON_FlashShutterSpeed, PTP_VENDOR_NIKON, 8, "4s"}, {PTP_DPC_NIKON_FlashShutterSpeed, PTP_VENDOR_NIKON, 9, "8s"}, {PTP_DPC_NIKON_FlashShutterSpeed, PTP_VENDOR_NIKON, 10, "15s"}, {PTP_DPC_NIKON_FlashShutterSpeed, PTP_VENDOR_NIKON, 11, "30s"}, PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_E4ModelingFlash,PTP_VENDOR_NIKON), /* D077 */ {PTP_DPC_NIKON_BracketSet, PTP_VENDOR_NIKON, 0, N_("AE & Flash")}, /* D078 */ {PTP_DPC_NIKON_BracketSet, PTP_VENDOR_NIKON, 1, N_("AE only")}, {PTP_DPC_NIKON_BracketSet, PTP_VENDOR_NIKON, 2, N_("Flash only")}, {PTP_DPC_NIKON_BracketSet, PTP_VENDOR_NIKON, 3, N_("WB bracketing")}, {PTP_DPC_NIKON_BracketOrder, PTP_VENDOR_NIKON, 0, N_("MTR > Under")}, /* D07A */ {PTP_DPC_NIKON_BracketOrder, PTP_VENDOR_NIKON, 1, N_("Under > MTR")}, {PTP_DPC_NIKON_F1CenterButtonShootingMode, PTP_VENDOR_NIKON, 0, N_("Reset focus point to center")}, /* D080 */ {PTP_DPC_NIKON_F1CenterButtonShootingMode, PTP_VENDOR_NIKON, 1, N_("Highlight active focus point")}, {PTP_DPC_NIKON_F1CenterButtonShootingMode, PTP_VENDOR_NIKON, 2, N_("Unused")}, PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_F3PhotoInfoPlayback,PTP_VENDOR_NIKON),/* D083 */ PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_F5CustomizeCommDials,PTP_VENDOR_NIKON),/* D085 */ PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_ReverseCommandDial,PTP_VENDOR_NIKON), /* D086 */ PTP_VENDOR_VAL_RBOOL(PTP_DPC_NIKON_F6ButtonsAndDials,PTP_VENDOR_NIKON), /* D089 */ PTP_VENDOR_VAL_RBOOL(PTP_DPC_NIKON_NoCFCard,PTP_VENDOR_NIKON), /* D08A */ PTP_VENDOR_VAL_RBOOL(PTP_DPC_NIKON_AFAreaPoint,PTP_VENDOR_NIKON), /* D08D */ PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_ImageCommentEnable,PTP_VENDOR_NIKON), /* D091 */ PTP_VENDOR_VAL_RBOOL(PTP_DPC_NIKON_ImageRotation,PTP_VENDOR_NIKON), /* D092 */ PTP_VENDOR_VAL_RBOOL(PTP_DPC_NIKON_MovVoice,PTP_VENDOR_NIKON), /* D0A1 */ PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_Bracketing,PTP_VENDOR_NIKON), /* D0C0 */ /* http://www.rottmerhusen.com/objektives/lensid/nikkor.html is complete */ {PTP_DPC_NIKON_LensID, PTP_VENDOR_NIKON, 0, N_("Unknown")}, /* D0E0 */ {PTP_DPC_NIKON_LensID, PTP_VENDOR_NIKON, 38, "Sigma 70-300mm 1:4-5.6 D APO Macro"}, {PTP_DPC_NIKON_LensID, PTP_VENDOR_NIKON, 83, "AF Nikkor 80-200mm 1:2.8 D ED"}, {PTP_DPC_NIKON_LensID, PTP_VENDOR_NIKON, 118, "AF Nikkor 50mm 1:1.8 D"}, {PTP_DPC_NIKON_LensID, PTP_VENDOR_NIKON, 127, "AF-S Nikkor 18-70mm 1:3.5-4.5G ED DX"}, {PTP_DPC_NIKON_LensID, PTP_VENDOR_NIKON, 139, "AF-S Nikkor 18-200mm 1:3.5-5.6 GED DX VR"}, {PTP_DPC_NIKON_LensID, PTP_VENDOR_NIKON, 147, "AF-S Nikkor 24-70mm 1:2.8G ED DX"}, {PTP_DPC_NIKON_LensID, PTP_VENDOR_NIKON, 154, "AF-S Nikkor 18-55mm 1:3.5-F5.6G DX VR"}, {PTP_DPC_NIKON_LensID, PTP_VENDOR_NIKON, 159, "AF-S Nikkor 35mm 1:1.8G DX"}, {PTP_DPC_NIKON_FinderISODisp, PTP_VENDOR_NIKON, 0, "Show ISO sensitivity"},/* 0xD0F0 */ {PTP_DPC_NIKON_FinderISODisp, PTP_VENDOR_NIKON, 1, "Show ISO/Easy ISO"}, {PTP_DPC_NIKON_FinderISODisp, PTP_VENDOR_NIKON, 2, "Show frame count"}, {PTP_DPC_NIKON_RawCompression, PTP_VENDOR_NIKON, 0, N_("Lossless")}, /* D016 */ {PTP_DPC_NIKON_RawCompression, PTP_VENDOR_NIKON, 1, N_("Lossy")}, PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_ACPower,PTP_VENDOR_NIKON), /* D101 */ PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_AFLockStatus,PTP_VENDOR_NIKON), /* D104 */ PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_AELockStatus,PTP_VENDOR_NIKON), /* D105 */ PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_FVLockStatus,PTP_VENDOR_NIKON), /* D106 */ {PTP_DPC_NIKON_AutofocusArea, PTP_VENDOR_NIKON, 0, N_("Centre")}, /* D108 */ {PTP_DPC_NIKON_AutofocusArea, PTP_VENDOR_NIKON, 1, N_("Top")}, {PTP_DPC_NIKON_AutofocusArea, PTP_VENDOR_NIKON, 2, N_("Bottom")}, {PTP_DPC_NIKON_AutofocusArea, PTP_VENDOR_NIKON, 3, N_("Left")}, {PTP_DPC_NIKON_AutofocusArea, PTP_VENDOR_NIKON, 4, N_("Right")}, {PTP_DPC_NIKON_RecordingMedia, PTP_VENDOR_NIKON, 0, N_("Card")}, /* D10B */ {PTP_DPC_NIKON_RecordingMedia, PTP_VENDOR_NIKON, 1, N_("SDRam")}, {PTP_DPC_NIKON_USBSpeed, PTP_VENDOR_NIKON, 0, N_("USB 1.1")}, /* D10C */ {PTP_DPC_NIKON_USBSpeed, PTP_VENDOR_NIKON, 1, N_("USB 2.0")}, {PTP_DPC_NIKON_CameraOrientation, PTP_VENDOR_NIKON, 0, "0'"}, /* D10E */ {PTP_DPC_NIKON_CameraOrientation, PTP_VENDOR_NIKON, 1, "270'"}, {PTP_DPC_NIKON_CameraOrientation, PTP_VENDOR_NIKON, 2, "90'"}, {PTP_DPC_NIKON_CameraOrientation, PTP_VENDOR_NIKON, 3, "180'"}, PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_FNumberLock,PTP_VENDOR_NIKON), /* D110 */ PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_ExposureApertureLock,PTP_VENDOR_NIKON), /* D111 */ PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_TVLockSetting,PTP_VENDOR_NIKON), /* D112 */ PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_AVLockSetting,PTP_VENDOR_NIKON), /* D113 */ {PTP_DPC_NIKON_IllumSetting,PTP_VENDOR_NIKON,0,N_("LCD Backlight")}, /* D114 */ {PTP_DPC_NIKON_IllumSetting,PTP_VENDOR_NIKON,1,N_("LCD Backlight and Info Display")}, PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_ExternalFlashAttached,PTP_VENDOR_NIKON),/* D120 */ PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_ExternalFlashStatus,PTP_VENDOR_NIKON), /* D121 */ {PTP_DPC_NIKON_OptimizeImage, PTP_VENDOR_NIKON, 0, N_("Normal")}, /* D140 */ {PTP_DPC_NIKON_OptimizeImage, PTP_VENDOR_NIKON, 1, N_("Vivid")}, {PTP_DPC_NIKON_OptimizeImage, PTP_VENDOR_NIKON, 2, N_("Sharper")}, {PTP_DPC_NIKON_OptimizeImage, PTP_VENDOR_NIKON, 3, N_("Softer")}, {PTP_DPC_NIKON_OptimizeImage, PTP_VENDOR_NIKON, 4, N_("Direct Print")}, {PTP_DPC_NIKON_OptimizeImage, PTP_VENDOR_NIKON, 5, N_("Portrait")}, {PTP_DPC_NIKON_OptimizeImage, PTP_VENDOR_NIKON, 6, N_("Landscape")}, {PTP_DPC_NIKON_OptimizeImage, PTP_VENDOR_NIKON, 7, N_("Custom")}, {PTP_DPC_NIKON_Saturation, PTP_VENDOR_NIKON, 0, N_("Normal")}, /* D142 */ {PTP_DPC_NIKON_Saturation, PTP_VENDOR_NIKON, 1, N_("Moderate")}, {PTP_DPC_NIKON_Saturation, PTP_VENDOR_NIKON, 2, N_("Enhanced")}, PTP_VENDOR_VAL_RBOOL(PTP_DPC_NIKON_BeepOff,PTP_VENDOR_NIKON), /* D160 */ {PTP_DPC_NIKON_AutofocusMode, PTP_VENDOR_NIKON, 0, N_("AF-S")}, /* D161 */ {PTP_DPC_NIKON_AutofocusMode, PTP_VENDOR_NIKON, 1, N_("AF-C")}, {PTP_DPC_NIKON_AutofocusMode, PTP_VENDOR_NIKON, 2, N_("AF-A")}, {PTP_DPC_NIKON_AutofocusMode, PTP_VENDOR_NIKON, 3, N_("MF (fixed)")}, {PTP_DPC_NIKON_AutofocusMode, PTP_VENDOR_NIKON, 4, N_("MF (selection)")}, PTP_VENDOR_VAL_RBOOL(PTP_DPC_NIKON_AFAssist,PTP_VENDOR_NIKON), /* D163 */ {PTP_DPC_NIKON_PADVPMode, PTP_VENDOR_NIKON, 0, "1/125"}, /* D164 */ {PTP_DPC_NIKON_PADVPMode, PTP_VENDOR_NIKON, 1, "1/60"}, {PTP_DPC_NIKON_PADVPMode, PTP_VENDOR_NIKON, 2, "1/30"}, {PTP_DPC_NIKON_PADVPMode, PTP_VENDOR_NIKON, 3, "1/15"}, {PTP_DPC_NIKON_PADVPMode, PTP_VENDOR_NIKON, 4, "1/8"}, {PTP_DPC_NIKON_PADVPMode, PTP_VENDOR_NIKON, 5, "1/4"}, {PTP_DPC_NIKON_PADVPMode, PTP_VENDOR_NIKON, 6, "1/2"}, {PTP_DPC_NIKON_PADVPMode, PTP_VENDOR_NIKON, 7, "1"}, {PTP_DPC_NIKON_PADVPMode, PTP_VENDOR_NIKON, 8, "2"}, {PTP_DPC_NIKON_PADVPMode, PTP_VENDOR_NIKON, 9, "4"}, {PTP_DPC_NIKON_PADVPMode, PTP_VENDOR_NIKON, 10, "8"}, {PTP_DPC_NIKON_PADVPMode, PTP_VENDOR_NIKON, 11, "15"}, {PTP_DPC_NIKON_PADVPMode, PTP_VENDOR_NIKON, 12, "30"}, PTP_VENDOR_VAL_RBOOL(PTP_DPC_NIKON_ImageReview,PTP_VENDOR_NIKON), /* D165 */ {PTP_DPC_NIKON_AFAreaIllumination, PTP_VENDOR_NIKON, 0, N_("Auto")}, /* D166 */ {PTP_DPC_NIKON_AFAreaIllumination, PTP_VENDOR_NIKON, 1, N_("Off")}, {PTP_DPC_NIKON_AFAreaIllumination, PTP_VENDOR_NIKON, 2, N_("On")}, {PTP_DPC_NIKON_FlashMode, PTP_VENDOR_NIKON, 0, "iTTL"}, /* D167 */ {PTP_DPC_NIKON_FlashMode, PTP_VENDOR_NIKON, 1, N_("Manual")}, {PTP_DPC_NIKON_FlashMode, PTP_VENDOR_NIKON, 2, N_("Commander")}, {PTP_DPC_NIKON_FlashCommanderMode, PTP_VENDOR_NIKON, 0, N_("TTL")}, /* D168 */ {PTP_DPC_NIKON_FlashCommanderMode, PTP_VENDOR_NIKON, 1, N_("Auto Aperture")}, {PTP_DPC_NIKON_FlashCommanderMode, PTP_VENDOR_NIKON, 2, N_("Full Manual")}, PTP_VENDOR_VAL_RBOOL(PTP_DPC_NIKON_FlashSign,PTP_VENDOR_NIKON), /* D169 */ {PTP_DPC_NIKON_RemoteTimeout, PTP_VENDOR_NIKON, 0, N_("1 min")}, /* D16B */ {PTP_DPC_NIKON_RemoteTimeout, PTP_VENDOR_NIKON, 1, N_("5 mins")}, {PTP_DPC_NIKON_RemoteTimeout, PTP_VENDOR_NIKON, 2, N_("10 mins")}, {PTP_DPC_NIKON_RemoteTimeout, PTP_VENDOR_NIKON, 3, N_("15 mins")}, PTP_VENDOR_VAL_BOOL(PTP_DPC_NIKON_GridDisplay,PTP_VENDOR_NIKON), /* D16C */ {PTP_DPC_NIKON_FlashModeManualPower, PTP_VENDOR_NIKON, 0, N_("Full")}, /* D16D */ {PTP_DPC_NIKON_FlashModeManualPower, PTP_VENDOR_NIKON, 1, "1/2"}, {PTP_DPC_NIKON_FlashModeManualPower, PTP_VENDOR_NIKON, 2, "1/4"}, {PTP_DPC_NIKON_FlashModeManualPower, PTP_VENDOR_NIKON, 3, "1/8"}, {PTP_DPC_NIKON_FlashModeManualPower, PTP_VENDOR_NIKON, 4, "1/16"}, {PTP_DPC_NIKON_FlashModeCommanderPower, PTP_VENDOR_NIKON, 0, N_("Full")},/* D16E */ {PTP_DPC_NIKON_FlashModeCommanderPower, PTP_VENDOR_NIKON, 1, "1/2"}, {PTP_DPC_NIKON_FlashModeCommanderPower, PTP_VENDOR_NIKON, 2, "1/4"}, {PTP_DPC_NIKON_FlashModeCommanderPower, PTP_VENDOR_NIKON, 3, "1/8"}, {PTP_DPC_NIKON_FlashModeCommanderPower, PTP_VENDOR_NIKON, 4, "1/16"}, {PTP_DPC_NIKON_FlashModeCommanderPower, PTP_VENDOR_NIKON, 5, "1/32"}, {PTP_DPC_NIKON_FlashModeCommanderPower, PTP_VENDOR_NIKON, 6, "1/64"}, {PTP_DPC_NIKON_FlashModeCommanderPower, PTP_VENDOR_NIKON, 7, "1/128"}, PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_CSMMenu,PTP_VENDOR_NIKON), /* D180 */ PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_WarningDisplay,PTP_VENDOR_NIKON), /* D181 */ {PTP_DPC_NIKON_BatteryCellKind, PTP_VENDOR_NIKON, 0, "LR6 (AA alkaline)"},/* D182 */ {PTP_DPC_NIKON_BatteryCellKind, PTP_VENDOR_NIKON, 1, "HR6 (AA Ni-Mh)"}, {PTP_DPC_NIKON_BatteryCellKind, PTP_VENDOR_NIKON, 2, "FR6 (AA Lithium)"}, {PTP_DPC_NIKON_BatteryCellKind, PTP_VENDOR_NIKON, 3, "ZR6 (AA Ni-Mn)"}, {PTP_DPC_NIKON_ISOAutoHiLimit, PTP_VENDOR_NIKON, 0, "400"}, /* D183 */ {PTP_DPC_NIKON_ISOAutoHiLimit, PTP_VENDOR_NIKON, 1, "800"}, {PTP_DPC_NIKON_ISOAutoHiLimit, PTP_VENDOR_NIKON, 2, "1600"}, {PTP_DPC_NIKON_ISOAutoHiLimit, PTP_VENDOR_NIKON, 3, "3200"}, {PTP_DPC_NIKON_ISOAutoHiLimit, PTP_VENDOR_NIKON, 4, "Hi 1"}, {PTP_DPC_NIKON_ISOAutoHiLimit, PTP_VENDOR_NIKON, 5, "Hi 2"}, {PTP_DPC_NIKON_InfoDispSetting, PTP_VENDOR_NIKON, 0, N_("Auto")}, /* 0xD187 */ {PTP_DPC_NIKON_InfoDispSetting, PTP_VENDOR_NIKON, 1, N_("Dark on light")}, {PTP_DPC_NIKON_InfoDispSetting, PTP_VENDOR_NIKON, 2, N_("Light on dark")}, PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_IndicatorDisp,PTP_VENDOR_NIKON), /* D18D */ PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_LiveViewStatus,PTP_VENDOR_NIKON), /* D1A2 */ PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_ExposureDisplayStatus,PTP_VENDOR_NIKON),/* D1B0 */ PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_InfoDispErrStatus,PTP_VENDOR_NIKON), /* D1B2 */ PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_ExposureIndicateLightup,PTP_VENDOR_NIKON),/* D1B3 */ PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_FlashOpen,PTP_VENDOR_NIKON), /* D1C0 */ PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_FlashCharged,PTP_VENDOR_NIKON), /* D1C1 */ PTP_VENDOR_VAL_YN(PTP_DPC_NIKON_ManualMovieSetting,PTP_VENDOR_NIKON), /* 0xD0A6 */ {PTP_DPC_NIKON_FlickerReduction, PTP_VENDOR_NIKON, 0, "50Hz"}, /* 0xD034 */ {PTP_DPC_NIKON_FlickerReduction, PTP_VENDOR_NIKON, 1, "60Hz"}, {PTP_DPC_NIKON_RemoteMode, PTP_VENDOR_NIKON, 0, N_("Delayed Remote")}, /* 0xD035 */ {PTP_DPC_NIKON_RemoteMode, PTP_VENDOR_NIKON, 1, N_("Quick Response")}, /* 0xD035 */ {PTP_DPC_NIKON_RemoteMode, PTP_VENDOR_NIKON, 2, N_("Remote Mirror Up")},/* 0xD035 */ {PTP_DPC_NIKON_MonitorOffDelay, PTP_VENDOR_NIKON, 0, "5min"}, /* 0xD0b3 */ {PTP_DPC_NIKON_MonitorOffDelay, PTP_VENDOR_NIKON, 1, "10min"}, /* 0xD0b3 */ {PTP_DPC_NIKON_MonitorOffDelay, PTP_VENDOR_NIKON, 2, "15min"}, /* 0xD0b3 */ {PTP_DPC_NIKON_MonitorOffDelay, PTP_VENDOR_NIKON, 3, "20min"}, /* 0xD0b3 */ {PTP_DPC_NIKON_MonitorOffDelay, PTP_VENDOR_NIKON, 4, "30min"}, /* 0xD0b3 */ /* Canon stuff */ PTP_VENDOR_VAL_BOOL(PTP_DPC_CANON_AssistLight,PTP_VENDOR_CANON), PTP_VENDOR_VAL_RBOOL(PTP_DPC_CANON_RotationScene,PTP_VENDOR_CANON), PTP_VENDOR_VAL_RBOOL(PTP_DPC_CANON_BeepMode,PTP_VENDOR_CANON), PTP_VENDOR_VAL_BOOL(PTP_DPC_CANON_Beep,PTP_VENDOR_CANON), {PTP_DPC_CANON_RotationAngle, PTP_VENDOR_CANON, 0, "0'"}, {PTP_DPC_CANON_RotationAngle, PTP_VENDOR_CANON, 3, "270'"}, {PTP_DPC_CANON_RotationAngle, PTP_VENDOR_CANON, 1, "90'"}, {PTP_DPC_CANON_BatteryKind, PTP_VENDOR_CANON, 0, N_("Unknown")}, {PTP_DPC_CANON_BatteryKind, PTP_VENDOR_CANON, 1, N_("AC")}, {PTP_DPC_CANON_BatteryKind, PTP_VENDOR_CANON, 2, N_("Lithium Ion")}, {PTP_DPC_CANON_BatteryKind, PTP_VENDOR_CANON, 3, N_("Nickel hydride")}, {PTP_DPC_CANON_BatteryKind, PTP_VENDOR_CANON, 4, N_("Nickel cadmium")}, {PTP_DPC_CANON_BatteryKind, PTP_VENDOR_CANON, 5, N_("Alkalium manganese")}, {PTP_DPC_CANON_BatteryStatus, PTP_VENDOR_CANON, 0, N_("Undefined")}, {PTP_DPC_CANON_BatteryStatus, PTP_VENDOR_CANON, 1, N_("Normal")}, {PTP_DPC_CANON_BatteryStatus, PTP_VENDOR_CANON, 2, N_("Warning Level 1")}, {PTP_DPC_CANON_BatteryStatus, PTP_VENDOR_CANON, 3, N_("Emergency")}, {PTP_DPC_CANON_BatteryStatus, PTP_VENDOR_CANON, 4, N_("Warning Level 0")}, {PTP_DPC_CANON_ImageQuality, PTP_VENDOR_CANON, 0, N_("Undefined")}, {PTP_DPC_CANON_ImageQuality, PTP_VENDOR_CANON, 1, N_("Economy")}, {PTP_DPC_CANON_ImageQuality, PTP_VENDOR_CANON, 2, N_("Normal")}, {PTP_DPC_CANON_ImageQuality, PTP_VENDOR_CANON, 3, N_("Fine")}, {PTP_DPC_CANON_ImageQuality, PTP_VENDOR_CANON, 4, N_("Lossless")}, {PTP_DPC_CANON_ImageQuality, PTP_VENDOR_CANON, 5, N_("SuperFine")}, {PTP_DPC_CANON_FullViewFileFormat, PTP_VENDOR_CANON, 0, N_("Undefined")}, {PTP_DPC_CANON_FullViewFileFormat, PTP_VENDOR_CANON, 1, N_("JPEG")}, {PTP_DPC_CANON_FullViewFileFormat, PTP_VENDOR_CANON, 2, N_("CRW")}, {PTP_DPC_CANON_ImageSize, PTP_VENDOR_CANON, 0, N_("Large")}, {PTP_DPC_CANON_ImageSize, PTP_VENDOR_CANON, 1, N_("Medium 1")}, {PTP_DPC_CANON_ImageSize, PTP_VENDOR_CANON, 2, N_("Small")}, {PTP_DPC_CANON_ImageSize, PTP_VENDOR_CANON, 3, N_("Medium 2")}, {PTP_DPC_CANON_ImageSize, PTP_VENDOR_CANON, 7, N_("Medium 3")}, {PTP_DPC_CANON_SelfTime, PTP_VENDOR_CANON, 0, N_("Not used")}, {PTP_DPC_CANON_SelfTime, PTP_VENDOR_CANON, 100, N_("10 seconds")}, {PTP_DPC_CANON_SelfTime, PTP_VENDOR_CANON, 20, N_("2 seconds")}, {PTP_DPC_CANON_FlashMode, PTP_VENDOR_CANON, 0, N_("Off")}, {PTP_DPC_CANON_FlashMode, PTP_VENDOR_CANON, 1, N_("Auto")}, {PTP_DPC_CANON_FlashMode, PTP_VENDOR_CANON, 2, N_("On")}, {PTP_DPC_CANON_FlashMode, PTP_VENDOR_CANON, 3, N_("Red Eye Suppression")}, {PTP_DPC_CANON_FlashMode, PTP_VENDOR_CANON, 4, N_("Low Speed Synchronization")}, {PTP_DPC_CANON_FlashMode, PTP_VENDOR_CANON, 5, N_("Auto + Red Eye Suppression")}, {PTP_DPC_CANON_FlashMode, PTP_VENDOR_CANON, 6, N_("On + Red Eye Suppression")}, {PTP_DPC_CANON_ShootingMode, PTP_VENDOR_CANON, 0, N_("Auto")}, {PTP_DPC_CANON_ShootingMode, PTP_VENDOR_CANON, 1, N_("P")}, {PTP_DPC_CANON_ShootingMode, PTP_VENDOR_CANON, 2, N_("Tv")}, {PTP_DPC_CANON_ShootingMode, PTP_VENDOR_CANON, 3, N_("Av")}, {PTP_DPC_CANON_ShootingMode, PTP_VENDOR_CANON, 4, N_("M")}, {PTP_DPC_CANON_ShootingMode, PTP_VENDOR_CANON, 5, N_("A_DEP")}, {PTP_DPC_CANON_ShootingMode, PTP_VENDOR_CANON, 6, N_("M_DEP")}, {PTP_DPC_CANON_ShootingMode, PTP_VENDOR_CANON, 7, N_("Bulb")}, /* more actually */ {PTP_DPC_CANON_ImageMode, PTP_VENDOR_CANON, 0, N_("Auto")}, {PTP_DPC_CANON_ImageMode, PTP_VENDOR_CANON, 1, N_("Manual")}, {PTP_DPC_CANON_ImageMode, PTP_VENDOR_CANON, 2, N_("Distant View")}, {PTP_DPC_CANON_ImageMode, PTP_VENDOR_CANON, 3, N_("High-Speed Shutter")}, {PTP_DPC_CANON_ImageMode, PTP_VENDOR_CANON, 4, N_("Low-Speed Shutter")}, {PTP_DPC_CANON_ImageMode, PTP_VENDOR_CANON, 5, N_("Night View")}, {PTP_DPC_CANON_ImageMode, PTP_VENDOR_CANON, 6, N_("Grayscale")}, {PTP_DPC_CANON_ImageMode, PTP_VENDOR_CANON, 7, N_("Sepia")}, {PTP_DPC_CANON_ImageMode, PTP_VENDOR_CANON, 8, N_("Portrait")}, {PTP_DPC_CANON_ImageMode, PTP_VENDOR_CANON, 9, N_("Sports")}, {PTP_DPC_CANON_ImageMode, PTP_VENDOR_CANON, 10, N_("Macro")}, {PTP_DPC_CANON_ImageMode, PTP_VENDOR_CANON, 11, N_("Monochrome")}, {PTP_DPC_CANON_ImageMode, PTP_VENDOR_CANON, 12, N_("Pan Focus")}, {PTP_DPC_CANON_ImageMode, PTP_VENDOR_CANON, 13, N_("Neutral")}, {PTP_DPC_CANON_ImageMode, PTP_VENDOR_CANON, 14, N_("Soft")}, {PTP_DPC_CANON_DriveMode, PTP_VENDOR_CANON, 0, N_("Single-Frame Shooting")}, {PTP_DPC_CANON_DriveMode, PTP_VENDOR_CANON, 1, N_("Continuous Shooting")}, {PTP_DPC_CANON_DriveMode, PTP_VENDOR_CANON, 2, N_("Timer (Single) Shooting")}, {PTP_DPC_CANON_DriveMode, PTP_VENDOR_CANON, 4, N_("Continuous Low-speed Shooting")}, {PTP_DPC_CANON_DriveMode, PTP_VENDOR_CANON, 5, N_("Continuous High-speed Shooting")}, {PTP_DPC_CANON_EZoom, PTP_VENDOR_CANON, 0, N_("Off")}, {PTP_DPC_CANON_EZoom, PTP_VENDOR_CANON, 1, N_("2x")}, {PTP_DPC_CANON_EZoom, PTP_VENDOR_CANON, 2, N_("4x")}, {PTP_DPC_CANON_EZoom, PTP_VENDOR_CANON, 3, N_("Smooth")}, {PTP_DPC_CANON_MeteringMode, PTP_VENDOR_CANON, 0, N_("Center-weighted Metering")}, {PTP_DPC_CANON_MeteringMode, PTP_VENDOR_CANON, 1, N_("Spot Metering")}, {PTP_DPC_CANON_MeteringMode, PTP_VENDOR_CANON, 2, N_("Average Metering")}, {PTP_DPC_CANON_MeteringMode, PTP_VENDOR_CANON, 3, N_("Evaluative Metering")}, {PTP_DPC_CANON_MeteringMode, PTP_VENDOR_CANON, 4, N_("Partial Metering")}, {PTP_DPC_CANON_MeteringMode, PTP_VENDOR_CANON, 5, N_("Center-weighted Average Metering")}, {PTP_DPC_CANON_MeteringMode, PTP_VENDOR_CANON, 6, N_("Spot Metering Interlocked with AF Frame")}, {PTP_DPC_CANON_MeteringMode, PTP_VENDOR_CANON, 7, N_("Multi-Spot Metering")}, {PTP_DPC_CANON_AFDistance, PTP_VENDOR_CANON, 0, N_("Manual")}, {PTP_DPC_CANON_AFDistance, PTP_VENDOR_CANON, 1, N_("Auto")}, {PTP_DPC_CANON_AFDistance, PTP_VENDOR_CANON, 2, N_("Unknown")}, {PTP_DPC_CANON_AFDistance, PTP_VENDOR_CANON, 3, N_("Zone Focus (Close-up)")}, {PTP_DPC_CANON_AFDistance, PTP_VENDOR_CANON, 4, N_("Zone Focus (Very Close)")}, {PTP_DPC_CANON_AFDistance, PTP_VENDOR_CANON, 5, N_("Zone Focus (Close)")}, {PTP_DPC_CANON_AFDistance, PTP_VENDOR_CANON, 6, N_("Zone Focus (Medium)")}, {PTP_DPC_CANON_AFDistance, PTP_VENDOR_CANON, 7, N_("Zone Focus (Far)")}, {PTP_DPC_CANON_FocusingPoint, PTP_VENDOR_CANON, 0, N_("Invalid")}, {PTP_DPC_CANON_FocusingPoint, PTP_VENDOR_CANON, 0x1000, N_("Focusing Point on Center Only, Manual")}, {PTP_DPC_CANON_FocusingPoint, PTP_VENDOR_CANON, 0x1001, N_("Focusing Point on Center Only, Auto")}, {PTP_DPC_CANON_FocusingPoint, PTP_VENDOR_CANON, 0x3000, N_("Multiple Focusing Points (No Specification), Manual")}, {PTP_DPC_CANON_FocusingPoint, PTP_VENDOR_CANON, 0x3001, N_("Multiple Focusing Points, Auto")}, {PTP_DPC_CANON_FocusingPoint, PTP_VENDOR_CANON, 0x3002, N_("Multiple Focusing Points (Right)")}, {PTP_DPC_CANON_FocusingPoint, PTP_VENDOR_CANON, 0x3003, N_("Multiple Focusing Points (Center)")}, {PTP_DPC_CANON_FocusingPoint, PTP_VENDOR_CANON, 0x3004, N_("Multiple Focusing Points (Left)")}, {PTP_DPC_CANON_WhiteBalance, PTP_VENDOR_CANON, 0, N_("Auto")}, {PTP_DPC_CANON_WhiteBalance, PTP_VENDOR_CANON, 1, N_("Daylight")}, {PTP_DPC_CANON_WhiteBalance, PTP_VENDOR_CANON, 2, N_("Cloudy")}, {PTP_DPC_CANON_WhiteBalance, PTP_VENDOR_CANON, 3, N_("Tungsten")}, {PTP_DPC_CANON_WhiteBalance, PTP_VENDOR_CANON, 4, N_("Fluorescent")}, {PTP_DPC_CANON_WhiteBalance, PTP_VENDOR_CANON, 6, N_("Preset")}, {PTP_DPC_CANON_WhiteBalance, PTP_VENDOR_CANON, 7, N_("Fluorescent H")}, {PTP_DPC_CANON_WhiteBalance, PTP_VENDOR_CANON, 9, N_("Color Temperature")}, {PTP_DPC_CANON_WhiteBalance, PTP_VENDOR_CANON, 10, N_("Custom Whitebalance PC-1")}, {PTP_DPC_CANON_WhiteBalance, PTP_VENDOR_CANON, 11, N_("Custom Whitebalance PC-2")}, {PTP_DPC_CANON_WhiteBalance, PTP_VENDOR_CANON, 12, N_("Custom Whitebalance PC-3")}, {PTP_DPC_CANON_WhiteBalance, PTP_VENDOR_CANON, 13, N_("Missing Number")}, {PTP_DPC_CANON_WhiteBalance, PTP_VENDOR_CANON, 14, N_("Fluorescent H")}, /* dup? */ {PTP_DPC_CANON_SlowShutterSetting, PTP_VENDOR_CANON, 0, N_("Off")}, {PTP_DPC_CANON_SlowShutterSetting, PTP_VENDOR_CANON, 1, N_("Night View")}, {PTP_DPC_CANON_SlowShutterSetting, PTP_VENDOR_CANON, 2, N_("On")}, {PTP_DPC_CANON_SlowShutterSetting, PTP_VENDOR_CANON, 3, N_("Low-speed shutter function not available")}, {PTP_DPC_CANON_AFMode, PTP_VENDOR_CANON, 0, N_("Single Shot")}, {PTP_DPC_CANON_AFMode, PTP_VENDOR_CANON, 1, N_("AI Servo")}, {PTP_DPC_CANON_AFMode, PTP_VENDOR_CANON, 2, N_("AI Focus")}, {PTP_DPC_CANON_AFMode, PTP_VENDOR_CANON, 3, N_("Manual")}, {PTP_DPC_CANON_AFMode, PTP_VENDOR_CANON, 4, N_("Continuous")}, PTP_VENDOR_VAL_BOOL(PTP_DPC_CANON_ImageStabilization,PTP_VENDOR_CANON), {PTP_DPC_CANON_Contrast, PTP_VENDOR_CANON, -2, N_("Low 2")}, {PTP_DPC_CANON_Contrast, PTP_VENDOR_CANON, -1, N_("Low")}, {PTP_DPC_CANON_Contrast, PTP_VENDOR_CANON, 0, N_("Standard")}, {PTP_DPC_CANON_Contrast, PTP_VENDOR_CANON, 1, N_("High")}, {PTP_DPC_CANON_Contrast, PTP_VENDOR_CANON, 2, N_("High 2")}, {PTP_DPC_CANON_ColorGain, PTP_VENDOR_CANON, -2, N_("Low 2")}, {PTP_DPC_CANON_ColorGain, PTP_VENDOR_CANON, -1, N_("Low")}, {PTP_DPC_CANON_ColorGain, PTP_VENDOR_CANON, 0, N_("Standard")}, {PTP_DPC_CANON_ColorGain, PTP_VENDOR_CANON, 1, N_("High")}, {PTP_DPC_CANON_ColorGain, PTP_VENDOR_CANON, 2, N_("High 2")}, {PTP_DPC_CANON_Sharpness, PTP_VENDOR_CANON, -2, N_("Low 2")}, {PTP_DPC_CANON_Sharpness, PTP_VENDOR_CANON, -1, N_("Low")}, {PTP_DPC_CANON_Sharpness, PTP_VENDOR_CANON, 0, N_("Standard")}, {PTP_DPC_CANON_Sharpness, PTP_VENDOR_CANON, 1, N_("High")}, {PTP_DPC_CANON_Sharpness, PTP_VENDOR_CANON, 2, N_("High 2")}, {PTP_DPC_CANON_Sensitivity, PTP_VENDOR_CANON, 0, N_("Standard")}, {PTP_DPC_CANON_Sensitivity, PTP_VENDOR_CANON, 1, N_("Upper 1")}, {PTP_DPC_CANON_Sensitivity, PTP_VENDOR_CANON, 2, N_("Upper 2")}, {PTP_DPC_CANON_ParameterSet, PTP_VENDOR_CANON, 0x08, N_("Standard Development Parameters")}, {PTP_DPC_CANON_ParameterSet, PTP_VENDOR_CANON, 0x10, N_("Development Parameters 1")}, {PTP_DPC_CANON_ParameterSet, PTP_VENDOR_CANON, 0x20, N_("Development Parameters 2")}, {PTP_DPC_CANON_ParameterSet, PTP_VENDOR_CANON, 0x40, N_("Development Parameters 3")}, {PTP_DPC_CANON_ISOSpeed, PTP_VENDOR_CANON, 0x00, N_("Auto")}, {PTP_DPC_CANON_ISOSpeed, PTP_VENDOR_CANON, 0x28, "6"}, {PTP_DPC_CANON_ISOSpeed, PTP_VENDOR_CANON, 0x30, "12"}, {PTP_DPC_CANON_ISOSpeed, PTP_VENDOR_CANON, 0x38, "25"}, {PTP_DPC_CANON_ISOSpeed, PTP_VENDOR_CANON, 0x40, "50"}, {PTP_DPC_CANON_ISOSpeed, PTP_VENDOR_CANON, 0x43, "64"}, {PTP_DPC_CANON_ISOSpeed, PTP_VENDOR_CANON, 0x48, "100"}, {PTP_DPC_CANON_ISOSpeed, PTP_VENDOR_CANON, 0x50, "200"}, {PTP_DPC_CANON_ISOSpeed, PTP_VENDOR_CANON, 0x58, "400"}, {PTP_DPC_CANON_ISOSpeed, PTP_VENDOR_CANON, 0x60, "800"}, {PTP_DPC_CANON_ISOSpeed, PTP_VENDOR_CANON, 0x68, "1600"}, {PTP_DPC_CANON_ISOSpeed, PTP_VENDOR_CANON, 0x70, "3200"}, {PTP_DPC_CANON_ISOSpeed, PTP_VENDOR_CANON, 0x78, "6400"}, /* 0xd01d - PTP_DPC_CANON_Aperture */ /* 0xd01e - PTP_DPC_CANON_ShutterSpeed */ /* 0xd01f - PTP_DPC_CANON_ExpCompensation */ /* 0xd020 - PTP_DPC_CANON_FlashCompensation */ /* 0xd021 - PTP_DPC_CANON_AEBExposureCompensation */ /* 0xd023 - PTP_DPC_CANON_AvOpen */ /* 0xd024 - PTP_DPC_CANON_AvMax */ {PTP_DPC_CANON_CameraOutput, PTP_VENDOR_CANON, 0, N_("Undefined")}, {PTP_DPC_CANON_CameraOutput, PTP_VENDOR_CANON, 1, N_("LCD")}, {PTP_DPC_CANON_CameraOutput, PTP_VENDOR_CANON, 2, N_("Video OUT")}, {PTP_DPC_CANON_CameraOutput, PTP_VENDOR_CANON, 3, N_("Off")}, {PTP_DPC_CANON_MlSpotPos, PTP_VENDOR_CANON, 0, N_("MlSpotPosCenter")}, {PTP_DPC_CANON_MlSpotPos, PTP_VENDOR_CANON, 1, N_("MlSpotPosAfLink")}, {PTP_DPC_CANON_PhotoEffect, PTP_VENDOR_CANON, 0, N_("Off")}, {PTP_DPC_CANON_PhotoEffect, PTP_VENDOR_CANON, 1, N_("Vivid")}, {PTP_DPC_CANON_PhotoEffect, PTP_VENDOR_CANON, 2, N_("Neutral")}, {PTP_DPC_CANON_PhotoEffect, PTP_VENDOR_CANON, 3, N_("Soft")}, {PTP_DPC_CANON_PhotoEffect, PTP_VENDOR_CANON, 4, N_("Sepia")}, {PTP_DPC_CANON_PhotoEffect, PTP_VENDOR_CANON, 5, N_("Monochrome")}, {0, 0, 0, NULL} }; for (i=0; ptp_value_trans[i].dpc!=0; i++) { if ((ptp_value_trans[i].dpc == dpc) && (((ptp_value_trans[i].dpc & 0xf000) == 0x5000) || (ptp_value_trans[i].vendor == params->deviceinfo.VendorExtensionID)) ) { double value = _value_to_num(&(dpd->CurrentValue), dpd->DataType); return snprintf(out, length, _(ptp_value_trans[i].format), value * ptp_value_trans[i].coef + ptp_value_trans[i].bias); } } kval = _value_to_num(&(dpd->CurrentValue), dpd->DataType); for (i=0; ptp_value_list[i].dpc!=0; i++) { if ((ptp_value_list[i].dpc == dpc) && (((ptp_value_list[i].dpc & 0xf000) == 0x5000) || (ptp_value_list[i].vendor == params->deviceinfo.VendorExtensionID)) && (ptp_value_list[i].key==kval) ) { return snprintf(out, length, "%s", _(ptp_value_list[i].value)); } } if (params->deviceinfo.VendorExtensionID==PTP_VENDOR_MICROSOFT || params->deviceinfo.VendorExtensionID==PTP_VENDOR_MTP) { switch (dpc) { case PTP_DPC_MTP_SynchronizationPartner: case PTP_DPC_MTP_DeviceFriendlyName: return snprintf(out, length, "%s", dpd->CurrentValue.str); case PTP_DPC_MTP_SecureTime: case PTP_DPC_MTP_DeviceCertificate: { /* FIXME: Convert to use unicode demux functions */ for (i=0;(iCurrentValue.a.count) && (iCurrentValue.a.v[i].u16; if ( dpd->CurrentValue.a.count && (dpd->CurrentValue.a.count < length)) { out[dpd->CurrentValue.a.count-1] = 0; return dpd->CurrentValue.a.count-1; } else { out[length-1] = 0; return length; } break; } default: break; } } return 0; } struct { uint16_t ofc; const char *format; } ptp_ofc_trans[] = { {PTP_OFC_Undefined,"Undefined Type"}, {PTP_OFC_Defined,"Defined Type"}, {PTP_OFC_Association,"Association/Directory"}, {PTP_OFC_Script,"Script"}, {PTP_OFC_Executable,"Executable"}, {PTP_OFC_Text,"Text"}, {PTP_OFC_HTML,"HTML"}, {PTP_OFC_DPOF,"DPOF"}, {PTP_OFC_AIFF,"AIFF"}, {PTP_OFC_WAV,"MS Wave"}, {PTP_OFC_MP3,"MP3"}, {PTP_OFC_AVI,"MS AVI"}, {PTP_OFC_MPEG,"MPEG"}, {PTP_OFC_ASF,"ASF"}, {PTP_OFC_QT,"Apple Quicktime"}, {PTP_OFC_EXIF_JPEG,"JPEG"}, {PTP_OFC_TIFF_EP,"TIFF EP"}, {PTP_OFC_FlashPix,"FlashPix"}, {PTP_OFC_BMP,"BMP"}, {PTP_OFC_CIFF,"CIFF"}, {PTP_OFC_GIF,"GIF"}, {PTP_OFC_JFIF,"JFIF"}, {PTP_OFC_PCD,"PCD"}, {PTP_OFC_PICT,"PICT"}, {PTP_OFC_PNG,"PNG"}, {PTP_OFC_TIFF,"TIFF"}, {PTP_OFC_TIFF_IT,"TIFF_IT"}, {PTP_OFC_JP2,"JP2"}, {PTP_OFC_JPX,"JPX"}, {PTP_OFC_DNG,"DNG"}, }; struct { uint16_t ofc; const char *format; } ptp_ofc_mtp_trans[] = { {PTP_OFC_MTP_MediaCard,N_("Media Card")}, {PTP_OFC_MTP_MediaCardGroup,N_("Media Card Group")}, {PTP_OFC_MTP_Encounter,N_("Encounter")}, {PTP_OFC_MTP_EncounterBox,N_("Encounter Box")}, {PTP_OFC_MTP_M4A,N_("M4A")}, {PTP_OFC_MTP_Firmware,N_("Firmware")}, {PTP_OFC_MTP_WindowsImageFormat,N_("Windows Image Format")}, {PTP_OFC_MTP_UndefinedAudio,N_("Undefined Audio")}, {PTP_OFC_MTP_WMA,"WMA"}, {PTP_OFC_MTP_OGG,"OGG"}, {PTP_OFC_MTP_AAC,"AAC"}, {PTP_OFC_MTP_AudibleCodec,N_("Audible.com Codec")}, {PTP_OFC_MTP_FLAC,"FLAC"}, {PTP_OFC_MTP_SamsungPlaylist,N_("Samsung Playlist")}, {PTP_OFC_MTP_UndefinedVideo,N_("Undefined Video")}, {PTP_OFC_MTP_WMV,"WMV"}, {PTP_OFC_MTP_MP4,"MP4"}, {PTP_OFC_MTP_MP2,"MP2"}, {PTP_OFC_MTP_3GP,"3GP"}, {PTP_OFC_MTP_UndefinedCollection,N_("Undefined Collection")}, {PTP_OFC_MTP_AbstractMultimediaAlbum,N_("Abstract Multimedia Album")}, {PTP_OFC_MTP_AbstractImageAlbum,N_("Abstract Image Album")}, {PTP_OFC_MTP_AbstractAudioAlbum,N_("Abstract Audio Album")}, {PTP_OFC_MTP_AbstractVideoAlbum,N_("Abstract Video Album")}, {PTP_OFC_MTP_AbstractAudioVideoPlaylist,N_("Abstract Audio Video Playlist")}, {PTP_OFC_MTP_AbstractContactGroup,N_("Abstract Contact Group")}, {PTP_OFC_MTP_AbstractMessageFolder,N_("Abstract Message Folder")}, {PTP_OFC_MTP_AbstractChapteredProduction,N_("Abstract Chaptered Production")}, {PTP_OFC_MTP_AbstractAudioPlaylist,N_("Abstract Audio Playlist")}, {PTP_OFC_MTP_AbstractVideoPlaylist,N_("Abstract Video Playlist")}, {PTP_OFC_MTP_AbstractMediacast,N_("Abstract Mediacast")}, {PTP_OFC_MTP_WPLPlaylist,N_("WPL Playlist")}, {PTP_OFC_MTP_M3UPlaylist,N_("M3U Playlist")}, {PTP_OFC_MTP_MPLPlaylist,N_("MPL Playlist")}, {PTP_OFC_MTP_ASXPlaylist,N_("ASX Playlist")}, {PTP_OFC_MTP_PLSPlaylist,N_("PLS Playlist")}, {PTP_OFC_MTP_UndefinedDocument,N_("Undefined Document")}, {PTP_OFC_MTP_AbstractDocument,N_("Abstract Document")}, {PTP_OFC_MTP_XMLDocument,N_("XMLDocument")}, {PTP_OFC_MTP_MSWordDocument,N_("Microsoft Word Document")}, {PTP_OFC_MTP_MHTCompiledHTMLDocument,N_("MHT Compiled HTML Document")}, {PTP_OFC_MTP_MSExcelSpreadsheetXLS,N_("Microsoft Excel Spreadsheet (.xls)")}, {PTP_OFC_MTP_MSPowerpointPresentationPPT,N_("Microsoft Powerpoint (.ppt)")}, {PTP_OFC_MTP_UndefinedMessage,N_("Undefined Message")}, {PTP_OFC_MTP_AbstractMessage,N_("Abstract Message")}, {PTP_OFC_MTP_UndefinedContact,N_("Undefined Contact")}, {PTP_OFC_MTP_AbstractContact,N_("Abstract Contact")}, {PTP_OFC_MTP_vCard2,N_("vCard2")}, {PTP_OFC_MTP_vCard3,N_("vCard3")}, {PTP_OFC_MTP_UndefinedCalendarItem,N_("Undefined Calendar Item")}, {PTP_OFC_MTP_AbstractCalendarItem,N_("Abstract Calendar Item")}, {PTP_OFC_MTP_vCalendar1,N_("vCalendar1")}, {PTP_OFC_MTP_vCalendar2,N_("vCalendar2")}, {PTP_OFC_MTP_UndefinedWindowsExecutable,N_("Undefined Windows Executable")}, {PTP_OFC_MTP_MediaCast,N_("Media Cast")}, {PTP_OFC_MTP_Section,N_("Section")}, }; int ptp_render_ofc(PTPParams* params, uint16_t ofc, int spaceleft, char *txt) { int i; if (!(ofc & 0x8000)) { for (i=0;ideviceinfo.VendorExtensionID) { case PTP_VENDOR_EASTMAN_KODAK: switch (ofc) { case PTP_OFC_EK_M3U: return snprintf (txt, spaceleft,"M3U"); default: break; } break; case PTP_VENDOR_CANON: switch (ofc) { case PTP_OFC_CANON_CRW: return snprintf (txt, spaceleft,"CRW"); default: break; } break; case PTP_VENDOR_MICROSOFT: case PTP_VENDOR_MTP: for (i=0;ideviceinfo.VendorExtensionID) { case PTP_VENDOR_MICROSOFT: case PTP_VENDOR_MTP: for (i=0;iproperty = PTP_OPC_StorageID; /* Should be "unknown" */ prop->datatype = PTP_DTC_UNDEF; prop->ObjectHandle = 0x00000000U; prop->propval.str = NULL; (*props) = newprops; (*nrofprops)++; return prop; } void ptp_destroy_object_prop(MTPProperties *prop) { if (!prop) return; if (prop->datatype == PTP_DTC_STR && prop->propval.str != NULL) free(prop->propval.str); else if ((prop->datatype == PTP_DTC_AINT8 || prop->datatype == PTP_DTC_AINT16 || prop->datatype == PTP_DTC_AINT32 || prop->datatype == PTP_DTC_AINT64 || prop->datatype == PTP_DTC_AINT128 || prop->datatype == PTP_DTC_AUINT8 || prop->datatype == PTP_DTC_AUINT16 || prop->datatype == PTP_DTC_AUINT32 || prop->datatype == PTP_DTC_AUINT64 || prop->datatype == PTP_DTC_AUINT128) && prop->propval.a.v != NULL) free(prop->propval.a.v); } void ptp_destroy_object_prop_list(MTPProperties *props, int nrofprops) { int i; MTPProperties *prop = props; for (i=0;imtpprops; for (i=0;inrofmtpprops;i++) { if (attribute_id == prop->property) return prop; prop++; } return NULL; } void ptp_remove_object_from_cache(PTPParams *params, uint32_t handle) { int i; PTPObject *ob; uint16_t ret; ret = ptp_object_find (params, handle, &ob); if (ret != PTP_RC_OK) return; i = ob-params->objects; /* remove object from object info cache */ ptp_free_object (ob); if (i < params->nrofobjects-1) memmove (ob,ob+1,(params->nrofobjects-1-i)*sizeof(PTPObject)); params->nrofobjects--; /* We use less memory than before so this shouldn't fail */ params->objects = realloc(params->objects, sizeof(PTPObject)*params->nrofobjects); } static int _cmp_ob (const void *a, const void *b) { PTPObject *oa = (PTPObject*)a; PTPObject *ob = (PTPObject*)b; return oa->oid - ob->oid; } void ptp_objects_sort (PTPParams *params) { qsort (params->objects, params->nrofobjects, sizeof(PTPObject), _cmp_ob); } /* Binary search in objects. Needs "objects" to be a sorted by objectid list! */ uint16_t ptp_object_find (PTPParams *params, uint32_t handle, PTPObject **retob) { PTPObject tmpob; tmpob.oid = handle; *retob = bsearch (&tmpob, params->objects, params->nrofobjects, sizeof(tmpob), _cmp_ob); if (!*retob) return PTP_RC_GeneralError; return PTP_RC_OK; } /* Binary search in objects + insert of not found. Needs "objects" to be a sorted by objectid list! */ uint16_t ptp_object_find_or_insert (PTPParams *params, uint32_t handle, PTPObject **retob) { int begin, end, cursor; int insertat; PTPObject *newobs; if (!handle) return PTP_RC_GeneralError; *retob = NULL; if (!params->nrofobjects) { params->objects = calloc(1,sizeof(PTPObject)); params->nrofobjects = 1; params->objects[0].oid = handle; *retob = ¶ms->objects[0]; return PTP_RC_OK; } begin = 0; end = params->nrofobjects-1; /*ptp_debug (params, "searching %08x, total=%d", handle, params->nrofobjects);*/ while (1) { cursor = (end-begin)/2+begin; /*ptp_debug (params, "ob %d: %08x [%d-%d]", cursor, params->objects[cursor].oid, begin, end);*/ if (params->objects[cursor].oid == handle) { *retob = ¶ms->objects[cursor]; return PTP_RC_OK; } if (params->objects[cursor].oid < handle) begin = cursor; else end = cursor; if ((end - begin) <= 1) break; } if (params->objects[begin].oid == handle) { *retob = ¶ms->objects[begin]; return PTP_RC_OK; } if (params->objects[end].oid == handle) { *retob = ¶ms->objects[end]; return PTP_RC_OK; } if ((begin == 0) && (handle < params->objects[0].oid)) { insertat=begin; } else { if ((end == params->nrofobjects-1) && (handle > params->objects[end].oid)) insertat=end+1; else insertat=begin+1; } /*ptp_debug (params, "inserting oid %x at [%x,%x], begin=%d, end=%d, insertat=%d\n", handle, params->objects[begin].oid, params->objects[end].oid, begin, end, insertat);*/ newobs = realloc (params->objects, sizeof(PTPObject)*(params->nrofobjects+1)); if (!newobs) return PTP_RC_GeneralError; params->objects = newobs; if (insertat<=params->nrofobjects) memmove (¶ms->objects[insertat+1],¶ms->objects[insertat],(params->nrofobjects-insertat)*sizeof(PTPObject)); memset(¶ms->objects[insertat],0,sizeof(PTPObject)); params->objects[insertat].oid = handle; *retob = ¶ms->objects[insertat]; params->nrofobjects++; return PTP_RC_OK; } uint16_t ptp_object_want (PTPParams *params, uint32_t handle, int want, PTPObject **retob) { uint16_t ret; PTPObject *ob; /*Camera *camera = ((PTPData *)params->data)->camera;*/ /* If GetObjectInfo is broken, force GetPropList */ if (params->device_flags & DEVICE_FLAG_PROPLIST_OVERRIDES_OI) want |= PTPOBJECT_MTPPROPLIST_LOADED; *retob = NULL; if (!handle) { ptp_debug (params, "ptp_object_want: querying handle 0?\n"); return PTP_RC_GeneralError; } ret = ptp_object_find_or_insert (params, handle, &ob); if (ret != PTP_RC_OK) return PTP_RC_GeneralError; *retob = ob; /* Do we have all of it already? */ if ((ob->flags & want) == want) return PTP_RC_OK; #define X (PTPOBJECT_OBJECTINFO_LOADED|PTPOBJECT_STORAGEID_LOADED|PTPOBJECT_PARENTOBJECT_LOADED) if ((want & X) && ((ob->flags & X) != X)) { uint32_t saveparent = 0; /* One EOS issue, where getobjecthandles(root) returns obs without root flag. */ if (ob->flags & PTPOBJECT_PARENTOBJECT_LOADED) saveparent = ob->oi.ParentObject; ret = ptp_getobjectinfo (params, handle, &ob->oi); if (ret != PTP_RC_OK) { /* kill it from the internal list ... */ ptp_remove_object_from_cache(params, handle); return ret; } if (!ob->oi.Filename) ob->oi.Filename=strdup(""); if (ob->flags & PTPOBJECT_PARENTOBJECT_LOADED) ob->oi.ParentObject = saveparent; /* Second EOS issue, 0x20000000 has 0x20000000 as parent */ if (ob->oi.ParentObject == handle) ob->oi.ParentObject = 0; /* Read out the canon special flags */ if ((params->deviceinfo.VendorExtensionID == PTP_VENDOR_CANON) && ptp_operation_issupported(params,PTP_OC_CANON_GetObjectInfoEx)) { PTPCANONFolderEntry *ents = NULL; uint32_t numents = 0; ret = ptp_canon_getobjectinfo(params, ob->oi.StorageID,0, ob->oi.ParentObject,handle, &ents,&numents ); if ((ret == PTP_RC_OK) && (numents >= 1)) ob->canon_flags = ents[0].Flags; } ob->flags |= X; } #undef X if ( (want & PTPOBJECT_MTPPROPLIST_LOADED) && (!(ob->flags & PTPOBJECT_MTPPROPLIST_LOADED)) ) { int nrofprops = 0; MTPProperties *props = NULL; if (params->device_flags & DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST) { want &= ~PTPOBJECT_MTPPROPLIST_LOADED; goto fallback; } /* Microsoft/MTP has fast directory retrieval. */ if (!ptp_operation_issupported(params,PTP_OC_MTP_GetObjPropList)) { want &= ~PTPOBJECT_MTPPROPLIST_LOADED; goto fallback; } ptp_debug (params, "ptp2/mtpfast: reading mtp proplist of %08x", handle); /* We just want this one object, not all at once. */ ret = ptp_mtp_getobjectproplist_single (params, handle, &props, &nrofprops); if (ret != PTP_RC_OK) goto fallback; ob->mtpprops = props; ob->nrofmtpprops = nrofprops; /* Override the ObjectInfo data with data from properties */ if (params->device_flags & DEVICE_FLAG_PROPLIST_OVERRIDES_OI) { int i; MTPProperties *prop = ob->mtpprops; for (i=0;inrofmtpprops;i++,prop++) { /* in case we got all subtree objects */ if (prop->ObjectHandle != handle) continue; switch (prop->property) { case PTP_OPC_StorageID: ob->oi.StorageID = prop->propval.u32; break; case PTP_OPC_ObjectFormat: ob->oi.ObjectFormat = prop->propval.u16; break; case PTP_OPC_ProtectionStatus: ob->oi.ProtectionStatus = prop->propval.u16; break; case PTP_OPC_ObjectSize: if (prop->datatype == PTP_DTC_UINT64) { if (prop->propval.u64 > 0xFFFFFFFFU) ob->oi.ObjectCompressedSize = 0xFFFFFFFFU; else ob->oi.ObjectCompressedSize = (uint32_t)prop->propval.u64; } else if (prop->datatype == PTP_DTC_UINT32) { ob->oi.ObjectCompressedSize = prop->propval.u32; } break; case PTP_OPC_AssociationType: ob->oi.AssociationType = prop->propval.u16; break; case PTP_OPC_AssociationDesc: ob->oi.AssociationDesc = prop->propval.u32; break; case PTP_OPC_ObjectFileName: if (prop->propval.str) { free(ob->oi.Filename); ob->oi.Filename = strdup(prop->propval.str); } break; case PTP_OPC_DateCreated: ob->oi.CaptureDate = ptp_unpack_PTPTIME(prop->propval.str); break; case PTP_OPC_DateModified: ob->oi.ModificationDate = ptp_unpack_PTPTIME(prop->propval.str); break; case PTP_OPC_Keywords: if (prop->propval.str) { free(ob->oi.Keywords); ob->oi.Keywords = strdup(prop->propval.str); } break; case PTP_OPC_ParentObject: ob->oi.ParentObject = prop->propval.u32; break; } } } #if 0 MTPProperties *xpl; int j; PTPObjectInfo oinfo; memset (&oinfo,0,sizeof(oinfo)); /* hmm, not necessary ... only if we would use it */ for (j=0;jproperty) { case PTP_OPC_ParentObject: if (xpl->datatype != PTP_DTC_UINT32) { ptp_debug (params, "ptp2/mtpfast: parentobject has type 0x%x???", xpl->datatype); break; } oinfo.ParentObject = xpl->propval.u32; ptp_debug (params, "ptp2/mtpfast: parent 0x%x", xpl->propval.u32); break; case PTP_OPC_ObjectFormat: if (xpl->datatype != PTP_DTC_UINT16) { ptp_debug (params, "ptp2/mtpfast: objectformat has type 0x%x???", xpl->datatype); break; } oinfo.ObjectFormat = xpl->propval.u16; ptp_debug (params, "ptp2/mtpfast: ofc 0x%x", xpl->propval.u16); break; case PTP_OPC_ObjectSize: switch (xpl->datatype) { case PTP_DTC_UINT32: oinfo.ObjectCompressedSize = xpl->propval.u32; break; case PTP_DTC_UINT64: oinfo.ObjectCompressedSize = xpl->propval.u64; break; default: ptp_debug (params, "ptp2/mtpfast: objectsize has type 0x%x???", xpl->datatype); break; } ptp_debug (params, "ptp2/mtpfast: objectsize %u", xpl->propval.u32); break; case PTP_OPC_StorageID: if (xpl->datatype != PTP_DTC_UINT32) { ptp_debug (params, "ptp2/mtpfast: storageid has type 0x%x???", xpl->datatype); break; } oinfo.StorageID = xpl->propval.u32; ptp_debug (params, "ptp2/mtpfast: storageid 0x%x", xpl->propval.u32); break; case PTP_OPC_ProtectionStatus:/*UINT16*/ if (xpl->datatype != PTP_DTC_UINT16) { ptp_debug (params, "ptp2/mtpfast: protectionstatus has type 0x%x???", xpl->datatype); break; } oinfo.ProtectionStatus = xpl->propval.u16; ptp_debug (params, "ptp2/mtpfast: protection 0x%x", xpl->propval.u16); break; case PTP_OPC_ObjectFileName: if (xpl->datatype != PTP_DTC_STR) { ptp_debug (params, "ptp2/mtpfast: filename has type 0x%x???", xpl->datatype); break; } if (xpl->propval.str) { ptp_debug (params, "ptp2/mtpfast: filename %s", xpl->propval.str); oinfo.Filename = strdup(xpl->propval.str); } else { oinfo.Filename = NULL; } break; case PTP_OPC_DateCreated: if (xpl->datatype != PTP_DTC_STR) { ptp_debug (params, "ptp2/mtpfast: datecreated has type 0x%x???", xpl->datatype); break; } ptp_debug (params, "ptp2/mtpfast: capturedate %s", xpl->propval.str); oinfo.CaptureDate = ptp_unpack_PTPTIME (xpl->propval.str); break; case PTP_OPC_DateModified: if (xpl->datatype != PTP_DTC_STR) { ptp_debug (params, "ptp2/mtpfast: datemodified has type 0x%x???", xpl->datatype); break; } ptp_debug (params, "ptp2/mtpfast: moddate %s", xpl->propval.str); oinfo.ModificationDate = ptp_unpack_PTPTIME (xpl->propval.str); break; default: if ((xpl->property & 0xfff0) == 0xdc00) ptp_debug (params, "ptp2/mtpfast:case %x type %x unhandled", xpl->property, xpl->datatype); break; } } if (!oinfo.Filename) /* i have one such file on my Creative */ oinfo.Filename = strdup(""); #endif ob->flags |= PTPOBJECT_MTPPROPLIST_LOADED; fallback: ; } if ((ob->flags & want) == want) return PTP_RC_OK; ptp_debug (params, "ptp_object_want: oid 0x%08x, want flags %x, have only %x?", handle, want, ob->flags); return PTP_RC_GeneralError; } uint16_t ptp_add_object_to_cache(PTPParams *params, uint32_t handle) { PTPObject *ob; return ptp_object_want (params, handle, PTPOBJECT_OBJECTINFO_LOADED|PTPOBJECT_MTPPROPLIST_LOADED, &ob); } libmtp-1.1.6-20-g1b9f164/src/libmtp.h.in0000664000175000017500000010672512205614637017561 0ustar glowwormglowworm/** * \file libmtp.h * Interface to the Media Transfer Protocol library. * * Copyright (C) 2005-2013 Linus Walleij * Copyright (C) 2005-2008 Richard A. Low * Copyright (C) 2007 Ted Bullock * Copyright (C) 2008 Florent Mertens * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * #include * */ #ifndef LIBMTP_H_INCLUSION_GUARD #define LIBMTP_H_INCLUSION_GUARD #define LIBMTP_VERSION @VERSION@ #define LIBMTP_VERSION_STRING "@VERSION@" /* This handles MSVC pecularities */ #ifdef _MSC_VER #include #define __WIN32__ #define snprintf _snprintf #define ssize_t SSIZE_T /* * Types that do not exist in Windows * sys/types.h, but they exist in mingw32 * sys/types.h. */ typedef char int8_t; typedef unsigned char uint8_t; typedef __int16 int16_t; typedef unsigned __int16 uint16_t; typedef __int32 int32_t; typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; #endif #include #include /* We use time_t */ #include /** * @defgroup types libmtp global type definitions * @{ */ /** * The debug flags defined here are the external flags used * by the libmtp library interface. * * Please keep this list in sync with libmtp.c. */ #define LIBMTP_DEBUG_NONE 0x00 #define LIBMTP_DEBUG_PTP 0x01 #define LIBMTP_DEBUG_PLST 0x02 #define LIBMTP_DEBUG_USB 0x04 #define LIBMTP_DEBUG_DATA 0x08 #define LIBMTP_DEBUG_ALL 0xFF /** * The filetypes defined here are the external types used * by the libmtp library interface. The types used internally * as PTP-defined enumerator types is something different. */ typedef enum { LIBMTP_FILETYPE_FOLDER, LIBMTP_FILETYPE_WAV, LIBMTP_FILETYPE_MP3, LIBMTP_FILETYPE_WMA, LIBMTP_FILETYPE_OGG, LIBMTP_FILETYPE_AUDIBLE, LIBMTP_FILETYPE_MP4, LIBMTP_FILETYPE_UNDEF_AUDIO, LIBMTP_FILETYPE_WMV, LIBMTP_FILETYPE_AVI, LIBMTP_FILETYPE_MPEG, LIBMTP_FILETYPE_ASF, LIBMTP_FILETYPE_QT, LIBMTP_FILETYPE_UNDEF_VIDEO, LIBMTP_FILETYPE_JPEG, LIBMTP_FILETYPE_JFIF, LIBMTP_FILETYPE_TIFF, LIBMTP_FILETYPE_BMP, LIBMTP_FILETYPE_GIF, LIBMTP_FILETYPE_PICT, LIBMTP_FILETYPE_PNG, LIBMTP_FILETYPE_VCALENDAR1, LIBMTP_FILETYPE_VCALENDAR2, LIBMTP_FILETYPE_VCARD2, LIBMTP_FILETYPE_VCARD3, LIBMTP_FILETYPE_WINDOWSIMAGEFORMAT, LIBMTP_FILETYPE_WINEXEC, LIBMTP_FILETYPE_TEXT, LIBMTP_FILETYPE_HTML, LIBMTP_FILETYPE_FIRMWARE, LIBMTP_FILETYPE_AAC, LIBMTP_FILETYPE_MEDIACARD, LIBMTP_FILETYPE_FLAC, LIBMTP_FILETYPE_MP2, LIBMTP_FILETYPE_M4A, LIBMTP_FILETYPE_DOC, LIBMTP_FILETYPE_XML, LIBMTP_FILETYPE_XLS, LIBMTP_FILETYPE_PPT, LIBMTP_FILETYPE_MHT, LIBMTP_FILETYPE_JP2, LIBMTP_FILETYPE_JPX, LIBMTP_FILETYPE_ALBUM, LIBMTP_FILETYPE_PLAYLIST, LIBMTP_FILETYPE_UNKNOWN } LIBMTP_filetype_t; /** * \def LIBMTP_FILETYPE_IS_AUDIO * Audio filetype test. * * For filetypes that can be either audio * or video, use LIBMTP_FILETYPE_IS_AUDIOVIDEO */ #define LIBMTP_FILETYPE_IS_AUDIO(a)\ (a == LIBMTP_FILETYPE_WAV ||\ a == LIBMTP_FILETYPE_MP3 ||\ a == LIBMTP_FILETYPE_MP2 ||\ a == LIBMTP_FILETYPE_WMA ||\ a == LIBMTP_FILETYPE_OGG ||\ a == LIBMTP_FILETYPE_FLAC ||\ a == LIBMTP_FILETYPE_AAC ||\ a == LIBMTP_FILETYPE_M4A ||\ a == LIBMTP_FILETYPE_AUDIBLE ||\ a == LIBMTP_FILETYPE_UNDEF_AUDIO) /** * \def LIBMTP_FILETYPE_IS_VIDEO * Video filetype test. * * For filetypes that can be either audio * or video, use LIBMTP_FILETYPE_IS_AUDIOVIDEO */ #define LIBMTP_FILETYPE_IS_VIDEO(a)\ (a == LIBMTP_FILETYPE_WMV ||\ a == LIBMTP_FILETYPE_AVI ||\ a == LIBMTP_FILETYPE_MPEG ||\ a == LIBMTP_FILETYPE_UNDEF_VIDEO) /** * \def LIBMTP_FILETYPE_IS_AUDIOVIDEO * Audio and&slash;or video filetype test. */ #define LIBMTP_FILETYPE_IS_AUDIOVIDEO(a)\ (a == LIBMTP_FILETYPE_MP4 ||\ a == LIBMTP_FILETYPE_ASF ||\ a == LIBMTP_FILETYPE_QT) /** * \def LIBMTP_FILETYPE_IS_TRACK * Test if filetype is a track. * Use this to determine if the File API or Track API * should be used to upload or download an object. */ #define LIBMTP_FILETYPE_IS_TRACK(a)\ (LIBMTP_FILETYPE_IS_AUDIO(a) ||\ LIBMTP_FILETYPE_IS_VIDEO(a) ||\ LIBMTP_FILETYPE_IS_AUDIOVIDEO(a)) /** * \def LIBMTP_FILETYPE_IS_IMAGE * Image filetype test */ #define LIBMTP_FILETYPE_IS_IMAGE(a)\ (a == LIBMTP_FILETYPE_JPEG ||\ a == LIBMTP_FILETYPE_JFIF ||\ a == LIBMTP_FILETYPE_TIFF ||\ a == LIBMTP_FILETYPE_BMP ||\ a == LIBMTP_FILETYPE_GIF ||\ a == LIBMTP_FILETYPE_PICT ||\ a == LIBMTP_FILETYPE_PNG ||\ a == LIBMTP_FILETYPE_JP2 ||\ a == LIBMTP_FILETYPE_JPX ||\ a == LIBMTP_FILETYPE_WINDOWSIMAGEFORMAT) /** * \def LIBMTP_FILETYPE_IS_ADDRESSBOOK * Addressbook and Business card filetype test */ #define LIBMTP_FILETYPE_IS_ADDRESSBOOK(a)\ (a == LIBMTP_FILETYPE_VCARD2 ||\ a == LIBMTP_FILETYPE_VCARD3) /** * \def LIBMTP_FILETYPE_IS_CALENDAR * Calendar and Appointment filetype test */ #define LIBMTP_FILETYPE_IS_CALENDAR(a)\ (a == LIBMTP_FILETYPE_VCALENDAR1 ||\ a == LIBMTP_FILETYPE_VCALENDAR2) /** * The properties defined here are the external types used * by the libmtp library interface. */ typedef enum { LIBMTP_PROPERTY_StorageID, LIBMTP_PROPERTY_ObjectFormat, LIBMTP_PROPERTY_ProtectionStatus, LIBMTP_PROPERTY_ObjectSize, LIBMTP_PROPERTY_AssociationType, LIBMTP_PROPERTY_AssociationDesc, LIBMTP_PROPERTY_ObjectFileName, LIBMTP_PROPERTY_DateCreated, LIBMTP_PROPERTY_DateModified, LIBMTP_PROPERTY_Keywords, LIBMTP_PROPERTY_ParentObject, LIBMTP_PROPERTY_AllowedFolderContents, LIBMTP_PROPERTY_Hidden, LIBMTP_PROPERTY_SystemObject, LIBMTP_PROPERTY_PersistantUniqueObjectIdentifier, LIBMTP_PROPERTY_SyncID, LIBMTP_PROPERTY_PropertyBag, LIBMTP_PROPERTY_Name, LIBMTP_PROPERTY_CreatedBy, LIBMTP_PROPERTY_Artist, LIBMTP_PROPERTY_DateAuthored, LIBMTP_PROPERTY_Description, LIBMTP_PROPERTY_URLReference, LIBMTP_PROPERTY_LanguageLocale, LIBMTP_PROPERTY_CopyrightInformation, LIBMTP_PROPERTY_Source, LIBMTP_PROPERTY_OriginLocation, LIBMTP_PROPERTY_DateAdded, LIBMTP_PROPERTY_NonConsumable, LIBMTP_PROPERTY_CorruptOrUnplayable, LIBMTP_PROPERTY_ProducerSerialNumber, LIBMTP_PROPERTY_RepresentativeSampleFormat, LIBMTP_PROPERTY_RepresentativeSampleSize, LIBMTP_PROPERTY_RepresentativeSampleHeight, LIBMTP_PROPERTY_RepresentativeSampleWidth, LIBMTP_PROPERTY_RepresentativeSampleDuration, LIBMTP_PROPERTY_RepresentativeSampleData, LIBMTP_PROPERTY_Width, LIBMTP_PROPERTY_Height, LIBMTP_PROPERTY_Duration, LIBMTP_PROPERTY_Rating, LIBMTP_PROPERTY_Track, LIBMTP_PROPERTY_Genre, LIBMTP_PROPERTY_Credits, LIBMTP_PROPERTY_Lyrics, LIBMTP_PROPERTY_SubscriptionContentID, LIBMTP_PROPERTY_ProducedBy, LIBMTP_PROPERTY_UseCount, LIBMTP_PROPERTY_SkipCount, LIBMTP_PROPERTY_LastAccessed, LIBMTP_PROPERTY_ParentalRating, LIBMTP_PROPERTY_MetaGenre, LIBMTP_PROPERTY_Composer, LIBMTP_PROPERTY_EffectiveRating, LIBMTP_PROPERTY_Subtitle, LIBMTP_PROPERTY_OriginalReleaseDate, LIBMTP_PROPERTY_AlbumName, LIBMTP_PROPERTY_AlbumArtist, LIBMTP_PROPERTY_Mood, LIBMTP_PROPERTY_DRMStatus, LIBMTP_PROPERTY_SubDescription, LIBMTP_PROPERTY_IsCropped, LIBMTP_PROPERTY_IsColorCorrected, LIBMTP_PROPERTY_ImageBitDepth, LIBMTP_PROPERTY_Fnumber, LIBMTP_PROPERTY_ExposureTime, LIBMTP_PROPERTY_ExposureIndex, LIBMTP_PROPERTY_DisplayName, LIBMTP_PROPERTY_BodyText, LIBMTP_PROPERTY_Subject, LIBMTP_PROPERTY_Priority, LIBMTP_PROPERTY_GivenName, LIBMTP_PROPERTY_MiddleNames, LIBMTP_PROPERTY_FamilyName, LIBMTP_PROPERTY_Prefix, LIBMTP_PROPERTY_Suffix, LIBMTP_PROPERTY_PhoneticGivenName, LIBMTP_PROPERTY_PhoneticFamilyName, LIBMTP_PROPERTY_EmailPrimary, LIBMTP_PROPERTY_EmailPersonal1, LIBMTP_PROPERTY_EmailPersonal2, LIBMTP_PROPERTY_EmailBusiness1, LIBMTP_PROPERTY_EmailBusiness2, LIBMTP_PROPERTY_EmailOthers, LIBMTP_PROPERTY_PhoneNumberPrimary, LIBMTP_PROPERTY_PhoneNumberPersonal, LIBMTP_PROPERTY_PhoneNumberPersonal2, LIBMTP_PROPERTY_PhoneNumberBusiness, LIBMTP_PROPERTY_PhoneNumberBusiness2, LIBMTP_PROPERTY_PhoneNumberMobile, LIBMTP_PROPERTY_PhoneNumberMobile2, LIBMTP_PROPERTY_FaxNumberPrimary, LIBMTP_PROPERTY_FaxNumberPersonal, LIBMTP_PROPERTY_FaxNumberBusiness, LIBMTP_PROPERTY_PagerNumber, LIBMTP_PROPERTY_PhoneNumberOthers, LIBMTP_PROPERTY_PrimaryWebAddress, LIBMTP_PROPERTY_PersonalWebAddress, LIBMTP_PROPERTY_BusinessWebAddress, LIBMTP_PROPERTY_InstantMessengerAddress, LIBMTP_PROPERTY_InstantMessengerAddress2, LIBMTP_PROPERTY_InstantMessengerAddress3, LIBMTP_PROPERTY_PostalAddressPersonalFull, LIBMTP_PROPERTY_PostalAddressPersonalFullLine1, LIBMTP_PROPERTY_PostalAddressPersonalFullLine2, LIBMTP_PROPERTY_PostalAddressPersonalFullCity, LIBMTP_PROPERTY_PostalAddressPersonalFullRegion, LIBMTP_PROPERTY_PostalAddressPersonalFullPostalCode, LIBMTP_PROPERTY_PostalAddressPersonalFullCountry, LIBMTP_PROPERTY_PostalAddressBusinessFull, LIBMTP_PROPERTY_PostalAddressBusinessLine1, LIBMTP_PROPERTY_PostalAddressBusinessLine2, LIBMTP_PROPERTY_PostalAddressBusinessCity, LIBMTP_PROPERTY_PostalAddressBusinessRegion, LIBMTP_PROPERTY_PostalAddressBusinessPostalCode, LIBMTP_PROPERTY_PostalAddressBusinessCountry, LIBMTP_PROPERTY_PostalAddressOtherFull, LIBMTP_PROPERTY_PostalAddressOtherLine1, LIBMTP_PROPERTY_PostalAddressOtherLine2, LIBMTP_PROPERTY_PostalAddressOtherCity, LIBMTP_PROPERTY_PostalAddressOtherRegion, LIBMTP_PROPERTY_PostalAddressOtherPostalCode, LIBMTP_PROPERTY_PostalAddressOtherCountry, LIBMTP_PROPERTY_OrganizationName, LIBMTP_PROPERTY_PhoneticOrganizationName, LIBMTP_PROPERTY_Role, LIBMTP_PROPERTY_Birthdate, LIBMTP_PROPERTY_MessageTo, LIBMTP_PROPERTY_MessageCC, LIBMTP_PROPERTY_MessageBCC, LIBMTP_PROPERTY_MessageRead, LIBMTP_PROPERTY_MessageReceivedTime, LIBMTP_PROPERTY_MessageSender, LIBMTP_PROPERTY_ActivityBeginTime, LIBMTP_PROPERTY_ActivityEndTime, LIBMTP_PROPERTY_ActivityLocation, LIBMTP_PROPERTY_ActivityRequiredAttendees, LIBMTP_PROPERTY_ActivityOptionalAttendees, LIBMTP_PROPERTY_ActivityResources, LIBMTP_PROPERTY_ActivityAccepted, LIBMTP_PROPERTY_Owner, LIBMTP_PROPERTY_Editor, LIBMTP_PROPERTY_Webmaster, LIBMTP_PROPERTY_URLSource, LIBMTP_PROPERTY_URLDestination, LIBMTP_PROPERTY_TimeBookmark, LIBMTP_PROPERTY_ObjectBookmark, LIBMTP_PROPERTY_ByteBookmark, LIBMTP_PROPERTY_LastBuildDate, LIBMTP_PROPERTY_TimetoLive, LIBMTP_PROPERTY_MediaGUID, LIBMTP_PROPERTY_TotalBitRate, LIBMTP_PROPERTY_BitRateType, LIBMTP_PROPERTY_SampleRate, LIBMTP_PROPERTY_NumberOfChannels, LIBMTP_PROPERTY_AudioBitDepth, LIBMTP_PROPERTY_ScanDepth, LIBMTP_PROPERTY_AudioWAVECodec, LIBMTP_PROPERTY_AudioBitRate, LIBMTP_PROPERTY_VideoFourCCCodec, LIBMTP_PROPERTY_VideoBitRate, LIBMTP_PROPERTY_FramesPerThousandSeconds, LIBMTP_PROPERTY_KeyFrameDistance, LIBMTP_PROPERTY_BufferSize, LIBMTP_PROPERTY_EncodingQuality, LIBMTP_PROPERTY_EncodingProfile, LIBMTP_PROPERTY_BuyFlag, LIBMTP_PROPERTY_UNKNOWN } LIBMTP_property_t; /** * These are the data types */ typedef enum { LIBMTP_DATATYPE_INT8, LIBMTP_DATATYPE_UINT8, LIBMTP_DATATYPE_INT16, LIBMTP_DATATYPE_UINT16, LIBMTP_DATATYPE_INT32, LIBMTP_DATATYPE_UINT32, LIBMTP_DATATYPE_INT64, LIBMTP_DATATYPE_UINT64, } LIBMTP_datatype_t; /** * These are device capabilities */ typedef enum { /** * This capability tells whether you can call the funcion getting * partial objects, @see LIBMTP_GetPartialObject() */ LIBMTP_DEVICECAP_GetPartialObject, /** * This capability tells whether you can call the function sending * partial objects. @see LIBMTP_SendPartialObject() */ LIBMTP_DEVICECAP_SendPartialObject, /** * This capability tells whether you can call the functions editing * objects in-place on a device. * @see LIBMTP_BeginEditObject() * @see LIBMTP_EndEditObject() * @see LIBMTP_TruncateObject() */ LIBMTP_DEVICECAP_EditObjects, } LIBMTP_devicecap_t; /** * These are the numbered error codes. You can also * get string representations for errors. */ typedef enum { LIBMTP_ERROR_NONE, LIBMTP_ERROR_GENERAL, LIBMTP_ERROR_PTP_LAYER, LIBMTP_ERROR_USB_LAYER, LIBMTP_ERROR_MEMORY_ALLOCATION, LIBMTP_ERROR_NO_DEVICE_ATTACHED, LIBMTP_ERROR_STORAGE_FULL, LIBMTP_ERROR_CONNECTING, LIBMTP_ERROR_CANCELLED } LIBMTP_error_number_t; typedef struct LIBMTP_device_entry_struct LIBMTP_device_entry_t; /**< @see LIBMTP_device_entry_struct */ typedef struct LIBMTP_raw_device_struct LIBMTP_raw_device_t; /**< @see LIBMTP_raw_device_struct */ typedef struct LIBMTP_error_struct LIBMTP_error_t; /**< @see LIBMTP_error_struct */ typedef struct LIBMTP_allowed_values_struct LIBMTP_allowed_values_t; /**< @see LIBMTP_allowed_values_struct */ typedef struct LIBMTP_device_extension_struct LIBMTP_device_extension_t; /** < @see LIBMTP_device_extension_struct */ typedef struct LIBMTP_mtpdevice_struct LIBMTP_mtpdevice_t; /**< @see LIBMTP_mtpdevice_struct */ typedef struct LIBMTP_file_struct LIBMTP_file_t; /**< @see LIBMTP_file_struct */ typedef struct LIBMTP_track_struct LIBMTP_track_t; /**< @see LIBMTP_track_struct */ typedef struct LIBMTP_playlist_struct LIBMTP_playlist_t; /**< @see LIBMTP_playlist_struct */ typedef struct LIBMTP_album_struct LIBMTP_album_t; /**< @see LIBMTP_album_struct */ typedef struct LIBMTP_folder_struct LIBMTP_folder_t; /**< @see LIBMTP_folder_t */ typedef struct LIBMTP_object_struct LIBMTP_object_t; /**< @see LIBMTP_object_t */ typedef struct LIBMTP_filesampledata_struct LIBMTP_filesampledata_t; /**< @see LIBMTP_filesample_t */ typedef struct LIBMTP_devicestorage_struct LIBMTP_devicestorage_t; /**< @see LIBMTP_devicestorage_t */ /** * The callback type definition. Notice that a progress percentage ratio * is easy to calculate by dividing sent by * total. * @param sent the number of bytes sent so far * @param total the total number of bytes to send * @param data a user-defined dereferencable pointer * @return if anything else than 0 is returned, the current transfer will be * interrupted / cancelled. */ typedef int (* LIBMTP_progressfunc_t) (uint64_t const sent, uint64_t const total, void const * const data); /** * Callback function for get by handler function * @param params the device parameters * @param priv a user-defined dereferencable pointer * @param wantlen the number of bytes wanted * @param data a buffer to write the data to * @param gotlen pointer to the number of bytes actually written * to data * @return LIBMTP_HANDLER_RETURN_OK if successful, * LIBMTP_HANDLER_RETURN_ERROR on error or * LIBMTP_HANDLER_RETURN_CANCEL to cancel the transfer */ typedef uint16_t (* MTPDataGetFunc) (void* params, void* priv, uint32_t wantlen, unsigned char *data, uint32_t *gotlen); /** * Callback function for put by handler function * @param params the device parameters * @param priv a user-defined dereferencable pointer * @param sendlen the number of bytes available * @param data a buffer to read the data from * @param putlen pointer to the number of bytes actually read * from data * @return LIBMTP_HANDLER_RETURN_OK if successful, * LIBMTP_HANDLER_RETURN_ERROR on error or * LIBMTP_HANDLER_RETURN_CANCEL to cancel the transfer */ typedef uint16_t (* MTPDataPutFunc) (void* params, void* priv, uint32_t sendlen, unsigned char *data, uint32_t *putlen); /** * The return codes for the get/put functions */ #define LIBMTP_HANDLER_RETURN_OK 0 #define LIBMTP_HANDLER_RETURN_ERROR 1 #define LIBMTP_HANDLER_RETURN_CANCEL 2 /** * @} * @defgroup structar libmtp data structures * @{ */ /** * A data structure to hold MTP device entries. */ struct LIBMTP_device_entry_struct { char *vendor; /**< The vendor of this device */ uint16_t vendor_id; /**< Vendor ID for this device */ char *product; /**< The product name of this device */ uint16_t product_id; /**< Product ID for this device */ uint32_t device_flags; /**< Bugs, device specifics etc */ }; /** * A data structure to hold a raw MTP device connected * to the bus. */ struct LIBMTP_raw_device_struct { LIBMTP_device_entry_t device_entry; /**< The device entry for this raw device */ uint32_t bus_location; /**< Location of the bus, if device available */ uint8_t devnum; /**< Device number on the bus, if device available */ }; /** * A data structure to hold errors from the library. */ struct LIBMTP_error_struct { LIBMTP_error_number_t errornumber; char *error_text; LIBMTP_error_t *next; }; /** * A data structure to hold allowed ranges of values */ struct LIBMTP_allowed_values_struct { uint8_t u8max; uint8_t u8min; uint8_t u8step; uint8_t* u8vals; int8_t i8max; int8_t i8min; int8_t i8step; int8_t* i8vals; uint16_t u16max; uint16_t u16min; uint16_t u16step; uint16_t* u16vals; int16_t i16max; int16_t i16min; int16_t i16step; int16_t* i16vals; uint32_t u32max; uint32_t u32min; uint32_t u32step; uint32_t* u32vals; int32_t i32max; int32_t i32min; int32_t i32step; int32_t* i32vals; uint64_t u64max; uint64_t u64min; uint64_t u64step; uint64_t* u64vals; int64_t i64max; int64_t i64min; int64_t i64step; int64_t* i64vals; /** * Number of entries in the vals array */ uint16_t num_entries; /** * The datatype specifying which of the above is used */ LIBMTP_datatype_t datatype; /** * Non zero for range, 0 for enum */ int is_range; }; /** * MTP device extension holder struct */ struct LIBMTP_device_extension_struct { /** * Name of extension e.g. "foo.com" */ char *name; /** * Major revision of extension */ int major; /** * Minor revision of extension */ int minor; /** * Pointer to the next extension or NULL if this is the * last extension. */ LIBMTP_device_extension_t *next; }; /** * Main MTP device object struct */ struct LIBMTP_mtpdevice_struct { /** * Object bitsize, typically 32 or 64. */ uint8_t object_bitsize; /** * Parameters for this device, must be cast into * \c (PTPParams*) before internal use. */ void *params; /** * USB device for this device, must be cast into * \c (PTP_USB*) before internal use. */ void *usbinfo; /** * The storage for this device, do not use strings in here without * copying them first, and beware that this list may be rebuilt at * any time. * @see LIBMTP_Get_Storage() */ LIBMTP_devicestorage_t *storage; /** * The error stack. This shall be handled using the error getting * and clearing functions, not by dereferencing this list. */ LIBMTP_error_t *errorstack; /** The maximum battery level for this device */ uint8_t maximum_battery_level; /** Default music folder */ uint32_t default_music_folder; /** Default playlist folder */ uint32_t default_playlist_folder; /** Default picture folder */ uint32_t default_picture_folder; /** Default video folder */ uint32_t default_video_folder; /** Default organizer folder */ uint32_t default_organizer_folder; /** Default ZENcast folder (only Creative devices...) */ uint32_t default_zencast_folder; /** Default Album folder */ uint32_t default_album_folder; /** Default Text folder */ uint32_t default_text_folder; /** Per device iconv() converters, only used internally */ void *cd; /** Extension list */ LIBMTP_device_extension_t *extensions; /** Whether the device uses caching, only used internally */ int cached; /** Pointer to next device in linked list; NULL if this is the last device */ LIBMTP_mtpdevice_t *next; }; /** * MTP file struct */ struct LIBMTP_file_struct { uint32_t item_id; /**< Unique item ID */ uint32_t parent_id; /**< ID of parent folder */ uint32_t storage_id; /**< ID of storage holding this file */ char *filename; /**< Filename of this file */ uint64_t filesize; /**< Size of file in bytes */ time_t modificationdate; /**< Date of last alteration of the file */ LIBMTP_filetype_t filetype; /**< Filetype used for the current file */ LIBMTP_file_t *next; /**< Next file in list or NULL if last file */ }; /** * MTP track struct */ struct LIBMTP_track_struct { uint32_t item_id; /**< Unique item ID */ uint32_t parent_id; /**< ID of parent folder */ uint32_t storage_id; /**< ID of storage holding this track */ char *title; /**< Track title */ char *artist; /**< Name of recording artist */ char *composer; /**< Name of recording composer */ char *genre; /**< Genre name for track */ char *album; /**< Album name for track */ char *date; /**< Date of original recording as a string */ char *filename; /**< Original filename of this track */ uint16_t tracknumber; /**< Track number (in sequence on recording) */ uint32_t duration; /**< Duration in milliseconds */ uint32_t samplerate; /**< Sample rate of original file, min 0x1f80 max 0xbb80 */ uint16_t nochannels; /**< Number of channels in this recording 0 = unknown, 1 or 2 */ uint32_t wavecodec; /**< FourCC wave codec name */ uint32_t bitrate; /**< (Average) bitrate for this file min=1 max=0x16e360 */ uint16_t bitratetype; /**< 0 = unused, 1 = constant, 2 = VBR, 3 = free */ uint16_t rating; /**< User rating 0-100 (0x00-0x64) */ uint32_t usecount; /**< Number of times used/played */ uint64_t filesize; /**< Size of track file in bytes */ time_t modificationdate; /**< Date of last alteration of the track */ LIBMTP_filetype_t filetype; /**< Filetype used for the current track */ LIBMTP_track_t *next; /**< Next track in list or NULL if last track */ }; /** * MTP Playlist structure */ struct LIBMTP_playlist_struct { uint32_t playlist_id; /**< Unique playlist ID */ uint32_t parent_id; /**< ID of parent folder */ uint32_t storage_id; /**< ID of storage holding this playlist */ char *name; /**< Name of playlist */ uint32_t *tracks; /**< The tracks in this playlist */ uint32_t no_tracks; /**< The number of tracks in this playlist */ LIBMTP_playlist_t *next; /**< Next playlist or NULL if last playlist */ }; /** * MTP Album structure */ struct LIBMTP_album_struct { uint32_t album_id; /**< Unique playlist ID */ uint32_t parent_id; /**< ID of parent folder */ uint32_t storage_id; /**< ID of storage holding this album */ char *name; /**< Name of album */ char *artist; /**< Name of album artist */ char *composer; /**< Name of recording composer */ char *genre; /**< Genre of album */ uint32_t *tracks; /**< The tracks in this album */ uint32_t no_tracks; /**< The number of tracks in this album */ LIBMTP_album_t *next; /**< Next album or NULL if last album */ }; /** * MTP Folder structure */ struct LIBMTP_folder_struct { uint32_t folder_id; /**< Unique folder ID */ uint32_t parent_id; /**< ID of parent folder */ uint32_t storage_id; /**< ID of storage holding this folder */ char *name; /**< Name of folder */ LIBMTP_folder_t *sibling; /**< Next folder at same level or NULL if no more */ LIBMTP_folder_t *child; /**< Child folder or NULL if no children */ }; /** * LIBMTP Object RepresentativeSampleData Structure */ struct LIBMTP_filesampledata_struct { uint32_t width; /**< Width of sample if it is an image */ uint32_t height; /**< Height of sample if it is an image */ uint32_t duration; /**< Duration in milliseconds if it is audio */ LIBMTP_filetype_t filetype; /**< Filetype used for the sample */ uint64_t size; /**< Size of sample data in bytes */ char *data; /**< Sample data */ }; /** * LIBMTP Device Storage structure */ struct LIBMTP_devicestorage_struct { uint32_t id; /**< Unique ID for this storage */ uint16_t StorageType; /**< Storage type */ uint16_t FilesystemType; /**< Filesystem type */ uint16_t AccessCapability; /**< Access capability */ uint64_t MaxCapacity; /**< Maximum capability */ uint64_t FreeSpaceInBytes; /**< Free space in bytes */ uint64_t FreeSpaceInObjects; /**< Free space in objects */ char *StorageDescription; /**< A brief description of this storage */ char *VolumeIdentifier; /**< A volume identifier */ LIBMTP_devicestorage_t *next; /**< Next storage, follow this link until NULL */ LIBMTP_devicestorage_t *prev; /**< Previous storage */ }; /** * LIBMTP Event structure * TODO: add all externally visible events here */ enum LIBMTP_event_enum { LIBMTP_EVENT_NONE, LIBMTP_EVENT_STORE_ADDED, LIBMTP_EVENT_STORE_REMOVED, LIBMTP_EVENT_OBJECT_ADDED, LIBMTP_EVENT_OBJECT_REMOVED, }; typedef enum LIBMTP_event_enum LIBMTP_event_t; /** @} */ /* Make functions available for C++ */ #ifdef __cplusplus extern "C" { #endif extern int LIBMTP_debug; /** * @defgroup internals The libmtp internals API. * @{ */ void LIBMTP_Set_Debug(int); void LIBMTP_Init(void); int LIBMTP_Get_Supported_Devices_List(LIBMTP_device_entry_t ** const, int * const); /** * @} * @defgroup basic The basic device management API. * @{ */ LIBMTP_error_number_t LIBMTP_Detect_Raw_Devices(LIBMTP_raw_device_t **, int *); int LIBMTP_Check_Specific_Device(int busno, int devno); LIBMTP_mtpdevice_t *LIBMTP_Open_Raw_Device(LIBMTP_raw_device_t *); LIBMTP_mtpdevice_t *LIBMTP_Open_Raw_Device_Uncached(LIBMTP_raw_device_t *); /* Begin old, legacy interface */ LIBMTP_mtpdevice_t *LIBMTP_Get_First_Device(void); LIBMTP_error_number_t LIBMTP_Get_Connected_Devices(LIBMTP_mtpdevice_t **); uint32_t LIBMTP_Number_Devices_In_List(LIBMTP_mtpdevice_t *); void LIBMTP_Release_Device_List(LIBMTP_mtpdevice_t*); /* End old, legacy interface */ void LIBMTP_Release_Device(LIBMTP_mtpdevice_t*); void LIBMTP_Dump_Device_Info(LIBMTP_mtpdevice_t*); int LIBMTP_Reset_Device(LIBMTP_mtpdevice_t*); char *LIBMTP_Get_Manufacturername(LIBMTP_mtpdevice_t*); char *LIBMTP_Get_Modelname(LIBMTP_mtpdevice_t*); char *LIBMTP_Get_Serialnumber(LIBMTP_mtpdevice_t*); char *LIBMTP_Get_Deviceversion(LIBMTP_mtpdevice_t*); char *LIBMTP_Get_Friendlyname(LIBMTP_mtpdevice_t*); int LIBMTP_Set_Friendlyname(LIBMTP_mtpdevice_t*, char const * const); char *LIBMTP_Get_Syncpartner(LIBMTP_mtpdevice_t*); int LIBMTP_Set_Syncpartner(LIBMTP_mtpdevice_t*, char const * const); int LIBMTP_Get_Batterylevel(LIBMTP_mtpdevice_t *, uint8_t * const, uint8_t * const); int LIBMTP_Get_Secure_Time(LIBMTP_mtpdevice_t *, char ** const); int LIBMTP_Get_Device_Certificate(LIBMTP_mtpdevice_t *, char ** const); int LIBMTP_Get_Supported_Filetypes(LIBMTP_mtpdevice_t *, uint16_t ** const, uint16_t * const); int LIBMTP_Check_Capability(LIBMTP_mtpdevice_t *, LIBMTP_devicecap_t); LIBMTP_error_t *LIBMTP_Get_Errorstack(LIBMTP_mtpdevice_t*); void LIBMTP_Clear_Errorstack(LIBMTP_mtpdevice_t*); void LIBMTP_Dump_Errorstack(LIBMTP_mtpdevice_t*); #define LIBMTP_STORAGE_SORTBY_NOTSORTED 0 #define LIBMTP_STORAGE_SORTBY_FREESPACE 1 #define LIBMTP_STORAGE_SORTBY_MAXSPACE 2 int LIBMTP_Get_Storage(LIBMTP_mtpdevice_t *, int const); int LIBMTP_Format_Storage(LIBMTP_mtpdevice_t *, LIBMTP_devicestorage_t *); /** * Get/set arbitrary properties. These do not update the cache; should only be used on * properties not stored in structs */ char *LIBMTP_Get_String_From_Object(LIBMTP_mtpdevice_t *, uint32_t const, LIBMTP_property_t const); uint64_t LIBMTP_Get_u64_From_Object(LIBMTP_mtpdevice_t *, uint32_t const, LIBMTP_property_t const, uint64_t const); uint32_t LIBMTP_Get_u32_From_Object(LIBMTP_mtpdevice_t *, uint32_t const, LIBMTP_property_t const, uint32_t const); uint16_t LIBMTP_Get_u16_From_Object(LIBMTP_mtpdevice_t *, uint32_t const, LIBMTP_property_t const, uint16_t const); uint8_t LIBMTP_Get_u8_From_Object(LIBMTP_mtpdevice_t *, uint32_t const, LIBMTP_property_t const, uint8_t const); int LIBMTP_Set_Object_String(LIBMTP_mtpdevice_t *, uint32_t const, LIBMTP_property_t const, char const * const); int LIBMTP_Set_Object_u32(LIBMTP_mtpdevice_t *, uint32_t const, LIBMTP_property_t const, uint32_t const); int LIBMTP_Set_Object_u16(LIBMTP_mtpdevice_t *, uint32_t const, LIBMTP_property_t const, uint16_t const); int LIBMTP_Set_Object_u8(LIBMTP_mtpdevice_t *, uint32_t const, LIBMTP_property_t const, uint8_t const); char const * LIBMTP_Get_Property_Description(LIBMTP_property_t inproperty); int LIBMTP_Is_Property_Supported(LIBMTP_mtpdevice_t*, LIBMTP_property_t const, LIBMTP_filetype_t const); int LIBMTP_Get_Allowed_Property_Values(LIBMTP_mtpdevice_t*, LIBMTP_property_t const, LIBMTP_filetype_t const, LIBMTP_allowed_values_t*); void LIBMTP_destroy_allowed_values_t(LIBMTP_allowed_values_t*); /** * @} * @defgroup files The file management API. * @{ */ LIBMTP_file_t *LIBMTP_new_file_t(void); void LIBMTP_destroy_file_t(LIBMTP_file_t*); char const * LIBMTP_Get_Filetype_Description(LIBMTP_filetype_t); LIBMTP_file_t *LIBMTP_Get_Filelisting(LIBMTP_mtpdevice_t *); LIBMTP_file_t *LIBMTP_Get_Filelisting_With_Callback(LIBMTP_mtpdevice_t *, LIBMTP_progressfunc_t const, void const * const); LIBMTP_file_t * LIBMTP_Get_Files_And_Folders(LIBMTP_mtpdevice_t *, uint32_t const, uint32_t const); LIBMTP_file_t *LIBMTP_Get_Filemetadata(LIBMTP_mtpdevice_t *, uint32_t const); int LIBMTP_Get_File_To_File(LIBMTP_mtpdevice_t*, uint32_t, char const * const, LIBMTP_progressfunc_t const, void const * const); int LIBMTP_Get_File_To_File_Descriptor(LIBMTP_mtpdevice_t*, uint32_t const, int const, LIBMTP_progressfunc_t const, void const * const); int LIBMTP_Get_File_To_Handler(LIBMTP_mtpdevice_t *, uint32_t const, MTPDataPutFunc, void *, LIBMTP_progressfunc_t const, void const * const); int LIBMTP_Send_File_From_File(LIBMTP_mtpdevice_t *, char const * const, LIBMTP_file_t * const, LIBMTP_progressfunc_t const, void const * const); int LIBMTP_Send_File_From_File_Descriptor(LIBMTP_mtpdevice_t *, int const, LIBMTP_file_t * const, LIBMTP_progressfunc_t const, void const * const); int LIBMTP_Send_File_From_Handler(LIBMTP_mtpdevice_t *, MTPDataGetFunc, void *, LIBMTP_file_t * const, LIBMTP_progressfunc_t const, void const * const); int LIBMTP_Set_File_Name(LIBMTP_mtpdevice_t *, LIBMTP_file_t *, const char *); LIBMTP_filesampledata_t *LIBMTP_new_filesampledata_t(void); void LIBMTP_destroy_filesampledata_t(LIBMTP_filesampledata_t *); int LIBMTP_Get_Representative_Sample_Format(LIBMTP_mtpdevice_t *, LIBMTP_filetype_t const, LIBMTP_filesampledata_t **); int LIBMTP_Send_Representative_Sample(LIBMTP_mtpdevice_t *, uint32_t const, LIBMTP_filesampledata_t *); int LIBMTP_Get_Representative_Sample(LIBMTP_mtpdevice_t *, uint32_t const, LIBMTP_filesampledata_t *); int LIBMTP_Get_Thumbnail(LIBMTP_mtpdevice_t *, uint32_t const, unsigned char **data, unsigned int *size); /** * @} * @defgroup tracks The track management API. * @{ */ LIBMTP_track_t *LIBMTP_new_track_t(void); void LIBMTP_destroy_track_t(LIBMTP_track_t*); LIBMTP_track_t *LIBMTP_Get_Tracklisting(LIBMTP_mtpdevice_t*); LIBMTP_track_t *LIBMTP_Get_Tracklisting_With_Callback(LIBMTP_mtpdevice_t*, LIBMTP_progressfunc_t const, void const * const); LIBMTP_track_t *LIBMTP_Get_Tracklisting_With_Callback_For_Storage(LIBMTP_mtpdevice_t*, uint32_t const, LIBMTP_progressfunc_t const, void const * const); LIBMTP_track_t *LIBMTP_Get_Trackmetadata(LIBMTP_mtpdevice_t*, uint32_t const); int LIBMTP_Get_Track_To_File(LIBMTP_mtpdevice_t*, uint32_t, char const * const, LIBMTP_progressfunc_t const, void const * const); int LIBMTP_Get_Track_To_File_Descriptor(LIBMTP_mtpdevice_t*, uint32_t const, int const, LIBMTP_progressfunc_t const, void const * const); int LIBMTP_Get_Track_To_Handler(LIBMTP_mtpdevice_t *, uint32_t const, MTPDataPutFunc, void *, LIBMTP_progressfunc_t const, void const * const); int LIBMTP_Send_Track_From_File(LIBMTP_mtpdevice_t *, char const * const, LIBMTP_track_t * const, LIBMTP_progressfunc_t const, void const * const); int LIBMTP_Send_Track_From_File_Descriptor(LIBMTP_mtpdevice_t *, int const, LIBMTP_track_t * const, LIBMTP_progressfunc_t const, void const * const); int LIBMTP_Send_Track_From_Handler(LIBMTP_mtpdevice_t *, MTPDataGetFunc, void *, LIBMTP_track_t * const, LIBMTP_progressfunc_t const, void const * const); int LIBMTP_Update_Track_Metadata(LIBMTP_mtpdevice_t *, LIBMTP_track_t const * const); int LIBMTP_Track_Exists(LIBMTP_mtpdevice_t *, uint32_t const); int LIBMTP_Set_Track_Name(LIBMTP_mtpdevice_t *, LIBMTP_track_t *, const char *); /** @} */ /** * @} * @defgroup folders The folder management API. * @{ */ LIBMTP_folder_t *LIBMTP_new_folder_t(void); void LIBMTP_destroy_folder_t(LIBMTP_folder_t*); LIBMTP_folder_t *LIBMTP_Get_Folder_List(LIBMTP_mtpdevice_t*); LIBMTP_folder_t *LIBMTP_Get_Folder_List_For_Storage(LIBMTP_mtpdevice_t*, uint32_t const); LIBMTP_folder_t *LIBMTP_Find_Folder(LIBMTP_folder_t*, uint32_t const); uint32_t LIBMTP_Create_Folder(LIBMTP_mtpdevice_t*, char *, uint32_t, uint32_t); int LIBMTP_Set_Folder_Name(LIBMTP_mtpdevice_t *, LIBMTP_folder_t *, const char *); /** @} */ /** * @} * @defgroup playlists The audio/video playlist management API. * @{ */ LIBMTP_playlist_t *LIBMTP_new_playlist_t(void); void LIBMTP_destroy_playlist_t(LIBMTP_playlist_t *); LIBMTP_playlist_t *LIBMTP_Get_Playlist_List(LIBMTP_mtpdevice_t *); LIBMTP_playlist_t *LIBMTP_Get_Playlist(LIBMTP_mtpdevice_t *, uint32_t const); int LIBMTP_Create_New_Playlist(LIBMTP_mtpdevice_t *, LIBMTP_playlist_t * const); int LIBMTP_Update_Playlist(LIBMTP_mtpdevice_t *, LIBMTP_playlist_t * const); int LIBMTP_Set_Playlist_Name(LIBMTP_mtpdevice_t *, LIBMTP_playlist_t *, const char *); /** * @} * @defgroup albums The audio/video album management API. * @{ */ LIBMTP_album_t *LIBMTP_new_album_t(void); void LIBMTP_destroy_album_t(LIBMTP_album_t *); LIBMTP_album_t *LIBMTP_Get_Album_List(LIBMTP_mtpdevice_t *); LIBMTP_album_t *LIBMTP_Get_Album_List_For_Storage(LIBMTP_mtpdevice_t *, uint32_t const); LIBMTP_album_t *LIBMTP_Get_Album(LIBMTP_mtpdevice_t *, uint32_t const); int LIBMTP_Create_New_Album(LIBMTP_mtpdevice_t *, LIBMTP_album_t * const); int LIBMTP_Update_Album(LIBMTP_mtpdevice_t *, LIBMTP_album_t const * const); int LIBMTP_Set_Album_Name(LIBMTP_mtpdevice_t *, LIBMTP_album_t *, const char *); /** * @} * @defgroup objects The object management API. * @{ */ int LIBMTP_Delete_Object(LIBMTP_mtpdevice_t *, uint32_t); int LIBMTP_Set_Object_Filename(LIBMTP_mtpdevice_t *, uint32_t , char *); int LIBMTP_GetPartialObject(LIBMTP_mtpdevice_t *, uint32_t const, uint64_t, uint32_t, unsigned char **, unsigned int *); int LIBMTP_SendPartialObject(LIBMTP_mtpdevice_t *, uint32_t const, uint64_t, unsigned char *, unsigned int); int LIBMTP_BeginEditObject(LIBMTP_mtpdevice_t *, uint32_t const); int LIBMTP_EndEditObject(LIBMTP_mtpdevice_t *, uint32_t const); int LIBMTP_TruncateObject(LIBMTP_mtpdevice_t *, uint32_t const, uint64_t); /** * @} * @defgroup files The events API. * @{ */ int LIBMTP_Read_Event(LIBMTP_mtpdevice_t *, LIBMTP_event_t *, uint32_t *); /** @} */ /* End of C++ exports */ #ifdef __cplusplus } #endif #endif /* LIBMTP_H_INCLUSION_GUARD */ libmtp-1.1.6-20-g1b9f164/src/playlist-spl.c0000664000175000017500000006161412205614637020312 0ustar glowwormglowworm/** * \File playlist-spl.c * * Playlist_t to Samsung (.spl) and back conversion functions. * * Copyright (C) 2008 Alistair Boyle * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "config.h" #include #include // mkstmp() #include #include #include #include #ifdef HAVE_SYS_UIO_H #include #endif #include #include #include "libmtp.h" #include "libusb-glue.h" #include "ptp.h" #include "unicode.h" #include "util.h" #include "playlist-spl.h" /** * Debug macro */ #define LIBMTP_PLST_DEBUG(format, args...) \ do { \ if ((LIBMTP_debug & LIBMTP_DEBUG_PLST) != 0) \ fprintf(stdout, "LIBMTP %s[%d]: " format, __FUNCTION__, __LINE__, ##args); \ } while (0) // Internal singly linked list of strings // used to hold .spl playlist in memory typedef struct text_struct { char* text; // String struct text_struct *next; // Link to next line, NULL if end of list } text_t; /** * Forward declarations of local (static) functions. */ static text_t* read_into_spl_text_t(LIBMTP_mtpdevice_t *device, const int fd); static void write_from_spl_text_t(LIBMTP_mtpdevice_t *device, const int fd, text_t* p); static void free_spl_text_t(text_t* p); static void print_spl_text_t(text_t* p); static uint32_t trackno_spl_text_t(text_t* p); static void tracks_from_spl_text_t(text_t* p, uint32_t* tracks, LIBMTP_folder_t* folders, LIBMTP_file_t* files); static void spl_text_t_from_tracks(text_t** p, uint32_t* tracks, const uint32_t trackno, const uint32_t ver_major, const uint32_t ver_minor, char* dnse, LIBMTP_folder_t* folders, LIBMTP_file_t* files); static uint32_t discover_id_from_filepath(const char* s, LIBMTP_folder_t* folders, LIBMTP_file_t* files); // TODO add file/dir cached args static void discover_filepath_from_id(char** p, uint32_t track, LIBMTP_folder_t* folders, LIBMTP_file_t* files); static void find_folder_name(LIBMTP_folder_t* folders, uint32_t* id, char** name); static uint32_t find_folder_id(LIBMTP_folder_t* folders, uint32_t parent, char* name); static void append_text_t(text_t** t, char* s); /** * Decides if the indicated object index is an .spl playlist. * * @param oi object we are deciding on * @return 1 if this is a Samsung .spl object, 0 otherwise */ int is_spl_playlist(PTPObjectInfo *oi) { return ((oi->ObjectFormat == PTP_OFC_Undefined) || (oi->ObjectFormat == PTP_OFC_MTP_SamsungPlaylist)) && (strlen(oi->Filename) > 4) && (strcmp((oi->Filename + strlen(oi->Filename) - 4), ".spl") == 0); } #ifndef HAVE_MKSTEMP # ifdef __WIN32__ # include # define mkstemp(_pattern) _open(_mktemp(_pattern), _O_CREAT | _O_SHORT_LIVED | _O_EXCL) # else # error Missing mkstemp() function. # endif #endif /** * Take an object ID, a .spl playlist on the MTP device, * and convert it to a playlist_t object. * * @param device mtp device pointer * @param oi object we are reading * @param id .spl playlist id on MTP device * @param pl the LIBMTP_playlist_t pointer to be filled with info from id */ void spl_to_playlist_t(LIBMTP_mtpdevice_t* device, PTPObjectInfo *oi, const uint32_t id, LIBMTP_playlist_t * const pl) { // Fill in playlist metadata // Use the Filename as the playlist name, dropping the ".spl" extension pl->name = malloc(sizeof(char)*(strlen(oi->Filename) -4 +1)); memcpy(pl->name, oi->Filename, strlen(oi->Filename) -4); // Set terminating character pl->name[strlen(oi->Filename) - 4] = 0; pl->playlist_id = id; pl->parent_id = oi->ParentObject; pl->storage_id = oi->StorageID; pl->tracks = NULL; pl->no_tracks = 0; LIBMTP_PLST_DEBUG("pl->name='%s'\n", pl->name); // open a temporary file char tmpname[] = "/tmp/mtp-spl2pl-XXXXXX"; int fd = mkstemp(tmpname); if(fd < 0) { LIBMTP_ERROR("failed to make temp file for %s.spl -> %s, errno=%s\n", pl->name, tmpname, strerror(errno)); return; } // make sure the file will be deleted afterwards if(unlink(tmpname) < 0) LIBMTP_ERROR("failed to delete temp file for %s.spl -> %s, errno=%s\n", pl->name, tmpname, strerror(errno)); int ret = LIBMTP_Get_File_To_File_Descriptor(device, pl->playlist_id, fd, NULL, NULL); if( ret < 0 ) { // FIXME add_ptp_error_to_errorstack(device, ret, "LIBMTP_Get_Playlist: Could not get .spl playlist file."); close(fd); LIBMTP_INFO("FIXME closed\n"); } text_t* p = read_into_spl_text_t(device, fd); close(fd); // FIXME cache these somewhere else so we don't keep calling this! LIBMTP_folder_t *folders; LIBMTP_file_t *files; folders = LIBMTP_Get_Folder_List(device); files = LIBMTP_Get_Filelisting_With_Callback(device, NULL, NULL); // convert the playlist listing to track ids pl->no_tracks = trackno_spl_text_t(p); LIBMTP_PLST_DEBUG("%u track%s found\n", pl->no_tracks, pl->no_tracks==1?"":"s"); pl->tracks = malloc(sizeof(uint32_t)*(pl->no_tracks)); tracks_from_spl_text_t(p, pl->tracks, folders, files); free_spl_text_t(p); // debug: add a break since this is the top level function call LIBMTP_PLST_DEBUG("------------\n\n"); } /** * Push a playlist_t onto the device after converting it to a .spl format * * @param device mtp device pointer * @param pl the LIBMTP_playlist_t to convert (pl->playlist_id will be updated * with the newly created object's id) * @return 0 on success, any other value means failure. */ int playlist_t_to_spl(LIBMTP_mtpdevice_t *device, LIBMTP_playlist_t * const pl) { text_t* t; LIBMTP_folder_t *folders; LIBMTP_file_t *files; folders = LIBMTP_Get_Folder_List(device); files = LIBMTP_Get_Filelisting_With_Callback(device, NULL, NULL); char tmpname[] = "/tmp/mtp-spl2pl-XXXXXX"; // must be a var since mkstemp modifies it LIBMTP_PLST_DEBUG("pl->name='%s'\n",pl->name); // open a file descriptor int fd = mkstemp(tmpname); if(fd < 0) { LIBMTP_ERROR("failed to make temp file for %s.spl -> %s, errno=%s\n", pl->name, tmpname, strerror(errno)); return -1; } // make sure the file will be deleted afterwards if(unlink(tmpname) < 0) LIBMTP_ERROR("failed to delete temp file for %s.spl -> %s, errno=%s\n", pl->name, tmpname, strerror(errno)); // decide on which version of the .spl format to use uint32_t ver_major; uint32_t ver_minor = 0; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; if(FLAG_PLAYLIST_SPL_V2(ptp_usb)) ver_major = 2; else ver_major = 1; // FLAG_PLAYLIST_SPL_V1() LIBMTP_PLST_DEBUG("%u track%s\n", pl->no_tracks, pl->no_tracks==1?"":"s"); LIBMTP_PLST_DEBUG(".spl version %d.%02d\n", ver_major, ver_minor); // create the text for the playlist spl_text_t_from_tracks(&t, pl->tracks, pl->no_tracks, ver_major, ver_minor, NULL, folders, files); write_from_spl_text_t(device, fd, t); free_spl_text_t(t); // done with the text // create the file object for storing LIBMTP_file_t* f = malloc(sizeof(LIBMTP_file_t)); f->item_id = 0; f->parent_id = pl->parent_id; f->storage_id = pl->storage_id; f->filename = malloc(sizeof(char)*(strlen(pl->name)+5)); strcpy(f->filename, pl->name); strcat(f->filename, ".spl"); // append suffix f->filesize = lseek(fd, 0, SEEK_CUR); // file desc is currently at end of file f->filetype = LIBMTP_FILETYPE_UNKNOWN; f->next = NULL; LIBMTP_PLST_DEBUG("%s is %dB\n", f->filename, (int)f->filesize); // push the playlist to the device lseek(fd, 0, SEEK_SET); // reset file desc. to start of file int ret = LIBMTP_Send_File_From_File_Descriptor(device, fd, f, NULL, NULL); pl->playlist_id = f->item_id; free(f->filename); free(f); // release the memory when we're done with it close(fd); // debug: add a break since this is the top level function call LIBMTP_PLST_DEBUG("------------\n\n"); return ret; } /** * Update a playlist on the device. If only the playlist's name is being * changed the pl->playlist_id will likely remain the same. An updated track * list will result in the old playlist being replaced (ie: new playlist_id). * NOTE: Other playlist metadata aside from playlist name and tracks are * ignored. * * @param device mtp device pointer * @param new the LIBMTP_playlist_t to convert (pl->playlist_id will be updated * with the newly created object's id) * @return 0 on success, any other value means failure. */ int update_spl_playlist(LIBMTP_mtpdevice_t *device, LIBMTP_playlist_t * const newlist) { LIBMTP_PLST_DEBUG("pl->name='%s'\n",newlist->name); // read in the playlist of interest LIBMTP_playlist_t * old = LIBMTP_Get_Playlist(device, newlist->playlist_id); // check to see if we found it if (!old) return -1; // check if the playlists match int delta = 0; int i; if(old->no_tracks != newlist->no_tracks) delta++; for(i=0;ino_tracks && delta==0;i++) { if(old->tracks[i] != newlist->tracks[i]) delta++; } // if not, kill the playlist and replace it if(delta) { LIBMTP_PLST_DEBUG("new tracks detected:\n"); LIBMTP_PLST_DEBUG("delete old playlist and build a new one\n"); LIBMTP_PLST_DEBUG(" NOTE: new playlist_id will result!\n"); if(LIBMTP_Delete_Object(device, old->playlist_id) != 0) return -1; if(strcmp(old->name,newlist->name) == 0) LIBMTP_PLST_DEBUG("name unchanged\n"); else LIBMTP_PLST_DEBUG("name is changing too -> %s\n",newlist->name); return LIBMTP_Create_New_Playlist(device, newlist); } // update the name only if(strcmp(old->name,newlist->name) != 0) { LIBMTP_PLST_DEBUG("ONLY name is changing -> %s\n",newlist->name); LIBMTP_PLST_DEBUG("playlist_id will remain unchanged\n"); char* s = malloc(sizeof(char)*(strlen(newlist->name)+5)); strcpy(s, newlist->name); strcat(s,".spl"); // FIXME check for success int ret = LIBMTP_Set_Playlist_Name(device, newlist, s); free(s); return ret; } LIBMTP_PLST_DEBUG("no change\n"); return 0; // nothing to be done, success } /** * Load a file descriptor into a string. * * @param device a pointer to the current device. * (needed for ucs2->utf8 charset conversion) * @param fd the file descriptor to load * @return text_t* a linked list of lines of text, id is left blank, NULL if nothing read in */ static text_t* read_into_spl_text_t(LIBMTP_mtpdevice_t *device, const int fd) { // set MAXREAD to match STRING_BUFFER_LENGTH in unicode.h conversion function const size_t MAXREAD = 1024*2; char t[MAXREAD]; // upto 3 bytes per utf8 character, 2 bytes per ucs2 character, // +1 for '\0' at end of string const size_t WSIZE = MAXREAD/2*3+1; char w[WSIZE]; char* it = t; // iterator on t char* iw = w; ssize_t rdcnt; off_t offcnt; text_t* head = NULL; text_t* tail = NULL; int eof = 0; // reset file descriptor (fd) to start of file offcnt = lseek(fd, 0, SEEK_SET); while(!eof) { // find the current offset in the file // to allow us to determine how many bytes we read if we hit the EOF // where returned rdcnt=0 from read() offcnt = lseek(fd, 0, SEEK_CUR); // read to refill buffer // (there might be data left from an incomplete last string in t, // hence start filling at it) it = t; // set ptr to start of buffer rdcnt = read(fd, it, sizeof(char)*MAXREAD); if(rdcnt < 0) LIBMTP_INFO("load_spl_fd read err %s\n", strerror(errno)); else if(rdcnt == 0) { // for EOF, fix rdcnt if(it-t == MAXREAD) LIBMTP_ERROR("error -- buffer too small to read in .spl playlist entry\n"); rdcnt = lseek(fd, 0, SEEK_CUR) - offcnt; eof = 1; } LIBMTP_PLST_DEBUG("read buff= {%dB new, %dB old/left-over}%s\n",(int)rdcnt, (int)(iw-w), eof?", EOF":""); // while more input bytes char* it_end = t + rdcnt; while(it < it_end) { // copy byte, unless EOL (then replace with end-of-string \0) if(*it == '\r' || *it == '\n') *iw = '\0'; else *iw = *it; it++; iw++; // EOL -- store it if( (iw-w) >= 2 && // we must have at least two bytes *(iw-1) == '\0' && *(iw-2) == '\0' && // 0x0000 is end-of-string // but it must be aligned such that we have an {odd,even} set of // bytes since we are expecting to consume bytes two-at-a-time !((iw-w)%2) ) { // drop empty lines // ... cast as a string of 2 byte characters if(ucs2_strlen((uint16_t*)w) == 0) { iw = w; continue; } // create a new node in the list if(head == NULL) { head = malloc(sizeof(text_t)); tail = head; } else { tail->next = malloc(sizeof(text_t)); tail = tail->next; } // fill in the data for the node // ... cast as a string of 2 byte characters tail->text = utf16_to_utf8(device, (uint16_t*) w); iw = w; // start again LIBMTP_PLST_DEBUG("line: %s\n", tail->text); } // prevent buffer overflow if(iw >= w + WSIZE) { // if we ever see this error its BAD: // we are dropping all the processed bytes for this line and // proceeding on as if everything is okay, probably losing a track // from the playlist LIBMTP_ERROR("ERROR %s:%u:%s(): buffer overflow! .spl line too long @ %zuB\n", __FILE__, __LINE__, __func__, WSIZE); iw = w; // reset buffer } } // if the last thing we did was save our line, then we finished working // on the input buffer and we can start fresh // otherwise we need to save our partial work, if we're not quiting (eof). // there is nothing special we need to do, to achieve this since the // partially completed string will sit in 'w' until we return to complete // the line } // set the next pointer at the end // if there is any list if(head != NULL) tail->next = NULL; // return the head of the list (NULL if no list) return head; } /** * Write a .spl text file to a file in preparation for pushing it * to the device. * * @param fd file descriptor to write to * @param p the text to output one line per string in the linked list * @see playlist_t_to_spl() */ static void write_from_spl_text_t(LIBMTP_mtpdevice_t *device, const int fd, text_t* p) { ssize_t ret; // write out BOM for utf16/ucs2 (byte order mark) ret = write(fd,"\xff\xfe",2); while(p != NULL) { char *const t = (char*) utf8_to_utf16(device, p->text); // note: 2 bytes per ucs2 character const size_t len = ucs2_strlen((uint16_t*)t)*sizeof(uint16_t); int i; LIBMTP_PLST_DEBUG("\nutf8=%s ",p->text); for(i=0;itext);i++) LIBMTP_PLST_DEBUG("%02x ", p->text[i] & 0xff); LIBMTP_PLST_DEBUG("\n"); LIBMTP_PLST_DEBUG("ucs2="); for(i=0;i utf16 ret += write(fd, t, len); // release the converted string free(t); // check for failures if(ret < 0) LIBMTP_ERROR("write spl file failed: %s\n", strerror(errno)); else if(ret != len +2) LIBMTP_ERROR("write spl file wrong number of bytes ret=%d len=%d '%s'\n", (int)ret, (int)len, p->text); // write carriage return, line feed in ucs2 ret = write(fd, "\r\0\n\0", 4); if(ret < 0) LIBMTP_ERROR("write spl file failed: %s\n", strerror(errno)); else if(ret != 4) LIBMTP_ERROR("failed to write the correct number of bytes '\\n'!\n"); // fake out count (first time through has two extra bytes from BOM) ret = 2; // advance to the next line p = p->next; } } /** * Destroy a linked-list of strings. * * @param p the list to destroy * @see spl_to_playlist_t() * @see playlist_t_to_spl() */ static void free_spl_text_t(text_t* p) { text_t* d; while(p != NULL) { d = p; free(p->text); p = p->next; free(d); } } /** * Print a linked-list of strings to stdout. * Used to debug. * * @param p the list to print */ static void print_spl_text_t(text_t* p) { while(p != NULL) { LIBMTP_PLST_DEBUG("%s\n",p->text); p = p->next; } } /** * Count the number of tracks in this playlist. A track will be counted as * such if the line starts with a leading slash. * * @param p the text to search * @return number of tracks in the playlist * @see spl_to_playlist_t() */ static uint32_t trackno_spl_text_t(text_t* p) { uint32_t c = 0; while(p != NULL) { if(p->text[0] == '\\' ) c++; p = p->next; } return c; } /** * Find the track ids for this playlist's files. * (ie: \Music\song.mp3 -> 12345) * * @param p the text to search * @param tracks returned list of track id's for the playlist_t, must be large * enough to accomodate all the tracks as reported by * trackno_spl_text_t() * @param folders the folders list for the device * @param fiels the files list for the device * @see spl_to_playlist_t() */ static void tracks_from_spl_text_t(text_t* p, uint32_t* tracks, LIBMTP_folder_t* folders, LIBMTP_file_t* files) { uint32_t c = 0; while(p != NULL) { if(p->text[0] == '\\' ) { tracks[c] = discover_id_from_filepath(p->text, folders, files); LIBMTP_PLST_DEBUG("track %d = %s (%u)\n", c+1, p->text, tracks[c]); c++; } p = p->next; } } /** * Find the track names (including path) for this playlist's track ids. * (ie: 12345 -> \Music\song.mp3) * * @param p the text to search * @param tracks list of track id's to look up * @param folders the folders list for the device * @param fiels the files list for the device * @see playlist_t_to_spl() */ static void spl_text_t_from_tracks(text_t** p, uint32_t* tracks, const uint32_t trackno, const uint32_t ver_major, const uint32_t ver_minor, char* dnse, LIBMTP_folder_t* folders, LIBMTP_file_t* files) { // HEADER text_t* c = NULL; append_text_t(&c, "SPL PLAYLIST"); *p = c; // save the top of the list! char vs[14]; // "VERSION 2.00\0" sprintf(vs,"VERSION %d.%02d",ver_major,ver_minor); append_text_t(&c, vs); append_text_t(&c, ""); // TRACKS int i; char* f; for(i=0;inext = NULL; // debug LIBMTP_PLST_DEBUG(".spl playlist:\n"); print_spl_text_t(*p); } /** * Find the track names (including path) given a fileid * (ie: 12345 -> \Music\song.mp3) * * @param p returns the file path (ie: \Music\song.mp3), * (*p) == NULL if the look up fails * @param track track id to look up * @param folders the folders list for the device * @param files the files list for the device * @see spl_text_t_from_tracks() */ // returns p = NULL on failure, else the filepath to the track including track name, allocated as a correct length string static void discover_filepath_from_id(char** p, uint32_t track, LIBMTP_folder_t* folders, LIBMTP_file_t* files) { // fill in a string from the right side since we don't know the root till the end const int M = 1024; char w[M]; char* iw = w + M; // iterator on w // in case of failure return NULL string *p = NULL; // find the right file while(files != NULL && files->item_id != track) { files = files->next; } // if we didn't find a matching file, abort if(files == NULL) return; // stuff the filename into our string // FIXME: check for string overflow before it occurs iw = iw - (strlen(files->filename) +1); // leave room for '\0' at the end strcpy(iw,files->filename); // next follow the directories to the root // prepending folders to the path as we go uint32_t id = files->parent_id; char* f = NULL; while(id != 0) { find_folder_name(folders, &id, &f); if(f == NULL) return; // fail if the next part of the path couldn't be found iw = iw - (strlen(f) +1); // FIXME: check for string overflow before it occurs strcpy(iw, f); iw[strlen(f)] = '\\'; free(f); } // prepend a slash iw--; iw[0] = '\\'; // now allocate a string of the right length to be returned *p = strdup(iw); } /** * Find the track id given a track's name (including path) * (ie: \Music\song.mp3 -> 12345) * * @param s file path to look up (ie: \Music\song.mp3), * (*p) == NULL if the look up fails * @param folders the folders list for the device * @param files the files list for the device * @return track id, 0 means failure * @see tracks_from_spl_text_t() */ static uint32_t discover_id_from_filepath(const char* s, LIBMTP_folder_t* folders, LIBMTP_file_t* files) { // abort if this isn't a path if(s[0] != '\\') return 0; int i; uint32_t id = 0; char* sc = strdup(s); char* sci = sc +1; // iterator // skip leading slash in path // convert all \ to \0 size_t len = strlen(s); for(i=0;iparent_id == id) && (strcmp(files->filename, sci) == 0) ) { // found it! id = files->item_id; break; } files = files->next; } } else { // otherwise its part of the directory path id = find_folder_id(folders, id, sci); } // move to next folder/file sci += strlen(sci) +1; } // release our copied string free(sc); // FIXME check that we actually have a file return id; } /** * Find the folder name given the folder's id. * * @param folders the folders list for the device * @param id the folder_id to look up, returns the folder's parent folder_id * @param name returns the name of the folder or NULL on failure * @see discover_filepath_from_id() */ static void find_folder_name(LIBMTP_folder_t* folders, uint32_t* id, char** name) { // FIXME this function is exactly LIBMTP_Find_Folder LIBMTP_folder_t* f = LIBMTP_Find_Folder(folders, *id); if(f == NULL) { *name = NULL; } else { // found it! *name = strdup(f->name); *id = f->parent_id; } } /** * Find the folder id given the folder's name and parent id. * * @param folders the folders list for the device * @param parent the folder's parent's id * @param name the name of the folder * @return the folder_id or 0 on failure * @see discover_filepath_from_id() */ static uint32_t find_folder_id(LIBMTP_folder_t* folders, uint32_t parent, char* name) { if(folders == NULL) return 0; // found it! else if( (folders->parent_id == parent) && (strcmp(folders->name, name) == 0) ) return folders->folder_id; // no luck so far, search both siblings and children else { uint32_t id = 0; if(folders->sibling != NULL) id = find_folder_id(folders->sibling, parent, name); if( (id == 0) && (folders->child != NULL) ) id = find_folder_id(folders->child, parent, name); return id; } } /** * Append a string to a linked-list of strings. * * @param t the list-of-strings, returns with the added string * @param s the string to append * @see spl_text_t_from_tracks() */ static void append_text_t(text_t** t, char* s) { if(*t == NULL) { *t = malloc(sizeof(text_t)); } else { (*t)->next = malloc(sizeof(text_t)); (*t) = (*t)->next; } (*t)->text = strdup(s); } libmtp-1.1.6-20-g1b9f164/src/libusb1-glue.c0000664000175000017500000020466012205614637020150 0ustar glowwormglowworm/* * \file libusb1-glue.c * Low-level USB interface glue towards libusb. * * Copyright (C) 2005-2007 Richard A. Low * Copyright (C) 2005-2012 Linus Walleij * Copyright (C) 2006-2012 Marcus Meissner * Copyright (C) 2007 Ted Bullock * Copyright (C) 2008 Chris Bagwell * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Created by Richard Low on 24/12/2005. (as mtp-utils.c) * Modified by Linus Walleij 2006-03-06 * (Notice that Anglo-Saxons use little-endian dates and Swedes * use big-endian dates.) * */ #include "config.h" #include "libmtp.h" #include "libusb-glue.h" #include "device-flags.h" #include "util.h" #include "ptp.h" #include #include #include #include #include #include "ptp-pack.c" /* * Default USB timeout length. This can be overridden as needed * but should start with a reasonable value so most common * requests can be completed. The original value of 4000 was * not long enough for large file transfer. Also, players can * spend a bit of time collecting data. Higher values also * make connecting/disconnecting more reliable. */ #define USB_TIMEOUT_DEFAULT 20000 #define USB_TIMEOUT_LONG 60000 static inline int get_timeout(PTP_USB* ptp_usb) { if (FLAG_LONG_TIMEOUT(ptp_usb)) { return USB_TIMEOUT_LONG; } return USB_TIMEOUT_DEFAULT; } /* USB Feature selector HALT */ #ifndef USB_FEATURE_HALT #define USB_FEATURE_HALT 0x00 #endif /* Internal data types */ struct mtpdevice_list_struct { libusb_device *device; PTPParams *params; PTP_USB *ptp_usb; uint32_t bus_location; struct mtpdevice_list_struct *next; }; typedef struct mtpdevice_list_struct mtpdevice_list_t; static const LIBMTP_device_entry_t mtp_device_table[] = { /* We include an .h file which is shared between us and libgphoto2 */ #include "music-players.h" }; static const int mtp_device_table_size = sizeof(mtp_device_table) / sizeof(LIBMTP_device_entry_t); // Local functions static LIBMTP_error_number_t init_usb(); static void close_usb(PTP_USB* ptp_usb); static int find_interface_and_endpoints(libusb_device *dev, uint8_t *conf, uint8_t *interface, uint8_t *altsetting, int* inep, int* inep_maxpacket, int* outep, int* outep_maxpacket, int* intep); static void clear_stall(PTP_USB* ptp_usb); static int init_ptp_usb (PTPParams* params, PTP_USB* ptp_usb, libusb_device* dev); static short ptp_write_func (unsigned long,PTPDataHandler*,void *data,unsigned long*); static short ptp_read_func (unsigned long,PTPDataHandler*,void *data,unsigned long*,int); static int usb_get_endpoint_status(PTP_USB* ptp_usb, int ep, uint16_t* status); /** * Get a list of the supported USB devices. * * The developers depend on users of this library to constantly * add in to the list of supported devices. What we need is the * device name, USB Vendor ID (VID) and USB Product ID (PID). * put this into a bug ticket at the project homepage, please. * The VID/PID is used to let e.g. udev lift the device to * console userspace access when it's plugged in. * * @param devices a pointer to a pointer that will hold a device * list after the call to this function, if it was * successful. * @param numdevs a pointer to an integer that will hold the number * of devices in the device list if the call was successful. * @return 0 if the list was successfull retrieved, any other * value means failure. */ int LIBMTP_Get_Supported_Devices_List(LIBMTP_device_entry_t ** const devices, int * const numdevs) { *devices = (LIBMTP_device_entry_t *) &mtp_device_table; *numdevs = mtp_device_table_size; return 0; } static LIBMTP_error_number_t init_usb() { /* * Some additional libusb debugging please. * We use the same level debug between MTP and USB. */ if (libusb_init(NULL) < 0) { LIBMTP_ERROR("Libusb1 init failed\n"); return LIBMTP_ERROR_USB_LAYER; } if ((LIBMTP_debug & LIBMTP_DEBUG_USB) != 0) libusb_set_debug(NULL,9); return LIBMTP_ERROR_NONE; } /** * Small recursive function to append a new usb_device to the linked list of * USB MTP devices * @param devlist dynamic linked list of pointers to usb devices with MTP * properties, to be extended with new device. * @param newdevice the new device to add. * @param bus_location bus for this device. * @return an extended array or NULL on failure. */ static mtpdevice_list_t *append_to_mtpdevice_list(mtpdevice_list_t *devlist, libusb_device *newdevice, uint32_t bus_location) { mtpdevice_list_t *new_list_entry; new_list_entry = (mtpdevice_list_t *) malloc(sizeof(mtpdevice_list_t)); if (new_list_entry == NULL) { return NULL; } // Fill in USB device, if we *HAVE* to make a copy of the device do it here. new_list_entry->device = newdevice; new_list_entry->bus_location = bus_location; new_list_entry->next = NULL; if (devlist == NULL) { return new_list_entry; } else { mtpdevice_list_t *tmp = devlist; while (tmp->next != NULL) { tmp = tmp->next; } tmp->next = new_list_entry; } return devlist; } /** * Small recursive function to free dynamic memory allocated to the linked list * of USB MTP devices * @param devlist dynamic linked list of pointers to usb devices with MTP * properties. * @return nothing */ static void free_mtpdevice_list(mtpdevice_list_t *devlist) { mtpdevice_list_t *tmplist = devlist; if (devlist == NULL) return; while (tmplist != NULL) { mtpdevice_list_t *tmp = tmplist; tmplist = tmplist->next; // Do not free() the fields (ptp_usb, params)! These are used elsewhere. free(tmp); } return; } /** * This checks if a device has an MTP descriptor. The descriptor was * elaborated about in gPhoto bug 1482084, and some official documentation * with no strings attached was published by Microsoft at * http://www.microsoft.com/whdc/system/bus/USB/USBFAQ_intermed.mspx#E3HAC * * @param dev a device struct from libusb. * @param dumpfile set to non-NULL to make the descriptors dump out * to this file in human-readable hex so we can scruitinze them. * @return 1 if the device is MTP compliant, 0 if not. */ static int probe_device_descriptor(libusb_device *dev, FILE *dumpfile) { libusb_device_handle *devh; unsigned char buf[1024], cmd; int i; int ret; /* This is to indicate if we find some vendor interface */ int found_vendor_spec_interface = 0; struct libusb_device_descriptor desc; ret = libusb_get_device_descriptor (dev, &desc); if (ret != LIBUSB_SUCCESS) return 0; /* * Don't examine devices that are not likely to * contain any MTP interface, update this the day * you find some weird combination... */ if (!(desc.bDeviceClass == LIBUSB_CLASS_PER_INTERFACE || desc.bDeviceClass == LIBUSB_CLASS_COMM || desc.bDeviceClass == LIBUSB_CLASS_PTP || desc.bDeviceClass == 0xEF || /* Intf. Association Desc.*/ desc.bDeviceClass == LIBUSB_CLASS_VENDOR_SPEC)) { return 0; } /* * Attempt to open Device on this port * * TODO: is there a way to check the number of endpoints etc WITHOUT * opening the device? Some color calibration devices are REALLY * sensitive to this, and I found a Canon custom scanner that doesn't * like it at all either :-( */ ret = libusb_open(dev, &devh); if (ret != LIBUSB_SUCCESS) { /* Could not open this device */ return 0; } /* * Loop over the device configurations and interfaces. Nokia MTP-capable * handsets (possibly others) typically have the string "MTP" in their * MTP interface descriptions, that's how they can be detected, before * we try the more esoteric "OS descriptors" (below). */ for (i = 0; i < desc.bNumConfigurations; i++) { uint8_t j; struct libusb_config_descriptor *config; ret = libusb_get_config_descriptor (dev, i, &config); if (ret != LIBUSB_SUCCESS) { LIBMTP_INFO("configdescriptor %d get failed with ret %d in probe_device_descriptor yet dev->descriptor.bNumConfigurations > 0\n", i, ret); continue; } for (j = 0; j < config->bNumInterfaces; j++) { int k; for (k = 0; k < config->interface[j].num_altsetting; k++) { /* Current interface descriptor */ const struct libusb_interface_descriptor *intf = &config->interface[j].altsetting[k]; /* * MTP interfaces have three endpoints, two bulk and one * interrupt. Don't probe anything else. */ if (intf->bNumEndpoints != 3) continue; /* * We only want to probe for the OS descriptor if the * device is LIBUSB_CLASS_VENDOR_SPEC or one of the interfaces * in it is, so flag if we find an interface like this. */ if (intf->bInterfaceClass == LIBUSB_CLASS_VENDOR_SPEC) { found_vendor_spec_interface = 1; } /* * Check for Still Image Capture class with PIMA 15740 protocol, * also known as PTP */ #if 0 if (intf->bInterfaceClass == LIBUSB_CLASS_PTP && intf->bInterfaceSubClass == 0x01 && intf->bInterfaceProtocol == 0x01) { if (dumpfile != NULL) { fprintf(dumpfile, "Configuration %d, interface %d, altsetting %d:\n", i, j, k); fprintf(dumpfile, " Found PTP device, check vendor " "extension...\n"); } /* * This is where we may insert code to open a PTP * session and query the vendor extension ID to see * if it is 0xffffffff, i.e. MTP according to the spec. */ if (was_mtp_extension) { libusb_close(devh); return 1; } } #endif /* * Next we search for the MTP substring in the interface name. * For example : "RIM MS/MTP" should work. */ buf[0] = '\0'; ret = libusb_get_string_descriptor_ascii(devh, config->interface[j].altsetting[k].iInterface, buf, 1024); if (ret < 3) continue; if (strstr((char *) buf, "MTP") != NULL) { if (dumpfile != NULL) { fprintf(dumpfile, "Configuration %d, interface %d, altsetting %d:\n", i, j, k); fprintf(dumpfile, " Interface description contains the string \"MTP\"\n"); fprintf(dumpfile, " Device recognized as MTP, no further probing.\n"); } libusb_free_config_descriptor(config); libusb_close(devh); return 1; } if (libusb_kernel_driver_active(devh, config->interface[j].altsetting[k].iInterface)) { /* * Specifically avoid probing anything else than USB mass storage devices * and non-associated drivers in Linux. */ if (config->interface[j].altsetting[k].bInterfaceClass != LIBUSB_CLASS_MASS_STORAGE) { LIBMTP_INFO("avoid probing device using attached kernel interface\n"); libusb_free_config_descriptor(config); libusb_close(devh); return 0; } } } } libusb_free_config_descriptor(config); } /* * Only probe for OS descriptor if the device is vendor specific * or one of the interfaces found is. */ if (desc.bDeviceClass == LIBUSB_CLASS_VENDOR_SPEC || found_vendor_spec_interface) { /* Read the special descriptor */ ret = libusb_get_descriptor(devh, 0x03, 0xee, buf, sizeof(buf)); /* * If something failed we're probably stalled to we need * to clear the stall off the endpoint and say this is not * MTP. */ if (ret < 0) { /* EP0 is the default control endpoint */ libusb_clear_halt (devh, 0); libusb_close(devh); return 0; } // Dump it, if requested if (dumpfile != NULL && ret > 0) { fprintf(dumpfile, "Microsoft device descriptor 0xee:\n"); data_dump_ascii(dumpfile, buf, ret, 16); } /* Check if descriptor length is at least 10 bytes */ if (ret < 10) { libusb_close(devh); return 0; } /* Check if this device has a Microsoft Descriptor */ if (!((buf[2] == 'M') && (buf[4] == 'S') && (buf[6] == 'F') && (buf[8] == 'T'))) { libusb_close(devh); return 0; } /* Check if device responds to control message 1 or if there is an error */ cmd = buf[16]; ret = libusb_control_transfer (devh, LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_DEVICE | LIBUSB_REQUEST_TYPE_VENDOR, cmd, 0, 4, buf, sizeof(buf), USB_TIMEOUT_DEFAULT); // Dump it, if requested if (dumpfile != NULL && ret > 0) { fprintf(dumpfile, "Microsoft device response to control message 1, CMD 0x%02x:\n", cmd); data_dump_ascii(dumpfile, buf, ret, 16); } /* If this is true, the device either isn't MTP or there was an error */ if (ret <= 0x15) { /* TODO: If there was an error, flag it and let the user know somehow */ /* if(ret == -1) {} */ libusb_close(devh); return 0; } /* Check if device is MTP or if it is something like a USB Mass Storage device with Janus DRM support */ if ((buf[0x12] != 'M') || (buf[0x13] != 'T') || (buf[0x14] != 'P')) { libusb_close(devh); return 0; } /* After this point we are probably dealing with an MTP device */ /* * Check if device responds to control message 2, which is * the extended device parameters. Most devices will just * respond with a copy of the same message as for the first * message, some respond with zero-length (which is OK) * and some with pure garbage. We're not parsing the result * so this is not very important. */ ret = libusb_control_transfer (devh, LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_DEVICE | LIBUSB_REQUEST_TYPE_VENDOR, cmd, 0, 5, buf, sizeof(buf), USB_TIMEOUT_DEFAULT); // Dump it, if requested if (dumpfile != NULL && ret > 0) { fprintf(dumpfile, "Microsoft device response to control message 2, CMD 0x%02x:\n", cmd); data_dump_ascii(dumpfile, buf, ret, 16); } /* If this is true, the device errored against control message 2 */ if (ret == -1) { /* TODO: Implement callback function to let managing program know there was a problem, along with description of the problem */ LIBMTP_ERROR("Potential MTP Device with VendorID:%04x and " "ProductID:%04x encountered an error responding to " "control message 2.\n" "Problems may arrise but continuing\n", desc.idVendor, desc.idProduct); } else if (dumpfile != NULL && ret == 0) { fprintf(dumpfile, "Zero-length response to control message 2 (OK)\n"); } else if (dumpfile != NULL) { fprintf(dumpfile, "Device responds to control message 2 with some data.\n"); } /* Close the USB device handle */ libusb_close(devh); return 1; } /* Close the USB device handle */ libusb_close(devh); return 0; } /** * This function scans through the connected usb devices on a machine and * if they match known Vendor and Product identifiers appends them to the * dynamic array mtp_device_list. Be sure to call * free_mtpdevice_list(mtp_device_list) when you are done * with it, assuming it is not NULL. * @param mtp_device_list dynamic array of pointers to usb devices with MTP * properties (if this list is not empty, new entries will be appended * to the list). * @return LIBMTP_ERROR_NONE implies that devices have been found, scan the list * appropriately. LIBMTP_ERROR_NO_DEVICE_ATTACHED implies that no * devices have been found. */ static LIBMTP_error_number_t get_mtp_usb_device_list(mtpdevice_list_t ** mtp_device_list) { ssize_t nrofdevs; libusb_device **devs = NULL; int ret, i; LIBMTP_error_number_t init_usb_ret; init_usb_ret = init_usb(); if (init_usb_ret != LIBMTP_ERROR_NONE) return init_usb_ret; nrofdevs = libusb_get_device_list (NULL, &devs); for (i = 0; i < nrofdevs ; i++) { libusb_device *dev = devs[i]; struct libusb_device_descriptor desc; ret = libusb_get_device_descriptor(dev, &desc); if (ret != LIBUSB_SUCCESS) continue; if (desc.bDeviceClass != LIBUSB_CLASS_HUB) { int i; int found = 0; // First check if we know about the device already. // Devices well known to us will not have their descriptors // probed, it caused problems with some devices. for(i = 0; i < mtp_device_table_size; i++) { if(desc.idVendor == mtp_device_table[i].vendor_id && desc.idProduct == mtp_device_table[i].product_id) { /* Append this usb device to the MTP device list */ *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list, dev, libusb_get_bus_number(dev)); found = 1; break; } } // If we didn't know it, try probing the "OS Descriptor". if (!found) { if (probe_device_descriptor(dev, NULL)) { /* Append this usb device to the MTP USB Device List */ *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list, dev, libusb_get_bus_number(dev)); } /* * By thomas_-_s: Also append devices that are no MTP but PTP devices * if this is commented out. */ /* else { // Check whether the device is no USB hub but a PTP. if ( dev->config != NULL &&dev->config->interface->altsetting->bInterfaceClass == LIBUSB_CLASS_PTP && dev->descriptor.bDeviceClass != LIBUSB_CLASS_HUB ) { *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list, dev, bus->location); } } */ } } } libusb_free_device_list (devs, 0); /* If nothing was found we end up here. */ if(*mtp_device_list == NULL) { return LIBMTP_ERROR_NO_DEVICE_ATTACHED; } return LIBMTP_ERROR_NONE; } /** * Checks if a specific device with a certain bus and device * number has an MTP type device descriptor. * * @param busno the bus number of the device to check * @param deviceno the device number of the device to check * @return 1 if the device is MTP else 0 */ int LIBMTP_Check_Specific_Device(int busno, int devno) { ssize_t nrofdevs; libusb_device **devs = NULL; int i; LIBMTP_error_number_t init_usb_ret; init_usb_ret = init_usb(); if (init_usb_ret != LIBMTP_ERROR_NONE) return 0; nrofdevs = libusb_get_device_list (NULL, &devs); for (i = 0; i < nrofdevs ; i++ ) { if (libusb_get_bus_number(devs[i]) != busno) continue; if (libusb_get_device_address(devs[i]) != devno) continue; if (probe_device_descriptor(devs[i], NULL)) return 1; } return 0; } /** * Detect the raw MTP device descriptors and return a list of * of the devices found. * * @param devices a pointer to a variable that will hold * the list of raw devices found. This may be NULL * on return if the number of detected devices is zero. * The user shall simply free() this * variable when finished with the raw devices, * in order to release memory. * @param numdevs a pointer to an integer that will hold * the number of devices in the list. This may * be 0. * @return 0 if successful, any other value means failure. */ LIBMTP_error_number_t LIBMTP_Detect_Raw_Devices(LIBMTP_raw_device_t ** devices, int * numdevs) { mtpdevice_list_t *devlist = NULL; mtpdevice_list_t *dev; LIBMTP_error_number_t ret; LIBMTP_raw_device_t *retdevs; int devs = 0; int i, j; ret = get_mtp_usb_device_list(&devlist); if (ret == LIBMTP_ERROR_NO_DEVICE_ATTACHED) { *devices = NULL; *numdevs = 0; return ret; } else if (ret != LIBMTP_ERROR_NONE) { LIBMTP_ERROR("LIBMTP PANIC: get_mtp_usb_device_list() " "error code: %d on line %d\n", ret, __LINE__); return ret; } // Get list size dev = devlist; while (dev != NULL) { devs++; dev = dev->next; } if (devs == 0) { *devices = NULL; *numdevs = 0; return LIBMTP_ERROR_NONE; } // Conjure a device list retdevs = (LIBMTP_raw_device_t *) malloc(sizeof(LIBMTP_raw_device_t) * devs); if (retdevs == NULL) { // Out of memory *devices = NULL; *numdevs = 0; return LIBMTP_ERROR_MEMORY_ALLOCATION; } dev = devlist; i = 0; while (dev != NULL) { int device_known = 0; struct libusb_device_descriptor desc; libusb_get_device_descriptor (dev->device, &desc); // Assign default device info retdevs[i].device_entry.vendor = NULL; retdevs[i].device_entry.vendor_id = desc.idVendor; retdevs[i].device_entry.product = NULL; retdevs[i].device_entry.product_id = desc.idProduct; retdevs[i].device_entry.device_flags = 0x00000000U; // See if we can locate some additional vendor info and device flags for(j = 0; j < mtp_device_table_size; j++) { if(desc.idVendor == mtp_device_table[j].vendor_id && desc.idProduct == mtp_device_table[j].product_id) { device_known = 1; retdevs[i].device_entry.vendor = mtp_device_table[j].vendor; retdevs[i].device_entry.product = mtp_device_table[j].product; retdevs[i].device_entry.device_flags = mtp_device_table[j].device_flags; // This device is known to the developers LIBMTP_ERROR("Device %d (VID=%04x and PID=%04x) is a %s %s.\n", i, desc.idVendor, desc.idProduct, mtp_device_table[j].vendor, mtp_device_table[j].product); break; } } if (!device_known) { // This device is unknown to the developers LIBMTP_ERROR("Device %d (VID=%04x and PID=%04x) is UNKNOWN.\n", i, desc.idVendor, desc.idProduct); LIBMTP_ERROR("Please report this VID/PID and the device model to the " "libmtp development team\n"); /* * Trying to get iManufacturer or iProduct from the device at this * point would require opening a device handle, that we don't want * to do right now. (Takes time for no good enough reason.) */ } // Save the location on the bus retdevs[i].bus_location = libusb_get_bus_number (dev->device); retdevs[i].devnum = libusb_get_device_address (dev->device); i++; dev = dev->next; } *devices = retdevs; *numdevs = i; free_mtpdevice_list(devlist); return LIBMTP_ERROR_NONE; } /** * This routine just dumps out low-level * USB information about the current device. * @param ptp_usb the USB device to get information from. */ void dump_usbinfo(PTP_USB *ptp_usb) { libusb_device *dev; struct libusb_device_descriptor desc; if (libusb_kernel_driver_active(ptp_usb->handle, ptp_usb->interface)) LIBMTP_INFO(" Interface has a kernel driver attached.\n"); dev = libusb_get_device (ptp_usb->handle); libusb_get_device_descriptor (dev, &desc); LIBMTP_INFO(" bcdUSB: %d\n", desc.bcdUSB); LIBMTP_INFO(" bDeviceClass: %d\n", desc.bDeviceClass); LIBMTP_INFO(" bDeviceSubClass: %d\n", desc.bDeviceSubClass); LIBMTP_INFO(" bDeviceProtocol: %d\n", desc.bDeviceProtocol); LIBMTP_INFO(" idVendor: %04x\n", desc.idVendor); LIBMTP_INFO(" idProduct: %04x\n", desc.idProduct); LIBMTP_INFO(" IN endpoint maxpacket: %d bytes\n", ptp_usb->inep_maxpacket); LIBMTP_INFO(" OUT endpoint maxpacket: %d bytes\n", ptp_usb->outep_maxpacket); LIBMTP_INFO(" Raw device info:\n"); LIBMTP_INFO(" Bus location: %d\n", ptp_usb->rawdevice.bus_location); LIBMTP_INFO(" Device number: %d\n", ptp_usb->rawdevice.devnum); LIBMTP_INFO(" Device entry info:\n"); LIBMTP_INFO(" Vendor: %s\n", ptp_usb->rawdevice.device_entry.vendor); LIBMTP_INFO(" Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.vendor_id); LIBMTP_INFO(" Product: %s\n", ptp_usb->rawdevice.device_entry.product); LIBMTP_INFO(" Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.product_id); LIBMTP_INFO(" Device flags: 0x%08x\n", ptp_usb->rawdevice.device_entry.device_flags); (void) probe_device_descriptor(dev, stdout); } /** * Retrieve the apropriate playlist extension for this * device. Rather hacky at the moment. This is probably * desired by the managing software, but when creating * lists on the device itself you notice certain preferences. * @param ptp_usb the USB device to get suggestion for. * @return the suggested playlist extension. */ const char *get_playlist_extension(PTP_USB *ptp_usb) { libusb_device *dev; struct libusb_device_descriptor desc; static char creative_pl_extension[] = ".zpl"; static char default_pl_extension[] = ".pla"; dev = libusb_get_device(ptp_usb->handle); libusb_get_device_descriptor (dev, &desc); if (desc.idVendor == 0x041e) return creative_pl_extension; return default_pl_extension; } static void libusb_glue_debug (PTPParams *params, const char *format, ...) { va_list args; va_start (args, format); if (params->debug_func!=NULL) params->debug_func (params->data, format, args); else { vfprintf (stderr, format, args); fprintf (stderr,"\n"); fflush (stderr); } va_end (args); } static void libusb_glue_error (PTPParams *params, const char *format, ...) { va_list args; va_start (args, format); if (params->error_func!=NULL) params->error_func (params->data, format, args); else { vfprintf (stderr, format, args); fprintf (stderr,"\n"); fflush (stderr); } va_end (args); } /* * ptp_read_func() and ptp_write_func() are * based on same functions usb.c in libgphoto2. * Much reading packet logs and having fun with trials and errors * reveals that WMP / Windows is probably using an algorithm like this * for large transfers: * * 1. Send the command (0x0c bytes) if headers are split, else, send * command plus sizeof(endpoint) - 0x0c bytes. * 2. Send first packet, max size to be sizeof(endpoint) but only when using * split headers. Else goto 3. * 3. REPEAT send 0x10000 byte chunks UNTIL remaining bytes < 0x10000 * We call 0x10000 CONTEXT_BLOCK_SIZE. * 4. Send remaining bytes MOD sizeof(endpoint) * 5. Send remaining bytes. If this happens to be exactly sizeof(endpoint) * then also send a zero-length package. * * Further there is some special quirks to handle zero reads from the * device, since some devices can't do them at all due to shortcomings * of the USB slave controller in the device. */ #define CONTEXT_BLOCK_SIZE_1 0x3e00 #define CONTEXT_BLOCK_SIZE_2 0x200 #define CONTEXT_BLOCK_SIZE CONTEXT_BLOCK_SIZE_1+CONTEXT_BLOCK_SIZE_2 static short ptp_read_func ( unsigned long size, PTPDataHandler *handler,void *data, unsigned long *readbytes, int readzero ) { PTP_USB *ptp_usb = (PTP_USB *)data; unsigned long toread = 0; int ret = 0; int xread; unsigned long curread = 0; unsigned long written; unsigned char *bytes; int expect_terminator_byte = 0; // This is the largest block we'll need to read in. bytes = malloc(CONTEXT_BLOCK_SIZE); while (curread < size) { LIBMTP_USB_DEBUG("Remaining size to read: 0x%04lx bytes\n", size - curread); // check equal to condition here if (size - curread < CONTEXT_BLOCK_SIZE) { // this is the last packet toread = size - curread; // this is equivalent to zero read for these devices if (readzero && FLAG_NO_ZERO_READS(ptp_usb) && toread % 64 == 0) { toread += 1; expect_terminator_byte = 1; } } else if (curread == 0) // we are first packet, but not last packet toread = CONTEXT_BLOCK_SIZE_1; else if (toread == CONTEXT_BLOCK_SIZE_1) toread = CONTEXT_BLOCK_SIZE_2; else if (toread == CONTEXT_BLOCK_SIZE_2) toread = CONTEXT_BLOCK_SIZE_1; else LIBMTP_INFO("unexpected toread size 0x%04x, 0x%04x remaining bytes\n", (unsigned int) toread, (unsigned int) (size-curread)); LIBMTP_USB_DEBUG("Reading in 0x%04lx bytes\n", toread); ret = USB_BULK_READ(ptp_usb->handle, ptp_usb->inep, bytes, toread, &xread, ptp_usb->timeout); LIBMTP_USB_DEBUG("Result of read: 0x%04x (%d bytes)\n", ret, xread); if (ret != LIBUSB_SUCCESS) return PTP_ERROR_IO; LIBMTP_USB_DEBUG("<==USB IN\n"); if (xread == 0) LIBMTP_USB_DEBUG("Zero Read\n"); else LIBMTP_USB_DATA(bytes, xread, 16); // want to discard extra byte if (expect_terminator_byte && xread == toread) { LIBMTP_USB_DEBUG("<==USB IN\nDiscarding extra byte\n"); xread--; } int putfunc_ret = handler->putfunc(NULL, handler->priv, xread, bytes, &written); if (putfunc_ret != PTP_RC_OK) return putfunc_ret; ptp_usb->current_transfer_complete += xread; curread += xread; // Increase counters, call callback if (ptp_usb->callback_active) { if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) { // send last update and disable callback. ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total; ptp_usb->callback_active = 0; } if (ptp_usb->current_transfer_callback != NULL) { int ret; ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete, ptp_usb->current_transfer_total, ptp_usb->current_transfer_callback_data); if (ret != 0) { return PTP_ERROR_CANCEL; } } } if (xread < toread) /* short reads are common */ break; } if (readbytes) *readbytes = curread; free (bytes); // there might be a zero packet waiting for us... if (readzero && !FLAG_NO_ZERO_READS(ptp_usb) && curread % ptp_usb->outep_maxpacket == 0) { unsigned char temp; int zeroresult = 0, xread; LIBMTP_USB_DEBUG("<==USB IN\n"); LIBMTP_USB_DEBUG("Zero Read\n"); zeroresult = USB_BULK_READ(ptp_usb->handle, ptp_usb->inep, &temp, 0, &xread, ptp_usb->timeout); if (zeroresult != LIBUSB_SUCCESS) LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult); } return PTP_RC_OK; } static short ptp_write_func ( unsigned long size, PTPDataHandler *handler, void *data, unsigned long *written ) { PTP_USB *ptp_usb = (PTP_USB *)data; unsigned long towrite = 0; int ret = 0; unsigned long curwrite = 0; unsigned char *bytes; // This is the largest block we'll need to read in. bytes = malloc(CONTEXT_BLOCK_SIZE); if (!bytes) { return PTP_ERROR_IO; } while (curwrite < size) { unsigned long usbwritten = 0; int xwritten; towrite = size-curwrite; if (towrite > CONTEXT_BLOCK_SIZE) { towrite = CONTEXT_BLOCK_SIZE; } else { // This magic makes packets the same size that WMP send them. if (towrite > ptp_usb->outep_maxpacket && towrite % ptp_usb->outep_maxpacket != 0) { towrite -= towrite % ptp_usb->outep_maxpacket; } } int getfunc_ret = handler->getfunc(NULL, handler->priv,towrite,bytes,&towrite); if (getfunc_ret != PTP_RC_OK) { free(bytes); return getfunc_ret; } while (usbwritten < towrite) { ret = USB_BULK_WRITE(ptp_usb->handle, ptp_usb->outep, bytes+usbwritten, towrite-usbwritten, &xwritten, ptp_usb->timeout); LIBMTP_USB_DEBUG("USB OUT==>\n"); if (ret != LIBUSB_SUCCESS) { free(bytes); return PTP_ERROR_IO; } LIBMTP_USB_DATA(bytes+usbwritten, xwritten, 16); // check for result == 0 perhaps too. // Increase counters ptp_usb->current_transfer_complete += xwritten; curwrite += xwritten; usbwritten += xwritten; } // call callback if (ptp_usb->callback_active) { if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) { // send last update and disable callback. ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total; ptp_usb->callback_active = 0; } if (ptp_usb->current_transfer_callback != NULL) { int ret; ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete, ptp_usb->current_transfer_total, ptp_usb->current_transfer_callback_data); if (ret != 0) { free(bytes); return PTP_ERROR_CANCEL; } } } if (xwritten < towrite) /* short writes happen */ break; } free (bytes); if (written) { *written = curwrite; } // If this is the last transfer send a zero write if required if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) { if ((towrite % ptp_usb->outep_maxpacket) == 0) { int xwritten; LIBMTP_USB_DEBUG("USB OUT==>\n"); LIBMTP_USB_DEBUG("Zero Write\n"); ret =USB_BULK_WRITE(ptp_usb->handle, ptp_usb->outep, (unsigned char *) "x", 0, &xwritten, ptp_usb->timeout); } } if (ret != LIBUSB_SUCCESS) return PTP_ERROR_IO; return PTP_RC_OK; } /* memory data get/put handler */ typedef struct { unsigned char *data; unsigned long size, curoff; } PTPMemHandlerPrivate; static uint16_t memory_getfunc(PTPParams* params, void* private, unsigned long wantlen, unsigned char *data, unsigned long *gotlen ) { PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)private; unsigned long tocopy = wantlen; if (priv->curoff + tocopy > priv->size) tocopy = priv->size - priv->curoff; memcpy (data, priv->data + priv->curoff, tocopy); priv->curoff += tocopy; *gotlen = tocopy; return PTP_RC_OK; } static uint16_t memory_putfunc(PTPParams* params, void* private, unsigned long sendlen, unsigned char *data, unsigned long *putlen ) { PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)private; if (priv->curoff + sendlen > priv->size) { priv->data = realloc (priv->data, priv->curoff+sendlen); priv->size = priv->curoff + sendlen; } memcpy (priv->data + priv->curoff, data, sendlen); priv->curoff += sendlen; *putlen = sendlen; return PTP_RC_OK; } /* init private struct for receiving data. */ static uint16_t ptp_init_recv_memory_handler(PTPDataHandler *handler) { PTPMemHandlerPrivate* priv; priv = malloc (sizeof(PTPMemHandlerPrivate)); handler->priv = priv; handler->getfunc = memory_getfunc; handler->putfunc = memory_putfunc; priv->data = NULL; priv->size = 0; priv->curoff = 0; return PTP_RC_OK; } /* init private struct and put data in for sending data. * data is still owned by caller. */ static uint16_t ptp_init_send_memory_handler(PTPDataHandler *handler, unsigned char *data, unsigned long len ) { PTPMemHandlerPrivate* priv; priv = malloc (sizeof(PTPMemHandlerPrivate)); if (!priv) return PTP_RC_GeneralError; handler->priv = priv; handler->getfunc = memory_getfunc; handler->putfunc = memory_putfunc; priv->data = data; priv->size = len; priv->curoff = 0; return PTP_RC_OK; } /* free private struct + data */ static uint16_t ptp_exit_send_memory_handler (PTPDataHandler *handler) { PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)handler->priv; /* data is owned by caller */ free (priv); return PTP_RC_OK; } /* hand over our internal data to caller */ static uint16_t ptp_exit_recv_memory_handler (PTPDataHandler *handler, unsigned char **data, unsigned long *size ) { PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)handler->priv; *data = priv->data; *size = priv->size; free (priv); return PTP_RC_OK; } /* send / receive functions */ uint16_t ptp_usb_sendreq (PTPParams* params, PTPContainer* req) { uint16_t ret; PTPUSBBulkContainer usbreq; PTPDataHandler memhandler; unsigned long written = 0; unsigned long towrite; char txt[256]; (void) ptp_render_opcode (params, req->Code, sizeof(txt), txt); LIBMTP_USB_DEBUG("REQUEST: 0x%04x, %s\n", req->Code, txt); /* build appropriate USB container */ usbreq.length=htod32(PTP_USB_BULK_REQ_LEN- (sizeof(uint32_t)*(5-req->Nparam))); usbreq.type=htod16(PTP_USB_CONTAINER_COMMAND); usbreq.code=htod16(req->Code); usbreq.trans_id=htod32(req->Transaction_ID); usbreq.payload.params.param1=htod32(req->Param1); usbreq.payload.params.param2=htod32(req->Param2); usbreq.payload.params.param3=htod32(req->Param3); usbreq.payload.params.param4=htod32(req->Param4); usbreq.payload.params.param5=htod32(req->Param5); /* send it to responder */ towrite = PTP_USB_BULK_REQ_LEN-(sizeof(uint32_t)*(5-req->Nparam)); ptp_init_send_memory_handler (&memhandler, (unsigned char*)&usbreq, towrite); ret=ptp_write_func( towrite, &memhandler, params->data, &written ); ptp_exit_send_memory_handler (&memhandler); if (ret != PTP_RC_OK && ret != PTP_ERROR_CANCEL) { ret = PTP_ERROR_IO; } if (written != towrite && ret != PTP_ERROR_CANCEL && ret != PTP_ERROR_IO) { libusb_glue_error (params, "PTP: request code 0x%04x sending req wrote only %ld bytes instead of %d", req->Code, written, towrite ); ret = PTP_ERROR_IO; } return ret; } uint16_t ptp_usb_senddata (PTPParams* params, PTPContainer* ptp, uint64_t size, PTPDataHandler *handler ) { uint16_t ret; int wlen, datawlen; unsigned long written; PTPUSBBulkContainer usbdata; uint64_t bytes_left_to_transfer; PTPDataHandler memhandler; LIBMTP_USB_DEBUG("SEND DATA PHASE\n"); /* build appropriate USB container */ usbdata.length = htod32(PTP_USB_BULK_HDR_LEN+size); usbdata.type = htod16(PTP_USB_CONTAINER_DATA); usbdata.code = htod16(ptp->Code); usbdata.trans_id= htod32(ptp->Transaction_ID); ((PTP_USB*)params->data)->current_transfer_complete = 0; ((PTP_USB*)params->data)->current_transfer_total = size+PTP_USB_BULK_HDR_LEN; if (params->split_header_data) { datawlen = 0; wlen = PTP_USB_BULK_HDR_LEN; } else { unsigned long gotlen; /* For all camera devices. */ datawlen = (sizegetfunc(params, handler->priv, datawlen, usbdata.payload.data, &gotlen); if (ret != PTP_RC_OK) return ret; if (gotlen != datawlen) return PTP_RC_GeneralError; } ptp_init_send_memory_handler (&memhandler, (unsigned char *)&usbdata, wlen); /* send first part of data */ ret = ptp_write_func(wlen, &memhandler, params->data, &written); ptp_exit_send_memory_handler (&memhandler); if (ret != PTP_RC_OK) { return ret; } if (size <= datawlen) return ret; /* if everything OK send the rest */ bytes_left_to_transfer = size-datawlen; ret = PTP_RC_OK; while(bytes_left_to_transfer > 0) { ret = ptp_write_func (bytes_left_to_transfer, handler, params->data, &written); if (ret != PTP_RC_OK) break; if (written == 0) { ret = PTP_ERROR_IO; break; } bytes_left_to_transfer -= written; } if (ret != PTP_RC_OK && ret != PTP_ERROR_CANCEL) ret = PTP_ERROR_IO; return ret; } static uint16_t ptp_usb_getpacket(PTPParams *params, PTPUSBBulkContainer *packet, unsigned long *rlen) { PTPDataHandler memhandler; uint16_t ret; unsigned char *x = NULL; /* read the header and potentially the first data */ if (params->response_packet_size > 0) { /* If there is a buffered packet, just use it. */ memcpy(packet, params->response_packet, params->response_packet_size); *rlen = params->response_packet_size; free(params->response_packet); params->response_packet = NULL; params->response_packet_size = 0; /* Here this signifies a "virtual read" */ return PTP_RC_OK; } ptp_init_recv_memory_handler (&memhandler); ret = ptp_read_func(PTP_USB_BULK_HS_MAX_PACKET_LEN_READ, &memhandler, params->data, rlen, 0); ptp_exit_recv_memory_handler (&memhandler, &x, rlen); if (x) { memcpy (packet, x, *rlen); free (x); } return ret; } uint16_t ptp_usb_getdata (PTPParams* params, PTPContainer* ptp, PTPDataHandler *handler) { uint16_t ret; PTPUSBBulkContainer usbdata; unsigned long written; PTP_USB *ptp_usb = (PTP_USB *) params->data; int putfunc_ret; LIBMTP_USB_DEBUG("GET DATA PHASE\n"); memset(&usbdata,0,sizeof(usbdata)); do { unsigned long len, rlen; ret = ptp_usb_getpacket(params, &usbdata, &rlen); if (ret != PTP_RC_OK) { ret = PTP_ERROR_IO; break; } if (dtoh16(usbdata.type)!=PTP_USB_CONTAINER_DATA) { ret = PTP_ERROR_DATA_EXPECTED; break; } if (dtoh16(usbdata.code)!=ptp->Code) { if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) { libusb_glue_debug (params, "ptp2/ptp_usb_getdata: detected a broken " "PTP header, code field insane, expect problems! (But continuing)"); // Repair the header, so it won't wreak more havoc, don't just ignore it. // Typically these two fields will be broken. usbdata.code = htod16(ptp->Code); usbdata.trans_id = htod32(ptp->Transaction_ID); ret = PTP_RC_OK; } else { ret = dtoh16(usbdata.code); // This filters entirely insane garbage return codes, but still // makes it possible to return error codes in the code field when // getting data. It appears Windows ignores the contents of this // field entirely. if (ret < PTP_RC_Undefined || ret > PTP_RC_SpecificationOfDestinationUnsupported) { libusb_glue_debug (params, "ptp2/ptp_usb_getdata: detected a broken " "PTP header, code field insane."); ret = PTP_ERROR_IO; } break; } } if (rlen == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ) { /* Copy first part of data to 'data' */ putfunc_ret = handler->putfunc( params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN, usbdata.payload.data, &written ); if (putfunc_ret != PTP_RC_OK) return putfunc_ret; /* stuff data directly to passed data handler */ while (1) { unsigned long readdata; uint16_t xret; xret = ptp_read_func( 0x20000000, handler, params->data, &readdata, 0 ); if (xret != PTP_RC_OK) return xret; if (readdata < 0x20000000) break; } return PTP_RC_OK; } if (rlen > dtoh32(usbdata.length)) { /* * Buffer the surplus response packet if it is >= * PTP_USB_BULK_HDR_LEN * (i.e. it is probably an entire package) * else discard it as erroneous surplus data. * This will even work if more than 2 packets appear * in the same transaction, they will just be handled * iteratively. * * Marcus observed stray bytes on iRiver devices; * these are still discarded. */ unsigned int packlen = dtoh32(usbdata.length); unsigned int surplen = rlen - packlen; if (surplen >= PTP_USB_BULK_HDR_LEN) { params->response_packet = malloc(surplen); memcpy(params->response_packet, (uint8_t *) &usbdata + packlen, surplen); params->response_packet_size = surplen; /* Ignore reading one extra byte if device flags have been set */ } else if(!FLAG_NO_ZERO_READS(ptp_usb) && (rlen - dtoh32(usbdata.length) == 1)) { libusb_glue_debug (params, "ptp2/ptp_usb_getdata: read %d bytes " "too much, expect problems!", rlen - dtoh32(usbdata.length)); } rlen = packlen; } /* For most PTP devices rlen is 512 == sizeof(usbdata) * here. For MTP devices splitting header and data it might * be 12. */ /* Evaluate full data length. */ len=dtoh32(usbdata.length)-PTP_USB_BULK_HDR_LEN; /* autodetect split header/data MTP devices */ if (dtoh32(usbdata.length) > 12 && (rlen==12)) params->split_header_data = 1; /* Copy first part of data to 'data' */ putfunc_ret = handler->putfunc( params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN, usbdata.payload.data, &written ); if (putfunc_ret != PTP_RC_OK) return putfunc_ret; if (FLAG_NO_ZERO_READS(ptp_usb) && len+PTP_USB_BULK_HDR_LEN == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ) { LIBMTP_USB_DEBUG("Reading in extra terminating byte\n"); // need to read in extra byte and discard it int result = 0, xread; unsigned char byte = 0; result = USB_BULK_READ(ptp_usb->handle, ptp_usb->inep, &byte, 1, &xread, ptp_usb->timeout); if (result != 1) 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); } else if (len+PTP_USB_BULK_HDR_LEN == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ && params->split_header_data == 0) { int zeroresult = 0, xread; unsigned char zerobyte = 0; LIBMTP_INFO("Reading in zero packet after header\n"); zeroresult = USB_BULK_READ(ptp_usb->handle, ptp_usb->inep, &zerobyte, 0, &xread, ptp_usb->timeout); if (zeroresult != 0) LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult); } /* Is that all of data? */ if (len+PTP_USB_BULK_HDR_LEN<=rlen) { break; } ret = ptp_read_func(len - (rlen - PTP_USB_BULK_HDR_LEN), handler, params->data, &rlen, 1); if (ret != PTP_RC_OK) { break; } } while (0); return ret; } uint16_t ptp_usb_getresp (PTPParams* params, PTPContainer* resp) { uint16_t ret; unsigned long rlen; PTPUSBBulkContainer usbresp; PTP_USB *ptp_usb = (PTP_USB *)(params->data); LIBMTP_USB_DEBUG("RESPONSE: "); memset(&usbresp,0,sizeof(usbresp)); /* read response, it should never be longer than sizeof(usbresp) */ ret = ptp_usb_getpacket(params, &usbresp, &rlen); // Fix for bevahiour reported by Scott Snyder on Samsung YP-U3. The player // sends a packet containing just zeroes of length 2 (up to 4 has been seen too) // after a NULL packet when it should send the response. This code ignores // such illegal packets. while (ret==PTP_RC_OK && rlenCode) { ret = dtoh16(usbresp.code); } LIBMTP_USB_DEBUG("%04x\n", ret); if (ret != PTP_RC_OK) { /* libusb_glue_error (params, "PTP: request code 0x%04x getting resp error 0x%04x", resp->Code, ret);*/ return ret; } /* build an appropriate PTPContainer */ resp->Code=dtoh16(usbresp.code); resp->SessionID=params->session_id; resp->Transaction_ID=dtoh32(usbresp.trans_id); if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) { if (resp->Transaction_ID != params->transaction_id-1) { libusb_glue_debug (params, "ptp_usb_getresp: detected a broken " "PTP header, transaction ID insane, expect " "problems! (But continuing)"); // Repair the header, so it won't wreak more havoc. resp->Transaction_ID = params->transaction_id-1; } } resp->Param1=dtoh32(usbresp.payload.params.param1); resp->Param2=dtoh32(usbresp.payload.params.param2); resp->Param3=dtoh32(usbresp.payload.params.param3); resp->Param4=dtoh32(usbresp.payload.params.param4); resp->Param5=dtoh32(usbresp.payload.params.param5); return ret; } /* Event handling functions */ /* PTP Events wait for or check mode */ #define PTP_EVENT_CHECK 0x0000 /* waits for */ #define PTP_EVENT_CHECK_FAST 0x0001 /* checks */ static inline uint16_t ptp_usb_event (PTPParams* params, PTPContainer* event, int wait) { uint16_t ret; int result, xread; unsigned long rlen; PTPUSBEventContainer usbevent; PTP_USB *ptp_usb = (PTP_USB *)(params->data); memset(&usbevent,0,sizeof(usbevent)); if ((params==NULL) || (event==NULL)) return PTP_ERROR_BADPARAM; ret = PTP_RC_OK; switch(wait) { case PTP_EVENT_CHECK: result = USB_BULK_READ(ptp_usb->handle, ptp_usb->intep, (unsigned char *) &usbevent, sizeof(usbevent), &xread, 0); if (xread == 0) result = USB_BULK_READ(ptp_usb->handle, ptp_usb->intep, (unsigned char *) &usbevent, sizeof(usbevent), &xread, 0); if (result < 0) ret = PTP_ERROR_IO; break; case PTP_EVENT_CHECK_FAST: result = USB_BULK_READ(ptp_usb->handle, ptp_usb->intep, (unsigned char *) &usbevent, sizeof(usbevent), &xread, ptp_usb->timeout); if (xread == 0) result = USB_BULK_READ(ptp_usb->handle, ptp_usb->intep, (unsigned char *) &usbevent, sizeof(usbevent), &xread, ptp_usb->timeout); if (result < 0) ret = PTP_ERROR_IO; break; default: ret = PTP_ERROR_BADPARAM; break; } if (ret != PTP_RC_OK) { libusb_glue_error (params, "PTP: reading event an error 0x%04x occurred", ret); return PTP_ERROR_IO; } rlen = xread; if (rlen < 8) { libusb_glue_error (params, "PTP: reading event an short read of %ld bytes occurred", rlen); return PTP_ERROR_IO; } /* if we read anything over interrupt endpoint it must be an event */ /* build an appropriate PTPContainer */ event->Code=dtoh16(usbevent.code); event->SessionID=params->session_id; event->Transaction_ID=dtoh32(usbevent.trans_id); event->Param1=dtoh32(usbevent.param1); event->Param2=dtoh32(usbevent.param2); event->Param3=dtoh32(usbevent.param3); return ret; } uint16_t ptp_usb_event_check (PTPParams* params, PTPContainer* event) { return ptp_usb_event (params, event, PTP_EVENT_CHECK_FAST); } uint16_t ptp_usb_event_wait (PTPParams* params, PTPContainer* event) { return ptp_usb_event (params, event, PTP_EVENT_CHECK); } uint16_t ptp_usb_control_cancel_request (PTPParams *params, uint32_t transactionid) { PTP_USB *ptp_usb = (PTP_USB *)(params->data); int ret; unsigned char buffer[6]; htod16a(&buffer[0],PTP_EC_CancelTransaction); htod32a(&buffer[2],transactionid); ret = libusb_control_transfer(ptp_usb->handle, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0x64, 0x0000, 0x0000, buffer, sizeof(buffer), ptp_usb->timeout); if (ret < sizeof(buffer)) return PTP_ERROR_IO; return PTP_RC_OK; } static int init_ptp_usb(PTPParams* params, PTP_USB* ptp_usb, libusb_device* dev) { libusb_device_handle *device_handle; unsigned char buf[255]; int ret, usbresult; struct libusb_config_descriptor *config; params->sendreq_func=ptp_usb_sendreq; params->senddata_func=ptp_usb_senddata; params->getresp_func=ptp_usb_getresp; params->getdata_func=ptp_usb_getdata; params->cancelreq_func=ptp_usb_control_cancel_request; params->data=ptp_usb; params->transaction_id=0; /* * This is hardcoded here since we have no devices whatsoever that are BE. * Change this the day we run into our first BE device (if ever). */ params->byteorder = PTP_DL_LE; ptp_usb->timeout = get_timeout(ptp_usb); ret = libusb_open(dev, &device_handle); if (ret != LIBUSB_SUCCESS) { perror("libusb_open() failed!"); return -1; } ptp_usb->handle = device_handle; /* * If this device is known to be wrongfully claimed by other kernel * drivers (such as mass storage), then try to unload it to make it * accessible from user space. */ if (FLAG_UNLOAD_DRIVER(ptp_usb) && libusb_kernel_driver_active(device_handle, ptp_usb->interface) ) { if (LIBUSB_SUCCESS != libusb_detach_kernel_driver(device_handle, ptp_usb->interface)) { perror("libusb_detach_kernel_driver() failed, continuing anyway..."); } } /* * Check if the config is set to something else than what we want * to use. Only set the configuration if we absolutely have to. * Also do not bail out if we fail. * * Note that Darwin will not set the configuration for vendor-specific * devices so we need to go in and set it. */ ret = libusb_get_active_config_descriptor(dev, &config); if (ret != LIBUSB_SUCCESS) { perror("libusb_get_active_config_descriptor(1) failed"); fprintf(stderr, "no active configuration, trying to set configuration\n"); if (libusb_set_configuration(device_handle, ptp_usb->config) != LIBUSB_SUCCESS) { perror("libusb_set_configuration() failed, continuing anyway..."); } ret = libusb_get_active_config_descriptor(dev, &config); if (ret != LIBUSB_SUCCESS) { perror("libusb_get_active_config_descriptor(2) failed"); return -1; } } if (config->bConfigurationValue != ptp_usb->config) { fprintf(stderr, "desired configuration different from current, trying to set configuration\n"); if (libusb_set_configuration(device_handle, ptp_usb->config)) { perror("libusb_set_configuration() failed, continuing anyway..."); } /* Re-fetch the config descriptor if we changed */ libusb_free_config_descriptor(config); ret = libusb_get_active_config_descriptor(dev, &config); if (ret != LIBUSB_SUCCESS) { perror("libusb_get_active_config_descriptor(2) failed"); return -1; } } /* * It seems like on kernel 2.6.31 if we already have it open on another * pthread in our app, we'll get an error if we try to claim it again, * but that error is harmless because our process already claimed the interface */ usbresult = libusb_claim_interface(device_handle, ptp_usb->interface); if (usbresult != 0) fprintf(stderr, "ignoring libusb_claim_interface() = %d", usbresult); /* * If the altsetting is set to something different than we want, switch * it. * * FIXME: this seems to cause trouble on the Mac:s so disable it. Retry * this on the Mac now that it only sets this when the altsetting differs. */ #ifndef __APPLE__ #if 0 /* Disable this always, no idea on how to handle it */ if (config->interface[].altsetting[].bAlternateSetting != ptp_usb->altsetting) { fprintf(stderr, "desired altsetting different from current, trying to set altsetting\n"); usbresult = libusb_set_interface_alt_setting(device_handle, ptp_usb->interface, ptp_usb->altsetting); if (usbresult != 0) fprintf(stderr, "ignoring libusb_set_interface_alt_setting() = %d\n", usbresult); } #endif #endif libusb_free_config_descriptor(config); if (FLAG_SWITCH_MODE_BLACKBERRY(ptp_usb)) { int ret; // FIXME : Only for BlackBerry Storm // What does it mean? Maybe switch mode... // This first control message is absolutely necessary usleep(1000); ret = libusb_control_transfer(device_handle, LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN, 0xaa, 0x00, 0x04, buf, 0x40, 1000); LIBMTP_USB_DEBUG("BlackBerry magic part 1:\n"); LIBMTP_USB_DATA(buf, ret, 16); usleep(1000); // This control message is unnecessary ret = libusb_control_transfer(device_handle, LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN, 0xa5, 0x00, 0x01, buf, 0x02, 1000); LIBMTP_USB_DEBUG("BlackBerry magic part 2:\n"); LIBMTP_USB_DATA(buf, ret, 16); usleep(1000); // This control message is unnecessary ret = libusb_control_transfer(device_handle, LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN, 0xa8, 0x00, 0x01, buf, 0x05, 1000); LIBMTP_USB_DEBUG("BlackBerry magic part 3:\n"); LIBMTP_USB_DATA(buf, ret, 16); usleep(1000); // This control message is unnecessary ret = libusb_control_transfer(device_handle, LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN, 0xa8, 0x00, 0x01, buf, 0x11, 1000); LIBMTP_USB_DEBUG("BlackBerry magic part 4:\n"); LIBMTP_USB_DATA(buf, ret, 16); usleep(1000); } return 0; } static void clear_stall(PTP_USB* ptp_usb) { uint16_t status; int ret; /* check the inep status */ status = 0; ret = usb_get_endpoint_status(ptp_usb,ptp_usb->inep,&status); if (ret<0) { perror ("inep: usb_get_endpoint_status()"); } else if (status) { LIBMTP_INFO("Clearing stall on IN endpoint\n"); ret = libusb_clear_halt (ptp_usb->handle, ptp_usb->inep); if (ret != LIBUSB_SUCCESS) { perror ("usb_clear_stall_feature()"); } } /* check the outep status */ status=0; ret = usb_get_endpoint_status(ptp_usb,ptp_usb->outep,&status); if (ret<0) { perror("outep: usb_get_endpoint_status()"); } else if (status) { LIBMTP_INFO("Clearing stall on OUT endpoint\n"); ret = libusb_clear_halt (ptp_usb->handle, ptp_usb->outep); if (ret != LIBUSB_SUCCESS) { perror("usb_clear_stall_feature()"); } } /* TODO: do we need this for INTERRUPT (ptp_usb->intep) too? */ } static void clear_halt(PTP_USB* ptp_usb) { int ret; ret = libusb_clear_halt(ptp_usb->handle,ptp_usb->inep); if (ret<0) { perror("usb_clear_halt() on IN endpoint"); } ret = libusb_clear_halt(ptp_usb->handle,ptp_usb->outep); if (ret<0) { perror("usb_clear_halt() on OUT endpoint"); } ret = libusb_clear_halt(ptp_usb->handle,ptp_usb->intep); if (ret<0) { perror("usb_clear_halt() on INTERRUPT endpoint"); } } static void close_usb(PTP_USB* ptp_usb) { if (!FLAG_NO_RELEASE_INTERFACE(ptp_usb)) { /* * Clear any stalled endpoints * On misbehaving devices designed for Windows/Mac, quote from: * http://www2.one-eyed-alien.net/~mdharm/linux-usb/target_offenses.txt * Device does Bad Things(tm) when it gets a GET_STATUS after CLEAR_HALT * (...) Windows, when clearing a stall, only sends the CLEAR_HALT command, * and presumes that the stall has cleared. Some devices actually choke * if the CLEAR_HALT is followed by a GET_STATUS (used to determine if the * STALL is persistant or not). */ clear_stall(ptp_usb); #if 0 // causes hangs on Linux 3.x at least up to 3.8 // Clear halts on any endpoints clear_halt(ptp_usb); // Added to clear some stuff on the OUT endpoint // TODO: is this good on the Mac too? // HINT: some devices may need that you comment these two out too. libusb_clear_halt(ptp_usb->handle, ptp_usb->outep); #endif libusb_release_interface(ptp_usb->handle, (int) ptp_usb->interface); } if (FLAG_FORCE_RESET_ON_CLOSE(ptp_usb)) { /* * Some devices really love to get reset after being * disconnected. Again, since Windows never disconnects * a device closing behaviour is seldom or never exercised * on devices when engineered and often error prone. * Reset may help some. */ libusb_reset_device (ptp_usb->handle); } libusb_close(ptp_usb->handle); } /** * Self-explanatory? */ static int find_interface_and_endpoints(libusb_device *dev, uint8_t *conf, uint8_t *interface, uint8_t *altsetting, int* inep, int* inep_maxpacket, int* outep, int *outep_maxpacket, int* intep) { uint8_t i, ret; struct libusb_device_descriptor desc; ret = libusb_get_device_descriptor(dev, &desc); if (ret != LIBUSB_SUCCESS) return -1; // Loop over the device configurations for (i = 0; i < desc.bNumConfigurations; i++) { uint8_t j; struct libusb_config_descriptor *config; ret = libusb_get_config_descriptor(dev, i, &config); if (ret != 0) continue; *conf = config->bConfigurationValue; if (ret != LIBUSB_SUCCESS) continue; // Loop over each configurations interfaces for (j = 0; j < config->bNumInterfaces; j++) { uint8_t k, l; uint8_t no_ep; int found_inep = 0; int found_outep = 0; int found_intep = 0; const struct libusb_endpoint_descriptor *ep; // Inspect the altsettings of this interface... for (k = 0; k < config->interface[j].num_altsetting; k++) { // MTP devices shall have 3 endpoints, ignore those interfaces // that haven't. no_ep = config->interface[j].altsetting[k].bNumEndpoints; if (no_ep != 3) continue; *interface = config->interface[j].altsetting[k].bInterfaceNumber; *altsetting = config->interface[j].altsetting[k].bAlternateSetting; ep = config->interface[j].altsetting[k].endpoint; // Loop over the three endpoints to locate two bulk and // one interrupt endpoint and FAIL if we cannot, and continue. for (l = 0; l < no_ep; l++) { if (ep[l].bmAttributes == LIBUSB_TRANSFER_TYPE_BULK) { if ((ep[l].bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_DIR_MASK) { *inep = ep[l].bEndpointAddress; *inep_maxpacket = ep[l].wMaxPacketSize; found_inep = 1; } if ((ep[l].bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == 0) { *outep = ep[l].bEndpointAddress; *outep_maxpacket = ep[l].wMaxPacketSize; found_outep = 1; } } else if (ep[l].bmAttributes == LIBUSB_TRANSFER_TYPE_INTERRUPT) { if ((ep[l].bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_DIR_MASK) { *intep = ep[l].bEndpointAddress; found_intep = 1; } } } if (found_inep && found_outep && found_intep) { libusb_free_config_descriptor(config); // We assigned the endpoints so return here. return 0; } } // Next altsetting } // Next interface libusb_free_config_descriptor(config); } // Next config return -1; } /** * This function assigns params and usbinfo given a raw device * as input. * @param device the device to be assigned. * @param usbinfo a pointer to the new usbinfo. * @return an error code. */ LIBMTP_error_number_t configure_usb_device(LIBMTP_raw_device_t *device, PTPParams *params, void **usbinfo) { PTP_USB *ptp_usb; libusb_device *ldevice; uint16_t ret = 0; int err, found = 0, i; ssize_t nrofdevs; libusb_device **devs = NULL; struct libusb_device_descriptor desc; LIBMTP_error_number_t init_usb_ret; /* See if we can find this raw device again... */ init_usb_ret = init_usb(); if (init_usb_ret != LIBMTP_ERROR_NONE) return init_usb_ret; nrofdevs = libusb_get_device_list(NULL, &devs); for (i = 0; i < nrofdevs ; i++) { if (libusb_get_bus_number(devs[i]) != device->bus_location) continue; if (libusb_get_device_address(devs[i]) != device->devnum) continue; ret = libusb_get_device_descriptor(devs[i], &desc); if (ret != LIBUSB_SUCCESS) continue; if(desc.idVendor == device->device_entry.vendor_id && desc.idProduct == device->device_entry.product_id ) { ldevice = devs[i]; found = 1; break; } } /* Device has gone since detecting raw devices! */ if (!found) { libusb_free_device_list (devs, 0); return LIBMTP_ERROR_NO_DEVICE_ATTACHED; } /* Allocate structs */ ptp_usb = (PTP_USB *) malloc(sizeof(PTP_USB)); if (ptp_usb == NULL) { libusb_free_device_list (devs, 0); return LIBMTP_ERROR_MEMORY_ALLOCATION; } /* Start with a blank slate (includes setting device_flags to 0) */ memset(ptp_usb, 0, sizeof(PTP_USB)); /* Copy the raw device */ memcpy(&ptp_usb->rawdevice, device, sizeof(LIBMTP_raw_device_t)); /* * Some devices must have their "OS Descriptor" massaged in order * to work. */ if (FLAG_ALWAYS_PROBE_DESCRIPTOR(ptp_usb)) { // Massage the device descriptor (void) probe_device_descriptor(ldevice, NULL); } /* Assign interface and endpoints to usbinfo... */ err = find_interface_and_endpoints(ldevice, &ptp_usb->config, &ptp_usb->interface, &ptp_usb->altsetting, &ptp_usb->inep, &ptp_usb->inep_maxpacket, &ptp_usb->outep, &ptp_usb->outep_maxpacket, &ptp_usb->intep); if (err) { libusb_free_device_list (devs, 0); LIBMTP_ERROR("LIBMTP PANIC: Unable to find interface & endpoints of device\n"); return LIBMTP_ERROR_CONNECTING; } /* Copy USB version number */ ptp_usb->bcdusb = desc.bcdUSB; /* Attempt to initialize this device */ if (init_ptp_usb(params, ptp_usb, ldevice) < 0) { LIBMTP_ERROR("LIBMTP PANIC: Unable to initialize device\n"); libusb_free_device_list (devs, 0); return LIBMTP_ERROR_CONNECTING; } /* * This works in situations where previous bad applications * have not used LIBMTP_Release_Device on exit */ if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) { LIBMTP_ERROR("PTP_ERROR_IO: failed to open session, trying again after resetting USB interface\n"); LIBMTP_ERROR("LIBMTP libusb: Attempt to reset device\n"); libusb_reset_device (ptp_usb->handle); close_usb(ptp_usb); if(init_ptp_usb(params, ptp_usb, ldevice) <0) { LIBMTP_ERROR("LIBMTP PANIC: Could not init USB on second attempt\n"); libusb_free_device_list (devs, 0); return LIBMTP_ERROR_CONNECTING; } /* Device has been reset, try again */ if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) { LIBMTP_ERROR("LIBMTP PANIC: failed to open session on second attempt\n"); libusb_free_device_list (devs, 0); return LIBMTP_ERROR_CONNECTING; } } /* Was the transaction id invalid? Try again */ if (ret == PTP_RC_InvalidTransactionID) { LIBMTP_ERROR("LIBMTP WARNING: Transaction ID was invalid, increment and try again\n"); params->transaction_id += 10; ret = ptp_opensession(params, 1); } if (ret != PTP_RC_SessionAlreadyOpened && ret != PTP_RC_OK) { LIBMTP_ERROR("LIBMTP PANIC: Could not open session! " "(Return code %d)\n Try to reset the device.\n", ret); libusb_release_interface(ptp_usb->handle, ptp_usb->interface); libusb_free_device_list (devs, 0); return LIBMTP_ERROR_CONNECTING; } /* OK configured properly */ *usbinfo = (void *) ptp_usb; libusb_free_device_list (devs, 0); return LIBMTP_ERROR_NONE; } void close_device (PTP_USB *ptp_usb, PTPParams *params) { if (ptp_closesession(params)!=PTP_RC_OK) LIBMTP_ERROR("ERROR: Could not close session!\n"); close_usb(ptp_usb); } void set_usb_device_timeout(PTP_USB *ptp_usb, int timeout) { ptp_usb->timeout = timeout; } void get_usb_device_timeout(PTP_USB *ptp_usb, int *timeout) { *timeout = ptp_usb->timeout; } int guess_usb_speed(PTP_USB *ptp_usb) { int bytes_per_second; /* * We don't know the actual speeds so these are rough guesses * from the info you can find here: * http://en.wikipedia.org/wiki/USB#Transfer_rates * http://www.barefeats.com/usb2.html */ switch (ptp_usb->bcdusb & 0xFF00) { case 0x0100: /* 1.x USB versions let's say 1MiB/s */ bytes_per_second = 1*1024*1024; break; case 0x0200: case 0x0300: /* USB 2.0 nominal speed 18MiB/s */ /* USB 3.0 won't be worse? */ bytes_per_second = 18*1024*1024; break; default: /* Half-guess something? */ bytes_per_second = 1*1024*1024; break; } return bytes_per_second; } static int usb_get_endpoint_status(PTP_USB* ptp_usb, int ep, uint16_t* status) { return libusb_control_transfer(ptp_usb->handle, LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_ENDPOINT, LIBUSB_REQUEST_GET_STATUS, USB_FEATURE_HALT, ep, (unsigned char *) status, 2, ptp_usb->timeout); } libmtp-1.1.6-20-g1b9f164/src/ptp-pack.c0000664000175000017500000020016212205614637017365 0ustar glowwormglowworm/* ptp-pack.c * * Copyright (C) 2001-2004 Mariusz Woloszyn * Copyright (C) 2003-2012 Marcus Meissner * Copyright (C) 2006-2008 Linus Walleij * Copyright (C) 2007 Tero Saarni * Copyright (C) 2009 Axel Waggershauser * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* currently this file is included into ptp.c */ #ifdef HAVE_ICONV #include #endif static inline uint16_t htod16p (PTPParams *params, uint16_t var) { return ((params->byteorder==PTP_DL_LE)?htole16(var):htobe16(var)); } static inline uint32_t htod32p (PTPParams *params, uint32_t var) { return ((params->byteorder==PTP_DL_LE)?htole32(var):htobe32(var)); } static inline void htod16ap (PTPParams *params, unsigned char *a, uint16_t val) { if (params->byteorder==PTP_DL_LE) htole16a(a,val); else htobe16a(a,val); } static inline void htod32ap (PTPParams *params, unsigned char *a, uint32_t val) { if (params->byteorder==PTP_DL_LE) htole32a(a,val); else htobe32a(a,val); } static inline void htod64ap (PTPParams *params, unsigned char *a, uint64_t val) { if (params->byteorder==PTP_DL_LE) htole64a(a,val); else htobe64a(a,val); } static inline uint16_t dtoh16p (PTPParams *params, uint16_t var) { return ((params->byteorder==PTP_DL_LE)?le16toh(var):be16toh(var)); } static inline uint32_t dtoh32p (PTPParams *params, uint32_t var) { return ((params->byteorder==PTP_DL_LE)?le32toh(var):be32toh(var)); } static inline uint64_t dtoh64p (PTPParams *params, uint64_t var) { return ((params->byteorder==PTP_DL_LE)?le64toh(var):be64toh(var)); } static inline uint16_t dtoh16ap (PTPParams *params, const unsigned char *a) { return ((params->byteorder==PTP_DL_LE)?le16atoh(a):be16atoh(a)); } static inline uint32_t dtoh32ap (PTPParams *params, const unsigned char *a) { return ((params->byteorder==PTP_DL_LE)?le32atoh(a):be32atoh(a)); } static inline uint64_t dtoh64ap (PTPParams *params, const unsigned char *a) { return ((params->byteorder==PTP_DL_LE)?le64atoh(a):be64atoh(a)); } #define htod8a(a,x) *(uint8_t*)(a) = x #define htod16a(a,x) htod16ap(params,a,x) #define htod32a(a,x) htod32ap(params,a,x) #define htod64a(a,x) htod64ap(params,a,x) #define htod16(x) htod16p(params,x) #define htod32(x) htod32p(params,x) #define htod64(x) htod64p(params,x) #define dtoh8a(x) (*(uint8_t*)(x)) #define dtoh16a(a) dtoh16ap(params,a) #define dtoh32a(a) dtoh32ap(params,a) #define dtoh64a(a) dtoh64ap(params,a) #define dtoh16(x) dtoh16p(params,x) #define dtoh32(x) dtoh32p(params,x) #define dtoh64(x) dtoh64p(params,x) static inline char* ptp_unpack_string(PTPParams *params, unsigned char* data, uint16_t offset, uint8_t *len) { uint8_t length; uint16_t string[PTP_MAXSTRLEN+1]; /* allow for UTF-8: max of 3 bytes per UCS-2 char, plus final null */ char loclstr[PTP_MAXSTRLEN*3+1]; size_t nconv, srclen, destlen; char *src, *dest; length = dtoh8a(&data[offset]); /* PTP_MAXSTRLEN == 255, 8 bit len */ *len = length; if (length == 0) /* nothing to do? */ return(NULL); /* copy to string[] to ensure correct alignment for iconv(3) */ memcpy(string, &data[offset+1], length * sizeof(string[0])); string[length] = 0x0000U; /* be paranoid! add a terminator. */ loclstr[0] = '\0'; /* convert from camera UCS-2 to our locale */ src = (char *)string; srclen = length * sizeof(string[0]); dest = loclstr; destlen = sizeof(loclstr)-1; nconv = (size_t)-1; #ifdef HAVE_ICONV if (params->cd_ucs2_to_locale != (iconv_t)-1) nconv = iconv(params->cd_ucs2_to_locale, &src, &srclen, &dest, &destlen); #endif if (nconv == (size_t) -1) { /* do it the hard way */ int i; /* try the old way, in case iconv is broken */ for (i=0;i127) loclstr[i] = '?'; else loclstr[i] = dtoh16a(&data[offset+1+2*i]); } dest = loclstr+length; } *dest = '\0'; loclstr[sizeof(loclstr)-1] = '\0'; /* be safe? */ return(strdup(loclstr)); } static inline int ucs2strlen(uint16_t const * const unicstr) { int length = 0; /* Unicode strings are terminated with 2 * 0x00 */ for(length = 0; unicstr[length] != 0x0000U; length ++); return length; } static inline void ptp_pack_string(PTPParams *params, char *string, unsigned char* data, uint16_t offset, uint8_t *len) { int packedlen = 0; uint16_t ucs2str[PTP_MAXSTRLEN+1]; char *ucs2strp = (char *) ucs2str; size_t convlen = strlen(string); /* Cannot exceed 255 (PTP_MAXSTRLEN) since it is a single byte, duh ... */ memset(ucs2strp, 0, sizeof(ucs2str)); /* XXX: necessary? */ #ifdef HAVE_ICONV if (params->cd_locale_to_ucs2 != (iconv_t)-1) { size_t nconv; size_t convmax = PTP_MAXSTRLEN * 2; /* Includes the terminator */ char *stringp = string; nconv = iconv(params->cd_locale_to_ucs2, &stringp, &convlen, &ucs2strp, &convmax); if (nconv == (size_t) -1) ucs2str[0] = 0x0000U; } else #endif { int i; for (i=0;i PTP_MAXSTRLEN-1) { *len=0; return; } /* number of characters including terminating 0 (PTP standard confirmed) */ htod8a(&data[offset],packedlen+1); memcpy(&data[offset+1], &ucs2str[0], packedlen * sizeof(ucs2str[0])); htod16a(&data[offset+packedlen*2+1], 0x0000); /* terminate 0 */ /* The returned length is in number of characters */ *len = (uint8_t) packedlen+1; } static inline unsigned char * ptp_get_packed_stringcopy(PTPParams *params, char *string, uint32_t *packed_size) { uint8_t packed[PTP_MAXSTRLEN*2+3], len; size_t plen; unsigned char *retcopy = NULL; if (string == NULL) ptp_pack_string(params, "", (unsigned char*) packed, 0, &len); else ptp_pack_string(params, string, (unsigned char*) packed, 0, &len); /* returned length is in characters, then one byte for string length */ plen = len*2 + 1; retcopy = malloc(plen); if (!retcopy) { *packed_size = 0; return NULL; } memcpy(retcopy, packed, plen); *packed_size = plen; return (retcopy); } static inline uint32_t ptp_unpack_uint32_t_array(PTPParams *params, unsigned char* data, uint16_t offset, uint32_t **array) { uint32_t n, i=0; n=dtoh32a(&data[offset]); *array = malloc (n*sizeof(uint32_t)); while (n>i) { (*array)[i]=dtoh32a(&data[offset+(sizeof(uint32_t)*(i+1))]); i++; } return n; } static inline uint32_t ptp_pack_uint32_t_array(PTPParams *params, uint32_t *array, uint32_t arraylen, unsigned char **data ) { uint32_t i=0; *data = malloc ((arraylen+1)*sizeof(uint32_t)); htod32a(&(*data)[0],arraylen); for (i=0;ii) { (*array)[i]=dtoh16a(&data[offset+(sizeof(uint16_t)*(i+2))]); i++; } return n; } /* DeviceInfo pack/unpack */ #define PTP_di_StandardVersion 0 #define PTP_di_VendorExtensionID 2 #define PTP_di_VendorExtensionVersion 6 #define PTP_di_VendorExtensionDesc 8 #define PTP_di_FunctionalMode 8 #define PTP_di_OperationsSupported 10 static inline void ptp_unpack_DI (PTPParams *params, unsigned char* data, PTPDeviceInfo *di, unsigned int datalen) { uint8_t len; unsigned int totallen; if (!data) return; if (datalen < 12) return; di->StandardVersion = dtoh16a(&data[PTP_di_StandardVersion]); di->VendorExtensionID = dtoh32a(&data[PTP_di_VendorExtensionID]); di->VendorExtensionVersion = dtoh16a(&data[PTP_di_VendorExtensionVersion]); di->VendorExtensionDesc = ptp_unpack_string(params, data, PTP_di_VendorExtensionDesc, &len); totallen=len*2+1; di->FunctionalMode = dtoh16a(&data[PTP_di_FunctionalMode+totallen]); di->OperationsSupported_len = ptp_unpack_uint16_t_array(params, data, PTP_di_OperationsSupported+totallen, &di->OperationsSupported); totallen=totallen+di->OperationsSupported_len*sizeof(uint16_t)+sizeof(uint32_t); di->EventsSupported_len = ptp_unpack_uint16_t_array(params, data, PTP_di_OperationsSupported+totallen, &di->EventsSupported); totallen=totallen+di->EventsSupported_len*sizeof(uint16_t)+sizeof(uint32_t); di->DevicePropertiesSupported_len = ptp_unpack_uint16_t_array(params, data, PTP_di_OperationsSupported+totallen, &di->DevicePropertiesSupported); totallen=totallen+di->DevicePropertiesSupported_len*sizeof(uint16_t)+sizeof(uint32_t); di->CaptureFormats_len = ptp_unpack_uint16_t_array(params, data, PTP_di_OperationsSupported+totallen, &di->CaptureFormats); totallen=totallen+di->CaptureFormats_len*sizeof(uint16_t)+sizeof(uint32_t); di->ImageFormats_len = ptp_unpack_uint16_t_array(params, data, PTP_di_OperationsSupported+totallen, &di->ImageFormats); totallen=totallen+di->ImageFormats_len*sizeof(uint16_t)+sizeof(uint32_t); di->Manufacturer = ptp_unpack_string(params, data, PTP_di_OperationsSupported+totallen, &len); totallen+=len*2+1; di->Model = ptp_unpack_string(params, data, PTP_di_OperationsSupported+totallen, &len); totallen+=len*2+1; di->DeviceVersion = ptp_unpack_string(params, data, PTP_di_OperationsSupported+totallen, &len); totallen+=len*2+1; di->SerialNumber = ptp_unpack_string(params, data, PTP_di_OperationsSupported+totallen, &len); } static void inline ptp_free_DI (PTPDeviceInfo *di) { if (di->SerialNumber) free (di->SerialNumber); if (di->DeviceVersion) free (di->DeviceVersion); if (di->Model) free (di->Model); if (di->Manufacturer) free (di->Manufacturer); if (di->ImageFormats) free (di->ImageFormats); if (di->CaptureFormats) free (di->CaptureFormats); if (di->VendorExtensionDesc) free (di->VendorExtensionDesc); if (di->OperationsSupported) free (di->OperationsSupported); if (di->EventsSupported) free (di->EventsSupported); if (di->DevicePropertiesSupported) free (di->DevicePropertiesSupported); } /* EOS Device Info unpack */ static inline void ptp_unpack_EOS_DI (PTPParams *params, unsigned char* data, PTPCanonEOSDeviceInfo *di, unsigned int datalen) { int totallen = 4; memset (di,0, sizeof(*di)); if (datalen < 8) return; /* uint32_t struct len - ignore */ di->EventsSupported_len = ptp_unpack_uint32_t_array(params, data, totallen, &di->EventsSupported); if (!di->EventsSupported) return; totallen += di->EventsSupported_len*sizeof(uint32_t)+4; if (totallen >= datalen) return; di->DevicePropertiesSupported_len = ptp_unpack_uint32_t_array(params, data, totallen, &di->DevicePropertiesSupported); if (!di->DevicePropertiesSupported) return; totallen += di->DevicePropertiesSupported_len*sizeof(uint32_t)+4; if (totallen >= datalen) return; di->unk_len = ptp_unpack_uint32_t_array(params, data, totallen, &di->unk); if (!di->unk) return; totallen += di->unk_len*sizeof(uint32_t)+4; return; } static inline void ptp_free_EOS_DI (PTPCanonEOSDeviceInfo *di) { free (di->EventsSupported); free (di->DevicePropertiesSupported); free (di->unk); } /* ObjectHandles array pack/unpack */ #define PTP_oh 0 static inline void ptp_unpack_OH (PTPParams *params, unsigned char* data, PTPObjectHandles *oh, unsigned int len) { if (len) { oh->n = ptp_unpack_uint32_t_array(params, data, PTP_oh, &oh->Handler); } else { oh->n = 0; oh->Handler = NULL; } } /* StoreIDs array pack/unpack */ #define PTP_sids 0 static inline void ptp_unpack_SIDs (PTPParams *params, unsigned char* data, PTPStorageIDs *sids, unsigned int len) { if (!data && !len) { sids->n = 0; sids->Storage = NULL; return; } sids->n = ptp_unpack_uint32_t_array(params, data, PTP_sids, &sids->Storage); } /* StorageInfo pack/unpack */ #define PTP_si_StorageType 0 #define PTP_si_FilesystemType 2 #define PTP_si_AccessCapability 4 #define PTP_si_MaxCapability 6 #define PTP_si_FreeSpaceInBytes 14 #define PTP_si_FreeSpaceInImages 22 #define PTP_si_StorageDescription 26 static inline void ptp_unpack_SI (PTPParams *params, unsigned char* data, PTPStorageInfo *si, unsigned int len) { uint8_t storagedescriptionlen; si->StorageType=dtoh16a(&data[PTP_si_StorageType]); si->FilesystemType=dtoh16a(&data[PTP_si_FilesystemType]); si->AccessCapability=dtoh16a(&data[PTP_si_AccessCapability]); si->MaxCapability=dtoh64a(&data[PTP_si_MaxCapability]); si->FreeSpaceInBytes=dtoh64a(&data[PTP_si_FreeSpaceInBytes]); si->FreeSpaceInImages=dtoh32a(&data[PTP_si_FreeSpaceInImages]); si->StorageDescription=ptp_unpack_string(params, data, PTP_si_StorageDescription, &storagedescriptionlen); si->VolumeLabel=ptp_unpack_string(params, data, PTP_si_StorageDescription+storagedescriptionlen*2+1, &storagedescriptionlen); } /* ObjectInfo pack/unpack */ #define PTP_oi_StorageID 0 #define PTP_oi_ObjectFormat 4 #define PTP_oi_ProtectionStatus 6 #define PTP_oi_ObjectCompressedSize 8 #define PTP_oi_ThumbFormat 12 #define PTP_oi_ThumbCompressedSize 14 #define PTP_oi_ThumbPixWidth 18 #define PTP_oi_ThumbPixHeight 22 #define PTP_oi_ImagePixWidth 26 #define PTP_oi_ImagePixHeight 30 #define PTP_oi_ImageBitDepth 34 #define PTP_oi_ParentObject 38 #define PTP_oi_AssociationType 42 #define PTP_oi_AssociationDesc 44 #define PTP_oi_SequenceNumber 48 #define PTP_oi_filenamelen 52 #define PTP_oi_Filename 53 /* the max length assuming zero length dates. We have need 3 */ /* bytes for these. */ #define PTP_oi_MaxLen PTP_oi_Filename+(PTP_MAXSTRLEN+1)*2+3 static inline uint32_t ptp_pack_OI (PTPParams *params, PTPObjectInfo *oi, unsigned char** oidataptr) { unsigned char* oidata; uint8_t filenamelen; uint8_t capturedatelen=0; /* let's allocate some memory first; correct assuming zero length dates */ oidata=malloc(PTP_oi_MaxLen + params->ocs64*4); *oidataptr=oidata; /* the caller should free it after use! */ #if 0 char *capture_date="20020101T010101"; /* XXX Fake date */ #endif memset (oidata, 0, PTP_oi_MaxLen + params->ocs64*4); htod32a(&oidata[PTP_oi_StorageID],oi->StorageID); htod16a(&oidata[PTP_oi_ObjectFormat],oi->ObjectFormat); htod16a(&oidata[PTP_oi_ProtectionStatus],oi->ProtectionStatus); htod32a(&oidata[PTP_oi_ObjectCompressedSize],oi->ObjectCompressedSize); if (params->ocs64) oidata += 4; htod16a(&oidata[PTP_oi_ThumbFormat],oi->ThumbFormat); htod32a(&oidata[PTP_oi_ThumbCompressedSize],oi->ThumbCompressedSize); htod32a(&oidata[PTP_oi_ThumbPixWidth],oi->ThumbPixWidth); htod32a(&oidata[PTP_oi_ThumbPixHeight],oi->ThumbPixHeight); htod32a(&oidata[PTP_oi_ImagePixWidth],oi->ImagePixWidth); htod32a(&oidata[PTP_oi_ImagePixHeight],oi->ImagePixHeight); htod32a(&oidata[PTP_oi_ImageBitDepth],oi->ImageBitDepth); htod32a(&oidata[PTP_oi_ParentObject],oi->ParentObject); htod16a(&oidata[PTP_oi_AssociationType],oi->AssociationType); htod32a(&oidata[PTP_oi_AssociationDesc],oi->AssociationDesc); htod32a(&oidata[PTP_oi_SequenceNumber],oi->SequenceNumber); ptp_pack_string(params, oi->Filename, oidata, PTP_oi_filenamelen, &filenamelen); /* filenamelen=(uint8_t)strlen(oi->Filename); htod8a(&req->data[PTP_oi_filenamelen],filenamelen+1); for (i=0;idata[PTP_oi_Filename+i*2]=oi->Filename[i]; } */ /* *XXX Fake date. * for example Kodak sets Capture date on the basis of EXIF data. * Spec says that this field is from perspective of Initiator. */ #if 0 /* seems now we don't need any data packed in OI dataset... for now ;)*/ capturedatelen=strlen(capture_date); htod8a(&data[PTP_oi_Filename+(filenamelen+1)*2], capturedatelen+1); for (i=0;iocs64*4; } static time_t ptp_unpack_PTPTIME (const char *str) { char ptpdate[40]; char tmp[5]; size_t ptpdatelen; struct tm tm; if (!str) return 0; ptpdatelen = strlen(str); if (ptpdatelen >= sizeof (ptpdate)) { /*ptp_debug (params ,"datelen is larger then size of buffer", ptpdatelen, (int)sizeof(ptpdate));*/ return 0; } if (ptpdatelen<15) { /*ptp_debug (params ,"datelen is less than 15 (%d)", ptpdatelen);*/ return 0; } strncpy (ptpdate, str, sizeof(ptpdate)); ptpdate[sizeof(ptpdate) - 1] = '\0'; memset(&tm,0,sizeof(tm)); strncpy (tmp, ptpdate, 4); tmp[4] = 0; tm.tm_year=atoi (tmp) - 1900; strncpy (tmp, ptpdate + 4, 2); tmp[2] = 0; tm.tm_mon = atoi (tmp) - 1; strncpy (tmp, ptpdate + 6, 2); tmp[2] = 0; tm.tm_mday = atoi (tmp); strncpy (tmp, ptpdate + 9, 2); tmp[2] = 0; tm.tm_hour = atoi (tmp); strncpy (tmp, ptpdate + 11, 2); tmp[2] = 0; tm.tm_min = atoi (tmp); strncpy (tmp, ptpdate + 13, 2); tmp[2] = 0; tm.tm_sec = atoi (tmp); tm.tm_isdst = -1; return mktime (&tm); } static inline void ptp_unpack_OI (PTPParams *params, unsigned char* data, PTPObjectInfo *oi, unsigned int len) { uint8_t filenamelen; uint8_t capturedatelen; char *capture_date; oi->StorageID=dtoh32a(&data[PTP_oi_StorageID]); oi->ObjectFormat=dtoh16a(&data[PTP_oi_ObjectFormat]); oi->ProtectionStatus=dtoh16a(&data[PTP_oi_ProtectionStatus]); oi->ObjectCompressedSize=dtoh32a(&data[PTP_oi_ObjectCompressedSize]); /* Stupid Samsung Galaxy developers emit a 64bit objectcompressedsize */ if ((data[PTP_oi_filenamelen] == 0) && (data[PTP_oi_filenamelen+4] != 0)) { params->ocs64 = 1; data += 4; } oi->ThumbFormat=dtoh16a(&data[PTP_oi_ThumbFormat]); oi->ThumbCompressedSize=dtoh32a(&data[PTP_oi_ThumbCompressedSize]); oi->ThumbPixWidth=dtoh32a(&data[PTP_oi_ThumbPixWidth]); oi->ThumbPixHeight=dtoh32a(&data[PTP_oi_ThumbPixHeight]); oi->ImagePixWidth=dtoh32a(&data[PTP_oi_ImagePixWidth]); oi->ImagePixHeight=dtoh32a(&data[PTP_oi_ImagePixHeight]); oi->ImageBitDepth=dtoh32a(&data[PTP_oi_ImageBitDepth]); oi->ParentObject=dtoh32a(&data[PTP_oi_ParentObject]); oi->AssociationType=dtoh16a(&data[PTP_oi_AssociationType]); oi->AssociationDesc=dtoh32a(&data[PTP_oi_AssociationDesc]); oi->SequenceNumber=dtoh32a(&data[PTP_oi_SequenceNumber]); oi->Filename= ptp_unpack_string(params, data, PTP_oi_filenamelen, &filenamelen); capture_date = ptp_unpack_string(params, data, PTP_oi_filenamelen+filenamelen*2+1, &capturedatelen); /* subset of ISO 8601, without '.s' tenths of second and * time zone */ oi->CaptureDate = ptp_unpack_PTPTIME(capture_date); free(capture_date); /* now the modification date ... */ capture_date = ptp_unpack_string(params, data, PTP_oi_filenamelen+filenamelen*2 +capturedatelen*2+2,&capturedatelen); oi->ModificationDate = ptp_unpack_PTPTIME(capture_date); free(capture_date); } /* Custom Type Value Assignement (without Length) macro frequently used below */ #define CTVAL(target,func) { \ if (total - *offset < sizeof(target)) \ return 0; \ target = func(&data[*offset]); \ *offset += sizeof(target); \ } #define RARR(val,member,func) { \ int n,j; \ if (total - *offset < sizeof(uint32_t)) \ return 0; \ n = dtoh32a (&data[*offset]); \ *offset += sizeof(uint32_t); \ \ val->a.count = n; \ val->a.v = malloc(sizeof(val->a.v[0])*n); \ if (!val->a.v) return 0; \ for (j=0;ja.v[j].member, func); \ } static inline int ptp_unpack_DPV ( PTPParams *params, unsigned char* data, int *offset, int total, PTPPropertyValue* value, uint16_t datatype ) { switch (datatype) { case PTP_DTC_INT8: CTVAL(value->i8,dtoh8a); break; case PTP_DTC_UINT8: CTVAL(value->u8,dtoh8a); break; case PTP_DTC_INT16: CTVAL(value->i16,dtoh16a); break; case PTP_DTC_UINT16: CTVAL(value->u16,dtoh16a); break; case PTP_DTC_INT32: CTVAL(value->i32,dtoh32a); break; case PTP_DTC_UINT32: CTVAL(value->u32,dtoh32a); break; case PTP_DTC_INT64: CTVAL(value->i64,dtoh64a); break; case PTP_DTC_UINT64: CTVAL(value->u64,dtoh64a); break; case PTP_DTC_UINT128: *offset += 16; /*fprintf(stderr,"unhandled unpack of uint128n");*/ break; case PTP_DTC_INT128: *offset += 16; /*fprintf(stderr,"unhandled unpack of int128n");*/ break; case PTP_DTC_AINT8: RARR(value,i8,dtoh8a); break; case PTP_DTC_AUINT8: RARR(value,u8,dtoh8a); break; case PTP_DTC_AUINT16: RARR(value,u16,dtoh16a); break; case PTP_DTC_AINT16: RARR(value,i16,dtoh16a); break; case PTP_DTC_AUINT32: RARR(value,u32,dtoh32a); break; case PTP_DTC_AINT32: RARR(value,i32,dtoh32a); break; case PTP_DTC_AUINT64: RARR(value,u64,dtoh64a); break; case PTP_DTC_AINT64: RARR(value,i64,dtoh64a); break; /* XXX: other int types are unimplemented */ /* XXX: other int arrays are unimplemented also */ case PTP_DTC_STR: { uint8_t len; /* XXX: max size */ value->str = ptp_unpack_string(params,data,*offset,&len); *offset += len*2+1; if (!value->str) return 1; break; } default: return 0; } return 1; } /* Device Property pack/unpack */ #define PTP_dpd_DevicePropertyCode 0 #define PTP_dpd_DataType 2 #define PTP_dpd_GetSet 4 #define PTP_dpd_FactoryDefaultValue 5 static inline int ptp_unpack_DPD (PTPParams *params, unsigned char* data, PTPDevicePropDesc *dpd, unsigned int dpdlen) { int offset=0, ret; memset (dpd, 0, sizeof(*dpd)); dpd->DevicePropertyCode=dtoh16a(&data[PTP_dpd_DevicePropertyCode]); dpd->DataType=dtoh16a(&data[PTP_dpd_DataType]); dpd->GetSet=dtoh8a(&data[PTP_dpd_GetSet]); dpd->FormFlag=PTP_DPFF_None; offset = PTP_dpd_FactoryDefaultValue; ret = ptp_unpack_DPV (params, data, &offset, dpdlen, &dpd->FactoryDefaultValue, dpd->DataType); if (!ret) goto outofmemory; if ((dpd->DataType == PTP_DTC_STR) && (offset == dpdlen)) return 1; ret = ptp_unpack_DPV (params, data, &offset, dpdlen, &dpd->CurrentValue, dpd->DataType); if (!ret) goto outofmemory; /* if offset==0 then Data Type format is not supported by this code or the Data Type is a string (with two empty strings as values). In both cases Form Flag should be set to 0x00 and FORM is not present. */ if (offset==PTP_dpd_FactoryDefaultValue) return 1; dpd->FormFlag=dtoh8a(&data[offset]); offset+=sizeof(uint8_t); switch (dpd->FormFlag) { case PTP_DPFF_Range: ret = ptp_unpack_DPV (params, data, &offset, dpdlen, &dpd->FORM.Range.MinimumValue, dpd->DataType); if (!ret) goto outofmemory; ret = ptp_unpack_DPV (params, data, &offset, dpdlen, &dpd->FORM.Range.MaximumValue, dpd->DataType); if (!ret) goto outofmemory; ret = ptp_unpack_DPV (params, data, &offset, dpdlen, &dpd->FORM.Range.StepSize, dpd->DataType); if (!ret) goto outofmemory; break; case PTP_DPFF_Enumeration: { int i; #define N dpd->FORM.Enum.NumberOfValues N = dtoh16a(&data[offset]); offset+=sizeof(uint16_t); dpd->FORM.Enum.SupportedValue = malloc(N*sizeof(dpd->FORM.Enum.SupportedValue[0])); if (!dpd->FORM.Enum.SupportedValue) goto outofmemory; memset (dpd->FORM.Enum.SupportedValue,0 , N*sizeof(dpd->FORM.Enum.SupportedValue[0])); for (i=0;iFORM.Enum.SupportedValue[i], dpd->DataType); /* Slightly different handling here. The HP PhotoSmart 120 * specifies an enumeration with N in wrong endian * 00 01 instead of 01 00, so we count the enum just until the * the end of the packet. */ if (!ret) { if (!i) goto outofmemory; dpd->FORM.Enum.NumberOfValues = i; break; } } } } #undef N return 1; outofmemory: ptp_free_devicepropdesc(dpd); return 0; } /* (MTP) Object Property pack/unpack */ #define PTP_opd_ObjectPropertyCode 0 #define PTP_opd_DataType 2 #define PTP_opd_GetSet 4 #define PTP_opd_FactoryDefaultValue 5 static inline int ptp_unpack_OPD (PTPParams *params, unsigned char* data, PTPObjectPropDesc *opd, unsigned int opdlen) { int offset=0, ret; memset (opd, 0, sizeof(*opd)); opd->ObjectPropertyCode=dtoh16a(&data[PTP_opd_ObjectPropertyCode]); opd->DataType=dtoh16a(&data[PTP_opd_DataType]); opd->GetSet=dtoh8a(&data[PTP_opd_GetSet]); offset = PTP_opd_FactoryDefaultValue; ret = ptp_unpack_DPV (params, data, &offset, opdlen, &opd->FactoryDefaultValue, opd->DataType); if (!ret) goto outofmemory; opd->GroupCode=dtoh32a(&data[offset]); offset+=sizeof(uint32_t); opd->FormFlag=dtoh8a(&data[offset]); offset+=sizeof(uint8_t); switch (opd->FormFlag) { case PTP_OPFF_Range: ret = ptp_unpack_DPV (params, data, &offset, opdlen, &opd->FORM.Range.MinimumValue, opd->DataType); if (!ret) goto outofmemory; ret = ptp_unpack_DPV (params, data, &offset, opdlen, &opd->FORM.Range.MaximumValue, opd->DataType); if (!ret) goto outofmemory; ret = ptp_unpack_DPV (params, data, &offset, opdlen, &opd->FORM.Range.StepSize, opd->DataType); if (!ret) goto outofmemory; break; case PTP_OPFF_Enumeration: { int i; #define N opd->FORM.Enum.NumberOfValues N = dtoh16a(&data[offset]); offset+=sizeof(uint16_t); opd->FORM.Enum.SupportedValue = malloc(N*sizeof(opd->FORM.Enum.SupportedValue[0])); if (!opd->FORM.Enum.SupportedValue) goto outofmemory; memset (opd->FORM.Enum.SupportedValue,0 , N*sizeof(opd->FORM.Enum.SupportedValue[0])); for (i=0;iFORM.Enum.SupportedValue[i], opd->DataType); /* Slightly different handling here. The HP PhotoSmart 120 * specifies an enumeration with N in wrong endian * 00 01 instead of 01 00, so we count the enum just until the * the end of the packet. */ if (!ret) { if (!i) goto outofmemory; opd->FORM.Enum.NumberOfValues = i; break; } } #undef N } } return 1; outofmemory: ptp_free_objectpropdesc(opd); return 0; } static inline uint32_t ptp_pack_DPV (PTPParams *params, PTPPropertyValue* value, unsigned char** dpvptr, uint16_t datatype) { unsigned char* dpv=NULL; uint32_t size=0; int i; switch (datatype) { case PTP_DTC_INT8: size=sizeof(int8_t); dpv=malloc(size); htod8a(dpv,value->i8); break; case PTP_DTC_UINT8: size=sizeof(uint8_t); dpv=malloc(size); htod8a(dpv,value->u8); break; case PTP_DTC_INT16: size=sizeof(int16_t); dpv=malloc(size); htod16a(dpv,value->i16); break; case PTP_DTC_UINT16: size=sizeof(uint16_t); dpv=malloc(size); htod16a(dpv,value->u16); break; case PTP_DTC_INT32: size=sizeof(int32_t); dpv=malloc(size); htod32a(dpv,value->i32); break; case PTP_DTC_UINT32: size=sizeof(uint32_t); dpv=malloc(size); htod32a(dpv,value->u32); break; case PTP_DTC_INT64: size=sizeof(int64_t); dpv=malloc(size); htod64a(dpv,value->i64); break; case PTP_DTC_UINT64: size=sizeof(uint64_t); dpv=malloc(size); htod64a(dpv,value->u64); break; case PTP_DTC_AUINT8: size=sizeof(uint32_t)+value->a.count*sizeof(uint8_t); dpv=malloc(size); htod32a(dpv,value->a.count); for (i=0;ia.count;i++) htod8a(&dpv[sizeof(uint32_t)+i*sizeof(uint8_t)],value->a.v[i].u8); break; case PTP_DTC_AINT8: size=sizeof(uint32_t)+value->a.count*sizeof(int8_t); dpv=malloc(size); htod32a(dpv,value->a.count); for (i=0;ia.count;i++) htod8a(&dpv[sizeof(uint32_t)+i*sizeof(int8_t)],value->a.v[i].i8); break; case PTP_DTC_AUINT16: size=sizeof(uint32_t)+value->a.count*sizeof(uint16_t); dpv=malloc(size); htod32a(dpv,value->a.count); for (i=0;ia.count;i++) htod16a(&dpv[sizeof(uint32_t)+i*sizeof(uint16_t)],value->a.v[i].u16); break; case PTP_DTC_AINT16: size=sizeof(uint32_t)+value->a.count*sizeof(int16_t); dpv=malloc(size); htod32a(dpv,value->a.count); for (i=0;ia.count;i++) htod16a(&dpv[sizeof(uint32_t)+i*sizeof(int16_t)],value->a.v[i].i16); break; case PTP_DTC_AUINT32: size=sizeof(uint32_t)+value->a.count*sizeof(uint32_t); dpv=malloc(size); htod32a(dpv,value->a.count); for (i=0;ia.count;i++) htod32a(&dpv[sizeof(uint32_t)+i*sizeof(uint32_t)],value->a.v[i].u32); break; case PTP_DTC_AINT32: size=sizeof(uint32_t)+value->a.count*sizeof(int32_t); dpv=malloc(size); htod32a(dpv,value->a.count); for (i=0;ia.count;i++) htod32a(&dpv[sizeof(uint32_t)+i*sizeof(int32_t)],value->a.v[i].i32); break; case PTP_DTC_AUINT64: size=sizeof(uint32_t)+value->a.count*sizeof(uint64_t); dpv=malloc(size); htod32a(dpv,value->a.count); for (i=0;ia.count;i++) htod64a(&dpv[sizeof(uint32_t)+i*sizeof(uint64_t)],value->a.v[i].u64); break; case PTP_DTC_AINT64: size=sizeof(uint32_t)+value->a.count*sizeof(int64_t); dpv=malloc(size); htod32a(dpv,value->a.count); for (i=0;ia.count;i++) htod64a(&dpv[sizeof(uint32_t)+i*sizeof(int64_t)],value->a.v[i].i64); break; /* XXX: other int types are unimplemented */ case PTP_DTC_STR: { dpv=ptp_get_packed_stringcopy(params, value->str, &size); break; } } *dpvptr=dpv; return size; } #define MAX_MTP_PROPS 127 static inline uint32_t ptp_pack_OPL (PTPParams *params, MTPProperties *props, int nrofprops, unsigned char** opldataptr) { unsigned char* opldata; MTPProperties *propitr; unsigned char *packedprops[MAX_MTP_PROPS]; uint32_t packedpropslens[MAX_MTP_PROPS]; uint32_t packedobjecthandles[MAX_MTP_PROPS]; uint16_t packedpropsids[MAX_MTP_PROPS]; uint16_t packedpropstypes[MAX_MTP_PROPS]; uint32_t totalsize = 0; uint32_t bufp = 0; uint32_t noitems = 0; uint32_t i; totalsize = sizeof(uint32_t); /* 4 bytes to store the number of elements */ propitr = props; while (nrofprops-- && noitems < MAX_MTP_PROPS) { /* Object Handle */ packedobjecthandles[noitems]=propitr->ObjectHandle; totalsize += sizeof(uint32_t); /* Object ID */ /* Metadata type */ packedpropsids[noitems]=propitr->property; totalsize += sizeof(uint16_t); /* Data type */ packedpropstypes[noitems]= propitr->datatype; totalsize += sizeof(uint16_t); /* Add each property to be sent. */ packedpropslens[noitems] = ptp_pack_DPV (params, &propitr->propval, &packedprops[noitems], propitr->datatype); totalsize += packedpropslens[noitems]; noitems ++; propitr ++; } /* Allocate memory for the packed property list */ opldata = malloc(totalsize); htod32a(&opldata[bufp],noitems); bufp += 4; /* Copy into a nice packed list */ for (i = 0; i < noitems; i++) { /* Object ID */ htod32a(&opldata[bufp],packedobjecthandles[i]); bufp += sizeof(uint32_t); htod16a(&opldata[bufp],packedpropsids[i]); bufp += sizeof(uint16_t); htod16a(&opldata[bufp],packedpropstypes[i]); bufp += sizeof(uint16_t); /* The copy the actual property */ memcpy(&opldata[bufp], packedprops[i], packedpropslens[i]); bufp += packedpropslens[i]; free(packedprops[i]); } *opldataptr = opldata; return totalsize; } static int _compare_func(const void* x, const void *y) { const MTPProperties *px = x; const MTPProperties *py = y; return px->ObjectHandle - py->ObjectHandle; } static inline int ptp_unpack_OPL (PTPParams *params, unsigned char* data, MTPProperties **pprops, unsigned int len) { uint32_t prop_count = dtoh32a(data); MTPProperties *props = NULL; int offset = 0, i; if (prop_count == 0) { *pprops = NULL; return 0; } ptp_debug (params ,"Unpacking MTP OPL, size %d (prop_count %d)", len, prop_count); data += sizeof(uint32_t); len -= sizeof(uint32_t); props = malloc(prop_count * sizeof(MTPProperties)); if (!props) return 0; for (i = 0; i < prop_count; i++) { if (len <= 0) { ptp_debug (params ,"short MTP Object Property List at property %d (of %d)", i, prop_count); ptp_debug (params ,"device probably needs DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL", i); ptp_debug (params ,"or even DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST", i); qsort (props, i, sizeof(MTPProperties),_compare_func); *pprops = props; return i; } props[i].ObjectHandle = dtoh32a(data); data += sizeof(uint32_t); len -= sizeof(uint32_t); props[i].property = dtoh16a(data); data += sizeof(uint16_t); len -= sizeof(uint16_t); props[i].datatype = dtoh16a(data); data += sizeof(uint16_t); len -= sizeof(uint16_t); offset = 0; ptp_unpack_DPV(params, data, &offset, len, &props[i].propval, props[i].datatype); data += offset; len -= offset; } qsort (props, prop_count, sizeof(MTPProperties),_compare_func); *pprops = props; return prop_count; } /* PTP USB Event container unpack Copyright (c) 2003 Nikolai Kopanygin */ #define PTP_ec_Length 0 #define PTP_ec_Type 4 #define PTP_ec_Code 6 #define PTP_ec_TransId 8 #define PTP_ec_Param1 12 #define PTP_ec_Param2 16 #define PTP_ec_Param3 20 static inline void ptp_unpack_EC (PTPParams *params, unsigned char* data, PTPContainer *ec, unsigned int len) { int length; int type; if (data==NULL) return; memset(ec,0,sizeof(*ec)); length=dtoh32a(&data[PTP_ec_Length]); type = dtoh16a(&data[PTP_ec_Type]); ec->Code=dtoh16a(&data[PTP_ec_Code]); ec->Transaction_ID=dtoh32a(&data[PTP_ec_TransId]); if (type!=PTP_USB_CONTAINER_EVENT) { ptp_debug (params, "Unknown canon event type %d (code=%x,tid=%x), please report!",type,ec->Code,ec->Transaction_ID); return; } if (length>=(PTP_ec_Param1+4)) { ec->Param1=dtoh32a(&data[PTP_ec_Param1]); ec->Nparam=1; } if (length>=(PTP_ec_Param2+4)) { ec->Param2=dtoh32a(&data[PTP_ec_Param2]); ec->Nparam=2; } if (length>=(PTP_ec_Param3+4)) { ec->Param3=dtoh32a(&data[PTP_ec_Param3]); ec->Nparam=3; } } /* PTP Canon Folder Entry unpack Copyright (c) 2003 Nikolai Kopanygin */ #define PTP_cfe_ObjectHandle 0 #define PTP_cfe_ObjectFormatCode 4 #define PTP_cfe_Flags 6 #define PTP_cfe_ObjectSize 7 #define PTP_cfe_Time 11 #define PTP_cfe_Filename 15 static inline void ptp_unpack_Canon_FE (PTPParams *params, unsigned char* data, PTPCANONFolderEntry *fe) { int i; if (data==NULL) return; fe->ObjectHandle=dtoh32a(&data[PTP_cfe_ObjectHandle]); fe->ObjectFormatCode=dtoh16a(&data[PTP_cfe_ObjectFormatCode]); fe->Flags=dtoh8a(&data[PTP_cfe_Flags]); fe->ObjectSize=dtoh32a((unsigned char*)&data[PTP_cfe_ObjectSize]); fe->Time=(time_t)dtoh32a(&data[PTP_cfe_Time]); for (i=0; iFilename[i]=(char)dtoh8a(&data[PTP_cfe_Filename+i]); } /* PTP Canon EOS Folder Entry unpack 0: 00 00 08 a0 objectid 4: 01 00 02 00 storageid 8: 01 30 00 00 ofc 12: 01 00 14: 00 00 16: 11 00 00 00 20: 00 00 00 00 24: 00 00 00 80 28: 00 00 08 a0 32: 4d 49 53 43-00 00 00 00 00 00 00 00 name 00 00 00 00 84 bc 74 46 objectime (normal PTP GetObjectInfo) ObjectInfo for 'IMG_0199.JPG': Object ID: 0x92740c72 StorageID: 0x00020001 ObjectFormat: 0x3801 ProtectionStatus: 0x0000 ObjectCompressedSize: 2217241 ThumbFormat: 0x3808 ThumbCompressedSize: 5122 ThumbPixWidth: 160 ThumbPixHeight: 120 ImagePixWidth: 4000 ImagePixHeight: 3000 ImageBitDepth: 24 ParentObject: 0x92740000 AssociationType: 0x0000 AssociationDesc: 0x00000000 SequenceNumber: 0x00000000 ModificationDate: 0x4d985ff0 CaptureDate: 0x4d985ff0 0010 38 00 00 00 Size of this entry 0014 72 0c 74 92 OID 0018 01 00 02 00 StorageID 001c 01 38 00 00 OFC 0020 00 00 00 00 00 00 00 00 ? 0028 19 d5 21 00 Size 002c 00 00 74 92 ? 0030 70 0c 74 92 OID 0034 49 4d 47 5f-30 31 39 39 2e 4a 50 47 IMG_0199.JPG 0040 00 00 00 00 0044 10 7c 98 4d Time */ #define PTP_cefe_ObjectHandle 0 #define PTP_cefe_StorageID 4 #define PTP_cefe_ObjectFormatCode 8 #define PTP_cefe_Flags 12 #define PTP_cefe_ObjectSize 20 #define PTP_cefe_Filename 32 #define PTP_cefe_Time 48 static inline void ptp_unpack_Canon_EOS_FE (PTPParams *params, unsigned char* data, PTPCANONFolderEntry *fe) { int i; fe->ObjectHandle=dtoh32a(&data[PTP_cefe_ObjectHandle]); fe->ObjectFormatCode=dtoh16a(&data[PTP_cefe_ObjectFormatCode]); fe->Flags=dtoh8a(&data[PTP_cefe_Flags]); fe->ObjectSize=dtoh32a((unsigned char*)&data[PTP_cefe_ObjectSize]); fe->Time=(time_t)dtoh32a(&data[PTP_cefe_Time]); for (i=0; iFilename[i]=(char)data[PTP_cefe_Filename+i]; } static inline uint16_t ptp_unpack_EOS_ImageFormat (PTPParams* params, unsigned char** data ) { /* EOS ImageFormat entries (of at least the 5DM2 and the 400D) look like this: uint32: number of entries / generated files (1 or 2) uint32: size of this entry in bytes (most likely allways 0x10) uint32: image type (1 == JPG, 6 == RAW) uint32: image size (0 == Large, 1 == Medium, 2 == Small, 0xe == S1, 0xf == S2, 0x10 == S3) uint32: image compression (2 == Standard/JPG, 3 == Fine/JPG, 4 == Lossles/RAW) If the number of entries is 2 the last 4 uint32 repeat. example: 0: 0x 1 1: 0x 10 2: 0x 6 3: 0x 1 4: 0x 4 The idea is to simply 'condense' these values to just one uint16 to be able to conveniently use the available enumeration facilities (look-up table). The image size and compression values fully describe the image format. Hence we generate a uint16 with the four nibles set as follows: entry 1 size | entry 1 compression | entry 2 size | entry 2 compression. The above example would result in the value 0x1400. The EOS 5D Mark III (and possibly other high-end EOS as well) added the extra fancy S1, S2 and S3 JPEG options. S1 replaces the old Small. -1 the S1/S2/S3 to prevent the 0x10 overflow. */ const unsigned char* d = *data; uint32_t n = dtoh32a( d ); uint32_t l, s1, c1, s2 = 0, c2 = 0; if (n != 1 && n !=2) { ptp_debug (params, "parsing EOS ImageFormat property failed (n != 1 && n != 2: %d)", n); return 0; } l = dtoh32a( d+=4 ); if (l != 0x10) { ptp_debug (params, "parsing EOS ImageFormat property failed (l != 0x10: 0x%x)", l); return 0; } d+=4; /* skip type */ s1 = dtoh32a( d+=4 ); c1 = dtoh32a( d+=4 ); if (n == 2) { l = dtoh32a( d+=4 ); if (l != 0x10) { ptp_debug (params, "parsing EOS ImageFormat property failed (l != 0x10: 0x%x)", l); return 0; } d+=4; /* skip type */ s2 = dtoh32a( d+=4 ); c2 = dtoh32a( d+=4 ); } *data = (unsigned char*) d+4; /* deal with S1/S2/S3 JPEG sizes, see above. */ if( s1 >= 0xe ) s1--; if( s2 >= 0xe ) s2--; return ((s1 & 0xF) << 12) | ((c1 & 0xF) << 8) | ((s2 & 0xF) << 4) | ((c2 & 0xF) << 0); } static inline uint32_t ptp_pack_EOS_ImageFormat (PTPParams* params, unsigned char* data, uint16_t value) { uint32_t n = (value & 0xFF) ? 2 : 1; uint32_t s = 4 + 0x10 * n; if( !data ) return s; #define PACK_5DM3_SMALL_JPEG_SIZE( X ) (X) >= 0xd ? (X)+1 : (X) htod32a(data+=0, n); htod32a(data+=4, 0x10); htod32a(data+=4, ((value >> 8) & 0xF) == 4 ? 6 : 1); htod32a(data+=4, PACK_5DM3_SMALL_JPEG_SIZE((value >> 12) & 0xF)); htod32a(data+=4, (value >> 8) & 0xF); if (n==2) { htod32a(data+=4, 0x10); htod32a(data+=4, ((value >> 0) & 0xF) == 4 ? 6 : 1); htod32a(data+=4, PACK_5DM3_SMALL_JPEG_SIZE((value >> 4) & 0xF)); htod32a(data+=4, (value >> 0) & 0xF); } #undef PACK_5DM3_SMALL_JPEG_SIZE return s; } static inline char* ptp_unpack_EOS_CustomFuncEx (PTPParams* params, unsigned char** data ) { uint32_t s = dtoh32a( *data ); uint32_t n = s/4, i; char* str = (char*)malloc( s ); /* n is size in uint32, average len(itoa(i)) < 4 -> alloc n chars */ if (!str) return str; char* p = str; for (i=0; i < n; ++i) p += sprintf(p, "%x,", dtoh32a( *data + 4*i )); return str; } static inline uint32_t ptp_pack_EOS_CustomFuncEx (PTPParams* params, unsigned char* data, char* str) { uint32_t s = strtoul(str, NULL, 16); uint32_t n = s/4, i, v; if (!data) return s; for (i=0; inrofcanon_props;j++) if (params->canon_props[j].proptype == proptype) break; if (j==params->nrofcanon_props) { ptp_debug (params, "event %d: propdesc %x, default value not found.", i, proptype); break; } dpd = ¶ms->canon_props[j].dpd; /* 1 - uint16 ? * 3 - uint16 * 7 - string? */ if (propxtype != 3) { ptp_debug (params, "event %d: propxtype is %x for %04x, unhandled.", i, propxtype, proptype); for (j=0;jDataType, propxcnt); dpd->FormFlag = PTP_DPFF_Enumeration; dpd->FORM.Enum.NumberOfValues = propxcnt; if (dpd->FORM.Enum.SupportedValue) free (dpd->FORM.Enum.SupportedValue); dpd->FORM.Enum.SupportedValue = malloc (sizeof (PTPPropertyValue)*propxcnt); switch (proptype) { case PTP_DPC_CANON_EOS_ImageFormat: case PTP_DPC_CANON_EOS_ImageFormatCF: case PTP_DPC_CANON_EOS_ImageFormatSD: case PTP_DPC_CANON_EOS_ImageFormatExtHD: /* special handling of ImageFormat properties */ for (j=0;jFORM.Enum.SupportedValue[j].u16 = dtoh16( ptp_unpack_EOS_ImageFormat( params, &xdata ) ); ptp_debug (params, "event %d: suppval[%d] of %x is 0x%x.", i, j, proptype, dpd->FORM.Enum.SupportedValue[j].u16); } break; default: /* 'normal' enumerated types */ switch (dpd->DataType) { #define XX( TYPE, CONV )\ for (j=0;jFORM.Enum.SupportedValue[j].TYPE = CONV(xdata); \ ptp_debug (params, "event %d: suppval[%d] of %x is 0x%x.", i, j, proptype, CONV(xdata)); \ xdata += 4; /* might only be for propxtype 3 */ \ } \ break; case PTP_DTC_INT16: XX( i16, dtoh16a ); case PTP_DTC_UINT32: XX( u32, dtoh32a ); case PTP_DTC_UINT16: XX( u16, dtoh16a ); case PTP_DTC_UINT8: XX( u8, dtoh8a ); #undef XX default: ptp_debug (params ,"event %d: data type 0x%04x of %x unhandled, raw values:", i, dpd->DataType, proptype, dtoh32a(xdata)); for (j=0;j<(size-PTP_ece_Prop_Desc_Data)/4;j++, xdata+=4) /* 4 is good for propxtype 3 */ ptp_debug (params, " %3d: 0x%8x", j, dtoh32a(xdata)); break; } } break; } case PTP_EC_CANON_EOS_PropValueChanged: if (size >= 0xc) { /* property info */ int j; uint32_t proptype = dtoh32a(&curdata[PTP_ece_Prop_Subtype]); unsigned char *xdata = &curdata[PTP_ece_Prop_Val_Data]; PTPDevicePropDesc *dpd; ptp_debug (params, "event %d: EOS prop %04x info record, datasize is %d", i, proptype, size-PTP_ece_Prop_Val_Data); for (j=0;jnrofcanon_props;j++) if (params->canon_props[j].proptype == proptype) break; if (jnrofcanon_props) { if ( (params->canon_props[j].size != size) || (memcmp(params->canon_props[j].data,xdata,size-PTP_ece_Prop_Val_Data))) { params->canon_props[j].data = realloc(params->canon_props[j].data,size-PTP_ece_Prop_Val_Data); memcpy (params->canon_props[j].data,xdata,size-PTP_ece_Prop_Val_Data); } } else { if (j) params->canon_props = realloc(params->canon_props, sizeof(params->canon_props[0])*(j+1)); else params->canon_props = malloc(sizeof(params->canon_props[0])); params->canon_props[j].type = type; params->canon_props[j].proptype = proptype; params->canon_props[j].size = size; params->canon_props[j].data = malloc(size-PTP_ece_Prop_Val_Data); memcpy(params->canon_props[j].data, xdata, size-PTP_ece_Prop_Val_Data); memset (¶ms->canon_props[j].dpd,0,sizeof(params->canon_props[j].dpd)); params->canon_props[j].dpd.GetSet = 1; params->canon_props[j].dpd.FormFlag = PTP_DPFF_None; params->nrofcanon_props = j+1; } dpd = ¶ms->canon_props[j].dpd; (*ce)[i].type = PTP_CANON_EOS_CHANGES_TYPE_PROPERTY; (*ce)[i].u.propid = proptype; /* fix GetSet value */ switch (proptype) { #define XX(x) case PTP_DPC_CANON_##x: XX(EOS_FocusMode) XX(EOS_BatteryPower) XX(EOS_BatterySelect) XX(EOS_ModelID) XX(EOS_PTPExtensionVersion) XX(EOS_DPOFVersion) XX(EOS_AvailableShots) XX(EOS_CurrentStorage) XX(EOS_CurrentFolder) XX(EOS_MyMenu) XX(EOS_MyMenuList) XX(EOS_HDDirectoryStructure) XX(EOS_BatteryInfo) XX(EOS_AdapterInfo) XX(EOS_LensStatus) XX(EOS_CardExtension) XX(EOS_TempStatus) XX(EOS_ShutterCounter) XX(EOS_SerialNumber) XX(EOS_DepthOfFieldPreview) XX(EOS_EVFRecordStatus) XX(EOS_LvAfSystem) XX(EOS_FocusInfoEx) XX(EOS_DepthOfField) XX(EOS_Brightness) XX(EOS_EFComp) XX(EOS_LensName) XX(EOS_LensID) #undef XX dpd->GetSet = PTP_DPGS_Get; break; } /* set DataType */ switch (proptype) { case PTP_DPC_CANON_EOS_CameraTime: case PTP_DPC_CANON_EOS_AvailableShots: case PTP_DPC_CANON_EOS_CaptureDestination: case PTP_DPC_CANON_EOS_WhiteBalanceXA: case PTP_DPC_CANON_EOS_WhiteBalanceXB: case PTP_DPC_CANON_EOS_CurrentStorage: case PTP_DPC_CANON_EOS_CurrentFolder: case PTP_DPC_CANON_EOS_ShutterCounter: case PTP_DPC_CANON_EOS_ModelID: case PTP_DPC_CANON_EOS_LensID: case PTP_DPC_CANON_EOS_StroboFiring: dpd->DataType = PTP_DTC_UINT32; break; /* enumeration for AEM is never provided, but is available to set */ case PTP_DPC_CANON_EOS_AutoExposureMode: dpd->DataType = PTP_DTC_UINT16; dpd->FormFlag = PTP_DPFF_Enumeration; dpd->FORM.Enum.NumberOfValues = 0; break; case PTP_DPC_CANON_EOS_Aperture: case PTP_DPC_CANON_EOS_ShutterSpeed: case PTP_DPC_CANON_EOS_ISOSpeed: case PTP_DPC_CANON_EOS_FocusMode: case PTP_DPC_CANON_EOS_ColorSpace: case PTP_DPC_CANON_EOS_BatteryPower: case PTP_DPC_CANON_EOS_BatterySelect: case PTP_DPC_CANON_EOS_PTPExtensionVersion: case PTP_DPC_CANON_EOS_DriveMode: case PTP_DPC_CANON_EOS_AEB: case PTP_DPC_CANON_EOS_BracketMode: case PTP_DPC_CANON_EOS_QuickReviewTime: case PTP_DPC_CANON_EOS_EVFMode: case PTP_DPC_CANON_EOS_EVFOutputDevice: case PTP_DPC_CANON_EOS_AutoPowerOff: dpd->DataType = PTP_DTC_UINT16; break; case PTP_DPC_CANON_EOS_PictureStyle: case PTP_DPC_CANON_EOS_WhiteBalance: case PTP_DPC_CANON_EOS_MeteringMode: case PTP_DPC_CANON_EOS_ExpCompensation: /* actually int8 if you calculate */ dpd->DataType = PTP_DTC_UINT8; break; case PTP_DPC_CANON_EOS_Owner: case PTP_DPC_CANON_EOS_Artist: case PTP_DPC_CANON_EOS_Copyright: case PTP_DPC_CANON_EOS_SerialNumber: case PTP_DPC_CANON_EOS_LensName: dpd->DataType = PTP_DTC_STR; break; case PTP_DPC_CANON_EOS_WhiteBalanceAdjustA: case PTP_DPC_CANON_EOS_WhiteBalanceAdjustB: dpd->DataType = PTP_DTC_INT16; break; /* unknown props, listed from dump.... all 16 bit, but vals might be smaller */ case PTP_DPC_CANON_EOS_DPOFVersion: dpd->DataType = PTP_DTC_UINT16; ptp_debug (params, "event %d: Unknown EOS property %04x, datasize is %d, using uint16", i ,proptype, size-PTP_ece_Prop_Val_Data); for (j=0;jDataType = PTP_DTC_UINT8; ptp_debug (params, "event %d: Unknown EOS property %04x, datasize is %d, using uint8", i ,proptype, size-PTP_ece_Prop_Val_Data); for (j=0;jDataType = PTP_DTC_UINT32; ptp_debug (params, "event %d: Unknown EOS property %04x, datasize is %d, using uint32", i ,proptype, size-PTP_ece_Prop_Val_Data); if ((size-PTP_ece_Prop_Val_Data) % sizeof(uint32_t) != 0) ptp_debug (params, "event %d: Warning: datasize modulo sizeof(uint32) is not 0: ", i, (size-PTP_ece_Prop_Val_Data) % sizeof(uint32_t) ); for (j=0;j<(size-PTP_ece_Prop_Val_Data)/sizeof(uint32_t);j++) ptp_debug (params, " %d: 0x%8x", j, ((uint32_t*)xdata)[j]); break; /* ImageFormat properties have to be ignored here, see special handling below */ case PTP_DPC_CANON_EOS_ImageFormat: case PTP_DPC_CANON_EOS_ImageFormatCF: case PTP_DPC_CANON_EOS_ImageFormatSD: case PTP_DPC_CANON_EOS_ImageFormatExtHD: case PTP_DPC_CANON_EOS_CustomFuncEx: break; default: ptp_debug (params, "event %d: Unknown EOS property %04x, datasize is %d", i ,proptype, size-PTP_ece_Prop_Val_Data); for (j=0;jDataType) { case PTP_DTC_UINT32: dpd->FactoryDefaultValue.u32 = dtoh32a(xdata); dpd->CurrentValue.u32 = dtoh32a(xdata); ptp_debug (params ,"event %d: currentvalue of %x is %x", i, proptype, dpd->CurrentValue.u32); break; case PTP_DTC_UINT16: dpd->FactoryDefaultValue.u16 = dtoh16a(xdata); dpd->CurrentValue.u16 = dtoh16a(xdata); ptp_debug (params,"event %d: currentvalue of %x is %x", i, proptype, dpd->CurrentValue.u16); break; case PTP_DTC_UINT8: dpd->FactoryDefaultValue.u8 = dtoh8a(xdata); dpd->CurrentValue.u8 = dtoh8a(xdata); ptp_debug (params,"event %d: currentvalue of %x is %x", i, proptype, dpd->CurrentValue.u8); break; case PTP_DTC_STR: { #if 0 /* 5D MII and 400D aktually store plain ASCII in their string properties */ uint8_t len = 0; dpd->FactoryDefaultValue.str = ptp_unpack_string(params, data, 0, &len); dpd->CurrentValue.str = ptp_unpack_string(params, data, 0, &len); #else if (dpd->FactoryDefaultValue.str) free (dpd->FactoryDefaultValue.str); dpd->FactoryDefaultValue.str = strdup( (char*)xdata ); if (dpd->CurrentValue.str) free (dpd->CurrentValue.str); dpd->CurrentValue.str = strdup( (char*)xdata ); #endif ptp_debug (params,"event %d: currentvalue of %x is %s", i, proptype, dpd->CurrentValue.str); break; } default: /* debug is printed in switch above this one */ break; } /* ImageFormat and customFuncEx special handling (WARNING: dont move this in front of the dpd->DataType switch!) */ switch (proptype) { case PTP_DPC_CANON_EOS_ImageFormat: case PTP_DPC_CANON_EOS_ImageFormatCF: case PTP_DPC_CANON_EOS_ImageFormatSD: case PTP_DPC_CANON_EOS_ImageFormatExtHD: dpd->DataType = PTP_DTC_UINT16; dpd->FactoryDefaultValue.u16 = ptp_unpack_EOS_ImageFormat( params, &xdata ); dpd->CurrentValue.u16 = dpd->FactoryDefaultValue.u16; ptp_debug (params,"event %d: decoded imageformat, currentvalue of %x is %x", i, proptype, dpd->CurrentValue.u16); break; case PTP_DPC_CANON_EOS_CustomFuncEx: dpd->DataType = PTP_DTC_STR; if (dpd->FactoryDefaultValue.str) free (dpd->FactoryDefaultValue.str); if (dpd->CurrentValue.str) free (dpd->CurrentValue.str); dpd->FactoryDefaultValue.str = ptp_unpack_EOS_CustomFuncEx( params, &data ); dpd->CurrentValue.str = strdup( (char*)dpd->FactoryDefaultValue.str ); ptp_debug (params,"event %d: decoded custom function, currentvalue of %x is %s", i, proptype, dpd->CurrentValue.str); break; } break; } case PTP_EC_CANON_EOS_CameraStatusChanged: ptp_debug (params, "event %d: EOS event CameraStatusChanged (size %d)", i, size); (*ce)[i].type = PTP_CANON_EOS_CHANGES_TYPE_CAMERASTATUS; (*ce)[i].u.status = dtoh32a(curdata+8); params->eos_camerastatus = dtoh32a(curdata+8); break; case 0: /* end marker */ if (size == 8) /* no output */ break; ptp_debug (params, "event %d: EOS event 0, but size %d", i, size); break; case PTP_EC_CANON_EOS_BulbExposureTime: (*ce)[i].type = PTP_CANON_EOS_CHANGES_TYPE_UNKNOWN; (*ce)[i].u.info = malloc(strlen("BulbExposureTime 123456789")); sprintf ((*ce)[i].u.info, "BulbExposureTime %d", dtoh32a(curdata+8)); break; default: switch (type) { #define XX(x) case PTP_EC_CANON_EOS_##x: \ ptp_debug (params, "event %d: unhandled EOS event "#x" (size %d)", i, size); \ (*ce)[i].u.info = malloc(strlen("unhandled EOS event "#x" (size 123456789)")); \ sprintf ((*ce)[i].u.info, "unhandled EOS event "#x" (size %d)", size); \ break; XX(RequestGetEvent) XX(ObjectRemoved) XX(RequestGetObjectInfoEx) XX(StorageStatusChanged) XX(StorageInfoChanged) XX(ObjectInfoChangedEx) XX(ObjectContentChanged) XX(WillSoonShutdown) XX(ShutdownTimerUpdated) XX(RequestCancelTransfer) XX(RequestObjectTransferDT) XX(RequestCancelTransferDT) XX(StoreAdded) XX(StoreRemoved) XX(BulbExposureTime) XX(RecordingTime) XX(RequestObjectTransferTS) XX(AfResult) #undef XX default: ptp_debug (params, "event %d: unknown EOS event %04x", i, type); break; } if (size >= 0x8) { /* event info */ int j; for (j=8;j (len-PTP_nikon_ec_Code)/PTP_nikon_ec_Size) /* broken cnt? */ return; if (!*cnt) return; *ec = malloc(sizeof(PTPContainer)*(*cnt)); for (i=0;i<*cnt;i++) { memset(&(*ec)[i],0,sizeof(PTPContainer)); (*ec)[i].Code = dtoh16a(&data[PTP_nikon_ec_Code+PTP_nikon_ec_Size*i]); (*ec)[i].Param1 = dtoh32a(&data[PTP_nikon_ec_Param1+PTP_nikon_ec_Size*i]); (*ec)[i].Nparam = 1; } } static inline uint32_t ptp_pack_EK_text(PTPParams *params, PTPEKTextParams *text, unsigned char **data) { int i, len = 0; uint8_t retlen; unsigned char *curdata; len = 2*(strlen(text->title)+1)+1+ 2*(strlen(text->line[0])+1)+1+ 2*(strlen(text->line[1])+1)+1+ 2*(strlen(text->line[2])+1)+1+ 2*(strlen(text->line[3])+1)+1+ 2*(strlen(text->line[4])+1)+1+ 4*2+2*4+2+4+2+5*4*2; *data = malloc(len); if (!*data) return 0; curdata = *data; htod16a(curdata,100);curdata+=2; htod16a(curdata,1);curdata+=2; htod16a(curdata,0);curdata+=2; htod16a(curdata,1000);curdata+=2; htod32a(curdata,0);curdata+=4; htod32a(curdata,0);curdata+=4; htod16a(curdata,6);curdata+=2; htod32a(curdata,0);curdata+=4; ptp_pack_string(params, text->title, curdata, 0, &retlen); curdata+=2*retlen+1;htod16a(curdata,0);curdata+=2; htod16a(curdata,0x10);curdata+=2; for (i=0;i<5;i++) { ptp_pack_string(params, text->line[i], curdata, 0, &retlen); curdata+=2*retlen+1;htod16a(curdata,0);curdata+=2; htod16a(curdata,0x10);curdata+=2; htod16a(curdata,0x01);curdata+=2; htod16a(curdata,0x02);curdata+=2; htod16a(curdata,0x06);curdata+=2; } return len; } #define ptp_canon_dir_version 0x00 #define ptp_canon_dir_ofc 0x02 #define ptp_canon_dir_unk1 0x04 #define ptp_canon_dir_objectid 0x08 #define ptp_canon_dir_parentid 0x0c #define ptp_canon_dir_previd 0x10 /* in same dir */ #define ptp_canon_dir_nextid 0x14 /* in same dir */ #define ptp_canon_dir_nextchild 0x18 /* down one dir */ #define ptp_canon_dir_storageid 0x1c /* only in storage entry */ #define ptp_canon_dir_name 0x20 #define ptp_canon_dir_flags 0x2c #define ptp_canon_dir_size 0x30 #define ptp_canon_dir_unixtime 0x34 #define ptp_canon_dir_year 0x38 #define ptp_canon_dir_month 0x39 #define ptp_canon_dir_mday 0x3a #define ptp_canon_dir_hour 0x3b #define ptp_canon_dir_minute 0x3c #define ptp_canon_dir_second 0x3d #define ptp_canon_dir_unk2 0x3e #define ptp_canon_dir_thumbsize 0x40 #define ptp_canon_dir_width 0x44 #define ptp_canon_dir_height 0x48 static inline uint16_t ptp_unpack_canon_directory ( PTPParams *params, unsigned char *dir, uint32_t cnt, PTPObjectHandles *handles, PTPObjectInfo **oinfos, /* size(handles->n) */ uint32_t **flags /* size(handles->n) */ ) { unsigned int i, j, nrofobs = 0, curob = 0; #define ISOBJECT(ptr) (dtoh32a((ptr)+ptp_canon_dir_storageid) == 0xffffffff) for (i=0;in = nrofobs; handles->Handler = calloc(sizeof(handles->Handler[0]),nrofobs); if (!handles->Handler) return PTP_RC_GeneralError; *oinfos = calloc(sizeof((*oinfos)[0]),nrofobs); if (!*oinfos) return PTP_RC_GeneralError; *flags = calloc(sizeof((*flags)[0]),nrofobs); if (!*flags) return PTP_RC_GeneralError; /* Migrate data into objects ids, handles into * the object handler array. */ curob = 0; for (i=0;iHandler[curob] = dtoh32a(cur + ptp_canon_dir_objectid); oi->StorageID = 0xffffffff; oi->ObjectFormat = dtoh16a(cur + ptp_canon_dir_ofc); oi->ParentObject = dtoh32a(cur + ptp_canon_dir_parentid); oi->Filename = strdup((char*)(cur + ptp_canon_dir_name)); oi->ObjectCompressedSize= dtoh32a(cur + ptp_canon_dir_size); oi->ThumbCompressedSize = dtoh32a(cur + ptp_canon_dir_thumbsize); oi->ImagePixWidth = dtoh32a(cur + ptp_canon_dir_width); oi->ImagePixHeight = dtoh32a(cur + ptp_canon_dir_height); oi->CaptureDate = oi->ModificationDate = dtoh32a(cur + ptp_canon_dir_unixtime); (*flags)[curob] = dtoh32a(cur + ptp_canon_dir_flags); curob++; } /* Walk over Storage ID entries and distribute the IDs to * the parent objects. */ for (i=0;in;j++) if (nextchild == handles->Handler[j]) break; if (j == handles->n) continue; (*oinfos)[j].StorageID = dtoh32a(cur + ptp_canon_dir_storageid); } /* Walk over all objects and distribute the storage ids */ while (1) { int changed = 0; for (i=0;in;j++) if (oid == handles->Handler[j]) break; if (j == handles->n) { /*fprintf(stderr,"did not find oid in lookup pass for current oid\n");*/ continue; } storageid = (*oinfos)[j].StorageID; if (storageid == 0xffffffff) continue; if (nextoid != 0xffffffff) { for (j=0;jn;j++) if (nextoid == handles->Handler[j]) break; if (j == handles->n) { /*fprintf(stderr,"did not find oid in lookup pass for next oid\n");*/ continue; } if ((*oinfos)[j].StorageID == 0xffffffff) { (*oinfos)[j].StorageID = storageid; changed++; } } if (nextchild != 0xffffffff) { for (j=0;jn;j++) if (nextchild == handles->Handler[j]) break; if (j == handles->n) { /*fprintf(stderr,"did not find oid in lookup pass for next child\n");*/ continue; } if ((*oinfos)[j].StorageID == 0xffffffff) { (*oinfos)[j].StorageID = storageid; changed++; } } } /* Check if we: * - changed no entry (nothing more to do) * - changed all of them at once (usually happens) * break if we do. */ if (!changed || (changed==nrofobs-1)) break; } #undef ISOBJECT return PTP_RC_OK; } libmtp-1.1.6-20-g1b9f164/src/README0000664000175000017500000000131412205614637016360 0ustar glowwormglowwormRELATION TO LIBPTP2 ------------------- Parts of libptp2 are copied (and modified) from version 1.1.0: ptp-pack.c ptp-pack.h ptp.c ptp.h These are just copies of the same files from libptp2. In order to avoid clashes with the libptp2 endianness scripts we have named libptp-endian.h and libptp-stdint.h the same way as in libptp2, though they are created by libmtp autoconfigure scripts. We will try to track libptp2 and fold changes back into libmtp. TODO: check if the following still holds! (Linus) I have changed the config script slightly for the le64atoh function in libptp-endian.h. This is required for OS X on PowerPC (not sure why). I've just cast the bytes to uint64_t to avoid shifting wrongly. libmtp-1.1.6-20-g1b9f164/src/mtpz.h0000664000175000017500000000245712205614637016654 0ustar glowwormglowworm/** * \file mtpz.h * * Copyright (C) 2011-2012 Sajid Anwar * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * */ #ifndef MTPZ_H_INCLUSION_GUARD #define MTPZ_H_INCLUSION_GUARD #include "config.h" /* USE_MTPZ or not */ #include "ptp.h" /* PTPParams */ #ifdef USE_MTPZ uint16_t ptp_mtpz_handshake (PTPParams* params); int mtpz_loaddata(void); #else /* Stubs if mtpz is unused */ static inline uint16_t ptp_mtpz_handshake (PTPParams* params) { return PTP_RC_OperationNotSupported; } static inline int mtpz_loaddata(void) { return -1; } #endif int use_mtpz; #endif /* LIBMTP_H_INCLUSION_GUARD */ libmtp-1.1.6-20-g1b9f164/src/libusb-glue.c0000664000175000017500000017733712205614637020101 0ustar glowwormglowworm/* * \file libusb-glue.c * Low-level USB interface glue towards libusb. * * Copyright (C) 2005-2007 Richard A. Low * Copyright (C) 2005-2012 Linus Walleij * Copyright (C) 2006-2007 Marcus Meissner * Copyright (C) 2007 Ted Bullock * Copyright (C) 2008 Chris Bagwell * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Created by Richard Low on 24/12/2005. (as mtp-utils.c) * Modified by Linus Walleij 2006-03-06 * (Notice that Anglo-Saxons use little-endian dates and Swedes * use big-endian dates.) * */ #include "config.h" #include "libmtp.h" #include "libusb-glue.h" #include "device-flags.h" #include "util.h" #include "ptp.h" #include #include #include #include #include #include "ptp-pack.c" /* Aha, older libusb does not have USB_CLASS_PTP */ #ifndef USB_CLASS_PTP #define USB_CLASS_PTP 6 #endif /* * Default USB timeout length. This can be overridden as needed * but should start with a reasonable value so most common * requests can be completed. The original value of 4000 was * not long enough for large file transfer. Also, players can * spend a bit of time collecting data. Higher values also * make connecting/disconnecting more reliable. */ #define USB_TIMEOUT_DEFAULT 20000 #define USB_TIMEOUT_LONG 60000 static inline int get_timeout(PTP_USB* ptp_usb) { if (FLAG_LONG_TIMEOUT(ptp_usb)) { return USB_TIMEOUT_LONG; } return USB_TIMEOUT_DEFAULT; } /* USB control message data phase direction */ #ifndef USB_DP_HTD #define USB_DP_HTD (0x00 << 7) /* host to device */ #endif #ifndef USB_DP_DTH #define USB_DP_DTH (0x01 << 7) /* device to host */ #endif /* USB Feature selector HALT */ #ifndef USB_FEATURE_HALT #define USB_FEATURE_HALT 0x00 #endif /* Internal data types */ struct mtpdevice_list_struct { struct usb_device *libusb_device; PTPParams *params; PTP_USB *ptp_usb; uint32_t bus_location; struct mtpdevice_list_struct *next; }; typedef struct mtpdevice_list_struct mtpdevice_list_t; static const LIBMTP_device_entry_t mtp_device_table[] = { /* We include an .h file which is shared between us and libgphoto2 */ #include "music-players.h" }; static const int mtp_device_table_size = sizeof(mtp_device_table) / sizeof(LIBMTP_device_entry_t); // Local functions static struct usb_bus* init_usb(); static void close_usb(PTP_USB* ptp_usb); static int find_interface_and_endpoints(struct usb_device *dev, uint8_t *conf, uint8_t *interface, uint8_t *altsetting, int* inep, int* inep_maxpacket, int* outep, int* outep_maxpacket, int* intep); static void clear_stall(PTP_USB* ptp_usb); static int init_ptp_usb(PTPParams* params, PTP_USB* ptp_usb, struct usb_device* dev); static short ptp_write_func(unsigned long,PTPDataHandler*,void *data,unsigned long*); static short ptp_read_func(unsigned long,PTPDataHandler*,void *data,unsigned long*,int); static int usb_clear_stall_feature(PTP_USB* ptp_usb, int ep); static int usb_get_endpoint_status(PTP_USB* ptp_usb, int ep, uint16_t* status); /** * Get a list of the supported USB devices. * * The developers depend on users of this library to constantly * add in to the list of supported devices. What we need is the * device name, USB Vendor ID (VID) and USB Product ID (PID). * put this into a bug ticket at the project homepage, please. * The VID/PID is used to let e.g. udev lift the device to * console userspace access when it's plugged in. * * @param devices a pointer to a pointer that will hold a device * list after the call to this function, if it was * successful. * @param numdevs a pointer to an integer that will hold the number * of devices in the device list if the call was successful. * @return 0 if the list was successfull retrieved, any other * value means failure. */ int LIBMTP_Get_Supported_Devices_List(LIBMTP_device_entry_t ** const devices, int * const numdevs) { *devices = (LIBMTP_device_entry_t *) &mtp_device_table; *numdevs = mtp_device_table_size; return 0; } static struct usb_bus* init_usb() { struct usb_bus* busses; struct usb_bus* bus; /* * Some additional libusb debugging please. * We use the same level debug between MTP and USB. */ if ((LIBMTP_debug & LIBMTP_DEBUG_USB) != 0) usb_set_debug(9); usb_init(); usb_find_busses(); usb_find_devices(); /* Workaround a libusb 0.1 bug : bus location is not initialised */ busses = usb_get_busses(); for (bus = busses; bus != NULL; bus = bus->next) { if (!bus->location) bus->location = strtoul(bus->dirname, NULL, 10); } return (busses); } /** * Small recursive function to append a new usb_device to the linked list of * USB MTP devices * @param devlist dynamic linked list of pointers to usb devices with MTP * properties, to be extended with new device. * @param newdevice the new device to add. * @param bus_location bus for this device. * @return an extended array or NULL on failure. */ static mtpdevice_list_t *append_to_mtpdevice_list(mtpdevice_list_t *devlist, struct usb_device *newdevice, uint32_t bus_location) { mtpdevice_list_t *new_list_entry; new_list_entry = (mtpdevice_list_t *) malloc(sizeof(mtpdevice_list_t)); if (new_list_entry == NULL) { return NULL; } // Fill in USB device, if we *HAVE* to make a copy of the device do it here. new_list_entry->libusb_device = newdevice; new_list_entry->bus_location = bus_location; new_list_entry->next = NULL; if (devlist == NULL) { return new_list_entry; } else { mtpdevice_list_t *tmp = devlist; while (tmp->next != NULL) { tmp = tmp->next; } tmp->next = new_list_entry; } return devlist; } /** * Small recursive function to free dynamic memory allocated to the linked list * of USB MTP devices * @param devlist dynamic linked list of pointers to usb devices with MTP * properties. * @return nothing */ static void free_mtpdevice_list(mtpdevice_list_t *devlist) { mtpdevice_list_t *tmplist = devlist; if (devlist == NULL) return; while (tmplist != NULL) { mtpdevice_list_t *tmp = tmplist; tmplist = tmplist->next; // Do not free() the fields (ptp_usb, params)! These are used elsewhere. free(tmp); } return; } /** * This checks if a device has an MTP descriptor. The descriptor was * elaborated about in gPhoto bug 1482084, and some official documentation * with no strings attached was published by Microsoft at * http://www.microsoft.com/whdc/system/bus/USB/USBFAQ_intermed.mspx#E3HAC * * @param dev a device struct from libusb. * @param dumpfile set to non-NULL to make the descriptors dump out * to this file in human-readable hex so we can scruitinze them. * @return 1 if the device is MTP compliant, 0 if not. */ static int probe_device_descriptor(struct usb_device *dev, FILE *dumpfile) { usb_dev_handle *devh; unsigned char buf[1024], cmd; int i; int ret; /* This is to indicate if we find some vendor interface */ int found_vendor_spec_interface = 0; /* * Don't examine devices that are not likely to * contain any MTP interface, update this the day * you find some weird combination... */ if (!(dev->descriptor.bDeviceClass == USB_CLASS_PER_INTERFACE || dev->descriptor.bDeviceClass == USB_CLASS_COMM || dev->descriptor.bDeviceClass == USB_CLASS_PTP || dev->descriptor.bDeviceClass == 0xEF || /* Intf. Association Desc.*/ dev->descriptor.bDeviceClass == USB_CLASS_VENDOR_SPEC)) { return 0; } /* Attempt to open Device on this port */ devh = usb_open(dev); if (devh == NULL) { /* Could not open this device */ return 0; } /* * This sometimes crashes on the j for loop below * I think it is because config is NULL yet * dev->descriptor.bNumConfigurations > 0 * this check should stop this */ if (dev->config) { /* * Loop over the device configurations and interfaces. Nokia MTP-capable * handsets (possibly others) typically have the string "MTP" in their * MTP interface descriptions, that's how they can be detected, before * we try the more esoteric "OS descriptors" (below). */ for (i = 0; i < dev->descriptor.bNumConfigurations; i++) { uint8_t j; for (j = 0; j < dev->config[i].bNumInterfaces; j++) { int k; for (k = 0; k < dev->config[i].interface[j].num_altsetting; k++) { /* Current interface descriptor */ struct usb_interface_descriptor *intf = &dev->config[i].interface[j].altsetting[k]; /* * MTP interfaces have three endpoints, two bulk and one * interrupt. Don't probe anything else. */ if (intf->bNumEndpoints != 3) continue; /* * We only want to probe for the OS descriptor if the * device is USB_CLASS_VENDOR_SPEC or one of the interfaces * in it is, so flag if we find an interface like this. */ if (intf->bInterfaceClass == USB_CLASS_VENDOR_SPEC) { found_vendor_spec_interface = 1; } /* * Check for Still Image Capture class with PIMA 15740 protocol, * also known as PTP */ #if 0 if (intf->bInterfaceClass == USB_CLASS_PTP && intf->bInterfaceSubClass == 0x01 && intf->bInterfaceProtocol == 0x01) { if (dumpfile != NULL) { fprintf(dumpfile, " Found PTP device, check vendor " "extension...\n"); } // This is where we may insert code to open a PTP // session and query the vendor extension ID to see // if it is 0xffffffff, i.e. MTP according to the spec. if (was_mtp_extension) { usb_close(devh); return 1; } } #endif /* * Next we search for the MTP substring in the interface name. * For example : "RIM MS/MTP" should work. */ buf[0] = '\0'; ret = usb_get_string_simple(devh, dev->config[i].interface[j].altsetting[k].iInterface, (char *) buf, 1024); if (ret < 3) continue; if (strstr((char *) buf, "MTP") != NULL) { if (dumpfile != NULL) { fprintf(dumpfile, "Configuration %d, interface %d, altsetting %d:\n", i, j, k); fprintf(dumpfile, " Interface description contains the string \"MTP\"\n"); fprintf(dumpfile, " Device recognized as MTP, no further probing.\n"); } usb_close(devh); return 1; } #ifdef LIBUSB_HAS_GET_DRIVER_NP { /* * Specifically avoid probing anything else than USB mass storage devices * and non-associated drivers in Linux. */ char devname[0x10]; devname[0] = '\0'; ret = usb_get_driver_np(devh, dev->config[i].interface[j].altsetting[k].iInterface, devname, sizeof(devname)); if (devname[0] != '\0' && strcmp(devname, "usb-storage")) { LIBMTP_INFO("avoid probing device using kernel interface \"%s\"\n", devname); return 0; } } #endif } } } } else { if (dev->descriptor.bNumConfigurations) LIBMTP_INFO("dev->config is NULL in probe_device_descriptor yet dev->descriptor.bNumConfigurations > 0\n"); } /* * Only probe for OS descriptor if the device is vendor specific * or one of the interfaces found is. */ if (dev->descriptor.bDeviceClass == USB_CLASS_VENDOR_SPEC || found_vendor_spec_interface) { /* Read the special descriptor */ ret = usb_get_descriptor(devh, 0x03, 0xee, buf, sizeof(buf)); /* * If something failed we're probably stalled to we need * to clear the stall off the endpoint and say this is not * MTP. */ if (ret < 0) { /* EP0 is the default control endpoint */ usb_clear_halt(devh, 0); usb_close(devh); return 0; } // Dump it, if requested if (dumpfile != NULL && ret > 0) { fprintf(dumpfile, "Microsoft device descriptor 0xee:\n"); data_dump_ascii(dumpfile, buf, ret, 16); } /* Check if descriptor length is at least 10 bytes */ if (ret < 10) { usb_close(devh); return 0; } /* Check if this device has a Microsoft Descriptor */ if (!((buf[2] == 'M') && (buf[4] == 'S') && (buf[6] == 'F') && (buf[8] == 'T'))) { usb_close(devh); return 0; } /* Check if device responds to control message 1 or if there is an error */ cmd = buf[16]; ret = usb_control_msg (devh, USB_ENDPOINT_IN | USB_RECIP_DEVICE | USB_TYPE_VENDOR, cmd, 0, 4, (char *) buf, sizeof(buf), USB_TIMEOUT_DEFAULT); // Dump it, if requested if (dumpfile != NULL && ret > 0) { fprintf(dumpfile, "Microsoft device response to control message 1, CMD 0x%02x:\n", cmd); data_dump_ascii(dumpfile, buf, ret, 16); } /* If this is true, the device either isn't MTP or there was an error */ if (ret <= 0x15) { /* TODO: If there was an error, flag it and let the user know somehow */ /* if(ret == -1) {} */ usb_close(devh); return 0; } /* Check if device is MTP or if it is something like a USB Mass Storage device with Janus DRM support */ if ((buf[0x12] != 'M') || (buf[0x13] != 'T') || (buf[0x14] != 'P')) { usb_close(devh); return 0; } /* After this point we are probably dealing with an MTP device */ /* * Check if device responds to control message 2, which is * the extended device parameters. Most devices will just * respond with a copy of the same message as for the first * message, some respond with zero-length (which is OK) * and some with pure garbage. We're not parsing the result * so this is not very important. */ ret = usb_control_msg (devh, USB_ENDPOINT_IN | USB_RECIP_DEVICE | USB_TYPE_VENDOR, cmd, 0, 5, (char *) buf, sizeof(buf), USB_TIMEOUT_DEFAULT); // Dump it, if requested if (dumpfile != NULL && ret > 0) { fprintf(dumpfile, "Microsoft device response to control message 2, CMD 0x%02x:\n", cmd); data_dump_ascii(dumpfile, buf, ret, 16); } /* If this is true, the device errored against control message 2 */ if (ret == -1) { /* TODO: Implement callback function to let managing program know there was a problem, along with description of the problem */ LIBMTP_ERROR("Potential MTP Device with VendorID:%04x and " "ProductID:%04x encountered an error responding to " "control message 2.\n" "Problems may arrise but continuing\n", dev->descriptor.idVendor, dev->descriptor.idProduct); } else if (dumpfile != NULL && ret == 0) { fprintf(dumpfile, "Zero-length response to control message 2 (OK)\n"); } else if (dumpfile != NULL) { fprintf(dumpfile, "Device responds to control message 2 with some data.\n"); } /* Close the USB device handle */ usb_close(devh); return 1; } /* Close the USB device handle */ usb_close(devh); return 0; } /** * This function scans through the connected usb devices on a machine and * if they match known Vendor and Product identifiers appends them to the * dynamic array mtp_device_list. Be sure to call * free_mtpdevice_list(mtp_device_list) when you are done * with it, assuming it is not NULL. * @param mtp_device_list dynamic array of pointers to usb devices with MTP * properties (if this list is not empty, new entries will be appended * to the list). * @return LIBMTP_ERROR_NONE implies that devices have been found, scan the list * appropriately. LIBMTP_ERROR_NO_DEVICE_ATTACHED implies that no * devices have been found. */ static LIBMTP_error_number_t get_mtp_usb_device_list(mtpdevice_list_t ** mtp_device_list) { struct usb_bus *bus = init_usb(); for (; bus != NULL; bus = bus->next) { struct usb_device *dev = bus->devices; for (; dev != NULL; dev = dev->next) { if (dev->descriptor.bDeviceClass != USB_CLASS_HUB) { int i; int found = 0; // First check if we know about the device already. // Devices well known to us will not have their descriptors // probed, it caused problems with some devices. for(i = 0; i < mtp_device_table_size; i++) { if(dev->descriptor.idVendor == mtp_device_table[i].vendor_id && dev->descriptor.idProduct == mtp_device_table[i].product_id) { /* Append this usb device to the MTP device list */ *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list, dev, bus->location); found = 1; break; } } // If we didn't know it, try probing the "OS Descriptor". if (!found) { if (probe_device_descriptor(dev, NULL)) { /* Append this usb device to the MTP USB Device List */ *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list, dev, bus->location); } /* * By thomas_-_s: Also append devices that are no MTP but PTP devices * if this is commented out. */ /* else { // Check whether the device is no USB hub but a PTP. if ( dev->config != NULL &&dev->config->interface->altsetting->bInterfaceClass == USB_CLASS_PTP && dev->descriptor.bDeviceClass != USB_CLASS_HUB ) { *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list, dev, bus->location); } } */ } } } } /* If nothing was found we end up here. */ if(*mtp_device_list == NULL) { return LIBMTP_ERROR_NO_DEVICE_ATTACHED; } return LIBMTP_ERROR_NONE; } /** * Checks if a specific device with a certain bus and device * number has an MTP type device descriptor. * * @param busno the bus number of the device to check * @param deviceno the device number of the device to check * @return 1 if the device is MTP else 0 */ int LIBMTP_Check_Specific_Device(int busno, int devno) { struct usb_bus *bus = init_usb(); for (; bus != NULL; bus = bus->next) { struct usb_device *dev = bus->devices; if (bus->location != busno) continue; for (; dev != NULL; dev = dev->next) { if (dev->devnum != devno) continue; if (probe_device_descriptor(dev, NULL)) return 1; } } return 0; } /** * Detect the raw MTP device descriptors and return a list of * of the devices found. * * @param devices a pointer to a variable that will hold * the list of raw devices found. This may be NULL * on return if the number of detected devices is zero. * The user shall simply free() this * variable when finished with the raw devices, * in order to release memory. * @param numdevs a pointer to an integer that will hold * the number of devices in the list. This may * be 0. * @return 0 if successful, any other value means failure. */ LIBMTP_error_number_t LIBMTP_Detect_Raw_Devices(LIBMTP_raw_device_t ** devices, int * numdevs) { mtpdevice_list_t *devlist = NULL; mtpdevice_list_t *dev; LIBMTP_error_number_t ret; LIBMTP_raw_device_t *retdevs; int devs = 0; int i, j; ret = get_mtp_usb_device_list(&devlist); if (ret == LIBMTP_ERROR_NO_DEVICE_ATTACHED) { *devices = NULL; *numdevs = 0; return ret; } else if (ret != LIBMTP_ERROR_NONE) { LIBMTP_ERROR("LIBMTP PANIC: get_mtp_usb_device_list() " "error code: %d on line %d\n", ret, __LINE__); return ret; } // Get list size dev = devlist; while (dev != NULL) { devs++; dev = dev->next; } if (devs == 0) { *devices = NULL; *numdevs = 0; return LIBMTP_ERROR_NONE; } // Conjure a device list retdevs = (LIBMTP_raw_device_t *) malloc(sizeof(LIBMTP_raw_device_t) * devs); if (retdevs == NULL) { // Out of memory *devices = NULL; *numdevs = 0; return LIBMTP_ERROR_MEMORY_ALLOCATION; } dev = devlist; i = 0; while (dev != NULL) { int device_known = 0; // Assign default device info retdevs[i].device_entry.vendor = NULL; retdevs[i].device_entry.vendor_id = dev->libusb_device->descriptor.idVendor; retdevs[i].device_entry.product = NULL; retdevs[i].device_entry.product_id = dev->libusb_device->descriptor.idProduct; retdevs[i].device_entry.device_flags = 0x00000000U; // See if we can locate some additional vendor info and device flags for(j = 0; j < mtp_device_table_size; j++) { if(dev->libusb_device->descriptor.idVendor == mtp_device_table[j].vendor_id && dev->libusb_device->descriptor.idProduct == mtp_device_table[j].product_id) { device_known = 1; retdevs[i].device_entry.vendor = mtp_device_table[j].vendor; retdevs[i].device_entry.product = mtp_device_table[j].product; retdevs[i].device_entry.device_flags = mtp_device_table[j].device_flags; // This device is known to the developers LIBMTP_ERROR("Device %d (VID=%04x and PID=%04x) is a %s %s.\n", i, dev->libusb_device->descriptor.idVendor, dev->libusb_device->descriptor.idProduct, mtp_device_table[j].vendor, mtp_device_table[j].product); break; } } if (!device_known) { // This device is unknown to the developers LIBMTP_ERROR("Device %d (VID=%04x and PID=%04x) is UNKNOWN.\n", i, dev->libusb_device->descriptor.idVendor, dev->libusb_device->descriptor.idProduct); LIBMTP_ERROR("Please report this VID/PID and the device model to the " "libmtp development team\n"); /* * Trying to get iManufacturer or iProduct from the device at this * point would require opening a device handle, that we don't want * to do right now. (Takes time for no good enough reason.) */ } // Save the location on the bus retdevs[i].bus_location = dev->bus_location; retdevs[i].devnum = dev->libusb_device->devnum; i++; dev = dev->next; } *devices = retdevs; *numdevs = i; free_mtpdevice_list(devlist); return LIBMTP_ERROR_NONE; } /** * This routine just dumps out low-level * USB information about the current device. * @param ptp_usb the USB device to get information from. */ void dump_usbinfo(PTP_USB *ptp_usb) { struct usb_device *dev; #ifdef LIBUSB_HAS_GET_DRIVER_NP char devname[0x10]; int res; devname[0] = '\0'; res = usb_get_driver_np(ptp_usb->handle, (int) ptp_usb->interface, devname, sizeof(devname)); if (devname[0] != '\0') { LIBMTP_INFO(" Using kernel interface \"%s\"\n", devname); } #endif dev = usb_device(ptp_usb->handle); LIBMTP_INFO(" bcdUSB: %d\n", dev->descriptor.bcdUSB); LIBMTP_INFO(" bDeviceClass: %d\n", dev->descriptor.bDeviceClass); LIBMTP_INFO(" bDeviceSubClass: %d\n", dev->descriptor.bDeviceSubClass); LIBMTP_INFO(" bDeviceProtocol: %d\n", dev->descriptor.bDeviceProtocol); LIBMTP_INFO(" idVendor: %04x\n", dev->descriptor.idVendor); LIBMTP_INFO(" idProduct: %04x\n", dev->descriptor.idProduct); LIBMTP_INFO(" IN endpoint maxpacket: %d bytes\n", ptp_usb->inep_maxpacket); LIBMTP_INFO(" OUT endpoint maxpacket: %d bytes\n", ptp_usb->outep_maxpacket); LIBMTP_INFO(" Raw device info:\n"); LIBMTP_INFO(" Bus location: %d\n", ptp_usb->rawdevice.bus_location); LIBMTP_INFO(" Device number: %d\n", ptp_usb->rawdevice.devnum); LIBMTP_INFO(" Device entry info:\n"); LIBMTP_INFO(" Vendor: %s\n", ptp_usb->rawdevice.device_entry.vendor); LIBMTP_INFO(" Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.vendor_id); LIBMTP_INFO(" Product: %s\n", ptp_usb->rawdevice.device_entry.product); LIBMTP_INFO(" Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.product_id); LIBMTP_INFO(" Device flags: 0x%08x\n", ptp_usb->rawdevice.device_entry.device_flags); (void) probe_device_descriptor(dev, stdout); } /** * Retrieve the apropriate playlist extension for this * device. Rather hacky at the moment. This is probably * desired by the managing software, but when creating * lists on the device itself you notice certain preferences. * @param ptp_usb the USB device to get suggestion for. * @return the suggested playlist extension. */ const char *get_playlist_extension(PTP_USB *ptp_usb) { struct usb_device *dev; static char creative_pl_extension[] = ".zpl"; static char default_pl_extension[] = ".pla"; dev = usb_device(ptp_usb->handle); if (dev->descriptor.idVendor == 0x041e) { return creative_pl_extension; } return default_pl_extension; } static void libusb_glue_debug (PTPParams *params, const char *format, ...) { va_list args; va_start (args, format); if (params->debug_func!=NULL) params->debug_func (params->data, format, args); else { vfprintf (stderr, format, args); fprintf (stderr,"\n"); fflush (stderr); } va_end (args); } static void libusb_glue_error (PTPParams *params, const char *format, ...) { va_list args; va_start (args, format); if (params->error_func!=NULL) params->error_func (params->data, format, args); else { vfprintf (stderr, format, args); fprintf (stderr,"\n"); fflush (stderr); } va_end (args); } /* * ptp_read_func() and ptp_write_func() are * based on same functions usb.c in libgphoto2. * Much reading packet logs and having fun with trials and errors * reveals that WMP / Windows is probably using an algorithm like this * for large transfers: * * 1. Send the command (0x0c bytes) if headers are split, else, send * command plus sizeof(endpoint) - 0x0c bytes. * 2. Send first packet, max size to be sizeof(endpoint) but only when using * split headers. Else goto 3. * 3. REPEAT send 0x10000 byte chunks UNTIL remaining bytes < 0x10000 * We call 0x10000 CONTEXT_BLOCK_SIZE. * 4. Send remaining bytes MOD sizeof(endpoint) * 5. Send remaining bytes. If this happens to be exactly sizeof(endpoint) * then also send a zero-length package. * * Further there is some special quirks to handle zero reads from the * device, since some devices can't do them at all due to shortcomings * of the USB slave controller in the device. */ #define CONTEXT_BLOCK_SIZE_1 0x3e00 #define CONTEXT_BLOCK_SIZE_2 0x200 #define CONTEXT_BLOCK_SIZE CONTEXT_BLOCK_SIZE_1+CONTEXT_BLOCK_SIZE_2 static short ptp_read_func ( unsigned long size, PTPDataHandler *handler,void *data, unsigned long *readbytes, int readzero ) { PTP_USB *ptp_usb = (PTP_USB *)data; unsigned long toread = 0; int result = 0; unsigned long curread = 0; unsigned long written; unsigned char *bytes; int expect_terminator_byte = 0; // This is the largest block we'll need to read in. bytes = malloc(CONTEXT_BLOCK_SIZE); while (curread < size) { LIBMTP_USB_DEBUG("Remaining size to read: 0x%04lx bytes\n", size - curread); // check equal to condition here if (size - curread < CONTEXT_BLOCK_SIZE) { // this is the last packet toread = size - curread; // this is equivalent to zero read for these devices if (readzero && FLAG_NO_ZERO_READS(ptp_usb) && toread % 64 == 0) { toread += 1; expect_terminator_byte = 1; } } else if (curread == 0) // we are first packet, but not last packet toread = CONTEXT_BLOCK_SIZE_1; else if (toread == CONTEXT_BLOCK_SIZE_1) toread = CONTEXT_BLOCK_SIZE_2; else if (toread == CONTEXT_BLOCK_SIZE_2) toread = CONTEXT_BLOCK_SIZE_1; else LIBMTP_INFO("unexpected toread size 0x%04x, 0x%04x remaining bytes\n", (unsigned int) toread, (unsigned int) (size-curread)); LIBMTP_USB_DEBUG("Reading in 0x%04lx bytes\n", toread); result = USB_BULK_READ(ptp_usb->handle, ptp_usb->inep, (char*) bytes, toread, ptp_usb->timeout); LIBMTP_USB_DEBUG("Result of read: 0x%04x\n", result); if (result < 0) { return PTP_ERROR_IO; } LIBMTP_USB_DEBUG("<==USB IN\n"); if (result == 0) LIBMTP_USB_DEBUG("Zero Read\n"); else LIBMTP_USB_DATA(bytes, result, 16); // want to discard extra byte if (expect_terminator_byte && result == toread) { LIBMTP_USB_DEBUG("<==USB IN\nDiscarding extra byte\n"); result--; } int putfunc_ret = handler->putfunc(NULL, handler->priv, result, bytes, &written); if (putfunc_ret != PTP_RC_OK) return putfunc_ret; ptp_usb->current_transfer_complete += result; curread += result; // Increase counters, call callback if (ptp_usb->callback_active) { if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) { // send last update and disable callback. ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total; ptp_usb->callback_active = 0; } if (ptp_usb->current_transfer_callback != NULL) { int ret; ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete, ptp_usb->current_transfer_total, ptp_usb->current_transfer_callback_data); if (ret != 0) { return PTP_ERROR_CANCEL; } } } if (result < toread) /* short reads are common */ break; } if (readbytes) *readbytes = curread; free (bytes); // there might be a zero packet waiting for us... if (readzero && !FLAG_NO_ZERO_READS(ptp_usb) && curread % ptp_usb->outep_maxpacket == 0) { char temp; int zeroresult = 0; LIBMTP_USB_DEBUG("<==USB IN\n"); LIBMTP_USB_DEBUG("Zero Read\n"); zeroresult = USB_BULK_READ(ptp_usb->handle, ptp_usb->inep, &temp, 0, ptp_usb->timeout); if (zeroresult != 0) LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult); } return PTP_RC_OK; } static short ptp_write_func ( unsigned long size, PTPDataHandler *handler, void *data, unsigned long *written ) { PTP_USB *ptp_usb = (PTP_USB *)data; unsigned long towrite = 0; int result = 0; unsigned long curwrite = 0; unsigned char *bytes; // This is the largest block we'll need to read in. bytes = malloc(CONTEXT_BLOCK_SIZE); if (!bytes) { return PTP_ERROR_IO; } while (curwrite < size) { unsigned long usbwritten = 0; towrite = size-curwrite; if (towrite > CONTEXT_BLOCK_SIZE) { towrite = CONTEXT_BLOCK_SIZE; } else { // This magic makes packets the same size that WMP send them. if (towrite > ptp_usb->outep_maxpacket && towrite % ptp_usb->outep_maxpacket != 0) { towrite -= towrite % ptp_usb->outep_maxpacket; } } int getfunc_ret = handler->getfunc(NULL, handler->priv,towrite,bytes,&towrite); if (getfunc_ret != PTP_RC_OK) return getfunc_ret; while (usbwritten < towrite) { result = USB_BULK_WRITE(ptp_usb->handle, ptp_usb->outep, ((char*) bytes+usbwritten), towrite-usbwritten, ptp_usb->timeout); LIBMTP_USB_DEBUG("USB OUT==>\n"); LIBMTP_USB_DATA(bytes+usbwritten, result, 16); if (result < 0) { return PTP_ERROR_IO; } // check for result == 0 perhaps too. // Increase counters ptp_usb->current_transfer_complete += result; curwrite += result; usbwritten += result; } // call callback if (ptp_usb->callback_active) { if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) { // send last update and disable callback. ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total; ptp_usb->callback_active = 0; } if (ptp_usb->current_transfer_callback != NULL) { int ret; ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete, ptp_usb->current_transfer_total, ptp_usb->current_transfer_callback_data); if (ret != 0) { return PTP_ERROR_CANCEL; } } } if (result < towrite) /* short writes happen */ break; } free (bytes); if (written) { *written = curwrite; } // If this is the last transfer send a zero write if required if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) { if ((towrite % ptp_usb->outep_maxpacket) == 0) { LIBMTP_USB_DEBUG("USB OUT==>\n"); LIBMTP_USB_DEBUG("Zero Write\n"); result=USB_BULK_WRITE(ptp_usb->handle, ptp_usb->outep, (char *) "x", 0, ptp_usb->timeout); } } if (result < 0) return PTP_ERROR_IO; return PTP_RC_OK; } /* memory data get/put handler */ typedef struct { unsigned char *data; unsigned long size, curoff; } PTPMemHandlerPrivate; static uint16_t memory_getfunc(PTPParams* params, void* private, unsigned long wantlen, unsigned char *data, unsigned long *gotlen ) { PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)private; unsigned long tocopy = wantlen; if (priv->curoff + tocopy > priv->size) tocopy = priv->size - priv->curoff; memcpy (data, priv->data + priv->curoff, tocopy); priv->curoff += tocopy; *gotlen = tocopy; return PTP_RC_OK; } static uint16_t memory_putfunc(PTPParams* params, void* private, unsigned long sendlen, unsigned char *data, unsigned long *putlen ) { PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)private; if (priv->curoff + sendlen > priv->size) { priv->data = realloc (priv->data, priv->curoff+sendlen); priv->size = priv->curoff + sendlen; } memcpy (priv->data + priv->curoff, data, sendlen); priv->curoff += sendlen; *putlen = sendlen; return PTP_RC_OK; } /* init private struct for receiving data. */ static uint16_t ptp_init_recv_memory_handler(PTPDataHandler *handler) { PTPMemHandlerPrivate* priv; priv = malloc (sizeof(PTPMemHandlerPrivate)); handler->priv = priv; handler->getfunc = memory_getfunc; handler->putfunc = memory_putfunc; priv->data = NULL; priv->size = 0; priv->curoff = 0; return PTP_RC_OK; } /* init private struct and put data in for sending data. * data is still owned by caller. */ static uint16_t ptp_init_send_memory_handler(PTPDataHandler *handler, unsigned char *data, unsigned long len ) { PTPMemHandlerPrivate* priv; priv = malloc (sizeof(PTPMemHandlerPrivate)); if (!priv) return PTP_RC_GeneralError; handler->priv = priv; handler->getfunc = memory_getfunc; handler->putfunc = memory_putfunc; priv->data = data; priv->size = len; priv->curoff = 0; return PTP_RC_OK; } /* free private struct + data */ static uint16_t ptp_exit_send_memory_handler (PTPDataHandler *handler) { PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)handler->priv; /* data is owned by caller */ free (priv); return PTP_RC_OK; } /* hand over our internal data to caller */ static uint16_t ptp_exit_recv_memory_handler (PTPDataHandler *handler, unsigned char **data, unsigned long *size ) { PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)handler->priv; *data = priv->data; *size = priv->size; free (priv); return PTP_RC_OK; } /* send / receive functions */ uint16_t ptp_usb_sendreq (PTPParams* params, PTPContainer* req) { uint16_t ret; PTPUSBBulkContainer usbreq; PTPDataHandler memhandler; unsigned long written = 0; unsigned long towrite; char txt[256]; (void) ptp_render_opcode (params, req->Code, sizeof(txt), txt); LIBMTP_USB_DEBUG("REQUEST: 0x%04x, %s\n", req->Code, txt); /* build appropriate USB container */ usbreq.length=htod32(PTP_USB_BULK_REQ_LEN- (sizeof(uint32_t)*(5-req->Nparam))); usbreq.type=htod16(PTP_USB_CONTAINER_COMMAND); usbreq.code=htod16(req->Code); usbreq.trans_id=htod32(req->Transaction_ID); usbreq.payload.params.param1=htod32(req->Param1); usbreq.payload.params.param2=htod32(req->Param2); usbreq.payload.params.param3=htod32(req->Param3); usbreq.payload.params.param4=htod32(req->Param4); usbreq.payload.params.param5=htod32(req->Param5); /* send it to responder */ towrite = PTP_USB_BULK_REQ_LEN-(sizeof(uint32_t)*(5-req->Nparam)); ptp_init_send_memory_handler (&memhandler, (unsigned char*)&usbreq, towrite); ret=ptp_write_func( towrite, &memhandler, params->data, &written ); ptp_exit_send_memory_handler (&memhandler); if (ret!=PTP_RC_OK && ret!=PTP_ERROR_CANCEL) { ret = PTP_ERROR_IO; } if (written != towrite && ret != PTP_ERROR_CANCEL && ret != PTP_ERROR_IO) { libusb_glue_error (params, "PTP: request code 0x%04x sending req wrote only %ld bytes instead of %d", req->Code, written, towrite ); ret = PTP_ERROR_IO; } return ret; } uint16_t ptp_usb_senddata (PTPParams* params, PTPContainer* ptp, uint64_t size, PTPDataHandler *handler ) { uint16_t ret; int wlen, datawlen; unsigned long written; PTPUSBBulkContainer usbdata; uint64_t bytes_left_to_transfer; PTPDataHandler memhandler; LIBMTP_USB_DEBUG("SEND DATA PHASE\n"); /* build appropriate USB container */ usbdata.length = htod32(PTP_USB_BULK_HDR_LEN+size); usbdata.type = htod16(PTP_USB_CONTAINER_DATA); usbdata.code = htod16(ptp->Code); usbdata.trans_id= htod32(ptp->Transaction_ID); ((PTP_USB*)params->data)->current_transfer_complete = 0; ((PTP_USB*)params->data)->current_transfer_total = size+PTP_USB_BULK_HDR_LEN; if (params->split_header_data) { datawlen = 0; wlen = PTP_USB_BULK_HDR_LEN; } else { unsigned long gotlen; /* For all camera devices. */ datawlen = (sizegetfunc(params, handler->priv, datawlen, usbdata.payload.data, &gotlen); if (ret != PTP_RC_OK) return ret; if (gotlen != datawlen) return PTP_RC_GeneralError; } ptp_init_send_memory_handler (&memhandler, (unsigned char *)&usbdata, wlen); /* send first part of data */ ret = ptp_write_func(wlen, &memhandler, params->data, &written); ptp_exit_send_memory_handler (&memhandler); if (ret!=PTP_RC_OK) { return ret; } if (size <= datawlen) return ret; /* if everything OK send the rest */ bytes_left_to_transfer = size-datawlen; ret = PTP_RC_OK; while(bytes_left_to_transfer > 0) { ret = ptp_write_func (bytes_left_to_transfer, handler, params->data, &written); if (ret != PTP_RC_OK) break; if (written == 0) { ret = PTP_ERROR_IO; break; } bytes_left_to_transfer -= written; } if (ret!=PTP_RC_OK && ret!=PTP_ERROR_CANCEL) ret = PTP_ERROR_IO; return ret; } static uint16_t ptp_usb_getpacket(PTPParams *params, PTPUSBBulkContainer *packet, unsigned long *rlen) { PTPDataHandler memhandler; uint16_t ret; unsigned char *x = NULL; /* read the header and potentially the first data */ if (params->response_packet_size > 0) { /* If there is a buffered packet, just use it. */ memcpy(packet, params->response_packet, params->response_packet_size); *rlen = params->response_packet_size; free(params->response_packet); params->response_packet = NULL; params->response_packet_size = 0; /* Here this signifies a "virtual read" */ return PTP_RC_OK; } ptp_init_recv_memory_handler (&memhandler); ret = ptp_read_func(PTP_USB_BULK_HS_MAX_PACKET_LEN_READ, &memhandler, params->data, rlen, 0); ptp_exit_recv_memory_handler (&memhandler, &x, rlen); if (x) { memcpy (packet, x, *rlen); free (x); } return ret; } uint16_t ptp_usb_getdata (PTPParams* params, PTPContainer* ptp, PTPDataHandler *handler) { uint16_t ret; PTPUSBBulkContainer usbdata; unsigned long written; PTP_USB *ptp_usb = (PTP_USB *) params->data; int putfunc_ret; LIBMTP_USB_DEBUG("GET DATA PHASE\n"); memset(&usbdata,0,sizeof(usbdata)); do { unsigned long len, rlen; ret = ptp_usb_getpacket(params, &usbdata, &rlen); if (ret!=PTP_RC_OK) { ret = PTP_ERROR_IO; break; } if (dtoh16(usbdata.type)!=PTP_USB_CONTAINER_DATA) { ret = PTP_ERROR_DATA_EXPECTED; break; } if (dtoh16(usbdata.code)!=ptp->Code) { if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) { libusb_glue_debug (params, "ptp2/ptp_usb_getdata: detected a broken " "PTP header, code field insane, expect problems! (But continuing)"); // Repair the header, so it won't wreak more havoc, don't just ignore it. // Typically these two fields will be broken. usbdata.code = htod16(ptp->Code); usbdata.trans_id = htod32(ptp->Transaction_ID); ret = PTP_RC_OK; } else { ret = dtoh16(usbdata.code); // This filters entirely insane garbage return codes, but still // makes it possible to return error codes in the code field when // getting data. It appears Windows ignores the contents of this // field entirely. if (ret < PTP_RC_Undefined || ret > PTP_RC_SpecificationOfDestinationUnsupported) { libusb_glue_debug (params, "ptp2/ptp_usb_getdata: detected a broken " "PTP header, code field insane."); ret = PTP_ERROR_IO; } break; } } if (rlen == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ) { /* Copy first part of data to 'data' */ putfunc_ret = handler->putfunc( params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN, usbdata.payload.data, &written ); if (putfunc_ret != PTP_RC_OK) return putfunc_ret; /* stuff data directly to passed data handler */ while (1) { unsigned long readdata; uint16_t xret; xret = ptp_read_func( 0x20000000, handler, params->data, &readdata, 0 ); if (xret != PTP_RC_OK) return xret; if (readdata < 0x20000000) break; } return PTP_RC_OK; } if (rlen > dtoh32(usbdata.length)) { /* * Buffer the surplus response packet if it is >= * PTP_USB_BULK_HDR_LEN * (i.e. it is probably an entire package) * else discard it as erroneous surplus data. * This will even work if more than 2 packets appear * in the same transaction, they will just be handled * iteratively. * * Marcus observed stray bytes on iRiver devices; * these are still discarded. */ unsigned int packlen = dtoh32(usbdata.length); unsigned int surplen = rlen - packlen; if (surplen >= PTP_USB_BULK_HDR_LEN) { params->response_packet = malloc(surplen); memcpy(params->response_packet, (uint8_t *) &usbdata + packlen, surplen); params->response_packet_size = surplen; /* Ignore reading one extra byte if device flags have been set */ } else if(!FLAG_NO_ZERO_READS(ptp_usb) && (rlen - dtoh32(usbdata.length) == 1)) { libusb_glue_debug (params, "ptp2/ptp_usb_getdata: read %d bytes " "too much, expect problems!", rlen - dtoh32(usbdata.length)); } rlen = packlen; } /* For most PTP devices rlen is 512 == sizeof(usbdata) * here. For MTP devices splitting header and data it might * be 12. */ /* Evaluate full data length. */ len=dtoh32(usbdata.length)-PTP_USB_BULK_HDR_LEN; /* autodetect split header/data MTP devices */ if (dtoh32(usbdata.length) > 12 && (rlen==12)) params->split_header_data = 1; /* Copy first part of data to 'data' */ putfunc_ret = handler->putfunc( params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN, usbdata.payload.data, &written ); if (putfunc_ret != PTP_RC_OK) return putfunc_ret; if (FLAG_NO_ZERO_READS(ptp_usb) && len+PTP_USB_BULK_HDR_LEN == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ) { LIBMTP_USB_DEBUG("Reading in extra terminating byte\n"); // need to read in extra byte and discard it int result = 0; char byte = 0; result = USB_BULK_READ(ptp_usb->handle, ptp_usb->inep, &byte, 1, ptp_usb->timeout); if (result != 1) 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); } else if (len+PTP_USB_BULK_HDR_LEN == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ && params->split_header_data == 0) { int zeroresult = 0; char zerobyte = 0; LIBMTP_INFO("Reading in zero packet after header\n"); zeroresult = USB_BULK_READ(ptp_usb->handle, ptp_usb->inep, &zerobyte, 0, ptp_usb->timeout); if (zeroresult != 0) LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult); } /* Is that all of data? */ if (len+PTP_USB_BULK_HDR_LEN<=rlen) { break; } ret = ptp_read_func(len - (rlen - PTP_USB_BULK_HDR_LEN), handler, params->data, &rlen, 1); if (ret!=PTP_RC_OK) { break; } } while (0); return ret; } uint16_t ptp_usb_getresp (PTPParams* params, PTPContainer* resp) { uint16_t ret; unsigned long rlen; PTPUSBBulkContainer usbresp; PTP_USB *ptp_usb = (PTP_USB *)(params->data); LIBMTP_USB_DEBUG("RESPONSE: "); memset(&usbresp,0,sizeof(usbresp)); /* read response, it should never be longer than sizeof(usbresp) */ ret = ptp_usb_getpacket(params, &usbresp, &rlen); // Fix for bevahiour reported by Scott Snyder on Samsung YP-U3. The player // sends a packet containing just zeroes of length 2 (up to 4 has been seen too) // after a NULL packet when it should send the response. This code ignores // such illegal packets. while (ret==PTP_RC_OK && rlenCode) { ret = dtoh16(usbresp.code); } LIBMTP_USB_DEBUG("%04x\n", ret); if (ret!=PTP_RC_OK) { /* libusb_glue_error (params, "PTP: request code 0x%04x getting resp error 0x%04x", resp->Code, ret);*/ return ret; } /* build an appropriate PTPContainer */ resp->Code=dtoh16(usbresp.code); resp->SessionID=params->session_id; resp->Transaction_ID=dtoh32(usbresp.trans_id); if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) { if (resp->Transaction_ID != params->transaction_id-1) { libusb_glue_debug (params, "ptp_usb_getresp: detected a broken " "PTP header, transaction ID insane, expect " "problems! (But continuing)"); // Repair the header, so it won't wreak more havoc. resp->Transaction_ID = params->transaction_id-1; } } resp->Param1=dtoh32(usbresp.payload.params.param1); resp->Param2=dtoh32(usbresp.payload.params.param2); resp->Param3=dtoh32(usbresp.payload.params.param3); resp->Param4=dtoh32(usbresp.payload.params.param4); resp->Param5=dtoh32(usbresp.payload.params.param5); return ret; } /* Event handling functions */ /* PTP Events wait for or check mode */ #define PTP_EVENT_CHECK 0x0000 /* waits for */ #define PTP_EVENT_CHECK_FAST 0x0001 /* checks */ static inline uint16_t ptp_usb_event (PTPParams* params, PTPContainer* event, int wait) { uint16_t ret; int result; unsigned long rlen; PTPUSBEventContainer usbevent; PTP_USB *ptp_usb = (PTP_USB *)(params->data); memset(&usbevent,0,sizeof(usbevent)); if ((params==NULL) || (event==NULL)) return PTP_ERROR_BADPARAM; ret = PTP_RC_OK; switch(wait) { case PTP_EVENT_CHECK: result = USB_BULK_READ(ptp_usb->handle, ptp_usb->intep, (char *) &usbevent, sizeof(usbevent), 0); if (result==0) result = USB_BULK_READ(ptp_usb->handle, ptp_usb->intep, (char *) &usbevent, sizeof(usbevent), 0); if (result < 0) ret = PTP_ERROR_IO; break; case PTP_EVENT_CHECK_FAST: result = USB_BULK_READ(ptp_usb->handle, ptp_usb->intep, (char *) &usbevent, sizeof(usbevent), ptp_usb->timeout); if (result==0) result = USB_BULK_READ(ptp_usb->handle, ptp_usb->intep, (char *) &usbevent, sizeof(usbevent), ptp_usb->timeout); if (result < 0) ret = PTP_ERROR_IO; break; default: ret=PTP_ERROR_BADPARAM; break; } if (ret!=PTP_RC_OK) { libusb_glue_error (params, "PTP: reading event an error 0x%04x occurred", ret); return PTP_ERROR_IO; } rlen = result; if (rlen < 8) { libusb_glue_error (params, "PTP: reading event an short read of %ld bytes occurred", rlen); return PTP_ERROR_IO; } /* if we read anything over interrupt endpoint it must be an event */ /* build an appropriate PTPContainer */ event->Code=dtoh16(usbevent.code); event->SessionID=params->session_id; event->Transaction_ID=dtoh32(usbevent.trans_id); event->Param1=dtoh32(usbevent.param1); event->Param2=dtoh32(usbevent.param2); event->Param3=dtoh32(usbevent.param3); return ret; } uint16_t ptp_usb_event_check (PTPParams* params, PTPContainer* event) { return ptp_usb_event (params, event, PTP_EVENT_CHECK_FAST); } uint16_t ptp_usb_event_wait (PTPParams* params, PTPContainer* event) { return ptp_usb_event (params, event, PTP_EVENT_CHECK); } uint16_t ptp_usb_control_cancel_request (PTPParams *params, uint32_t transactionid) { PTP_USB *ptp_usb = (PTP_USB *)(params->data); int ret; unsigned char buffer[6]; htod16a(&buffer[0],PTP_EC_CancelTransaction); htod32a(&buffer[2],transactionid); ret = usb_control_msg(ptp_usb->handle, USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0x64, 0x0000, 0x0000, (char *) buffer, sizeof(buffer), ptp_usb->timeout); if (ret < sizeof(buffer)) return PTP_ERROR_IO; return PTP_RC_OK; } static int init_ptp_usb(PTPParams* params, PTP_USB* ptp_usb, struct usb_device* dev) { usb_dev_handle *device_handle; char buf[255]; int usbresult; params->sendreq_func=ptp_usb_sendreq; params->senddata_func=ptp_usb_senddata; params->getresp_func=ptp_usb_getresp; params->getdata_func=ptp_usb_getdata; params->cancelreq_func=ptp_usb_control_cancel_request; params->data=ptp_usb; params->transaction_id=0; /* * This is hardcoded here since we have no devices whatsoever that are BE. * Change this the day we run into our first BE device (if ever). */ params->byteorder = PTP_DL_LE; ptp_usb->timeout = get_timeout(ptp_usb); device_handle = usb_open(dev); if (!device_handle) { perror("usb_open()"); return -1; } ptp_usb->handle = device_handle; #ifdef LIBUSB_HAS_DETACH_KERNEL_DRIVER_NP /* * If this device is known to be wrongfully claimed by other kernel * drivers (such as mass storage), then try to unload it to make it * accessible from user space. */ if (FLAG_UNLOAD_DRIVER(ptp_usb)) { if (usb_get_driver_np(device_handle, (int) ptp_usb->interface, buf, sizeof(buf)) == 0) { if (usb_detach_kernel_driver_np(device_handle, (int) ptp_usb->interface)) { perror("usb_detach_kernel_driver_np()"); return -1; } } } #endif /* * Check if the config is set to something else than what we want * to use. Only set the configuration if we absolutely have to. * Also do not bail out if we fail. */ if (dev->config->bConfigurationValue != ptp_usb->config) { if (usb_set_configuration(device_handle, dev->config->bConfigurationValue)) { perror("error in usb_set_configuration()- continuing anyway"); } } /* * It seems like on kernel 2.6.31 if we already have it open on another * pthread in our app, we'll get an error if we try to claim it again, * but that error is harmless because our process already claimed the interface */ usbresult = usb_claim_interface(device_handle, (int) ptp_usb->interface); if (usbresult != 0) fprintf(stderr, "ignoring usb_claim_interface = %d", usbresult); /* * If the altsetting is set to something different than we want, switch * it. * * FIXME: this seems to cause trouble on the Mac:s so disable it. Retry * this on the Mac now that it only sets this when the altsetting differs. */ #ifndef __APPLE__ #if 0 /* Disable this always, no idea on how to handle it */ if (dev->config->interface[].altsetting[] != ptp_usb->altsetting) { fprintf(stderr, "desired altsetting different from current, trying to set altsetting\n"); usbresult = usb_set_altinterface(device_handle, 0); if (usbresult) fprintf(stderr, "ignoring error from usb_claim_interface = %d\n", usbresult); } #endif #endif if (FLAG_SWITCH_MODE_BLACKBERRY(ptp_usb)) { int ret; // FIXME : Only for BlackBerry Storm // What does it mean? Maybe switch mode... // This first control message is absolutely necessary usleep(1000); ret = usb_control_msg(device_handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN, 0xaa, 0x00, 0x04, buf, 0x40, 1000); LIBMTP_USB_DEBUG("BlackBerry magic part 1:\n"); LIBMTP_USB_DATA(buf, ret, 16); usleep(1000); // This control message is unnecessary ret = usb_control_msg(device_handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN, 0xa5, 0x00, 0x01, buf, 0x02, 1000); LIBMTP_USB_DEBUG("BlackBerry magic part 2:\n"); LIBMTP_USB_DATA(buf, ret, 16); usleep(1000); // This control message is unnecessary ret = usb_control_msg(device_handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN, 0xa8, 0x00, 0x01, buf, 0x05, 1000); LIBMTP_USB_DEBUG("BlackBerry magic part 3:\n"); LIBMTP_USB_DATA(buf, ret, 16); usleep(1000); // This control message is unnecessary ret = usb_control_msg(device_handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN, 0xa8, 0x00, 0x01, buf, 0x11, 1000); LIBMTP_USB_DEBUG("BlackBerry magic part 4:\n"); LIBMTP_USB_DATA(buf, ret, 16); usleep(1000); } return 0; } static void clear_stall(PTP_USB* ptp_usb) { uint16_t status; int ret; /* check the inep status */ status = 0; ret = usb_get_endpoint_status(ptp_usb,ptp_usb->inep,&status); if (ret<0) { perror ("inep: usb_get_endpoint_status()"); } else if (status) { LIBMTP_INFO("Clearing stall on IN endpoint\n"); ret = usb_clear_stall_feature(ptp_usb,ptp_usb->inep); if (ret<0) { perror ("usb_clear_stall_feature()"); } } /* check the outep status */ status=0; ret = usb_get_endpoint_status(ptp_usb,ptp_usb->outep,&status); if (ret<0) { perror("outep: usb_get_endpoint_status()"); } else if (status) { LIBMTP_INFO("Clearing stall on OUT endpoint\n"); ret = usb_clear_stall_feature(ptp_usb,ptp_usb->outep); if (ret<0) { perror("usb_clear_stall_feature()"); } } /* TODO: do we need this for INTERRUPT (ptp_usb->intep) too? */ } static void clear_halt(PTP_USB* ptp_usb) { int ret; ret = usb_clear_halt(ptp_usb->handle,ptp_usb->inep); if (ret<0) { perror("usb_clear_halt() on IN endpoint"); } ret = usb_clear_halt(ptp_usb->handle,ptp_usb->outep); if (ret<0) { perror("usb_clear_halt() on OUT endpoint"); } ret = usb_clear_halt(ptp_usb->handle,ptp_usb->intep); if (ret<0) { perror("usb_clear_halt() on INTERRUPT endpoint"); } } static void close_usb(PTP_USB* ptp_usb) { if (!FLAG_NO_RELEASE_INTERFACE(ptp_usb)) { /* * Clear any stalled endpoints * On misbehaving devices designed for Windows/Mac, quote from: * http://www2.one-eyed-alien.net/~mdharm/linux-usb/target_offenses.txt * Device does Bad Things(tm) when it gets a GET_STATUS after CLEAR_HALT * (...) Windows, when clearing a stall, only sends the CLEAR_HALT command, * and presumes that the stall has cleared. Some devices actually choke * if the CLEAR_HALT is followed by a GET_STATUS (used to determine if the * STALL is persistant or not). */ clear_stall(ptp_usb); #if 0 // causes troubles due to a kernel bug in 3.x kernels before/around 3.8 // Clear halts on any endpoints clear_halt(ptp_usb); // Added to clear some stuff on the OUT endpoint // TODO: is this good on the Mac too? // HINT: some devices may need that you comment these two out too. #endif usb_resetep(ptp_usb->handle, ptp_usb->outep); usb_release_interface(ptp_usb->handle, (int) ptp_usb->interface); } if (FLAG_FORCE_RESET_ON_CLOSE(ptp_usb)) { /* * Some devices really love to get reset after being * disconnected. Again, since Windows never disconnects * a device closing behaviour is seldom or never exercised * on devices when engineered and often error prone. * Reset may help some. */ usb_reset(ptp_usb->handle); } usb_close(ptp_usb->handle); } /** * Self-explanatory? */ static int find_interface_and_endpoints(struct usb_device *dev, uint8_t *conf, uint8_t *interface, uint8_t *altsetting, int* inep, int* inep_maxpacket, int* outep, int *outep_maxpacket, int* intep) { uint8_t i; // Loop over the device configurations for (i = 0; i < dev->descriptor.bNumConfigurations; i++) { uint8_t j; *conf = dev->config->bConfigurationValue;; // Loop over each configurations interfaces for (j = 0; j < dev->config[i].bNumInterfaces; j++) { uint8_t k, l; uint8_t no_ep; int found_inep = 0; int found_outep = 0; int found_intep = 0; struct usb_endpoint_descriptor *ep; // Inspect the altsettings of this interface for (k = 0; k < dev->config[i].interface[j].num_altsetting; k++) { // MTP devices shall have 3 endpoints, ignore those interfaces // that haven't. no_ep = dev->config[i].interface[j].altsetting[k].bNumEndpoints; if (no_ep != 3) continue; *interface = dev->config[i].interface[j].altsetting[k].bInterfaceNumber; *altsetting = dev->config[i].interface[j].altsetting[k].bAlternateSetting; ep = dev->config[i].interface[j].altsetting[k].endpoint; // Loop over the three endpoints to locate two bulk and // one interrupt endpoint and FAIL if we cannot, and continue. for (l = 0; l < no_ep; l++) { if (ep[l].bmAttributes == USB_ENDPOINT_TYPE_BULK) { if ((ep[l].bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_MASK) { *inep = ep[l].bEndpointAddress; *inep_maxpacket = ep[l].wMaxPacketSize; found_inep = 1; } if ((ep[l].bEndpointAddress & USB_ENDPOINT_DIR_MASK) == 0) { *outep = ep[l].bEndpointAddress; *outep_maxpacket = ep[l].wMaxPacketSize; found_outep = 1; } } else if (ep[l].bmAttributes == USB_ENDPOINT_TYPE_INTERRUPT) { if ((ep[l].bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_MASK) { *intep = ep[l].bEndpointAddress; found_intep = 1; } } } if (found_inep && found_outep && found_intep) // We assigned the endpoints so return here. return 0; // Else loop to next interface/config } /* Next altsetting */ } /* Next interface */ } /* Next config */ return -1; } /** * This function assigns params and usbinfo given a raw device * as input. * @param device the device to be assigned. * @param usbinfo a pointer to the new usbinfo. * @return an error code. */ LIBMTP_error_number_t configure_usb_device(LIBMTP_raw_device_t *device, PTPParams *params, void **usbinfo) { PTP_USB *ptp_usb; struct usb_device *libusb_device; uint16_t ret = 0; struct usb_bus *bus; int found = 0; int err; /* See if we can find this raw device again... */ bus = init_usb(); for (; bus != NULL; bus = bus->next) { if (bus->location == device->bus_location) { struct usb_device *dev = bus->devices; for (; dev != NULL; dev = dev->next) { if(dev->devnum == device->devnum && dev->descriptor.idVendor == device->device_entry.vendor_id && dev->descriptor.idProduct == device->device_entry.product_id ) { libusb_device = dev; found = 1; break; } } if (found) break; } } /* Device has gone since detecting raw devices! */ if (!found) { return LIBMTP_ERROR_NO_DEVICE_ATTACHED; } /* Allocate structs */ ptp_usb = (PTP_USB *) malloc(sizeof(PTP_USB)); if (ptp_usb == NULL) { return LIBMTP_ERROR_MEMORY_ALLOCATION; } /* Start with a blank slate (includes setting device_flags to 0) */ memset(ptp_usb, 0, sizeof(PTP_USB)); /* Copy the raw device */ memcpy(&ptp_usb->rawdevice, device, sizeof(LIBMTP_raw_device_t)); /* * Some devices must have their "OS Descriptor" massaged in order * to work. */ if (FLAG_ALWAYS_PROBE_DESCRIPTOR(ptp_usb)) { // Massage the device descriptor (void) probe_device_descriptor(libusb_device, NULL); } /* Assign interface and endpoints to usbinfo... */ err = find_interface_and_endpoints(libusb_device, &ptp_usb->config, &ptp_usb->interface, &ptp_usb->altsetting, &ptp_usb->inep, &ptp_usb->inep_maxpacket, &ptp_usb->outep, &ptp_usb->outep_maxpacket, &ptp_usb->intep); if (err) { LIBMTP_ERROR("LIBMTP PANIC: Unable to find interface & endpoints of device\n"); return LIBMTP_ERROR_CONNECTING; } /* Copy USB version number */ ptp_usb->bcdusb = libusb_device->descriptor.bcdUSB; /* Attempt to initialize this device */ if (init_ptp_usb(params, ptp_usb, libusb_device) < 0) { LIBMTP_ERROR("LIBMTP PANIC: Unable to initialize device\n"); return LIBMTP_ERROR_CONNECTING; } /* * This works in situations where previous bad applications * have not used LIBMTP_Release_Device on exit */ if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) { LIBMTP_ERROR("PTP_ERROR_IO: failed to open session, trying again after resetting USB interface\n"); LIBMTP_ERROR("LIBMTP libusb: Attempt to reset device\n"); usb_reset(ptp_usb->handle); close_usb(ptp_usb); if(init_ptp_usb(params, ptp_usb, libusb_device) <0) { LIBMTP_ERROR("LIBMTP PANIC: Could not init USB on second attempt\n"); return LIBMTP_ERROR_CONNECTING; } /* Device has been reset, try again */ if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) { LIBMTP_ERROR("LIBMTP PANIC: failed to open session on second attempt\n"); return LIBMTP_ERROR_CONNECTING; } } /* Was the transaction id invalid? Try again */ if (ret == PTP_RC_InvalidTransactionID) { LIBMTP_ERROR("LIBMTP WARNING: Transaction ID was invalid, increment and try again\n"); params->transaction_id += 10; ret = ptp_opensession(params, 1); } if (ret != PTP_RC_SessionAlreadyOpened && ret != PTP_RC_OK) { LIBMTP_ERROR("LIBMTP PANIC: Could not open session! " "(Return code %d)\n Try to reset the device.\n", ret); usb_release_interface(ptp_usb->handle, (int) ptp_usb->interface); return LIBMTP_ERROR_CONNECTING; } /* OK configured properly */ *usbinfo = (void *) ptp_usb; return LIBMTP_ERROR_NONE; } void close_device (PTP_USB *ptp_usb, PTPParams *params) { if (ptp_closesession(params)!=PTP_RC_OK) LIBMTP_ERROR("ERROR: Could not close session!\n"); close_usb(ptp_usb); } void set_usb_device_timeout(PTP_USB *ptp_usb, int timeout) { ptp_usb->timeout = timeout; } void get_usb_device_timeout(PTP_USB *ptp_usb, int *timeout) { *timeout = ptp_usb->timeout; } int guess_usb_speed(PTP_USB *ptp_usb) { int bytes_per_second; /* * We don't know the actual speeds so these are rough guesses * from the info you can find here: * http://en.wikipedia.org/wiki/USB#Transfer_rates * http://www.barefeats.com/usb2.html */ switch (ptp_usb->bcdusb & 0xFF00) { case 0x0100: /* 1.x USB versions let's say 1MiB/s */ bytes_per_second = 1*1024*1024; break; case 0x0200: case 0x0300: /* USB 2.0 nominal speed 18MiB/s */ /* USB 3.0 won't be worse? */ bytes_per_second = 18*1024*1024; break; default: /* Half-guess something? */ bytes_per_second = 1*1024*1024; break; } return bytes_per_second; } static int usb_clear_stall_feature(PTP_USB* ptp_usb, int ep) { return (usb_control_msg(ptp_usb->handle, USB_RECIP_ENDPOINT, USB_REQ_CLEAR_FEATURE, USB_FEATURE_HALT, ep, NULL, 0, ptp_usb->timeout)); } static int usb_get_endpoint_status(PTP_USB* ptp_usb, int ep, uint16_t* status) { return (usb_control_msg(ptp_usb->handle, USB_DP_DTH|USB_RECIP_ENDPOINT, USB_REQ_GET_STATUS, USB_FEATURE_HALT, ep, (char *) status, 2, ptp_usb->timeout)); } libmtp-1.1.6-20-g1b9f164/src/util.h0000664000175000017500000000311712205614637016631 0ustar glowwormglowworm/* * \file util.h * Utilityfunctions. * * Copyright (C) 2005-2007 Linus Walleij * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef __MTP__UTIL__H #define __MTP__UTIL__H void data_dump(FILE *f, void *buf, uint32_t nbytes); void data_dump_ascii (FILE *f, void *buf, uint32_t n, uint32_t dump_boundry); #ifndef HAVE_STRNDUP char *strndup (const char *s, size_t n); #endif /** * Info macro */ #define LIBMTP_INFO(format, args...) \ do { \ if (LIBMTP_debug != 0) \ fprintf(stdout, "LIBMTP %s[%d]: " format, __FUNCTION__, __LINE__, ##args); \ else \ fprintf(stdout, format, ##args); \ } while (0) /** * Error macro */ #define LIBMTP_ERROR(format, args...) \ do { \ if (LIBMTP_debug != 0) \ fprintf(stderr, "LIBMTP %s[%d]: " format, __FUNCTION__, __LINE__, ##args); \ else \ fprintf(stderr, format, ##args); \ } while (0) #endif //__MTP__UTIL__H libmtp-1.1.6-20-g1b9f164/src/gphoto2-sync.sh0000775000175000017500000000172612205614637020402 0ustar glowwormglowworm#!/bin/sh #set -e srcdir=`dirname $0` # Get sources from gphoto2 SVN WGET=`which wget` if [ "x$WGET" != "x" ]; then wget -O tmpfile http://sourceforge.net/p/gphoto/code/14266/tree/trunk/libgphoto2/camlibs/ptp2/ptp.c?format=raw mv tmpfile ptp.c.gphoto2 wget -O tmpfile tmpfile http://sourceforge.net/p/gphoto/code/14266/tree/trunk/libgphoto2/camlibs/ptp2/ptp.h?format=raw mv tmpfile ptp.h.gphoto2 wget -O tmpfile tmpfile http://sourceforge.net/p/gphoto/code/14266/tree/trunk/libgphoto2/camlibs/ptp2/ptp-pack.c?format=raw mv tmpfile ptp-pack.c.gphoto2 wget -O tmpfile tmpfile http://sourceforge.net/p/gphoto/code/14266/tree/trunk/libgphoto2/camlibs/ptp2/library.c?format=raw mv tmpfile library.c.gphoto2 wget -O tmpfile tmpfile http://sourceforge.net/p/gphoto/code/14266/tree/trunk/libgphoto2/camlibs/ptp2/music-players.h?format=raw mv tmpfile music-players.h.gphoto2 else echo "Could not sync to gphoto2. No WGET." fi echo "Finished!" libmtp-1.1.6-20-g1b9f164/src/unicode.c0000664000175000017500000001256512205614637017304 0ustar glowwormglowworm/** * \file unicode.c * * This file contains general Unicode string manipulation functions. * It mainly consist of functions for converting between UCS-2 (used on * the devices) and UTF-8 (used by several applications). * * For a deeper understanding of Unicode encoding formats see the * Wikipedia entries for * UTF-16/UCS-2 * and UTF-8. * * Copyright (C) 2005-2009 Linus Walleij * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * */ #include "config.h" #include #include #ifdef HAVE_ICONV #include "iconv.h" #else #error "libmtp unicode.c needs fixing to work without iconv()!" #endif #include "libmtp.h" #include "unicode.h" #include "util.h" #include "ptp.h" /** * The size of the buffer (in characters) used for creating string copies. */ #define STRING_BUFFER_LENGTH 1024 /** * Gets the length (in characters, not bytes) of a unicode * UCS-2 string, eg a string which physically is 0x00 0x41 0x00 0x00 * will return a value of 1. * * @param unicstr a UCS-2 Unicode string * @return the length of the string, in number of characters. If you * want to know the length in bytes, multiply this by two and * add two (for zero terminator). */ int ucs2_strlen(uint16_t const * const unicstr) { int length; /* Unicode strings are terminated with 2 * 0x00 */ for(length = 0; unicstr[length] != 0x0000U; length ++); return length; } /** * Converts a big-endian UTF-16 2-byte string * to a UTF-8 string. Actually just a UCS-2 internal conversion * routine that strips off the BOM if there is one. * * @param device a pointer to the current device. * @param unicstr the UTF-16 unicode string to convert * @return a UTF-8 string. */ char *utf16_to_utf8(LIBMTP_mtpdevice_t *device, const uint16_t *unicstr) { PTPParams *params = (PTPParams *) device->params; char *stringp = (char *) unicstr; char loclstr[STRING_BUFFER_LENGTH*3+1]; // UTF-8 encoding is max 3 bytes per UCS2 char. char *locp = loclstr; size_t nconv; size_t convlen = (ucs2_strlen(unicstr)+1) * sizeof(uint16_t); // UCS-2 is 16 bit wide, include terminator size_t convmax = STRING_BUFFER_LENGTH*3; loclstr[0]='\0'; /* Do the conversion. */ nconv = iconv(params->cd_ucs2_to_locale, &stringp, &convlen, &locp, &convmax); if (nconv == (size_t) -1) { // Return partial string anyway. *locp = '\0'; } loclstr[STRING_BUFFER_LENGTH*3] = '\0'; // Strip off any BOM, it's totally useless... if ((uint8_t) loclstr[0] == 0xEFU && (uint8_t) loclstr[1] == 0xBBU && (uint8_t) loclstr[2] == 0xBFU) { return strdup(loclstr+3); } return strdup(loclstr); } /** * Converts a UTF-8 string to a big-endian UTF-16 2-byte string * Actually just a UCS-2 internal conversion. * * @param device a pointer to the current device. * @param localstr the UTF-8 unicode string to convert * @return a UTF-16 string. */ uint16_t *utf8_to_utf16(LIBMTP_mtpdevice_t *device, const char *localstr) { PTPParams *params = (PTPParams *) device->params; char *stringp = (char *) localstr; // cast away "const" char unicstr[(STRING_BUFFER_LENGTH+1)*2]; // UCS2 encoding is 2 bytes per UTF-8 char. char *unip = unicstr; size_t nconv = 0; size_t convlen = strlen(localstr)+1; // utf8 bytes, include terminator size_t convmax = STRING_BUFFER_LENGTH*2; unicstr[0]='\0'; unicstr[1]='\0'; /* Do the conversion. */ nconv = iconv(params->cd_locale_to_ucs2, &stringp, &convlen, &unip, &convmax); if (nconv == (size_t) -1) { // Return partial string anyway. unip[0] = '\0'; unip[1] = '\0'; } // make sure the string is null terminated unicstr[STRING_BUFFER_LENGTH*2] = '\0'; unicstr[STRING_BUFFER_LENGTH*2+1] = '\0'; // allocate the string to be returned // Note: can't use strdup since every other byte is a null byte int ret_len = ucs2_strlen((uint16_t*)unicstr)*sizeof(uint16_t)+2; uint16_t* ret = malloc(ret_len); memcpy(ret,unicstr,(size_t)ret_len); return ret; } /** * This helper function simply removes any consecutive chars * > 0x7F and replace then with an underscore. In UTF-8 * consequtive chars > 0x7F represent one single character so * it has to be done like this (and it's elegant). It will only * shrink the string in size so no copying is needed. */ void strip_7bit_from_utf8(char *str) { int i,j,k; i = 0; j = 0; k = strlen(str); while (i < k) { if ((uint8_t) str[i] > 0x7FU) { str[j] = '_'; i++; // Skip over any consequtive > 0x7F chars. while((uint8_t) str[i] > 0x7FU) { i++; } } else { str[j] = str[i]; i++; } j++; } // Terminate stripped string... str[j] = '\0'; } libmtp-1.1.6-20-g1b9f164/src/libusb-glue.h0000664000175000017500000001466512205614637020100 0ustar glowwormglowworm/** * \file libusb-glue.h * Low-level USB interface glue towards libusb. * * Copyright (C) 2005-2007 Richard A. Low * Copyright (C) 2005-2012 Linus Walleij * Copyright (C) 2006-2011 Marcus Meissner * Copyright (C) 2007 Ted Bullock * Copyright (C) 2008 Chris Bagwell * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Created by Richard Low on 24/12/2005. * Modified by Linus Walleij * */ #ifndef LIBUSB_GLUE_H #define LIBUSB_GLUE_H #include "ptp.h" #ifdef HAVE_LIBUSB1 #include #endif #ifdef HAVE_LIBUSB0 #include #endif #ifdef HAVE_LIBOPENUSB #include #endif #include "libmtp.h" #include "device-flags.h" /* Make functions available for C++ */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** * Debug macro */ #define LIBMTP_USB_DEBUG(format, args...) \ do { \ if ((LIBMTP_debug & LIBMTP_DEBUG_USB) != 0) \ fprintf(stdout, "LIBMTP %s[%d]: " format, __FUNCTION__, __LINE__, ##args); \ } while (0) #define LIBMTP_USB_DATA(buffer, length, base) \ do { \ if ((LIBMTP_debug & LIBMTP_DEBUG_DATA) != 0) \ data_dump_ascii (stdout, buffer, length, base); \ } while (0) #ifdef HAVE_LIBUSB1 #define USB_BULK_READ libusb_bulk_transfer #define USB_BULK_WRITE libusb_bulk_transfer #endif #ifdef HAVE_LIBUSB0 #define USB_BULK_READ usb_bulk_read #define USB_BULK_WRITE usb_bulk_write #endif #ifdef HAVE_LIBOPENUSB #define USB_BULK_READ openusb_bulk_xfer #define USB_BULK_WRITE openusb_bulk_xfer #endif /** * Internal USB struct. */ typedef struct _PTP_USB PTP_USB; struct _PTP_USB { PTPParams *params; #ifdef HAVE_LIBUSB1 libusb_device_handle* handle; #endif #ifdef HAVE_LIBUSB0 usb_dev_handle* handle; #endif #ifdef HAVE_LIBOPENUSB openusb_dev_handle_t* handle; #endif uint8_t config; uint8_t interface; uint8_t altsetting; int inep; int inep_maxpacket; int outep; int outep_maxpacket; int intep; /** File transfer callbacks and counters */ int callback_active; int timeout; uint16_t bcdusb; uint64_t current_transfer_total; uint64_t current_transfer_complete; LIBMTP_progressfunc_t current_transfer_callback; void const * current_transfer_callback_data; /** Any special device flags, only used internally */ LIBMTP_raw_device_t rawdevice; }; void dump_usbinfo(PTP_USB *ptp_usb); const char *get_playlist_extension(PTP_USB *ptp_usb); void close_device(PTP_USB *ptp_usb, PTPParams *params); LIBMTP_error_number_t configure_usb_device(LIBMTP_raw_device_t *device, PTPParams *params, void **usbinfo); void set_usb_device_timeout(PTP_USB *ptp_usb, int timeout); void get_usb_device_timeout(PTP_USB *ptp_usb, int *timeout); int guess_usb_speed(PTP_USB *ptp_usb); /* Flag check macros */ #define FLAG_BROKEN_MTPGETOBJPROPLIST_ALL(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL) #define FLAG_UNLOAD_DRIVER(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_UNLOAD_DRIVER) #define FLAG_BROKEN_MTPGETOBJPROPLIST(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST) #define FLAG_NO_ZERO_READS(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_NO_ZERO_READS) #define FLAG_IRIVER_OGG_ALZHEIMER(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_IRIVER_OGG_ALZHEIMER) #define FLAG_ONLY_7BIT_FILENAMES(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_ONLY_7BIT_FILENAMES) #define FLAG_NO_RELEASE_INTERFACE(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_NO_RELEASE_INTERFACE) #define FLAG_IGNORE_HEADER_ERRORS(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_IGNORE_HEADER_ERRORS) #define FLAG_BROKEN_SET_OBJECT_PROPLIST(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_BROKEN_SET_OBJECT_PROPLIST) #define FLAG_OGG_IS_UNKNOWN(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_OGG_IS_UNKNOWN) #define FLAG_BROKEN_SET_SAMPLE_DIMENSIONS(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_BROKEN_SET_SAMPLE_DIMENSIONS) #define FLAG_ALWAYS_PROBE_DESCRIPTOR(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_ALWAYS_PROBE_DESCRIPTOR) #define FLAG_PLAYLIST_SPL_V1(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_PLAYLIST_SPL_V1) #define FLAG_PLAYLIST_SPL_V2(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_PLAYLIST_SPL_V2) #define FLAG_PLAYLIST_SPL(a) \ ((a)->rawdevice.device_entry.device_flags & (DEVICE_FLAG_PLAYLIST_SPL_V1 | DEVICE_FLAG_PLAYLIST_SPL_V2)) #define FLAG_CANNOT_HANDLE_DATEMODIFIED(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED) #define FLAG_BROKEN_SEND_OBJECT_PROPLIST(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST) #define FLAG_BROKEN_BATTERY_LEVEL(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_BROKEN_BATTERY_LEVEL) #define FLAG_FLAC_IS_UNKNOWN(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_FLAC_IS_UNKNOWN) #define FLAG_UNIQUE_FILENAMES(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_UNIQUE_FILENAMES) #define FLAG_SWITCH_MODE_BLACKBERRY(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_SWITCH_MODE_BLACKBERRY) #define FLAG_LONG_TIMEOUT(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_LONG_TIMEOUT) #define FLAG_FORCE_RESET_ON_CLOSE(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_FORCE_RESET_ON_CLOSE) #define FLAG_BROKEN_GET_OBJECT_PROPVAL(a) \ ((a)->rawdevice.device_entry.device_flags & DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL) /* connect_first_device return codes */ #define PTP_CD_RC_CONNECTED 0 #define PTP_CD_RC_NO_DEVICES 1 #define PTP_CD_RC_ERROR_CONNECTING 2 #ifdef __cplusplus } #endif /* __cplusplus */ #endif // LIBUSB-GLUE_H libmtp-1.1.6-20-g1b9f164/src/device-flags.h0000664000175000017500000003214512205614637020210 0ustar glowwormglowworm/** * \file device-flags.h * Special device flags to deal with bugs in specific devices. * * Copyright (C) 2005-2007 Richard A. Low * Copyright (C) 2005-2012 Linus Walleij * Copyright (C) 2006-2007 Marcus Meissner * Copyright (C) 2007 Ted Bullock * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * This file is supposed to be included by both libmtp and libgphoto2. */ /** * These flags are used to indicate if some or other * device need special treatment. These should be possible * to concatenate using logical OR so please use one bit per * feature and lets pray we don't need more than 32 bits... */ #define DEVICE_FLAG_NONE 0x00000000 /** * This means that the PTP_OC_MTP_GetObjPropList is broken * in the sense that it won't return properly formatted metadata * for ALL files on the device when you request an object * property list for object 0xFFFFFFFF with parameter 3 likewise * set to 0xFFFFFFFF. Compare to * DEVICE_FLAG_BROKEN_MTPGETOBJECTPROPLIST which only signify * that it's broken when getting metadata for a SINGLE object. * A typical way the implementation may be broken is that it * may not return a proper count of the objects, and sometimes * (like on the ZENs) objects are simply missing from the list * if you use this. Sometimes it has been used incorrectly to * mask bugs in the code (like handling transactions of data * with size given to -1 (0xFFFFFFFFU), in that case please * help us remove it now the code is fixed. Sometimes this is * used because getting all the objects is just too slow and * the USB transaction will time out if you use this command. */ #define DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL 0x00000001 /** * This means that under Linux, another kernel module may * be using this device's USB interface, so we need to detach * it if it is. Typically this is on dual-mode devices that * will present both an MTP compliant interface and device * descriptor *and* a USB mass storage interface. If the USB * mass storage interface is in use, other apps (like our * userspace libmtp through libusb access path) cannot get in * and get cosy with it. So we can remove the offending * application. Typically this means you have to run the program * as root as well. */ #define DEVICE_FLAG_UNLOAD_DRIVER 0x00000002 /** * This means that the PTP_OC_MTP_GetObjPropList (9805) * is broken in some way, either it doesn't work at all * (as for Android devices) or it won't properly return all * object properties if parameter 3 is set to 0xFFFFFFFFU. */ #define DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST 0x00000004 /** * This means the device doesn't send zero packets to indicate * end of transfer when the transfer boundary occurs at a * multiple of 64 bytes (the USB 1.1 endpoint size). Instead, * exactly one extra byte is sent at the end of the transfer * if the size is an integer multiple of USB 1.1 endpoint size * (64 bytes). * * This behaviour is most probably a workaround due to the fact * that the hardware USB slave controller in the device cannot * handle zero writes at all, and the usage of the USB 1.1 * endpoint size is due to the fact that the device will "gear * down" on a USB 1.1 hub, and since 64 bytes is a multiple of * 512 bytes, it will work with USB 1.1 and USB 2.0 alike. */ #define DEVICE_FLAG_NO_ZERO_READS 0x00000008 /** * This flag means that the device is prone to forgetting the * OGG container file type, so that libmtp must look at the * filename extensions in order to determine that a file is * actually OGG. This is a clear and present firmware bug, and * while firmware bugs should be fixed in firmware, we like * OGG so much that we back it by introducing this flag. * The error has only been seen on iriver devices. Turning this * flag on won't hurt anything, just that the check against * filename extension will be done for files of "unknown" type. * If the player does not even know (reports) that it supports * ogg even though it does, please use the stronger * OGG_IS_UNKNOWN flag, which will forcedly support ogg on * anything with the .ogg filename extension. */ #define DEVICE_FLAG_IRIVER_OGG_ALZHEIMER 0x00000010 /** * This flag indicates a limitation in the filenames a device * can accept - they must be 7 bit (all chars <= 127/0x7F). * It was found first on the Philips Shoqbox, and is a deviation * from the PTP standard which mandates that any unicode chars * may be used for filenames. I guess this is caused by a 7bit-only * filesystem being used intrinsically on the device. */ #define DEVICE_FLAG_ONLY_7BIT_FILENAMES 0x00000020 /** * This flag indicates that the device will lock up if you * try to get status of endpoints and/or release the interface * when closing the device. This fixes problems with SanDisk * Sansa devices especially. It may be a side-effect of a * Windows behaviour of never releasing interfaces. */ #define DEVICE_FLAG_NO_RELEASE_INTERFACE 0x00000040 /** * This flag was introduced with the advent of Creative ZEN * 8GB. The device sometimes return a broken PTP header * like this: < 1502 0000 0200 01d1 02d1 01d2 > * the latter 6 bytes (representing "code" and "transaction ID") * contain junk. This is breaking the PTP/MTP spec but works * on Windows anyway, probably because the Windows implementation * does not check that these bytes are valid. To interoperate * with devices like this, we need this flag to emulate the * Windows bug. Broken headers has also been found in the * Aricent MTP stack. */ #define DEVICE_FLAG_IGNORE_HEADER_ERRORS 0x00000080 /** * The Motorola RAZR2 V8 (others?) has broken set object * proplist causing the metadata setting to fail. (The * set object prop to set individual properties work on * this device, but the metadata is plain ignored on * tracks, though e.g. playlist names can be set.) */ #define DEVICE_FLAG_BROKEN_SET_OBJECT_PROPLIST 0x00000100 /** * The Samsung YP-T10 think Ogg files shall be sent with * the "unknown" (PTP_OFC_Undefined) file type, this gives a * side effect that is a combination of the iRiver Ogg Alzheimer * problem (have to recognized Ogg files on file extension) * and a need to report the Ogg support (the device itself does * not properly claim to support it) and need to set filetype * to unknown when storing Ogg files, even though they're not * actually unknown. Later iRivers seem to need this flag since * they do not report to support OGG even though they actually * do. Often the device supports OGG in USB mass storage mode, * then the firmware simply miss to declare metadata support * for OGG properly. */ #define DEVICE_FLAG_OGG_IS_UNKNOWN 0x00000200 /** * The Creative Zen is quite unstable in libmtp but seems to * be better with later firmware versions. However, it still * frequently crashes when setting album art dimensions. This * flag disables setting the dimensions (which seems to make * no difference to how the graphic is displayed). */ #define DEVICE_FLAG_BROKEN_SET_SAMPLE_DIMENSIONS 0x00000400 /** * Some devices, particularly SanDisk Sansas, need to always * have their "OS Descriptor" probed in order to work correctly. * This flag provides that extra massage. */ #define DEVICE_FLAG_ALWAYS_PROBE_DESCRIPTOR 0x00000800 /** * Samsung has implimented its own playlist format as a .spl file * stored in the normal file system, rather than a proper mtp * playlist. There are multiple versions of the .spl format * identified by a line in the file: VERSION X.XX * Version 1.00 is just a simple playlist. */ #define DEVICE_FLAG_PLAYLIST_SPL_V1 0x00001000 /** * Samsung has implimented its own playlist format as a .spl file * stored in the normal file system, rather than a proper mtp * playlist. There are multiple versions of the .spl format * identified by a line in the file: VERSION X.XX * Version 2.00 is playlist but allows DNSe sound settings * to be stored, per playlist. */ #define DEVICE_FLAG_PLAYLIST_SPL_V2 0x00002000 /** * The Sansa E250 is know to have this problem which is actually * that the device claims that property PTP_OPC_DateModified * is read/write but will still fail to update it. It can only * be set properly the first time a file is sent. */ #define DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED 0x00004000 /** * This avoids use of the send object proplist which * is used when creating new objects (not just updating) * The DEVICE_FLAG_BROKEN_SET_OBJECT_PROPLIST is related * but only concerns the case where the object proplist * is sent in to update an existing object. The Toshiba * Gigabeat MEU202 for example has this problem. */ #define DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST 0x00008000 /** * Devices that cannot support reading out battery * level. */ #define DEVICE_FLAG_BROKEN_BATTERY_LEVEL 0x00010000 /** * Devices that send "ObjectDeleted" events after deletion * of images. (libgphoto2) */ #define DEVICE_FLAG_DELETE_SENDS_EVENT 0x00020000 /** * Cameras that can capture images. (libgphoto2) */ #define DEVICE_FLAG_CAPTURE 0x00040000 /** * Cameras that can capture images. (libgphoto2) */ #define DEVICE_FLAG_CAPTURE_PREVIEW 0x00080000 /** * Nikon broken capture support without proper ObjectAdded events. * (libgphoto2) */ #define DEVICE_FLAG_NIKON_BROKEN_CAPTURE 0x00100000 /** * Broken capture support where cameras do not send CaptureComplete events. * (libgphoto2) */ #define DEVICE_FLAG_NO_CAPTURE_COMPLETE 0x00400000 /** * Direct PTP match required. * (libgphoto2) */ #define DEVICE_FLAG_MATCH_PTP_INTERFACE 0x00800000 /** * This flag is like DEVICE_FLAG_OGG_IS_UNKNOWN but for FLAC * files instead. Using the unknown filetype for FLAC files. */ #define DEVICE_FLAG_FLAC_IS_UNKNOWN 0x01000000 /** * Device needs unique filenames, no two files can be * named the same string. */ #define DEVICE_FLAG_UNIQUE_FILENAMES 0x02000000 /** * This flag performs some random magic on the BlackBerry * device to switch from USB mass storage to MTP mode we think. */ #define DEVICE_FLAG_SWITCH_MODE_BLACKBERRY 0x04000000 /** * This flag indicates that the device need an extra long * timeout on some operations. */ #define DEVICE_FLAG_LONG_TIMEOUT 0x08000000 /** * This flag indicates that the device need an explicit * USB reset after each connection. Some devices don't * like this, so it's not done by default. */ #define DEVICE_FLAG_FORCE_RESET_ON_CLOSE 0x10000000 /** * Early Creative Zen (etc) models actually only support * command 9805 (Get object property list) and will hang * if you try to get individual properties of an object. */ #define DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL 0x20000000 /** * It seems that some devices return an bad data when * using the GetObjectInfo operation. So in these cases * we prefer to override the PTP-compatible object infos * with the MTP property list. * * For example Some Samsung Galaxy S devices contain an MTP * stack that present the ObjectInfo in 64 bit instead of * 32 bit. */ #define DEVICE_FLAG_PROPLIST_OVERRIDES_OI 0x40000000 /** * All these bug flags need to be set on SONY NWZ Walkman * players, and will be autodetected on unknown devices * by detecting the vendor extension descriptor "sony.net" */ #define DEVICE_FLAGS_SONY_NWZ_BUGS \ (DEVICE_FLAG_UNLOAD_DRIVER | \ DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | \ DEVICE_FLAG_UNIQUE_FILENAMES | \ DEVICE_FLAG_FORCE_RESET_ON_CLOSE ) /** * All these bug flags need to be set on Android devices, * they claim to support MTP operations they actually * cannot handle, especially 9805 (Get object property list). * These are auto-assigned to devices reporting * "android.com" in their device extension descriptor. */ #define DEVICE_FLAGS_ANDROID_BUGS \ (DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | \ DEVICE_FLAG_BROKEN_SET_OBJECT_PROPLIST | \ DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST | \ DEVICE_FLAG_UNLOAD_DRIVER | \ DEVICE_FLAG_LONG_TIMEOUT ) /** * All these bug flags appear on a number of SonyEricsson * devices including Android devices not using the stock * Android 4.0+ (Ice Cream Sandwich) MTP stack. It is highly * supected that these bugs comes from an MTP implementation * from Aricent, so it is called the Aricent bug flags as a * shorthand. Especially the header errors that need to be * ignored is typical for this stack. * * After some guesswork we auto-assign these bug flags to * devices that present the "microsoft.com/WPDNA", and * "sonyericsson.com/SE" but NOT the "android.com" * descriptor. */ #define DEVICE_FLAGS_ARICENT_BUGS \ (DEVICE_FLAG_IGNORE_HEADER_ERRORS | \ DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST | \ DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST ) libmtp-1.1.6-20-g1b9f164/src/libmtp.sym0000664000175000017500000000540512205614637017526 0ustar glowwormglowwormLIBMTP_Set_Debug LIBMTP_Init LIBMTP_Get_Supported_Devices_List LIBMTP_Detect_Raw_Devices LIBMTP_Check_Specific_Device LIBMTP_Open_Raw_Device LIBMTP_Open_Raw_Device_Uncached LIBMTP_Get_First_Device LIBMTP_Get_Connected_Devices LIBMTP_Number_Devices_In_List LIBMTP_Release_Device_List LIBMTP_Release_Device LIBMTP_Dump_Device_Info LIBMTP_Reset_Device LIBMTP_Get_Manufacturername LIBMTP_Get_Modelname LIBMTP_Get_Serialnumber LIBMTP_Get_Deviceversion LIBMTP_Get_Friendlyname LIBMTP_Set_Friendlyname LIBMTP_Get_Syncpartner LIBMTP_Set_Syncpartner LIBMTP_Get_Batterylevel LIBMTP_Get_Secure_Time LIBMTP_Get_Device_Certificate LIBMTP_Get_Supported_Filetypes LIBMTP_Get_Errorstack LIBMTP_Clear_Errorstack LIBMTP_Dump_Errorstack LIBMTP_Get_Storage LIBMTP_Format_Storage LIBMTP_Get_String_From_Object LIBMTP_Get_u64_From_Object LIBMTP_Get_u32_From_Object LIBMTP_Get_u16_From_Object LIBMTP_Get_u8_From_Object LIBMTP_Set_Object_String LIBMTP_Set_Object_u32 LIBMTP_Set_Object_u16 LIBMTP_Set_Object_u8 LIBMTP_Get_Property_Description LIBMTP_Is_Property_Supported LIBMTP_Get_Allowed_Property_Values LIBMTP_destroy_allowed_values_t LIBMTP_new_file_t LIBMTP_destroy_file_t LIBMTP_Get_Filetype_Description LIBMTP_Get_Filelisting LIBMTP_Get_Filelisting_With_Callback LIBMTP_Get_Files_And_Folders LIBMTP_Get_Filemetadata LIBMTP_Get_File_To_File LIBMTP_Get_File_To_File_Descriptor LIBMTP_Get_File_To_Handler LIBMTP_Send_File_From_File LIBMTP_Send_File_From_File_Descriptor LIBMTP_Send_File_From_Handler LIBMTP_new_filesampledata_t LIBMTP_destroy_filesampledata_t LIBMTP_Get_Representative_Sample_Format LIBMTP_Send_Representative_Sample LIBMTP_Get_Representative_Sample LIBMTP_new_track_t LIBMTP_destroy_track_t LIBMTP_Get_Tracklisting LIBMTP_Get_Tracklisting_With_Callback LIBMTP_Get_Tracklisting_With_Callback_For_Storage LIBMTP_Get_Trackmetadata LIBMTP_Get_Track_To_File LIBMTP_Get_Track_To_File_Descriptor LIBMTP_Get_Track_To_Handler LIBMTP_Send_Track_From_File LIBMTP_Send_Track_From_File_Descriptor LIBMTP_Send_Track_From_Handler LIBMTP_Update_Track_Metadata LIBMTP_Track_Exists LIBMTP_new_folder_t LIBMTP_destroy_folder_t LIBMTP_Get_Folder_List LIBMTP_Get_Folder_List_For_Storage LIBMTP_Find_Folder LIBMTP_Create_Folder LIBMTP_new_playlist_t LIBMTP_destroy_playlist_t LIBMTP_Get_Playlist_List LIBMTP_Get_Playlist LIBMTP_Create_New_Playlist LIBMTP_Update_Playlist LIBMTP_new_album_t LIBMTP_destroy_album_t LIBMTP_Get_Album_List LIBMTP_Get_Album_List_For_Storage LIBMTP_Get_Album LIBMTP_Create_New_Album LIBMTP_Update_Album LIBMTP_Delete_Object LIBMTP_Set_File_Name LIBMTP_Set_Folder_Name LIBMTP_Set_Track_Name LIBMTP_Set_Playlist_Name LIBMTP_Set_Album_Name LIBMTP_Set_Object_Filename LIBMTP_Get_Thumbnail LIBMTP_Read_Event LIBMTP_GetPartialObject LIBMTP_SendPartialObject LIBMTP_BeginEditObject LIBMTP_EndEditObject LIBMTP_TruncateObject libmtp-1.1.6-20-g1b9f164/src/libmtp.c0000664000175000017500000114671012205614637017146 0ustar glowwormglowworm/** * \file libmtp.c * * Copyright (C) 2005-2011 Linus Walleij * Copyright (C) 2005-2008 Richard A. Low * Copyright (C) 2007 Ted Bullock * Copyright (C) 2007 Tero Saarni * Copyright (C) 2008 Florent Mertens * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * This file provides an interface "glue" to the underlying * PTP implementation from libgphoto2. It uses some local * code to convert from/to UTF-8 (stored in unicode.c/.h) * and some small utility functions, mainly for debugging * (stored in util.c/.h). * * The three PTP files (ptp.c, ptp.h and ptp-pack.c) are * plain copied from the libhphoto2 codebase. * * The files libusb-glue.c/.h are just what they say: an * interface to libusb for the actual, physical USB traffic. */ #include "config.h" #include "libmtp.h" #include "unicode.h" #include "ptp.h" #include "libusb-glue.h" #include "device-flags.h" #include "playlist-spl.h" #include "util.h" #include "mtpz.h" #include #include #include #include #include #include #include #include #include #ifdef _MSC_VER // For MSVC++ #define USE_WINDOWS_IO_H #include #endif /** * Global debug level * We use a flag system to enable a part of logs. * * The LIBMTP_DEBUG environment variable sets the debug flags for any binary * that uses libmtp and calls LIBMTP_Init. The value can be given in decimal * (must not start with "0" or it will be interpreted in octal), or in * hexadecimal (must start with "0x"). * * The value "-1" enables all debug flags. * * Some of the utilities in examples/ also take a command-line flag "-d" that * enables LIBMTP_DEBUG_PTP and LIBMTP_DEBUG_DATA (same as setting * LIBMTP_DEBUG=9). * * Flags (combine by adding the hex values): * 0x00 [0000 0000] : LIBMTP_DEBUG_NONE : no debug (default) * 0x01 [0000 0001] : LIBMTP_DEBUG_PTP : PTP debug * 0x02 [0000 0010] : LIBMTP_DEBUG_PLST : Playlist debug * 0x04 [0000 0100] : LIBMTP_DEBUG_USB : USB debug * 0x08 [0000 1000] : LIBMTP_DEBUG_DATA : USB data debug * * (Please keep this list in sync with libmtp.h.) */ int LIBMTP_debug = LIBMTP_DEBUG_NONE; /* * This is a mapping between libmtp internal MTP filetypes and * the libgphoto2/PTP equivalent defines. We need this because * otherwise the libmtp.h device has to be dependent on ptp.h * to be installed too, and we don't want that. */ //typedef struct filemap_struct filemap_t; typedef struct filemap_struct { char *description; /**< Text description for the file type */ LIBMTP_filetype_t id; /**< LIBMTP internal type for the file type */ uint16_t ptp_id; /**< PTP ID for the filetype */ struct filemap_struct *next; } filemap_t; /* * This is a mapping between libmtp internal MTP properties and * the libgphoto2/PTP equivalent defines. We need this because * otherwise the libmtp.h device has to be dependent on ptp.h * to be installed too, and we don't want that. */ typedef struct propertymap_struct { char *description; /**< Text description for the property */ LIBMTP_property_t id; /**< LIBMTP internal type for the property */ uint16_t ptp_id; /**< PTP ID for the property */ struct propertymap_struct *next; } propertymap_t; // Global variables // This holds the global filetype mapping table static filemap_t *filemap = NULL; // This holds the global property mapping table static propertymap_t *propertymap = NULL; /* * Forward declarations of local (static) functions. */ static int register_filetype(char const * const description, LIBMTP_filetype_t const id, uint16_t const ptp_id); static void init_filemap(); static int register_property(char const * const description, LIBMTP_property_t const id, uint16_t const ptp_id); static void init_propertymap(); static void add_error_to_errorstack(LIBMTP_mtpdevice_t *device, LIBMTP_error_number_t errornumber, char const * const error_text); static void add_ptp_error_to_errorstack(LIBMTP_mtpdevice_t *device, uint16_t ptp_error, char const * const error_text); static void flush_handles(LIBMTP_mtpdevice_t *device); static void get_handles_recursively(LIBMTP_mtpdevice_t *device, PTPParams *params, uint32_t storageid, uint32_t parent); static void free_storage_list(LIBMTP_mtpdevice_t *device); static int sort_storage_by(LIBMTP_mtpdevice_t *device, int const sortby); static uint32_t get_writeable_storageid(LIBMTP_mtpdevice_t *device, uint64_t fitsize); static int get_storage_freespace(LIBMTP_mtpdevice_t *device, LIBMTP_devicestorage_t *storage, uint64_t *freespace); static int check_if_file_fits(LIBMTP_mtpdevice_t *device, LIBMTP_devicestorage_t *storage, uint64_t const filesize); static uint16_t map_libmtp_type_to_ptp_type(LIBMTP_filetype_t intype); static LIBMTP_filetype_t map_ptp_type_to_libmtp_type(uint16_t intype); static uint16_t map_libmtp_property_to_ptp_property(LIBMTP_property_t inproperty); static LIBMTP_property_t map_ptp_property_to_libmtp_property(uint16_t intype); static int get_device_unicode_property(LIBMTP_mtpdevice_t *device, char **unicstring, uint16_t property); static uint16_t adjust_u16(uint16_t val, PTPObjectPropDesc *opd); static uint32_t adjust_u32(uint32_t val, PTPObjectPropDesc *opd); static char *get_iso8601_stamp(void); static char *get_string_from_object(LIBMTP_mtpdevice_t *device, uint32_t const object_id, uint16_t const attribute_id); static uint64_t get_u64_from_object(LIBMTP_mtpdevice_t *device,uint32_t const object_id, uint16_t const attribute_id, uint64_t const value_default); static uint32_t get_u32_from_object(LIBMTP_mtpdevice_t *device,uint32_t const object_id, uint16_t const attribute_id, uint32_t const value_default); static uint16_t get_u16_from_object(LIBMTP_mtpdevice_t *device, uint32_t const object_id, uint16_t const attribute_id, uint16_t const value_default); static uint8_t get_u8_from_object(LIBMTP_mtpdevice_t *device, uint32_t const object_id, uint16_t const attribute_id, uint8_t const value_default); static int set_object_string(LIBMTP_mtpdevice_t *device, uint32_t const object_id, uint16_t const attribute_id, char const * const string); static int set_object_u32(LIBMTP_mtpdevice_t *device, uint32_t const object_id, uint16_t const attribute_id, uint32_t const value); static int set_object_u16(LIBMTP_mtpdevice_t *device, uint32_t const object_id, uint16_t const attribute_id, uint16_t const value); static int set_object_u8(LIBMTP_mtpdevice_t *device, uint32_t const object_id, uint16_t const attribute_id, uint8_t const value); static void get_track_metadata(LIBMTP_mtpdevice_t *device, uint16_t objectformat, LIBMTP_track_t *track); static LIBMTP_folder_t *get_subfolders_for_folder(LIBMTP_folder_t *list, uint32_t parent); static int create_new_abstract_list(LIBMTP_mtpdevice_t *device, char const * const name, char const * const artist, char const * const composer, char const * const genre, uint32_t const parenthandle, uint32_t const storageid, uint16_t const objectformat, char const * const suffix, uint32_t * const newid, uint32_t const * const tracks, uint32_t const no_tracks); static int update_abstract_list(LIBMTP_mtpdevice_t *device, char const * const name, char const * const artist, char const * const composer, char const * const genre, uint32_t const objecthandle, uint16_t const objectformat, uint32_t const * const tracks, uint32_t const no_tracks); static int send_file_object_info(LIBMTP_mtpdevice_t *device, LIBMTP_file_t *filedata); static void add_object_to_cache(LIBMTP_mtpdevice_t *device, uint32_t object_id); static void update_metadata_cache(LIBMTP_mtpdevice_t *device, uint32_t object_id); static int set_object_filename(LIBMTP_mtpdevice_t *device, uint32_t object_id, uint16_t ptp_type, const char **newname); static char *generate_unique_filename(PTPParams* params, char const * const filename); static int check_filename_exists(PTPParams* params, char const * const filename); /** * These are to wrap the get/put handlers to convert from the MTP types to PTP types * in a reliable way */ typedef struct _MTPDataHandler { MTPDataGetFunc getfunc; MTPDataPutFunc putfunc; void *priv; } MTPDataHandler; static uint16_t get_func_wrapper(PTPParams* params, void* priv, unsigned long wantlen, unsigned char *data, unsigned long *gotlen); static uint16_t put_func_wrapper(PTPParams* params, void* priv, unsigned long sendlen, unsigned char *data, unsigned long *putlen); /** * Checks if a filename ends with ".ogg". Used in various * situations when the device has no idea that it support * OGG but still does. * * @param name string to be checked. * @return 0 if this does not end with ogg, any other * value means it does. */ static int has_ogg_extension(char *name) { char *ptype; if (name == NULL) return 0; ptype = strrchr(name,'.'); if (ptype == NULL) return 0; if (!strcasecmp (ptype, ".ogg")) return 1; return 0; } /** * Checks if a filename ends with ".flac". Used in various * situations when the device has no idea that it support * FLAC but still does. * * @param name string to be checked. * @return 0 if this does not end with flac, any other * value means it does. */ static int has_flac_extension(char *name) { char *ptype; if (name == NULL) return 0; ptype = strrchr(name,'.'); if (ptype == NULL) return 0; if (!strcasecmp (ptype, ".flac")) return 1; return 0; } /** * Create a new file mapping entry * @return a newly allocated filemapping entry. */ static filemap_t *new_filemap_entry() { filemap_t *filemap; filemap = (filemap_t *)malloc(sizeof(filemap_t)); if( filemap != NULL ) { filemap->description = NULL; filemap->id = LIBMTP_FILETYPE_UNKNOWN; filemap->ptp_id = PTP_OFC_Undefined; filemap->next = NULL; } return filemap; } /** * Register an MTP or PTP filetype for data retrieval * * @param description Text description of filetype * @param id libmtp internal filetype id * @param ptp_id PTP filetype id * @return 0 for success any other value means error. */ static int register_filetype(char const * const description, LIBMTP_filetype_t const id, uint16_t const ptp_id) { filemap_t *new = NULL, *current; // Has this LIBMTP filetype been registered before ? current = filemap; while (current != NULL) { if(current->id == id) { break; } current = current->next; } // Create the entry if(current == NULL) { new = new_filemap_entry(); if(new == NULL) { return 1; } new->id = id; if(description != NULL) { new->description = strdup(description); } new->ptp_id = ptp_id; // Add the entry to the list if(filemap == NULL) { filemap = new; } else { current = filemap; while (current->next != NULL ) current=current->next; current->next = new; } // Update the existing entry } else { if (current->description != NULL) { free(current->description); } current->description = NULL; if(description != NULL) { current->description = strdup(description); } current->ptp_id = ptp_id; } return 0; } static void init_filemap() { register_filetype("Folder", LIBMTP_FILETYPE_FOLDER, PTP_OFC_Association); register_filetype("MediaCard", LIBMTP_FILETYPE_MEDIACARD, PTP_OFC_MTP_MediaCard); register_filetype("RIFF WAVE file", LIBMTP_FILETYPE_WAV, PTP_OFC_WAV); register_filetype("ISO MPEG-1 Audio Layer 3", LIBMTP_FILETYPE_MP3, PTP_OFC_MP3); register_filetype("ISO MPEG-1 Audio Layer 2", LIBMTP_FILETYPE_MP2, PTP_OFC_MTP_MP2); register_filetype("Microsoft Windows Media Audio", LIBMTP_FILETYPE_WMA, PTP_OFC_MTP_WMA); register_filetype("Ogg container format", LIBMTP_FILETYPE_OGG, PTP_OFC_MTP_OGG); register_filetype("Free Lossless Audio Codec (FLAC)", LIBMTP_FILETYPE_FLAC, PTP_OFC_MTP_FLAC); register_filetype("Advanced Audio Coding (AAC)/MPEG-2 Part 7/MPEG-4 Part 3", LIBMTP_FILETYPE_AAC, PTP_OFC_MTP_AAC); register_filetype("MPEG-4 Part 14 Container Format (Audio Emphasis)", LIBMTP_FILETYPE_M4A, PTP_OFC_MTP_M4A); register_filetype("MPEG-4 Part 14 Container Format (Audio+Video Emphasis)", LIBMTP_FILETYPE_MP4, PTP_OFC_MTP_MP4); register_filetype("Audible.com Audio Codec", LIBMTP_FILETYPE_AUDIBLE, PTP_OFC_MTP_AudibleCodec); register_filetype("Undefined audio file", LIBMTP_FILETYPE_UNDEF_AUDIO, PTP_OFC_MTP_UndefinedAudio); register_filetype("Microsoft Windows Media Video", LIBMTP_FILETYPE_WMV, PTP_OFC_MTP_WMV); register_filetype("Audio Video Interleave", LIBMTP_FILETYPE_AVI, PTP_OFC_AVI); register_filetype("MPEG video stream", LIBMTP_FILETYPE_MPEG, PTP_OFC_MPEG); register_filetype("Microsoft Advanced Systems Format", LIBMTP_FILETYPE_ASF, PTP_OFC_ASF); register_filetype("Apple Quicktime container format", LIBMTP_FILETYPE_QT, PTP_OFC_QT); register_filetype("Undefined video file", LIBMTP_FILETYPE_UNDEF_VIDEO, PTP_OFC_MTP_UndefinedVideo); register_filetype("JPEG file", LIBMTP_FILETYPE_JPEG, PTP_OFC_EXIF_JPEG); register_filetype("JP2 file", LIBMTP_FILETYPE_JP2, PTP_OFC_JP2); register_filetype("JPX file", LIBMTP_FILETYPE_JPX, PTP_OFC_JPX); register_filetype("JFIF file", LIBMTP_FILETYPE_JFIF, PTP_OFC_JFIF); register_filetype("TIFF bitmap file", LIBMTP_FILETYPE_TIFF, PTP_OFC_TIFF); register_filetype("BMP bitmap file", LIBMTP_FILETYPE_BMP, PTP_OFC_BMP); register_filetype("GIF bitmap file", LIBMTP_FILETYPE_GIF, PTP_OFC_GIF); register_filetype("PICT bitmap file", LIBMTP_FILETYPE_PICT, PTP_OFC_PICT); register_filetype("Portable Network Graphics", LIBMTP_FILETYPE_PNG, PTP_OFC_PNG); register_filetype("Microsoft Windows Image Format", LIBMTP_FILETYPE_WINDOWSIMAGEFORMAT, PTP_OFC_MTP_WindowsImageFormat); register_filetype("VCalendar version 1", LIBMTP_FILETYPE_VCALENDAR1, PTP_OFC_MTP_vCalendar1); register_filetype("VCalendar version 2", LIBMTP_FILETYPE_VCALENDAR2, PTP_OFC_MTP_vCalendar2); register_filetype("VCard version 2", LIBMTP_FILETYPE_VCARD2, PTP_OFC_MTP_vCard2); register_filetype("VCard version 3", LIBMTP_FILETYPE_VCARD3, PTP_OFC_MTP_vCard3); register_filetype("Undefined Windows executable file", LIBMTP_FILETYPE_WINEXEC, PTP_OFC_MTP_UndefinedWindowsExecutable); register_filetype("Text file", LIBMTP_FILETYPE_TEXT, PTP_OFC_Text); register_filetype("HTML file", LIBMTP_FILETYPE_HTML, PTP_OFC_HTML); register_filetype("XML file", LIBMTP_FILETYPE_XML, PTP_OFC_MTP_XMLDocument); register_filetype("DOC file", LIBMTP_FILETYPE_DOC, PTP_OFC_MTP_MSWordDocument); register_filetype("XLS file", LIBMTP_FILETYPE_XLS, PTP_OFC_MTP_MSExcelSpreadsheetXLS); register_filetype("PPT file", LIBMTP_FILETYPE_PPT, PTP_OFC_MTP_MSPowerpointPresentationPPT); register_filetype("MHT file", LIBMTP_FILETYPE_MHT, PTP_OFC_MTP_MHTCompiledHTMLDocument); register_filetype("Firmware file", LIBMTP_FILETYPE_FIRMWARE, PTP_OFC_MTP_Firmware); register_filetype("Abstract Album file", LIBMTP_FILETYPE_ALBUM, PTP_OFC_MTP_AbstractAudioAlbum); register_filetype("Abstract Playlist file", LIBMTP_FILETYPE_PLAYLIST, PTP_OFC_MTP_AbstractAudioVideoPlaylist); register_filetype("Undefined filetype", LIBMTP_FILETYPE_UNKNOWN, PTP_OFC_Undefined); } /** * Returns the PTP filetype that maps to a certain libmtp internal file type. * @param intype the MTP library interface type * @return the PTP (libgphoto2) interface type */ static uint16_t map_libmtp_type_to_ptp_type(LIBMTP_filetype_t intype) { filemap_t *current; current = filemap; while (current != NULL) { if(current->id == intype) { return current->ptp_id; } current = current->next; } // printf("map_libmtp_type_to_ptp_type: unknown filetype.\n"); return PTP_OFC_Undefined; } /** * Returns the MTP internal interface type that maps to a certain ptp * interface type. * @param intype the PTP (libgphoto2) interface type * @return the MTP library interface type */ static LIBMTP_filetype_t map_ptp_type_to_libmtp_type(uint16_t intype) { filemap_t *current; current = filemap; while (current != NULL) { if(current->ptp_id == intype) { return current->id; } current = current->next; } // printf("map_ptp_type_to_libmtp_type: unknown filetype.\n"); return LIBMTP_FILETYPE_UNKNOWN; } /** * Create a new property mapping entry * @return a newly allocated propertymapping entry. */ static propertymap_t *new_propertymap_entry() { propertymap_t *propertymap; propertymap = (propertymap_t *)malloc(sizeof(propertymap_t)); if( propertymap != NULL ) { propertymap->description = NULL; propertymap->id = LIBMTP_PROPERTY_UNKNOWN; propertymap->ptp_id = 0; propertymap->next = NULL; } return propertymap; } /** * Register an MTP or PTP property for data retrieval * * @param description Text description of property * @param id libmtp internal property id * @param ptp_id PTP property id * @return 0 for success any other value means error. */ static int register_property(char const * const description, LIBMTP_property_t const id, uint16_t const ptp_id) { propertymap_t *new = NULL, *current; // Has this LIBMTP propety been registered before ? current = propertymap; while (current != NULL) { if(current->id == id) { break; } current = current->next; } // Create the entry if(current == NULL) { new = new_propertymap_entry(); if(new == NULL) { return 1; } new->id = id; if(description != NULL) { new->description = strdup(description); } new->ptp_id = ptp_id; // Add the entry to the list if(propertymap == NULL) { propertymap = new; } else { current = propertymap; while (current->next != NULL ) current=current->next; current->next = new; } // Update the existing entry } else { if (current->description != NULL) { free(current->description); } current->description = NULL; if(description != NULL) { current->description = strdup(description); } current->ptp_id = ptp_id; } return 0; } static void init_propertymap() { register_property("Storage ID", LIBMTP_PROPERTY_StorageID, PTP_OPC_StorageID); register_property("Object Format", LIBMTP_PROPERTY_ObjectFormat, PTP_OPC_ObjectFormat); register_property("Protection Status", LIBMTP_PROPERTY_ProtectionStatus, PTP_OPC_ProtectionStatus); register_property("Object Size", LIBMTP_PROPERTY_ObjectSize, PTP_OPC_ObjectSize); register_property("Association Type", LIBMTP_PROPERTY_AssociationType, PTP_OPC_AssociationType); register_property("Association Desc", LIBMTP_PROPERTY_AssociationDesc, PTP_OPC_AssociationDesc); register_property("Object File Name", LIBMTP_PROPERTY_ObjectFileName, PTP_OPC_ObjectFileName); register_property("Date Created", LIBMTP_PROPERTY_DateCreated, PTP_OPC_DateCreated); register_property("Date Modified", LIBMTP_PROPERTY_DateModified, PTP_OPC_DateModified); register_property("Keywords", LIBMTP_PROPERTY_Keywords, PTP_OPC_Keywords); register_property("Parent Object", LIBMTP_PROPERTY_ParentObject, PTP_OPC_ParentObject); register_property("Allowed Folder Contents", LIBMTP_PROPERTY_AllowedFolderContents, PTP_OPC_AllowedFolderContents); register_property("Hidden", LIBMTP_PROPERTY_Hidden, PTP_OPC_Hidden); register_property("System Object", LIBMTP_PROPERTY_SystemObject, PTP_OPC_SystemObject); register_property("Persistant Unique Object Identifier", LIBMTP_PROPERTY_PersistantUniqueObjectIdentifier, PTP_OPC_PersistantUniqueObjectIdentifier); register_property("Sync ID", LIBMTP_PROPERTY_SyncID, PTP_OPC_SyncID); register_property("Property Bag", LIBMTP_PROPERTY_PropertyBag, PTP_OPC_PropertyBag); register_property("Name", LIBMTP_PROPERTY_Name, PTP_OPC_Name); register_property("Created By", LIBMTP_PROPERTY_CreatedBy, PTP_OPC_CreatedBy); register_property("Artist", LIBMTP_PROPERTY_Artist, PTP_OPC_Artist); register_property("Date Authored", LIBMTP_PROPERTY_DateAuthored, PTP_OPC_DateAuthored); register_property("Description", LIBMTP_PROPERTY_Description, PTP_OPC_Description); register_property("URL Reference", LIBMTP_PROPERTY_URLReference, PTP_OPC_URLReference); register_property("Language Locale", LIBMTP_PROPERTY_LanguageLocale, PTP_OPC_LanguageLocale); register_property("Copyright Information", LIBMTP_PROPERTY_CopyrightInformation, PTP_OPC_CopyrightInformation); register_property("Source", LIBMTP_PROPERTY_Source, PTP_OPC_Source); register_property("Origin Location", LIBMTP_PROPERTY_OriginLocation, PTP_OPC_OriginLocation); register_property("Date Added", LIBMTP_PROPERTY_DateAdded, PTP_OPC_DateAdded); register_property("Non Consumable", LIBMTP_PROPERTY_NonConsumable, PTP_OPC_NonConsumable); register_property("Corrupt Or Unplayable", LIBMTP_PROPERTY_CorruptOrUnplayable, PTP_OPC_CorruptOrUnplayable); register_property("Producer Serial Number", LIBMTP_PROPERTY_ProducerSerialNumber, PTP_OPC_ProducerSerialNumber); register_property("Representative Sample Format", LIBMTP_PROPERTY_RepresentativeSampleFormat, PTP_OPC_RepresentativeSampleFormat); register_property("Representative Sample Sise", LIBMTP_PROPERTY_RepresentativeSampleSize, PTP_OPC_RepresentativeSampleSize); register_property("Representative Sample Height", LIBMTP_PROPERTY_RepresentativeSampleHeight, PTP_OPC_RepresentativeSampleHeight); register_property("Representative Sample Width", LIBMTP_PROPERTY_RepresentativeSampleWidth, PTP_OPC_RepresentativeSampleWidth); register_property("Representative Sample Duration", LIBMTP_PROPERTY_RepresentativeSampleDuration, PTP_OPC_RepresentativeSampleDuration); register_property("Representative Sample Data", LIBMTP_PROPERTY_RepresentativeSampleData, PTP_OPC_RepresentativeSampleData); register_property("Width", LIBMTP_PROPERTY_Width, PTP_OPC_Width); register_property("Height", LIBMTP_PROPERTY_Height, PTP_OPC_Height); register_property("Duration", LIBMTP_PROPERTY_Duration, PTP_OPC_Duration); register_property("Rating", LIBMTP_PROPERTY_Rating, PTP_OPC_Rating); register_property("Track", LIBMTP_PROPERTY_Track, PTP_OPC_Track); register_property("Genre", LIBMTP_PROPERTY_Genre, PTP_OPC_Genre); register_property("Credits", LIBMTP_PROPERTY_Credits, PTP_OPC_Credits); register_property("Lyrics", LIBMTP_PROPERTY_Lyrics, PTP_OPC_Lyrics); register_property("Subscription Content ID", LIBMTP_PROPERTY_SubscriptionContentID, PTP_OPC_SubscriptionContentID); register_property("Produced By", LIBMTP_PROPERTY_ProducedBy, PTP_OPC_ProducedBy); register_property("Use Count", LIBMTP_PROPERTY_UseCount, PTP_OPC_UseCount); register_property("Skip Count", LIBMTP_PROPERTY_SkipCount, PTP_OPC_SkipCount); register_property("Last Accessed", LIBMTP_PROPERTY_LastAccessed, PTP_OPC_LastAccessed); register_property("Parental Rating", LIBMTP_PROPERTY_ParentalRating, PTP_OPC_ParentalRating); register_property("Meta Genre", LIBMTP_PROPERTY_MetaGenre, PTP_OPC_MetaGenre); register_property("Composer", LIBMTP_PROPERTY_Composer, PTP_OPC_Composer); register_property("Effective Rating", LIBMTP_PROPERTY_EffectiveRating, PTP_OPC_EffectiveRating); register_property("Subtitle", LIBMTP_PROPERTY_Subtitle, PTP_OPC_Subtitle); register_property("Original Release Date", LIBMTP_PROPERTY_OriginalReleaseDate, PTP_OPC_OriginalReleaseDate); register_property("Album Name", LIBMTP_PROPERTY_AlbumName, PTP_OPC_AlbumName); register_property("Album Artist", LIBMTP_PROPERTY_AlbumArtist, PTP_OPC_AlbumArtist); register_property("Mood", LIBMTP_PROPERTY_Mood, PTP_OPC_Mood); register_property("DRM Status", LIBMTP_PROPERTY_DRMStatus, PTP_OPC_DRMStatus); register_property("Sub Description", LIBMTP_PROPERTY_SubDescription, PTP_OPC_SubDescription); register_property("Is Cropped", LIBMTP_PROPERTY_IsCropped, PTP_OPC_IsCropped); register_property("Is Color Corrected", LIBMTP_PROPERTY_IsColorCorrected, PTP_OPC_IsColorCorrected); register_property("Image Bit Depth", LIBMTP_PROPERTY_ImageBitDepth, PTP_OPC_ImageBitDepth); register_property("f Number", LIBMTP_PROPERTY_Fnumber, PTP_OPC_Fnumber); register_property("Exposure Time", LIBMTP_PROPERTY_ExposureTime, PTP_OPC_ExposureTime); register_property("Exposure Index", LIBMTP_PROPERTY_ExposureIndex, PTP_OPC_ExposureIndex); register_property("Display Name", LIBMTP_PROPERTY_DisplayName, PTP_OPC_DisplayName); register_property("Body Text", LIBMTP_PROPERTY_BodyText, PTP_OPC_BodyText); register_property("Subject", LIBMTP_PROPERTY_Subject, PTP_OPC_Subject); register_property("Priority", LIBMTP_PROPERTY_Priority, PTP_OPC_Priority); register_property("Given Name", LIBMTP_PROPERTY_GivenName, PTP_OPC_GivenName); register_property("Middle Names", LIBMTP_PROPERTY_MiddleNames, PTP_OPC_MiddleNames); register_property("Family Name", LIBMTP_PROPERTY_FamilyName, PTP_OPC_FamilyName); register_property("Prefix", LIBMTP_PROPERTY_Prefix, PTP_OPC_Prefix); register_property("Suffix", LIBMTP_PROPERTY_Suffix, PTP_OPC_Suffix); register_property("Phonetic Given Name", LIBMTP_PROPERTY_PhoneticGivenName, PTP_OPC_PhoneticGivenName); register_property("Phonetic Family Name", LIBMTP_PROPERTY_PhoneticFamilyName, PTP_OPC_PhoneticFamilyName); register_property("Email: Primary", LIBMTP_PROPERTY_EmailPrimary, PTP_OPC_EmailPrimary); register_property("Email: Personal 1", LIBMTP_PROPERTY_EmailPersonal1, PTP_OPC_EmailPersonal1); register_property("Email: Personal 2", LIBMTP_PROPERTY_EmailPersonal2, PTP_OPC_EmailPersonal2); register_property("Email: Business 1", LIBMTP_PROPERTY_EmailBusiness1, PTP_OPC_EmailBusiness1); register_property("Email: Business 2", LIBMTP_PROPERTY_EmailBusiness2, PTP_OPC_EmailBusiness2); register_property("Email: Others", LIBMTP_PROPERTY_EmailOthers, PTP_OPC_EmailOthers); register_property("Phone Number: Primary", LIBMTP_PROPERTY_PhoneNumberPrimary, PTP_OPC_PhoneNumberPrimary); register_property("Phone Number: Personal", LIBMTP_PROPERTY_PhoneNumberPersonal, PTP_OPC_PhoneNumberPersonal); register_property("Phone Number: Personal 2", LIBMTP_PROPERTY_PhoneNumberPersonal2, PTP_OPC_PhoneNumberPersonal2); register_property("Phone Number: Business", LIBMTP_PROPERTY_PhoneNumberBusiness, PTP_OPC_PhoneNumberBusiness); register_property("Phone Number: Business 2", LIBMTP_PROPERTY_PhoneNumberBusiness2, PTP_OPC_PhoneNumberBusiness2); register_property("Phone Number: Mobile", LIBMTP_PROPERTY_PhoneNumberMobile, PTP_OPC_PhoneNumberMobile); register_property("Phone Number: Mobile 2", LIBMTP_PROPERTY_PhoneNumberMobile2, PTP_OPC_PhoneNumberMobile2); register_property("Fax Number: Primary", LIBMTP_PROPERTY_FaxNumberPrimary, PTP_OPC_FaxNumberPrimary); register_property("Fax Number: Personal", LIBMTP_PROPERTY_FaxNumberPersonal, PTP_OPC_FaxNumberPersonal); register_property("Fax Number: Business", LIBMTP_PROPERTY_FaxNumberBusiness, PTP_OPC_FaxNumberBusiness); register_property("Pager Number", LIBMTP_PROPERTY_PagerNumber, PTP_OPC_PagerNumber); register_property("Phone Number: Others", LIBMTP_PROPERTY_PhoneNumberOthers, PTP_OPC_PhoneNumberOthers); register_property("Primary Web Address", LIBMTP_PROPERTY_PrimaryWebAddress, PTP_OPC_PrimaryWebAddress); register_property("Personal Web Address", LIBMTP_PROPERTY_PersonalWebAddress, PTP_OPC_PersonalWebAddress); register_property("Business Web Address", LIBMTP_PROPERTY_BusinessWebAddress, PTP_OPC_BusinessWebAddress); register_property("Instant Messenger Address 1", LIBMTP_PROPERTY_InstantMessengerAddress, PTP_OPC_InstantMessengerAddress); register_property("Instant Messenger Address 2", LIBMTP_PROPERTY_InstantMessengerAddress2, PTP_OPC_InstantMessengerAddress2); register_property("Instant Messenger Address 3", LIBMTP_PROPERTY_InstantMessengerAddress3, PTP_OPC_InstantMessengerAddress3); register_property("Postal Address: Personal: Full", LIBMTP_PROPERTY_PostalAddressPersonalFull, PTP_OPC_PostalAddressPersonalFull); register_property("Postal Address: Personal: Line 1", LIBMTP_PROPERTY_PostalAddressPersonalFullLine1, PTP_OPC_PostalAddressPersonalFullLine1); register_property("Postal Address: Personal: Line 2", LIBMTP_PROPERTY_PostalAddressPersonalFullLine2, PTP_OPC_PostalAddressPersonalFullLine2); register_property("Postal Address: Personal: City", LIBMTP_PROPERTY_PostalAddressPersonalFullCity, PTP_OPC_PostalAddressPersonalFullCity); register_property("Postal Address: Personal: Region", LIBMTP_PROPERTY_PostalAddressPersonalFullRegion, PTP_OPC_PostalAddressPersonalFullRegion); register_property("Postal Address: Personal: Postal Code", LIBMTP_PROPERTY_PostalAddressPersonalFullPostalCode, PTP_OPC_PostalAddressPersonalFullPostalCode); register_property("Postal Address: Personal: Country", LIBMTP_PROPERTY_PostalAddressPersonalFullCountry, PTP_OPC_PostalAddressPersonalFullCountry); register_property("Postal Address: Business: Full", LIBMTP_PROPERTY_PostalAddressBusinessFull, PTP_OPC_PostalAddressBusinessFull); register_property("Postal Address: Business: Line 1", LIBMTP_PROPERTY_PostalAddressBusinessLine1, PTP_OPC_PostalAddressBusinessLine1); register_property("Postal Address: Business: Line 2", LIBMTP_PROPERTY_PostalAddressBusinessLine2, PTP_OPC_PostalAddressBusinessLine2); register_property("Postal Address: Business: City", LIBMTP_PROPERTY_PostalAddressBusinessCity, PTP_OPC_PostalAddressBusinessCity); register_property("Postal Address: Business: Region", LIBMTP_PROPERTY_PostalAddressBusinessRegion, PTP_OPC_PostalAddressBusinessRegion); register_property("Postal Address: Business: Postal Code", LIBMTP_PROPERTY_PostalAddressBusinessPostalCode, PTP_OPC_PostalAddressBusinessPostalCode); register_property("Postal Address: Business: Country", LIBMTP_PROPERTY_PostalAddressBusinessCountry, PTP_OPC_PostalAddressBusinessCountry); register_property("Postal Address: Other: Full", LIBMTP_PROPERTY_PostalAddressOtherFull, PTP_OPC_PostalAddressOtherFull); register_property("Postal Address: Other: Line 1", LIBMTP_PROPERTY_PostalAddressOtherLine1, PTP_OPC_PostalAddressOtherLine1); register_property("Postal Address: Other: Line 2", LIBMTP_PROPERTY_PostalAddressOtherLine2, PTP_OPC_PostalAddressOtherLine2); register_property("Postal Address: Other: City", LIBMTP_PROPERTY_PostalAddressOtherCity, PTP_OPC_PostalAddressOtherCity); register_property("Postal Address: Other: Region", LIBMTP_PROPERTY_PostalAddressOtherRegion, PTP_OPC_PostalAddressOtherRegion); register_property("Postal Address: Other: Postal Code", LIBMTP_PROPERTY_PostalAddressOtherPostalCode, PTP_OPC_PostalAddressOtherPostalCode); register_property("Postal Address: Other: Counrtry", LIBMTP_PROPERTY_PostalAddressOtherCountry, PTP_OPC_PostalAddressOtherCountry); register_property("Organization Name", LIBMTP_PROPERTY_OrganizationName, PTP_OPC_OrganizationName); register_property("Phonetic Organization Name", LIBMTP_PROPERTY_PhoneticOrganizationName, PTP_OPC_PhoneticOrganizationName); register_property("Role", LIBMTP_PROPERTY_Role, PTP_OPC_Role); register_property("Birthdate", LIBMTP_PROPERTY_Birthdate, PTP_OPC_Birthdate); register_property("Message To", LIBMTP_PROPERTY_MessageTo, PTP_OPC_MessageTo); register_property("Message CC", LIBMTP_PROPERTY_MessageCC, PTP_OPC_MessageCC); register_property("Message BCC", LIBMTP_PROPERTY_MessageBCC, PTP_OPC_MessageBCC); register_property("Message Read", LIBMTP_PROPERTY_MessageRead, PTP_OPC_MessageRead); register_property("Message Received Time", LIBMTP_PROPERTY_MessageReceivedTime, PTP_OPC_MessageReceivedTime); register_property("Message Sender", LIBMTP_PROPERTY_MessageSender, PTP_OPC_MessageSender); register_property("Activity Begin Time", LIBMTP_PROPERTY_ActivityBeginTime, PTP_OPC_ActivityBeginTime); register_property("Activity End Time", LIBMTP_PROPERTY_ActivityEndTime, PTP_OPC_ActivityEndTime); register_property("Activity Location", LIBMTP_PROPERTY_ActivityLocation, PTP_OPC_ActivityLocation); register_property("Activity Required Attendees", LIBMTP_PROPERTY_ActivityRequiredAttendees, PTP_OPC_ActivityRequiredAttendees); register_property("Optional Attendees", LIBMTP_PROPERTY_ActivityOptionalAttendees, PTP_OPC_ActivityOptionalAttendees); register_property("Activity Resources", LIBMTP_PROPERTY_ActivityResources, PTP_OPC_ActivityResources); register_property("Activity Accepted", LIBMTP_PROPERTY_ActivityAccepted, PTP_OPC_ActivityAccepted); register_property("Owner", LIBMTP_PROPERTY_Owner, PTP_OPC_Owner); register_property("Editor", LIBMTP_PROPERTY_Editor, PTP_OPC_Editor); register_property("Webmaster", LIBMTP_PROPERTY_Webmaster, PTP_OPC_Webmaster); register_property("URL Source", LIBMTP_PROPERTY_URLSource, PTP_OPC_URLSource); register_property("URL Destination", LIBMTP_PROPERTY_URLDestination, PTP_OPC_URLDestination); register_property("Time Bookmark", LIBMTP_PROPERTY_TimeBookmark, PTP_OPC_TimeBookmark); register_property("Object Bookmark", LIBMTP_PROPERTY_ObjectBookmark, PTP_OPC_ObjectBookmark); register_property("Byte Bookmark", LIBMTP_PROPERTY_ByteBookmark, PTP_OPC_ByteBookmark); register_property("Last Build Date", LIBMTP_PROPERTY_LastBuildDate, PTP_OPC_LastBuildDate); register_property("Time To Live", LIBMTP_PROPERTY_TimetoLive, PTP_OPC_TimetoLive); register_property("Media GUID", LIBMTP_PROPERTY_MediaGUID, PTP_OPC_MediaGUID); register_property("Total Bit Rate", LIBMTP_PROPERTY_TotalBitRate, PTP_OPC_TotalBitRate); register_property("Bit Rate Type", LIBMTP_PROPERTY_BitRateType, PTP_OPC_BitRateType); register_property("Sample Rate", LIBMTP_PROPERTY_SampleRate, PTP_OPC_SampleRate); register_property("Number Of Channels", LIBMTP_PROPERTY_NumberOfChannels, PTP_OPC_NumberOfChannels); register_property("Audio Bit Depth", LIBMTP_PROPERTY_AudioBitDepth, PTP_OPC_AudioBitDepth); register_property("Scan Depth", LIBMTP_PROPERTY_ScanDepth, PTP_OPC_ScanDepth); register_property("Audio WAVE Codec", LIBMTP_PROPERTY_AudioWAVECodec, PTP_OPC_AudioWAVECodec); register_property("Audio Bit Rate", LIBMTP_PROPERTY_AudioBitRate, PTP_OPC_AudioBitRate); register_property("Video Four CC Codec", LIBMTP_PROPERTY_VideoFourCCCodec, PTP_OPC_VideoFourCCCodec); register_property("Video Bit Rate", LIBMTP_PROPERTY_VideoBitRate, PTP_OPC_VideoBitRate); register_property("Frames Per Thousand Seconds", LIBMTP_PROPERTY_FramesPerThousandSeconds, PTP_OPC_FramesPerThousandSeconds); register_property("Key Frame Distance", LIBMTP_PROPERTY_KeyFrameDistance, PTP_OPC_KeyFrameDistance); register_property("Buffer Size", LIBMTP_PROPERTY_BufferSize, PTP_OPC_BufferSize); register_property("Encoding Quality", LIBMTP_PROPERTY_EncodingQuality, PTP_OPC_EncodingQuality); register_property("Encoding Profile", LIBMTP_PROPERTY_EncodingProfile, PTP_OPC_EncodingProfile); register_property("Buy flag", LIBMTP_PROPERTY_BuyFlag, PTP_OPC_BuyFlag); register_property("Unknown property", LIBMTP_PROPERTY_UNKNOWN, 0); } /** * Returns the PTP property that maps to a certain libmtp internal property type. * @param inproperty the MTP library interface property * @return the PTP (libgphoto2) property type */ static uint16_t map_libmtp_property_to_ptp_property(LIBMTP_property_t inproperty) { propertymap_t *current; current = propertymap; while (current != NULL) { if(current->id == inproperty) { return current->ptp_id; } current = current->next; } return 0; } /** * Returns the MTP internal interface property that maps to a certain ptp * interface property. * @param inproperty the PTP (libgphoto2) interface property * @return the MTP library interface property */ static LIBMTP_property_t map_ptp_property_to_libmtp_property(uint16_t inproperty) { propertymap_t *current; current = propertymap; while (current != NULL) { if(current->ptp_id == inproperty) { return current->id; } current = current->next; } // printf("map_ptp_type_to_libmtp_type: unknown filetype.\n"); return LIBMTP_PROPERTY_UNKNOWN; } /** * Set the debug level. * * By default, the debug level is set to '0' (disable). */ void LIBMTP_Set_Debug(int level) { if (LIBMTP_debug || level) LIBMTP_ERROR("LIBMTP_Set_Debug: Setting debugging level to %d (0x%02x) " "(%s)\n", level, level, level ? "on" : "off"); LIBMTP_debug = level; } /** * Initialize the library. You are only supposed to call this * one, before using the library for the first time in a program. * Never re-initialize libmtp! * * The only thing this does at the moment is to initialise the * filetype mapping table, as well as load MTPZ data if necessary. */ void LIBMTP_Init(void) { const char *env_debug = getenv("LIBMTP_DEBUG"); if (env_debug) { const long debug_flags = strtol(env_debug, NULL, 0); if (debug_flags != LONG_MIN && debug_flags != LONG_MAX && INT_MIN <= debug_flags && debug_flags <= INT_MAX) { LIBMTP_Set_Debug(debug_flags); } else { fprintf(stderr, "LIBMTP_Init: error setting debug flags from environment " "value \"%s\"\n", env_debug); } } init_filemap(); init_propertymap(); if (mtpz_loaddata() == -1) use_mtpz = 0; else use_mtpz = 1; return; } /** * This helper function returns a textual description for a libmtp * file type to be used in dialog boxes etc. * @param intype the libmtp internal filetype to get a description for. * @return a string representing the filetype, this must NOT * be free():ed by the caller! */ char const * LIBMTP_Get_Filetype_Description(LIBMTP_filetype_t intype) { filemap_t *current; current = filemap; while (current != NULL) { if(current->id == intype) { return current->description; } current = current->next; } return "Unknown filetype"; } /** * This helper function returns a textual description for a libmtp * property to be used in dialog boxes etc. * @param inproperty the libmtp internal property to get a description for. * @return a string representing the filetype, this must NOT * be free():ed by the caller! */ char const * LIBMTP_Get_Property_Description(LIBMTP_property_t inproperty) { propertymap_t *current; current = propertymap; while (current != NULL) { if(current->id == inproperty) { return current->description; } current = current->next; } return "Unknown property"; } /** * This function will do its best to fit a 16bit * value into a PTP object property if the property * is limited in range or step sizes. */ static uint16_t adjust_u16(uint16_t val, PTPObjectPropDesc *opd) { switch (opd->FormFlag) { case PTP_DPFF_Range: if (val < opd->FORM.Range.MinimumValue.u16) { return opd->FORM.Range.MinimumValue.u16; } if (val > opd->FORM.Range.MaximumValue.u16) { return opd->FORM.Range.MaximumValue.u16; } // Round down to last step. if (val % opd->FORM.Range.StepSize.u16 != 0) { return val - (val % opd->FORM.Range.StepSize.u16); } return val; break; case PTP_DPFF_Enumeration: { int i; uint16_t bestfit = opd->FORM.Enum.SupportedValue[0].u16; for (i=0; iFORM.Enum.NumberOfValues; i++) { if (val == opd->FORM.Enum.SupportedValue[i].u16) { return val; } // Rough guess of best fit if (opd->FORM.Enum.SupportedValue[i].u16 < val) { bestfit = opd->FORM.Enum.SupportedValue[i].u16; } } // Just some default that'll work. return bestfit; } default: // Will accept any value break; } return val; } /** * This function will do its best to fit a 32bit * value into a PTP object property if the property * is limited in range or step sizes. */ static uint32_t adjust_u32(uint32_t val, PTPObjectPropDesc *opd) { switch (opd->FormFlag) { case PTP_DPFF_Range: if (val < opd->FORM.Range.MinimumValue.u32) { return opd->FORM.Range.MinimumValue.u32; } if (val > opd->FORM.Range.MaximumValue.u32) { return opd->FORM.Range.MaximumValue.u32; } // Round down to last step. if (val % opd->FORM.Range.StepSize.u32 != 0) { return val - (val % opd->FORM.Range.StepSize.u32); } return val; break; case PTP_DPFF_Enumeration: { int i; uint32_t bestfit = opd->FORM.Enum.SupportedValue[0].u32; for (i=0; iFORM.Enum.NumberOfValues; i++) { if (val == opd->FORM.Enum.SupportedValue[i].u32) { return val; } // Rough guess of best fit if (opd->FORM.Enum.SupportedValue[i].u32 < val) { bestfit = opd->FORM.Enum.SupportedValue[i].u32; } } // Just some default that'll work. return bestfit; } default: // Will accept any value break; } return val; } /** * This function returns a newly created ISO 8601 timestamp with the * current time in as high precision as possible. It even adds * the time zone if it can. */ static char *get_iso8601_stamp(void) { time_t curtime; struct tm *loctime; char tmp[64]; curtime = time(NULL); loctime = localtime(&curtime); strftime (tmp, sizeof(tmp), "%Y%m%dT%H%M%S.0%z", loctime); return strdup(tmp); } /** * Gets the allowed values (range or enum) for a property * @param device a pointer to an MTP device * @param property the property to query * @param filetype the filetype of the object you want to set values for * @param allowed_vals pointer to a LIBMTP_allowed_values_t struct to * receive the allowed values. Call LIBMTP_destroy_allowed_values_t * on this on successful completion. * @return 0 on success, any other value means failure */ int LIBMTP_Get_Allowed_Property_Values(LIBMTP_mtpdevice_t *device, LIBMTP_property_t const property, LIBMTP_filetype_t const filetype, LIBMTP_allowed_values_t *allowed_vals) { PTPObjectPropDesc opd; uint16_t ret = 0; ret = ptp_mtp_getobjectpropdesc(device->params, map_libmtp_property_to_ptp_property(property), map_libmtp_type_to_ptp_type(filetype), &opd); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Get_Allowed_Property_Values(): could not get property description."); return -1; } if (opd.FormFlag == PTP_OPFF_Enumeration) { int i = 0; allowed_vals->is_range = 0; allowed_vals->num_entries = opd.FORM.Enum.NumberOfValues; switch (opd.DataType) { case PTP_DTC_INT8: allowed_vals->i8vals = malloc(sizeof(int8_t) * opd.FORM.Enum.NumberOfValues); allowed_vals->datatype = LIBMTP_DATATYPE_INT8; break; case PTP_DTC_UINT8: allowed_vals->u8vals = malloc(sizeof(uint8_t) * opd.FORM.Enum.NumberOfValues); allowed_vals->datatype = LIBMTP_DATATYPE_UINT8; break; case PTP_DTC_INT16: allowed_vals->i16vals = malloc(sizeof(int16_t) * opd.FORM.Enum.NumberOfValues); allowed_vals->datatype = LIBMTP_DATATYPE_INT16; break; case PTP_DTC_UINT16: allowed_vals->u16vals = malloc(sizeof(uint16_t) * opd.FORM.Enum.NumberOfValues); allowed_vals->datatype = LIBMTP_DATATYPE_UINT16; break; case PTP_DTC_INT32: allowed_vals->i32vals = malloc(sizeof(int32_t) * opd.FORM.Enum.NumberOfValues); allowed_vals->datatype = LIBMTP_DATATYPE_INT32; break; case PTP_DTC_UINT32: allowed_vals->u32vals = malloc(sizeof(uint32_t) * opd.FORM.Enum.NumberOfValues); allowed_vals->datatype = LIBMTP_DATATYPE_UINT32; break; case PTP_DTC_INT64: allowed_vals->i64vals = malloc(sizeof(int64_t) * opd.FORM.Enum.NumberOfValues); allowed_vals->datatype = LIBMTP_DATATYPE_INT64; break; case PTP_DTC_UINT64: allowed_vals->u64vals = malloc(sizeof(uint64_t) * opd.FORM.Enum.NumberOfValues); allowed_vals->datatype = LIBMTP_DATATYPE_UINT64; break; } for (i = 0; i < opd.FORM.Enum.NumberOfValues; i++) { switch (opd.DataType) { case PTP_DTC_INT8: allowed_vals->i8vals[i] = opd.FORM.Enum.SupportedValue[i].i8; break; case PTP_DTC_UINT8: allowed_vals->u8vals[i] = opd.FORM.Enum.SupportedValue[i].u8; break; case PTP_DTC_INT16: allowed_vals->i16vals[i] = opd.FORM.Enum.SupportedValue[i].i16; break; case PTP_DTC_UINT16: allowed_vals->u16vals[i] = opd.FORM.Enum.SupportedValue[i].u16; break; case PTP_DTC_INT32: allowed_vals->i32vals[i] = opd.FORM.Enum.SupportedValue[i].i32; break; case PTP_DTC_UINT32: allowed_vals->u32vals[i] = opd.FORM.Enum.SupportedValue[i].u32; break; case PTP_DTC_INT64: allowed_vals->i64vals[i] = opd.FORM.Enum.SupportedValue[i].i64; break; case PTP_DTC_UINT64: allowed_vals->u64vals[i] = opd.FORM.Enum.SupportedValue[i].u64; break; } } ptp_free_objectpropdesc(&opd); return 0; } else if (opd.FormFlag == PTP_OPFF_Range) { allowed_vals->is_range = 1; switch (opd.DataType) { case PTP_DTC_INT8: allowed_vals->i8min = opd.FORM.Range.MinimumValue.i8; allowed_vals->i8max = opd.FORM.Range.MaximumValue.i8; allowed_vals->i8step = opd.FORM.Range.StepSize.i8; allowed_vals->datatype = LIBMTP_DATATYPE_INT8; break; case PTP_DTC_UINT8: allowed_vals->u8min = opd.FORM.Range.MinimumValue.u8; allowed_vals->u8max = opd.FORM.Range.MaximumValue.u8; allowed_vals->u8step = opd.FORM.Range.StepSize.u8; allowed_vals->datatype = LIBMTP_DATATYPE_UINT8; break; case PTP_DTC_INT16: allowed_vals->i16min = opd.FORM.Range.MinimumValue.i16; allowed_vals->i16max = opd.FORM.Range.MaximumValue.i16; allowed_vals->i16step = opd.FORM.Range.StepSize.i16; allowed_vals->datatype = LIBMTP_DATATYPE_INT16; break; case PTP_DTC_UINT16: allowed_vals->u16min = opd.FORM.Range.MinimumValue.u16; allowed_vals->u16max = opd.FORM.Range.MaximumValue.u16; allowed_vals->u16step = opd.FORM.Range.StepSize.u16; allowed_vals->datatype = LIBMTP_DATATYPE_UINT16; break; case PTP_DTC_INT32: allowed_vals->i32min = opd.FORM.Range.MinimumValue.i32; allowed_vals->i32max = opd.FORM.Range.MaximumValue.i32; allowed_vals->i32step = opd.FORM.Range.StepSize.i32; allowed_vals->datatype = LIBMTP_DATATYPE_INT32; break; case PTP_DTC_UINT32: allowed_vals->u32min = opd.FORM.Range.MinimumValue.u32; allowed_vals->u32max = opd.FORM.Range.MaximumValue.u32; allowed_vals->u32step = opd.FORM.Range.StepSize.u32; allowed_vals->datatype = LIBMTP_DATATYPE_UINT32; break; case PTP_DTC_INT64: allowed_vals->i64min = opd.FORM.Range.MinimumValue.i64; allowed_vals->i64max = opd.FORM.Range.MaximumValue.i64; allowed_vals->i64step = opd.FORM.Range.StepSize.i64; allowed_vals->datatype = LIBMTP_DATATYPE_INT64; break; case PTP_DTC_UINT64: allowed_vals->u64min = opd.FORM.Range.MinimumValue.u64; allowed_vals->u64max = opd.FORM.Range.MaximumValue.u64; allowed_vals->u64step = opd.FORM.Range.StepSize.u64; allowed_vals->datatype = LIBMTP_DATATYPE_UINT64; break; } return 0; } else return -1; } /** * Destroys a LIBMTP_allowed_values_t struct * @param allowed_vals the struct to destroy */ void LIBMTP_destroy_allowed_values_t(LIBMTP_allowed_values_t *allowed_vals) { if (!allowed_vals->is_range) { switch (allowed_vals->datatype) { case LIBMTP_DATATYPE_INT8: if (allowed_vals->i8vals) free(allowed_vals->i8vals); break; case LIBMTP_DATATYPE_UINT8: if (allowed_vals->u8vals) free(allowed_vals->u8vals); break; case LIBMTP_DATATYPE_INT16: if (allowed_vals->i16vals) free(allowed_vals->i16vals); break; case LIBMTP_DATATYPE_UINT16: if (allowed_vals->u16vals) free(allowed_vals->u16vals); break; case LIBMTP_DATATYPE_INT32: if (allowed_vals->i32vals) free(allowed_vals->i32vals); break; case LIBMTP_DATATYPE_UINT32: if (allowed_vals->u32vals) free(allowed_vals->u32vals); break; case LIBMTP_DATATYPE_INT64: if (allowed_vals->i64vals) free(allowed_vals->i64vals); break; case LIBMTP_DATATYPE_UINT64: if (allowed_vals->u64vals) free(allowed_vals->u64vals); break; } } } /** * Determine if a property is supported for a given file type * @param device a pointer to an MTP device * @param property the property to query * @param filetype the filetype of the object you want to set values for * @return 0 if not supported, positive if supported, negative on error */ int LIBMTP_Is_Property_Supported(LIBMTP_mtpdevice_t *device, LIBMTP_property_t const property, LIBMTP_filetype_t const filetype) { uint16_t *props = NULL; uint32_t propcnt = 0; uint16_t ret = 0; int i = 0; int supported = 0; uint16_t ptp_prop = map_libmtp_property_to_ptp_property(property); if (!ptp_operation_issupported(device->params, PTP_OC_MTP_GetObjectPropsSupported)) return 0; ret = ptp_mtp_getobjectpropssupported(device->params, map_libmtp_type_to_ptp_type(filetype), &propcnt, &props); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Is_Property_Supported(): could not get properties supported."); return -1; } for (i = 0; i < propcnt; i++) { if (props[i] == ptp_prop) { supported = 1; break; } } free(props); return supported; } /** * Retrieves a string from an object * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id MTP attribute ID * @return valid string or NULL on failure. The returned string * must bee free():ed by the caller after * use. */ char *LIBMTP_Get_String_From_Object(LIBMTP_mtpdevice_t *device, uint32_t const object_id, LIBMTP_property_t const attribute_id) { return get_string_from_object(device, object_id, attribute_id); } /** * Retrieves an unsigned 64-bit integer from an object attribute * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id MTP attribute ID * @param value_default Default value to return on failure * @return the value */ uint64_t LIBMTP_Get_u64_From_Object(LIBMTP_mtpdevice_t *device,uint32_t const object_id, LIBMTP_property_t const attribute_id, uint64_t const value_default) { return get_u64_from_object(device, object_id, map_libmtp_property_to_ptp_property(attribute_id), value_default); } /** * Retrieves an unsigned 32-bit integer from an object attribute * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id MTP attribute ID * @param value_default Default value to return on failure * @return the value */ uint32_t LIBMTP_Get_u32_From_Object(LIBMTP_mtpdevice_t *device,uint32_t const object_id, LIBMTP_property_t const attribute_id, uint32_t const value_default) { return get_u32_from_object(device, object_id, map_libmtp_property_to_ptp_property(attribute_id), value_default); } /** * Retrieves an unsigned 16-bit integer from an object attribute * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id MTP attribute ID * @param value_default Default value to return on failure * @return a value */ uint16_t LIBMTP_Get_u16_From_Object(LIBMTP_mtpdevice_t *device, uint32_t const object_id, LIBMTP_property_t const attribute_id, uint16_t const value_default) { return get_u16_from_object(device, object_id, map_libmtp_property_to_ptp_property(attribute_id), value_default); } /** * Retrieves an unsigned 8-bit integer from an object attribute * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id MTP attribute ID * @param value_default Default value to return on failure * @return a value */ uint8_t LIBMTP_Get_u8_From_Object(LIBMTP_mtpdevice_t *device, uint32_t const object_id, LIBMTP_property_t const attribute_id, uint8_t const value_default) { return get_u8_from_object(device, object_id, map_libmtp_property_to_ptp_property(attribute_id), value_default); } /** * Sets an object attribute from a string * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id MTP attribute ID * @param string string value to set * @return 0 on success, any other value means failure */ int LIBMTP_Set_Object_String(LIBMTP_mtpdevice_t *device, uint32_t const object_id, LIBMTP_property_t const attribute_id, char const * const string) { return set_object_string(device, object_id, map_libmtp_property_to_ptp_property(attribute_id), string); } /** * Sets an object attribute from an unsigned 32-bit integer * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id MTP attribute ID * @param value 32-bit unsigned integer to set * @return 0 on success, any other value means failure */ int LIBMTP_Set_Object_u32(LIBMTP_mtpdevice_t *device, uint32_t const object_id, LIBMTP_property_t const attribute_id, uint32_t const value) { return set_object_u32(device, object_id, map_libmtp_property_to_ptp_property(attribute_id), value); } /** * Sets an object attribute from an unsigned 16-bit integer * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id MTP attribute ID * @param value 16-bit unsigned integer to set * @return 0 on success, any other value means failure */ int LIBMTP_Set_Object_u16(LIBMTP_mtpdevice_t *device, uint32_t const object_id, LIBMTP_property_t const attribute_id, uint16_t const value) { return set_object_u16(device, object_id, map_libmtp_property_to_ptp_property(attribute_id), value); } /** * Sets an object attribute from an unsigned 8-bit integer * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id MTP attribute ID * @param value 8-bit unsigned integer to set * @return 0 on success, any other value means failure */ int LIBMTP_Set_Object_u8(LIBMTP_mtpdevice_t *device, uint32_t const object_id, LIBMTP_property_t const attribute_id, uint8_t const value) { return set_object_u8(device, object_id, map_libmtp_property_to_ptp_property(attribute_id), value); } /** * Retrieves a string from an object * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id PTP attribute ID * @return valid string or NULL on failure. The returned string * must bee free():ed by the caller after * use. */ static char *get_string_from_object(LIBMTP_mtpdevice_t *device, uint32_t const object_id, uint16_t const attribute_id) { PTPPropertyValue propval; char *retstring = NULL; PTPParams *params = (PTPParams *) device->params; uint16_t ret; MTPProperties *prop; if ( device == NULL || object_id == 0) { return NULL; } prop = ptp_find_object_prop_in_cache(params, object_id, attribute_id); if (prop) { if (prop->propval.str != NULL) return strdup(prop->propval.str); else return NULL; } ret = ptp_mtp_getobjectpropvalue(params, object_id, attribute_id, &propval, PTP_DTC_STR); if (ret == PTP_RC_OK) { if (propval.str != NULL) { retstring = (char *) strdup(propval.str); free(propval.str); } } else { add_ptp_error_to_errorstack(device, ret, "get_string_from_object(): could not get object string."); } return retstring; } /** * Retrieves an unsigned 64-bit integer from an object attribute * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id PTP attribute ID * @param value_default Default value to return on failure * @return the value */ static uint64_t get_u64_from_object(LIBMTP_mtpdevice_t *device,uint32_t const object_id, uint16_t const attribute_id, uint64_t const value_default) { PTPPropertyValue propval; uint64_t retval = value_default; PTPParams *params = (PTPParams *) device->params; uint16_t ret; MTPProperties *prop; if ( device == NULL ) { return value_default; } prop = ptp_find_object_prop_in_cache(params, object_id, attribute_id); if (prop) return prop->propval.u64; ret = ptp_mtp_getobjectpropvalue(params, object_id, attribute_id, &propval, PTP_DTC_UINT64); if (ret == PTP_RC_OK) { retval = propval.u64; } else { add_ptp_error_to_errorstack(device, ret, "get_u64_from_object(): could not get unsigned 64bit integer from object."); } return retval; } /** * Retrieves an unsigned 32-bit integer from an object attribute * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id PTP attribute ID * @param value_default Default value to return on failure * @return the value */ static uint32_t get_u32_from_object(LIBMTP_mtpdevice_t *device,uint32_t const object_id, uint16_t const attribute_id, uint32_t const value_default) { PTPPropertyValue propval; uint32_t retval = value_default; PTPParams *params = (PTPParams *) device->params; uint16_t ret; MTPProperties *prop; if ( device == NULL ) { return value_default; } prop = ptp_find_object_prop_in_cache(params, object_id, attribute_id); if (prop) return prop->propval.u32; ret = ptp_mtp_getobjectpropvalue(params, object_id, attribute_id, &propval, PTP_DTC_UINT32); if (ret == PTP_RC_OK) { retval = propval.u32; } else { add_ptp_error_to_errorstack(device, ret, "get_u32_from_object(): could not get unsigned 32bit integer from object."); } return retval; } /** * Retrieves an unsigned 16-bit integer from an object attribute * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id PTP attribute ID * @param value_default Default value to return on failure * @return a value */ static uint16_t get_u16_from_object(LIBMTP_mtpdevice_t *device, uint32_t const object_id, uint16_t const attribute_id, uint16_t const value_default) { PTPPropertyValue propval; uint16_t retval = value_default; PTPParams *params = (PTPParams *) device->params; uint16_t ret; MTPProperties *prop; if ( device == NULL ) { return value_default; } // This O(n) search should not be used so often, since code // using the cached properties don't usually call this function. prop = ptp_find_object_prop_in_cache(params, object_id, attribute_id); if (prop) return prop->propval.u16; ret = ptp_mtp_getobjectpropvalue(params, object_id, attribute_id, &propval, PTP_DTC_UINT16); if (ret == PTP_RC_OK) { retval = propval.u16; } else { add_ptp_error_to_errorstack(device, ret, "get_u16_from_object(): could not get unsigned 16bit integer from object."); } return retval; } /** * Retrieves an unsigned 8-bit integer from an object attribute * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id PTP attribute ID * @param value_default Default value to return on failure * @return a value */ static uint8_t get_u8_from_object(LIBMTP_mtpdevice_t *device, uint32_t const object_id, uint16_t const attribute_id, uint8_t const value_default) { PTPPropertyValue propval; uint8_t retval = value_default; PTPParams *params = (PTPParams *) device->params; uint16_t ret; MTPProperties *prop; if ( device == NULL ) { return value_default; } // This O(n) search should not be used so often, since code // using the cached properties don't usually call this function. prop = ptp_find_object_prop_in_cache(params, object_id, attribute_id); if (prop) return prop->propval.u8; ret = ptp_mtp_getobjectpropvalue(params, object_id, attribute_id, &propval, PTP_DTC_UINT8); if (ret == PTP_RC_OK) { retval = propval.u8; } else { add_ptp_error_to_errorstack(device, ret, "get_u8_from_object(): could not get unsigned 8bit integer from object."); } return retval; } /** * Sets an object attribute from a string * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id PTP attribute ID * @param string string value to set * @return 0 on success, any other value means failure */ static int set_object_string(LIBMTP_mtpdevice_t *device, uint32_t const object_id, uint16_t const attribute_id, char const * const string) { PTPPropertyValue propval; PTPParams *params = (PTPParams *) device->params; uint16_t ret; if (device == NULL || string == NULL) { return -1; } if (!ptp_operation_issupported(params,PTP_OC_MTP_SetObjectPropValue)) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "set_object_string(): could not set object string: " "PTP_OC_MTP_SetObjectPropValue not supported."); return -1; } propval.str = (char *) string; ret = ptp_mtp_setobjectpropvalue(params, object_id, attribute_id, &propval, PTP_DTC_STR); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "set_object_string(): could not set object string."); return -1; } return 0; } /** * Sets an object attribute from an unsigned 32-bit integer * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id PTP attribute ID * @param value 32-bit unsigned integer to set * @return 0 on success, any other value means failure */ static int set_object_u32(LIBMTP_mtpdevice_t *device, uint32_t const object_id, uint16_t const attribute_id, uint32_t const value) { PTPPropertyValue propval; PTPParams *params = (PTPParams *) device->params; uint16_t ret; if (device == NULL) { return -1; } if (!ptp_operation_issupported(params,PTP_OC_MTP_SetObjectPropValue)) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "set_object_u32(): could not set unsigned 32bit integer property: " "PTP_OC_MTP_SetObjectPropValue not supported."); return -1; } propval.u32 = value; ret = ptp_mtp_setobjectpropvalue(params, object_id, attribute_id, &propval, PTP_DTC_UINT32); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "set_object_u32(): could not set unsigned 32bit integer property."); return -1; } return 0; } /** * Sets an object attribute from an unsigned 16-bit integer * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id PTP attribute ID * @param value 16-bit unsigned integer to set * @return 0 on success, any other value means failure */ static int set_object_u16(LIBMTP_mtpdevice_t *device, uint32_t const object_id, uint16_t const attribute_id, uint16_t const value) { PTPPropertyValue propval; PTPParams *params = (PTPParams *) device->params; uint16_t ret; if (device == NULL) { return 1; } if (!ptp_operation_issupported(params,PTP_OC_MTP_SetObjectPropValue)) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "set_object_u16(): could not set unsigned 16bit integer property: " "PTP_OC_MTP_SetObjectPropValue not supported."); return -1; } propval.u16 = value; ret = ptp_mtp_setobjectpropvalue(params, object_id, attribute_id, &propval, PTP_DTC_UINT16); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "set_object_u16(): could not set unsigned 16bit integer property."); return 1; } return 0; } /** * Sets an object attribute from an unsigned 8-bit integer * * @param device a pointer to an MTP device. * @param object_id Object reference * @param attribute_id PTP attribute ID * @param value 8-bit unsigned integer to set * @return 0 on success, any other value means failure */ static int set_object_u8(LIBMTP_mtpdevice_t *device, uint32_t const object_id, uint16_t const attribute_id, uint8_t const value) { PTPPropertyValue propval; PTPParams *params = (PTPParams *) device->params; uint16_t ret; if (device == NULL) { return 1; } if (!ptp_operation_issupported(params,PTP_OC_MTP_SetObjectPropValue)) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "set_object_u8(): could not set unsigned 8bit integer property: " "PTP_OC_MTP_SetObjectPropValue not supported."); return -1; } propval.u8 = value; ret = ptp_mtp_setobjectpropvalue(params, object_id, attribute_id, &propval, PTP_DTC_UINT8); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "set_object_u8(): could not set unsigned 8bit integer property."); return 1; } return 0; } /** * Get the first (as in "first in the list of") connected MTP device. * @return a device pointer. * @see LIBMTP_Get_Connected_Devices() */ LIBMTP_mtpdevice_t *LIBMTP_Get_First_Device(void) { LIBMTP_mtpdevice_t *first_device = NULL; LIBMTP_raw_device_t *devices; int numdevs; LIBMTP_error_number_t ret; ret = LIBMTP_Detect_Raw_Devices(&devices, &numdevs); if (ret != LIBMTP_ERROR_NONE) { return NULL; } if (devices == NULL || numdevs == 0) { return NULL; } first_device = LIBMTP_Open_Raw_Device(&devices[0]); free(devices); return first_device; } /** * Overriding debug function. * This way we can disable debug prints. */ static void #ifdef __GNUC__ __attribute__((__format__(printf,2,0))) #endif LIBMTP_ptp_debug(void *data, const char *format, va_list args) { if ((LIBMTP_debug & LIBMTP_DEBUG_PTP) != 0) { vfprintf (stderr, format, args); fprintf (stderr, "\n"); fflush (stderr); } } /** * Overriding error function. * This way we can capture all error etc to our errorstack. */ static void #ifdef __GNUC__ __attribute__((__format__(printf,2,0))) #endif LIBMTP_ptp_error(void *data, const char *format, va_list args) { // if (data == NULL) { vfprintf (stderr, format, args); fflush (stderr); /* FIXME: find out how we shall get the device here. } else { PTP_USB *ptp_usb = data; LIBMTP_mtpdevice_t *device = ...; char buf[2048]; vsnprintf (buf, sizeof (buf), format, args); add_error_to_errorstack(device, LIBMTP_ERROR_PTP_LAYER, buf); } */ } /** * Parses the extension descriptor, there may be stuff in * this that we want to know about. */ static void parse_extension_descriptor(LIBMTP_mtpdevice_t *mtpdevice, char *desc) { int start = 0; int end = 0; /* NULL on Canon A70 */ if (!desc) return; /* descriptors are divided by semicolons */ while (end < strlen(desc)) { /* Skip past initial whitespace */ while (desc[start] == ' ' && end < strlen(desc)) { start++; end++; } /* Detect extension */ while (desc[end] != ';' && end < strlen(desc)) end++; if (end < strlen(desc)) { char *element = strndup(desc + start, end-start); if (element) { int i = 0; // printf(" Element: \"%s\"\n", element); /* Parse for an extension */ while (element[i] != ':' && i < strlen(element)) i++; if (i < strlen(element)) { char *name = strndup(element, i); int majstart = i+1; // printf(" Extension: \"%s\"\n", name); /* Parse for minor/major punctuation mark for this extension */ while (element[i] != '.' && i < strlen(element)) i++; if (i > majstart && i < strlen(element)) { LIBMTP_device_extension_t *extension; int major = 0; int minor = 0; char *majorstr = strndup(element + majstart, i - majstart); char *minorstr = strndup(element + i + 1, strlen(element) - i - 1); major = atoi(majorstr); minor = atoi(minorstr); free(majorstr); free(minorstr); extension = malloc(sizeof(LIBMTP_device_extension_t)); extension->name = name; extension->major = major; extension->minor = minor; extension->next = NULL; if (mtpdevice->extensions == NULL) { mtpdevice->extensions = extension; } else { LIBMTP_device_extension_t *tmp = mtpdevice->extensions; while (tmp->next != NULL) tmp = tmp->next; tmp->next = extension; } // printf(" Major: \"%s\" (parsed %d) Minor: \"%s\" (parsed %d)\n", // majorstr, major, minorstr, minor); } else { LIBMTP_ERROR("LIBMTP ERROR: couldnt parse extension %s\n", element); } } free(element); } } end++; start = end; } } /** * This function opens a device from a raw device. It is the * preferred way to access devices in the new interface where * several devices can come and go as the library is working * on a certain device. * @param rawdevice the raw device to open a "real" device for. * @return an open device. */ LIBMTP_mtpdevice_t *LIBMTP_Open_Raw_Device_Uncached(LIBMTP_raw_device_t *rawdevice) { LIBMTP_mtpdevice_t *mtp_device; uint8_t bs = 0; PTPParams *current_params; PTP_USB *ptp_usb; LIBMTP_error_number_t err; int i; /* Allocate dynamic space for our device */ mtp_device = (LIBMTP_mtpdevice_t *) malloc(sizeof(LIBMTP_mtpdevice_t)); memset(mtp_device, 0, sizeof(LIBMTP_mtpdevice_t)); /* Check if there was a memory allocation error */ if(mtp_device == NULL) { /* There has been an memory allocation error. We are going to ignore this device and attempt to continue */ /* TODO: This error statement could probably be a bit more robust */ LIBMTP_ERROR("LIBMTP PANIC: connect_usb_devices encountered a memory " "allocation error with device %d on bus %d, trying to continue", rawdevice->devnum, rawdevice->bus_location); return NULL; } // Non-cached by default mtp_device->cached = 0; /* Create PTP params */ current_params = (PTPParams *) malloc(sizeof(PTPParams)); if (current_params == NULL) { free(mtp_device); return NULL; } memset(current_params, 0, sizeof(PTPParams)); current_params->device_flags = rawdevice->device_entry.device_flags; current_params->nrofobjects = 0; current_params->objects = NULL; current_params->response_packet_size = 0; current_params->response_packet = NULL; /* This will be a pointer to PTP_USB later */ current_params->data = NULL; /* Set upp local debug and error functions */ current_params->debug_func = LIBMTP_ptp_debug; current_params->error_func = LIBMTP_ptp_error; /* TODO: Will this always be little endian? */ current_params->byteorder = PTP_DL_LE; current_params->cd_locale_to_ucs2 = iconv_open("UCS-2LE", "UTF-8"); current_params->cd_ucs2_to_locale = iconv_open("UTF-8", "UCS-2LE"); if(current_params->cd_locale_to_ucs2 == (iconv_t) -1 || current_params->cd_ucs2_to_locale == (iconv_t) -1) { LIBMTP_ERROR("LIBMTP PANIC: Cannot open iconv() converters to/from UCS-2!\n" "Too old stdlibc, glibc and libiconv?\n"); free(current_params); free(mtp_device); return NULL; } mtp_device->params = current_params; /* Create usbinfo, this also opens the session */ err = configure_usb_device(rawdevice, current_params, &mtp_device->usbinfo); if (err != LIBMTP_ERROR_NONE) { free(current_params); free(mtp_device); return NULL; } ptp_usb = (PTP_USB*) mtp_device->usbinfo; /* Set pointer back to params */ ptp_usb->params = current_params; /* Cache the device information for later use */ if (ptp_getdeviceinfo(current_params, ¤t_params->deviceinfo) != PTP_RC_OK) { LIBMTP_ERROR("LIBMTP PANIC: Unable to read device information on device " "%d on bus %d, trying to continue", rawdevice->devnum, rawdevice->bus_location); /* Prevent memory leaks for this device */ free(mtp_device->usbinfo); free(mtp_device->params); current_params = NULL; free(mtp_device); return NULL; } /* Check: if this is a PTP device, is it really tagged as MTP? */ if (current_params->deviceinfo.VendorExtensionID != 0x00000006) { LIBMTP_ERROR("LIBMTP WARNING: no MTP vendor extension on device " "%d on bus %d", rawdevice->devnum, rawdevice->bus_location); LIBMTP_ERROR("LIBMTP WARNING: VendorExtensionID: %08x", current_params->deviceinfo.VendorExtensionID); LIBMTP_ERROR("LIBMTP WARNING: VendorExtensionDesc: %s", current_params->deviceinfo.VendorExtensionDesc); LIBMTP_ERROR("LIBMTP WARNING: this typically means the device is PTP " "(i.e. a camera) but not an MTP device at all. " "Trying to continue anyway."); } parse_extension_descriptor(mtp_device, current_params->deviceinfo.VendorExtensionDesc); /* * Android has a number of bugs, force-assign these bug flags * if Android is encountered. Same thing for devices we detect * as SONY NWZ Walkmen. I have no clue what "sony.net/WMFU" means * I just know only NWZs have it. */ { LIBMTP_device_extension_t *tmpext = mtp_device->extensions; int is_microsoft_com_wpdna = 0; int is_android = 0; int is_sony_net_wmfu = 0; int is_sonyericsson_com_se = 0; /* Loop over extensions and set flags */ while (tmpext != NULL) { if (!strcmp(tmpext->name, "microsoft.com/WPDNA")) is_microsoft_com_wpdna = 1; if (!strcmp(tmpext->name, "android.com")) is_android = 1; if (!strcmp(tmpext->name, "sony.net/WMFU")) is_sony_net_wmfu = 1; if (!strcmp(tmpext->name, "sonyericsson.com/SE")) is_sonyericsson_com_se = 1; tmpext = tmpext->next; } /* Check for specific stacks */ if (is_microsoft_com_wpdna && is_sonyericsson_com_se && !is_android) { /* * The Aricent stack seems to be detected by providing WPDNA, the SonyEricsson * extension and NO Android extension. */ ptp_usb->rawdevice.device_entry.device_flags |= DEVICE_FLAGS_ARICENT_BUGS; LIBMTP_INFO("Aricent MTP stack device detected, assigning default bug flags\n"); } else if (is_android) { /* * If bugs are fixed in later versions, test on tmpext->major, tmpext->minor */ ptp_usb->rawdevice.device_entry.device_flags |= DEVICE_FLAGS_ANDROID_BUGS; LIBMTP_INFO("Android device detected, assigning default bug flags\n"); } else if (is_sony_net_wmfu) { ptp_usb->rawdevice.device_entry.device_flags |= DEVICE_FLAGS_SONY_NWZ_BUGS; LIBMTP_INFO("SONY NWZ device detected, assigning default bug flags\n"); } } /* * If the OGG or FLAC filetypes are flagged as "unknown", check * if the firmware has been updated to actually support it. */ if (FLAG_OGG_IS_UNKNOWN(ptp_usb)) { for (i=0;ideviceinfo.ImageFormats_len;i++) { if (current_params->deviceinfo.ImageFormats[i] == PTP_OFC_MTP_OGG) { /* This is not unknown anymore, unflag it */ ptp_usb->rawdevice.device_entry.device_flags &= ~DEVICE_FLAG_OGG_IS_UNKNOWN; break; } } } if (FLAG_FLAC_IS_UNKNOWN(ptp_usb)) { for (i=0;ideviceinfo.ImageFormats_len;i++) { if (current_params->deviceinfo.ImageFormats[i] == PTP_OFC_MTP_FLAC) { /* This is not unknown anymore, unflag it */ ptp_usb->rawdevice.device_entry.device_flags &= ~DEVICE_FLAG_FLAC_IS_UNKNOWN; break; } } } /* Determine if the object size supported is 32 or 64 bit wide */ if (ptp_operation_issupported(current_params,PTP_OC_MTP_GetObjectPropsSupported)) { for (i=0;ideviceinfo.ImageFormats_len;i++) { PTPObjectPropDesc opd; if (ptp_mtp_getobjectpropdesc(current_params, PTP_OPC_ObjectSize, current_params->deviceinfo.ImageFormats[i], &opd) != PTP_RC_OK) { LIBMTP_ERROR("LIBMTP PANIC: " "could not inspect object property descriptions!\n"); } else { if (opd.DataType == PTP_DTC_UINT32) { if (bs == 0) { bs = 32; } else if (bs != 32) { LIBMTP_ERROR("LIBMTP PANIC: " "different objects support different object sizes!\n"); bs = 0; break; } } else if (opd.DataType == PTP_DTC_UINT64) { if (bs == 0) { bs = 64; } else if (bs != 64) { LIBMTP_ERROR("LIBMTP PANIC: " "different objects support different object sizes!\n"); bs = 0; break; } } else { // Ignore if other size. LIBMTP_ERROR("LIBMTP PANIC: " "awkward object size data type: %04x\n", opd.DataType); bs = 0; break; } } } } if (bs == 0) { // Could not detect object bitsize, assume 32 bits bs = 32; } mtp_device->object_bitsize = bs; /* No Errors yet for this device */ mtp_device->errorstack = NULL; /* Default Max Battery Level, we will adjust this if possible */ mtp_device->maximum_battery_level = 100; /* Check if device supports reading maximum battery level */ if(!FLAG_BROKEN_BATTERY_LEVEL(ptp_usb) && ptp_property_issupported( current_params, PTP_DPC_BatteryLevel)) { PTPDevicePropDesc dpd; /* Try to read maximum battery level */ if(ptp_getdevicepropdesc(current_params, PTP_DPC_BatteryLevel, &dpd) != PTP_RC_OK) { add_error_to_errorstack(mtp_device, LIBMTP_ERROR_CONNECTING, "Unable to read Maximum Battery Level for this " "device even though the device supposedly " "supports this functionality"); } /* TODO: is this appropriate? */ /* If max battery level is 0 then leave the default, otherwise assign */ if (dpd.FORM.Range.MaximumValue.u8 != 0) { mtp_device->maximum_battery_level = dpd.FORM.Range.MaximumValue.u8; } ptp_free_devicepropdesc(&dpd); } /* Set all default folders to 0xffffffffU (root directory) */ mtp_device->default_music_folder = 0xffffffffU; mtp_device->default_playlist_folder = 0xffffffffU; mtp_device->default_picture_folder = 0xffffffffU; mtp_device->default_video_folder = 0xffffffffU; mtp_device->default_organizer_folder = 0xffffffffU; mtp_device->default_zencast_folder = 0xffffffffU; mtp_device->default_album_folder = 0xffffffffU; mtp_device->default_text_folder = 0xffffffffU; /* Set initial storage information */ mtp_device->storage = NULL; if (LIBMTP_Get_Storage(mtp_device, LIBMTP_STORAGE_SORTBY_NOTSORTED) == -1) { add_error_to_errorstack(mtp_device, LIBMTP_ERROR_GENERAL, "Get Storage information failed."); mtp_device->storage = NULL; } return mtp_device; } LIBMTP_mtpdevice_t *LIBMTP_Open_Raw_Device(LIBMTP_raw_device_t *rawdevice) { LIBMTP_mtpdevice_t *mtp_device = LIBMTP_Open_Raw_Device_Uncached(rawdevice); if (mtp_device == NULL) return NULL; /* Check for MTPZ devices. */ if (use_mtpz) { LIBMTP_device_extension_t *tmpext = mtp_device->extensions; while (tmpext != NULL) { if (!strcmp(tmpext->name, "microsoft.com/MTPZ")) { LIBMTP_INFO("MTPZ device detected. Authenticating...\n"); if (PTP_RC_OK == ptp_mtpz_handshake(mtp_device->params)) { LIBMTP_INFO ("(MTPZ) Successfully authenticated with device.\n"); } else { LIBMTP_INFO ("(MTPZ) Failure - could not authenticate with device.\n"); } break; } tmpext = tmpext->next; } } // Set up this device as cached mtp_device->cached = 1; /* * Then get the handles and try to locate the default folders. * This has the desired side effect of caching all handles from * the device which speeds up later operations. */ flush_handles(mtp_device); return mtp_device; } /** * To read events sent by the device, repeatedly call this function from a secondary * thread until the return value is < 0. * * @param device a pointer to the MTP device to poll for events. * @param event contains a pointer to be filled in with the event retrieved if the call * is successful. * @param out1 contains the param1 value from the raw event. * @return 0 on success, any other value means the polling loop shall be * terminated immediately for this session. */ int LIBMTP_Read_Event(LIBMTP_mtpdevice_t *device, LIBMTP_event_t *event, uint32_t *out1) { /* * FIXME: Potential race-condition here, if client deallocs device * while we're *not* waiting for input. As we'll be waiting for * input most of the time, it's unlikely but still worth considering * for improvement. Also we cannot affect the state of the cache etc * unless we know we are the sole user on the device. A spinlock or * mutex in the LIBMTP_mtpdevice_t is needed for this to work. */ PTPParams *params = (PTPParams *) device->params; PTPContainer ptp_event; uint16_t ret = ptp_usb_event_wait(params, &ptp_event); uint16_t code; uint32_t session_id; uint32_t transaction_id; uint32_t param1; uint32_t param2; uint32_t param3; if (ret != PTP_RC_OK) { /* Device is closing down or other fatal stuff, exit thread */ return -1; } *event = LIBMTP_EVENT_NONE; /* Process the event */ code = ptp_event.Code; session_id = ptp_event.SessionID; transaction_id = ptp_event.Transaction_ID; param1 = ptp_event.Param1; param2 = ptp_event.Param2; param3 = ptp_event.Param3; switch(code) { case PTP_EC_Undefined: LIBMTP_INFO("Received event PTP_EC_Undefined in session %u\n", session_id); break; case PTP_EC_CancelTransaction: LIBMTP_INFO("Received event PTP_EC_CancelTransaction in session %u\n", session_id); break; case PTP_EC_ObjectAdded: LIBMTP_INFO("Received event PTP_EC_ObjectAdded in session %u\n", session_id); *event = LIBMTP_EVENT_OBJECT_ADDED; *out1 = param1; break; case PTP_EC_ObjectRemoved: LIBMTP_INFO("Received event PTP_EC_ObjectRemoved in session %u\n", session_id); *event = LIBMTP_EVENT_OBJECT_REMOVED; *out1 = param1; break; case PTP_EC_StoreAdded: LIBMTP_INFO("Received event PTP_EC_StoreAdded in session %u\n", session_id); /* TODO: rescan storages */ *event = LIBMTP_EVENT_STORE_ADDED; *out1 = param1; break; case PTP_EC_StoreRemoved: LIBMTP_INFO("Received event PTP_EC_StoreRemoved in session %u\n", session_id); /* TODO: rescan storages */ *event = LIBMTP_EVENT_STORE_REMOVED; *out1 = param1; break; case PTP_EC_DevicePropChanged: LIBMTP_INFO("Received event PTP_EC_DevicePropChanged in session %u\n", session_id); /* TODO: update device properties */ break; case PTP_EC_ObjectInfoChanged: LIBMTP_INFO("Received event PTP_EC_ObjectInfoChanged in session %u\n", session_id); /* TODO: rescan object cache or just for this one object */ break; case PTP_EC_DeviceInfoChanged: LIBMTP_INFO("Received event PTP_EC_DeviceInfoChanged in session %u\n", session_id); /* TODO: update device info */ break; case PTP_EC_RequestObjectTransfer: LIBMTP_INFO("Received event PTP_EC_RequestObjectTransfer in session %u\n", session_id); break; case PTP_EC_StoreFull: LIBMTP_INFO("Received event PTP_EC_StoreFull in session %u\n", session_id); break; case PTP_EC_DeviceReset: LIBMTP_INFO("Received event PTP_EC_DeviceReset in session %u\n", session_id); break; case PTP_EC_StorageInfoChanged : LIBMTP_INFO( "Received event PTP_EC_StorageInfoChanged in session %u\n", session_id); /* TODO: update storage info */ break; case PTP_EC_CaptureComplete : LIBMTP_INFO( "Received event PTP_EC_CaptureComplete in session %u\n", session_id); break; case PTP_EC_UnreportedStatus : LIBMTP_INFO( "Received event PTP_EC_UnreportedStatus in session %u\n", session_id); break; default : LIBMTP_INFO( "Received unknown event in session %u\n", session_id); break; } return 0; } /** * Recursive function that adds MTP devices to a linked list * @param devices a list of raw devices to have real devices created for. * @return a device pointer to a newly created mtpdevice (used in linked * list creation). */ static LIBMTP_mtpdevice_t * create_usb_mtp_devices(LIBMTP_raw_device_t *devices, int numdevs) { uint8_t i; LIBMTP_mtpdevice_t *mtp_device_list = NULL; LIBMTP_mtpdevice_t *current_device = NULL; for (i=0; i < numdevs; i++) { LIBMTP_mtpdevice_t *mtp_device; mtp_device = LIBMTP_Open_Raw_Device(&devices[i]); /* On error, try next device */ if (mtp_device == NULL) continue; /* Add the device to the list */ mtp_device->next = NULL; if (mtp_device_list == NULL) { mtp_device_list = current_device = mtp_device; } else { current_device->next = mtp_device; current_device = mtp_device; } } return mtp_device_list; } /** * Get the number of devices that are available in the listed device list * @param device_list Pointer to a linked list of devices * @return Number of devices in the device list device_list * @see LIBMTP_Get_Connected_Devices() */ uint32_t LIBMTP_Number_Devices_In_List(LIBMTP_mtpdevice_t *device_list) { uint32_t numdevices = 0; LIBMTP_mtpdevice_t *iter; for(iter = device_list; iter != NULL; iter = iter->next) numdevices++; return numdevices; } /** * Get the first connected MTP device node in the linked list of devices. * Currently this only provides access to USB devices * @param device_list A list of devices ready to be used by the caller. You * need to know how many there are. * @return Any error information gathered from device connections * @see LIBMTP_Number_Devices_In_List() */ LIBMTP_error_number_t LIBMTP_Get_Connected_Devices(LIBMTP_mtpdevice_t **device_list) { LIBMTP_raw_device_t *devices; int numdevs; LIBMTP_error_number_t ret; ret = LIBMTP_Detect_Raw_Devices(&devices, &numdevs); if (ret != LIBMTP_ERROR_NONE) { *device_list = NULL; return ret; } /* Assign linked list of devices */ if (devices == NULL || numdevs == 0) { *device_list = NULL; return LIBMTP_ERROR_NO_DEVICE_ATTACHED; } *device_list = create_usb_mtp_devices(devices, numdevs); free(devices); /* TODO: Add wifi device access here */ /* We have found some devices but create failed */ if (*device_list == NULL) return LIBMTP_ERROR_CONNECTING; return LIBMTP_ERROR_NONE; } /** * This closes and releases an allocated MTP device. * @param device a pointer to the MTP device to release. */ void LIBMTP_Release_Device_List(LIBMTP_mtpdevice_t *device) { if(device != NULL) { if(device->next != NULL) { LIBMTP_Release_Device_List(device->next); } LIBMTP_Release_Device(device); } } /** * This closes and releases an allocated MTP device. * @param device a pointer to the MTP device to release. */ void LIBMTP_Release_Device(LIBMTP_mtpdevice_t *device) { PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; close_device(ptp_usb, params); // Clear error stack LIBMTP_Clear_Errorstack(device); // Free iconv() converters... iconv_close(params->cd_locale_to_ucs2); iconv_close(params->cd_ucs2_to_locale); free(ptp_usb); ptp_free_params(params); free(params); free_storage_list(device); // Free extension list... if (device->extensions != NULL) { LIBMTP_device_extension_t *tmp = device->extensions; while (tmp != NULL) { LIBMTP_device_extension_t *next = tmp->next; if (tmp->name) free(tmp->name); free(tmp); tmp = next; } } free(device); } /** * This can be used by any libmtp-intrinsic code that * need to stack up an error on the stack. You are only * supposed to add errors to the error stack using this * function, do not create and reference error entries * directly. */ static void add_error_to_errorstack(LIBMTP_mtpdevice_t *device, LIBMTP_error_number_t errornumber, char const * const error_text) { LIBMTP_error_t *newerror; if (device == NULL) { LIBMTP_ERROR("LIBMTP PANIC: Trying to add error to a NULL device!\n"); return; } newerror = (LIBMTP_error_t *) malloc(sizeof(LIBMTP_error_t)); newerror->errornumber = errornumber; newerror->error_text = strdup(error_text); newerror->next = NULL; if (device->errorstack == NULL) { device->errorstack = newerror; } else { LIBMTP_error_t *tmp = device->errorstack; while (tmp->next != NULL) { tmp = tmp->next; } tmp->next = newerror; } } /** * Adds an error from the PTP layer to the error stack. */ static void add_ptp_error_to_errorstack(LIBMTP_mtpdevice_t *device, uint16_t ptp_error, char const * const error_text) { if (device == NULL) { LIBMTP_ERROR("LIBMTP PANIC: Trying to add PTP error to a NULL device!\n"); return; } else { char outstr[256]; snprintf(outstr, sizeof(outstr), "PTP Layer error %04x: %s", ptp_error, error_text); outstr[sizeof(outstr)-1] = '\0'; add_error_to_errorstack(device, LIBMTP_ERROR_PTP_LAYER, outstr); snprintf(outstr, sizeof(outstr), "Error %04x: %s", ptp_error, ptp_strerror(ptp_error)); outstr[sizeof(outstr)-1] = '\0'; add_error_to_errorstack(device, LIBMTP_ERROR_PTP_LAYER, outstr); } } /** * This returns the error stack for a device in case you * need to either reference the error numbers (e.g. when * creating multilingual apps with multiple-language text * representations for each error number) or when you need * to build a multi-line error text widget or something like * that. You need to call the LIBMTP_Clear_Errorstack * to clear it when you're finished with it. * @param device a pointer to the MTP device to get the error * stack for. * @return the error stack or NULL if there are no errors * on the stack. * @see LIBMTP_Clear_Errorstack() * @see LIBMTP_Dump_Errorstack() */ LIBMTP_error_t *LIBMTP_Get_Errorstack(LIBMTP_mtpdevice_t *device) { if (device == NULL) { LIBMTP_ERROR("LIBMTP PANIC: Trying to get the error stack of a NULL device!\n"); return NULL; } return device->errorstack; } /** * This function clears the error stack of a device and frees * any memory used by it. Call this when you're finished with * using the errors. * @param device a pointer to the MTP device to clear the error * stack for. */ void LIBMTP_Clear_Errorstack(LIBMTP_mtpdevice_t *device) { if (device == NULL) { LIBMTP_ERROR("LIBMTP PANIC: Trying to clear the error stack of a NULL device!\n"); } else { LIBMTP_error_t *tmp = device->errorstack; while (tmp != NULL) { LIBMTP_error_t *tmp2; if (tmp->error_text != NULL) { free(tmp->error_text); } tmp2 = tmp; tmp = tmp->next; free(tmp2); } device->errorstack = NULL; } } /** * This function dumps the error stack to stderr. * (You still have to clear the stack though.) * @param device a pointer to the MTP device to dump the error * stack for. */ void LIBMTP_Dump_Errorstack(LIBMTP_mtpdevice_t *device) { if (device == NULL) { LIBMTP_ERROR("LIBMTP PANIC: Trying to dump the error stack of a NULL device!\n"); } else { LIBMTP_error_t *tmp = device->errorstack; while (tmp != NULL) { if (tmp->error_text != NULL) { LIBMTP_ERROR("Error %d: %s\n", tmp->errornumber, tmp->error_text); } else { LIBMTP_ERROR("Error %d: (unknown)\n", tmp->errornumber); } tmp = tmp->next; } } } /** * This command gets all handles and stuff by FAST directory retrieveal * which is available by getting all metadata for object * 0xffffffff which simply means "all metadata for all objects". * This works on the vast majority of MTP devices (there ARE exceptions!) * and is quite quick. Check the error stack to see if there were * problems getting the metadata. * @return 0 if all was OK, -1 on failure. */ static int get_all_metadata_fast(LIBMTP_mtpdevice_t *device) { PTPParams *params = (PTPParams *) device->params; int cnt = 0; int i, j, nrofprops; uint32_t lasthandle = 0xffffffff; MTPProperties *props = NULL; MTPProperties *prop; uint16_t ret; int oldtimeout; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; /* * The follow request causes the device to generate * a list of every file on the device and return it * in a single response. * * Some slow devices as well as devices with very * large file systems can easily take longer then * the standard timeout value before it is able * to return a response. * * Temporarly set timeout to allow working with * widest range of devices. */ get_usb_device_timeout(ptp_usb, &oldtimeout); set_usb_device_timeout(ptp_usb, 60000); ret = ptp_mtp_getobjectproplist(params, 0xffffffff, &props, &nrofprops); set_usb_device_timeout(ptp_usb, oldtimeout); if (ret == PTP_RC_MTP_Specification_By_Group_Unsupported) { // What's the point in the device implementing this command if // you cannot use it to get all props for AT LEAST one object? // Well, whatever... add_ptp_error_to_errorstack(device, ret, "get_all_metadata_fast(): " "cannot retrieve all metadata for an object on this device."); return -1; } if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "get_all_metadata_fast(): " "could not get proplist of all objects."); return -1; } if (props == NULL && nrofprops != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "get_all_metadata_fast(): " "call to ptp_mtp_getobjectproplist() returned " "inconsistent results."); return -1; } /* * We count the number of objects by counting the ObjectHandle * references, whenever it changes we get a new object, when it's * the same, it is just different properties of the same object. */ prop = props; for (i=0;iObjectHandle) { cnt++; lasthandle = prop->ObjectHandle; } prop++; } lasthandle = 0xffffffff; params->objects = calloc (sizeof(PTPObject),cnt); prop = props; i = -1; for (j=0;jObjectHandle) { if (i >= 0) { params->objects[i].flags |= PTPOBJECT_OBJECTINFO_LOADED; if (!params->objects[i].oi.Filename) { /* I have one such file on my Creative (Marcus) */ params->objects[i].oi.Filename = strdup(""); } } i++; lasthandle = prop->ObjectHandle; params->objects[i].oid = prop->ObjectHandle; } switch (prop->property) { case PTP_OPC_ParentObject: params->objects[i].oi.ParentObject = prop->propval.u32; params->objects[i].flags |= PTPOBJECT_PARENTOBJECT_LOADED; break; case PTP_OPC_ObjectFormat: params->objects[i].oi.ObjectFormat = prop->propval.u16; break; case PTP_OPC_ObjectSize: // We loose precision here, up to 32 bits! However the commands that // retrieve metadata for files and tracks will make sure that the // PTP_OPC_ObjectSize is read in and duplicated again. if (device->object_bitsize == 64) { params->objects[i].oi.ObjectCompressedSize = (uint32_t) prop->propval.u64; } else { params->objects[i].oi.ObjectCompressedSize = prop->propval.u32; } break; case PTP_OPC_StorageID: params->objects[i].oi.StorageID = prop->propval.u32; params->objects[i].flags |= PTPOBJECT_STORAGEID_LOADED; break; case PTP_OPC_ObjectFileName: if (prop->propval.str != NULL) params->objects[i].oi.Filename = strdup(prop->propval.str); break; default: { MTPProperties *newprops; /* Copy all of the other MTP oprierties into the per-object proplist */ if (params->objects[i].nrofmtpprops) { newprops = realloc(params->objects[i].mtpprops, (params->objects[i].nrofmtpprops+1)*sizeof(MTPProperties)); } else { newprops = calloc(sizeof(MTPProperties),1); } if (!newprops) return 0; /* FIXME: error handling? */ params->objects[i].mtpprops = newprops; memcpy(¶ms->objects[i].mtpprops[params->objects[i].nrofmtpprops], &props[j],sizeof(props[j])); params->objects[i].nrofmtpprops++; params->objects[i].flags |= PTPOBJECT_MTPPROPLIST_LOADED; break; } } prop++; } /* mark last entry also */ params->objects[i].flags |= PTPOBJECT_OBJECTINFO_LOADED; params->nrofobjects = i+1; /* The device might not give the list in linear ascending order */ ptp_objects_sort (params); return 0; } /** * This function will recurse through all the directories on the device, * starting at the root directory, gathering metadata as it moves along. * It works better on some devices that will only return data for a * certain directory and does not respect the option to get all metadata * for all objects. */ static void get_handles_recursively(LIBMTP_mtpdevice_t *device, PTPParams *params, uint32_t storageid, uint32_t parent) { PTPObjectHandles currentHandles; int i = 0; uint16_t ret = ptp_getobjecthandles(params, storageid, PTP_GOH_ALL_FORMATS, parent, ¤tHandles); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "get_handles_recursively(): could not get object handles."); return; } if (currentHandles.Handler == NULL || currentHandles.n == 0) return; // Now descend into any subdirectories found for (i = 0; i < currentHandles.n; i++) { PTPObject *ob; ret = ptp_object_want(params,currentHandles.Handler[i], PTPOBJECT_OBJECTINFO_LOADED, &ob); if (ret == PTP_RC_OK) { if (ob->oi.ObjectFormat == PTP_OFC_Association) get_handles_recursively(device, params, storageid, currentHandles.Handler[i]); } else { add_error_to_errorstack(device, LIBMTP_ERROR_CONNECTING, "Found a bad handle, trying to ignore it."); } } free(currentHandles.Handler); } /** * This function refresh the internal handle list whenever * the items stored inside the device is altered. On operations * that do not add or remove objects, this is typically not * called. * @param device a pointer to the MTP device to flush handles for. */ static void flush_handles(LIBMTP_mtpdevice_t *device) { PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; int ret; uint32_t i; if (!device->cached) { return; } if (params->objects != NULL) { for (i=0;inrofobjects;i++) ptp_free_object (¶ms->objects[i]); free(params->objects); params->objects = NULL; params->nrofobjects = 0; } if (ptp_operation_issupported(params,PTP_OC_MTP_GetObjPropList) && !FLAG_BROKEN_MTPGETOBJPROPLIST(ptp_usb) && !FLAG_BROKEN_MTPGETOBJPROPLIST_ALL(ptp_usb)) { // Use the fast method. Ignore return value for now. ret = get_all_metadata_fast(device); } // If the previous failed or returned no objects, use classic // methods instead. if (params->nrofobjects == 0) { // Get all the handles using just standard commands. if (device->storage == NULL) { get_handles_recursively(device, params, PTP_GOH_ALL_STORAGE, PTP_GOH_ROOT_PARENT); } else { // Get handles for each storage in turn. LIBMTP_devicestorage_t *storage = device->storage; while(storage != NULL) { get_handles_recursively(device, params, storage->id, PTP_GOH_ROOT_PARENT); storage = storage->next; } } } /* * Loop over the handles, fix up any NULL filenames or * keywords, then attempt to locate some default folders * in the root directory of the primary storage. */ for(i = 0; i < params->nrofobjects; i++) { PTPObject *ob, *xob; ob = ¶ms->objects[i]; ret = ptp_object_want(params,params->objects[i].oid, PTPOBJECT_OBJECTINFO_LOADED, &xob); if (ret != PTP_RC_OK) { LIBMTP_ERROR("broken! %x not found\n", params->objects[i].oid); } if (ob->oi.Filename == NULL) ob->oi.Filename = strdup(""); if (ob->oi.Keywords == NULL) ob->oi.Keywords = strdup(""); /* Ignore handles that point to non-folders */ if(ob->oi.ObjectFormat != PTP_OFC_Association) continue; /* Only look in the root folder */ if (ob->oi.ParentObject == 0xffffffffU) { LIBMTP_ERROR("object %x has parent 0xffffffff (-1) continuing anyway\n", ob->oid); } else if (ob->oi.ParentObject != 0x00000000U) continue; /* Only look in the primary storage */ if (device->storage != NULL && ob->oi.StorageID != device->storage->id) continue; /* Is this the Music Folder */ if (!strcasecmp(ob->oi.Filename, "My Music") || !strcasecmp(ob->oi.Filename, "My_Music") || !strcasecmp(ob->oi.Filename, "Music")) { device->default_music_folder = ob->oid; } else if (!strcasecmp(ob->oi.Filename, "My Playlists") || !strcasecmp(ob->oi.Filename, "My_Playlists") || !strcasecmp(ob->oi.Filename, "Playlists")) { device->default_playlist_folder = ob->oid; } else if (!strcasecmp(ob->oi.Filename, "My Pictures") || !strcasecmp(ob->oi.Filename, "My_Pictures") || !strcasecmp(ob->oi.Filename, "Pictures")) { device->default_picture_folder = ob->oid; } else if (!strcasecmp(ob->oi.Filename, "My Video") || !strcasecmp(ob->oi.Filename, "My_Video") || !strcasecmp(ob->oi.Filename, "Video")) { device->default_video_folder = ob->oid; } else if (!strcasecmp(ob->oi.Filename, "My Organizer") || !strcasecmp(ob->oi.Filename, "My_Organizer")) { device->default_organizer_folder = ob->oid; } else if (!strcasecmp(ob->oi.Filename, "ZENcast") || !strcasecmp(ob->oi.Filename, "Datacasts")) { device->default_zencast_folder = ob->oid; } else if (!strcasecmp(ob->oi.Filename, "My Albums") || !strcasecmp(ob->oi.Filename, "My_Albums") || !strcasecmp(ob->oi.Filename, "Albums")) { device->default_album_folder = ob->oid; } else if (!strcasecmp(ob->oi.Filename, "Text") || !strcasecmp(ob->oi.Filename, "Texts")) { device->default_text_folder = ob->oid; } } } /** * This function traverses a devices storage list freeing up the * strings and the structs. * @param device a pointer to the MTP device to free the storage * list for. */ static void free_storage_list(LIBMTP_mtpdevice_t *device) { LIBMTP_devicestorage_t *storage; LIBMTP_devicestorage_t *tmp; storage = device->storage; while(storage != NULL) { if (storage->StorageDescription != NULL) { free(storage->StorageDescription); } if (storage->VolumeIdentifier != NULL) { free(storage->VolumeIdentifier); } tmp = storage; storage = storage->next; free(tmp); } device->storage = NULL; return; } /** * This function traverses a devices storage list freeing up the * strings and the structs. * @param device a pointer to the MTP device to free the storage * list for. */ static int sort_storage_by(LIBMTP_mtpdevice_t *device,int const sortby) { LIBMTP_devicestorage_t *oldhead, *ptr1, *ptr2, *newlist; if (device->storage == NULL) return -1; if (sortby == LIBMTP_STORAGE_SORTBY_NOTSORTED) return 0; oldhead = ptr1 = ptr2 = device->storage; newlist = NULL; while(oldhead != NULL) { ptr1 = ptr2 = oldhead; while(ptr1 != NULL) { if (sortby == LIBMTP_STORAGE_SORTBY_FREESPACE && ptr1->FreeSpaceInBytes > ptr2->FreeSpaceInBytes) ptr2 = ptr1; if (sortby == LIBMTP_STORAGE_SORTBY_MAXSPACE && ptr1->FreeSpaceInBytes > ptr2->FreeSpaceInBytes) ptr2 = ptr1; ptr1 = ptr1->next; } // Make our previous entries next point to our next if(ptr2->prev != NULL) { ptr1 = ptr2->prev; ptr1->next = ptr2->next; } else { oldhead = ptr2->next; if(oldhead != NULL) oldhead->prev = NULL; } // Make our next entries previous point to our previous ptr1 = ptr2->next; if(ptr1 != NULL) { ptr1->prev = ptr2->prev; } else { ptr1 = ptr2->prev; if(ptr1 != NULL) ptr1->next = NULL; } if(newlist == NULL) { newlist = ptr2; newlist->prev = NULL; } else { ptr2->prev = newlist; newlist->next = ptr2; newlist = newlist->next; } } if (newlist != NULL) { newlist->next = NULL; while(newlist->prev != NULL) newlist = newlist->prev; device->storage = newlist; } return 0; } /** * This function grabs the first writeable storageid from the * device storage list. * @param device a pointer to the MTP device to locate writeable * storage for. * @param fitsize a file of this file must fit on the device. */ static uint32_t get_writeable_storageid(LIBMTP_mtpdevice_t *device, uint64_t fitsize) { LIBMTP_devicestorage_t *storage; uint32_t store = 0x00000000; //Should this be 0xffffffffu instead? int subcall_ret; // See if there is some storage we can fit this file on. storage = device->storage; if (storage == NULL) { // Sometimes the storage just cannot be detected. store = 0x00000000U; } else { while(storage != NULL) { // These storages cannot be used. if (storage->StorageType == PTP_ST_FixedROM || storage->StorageType == PTP_ST_RemovableROM) { storage = storage->next; continue; } // Storage IDs with the lower 16 bits 0x0000 are not supposed // to be writeable. if ((storage->id & 0x0000FFFFU) == 0x00000000U) { storage = storage->next; continue; } // Also check the access capability to avoid e.g. deletable only storages if (storage->AccessCapability == PTP_AC_ReadOnly || storage->AccessCapability == PTP_AC_ReadOnly_with_Object_Deletion) { storage = storage->next; continue; } // Then see if we can fit the file. subcall_ret = check_if_file_fits(device, storage, fitsize); if (subcall_ret != 0) { storage = storage->next; } else { // We found a storage that is writable and can fit the file! break; } } if (storage == NULL) { add_error_to_errorstack(device, LIBMTP_ERROR_STORAGE_FULL, "get_writeable_storageid(): " "all device storage is full or corrupt."); return -1; } store = storage->id; } return store; } /** * This function grabs the freespace from a certain storage in * device storage list. * @param device a pointer to the MTP device to free the storage * list for. * @param storageid the storage ID for the storage to flush and * get free space for. * @param freespace the free space on this storage will be returned * in this variable. */ static int get_storage_freespace(LIBMTP_mtpdevice_t *device, LIBMTP_devicestorage_t *storage, uint64_t *freespace) { PTPParams *params = (PTPParams *) device->params; // Always query the device about this, since some models explicitly // needs that. We flush all data on queries storage here. if (ptp_operation_issupported(params,PTP_OC_GetStorageInfo)) { PTPStorageInfo storageInfo; uint16_t ret; ret = ptp_getstorageinfo(params, storage->id, &storageInfo); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "get_storage_freespace(): could not get storage info."); return -1; } if (storage->StorageDescription != NULL) { free(storage->StorageDescription); } if (storage->VolumeIdentifier != NULL) { free(storage->VolumeIdentifier); } storage->StorageType = storageInfo.StorageType; storage->FilesystemType = storageInfo.FilesystemType; storage->AccessCapability = storageInfo.AccessCapability; storage->MaxCapacity = storageInfo.MaxCapability; storage->FreeSpaceInBytes = storageInfo.FreeSpaceInBytes; storage->FreeSpaceInObjects = storageInfo.FreeSpaceInImages; storage->StorageDescription = storageInfo.StorageDescription; storage->VolumeIdentifier = storageInfo.VolumeLabel; } if(storage->FreeSpaceInBytes == (uint64_t) -1) return -1; *freespace = storage->FreeSpaceInBytes; return 0; } /** * This function dumps out a large chunk of textual information * provided from the PTP protocol and additionally some extra * MTP-specific information where applicable. * @param device a pointer to the MTP device to report info from. */ void LIBMTP_Dump_Device_Info(LIBMTP_mtpdevice_t *device) { int i; PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; LIBMTP_devicestorage_t *storage = device->storage; LIBMTP_device_extension_t *tmpext = device->extensions; printf("USB low-level info:\n"); dump_usbinfo(ptp_usb); /* Print out some verbose information */ printf("Device info:\n"); printf(" Manufacturer: %s\n", params->deviceinfo.Manufacturer); printf(" Model: %s\n", params->deviceinfo.Model); printf(" Device version: %s\n", params->deviceinfo.DeviceVersion); printf(" Serial number: %s\n", params->deviceinfo.SerialNumber); printf(" Vendor extension ID: 0x%08x\n", params->deviceinfo.VendorExtensionID); printf(" Vendor extension description: %s\n", params->deviceinfo.VendorExtensionDesc); printf(" Detected object size: %d bits\n", device->object_bitsize); printf(" Extensions:\n"); while (tmpext != NULL) { printf(" %s: %d.%d\n", tmpext->name, tmpext->major, tmpext->minor); tmpext = tmpext->next; } printf("Supported operations:\n"); for (i=0;ideviceinfo.OperationsSupported_len;i++) { char txt[256]; (void) ptp_render_opcode(params, params->deviceinfo.OperationsSupported[i], sizeof(txt), txt); printf(" %04x: %s\n", params->deviceinfo.OperationsSupported[i], txt); } printf("Events supported:\n"); if (params->deviceinfo.EventsSupported_len == 0) { printf(" None.\n"); } else { for (i=0;ideviceinfo.EventsSupported_len;i++) { printf(" 0x%04x\n", params->deviceinfo.EventsSupported[i]); } } printf("Device Properties Supported:\n"); for (i=0;ideviceinfo.DevicePropertiesSupported_len;i++) { char const *propdesc = ptp_get_property_description(params, params->deviceinfo.DevicePropertiesSupported[i]); if (propdesc != NULL) { printf(" 0x%04x: %s\n", params->deviceinfo.DevicePropertiesSupported[i], propdesc); } else { uint16_t prop = params->deviceinfo.DevicePropertiesSupported[i]; printf(" 0x%04x: Unknown property\n", prop); } } if (ptp_operation_issupported(params,PTP_OC_MTP_GetObjectPropsSupported)) { printf("Playable File (Object) Types and Object Properties Supported:\n"); for (i=0;ideviceinfo.ImageFormats_len;i++) { char txt[256]; uint16_t ret; uint16_t *props = NULL; uint32_t propcnt = 0; int j; (void) ptp_render_ofc (params, params->deviceinfo.ImageFormats[i], sizeof(txt), txt); printf(" %04x: %s\n", params->deviceinfo.ImageFormats[i], txt); ret = ptp_mtp_getobjectpropssupported (params, params->deviceinfo.ImageFormats[i], &propcnt, &props); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Dump_Device_Info(): " "error on query for object properties."); } else { for (j=0;jdeviceinfo.ImageFormats[i], &opd); if (ret != PTP_RC_OK) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Dump_Device_Info(): " "could not get property description."); break; } if (opd.DataType == PTP_DTC_STR) { printf(" STRING data type"); switch (opd.FormFlag) { case PTP_OPFF_DateTime: printf(" DATETIME FORM"); break; case PTP_OPFF_RegularExpression: printf(" REGULAR EXPRESSION FORM"); break; case PTP_OPFF_LongString: printf(" LONG STRING FORM"); break; default: break; } } else { if (opd.DataType & PTP_DTC_ARRAY_MASK) { printf(" array of"); } switch (opd.DataType & (~PTP_DTC_ARRAY_MASK)) { case PTP_DTC_UNDEF: printf(" UNDEFINED data type"); break; case PTP_DTC_INT8: printf(" INT8 data type"); switch (opd.FormFlag) { case PTP_OPFF_Range: printf(" range: MIN %d, MAX %d, STEP %d", opd.FORM.Range.MinimumValue.i8, opd.FORM.Range.MaximumValue.i8, opd.FORM.Range.StepSize.i8); break; case PTP_OPFF_Enumeration: printf(" enumeration: "); for(k=0;kdeviceinfo.ImageFormats[i] == PTP_OPC_VideoFourCCCodec) { printf(" enumeration of u32 casted FOURCC: "); for (k=0;k> 24) & 0xFFU; fourcc[1] = (opd.FORM.Enum.SupportedValue[k].u32 >> 16) & 0xFFU; fourcc[2] = (opd.FORM.Enum.SupportedValue[k].u32 >> 8) & 0xFFU; fourcc[3] = opd.FORM.Enum.SupportedValue[k].u32 & 0xFFU; fourcc[4] = '\n'; fourcc[5] = '\0'; printf("\"%s\", ", fourcc); } } } else { printf(" enumeration: "); for(k=0;kid); printf(" StorageType: 0x%04x ",storage->StorageType); switch (storage->StorageType) { case PTP_ST_Undefined: printf("(undefined)\n"); break; case PTP_ST_FixedROM: printf("fixed ROM storage\n"); break; case PTP_ST_RemovableROM: printf("removable ROM storage\n"); break; case PTP_ST_FixedRAM: printf("fixed RAM storage\n"); break; case PTP_ST_RemovableRAM: printf("removable RAM storage\n"); break; default: printf("UNKNOWN storage\n"); break; } printf(" FilesystemType: 0x%04x ",storage->FilesystemType); switch(storage->FilesystemType) { case PTP_FST_Undefined: printf("(undefined)\n"); break; case PTP_FST_GenericFlat: printf("generic flat filesystem\n"); break; case PTP_FST_GenericHierarchical: printf("generic hierarchical\n"); break; case PTP_FST_DCF: printf("DCF\n"); break; default: printf("UNKNONWN filesystem type\n"); break; } printf(" AccessCapability: 0x%04x ",storage->AccessCapability); switch(storage->AccessCapability) { case PTP_AC_ReadWrite: printf("read/write\n"); break; case PTP_AC_ReadOnly: printf("read only\n"); break; case PTP_AC_ReadOnly_with_Object_Deletion: printf("read only + object deletion\n"); break; default: printf("UNKNOWN access capability\n"); break; } printf(" MaxCapacity: %llu\n", (long long unsigned int) storage->MaxCapacity); printf(" FreeSpaceInBytes: %llu\n", (long long unsigned int) storage->FreeSpaceInBytes); printf(" FreeSpaceInObjects: %llu\n", (long long unsigned int) storage->FreeSpaceInObjects); printf(" StorageDescription: %s\n",storage->StorageDescription); printf(" VolumeIdentifier: %s\n",storage->VolumeIdentifier); storage = storage->next; } } printf("Special directories:\n"); printf(" Default music folder: 0x%08x\n", device->default_music_folder); printf(" Default playlist folder: 0x%08x\n", device->default_playlist_folder); printf(" Default picture folder: 0x%08x\n", device->default_picture_folder); printf(" Default video folder: 0x%08x\n", device->default_video_folder); printf(" Default organizer folder: 0x%08x\n", device->default_organizer_folder); printf(" Default zencast folder: 0x%08x\n", device->default_zencast_folder); printf(" Default album folder: 0x%08x\n", device->default_album_folder); printf(" Default text folder: 0x%08x\n", device->default_text_folder); } /** * This resets a device in case it supports the PTP_OC_ResetDevice * operation code (0x1010). * @param device a pointer to the device to reset. * @return 0 on success, any other value means failure. */ int LIBMTP_Reset_Device(LIBMTP_mtpdevice_t *device) { PTPParams *params = (PTPParams *) device->params; uint16_t ret; if (!ptp_operation_issupported(params,PTP_OC_ResetDevice)) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Reset_Device(): " "device does not support resetting."); return -1; } ret = ptp_resetdevice(params); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "Error resetting."); return -1; } return 0; } /** * This retrieves the manufacturer name of an MTP device. * @param device a pointer to the device to get the manufacturer name for. * @return a newly allocated UTF-8 string representing the manufacturer name. * The string must be freed by the caller after use. If the call * was unsuccessful this will contain NULL. */ char *LIBMTP_Get_Manufacturername(LIBMTP_mtpdevice_t *device) { char *retmanuf = NULL; PTPParams *params = (PTPParams *) device->params; if (params->deviceinfo.Manufacturer != NULL) { retmanuf = strdup(params->deviceinfo.Manufacturer); } return retmanuf; } /** * This retrieves the model name (often equal to product name) * of an MTP device. * @param device a pointer to the device to get the model name for. * @return a newly allocated UTF-8 string representing the model name. * The string must be freed by the caller after use. If the call * was unsuccessful this will contain NULL. */ char *LIBMTP_Get_Modelname(LIBMTP_mtpdevice_t *device) { char *retmodel = NULL; PTPParams *params = (PTPParams *) device->params; if (params->deviceinfo.Model != NULL) { retmodel = strdup(params->deviceinfo.Model); } return retmodel; } /** * This retrieves the serial number of an MTP device. * @param device a pointer to the device to get the serial number for. * @return a newly allocated UTF-8 string representing the serial number. * The string must be freed by the caller after use. If the call * was unsuccessful this will contain NULL. */ char *LIBMTP_Get_Serialnumber(LIBMTP_mtpdevice_t *device) { char *retnumber = NULL; PTPParams *params = (PTPParams *) device->params; if (params->deviceinfo.SerialNumber != NULL) { retnumber = strdup(params->deviceinfo.SerialNumber); } return retnumber; } /** * This retrieves the device version (hardware and firmware version) of an * MTP device. * @param device a pointer to the device to get the device version for. * @return a newly allocated UTF-8 string representing the device version. * The string must be freed by the caller after use. If the call * was unsuccessful this will contain NULL. */ char *LIBMTP_Get_Deviceversion(LIBMTP_mtpdevice_t *device) { char *retversion = NULL; PTPParams *params = (PTPParams *) device->params; if (params->deviceinfo.DeviceVersion != NULL) { retversion = strdup(params->deviceinfo.DeviceVersion); } return retversion; } /** * This retrieves the "friendly name" of an MTP device. Usually * this is simply the name of the owner or something like * "John Doe's Digital Audio Player". This property should be supported * by all MTP devices. * @param device a pointer to the device to get the friendly name for. * @return a newly allocated UTF-8 string representing the friendly name. * The string must be freed by the caller after use. * @see LIBMTP_Set_Friendlyname() */ char *LIBMTP_Get_Friendlyname(LIBMTP_mtpdevice_t *device) { PTPPropertyValue propval; char *retstring = NULL; PTPParams *params = (PTPParams *) device->params; uint16_t ret; if (!ptp_property_issupported(params, PTP_DPC_MTP_DeviceFriendlyName)) { return NULL; } ret = ptp_getdevicepropvalue(params, PTP_DPC_MTP_DeviceFriendlyName, &propval, PTP_DTC_STR); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "Error getting friendlyname."); return NULL; } if (propval.str != NULL) { retstring = strdup(propval.str); free(propval.str); } return retstring; } /** * Sets the "friendly name" of an MTP device. * @param device a pointer to the device to set the friendly name for. * @param friendlyname the new friendly name for the device. * @return 0 on success, any other value means failure. * @see LIBMTP_Get_Friendlyname() */ int LIBMTP_Set_Friendlyname(LIBMTP_mtpdevice_t *device, char const * const friendlyname) { PTPPropertyValue propval; PTPParams *params = (PTPParams *) device->params; uint16_t ret; if (!ptp_property_issupported(params, PTP_DPC_MTP_DeviceFriendlyName)) { return -1; } propval.str = (char *) friendlyname; ret = ptp_setdevicepropvalue(params, PTP_DPC_MTP_DeviceFriendlyName, &propval, PTP_DTC_STR); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "Error setting friendlyname."); return -1; } return 0; } /** * This retrieves the syncronization partner of an MTP device. This * property should be supported by all MTP devices. * @param device a pointer to the device to get the sync partner for. * @return a newly allocated UTF-8 string representing the synchronization * partner. The string must be freed by the caller after use. * @see LIBMTP_Set_Syncpartner() */ char *LIBMTP_Get_Syncpartner(LIBMTP_mtpdevice_t *device) { PTPPropertyValue propval; char *retstring = NULL; PTPParams *params = (PTPParams *) device->params; uint16_t ret; if (!ptp_property_issupported(params, PTP_DPC_MTP_SynchronizationPartner)) { return NULL; } ret = ptp_getdevicepropvalue(params, PTP_DPC_MTP_SynchronizationPartner, &propval, PTP_DTC_STR); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "Error getting syncpartner."); return NULL; } if (propval.str != NULL) { retstring = strdup(propval.str); free(propval.str); } return retstring; } /** * Sets the synchronization partner of an MTP device. Note that * we have no idea what the effect of setting this to "foobar" * may be. But the general idea seems to be to tell which program * shall synchronize with this device and tell others to leave * it alone. * @param device a pointer to the device to set the sync partner for. * @param syncpartner the new synchronization partner for the device. * @return 0 on success, any other value means failure. * @see LIBMTP_Get_Syncpartner() */ int LIBMTP_Set_Syncpartner(LIBMTP_mtpdevice_t *device, char const * const syncpartner) { PTPPropertyValue propval; PTPParams *params = (PTPParams *) device->params; uint16_t ret; if (!ptp_property_issupported(params, PTP_DPC_MTP_SynchronizationPartner)) { return -1; } propval.str = (char *) syncpartner; ret = ptp_setdevicepropvalue(params, PTP_DPC_MTP_SynchronizationPartner, &propval, PTP_DTC_STR); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "Error setting syncpartner."); return -1; } return 0; } /** * Checks if the device can stora a file of this size or * if it's too big. * @param device a pointer to the device. * @param filesize the size of the file to check whether it will fit. * @param storageid the ID of the storage to try to fit the file on. * @return 0 if the file fits, any other value means failure. */ static int check_if_file_fits(LIBMTP_mtpdevice_t *device, LIBMTP_devicestorage_t *storage, uint64_t const filesize) { PTPParams *params = (PTPParams *) device->params; uint64_t freebytes; int ret; // If we cannot check the storage, no big deal. if (!ptp_operation_issupported(params,PTP_OC_GetStorageInfo)) { return 0; } ret = get_storage_freespace(device, storage, &freebytes); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "check_if_file_fits(): error checking free storage."); return -1; } else { // See if it fits. if (filesize > freebytes) { return -1; } } return 0; } /** * This function retrieves the current battery level on the device. * @param device a pointer to the device to get the battery level for. * @param maximum_level a pointer to a variable that will hold the * maximum level of the battery if the call was successful. * @param current_level a pointer to a variable that will hold the * current level of the battery if the call was successful. * A value of 0 means that the device is on external power. * @return 0 if the storage info was successfully retrieved, any other * means failure. A typical cause of failure is that * the device does not support the battery level property. */ int LIBMTP_Get_Batterylevel(LIBMTP_mtpdevice_t *device, uint8_t * const maximum_level, uint8_t * const current_level) { PTPPropertyValue propval; uint16_t ret; PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; *maximum_level = 0; *current_level = 0; if (FLAG_BROKEN_BATTERY_LEVEL(ptp_usb) || !ptp_property_issupported(params, PTP_DPC_BatteryLevel)) { return -1; } ret = ptp_getdevicepropvalue(params, PTP_DPC_BatteryLevel, &propval, PTP_DTC_UINT8); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Get_Batterylevel(): " "could not get device property value."); return -1; } *maximum_level = device->maximum_battery_level; *current_level = propval.u8; return 0; } /** * Formats device storage (if the device supports the operation). * WARNING: This WILL delete all data from the device. Make sure you've * got confirmation from the user BEFORE you call this function. * * @param device a pointer to the device containing the storage to format. * @param storage the actual storage to format. * @return 0 on success, any other value means failure. */ int LIBMTP_Format_Storage(LIBMTP_mtpdevice_t *device, LIBMTP_devicestorage_t *storage) { uint16_t ret; PTPParams *params = (PTPParams *) device->params; if (!ptp_operation_issupported(params,PTP_OC_FormatStore)) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Format_Storage(): " "device does not support formatting storage."); return -1; } ret = ptp_formatstore(params, storage->id); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Format_Storage(): " "failed to format storage."); return -1; } return 0; } /** * Helper function to extract a unicode property off a device. * This is the standard way of retrieveing unicode device * properties as described by the PTP spec. * @param device a pointer to the device to get the property from. * @param unicstring a pointer to a pointer that will hold the * property after this call is completed. * @param property the property to retrieve. * @return 0 on success, any other value means failure. */ static int get_device_unicode_property(LIBMTP_mtpdevice_t *device, char **unicstring, uint16_t property) { PTPPropertyValue propval; PTPParams *params = (PTPParams *) device->params; uint16_t *tmp; uint16_t ret; int i; if (!ptp_property_issupported(params, property)) { return -1; } // Unicode strings are 16bit unsigned integer arrays. ret = ptp_getdevicepropvalue(params, property, &propval, PTP_DTC_AUINT16); if (ret != PTP_RC_OK) { // TODO: add a note on WHICH property that we failed to get. *unicstring = NULL; add_ptp_error_to_errorstack(device, ret, "get_device_unicode_property(): " "failed to get unicode property."); return -1; } // Extract the actual array. // printf("Array of %d elements\n", propval.a.count); tmp = malloc((propval.a.count + 1)*sizeof(uint16_t)); for (i = 0; i < propval.a.count; i++) { tmp[i] = propval.a.v[i].u16; // printf("%04x ", tmp[i]); } tmp[propval.a.count] = 0x0000U; free(propval.a.v); *unicstring = utf16_to_utf8(device, tmp); free(tmp); return 0; } /** * This function returns the secure time as an XML document string from * the device. * @param device a pointer to the device to get the secure time for. * @param sectime the secure time string as an XML document or NULL if the call * failed or the secure time property is not supported. This string * must be free():ed by the caller after use. * @return 0 on success, any other value means failure. */ int LIBMTP_Get_Secure_Time(LIBMTP_mtpdevice_t *device, char ** const sectime) { return get_device_unicode_property(device, sectime, PTP_DPC_MTP_SecureTime); } /** * This function returns the device (public key) certificate as an * XML document string from the device. * @param device a pointer to the device to get the device certificate for. * @param devcert the device certificate as an XML string or NULL if the call * failed or the device certificate property is not supported. This * string must be free():ed by the caller after use. * @return 0 on success, any other value means failure. */ int LIBMTP_Get_Device_Certificate(LIBMTP_mtpdevice_t *device, char ** const devcert) { return get_device_unicode_property(device, devcert, PTP_DPC_MTP_DeviceCertificate); } /** * This function retrieves a list of supported file types, i.e. the file * types that this device claims it supports, e.g. audio file types that * the device can play etc. This list is mitigated to * inlcude the file types that libmtp can handle, i.e. it will not list * filetypes that libmtp will handle internally like playlists and folders. * @param device a pointer to the device to get the filetype capabilities for. * @param filetypes a pointer to a pointer that will hold the list of * supported filetypes if the call was successful. This list must * be free():ed by the caller after use. * @param length a pointer to a variable that will hold the length of the * list of supported filetypes if the call was successful. * @return 0 on success, any other value means failure. * @see LIBMTP_Get_Filetype_Description() */ int LIBMTP_Get_Supported_Filetypes(LIBMTP_mtpdevice_t *device, uint16_t ** const filetypes, uint16_t * const length) { PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; uint16_t *localtypes; uint16_t localtypelen; uint32_t i; // This is more memory than needed if there are unknown types, but what the heck. localtypes = (uint16_t *) malloc(params->deviceinfo.ImageFormats_len * sizeof(uint16_t)); localtypelen = 0; for (i=0;ideviceinfo.ImageFormats_len;i++) { uint16_t localtype = map_ptp_type_to_libmtp_type(params->deviceinfo.ImageFormats[i]); if (localtype != LIBMTP_FILETYPE_UNKNOWN) { localtypes[localtypelen] = localtype; localtypelen++; } } // The forgotten Ogg support on YP-10 and others... if (FLAG_OGG_IS_UNKNOWN(ptp_usb)) { localtypes = (uint16_t *) realloc(localtypes, (params->deviceinfo.ImageFormats_len+1) * sizeof(uint16_t)); localtypes[localtypelen] = LIBMTP_FILETYPE_OGG; localtypelen++; } // The forgotten FLAC support on Cowon iAudio S9 and others... if (FLAG_FLAC_IS_UNKNOWN(ptp_usb)) { localtypes = (uint16_t *) realloc(localtypes, (params->deviceinfo.ImageFormats_len+1) * sizeof(uint16_t)); localtypes[localtypelen] = LIBMTP_FILETYPE_FLAC; localtypelen++; } *filetypes = localtypes; *length = localtypelen; return 0; } /** * This function checks if the device has some specific capabilities, in * order to avoid calling APIs that may disturb the device. * * @param device a pointer to the device to check the capability on. * @param cap the capability to check. * @return 0 if not supported, any other value means the device has the * requested capability. */ int LIBMTP_Check_Capability(LIBMTP_mtpdevice_t *device, LIBMTP_devicecap_t cap) { switch (cap) { case LIBMTP_DEVICECAP_GetPartialObject: return (ptp_operation_issupported(device->params, PTP_OC_GetPartialObject) || ptp_operation_issupported(device->params, PTP_OC_ANDROID_GetPartialObject64)); case LIBMTP_DEVICECAP_SendPartialObject: return ptp_operation_issupported(device->params, PTP_OC_ANDROID_SendPartialObject); case LIBMTP_DEVICECAP_EditObjects: return (ptp_operation_issupported(device->params, PTP_OC_ANDROID_TruncateObject) && ptp_operation_issupported(device->params, PTP_OC_ANDROID_BeginEditObject) && ptp_operation_issupported(device->params, PTP_OC_ANDROID_EndEditObject)); /* * Handle other capabilities here, this is also a good place to * blacklist some advanced operations on specific devices if need * be. */ default: break; } return 0; } /** * This function updates all the storage id's of a device and their * properties, then creates a linked list and puts the list head into * the device struct. It also optionally sorts this list. If you want * to display storage information in your application you should call * this function, then dereference the device struct * (device->storage) to get out information on the storage. * * You need to call this everytime you want to update the * device->storage list, for example anytime you need * to check available storage somewhere. * * WARNING: since this list is dynamically updated, do not * reference its fields in external applications by pointer! E.g * do not put a reference to any char * field. instead * strncpy() it! * * @param device a pointer to the device to get the storage for. * @param sortby an integer that determines the sorting of the storage list. * Valid sort methods are defined in libmtp.h with beginning with * LIBMTP_STORAGE_SORTBY_. 0 or LIBMTP_STORAGE_SORTBY_NOTSORTED to not * sort. * @return 0 on success, 1 success but only with storage id's, storage * properities could not be retrieved and -1 means failure. */ int LIBMTP_Get_Storage(LIBMTP_mtpdevice_t *device, int const sortby) { uint32_t i = 0; PTPStorageInfo storageInfo; PTPParams *params = (PTPParams *) device->params; PTPStorageIDs storageIDs; LIBMTP_devicestorage_t *storage = NULL; LIBMTP_devicestorage_t *storageprev = NULL; if (device->storage != NULL) free_storage_list(device); // if (!ptp_operation_issupported(params,PTP_OC_GetStorageIDs)) // return -1; if (ptp_getstorageids (params, &storageIDs) != PTP_RC_OK) return -1; if (storageIDs.n < 1) return -1; if (!ptp_operation_issupported(params,PTP_OC_GetStorageInfo)) { for (i = 0; i < storageIDs.n; i++) { storage = (LIBMTP_devicestorage_t *) malloc(sizeof(LIBMTP_devicestorage_t)); storage->prev = storageprev; if (storageprev != NULL) storageprev->next = storage; if (device->storage == NULL) device->storage = storage; storage->id = storageIDs.Storage[i]; storage->StorageType = PTP_ST_Undefined; storage->FilesystemType = PTP_FST_Undefined; storage->AccessCapability = PTP_AC_ReadWrite; storage->MaxCapacity = (uint64_t) -1; storage->FreeSpaceInBytes = (uint64_t) -1; storage->FreeSpaceInObjects = (uint64_t) -1; storage->StorageDescription = strdup("Unknown storage"); storage->VolumeIdentifier = strdup("Unknown volume"); storage->next = NULL; storageprev = storage; } free(storageIDs.Storage); return 1; } else { for (i = 0; i < storageIDs.n; i++) { uint16_t ret; ret = ptp_getstorageinfo(params, storageIDs.Storage[i], &storageInfo); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Get_Storage(): " "Could not get storage info."); if (device->storage != NULL) { free_storage_list(device); } return -1; } storage = (LIBMTP_devicestorage_t *) malloc(sizeof(LIBMTP_devicestorage_t)); storage->prev = storageprev; if (storageprev != NULL) storageprev->next = storage; if (device->storage == NULL) device->storage = storage; storage->id = storageIDs.Storage[i]; storage->StorageType = storageInfo.StorageType; storage->FilesystemType = storageInfo.FilesystemType; storage->AccessCapability = storageInfo.AccessCapability; storage->MaxCapacity = storageInfo.MaxCapability; storage->FreeSpaceInBytes = storageInfo.FreeSpaceInBytes; storage->FreeSpaceInObjects = storageInfo.FreeSpaceInImages; storage->StorageDescription = storageInfo.StorageDescription; storage->VolumeIdentifier = storageInfo.VolumeLabel; storage->next = NULL; storageprev = storage; } if (storage != NULL) storage->next = NULL; sort_storage_by(device,sortby); free(storageIDs.Storage); return 0; } } /** * This creates a new file metadata structure and allocates memory * for it. Notice that if you add strings to this structure they * will be freed by the corresponding LIBMTP_destroy_file_t * operation later, so be careful of using strdup() when assigning * strings, e.g.: * *
 * LIBMTP_file_t *file = LIBMTP_new_file_t();
 * file->filename = strdup(namestr);
 * ....
 * LIBMTP_destroy_file_t(file);
 * 
* * @return a pointer to the newly allocated metadata structure. * @see LIBMTP_destroy_file_t() */ LIBMTP_file_t *LIBMTP_new_file_t(void) { LIBMTP_file_t *new = (LIBMTP_file_t *) malloc(sizeof(LIBMTP_file_t)); if (new == NULL) { return NULL; } new->filename = NULL; new->item_id = 0; new->parent_id = 0; new->storage_id = 0; new->filesize = 0; new->modificationdate = 0; new->filetype = LIBMTP_FILETYPE_UNKNOWN; new->next = NULL; return new; } /** * This destroys a file metadata structure and deallocates the memory * used by it, including any strings. Never use a file metadata * structure again after calling this function on it. * @param file the file metadata to destroy. * @see LIBMTP_new_file_t() */ void LIBMTP_destroy_file_t(LIBMTP_file_t *file) { if (file == NULL) { return; } if (file->filename != NULL) free(file->filename); free(file); return; } /** * Helper function that takes one PTP object and creates a * LIBMTP_file_t metadata entry. */ static LIBMTP_file_t *obj2file(LIBMTP_mtpdevice_t *device, PTPObject *ob) { PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; LIBMTP_file_t *file; int i; // Allocate a new file type file = LIBMTP_new_file_t(); file->parent_id = ob->oi.ParentObject; file->storage_id = ob->oi.StorageID; // Set the filetype file->filetype = map_ptp_type_to_libmtp_type(ob->oi.ObjectFormat); /* * A special quirk for devices that doesn't quite * remember that some files marked as "unknown" type are * actually OGG or FLAC files. We look at the filename extension * and see if it happens that this was atleast named "ogg" or "flac" * and fall back on this heuristic approach in that case, * for these bugged devices only. */ if (file->filetype == LIBMTP_FILETYPE_UNKNOWN) { if ((FLAG_IRIVER_OGG_ALZHEIMER(ptp_usb) || FLAG_OGG_IS_UNKNOWN(ptp_usb)) && has_ogg_extension(file->filename)) { file->filetype = LIBMTP_FILETYPE_OGG; } if (FLAG_FLAC_IS_UNKNOWN(ptp_usb) && has_flac_extension(file->filename)) { file->filetype = LIBMTP_FILETYPE_FLAC; } } // Set the modification date file->modificationdate = ob->oi.ModificationDate; // We only have 32-bit file size here; later we use the PTP_OPC_ObjectSize property file->filesize = ob->oi.ObjectCompressedSize; if (ob->oi.Filename != NULL) { file->filename = strdup(ob->oi.Filename); } // This is a unique ID so we can keep track of the file. file->item_id = ob->oid; /* * If we have a cached, large set of metadata, then use it! */ if (ob->mtpprops) { MTPProperties *prop = ob->mtpprops; for (i=0; i < ob->nrofmtpprops; i++, prop++) { // Pick ObjectSize here... if (prop->property == PTP_OPC_ObjectSize) { // This may already be set, but this 64bit precision value // is better than the PTP 32bit value, so let it override. if (device->object_bitsize == 64) { file->filesize = prop->propval.u64; } else { file->filesize = prop->propval.u32; } break; } } } else if (ptp_operation_issupported(params,PTP_OC_MTP_GetObjectPropsSupported)) { uint16_t *props = NULL; uint32_t propcnt = 0; int ret; // First see which properties can be retrieved for this object format ret = ptp_mtp_getobjectpropssupported(params, map_libmtp_type_to_ptp_type(file->filetype), &propcnt, &props); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "obj2file: call to ptp_mtp_getobjectpropssupported() failed."); // Silently fall through. } else { for (i = 0; i < propcnt; i++) { switch (props[i]) { case PTP_OPC_ObjectSize: if (device->object_bitsize == 64) { file->filesize = get_u64_from_object(device, file->item_id, PTP_OPC_ObjectSize, 0); } else { file->filesize = get_u32_from_object(device, file->item_id, PTP_OPC_ObjectSize, 0); } break; default: break; } } free(props); } } return file; } /** * This function retrieves the metadata for a single file off * the device. * * Do not call this function repeatedly! The file handles are linearly * searched O(n) and the call may involve (slow) USB traffic, so use * LIBMTP_Get_Filelisting() and cache the file, preferably * as an efficient data structure such as a hash list. * * Incidentally this function will return metadata for * a folder (association) as well, but this is not a proper use * of it, it is intended for file manipulation, not folder manipulation. * * @param device a pointer to the device to get the file metadata from. * @param fileid the object ID of the file that you want the metadata for. * @return a metadata entry on success or NULL on failure. * @see LIBMTP_Get_Filelisting() */ LIBMTP_file_t *LIBMTP_Get_Filemetadata(LIBMTP_mtpdevice_t *device, uint32_t const fileid) { PTPParams *params = (PTPParams *) device->params; uint16_t ret; PTPObject *ob; // Get all the handles if we haven't already done that // (Only on cached devices.) if (device->cached && params->nrofobjects == 0) { flush_handles(device); } ret = ptp_object_want(params, fileid, PTPOBJECT_OBJECTINFO_LOADED|PTPOBJECT_MTPPROPLIST_LOADED, &ob); if (ret != PTP_RC_OK) return NULL; return obj2file(device, ob); } /** * THIS FUNCTION IS DEPRECATED. PLEASE UPDATE YOUR CODE IN ORDER * NOT TO USE IT. * @see LIBMTP_Get_Filelisting_With_Callback() */ LIBMTP_file_t *LIBMTP_Get_Filelisting(LIBMTP_mtpdevice_t *device) { LIBMTP_INFO("WARNING: LIBMTP_Get_Filelisting() is deprecated.\n"); LIBMTP_INFO("WARNING: please update your code to use LIBMTP_Get_Filelisting_With_Callback()\n"); return LIBMTP_Get_Filelisting_With_Callback(device, NULL, NULL); } /** * This returns a long list of all files available * on the current MTP device. Folders will not be returned, but abstract * entities like playlists and albums will show up as "files". Typical usage: * *
 * LIBMTP_file_t *filelist;
 *
 * filelist = LIBMTP_Get_Filelisting_With_Callback(device, callback, data);
 * while (filelist != NULL) {
 *   LIBMTP_file_t *tmp;
 *
 *   // Do something on each element in the list here...
 *   tmp = filelist;
 *   filelist = filelist->next;
 *   LIBMTP_destroy_file_t(tmp);
 * }
 * 
* * If you want to group your file listing by storage (per storage unit) or * arrange files into folders, you must dereference the storage_id * and/or parent_id field of the returned LIBMTP_file_t * struct. To arrange by folders or files you typically have to create the proper * trees by calls to LIBMTP_Get_Storage() and/or * LIBMTP_Get_Folder_List() first. * * @param device a pointer to the device to get the file listing for. * @param callback a function to be called during the tracklisting retrieveal * for displaying progress bars etc, or NULL if you don't want * any callbacks. * @param data a user-defined pointer that is passed along to * the progress function in order to * pass along some user defined data to the progress * updates. If not used, set this to NULL. * @return a list of files that can be followed using the next * field of the LIBMTP_file_t data structure. * Each of the metadata tags must be freed after use, and may * contain only partial metadata information, i.e. one or several * fields may be NULL or 0. * @see LIBMTP_Get_Filemetadata() */ LIBMTP_file_t *LIBMTP_Get_Filelisting_With_Callback(LIBMTP_mtpdevice_t *device, LIBMTP_progressfunc_t const callback, void const * const data) { uint32_t i = 0; LIBMTP_file_t *retfiles = NULL; LIBMTP_file_t *curfile = NULL; PTPParams *params = (PTPParams *) device->params; // Get all the handles if we haven't already done that if (params->nrofobjects == 0) { flush_handles(device); } for (i = 0; i < params->nrofobjects; i++) { LIBMTP_file_t *file; PTPObject *ob; if (callback != NULL) callback(i, params->nrofobjects, data); ob = ¶ms->objects[i]; if (ob->oi.ObjectFormat == PTP_OFC_Association) { // MTP use this object format for folders which means // these "files" will turn up on a folder listing instead. continue; } // Look up metadata file = obj2file(device, ob); if (file == NULL) { continue; } // Add track to a list that will be returned afterwards. if (retfiles == NULL) { retfiles = file; curfile = file; } else { curfile->next = file; curfile = file; } // Call listing callback // double progressPercent = (double)i*(double)100.0 / (double)params->handles.n; } // Handle counting loop return retfiles; } /** * This function retrieves the contents of a certain folder * with id parent on a certain storage on a certain device. * The result contains both files and folders. * The device used with this operations must have been opened with * LIBMTP_Open_Raw_Device_Uncached() or it will fail. * * NOTE: the request will always perform I/O with the device. * @param device a pointer to the MTP device to report info from. * @param storage a storage on the device to report info from. If * 0 is passed in, the files for the given parent will be * searched across all available storages. * @param parent the parent folder id. */ LIBMTP_file_t * LIBMTP_Get_Files_And_Folders(LIBMTP_mtpdevice_t *device, uint32_t const storage, uint32_t const parent) { PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; LIBMTP_file_t *retfiles = NULL; LIBMTP_file_t *curfile = NULL; PTPObjectHandles currentHandles; uint32_t storageid; uint16_t ret; int i = 0; if (device->cached) { // This function is only supposed to be used by devices // opened as uncached! LIBMTP_ERROR("tried to use %s on a cached device!\n", __func__); return NULL; } if (FLAG_BROKEN_GET_OBJECT_PROPVAL(ptp_usb)) { // These devices cannot handle the commands needed for // Uncached access! LIBMTP_ERROR("tried to use %s on an unsupported device, " "this command does not work on all devices " "due to missing low-level support to read " "information on individual tracks\n", __func__); return NULL; } if (storage == 0) storageid = PTP_GOH_ALL_STORAGE; else storageid = storage; ret = ptp_getobjecthandles(params, storageid, PTP_GOH_ALL_FORMATS, parent, ¤tHandles); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Get_Files_And_Folders(): could not get object handles."); return NULL; } if (currentHandles.Handler == NULL || currentHandles.n == 0) return NULL; for (i = 0; i < currentHandles.n; i++) { LIBMTP_file_t *file; // Get metadata for one file, if it fails, try next file file = LIBMTP_Get_Filemetadata(device, currentHandles.Handler[i]); if (file == NULL) continue; // Add track to a list that will be returned afterwards. if (curfile == NULL) { curfile = file; retfiles = file; } else { curfile->next = file; curfile = file; } } free(currentHandles.Handler); // Return a pointer to the original first file // in the big list. return retfiles; } /** * This creates a new track metadata structure and allocates memory * for it. Notice that if you add strings to this structure they * will be freed by the corresponding LIBMTP_destroy_track_t * operation later, so be careful of using strdup() when assigning * strings, e.g.: * *
 * LIBMTP_track_t *track = LIBMTP_new_track_t();
 * track->title = strdup(titlestr);
 * ....
 * LIBMTP_destroy_track_t(track);
 * 
* * @return a pointer to the newly allocated metadata structure. * @see LIBMTP_destroy_track_t() */ LIBMTP_track_t *LIBMTP_new_track_t(void) { LIBMTP_track_t *new = (LIBMTP_track_t *) malloc(sizeof(LIBMTP_track_t)); if (new == NULL) { return NULL; } new->item_id = 0; new->parent_id = 0; new->storage_id = 0; new->title = NULL; new->artist = NULL; new->composer = NULL; new->album = NULL; new->genre = NULL; new->date = NULL; new->filename = NULL; new->duration = 0; new->tracknumber = 0; new->filesize = 0; new->filetype = LIBMTP_FILETYPE_UNKNOWN; new->samplerate = 0; new->nochannels = 0; new->wavecodec = 0; new->bitrate = 0; new->bitratetype = 0; new->rating = 0; new->usecount = 0; new->modificationdate = 0; new->next = NULL; return new; } /** * This destroys a track metadata structure and deallocates the memory * used by it, including any strings. Never use a track metadata * structure again after calling this function on it. * @param track the track metadata to destroy. * @see LIBMTP_new_track_t() */ void LIBMTP_destroy_track_t(LIBMTP_track_t *track) { if (track == NULL) { return; } if (track->title != NULL) free(track->title); if (track->artist != NULL) free(track->artist); if (track->composer != NULL) free(track->composer); if (track->album != NULL) free(track->album); if (track->genre != NULL) free(track->genre); if (track->date != NULL) free(track->date); if (track->filename != NULL) free(track->filename); free(track); return; } /** * This function maps and copies a property onto the track metadata if applicable. */ static void pick_property_to_track_metadata(LIBMTP_mtpdevice_t *device, MTPProperties *prop, LIBMTP_track_t *track) { switch (prop->property) { case PTP_OPC_Name: if (prop->propval.str != NULL) track->title = strdup(prop->propval.str); else track->title = NULL; break; case PTP_OPC_Artist: if (prop->propval.str != NULL) track->artist = strdup(prop->propval.str); else track->artist = NULL; break; case PTP_OPC_Composer: if (prop->propval.str != NULL) track->composer = strdup(prop->propval.str); else track->composer = NULL; break; case PTP_OPC_Duration: track->duration = prop->propval.u32; break; case PTP_OPC_Track: track->tracknumber = prop->propval.u16; break; case PTP_OPC_Genre: if (prop->propval.str != NULL) track->genre = strdup(prop->propval.str); else track->genre = NULL; break; case PTP_OPC_AlbumName: if (prop->propval.str != NULL) track->album = strdup(prop->propval.str); else track->album = NULL; break; case PTP_OPC_OriginalReleaseDate: if (prop->propval.str != NULL) track->date = strdup(prop->propval.str); else track->date = NULL; break; // These are, well not so important. case PTP_OPC_SampleRate: track->samplerate = prop->propval.u32; break; case PTP_OPC_NumberOfChannels: track->nochannels = prop->propval.u16; break; case PTP_OPC_AudioWAVECodec: track->wavecodec = prop->propval.u32; break; case PTP_OPC_AudioBitRate: track->bitrate = prop->propval.u32; break; case PTP_OPC_BitRateType: track->bitratetype = prop->propval.u16; break; case PTP_OPC_Rating: track->rating = prop->propval.u16; break; case PTP_OPC_UseCount: track->usecount = prop->propval.u32; break; case PTP_OPC_ObjectSize: if (device->object_bitsize == 64) { track->filesize = prop->propval.u64; } else { track->filesize = prop->propval.u32; } break; default: break; } } /** * This function retrieves the track metadata for a track * given by a unique ID. * @param device a pointer to the device to get the track metadata off. * @param trackid the unique ID of the track. * @param objectformat the object format of this track, so we know what it supports. * @param track a metadata set to fill in. */ static void get_track_metadata(LIBMTP_mtpdevice_t *device, uint16_t objectformat, LIBMTP_track_t *track) { uint16_t ret; PTPParams *params = (PTPParams *) device->params; uint32_t i; MTPProperties *prop; PTPObject *ob; /* * If we have a cached, large set of metadata, then use it! */ ret = ptp_object_want(params, track->item_id, PTPOBJECT_MTPPROPLIST_LOADED, &ob); if (ob->mtpprops) { prop = ob->mtpprops; for (i=0;inrofmtpprops;i++,prop++) pick_property_to_track_metadata(device, prop, track); } else { uint16_t *props = NULL; uint32_t propcnt = 0; // First see which properties can be retrieved for this object format ret = ptp_mtp_getobjectpropssupported(params, map_libmtp_type_to_ptp_type(track->filetype), &propcnt, &props); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "get_track_metadata(): call to ptp_mtp_getobjectpropssupported() failed."); // Just bail out for now, nothing is ever set. return; } else { for (i=0;ititle = get_string_from_object(device, track->item_id, PTP_OPC_Name); break; case PTP_OPC_Artist: track->artist = get_string_from_object(device, track->item_id, PTP_OPC_Artist); break; case PTP_OPC_Composer: track->composer = get_string_from_object(device, track->item_id, PTP_OPC_Composer); break; case PTP_OPC_Duration: track->duration = get_u32_from_object(device, track->item_id, PTP_OPC_Duration, 0); break; case PTP_OPC_Track: track->tracknumber = get_u16_from_object(device, track->item_id, PTP_OPC_Track, 0); break; case PTP_OPC_Genre: track->genre = get_string_from_object(device, track->item_id, PTP_OPC_Genre); break; case PTP_OPC_AlbumName: track->album = get_string_from_object(device, track->item_id, PTP_OPC_AlbumName); break; case PTP_OPC_OriginalReleaseDate: track->date = get_string_from_object(device, track->item_id, PTP_OPC_OriginalReleaseDate); break; // These are, well not so important. case PTP_OPC_SampleRate: track->samplerate = get_u32_from_object(device, track->item_id, PTP_OPC_SampleRate, 0); break; case PTP_OPC_NumberOfChannels: track->nochannels = get_u16_from_object(device, track->item_id, PTP_OPC_NumberOfChannels, 0); break; case PTP_OPC_AudioWAVECodec: track->wavecodec = get_u32_from_object(device, track->item_id, PTP_OPC_AudioWAVECodec, 0); break; case PTP_OPC_AudioBitRate: track->bitrate = get_u32_from_object(device, track->item_id, PTP_OPC_AudioBitRate, 0); break; case PTP_OPC_BitRateType: track->bitratetype = get_u16_from_object(device, track->item_id, PTP_OPC_BitRateType, 0); break; case PTP_OPC_Rating: track->rating = get_u16_from_object(device, track->item_id, PTP_OPC_Rating, 0); break; case PTP_OPC_UseCount: track->usecount = get_u32_from_object(device, track->item_id, PTP_OPC_UseCount, 0); break; case PTP_OPC_ObjectSize: if (device->object_bitsize == 64) { track->filesize = get_u64_from_object(device, track->item_id, PTP_OPC_ObjectSize, 0); } else { track->filesize = (uint64_t) get_u32_from_object(device, track->item_id, PTP_OPC_ObjectSize, 0); } break; } } free(props); } } } /** * THIS FUNCTION IS DEPRECATED. PLEASE UPDATE YOUR CODE IN ORDER * NOT TO USE IT. * @see LIBMTP_Get_Tracklisting_With_Callback() */ LIBMTP_track_t *LIBMTP_Get_Tracklisting(LIBMTP_mtpdevice_t *device) { LIBMTP_INFO("WARNING: LIBMTP_Get_Tracklisting() is deprecated.\n"); LIBMTP_INFO("WARNING: please update your code to use LIBMTP_Get_Tracklisting_With_Callback()\n"); return LIBMTP_Get_Tracklisting_With_Callback(device, NULL, NULL); } /** * This returns a long list of all tracks available on the current MTP device. * Tracks include multimedia objects, both music tracks and video tracks. * Typical usage: * *
 * LIBMTP_track_t *tracklist;
 *
 * tracklist = LIBMTP_Get_Tracklisting_With_Callback(device, callback, data);
 * while (tracklist != NULL) {
 *   LIBMTP_track_t *tmp;
 *
 *   // Do something on each element in the list here...
 *   tmp = tracklist;
 *   tracklist = tracklist->next;
 *   LIBMTP_destroy_track_t(tmp);
 * }
 * 
* * If you want to group your track listing by storage (per storage unit) or * arrange tracks into folders, you must dereference the storage_id * and/or parent_id field of the returned LIBMTP_track_t * struct. To arrange by folders or files you typically have to create the proper * trees by calls to LIBMTP_Get_Storage() and/or * LIBMTP_Get_Folder_List() first. * * @param device a pointer to the device to get the track listing for. * @param callback a function to be called during the tracklisting retrieveal * for displaying progress bars etc, or NULL if you don't want * any callbacks. * @param data a user-defined pointer that is passed along to * the progress function in order to * pass along some user defined data to the progress * updates. If not used, set this to NULL. * @return a list of tracks that can be followed using the next * field of the LIBMTP_track_t data structure. * Each of the metadata tags must be freed after use, and may * contain only partial metadata information, i.e. one or several * fields may be NULL or 0. * @see LIBMTP_Get_Trackmetadata() */ LIBMTP_track_t *LIBMTP_Get_Tracklisting_With_Callback(LIBMTP_mtpdevice_t *device, LIBMTP_progressfunc_t const callback, void const * const data) { return LIBMTP_Get_Tracklisting_With_Callback_For_Storage(device, 0, callback, data); } /** * This returns a long list of all tracks available on the current MTP device. * Tracks include multimedia objects, both music tracks and video tracks. * Typical usage: * *
 * LIBMTP_track_t *tracklist;
 *
 * tracklist = LIBMTP_Get_Tracklisting_With_Callback_For_Storage(device, storage_id, callback, data);
 * while (tracklist != NULL) {
 *   LIBMTP_track_t *tmp;
 *
 *   // Do something on each element in the list here...
 *   tmp = tracklist;
 *   tracklist = tracklist->next;
 *   LIBMTP_destroy_track_t(tmp);
 * }
 * 
* * If you want to group your track listing by storage (per storage unit) or * arrange tracks into folders, you must dereference the storage_id * and/or parent_id field of the returned LIBMTP_track_t * struct. To arrange by folders or files you typically have to create the proper * trees by calls to LIBMTP_Get_Storage() and/or * LIBMTP_Get_Folder_List() first. * * @param device a pointer to the device to get the track listing for. * @param storage_id ID of device storage (if null, no filter) * @param callback a function to be called during the tracklisting retrieveal * for displaying progress bars etc, or NULL if you don't want * any callbacks. * @param data a user-defined pointer that is passed along to * the progress function in order to * pass along some user defined data to the progress * updates. If not used, set this to NULL. * @return a list of tracks that can be followed using the next * field of the LIBMTP_track_t data structure. * Each of the metadata tags must be freed after use, and may * contain only partial metadata information, i.e. one or several * fields may be NULL or 0. * @see LIBMTP_Get_Trackmetadata() */ LIBMTP_track_t *LIBMTP_Get_Tracklisting_With_Callback_For_Storage(LIBMTP_mtpdevice_t *device, uint32_t const storage_id, LIBMTP_progressfunc_t const callback, void const * const data) { uint32_t i = 0; LIBMTP_track_t *retracks = NULL; LIBMTP_track_t *curtrack = NULL; PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; // Get all the handles if we haven't already done that if (params->nrofobjects == 0) { flush_handles(device); } for (i = 0; i < params->nrofobjects; i++) { LIBMTP_track_t *track; PTPObject *ob; LIBMTP_filetype_t mtptype; if (callback != NULL) callback(i, params->nrofobjects, data); ob = ¶ms->objects[i]; mtptype = map_ptp_type_to_libmtp_type(ob->oi.ObjectFormat); // Ignore stuff we don't know how to handle... // TODO: get this list as an intersection of the sets // supported by the device and the from the device and // all known track files? if (!LIBMTP_FILETYPE_IS_TRACK(mtptype) && // This row lets through undefined files for examination since they may be forgotten OGG files. (ob->oi.ObjectFormat != PTP_OFC_Undefined || (!FLAG_IRIVER_OGG_ALZHEIMER(ptp_usb) && !FLAG_OGG_IS_UNKNOWN(ptp_usb) && !FLAG_FLAC_IS_UNKNOWN(ptp_usb))) ) { //printf("Not a music track (name: %s format: %d), skipping...\n", oi->Filename, oi->ObjectFormat); continue; } // Ignore stuff that isn't into the storage device if ((storage_id != 0) && (ob->oi.StorageID != storage_id )) continue; // Allocate a new track type track = LIBMTP_new_track_t(); // This is some sort of unique ID so we can keep track of the track. track->item_id = ob->oid; track->parent_id = ob->oi.ParentObject; track->storage_id = ob->oi.StorageID; track->modificationdate = ob->oi.ModificationDate; track->filetype = mtptype; // Original file-specific properties track->filesize = ob->oi.ObjectCompressedSize; if (ob->oi.Filename != NULL) { track->filename = strdup(ob->oi.Filename); } get_track_metadata(device, ob->oi.ObjectFormat, track); /* * A special quirk for iriver devices that doesn't quite * remember that some files marked as "unknown" type are * actually OGG or FLAC files. We look at the filename extension * and see if it happens that this was atleast named "ogg" or "flac" * and fall back on this heuristic approach in that case, * for these bugged devices only. */ if (track->filetype == LIBMTP_FILETYPE_UNKNOWN && track->filename != NULL) { if ((FLAG_IRIVER_OGG_ALZHEIMER(ptp_usb) || FLAG_OGG_IS_UNKNOWN(ptp_usb)) && has_ogg_extension(track->filename)) track->filetype = LIBMTP_FILETYPE_OGG; else if (FLAG_FLAC_IS_UNKNOWN(ptp_usb) && has_flac_extension(track->filename)) track->filetype = LIBMTP_FILETYPE_FLAC; else { // This was not an OGG/FLAC file so discard it and continue LIBMTP_destroy_track_t(track); continue; } } // Add track to a list that will be returned afterwards. if (retracks == NULL) { retracks = track; curtrack = track; } else { curtrack->next = track; curtrack = track; } // Call listing callback // double progressPercent = (double)i*(double)100.0 / (double)params->handles.n; } // Handle counting loop return retracks; } /** * This function retrieves the metadata for a single track off * the device. * * Do not call this function repeatedly! The track handles are linearly * searched O(n) and the call may involve (slow) USB traffic, so use * LIBMTP_Get_Tracklisting() and cache the tracks, preferably * as an efficient data structure such as a hash list. * * @param device a pointer to the device to get the track metadata from. * @param trackid the object ID of the track that you want the metadata for. * @return a track metadata entry on success or NULL on failure. * @see LIBMTP_Get_Tracklisting() */ LIBMTP_track_t *LIBMTP_Get_Trackmetadata(LIBMTP_mtpdevice_t *device, uint32_t const trackid) { PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; PTPObject *ob; LIBMTP_track_t *track; LIBMTP_filetype_t mtptype; uint16_t ret; // Get all the handles if we haven't already done that if (params->nrofobjects == 0) flush_handles(device); ret = ptp_object_want (params, trackid, PTPOBJECT_OBJECTINFO_LOADED, &ob); if (ret != PTP_RC_OK) return NULL; mtptype = map_ptp_type_to_libmtp_type(ob->oi.ObjectFormat); // Ignore stuff we don't know how to handle... if (!LIBMTP_FILETYPE_IS_TRACK(mtptype) && /* * This row lets through undefined files for examination * since they may be forgotten OGG or FLAC files. */ (ob->oi.ObjectFormat != PTP_OFC_Undefined || (!FLAG_IRIVER_OGG_ALZHEIMER(ptp_usb) && !FLAG_OGG_IS_UNKNOWN(ptp_usb) && !FLAG_FLAC_IS_UNKNOWN(ptp_usb))) ) { //printf("Not a music track (name: %s format: %d), skipping...\n", oi->Filename, oi->ObjectFormat); return NULL; } // Allocate a new track type track = LIBMTP_new_track_t(); // This is some sort of unique ID so we can keep track of the track. track->item_id = ob->oid; track->parent_id = ob->oi.ParentObject; track->storage_id = ob->oi.StorageID; track->modificationdate = ob->oi.ModificationDate; track->filetype = mtptype; // Original file-specific properties track->filesize = ob->oi.ObjectCompressedSize; if (ob->oi.Filename != NULL) { track->filename = strdup(ob->oi.Filename); } /* * A special quirk for devices that doesn't quite * remember that some files marked as "unknown" type are * actually OGG or FLAC files. We look at the filename extension * and see if it happens that this was atleast named "ogg" * and fall back on this heuristic approach in that case, * for these bugged devices only. */ if (track->filetype == LIBMTP_FILETYPE_UNKNOWN && track->filename != NULL) { if ((FLAG_IRIVER_OGG_ALZHEIMER(ptp_usb) || FLAG_OGG_IS_UNKNOWN(ptp_usb)) && has_ogg_extension(track->filename)) track->filetype = LIBMTP_FILETYPE_OGG; else if (FLAG_FLAC_IS_UNKNOWN(ptp_usb) && has_flac_extension(track->filename)) track->filetype = LIBMTP_FILETYPE_FLAC; else { // This was not an OGG/FLAC file so discard it LIBMTP_destroy_track_t(track); return NULL; } } get_track_metadata(device, ob->oi.ObjectFormat, track); return track; } /** * This is a manual conversion from MTPDataGetFunc to PTPDataGetFunc * to isolate the internal type. */ static uint16_t get_func_wrapper(PTPParams* params, void* priv, unsigned long wantlen, unsigned char *data, unsigned long *gotlen) { MTPDataHandler *handler = (MTPDataHandler *)priv; uint16_t ret; uint32_t local_gotlen = 0; ret = handler->getfunc(params, handler->priv, wantlen, data, &local_gotlen); *gotlen = local_gotlen; switch (ret) { case LIBMTP_HANDLER_RETURN_OK: return PTP_RC_OK; case LIBMTP_HANDLER_RETURN_ERROR: return PTP_ERROR_IO; case LIBMTP_HANDLER_RETURN_CANCEL: return PTP_ERROR_CANCEL; default: return PTP_ERROR_IO; } } /** * This is a manual conversion from MTPDataPutFunc to PTPDataPutFunc * to isolate the internal type. */ static uint16_t put_func_wrapper(PTPParams* params, void* priv, unsigned long sendlen, unsigned char *data, unsigned long *putlen) { MTPDataHandler *handler = (MTPDataHandler *)priv; uint16_t ret; uint32_t local_putlen = 0; ret = handler->putfunc(params, handler->priv, sendlen, data, &local_putlen); *putlen = local_putlen; switch (ret) { case LIBMTP_HANDLER_RETURN_OK: return PTP_RC_OK; case LIBMTP_HANDLER_RETURN_ERROR: return PTP_ERROR_IO; case LIBMTP_HANDLER_RETURN_CANCEL: return PTP_ERROR_CANCEL; default: return PTP_ERROR_IO; } } /** * This gets a file off the device to a local file identified * by a filename. * @param device a pointer to the device to get the track from. * @param id the file ID of the file to retrieve. * @param path a filename to use for the retrieved file. * @param callback a progress indicator function or NULL to ignore. * @param data a user-defined pointer that is passed along to * the progress function in order to * pass along some user defined data to the progress * updates. If not used, set this to NULL. * @return 0 if the transfer was successful, any other value means * failure. * @see LIBMTP_Get_File_To_File_Descriptor() */ int LIBMTP_Get_File_To_File(LIBMTP_mtpdevice_t *device, uint32_t const id, char const * const path, LIBMTP_progressfunc_t const callback, void const * const data) { int fd = -1; int ret; // Sanity check if (path == NULL) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Get_File_To_File(): Bad arguments, path was NULL."); return -1; } // Open file #ifdef __WIN32__ #ifdef USE_WINDOWS_IO_H if ( (fd = _open(path, O_RDWR|O_CREAT|O_TRUNC|O_BINARY,_S_IREAD)) == -1 ) { #else if ( (fd = open(path, O_RDWR|O_CREAT|O_TRUNC|O_BINARY,S_IRWXU)) == -1 ) { #endif #else if ( (fd = open(path, O_RDWR|O_CREAT|O_TRUNC,S_IRWXU|S_IRGRP)) == -1) { #endif add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Get_File_To_File(): Could not create file."); return -1; } ret = LIBMTP_Get_File_To_File_Descriptor(device, id, fd, callback, data); // Close file close(fd); // Delete partial file. if (ret == -1) { unlink(path); } return ret; } /** * This gets a file off the device to a file identified * by a file descriptor. * * This function can potentially be used for streaming * files off the device for playback or broadcast for example, * by downloading the file into a stream sink e.g. a socket. * * @param device a pointer to the device to get the file from. * @param id the file ID of the file to retrieve. * @param fd a local file descriptor to write the file to. * @param callback a progress indicator function or NULL to ignore. * @param data a user-defined pointer that is passed along to * the progress function in order to * pass along some user defined data to the progress * updates. If not used, set this to NULL. * @return 0 if the transfer was successful, any other value means * failure. * @see LIBMTP_Get_File_To_File() */ int LIBMTP_Get_File_To_File_Descriptor(LIBMTP_mtpdevice_t *device, uint32_t const id, int const fd, LIBMTP_progressfunc_t const callback, void const * const data) { uint16_t ret; PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; PTPObject *ob; ret = ptp_object_want (params, id, PTPOBJECT_OBJECTINFO_LOADED, &ob); if (ret != PTP_RC_OK) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Get_File_To_File_Descriptor(): Could not get object info."); return -1; } if (ob->oi.ObjectFormat == PTP_OFC_Association) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Get_File_To_File_Descriptor(): Bad object format."); return -1; } // Callbacks ptp_usb->callback_active = 1; ptp_usb->current_transfer_total = ob->oi.ObjectCompressedSize+ PTP_USB_BULK_HDR_LEN+sizeof(uint32_t); // Request length, one parameter ptp_usb->current_transfer_complete = 0; ptp_usb->current_transfer_callback = callback; ptp_usb->current_transfer_callback_data = data; ret = ptp_getobject_tofd(params, id, fd); ptp_usb->callback_active = 0; ptp_usb->current_transfer_callback = NULL; ptp_usb->current_transfer_callback_data = NULL; if (ret == PTP_ERROR_CANCEL) { add_error_to_errorstack(device, LIBMTP_ERROR_CANCELLED, "LIBMTP_Get_File_From_File_Descriptor(): Cancelled transfer."); return -1; } if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Get_File_To_File_Descriptor(): Could not get file from device."); return -1; } return 0; } /** * This gets a file off the device and calls put_func * with chunks of data * * @param device a pointer to the device to get the file from. * @param id the file ID of the file to retrieve. * @param put_func the function to call when we have data. * @param priv the user-defined pointer that is passed to * put_func. * @param callback a progress indicator function or NULL to ignore. * @param data a user-defined pointer that is passed along to * the progress function in order to * pass along some user defined data to the progress * updates. If not used, set this to NULL. * @return 0 if the transfer was successful, any other value means * failure. */ int LIBMTP_Get_File_To_Handler(LIBMTP_mtpdevice_t *device, uint32_t const id, MTPDataPutFunc put_func, void * priv, LIBMTP_progressfunc_t const callback, void const * const data) { PTPObject *ob; uint16_t ret; PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; ret = ptp_object_want (params, id, PTPOBJECT_OBJECTINFO_LOADED, &ob); if (ret != PTP_RC_OK) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Get_File_To_File_Descriptor(): Could not get object info."); return -1; } if (ob->oi.ObjectFormat == PTP_OFC_Association) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Get_File_To_File_Descriptor(): Bad object format."); return -1; } // Callbacks ptp_usb->callback_active = 1; ptp_usb->current_transfer_total = ob->oi.ObjectCompressedSize+ PTP_USB_BULK_HDR_LEN+sizeof(uint32_t); // Request length, one parameter ptp_usb->current_transfer_complete = 0; ptp_usb->current_transfer_callback = callback; ptp_usb->current_transfer_callback_data = data; MTPDataHandler mtp_handler; mtp_handler.getfunc = NULL; mtp_handler.putfunc = put_func; mtp_handler.priv = priv; PTPDataHandler handler; handler.getfunc = NULL; handler.putfunc = put_func_wrapper; handler.priv = &mtp_handler; ret = ptp_getobject_to_handler(params, id, &handler); ptp_usb->callback_active = 0; ptp_usb->current_transfer_callback = NULL; ptp_usb->current_transfer_callback_data = NULL; if (ret == PTP_ERROR_CANCEL) { add_error_to_errorstack(device, LIBMTP_ERROR_CANCELLED, "LIBMTP_Get_File_From_File_Descriptor(): Cancelled transfer."); return -1; } if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Get_File_To_File_Descriptor(): Could not get file from device."); return -1; } return 0; } /** * This gets a track off the device to a file identified * by a filename. This is actually just a wrapper for the * \c LIBMTP_Get_Track_To_File() function. * @param device a pointer to the device to get the track from. * @param id the track ID of the track to retrieve. * @param path a filename to use for the retrieved track. * @param callback a progress indicator function or NULL to ignore. * @param data a user-defined pointer that is passed along to * the progress function in order to * pass along some user defined data to the progress * updates. If not used, set this to NULL. * @return 0 if the transfer was successful, any other value means * failure. * @see LIBMTP_Get_Track_To_File_Descriptor() */ int LIBMTP_Get_Track_To_File(LIBMTP_mtpdevice_t *device, uint32_t const id, char const * const path, LIBMTP_progressfunc_t const callback, void const * const data) { // This is just a wrapper return LIBMTP_Get_File_To_File(device, id, path, callback, data); } /** * This gets a track off the device to a file identified * by a file descriptor. This is actually just a wrapper for * the \c LIBMTP_Get_File_To_File_Descriptor() function. * @param device a pointer to the device to get the track from. * @param id the track ID of the track to retrieve. * @param fd a file descriptor to write the track to. * @param callback a progress indicator function or NULL to ignore. * @param data a user-defined pointer that is passed along to * the progress function in order to * pass along some user defined data to the progress * updates. If not used, set this to NULL. * @return 0 if the transfer was successful, any other value means * failure. * @see LIBMTP_Get_Track_To_File() */ int LIBMTP_Get_Track_To_File_Descriptor(LIBMTP_mtpdevice_t *device, uint32_t const id, int const fd, LIBMTP_progressfunc_t const callback, void const * const data) { // This is just a wrapper return LIBMTP_Get_File_To_File_Descriptor(device, id, fd, callback, data); } /** * This gets a track off the device to a handler function. * This is actually just a wrapper for * the \c LIBMTP_Get_File_To_Handler() function. * @param device a pointer to the device to get the track from. * @param id the track ID of the track to retrieve. * @param put_func the function to call when we have data. * @param priv the user-defined pointer that is passed to * put_func. * @param callback a progress indicator function or NULL to ignore. * @param data a user-defined pointer that is passed along to * the progress function in order to * pass along some user defined data to the progress * updates. If not used, set this to NULL. * @return 0 if the transfer was successful, any other value means * failure. */ int LIBMTP_Get_Track_To_Handler(LIBMTP_mtpdevice_t *device, uint32_t const id, MTPDataPutFunc put_func, void * priv, LIBMTP_progressfunc_t const callback, void const * const data) { // This is just a wrapper return LIBMTP_Get_File_To_Handler(device, id, put_func, priv, callback, data); } /** * This function sends a track from a local file to an * MTP device. A filename and a set of metadata must be * given as input. * @param device a pointer to the device to send the track to. * @param path the filename of a local file which will be sent. * @param metadata a track metadata set to be written along with the file. * After this call the field metadata->item_id * will contain the new track ID. Other fields such * as the metadata->filename, metadata->parent_id * or metadata->storage_id may also change during this * operation due to device restrictions, so do not rely on the * contents of this struct to be preserved in any way. *
    *
  • metadata->parent_id should be set to the parent * (e.g. folder) to store this track in. Since some * devices are a bit picky about where files * are placed, a default folder will be chosen if libmtp * has detected one for the current filetype and this * parameter is set to 0. If this is 0 and no default folder * can be found, the file will be stored in the root folder. *
  • metadata->storage_id should be set to the * desired storage (e.g. memory card or whatever your device * presents) to store this track in. Setting this to 0 will store * the track on the primary storage. *
* @param callback a progress indicator function or NULL to ignore. * @param data a user-defined pointer that is passed along to * the progress function in order to * pass along some user defined data to the progress * updates. If not used, set this to NULL. * @return 0 if the transfer was successful, any other value means * failure. * @see LIBMTP_Send_Track_From_File_Descriptor() * @see LIBMTP_Send_File_From_File() * @see LIBMTP_Delete_Object() */ int LIBMTP_Send_Track_From_File(LIBMTP_mtpdevice_t *device, char const * const path, LIBMTP_track_t * const metadata, LIBMTP_progressfunc_t const callback, void const * const data) { int fd; int ret; // Sanity check if (path == NULL) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Send_Track_From_File(): Bad arguments, path was NULL."); return -1; } // Open file #ifdef __WIN32__ #ifdef USE_WINDOWS_IO_H if ( (fd = _open(path, O_RDONLY|O_BINARY)) == -1 ) { #else if ( (fd = open(path, O_RDONLY|O_BINARY)) == -1 ) { #endif #else if ( (fd = open(path, O_RDONLY)) == -1) { #endif LIBMTP_ERROR("LIBMTP_Send_Track_From_File(): Could not open source file \"%s\"\n", path); return -1; } ret = LIBMTP_Send_Track_From_File_Descriptor(device, fd, metadata, callback, data); // Close file. #ifdef USE_WINDOWS_IO_H _close(fd); #else close(fd); #endif return ret; } /** * This helper function checks if a filename already exists on the device * @param PTPParams* * @param string representing the filename * @return 0 if the filename doesn't exist, -1 if it does */ static int check_filename_exists(PTPParams* params, char const * const filename) { int i; for (i = 0; i < params->nrofobjects; i++) { char *fname = params->objects[i].oi.Filename; if ((fname != NULL) && (strcmp(filename, fname) == 0)) { return -1; } } return 0; } /** * This helper function returns a unique filename, with a random string before the extension * @param string representing the original filename * @return a string representing the unique filename */ static char *generate_unique_filename(PTPParams* params, char const * const filename) { int suffix; char * extension_position; if (check_filename_exists(params, filename)) { extension_position = strrchr(filename,'.'); char basename[extension_position - filename + 1]; strncpy(basename, filename, extension_position - filename); basename[extension_position - filename] = '\0'; suffix = 1; char newname[ strlen(basename) + 6 + strlen(extension_position)]; sprintf(newname, "%s_%d%s", basename, suffix, extension_position); while ((check_filename_exists(params, newname)) && (suffix < 1000000)) { suffix++; sprintf(newname, "%s_%d%s", basename, suffix, extension_position); } return strdup(newname); } else { return strdup(filename); } } /** * This function sends a track from a file descriptor to an * MTP device. A filename and a set of metadata must be * given as input. * @param device a pointer to the device to send the track to. * @param fd the filedescriptor for a local file which will be sent. * @param metadata a track metadata set to be written along with the file. * After this call the field metadata->item_id * will contain the new track ID. Other fields such * as the metadata->filename, metadata->parent_id * or metadata->storage_id may also change during this * operation due to device restrictions, so do not rely on the * contents of this struct to be preserved in any way. *
    *
  • metadata->parent_id should be set to the parent * (e.g. folder) to store this track in. Since some * devices are a bit picky about where files * are placed, a default folder will be chosen if libmtp * has detected one for the current filetype and this * parameter is set to 0. If this is 0 and no default folder * can be found, the file will be stored in the root folder. *
  • metadata->storage_id should be set to the * desired storage (e.g. memory card or whatever your device * presents) to store this track in. Setting this to 0 will store * the track on the primary storage. *
* @param callback a progress indicator function or NULL to ignore. * @param data a user-defined pointer that is passed along to * the progress function in order to * pass along some user defined data to the progress * updates. If not used, set this to NULL. * @return 0 if the transfer was successful, any other value means * failure. * @see LIBMTP_Send_Track_From_File() * @see LIBMTP_Delete_Object() */ int LIBMTP_Send_Track_From_File_Descriptor(LIBMTP_mtpdevice_t *device, int const fd, LIBMTP_track_t * const metadata, LIBMTP_progressfunc_t const callback, void const * const data) { int subcall_ret; LIBMTP_file_t filedata; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; PTPParams *params = (PTPParams *) device->params; // Sanity check, is this really a track? if (!LIBMTP_FILETYPE_IS_TRACK(metadata->filetype)) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Send_Track_From_File_Descriptor(): " "I don't think this is actually a track, strange filetype..."); } // Wrap around the file transfer function filedata.item_id = metadata->item_id; filedata.parent_id = metadata->parent_id; filedata.storage_id = metadata->storage_id; if FLAG_UNIQUE_FILENAMES(ptp_usb) { filedata.filename = generate_unique_filename(params, metadata->filename); } else { filedata.filename = metadata->filename; } filedata.filesize = metadata->filesize; filedata.filetype = metadata->filetype; filedata.next = NULL; subcall_ret = LIBMTP_Send_File_From_File_Descriptor(device, fd, &filedata, callback, data); if (subcall_ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Send_Track_From_File_Descriptor(): " "subcall to LIBMTP_Send_File_From_File_Descriptor failed."); // We used to delete the file here, but don't... It might be OK after all. // (void) LIBMTP_Delete_Object(device, metadata->item_id); return -1; } // Pick up new item (and parent, storage) ID metadata->item_id = filedata.item_id; metadata->parent_id = filedata.parent_id; metadata->storage_id = filedata.storage_id; // Set track metadata for the new fine track subcall_ret = LIBMTP_Update_Track_Metadata(device, metadata); if (subcall_ret != 0) { // Subcall will add error to errorstack // We used to delete the file here, but don't... It might be OK after all. // (void) LIBMTP_Delete_Object(device, metadata->item_id); return -1; } // note we don't need to update the cache here because LIBMTP_Send_File_From_File_Descriptor // has added the object handle and LIBMTP_Update_Track_Metadata has added the metadata. return 0; } /** * This function sends a track from a handler function to an * MTP device. A filename and a set of metadata must be * given as input. * @param device a pointer to the device to send the track to. * @param get_func the function to call when we have data. * @param priv the user-defined pointer that is passed to * get_func. * @param metadata a track metadata set to be written along with the file. * After this call the field metadata->item_id * will contain the new track ID. Other fields such * as the metadata->filename, metadata->parent_id * or metadata->storage_id may also change during this * operation due to device restrictions, so do not rely on the * contents of this struct to be preserved in any way. *
    *
  • metadata->parent_id should be set to the parent * (e.g. folder) to store this track in. Since some * devices are a bit picky about where files * are placed, a default folder will be chosen if libmtp * has detected one for the current filetype and this * parameter is set to 0. If this is 0 and no default folder * can be found, the file will be stored in the root folder. *
  • metadata->storage_id should be set to the * desired storage (e.g. memory card or whatever your device * presents) to store this track in. Setting this to 0 will store * the track on the primary storage. *
* @param callback a progress indicator function or NULL to ignore. * @param data a user-defined pointer that is passed along to * the progress function in order to * pass along some user defined data to the progress * updates. If not used, set this to NULL. * @return 0 if the transfer was successful, any other value means * failure. * @see LIBMTP_Send_Track_From_File() * @see LIBMTP_Delete_Object() */ int LIBMTP_Send_Track_From_Handler(LIBMTP_mtpdevice_t *device, MTPDataGetFunc get_func, void * priv, LIBMTP_track_t * const metadata, LIBMTP_progressfunc_t const callback, void const * const data) { int subcall_ret; LIBMTP_file_t filedata; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; PTPParams *params = (PTPParams *) device->params; // Sanity check, is this really a track? if (!LIBMTP_FILETYPE_IS_TRACK(metadata->filetype)) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Send_Track_From_Handler(): " "I don't think this is actually a track, strange filetype..."); } // Wrap around the file transfer function filedata.item_id = metadata->item_id; filedata.parent_id = metadata->parent_id; filedata.storage_id = metadata->storage_id; if FLAG_UNIQUE_FILENAMES(ptp_usb) { filedata.filename = generate_unique_filename(params, metadata->filename); } else { filedata.filename = metadata->filename; } filedata.filesize = metadata->filesize; filedata.filetype = metadata->filetype; filedata.next = NULL; subcall_ret = LIBMTP_Send_File_From_Handler(device, get_func, priv, &filedata, callback, data); if (subcall_ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Send_Track_From_Handler(): " "subcall to LIBMTP_Send_File_From_Handler failed."); // We used to delete the file here, but don't... It might be OK after all. // (void) LIBMTP_Delete_Object(device, metadata->item_id); return -1; } // Pick up new item (and parent, storage) ID metadata->item_id = filedata.item_id; metadata->parent_id = filedata.parent_id; metadata->storage_id = filedata.storage_id; // Set track metadata for the new fine track subcall_ret = LIBMTP_Update_Track_Metadata(device, metadata); if (subcall_ret != 0) { // Subcall will add error to errorstack // We used to delete the file here, but don't... It might be OK after all. // (void) LIBMTP_Delete_Object(device, metadata->item_id); return -1; } // note we don't need to update the cache here because LIBMTP_Send_File_From_File_Descriptor // has added the object handle and LIBMTP_Update_Track_Metadata has added the metadata. return 0; } /** * This function sends a local file to an MTP device. * A filename and a set of metadata must be * given as input. * @param device a pointer to the device to send the track to. * @param path the filename of a local file which will be sent. * @param filedata a file metadata set to be written along with the file. * After this call the field filedata->item_id * will contain the new file ID. Other fields such * as the filedata->filename, filedata->parent_id * or filedata->storage_id may also change during this * operation due to device restrictions, so do not rely on the * contents of this struct to be preserved in any way. *
    *
  • filedata->parent_id should be set to the parent * (e.g. folder) to store this file in. If this is 0, * the file will be stored in the root folder. *
  • filedata->storage_id should be set to the * desired storage (e.g. memory card or whatever your device * presents) to store this file in. Setting this to 0 will store * the file on the primary storage. *
* @param callback a progress indicator function or NULL to ignore. * @param data a user-defined pointer that is passed along to * the progress function in order to * pass along some user defined data to the progress * updates. If not used, set this to NULL. * @return 0 if the transfer was successful, any other value means * failure. * @see LIBMTP_Send_File_From_File_Descriptor() * @see LIBMTP_Delete_Object() */ int LIBMTP_Send_File_From_File(LIBMTP_mtpdevice_t *device, char const * const path, LIBMTP_file_t * const filedata, LIBMTP_progressfunc_t const callback, void const * const data) { int fd; int ret; // Sanity check if (path == NULL) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Send_File_From_File(): Bad arguments, path was NULL."); return -1; } // Open file #ifdef __WIN32__ #ifdef USE_WINDOWS_IO_H if ( (fd = _open(path, O_RDONLY|O_BINARY)) == -1 ) { #else if ( (fd = open(path, O_RDONLY|O_BINARY)) == -1 ) { #endif #else if ( (fd = open(path, O_RDONLY)) == -1) { #endif add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Send_File_From_File(): Could not open source file."); return -1; } ret = LIBMTP_Send_File_From_File_Descriptor(device, fd, filedata, callback, data); // Close file. #ifdef USE_WINDOWS_IO_H _close(fd); #else close(fd); #endif return ret; } /** * This function sends a generic file from a file descriptor to an * MTP device. A filename and a set of metadata must be * given as input. * * This can potentially be used for sending in a stream of unknown * length. Send music files with * LIBMTP_Send_Track_From_File_Descriptor() * * @param device a pointer to the device to send the file to. * @param fd the filedescriptor for a local file which will be sent. * @param filedata a file metadata set to be written along with the file. * After this call the field filedata->item_id * will contain the new file ID. Other fields such * as the filedata->filename, filedata->parent_id * or filedata->storage_id may also change during this * operation due to device restrictions, so do not rely on the * contents of this struct to be preserved in any way. *
    *
  • filedata->parent_id should be set to the parent * (e.g. folder) to store this file in. If this is 0, * the file will be stored in the root folder. *
  • filedata->storage_id should be set to the * desired storage (e.g. memory card or whatever your device * presents) to store this file in. Setting this to 0 will store * the file on the primary storage. *
* @param callback a progress indicator function or NULL to ignore. * @param data a user-defined pointer that is passed along to * the progress function in order to * pass along some user defined data to the progress * updates. If not used, set this to NULL. * @return 0 if the transfer was successful, any other value means * failure. * @see LIBMTP_Send_File_From_File() * @see LIBMTP_Send_Track_From_File_Descriptor() * @see LIBMTP_Delete_Object() */ int LIBMTP_Send_File_From_File_Descriptor(LIBMTP_mtpdevice_t *device, int const fd, LIBMTP_file_t * const filedata, LIBMTP_progressfunc_t const callback, void const * const data) { uint16_t ret; PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; LIBMTP_file_t *newfilemeta; int oldtimeout; int timeout; if (send_file_object_info(device, filedata)) { // no need to output an error since send_file_object_info will already have done so return -1; } // Callbacks ptp_usb->callback_active = 1; // The callback will deactivate itself after this amount of data has been sent // One BULK header for the request, one for the data phase. No parameters to the request. ptp_usb->current_transfer_total = filedata->filesize+PTP_USB_BULK_HDR_LEN*2; ptp_usb->current_transfer_complete = 0; ptp_usb->current_transfer_callback = callback; ptp_usb->current_transfer_callback_data = data; /* * We might need to increase the timeout here, files can be pretty * large. Take the default timeout and add the calculated time for * this transfer */ get_usb_device_timeout(ptp_usb, &oldtimeout); timeout = oldtimeout + (ptp_usb->current_transfer_total / guess_usb_speed(ptp_usb)) * 1000; set_usb_device_timeout(ptp_usb, timeout); ret = ptp_sendobject_fromfd(params, fd, filedata->filesize); ptp_usb->callback_active = 0; ptp_usb->current_transfer_callback = NULL; ptp_usb->current_transfer_callback_data = NULL; set_usb_device_timeout(ptp_usb, oldtimeout); if (ret == PTP_ERROR_CANCEL) { add_error_to_errorstack(device, LIBMTP_ERROR_CANCELLED, "LIBMTP_Send_File_From_File_Descriptor(): Cancelled transfer."); return -1; } if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Send_File_From_File_Descriptor(): " "Could not send object."); return -1; } add_object_to_cache(device, filedata->item_id); /* * Get the device-assigned parent_id from the cache. * The operation that adds it to the cache will * look it up from the device, so we get the new * parent_id from the cache. */ newfilemeta = LIBMTP_Get_Filemetadata(device, filedata->item_id); if (newfilemeta != NULL) { filedata->parent_id = newfilemeta->parent_id; filedata->storage_id = newfilemeta->storage_id; LIBMTP_destroy_file_t(newfilemeta); } else { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Send_File_From_File_Descriptor(): " "Could not retrieve updated metadata."); return -1; } return 0; } /** * This function sends a generic file from a handler function to an * MTP device. A filename and a set of metadata must be * given as input. * * This can potentially be used for sending in a stream of unknown * length. Send music files with * LIBMTP_Send_Track_From_Handler() * * @param device a pointer to the device to send the file to. * @param get_func the function to call to get data to write * @param priv a user-defined pointer that is passed along to * get_func. If not used, this is set to NULL. * @param filedata a file metadata set to be written along with the file. * After this call the field filedata->item_id * will contain the new file ID. Other fields such * as the filedata->filename, filedata->parent_id * or filedata->storage_id may also change during this * operation due to device restrictions, so do not rely on the * contents of this struct to be preserved in any way. *
    *
  • filedata->parent_id should be set to the parent * (e.g. folder) to store this file in. If this is 0, * the file will be stored in the root folder. *
  • filedata->storage_id should be set to the * desired storage (e.g. memory card or whatever your device * presents) to store this file in. Setting this to 0 will store * the file on the primary storage. *
* @param callback a progress indicator function or NULL to ignore. * @param data a user-defined pointer that is passed along to * the progress function in order to * pass along some user defined data to the progress * updates. If not used, set this to NULL. * @return 0 if the transfer was successful, any other value means * failure. * @see LIBMTP_Send_File_From_File() * @see LIBMTP_Send_Track_From_File_Descriptor() * @see LIBMTP_Delete_Object() */ int LIBMTP_Send_File_From_Handler(LIBMTP_mtpdevice_t *device, MTPDataGetFunc get_func, void * priv, LIBMTP_file_t * const filedata, LIBMTP_progressfunc_t const callback, void const * const data) { uint16_t ret; PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; LIBMTP_file_t *newfilemeta; if (send_file_object_info(device, filedata)) { // no need to output an error since send_file_object_info will already have done so return -1; } // Callbacks ptp_usb->callback_active = 1; // The callback will deactivate itself after this amount of data has been sent // One BULK header for the request, one for the data phase. No parameters to the request. ptp_usb->current_transfer_total = filedata->filesize+PTP_USB_BULK_HDR_LEN*2; ptp_usb->current_transfer_complete = 0; ptp_usb->current_transfer_callback = callback; ptp_usb->current_transfer_callback_data = data; MTPDataHandler mtp_handler; mtp_handler.getfunc = get_func; mtp_handler.putfunc = NULL; mtp_handler.priv = priv; PTPDataHandler handler; handler.getfunc = get_func_wrapper; handler.putfunc = NULL; handler.priv = &mtp_handler; ret = ptp_sendobject_from_handler(params, &handler, filedata->filesize); ptp_usb->callback_active = 0; ptp_usb->current_transfer_callback = NULL; ptp_usb->current_transfer_callback_data = NULL; if (ret == PTP_ERROR_CANCEL) { add_error_to_errorstack(device, LIBMTP_ERROR_CANCELLED, "LIBMTP_Send_File_From_Handler(): Cancelled transfer."); return -1; } if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Send_File_From_Handler(): " "Could not send object."); return -1; } add_object_to_cache(device, filedata->item_id); /* * Get the device-assined parent_id from the cache. * The operation that adds it to the cache will * look it up from the device, so we get the new * parent_id from the cache. */ newfilemeta = LIBMTP_Get_Filemetadata(device, filedata->item_id); if (newfilemeta != NULL) { filedata->parent_id = newfilemeta->parent_id; filedata->storage_id = newfilemeta->storage_id; LIBMTP_destroy_file_t(newfilemeta); } else { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Send_File_From_Handler(): " "Could not retrieve updated metadata."); return -1; } return 0; } /** * This function sends the file object info, ready for sendobject * @param device a pointer to the device to send the file to. * @param filedata a file metadata set to be written along with the file. * @return 0 if the transfer was successful, any other value means * failure. */ static int send_file_object_info(LIBMTP_mtpdevice_t *device, LIBMTP_file_t *filedata) { PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; uint32_t store; int use_primary_storage = 1; uint16_t of = map_libmtp_type_to_ptp_type(filedata->filetype); LIBMTP_devicestorage_t *storage; uint32_t localph = filedata->parent_id; uint16_t ret; int i; #if 0 // Sanity check: no zerolength files on some devices? // If the zerolength files cause problems on some devices, // then add a bug flag for this. if (filedata->filesize == 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "send_file_object_info(): " "File of zero size."); return -1; } #endif if (filedata->storage_id != 0) { store = filedata->storage_id; } else { store = get_writeable_storageid(device, filedata->filesize); } // Detect if something non-primary is in use. storage = device->storage; if (storage != NULL && store != storage->id) { use_primary_storage = 0; } /* * If no destination folder was given, look up a default * folder if possible. Perhaps there is some way of retrieveing * the default folder for different forms of content, what * do I know, we use a fixed list in lack of any better method. * Some devices obviously need to have their files in certain * folders in order to find/display them at all (hello Creative), * so we have to have a method for this. We only do this if the * primary storage is in use. */ if (localph == 0 && use_primary_storage) { if (LIBMTP_FILETYPE_IS_AUDIO(filedata->filetype)) { localph = device->default_music_folder; } else if (LIBMTP_FILETYPE_IS_VIDEO(filedata->filetype)) { localph = device->default_video_folder; } else if (of == PTP_OFC_EXIF_JPEG || of == PTP_OFC_JP2 || of == PTP_OFC_JPX || of == PTP_OFC_JFIF || of == PTP_OFC_TIFF || of == PTP_OFC_TIFF_IT || of == PTP_OFC_BMP || of == PTP_OFC_GIF || of == PTP_OFC_PICT || of == PTP_OFC_PNG || of == PTP_OFC_MTP_WindowsImageFormat) { localph = device->default_picture_folder; } else if (of == PTP_OFC_MTP_vCalendar1 || of == PTP_OFC_MTP_vCalendar2 || of == PTP_OFC_MTP_UndefinedContact || of == PTP_OFC_MTP_vCard2 || of == PTP_OFC_MTP_vCard3 || of == PTP_OFC_MTP_UndefinedCalendarItem) { localph = device->default_organizer_folder; } else if (of == PTP_OFC_Text) { localph = device->default_text_folder; } } // Here we wire the type to unknown on bugged, but // Ogg or FLAC-supportive devices. if (FLAG_OGG_IS_UNKNOWN(ptp_usb) && of == PTP_OFC_MTP_OGG) { of = PTP_OFC_Undefined; } if (FLAG_FLAC_IS_UNKNOWN(ptp_usb) && of == PTP_OFC_MTP_FLAC) { of = PTP_OFC_Undefined; } if (ptp_operation_issupported(params, PTP_OC_MTP_SendObjectPropList) && !FLAG_BROKEN_SEND_OBJECT_PROPLIST(ptp_usb)) { /* * MTP enhanched does it this way (from a sniff): * -> PTP_OC_MTP_SendObjectPropList (0x9808): * 20 00 00 00 01 00 08 98 1B 00 00 00 01 00 01 00 * FF FF FF FF 00 30 00 00 00 00 00 00 12 5E 00 00 * Length: 0x00000020 * Type: 0x0001 PTP_USB_CONTAINER_COMMAND * Code: 0x9808 * Transaction ID: 0x0000001B * Param1: 0x00010001 <- store * Param2: 0xffffffff <- parent handle (-1 ?) * Param3: 0x00003000 <- file type PTP_OFC_Undefined - we don't know about PDF files * Param4: 0x00000000 <- file length MSB (-0x0c header len) * Param5: 0x00005e12 <- file length LSB (-0x0c header len) * * -> PTP_OC_MTP_SendObjectPropList (0x9808): * 46 00 00 00 02 00 08 98 1B 00 00 00 03 00 00 00 * 00 00 00 00 07 DC FF FF 0D 4B 00 53 00 30 00 36 - dc07 = file name * 00 30 00 33 00 30 00 36 00 2E 00 70 00 64 00 66 * 00 00 00 00 00 00 00 03 DC 04 00 00 00 00 00 00 - dc03 = protection status * 00 4F DC 02 00 01 - dc4f = non consumable * Length: 0x00000046 * Type: 0x0002 PTP_USB_CONTAINER_DATA * Code: 0x9808 * Transaction ID: 0x0000001B * Metadata.... * 0x00000003 <- Number of metadata items * 0x00000000 <- Object handle, set to 0x00000000 since it is unknown! * 0xdc07 <- metadata type: file name * 0xffff <- metadata type: string * 0x0d <- number of (uint16_t) characters * 4b 53 30 36 30 33 30 36 2e 50 64 66 00 "KS060306.pdf", null terminated * 0x00000000 <- Object handle, set to 0x00000000 since it is unknown! * 0xdc03 <- metadata type: protection status * 0x0004 <- metadata type: uint16_t * 0x0000 <- not protected * 0x00000000 <- Object handle, set to 0x00000000 since it is unknown! * 0xdc4f <- non consumable * 0x0002 <- metadata type: uint8_t * 0x01 <- non-consumable (this device cannot display PDF) * * <- Read 0x18 bytes back * 18 00 00 00 03 00 01 20 1B 00 00 00 01 00 01 00 * 00 00 00 00 01 40 00 00 * Length: 0x000000018 * Type: 0x0003 PTP_USB_CONTAINER_RESPONSE * Code: 0x2001 PTP_OK * Transaction ID: 0x0000001B * Param1: 0x00010001 <- store * Param2: 0x00000000 <- parent handle * Param3: 0x00004001 <- new file/object ID * * -> PTP_OC_SendObject (0x100d) * 0C 00 00 00 01 00 0D 10 1C 00 00 00 * -> ... all the bytes ... * <- Read 0x0c bytes back * 0C 00 00 00 03 00 01 20 1C 00 00 00 * ... Then update metadata one-by one, actually (instead of sending it first!) ... */ MTPProperties *props = NULL; int nrofprops = 0; MTPProperties *prop = NULL; uint16_t *properties = NULL; uint32_t propcnt = 0; // default parent handle if (localph == 0) localph = 0xFFFFFFFFU; // Set to -1 // Must be 0x00000000U for new objects filedata->item_id = 0x00000000U; ret = ptp_mtp_getobjectpropssupported(params, of, &propcnt, &properties); for (i=0;iObjectHandle = filedata->item_id; prop->property = PTP_OPC_ObjectFileName; prop->datatype = PTP_DTC_STR; if (filedata->filename != NULL) { prop->propval.str = strdup(filedata->filename); if (FLAG_ONLY_7BIT_FILENAMES(ptp_usb)) { strip_7bit_from_utf8(prop->propval.str); } } break; case PTP_OPC_ProtectionStatus: prop = ptp_get_new_object_prop_entry(&props,&nrofprops); prop->ObjectHandle = filedata->item_id; prop->property = PTP_OPC_ProtectionStatus; prop->datatype = PTP_DTC_UINT16; prop->propval.u16 = 0x0000U; /* Not protected */ break; case PTP_OPC_NonConsumable: prop = ptp_get_new_object_prop_entry(&props,&nrofprops); prop->ObjectHandle = filedata->item_id; prop->property = PTP_OPC_NonConsumable; prop->datatype = PTP_DTC_UINT8; prop->propval.u8 = 0x00; /* It is supported, then it is consumable */ break; case PTP_OPC_Name: prop = ptp_get_new_object_prop_entry(&props,&nrofprops); prop->ObjectHandle = filedata->item_id; prop->property = PTP_OPC_Name; prop->datatype = PTP_DTC_STR; if (filedata->filename != NULL) prop->propval.str = strdup(filedata->filename); break; case PTP_OPC_DateModified: // Tag with current time if that is supported if (!FLAG_CANNOT_HANDLE_DATEMODIFIED(ptp_usb)) { prop = ptp_get_new_object_prop_entry(&props,&nrofprops); prop->ObjectHandle = filedata->item_id; prop->property = PTP_OPC_DateModified; prop->datatype = PTP_DTC_STR; prop->propval.str = get_iso8601_stamp(); filedata->modificationdate = time(NULL); } break; } } ptp_free_objectpropdesc(&opd); } free(properties); ret = ptp_mtp_sendobjectproplist(params, &store, &localph, &filedata->item_id, of, filedata->filesize, props, nrofprops); /* Free property list */ ptp_destroy_object_prop_list(props, nrofprops); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "send_file_object_info():" "Could not send object property list."); if (ret == PTP_RC_AccessDenied) { add_ptp_error_to_errorstack(device, ret, "ACCESS DENIED."); } return -1; } } else if (ptp_operation_issupported(params,PTP_OC_SendObjectInfo)) { PTPObjectInfo new_file; memset(&new_file, 0, sizeof(PTPObjectInfo)); new_file.Filename = filedata->filename; if (FLAG_ONLY_7BIT_FILENAMES(ptp_usb)) { strip_7bit_from_utf8(new_file.Filename); } if (filedata->filesize > 0xFFFFFFFFL) { // This is a kludge in the MTP standard for large files. new_file.ObjectCompressedSize = (uint32_t) 0xFFFFFFFF; } else { new_file.ObjectCompressedSize = (uint32_t) filedata->filesize; } new_file.ObjectFormat = of; new_file.StorageID = store; new_file.ParentObject = localph; new_file.ModificationDate = time(NULL); // Create the object ret = ptp_sendobjectinfo(params, &store, &localph, &filedata->item_id, &new_file); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "send_file_object_info(): " "Could not send object info."); if (ret == PTP_RC_AccessDenied) { add_ptp_error_to_errorstack(device, ret, "ACCESS DENIED."); } return -1; } // NOTE: the char* pointers inside new_file are not copies so don't // try to destroy this objectinfo! } // Now there IS an object with this parent handle. filedata->parent_id = localph; return 0; } /** * This function updates the MTP track object metadata on a * single file identified by an object ID. * @param device a pointer to the device to update the track * metadata on. * @param metadata a track metadata set to be written to the file. * notice that the track_id field of the * metadata structure must be correct so that the * function can update the right file. If some properties * of this metadata are set to NULL (strings) or 0 * (numerical values) they will be discarded and the * track will not be tagged with these blank values. * @return 0 on success, any other value means failure. If some * or all of the properties fail to update we will still * return success. On some devices (notably iRiver T30) * properties that exist cannot be updated. */ int LIBMTP_Update_Track_Metadata(LIBMTP_mtpdevice_t *device, LIBMTP_track_t const * const metadata) { uint16_t ret; PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; uint32_t i; uint16_t *properties = NULL; uint32_t propcnt = 0; // First see which properties can be set on this file format and apply accordingly // i.e only try to update this metadata for object tags that exist on the current player. ret = ptp_mtp_getobjectpropssupported(params, map_libmtp_type_to_ptp_type(metadata->filetype), &propcnt, &properties); if (ret != PTP_RC_OK) { // Just bail out for now, nothing is ever set. add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not retrieve supported object properties."); return -1; } if (ptp_operation_issupported(params, PTP_OC_MTP_SetObjPropList) && !FLAG_BROKEN_SET_OBJECT_PROPLIST(ptp_usb)) { MTPProperties *props = NULL; MTPProperties *prop = NULL; int nrofprops = 0; for (i=0;ifiletype), &opd); if (ret != PTP_RC_OK) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not get property description."); } else if (opd.GetSet) { switch (properties[i]) { case PTP_OPC_Name: if (metadata->title == NULL) break; prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = metadata->item_id; prop->property = PTP_OPC_Name; prop->datatype = PTP_DTC_STR; prop->propval.str = strdup(metadata->title); break; case PTP_OPC_AlbumName: if (metadata->album == NULL) break; prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = metadata->item_id; prop->property = PTP_OPC_AlbumName; prop->datatype = PTP_DTC_STR; prop->propval.str = strdup(metadata->album); break; case PTP_OPC_Artist: if (metadata->artist == NULL) break; prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = metadata->item_id; prop->property = PTP_OPC_Artist; prop->datatype = PTP_DTC_STR; prop->propval.str = strdup(metadata->artist); break; case PTP_OPC_Composer: if (metadata->composer == NULL) break; prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = metadata->item_id; prop->property = PTP_OPC_Composer; prop->datatype = PTP_DTC_STR; prop->propval.str = strdup(metadata->composer); break; case PTP_OPC_Genre: if (metadata->genre == NULL) break; prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = metadata->item_id; prop->property = PTP_OPC_Genre; prop->datatype = PTP_DTC_STR; prop->propval.str = strdup(metadata->genre); break; case PTP_OPC_Duration: prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = metadata->item_id; prop->property = PTP_OPC_Duration; prop->datatype = PTP_DTC_UINT32; prop->propval.u32 = adjust_u32(metadata->duration, &opd); break; case PTP_OPC_Track: prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = metadata->item_id; prop->property = PTP_OPC_Track; prop->datatype = PTP_DTC_UINT16; prop->propval.u16 = adjust_u16(metadata->tracknumber, &opd); break; case PTP_OPC_OriginalReleaseDate: if (metadata->date == NULL) break; prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = metadata->item_id; prop->property = PTP_OPC_OriginalReleaseDate; prop->datatype = PTP_DTC_STR; prop->propval.str = strdup(metadata->date); break; case PTP_OPC_SampleRate: prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = metadata->item_id; prop->property = PTP_OPC_SampleRate; prop->datatype = PTP_DTC_UINT32; prop->propval.u32 = adjust_u32(metadata->samplerate, &opd); break; case PTP_OPC_NumberOfChannels: prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = metadata->item_id; prop->property = PTP_OPC_NumberOfChannels; prop->datatype = PTP_DTC_UINT16; prop->propval.u16 = adjust_u16(metadata->nochannels, &opd); break; case PTP_OPC_AudioWAVECodec: prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = metadata->item_id; prop->property = PTP_OPC_AudioWAVECodec; prop->datatype = PTP_DTC_UINT32; prop->propval.u32 = adjust_u32(metadata->wavecodec, &opd); break; case PTP_OPC_AudioBitRate: prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = metadata->item_id; prop->property = PTP_OPC_AudioBitRate; prop->datatype = PTP_DTC_UINT32; prop->propval.u32 = adjust_u32(metadata->bitrate, &opd); break; case PTP_OPC_BitRateType: prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = metadata->item_id; prop->property = PTP_OPC_BitRateType; prop->datatype = PTP_DTC_UINT16; prop->propval.u16 = adjust_u16(metadata->bitratetype, &opd); break; case PTP_OPC_Rating: // TODO: shall this be set for rating 0? if (metadata->rating == 0) break; prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = metadata->item_id; prop->property = PTP_OPC_Rating; prop->datatype = PTP_DTC_UINT16; prop->propval.u16 = adjust_u16(metadata->rating, &opd); break; case PTP_OPC_UseCount: prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = metadata->item_id; prop->property = PTP_OPC_UseCount; prop->datatype = PTP_DTC_UINT32; prop->propval.u32 = adjust_u32(metadata->usecount, &opd); break; case PTP_OPC_DateModified: if (!FLAG_CANNOT_HANDLE_DATEMODIFIED(ptp_usb)) { // Tag with current time if that is supported prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = metadata->item_id; prop->property = PTP_OPC_DateModified; prop->datatype = PTP_DTC_STR; prop->propval.str = get_iso8601_stamp(); } break; default: break; } } ptp_free_objectpropdesc(&opd); } // NOTE: File size is not updated, this should not change anyway. // neither will we change the filename. ret = ptp_mtp_setobjectproplist(params, props, nrofprops); ptp_destroy_object_prop_list(props, nrofprops); if (ret != PTP_RC_OK) { // TODO: return error of which property we couldn't set add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not set object property list."); free(properties); return -1; } } else if (ptp_operation_issupported(params,PTP_OC_MTP_SetObjectPropValue)) { for (i=0;ifiletype), &opd); if (ret != PTP_RC_OK) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not get property description."); } else if (opd.GetSet) { switch (properties[i]) { case PTP_OPC_Name: // Update title ret = set_object_string(device, metadata->item_id, PTP_OPC_Name, metadata->title); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not set track title."); } break; case PTP_OPC_AlbumName: // Update album ret = set_object_string(device, metadata->item_id, PTP_OPC_AlbumName, metadata->album); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not set track album name."); } break; case PTP_OPC_Artist: // Update artist ret = set_object_string(device, metadata->item_id, PTP_OPC_Artist, metadata->artist); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not set track artist name."); } break; case PTP_OPC_Composer: // Update composer ret = set_object_string(device, metadata->item_id, PTP_OPC_Composer, metadata->composer); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not set track composer name."); } break; case PTP_OPC_Genre: // Update genre (but only if valid) if (metadata->genre) { ret = set_object_string(device, metadata->item_id, PTP_OPC_Genre, metadata->genre); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "update_abstract_list(): " "could not set genre."); } } break; case PTP_OPC_Duration: // Update duration if (metadata->duration != 0) { ret = set_object_u32(device, metadata->item_id, PTP_OPC_Duration, adjust_u32(metadata->duration, &opd)); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not set track duration."); } } break; case PTP_OPC_Track: // Update track number. if (metadata->tracknumber != 0) { ret = set_object_u16(device, metadata->item_id, PTP_OPC_Track, adjust_u16(metadata->tracknumber, &opd)); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not set track tracknumber."); } } break; case PTP_OPC_OriginalReleaseDate: // Update creation datetime // The date can be zero, but some devices do not support setting zero // dates (and it seems that a zero date should never be set anyway) if (metadata->date) { ret = set_object_string(device, metadata->item_id, PTP_OPC_OriginalReleaseDate, metadata->date); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not set track release date."); } } break; // These are, well not so important. case PTP_OPC_SampleRate: // Update sample rate if (metadata->samplerate != 0) { ret = set_object_u32(device, metadata->item_id, PTP_OPC_SampleRate, adjust_u32(metadata->samplerate, &opd)); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not set samplerate."); } } break; case PTP_OPC_NumberOfChannels: // Update number of channels if (metadata->nochannels != 0) { ret = set_object_u16(device, metadata->item_id, PTP_OPC_NumberOfChannels, adjust_u16(metadata->nochannels, &opd)); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not set number of channels."); } } break; case PTP_OPC_AudioWAVECodec: // Update WAVE codec if (metadata->wavecodec != 0) { ret = set_object_u32(device, metadata->item_id, PTP_OPC_AudioWAVECodec, adjust_u32(metadata->wavecodec, &opd)); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not set WAVE codec."); } } break; case PTP_OPC_AudioBitRate: // Update bitrate if (metadata->bitrate != 0) { ret = set_object_u32(device, metadata->item_id, PTP_OPC_AudioBitRate, adjust_u32(metadata->bitrate, &opd)); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not set bitrate."); } } break; case PTP_OPC_BitRateType: // Update bitrate type if (metadata->bitratetype != 0) { ret = set_object_u16(device, metadata->item_id, PTP_OPC_BitRateType, adjust_u16(metadata->bitratetype, &opd)); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not set bitratetype."); } } break; case PTP_OPC_Rating: // Update user rating // TODO: shall this be set for rating 0? if (metadata->rating != 0) { ret = set_object_u16(device, metadata->item_id, PTP_OPC_Rating, adjust_u16(metadata->rating, &opd)); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not set user rating."); } } break; case PTP_OPC_UseCount: // Update use count, set even to zero if desired. ret = set_object_u32(device, metadata->item_id, PTP_OPC_UseCount, adjust_u32(metadata->usecount, &opd)); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not set use count."); } break; case PTP_OPC_DateModified: if (!FLAG_CANNOT_HANDLE_DATEMODIFIED(ptp_usb)) { // Update modification time if supported char *tmpstamp = get_iso8601_stamp(); ret = set_object_string(device, metadata->item_id, PTP_OPC_DateModified, tmpstamp); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "could not set modification date."); } free(tmpstamp); } break; // NOTE: File size is not updated, this should not change anyway. // neither will we change the filename. default: break; } } ptp_free_objectpropdesc(&opd); } } else { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Update_Track_Metadata(): " "Your device doesn't seem to support any known way of setting metadata."); free(properties); return -1; } // update cached object properties if metadata cache exists update_metadata_cache(device, metadata->item_id); free(properties); return 0; } /** * This function deletes a single file, track, playlist, folder or * any other object off the MTP device, identified by the object ID. * * If you delete a folder, there is no guarantee that the device will * really delete all the files that were in that folder, rather it is * expected that they will not be deleted, and will turn up in object * listings with parent set to a non-existant object ID. The safe way * to do this is to recursively delete all files (and folders) contained * in the folder, then the folder itself. * * @param device a pointer to the device to delete the object from. * @param object_id the object to delete. * @return 0 on success, any other value means failure. */ int LIBMTP_Delete_Object(LIBMTP_mtpdevice_t *device, uint32_t object_id) { uint16_t ret; PTPParams *params = (PTPParams *) device->params; ret = ptp_deleteobject(params, object_id, 0); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Delete_Object(): could not delete object."); return -1; } return 0; } /** * Internal function to update an object filename property. */ static int set_object_filename(LIBMTP_mtpdevice_t *device, uint32_t object_id, uint16_t ptp_type, const char **newname_ptr) { PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; PTPObjectPropDesc opd; uint16_t ret; char *newname; // See if we can modify the filename on this kind of files. ret = ptp_mtp_getobjectpropdesc(params, PTP_OPC_ObjectFileName, ptp_type, &opd); if (ret != PTP_RC_OK) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "set_object_filename(): " "could not get property description."); return -1; } if (!opd.GetSet) { ptp_free_objectpropdesc(&opd); add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "set_object_filename(): " " property is not settable."); // TODO: we COULD actually upload/download the object here, if we feel // like wasting time for the user. return -1; } newname = strdup(*newname_ptr); if (FLAG_ONLY_7BIT_FILENAMES(ptp_usb)) { strip_7bit_from_utf8(newname); } if (ptp_operation_issupported(params, PTP_OC_MTP_SetObjPropList) && !FLAG_BROKEN_SET_OBJECT_PROPLIST(ptp_usb)) { MTPProperties *props = NULL; MTPProperties *prop = NULL; int nrofprops = 0; prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = object_id; prop->property = PTP_OPC_ObjectFileName; prop->datatype = PTP_DTC_STR; prop->propval.str = newname; ret = ptp_mtp_setobjectproplist(params, props, nrofprops); ptp_destroy_object_prop_list(props, nrofprops); if (ret != PTP_RC_OK) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "set_object_filename(): " " could not set object property list."); ptp_free_objectpropdesc(&opd); return -1; } } else if (ptp_operation_issupported(params, PTP_OC_MTP_SetObjectPropValue)) { ret = set_object_string(device, object_id, PTP_OPC_ObjectFileName, newname); if (ret != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "set_object_filename(): " " could not set object filename."); ptp_free_objectpropdesc(&opd); return -1; } } else { free(newname); add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "set_object_filename(): " " your device doesn't seem to support any known way of setting metadata."); ptp_free_objectpropdesc(&opd); return -1; } ptp_free_objectpropdesc(&opd); // update cached object properties if metadata cache exists update_metadata_cache(device, object_id); return 0; } /** * This function renames a single file. * This simply means that the PTP_OPC_ObjectFileName property * is updated, if this is supported by the device. * * @param device a pointer to the device that contains the file. * @param file the file metadata of the file to rename. * On success, the filename member is updated. Be aware, that * this name can be different than newname depending of device restrictions. * @param newname the new filename for this object. * @return 0 on success, any other value means failure. */ int LIBMTP_Set_File_Name(LIBMTP_mtpdevice_t *device, LIBMTP_file_t *file, const char *newname) { int ret; ret = set_object_filename(device, file->item_id, map_libmtp_type_to_ptp_type(file->filetype), &newname); if (ret != 0) { return ret; } free(file->filename); file->filename = strdup(newname); return ret; } /** * This function renames a single folder. * This simply means that the PTP_OPC_ObjectFileName property * is updated, if this is supported by the device. * * @param device a pointer to the device that contains the file. * @param folder the folder metadata of the folder to rename. * On success, the name member is updated. Be aware, that * this name can be different than newname depending of device restrictions. * @param newname the new name for this object. * @return 0 on success, any other value means failure. */ int LIBMTP_Set_Folder_Name(LIBMTP_mtpdevice_t *device, LIBMTP_folder_t *folder, const char* newname) { int ret; ret = set_object_filename(device, folder->folder_id, PTP_OFC_Association, &newname); if (ret != 0) { return ret; } free(folder->name); folder->name = strdup(newname); return ret; } /** * This function renames a single track. * This simply means that the PTP_OPC_ObjectFileName property * is updated, if this is supported by the device. * * @param device a pointer to the device that contains the file. * @param track the track metadata of the track to rename. * On success, the filename member is updated. Be aware, that * this name can be different than newname depending of device restrictions. * @param newname the new filename for this object. * @return 0 on success, any other value means failure. */ int LIBMTP_Set_Track_Name(LIBMTP_mtpdevice_t *device, LIBMTP_track_t *track, const char* newname) { int ret; ret = set_object_filename(device, track->item_id, map_libmtp_type_to_ptp_type(track->filetype), &newname); if (ret != 0) { return ret; } free(track->filename); track->filename = strdup(newname); return ret; } /** * This function renames a single playlist object file holder. * This simply means that the PTP_OPC_ObjectFileName * property is updated, if this is supported by the device. * The playlist filename should nominally end with an extension * like ".pla". * * NOTE: if you want to change the metadata the device display * about a playlist you must not use this function, * use LIBMTP_Update_Playlist() instead! * * @param device a pointer to the device that contains the file. * @param playlist the playlist metadata of the playlist to rename. * On success, the name member is updated. Be aware, that * this name can be different than newname depending of device restrictions. * @param newname the new name for this object. * @return 0 on success, any other value means failure. * @see LIBMTP_Update_Playlist() */ int LIBMTP_Set_Playlist_Name(LIBMTP_mtpdevice_t *device, LIBMTP_playlist_t *playlist, const char* newname) { int ret; ret = set_object_filename(device, playlist->playlist_id, PTP_OFC_MTP_AbstractAudioVideoPlaylist, &newname); if (ret != 0) { return ret; } free(playlist->name); playlist->name = strdup(newname); return ret; } /** * This function renames a single album. * This simply means that the PTP_OPC_ObjectFileName * property is updated, if this is supported by the device. * The album filename should nominally end with an extension * like ".alb". * * NOTE: if you want to change the metadata the device display * about a playlist you must not use this function, * use LIBMTP_Update_Album() instead! * * @param device a pointer to the device that contains the file. * @param album the album metadata of the album to rename. * On success, the name member is updated. Be aware, that * this name can be different than newname depending of device restrictions. * @param newname the new name for this object. * @return 0 on success, any other value means failure. * @see LIBMTP_Update_Album() */ int LIBMTP_Set_Album_Name(LIBMTP_mtpdevice_t *device, LIBMTP_album_t *album, const char* newname) { int ret; ret = set_object_filename(device, album->album_id, PTP_OFC_MTP_AbstractAudioAlbum, &newname); if (ret != 0) { return ret; } free(album->name); album->name = strdup(newname); return ret; } /** * THIS FUNCTION IS DEPRECATED. PLEASE UPDATE YOUR CODE IN ORDER * NOT TO USE IT. * * @see LIBMTP_Set_File_Name() * @see LIBMTP_Set_Track_Name() * @see LIBMTP_Set_Folder_Name() * @see LIBMTP_Set_Playlist_Name() * @see LIBMTP_Set_Album_Name() */ int LIBMTP_Set_Object_Filename(LIBMTP_mtpdevice_t *device, uint32_t object_id, char* newname) { int ret; LIBMTP_file_t *file; file = LIBMTP_Get_Filemetadata(device, object_id); if (file == NULL) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Set_Object_Filename(): " "could not get file metadata for target object."); return -1; } ret = set_object_filename(device, object_id, map_libmtp_type_to_ptp_type(file->filetype), (const char **) &newname); free(file); return ret; } /** * Helper function. This indicates if a track exists on the device * @param device a pointer to the device to get the track from. * @param id the track ID of the track to retrieve. * @return TRUE (!=0) if the track exists, FALSE (0) if not */ int LIBMTP_Track_Exists(LIBMTP_mtpdevice_t *device, uint32_t const id) { PTPParams *params = (PTPParams *) device->params; uint16_t ret; PTPObject *ob; ret = ptp_object_want (params, id, 0, &ob); if (ret == PTP_RC_OK) return -1; return 0; } /** * This creates a new folder structure and allocates memory * for it. Notice that if you add strings to this structure they * will be freed by the corresponding LIBMTP_folder_track_t * operation later, so be careful of using strdup() when assigning * strings, e.g.: * * @return a pointer to the newly allocated folder structure. * @see LIBMTP_destroy_folder_t() */ LIBMTP_folder_t *LIBMTP_new_folder_t(void) { LIBMTP_folder_t *new = (LIBMTP_folder_t *) malloc(sizeof(LIBMTP_folder_t)); if (new == NULL) { return NULL; } new->folder_id = 0; new->parent_id = 0; new->storage_id = 0; new->name = NULL; new->sibling = NULL; new->child = NULL; return new; } /** * This recursively deletes the memory for a folder structure. * This shall typically be called on a top-level folder list to * detsroy the entire folder tree. * * @param folder folder structure to destroy * @see LIBMTP_new_folder_t() */ void LIBMTP_destroy_folder_t(LIBMTP_folder_t *folder) { if(folder == NULL) { return; } //Destroy from the bottom up if(folder->child != NULL) { LIBMTP_destroy_folder_t(folder->child); } if(folder->sibling != NULL) { LIBMTP_destroy_folder_t(folder->sibling); } if(folder->name != NULL) { free(folder->name); } free(folder); } /** * Helper function. Returns a folder structure for a * specified id. * * @param folderlist list of folders to search * @id id of folder to look for * @return a folder or NULL if not found */ LIBMTP_folder_t *LIBMTP_Find_Folder(LIBMTP_folder_t *folderlist, uint32_t id) { LIBMTP_folder_t *ret = NULL; if(folderlist == NULL) { return NULL; } if(folderlist->folder_id == id) { return folderlist; } if(folderlist->sibling) { ret = LIBMTP_Find_Folder(folderlist->sibling, id); } if(folderlist->child && ret == NULL) { ret = LIBMTP_Find_Folder(folderlist->child, id); } return ret; } /** * Function used to recursively get subfolders from params. */ static LIBMTP_folder_t *get_subfolders_for_folder(LIBMTP_folder_t *list, uint32_t parent) { LIBMTP_folder_t *retfolders = NULL; LIBMTP_folder_t *children, *iter, *curr; iter = list->sibling; while(iter != list) { if (iter->parent_id != parent) { iter = iter->sibling; continue; } /* We know that iter is a child of 'parent', therefore we can safely * hold on to 'iter' locally since no one else will steal it * from the 'list' as we recurse. */ children = get_subfolders_for_folder(list, iter->folder_id); curr = iter; iter = iter->sibling; // Remove curr from the list. curr->child->sibling = curr->sibling; curr->sibling->child = curr->child; // Attach the children to curr. curr->child = children; // Put this folder into the list of siblings. curr->sibling = retfolders; retfolders = curr; } return retfolders; } /** * This returns a list of all folders available * on the current MTP device. * * @param device a pointer to the device to get the folder listing for. * @param storage a storage ID to get the folder list from * @return a list of folders */ LIBMTP_folder_t *LIBMTP_Get_Folder_List_For_Storage(LIBMTP_mtpdevice_t *device, uint32_t const storage) { PTPParams *params = (PTPParams *) device->params; LIBMTP_folder_t head, *rv; int i; // Get all the handles if we haven't already done that if (params->nrofobjects == 0) { flush_handles(device); } /* * This creates a temporary list of the folders, this is in a * reverse order and uses the Folder pointers that are already * in the Folder structure. From this we can then build up the * folder hierarchy with only looking at this temporary list, * and removing the folders from this temporary list as we go. * This significantly reduces the number of operations that we * have to do in building the folder hierarchy. Also since the * temp list is in reverse order, when we prepend to the sibling * list things are in the same order as they were originally * in the handle list. */ head.sibling = &head; head.child = &head; for (i = 0; i < params->nrofobjects; i++) { LIBMTP_folder_t *folder; PTPObject *ob; ob = ¶ms->objects[i]; if (ob->oi.ObjectFormat != PTP_OFC_Association) { continue; } if (storage != PTP_GOH_ALL_STORAGE && storage != ob->oi.StorageID) { continue; } /* * Do we know how to handle these? They are part * of the MTP 1.0 specification paragraph 3.6.4. * For AssociationDesc 0x00000001U ptp_mtp_getobjectreferences() * should be called on these to get the contained objects, but * we basically don't care. Hopefully parent_id is maintained for all * children, because we rely on that instead. */ if (ob->oi.AssociationDesc != 0x00000000U) { LIBMTP_INFO("MTP extended association type 0x%08x encountered\n", ob->oi.AssociationDesc); } // Create a folder struct... folder = LIBMTP_new_folder_t(); if (folder == NULL) { // malloc failure or so. return NULL; } folder->folder_id = ob->oid; folder->parent_id = ob->oi.ParentObject; folder->storage_id = ob->oi.StorageID; folder->name = (ob->oi.Filename) ? (char *)strdup(ob->oi.Filename) : NULL; // pretend sibling says next, and child says prev. folder->sibling = head.sibling; folder->child = &head; head.sibling->child = folder; head.sibling = folder; } // We begin at the given root folder and get them all recursively rv = get_subfolders_for_folder(&head, 0x00000000U); // Some buggy devices may have some files in the "root folder" // 0xffffffff so if 0x00000000 didn't return any folders, // look for children of the root 0xffffffffU if (rv == NULL) { rv = get_subfolders_for_folder(&head, 0xffffffffU); if (rv != NULL) LIBMTP_ERROR("Device have files in \"root folder\" 0xffffffffU - " "this is a firmware bug (but continuing)\n"); } // The temp list should be empty. Clean up any orphans just in case. while(head.sibling != &head) { LIBMTP_folder_t *curr = head.sibling; LIBMTP_INFO("Orphan folder with ID: 0x%08x name: \"%s\" encountered.\n", curr->folder_id, curr->name); curr->sibling->child = curr->child; curr->child->sibling = curr->sibling; curr->child = NULL; curr->sibling = NULL; LIBMTP_destroy_folder_t(curr); } return rv; } /** * This returns a list of all folders available * on the current MTP device. * * @param device a pointer to the device to get the folder listing for. * @return a list of folders */ LIBMTP_folder_t *LIBMTP_Get_Folder_List(LIBMTP_mtpdevice_t *device) { return LIBMTP_Get_Folder_List_For_Storage(device, PTP_GOH_ALL_STORAGE); } /** * This create a folder on the current MTP device. The PTP name * for a folder is "association". The PTP/MTP devices does not * have an internal "folder" concept really, it contains a flat * list of all files and some file are "associations" that other * files and folders may refer to as its "parent". * * @param device a pointer to the device to create the folder on. * @param name the name of the new folder. Note this can be modified * if the device does not support all the characters in the * name. * @param parent_id id of parent folder to add the new folder to, * or 0 to put it in the root directory. * @param storage_id id of the storage to add this new folder to. * notice that you cannot mismatch storage id and parent id: * they must both be on the same storage! Pass in 0 if you * want to create this folder on the default storage. * @return id to new folder or 0 if an error occured */ uint32_t LIBMTP_Create_Folder(LIBMTP_mtpdevice_t *device, char *name, uint32_t parent_id, uint32_t storage_id) { PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; uint32_t parenthandle = 0; uint32_t store; PTPObjectInfo new_folder; uint16_t ret; uint32_t new_id = 0; if (storage_id == 0) { // I'm just guessing that a folder may require 512 bytes store = get_writeable_storageid(device, 512); } else { store = storage_id; } parenthandle = parent_id; memset(&new_folder, 0, sizeof(new_folder)); new_folder.Filename = name; if (FLAG_ONLY_7BIT_FILENAMES(ptp_usb)) { strip_7bit_from_utf8(new_folder.Filename); } new_folder.ObjectCompressedSize = 0; new_folder.ObjectFormat = PTP_OFC_Association; new_folder.ProtectionStatus = PTP_PS_NoProtection; new_folder.AssociationType = PTP_AT_GenericFolder; new_folder.ParentObject = parent_id; new_folder.StorageID = store; // Create the object if (!(params->device_flags & DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST) && ptp_operation_issupported(params,PTP_OC_MTP_SendObjectPropList)) { MTPProperties *props = (MTPProperties*)calloc(2,sizeof(MTPProperties)); props[0].property = PTP_OPC_ObjectFileName; props[0].datatype = PTP_DTC_STR; props[0].propval.str = name; props[1].property = PTP_OPC_Name; props[1].datatype = PTP_DTC_STR; props[1].propval.str = name; ret = ptp_mtp_sendobjectproplist(params, &store, &parenthandle, &new_id, PTP_OFC_Association, 0, props, 1); free(props); } else { ret = ptp_sendobjectinfo(params, &store, &parenthandle, &new_id, &new_folder); } if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Create_Folder: Could not send object info."); if (ret == PTP_RC_AccessDenied) { add_ptp_error_to_errorstack(device, ret, "ACCESS DENIED."); } return 0; } // NOTE: don't destroy the new_folder objectinfo, because it is statically referencing // several strings. add_object_to_cache(device, new_id); return new_id; } /** * This creates a new playlist metadata structure and allocates memory * for it. Notice that if you add strings to this structure they * will be freed by the corresponding LIBMTP_destroy_playlist_t * operation later, so be careful of using strdup() when assigning * strings, e.g.: * *
 * LIBMTP_playlist_t *pl = LIBMTP_new_playlist_t();
 * pl->name = strdup(str);
 * ....
 * LIBMTP_destroy_playlist_t(pl);
 * 
* * @return a pointer to the newly allocated metadata structure. * @see LIBMTP_destroy_playlist_t() */ LIBMTP_playlist_t *LIBMTP_new_playlist_t(void) { LIBMTP_playlist_t *new = (LIBMTP_playlist_t *) malloc(sizeof(LIBMTP_playlist_t)); if (new == NULL) { return NULL; } new->playlist_id = 0; new->parent_id = 0; new->storage_id = 0; new->name = NULL; new->tracks = NULL; new->no_tracks = 0; new->next = NULL; return new; } /** * This destroys a playlist metadata structure and deallocates the memory * used by it, including any strings. Never use a track metadata * structure again after calling this function on it. * @param playlist the playlist metadata to destroy. * @see LIBMTP_new_playlist_t() */ void LIBMTP_destroy_playlist_t(LIBMTP_playlist_t *playlist) { if (playlist == NULL) { return; } if (playlist->name != NULL) free(playlist->name); if (playlist->tracks != NULL) free(playlist->tracks); free(playlist); return; } /** * This function returns a list of the playlists available on the * device. Typical usage: * *
 * 
* * @param device a pointer to the device to get the playlist listing from. * @return a playlist list on success, else NULL. If there are no playlists * on the device, NULL will be returned as well. * @see LIBMTP_Get_Playlist() */ LIBMTP_playlist_t *LIBMTP_Get_Playlist_List(LIBMTP_mtpdevice_t *device) { PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; const int REQ_SPL = FLAG_PLAYLIST_SPL(ptp_usb); PTPParams *params = (PTPParams *) device->params; LIBMTP_playlist_t *retlists = NULL; LIBMTP_playlist_t *curlist = NULL; uint32_t i; // Get all the handles if we haven't already done that if (params->nrofobjects == 0) { flush_handles(device); } for (i = 0; i < params->nrofobjects; i++) { LIBMTP_playlist_t *pl; PTPObject *ob; uint16_t ret; ob = ¶ms->objects[i]; // Ignore stuff that isn't playlists // For Samsung players we must look for the .spl extension explicitly since // playlists are not stored as playlist objects. if ( REQ_SPL && is_spl_playlist(&ob->oi) ) { // Allocate a new playlist type pl = LIBMTP_new_playlist_t(); spl_to_playlist_t(device, &ob->oi, ob->oid, pl); } else if ( ob->oi.ObjectFormat != PTP_OFC_MTP_AbstractAudioVideoPlaylist ) { continue; } else { // Allocate a new playlist type pl = LIBMTP_new_playlist_t(); // Try to look up proper name, else use the oi->Filename field. pl->name = get_string_from_object(device, ob->oid, PTP_OPC_Name); if (pl->name == NULL) { pl->name = strdup(ob->oi.Filename); } pl->playlist_id = ob->oid; pl->parent_id = ob->oi.ParentObject; pl->storage_id = ob->oi.StorageID; // Then get the track listing for this playlist ret = ptp_mtp_getobjectreferences(params, pl->playlist_id, &pl->tracks, &pl->no_tracks); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Get_Playlist_List(): " "could not get object references."); pl->tracks = NULL; pl->no_tracks = 0; } } // Add playlist to a list that will be returned afterwards. if (retlists == NULL) { retlists = pl; curlist = pl; } else { curlist->next = pl; curlist = pl; } // Call callback here if we decide to add that possibility... } return retlists; } /** * This function retrieves an individual playlist from the device. * @param device a pointer to the device to get the playlist from. * @param plid the unique ID of the playlist to retrieve. * @return a valid playlist metadata post or NULL on failure. * @see LIBMTP_Get_Playlist_List() */ LIBMTP_playlist_t *LIBMTP_Get_Playlist(LIBMTP_mtpdevice_t *device, uint32_t const plid) { PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; const int REQ_SPL = FLAG_PLAYLIST_SPL(ptp_usb); PTPParams *params = (PTPParams *) device->params; PTPObject *ob; LIBMTP_playlist_t *pl; uint16_t ret; // Get all the handles if we haven't already done that if (params->nrofobjects == 0) { flush_handles(device); } ret = ptp_object_want (params, plid, PTPOBJECT_OBJECTINFO_LOADED, &ob); if (ret != PTP_RC_OK) return NULL; // For Samsung players we must look for the .spl extension explicitly since // playlists are not stored as playlist objects. if ( REQ_SPL && is_spl_playlist(&ob->oi) ) { // Allocate a new playlist type pl = LIBMTP_new_playlist_t(); spl_to_playlist_t(device, &ob->oi, ob->oid, pl); return pl; } // Ignore stuff that isn't playlists else if ( ob->oi.ObjectFormat != PTP_OFC_MTP_AbstractAudioVideoPlaylist ) { return NULL; } // Allocate a new playlist type pl = LIBMTP_new_playlist_t(); pl->name = get_string_from_object(device, ob->oid, PTP_OPC_Name); if (pl->name == NULL) { pl->name = strdup(ob->oi.Filename); } pl->playlist_id = ob->oid; pl->parent_id = ob->oi.ParentObject; pl->storage_id = ob->oi.StorageID; // Then get the track listing for this playlist ret = ptp_mtp_getobjectreferences(params, pl->playlist_id, &pl->tracks, &pl->no_tracks); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Get_Playlist(): Could not get object references."); pl->tracks = NULL; pl->no_tracks = 0; } return pl; } /** * This function creates a new abstract list such as a playlist * or an album. * * @param device a pointer to the device to create the new abstract list * on. * @param name the name of the new abstract list. * @param artist the artist of the new abstract list or NULL. * @param genre the genre of the new abstract list or NULL. * @param parenthandle the handle of the parent or 0 for no parent * i.e. the root folder. * @param objectformat the abstract list type to create. * @param suffix the ".foo" (4 characters) suffix to use for the virtual * "file" created by this operation. * @param newid a pointer to a variable that will hold the new object * ID if this call is successful. * @param tracks an array of tracks to associate with this list. * @param no_tracks the number of tracks in the list. * @return 0 on success, any other value means failure. */ static int create_new_abstract_list(LIBMTP_mtpdevice_t *device, char const * const name, char const * const artist, char const * const composer, char const * const genre, uint32_t const parenthandle, uint32_t const storageid, uint16_t const objectformat, char const * const suffix, uint32_t * const newid, uint32_t const * const tracks, uint32_t const no_tracks) { int i; int supported = 0; uint16_t ret; uint16_t *properties = NULL; uint32_t propcnt = 0; uint32_t store; uint32_t localph = parenthandle; uint8_t nonconsumable = 0x00U; /* By default it is consumable */ PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; char fname[256]; //uint8_t data[2]; // NULL check if (!name) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "create_new_abstract_list(): list name was NULL, using default name \"Unknown\""); return -1; } if (storageid == 0) { // I'm just guessing that an abstract list may require 512 bytes store = get_writeable_storageid(device, 512); } else { store = storageid; } // Check if we can create an object of this type for ( i=0; i < params->deviceinfo.ImageFormats_len; i++ ) { if (params->deviceinfo.ImageFormats[i] == objectformat) { supported = 1; break; } } if (!supported) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "create_new_abstract_list(): player does not support this abstract type"); LIBMTP_ERROR("Unsupported abstract list type: %04x\n", objectformat); return -1; } // add the new suffix if it isn't there fname[0] = '\0'; if (strlen(name) > strlen(suffix)) { char const * const suff = &name[strlen(name)-strlen(suffix)]; if (!strcmp(suff, suffix)) { // Home free. strncpy(fname, name, sizeof(fname)); } } // If it didn't end with "" then add that here. if (fname[0] == '\0') { strncpy(fname, name, sizeof(fname)-strlen(suffix)-1); strcat(fname, suffix); fname[sizeof(fname)-1] = '\0'; } if (ptp_operation_issupported(params, PTP_OC_MTP_SendObjectPropList) && !FLAG_BROKEN_SEND_OBJECT_PROPLIST(ptp_usb)) { MTPProperties *props = NULL; MTPProperties *prop = NULL; int nrofprops = 0; *newid = 0x00000000U; ret = ptp_mtp_getobjectpropssupported(params, objectformat, &propcnt, &properties); for (i=0;iObjectHandle = *newid; prop->property = PTP_OPC_ObjectFileName; prop->datatype = PTP_DTC_STR; prop->propval.str = strdup(fname); if (FLAG_ONLY_7BIT_FILENAMES(ptp_usb)) { strip_7bit_from_utf8(prop->propval.str); } break; case PTP_OPC_ProtectionStatus: prop = ptp_get_new_object_prop_entry(&props,&nrofprops); prop->ObjectHandle = *newid; prop->property = PTP_OPC_ProtectionStatus; prop->datatype = PTP_DTC_UINT16; prop->propval.u16 = 0x0000U; /* Not protected */ break; case PTP_OPC_NonConsumable: prop = ptp_get_new_object_prop_entry(&props,&nrofprops); prop->ObjectHandle = *newid; prop->property = PTP_OPC_NonConsumable; prop->datatype = PTP_DTC_UINT8; prop->propval.u8 = nonconsumable; break; case PTP_OPC_Name: if (name != NULL) { prop = ptp_get_new_object_prop_entry(&props,&nrofprops); prop->ObjectHandle = *newid; prop->property = PTP_OPC_Name; prop->datatype = PTP_DTC_STR; prop->propval.str = strdup(name); } break; case PTP_OPC_AlbumArtist: if (artist != NULL) { prop = ptp_get_new_object_prop_entry(&props,&nrofprops); prop->ObjectHandle = *newid; prop->property = PTP_OPC_AlbumArtist; prop->datatype = PTP_DTC_STR; prop->propval.str = strdup(artist); } break; case PTP_OPC_Artist: if (artist != NULL) { prop = ptp_get_new_object_prop_entry(&props,&nrofprops); prop->ObjectHandle = *newid; prop->property = PTP_OPC_Artist; prop->datatype = PTP_DTC_STR; prop->propval.str = strdup(artist); } break; case PTP_OPC_Composer: if (composer != NULL) { prop = ptp_get_new_object_prop_entry(&props,&nrofprops); prop->ObjectHandle = *newid; prop->property = PTP_OPC_Composer; prop->datatype = PTP_DTC_STR; prop->propval.str = strdup(composer); } break; case PTP_OPC_Genre: if (genre != NULL) { prop = ptp_get_new_object_prop_entry(&props,&nrofprops); prop->ObjectHandle = *newid; prop->property = PTP_OPC_Genre; prop->datatype = PTP_DTC_STR; prop->propval.str = strdup(genre); } break; case PTP_OPC_DateModified: // Tag with current time if that is supported if (!FLAG_CANNOT_HANDLE_DATEMODIFIED(ptp_usb)) { prop = ptp_get_new_object_prop_entry(&props,&nrofprops); prop->ObjectHandle = *newid; prop->property = PTP_OPC_DateModified; prop->datatype = PTP_DTC_STR; prop->propval.str = get_iso8601_stamp(); } break; } } ptp_free_objectpropdesc(&opd); } free(properties); ret = ptp_mtp_sendobjectproplist(params, &store, &localph, newid, objectformat, 0, props, nrofprops); /* Free property list */ ptp_destroy_object_prop_list(props, nrofprops); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "create_new_abstract_list(): Could not send object property list."); if (ret == PTP_RC_AccessDenied) { add_ptp_error_to_errorstack(device, ret, "ACCESS DENIED."); } return -1; } // now send the blank object ret = ptp_sendobject(params, NULL, 0); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "create_new_abstract_list(): Could not send blank object data."); return -1; } } else if (ptp_operation_issupported(params,PTP_OC_SendObjectInfo)) { PTPObjectInfo new_object; new_object.Filename = fname; if (FLAG_ONLY_7BIT_FILENAMES(ptp_usb)) { strip_7bit_from_utf8(new_object.Filename); } // At one point this had to be one new_object.ObjectCompressedSize = 0; new_object.ObjectFormat = objectformat; // Create the object ret = ptp_sendobjectinfo(params, &store, &localph, newid, &new_object); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "create_new_abstract_list(): Could not send object info (the playlist itself)."); if (ret == PTP_RC_AccessDenied) { add_ptp_error_to_errorstack(device, ret, "ACCESS DENIED."); } return -1; } // NOTE: don't destroy new_object objectinfo afterwards - the strings it contains are // not copies. #if 0 /* * At one time we had to send this one blank data byte. * If we didn't, the handle will not be created and thus there is * no playlist. Possibly this was masking some bug, so removing it * now. */ data[0] = '\0'; data[1] = '\0'; ret = ptp_sendobject(params, data, 1); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "create_new_abstract_list(): Could not send blank object data."); return -1; } #endif // set the properties one by one ret = ptp_mtp_getobjectpropssupported(params, objectformat, &propcnt, &properties); for (i=0;i 0) { // Add tracks to the list as object references. ret = ptp_mtp_setobjectreferences (params, *newid, (uint32_t *) tracks, no_tracks); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "create_new_abstract_list(): could not add tracks as object references."); return -1; } } add_object_to_cache(device, *newid); return 0; } /** * This updates the metadata and track listing * for an abstract list. * @param device a pointer to the device that the abstract list * resides on. * @param name the name of the abstract list. * @param artist the artist of the abstract list or NULL. * @param genre the genre of the abstract list or NULL. * @param objecthandle the object to be updated. * @param objectformat the abstract list type to update. * @param tracks an array of tracks to associate with this list. * @param no_tracks the number of tracks in the list. * @return 0 on success, any other value means failure. */ static int update_abstract_list(LIBMTP_mtpdevice_t *device, char const * const name, char const * const artist, char const * const composer, char const * const genre, uint32_t const objecthandle, uint16_t const objectformat, uint32_t const * const tracks, uint32_t const no_tracks) { uint16_t ret; PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; uint16_t *properties = NULL; uint32_t propcnt = 0; int i; // First see which properties can be set // i.e only try to update this metadata for object tags that exist on the current player. ret = ptp_mtp_getobjectpropssupported(params, objectformat, &propcnt, &properties); if (ret != PTP_RC_OK) { // Just bail out for now, nothing is ever set. add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "update_abstract_list(): " "could not retrieve supported object properties."); return -1; } if (ptp_operation_issupported(params,PTP_OC_MTP_SetObjPropList) && !FLAG_BROKEN_SET_OBJECT_PROPLIST(ptp_usb)) { MTPProperties *props = NULL; MTPProperties *prop = NULL; int nrofprops = 0; for (i=0;iObjectHandle = objecthandle; prop->property = PTP_OPC_Name; prop->datatype = PTP_DTC_STR; if (name != NULL) prop->propval.str = strdup(name); break; case PTP_OPC_AlbumArtist: if (artist != NULL) { prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = objecthandle; prop->property = PTP_OPC_AlbumArtist; prop->datatype = PTP_DTC_STR; prop->propval.str = strdup(artist); } break; case PTP_OPC_Artist: if (artist != NULL) { prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = objecthandle; prop->property = PTP_OPC_Artist; prop->datatype = PTP_DTC_STR; prop->propval.str = strdup(artist); } break; case PTP_OPC_Composer: if (composer != NULL) { prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = objecthandle; prop->property = PTP_OPC_Composer; prop->datatype = PTP_DTC_STR; prop->propval.str = strdup(composer); } break; case PTP_OPC_Genre: if (genre != NULL) { prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = objecthandle; prop->property = PTP_OPC_Genre; prop->datatype = PTP_DTC_STR; prop->propval.str = strdup(genre); } break; case PTP_OPC_DateModified: if (!FLAG_CANNOT_HANDLE_DATEMODIFIED(ptp_usb)) { // Tag with current time if that is supported prop = ptp_get_new_object_prop_entry(&props, &nrofprops); prop->ObjectHandle = objecthandle; prop->property = PTP_OPC_DateModified; prop->datatype = PTP_DTC_STR; prop->propval.str = get_iso8601_stamp(); } break; default: break; } } ptp_free_objectpropdesc(&opd); } // proplist could be NULL if we can't write any properties if (props != NULL) { ret = ptp_mtp_setobjectproplist(params, props, nrofprops); ptp_destroy_object_prop_list(props, nrofprops); if (ret != PTP_RC_OK) { // TODO: return error of which property we couldn't set add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "update_abstract_list(): " "could not set object property list."); free(properties); return -1; } } } else if (ptp_operation_issupported(params,PTP_OC_MTP_SetObjectPropValue)) { for (i=0;itracks field of the metadata * contains a track listing, these tracks will be added to the * playlist. * @param device a pointer to the device to create the new playlist on. * @param metadata the metadata for the new playlist. If the function * exits with success, the playlist_id field of this * struct will contain the new playlist ID of the playlist. *
    *
  • metadata->parent_id should be set to the parent * (e.g. folder) to store this track in. Since some * devices are a bit picky about where files * are placed, a default folder will be chosen if libmtp * has detected one for the current filetype and this * parameter is set to 0. If this is 0 and no default folder * can be found, the file will be stored in the root folder. *
  • metadata->storage_id should be set to the * desired storage (e.g. memory card or whatever your device * presents) to store this track in. Setting this to 0 will store * the track on the primary storage. *
* @return 0 on success, any other value means failure. * @see LIBMTP_Update_Playlist() * @see LIBMTP_Delete_Object() */ int LIBMTP_Create_New_Playlist(LIBMTP_mtpdevice_t *device, LIBMTP_playlist_t * const metadata) { PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; uint32_t localph = metadata->parent_id; // Use a default folder if none given if (localph == 0) { if (device->default_playlist_folder != 0) localph = device->default_playlist_folder; else localph = device->default_music_folder; } metadata->parent_id = localph; // Samsung needs its own special type of playlists if(FLAG_PLAYLIST_SPL(ptp_usb)) { return playlist_t_to_spl(device, metadata); } // Just create a new abstract audio/video playlist... return create_new_abstract_list(device, metadata->name, NULL, NULL, NULL, localph, metadata->storage_id, PTP_OFC_MTP_AbstractAudioVideoPlaylist, get_playlist_extension(ptp_usb), &metadata->playlist_id, metadata->tracks, metadata->no_tracks); } /** * This routine updates a playlist based on the metadata * supplied. If the tracks field of the metadata * contains a track listing, these tracks will be added to the * playlist in place of those already present, i.e. the * previous track listing will be deleted. For Samsung devices the * playlist id (metadata->playlist_id) is likely to change. * @param device a pointer to the device to create the new playlist on. * @param metadata the metadata for the playlist to be updated. * notice that the field playlist_id * must contain the apropriate playlist ID. Playlist ID * be modified to a new playlist ID by the time the * function returns since edit-in-place is not always possible. * @return 0 on success, any other value means failure. * @see LIBMTP_Create_New_Playlist() * @see LIBMTP_Delete_Object() */ int LIBMTP_Update_Playlist(LIBMTP_mtpdevice_t *device, LIBMTP_playlist_t * const metadata) { // Samsung needs its own special type of playlists PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; if(FLAG_PLAYLIST_SPL(ptp_usb)) { return update_spl_playlist(device, metadata); } return update_abstract_list(device, metadata->name, NULL, NULL, NULL, metadata->playlist_id, PTP_OFC_MTP_AbstractAudioVideoPlaylist, metadata->tracks, metadata->no_tracks); } /** * This creates a new album metadata structure and allocates memory * for it. Notice that if you add strings to this structure they * will be freed by the corresponding LIBMTP_destroy_album_t * operation later, so be careful of using strdup() when assigning * strings. * * @return a pointer to the newly allocated metadata structure. * @see LIBMTP_destroy_album_t() */ LIBMTP_album_t *LIBMTP_new_album_t(void) { LIBMTP_album_t *new = (LIBMTP_album_t *) malloc(sizeof(LIBMTP_album_t)); if (new == NULL) { return NULL; } new->album_id = 0; new->parent_id = 0; new->storage_id = 0; new->name = NULL; new->artist = NULL; new->composer = NULL; new->genre = NULL; new->tracks = NULL; new->no_tracks = 0; new->next = NULL; return new; } /** * This recursively deletes the memory for an album structure * * @param album structure to destroy * @see LIBMTP_new_album_t() */ void LIBMTP_destroy_album_t(LIBMTP_album_t *album) { if (album == NULL) { return; } if (album->name != NULL) free(album->name); if (album->artist != NULL) free(album->artist); if (album->composer != NULL) free(album->composer); if (album->genre != NULL) free(album->genre); if (album->tracks != NULL) free(album->tracks); free(album); return; } /** * This function maps and copies a property onto the album metadata if applicable. */ static void pick_property_to_album_metadata(LIBMTP_mtpdevice_t *device, MTPProperties *prop, LIBMTP_album_t *alb) { switch (prop->property) { case PTP_OPC_Name: if (prop->propval.str != NULL) alb->name = strdup(prop->propval.str); else alb->name = NULL; break; case PTP_OPC_AlbumArtist: if (prop->propval.str != NULL) { // This should take precedence over plain "Artist" if (alb->artist != NULL) free(alb->artist); alb->artist = strdup(prop->propval.str); } else alb->artist = NULL; break; case PTP_OPC_Artist: if (prop->propval.str != NULL) { // Only use of AlbumArtist is not set if (alb->artist == NULL) alb->artist = strdup(prop->propval.str); } else alb->artist = NULL; break; case PTP_OPC_Composer: if (prop->propval.str != NULL) alb->composer = strdup(prop->propval.str); else alb->composer = NULL; break; case PTP_OPC_Genre: if (prop->propval.str != NULL) alb->genre = strdup(prop->propval.str); else alb->genre = NULL; break; } } /** * This function retrieves the album metadata for an album * given by a unique ID. * @param device a pointer to the device to get the track metadata off. * @param alb an album metadata metadata set to fill in. */ static void get_album_metadata(LIBMTP_mtpdevice_t *device, LIBMTP_album_t *alb) { uint16_t ret; PTPParams *params = (PTPParams *) device->params; uint32_t i; MTPProperties *prop; PTPObject *ob; /* * If we have a cached, large set of metadata, then use it! */ ret = ptp_object_want(params, alb->album_id, PTPOBJECT_MTPPROPLIST_LOADED, &ob); if (ob->mtpprops) { prop = ob->mtpprops; for (i=0;inrofmtpprops;i++,prop++) pick_property_to_album_metadata(device, prop, alb); } else { uint16_t *props = NULL; uint32_t propcnt = 0; // First see which properties can be retrieved for albums ret = ptp_mtp_getobjectpropssupported(params, PTP_OFC_MTP_AbstractAudioAlbum, &propcnt, &props); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "get_album_metadata(): call to ptp_mtp_getobjectpropssupported() failed."); // Just bail out for now, nothing is ever set. return; } else { for (i=0;iname = get_string_from_object(device, ob->oid, PTP_OPC_Name); break; case PTP_OPC_AlbumArtist: if (alb->artist != NULL) free(alb->artist); alb->artist = get_string_from_object(device, ob->oid, PTP_OPC_AlbumArtist); break; case PTP_OPC_Artist: if (alb->artist == NULL) alb->artist = get_string_from_object(device, ob->oid, PTP_OPC_Artist); break; case PTP_OPC_Composer: alb->composer = get_string_from_object(device, ob->oid, PTP_OPC_Composer); break; case PTP_OPC_Genre: alb->genre = get_string_from_object(device, ob->oid, PTP_OPC_Genre); break; default: break; } } free(props); } } } /** * This function returns a list of the albums available on the * device. * * @param device a pointer to the device to get the album listing from. * @return an album list on success, else NULL. If there are no albums * on the device, NULL will be returned as well. * @see LIBMTP_Get_Album() */ LIBMTP_album_t *LIBMTP_Get_Album_List(LIBMTP_mtpdevice_t *device) { // Read all storage devices return LIBMTP_Get_Album_List_For_Storage(device, 0); } /** * This function returns a list of the albums available on the * device. You can filter on the storage ID. * * @param device a pointer to the device to get the album listing from. * @param storage_id ID of device storage (if null, all storages) * * @return an album list on success, else NULL. If there are no albums * on the device, NULL will be returned as well. * @see LIBMTP_Get_Album() */ LIBMTP_album_t *LIBMTP_Get_Album_List_For_Storage(LIBMTP_mtpdevice_t *device, uint32_t const storage_id) { PTPParams *params = (PTPParams *) device->params; LIBMTP_album_t *retalbums = NULL; LIBMTP_album_t *curalbum = NULL; uint32_t i; // Get all the handles if we haven't already done that if (params->nrofobjects == 0) flush_handles(device); for (i = 0; i < params->nrofobjects; i++) { LIBMTP_album_t *alb; PTPObject *ob; uint16_t ret; ob = ¶ms->objects[i]; // Ignore stuff that isn't an album if ( ob->oi.ObjectFormat != PTP_OFC_MTP_AbstractAudioAlbum ) continue; // Ignore stuff that isn't into the storage device if ((storage_id != 0) && (ob->oi.StorageID != storage_id )) continue; // Allocate a new album type alb = LIBMTP_new_album_t(); alb->album_id = ob->oid; alb->parent_id = ob->oi.ParentObject; alb->storage_id = ob->oi.StorageID; // Fetch supported metadata get_album_metadata(device, alb); // Then get the track listing for this album ret = ptp_mtp_getobjectreferences(params, alb->album_id, &alb->tracks, &alb->no_tracks); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Get_Album_List(): Could not get object references."); alb->tracks = NULL; alb->no_tracks = 0; } // Add album to a list that will be returned afterwards. if (retalbums == NULL) { retalbums = alb; curalbum = alb; } else { curalbum->next = alb; curalbum = alb; } } return retalbums; } /** * This function retrieves an individual album from the device. * @param device a pointer to the device to get the album from. * @param albid the unique ID of the album to retrieve. * @return a valid album metadata or NULL on failure. * @see LIBMTP_Get_Album_List() */ LIBMTP_album_t *LIBMTP_Get_Album(LIBMTP_mtpdevice_t *device, uint32_t const albid) { PTPParams *params = (PTPParams *) device->params; uint16_t ret; PTPObject *ob; LIBMTP_album_t *alb; // Get all the handles if we haven't already done that if (params->nrofobjects == 0) flush_handles(device); ret = ptp_object_want(params, albid, PTPOBJECT_OBJECTINFO_LOADED, &ob); if (ret != PTP_RC_OK) return NULL; // Ignore stuff that isn't an album if (ob->oi.ObjectFormat != PTP_OFC_MTP_AbstractAudioAlbum) return NULL; // Allocate a new album type alb = LIBMTP_new_album_t(); alb->album_id = ob->oid; alb->parent_id = ob->oi.ParentObject; alb->storage_id = ob->oi.StorageID; // Fetch supported metadata get_album_metadata(device, alb); // Then get the track listing for this album ret = ptp_mtp_getobjectreferences(params, alb->album_id, &alb->tracks, &alb->no_tracks); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Get_Album: Could not get object references."); alb->tracks = NULL; alb->no_tracks = 0; } return alb; } /** * This routine creates a new album based on the metadata * supplied. If the tracks field of the metadata * contains a track listing, these tracks will be added to the * album. * @param device a pointer to the device to create the new album on. * @param metadata the metadata for the new album. If the function * exits with success, the album_id field of this * struct will contain the new ID of the album. *
    *
  • metadata->parent_id should be set to the parent * (e.g. folder) to store this track in. Since some * devices are a bit picky about where files * are placed, a default folder will be chosen if libmtp * has detected one for the current filetype and this * parameter is set to 0. If this is 0 and no default folder * can be found, the file will be stored in the root folder. *
  • metadata->storage_id should be set to the * desired storage (e.g. memory card or whatever your device * presents) to store this track in. Setting this to 0 will store * the track on the primary storage. *
* @return 0 on success, any other value means failure. * @see LIBMTP_Update_Album() * @see LIBMTP_Delete_Object() */ int LIBMTP_Create_New_Album(LIBMTP_mtpdevice_t *device, LIBMTP_album_t * const metadata) { uint32_t localph = metadata->parent_id; // Use a default folder if none given if (localph == 0) { if (device->default_album_folder != 0) localph = device->default_album_folder; else localph = device->default_music_folder; } metadata->parent_id = localph; // Just create a new abstract album... return create_new_abstract_list(device, metadata->name, metadata->artist, metadata->composer, metadata->genre, localph, metadata->storage_id, PTP_OFC_MTP_AbstractAudioAlbum, ".alb", &metadata->album_id, metadata->tracks, metadata->no_tracks); } /** * This creates a new sample data metadata structure and allocates memory * for it. Notice that if you add strings to this structure they * will be freed by the corresponding LIBMTP_destroy_sampledata_t * operation later, so be careful of using strdup() when assigning * strings. * * @return a pointer to the newly allocated metadata structure. * @see LIBMTP_destroy_sampledata_t() */ LIBMTP_filesampledata_t *LIBMTP_new_filesampledata_t(void) { LIBMTP_filesampledata_t *new = (LIBMTP_filesampledata_t *) malloc(sizeof(LIBMTP_filesampledata_t)); if (new == NULL) { return NULL; } new->height=0; new->width = 0; new->data = NULL; new->duration = 0; new->size = 0; return new; } /** * This destroys a file sample metadata type. * @param sample the file sample metadata to be destroyed. */ void LIBMTP_destroy_filesampledata_t(LIBMTP_filesampledata_t * sample) { if (sample == NULL) { return; } if (sample->data != NULL) { free(sample->data); } free(sample); } /** * This routine figures out whether a certain filetype supports * representative samples (small thumbnail images) or not. This * typically applies to JPEG files, MP3 files and Album abstract * playlists, but in theory any filetype could support representative * samples. * @param device a pointer to the device which is to be examined. * @param filetype the fileype to examine, and return the representative sample * properties for. * @param sample this will contain a new sample type with the fields * filled in with suitable default values. For example, the * supported sample type will be set, the supported height and * width will be set to max values if it is an image sample, * and duration will also be given some suitable default value * which should not be exceeded on audio samples. If the * device does not support samples for this filetype, this * pointer will be NULL. If it is not NULL, the user must * destroy this struct with LIBMTP_destroy_filesampledata_t() * after use. * @return 0 on success, any other value means failure. * @see LIBMTP_Send_Representative_Sample() * @see LIBMTP_Create_New_Album() */ int LIBMTP_Get_Representative_Sample_Format(LIBMTP_mtpdevice_t *device, LIBMTP_filetype_t const filetype, LIBMTP_filesampledata_t ** sample) { uint16_t ret; PTPParams *params = (PTPParams *) device->params; uint16_t *props = NULL; uint32_t propcnt = 0; int i; // TODO: Get rid of these when we can properly query the device. int support_data = 0; int support_format = 0; int support_height = 0; int support_width = 0; int support_duration = 0; int support_size = 0; PTPObjectPropDesc opd_height; PTPObjectPropDesc opd_width; PTPObjectPropDesc opd_format; PTPObjectPropDesc opd_duration; PTPObjectPropDesc opd_size; // Default to no type supported. *sample = NULL; ret = ptp_mtp_getobjectpropssupported(params, map_libmtp_type_to_ptp_type(filetype), &propcnt, &props); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Get_Representative_Sample_Format(): could not get object properties."); return -1; } /* * TODO: when walking through these object properties, make calls to * a new function in ptp.h/ptp.c that can send the command * PTP_OC_MTP_GetObjectPropDesc to get max/min values of the properties * supported. */ for (i = 0; i < propcnt; i++) { switch(props[i]) { case PTP_OPC_RepresentativeSampleData: support_data = 1; break; case PTP_OPC_RepresentativeSampleFormat: support_format = 1; break; case PTP_OPC_RepresentativeSampleSize: support_size = 1; break; case PTP_OPC_RepresentativeSampleHeight: support_height = 1; break; case PTP_OPC_RepresentativeSampleWidth: support_width = 1; break; case PTP_OPC_RepresentativeSampleDuration: support_duration = 1; break; default: break; } } free(props); if (support_data && support_format && support_height && support_width && !support_duration) { // Something that supports height and width and not duration is likely to be JPEG LIBMTP_filesampledata_t *retsam = LIBMTP_new_filesampledata_t(); /* * Populate the sample format with the first supported format * * TODO: figure out how to pass back more than one format if more are * supported by the device. */ ptp_mtp_getobjectpropdesc (params, PTP_OPC_RepresentativeSampleFormat, map_libmtp_type_to_ptp_type(filetype), &opd_format); retsam->filetype = map_ptp_type_to_libmtp_type(opd_format.FORM.Enum.SupportedValue[0].u16); ptp_free_objectpropdesc(&opd_format); /* Populate the maximum image height */ ptp_mtp_getobjectpropdesc (params, PTP_OPC_RepresentativeSampleWidth, map_libmtp_type_to_ptp_type(filetype), &opd_width); retsam->width = opd_width.FORM.Range.MaximumValue.u32; ptp_free_objectpropdesc(&opd_width); /* Populate the maximum image width */ ptp_mtp_getobjectpropdesc (params, PTP_OPC_RepresentativeSampleHeight, map_libmtp_type_to_ptp_type(filetype), &opd_height); retsam->height = opd_height.FORM.Range.MaximumValue.u32; ptp_free_objectpropdesc(&opd_height); /* Populate the maximum size */ if (support_size) { ptp_mtp_getobjectpropdesc (params, PTP_OPC_RepresentativeSampleSize, map_libmtp_type_to_ptp_type(filetype), &opd_size); retsam->size = opd_size.FORM.Range.MaximumValue.u32; ptp_free_objectpropdesc(&opd_size); } *sample = retsam; } else if (support_data && support_format && !support_height && !support_width && support_duration) { // Another qualified guess LIBMTP_filesampledata_t *retsam = LIBMTP_new_filesampledata_t(); /* * Populate the sample format with the first supported format * * TODO: figure out how to pass back more than one format if more are * supported by the device. */ ptp_mtp_getobjectpropdesc (params, PTP_OPC_RepresentativeSampleFormat, map_libmtp_type_to_ptp_type(filetype), &opd_format); retsam->filetype = map_ptp_type_to_libmtp_type(opd_format.FORM.Enum.SupportedValue[0].u16); ptp_free_objectpropdesc(&opd_format); /* Populate the maximum duration */ ptp_mtp_getobjectpropdesc (params, PTP_OPC_RepresentativeSampleDuration, map_libmtp_type_to_ptp_type(filetype), &opd_duration); retsam->duration = opd_duration.FORM.Range.MaximumValue.u32; ptp_free_objectpropdesc(&opd_duration); /* Populate the maximum size */ if (support_size) { ptp_mtp_getobjectpropdesc (params, PTP_OPC_RepresentativeSampleSize, map_libmtp_type_to_ptp_type(filetype), &opd_size); retsam->size = opd_size.FORM.Range.MaximumValue.u32; ptp_free_objectpropdesc(&opd_size); } *sample = retsam; } return 0; } /** * This routine sends representative sample data for an object. * This uses the RepresentativeSampleData property of the album, * if the device supports it. The data should be of a format acceptable * to the player (for iRiver and Creative, this seems to be JPEG) and * must not be too large. (for a Creative, max seems to be about 20KB.) * Check by calling LIBMTP_Get_Representative_Sample_Format() to get * maximum size, dimensions, etc.. * @param device a pointer to the device which the object is on. * @param id unique id of the object to set artwork for. * @param pointer to LIBMTP_filesampledata_t struct containing data * @return 0 on success, any other value means failure. * @see LIBMTP_Get_Representative_Sample() * @see LIBMTP_Get_Representative_Sample_Format() * @see LIBMTP_Create_New_Album() */ int LIBMTP_Send_Representative_Sample(LIBMTP_mtpdevice_t *device, uint32_t const id, LIBMTP_filesampledata_t *sampledata) { uint16_t ret; PTPParams *params = (PTPParams *) device->params; PTP_USB *ptp_usb = (PTP_USB*) device->usbinfo; PTPPropertyValue propval; PTPObject *ob; uint32_t i; uint16_t *props = NULL; uint32_t propcnt = 0; int supported = 0; // get the file format for the object we're going to send representative data for ret = ptp_object_want (params, id, PTPOBJECT_OBJECTINFO_LOADED, &ob); if (ret != PTP_RC_OK) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Send_Representative_Sample(): could not get object info."); return -1; } // check that we can send representative sample data for this object format ret = ptp_mtp_getobjectpropssupported(params, ob->oi.ObjectFormat, &propcnt, &props); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Send_Representative_Sample(): could not get object properties."); return -1; } for (i = 0; i < propcnt; i++) { if (props[i] == PTP_OPC_RepresentativeSampleData) { supported = 1; break; } } if (!supported) { free(props); add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Send_Representative_Sample(): object type doesn't support RepresentativeSampleData."); return -1; } free(props); // Go ahead and send the data propval.a.count = sampledata->size; propval.a.v = malloc(sizeof(PTPPropertyValue) * sampledata->size); for (i = 0; i < sampledata->size; i++) { propval.a.v[i].u8 = sampledata->data[i]; } ret = ptp_mtp_setobjectpropvalue(params,id,PTP_OPC_RepresentativeSampleData, &propval,PTP_DTC_AUINT8); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Send_Representative_Sample(): could not send sample data."); free(propval.a.v); return -1; } free(propval.a.v); /* Set the height and width if the sample is an image, otherwise just * set the duration and size */ switch(sampledata->filetype) { case LIBMTP_FILETYPE_JPEG: case LIBMTP_FILETYPE_JFIF: case LIBMTP_FILETYPE_TIFF: case LIBMTP_FILETYPE_BMP: case LIBMTP_FILETYPE_GIF: case LIBMTP_FILETYPE_PICT: case LIBMTP_FILETYPE_PNG: if (!FLAG_BROKEN_SET_SAMPLE_DIMENSIONS(ptp_usb)) { // For images, set the height and width set_object_u32(device, id, PTP_OPC_RepresentativeSampleHeight, sampledata->height); set_object_u32(device, id, PTP_OPC_RepresentativeSampleWidth, sampledata->width); } break; default: // For anything not an image, set the duration and size set_object_u32(device, id, PTP_OPC_RepresentativeSampleDuration, sampledata->duration); set_object_u32(device, id, PTP_OPC_RepresentativeSampleSize, sampledata->size); break; } return 0; } /** * This routine gets representative sample data for an object. * This uses the RepresentativeSampleData property of the album, * if the device supports it. * @param device a pointer to the device which the object is on. * @param id unique id of the object to get data for. * @param pointer to LIBMTP_filesampledata_t struct to receive data * @return 0 on success, any other value means failure. * @see LIBMTP_Send_Representative_Sample() * @see LIBMTP_Get_Representative_Sample_Format() * @see LIBMTP_Create_New_Album() */ int LIBMTP_Get_Representative_Sample(LIBMTP_mtpdevice_t *device, uint32_t const id, LIBMTP_filesampledata_t *sampledata) { uint16_t ret; PTPParams *params = (PTPParams *) device->params; PTPPropertyValue propval; PTPObject *ob; uint32_t i; uint16_t *props = NULL; uint32_t propcnt = 0; int supported = 0; // get the file format for the object we're going to send representative data for ret = ptp_object_want (params, id, PTPOBJECT_OBJECTINFO_LOADED, &ob); if (ret != PTP_RC_OK) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Get_Representative_Sample(): could not get object info."); return -1; } // check that we can store representative sample data for this object format ret = ptp_mtp_getobjectpropssupported(params, ob->oi.ObjectFormat, &propcnt, &props); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Get_Representative_Sample(): could not get object properties."); return -1; } for (i = 0; i < propcnt; i++) { if (props[i] == PTP_OPC_RepresentativeSampleData) { supported = 1; break; } } if (!supported) { free(props); add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_Get_Representative_Sample(): object type doesn't support RepresentativeSampleData."); return -1; } free(props); // Get the data ret = ptp_mtp_getobjectpropvalue(params,id,PTP_OPC_RepresentativeSampleData, &propval,PTP_DTC_AUINT8); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "LIBMTP_Get_Representative_Sample(): could not get sample data."); return -1; } // Store it sampledata->size = propval.a.count; sampledata->data = malloc(sizeof(PTPPropertyValue) * propval.a.count); for (i = 0; i < propval.a.count; i++) { sampledata->data[i] = propval.a.v[i].u8; } free(propval.a.v); // Get the other properties sampledata->width = get_u32_from_object(device, id, PTP_OPC_RepresentativeSampleWidth, 0); sampledata->height = get_u32_from_object(device, id, PTP_OPC_RepresentativeSampleHeight, 0); sampledata->duration = get_u32_from_object(device, id, PTP_OPC_RepresentativeSampleDuration, 0); sampledata->filetype = map_ptp_type_to_libmtp_type( get_u16_from_object(device, id, PTP_OPC_RepresentativeSampleFormat, LIBMTP_FILETYPE_UNKNOWN)); return 0; } /** * Retrieve the thumbnail for a file. * @param device a pointer to the device to get the thumbnail from. * @param id the object ID of the file to retrieve the thumbnail for. * @return 0 on success, any other value means failure. */ int LIBMTP_Get_Thumbnail(LIBMTP_mtpdevice_t *device, uint32_t const id, unsigned char **data, unsigned int *size) { PTPParams *params = (PTPParams *) device->params; uint16_t ret; ret = ptp_getthumb(params, id, data, size); if (ret == PTP_RC_OK) return 0; return -1; } int LIBMTP_GetPartialObject(LIBMTP_mtpdevice_t *device, uint32_t const id, uint64_t offset, uint32_t maxbytes, unsigned char **data, unsigned int *size) { PTPParams *params = (PTPParams *) device->params; uint16_t ret; if (!ptp_operation_issupported(params, PTP_OC_ANDROID_GetPartialObject64)) { if (!ptp_operation_issupported(params, PTP_OC_GetPartialObject)) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_GetPartialObject: PTP_OC_GetPartialObject not supported"); return -1; } if (offset >> 32 != 0) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_GetPartialObject: PTP_OC_GetPartialObject only supports 32bit offsets"); return -1; } ret = ptp_getpartialobject(params, id, (uint32_t)offset, maxbytes, data, size); } else { ret = ptp_android_getpartialobject64(params, id, offset, maxbytes, data, size); } if (ret == PTP_RC_OK) return 0; return -1; } int LIBMTP_SendPartialObject(LIBMTP_mtpdevice_t *device, uint32_t const id, uint64_t offset, unsigned char *data, unsigned int size) { PTPParams *params = (PTPParams *) device->params; uint16_t ret; if (!ptp_operation_issupported(params, PTP_OC_ANDROID_SendPartialObject)) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_SendPartialObject: PTP_OC_ANDROID_SendPartialObject not supported"); return -1; } ret = ptp_android_sendpartialobject(params, id, offset, data, size); if (ret == PTP_RC_OK) return 0; return -1; } int LIBMTP_BeginEditObject(LIBMTP_mtpdevice_t *device, uint32_t const id) { PTPParams *params = (PTPParams *) device->params; uint16_t ret; if (!ptp_operation_issupported(params, PTP_OC_ANDROID_BeginEditObject)) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_BeginEditObject: PTP_OC_ANDROID_BeginEditObject not supported"); return -1; } ret = ptp_android_begineditobject(params, id); if (ret == PTP_RC_OK) return 0; return -1; } int LIBMTP_EndEditObject(LIBMTP_mtpdevice_t *device, uint32_t const id) { PTPParams *params = (PTPParams *) device->params; uint16_t ret; if (!ptp_operation_issupported(params, PTP_OC_ANDROID_EndEditObject)) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_EndEditObject: PTP_OC_ANDROID_EndEditObject not supported"); return -1; } ret = ptp_android_endeditobject(params, id); if (ret == PTP_RC_OK) { // update cached object properties if metadata cache exists update_metadata_cache(device, id); return 0; } return -1; } int LIBMTP_TruncateObject(LIBMTP_mtpdevice_t *device, uint32_t const id, uint64_t offset) { PTPParams *params = (PTPParams *) device->params; uint16_t ret; if (!ptp_operation_issupported(params, PTP_OC_ANDROID_TruncateObject)) { add_error_to_errorstack(device, LIBMTP_ERROR_GENERAL, "LIBMTP_TruncateObject: PTP_OC_ANDROID_TruncateObject not supported"); return -1; } ret = ptp_android_truncate(params, id, offset); if (ret == PTP_RC_OK) return 0; return -1; } /** * This routine updates an album based on the metadata * supplied. If the tracks field of the metadata * contains a track listing, these tracks will be added to the * album in place of those already present, i.e. the * previous track listing will be deleted. * @param device a pointer to the device to create the new album on. * @param metadata the metadata for the album to be updated. * notice that the field album_id * must contain the apropriate album ID. * @return 0 on success, any other value means failure. * @see LIBMTP_Create_New_Album() * @see LIBMTP_Delete_Object() */ int LIBMTP_Update_Album(LIBMTP_mtpdevice_t *device, LIBMTP_album_t const * const metadata) { return update_abstract_list(device, metadata->name, metadata->artist, metadata->composer, metadata->genre, metadata->album_id, PTP_OFC_MTP_AbstractAudioAlbum, metadata->tracks, metadata->no_tracks); } /** * Dummy function needed to interface to upstream * ptp.c/ptp.h files. */ void ptp_nikon_getptpipguid (unsigned char* guid) { return; } /** * Add an object to cache. * @param device the device which may have a cache to which the object should be added. * @param object_id the object to add to the cache. */ static void add_object_to_cache(LIBMTP_mtpdevice_t *device, uint32_t object_id) { PTPParams *params = (PTPParams *)device->params; uint16_t ret; ret = ptp_add_object_to_cache(params, object_id); if (ret != PTP_RC_OK) { add_ptp_error_to_errorstack(device, ret, "add_object_to_cache(): couldn't add object to cache"); } } /** * Update cache after object has been modified * @param device the device which may have a cache to which the object should be updated. * @param object_id the object to update. */ static void update_metadata_cache(LIBMTP_mtpdevice_t *device, uint32_t object_id) { PTPParams *params = (PTPParams *)device->params; ptp_remove_object_from_cache(params, object_id); add_object_to_cache(device, object_id); } libmtp-1.1.6-20-g1b9f164/src/ptp.h0000664000175000017500000033603612205614637016470 0ustar glowwormglowworm/* ptp.h * * Copyright (C) 2001 Mariusz Woloszyn * Copyright (C) 2003-2012 Marcus Meissner * Copyright (C) 2006-2008 Linus Walleij * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef __PTP_H__ #define __PTP_H__ #include #include #ifdef HAVE_ICONV #include #endif #include "gphoto2-endian.h" #include "device-flags.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* PTP datalayer byteorder */ #define PTP_DL_BE 0xF0 #define PTP_DL_LE 0x0F /* USB interface class */ #ifndef USB_CLASS_PTP #define USB_CLASS_PTP 6 #endif /* PTP request/response/event general PTP container (transport independent) */ struct _PTPContainer { uint16_t Code; uint32_t SessionID; uint32_t Transaction_ID; /* params may be of any type of size less or equal to uint32_t */ uint32_t Param1; uint32_t Param2; uint32_t Param3; /* events can only have three parameters */ uint32_t Param4; uint32_t Param5; /* the number of meaningfull parameters */ uint8_t Nparam; }; typedef struct _PTPContainer PTPContainer; /* PTP USB Bulk-Pipe container */ /* USB bulk max packet length for high speed endpoints */ /* The max packet is set to 512 bytes. The spec says * "end of data transfers are signaled by short packets or NULL * packets". It never says anything about 512, but current * implementations seem to have chosen this value, which also * happens to be the size of an USB 2.0 HS endpoint, even though * this is not necessary. * * Previously we had this as 4096 for MTP devices. We have found * and fixed the bugs that made this necessary and it can be 512 again. */ #define PTP_USB_BULK_HS_MAX_PACKET_LEN_WRITE 512 #define PTP_USB_BULK_HS_MAX_PACKET_LEN_READ 512 #define PTP_USB_BULK_HDR_LEN (2*sizeof(uint32_t)+2*sizeof(uint16_t)) #define PTP_USB_BULK_PAYLOAD_LEN_WRITE (PTP_USB_BULK_HS_MAX_PACKET_LEN_WRITE-PTP_USB_BULK_HDR_LEN) #define PTP_USB_BULK_PAYLOAD_LEN_READ (PTP_USB_BULK_HS_MAX_PACKET_LEN_READ-PTP_USB_BULK_HDR_LEN) #define PTP_USB_BULK_REQ_LEN (PTP_USB_BULK_HDR_LEN+5*sizeof(uint32_t)) struct _PTPUSBBulkContainer { uint32_t length; uint16_t type; uint16_t code; uint32_t trans_id; union { struct { uint32_t param1; uint32_t param2; uint32_t param3; uint32_t param4; uint32_t param5; } params; /* this must be set to the maximum of PTP_USB_BULK_PAYLOAD_LEN_WRITE * and PTP_USB_BULK_PAYLOAD_LEN_READ */ unsigned char data[PTP_USB_BULK_PAYLOAD_LEN_READ]; } payload; }; typedef struct _PTPUSBBulkContainer PTPUSBBulkContainer; /* PTP USB Asynchronous Event Interrupt Data Format */ struct _PTPUSBEventContainer { uint32_t length; uint16_t type; uint16_t code; uint32_t trans_id; uint32_t param1; uint32_t param2; uint32_t param3; }; typedef struct _PTPUSBEventContainer PTPUSBEventContainer; struct _PTPCanon_directtransfer_entry { uint32_t oid; char *str; }; typedef struct _PTPCanon_directtransfer_entry PTPCanon_directtransfer_entry; /* USB container types */ #define PTP_USB_CONTAINER_UNDEFINED 0x0000 #define PTP_USB_CONTAINER_COMMAND 0x0001 #define PTP_USB_CONTAINER_DATA 0x0002 #define PTP_USB_CONTAINER_RESPONSE 0x0003 #define PTP_USB_CONTAINER_EVENT 0x0004 /* PTP/IP definitions */ #define PTPIP_INIT_COMMAND_REQUEST 1 #define PTPIP_INIT_COMMAND_ACK 2 #define PTPIP_INIT_EVENT_REQUEST 3 #define PTPIP_INIT_EVENT_ACK 4 #define PTPIP_INIT_FAIL 5 #define PTPIP_CMD_REQUEST 6 #define PTPIP_CMD_RESPONSE 7 #define PTPIP_EVENT 8 #define PTPIP_START_DATA_PACKET 9 #define PTPIP_DATA_PACKET 10 #define PTPIP_CANCEL_TRANSACTION 11 #define PTPIP_END_DATA_PACKET 12 #define PTPIP_PING 13 #define PTPIP_PONG 14 struct _PTPIPHeader { uint32_t length; uint32_t type; }; typedef struct _PTPIPHeader PTPIPHeader; /* Vendor IDs */ #define PTP_VENDOR_EASTMAN_KODAK 0x00000001 #define PTP_VENDOR_SEIKO_EPSON 0x00000002 #define PTP_VENDOR_AGILENT 0x00000003 #define PTP_VENDOR_POLAROID 0x00000004 #define PTP_VENDOR_AGFA_GEVAERT 0x00000005 #define PTP_VENDOR_MICROSOFT 0x00000006 #define PTP_VENDOR_EQUINOX 0x00000007 #define PTP_VENDOR_VIEWQUEST 0x00000008 #define PTP_VENDOR_STMICROELECTRONICS 0x00000009 #define PTP_VENDOR_NIKON 0x0000000A #define PTP_VENDOR_CANON 0x0000000B #define PTP_VENDOR_FOTONATION 0x0000000C #define PTP_VENDOR_PENTAX 0x0000000D #define PTP_VENDOR_FUJI 0x0000000E /* Vendor extension ID used for MTP (occasionaly, usualy 6 is used) */ #define PTP_VENDOR_MTP 0xffffffff /* Operation Codes */ /* PTP v1.0 operation codes */ #define PTP_OC_Undefined 0x1000 #define PTP_OC_GetDeviceInfo 0x1001 #define PTP_OC_OpenSession 0x1002 #define PTP_OC_CloseSession 0x1003 #define PTP_OC_GetStorageIDs 0x1004 #define PTP_OC_GetStorageInfo 0x1005 #define PTP_OC_GetNumObjects 0x1006 #define PTP_OC_GetObjectHandles 0x1007 #define PTP_OC_GetObjectInfo 0x1008 #define PTP_OC_GetObject 0x1009 #define PTP_OC_GetThumb 0x100A #define PTP_OC_DeleteObject 0x100B #define PTP_OC_SendObjectInfo 0x100C #define PTP_OC_SendObject 0x100D #define PTP_OC_InitiateCapture 0x100E #define PTP_OC_FormatStore 0x100F #define PTP_OC_ResetDevice 0x1010 #define PTP_OC_SelfTest 0x1011 #define PTP_OC_SetObjectProtection 0x1012 #define PTP_OC_PowerDown 0x1013 #define PTP_OC_GetDevicePropDesc 0x1014 #define PTP_OC_GetDevicePropValue 0x1015 #define PTP_OC_SetDevicePropValue 0x1016 #define PTP_OC_ResetDevicePropValue 0x1017 #define PTP_OC_TerminateOpenCapture 0x1018 #define PTP_OC_MoveObject 0x1019 #define PTP_OC_CopyObject 0x101A #define PTP_OC_GetPartialObject 0x101B #define PTP_OC_InitiateOpenCapture 0x101C /* PTP v1.1 operation codes */ #define PTP_OC_StartEnumHandles 0x101D #define PTP_OC_EnumHandles 0x101E #define PTP_OC_StopEnumHandles 0x101F #define PTP_OC_GetVendorExtensionMaps 0x1020 #define PTP_OC_GetVendorDeviceInfo 0x1021 #define PTP_OC_GetResizedImageObject 0x1022 #define PTP_OC_GetFilesystemManifest 0x1023 #define PTP_OC_GetStreamInfo 0x1024 #define PTP_OC_GetStream 0x1025 /* Eastman Kodak extension Operation Codes */ #define PTP_OC_EK_GetSerial 0x9003 #define PTP_OC_EK_SetSerial 0x9004 #define PTP_OC_EK_SendFileObjectInfo 0x9005 #define PTP_OC_EK_SendFileObject 0x9006 #define PTP_OC_EK_SetText 0x9008 /* Canon extension Operation Codes */ #define PTP_OC_CANON_GetPartialObjectInfo 0x9001 /* 9002 - sends 2 uint32, nothing back */ #define PTP_OC_CANON_SetObjectArchive 0x9002 #define PTP_OC_CANON_KeepDeviceOn 0x9003 #define PTP_OC_CANON_LockDeviceUI 0x9004 #define PTP_OC_CANON_UnlockDeviceUI 0x9005 #define PTP_OC_CANON_GetObjectHandleByName 0x9006 /* no 9007 observed yet */ #define PTP_OC_CANON_InitiateReleaseControl 0x9008 #define PTP_OC_CANON_TerminateReleaseControl 0x9009 #define PTP_OC_CANON_TerminatePlaybackMode 0x900A #define PTP_OC_CANON_ViewfinderOn 0x900B #define PTP_OC_CANON_ViewfinderOff 0x900C #define PTP_OC_CANON_DoAeAfAwb 0x900D /* 900e - send nothing, gets 5 uint16t in 32bit entities back in 20byte datablob */ #define PTP_OC_CANON_GetCustomizeSpec 0x900E #define PTP_OC_CANON_GetCustomizeItemInfo 0x900F #define PTP_OC_CANON_GetCustomizeData 0x9010 #define PTP_OC_CANON_SetCustomizeData 0x9011 #define PTP_OC_CANON_GetCaptureStatus 0x9012 #define PTP_OC_CANON_CheckEvent 0x9013 #define PTP_OC_CANON_FocusLock 0x9014 #define PTP_OC_CANON_FocusUnlock 0x9015 #define PTP_OC_CANON_GetLocalReleaseParam 0x9016 #define PTP_OC_CANON_SetLocalReleaseParam 0x9017 #define PTP_OC_CANON_AskAboutPcEvf 0x9018 #define PTP_OC_CANON_SendPartialObject 0x9019 #define PTP_OC_CANON_InitiateCaptureInMemory 0x901A #define PTP_OC_CANON_GetPartialObjectEx 0x901B #define PTP_OC_CANON_SetObjectTime 0x901C #define PTP_OC_CANON_GetViewfinderImage 0x901D #define PTP_OC_CANON_GetObjectAttributes 0x901E #define PTP_OC_CANON_ChangeUSBProtocol 0x901F #define PTP_OC_CANON_GetChanges 0x9020 #define PTP_OC_CANON_GetObjectInfoEx 0x9021 #define PTP_OC_CANON_InitiateDirectTransfer 0x9022 #define PTP_OC_CANON_TerminateDirectTransfer 0x9023 #define PTP_OC_CANON_SendObjectInfoByPath 0x9024 #define PTP_OC_CANON_SendObjectByPath 0x9025 #define PTP_OC_CANON_InitiateDirectTansferEx 0x9026 #define PTP_OC_CANON_GetAncillaryObjectHandles 0x9027 #define PTP_OC_CANON_GetTreeInfo 0x9028 #define PTP_OC_CANON_GetTreeSize 0x9029 #define PTP_OC_CANON_NotifyProgress 0x902A #define PTP_OC_CANON_NotifyCancelAccepted 0x902B /* 902c: no parms, read 3 uint32 in data, no response parms */ #define PTP_OC_CANON_902C 0x902C #define PTP_OC_CANON_GetDirectory 0x902D #define PTP_OC_CANON_SetPairingInfo 0x9030 #define PTP_OC_CANON_GetPairingInfo 0x9031 #define PTP_OC_CANON_DeletePairingInfo 0x9032 #define PTP_OC_CANON_GetMACAddress 0x9033 /* 9034: 1 param, no parms returned */ #define PTP_OC_CANON_SetDisplayMonitor 0x9034 #define PTP_OC_CANON_PairingComplete 0x9035 #define PTP_OC_CANON_GetWirelessMAXChannel 0x9036 /* 9101: no args, 8 byte data (01 00 00 00 00 00 00 00), no resp data. */ #define PTP_OC_CANON_EOS_GetStorageIDs 0x9101 /* 9102: 1 arg (0) * 0x28 bytes of data: 00000000: 34 00 00 00 02 00 02 91 0a 00 00 00 04 00 03 00 00000010: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00000020: 00 00 ff ff ff ff 03 43 00 46 00 00 00 03 41 00 00000030: 3a 00 00 00 * no resp args */ #define PTP_OC_CANON_EOS_GetStorageInfo 0x9102 #define PTP_OC_CANON_EOS_GetObjectInfo 0x9103 #define PTP_OC_CANON_EOS_GetObject 0x9104 #define PTP_OC_CANON_EOS_DeleteObject 0x9105 #define PTP_OC_CANON_EOS_FormatStore 0x9106 #define PTP_OC_CANON_EOS_GetPartialObject 0x9107 #define PTP_OC_CANON_EOS_GetDeviceInfoEx 0x9108 /* sample1: * 3 cmdargs: 1,0xffffffff,00 00 10 00; * data: 00000000: 48 00 00 00 02 00 09 91 12 00 00 00 01 00 00 00 00000010: 38 00 00 00 00 00 00 30 01 00 00 00 01 30 00 00 00000020: 01 00 00 00 10 00 00 00 00 00 00 00 00 00 00 20 00000030: 00 00 00 30 44 43 49 4d 00 00 00 00 00 00 00 00 DCIM 00000040: 00 00 00 00 cc c3 01 46 * 2 respargs: 0x0, 0x3c * * sample2: * 00000000: 18 00 00 00 01 00 09 91 15 00 00 00 01 00 00 00 00000010: 00 00 00 30 00 00 10 00 00000000: 48 00 00 00 02 00 09 91 15 00 00 00 01 00 00 00 00000010: 38 00 00 00 00 00 9c 33 01 00 00 00 01 30 00 00 00000020: 01 00 00 00 10 00 00 00 00 00 00 00 00 00 00 30 00000030: 00 00 9c 33 32 33 31 43 41 4e 4f 4e 00 00 00 00 231CANON 00000040: 00 00 00 00 cc c3 01 46 */ #define PTP_OC_CANON_EOS_GetObjectInfoEx 0x9109 #define PTP_OC_CANON_EOS_GetThumbEx 0x910A #define PTP_OC_CANON_EOS_SendPartialObject 0x910B #define PTP_OC_CANON_EOS_SetObjectAttributes 0x910C #define PTP_OC_CANON_EOS_GetObjectTime 0x910D #define PTP_OC_CANON_EOS_SetObjectTime 0x910E /* 910f: no args, no data, 1 response arg (0). */ #define PTP_OC_CANON_EOS_RemoteRelease 0x910F /* Marcus: looks more like "Set DeviceProperty" in the trace. * * no cmd args * data phase (0xc, 0xd11c, 0x1) * no resp args */ #define PTP_OC_CANON_EOS_SetDevicePropValueEx 0x9110 #define PTP_OC_CANON_EOS_GetRemoteMode 0x9113 /* 9114: 1 arg (0x1), no data, no resp data. */ #define PTP_OC_CANON_EOS_SetRemoteMode 0x9114 /* 9115: 1 arg (0x1), no data, no resp data. */ #define PTP_OC_CANON_EOS_SetEventMode 0x9115 /* 9116: no args, data phase, no resp data. */ #define PTP_OC_CANON_EOS_GetEvent 0x9116 #define PTP_OC_CANON_EOS_TransferComplete 0x9117 #define PTP_OC_CANON_EOS_CancelTransfer 0x9118 #define PTP_OC_CANON_EOS_ResetTransfer 0x9119 /* 911a: 3 args (0xfffffff7, 0x00001000, 0x00000001), no data, no resp data. */ /* 911a: 3 args (0x001dfc60, 0x00001000, 0x00000001), no data, no resp data. */ #define PTP_OC_CANON_EOS_PCHDDCapacity 0x911A /* 911b: no cmd args, no data, no resp args */ #define PTP_OC_CANON_EOS_SetUILock 0x911B /* 911c: no cmd args, no data, no resp args */ #define PTP_OC_CANON_EOS_ResetUILock 0x911C #define PTP_OC_CANON_EOS_KeepDeviceOn 0x911D #define PTP_OC_CANON_EOS_SetNullPacketMode 0x911E #define PTP_OC_CANON_EOS_UpdateFirmware 0x911F #define PTP_OC_CANON_EOS_TransferCompleteDT 0x9120 #define PTP_OC_CANON_EOS_CancelTransferDT 0x9121 #define PTP_OC_CANON_EOS_SetWftProfile 0x9122 #define PTP_OC_CANON_EOS_GetWftProfile 0x9122 #define PTP_OC_CANON_EOS_SetProfileToWft 0x9124 #define PTP_OC_CANON_EOS_BulbStart 0x9125 #define PTP_OC_CANON_EOS_BulbEnd 0x9126 #define PTP_OC_CANON_EOS_RequestDevicePropValue 0x9127 /* 0x9128 args (0x1/0x2, 0x0), no data, no resp args */ #define PTP_OC_CANON_EOS_RemoteReleaseOn 0x9128 /* 0x9129 args (0x1/0x2), no data, no resp args */ #define PTP_OC_CANON_EOS_RemoteReleaseOff 0x9129 #define PTP_OC_CANON_EOS_InitiateViewfinder 0x9151 #define PTP_OC_CANON_EOS_TerminateViewfinder 0x9152 #define PTP_OC_CANON_EOS_GetViewFinderData 0x9153 #define PTP_OC_CANON_EOS_DoAf 0x9154 #define PTP_OC_CANON_EOS_DriveLens 0x9155 #define PTP_OC_CANON_EOS_DepthOfFieldPreview 0x9156 #define PTP_OC_CANON_EOS_ClickWB 0x9157 #define PTP_OC_CANON_EOS_Zoom 0x9158 #define PTP_OC_CANON_EOS_ZoomPosition 0x9159 #define PTP_OC_CANON_EOS_SetLiveAfFrame 0x915a #define PTP_OC_CANON_EOS_AfCancel 0x9160 #define PTP_OC_CANON_EOS_FAPIMessageTX 0x91FE #define PTP_OC_CANON_EOS_FAPIMessageRX 0x91FF /* Nikon extension Operation Codes */ #define PTP_OC_NIKON_GetProfileAllData 0x9006 #define PTP_OC_NIKON_SendProfileData 0x9007 #define PTP_OC_NIKON_DeleteProfile 0x9008 #define PTP_OC_NIKON_SetProfileData 0x9009 #define PTP_OC_NIKON_AdvancedTransfer 0x9010 #define PTP_OC_NIKON_GetFileInfoInBlock 0x9011 #define PTP_OC_NIKON_Capture 0x90C0 /* 1 param, no data */ #define PTP_OC_NIKON_AfDrive 0x90C1 /* no params, no data */ #define PTP_OC_NIKON_SetControlMode 0x90C2 /* 1 param, no data */ #define PTP_OC_NIKON_DelImageSDRAM 0x90C3 /* no params, no data */ #define PTP_OC_NIKON_GetLargeThumb 0x90C4 #define PTP_OC_NIKON_CurveDownload 0x90C5 /* 1 param, data in */ #define PTP_OC_NIKON_CurveUpload 0x90C6 /* 1 param, data out */ #define PTP_OC_NIKON_CheckEvent 0x90C7 /* no params, data in */ #define PTP_OC_NIKON_DeviceReady 0x90C8 /* no params, no data */ #define PTP_OC_NIKON_SetPreWBData 0x90C9 /* 3 params, data out */ #define PTP_OC_NIKON_GetVendorPropCodes 0x90CA /* 0 params, data in */ #define PTP_OC_NIKON_AfCaptureSDRAM 0x90CB /* no params, no data */ #define PTP_OC_NIKON_GetPictCtrlData 0x90CC #define PTP_OC_NIKON_SetPictCtrlData 0x90CD #define PTP_OC_NIKON_DelCstPicCtrl 0x90CE #define PTP_OC_NIKON_GetPicCtrlCapability 0x90CF /* Nikon Liveview stuff */ #define PTP_OC_NIKON_GetPreviewImg 0x9200 #define PTP_OC_NIKON_StartLiveView 0x9201 #define PTP_OC_NIKON_EndLiveView 0x9202 #define PTP_OC_NIKON_GetLiveViewImg 0x9203 #define PTP_OC_NIKON_MfDrive 0x9204 #define PTP_OC_NIKON_ChangeAfArea 0x9205 #define PTP_OC_NIKON_AfDriveCancel 0x9206 #define PTP_OC_NIKON_GetDevicePTPIPInfo 0x90E0 /* Casio EX-F1 (from http://code.google.com/p/exf1ctrl/ ) */ #define PTP_OC_CASIO_STILL_START 0x9001 #define PTP_OC_CASIO_STILL_STOP 0x9002 #define PTP_OC_CASIO_FOCUS 0x9007 #define PTP_OC_CASIO_CF_PRESS 0x9009 #define PTP_OC_CASIO_CF_RELEASE 0x900A #define PTP_OC_CASIO_GET_OBJECT_INFO 0x900C #define PTP_OC_CASIO_SHUTTER 0x9024 #define PTP_OC_CASIO_GET_STILL_HANDLES 0x9027 #define PTP_OC_CASIO_STILL_RESET 0x9028 #define PTP_OC_CASIO_HALF_PRESS 0x9029 #define PTP_OC_CASIO_HALF_RELEASE 0x902A #define PTP_OC_CASIO_CS_PRESS 0x902B #define PTP_OC_CASIO_CS_RELEASE 0x902C #define PTP_OC_CASIO_ZOOM 0x902D #define PTP_OC_CASIO_CZ_PRESS 0x902E #define PTP_OC_CASIO_CZ_RELEASE 0x902F #define PTP_OC_CASIO_MOVIE_START 0x9041 #define PTP_OC_CASIO_MOVIE_STOP 0x9042 #define PTP_OC_CASIO_MOVIE_PRESS 0x9043 #define PTP_OC_CASIO_MOVIE_RELEASE 0x9044 #define PTP_OC_CASIO_GET_MOVIE_HANDLES 0x9045 #define PTP_OC_CASIO_MOVIE_RESET 0x9046 #define PTP_OC_CASIO_GET_OBJECT 0x9025 #define PTP_OC_CASIO_GET_THUMBNAIL 0x9026 /* Microsoft / MTP extension codes */ #define PTP_OC_MTP_GetObjectPropsSupported 0x9801 #define PTP_OC_MTP_GetObjectPropDesc 0x9802 #define PTP_OC_MTP_GetObjectPropValue 0x9803 #define PTP_OC_MTP_SetObjectPropValue 0x9804 #define PTP_OC_MTP_GetObjPropList 0x9805 #define PTP_OC_MTP_SetObjPropList 0x9806 #define PTP_OC_MTP_GetInterdependendPropdesc 0x9807 #define PTP_OC_MTP_SendObjectPropList 0x9808 #define PTP_OC_MTP_GetObjectReferences 0x9810 #define PTP_OC_MTP_SetObjectReferences 0x9811 #define PTP_OC_MTP_UpdateDeviceFirmware 0x9812 #define PTP_OC_MTP_Skip 0x9820 /* * Windows Media Digital Rights Management for Portable Devices * Extension Codes (microsoft.com/WMDRMPD: 10.1) */ #define PTP_OC_MTP_WMDRMPD_GetSecureTimeChallenge 0x9101 #define PTP_OC_MTP_WMDRMPD_GetSecureTimeResponse 0x9102 #define PTP_OC_MTP_WMDRMPD_SetLicenseResponse 0x9103 #define PTP_OC_MTP_WMDRMPD_GetSyncList 0x9104 #define PTP_OC_MTP_WMDRMPD_SendMeterChallengeQuery 0x9105 #define PTP_OC_MTP_WMDRMPD_GetMeterChallenge 0x9106 #define PTP_OC_MTP_WMDRMPD_SetMeterResponse 0x9107 #define PTP_OC_MTP_WMDRMPD_CleanDataStore 0x9108 #define PTP_OC_MTP_WMDRMPD_GetLicenseState 0x9109 #define PTP_OC_MTP_WMDRMPD_SendWMDRMPDCommand 0x910A #define PTP_OC_MTP_WMDRMPD_SendWMDRMPDRequest 0x910B /* * Windows Media Digital Rights Management for Portable Devices * Extension Codes (microsoft.com/WMDRMPD: 10.1) * Below are operations that have no public documented identifier * associated with them "Vendor-defined Command Code" */ #define PTP_OC_MTP_WMDRMPD_SendWMDRMPDAppRequest 0x9212 #define PTP_OC_MTP_WMDRMPD_GetWMDRMPDAppResponse 0x9213 #define PTP_OC_MTP_WMDRMPD_EnableTrustedFilesOperations 0x9214 #define PTP_OC_MTP_WMDRMPD_DisableTrustedFilesOperations 0x9215 #define PTP_OC_MTP_WMDRMPD_EndTrustedAppSession 0x9216 /* ^^^ guess ^^^ */ /* * Microsoft Advanced Audio/Video Transfer * Extensions (microsoft.com/AAVT: 1.0) */ #define PTP_OC_MTP_AAVT_OpenMediaSession 0x9170 #define PTP_OC_MTP_AAVT_CloseMediaSession 0x9171 #define PTP_OC_MTP_AAVT_GetNextDataBlock 0x9172 #define PTP_OC_MTP_AAVT_SetCurrentTimePosition 0x9173 /* * Windows Media Digital Rights Management for Network Devices * Extensions (microsoft.com/WMDRMND: 1.0) MTP/IP? */ #define PTP_OC_MTP_WMDRMND_SendRegistrationRequest 0x9180 #define PTP_OC_MTP_WMDRMND_GetRegistrationResponse 0x9181 #define PTP_OC_MTP_WMDRMND_GetProximityChallenge 0x9182 #define PTP_OC_MTP_WMDRMND_SendProximityResponse 0x9183 #define PTP_OC_MTP_WMDRMND_SendWMDRMNDLicenseRequest 0x9184 #define PTP_OC_MTP_WMDRMND_GetWMDRMNDLicenseResponse 0x9185 /* * Windows Media Player Portiable Devices * Extension Codes (microsoft.com/WMPPD: 11.1) */ #define PTP_OC_MTP_WMPPD_ReportAddedDeletedItems 0x9201 #define PTP_OC_MTP_WMPPD_ReportAcquiredItems 0x9202 #define PTP_OC_MTP_WMPPD_PlaylistObjectPref 0x9203 /* * Undocumented Zune Operation Codes * maybe related to WMPPD extension set? */ #define PTP_OC_MTP_ZUNE_GETUNDEFINED001 0x9204 /* WiFi Provisioning MTP Extension Codes (microsoft.com/WPDWCN: 1.0) */ #define PTP_OC_MTP_WPDWCN_ProcessWFCObject 0x9122 /* Olympus E series commands */ #define PTP_OC_OLYMPUS_Capture 0x9101 #define PTP_OC_OLYMPUS_SelfCleaning 0x9103 #define PTP_OC_OLYMPUS_SetRGBGain 0x9106 #define PTP_OC_OLYMPUS_SetPresetMode 0x9107 #define PTP_OC_OLYMPUS_SetWBBiasAll 0x9108 #define PTP_OC_OLYMPUS_GetCameraControlMode 0x910a #define PTP_OC_OLYMPUS_SetCameraControlMode 0x910b #define PTP_OC_OLYMPUS_SetWBRGBGain 0x910c #define PTP_OC_OLYMPUS_GetDeviceInfo 0x9301 #define PTP_OC_OLYMPUS_Init1 0x9302 #define PTP_OC_OLYMPUS_SetDateTime 0x9402 #define PTP_OC_OLYMPUS_GetDateTime 0x9482 #define PTP_OC_OLYMPUS_SetCameraID 0x9501 #define PTP_OC_OLYMPUS_GetCameraID 0x9581 /* Android Random I/O Extensions Codes */ #define PTP_OC_ANDROID_GetPartialObject64 0x95C1 #define PTP_OC_ANDROID_SendPartialObject 0x95C2 #define PTP_OC_ANDROID_TruncateObject 0x95C3 #define PTP_OC_ANDROID_BeginEditObject 0x95C4 #define PTP_OC_ANDROID_EndEditObject 0x95C5 /* Proprietary vendor extension operations mask */ #define PTP_OC_EXTENSION_MASK 0xF000 #define PTP_OC_EXTENSION 0x9000 /* Response Codes */ /* PTP v1.0 response codes */ #define PTP_RC_Undefined 0x2000 #define PTP_RC_OK 0x2001 #define PTP_RC_GeneralError 0x2002 #define PTP_RC_SessionNotOpen 0x2003 #define PTP_RC_InvalidTransactionID 0x2004 #define PTP_RC_OperationNotSupported 0x2005 #define PTP_RC_ParameterNotSupported 0x2006 #define PTP_RC_IncompleteTransfer 0x2007 #define PTP_RC_InvalidStorageId 0x2008 #define PTP_RC_InvalidObjectHandle 0x2009 #define PTP_RC_DevicePropNotSupported 0x200A #define PTP_RC_InvalidObjectFormatCode 0x200B #define PTP_RC_StoreFull 0x200C #define PTP_RC_ObjectWriteProtected 0x200D #define PTP_RC_StoreReadOnly 0x200E #define PTP_RC_AccessDenied 0x200F #define PTP_RC_NoThumbnailPresent 0x2010 #define PTP_RC_SelfTestFailed 0x2011 #define PTP_RC_PartialDeletion 0x2012 #define PTP_RC_StoreNotAvailable 0x2013 #define PTP_RC_SpecificationByFormatUnsupported 0x2014 #define PTP_RC_NoValidObjectInfo 0x2015 #define PTP_RC_InvalidCodeFormat 0x2016 #define PTP_RC_UnknownVendorCode 0x2017 #define PTP_RC_CaptureAlreadyTerminated 0x2018 #define PTP_RC_DeviceBusy 0x2019 #define PTP_RC_InvalidParentObject 0x201A #define PTP_RC_InvalidDevicePropFormat 0x201B #define PTP_RC_InvalidDevicePropValue 0x201C #define PTP_RC_InvalidParameter 0x201D #define PTP_RC_SessionAlreadyOpened 0x201E #define PTP_RC_TransactionCanceled 0x201F #define PTP_RC_SpecificationOfDestinationUnsupported 0x2020 /* PTP v1.1 response codes */ #define PTP_RC_InvalidEnumHandle 0x2021 #define PTP_RC_NoStreamEnabled 0x2022 #define PTP_RC_InvalidDataSet 0x2023 /* Eastman Kodak extension Response Codes */ #define PTP_RC_EK_FilenameRequired 0xA001 #define PTP_RC_EK_FilenameConflicts 0xA002 #define PTP_RC_EK_FilenameInvalid 0xA003 /* Nikon specific response codes */ #define PTP_RC_NIKON_HardwareError 0xA001 #define PTP_RC_NIKON_OutOfFocus 0xA002 #define PTP_RC_NIKON_ChangeCameraModeFailed 0xA003 #define PTP_RC_NIKON_InvalidStatus 0xA004 #define PTP_RC_NIKON_SetPropertyNotSupported 0xA005 #define PTP_RC_NIKON_WbResetError 0xA006 #define PTP_RC_NIKON_DustReferenceError 0xA007 #define PTP_RC_NIKON_ShutterSpeedBulb 0xA008 #define PTP_RC_NIKON_MirrorUpSequence 0xA009 #define PTP_RC_NIKON_CameraModeNotAdjustFNumber 0xA00A #define PTP_RC_NIKON_NotLiveView 0xA00B #define PTP_RC_NIKON_MfDriveStepEnd 0xA00C #define PTP_RC_NIKON_MfDriveStepInsufficiency 0xA00E #define PTP_RC_NIKON_AdvancedTransferCancel 0xA022 /* Canon specific response codes */ #define PTP_RC_CANON_UNKNOWN_COMMAND 0xA001 #define PTP_RC_CANON_OPERATION_REFUSED 0xA005 #define PTP_RC_CANON_LENS_COVER 0xA006 #define PTP_RC_CANON_BATTERY_LOW 0xA101 #define PTP_RC_CANON_NOT_READY 0xA102 #define PTP_RC_CANON_A009 0xA009 /* Microsoft/MTP specific codes */ #define PTP_RC_MTP_Undefined 0xA800 #define PTP_RC_MTP_Invalid_ObjectPropCode 0xA801 #define PTP_RC_MTP_Invalid_ObjectProp_Format 0xA802 #define PTP_RC_MTP_Invalid_ObjectProp_Value 0xA803 #define PTP_RC_MTP_Invalid_ObjectReference 0xA804 #define PTP_RC_MTP_Invalid_Dataset 0xA806 #define PTP_RC_MTP_Specification_By_Group_Unsupported 0xA807 #define PTP_RC_MTP_Specification_By_Depth_Unsupported 0xA808 #define PTP_RC_MTP_Object_Too_Large 0xA809 #define PTP_RC_MTP_ObjectProp_Not_Supported 0xA80A /* Microsoft Advanced Audio/Video Transfer response codes (microsoft.com/AAVT 1.0) */ #define PTP_RC_MTP_Invalid_Media_Session_ID 0xA170 #define PTP_RC_MTP_Media_Session_Limit_Reached 0xA171 #define PTP_RC_MTP_No_More_Data 0xA172 /* WiFi Provisioning MTP Extension Error Codes (microsoft.com/WPDWCN: 1.0) */ #define PTP_RC_MTP_Invalid_WFC_Syntax 0xA121 #define PTP_RC_MTP_WFC_Version_Not_Supported 0xA122 /* libptp2 extended ERROR codes */ #define PTP_ERROR_IO 0x02FF #define PTP_ERROR_DATA_EXPECTED 0x02FE #define PTP_ERROR_RESP_EXPECTED 0x02FD #define PTP_ERROR_BADPARAM 0x02FC #define PTP_ERROR_CANCEL 0x02FB #define PTP_ERROR_TIMEOUT 0x02FA /* PTP Event Codes */ #define PTP_EC_Undefined 0x4000 #define PTP_EC_CancelTransaction 0x4001 #define PTP_EC_ObjectAdded 0x4002 #define PTP_EC_ObjectRemoved 0x4003 #define PTP_EC_StoreAdded 0x4004 #define PTP_EC_StoreRemoved 0x4005 #define PTP_EC_DevicePropChanged 0x4006 #define PTP_EC_ObjectInfoChanged 0x4007 #define PTP_EC_DeviceInfoChanged 0x4008 #define PTP_EC_RequestObjectTransfer 0x4009 #define PTP_EC_StoreFull 0x400A #define PTP_EC_DeviceReset 0x400B #define PTP_EC_StorageInfoChanged 0x400C #define PTP_EC_CaptureComplete 0x400D #define PTP_EC_UnreportedStatus 0x400E /* Canon extension Event Codes */ #define PTP_EC_CANON_ExtendedErrorcode 0xC005 /* ? */ #define PTP_EC_CANON_ObjectInfoChanged 0xC008 #define PTP_EC_CANON_RequestObjectTransfer 0xC009 #define PTP_EC_CANON_ShutterButtonPressed0 0xC00B #define PTP_EC_CANON_CameraModeChanged 0xC00C #define PTP_EC_CANON_ShutterButtonPressed1 0xC00E #define PTP_EC_CANON_StartDirectTransfer 0xC011 #define PTP_EC_CANON_StopDirectTransfer 0xC013 /* Canon EOS events */ #define PTP_EC_CANON_EOS_RequestGetEvent 0xc101 #define PTP_EC_CANON_EOS_ObjectAddedEx 0xc181 #define PTP_EC_CANON_EOS_ObjectRemoved 0xc182 #define PTP_EC_CANON_EOS_RequestGetObjectInfoEx 0xc183 #define PTP_EC_CANON_EOS_StorageStatusChanged 0xc184 #define PTP_EC_CANON_EOS_StorageInfoChanged 0xc185 #define PTP_EC_CANON_EOS_RequestObjectTransfer 0xc186 #define PTP_EC_CANON_EOS_ObjectInfoChangedEx 0xc187 #define PTP_EC_CANON_EOS_ObjectContentChanged 0xc188 #define PTP_EC_CANON_EOS_PropValueChanged 0xc189 #define PTP_EC_CANON_EOS_AvailListChanged 0xc18a #define PTP_EC_CANON_EOS_CameraStatusChanged 0xc18b #define PTP_EC_CANON_EOS_WillSoonShutdown 0xc18d #define PTP_EC_CANON_EOS_ShutdownTimerUpdated 0xc18e #define PTP_EC_CANON_EOS_RequestCancelTransfer 0xc18f #define PTP_EC_CANON_EOS_RequestObjectTransferDT 0xc190 #define PTP_EC_CANON_EOS_RequestCancelTransferDT 0xc191 #define PTP_EC_CANON_EOS_StoreAdded 0xc192 #define PTP_EC_CANON_EOS_StoreRemoved 0xc193 #define PTP_EC_CANON_EOS_BulbExposureTime 0xc194 #define PTP_EC_CANON_EOS_RecordingTime 0xc195 #define PTP_EC_CANON_EOS_RequestObjectTransferTS 0xC1a2 #define PTP_EC_CANON_EOS_AfResult 0xc1a3 /* Nikon extension Event Codes */ /* Nikon extension Event Codes */ #define PTP_EC_Nikon_ObjectAddedInSDRAM 0xC101 #define PTP_EC_Nikon_CaptureCompleteRecInSdram 0xC102 /* Gets 1 parameter, objectid pointing to DPOF object */ #define PTP_EC_Nikon_AdvancedTransfer 0xC103 #define PTP_EC_Nikon_PreviewImageAdded 0xC104 /* Olympus E series */ #define PTP_EC_Olympus_PropertyChanged 0xC102 #define PTP_EC_Olympus_CaptureComplete 0xC103 /* MTP Event codes */ #define PTP_EC_MTP_ObjectPropChanged 0xC801 #define PTP_EC_MTP_ObjectPropDescChanged 0xC802 #define PTP_EC_MTP_ObjectReferencesChanged 0xC803 /* constants for GetObjectHandles */ #define PTP_GOH_ALL_STORAGE 0xffffffff #define PTP_GOH_ALL_FORMATS 0x00000000 #define PTP_GOH_ALL_ASSOCS 0x00000000 #define PTP_GOH_ROOT_PARENT 0xffffffff /* PTP device info structure (returned by GetDevInfo) */ struct _PTPDeviceInfo { uint16_t StandardVersion; uint32_t VendorExtensionID; uint16_t VendorExtensionVersion; char *VendorExtensionDesc; uint16_t FunctionalMode; uint32_t OperationsSupported_len; uint16_t *OperationsSupported; uint32_t EventsSupported_len; uint16_t *EventsSupported; uint32_t DevicePropertiesSupported_len; uint16_t *DevicePropertiesSupported; uint32_t CaptureFormats_len; uint16_t *CaptureFormats; uint32_t ImageFormats_len; uint16_t *ImageFormats; char *Manufacturer; char *Model; char *DeviceVersion; char *SerialNumber; }; typedef struct _PTPDeviceInfo PTPDeviceInfo; /* PTP storageIDs structute (returned by GetStorageIDs) */ struct _PTPStorageIDs { uint32_t n; uint32_t *Storage; }; typedef struct _PTPStorageIDs PTPStorageIDs; /* PTP StorageInfo structure (returned by GetStorageInfo) */ struct _PTPStorageInfo { uint16_t StorageType; uint16_t FilesystemType; uint16_t AccessCapability; uint64_t MaxCapability; uint64_t FreeSpaceInBytes; uint32_t FreeSpaceInImages; char *StorageDescription; char *VolumeLabel; }; typedef struct _PTPStorageInfo PTPStorageInfo; /* PTP objecthandles structure (returned by GetObjectHandles) */ struct _PTPObjectHandles { uint32_t n; uint32_t *Handler; }; typedef struct _PTPObjectHandles PTPObjectHandles; #define PTP_HANDLER_SPECIAL 0xffffffff #define PTP_HANDLER_ROOT 0x00000000 /* PTP objectinfo structure (returned by GetObjectInfo) */ struct _PTPObjectInfo { uint32_t StorageID; uint16_t ObjectFormat; uint16_t ProtectionStatus; /* In the regular objectinfo this is 32bit, * but we keep the general object size here * that also arrives via other methods and so * use 64bit */ uint64_t ObjectCompressedSize; uint16_t ThumbFormat; uint32_t ThumbCompressedSize; uint32_t ThumbPixWidth; uint32_t ThumbPixHeight; uint32_t ImagePixWidth; uint32_t ImagePixHeight; uint32_t ImageBitDepth; uint32_t ParentObject; uint16_t AssociationType; uint32_t AssociationDesc; uint32_t SequenceNumber; char *Filename; time_t CaptureDate; time_t ModificationDate; char *Keywords; }; typedef struct _PTPObjectInfo PTPObjectInfo; /* max ptp string length INCLUDING terminating null character */ #define PTP_MAXSTRLEN 255 /* PTP Object Format Codes */ /* ancillary formats */ #define PTP_OFC_Undefined 0x3000 #define PTP_OFC_Defined 0x3800 #define PTP_OFC_Association 0x3001 #define PTP_OFC_Script 0x3002 #define PTP_OFC_Executable 0x3003 #define PTP_OFC_Text 0x3004 #define PTP_OFC_HTML 0x3005 #define PTP_OFC_DPOF 0x3006 #define PTP_OFC_AIFF 0x3007 #define PTP_OFC_WAV 0x3008 #define PTP_OFC_MP3 0x3009 #define PTP_OFC_AVI 0x300A #define PTP_OFC_MPEG 0x300B #define PTP_OFC_ASF 0x300C #define PTP_OFC_QT 0x300D /* guessing */ /* image formats */ #define PTP_OFC_EXIF_JPEG 0x3801 #define PTP_OFC_TIFF_EP 0x3802 #define PTP_OFC_FlashPix 0x3803 #define PTP_OFC_BMP 0x3804 #define PTP_OFC_CIFF 0x3805 #define PTP_OFC_Undefined_0x3806 0x3806 #define PTP_OFC_GIF 0x3807 #define PTP_OFC_JFIF 0x3808 #define PTP_OFC_PCD 0x3809 #define PTP_OFC_PICT 0x380A #define PTP_OFC_PNG 0x380B #define PTP_OFC_Undefined_0x380C 0x380C #define PTP_OFC_TIFF 0x380D #define PTP_OFC_TIFF_IT 0x380E #define PTP_OFC_JP2 0x380F #define PTP_OFC_JPX 0x3810 /* ptp v1.1 has only DNG new */ #define PTP_OFC_DNG 0x3811 /* Eastman Kodak extension ancillary format */ #define PTP_OFC_EK_M3U 0xb002 /* Canon extension */ #define PTP_OFC_CANON_CRW 0xb101 #define PTP_OFC_CANON_CRW3 0xb103 #define PTP_OFC_CANON_MOV 0xb104 #define PTP_OFC_CANON_MOV2 0xb105 /* CHDK specific raw mode */ #define PTP_OFC_CANON_CHDK_CRW 0xb1ff /* MTP extensions */ #define PTP_OFC_MTP_MediaCard 0xb211 #define PTP_OFC_MTP_MediaCardGroup 0xb212 #define PTP_OFC_MTP_Encounter 0xb213 #define PTP_OFC_MTP_EncounterBox 0xb214 #define PTP_OFC_MTP_M4A 0xb215 #define PTP_OFC_MTP_ZUNEUNDEFINED 0xb217 /* Unknown file type */ #define PTP_OFC_MTP_Firmware 0xb802 #define PTP_OFC_MTP_WindowsImageFormat 0xb881 #define PTP_OFC_MTP_UndefinedAudio 0xb900 #define PTP_OFC_MTP_WMA 0xb901 #define PTP_OFC_MTP_OGG 0xb902 #define PTP_OFC_MTP_AAC 0xb903 #define PTP_OFC_MTP_AudibleCodec 0xb904 #define PTP_OFC_MTP_FLAC 0xb906 #define PTP_OFC_MTP_SamsungPlaylist 0xb909 #define PTP_OFC_MTP_UndefinedVideo 0xb980 #define PTP_OFC_MTP_WMV 0xb981 #define PTP_OFC_MTP_MP4 0xb982 #define PTP_OFC_MTP_MP2 0xb983 #define PTP_OFC_MTP_3GP 0xb984 #define PTP_OFC_MTP_UndefinedCollection 0xba00 #define PTP_OFC_MTP_AbstractMultimediaAlbum 0xba01 #define PTP_OFC_MTP_AbstractImageAlbum 0xba02 #define PTP_OFC_MTP_AbstractAudioAlbum 0xba03 #define PTP_OFC_MTP_AbstractVideoAlbum 0xba04 #define PTP_OFC_MTP_AbstractAudioVideoPlaylist 0xba05 #define PTP_OFC_MTP_AbstractContactGroup 0xba06 #define PTP_OFC_MTP_AbstractMessageFolder 0xba07 #define PTP_OFC_MTP_AbstractChapteredProduction 0xba08 #define PTP_OFC_MTP_AbstractAudioPlaylist 0xba09 #define PTP_OFC_MTP_AbstractVideoPlaylist 0xba0a #define PTP_OFC_MTP_AbstractMediacast 0xba0b #define PTP_OFC_MTP_WPLPlaylist 0xba10 #define PTP_OFC_MTP_M3UPlaylist 0xba11 #define PTP_OFC_MTP_MPLPlaylist 0xba12 #define PTP_OFC_MTP_ASXPlaylist 0xba13 #define PTP_OFC_MTP_PLSPlaylist 0xba14 #define PTP_OFC_MTP_UndefinedDocument 0xba80 #define PTP_OFC_MTP_AbstractDocument 0xba81 #define PTP_OFC_MTP_XMLDocument 0xba82 #define PTP_OFC_MTP_MSWordDocument 0xba83 #define PTP_OFC_MTP_MHTCompiledHTMLDocument 0xba84 #define PTP_OFC_MTP_MSExcelSpreadsheetXLS 0xba85 #define PTP_OFC_MTP_MSPowerpointPresentationPPT 0xba86 #define PTP_OFC_MTP_UndefinedMessage 0xbb00 #define PTP_OFC_MTP_AbstractMessage 0xbb01 #define PTP_OFC_MTP_UndefinedContact 0xbb80 #define PTP_OFC_MTP_AbstractContact 0xbb81 #define PTP_OFC_MTP_vCard2 0xbb82 #define PTP_OFC_MTP_vCard3 0xbb83 #define PTP_OFC_MTP_UndefinedCalendarItem 0xbe00 #define PTP_OFC_MTP_AbstractCalendarItem 0xbe01 #define PTP_OFC_MTP_vCalendar1 0xbe02 #define PTP_OFC_MTP_vCalendar2 0xbe03 #define PTP_OFC_MTP_UndefinedWindowsExecutable 0xbe80 #define PTP_OFC_MTP_MediaCast 0xbe81 #define PTP_OFC_MTP_Section 0xbe82 /* PTP Association Types */ #define PTP_AT_Undefined 0x0000 #define PTP_AT_GenericFolder 0x0001 #define PTP_AT_Album 0x0002 #define PTP_AT_TimeSequence 0x0003 #define PTP_AT_HorizontalPanoramic 0x0004 #define PTP_AT_VerticalPanoramic 0x0005 #define PTP_AT_2DPanoramic 0x0006 #define PTP_AT_AncillaryData 0x0007 /* PTP Protection Status */ #define PTP_PS_NoProtection 0x0000 #define PTP_PS_ReadOnly 0x0001 #define PTP_PS_MTP_ReadOnlyData 0x8002 #define PTP_PS_MTP_NonTransferableData 0x8003 /* PTP Storage Types */ #define PTP_ST_Undefined 0x0000 #define PTP_ST_FixedROM 0x0001 #define PTP_ST_RemovableROM 0x0002 #define PTP_ST_FixedRAM 0x0003 #define PTP_ST_RemovableRAM 0x0004 /* PTP FilesystemType Values */ #define PTP_FST_Undefined 0x0000 #define PTP_FST_GenericFlat 0x0001 #define PTP_FST_GenericHierarchical 0x0002 #define PTP_FST_DCF 0x0003 /* PTP StorageInfo AccessCapability Values */ #define PTP_AC_ReadWrite 0x0000 #define PTP_AC_ReadOnly 0x0001 #define PTP_AC_ReadOnly_with_Object_Deletion 0x0002 /* Property Describing Dataset, Range Form */ union _PTPPropertyValue { char *str; /* common string, malloced */ uint8_t u8; int8_t i8; uint16_t u16; int16_t i16; uint32_t u32; int32_t i32; uint64_t u64; int64_t i64; /* XXXX: 128 bit signed and unsigned missing */ struct array { uint32_t count; union _PTPPropertyValue *v; /* malloced, count elements */ } a; }; typedef union _PTPPropertyValue PTPPropertyValue; /* Metadata lists for MTP operations */ struct _MTPProperties { uint16_t property; uint16_t datatype; uint32_t ObjectHandle; PTPPropertyValue propval; }; typedef struct _MTPProperties MTPProperties; struct _PTPPropDescRangeForm { PTPPropertyValue MinimumValue; PTPPropertyValue MaximumValue; PTPPropertyValue StepSize; }; typedef struct _PTPPropDescRangeForm PTPPropDescRangeForm; /* Property Describing Dataset, Enum Form */ struct _PTPPropDescEnumForm { uint16_t NumberOfValues; PTPPropertyValue *SupportedValue; /* malloced */ }; typedef struct _PTPPropDescEnumForm PTPPropDescEnumForm; /* Device Property Describing Dataset (DevicePropDesc) */ struct _PTPDevicePropDesc { uint16_t DevicePropertyCode; uint16_t DataType; uint8_t GetSet; PTPPropertyValue FactoryDefaultValue; PTPPropertyValue CurrentValue; uint8_t FormFlag; union { PTPPropDescEnumForm Enum; PTPPropDescRangeForm Range; } FORM; }; typedef struct _PTPDevicePropDesc PTPDevicePropDesc; /* Object Property Describing Dataset (DevicePropDesc) */ struct _PTPObjectPropDesc { uint16_t ObjectPropertyCode; uint16_t DataType; uint8_t GetSet; PTPPropertyValue FactoryDefaultValue; uint32_t GroupCode; uint8_t FormFlag; union { PTPPropDescEnumForm Enum; PTPPropDescRangeForm Range; } FORM; }; typedef struct _PTPObjectPropDesc PTPObjectPropDesc; /* Canon filesystem's folder entry Dataset */ #define PTP_CANON_FilenameBufferLen 13 #define PTP_CANON_FolderEntryLen 28 struct _PTPCANONFolderEntry { uint32_t ObjectHandle; uint16_t ObjectFormatCode; uint8_t Flags; uint32_t ObjectSize; time_t Time; char Filename[PTP_CANON_FilenameBufferLen]; uint32_t StorageID; }; typedef struct _PTPCANONFolderEntry PTPCANONFolderEntry; /* Nikon Tone Curve Data */ #define PTP_NIKON_MaxCurvePoints 19 struct _PTPNIKONCoordinatePair { uint8_t X; uint8_t Y; }; typedef struct _PTPNIKONCoordinatePair PTPNIKONCoordinatePair; struct _PTPNTCCoordinatePair { uint8_t X; uint8_t Y; }; typedef struct _PTPNTCCoordinatePair PTPNTCCoordinatePair; struct _PTPNIKONCurveData { char static_preamble[6]; uint8_t XAxisStartPoint; uint8_t XAxisEndPoint; uint8_t YAxisStartPoint; uint8_t YAxisEndPoint; uint8_t MidPointIntegerPart; uint8_t MidPointDecimalPart; uint8_t NCoordinates; PTPNIKONCoordinatePair CurveCoordinates[PTP_NIKON_MaxCurvePoints]; }; typedef struct _PTPNIKONCurveData PTPNIKONCurveData; struct _PTPEKTextParams { char *title; char *line[5]; }; typedef struct _PTPEKTextParams PTPEKTextParams; /* Nikon Wifi profiles */ struct _PTPNIKONWifiProfile { /* Values valid both when reading and writing profiles */ char profile_name[17]; uint8_t device_type; uint8_t icon_type; char essid[33]; /* Values only valid when reading. Some of these are in the write packet, * but are set automatically, like id, display_order and creation_date. */ uint8_t id; uint8_t valid; uint8_t display_order; char creation_date[16]; char lastusage_date[16]; /* Values only valid when writing */ uint32_t ip_address; uint8_t subnet_mask; /* first zero bit position, e.g. 24 for 255.255.255.0 */ uint32_t gateway_address; uint8_t address_mode; /* 0 - Manual, 2-3 - DHCP ad-hoc/managed*/ uint8_t access_mode; /* 0 - Managed, 1 - Adhoc */ uint8_t wifi_channel; /* 1-11 */ uint8_t authentification; /* 0 - Open, 1 - Shared, 2 - WPA-PSK */ uint8_t encryption; /* 0 - None, 1 - WEP 64bit, 2 - WEP 128bit (not supported: 3 - TKIP) */ uint8_t key[64]; uint8_t key_nr; /* char guid[16]; */ }; typedef struct _PTPNIKONWifiProfile PTPNIKONWifiProfile; #define PTP_CANON_EOS_CHANGES_TYPE_UNKNOWN 0 #define PTP_CANON_EOS_CHANGES_TYPE_OBJECTINFO 1 #define PTP_CANON_EOS_CHANGES_TYPE_OBJECTTRANSFER 2 #define PTP_CANON_EOS_CHANGES_TYPE_PROPERTY 3 #define PTP_CANON_EOS_CHANGES_TYPE_CAMERASTATUS 4 struct _PTPCanon_New_Object { uint32_t oid; PTPObjectInfo oi; }; struct _PTPCanon_changes_entry { int type; union { struct _PTPCanon_New_Object object; /* TYPE_OBJECTINFO */ char *info; uint16_t propid; int status; } u; }; typedef struct _PTPCanon_changes_entry PTPCanon_changes_entry; typedef struct _PTPCanon_Property { uint32_t size; uint32_t type; uint32_t proptype; unsigned char *data; /* fill out for queries */ PTPDevicePropDesc dpd; } PTPCanon_Property; typedef struct _PTPCanonEOSDeviceInfo { /* length */ uint32_t EventsSupported_len; uint32_t *EventsSupported; uint32_t DevicePropertiesSupported_len; uint32_t *DevicePropertiesSupported; uint32_t unk_len; uint32_t *unk; } PTPCanonEOSDeviceInfo; /* DataType Codes */ #define PTP_DTC_UNDEF 0x0000 #define PTP_DTC_INT8 0x0001 #define PTP_DTC_UINT8 0x0002 #define PTP_DTC_INT16 0x0003 #define PTP_DTC_UINT16 0x0004 #define PTP_DTC_INT32 0x0005 #define PTP_DTC_UINT32 0x0006 #define PTP_DTC_INT64 0x0007 #define PTP_DTC_UINT64 0x0008 #define PTP_DTC_INT128 0x0009 #define PTP_DTC_UINT128 0x000A #define PTP_DTC_ARRAY_MASK 0x4000 #define PTP_DTC_AINT8 (PTP_DTC_ARRAY_MASK | PTP_DTC_INT8) #define PTP_DTC_AUINT8 (PTP_DTC_ARRAY_MASK | PTP_DTC_UINT8) #define PTP_DTC_AINT16 (PTP_DTC_ARRAY_MASK | PTP_DTC_INT16) #define PTP_DTC_AUINT16 (PTP_DTC_ARRAY_MASK | PTP_DTC_UINT16) #define PTP_DTC_AINT32 (PTP_DTC_ARRAY_MASK | PTP_DTC_INT32) #define PTP_DTC_AUINT32 (PTP_DTC_ARRAY_MASK | PTP_DTC_UINT32) #define PTP_DTC_AINT64 (PTP_DTC_ARRAY_MASK | PTP_DTC_INT64) #define PTP_DTC_AUINT64 (PTP_DTC_ARRAY_MASK | PTP_DTC_UINT64) #define PTP_DTC_AINT128 (PTP_DTC_ARRAY_MASK | PTP_DTC_INT128) #define PTP_DTC_AUINT128 (PTP_DTC_ARRAY_MASK | PTP_DTC_UINT128) #define PTP_DTC_STR 0xFFFF /* Device Properties Codes */ /* PTP v1.0 property codes */ #define PTP_DPC_Undefined 0x5000 #define PTP_DPC_BatteryLevel 0x5001 #define PTP_DPC_FunctionalMode 0x5002 #define PTP_DPC_ImageSize 0x5003 #define PTP_DPC_CompressionSetting 0x5004 #define PTP_DPC_WhiteBalance 0x5005 #define PTP_DPC_RGBGain 0x5006 #define PTP_DPC_FNumber 0x5007 #define PTP_DPC_FocalLength 0x5008 #define PTP_DPC_FocusDistance 0x5009 #define PTP_DPC_FocusMode 0x500A #define PTP_DPC_ExposureMeteringMode 0x500B #define PTP_DPC_FlashMode 0x500C #define PTP_DPC_ExposureTime 0x500D #define PTP_DPC_ExposureProgramMode 0x500E #define PTP_DPC_ExposureIndex 0x500F #define PTP_DPC_ExposureBiasCompensation 0x5010 #define PTP_DPC_DateTime 0x5011 #define PTP_DPC_CaptureDelay 0x5012 #define PTP_DPC_StillCaptureMode 0x5013 #define PTP_DPC_Contrast 0x5014 #define PTP_DPC_Sharpness 0x5015 #define PTP_DPC_DigitalZoom 0x5016 #define PTP_DPC_EffectMode 0x5017 #define PTP_DPC_BurstNumber 0x5018 #define PTP_DPC_BurstInterval 0x5019 #define PTP_DPC_TimelapseNumber 0x501A #define PTP_DPC_TimelapseInterval 0x501B #define PTP_DPC_FocusMeteringMode 0x501C #define PTP_DPC_UploadURL 0x501D #define PTP_DPC_Artist 0x501E #define PTP_DPC_CopyrightInfo 0x501F /* PTP v1.1 property codes */ #define PTP_DPC_SupportedStreams 0x5020 #define PTP_DPC_EnabledStreams 0x5021 #define PTP_DPC_VideoFormat 0x5022 #define PTP_DPC_VideoResolution 0x5023 #define PTP_DPC_VideoQuality 0x5024 #define PTP_DPC_VideoFrameRate 0x5025 #define PTP_DPC_VideoContrast 0x5026 #define PTP_DPC_VideoBrightness 0x5027 #define PTP_DPC_AudioFormat 0x5028 #define PTP_DPC_AudioBitrate 0x5029 #define PTP_DPC_AudioSamplingRate 0x502A #define PTP_DPC_AudioBitPerSample 0x502B #define PTP_DPC_AudioVolume 0x502C /* Proprietary vendor extension device property mask */ #define PTP_DPC_EXTENSION_MASK 0xF000 #define PTP_DPC_EXTENSION 0xD000 /* Zune extension device property codes */ #define PTP_DPC_MTP_ZUNE_UNKNOWN1 0xD181 #define PTP_DPC_MTP_ZUNE_UNKNOWN2 0xD132 #define PTP_DPC_MTP_ZUNE_UNKNOWN3 0xD215 #define PTP_DPC_MTP_ZUNE_UNKNOWN4 0xD216 /* Eastman Kodak extension device property codes */ #define PTP_DPC_EK_ColorTemperature 0xD001 #define PTP_DPC_EK_DateTimeStampFormat 0xD002 #define PTP_DPC_EK_BeepMode 0xD003 #define PTP_DPC_EK_VideoOut 0xD004 #define PTP_DPC_EK_PowerSaving 0xD005 #define PTP_DPC_EK_UI_Language 0xD006 /* Canon extension device property codes */ #define PTP_DPC_CANON_BeepMode 0xD001 #define PTP_DPC_CANON_BatteryKind 0xD002 #define PTP_DPC_CANON_BatteryStatus 0xD003 #define PTP_DPC_CANON_UILockType 0xD004 #define PTP_DPC_CANON_CameraMode 0xD005 #define PTP_DPC_CANON_ImageQuality 0xD006 #define PTP_DPC_CANON_FullViewFileFormat 0xD007 #define PTP_DPC_CANON_ImageSize 0xD008 #define PTP_DPC_CANON_SelfTime 0xD009 #define PTP_DPC_CANON_FlashMode 0xD00A #define PTP_DPC_CANON_Beep 0xD00B #define PTP_DPC_CANON_ShootingMode 0xD00C #define PTP_DPC_CANON_ImageMode 0xD00D #define PTP_DPC_CANON_DriveMode 0xD00E #define PTP_DPC_CANON_EZoom 0xD00F #define PTP_DPC_CANON_MeteringMode 0xD010 #define PTP_DPC_CANON_AFDistance 0xD011 #define PTP_DPC_CANON_FocusingPoint 0xD012 #define PTP_DPC_CANON_WhiteBalance 0xD013 #define PTP_DPC_CANON_SlowShutterSetting 0xD014 #define PTP_DPC_CANON_AFMode 0xD015 #define PTP_DPC_CANON_ImageStabilization 0xD016 #define PTP_DPC_CANON_Contrast 0xD017 #define PTP_DPC_CANON_ColorGain 0xD018 #define PTP_DPC_CANON_Sharpness 0xD019 #define PTP_DPC_CANON_Sensitivity 0xD01A #define PTP_DPC_CANON_ParameterSet 0xD01B #define PTP_DPC_CANON_ISOSpeed 0xD01C #define PTP_DPC_CANON_Aperture 0xD01D #define PTP_DPC_CANON_ShutterSpeed 0xD01E #define PTP_DPC_CANON_ExpCompensation 0xD01F #define PTP_DPC_CANON_FlashCompensation 0xD020 #define PTP_DPC_CANON_AEBExposureCompensation 0xD021 #define PTP_DPC_CANON_AvOpen 0xD023 #define PTP_DPC_CANON_AvMax 0xD024 #define PTP_DPC_CANON_FocalLength 0xD025 #define PTP_DPC_CANON_FocalLengthTele 0xD026 #define PTP_DPC_CANON_FocalLengthWide 0xD027 #define PTP_DPC_CANON_FocalLengthDenominator 0xD028 #define PTP_DPC_CANON_CaptureTransferMode 0xD029 #define CANON_TRANSFER_ENTIRE_IMAGE_TO_PC 0x0002 #define CANON_TRANSFER_SAVE_THUMBNAIL_TO_DEVICE 0x0004 #define CANON_TRANSFER_SAVE_IMAGE_TO_DEVICE 0x0008 /* we use those values: */ #define CANON_TRANSFER_MEMORY (2|1) #define CANON_TRANSFER_CARD (8|4|1) #define PTP_DPC_CANON_Zoom 0xD02A #define PTP_DPC_CANON_NamePrefix 0xD02B #define PTP_DPC_CANON_SizeQualityMode 0xD02C #define PTP_DPC_CANON_SupportedThumbSize 0xD02D #define PTP_DPC_CANON_SizeOfOutputDataFromCamera 0xD02E #define PTP_DPC_CANON_SizeOfInputDataToCamera 0xD02F #define PTP_DPC_CANON_RemoteAPIVersion 0xD030 #define PTP_DPC_CANON_FirmwareVersion 0xD031 #define PTP_DPC_CANON_CameraModel 0xD032 #define PTP_DPC_CANON_CameraOwner 0xD033 #define PTP_DPC_CANON_UnixTime 0xD034 #define PTP_DPC_CANON_CameraBodyID 0xD035 #define PTP_DPC_CANON_CameraOutput 0xD036 #define PTP_DPC_CANON_DispAv 0xD037 #define PTP_DPC_CANON_AvOpenApex 0xD038 #define PTP_DPC_CANON_DZoomMagnification 0xD039 #define PTP_DPC_CANON_MlSpotPos 0xD03A #define PTP_DPC_CANON_DispAvMax 0xD03B #define PTP_DPC_CANON_AvMaxApex 0xD03C #define PTP_DPC_CANON_EZoomStartPosition 0xD03D #define PTP_DPC_CANON_FocalLengthOfTele 0xD03E #define PTP_DPC_CANON_EZoomSizeOfTele 0xD03F #define PTP_DPC_CANON_PhotoEffect 0xD040 #define PTP_DPC_CANON_AssistLight 0xD041 #define PTP_DPC_CANON_FlashQuantityCount 0xD042 #define PTP_DPC_CANON_RotationAngle 0xD043 #define PTP_DPC_CANON_RotationScene 0xD044 #define PTP_DPC_CANON_EventEmulateMode 0xD045 #define PTP_DPC_CANON_DPOFVersion 0xD046 #define PTP_DPC_CANON_TypeOfSupportedSlideShow 0xD047 #define PTP_DPC_CANON_AverageFilesizes 0xD048 #define PTP_DPC_CANON_ModelID 0xD049 /* From EOS 400D trace. */ #define PTP_DPC_CANON_EOS_Aperture 0xD101 #define PTP_DPC_CANON_EOS_ShutterSpeed 0xD102 #define PTP_DPC_CANON_EOS_ISOSpeed 0xD103 #define PTP_DPC_CANON_EOS_ExpCompensation 0xD104 #define PTP_DPC_CANON_EOS_AutoExposureMode 0xD105 #define PTP_DPC_CANON_EOS_DriveMode 0xD106 #define PTP_DPC_CANON_EOS_MeteringMode 0xD107 #define PTP_DPC_CANON_EOS_FocusMode 0xD108 #define PTP_DPC_CANON_EOS_WhiteBalance 0xD109 #define PTP_DPC_CANON_EOS_ColorTemperature 0xD10A #define PTP_DPC_CANON_EOS_WhiteBalanceAdjustA 0xD10B #define PTP_DPC_CANON_EOS_WhiteBalanceAdjustB 0xD10C #define PTP_DPC_CANON_EOS_WhiteBalanceXA 0xD10D #define PTP_DPC_CANON_EOS_WhiteBalanceXB 0xD10E #define PTP_DPC_CANON_EOS_ColorSpace 0xD10F #define PTP_DPC_CANON_EOS_PictureStyle 0xD110 #define PTP_DPC_CANON_EOS_BatteryPower 0xD111 #define PTP_DPC_CANON_EOS_BatterySelect 0xD112 #define PTP_DPC_CANON_EOS_CameraTime 0xD113 #define PTP_DPC_CANON_EOS_AutoPowerOff 0xD114 #define PTP_DPC_CANON_EOS_Owner 0xD115 #define PTP_DPC_CANON_EOS_ModelID 0xD116 #define PTP_DPC_CANON_EOS_PTPExtensionVersion 0xD119 #define PTP_DPC_CANON_EOS_DPOFVersion 0xD11A #define PTP_DPC_CANON_EOS_AvailableShots 0xD11B #define PTP_CANON_EOS_CAPTUREDEST_HD 4 #define PTP_DPC_CANON_EOS_CaptureDestination 0xD11C #define PTP_DPC_CANON_EOS_BracketMode 0xD11D #define PTP_DPC_CANON_EOS_CurrentStorage 0xD11E #define PTP_DPC_CANON_EOS_CurrentFolder 0xD11F #define PTP_DPC_CANON_EOS_ImageFormat 0xD120 /* file setting */ #define PTP_DPC_CANON_EOS_ImageFormatCF 0xD121 /* file setting CF */ #define PTP_DPC_CANON_EOS_ImageFormatSD 0xD122 /* file setting SD */ #define PTP_DPC_CANON_EOS_ImageFormatExtHD 0xD123 /* file setting exthd */ #define PTP_DPC_CANON_EOS_CompressionS 0xD130 #define PTP_DPC_CANON_EOS_CompressionM1 0xD131 #define PTP_DPC_CANON_EOS_CompressionM2 0xD132 #define PTP_DPC_CANON_EOS_CompressionL 0xD133 #define PTP_DPC_CANON_EOS_PCWhiteBalance1 0xD140 #define PTP_DPC_CANON_EOS_PCWhiteBalance2 0xD141 #define PTP_DPC_CANON_EOS_PCWhiteBalance3 0xD142 #define PTP_DPC_CANON_EOS_PCWhiteBalance4 0xD143 #define PTP_DPC_CANON_EOS_PCWhiteBalance5 0xD144 #define PTP_DPC_CANON_EOS_MWhiteBalance 0xD145 #define PTP_DPC_CANON_EOS_PictureStyleStandard 0xD150 #define PTP_DPC_CANON_EOS_PictureStylePortrait 0xD151 #define PTP_DPC_CANON_EOS_PictureStyleLandscape 0xD152 #define PTP_DPC_CANON_EOS_PictureStyleNeutral 0xD153 #define PTP_DPC_CANON_EOS_PictureStyleFaithful 0xD154 #define PTP_DPC_CANON_EOS_PictureStyleBlackWhite 0xD155 #define PTP_DPC_CANON_EOS_PictureStyleUserSet1 0xD160 #define PTP_DPC_CANON_EOS_PictureStyleUserSet2 0xD161 #define PTP_DPC_CANON_EOS_PictureStyleUserSet3 0xD162 #define PTP_DPC_CANON_EOS_PictureStyleParam1 0xD170 #define PTP_DPC_CANON_EOS_PictureStyleParam2 0xD171 #define PTP_DPC_CANON_EOS_PictureStyleParam3 0xD172 #define PTP_DPC_CANON_EOS_FlavorLUTParams 0xD17f #define PTP_DPC_CANON_EOS_CustomFunc1 0xD180 #define PTP_DPC_CANON_EOS_CustomFunc2 0xD181 #define PTP_DPC_CANON_EOS_CustomFunc3 0xD182 #define PTP_DPC_CANON_EOS_CustomFunc4 0xD183 #define PTP_DPC_CANON_EOS_CustomFunc5 0xD184 #define PTP_DPC_CANON_EOS_CustomFunc6 0xD185 #define PTP_DPC_CANON_EOS_CustomFunc7 0xD186 #define PTP_DPC_CANON_EOS_CustomFunc8 0xD187 #define PTP_DPC_CANON_EOS_CustomFunc9 0xD188 #define PTP_DPC_CANON_EOS_CustomFunc10 0xD189 #define PTP_DPC_CANON_EOS_CustomFunc11 0xD18a #define PTP_DPC_CANON_EOS_CustomFunc12 0xD18b #define PTP_DPC_CANON_EOS_CustomFunc13 0xD18c #define PTP_DPC_CANON_EOS_CustomFunc14 0xD18d #define PTP_DPC_CANON_EOS_CustomFunc15 0xD18e #define PTP_DPC_CANON_EOS_CustomFunc16 0xD18f #define PTP_DPC_CANON_EOS_CustomFunc17 0xD190 #define PTP_DPC_CANON_EOS_CustomFunc18 0xD191 #define PTP_DPC_CANON_EOS_CustomFunc19 0xD192 #define PTP_DPC_CANON_EOS_CustomFunc19 0xD192 #define PTP_DPC_CANON_EOS_CustomFuncEx 0xD1a0 #define PTP_DPC_CANON_EOS_MyMenu 0xD1a1 #define PTP_DPC_CANON_EOS_MyMenuList 0xD1a2 #define PTP_DPC_CANON_EOS_WftStatus 0xD1a3 #define PTP_DPC_CANON_EOS_WftInputTransmission 0xD1a4 #define PTP_DPC_CANON_EOS_HDDirectoryStructure 0xD1a5 #define PTP_DPC_CANON_EOS_BatteryInfo 0xD1a6 #define PTP_DPC_CANON_EOS_AdapterInfo 0xD1a7 #define PTP_DPC_CANON_EOS_LensStatus 0xD1a8 #define PTP_DPC_CANON_EOS_QuickReviewTime 0xD1a9 #define PTP_DPC_CANON_EOS_CardExtension 0xD1aa #define PTP_DPC_CANON_EOS_TempStatus 0xD1ab #define PTP_DPC_CANON_EOS_ShutterCounter 0xD1ac #define PTP_DPC_CANON_EOS_SpecialOption 0xD1ad #define PTP_DPC_CANON_EOS_PhotoStudioMode 0xD1ae #define PTP_DPC_CANON_EOS_SerialNumber 0xD1af #define PTP_DPC_CANON_EOS_EVFOutputDevice 0xD1b0 #define PTP_DPC_CANON_EOS_EVFMode 0xD1b1 #define PTP_DPC_CANON_EOS_DepthOfFieldPreview 0xD1b2 #define PTP_DPC_CANON_EOS_EVFSharpness 0xD1b3 #define PTP_DPC_CANON_EOS_EVFWBMode 0xD1b4 #define PTP_DPC_CANON_EOS_EVFClickWBCoeffs 0xD1b5 #define PTP_DPC_CANON_EOS_EVFColorTemp 0xD1b6 #define PTP_DPC_CANON_EOS_ExposureSimMode 0xD1b7 #define PTP_DPC_CANON_EOS_EVFRecordStatus 0xD1b8 #define PTP_DPC_CANON_EOS_LvAfSystem 0xD1ba #define PTP_DPC_CANON_EOS_MovSize 0xD1bb #define PTP_DPC_CANON_EOS_LvViewTypeSelect 0xD1bc #define PTP_DPC_CANON_EOS_Artist 0xD1d0 #define PTP_DPC_CANON_EOS_Copyright 0xD1d1 #define PTP_DPC_CANON_EOS_BracketValue 0xD1d2 #define PTP_DPC_CANON_EOS_FocusInfoEx 0xD1d3 #define PTP_DPC_CANON_EOS_DepthOfField 0xD1d4 #define PTP_DPC_CANON_EOS_Brightness 0xD1d5 #define PTP_DPC_CANON_EOS_LensAdjustParams 0xD1d6 #define PTP_DPC_CANON_EOS_EFComp 0xD1d7 #define PTP_DPC_CANON_EOS_LensName 0xD1d8 #define PTP_DPC_CANON_EOS_AEB 0xD1d9 #define PTP_DPC_CANON_EOS_StroboSetting 0xD1da #define PTP_DPC_CANON_EOS_StroboWirelessSetting 0xD1db #define PTP_DPC_CANON_EOS_StroboFiring 0xD1dc #define PTP_DPC_CANON_EOS_LensID 0xD1dd /* Nikon extension device property codes */ #define PTP_DPC_NIKON_ShootingBank 0xD010 #define PTP_DPC_NIKON_ShootingBankNameA 0xD011 #define PTP_DPC_NIKON_ShootingBankNameB 0xD012 #define PTP_DPC_NIKON_ShootingBankNameC 0xD013 #define PTP_DPC_NIKON_ShootingBankNameD 0xD014 #define PTP_DPC_NIKON_ResetBank0 0xD015 #define PTP_DPC_NIKON_RawCompression 0xD016 #define PTP_DPC_NIKON_WhiteBalanceAutoBias 0xD017 #define PTP_DPC_NIKON_WhiteBalanceTungstenBias 0xD018 #define PTP_DPC_NIKON_WhiteBalanceFluorescentBias 0xD019 #define PTP_DPC_NIKON_WhiteBalanceDaylightBias 0xD01A #define PTP_DPC_NIKON_WhiteBalanceFlashBias 0xD01B #define PTP_DPC_NIKON_WhiteBalanceCloudyBias 0xD01C #define PTP_DPC_NIKON_WhiteBalanceShadeBias 0xD01D #define PTP_DPC_NIKON_WhiteBalanceColorTemperature 0xD01E #define PTP_DPC_NIKON_WhiteBalancePresetNo 0xD01F #define PTP_DPC_NIKON_WhiteBalancePresetName0 0xD020 #define PTP_DPC_NIKON_WhiteBalancePresetName1 0xD021 #define PTP_DPC_NIKON_WhiteBalancePresetName2 0xD022 #define PTP_DPC_NIKON_WhiteBalancePresetName3 0xD023 #define PTP_DPC_NIKON_WhiteBalancePresetName4 0xD024 #define PTP_DPC_NIKON_WhiteBalancePresetVal0 0xD025 #define PTP_DPC_NIKON_WhiteBalancePresetVal1 0xD026 #define PTP_DPC_NIKON_WhiteBalancePresetVal2 0xD027 #define PTP_DPC_NIKON_WhiteBalancePresetVal3 0xD028 #define PTP_DPC_NIKON_WhiteBalancePresetVal4 0xD029 #define PTP_DPC_NIKON_ImageSharpening 0xD02A #define PTP_DPC_NIKON_ToneCompensation 0xD02B #define PTP_DPC_NIKON_ColorModel 0xD02C #define PTP_DPC_NIKON_HueAdjustment 0xD02D #define PTP_DPC_NIKON_NonCPULensDataFocalLength 0xD02E /* Set FMM Manual */ #define PTP_DPC_NIKON_NonCPULensDataMaximumAperture 0xD02F /* Set F0 Manual */ #define PTP_DPC_NIKON_ShootingMode 0xD030 #define PTP_DPC_NIKON_JPEG_Compression_Policy 0xD031 #define PTP_DPC_NIKON_ColorSpace 0xD032 #define PTP_DPC_NIKON_AutoDXCrop 0xD033 #define PTP_DPC_NIKON_FlickerReduction 0xD034 #define PTP_DPC_NIKON_RemoteMode 0xD035 #define PTP_DPC_NIKON_VideoMode 0xD036 #define PTP_DPC_NIKON_EffectMode 0xD037 #define PTP_DPC_NIKON_CSMMenuBankSelect 0xD040 #define PTP_DPC_NIKON_MenuBankNameA 0xD041 #define PTP_DPC_NIKON_MenuBankNameB 0xD042 #define PTP_DPC_NIKON_MenuBankNameC 0xD043 #define PTP_DPC_NIKON_MenuBankNameD 0xD044 #define PTP_DPC_NIKON_ResetBank 0xD045 #define PTP_DPC_NIKON_A1AFCModePriority 0xD048 #define PTP_DPC_NIKON_A2AFSModePriority 0xD049 #define PTP_DPC_NIKON_A3GroupDynamicAF 0xD04A #define PTP_DPC_NIKON_A4AFActivation 0xD04B #define PTP_DPC_NIKON_FocusAreaIllumManualFocus 0xD04C #define PTP_DPC_NIKON_FocusAreaIllumContinuous 0xD04D #define PTP_DPC_NIKON_FocusAreaIllumWhenSelected 0xD04E #define PTP_DPC_NIKON_FocusAreaWrap 0xD04F /* area sel */ #define PTP_DPC_NIKON_VerticalAFON 0xD050 #define PTP_DPC_NIKON_AFLockOn 0xD051 #define PTP_DPC_NIKON_FocusAreaZone 0xD052 #define PTP_DPC_NIKON_EnableCopyright 0xD053 #define PTP_DPC_NIKON_ISOAuto 0xD054 #define PTP_DPC_NIKON_EVISOStep 0xD055 #define PTP_DPC_NIKON_EVStep 0xD056 /* EV Step SS FN */ #define PTP_DPC_NIKON_EVStepExposureComp 0xD057 #define PTP_DPC_NIKON_ExposureCompensation 0xD058 #define PTP_DPC_NIKON_CenterWeightArea 0xD059 #define PTP_DPC_NIKON_ExposureBaseMatrix 0xD05A #define PTP_DPC_NIKON_ExposureBaseCenter 0xD05B #define PTP_DPC_NIKON_ExposureBaseSpot 0xD05C #define PTP_DPC_NIKON_LiveViewAFArea 0xD05D #define PTP_DPC_NIKON_AELockMode 0xD05E #define PTP_DPC_NIKON_AELAFLMode 0xD05F #define PTP_DPC_NIKON_LiveViewAFFocus 0xD061 #define PTP_DPC_NIKON_MeterOff 0xD062 #define PTP_DPC_NIKON_SelfTimer 0xD063 #define PTP_DPC_NIKON_MonitorOff 0xD064 #define PTP_DPC_NIKON_ImgConfTime 0xD065 #define PTP_DPC_NIKON_AutoOffTimers 0xD066 #define PTP_DPC_NIKON_AngleLevel 0xD067 #define PTP_DPC_NIKON_D1ShootingSpeed 0xD068 /* continous speed low */ #define PTP_DPC_NIKON_D2MaximumShots 0xD069 #define PTP_DPC_NIKON_ExposureDelayMode 0xD06A #define PTP_DPC_NIKON_LongExposureNoiseReduction 0xD06B #define PTP_DPC_NIKON_FileNumberSequence 0xD06C #define PTP_DPC_NIKON_ControlPanelFinderRearControl 0xD06D #define PTP_DPC_NIKON_ControlPanelFinderViewfinder 0xD06E #define PTP_DPC_NIKON_D7Illumination 0xD06F #define PTP_DPC_NIKON_NrHighISO 0xD070 #define PTP_DPC_NIKON_SHSET_CH_GUID_DISP 0xD071 #define PTP_DPC_NIKON_ArtistName 0xD072 #define PTP_DPC_NIKON_CopyrightInfo 0xD073 #define PTP_DPC_NIKON_FlashSyncSpeed 0xD074 #define PTP_DPC_NIKON_FlashShutterSpeed 0xD075 /* SB Low Limit */ #define PTP_DPC_NIKON_E3AAFlashMode 0xD076 #define PTP_DPC_NIKON_E4ModelingFlash 0xD077 #define PTP_DPC_NIKON_BracketSet 0xD078 /* Bracket Type? */ #define PTP_DPC_NIKON_E6ManualModeBracketing 0xD079 /* Bracket Factor? */ #define PTP_DPC_NIKON_BracketOrder 0xD07A #define PTP_DPC_NIKON_E8AutoBracketSelection 0xD07B /* Bracket Method? */ #define PTP_DPC_NIKON_BracketingSet 0xD07C #define PTP_DPC_NIKON_F1CenterButtonShootingMode 0xD080 #define PTP_DPC_NIKON_CenterButtonPlaybackMode 0xD081 #define PTP_DPC_NIKON_F2Multiselector 0xD082 #define PTP_DPC_NIKON_F3PhotoInfoPlayback 0xD083 /* MultiSelector Dir */ #define PTP_DPC_NIKON_F4AssignFuncButton 0xD084 /* CMD Dial Rotate */ #define PTP_DPC_NIKON_F5CustomizeCommDials 0xD085 /* CMD Dial Change */ #define PTP_DPC_NIKON_ReverseCommandDial 0xD086 /* CMD Dial FN Set */ #define PTP_DPC_NIKON_ApertureSetting 0xD087 /* CMD Dial Active */ #define PTP_DPC_NIKON_MenusAndPlayback 0xD088 /* CMD Dial Active */ #define PTP_DPC_NIKON_F6ButtonsAndDials 0xD089 /* Universal Mode? */ #define PTP_DPC_NIKON_NoCFCard 0xD08A /* Enable Shutter? */ #define PTP_DPC_NIKON_CenterButtonZoomRatio 0xD08B #define PTP_DPC_NIKON_FunctionButton2 0xD08C #define PTP_DPC_NIKON_AFAreaPoint 0xD08D #define PTP_DPC_NIKON_NormalAFOn 0xD08E #define PTP_DPC_NIKON_CleanImageSensor 0xD08F #define PTP_DPC_NIKON_ImageCommentString 0xD090 #define PTP_DPC_NIKON_ImageCommentEnable 0xD091 #define PTP_DPC_NIKON_ImageRotation 0xD092 #define PTP_DPC_NIKON_ManualSetLensNo 0xD093 #define PTP_DPC_NIKON_MovScreenSize 0xD0A0 #define PTP_DPC_NIKON_MovVoice 0xD0A1 #define PTP_DPC_NIKON_MovMicrophone 0xD0A2 #define PTP_DPC_NIKON_MovFileSlot 0xD0A3 #define PTP_DPC_NIKON_ManualMovieSetting 0xD0A6 #define PTP_DPC_NIKON_MonitorOffDelay 0xD0B3 #define PTP_DPC_NIKON_Bracketing 0xD0C0 #define PTP_DPC_NIKON_AutoExposureBracketStep 0xD0C1 #define PTP_DPC_NIKON_AutoExposureBracketProgram 0xD0C2 #define PTP_DPC_NIKON_AutoExposureBracketCount 0xD0C3 #define PTP_DPC_NIKON_WhiteBalanceBracketStep 0xD0C4 #define PTP_DPC_NIKON_WhiteBalanceBracketProgram 0xD0C5 #define PTP_DPC_NIKON_LensID 0xD0E0 #define PTP_DPC_NIKON_LensSort 0xD0E1 #define PTP_DPC_NIKON_LensType 0xD0E2 #define PTP_DPC_NIKON_FocalLengthMin 0xD0E3 #define PTP_DPC_NIKON_FocalLengthMax 0xD0E4 #define PTP_DPC_NIKON_MaxApAtMinFocalLength 0xD0E5 #define PTP_DPC_NIKON_MaxApAtMaxFocalLength 0xD0E6 #define PTP_DPC_NIKON_FinderISODisp 0xD0F0 #define PTP_DPC_NIKON_AutoOffPhoto 0xD0F2 #define PTP_DPC_NIKON_AutoOffMenu 0xD0F3 #define PTP_DPC_NIKON_AutoOffInfo 0xD0F4 #define PTP_DPC_NIKON_SelfTimerShootNum 0xD0F5 #define PTP_DPC_NIKON_VignetteCtrl 0xD0F7 #define PTP_DPC_NIKON_AutoDistortionControl 0xD0F8 #define PTP_DPC_NIKON_SceneMode 0xD0F9 #define PTP_DPC_NIKON_ExposureTime 0xD100 /* Shutter Speed */ #define PTP_DPC_NIKON_ACPower 0xD101 #define PTP_DPC_NIKON_WarningStatus 0xD102 #define PTP_DPC_NIKON_MaximumShots 0xD103 /* remain shots (in RAM buffer?) */ #define PTP_DPC_NIKON_AFLockStatus 0xD104 #define PTP_DPC_NIKON_AELockStatus 0xD105 #define PTP_DPC_NIKON_FVLockStatus 0xD106 #define PTP_DPC_NIKON_AutofocusLCDTopMode2 0xD107 #define PTP_DPC_NIKON_AutofocusArea 0xD108 #define PTP_DPC_NIKON_FlexibleProgram 0xD109 #define PTP_DPC_NIKON_LightMeter 0xD10A /* Exposure Status */ #define PTP_DPC_NIKON_RecordingMedia 0xD10B /* Card or SDRAM */ #define PTP_DPC_NIKON_USBSpeed 0xD10C #define PTP_DPC_NIKON_CCDNumber 0xD10D #define PTP_DPC_NIKON_CameraOrientation 0xD10E #define PTP_DPC_NIKON_GroupPtnType 0xD10F #define PTP_DPC_NIKON_FNumberLock 0xD110 #define PTP_DPC_NIKON_ExposureApertureLock 0xD111 /* shutterspeed lock*/ #define PTP_DPC_NIKON_TVLockSetting 0xD112 #define PTP_DPC_NIKON_AVLockSetting 0xD113 #define PTP_DPC_NIKON_IllumSetting 0xD114 #define PTP_DPC_NIKON_FocusPointBright 0xD115 #define PTP_DPC_NIKON_ExternalFlashAttached 0xD120 #define PTP_DPC_NIKON_ExternalFlashStatus 0xD121 #define PTP_DPC_NIKON_ExternalFlashSort 0xD122 #define PTP_DPC_NIKON_ExternalFlashMode 0xD123 #define PTP_DPC_NIKON_ExternalFlashCompensation 0xD124 #define PTP_DPC_NIKON_NewExternalFlashMode 0xD125 #define PTP_DPC_NIKON_FlashExposureCompensation 0xD126 #define PTP_DPC_NIKON_HDRMode 0xD130 #define PTP_DPC_NIKON_HDRHighDynamic 0xD131 #define PTP_DPC_NIKON_HDRSmoothing 0xD132 #define PTP_DPC_NIKON_OptimizeImage 0xD140 #define PTP_DPC_NIKON_Saturation 0xD142 #define PTP_DPC_NIKON_BW_FillerEffect 0xD143 #define PTP_DPC_NIKON_BW_Sharpness 0xD144 #define PTP_DPC_NIKON_BW_Contrast 0xD145 #define PTP_DPC_NIKON_BW_Setting_Type 0xD146 #define PTP_DPC_NIKON_Slot2SaveMode 0xD148 #define PTP_DPC_NIKON_RawBitMode 0xD149 #define PTP_DPC_NIKON_ISOAutoTime 0xD14E #define PTP_DPC_NIKON_FlourescentType 0xD14F #define PTP_DPC_NIKON_TuneColourTemperature 0xD150 #define PTP_DPC_NIKON_TunePreset0 0xD151 #define PTP_DPC_NIKON_TunePreset1 0xD152 #define PTP_DPC_NIKON_TunePreset2 0xD153 #define PTP_DPC_NIKON_TunePreset3 0xD154 #define PTP_DPC_NIKON_TunePreset4 0xD155 #define PTP_DPC_NIKON_BeepOff 0xD160 #define PTP_DPC_NIKON_AutofocusMode 0xD161 #define PTP_DPC_NIKON_AFAssist 0xD163 #define PTP_DPC_NIKON_PADVPMode 0xD164 /* iso auto time */ #define PTP_DPC_NIKON_ImageReview 0xD165 #define PTP_DPC_NIKON_AFAreaIllumination 0xD166 #define PTP_DPC_NIKON_FlashMode 0xD167 #define PTP_DPC_NIKON_FlashCommanderMode 0xD168 #define PTP_DPC_NIKON_FlashSign 0xD169 #define PTP_DPC_NIKON_ISO_Auto 0xD16A #define PTP_DPC_NIKON_RemoteTimeout 0xD16B #define PTP_DPC_NIKON_GridDisplay 0xD16C #define PTP_DPC_NIKON_FlashModeManualPower 0xD16D #define PTP_DPC_NIKON_FlashModeCommanderPower 0xD16E #define PTP_DPC_NIKON_AutoFP 0xD16F #define PTP_DPC_NIKON_CSMMenu 0xD180 #define PTP_DPC_NIKON_WarningDisplay 0xD181 #define PTP_DPC_NIKON_BatteryCellKind 0xD182 #define PTP_DPC_NIKON_ISOAutoHiLimit 0xD183 #define PTP_DPC_NIKON_DynamicAFArea 0xD184 #define PTP_DPC_NIKON_ContinuousSpeedHigh 0xD186 #define PTP_DPC_NIKON_InfoDispSetting 0xD187 #define PTP_DPC_NIKON_PreviewButton 0xD189 #define PTP_DPC_NIKON_PreviewButton2 0xD18A #define PTP_DPC_NIKON_AEAFLockButton2 0xD18B #define PTP_DPC_NIKON_IndicatorDisp 0xD18D #define PTP_DPC_NIKON_CellKindPriority 0xD18E #define PTP_DPC_NIKON_BracketingFramesAndSteps 0xD190 #define PTP_DPC_NIKON_LiveViewMode 0xD1A0 #define PTP_DPC_NIKON_LiveViewDriveMode 0xD1A1 #define PTP_DPC_NIKON_LiveViewStatus 0xD1A2 #define PTP_DPC_NIKON_LiveViewImageZoomRatio 0xD1A3 #define PTP_DPC_NIKON_LiveViewProhibitCondition 0xD1A4 #define PTP_DPC_NIKON_ExposureDisplayStatus 0xD1B0 #define PTP_DPC_NIKON_ExposureIndicateStatus 0xD1B1 #define PTP_DPC_NIKON_InfoDispErrStatus 0xD1B2 #define PTP_DPC_NIKON_ExposureIndicateLightup 0xD1B3 #define PTP_DPC_NIKON_FlashOpen 0xD1C0 #define PTP_DPC_NIKON_FlashCharged 0xD1C1 #define PTP_DPC_NIKON_FlashMRepeatValue 0xD1D0 #define PTP_DPC_NIKON_FlashMRepeatCount 0xD1D1 #define PTP_DPC_NIKON_FlashMRepeatInterval 0xD1D2 #define PTP_DPC_NIKON_FlashCommandChannel 0xD1D3 #define PTP_DPC_NIKON_FlashCommandSelfMode 0xD1D4 #define PTP_DPC_NIKON_FlashCommandSelfCompensation 0xD1D5 #define PTP_DPC_NIKON_FlashCommandSelfValue 0xD1D6 #define PTP_DPC_NIKON_FlashCommandAMode 0xD1D7 #define PTP_DPC_NIKON_FlashCommandACompensation 0xD1D8 #define PTP_DPC_NIKON_FlashCommandAValue 0xD1D9 #define PTP_DPC_NIKON_FlashCommandBMode 0xD1DA #define PTP_DPC_NIKON_FlashCommandBCompensation 0xD1DB #define PTP_DPC_NIKON_FlashCommandBValue 0xD1DC #define PTP_DPC_NIKON_ActivePicCtrlItem 0xD200 #define PTP_DPC_NIKON_ChangePicCtrlItem 0xD201 /* Fuji specific */ #define PTP_DPC_FUJI_ColorTemperature 0xD017 #define PTP_DPC_FUJI_Quality 0xD018 #define PTP_DPC_FUJI_ReleaseMode 0xD201 #define PTP_DPC_FUJI_FocusAreas 0xD206 #define PTP_DPC_FUJI_AELock 0xD213 #define PTP_DPC_FUJI_Aperture 0xD218 #define PTP_DPC_FUJI_ShutterSpeed 0xD219 /* Microsoft/MTP specific */ #define PTP_DPC_MTP_SecureTime 0xD101 #define PTP_DPC_MTP_DeviceCertificate 0xD102 #define PTP_DPC_MTP_RevocationInfo 0xD103 #define PTP_DPC_MTP_SynchronizationPartner 0xD401 #define PTP_DPC_MTP_DeviceFriendlyName 0xD402 #define PTP_DPC_MTP_VolumeLevel 0xD403 #define PTP_DPC_MTP_DeviceIcon 0xD405 #define PTP_DPC_MTP_SessionInitiatorInfo 0xD406 #define PTP_DPC_MTP_PerceivedDeviceType 0xD407 #define PTP_DPC_MTP_PlaybackRate 0xD410 #define PTP_DPC_MTP_PlaybackObject 0xD411 #define PTP_DPC_MTP_PlaybackContainerIndex 0xD412 #define PTP_DPC_MTP_PlaybackPosition 0xD413 #define PTP_DPC_MTP_PlaysForSureID 0xD131 /* Zune specific property codes */ #define PTP_DPC_MTP_Zune_UnknownVersion 0xD181 /* Olympus */ #define PTP_DPC_OLYMPUS_ResolutionMode 0xD102 #define PTP_DPC_OLYMPUS_FocusPriority 0xD103 #define PTP_DPC_OLYMPUS_DriveMode 0xD104 #define PTP_DPC_OLYMPUS_DateTimeFormat 0xD105 #define PTP_DPC_OLYMPUS_ExposureBiasStep 0xD106 #define PTP_DPC_OLYMPUS_WBMode 0xD107 #define PTP_DPC_OLYMPUS_OneTouchWB 0xD108 #define PTP_DPC_OLYMPUS_ManualWB 0xD109 #define PTP_DPC_OLYMPUS_ManualWBRBBias 0xD10A #define PTP_DPC_OLYMPUS_CustomWB 0xD10B #define PTP_DPC_OLYMPUS_CustomWBValue 0xD10C #define PTP_DPC_OLYMPUS_ExposureTimeEx 0xD10D #define PTP_DPC_OLYMPUS_BulbMode 0xD10E #define PTP_DPC_OLYMPUS_AntiMirrorMode 0xD10F #define PTP_DPC_OLYMPUS_AEBracketingFrame 0xD110 #define PTP_DPC_OLYMPUS_AEBracketingStep 0xD111 #define PTP_DPC_OLYMPUS_WBBracketingFrame 0xD112 #define PTP_DPC_OLYMPUS_WBBracketingRBFrame 0xD112 /* dup ? */ #define PTP_DPC_OLYMPUS_WBBracketingRBRange 0xD113 #define PTP_DPC_OLYMPUS_WBBracketingGMFrame 0xD114 #define PTP_DPC_OLYMPUS_WBBracketingGMRange 0xD115 #define PTP_DPC_OLYMPUS_FLBracketingFrame 0xD118 #define PTP_DPC_OLYMPUS_FLBracketingStep 0xD119 #define PTP_DPC_OLYMPUS_FlashBiasCompensation 0xD11A #define PTP_DPC_OLYMPUS_ManualFocusMode 0xD11B #define PTP_DPC_OLYMPUS_RawSaveMode 0xD11D #define PTP_DPC_OLYMPUS_AUXLightMode 0xD11E #define PTP_DPC_OLYMPUS_LensSinkMode 0xD11F #define PTP_DPC_OLYMPUS_BeepStatus 0xD120 #define PTP_DPC_OLYMPUS_ColorSpace 0xD122 #define PTP_DPC_OLYMPUS_ColorMatching 0xD123 #define PTP_DPC_OLYMPUS_Saturation 0xD124 #define PTP_DPC_OLYMPUS_NoiseReductionPattern 0xD126 #define PTP_DPC_OLYMPUS_NoiseReductionRandom 0xD127 #define PTP_DPC_OLYMPUS_ShadingMode 0xD129 #define PTP_DPC_OLYMPUS_ISOBoostMode 0xD12A #define PTP_DPC_OLYMPUS_ExposureIndexBiasStep 0xD12B #define PTP_DPC_OLYMPUS_FilterEffect 0xD12C #define PTP_DPC_OLYMPUS_ColorTune 0xD12D #define PTP_DPC_OLYMPUS_Language 0xD12E #define PTP_DPC_OLYMPUS_LanguageCode 0xD12F #define PTP_DPC_OLYMPUS_RecviewMode 0xD130 #define PTP_DPC_OLYMPUS_SleepTime 0xD131 #define PTP_DPC_OLYMPUS_ManualWBGMBias 0xD132 #define PTP_DPC_OLYMPUS_AELAFLMode 0xD135 #define PTP_DPC_OLYMPUS_AELButtonStatus 0xD136 #define PTP_DPC_OLYMPUS_CompressionSettingEx 0xD137 #define PTP_DPC_OLYMPUS_ToneMode 0xD139 #define PTP_DPC_OLYMPUS_GradationMode 0xD13A #define PTP_DPC_OLYMPUS_DevelopMode 0xD13B #define PTP_DPC_OLYMPUS_ExtendInnerFlashMode 0xD13C #define PTP_DPC_OLYMPUS_OutputDeviceMode 0xD13D #define PTP_DPC_OLYMPUS_LiveViewMode 0xD13E #define PTP_DPC_OLYMPUS_LCDBacklight 0xD140 #define PTP_DPC_OLYMPUS_CustomDevelop 0xD141 #define PTP_DPC_OLYMPUS_GradationAutoBias 0xD142 #define PTP_DPC_OLYMPUS_FlashRCMode 0xD143 #define PTP_DPC_OLYMPUS_FlashRCGroupValue 0xD144 #define PTP_DPC_OLYMPUS_FlashRCChannelValue 0xD145 #define PTP_DPC_OLYMPUS_FlashRCFPMode 0xD146 #define PTP_DPC_OLYMPUS_FlashRCPhotoChromicMode 0xD147 #define PTP_DPC_OLYMPUS_FlashRCPhotoChromicBias 0xD148 #define PTP_DPC_OLYMPUS_FlashRCPhotoChromicManualBias 0xD149 #define PTP_DPC_OLYMPUS_FlashRCQuantityLightLevel 0xD14A #define PTP_DPC_OLYMPUS_FocusMeteringValue 0xD14B #define PTP_DPC_OLYMPUS_ISOBracketingFrame 0xD14C #define PTP_DPC_OLYMPUS_ISOBracketingStep 0xD14D #define PTP_DPC_OLYMPUS_BulbMFMode 0xD14E #define PTP_DPC_OLYMPUS_BurstFPSValue 0xD14F #define PTP_DPC_OLYMPUS_ISOAutoBaseValue 0xD150 #define PTP_DPC_OLYMPUS_ISOAutoMaxValue 0xD151 #define PTP_DPC_OLYMPUS_BulbLimiterValue 0xD152 #define PTP_DPC_OLYMPUS_DPIMode 0xD153 #define PTP_DPC_OLYMPUS_DPICustomValue 0xD154 #define PTP_DPC_OLYMPUS_ResolutionValueSetting 0xD155 #define PTP_DPC_OLYMPUS_AFTargetSize 0xD157 #define PTP_DPC_OLYMPUS_LightSensorMode 0xD158 #define PTP_DPC_OLYMPUS_AEBracket 0xD159 #define PTP_DPC_OLYMPUS_WBRBBracket 0xD15A #define PTP_DPC_OLYMPUS_WBGMBracket 0xD15B #define PTP_DPC_OLYMPUS_FlashBracket 0xD15C #define PTP_DPC_OLYMPUS_ISOBracket 0xD15D #define PTP_DPC_OLYMPUS_MyModeStatus 0xD15E /* Casio EX-F1 */ #define PTP_DPC_CASIO_MONITOR 0xD001 #define PTP_DPC_CASIO_STORAGE 0xD002 //Not reported by DeviceInfo? #define PTP_DPC_CASIO_UNKNOWN_1 0xD004 #define PTP_DPC_CASIO_UNKNOWN_2 0xD005 #define PTP_DPC_CASIO_UNKNOWN_3 0xD007 #define PTP_DPC_CASIO_RECORD_LIGHT 0xD008 #define PTP_DPC_CASIO_UNKNOWN_4 0xD009 #define PTP_DPC_CASIO_UNKNOWN_5 0xD00A #define PTP_DPC_CASIO_MOVIE_MODE 0xD00B #define PTP_DPC_CASIO_HD_SETTING 0xD00C #define PTP_DPC_CASIO_HS_SETTING 0xD00D #define PTP_DPC_CASIO_CS_HIGH_SPEED 0xD00F #define PTP_DPC_CASIO_CS_UPPER_LIMIT 0xD010 #define PTP_DPC_CASIO_CS_SHOT 0xD011 #define PTP_DPC_CASIO_UNKNOWN_6 0xD012 #define PTP_DPC_CASIO_UNKNOWN_7 0xD013 #define PTP_DPC_CASIO_UNKNOWN_8 0xD015 #define PTP_DPC_CASIO_UNKNOWN_9 0xD017 #define PTP_DPC_CASIO_UNKNOWN_10 0xD018 #define PTP_DPC_CASIO_UNKNOWN_11 0xD019 #define PTP_DPC_CASIO_UNKNOWN_12 0xD01A #define PTP_DPC_CASIO_UNKNOWN_13 0xD01B #define PTP_DPC_CASIO_UNKNOWN_14 0xD01C #define PTP_DPC_CASIO_UNKNOWN_15 0xD01D #define PTP_DPC_CASIO_UNKNOWN_16 0xD020 #define PTP_DPC_CASIO_UNKNOWN_17 0xD030 #define PTP_DPC_CASIO_UNKNOWN_18 0xD080 /* MTP specific Object Properties */ #define PTP_OPC_StorageID 0xDC01 #define PTP_OPC_ObjectFormat 0xDC02 #define PTP_OPC_ProtectionStatus 0xDC03 #define PTP_OPC_ObjectSize 0xDC04 #define PTP_OPC_AssociationType 0xDC05 #define PTP_OPC_AssociationDesc 0xDC06 #define PTP_OPC_ObjectFileName 0xDC07 #define PTP_OPC_DateCreated 0xDC08 #define PTP_OPC_DateModified 0xDC09 #define PTP_OPC_Keywords 0xDC0A #define PTP_OPC_ParentObject 0xDC0B #define PTP_OPC_AllowedFolderContents 0xDC0C #define PTP_OPC_Hidden 0xDC0D #define PTP_OPC_SystemObject 0xDC0E #define PTP_OPC_PersistantUniqueObjectIdentifier 0xDC41 #define PTP_OPC_SyncID 0xDC42 #define PTP_OPC_PropertyBag 0xDC43 #define PTP_OPC_Name 0xDC44 #define PTP_OPC_CreatedBy 0xDC45 #define PTP_OPC_Artist 0xDC46 #define PTP_OPC_DateAuthored 0xDC47 #define PTP_OPC_Description 0xDC48 #define PTP_OPC_URLReference 0xDC49 #define PTP_OPC_LanguageLocale 0xDC4A #define PTP_OPC_CopyrightInformation 0xDC4B #define PTP_OPC_Source 0xDC4C #define PTP_OPC_OriginLocation 0xDC4D #define PTP_OPC_DateAdded 0xDC4E #define PTP_OPC_NonConsumable 0xDC4F #define PTP_OPC_CorruptOrUnplayable 0xDC50 #define PTP_OPC_ProducerSerialNumber 0xDC51 #define PTP_OPC_RepresentativeSampleFormat 0xDC81 #define PTP_OPC_RepresentativeSampleSize 0xDC82 #define PTP_OPC_RepresentativeSampleHeight 0xDC83 #define PTP_OPC_RepresentativeSampleWidth 0xDC84 #define PTP_OPC_RepresentativeSampleDuration 0xDC85 #define PTP_OPC_RepresentativeSampleData 0xDC86 #define PTP_OPC_Width 0xDC87 #define PTP_OPC_Height 0xDC88 #define PTP_OPC_Duration 0xDC89 #define PTP_OPC_Rating 0xDC8A #define PTP_OPC_Track 0xDC8B #define PTP_OPC_Genre 0xDC8C #define PTP_OPC_Credits 0xDC8D #define PTP_OPC_Lyrics 0xDC8E #define PTP_OPC_SubscriptionContentID 0xDC8F #define PTP_OPC_ProducedBy 0xDC90 #define PTP_OPC_UseCount 0xDC91 #define PTP_OPC_SkipCount 0xDC92 #define PTP_OPC_LastAccessed 0xDC93 #define PTP_OPC_ParentalRating 0xDC94 #define PTP_OPC_MetaGenre 0xDC95 #define PTP_OPC_Composer 0xDC96 #define PTP_OPC_EffectiveRating 0xDC97 #define PTP_OPC_Subtitle 0xDC98 #define PTP_OPC_OriginalReleaseDate 0xDC99 #define PTP_OPC_AlbumName 0xDC9A #define PTP_OPC_AlbumArtist 0xDC9B #define PTP_OPC_Mood 0xDC9C #define PTP_OPC_DRMStatus 0xDC9D #define PTP_OPC_SubDescription 0xDC9E #define PTP_OPC_IsCropped 0xDCD1 #define PTP_OPC_IsColorCorrected 0xDCD2 #define PTP_OPC_ImageBitDepth 0xDCD3 #define PTP_OPC_Fnumber 0xDCD4 #define PTP_OPC_ExposureTime 0xDCD5 #define PTP_OPC_ExposureIndex 0xDCD6 #define PTP_OPC_DisplayName 0xDCE0 #define PTP_OPC_BodyText 0xDCE1 #define PTP_OPC_Subject 0xDCE2 #define PTP_OPC_Priority 0xDCE3 #define PTP_OPC_GivenName 0xDD00 #define PTP_OPC_MiddleNames 0xDD01 #define PTP_OPC_FamilyName 0xDD02 #define PTP_OPC_Prefix 0xDD03 #define PTP_OPC_Suffix 0xDD04 #define PTP_OPC_PhoneticGivenName 0xDD05 #define PTP_OPC_PhoneticFamilyName 0xDD06 #define PTP_OPC_EmailPrimary 0xDD07 #define PTP_OPC_EmailPersonal1 0xDD08 #define PTP_OPC_EmailPersonal2 0xDD09 #define PTP_OPC_EmailBusiness1 0xDD0A #define PTP_OPC_EmailBusiness2 0xDD0B #define PTP_OPC_EmailOthers 0xDD0C #define PTP_OPC_PhoneNumberPrimary 0xDD0D #define PTP_OPC_PhoneNumberPersonal 0xDD0E #define PTP_OPC_PhoneNumberPersonal2 0xDD0F #define PTP_OPC_PhoneNumberBusiness 0xDD10 #define PTP_OPC_PhoneNumberBusiness2 0xDD11 #define PTP_OPC_PhoneNumberMobile 0xDD12 #define PTP_OPC_PhoneNumberMobile2 0xDD13 #define PTP_OPC_FaxNumberPrimary 0xDD14 #define PTP_OPC_FaxNumberPersonal 0xDD15 #define PTP_OPC_FaxNumberBusiness 0xDD16 #define PTP_OPC_PagerNumber 0xDD17 #define PTP_OPC_PhoneNumberOthers 0xDD18 #define PTP_OPC_PrimaryWebAddress 0xDD19 #define PTP_OPC_PersonalWebAddress 0xDD1A #define PTP_OPC_BusinessWebAddress 0xDD1B #define PTP_OPC_InstantMessengerAddress 0xDD1C #define PTP_OPC_InstantMessengerAddress2 0xDD1D #define PTP_OPC_InstantMessengerAddress3 0xDD1E #define PTP_OPC_PostalAddressPersonalFull 0xDD1F #define PTP_OPC_PostalAddressPersonalFullLine1 0xDD20 #define PTP_OPC_PostalAddressPersonalFullLine2 0xDD21 #define PTP_OPC_PostalAddressPersonalFullCity 0xDD22 #define PTP_OPC_PostalAddressPersonalFullRegion 0xDD23 #define PTP_OPC_PostalAddressPersonalFullPostalCode 0xDD24 #define PTP_OPC_PostalAddressPersonalFullCountry 0xDD25 #define PTP_OPC_PostalAddressBusinessFull 0xDD26 #define PTP_OPC_PostalAddressBusinessLine1 0xDD27 #define PTP_OPC_PostalAddressBusinessLine2 0xDD28 #define PTP_OPC_PostalAddressBusinessCity 0xDD29 #define PTP_OPC_PostalAddressBusinessRegion 0xDD2A #define PTP_OPC_PostalAddressBusinessPostalCode 0xDD2B #define PTP_OPC_PostalAddressBusinessCountry 0xDD2C #define PTP_OPC_PostalAddressOtherFull 0xDD2D #define PTP_OPC_PostalAddressOtherLine1 0xDD2E #define PTP_OPC_PostalAddressOtherLine2 0xDD2F #define PTP_OPC_PostalAddressOtherCity 0xDD30 #define PTP_OPC_PostalAddressOtherRegion 0xDD31 #define PTP_OPC_PostalAddressOtherPostalCode 0xDD32 #define PTP_OPC_PostalAddressOtherCountry 0xDD33 #define PTP_OPC_OrganizationName 0xDD34 #define PTP_OPC_PhoneticOrganizationName 0xDD35 #define PTP_OPC_Role 0xDD36 #define PTP_OPC_Birthdate 0xDD37 #define PTP_OPC_MessageTo 0xDD40 #define PTP_OPC_MessageCC 0xDD41 #define PTP_OPC_MessageBCC 0xDD42 #define PTP_OPC_MessageRead 0xDD43 #define PTP_OPC_MessageReceivedTime 0xDD44 #define PTP_OPC_MessageSender 0xDD45 #define PTP_OPC_ActivityBeginTime 0xDD50 #define PTP_OPC_ActivityEndTime 0xDD51 #define PTP_OPC_ActivityLocation 0xDD52 #define PTP_OPC_ActivityRequiredAttendees 0xDD54 #define PTP_OPC_ActivityOptionalAttendees 0xDD55 #define PTP_OPC_ActivityResources 0xDD56 #define PTP_OPC_ActivityAccepted 0xDD57 #define PTP_OPC_Owner 0xDD5D #define PTP_OPC_Editor 0xDD5E #define PTP_OPC_Webmaster 0xDD5F #define PTP_OPC_URLSource 0xDD60 #define PTP_OPC_URLDestination 0xDD61 #define PTP_OPC_TimeBookmark 0xDD62 #define PTP_OPC_ObjectBookmark 0xDD63 #define PTP_OPC_ByteBookmark 0xDD64 #define PTP_OPC_LastBuildDate 0xDD70 #define PTP_OPC_TimetoLive 0xDD71 #define PTP_OPC_MediaGUID 0xDD72 #define PTP_OPC_TotalBitRate 0xDE91 #define PTP_OPC_BitRateType 0xDE92 #define PTP_OPC_SampleRate 0xDE93 #define PTP_OPC_NumberOfChannels 0xDE94 #define PTP_OPC_AudioBitDepth 0xDE95 #define PTP_OPC_ScanDepth 0xDE97 #define PTP_OPC_AudioWAVECodec 0xDE99 #define PTP_OPC_AudioBitRate 0xDE9A #define PTP_OPC_VideoFourCCCodec 0xDE9B #define PTP_OPC_VideoBitRate 0xDE9C #define PTP_OPC_FramesPerThousandSeconds 0xDE9D #define PTP_OPC_KeyFrameDistance 0xDE9E #define PTP_OPC_BufferSize 0xDE9F #define PTP_OPC_EncodingQuality 0xDEA0 #define PTP_OPC_EncodingProfile 0xDEA1 #define PTP_OPC_BuyFlag 0xD901 /* WiFi Provisioning MTP Extension property codes */ #define PTP_OPC_WirelessConfigurationFile 0xB104 /* Device Property Form Flag */ #define PTP_DPFF_None 0x00 #define PTP_DPFF_Range 0x01 #define PTP_DPFF_Enumeration 0x02 /* Object Property Codes used by MTP (first 3 are same as DPFF codes) */ #define PTP_OPFF_None 0x00 #define PTP_OPFF_Range 0x01 #define PTP_OPFF_Enumeration 0x02 #define PTP_OPFF_DateTime 0x03 #define PTP_OPFF_FixedLengthArray 0x04 #define PTP_OPFF_RegularExpression 0x05 #define PTP_OPFF_ByteArray 0x06 #define PTP_OPFF_LongString 0xFF /* Device Property GetSet type */ #define PTP_DPGS_Get 0x00 #define PTP_DPGS_GetSet 0x01 /* Glue stuff starts here */ typedef struct _PTPParams PTPParams; typedef uint16_t (* PTPDataGetFunc) (PTPParams* params, void*priv, unsigned long wantlen, unsigned char *data, unsigned long *gotlen); typedef uint16_t (* PTPDataPutFunc) (PTPParams* params, void*priv, unsigned long sendlen, unsigned char *data, unsigned long *putlen); typedef struct _PTPDataHandler { PTPDataGetFunc getfunc; PTPDataPutFunc putfunc; void *priv; } PTPDataHandler; /* * This functions take PTP oriented arguments and send them over an * appropriate data layer doing byteorder conversion accordingly. */ typedef uint16_t (* PTPIOSendReq) (PTPParams* params, PTPContainer* req); typedef uint16_t (* PTPIOSendData) (PTPParams* params, PTPContainer* ptp, uint64_t size, PTPDataHandler*getter); typedef uint16_t (* PTPIOGetResp) (PTPParams* params, PTPContainer* resp); typedef uint16_t (* PTPIOGetData) (PTPParams* params, PTPContainer* ptp, PTPDataHandler *putter); typedef uint16_t (* PTPIOCancelReq) (PTPParams* params, uint32_t transaction_id); /* debug functions */ typedef void (* PTPErrorFunc) (void *data, const char *format, va_list args) #if (__GNUC__ >= 3) __attribute__((__format__(printf,2,0))) #endif ; typedef void (* PTPDebugFunc) (void *data, const char *format, va_list args) #if (__GNUC__ >= 3) __attribute__((__format__(printf,2,0))) #endif ; struct _PTPObject { uint32_t oid; unsigned int flags; #define PTPOBJECT_OBJECTINFO_LOADED (1<<0) #define PTPOBJECT_CANONFLAGS_LOADED (1<<1) #define PTPOBJECT_MTPPROPLIST_LOADED (1<<2) #define PTPOBJECT_DIRECTORY_LOADED (1<<3) #define PTPOBJECT_PARENTOBJECT_LOADED (1<<4) #define PTPOBJECT_STORAGEID_LOADED (1<<5) PTPObjectInfo oi; uint32_t canon_flags; MTPProperties *mtpprops; int nrofmtpprops; }; typedef struct _PTPObject PTPObject; struct _PTPParams { /* device flags */ uint32_t device_flags; /* data layer byteorder */ uint8_t byteorder; uint16_t maxpacketsize; /* PTP IO: Custom IO functions */ PTPIOSendReq sendreq_func; PTPIOSendData senddata_func; PTPIOGetResp getresp_func; PTPIOGetData getdata_func; PTPIOGetResp event_check; PTPIOGetResp event_wait; PTPIOCancelReq cancelreq_func; /* Custom error and debug function */ PTPErrorFunc error_func; PTPDebugFunc debug_func; /* Data passed to above functions */ void *data; /* ptp transaction ID */ uint32_t transaction_id; /* ptp session ID */ uint32_t session_id; /* PTP IO: if we have MTP style split header/data transfers */ int split_header_data; int ocs64; /* 64bit objectsize */ /* PTP: internal structures used by ptp driver */ PTPObject *objects; int nrofobjects; PTPDeviceInfo deviceinfo; /* PTP: the current event queue */ PTPContainer *events; int nrofevents; /* PTP: Canon specific flags list */ PTPCanon_Property *canon_props; int nrofcanon_props; int canon_viewfinder_on; int canon_event_mode; /* PTP: Canon EOS event queue */ PTPCanon_changes_entry *backlogentries; int nrofbacklogentries; int eos_captureenabled; int eos_viewfinderenabled; int eos_camerastatus; /* PTP: Wifi profiles */ uint8_t wifi_profiles_version; uint8_t wifi_profiles_number; PTPNIKONWifiProfile *wifi_profiles; /* IO: PTP/IP related data */ int cmdfd, evtfd; uint8_t cameraguid[16]; uint32_t eventpipeid; char *cameraname; /* Olympus UMS wrapping related data */ PTPDeviceInfo outer_deviceinfo; char *olympus_cmd; char *olympus_reply; struct _PTPParams *outer_params; #ifdef HAVE_ICONV /* PTP: iconv converters */ iconv_t cd_locale_to_ucs2; iconv_t cd_ucs2_to_locale; #endif /* IO: Sometimes the response packet get send in the dataphase * too. This only happens for a Samsung player now. */ uint8_t *response_packet; uint16_t response_packet_size; }; /* last, but not least - ptp functions */ uint16_t ptp_usb_sendreq (PTPParams* params, PTPContainer* req); uint16_t ptp_usb_senddata (PTPParams* params, PTPContainer* ptp, uint64_t size, PTPDataHandler *handler); uint16_t ptp_usb_getresp (PTPParams* params, PTPContainer* resp); uint16_t ptp_usb_getdata (PTPParams* params, PTPContainer* ptp, PTPDataHandler *handler); uint16_t ptp_usb_event_check (PTPParams* params, PTPContainer* event); uint16_t ptp_usb_event_wait (PTPParams* params, PTPContainer* event); uint16_t ptp_usb_control_get_extended_event_data (PTPParams *params, char *buffer, int *size); uint16_t ptp_usb_control_device_reset_request (PTPParams *params); uint16_t ptp_usb_control_get_device_status (PTPParams *params, char *buffer, int *size); uint16_t ptp_usb_control_cancel_request (PTPParams *params, uint32_t transid); int ptp_ptpip_connect (PTPParams* params, const char *port); uint16_t ptp_ptpip_sendreq (PTPParams* params, PTPContainer* req); uint16_t ptp_ptpip_senddata (PTPParams* params, PTPContainer* ptp, uint64_t size, PTPDataHandler *handler); uint16_t ptp_ptpip_getresp (PTPParams* params, PTPContainer* resp); uint16_t ptp_ptpip_getdata (PTPParams* params, PTPContainer* ptp, PTPDataHandler *handler); uint16_t ptp_ptpip_event_wait (PTPParams* params, PTPContainer* event); uint16_t ptp_ptpip_event_check (PTPParams* params, PTPContainer* event); uint16_t ptp_getdeviceinfo (PTPParams* params, PTPDeviceInfo* deviceinfo); uint16_t ptp_generic_no_data (PTPParams* params, uint16_t opcode, unsigned int cnt, ...); uint16_t ptp_opensession (PTPParams *params, uint32_t session); uint16_t ptp_transaction_new (PTPParams* params, PTPContainer* ptp, uint16_t flags, uint64_t sendlen, PTPDataHandler *handler ); uint16_t ptp_transaction (PTPParams* params, PTPContainer* ptp, uint16_t flags, uint64_t sendlen, unsigned char **data, unsigned int *recvlen ); /** * ptp_closesession: * params: PTPParams* * * Closes session. * * Return values: Some PTP_RC_* code. **/ #define ptp_closesession(params) ptp_generic_no_data(params,PTP_OC_CloseSession,0) /** * ptp_resetdevice: * params: PTPParams* * * Uses the built-in function to reset the device * * Return values: Some PTP_RC_* code. * */ #define ptp_resetdevice(params) ptp_generic_no_data(params,PTP_OC_ResetDevice,0) uint16_t ptp_getstorageids (PTPParams* params, PTPStorageIDs* storageids); uint16_t ptp_getstorageinfo (PTPParams* params, uint32_t storageid, PTPStorageInfo* storageinfo); /** * ptp_formatstore: * params: PTPParams* * storageid - StorageID * * Formats the storage on the device. * * Return values: Some PTP_RC_* code. **/ #define ptp_formatstore(params,storageid) ptp_generic_no_data(params,PTP_OC_FormatStore,1,storageid) uint16_t ptp_getobjecthandles (PTPParams* params, uint32_t storage, uint32_t objectformatcode, uint32_t associationOH, PTPObjectHandles* objecthandles); uint16_t ptp_getnumobjects (PTPParams* params, uint32_t storage, uint32_t objectformatcode, uint32_t associationOH, uint32_t* numobs); uint16_t ptp_getobjectinfo (PTPParams *params, uint32_t handle, PTPObjectInfo* objectinfo); uint16_t ptp_getobject (PTPParams *params, uint32_t handle, unsigned char** object); uint16_t ptp_getobject_tofd (PTPParams* params, uint32_t handle, int fd); uint16_t ptp_getobject_to_handler (PTPParams* params, uint32_t handle, PTPDataHandler*); uint16_t ptp_getpartialobject (PTPParams* params, uint32_t handle, uint32_t offset, uint32_t maxbytes, unsigned char** object, uint32_t *len); uint16_t ptp_getthumb (PTPParams *params, uint32_t handle, unsigned char** object, unsigned int *len); uint16_t ptp_deleteobject (PTPParams* params, uint32_t handle, uint32_t ofc); uint16_t ptp_sendobjectinfo (PTPParams* params, uint32_t* store, uint32_t* parenthandle, uint32_t* handle, PTPObjectInfo* objectinfo); /** * ptp_setobjectprotection: * params: PTPParams* * uint16_t newprot - object protection flag * * Set protection of object. * * Return values: Some PTP_RC_* code. * */ #define ptp_setobjectprotection(params,oid,newprot) ptp_generic_no_data(params,PTP_OC_SetObjectProtection,2,oid,newprot) uint16_t ptp_sendobject (PTPParams* params, unsigned char* object, uint64_t size); uint16_t ptp_sendobject_fromfd (PTPParams* params, int fd, uint64_t size); uint16_t ptp_sendobject_from_handler (PTPParams* params, PTPDataHandler*, uint64_t size); /** * ptp_initiatecapture: * params: PTPParams* * storageid - destination StorageID on Responder * ofc - object format code * * Causes device to initiate the capture of one or more new data objects * according to its current device properties, storing the data into store * indicated by storageid. If storageid is 0x00000000, the object(s) will * be stored in a store that is determined by the capturing device. * The capturing of new data objects is an asynchronous operation. * * Return values: Some PTP_RC_* code. **/ #define ptp_initiatecapture(params,storageid,ofc) ptp_generic_no_data(params,PTP_OC_InitiateCapture,2,storageid,ofc) uint16_t ptp_getdevicepropdesc (PTPParams* params, uint16_t propcode, PTPDevicePropDesc *devicepropertydesc); uint16_t ptp_getdevicepropvalue (PTPParams* params, uint16_t propcode, PTPPropertyValue* value, uint16_t datatype); uint16_t ptp_setdevicepropvalue (PTPParams* params, uint16_t propcode, PTPPropertyValue* value, uint16_t datatype); uint16_t ptp_getfilesystemmanifest (PTPParams* params, uint32_t storage, uint32_t objectformatcode, uint32_t associationOH, unsigned char** data); uint16_t ptp_check_event (PTPParams *params); int ptp_get_one_event (PTPParams *params, PTPContainer *evt); uint16_t ptp_check_eos_events (PTPParams *params); int ptp_get_one_eos_event (PTPParams *params, PTPCanon_changes_entry *entry); /* Microsoft MTP extensions */ uint16_t ptp_mtp_getobjectpropdesc (PTPParams* params, uint16_t opc, uint16_t ofc, PTPObjectPropDesc *objectpropertydesc); uint16_t ptp_mtp_getobjectpropvalue (PTPParams* params, uint32_t oid, uint16_t opc, PTPPropertyValue *value, uint16_t datatype); uint16_t ptp_mtp_setobjectpropvalue (PTPParams* params, uint32_t oid, uint16_t opc, PTPPropertyValue *value, uint16_t datatype); uint16_t ptp_mtp_getobjectreferences (PTPParams* params, uint32_t handle, uint32_t** ohArray, uint32_t* arraylen); uint16_t ptp_mtp_setobjectreferences (PTPParams* params, uint32_t handle, uint32_t* ohArray, uint32_t arraylen); uint16_t ptp_mtp_getobjectproplist (PTPParams* params, uint32_t handle, MTPProperties **props, int *nrofprops); uint16_t ptp_mtp_getobjectproplist_single (PTPParams* params, uint32_t handle, MTPProperties **props, int *nrofprops); uint16_t ptp_mtp_sendobjectproplist (PTPParams* params, uint32_t* store, uint32_t* parenthandle, uint32_t* handle, uint16_t objecttype, uint64_t objectsize, MTPProperties *props, int nrofprops); uint16_t ptp_mtp_setobjectproplist (PTPParams* params, MTPProperties *props, int nrofprops); /* Microsoft MTPZ (Zune) extensions */ uint16_t ptp_mtpz_sendwmdrmpdapprequest (PTPParams*, unsigned char *, uint32_t); #define ptp_mtpz_resethandshake(params) ptp_generic_no_data(params, PTP_OC_MTP_WMDRMPD_EndTrustedAppSession, 0) uint16_t ptp_mtpz_getwmdrmpdappresponse (PTPParams*, unsigned char **, uint32_t*); #define ptp_mtpz_wmdrmpd_enabletrustedfilesoperations(params,hash1,hash2,hash3,hash4) \ ptp_generic_no_data(params, PTP_OC_MTP_WMDRMPD_EnableTrustedFilesOperations, 4,\ hash1, hash2, hash3, hash4) /* Eastman Kodak extensions */ uint16_t ptp_ek_9007 (PTPParams* params, unsigned char **serial, unsigned int *size); uint16_t ptp_ek_9009 (PTPParams* params, uint32_t*, uint32_t*); uint16_t ptp_ek_900c (PTPParams* params, unsigned char **serial, unsigned int *size); uint16_t ptp_ek_getserial (PTPParams* params, unsigned char **serial, unsigned int *size); uint16_t ptp_ek_setserial (PTPParams* params, unsigned char *serial, unsigned int size); uint16_t ptp_ek_settext (PTPParams* params, PTPEKTextParams *text); uint16_t ptp_ek_sendfileobjectinfo (PTPParams* params, uint32_t* store, uint32_t* parenthandle, uint32_t* handle, PTPObjectInfo* objectinfo); uint16_t ptp_ek_sendfileobject (PTPParams* params, unsigned char* object, uint32_t size); uint16_t ptp_ek_sendfileobject_from_handler (PTPParams* params, PTPDataHandler*, uint32_t size); /* Canon PTP extensions */ #define ptp_canon_9012(params) ptp_generic_no_data(params,0x9012,0) uint16_t ptp_canon_gettreeinfo (PTPParams* params, uint32_t* out); uint16_t ptp_canon_gettreesize (PTPParams* params, PTPCanon_directtransfer_entry**, unsigned int*cnt); uint16_t ptp_canon_getpartialobjectinfo (PTPParams* params, uint32_t handle, uint32_t p2, uint32_t* size, uint32_t* rp2); uint16_t ptp_canon_get_mac_address (PTPParams* params, unsigned char **mac); /** * ptp_canon_startshootingmode: * params: PTPParams* * * Starts shooting session. It emits a StorageInfoChanged * event via the interrupt pipe and pushes the StorageInfoChanged * and CANON_CameraModeChange events onto the event stack * (see operation PTP_OC_CANON_CheckEvent). * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_startshootingmode(params) ptp_generic_no_data(params,PTP_OC_CANON_InitiateReleaseControl,0) /** * ptp_canon_endshootingmode: * params: PTPParams* * * This operation is observed after pressing the Disconnect * button on the Remote Capture app. It emits a StorageInfoChanged * event via the interrupt pipe and pushes the StorageInfoChanged * and CANON_CameraModeChange events onto the event stack * (see operation PTP_OC_CANON_CheckEvent). * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_endshootingmode(params) ptp_generic_no_data(params,PTP_OC_CANON_TerminateReleaseControl,0) /** * ptp_canon_viewfinderon: * params: PTPParams* * * Prior to start reading viewfinder images, one must call this operation. * Supposedly, this operation affects the value of the CANON_ViewfinderMode * property. * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_viewfinderon(params) ptp_generic_no_data(params,PTP_OC_CANON_ViewfinderOn,0) /** * ptp_canon_viewfinderoff: * params: PTPParams* * * Before changing the shooting mode, or when one doesn't need to read * viewfinder images any more, one must call this operation. * Supposedly, this operation affects the value of the CANON_ViewfinderMode * property. * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_viewfinderoff(params) ptp_generic_no_data(params,PTP_OC_CANON_ViewfinderOff,0) /** * ptp_canon_reset_aeafawb: * params: PTPParams* * uint32_t flags - what shall be reset. * 1 - autoexposure * 2 - autofocus * 4 - autowhitebalance * * Called "Reset AeAfAwb" (auto exposure, focus, white balance) * * Return values: Some PTP_RC_* code. **/ #define PTP_CANON_RESET_AE 0x1 #define PTP_CANON_RESET_AF 0x2 #define PTP_CANON_RESET_AWB 0x4 #define ptp_canon_reset_aeafawb(params,flags) ptp_generic_no_data(params,PTP_OC_CANON_DoAeAfAwb,1,flags) uint16_t ptp_canon_checkevent (PTPParams* params, PTPContainer* event, int* isevent); /** * ptp_canon_focuslock: * * This operation locks the focus. It is followed by the CANON_GetChanges(?) * operation in the log. * It affects the CANON_MacroMode property. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_focuslock(params) ptp_generic_no_data(params,PTP_OC_CANON_FocusLock,0) /** * ptp_canon_focusunlock: * * This operation unlocks the focus. It is followed by the CANON_GetChanges(?) * operation in the log. * It sets the CANON_MacroMode property value to 1 (where it occurs in the log). * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_focusunlock(params) ptp_generic_no_data(params,PTP_OC_CANON_FocusUnlock,0) /** * ptp_canon_keepdeviceon: * * This operation sends a "ping" style message to the camera. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_keepdeviceon(params) ptp_generic_no_data(params,PTP_OC_CANON_KeepDeviceOn,0) /** * ptp_canon_eos_keepdeviceon: * * This operation sends a "ping" style message to the camera. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_eos_keepdeviceon(params) ptp_generic_no_data(params,PTP_OC_CANON_EOS_KeepDeviceOn,0) /** * ptp_canon_initiatecaptureinmemory: * * This operation starts the image capture according to the current camera * settings. When the capture has happened, the camera emits a CaptureComplete * event via the interrupt pipe and pushes the CANON_RequestObjectTransfer, * CANON_DeviceInfoChanged and CaptureComplete events onto the event stack * (see operation CANON_CheckEvent). From the CANON_RequestObjectTransfer * event's parameter one can learn the just captured image's ObjectHandle. * The image is stored in the camera's own RAM. * On the next capture the image will be overwritten! * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_initiatecaptureinmemory(params) ptp_generic_no_data(params,PTP_OC_CANON_InitiateCaptureInMemory,0) /** * ptp_canon_eos_requestdevicepropvalue: * * This operation sends a "ping" style message to the camera. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_eos_requestdevicepropvalue(params,prop) ptp_generic_no_data(params,PTP_OC_CANON_EOS_RequestDevicePropValue,1,prop) uint16_t ptp_canon_eos_capture (PTPParams* params, uint32_t *result); uint16_t ptp_canon_eos_getevent (PTPParams* params, PTPCanon_changes_entry **entries, int *nrofentries); uint16_t ptp_canon_getpartialobject (PTPParams* params, uint32_t handle, uint32_t offset, uint32_t size, uint32_t pos, unsigned char** block, uint32_t* readnum); uint16_t ptp_canon_getviewfinderimage (PTPParams* params, unsigned char** image, uint32_t* size); uint16_t ptp_canon_getchanges (PTPParams* params, uint16_t** props, uint32_t* propnum); uint16_t ptp_canon_getobjectinfo (PTPParams* params, uint32_t store, uint32_t p2, uint32_t parenthandle, uint32_t handle, PTPCANONFolderEntry** entries, uint32_t* entnum); uint16_t ptp_canon_eos_getdeviceinfo (PTPParams* params, PTPCanonEOSDeviceInfo*di); /** * ptp_canon_eos_setuilock: * * This command sets UI lock * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_eos_setuilock(params) ptp_generic_no_data(params,PTP_OC_CANON_EOS_SetUILock,0) /** * ptp_canon_eos_resetuilock: * * This command sets UI lock * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_eos_resetuilock(params) ptp_generic_no_data(params,PTP_OC_CANON_EOS_ResetUILock,0) /** * ptp_canon_eos_start_viewfinder: * * This command starts Viewfinder mode of newer Canon DSLRs. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_eos_start_viewfinder(params) ptp_generic_no_data(params,PTP_OC_CANON_EOS_InitiateViewfinder,0) /** * ptp_canon_eos_end_viewfinder: * * This command ends Viewfinder mode of newer Canon DSLRs. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_eos_end_viewfinder(params) ptp_generic_no_data(params,PTP_OC_CANON_EOS_TerminateViewfinder,0) uint16_t ptp_canon_eos_get_viewfinder_image (PTPParams* params, unsigned char **data, unsigned int *size); uint16_t ptp_canon_eos_get_viewfinder_image_handler (PTPParams* params, PTPDataHandler*); uint16_t ptp_canon_get_objecthandle_by_name (PTPParams* params, char* name, uint32_t* objectid); uint16_t ptp_canon_get_directory (PTPParams* params, PTPObjectHandles *handles, PTPObjectInfo **oinfos, uint32_t **flags); /** * ptp_canon_setobjectarchive: * * params: PTPParams* * uint32_t objectid * uint32_t flags * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_setobjectarchive(params,oid,flags) ptp_generic_no_data(params,PTP_OC_CANON_SetObjectArchive,2,oid,flags) uint16_t ptp_canon_get_customize_data (PTPParams* params, uint32_t themenr, unsigned char **data, unsigned int *size); uint16_t ptp_canon_getpairinginfo (PTPParams* params, uint32_t nr, unsigned char**, unsigned int*); uint16_t ptp_canon_eos_getstorageids (PTPParams* params, PTPStorageIDs* storageids); uint16_t ptp_canon_eos_getstorageinfo (PTPParams* params, uint32_t p1, unsigned char**, unsigned int*); uint16_t ptp_canon_eos_getpartialobject (PTPParams* params, uint32_t oid, uint32_t off, uint32_t xsize, unsigned char**data); uint16_t ptp_canon_eos_getobjectinfoex (PTPParams* params, uint32_t storageid, uint32_t objectid, uint32_t unk, PTPCANONFolderEntry **entries, unsigned int *nrofentries); uint16_t ptp_canon_eos_setdevicepropvalueex (PTPParams* params, unsigned char* data, unsigned int size); #define ptp_canon_eos_setremotemode(params,p1) ptp_generic_no_data(params,PTP_OC_CANON_EOS_SetRemoteMode,1,p1) #define ptp_canon_eos_seteventmode(params,p1) ptp_generic_no_data(params,PTP_OC_CANON_EOS_SetEventMode,1,p1) /** * ptp_canon_eos_transfercomplete: * * This ends a direct object transfer from an EOS camera. * * params: PTPParams* * oid Object ID * * Return values: Some PTP_RC_* code. * */ #define ptp_canon_eos_transfercomplete(params,oid) ptp_generic_no_data(params,PTP_OC_CANON_EOS_TransferComplete,1,oid) /* inHDD = %d, inLength =%d, inReset = %d */ #define ptp_canon_eos_pchddcapacity(params,p1,p2,p3) ptp_generic_no_data(params,PTP_OC_CANON_EOS_PCHDDCapacity,3,p1,p2,p3) uint16_t ptp_canon_eos_bulbstart (PTPParams* params); uint16_t ptp_canon_eos_bulbend (PTPParams* params); uint16_t ptp_canon_eos_getdevicepropdesc (PTPParams* params, uint16_t propcode, PTPDevicePropDesc *devicepropertydesc); uint16_t ptp_canon_eos_setdevicepropvalue (PTPParams* params, uint16_t propcode, PTPPropertyValue* value, uint16_t datatype); uint16_t ptp_nikon_get_vendorpropcodes (PTPParams* params, uint16_t **props, unsigned int *size); uint16_t ptp_nikon_curve_download (PTPParams* params, unsigned char **data, unsigned int *size); uint16_t ptp_nikon_getptpipinfo (PTPParams* params, unsigned char **data, unsigned int *size); uint16_t ptp_nikon_getwifiprofilelist (PTPParams* params); uint16_t ptp_nikon_writewifiprofile (PTPParams* params, PTPNIKONWifiProfile* profile); /** * ptp_nikon_deletewifiprofile: * * This command deletes a wifi profile. * * params: PTPParams* * unsigned int profilenr - profile number * * Return values: Some PTP_RC_* code. * **/ #define ptp_nikon_deletewifiprofile(params,profilenr) ptp_generic_no_data(params,PTP_OC_NIKON_DeleteProfile,1,profilenr) /** * ptp_nikon_setcontrolmode: * * This command can switch the camera to full PC control mode. * * params: PTPParams* * uint32_t mode - mode * * Return values: Some PTP_RC_* code. * **/ #define ptp_nikon_setcontrolmode(params,mode) ptp_generic_no_data(params,PTP_OC_NIKON_SetControlMode,1,mode) /** * ptp_nikon_afdrive: * * This command runs (drives) the lens autofocus. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ #define ptp_nikon_afdrive(params) ptp_generic_no_data(params,PTP_OC_NIKON_AfDrive,0) /** * ptp_canon_eos_afdrive: * * This command runs (drives) the lens autofocus. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_eos_afdrive(params) ptp_generic_no_data(params,PTP_OC_CANON_EOS_DoAf,0) /** * ptp_canon_eos_zoom: * * This command runs (drives) the lens autofocus. * * params: PTPParams* * params: arg1 unknown * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_eos_zoom(params,x) ptp_generic_no_data(params,PTP_OC_CANON_EOS_Zoom,1,x) #define ptp_canon_eos_zoomposition(params,x,y) ptp_generic_no_data(params,PTP_OC_CANON_EOS_ZoomPosition,2,x,y) #define ptp_canon_eos_remotereleaseon(params,x) ptp_generic_no_data(params,PTP_OC_CANON_EOS_RemoteReleaseOn,2,x,1) #define ptp_canon_eos_remotereleaseoff(params,x) ptp_generic_no_data(params,PTP_OC_CANON_EOS_RemoteReleaseOff,1,x) /** * ptp_nikon_mfdrive: * * This command runs (drives) the lens focus manually. * * params: PTPParams* * flag: 0x1 for (no limit - closest), 0x2 for (closest - no limit) * amount: amount of steps * * Return values: Some PTP_RC_* code. * **/ #define ptp_nikon_mfdrive(params,flag,amount) ptp_generic_no_data(params,PTP_OC_NIKON_MfDrive,2,flag,amount) /** * ptp_canon_eos_drivelens: * * This command runs (drives) the lens focus manually. * * params: PTPParams* * amount: 0x1-0x3 for near range, 0x8001-0x8003 for far range. * * Return values: Some PTP_RC_* code. * **/ #define ptp_canon_eos_drivelens(params,amount) ptp_generic_no_data(params,PTP_OC_CANON_EOS_DriveLens,1,amount) /** * ptp_nikon_capture: * * This command captures a picture on the Nikon. * * params: PTPParams* * uint32_t x - unknown parameter. seen to be -1. * * Return values: Some PTP_RC_* code. * **/ #define ptp_nikon_capture(params,x) ptp_generic_no_data(params,PTP_OC_NIKON_Capture,1,x) /** * ptp_nikon_capture_sdram: * * This command captures a picture on the Nikon. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ #define ptp_nikon_capture_sdram(params) ptp_generic_no_data(params,PTP_OC_NIKON_AfCaptureSDRAM,0) /** * ptp_nikon_delete_sdram_image: * * This command deletes the current SDRAM image * * params: PTPParams* * uint32_t oid * * Return values: Some PTP_RC_* code. * **/ #define ptp_nikon_delete_sdram_image(params,oid) ptp_generic_no_data(params,PTP_OC_NIKON_DelImageSDRAM,1,oid) /** * ptp_nikon_start_liveview: * * This command starts LiveView mode of newer Nikons DSLRs. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ #define ptp_nikon_start_liveview(params) ptp_generic_no_data(params,PTP_OC_NIKON_StartLiveView,0) uint16_t ptp_nikon_get_liveview_image (PTPParams* params, unsigned char**,unsigned int*); uint16_t ptp_nikon_get_preview_image (PTPParams* params, unsigned char**, unsigned int*, uint32_t*); /** * ptp_nikon_end_liveview: * * This command ends LiveView mode of newer Nikons DSLRs. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ #define ptp_nikon_end_liveview(params) ptp_generic_no_data(params,PTP_OC_NIKON_EndLiveView,0) uint16_t ptp_nikon_check_event (PTPParams* params, PTPContainer **evt, int *evtcnt); uint16_t ptp_nikon_getfileinfoinblock (PTPParams* params, uint32_t p1, uint32_t p2, uint32_t p3, unsigned char **data, unsigned int *size); /** * ptp_nikon_device_ready: * * This command checks if the device is ready. Used after * a capture. * * params: PTPParams* * * Return values: Some PTP_RC_* code. * **/ #define ptp_nikon_device_ready(params) ptp_generic_no_data (params, PTP_OC_NIKON_DeviceReady, 0) uint16_t ptp_mtp_getobjectpropssupported (PTPParams* params, uint16_t ofc, uint32_t *propnum, uint16_t **props); /* Android MTP Extensions */ uint16_t ptp_android_getpartialobject64 (PTPParams* params, uint32_t handle, uint64_t offset, uint32_t maxbytes, unsigned char** object, uint32_t *len); #define ptp_android_begineditobject(params,handle) ptp_generic_no_data (params, PTP_OC_ANDROID_BeginEditObject, 1, handle); #define ptp_android_truncate(params,handle,offset) ptp_generic_no_data (params, PTP_OC_ANDROID_TruncateObject, 3, handle, (offset & 0xFFFFFFFF), (offset >> 32)); uint16_t ptp_android_sendpartialobject (PTPParams *params, uint32_t handle, uint64_t offset, unsigned char *object, uint32_t len); #define ptp_android_endeditobject(params,handle) ptp_generic_no_data (params, PTP_OC_ANDROID_EndEditObject, 1, handle); /* Non PTP protocol functions */ static inline int ptp_operation_issupported(PTPParams* params, uint16_t operation) { unsigned int i=0; for (;ideviceinfo.OperationsSupported_len;i++) { if (params->deviceinfo.OperationsSupported[i]==operation) return 1; } return 0; } int ptp_event_issupported (PTPParams* params, uint16_t event); int ptp_property_issupported (PTPParams* params, uint16_t property); void ptp_free_devicepropdesc (PTPDevicePropDesc* dpd); void ptp_free_devicepropvalue (uint16_t dt, PTPPropertyValue* dpd); void ptp_free_objectpropdesc (PTPObjectPropDesc* dpd); void ptp_free_params (PTPParams *params); void ptp_free_objectinfo (PTPObjectInfo *oi); void ptp_free_object (PTPObject *oi); const char *ptp_strerror(uint16_t error); void ptp_perror (PTPParams* params, uint16_t error); void ptp_debug (PTPParams *params, const char *format, ...); void ptp_error (PTPParams *params, const char *format, ...); const char* ptp_get_property_description(PTPParams* params, uint16_t dpc); int ptp_render_property_value(PTPParams* params, uint16_t dpc, PTPDevicePropDesc *dpd, int length, char *out); int ptp_render_ofc(PTPParams* params, uint16_t ofc, int spaceleft, char *txt); int ptp_render_opcode(PTPParams* params, uint16_t opcode, int spaceleft, char *txt); int ptp_render_mtp_propname(uint16_t propid, int spaceleft, char *txt); MTPProperties *ptp_get_new_object_prop_entry(MTPProperties **props, int *nrofprops); void ptp_destroy_object_prop(MTPProperties *prop); void ptp_destroy_object_prop_list(MTPProperties *props, int nrofprops); MTPProperties *ptp_find_object_prop_in_cache(PTPParams *params, uint32_t const handle, uint32_t const attribute_id); void ptp_remove_object_from_cache(PTPParams *params, uint32_t handle); uint16_t ptp_add_object_to_cache(PTPParams *params, uint32_t handle); uint16_t ptp_object_want (PTPParams *, uint32_t handle, int want, PTPObject**retob); void ptp_objects_sort (PTPParams *); uint16_t ptp_object_find (PTPParams *params, uint32_t handle, PTPObject **retob); uint16_t ptp_object_find_or_insert (PTPParams *params, uint32_t handle, PTPObject **retob); /* ptpip.c */ void ptp_nikon_getptpipguid (unsigned char* guid); enum PTP_CHDK_Command { PTP_CHDK_Shutdown = 0, /* param2 is 0 (hard), 1 (soft), 2 (reboot) or 3 (reboot fw update) if param2 == 3, then filename of fw update is send as data (empty for default) */ PTP_CHDK_GetMemory, /* param2 is base address (or 0 for live image buffer, 1 for bitmap buffer) param3 is size (in bytes) return data is memory block */ PTP_CHDK_SetMemoryLong, /* param2 is address param3 is value */ PTP_CHDK_CallFunction, /* data is array of function pointer and (long) arguments (max: 10 args) return param1 is return value */ PTP_CHDK_GetPropCase, /* param2 is base id param3 is number of properties return data is array of longs */ PTP_CHDK_GetParamData, /* param2 is base id param3 is number of parameters return data is sequence of strings prefixed by their length (as long) */ PTP_CHDK_TempData, /* data is data to be stored for later */ PTP_CHDK_UploadFile, /* data is 4-byte length of filename, followed by filename and contents */ PTP_CHDK_DownloadFile, /* preceded by PTP_CHDK_TempData with filename return data are file contents */ PTP_CHDK_SwitchMode, /* param2 is 0 (playback) or 1 (record) */ PTP_CHDK_ExecuteLUA, /* data is script to be executed */ PTP_CHDK_GetVideoSettings, PTP_CHDK_GetScriptOutput, /* return script output in ASCIIZ */ PTP_CHDK_OpenDir, /* open directory listing, data is directory name */ PTP_CHDK_ReadDir, /* return data is next file info */ PTP_CHDK_CloseDir, /* close directory listing */ PTP_CHDK_GetShootingModesList, /* not used */ PTP_CHDK_StartDownloadFile, PTP_CHDK_ResumeDownloadFile, PTP_CHDK_EndDownloadFile, }; #define PTP_OC_CHDK 0x9999 typedef struct tagptp_chdk_videosettings { long live_image_buffer_width; long live_image_width; long live_image_height; long bitmap_buffer_width; long bitmap_width; long bitmap_height; unsigned palette[16]; } ptp_chdk_videosettings; #define ptp_chdk_shutdown_hard(params) ptp_generic_no_data(params,PTP_OC_CHDK,2,PTP_CHDK_Shutdown,0) #define ptp_chdk_shutdown_soft(params) ptp_generic_no_data(params,PTP_OC_CHDK,2,PTP_CHDK_Shutdown,1) #define ptp_chdk_reboot(params) ptp_generic_no_data(params,PTP_OC_CHDK,2,PTP_CHDK_Shutdown,2) #define ptp_chdk_reboot_fw_update(params) ptp_generic_no_data(params,PTP_OC_CHDK,2,PTP_CHDK_Shutdown,3) uint16_t ptp_chdk_get_memory(PTPParams* params, int start, int num, unsigned char**); #define ptp_chdk_set_memory_long(params,addr,val) ptp_generic_no_data(params,PTP_OC_CHDK,3,PTP_CHDK_SetMemoryLong,addr,val) uint16_t ptp_chdk_call(PTPParams* params, int *args, int size, int *ret); uint16_t ptp_chdk_get_propcase(PTPParams* params, int start, int num, int* ints); uint16_t ptp_chdk_get_paramdata(PTPParams* params, int start, int num, unsigned char** x); #define ptp_chdk_switch_mode(params,mode) ptp_generic_no_data(params,PTP_OC_CHDK,2,PTP_CHDK_SwitchMode,mode) uint16_t ptp_chdk_exec_lua(PTPParams *params, char *script, uint32_t* ret); uint16_t ptp_chdk_get_script_output(PTPParams* params, char **output ); uint16_t ptp_chdk_get_video_settings(PTPParams* params, ptp_chdk_videosettings* vsettings); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __PTP_H__ */ libmtp-1.1.6-20-g1b9f164/src/mtpz.c0000664000175000017500000023716112205614637016651 0ustar glowwormglowworm/** * \file mtpz.c * * Copyright (C) 2011-2012 Sajid Anwar * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * This file provides mtp zune cryptographic setup interfaces. * It is also used with Windows Phone 7, but Microsoft/Nokiad seem * to have discontinued MTPZ on Windows Phone 8. * * DISCLAIMER: * * The intention of this implementation is for users to be able * to interoperate with their devices, i.e. copy music to them in * operating systems other than Microsoft Windows, so it can be * played back on the device. We do not provide encryption keys * and constants in libmtp, we never will. You have to have these * on file in your home directory in $HOME/.mtpz-data, and we suggest * that you talk to Microsoft about providing the proper numbers if * you want to use this facility. */ #include "config.h" #include "libmtp.h" #include "unicode.h" #include "ptp.h" #include "libusb-glue.h" #include "device-flags.h" #include "playlist-spl.h" #include "util.h" #include "mtpz.h" #include #include #include #include #include #include #include #include /* Microsoft MTPZ extensions */ /* * The ~/.mtpz-data file contains all four necessary pieces of data: * * encryption key * public exponent * modulus * private key * certificate data * * These four pieces of data are each stored in hex representation, * separated by newline characters. * * If you know of a published, public reference for one of these * arrays of data, please inform us, so we can include it here and * drop it from the external file. Even better is if you convince * Microsoft to officially provide keys to this project. */ static unsigned char *MTPZ_ENCRYPTION_KEY; static unsigned char *MTPZ_PUBLIC_EXPONENT; static unsigned char *MTPZ_MODULUS; static unsigned char *MTPZ_PRIVATE_KEY; static char *MTPZ_CERTIFICATES; // Strip the trailing newline from fgets(). static char *fgets_strip(char * str, int num, FILE * stream) { char *result = str; if ((result = fgets(str, num, stream))) { size_t newlen = strlen(result); if (result[newlen - 1] == '\n') result[newlen - 1] = '\0'; } return result; } static char *hex_to_bytes(char *hex, size_t len) { if (len % 2) return NULL; char *bytes = malloc(len / 2); unsigned int u; int i = 0; while (i < len && sscanf(hex + i, "%2x", &u) == 1) { bytes[i / 2] = u; i += 2; } return bytes; } int mtpz_loaddata() { char *home = getenv("HOME"); if (!home) { LIBMTP_INFO("Unable to determine user's home directory, MTPZ disabled"); return -1; } int plen = strlen(home) + strlen("/.mtpz-data") + 1; char path[plen]; sprintf(path, "%s/.mtpz-data", home); FILE *fdata = fopen(path, "r"); if (!fdata) { LIBMTP_INFO("Unable to open ~/.mtpz-data for reading, MTPZ disabled."); return -1; } // Should only be six characters in length, but fgets will encounter a newline and stop. MTPZ_PUBLIC_EXPONENT = (unsigned char *)fgets_strip((char *)malloc(8), 8, fdata); if (!MTPZ_PUBLIC_EXPONENT) { LIBMTP_INFO("Unable to read MTPZ public exponent from ~/.mtpz-data, MTPZ disabled"); return -1; } // Should only be 33 characters in length, but fgets will encounter a newline and stop. char *hexenckey = (unsigned char *)fgets_strip((char *)malloc(35), 35, fdata); if (!hexenckey) { LIBMTP_INFO("Unable to read MTPZ encryption key from ~/.mtpz-data, MTPZ disabled"); return -1; } MTPZ_ENCRYPTION_KEY = hex_to_bytes(hexenckey, strlen(hexenckey)); if (!MTPZ_ENCRYPTION_KEY) { LIBMTP_INFO("Unable to read MTPZ encryption key from ~/.mtpz-data, MTPZ disabled"); } // Should only be 256 characters in length, but fgets will encounter a newline and stop. MTPZ_MODULUS = (unsigned char *)fgets_strip((char *)malloc(260), 260, fdata); if (!MTPZ_MODULUS) { LIBMTP_INFO("Unable to read MTPZ modulus from ~/.mtpz-data, MTPZ disabled"); return -1; } // Should only be 256 characters in length, but fgets will encounter a newline and stop. MTPZ_PRIVATE_KEY = (unsigned char *)fgets_strip((char *)malloc(260), 260, fdata); if (!MTPZ_PRIVATE_KEY) { LIBMTP_INFO("Unable to read MTPZ private key from ~/.mtpz-data, MTPZ disabled"); return -1; } // Should only be 1258 characters in length, but fgets will encounter the end of the file and stop. char *hexcerts = fgets_strip((char *)malloc(1260), 1260, fdata); if (!hexcerts) { LIBMTP_INFO("Unable to read MTPZ certificates from ~/.mtpz-data, MTPZ disabled"); return -1; } MTPZ_CERTIFICATES = hex_to_bytes(hexcerts, strlen(hexcerts)); if (!MTPZ_CERTIFICATES) { LIBMTP_INFO("Unable to parse MTPZ certificates from ~/.mtpz-data, MTPZ disabled"); return -1; } return 0; } /* MTPZ RSA */ typedef struct mtpz_rsa_struct { gcry_sexp_t privkey; gcry_sexp_t pubkey; } mtpz_rsa_t; mtpz_rsa_t *mtpz_rsa_init(const unsigned char *modulus, const unsigned char *priv_key, const unsigned char *pub_exp); void mtpz_rsa_free(mtpz_rsa_t *); int mtpz_rsa_decrypt(int flen, unsigned char *from, int tlen, unsigned char *to, mtpz_rsa_t *rsa); int mtpz_rsa_sign(int flen, unsigned char *from, int tlen, unsigned char *to, mtpz_rsa_t *rsa); /* MTPZ hashing */ #define MTPZ_HASHSTATE_84 5 #define MTPZ_HASHSTATE_88 6 static char *mtpz_hash_init_state(); static void mtpz_hash_reset_state(char *); static void mtpz_hash_transform_hash(char *, char *, int); static void mtpz_hash_finalize_hash(char *, char *); static char *mtpz_hash_custom6A5DC(char *, char *, int, int); static void mtpz_hash_compute_hash(char *, char *, int); static unsigned int mtpz_hash_f(int s, unsigned int x, unsigned int y, unsigned int z); static unsigned int mtpz_hash_rotate_left(unsigned int x, int n); /* MTPZ encryption */ unsigned char mtpz_aes_rcon[]; unsigned char mtpz_aes_sbox[]; unsigned char mtpz_aes_invsbox[]; unsigned int mtpz_aes_ft1[]; unsigned int mtpz_aes_ft2[]; unsigned int mtpz_aes_ft3[]; unsigned int mtpz_aes_ft4[]; unsigned int mtpz_aes_rt1[]; unsigned int mtpz_aes_rt2[]; unsigned int mtpz_aes_rt3[]; unsigned int mtpz_aes_rt4[]; unsigned int mtpz_aes_gb11[]; unsigned int mtpz_aes_gb14[]; unsigned int mtpz_aes_gb13[]; unsigned int mtpz_aes_gb9[]; #define MTPZ_ENCRYPTIONLOBYTE(val) (((val) >> 24) & 0xFF) #define MTPZ_ENCRYPTIONBYTE1(val) (((val) >> 16) & 0xFF) #define MTPZ_ENCRYPTIONBYTE2(val) (((val) >> 8) & 0xFF) #define MTPZ_ENCRYPTIONBYTE3(val) (((val) >> 0) & 0xFF) #define MTPZ_SWAP(x) mtpz_bswap32(x) void mtpz_encryption_cipher(unsigned char *data, unsigned int len, char encrypt); void mtpz_encryption_cipher_advanced(unsigned char *key, unsigned int key_len, unsigned char *data, unsigned int data_len, char encrypt); unsigned char *mtpz_encryption_expand_key(unsigned char *constant, int key_len, int count, int *out_len); void mtpz_encryption_expand_key_inner(unsigned char *constant, int key_len, unsigned char **out, int *out_len); void mtpz_encryption_inv_mix_columns(unsigned char *expanded, int offset, int rounds); void mtpz_encryption_decrypt_custom(unsigned char *data, unsigned char *seed, unsigned char *expanded); void mtpz_encryption_encrypt_custom(unsigned char *data, unsigned char *seed, unsigned char *expanded); void mtpz_encryption_encrypt_mac(unsigned char *hash, unsigned int hash_length, unsigned char *seed, unsigned int seed_len, unsigned char *out); static inline uint32_t mtpz_bswap32(uint32_t x) { #if defined __GNUC__ && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) || defined(__clang__) return __builtin_bswap32(x); #else return (x >> 24) | ((x >> 8) & 0x0000ff00) | ((x << 8) & 0x00ff0000) | (x << 24); #endif } /* MTPZ RSA implementation */ mtpz_rsa_t *mtpz_rsa_init(const unsigned char *str_modulus, const unsigned char *str_privkey, const unsigned char *str_pubexp) { mtpz_rsa_t *rsa = (mtpz_rsa_t *)malloc(sizeof(mtpz_rsa_t)); memset(rsa, 0, sizeof(rsa)); gcry_mpi_t mpi_modulus, mpi_privkey, mpi_pubexp; gcry_mpi_scan(&mpi_modulus, GCRYMPI_FMT_HEX, str_modulus, 0, NULL); gcry_mpi_scan(&mpi_privkey, GCRYMPI_FMT_HEX, str_privkey, 0, NULL); gcry_mpi_scan(&mpi_pubexp, GCRYMPI_FMT_HEX, str_pubexp, 0, NULL); gcry_sexp_build(&rsa->privkey, NULL, "(private-key (rsa (n %m) (e %m) (d %m)))", mpi_modulus, mpi_pubexp, mpi_privkey); gcry_sexp_build(&rsa->pubkey, NULL, "(public-key (rsa (n %m) (e %m)))", mpi_modulus, mpi_pubexp); gcry_mpi_release(mpi_modulus); gcry_mpi_release(mpi_privkey); gcry_mpi_release(mpi_pubexp); return rsa; } void mtpz_rsa_free(mtpz_rsa_t *rsa) { gcry_sexp_release(rsa->privkey); gcry_sexp_release(rsa->pubkey); } int mtpz_rsa_decrypt(int flen, unsigned char *from, int tlen, unsigned char *to, mtpz_rsa_t *rsa) { gcry_mpi_t mpi_from; gcry_mpi_scan(&mpi_from, GCRYMPI_FMT_USG, from, flen, NULL); gcry_sexp_t sexp_data; gcry_sexp_build(&sexp_data, NULL, "(enc-val (flags raw) (rsa (a %m)))", mpi_from); gcry_sexp_t sexp_plain; gcry_pk_decrypt(&sexp_plain, sexp_data, rsa->privkey); gcry_mpi_t mpi_value = gcry_sexp_nth_mpi(sexp_plain, 1, GCRYMPI_FMT_USG); // Lame workaround. GCRYMPI_FMT_USG gets rid of any leading zeroes which we do need, // so we'll count how many bits are being used, and subtract that from how many bits actually // should be there, and then write into our output array shifted over however many bits/8. int bitshift = (tlen * 8) - gcry_mpi_get_nbits(mpi_value); size_t written; if (bitshift / 8) { memset(to, 0, bitshift / 8); to += bitshift / 8; tlen -= bitshift / 8; } gcry_mpi_print(GCRYMPI_FMT_USG, to, tlen, &written, mpi_value); gcry_mpi_release(mpi_from); gcry_mpi_release(mpi_value); gcry_sexp_release(sexp_data); gcry_sexp_release(sexp_plain); return (int)written; } int mtpz_rsa_sign(int flen, unsigned char *from, int tlen, unsigned char *to, mtpz_rsa_t *rsa) { return mtpz_rsa_decrypt(flen, from, tlen, to, rsa); } /* MTPZ hashing implementation */ static char *mtpz_hash_init_state() { char *s = (char *)malloc(92); if (s != NULL) memset(s, 0, 92); return s; } void mtpz_hash_reset_state(char *state) { int *state_box = (int *)(state + 64); /* * Constants from * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf * Page 13, section 5.3.1 */ state_box[0] = 0x67452301; state_box[1] = 0xefcdab89; state_box[2] = 0x98badcfe; state_box[3] = 0x10325476; state_box[4] = 0xc3d2e1f0; state_box[MTPZ_HASHSTATE_84] = 0; state_box[MTPZ_HASHSTATE_88] = 0; } void mtpz_hash_transform_hash(char *state, char *msg, int len) { int *state_box = (int *)(state + 64); int x = state_box[MTPZ_HASHSTATE_88] & 0x3F; int v5 = len + state_box[MTPZ_HASHSTATE_88]; state_box[MTPZ_HASHSTATE_88] = v5; int i = len, j = 0; int a1 = 0; int c = 0; if (len > v5) state_box[MTPZ_HASHSTATE_84] += 1; if (x) { if (len + x > 0x3F) { for (a1 = 0; a1 < 64 - x; a1++) { state[x + a1] = msg[a1]; } i = len + x - 64; j = 64 - x; mtpz_hash_compute_hash(state, state, 64); } } while (i > 63) { mtpz_hash_compute_hash(state, msg + j, 64); j += 64; i -= 64; } if (i != 0) { for (c = 0; c < i; c++) { state[x + c] = msg[j + c]; } } } // out has at least 20 bytes of space void mtpz_hash_finalize_hash(char *state, char *out) { int *state_box = (int *)(state + 64); int v2 = 64 - (state_box[MTPZ_HASHSTATE_88] & 0x3F); int v6, v7; if (v2 <= 8) v2 += 64; char *v5 = (char *)malloc(72); memset(v5, 0, 72); v5[0] = '\x80'; v6 = 8 * state_box[MTPZ_HASHSTATE_84] | (state_box[MTPZ_HASHSTATE_88] >> 29); v7 = 8 * state_box[MTPZ_HASHSTATE_88]; v6 = MTPZ_SWAP(v6); v7 = MTPZ_SWAP(v7); *(int *)(v5 + v2 - 8) = v6; *(int *)(v5 + v2 - 4) = v7; mtpz_hash_transform_hash(state, v5, v2); int *out_int = (int *)out; out_int[0] = MTPZ_SWAP(state_box[0]); out_int[1] = MTPZ_SWAP(state_box[1]); out_int[2] = MTPZ_SWAP(state_box[2]); out_int[3] = MTPZ_SWAP(state_box[3]); out_int[4] = MTPZ_SWAP(state_box[4]); memset(state, 0, 64); mtpz_hash_reset_state(state); } char *mtpz_hash_custom6A5DC(char *state, char *msg, int len, int a4) { int v11 = (a4 / 20) + 1; char *v13 = (char *)malloc(v11 * 20); char *v5 = (char *)malloc(len + 4); int i; int k; memset(v13, 0, v11 * 20); memset(v5, 0, len + 4); memcpy(v5, msg, len); for (i = 0; i < v11; i++) { k = MTPZ_SWAP(i); *(int *)(v5 + len) = k; mtpz_hash_reset_state(state); mtpz_hash_transform_hash(state, v5, len + 4); mtpz_hash_finalize_hash(state, v13 + i * 20); } free(v5); v5 = NULL; return v13; } void mtpz_hash_compute_hash(char *state, char *msg, int len) { int *state_box = (int *)(state + 64); const unsigned int K[] = { 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6 }; if (len != 64) return; int *M = (int *)msg; // HASH COMPUTATION unsigned int W[80]; unsigned int a, b, c, d, e; int i, s; unsigned int T; // 1 - prepare message schedule 'W'. for (i = 0; i < 16; i++) W[i] = MTPZ_SWAP(M[i]); for (i = 16; i < 80; i++) W[i] = mtpz_hash_rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); // 2 - initialize five working variables a, b, c, d, e with previous hash value a = state_box[0]; b = state_box[1]; c = state_box[2]; d = state_box[3]; e = state_box[4]; // 3 - main loop for (i = 0; i < 80; i++) { s = i / 20; T = (mtpz_hash_rotate_left(a, 5) + mtpz_hash_f(s, b, c, d) + e + K[s] + W[i]) & 0xFFFFFFFF; e = d; d = c; c = mtpz_hash_rotate_left(b, 30); b = a; a = T; } state_box[0] = (state_box[0] + a) & 0xFFFFFFFF; state_box[1] = (state_box[1] + b) & 0xFFFFFFFF; state_box[2] = (state_box[2] + c) & 0xFFFFFFFF; state_box[3] = (state_box[3] + d) & 0xFFFFFFFF; state_box[4] = (state_box[4] + e) & 0xFFFFFFFF; } unsigned int mtpz_hash_f(int s, unsigned int x, unsigned int y, unsigned int z) { switch (s) { case 0: return (x & y) ^ (~x & z); // Ch() case 1: return x ^ y ^ z; // Parity() case 2: return (x & y) ^ (x & z) ^ (y & z); // Maj() case 3: return x ^ y ^ z; // Parity() } return 0; } unsigned int mtpz_hash_rotate_left(unsigned int x, int n) { return (x << n) | (x >> (32 - n)); } /* MTPZ encryption implementation */ void mtpz_encryption_cipher(unsigned char *data, unsigned int len, char encrypt) { unsigned char *expanded = NULL; int offset = 0, count = len; if ((count & 0x0F) == 0) { int exp_len = 0; expanded = mtpz_encryption_expand_key((unsigned char *)MTPZ_ENCRYPTION_KEY, 16, 10, &exp_len); if (count != 0) { do { if (encrypt) mtpz_encryption_encrypt_custom(data + offset, NULL, expanded); else mtpz_encryption_decrypt_custom(data + offset, NULL, expanded); count -= 16; offset += 16; } while (count != 0); } } } void mtpz_encryption_cipher_advanced(unsigned char *key, unsigned int key_len, unsigned char *data, unsigned int data_len, char encrypt) { int len = (key_len == 16) ? 10 : (key_len == 24) ? 12 : 32; int exp_len; unsigned char *expanded = mtpz_encryption_expand_key(key, key_len, len, &exp_len); int offset = 0, count = data_len; unsigned char *out = (unsigned char *)malloc(16); unsigned int *out_int = (unsigned int *)out; unsigned int *data_int = (unsigned int *)data; unsigned int *dtf = (unsigned int *)malloc(16); memset((unsigned char *)dtf, 0, 16); while (count != 0) { int chunk = 16; if (count < 16) { memset(out, 0, 16); chunk = count; } memcpy(out, data + offset, chunk); if (encrypt) { out_int[0] ^= MTPZ_SWAP(dtf[0]); out_int[1] ^= MTPZ_SWAP(dtf[1]); out_int[2] ^= MTPZ_SWAP(dtf[2]); out_int[3] ^= MTPZ_SWAP(dtf[3]); mtpz_encryption_encrypt_custom(data + offset, out, expanded); dtf[0] = MTPZ_SWAP(data_int[(offset / 4) + 0]); dtf[1] = MTPZ_SWAP(data_int[(offset / 4) + 1]); dtf[2] = MTPZ_SWAP(data_int[(offset / 4) + 2]); dtf[3] = MTPZ_SWAP(data_int[(offset / 4) + 3]); } else { mtpz_encryption_decrypt_custom(data + offset, out, expanded); data_int[(offset / 4) + 0] ^= MTPZ_SWAP(dtf[0]); data_int[(offset / 4) + 1] ^= MTPZ_SWAP(dtf[1]); data_int[(offset / 4) + 2] ^= MTPZ_SWAP(dtf[2]); data_int[(offset / 4) + 3] ^= MTPZ_SWAP(dtf[3]); dtf[0] = MTPZ_SWAP(out_int[0]); dtf[1] = MTPZ_SWAP(out_int[1]); dtf[2] = MTPZ_SWAP(out_int[2]); dtf[3] = MTPZ_SWAP(out_int[3]); } offset += chunk; count -= chunk; } free(out); free(dtf); free(expanded); } unsigned char *mtpz_encryption_expand_key(unsigned char *constant, int key_len, int count, int *out_len) { int i = 0; int seek = 0; unsigned char *back = (unsigned char *)malloc(484); memset(back, 0, 484); *out_len = 484; unsigned char *inner; int inner_len; mtpz_encryption_expand_key_inner(constant, key_len, &inner, &inner_len); back[i] = (unsigned char)(count % 0xFF); i += 4; memcpy(back + i, inner, inner_len); i += inner_len; memcpy(back + i, inner, inner_len); i += inner_len; switch (count) { case 10: seek = 0xB4; break; case 12: seek = 0xD4; break; case 14: default: seek = 0xF4; break; } mtpz_encryption_inv_mix_columns(back, seek, count); return back; } void mtpz_encryption_expand_key_inner(unsigned char *constant, int key_len, unsigned char **out, int *out_len) { int ks = -1; int rcon_i = 0; int i = 0, j = 0; switch (key_len) { case 16: ks = 16 * (10 + 1); break; case 24: ks = 16 * (12 + 1); break; case 32: ks = 16 * (14 + 1); break; default: *out = NULL; *out_len = 0; } unsigned char *key = (unsigned char *)malloc(ks); unsigned char *temp = (unsigned char *)malloc(4); memcpy(key, constant, key_len); unsigned char t0, t1, t2, t3; for (i = key_len; i < ks; i += 4) { temp[0] = t0 = key[i - 4]; temp[1] = t1 = key[i - 3]; temp[2] = t2 = key[i - 2]; temp[3] = t3 = key[i - 1]; if (i % key_len == 0) { temp[0] = (mtpz_aes_sbox[t1] ^ mtpz_aes_rcon[rcon_i]) & 0xFF; temp[1] = mtpz_aes_sbox[t2]; temp[2] = mtpz_aes_sbox[t3]; temp[3] = mtpz_aes_sbox[t0]; rcon_i++; } else if ((key_len > 24) && (i % key_len == 16)) { temp[0] = mtpz_aes_sbox[t0]; temp[1] = mtpz_aes_sbox[t1]; temp[2] = mtpz_aes_sbox[t2]; temp[3] = mtpz_aes_sbox[t3]; } for (j = 0; j < 4; j++) { key[i + j] = (unsigned char)((key[i + j - key_len] ^ temp[j]) & 0xFF); } } free(temp); *out = key; *out_len = ks; } void mtpz_encryption_inv_mix_columns(unsigned char *expanded, int offset, int rounds) { int v8 = 1, o = offset; unsigned int *exp_int = NULL; for (v8 = 1; v8 < rounds; v8++) { exp_int = (unsigned int *)(expanded + o + 16); exp_int[0] = MTPZ_SWAP(mtpz_aes_gb9[expanded[o + 19]] ^ mtpz_aes_gb13[expanded[o + 18]] ^ mtpz_aes_gb11[expanded[o + 17]] ^ mtpz_aes_gb14[expanded[o + 16]]); exp_int[1] = MTPZ_SWAP(mtpz_aes_gb9[expanded[o + 23]] ^ mtpz_aes_gb13[expanded[o + 22]] ^ mtpz_aes_gb11[expanded[o + 21]] ^ mtpz_aes_gb14[expanded[o + 20]]); exp_int[2] = MTPZ_SWAP(mtpz_aes_gb9[expanded[o + 27]] ^ mtpz_aes_gb13[expanded[o + 26]] ^ mtpz_aes_gb11[expanded[o + 25]] ^ mtpz_aes_gb14[expanded[o + 24]]); exp_int[3] = MTPZ_SWAP(mtpz_aes_gb9[expanded[o + 31]] ^ mtpz_aes_gb13[expanded[o + 30]] ^ mtpz_aes_gb11[expanded[o + 29]] ^ mtpz_aes_gb14[expanded[o + 28]]); o += 16; } } void mtpz_encryption_decrypt_custom(unsigned char *data, unsigned char *seed, unsigned char *expanded) { unsigned int *u_data = (unsigned int *)data; unsigned int *u_expanded = (unsigned int *)expanded; int keyOffset = 0xB4 + 0xA0; unsigned int *u_seed; if (seed == NULL) u_seed = u_data; else u_seed = (unsigned int *)seed; unsigned int v14 = MTPZ_SWAP(u_seed[0]) ^ MTPZ_SWAP(u_expanded[(keyOffset ) / 4]); unsigned int v15 = MTPZ_SWAP(u_seed[1]) ^ MTPZ_SWAP(u_expanded[(keyOffset + 4) / 4]); unsigned int v16 = MTPZ_SWAP(u_seed[2]) ^ MTPZ_SWAP(u_expanded[(keyOffset + 8) / 4]); unsigned int v17 = MTPZ_SWAP(u_seed[3]) ^ MTPZ_SWAP(u_expanded[(keyOffset + 12) / 4]); unsigned int v18 = mtpz_aes_rt1[MTPZ_ENCRYPTIONBYTE3(v15)] ^ mtpz_aes_rt2[MTPZ_ENCRYPTIONBYTE2(v16)] ^ mtpz_aes_rt3[MTPZ_ENCRYPTIONLOBYTE(v14)] ^ mtpz_aes_rt4[MTPZ_ENCRYPTIONBYTE1(v17)]; unsigned int v19 = mtpz_aes_rt1[MTPZ_ENCRYPTIONBYTE3(v16)] ^ mtpz_aes_rt2[MTPZ_ENCRYPTIONBYTE2(v17)] ^ mtpz_aes_rt3[MTPZ_ENCRYPTIONLOBYTE(v15)] ^ mtpz_aes_rt4[MTPZ_ENCRYPTIONBYTE1(v14)]; unsigned int v20 = mtpz_aes_rt1[MTPZ_ENCRYPTIONBYTE3(v17)] ^ mtpz_aes_rt2[MTPZ_ENCRYPTIONBYTE2(v14)] ^ mtpz_aes_rt3[MTPZ_ENCRYPTIONLOBYTE(v16)] ^ mtpz_aes_rt4[MTPZ_ENCRYPTIONBYTE1(v15)]; unsigned int v21 = mtpz_aes_rt1[MTPZ_ENCRYPTIONBYTE3(v14)] ^ mtpz_aes_rt2[MTPZ_ENCRYPTIONBYTE2(v15)] ^ mtpz_aes_rt3[MTPZ_ENCRYPTIONLOBYTE(v17)] ^ mtpz_aes_rt4[MTPZ_ENCRYPTIONBYTE1(v16)]; keyOffset -= 16; int rounds = 9; do { v14 = v18 ^ MTPZ_SWAP(u_expanded[(keyOffset ) / 4]); v15 = v19 ^ MTPZ_SWAP(u_expanded[(keyOffset + 4) / 4]); v16 = v20 ^ MTPZ_SWAP(u_expanded[(keyOffset + 8) / 4]); v17 = v21 ^ MTPZ_SWAP(u_expanded[(keyOffset + 12) / 4]); v18 = mtpz_aes_rt1[MTPZ_ENCRYPTIONBYTE3(v15)] ^ mtpz_aes_rt2[MTPZ_ENCRYPTIONBYTE2(v16)] ^ mtpz_aes_rt3[MTPZ_ENCRYPTIONLOBYTE(v14)] ^ mtpz_aes_rt4[MTPZ_ENCRYPTIONBYTE1(v17)]; v19 = mtpz_aes_rt1[MTPZ_ENCRYPTIONBYTE3(v16)] ^ mtpz_aes_rt2[MTPZ_ENCRYPTIONBYTE2(v17)] ^ mtpz_aes_rt3[MTPZ_ENCRYPTIONLOBYTE(v15)] ^ mtpz_aes_rt4[MTPZ_ENCRYPTIONBYTE1(v14)]; v20 = mtpz_aes_rt1[MTPZ_ENCRYPTIONBYTE3(v17)] ^ mtpz_aes_rt2[MTPZ_ENCRYPTIONBYTE2(v14)] ^ mtpz_aes_rt3[MTPZ_ENCRYPTIONLOBYTE(v16)] ^ mtpz_aes_rt4[MTPZ_ENCRYPTIONBYTE1(v15)]; v21 = mtpz_aes_rt1[MTPZ_ENCRYPTIONBYTE3(v14)] ^ mtpz_aes_rt2[MTPZ_ENCRYPTIONBYTE2(v15)] ^ mtpz_aes_rt3[MTPZ_ENCRYPTIONLOBYTE(v17)] ^ mtpz_aes_rt4[MTPZ_ENCRYPTIONBYTE1(v16)]; rounds--; keyOffset -= 16; } while (rounds != 1); v14 = v18 ^ MTPZ_SWAP(u_expanded[(keyOffset ) / 4]); v15 = v19 ^ MTPZ_SWAP(u_expanded[(keyOffset + 4) / 4]); v16 = v20 ^ MTPZ_SWAP(u_expanded[(keyOffset + 8) / 4]); v17 = v21 ^ MTPZ_SWAP(u_expanded[(keyOffset + 12) / 4]); keyOffset -= 16; v18 = ((mtpz_aes_invsbox[MTPZ_ENCRYPTIONLOBYTE(v14)]) << 24) | ((mtpz_aes_invsbox[MTPZ_ENCRYPTIONBYTE1 (v17)]) << 16) | ((mtpz_aes_invsbox[MTPZ_ENCRYPTIONBYTE2 (v16)]) << 8) | ((mtpz_aes_invsbox[MTPZ_ENCRYPTIONBYTE3 (v15)]) << 0); v19 = ((mtpz_aes_invsbox[MTPZ_ENCRYPTIONLOBYTE(v15)]) << 24) | ((mtpz_aes_invsbox[MTPZ_ENCRYPTIONBYTE1 (v14)]) << 16) | ((mtpz_aes_invsbox[MTPZ_ENCRYPTIONBYTE2 (v17)]) << 8) | ((mtpz_aes_invsbox[MTPZ_ENCRYPTIONBYTE3 (v16)]) << 0); v20 = ((mtpz_aes_invsbox[MTPZ_ENCRYPTIONLOBYTE(v16)]) << 24) | ((mtpz_aes_invsbox[MTPZ_ENCRYPTIONBYTE1 (v15)]) << 16) | ((mtpz_aes_invsbox[MTPZ_ENCRYPTIONBYTE2 (v14)]) << 8) | ((mtpz_aes_invsbox[MTPZ_ENCRYPTIONBYTE3 (v17)]) << 0); v21 = ((mtpz_aes_invsbox[MTPZ_ENCRYPTIONLOBYTE(v17)]) << 24) | ((mtpz_aes_invsbox[MTPZ_ENCRYPTIONBYTE1 (v16)]) << 16) | ((mtpz_aes_invsbox[MTPZ_ENCRYPTIONBYTE2 (v15)]) << 8) | ((mtpz_aes_invsbox[MTPZ_ENCRYPTIONBYTE3 (v14)]) << 0); u_data[0] = MTPZ_SWAP(v18 ^ MTPZ_SWAP(u_expanded[(keyOffset ) / 4])); u_data[1] = MTPZ_SWAP(v19 ^ MTPZ_SWAP(u_expanded[(keyOffset + 4) / 4])); u_data[2] = MTPZ_SWAP(v20 ^ MTPZ_SWAP(u_expanded[(keyOffset + 8) / 4])); u_data[3] = MTPZ_SWAP(v21 ^ MTPZ_SWAP(u_expanded[(keyOffset + 12) / 4])); }; void mtpz_encryption_encrypt_custom(unsigned char *data, unsigned char *seed, unsigned char *expanded) { unsigned int *u_data = (unsigned int *)data; unsigned int *u_expanded = (unsigned int *)expanded; int keyOffset = 0x04; unsigned int *u_seed; if (seed == NULL) u_seed = u_data; else u_seed = (unsigned int *)seed; unsigned int v14 = MTPZ_SWAP(u_seed[0]) ^ MTPZ_SWAP(u_expanded[(keyOffset ) / 4]); unsigned int v15 = MTPZ_SWAP(u_seed[1]) ^ MTPZ_SWAP(u_expanded[(keyOffset + 4) / 4]); unsigned int v16 = MTPZ_SWAP(u_seed[2]) ^ MTPZ_SWAP(u_expanded[(keyOffset + 8) / 4]); unsigned int v17 = MTPZ_SWAP(u_seed[3]) ^ MTPZ_SWAP(u_expanded[(keyOffset + 12) / 4]); unsigned int v18 = mtpz_aes_ft1[MTPZ_ENCRYPTIONBYTE3(v17)] ^ mtpz_aes_ft2[MTPZ_ENCRYPTIONBYTE2(v16)] ^ mtpz_aes_ft3[MTPZ_ENCRYPTIONLOBYTE(v14)] ^ mtpz_aes_ft4[MTPZ_ENCRYPTIONBYTE1(v15)]; unsigned int v19 = mtpz_aes_ft1[MTPZ_ENCRYPTIONBYTE3(v14)] ^ mtpz_aes_ft2[MTPZ_ENCRYPTIONBYTE2(v17)] ^ mtpz_aes_ft3[MTPZ_ENCRYPTIONLOBYTE(v15)] ^ mtpz_aes_ft4[MTPZ_ENCRYPTIONBYTE1(v16)]; unsigned int v20 = mtpz_aes_ft1[MTPZ_ENCRYPTIONBYTE3(v15)] ^ mtpz_aes_ft2[MTPZ_ENCRYPTIONBYTE2(v14)] ^ mtpz_aes_ft3[MTPZ_ENCRYPTIONLOBYTE(v16)] ^ mtpz_aes_ft4[MTPZ_ENCRYPTIONBYTE1(v17)]; unsigned int v21 = mtpz_aes_ft1[MTPZ_ENCRYPTIONBYTE3(v16)] ^ mtpz_aes_ft2[MTPZ_ENCRYPTIONBYTE2(v15)] ^ mtpz_aes_ft3[MTPZ_ENCRYPTIONLOBYTE(v17)] ^ mtpz_aes_ft4[MTPZ_ENCRYPTIONBYTE1(v14)]; keyOffset += 16; int rounds = 1; do { v14 = v18 ^ MTPZ_SWAP(u_expanded[(keyOffset ) / 4]); v15 = v19 ^ MTPZ_SWAP(u_expanded[(keyOffset + 4) / 4]); v16 = v20 ^ MTPZ_SWAP(u_expanded[(keyOffset + 8) / 4]); v17 = v21 ^ MTPZ_SWAP(u_expanded[(keyOffset + 12) / 4]); v18 = mtpz_aes_ft1[MTPZ_ENCRYPTIONBYTE3(v17)] ^ mtpz_aes_ft2[MTPZ_ENCRYPTIONBYTE2(v16)] ^ mtpz_aes_ft3[MTPZ_ENCRYPTIONLOBYTE(v14)] ^ mtpz_aes_ft4[MTPZ_ENCRYPTIONBYTE1(v15)]; v19 = mtpz_aes_ft1[MTPZ_ENCRYPTIONBYTE3(v14)] ^ mtpz_aes_ft2[MTPZ_ENCRYPTIONBYTE2(v17)] ^ mtpz_aes_ft3[MTPZ_ENCRYPTIONLOBYTE(v15)] ^ mtpz_aes_ft4[MTPZ_ENCRYPTIONBYTE1(v16)]; v20 = mtpz_aes_ft1[MTPZ_ENCRYPTIONBYTE3(v15)] ^ mtpz_aes_ft2[MTPZ_ENCRYPTIONBYTE2(v14)] ^ mtpz_aes_ft3[MTPZ_ENCRYPTIONLOBYTE(v16)] ^ mtpz_aes_ft4[MTPZ_ENCRYPTIONBYTE1(v17)]; v21 = mtpz_aes_ft1[MTPZ_ENCRYPTIONBYTE3(v16)] ^ mtpz_aes_ft2[MTPZ_ENCRYPTIONBYTE2(v15)] ^ mtpz_aes_ft3[MTPZ_ENCRYPTIONLOBYTE(v17)] ^ mtpz_aes_ft4[MTPZ_ENCRYPTIONBYTE1(v14)]; rounds++; keyOffset += 16; } while (rounds != 9); v14 = v18 ^ MTPZ_SWAP(u_expanded[(keyOffset ) / 4]); v15 = v19 ^ MTPZ_SWAP(u_expanded[(keyOffset + 4) / 4]); v16 = v20 ^ MTPZ_SWAP(u_expanded[(keyOffset + 8) / 4]); v17 = v21 ^ MTPZ_SWAP(u_expanded[(keyOffset + 12) / 4]); keyOffset += 16; unsigned char *FT3_Bytes = (unsigned char *)mtpz_aes_ft3; v18 = ((FT3_Bytes[1 + 4 * MTPZ_ENCRYPTIONLOBYTE(v14)]) << 24) | ((FT3_Bytes[1 + 4 * MTPZ_ENCRYPTIONBYTE1 (v15)]) << 16) | ((FT3_Bytes[1 + 4 * MTPZ_ENCRYPTIONBYTE2 (v16)]) << 8) | ((FT3_Bytes[1 + 4 * MTPZ_ENCRYPTIONBYTE3 (v17)]) << 0); v19 = ((FT3_Bytes[1 + 4 * MTPZ_ENCRYPTIONLOBYTE(v15)]) << 24) | ((FT3_Bytes[1 + 4 * MTPZ_ENCRYPTIONBYTE1 (v16)]) << 16) | ((FT3_Bytes[1 + 4 * MTPZ_ENCRYPTIONBYTE2 (v17)]) << 8) | ((FT3_Bytes[1 + 4 * MTPZ_ENCRYPTIONBYTE3 (v14)]) << 0); v20 = ((FT3_Bytes[1 + 4 * MTPZ_ENCRYPTIONLOBYTE(v16)]) << 24) | ((FT3_Bytes[1 + 4 * MTPZ_ENCRYPTIONBYTE1 (v17)]) << 16) | ((FT3_Bytes[1 + 4 * MTPZ_ENCRYPTIONBYTE2 (v14)]) << 8) | ((FT3_Bytes[1 + 4 * MTPZ_ENCRYPTIONBYTE3 (v15)]) << 0); v21 = ((FT3_Bytes[1 + 4 * MTPZ_ENCRYPTIONLOBYTE(v17)]) << 24) | ((FT3_Bytes[1 + 4 * MTPZ_ENCRYPTIONBYTE1 (v14)]) << 16) | ((FT3_Bytes[1 + 4 * MTPZ_ENCRYPTIONBYTE2 (v15)]) << 8) | ((FT3_Bytes[1 + 4 * MTPZ_ENCRYPTIONBYTE3 (v16)]) << 0); u_data[0] = MTPZ_SWAP(v18 ^ MTPZ_SWAP(u_expanded[(keyOffset ) / 4])); u_data[1] = MTPZ_SWAP(v19 ^ MTPZ_SWAP(u_expanded[(keyOffset + 4) / 4])); u_data[2] = MTPZ_SWAP(v20 ^ MTPZ_SWAP(u_expanded[(keyOffset + 8) / 4])); u_data[3] = MTPZ_SWAP(v21 ^ MTPZ_SWAP(u_expanded[(keyOffset + 12) / 4])); } void mtpz_encryption_encrypt_mac(unsigned char *hash, unsigned int hash_length, unsigned char *seed, unsigned int seed_len, unsigned char *out) { if (hash == NULL || hash_length != 16) return; unsigned char *loop1 = (unsigned char *)malloc(17); memset(loop1, 0, 17); unsigned char *loop2 = (unsigned char *)malloc(17); memset(loop2, 0, 17); int i = 0; { unsigned char *enc_hash = (unsigned char *)malloc(17); memset(enc_hash, 0, 17); mtpz_encryption_cipher_advanced(hash, hash_length, enc_hash, 16, 1); for (i = 0; i < 16; i++) loop1[i] = (unsigned char)((2 * enc_hash[i]) | (enc_hash[i + 1] >> 7)); if (enc_hash[0] >= (unsigned char)128) loop1[15] ^= (unsigned char)0x87; for (i = 0; i < 16; i++) loop2[i] = (unsigned char)((2 * loop1[i]) | (loop1[i + 1] >> 7)); if (loop1[0] >= (unsigned char)128) loop2[15] ^= (unsigned char)0x87; free(enc_hash); } { int len = (hash_length == 16) ? 10 : (hash_length == 24) ? 12 : 32; int exp_len; unsigned char *expanded = mtpz_encryption_expand_key(hash, hash_length, len, &exp_len); unsigned char *actual_seed = (unsigned char *)malloc(16); memset(actual_seed, 0, 16); int i = 0; if (seed_len == 16) { for (i = 0; i < 16; i++) actual_seed[i] ^= seed[i]; for (i = 0; i < 16; i++) actual_seed[i] ^= loop1[i]; } else { for (i = 0; i < seed_len; i++) actual_seed[i] ^= seed[i]; actual_seed[seed_len] = (unsigned char)128; for (i = 0; i < 16; i++) actual_seed[i] ^= loop2[i]; } mtpz_encryption_encrypt_custom(out, actual_seed, expanded); free(expanded); free(actual_seed); } free(loop1); free(loop2); } /* ENCRYPTION CONSTANTS */ /* * These tables can also be found in Mozilla's Network Security Services: * http://www.mozilla.org/projects/security/pki/nss/ * * : * https://hg.mozilla.org/mozilla-central/raw-file/90828ac18dcf/security/nss/lib/freebl/rijndael32.tab * * Each of the following constant tables will also identify the corresponding * table in the link. */ /* Corresponds to Rcon[30] (seems to be truncated to include only the used constants) */ unsigned char mtpz_aes_rcon[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a }; /* Corresponds to _S[256] (in hex) */ unsigned char mtpz_aes_sbox[] = { 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 }; /* Corresponds to _SInv[256] (in hex) */ unsigned char mtpz_aes_invsbox[] = { 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D }; /* Corresponds to _T3[256] */ unsigned int mtpz_aes_ft1[] = { 0x6363A5C6, 0x7C7C84F8, 0x777799EE, 0x7B7B8DF6, 0xF2F20DFF, 0x6B6BBDD6, 0x6F6FB1DE, 0xC5C55491, 0x30305060, 0x01010302, 0x6767A9CE, 0x2B2B7D56, 0xFEFE19E7, 0xD7D762B5, 0xABABE64D, 0x76769AEC, 0xCACA458F, 0x82829D1F, 0xC9C94089, 0x7D7D87FA, 0xFAFA15EF, 0x5959EBB2, 0x4747C98E, 0xF0F00BFB, 0xADADEC41, 0xD4D467B3, 0xA2A2FD5F, 0xAFAFEA45, 0x9C9CBF23, 0xA4A4F753, 0x727296E4, 0xC0C05B9B, 0xB7B7C275, 0xFDFD1CE1, 0x9393AE3D, 0x26266A4C, 0x36365A6C, 0x3F3F417E, 0xF7F702F5, 0xCCCC4F83, 0x34345C68, 0xA5A5F451, 0xE5E534D1, 0xF1F108F9, 0x717193E2, 0xD8D873AB, 0x31315362, 0x15153F2A, 0x04040C08, 0xC7C75295, 0x23236546, 0xC3C35E9D, 0x18182830, 0x9696A137, 0x05050F0A, 0x9A9AB52F, 0x0707090E, 0x12123624, 0x80809B1B, 0xE2E23DDF, 0xEBEB26CD, 0x2727694E, 0xB2B2CD7F, 0x75759FEA, 0x09091B12, 0x83839E1D, 0x2C2C7458, 0x1A1A2E34, 0x1B1B2D36, 0x6E6EB2DC, 0x5A5AEEB4, 0xA0A0FB5B, 0x5252F6A4, 0x3B3B4D76, 0xD6D661B7, 0xB3B3CE7D, 0x29297B52, 0xE3E33EDD, 0x2F2F715E, 0x84849713, 0x5353F5A6, 0xD1D168B9, 0x00000000, 0xEDED2CC1, 0x20206040, 0xFCFC1FE3, 0xB1B1C879, 0x5B5BEDB6, 0x6A6ABED4, 0xCBCB468D, 0xBEBED967, 0x39394B72, 0x4A4ADE94, 0x4C4CD498, 0x5858E8B0, 0xCFCF4A85, 0xD0D06BBB, 0xEFEF2AC5, 0xAAAAE54F, 0xFBFB16ED, 0x4343C586, 0x4D4DD79A, 0x33335566, 0x85859411, 0x4545CF8A, 0xF9F910E9, 0x02020604, 0x7F7F81FE, 0x5050F0A0, 0x3C3C4478, 0x9F9FBA25, 0xA8A8E34B, 0x5151F3A2, 0xA3A3FE5D, 0x4040C080, 0x8F8F8A05, 0x9292AD3F, 0x9D9DBC21, 0x38384870, 0xF5F504F1, 0xBCBCDF63, 0xB6B6C177, 0xDADA75AF, 0x21216342, 0x10103020, 0xFFFF1AE5, 0xF3F30EFD, 0xD2D26DBF, 0xCDCD4C81, 0x0C0C1418, 0x13133526, 0xECEC2FC3, 0x5F5FE1BE, 0x9797A235, 0x4444CC88, 0x1717392E, 0xC4C45793, 0xA7A7F255, 0x7E7E82FC, 0x3D3D477A, 0x6464ACC8, 0x5D5DE7BA, 0x19192B32, 0x737395E6, 0x6060A0C0, 0x81819819, 0x4F4FD19E, 0xDCDC7FA3, 0x22226644, 0x2A2A7E54, 0x9090AB3B, 0x8888830B, 0x4646CA8C, 0xEEEE29C7, 0xB8B8D36B, 0x14143C28, 0xDEDE79A7, 0x5E5EE2BC, 0x0B0B1D16, 0xDBDB76AD, 0xE0E03BDB, 0x32325664, 0x3A3A4E74, 0x0A0A1E14, 0x4949DB92, 0x06060A0C, 0x24246C48, 0x5C5CE4B8, 0xC2C25D9F, 0xD3D36EBD, 0xACACEF43, 0x6262A6C4, 0x9191A839, 0x9595A431, 0xE4E437D3, 0x79798BF2, 0xE7E732D5, 0xC8C8438B, 0x3737596E, 0x6D6DB7DA, 0x8D8D8C01, 0xD5D564B1, 0x4E4ED29C, 0xA9A9E049, 0x6C6CB4D8, 0x5656FAAC, 0xF4F407F3, 0xEAEA25CF, 0x6565AFCA, 0x7A7A8EF4, 0xAEAEE947, 0x08081810, 0xBABAD56F, 0x787888F0, 0x25256F4A, 0x2E2E725C, 0x1C1C2438, 0xA6A6F157, 0xB4B4C773, 0xC6C65197, 0xE8E823CB, 0xDDDD7CA1, 0x74749CE8, 0x1F1F213E, 0x4B4BDD96, 0xBDBDDC61, 0x8B8B860D, 0x8A8A850F, 0x707090E0, 0x3E3E427C, 0xB5B5C471, 0x6666AACC, 0x4848D890, 0x03030506, 0xF6F601F7, 0x0E0E121C, 0x6161A3C2, 0x35355F6A, 0x5757F9AE, 0xB9B9D069, 0x86869117, 0xC1C15899, 0x1D1D273A, 0x9E9EB927, 0xE1E138D9, 0xF8F813EB, 0x9898B32B, 0x11113322, 0x6969BBD2, 0xD9D970A9, 0x8E8E8907, 0x9494A733, 0x9B9BB62D, 0x1E1E223C, 0x87879215, 0xE9E920C9, 0xCECE4987, 0x5555FFAA, 0x28287850, 0xDFDF7AA5, 0x8C8C8F03, 0xA1A1F859, 0x89898009, 0x0D0D171A, 0xBFBFDA65, 0xE6E631D7, 0x4242C684, 0x6868B8D0, 0x4141C382, 0x9999B029, 0x2D2D775A, 0x0F0F111E, 0xB0B0CB7B, 0x5454FCA8, 0xBBBBD66D, 0x16163A2C, }; /* Corresponds to _T2[256] */ unsigned int mtpz_aes_ft2[] = { 0x63A5C663, 0x7C84F87C, 0x7799EE77, 0x7B8DF67B, 0xF20DFFF2, 0x6BBDD66B, 0x6FB1DE6F, 0xC55491C5, 0x30506030, 0x01030201, 0x67A9CE67, 0x2B7D562B, 0xFE19E7FE, 0xD762B5D7, 0xABE64DAB, 0x769AEC76, 0xCA458FCA, 0x829D1F82, 0xC94089C9, 0x7D87FA7D, 0xFA15EFFA, 0x59EBB259, 0x47C98E47, 0xF00BFBF0, 0xADEC41AD, 0xD467B3D4, 0xA2FD5FA2, 0xAFEA45AF, 0x9CBF239C, 0xA4F753A4, 0x7296E472, 0xC05B9BC0, 0xB7C275B7, 0xFD1CE1FD, 0x93AE3D93, 0x266A4C26, 0x365A6C36, 0x3F417E3F, 0xF702F5F7, 0xCC4F83CC, 0x345C6834, 0xA5F451A5, 0xE534D1E5, 0xF108F9F1, 0x7193E271, 0xD873ABD8, 0x31536231, 0x153F2A15, 0x040C0804, 0xC75295C7, 0x23654623, 0xC35E9DC3, 0x18283018, 0x96A13796, 0x050F0A05, 0x9AB52F9A, 0x07090E07, 0x12362412, 0x809B1B80, 0xE23DDFE2, 0xEB26CDEB, 0x27694E27, 0xB2CD7FB2, 0x759FEA75, 0x091B1209, 0x839E1D83, 0x2C74582C, 0x1A2E341A, 0x1B2D361B, 0x6EB2DC6E, 0x5AEEB45A, 0xA0FB5BA0, 0x52F6A452, 0x3B4D763B, 0xD661B7D6, 0xB3CE7DB3, 0x297B5229, 0xE33EDDE3, 0x2F715E2F, 0x84971384, 0x53F5A653, 0xD168B9D1, 0x00000000, 0xED2CC1ED, 0x20604020, 0xFC1FE3FC, 0xB1C879B1, 0x5BEDB65B, 0x6ABED46A, 0xCB468DCB, 0xBED967BE, 0x394B7239, 0x4ADE944A, 0x4CD4984C, 0x58E8B058, 0xCF4A85CF, 0xD06BBBD0, 0xEF2AC5EF, 0xAAE54FAA, 0xFB16EDFB, 0x43C58643, 0x4DD79A4D, 0x33556633, 0x85941185, 0x45CF8A45, 0xF910E9F9, 0x02060402, 0x7F81FE7F, 0x50F0A050, 0x3C44783C, 0x9FBA259F, 0xA8E34BA8, 0x51F3A251, 0xA3FE5DA3, 0x40C08040, 0x8F8A058F, 0x92AD3F92, 0x9DBC219D, 0x38487038, 0xF504F1F5, 0xBCDF63BC, 0xB6C177B6, 0xDA75AFDA, 0x21634221, 0x10302010, 0xFF1AE5FF, 0xF30EFDF3, 0xD26DBFD2, 0xCD4C81CD, 0x0C14180C, 0x13352613, 0xEC2FC3EC, 0x5FE1BE5F, 0x97A23597, 0x44CC8844, 0x17392E17, 0xC45793C4, 0xA7F255A7, 0x7E82FC7E, 0x3D477A3D, 0x64ACC864, 0x5DE7BA5D, 0x192B3219, 0x7395E673, 0x60A0C060, 0x81981981, 0x4FD19E4F, 0xDC7FA3DC, 0x22664422, 0x2A7E542A, 0x90AB3B90, 0x88830B88, 0x46CA8C46, 0xEE29C7EE, 0xB8D36BB8, 0x143C2814, 0xDE79A7DE, 0x5EE2BC5E, 0x0B1D160B, 0xDB76ADDB, 0xE03BDBE0, 0x32566432, 0x3A4E743A, 0x0A1E140A, 0x49DB9249, 0x060A0C06, 0x246C4824, 0x5CE4B85C, 0xC25D9FC2, 0xD36EBDD3, 0xACEF43AC, 0x62A6C462, 0x91A83991, 0x95A43195, 0xE437D3E4, 0x798BF279, 0xE732D5E7, 0xC8438BC8, 0x37596E37, 0x6DB7DA6D, 0x8D8C018D, 0xD564B1D5, 0x4ED29C4E, 0xA9E049A9, 0x6CB4D86C, 0x56FAAC56, 0xF407F3F4, 0xEA25CFEA, 0x65AFCA65, 0x7A8EF47A, 0xAEE947AE, 0x08181008, 0xBAD56FBA, 0x7888F078, 0x256F4A25, 0x2E725C2E, 0x1C24381C, 0xA6F157A6, 0xB4C773B4, 0xC65197C6, 0xE823CBE8, 0xDD7CA1DD, 0x749CE874, 0x1F213E1F, 0x4BDD964B, 0xBDDC61BD, 0x8B860D8B, 0x8A850F8A, 0x7090E070, 0x3E427C3E, 0xB5C471B5, 0x66AACC66, 0x48D89048, 0x03050603, 0xF601F7F6, 0x0E121C0E, 0x61A3C261, 0x355F6A35, 0x57F9AE57, 0xB9D069B9, 0x86911786, 0xC15899C1, 0x1D273A1D, 0x9EB9279E, 0xE138D9E1, 0xF813EBF8, 0x98B32B98, 0x11332211, 0x69BBD269, 0xD970A9D9, 0x8E89078E, 0x94A73394, 0x9BB62D9B, 0x1E223C1E, 0x87921587, 0xE920C9E9, 0xCE4987CE, 0x55FFAA55, 0x28785028, 0xDF7AA5DF, 0x8C8F038C, 0xA1F859A1, 0x89800989, 0x0D171A0D, 0xBFDA65BF, 0xE631D7E6, 0x42C68442, 0x68B8D068, 0x41C38241, 0x99B02999, 0x2D775A2D, 0x0F111E0F, 0xB0CB7BB0, 0x54FCA854, 0xBBD66DBB, 0x163A2C16, }; /* Corresponds to _T0[256] */ unsigned int mtpz_aes_ft3[] = { 0xC66363A5, 0xF87C7C84, 0xEE777799, 0xF67B7B8D, 0xFFF2F20D, 0xD66B6BBD, 0xDE6F6FB1, 0x91C5C554, 0x60303050, 0x02010103, 0xCE6767A9, 0x562B2B7D, 0xE7FEFE19, 0xB5D7D762, 0x4DABABE6, 0xEC76769A, 0x8FCACA45, 0x1F82829D, 0x89C9C940, 0xFA7D7D87, 0xEFFAFA15, 0xB25959EB, 0x8E4747C9, 0xFBF0F00B, 0x41ADADEC, 0xB3D4D467, 0x5FA2A2FD, 0x45AFAFEA, 0x239C9CBF, 0x53A4A4F7, 0xE4727296, 0x9BC0C05B, 0x75B7B7C2, 0xE1FDFD1C, 0x3D9393AE, 0x4C26266A, 0x6C36365A, 0x7E3F3F41, 0xF5F7F702, 0x83CCCC4F, 0x6834345C, 0x51A5A5F4, 0xD1E5E534, 0xF9F1F108, 0xE2717193, 0xABD8D873, 0x62313153, 0x2A15153F, 0x0804040C, 0x95C7C752, 0x46232365, 0x9DC3C35E, 0x30181828, 0x379696A1, 0x0A05050F, 0x2F9A9AB5, 0x0E070709, 0x24121236, 0x1B80809B, 0xDFE2E23D, 0xCDEBEB26, 0x4E272769, 0x7FB2B2CD, 0xEA75759F, 0x1209091B, 0x1D83839E, 0x582C2C74, 0x341A1A2E, 0x361B1B2D, 0xDC6E6EB2, 0xB45A5AEE, 0x5BA0A0FB, 0xA45252F6, 0x763B3B4D, 0xB7D6D661, 0x7DB3B3CE, 0x5229297B, 0xDDE3E33E, 0x5E2F2F71, 0x13848497, 0xA65353F5, 0xB9D1D168, 0x00000000, 0xC1EDED2C, 0x40202060, 0xE3FCFC1F, 0x79B1B1C8, 0xB65B5BED, 0xD46A6ABE, 0x8DCBCB46, 0x67BEBED9, 0x7239394B, 0x944A4ADE, 0x984C4CD4, 0xB05858E8, 0x85CFCF4A, 0xBBD0D06B, 0xC5EFEF2A, 0x4FAAAAE5, 0xEDFBFB16, 0x864343C5, 0x9A4D4DD7, 0x66333355, 0x11858594, 0x8A4545CF, 0xE9F9F910, 0x04020206, 0xFE7F7F81, 0xA05050F0, 0x783C3C44, 0x259F9FBA, 0x4BA8A8E3, 0xA25151F3, 0x5DA3A3FE, 0x804040C0, 0x058F8F8A, 0x3F9292AD, 0x219D9DBC, 0x70383848, 0xF1F5F504, 0x63BCBCDF, 0x77B6B6C1, 0xAFDADA75, 0x42212163, 0x20101030, 0xE5FFFF1A, 0xFDF3F30E, 0xBFD2D26D, 0x81CDCD4C, 0x180C0C14, 0x26131335, 0xC3ECEC2F, 0xBE5F5FE1, 0x359797A2, 0x884444CC, 0x2E171739, 0x93C4C457, 0x55A7A7F2, 0xFC7E7E82, 0x7A3D3D47, 0xC86464AC, 0xBA5D5DE7, 0x3219192B, 0xE6737395, 0xC06060A0, 0x19818198, 0x9E4F4FD1, 0xA3DCDC7F, 0x44222266, 0x542A2A7E, 0x3B9090AB, 0x0B888883, 0x8C4646CA, 0xC7EEEE29, 0x6BB8B8D3, 0x2814143C, 0xA7DEDE79, 0xBC5E5EE2, 0x160B0B1D, 0xADDBDB76, 0xDBE0E03B, 0x64323256, 0x743A3A4E, 0x140A0A1E, 0x924949DB, 0x0C06060A, 0x4824246C, 0xB85C5CE4, 0x9FC2C25D, 0xBDD3D36E, 0x43ACACEF, 0xC46262A6, 0x399191A8, 0x319595A4, 0xD3E4E437, 0xF279798B, 0xD5E7E732, 0x8BC8C843, 0x6E373759, 0xDA6D6DB7, 0x018D8D8C, 0xB1D5D564, 0x9C4E4ED2, 0x49A9A9E0, 0xD86C6CB4, 0xAC5656FA, 0xF3F4F407, 0xCFEAEA25, 0xCA6565AF, 0xF47A7A8E, 0x47AEAEE9, 0x10080818, 0x6FBABAD5, 0xF0787888, 0x4A25256F, 0x5C2E2E72, 0x381C1C24, 0x57A6A6F1, 0x73B4B4C7, 0x97C6C651, 0xCBE8E823, 0xA1DDDD7C, 0xE874749C, 0x3E1F1F21, 0x964B4BDD, 0x61BDBDDC, 0x0D8B8B86, 0x0F8A8A85, 0xE0707090, 0x7C3E3E42, 0x71B5B5C4, 0xCC6666AA, 0x904848D8, 0x06030305, 0xF7F6F601, 0x1C0E0E12, 0xC26161A3, 0x6A35355F, 0xAE5757F9, 0x69B9B9D0, 0x17868691, 0x99C1C158, 0x3A1D1D27, 0x279E9EB9, 0xD9E1E138, 0xEBF8F813, 0x2B9898B3, 0x22111133, 0xD26969BB, 0xA9D9D970, 0x078E8E89, 0x339494A7, 0x2D9B9BB6, 0x3C1E1E22, 0x15878792, 0xC9E9E920, 0x87CECE49, 0xAA5555FF, 0x50282878, 0xA5DFDF7A, 0x038C8C8F, 0x59A1A1F8, 0x09898980, 0x1A0D0D17, 0x65BFBFDA, 0xD7E6E631, 0x844242C6, 0xD06868B8, 0x824141C3, 0x299999B0, 0x5A2D2D77, 0x1E0F0F11, 0x7BB0B0CB, 0xA85454FC, 0x6DBBBBD6, 0x2C16163A, }; /* Corresponds to _T1[256] */ unsigned int mtpz_aes_ft4[] = { 0xA5C66363, 0x84F87C7C, 0x99EE7777, 0x8DF67B7B, 0x0DFFF2F2, 0xBDD66B6B, 0xB1DE6F6F, 0x5491C5C5, 0x50603030, 0x03020101, 0xA9CE6767, 0x7D562B2B, 0x19E7FEFE, 0x62B5D7D7, 0xE64DABAB, 0x9AEC7676, 0x458FCACA, 0x9D1F8282, 0x4089C9C9, 0x87FA7D7D, 0x15EFFAFA, 0xEBB25959, 0xC98E4747, 0x0BFBF0F0, 0xEC41ADAD, 0x67B3D4D4, 0xFD5FA2A2, 0xEA45AFAF, 0xBF239C9C, 0xF753A4A4, 0x96E47272, 0x5B9BC0C0, 0xC275B7B7, 0x1CE1FDFD, 0xAE3D9393, 0x6A4C2626, 0x5A6C3636, 0x417E3F3F, 0x02F5F7F7, 0x4F83CCCC, 0x5C683434, 0xF451A5A5, 0x34D1E5E5, 0x08F9F1F1, 0x93E27171, 0x73ABD8D8, 0x53623131, 0x3F2A1515, 0x0C080404, 0x5295C7C7, 0x65462323, 0x5E9DC3C3, 0x28301818, 0xA1379696, 0x0F0A0505, 0xB52F9A9A, 0x090E0707, 0x36241212, 0x9B1B8080, 0x3DDFE2E2, 0x26CDEBEB, 0x694E2727, 0xCD7FB2B2, 0x9FEA7575, 0x1B120909, 0x9E1D8383, 0x74582C2C, 0x2E341A1A, 0x2D361B1B, 0xB2DC6E6E, 0xEEB45A5A, 0xFB5BA0A0, 0xF6A45252, 0x4D763B3B, 0x61B7D6D6, 0xCE7DB3B3, 0x7B522929, 0x3EDDE3E3, 0x715E2F2F, 0x97138484, 0xF5A65353, 0x68B9D1D1, 0x00000000, 0x2CC1EDED, 0x60402020, 0x1FE3FCFC, 0xC879B1B1, 0xEDB65B5B, 0xBED46A6A, 0x468DCBCB, 0xD967BEBE, 0x4B723939, 0xDE944A4A, 0xD4984C4C, 0xE8B05858, 0x4A85CFCF, 0x6BBBD0D0, 0x2AC5EFEF, 0xE54FAAAA, 0x16EDFBFB, 0xC5864343, 0xD79A4D4D, 0x55663333, 0x94118585, 0xCF8A4545, 0x10E9F9F9, 0x06040202, 0x81FE7F7F, 0xF0A05050, 0x44783C3C, 0xBA259F9F, 0xE34BA8A8, 0xF3A25151, 0xFE5DA3A3, 0xC0804040, 0x8A058F8F, 0xAD3F9292, 0xBC219D9D, 0x48703838, 0x04F1F5F5, 0xDF63BCBC, 0xC177B6B6, 0x75AFDADA, 0x63422121, 0x30201010, 0x1AE5FFFF, 0x0EFDF3F3, 0x6DBFD2D2, 0x4C81CDCD, 0x14180C0C, 0x35261313, 0x2FC3ECEC, 0xE1BE5F5F, 0xA2359797, 0xCC884444, 0x392E1717, 0x5793C4C4, 0xF255A7A7, 0x82FC7E7E, 0x477A3D3D, 0xACC86464, 0xE7BA5D5D, 0x2B321919, 0x95E67373, 0xA0C06060, 0x98198181, 0xD19E4F4F, 0x7FA3DCDC, 0x66442222, 0x7E542A2A, 0xAB3B9090, 0x830B8888, 0xCA8C4646, 0x29C7EEEE, 0xD36BB8B8, 0x3C281414, 0x79A7DEDE, 0xE2BC5E5E, 0x1D160B0B, 0x76ADDBDB, 0x3BDBE0E0, 0x56643232, 0x4E743A3A, 0x1E140A0A, 0xDB924949, 0x0A0C0606, 0x6C482424, 0xE4B85C5C, 0x5D9FC2C2, 0x6EBDD3D3, 0xEF43ACAC, 0xA6C46262, 0xA8399191, 0xA4319595, 0x37D3E4E4, 0x8BF27979, 0x32D5E7E7, 0x438BC8C8, 0x596E3737, 0xB7DA6D6D, 0x8C018D8D, 0x64B1D5D5, 0xD29C4E4E, 0xE049A9A9, 0xB4D86C6C, 0xFAAC5656, 0x07F3F4F4, 0x25CFEAEA, 0xAFCA6565, 0x8EF47A7A, 0xE947AEAE, 0x18100808, 0xD56FBABA, 0x88F07878, 0x6F4A2525, 0x725C2E2E, 0x24381C1C, 0xF157A6A6, 0xC773B4B4, 0x5197C6C6, 0x23CBE8E8, 0x7CA1DDDD, 0x9CE87474, 0x213E1F1F, 0xDD964B4B, 0xDC61BDBD, 0x860D8B8B, 0x850F8A8A, 0x90E07070, 0x427C3E3E, 0xC471B5B5, 0xAACC6666, 0xD8904848, 0x05060303, 0x01F7F6F6, 0x121C0E0E, 0xA3C26161, 0x5F6A3535, 0xF9AE5757, 0xD069B9B9, 0x91178686, 0x5899C1C1, 0x273A1D1D, 0xB9279E9E, 0x38D9E1E1, 0x13EBF8F8, 0xB32B9898, 0x33221111, 0xBBD26969, 0x70A9D9D9, 0x89078E8E, 0xA7339494, 0xB62D9B9B, 0x223C1E1E, 0x92158787, 0x20C9E9E9, 0x4987CECE, 0xFFAA5555, 0x78502828, 0x7AA5DFDF, 0x8F038C8C, 0xF859A1A1, 0x80098989, 0x171A0D0D, 0xDA65BFBF, 0x31D7E6E6, 0xC6844242, 0xB8D06868, 0xC3824141, 0xB0299999, 0x775A2D2D, 0x111E0F0F, 0xCB7BB0B0, 0xFCA85454, 0xD66DBBBB, 0x3A2C1616, }; /* Corresponds to _TInv3[256] */ unsigned int mtpz_aes_rt1[] = { 0xF4A75051, 0x4165537E, 0x17A4C31A, 0x275E963A, 0xAB6BCB3B, 0x9D45F11F, 0xFA58ABAC, 0xE303934B, 0x30FA5520, 0x766DF6AD, 0xCC769188, 0x024C25F5, 0xE5D7FC4F, 0x2ACBD7C5, 0x35448026, 0x62A38FB5, 0xB15A49DE, 0xBA1B6725, 0xEA0E9845, 0xFEC0E15D, 0x2F7502C3, 0x4CF01281, 0x4697A38D, 0xD3F9C66B, 0x8F5FE703, 0x929C9515, 0x6D7AEBBF, 0x5259DA95, 0xBE832DD4, 0x7421D358, 0xE0692949, 0xC9C8448E, 0xC2896A75, 0x8E7978F4, 0x583E6B99, 0xB971DD27, 0xE14FB6BE, 0x88AD17F0, 0x20AC66C9, 0xCE3AB47D, 0xDF4A1863, 0x1A3182E5, 0x51336097, 0x537F4562, 0x6477E0B1, 0x6BAE84BB, 0x81A01CFE, 0x082B94F9, 0x48685870, 0x45FD198F, 0xDE6C8794, 0x7BF8B752, 0x73D323AB, 0x4B02E272, 0x1F8F57E3, 0x55AB2A66, 0xEB2807B2, 0xB5C2032F, 0xC57B9A86, 0x3708A5D3, 0x2887F230, 0xBFA5B223, 0x036ABA02, 0x16825CED, 0xCF1C2B8A, 0x79B492A7, 0x07F2F0F3, 0x69E2A14E, 0xDAF4CD65, 0x05BED506, 0x34621FD1, 0xA6FE8AC4, 0x2E539D34, 0xF355A0A2, 0x8AE13205, 0xF6EB75A4, 0x83EC390B, 0x60EFAA40, 0x719F065E, 0x6E1051BD, 0x218AF93E, 0xDD063D96, 0x3E05AEDD, 0xE6BD464D, 0x548DB591, 0xC45D0571, 0x06D46F04, 0x5015FF60, 0x98FB2419, 0xBDE997D6, 0x4043CC89, 0xD99E7767, 0xE842BDB0, 0x898B8807, 0x195B38E7, 0xC8EEDB79, 0x7C0A47A1, 0x420FE97C, 0x841EC9F8, 0x00000000, 0x80868309, 0x2BED4832, 0x1170AC1E, 0x5A724E6C, 0x0EFFFBFD, 0x8538560F, 0xAED51E3D, 0x2D392736, 0x0FD9640A, 0x5CA62168, 0x5B54D19B, 0x362E3A24, 0x0A67B10C, 0x57E70F93, 0xEE96D2B4, 0x9B919E1B, 0xC0C54F80, 0xDC20A261, 0x774B695A, 0x121A161C, 0x93BA0AE2, 0xA02AE5C0, 0x22E0433C, 0x1B171D12, 0x090D0B0E, 0x8BC7ADF2, 0xB6A8B92D, 0x1EA9C814, 0xF1198557, 0x75074CAF, 0x99DDBBEE, 0x7F60FDA3, 0x01269FF7, 0x72F5BC5C, 0x663BC544, 0xFB7E345B, 0x4329768B, 0x23C6DCCB, 0xEDFC68B6, 0xE4F163B8, 0x31DCCAD7, 0x63851042, 0x97224013, 0xC6112084, 0x4A247D85, 0xBB3DF8D2, 0xF93211AE, 0x29A16DC7, 0x9E2F4B1D, 0xB230F3DC, 0x8652EC0D, 0xC1E3D077, 0xB3166C2B, 0x70B999A9, 0x9448FA11, 0xE9642247, 0xFC8CC4A8, 0xF03F1AA0, 0x7D2CD856, 0x3390EF22, 0x494EC787, 0x38D1C1D9, 0xCAA2FE8C, 0xD40B3698, 0xF581CFA6, 0x7ADE28A5, 0xB78E26DA, 0xADBFA43F, 0x3A9DE42C, 0x78920D50, 0x5FCC9B6A, 0x7E466254, 0x8D13C2F6, 0xD8B8E890, 0x39F75E2E, 0xC3AFF582, 0x5D80BE9F, 0xD0937C69, 0xD52DA96F, 0x2512B3CF, 0xAC993BC8, 0x187DA710, 0x9C636EE8, 0x3BBB7BDB, 0x267809CD, 0x5918F46E, 0x9AB701EC, 0x4F9AA883, 0x956E65E6, 0xFFE67EAA, 0xBCCF0821, 0x15E8E6EF, 0xE79BD9BA, 0x6F36CE4A, 0x9F09D4EA, 0xB07CD629, 0xA4B2AF31, 0x3F23312A, 0xA59430C6, 0xA266C035, 0x4EBC3774, 0x82CAA6FC, 0x90D0B0E0, 0xA7D81533, 0x04984AF1, 0xECDAF741, 0xCD500E7F, 0x91F62F17, 0x4DD68D76, 0xEFB04D43, 0xAA4D54CC, 0x9604DFE4, 0xD1B5E39E, 0x6A881B4C, 0x2C1FB8C1, 0x65517F46, 0x5EEA049D, 0x8C355D01, 0x877473FA, 0x0B412EFB, 0x671D5AB3, 0xDBD25292, 0x105633E9, 0xD647136D, 0xD7618C9A, 0xA10C7A37, 0xF8148E59, 0x133C89EB, 0xA927EECE, 0x61C935B7, 0x1CE5EDE1, 0x47B13C7A, 0xD2DF599C, 0xF2733F55, 0x14CE7918, 0xC737BF73, 0xF7CDEA53, 0xFDAA5B5F, 0x3D6F14DF, 0x44DB8678, 0xAFF381CA, 0x68C43EB9, 0x24342C38, 0xA3405FC2, 0x1DC37216, 0xE2250CBC, 0x3C498B28, 0x0D9541FF, 0xA8017139, 0x0CB3DE08, 0xB4E49CD8, 0x56C19064, 0xCB84617B, 0x32B670D5, 0x6C5C7448, 0xB85742D0 }; /* Corresponds to _TInv2[256] */ unsigned int mtpz_aes_rt2[] = { 0xA75051F4, 0x65537E41, 0xA4C31A17, 0x5E963A27, 0x6BCB3BAB, 0x45F11F9D, 0x58ABACFA, 0x03934BE3, 0xFA552030, 0x6DF6AD76, 0x769188CC, 0x4C25F502, 0xD7FC4FE5, 0xCBD7C52A, 0x44802635, 0xA38FB562, 0x5A49DEB1, 0x1B6725BA, 0x0E9845EA, 0xC0E15DFE, 0x7502C32F, 0xF012814C, 0x97A38D46, 0xF9C66BD3, 0x5FE7038F, 0x9C951592, 0x7AEBBF6D, 0x59DA9552, 0x832DD4BE, 0x21D35874, 0x692949E0, 0xC8448EC9, 0x896A75C2, 0x7978F48E, 0x3E6B9958, 0x71DD27B9, 0x4FB6BEE1, 0xAD17F088, 0xAC66C920, 0x3AB47DCE, 0x4A1863DF, 0x3182E51A, 0x33609751, 0x7F456253, 0x77E0B164, 0xAE84BB6B, 0xA01CFE81, 0x2B94F908, 0x68587048, 0xFD198F45, 0x6C8794DE, 0xF8B7527B, 0xD323AB73, 0x02E2724B, 0x8F57E31F, 0xAB2A6655, 0x2807B2EB, 0xC2032FB5, 0x7B9A86C5, 0x08A5D337, 0x87F23028, 0xA5B223BF, 0x6ABA0203, 0x825CED16, 0x1C2B8ACF, 0xB492A779, 0xF2F0F307, 0xE2A14E69, 0xF4CD65DA, 0xBED50605, 0x621FD134, 0xFE8AC4A6, 0x539D342E, 0x55A0A2F3, 0xE132058A, 0xEB75A4F6, 0xEC390B83, 0xEFAA4060, 0x9F065E71, 0x1051BD6E, 0x8AF93E21, 0x063D96DD, 0x05AEDD3E, 0xBD464DE6, 0x8DB59154, 0x5D0571C4, 0xD46F0406, 0x15FF6050, 0xFB241998, 0xE997D6BD, 0x43CC8940, 0x9E7767D9, 0x42BDB0E8, 0x8B880789, 0x5B38E719, 0xEEDB79C8, 0x0A47A17C, 0x0FE97C42, 0x1EC9F884, 0x00000000, 0x86830980, 0xED48322B, 0x70AC1E11, 0x724E6C5A, 0xFFFBFD0E, 0x38560F85, 0xD51E3DAE, 0x3927362D, 0xD9640A0F, 0xA621685C, 0x54D19B5B, 0x2E3A2436, 0x67B10C0A, 0xE70F9357, 0x96D2B4EE, 0x919E1B9B, 0xC54F80C0, 0x20A261DC, 0x4B695A77, 0x1A161C12, 0xBA0AE293, 0x2AE5C0A0, 0xE0433C22, 0x171D121B, 0x0D0B0E09, 0xC7ADF28B, 0xA8B92DB6, 0xA9C8141E, 0x198557F1, 0x074CAF75, 0xDDBBEE99, 0x60FDA37F, 0x269FF701, 0xF5BC5C72, 0x3BC54466, 0x7E345BFB, 0x29768B43, 0xC6DCCB23, 0xFC68B6ED, 0xF163B8E4, 0xDCCAD731, 0x85104263, 0x22401397, 0x112084C6, 0x247D854A, 0x3DF8D2BB, 0x3211AEF9, 0xA16DC729, 0x2F4B1D9E, 0x30F3DCB2, 0x52EC0D86, 0xE3D077C1, 0x166C2BB3, 0xB999A970, 0x48FA1194, 0x642247E9, 0x8CC4A8FC, 0x3F1AA0F0, 0x2CD8567D, 0x90EF2233, 0x4EC78749, 0xD1C1D938, 0xA2FE8CCA, 0x0B3698D4, 0x81CFA6F5, 0xDE28A57A, 0x8E26DAB7, 0xBFA43FAD, 0x9DE42C3A, 0x920D5078, 0xCC9B6A5F, 0x4662547E, 0x13C2F68D, 0xB8E890D8, 0xF75E2E39, 0xAFF582C3, 0x80BE9F5D, 0x937C69D0, 0x2DA96FD5, 0x12B3CF25, 0x993BC8AC, 0x7DA71018, 0x636EE89C, 0xBB7BDB3B, 0x7809CD26, 0x18F46E59, 0xB701EC9A, 0x9AA8834F, 0x6E65E695, 0xE67EAAFF, 0xCF0821BC, 0xE8E6EF15, 0x9BD9BAE7, 0x36CE4A6F, 0x09D4EA9F, 0x7CD629B0, 0xB2AF31A4, 0x23312A3F, 0x9430C6A5, 0x66C035A2, 0xBC37744E, 0xCAA6FC82, 0xD0B0E090, 0xD81533A7, 0x984AF104, 0xDAF741EC, 0x500E7FCD, 0xF62F1791, 0xD68D764D, 0xB04D43EF, 0x4D54CCAA, 0x04DFE496, 0xB5E39ED1, 0x881B4C6A, 0x1FB8C12C, 0x517F4665, 0xEA049D5E, 0x355D018C, 0x7473FA87, 0x412EFB0B, 0x1D5AB367, 0xD25292DB, 0x5633E910, 0x47136DD6, 0x618C9AD7, 0x0C7A37A1, 0x148E59F8, 0x3C89EB13, 0x27EECEA9, 0xC935B761, 0xE5EDE11C, 0xB13C7A47, 0xDF599CD2, 0x733F55F2, 0xCE791814, 0x37BF73C7, 0xCDEA53F7, 0xAA5B5FFD, 0x6F14DF3D, 0xDB867844, 0xF381CAAF, 0xC43EB968, 0x342C3824, 0x405FC2A3, 0xC372161D, 0x250CBCE2, 0x498B283C, 0x9541FF0D, 0x017139A8, 0xB3DE080C, 0xE49CD8B4, 0xC1906456, 0x84617BCB, 0xB670D532, 0x5C74486C, 0x5742D0B8 }; /* Corresponds to _TInv0[256] */ unsigned int mtpz_aes_rt3[] = { 0x51F4A750, 0x7E416553, 0x1A17A4C3, 0x3A275E96, 0x3BAB6BCB, 0x1F9D45F1, 0xACFA58AB, 0x4BE30393, 0x2030FA55, 0xAD766DF6, 0x88CC7691, 0xF5024C25, 0x4FE5D7FC, 0xC52ACBD7, 0x26354480, 0xB562A38F, 0xDEB15A49, 0x25BA1B67, 0x45EA0E98, 0x5DFEC0E1, 0xC32F7502, 0x814CF012, 0x8D4697A3, 0x6BD3F9C6, 0x038F5FE7, 0x15929C95, 0xBF6D7AEB, 0x955259DA, 0xD4BE832D, 0x587421D3, 0x49E06929, 0x8EC9C844, 0x75C2896A, 0xF48E7978, 0x99583E6B, 0x27B971DD, 0xBEE14FB6, 0xF088AD17, 0xC920AC66, 0x7DCE3AB4, 0x63DF4A18, 0xE51A3182, 0x97513360, 0x62537F45, 0xB16477E0, 0xBB6BAE84, 0xFE81A01C, 0xF9082B94, 0x70486858, 0x8F45FD19, 0x94DE6C87, 0x527BF8B7, 0xAB73D323, 0x724B02E2, 0xE31F8F57, 0x6655AB2A, 0xB2EB2807, 0x2FB5C203, 0x86C57B9A, 0xD33708A5, 0x302887F2, 0x23BFA5B2, 0x02036ABA, 0xED16825C, 0x8ACF1C2B, 0xA779B492, 0xF307F2F0, 0x4E69E2A1, 0x65DAF4CD, 0x0605BED5, 0xD134621F, 0xC4A6FE8A, 0x342E539D, 0xA2F355A0, 0x058AE132, 0xA4F6EB75, 0x0B83EC39, 0x4060EFAA, 0x5E719F06, 0xBD6E1051, 0x3E218AF9, 0x96DD063D, 0xDD3E05AE, 0x4DE6BD46, 0x91548DB5, 0x71C45D05, 0x0406D46F, 0x605015FF, 0x1998FB24, 0xD6BDE997, 0x894043CC, 0x67D99E77, 0xB0E842BD, 0x07898B88, 0xE7195B38, 0x79C8EEDB, 0xA17C0A47, 0x7C420FE9, 0xF8841EC9, 0x00000000, 0x09808683, 0x322BED48, 0x1E1170AC, 0x6C5A724E, 0xFD0EFFFB, 0x0F853856, 0x3DAED51E, 0x362D3927, 0x0A0FD964, 0x685CA621, 0x9B5B54D1, 0x24362E3A, 0x0C0A67B1, 0x9357E70F, 0xB4EE96D2, 0x1B9B919E, 0x80C0C54F, 0x61DC20A2, 0x5A774B69, 0x1C121A16, 0xE293BA0A, 0xC0A02AE5, 0x3C22E043, 0x121B171D, 0x0E090D0B, 0xF28BC7AD, 0x2DB6A8B9, 0x141EA9C8, 0x57F11985, 0xAF75074C, 0xEE99DDBB, 0xA37F60FD, 0xF701269F, 0x5C72F5BC, 0x44663BC5, 0x5BFB7E34, 0x8B432976, 0xCB23C6DC, 0xB6EDFC68, 0xB8E4F163, 0xD731DCCA, 0x42638510, 0x13972240, 0x84C61120, 0x854A247D, 0xD2BB3DF8, 0xAEF93211, 0xC729A16D, 0x1D9E2F4B, 0xDCB230F3, 0x0D8652EC, 0x77C1E3D0, 0x2BB3166C, 0xA970B999, 0x119448FA, 0x47E96422, 0xA8FC8CC4, 0xA0F03F1A, 0x567D2CD8, 0x223390EF, 0x87494EC7, 0xD938D1C1, 0x8CCAA2FE, 0x98D40B36, 0xA6F581CF, 0xA57ADE28, 0xDAB78E26, 0x3FADBFA4, 0x2C3A9DE4, 0x5078920D, 0x6A5FCC9B, 0x547E4662, 0xF68D13C2, 0x90D8B8E8, 0x2E39F75E, 0x82C3AFF5, 0x9F5D80BE, 0x69D0937C, 0x6FD52DA9, 0xCF2512B3, 0xC8AC993B, 0x10187DA7, 0xE89C636E, 0xDB3BBB7B, 0xCD267809, 0x6E5918F4, 0xEC9AB701, 0x834F9AA8, 0xE6956E65, 0xAAFFE67E, 0x21BCCF08, 0xEF15E8E6, 0xBAE79BD9, 0x4A6F36CE, 0xEA9F09D4, 0x29B07CD6, 0x31A4B2AF, 0x2A3F2331, 0xC6A59430, 0x35A266C0, 0x744EBC37, 0xFC82CAA6, 0xE090D0B0, 0x33A7D815, 0xF104984A, 0x41ECDAF7, 0x7FCD500E, 0x1791F62F, 0x764DD68D, 0x43EFB04D, 0xCCAA4D54, 0xE49604DF, 0x9ED1B5E3, 0x4C6A881B, 0xC12C1FB8, 0x4665517F, 0x9D5EEA04, 0x018C355D, 0xFA877473, 0xFB0B412E, 0xB3671D5A, 0x92DBD252, 0xE9105633, 0x6DD64713, 0x9AD7618C, 0x37A10C7A, 0x59F8148E, 0xEB133C89, 0xCEA927EE, 0xB761C935, 0xE11CE5ED, 0x7A47B13C, 0x9CD2DF59, 0x55F2733F, 0x1814CE79, 0x73C737BF, 0x53F7CDEA, 0x5FFDAA5B, 0xDF3D6F14, 0x7844DB86, 0xCAAFF381, 0xB968C43E, 0x3824342C, 0xC2A3405F, 0x161DC372, 0xBCE2250C, 0x283C498B, 0xFF0D9541, 0x39A80171, 0x080CB3DE, 0xD8B4E49C, 0x6456C190, 0x7BCB8461, 0xD532B670, 0x486C5C74, 0xD0B85742 }; /* Corresponds to _TInv1[256] */ unsigned int mtpz_aes_rt4[] = { 0x5051F4A7, 0x537E4165, 0xC31A17A4, 0x963A275E, 0xCB3BAB6B, 0xF11F9D45, 0xABACFA58, 0x934BE303, 0x552030FA, 0xF6AD766D, 0x9188CC76, 0x25F5024C, 0xFC4FE5D7, 0xD7C52ACB, 0x80263544, 0x8FB562A3, 0x49DEB15A, 0x6725BA1B, 0x9845EA0E, 0xE15DFEC0, 0x02C32F75, 0x12814CF0, 0xA38D4697, 0xC66BD3F9, 0xE7038F5F, 0x9515929C, 0xEBBF6D7A, 0xDA955259, 0x2DD4BE83, 0xD3587421, 0x2949E069, 0x448EC9C8, 0x6A75C289, 0x78F48E79, 0x6B99583E, 0xDD27B971, 0xB6BEE14F, 0x17F088AD, 0x66C920AC, 0xB47DCE3A, 0x1863DF4A, 0x82E51A31, 0x60975133, 0x4562537F, 0xE0B16477, 0x84BB6BAE, 0x1CFE81A0, 0x94F9082B, 0x58704868, 0x198F45FD, 0x8794DE6C, 0xB7527BF8, 0x23AB73D3, 0xE2724B02, 0x57E31F8F, 0x2A6655AB, 0x07B2EB28, 0x032FB5C2, 0x9A86C57B, 0xA5D33708, 0xF2302887, 0xB223BFA5, 0xBA02036A, 0x5CED1682, 0x2B8ACF1C, 0x92A779B4, 0xF0F307F2, 0xA14E69E2, 0xCD65DAF4, 0xD50605BE, 0x1FD13462, 0x8AC4A6FE, 0x9D342E53, 0xA0A2F355, 0x32058AE1, 0x75A4F6EB, 0x390B83EC, 0xAA4060EF, 0x065E719F, 0x51BD6E10, 0xF93E218A, 0x3D96DD06, 0xAEDD3E05, 0x464DE6BD, 0xB591548D, 0x0571C45D, 0x6F0406D4, 0xFF605015, 0x241998FB, 0x97D6BDE9, 0xCC894043, 0x7767D99E, 0xBDB0E842, 0x8807898B, 0x38E7195B, 0xDB79C8EE, 0x47A17C0A, 0xE97C420F, 0xC9F8841E, 0x00000000, 0x83098086, 0x48322BED, 0xAC1E1170, 0x4E6C5A72, 0xFBFD0EFF, 0x560F8538, 0x1E3DAED5, 0x27362D39, 0x640A0FD9, 0x21685CA6, 0xD19B5B54, 0x3A24362E, 0xB10C0A67, 0x0F9357E7, 0xD2B4EE96, 0x9E1B9B91, 0x4F80C0C5, 0xA261DC20, 0x695A774B, 0x161C121A, 0x0AE293BA, 0xE5C0A02A, 0x433C22E0, 0x1D121B17, 0x0B0E090D, 0xADF28BC7, 0xB92DB6A8, 0xC8141EA9, 0x8557F119, 0x4CAF7507, 0xBBEE99DD, 0xFDA37F60, 0x9FF70126, 0xBC5C72F5, 0xC544663B, 0x345BFB7E, 0x768B4329, 0xDCCB23C6, 0x68B6EDFC, 0x63B8E4F1, 0xCAD731DC, 0x10426385, 0x40139722, 0x2084C611, 0x7D854A24, 0xF8D2BB3D, 0x11AEF932, 0x6DC729A1, 0x4B1D9E2F, 0xF3DCB230, 0xEC0D8652, 0xD077C1E3, 0x6C2BB316, 0x99A970B9, 0xFA119448, 0x2247E964, 0xC4A8FC8C, 0x1AA0F03F, 0xD8567D2C, 0xEF223390, 0xC787494E, 0xC1D938D1, 0xFE8CCAA2, 0x3698D40B, 0xCFA6F581, 0x28A57ADE, 0x26DAB78E, 0xA43FADBF, 0xE42C3A9D, 0x0D507892, 0x9B6A5FCC, 0x62547E46, 0xC2F68D13, 0xE890D8B8, 0x5E2E39F7, 0xF582C3AF, 0xBE9F5D80, 0x7C69D093, 0xA96FD52D, 0xB3CF2512, 0x3BC8AC99, 0xA710187D, 0x6EE89C63, 0x7BDB3BBB, 0x09CD2678, 0xF46E5918, 0x01EC9AB7, 0xA8834F9A, 0x65E6956E, 0x7EAAFFE6, 0x0821BCCF, 0xE6EF15E8, 0xD9BAE79B, 0xCE4A6F36, 0xD4EA9F09, 0xD629B07C, 0xAF31A4B2, 0x312A3F23, 0x30C6A594, 0xC035A266, 0x37744EBC, 0xA6FC82CA, 0xB0E090D0, 0x1533A7D8, 0x4AF10498, 0xF741ECDA, 0x0E7FCD50, 0x2F1791F6, 0x8D764DD6, 0x4D43EFB0, 0x54CCAA4D, 0xDFE49604, 0xE39ED1B5, 0x1B4C6A88, 0xB8C12C1F, 0x7F466551, 0x049D5EEA, 0x5D018C35, 0x73FA8774, 0x2EFB0B41, 0x5AB3671D, 0x5292DBD2, 0x33E91056, 0x136DD647, 0x8C9AD761, 0x7A37A10C, 0x8E59F814, 0x89EB133C, 0xEECEA927, 0x35B761C9, 0xEDE11CE5, 0x3C7A47B1, 0x599CD2DF, 0x3F55F273, 0x791814CE, 0xBF73C737, 0xEA53F7CD, 0x5B5FFDAA, 0x14DF3D6F, 0x867844DB, 0x81CAAFF3, 0x3EB968C4, 0x2C382434, 0x5FC2A340, 0x72161DC3, 0x0CBCE225, 0x8B283C49, 0x41FF0D95, 0x7139A801, 0xDE080CB3, 0x9CD8B4E4, 0x906456C1, 0x617BCB84, 0x70D532B6, 0x74486C5C, 0x42D0B857 }; /* Corresponds to _IMXC1[256] */ unsigned int mtpz_aes_gb11[] = { 0x00000000, 0x0B0E090D, 0x161C121A, 0x1D121B17, 0x2C382434, 0x27362D39, 0x3A24362E, 0x312A3F23, 0x58704868, 0x537E4165, 0x4E6C5A72, 0x4562537F, 0x74486C5C, 0x7F466551, 0x62547E46, 0x695A774B, 0xB0E090D0, 0xBBEE99DD, 0xA6FC82CA, 0xADF28BC7, 0x9CD8B4E4, 0x97D6BDE9, 0x8AC4A6FE, 0x81CAAFF3, 0xE890D8B8, 0xE39ED1B5, 0xFE8CCAA2, 0xF582C3AF, 0xC4A8FC8C, 0xCFA6F581, 0xD2B4EE96, 0xD9BAE79B, 0x7BDB3BBB, 0x70D532B6, 0x6DC729A1, 0x66C920AC, 0x57E31F8F, 0x5CED1682, 0x41FF0D95, 0x4AF10498, 0x23AB73D3, 0x28A57ADE, 0x35B761C9, 0x3EB968C4, 0x0F9357E7, 0x049D5EEA, 0x198F45FD, 0x12814CF0, 0xCB3BAB6B, 0xC035A266, 0xDD27B971, 0xD629B07C, 0xE7038F5F, 0xEC0D8652, 0xF11F9D45, 0xFA119448, 0x934BE303, 0x9845EA0E, 0x8557F119, 0x8E59F814, 0xBF73C737, 0xB47DCE3A, 0xA96FD52D, 0xA261DC20, 0xF6AD766D, 0xFDA37F60, 0xE0B16477, 0xEBBF6D7A, 0xDA955259, 0xD19B5B54, 0xCC894043, 0xC787494E, 0xAEDD3E05, 0xA5D33708, 0xB8C12C1F, 0xB3CF2512, 0x82E51A31, 0x89EB133C, 0x94F9082B, 0x9FF70126, 0x464DE6BD, 0x4D43EFB0, 0x5051F4A7, 0x5B5FFDAA, 0x6A75C289, 0x617BCB84, 0x7C69D093, 0x7767D99E, 0x1E3DAED5, 0x1533A7D8, 0x0821BCCF, 0x032FB5C2, 0x32058AE1, 0x390B83EC, 0x241998FB, 0x2F1791F6, 0x8D764DD6, 0x867844DB, 0x9B6A5FCC, 0x906456C1, 0xA14E69E2, 0xAA4060EF, 0xB7527BF8, 0xBC5C72F5, 0xD50605BE, 0xDE080CB3, 0xC31A17A4, 0xC8141EA9, 0xF93E218A, 0xF2302887, 0xEF223390, 0xE42C3A9D, 0x3D96DD06, 0x3698D40B, 0x2B8ACF1C, 0x2084C611, 0x11AEF932, 0x1AA0F03F, 0x07B2EB28, 0x0CBCE225, 0x65E6956E, 0x6EE89C63, 0x73FA8774, 0x78F48E79, 0x49DEB15A, 0x42D0B857, 0x5FC2A340, 0x54CCAA4D, 0xF741ECDA, 0xFC4FE5D7, 0xE15DFEC0, 0xEA53F7CD, 0xDB79C8EE, 0xD077C1E3, 0xCD65DAF4, 0xC66BD3F9, 0xAF31A4B2, 0xA43FADBF, 0xB92DB6A8, 0xB223BFA5, 0x83098086, 0x8807898B, 0x9515929C, 0x9E1B9B91, 0x47A17C0A, 0x4CAF7507, 0x51BD6E10, 0x5AB3671D, 0x6B99583E, 0x60975133, 0x7D854A24, 0x768B4329, 0x1FD13462, 0x14DF3D6F, 0x09CD2678, 0x02C32F75, 0x33E91056, 0x38E7195B, 0x25F5024C, 0x2EFB0B41, 0x8C9AD761, 0x8794DE6C, 0x9A86C57B, 0x9188CC76, 0xA0A2F355, 0xABACFA58, 0xB6BEE14F, 0xBDB0E842, 0xD4EA9F09, 0xDFE49604, 0xC2F68D13, 0xC9F8841E, 0xF8D2BB3D, 0xF3DCB230, 0xEECEA927, 0xE5C0A02A, 0x3C7A47B1, 0x37744EBC, 0x2A6655AB, 0x21685CA6, 0x10426385, 0x1B4C6A88, 0x065E719F, 0x0D507892, 0x640A0FD9, 0x6F0406D4, 0x72161DC3, 0x791814CE, 0x48322BED, 0x433C22E0, 0x5E2E39F7, 0x552030FA, 0x01EC9AB7, 0x0AE293BA, 0x17F088AD, 0x1CFE81A0, 0x2DD4BE83, 0x26DAB78E, 0x3BC8AC99, 0x30C6A594, 0x599CD2DF, 0x5292DBD2, 0x4F80C0C5, 0x448EC9C8, 0x75A4F6EB, 0x7EAAFFE6, 0x63B8E4F1, 0x68B6EDFC, 0xB10C0A67, 0xBA02036A, 0xA710187D, 0xAC1E1170, 0x9D342E53, 0x963A275E, 0x8B283C49, 0x80263544, 0xE97C420F, 0xE2724B02, 0xFF605015, 0xF46E5918, 0xC544663B, 0xCE4A6F36, 0xD3587421, 0xD8567D2C, 0x7A37A10C, 0x7139A801, 0x6C2BB316, 0x6725BA1B, 0x560F8538, 0x5D018C35, 0x40139722, 0x4B1D9E2F, 0x2247E964, 0x2949E069, 0x345BFB7E, 0x3F55F273, 0x0E7FCD50, 0x0571C45D, 0x1863DF4A, 0x136DD647, 0xCAD731DC, 0xC1D938D1, 0xDCCB23C6, 0xD7C52ACB, 0xE6EF15E8, 0xEDE11CE5, 0xF0F307F2, 0xFBFD0EFF, 0x92A779B4, 0x99A970B9, 0x84BB6BAE, 0x8FB562A3, 0xBE9F5D80, 0xB591548D, 0xA8834F9A, 0xA38D4697, }; /* Corresponds to _IMXC0[256] */ unsigned int mtpz_aes_gb14[] = { 0x00000000, 0x0E090D0B, 0x1C121A16, 0x121B171D, 0x3824342C, 0x362D3927, 0x24362E3A, 0x2A3F2331, 0x70486858, 0x7E416553, 0x6C5A724E, 0x62537F45, 0x486C5C74, 0x4665517F, 0x547E4662, 0x5A774B69, 0xE090D0B0, 0xEE99DDBB, 0xFC82CAA6, 0xF28BC7AD, 0xD8B4E49C, 0xD6BDE997, 0xC4A6FE8A, 0xCAAFF381, 0x90D8B8E8, 0x9ED1B5E3, 0x8CCAA2FE, 0x82C3AFF5, 0xA8FC8CC4, 0xA6F581CF, 0xB4EE96D2, 0xBAE79BD9, 0xDB3BBB7B, 0xD532B670, 0xC729A16D, 0xC920AC66, 0xE31F8F57, 0xED16825C, 0xFF0D9541, 0xF104984A, 0xAB73D323, 0xA57ADE28, 0xB761C935, 0xB968C43E, 0x9357E70F, 0x9D5EEA04, 0x8F45FD19, 0x814CF012, 0x3BAB6BCB, 0x35A266C0, 0x27B971DD, 0x29B07CD6, 0x038F5FE7, 0x0D8652EC, 0x1F9D45F1, 0x119448FA, 0x4BE30393, 0x45EA0E98, 0x57F11985, 0x59F8148E, 0x73C737BF, 0x7DCE3AB4, 0x6FD52DA9, 0x61DC20A2, 0xAD766DF6, 0xA37F60FD, 0xB16477E0, 0xBF6D7AEB, 0x955259DA, 0x9B5B54D1, 0x894043CC, 0x87494EC7, 0xDD3E05AE, 0xD33708A5, 0xC12C1FB8, 0xCF2512B3, 0xE51A3182, 0xEB133C89, 0xF9082B94, 0xF701269F, 0x4DE6BD46, 0x43EFB04D, 0x51F4A750, 0x5FFDAA5B, 0x75C2896A, 0x7BCB8461, 0x69D0937C, 0x67D99E77, 0x3DAED51E, 0x33A7D815, 0x21BCCF08, 0x2FB5C203, 0x058AE132, 0x0B83EC39, 0x1998FB24, 0x1791F62F, 0x764DD68D, 0x7844DB86, 0x6A5FCC9B, 0x6456C190, 0x4E69E2A1, 0x4060EFAA, 0x527BF8B7, 0x5C72F5BC, 0x0605BED5, 0x080CB3DE, 0x1A17A4C3, 0x141EA9C8, 0x3E218AF9, 0x302887F2, 0x223390EF, 0x2C3A9DE4, 0x96DD063D, 0x98D40B36, 0x8ACF1C2B, 0x84C61120, 0xAEF93211, 0xA0F03F1A, 0xB2EB2807, 0xBCE2250C, 0xE6956E65, 0xE89C636E, 0xFA877473, 0xF48E7978, 0xDEB15A49, 0xD0B85742, 0xC2A3405F, 0xCCAA4D54, 0x41ECDAF7, 0x4FE5D7FC, 0x5DFEC0E1, 0x53F7CDEA, 0x79C8EEDB, 0x77C1E3D0, 0x65DAF4CD, 0x6BD3F9C6, 0x31A4B2AF, 0x3FADBFA4, 0x2DB6A8B9, 0x23BFA5B2, 0x09808683, 0x07898B88, 0x15929C95, 0x1B9B919E, 0xA17C0A47, 0xAF75074C, 0xBD6E1051, 0xB3671D5A, 0x99583E6B, 0x97513360, 0x854A247D, 0x8B432976, 0xD134621F, 0xDF3D6F14, 0xCD267809, 0xC32F7502, 0xE9105633, 0xE7195B38, 0xF5024C25, 0xFB0B412E, 0x9AD7618C, 0x94DE6C87, 0x86C57B9A, 0x88CC7691, 0xA2F355A0, 0xACFA58AB, 0xBEE14FB6, 0xB0E842BD, 0xEA9F09D4, 0xE49604DF, 0xF68D13C2, 0xF8841EC9, 0xD2BB3DF8, 0xDCB230F3, 0xCEA927EE, 0xC0A02AE5, 0x7A47B13C, 0x744EBC37, 0x6655AB2A, 0x685CA621, 0x42638510, 0x4C6A881B, 0x5E719F06, 0x5078920D, 0x0A0FD964, 0x0406D46F, 0x161DC372, 0x1814CE79, 0x322BED48, 0x3C22E043, 0x2E39F75E, 0x2030FA55, 0xEC9AB701, 0xE293BA0A, 0xF088AD17, 0xFE81A01C, 0xD4BE832D, 0xDAB78E26, 0xC8AC993B, 0xC6A59430, 0x9CD2DF59, 0x92DBD252, 0x80C0C54F, 0x8EC9C844, 0xA4F6EB75, 0xAAFFE67E, 0xB8E4F163, 0xB6EDFC68, 0x0C0A67B1, 0x02036ABA, 0x10187DA7, 0x1E1170AC, 0x342E539D, 0x3A275E96, 0x283C498B, 0x26354480, 0x7C420FE9, 0x724B02E2, 0x605015FF, 0x6E5918F4, 0x44663BC5, 0x4A6F36CE, 0x587421D3, 0x567D2CD8, 0x37A10C7A, 0x39A80171, 0x2BB3166C, 0x25BA1B67, 0x0F853856, 0x018C355D, 0x13972240, 0x1D9E2F4B, 0x47E96422, 0x49E06929, 0x5BFB7E34, 0x55F2733F, 0x7FCD500E, 0x71C45D05, 0x63DF4A18, 0x6DD64713, 0xD731DCCA, 0xD938D1C1, 0xCB23C6DC, 0xC52ACBD7, 0xEF15E8E6, 0xE11CE5ED, 0xF307F2F0, 0xFD0EFFFB, 0xA779B492, 0xA970B999, 0xBB6BAE84, 0xB562A38F, 0x9F5D80BE, 0x91548DB5, 0x834F9AA8, 0x8D4697A3, } ; /* Corresponds to _IMXC2[256] */ unsigned int mtpz_aes_gb13[] = { 0x00000000, 0x0D0B0E09, 0x1A161C12, 0x171D121B, 0x342C3824, 0x3927362D, 0x2E3A2436, 0x23312A3F, 0x68587048, 0x65537E41, 0x724E6C5A, 0x7F456253, 0x5C74486C, 0x517F4665, 0x4662547E, 0x4B695A77, 0xD0B0E090, 0xDDBBEE99, 0xCAA6FC82, 0xC7ADF28B, 0xE49CD8B4, 0xE997D6BD, 0xFE8AC4A6, 0xF381CAAF, 0xB8E890D8, 0xB5E39ED1, 0xA2FE8CCA, 0xAFF582C3, 0x8CC4A8FC, 0x81CFA6F5, 0x96D2B4EE, 0x9BD9BAE7, 0xBB7BDB3B, 0xB670D532, 0xA16DC729, 0xAC66C920, 0x8F57E31F, 0x825CED16, 0x9541FF0D, 0x984AF104, 0xD323AB73, 0xDE28A57A, 0xC935B761, 0xC43EB968, 0xE70F9357, 0xEA049D5E, 0xFD198F45, 0xF012814C, 0x6BCB3BAB, 0x66C035A2, 0x71DD27B9, 0x7CD629B0, 0x5FE7038F, 0x52EC0D86, 0x45F11F9D, 0x48FA1194, 0x03934BE3, 0x0E9845EA, 0x198557F1, 0x148E59F8, 0x37BF73C7, 0x3AB47DCE, 0x2DA96FD5, 0x20A261DC, 0x6DF6AD76, 0x60FDA37F, 0x77E0B164, 0x7AEBBF6D, 0x59DA9552, 0x54D19B5B, 0x43CC8940, 0x4EC78749, 0x05AEDD3E, 0x08A5D337, 0x1FB8C12C, 0x12B3CF25, 0x3182E51A, 0x3C89EB13, 0x2B94F908, 0x269FF701, 0xBD464DE6, 0xB04D43EF, 0xA75051F4, 0xAA5B5FFD, 0x896A75C2, 0x84617BCB, 0x937C69D0, 0x9E7767D9, 0xD51E3DAE, 0xD81533A7, 0xCF0821BC, 0xC2032FB5, 0xE132058A, 0xEC390B83, 0xFB241998, 0xF62F1791, 0xD68D764D, 0xDB867844, 0xCC9B6A5F, 0xC1906456, 0xE2A14E69, 0xEFAA4060, 0xF8B7527B, 0xF5BC5C72, 0xBED50605, 0xB3DE080C, 0xA4C31A17, 0xA9C8141E, 0x8AF93E21, 0x87F23028, 0x90EF2233, 0x9DE42C3A, 0x063D96DD, 0x0B3698D4, 0x1C2B8ACF, 0x112084C6, 0x3211AEF9, 0x3F1AA0F0, 0x2807B2EB, 0x250CBCE2, 0x6E65E695, 0x636EE89C, 0x7473FA87, 0x7978F48E, 0x5A49DEB1, 0x5742D0B8, 0x405FC2A3, 0x4D54CCAA, 0xDAF741EC, 0xD7FC4FE5, 0xC0E15DFE, 0xCDEA53F7, 0xEEDB79C8, 0xE3D077C1, 0xF4CD65DA, 0xF9C66BD3, 0xB2AF31A4, 0xBFA43FAD, 0xA8B92DB6, 0xA5B223BF, 0x86830980, 0x8B880789, 0x9C951592, 0x919E1B9B, 0x0A47A17C, 0x074CAF75, 0x1051BD6E, 0x1D5AB367, 0x3E6B9958, 0x33609751, 0x247D854A, 0x29768B43, 0x621FD134, 0x6F14DF3D, 0x7809CD26, 0x7502C32F, 0x5633E910, 0x5B38E719, 0x4C25F502, 0x412EFB0B, 0x618C9AD7, 0x6C8794DE, 0x7B9A86C5, 0x769188CC, 0x55A0A2F3, 0x58ABACFA, 0x4FB6BEE1, 0x42BDB0E8, 0x09D4EA9F, 0x04DFE496, 0x13C2F68D, 0x1EC9F884, 0x3DF8D2BB, 0x30F3DCB2, 0x27EECEA9, 0x2AE5C0A0, 0xB13C7A47, 0xBC37744E, 0xAB2A6655, 0xA621685C, 0x85104263, 0x881B4C6A, 0x9F065E71, 0x920D5078, 0xD9640A0F, 0xD46F0406, 0xC372161D, 0xCE791814, 0xED48322B, 0xE0433C22, 0xF75E2E39, 0xFA552030, 0xB701EC9A, 0xBA0AE293, 0xAD17F088, 0xA01CFE81, 0x832DD4BE, 0x8E26DAB7, 0x993BC8AC, 0x9430C6A5, 0xDF599CD2, 0xD25292DB, 0xC54F80C0, 0xC8448EC9, 0xEB75A4F6, 0xE67EAAFF, 0xF163B8E4, 0xFC68B6ED, 0x67B10C0A, 0x6ABA0203, 0x7DA71018, 0x70AC1E11, 0x539D342E, 0x5E963A27, 0x498B283C, 0x44802635, 0x0FE97C42, 0x02E2724B, 0x15FF6050, 0x18F46E59, 0x3BC54466, 0x36CE4A6F, 0x21D35874, 0x2CD8567D, 0x0C7A37A1, 0x017139A8, 0x166C2BB3, 0x1B6725BA, 0x38560F85, 0x355D018C, 0x22401397, 0x2F4B1D9E, 0x642247E9, 0x692949E0, 0x7E345BFB, 0x733F55F2, 0x500E7FCD, 0x5D0571C4, 0x4A1863DF, 0x47136DD6, 0xDCCAD731, 0xD1C1D938, 0xC6DCCB23, 0xCBD7C52A, 0xE8E6EF15, 0xE5EDE11C, 0xF2F0F307, 0xFFFBFD0E, 0xB492A779, 0xB999A970, 0xAE84BB6B, 0xA38FB562, 0x80BE9F5D, 0x8DB59154, 0x9AA8834F, 0x97A38D46, }; /* Corresponds to _IMXC3[256] */ unsigned int mtpz_aes_gb9[] = { 0x00000000, 0x090D0B0E, 0x121A161C, 0x1B171D12, 0x24342C38, 0x2D392736, 0x362E3A24, 0x3F23312A, 0x48685870, 0x4165537E, 0x5A724E6C, 0x537F4562, 0x6C5C7448, 0x65517F46, 0x7E466254, 0x774B695A, 0x90D0B0E0, 0x99DDBBEE, 0x82CAA6FC, 0x8BC7ADF2, 0xB4E49CD8, 0xBDE997D6, 0xA6FE8AC4, 0xAFF381CA, 0xD8B8E890, 0xD1B5E39E, 0xCAA2FE8C, 0xC3AFF582, 0xFC8CC4A8, 0xF581CFA6, 0xEE96D2B4, 0xE79BD9BA, 0x3BBB7BDB, 0x32B670D5, 0x29A16DC7, 0x20AC66C9, 0x1F8F57E3, 0x16825CED, 0x0D9541FF, 0x04984AF1, 0x73D323AB, 0x7ADE28A5, 0x61C935B7, 0x68C43EB9, 0x57E70F93, 0x5EEA049D, 0x45FD198F, 0x4CF01281, 0xAB6BCB3B, 0xA266C035, 0xB971DD27, 0xB07CD629, 0x8F5FE703, 0x8652EC0D, 0x9D45F11F, 0x9448FA11, 0xE303934B, 0xEA0E9845, 0xF1198557, 0xF8148E59, 0xC737BF73, 0xCE3AB47D, 0xD52DA96F, 0xDC20A261, 0x766DF6AD, 0x7F60FDA3, 0x6477E0B1, 0x6D7AEBBF, 0x5259DA95, 0x5B54D19B, 0x4043CC89, 0x494EC787, 0x3E05AEDD, 0x3708A5D3, 0x2C1FB8C1, 0x2512B3CF, 0x1A3182E5, 0x133C89EB, 0x082B94F9, 0x01269FF7, 0xE6BD464D, 0xEFB04D43, 0xF4A75051, 0xFDAA5B5F, 0xC2896A75, 0xCB84617B, 0xD0937C69, 0xD99E7767, 0xAED51E3D, 0xA7D81533, 0xBCCF0821, 0xB5C2032F, 0x8AE13205, 0x83EC390B, 0x98FB2419, 0x91F62F17, 0x4DD68D76, 0x44DB8678, 0x5FCC9B6A, 0x56C19064, 0x69E2A14E, 0x60EFAA40, 0x7BF8B752, 0x72F5BC5C, 0x05BED506, 0x0CB3DE08, 0x17A4C31A, 0x1EA9C814, 0x218AF93E, 0x2887F230, 0x3390EF22, 0x3A9DE42C, 0xDD063D96, 0xD40B3698, 0xCF1C2B8A, 0xC6112084, 0xF93211AE, 0xF03F1AA0, 0xEB2807B2, 0xE2250CBC, 0x956E65E6, 0x9C636EE8, 0x877473FA, 0x8E7978F4, 0xB15A49DE, 0xB85742D0, 0xA3405FC2, 0xAA4D54CC, 0xECDAF741, 0xE5D7FC4F, 0xFEC0E15D, 0xF7CDEA53, 0xC8EEDB79, 0xC1E3D077, 0xDAF4CD65, 0xD3F9C66B, 0xA4B2AF31, 0xADBFA43F, 0xB6A8B92D, 0xBFA5B223, 0x80868309, 0x898B8807, 0x929C9515, 0x9B919E1B, 0x7C0A47A1, 0x75074CAF, 0x6E1051BD, 0x671D5AB3, 0x583E6B99, 0x51336097, 0x4A247D85, 0x4329768B, 0x34621FD1, 0x3D6F14DF, 0x267809CD, 0x2F7502C3, 0x105633E9, 0x195B38E7, 0x024C25F5, 0x0B412EFB, 0xD7618C9A, 0xDE6C8794, 0xC57B9A86, 0xCC769188, 0xF355A0A2, 0xFA58ABAC, 0xE14FB6BE, 0xE842BDB0, 0x9F09D4EA, 0x9604DFE4, 0x8D13C2F6, 0x841EC9F8, 0xBB3DF8D2, 0xB230F3DC, 0xA927EECE, 0xA02AE5C0, 0x47B13C7A, 0x4EBC3774, 0x55AB2A66, 0x5CA62168, 0x63851042, 0x6A881B4C, 0x719F065E, 0x78920D50, 0x0FD9640A, 0x06D46F04, 0x1DC37216, 0x14CE7918, 0x2BED4832, 0x22E0433C, 0x39F75E2E, 0x30FA5520, 0x9AB701EC, 0x93BA0AE2, 0x88AD17F0, 0x81A01CFE, 0xBE832DD4, 0xB78E26DA, 0xAC993BC8, 0xA59430C6, 0xD2DF599C, 0xDBD25292, 0xC0C54F80, 0xC9C8448E, 0xF6EB75A4, 0xFFE67EAA, 0xE4F163B8, 0xEDFC68B6, 0x0A67B10C, 0x036ABA02, 0x187DA710, 0x1170AC1E, 0x2E539D34, 0x275E963A, 0x3C498B28, 0x35448026, 0x420FE97C, 0x4B02E272, 0x5015FF60, 0x5918F46E, 0x663BC544, 0x6F36CE4A, 0x7421D358, 0x7D2CD856, 0xA10C7A37, 0xA8017139, 0xB3166C2B, 0xBA1B6725, 0x8538560F, 0x8C355D01, 0x97224013, 0x9E2F4B1D, 0xE9642247, 0xE0692949, 0xFB7E345B, 0xF2733F55, 0xCD500E7F, 0xC45D0571, 0xDF4A1863, 0xD647136D, 0x31DCCAD7, 0x38D1C1D9, 0x23C6DCCB, 0x2ACBD7C5, 0x15E8E6EF, 0x1CE5EDE1, 0x07F2F0F3, 0x0EFFFBFD, 0x79B492A7, 0x70B999A9, 0x6BAE84BB, 0x62A38FB5, 0x5D80BE9F, 0x548DB591, 0x4F9AA883, 0x4697A38D, }; static uint16_t ptp_mtpz_validatehandshakeresponse (PTPParams* params, unsigned char *random, unsigned char **calculatedHash) { uint16_t ret; unsigned int len; unsigned char* response = NULL; ret = ptp_mtpz_getwmdrmpdappresponse (params, &response, &len); if (ret == PTP_RC_OK) { char *reader = (char *)response; int i; if (*(reader++) != '\x02') { return -1; } if (*(reader++) != '\x02') { return -1; } // Message is always 128 bytes. reader++; if (*(reader++) != '\x80') { return -1; } char *message = (char *)malloc(128); memcpy(message, reader, 128); reader += 128; // Decrypt the hash-key-message.. char *msg_dec = (char *)malloc(128); memset(msg_dec, 0, 128); mtpz_rsa_t *rsa = mtpz_rsa_init(MTPZ_MODULUS, MTPZ_PRIVATE_KEY, MTPZ_PUBLIC_EXPONENT); if (!rsa) { LIBMTP_INFO ("(MTPZ) Failure - could not instantiate RSA object.\n"); free(message); free(msg_dec); return -1; } if (mtpz_rsa_decrypt(128, (unsigned char *)message, 128, (unsigned char *)msg_dec, rsa) == 0) { LIBMTP_INFO ("(MTPZ) Failure - could not perform RSA decryption.\n"); free(message); free(msg_dec); mtpz_rsa_free(rsa); return -1; } mtpz_rsa_free(rsa); rsa = NULL; char *state = mtpz_hash_init_state(); char *hash_key = (char *)malloc(16); char *v10 = mtpz_hash_custom6A5DC(state, msg_dec + 21, 107, 20); for (i = 0; i < 20; i++) msg_dec[i + 1] ^= v10[i]; char *v11 = mtpz_hash_custom6A5DC(state, msg_dec + 1, 20, 107); for (i = 0; i < 107; i++) msg_dec[i + 21] ^= v11[i]; memcpy(hash_key, msg_dec + 112, 16); // Encrypted message is 0x340 bytes. reader += 2; if (*(reader++) != '\x03' || *(reader++) != '\x40') { return -1; } unsigned char *act_msg = (unsigned char *)malloc(832); unsigned char *act_reader = act_msg; memcpy(act_msg, reader, 832); reader = NULL; mtpz_encryption_cipher_advanced((unsigned char *)hash_key, 16, act_msg, 832, 0); act_reader++; unsigned int certs_length = MTPZ_SWAP(*(unsigned int *)(act_reader)); act_reader += 4; act_reader += certs_length; unsigned int rand_length = MTPZ_SWAP(*(unsigned short *)(act_reader) << 16); act_reader += 2; unsigned char *rand_data = (unsigned char *)malloc(rand_length); memcpy(rand_data, act_reader, rand_length); if (memcmp(rand_data, random, 16) != 0) { free(rand_data); return -1; } free(rand_data); act_reader += rand_length; unsigned int dev_rand_length = MTPZ_SWAP(*(unsigned short *)(act_reader) << 16); act_reader += 2; act_reader += dev_rand_length; act_reader++; unsigned int sig_length = MTPZ_SWAP(*(unsigned short *)(act_reader) << 16); act_reader += 2; act_reader += sig_length; act_reader++; unsigned int machash_length = MTPZ_SWAP(*(unsigned short *)(act_reader) << 16); act_reader += 2; unsigned char *machash_data = (unsigned char *)malloc(machash_length); memcpy(machash_data, act_reader, machash_length); act_reader += machash_length; *calculatedHash = machash_data; free(message); free(msg_dec); free(state); free(v10); free(v11); free(act_msg); } else { LIBMTP_INFO ("(MTPZ) Failure - did not receive device's response.\n"); } return ret; } static uint16_t ptp_mtpz_opensecuresyncsession (PTPParams* params, unsigned char *hash) { unsigned char mch[16]; uint32_t *hashparams = (unsigned int *)mch; unsigned int macCount = *(unsigned int *)(hash + 16); uint16_t ret; mtpz_encryption_encrypt_mac(hash, 16, (unsigned char *)(&macCount), 4, mch); ret = ptp_mtpz_wmdrmpd_enabletrustedfilesoperations(params, MTPZ_SWAP(hashparams[0]), MTPZ_SWAP(hashparams[1]), MTPZ_SWAP(hashparams[2]), MTPZ_SWAP(hashparams[3])); return ret; }; static unsigned char * ptp_mtpz_makeapplicationcertificatemessage (unsigned int *out_len, unsigned char **out_random) { *out_len = 785; unsigned char *acm = (unsigned char *)malloc(785); unsigned char *target = acm; memset(acm, 0, 785); unsigned char *random = (unsigned char *)malloc(16); int i = 0; int certsLength = 0x275; // Write the marker bytes, length of certificates, and certificates themselves. *(target++) = '\x02'; *(target++) = '\x01'; *(target++) = '\x01'; *(target++) = '\x00'; *(target++) = '\x00'; *(target++) = '\x02'; *(target++) = '\x75'; memcpy(target, MTPZ_CERTIFICATES, certsLength); target += certsLength; // Write the random bytes. *(target++) = '\x00'; *(target++) = '\x10'; srand(time(NULL)); for (i = 0; i < 16; i++) *(random + i) = (unsigned char)(rand() % 256); *out_random = random; memcpy(target, random, 16); target += 16; char *state = mtpz_hash_init_state(); char *v16 = (char *)malloc(28); memset(v16, 0, 28); char *hash = (char *)malloc(20); memset(hash, 0, 20); char *odata = (char *)malloc(128); memset(odata, 0, 128); mtpz_hash_reset_state(state); mtpz_hash_transform_hash(state, (char *)acm + 2, (target - acm - 2)); mtpz_hash_finalize_hash(state, v16 + 8); mtpz_hash_reset_state(state); mtpz_hash_transform_hash(state, v16, 28); mtpz_hash_finalize_hash(state, hash); char *v17 = mtpz_hash_custom6A5DC(state, hash, 20, 107); for (i = 0; i < 20; i++) odata[107 + i] = hash[i]; odata[106] = '\x01'; if (v17 != NULL) { for (i = 0; i < 107; i++) odata[i] ^= v17[i]; odata[0] &= 127; odata[127] = 188; } // Free up some jazz. free(state); state = NULL; free(v16); v16 = NULL; free(v17); v17 = NULL; free(hash); hash = NULL; // Take care of some RSA jazz. mtpz_rsa_t *rsa = mtpz_rsa_init(MTPZ_MODULUS, MTPZ_PRIVATE_KEY, MTPZ_PUBLIC_EXPONENT); if (!rsa) { LIBMTP_INFO("(MTPZ) Failure - could not instantiate RSA object.\n"); *out_len = 0; return NULL; } char *signature = (char *)malloc(128); memset(signature, 0, 128); mtpz_rsa_sign(128, (unsigned char *)odata, 128, (unsigned char *)signature, rsa); // Free some more things. mtpz_rsa_free(rsa); rsa = NULL; free(odata); odata = NULL; // Write the signature + bytes. *(target++) = '\x01'; *(target++) = '\x00'; *(target++) = '\x80'; memcpy(target, signature, 128); // Kill target. target = NULL; return acm; }; static unsigned char * ptp_mtpz_makeconfirmationmessage (unsigned char *hash, unsigned int *out_len) { *out_len = 20; unsigned char *message = (unsigned char *)malloc(20); message[0] = (unsigned char)0x02; message[1] = (unsigned char)0x03; message[2] = (unsigned char)0x00; message[3] = (unsigned char)0x10; unsigned char *seed = (unsigned char *)malloc(16); memset(seed, 0, 16); seed[15] = (unsigned char)(0x01); mtpz_encryption_encrypt_mac(hash, 16u, seed, 16u, message + 4); free(seed); return message; } uint16_t ptp_mtpz_handshake (PTPParams* params) { uint16_t ret = PTP_RC_OK; uint32_t size; unsigned char *hash=NULL; unsigned char *random=NULL; PTPPropertyValue propval; unsigned char* applicationCertificateMessage; unsigned char* message; /* FIXME: do other places of libmtp set it? should we set it? */ LIBMTP_INFO ("(MTPZ) Setting session initiator info.\n"); propval.str = "libmtp/Sajid Anwar - MTPZClassDriver"; ret = ptp_setdevicepropvalue(params, PTP_DPC_MTP_SessionInitiatorInfo, &propval, PTP_DTC_STR); if (ret != PTP_RC_OK) return ret; LIBMTP_INFO ("(MTPZ) Resetting handshake.\n"); ret = ptp_mtpz_resethandshake(params); if (ret != PTP_RC_OK) return ret; LIBMTP_INFO ("(MTPZ) Sending application certificate message.\n"); applicationCertificateMessage = ptp_mtpz_makeapplicationcertificatemessage(&size, &random); ret = ptp_mtpz_sendwmdrmpdapprequest (params, applicationCertificateMessage, size); free (applicationCertificateMessage); if (ret != PTP_RC_OK) return ret; LIBMTP_INFO ("(MTPZ) Getting and validating handshake response.\n"); ret = ptp_mtpz_validatehandshakeresponse(params, random, &hash); if (ret != PTP_RC_OK) goto free_random; LIBMTP_INFO ("(MTPZ) Sending confirmation message.\n"); message = ptp_mtpz_makeconfirmationmessage(hash, &size); ret = ptp_mtpz_sendwmdrmpdapprequest (params, message, size); if (ret != PTP_RC_OK) goto free_hash; free (message); LIBMTP_INFO ("(MTPZ) Opening secure sync session.\n"); ret = ptp_mtpz_opensecuresyncsession(params, hash); free_hash: free(hash); free_random: free(random); return ret; } libmtp-1.1.6-20-g1b9f164/src/music-players.h0000664000175000017500000030145212205614637020454 0ustar glowwormglowworm/** * \file music-players.h * List of music players as USB ids. * * Copyright (C) 2005-2007 Richard A. Low * Copyright (C) 2005-2013 Linus Walleij * Copyright (C) 2006-2007 Marcus Meissner * Copyright (C) 2007 Ted Bullock * Copyright (C) 2012 Sony Mobile Communications AB * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * This file is supposed to be included within a struct from both libmtp * and libgphoto2. * * Information can be harvested from Windows driver .INF files, see: * http://msdn.microsoft.com/en-us/library/aa973606.aspx */ /* * MTP device list, trying real bad to get all devices into * this list by stealing from everyone I know. * Some devices taken from the Rockbox device listing: * http://www.rockbox.org/twiki/bin/view/Main/DeviceDetection */ /* * Creative Technology and ZiiLABS * Initially the Creative devices was all we supported so these are * the most thoroughly tested devices. Presumably only the devices * with older firmware (the ones that have 32bit object size) will * need the DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL flag. This bug * manifest itself when you have a lot of folders on the device, * some of the folders will start to disappear when getting all objects * and properties. */ { "Creative", 0x041e, "ZEN Vision", 0x411f, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, { "Creative", 0x041e, "Portable Media Center", 0x4123, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, { "Creative", 0x041e, "ZEN Xtra (MTP mode)", 0x4128, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, { "Dell", 0x041e, "DJ (2nd generation)", 0x412f, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, { "Creative", 0x041e, "ZEN Micro (MTP mode)", 0x4130, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, { "Creative", 0x041e, "ZEN Touch (MTP mode)", 0x4131, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, { "Dell", 0x041e, "Dell Pocket DJ (MTP mode)", 0x4132, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, { "Creative", 0x041e, "ZEN MicroPhoto (alternate version)", 0x4133, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, { "Creative", 0x041e, "ZEN Sleek (MTP mode)", 0x4137, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, { "Creative", 0x041e, "ZEN MicroPhoto", 0x413c, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, { "Creative", 0x041e, "ZEN Sleek Photo", 0x413d, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, { "Creative", 0x041e, "ZEN Vision:M", 0x413e, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, // Reported by marazm@o2.pl { "Creative", 0x041e, "ZEN V", 0x4150, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, // Reported by danielw@iinet.net.au // This version of the Vision:M needs the no release interface flag, // unclear whether the other version above need it too or not. { "Creative", 0x041e, "ZEN Vision:M (DVP-HD0004)", 0x4151, DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, // Reported by Darel on the XNJB forums { "Creative", 0x041e, "ZEN V Plus", 0x4152, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, { "Creative", 0x041e, "ZEN Vision W", 0x4153, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, // Don't add 0x4155: this is a Zen Stone device which is not MTP // Reported by Paul Kurczaba { "Creative", 0x041e, "ZEN", 0x4157, DEVICE_FLAG_IGNORE_HEADER_ERRORS | DEVICE_FLAG_BROKEN_SET_SAMPLE_DIMENSIONS | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, // Reported by Ringofan { "Creative", 0x041e, "ZEN V 2GB", 0x4158, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, // Reported by j norment { "Creative", 0x041e, "ZEN Mozaic", 0x4161, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, // Reported by Aaron F. Gonzalez { "Creative", 0x041e, "ZEN X-Fi", 0x4162, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, // Reported by farmerstimuli { "Creative", 0x041e, "ZEN X-Fi 3", 0x4169, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_GET_OBJECT_PROPVAL }, // Reported by Todor Gyumyushev { "ZiiLABS", 0x041e, "Zii EGG", 0x6000, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_ALWAYS_PROBE_DESCRIPTOR | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED }, /* * Samsung * We suspect that more of these are dual mode. * We suspect more of these might need DEVICE_FLAG_NO_ZERO_READS * We suspect more of these might need DEVICE_FLAG_PLAYLIST_SPL_V1 * or DEVICE_FLAG_PLAYLIST_SPL_V2 to get playlists working. * YP-NEU, YP-NDU, YP-20, YP-800, YP-MF Series, YP-100, YP-30 * YP-700 and YP-90 are NOT MTP, but use a Samsung custom protocol. * See: http://wiki.xiph.org/index.php/PortablePlayers for Ogg * status. */ // From anonymous SourceForge user, not verified { "Samsung", 0x04e8, "YP-900", 0x0409, DEVICE_FLAG_NONE }, // From MItch { "Samsung", 0x04e8, "I550W Phone", 0x04a4, DEVICE_FLAG_NONE }, // From Manfred Enning { "Samsung", 0x04e8, "Jet S8000", 0x4f1f, DEVICE_FLAG_NONE }, // From Gabriel Nunes { "Samsung", 0x04e8, "YH-920 (501d)", 0x501d, DEVICE_FLAG_UNLOAD_DRIVER }, // From Soren O'Neill { "Samsung", 0x04e8, "YH-920 (5022)", 0x5022, DEVICE_FLAG_UNLOAD_DRIVER }, // Contributed by aronvanammers on SourceForge { "Samsung", 0x04e8, "YH-925GS", 0x5024, DEVICE_FLAG_NONE }, // From libgphoto2, according to tests by Stephan Fabel it cannot // get all objects with the getobjectproplist command.. { "Samsung", 0x04e8, "YH-820", 0x502e, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL }, // Contributed by polux2001@users.sourceforge.net { "Samsung", 0x04e8, "YH-925(-GS)", 0x502f, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL }, // Contributed by anonymous person on SourceForge { "Samsung", 0x04e8, "YH-J70J", 0x5033, DEVICE_FLAG_UNLOAD_DRIVER }, // From XNJB user // Guessing on .spl flag { "Samsung", 0x04e8, "YP-Z5", 0x503c, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_PLAYLIST_SPL_V1 }, // Don't add 0x5041 as this is YP-Z5 in USB mode // Contributed by anonymous person on SourceForge { "Samsung", 0x04e8, "YP-T7J", 0x5047, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_OGG_IS_UNKNOWN }, // Reported by cstrickler@gmail.com { "Samsung", 0x04e8, "YP-U2J (YP-U2JXB/XAA)", 0x5054, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_OGG_IS_UNKNOWN }, // Reported by Andrew Benson { "Samsung", 0x04e8, "YP-F2J", 0x5057, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Patrick // Just guessing but looks like .spl v1 http://www.anythingbutipod.com/forum/showthread.php?t=14160 { "Samsung", 0x04e8, "YP-K5", 0x505a, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_PLAYLIST_SPL_V1 }, // From dev.local@gmail.com - 0x4e8/0x507c is the UMS mode, apparently // do not add that device. // From m.eik michalke // This device does NOT use the special SPL playlist according to sypqgjxu@gmx.de. { "Samsung", 0x04e8, "YP-U3", 0x507d, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_OGG_IS_UNKNOWN }, // Reported by Matthew Wilcox // Sergio reports this device need the BROKEN ALL flag. // Guessing on .spl flag { "Samsung", 0x04e8, "YP-T9", 0x507f, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_PLAYLIST_SPL_V1 }, // From Paul Clinch // Just guessing but looks like .spl v1 http://www.anythingbutipod.com/forum/showthread.php?t=14160 // Some versions of the firmware reportedly support OGG, reportedly only the // UMS versions, so MTP+OGG is not possible on this device. { "Samsung", 0x04e8, "YP-K3", 0x5081, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_PLAYLIST_SPL_V1 }, // From XNJB user // From Alistair Boyle, .spl v2 required for playlists // According to the device log it properly supports OGG { "Samsung", 0x04e8, "YP-P2", 0x5083, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_PLAYLIST_SPL_V2 }, // From Paul Clinch // Guessing on .spl flag { "Samsung", 0x04e8, "YP-T10", 0x508a, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_PLAYLIST_SPL_V1 | DEVICE_FLAG_NO_ZERO_READS }, // From Wim Verwimp // Not sure about the Ogg and broken proplist flags here. Just guessing. // Guessing on .spl flag { "Samsung", 0x04e8, "YP-S5", 0x508b, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_PLAYLIST_SPL_V1 }, // From Ludovic Danigo // Guessing on .spl flag { "Samsung", 0x04e8, "YP-S3", 0x5091, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_PLAYLIST_SPL_V1 }, // From Adrian Levi // Guessing on .spl flag // This one supports OGG properly through the correct MTP type. { "Samsung", 0x04e8, "YP-U4", 0x5093, DEVICE_FLAG_UNLOAD_DRIVER }, // From Chris Le Sueur // Guessing on .spl flag // This one supports OGG properly through the correct MTP type. { "Samsung", 0x04e8, "YP-R1", 0x510f, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_UNIQUE_FILENAMES | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // From Anonymous SourceForge user // Guessing on .spl flag { "Samsung", 0x04e8, "YP-Q1", 0x5115, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_PLAYLIST_SPL_V1 }, // From Holger { "Samsung", 0x04e8, "YP-M1", 0x5118, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_PLAYLIST_SPL_V2 }, // From Anonymous SourceForge user // Guessing on .spl flag { "Samsung", 0x04e8, "YP-P3", 0x511a, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_PLAYLIST_SPL_V1 }, // From Anonymous SourceForge user // Guessing on .spl flag { "Samsung", 0x04e8, "YP-Q2", 0x511d, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_PLAYLIST_SPL_V1 }, // From Marco Pizzocaro // Guessing on .spl flag { "Samsung", 0x04e8, "YP-U5", 0x5121, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_PLAYLIST_SPL_V1 | DEVICE_FLAG_UNIQUE_FILENAMES | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // From Leonardo Accorsi // Guessing on .spl flag { "Samsung", 0x04e8, "YP-R0", 0x5125, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_PLAYLIST_SPL_V1 | DEVICE_FLAG_UNIQUE_FILENAMES | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // The "YP-R2" (0x04e8/0x512d) is NOT MTP, it is UMS only. // Guessing on device flags for the MTP mode... { "Samsung", 0x04e8, "YP-R2", 0x512e, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_UNIQUE_FILENAMES | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_PLAYLIST_SPL_V1 }, // From Manuel Carro // Copied from Q2 { "Samsung", 0x04e8, "YP-Q3", 0x5130, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_PLAYLIST_SPL_V1 }, // Reported by: traaf // Guessing on the playlist type! // Appears to present itself properly as a PTP device with MTP extensions! { "Samsung", 0x04e8, "YP-Z3", 0x5137, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_PLAYLIST_SPL_V1 }, // YP-F3 is NOT MTP - USB mass storage // From a rouge .INF file // this device ID seems to have been recycled for: // the Samsung SGH-A707 Cingular cellphone // the Samsung L760-V cellphone // the Samsung SGH-U900 cellphone // the Samsung Fascinate player { "Samsung", 0x04e8, "YH-999 Portable Media Center/SGH-A707/SGH-L760V/SGH-U900/Verizon Intensity/Fascinate", 0x5a0f, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL }, // From Santi Béjar - not sure this is MTP... // { "Samsung", 0x04e8, "Z170 Mobile Phone", 0x6601, DEVICE_FLAG_UNLOAD_DRIVER }, // From Santi Béjar - not sure this is MTP... // { "Samsung", 0x04e8, "E250 Mobile Phone", 0x663e, DEVICE_FLAG_UNLOAD_DRIVER }, // From an anonymous SF user { "Samsung", 0x04e8, "M7600 Beat/GT-S8300T/SGH-F490/S8300", 0x6642, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_BATTERY_LEVEL }, // From Lionel Bouton { "Samsung", 0x04e8, "X830 Mobile Phone", 0x6702, DEVICE_FLAG_UNLOAD_DRIVER }, // From James { "Samsung", 0x04e8, "U600 Mobile Phone", 0x6709, DEVICE_FLAG_UNLOAD_DRIVER }, // From Cesar Cardoso // No confirmation that this is really MTP. { "Samsung", 0x04e8, "F250 Mobile Phone", 0x6727, DEVICE_FLAG_UNLOAD_DRIVER }, // From Charlie Todd 2007-10-31 { "Samsung", 0x04e8, "Juke (SCH-U470)", 0x6734, DEVICE_FLAG_UNLOAD_DRIVER}, // Reported by Tenn { "Samsung", 0x04e8, "GT-B2700", 0x6752, DEVICE_FLAG_UNLOAD_DRIVER }, // Added by Greg Fitzgerald { "Samsung", 0x04e8, "SAMSUNG Trance", 0x6763, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_PLAYLIST_SPL_V1 }, // From anonymous sourceforge user // Guessing on .spl flag, maybe needs NO_ZERO_READS, whatdoIknow { "Samsung", 0x04e8, "GT-S8500", 0x6819, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_PLAYLIST_SPL_V1 }, /* * These entries seems to be used on a *lot* of Samsung * Android phones. It is *not* the Android MTP stack but an internal * Samsung stack. The devices present a few different product IDs * depending on mode: * * 0x685b - UMS * 0x685c - MTP + ADB * 0x685e - UMS + CDC * 0x6860 - MTP mode (default) * 0x6863 - USB CDC RNDIS (not MTP) * 0x6865 - PTP mode (not MTP) * 0x6877 - Kies mode? Does it have MTP? * * Used on these samsung devices: * GT P7310/P7510/N7000/I9100/I9250/I9300 * Galaxy Nexus * Galaxy Tab 7.7/10.1 * Galaxy S GT-I9000 * Galaxy S Advance GT-I9070 * Galaxy S2 * Galaxy S3 * Galaxy Note * Galaxy Y * * - It seems that some PTP commands are broken. * - Devices seem to have a connection timeout, the session must be * open in about 3 seconds since the device is plugged in, after * that time it will not respond. Thus GUI programs work fine. * - Seems also to be used with Galaxy Nexus debug mode and on * US markets for some weird reason. * * From: Ignacio Martínez and others * From Harrison Metzger */ { "Samsung", 0x04e8, "Galaxy models (MTP+ADB)", 0x685c, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_LONG_TIMEOUT | DEVICE_FLAG_PROPLIST_OVERRIDES_OI | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, // Reported by David Goodenough // Guessing on flags. { "Samsung", 0x04e8, "Galaxy Y", 0x685e, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_LONG_TIMEOUT | DEVICE_FLAG_PROPLIST_OVERRIDES_OI | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, { "Samsung", 0x04e8, "Galaxy models (MTP)", 0x6860, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_LONG_TIMEOUT | DEVICE_FLAG_PROPLIST_OVERRIDES_OI | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, // From: Erik Berglund // Logs indicate this needs DEVICE_FLAG_NO_ZERO_READS // No Samsung platlists on this device. // https://sourceforge.net/tracker/?func=detail&atid=809061&aid=3026337&group_id=158745 // i5800 duplicate reported by igel // Guessing this has the same problematic MTP stack as the device // above. { "Samsung", 0x04e8, "Galaxy models Kies mode", 0x6877, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_LONG_TIMEOUT | DEVICE_FLAG_PROPLIST_OVERRIDES_OI | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, // From: John Gorkos and // Akos Maroy { "Samsung", 0x04e8, "Vibrant SGH-T959/Captivate/Media player mode", 0x68a9, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_PLAYLIST_SPL_V1 }, // Reported by Sleep.Walker { "Samsung", 0x04e8, "GT-B2710/Xcover 271", 0x68af, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_PLAYLIST_SPL_V1 }, // From anonymous Sourceforge user { "Samsung", 0x04e8, "GT-S5230", 0xe20c, DEVICE_FLAG_NONE }, /* * Microsoft * All except the first probably need MTPZ to work */ { "Microsoft/Intel", 0x045e, "Bandon Portable Media Center", 0x00c9, DEVICE_FLAG_NONE }, // HTC Mozart is using the PID, as is Nokia Lumia 800 // May need MTPZ to work { "Microsoft", 0x045e, "Windows Phone", 0x04ec, DEVICE_FLAG_NONE }, // Reported by Tadimarri Sarath // No idea why this use an Intel PID, perhaps a leftover from // the early PMC development days when Intel and Microsoft were // partnering. { "Microsoft", 0x045e, "Windows MTP Simulator", 0x0622, DEVICE_FLAG_NONE }, // Reported by Edward Hutchins (used for Zune HDs) { "Microsoft", 0x045e, "Zune HD", 0x063e, DEVICE_FLAG_NONE }, { "Microsoft", 0x045e, "Kin 1", 0x0640, DEVICE_FLAG_NONE }, { "Microsoft/Sharp/nVidia", 0x045e, "Kin TwoM", 0x0641, DEVICE_FLAG_NONE }, // Reported by Farooq Zaman (used for all Zunes) { "Microsoft", 0x045e, "Zune", 0x0710, DEVICE_FLAG_NONE }, // Reported by Olegs Jeremejevs { "Microsoft/HTC", 0x045e, "HTC 8S", 0xf0ca, DEVICE_FLAG_NONE }, /* * JVC */ // From Mark Veinot { "JVC", 0x04f1, "Alneo XA-HD500", 0x6105, DEVICE_FLAG_NONE }, /* * Philips */ { "Philips", 0x0471, "HDD6320/00 or HDD6330/17", 0x014b, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL }, // Anonymous SourceForge user { "Philips", 0x0471, "HDD14XX,HDD1620 or HDD1630/17", 0x014c, DEVICE_FLAG_NONE }, // from discussion forum { "Philips", 0x0471, "HDD085/00 or HDD082/17", 0x014d, DEVICE_FLAG_NONE }, // from XNJB forum { "Philips", 0x0471, "GoGear SA9200", 0x014f, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL }, // From John Coppens { "Philips", 0x0471, "SA1115/55", 0x0164, DEVICE_FLAG_NONE }, // From Gerhard Mekenkamp { "Philips", 0x0471, "GoGear Audio", 0x0165, DEVICE_FLAG_NONE }, // from David Holm { "Philips", 0x0471, "Shoqbox", 0x0172, DEVICE_FLAG_ONLY_7BIT_FILENAMES }, // from npedrosa { "Philips", 0x0471, "PSA610", 0x0181, DEVICE_FLAG_NONE }, // From libgphoto2 source { "Philips", 0x0471, "HDD6320", 0x01eb, DEVICE_FLAG_NONE }, // From Detlef Meier { "Philips", 0x0471, "GoGear SA6014/SA6015/SA6024/SA6025/SA6044/SA6045", 0x084e, DEVICE_FLAG_UNLOAD_DRIVER }, // From anonymous Sourceforge user SA5145/02 { "Philips", 0x0471, "GoGear SA5145", 0x0857, DEVICE_FLAG_UNLOAD_DRIVER }, // From a { "Philips", 0x0471, "GoGear SA6125/SA6145/SA6185", 0x2002, DEVICE_FLAG_UNLOAD_DRIVER }, // From anonymous Sourceforge user, not verified to be MTP! { "Philips", 0x0471, "GoGear SA3345", 0x2004, DEVICE_FLAG_UNLOAD_DRIVER }, // From Roberto Vidmar { "Philips", 0x0471, "SA5285", 0x2022, DEVICE_FLAG_UNLOAD_DRIVER }, // From Elie De Brauwer { "Philips", 0x0471, "GoGear ViBE SA1VBE04", 0x2075, DEVICE_FLAG_UNLOAD_DRIVER }, // From Anonymous SourceForge user { "Philips", 0x0471, "GoGear Muse", 0x2077, DEVICE_FLAG_UNLOAD_DRIVER }, // From Elie De Brauwer { "Philips", 0x0471, "GoGear ViBE SA1VBE04/08", 0x207b, DEVICE_FLAG_UNLOAD_DRIVER }, // From josmtx { "Philips", 0x0471, "GoGear Aria", 0x207c, DEVICE_FLAG_UNLOAD_DRIVER }, // From epklein { "Philips", 0x0471, "GoGear SA1VBE08KX/78", 0x208e, DEVICE_FLAG_UNLOAD_DRIVER }, // From Anonymous SourceForge User { "Philips", 0x0471, "GoGear VIBE SA2VBE[08|16]K/02", 0x20b7, DEVICE_FLAG_UNLOAD_DRIVER }, // From Anonymous SourceForge User { "Philips", 0x0471, "GoGear Ariaz", 0x20b9, DEVICE_FLAG_UNLOAD_DRIVER }, // From Anonymous SourceForge User { "Philips", 0x0471, "GoGear Vibe/02", 0x20e5, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Philip Rhoades { "Philips", 0x0471, "GoGear Ariaz/97", 0x2138, DEVICE_FLAG_UNLOAD_DRIVER }, // from XNJB user { "Philips", 0x0471, "PSA235", 0x7e01, DEVICE_FLAG_NONE }, /* * Acer * Reporters: * Franck VDL * Matthias Arndt * Arvin Schnell * Philippe Marzouk * nE0sIghT * Maxime de Roucy */ { "Acer", 0x0502, "Iconia TAB A500 (ID1)", 0x3325, DEVICE_FLAGS_ANDROID_BUGS }, { "Acer", 0x0502, "Iconia TAB A500 (ID2)", 0x3341, DEVICE_FLAGS_ANDROID_BUGS }, { "Acer", 0x0502, "Iconia TAB A501 (ID1)", 0x3344, DEVICE_FLAGS_ANDROID_BUGS }, { "Acer", 0x0502, "Iconia TAB A501 (ID2)", 0x3345, DEVICE_FLAGS_ANDROID_BUGS }, { "Acer", 0x0502, "Iconia TAB A100 (ID1)", 0x3348, DEVICE_FLAGS_ANDROID_BUGS }, { "Acer", 0x0502, "Iconia TAB A100 (ID2)", 0x3349, DEVICE_FLAGS_ANDROID_BUGS }, { "Acer", 0x0502, "Iconia TAB A700", 0x3378, DEVICE_FLAGS_ANDROID_BUGS }, { "Acer", 0x0502, "Iconia TAB A200 (ID1)", 0x337c, DEVICE_FLAGS_ANDROID_BUGS }, { "Acer", 0x0502, "Iconia TAB A200 (ID2)", 0x337d, DEVICE_FLAGS_ANDROID_BUGS }, { "Acer", 0x0502, "Iconia TAB A510 (ID1)", 0x3389, DEVICE_FLAGS_ANDROID_BUGS }, { "Acer", 0x0502, "Iconia TAB A510 (ID2)", 0x338a, DEVICE_FLAGS_ANDROID_BUGS }, { "Acer", 0x0502, "S500 CloudMobile", 0x33aa, DEVICE_FLAGS_ANDROID_BUGS }, { "Acer", 0x0502, "E350 Liquid Gallant Duo", 0x33c3, DEVICE_FLAGS_ANDROID_BUGS }, { "Acer", 0x0502, "Iconia TAB A210", 0x33cb, DEVICE_FLAGS_ANDROID_BUGS }, { "Acer", 0x0502, "Iconia TAB A110", 0x33d8, DEVICE_FLAGS_ANDROID_BUGS }, { "Acer", 0x0502, "Liquid Z120 MT65xx Android Phone", 0x3473, DEVICE_FLAGS_ANDROID_BUGS }, /* * SanDisk * several devices (c150 for sure) are definately dual-mode and must * have the USB mass storage driver that hooks them unloaded first. * They all have problematic dual-mode making the device unload effect * uncertain on these devices. * * All older devices seem to need DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL. * Old chipsets: e200/c200 use PP5024 from Nvidia (formerly PortalPlayer). * m200 use TCC770 from Telechips. * * The newer Sansa v2 chipset, AD3525 from Austriamicrosystems (AMS) found * in e280 v2 c200 v2, Clip, Fuze etc require * DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST * and DEVICE_FLAG_ALWAYS_PROBE_DESCRIPTOR to work properly. * * For more info see: http://daniel.haxx.se/sansa/v2.html */ // Reported by Brian Robison { "SanDisk", 0x0781, "Sansa m230/m240", 0x7400, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED }, // From Rockbox device listing { "SanDisk", 0x0781, "Sansa m200-tcc (MTP mode)", 0x7401, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED }, // Reported by tangent_@users.sourceforge.net { "SanDisk", 0x0781, "Sansa c150", 0x7410, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED }, // From libgphoto2 source // Reported by // Reported by Mike Owen { "SanDisk", 0x0781, "Sansa e200/e250/e260/e270/e280", 0x7420, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED }, // Don't add 0x7421 as this is e280 in MSC mode // Reported by XNJB user { "SanDisk", 0x0781, "Sansa e260/e280 v2", 0x7422, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_ALWAYS_PROBE_DESCRIPTOR | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED }, // Reported by XNJB user { "SanDisk", 0x0781, "Sansa m240/m250", 0x7430, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED }, // Reported by Eugene Brevdo { "SanDisk", 0x0781, "Sansa Clip", 0x7432, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_ALWAYS_PROBE_DESCRIPTOR | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED}, // Reported by HackAR { "SanDisk", 0x0781, "Sansa Clip v2", 0x7434, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_ALWAYS_PROBE_DESCRIPTOR | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED}, // Reported by anonymous user at sourceforge.net { "SanDisk", 0x0781, "Sansa c240/c250", 0x7450, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED }, // Reported by anonymous SourceForge user { "SanDisk", 0x0781, "Sansa c250 v2", 0x7452, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED }, // Reported by Troy Curtis Jr. { "SanDisk", 0x0781, "Sansa Express", 0x7460, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED }, // Reported by XNJB user, and Miguel de Icaza // This has no dual-mode so no need to unload any driver. // This is a Linux based device! { "SanDisk", 0x0781, "Sansa Connect", 0x7480, DEVICE_FLAG_NONE }, // Reported by anonymous SourceForge user { "SanDisk", 0x0781, "Sansa View", 0x74b0, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED }, // Reported by Patrick // There are apparently problems with this device. { "SanDisk", 0x0781, "Sansa Fuze", 0x74c0, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_ALWAYS_PROBE_DESCRIPTOR | DEVICE_FLAG_BROKEN_SET_SAMPLE_DIMENSIONS | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED }, // Harry Phillips { "SanDisk", 0x0781, "Sansa Fuze v2", 0x74c2, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_ALWAYS_PROBE_DESCRIPTOR | DEVICE_FLAG_BROKEN_SET_SAMPLE_DIMENSIONS | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED }, // Reported by anonymous SourceForge user // Need BROKEN_SET_SAMPLE_DIMENSIONS accordning to // Michael { "SanDisk", 0x0781, "Sansa Clip+", 0x74d0, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_ALWAYS_PROBE_DESCRIPTOR | DEVICE_FLAG_BROKEN_SET_SAMPLE_DIMENSIONS | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED}, // Reported by anonymous SourceForge user { "SanDisk", 0x0781, "Sansa Fuze+", 0x74e0, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_ALWAYS_PROBE_DESCRIPTOR | DEVICE_FLAG_BROKEN_SET_SAMPLE_DIMENSIONS | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED}, // Reported by mattyj2001@users.sourceforge.net { "SanDisk", 0x0781, "Sansa Clip Zip", 0x74e4, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_ALWAYS_PROBE_DESCRIPTOR | DEVICE_FLAG_BROKEN_SET_SAMPLE_DIMENSIONS | DEVICE_FLAG_CANNOT_HANDLE_DATEMODIFIED}, /* * iRiver * we assume that PTP_OC_MTP_GetObjPropList is essentially * broken on all iRiver devices, meaning it simply won't return * all properties for a file when asking for metadata 0xffffffff. * Please test on your device if you believe it isn't broken! */ { "iRiver", 0x1006, "H300 Series MTP", 0x3004, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, { "iRiver", 0x1006, "Portable Media Center", 0x4002, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, { "iRiver", 0x1006, "Portable Media Center", 0x4003, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, // From [st]anislav { "iRiver", 0x1042, "T7 Volcano", 0x1143, DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, // From an anonymous person at SourceForge, uncertain about this one { "iRiver", 0x4102, "iFP-880", 0x1008, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, // 0x4102, 0x1042 is a USB mass storage mode for E100 v2/Lplayer // From libgphoto2 source { "iRiver", 0x4102, "T10", 0x1113, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, { "iRiver", 0x4102, "T20 FM", 0x1114, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, // This appears at the MTP-UMS site { "iRiver", 0x4102, "T20", 0x1115, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, { "iRiver", 0x4102, "U10", 0x1116, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, { "iRiver", 0x4102, "T10a", 0x1117, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, { "iRiver", 0x4102, "T20", 0x1118, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, { "iRiver", 0x4102, "T30", 0x1119, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, // Reported by David Wolpoff { "iRiver", 0x4102, "T10 2GB", 0x1120, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, // Rough guess this is the MTP device ID... { "iRiver", 0x4102, "N12", 0x1122, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, // Reported by Philip Antoniades // Newer iriver devices seem to have shaped-up firmware without any // of the annoying bugs. { "iRiver", 0x4102, "Clix2", 0x1126, DEVICE_FLAG_NONE }, // Reported by Adam Torgerson { "iRiver", 0x4102, "Clix", 0x112a, DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, // Reported by Douglas Roth { "iRiver", 0x4102, "X20", 0x1132, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, // Reported by Robert Ugo { "iRiver", 0x4102, "T60", 0x1134, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_IRIVER_OGG_ALZHEIMER }, // Reported by two anonymous SourceForge users // Needs the stronger OGG_IS_UNKNOWN flag to support OGG properly, // be aware of newer players that may be needing this too. { "iRiver", 0x4102, "E100", 0x1141, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_OGG_IS_UNKNOWN }, // Reported by anonymous SourceForge user // Need verification of whether this firmware really need all these flags { "iRiver", 0x4102, "E100 v2/Lplayer", 0x1142, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_OGG_IS_UNKNOWN }, // Reported by Richard Vennemann // In USB Mass Storage mode it is 0x4102/0x1047 // Seems to use the new shaped-up firmware. { "iRiver", 0x4102, "Spinn", 0x1147, DEVICE_FLAG_NONE }, // Reported by Tony Janssen { "iRiver", 0x4102, "E50", 0x1151, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_OGG_IS_UNKNOWN }, // Reported by anonymous SourceForge user, guessing on flags { "iRiver", 0x4102, "E150", 0x1152, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_OGG_IS_UNKNOWN }, // Reported by Jakub Matraszek { "iRiver", 0x4102, "T5", 0x1153, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_OGG_IS_UNKNOWN }, // Reported by pyalex@users.sourceforge.net // Guessing that this needs the FLAG_NO_ZERO_READS... { "iRiver", 0x4102, "E30", 0x1167, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_OGG_IS_UNKNOWN }, // Reported by Scott Call // Assume this actually supports OGG though it reports it doesn't. { "iRiver", 0x4102, "H10 20GB", 0x2101, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_OGG_IS_UNKNOWN }, { "iRiver", 0x4102, "H10 5GB", 0x2102, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_OGG_IS_UNKNOWN }, // From Rockbox device listing { "iRiver", 0x4102, "H10 5.6GB", 0x2105, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_NO_ZERO_READS | DEVICE_FLAG_OGG_IS_UNKNOWN }, /* * Dell */ { "Dell, Inc", 0x413c, "DJ Itty", 0x4500, DEVICE_FLAG_NONE }, /* Reported by: JR */ { "Dell, Inc", 0x413c, "Dell Streak 7", 0xb10b, DEVICE_FLAGS_ANDROID_BUGS }, /* * Toshiba * Tentatively flagged all Toshiba devices with * DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST after one of them * showed erroneous behaviour. */ { "Toshiba", 0x0930, "Gigabeat MEGF-40", 0x0009, DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST }, { "Toshiba", 0x0930, "Gigabeat", 0x000c, DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST }, // Reported by Nicholas Tripp { "Toshiba", 0x0930, "Gigabeat P20", 0x000f, DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST }, // From libgphoto2 { "Toshiba", 0x0930, "Gigabeat S", 0x0010, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST }, // Reported by Rob Brown { "Toshiba", 0x0930, "Gigabeat P10", 0x0011, DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST }, // Reported by solanum@users.sourceforge.net { "Toshiba", 0x0930, "Gigabeat V30", 0x0014, DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST }, // Reported by Michael Davis { "Toshiba", 0x0930, "Gigabeat U", 0x0016, DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST }, // Reported by Devon Jacobs { "Toshiba", 0x0930, "Gigabeat MEU202", 0x0018, DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST }, // Reported by Rolf { "Toshiba", 0x0930, "Gigabeat T", 0x0019, DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST }, // Reported by Phil Ingram // Tentatively added - no real reports of this device ID being MTP, // reports as USB Mass Storage currently. { "Toshiba", 0x0930, "Gigabeat MEU201", 0x001a, DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST }, // Reported by anonymous SourceForge user { "Toshiba", 0x0930, "Gigabeat MET401", 0x001d, DEVICE_FLAG_NO_RELEASE_INTERFACE | DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST }, // Reported by Andree Jacobson { "Toshiba", 0x0930, "Excite AT300", 0x0963, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by Nigel Cunningham // Guessing on Android bugs { "Toshiba", 0x0930, "Thrive AT100/AT105", 0x7100, DEVICE_FLAGS_ANDROID_BUGS }, /* * Archos * These devices have some dual-mode interfaces which will really * respect the driver unloading, so DEVICE_FLAG_UNLOAD_DRIVER * really work on these devices! */ // Reported by Alexander Haertig { "Archos", 0x0e79, "Gmini XS100", 0x1207, DEVICE_FLAG_UNLOAD_DRIVER }, // Added by Jan Binder { "Archos", 0x0e79, "XS202 (MTP mode)", 0x1208, DEVICE_FLAG_NONE }, // Reported by gudul1@users.sourceforge.net { "Archos", 0x0e79, "104 (MTP mode)", 0x120a, DEVICE_FLAG_NONE }, // Reported by Archos { "Archos", 0x0e79, "204 (MTP mode)", 0x120c, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by anonymous Sourceforge user. { "Archos", 0x0e79, "404 (MTP mode)", 0x1301, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Archos { "Archos", 0x0e79, "404CAM (MTP mode)", 0x1303, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Etienne Chauchot { "Archos", 0x0e79, "504 (MTP mode)", 0x1307, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Archos { "Archos", 0x0e79, "604 (MTP mode)", 0x1309, DEVICE_FLAG_UNLOAD_DRIVER }, { "Archos", 0x0e79, "604WIFI (MTP mode)", 0x130b, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Kay McCormick { "Archos", 0x0e79, "704 mobile dvr", 0x130d, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Archos { "Archos", 0x0e79, "704TV (MTP mode)", 0x130f, DEVICE_FLAG_UNLOAD_DRIVER }, { "Archos", 0x0e79, "405 (MTP mode)", 0x1311, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Joe Rabinoff { "Archos", 0x0e79, "605 (MTP mode)", 0x1313, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Archos { "Archos", 0x0e79, "605F (MTP mode)", 0x1315, DEVICE_FLAG_UNLOAD_DRIVER }, { "Archos", 0x0e79, "705 (MTP mode)", 0x1319, DEVICE_FLAG_UNLOAD_DRIVER }, { "Archos", 0x0e79, "TV+ (MTP mode)", 0x131b, DEVICE_FLAG_UNLOAD_DRIVER }, { "Archos", 0x0e79, "105 (MTP mode)", 0x131d, DEVICE_FLAG_UNLOAD_DRIVER }, { "Archos", 0x0e79, "405HDD (MTP mode)", 0x1321, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Jim Krehl { "Archos", 0x0e79, "5 (MTP mode)", 0x1331, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Adrien Guichard { "Archos", 0x0e79, "5 (MTP mode)", 0x1333, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Archos { "Archos", 0x0e79, "7 (MTP mode)", 0x1335, DEVICE_FLAG_UNLOAD_DRIVER }, { "Archos", 0x0e79, "SPOD (MTP mode)", 0x1341, DEVICE_FLAG_UNLOAD_DRIVER }, { "Archos", 0x0e79, "5S IT (MTP mode)", 0x1351, DEVICE_FLAG_UNLOAD_DRIVER }, { "Archos", 0x0e79, "5H IT (MTP mode)", 0x1357, DEVICE_FLAG_UNLOAD_DRIVER }, { "Archos", 0x0e79, "Arnova Childpad", 0x1458, DEVICE_FLAGS_ANDROID_BUGS }, { "Archos", 0x0e79, "Arnova 8c G3", 0x145e, DEVICE_FLAGS_ANDROID_BUGS }, { "Archos", 0x0e79, "Arnova 10bG3 Tablet", 0x146b, DEVICE_FLAGS_ANDROID_BUGS }, { "Archos", 0x0e79, "97 Xenon", 0x149a, DEVICE_FLAGS_ANDROID_BUGS }, { "Archos", 0x0e79, "8o G9 (MTP mode)", 0x1508, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Clément { "Archos", 0x0e79, "8o G9 Turbo (MTP mode)", 0x1509, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Thackert { "Archos", 0x0e79, "80G9", 0x1518, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by Till { "Archos", 0x0e79, "101 G9", 0x1528, DEVICE_FLAGS_ANDROID_BUGS }, { "Archos", 0x0e79, "101 G9 (v2)", 0x1529, DEVICE_FLAGS_ANDROID_BUGS }, { "Archos", 0x0e79, "101 G9 Turbo 250 HD", 0x1538, DEVICE_FLAGS_ANDROID_BUGS }, { "Archos", 0x0e79, "101 G9 Turbo", 0x1539, DEVICE_FLAGS_ANDROID_BUGS }, { "Archos", 0x0e79, "70it2 (mode 1)", 0x1568, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by Sebastien ROHAUT { "Archos", 0x0e79, "70it2 (mode 2)", 0x1569, DEVICE_FLAGS_ANDROID_BUGS }, /* * Dunlop (OEM of EGOMAN ltd?) reported by Nanomad * This unit is falsely detected as USB mass storage in Linux * prior to kernel 2.6.19 (fixed by patch from Alan Stern) * so on older kernels special care is needed to remove the * USB mass storage driver that erroneously binds to the device * interface. * * More problematic, this manufacturer+device ID seems to be * reused in a USB Mass Storage device named "Zipy Fox 8GB", * which means libmtp may mistreat it. */ { "Dunlop", 0x10d6, "MP3 player 1GB / EGOMAN MD223AFD", 0x2200, DEVICE_FLAG_UNLOAD_DRIVER}, // Reported by Steven Black // Obviously this company goes by many names. // This device is USB 2.0 only. Broken pipe on closing. // A later report indicates that this is also used by the iRiver E200 { "Memorex or iRiver", 0x10d6, "MMP 8585/8586 or iRiver E200", 0x2300, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_NO_RELEASE_INTERFACE}, /* * Sirius */ { "Sirius", 0x18f6, "Stiletto", 0x0102, DEVICE_FLAG_NONE }, // Reported by Chris Bagwell { "Sirius", 0x18f6, "Stiletto 2", 0x0110, DEVICE_FLAG_NONE }, /* * Canon * These are actually cameras, but they have a Microsoft device descriptor * and reports themselves as supporting the MTP extension. */ { "Canon", 0x04a9, "Ixus Digital 700 (PTP/MTP mode)", 0x30f2, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL }, { "Canon", 0x04a9, "PowerShot A640 (PTP/MTP mode)", 0x3139, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL }, // From Peter { "Canon", 0x04a9, "PowerShot SX20IS (PTP/MTP mode)", 0x31e4, DEVICE_FLAG_NONE }, /* * Nokia * Please verify the low device IDs here, I suspect these might be for * things like USB storage or modem mode actually, whereas the higher * range (0x04nn) could be for MTP. Some of the devices were gathered * from the Nokia WMP drivers: * http://nds2.nokia.com/files/support/global/phones/software/ * Address was gathered from going to: * nseries.com * -> support * -> select supported device * -> PC software * -> Music software * -> Windows Media Player 10 driver */ // From: DoomHammer { "Nokia", 0x0421, "N81 Mobile Phone", 0x000a, DEVICE_FLAG_NONE }, // From an anonymous SourceForge user { "Nokia", 0x0421, "6120c Classic Mobile Phone", 0x002e, DEVICE_FLAG_NONE }, // From Stefano { "Nokia", 0x0421, "N96 Mobile Phone", 0x0039, DEVICE_FLAG_NONE }, // From Martijn van de Streek { "Nokia", 0x0421, "6500c Classic Mobile Phone", 0x003c, DEVICE_FLAG_NONE }, // From: DoomHammer { "Nokia", 0x0421, "3110c Mobile Phone", 0x005f, DEVICE_FLAG_NONE }, // From: Vasily { "Nokia", 0x0421, "3109c Mobile Phone", 0x0065, DEVICE_FLAG_NONE }, // From: { "Nokia", 0x0421, "5310 XpressMusic", 0x006c, DEVICE_FLAG_NONE }, // From: robin (AT) headbank D0Tco DOTuk { "Nokia", 0x0421, "N95 Mobile Phone 8GB", 0x006e, DEVICE_FLAG_NONE }, // From Bastien Nocera { "Nokia", 0x0421, "N82 Mobile Phone", 0x0074, DEVICE_FLAG_UNLOAD_DRIVER }, // From Martijn van de Streek { "Nokia", 0x0421, "N78 Mobile Phone", 0x0079, DEVICE_FLAG_NONE }, // From William Pettersson { "Nokia", 0x0421, "6220 Classic", 0x008d, DEVICE_FLAG_NONE }, // From kellerkev@gmail.com { "Nokia", 0x0421, "N85 Mobile Phone", 0x0092, DEVICE_FLAG_NONE }, // From Alexandre LISSY { "Nokia", 0x0421, "6210 Navigator", 0x0098, DEVICE_FLAG_NONE }, // From: danielw { "Nokia", 0x0421, "E71", 0x00e4, DEVICE_FLAG_NONE }, // From: Laurent Bigonville { "Nokia", 0x0421, "E66", 0x00e5, DEVICE_FLAG_NONE }, // From: Pier { "Nokia", 0x0421, "5320 XpressMusic", 0x00ea, DEVICE_FLAG_NONE }, // From: Gausie { "Nokia", 0x0421, "5800 XpressMusic", 0x0154, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL }, // From: Willy Gardiol (web) // Spurious errors for getting all objects, lead me to believe // this flag atleast is needed { "Nokia", 0x0421, "5800 XpressMusic v2", 0x0155, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL }, // Yet another version... I think { "Nokia", 0x0421, "5800 XpressMusic v3", 0x0159, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL }, // From an anonymous SourceForge user // Not verified to be MTP { "Nokia", 0x0421, "E63", 0x0179, DEVICE_FLAG_NONE }, // Reported by: max g // Reported by: oswillios { "Nokia", 0x0421, "N79", 0x0186, DEVICE_FLAG_NONE }, // From an anonymous SourceForge user { "Nokia", 0x0421, "E71x", 0x01a1, DEVICE_FLAG_NONE }, // From Ser { "Nokia", 0x0421, "E52", 0x01cf, DEVICE_FLAG_NONE }, // From Marcus Meissner { "Nokia", 0x0421, "3710", 0x01ee, DEVICE_FLAG_NONE }, // From: AxeL { "Nokia", 0x0421, "N97-1", 0x01f4, DEVICE_FLAG_NONE }, // From: FunkyPenguin { "Nokia", 0x0421, "N97", 0x01f5, DEVICE_FLAG_NONE }, // From: Anonymous SourceForge user { "Nokia", 0x0421, "5130 XpressMusic", 0x0209, DEVICE_FLAG_NONE }, // From: Anonymous SourceForge user { "Nokia", 0x0421, "E72", 0x0221, DEVICE_FLAG_NONE }, // From: Anonymous SourceForge user { "Nokia", 0x0421, "5530", 0x0229, DEVICE_FLAG_NONE }, /* Grzegorz Woźniak */ { "Nokia", 0x0421, "E6", 0x032f, DEVICE_FLAG_NONE }, // From: Anonymous SourceForge user { "Nokia", 0x0421, "N97 mini", 0x026b, DEVICE_FLAG_NONE }, // From: Anonymous SourceForge user { "Nokia", 0x0421, "X6", 0x0274, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL }, // From: Alexander Kojevnikov { "Nokia", 0x0421, "6600i", 0x0297, DEVICE_FLAG_NONE }, // From: Karthik Paithankar { "Nokia", 0x0421, "2710", 0x02c1, DEVICE_FLAG_NONE }, // From: Mick Stephenson { "Nokia", 0x0421, "5230", 0x02e2, DEVICE_FLAG_NONE }, // From: Lan Liu at Nokia { "Nokia", 0x0421, "N8", 0x02fe, DEVICE_FLAG_NONE }, // From: Lan Liu at Nokia { "Nokia", 0x0421, "N8 (Ovi mode)", 0x0302, DEVICE_FLAG_NONE }, // From: Martijn Hoogendoorn { "Nokia", 0x0421, "E7", 0x0334, DEVICE_FLAG_NONE }, // From: Raul Metsma { "Nokia", 0x0421, "E7 (Ovi mode)", 0x0335, DEVICE_FLAG_NONE }, // Reported by Serg // Symbian phone { "Nokia", 0x0421, "C7", 0x03c1, DEVICE_FLAG_NONE }, // Reported by Anonymous SourceForge user { "Nokia", 0x0421, "C7 (ID2)", 0x03cd, DEVICE_FLAG_NONE }, // Reported by Anonymous SourceForge user { "Nokia", 0x0421, "N950", 0x03d2, DEVICE_FLAG_NONE }, // From: http://nds2.nokia.com/files/support/global/phones/software/Nokia_3250_WMP10_driver.inf { "Nokia", 0x0421, "3250 Mobile Phone", 0x0462, DEVICE_FLAG_NONE }, // From http://nds2.nokia.com/files/support/global/phones/software/Nokia_N93_WMP10_Driver.inf { "Nokia", 0x0421, "N93 Mobile Phone", 0x0478, DEVICE_FLAG_NONE }, // From: http://nds2.nokia.com/files/support/global/phones/software/Nokia_5500_Sport_WMP10_driver.inf { "Nokia", 0x0421, "5500 Sport Mobile Phone", 0x047e, DEVICE_FLAG_NONE }, // From http://nds2.nokia.com/files/support/global/phones/software/Nokia_N91_WMP10_Driver.inf { "Nokia", 0x0421, "N91 Mobile Phone", 0x0485, DEVICE_FLAG_NONE }, // From: Christian Rusa { "Nokia", 0x0421, "5700 XpressMusic Mobile Phone", 0x04b4, DEVICE_FLAG_NONE }, // From: Mitchell Hicks { "Nokia", 0x0421, "5300 Mobile Phone", 0x04ba, DEVICE_FLAG_NONE }, // https://sourceforge.net/tracker/index.php?func=detail&aid=2692473&group_id=8874&atid=358874 // From: Tiburce { "Nokia", 0x0421, "5200 Mobile Phone", 0x04be, DEVICE_FLAG_BROKEN_BATTERY_LEVEL }, // From Christian Arnold { "Nokia", 0x0421, "N73 Mobile Phone", 0x04d1, DEVICE_FLAG_UNLOAD_DRIVER }, // From Swapan { "Nokia", 0x0421, "N75 Mobile Phone", 0x04e1, DEVICE_FLAG_NONE }, // From: http://nds2.nokia.com/files/support/global/phones/software/Nokia_N93i_WMP10_driver.inf { "Nokia", 0x0421, "N93i Mobile Phone", 0x04e5, DEVICE_FLAG_NONE }, // From Anonymous Sourceforge User { "Nokia", 0x0421, "N95 Mobile Phone", 0x04ef, DEVICE_FLAG_NONE }, // From: Pat Nicholls { "Nokia", 0x0421, "N80 Internet Edition (Media Player)", 0x04f1, DEVICE_FLAG_UNLOAD_DRIVER }, // From: Maxin B. John { "Nokia", 0x0421, "N9", 0x051a, DEVICE_FLAG_NONE }, { "Nokia", 0x0421, "C5-00", 0x0592, DEVICE_FLAG_NONE }, { "Nokia", 0x0421, "808 PureView", 0x05d3, DEVICE_FLAG_NONE }, // Reported by Sampo Savola // Covers Lumia 920, 820 and probably any WP8 device. { "Nokia", 0x0421, "Nokia Lumia WP8", 0x0661, DEVICE_FLAG_NONE }, // Reported by Richard Wall { "Nokia", 0x05c6, "5530 Xpressmusic", 0x0229, DEVICE_FLAG_NONE }, // Reported by anonymous SourceForge user // One thing stated by reporter (Nokia model) another by the detect log... { "Nokia/Verizon", 0x05c6, "6205 Balboa/Verizon Music Phone", 0x3196, DEVICE_FLAG_NONE }, /* * Vendor ID 0x13d1 is some offshoring company in China, * in one source named "A-Max Technology Macao Commercial * Offshore Co. Ltd." sometime "CCTech". */ // Logik brand { "Logik", 0x13d1, "LOG DAX MP3 and DAB Player", 0x7002, DEVICE_FLAG_UNLOAD_DRIVER }, // Technika brand // Reported by { "Technika", 0x13d1, "MP-709", 0x7017, DEVICE_FLAG_UNLOAD_DRIVER }, /* * RCA / Thomson */ // From kiki { "Thomson", 0x069b, "EM28 Series", 0x0774, DEVICE_FLAG_NONE }, { "Thomson / RCA", 0x069b, "Opal / Lyra MC4002", 0x0777, DEVICE_FLAG_NONE }, { "Thomson", 0x069b, "Lyra MC5104B (M51 Series)", 0x077c, DEVICE_FLAG_NONE }, { "Thomson", 0x069b, "RCA H106", 0x301a, DEVICE_FLAG_UNLOAD_DRIVER }, // From Svenna // Not confirmed to be MTP. { "Thomson", 0x069b, "scenium E308", 0x3028, DEVICE_FLAG_NONE }, // From XNJB user { "Thomson / RCA", 0x069b, "Lyra HC308A", 0x3035, DEVICE_FLAG_NONE }, /* * Fujitsu devices */ { "Fujitsu, Ltd", 0x04c5, "F903iX HIGH-SPEED", 0x1140, DEVICE_FLAG_NONE }, // Reported by Thomas Bretthauer { "Fujitsu, Ltd", 0x04c5, "STYLISTIC M532", 0x133b, DEVICE_FLAGS_ANDROID_BUGS }, /* * Palm device userland program named Pocket Tunes * Reported by Peter Gyongyosi */ { "NormSoft, Inc.", 0x1703, "Pocket Tunes", 0x0001, DEVICE_FLAG_NONE }, // Reported by anonymous submission { "NormSoft, Inc.", 0x1703, "Pocket Tunes 4", 0x0002, DEVICE_FLAG_NONE }, /* * TrekStor, Medion and Maxfield devices * Their datasheet claims their devices are dualmode so probably needs to * unload the attached drivers here. */ // Reported by Stefan Voss // This is a Sigmatel SoC with a hard disk. { "TrekStor", 0x066f, "Vibez 8/12GB", 0x842a, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by anonymous SourceForge user. // This one done for Medion, whatever that is. Error reported so assume // the same bug flag as its ancestor above. { "Medion", 0x066f, "MD8333", 0x8550, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by anonymous SourceForge user { "Medion", 0x066f, "MD8333", 0x8588, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // The vendor ID is "Quanta Computer, Inc." // same as Olivetti Olipad 110 // Guessing on device flags { "Medion", 0x0408, "MD99000 (P9514)/Olivetti Olipad 110", 0xb009, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by Richard Eigenmann { "Medion", 0x0408, "Lifetab P9514", 0xb00a, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAGS_ANDROID_BUGS }, // Reported by anonymous SourceForge user { "Maxfield", 0x066f, "G-Flash NG 1GB", 0x846c, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by PaoloC // Apparently SigmaTel has an SDK for MTP players with this ID { "SigmaTel Inc.", 0x066f, "MTPMSCN Audio Player", 0xa010, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by Cristi Magherusan { "TrekStor", 0x0402, "i.Beat Sweez FM", 0x0611, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Fox-ino // No confirmation that this is really MTP so commented it out. // { "ALi Corp.", 0x0402, "MPMAN 2GB", 0x5668, // DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Anonymous SourceForge user {"TrekStor", 0x1e68, "i.Beat Organix 2.0", 0x0002, DEVICE_FLAG_UNLOAD_DRIVER }, /* * Disney/Tevion/MyMusix */ // Reported by XNJB user { "Disney", 0x0aa6, "MixMax", 0x6021, DEVICE_FLAG_NONE }, // Reported by anonymous Sourceforge user { "Tevion", 0x0aa6, "MD 81488", 0x3011, DEVICE_FLAG_NONE }, // Reported by Peter Hedlund { "MyMusix", 0x0aa6, "PD-6070", 0x9601, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST | DEVICE_FLAG_NO_RELEASE_INTERFACE }, /* * Cowon Systems, Inc. * The iAudio audiophile devices don't encourage the use of MTP. * See: http://wiki.xiph.org/index.php/PortablePlayers for Ogg * status */ // Reported by Patrik Johansson { "Cowon", 0x0e21, "iAudio U3 (MTP mode)", 0x0701, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, // Reported by Kevin Michael Smith { "Cowon", 0x0e21, "iAudio 6 (MTP mode)", 0x0711, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by Roberth Karman { "Cowon", 0x0e21, "iAudio 7 (MTP mode)", 0x0751, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, // Reported by an anonymous SourceForge user { "Cowon", 0x0e21, "iAudio U5 (MTP mode)", 0x0761, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, // Reported by TJ Something { "Cowon", 0x0e21, "iAudio D2 (MTP mode)", 0x0801, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, // Reported by anonymous Sourceforge user { "Cowon", 0x0e21, "iAudio D2+ FW 2.x (MTP mode)", 0x0861, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, // From Rockbox device listing { "Cowon", 0x0e21, "iAudio D2+ DAB FW 4.x (MTP mode)", 0x0871, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, // From Rockbox device listing { "Cowon", 0x0e21, "iAudio D2+ FW 3.x (MTP mode)", 0x0881, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, // From Rockbox device listing { "Cowon", 0x0e21, "iAudio D2+ DMB FW 1.x (MTP mode)", 0x0891, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, // Reported by { "Cowon", 0x0e21, "iAudio S9 (MTP mode)", 0x0901, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, // Reported by Dan Nicholson { "Cowon", 0x0e21, "iAudio 9 (MTP mode)", 0x0911, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, // Reported by Franck VDL { "Cowon", 0x0e21, "iAudio J3 (MTP mode)", 0x0921, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, // Reported by anonymous SourceForge user { "Cowon", 0x0e21, "iAudio X7 (MTP mode)", 0x0931, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, // Reported by anonymous SourceForge user { "Cowon", 0x0e21, "iAudio C2 (MTP mode)", 0x0941, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, { "Cowon", 0x0e21, "iAudio 10 (MTP mode)", 0x0952, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_OGG_IS_UNKNOWN | DEVICE_FLAG_FLAC_IS_UNKNOWN }, /* * Insignia, dual-mode. */ { "Insignia", 0x19ff, "NS-DV45", 0x0303, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Rajan Bella { "Insignia", 0x19ff, "Sport Player", 0x0307, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by "brad" (anonymous, sourceforge) { "Insignia", 0x19ff, "Pilot 4GB", 0x0309, DEVICE_FLAG_UNLOAD_DRIVER }, /* * LG Electronics */ // Uncertain if this is really the MTP mode device ID... { "LG Electronics Inc.", 0x043e, "T54", 0x7040, DEVICE_FLAG_UNLOAD_DRIVER }, // Not verified - anonymous submission { "LG Electronics Inc.", 0x043e, "UP3", 0x70b1, DEVICE_FLAG_NONE }, // Reported by Joseph Nahmias { "LG Electronics Inc.", 0x1004, "VX8550 V CAST Mobile Phone", 0x6010, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_ALWAYS_PROBE_DESCRIPTOR }, // Reported by Cyrille Potereau { "LG Electronics Inc.", 0x1004, "KC910 Renoir Mobile Phone", 0x608f, DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Aaron Slunt { "LG Electronics Inc.", 0x1004, "GR-500 Music Player", 0x611b, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_ALWAYS_PROBE_DESCRIPTOR }, { "LG Electronics Inc.", 0x1004, "KM900", 0x6132, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_UNLOAD_DRIVER }, { "LG Electronics Inc.", 0x1004, "LG8575", 0x619a, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_UNLOAD_DRIVER }, { "LG Electronics Inc.", 0x1004, "V909 G-Slate", 0x61f9, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_UNLOAD_DRIVER }, { "LG Electronics Inc.", 0x1004, "LG2 Optimus", 0x6225, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_UNLOAD_DRIVER }, // Reported by Brian J. Murrell { "LG Electronics Inc.", 0x1004, "LG-E610/E612/E617G/E970/P700", 0x631c, DEVICE_FLAGS_ANDROID_BUGS }, /* * Sony * It could be that these PIDs are one-per hundred series, so * NWZ-A8xx is 0325, NWZ-S5xx is 0x326 etc. We need more devices * reported to see a pattern here. */ // Reported by Alessandro Radaelli { "Sony", 0x054c, "NWZ-A815/NWZ-A818", 0x0325, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by anonymous Sourceforge user. { "Sony", 0x054c, "NWZ-S516", 0x0326, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Endre Oma { "Sony", 0x054c, "NWZ-S615F/NWZ-S616F/NWZ-S618F", 0x0327, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Jean-Marc Bourguet { "Sony", 0x054c, "NWZ-S716F", 0x035a, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Anon SF User / Anthon van der Neut { "Sony", 0x054c, "NWZ-A826/NWZ-A828/NWZ-A829", 0x035b, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Niek Klaverstijn { "Sony", 0x054c, "NWZ-A726/NWZ-A728/NWZ-A768", 0x035c, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Mehdi AMINI { "Sony", 0x054c, "NWZ-B135", 0x036e, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by { "Sony", 0x054c, "NWZ-E436F", 0x0385, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Michael Wilkinson { "Sony", 0x054c, "NWZ-W202", 0x0388, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Ondrej Sury { "Sony", 0x054c, "NWZ-S739F", 0x038c, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Marco Filipe Nunes Soares Abrantes Pereira { "Sony", 0x054c, "NWZ-S638F", 0x038e, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Elliot { "Sony", 0x054c, "NWZ-X1050B/NWZ-X1060B", 0x0397, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Silvio J. Gutierrez { "Sony", 0x054c, "NWZ-X1051/NWZ-X1061", 0x0398, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Gregory Boddin { "Sony", 0x054c, "NWZ-B142F", 0x03d8, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Rick Warner { "Sony", 0x054c, "NWZ-E344/E345", 0x03fc, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Jonathan Stowe { "Sony", 0x054c, "NWZ-E445", 0x03fd, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Anonymous SourceForge user { "Sony", 0x054c, "NWZ-S545", 0x03fe, DEVICE_FLAGS_SONY_NWZ_BUGS }, { "Sony", 0x054c, "NWZ-A845", 0x0404, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by anonymous SourceForge user { "Sony", 0x054c, "NWZ-W252B", 0x04bb, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Suspect this device has strong DRM features // See https://answers.launchpad.net/ubuntu/+source/libmtp/+question/149587 { "Sony", 0x054c, "NWZ-B153F", 0x04be, DEVICE_FLAGS_SONY_NWZ_BUGS }, { "Sony", 0x054c, "NWZ-E354", 0x04cb, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Toni Burgarello { "Sony", 0x054c, "NWZ-S754", 0x04cc, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Hideki Yamane { "Sony", 0x054c, "Sony Tablet P1", 0x04d1, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by dmiceman { "Sony", 0x054c, "NWZ-B163F", 0x059a, DEVICE_FLAGS_SONY_NWZ_BUGS }, { "Sony", 0x054c, "NWZ-E464", 0x05a6, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Reported by Jan Rheinlaender { "Sony", 0x054c, "NWZ-S765", 0x05a8, DEVICE_FLAGS_SONY_NWZ_BUGS }, // Olivier Keshavjee { "Sony", 0x054c, "Sony Tablet S", 0x05b3, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by ghalambaz { "Sony", 0x054c, "Sony Tablet S1", 0x05b4, DEVICE_FLAGS_ANDROID_BUGS }, { "Sony", 0x054c, "NWZ-B173F", 0x0689, DEVICE_FLAGS_SONY_NWZ_BUGS }, { "Sony", 0x054c, "DCR-SR75", 0x1294, DEVICE_FLAGS_SONY_NWZ_BUGS }, /* * SonyEricsson * These initially seemed to support GetObjPropList but later revisions * of the firmware seem to have broken it, so all are flagged as broken * for now. */ // Reported by Øyvind Stegard { "SonyEricsson", 0x0fce, "K850i", 0x0075, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by Michael Eriksson { "SonyEricsson", 0x0fce, "W910", 0x0076, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by Zack { "SonyEricsson", 0x0fce, "W890i", 0x00b3, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by robert dot ahlskog at gmail { "SonyEricsson", 0x0fce, "W760i", 0x00c6, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by Linus Ã…kesson { "SonyEricsson", 0x0fce, "C902", 0x00d4, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by an anonymous SourceForge user { "SonyEricsson", 0x0fce, "C702", 0x00d9, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by Christian Zuckschwerdt { "SonyEricsson", 0x0fce, "W980", 0x00da, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by David Taylor { "SonyEricsson", 0x0fce, "C905", 0x00ef, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by David House { "SonyEricsson", 0x0fce, "W595", 0x00f3, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL | DEVICE_FLAG_BROKEN_SET_OBJECT_PROPLIST }, // Reported by Mattias Evensson { "SonyEricsson", 0x0fce, "W902", 0x00f5, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by Sarunas // Doesn't need any flags according to reporter { "SonyEricsson", 0x0fce, "T700", 0x00fb, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL }, // Reported by Stéphane Pontier { "SonyEricsson", 0x0fce, "W705/W715", 0x0105, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by HÃ¥kan Kvist { "SonyEricsson", 0x0fce, "W995", 0x0112, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by anonymous SourceForge user { "SonyEricsson", 0x0fce, "U5", 0x0133, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by Flo { "SonyEricsson", 0x0fce, "U8i", 0x013a, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by xirotyu { "SonyEricsson", 0x0fce, "j10i2 (Elm)", 0x0144, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by Serge Chirik { "SonyEricsson", 0x0fce, "j108i (Cedar)", 0x014e, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by Jonas Nyrén { "SonyEricsson", 0x0fce, "W302", 0x10c8, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by Anonymous Sourceforge user { "SonyEricsson", 0x0fce, "j10i (Elm)", 0xd144, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by Thomas Schweitzer { "SonyEricsson", 0x0fce, "K550i", 0xe000, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, /* * SonyEricsson/SONY Android devices usually have three personalities due to * using composite descriptors and the fact that Windows cannot distinguish * the device unless each composite descriptor is unique. * * Legend: * MTP = Media Transfer Protocol * UMS = USB Mass Storage Protocol * ADB = Android Debug Bridge Protocol * CDC = Communications Device Class, Internet Sharing * * 0x0nnn = MTP * 0x4nnn = MTP + UMS (for CD-ROM) * 0x5nnn = MTP + ADB * 0x6nnn = UMS + ADB * 0x7nnn = MTP + CDC * 0x8nnn = MTP + CDC + ADB * 0xannn = MTP + UMS (MTP for eMMC and UMS for external SD card) * 0xbnnn = MTP + UMS + ADB * 0xennn = UMS only * * The SonyEricsson and SONY devices have (at least) two deployed MTP * stacks: Aricent and Android. These have different bug flags, and * sometimes the same device has firmware upgrades moving it from * the Aricent to Android MTP stack without changing the device * VID+PID (first observed on the SK17i Xperia Mini Pro), so the * detection has to be more elaborate. The code in libmtp.c will do * this and assign the proper bug flags (hopefully). * That is why DEVICE_FLAG_NONE is used for these devices. * * Devices reported by: * Sony Mobile Communications (via Toby Collett) * Jonas Salling * Eamonn Webster * Alejandro DC * StehpanKa * hdhoang * Paul Taylor * Bruno Basilio * Christoffer Holmstedt * equaeghe * Ondra Lengal * Michael K. * Jean-François B. * Eduard Bloch * Ah Hong * Eowyn Carter */ { "SonyEricsson", 0x0fce, "LT15i Xperia arc S MTP", 0x014f, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "MT11i Xperia Neo MTP", 0x0156, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "IS12S Xperia Acro MTP", 0x0157, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "MK16i Xperia MTP", 0x015a, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "R800/R88i Xperia Play MTP", 0x015d, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "ST18a Xperia Ray MTP", 0x0161, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "SK17i Xperia Mini Pro MTP", 0x0166, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "ST15i Xperia Mini MTP", 0x0167, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "ST17i Xperia Active MTP", 0x0168, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT26i Xperia S MTP", 0x0169, DEVICE_FLAG_NO_ZERO_READS }, { "SONY", 0x0fce, "WT19i Live Walkman MTP", 0x016d, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "ST21i Xperia Tipo MTP", 0x0170, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "ST15i Xperia U MTP", 0x0171, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT22i Xperia P MTP", 0x0172, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "MT27i Xperia Sola MTP", 0x0173, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT26w Xperia Acro HD IS12S MTP", 0x0175, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT26w Xperia Acro HD SO-03D MTP", 0x0176, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT28at Xperia Ion MTP", 0x0177, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT29i Xperia GX MTP", 0x0178, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "ST27i/ST27a Xperia go MTP", 0x017e, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "ST23i Xperia Miro MTP", 0x0180, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "SO-05D Xperia SX MTP", 0x0181, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT30p Xperia T MTP", 0x0182, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT25i Xperia V MTP", 0x0186, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia J MTP", 0x0188, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia ZL MTP", 0x0189, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia E MTP", 0x018c, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia Tablet Z MTP 1", 0x018d, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia Z MTP", 0x0193, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia Tablet Z MTP 2", 0x0194, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia SP MTP", 0x0195, DEVICE_FLAG_NONE }, /* * MTP+UMS personalities of MTP devices (see above) */ { "SonyEricsson", 0x0fce, "IS12S Xperia Acro MTP+CDROM", 0x4157, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "ST17i Xperia Active MTP+CDROM", 0x4168, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT26i Xperia S MTP+CDROM", 0x4169, DEVICE_FLAG_NO_ZERO_READS }, { "SONY", 0x0fce, "ST21i Xperia Tipo MTP+CDROM", 0x4170, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "ST25i Xperia U MTP+CDROM", 0x4171, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT22i Xperia P MTP+CDROM", 0x4172, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "MT27i Xperia Sola MTP+CDROM", 0x4173, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT26w Xperia Acro HD IS12S MTP+CDROM", 0x4175, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT26w Xperia Acro HD SO-03D MTP+CDROM", 0x4176, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT28at Xperia Ion MTP+CDROM", 0x4177, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT29i Xperia GX MTP+CDROM", 0x4178, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "ST27i/ST27a Xperia go MTP+CDROM", 0x417e, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "ST23i Xperia Miro MTP+CDROM", 0x4180, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "SO-05D Xperia SX MTP+CDROM", 0x4181, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT30p Xperia T MTP+CDROM", 0x4182, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT25i Xperia V MTP+CDROM", 0x4186, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia J MTP+CDROM", 0x4188, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia ZL MTP+CDROM", 0x4189, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia E MTP+CDROM", 0x418c, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia Tablet Z MTP+CDROM 1", 0x418d, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia Z MTP+CDROM", 0x4193, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia Tablet Z MTP+CDROM 2", 0x4194, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia SP MTP+CDROM", 0x4195, DEVICE_FLAG_NONE }, /* * MTP+ADB personalities of MTP devices (see above) */ { "SonyEricsson", 0x0fce, "LT15i Xperia Arc MTP+ADB", 0x514f, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "MT11i Xperia Neo MTP+ADB", 0x5156, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "IS12S Xperia Acro MTP+ADB", 0x5157, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "MK16i Xperia MTP+ADB", 0x515a, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "R800/R88i Xperia Play MTP+ADB", 0x515d, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "ST18i Xperia Ray MTP+ADB", 0x5161, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "SK17i Xperia Mini Pro MTP+ADB", 0x5166, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "ST15i Xperia Mini MTP+ADB", 0x5167, DEVICE_FLAG_NONE }, { "SonyEricsson", 0x0fce, "ST17i Xperia Active MTP+ADB", 0x5168, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT26i Xperia S MTP+ADB", 0x5169, DEVICE_FLAG_NO_ZERO_READS }, { "SonyEricsson", 0x0fce, "WT19i Live Walkman MTP+ADB", 0x516d, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "ST21i Xperia Tipo MTP+ADB", 0x5170, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "ST25i Xperia U MTP+ADB", 0x5171, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT22i Xperia P MTP+ADB", 0x5172, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "MT27i Xperia Sola MTP+ADB", 0x5173, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "IS12S Xperia Acro HD MTP+ADB", 0x5175, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "SO-03D Xperia Acro HD MTP+ADB", 0x5176, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT28at Xperia Ion MTP+ADB", 0x5177, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT29i Xperia GX MTP+ADB", 0x5178, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "ST27i/ST27a Xperia go MTP+ADB", 0x517e, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "ST23i Xperia Miro MTP+ADB", 0x5180, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "SO-05D Xperia SX MTP+ADB", 0x5181, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT30p Xperia T MTP+ADB", 0x5182, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT25i Xperia V MTP+ADB", 0x5186, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia J MTP+ADB", 0x5188, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia ZL MTP+ADB", 0x5189, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia E MTP+ADB", 0x518c, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia Tablet Z MTP+ADB 1", 0x518d, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia Z MTP+ADB", 0x5193, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia Tablet Z MTP+ADB 2", 0x5194, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "Xperia SP MTP+ADB", 0x5195, DEVICE_FLAG_NONE }, /* * MTP+UMS modes * This mode is for using MTP on the internal storage (eMMC) * and using UMS (Mass Storage Device Class) on the external * SD card */ { "SONY", 0x0fce, "MT27i Xperia Sola MTP+UMS", 0xa173, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "IS12S Xperia Acro HD MTP+UMS", 0xa175, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "SO-03D Xperia Acro HD MTP+UMS", 0xa176, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT28at Xperia Ion MTP+UMS", 0xa177, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "ST27i/ST27a Xperia go MTP+UMS", 0xa17e, DEVICE_FLAG_NONE }, /* * MTP+UMS+ADB modes * Like the above, but also ADB */ { "SONY", 0x0fce, "MT27i Xperia Sola MTP+UMS+ADB", 0xb173, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "IS12S Xperia Acro MTP+UMS+ADB", 0xb175, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "SO-03D Xperia Acro MTP+UMS+ADB", 0xb176, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "LT28at Xperia Ion MTP+UMS+ADB", 0xb177, DEVICE_FLAG_NONE }, { "SONY", 0x0fce, "ST27i/ST27a Xperia go MTP+UMS+ADB", 0xb17e, DEVICE_FLAG_NONE }, /* * Motorola * Assume DEVICE_FLAG_BROKEN_SET_OBJECT_PROPLIST on all of these. */ // Reported by David Boyd { "Motorola", 0x22b8, "V3m/V750 verizon", 0x2a65, DEVICE_FLAG_BROKEN_SET_OBJECT_PROPLIST | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL }, { "Motorola", 0x22b8, "Atrix/Razr HD (MTP)", 0x2e32, DEVICE_FLAGS_ANDROID_BUGS }, { "Motorola", 0x22b8, "Atrix/Razr HD (MTP+ADB)", 0x2e33, DEVICE_FLAGS_ANDROID_BUGS }, { "Motorola", 0x22b8, "RAZR M (XT907)", 0x2e51, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by Jader Rodrigues Simoes { "Motorola", 0x22b8, "Xoom 2 Media Edition (ID2)", 0x41cf, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by Steven Roemen { "Motorola", 0x22b8, "Droid X/MB525 (Defy)", 0x41d6, DEVICE_FLAG_NONE }, { "Motorola", 0x22b8, "DROID2 (ID1)", 0x41da, DEVICE_FLAG_NONE }, { "Motorola", 0x22b8, "Milestone / Verizon Droid", 0x41dc, DEVICE_FLAGS_ANDROID_BUGS }, { "Motorola", 0x22b8, "DROID2 (ID2)", 0x42a7, DEVICE_FLAGS_ANDROID_BUGS }, { "Motorola", 0x22b8, "Xoom 2 Media Edition", 0x4311, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by B,H,Kissinger { "Motorola", 0x22b8, "XT912/XT928", 0x4362, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by Lundgren { "Motorola", 0x22b8, "DROID4", 0x437f, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by Marcus Meissner to libptp2 { "Motorola", 0x22b8, "IdeaPad K1", 0x4811, DEVICE_FLAG_BROKEN_SET_OBJECT_PROPLIST }, // Reported by Hans-Joachim Baader to libptp2 { "Motorola", 0x22b8, "A1200", 0x60ca, DEVICE_FLAG_BROKEN_SET_OBJECT_PROPLIST }, // http://mark.cdmaforums.com/Files/Motdmmtp.inf { "Motorola", 0x22b8, "MTP Test Command Interface", 0x6413, DEVICE_FLAG_BROKEN_SET_OBJECT_PROPLIST }, // Reported by anonymous user { "Motorola", 0x22b8, "RAZR2 V8/U9/Z6", 0x6415, DEVICE_FLAG_BROKEN_SET_OBJECT_PROPLIST }, // Reported by Brian Dolbec { "Motorola", 0x22b8, "Atrix MB860 (MTP)", 0x7088, DEVICE_FLAGS_ANDROID_BUGS }, /* * Motorola Xoom (Wingray) variants * * These devices seem to use these product IDs simulatenously * https://code.google.com/p/android-source-browsing/source/browse/init.stingray.usb.rc?repo=device--moto--wingray * * 0x70a3 - Factory test - reported as early MTP ID * 0x70a8 - MTP * 0x70a9 - MTP+ADB * 0x70ae - RNDIS * 0x70af - RNDIS+ADB * 0x70b0 - ACM * 0x70b1 - ACM+ADB * 0x70b2 - ACM+RNDIS * 0x70b3 - ACM+RNDIS+ADB * 0x70b4 - PTP * 0x70b5 - PTP+ADB * * Reported by Google Inc's Yavor Goulishev */ { "Motorola", 0x22b8, "Xoom (Factory test)", 0x70a3, DEVICE_FLAGS_ANDROID_BUGS }, { "Motorola", 0x22b8, "Xoom (MTP)", 0x70a8, DEVICE_FLAGS_ANDROID_BUGS }, { "Motorola", 0x22b8, "Xoom (MTP+ADB)", 0x70a9, DEVICE_FLAGS_ANDROID_BUGS }, // "carried by C Spire and other CDMA US carriers" { "Motorola", 0x22b8, "Milestone X2", 0x70ca, DEVICE_FLAGS_ANDROID_BUGS }, { "Motorola", 0x22b8, "XT890/907 (MTP)", 0x710d, DEVICE_FLAGS_ANDROID_BUGS }, { "Motorola", 0x22b8, "XT890/907 (MTP+ADB)", 0x710e, DEVICE_FLAGS_ANDROID_BUGS }, { "Motorola", 0x22b8, "XT890/907 (MTP+?)", 0x710f, DEVICE_FLAGS_ANDROID_BUGS }, /* * Google * These guys lend their Vendor ID to anyone who comes down the * road to produce an Android tablet it seems... The Vendor ID * was originally used for Nexus phones */ { "Google Inc (for Ainol Novo)", 0x18d1, "Fire/Flame", 0x0007, DEVICE_FLAGS_ANDROID_BUGS }, { "Google Inc (for Sony)", 0x18d1, "S1", 0x05b3, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by anonymous Sourceforge user { "Google Inc (for Barnes & Noble)", 0x18d1, "Nook Color", 0x2d02, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by anonymous Sourceforge user { "Google Inc (for Asus)", 0x18d1, "TF201 Transformer", 0x4d00, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by anonymous Sourceforge user { "Google Inc (for Asus)", 0x18d1, "TF101 Transformer", 0x4e0f, DEVICE_FLAGS_ANDROID_BUGS }, // 0x4e21 (Nexus S) is a USB Mass Storage device. { "Google Inc (for Samsung)", 0x18d1, "Nexus S (MTP)", 0x4e25, DEVICE_FLAGS_ANDROID_BUGS }, { "Google Inc (for Samsung)", 0x18d1, "Nexus S (MTP+ADB)", 0x4e26, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by Chris Smith { "Google Inc (for Asus)", 0x18d1, "Nexus 7 (MTP)", 0x4e41, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by Michael Hess { "Google Inc (for Asus)", 0x18d1, "Nexus 7 (MTP+ADB)", 0x4e42, DEVICE_FLAGS_ANDROID_BUGS }, { "Google Inc (for LG Electronics/Samsung)", 0x18d1, "Nexus 4/10 (MTP)", 0x4ee1, DEVICE_FLAGS_ANDROID_BUGS }, { "Google Inc (for LG Electronics/Samsung)", 0x18d1, "Nexus 4/10 (MTP+ADB)", 0x4ee2, DEVICE_FLAGS_ANDROID_BUGS }, // WiFi-only version of Xoom // See: http://bugzilla.gnome.org/show_bug.cgi?id=647506 { "Google Inc (for Motorola)", 0x18d1, "Xoom (MZ604)", 0x70a8, DEVICE_FLAGS_ANDROID_BUGS }, { "Google Inc (for Toshiba)", 0x18d1, "Thrive 7/AT105", 0x7102, DEVICE_FLAGS_ANDROID_BUGS }, { "Google Inc (for Lenovo)", 0x18d1, "Ideapad K1", 0x740a, DEVICE_FLAGS_ANDROID_BUGS }, // Another OEM for Medion { "Google Inc (for Medion)", 0x18d1, "MD99000 (P9514)", 0xb00a, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by Frederik Himpe { "Google Inc (for LG Electronics)", 0x18d1, "P990/Optimus (Cyanogen)", 0xd109, DEVICE_FLAGS_ANDROID_BUGS }, { "Google Inc (for LG Electronics)", 0x18d1, "P990/Optimus", 0xd10a, DEVICE_FLAGS_ANDROID_BUGS }, /* * Media Keg */ // Reported by Rajan Bella { "Kenwood", 0x0b28, "Media Keg HD10GB7 Sport Player", 0x100c, DEVICE_FLAG_UNLOAD_DRIVER}, /* * Micro-Star International (MSI) */ // Reported by anonymous sourceforge user. { "Micro-Star International", 0x0db0, "P610/Model MS-5557", 0x5572, DEVICE_FLAG_NONE }, /* * FOMA */ { "FOMA", 0x06d3, "D905i", 0x21ba, DEVICE_FLAG_NONE }, /* * Haier */ // Both reported by an anonymous SourceForge user // This is the 30 GiB model { "Haier", 0x1302, "Ibiza Rhapsody", 0x1016, DEVICE_FLAG_NONE }, // This is the 4/8 GiB model { "Haier", 0x1302, "Ibiza Rhapsody", 0x1017, DEVICE_FLAG_NONE }, /* * Panasonic */ // Reported by dmizer { "Panasonic", 0x04da, "P905i", 0x2145, DEVICE_FLAG_NONE }, // Reported by Taku { "Panasonic", 0x04da, "P906i", 0x2158, DEVICE_FLAG_NONE }, /* * Polaroid */ { "Polaroid", 0x0546, "Freescape/MPU-433158", 0x2035, DEVICE_FLAG_NONE }, /* * Pioneer */ // Reported by Dan Allen { "Pioneer", 0x08e4, "XMP3", 0x0148, DEVICE_FLAG_NONE }, /* * Slacker Inc. * Put in all evilness flags because it looks fragile. */ // Reported by Pug Fantus { "Slacker Inc.", 0x1bdc, "Slacker Portable Media Player", 0xfabf, DEVICE_FLAG_BROKEN_BATTERY_LEVEL | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST | DEVICE_FLAG_BROKEN_SET_OBJECT_PROPLIST | DEVICE_FLAG_BROKEN_SEND_OBJECT_PROPLIST }, // Reported by anonymous user { "Conceptronic", 0x1e53, "CMTD2", 0x0005, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by Demadridsur { "O2 Sistemas", 0x1e53, "ZoltarTV", 0x0006, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by da-beat { "Wyplay", 0x1e53, "Wyplayer", 0x0007, DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST }, // Reported by Sense Hofstede { "Perception Digital, Ltd", 0x0aa6, "Gigaware GX400", 0x9702, DEVICE_FLAG_NONE }, /* * RIM's BlackBerry */ // Reported by Nicolas VIVIEN { "RIM", 0x0fca, "BlackBerry Storm/9650", 0x8007, DEVICE_FLAG_UNLOAD_DRIVER | DEVICE_FLAG_SWITCH_MODE_BLACKBERRY | DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL }, /* * Nextar */ { "Nextar", 0x0402, "MA715A-8R", 0x5668, DEVICE_FLAG_NONE }, /* * Coby */ { "Coby", 0x1e74, "COBY MP705", 0x6512, DEVICE_FLAG_NONE }, #if 0 /* * Apple devices, which are not MTP natively but can be made to speak MTP * using PwnTunes (http://www.pwntunes.net/) * CURRENTLY COMMENTED OUT: * These will make the UDEV rules flag these as MTP devices even if * PwnTunes is NOT installed. That is unacceptable, so a better solution * that actually inspects if the device has PwnTunes/MTP support needs * to be found, see: * https://sourceforge.net/p/libmtp/bugs/759/ */ { "Apple", 0x05ac, "iPhone", 0x1290, DEVICE_FLAG_NONE }, { "Apple", 0x05ac, "iPod Touch 1st Gen", 0x1291, DEVICE_FLAG_NONE }, { "Apple", 0x05ac, "iPhone 3G", 0x1292, DEVICE_FLAG_NONE }, { "Apple", 0x05ac, "iPod Touch 2nd Gen", 0x1293, DEVICE_FLAG_NONE }, { "Apple", 0x05ac, "iPhone 3GS", 0x1294, DEVICE_FLAG_NONE }, { "Apple", 0x05ac, "0x1296", 0x1296, DEVICE_FLAG_NONE }, { "Apple", 0x05ac, "0x1297", 0x1297, DEVICE_FLAG_NONE }, { "Apple", 0x05ac, "0x1298", 0x1298, DEVICE_FLAG_NONE }, { "Apple", 0x05ac, "iPod Touch 3rd Gen", 0x1299, DEVICE_FLAG_NONE }, { "Apple", 0x05ac, "iPad", 0x129a, DEVICE_FLAG_NONE }, #endif // Reported by anonymous SourceForge user, also reported as // Pantech Crux, claming to be: // Manufacturer: Qualcomm // Model: Windows Simulator // Device version: Qualcomm MTP1.0 { "Curitel Communications, Inc.", 0x106c, "Verizon Wireless Device", 0x3215, DEVICE_FLAG_NONE }, // Reported by: Jim Hanrahan { "Pantech", 0x106c, "Crux", 0xf003, DEVICE_FLAG_NONE }, /* * Asus * Pattern of PIDs on Android devices seem to be: * n+0 = MTP * n+1 = MTP+ADB * n+2 = ? * n+3 = ? * n+4 = PTP */ // Reported by Glen Overby { "Asus", 0x0b05, "TF300 Transformer (MTP)", 0x4c80, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by jaile { "Asus", 0x0b05, "TF300 Transformer (MTP+ADB)", 0x4c81, DEVICE_FLAGS_ANDROID_BUGS }, // Repored by Florian Apolloner { "Asus", 0x0b05, "TF700 Transformer (MTP)", 0x4c90, DEVICE_FLAGS_ANDROID_BUGS }, { "Asus", 0x0b05, "TF700 Transformer (MTP+ADB)", 0x4c91, DEVICE_FLAGS_ANDROID_BUGS }, { "Asus", 0x0b05, "MeMo Pad Smart 10", 0x4cd0, DEVICE_FLAGS_ANDROID_BUGS }, { "Asus", 0x0b05, "TF201 Transformer Prime (keyboard dock)", 0x4d00, DEVICE_FLAGS_ANDROID_BUGS }, { "Asus", 0x0b05, "TF201 Transformer Prime (tablet only)", 0x4d01, DEVICE_FLAGS_ANDROID_BUGS }, // 4d04 is the PTP mode, don't add it { "Asus", 0x0b05, "SL101 (MTP)", 0x4e00, DEVICE_FLAGS_ANDROID_BUGS }, { "Asus", 0x0b05, "SL101 (MTP+ADB)", 0x4e01, DEVICE_FLAGS_ANDROID_BUGS }, { "Asus", 0x0b05, "TF101 Eeepad Transformer (MTP)", 0x4e0f, DEVICE_FLAGS_ANDROID_BUGS }, { "Asus", 0x0b05, "TF101 Eeepad Transformer (MTP+ADB)", 0x4e1f, DEVICE_FLAGS_ANDROID_BUGS }, { "Asus", 0x0b05, "Fonepad", 0x514f, DEVICE_FLAGS_ANDROID_BUGS }, { "Asus", 0x0b05, "PadFone (MTP)", 0x5200, DEVICE_FLAGS_ANDROID_BUGS }, { "Asus", 0x0b05, "PadFone (MTP+ADB)", 0x5201, DEVICE_FLAGS_ANDROID_BUGS }, { "Asus", 0x0b05, "PadFone 2 (MTP+?)", 0x5210, DEVICE_FLAGS_ANDROID_BUGS }, { "Asus", 0x0b05, "PadFone 2 (MTP)", 0x5211, DEVICE_FLAGS_ANDROID_BUGS }, /* * Lenovo */ // Reported by Richard Körber { "Lenovo", 0x17ef, "K1", 0x740a, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by anonymous sourceforge user // Adding Android default bug flags since it appears to be an Android { "Lenovo", 0x17ef, "ThinkPad Tablet", 0x741c, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by: XChesser { "Lenovo", 0x17ef, "P700", 0x7497, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by: anonymous sourceforge user { "Lenovo", 0x17ef, "Lifetab S9512", 0x74cc, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by Brian J. Murrell { "Lenovo", 0x17ef, "IdeaTab A2109A", 0x7542, DEVICE_FLAGS_ANDROID_BUGS }, /* * Huawei */ // Reported by anonymous SourceForge user { "Huawei", 0x12d1, "Honor U8860", 0x1051, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by anonymous SourceForge user { "Huawei", 0x12d1, "U8815/U9200", 0x1052, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by anonymous SourceForge user { "Huawei", 0x12d1, "Mediapad (mode 0)", 0x360f, DEVICE_FLAGS_ANDROID_BUGS }, // Reported by Bearsh { "Huawei", 0x12d1, "Mediapad (mode 1)", 0x361f, DEVICE_FLAGS_ANDROID_BUGS }, /* * ZTE * Android devices reported by junwang */ { "ZTE", 0x19d2, "V55 ID 1", 0x0244, DEVICE_FLAGS_ANDROID_BUGS }, { "ZTE", 0x19d2, "V55 ID 2", 0x0245, DEVICE_FLAGS_ANDROID_BUGS }, { "ZTE", 0x19d2, "V790/Blade 3", 0x0306, DEVICE_FLAGS_ANDROID_BUGS }, { "ZTE", 0x19d2, "V880E", 0x0307, DEVICE_FLAGS_ANDROID_BUGS }, { "ZTE", 0x19d2, "V985", 0x0383, DEVICE_FLAGS_ANDROID_BUGS }, /* * HTC (High Tech Computer Corp) * Reporters: * Steven Eastland * Kevin Cheng */ #if 0 /* * This had to be commented out - the same VID+PID is used also for * other modes than MTP, so we need to let mtp-probe do its job on this * device instead of adding it to the database. */ { "HTC", 0x0bb4, "Android Device ID1 (Zopo, HD2, Bird...)", 0x0c02, DEVICE_FLAGS_ANDROID_BUGS }, #endif { "HTC", 0x0bb4, "EVO 4G LTE/One V (ID1)", 0x0c93, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "EVO 4G LTE/One V (ID2)", 0x0ca8, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "HTC One S (ID1)", 0x0cec, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "HTC Desire X", 0x0dd5, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "HTC One (ID1)", 0x0dda, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "HTC One (MTP+UMS+ADB)", 0x0dea, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "HTC Evo 4G LTE (ID1)", 0x0df5, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "HTC One S (ID2)", 0x0df9, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "HTC One X (ID1)", 0x0dfb, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "HTC One X (ID2)", 0x0dfc, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "HTC One X (ID3)", 0x0dfd, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "HTC Butterfly (ID1)", 0x0dfe, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "Droid DNA (MTP+UMS+ADB)", 0x0dff, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "HTC Droid Incredible 4G LTE (MTP)", 0x0e31, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "HTC Droid Incredible 4G LTE (MTP+ADB)", 0x0e32, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "Droid DNA (MTP+UMS)", 0x0ebd, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "HTC One (MTP+ADB)", 0x0f87, DEVICE_FLAGS_ANDROID_BUGS }, { "HTC", 0x0bb4, "HTC One (ID3)", 0x0f91, DEVICE_FLAGS_ANDROID_BUGS }, // These identify themselves as "cm_tenderloin", fun... // Done by HTC for HP I guess. { "Hewlett-Packard", 0x0bb4, "HP Touchpad (MTP)", 0x685c, DEVICE_FLAGS_ANDROID_BUGS }, { "Hewlett-Packard", 0x0bb4, "HP Touchpad (MTP+ADB)", 0x6860, DEVICE_FLAGS_ANDROID_BUGS }, #if 0 // Apparently also used by a clone called Jiayu G2S // with the MTK6577T chipset // http://www.ejiayu.com/en/Product-19.html with { "HTC", 0x0bb4, "Android Device ID2 (Zopo, HD2...)", 0x2008, DEVICE_FLAGS_ANDROID_BUGS }, #endif /* * NEC */ { "NEC", 0x0409, "FOMA N01A", 0x0242, DEVICE_FLAG_NONE }, /* * nVidia */ // Found on Internet forum { "nVidia", 0x0955, "CM9-Adam", 0x70a9, DEVICE_FLAGS_ANDROID_BUGS }, { "nVidia", 0x0955, "Nabi2 Tablet (ID1)", 0x7100, DEVICE_FLAGS_ANDROID_BUGS }, { "nVidia", 0x0955, "Nabi2 Tablet (ID2)", 0x7102, DEVICE_FLAGS_ANDROID_BUGS }, /* * Vizio */ // Reported by Michael Gurski { "Vizio", 0x0489, "VTAB1008", 0xe040, DEVICE_FLAGS_ANDROID_BUGS }, /* * Amazon */ { "Amazon", 0x1949, "Kindle Fire 2G (ID1)", 0x0005, DEVICE_FLAGS_ANDROID_BUGS }, { "Amazon", 0x1949, "Kindle Fire (ID1)", 0x0007, DEVICE_FLAGS_ANDROID_BUGS }, { "Amazon", 0x1949, "Kindle Fire (ID2)", 0x0008, DEVICE_FLAGS_ANDROID_BUGS }, { "Amazon", 0x1949, "Kindle Fire (ID3)", 0x000a, DEVICE_FLAGS_ANDROID_BUGS }, /* * Barnes&Noble */ { "Barnes&Noble", 0x2080, "Nook HD+", 0x0005, DEVICE_FLAGS_ANDROID_BUGS }, { "Barnes&Noble", 0x2080, "Nook HD", 0x0006, DEVICE_FLAGS_ANDROID_BUGS }, /* * Viewpia, bq, YiFang * Seems like some multi-branded OEM product line. */ { "Various", 0x2207, "Viewpia DR/bq Kepler", 0x0001, DEVICE_FLAGS_ANDROID_BUGS }, { "YiFang", 0x2207, "BQ Tesla", 0x0006, DEVICE_FLAGS_ANDROID_BUGS }, /* * Kobo */ // Reported by George Talusan { "Kobo", 0x2237, "Arc (ID1)", 0xd108, DEVICE_FLAGS_ANDROID_BUGS }, { "Kobo", 0x2237, "Arc (ID2)", 0xd109, DEVICE_FLAGS_ANDROID_BUGS }, /* * Hisense */ // Reported by Anonymous SourceForge user { "Hisense", 0x109b, "E860", 0x9109, DEVICE_FLAGS_ANDROID_BUGS }, /* * Intel * Also sold rebranded as Orange products */ { "Intel", 0x8087, "Xolo 900/AZ210A", 0x09fb, DEVICE_FLAGS_ANDROID_BUGS }, /* * Xiaomi */ { "Xiaomi", 0x2717, "Mi-2 (MTP+ADB)", 0x9039, DEVICE_FLAGS_ANDROID_BUGS }, { "Xiaomi", 0x2717, "Mi-2 (MTP)", 0xf003, DEVICE_FLAGS_ANDROID_BUGS }, /* * XO Learning Tablet */ { "Acromag Inc.", 0x16d5, "XO Learning Tablet (MTP+ADB)", 0x8005, DEVICE_FLAGS_ANDROID_BUGS }, { "Acromag Inc.", 0x16d5, "XO Learning Tablet (MTP)", 0x8006, DEVICE_FLAGS_ANDROID_BUGS }, /* * SHARP Corporation */ { "SHARP Corporation", 0x0489, "SH930W", 0xc025, DEVICE_FLAGS_ANDROID_BUGS }, { "SHARP Corporation", 0x04dd, "SBM203SH", 0x9661, DEVICE_FLAGS_ANDROID_BUGS }, /* * Alcatel */ { "Alcatel", 0x1bbb, "One Touch 997D", 0x2008, DEVICE_FLAGS_ANDROID_BUGS }, /* * Other strange stuff. */ { "Isabella", 0x0b20, "Her Prototype", 0xddee, DEVICE_FLAG_NONE } libmtp-1.1.6-20-g1b9f164/src/util.c0000664000175000017500000000622712205614637016631 0ustar glowwormglowworm/** * \file util.c * * This file contains generic utility functions such as can be * used for debugging for example. * * Copyright (C) 2005-2007 Linus Walleij * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* MSVC does not have these */ #ifndef _MSC_VER #include #include #endif #include #include #include #include #include #include #include "libmtp.h" #include "util.h" /** * This dumps out a number of bytes to a textual, hexadecimal * dump. * * @param f the file to dump to (e.g. stdout or stderr) * @param buf a pointer to the buffer containing the bytes to * be dumped out in hex * @param n the number of bytes to dump from this buffer */ void data_dump (FILE *f, void *buf, uint32_t n) { unsigned char *bp = (unsigned char *) buf; uint32_t i; for (i = 0; i < n; i++) { fprintf(f, "%02x ", *bp); bp++; } fprintf(f, "\n"); } /** * This dumps out a number of bytes to a textual, hexadecimal * dump, and also prints out the string ASCII representation * for each line of bytes. It will also print the memory address * offset from a certain boundry. * * @param f the file to dump to (e.g. stdout or stderr) * @param buf a pointer to the buffer containing the bytes to * be dumped out in hex * @param n the number of bytes to dump from this buffer * @param dump_boundry the address offset to start at (usually 0) */ void data_dump_ascii (FILE *f, void *buf, uint32_t n, uint32_t dump_boundry) { uint32_t remain = n; uint32_t ln, lc; int i; unsigned char *bp = (unsigned char *) buf; lc = 0; while (remain) { fprintf(f, "\t%04x:", dump_boundry-0x10); ln = ( remain > 16 ) ? 16 : remain; for (i = 0; i < ln; i++) { if ( ! (i%2) ) fprintf(f, " "); fprintf(f, "%02x", bp[16*lc+i]); } if ( ln < 16 ) { int width = ((16-ln)/2)*5 + (2*(ln%2)); fprintf(f, "%*.*s", width, width, ""); } fprintf(f, "\t"); for (i = 0; i < ln; i++) { unsigned char ch= bp[16*lc+i]; fprintf(f, "%c", ( ch >= 0x20 && ch <= 0x7e ) ? ch : '.'); } fprintf(f, "\n"); lc++; remain -= ln; dump_boundry += ln; } } #ifndef HAVE_STRNDUP char *strndup (const char *s, size_t n) { size_t len = strlen (s); char *ret; if (len <= n) return strdup (s); ret = malloc(n + 1); strncpy(ret, s, n); ret[n] = '\0'; return ret; } #endif libmtp-1.1.6-20-g1b9f164/doc/0000775000175000017500000000000012205614637015457 5ustar glowwormglowwormlibmtp-1.1.6-20-g1b9f164/doc/Makefile.am0000664000175000017500000000061512205614637017515 0ustar glowwormglowwormEXTRA_DIST=Doxyfile.in examples.h mainpage.h if HAVE_DOXYGEN pkgdocdir=$(datadir)/doc/$(PACKAGE)-$(VERSION) htmldocdir=$(pkgdocdir)/html all-local: doxygen install-data-local: $(INSTALL) -d $(DESTDIR)$(htmldocdir) $(INSTALL_DATA) html/* $(DESTDIR)$(htmldocdir) uninstall-local: $(RM) -r $(DESTDIR)$(htmldocdir) $(RM) -r $(DESTDIR)$(pkgdocdir) clean-local: $(RM) -r html latex man endif libmtp-1.1.6-20-g1b9f164/doc/mainpage.h0000664000175000017500000000102012205614637017402 0ustar glowwormglowworm/** * \mainpage The official libmtp documentation * * \section Introduction * * libmtp is a library for the Media Transfer Protocol (MTP) * under various POSIX operating systems. * * \section License * * libmtp is available under the GNU Lesser General Public License, * version 2. You can use libmtp in Free or proprietary software alike as * long as you publish your modifications to this library in accordance * with the LGPL license. If you do not follow the LGPL you will be in * deep, deep trouble. * */ libmtp-1.1.6-20-g1b9f164/doc/examples.h0000664000175000017500000000062512205614637017451 0ustar glowwormglowworm/* * List examples here... */ /** \example delfile.c */ /** \example detect.c */ /** \example files.c */ /** \example folders.c */ /** \example getfile.c */ /** \example hotplug.c */ /** \example newfolder.c */ /** \example sendfile.c */ /** \example sendtr.c */ /** \example tracks.c */ /** \example trexist.c */ /** \example playlists.c */ /** \example getplaylist.c */ /** \example refactortest.c */ libmtp-1.1.6-20-g1b9f164/doc/Doxyfile.in0000664000175000017500000013317412205614637017603 0ustar glowwormglowworm# Doxyfile 1.3.9.1 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project # # All text after a hash (#) is considered a comment and will be ignored # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" ") #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # The PROJECT_NAME tag is a single word (or a sequence of words surrounded # by quotes) that should identify the project. PROJECT_NAME = "libmtp" # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. # Do this with autoconf eventually PROJECT_NUMBER = @VERSION@ # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. #OUTPUT_DIRECTORY = . # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create # 4096 sub-directories (in 2 levels) under the output directory of each output # format and will distribute the generated files over these directories. # Enabling this option can be useful when feeding doxygen a huge amount of source # files, where putting all generated files in the same directory would otherwise # cause performance problems for the file system. CREATE_SUBDIRS = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Brazilian, Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, # Dutch, Finnish, French, German, Greek, Hungarian, Italian, Japanese, # Japanese-en (Japanese with English messages), Korean, Korean-en, Norwegian, # Polish, Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, # Swedish, and Ukrainian. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is used # as the annotated text. Otherwise, the brief description is used as-is. If left # blank, the following values are used ("$name" is automatically replaced with the # name of the entity): "The $name class" "The $name widget" "The $name file" # "is" "provides" "specifies" "contains" "represents" "a" "an" "the" ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all inherited # members of a class in the documentation of that class as if those members were # ordinary class members. Constructors, destructors and assignment operators of # the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = YES # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the # path to strip. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of # the path mentioned in the documentation of a class, which tells # the reader which header file to include in order to use a class. # If left blank only the name of the header file containing the class # definition is used. Otherwise one should specify the include paths that # are normally passed to the compiler using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful is your file systems # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like the Qt-style comments (thus requiring an # explicit @brief command for a brief description. JAVADOC_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the DETAILS_AT_TOP tag is set to YES then Doxygen # will output the detailed description near the top, like JavaDoc. # If set to NO, the detailed description appears after the member # documentation. # DETAILS_AT_TOP = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 8 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources # only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = YES # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java sources # only. Doxygen will then generate output that is more tailored for Java. # For instance, namespaces will be presented as packages, qualified scopes # will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = NO # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = NO # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = YES # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or define consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and defines in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = YES # If the sources in your project are distributed over multiple directories # then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy # in the documentation. SHOW_DIRECTORIES = YES #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. # Set to YES by Linus Walleij on 2005-07-30. QUIET = YES # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. # Set to NO by Linus Walleij on 2005-07-30. WARNINGS = NO # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. # Set to NO by Linus Walleij on 2005-07-30. WARN_IF_UNDOCUMENTED = NO # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. # Set to NO by Linus Walleij on 2005-07-30. WARN_IF_DOC_ERROR = NO # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = @top_srcdir@/src \ @top_srcdir@/doc/mainpage.h \ @top_srcdir@/doc/examples.h # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx *.hpp # *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm FILE_PATTERNS = *.c *.h # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = NO # The EXCLUDE tag can be used to specify files and/or directories that should # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used select whether or not files or directories # that are symbolic links (a Unix filesystem feature) are excluded from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. EXCLUDE_PATTERNS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = @top_srcdir@/examples # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = *.c # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. If FILTER_PATTERNS is specified, this tag will be # ignored. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. Doxygen will compare the file name with each pattern and apply the # filter if there is a match. The filters are a list of the form: # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further # info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER # is applied to all files. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES (the default) # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = YES # If the REFERENCES_RELATION tag is set to YES (the default) # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = YES # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = NO # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. # doc/libnjb_header.html HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet. Note that doxygen will try to copy # the style sheet file to the HTML output directory, so don't put your own # stylesheet in the HTML output directory as well, or it will be erased! HTML_STYLESHEET = # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. HTML_ALIGN_MEMBERS = YES # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compressed HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # The DISABLE_INDEX tag can be used to turn on/off the condensed index at # top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. DISABLE_INDEX = NO # This tag can be used to set the number of enum values (range [1..20]) # that doxygen will group on one line in the generated HTML documentation. ENUM_VALUES_PER_LINE = 4 # If the GENERATE_TREEVIEW tag is set to YES, a side panel will be # generated containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, # Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are # probably better off using the HTML help feature. GENERATE_TREEVIEW = NO # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 250 #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = YES # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, a4wide, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = NO # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = NO # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load stylesheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = YES # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. This is useful # if you want to understand what is going on. On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = NO # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_PREDEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # in the INCLUDE_PATH (see below) will be search if a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. To prevent a macro definition from being # undefined via #undef or recursively expanded use the := operator # instead of the = operator. PREDEFINED = # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all function-like macros that are alone # on a line, have an all uppercase name, and do not end with a semicolon. Such # function macros are typically used for boiler-plate code, and will confuse the # parser if not removed. SKIP_FUNCTION_MACROS = NO #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. # Optionally an initial location of the external documentation # can be added for each tagfile. The format of a tag file without # this location is as follows: # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths or # URLs. If a location is present for each tag, the installdox tool # does not have to be run to correct the links. # Note that each tag file must have a unique name # (where the name does NOT include the path) # If a tag file is not located in the directory in which doxygen # is run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = YES # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base or # super classes. Setting the tag to NO turns the diagrams off. Note that this # option is superseded by the HAVE_DOT option below. This is only a fallback. It is # recommended to install and use dot, since it yields more powerful graphs. CLASS_DIAGRAMS = YES # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = NO # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # the CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = NO # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = NO # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = YES # If the CALL_GRAPH and HAVE_DOT tags are set to YES then doxygen will # generate a call dependency graph for every global function or class method. # Note that enabling this option will significantly increase the time of a run. # So in most cases it will be better to enable call graphs for selected # functions only using the \callgraph command. CALL_GRAPH = NO # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are png, jpg, or gif # If left blank png will be used. DOT_IMAGE_FORMAT = png # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found on the path. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes that # lay further from the root node will be omitted. Note that setting this option to # 1 or 2 may greatly reduce the computation time needed for large code bases. Also # note that a graph may be further truncated if the graph's image dimensions are # not sufficient to fit the graph (see MAX_DOT_GRAPH_WIDTH and MAX_DOT_GRAPH_HEIGHT). # If 0 is used for the depth value (the default), the graph is not depth-constrained. MAX_DOT_GRAPH_DEPTH = 0 # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES #--------------------------------------------------------------------------- # Configuration::additions related to the search engine #--------------------------------------------------------------------------- # The SEARCHENGINE tag specifies whether or not a search engine should be # used. If set to NO the values of all tags below this one will be ignored. SEARCHENGINE = NO libmtp-1.1.6-20-g1b9f164/hotplug.sh.in0000775000175000017500000001167712205614637017354 0ustar glowwormglowworm#!/bin/bash INSTALL="@INSTALL@" HOTPLUGPATH=/etc/hotplug SCRIPTNAME=libmtp.sh USERMAP=libmtp.usermap UDEVPATH=/etc/udev/rules.d UDEVRULES=libmtp.rules HALBASEPATH=/usr/share/hal/fdi/information HALPATH=/usr/share/hal/fdi/information/20thirdparty HALRULES=libmtp.fdi # See if the parameter script ($2), device ($3) and productid ($4) # are already defined in the usermap ($1) function inmap { while read LINE; do if [ "x${LINE}" != "x" ]; then firstword=`echo ${LINE} | awk '{ print $1 }'` if [ ${firstword} != "#" ]; then # This is a device line entry script=${firstword} manid=`echo ${LINE} | awk '{ print $3 }'` productid=`echo ${LINE} | awk '{ print $4 }'` # Skip blank products... if [ "x${script}" = "x$2" ]; then if [ "x${manid}" = "x$3" ]; then if [ "x${productid}" = "x$4" ]; then echo "yes" return 0 fi fi fi fi fi done < $1 echo "no" return 0 } # Scan the usermap $2 for all devices in $1 to see if they are already # there, else patch the usermap. function patchusermap { # Nullify comment comment="" while read LINE; do if [ "x$LINE" != "x" ]; then firstword=`echo ${LINE} | awk '{ print $1 }'` if [ ${firstword} = "#" ]; then # This is a comment line, save it. comment=${LINE} else # This is a device line entry script=${firstword} manid=`echo ${LINE} | awk '{ print $3 }'` productid=`echo ${LINE} | awk '{ print $4 }'` # Skip blank products... if [ "x${manid}" != "x" ]; then # See if this product is already in the usermap echo "Checking for product ${productid} in $2..." if [ `inmap $2 ${script} ${manid} ${productid}` = "no" ]; then echo "Not present, adding to hotplug map." echo ${comment} >> $2 echo ${LINE} >> $2 comment="" else echo "Already installed." fi fi fi fi done < $1 } # Check for udev first if test -d ${UDEVPATH} ; then echo "You seem to have udev on your system. Installing udev rules..." ${INSTALL} ${UDEVRULES} ${UDEVPATH} echo "You may need additional setup to get correct permissions on your device." echo "See the INSTALL file for information." echo "Do you also want to install HAL support or the old hotplug support (y/n)?" read IN if [ "$IN" = "y" ] || [ "$IN" = "Y" ]; then echo "Continuing..." else exit 0 fi fi # Check for HAL next if test -d ${HALBASEPATH} ; then echo "You seem to have HAL on your system. Installing HAL rules..." mkdir -p ${HALPATH} ${INSTALL} ${HALRULES} ${HALPATH} echo "Do you also want to install the old hotplug support (y/n)?" read IN if [ "$IN" = "y" ] || [ "$IN" = "Y" ]; then echo "Continuing..." else exit 0 fi fi # Check prerequisites COMMAND=`which grep 2> /dev/null` if [ "x${COMMAND}" = "x" ]; then echo "Missing grep program. Fatal error." exit 1 fi COMMAND=`which awk 2> /dev/null` if [ "x${COMMAND}" = "x" ]; then echo "Missing awk program. Fatal error." exit 1 fi if [ "x${USER}" != "xroot" ]; then echo "WARNING: this program should be run as root!" fi # This script locates the hotplug distribution on a certain host # and sets up userland hotplugging scripts according to rules. # The in-parameters are the hotplug directory and the name of a # file of hotplug device entries and a script to be executed for # these deviced. if test -d ${HOTPLUGPATH} then echo "Hotplug in ${HOTPLUGPATH}" else echo "Hotplug missing on this system. Cannot install." exit 1 fi if test -d ${HOTPLUGPATH}/usb then echo "Has usb subdirectory." else mkdir ${HOTPLUGPATH}/usb fi echo "Installing script." ${INSTALL} libmtp.sh ${HOTPLUGPATH}/usb echo "Installing usermap." ${INSTALL} -m 644 ${USERMAP} ${HOTPLUGPATH}/usb # If we find a usb.usermap file, and we see that this distribution # of hotplug does not support private usermaps, then we need to # patch the usb.usermap file. # # Create a merged file, diff the files to each other, and if there # were mismatches, then patch the installed file. echo "Checking hotplugging CVS version..." echo "/etc/hotplug/usb/*.usermap support was added in august 2002" EDITMAP="yes" CVSTAG=`grep '\$Id:' /etc/hotplug/usb.agent` if [ "x${CVSTAG}" != "x" ]; then DATE=`echo ${CVSTAG} | awk '{ print $5 }'` echo "Hotplug version seems to be from ${DATE}" YEAR=`echo ${DATE} | awk 'BEGIN { FS="/"} {print $1; }'` MONTH=`echo ${DATE} | awk 'BEGIN { FS="/"} {print $2; }'` DAY=`echo ${DATE} | awk 'BEGIN { FS="/"} {print $3; }'` if [ "${YEAR}" -gt "2002" ]; then EDITMAP="no" else if [ "${YEAR}" -eq "2002" ]; then if [ "${MONTH}" -ge "08" ]; then EDITMAP="no" fi fi fi fi if [ "x${EDITMAP}" == "xyes" ]; then echo "We need to edit the ${HOTPLUGPATH}/usb.usermap if it exists..." if test -f ${HOTPLUGPATH}/usb.usermap then echo "We have a usb.usermap..." patchusermap ${USERMAP} /etc/hotplug/usb.usermap fi fi echo "Hotplugging successfully installed." exit 0 libmtp-1.1.6-20-g1b9f164/util/0000775000175000017500000000000012205614637015667 5ustar glowwormglowwormlibmtp-1.1.6-20-g1b9f164/util/Makefile.am0000664000175000017500000000033012205614637017717 0ustar glowwormglowwormif USE_LINUX bin_PROGRAMS=mtp-hotplug mtp_hotplug_SOURCES=mtp-hotplug.c mtp_probedir=@UDEV@ mtp_probe_PROGRAMS=mtp-probe mtp_probe_SOURCES=mtp-probe.c endif AM_CPPFLAGS=-I$(top_builddir)/src LDADD=../src/libmtp.la libmtp-1.1.6-20-g1b9f164/util/mtp-probe.c0000664000175000017500000001632512205614637017747 0ustar glowwormglowworm/** * \file mtp-probe.c * Program to probe newly connected device interfaces from * userspace to determine if they are MTP devices, used for * udev rules. * * Invoke the program from udev to check it for MTP signatures, * e.g. * ATTR{bDeviceClass}=="ff", * PROGRAM="/mtp-probe /sys$env{DEVPATH} $attr{busnum} $attr{devnum}", * RESULT=="1", ENV{ID_MTP_DEVICE}="1", ENV{ID_MEDIA_PLAYER}="1", * SYMLINK+="libmtp-%k", MODE="666" * * Is you issue this before testing your /var/log/messages * will be more verbose: * * udevadm control --log-priority=debug * * Exits with status code 1 if the device is an MTP device, * else exits with 0. * * Copyright (C) 2011-2012 Linus Walleij * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef __linux__ #error "This program should only be compiled for Linux!" #endif #include #include #include #include #include #include #include #include #include #include #include enum ep_type { OTHER_EP, BULK_OUT_EP, BULK_IN_EP, INTERRUPT_IN_EP, INTERRUPT_OUT_EP, }; static enum ep_type get_ep_type(char *path) { char pbuf[FILENAME_MAX]; int len = strlen(path); int fd; char buf[128]; int bread; int is_out = 0; int is_in = 0; int is_bulk = 0; int is_interrupt = 0; int i; strcpy(pbuf, path); pbuf[len++] = '/'; /* Check the type */ strncpy(pbuf + len, "type", FILENAME_MAX - len); pbuf[FILENAME_MAX - 1] = '\0'; /* Sentinel */ fd = open(pbuf, O_RDONLY); if (fd < 0) return OTHER_EP; bread = read(fd, buf, sizeof(buf)); close(fd); if (bread < 2) return OTHER_EP; for (i = 0; i < bread; i++) if(buf[i] == 0x0d || buf[i] == 0x0a) buf[i] = '\0'; if (!strcmp(buf, "Bulk")) is_bulk = 1; if (!strcmp(buf, "Interrupt")) is_interrupt = 1; /* Check the direction */ strncpy(pbuf + len, "direction", FILENAME_MAX - len); pbuf[FILENAME_MAX - 1] = '\0'; /* Sentinel */ fd = open(pbuf, O_RDONLY); if (fd < 0) return OTHER_EP; bread = read(fd, buf, sizeof(buf)); close(fd); if (bread < 2) return OTHER_EP; for (i = 0; i < bread; i++) if(buf[i] == 0x0d || buf[i] == 0x0a) buf[i] = '\0'; if (!strcmp(buf, "in")) is_in = 1; if (!strcmp(buf, "out")) is_out = 1; if (is_bulk && is_in) return BULK_IN_EP; if (is_bulk && is_out) return BULK_OUT_EP; if (is_interrupt && is_in) return INTERRUPT_IN_EP; if (is_interrupt && is_out) return INTERRUPT_OUT_EP; return OTHER_EP; } static int has_3_ep(char *path) { char pbuf[FILENAME_MAX]; int len = strlen(path); int fd; char buf[128]; int bread; strcpy(pbuf, path); pbuf[len++] = '/'; strncpy(pbuf + len, "bNumEndpoints", FILENAME_MAX - len); pbuf[FILENAME_MAX - 1] = '\0'; /* Sentinel */ fd = open(pbuf, O_RDONLY); if (fd < 0) return -1; /* Read all contents to buffer */ bread = read(fd, buf, sizeof(buf)); close(fd); if (bread < 2) return 0; /* 0x30, 0x33 = "03", maybe we should parse it? */ if (buf[0] == 0x30 && buf[1] == 0x33) return 1; return 0; } static int check_interface(char *sysfspath) { char dirbuf[FILENAME_MAX]; int len = strlen(sysfspath); DIR *dir; struct dirent *dent; regex_t r; int ret; int bulk_out_ep_found = 0; int bulk_in_ep_found = 0; int interrupt_in_ep_found = 0; ret = has_3_ep(sysfspath); if (ret <= 0) return ret; /* Yes it has three endpoints ... look even closer! */ dir = opendir(sysfspath); if (!dir) return -1; strcpy(dirbuf, sysfspath); dirbuf[len++] = '/'; /* Check for dirs that identify endpoints */ ret = regcomp(&r, "^ep_[0-9a-f]+$", REG_EXTENDED | REG_NOSUB); if (ret) return -1; while ((dent = readdir(dir))) { struct stat st; /* No need to check those beginning with a period */ if (dent->d_name[0] == '.') continue; strncpy(dirbuf + len, dent->d_name, FILENAME_MAX - len); dirbuf[FILENAME_MAX - 1] = '\0'; /* Sentinel */ ret = lstat(dirbuf, &st); if (ret) continue; if (S_ISDIR(st.st_mode) && !regexec(&r, dent->d_name, 0, 0, 0)) { enum ep_type ept; ept = get_ep_type(dirbuf); if (ept == BULK_OUT_EP) bulk_out_ep_found = 1; else if (ept == BULK_IN_EP) bulk_in_ep_found = 1; else if (ept == INTERRUPT_IN_EP) interrupt_in_ep_found = 1; } } regfree(&r); closedir(dir); /* * If this is fulfilled the interface is an MTP candidate */ if (bulk_out_ep_found && bulk_in_ep_found && interrupt_in_ep_found) { return 1; } return 0; } static int check_sysfs(char *sysfspath) { char dirbuf[FILENAME_MAX]; int len = strlen(sysfspath); DIR *dir; struct dirent *dent; regex_t r; int ret; int look_closer = 0; dir = opendir(sysfspath); if (!dir) return -1; strcpy(dirbuf, sysfspath); dirbuf[len++] = '/'; /* Check for dirs that identify interfaces */ ret = regcomp(&r, "^[0-9]+-[0-9]+\\:[0-9]+\\.[0-9]+$", REG_EXTENDED | REG_NOSUB); if (ret) return -1; while ((dent = readdir(dir))) { struct stat st; int ret; /* No need to check those beginning with a period */ if (dent->d_name[0] == '.') continue; strncpy(dirbuf + len, dent->d_name, FILENAME_MAX - len); dirbuf[FILENAME_MAX - 1] = '\0'; /* Sentinel */ ret = lstat(dirbuf, &st); if (ret) continue; /* Look closer at dirs that may be interfaces */ if (S_ISDIR(st.st_mode)) { if (!regexec(&r, dent->d_name, 0, 0, 0)) if (check_interface(dirbuf) > 0) /* potential MTP interface! */ look_closer = 1; } } regfree(&r); closedir(dir); return look_closer; } int main (int argc, char **argv) { char *fname; int busno; int devno; int ret; if (argc < 4) { syslog(LOG_INFO, "need device path, busnumber, device number as argument\n"); printf("0"); exit(0); } fname = argv[1]; busno = atoi(argv[2]); devno = atoi(argv[3]); syslog(LOG_INFO, "checking bus %d, device %d: \"%s\"\n", busno, devno, fname); ret = check_sysfs(fname); /* * This means that regular directory check either agrees that this may be a * MTP device, or that it doesn't know (failed). In that case, kick the deeper * check inside LIBMTP. */ if (ret != 0) ret = LIBMTP_Check_Specific_Device(busno, devno); if (ret) { syslog(LOG_INFO, "bus: %d, device: %d was an MTP device\n", busno, devno); printf("1"); } else { syslog(LOG_INFO, "bus: %d, device: %d was not an MTP device\n", busno, devno); printf("0"); } exit(0); } libmtp-1.1.6-20-g1b9f164/util/mtp-hotplug.c0000664000175000017500000002661412205614637020324 0ustar glowwormglowworm/** * \file mtp-hotplug.c * Program to create hotplug scripts. * * Copyright (C) 2005-2012 Linus Walleij * Copyright (C) 2006-2008 Marcus Meissner * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include #include #include #include #include static void usage(void) { fprintf(stderr, "usage: hotplug [-u -H -i -a\"ACTION\"] -p\"DIR\" -g\"GROUP\" -m\"MODE\"\n"); fprintf(stderr, " -u: use udev syntax\n"); fprintf(stderr, " -o: use old udev syntax\n"); fprintf(stderr, " -H: use hal syntax\n"); fprintf(stderr, " -i: use usb.ids simple list syntax\n"); fprintf(stderr, " -a\"ACTION\": perform udev action ACTION on attachment\n"); fprintf(stderr, " -p\"DIR\": directory where mtp-probe will be installed\n"); fprintf(stderr, " -g\"GROUP\": file group for device nodes\n"); fprintf(stderr, " -m\"MODE\": file mode for device nodes\n"); exit(1); } enum style { style_usbmap, style_udev, style_udev_old, style_hal, style_usbids }; int main (int argc, char **argv) { LIBMTP_device_entry_t *entries; int numentries; int i; int ret; enum style style = style_usbmap; int opt; extern int optind; extern char *optarg; char *udev_action = NULL; /* * You could tag on MODE="0666" here to enfore writeable * device nodes, use the command line argument for that. * Current udev default rules will make any device tagged * with ENV{ID_MEDIA_PLAYER}=1 writable for the console * user. */ char default_udev_action[] = "SYMLINK+=\"libmtp-%k\", ENV{ID_MTP_DEVICE}=\"1\", ENV{ID_MEDIA_PLAYER}=\"1\""; char *action; // To hold the action actually used. uint16_t last_vendor = 0x0000U; char mtp_probe_dir[256]; char *udev_group= NULL; char *udev_mode = NULL; while ( (opt = getopt(argc, argv, "uoiHa:p:g:m:")) != -1 ) { switch (opt) { case 'a': udev_action = strdup(optarg); break; case 'u': style = style_udev; break; case 'o': style = style_udev_old; break; case 'H': style = style_hal; break; case 'i': style = style_usbids; break; case 'p': strncpy(mtp_probe_dir,optarg,sizeof(mtp_probe_dir)); mtp_probe_dir[sizeof(mtp_probe_dir)-1] = '\0'; if (strlen(mtp_probe_dir) <= 1) { printf("Supply some sane mtp-probe dir\n"); exit(1); } /* Make sure the dir ends with '/' */ if (mtp_probe_dir[strlen(mtp_probe_dir)-1] != '/') { int index = strlen(mtp_probe_dir); if (index >= (sizeof(mtp_probe_dir)-1)) { exit(1); } mtp_probe_dir[index] = '/'; mtp_probe_dir[index+1] = '\0'; } /* Don't add the standard udev path... */ if (!strcmp(mtp_probe_dir, "/lib/udev/")) { mtp_probe_dir[0] = '\0'; } break; case 'g': udev_group = strdup(optarg); break; case 'm': udev_mode = strdup(optarg); break; default: usage(); } } if (udev_action != NULL) { action = udev_action; } else { action = default_udev_action; } LIBMTP_Init(); ret = LIBMTP_Get_Supported_Devices_List(&entries, &numentries); if (ret == 0) { switch (style) { case style_udev: printf("# UDEV-style hotplug map for libmtp\n"); printf("# Put this file in /etc/udev/rules.d\n\n"); printf("ACTION!=\"add\", GOTO=\"libmtp_rules_end\"\n"); printf("ENV{MAJOR}!=\"?*\", GOTO=\"libmtp_rules_end\"\n"); printf("SUBSYSTEM==\"usb\", GOTO=\"libmtp_usb_rules\"\n" "GOTO=\"libmtp_rules_end\"\n\n" "LABEL=\"libmtp_usb_rules\"\n\n"); printf("# Some sensitive devices we surely don\'t wanna probe\n"); printf("# Color instruments\n"); printf("ATTR{idVendor}==\"0670\", GOTO=\"libmtp_rules_end\"\n"); printf("ATTR{idVendor}==\"0765\", GOTO=\"libmtp_rules_end\"\n"); printf("ATTR{idVendor}==\"085c\", GOTO=\"libmtp_rules_end\"\n"); printf("ATTR{idVendor}==\"0971\", GOTO=\"libmtp_rules_end\"\n"); printf("# Canon scanners that look like MTP devices (PID 0x22nn)\n"); printf("ATTR{idVendor}==\"04a9\", ATTR{idProduct}==\"22*\", GOTO=\"libmtp_rules_end\"\n"); printf("# Canon digital camera (EOS 3D) that looks like MTP device (PID 0x3113)\n"); printf("ATTR{idVendor}==\"04a9\", ATTR{idProduct}==\"3113\", GOTO=\"libmtp_rules_end\"\n"); printf("# Sensitive Atheros devices that look like MTP devices\n"); printf("ATTR{idVendor}==\"0cf3\", GOTO=\"libmtp_rules_end\"\n"); printf("# Sensitive Atmel JTAG programmers\n"); printf("ATTR{idVendor}==\"03eb\", GOTO=\"libmtp_rules_end\"\n"); printf("# Sensitive Philips device\n"); printf("ATTR{idVendor}==\"0471\", ATTR{idProduct}==\"083f\", GOTO=\"libmtp_rules_end\"\n"); break; case style_udev_old: printf("# UDEV-style hotplug map for libmtp\n"); printf("# Put this file in /etc/udev/rules.d\n\n"); printf("ACTION!=\"add\", GOTO=\"libmtp_rules_end\"\n"); printf("ENV{MAJOR}!=\"?*\", GOTO=\"libmtp_rules_end\"\n"); printf("SUBSYSTEM==\"usb_device\", GOTO=\"libmtp_usb_device_rules\"\n" "GOTO=\"libmtp_rules_end\"\n\n" "LABEL=\"libmtp_usb_device_rules\"\n\n"); break; case style_usbmap: printf("# This usermap will call the script \"libmtp.sh\" whenever a known MTP device is attached.\n\n"); break; case style_hal: printf(" \n"); printf("\n", argv[0]); printf("\n"); printf(" \n"); printf(" \n"); break; case style_usbids: printf("# usb.ids style device list from libmtp\n"); printf("# Compare: http://www.linux-usb.org/usb.ids\n"); break; } for (i = 0; i < numentries; i++) { LIBMTP_device_entry_t * entry = &entries[i]; switch (style) { case style_udev: case style_udev_old: printf("# %s %s\n", entry->vendor, entry->product); printf("ATTR{idVendor}==\"%04x\", ATTR{idProduct}==\"%04x\", %s", entry->vendor_id, entry->product_id, action); if (udev_group != NULL) printf(", GROUP=\"%s\"", udev_group); if (udev_mode != NULL) printf(", MODE=\"%s\"", udev_mode); printf("\n"); break; case style_usbmap: printf("# %s %s\n", entry->vendor, entry->product); printf("libmtp.sh 0x0003 0x%04x 0x%04x 0x0000 0x0000 0x00 0x00 0x00 0x00 0x00 0x00 0x00000000\n", entry->vendor_id, entry->product_id); break; case style_hal: printf(" \n", entry->vendor, entry->product); printf(" \n", entry->vendor_id); printf(" \n", entry->product_id); /* FIXME: If hal >=0.5.10 can be depended upon, the matches below with contains_not can instead use addset */ printf(" \n"); printf(" portable_audio_player\n"); printf(" \n"); printf(" %s\n", entry->vendor); printf(" %s\n", entry->product); printf(" portable_audio_player\n"); printf(" user\n"); printf(" \n"); printf(" mtp\n"); printf(" \n"); printf(" libmtp\n"); /* FIXME: needs true list of formats ... But all of them can do MP3 and WMA */ printf(" \n"); printf(" audio/mpeg\n"); printf(" \n"); printf(" \n"); printf(" audio/x-ms-wma\n"); printf(" \n"); /* Special hack to support the OGG format - irivers, TrekStor and NormSoft (Palm) can always play these files! */ if (entry->vendor_id == 0x4102 || // iriver entry->vendor_id == 0x066f || // TrekStor entry->vendor_id == 0x1703) { // NormSoft, Inc. printf(" \n"); printf(" application/ogg\n"); printf(" \n"); } printf(" mtp\n"); printf(" \n"); printf(" \n"); break; case style_usbids: if (last_vendor != entry->vendor_id) { printf("%04x\n", entry->vendor_id); } printf("\t%04x %s %s\n", entry->product_id, entry->vendor, entry->product); break; } last_vendor = entry->vendor_id; } } else { printf("Error.\n"); exit(1); } // Then the footer. switch (style) { case style_usbmap: break; case style_udev: case style_udev_old: /* * This is code that invokes the mtp-probe program on * every USB device that is either PTP or vendor specific */ printf("\n# Autoprobe vendor-specific, communication and PTP devices\n"); printf("ENV{ID_MTP_DEVICE}!=\"1\", ENV{MTP_NO_PROBE}!=\"1\", ENV{COLOR_MEASUREMENT_DEVICE}!=\"1\", ENV{libsane_matched}!=\"yes\", ATTR{bDeviceClass}==\"00|02|06|ef|ff\", PROGRAM=\"%smtp-probe /sys$env{DEVPATH} $attr{busnum} $attr{devnum}\", RESULT==\"1\", %s", mtp_probe_dir, action); if (udev_group != NULL) printf(", GROUP=\"%s\"", udev_group); if (udev_mode != NULL) printf(", MODE=\"%s\"", udev_mode); printf("\n"); printf("\nLABEL=\"libmtp_rules_end\"\n"); break; case style_hal: printf(" \n"); printf(" \n"); printf("\n"); break; case style_usbids: printf("\n"); } exit (0); } libmtp-1.1.6-20-g1b9f164/examples/0000775000175000017500000000000012205614637016530 5ustar glowwormglowwormlibmtp-1.1.6-20-g1b9f164/examples/getfile.c0000664000175000017500000000467712205614637020331 0ustar glowwormglowworm/** * \file getfile.c * Example program to retrieve a file off the device. * * Copyright (C) 2005-2007 Linus Walleij * Copyright (C) 2006 Chris A. Debenham * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include #include #include "common.h" #include "pathutils.h" #include "connect.h" extern LIBMTP_folder_t *folders; extern LIBMTP_file_t *files; extern LIBMTP_mtpdevice_t *device; void getfile_usage (void) { fprintf(stderr, "getfile \n"); } int getfile_function(char * from_path,char * to_path) { int id = parse_path (from_path,files,folders); if (id > 0) { printf("Getting %s to %s\n",from_path,to_path); if (LIBMTP_Get_File_To_File(device, id, to_path, progress, NULL) != 0 ) { printf("\nError getting file from MTP device.\n"); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); return 1; } } return 0; } int getfile_command(int argc, char **argv) { uint32_t id; char *endptr; char *file; int ret = 0; // We need file ID and filename if ( argc != 3 ) { getfile_usage(); return 0; } // Sanity check song ID id = strtoul(argv[1], &endptr, 10); if ( *endptr != 0 ) { fprintf(stderr, "illegal value %s\n", argv[1]); return 1; } else if ( ! id ) { fprintf(stderr, "bad file/track id %u\n", id); return 1; } // Filename, e.g. "foo.mp3" file = argv[2]; printf("Getting file/track %d to local file %s\n", id, file); // This function will also work just as well for tracks. if (LIBMTP_Get_File_To_File(device, id, file, progress, NULL) != 0 ) { printf("\nError getting file from MTP device.\n"); ret = 1; } // Terminate progress bar. printf("\n"); return ret; } libmtp-1.1.6-20-g1b9f164/examples/pathutils.h0000664000175000017500000000217312205614637020721 0ustar glowwormglowworm/** * \file pathutils.h * * Copyright (C) 2006 Chris A. Debenham * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef PATHUTILS_H_INCLUSION_GUARD #define PATHUTILS_H_INCLUSION_GUARD int parse_path (char *, LIBMTP_file_t *, LIBMTP_folder_t *); LIBMTP_filetype_t find_filetype (const char *); int progress (const uint64_t, const uint64_t, void const * const); #ifndef HAVE_LIBGEN_H char *basename(char *in); #endif #endif libmtp-1.1.6-20-g1b9f164/examples/folders.c0000664000175000017500000000717312205614637020342 0ustar glowwormglowworm/** * \file folders.c * Example program that lists all folders on a device. * * Copyright (C) 2005-2011 Linus Walleij * Copyright (C) 2007 Ted Bullock * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common.h" #include static void dump_folder_list(LIBMTP_folder_t *folderlist, int level) { int i; if(folderlist==NULL) { return; } printf("%u\t", folderlist->folder_id); for(i=0;iname); dump_folder_list(folderlist->child, level+1); dump_folder_list(folderlist->sibling, level); } int main (int argc, char **argv) { LIBMTP_mtpdevice_t *device_list, *device; LIBMTP_Init(); printf("Attempting to connect device(s)\n"); switch(LIBMTP_Get_Connected_Devices(&device_list)) { case LIBMTP_ERROR_NO_DEVICE_ATTACHED: printf("mtp-folders: no devices found\n"); return 0; case LIBMTP_ERROR_CONNECTING: fprintf(stderr, "mtp-folders: There has been an error connecting. Exit\n"); return 1; case LIBMTP_ERROR_MEMORY_ALLOCATION: fprintf(stderr, "mtp-folders: Memory Allocation Error. Exit\n"); return 1; /* Unknown general errors - This should never execute */ case LIBMTP_ERROR_GENERAL: default: fprintf(stderr, "mtp-folders: Unknown error, please report " "this to the libmtp developers\n"); return 1; /* Successfully connected at least one device, so continue */ case LIBMTP_ERROR_NONE: printf("mtp-folders: Successfully connected\n"); } /* iterate through connected MTP devices */ for(device = device_list; device != NULL; device = device->next) { LIBMTP_devicestorage_t *storage; char *friendlyname; int ret; /* Echo the friendly name so we know which device we are working with */ friendlyname = LIBMTP_Get_Friendlyname(device); if (friendlyname == NULL) { printf("Friendly name: (NULL)\n"); } else { printf("Friendly name: %s\n", friendlyname); free(friendlyname); } LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); /* Get all storages for this device */ ret = LIBMTP_Get_Storage(device, LIBMTP_STORAGE_SORTBY_NOTSORTED); if (ret != 0) { perror("LIBMTP_Get_Storage()\n"); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); continue; } /* Loop over storages, dump folder for each one */ for (storage = device->storage; storage != 0; storage = storage->next) { LIBMTP_folder_t *folders; printf("Storage: %s\n", storage->StorageDescription); folders = LIBMTP_Get_Folder_List_For_Storage(device, storage->id); if (folders == NULL) { fprintf(stdout, "No folders found\n"); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); } else { dump_folder_list(folders,0); } LIBMTP_destroy_folder_t(folders); } } LIBMTP_Release_Device_List(device_list); printf("OK.\n"); return 0; } libmtp-1.1.6-20-g1b9f164/examples/connect.h0000664000175000017500000000276312205614637020342 0ustar glowwormglowworm/** * \file connect.h * Header file for connect subfunctions * * Copyright (C) 2006 Chris A. Debenham * Copyright (C) 2008-2010 Linus Walleij * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ int delfile_function(char *); int delfile_command(int, char **); void delfile_usage(void); int sendtrack_function (char *, char *, char *, char *, char *, char *, char *, char *, uint16_t, uint16_t, uint16_t, uint32_t, uint16_t); int sendtrack_command (int, char **); void sendtrack_usage(void); int sendfile_function(char *,char *); int sendfile_command(int, char **); void sendfile_usage(void); int getfile_function(char *,char *); int getfile_command(int, char **); void getfile_usage(void); int newfolder_function(char *); int newfolder_command(int,char **); void newfolder_usage(void); libmtp-1.1.6-20-g1b9f164/examples/Makefile.am0000664000175000017500000000315512205614637020570 0ustar glowwormglowwormbin_PROGRAMS=mtp-connect mtp-detect mtp-tracks mtp-files \ mtp-folders mtp-trexist mtp-playlists mtp-getplaylist \ mtp-format mtp-albumart mtp-albums mtp-newplaylist mtp-emptyfolders \ mtp-thumb mtp-reset mtp-filetree mtp_connect_SOURCES=connect.c connect.h delfile.c getfile.c newfolder.c \ sendfile.c sendtr.c pathutils.c pathutils.h \ util.c util.h common.h mtp_detect_SOURCES=detect.c util.c util.h common.h mtp_tracks_SOURCES=tracks.c util.c util.h common.h mtp_files_SOURCES=files.c util.c util.h common.h mtp_folders_SOURCES=folders.c util.c util.h common.h mtp_trexist_SOURCES=trexist.c util.c util.h common.h mtp_playlists_SOURCES=playlists.c util.c util.h common.h mtp_getplaylist_SOURCES=getplaylist.c util.c util.h common.h mtp_newplaylist_SOURCES=newplaylist.c util.c util.h common.h mtp_format_SOURCES=format.c util.c util.h common.h mtp_albumart_SOURCES=albumart.c util.c util.h common.h mtp_albums_SOURCES=albums.c util.c util.h common.h mtp_emptyfolders_SOURCES=emptyfolders.c util.c util.h common.h mtp_thumb_SOURCES=thumb.c util.c util.h common.h mtp_reset_SOURCES=reset.c util.c util.h common.h mtp_filetree_SOURCES=filetree.c util.c util.h common.h AM_CPPFLAGS=-I$(top_builddir)/src LDADD=../src/libmtp.la EXTRA_DIST=evolution-sync.sh install-exec-hook: ln -f -s mtp-connect$(EXEEXT) $(DESTDIR)$(bindir)/mtp-delfile$(EXEEXT) ln -f -s mtp-connect$(EXEEXT) $(DESTDIR)$(bindir)/mtp-getfile$(EXEEXT) ln -f -s mtp-connect$(EXEEXT) $(DESTDIR)$(bindir)/mtp-newfolder$(EXEEXT) ln -f -s mtp-connect$(EXEEXT) $(DESTDIR)$(bindir)/mtp-sendfile$(EXEEXT) ln -f -s mtp-connect$(EXEEXT) $(DESTDIR)$(bindir)/mtp-sendtr$(EXEEXT) libmtp-1.1.6-20-g1b9f164/examples/emptyfolders.c0000664000175000017500000000605512205614637021417 0ustar glowwormglowworm/** * \file emptyfolders.c * Example program that prunes empty folders. * * Copyright (C) 2006 Andy Kelk * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common.h" #include static void prune_empty_folders(LIBMTP_mtpdevice_t *device, LIBMTP_file_t *files, LIBMTP_folder_t *folderlist, int do_delete) { if(folderlist==NULL) return; if(folderlist->child == NULL) { // this *might* be empty // therefore, check every file for this parent_id int found = 0; LIBMTP_file_t *file; file = files; while (file != NULL) { if(file->parent_id == folderlist->folder_id) { // folder has a child found = 1; break; } file = file->next; } if(found == 0) { // no files claim this as a parent printf("empty folder %u (%s)\n",folderlist->folder_id,folderlist->name); if(do_delete) { if (LIBMTP_Delete_Object(device,folderlist->folder_id) != 0) { printf("Couldn't delete folder %u\n",folderlist->folder_id); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); } } } } prune_empty_folders(device,files,folderlist->child,do_delete); // recurse down prune_empty_folders(device,files,folderlist->sibling,do_delete); // recurse along } int main (int argc, char **argv) { // check if we're doing a dummy run int do_delete = 0; int opt; fprintf(stdout, "libmtp version: " LIBMTP_VERSION_STRING "\n\n"); while ( (opt = getopt(argc, argv, "d")) != -1 ) { switch (opt) { case 'd': do_delete = 1; break; default: break; } } if(do_delete == 0) { printf("This is a dummy run. No folders will be deleted.\n"); printf("To delete folders, use the '-d' option.\n"); } LIBMTP_mtpdevice_t *device; LIBMTP_folder_t *folders; LIBMTP_file_t *files; LIBMTP_Init(); device = LIBMTP_Get_First_Device(); if (device == NULL) { printf("No devices.\n"); exit (0); } // Get file listing. files = LIBMTP_Get_Filelisting_With_Callback(device,NULL,NULL); // Get folder listing. folders = LIBMTP_Get_Folder_List(device); if(folders == NULL) { printf("No folders found\n"); } else { prune_empty_folders(device,files,folders,do_delete); } LIBMTP_destroy_folder_t(folders); LIBMTP_destroy_file_t(files); LIBMTP_Release_Device(device); printf("OK.\n"); exit (0); } libmtp-1.1.6-20-g1b9f164/examples/trexist.c0000664000175000017500000000342712205614637020404 0ustar glowwormglowworm/** * \file trexist.c * Example program to check if a certain track exists on the device. * * Copyright (C) 2006 The libmtp development team. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common.h" #include #include static void usage (void) { fprintf(stderr, "trexist \n"); } int main (int argc, char **argv) { LIBMTP_mtpdevice_t *device; uint32_t id; char *endptr; fprintf(stdout, "libmtp version: " LIBMTP_VERSION_STRING "\n\n"); // We need track ID if ( argc != 2 ) { usage(); return 1; } // Sanity check song ID id = strtoul(argv[1], &endptr, 10); if ( *endptr != 0 ) { fprintf(stderr, "illegal value %s\n", argv[1]); return 1; } else if ( ! id ) { fprintf(stderr, "bad song id %u\n", id); return 1; } LIBMTP_Init(); device = LIBMTP_Get_First_Device(); if (device == NULL) { printf("No devices. Connect/replug device and try again.\n"); exit (0); } printf("%s\n", LIBMTP_Track_Exists(device, id) ? "Yes" : "No"); LIBMTP_Release_Device(device); printf("OK.\n"); exit (0); } libmtp-1.1.6-20-g1b9f164/examples/sendfile.c0000664000175000017500000000525312205614637020472 0ustar glowwormglowworm/** * \file sendfile.c * Example program to send an arbitrary file to a device. * * Copyright (C) 2005-2010 Linus Walleij * Copyright (C) 2006 Chris A. Debenham * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "config.h" #include #include #include #include #include #include #include "common.h" #include "libmtp.h" #include "pathutils.h" #include "util.h" #include "connect.h" extern LIBMTP_folder_t *folders; extern LIBMTP_file_t *files; extern LIBMTP_mtpdevice_t *device; void sendfile_usage(void) { fprintf(stderr, "usage: sendfile \n"); } int sendfile_function(char * from_path, char *to_path) { printf("Sending %s to %s\n",from_path,to_path); char *filename; uint64_t filesize; struct stat sb; LIBMTP_file_t *genfile; int ret; uint32_t parent_id = 0; if ( stat(from_path, &sb) == -1 ) { fprintf(stderr, "%s: ", from_path); perror("stat"); return 1; } filesize = sb.st_size; filename = basename(from_path); parent_id = parse_path (to_path,files,folders); if (parent_id == -1) { printf("Parent folder could not be found, skipping\n"); return 0; } genfile = LIBMTP_new_file_t(); genfile->filesize = filesize; genfile->filename = strdup(filename); genfile->filetype = find_filetype (filename); genfile->parent_id = parent_id; genfile->storage_id = 0; printf("Sending file...\n"); ret = LIBMTP_Send_File_From_File(device, from_path, genfile, progress, NULL); printf("\n"); if (ret != 0) { printf("Error sending file.\n"); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); ret = 1; } else { printf("New file ID: %d\n", genfile->item_id); } LIBMTP_destroy_file_t(genfile); return ret; } int sendfile_command (int argc, char **argv) { if (argc < 3) { sendfile_usage(); return 0; } checklang(); return sendfile_function(argv[1],argv[2]); } libmtp-1.1.6-20-g1b9f164/examples/evolution-sync.sh0000775000175000017500000000616212205614637022072 0ustar glowwormglowworm#!/bin/bash # Example evolution synchronization script by Nicolas Tetreault, # modified by Linus Walleij. # Define target files SYNC_HOME=$HOME/MTP_device_sync # Define tool locations SENDFILE=`which mtp-sendfile` # SENDFILE="$HOME/comp-apps/bin/sendfile" #EADDEXP=`which evolution-addressbook-export` # This is the location in Fedora Core 5: EADDEXP="/usr/libexec/evolution/2.6/evolution-addressbook-export" # You need to change the name of the files # that contains the calendar and contacts on your device. # You can find out by starting Gnomad2, choose the data transfer # tab, sort by size (it should be small files, extension .ics and .vcf) # On my Zen Microphoto, the calendar and contacts files are called # 6651416 with the ics and vcf extensions, respectively. CALENDAR_FILE="6651416.ics" CONTACTS_FILE="6651416.vcf" # The evolution address book. To list your addressbooks, type: # evolution-addressbook-export -l # the output for me: # "file:///home/nt271/.evolution/addressbook/local/system # ","Personal",26 # "file:///home/nt271/.evolution/addressbook/local/1158600180.5386.0@sierra" # ,"MicroPhoto",24 # I only want the Microphoto addressbook and the output will be # $SYNC_HOME/contacts/Evolution_contacts.vcf EVOLUTION_CONTACTS="file:///home/linus/.evolution/addressbook/local/system" # Check for sync dir, create it if needed if test -d $SYNC_HOME ; then echo "$SYNC_HOME exists, OK." else echo "$SYNC_HOME must first be created..." mkdir $SYNC_HOME # This is a working dir for contact merging, you can put # in some extra .vcf files here as well if you like. mkdir $SYNC_HOME/contacts # Here you can place some extra calendars to be sync:ed, you # can put in some extra .ics files of any kind here. mkdir $SYNC_HOME/calendars fi # Check for prerequisites if test -f $EADDEXP ; then echo "evolution-addressbook-export present in $EADDEXP, OK." else echo "Cannot locate evolution-addressbook-export!!" exit 0 fi # Next line merges all of your tasklist, your personal calendar, # and then any saved to disk calendar you have placed in # $SYNC_HOME/calendars cat $HOME/.evolution/tasks/local/system/tasks.ics \ $HOME/.evolution/calendar/local/system/calendar.ics \ $SYNC_HOME/calendars/*.ics > $SYNC_HOME/$CALENDAR_FILE # Use evolution-addressbook-export (installed with Evolution) to # export your contacts to vcard. $EADDEXP --format=vcard \ --output=$SYNC_HOME/contacts/Evolution_contacts.vcf \ $EVOLUTION_CONTACTS # Repeat for each addressbook you want to upload. # The next command will then merge all the contact lists cat $SYNC_HOME/contacts/*.vcf > $SYNC_HOME/$CONTACTS_FILE # The calendar and contacts files now need to be converted from unix # to DOS linefeeds (CR+LF instead of just LF) unix2dos $SYNC_HOME/$CALENDAR_FILE $SYNC_HOME/$CONTACTS_FILE # You can now upload the ics and vcf files to you My Organizer folder # on your device. Change the path to your sendfile command. # Sending the vcf file is only supported in CVS version at this time $SENDFILE -f "My Organizer" -t ics $SYNC_HOME/$CALENDAR_FILE $SENDFILE -f "My Organizer" -t vcf $SYNC_HOME/$CONTACTS_FILE libmtp-1.1.6-20-g1b9f164/examples/files.c0000664000175000017500000000727512205614637020011 0ustar glowwormglowworm/** * \file files.c * Example program that lists all files on a device. * * Copyright (C) 2005-2012 Linus Walleij * Copyright (C) 2007 Ted Bullock * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common.h" #include static void dump_fileinfo(LIBMTP_file_t *file) { printf("File ID: %u\n", file->item_id); if (file->filename != NULL) printf(" Filename: %s\n", file->filename); // This is sort of special... if (file->filesize == (uint32_t) -1) { printf(" None. (abstract file, size = -1)\n"); } else { #ifdef __WIN32__ printf(" File size %llu (0x%016I64X) bytes\n", file->filesize, file->filesize); #else printf(" File size %llu (0x%016llX) bytes\n", (long long unsigned int) file->filesize, (long long unsigned int) file->filesize); #endif } printf(" Parent ID: %u\n", file->parent_id); printf(" Storage ID: 0x%08X\n", file->storage_id); printf(" Filetype: %s\n", LIBMTP_Get_Filetype_Description(file->filetype)); } int main (int argc, char **argv) { LIBMTP_mtpdevice_t *device_list, *device; LIBMTP_file_t *files; fprintf(stdout, "libmtp version: " LIBMTP_VERSION_STRING "\n\n"); LIBMTP_Init(); switch(LIBMTP_Get_Connected_Devices(&device_list)) { case LIBMTP_ERROR_NO_DEVICE_ATTACHED: fprintf(stdout, "mtp-files: No Devices have been found\n"); return 0; case LIBMTP_ERROR_CONNECTING: fprintf(stderr, "mtp-files: There has been an error connecting. Exit\n"); return 1; case LIBMTP_ERROR_MEMORY_ALLOCATION: fprintf(stderr, "mtp-files: Memory Allocation Error. Exit\n"); return 1; /* Unknown general errors - This should never execute */ case LIBMTP_ERROR_GENERAL: default: fprintf(stderr, "mtp-files: Unknown error, please report " "this to the libmtp developers\n"); return 1; /* Successfully connected at least one device, so continue */ case LIBMTP_ERROR_NONE: fprintf(stdout, "mtp-files: Successfully connected\n"); fflush(stdout); } /* iterate through connected MTP devices */ for(device = device_list; device != NULL; device = device->next) { char *friendlyname; /* Echo the friendly name so we know which device we are working with */ friendlyname = LIBMTP_Get_Friendlyname(device); if (friendlyname == NULL) { printf("Listing File Information on Device with name: (NULL)\n"); } else { printf("Listing File Information on Device with name: %s\n", friendlyname); free(friendlyname); } /* Get track listing. */ files = LIBMTP_Get_Filelisting_With_Callback(device, NULL, NULL); if (files == NULL) { printf("No files.\n"); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); } else { LIBMTP_file_t *file, *tmp; file = files; while (file != NULL) { dump_fileinfo(file); tmp = file; file = file->next; LIBMTP_destroy_file_t(tmp); } } } LIBMTP_Release_Device_List(device_list); printf("OK.\n"); exit (0); } libmtp-1.1.6-20-g1b9f164/examples/reset.c0000664000175000017500000000426612205614637020026 0ustar glowwormglowworm/** * \file reset.c * Example program that resets the device. * * Copyright (C) 2007 Linus Walleij * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common.h" /** * Returns 0 if OK (yes), 1 if not OK (no) */ static int prompt() { char buff[2]; while (1) { fprintf(stdout, "> "); if ( fgets(buff, sizeof(buff), stdin) == NULL ) { if (ferror(stdin)) { fprintf(stderr, "File error on stdin\n"); } else { fprintf(stderr, "EOF on stdin\n"); } return 1; } if (buff[0] == 'y') { return 0; } else if (buff[0] == 'n') { return 1; } } } int main (int argc, char **argv) { LIBMTP_mtpdevice_t *device; int ret; fprintf(stdout, "libmtp version: " LIBMTP_VERSION_STRING "\n\n"); LIBMTP_Init(); device = LIBMTP_Get_First_Device(); if (device == NULL) { printf("No devices.\n"); return 0; } printf("I will now reset your device. This means that\n"); printf("the device may go inactive immediately and may report errors.\n"); printf("Continue? (y/n)\n"); if (prompt() == 0) { ret = LIBMTP_Reset_Device(device); } else { printf("Aborted.\n"); ret = 0; } if ( ret != 0 ) { printf("Failed to reset device.\n"); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); LIBMTP_Release_Device(device); return 1; } // It is not possible to release the device after successful reset! // LIBMTP_Release_Device(device); printf("OK.\n"); return 0; } libmtp-1.1.6-20-g1b9f164/examples/delfile.c0000664000175000017500000000544212205614637020305 0ustar glowwormglowworm/** * \file delfile.c * Example program to delete a file off the device. * * Copyright (C) 2005-2008 Linus Walleij * Copyright (C) 2006 Chris A. Debenham * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include #include #include "common.h" #include "string.h" #include "pathutils.h" #include "connect.h" extern LIBMTP_mtpdevice_t *device; extern LIBMTP_folder_t *folders; extern LIBMTP_file_t *files; void delfile_usage(void) { printf("Usage: delfile [-n] | -f \n"); } int delfile_function(char * path) { uint32_t id = parse_path (path,files,folders); if (id > 0) { printf("Deleting %s which has item_id:%d\n",path,id); int ret = 1; ret = LIBMTP_Delete_Object(device, id); if (ret != 0) { LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); printf("Failed to remove file\n"); return 1; } } return 0; } int delfile_command(int argc, char **argv) { int FILENAME = 1; int ITEMID = 2; int field_type = 0; int i; int ret = 0; if ( argc > 2 ) { if (strncmp(argv[1],"-f",2) == 0) { field_type = FILENAME; strcpy(argv[1],""); } else if (strncmp(argv[1],"-n",2) == 0) { field_type = ITEMID; strcpy(argv[1],"0"); } else { delfile_usage(); return 0; } } else { delfile_usage(); return 0; } for (i=1;i 0) { id = parse_path (argv[i],files,folders); } else { id = 0; } } if (id > 0 ) { printf("Deleting %s\n",argv[i]); ret = LIBMTP_Delete_Object(device, id); } if ( ret != 0 ) { printf("Failed to delete file:%s\n",argv[i]); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); ret = 1; } } return ret; } libmtp-1.1.6-20-g1b9f164/examples/newfolder.c0000664000175000017500000000425412205614637020666 0ustar glowwormglowworm/** * \file newfolder.c * Example program to create a folder on the device. * * Copyright (C) 2006-2009 Linus Walleij * Copyright (C) 2006 Chris A. Debenham * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include #include #include "common.h" #include "pathutils.h" #include "connect.h" extern LIBMTP_folder_t *folders; extern LIBMTP_file_t *files; extern LIBMTP_mtpdevice_t *device; int newfolder_command (int argc, char **argv) { uint32_t newid; if(argc != 4) { printf("Usage: newfolder name \n"); printf(" parent = parent folder or 0 to create the new folder in the root dir\n"); printf(" storage = storage id or 0 to create the new folder on the primary storage\n"); return 0; } newid = LIBMTP_Create_Folder(device, argv[1], atol(argv[2]), atol(argv[3])); if (newid == 0) { printf("Folder creation failed.\n"); return 1; } else { printf("New folder created with ID: %d\n", newid); } return 0; } int newfolder_function(char * path) { printf("Creating new folder %s\n",path); char * parent = dirname(path); char * folder = basename(path); int id = parse_path (parent,files,folders); int newid = LIBMTP_Create_Folder(device, folder, id, 0); if (newid == 0) { printf("Folder creation failed.\n"); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); return 1; } else { printf("New folder created with ID: %d\n", newid); } return 0; } libmtp-1.1.6-20-g1b9f164/examples/albums.c0000664000175000017500000000661012205614637020162 0ustar glowwormglowworm/** * \file albums.c * Example program that lists the albums on the device. * * Copyright (C) 2006 Chris A. Debenham * Copyright (C) 2007 Ted Bullock * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common.h" #include static void dump_albuminfo(LIBMTP_album_t *album) { printf("Album ID: %d\n",album->album_id); printf(" Parent ID: %d\n",album->parent_id); printf(" Name: %s\n",album->name); printf(" Artist: %s\n", album->artist); printf(" Composer: %s\n", album->composer); printf(" Genre: %s\n", album->genre); printf(" Tracks: %d\n\n",album->no_tracks); } int main (int argc, char *argv[]) { LIBMTP_mtpdevice_t *device_list, *device; int opt; extern int optind; extern char *optarg; while ((opt = getopt(argc, argv, "d")) != -1 ) { switch (opt) { case 'd': LIBMTP_Set_Debug(LIBMTP_DEBUG_PTP | LIBMTP_DEBUG_DATA); break; } } argc -= optind; argv += optind; LIBMTP_Init(); fprintf(stdout, "libmtp version: " LIBMTP_VERSION_STRING "\n\n"); switch(LIBMTP_Get_Connected_Devices(&device_list)) { case LIBMTP_ERROR_NO_DEVICE_ATTACHED: fprintf(stdout, "mtp-albums: No Devices have been found\n"); return 0; case LIBMTP_ERROR_CONNECTING: fprintf(stderr, "mtp-albums: There has been an error connecting. Exit\n"); return 1; case LIBMTP_ERROR_MEMORY_ALLOCATION: fprintf(stderr, "mtp-albums: Memory Allocation Error. Exit\n"); return 1; /* Unknown general errors - This should never execute */ case LIBMTP_ERROR_GENERAL: default: fprintf(stderr, "mtp-albums: Unknown error, please report " "this to the libmtp developers\n"); return 1; /* Successfully connected at least one device, so continue */ case LIBMTP_ERROR_NONE: fprintf(stdout, "mtp-albums: Successfully connected\n"); fflush(stdout); } /* iterate through connected MTP devices */ for(device = device_list; device != NULL; device = device->next) { char *friendlyname; LIBMTP_album_t *album_list, *album, *tmp; /* Echo the friendly name so we know which device we are working with */ friendlyname = LIBMTP_Get_Friendlyname(device); if (friendlyname == NULL) { printf("Retrieving Albums on Device with name: (NULL)\n"); } else { printf("Retrieving Albums on Device with name: %s\n", friendlyname); free(friendlyname); } album_list = LIBMTP_Get_Album_List(device); album = album_list; while(album != NULL) { dump_albuminfo(album); tmp = album; album = album->next; LIBMTP_destroy_album_t(tmp); } } LIBMTP_Release_Device_List(device_list); printf("OK.\n"); return 0; } libmtp-1.1.6-20-g1b9f164/examples/pathutils.c0000664000175000017500000001621412205614637020715 0ustar glowwormglowworm/** * \file pathutils.c * * Copyright (C) 2005-2008 Linus Walleij * Copyright (C) 2006 Chris A. Debenham * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common.h" #include "pathutils.h" #include #include #include #include /* Find the folder_id of a given path * Runs by walking through folders structure */ static uint32_t lookup_folder_id (LIBMTP_folder_t * folder, char * path, char * parent) { char * current; uint32_t ret = (uint32_t) -1; if (strcmp(path,"/")==0) return 0; if (folder == NULL) { return ret; } current = malloc (strlen(parent) + strlen(folder->name) + 2); sprintf(current,"%s/%s",parent,folder->name); if (strcasecmp (path, current) == 0) { free (current); return folder->folder_id; } if (strncasecmp (path, current, strlen (current)) == 0) { ret = lookup_folder_id (folder->child, path, current); } free (current); if (ret != (uint32_t) (-1)) { return ret; } ret = lookup_folder_id (folder->sibling, path, parent); return ret; } /* Parses a string to find item_id */ int parse_path (char * path, LIBMTP_file_t * files, LIBMTP_folder_t * folders) { char *rest; uint32_t item_id; // Check if path is an item_id if (*path != '/') { item_id = strtoul(path, &rest, 0); // really should check contents of "rest" here... /* if not number, assume a file name */ if (item_id == 0) { LIBMTP_file_t * file = files; /* search for matching name */ while (file != NULL) { if (strcasecmp (file->filename, path) == 0) { return file->item_id; } file = file->next; } } return item_id; } // Check if path is a folder item_id = lookup_folder_id(folders,path,""); if (item_id == (uint32_t) -1) { char * dirc = strdup(path); char * basec = strdup(path); char * parent = dirname(dirc); char * filename = basename(basec); uint32_t parent_id = lookup_folder_id(folders,parent,""); LIBMTP_file_t * file; file = files; while (file != NULL) { if (file->parent_id == parent_id) { if (strcasecmp (file->filename, filename) == 0) { free(dirc); free(basec); return file->item_id; } } file = file->next; } free(dirc); free(basec); } else { return item_id; } return -1; } int progress (const uint64_t sent, const uint64_t total, void const * const data) { int percent = (sent*100)/total; #ifdef __WIN32__ printf("Progress: %I64u of %I64u (%d%%)\r", sent, total, percent); #else printf("Progress: %llu of %llu (%d%%)\r", sent, total, percent); #endif fflush(stdout); return 0; } /* Find the file type based on extension */ LIBMTP_filetype_t find_filetype (const char * filename) { char *ptype; LIBMTP_filetype_t filetype; #ifdef __WIN32__ ptype = strrchr(filename, '.'); #else ptype = rindex(filename,'.'); #endif // This accounts for the case with a filename without any "." (period). if (!ptype) { ptype = ""; } else { ++ptype; } /* This need to be kept constantly updated as new file types arrive. */ if (!strcasecmp (ptype, "wav")) { filetype = LIBMTP_FILETYPE_WAV; } else if (!strcasecmp (ptype, "mp3")) { filetype = LIBMTP_FILETYPE_MP3; } else if (!strcasecmp (ptype, "wma")) { filetype = LIBMTP_FILETYPE_WMA; } else if (!strcasecmp (ptype, "ogg")) { filetype = LIBMTP_FILETYPE_OGG; } else if (!strcasecmp (ptype, "mp4")) { filetype = LIBMTP_FILETYPE_MP4; } else if (!strcasecmp (ptype, "wmv")) { filetype = LIBMTP_FILETYPE_WMV; } else if (!strcasecmp (ptype, "avi")) { filetype = LIBMTP_FILETYPE_AVI; } else if (!strcasecmp (ptype, "mpeg") || !strcasecmp (ptype, "mpg")) { filetype = LIBMTP_FILETYPE_MPEG; } else if (!strcasecmp (ptype, "asf")) { filetype = LIBMTP_FILETYPE_ASF; } else if (!strcasecmp (ptype, "qt") || !strcasecmp (ptype, "mov")) { filetype = LIBMTP_FILETYPE_QT; } else if (!strcasecmp (ptype, "wma")) { filetype = LIBMTP_FILETYPE_WMA; } else if (!strcasecmp (ptype, "jpg") || !strcasecmp (ptype, "jpeg")) { filetype = LIBMTP_FILETYPE_JPEG; } else if (!strcasecmp (ptype, "jfif")) { filetype = LIBMTP_FILETYPE_JFIF; } else if (!strcasecmp (ptype, "tif") || !strcasecmp (ptype, "tiff")) { filetype = LIBMTP_FILETYPE_TIFF; } else if (!strcasecmp (ptype, "bmp")) { filetype = LIBMTP_FILETYPE_BMP; } else if (!strcasecmp (ptype, "gif")) { filetype = LIBMTP_FILETYPE_GIF; } else if (!strcasecmp (ptype, "pic") || !strcasecmp (ptype, "pict")) { filetype = LIBMTP_FILETYPE_PICT; } else if (!strcasecmp (ptype, "png")) { filetype = LIBMTP_FILETYPE_PNG; } else if (!strcasecmp (ptype, "wmf")) { filetype = LIBMTP_FILETYPE_WINDOWSIMAGEFORMAT; } else if (!strcasecmp (ptype, "ics")) { filetype = LIBMTP_FILETYPE_VCALENDAR2; } else if (!strcasecmp (ptype, "exe") || !strcasecmp (ptype, "com") || !strcasecmp (ptype, "bat") || !strcasecmp (ptype, "dll") || !strcasecmp (ptype, "sys")) { filetype = LIBMTP_FILETYPE_WINEXEC; } else if (!strcasecmp (ptype, "aac")) { filetype = LIBMTP_FILETYPE_AAC; } else if (!strcasecmp (ptype, "mp2")) { filetype = LIBMTP_FILETYPE_MP2; } else if (!strcasecmp (ptype, "flac")) { filetype = LIBMTP_FILETYPE_FLAC; } else if (!strcasecmp (ptype, "m4a")) { filetype = LIBMTP_FILETYPE_M4A; } else if (!strcasecmp (ptype, "doc")) { filetype = LIBMTP_FILETYPE_DOC; } else if (!strcasecmp (ptype, "xml")) { filetype = LIBMTP_FILETYPE_XML; } else if (!strcasecmp (ptype, "xls")) { filetype = LIBMTP_FILETYPE_XLS; } else if (!strcasecmp (ptype, "ppt")) { filetype = LIBMTP_FILETYPE_PPT; } else if (!strcasecmp (ptype, "mht")) { filetype = LIBMTP_FILETYPE_MHT; } else if (!strcasecmp (ptype, "jp2")) { filetype = LIBMTP_FILETYPE_JP2; } else if (!strcasecmp (ptype, "jpx")) { filetype = LIBMTP_FILETYPE_JPX; } else if (!strcasecmp (ptype, "bin")) { filetype = LIBMTP_FILETYPE_FIRMWARE; } else if (!strcasecmp (ptype, "vcf")) { filetype = LIBMTP_FILETYPE_VCARD3; } else { /* Tagging as unknown file type */ filetype = LIBMTP_FILETYPE_UNKNOWN; } printf("type: %s, %d\n", ptype, filetype); return filetype; } /* Function that compensate for missing libgen.h on Windows */ #ifndef HAVE_LIBGEN_H static char *basename(char *in) { char *p; if (in == NULL) return NULL; p = in + strlen(in) - 1; while (*p != '\\' && *p != '/' && *p != ':') { p--; } return ++p; } #endif libmtp-1.1.6-20-g1b9f164/examples/util.h0000664000175000017500000000173312205614637017662 0ustar glowwormglowworm/** * \file util.h * Header for a set of common utility functions found * in all samples. * * Copyright (C) 2008 Linus Walleij * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef LIBMTP_EXAMPLES_UTIL_H #define LIBMTP_EXAMPLES_UTIL_H void checklang(void); #endif libmtp-1.1.6-20-g1b9f164/examples/thumb.c0000664000175000017500000000615512205614637020022 0ustar glowwormglowworm/** * \file thumb.c * Example program to send and associate album art to an entity * on a device. * * Copyright (C) 2006 Robert Reardon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "config.h" #include "common.h" #include "string.h" #include #include #include #include #include #include #ifdef HAVE_SYS_UIO_H #include #endif #include static void usage(void) { printf("Usage: thumb -i \n"); exit(0); } int main (int argc, char **argv) { int opt; extern int optind; extern char *optarg; LIBMTP_mtpdevice_t *device = NULL; int fd; uint32_t id = 0; uint64_t filesize; uint8_t *imagedata = NULL; char *path = NULL; char *rest; struct stat statbuff; int ret; fprintf(stdout, "libmtp version: " LIBMTP_VERSION_STRING "\n\n"); while ( (opt = getopt(argc, argv, "hi:")) != -1 ) { switch (opt) { case 'h': usage(); case 'i': id = strtoul(optarg, &rest, 0); break; default: usage(); } } argc -= optind; argv += optind; if ( argc != 1 ) { printf("You need to pass a filename.\n"); usage(); } path = argv[0]; if ( stat(path, &statbuff) == -1 ) { fprintf(stderr, "%s: ", path); perror("stat"); exit(1); } filesize = (uint64_t) statbuff.st_size; imagedata = malloc(filesize * sizeof(uint16_t)); #ifdef __WIN32__ if ( (fd = open(path, O_RDONLY|O_BINARY) == -1) ) { #else if ( (fd = open(path, O_RDONLY)) == -1) { #endif printf("Couldn't open image file %s (%s)\n",path,strerror(errno)); return 1; } else { read(fd, imagedata, filesize); close(fd); } LIBMTP_Init(); device = LIBMTP_Get_First_Device(); if (device == NULL) { printf("No devices.\n"); return 0; } LIBMTP_filesampledata_t *thumb = LIBMTP_new_filesampledata_t(); int i; thumb->data = malloc(sizeof(uint16_t) * filesize); for (i = 0; i < filesize; i++) { thumb->data[i] = imagedata[i]; } thumb->size = filesize; thumb->filetype = LIBMTP_FILETYPE_JPEG; ret = LIBMTP_Send_Representative_Sample(device,id,thumb); if (ret != 0) { printf("Couldn't send thumbnail\n"); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); } free(imagedata); LIBMTP_destroy_filesampledata_t(thumb); LIBMTP_Release_Device(device); printf("OK.\n"); return 0; } libmtp-1.1.6-20-g1b9f164/examples/getplaylist.c0000664000175000017500000000474312205614637021245 0ustar glowwormglowworm/** * \file getplaylist.c * Example program that lists the abstract playlists on the device. * * Copyright (C) 2005-2007 Linus Walleij * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common.h" #include #include static uint32_t dump_playlist(LIBMTP_mtpdevice_t *device, LIBMTP_playlist_t *pl) { uint32_t i; printf("Number of items: %u\n", pl->no_tracks); if(pl->no_tracks > 0) { for(i=0;ino_tracks;i++) { LIBMTP_track_t *track; track = LIBMTP_Get_Trackmetadata(device, pl->tracks[i]); if (track != NULL) { printf(" %u: %s - %s\n", pl->tracks[i], track->artist, track->title); LIBMTP_destroy_track_t(track); } else { printf(" %u: INVALID TRACK REFERENCE!\n", pl->tracks[i]); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); } } } return 0; } int main (int argc, char **argv) { LIBMTP_mtpdevice_t *device; LIBMTP_playlist_t *playlist; uint32_t id; char *endptr; fprintf(stdout, "libmtp version: " LIBMTP_VERSION_STRING "\n\n"); // We need file ID if ( argc != 2 ) { fprintf(stderr, "Just a playlist ID is required\n"); return 1; } // Sanity check playlist ID id = strtoul(argv[1], &endptr, 10); if ( *endptr != 0 ) { fprintf(stderr, "illegal value %s\n", argv[1]); return 1; } else if ( ! id ) { fprintf(stderr, "bad playlist id %u\n", id); return 1; } LIBMTP_Init(); device = LIBMTP_Get_First_Device(); if (device == NULL) { printf("No devices. Connect/replug device and try again.\n"); exit (0); } playlist = LIBMTP_Get_Playlist(device,id); if (playlist != NULL) { dump_playlist(device,playlist); } LIBMTP_destroy_playlist_t(playlist); LIBMTP_Release_Device(device); printf("OK.\n"); exit (0); } libmtp-1.1.6-20-g1b9f164/examples/sendtr.c0000664000175000017500000003072212205614637020177 0ustar glowwormglowworm/** * \file sendtr.c * Example program to send a music track to a device. * This program is derived from the exact equivalent in libnjb. * based on Enrique Jorreto Ledesma's work on the original program by * Shaun Jackman and Linus Walleij. * * Copyright (C) 2003-2010 Linus Walleij * Copyright (C) 2003-2005 Shaun Jackman * Copyright (C) 2003-2005 Enrique Jorrete Ledesma * Copyright (C) 2006 Chris A. Debenham * Copyright (C) 2008 Nicolas Pennequin * Copyright (C) 2008 Joseph Nahmias * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include #include #include #include #include #include #include #ifdef HAVE_LANGINFO_H #include #endif #include "config.h" #include "common.h" #include "util.h" #include "connect.h" #include "libmtp.h" #include "pathutils.h" extern LIBMTP_folder_t *folders; extern LIBMTP_file_t *files; extern LIBMTP_mtpdevice_t *device; void sendtrack_usage (void) { fprintf(stderr, "usage: sendtr [ -D debuglvl ] [ -q ]\n"); fprintf(stderr, "-t -a <artist> -A <Album artist> -w <writer or composer>\n"); fprintf(stderr, " -l <album> -c <codec> -g <genre> -n <track number> -y <year>\n"); fprintf(stderr, " -d <duration in seconds> -s <storage_id> <local path> <remote path>\n"); fprintf(stderr, "(-q means the program will not ask for missing information.)\n"); } static char *prompt (const char *prompt, char *buffer, size_t bufsz, int required) { char *cp, *bp; while (1) { fprintf(stdout, "%s> ", prompt); if ( fgets(buffer, bufsz, stdin) == NULL ) { if (ferror(stdin)) { perror("fgets"); } else { fprintf(stderr, "EOF on stdin\n"); } return NULL; } cp = strrchr(buffer, '\n'); if ( cp != NULL ) *cp = '\0'; bp = buffer; while ( bp != cp ) { if ( *bp != ' ' && *bp != '\t' ) return bp; bp++; } if (! required) return bp; } } static int add_track_to_album(LIBMTP_album_t *albuminfo, LIBMTP_track_t *trackmeta) { LIBMTP_album_t *album; LIBMTP_album_t *album_orig; LIBMTP_album_t *found_album = NULL; int ret; /* Look for the album */ album = LIBMTP_Get_Album_List(device); album_orig = album; while(album != NULL) { if ((album->name != NULL && album->artist != NULL && !strcmp(album->name, albuminfo->name) && !strcmp(album->artist, albuminfo->artist)) || (album->name != NULL && album->composer != NULL && !strcmp(album->name, albuminfo->name) && !strcmp(album->composer, albuminfo->composer))) { /* Disconnect this album for later use */ found_album = album; album = album->next; found_album->next = NULL; } else { album = album->next; } } if (found_album == NULL) { printf("Could not find Album. Retrying with only Album name\n"); album = album_orig; while(album != NULL) { if ((album->name != NULL) && !strcmp(album->name, albuminfo->name) ){ /* Disconnect this album for later use */ found_album = album; album = album->next; found_album->next = NULL; } else { album = album->next; } } } if (found_album != NULL) { uint32_t *tracks; tracks = (uint32_t *)malloc((found_album->no_tracks+1) * sizeof(uint32_t)); printf("Album \"%s\" found: updating...\n", found_album->name); if (!tracks) { printf("failed malloc in add_track_to_album()\n"); return 1; } found_album->no_tracks++; if (found_album->tracks != NULL) { memcpy(tracks, found_album->tracks, found_album->no_tracks * sizeof(uint32_t)); free(found_album->tracks); } tracks[found_album->no_tracks-1] = trackmeta->item_id; found_album->tracks = tracks; ret = LIBMTP_Update_Album(device, found_album); } else { uint32_t *trackid; trackid = (uint32_t *)malloc(sizeof(uint32_t)); *trackid = trackmeta->item_id; albuminfo->tracks = trackid; albuminfo->no_tracks = 1; albuminfo->storage_id = trackmeta->storage_id; printf("Album doesn't exist: creating...\n"); ret = LIBMTP_Create_New_Album(device, albuminfo); /* albuminfo will be destroyed later by caller */ } /* Delete the earlier retrieved Album list */ album=album_orig; while(album!=NULL){ LIBMTP_album_t *tmp; tmp = album; album = album->next; LIBMTP_destroy_album_t(tmp); } if (ret != 0) { printf("Error creating or updating album.\n"); printf("(This could be due to that your device does not support albums.)\n"); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); } else { printf("success!\n"); } return ret; } int sendtrack_function(char * from_path, char * to_path, char *partist, char *palbumartist, char *ptitle, char *pgenre, char *palbum, char *pcomposer, uint16_t tracknum, uint16_t length, uint16_t year, uint32_t storageid, uint16_t quiet) { char *filename, *parent; char artist[80], albumartist[80], title[80], genre[80], album[80], composer[80]; char num[80]; uint64_t filesize; uint32_t parent_id = 0; struct stat sb; LIBMTP_track_t *trackmeta; LIBMTP_album_t *albuminfo; int ret; printf("Sending track %s to %s\n", from_path, to_path); trackmeta = LIBMTP_new_track_t(); albuminfo = LIBMTP_new_album_t(); parent = dirname(strdup(to_path)); filename = basename(strdup(to_path)); parent_id = parse_path (parent,files,folders); if (parent_id == -1) { printf("Parent folder could not be found, skipping\n"); return 1; } if (stat(from_path, &sb) == -1) { fprintf(stderr, "%s: ", from_path); perror("stat"); return 1; } if (!S_ISREG(sb.st_mode)) return 0; filesize = sb.st_size; trackmeta->filetype = find_filetype (from_path); if (!LIBMTP_FILETYPE_IS_TRACK(trackmeta->filetype)) { printf("Not a valid track codec: \"%s\"\n", LIBMTP_Get_Filetype_Description(trackmeta->filetype)); return 1; } if ((ptitle == NULL) && (quiet == 0)) { if ( (ptitle = prompt("Title", title, 80, 0)) != NULL ) if (!strlen(ptitle)) ptitle = NULL; } if ((palbum == NULL) && (quiet == 0)) { if ( (palbum = prompt("Album", album, 80, 0)) != NULL ) if (!strlen(palbum)) palbum = NULL; } if ((palbumartist == NULL) && (quiet == 0)) { if ( (palbumartist = prompt("Album artist", albumartist, 80, 0)) != NULL ) if (!strlen(palbumartist)) palbumartist = NULL; } if ((partist == NULL) && (quiet == 0)) { if ( (partist = prompt("Artist", artist, 80, 0)) != NULL ) if (!strlen(partist)) partist = NULL; } if ((pcomposer == NULL) && (quiet == 0)) { if ( (pcomposer = prompt("Writer or Composer", composer, 80, 0)) != NULL ) if (!strlen(pcomposer)) pcomposer = NULL; } if ((pgenre == NULL) && (quiet == 0)) { if ( (pgenre = prompt("Genre", genre, 80, 0)) != NULL ) if (!strlen(pgenre)) pgenre = NULL; } if ((tracknum == 0) && (quiet == 0)) { char *pnum; if ( (pnum = prompt("Track number", num, 80, 0)) == NULL ) tracknum = 0; else tracknum = strtoul(pnum, 0, 10); } if ((year == 0) && (quiet == 0)) { char *pnum; if ( (pnum = prompt("Year", num, 80, 0)) == NULL ) year = 0; else year = strtoul(pnum, 0, 10); } if ((length == 0) && (quiet == 0)) { char *pnum; if ( (pnum = prompt("Length", num, 80, 0)) == NULL ) length = 0; else length = strtoul(pnum, 0, 10); } printf("Sending track:\n"); printf("Codec: %s\n", LIBMTP_Get_Filetype_Description(trackmeta->filetype)); if (ptitle) { printf("Title: %s\n", ptitle); trackmeta->title = strdup(ptitle); } if (palbum) { printf("Album: %s\n", palbum); trackmeta->album = strdup(palbum); albuminfo->name = strdup(palbum); } if (palbumartist) { printf("Album artist: %s\n", palbumartist); albuminfo->artist = strdup(palbumartist); } if (partist) { printf("Artist: %s\n", partist); trackmeta->artist = strdup(partist); if (palbumartist == NULL) albuminfo->artist = strdup(partist); } if (pcomposer) { printf("Writer or Composer: %s\n", pcomposer); trackmeta->composer = strdup(pcomposer); albuminfo->composer = strdup(pcomposer); } if (pgenre) { printf("Genre: %s\n", pgenre); trackmeta->genre = strdup(pgenre); albuminfo->genre = strdup(pgenre); } if (year > 0) { char tmp[80]; printf("Year: %d\n", year); snprintf(tmp, sizeof(tmp)-1, "%4d0101T0000.0", year); tmp[sizeof(tmp)-1] = '\0'; trackmeta->date = strdup(tmp); } if (tracknum > 0) { printf("Track no: %d\n", tracknum); trackmeta->tracknumber = tracknum; } if (length > 0) { printf("Length: %d\n", length); // Multiply by 1000 since this is in milliseconds trackmeta->duration = length * 1000; } // We should always have this if (filename != NULL) { trackmeta->filename = strdup(filename); } trackmeta->filesize = filesize; trackmeta->parent_id = parent_id; { int rc; char *desc = NULL; LIBMTP_devicestorage_t *pds = NULL; if (0 != (rc=LIBMTP_Get_Storage(device, LIBMTP_STORAGE_SORTBY_NOTSORTED))) { perror("LIBMTP_Get_Storage()"); exit(-1); } for (pds = device->storage; pds != NULL; pds = pds->next) { if (pds->id == storageid) { desc = strdup(pds->StorageDescription); break; } } if (NULL != desc) { printf("Storage ID: %s (%u)\n", desc, storageid); free(desc); } else printf("Storage ID: %u\n", storageid); trackmeta->storage_id = storageid; } printf("Sending track...\n"); ret = LIBMTP_Send_Track_From_File(device, from_path, trackmeta, progress, NULL); printf("\n"); if (ret != 0) { printf("Error sending track.\n"); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); ret = 1; } else { printf("New track ID: %d\n", trackmeta->item_id); } /* Add here add to album call */ if (palbum) ret = add_track_to_album(albuminfo, trackmeta); LIBMTP_destroy_album_t(albuminfo); LIBMTP_destroy_track_t(trackmeta); return ret; } int sendtrack_command (int argc, char **argv) { int opt; extern int optind; extern char *optarg; char *partist = NULL; char *palbumartist = NULL; char *pcomposer = NULL; char *ptitle = NULL; char *pgenre = NULL; char *pcodec = NULL; char *palbum = NULL; uint16_t tracknum = 0; uint16_t length = 0; uint16_t year = 0; uint16_t quiet = 0; uint32_t storageid = 0; while ( (opt = getopt(argc, argv, "qD:t:a:A:w:l:c:g:n:d:y:s:")) != -1 ) { switch (opt) { case 't': ptitle = strdup(optarg); break; case 'a': partist = strdup(optarg); break; case 'A': palbumartist = strdup(optarg); break; case 'w': pcomposer = strdup(optarg); break; case 'l': palbum = strdup(optarg); break; case 'c': pcodec = strdup(optarg); // FIXME: DSM check for MP3, WAV or WMA break; case 'g': pgenre = strdup(optarg); break; case 'n': tracknum = atoi(optarg); break; case 's': storageid = (uint32_t) strtoul(optarg, NULL, 0); break; case 'd': length = atoi(optarg); break; case 'y': year = atoi(optarg); break; case 'q': quiet = 1; break; default: sendtrack_usage(); } } argc -= optind; argv += optind; if ( argc != 2 ) { printf("You need to pass a filename and destination.\n"); sendtrack_usage(); return 0; } checklang(); printf("%s,%s,%s,%s,%s,%s,%s,%s,%d%d,%d,%u,%d\n",argv[0],argv[1],partist,palbumartist,ptitle,pgenre,palbum,pcomposer,tracknum, length, year, storageid, quiet); return sendtrack_function(argv[0],argv[1],partist,palbumartist,ptitle,pgenre,palbum,pcomposer, tracknum, length, year, storageid, quiet); } ����������������������������������������������libmtp-1.1.6-20-g1b9f164/examples/format.c����������������������������������������������������������0000664�0001750�0001750�00000004360�12205614637�020167� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/** * \file format.c * Example program that formats the device storage. * * Copyright (C) 2006-2007 Linus Walleij <triad@df.lth.se> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common.h" /** * Returns 0 if OK (yes), 1 if not OK (no) */ static int prompt() { char buff[2]; while (1) { fprintf(stdout, "> "); if ( fgets(buff, sizeof(buff), stdin) == NULL ) { if (ferror(stdin)) { fprintf(stderr, "File error on stdin\n"); } else { fprintf(stderr, "EOF on stdin\n"); } return 1; } if (buff[0] == 'y') { return 0; } else if (buff[0] == 'n') { return 1; } } } int main (int argc, char **argv) { LIBMTP_mtpdevice_t *device; int ret; fprintf(stdout, "libmtp version: " LIBMTP_VERSION_STRING "\n\n"); LIBMTP_Init(); device = LIBMTP_Get_First_Device(); if (device == NULL) { printf("No devices.\n"); return 0; } printf("I will now format your device. This means that\n"); printf("all content (and licenses) will be lost forever.\n"); printf("you will not be able to undo this operation.\n"); printf("Continue? (y/n)\n"); if (prompt() == 0) { // This will just format the first storage. ret = LIBMTP_Format_Storage(device, device->storage); } else { printf("Aborted.\n"); ret = 0; } if ( ret != 0 ) { printf("Failed to format device.\n"); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); LIBMTP_Release_Device(device); return 1; } LIBMTP_Release_Device(device); printf("OK.\n"); return 0; } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/examples/albumart.c��������������������������������������������������������0000664�0001750�0001750�00000010336�12205614637�020506� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/** * \file albumart.c * Example program to send album art. * * Copyright (C) 2006 Andy Kelk <andy@mopoke.co.uk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "config.h" #include "common.h" #include "string.h" #include <stdlib.h> #include <limits.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <sys/stat.h> #include <sys/types.h> #ifdef HAVE_SYS_UIO_H #include <sys/uio.h> #endif static void usage(void) { printf("Usage: albumart -d -i <fileid/trackid> -n <albumname> -s <storage_id> -p <parent_id> <imagefile>\n"); exit(0); } int main (int argc, char **argv) { int opt; extern int optind; extern char *optarg; LIBMTP_mtpdevice_t *device = NULL; int idcount = 0; int fd; uint32_t *ids = NULL; uint32_t *tmp = NULL; uint64_t filesize; char *imagedata = NULL; char *albumname = NULL; char *path = NULL; char *rest; struct stat statbuff; uint32_t storageid = 0; uint32_t parentid = 0; fprintf(stdout, "libmtp version: " LIBMTP_VERSION_STRING "\n\n"); while ( (opt = getopt(argc, argv, "dhn:i:s:p:")) != -1 ) { switch (opt) { case 'h': usage(); case 'd': LIBMTP_Set_Debug(LIBMTP_DEBUG_PTP | LIBMTP_DEBUG_DATA); break; case 'i': idcount++; if ((tmp = realloc(ids, sizeof(uint32_t) * (idcount))) == NULL) { printf("realloc failed\n"); return 1; } ids = tmp; ids[(idcount-1)] = strtoul(optarg, &rest, 0); break; case 'n': albumname = strdup(optarg); break; case 's': storageid = (uint32_t) strtoul(optarg, NULL, 0); break; case 'p': parentid = (uint32_t) strtoul(optarg, NULL, 0); break; default: usage(); } } argc -= optind; argv += optind; if ( argc != 1 ) { printf("You need to pass a filename.\n"); usage(); } if ( albumname == NULL) { printf("You need to supply an album name.\n"); usage(); } if (idcount == 0) { printf("You need to supply one or more track IDs\n"); usage(); } path = argv[0]; if ( stat(path, &statbuff) == -1 ) { fprintf(stderr, "%s: ", path); perror("stat"); exit(1); } filesize = (uint64_t) statbuff.st_size; imagedata = malloc(filesize * sizeof(uint8_t)); #ifdef __WIN32__ if ( (fd = open(path, O_RDONLY|O_BINARY) == -1) ) { #else if ( (fd = open(path, O_RDONLY)) == -1) { #endif printf("Couldn't open image file %s (%s)\n",path,strerror(errno)); return 1; } else { read(fd, imagedata, filesize); close(fd); } LIBMTP_Init(); device = LIBMTP_Get_First_Device(); if (device == NULL) { printf("No devices.\n"); return 0; } LIBMTP_filesampledata_t *albumart = LIBMTP_new_filesampledata_t(); albumart->data = imagedata; albumart->size = filesize; albumart->filetype = LIBMTP_FILETYPE_JPEG; LIBMTP_album_t *album = LIBMTP_new_album_t(); album->name = albumname; album->no_tracks = idcount; album->tracks = ids; album->parent_id = parentid; album->storage_id = storageid; int ret = LIBMTP_Create_New_Album(device,album); if (ret == 0) { ret = LIBMTP_Send_Representative_Sample(device,album->album_id, albumart); if (ret != 0) { printf("Couldn't send album art\n"); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); } } else { printf("Couldn't create album object\n"); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); } LIBMTP_destroy_filesampledata_t(albumart); LIBMTP_destroy_album_t(album); LIBMTP_Release_Device(device); printf("OK.\n"); return 0; } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/examples/detect.c����������������������������������������������������������0000664�0001750�0001750�00000020416�12205614637�020147� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/** * \file detect.c * Example program to detect a device and list capabilities. * * Copyright (C) 2005-2008 Linus Walleij <triad@df.lth.se> * Copyright (C) 2007 Ted Bullock <tbullock@canada.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common.h" #include "util.h" #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #define XML_BUFSIZE 0x10000 static void dump_xml_fragment(uint8_t *buf, uint32_t len) { static int endianness = 0; // 0 = LE, 1 = BE uint32_t bp = 0; while (bp < len) { if (buf[bp+0] == 0xFF && buf[bp+1] == 0xFE) { endianness = 0; } else if (buf[bp+0] == 0xFE && buf[bp+1] == 0xff) { endianness = 1; } else { uint16_t tmp; if (endianness == 0) { tmp = buf[bp+1] << 8 | buf[bp+0]; } else { tmp = buf[bp+0] << 8 | buf[bp+1]; } // Fix this some day, we only print ISO 8859-1 correctly here, // should atleast support UTF-8. printf("%c", (uint8_t) tmp); } bp += 2; } printf("\n"); } int main (int argc, char **argv) { LIBMTP_raw_device_t * rawdevices; int numrawdevices; LIBMTP_error_number_t err; int i; int opt; extern int optind; extern char *optarg; while ((opt = getopt(argc, argv, "d")) != -1 ) { switch (opt) { case 'd': LIBMTP_Set_Debug(LIBMTP_DEBUG_PTP | LIBMTP_DEBUG_DATA); break; } } argc -= optind; argv += optind; LIBMTP_Init(); fprintf(stdout, "libmtp version: " LIBMTP_VERSION_STRING "\n\n"); fprintf(stdout, "Listing raw device(s)\n"); err = LIBMTP_Detect_Raw_Devices(&rawdevices, &numrawdevices); switch(err) { case LIBMTP_ERROR_NO_DEVICE_ATTACHED: fprintf(stdout, " No raw devices found.\n"); return 0; case LIBMTP_ERROR_CONNECTING: fprintf(stderr, "Detect: There has been an error connecting. Exiting\n"); return 1; case LIBMTP_ERROR_MEMORY_ALLOCATION: fprintf(stderr, "Detect: Encountered a Memory Allocation Error. Exiting\n"); return 1; case LIBMTP_ERROR_NONE: { int i; fprintf(stdout, " Found %d device(s):\n", numrawdevices); for (i = 0; i < numrawdevices; i++) { if (rawdevices[i].device_entry.vendor != NULL || rawdevices[i].device_entry.product != NULL) { fprintf(stdout, " %s: %s (%04x:%04x) @ bus %d, dev %d\n", rawdevices[i].device_entry.vendor, rawdevices[i].device_entry.product, rawdevices[i].device_entry.vendor_id, rawdevices[i].device_entry.product_id, rawdevices[i].bus_location, rawdevices[i].devnum); } else { fprintf(stdout, " %04x:%04x @ bus %d, dev %d\n", rawdevices[i].device_entry.vendor_id, rawdevices[i].device_entry.product_id, rawdevices[i].bus_location, rawdevices[i].devnum); } } } break; case LIBMTP_ERROR_GENERAL: default: fprintf(stderr, "Unknown connection error.\n"); return 1; } /* Iterate over connected MTP devices */ fprintf(stdout, "Attempting to connect device(s)\n"); for (i = 0; i < numrawdevices; i++) { LIBMTP_mtpdevice_t *device; LIBMTP_file_t *files; char *friendlyname; char *syncpartner; char *sectime; char *devcert; uint16_t *filetypes; uint16_t filetypes_len; uint8_t maxbattlevel; uint8_t currbattlevel; int ret; device = LIBMTP_Open_Raw_Device(&rawdevices[i]); if (device == NULL) { fprintf(stderr, "Unable to open raw device %d\n", i); continue; } LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); LIBMTP_Dump_Device_Info(device); printf("MTP-specific device properties:\n"); // The friendly name friendlyname = LIBMTP_Get_Friendlyname(device); if (friendlyname == NULL) { fprintf(stdout, " Friendly name: (NULL)\n"); } else { fprintf(stdout, " Friendly name: %s\n", friendlyname); free(friendlyname); } syncpartner = LIBMTP_Get_Syncpartner(device); if (syncpartner == NULL) { fprintf(stdout, " Synchronization partner: (NULL)\n"); } else { fprintf(stdout, " Synchronization partner: %s\n", syncpartner); free(syncpartner); } // Some battery info ret = LIBMTP_Get_Batterylevel(device, &maxbattlevel, &currbattlevel); if (ret == 0) { fprintf(stdout, " Battery level %d of %d (%d%%)\n",currbattlevel, maxbattlevel, (int) ((float) currbattlevel/ (float) maxbattlevel * 100.0)); } else { // Silently ignore. Some devices does not support getting the // battery level. LIBMTP_Clear_Errorstack(device); } ret = LIBMTP_Get_Supported_Filetypes(device, &filetypes, &filetypes_len); if (ret == 0) { uint16_t i; printf("libmtp supported (playable) filetypes:\n"); for (i = 0; i < filetypes_len; i++) { fprintf(stdout, " %s\n", LIBMTP_Get_Filetype_Description(filetypes[i])); } } else { LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); } // Secure time XML fragment ret = LIBMTP_Get_Secure_Time(device, §ime); if (ret == 0 && sectime != NULL) { fprintf(stdout, "\nSecure Time:\n%s\n", sectime); free(sectime); } else { // Silently ignore - there may be devices not supporting secure time. LIBMTP_Clear_Errorstack(device); } // Device certificate XML fragment #if 0 /* * This code is currently disabled: all devices say that * they support getting a device certificate but a lot of * them obviously doesn't, instead they crash when you try * to obtain it. */ ret = LIBMTP_Get_Device_Certificate(device, &devcert); if (ret == 0 && devcert != NULL) { fprintf(stdout, "\nDevice Certificate:\n%s\n", devcert); free(devcert); } else { fprintf(stdout, "Unable to acquire device certificate, perhaps this device " "does not support this\n"); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); } #endif // Try to get Media player device info XML file... files = LIBMTP_Get_Filelisting_With_Callback(device, NULL, NULL); if (files != NULL) { LIBMTP_file_t *file, *tmp; file = files; while (file != NULL) { if (!strcmp(file->filename, "WMPInfo.xml") || !strcmp(file->filename, "WMPinfo.xml") || !strcmp(file->filename, "default-capabilities.xml")) { if (file->item_id != 0) { /* Dump this file */ FILE *xmltmp = tmpfile(); int tmpfiledescriptor = fileno(xmltmp); if (tmpfiledescriptor != -1) { int ret = LIBMTP_Get_Track_To_File_Descriptor(device, file->item_id, tmpfiledescriptor, NULL, NULL); if (ret == 0) { uint8_t *buf = NULL; uint32_t readbytes; buf = malloc(XML_BUFSIZE); if (buf == NULL) { printf("Could not allocate %08x bytes...\n", XML_BUFSIZE); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); free(rawdevices); return 1; } lseek(tmpfiledescriptor, 0, SEEK_SET); readbytes = read(tmpfiledescriptor, (void*) buf, XML_BUFSIZE); if (readbytes >= 2 && readbytes < XML_BUFSIZE) { fprintf(stdout, "\n%s file contents:\n", file->filename); dump_xml_fragment(buf, readbytes); } else { perror("Unable to read file"); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); } free(buf); } else { LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); } fclose(xmltmp); } } } tmp = file; file = file->next; LIBMTP_destroy_file_t(tmp); } } LIBMTP_Release_Device(device); } /* End For Loop */ free(rawdevices); printf("OK.\n"); return 0; } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/examples/filetree.c��������������������������������������������������������0000664�0001750�0001750�00000007777�12205614637�020515� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/** * \file filetree.c * List all files and folders of all storages recursively * * Copyright (C) 2011 Linus Walleij <triad@df.lth.se> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common.h" #include "util.h" #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> /* Clever prototype to be able to recurse */ void recursive_file_tree(LIBMTP_mtpdevice_t *, LIBMTP_devicestorage_t *, uint32_t, int); void recursive_file_tree(LIBMTP_mtpdevice_t *device, LIBMTP_devicestorage_t *storage, uint32_t leaf, int depth) { LIBMTP_file_t *files; LIBMTP_file_t *file; files = LIBMTP_Get_Files_And_Folders(device, storage->id, leaf); if (files == NULL) { return; } /* Iterate over the filelisting */ for (file = files; file != NULL; file = file->next) { int i; /* Indent */ for (i = 0; i < depth; i++) { printf(" "); } printf("%u %s\n", file->item_id, file->filename); if (file->filetype == LIBMTP_FILETYPE_FOLDER) { recursive_file_tree(device, storage, file->item_id, depth+2); } } } int main (int argc, char **argv) { LIBMTP_raw_device_t * rawdevices; int numrawdevices; LIBMTP_error_number_t err; int i; int opt; extern int optind; extern char *optarg; while ((opt = getopt(argc, argv, "d")) != -1 ) { switch (opt) { case 'd': LIBMTP_Set_Debug(LIBMTP_DEBUG_PTP | LIBMTP_DEBUG_DATA); break; } } argc -= optind; argv += optind; LIBMTP_Init(); err = LIBMTP_Detect_Raw_Devices(&rawdevices, &numrawdevices); switch(err) { case LIBMTP_ERROR_NO_DEVICE_ATTACHED: fprintf(stdout, " No raw devices found.\n"); return 0; case LIBMTP_ERROR_CONNECTING: fprintf(stderr, "Detect: There has been an error connecting. Exiting\n"); return 1; case LIBMTP_ERROR_MEMORY_ALLOCATION: fprintf(stderr, "Detect: Encountered a Memory Allocation Error. Exiting\n"); return 1; case LIBMTP_ERROR_NONE: break; case LIBMTP_ERROR_GENERAL: default: fprintf(stderr, "Unknown connection error.\n"); return 1; } /* Iterate over connected MTP devices */ fprintf(stdout, "Attempting to connect device(s)\n"); for (i = 0; i < numrawdevices; i++) { LIBMTP_mtpdevice_t *device; LIBMTP_devicestorage_t *storage; char *friendlyname; int ret; device = LIBMTP_Open_Raw_Device_Uncached(&rawdevices[i]); if (device == NULL) { fprintf(stderr, "Unable to open raw device %d\n", i); continue; } LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); friendlyname = LIBMTP_Get_Friendlyname(device); if (friendlyname == NULL) { printf("Device: (NULL)\n"); } else { printf("Device: %s\n", friendlyname); free(friendlyname); } /* Get all storages for this device */ ret = LIBMTP_Get_Storage(device, LIBMTP_STORAGE_SORTBY_NOTSORTED); if (ret != 0) { perror("LIBMTP_Get_Storage()"); goto bailout; } /* Loop over storages */ for (storage = device->storage; storage != 0; storage = storage->next) { fprintf(stdout, "Storage: %s\n", storage->StorageDescription); recursive_file_tree(device, storage, 0, 0); } bailout: LIBMTP_Release_Device(device); } /* End For Loop */ free(rawdevices); printf("OK.\n"); return 0; } �libmtp-1.1.6-20-g1b9f164/examples/newplaylist.c�����������������������������������������������������0000664�0001750�0001750�00000006022�12205614637�021247� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/** * \file newplaylist.c * Example program to create a playlist on a device. * * Copyright (C) 2006 Robert Reardon <rreardon@monkshatch.vispa.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common.h" #include "string.h" #include <stdlib.h> #include <limits.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> static void usage(void) { printf("Usage: newplaylist -i <fileid/trackid> -n <playlistname> -s <storage_id> -p <parent_id>\n"); exit(0); } int main (int argc, char **argv) { int opt; extern int optind; extern char *optarg; LIBMTP_mtpdevice_t *device = NULL; int idcount = 0; uint32_t *ids = NULL; uint32_t *tmp = NULL; char *playlistname = NULL; char *rest; uint32_t storageid = 0; uint32_t parentid = 0; fprintf(stdout, "libmtp version: " LIBMTP_VERSION_STRING "\n\n"); while ( (opt = getopt(argc, argv, "hn:i:s:p:")) != -1 ) { switch (opt) { case 'h': usage(); case 'i': idcount++; if ((tmp = realloc(ids, sizeof(uint32_t) * (idcount))) == NULL) { printf("realloc failed\n"); return 1; } ids = tmp; ids[(idcount-1)] = strtoul(optarg, &rest, 0); break; case 'n': playlistname = strdup(optarg); break; case 's': storageid = (uint32_t) strtoul(optarg, NULL, 0); break; case 'p': parentid = (uint32_t) strtoul(optarg, NULL, 0); break; default: usage(); } } argc -= optind; argv += optind; if ( playlistname == NULL) { printf("You need to supply a playlist name.\n"); usage(); } if (idcount == 0) { printf("You need to supply one or more track IDs\n"); usage(); } LIBMTP_Init(); device = LIBMTP_Get_First_Device(); if (device == NULL) { printf("No devices.\n"); return 0; } LIBMTP_playlist_t *playlist = LIBMTP_new_playlist_t(); playlist->name = playlistname; playlist->no_tracks = idcount; playlist->tracks = ids; playlist->parent_id = parentid; playlist->storage_id = storageid; int ret = LIBMTP_Create_New_Playlist(device,playlist); if (ret != 0) { printf("Couldn't create playlist object\n"); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); } else { printf("Created new playlist: %u\n", playlist->playlist_id); } LIBMTP_Release_Device(device); printf("OK.\n"); return 0; } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/examples/tracks.c����������������������������������������������������������0000664�0001750�0001750�00000011271�12205614637�020165� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/** * \file tracks.c * Example program to list the tracks on a device. * * Copyright (C) 2005-2012 Linus Walleij <triad@df.lth.se> * Copyright (C) 2007 Ted Bullock <tbullock@canada.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common.h" #include <stdlib.h> static void dump_trackinfo(LIBMTP_track_t *track) { printf("Track ID: %u\n", track->item_id); if (track->title != NULL) printf(" Title: %s\n", track->title); if (track->artist != NULL) printf(" Artist: %s\n", track->artist); if (track->genre != NULL) printf(" Genre: %s\n", track->genre); if (track->composer != NULL) printf(" Composer: %s\n", track->composer); if (track->album != NULL) printf(" Album: %s\n", track->album); if (track->date != NULL) printf(" Date: %s\n", track->date); if (track->filename != NULL) printf(" Origfilename: %s\n", track->filename); printf(" Track number: %d\n", track->tracknumber); printf(" Duration: %d milliseconds\n", track->duration); #ifdef __WIN32__ printf(" File size %I64u bytes\n", track->filesize); #else printf(" File size %llu bytes\n", (long long unsigned int) track->filesize); #endif printf(" Filetype: %s\n", LIBMTP_Get_Filetype_Description(track->filetype)); if (track->samplerate != 0) { printf(" Sample rate: %u Hz\n", track->samplerate); } if (track->nochannels != 0) { printf(" Number of channels: %u\n", track->nochannels); } if (track->wavecodec != 0) { printf(" WAVE fourCC code: 0x%08X\n", track->wavecodec); } if (track->bitrate != 0) { printf(" Bitrate: %u bits/s\n", track->bitrate); } if (track->bitratetype != 0) { if (track->bitratetype == 1) { printf(" Bitrate type: Constant\n"); } else if (track->bitratetype == 2) { printf(" Bitrate type: Variable (VBR)\n"); } else if (track->bitratetype == 3) { printf(" Bitrate type: Free\n"); } else { printf(" Bitrate type: Unknown/Erroneous value\n"); } } if (track->rating != 0) { printf(" User rating: %u (out of 100)\n", track->rating); } if (track->usecount != 0) { printf(" Use count: %u times\n", track->usecount); } } int main (int argc, char **argv) { LIBMTP_mtpdevice_t *device_list, *device; LIBMTP_track_t *tracks; LIBMTP_Init(); fprintf(stdout, "Attempting to connect device(s)\n"); switch(LIBMTP_Get_Connected_Devices(&device_list)) { case LIBMTP_ERROR_NO_DEVICE_ATTACHED: fprintf(stdout, "mtp-tracks: No Devices have been found\n"); return 0; case LIBMTP_ERROR_CONNECTING: fprintf(stderr, "mtp-tracks: There has been an error connecting. Exit\n"); return 1; case LIBMTP_ERROR_MEMORY_ALLOCATION: fprintf(stderr, "mtp-tracks: Memory Allocation Error. Exit\n"); return 1; /* Unknown general errors - This should never execute */ case LIBMTP_ERROR_GENERAL: default: fprintf(stderr, "mtp-tracks: Unknown error, please report " "this to the libmtp developers\n"); return 1; /* Successfully connected at least one device, so continue */ case LIBMTP_ERROR_NONE: fprintf(stdout, "mtp-tracks: Successfully connected\n"); fflush(stdout); } /* iterate through connected MTP devices */ for(device = device_list; device != NULL; device = device->next) { char *friendlyname; /* Echo the friendly name so we know which device we are working with */ friendlyname = LIBMTP_Get_Friendlyname(device); if (friendlyname == NULL) { printf("Friendly name: (NULL)\n"); } else { printf("Friendly name: %s\n", friendlyname); free(friendlyname); } // Get track listing. tracks = LIBMTP_Get_Tracklisting_With_Callback(device, NULL, NULL); if (tracks == NULL) { printf("No tracks.\n"); } else { LIBMTP_track_t *track, *tmp; track = tracks; while (track != NULL) { dump_trackinfo(track); tmp = track; track = track->next; LIBMTP_destroy_track_t(tmp); } } } LIBMTP_Release_Device_List(device_list); printf("OK.\n"); exit (0); } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/examples/common.h����������������������������������������������������������0000664�0001750�0001750�00000002167�12205614637�020177� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/** * \file common.h * These headers are used by absolutely all sample programs. * Special quirks that apply to all samples go here. * * Copyright (C) 2005-2011 Linus Walleij <triad@df.lth.se> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include <libmtp.h> #ifndef _MSC_VER #include <config.h> #ifdef HAVE_GETOPT_H #include <getopt.h> #else #include <unistd.h> #endif #else // Only if using MSVC... #include "..\windows\getopt.h" #endif ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/examples/playlists.c�������������������������������������������������������0000664�0001750�0001750�00000004466�12205614637�020732� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/** * \file playlists.c * Example program to list the playlists on a device. * * Copyright (C) 2005-2007 Linus Walleij <triad@df.lth.se> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common.h" #include <stdlib.h> static void dump_plinfo(LIBMTP_mtpdevice_t *device, LIBMTP_playlist_t *pl) { uint32_t i; printf("Playlist ID: %d\n", pl->playlist_id); if (pl->name != NULL) printf(" Name: %s\n", pl->name); printf(" Parent ID: %d\n", pl->parent_id); printf(" Tracks:\n"); for (i = 0; i < pl->no_tracks; i++) { LIBMTP_track_t *track; track = LIBMTP_Get_Trackmetadata(device, pl->tracks[i]); if (track != NULL) { printf(" %u: %s - %s\n", pl->tracks[i], track->artist, track->title); LIBMTP_destroy_track_t(track); } else { printf(" %u: INVALID TRACK REFERENCE!\n", pl->tracks[i]); LIBMTP_Dump_Errorstack(device); LIBMTP_Clear_Errorstack(device); } } } int main (int argc, char **argv) { LIBMTP_mtpdevice_t *device; LIBMTP_playlist_t *playlists; fprintf(stdout, "libmtp version: " LIBMTP_VERSION_STRING "\n\n"); LIBMTP_Init(); device = LIBMTP_Get_First_Device(); if (device == NULL) { printf("No devices.\n"); exit (0); } // Get playlist listing. playlists = LIBMTP_Get_Playlist_List(device); if (playlists == NULL) { printf("No playlists.\n"); } else { LIBMTP_playlist_t *pl, *tmp; pl = playlists; while (pl != NULL) { dump_plinfo(device, pl); tmp = pl; pl = pl->next; LIBMTP_destroy_playlist_t(tmp); } } LIBMTP_Release_Device(device); printf("OK.\n"); exit (0); } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/examples/util.c������������������������������������������������������������0000664�0001750�0001750�00000004070�12205614637�017652� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/** * \file util.c * A set of common utility functions found * in all samples. * * Copyright (C) 2008 Linus Walleij <triad@df.lth.se> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "config.h" #include "util.h" #ifdef HAVE_LANGINFO_H #include <langinfo.h> #endif #ifdef HAVE_LOCALE_H #include <locale.h> #endif #include <stdlib.h> #include <stdio.h> #include <string.h> #include <strings.h> void checklang(void) { const char *langsuff = NULL; const char *lang = getenv("LANG"); #ifdef HAVE_LOCALE_H // Set the locale in accordance with environment setlocale(LC_ALL, ""); #endif #ifdef HAVE_LANGINFO_H langsuff = nl_langinfo(CODESET); #else /* * Check environment variables $LANG and $LC_CTYPE * to see if we want to support UTF-8 unicode */ if (lang != NULL) { const char *sep = strrchr(lang, '.'); if (sep != NULL) { langsuff = sep + 1; } else { langsuff = lang; } } #endif if (langsuff == NULL) { printf("Could not determine language suffix for your system. Please check your setup!\n"); } else if (strcasecmp(langsuff, "UTF-8") && strcasecmp(langsuff, "UTF8")) { printf("Your system does not appear to have UTF-8 enabled ($LANG=\"%s\")\n", lang); printf("If you want to have support for diacritics and Unicode characters,\n"); printf("please switch your locale to an UTF-8 locale, e.g. \"en_US.UTF-8\".\n"); } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/examples/connect.c���������������������������������������������������������0000664�0001750�0001750�00000010453�12205614637�020330� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/** * \file connect.c * Main programs implementing several utilities in one. * * Copyright (C) 2006 Chris A. Debenham <chris@adebenham.com> * Copyright (C) 2008-2010 Linus Walleij <triad@df.lth.se> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include <stdlib.h> #include <libgen.h> #include <getopt.h> #include <string.h> #include "common.h" #include "util.h" #include "pathutils.h" #include "connect.h" LIBMTP_folder_t *folders; LIBMTP_file_t *files; LIBMTP_mtpdevice_t *device; static void split_arg(char * argument, char ** part1, char ** part2) { char *sepp; *part1 = NULL; *part2 = NULL; sepp = argument + strcspn(argument, ","); sepp[0] = '\0'; *part1 = argument; *part2 = sepp+1; } static void usage(void) { printf("Usage: connect <command1> <command2>\n"); printf("Commands: --delete [filename]\n"); printf(" --sendfile [source] [destination]\n"); printf(" --sendtrack [source] [destination]\n"); printf(" --getfile [source] [destination]\n"); printf(" --newfolder [foldername]\n"); } int main (int argc, char **argv) { int ret = 0; checklang(); LIBMTP_Init(); fprintf(stdout, "libmtp version: " LIBMTP_VERSION_STRING "\n\n"); device = LIBMTP_Get_First_Device(); if (device == NULL) { printf("No devices.\n"); return 0; } files = LIBMTP_Get_Filelisting_With_Callback (device, NULL, NULL); folders = LIBMTP_Get_Folder_List (device); if ((strncmp(basename(argv[0]),"mtp-delfile",11) == 0) || (strncmp(basename(argv[0]),"delfile",7) == 0)) { ret = delfile_command(argc,argv); } else if ((strncmp(basename(argv[0]),"mtp-getfile",13) == 0) || (strncmp(basename(argv[0]),"getfile",9) == 0)) { ret = getfile_command(argc,argv); } else if ((strncmp(basename(argv[0]),"mtp-newfolder",13) == 0) || (strncmp(basename(argv[0]),"newfolder",9) == 0)) { ret = newfolder_command(argc,argv); } else if ((strncmp(basename(argv[0]),"mtp-sendfile",11) == 0) || (strncmp(basename(argv[0]),"sendfile",7) == 0)) { ret = sendfile_command(argc, argv); } else if ((strncmp(basename(argv[0]),"mtp-sendtr",10) == 0) || (strncmp(basename(argv[0]),"sendtr",6) == 0)) { ret = sendtrack_command(argc, argv); } else { if ( argc < 2 ) { usage (); return 1; } while (1) { int option_index = 0; static struct option long_options[] = { {"delete", 1, 0, 'd'}, {"sendfile", 1, 0, 'f'}, {"getfile", 1, 0, 'g'}, {"newfolder", 1, 0, 'n'}, {"sendtrack", 1, 0, 't'}, {0, 0, 0, 0} }; int c = getopt_long (argc, argv, "d:f:g:n:t:", long_options, &option_index); if (c == -1) break; char *arg1, *arg2; switch (c) { case 'd': printf("Delete %s\n",optarg); ret = delfile_function(optarg); break; case 'f': printf("Send file %s\n",optarg); split_arg(optarg,&arg1,&arg2); ret = sendfile_function(arg1,arg2); break; case 'g': printf("Get file %s\n",optarg); split_arg(optarg,&arg1,&arg2); ret = getfile_function(arg1,arg2); break; case 'n': printf("New folder %s\n",optarg); ret = newfolder_function(optarg); break; case 't': printf("Send track %s\n",optarg); split_arg(optarg,&arg1,&arg2); ret = sendtrack_function(arg1,arg2,NULL,NULL,NULL,NULL,NULL,NULL,0,0,0,0,0); break; } } if (optind < argc) { printf("Unknown options: "); while (optind < argc) printf("%s ", argv[optind++]); printf("\n"); } } LIBMTP_Release_Device(device); return ret; } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/configure.ac���������������������������������������������������������������0000664�0001750�0001750�00000015645�12205614637�017213� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Process this file with autoconf to produce a configure script. AC_PREREQ(2.52) AC_INIT([libmtp], [1.1.6], [libmtp-discuss@lists.sourceforge.net]) AC_CONFIG_MACRO_DIR([m4]) AM_INIT_AUTOMAKE([foreign]) AC_CONFIG_SRCDIR([src/libmtp.c]) AM_CONFIG_HEADER(config.h) # Checks for programs. AC_PROG_CC AC_PROG_INSTALL AC_PROG_LN_S AC_LIBTOOL_WIN32_DLL AC_PROG_LIBTOOL AM_ICONV # Optionally set install location of udev UDEV=/lib/udev AC_ARG_WITH(udev, AC_HELP_STRING([--with-udev=DIR], [directory where udev is installed [default=/lib/udev]]), [UDEV="${withval}"], []) AC_SUBST(UDEV) # Optionally set name of udev rules file, default # priority is 69, to appear before 70-acl.rules which handles # access control to the devices. We try to let all other userspace # libusb-based device handlers take precedence since libmtp may # attempt to autoprobe the devices. # # Later rules can then use the identifiers for its processing. UDEV_RULES=69-libmtp.rules AC_ARG_WITH(udev-rules, AC_HELP_STRING([--with-udev-rules=NAME], [file name for udev rules [default=69-libmtp.rules]]), [UDEV_RULES="${withval}"], []) AC_SUBST(UDEV_RULES) # Optionally set group for device nodes UDEV_GROUP= AC_ARG_WITH(udev-group, AC_HELP_STRING([--with-udev-group=GROUP], [file group for device nodes [default: none specified]]), [UDEV_GROUP="-g\"${withval}\""], []) AC_SUBST(UDEV_GROUP) # Optionally set mode for device nodes UDEV_MODE= AC_ARG_WITH(udev-mode, AC_HELP_STRING([--with-udev-mode=GROUP], [file mode for device nodes [default: none specified]]), [UDEV_MODE="-m\"${withval}\""], []) AC_SUBST(UDEV_MODE) # Optionally enable and check for doxygen AC_ARG_ENABLE([doxygen], AS_HELP_STRING([--enable-doxygen], [Build API documentation using Doxygen [default=no]]), [ac_enable_doxygen=$enableval], [ac_enable_doxygen=auto]) if test "x$ac_enable_doxygen" == "xyes"; then AC_CHECK_PROG(HAVE_DOXYGEN, doxygen, true, false) if test "x$HAVE_DOXYGEN" = "xfalse" -a "x$ac_enable_doxygen" = "xyes"; then AC_MSG_ERROR([*** API documentation explicitly requested but Doxygen not found]) fi AC_MSG_NOTICE([API documentation will be generated using Doxygen]) else HAVE_DOXYGEN=false AC_MSG_NOTICE([API documentation will not be generated]) fi AM_CONDITIONAL(HAVE_DOXYGEN,$HAVE_DOXYGEN) # Check for Darwin AC_MSG_CHECKING([if the host operating system is Darwin]) case "$host" in *-darwin*) AC_MSG_RESULT([yes]) CFLAGS="$CFLAGS -DUSE_DARWIN" OSFLAGS="-framework IOKit" ;; *) AC_MSG_RESULT([no]) ;; esac AC_SUBST(OSFLAGS) AC_MSG_CHECKING([if the host operating system is Linux]) AC_TRY_COMPILE([#ifndef __linux__ #error "FAIL" #endif ], [int test;], [ AC_MSG_RESULT(yes) AM_CONDITIONAL(USE_LINUX, true) ], [ AC_MSG_RESULT(no) AM_CONDITIONAL(USE_LINUX, false) ]) # Check for mingw compiler platform AC_MSG_CHECKING([For MinGW32]) case "$host" in *-*-mingw*) AC_MSG_RESULT([yes]) mingw_compiler=yes ;; *) AC_MSG_RESULT([no]) ;; esac AM_CONDITIONAL(COMPILE_MINGW32, [test "$mingw_compiler" = "yes"]) # Check if Microsoft LIB.EXE is available if test "$mingw_compiler" = "yes"; then AC_CHECK_PROG(ms_lib_exe, lib.exe, yes, no) fi AM_CONDITIONAL(MS_LIB_EXE, test x$ms_lib_exe = xyes) # Check for libusb-1.0 PKG_CHECK_MODULES(LIBUSB, libusb-1.0 >= 1.0.0,[ LIBUSB_VER=`pkg-config --modversion libusb-1.0` LIBUSB_REQUIRES='libusb-1.0' AC_DEFINE(HAVE_LIBUSB1, [], [Have libusb 1.0]) found_libusb1_pkg=yes ],[ # Check for libopenusb second AC_CHECK_LIB([openusb], [openusb_init],[ AC_DEFINE(HAVE_OPENUSB, [], [Have libopenusb 1.0]) LIBUSB_VER=1.0 ],[ PKG_CHECK_MODULES(LIBUSB, libusb >= 0.1.8, [ LIBUSB_VER=`pkg-config --modversion libusb` LIBUSB_REQUIRES='libusb' AC_DEFINE(HAVE_LIBUSB0, [], [Have libusb 0.x]) found_libusb0_pkg=yes ],[ # Some systems don't use pkg-config for libusb, so double check. AC_CHECK_LIB([usb], [usb_open],[ LIBUSB_VER=0.1 AC_DEFINE(HAVE_LIBUSB0, [], [Have libusb 0.x]) found_libusb0_pkg=yes ],[ AC_MSG_ERROR([*** libusb not found! (missing -dev/-devel package?) ***\n*** prefer to install libusb-1 if you can! ***]) ]) ]) ]) ]) # Optionally disable MTPZ functionality. AC_ARG_ENABLE([mtpz], AC_HELP_STRING([--disable-mtpz], [Disable functionality to connect to MTPZ devices (e.g. Zune)]), [use_mtpz=$enableval], [use_mtpz="yes"]) # Include MTPZ if not disabled. if test x"$use_mtpz" = "xyes" ; then # Check for libgcrypt. AC_MSG_CHECKING([for libgcrypt]) AC_CHECK_LIB([gcrypt], [gcry_check_version], , [AC_MSG_NOTICE([*** libgcrypt not found - disabling MTPZ support ***]) ; use_mtpz="no"]) fi if test x"$use_mtpz" = "xyes" ; then AC_DEFINE(USE_MTPZ, [], [Enable MTPZ functionality]) AC_MSG_NOTICE([MTPZ functionality enabled]); else AC_MSG_NOTICE([MTPZ functionality disable]); fi AC_SUBST(LIBUSB_CFLAGS) AC_SUBST(LIBUSB_LIBS) AC_SUBST(LIBUSB_REQUIRES) AM_CONDITIONAL(MTPZ_COMPILE, test x"$use_mtpz" = "xyes") AM_CONDITIONAL(LIBUSB1_COMPILE, test x"$found_libusb1_pkg" = "xyes") AM_CONDITIONAL(LIBUSB0_COMPILE, test x"$found_libusb0_pkg" = "xyes") AM_CONDITIONAL(LIBOPENUSB_COMPILE, test x"$ac_cv_lib_openusb_openusb_init" = "xyes") AC_MSG_NOTICE([*** using libusb $LIBUSB_VER ***]) # Checks for header files. AC_HEADER_STDC AC_HEADER_TIME # zlib.h the day we need to decompress firmware AC_CHECK_HEADERS([ctype.h errno.h fcntl.h getopt.h libgen.h \ limits.h stdio.h string.h sys/stat.h sys/time.h unistd.h \ langinfo.h locale.h arpa/inet.h byteswap.h sys/uio.h]) # Checks for typedefs, structures, and compiler characteristics. AC_C_CONST AC_TYPE_OFF_T AC_TYPE_SIGNAL AC_TYPE_SIZE_T AC_STRUCT_ST_BLKSIZE # Checks for library functions. AC_FUNC_MALLOC AC_FUNC_MEMCMP AC_FUNC_STAT AC_CHECK_FUNCS(basename memset select strdup strerror strndup strrchr strtoul usleep mkstemp) # Switches. # Enable LFS (Large File Support) AC_SYS_LARGEFILE # Stick in "-Werror" if you want to be more aggressive. # (No need to use AC_SUBST on this default substituted environment variable.) # Only add these additional CFLAGS if we are using GCC. Other C compilers may # not support them. if test x"$GCC" == "xyes" ; then CFLAGS="$CFLAGS -Wall -Wmissing-prototypes" fi # Output files # Create a stdint.h-like file containing size-specific integer definitions # that will always be available. The <stdint.h> file is required by the # library, but we provide this anyway because the libptp2 stuff wants this # file. AX_NEED_STDINT_H([src/_stdint.h]) # Create a header file containing NetBSD-style byte swapping macros. # This m4 macros has caused severe pain, I am considering creating a # hard-coded byte swapper that will be eternally portable. AC_NEED_BYTEORDER_H(src/gphoto2-endian.h) AC_CONFIG_FILES([src/libmtp.h doc/Doxyfile Makefile doc/Makefile src/Makefile examples/Makefile util/Makefile libmtp.sh hotplug.sh libmtp.pc]) AC_OUTPUT chmod +x hotplug.sh �������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/README���������������������������������������������������������������������0000664�0001750�0001750�00000125253�12205614637�015602� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Building and Installing ----------------------- See the "INSTALL" file. Initiator and Responder ----------------------- libmtp implements an MTP initiator, which means it initiate MTP sessions with devices. The devices responding are known as MTP responders. libmtp runs on something with a USB host controller interface, using libusb to access the host controller. If you're more interested in the MTP responders, gadgets like MP3 players, mobile phones etc, look into MeeGo:s Buteo Sync: http://wiki.meego.com/Buteo - these guys are creating a fully open source MTP responder. Heritage -------- libmtp is based on several ancestors: * libptp2 by Mariusz Woloszyn was the starting point used by Richard A. Low for the initial starter port. You can find it at http://libptp.sourceforge.net/ * libgphoto2 by Mariusz Woloszyn and Marcus Meissner was used at a later stage since it was (is) more actively maintained. libmtp tracks the PTP implementation in libgphoto2 and considers it an upstream project. We will try to submit anything generally useful back to libgphoto2 and not make double efforts. In practice this means we use ptp.c, ptp.h and ptp-pack.c verbatim from the libgphoto2 source code. If you need to change things in these files, make sure it is so general that libgphoto2 will want to merge it to their codebase too. You find libgphoto2 as part of gPhoto: http://gphoto.sourceforge.net/ * libnjb was a project that Richard and Linus were working on before libmtp. When Linus took Richards initial port and made an generic C API he re-used the philosophy and much code from libnjb. Many of the sample programs are for example taken quite literally from libnjb. You find it here: http://libnjb.sourceforge.net/ Contacting and Contributing --------------------------- See the project page at http://libmtp.sourceforge.net/ We always need your help. There is a mailinglist and a bug report system there. People who want to discuss MTP devices in fora seem to hang out on the forums at AnythingbutiPod: http://www.anythingbutipod.com/forum/ Compiling programs for libmtp ----------------------------- libmtp has support for the pkg-config script by adding a libmtp.pc entry in $(prefix)/lib/pkgconfig. To compile a libmtp program, "just" write: gcc -o foo `pkg-config --cflags --libs libmtp` foo.c This also simplifies compilation using autoconf and pkg-config: just write e.g. PKG_CHECK_MODULES(MTP, libmtp) AC_SUBST(MTP_CFLAGS) AC_SUBST(MTP_LIBS) To have libmtp LIBS and CFLAGS defined. Needless to say, this will only work if you have pkgconfig installed on your system, but most people have nowadays. If your library is installed in e.g. /usr/local you may have to tell this to pkgconfig by setting the PKG_CONFIG_PATH thus: export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig Documentation ------------- Read the API documentation that can be generated with doxygen. It will be output in doc/html if you have Doxygen properly installed. (It will not be created unless you have Doxygen!) For information about the Media Transfer Protocol, see: http://en.wikipedia.org/wiki/Media_Transfer_Protocol The official 1.0 specification for MTP was released by the USB Implementers Forum in may, 2008. Prior to this, only a proprietary Microsoft version was available, and quite a few devices out there still use some aspects of the Microsoft version, which deviates from the specified standard. You can find the official specification here: http://www.usb.org/developers/devclass_docs/MTP_1.0.zip The Examples ------------ In the subdirectory "examples" you find a number of command-line tools, illustrating the use of libmtp in very simple terms. Please do not complain about the usability or documentation of these examples, they look like they do for two reasons: 1. They are examples, not tools. If they were intended for day-to-day usage by commandline freaks, I would have called them "tools" not "examples". 2. The MTP usage paradigm is that a daemon should hook the device upon connection, and that it should be released by unplugging. GUI tools utilizing HAL (hald) and D-Bus do this much better than any commandline program ever can. (See below on bugs.) Specificationwise this is a bug, however it is present in many, many devices. That said, if you want to pick up and maintain the examples, please volunteer. FAQ: Common Problems -------------------- Some MTP devices have strange pecularities. We try to work around these whenever we can, sometimes we cannot work around it or we cannot test your solution. * Android locked screen: some devices just report zero files and no storages when the device screen is locked, it looks like so: mtp-detect Device 0 (VID=04e8 and PID=6860) is a Samsung Galaxy models (MTP). Attempting to connect device(s) Error 1: Get Storage information failed. Device: SHV-E210K LIBMTP_Get_Storage(): No data available OK. This is probably so as not to allow the MTP access to be used as a "backdoor" into the device. Unlock the device before listing files, set the autolock to some large value or disabled if it disturbs you, you are causing this to yourself, or should we say that your vendor is prioritizing security and privacy over ease-of-use. (You may talk to your vendor about this.) * mtp-* tools doesn't work because someone else is already hogging the device This is a common problem, the most common case could be that gphoto2 (which can also talk PTP/MTP) is taking over the device as soon as it's plugged in. Some distributions are configured that way. Counter it like this: gvfs-mount -s gphoto2 Then re-attach the device. Sometimes the "gvfs-gphoto2-volume-monitor" is running on the system and hogging the device, try something like: pkill gfvs-gphoto2-volume-monitor Then plug in the device and issue "mtp-detect" to figure out if this may be the case. * Generic MTP/PTP disconnect misbehaviour: we have noticed that Windows Media Player apparently never close the session to an MTP device. There is a daemon in Windows that "hooks" the device by opening a PTP session to any MTP device, whenever it is plugged in. This daemon proxies any subsequent transactions to/from the device and will never close the session, thus Windows simply does not close sessions at all. For example this means that a device may work the first time you run some command-line example like "mtp-detect" while subsequent runs fail. Typical sign of this illness: broken pipes on closing sessions, on the main transfer pipes(s) or the interrupt pipe: Closing session usb_clear_halt() on INTERRUPT endpoint: Broken pipe OK. This means that device manufacturers doesn't notice any problems with devices that do not correctly handle closing PTP/MTP sessions, since Windows never do it. The proper way of closing a session in Windows is to unplug the device, simply put. Since libmtp actually tries to close sessions, some devices may fail since the close session functionality has never been properly tested, and "it works with Windows" is sort of the testing criteria at some companies. You can get Windows-like behaviour on Linux by running a udev-aware libmtp GUI client like Rhythmbox or Gnomad2, which will "hook" the device when you plug it in, and "release" it if you unplug it, and you start/end you transfer sessions by plugging/unplugging the USB cable. The "Unix way" of running small programs that open the device, do something, then close the device, isn't really working with such devices and you cannot expect to have command line tools like the mtp examples work with them. You could implement new example programs that just call to a mediating daemon like the Windows MTP stack does. (And change all programs using libmtp directly today.) If this bug in your device annoys you, contact your device manufacturer and ask them to test their product with some libmtp program. * Samsung Android 2.3.x devices: these have a special MTP stack with some specific bugs that we have maybe nailed down now. It suffers from an "immediate connect" syndrome, i.e. you have to connect to the device within 7 seconds of plugging in, or it will go numb. This also goes for command-line activity with the example programs, so this device is better used with a GUI tool like Rhythmbox, gnomad2... * Generic USB misbehaviour: some devices behave badly under MTP and USB mass storage alike, even down to the lowest layers of USB. You can always discuss such issues at the linux-usb mailing list if you're using Linux: http://www.linux-usb.org/mailing.html If you have a problem specific to USB mass storage mode, there is a list of strange behaving devices in the Linux kernel: http://lxr.linux.no/linux/drivers/usb/storage/unusual_devs.h You can discuss this too on the mentioned list, for understanding the quirks, see: http://www2.one-eyed-alien.net/~mdharm/linux-usb/target_offenses.txt * Generic certificate misbehaviour. All devices are actually required to support a device certificate to be able to encrypt Windows Media (WMA/WMV) files. However there are obviously a lot of devices out there which doesn't support this at all but instead crash. Typical printout: Error 2: PTP Layer error 02ff: get_device_unicode_property(): failed to get unicode property. This should only affect "mtp-detect", there is no other application currently retrieveing the certificate (not that we know anyway). * Kernel bug on Linux. Linux 2.6.16 is generally speaking required to use any MTP device under USB 2.0. This is because the EHCI driver previously did not support zero-length writes to endpoints. It should work in most cases however, or if you connect it to an UHCI/OHCI port instead (yielding lower speed). But please just use a recent kernel. * Zen models AVI file seeking problem: the Zens cannot parse the files for the runlength metadata. Do not transfer file with e.g. mtp-sendfile, use mtp-sendtr and set the length of the track to the apropriate number of seconds and it will work. In graphical clients, use a "track transfer" function to send these AVI files, the Zens need the metadata associated with tracks to play back movies properly. Movies are considered "tracks" in the MTP world. * Some devices that disregard the metadata sent with the MTP commands will parse the files for e.g. ID3 metadata. Some still of these devices expect only ID3v2.3 metadata and will fail with a modern ID3v2,4 tag writer, like many of those found in Linux applications. Windows Media Player use ID3v2.3 only, so many manufacturers only test this version. * The Zen Vision:M (possibly more Creative Zens) has a firmware bug that makes it drop the last two characters off a playlist name. It is fixed in later firmware. * For Creative Technology devices, there are hard limits on how many files can be put onto the device. For a 30 GiB device (like the Zen Xtra) the limit is 6000, for a 60 GiB device the limit is 15000 files. For further Creative pecularities, see the FAQ sections at www.nomadness.net. * Sandisk sansa c150 and probably several other Sandisk devices (and possibly devices from other manufacturers) have a dual mode with MTP and USB mass storage. The device will initially claim to be mass storage so udev will capture is and make the use of MTP mode impossible. One way of avoiding it could be to be to blacklist the "usb-storage" module in /etc/modprobe.c/blacklist with a row like this: "blacklist usb-storage". Some have even removed the "usb-storage.ko" (kernel module file) to avoid loading. * Sandisk Sansa Fuze has three modes: auto, MTP or mass storage (MSC). Please set it to MTP to avoid problems with libmtp. * The iriver devices (possibly all of them) cannot handle the enhanced GetObjectPropList MTP command (0x9805) properly. So they have been banned from using it. * iriver devices have problems with older versions of libmtp and with new devices libmtp does not know of as of yet, since it has an oldstyle USB device controller that cannot handle zero writes. (Register your device with us!) All their devices are likely to need a special device flag in the src/libusb-glue.c database. * The Samsung Yepp T9 has several strange characteristics, some that we've managed to work around. (For example it will return multiple PTP packages in a single transaction.) * The early firmware for Philips HDD players is known to be problematic. Please upgrade to as new firmware as you can get. (Yes this requires some kind of Windows Installation I think.) * Philips HDD 1630/16 or 1630/17 etc may lock themselves up, turning inresponsive due to internal corruption. This typically gives an error in opening the PTP session. Apparently you can do a "repair" with the firmware utility (Windows only) which will often fix this problem and make the device responsive again. * Some devices that implement GetObjectPropList (0x9805) will not return the entire object list if you request a list for object 0xffffffffu. (But they should.) So they may need the special DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST_ALL. * Some (smaller) subset of devices cannot even get all the properties for a single object in one go, these need the DEVICE_FLAG_BROKEN_MTPGETOBJPROPLIST. Currently only the iriver devices seem to have this bug. * The Toshiba Gigabeat S (and probably its sibling the Microsoft Zune and other Toshiba devices) will only display album information tags for a song in case there is also an abstract album (created with the album interface) with the exact same name. * The Zen Vision:M has an older firmware which is very corrupt, it is incompatible with the Linux USB stack altogether. The kernel dmesg will look something like this, and you have to upgrade the firmware using Windows: usb 4-5: new high speed USB device using ehci_hcd and address 5 usb 4-5: configuration #1 chosen from 1 choice usb 4-5: can't set config #1, error -110 * The Sirus Stiletto does not seem to allow you to copy any files off the device. This may be someone's idea of copy protection. * The Samsung P2 assigns parent folder ID 0 to all unknown file types.(i.e. moves them to the root folder) * The Sandisk Sansa Clip+ needs a firmware upgrade in earlier versions in order to work properly. New Devices ----------- If you happen upon a device which libmtp claims it cannot autodetect, please submit the vendor ID and device ID (these can be obtained from the "lsusb" and "lsusb -n" commands run as root) as a bug, patch or feature request on the Sourceforge bug tracker at our homepage. If it gives a sensible output from "mtp-detect" then please attach the result as well as it teach us some stuff about your device. If you've done some additional hacking, join our mailinglist and post your experiences there. If you want to be able to hack some more and you're not afraid of C hacking, add an entry for your device's vendor/product ID and a descriptive string to the database in the file src/music-players.h. If you want to poke around to see if your device has some special pecularities, you can test some special device flags (defined in src/device-flags.h) by inserting them together with your device entry in src/music-players.h. Flags can be tested in isolation or catenated with "|" (binary OR). If relatives to your device use a certain flag, chances are high that a new device will need it too, typically from the same manufacturer. The most common flag that needs to be set is the DEVICE_FLAG_UNLOAD_DRIVER that detach any Linux kernel drivers that may have attached to the device making MTP access impossible. This is however not expected to really work: this is a problem being tracked as of now (2007-08-04). See the "last resort" solutions below if you really need to get your dual-mode device to work with MTP. Another flag which is easy to identify is the DEVICE_FLAG_NO_ZERO_READS, which remedies connection timeouts when getting files, and some timeouts on e.g. successive "mtp-connect" calls. If your device is very problematic we are curious of how it works under Windows, so we enjoy reading USB packet sniffs that reveal the low-level traffic carried out between Windows Media Player and your device. This can be done using e.g.: * USBsnoop: http://benoit.papillault.free.fr/usbsnoop/ * The trial version of HHD Softwares software-only USB monitor. You need to get a copy of version 2.37 since the newer trial versions won't let you carry out the needed packet sniffs. (As of 2007-03-10 a copy can be found at: http://www.cobbleware.com/files/usb-monitor-237.exe) There are other USB monitors as well, some more expensive alternatives use hardware and even measure electronic characteristics of the traffic (which is far too much detail for us). Device sniffs are an easy read since the PTP/MTP protocol is nicely structured. All commands will have a structure such as this in the log, we examplify with a object list request: PTP REQEUST: 000120: Bulk or Interrupt Transfer (UP), 03.09.2007 12:49:25.9843750 +0.0 Pipe Handle: 0x863ce234 (Endpoint Address: 0x2) Send 0x20 bytes to the device: 20 00 00 00 01 00 05 98 23 00 00 00 27 03 00 10 ......?#...'... Length TYPE CMD Trans# Param1 00 00 00 00 02 DC 00 00 00 00 00 00 00 00 00 00 .....Ü.......... Param2 Param3 Param4 Param5 [OPTIONAL] DATA PHASE: 000121: Bulk or Interrupt Transfer (UP), 03.09.2007 12:49:26.0 +0.0156250 Pipe Handle: 0x863ce214 (Endpoint Address: 0x81) Get 0x1a bytes from the device: 1A 00 00 00 02 00 05 98 23 00 00 00 01 00 00 00 .......?#....... Length TYPE CMD Trans# DATA 27 03 00 10 02 DC 04 00 00 30 '....Ü...0 RESPONSE: 000122: Bulk or Interrupt Transfer (UP), 03.09.2007 12:49:26.0 +0.0 Pipe Handle: 0x863ce214 (Endpoint Address: 0x81) Get 0xc bytes from the device: 0C 00 00 00 03 00 01 20 23 00 00 00 ....... #... Length TYPE CODE Trans# * One send (OUT to the device), two reads (IN from the device). * All three byte chunks commands are sent/recieved/recieeved by the function ptp_transaction() in the file ptp.c. * It boils down to ptp_usb_sendreq(), optionally ptp_usb_senddata() or ptp_usb_getdata() and finally ptp_usb_getresp() in the file libusb-glue.c. Notice ptp_usb_sendreq() and ptp_usb_getresp() are ALWAYS called. The TYPE field correspond to this, so the TYPES in this case are "COMMAND" (0x0001), "DATA" (0x0002), and "RESPONSE" (0x0003). * Notice that the byte order is little endian, so you need to read each field from right to left. * This COMMAND has: CMD 0x99805, we see in ptp.h that this is PTP_OC_MTP_GetObjPropList. Transaction# 0x00000023. REQUEST parameters 0x10000327, 0x00000000, 0x0000DC02, 0x00000000 0x00000000, in this case it means "get props for object 0x10000327", "any format", "property 0xDC02" (PTP_OPC_ObjectFormat), then two parameters that are always zero (no idea what they mean or their use). * The DATA has: CMD 0x99805, we see in ptp.h that this is PTP_OC_MTP_GetObjPropList. Transaction# 0x00000023. Then comes data 0x00000001, 0x10000327, 0xDC02, 0x0004, 0x3000 Which means in this case, (and this is the tricky part) "here you have 1 property", "for object 0x10000327", "it is property 0xDC02" (PTP_OPC_ObjectFormat), "which is of type 0x0004" (PTP_DTC_UINT16), "and set to 0x3000" (PTP_OFC_Undefined, it is perfectly valid to have undefined object formats, since it is a legal value defining this). * This RESPONSE has: CMD 0x99805, we see in ptp.h that this is PTP_OC_MTP_GetObjPropList. Return Code ("RC") = 0x2001, PTP_RC_OK, all went fine. Transaction# 0x00000023. If you want to compare the Windows behaviour with a similar operation using libmtp you can go into the src/libusb-glue.c file and uncomment the row that reads: //#define ENABLE_USB_BULK_DEBUG (I.e. remove the two //.) This will make libmtp print out a hex dump of every bulk USB transaction. The bulk transactions contain all the PTP/MTP layer data, which is usually where the problems appear. Notes to assist with debugging new devices: ------------------------------------------- In debugging new hardware, we highly recommend that you only use the example mtp-* applications that come with libmtp, as other applications may have their own bugs that may interfere with your new device working correctly. Using another application instead of those that come with libmtp just adds another point of failure. For debugging, there are 3 main options: 1. Use the env variable: LIBMTP_DEBUG to increase the verboseness of the debugging output for any application using libmtp. Relevant codes are: * 0x00 [0000 0000] : no debug (default) * 0x01 [0000 0001] : PTP debug * 0x02 [0000 0010] : Playlist debug * 0x04 [0000 0100] : USB debug * 0x08 [0000 1000] : USB data debug // Codes are hex and binary respectively. Simple add them togther // to get your desired level of output. (Assuming bash) eg: $ export LIBMTP_DEBUG=12 $ mtp-detect // To get USB debug and USB data debug information. $ export LIBMTP_DEBUG=2 $ mtp-detect // To get Playlist debug information. Also note, an application may also use the LIBMTP_debug() API function to achieve the same options as listed above. 2. Use "strace" on the various mtp-* commands to see where/what is falling over or getting stuck at. * On Solaris and FreeBSD, use "truss" or "dtrace" instead on "strace". * On Mac OS X, use "ktrace" or "dtrace" instead of "strace". * On OpenBSD and NetBSD, use "ktrace" instead of "strace". This will at least help pinpoint where the application is failing, or a device is reporting incorrect information. (This is extremely helpful with devices that have odd disconnection requirements). The use of these tools may also pinpoint issues with libusb as implemented by each OS vendor or issues with the MTP implementation on the new device as well, so please be prepared for either case. 3. Use "gdb" or similar debugger to step through the code as it is run. This is time consuming, and not needed just to pinpoint where the fault is. The use of gdb or another debugger may also miss or actually cause command and data timing issues with some devices, leading to false information. So please consider this a last resort option. Also please read the "It's Not Our Bug!" section below, as it does contain some useful information that may assist with your device. Dual-mode devices does not work - last resort: ---------------------------------------------- Some devices that are dual-mode are simply impossible to get to work under Linux because the usb-storage(.ko) kernel module hook them first, and refuse to release them, even when we specify the DEVICE_FLAG_UNLOAD_DRIVER flag. (Maybe it DOES release it but the device will immediately be probed at the USB mass storage interface AGAIN because it enumerates.) Here is what some people do: 1. Plug in the device. 2. USB-mass storage folder will open automatically. 3. Unmount the device. 4. Run mtp-detect. It will most likely fail the first time. 5. Run mtp-detect again, it might work this time, or fail. Keep running till it works. 99% it works by the third try. 6. Once mtp-detect gives you an "Ok", open either Rhythmbox or Gnomad2, everything should work. Linux: Try this, if you have a recent Linux kernel, add the file (as root): /etc/modprobe.d/no-usb-storage.conf With the contents: options usb-storage quirks=1234:4321:i This will tell usb-storage to ignore this device when it's inserted so it is not hogged by the mass storage interfaces. Remove and re-insert the device and see if it works. Usually this does the trick. For older systems, or as a bigger hammer, run (as root) something like: > rmmod usb_storage ; mtp-detect You can run most any command or a client like gnomad2 or Amarok immediately after the rmmod command. This works sometimes. Another even more brutal approach is this: * Edit /etc/modprobe.d/blacklist * Add the line "blacklist usb-storage" * Reboot. Now none of you USB disks, flash memory sticks etc will be working (you just disabled them all). However you *can* try your device, and it might have started working because there is no longer a USB mass storage driver that tries to hook onto the mass storage interface of your device. If not even blacklisting works (check with "lsmod | grep usb-storage"), there is some problem with something else and you may need to remove or rename the file /lib/modules/<VERSION>/kernel/drivers/usb/storage/usb-storage.ko manually. If you find the PerfectSolution(TM) to this dilemma, so you can properly switch for individual devices whether to use it as USB mass storage or not, please tell us how you did it. We know we cannot use udev, because udev is called after-the-fact: the device is already configured for USB mass storage when udev is called. On Mac OS there is another ugly hack: 1. Open up a terminal window 2. Type: sudo mv /System/Library/Extensions/IOUSBMassStorageClass.kext /System/Library/Extensions/IOUSBMassStorageClass.kext.disabled and when prompted enter your password. 3. Restart. To reverse this change, just reverse the filenames: sudo mv /System/Library/Extensions/ IOUSBMassStorageClass.kext.disabled /System/Library/Extensions/ IOUSBMassStorageClass.kext and restart. Calendar and contact support: ----------------------------- The Creative Zen series can read VCALENDAR2 (.ics) files and VCard (.vcf) files from programs like for example Evolution with the following limitations/conditions: - The file must be in DOS (CR/LF) format, use the unix2dos program to convert if needed - Repeat events in calendar files do not seem to be supported, entries will only appear once. - Calendar (.ics) files should be stored in the folder "My Organizer" when sent to the device (this directory should be autodetected for use with calendar files, otherwise use the option -f "My Organizer" to sendfile for this) Apparently this file can also contain tasklists. - Contact (.vcf) files should be stored in the folder "My Contacts" when sent to the device. (-f "My Contacts") - Some devices are picky about the name of the calendar and contact files. For example the Zen Microphoto wants: Calendar: My Organizer/6651416.ics Contacts: My Organizer/6651416.vcf Syncing in with Evolution and Creative Devices ---------------------------------------------- Evolution can easily export .ics an .vcf files, but you currently need some command-line hacking to get you stuff copied over in one direction host -> device. The examples/ directory contains a script created for the Creative Zen Microphoto by Nicolas Tetreault. Lost symbols ------------ Shared libraries can be troublesome to users not experienced with them. The following is a condensed version of a generic question that has appeared on the libmtp mailing list from time to time. > PTP: Opening session > Queried Creative Zen Vision:M > gnomad2: relocation error: gnomad2: undefined symbol: > LIBMTP_Get_Storageinfo > (...) > Are these type of errors related to libmtp or something else? The problem is of a generic nature, and related to dynamic library loading. It is colloquially known as "dependency hell". (http://en.wikipedia.org/wiki/Dependency_hell) The gnomad2 application calls upon the dynamic linker in Linux to resolve the symbol "LIBMTP_Get_Storageinfo" or any other symbol (ELF symbol, or link point or whatever you want to call them, a symbol is a label on a memory address that the linker shall resolve from label to actual address.) For generic information on this subject see the INSTALL file and this Wikipedia page: http://en.wikipedia.org/wiki/Library_(computing) When Linux /lib/ld-linux.so.X is called to link the symbols compiled into gnomad2 (or any other executable using libmtp), it examines the ELF file for the libmtp.so.X file it finds first and cannot resolve the symbol "LIBMTP_Get_Storageinfo" (or whichever symbol you have a problem witj) from it, since it's probably not there. There are many possible causes of this symbol breakage: 1) You installed precompiled libmtp and gnomad2 packages (RPMs, debs whatever) that do not match up. Typical cause: your gnomad2 package was built against a newer version of libmtp than what's installed on your machine. Another typical cause: you installed a package you found on the web, somewhere, the dependency resolution system did not protest properly (as it should) or you forced it to install anyway, ignoring some warnings. 2) You compiled libmtp and/or gnomad2 from source, installing both or either in /usr/local/lib and /usr/local/bin. This means at compile-time gnomad2 finds the libmtp library in /usr/local/lib but at runtime, it depends on the Linux system wide library loader (/lib/ld-linux.so.X) in order to resolve the symbols. This loader will look into the file /etc/ld.so.conf and/or the folder /etc/ld.so.conf.d in order to find paths to libraries to be used for resolving the symbols. If you have some older version of libmtp in e.g. /usr/lib (typically installed by a package manager) it will take precedence over the new version you just installed in /usr/local/lib and the newly compiled library in /usr/local/lib will *not* be used, resulting in this error message. 3) You really did install the very latest versions (as of writing libmtp 0.1.5 and gnomad2 2.8.11) from source and there really is no pre-installed package of either on your machine. In that case I'm totally lost, I have no idea what's causing this. Typical remedies: 1) If you don't want to mess around with your system and risk these situations, only use pre-packaged software that came with the distribution or its official support channels. If it still breaks, blame your distribution, they're not packaging correctly. Relying on properly packaged software and not installing things yourself *is* the Linux solution to the "dependency hell" problem. 2) Read about dynamically linked library handling until the stuff I wrote about in the previous list sounds like music to your ears, inspect your /lib, /usr/lib, /usr/local/lib, /etc/ld.so.conf and the /etc/ld.so.conf.d, remove all pre-packed versions using RPM, APT, YaST or whatever your distribution uses, compile libmtp and gnomad2 (or whatever) from source only and you will be enlighted. I don't know if this helps you, it's the best answer we can give. API is obscure - I want plain files! ------------------------------------ PTP/MTP devices does not actually contain "files", they contain objects. These objects have file names, but that is actually just a name tag on the object. Folders/directories aren't really such entities: they are just objects too, albeit objects that can act as parent to other objects. They are called "associations" and are created in atomic fashion and even though there is an MTP command to get all the associations of a certain object, this command is optional so it is perfectly possible (and most common, actually) to create devices where the "folders" (which are actually associations) have no idea whatsoever of what files they are associated as parents to (i.e. which files they contain). This is very easy for device manufacturers to implement, all the association (i.e. finding out which files are in a certain folder) has to be done by the MTP Initiator / host computer. Moving a file to a new folder is for example very simple in a "real" file system. In PTP/MTP devices it is often not even possible, some devices *may* be able to do that, if they support command 0x1019 "Move Object", but actually the only reliable way of executing file movement is to upload the file to the host, download it with the new parent, then delete the old file. We have played with the idea of implementing this time consuming function as a fallback in case the device does not support command 0x1019, perhaps one day we will do that. (Some devices also support command 0x101a "Copy Object".) Then the issue that in PTP/MTP it is legal for two files to have exactly the same path as long as their object IDs differ. A folder/association can contain two files with the exact same name. (And on the Creative devices this even works, too, though most devices implicitly fail at this.) Perhaps one could add some custom hook for handling that, so they become /Foo.mp3 and /Foo.mp3(1) or something similar, but it's really a bit kludgy. Playlists and albums aren't really files, thinking about them as files like the hacks in libgphoto2 is really backwards. They are called associations and are more like a symbolic link that links in a star-shaped pattern to all the files that are part of the album/playlist. Some devices (Samsung) thought that was too complicated and have a different way of storing playlists in an UTF-16 encoded .spl-like file instead! This is why playlists/albums must have their own structs and functions. Plain file access also assumes to be able to write files of an undetermined size, which is simply not possible in a transactional file system like PTP/MTP. (See further below.) I Want Streaming! ----------------- Streaming reads is easy. Just connect the output file descriptor from LIBMTP_Get_File_To_File_Descriptor() (and a similar function for tracks) wherever you want. People have connected this to TCP sockets for streaming web servers etc, works like a charm. Some devices will even survive if the callback functions return non-zero and cancel the download. Some devices will lock up and even require a reset if you do that. Devices are poorly implemented so that's life. If you want to stream off a device, the best idea is always to stream the entire file and discard the stuff at the end you don't want. It will incur a delay if you e.g. want to skip between tracks, sadly. Then we get to the complicated things: streaming WRITES... There is a function: LIBMTP_Send_File_From_File_Descriptor() (and similar for tracks) which will write a file to a device from a file descriptor, which may be a socket or whatever. HOWEVER: this requires a piece of metadata with the .filesize properly set first. This is not because we think it is funny to require that, the protocol requires it. The reason is that PTP/MTP is a transactional file system and it wants to be able to deny file transfer if the file won't fit on the device, so the transaction never even starts, it's impossible to start a transaction without giving file length. People really want streaming so I tried a lot of hacks to see if they would work, such as setting file size to 0xffffffffU or something other unnaturally big and then aborting the file transfer when the stream ends. It doesn't work: either the device crashes or the file simply disappears since the device rolls back all failed transactions. So this is an inherent limitation of the PTP/MTP protocol. I want to remote control my device! ----------------------------------- I have both good and bad news for you. The good news is that the MTP protocol has well-defined commands to play back content on a device. Operation 0xD411 (PTP_DPC_MTP_PlaybackObject) will start playing back a file on the device (whatever that may mean if this is not a music or video file), and operation 0xD403 can set the playback volume to save your ears. Then there are operations to determine how far into the current file you currently are, so as to support say progress bars. Since these commands have been around since the dawn of the MTP protocol and since it was developed in cooperation with Creative Technology, this is probably a requested feature from the Creative people who already had support for playback on their devices using the PDE protocol back then. Anyway, here are the bad news: [logs]$ grep d411 * mtp-detect-trekstor-vibez.txt: 0xd411: Playback Object Aha there is only one known device in the world which actually supports playback on the device. So either you go buy the Trekstor Vibez, or you can forget about this. You could always try asking your hardware vendor of choice to go implement this. Since none of the core developers of libmtp has the Trekstor device, this is not yet implemented in libmtp. I make MTP devices! ------------------- If you are a device vendor there is a lot you can do for libmtp: * Please consider assigning one of your employees as a contact person for libmtp, have them sign up to the libmtp development list and answer questions and post new device ID:s as they are released to our mailing list. * If you want to help even more, assign someone to look deeper into error reports on your specific devices, understand why your firmware may require some special device flags and what can be done about it. * Do you have spare devices you can give us? Send them to Richard (Mac support) or Linus (Linux support). (So far nobody did that except for Microsoft who sent us a Zune by proxy!) Vendors do need help from libmtp too, especially we want to help vendors improve their MTP stacks, because they all suffer from the same problem: the lack of a proper conformance test has made many devices incompliant with the MTP specification as it is published today: most devices are just compliant with the Windows MTP stack, and don't work out-of-the-box with libmtp. We need someone on the inside to help in bug reporting vendors MTP stacks internally so these issues are raised. A good way to go toward better MTP compliance is to test with an alternative implementation of the stack. In e.g. IETF standardization it is compulsory for an RFC to have atleast two independent implementations for it to reach the status as standard. Being compliant with libmtp is also more and more important for vendors: libmtp is being deployed in some embedded systems like set-top-boxes etc. It will be very irritating for customers if a device will not dock properly with some home entertainment equipment just because it is based on Linux and libmtp and not the Windows MTP stack. Autodetect with gudev --------------------- Previously you would use HAL to detect devices being plugged in. Nowadays we use udev directly, or though the GNOME libgudev library. LIBMTPs default udev rules export the proper properties to detect any MTP device automatically, here is a verbose example derived from gnomad2: #define G_UDEV_API_IS_SUBJECT_TO_CHANGE #include <gudev/gudev.h> const char * const gudev_subsystems[] = { "usb", NULL }; GUdevClient *gudev_client; guint uevent_id; guint uevent_bus_hooked = 0; guint uevent_device_hooked = 0; static void uevent_cb(GUdevClient *client, const char *action, GUdevDevice *device, void *data) { guint64 devicenum; guint vendor; guint model; guint busnum; guint devnum; guint mtpdevice; devicenum = (guint64) g_udev_device_get_device_number(device); g_print("%s event for %s (%"G_GINT64_MODIFIER"x)", action, g_udev_device_get_sysfs_path (device), devicenum); /* get device info */ vendor = get_property_as_int(device, "ID_VENDOR_ID", 16); model = get_property_as_int(device, "ID_MODEL_ID", 16); busnum = get_property_as_int(device, "BUSNUM", 10); devnum = get_property_as_int(device, "DEVNUM", 10); mtpdevice = get_property_as_int(device, "ID_MTP_DEVICE", 10); if (vendor == 0 || model == 0) { g_print("couldn't get vendor or model ID for device at (%x:%x)\n", busnum, devnum); return; } else { g_print("vendor = %x, model = %x, bus = %x, device = %x\n", vendor, model, busnum, devnum); } if (mtpdevice) { g_print("device is MTP compliant\n"); if (g_str_equal(action, "add") && uevent_bus_hooked == 0 && uevent_device_hooked == 0) { g_print(MTP device plugged in!\n"); uevent_bus_hooked = busnum; uevent_device_hooked = devnum; scan_jukebox(NULL); } else if (g_str_equal (action, "remove") && uevent_bus_hooked == busnum && uevent_device_hooked == devnum) { g_print("MTP device removed!\n"); uevent_bus_hooked = 0; uevent_device_hooked = 0; } } } (...) /* * Monitor udev device events - we're only really interested in events * for USB devices. */ gudev_client = g_udev_client_new(gudev_subsystems); uevent_id = g_signal_connect_object(gudev_client, "uevent", G_CALLBACK(uevent_cb), NULL, 0); SKETCH OF AN OVERVIEW --------------------- Draft agenda for a talk on MTP devices submitted for the Android builders summit, might come to recycle this: - Protocol overview - Transactional filesystem - no corruption due to unplugged cables! - The host and the device can access the files simultaneously, the device will always "own" the physical file system and proxy the host (MTP initiator). - libmtp interface - relation to libgphoto2 - User expectations fall short: - Not really a mountable filesystem. - Streaming does not work. (Size needs to be known beforehand due to transactional nature.) - GVFS MTP backend to the rescue. - Device sins - Android bugs - Samsungs special Android MTP stack - SonyEricsson Aricent stack for Xperia Androids pre 4.0, broken headers! - Flat access model vs hierarchical, how Android uses MTP as an hierachical file system while it was previously a flat database. - Old paradigm: scan the entire non-hierarchical storage for all content, build a cache to speed up the (USB 1.1!) link. Usually all files were stored in the root folder or a single folder named "/Music" or similar. - Android introduced deeply nested folder hierarchies, not seen before on MTP devices. - Microsoft not using the complete metadata dump feature of the MTP protocol (once introduced by creative) instead they walk directories separately. - So caching a big device will take long time and/or timeout. - Go-MTPFS (FUSE) and GVFS MTP - doing the partial directory walk rather than caching all files. - Especially Android devices nowadays assume that you want to index a folder at the time, whereas older MTP devices (such as those from Creative) would assume that you wanted to index the entire device as it was plugged in, and device firmware is now ever more tailored toward per-folder filetree walking. This makes it harder for the library to provide the right abstractions: do we provide an API for indexing the whole device which is unacceptably slow on new devices, or do we provide an API for indexing a directory at the time which will somehow work on older devices too? Shall we deprecate the older API? - Detecting from vendor extension, can fix in newer extensions! - Autoprobing on Linux - Color devices do not like autoprobing - Devices need different PIDs for every alternative interface due to the Windows USB stack. - Multimode USB - one PID for each mode due to Windows limitations not applicable to Linux, SONY devices have ~5 different PIDs for a single device. - Mode switch devices? Maybe we do this wrong. - MTPZ, came and went. Apparently deprecated by Microsoft with Windows Phone 8. - Ideas?? �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/autogen.sh�����������������������������������������������������������������0000775�0001750�0001750�00000003100�12205614637�016705� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/sh #set -e srcdir=`dirname $0` ACLOCAL_FLAGS="-I ${srcdir}/m4 ${ACLOCAL_FLAGS}" fail() { status=$? echo "Last command failed with status $status in directory $(pwd)." echo "Aborting" exit $status } # Refresh GNU autotools toolchain: libtool echo "Removing libtool cruft" rm -f ltmain.sh config.guess config.sub echo "Running libtoolize" libtoolize --copy --force || fail # Refresh GNU autotools toolchain: aclocal autoheader echo "Removing aclocal cruft" rm -f aclocal.m4 echo "Running aclocal $ACLOCAL_FLAGS" aclocal $ACLOCAL_FLAGS || fail echo "Removing autoheader cruft" rm -f config.h.in src/config.h.in echo "Running autoheader" autoheader || fail # Refresh GNU autotools toolchain: automake echo "Removing automake cruft" rm -f depcomp install-sh missing mkinstalldirs rm -f stamp-h* echo "Running automake" touch config.rpath automake --add-missing --gnu || fail # Refresh GNU autotools toolchain: autoconf echo "Removing autoconf cruft" rm -f configure rm -rf autom4te*.cache/ echo "Running autoconf" autoconf # Autoupdate config.sub and config.guess # from GNU CVS WGET=`which wget` if [ "x$WGET" != "x" ]; then echo "Autoupdate config.sub and config.guess (y/n)?" read IN if [ "$IN" = "y" ] || [ "$IN" = "Y" ]; then wget -O tmpfile http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.guess mv tmpfile config.guess wget -O tmpfile http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.sub mv tmpfile config.sub fi else echo "Could not autoupdate config.sub and config.guess" fi echo "Finished!" ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/libmtp.sh.in���������������������������������������������������������������0000664�0001750�0001750�00000002351�12205614637�017143� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/sh # Lifts a plugged in MTP device to user space and # optionally runs a client program. # Written by Linus Walleij 2006, based on the "usbcam" # script by Nalin Dahyabhai. DEVICEOWNER=root DEVICEPERMS=666 # Special quirk for SuSE systems using "resmgr" # (see http://rechner.lst.de/~okir/resmgr/) if [ -f /sbin/resmgr ] then /sbin/resmgr "${ACTION}" "${DEVICE}" desktop usb exit 0 fi # This is for most other distributions if [ "${ACTION}" = "add" ] && [ -f "${DEVICE}" ] then # New code, using lock files instead of copying /dev/console permissions # This also works with non-gdm logins (e.g. on a virtual terminal) # Idea and code from Nalin Dahyabhai <nalin@redhat.com> if [ "x$DEVICEOWNER" = "xCONSOLE" ] then if [ -f /var/run/console/console.lock ] then DEVICEOWNER=`cat /var/run/console/console.lock` elif [ -f /var/run/console.lock ] then DEVICEOWNER=`cat /var/run/console.lock` elif [ -f /var/lock/console.lock ] then DEVICEOWNER=`cat /var/lock/console.lock` else DEVICEOWNER="nobody" DEVICEPERMS="666" fi fi if [ -n "$DEVICEOWNER" ] then chmod 0000 "${DEVICE}" chown "${DEVICEOWNER}" "${DEVICE}" chmod "${DEVICEPERMS}" "${DEVICE}" fi fi ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/TODO�����������������������������������������������������������������������0000664�0001750�0001750�00000012114�12205614637�015401� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������TODO file: ---------- COMPATIBILITY fixes: 1. COMPATIBILITY: dual-mode devices, i.e. devices exposing both an MTP and a USB Mass Storage Device Class (flashdrive) interface are and have always been problematic. We must find a way to get this to work, eventually. The problem is that the in-kernel mass storage driver hogs the device before the MTP mode gets a chance of being used, whereas the Windows kernel driver apparently does it the other way around, trying the MTP mode first and then not fall back on mass storage if MTP is available. (For some more explanations se src/libusb-glue.h.) This may involve kernel modifications. Perhaps it is only necessary to tweak the udev config not to load USB mass storage support for these devices. Dunno. 2. COMPATIBILITY: several devices tend to "hang" after disconnect, needing to be unplugged and replugged before they can be used again. We don't know why, it may be related to low-level USB behaviour that is not exposed in the logs we read. On some devices it appear that avoiding to release the USB interface after closing the PTP/MTP session solves this, and might be a hint at how the Windows MTP stack works: perhaps the Windows MTP daemon grabs the interface once the device is plugged in, created a session and NEVER release it. Thus only unplug or shutdown ends the session. This behaviour can be emulated (sort of) by DEVICE_FLAG_NO_RELEASE_INTERFACE which will make the device not release the USB low-level interface, though it'll still close the session. But is it really desireable to have as default? Not unless we run an MTP daemon as well, probably, and the behaviour is questionable from an USB interoperability point of view. SPEEDUP fixes: None known. libmtp is fast :-) FEATURE fixes: 1. FEATURE: Support playback and volume setting on devices that have it. (I don't have one that does - Linus.) 2. FEATURE: Support relevant events. MTP devices seen in existance provide events for "object added" and "object deleted". These should result in atleast a call to the cache update function. 3. FEATURE: Mechanism to retrieve the device icon device property, else if not present, look for DevIcon.fil (Windows ICO format) and DevLogo.fil (PNG Format) images from the device (if available). 4. FEATURE: Shared device access so that multiple client applications can have an open connection to the device at the same time via a handle. For example, it should be somehow possible to run mtp-detect at the same time as amarok or mtpfs is connected to a device. This would require some form of resource sharing, discussions have centered on a D-Bus based connection arbiter daemon. 5. FEATURE: Implement an OpenSync backend for devices which have calendaring, contact etc support. http://opensync.org/ THOSE ARE ALREADY DONE: 1. FEATURE: Make an API that can return several devices and let the user choose which one to operate, not just connect to the first one... 2. SPEED: Cache the object info for all items on the device. Right now, ptp_getobjectinfo() is called repeatedly on the same objects during startup, track listing, file listing, playlist listing, album listing and whatever we implement tomorrow. A lot of useless communication can be saved by cacheing this info. Notice that this needs to be updated whenever flush_handles() is called too. (This came from libgphoto2 implementing it!) 3. SPEED: Cache track metadata, file metadata etc in params->proplist. 4. SPEED: Whenever we add an object (file, track, playlist...) we should only need to update the cache with relevant data. Atleast for speedup caches. 5. COMPATIBILITY: account for different step sizes and intervals on some numeric properties we set, make the functions round off when possible. 6. SPEED: Cache the supported object properties at first read/startup. then use the cache to check for supported props instead of calling out to PTP with ptp_mtp_getobjectpropssupported() every time. The cache would be an array of size params->deviceinfo.ImageFormats_len with a list for each format of the properties it will support. Notice that this needs to be updated whenever flush_handles() is called too. THIS HAS BEEN DISCARDED, TERO IMPLEMENTED IT BUT IT DOESN'T SEEM TO YIELD MUCH. 7. FEATURE: Make abstract playlists really become size -1 when created as the ones created on the device instead of the current 1 byte size. (Is this possible using enhanced commands? See TODO remarks in the create_abstract_entity() function) 8. FEATURE: Integrate libmtp with HAL / D-Bus so applications can dynamically know when a device has been plugged in or removed. Need a mechanism to connect a specific hal UDI. 9. SPEEDUP: The recursive function that builds the folder tree is O(n^2)! Atleast remove all non-folders (PTP associations) from the list before we start sorting and building that tree. We walk the entire list for each group of siblings right now! 10. FEATURE: program to autoprobe device interfaces on connection. 11. FEATURE: accomodate Googles uncached device needs. 12. FEATURE: rudimentary event interface. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/m4/������������������������������������������������������������������������0000775�0001750�0001750�00000000000�12205614637�015232� 5����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/m4/iconv.m4����������������������������������������������������������������0000664�0001750�0001750�00000015321�12205614637�016614� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# iconv.m4 serial 11 (gettext-0.18.1) dnl Copyright (C) 2000-2002, 2007-2010 Free Software Foundation, Inc. dnl This file is free software; the Free Software Foundation dnl gives unlimited permission to copy and/or distribute it, dnl with or without modifications, as long as this notice is preserved. dnl From Bruno Haible. AC_DEFUN([AM_ICONV_LINKFLAGS_BODY], [ dnl Prerequisites of AC_LIB_LINKFLAGS_BODY. AC_REQUIRE([AC_LIB_PREPARE_PREFIX]) AC_REQUIRE([AC_LIB_RPATH]) dnl Search for libiconv and define LIBICONV, LTLIBICONV and INCICONV dnl accordingly. AC_LIB_LINKFLAGS_BODY([iconv]) ]) AC_DEFUN([AM_ICONV_LINK], [ dnl Some systems have iconv in libc, some have it in libiconv (OSF/1 and dnl those with the standalone portable GNU libiconv installed). AC_REQUIRE([AC_CANONICAL_HOST]) dnl for cross-compiles dnl Search for libiconv and define LIBICONV, LTLIBICONV and INCICONV dnl accordingly. AC_REQUIRE([AM_ICONV_LINKFLAGS_BODY]) dnl Add $INCICONV to CPPFLAGS before performing the following checks, dnl because if the user has installed libiconv and not disabled its use dnl via --without-libiconv-prefix, he wants to use it. The first dnl AC_TRY_LINK will then fail, the second AC_TRY_LINK will succeed. am_save_CPPFLAGS="$CPPFLAGS" AC_LIB_APPENDTOVAR([CPPFLAGS], [$INCICONV]) AC_CACHE_CHECK([for iconv], [am_cv_func_iconv], [ am_cv_func_iconv="no, consider installing GNU libiconv" am_cv_lib_iconv=no AC_TRY_LINK([#include <stdlib.h> #include <iconv.h>], [iconv_t cd = iconv_open("",""); iconv(cd,NULL,NULL,NULL,NULL); iconv_close(cd);], [am_cv_func_iconv=yes]) if test "$am_cv_func_iconv" != yes; then am_save_LIBS="$LIBS" LIBS="$LIBS $LIBICONV" AC_TRY_LINK([#include <stdlib.h> #include <iconv.h>], [iconv_t cd = iconv_open("",""); iconv(cd,NULL,NULL,NULL,NULL); iconv_close(cd);], [am_cv_lib_iconv=yes] [am_cv_func_iconv=yes]) LIBS="$am_save_LIBS" fi ]) if test "$am_cv_func_iconv" = yes; then AC_CACHE_CHECK([for working iconv], [am_cv_func_iconv_works], [ dnl This tests against bugs in AIX 5.1, HP-UX 11.11, Solaris 10. am_save_LIBS="$LIBS" if test $am_cv_lib_iconv = yes; then LIBS="$LIBS $LIBICONV" fi AC_TRY_RUN([ #include <iconv.h> #include <string.h> int main () { /* Test against AIX 5.1 bug: Failures are not distinguishable from successful returns. */ { iconv_t cd_utf8_to_88591 = iconv_open ("ISO8859-1", "UTF-8"); if (cd_utf8_to_88591 != (iconv_t)(-1)) { static const char input[] = "\342\202\254"; /* EURO SIGN */ char buf[10]; const char *inptr = input; size_t inbytesleft = strlen (input); char *outptr = buf; size_t outbytesleft = sizeof (buf); size_t res = iconv (cd_utf8_to_88591, (char **) &inptr, &inbytesleft, &outptr, &outbytesleft); if (res == 0) return 1; } } #if 0 /* This bug could be worked around by the caller. */ /* Test against HP-UX 11.11 bug: Positive return value instead of 0. */ { iconv_t cd_88591_to_utf8 = iconv_open ("utf8", "iso88591"); if (cd_88591_to_utf8 != (iconv_t)(-1)) { static const char input[] = "\304rger mit b\366sen B\374bchen ohne Augenma\337"; char buf[50]; const char *inptr = input; size_t inbytesleft = strlen (input); char *outptr = buf; size_t outbytesleft = sizeof (buf); size_t res = iconv (cd_88591_to_utf8, (char **) &inptr, &inbytesleft, &outptr, &outbytesleft); if ((int)res > 0) return 1; } } #endif /* Test against HP-UX 11.11 bug: No converter from EUC-JP to UTF-8 is provided. */ if (/* Try standardized names. */ iconv_open ("UTF-8", "EUC-JP") == (iconv_t)(-1) /* Try IRIX, OSF/1 names. */ && iconv_open ("UTF-8", "eucJP") == (iconv_t)(-1) /* Try AIX names. */ && iconv_open ("UTF-8", "IBM-eucJP") == (iconv_t)(-1) /* Try HP-UX names. */ && iconv_open ("utf8", "eucJP") == (iconv_t)(-1)) return 1; return 0; }], [am_cv_func_iconv_works=yes], [am_cv_func_iconv_works=no], [case "$host_os" in aix* | hpux*) am_cv_func_iconv_works="guessing no" ;; *) am_cv_func_iconv_works="guessing yes" ;; esac]) LIBS="$am_save_LIBS" ]) case "$am_cv_func_iconv_works" in *no) am_func_iconv=no am_cv_lib_iconv=no ;; *) am_func_iconv=yes ;; esac else am_func_iconv=no am_cv_lib_iconv=no fi if test "$am_func_iconv" = yes; then AC_DEFINE([HAVE_ICONV], [1], [Define if you have the iconv() function and it works.]) fi if test "$am_cv_lib_iconv" = yes; then AC_MSG_CHECKING([how to link with libiconv]) AC_MSG_RESULT([$LIBICONV]) else dnl If $LIBICONV didn't lead to a usable library, we don't need $INCICONV dnl either. CPPFLAGS="$am_save_CPPFLAGS" LIBICONV= LTLIBICONV= fi AC_SUBST([LIBICONV]) AC_SUBST([LTLIBICONV]) ]) dnl Define AM_ICONV using AC_DEFUN_ONCE for Autoconf >= 2.64, in order to dnl avoid warnings like dnl "warning: AC_REQUIRE: `AM_ICONV' was expanded before it was required". dnl This is tricky because of the way 'aclocal' is implemented: dnl - It requires defining an auxiliary macro whose name ends in AC_DEFUN. dnl Otherwise aclocal's initial scan pass would miss the macro definition. dnl - It requires a line break inside the AC_DEFUN_ONCE and AC_DEFUN expansions. dnl Otherwise aclocal would emit many "Use of uninitialized value $1" dnl warnings. m4_define([gl_iconv_AC_DEFUN], m4_version_prereq([2.64], [[AC_DEFUN_ONCE( [$1], [$2])]], [[AC_DEFUN( [$1], [$2])]])) gl_iconv_AC_DEFUN([AM_ICONV], [ AM_ICONV_LINK if test "$am_cv_func_iconv" = yes; then AC_MSG_CHECKING([for iconv declaration]) AC_CACHE_VAL([am_cv_proto_iconv], [ AC_TRY_COMPILE([ #include <stdlib.h> #include <iconv.h> extern #ifdef __cplusplus "C" #endif #if defined(__STDC__) || defined(__cplusplus) size_t iconv (iconv_t cd, char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft); #else size_t iconv(); #endif ], [], [am_cv_proto_iconv_arg1=""], [am_cv_proto_iconv_arg1="const"]) am_cv_proto_iconv="extern size_t iconv (iconv_t cd, $am_cv_proto_iconv_arg1 char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft);"]) am_cv_proto_iconv=`echo "[$]am_cv_proto_iconv" | tr -s ' ' | sed -e 's/( /(/'` AC_MSG_RESULT([ $am_cv_proto_iconv]) AC_DEFINE_UNQUOTED([ICONV_CONST], [$am_cv_proto_iconv_arg1], [Define as const if the declaration of iconv() needs const.]) fi ]) ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/m4/stdint.m4���������������������������������������������������������������0000664�0001750�0001750�00000057006�12205614637�017011� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������dnl AC_NEED_STDINT_H ( HEADER-TO-GENERATE ) dnl Copyright 2001-2002 by Dan Fandrich <dan@coneharvesters.com> dnl This file may be copied and used freely without restrictions. No warranty dnl is expressed or implied. dnl dnl Look for a header file that defines size-specific integer types like the dnl ones recommended to be in stdint.h in the C99 standard (e.g. uint32_t). dnl This is a dumbed-down version of the macro of the same name in the file dnl ac_need_stdint_h.m4 which is part of the ac-archive, available at dnl <URL:http://ac-archive.sourceforge.net/> (also, another macro dnl AC_CREATE_STDINT_H by the same author). This version is not as smart, dnl but works on older autoconf versions and has a different license. dnl AX_CHECK_DEFINED_TYPE ( TYPE, FILE, ACTION-IF-FOUND, ACTION-IF-NOT-FOUND ) dnl This is similar to _AC_CHECK_TYPE_NEW (a.k.a. new syntax version of dnl AC_CHECK_TYPE) in autoconf 2.50 but works on older versions AC_DEFUN([AX_CHECK_DEFINED_TYPE], [AC_MSG_CHECKING([for $1 in $2]) AC_EGREP_CPP(changequote(<<,>>)dnl <<(^|[^a-zA-Z_0-9])$1[^a-zA-Z_0-9]>>dnl changequote([,]), [#include <$2>], ac_cv_type_$1=yes, ac_cv_type_$1=no)dnl AC_MSG_RESULT($ac_cv_type_$1) if test $ac_cv_type_$1 = yes; then $3 else $4 fi ]) dnl Look for a header file that defines size-specific integer types AC_DEFUN([AX_NEED_STDINT_H], [ ac_dir=`AS_DIRNAME(["$1"])` if test "$ac_dir" != "$1" && test "$ac_dir" != .; then # The file is in a subdirectory. test ! -d "$ac_dir" && (AS_MKDIR_P(["$ac_dir"])) fi AX_CHECK_DEFINED_TYPE(uint8_t, stdint.h, [ cat > "$1" <<EOF /* This file is generated automatically by configure */ #include <stdint.h> EOF], [AX_CHECK_DEFINED_TYPE(uint8_t, inttypes.h, [cat > "$1" <<EOF /* This file is generated automatically by configure */ #include <inttypes.h> EOF], [AX_CHECK_DEFINED_TYPE(uint8_t, sys/types.h, [cat > "$1" <<EOF /* This file is generated automatically by configure */ #include <sys/types.h> EOF], [AX_CHECK_DEFINED_TYPE(u_int8_t, sys/types.h, [cat > "$1" <<EOF /* This file is generated automatically by configure */ #ifndef __STDINT_H #define __STDINT_H #include <sys/types.h> typedef u_int8_t uint8_t; typedef u_int16_t uint16_t; typedef u_int32_t uint32_t; EOF AX_CHECK_DEFINED_TYPE(u_int64_t, sys/types.h, [cat >> "$1" <<EOF typedef u_int64_t uint64_t; #endif /*!__STDINT_H*/ EOF], [cat >> "$1" <<EOF /* 64-bit types are not available on this system */ /* typedef u_int64_t uint64_t; */ #endif /*!__STDINT_H*/ EOF]) ], [AC_MSG_WARN([I can't find size-specific integer definitions on this system]) if test -e "$1" ; then rm -f "$1" fi ])])])])dnl ]) AC_DEFUN([AX_CHECK_DATA_MODEL],[ AC_CHECK_SIZEOF(char) AC_CHECK_SIZEOF(short) AC_CHECK_SIZEOF(int) AC_CHECK_SIZEOF(long) AC_CHECK_SIZEOF(void*) ac_cv_char_data_model="" ac_cv_char_data_model="$ac_cv_char_data_model$ac_cv_sizeof_char" ac_cv_char_data_model="$ac_cv_char_data_model$ac_cv_sizeof_short" ac_cv_char_data_model="$ac_cv_char_data_model$ac_cv_sizeof_int" ac_cv_long_data_model="" ac_cv_long_data_model="$ac_cv_long_data_model$ac_cv_sizeof_int" ac_cv_long_data_model="$ac_cv_long_data_model$ac_cv_sizeof_long" ac_cv_long_data_model="$ac_cv_long_data_model$ac_cv_sizeof_voidp" AC_MSG_CHECKING([data model]) case "$ac_cv_char_data_model/$ac_cv_long_data_model" in 122/242) ac_cv_data_model="IP16" ; n="standard 16bit machine" ;; 122/244) ac_cv_data_model="LP32" ; n="standard 32bit machine" ;; 122/*) ac_cv_data_model="i16" ; n="unusual int16 model" ;; 124/444) ac_cv_data_model="ILP32" ; n="standard 32bit unixish" ;; 124/488) ac_cv_data_model="LP64" ; n="standard 64bit unixish" ;; 124/448) ac_cv_data_model="LLP64" ; n="unusual 64bit unixish" ;; 124/*) ac_cv_data_model="i32" ; n="unusual int32 model" ;; 128/888) ac_cv_data_model="ILP64" ; n="unusual 64bit numeric" ;; 128/*) ac_cv_data_model="i64" ; n="unusual int64 model" ;; 222/*2) ac_cv_data_model="DSP16" ; n="strict 16bit dsptype" ;; 333/*3) ac_cv_data_model="DSP24" ; n="strict 24bit dsptype" ;; 444/*4) ac_cv_data_model="DSP32" ; n="strict 32bit dsptype" ;; 666/*6) ac_cv_data_model="DSP48" ; n="strict 48bit dsptype" ;; 888/*8) ac_cv_data_model="DSP64" ; n="strict 64bit dsptype" ;; 222/*|333/*|444/*|666/*|888/*) : ac_cv_data_model="iDSP" ; n="unusual dsptype" ;; *) ac_cv_data_model="none" ; n="very unusual model" ;; esac AC_MSG_RESULT([$ac_cv_data_model ($ac_cv_long_data_model, $n)]) ]) dnl AX_CHECK_HEADER_STDINT_X([HEADERLIST][,ACTION-IF]) AC_DEFUN([AX_CHECK_HEADER_STDINT_X],[ AC_CACHE_CHECK([for stdint uintptr_t], [ac_cv_header_stdint_x],[ ac_cv_header_stdint_x="" # the 1997 typedefs (inttypes.h) AC_MSG_RESULT([(..)]) for i in m4_ifval([$1],[$1],[stdint.h inttypes.h sys/inttypes.h]) ; do unset ac_cv_type_uintptr_t unset ac_cv_type_uint64_t AC_CHECK_TYPE(uintptr_t,[ac_cv_header_stdint_x=$i],continue,[#include <$i>]) AC_CHECK_TYPE(uint64_t,[and64="/uint64_t"],[and64=""],[#include<$i>]) m4_ifvaln([$1],[$1]) break done AC_MSG_CHECKING([for stdint uintptr_t]) ]) ]) AC_DEFUN([AX_CHECK_HEADER_STDINT_O],[ AC_CACHE_CHECK([for stdint uint32_t], [ac_cv_header_stdint_o],[ ac_cv_header_stdint_o="" # the 1995 typedefs (sys/inttypes.h) AC_MSG_RESULT([(..)]) for i in m4_ifval([$1],[$1],[inttypes.h sys/inttypes.h stdint.h]) ; do unset ac_cv_type_uint32_t unset ac_cv_type_uint64_t AC_CHECK_TYPE(uint32_t,[ac_cv_header_stdint_o=$i],continue,[#include <$i>]) AC_CHECK_TYPE(uint64_t,[and64="/uint64_t"],[and64=""],[#include<$i>]) m4_ifvaln([$1],[$1]) break break; done AC_MSG_CHECKING([for stdint uint32_t]) ]) ]) AC_DEFUN([AX_CHECK_HEADER_STDINT_U],[ AC_CACHE_CHECK([for stdint u_int32_t], [ac_cv_header_stdint_u],[ ac_cv_header_stdint_u="" # the BSD typedefs (sys/types.h) AC_MSG_RESULT([(..)]) for i in m4_ifval([$1],[$1],[sys/types.h inttypes.h sys/inttypes.h]) ; do unset ac_cv_type_u_int32_t unset ac_cv_type_u_int64_t AC_CHECK_TYPE(u_int32_t,[ac_cv_header_stdint_u=$i],continue,[#include <$i>]) AC_CHECK_TYPE(u_int64_t,[and64="/u_int64_t"],[and64=""],[#include<$i>]) m4_ifvaln([$1],[$1]) break break; done AC_MSG_CHECKING([for stdint u_int32_t]) ]) ]) AC_DEFUN([AX_CREATE_STDINT_H], [# ------ AX CREATE STDINT H ------------------------------------- AC_MSG_CHECKING([for stdint types]) ac_stdint_h=`echo ifelse($1, , _stdint.h, $1)` # try to shortcircuit - if the default include path of the compiler # can find a "stdint.h" header then we assume that all compilers can. AC_CACHE_VAL([ac_cv_header_stdint_t],[ old_CXXFLAGS="$CXXFLAGS" ; CXXFLAGS="" old_CPPFLAGS="$CPPFLAGS" ; CPPFLAGS="" old_CFLAGS="$CFLAGS" ; CFLAGS="" AC_TRY_COMPILE([#include <stdint.h>],[int_least32_t v = 0;], [ac_cv_stdint_result="(assuming C99 compatible system)" ac_cv_header_stdint_t="stdint.h"; ], [ac_cv_header_stdint_t=""]) CXXFLAGS="$old_CXXFLAGS" CPPFLAGS="$old_CPPFLAGS" CFLAGS="$old_CFLAGS" ]) v="... $ac_cv_header_stdint_h" if test "$ac_stdint_h" = "stdint.h" ; then AC_MSG_RESULT([(are you sure you want them in ./stdint.h?)]) elif test "$ac_stdint_h" = "inttypes.h" ; then AC_MSG_RESULT([(are you sure you want them in ./inttypes.h?)]) elif test "_$ac_cv_header_stdint_t" = "_" ; then AC_MSG_RESULT([(putting them into $ac_stdint_h)$v]) else ac_cv_header_stdint="$ac_cv_header_stdint_t" AC_MSG_RESULT([$ac_cv_header_stdint (shortcircuit)]) fi if test "_$ac_cv_header_stdint_t" = "_" ; then # can not shortcircuit.. dnl .....intro message done, now do a few system checks..... dnl btw, all old CHECK_TYPE macros do automatically "DEFINE" a type, dnl therefore we use the autoconf implementation detail CHECK_TYPE_NEW dnl instead that is triggered with 3 or more arguments (see types.m4) inttype_headers=`echo $2 | sed -e 's/,/ /g'` ac_cv_stdint_result="(no helpful system typedefs seen)" AX_CHECK_HEADER_STDINT_X(dnl stdint.h inttypes.h sys/inttypes.h $inttype_headers, ac_cv_stdint_result="(seen uintptr_t$and64 in $i)") if test "_$ac_cv_header_stdint_x" = "_" ; then AX_CHECK_HEADER_STDINT_O(dnl, inttypes.h sys/inttypes.h stdint.h $inttype_headers, ac_cv_stdint_result="(seen uint32_t$and64 in $i)") fi if test "_$ac_cv_header_stdint_x" = "_" ; then if test "_$ac_cv_header_stdint_o" = "_" ; then AX_CHECK_HEADER_STDINT_U(dnl, sys/types.h inttypes.h sys/inttypes.h $inttype_headers, ac_cv_stdint_result="(seen u_int32_t$and64 in $i)") fi fi dnl if there was no good C99 header file, do some typedef checks... if test "_$ac_cv_header_stdint_x" = "_" ; then AC_MSG_CHECKING([for stdint datatype model]) AC_MSG_RESULT([(..)]) AX_CHECK_DATA_MODEL fi if test "_$ac_cv_header_stdint_x" != "_" ; then ac_cv_header_stdint="$ac_cv_header_stdint_x" elif test "_$ac_cv_header_stdint_o" != "_" ; then ac_cv_header_stdint="$ac_cv_header_stdint_o" elif test "_$ac_cv_header_stdint_u" != "_" ; then ac_cv_header_stdint="$ac_cv_header_stdint_u" else ac_cv_header_stdint="stddef.h" fi AC_MSG_CHECKING([for extra inttypes in chosen header]) AC_MSG_RESULT([($ac_cv_header_stdint)]) dnl see if int_least and int_fast types are present in _this_ header. unset ac_cv_type_int_least32_t unset ac_cv_type_int_fast32_t AC_CHECK_TYPE(int_least32_t,,,[#include <$ac_cv_header_stdint>]) AC_CHECK_TYPE(int_fast32_t,,,[#include<$ac_cv_header_stdint>]) AC_CHECK_TYPE(intmax_t,,,[#include <$ac_cv_header_stdint>]) fi # shortcircut to system "stdint.h" # ------------------ PREPARE VARIABLES ------------------------------ if test "$GCC" = "yes" ; then ac_cv_stdint_message="using gnu compiler "`$CC --version | head -1` else ac_cv_stdint_message="using $CC" fi AC_MSG_RESULT([make use of $ac_cv_header_stdint in $ac_stdint_h dnl $ac_cv_stdint_result]) dnl ----------------------------------------------------------------- # ----------------- DONE inttypes.h checks START header ------------- AC_CONFIG_COMMANDS([$ac_stdint_h],[ AC_MSG_NOTICE(creating $ac_stdint_h : $_ac_stdint_h) ac_stdint=$tmp/_stdint.h echo "#ifndef" $_ac_stdint_h >$ac_stdint echo "#define" $_ac_stdint_h "1" >>$ac_stdint echo "#ifndef" _GENERATED_STDINT_H >>$ac_stdint echo "#define" _GENERATED_STDINT_H '"'$PACKAGE $VERSION'"' >>$ac_stdint echo "/* generated $ac_cv_stdint_message */" >>$ac_stdint if test "_$ac_cv_header_stdint_t" != "_" ; then echo "#define _STDINT_HAVE_STDINT_H" "1" >>$ac_stdint echo "#include <stdint.h>" >>$ac_stdint echo "#endif" >>$ac_stdint echo "#endif" >>$ac_stdint else cat >>$ac_stdint <<STDINT_EOF /* ................... shortcircuit part ........................... */ #if defined HAVE_STDINT_H || defined _STDINT_HAVE_STDINT_H #include <stdint.h> #else #include <stddef.h> /* .................... configured part ............................ */ STDINT_EOF echo "/* whether we have a C99 compatible stdint header file */" >>$ac_stdint if test "_$ac_cv_header_stdint_x" != "_" ; then ac_header="$ac_cv_header_stdint_x" echo "#define _STDINT_HEADER_INTPTR" '"'"$ac_header"'"' >>$ac_stdint else echo "/* #undef _STDINT_HEADER_INTPTR */" >>$ac_stdint fi echo "/* whether we have a C96 compatible inttypes header file */" >>$ac_stdint if test "_$ac_cv_header_stdint_o" != "_" ; then ac_header="$ac_cv_header_stdint_o" echo "#define _STDINT_HEADER_UINT32" '"'"$ac_header"'"' >>$ac_stdint else echo "/* #undef _STDINT_HEADER_UINT32 */" >>$ac_stdint fi echo "/* whether we have a BSD compatible inet types header */" >>$ac_stdint if test "_$ac_cv_header_stdint_u" != "_" ; then ac_header="$ac_cv_header_stdint_u" echo "#define _STDINT_HEADER_U_INT32" '"'"$ac_header"'"' >>$ac_stdint else echo "/* #undef _STDINT_HEADER_U_INT32 */" >>$ac_stdint fi echo "" >>$ac_stdint if test "_$ac_header" != "_" ; then if test "$ac_header" != "stddef.h" ; then echo "#include <$ac_header>" >>$ac_stdint echo "" >>$ac_stdint fi fi echo "/* which 64bit typedef has been found */" >>$ac_stdint if test "$ac_cv_type_uint64_t" = "yes" ; then echo "#define _STDINT_HAVE_UINT64_T" "1" >>$ac_stdint else echo "/* #undef _STDINT_HAVE_UINT64_T */" >>$ac_stdint fi if test "$ac_cv_type_u_int64_t" = "yes" ; then echo "#define _STDINT_HAVE_U_INT64_T" "1" >>$ac_stdint else echo "/* #undef _STDINT_HAVE_U_INT64_T */" >>$ac_stdint fi echo "" >>$ac_stdint echo "/* which type model has been detected */" >>$ac_stdint if test "_$ac_cv_char_data_model" != "_" ; then echo "#define _STDINT_CHAR_MODEL" "$ac_cv_char_data_model" >>$ac_stdint echo "#define _STDINT_LONG_MODEL" "$ac_cv_long_data_model" >>$ac_stdint else echo "/* #undef _STDINT_CHAR_MODEL // skipped */" >>$ac_stdint echo "/* #undef _STDINT_LONG_MODEL // skipped */" >>$ac_stdint fi echo "" >>$ac_stdint echo "/* whether int_least types were detected */" >>$ac_stdint if test "$ac_cv_type_int_least32_t" = "yes"; then echo "#define _STDINT_HAVE_INT_LEAST32_T" "1" >>$ac_stdint else echo "/* #undef _STDINT_HAVE_INT_LEAST32_T */" >>$ac_stdint fi echo "/* whether int_fast types were detected */" >>$ac_stdint if test "$ac_cv_type_int_fast32_t" = "yes"; then echo "#define _STDINT_HAVE_INT_FAST32_T" "1" >>$ac_stdint else echo "/* #undef _STDINT_HAVE_INT_FAST32_T */" >>$ac_stdint fi echo "/* whether intmax_t type was detected */" >>$ac_stdint if test "$ac_cv_type_intmax_t" = "yes"; then echo "#define _STDINT_HAVE_INTMAX_T" "1" >>$ac_stdint else echo "/* #undef _STDINT_HAVE_INTMAX_T */" >>$ac_stdint fi echo "" >>$ac_stdint cat >>$ac_stdint <<STDINT_EOF /* .................... detections part ............................ */ /* whether we need to define bitspecific types from compiler base types */ #ifndef _STDINT_HEADER_INTPTR #ifndef _STDINT_HEADER_UINT32 #ifndef _STDINT_HEADER_U_INT32 #define _STDINT_NEED_INT_MODEL_T #else #define _STDINT_HAVE_U_INT_TYPES #endif #endif #endif #ifdef _STDINT_HAVE_U_INT_TYPES #undef _STDINT_NEED_INT_MODEL_T #endif #ifdef _STDINT_CHAR_MODEL #if _STDINT_CHAR_MODEL+0 == 122 || _STDINT_CHAR_MODEL+0 == 124 #ifndef _STDINT_BYTE_MODEL #define _STDINT_BYTE_MODEL 12 #endif #endif #endif #ifndef _STDINT_HAVE_INT_LEAST32_T #define _STDINT_NEED_INT_LEAST_T #endif #ifndef _STDINT_HAVE_INT_FAST32_T #define _STDINT_NEED_INT_FAST_T #endif #ifndef _STDINT_HEADER_INTPTR #define _STDINT_NEED_INTPTR_T #ifndef _STDINT_HAVE_INTMAX_T #define _STDINT_NEED_INTMAX_T #endif #endif /* .................... definition part ............................ */ /* some system headers have good uint64_t */ #ifndef _HAVE_UINT64_T #if defined _STDINT_HAVE_UINT64_T || defined HAVE_UINT64_T #define _HAVE_UINT64_T #elif defined _STDINT_HAVE_U_INT64_T || defined HAVE_U_INT64_T #define _HAVE_UINT64_T typedef u_int64_t uint64_t; #endif #endif #ifndef _HAVE_UINT64_T /* .. here are some common heuristics using compiler runtime specifics */ #if defined __STDC_VERSION__ && defined __STDC_VERSION__ >= 199901L #define _HAVE_UINT64_T #define _HAVE_LONGLONG_UINT64_T typedef long long int64_t; typedef unsigned long long uint64_t; #elif !defined __STRICT_ANSI__ #if defined _MSC_VER || defined __WATCOMC__ || defined __BORLANDC__ #define _HAVE_UINT64_T typedef __int64 int64_t; typedef unsigned __int64 uint64_t; #elif defined __GNUC__ || defined __MWERKS__ || defined __ELF__ /* note: all ELF-systems seem to have loff-support which needs 64-bit */ #if !defined _NO_LONGLONG #define _HAVE_UINT64_T #define _HAVE_LONGLONG_UINT64_T typedef long long int64_t; typedef unsigned long long uint64_t; #endif #elif defined __alpha || (defined __mips && defined _ABIN32) #if !defined _NO_LONGLONG typedef long int64_t; typedef unsigned long uint64_t; #endif /* compiler/cpu type to define int64_t */ #endif #endif #endif #if defined _STDINT_HAVE_U_INT_TYPES /* int8_t int16_t int32_t defined by inet code, redeclare the u_intXX types */ typedef u_int8_t uint8_t; typedef u_int16_t uint16_t; typedef u_int32_t uint32_t; /* glibc compatibility */ #ifndef __int8_t_defined #define __int8_t_defined #endif #endif #ifdef _STDINT_NEED_INT_MODEL_T /* we must guess all the basic types. Apart from byte-adressable system, */ /* there a few 32-bit-only dsp-systems that we guard with BYTE_MODEL 8-} */ /* (btw, those nibble-addressable systems are way off, or so we assume) */ dnl /* have a look at "64bit and data size neutrality" at */ dnl /* http://unix.org/version2/whatsnew/login_64bit.html */ dnl /* (the shorthand "ILP" types always have a "P" part) */ #if defined _STDINT_BYTE_MODEL #if _STDINT_LONG_MODEL+0 == 242 /* 2:4:2 = IP16 = a normal 16-bit system */ typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned long uint32_t; #ifndef __int8_t_defined #define __int8_t_defined typedef char int8_t; typedef short int16_t; typedef long int32_t; #endif #elif _STDINT_LONG_MODEL+0 == 244 || _STDINT_LONG_MODEL == 444 /* 2:4:4 = LP32 = a 32-bit system derived from a 16-bit */ /* 4:4:4 = ILP32 = a normal 32-bit system */ typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; #ifndef __int8_t_defined #define __int8_t_defined typedef char int8_t; typedef short int16_t; typedef int int32_t; #endif #elif _STDINT_LONG_MODEL+0 == 484 || _STDINT_LONG_MODEL+0 == 488 /* 4:8:4 = IP32 = a 32-bit system prepared for 64-bit */ /* 4:8:8 = LP64 = a normal 64-bit system */ typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; #ifndef __int8_t_defined #define __int8_t_defined typedef char int8_t; typedef short int16_t; typedef int int32_t; #endif /* this system has a "long" of 64bit */ #ifndef _HAVE_UINT64_T #define _HAVE_UINT64_T typedef unsigned long uint64_t; typedef long int64_t; #endif #elif _STDINT_LONG_MODEL+0 == 448 /* LLP64 a 64-bit system derived from a 32-bit system */ typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; #ifndef __int8_t_defined #define __int8_t_defined typedef char int8_t; typedef short int16_t; typedef int int32_t; #endif /* assuming the system has a "long long" */ #ifndef _HAVE_UINT64_T #define _HAVE_UINT64_T #define _HAVE_LONGLONG_UINT64_T typedef unsigned long long uint64_t; typedef long long int64_t; #endif #else #define _STDINT_NO_INT32_T #endif #else #define _STDINT_NO_INT8_T #define _STDINT_NO_INT32_T #endif #endif /* * quote from SunOS-5.8 sys/inttypes.h: * Use at your own risk. As of February 1996, the committee is squarely * behind the fixed sized types; the "least" and "fast" types are still being * discussed. The probability that the "fast" types may be removed before * the standard is finalized is high enough that they are not currently * implemented. */ #if defined _STDINT_NEED_INT_LEAST_T typedef int8_t int_least8_t; typedef int16_t int_least16_t; typedef int32_t int_least32_t; #ifdef _HAVE_UINT64_T typedef int64_t int_least64_t; #endif typedef uint8_t uint_least8_t; typedef uint16_t uint_least16_t; typedef uint32_t uint_least32_t; #ifdef _HAVE_UINT64_T typedef uint64_t uint_least64_t; #endif /* least types */ #endif #if defined _STDINT_NEED_INT_FAST_T typedef int8_t int_fast8_t; typedef int int_fast16_t; typedef int32_t int_fast32_t; #ifdef _HAVE_UINT64_T typedef int64_t int_fast64_t; #endif typedef uint8_t uint_fast8_t; typedef unsigned uint_fast16_t; typedef uint32_t uint_fast32_t; #ifdef _HAVE_UINT64_T typedef uint64_t uint_fast64_t; #endif /* fast types */ #endif #ifdef _STDINT_NEED_INTMAX_T #ifdef _HAVE_UINT64_T typedef int64_t intmax_t; typedef uint64_t uintmax_t; #else typedef long intmax_t; typedef unsigned long uintmax_t; #endif #endif #ifdef _STDINT_NEED_INTPTR_T #ifndef __intptr_t_defined #define __intptr_t_defined /* we encourage using "long" to store pointer values, never use "int" ! */ #if _STDINT_LONG_MODEL+0 == 242 || _STDINT_LONG_MODEL+0 == 484 typedef unsinged int uintptr_t; typedef int intptr_t; #elif _STDINT_LONG_MODEL+0 == 244 || _STDINT_LONG_MODEL+0 == 444 typedef unsigned long uintptr_t; typedef long intptr_t; #elif _STDINT_LONG_MODEL+0 == 448 && defined _HAVE_UINT64_T typedef uint64_t uintptr_t; typedef int64_t intptr_t; #else /* matches typical system types ILP32 and LP64 - but not IP16 or LLP64 */ typedef unsigned long uintptr_t; typedef long intptr_t; #endif #endif #endif /* The ISO C99 standard specifies that in C++ implementations these should only be defined if explicitly requested. */ #if !defined __cplusplus || defined __STDC_CONSTANT_MACROS #ifndef UINT32_C /* Signed. */ # define INT8_C(c) c # define INT16_C(c) c # define INT32_C(c) c # ifdef _HAVE_LONGLONG_UINT64_T # define INT64_C(c) c ## L # else # define INT64_C(c) c ## LL # endif /* Unsigned. */ # define UINT8_C(c) c ## U # define UINT16_C(c) c ## U # define UINT32_C(c) c ## U # ifdef _HAVE_LONGLONG_UINT64_T # define UINT64_C(c) c ## UL # else # define UINT64_C(c) c ## ULL # endif /* Maximal type. */ # ifdef _HAVE_LONGLONG_UINT64_T # define INTMAX_C(c) c ## L # define UINTMAX_C(c) c ## UL # else # define INTMAX_C(c) c ## LL # define UINTMAX_C(c) c ## ULL # endif /* literalnumbers */ #endif #endif /* These limits are merily those of a two complement byte-oriented system */ /* Minimum of signed integral types. */ # define INT8_MIN (-128) # define INT16_MIN (-32767-1) # define INT32_MIN (-2147483647-1) # define INT64_MIN (-__INT64_C(9223372036854775807)-1) /* Maximum of signed integral types. */ # define INT8_MAX (127) # define INT16_MAX (32767) # define INT32_MAX (2147483647) # define INT64_MAX (__INT64_C(9223372036854775807)) /* Maximum of unsigned integral types. */ # define UINT8_MAX (255) # define UINT16_MAX (65535) # define UINT32_MAX (4294967295U) # define UINT64_MAX (__UINT64_C(18446744073709551615)) /* Minimum of signed integral types having a minimum size. */ # define INT_LEAST8_MIN INT8_MIN # define INT_LEAST16_MIN INT16_MIN # define INT_LEAST32_MIN INT32_MIN # define INT_LEAST64_MIN INT64_MIN /* Maximum of signed integral types having a minimum size. */ # define INT_LEAST8_MAX INT8_MAX # define INT_LEAST16_MAX INT16_MAX # define INT_LEAST32_MAX INT32_MAX # define INT_LEAST64_MAX INT64_MAX /* Maximum of unsigned integral types having a minimum size. */ # define UINT_LEAST8_MAX UINT8_MAX # define UINT_LEAST16_MAX UINT16_MAX # define UINT_LEAST32_MAX UINT32_MAX # define UINT_LEAST64_MAX UINT64_MAX /* shortcircuit*/ #endif /* once */ #endif #endif STDINT_EOF fi if cmp -s $ac_stdint_h $ac_stdint 2>/dev/null; then AC_MSG_NOTICE([$ac_stdint_h is unchanged]) else ac_dir=`AS_DIRNAME(["$ac_stdint_h"])` AS_MKDIR_P(["$ac_dir"]) rm -f $ac_stdint_h mv $ac_stdint $ac_stdint_h fi ],[# variables for create stdint.h replacement PACKAGE="$PACKAGE" VERSION="$VERSION" ac_stdint_h="$ac_stdint_h" _ac_stdint_h=AS_TR_CPP(_$PACKAGE-$ac_stdint_h) ac_cv_stdint_message="$ac_cv_stdint_message" ac_cv_header_stdint_t="$ac_cv_header_stdint_t" ac_cv_header_stdint_x="$ac_cv_header_stdint_x" ac_cv_header_stdint_o="$ac_cv_header_stdint_o" ac_cv_header_stdint_u="$ac_cv_header_stdint_u" ac_cv_type_uint64_t="$ac_cv_type_uint64_t" ac_cv_type_u_int64_t="$ac_cv_type_u_int64_t" ac_cv_char_data_model="$ac_cv_char_data_model" ac_cv_long_data_model="$ac_cv_long_data_model" ac_cv_type_int_least32_t="$ac_cv_type_int_least32_t" ac_cv_type_int_fast32_t="$ac_cv_type_int_fast32_t" ac_cv_type_intmax_t="$ac_cv_type_intmax_t" ]) ]) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libmtp-1.1.6-20-g1b9f164/m4/byteorder.m4������������������������������������������������������������0000664�0001750�0001750�00000030075�12205614637�017500� 0����������������������������������������������������������������������������������������������������ustar �glowworm������������������������glowworm���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������dnl AC_NEED_BYTEORDER_H ( HEADER-TO-GENERATE ) dnl Copyright 2001-2002 by Dan Fandrich <dan@coneharvesters.com> dnl This file may be copied and used freely without restrictions. No warranty dnl is expressed or implied. dnl dnl Create a header file that guarantees that byte swapping macros of the dnl ntohl variety as well as the extended types included in OpenBSD and dnl NetBSD such as le32toh are defined. If possible, the standard ntohl dnl are overloaded as they are optimized for the given platform, but when dnl this is not possible (e.g. on a big-endian machine) they are defined dnl in this file. dnl Look for a symbol in a header file dnl AC_HAVE_SYMBOL ( IDENTIFIER, HEADER-FILE, ACTION-IF-FOUND, ACTION-IF-NOT-FOUND ) AC_DEFUN([AC_HAVE_SYMBOL], [ AC_MSG_CHECKING(for $1 in $2) AC_EGREP_CPP([symbol is present|\<$1\>],[ #include <$2> #ifdef $1 symbol is present #endif ], [AC_MSG_RESULT(yes) $3 ], [AC_MSG_RESULT(no) $4 ])]) dnl Create a header file that defines extended byte swapping macros AC_DEFUN([AC_NEED_BYTEORDER_H], [ ac_dir=`AS_DIRNAME(["$1"])` if test "$ac_dir" != "$1" && test "$ac_dir" != .; then # The file is in a subdirectory. test ! -d "$ac_dir" && (AS_MKDIR_P(["$ac_dir"])) fi # We're only interested in the target CPU, but it's not always set effective_target="$target" if test "x$effective_target" = xNONE -o "x$effective_target" = x ; then effective_target="$host" fi AC_SUBST(effective_target) cat > "$1" << EOF /* This file is generated automatically by configure */ /* It is valid only for the system type ${effective_target} */ #ifndef __BYTEORDER_H #define __BYTEORDER_H EOF dnl First, do an endian check AC_C_BIGENDIAN dnl Look for NetBSD-style extended byte swapping macros AC_HAVE_SYMBOL(le32toh,machine/endian.h, [HAVE_LE32TOH=1 cat >> "$1" << EOF /* extended byte swapping macros are already available */ #include <machine/endian.h> EOF], [ dnl Look for standard byte swapping macros AC_HAVE_SYMBOL(ntohl,arpa/inet.h, [cat >> "$1" << EOF /* ntohl and relatives live here */ #include <arpa/inet.h> EOF], [AC_HAVE_SYMBOL(ntohl,netinet/in.h, [cat >> "$1" << EOF /* ntohl and relatives live here */ #include <netinet/in.h> EOF],true)]) ]) dnl Look for generic byte swapping macros dnl OpenBSD AC_HAVE_SYMBOL(swap32,machine/endian.h, [cat >> "$1" << EOF /* swap32 and swap16 are defined in machine/endian.h */ EOF], [ dnl Linux GLIBC AC_HAVE_SYMBOL(bswap_32,byteswap.h, [cat >> "$1" << EOF /* Define generic byte swapping functions */ #include <byteswap.h> #define swap16(x) bswap_16(x) #define swap32(x) bswap_32(x) #define swap64(x) bswap_64(x) EOF], [ dnl NetBSD AC_HAVE_SYMBOL(bswap32,machine/endian.h, dnl We're already including machine/endian.h if this test succeeds [cat >> "$1" << EOF /* Define generic byte swapping functions */ EOF if test "$HAVE_LE32TOH" != "1"; then echo '#include <machine/endian.h>'>> "$1" fi cat >> "$1" << EOF #define swap16(x) bswap16(x) #define swap32(x) bswap32(x) #define swap64(x) bswap64(x) EOF], [ dnl FreeBSD AC_HAVE_SYMBOL(__byte_swap_long,sys/types.h, [cat >> "$1" << EOF /* Define generic byte swapping functions */ #include <sys/types.h> #define swap16(x) __byte_swap_word(x) #define swap32(x) __byte_swap_long(x) /* No optimized 64 bit byte swapping macro is available */ #define swap64(x) ((uint64_t)(((uint64_t)(x) << 56) & 0xff00000000000000ULL | \\ ((uint64_t)(x) << 40) & 0x00ff000000000000ULL | \\ ((uint64_t)(x) << 24) & 0x0000ff0000000000ULL | \\ ((uint64_t)(x) << 8) & 0x000000ff00000000ULL | \\ ((x) >> 8) & 0x00000000ff000000ULL | \\ ((x) >> 24) & 0x0000000000ff0000ULL | \\ ((x) >> 40) & 0x000000000000ff00ULL | \\ ((x) >> 56) & 0x00000000000000ffULL)) EOF], [ dnl OS X AC_HAVE_SYMBOL(NXSwapLong,machine/byte_order.h, [cat >> "$1" << EOF /* Define generic byte swapping functions */ #include <machine/byte_order.h> #define swap16(x) NXSwapShort(x) #define swap32(x) NXSwapLong(x) #define swap64(x) NXSwapLongLong(x) EOF], [ if test $ac_cv_c_bigendian = yes; then cat >> "$1" << EOF /* No other byte swapping functions are available on this big-endian system */ #define swap16(x) ((uint16_t)(((x) << 8) | ((uint16_t)(x) >> 8))) #define swap32(x) ((uint32_t)(((uint32_t)(x) << 24) & 0xff000000UL | \\ ((uint32_t)(x) << 8) & 0x00ff0000UL | \\ ((x) >> 8) & 0x0000ff00UL | \\ ((x) >> 24) & 0x000000ffUL)) #define swap64(x) ((uint64_t)(((uint64_t)(x) << 56) & 0xff00000000000000ULL | \\ ((uint64_t)(x) << 40) & 0x00ff000000000000ULL | \\ ((uint64_t)(x) << 24) & 0x0000ff0000000000ULL | \\ ((uint64_t)(x) << 8) & 0x000000ff00000000ULL | \\ ((x) >> 8) & 0x00000000ff000000ULL | \\ ((x) >> 24) & 0x0000000000ff0000ULL | \\ ((x) >> 40) & 0x000000000000ff00ULL | \\ ((x) >> 56) & 0x00000000000000ffULL)) EOF else cat >> "$1" << EOF /* Use these as generic byteswapping macros on this little endian system */ #define swap16(x) ntohs(x) #define swap32(x) ntohl(x) /* No optimized 64 bit byte swapping macro is available */ #define swap64(x) ((uint64_t)(((uint64_t)(x) << 56) & 0xff00000000000000ULL | \\ ((uint64_t)(x) << 40) & 0x00ff000000000000ULL | \\ ((uint64_t)(x) << 24) & 0x0000ff0000000000ULL | \\ ((uint64_t)(x) << 8) & 0x000000ff00000000ULL | \\ ((x) >> 8) & 0x00000000ff000000ULL | \\ ((x) >> 24) & 0x0000000000ff0000ULL | \\ ((x) >> 40) & 0x000000000000ff00ULL | \\ ((x) >> 56) & 0x00000000000000ffULL)) EOF fi ]) ]) ]) ]) ]) [ if test "$HAVE_LE32TOH" != "1"; then cat >> "$1" << EOF /* The byte swapping macros have the form: */ /* EENN[a]toh or htoEENN[a] where EE is be (big endian) or */ /* le (little-endian), NN is 16 or 32 (number of bits) and a, */ /* if present, indicates that the endian side is a pointer to an */ /* array of uint8_t bytes instead of an integer of the specified length. */ /* h refers to the host's ordering method. */ /* So, to convert a 32-bit integer stored in a buffer in little-endian */ /* format into a uint32_t usable on this machine, you could use: */ /* uint32_t value = le32atoh(&buf[3]); */ /* To put that value back into the buffer, you could use: */ /* htole32a(&buf[3], value); */ /* Define aliases for the standard byte swapping macros */ /* Arguments to these macros must be properly aligned on natural word */ /* boundaries in order to work properly on all architectures */ #ifndef htobe16 # define htobe16(x) htons(x) #endif #ifndef htobe32 # define htobe32(x) htonl(x) #endif #ifndef be16toh # define be16toh(x) ntohs(x) #endif #ifndef be32toh # define be32toh(x) ntohl(x) #endif #define HTOBE16(x) (x) = htobe16(x) #define HTOBE32(x) (x) = htobe32(x) #define BE32TOH(x) (x) = be32toh(x) #define BE16TOH(x) (x) = be16toh(x) EOF if test $ac_cv_c_bigendian = yes; then cat >> "$1" << EOF /* Define our own extended byte swapping macros for big-endian machines */ #ifndef htole16 # define htole16(x) swap16(x) #endif #ifndef htole32 # define htole32(x) swap32(x) #endif #ifndef le16toh # define le16toh(x) swap16(x) #endif #ifndef le32toh # define le32toh(x) swap32(x) #endif #ifndef le64toh # define le64toh(x) swap64(x) #endif #ifndef htobe64 # define htobe64(x) (x) #endif #ifndef be64toh # define be64toh(x) (x) #endif #define HTOLE16(x) (x) = htole16(x) #define HTOLE32(x) (x) = htole32(x) #define LE16TOH(x) (x) = le16toh(x) #define LE32TOH(x) (x) = le32toh(x) #define LE64TOH(x) (x) = le64toh(x) #define HTOBE64(x) (void) (x) #define BE64TOH(x) (void) (x) EOF else cat >> "$1" << EOF /* On little endian machines, these macros are null */ #ifndef htole16 # define htole16(x) (x) #endif #ifndef htole32 # define htole32(x) (x) #endif #ifndef htole64 # define htole64(x) (x) #endif #ifndef le16toh # define le16toh(x) (x) #endif #ifndef le32toh # define le32toh(x) (x) #endif #ifndef le64toh # define le64toh(x) (x) #endif #define HTOLE16(x) (void) (x) #define HTOLE32(x) (void) (x) #define HTOLE64(x) (void) (x) #define LE16TOH(x) (void) (x) #define LE32TOH(x) (void) (x) #define LE64TOH(x) (void) (x) /* These don't have standard aliases */ #ifndef htobe64 # define htobe64(x) swap64(x) #endif #ifndef be64toh # define be64toh(x) swap64(x) #endif #define HTOBE64(x) (x) = htobe64(x) #define BE64TOH(x) (x) = be64toh(x) EOF fi fi cat >> "$1" << EOF /* Define the C99 standard length-specific integer types */ #include <_stdint.h> EOF case "${effective_target}" in i[3456]86-*) cat >> "$1" << EOF /* Here are some macros to create integers from a byte array */ /* These are used to get and put integers from/into a uint8_t array */ /* with a specific endianness. This is the most portable way to generate */ /* and read messages to a network or serial device. Each member of a */ /* packet structure must be handled separately. */ /* The i386 and compatibles can handle unaligned memory access, */ /* so use the optimized macros above to do this job */ #ifndef be16atoh # define be16atoh(x) be16toh(*(uint16_t*)(x)) #endif #ifndef be32atoh # define be32atoh(x) be32toh(*(uint32_t*)(x)) #endif #ifndef be64atoh # define be64atoh(x) be64toh(*(uint64_t*)(x)) #endif #ifndef le16atoh # define le16atoh(x) le16toh(*(uint16_t*)(x)) #endif #ifndef le32atoh # define le32atoh(x) le32toh(*(uint32_t*)(x)) #endif #ifndef le64atoh # define le64atoh(x) le64toh(*(uint64_t*)(x)) #endif #ifndef htob16a # define htobe16a(a,x) *(uint16_t*)(a) = htobe16(x) #endif #ifndef htobe32a # define htobe32a(a,x) *(uint32_t*)(a) = htobe32(x) #endif #ifndef htobe64a # define htobe64a(a,x) *(uint64_t*)(a) = htobe64(x) #endif #ifndef htole16a # define htole16a(a,x) *(uint16_t*)(a) = htole16(x) #endif #ifndef htole32a # define htole32a(a,x) *(uint32_t*)(a) = htole32(x) #endif #ifndef htole64a # define htole64a(a,x) *(uint64_t*)(a) = htole64(x) #endif EOF ;; *) cat >> "$1" << EOF /* Here are some macros to create integers from a byte array */ /* These are used to get and put integers from/into a uint8_t array */ /* with a specific endianness. This is the most portable way to generate */ /* and read messages to a network or serial device. Each member of a */ /* packet structure must be handled separately. */ /* Non-optimized but portable macros */ #define be16atoh(x) ((uint16_t)(((x)[0]<<8)|(x)[1])) #define be32atoh(x) ((uint32_t)(((x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])) #define be64atoh_x(x,off,shift) (((uint64_t)((x)[off]))<<shift) #define be64atoh(x) ((uint64_t)(be64atoh_x(x,0,56)|be64atoh_x(x,1,48)|be64atoh_x(x,2,40)| \\ be64atoh_x(x,3,32)|be64atoh_x(x,4,24)|be64atoh_x(x,5,16)|be64atoh_x(x,6,8)|((x)[7]))) #define le16atoh(x) ((uint16_t)(((x)[1]<<8)|(x)[0])) #define le32atoh(x) ((uint32_t)(((x)[3]<<24)|((x)[2]<<16)|((x)[1]<<8)|(x)[0])) #define le64atoh_x(x,off,shift) (((uint64_t)(x)[off])<<shift) #define le64atoh(x) ((uint64_t)(le64atoh_x(x,7,56)|le64atoh_x(x,6,48)|le64atoh_x(x,5,40)| \\ le64atoh_x(x,4,32)|le64atoh_x(x,3,24)|le64atoh_x(x,2,16)|le64atoh_x(x,1,8)|((x)[0]))) #define htobe16a(a,x) (a)[0]=(uint8_t)((x)>>8), (a)[1]=(uint8_t)(x) #define htobe32a(a,x) (a)[0]=(uint8_t)((x)>>24), (a)[1]=(uint8_t)((x)>>16), \\ (a)[2]=(uint8_t)((x)>>8), (a)[3]=(uint8_t)(x) #define htobe64a(a,x) (a)[0]=(uint8_t)((x)>>56), (a)[1]=(uint8_t)((x)>>48), \\ (a)[2]=(uint8_t)((x)>>40), (a)[3]=(uint8_t)((x)>>32), \\ (a)[4]=(uint8_t)((x)>>24), (a)[5]=(uint8_t)((x)>>16), \\ (a)[6]=(uint8_t)((x)>>8), (a)[7]=(uint8_t)(x) #define htole16a(a,x) (a)[1]=(uint8_t)((x)>>8), (a)[0]=(uint8_t)(x) #define htole32a(a,x) (a)[3]=(uint8_t)((x)>>24), (a)[2]=(uint8_t)((x)>>16), \\ (a)[1]=(uint8_t)((x)>>8), (a)[0]=(uint8_t)(x) #define htole64a(a,x) (a)[7]=(uint8_t)((x)>>56), (a)[6]=(uint8_t)((x)>>48), \\ (a)[5]=(uint8_t)((x)>>40), (a)[4]=(uint8_t)((x)>>32), \\ (a)[3]=(uint8_t)((x)>>24), (a)[2]=(uint8_t)((x)>>16), \\ (a)[1]=(uint8_t)((x)>>8), (a)[0]=(uint8_t)(x) EOF ;; esac ] cat >> "$1" << EOF #endif /*__BYTEORDER_H*/ EOF]) �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������