Introducing a new way to review your PRs.

Read the announcement

hathach / tinyusb

An open source cross-platform USB stack for embedded system

View on GitHub

18 documents · Updated Nov 23, 2026

docs / usb-class-drivers

USB class drivers

USB class drivers turn standard USB interfaces into application-facing device and host capabilities. They sit between the USB bus stacks and application code, so an application works with streams, reports, packets, blocks, media frames, or protocol messages instead of raw USB transfers.

Class-driver layer

Capability boundary

The class-driver layer gives each supported USB protocol a clear application boundary. A device driver makes the local board present a function to a host. A host driver makes the local board use a connected function. Both roles translate interface descriptions and USB transfers into protocol state, data APIs, and callbacks.

The USB device stack and USB host stack provide the bus and transfer services below this layer. The class pages describe the application behavior for each family of protocols.

FamilyMain capabilitiesChild page
Serial and human interfaceSerial links, keyboards, mice, gamepads, and MIDI dataSerial and human-interface classes
Media and connectivityAudio, video, storage, and USB network linksMedia and connectivity classes
Specialized peripheralsFirmware update, printing, Bluetooth controller transport, test and measurement, vendor transport, image transfer, and MIDI 2.0 functionsSpecialized peripheral classes

USB-MIDI 2.0 adds a mode-selection step before normal data use. A device and host can use MIDI 1.0 event packets or MIDI 2.0 Universal MIDI Packets (UMP). The active mode exposes its own topology and packet boundary to the application. If MIDI 2.0 cannot be selected, the host keeps MIDI 1.0 as the usable mode.

References: src/…/midi2_device.c• L582-663 src/…/midi2_host.c• L605-723 src/…/bth_device.c• L110-218 src/…/printer_device.c• L183-227 src/…/vendor_device.c• L692-803

Device and host roles

Device capabilities

Device class drivers make a board act as one or more USB functions. The application supplies descriptors and protocol data. The class driver handles requests, endpoint transfers, and protocol state after the host selects the configuration.

Several functions can share one configuration. A device can therefore offer serial, human-interface, storage, network, audio, video, printer, Bluetooth, or vendor-specific capabilities at the same time. Each class maps its USB transport to an application model:

  • HID sends and receives reports.
  • CDC presents a serial stream with line state and line coding.
  • Audio presents timed samples through capture or playback streams.
  • Video presents negotiated frames.
  • MSC presents storage through commands, blocks, sense status, and completion callbacks.
  • Network classes present packets while applying ECM, RNDIS, or NCM framing.
  • MIDI presents event packets or UMP messages according to the active mode.
  • Bluetooth presents HCI commands, events, and ACL data to a Bluetooth controller.
  • Printer presents byte streams plus device ID, port status, and soft-reset controls.
  • Vendor-specific functions provide application-defined bulk, interrupt, or isochronous transfers.
  • DFU presents firmware download, upload, status, and manifest control.

The application boundary also defines when submitted data can be reused. This matters for media frames, storage I/O, Bluetooth packets, network buffers, and vendor transfers because the class can retain ownership until a completion or release callback.

References: src/…/cdc_device.c• L113-225 src/…/audio_device.c• L421-559 src/…/hid_device.c• L89-186 src/…/msc_device.c• L169-225 src/…/bth_device.c• L46-92 src/…/printer_device.c• L62-135 src/…/vendor_device.c• L168-357

Host capabilities

Host class drivers make a board use functions exposed by attached USB devices. During enumeration, a compatible driver claims an interface and opens the endpoints that carry its protocol. The application can use the capability only after the driver completes class-specific setup and reports the mount event.

The host role hides protocol setup behind class APIs. CDC host support exposes buffered serial access and line controls. HID host support exposes reports and report controls. Audio host support exposes discovered capture and playback streams. MSC host support discovers logical units and capacity before it reports storage as mounted. MIDI host support exposes packet or stream access after it finds the MIDI Streaming interface.

Some host drivers also adapt protocol variants to one application boundary. CDC maps supported vendor serial devices to the common serial model. MIDI 2.0 selects UMP mode when possible and reports MIDI 1.0 when it cannot activate that mode. The application therefore handles a ready capability instead of repeating device-specific setup.

References: src/…/cdc_host.c• L745-810 src/…/cdc_host.c• L982-1040 src/…/audio_host.c• L763-821 src/…/msc_host.c• L593-639 src/…/midi_host.c• L323-341 src/…/midi2_host.c• L678-786

Interface lifecycle

Descriptor matching

USB descriptors are the hand-off between the bus stack and a class driver. An interface descriptor identifies the class, subclass, and protocol. Related interfaces, alternate settings, and endpoints can form one function, so a driver can claim a group rather than one interface.

The matching flow turns a descriptor set into an application capability:

flowchart TD
    A[USB interface descriptors] --> B[Class driver checks support]
    B -->|Supported| C[Driver claims interfaces and endpoints]
    B -->|Unsupported| D[Interface remains unavailable]
    C --> E[Class-specific setup]
    E --> F[Application-facing capability]

On the device side, local descriptors describe the functions that the board offers. On the host side, the connected device supplies the descriptors. The class and interface relationship remains the same in both roles.

Matching also protects endpoint and mode rules. Audio groups control and streaming interfaces. CDC may match a standard ACM interface or an identified vendor serial interface. MIDI 2.0 associates alternate settings with one interface. Vendor interfaces can expose different endpoint sets through alternate settings. Bluetooth and printer functions require their class-specific interface shape before they open.

References: src/…/audio_host.c• L960-1045 src/…/cdc_host.c• L745-771 src/…/midi2_host.c• L605-675 src/…/bth_device.c• L110-218 src/…/printer_device.c• L183-227 src/…/vendor_device.c• L692-803

Application readiness

A class driver separates discovery from use. The application receives a mount or ready event after the stack has claimed interfaces and completed the required setup. It then uses the class API to exchange data or control the function.

Readiness can include protocol checks before the event:

  • HID can fetch its report descriptor and select its configured protocol.
  • MSC can establish the logical-unit range, readiness, and capacity.
  • Audio can discover stream formats and control ranges before mount. A stream becomes active after the application selects a configuration and receives the start-complete event.
  • Video becomes usable after format negotiation and commit.
  • MIDI 2.0 reports its mode only after alternate-setting selection succeeds or fallback is complete.
  • Network traffic waits for active data endpoints.
  • Vendor alternate-setting support exposes only the endpoint set selected by the host.

When a device leaves the bus, the class state closes and the application receives the matching unmount event when the class contract provides one. The application must stop using that capability and wait for a later mount event before it starts again.

References: src/…/audio_host.c• L795-821 src/…/msc_host.c• L587-591 src/…/midi2_host.c• L678-723 src/…/vendor_device.c• L562-690

Application interfaces

Data and control paths

Class drivers expose two related paths. The data path carries protocol payloads. The control path changes settings or returns status through USB control requests. Class APIs hide endpoint and transfer details while callbacks report data, completion, and state changes.

Applications normally follow this pattern:

  1. Wait for the class mount or ready event.
  2. Read, write, submit, or configure through the class API.
  3. Handle receive, transmit, completion, or status callbacks.
  4. Stop new work when the class reports an unmount, disconnect, or inactive stream.

The data model depends on the protocol. HID uses reports. Storage uses commands and blocks. Media uses timed streams or frames. Networking uses packets. Printing and CDC use byte streams. Bluetooth uses HCI and ACL packets. MIDI 1.0 uses event packets. MIDI 2.0 uses complete UMP messages when its alternate setting is active.

References: src/…/cdc_device.c• L113-225 src/…/printer_device.c• L92-135 src/…/bth_device.c• L46-92 src/…/net_device.h• L65-114 src/…/midi2_device.c• L668-750

Serial stream control

The CDC host interface combines a buffered byte stream with serial control state. The application can check whether an interface is mounted, read or write bytes, and set DTR, RTS, baud rate, and data format through control requests.

This separates stream use from device setup. Standard CDC ACM devices and supported vendor serial devices share this boundary even when their control steps differ. Backend-specific limits remain part of the contract; an invalid setting is rejected instead of silently changed.

References: src/…/cdc_host.h• L45-175 src/…/cdc_host.c• L745-810 src/…/cdc_host.c• L982-1040

Report exchange

HID presents input and output as reports. A device can send input reports and receive output reports. A host can receive and send reports and can use control requests for report, idle, and protocol operations.

The host reports the report descriptor at mount when it fits the available enumeration buffer. A failed input transfer is reported as a failure rather than stale report data. Boot handling applies only to the defined keyboard and mouse protocol values; other values remain generic report interfaces.

References: src/…/hid_device.c• L89-186 src/…/hid_host.c• L257-338 src/…/hid_host.c• L614-695

Timed media exchange

Audio and video class drivers turn USB media interfaces into application streams. Audio uses application-facing buffers for timed samples. Video uses a negotiated frame format and sends one accepted frame through a sequence of payload transfers.

The media flow keeps USB timing and payload state below the application boundary:

flowchart LR
    A[Host selects media settings] --> B[Class negotiates stream]
    B --> C[Application supplies samples or frame data]
    C --> D[Class sends or receives USB payloads]
    D --> E[Completion or abort callback]

Audio host support exposes complete PCM configurations and optional feedback. The application selects a configuration and starts the stream asynchronously. The device side uses the selected alternate setting to activate streaming. Video uses probe and commit before it accepts frames. A submitted frame remains owned by the class until completion or abort.

References: src/…/audio_host.c• L730-757 src/…/audio_host.c• L824-849 src/…/audio_device.c• L441-559 src/…/video_device.c• L1219-1324 src/…/video_device.c• L1425-1485

Storage command and block exchange

MSC presents storage through a command, data, and status flow. The host sends SCSI commands and receives completion data. The device maps commands such as inquiry, capacity, read, and write to storage callbacks, then returns status and sense information.

Host readiness includes capacity discovery. The host does not report storage as mounted until it has established the logical-unit range and block geometry. Device-side checks reject invalid block ranges and transfer lengths before storage callbacks run.

Device storage can complete read and write work at once or later through the asynchronous I/O boundary. A bus reset or mass-storage reset can abandon a pending operation, but the application still completes that operation before the class reuses its buffer. A failed host command can fence later commands until reset recovery succeeds.

References: src/…/msc_host.c• L520-576 src/…/msc_host.c• L587-639 src/…/msc_device.c• L169-225 src/…/msc_device.c• L342-384

Object and image transfer

MTP presents an object and image service through command, data, and response containers. The application handles supported commands and data phases. It can also handle cancel, reset, device status, vendor requests, and event delivery.

The service keeps a session and phase boundary visible to the application. A refused command or invalid data container moves the service into recovery. The host then uses status, endpoint recovery, or reset actions before a new command can proceed.

References: src/…/mtp_device.c• L32-68 src/…/mtp_device.c• L186-230 src/…/mtp_device.c• L426-527 src/…/mtp_device.c• L575-761

Test and measurement exchange

USBTMC turns a USB interface into a test-and-measurement message service. The application receives device-dependent commands, supplies response data, and can send notifications while the class driver carries the required bulk and control protocol. Optional USB488 support adds status-byte and trigger behavior to the same message boundary.

The service keeps one command direction active at a time. Abort and clear actions form a recovery boundary that can keep the interface busy until the class and application finish their work.

References: src/…/usbtmc_device.h• L24-90 src/…/usbtmc_device.c• L217-281 src/…/usbtmc_device.c• L420-559 src/…/usbtmc_device.c• L667-719

Network packet exchange

Network class drivers present Ethernet-sized packets to an application network layer. The application supplies receive and transmit callbacks. The class driver adds or removes the framing required by ECM, RNDIS, or NCM and controls link notifications.

ProtocolUSB data modelReadiness boundary
ECMOne packet per data transferData interface alternate setting 1
RNDISA packet message wraps the Ethernet payloadManagement and data interfaces configured
NCMOne or more datagrams inside a Network Transfer BlockData interface alternate setting 1 and negotiated NTB limits

NCM groups packets for efficient transfer and validates the block and datagram ranges before it passes packets to the application. It can hold a receive buffer for zero-copy use until the network layer releases it. ECM and RNDIS use their own management requests and notifications. The application boundary remains packet-based across these transport differences.

References: src/…/net_device.h• L65-114 src/…/ecm_rndis_device.c• L161-201 src/…/ecm_rndis_device.c• L332-359 src/…/ncm.h• L14-59 src/…/ncm_device.c• L612-752 src/…/ncm_device.c• L764-880

Peripheral stream exchange

Printer, Bluetooth, and vendor-specific classes cover functions that do not fit the common serial, media, storage, or network models. They still use the same class boundary: the driver owns USB state and the application owns protocol data and completion decisions.

CapabilityApplication-facing model
PrinterBuffered byte input and output plus device ID, port status, and soft reset controls
Bluetooth controllerHCI commands, controller events, and ACL data
Vendor-specific functionApplication-defined bulk, interrupt, or isochronous transfers

Vendor-specific interfaces can use alternate settings to select different endpoint sets. The application must use the API that matches the active setting and must re-arm transfers for manually controlled interrupt or isochronous endpoints. Bluetooth send buffers remain owned until the matching completion callback.

References: src/…/printer_device.h• L29-114 src/…/printer_device.c• L230-317 src/…/bth_device.h• L47-83 src/…/bth_device.c• L255-282 src/…/vendor_device.h• L125-207 src/…/vendor_device.c• L562-690 src/…/vendor_device.c• L923-988

Firmware update control

DFU provides a control-based firmware update service. In DFU mode, the host selects an alternate setting that identifies a target area, downloads or uploads blocks, and polls status until the device reaches an idle, busy, manifest, or error state. The application supplies the storage and reboot work through callbacks.

Runtime DFU exposes a smaller service while the normal application is running. A host can request detach, which lets the application reboot into DFU mode. This separates the request to enter update mode from the later block transfer and manifest process.

The update flow is stateful and keeps each block valid until the class reports its next status:

flowchart TD
    A[Host selects DFU target] --> B[Download or upload block]
    B --> C[Host polls status]
    C -->|More work| B
    C -->|Download complete| D[Manifest firmware]
    D --> E[Idle or wait for reset]
    C -->|Failure| F[DFU error and recovery]
    G[Running application] --> H[Runtime detach request]
    H --> I[Application reboots to DFU mode]

References: src/…/dfu_device.c• L161-199 src/…/dfu_device.c• L202-427 src/…/dfu_rt_device.c• L47-118

MIDI 2.0 discovery and data

MIDI 2.0 support has a mode-selection path before its normal data path. A host identifies the MIDI 2.0 alternate setting and selects it when available. The host then exposes UMP words and the device describes its Group Terminal Blocks and optional Function Block identity. MIDI 1.0 event packets remain available through the MIDI 1.0 mode.

After setup, applications exchange complete UMP messages or MIDI 1.0 packets through the class API:

sequenceDiagram
    participant Host
    participant Class as MIDI class
    participant App as Application
    Host->>Class: Detect streaming modes
    Host->>Class: Select MIDI 2.0 alternate setting
    Class-->>Host: Report active mode and groups
    Host->>Class: Exchange UMP or event packets
    Class->>App: Deliver received data
    App-->>Class: Queue outgoing data

If alternate-setting activation fails, the host restores the MIDI 1.0 endpoint view and reports that mode instead of exposing a partly active MIDI 2.0 function. On the device side, discovery replies can be handled by the application or by the class responder.

References: src/…/midi2_host.c• L678-786 src/…/midi2_host.c• L803-885 src/…/midi2_device.c• L582-663 src/…/midi2_device.c• L668-769

Configuration scope

Class support is selected separately for the device and host roles. Device options use CFG_TUD_* names. Host options use CFG_TUH_* names. A protocol can therefore be enabled for one role without enabling it for the other.

The selected class set also shapes the resources needed by the stack. Interface counts, endpoint counts, buffers, connected-device limits, and protocol-specific transfer limits must fit the target board. NCM buffer counts and datagram limits trade memory for packet throughput. Vendor alternate-setting support requires a compatible transfer mode and endpoint buffers. Network mode selection remains exclusive: ECM/RNDIS and NCM cannot be enabled together.

References: src/…/audio_host.h• L22-69 src/…/net_device.h• L17-29 src/…/ncm.h• L14-59 src/…/cdc_host.c• L63-92 src/…/vendor_device.h• L36-123 src/…/midi2_device.c• L140-145

Serial and human-interface classes

The serial and human-interface page covers CDC serial links, HID reports, and MIDI data. Start there when the application needs a byte stream, user input, or musical data.

References: src/…/cdc_host.h• L45-175 src/…/hid_host.c• L153-178 src/…/midi_host.c• L317-435

Media and connectivity classes

The media and connectivity page covers audio, video, storage, and network links. Start there when the application needs timed media, block storage, or packet transport.

References: src/…/audio_host.h• L139-207 src/…/audio_device.c• L421-559 src/…/video_device.c• L1219-1324 src/…/msc_host.h• L46-120 src/…/net_device.h• L63-114

Specialized peripheral classes

The specialized peripheral page covers firmware update, printing, Bluetooth controller transport, test and measurement, vendor transport, image transfer, and MIDI 2.0. Start there when the function has a focused control or transfer model.

References: src/…/dfu_device.c• L202-427 src/…/printer_device.c• L230-317 src/…/bth_device.c• L224-282 src/…/vendor_device.c• L891-988 src/…/midi2_host.c• L678-786

Change checklist

When these files or sections are changed, remember to consider these:

  • Update both the device and host role descriptions when a protocol gains or loses support in one role.
  • Keep interface grouping, endpoint ownership, alternate settings, and class matching aligned with the descriptors.
  • Keep mount and unmount events separate from descriptor discovery and intermediate setup.
  • Keep application callbacks aligned with the class data model: reports, serial bytes, blocks, packets, media samples, frames, HCI data, printer bytes, or UMP messages.
  • Keep supported vendor serial identification and control behavior aligned with the common CDC stream and line-control API.
  • Keep audio alternate-setting changes aligned with endpoint activation, FIFO state, feedback, and stream callbacks.
  • Keep audio host format lists, sample-rate control, packet limits, and asynchronous start or stop events aligned.
  • Keep video probe and commit values aligned with frame format, payload size, endpoint settings, and frame ownership callbacks.
  • Keep DFU alternate settings, transfer size, block lifetime, status polling, manifest completion, and runtime detach behavior aligned.
  • Keep host MSC capacity, logical-unit limits, command fencing, and reset recovery aligned with the storage API.
  • Keep MSC transfer validation, sense status, asynchronous I/O ownership, and reset handling aligned with storage callbacks.
  • Keep HID report failure recovery aligned with polling lifetime and stall recovery.
  • Keep HID boot protocol matching limited to the defined keyboard and mouse values.
  • Keep network framing, data-interface activation, packet ownership, link notifications, and NTB limits aligned across ECM, RNDIS, and NCM.
  • Keep NCM validation, buffer holds, release calls, and buffering limits aligned with the packet API.
  • Keep printer control requests aligned with device ID lifetime, port status, soft reset, and stream completion callbacks.
  • Keep Bluetooth HCI and ACL buffer ownership aligned with the matching send callbacks and endpoint packet rules.
  • Keep vendor alternate-setting transitions aligned with endpoint activation, stale-transfer aborts, mounted state, and manual re-arm callbacks.
  • Keep MIDI 1.0 and MIDI 2.0 alternate-setting selection aligned with the reported packet or UMP API.
  • Keep MIDI 2.0 group counts, mount data, packet boundaries, discovery replies, and fallback behavior aligned.
  • Keep role-specific configuration limits aligned with the buffers and interface counts used by the class API.

Important failure modes

TriggerConsequenceGuard
A class is not enabled for the active roleThe interface is not claimed or the local function is not exposedEnable the matching device or host class option and provide matching descriptors
Interface or endpoint descriptors do not match the class functionThe class cannot open or can claim only part of a composite functionKeep interface groups, endpoints, and alternate settings consistent
Application I/O starts before mount, ready, or active-interface stateTransfers fail or data endpoints remain inactiveGate I/O on the class readiness event and protocol state
Application I/O continues after unmountWork uses invalid class state after disconnectStop class work at unmount and wait for a new mount
Audio configuration needs packets larger than its endpoint or buffersThe stream configuration is rejectedKeep sample format, rate, channel count, endpoint size, and buffers consistent
Audio start or stop is treated as complete before its eventThe application reads or writes before the stream is active or after it has stoppedWait for the matching audio event callback
Video frame storage is reused before completion or abortA later frame can overwrite data still in transitReuse a submitted frame buffer only after the matching callback
HID boot handling accepts a reserved protocol valueA generic report interface can be treated as a boot keyboard or mouseTreat only the defined keyboard and mouse values as boot protocols
HID report polling is not re-armed after a retryable failureInput reports stopRe-arm retryable failures and handle stalled or aborted transfers separately
MSC readiness or capacity discovery failsThe host does not report storage as mountedWait for mount and handle readiness, sense, and capacity results
An MSC command stage fails or returns a phase errorLater commands are refused until reset recovery or re-enumerationTreat the completion status as a fence and run reset recovery
A storage reset abandons asynchronous work but the application reuses its bufferA later command can overwrite data still owned by storage workKeep the buffer until the asynchronous completion boundary
DFU receives a block larger than its configured transfer bufferThe update cannot advanceMake the transfer buffer at least as large as the descriptor transfer size
Runtime DFU detach is accepted without a reboot actionThe host requests update mode but the device stays in the applicationConnect the detach callback to the platform boot transition
NCM receives an invalid transfer block or datagram rangePackets are discardedValidate NTB bounds, NDP entries, and configured buffer sizes
An NCM receive buffer is released too early or never releasedThe network layer reads invalid data or receive buffers run outHold the buffer through packet use and release it once
RNDIS receives an invalid packet offset or lengthThe network callback receives no valid payloadValidate the packet window against the received transfer length
Network traffic starts before the data interface becomes activeUSB data endpoints are inactiveWait for the required data alternate setting
ECM/RNDIS and NCM are enabled togetherThe network configuration is rejectedSelect one supported network mode
A printer device ID buffer is changed before the control transfer completesThe host receives an invalid device IDKeep the returned device ID valid through the request completion callback
Bluetooth event or ACL data is reused before its send callbackThe controller sends corrupted or stale dataRelease or reuse the buffer only after completion
A vendor interrupt or isochronous OUT transfer is not re-armedNew data is not receivedRe-arm the endpoint from the application callback or polling path
A vendor alternate setting changes while old transfers remain activeStale completions can use the wrong endpoint stateAbort old endpoint work and use only the selected setting
MIDI 2.0 alternate-setting selection or UMP packet boundaries are incompleteThe host falls back to MIDI 1.0 or cannot exchange valid UMP dataKeep descriptors, alternate settings, group counts, and whole-message rules consistent

Key files

FileWhy to read it
src/…/cdc_host.cShows how standard and supported vendor serial interfaces become one mounted host stream.
src/…/cdc_device.cShows the device-side serial stream and line-control boundary.
src/…/hid_host.cShows how a host HID interface becomes mounted and how report polling follows its lifetime.
src/…/audio_host.cShows how host audio interfaces become selectable capture and playback streams.
src/…/audio_device.cShows how device audio streaming maps samples to the active interface state.
src/…/video_device.cShows how video settings are negotiated and how accepted frames move through USB payload transfers.
src/…/msc_host.cShows how storage readiness, capacity discovery, command fencing, and reset recovery protect mounted storage use.
src/…/msc_device.cShows how device storage validates command phases and maps them to application callbacks.
src/…/ecm_rndis_device.cShows how ECM and RNDIS map management state and USB framing to network packets.
src/…/ncm.hDefines the NCM transfer limits and packet-grouping model.
src/…/ncm_device.cShows how NCM validates NTBs and manages packet buffer ownership.
src/…/printer_device.cShows how a printer function exposes byte streams and printer control requests.
src/…/bth_device.cShows how a Bluetooth controller function exposes HCI and ACL data.
src/…/vendor_device.cShows how vendor-specific endpoints, buffering, and alternate settings become an application transport.
src/…/dfu_device.cShows how DFU download, upload, status polling, manifest, and error states form a firmware update service.
src/…/midi_host.cShows how a host MIDI 1.0 interface becomes mounted and exposes packet or stream access.
src/…/midi2_host.cShows how a host selects MIDI 2.0 mode and falls back to MIDI 1.0 when needed.
src/…/midi2_device.cShows how MIDI 2.0 discovery, protocol selection, and UMP or packet APIs form one device capability.