summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHa Thach <[email protected]>2025-10-02 19:58:12 +0700
committerGitHub <[email protected]>2025-10-02 19:58:12 +0700
commitc1bf19ed6cf1eaa791f221c1bc5ce4b3d069f76d (patch)
tree60fe2447d25af0ab07b80f435d79a147cf717d8f
parentf655d210b17fad3d2e95c7ef07e114a2f0b6dac6 (diff)
parent610f353d8d602c3192f9edc03669ab792056f7da (diff)
Merge pull request #3023 from ennebi/mtp
Add support for MTP device class
-rw-r--r--.github/workflows/build.yml13
-rw-r--r--README.rst1
-rw-r--r--docs/reference/getting_started.rst2
-rw-r--r--examples/device/CMakeLists.txt1
-rw-r--r--examples/device/cdc_msc/src/usb_descriptors.c2
-rw-r--r--examples/device/cdc_msc_freertos/src/usb_descriptors.c2
-rw-r--r--examples/device/cdc_uac2/src/usb_descriptors.c2
-rw-r--r--examples/device/hid_composite/src/usb_descriptors.c2
-rw-r--r--examples/device/hid_composite_freertos/src/usb_descriptors.c2
-rw-r--r--examples/device/mtp/CMakeLists.txt39
-rw-r--r--examples/device/mtp/CMakePresets.json6
-rw-r--r--examples/device/mtp/Makefile11
-rw-r--r--examples/device/mtp/prj.conf6
-rw-r--r--examples/device/mtp/skip.txt1
-rw-r--r--examples/device/mtp/src/main.c110
-rw-r--r--examples/device/mtp/src/mtp_fs_example.c624
-rw-r--r--examples/device/mtp/src/tinyusb_logo_png.h175
-rw-r--r--examples/device/mtp/src/tusb_config.h139
-rw-r--r--examples/device/mtp/src/usb_descriptors.c255
-rw-r--r--examples/dual/host_hid_to_device_cdc/src/usb_descriptors.c2
-rw-r--r--examples/dual/host_info_to_device_cdc/src/usb_descriptors.c2
-rw-r--r--hw/bsp/espressif/components/tinyusb_src/CMakeLists.txt1
-rw-r--r--hw/bsp/rp2040/family.cmake1
-rw-r--r--hw/bsp/samd11/family.cmake1
-rw-r--r--lib/rt-thread/SConscript2
-rw-r--r--src/CMakeLists.txt1
-rw-r--r--src/class/mtp/mtp.h888
-rw-r--r--src/class/mtp/mtp_device.c540
-rw-r--r--src/class/mtp/mtp_device.h167
-rw-r--r--src/common/tusb_common.h1
-rw-r--r--src/device/usbd.c14
-rw-r--r--src/device/usbd.h19
-rw-r--r--src/tinyusb.mk1
-rw-r--r--src/tusb.h4
-rw-r--r--src/tusb_option.h4
-rw-r--r--test/fuzz/device/cdc/src/usb_descriptors.cc2
-rw-r--r--test/fuzz/device/msc/src/usb_descriptors.cc2
-rw-r--r--test/fuzz/device/net/src/usb_descriptors.cc2
-rw-r--r--test/fuzz/rules.mk1
-rwxr-xr-xtest/hil/hil_test.py119
-rw-r--r--test/hil/pymtp.py1290
-rw-r--r--tools/file2carray.py45
-rw-r--r--tools/iar_template.ipcf5
43 files changed, 4475 insertions, 32 deletions
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index ff59421ce..9243c866d 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -199,25 +199,28 @@ jobs:
runs-on: [self-hosted, X64, hathach, hardware-in-the-loop]
steps:
- name: Clean workspace
- if: github.run_attempt == '1'
run: |
echo "Cleaning up for the first run"
rm -rf "${{ github.workspace }}"
mkdir -p "${{ github.workspace }}"
- name: Checkout TinyUSB
- if: github.run_attempt == '1'
uses: actions/checkout@v4
- with:
- sparse-checkout: test/hil
- name: Download Artifacts
- if: github.run_attempt == '1'
uses: actions/download-artifact@v4
with:
path: cmake-build
merge-multiple: true
+ - name: Cache skip list
+ uses: actions/cache@v4
+ with:
+ path: ${{ env.HIL_JSON }}.skip
+ key: hil-skip-${{ github.run_id }}-${{ github.run_attempt }}
+ restore-keys: |
+ hil-skip-${{ github.run_id }}-
+
- name: Test on actual hardware
run: |
ls cmake-build/
diff --git a/README.rst b/README.rst
index 66fbcaa10..16de684a6 100644
--- a/README.rst
+++ b/README.rst
@@ -60,6 +60,7 @@ Supports multiple device configurations by dynamically changing USB descriptors,
- Human Interface Device (HID): Generic (In & Out), Keyboard, Mouse, Gamepad etc ...
- Mass Storage Class (MSC): with multiple LUNs
- Musical Instrument Digital Interface (MIDI)
+- Media Transfer Protocol (MTP/PTP)
- Network with RNDIS, Ethernet Control Model (ECM), Network Control Model (NCM)
- Test and Measurement Class (USBTMC)
- Video class 1.5 (UVC): work in progress
diff --git a/docs/reference/getting_started.rst b/docs/reference/getting_started.rst
index bb9ff1cb4..f1a755804 100644
--- a/docs/reference/getting_started.rst
+++ b/docs/reference/getting_started.rst
@@ -178,7 +178,7 @@ By default log message is printed via on-board UART which is slow and take lots
* Pros: work with most if not all MCUs
* Software viewer is JLink RTT Viewer/Client/Logger which is bundled with JLink driver package.
-* ``LOGGER=swo``\ : Use dedicated SWO pin of ARM Cortex SWD debug header.
+* ``LOGGER=swo`` : Use dedicated SWO pin of ARM Cortex SWD debug header.
* Cons: only work with ARM Cortex MCUs minus M0
* Pros: should be compatible with more debugger that support SWO.
diff --git a/examples/device/CMakeLists.txt b/examples/device/CMakeLists.txt
index bb7dd0a0f..eb625ea51 100644
--- a/examples/device/CMakeLists.txt
+++ b/examples/device/CMakeLists.txt
@@ -26,6 +26,7 @@ family_add_subdirectory(hid_generic_inout)
family_add_subdirectory(hid_multiple_interface)
family_add_subdirectory(midi_test)
family_add_subdirectory(msc_dual_lun)
+family_add_subdirectory(mtp)
family_add_subdirectory(net_lwip_webserver)
family_add_subdirectory(uac2_headset)
family_add_subdirectory(uac2_speaker_fb)
diff --git a/examples/device/cdc_msc/src/usb_descriptors.c b/examples/device/cdc_msc/src/usb_descriptors.c
index edcee0462..597a6b1e6 100644
--- a/examples/device/cdc_msc/src/usb_descriptors.c
+++ b/examples/device/cdc_msc/src/usb_descriptors.c
@@ -184,7 +184,7 @@ uint8_t const *tud_descriptor_other_speed_configuration_cb(uint8_t index) {
(void) index; // for multiple configurations
// if link speed is high return fullspeed config, and vice versa
- // Note: the descriptor type is OHER_SPEED_CONFIG instead of CONFIG
+ // Note: the descriptor type is OTHER_SPEED_CONFIG instead of CONFIG
memcpy(desc_other_speed_config,
(tud_speed_get() == TUSB_SPEED_HIGH) ? desc_fs_configuration : desc_hs_configuration,
CONFIG_TOTAL_LEN);
diff --git a/examples/device/cdc_msc_freertos/src/usb_descriptors.c b/examples/device/cdc_msc_freertos/src/usb_descriptors.c
index a55fa3675..cb440c209 100644
--- a/examples/device/cdc_msc_freertos/src/usb_descriptors.c
+++ b/examples/device/cdc_msc_freertos/src/usb_descriptors.c
@@ -186,7 +186,7 @@ uint8_t const* tud_descriptor_other_speed_configuration_cb(uint8_t index) {
(void) index; // for multiple configurations
// if link speed is high return fullspeed config, and vice versa
- // Note: the descriptor type is OHER_SPEED_CONFIG instead of CONFIG
+ // Note: the descriptor type is OTHER_SPEED_CONFIG instead of CONFIG
memcpy(desc_other_speed_config,
(tud_speed_get() == TUSB_SPEED_HIGH) ? desc_fs_configuration : desc_hs_configuration,
CONFIG_TOTAL_LEN);
diff --git a/examples/device/cdc_uac2/src/usb_descriptors.c b/examples/device/cdc_uac2/src/usb_descriptors.c
index 22d3cf05a..da55bdb5a 100644
--- a/examples/device/cdc_uac2/src/usb_descriptors.c
+++ b/examples/device/cdc_uac2/src/usb_descriptors.c
@@ -176,7 +176,7 @@ uint8_t const *tud_descriptor_other_speed_configuration_cb(uint8_t index) {
(void) index; // for multiple configurations
// if link speed is high return fullspeed config, and vice versa
- // Note: the descriptor type is OHER_SPEED_CONFIG instead of CONFIG
+ // Note: the descriptor type is OTHER_SPEED_CONFIG instead of CONFIG
memcpy(desc_other_speed_config,
(tud_speed_get() == TUSB_SPEED_HIGH) ? desc_fs_configuration : desc_hs_configuration,
CONFIG_TOTAL_LEN);
diff --git a/examples/device/hid_composite/src/usb_descriptors.c b/examples/device/hid_composite/src/usb_descriptors.c
index 15c6e1f73..ce7fbd13f 100644
--- a/examples/device/hid_composite/src/usb_descriptors.c
+++ b/examples/device/hid_composite/src/usb_descriptors.c
@@ -154,7 +154,7 @@ uint8_t const* tud_descriptor_other_speed_configuration_cb(uint8_t index)
{
(void) index; // for multiple configurations
- // other speed config is basically configuration with type = OHER_SPEED_CONFIG
+ // other speed config is basically configuration with type = OTHER_SPEED_CONFIG
memcpy(desc_other_speed_config, desc_configuration, CONFIG_TOTAL_LEN);
desc_other_speed_config[1] = TUSB_DESC_OTHER_SPEED_CONFIG;
diff --git a/examples/device/hid_composite_freertos/src/usb_descriptors.c b/examples/device/hid_composite_freertos/src/usb_descriptors.c
index 85820de55..3f231fecc 100644
--- a/examples/device/hid_composite_freertos/src/usb_descriptors.c
+++ b/examples/device/hid_composite_freertos/src/usb_descriptors.c
@@ -153,7 +153,7 @@ uint8_t const* tud_descriptor_other_speed_configuration_cb(uint8_t index)
{
(void) index; // for multiple configurations
- // other speed config is basically configuration with type = OHER_SPEED_CONFIG
+ // other speed config is basically configuration with type = OTHER_SPEED_CONFIG
memcpy(desc_other_speed_config, desc_configuration, CONFIG_TOTAL_LEN);
desc_other_speed_config[1] = TUSB_DESC_OTHER_SPEED_CONFIG;
diff --git a/examples/device/mtp/CMakeLists.txt b/examples/device/mtp/CMakeLists.txt
new file mode 100644
index 000000000..e91eb8fd9
--- /dev/null
+++ b/examples/device/mtp/CMakeLists.txt
@@ -0,0 +1,39 @@
+cmake_minimum_required(VERSION 3.20)
+
+include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake)
+
+# gets PROJECT name for the example (e.g. <BOARD>-<DIR_NAME>)
+family_get_project_name(PROJECT ${CMAKE_CURRENT_LIST_DIR})
+
+project(${PROJECT} C CXX ASM)
+
+# Checks this example is valid for the family and initializes the project
+family_initialize_project(${PROJECT} ${CMAKE_CURRENT_LIST_DIR})
+
+# Espressif has its own cmake build system
+if(FAMILY STREQUAL "espressif")
+ return()
+endif()
+
+if (RTOS STREQUAL zephyr)
+ set(EXE_NAME app)
+else()
+ set(EXE_NAME ${PROJECT})
+ add_executable(${EXE_NAME})
+endif()
+
+# Example source
+target_sources(${EXE_NAME} PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/main.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/mtp_fs_example.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/usb_descriptors.c
+ )
+
+# Example include
+target_include_directories(${EXE_NAME} PUBLIC
+ ${CMAKE_CURRENT_SOURCE_DIR}/src
+ )
+
+# Configure compilation flags and libraries for the example without RTOS.
+# See the corresponding function in hw/bsp/FAMILY/family.cmake for details.
+family_configure_device_example(${EXE_NAME} ${RTOS})
diff --git a/examples/device/mtp/CMakePresets.json b/examples/device/mtp/CMakePresets.json
new file mode 100644
index 000000000..5cd8971e9
--- /dev/null
+++ b/examples/device/mtp/CMakePresets.json
@@ -0,0 +1,6 @@
+{
+ "version": 6,
+ "include": [
+ "../../../hw/bsp/BoardPresets.json"
+ ]
+}
diff --git a/examples/device/mtp/Makefile b/examples/device/mtp/Makefile
new file mode 100644
index 000000000..7fa475da5
--- /dev/null
+++ b/examples/device/mtp/Makefile
@@ -0,0 +1,11 @@
+include ../../build_system/make/make.mk
+
+INC += \
+ src \
+ $(TOP)/hw \
+
+# Example source
+EXAMPLE_SOURCE += $(wildcard src/*.c)
+SRC_C += $(addprefix $(CURRENT_PATH)/, $(EXAMPLE_SOURCE))
+
+include ../../build_system/make/rules.mk
diff --git a/examples/device/mtp/prj.conf b/examples/device/mtp/prj.conf
new file mode 100644
index 000000000..2f5139d9d
--- /dev/null
+++ b/examples/device/mtp/prj.conf
@@ -0,0 +1,6 @@
+CONFIG_GPIO=y
+CONFIG_FPU=y
+CONFIG_NO_OPTIMIZATIONS=y
+CONFIG_UART_INTERRUPT_DRIVEN=y
+CONFIG_NRFX_POWER=y
+CONFIG_NRFX_UARTE0=y
diff --git a/examples/device/mtp/skip.txt b/examples/device/mtp/skip.txt
new file mode 100644
index 000000000..37a4485d7
--- /dev/null
+++ b/examples/device/mtp/skip.txt
@@ -0,0 +1 @@
+board:cynthion_d11
diff --git a/examples/device/mtp/src/main.c b/examples/device/mtp/src/main.c
new file mode 100644
index 000000000..57d1535b2
--- /dev/null
+++ b/examples/device/mtp/src/main.c
@@ -0,0 +1,110 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2025 Ennebi Elettronica (https://ennebielettronica.com)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "bsp/board_api.h"
+#include "tusb.h"
+
+//--------------------------------------------------------------------+
+// MACRO CONSTANT TYPEDEF PROTYPES
+//--------------------------------------------------------------------+
+
+/* Blink pattern
+ * - 250 ms : device not mounted
+ * - 1000 ms : device mounted
+ * - 2500 ms : device is suspended
+ */
+enum {
+ BLINK_NOT_MOUNTED = 250,
+ BLINK_MOUNTED = 1000,
+ BLINK_SUSPENDED = 2500,
+};
+
+static uint32_t blink_interval_ms = BLINK_NOT_MOUNTED;
+
+void led_blinking_task(void);
+
+/*------------- MAIN -------------*/
+int main(void) {
+ board_init();
+
+ // init device stack on configured roothub port
+ tusb_rhport_init_t dev_init = {
+ .role = TUSB_ROLE_DEVICE,
+ .speed = TUSB_SPEED_AUTO
+ };
+ tusb_init(BOARD_TUD_RHPORT, &dev_init);
+ board_init_after_tusb();
+
+ while (1) {
+ tud_task(); // tinyusb device task
+ led_blinking_task();
+ }
+}
+
+//--------------------------------------------------------------------+
+// Device callbacks
+//--------------------------------------------------------------------+
+
+// Invoked when device is mounted
+void tud_mount_cb(void) {
+ blink_interval_ms = BLINK_MOUNTED;
+}
+
+// Invoked when device is unmounted
+void tud_umount_cb(void) {
+ blink_interval_ms = BLINK_NOT_MOUNTED;
+}
+
+// Invoked when usb bus is suspended
+// remote_wakeup_en : if host allow us to perform remote wakeup
+// Within 7ms, device must draw an average of current less than 2.5 mA from bus
+void tud_suspend_cb(bool remote_wakeup_en) {
+ (void) remote_wakeup_en;
+ blink_interval_ms = BLINK_SUSPENDED;
+}
+
+// Invoked when usb bus is resumed
+void tud_resume_cb(void) {
+ blink_interval_ms = tud_mounted() ? BLINK_MOUNTED : BLINK_NOT_MOUNTED;
+}
+
+//--------------------------------------------------------------------+
+// BLINKING TASK
+//--------------------------------------------------------------------+
+void led_blinking_task(void) {
+ static uint32_t start_ms = 0;
+ static bool led_state = false;
+
+ // Blink every interval ms
+ if (board_millis() - start_ms < blink_interval_ms) return; // not enough time
+ start_ms += blink_interval_ms;
+
+ board_led_write(led_state);
+ led_state = 1 - led_state; // toggle
+}
diff --git a/examples/device/mtp/src/mtp_fs_example.c b/examples/device/mtp/src/mtp_fs_example.c
new file mode 100644
index 000000000..5f56ca24d
--- /dev/null
+++ b/examples/device/mtp/src/mtp_fs_example.c
@@ -0,0 +1,624 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2025 Ennebi Elettronica (https://ennebielettronica.com)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ */
+
+#include "bsp/board_api.h"
+#include "tusb.h"
+
+#include "tinyusb_logo_png.h"
+
+//--------------------------------------------------------------------+
+// Dataset
+//--------------------------------------------------------------------+
+
+//------------- device info -------------//
+#define DEV_INFO_MANUFACTURER "TinyUSB"
+#define DEV_INFO_MODEL "MTP Example"
+#define DEV_INFO_VERSION "1.0"
+#define DEV_PROP_FRIENDLY_NAME "TinyUSB MTP"
+
+//------------- storage info -------------//
+#define STORAGE_DESCRIPTRION { 'd', 'i', 's', 'k', 0 }
+#define VOLUME_IDENTIFIER { 'v', 'o', 'l', 0 }
+
+typedef MTP_STORAGE_INFO_STRUCT(TU_ARRAY_SIZE((uint16_t[]) STORAGE_DESCRIPTRION),
+ TU_ARRAY_SIZE(((uint16_t[])VOLUME_IDENTIFIER))
+) storage_info_t;
+
+storage_info_t storage_info = {
+ #ifdef CFG_EXAMPLE_MTP_READONLY
+ .storage_type = MTP_STORAGE_TYPE_FIXED_ROM,
+ #else
+ .storage_type = MTP_STORAGE_TYPE_FIXED_RAM,
+ #endif
+
+ .filesystem_type = MTP_FILESYSTEM_TYPE_GENERIC_HIERARCHICAL,
+ .access_capability = MTP_ACCESS_CAPABILITY_READ_WRITE,
+ .max_capacity_in_bytes = 0, // calculated at runtime
+ .free_space_in_bytes = 0, // calculated at runtime
+ .free_space_in_objects = 0, // calculated at runtime
+ .storage_description = {
+ .count = (TU_FIELD_SZIE(storage_info_t, storage_description)-1) / sizeof(uint16_t),
+ .utf16 = STORAGE_DESCRIPTRION
+ },
+ .volume_identifier = {
+ .count = (TU_FIELD_SZIE(storage_info_t, volume_identifier)-1) / sizeof(uint16_t),
+ .utf16 = VOLUME_IDENTIFIER
+ }
+};
+
+//--------------------------------------------------------------------+
+// MTP FILESYSTEM
+//--------------------------------------------------------------------+
+// only allow to add 1 more object to make it simpler to manage memory
+#define FS_MAX_FILE_COUNT 3UL
+#define FS_MAX_FILENAME_LEN 16
+
+#ifdef CFG_EXAMPLE_MTP_READONLY
+ #define FS_MAX_CAPACITY_BYTES 0
+#else
+ #define FS_MAX_CAPACITY_BYTES (4 * 1024UL)
+
+ // object data buffer (excluding 2 predefined files) with simple allocation pointer
+ uint8_t fs_buf[FS_MAX_CAPACITY_BYTES];
+#endif
+
+#define FS_FIXED_DATETIME "20250808T173500.0" // "YYYYMMDDTHHMMSS.s"
+#define README_TXT_CONTENT "TinyUSB MTP Filesystem example"
+
+typedef struct {
+ uint16_t name[FS_MAX_FILENAME_LEN];
+ uint16_t object_format;
+ uint16_t protection_status;
+ uint32_t image_pix_width;
+ uint32_t image_pix_height;
+ uint32_t image_bit_depth;
+ uint32_t parent;
+ uint16_t association_type;
+ uint32_t size;
+ uint8_t* data;
+} fs_file_t;
+
+// Files system, handle is index + 1
+static fs_file_t fs_objects[FS_MAX_FILE_COUNT] = {
+ {
+ .name = { 'r', 'e', 'a', 'd', 'm', 'e', '.', 't', 'x', 't', 0 }, // readme.txt
+ .object_format = MTP_OBJ_FORMAT_TEXT,
+ .protection_status = MTP_PROTECTION_STATUS_READ_ONLY,
+ .image_pix_width = 0,
+ .image_pix_height = 0,
+ .image_bit_depth = 0,
+ .parent = 0,
+ .association_type = MTP_ASSOCIATION_UNDEFINED,
+ .data = (uint8_t*) (uintptr_t) README_TXT_CONTENT,
+ .size = sizeof(README_TXT_CONTENT)-1
+ },
+ {
+ .name = { 't', 'i', 'n', 'y', 'u', 's', 'b', '.', 'p', 'n', 'g', 0 }, // "tinyusb.png"
+ .object_format = MTP_OBJ_FORMAT_PNG,
+ .protection_status = MTP_PROTECTION_STATUS_READ_ONLY,
+ .image_pix_width = 128,
+ .image_pix_height = 64,
+ .image_bit_depth = 32,
+ .parent = 0,
+ .association_type = MTP_ASSOCIATION_UNDEFINED,
+ .data = (uint8_t*) (uintptr_t) logo_bin,
+ .size = logo_len,
+ }
+};
+
+enum {
+ SUPPORTED_STORAGE_ID = 0x00010001u // physical = 1, logical = 1
+};
+
+static int32_t fs_get_device_info(tud_mtp_cb_data_t* cb_data);
+static int32_t fs_open_close_session(tud_mtp_cb_data_t* cb_data);
+static int32_t fs_get_storage_ids(tud_mtp_cb_data_t* cb_data);
+static int32_t fs_get_storage_info(tud_mtp_cb_data_t* cb_data);
+static int32_t fs_get_device_properties(tud_mtp_cb_data_t* cb_data);
+static int32_t fs_get_object_handles(tud_mtp_cb_data_t* cb_data);
+static int32_t fs_get_object_info(tud_mtp_cb_data_t* cb_data);
+static int32_t fs_get_object(tud_mtp_cb_data_t* cb_data);
+static int32_t fs_delete_object(tud_mtp_cb_data_t* cb_data);
+static int32_t fs_send_object_info(tud_mtp_cb_data_t* cb_data);
+static int32_t fs_send_object(tud_mtp_cb_data_t* cb_data);
+
+typedef int32_t (*fs_op_handler_t)(tud_mtp_cb_data_t* cb_data);
+typedef struct {
+ uint32_t op_code;
+ fs_op_handler_t handler;
+}fs_op_handler_dict_t;
+
+fs_op_handler_dict_t fs_op_handler_dict[] = {
+ { MTP_OP_GET_DEVICE_INFO, fs_get_device_info },
+ { MTP_OP_OPEN_SESSION, fs_open_close_session },
+ { MTP_OP_CLOSE_SESSION, fs_open_close_session },
+ { MTP_OP_GET_STORAGE_IDS, fs_get_storage_ids },
+ { MTP_OP_GET_STORAGE_INFO, fs_get_storage_info },
+ { MTP_OP_GET_DEVICE_PROP_DESC, fs_get_device_properties },
+ { MTP_OP_GET_DEVICE_PROP_VALUE, fs_get_device_properties },
+ { MTP_OP_GET_OBJECT_HANDLES, fs_get_object_handles },
+ { MTP_OP_GET_OBJECT_INFO, fs_get_object_info },
+ { MTP_OP_GET_OBJECT, fs_get_object },
+ { MTP_OP_DELETE_OBJECT, fs_delete_object },
+ { MTP_OP_SEND_OBJECT_INFO, fs_send_object_info },
+ { MTP_OP_SEND_OBJECT, fs_send_object },
+};
+
+static bool is_session_opened = false;
+static uint32_t send_obj_handle = 0;
+
+//--------------------------------------------------------------------+
+//
+//--------------------------------------------------------------------+
+// Get pointer to object info from handle
+static inline fs_file_t* fs_get_file(uint32_t handle) {
+ if (handle == 0 || handle > FS_MAX_FILE_COUNT) {
+ return NULL;
+ }
+ return &fs_objects[handle-1];
+}
+
+static inline bool fs_file_exist(fs_file_t* f) {
+ return f->name[0] != 0;
+}
+
+// Get the number of allocated nodes in filesystem
+static uint32_t fs_get_file_count(void) {
+ uint32_t count = 0;
+ for (size_t i = 0; i < FS_MAX_FILE_COUNT; i++) {
+ if (fs_file_exist(&fs_objects[i])) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static inline fs_file_t* fs_create_file(void) {
+ for (size_t i = 0; i < FS_MAX_FILE_COUNT; i++) {
+ fs_file_t* f = &fs_objects[i];
+ if (!fs_file_exist(f)) {
+ send_obj_handle = i + 1;
+ return f;
+ }
+ }
+ return NULL;
+}
+
+// simple malloc
+static inline uint8_t* fs_malloc(size_t size) {
+#ifdef CFG_EXAMPLE_MTP_READONLY
+ (void) size;
+ return NULL;
+#else
+ if (size > FS_MAX_CAPACITY_BYTES) {
+ return NULL;
+ }
+ return fs_buf;
+#endif
+}
+
+//--------------------------------------------------------------------+
+// Control Request callback
+//--------------------------------------------------------------------+
+bool tud_mtp_request_cancel_cb(tud_mtp_request_cb_data_t* cb_data) {
+ mtp_request_reset_cancel_data_t cancel_data;
+ memcpy(&cancel_data, cb_data->buf, sizeof(cancel_data));
+ (void) cancel_data.code;
+ (void ) cancel_data.transaction_id;
+ return true;
+}
+
+// Invoked when received Device Reset request
+// return false to stall the request
+bool tud_mtp_request_device_reset_cb(tud_mtp_request_cb_data_t* cb_data) {
+ (void) cb_data;
+ return true;
+}
+
+// Invoked when received Get Extended Event request. Application fill callback data's buffer for response
+// return negative to stall the request
+int32_t tud_mtp_request_get_extended_event_cb(tud_mtp_request_cb_data_t* cb_data) {
+ (void) cb_data;
+ return false; // not implemented yet
+}
+
+// Invoked when received Get DeviceStatus request. Application fill callback data's buffer for response
+// return negative to stall the request
+int32_t tud_mtp_request_get_device_status_cb(tud_mtp_request_cb_data_t* cb_data) {
+ uint16_t* buf16 = (uint16_t*)(uintptr_t) cb_data->buf;
+ buf16[0] = 4; // length
+ buf16[1] = MTP_RESP_OK; // status
+ return 4;
+}
+
+//--------------------------------------------------------------------+
+// Bulk Only Protocol
+//--------------------------------------------------------------------+
+int32_t tud_mtp_command_received_cb(tud_mtp_cb_data_t* cb_data) {
+ const mtp_container_command_t* command = cb_data->command_container;
+ mtp_container_info_t* io_container = &cb_data->io_container;
+ fs_op_handler_t handler = NULL;
+ for (size_t i = 0; i < TU_ARRAY_SIZE(fs_op_handler_dict); i++) {
+ if (fs_op_handler_dict[i].op_code == command->header.code) {
+ handler = fs_op_handler_dict[i].handler;
+ break;
+ }
+ }
+
+ int32_t resp_code;
+ if (handler == NULL) {
+ resp_code = MTP_RESP_OPERATION_NOT_SUPPORTED;
+ } else {
+ resp_code = handler(cb_data);
+ if (resp_code > MTP_RESP_UNDEFINED) {
+ // send response if needed
+ io_container->header->code = (uint16_t)resp_code;
+ tud_mtp_response_send(io_container);
+ }
+ }
+
+ return resp_code;
+}
+
+int32_t tud_mtp_data_xfer_cb(tud_mtp_cb_data_t* cb_data) {
+ const mtp_container_command_t* command = cb_data->command_container;
+ mtp_container_info_t* io_container = &cb_data->io_container;
+
+ fs_op_handler_t handler = NULL;
+ for (size_t i = 0; i < TU_ARRAY_SIZE(fs_op_handler_dict); i++) {
+ if (fs_op_handler_dict[i].op_code == command->header.code) {
+ handler = fs_op_handler_dict[i].handler;
+ break;
+ }
+ }
+
+ int32_t resp_code;
+ if (handler == NULL) {
+ resp_code = MTP_RESP_OPERATION_NOT_SUPPORTED;
+ } else {
+ resp_code = handler(cb_data);
+ if (resp_code > MTP_RESP_UNDEFINED) {
+ // send response if needed
+ io_container->header->code = (uint16_t)resp_code;
+ tud_mtp_response_send(io_container);
+ }
+ }
+
+ return 0;
+}
+
+int32_t tud_mtp_data_complete_cb(tud_mtp_cb_data_t* cb_data) {
+ const mtp_container_command_t* command = cb_data->command_container;
+ mtp_container_info_t* resp = &cb_data->io_container;
+ switch (command->header.code) {
+ case MTP_OP_SEND_OBJECT_INFO: {
+ fs_file_t* f = fs_get_file(send_obj_handle);
+ if (f == NULL) {
+ resp->header->code = MTP_RESP_GENERAL_ERROR;
+ break;
+ }
+ // parameter is: storage id, parent handle, new handle
+ mtp_container_add_uint32(resp, SUPPORTED_STORAGE_ID);
+ mtp_container_add_uint32(resp, f->parent);
+ mtp_container_add_uint32(resp, send_obj_handle);
+ resp->header->code = MTP_RESP_OK;
+ break;
+ }
+
+ default:
+ resp->header->code = (cb_data->xfer_result == XFER_RESULT_SUCCESS) ? MTP_RESP_OK : MTP_RESP_GENERAL_ERROR;
+ break;
+ }
+
+ tud_mtp_response_send(resp);
+ return 0;
+}
+
+int32_t tud_mtp_response_complete_cb(tud_mtp_cb_data_t* cb_data) {
+ (void) cb_data;
+ return 0; // nothing to do
+}
+
+//--------------------------------------------------------------------+
+// File System Handlers
+//--------------------------------------------------------------------+
+static int32_t fs_get_device_info(tud_mtp_cb_data_t* cb_data) {
+ // Device info is already prepared up to playback formats. Application only need to add string fields
+ mtp_container_info_t* io_container = &cb_data->io_container;
+ mtp_container_add_cstring(io_container, DEV_INFO_MANUFACTURER);
+ mtp_container_add_cstring(io_container, DEV_INFO_MODEL);
+ mtp_container_add_cstring(io_container, DEV_INFO_VERSION);
+
+ enum { MAX_SERIAL_NCHARS = 32 };
+ uint16_t serial_utf16[MAX_SERIAL_NCHARS+1];
+ size_t nchars = board_usb_get_serial(serial_utf16, MAX_SERIAL_NCHARS);
+ serial_utf16[tu_min32(nchars, MAX_SERIAL_NCHARS)] = 0; // ensure null termination
+ mtp_container_add_string(io_container, serial_utf16);
+
+ tud_mtp_data_send(io_container);
+ return 0;
+}
+
+static int32_t fs_open_close_session(tud_mtp_cb_data_t* cb_data) {
+ const mtp_container_command_t* command = cb_data->command_container;
+ if (command->header.code == MTP_OP_OPEN_SESSION) {
+ if (is_session_opened) {
+ return MTP_RESP_SESSION_ALREADY_OPEN;
+ }
+ is_session_opened = true;
+ } else { // close session
+ if (!is_session_opened) {
+ return MTP_RESP_SESSION_NOT_OPEN;
+ }
+ is_session_opened = false;
+ }
+ return MTP_RESP_OK;
+}
+
+static int32_t fs_get_storage_ids(tud_mtp_cb_data_t* cb_data) {
+ mtp_container_info_t* io_container = &cb_data->io_container;
+ uint32_t storage_ids [] = { SUPPORTED_STORAGE_ID };
+ mtp_container_add_auint32(io_container, 1, storage_ids);
+ tud_mtp_data_send(io_container);
+ return 0;
+}
+
+static int32_t fs_get_storage_info(tud_mtp_cb_data_t* cb_data) {
+ const mtp_container_command_t* command = cb_data->command_container;
+ mtp_container_info_t* io_container = &cb_data->io_container;
+ const uint32_t storage_id = command->params[0];
+ TU_VERIFY(SUPPORTED_STORAGE_ID == storage_id, -1);
+ // update storage info with current free space
+ storage_info.max_capacity_in_bytes = sizeof(README_TXT_CONTENT) + logo_len + FS_MAX_CAPACITY_BYTES;
+ storage_info.free_space_in_objects = FS_MAX_FILE_COUNT - fs_get_file_count();
+ storage_info.free_space_in_bytes = storage_info.free_space_in_objects ? FS_MAX_CAPACITY_BYTES : 0;
+ mtp_container_add_raw(io_container, &storage_info, sizeof(storage_info));
+ tud_mtp_data_send(io_container);
+ return 0;
+}
+
+static int32_t fs_get_device_properties(tud_mtp_cb_data_t* cb_data) {
+ const mtp_container_command_t* command = cb_data->command_container;
+ mtp_container_info_t* io_container = &cb_data->io_container;
+ const uint16_t dev_prop_code = (uint16_t) command->params[0];
+
+ if (command->header.code == MTP_OP_GET_DEVICE_PROP_DESC) {
+ // get describing dataset
+ mtp_device_prop_desc_header_t device_prop_header;
+ device_prop_header.device_property_code = dev_prop_code;
+ switch (dev_prop_code) {
+ case MTP_DEV_PROP_DEVICE_FRIENDLY_NAME:
+ device_prop_header.datatype = MTP_DATA_TYPE_STR;
+ device_prop_header.get_set = MTP_MODE_GET;
+ mtp_container_add_raw(io_container, &device_prop_header, sizeof(device_prop_header));
+ mtp_container_add_cstring(io_container, DEV_PROP_FRIENDLY_NAME); // factory
+ mtp_container_add_cstring(io_container, DEV_PROP_FRIENDLY_NAME); // current
+ mtp_container_add_uint8(io_container, 0); // no form
+ tud_mtp_data_send(io_container);
+ break;
+
+ default:
+ return MTP_RESP_PARAMETER_NOT_SUPPORTED;
+ }
+ } else {
+ // get value
+ switch (dev_prop_code) {
+ case MTP_DEV_PROP_DEVICE_FRIENDLY_NAME:
+ mtp_container_add_cstring(io_container, DEV_PROP_FRIENDLY_NAME);
+ tud_mtp_data_send(io_container);
+ break;
+
+ default:
+ return MTP_RESP_PARAMETER_NOT_SUPPORTED;
+ }
+ }
+ return 0;
+}
+
+static int32_t fs_get_object_handles(tud_mtp_cb_data_t* cb_data) {
+ const mtp_container_command_t* command = cb_data->command_container;
+ mtp_container_info_t* io_container = &cb_data->io_container;
+
+ const uint32_t storage_id = command->params[0];
+ const uint32_t obj_format = command->params[1]; // optional
+ const uint32_t parent_handle = command->params[2]; // folder handle, 0xFFFFFFFF is root
+ (void)obj_format;
+
+ if (storage_id != 0xFFFFFFFF && storage_id != SUPPORTED_STORAGE_ID) {
+ return MTP_RESP_INVALID_STORAGE_ID;
+ }
+
+ uint32_t handles[FS_MAX_FILE_COUNT] = { 0 };
+ uint32_t count = 0;
+ for (uint8_t i = 0; i < FS_MAX_FILE_COUNT; i++) {
+ fs_file_t* f = &fs_objects[i];
+ if (fs_file_exist(f) &&
+ (parent_handle == f->parent || (parent_handle == 0xFFFFFFFF && f->parent == 0))) {
+ handles[count++] = i + 1; // handle is index + 1
+ }
+ }
+ mtp_container_add_auint32(io_container, count, handles);
+ tud_mtp_data_send(io_container);
+
+ return 0;
+}
+
+static int32_t fs_get_object_info(tud_mtp_cb_data_t* cb_data) {
+ const mtp_container_command_t* command = cb_data->command_container;
+ mtp_container_info_t* io_container = &cb_data->io_container;
+ const uint32_t obj_handle = command->params[0];
+ fs_file_t* f = fs_get_file(obj_handle);
+ if (f == NULL) {
+ return MTP_RESP_INVALID_OBJECT_HANDLE;
+ }
+ mtp_object_info_header_t obj_info_header = {
+ .storage_id = SUPPORTED_STORAGE_ID,
+ .object_format = f->object_format,
+ .protection_status = f->protection_status,
+ .object_compressed_size = f->size,
+ .thumb_format = MTP_OBJ_FORMAT_UNDEFINED,
+ .thumb_compressed_size = 0,
+ .thumb_pix_width = 0,
+ .thumb_pix_height = 0,
+ .image_pix_width = f->image_pix_width,
+ .image_pix_height = f->image_pix_height,
+ .image_bit_depth = f->image_bit_depth,
+ .parent_object = f->parent,
+ .association_type = f->association_type,
+ .association_desc = 0,
+ .sequence_number = 0
+ };
+ mtp_container_add_raw(io_container, &obj_info_header, sizeof(obj_info_header));
+ mtp_container_add_string(io_container, f->name);
+ mtp_container_add_cstring(io_container, FS_FIXED_DATETIME);
+ mtp_container_add_cstring(io_container, FS_FIXED_DATETIME);
+ mtp_container_add_cstring(io_container, ""); // keywords, not used
+ tud_mtp_data_send(io_container);
+
+ return 0;
+}
+
+static int32_t fs_get_object(tud_mtp_cb_data_t* cb_data) {
+ const mtp_container_command_t* command = cb_data->command_container;
+ mtp_container_info_t* io_container = &cb_data->io_container;
+ const uint32_t obj_handle = command->params[0];
+ const fs_file_t* f = fs_get_file(obj_handle);
+ if (f == NULL) {
+ return MTP_RESP_INVALID_OBJECT_HANDLE;
+ }
+
+ if (cb_data->phase == MTP_PHASE_COMMAND) {
+ // If file contents is larger than CFG_TUD_MTP_EP_BUFSIZE, data may only partially is added here
+ // the rest will be sent in tud_mtp_data_more_cb
+ mtp_container_add_raw(io_container, f->data, f->size);
+ tud_mtp_data_send(io_container);
+ } else if (cb_data->phase == MTP_PHASE_DATA) {
+ // continue sending remaining data: file contents offset is xferred byte minus header size
+ const uint32_t offset = cb_data->total_xferred_bytes - sizeof(mtp_container_header_t);
+ const uint32_t xact_len = tu_min32(f->size - offset, io_container->payload_bytes);
+ if (xact_len > 0) {
+ memcpy(io_container->payload, f->data + offset, xact_len);
+ tud_mtp_data_send(io_container);
+ }
+ }
+
+ return 0;
+}
+
+static int32_t fs_send_object_info(tud_mtp_cb_data_t* cb_data) {
+ const mtp_container_command_t* command = cb_data->command_container;
+ mtp_container_info_t* io_container = &cb_data->io_container;
+ const uint32_t storage_id = command->params[0];
+ const uint32_t parent_handle = command->params[1]; // folder handle, 0xFFFFFFFF is root
+ (void) parent_handle;
+
+ if (!is_session_opened) {
+ return MTP_RESP_SESSION_NOT_OPEN;
+ }
+ if (storage_id != 0xFFFFFFFF && storage_id != SUPPORTED_STORAGE_ID) {
+ return MTP_RESP_INVALID_STORAGE_ID;
+ }
+
+ if (cb_data->phase == MTP_PHASE_COMMAND) {
+ tud_mtp_data_receive(io_container);
+ } else if (cb_data->phase == MTP_PHASE_DATA) {
+ mtp_object_info_header_t* obj_info = (mtp_object_info_header_t*) io_container->payload;
+ if (obj_info->storage_id != 0 && obj_info->storage_id != SUPPORTED_STORAGE_ID) {
+ return MTP_RESP_INVALID_STORAGE_ID;
+ }
+
+ if (obj_info->parent_object) {
+ fs_file_t* parent = fs_get_file(obj_info->parent_object);
+ if (parent == NULL || !parent->association_type) {
+ return MTP_RESP_INVALID_PARENT_OBJECT;
+ }
+ }
+
+ uint8_t* f_buf = fs_malloc(obj_info->object_compressed_size);
+ if (f_buf == NULL) {
+ return MTP_RESP_STORE_FULL;
+ }
+ fs_file_t* f = fs_create_file();
+ if (f == NULL) {
+ return MTP_RESP_STORE_FULL;
+ }
+
+ f->object_format = obj_info->object_format;
+ f->protection_status = obj_info->protection_status;
+ f->image_pix_width = obj_info->image_pix_width;
+ f->image_pix_height = obj_info->image_pix_height;
+ f->image_bit_depth = obj_info->image_bit_depth;
+ f->parent = obj_info->parent_object;
+ f->association_type = obj_info->association_type;
+ f->size = obj_info->object_compressed_size;
+ f->data = f_buf;
+ uint8_t* buf = io_container->payload + sizeof(mtp_object_info_header_t);
+ mtp_container_get_string(buf, f->name);
+ // ignore date created/modified/keywords
+ }
+
+ return 0;
+}
+
+static int32_t fs_send_object(tud_mtp_cb_data_t* cb_data) {
+ mtp_container_info_t* io_container = &cb_data->io_container;
+ fs_file_t* f = fs_get_file(send_obj_handle);
+ if (f == NULL) {
+ return MTP_RESP_INVALID_OBJECT_HANDLE;
+ }
+
+ if (cb_data->phase == MTP_PHASE_COMMAND) {
+ io_container->header->len += f->size;
+ tud_mtp_data_receive(io_container);
+ } else {
+ // file contents offset is total xferred minus header size minus last received chunk
+ const uint32_t offset = cb_data->total_xferred_bytes - sizeof(mtp_container_header_t) - io_container->payload_bytes;
+ memcpy(f->data + offset, io_container->payload, io_container->payload_bytes);
+ if (cb_data->total_xferred_bytes - sizeof(mtp_container_header_t) < f->size) {
+ tud_mtp_data_receive(io_container);
+ }
+ }
+
+ return 0;
+}
+
+static int32_t fs_delete_object(tud_mtp_cb_data_t* cb_data) {
+ const mtp_container_command_t* command = cb_data->command_container;
+ const uint32_t obj_handle = command->params[0];
+ const uint32_t obj_format = command->params[1]; // optional
+ (void) obj_format;
+
+ if (!is_session_opened) {
+ return MTP_RESP_SESSION_NOT_OPEN;
+ }
+ fs_file_t* f = fs_get_file(obj_handle);
+ if (f == NULL) {
+ return MTP_RESP_INVALID_OBJECT_HANDLE;
+ }
+
+ // delete object by clear the name
+ f->name[0] = 0;
+ return MTP_RESP_OK;
+}
diff --git a/examples/device/mtp/src/tinyusb_logo_png.h b/examples/device/mtp/src/tinyusb_logo_png.h
new file mode 100644
index 000000000..061fbc85a
--- /dev/null
+++ b/examples/device/mtp/src/tinyusb_logo_png.h
@@ -0,0 +1,175 @@
+// convert using tools/file2carray.py
+const size_t logo_len = 2733;
+const uint8_t logo_bin[] __attribute__((aligned(16))) = {
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
+ 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x40, 0x08, 0x06, 0x00, 0x00, 0x00, 0xd2, 0xd6, 0x7f,
+ 0x7f, 0x00, 0x00, 0x00, 0x06, 0x62, 0x4b, 0x47, 0x44, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0xa0,
+ 0xbd, 0xa7, 0x93, 0x00, 0x00, 0x0a, 0x62, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0xed, 0x9c, 0x7d,
+ 0x54, 0x54, 0x65, 0x1a, 0xc0, 0x7f, 0xc3, 0x00, 0x29, 0x1f, 0x31, 0x88, 0x61, 0x90, 0xd6, 0xa1,
+ 0xb3, 0xba, 0x1a, 0x18, 0x7e, 0xf2, 0xad, 0x40, 0x82, 0xb8, 0x9b, 0x2b, 0x43, 0x1e, 0xd2, 0x00,
+ 0x53, 0xc0, 0xea, 0xec, 0xc9, 0x70, 0x18, 0x3d, 0x5b, 0xb1, 0x9e, 0x4a, 0x6d, 0x13, 0x2d, 0xcb,
+ 0x76, 0xcd, 0x00, 0xf3, 0x8b, 0x10, 0x8a, 0x8e, 0xd6, 0xee, 0xda, 0x8a, 0x96, 0x30, 0x66, 0xa2,
+ 0xa0, 0x91, 0x64, 0xae, 0x16, 0x98, 0x45, 0x9d, 0x2c, 0x93, 0x8f, 0x05, 0x11, 0x92, 0x81, 0xbb,
+ 0x7f, 0xa8, 0x93, 0x33, 0x23, 0xc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 0xdf,
+ 0x63, 0x49, 0xdc, 0xaa, 0x34, 0x3a, 0x00, 0xe2, 0x0e, 0xaa, 0x49, 0x0c, 0x24, 0xca, 0x65, 0x82,
+ 0x20, 0x44, 0x03, 0x07, 0x90, 0xe6, 0x01, 0x83, 0x0d, 0x01, 0x88, 0x75, 0x90, 0xc9, 0x64, 0x65,
+ 0xc0, 0x8b, 0xb6, 0xf6, 0x46, 0xa2, 0xdf, 0xf9, 0x9b, 0x4c, 0x26, 0x3b, 0xa0, 0x7b, 0xea, 0x05,
+ 0x41, 0x98, 0x0b, 0xa8, 0x81, 0x89, 0xc0, 0x50, 0x9b, 0xb9, 0x25, 0xd1, 0x97, 0xb4, 0x03, 0x9f,
+ 0x03, 0xeb, 0x65, 0x32, 0xd9, 0x2e, 0x80, 0xff, 0x03, 0xff, 0x08, 0x81, 0xdd, 0xa8, 0xcb, 0xf5,
+ 0x99, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
+};
diff --git a/examples/device/mtp/src/tusb_config.h b/examples/device/mtp/src/tusb_config.h
new file mode 100644
index 000000000..4d166aa63
--- /dev/null
+++ b/examples/device/mtp/src/tusb_config.h
@@ -0,0 +1,139 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2025 Ennebi Elettronica (https://ennebielettronica.com)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ */
+
+#ifndef _TUSB_CONFIG_H_
+#define _TUSB_CONFIG_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// Board Specific Configuration
+//--------------------------------------------------------------------+
+
+// RHPort number used for device can be defined by board.mk, default to port 0
+#ifndef BOARD_TUD_RHPORT
+#define BOARD_TUD_RHPORT 0
+#endif
+
+// RHPort max operational speed can defined by board.mk
+#ifndef BOARD_TUD_MAX_SPEED
+#define BOARD_TUD_MAX_SPEED OPT_MODE_DEFAULT_SPEED
+#endif
+
+//--------------------------------------------------------------------
+// COMMON CONFIGURATION
+//--------------------------------------------------------------------
+
+// defined by compiler flags for flexibility
+#ifndef CFG_TUSB_MCU
+#error CFG_TUSB_MCU must be defined
+#endif
+
+#ifndef CFG_TUSB_OS
+#define CFG_TUSB_OS OPT_OS_NONE
+#endif
+
+#ifndef CFG_TUSB_DEBUG
+#define CFG_TUSB_DEBUG 0
+#endif
+
+// Enable Device stack
+#define CFG_TUD_ENABLED 1
+
+// Default is max speed that hardware controller could support with on-chip PHY
+#define CFG_TUD_MAX_SPEED BOARD_TUD_MAX_SPEED
+
+/* USB DMA on some MCUs can only access a specific SRAM region with restriction on alignment.
+ * Tinyusb use follows macros to declare transferring memory so that they can be put
+ * into those specific section.
+ * e.g
+ * - CFG_TUSB_MEM SECTION : __attribute__ (( section(".usb_ram") ))
+ * - CFG_TUSB_MEM_ALIGN : __attribute__ ((aligned(4)))
+ */
+#ifndef CFG_TUSB_MEM_SECTION
+#define CFG_TUSB_MEM_SECTION
+#endif
+
+#ifndef CFG_TUSB_MEM_ALIGN
+#define CFG_TUSB_MEM_ALIGN __attribute__ ((aligned(4)))
+#endif
+
+//--------------------------------------------------------------------
+// DEVICE CONFIGURATION
+//--------------------------------------------------------------------
+
+#ifndef CFG_TUD_ENDPOINT0_SIZE
+#define CFG_TUD_ENDPOINT0_SIZE 64
+#endif
+
+//------------- CLASS -------------//
+#define CFG_TUD_MTP 1
+#define CFG_TUD_MTP_EP_BUFSIZE 512
+#define CFG_TUD_MTP_EP_CONTROL_BUFSIZE 16 // should be enough to hold data in MTP control request
+
+//------------- MTP device info -------------//
+#define CFG_TUD_MTP_DEVICEINFO_EXTENSIONS "microsoft.com: 1.0; "
+#define CFG_TUD_MTP_DEVICEINFO_SUPPORTED_OPERATIONS \
+ MTP_OP_GET_DEVICE_INFO, \
+ MTP_OP_OPEN_SESSION, \
+ MTP_OP_CLOSE_SESSION, \
+ MTP_OP_GET_STORAGE_IDS, \
+ MTP_OP_GET_STORAGE_INFO, \
+ MTP_OP_GET_OBJECT_HANDLES, \
+ MTP_OP_GET_OBJECT_INFO, \
+ MTP_OP_GET_OBJECT, \
+ MTP_OP_DELETE_OBJECT, \
+ MTP_OP_SEND_OBJECT_INFO, \
+ MTP_OP_SEND_OBJECT, \
+ MTP_OP_RESET_DEVICE, \
+ MTP_OP_GET_DEVICE_PROP_DESC, \
+ MTP_OP_GET_DEVICE_PROP_VALUE, \
+ MTP_OP_SET_DEVICE_PROP_VALUE
+
+#define CFG_TUD_MTP_DEVICEINFO_SUPPORTED_EVENTS \
+ MTP_EVENT_OBJECT_ADDED
+
+#define CFG_TUD_MTP_DEVICEINFO_SUPPORTED_DEVICE_PROPERTIES \
+ MTP_DEV_PROP_DEVICE_FRIENDLY_NAME
+
+#define CFG_TUD_MTP_DEVICEINFO_CAPTURE_FORMATS \
+ MTP_OBJ_FORMAT_UNDEFINED, \
+ MTP_OBJ_FORMAT_ASSOCIATION, \
+ MTP_OBJ_FORMAT_TEXT, \
+ MTP_OBJ_FORMAT_PNG
+
+#define CFG_TUD_MTP_DEVICEINFO_PLAYBACK_FORMATS \
+ MTP_OBJ_FORMAT_UNDEFINED, \
+ MTP_OBJ_FORMAT_ASSOCIATION, \
+ MTP_OBJ_FORMAT_TEXT, \
+ MTP_OBJ_FORMAT_PNG
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_CONFIG_H_ */
diff --git a/examples/device/mtp/src/usb_descriptors.c b/examples/device/mtp/src/usb_descriptors.c
new file mode 100644
index 000000000..80345d8f8
--- /dev/null
+++ b/examples/device/mtp/src/usb_descriptors.c
@@ -0,0 +1,255 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Ha Thach (tinyusb.org)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ */
+
+#include "bsp/board_api.h"
+#include "tusb.h"
+
+/* A combination of interfaces must have a unique product id, since PC will save device driver after the first plug.
+ * Same VID/PID with different interface e.g MSC (first), then CDC (later) will possibly cause system error on PC.
+ *
+ * Auto ProductID layout's Bitmap:
+ * [MSB] MTP | VENDOR | MIDI | HID | MSC | CDC [LSB]
+ */
+#define _PID_MAP(itf, n) ( (CFG_TUD_##itf) << (n) )
+#define USB_PID (0x4000 | _PID_MAP(CDC, 0) | _PID_MAP(MSC, 1) | _PID_MAP(HID, 2) | \
+ _PID_MAP(MIDI, 3) | _PID_MAP(VENDOR, 4) | _PID_MAP(MTP, 5))
+
+#define USB_VID 0xCafe
+#define USB_BCD 0x0200
+
+//--------------------------------------------------------------------+
+// Device Descriptors
+//--------------------------------------------------------------------+
+tusb_desc_device_t const desc_device =
+{
+ .bLength = sizeof(tusb_desc_device_t),
+ .bDescriptorType = TUSB_DESC_DEVICE,
+ .bcdUSB = USB_BCD,
+ .bDeviceClass = TUSB_CLASS_UNSPECIFIED,
+ .bDeviceSubClass = 0x00,
+ .bDeviceProtocol = 0x00,
+ .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE,
+
+ .idVendor = USB_VID,
+ .idProduct = USB_PID,
+ .bcdDevice = 0x0100,
+
+ .iManufacturer = 0x01,
+ .iProduct = 0x02,
+ .iSerialNumber = 0x03,
+
+ .bNumConfigurations = 0x01
+};
+
+// Invoked when received GET DEVICE DESCRIPTOR
+// Application return pointer to descriptor
+uint8_t const *tud_descriptor_device_cb(void)
+{
+ return (uint8_t const *) &desc_device;
+}
+
+//--------------------------------------------------------------------+
+// Configuration Descriptor
+//--------------------------------------------------------------------+
+
+enum
+{
+ ITF_NUM_MTP = 0,
+ ITF_NUM_TOTAL
+};
+
+#if CFG_TUSB_MCU == OPT_MCU_LPC175X_6X || CFG_TUSB_MCU == OPT_MCU_LPC177X_8X || CFG_TUSB_MCU == OPT_MCU_LPC40XX
+ // LPC 17xx and 40xx endpoint type (bulk/interrupt/iso) are fixed by its number
+ // 0 control, 1 In, 2 Bulk, 3 Iso, 4 In, 5 Bulk etc ...
+ #define EPNUM_MTP_EVT 0x81
+ #define EPNUM_MTP_OUT 0x02
+ #define EPNUM_MTP_IN 0x82
+
+#elif CFG_TUSB_MCU == OPT_MCU_CXD56
+ // CXD56 USB driver has fixed endpoint type (bulk/interrupt/iso) and direction (IN/OUT) by its number
+ // 0 control (IN/OUT), 1 Bulk (IN), 2 Bulk (OUT), 3 In (IN), 4 Bulk (IN), 5 Bulk (OUT), 6 In (IN)
+ #define EPNUM_MTP_EVT 0x83
+ #define EPNUM_MTP_OUT 0x02
+ #define EPNUM_MTP_IN 0x81
+
+#elif defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+ // MCUs that don't support a same endpoint number with different direction IN and OUT defined in tusb_mcu.h
+ // e.g EP1 OUT & EP1 IN cannot exist together
+ #define EPNUM_MTP_EVT 0x81
+ #define EPNUM_MTP_OUT 0x03
+ #define EPNUM_MTP_IN 0x82
+
+#else
+ #define EPNUM_MTP_EVT 0x81
+ #define EPNUM_MTP_OUT 0x02
+ #define EPNUM_MTP_IN 0x82
+#endif
+
+#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_MTP_DESC_LEN)
+
+// full speed configuration
+const uint8_t desc_fs_configuration[] = {
+ // Config number, interface count, string index, total length, attribute, power in mA
+ TUD_CONFIG_DESCRIPTOR(1, ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, 0x00, 100),
+ // Interface number, string index, EP event, EP event size, EP event polling, EP Out & EP In address, EP size
+ TUD_MTP_DESCRIPTOR(ITF_NUM_MTP, 4, EPNUM_MTP_EVT, 64, 1, EPNUM_MTP_OUT, EPNUM_MTP_IN, 64),
+};
+
+#if TUD_OPT_HIGH_SPEED
+// Per USB specs: high speed capable device must report device_qualifier and other_speed_configuration
+
+// high speed configuration
+uint8_t const desc_hs_configuration[] = {
+ // Config number, interface count, string index, total length, attribute, power in mA
+ TUD_CONFIG_DESCRIPTOR(1, ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, 0x00, 100),
+ // Interface number, string index, EP event, EP event size, EP event polling, EP Out & EP In address, EP size
+ TUD_MTP_DESCRIPTOR(ITF_NUM_MTP, 4, EPNUM_MTP_EVT, 64, 1, EPNUM_MTP_OUT, EPNUM_MTP_IN, 512),
+};
+
+// other speed configuration
+uint8_t desc_other_speed_config[CONFIG_TOTAL_LEN];
+
+// device qualifier is mostly similar to device descriptor since we don't change configuration based on speed
+tusb_desc_device_qualifier_t const desc_device_qualifier = {
+ .bLength = sizeof(tusb_desc_device_qualifier_t),
+ .bDescriptorType = TUSB_DESC_DEVICE_QUALIFIER,
+ .bcdUSB = USB_BCD,
+
+ .bDeviceClass = TUSB_CLASS_MISC,
+ .bDeviceSubClass = MISC_SUBCLASS_COMMON,
+ .bDeviceProtocol = MISC_PROTOCOL_IAD,
+
+ .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE,
+ .bNumConfigurations = 0x01,
+ .bReserved = 0x00
+};
+
+// Invoked when received GET DEVICE QUALIFIER DESCRIPTOR request
+// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete.
+// device_qualifier descriptor describes information about a high-speed capable device that would
+// change if the device were operating at the other speed. If not highspeed capable stall this request.
+uint8_t const *tud_descriptor_device_qualifier_cb(void) {
+ return (uint8_t const *) &desc_device_qualifier;
+}
+
+// Invoked when received GET OTHER SEED CONFIGURATION DESCRIPTOR request
+// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete
+// Configuration descriptor in the other speed e.g if high speed then this is for full speed and vice versa
+uint8_t const *tud_descriptor_other_speed_configuration_cb(uint8_t index) {
+ (void) index; // for multiple configurations
+
+ // if link speed is high return fullspeed config, and vice versa
+ // Note: the descriptor type is OTHER_SPEED_CONFIG instead of CONFIG
+ memcpy(desc_other_speed_config,
+ (tud_speed_get() == TUSB_SPEED_HIGH) ? desc_fs_configuration : desc_hs_configuration,
+ CONFIG_TOTAL_LEN);
+ desc_other_speed_config[1] = TUSB_DESC_OTHER_SPEED_CONFIG;
+ return desc_other_speed_config;
+}
+
+#endif // highspeed
+
+// Invoked when received GET CONFIGURATION DESCRIPTOR
+// Application return pointer to descriptor
+// Descriptor contents must exist long enough for transfer to complete
+const uint8_t*tud_descriptor_configuration_cb(uint8_t index) {
+ (void) index; // for multiple configurations
+#if TUD_OPT_HIGH_SPEED
+ // Although we are highspeed, host may be fullspeed.
+ return (tud_speed_get() == TUSB_SPEED_HIGH) ? desc_hs_configuration : desc_fs_configuration;
+#else
+ return desc_fs_configuration;
+#endif
+}
+
+//--------------------------------------------------------------------+
+// String Descriptors
+//--------------------------------------------------------------------+
+
+// String Descriptor Index
+enum {
+ STRID_LANGID = 0,
+ STRID_MANUFACTURER,
+ STRID_PRODUCT,
+ STRID_SERIAL,
+ STRID_MTP,
+};
+
+// array of pointer to string descriptors
+char const *string_desc_arr[] =
+{
+ (const char[]) { 0x09, 0x04 }, // 0: is supported language is English (0x0409)
+ "TinyUsb", // 1: Manufacturer
+ "TinyUsb Device", // 2: Product
+ NULL, // 3: Serials will use unique ID if possible
+ "TinyUSB MTP", // 4: MTP Interface
+};
+
+static uint16_t _desc_str[32 + 1];
+
+// Invoked when received GET STRING DESCRIPTOR request
+// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete
+uint16_t const *tud_descriptor_string_cb(uint8_t index, uint16_t langid) {
+ (void) langid;
+ size_t chr_count;
+
+ switch ( index ) {
+ case STRID_LANGID:
+ memcpy(&_desc_str[1], string_desc_arr[0], 2);
+ chr_count = 1;
+ break;
+
+ case STRID_SERIAL:
+ chr_count = board_usb_get_serial(_desc_str + 1, 32);
+ break;
+
+ default:
+ // Note: the 0xEE index string is a Microsoft OS 1.0 Descriptors.
+ // https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/microsoft-defined-usb-descriptors
+
+ if ( !(index < sizeof(string_desc_arr) / sizeof(string_desc_arr[0])) ) {
+ return NULL;
+ }
+
+ const char *str = string_desc_arr[index];
+ // Cap at max char
+ chr_count = strlen(str);
+ const size_t max_count = sizeof(_desc_str) / sizeof(_desc_str[0]) - 1; // -1 for string type
+ if ( chr_count > max_count ) {
+ chr_count = max_count;
+ }
+
+ // Convert ASCII string into UTF-16
+ for ( size_t i = 0; i < chr_count; i++ ) {
+ _desc_str[1 + i] = str[i];
+ }
+ break;
+ }
+
+ // first byte is length (including header), second byte is string type
+ _desc_str[0] = (uint16_t) ((TUSB_DESC_STRING << 8) | (2 * chr_count + 2));
+
+ return _desc_str;
+}
diff --git a/examples/dual/host_hid_to_device_cdc/src/usb_descriptors.c b/examples/dual/host_hid_to_device_cdc/src/usb_descriptors.c
index 9d57737fb..b7cffe23d 100644
--- a/examples/dual/host_hid_to_device_cdc/src/usb_descriptors.c
+++ b/examples/dual/host_hid_to_device_cdc/src/usb_descriptors.c
@@ -175,7 +175,7 @@ uint8_t const* tud_descriptor_other_speed_configuration_cb(uint8_t index) {
(void) index; // for multiple configurations
// if link speed is high return fullspeed config, and vice versa
- // Note: the descriptor type is OHER_SPEED_CONFIG instead of CONFIG
+ // Note: the descriptor type is OTHER_SPEED_CONFIG instead of CONFIG
memcpy(desc_other_speed_config,
(tud_speed_get() == TUSB_SPEED_HIGH) ? desc_fs_configuration : desc_hs_configuration,
CONFIG_TOTAL_LEN);
diff --git a/examples/dual/host_info_to_device_cdc/src/usb_descriptors.c b/examples/dual/host_info_to_device_cdc/src/usb_descriptors.c
index 9d57737fb..b7cffe23d 100644
--- a/examples/dual/host_info_to_device_cdc/src/usb_descriptors.c
+++ b/examples/dual/host_info_to_device_cdc/src/usb_descriptors.c
@@ -175,7 +175,7 @@ uint8_t const* tud_descriptor_other_speed_configuration_cb(uint8_t index) {
(void) index; // for multiple configurations
// if link speed is high return fullspeed config, and vice versa
- // Note: the descriptor type is OHER_SPEED_CONFIG instead of CONFIG
+ // Note: the descriptor type is OTHER_SPEED_CONFIG instead of CONFIG
memcpy(desc_other_speed_config,
(tud_speed_get() == TUSB_SPEED_HIGH) ? desc_fs_configuration : desc_hs_configuration,
CONFIG_TOTAL_LEN);
diff --git a/hw/bsp/espressif/components/tinyusb_src/CMakeLists.txt b/hw/bsp/espressif/components/tinyusb_src/CMakeLists.txt
index 00e288bad..beabcad9c 100644
--- a/hw/bsp/espressif/components/tinyusb_src/CMakeLists.txt
+++ b/hw/bsp/espressif/components/tinyusb_src/CMakeLists.txt
@@ -37,6 +37,7 @@ list(APPEND srcs
${tusb_src}/class/hid/hid_device.c
${tusb_src}/class/midi/midi_device.c
${tusb_src}/class/msc/msc_device.c
+ ${tusb_src}/class/mtp/mtp_device.c
${tusb_src}/class/net/ecm_rndis_device.c
${tusb_src}/class/net/ncm_device.c
${tusb_src}/class/usbtmc/usbtmc_device.c
diff --git a/hw/bsp/rp2040/family.cmake b/hw/bsp/rp2040/family.cmake
index 2182e9ad1..3bec5bf70 100644
--- a/hw/bsp/rp2040/family.cmake
+++ b/hw/bsp/rp2040/family.cmake
@@ -95,6 +95,7 @@ target_sources(tinyusb_device_base INTERFACE
${TOP}/src/class/hid/hid_device.c
${TOP}/src/class/midi/midi_device.c
${TOP}/src/class/msc/msc_device.c
+ ${TOP}/src/class/mtp/mtp_device.c
${TOP}/src/class/net/ecm_rndis_device.c
${TOP}/src/class/net/ncm_device.c
${TOP}/src/class/usbtmc/usbtmc_device.c
diff --git a/hw/bsp/samd11/family.cmake b/hw/bsp/samd11/family.cmake
index 965b1cfb5..e3dc23c35 100644
--- a/hw/bsp/samd11/family.cmake
+++ b/hw/bsp/samd11/family.cmake
@@ -54,6 +54,7 @@ function(add_board_target BOARD_TARGET)
OSC32K_OVERWRITE_CALIBRATION=0
CFG_EXAMPLE_MSC_READONLY
CFG_EXAMPLE_VIDEO_READONLY
+ CFG_EXAMPLE_MTP_READONLY
)
update_board(${BOARD_TARGET})
diff --git a/lib/rt-thread/SConscript b/lib/rt-thread/SConscript
index 34399fd45..99517a090 100644
--- a/lib/rt-thread/SConscript
+++ b/lib/rt-thread/SConscript
@@ -34,6 +34,8 @@ if GetDepend(["PKG_TINYUSB_DEVICE_ENABLE"]):
src += ["../../src/class/cdc/cdc_device.c"]
if GetDepend(["PKG_TINYUSB_DEVICE_MSC"]):
src += ["../../src/class/msc/msc_device.c", "port/msc_device_port.c"]
+ if GetDepend(["PKG_TINYUSB_DEVICE_MTP"]):
+ src += ["../../src/class/mtp/mtp_device.c"]
if GetDepend(["PKG_TINYUSB_DEVICE_HID"]):
src += ["../../src/class/hid/hid_device.c"]
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 99d3059fc..951683104 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -16,6 +16,7 @@ function(tinyusb_target_add TARGET)
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/hid/hid_device.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/midi/midi_device.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/msc/msc_device.c
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/mtp/mtp_device.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/net/ecm_rndis_device.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/net/ncm_device.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/usbtmc/usbtmc_device.c
diff --git a/src/class/mtp/mtp.h b/src/class/mtp/mtp.h
new file mode 100644
index 000000000..40b6dd8b0
--- /dev/null
+++ b/src/class/mtp/mtp.h
@@ -0,0 +1,888 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2025 Ennebi Elettronica (https://ennebielettronica.com)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+
+#ifndef TUSB_MTP_H_
+#define TUSB_MTP_H_
+
+#include "common/tusb_common.h"
+
+#if (CFG_TUD_ENABLED && CFG_TUD_MTP)
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// Media Transfer Protocol Class Constant
+//--------------------------------------------------------------------+
+
+// Media Transfer Protocol Subclass
+typedef enum {
+ MTP_SUBCLASS_STILL_IMAGE = 1
+} mtp_subclass_type_t;
+
+// MTP Protocol.
+typedef enum {
+ MTP_PROTOCOL_PIMA_15470 = 1, ///< Picture Transfer Protocol (PIMA 15470)
+} mtp_protocol_type_t;
+
+// PTP/MTP protocol phases
+typedef enum {
+ MTP_PHASE_COMMAND = 0,
+ MTP_PHASE_DATA,
+ MTP_PHASE_RESPONSE,
+ MTP_PHASE_ERROR
+} mtp_phase_type_t;
+
+// PTP/MTP Class requests, PIMA 15740-2000: D.5.2
+typedef enum {
+ MTP_REQ_CANCEL = 0x64,
+ MTP_REQ_GET_EXT_EVENT_DATA = 0x65,
+ MTP_REQ_RESET = 0x66,
+ MTP_REQ_GET_DEVICE_STATUS = 0x67,
+} mtp_class_request_t;
+
+// PTP/MTP Container type
+typedef enum {
+ MTP_CONTAINER_TYPE_UNDEFINED = 0,
+ MTP_CONTAINER_TYPE_COMMAND_BLOCK = 1,
+ MTP_CONTAINER_TYPE_DATA_BLOCK = 2,
+ MTP_CONTAINER_TYPE_RESPONSE_BLOCK = 3,
+ MTP_CONTAINER_TYPE_EVENT_BLOCK = 4,
+} mtp_container_type_t;
+
+// MTP 1.1 Appendix A: Object formats
+typedef enum {
+ // ---- Base formats ----
+ MTP_OBJ_FORMAT_UNDEFINED = 0x3000u, // Undefined object
+ MTP_OBJ_FORMAT_ASSOCIATION = 0x3001u, // Association (for example, a folder)
+ MTP_OBJ_FORMAT_SCRIPT = 0x3002u, // Device model-specific script
+ MTP_OBJ_FORMAT_EXECUTABLE = 0x3003u, // Device model-specific binary executable
+ MTP_OBJ_FORMAT_TEXT = 0x3004u, // Text file
+ MTP_OBJ_FORMAT_HTML = 0x3005u, // Hypertext Markup Language file (text)
+ MTP_OBJ_FORMAT_DPOF = 0x3006u, // Digital Print Order Format file (text)
+ MTP_OBJ_FORMAT_AIFF = 0x3007u, // Audio clip (AIFF)
+ MTP_OBJ_FORMAT_WAV = 0x3008u, // Audio clip (WAV)
+ MTP_OBJ_FORMAT_MP3 = 0x3009u, // MPEG-1 Layer III audio (ISO/IEC 13818-3)
+ MTP_OBJ_FORMAT_AVI = 0x300Au, // Video clip (AVI)
+ MTP_OBJ_FORMAT_MPEG = 0x300Bu, // Video clip (MPEG)
+ MTP_OBJ_FORMAT_ASF = 0x300Cu, // Microsoft Advanced Streaming Format (video)
+
+ // ---- Image formats ----
+ MTP_OBJ_FORMAT_UNDEFINED_IMAGE = 0x3800u, // Undefined image object
+ MTP_OBJ_FORMAT_EXIF_JPEG = 0x3801u, // Exchangeable Image Format, JEIDA standard
+ MTP_OBJ_FORMAT_TIFF_EP = 0x3802u, // Tag Image File Format for Electronic Photography
+ MTP_OBJ_FORMAT_FLASHPIX = 0x3803u, // Structured Storage Image Format (FlashPix)
+ MTP_OBJ_FORMAT_BMP = 0x3804u, // Microsoft Windows Bitmap file
+ MTP_OBJ_FORMAT_CIFF = 0x3805u, // Canon Camera Image File Format
+ MTP_OBJ_FORMAT_UNDEFINED_3806 = 0x3806u, // Reserved / Undefined
+ MTP_OBJ_FORMAT_GIF = 0x3807u, // Graphics Interchange Format
+ MTP_OBJ_FORMAT_JFIF = 0x3808u, // JPEG File Interchange Format
+ MTP_OBJ_FORMAT_CD = 0x3809u, // PhotoCD Image Pac
+ MTP_OBJ_FORMAT_PICT = 0x380Au, // Quickdraw Image Format
+ MTP_OBJ_FORMAT_PNG = 0x380Bu, // Portable Network Graphics
+ MTP_OBJ_FORMAT_UNDEFINED_380C = 0x380Cu, // Reserved / Undefined
+ MTP_OBJ_FORMAT_TIFF = 0x380Du, // Tag Image File Format (baseline)
+ MTP_OBJ_FORMAT_TIFF_IT = 0x380Eu, // Tag Image File Format for IT (graphic arts)
+ MTP_OBJ_FORMAT_JP2 = 0x380Fu, // JPEG2000 Baseline File Format
+ MTP_OBJ_FORMAT_JPX = 0x3810u, // JPEG2000 Extended File Format
+
+ // ---- Firmware & misc ----
+ MTP_OBJ_FORMAT_UNDEFINED_FIRMWARE = 0xB802u, // Undefined Firmware
+ MTP_OBJ_FORMAT_WBMP = 0xB803u, // Wireless Application Protocol Bitmap Format (.wbmp)
+ MTP_OBJ_FORMAT_WINDOWS_IMAGE = 0xB881u, // Windows Image Format
+ MTP_OBJ_FORMAT_JPEGXR = 0xB804u, // JPEG XR (.hdp, .jxr, .wdp)
+
+ // ---- Audio formats ----
+ MTP_OBJ_FORMAT_UNDEFINED_AUDIO = 0xB900u, // Undefined audio object
+ MTP_OBJ_FORMAT_WMA = 0xB901u, // Windows Media Audio
+ MTP_OBJ_FORMAT_OGG = 0xB902u, // OGG container
+ MTP_OBJ_FORMAT_AAC = 0xB903u, // Advanced Audio Coding (.aac)
+ MTP_OBJ_FORMAT_AUDIBLE = 0xB904u, // Audible format
+ MTP_OBJ_FORMAT_FLAC = 0xB906u, // Free Lossless Audio Codec
+ MTP_OBJ_FORMAT_QCELP = 0xB907u, // Qualcomm Code Excited Linear Prediction (.qcp)
+ MTP_OBJ_FORMAT_AMR = 0xB908u, // Adaptive Multi-Rate audio (.amr)
+
+ // ---- Video formats ----
+ MTP_OBJ_FORMAT_UNDEFINED_VIDEO = 0xB980u, // Undefined video object
+ MTP_OBJ_FORMAT_WMV = 0xB981u, // Windows Media Video
+ MTP_OBJ_FORMAT_MP4 = 0xB982u, // MP4 Container (ISO 14496-1)
+ MTP_OBJ_FORMAT_MP2 = 0xB983u, // MPEG-1 Layer II audio
+ MTP_OBJ_FORMAT_3GP = 0xB984u, // 3GP Container
+ MTP_OBJ_FORMAT_3G2 = 0xB985u, // 3GPP2 Container
+ MTP_OBJ_FORMAT_AVCHD = 0xB986u, // AVCHD (MPEG-4 AVC + Dolby Digital)
+ MTP_OBJ_FORMAT_ATSC_TS = 0xB987u, // ATSC-compliant MPEG-2 Transport Stream
+ MTP_OBJ_FORMAT_DVB_TS = 0xB988u, // DVB-compliant MPEG-2 Transport Stream
+
+ // ---- Collections ----
+ MTP_OBJ_FORMAT_UNDEFINED_COLLECTION = 0xBA00u, // Undefined collection
+ MTP_OBJ_FORMAT_ABSTRACT_MULTIMEDIA_ALBUM = 0xBA01u, // Abstract Multimedia Album
+ MTP_OBJ_FORMAT_ABSTRACT_IMAGE_ALBUM = 0xBA02u, // Abstract Image Album
+ MTP_OBJ_FORMAT_ABSTRACT_AUDIO_ALBUM = 0xBA03u, // Abstract Audio Album
+ MTP_OBJ_FORMAT_ABSTRACT_VIDEO_ALBUM = 0xBA04u, // Abstract Video Album
+ MTP_OBJ_FORMAT_ABSTRACT_AV_PLAYLIST = 0xBA05u, // Abstract Audio & Video Playlist
+ MTP_OBJ_FORMAT_ABSTRACT_CONTACT_GROUP = 0xBA06u, // Abstract Contact Group
+ MTP_OBJ_FORMAT_ABSTRACT_MESSAGE_FOLDER = 0xBA07u, // Abstract Message Folder
+ MTP_OBJ_FORMAT_ABSTRACT_CHAPTERED_PRODUCTION = 0xBA08u, // Abstract Chaptered Production
+ MTP_OBJ_FORMAT_ABSTRACT_AUDIO_PLAYLIST = 0xBA09u, // Abstract Audio Playlist
+ MTP_OBJ_FORMAT_ABSTRACT_VIDEO_PLAYLIST = 0xBA0Au, // Abstract Video Playlist
+ MTP_OBJ_FORMAT_ABSTRACT_MEDIACAST = 0xBA0Bu, // Abstract Mediacast (RSS enclosure)
+
+ // ---- Playlist formats ----
+ MTP_OBJ_FORMAT_WPL_PLAYLIST = 0xBA10u, // Windows Media Player Playlist (.wpl)
+ MTP_OBJ_FORMAT_M3U_PLAYLIST = 0xBA11u, // M3U Playlist
+ MTP_OBJ_FORMAT_MPL_PLAYLIST = 0xBA12u, // MPL Playlist
+ MTP_OBJ_FORMAT_ASX_PLAYLIST = 0xBA13u, // ASX Playlist
+ MTP_OBJ_FORMAT_PLS_PLAYLIST = 0xBA14u, // PLS Playlist
+
+ // ---- Document formats ----
+ MTP_OBJ_FORMAT_UNDEFINED_DOC = 0xBA80u, // Undefined Document
+ MTP_OBJ_FORMAT_ABSTRACT_DOC = 0xBA81u, // Abstract Document
+ MTP_OBJ_FORMAT_XML_DOC = 0xBA82u, // XML Document
+ MTP_OBJ_FORMAT_DOC = 0xBA83u, // Microsoft Word Document
+ MTP_OBJ_FORMAT_MHT_DOC = 0xBA84u, // MHT Compiled HTML Document
+ MTP_OBJ_FORMAT_XLS = 0xBA85u, // Microsoft Excel Spreadsheet
+ MTP_OBJ_FORMAT_PPT = 0xBA86u, // Microsoft PowerPoint Presentation
+
+ // ---- Messaging ----
+ MTP_OBJ_FORMAT_UNDEFINED_MSG = 0xBB00u, // Undefined Message
+ MTP_OBJ_FORMAT_ABSTRACT_MSG = 0xBB01u, // Abstract Message
+
+ // ---- Bookmarks ----
+ MTP_OBJ_FORMAT_UNDEFINED_BOOKMARK = 0xBB10u, // Undefined Bookmark
+ MTP_OBJ_FORMAT_ABSTRACT_BOOKMARK = 0xBB11u, // Abstract Bookmark
+
+ // ---- Appointments ----
+ MTP_OBJ_FORMAT_UNDEFINED_APPT = 0xBB20u, // Undefined Appointment
+ MTP_OBJ_FORMAT_ABSTRACT_APPT = 0xBB21u, // Abstract Appointment
+ MTP_OBJ_FORMAT_VCALENDAR1 = 0xBB22u, // vCalendar 1.0
+
+ // ---- Tasks ----
+ MTP_OBJ_FORMAT_UNDEFINED_TASK = 0xBB40u, // Undefined Task
+ MTP_OBJ_FORMAT_ABSTRACT_TASK = 0xBB41u, // Abstract Task
+ MTP_OBJ_FORMAT_ICALENDAR = 0xBB42u, // iCalendar
+
+ // ---- Notes ----
+ MTP_OBJ_FORMAT_UNDEFINED_NOTE = 0xBB60u, // Undefined Note
+ MTP_OBJ_FORMAT_ABSTRACT_NOTE = 0xBB61u, // Abstract Note
+
+ // ---- Contacts ----
+ MTP_OBJ_FORMAT_UNDEFINED_CONTACT= 0xBB80u, // Undefined Contact
+ MTP_OBJ_FORMAT_ABSTRACT_CONTACT = 0xBB81u, // Abstract Contact
+ MTP_OBJ_FORMAT_VCARD2 = 0xBB82u, // vCard 2.1
+ MTP_OBJ_FORMAT_VCARD3 = 0xBB83u, // vCard 3.0
+} mtp_object_formats_t;
+
+// MTP 1.1 Appendix B: Object Properties
+typedef enum {
+ MTP_OBJ_PROP_STORAGE_ID = 0xDC01u, // StorageID
+ MTP_OBJ_PROP_OBJECT_FORMAT = 0xDC02u, // Object Format
+ MTP_OBJ_PROP_PROTECTION_STATUS = 0xDC03u, // Protection Status
+ MTP_OBJ_PROP_OBJECT_SIZE = 0xDC04u, // Object Size
+ MTP_OBJ_PROP_ASSOCIATION_TYPE = 0xDC05u, // Association Type
+ MTP_OBJ_PROP_ASSOCIATION_DESC = 0xDC06u, // Association Description
+ MTP_OBJ_PROP_OBJECT_FILE_NAME = 0xDC07u, // Object File Name
+ MTP_OBJ_PROP_DATE_CREATED = 0xDC08u, // Date Created
+ MTP_OBJ_PROP_DATE_MODIFIED = 0xDC09u, // Date Modified
+ MTP_OBJ_PROP_KEYWORDS = 0xDC0Au, // Keywords
+ MTP_OBJ_PROP_PARENT_OBJECT = 0xDC0Bu, // Parent Object
+ MTP_OBJ_PROP_ALLOWED_FOLDER_CONTENTS = 0xDC0Cu, // Allowed Folder Contents
+ MTP_OBJ_PROP_HIDDEN = 0xDC0Du, // Hidden
+ MTP_OBJ_PROP_SYSTEM_OBJECT = 0xDC0Eu, // System Object
+ // 0xDC0F-0xDC40 is reserved
+
+ MTP_OBJ_PROP_PERSISTENT_UID = 0xDC41u, // Persistent Unique Object Identifier
+ MTP_OBJ_PROP_SYNC_ID = 0xDC42u, // SyncID
+ MTP_OBJ_PROP_PROPERTY_BAG = 0xDC43u, // Property Bag
+ MTP_OBJ_PROP_NAME = 0xDC44u, // Name
+ MTP_OBJ_PROP_CREATED_BY = 0xDC45u, // Created By
+ MTP_OBJ_PROP_ARTIST = 0xDC46u, // Artist
+ MTP_OBJ_PROP_DATE_AUTHORED = 0xDC47u, // Date Authored
+ MTP_OBJ_PROP_DESCRIPTION = 0xDC48u, // Description
+ MTP_OBJ_PROP_URL_REFERENCE = 0xDC49u, // URL Reference
+ MTP_OBJ_PROP_LANGUAGE_LOCALE = 0xDC4Au, // Language-Locale
+ MTP_OBJ_PROP_COPYRIGHT_INFO = 0xDC4Bu, // Copyright Information
+ MTP_OBJ_PROP_SOURCE = 0xDC4Cu, // Source
+ MTP_OBJ_PROP_ORIGIN_LOCATION = 0xDC4Du, // Origin Location
+ MTP_OBJ_PROP_DATE_ADDED = 0xDC4Eu, // Date Added
+ MTP_OBJ_PROP_NON_CONSUMABLE = 0xDC4Fu, // Non-Consumable
+ MTP_OBJ_PROP_CORRUPT_UNPLAYABLE = 0xDC50u, // Corrupt/Unplayable
+ MTP_OBJ_PROP_PRODUCER_SERIAL_NUMBER = 0xDC51u, // ProducerSerialNumber
+ // 0xDC52-0xDC80 is reserved
+
+ MTP_OBJ_PROP_REP_SAMPLE_FORMAT = 0xDC81u, // Representative Sample Format
+ MTP_OBJ_PROP_REP_SAMPLE_SIZE = 0xDC82u, // Representative Sample Size
+ MTP_OBJ_PROP_REP_SAMPLE_HEIGHT = 0xDC83u, // Representative Sample Height
+ MTP_OBJ_PROP_REP_SAMPLE_WIDTH = 0xDC84u, // Representative Sample Width
+ MTP_OBJ_PROP_REP_SAMPLE_DURATION = 0xDC85u, // Representative Sample Duration
+ MTP_OBJ_PROP_REP_SAMPLE_DATA = 0xDC86u, // Representative Sample Data
+ MTP_OBJ_PROP_WIDTH = 0xDC87u, // Width
+ MTP_OBJ_PROP_HEIGHT = 0xDC88u, // Height
+ MTP_OBJ_PROP_DURATION = 0xDC89u, // Duration
+ MTP_OBJ_PROP_RATING = 0xDC8Au, // Rating
+ MTP_OBJ_PROP_TRACK = 0xDC8Bu, // Track
+ MTP_OBJ_PROP_GENRE = 0xDC8Cu, // Genre
+ MTP_OBJ_PROP_CREDITS = 0xDC8Du, // Credits
+ MTP_OBJ_PROP_LYRICS = 0xDC8Eu, // Lyrics
+ MTP_OBJ_PROP_SUBSCRIPTION_CONTENT_ID = 0xDC8Fu, // Subscription Content ID
+ MTP_OBJ_PROP_PRODUCED_BY = 0xDC90u, // Produced By
+ MTP_OBJ_PROP_USE_COUNT = 0xDC91u, // Use Count
+ MTP_OBJ_PROP_SKIP_COUNT = 0xDC92u, // Skip Count
+ MTP_OBJ_PROP_LAST_ACCESSED = 0xDC93u, // Last Accessed
+ MTP_OBJ_PROP_PARENTAL_RATING = 0xDC94u, // Parental Rating
+ MTP_OBJ_PROP_META_GENRE = 0xDC95u, // Meta Genre
+ MTP_OBJ_PROP_COMPOSER = 0xDC96u, // Composer
+ MTP_OBJ_PROP_EFFECTIVE_RATING = 0xDC97u, // Effective Rating
+ MTP_OBJ_PROP_SUBTITLE = 0xDC98u, // Subtitle
+ MTP_OBJ_PROP_ORIGINAL_RELEASE_DATE = 0xDC99u, // Original Release Date
+ MTP_OBJ_PROP_ALBUM_NAME = 0xDC9Au, // Album Name
+ MTP_OBJ_PROP_ALBUM_ARTIST = 0xDC9Bu, // Album Artist
+ MTP_OBJ_PROP_MOOD = 0xDC9Cu, // Mood
+ MTP_OBJ_PROP_DRM_STATUS = 0xDC9Du, // DRM Status
+ MTP_OBJ_PROP_SUB_DESCRIPTION = 0xDC9Eu, // Sub Description
+ // 0xDC9F-0xDCD0 is reserved
+
+ MTP_OBJ_PROP_IS_CROPPED = 0xDCD1u, // Is Cropped
+ MTP_OBJ_PROP_IS_COLOUR_CORRECTED = 0xDCD2u, // Is Colour Corrected
+ MTP_OBJ_PROP_IMAGE_BIT_DEPTH = 0xDCD3u, // Image Bit Depth
+ MTP_OBJ_PROP_FNUMBER = 0xDCD4u, // Fnumber (aperture ×100)
+ MTP_OBJ_PROP_EXPOSURE_TIME = 0xDCD5u, // Exposure Time (sec ×10,000)
+ MTP_OBJ_PROP_EXPOSURE_INDEX = 0xDCD6u, // Exposure Index (ISO)
+ // 0xDCD7-0xDCDF is reserved
+
+ MTP_OBJ_PROP_DISPLAY_NAME = 0xDCE0u, // Display Name
+ MTP_OBJ_PROP_BODY_TEXT = 0xDCE1u, // Body Text
+ MTP_OBJ_PROP_SUBJECT = 0xDCE2u, // Subject
+ MTP_OBJ_PROP_PRIORITY = 0xDCE3u, // Priority
+ // 0xDCE4-0xDCFF is reserved
+
+ MTP_OBJ_PROP_GIVEN_NAME = 0xDD00u, // Given Name
+ MTP_OBJ_PROP_MIDDLE_NAMES = 0xDD01u, // Middle Names
+ MTP_OBJ_PROP_FAMILY_NAME = 0xDD02u, // Family Name
+ MTP_OBJ_PROP_PREFIX = 0xDD03u, // Prefix
+ MTP_OBJ_PROP_SUFFIX = 0xDD04u, // Suffix
+ MTP_OBJ_PROP_PHONETIC_GIVEN_NAME = 0xDD05u, // Phonetic Given Name
+ MTP_OBJ_PROP_PHONETIC_FAMILY_NAME = 0xDD06u, // Phonetic Family Name
+ MTP_OBJ_PROP_EMAIL_PRIMARY = 0xDD07u, // Email Primary
+ MTP_OBJ_PROP_EMAIL_PERSONAL_1 = 0xDD08u, // Email Personal 1
+ MTP_OBJ_PROP_EMAIL_PERSONAL_2 = 0xDD09u, // Email Personal 2
+ MTP_OBJ_PROP_EMAIL_BUSINESS_1 = 0xDD0Au, // Email Business 1
+ MTP_OBJ_PROP_EMAIL_BUSINESS_2 = 0xDD0Bu, // Email Business 2
+ MTP_OBJ_PROP_EMAIL_OTHERS = 0xDD0Cu, // Email Others
+ MTP_OBJ_PROP_PHONE_PRIMARY = 0xDD0Du, // Phone Number Primary
+ MTP_OBJ_PROP_PHONE_PERSONAL_1 = 0xDD0Eu, // Phone Number Personal
+ MTP_OBJ_PROP_PHONE_PERSONAL_2 = 0xDD0Fu, // Phone Number Personal 2
+ MTP_OBJ_PROP_PHONE_BUSINESS_1 = 0xDD10u, // Phone Number Business
+ MTP_OBJ_PROP_PHONE_BUSINESS_2 = 0xDD11u, // Phone Number Business 2
+ MTP_OBJ_PROP_PHONE_MOBILE_1 = 0xDD12u, // Phone Number Mobile
+ MTP_OBJ_PROP_PHONE_MOBILE_2 = 0xDD13u, // Phone Number Mobile 2
+ MTP_OBJ_PROP_FAX_PRIMARY = 0xDD14u, // Fax Number Primary
+ MTP_OBJ_PROP_FAX_PERSONAL = 0xDD15u, // Fax Number Personal
+ MTP_OBJ_PROP_FAX_BUSINESS = 0xDD16u, // Fax Number Business
+ MTP_OBJ_PROP_PAGER_NUMBER = 0xDD17u, // Pager Number
+ MTP_OBJ_PROP_PHONE_OTHERS = 0xDD18u, // Phone Number Others
+ MTP_OBJ_PROP_WEB_PRIMARY = 0xDD19u, // Primary Web Address
+ MTP_OBJ_PROP_WEB_PERSONAL = 0xDD1Au, // Personal Web Address
+ MTP_OBJ_PROP_WEB_BUSINESS = 0xDD1Bu, // Business Web Address
+ MTP_OBJ_PROP_IM_ADDRESS_1 = 0xDD1Cu, // Instant Messenger Address
+ MTP_OBJ_PROP_IM_ADDRESS_2 = 0xDD1Du, // Instant Messenger Address 2
+ MTP_OBJ_PROP_IM_ADDRESS_3 = 0xDD1Eu, // Instant Messenger Address 3
+ MTP_OBJ_PROP_ADDR_PERSONAL_FULL = 0xDD1Fu, // Postal Address Personal Full
+ MTP_OBJ_PROP_ADDR_PERSONAL_LINE1 = 0xDD20u, // Postal Address Personal Line 1
+ MTP_OBJ_PROP_ADDR_PERSONAL_LINE2 = 0xDD21u, // Postal Address Personal Line 2
+ MTP_OBJ_PROP_ADDR_PERSONAL_CITY = 0xDD22u, // Postal Address Personal City
+ MTP_OBJ_PROP_ADDR_PERSONAL_REGION = 0xDD23u, // Postal Address Personal Region
+ MTP_OBJ_PROP_ADDR_PERSONAL_POSTAL_CODE = 0xDD24u, // Postal Address Personal Postal Code
+ MTP_OBJ_PROP_ADDR_PERSONAL_COUNTRY = 0xDD25u, // Postal Address Personal Country
+ MTP_OBJ_PROP_ADDR_BUSINESS_FULL = 0xDD26u, // Postal Address Business Full
+ MTP_OBJ_PROP_ADDR_BUSINESS_LINE1 = 0xDD27u, // Postal Address Business Line 1
+ MTP_OBJ_PROP_ADDR_BUSINESS_LINE2 = 0xDD28u, // Postal Address Business Line 2
+ MTP_OBJ_PROP_ADDR_BUSINESS_CITY = 0xDD29u, // Postal Address Business City
+ MTP_OBJ_PROP_ADDR_BUSINESS_REGION = 0xDD2Au, // Postal Address Business Region
+ MTP_OBJ_PROP_ADDR_BUSINESS_POSTAL_CODE = 0xDD2Bu, // Postal Address Business Postal Code
+ MTP_OBJ_PROP_ADDR_BUSINESS_COUNTRY = 0xDD2Cu, // Postal Address Business Country
+ MTP_OBJ_PROP_ADDR_OTHER_FULL = 0xDD2Du, // Postal Address Other Full
+ MTP_OBJ_PROP_ADDR_OTHER_LINE1 = 0xDD2Eu, // Postal Address Other Line 1
+ MTP_OBJ_PROP_ADDR_OTHER_LINE2 = 0xDD2Fu, // Postal Address Other Line 2
+ MTP_OBJ_PROP_ADDR_OTHER_CITY = 0xDD30u, // Postal Address Other City
+ MTP_OBJ_PROP_ADDR_OTHER_REGION = 0xDD31u, // Postal Address Other Region
+ MTP_OBJ_PROP_ADDR_OTHER_POSTAL_CODE = 0xDD32u, // Postal Address Other Postal Code
+ MTP_OBJ_PROP_ADDR_OTHER_COUNTRY = 0xDD33u, // Postal Address Other Country
+ MTP_OBJ_PROP_ORGANIZATION_NAME = 0xDD34u, // Organization Name
+ MTP_OBJ_PROP_PHONETIC_ORG_NAME = 0xDD35u, // Phonetic Organization Name
+ MTP_OBJ_PROP_ROLE = 0xDD36u, // Role
+ MTP_OBJ_PROP_BIRTHDATE = 0xDD37u, // Birthdate
+ // 0xDD38-0xDD3F is reserved
+
+ MTP_OBJ_PROP_MESSAGE_TO = 0xDD40u, // Message To
+ MTP_OBJ_PROP_MESSAGE_CC = 0xDD41u, // Message CC
+ MTP_OBJ_PROP_MESSAGE_BCC = 0xDD42u, // Message BCC
+ MTP_OBJ_PROP_MESSAGE_READ = 0xDD43u, // Message Read
+ MTP_OBJ_PROP_MESSAGE_RECEIVED_TIME = 0xDD44u, // Message Received Time
+ MTP_OBJ_PROP_MESSAGE_SENDER = 0xDD45u, // Message Sender
+ // 0xDD46-0xDD4F is reserved
+
+ MTP_OBJ_PROP_ACTIVITY_BEGIN_TIME = 0xDD50u, // Activity Begin Time
+ MTP_OBJ_PROP_ACTIVITY_END_TIME = 0xDD51u, // Activity End Time
+ MTP_OBJ_PROP_ACTIVITY_LOCATION = 0xDD52u, // Activity Location
+ // 0xDD53 is reserved
+ MTP_OBJ_PROP_ACTIVITY_REQUIRED_ATTENDEES= 0xDD54u, // Activity Required Attendees
+ MTP_OBJ_PROP_ACTIVITY_OPTIONAL_ATTENDEES= 0xDD55u, // Activity Optional Attendees
+ MTP_OBJ_PROP_ACTIVITY_RESOURCES = 0xDD56u, // Activity Resources
+ MTP_OBJ_PROP_ACTIVITY_ACCEPTED = 0xDD57u, // Activity Accepted
+ MTP_OBJ_PROP_ACTIVITY_TENTATIVE = 0xDD58u, // Activity Tentative
+ MTP_OBJ_PROP_ACTIVITY_DECLINED = 0xDD59u, // Activity Declined
+ MTP_OBJ_PROP_ACTIVITY_REMINDER_TIME = 0xDD5Au, // Activity Reminder Time
+ MTP_OBJ_PROP_ACTIVITY_OWNER = 0xDD5Bu, // Activity Owner
+ MTP_OBJ_PROP_ACTIVITY_STATUS = 0xDD5Cu, // Activity Status
+ MTP_OBJ_PROP_OWNER = 0xDD5Du, // Owner
+ MTP_OBJ_PROP_EDITOR = 0xDD5Eu, // Editor
+ MTP_OBJ_PROP_WEBMASTER = 0xDD5Fu, // Webmaster
+
+ MTP_OBJ_PROP_URL_SOURCE = 0xDD60u, // URL Source
+ MTP_OBJ_PROP_URL_DESTINATION = 0xDD61u, // URL Destination
+ MTP_OBJ_PROP_TIME_BOOKMARK = 0xDD62u, // Time Bookmark
+ MTP_OBJ_PROP_OBJECT_BOOKMARK = 0xDD63u, // Object Bookmark
+ MTP_OBJ_PROP_BYTE_BOOKMARK = 0xDD64u, // Byte Bookmark
+ // 0xDD65-0xDD6F is reserved
+
+ MTP_OBJ_PROP_LAST_BUILD_DATE = 0xDD70u, // Last Build Date
+ MTP_OBJ_PROP_TIME_TO_LIVE = 0xDD71u, // Time to Live (minutes)
+ MTP_OBJ_PROP_MEDIA_GUID = 0xDD72u, // Media GUID
+ // 0xDD73-0xDDFF is reserved
+
+ // media encoding
+ MTP_OBJ_PROP_TOTAL_BITRATE = 0xDE91u, // Total BitRate
+ MTP_OBJ_PROP_BITRATE_TYPE = 0xDE92u, // Bitrate Type
+ MTP_OBJ_PROP_SAMPLE_RATE = 0xDE93u, // Sample Rate
+ MTP_OBJ_PROP_NUM_CHANNELS = 0xDE94u, // Number Of Channels
+ MTP_OBJ_PROP_AUDIO_BITDEPTH = 0xDE95u, // Audio BitDepth
+ // 0xDE96 is reserved
+ MTP_OBJ_PROP_SCAN_TYPE = 0xDE97u, // Scan Type
+ // 0xDE98 is reserved
+ MTP_OBJ_PROP_AUDIO_WAVE_CODEC = 0xDE99u, // Audio WAVE Codec
+ MTP_OBJ_PROP_AUDIO_BITRATE = 0xDE9Au, // Audio BitRate
+ MTP_OBJ_PROP_VIDEO_FOURCC_CODEC = 0xDE9Bu, // Video FourCC Codec
+ MTP_OBJ_PROP_VIDEO_BITRATE = 0xDE9Cu, // Video BitRate
+ MTP_OBJ_PROP_FRAMES_PER_KSEC = 0xDE9Du, // Frames Per Thousand Seconds
+ MTP_OBJ_PROP_KEYFRAME_DISTANCE = 0xDE9Eu, // KeyFrame Distance (ms)
+ MTP_OBJ_PROP_BUFFER_SIZE = 0xDE9Fu, // Buffer Size
+ MTP_OBJ_PROP_ENCODING_QUALITY = 0xDEA0u, // Encoding Quality
+ MTP_OBJ_PROP_ENCODING_PROFILE = 0xDEA1u // Encoding Profile
+} mtp_object_properties_t;
+
+
+// MTP 1.1 Appendeix C: Device Properties
+typedef enum {
+ MTP_DEV_PROP_UNDEFINED = 0x5000u,
+ MTP_DEV_PROP_BATTERY_LEVEL = 0x5001u,
+ MTP_DEV_PROP_FUNCTIONAL_MODE = 0x5002u,
+ MTP_DEV_PROP_IMAGE_SIZE = 0x5003u,
+ MTP_DEV_PROP_COMPRESSION_SETTING = 0x5004u,
+ MTP_DEV_PROP_WHITE_BALANCE = 0x5005u,
+ MTP_DEV_PROP_RGB_GAIN = 0x5006u,
+ MTP_DEV_PROP_F_NUMBER = 0x5007u,
+ MTP_DEV_PROP_FOCAL_LENGTH = 0x5008u,
+ MTP_DEV_PROP_FOCUS_DISTANCE = 0x5009u,
+ MTP_DEV_PROP_FOCUS_MODE = 0x500Au,
+ MTP_DEV_PROP_EXPOSURE_METERING_MODE = 0x500Bu,
+ MTP_DEV_PROP_FLASH_MODE = 0x500Cu,
+ MTP_DEV_PROP_EXPOSURE_TIME = 0x500Du,
+ MTP_DEV_PROP_EXPOSURE_PROGRAM_MODE = 0x500Eu,
+ MTP_DEV_PROP_EXPOSURE_INDEX = 0x500Fu,
+ MTP_DEV_PROP_EXPOSURE_BIAS_COMPENSATION = 0x5010u,
+ MTP_DEV_PROP_DATE_TIME = 0x5011u,
+ MTP_DEV_PROP_CAPTURE_DELAY = 0x5012u,
+ MTP_DEV_PROP_STILL_CAPTURE_MODE = 0x5013u,
+ MTP_DEV_PROP_CONTRAST = 0x5014u,
+ MTP_DEV_PROP_SHARPNESS = 0x5015u,
+ MTP_DEV_PROP_DIGITAL_ZOOM = 0x5016u,
+ MTP_DEV_PROP_EFFECT_MODE = 0x5017u,
+ MTP_DEV_PROP_BURST_NUMBER = 0x5018u,
+ MTP_DEV_PROP_BURST_INTERVAL = 0x5019u,
+ MTP_DEV_PROP_TIMELAPSE_NUMBER = 0x501Au,
+ MTP_DEV_PROP_TIMELAPSE_INTERVAL = 0x501Bu,
+ MTP_DEV_PROP_FOCUS_METERING_MODE = 0x501Cu,
+ MTP_DEV_PROP_UPLOAD_URL = 0x501Du,
+ MTP_DEV_PROP_ARTIST = 0x501Eu,
+ MTP_DEV_PROP_COPYRIGHT_INFO = 0x501Fu,
+ MTP_DEV_PROP_SYNCHRONIZTION_PARTNER = 0xD401,
+ MTP_DEV_PROP_DEVICE_FRIENDLY_NAME = 0xD402u,
+ MTP_DEV_PROP_VOLUME = 0xD403u,
+ MTP_DEV_PROP_SUPPORTED_FORMATS_ORDERED = 0xD404u,
+ MTP_DEV_PROP_DEVICE_ICON = 0xD405u,
+ MTP_DEV_PROP_SECTION_INITIATOR_VERSION_INFO = 0xD406u,
+ MTP_DEV_PROP_PERCEIVED_DEVICE_TYPE = 0xD407u,
+ MTP_DEV_PROP_PLAYBACK_RATE = 0xD410u,
+ MTP_DEV_PROP_PLAYBACK_OBJECT = 0xD411u,
+ MTP_DEV_PROP_PLAYBACK_CONTAINER_INDEX = 0xD412u,
+} mtp_event_properties_t;
+
+// MTP 1.1 Appendix D: Operations
+typedef enum {
+ MTP_OP_UNDEFINED = 0x1000u,
+ MTP_OP_GET_DEVICE_INFO = 0x1001u,
+ MTP_OP_OPEN_SESSION = 0x1002u,
+ MTP_OP_CLOSE_SESSION = 0x1003u,
+ MTP_OP_GET_STORAGE_IDS = 0x1004u,
+ MTP_OP_GET_STORAGE_INFO = 0x1005u,
+ MTP_OP_GET_NUM_OBJECTS = 0x1006u,
+ MTP_OP_GET_OBJECT_HANDLES = 0x1007u,
+ MTP_OP_GET_OBJECT_INFO = 0x1008u,
+ MTP_OP_GET_OBJECT = 0x1009u,
+ MTP_OP_GET_THUMB = 0x100Au,
+ MTP_OP_DELETE_OBJECT = 0x100Bu,
+ MTP_OP_SEND_OBJECT_INFO = 0x100Cu,
+ MTP_OP_SEND_OBJECT = 0x100Du,
+ MTP_OP_INITIATE_CAPTURE = 0x100Eu,
+ MTP_OP_FORMAT_STORE = 0x100Fu,
+ MTP_OP_RESET_DEVICE = 0x1010u,
+ MTP_OP_SELF_TEST = 0x1011u,
+ MTP_OP_SET_OBJECT_PROTECTION = 0x1012u,
+ MTP_OP_POWER_DOWN = 0x1013u,
+ MTP_OP_GET_DEVICE_PROP_DESC = 0x1014u,
+ MTP_OP_GET_DEVICE_PROP_VALUE = 0x1015u,
+ MTP_OP_SET_DEVICE_PROP_VALUE = 0x1016u,
+ MTP_OP_RESET_DEVICE_PROP_VALUE = 0x1017u,
+ MTP_OP_TERMINATE_OPEN_CAPTURE = 0x1018u,
+ MTP_OP_MOVE_OBJECT = 0x1019u,
+ MTP_OP_COPY_OBJECT = 0x101Au,
+ MTP_OP_GET_PARTIAL_OBJECT = 0x101Bu,
+ MTP_OP_INITIATE_OPEN_CAPTURE = 0x101Bu,
+ MTP_OP_GET_OBJECT_PROPS_SUPPORTED = 0x9801u,
+ MTP_OP_GET_OBJECT_PROP_DESC = 0x9802u,
+ MTP_OP_GET_OBJECT_PROP_VALUE = 0x9803u,
+ MTP_OP_SET_OBJECT_PROP_VALUE = 0x9804u,
+ MTP_OP_GET_OBJECT_PROPLIST = 0x9805u,
+ MTP_OP_GET_OBJECT_PROP_REFERENCES = 0x9810u,
+
+ MTP_OP_GET_SERVICE_IDS = 0x9301u,
+ MTP_OP_GET_SERVICE_INFO = 0x9302u,
+ MTP_OP_GET_SERVICE_CAPABILITIES = 0x9303u,
+ MTP_OP_GET_SERVICE_PROP_DESC = 0x9304u,
+
+ // Appendix E: Enhanced Operations
+ MTP_OP_GET_OBJECT_PROP_LIST = 0x9805u,
+ MTP_OP_SET_OBJECT_PROP_LIST = 0x9806u,
+ MTP_OP_GET_INTERDEPENDENT_PROP_DESC = 0x9807u,
+ MTP_OP_SEND_OBJECT_PROP_LIST = 0x9808u,
+} mtp_operation_code_t;
+
+// Appendix F: Responses
+typedef enum {
+ MTP_RESP_UNDEFINED = 0x2000u,
+ MTP_RESP_OK = 0x2001u,
+ MTP_RESP_GENERAL_ERROR = 0x2002u,
+ MTP_RESP_SESSION_NOT_OPEN = 0x2003u,
+ MTP_RESP_INVALID_TRANSACTION_ID = 0x2004u,
+ MTP_RESP_OPERATION_NOT_SUPPORTED = 0x2005u,
+ MTP_RESP_PARAMETER_NOT_SUPPORTED = 0x2006u,
+ MTP_RESP_INCOMPLETE_TRANSFER = 0x2007u,
+ MTP_RESP_INVALID_STORAGE_ID = 0x2008u,
+ MTP_RESP_INVALID_OBJECT_HANDLE = 0x2009u,
+ MTP_RESP_DEVICE_PROP_NOT_SUPPORTED = 0x200Au,
+ MTP_RESP_INVALID_OBJECT_FORMAT_CODE = 0x200Bu,
+ MTP_RESP_STORE_FULL = 0x200Cu,
+ MTP_RESP_OBJECT_WRITE_PROTECTED = 0x200Du,
+ MPT_RESC_STORE_READ_ONLY = 0x200Eu,
+ MTP_RESP_ACCESS_DENIED = 0x200Fu,
+ MTP_RESP_NO_THUMBNAIL_PRESENT = 0x2010u,
+ MTP_RESP_SELF_TEST_FAILED = 0x2011u,
+ MTP_RESP_PARTIAL_DELETION = 0x2012u,
+ MTP_RESP_STORE_NOT_AVAILABLE = 0x2013u,
+ MTP_RESP_SPECIFICATION_BY_FORMAT_UNSUPPORTED = 0x2014u,
+ MTP_RESP_NO_VALID_OBJECTINFO = 0x2015u,
+ MTP_RESP_INVALID_CODE_FORMAT = 0x2016u,
+ MTP_RESP_UNKNOWN_VENDOR_CODE = 0x2017u,
+ MTP_RESP_CAPTURE_ALREADY_TERMINATED = 0x2018u,
+ MTP_RESP_DEVICE_BUSY = 0x2019u,
+ MTP_RESP_INVALID_PARENT_OBJECT = 0x201Au,
+ MTP_RESP_INVALID_DEVICE_PROP_FORMAT = 0x201Bu,
+ MTP_RESP_INVALID_DEVICE_PROP_VALUE = 0x201Cu,
+ MTP_RESP_INVALID_PARAMETER = 0x201Du,
+ MTP_RESP_SESSION_ALREADY_OPEN = 0x201Eu,
+ MTP_RESP_TRANSACTION_CANCELLED = 0x201Fu,
+ MTP_RESP_SPEC_OF_DESTINATION_UNSUPPORTED = 0x2020u,
+
+ MTP_RESP_INVALID_OBJECT_PROP_CODE = 0xA801u,
+ MTP_RESP_INVALID_OBJECT_PROP_FORMAT = 0xA802u,
+ MTP_RESP_INVALID_OBJECT_PROP_VALUE = 0xA803u,
+ MTP_RESP_INVALID_OBJECT_REFERENCE = 0xA804u,
+ MTP_RESP_GROUP_NOT_SUPPORTED = 0xA805u,
+ MTP_RESP_INVALID_DATASET = 0xA806u,
+ MTP_RESP_SPEC_BY_GROUP_UNSUPPORTED = 0xA807u,
+ MTP_RESP_SPEC_BY_DEPTH_UNSUPPORTED = 0xA808u,
+ MTP_RESP_OBJECT_TOO_LARGE = 0xA809u,
+ MTP_RESP_OBJECT_PROP_NOT_SUPPORTED = 0xA80Au,
+} mtp_response_t;
+
+// Appendix G: Events
+typedef enum {
+ MTP_EVENT_UNDEFINED = 0x4000,
+ MTP_EVENT_CANCEL_TRANSACTION = 0x4001,
+ MTP_EVENT_OBJECT_ADDED = 0x4002,
+ MTP_EVENT_OBJECT_REMOVED = 0x4003,
+ MTP_EVENT_STORE_ADDED = 0x4004,
+ MTP_EVENT_STORE_REMOVED = 0x4005,
+ MTP_EVENT_DEVICE_PROP_CHANGED = 0x4006,
+ MTP_EVENT_OBJECT_INFO_CHANGED = 0x4007,
+ MTP_EVENT_DEVICE_INFO_CHANGED = 0x4008,
+ MTP_EVENT_REQUEST_OBJECT_TRANSFER = 0x4009,
+ MTP_EVENT_STORE_FULL = 0x400Au,
+ MTP_EVENT_DEVICE_RESET = 0x400Bu,
+ MTP_EVENT_STORAGE_INFO_CHANGED = 0x400Cu,
+ MTP_EVENT_CAPTURE_COMPLETE = 0x400Du,
+ MTP_EVENT_UNREPORTED_STATUS = 0x400Eu,
+ MTP_EVENT_OBJECT_PROP_CHANGED = 0xC801u,
+ MTP_EVENT_OBJECT_PROP_DESC_CHANGED = 0xC802u,
+ MTP_EVENT_OBJECT_REFERENCES_CHANGED = 0xC803u,
+} mtp_event_code_t;
+
+// Datatypes
+typedef enum {
+ MTP_DATA_TYPE_UNDEFINED = 0x0000u,
+ // scalars
+ MTP_DATA_TYPE_INT8 = 0x0001u,
+ MTP_DATA_TYPE_UINT8 = 0x0002u,
+ MTP_DATA_TYPE_INT16 = 0x0003u,
+ MTP_DATA_TYPE_UINT16 = 0x0004u,
+ MTP_DATA_TYPE_INT32 = 0x0005u,
+ MTP_DATA_TYPE_UINT32 = 0x0006u,
+ MTP_DATA_TYPE_INT64 = 0x0007u,
+ MTP_DATA_TYPE_UINT64 = 0x0008u,
+ MTP_DATA_TYPE_INT128 = 0x0009u,
+ MTP_DATA_TYPE_UINT128 = 0x000Au,
+ // array
+ MTP_DATA_TYPE_AINT8 = 0x4001u,
+ MTP_DATA_TYPE_AUINT8 = 0x4002u,
+ MTP_DATA_TYPE_AINT16 = 0x4003u,
+ MTP_DATA_TYPE_AUINT16 = 0x4004u,
+ MTP_DATA_TYPE_AINT32 = 0x4005u,
+ MTP_DATA_TYPE_AUINT32 = 0x4006u,
+ MTP_DATA_TYPE_AINT64 = 0x4007u,
+ MTP_DATA_TYPE_AUINT64 = 0x4008u,
+ MTP_DATA_TYPE_AINT128 = 0x4009u,
+ MTP_DATA_TYPE_AUINT128 = 0x400Au,
+ MTP_DATA_TYPE_STR = 0xFFFFu,
+} mtp_data_type_t;
+
+// Get/Set
+typedef enum {
+ MTP_MODE_GET = 0x00u,
+ MTP_MODE_GET_SET = 0x01u,
+} mtp_mode_get_set_t;
+
+typedef enum {
+ MTP_STORAGE_TYPE_UNDEFINED = 0x0000u,
+ MTP_STORAGE_TYPE_FIXED_ROM = 0x0001u,
+ MTP_STORAGE_TYPE_REMOVABLE_ROM = 0x0002u,
+ MTP_STORAGE_TYPE_FIXED_RAM = 0x0003u,
+ MTP_STORAGE_TYPE_REMOVABLE_RAM = 0x0004u,
+} mtp_storage_type_t;
+
+typedef enum {
+ MTP_FILESYSTEM_TYPE_UNDEFINED = 0x0000u,
+ MTP_FILESYSTEM_TYPE_GENERIC_FLAT = 0x0001u,
+ MTP_FILESYSTEM_TYPE_GENERIC_HIERARCHICAL = 0x0002u,
+ MTP_FILESYSTEM_TYPE_DCF = 0x0003u,
+} mtp_filesystem_type_t;
+
+typedef enum {
+ MTP_ACCESS_CAPABILITY_READ_WRITE = 0x0000u,
+ MTP_ACCESS_CAPABILITY_READ_ONLY_WITHOUT_OBJECT_DELETION = 0x0001u,
+ MTP_ACCESS_CAPABILITY_READ_ONLY_WITH_OBJECT_DELETION = 0x0002u,
+} mtp_access_capability_t;
+
+typedef enum {
+ MTP_PROTECTION_STATUS_NO_PROTECTION = 0x0000u,
+ MTP_PROTECTION_STATUS_READ_ONLY = 0x0001u,
+ MTP_PROTECTION_STATUS_READ_ONLY_DATA = 0x8002u,
+ MTP_PROTECTION_NON_TRANSFERABLE_DATA = 0x8003u,
+} mtp_protection_status_t;
+
+typedef enum {
+ MTP_ASSOCIATION_UNDEFINED = 0x0000u,
+ MTP_ASSOCIATION_GENERIC_FOLDER = 0x0001u,
+ MTP_ASSOCIATION_ALBUM = 0x0002u,
+ MTP_ASSOCIATION_TIME_SEQUENCE = 0x0003u,
+ MTP_ASSOCIATION_HORIZONTAL_PANORAMIC = 0x0004u,
+ MTP_ASSOCIATION_VERTICAL_PANORAMIC = 0x0005u,
+ MTP_ASSOCIATION_2D_PANORAMIC = 0x0006u,
+ MTP_ASSOCIATION_ANCILLARY_DATA = 0x0007u,
+} mtp_association_t;
+
+//--------------------------------------------------------------------+
+// Data structures
+//--------------------------------------------------------------------+
+typedef struct TU_ATTR_PACKED {
+ uint32_t len;
+ uint16_t type;
+ uint16_t code;
+ uint32_t transaction_id;
+} mtp_container_header_t;
+TU_VERIFY_STATIC(sizeof(mtp_container_header_t) == 12, "size is not correct");
+
+typedef struct TU_ATTR_PACKED {
+ mtp_container_header_t header;
+ uint32_t params[5];
+} mtp_container_command_t;
+TU_VERIFY_STATIC(sizeof(mtp_container_command_t) == 32, "size is not correct");
+
+// PTP/MTP Generic container
+typedef struct TU_ATTR_PACKED {
+ mtp_container_header_t header;
+ uint8_t payload[(CFG_TUD_MTP_EP_BUFSIZE - sizeof(mtp_container_header_t))];
+} mtp_generic_container_t;
+
+typedef struct {
+ mtp_container_header_t* header;
+ union {
+ uint8_t* payload;
+ uint16_t* payload16;
+ uint32_t* payload32;
+ };
+ uint32_t payload_bytes; // available bytes for read/write
+} mtp_container_info_t;
+
+typedef struct TU_ATTR_PACKED {
+ uint16_t code;
+ uint32_t session_id;
+ uint32_t transaction_id;
+ uint32_t params[3];
+} mtp_event_t;
+TU_VERIFY_STATIC(sizeof(mtp_event_t) == 22, "size is not correct");
+
+#define mtp_string_t(_nchars) \
+ struct TU_ATTR_PACKED { \
+ uint8_t count; /* in characters including null */ \
+ uint16_t utf16[_nchars]; \
+ }
+
+#define mtp_array_t(_type, _count) \
+ struct TU_ATTR_PACKED { \
+ uint32_t count; \
+ _type arr[_count];\
+ }
+
+#define mtp_aint8_t(_count) mtp_array_t(int8_t, _count)
+#define mtp_auint16_t(_count) mtp_array_t(uint16_t, _count)
+#define mtp_auint32_t(_count) mtp_array_t(uint32_t, _count)
+#define mtp_auint64_t(_count) mtp_array_t(uint64_t, _count)
+
+#define MTP_STORAGE_INFO_STRUCT(_storage_desc_chars, _volume_id_chars) \
+ struct TU_ATTR_PACKED { \
+ uint16_t storage_type; \
+ uint16_t filesystem_type; \
+ uint16_t access_capability; \
+ uint64_t max_capacity_in_bytes; \
+ uint64_t free_space_in_bytes; \
+ uint32_t free_space_in_objects; \
+ mtp_string_t(_storage_desc_chars) storage_description; \
+ mtp_string_t(_volume_id_chars) volume_identifier; \
+ }
+
+// Object Info Dataset without dynamic string: filename, date_created, date_modified, keywords
+typedef struct TU_ATTR_PACKED {
+ uint32_t storage_id;
+ uint16_t object_format;
+ uint16_t protection_status;
+ uint32_t object_compressed_size;
+ uint16_t thumb_format;
+ uint32_t thumb_compressed_size;
+ uint32_t thumb_pix_width;
+ uint32_t thumb_pix_height;
+ uint32_t image_pix_width;
+ uint32_t image_pix_height;
+ uint32_t image_bit_depth;
+ uint32_t parent_object; // 0: root
+ uint16_t association_type;
+ uint32_t association_desc;
+ uint32_t sequence_number;
+ // mtp_string_t() filename
+ // mtp_string_t() date_created
+ // mtp_string_t() date_modified
+ // mtp_string_t() keywords
+} mtp_object_info_header_t;
+
+// Device property desc up to get/set
+typedef struct TU_ATTR_PACKED {
+ uint16_t device_property_code;
+ uint16_t datatype;
+ uint8_t get_set;
+} mtp_device_prop_desc_header_t;
+
+// The following fields will be dynamically added to the struct at runtime:
+// - wstring factory_def_value;
+// - wstring current_value_len;
+// - uint8_t form_flag;
+
+// no form
+#define MTP_DEVICE_PROPERTIES_STRUCT(_type) \
+ struct TU_ATTR_PACKED { \
+ uint16_t device_property_code; \
+ uint16_t datatype; \
+ uint8_t get_set; \
+ _type factory_default; \
+ _type current_value; \
+ uint8_t form_flag; /* 0: none, 1: range, 2: enum */ \
+ };
+
+typedef struct TU_ATTR_PACKED {
+ uint16_t code;
+ uint32_t transaction_id;
+} mtp_request_reset_cancel_data_t;
+TU_VERIFY_STATIC(sizeof(mtp_request_reset_cancel_data_t) == 6, "size is not correct");
+
+//--------------------------------------------------------------------+
+// Container helper function
+// return number of bytes added
+//--------------------------------------------------------------------+
+
+// return payload buffer for next write
+TU_ATTR_ALWAYS_INLINE static inline uint8_t* mtp_container_payload_ptr(mtp_container_info_t* p_container) {
+ // only 1st packet include header
+ uint32_t pos = p_container->header->len - sizeof(mtp_container_header_t);
+ while (pos > CFG_TUD_MTP_EP_BUFSIZE) {
+ pos -= CFG_TUD_MTP_EP_BUFSIZE;
+ }
+ return p_container->payload + pos;
+}
+
+// only add_raw does partial copy
+TU_ATTR_ALWAYS_INLINE static inline uint32_t mtp_container_add_raw(mtp_container_info_t* p_container, const void* data, uint32_t len) {
+ uint8_t* buf = mtp_container_payload_ptr(p_container);
+ const uint32_t added_len = tu_min32(len, CFG_TUD_MTP_EP_BUFSIZE - p_container->header->len);
+ if (added_len > 0) {
+ memcpy(buf, data, added_len);
+ }
+ p_container->header->len += len; // always increase len, even partial copy
+ return added_len;
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t mtp_container_add_array(mtp_container_info_t* p_container, uint8_t scalar_size, uint32_t count, const void* data) {
+ const uint32_t added_len = 4 + count * scalar_size;
+ TU_ASSERT(p_container->header->len + added_len < CFG_TUD_MTP_EP_BUFSIZE, 0);
+ uint8_t* buf = p_container->payload + p_container->header->len - sizeof(mtp_container_header_t);
+
+ tu_unaligned_write32(buf, count);
+ p_container->header->len += 4;
+ buf += 4;
+
+ memcpy(buf, data, count * scalar_size);
+ p_container->header->len += count * scalar_size;
+
+ return added_len;
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t mtp_container_add_string(mtp_container_info_t* p_container, uint16_t* utf16) {
+ uint8_t count = 0;
+ while (utf16[count]) {
+ count++;
+ }
+ const uint32_t added_len = 1u + 2u * count;
+ TU_ASSERT(p_container->header->len + added_len < CFG_TUD_MTP_EP_BUFSIZE, 0);
+ uint8_t* buf = p_container->payload + p_container->header->len - sizeof(mtp_container_header_t);
+
+ *buf++ = count;
+ p_container->header->len++;
+
+ memcpy(buf, utf16, 2 * count);
+ p_container->header->len += 2 * count;
+
+ return added_len;
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t mtp_container_add_cstring(mtp_container_info_t* p_container, const char* str) {
+ const uint8_t len = (uint8_t) (strlen(str) + 1); // include null
+ TU_ASSERT(p_container->header->len + 1 + 2 * len < CFG_TUD_MTP_EP_BUFSIZE, 0);
+ uint8_t* buf = p_container->payload + p_container->header->len - sizeof(mtp_container_header_t);
+
+ if (len == 1) {
+ // empty string (null only): single zero byte
+ *buf = 0;
+ p_container->header->len++;
+ return 1;
+ } else {
+ *buf++ = len;
+ p_container->header->len++;
+
+ for (uint8_t i = 0; i < len; i++) {
+ buf[0] = str[i];
+ buf[1] = 0;
+ buf += 2;
+ p_container->header->len += 2;
+ }
+ return 1u + 2u * len;
+ }
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t mtp_container_add_uint8(mtp_container_info_t* p_container, uint8_t data) {
+ return mtp_container_add_raw(p_container, &data, 1);
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t mtp_container_add_uint16(mtp_container_info_t* p_container, uint16_t data) {
+ return mtp_container_add_raw(p_container, &data, 2);
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t mtp_container_add_uint32(mtp_container_info_t* p_container, uint32_t data) {
+ return mtp_container_add_raw(p_container, &data, 4);
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t mtp_container_add_uint64(mtp_container_info_t* p_container, uint64_t data) {
+ return mtp_container_add_raw(p_container, &data, 8);
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t mtp_container_add_uint128(mtp_container_info_t* p_container, const void* data) {
+ return mtp_container_add_raw(p_container, data, 16);
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t mtp_container_add_auint8(mtp_container_info_t* p_container, uint32_t count, const uint8_t* data) {
+ return mtp_container_add_array(p_container, sizeof(uint8_t), count, data);
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t mtp_container_add_auint16(mtp_container_info_t* p_container, uint32_t count, const uint16_t* data) {
+ return mtp_container_add_array(p_container, sizeof(uint16_t), count, data);
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t mtp_container_add_auint32(mtp_container_info_t* p_container, uint32_t count, const uint32_t* data) {
+ return mtp_container_add_array(p_container, sizeof(uint32_t), count, data);
+}
+
+//--------------------------------------------------------------------+
+//
+//--------------------------------------------------------------------+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t mtp_container_get_string(uint8_t* buf, uint16_t utf16[]) {
+ uint8_t nchars = *buf++;
+ memcpy(utf16, buf, 2 * nchars);
+ return 1u + 2u * nchars;
+}
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif
+#endif
diff --git a/src/class/mtp/mtp_device.c b/src/class/mtp/mtp_device.c
new file mode 100644
index 000000000..798a965eb
--- /dev/null
+++ b/src/class/mtp/mtp_device.c
@@ -0,0 +1,540 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2025 Ennebi Elettronica (https://ennebielettronica.com)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+
+#include "tusb_option.h"
+
+#if (CFG_TUD_ENABLED && CFG_TUD_MTP)
+
+//--------------------------------------------------------------------+
+// INCLUDE
+//--------------------------------------------------------------------+
+#include "device/dcd.h"
+#include "device/usbd.h"
+#include "device/usbd_pvt.h"
+
+#include "mtp_device.h"
+
+// Level where CFG_TUSB_DEBUG must be at least for this driver is logged
+#ifndef CFG_TUD_MTP_LOG_LEVEL
+ #define CFG_TUD_MTP_LOG_LEVEL CFG_TUD_LOG_LEVEL
+#endif
+
+#define TU_LOG_DRV(...) TU_LOG(CFG_TUD_MTP_LOG_LEVEL, __VA_ARGS__)
+
+//--------------------------------------------------------------------+
+// Weak stubs: invoked if no strong implementation is available
+//--------------------------------------------------------------------+
+TU_ATTR_WEAK bool tud_mtp_request_cancel_cb(tud_mtp_request_cb_data_t* cb_data) {
+ (void) cb_data;
+ return false;
+}
+TU_ATTR_WEAK bool tud_mtp_request_device_reset_cb(tud_mtp_request_cb_data_t* cb_data) {
+ (void) cb_data;
+ return false;
+}
+TU_ATTR_WEAK int32_t tud_mtp_request_get_extended_event_cb(tud_mtp_request_cb_data_t* cb_data) {
+ (void) cb_data;
+ return -1;
+}
+TU_ATTR_WEAK int32_t tud_mtp_request_get_device_status_cb(tud_mtp_request_cb_data_t* cb_data) {
+ (void) cb_data;
+ return -1;
+}
+TU_ATTR_WEAK bool tud_mtp_request_vendor_cb(tud_mtp_request_cb_data_t* cb_data) {
+ (void) cb_data;
+ return false;
+}
+TU_ATTR_WEAK int32_t tud_mtp_command_received_cb(tud_mtp_cb_data_t * cb_data) {
+ (void) cb_data;
+ return -1;
+}
+TU_ATTR_WEAK int32_t tud_mtp_data_xfer_cb(tud_mtp_cb_data_t* cb_data) {
+ (void) cb_data;
+ return -1;
+}
+TU_ATTR_WEAK int32_t tud_mtp_data_complete_cb(tud_mtp_cb_data_t* cb_data) {
+ (void) cb_data;
+ return -1;
+}
+TU_ATTR_WEAK int32_t tud_mtp_response_complete_cb(tud_mtp_cb_data_t* cb_data) {
+ (void) cb_data;
+ return -1;
+}
+
+//--------------------------------------------------------------------+
+// STRUCT
+//--------------------------------------------------------------------+
+typedef struct {
+ uint8_t rhport;
+ uint8_t itf_num;
+ uint8_t ep_in;
+ uint8_t ep_out;
+ uint8_t ep_event;
+
+ // Bulk Only Transfer (BOT) Protocol
+ uint8_t phase;
+
+ uint32_t total_len;
+ uint32_t xferred_len;
+
+ uint32_t session_id;
+ mtp_container_command_t command;
+ mtp_container_header_t io_header;
+
+ TU_ATTR_ALIGNED(4) uint8_t control_buf[CFG_TUD_MTP_EP_CONTROL_BUFSIZE];
+} mtpd_interface_t;
+
+typedef struct {
+ TUD_EPBUF_DEF(buf, CFG_TUD_MTP_EP_BUFSIZE);
+ TUD_EPBUF_TYPE_DEF(mtp_event_t, buf_event);
+} mtpd_epbuf_t;
+
+//--------------------------------------------------------------------+
+// INTERNAL FUNCTION DECLARATION
+//--------------------------------------------------------------------+
+static mtpd_interface_t _mtpd_itf;
+CFG_TUD_MEM_SECTION static mtpd_epbuf_t _mtpd_epbuf;
+
+static void preprocess_cmd(mtpd_interface_t* p_mtp, tud_mtp_cb_data_t* cb_data);
+
+//--------------------------------------------------------------------+
+// Debug
+//--------------------------------------------------------------------+
+#if CFG_TUSB_DEBUG >= CFG_TUD_MTP_LOG_LEVEL
+
+TU_ATTR_UNUSED static tu_lookup_entry_t const _mpt_op_lookup[] = {
+{.key = MTP_OP_UNDEFINED , .data = "Undefined" } ,
+{.key = MTP_OP_GET_DEVICE_INFO , .data = "GetDeviceInfo" } ,
+{.key = MTP_OP_OPEN_SESSION , .data = "OpenSession" } ,
+{.key = MTP_OP_CLOSE_SESSION , .data = "CloseSession" } ,
+{.key = MTP_OP_GET_STORAGE_IDS , .data = "GetStorageIDs" } ,
+{.key = MTP_OP_GET_STORAGE_INFO , .data = "GetStorageInfo" } ,
+{.key = MTP_OP_GET_NUM_OBJECTS , .data = "GetNumObjects" } ,
+{.key = MTP_OP_GET_OBJECT_HANDLES , .data = "GetObjectHandles" } ,
+{.key = MTP_OP_GET_OBJECT_INFO , .data = "GetObjectInfo" } ,
+{.key = MTP_OP_GET_OBJECT , .data = "GetObject" } ,
+{.key = MTP_OP_GET_THUMB , .data = "GetThumb" } ,
+{.key = MTP_OP_DELETE_OBJECT , .data = "DeleteObject" } ,
+{.key = MTP_OP_SEND_OBJECT_INFO , .data = "SendObjectInfo" } ,
+{.key = MTP_OP_SEND_OBJECT , .data = "SendObject" } ,
+{.key = MTP_OP_INITIATE_CAPTURE , .data = "InitiateCapture" } ,
+{.key = MTP_OP_FORMAT_STORE , .data = "FormatStore" } ,
+{.key = MTP_OP_RESET_DEVICE , .data = "ResetDevice" } ,
+{.key = MTP_OP_SELF_TEST , .data = "SelfTest" } ,
+{.key = MTP_OP_SET_OBJECT_PROTECTION , .data = "SetObjectProtection" } ,
+{.key = MTP_OP_POWER_DOWN , .data = "PowerDown" } ,
+{.key = MTP_OP_GET_DEVICE_PROP_DESC , .data = "GetDevicePropDesc" } ,
+{.key = MTP_OP_GET_DEVICE_PROP_VALUE , .data = "GetDevicePropValue" } ,
+{.key = MTP_OP_SET_DEVICE_PROP_VALUE , .data = "SetDevicePropValue" } ,
+{.key = MTP_OP_RESET_DEVICE_PROP_VALUE , .data = "ResetDevicePropValue" } ,
+{.key = MTP_OP_TERMINATE_OPEN_CAPTURE , .data = "TerminateOpenCapture" } ,
+{.key = MTP_OP_MOVE_OBJECT , .data = "MoveObject" } ,
+{.key = MTP_OP_COPY_OBJECT , .data = "CopyObject" } ,
+{.key = MTP_OP_GET_PARTIAL_OBJECT , .data = "GetPartialObject" } ,
+{.key = MTP_OP_INITIATE_OPEN_CAPTURE , .data = "InitiateOpenCapture" } ,
+{.key = MTP_OP_GET_OBJECT_PROPS_SUPPORTED , .data = "GetObjectPropsSupported" } ,
+{.key = MTP_OP_GET_OBJECT_PROP_DESC , .data = "GetObjectPropDesc" } ,
+{.key = MTP_OP_GET_OBJECT_PROP_VALUE , .data = "GetObjectPropValue" } ,
+{.key = MTP_OP_SET_OBJECT_PROP_VALUE , .data = "SetObjectPropValue" } ,
+{.key = MTP_OP_GET_OBJECT_PROPLIST , .data = "GetObjectPropList" } ,
+{.key = MTP_OP_GET_OBJECT_PROP_REFERENCES , .data = "GetObjectPropReferences" } ,
+{.key = MTP_OP_GET_SERVICE_IDS , .data = "GetServiceIDs" } ,
+{.key = MTP_OP_GET_SERVICE_INFO , .data = "GetServiceInfo" } ,
+{.key = MTP_OP_GET_SERVICE_CAPABILITIES , .data = "GetServiceCapabilities" } ,
+{.key = MTP_OP_GET_SERVICE_PROP_DESC , .data = "GetServicePropDesc" } ,
+{.key = MTP_OP_GET_OBJECT_PROP_LIST , .data = "GetObjectPropList" } ,
+{.key = MTP_OP_SET_OBJECT_PROP_LIST , .data = "SetObjectPropList" } ,
+{.key = MTP_OP_GET_INTERDEPENDENT_PROP_DESC , .data = "GetInterdependentPropDesc" } ,
+{.key = MTP_OP_SEND_OBJECT_PROP_LIST , .data = "SendObjectPropList" }
+};
+
+TU_ATTR_UNUSED static tu_lookup_table_t const _mtp_op_table = {
+ .count = TU_ARRAY_SIZE(_mpt_op_lookup),
+ .items = _mpt_op_lookup
+};
+
+TU_ATTR_UNUSED static const char* _mtp_phase_str[] = {
+ "Command",
+ "Data",
+ "Response",
+ "Error"
+};
+
+#endif
+
+
+//--------------------------------------------------------------------+
+// Helper
+//--------------------------------------------------------------------+
+static bool prepare_new_command(mtpd_interface_t* p_mtp) {
+ p_mtp->phase = MTP_PHASE_COMMAND;
+ return usbd_edpt_xfer(p_mtp->rhport, p_mtp->ep_out, _mtpd_epbuf.buf, CFG_TUD_MTP_EP_BUFSIZE);
+}
+
+static bool mtpd_data_xfer(mtp_container_info_t* p_container, uint8_t ep_addr) {
+ mtpd_interface_t* p_mtp = &_mtpd_itf;
+ if (p_mtp->phase == MTP_PHASE_COMMAND) {
+ // 1st data block: header + payload
+ p_mtp->phase = MTP_PHASE_DATA;
+ p_mtp->xferred_len = 0;
+
+ if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) {
+ p_mtp->total_len = p_container->header->len;
+ p_container->header->type = MTP_CONTAINER_TYPE_DATA_BLOCK;
+ p_container->header->transaction_id = p_mtp->command.header.transaction_id;
+ p_mtp->io_header = *p_container->header; // save header for subsequent data
+ } else {
+ // OUT transfer: total length is at least max packet size
+ p_mtp->total_len = tu_max32(p_container->header->len, CFG_TUD_MTP_EP_BUFSIZE);
+ }
+ } else {
+ // subsequent data block: payload only
+ TU_ASSERT(p_mtp->phase == MTP_PHASE_DATA);
+ }
+
+ const uint16_t xact_len = tu_min16((uint16_t) (p_mtp->total_len - p_mtp->xferred_len), CFG_TUD_MTP_EP_BUFSIZE);
+ if (xact_len) {
+ // already transferred all bytes in header's length. Application make an unnecessary extra call
+ TU_VERIFY(usbd_edpt_claim(p_mtp->rhport, ep_addr));
+ TU_ASSERT(usbd_edpt_xfer(p_mtp->rhport, ep_addr, _mtpd_epbuf.buf, xact_len));
+ }
+ return true;
+}
+
+bool tud_mtp_data_send(mtp_container_info_t* p_container) {
+ return mtpd_data_xfer(p_container, _mtpd_itf.ep_in);
+}
+
+bool tud_mtp_data_receive(mtp_container_info_t* p_container) {
+ return mtpd_data_xfer(p_container, _mtpd_itf.ep_out);
+}
+
+bool tud_mtp_response_send(mtp_container_info_t* p_container) {
+ mtpd_interface_t* p_mtp = &_mtpd_itf;
+ p_mtp->phase = MTP_PHASE_RESPONSE;
+ p_container->header->type = MTP_CONTAINER_TYPE_RESPONSE_BLOCK;
+ p_container->header->transaction_id = p_mtp->command.header.transaction_id;
+ TU_VERIFY(usbd_edpt_claim(p_mtp->rhport, p_mtp->ep_in));
+ return usbd_edpt_xfer(p_mtp->rhport, p_mtp->ep_in, _mtpd_epbuf.buf, (uint16_t)p_container->header->len);
+}
+
+bool tud_mtp_mounted(void) {
+ mtpd_interface_t* p_mtp = &_mtpd_itf;
+ return p_mtp->ep_out != 0 && p_mtp->ep_in != 0;
+}
+
+bool tud_mtp_event_send(mtp_event_t* event) {
+ mtpd_interface_t* p_mtp = &_mtpd_itf;
+ TU_VERIFY(p_mtp->ep_event != 0);
+ _mtpd_epbuf.buf_event = *event;
+ TU_VERIFY(usbd_edpt_claim(p_mtp->rhport, p_mtp->ep_event)); // Claim the endpoint
+ return usbd_edpt_xfer(p_mtp->rhport, p_mtp->ep_event, (uint8_t*) &_mtpd_epbuf.buf_event, sizeof(mtp_event_t));
+}
+
+//--------------------------------------------------------------------+
+// USBD Driver API
+//--------------------------------------------------------------------+
+void mtpd_init(void) {
+ tu_memclr(&_mtpd_itf, sizeof(mtpd_interface_t));
+}
+
+bool mtpd_deinit(void) {
+ return true; // nothing to do
+}
+
+void mtpd_reset(uint8_t rhport) {
+ (void) rhport;
+ tu_memclr(&_mtpd_itf, sizeof(mtpd_interface_t));
+}
+
+uint16_t mtpd_open(uint8_t rhport, tusb_desc_interface_t const* itf_desc, uint16_t max_len) {
+ // only support PIMA 15470 protocol
+ TU_VERIFY(TUSB_CLASS_IMAGE == itf_desc->bInterfaceClass &&
+ MTP_SUBCLASS_STILL_IMAGE == itf_desc->bInterfaceSubClass &&
+ MTP_PROTOCOL_PIMA_15470 == itf_desc->bInterfaceProtocol, 0);
+
+ // mtp driver length is fixed
+ const uint16_t mtpd_itf_size = sizeof(tusb_desc_interface_t) + 3 * sizeof(tusb_desc_endpoint_t);
+
+ // Max length must be at least 1 interface + 3 endpoints
+ TU_ASSERT(itf_desc->bNumEndpoints == 3 && max_len >= mtpd_itf_size);
+ mtpd_interface_t* p_mtp = &_mtpd_itf;
+ tu_memclr(p_mtp, sizeof(mtpd_interface_t));
+ p_mtp->rhport = rhport;
+ p_mtp->itf_num = itf_desc->bInterfaceNumber;
+
+ // Open interrupt IN endpoint
+ const tusb_desc_endpoint_t* ep_desc = (const tusb_desc_endpoint_t*) tu_desc_next(itf_desc);
+ TU_ASSERT(ep_desc->bDescriptorType == TUSB_DESC_ENDPOINT && ep_desc->bmAttributes.xfer == TUSB_XFER_INTERRUPT, 0);
+ TU_ASSERT(usbd_edpt_open(rhport, ep_desc), 0);
+ p_mtp->ep_event = ep_desc->bEndpointAddress;
+
+ // Open endpoint pair
+ TU_ASSERT(usbd_open_edpt_pair(rhport, tu_desc_next(ep_desc), 2, TUSB_XFER_BULK, &p_mtp->ep_out, &p_mtp->ep_in), 0);
+ TU_ASSERT(prepare_new_command(p_mtp), 0);
+
+ return mtpd_itf_size;
+}
+
+// Invoked when a control transfer occurred on an interface of this class
+// Driver response accordingly to the request and the transfer stage (setup/data/ack)
+// return false to stall control endpoint (e.g unsupported request)
+bool mtpd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const* request) {
+ mtpd_interface_t* p_mtp = &_mtpd_itf;
+ tud_mtp_request_cb_data_t cb_data = {
+ .idx = 0,
+ .stage = stage,
+ .session_id = p_mtp->session_id,
+ .request = request,
+ .buf = p_mtp->control_buf,
+ .bufsize = tu_le16toh(request->wLength),
+ };
+
+ switch (request->bRequest) {
+ case MTP_REQ_CANCEL:
+ TU_LOG_DRV(" MTP request: Cancel\n");
+ if (stage == CONTROL_STAGE_SETUP) {
+ return tud_control_xfer(rhport, request, p_mtp->control_buf, CFG_TUD_MTP_EP_CONTROL_BUFSIZE);
+ } else if (stage == CONTROL_STAGE_ACK) {
+ return tud_mtp_request_cancel_cb(&cb_data);
+ }
+ break;
+
+ case MTP_REQ_GET_EXT_EVENT_DATA:
+ TU_LOG_DRV(" MTP request: Get Extended Event Data\n");
+ if (stage == CONTROL_STAGE_SETUP) {
+ const int32_t len = tud_mtp_request_get_extended_event_cb(&cb_data);
+ TU_VERIFY(len > 0);
+ return tud_control_xfer(rhport,request, p_mtp->control_buf, (uint16_t) len);
+ }
+ break;
+
+ case MTP_REQ_RESET:
+ TU_LOG_DRV(" MTP request: Device Reset\n");
+ // used by the host to return the Still Image Capture Device to the Idle state after the Bulk-pipe has stalled
+ if (stage == CONTROL_STAGE_SETUP) {
+ // clear stalled
+ if (usbd_edpt_stalled(rhport, p_mtp->ep_out)) {
+ usbd_edpt_clear_stall(rhport, p_mtp->ep_out);
+ }
+ if (usbd_edpt_stalled(rhport, p_mtp->ep_in)) {
+ usbd_edpt_clear_stall(rhport, p_mtp->ep_in);
+ }
+ } else if (stage == CONTROL_STAGE_ACK) {
+ prepare_new_command(p_mtp);
+ return tud_mtp_request_device_reset_cb(&cb_data);
+ }
+ break;
+
+ case MTP_REQ_GET_DEVICE_STATUS: {
+ TU_LOG_DRV(" MTP request: Get Device Status\n");
+ if (stage == CONTROL_STAGE_SETUP) {
+ const int32_t len = tud_mtp_request_get_device_status_cb(&cb_data);
+ TU_VERIFY(len > 0);
+ return tud_control_xfer(rhport, request, p_mtp->control_buf, (uint16_t) len);
+ }
+ break;
+ }
+
+ default:
+ return tud_mtp_request_vendor_cb(&cb_data);
+ }
+
+ return true;
+}
+
+// Transfer on bulk endpoints
+bool mtpd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) {
+ if (ep_addr == _mtpd_itf.ep_event) {
+ // nothing to do
+ return true;
+ }
+
+ mtpd_interface_t* p_mtp = &_mtpd_itf;
+ mtp_generic_container_t* p_container = (mtp_generic_container_t*) _mtpd_epbuf.buf;
+
+#if CFG_TUSB_DEBUG >= CFG_TUD_MTP_LOG_LEVEL
+ tu_lookup_find(&_mtp_op_table, p_mtp->command.header.code);
+ TU_LOG_DRV(" MTP %s: %s phase\r\n", (const char *) tu_lookup_find(&_mtp_op_table, p_mtp->command.header.code),
+ _mtp_phase_str[p_mtp->phase]);
+#endif
+
+ const mtp_container_info_t headered_packet = {
+ .header = &p_container->header,
+ .payload = p_container->payload,
+ .payload_bytes = CFG_TUD_MTP_EP_BUFSIZE - sizeof(mtp_container_header_t)
+ };
+
+ const mtp_container_info_t headerless_packet = {
+ .header = &p_mtp->io_header,
+ .payload = _mtpd_epbuf.buf,
+ .payload_bytes = CFG_TUD_MTP_EP_BUFSIZE
+ };
+
+ tud_mtp_cb_data_t cb_data;
+ cb_data.idx = 0;
+ cb_data.phase = p_mtp->phase;
+ cb_data.session_id = p_mtp->session_id;
+ cb_data.command_container = &p_mtp->command;
+ cb_data.io_container = headered_packet;
+ cb_data.total_xferred_bytes = 0;
+ cb_data.xfer_result = event;
+
+ switch (p_mtp->phase) {
+ case MTP_PHASE_COMMAND: {
+ // received new command
+ TU_VERIFY(ep_addr == p_mtp->ep_out && p_container->header.type == MTP_CONTAINER_TYPE_COMMAND_BLOCK);
+ memcpy(&p_mtp->command, p_container, sizeof(mtp_container_command_t)); // save new command
+ p_container->header.len = sizeof(mtp_container_header_t); // default container to header only
+ preprocess_cmd(p_mtp, &cb_data);
+ if (tud_mtp_command_received_cb(&cb_data) < 0) {
+ p_mtp->phase = MTP_PHASE_ERROR;
+ }
+ break;
+ }
+
+ case MTP_PHASE_DATA: {
+ const uint16_t bulk_mps = (tud_speed_get() == TUSB_SPEED_HIGH) ? 512 : 64;
+ p_mtp->xferred_len += xferred_bytes;
+ cb_data.total_xferred_bytes = p_mtp->xferred_len;
+
+ bool is_complete = false;
+ // complete if ZLP or short packet or overflow
+ if (xferred_bytes == 0 || // ZLP
+ (xferred_bytes & (bulk_mps - 1)) || // short packet
+ p_mtp->xferred_len > p_mtp->total_len) {
+ is_complete = true;
+ }
+
+ if (ep_addr == p_mtp->ep_in) {
+ // Data In
+ if (is_complete) {
+ cb_data.io_container.header->len = sizeof(mtp_container_header_t);
+ tud_mtp_data_complete_cb(&cb_data);
+ } else {
+ // 2nd+ packet: payload only
+ cb_data.io_container = headerless_packet;
+ tud_mtp_data_xfer_cb(&cb_data);
+ }
+ } else {
+ // Data Out
+ if (p_mtp->xferred_len == xferred_bytes) {
+ // 1st OUT packet: header + payload
+ p_mtp->io_header = p_container->header; // save header for subsequent transaction
+ cb_data.io_container.payload_bytes = xferred_bytes - sizeof(mtp_container_header_t);
+ } else {
+ // 2nd+ packet: payload only
+ cb_data.io_container = headerless_packet;
+ cb_data.io_container.payload_bytes = xferred_bytes;
+ }
+ tud_mtp_data_xfer_cb(&cb_data);
+
+ if (is_complete) {
+ // back to header + payload for response
+ cb_data.io_container = headered_packet;
+ cb_data.io_container.header->len = sizeof(mtp_container_header_t);
+ tud_mtp_data_complete_cb(&cb_data);
+ }
+ }
+ break;
+ }
+
+ case MTP_PHASE_RESPONSE:
+ // response phase is complete -> prepare for new command
+ TU_ASSERT(ep_addr == p_mtp->ep_in);
+ tud_mtp_response_complete_cb(&cb_data);
+ prepare_new_command(p_mtp);
+ break;
+
+ case MTP_PHASE_ERROR:
+ // handled after switch, supposedly to be empty
+ break;
+ default: return false;
+ }
+
+ if (p_mtp->phase == MTP_PHASE_ERROR) {
+ // stall both IN & OUT endpoints
+ usbd_edpt_stall(rhport, p_mtp->ep_out);
+ usbd_edpt_stall(rhport, p_mtp->ep_in);
+ }
+
+ return true;
+}
+
+
+//--------------------------------------------------------------------+
+// MTPD Internal functionality
+//--------------------------------------------------------------------+
+
+// pre-processed commands
+void preprocess_cmd(mtpd_interface_t* p_mtp, tud_mtp_cb_data_t* cb_data) {
+ switch (p_mtp->command.header.code) {
+ case MTP_OP_GET_DEVICE_INFO: {
+ tud_mtp_device_info_t dev_info = {
+ .standard_version = 100,
+ .mtp_vendor_extension_id = 6, // MTP specs say 0xFFFFFFFF but libMTP check for value 6
+ .mtp_version = 100,
+ .mtp_extensions = {
+ .count = sizeof(CFG_TUD_MTP_DEVICEINFO_EXTENSIONS),
+ .utf16 = { 0 }
+ },
+ .functional_mode = 0x0000,
+ .supported_operations = {
+ .count = TU_ARGS_NUM(CFG_TUD_MTP_DEVICEINFO_SUPPORTED_OPERATIONS),
+ .arr = { CFG_TUD_MTP_DEVICEINFO_SUPPORTED_OPERATIONS }
+ },
+ .supported_events = {
+ .count = TU_ARGS_NUM(CFG_TUD_MTP_DEVICEINFO_SUPPORTED_EVENTS),
+ .arr = { CFG_TUD_MTP_DEVICEINFO_SUPPORTED_EVENTS }
+ },
+ .supported_device_properties = {
+ .count = TU_ARGS_NUM(CFG_TUD_MTP_DEVICEINFO_SUPPORTED_DEVICE_PROPERTIES),
+ .arr = { CFG_TUD_MTP_DEVICEINFO_SUPPORTED_DEVICE_PROPERTIES }
+ },
+ .capture_formats = {
+ .count = TU_ARGS_NUM(CFG_TUD_MTP_DEVICEINFO_CAPTURE_FORMATS),
+ .arr = { CFG_TUD_MTP_DEVICEINFO_CAPTURE_FORMATS }
+ },
+ .playback_formats = {
+ .count = TU_ARGS_NUM(CFG_TUD_MTP_DEVICEINFO_PLAYBACK_FORMATS),
+ .arr = { CFG_TUD_MTP_DEVICEINFO_PLAYBACK_FORMATS }
+ }
+ };
+
+ for (uint8_t i=0; i < dev_info.mtp_extensions.count; i++) {
+ dev_info.mtp_extensions.utf16[i] = (uint16_t)CFG_TUD_MTP_DEVICEINFO_EXTENSIONS[i];
+ }
+
+ mtp_container_add_raw(&cb_data->io_container, &dev_info, sizeof(tud_mtp_device_info_t));
+ break;
+ }
+
+ default:
+ break;
+ }
+}
+
+#endif
diff --git a/src/class/mtp/mtp_device.h b/src/class/mtp/mtp_device.h
new file mode 100644
index 000000000..397fbbbce
--- /dev/null
+++ b/src/class/mtp/mtp_device.h
@@ -0,0 +1,167 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2025 Ennebi Elettronica (https://ennebielettronica.com)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN0
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+
+#ifndef TUSB_MTP_DEVICE_H_
+#define TUSB_MTP_DEVICE_H_
+
+#include "common/tusb_common.h"
+#include "mtp.h"
+
+#if (CFG_TUD_ENABLED && CFG_TUD_MTP)
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+// callback data for Bulk Only Transfer (BOT) protocol
+typedef struct {
+ uint8_t idx; // mtp instance
+ uint8_t phase; // current phase
+ uint32_t session_id;
+
+ const mtp_container_command_t* command_container;
+ mtp_container_info_t io_container;
+
+ tusb_xfer_result_t xfer_result;
+ uint32_t total_xferred_bytes; // number of bytes transferred so far in this phase
+} tud_mtp_cb_data_t;
+
+// callback data for Control requests
+typedef struct {
+ uint8_t idx;
+ uint8_t stage; // control stage
+ uint32_t session_id;
+
+ const tusb_control_request_t* request;
+ // buffer for data stage
+ uint8_t* buf;
+ uint16_t bufsize;
+} tud_mtp_request_cb_data_t;
+
+// Number of supported operations, events, device properties, capture formats, playback formats
+// and max number of characters for strings manufacturer, model, device_version, serial_number
+#define MTP_DEVICE_INFO_STRUCT(_extension_nchars, _op_count, _event_count, _devprop_count, _capture_count, _playback_count) \
+ struct TU_ATTR_PACKED { \
+ uint16_t standard_version; \
+ uint32_t mtp_vendor_extension_id; \
+ uint16_t mtp_version; \
+ mtp_string_t(_extension_nchars) mtp_extensions; \
+ uint16_t functional_mode; \
+ mtp_auint16_t(_op_count) supported_operations; \
+ mtp_auint16_t(_event_count) supported_events; \
+ mtp_auint16_t(_devprop_count) supported_device_properties; \
+ mtp_auint16_t(_capture_count) capture_formats; \
+ mtp_auint16_t(_playback_count) playback_formats; \
+ /* string fields will be added using append function */ \
+ }
+
+typedef MTP_DEVICE_INFO_STRUCT(
+ sizeof(CFG_TUD_MTP_DEVICEINFO_EXTENSIONS), TU_ARGS_NUM(CFG_TUD_MTP_DEVICEINFO_SUPPORTED_OPERATIONS),
+ TU_ARGS_NUM(CFG_TUD_MTP_DEVICEINFO_SUPPORTED_EVENTS), TU_ARGS_NUM(CFG_TUD_MTP_DEVICEINFO_SUPPORTED_DEVICE_PROPERTIES),
+ TU_ARGS_NUM(CFG_TUD_MTP_DEVICEINFO_CAPTURE_FORMATS), TU_ARGS_NUM(CFG_TUD_MTP_DEVICEINFO_PLAYBACK_FORMATS)
+) tud_mtp_device_info_t;
+
+//--------------------------------------------------------------------+
+// Application API
+//--------------------------------------------------------------------+
+
+// check if mtp interface is mounted
+bool tud_mtp_mounted(void);
+
+// send data phase
+bool tud_mtp_data_send(mtp_container_info_t* p_container);
+
+// receive data phase
+bool tud_mtp_data_receive(mtp_container_info_t* p_container);
+
+// send response
+bool tud_mtp_response_send(mtp_container_info_t* p_container);
+
+// send event notification on event endpoint
+bool tud_mtp_event_send(mtp_event_t* event);
+
+//--------------------------------------------------------------------+
+// Control request Callbacks
+//--------------------------------------------------------------------+
+
+// Invoked when received Cancel request. Data is available in callback data's buffer
+// return false to stall the request
+bool tud_mtp_request_cancel_cb(tud_mtp_request_cb_data_t* cb_data);
+
+// Invoked when received Device Reset request
+// return false to stall the request
+bool tud_mtp_request_device_reset_cb(tud_mtp_request_cb_data_t* cb_data);
+
+// Invoked when received Get Extended Event request. Application fill callback data's buffer for response
+// return negative to stall the request
+int32_t tud_mtp_request_get_extended_event_cb(tud_mtp_request_cb_data_t* cb_data);
+
+// Invoked when received Get DeviceStatus request. Application fill callback data's buffer for response
+// return negative to stall the request
+int32_t tud_mtp_request_get_device_status_cb(tud_mtp_request_cb_data_t* cb_data);
+
+// Invoked when received vendor-specific request not in the above standard MTP requests
+// return false to stall the request
+bool tud_mtp_request_vendor_cb(tud_mtp_request_cb_data_t* cb_data);
+
+//--------------------------------------------------------------------+
+// Bulk only protocol Callbacks
+//--------------------------------------------------------------------+
+
+// Invoked when new command is received. Application fill the cb_data->io_container and call tud_mtp_data_send() or
+// tud_mtp_response_send() for Data or Response phase.
+// Return negative to stall the endpoints
+int32_t tud_mtp_command_received_cb(tud_mtp_cb_data_t * cb_data);
+
+// Invoked when a data packet is transferred. If data spans over multiple packets, application can use
+// total_xferred_bytes and io_container's payload_bytes to determine the offset and remaining bytes to be transferred.
+// Return negative to stall the endpoints
+int32_t tud_mtp_data_xfer_cb(tud_mtp_cb_data_t* cb_data);
+
+// Invoked when all bytes in DATA phase is complete. A response packet is expected
+// Return negative to stall the endpoints
+int32_t tud_mtp_data_complete_cb(tud_mtp_cb_data_t* cb_data);
+
+// Invoked when response phase is complete
+// Return negative to stall the endpoints
+int32_t tud_mtp_response_complete_cb(tud_mtp_cb_data_t* cb_data);
+
+//--------------------------------------------------------------------+
+// Internal Class Driver API
+//--------------------------------------------------------------------+
+void mtpd_init (void);
+bool mtpd_deinit (void);
+void mtpd_reset (uint8_t rhport);
+uint16_t mtpd_open (uint8_t rhport, tusb_desc_interface_t const *itf_desc, uint16_t max_len);
+bool mtpd_control_xfer_cb (uint8_t rhport, uint8_t stage, tusb_control_request_t const *p_request);
+bool mtpd_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif
+#endif
diff --git a/src/common/tusb_common.h b/src/common/tusb_common.h
index 9c4699362..12dea2183 100644
--- a/src/common/tusb_common.h
+++ b/src/common/tusb_common.h
@@ -35,6 +35,7 @@
// Macros Helper
//--------------------------------------------------------------------+
#define TU_ARRAY_SIZE(_arr) ( sizeof(_arr) / sizeof(_arr[0]) )
+#define TU_FIELD_SZIE(_type, _field) (sizeof(((_type *)0)->_field))
#define TU_MIN(_x, _y) ( ( (_x) < (_y) ) ? (_x) : (_y) )
#define TU_MAX(_x, _y) ( ( (_x) > (_y) ) ? (_x) : (_y) )
#define TU_DIV_CEIL(n, d) (((n) + (d) - 1) / (d))
diff --git a/src/device/usbd.c b/src/device/usbd.c
index b1aef0b38..339ccf4b4 100644
--- a/src/device/usbd.c
+++ b/src/device/usbd.c
@@ -321,6 +321,20 @@ tu_static usbd_class_driver_t const _usbd_driver[] = {
.sof = NULL
},
#endif
+
+ #if CFG_TUD_MTP
+ {
+ .name = DRIVER_NAME("MTP"),
+ .init = mtpd_init,
+ .deinit = mtpd_deinit,
+ .reset = mtpd_reset,
+ .open = mtpd_open,
+ .control_xfer_cb = mtpd_control_xfer_cb,
+ .xfer_cb = mtpd_xfer_cb,
+ .xfer_isr = NULL,
+ .sof = NULL
+ },
+ #endif
};
enum { BUILTIN_DRIVER_COUNT = TU_ARRAY_SIZE(_usbd_driver) };
diff --git a/src/device/usbd.h b/src/device/usbd.h
index e5a848809..a4104e47d 100644
--- a/src/device/usbd.h
+++ b/src/device/usbd.h
@@ -270,6 +270,25 @@ bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_requ
//--------------------------------------------------------------------+
+// MTP Descriptor Templates
+//--------------------------------------------------------------------+
+
+// Length of template descriptor: 30 bytes
+#define TUD_MTP_DESC_LEN (9 + 7 + 7 + 7)
+
+// Interface number, string index, EP event, EP event size, EP event polling, EP Out & EP In address, EP size
+#define TUD_MTP_DESCRIPTOR(_itfnum, _stridx, _ep_evt, _ep_evt_size, _ep_evt_polling_interval, _epout, _epin, _epsize) \
+ /* Interface */\
+ 9, TUSB_DESC_INTERFACE, _itfnum, 0, 3, TUSB_CLASS_IMAGE, MTP_SUBCLASS_STILL_IMAGE, MTP_PROTOCOL_PIMA_15470, _stridx,\
+ /* Endpoint Interrupt */\
+ 7, TUSB_DESC_ENDPOINT, _ep_evt, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_evt_size), _ep_evt_polling_interval,\
+ /* Endpoint Out */\
+ 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\
+ /* Endpoint In */\
+ 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0
+
+
+//--------------------------------------------------------------------+
// HID Descriptor Templates
//--------------------------------------------------------------------+
diff --git a/src/tinyusb.mk b/src/tinyusb.mk
index a9f623c24..8f9d52de9 100644
--- a/src/tinyusb.mk
+++ b/src/tinyusb.mk
@@ -12,6 +12,7 @@ TINYUSB_SRC_C += \
src/class/hid/hid_device.c \
src/class/midi/midi_device.c \
src/class/msc/msc_device.c \
+ src/class/mtp/mtp_device.c \
src/class/net/ecm_rndis_device.c \
src/class/net/ncm_device.c \
src/class/usbtmc/usbtmc_device.c \
diff --git a/src/tusb.h b/src/tusb.h
index 92da845c0..6a469eef4 100644
--- a/src/tusb.h
+++ b/src/tusb.h
@@ -88,6 +88,10 @@
#include "class/msc/msc_device.h"
#endif
+ #if CFG_TUD_MTP
+ #include "class/mtp/mtp_device.h"
+ #endif
+
#if CFG_TUD_AUDIO
#include "class/audio/audio_device.h"
#endif
diff --git a/src/tusb_option.h b/src/tusb_option.h
index fe7e34111..80060914b 100644
--- a/src/tusb_option.h
+++ b/src/tusb_option.h
@@ -517,6 +517,10 @@
#define CFG_TUD_MSC 0
#endif
+#ifndef CFG_TUD_MTP
+ #define CFG_TUD_MTP 0
+#endif
+
#ifndef CFG_TUD_HID
#define CFG_TUD_HID 0
#endif
diff --git a/test/fuzz/device/cdc/src/usb_descriptors.cc b/test/fuzz/device/cdc/src/usb_descriptors.cc
index 0f636f05d..c26bd18c3 100644
--- a/test/fuzz/device/cdc/src/usb_descriptors.cc
+++ b/test/fuzz/device/cdc/src/usb_descriptors.cc
@@ -148,7 +148,7 @@ uint8_t const *tud_descriptor_other_speed_configuration_cb(uint8_t index) {
(void)index; // for multiple configurations
// if link speed is high return fullspeed config, and vice versa
- // Note: the descriptor type is OHER_SPEED_CONFIG instead of CONFIG
+ // Note: the descriptor type is OTHER_SPEED_CONFIG instead of CONFIG
memcpy(desc_other_speed_config,
(tud_speed_get() == TUSB_SPEED_HIGH) ? desc_fs_configuration
: desc_hs_configuration,
diff --git a/test/fuzz/device/msc/src/usb_descriptors.cc b/test/fuzz/device/msc/src/usb_descriptors.cc
index efe4d0a3c..6d9c4cd96 100644
--- a/test/fuzz/device/msc/src/usb_descriptors.cc
+++ b/test/fuzz/device/msc/src/usb_descriptors.cc
@@ -142,7 +142,7 @@ uint8_t const *tud_descriptor_other_speed_configuration_cb(uint8_t index) {
(void)index; // for multiple configurations
// if link speed is high return fullspeed config, and vice versa
- // Note: the descriptor type is OHER_SPEED_CONFIG instead of CONFIG
+ // Note: the descriptor type is OTHER_SPEED_CONFIG instead of CONFIG
memcpy(desc_other_speed_config,
(tud_speed_get() == TUSB_SPEED_HIGH) ? desc_fs_configuration
: desc_hs_configuration,
diff --git a/test/fuzz/device/net/src/usb_descriptors.cc b/test/fuzz/device/net/src/usb_descriptors.cc
index 5597d49d5..e57a791b6 100644
--- a/test/fuzz/device/net/src/usb_descriptors.cc
+++ b/test/fuzz/device/net/src/usb_descriptors.cc
@@ -148,7 +148,7 @@ uint8_t const *tud_descriptor_other_speed_configuration_cb(uint8_t index) {
(void)index; // for multiple configurations
// if link speed is high return fullspeed config, and vice versa
- // Note: the descriptor type is OHER_SPEED_CONFIG instead of CONFIG
+ // Note: the descriptor type is OTHER_SPEED_CONFIG instead of CONFIG
memcpy(desc_other_speed_config,
(tud_speed_get() == TUSB_SPEED_HIGH) ? desc_fs_configuration
: desc_hs_configuration,
diff --git a/test/fuzz/rules.mk b/test/fuzz/rules.mk
index 562969663..b32f8d695 100644
--- a/test/fuzz/rules.mk
+++ b/test/fuzz/rules.mk
@@ -31,6 +31,7 @@ SRC_C += \
src/class/hid/hid_device.c \
src/class/midi/midi_device.c \
src/class/msc/msc_device.c \
+ src/class/mtp/mtp_device.c \
src/class/net/ecm_rndis_device.c \
src/class/net/ncm_device.c \
src/class/usbtmc/usbtmc_device.c \
diff --git a/test/hil/hil_test.py b/test/hil/hil_test.py
index 93cc0a750..fc8255f1b 100755
--- a/test/hil/hil_test.py
+++ b/test/hil/hil_test.py
@@ -28,6 +28,7 @@
import argparse
import os
+import random
import re
import sys
import time
@@ -37,6 +38,9 @@ import json
import glob
from multiprocessing import Pool
import fs
+import hashlib
+import ctypes
+from pymtp import MTP
ENUM_TIMEOUT = 30
@@ -45,6 +49,7 @@ STATUS_FAILED = "\033[31mFailed\033[0m"
STATUS_SKIPPED = "\033[33mSkipped\033[0m"
verbose = False
+test_only = []
WCH_RISCV_CONTENT = """
adapter driver wlinke
@@ -134,6 +139,23 @@ def read_disk_file(uid, lun, fname):
return None
+def open_mtp_dev(uid):
+ mtp = MTP()
+ timeout = ENUM_TIMEOUT
+ while timeout > 0:
+ # run_cmd(f"gio mount -u mtp://TinyUsb_TinyUsb_Device_{uid}/")
+ for raw in mtp.detect_devices():
+ mtp.device = mtp.mtp.LIBMTP_Open_Raw_Device(ctypes.byref(raw))
+ if mtp.device:
+ sn = mtp.get_serialnumber().decode('utf-8')
+ #print(f'mtp serial = {sn}')
+ if sn == uid:
+ return mtp
+ time.sleep(1)
+ timeout -= 1
+ return None
+
+
# -------------------------------------------------------------
# Flashing firmware
# -------------------------------------------------------------
@@ -456,7 +478,6 @@ def test_device_dfu(board):
def test_device_dfu_runtime(board):
uid = board['uid']
-
# Wait device enum
timeout = ENUM_TIMEOUT
while timeout > 0:
@@ -491,6 +512,65 @@ def test_device_hid_composite_freertos(id):
pass
+def test_device_mtp(board):
+ uid = board['uid']
+
+ # --- BEFORE: mute C-level stderr for libmtp vid/pid warnings ---
+ fd = sys.stderr.fileno()
+ _saved = os.dup(fd)
+ _null = os.open(os.devnull, os.O_WRONLY)
+ os.dup2(_null, fd)
+
+ mtp = open_mtp_dev(uid)
+
+ # --- AFTER: restore stderr ---
+ os.dup2(_saved, fd)
+ os.close(_null)
+ os.close(_saved)
+
+ if mtp is None or mtp.device is None:
+ assert False, 'MTP device not found'
+
+ try:
+ assert b"TinyUSB" == mtp.get_manufacturer(), 'MTP wrong manufacturer'
+ assert b"MTP Example" == mtp.get_modelname(), 'MTP wrong model'
+ assert b'1.0' == mtp.get_deviceversion(), 'MTP wrong version'
+ assert b'TinyUSB MTP' == mtp.get_devicename(), 'MTP wrong device name'
+
+ # read and compare readme.txt and logo.png
+ f1_expect = b'TinyUSB MTP Filesystem example'
+ f2_md5_expect = '40ef23fc2891018d41a05d4a0d5f822f' # md5sum of logo.png
+ f1 = uid.encode("utf-8") + b'_file1'
+ f2 = uid.encode("utf-8") + b'_file2'
+ f3 = uid.encode("utf-8") + b'_file3'
+ mtp.get_file_to_file(1, f1)
+ with open(f1, 'rb') as file:
+ f1_data = file.read()
+ os.remove(f1)
+ assert f1_data == f1_expect, 'MTP file1 wrong data'
+ mtp.get_file_to_file(2, f2)
+ with open(f2, 'rb') as file:
+ f2_data = file.read()
+ os.remove(f2)
+ assert f2_md5_expect == hashlib.md5(f2_data).hexdigest(), 'MTP file2 wrong data'
+ # test send file
+ with open(f3, "wb") as file:
+ f3_data = os.urandom(random.randint(1024, 3*1024))
+ file.write(f3_data)
+ file.close()
+ fid = mtp.send_file_from_file(f3, b'file3')
+ f3_readback = f3 + b'_readback'
+ mtp.get_file_to_file(fid, f3_readback)
+ with open(f3_readback, 'rb') as f:
+ f3_rb_data = f.read()
+ os.remove(f3_readback)
+ assert f3_rb_data == f3_data, 'MTP file3 wrong data'
+ os.remove(f3)
+ mtp.delete_object(fid)
+ finally:
+ mtp.disconnect()
+
+
# -------------------------------------------------------------
# Main
# -------------------------------------------------------------
@@ -503,6 +583,7 @@ device_tests = [
'device/dfu_runtime',
'device/cdc_msc_freertos',
'device/hid_boot_interface',
+ 'device/mtp'
]
dual_tests = [
@@ -579,21 +660,24 @@ def test_board(board):
# default to all tests
test_list = []
- if 'tests' in board:
- board_tests = board['tests']
- if 'device' in board_tests and board_tests['device'] == True:
- test_list += list(device_tests)
- if 'dual' in board_tests and board_tests['dual'] == True:
- test_list += dual_tests
- if 'host' in board_tests and board_tests['host'] == True:
- test_list += host_test
- if 'only' in board_tests:
- test_list = board_tests['only']
- if 'skip' in board_tests:
- for skip in board_tests['skip']:
- if skip in test_list:
- test_list.remove(skip)
- print(f'{name:25} {skip:30} ... Skip')
+ if len(test_only) > 0:
+ test_list = test_only
+ else:
+ if 'tests' in board:
+ board_tests = board['tests']
+ if 'device' in board_tests and board_tests['device'] == True:
+ test_list += list(device_tests)
+ if 'dual' in board_tests and board_tests['dual'] == True:
+ test_list += dual_tests
+ if 'host' in board_tests and board_tests['host'] == True:
+ test_list += host_test
+ if 'only' in board_tests:
+ test_list = board_tests['only']
+ if 'skip' in board_tests:
+ for skip in board_tests['skip']:
+ if skip in test_list:
+ test_list.remove(skip)
+ print(f'{name:25} {skip:30} ... Skip')
err_count = 0
flags_on_list = [""]
@@ -615,6 +699,7 @@ def main():
Hardware test on specified boards
"""
global verbose
+ global test_only
duration = time.time()
@@ -622,6 +707,7 @@ def main():
parser.add_argument('config_file', help='Configuration JSON file')
parser.add_argument('-b', '--board', action='append', default=[], help='Boards to test, all if not specified')
parser.add_argument('-s', '--skip', action='append', default=[], help='Skip boards from test')
+ parser.add_argument('-t', '--test-only', action='append', default=[], help='Tests to run, all if not specified')
parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
args = parser.parse_args()
@@ -629,6 +715,7 @@ def main():
boards = args.board
skip_boards = args.skip
verbose = args.verbose
+ test_only = args.test_only
# if config file is not found, try to find it in the same directory as this script
if not os.path.exists(config_file):
diff --git a/test/hil/pymtp.py b/test/hil/pymtp.py
new file mode 100644
index 000000000..8b694df94
--- /dev/null
+++ b/test/hil/pymtp.py
@@ -0,0 +1,1290 @@
+#!/usr/bin/env python
+#
+# A Ctypes wrapper to LibMTP
+# Developed by: Nick Devito ([email protected])
+# (c) 2008 Nick Devito
+# Released under the GPLv3 or later.
+#
+
+"""
+ PyMTP is a pythonic wrapper around libmtp, making it a bit more
+ friendly to use in python
+
+ Example Usage (or see examples/):
+ >>> import pymtp
+ >>> mtp = pymtp.MTP()
+ >>> mtp.connect()
+ PTP: Opening session
+ >>> print mtp.get_devicename()
+ Device name
+ >>> mtp.disconnect()
+ PTP: Closing session
+ >>>
+"""
+
+__VERSION__ = "0.0.5"
+__VERSION_MACRO__ = 5
+__VERSION_MINOR__ = 0
+__VERSION_MAJOR__ = 0
+__VERSION_TUPLE__ = (__VERSION_MAJOR__, __VERSION_MINOR__, __VERSION_MACRO__)
+__AUTHOR__ = "Nick Devito ([email protected])"
+__LICENSE__ = "GPL-3"
+__DEBUG__ = 1
+
+import os
+import ctypes
+import ctypes.util
+
+# NOTE: This code *may* work on windows, I don't have a win32 system to test
+# this on.
+_module_path = ctypes.util.find_library("mtp")
+_libmtp = ctypes.CDLL(_module_path)
+
+# ----------
+# Error Definitions
+# ----------
+class NoDeviceConnected(Exception):
+ """
+ Raised when there isn't a device connected to the USB bus
+ """
+
+ pass
+
+class AlreadyConnected(Exception):
+ """
+ Raised when we're already connected to a device and there is
+ an attempt to connect
+ """
+
+ pass
+
+class UnsupportedCommand(Exception):
+ """
+ Raised when the connected device does not support the command
+ issued
+ """
+
+ pass
+
+class CommandFailed(Exception):
+ """
+ Raised when the connected device returned an error when trying
+ to execute a command
+ """
+
+ pass
+
+class NotConnected(Exception):
+ """
+ Raised when a command is called and the device is not connected
+ """
+
+ pass
+
+class ObjectNotFound(Exception):
+ """
+ Raised when a command tries to get an object that doesn't exist
+ """
+
+ pass
+
+# ----------
+# End Error Definitions
+# ----------
+
+# ----------
+# Data Model Definitions
+# ----------
+
+class LIBMTP_Error(ctypes.Structure):
+ """
+ LIBMTP_Error
+ Contains the ctypes structure for LIBMTP_error_t
+ """
+
+ def __repr__(self):
+ return self.errornumber
+
+LIBMTP_Error._fields_ = [("errornumber", ctypes.c_int),
+ ("error_text", ctypes.c_char_p),
+ ("next", ctypes.POINTER(LIBMTP_Error))]
+
+class LIBMTP_DeviceStorage(ctypes.Structure):
+ """
+ LIBMTP_DeviceStorage
+ Contains the ctypes structure for LIBMTP_devicestorage_t
+ """
+
+ def __repr__(self):
+ return self.id
+
+LIBMTP_DeviceStorage._fields_ = [("id", ctypes.c_uint32),
+ ("StorageType", ctypes.c_uint16),
+ ("FilesystemType", ctypes.c_uint16),
+ ("AccessCapability", ctypes.c_uint16),
+ ("MaxCapacity", ctypes.c_uint64),
+ ("FreeSpaceInBytes", ctypes.c_uint64),
+ ("FreeSpaceInObjects", ctypes.c_uint64),
+ ("StorageDescription", ctypes.c_char_p),
+ ("VolumeIdentifier", ctypes.c_char_p),
+ ("next", ctypes.POINTER(LIBMTP_DeviceStorage)),
+ ("prev", ctypes.POINTER(LIBMTP_DeviceStorage))]
+
+class LIBMTP_DeviceEntry(ctypes.Structure):
+ """
+ LIBMTP_DeviceEntry
+ Contains the ctypes structure for LIBMTP_device_entry_t
+ """
+
+ def __repr__(self):
+ return self.vendor
+
+LIBMTP_DeviceEntry._fields_ = [("vendor", ctypes.c_char_p),
+ ("vendor_id", ctypes.c_uint16),
+ ("product", ctypes.c_char_p),
+ ("product_id", ctypes.c_uint16),
+ ("device_flags", ctypes.c_uint32)]
+
+class LIBMTP_RawDevice(ctypes.Structure):
+ """
+ LIBMTP_RawDevice
+ Contains the ctypes structure for LIBMTP_raw_device_t
+ """
+
+ def __repr__(self):
+ return self.device_entry
+
+LIBMTP_RawDevice._fields_ = [("device_entry", LIBMTP_DeviceEntry),
+ ("bus_location", ctypes.c_uint32),
+ ("devnum", ctypes.c_uint8)]
+
+class LIBMTP_MTPDevice(ctypes.Structure):
+ """
+ LIBMTP_MTPDevice
+ Contains the ctypes structure for LIBMTP_mtpdevice_t
+ """
+
+ def __repr__(self):
+ return self.interface_number
+
+LIBMTP_MTPDevice._fields_ = [("interface_number", ctypes.c_uint8),
+ ("params", ctypes.c_void_p),
+ ("usbinfo", ctypes.c_void_p),
+ ("storage", ctypes.POINTER(LIBMTP_DeviceStorage)),
+ ("errorstack", ctypes.POINTER(LIBMTP_Error)),
+ ("maximum_battery_level", ctypes.c_uint8),
+ ("default_music_folder", ctypes.c_uint32),
+ ("default_playlist_folder", ctypes.c_uint32),
+ ("default_picture_folder", ctypes.c_uint32),
+ ("default_video_folder", ctypes.c_uint32),
+ ("default_organizer_folder", ctypes.c_uint32),
+ ("default_zencast_folder", ctypes.c_uint32),
+ ("default_album_folder", ctypes.c_uint32),
+ ("default_text_folder", ctypes.c_uint32),
+ ("cd", ctypes.c_void_p),
+ ("next", ctypes.POINTER(LIBMTP_MTPDevice))]
+
+class LIBMTP_File(ctypes.Structure):
+ """
+ LIBMTP_File
+ Contains the ctypes structure for LIBMTP_file_t
+ """
+
+ def __repr__(self):
+ return "%s (%s)" % (self.filename, self.item_id)
+
+LIBMTP_File._fields_ = [("item_id", ctypes.c_uint32),
+ ("parent_id", ctypes.c_uint32),
+ ("storage_id", ctypes.c_uint32),
+ ("filename", ctypes.c_char_p),
+ ("filesize", ctypes.c_uint64),
+ ("modificationdate", ctypes.c_uint64),
+ ("filetype", ctypes.c_int), # LIBMTP_filetype_t enum
+ ("next", ctypes.POINTER(LIBMTP_File))]
+
+class LIBMTP_Track(ctypes.Structure):
+ """
+ LIBMTP_Track
+ Contains the ctypes structure for LIBMTP_track_t
+ """
+
+ def __repr__(self):
+ return "%s - %s (%s)" % (self.artist, self.title, self.item_id)
+
+LIBMTP_Track._fields_ = [("item_id", ctypes.c_uint32),
+ ("parent_id", ctypes.c_uint32),
+ ("storage_id", ctypes.c_uint32),
+ ("title", ctypes.c_char_p),
+ ("artist", ctypes.c_char_p),
+ ("composer", ctypes.c_char_p),
+ ("genre", ctypes.c_char_p),
+ ("album", ctypes.c_char_p),
+ ("date", ctypes.c_char_p),
+ ("filename", ctypes.c_char_p),
+ ("tracknumber", ctypes.c_uint16),
+ ("duration", ctypes.c_uint32),
+ ("samplerate", ctypes.c_uint32),
+ ("nochannels", ctypes.c_uint16),
+ ("wavecodec", ctypes.c_uint32),
+ ("bitrate", ctypes.c_uint32),
+ ("bitratetype", ctypes.c_uint16),
+ ("rating", ctypes.c_uint16),
+ ("usecount", ctypes.c_uint32),
+ ("filesize", ctypes.c_uint64),
+ ("modificationdate", ctypes.c_uint64),
+ ("filetype", ctypes.c_int), # LIBMTP_filetype_t enum
+ ("next", ctypes.POINTER(LIBMTP_Track))]
+
+class LIBMTP_Playlist(ctypes.Structure):
+ """
+ LIBMTP_Playlist
+ Contains the ctypes structure for LIBMTP_playlist_t
+ """
+
+ def __init__(self):
+ self.tracks = ctypes.pointer(ctypes.c_uint32(0))
+ self.no_tracks = ctypes.c_uint32(0)
+ def __repr__(self):
+ return "%s (%s)" % (self.name, self.playlist_id)
+
+ def __iter__(self):
+ """
+ This allows the playlist object to act like a list with
+ a generator.
+ """
+ for track in xrange(self.no_tracks):
+ yield self.tracks[track]
+
+ def __getitem__(self, key):
+ """
+ This allows the playlist to return tracks like a list
+ """
+
+ if (key > (self.no_tracks - 1)):
+ raise IndexError
+
+ return self.tracks[key]
+
+ def __setitem__(self, key, value):
+ """
+ This allows the user to manipulate the playlist like a
+ list. However, this will only modify existing objects,
+ you can't try to set a key outside of the current size.
+ """
+
+ if (key > (self.no_tracks - 1)):
+ raise IndexError
+
+ self.tracks[key] = value
+
+ def __delitem__(self, key):
+ """
+ This allows the user to delete an object
+ from the playlist
+ """
+
+ if (key > (self.no_tracks - 1)):
+ raise IndexError
+
+ for i in range(key, (self.no_tracks - 1)):
+ self.tracks[i] = self.tracks[i + 1]
+
+ self.no_tracks -= 1
+
+ def append(self, value):
+ """
+ This function appends a track to the end of the tracks
+ list.
+ """
+ if (self.tracks == None):
+ self.tracks = ctypes.pointer(ctypes.c_uint32(0))
+
+ self.no_tracks += 1
+ self.tracks[(self.no_tracks - 1)] = value
+
+ def __len__(self):
+ """
+ This returns the number of tracks in the playlist
+ """
+
+ return self.no_tracks
+
+LIBMTP_Playlist._fields_ = [("playlist_id", ctypes.c_uint32),
+ ("parent_id", ctypes.c_uint32),
+ ("storage_id", ctypes.c_uint32),
+ ("name", ctypes.c_char_p),
+ ("tracks", ctypes.POINTER(ctypes.c_uint32)),
+ ("no_tracks", ctypes.c_uint32),
+ ("next", ctypes.POINTER(LIBMTP_Playlist))]
+
+class LIBMTP_Folder(ctypes.Structure):
+ """
+ LIBMTP_Folder
+ Contains the ctypes structure for LIBMTP_folder_t
+ """
+
+ def __repr__(self):
+ return "%s (%s)" % (self.name, self.folder_id)
+
+LIBMTP_Folder._fields_ = [("folder_id", ctypes.c_uint32),
+ ("parent_id", ctypes.c_uint32),
+ ("storage_id", ctypes.c_uint32),
+ ("name", ctypes.c_char_p),
+ ("sibling", ctypes.POINTER(LIBMTP_Folder)),
+ ("child", ctypes.POINTER(LIBMTP_Folder))]
+
+# Abstracted from libmtp's LIBMTP_filetype_t. This must be kept in sync.
+# first checked in 0.2.6.1
+# last checked in version 1.1.6
+LIBMTP_Filetype = {
+ "WAV": ctypes.c_int(0),
+ "MP3": ctypes.c_int(1),
+ "WMA": ctypes.c_int(2),
+ "OGG": ctypes.c_int(3),
+ "AUDIBLE": ctypes.c_int(4),
+ "MP4": ctypes.c_int(5),
+ "UNDEF_AUDIO": ctypes.c_int(6),
+ "WMV": ctypes.c_int(7),
+ "AVI": ctypes.c_int(8),
+ "MPEG": ctypes.c_int(9),
+ "ASF": ctypes.c_int(10),
+ "QT": ctypes.c_int(11),
+ "UNDEF_VIDEO": ctypes.c_int(12),
+ "JPEG": ctypes.c_int(13),
+ "JFIF": ctypes.c_int(14),
+ "TIFF": ctypes.c_int(15),
+ "BMP": ctypes.c_int(16),
+ "GIF": ctypes.c_int(17),
+ "PICT": ctypes.c_int(18),
+ "PNG": ctypes.c_int(19),
+ "VCALENDAR1": ctypes.c_int(20),
+ "VCALENDAR2": ctypes.c_int(21),
+ "VCARD2": ctypes.c_int(22),
+ "VCARD3": ctypes.c_int(23),
+ "WINDOWSIMAGEFORMAT": ctypes.c_int(24),
+ "WINEXEC": ctypes.c_int(25),
+ "TEXT": ctypes.c_int(26),
+ "HTML": ctypes.c_int(27),
+ "FIRMWARE": ctypes.c_int(28),
+ "AAC": ctypes.c_int(29),
+ "MEDIACARD": ctypes.c_int(30),
+ "FLAC": ctypes.c_int(31),
+ "MP2": ctypes.c_int(32),
+ "M4A": ctypes.c_int(33),
+ "DOC": ctypes.c_int(34),
+ "XML": ctypes.c_int(35),
+ "XLS": ctypes.c_int(36),
+ "PPT": ctypes.c_int(37),
+ "MHT": ctypes.c_int(38),
+ "JP2": ctypes.c_int(39),
+ "JPX": ctypes.c_int(40),
+ "ALBUM": ctypes.c_int(41),
+ "PLAYLIST": ctypes.c_int(42),
+ "UNKNOWN": ctypes.c_int(43),
+}
+
+# Synced from libmtp 0.2.6.1's libmtp.h. Must be kept in sync.
+LIBMTP_Error_Number = {
+ "NONE": ctypes.c_int(0),
+ "GENERAL": ctypes.c_int(1),
+ "PTP_LAYER": ctypes.c_int(2),
+ "USB_LAYER": ctypes.c_int(3),
+ "MEMORY_ALLOCATION": ctypes.c_int(4),
+ "NO_DEVICE_ATTACHED": ctypes.c_int(5),
+ "STORAGE_FULL": ctypes.c_int(6),
+ "CONNECTING": ctypes.c_int(7),
+ "CANCELLED": ctypes.c_int(8),
+}
+
+# ----------
+# End Data Model Definitions
+# ----------
+
+# ----------
+# Type Definitions
+# ----------
+_libmtp.LIBMTP_Detect_Raw_Devices.restype = ctypes.c_int # actually LIBMTP_Error_Number enum
+_libmtp.LIBMTP_Get_Friendlyname.restype = ctypes.c_char_p
+_libmtp.LIBMTP_Get_Serialnumber.restype = ctypes.c_char_p
+_libmtp.LIBMTP_Get_Modelname.restype = ctypes.c_char_p
+_libmtp.LIBMTP_Get_Manufacturername.restype = ctypes.c_char_p
+_libmtp.LIBMTP_Get_Deviceversion.restype = ctypes.c_char_p
+_libmtp.LIBMTP_Get_Filelisting_With_Callback.restype = ctypes.POINTER(LIBMTP_File)
+_libmtp.LIBMTP_Get_Tracklisting_With_Callback.restype = ctypes.POINTER(LIBMTP_Track)
+_libmtp.LIBMTP_Get_Filetype_Description.restype = ctypes.c_char_p
+_libmtp.LIBMTP_Get_Filemetadata.restype = ctypes.POINTER(LIBMTP_File)
+_libmtp.LIBMTP_Get_Trackmetadata.restype = ctypes.POINTER(LIBMTP_Track)
+_libmtp.LIBMTP_Get_First_Device.restype = ctypes.POINTER(LIBMTP_MTPDevice)
+_libmtp.LIBMTP_Get_Playlist_List.restype = ctypes.POINTER(LIBMTP_Playlist)
+_libmtp.LIBMTP_Get_Playlist.restype = ctypes.POINTER(LIBMTP_Playlist)
+_libmtp.LIBMTP_Get_Folder_List.restype = ctypes.POINTER(LIBMTP_Folder)
+_libmtp.LIBMTP_Find_Folder.restype = ctypes.POINTER(LIBMTP_Folder)
+_libmtp.LIBMTP_Get_Errorstack.restype = ctypes.POINTER(LIBMTP_Error)
+
+_libmtp.LIBMTP_Open_Raw_Device.restype = ctypes.POINTER(LIBMTP_MTPDevice)
+_libmtp.LIBMTP_Open_Raw_Device.argtypes = [ctypes.POINTER(LIBMTP_RawDevice)]
+
+# This is for callbacks with the type of LIBMTP_progressfunc_t
+Progressfunc = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_uint64, ctypes.c_uint64)
+
+# ----------
+# End Type Definitions
+# ----------
+
+class MTP:
+ """
+ The MTP object
+ This is the main wrapper around libmtp
+ """
+
+ def __init__(self):
+ """
+ Initializes the MTP object
+
+ @rtype: None
+ @return: None
+ """
+
+ self.mtp = _libmtp
+ self.mtp.LIBMTP_Init()
+ self.device = None
+
+ def debug_stack(self):
+ """
+ Checks if __DEBUG__ is set, if so, prints and clears the
+ errorstack.
+
+ @rtype: None
+ @return: None
+ """
+
+ if __DEBUG__:
+ self.mtp.LIBMTP_Dump_Errorstack()
+ #self.mtp.LIBMTP_Clear_Errorstack()
+
+ def detect_devices(self):
+ """
+ Detect if any MTP devices are connected
+
+ @rtype: None
+ @return: a list of LIBMTP_RawDevice instances for devices found
+
+ """
+
+ devlist = []
+ device = LIBMTP_RawDevice()
+ devices = ctypes.pointer(device)
+ numdevs = ctypes.c_int(0)
+ err = self.mtp.LIBMTP_Detect_Raw_Devices(ctypes.byref(devices),
+ ctypes.byref(numdevs))
+ if err == LIBMTP_Error_Number['NO_DEVICE_ATTACHED']:
+ return devlist
+ elif err == LIBMTP_Error_Number['STORAGE_FULL']:
+ # ignore this, we're just trying to detect here, not do anything else
+ pass
+ elif err == LIBMTP_Error_Number['CONNECTING']:
+ raise AlreadyConnected('CONNECTING')
+ elif err == LIBMTP_Error_Number['GENERAL']:
+ raise CommandFailed('GENERAL')
+ elif err == LIBMTP_Error_Number['PTP_LAYER']:
+ raise CommandFailed('PTP_LAYER')
+ elif err == LIBMTP_Error_Number['USB_LAYER']:
+ raise CommandFailed('USB_LAYER')
+ elif err == LIBMTP_Error_Number['MEMORY_ALLOCATION']:
+ raise CommandFailed('MEMORY_ALLOCATION')
+ elif err == LIBMTP_Error_Number['CANCELLED']:
+ raise CommandFailed('CANCELLED')
+ if numdevs.value == 0:
+ return devlist
+ for i in range(numdevs.value):
+ devlist.append(devices[i])
+ return devlist
+
+ def connect(self):
+ """
+ Initializes the MTP connection to the device
+
+ @rtype: None
+ @return: None
+
+ """
+
+ if (self.device != None):
+ raise AlreadyConnected
+
+ self.device = self.mtp.LIBMTP_Get_First_Device()
+
+ if not self.device:
+ self.device = None
+ raise NoDeviceConnected
+
+ def disconnect(self):
+ """
+ Disconnects the MTP device and deletes the self.device object
+
+ @rtype: None
+ @return: None
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ self.mtp.LIBMTP_Release_Device(self.device)
+ del self.device
+ self.device = None
+
+ def get_devicename(self):
+ """
+ Returns the connected device's 'friendly name' (or
+ known as the owner name)
+
+ @rtype: string
+ @return: The connected device's 'friendly name'
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ return self.mtp.LIBMTP_Get_Friendlyname(self.device)
+
+ def set_devicename(self, name):
+ """
+ Changes the connected device's 'friendly name' to name
+
+ @type name: string
+ @param name: The name to change the connected device's
+ 'friendly name' to
+ @rtype: None
+ @return: None
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ ret = self.mtp.LIBMTP_Set_Friendlyname(self.device, name)
+ if (ret != 0):
+ self.debug_stack()
+ raise CommandFailed
+
+ def get_serialnumber(self):
+ """
+ Returns the connected device's serial number
+
+ @rtype: string
+ @return: The connected device's serial number
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ return self.mtp.LIBMTP_Get_Serialnumber(self.device)
+
+ def get_manufacturer(self):
+ """
+ Return the connected device's manufacturer
+
+ @rtype: string
+ @return: The connected device's manufacturer
+ """
+ if (self.device == None):
+ raise NotConnected
+
+ return self.mtp.LIBMTP_Get_Manufacturername(self.device)
+
+ def get_batterylevel(self):
+ """
+ Returns the connected device's maximum and current
+ battery levels
+
+ @rtype: tuple
+ @return: The connected device's maximum and current
+ battery levels ([0] is maximum, [1] is current)
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ maximum_level = ctypes.c_uint8()
+ current_level = ctypes.c_uint8()
+
+ ret = self.mtp.LIBMTP_Get_Batterylevel(self.device, \
+ ctypes.byref(maximum_level), ctypes.byref(current_level))
+
+ if (ret != 0):
+ raise CommandFailed
+
+ return (maximum_level.value, current_level.value)
+
+ def get_modelname(self):
+ """
+ Returns the connected device's model name (such
+ as "Zen V Plus")
+
+ @rtype: string
+ @return: The connected device's model name
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ return self.mtp.LIBMTP_Get_Modelname(self.device)
+
+ def get_deviceversion(self):
+ """
+ Returns the connected device's version (such as
+ firmware/hardware version)
+
+ @rtype: string
+ @return: Returns the connect device's version
+ information
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ return self.mtp.LIBMTP_Get_Deviceversion(self.device)
+
+ def get_filelisting(self, callback=None):
+ """
+ Returns the connected device's file listing as a tuple,
+ containing L{LIBMTP_File} objects.
+
+ @type callback: function or None
+ @param callback: The function provided to libmtp to
+ receive callbacks from ptp. Callback must take two
+ arguments, total and sent (in bytes)
+ @rtype: tuple
+ @return: Returns the connect device file listing tuple
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ if (callback != None):
+ callback = Progressfunc(callback)
+
+ files = self.mtp.LIBMTP_Get_Filelisting_With_Callback(self.device, callback, None)
+ ret = []
+ next = files
+
+ while next:
+ ret.append(next.contents)
+ if (next.contents.next == None):
+ break
+ next = next.contents.next
+
+ return ret
+
+ def get_filetype_description(self, filetype):
+ """
+ Returns the description of the filetype
+
+ @type filetype: int
+ @param filetype: The MTP filetype integer
+ @rtype: string
+ @return: The file type information
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ return self.mtp.LIBMTP_Get_Filetype_Description(filetype)
+
+ def get_file_metadata(self, file_id):
+ """
+ Returns the file metadata from the connected device
+
+ As per the libmtp documentation, calling this function
+ repeatedly is not recommended, as it is slow and creates
+ a large amount of USB traffic.
+
+ @type file_id: int
+ @param file_id: The unique numeric file id
+ @rtype: LIBMTP_File
+ @return: The file metadata
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ ret = self.mtp.LIBMTP_Get_Filemetadata(self.device, file_id)
+
+ if (not hasattr(ret, 'contents')):
+ raise ObjectNotFound
+
+ return ret.contents
+
+ def get_tracklisting(self, callback=None):
+ """
+ Returns tracks from the connected device
+
+ @type callback: function or None
+ @param callback: The function provided to libmtp to
+ receive callbacks from ptp. Callback must take two
+ arguments, total and sent (in bytes)
+ @rtype: tuple
+ @return: Returns a tuple full of L{LIBMTP_Track} objects
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ if (callback != None):
+ callback = Progressfunc(callback)
+
+ tracks = self.mtp.LIBMTP_Get_Tracklisting_With_Callback(self.device, callback, None)
+ ret = []
+ next = tracks
+
+ while next:
+ ret.append(next.contents)
+ if (next.contents.next == None):
+ break
+ next = next.contents.next
+
+ return ret
+
+ def get_track_metadata(self, track_id):
+ """
+ Returns the track metadata
+
+ As per the libmtp documentation, calling this function repeatedly is not
+ recommended, as it is slow and creates a large amount of USB traffic.
+
+ @type track_id: int
+ @param track_id: The unique numeric track id
+ @rtype: L{LIBMTP_Track}
+ @return: The track metadata
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ ret = self.mtp.LIBMTP_Get_Trackmetadata(self.device, track_id)
+
+ if (not hasattr(ret, 'contents')):
+ raise ObjectNotFound
+
+ return ret.contents
+
+ def get_file_to_file(self, file_id, target, callback=None):
+ """
+ Downloads the file from the connected device and stores it at the
+ target location
+
+ @type file_id: int
+ @param file_id: The unique numeric file id
+ @type target: str
+ @param target: The location to place the file
+ @type callback: function or None
+ @param callback: The function provided to libmtp to
+ receive callbacks from ptp. Callback must take two
+ arguments, total and sent (in bytes)
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ if (callback != None):
+ callback = Progressfunc(callback)
+
+ ret = self.mtp.LIBMTP_Get_File_To_File(self.device, file_id, target, callback, None)
+
+ if (ret != 0):
+ self.debug_stack()
+ raise CommandFailed
+
+ def get_track_to_file(self, track_id, target, callback=None):
+ """
+ Downloads the track from the connected device and stores it at
+ the target location
+
+ @type track_id: int
+ @param track_id: The unique numeric track id
+ @type target: str
+ @param target: The location to place the track
+ @type callback: function or None
+ @param callback: The function provided to libmtp to
+ receive callbacks from ptp. Callback must take two
+ arguments, total and sent (in bytes)
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ if (callback != None):
+ callback = Progressfunc(callback)
+
+ ret = self.mtp.LIBMTP_Get_Track_To_File(self.device, track_id, target, callback, None)
+
+ if (ret != 0):
+ self.debug_stack()
+ raise CommandFailed
+
+ def find_filetype(self, filename):
+ """
+ Attempts to guess the filetype off the filename. Kind of
+ inaccurate and should be trusted with a grain of salt. It
+ works in most situations, though.
+
+ @type filename: str
+ @param filename: The filename to attempt to guess from
+ @rtype: int
+ @return: The integer of the Filetype
+ """
+
+ fileext = filename.decode('utf-8').lower().split(".")[-1]
+
+ if (fileext == "wav" or fileext == "wave"):
+ return LIBMTP_Filetype["WAV"]
+ elif (fileext == "mp3"):
+ return LIBMTP_Filetype["MP3"]
+ elif (fileext == "wma"):
+ return LIBMTP_Filetype["WMA"]
+ elif (fileext == "ogg"):
+ return LIBMTP_Filetype["OGG"]
+ elif (fileext == "mp4"):
+ return LIBMTP_Filetype["MP4"]
+ elif (fileext == "wmv"):
+ return LIBMTP_Filetype["WMV"]
+ elif (fileext == "avi"):
+ return LIBMTP_Filetype["AVI"]
+ elif (fileext == "mpeg" or fileext == "mpg"):
+ return LIBMTP_Filetype["MPEG"]
+ elif (fileext == "asf"):
+ return LIBMTP_Filetype["ASF"]
+ elif (fileext == "qt" or fileext == "mov"):
+ return LIBMTP_Filetype["QT"]
+ elif (fileext == "jpeg" or fileext == "jpg"):
+ return LIBMTP_Filetype["JPEG"]
+ elif (fileext == "jfif"):
+ return LIBMTP_Filetype["JFIF"]
+ elif (fileext == "tif" or fileext == "tiff"):
+ return LIBMTP_Filetype["TIFF"]
+ elif (fileext == "bmp"):
+ return LIBMTP_Filetype["BMP"]
+ elif (fileext == "gif"):
+ return LIBMTP_Filetype["GIF"]
+ elif (fileext == "pic" or fileext == "pict"):
+ return LIBMTP_Filetype["PICT"]
+ elif (fileext == "png"):
+ return LIBMTP_Filetype["PNG"]
+ elif (fileext == "wmf"):
+ return LIBMTP_Filetype["WINDOWSIMAGEFORMAT"]
+ elif (fileext == "ics"):
+ return LIBMTP_Filetype["VCALENDAR2"]
+ elif (fileext == "exe" or fileext == "com" or fileext == "bat"\
+ or fileext == "dll" or fileext == "sys"):
+ return LIBMTP_Filetype["WINEXEC"]
+ elif (fileext == "aac"):
+ return LIBMTP_Filetype["AAC"]
+ elif (fileext == "mp2"):
+ return LIBMTP_Filetype["MP2"]
+ elif (fileext == "flac"):
+ return LIBMTP_Filetype["FLAC"]
+ elif (fileext == "m4a"):
+ return LIBMTP_Filetype["M4A"]
+ elif (fileext == "doc"):
+ return LIBMTP_Filetype["DOC"]
+ elif (fileext == "xml"):
+ return LIBMTP_Filetype["XML"]
+ elif (fileext == "xls"):
+ return LIBMTP_Filetype["XLS"]
+ elif (fileext == "ppt"):
+ return LIBMTP_Filetype["PPT"]
+ elif (fileext == "mht"):
+ return LIBMTP_Filetype["MHT"]
+ elif (fileext == "jp2"):
+ return LIBMTP_Filetype["JP2"]
+ elif (fileext == "jpx"):
+ return LIBMTP_Filetype["JPX"]
+ else:
+ return LIBMTP_Filetype["UNKNOWN"]
+
+ def send_file_from_file(self, source, target, callback=None):
+ """
+ Sends a file from the filesystem to the connected device
+ and stores it at the target filename inside the parent.
+
+ This will attempt to "guess" the filetype with
+ find_filetype()
+
+ @type source: str
+ @param source: The path on the filesystem where the file resides
+ @type target: str
+ @param target: The target filename on the device
+ @type callback: function or None
+ @param callback: The function provided to libmtp to
+ receive callbacks from ptp. Callback function must
+ take two arguments, sent and total (in bytes)
+ @rtype: int
+ @return: The object ID of the new file
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ if (os.path.isfile(source) == False):
+ raise IOError
+
+ if (callback != None):
+ callback = Progressfunc(callback)
+
+ metadata = LIBMTP_File(filename=target, \
+ filetype=self.find_filetype(source), \
+ filesize=os.stat(source).st_size)
+
+ ret = self.mtp.LIBMTP_Send_File_From_File(self.device, source, \
+ ctypes.pointer(metadata), callback, None)
+
+ if (ret != 0):
+ self.debug_stack()
+ raise CommandFailed
+
+ return metadata.item_id
+
+ def send_track_from_file(self, source, target, metadata, callback=None):
+ """
+ Sends a track from the filesystem to the connected
+ device
+
+ @type source: str
+ @param source: The path where the track resides
+ @type target: str
+ @param target: The target filename on the device
+ @type metadata: LIBMTP_Track
+ @param metadata: The track metadata
+ @type callback: function or None
+ @param callback: The function provided to libmtp to
+ receive callbacks from ptp. Callback function must
+ take two arguments, sent and total (in bytes)
+ @rtype: int
+ @return: The object ID of the new track
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ if (os.path.exists(source) == None):
+ raise IOError
+
+ if callback:
+ callback = Progressfunc(callback)
+
+ metadata.filename = target
+ metadata.filetype = self.find_filetype(source)
+ metadata.filesize = os.stat(source).st_size
+
+ ret = self.mtp.LIBMTP_Send_Track_From_File(self.device, source, \
+ ctypes.pointer(metadata), callback, None)
+
+ if (ret != 0):
+ self.debug_stack()
+ raise CommandFailed
+
+ return metadata.item_id
+
+ def get_freespace(self):
+ """
+ Returns the amount of free space on the connected device
+ @rtype: long
+ @return: The amount of free storage in bytes
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ self.mtp.LIBMTP_Get_Storage(self.device, 0)
+ return self.device.contents.storage.contents.FreeSpaceInBytes
+
+ def get_totalspace(self):
+ """
+ Returns the total space on the connected device
+ @rtype: long
+ @return: The amount of total storage in bytes
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ self.mtp.LIBMTP_Get_Storage(self.device, 0)
+ return self.device.contents.storage.contents.MaxCapacity
+
+ def get_usedspace(self):
+ """
+ Returns the amount of used space on the connected device
+
+ @rtype: long
+ @return: The amount of used storage in bytes
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ self.mtp.LIBMTP_Get_Storage(self.device, 0)
+ storage = self.device.contents.storage.contents
+ return (storage.MaxCapacity - storage.FreeSpaceInBytes)
+
+ def get_usedspace_percent(self):
+ """
+ Returns the amount of used space as a percentage
+
+ @rtype: float
+ @return: The percentage of used storage
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ self.mtp.LIBMTP_Get_Storage(self.device, 0)
+ storage = self.device.contents.storage.contents
+
+ # Why don't we call self.get_totalspace/self.get_usedspace
+ # here? That would require 3 *more* calls to
+ # LIBMTP_Get_Storage
+ usedspace = storage.MaxCapacity - storage.FreeSpaceInBytes
+ return ((float(usedspace) / float(storage.MaxCapacity)) * 100)
+
+ def delete_object(self, object_id):
+ """
+ Deletes the object off the connected device.
+
+ @type object_id: int
+ @param object_id: The unique object identifier
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ ret = self.mtp.LIBMTP_Delete_Object(self.device, object_id)
+
+ if (ret != 0):
+ self.debug_stack()
+ raise CommandFailed
+
+ def get_playlists(self):
+ """
+ Returns a tuple filled with L{LIBMTP_Playlist} objects
+ from the connected device.
+
+ The main gotcha of this function is that the tracks
+ variable of LIBMTP_Playlist isn't iterable (without
+ segfaults), so, you have to iterate over the no_tracks
+ (through range or xrange) and access it that way (i.e.
+ tracks[track_id]). Kind of sucks.
+
+ @rtype: tuple
+ @return: Tuple filled with LIBMTP_Playlist objects
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ playlists = self.mtp.LIBMTP_Get_Playlist_List(self.device)
+ ret = []
+ next = playlists
+
+ while next:
+ ret.append(next.contents)
+ if (next.contents.next == None):
+ break
+ next = next.contents.next
+
+ return ret
+
+ def get_playlist(self, playlist_id):
+ """
+ Returns a L{LIBMTP_Playlist} object of the requested
+ playlist_id from the connected device
+
+ @type playlist_id: int
+ @param playlist_id: The unique playlist identifier
+ @rtype: LIBMTP_Playlist
+ @return: The playlist object
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ try:
+ ret = self.mtp.LIBMTP_Get_Playlist(self.device, playlist_id).contents
+ except ValueError:
+ raise ObjectNotFound
+
+ return ret
+
+ def create_new_playlist(self, metadata):
+ """
+ Creates a new playlist based on the metadata object
+ passed.
+
+ @type metadata: LIBMTP_Playlist
+ @param metadata: A LIBMTP_Playlist object describing
+ the playlist
+ @rtype: int
+ @return: The object ID of the new playlist
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ ret = self.mtp.LIBMTP_Create_New_Playlist(self.device, ctypes.pointer(metadata))
+
+ if (ret != 0):
+ self.debug_stack()
+ raise CommandFailed
+
+ return metadata.playlist_id
+
+ def update_playlist(self, metadata):
+ """
+ Updates a playlist based on the supplied metadata.
+
+ When updating the tracks field in a playlist, this
+ function will replace the playlist's tracks with
+ the tracks supplied in the metadata object. This
+ means that the previous tracks in the playlist
+ will be overwritten.
+
+ @type metadata: LIBMTP_Playlist
+ @param metadata: A LIBMTP_Playlist object describing
+ the updates to the playlist.
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ ret = self.mtp.LIBMTP_Update_Playlist(self.device, ctypes.pointer(metadata))
+
+ if (ret != 0):
+ self.debug_stack()
+ raise CommandFailed
+
+ def get_folder_list(self):
+ """
+ Returns a pythonic dict of the folders on the
+ device.
+
+ @rtype: dict
+ @return: A dict of the folders on the device where
+ the folder ID is the key.
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ folders = self.mtp.LIBMTP_Get_Folder_List(self.device)
+ next = folders
+ # List of folders, key being the folder ID
+ ret = {}
+ # Iterate over the folders to grab the first-level parents
+ while True:
+ next = next.contents
+ scanned = True
+
+ # Check if this ID exists, if not, add it
+ # and trigger a scan of the children
+ if not (ret.has_key(next.folder_id)):
+ ret[next.folder_id] = next
+ scanned = False
+
+ if ((scanned == False) and (next.child)):
+ ## Scan the children
+ next = next.child
+
+ elif (next.sibling):
+ ## Scan the siblings
+ next = next.sibling
+
+ elif (next.parent_id != 0):
+ ## If we have no children/siblings to visit,
+ ## and we aren't at the parent, go back to
+ ## the parent.
+ next = self.mtp.LIBMTP_Find_Folder(folders, int(next.parent_id))
+
+ else:
+ ## We have scanned everything, let's go home.
+ break
+
+ return ret
+
+ def get_parent_folders(self):
+ """
+ Returns a list of only the parent folders.
+ @rtype: list
+ @return: Returns a list of the parent folders
+ """
+
+ if (self.device == None):
+ raise NotConnected
+ folders = self.mtp.LIBMTP_Get_Folder_List(self.device)
+ next = folders
+ # A temporary holding space, this makes checking folder
+ # IDs easier
+ tmp = {}
+
+ while True:
+ next = next.contents
+ ## Check if this folder is in the dict
+ if not (tmp.has_key(next.folder_id)):
+ tmp[next.folder_id] = next
+
+ # Check for siblings
+ if (next.sibling):
+ ## Scan the sibling
+ next = next.sibling
+ else:
+ ## We're done here.
+ break
+
+ ## convert the dict into a list
+ ret = []
+ for key in tmp:
+ ret.append(tmp[key])
+
+ return ret
+
+ def create_folder(self, name, parent=0, storage=0):
+ """
+ This creates a new folder in the parent. If the parent
+ is 0, it will go in the main directory.
+
+ @type name: str
+ @param name: The name for the folder
+ @type parent: int
+ @param parent: The parent ID or 0 for main directory
+ @type storage: int
+ @param storage: The storage id or 0 to create the new folder
+ on the primary storage
+ @rtype: int
+ @return: Returns the object ID of the new folder
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ ret = self.mtp.LIBMTP_Create_Folder(self.device, name, parent, storage)
+
+ if (ret == 0):
+ self.debug_stack()
+ raise CommandFailed
+
+ return ret
+
+ def get_errorstack(self):
+ """
+ Returns the connected device's errorstack from
+ LIBMTP.
+ @rtype: L{LIBMTP_Error}
+ @return: An array of LIBMTP_Errors.
+ """
+
+ if (self.device == None):
+ raise NotConnected
+
+ ret = self.mtp.LIBMTP_Get_Errorstack(self.device)
+
+ if (ret != 0):
+ raise CommandFailed
+
+ return ret
diff --git a/tools/file2carray.py b/tools/file2carray.py
new file mode 100644
index 000000000..abfb4e21b
--- /dev/null
+++ b/tools/file2carray.py
@@ -0,0 +1,45 @@
+#!/usr/bin/env python3
+import argparse
+import random
+import os
+import sys
+import time
+import subprocess
+from pathlib import Path
+from multiprocessing import Pool
+from weakref import finalize
+
+
+def print_carray(f, payload):
+ while len(payload) > 0:
+ f.write('\n ')
+ f.write(', '.join('0x{:02x}'.format(x) for x in payload[0:16]))
+ f.write(',')
+ payload = payload[16:]
+ f.write('\n')
+
+
+def main():
+ parser = argparse.ArgumentParser(description='Convert binary files to C array format')
+ parser.add_argument('files', nargs='+', help='Binary files to convert')
+ args = parser.parse_args()
+
+ files = args.files
+ for fin_name in files:
+ if not os.path.isfile(fin_name):
+ print(f"File {fin_name} does not exist")
+ continue
+
+ with open(fin_name, 'rb') as fin:
+ contents = fin.read()
+ fout_name = fin_name + '.h'
+ with open(fout_name, 'w') as fout:
+ print(f"Converting {fin_name} to {fout_name}")
+ fout.write(f'const size_t bindata_len = {len(contents)};\n')
+ fout.write(f'const uint8_t bindata[] __attribute__((aligned(16))) = {{')
+ print_carray(fout, contents)
+ fout.write('};\n')
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/tools/iar_template.ipcf b/tools/iar_template.ipcf
index 33a6ef045..2581a4702 100644
--- a/tools/iar_template.ipcf
+++ b/tools/iar_template.ipcf
@@ -58,6 +58,11 @@
<path>$TUSB_DIR$/src/class/msc/msc_device.h</path>
<path>$TUSB_DIR$/src/class/msc/msc_host.h</path>
</group>
+ <group name="src/class/mtp">
+ <path>$TUSB_DIR$/src/class/mtp/mtp_device.c</path>
+ <path>$TUSB_DIR$/src/class/mtp/mtp.h</path>
+ <path>$TUSB_DIR$/src/class/mtp/mtp_device.h</path>
+ </group>
<group name="src/class/net">
<path>$TUSB_DIR$/src/class/net/ecm_rndis_device.c</path>
<path>$TUSB_DIR$/src/class/net/ncm_device.c</path>