initial commit

This commit is contained in:
shell committed 2026-10-11 21:48:59 +08:00
commit b44ce7bd77
2716 files changed
+559005

No files matched your search

@@ -0,0 +1,30 @@
cmake_minimum_required(VERSION 3.20)
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake)
project(uac2_speaker_fb C CXX ASM)
# Checks this example is valid for the family and initializes the project
family_initialize_project(${PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR})
# Espressif has its own cmake build system
if(FAMILY STREQUAL "espressif")
return()
endif()
add_executable(${PROJECT_NAME})
# Example source
target_sources(${PROJECT_NAME} PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/src/main.c
${CMAKE_CURRENT_SOURCE_DIR}/src/usb_descriptors.c
)
# Example include
target_include_directories(${PROJECT_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(${PROJECT_NAME} noos)
@@ -0,0 +1,6 @@
{
"version": 6,
"include": [
"../../../hw/bsp/BoardPresets.json"
]
}
@@ -0,0 +1,11 @@
include ../../../hw/bsp/family_support.mk
INC += \
src \
# Example source
EXAMPLE_SOURCE += $(wildcard src/*.c)
SRC_C += $(addprefix $(EXAMPLE_PATH)/, $(EXAMPLE_SOURCE))
include ../../../hw/bsp/family_rules.mk
@@ -0,0 +1,57 @@
# USB Speaker with Feedback
A stereo USB speaker (output only) that uses an explicit isochronous feedback endpoint to keep the host's sample rate in sync, adapting its descriptors to the negotiated bus speed — UAC1 at Full-Speed and UAC2 at High-Speed.
## What it does
- Enumerates as a stereo speaker (host → device), 16-bit. The configuration returned depends on link speed: a UAC1 configuration at Full-Speed and a UAC2 configuration at High-Speed, with a device-qualifier and other-speed-configuration descriptor so it works at either speed.
- Declares an explicit asynchronous feedback endpoint and reports rate via the FIFO-count feedback method (`tud_audio_feedback_params_cb`), letting the host adjust how many samples it sends so the device buffer neither under- nor over-runs.
- The audio task drains the speaker FIFO every 1 ms into a dummy buffer (the data is discarded), reading roughly one millisecond of audio per cycle with a small periodic adjustment for the 44.1 kHz and 88.2 kHz rates.
- Supports 44.1 kHz and 48 kHz at Full-Speed, plus 88.2 kHz and 96 kHz at High-Speed (UAC2). Handles UAC1 and UAC2 control requests (mute, volume, sample frequency).
- When `CFG_AUDIO_DEBUG` is enabled (default), adds a HID interface that reports debug telemetry — current sample rate, alternate setting, mute/volume, and FIFO size/count/average — every 1 ms.
- Blinks the on-board LED to indicate USB state, with a fast pattern while streaming.
## USB Descriptors
| Interface | Class driver |
|-----------|--------------|
| 0–1 | UAC2 audio (control + streaming), stereo speaker output with feedback endpoint |
| 2 | HID (vendor report) — audio debug telemetry, present only when `CFG_AUDIO_DEBUG` is enabled |
(UAC1 at Full-Speed, UAC2 at High-Speed.)
## Configuration
Notable `tusb_config.h` settings:
```c
#define CFG_TUD_AUDIO 1
#define CFG_AUDIO_DEBUG 1 // adds HID debug interface
#define CFG_TUD_HID 1 // present when CFG_AUDIO_DEBUG
#define CFG_TUD_AUDIO_ENABLE_EP_OUT 1 // speaker
#define CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP 1
#define CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_RX 2 // stereo
#define CFG_TUD_AUDIO_FUNC_1_RESOLUTION_RX 16 // 16-bit
#define CFG_TUD_AUDIO_FUNC_1_MAX_SAMPLE_RATE_FS 48000
#define CFG_TUD_AUDIO_FUNC_1_MAX_SAMPLE_RATE_HS 96000
```
## Building
CMake:
```bash
mkdir build && cd build
cmake -DBOARD=raspberry_pi_pico ..
cmake --build .
```
Make:
```bash
make BOARD=raspberry_pi_pico all
```
## Try it
The device appears as a stereo USB speaker; select it as the system output or play to it with `aplay`/`speaker-test` (the audio is consumed and discarded). The feedback endpoint keeps the host's send rate matched to the device. With `CFG_AUDIO_DEBUG` enabled, `src/audio_debug.py` reads the HID telemetry stream and plots the FIFO level and sample rate.
@@ -0,0 +1,9 @@
mcu:LPC11UXX
mcu:LPC13XX
mcu:NUC121
mcu:SAMD11
mcu:SAME5X
mcu:SAMG
board:stm32l052dap52
family:broadcom_64bit
mcu:CH583
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
# Install python3 HID package https://pypi.org/project/hid/
# Install python3 matplotlib package https://pypi.org/project/matplotlib/
from ctypes import Structure, c_uint32, c_uint8, c_int8, c_int16, c_uint16
import signal
try:
import hid
import matplotlib.pyplot as plt
import matplotlib.animation as animation
except:
print("Missing import, please try 'pip install hid matplotlib' or consult your OS's python package manager.")
exit(1)
# Example must be compiled with CFG_AUDIO_DEBUG=1
VID = 0xcafe
PID = 0x4014
CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_RX = 2
class audio_debug_info_t (Structure):
_fields_ = [("sample_rate", c_uint32),
("alt_settings", c_uint8),
("mute", (CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_RX + 1) * c_int8),
("volume", (CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_RX + 1) * c_int16),
("fifo_size", c_uint16),
("fifo_count", c_uint16),
("fifo_count_avg", c_uint16)
]
dev = hid.Device(VID, PID)
if dev:
signal.signal(signal.SIGINT, signal.SIG_DFL)
# Create figure for plotting
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
fifo_avg = []
fifo_cnt = []
# This function is called periodically from FuncAnimation
def animate(i):
info = None
for i in range(30):
try:
str_in = dev.read(64, 50)
info = audio_debug_info_t.from_buffer_copy(str_in)
global fifo_avg
global fifo_cnt
fifo_avg.append(info.fifo_count_avg)
fifo_cnt.append(info.fifo_count)
except:
exit(1)
# Limit to 1000 items
fifo_avg = fifo_avg[-1000:]
fifo_cnt = fifo_cnt[-1000:]
if info is not None:
# Draw x and y lists
ax.clear()
ax.plot(fifo_cnt, label='FIFO count')
ax.plot(fifo_avg, label='FIFO average')
ax.legend()
ax.set_ylim(bottom=0, top=info.fifo_size)
# Format plot
ax.set_title('FIFO information')
ax.grid(True)
print(f'Sample rate:{info.sample_rate} | Alt settings:{info.alt_settings} | Volume:{info.volume[:]}')
ani = animation.FuncAnimation(fig, animate, interval=10, cache_frame_data=False) # type: ignore
plt.show(block=True)
@@ -0,0 +1,52 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2023 HiFiPhile
*
* 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 _COMMON_TYPES_H_
#define _COMMON_TYPES_H_
enum
{
ITF_NUM_AUDIO_CONTROL = 0,
ITF_NUM_AUDIO_STREAMING,
#if CFG_AUDIO_DEBUG
ITF_NUM_DEBUG,
#endif
ITF_NUM_TOTAL
};
#if CFG_AUDIO_DEBUG
typedef struct
{
uint32_t sample_rate;
uint8_t alt_settings;
uint8_t mute[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_RX + 1];
int16_t volume[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_RX + 1];
uint16_t fifo_size;
uint16_t fifo_count;
uint16_t fifo_count_avg;
} audio_debug_info_t;
#endif
#endif
@@ -0,0 +1,676 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Jerzy Kasenberg
*
* 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 <stdio.h>
#include <string.h>
#include "bsp/board_api.h"
#include "common_types.h"
#include "tusb.h"
#include "usb_descriptors.h"
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF PROTOTYPES
//--------------------------------------------------------------------+
/* Blink pattern
* - 25 ms : streaming data
* - 250 ms : device not mounted
* - 1000 ms : device mounted
* - 2500 ms : device is suspended
*/
enum {
BLINK_STREAMING = 25,
BLINK_NOT_MOUNTED = 250,
BLINK_MOUNTED = 1000,
BLINK_SUSPENDED = 2500,
};
enum {
VOLUME_CTRL_0_DB = 0,
VOLUME_CTRL_10_DB = 2560,
VOLUME_CTRL_20_DB = 5120,
VOLUME_CTRL_30_DB = 7680,
VOLUME_CTRL_40_DB = 10240,
VOLUME_CTRL_50_DB = 12800,
VOLUME_CTRL_60_DB = 15360,
VOLUME_CTRL_70_DB = 17920,
VOLUME_CTRL_80_DB = 20480,
VOLUME_CTRL_90_DB = 23040,
VOLUME_CTRL_100_DB = 25600,
VOLUME_CTRL_SILENCE = 0x8000,
};
static uint32_t blink_interval_ms = BLINK_NOT_MOUNTED;
// Audio controls
// Current states
uint8_t mute[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_RX + 1]; // +1 for master channel 0
int16_t volume[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_RX + 1];// +1 for master channel 0
uint32_t current_sample_rate = 44100;
// Buffer for speaker data
uint16_t i2s_dummy_buffer[CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ / 2];
void led_blinking_task(void);
void audio_task(void);
#if CFG_AUDIO_DEBUG
void audio_debug_task(void);
uint8_t current_alt_settings;
volatile uint16_t fifo_count;
volatile uint32_t fifo_count_avg;
#endif
/*------------- 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();
TU_LOG1("Speaker running\r\n");
while (1) {
tud_task();// TinyUSB device task
led_blinking_task();
#if CFG_AUDIO_DEBUG
audio_debug_task();
#endif
audio_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;
}
//--------------------------------------------------------------------+
// Application Callback API Implementations
//--------------------------------------------------------------------+
//--------------------------------------------------------------------+
// UAC1 Helper Functions
//--------------------------------------------------------------------+
static bool audio10_set_req_ep(tusb_control_request_t const *p_request, uint8_t *pBuff) {
uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue);
switch (ctrlSel) {
case AUDIO10_EP_CTRL_SAMPLING_FREQ:
if (p_request->bRequest == AUDIO10_CS_REQ_SET_CUR) {
// Request uses 3 bytes
TU_VERIFY(p_request->wLength == 3);
current_sample_rate = tu_unaligned_read32(pBuff) & 0x00FFFFFF;
TU_LOG2("EP set current freq: %" PRIu32 "\r\n", current_sample_rate);
return true;
}
break;
// Unknown/Unsupported control
default:
TU_BREAKPOINT();
return false;
}
return false;
}
static bool audio10_get_req_ep(uint8_t rhport, tusb_control_request_t const *p_request) {
uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue);
switch (ctrlSel) {
case AUDIO10_EP_CTRL_SAMPLING_FREQ:
if (p_request->bRequest == AUDIO10_CS_REQ_GET_CUR) {
TU_LOG2("EP get current freq\r\n");
uint8_t freq[3];
freq[0] = (uint8_t) (current_sample_rate & 0xFF);
freq[1] = (uint8_t) ((current_sample_rate >> 8) & 0xFF);
freq[2] = (uint8_t) ((current_sample_rate >> 16) & 0xFF);
return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, freq, sizeof(freq));
}
break;
// Unknown/Unsupported control
default:
TU_BREAKPOINT();
return false;
}
return false;
}
static bool audio10_set_req_entity(tusb_control_request_t const *p_request, uint8_t *pBuff) {
uint8_t channelNum = TU_U16_LOW(p_request->wValue);
uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue);
uint8_t entityID = TU_U16_HIGH(p_request->wIndex);
// If request is for our feature unit
if (entityID == UAC1_ENTITY_FEATURE_UNIT) {
switch (ctrlSel) {
case AUDIO10_FU_CTRL_MUTE:
switch (p_request->bRequest) {
case AUDIO10_CS_REQ_SET_CUR:
// Only 1st form is supported
TU_VERIFY(p_request->wLength == 1);
mute[channelNum] = pBuff[0];
TU_LOG2(" Set Mute: %d of channel: %u\r\n", mute[channelNum], channelNum);
return true;
default:
return false; // not supported
}
case AUDIO10_FU_CTRL_VOLUME:
switch (p_request->bRequest) {
case AUDIO10_CS_REQ_SET_CUR:
// Only 1st form is supported
TU_VERIFY(p_request->wLength == 2);
volume[channelNum] = (int16_t)tu_unaligned_read16(pBuff) / 256;
TU_LOG2(" Set Volume: %d dB of channel: %u\r\n", volume[channelNum], channelNum);
return true;
default:
return false; // not supported
}
// Unknown/Unsupported control
default:
TU_BREAKPOINT();
return false;
}
}
return false;
}
static bool audio10_get_req_entity(uint8_t rhport, tusb_control_request_t const *p_request) {
uint8_t channelNum = TU_U16_LOW(p_request->wValue);
uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue);
uint8_t entityID = TU_U16_HIGH(p_request->wIndex);
// If request is for our feature unit
if (entityID == UAC1_ENTITY_FEATURE_UNIT) {
switch (ctrlSel) {
case AUDIO10_FU_CTRL_MUTE:
// Audio control mute cur parameter block consists of only one byte - we thus can send it right away
// There does not exist a range parameter block for mute
TU_LOG2(" Get Mute of channel: %u\r\n", channelNum);
return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &mute[channelNum], 1);
case AUDIO10_FU_CTRL_VOLUME:
switch (p_request->bRequest) {
case AUDIO10_CS_REQ_GET_CUR:
TU_LOG2(" Get Volume of channel: %u\r\n", channelNum);
{
int16_t vol = (int16_t) volume[channelNum];
vol = vol * 256; // convert to 1/256 dB units
return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &vol, sizeof(vol));
}
case AUDIO10_CS_REQ_GET_MIN:
TU_LOG2(" Get Volume min of channel: %u\r\n", channelNum);
{
int16_t min = -90; // -90 dB
min = min * 256; // convert to 1/256 dB units
return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &min, sizeof(min));
}
case AUDIO10_CS_REQ_GET_MAX:
TU_LOG2(" Get Volume max of channel: %u\r\n", channelNum);
{
int16_t max = 30; // +30 dB
max = max * 256; // convert to 1/256 dB units
return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &max, sizeof(max));
}
case AUDIO10_CS_REQ_GET_RES:
TU_LOG2(" Get Volume res of channel: %u\r\n", channelNum);
{
int16_t res = 128; // 0.5 dB
return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &res, sizeof(res));
}
// Unknown/Unsupported control
default:
TU_BREAKPOINT();
return false;
}
break;
// Unknown/Unsupported control
default:
TU_BREAKPOINT();
return false;
}
}
return false;
}
//--------------------------------------------------------------------+
// UAC2 Helper Functions
//--------------------------------------------------------------------+
#if TUD_OPT_HIGH_SPEED
// List of supported sample rates for UAC2
const uint32_t sample_rates[] = {44100, 48000, 88200, 96000};
#define N_SAMPLE_RATES TU_ARRAY_SIZE(sample_rates)
static bool audio20_clock_get_request(uint8_t rhport, tusb_control_request_t const *p_request) {
uint8_t const ctrl_sel = TU_U16_HIGH(p_request->wValue);
if (ctrl_sel == AUDIO20_CS_CTRL_SAM_FREQ) {
if (p_request->bRequest == AUDIO20_CS_REQ_CUR) {
TU_LOG1("Clock get current freq %" PRIu32 "\r\n", current_sample_rate);
audio20_control_cur_4_t curf = {(int32_t) tu_htole32(current_sample_rate)};
return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &curf, sizeof(curf));
} else if (p_request->bRequest == AUDIO20_CS_REQ_RANGE) {
audio20_control_range_4_n_t(N_SAMPLE_RATES) rangef =
{
.wNumSubRanges = tu_htole16(N_SAMPLE_RATES)};
TU_LOG1("Clock get %d freq ranges\r\n", N_SAMPLE_RATES);
for (uint8_t i = 0; i < N_SAMPLE_RATES; i++) {
rangef.subrange[i].bMin = (int32_t) sample_rates[i];
rangef.subrange[i].bMax = (int32_t) sample_rates[i];
rangef.subrange[i].bRes = 0;
TU_LOG1("Range %d (%d, %d, %d)\r\n", i, (int) rangef.subrange[i].bMin, (int) rangef.subrange[i].bMax, (int) rangef.subrange[i].bRes);
}
return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &rangef, sizeof(rangef));
}
} else if (ctrl_sel == AUDIO20_CS_CTRL_CLK_VALID &&
p_request->bRequest == AUDIO20_CS_REQ_CUR) {
audio20_control_cur_1_t cur_valid = {.bCur = 1};
TU_LOG1("Clock get is valid %u\r\n", cur_valid.bCur);
return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &cur_valid, sizeof(cur_valid));
}
TU_LOG1("Clock get request not supported, selector = %u, request = %u\r\n",
ctrl_sel, p_request->bRequest);
return false;
}
static bool audio20_clock_set_request(tusb_control_request_t const *p_request, uint8_t const *buf) {
uint8_t const ctrl_sel = TU_U16_HIGH(p_request->wValue);
TU_VERIFY(p_request->bRequest == AUDIO20_CS_REQ_CUR);
if (ctrl_sel == AUDIO20_CS_CTRL_SAM_FREQ) {
TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_4_t));
current_sample_rate = (uint32_t) ((audio20_control_cur_4_t const *) buf)->bCur;
TU_LOG1("Clock set current freq: %" PRIu32 "\r\n", current_sample_rate);
return true;
} else {
TU_LOG1("Clock set request not supported, selector = %u, request = %u\r\n",
ctrl_sel, p_request->bRequest);
return false;
}
}
static bool audio20_feature_unit_get_request(uint8_t rhport, tusb_control_request_t const *p_request) {
uint8_t const ctrl_sel = TU_U16_HIGH(p_request->wValue);
uint8_t const channel_num = TU_U16_LOW(p_request->wValue);
if (ctrl_sel == AUDIO20_FU_CTRL_MUTE && p_request->bRequest == AUDIO20_CS_REQ_CUR) {
audio20_control_cur_1_t mute1 = {.bCur = mute[channel_num]};
TU_LOG1("Get channel %u mute %d\r\n", channel_num, mute1.bCur);
return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &mute1, sizeof(mute1));
} else if (ctrl_sel == AUDIO20_FU_CTRL_VOLUME) {
if (p_request->bRequest == AUDIO20_CS_REQ_RANGE) {
audio20_control_range_2_n_t(1) range_vol = {
.wNumSubRanges = tu_htole16(1),
.subrange[0] = {.bMin = tu_htole16(-VOLUME_CTRL_50_DB), tu_htole16(VOLUME_CTRL_0_DB), tu_htole16(256)}};
TU_LOG1("Get channel %u volume range (%d, %d, %u) dB\r\n", channel_num,
range_vol.subrange[0].bMin / 256, range_vol.subrange[0].bMax / 256, range_vol.subrange[0].bRes / 256);
return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &range_vol, sizeof(range_vol));
} else if (p_request->bRequest == AUDIO20_CS_REQ_CUR) {
audio20_control_cur_2_t cur_vol = {.bCur = tu_htole16(volume[channel_num])};
TU_LOG1("Get channel %u volume %d dB\r\n", channel_num, cur_vol.bCur / 256);
return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &cur_vol, sizeof(cur_vol));
}
}
TU_LOG1("Feature unit get request not supported, selector = %u, request = %u\r\n",
ctrl_sel, p_request->bRequest);
return false;
}
static bool audio20_feature_unit_set_request(tusb_control_request_t const *p_request, uint8_t const *buf) {
uint8_t const ctrl_sel = TU_U16_HIGH(p_request->wValue);
uint8_t const channel_num = TU_U16_LOW(p_request->wValue);
TU_VERIFY(p_request->bRequest == AUDIO20_CS_REQ_CUR);
if (ctrl_sel == AUDIO20_FU_CTRL_MUTE) {
TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_1_t));
mute[channel_num] = ((audio20_control_cur_1_t const *) buf)->bCur;
TU_LOG1("Set channel %d Mute: %d\r\n", channel_num, mute[channel_num]);
return true;
} else if (ctrl_sel == AUDIO20_FU_CTRL_VOLUME) {
TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_2_t));
volume[channel_num] = ((audio20_control_cur_2_t const *) buf)->bCur;
TU_LOG1("Set channel %d volume: %d dB\r\n", channel_num, volume[channel_num] / 256);
return true;
} else {
TU_LOG1("Feature unit set request not supported, selector = %u, request = %u\r\n",
ctrl_sel, p_request->bRequest);
return false;
}
}
static bool audio20_get_req_entity(uint8_t rhport, tusb_control_request_t const *p_request) {
uint8_t const entity_id = TU_U16_HIGH(p_request->wIndex);
if (entity_id == UAC2_ENTITY_CLOCK)
return audio20_clock_get_request(rhport, p_request);
if (entity_id == UAC2_ENTITY_FEATURE_UNIT)
return audio20_feature_unit_get_request(rhport, p_request);
else {
TU_LOG1("Get request not handled, entity = %d, selector = %d, request = %d\r\n",
entity_id, TU_U16_HIGH(p_request->wValue), p_request->bRequest);
}
return false;
}
static bool audio20_set_req_entity(tusb_control_request_t const *p_request, uint8_t *buf) {
uint8_t const entity_id = TU_U16_HIGH(p_request->wIndex);
if (entity_id == UAC2_ENTITY_FEATURE_UNIT)
return audio20_feature_unit_set_request(p_request, buf);
if (entity_id == UAC2_ENTITY_CLOCK)
return audio20_clock_set_request(p_request, buf);
TU_LOG1("Set request not handled, entity = %d, selector = %d, request = %d\r\n",
entity_id, TU_U16_HIGH(p_request->wValue), p_request->bRequest);
return false;
}
#endif // TUD_OPT_HIGH_SPEED
//--------------------------------------------------------------------+
// Main Callback Functions
//--------------------------------------------------------------------+
bool tud_audio_set_itf_cb(uint8_t rhport, tusb_control_request_t const *p_request) {
(void) rhport;
uint8_t const itf = tu_u16_low(p_request->wIndex);
uint8_t const alt = tu_u16_low(p_request->wValue);
TU_LOG2("Set interface %d alt %d\r\n", itf, alt);
if (ITF_NUM_AUDIO_STREAMING == itf && alt != 0)
blink_interval_ms = BLINK_STREAMING;
#if CFG_AUDIO_DEBUG
current_alt_settings = alt;
#endif
return true;
}
// Invoked when audio class specific set request received for an EP
bool tud_audio_set_req_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff) {
(void) rhport;
(void) pBuff;
if (tud_audio_version() == 1) {
return audio10_set_req_ep(p_request, pBuff);
} else if (tud_audio_version() == 2) {
// We do not support any requests here
}
return false;// Yet not implemented
}
// Invoked when audio class specific get request received for an EP
bool tud_audio_get_req_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request) {
(void) rhport;
if (tud_audio_version() == 1) {
return audio10_get_req_ep(rhport, p_request);
} else if (tud_audio_version() == 2) {
// We do not support any requests here
}
return false;// Yet not implemented
}
// Invoked when audio class specific set request received for an entity
bool tud_audio_set_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *buf) {
(void) rhport;
if (tud_audio_version() == 1) {
return audio10_set_req_entity(p_request, buf);
#if TUD_OPT_HIGH_SPEED
} else if (tud_audio_version() == 2) {
return audio20_set_req_entity(p_request, buf);
#endif
}
return false;
}
// Invoked when audio class specific get request received for an entity
bool tud_audio_get_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p_request) {
(void) rhport;
if (tud_audio_version() == 1) {
return audio10_get_req_entity(rhport, p_request);
#if TUD_OPT_HIGH_SPEED
} else if (tud_audio_version() == 2) {
return audio20_get_req_entity(rhport, p_request);
#endif
}
return false;
}
bool tud_audio_set_itf_close_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request) {
(void) rhport;
uint8_t const itf = tu_u16_low(p_request->wIndex);
uint8_t const alt = tu_u16_low(p_request->wValue);
if (ITF_NUM_AUDIO_STREAMING == itf && alt == 0) {
blink_interval_ms = BLINK_MOUNTED;
}
return true;
}
void tud_audio_feedback_params_cb(uint8_t func_id, uint8_t alt_itf, audio_feedback_params_t *feedback_param) {
(void) func_id;
(void) alt_itf;
// Set feedback method to fifo counting
feedback_param->method = AUDIO_FEEDBACK_METHOD_FIFO_COUNT;
feedback_param->sample_freq = current_sample_rate;
// About FIFO threshold:
//
// By default the threshold is set to half FIFO size, which works well in most cases,
// you can reduce the threshold to have less latency.
//
// For example, here we could set the threshold to 2 ms of audio data, as audio_task() read audio data every 1 ms,
// having 2 ms threshold allows some margin and a quick response:
//
// feedback_param->fifo_count.fifo_threshold =
// current_sample_rate * CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_RX * CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_RX / 1000 * 2;
}
#if CFG_AUDIO_DEBUG
bool tud_audio_rx_done_isr(uint8_t rhport, uint16_t n_bytes_received, uint8_t func_id, uint8_t ep_out, uint8_t cur_alt_setting) {
(void) rhport;
(void) n_bytes_received;
(void) func_id;
(void) ep_out;
(void) cur_alt_setting;
fifo_count = tud_audio_available();
// Same averaging method used in UAC2 class
const uint32_t ff_count32 = (uint32_t) fifo_count << 16;
fifo_count_avg = (uint32_t) (((uint64_t) fifo_count_avg * 63 + ff_count32) >> 6);
return true;
}
#endif
//--------------------------------------------------------------------+
// AUDIO Task
//--------------------------------------------------------------------+
// This task simulates an audio transmit callback, one frame is sent every 1ms.
// In a real application, this would be replaced with actual I2S transmit callback.
void audio_task(void) {
static uint32_t start_ms = 0;
uint32_t curr_ms = tusb_time_millis_api();
if (start_ms == curr_ms) return;// not enough time
start_ms = curr_ms;
uint16_t length = (uint16_t) (current_sample_rate / 1000 * CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_RX * CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_RX);
if (current_sample_rate == 44100 && (curr_ms % 10 == 0)) {
// Take one more sample every 10 cycles, to have a average reading speed of 44.1
// This correction is not needed in real world cases
length += CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_RX * CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_RX;
} else if (current_sample_rate == 88200 && (curr_ms % 5 == 0)) {
// Take one more sample every 5 cycles, to have a average reading speed of 88.2
// This correction is not needed in real world cases
length += CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_RX * CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_RX;
}
tud_audio_read(i2s_dummy_buffer, length);
}
//--------------------------------------------------------------------+
// BLINKING TASK
//--------------------------------------------------------------------+
void led_blinking_task(void) {
static uint32_t start_ms = 0;
static bool led_state = false;
// Blink every interval ms
if (tusb_time_millis_api() - start_ms < blink_interval_ms) return;
start_ms += blink_interval_ms;
board_led_write(led_state);
led_state = 1 - led_state;
}
#if CFG_AUDIO_DEBUG
//--------------------------------------------------------------------+
// HID interface for audio debug
//--------------------------------------------------------------------+
// Every 1ms, we will sent 1 debug information report
void audio_debug_task(void) {
static uint32_t start_ms = 0;
uint32_t curr_ms = tusb_time_millis_api();
if (start_ms == curr_ms) return;// not enough time
start_ms = curr_ms;
audio_debug_info_t debug_info;
debug_info.sample_rate = current_sample_rate;
debug_info.alt_settings = current_alt_settings;
debug_info.fifo_size = CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ;
debug_info.fifo_count = fifo_count;
debug_info.fifo_count_avg = (uint16_t) (fifo_count_avg >> 16);
for (int i = 0; i < CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_RX + 1; i++) {
debug_info.mute[i] = mute[i];
debug_info.volume[i] = volume[i];
}
if (tud_hid_ready())
tud_hid_report(0, &debug_info, sizeof(debug_info));
}
// Invoked when received GET_REPORT control request
// Unused here
uint16_t tud_hid_get_report_cb(uint8_t itf, uint8_t report_id, hid_report_type_t report_type, uint8_t *buffer, uint16_t reqlen) {
// TODO not Implemented
(void) itf;
(void) report_id;
(void) report_type;
(void) buffer;
(void) reqlen;
return 0;
}
// Invoked when received SET_REPORT control request or
// Unused here
void tud_hid_set_report_cb(uint8_t itf, uint8_t report_id, hid_report_type_t report_type, uint8_t const *buffer, uint16_t bufsize) {
// This example doesn't use multiple report and report ID
(void) itf;
(void) report_id;
(void) report_type;
(void) buffer;
(void) bufsize;
}
#endif
@@ -0,0 +1,152 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Ha Thach (tinyusb.org)
* Copyright (c) 2020 Jerzy Kasenberg
*
* 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
#include "usb_descriptors.h"
//--------------------------------------------------------------------+
// 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
// It's recommended to disable debug unless for control requests debugging,
// as the extra time needed will impact data stream !
#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
//--------------------------------------------------------------------
// Expose audio class debug information via HID interface
#ifndef CFG_AUDIO_DEBUG
#define CFG_AUDIO_DEBUG 1
#endif
#ifndef CFG_TUD_ENDPOINT0_SIZE
#define CFG_TUD_ENDPOINT0_SIZE 64
#endif
#define CFG_TUD_HID_EP_BUFSIZE 64
//------------- CLASS -------------//
#define CFG_TUD_AUDIO 1
#if CFG_AUDIO_DEBUG
#define CFG_TUD_HID 1
#else
#define CFG_TUD_HID 0
#endif
#define CFG_TUD_CDC 0
#define CFG_TUD_MSC 0
#define CFG_TUD_MIDI 0
#define CFG_TUD_VENDOR 0
//--------------------------------------------------------------------
// AUDIO CLASS DRIVER CONFIGURATION
//--------------------------------------------------------------------
#define CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_RX 2
// 16bit data in 16bit slots
#define CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_RX 2
#define CFG_TUD_AUDIO_FUNC_1_RESOLUTION_RX 16
// UAC1 Full-Speed endpoint size
#define CFG_TUD_AUDIO_FUNC_1_MAX_SAMPLE_RATE_FS 48000
#define CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_FS TUD_AUDIO_EP_SIZE(false, CFG_TUD_AUDIO_FUNC_1_MAX_SAMPLE_RATE_FS, CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_RX, CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_RX)
// UAC2 High-Speed endpoint size
#define CFG_TUD_AUDIO_FUNC_1_MAX_SAMPLE_RATE_HS 96000
#define CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_HS TUD_AUDIO_EP_SIZE(true, CFG_TUD_AUDIO_FUNC_1_MAX_SAMPLE_RATE_HS, CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_RX, CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_RX)
#define CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_MAX TU_MAX(CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_FS, CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_HS)
// AUDIO_FEEDBACK_METHOD_FIFO_COUNT needs buffer size >= 4* EP size to work correctly
// Example read FIFO every 1ms (8 HS frames), so buffer size should be 8 times larger for HS device
#define CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ TU_MAX(4 * CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_FS, 32 * CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_HS)
// Enable OUT EP
#define CFG_TUD_AUDIO_ENABLE_EP_OUT 1
// Enable feedback EP
#define CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP 1
#ifdef __cplusplus
}
#endif
#endif /* TUSB_CONFIG_H_ */
@@ -0,0 +1,299 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2023 HiFiPhile
*
* 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 "usb_descriptors.h"
#include "common_types.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] AUDIO | MIDI | HID | MSC | CDC [LSB]
*/
#define PID_MAP(itf, n) ((CFG_TUD_##itf) ? (1 << (n)) : 0)
#define USB_PID (0x4000 | PID_MAP(CDC, 0) | PID_MAP(MSC, 1) | PID_MAP(HID, 2) | \
PID_MAP(MIDI, 3) | PID_MAP(AUDIO, 4) | PID_MAP(VENDOR, 5) )
//--------------------------------------------------------------------+
// Device Descriptors
//--------------------------------------------------------------------+
static tusb_desc_device_t const desc_device =
{
.bLength = sizeof(tusb_desc_device_t),
.bDescriptorType = TUSB_DESC_DEVICE,
.bcdUSB = 0x0200,
// Use Interface Association Descriptor (IAD) for Audio
// As required by USB Specs IAD's subclass must be common class (2) and protocol must be IAD (1)
.bDeviceClass = TUSB_CLASS_MISC,
.bDeviceSubClass = MISC_SUBCLASS_COMMON,
.bDeviceProtocol = MISC_PROTOCOL_IAD,
.bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE,
.idVendor = 0xCafe,
.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;
}
#if CFG_AUDIO_DEBUG
//--------------------------------------------------------------------+
// HID Report Descriptor
//--------------------------------------------------------------------+
uint8_t const desc_hid_report[] = {
HID_USAGE_PAGE_N ( HID_USAGE_PAGE_VENDOR, 2 ),\
HID_USAGE ( 0x01 ),\
HID_COLLECTION ( HID_COLLECTION_APPLICATION ),\
HID_USAGE ( 0x02 ),\
HID_LOGICAL_MIN ( 0x00 ),\
HID_LOGICAL_MAX_N ( 0xff, 2 ),\
HID_REPORT_SIZE ( 8 ),\
HID_REPORT_COUNT( sizeof(audio_debug_info_t) ),\
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\
HID_COLLECTION_END
};
// Invoked when received GET HID REPORT DESCRIPTOR
// Application return pointer to descriptor
// Descriptor contents must exist long enough for transfer to complete
uint8_t const * tud_hid_descriptor_report_cb(uint8_t itf) {
(void) itf;
return desc_hid_report;
}
#endif
//--------------------------------------------------------------------+
// Configuration Descriptor
//--------------------------------------------------------------------+
#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 etc ...
#define EPNUM_AUDIO 0x03
#define EPNUM_AUDIO_FB 0x03
#define EPNUM_DEBUG 0x04
#elif TU_CHECK_MCU(OPT_MCU_NRF5X)
// nRF5x ISO can only be endpoint 8
#define EPNUM_AUDIO 0x08
#define EPNUM_AUDIO_FB 0x08
#define EPNUM_DEBUG 0x01
#elif CFG_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
#if TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
// Put audio iso on EP10/11 so the 4096-byte FIFOs can back double packet buffering
#define EPNUM_AUDIO 0x0A
#define EPNUM_AUDIO_FB 0x0B
#define EPNUM_DEBUG 0x01
#else
#define EPNUM_AUDIO 0x02
#define EPNUM_AUDIO_FB 0x01
#define EPNUM_DEBUG 0x03
#endif
#else
#define EPNUM_AUDIO 0x01
#define EPNUM_AUDIO_FB 0x01
#define EPNUM_DEBUG 0x02
#endif
#if CFG_AUDIO_DEBUG
#define CONFIG_UAC1_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_AUDIO10_SPEAKER_STEREO_FB_DESC_LEN(2) + TUD_HID_DESC_LEN)
#else
#define CONFIG_UAC1_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_AUDIO10_SPEAKER_STEREO_FB_DESC_LEN(2))
#endif
uint8_t const desc_uac1_configuration[] = {
// Config number, interface count, string index, total length, attribute, power in mA
TUD_CONFIG_DESCRIPTOR(1, ITF_NUM_TOTAL, 0, CONFIG_UAC1_TOTAL_LEN, 0x00, 100),
// Interface number, string index, byte per sample, bit per sample, EP Out, EP size, EP feedback, sample rates (44.1kHz, 48kHz)
TUD_AUDIO10_SPEAKER_STEREO_FB_DESCRIPTOR(ITF_NUM_AUDIO_CONTROL, 5, CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_RX, CFG_TUD_AUDIO_FUNC_1_RESOLUTION_RX, EPNUM_AUDIO, CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_FS, EPNUM_AUDIO_FB | 0x80, 44100, 48000),
#if CFG_AUDIO_DEBUG
// Interface number, string index, protocol, report descriptor len, EP In address, size & polling interval
TUD_HID_DESCRIPTOR(ITF_NUM_DEBUG, 0, HID_ITF_PROTOCOL_NONE, sizeof(desc_hid_report), EPNUM_DEBUG | 0x80, CFG_TUD_HID_EP_BUFSIZE, 7)
#endif
};
TU_VERIFY_STATIC(sizeof(desc_uac1_configuration) == CONFIG_UAC1_TOTAL_LEN, "Incorrect size");
#if TUD_OPT_HIGH_SPEED
#if CFG_AUDIO_DEBUG
#define CONFIG_UAC2_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_AUDIO20_SPEAKER_STEREO_FB_DESC_LEN + TUD_HID_DESC_LEN)
#else
#define CONFIG_UAC2_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_AUDIO20_SPEAKER_STEREO_FB_DESC_LEN)
#endif
uint8_t const desc_uac2_configuration[] = {
// Config number, interface count, string index, total length, attribute, power in mA
TUD_CONFIG_DESCRIPTOR(1, ITF_NUM_TOTAL, 0, CONFIG_UAC2_TOTAL_LEN, 0x00, 100),
// Interface number, string index, byte per sample, bit per sample, EP Out, EP size, EP feedback, feedback EP size,
TUD_AUDIO20_SPEAKER_STEREO_FB_DESCRIPTOR(ITF_NUM_AUDIO_CONTROL, 4, CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_RX, CFG_TUD_AUDIO_FUNC_1_RESOLUTION_RX, EPNUM_AUDIO, CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_HS, EPNUM_AUDIO_FB | 0x80, 4),
#if CFG_AUDIO_DEBUG
// Interface number, string index, protocol, report descriptor len, EP In address, size & polling interval
TUD_HID_DESCRIPTOR(ITF_NUM_DEBUG, 0, HID_ITF_PROTOCOL_NONE, sizeof(desc_hid_report), EPNUM_DEBUG | 0x80, CFG_TUD_HID_EP_BUFSIZE, 7)
#endif
};
TU_VERIFY_STATIC(sizeof(desc_uac2_configuration) == CONFIG_UAC2_TOTAL_LEN, "Incorrect size");
// 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 = 0x0200,
.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
return (tud_speed_get() == TUSB_SPEED_HIGH) ? desc_uac1_configuration : desc_uac2_configuration;
}
#endif // highspeed
// Invoked when received GET CONFIGURATION DESCRIPTOR
// Application return pointer to descriptor
// Descriptor contents must exist long enough for transfer to complete
uint8_t const * 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.
if(tud_speed_get() == TUSB_SPEED_FULL) {
return desc_uac1_configuration;
} else {
return desc_uac2_configuration;
}
#else
return desc_uac1_configuration;
#endif
}
//--------------------------------------------------------------------+
// String Descriptors
//--------------------------------------------------------------------+
// String Descriptor Index
enum {
STRID_LANGID = 0,
STRID_MANUFACTURER,
STRID_PRODUCT,
STRID_SERIAL,
};
// array of pointer to string descriptors
static char const *string_desc_arr[] =
{
(const char[]) { 0x09, 0x04 }, // 0: is supported language is English (0x0409)
"TinyUSB", // 1: Manufacturer
"TinyUSB Speaker", // 2: Product
NULL, // 3: Serials will use unique ID if possible
"UAC2 Speaker", // 4: Audio Interface
"UAC1 Speaker", // 5: UAC1 Audio 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);
size_t const 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;
}
@@ -0,0 +1,170 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2023 HiFiPhile
*
* 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 USB_DESCRIPTORS_H_
#define USB_DESCRIPTORS_H_
//--------------------------------------------------------------------+
// UAC2 DESCRIPTOR TEMPLATES
//--------------------------------------------------------------------+
// Defined in TUD_AUDIO20_SPEAKER_STEREO_FB_DESCRIPTOR
#define UAC2_ENTITY_CLOCK 0x04
#define UAC2_ENTITY_INPUT_TERMINAL 0x01
#define UAC2_ENTITY_FEATURE_UNIT 0x02
#define UAC2_ENTITY_OUTPUT_TERMINAL 0x03
#define TUD_AUDIO20_SPEAKER_STEREO_FB_DESC_LEN (TUD_AUDIO20_DESC_IAD_LEN\
+ TUD_AUDIO20_DESC_STD_AC_LEN\
+ TUD_AUDIO20_DESC_CS_AC_LEN\
+ TUD_AUDIO20_DESC_CLK_SRC_LEN\
+ TUD_AUDIO20_DESC_INPUT_TERM_LEN\
+ TUD_AUDIO20_DESC_OUTPUT_TERM_LEN\
+ TUD_AUDIO20_DESC_FEATURE_UNIT_LEN(2)\
+ TUD_AUDIO20_DESC_STD_AS_LEN\
+ TUD_AUDIO20_DESC_STD_AS_LEN\
+ TUD_AUDIO20_DESC_CS_AS_INT_LEN\
+ TUD_AUDIO20_DESC_TYPE_I_FORMAT_LEN\
+ TUD_AUDIO20_DESC_STD_AS_ISO_EP_LEN\
+ TUD_AUDIO20_DESC_CS_AS_ISO_EP_LEN\
+ TUD_AUDIO20_DESC_STD_AS_ISO_FB_EP_LEN)
#define TUD_AUDIO20_SPEAKER_STEREO_FB_DESCRIPTOR(_itfnum, _stridx, _nBytesPerSample, _nBitsUsedPerSample, _epout, _epoutsize, _epfb, _epfbsize) \
/* Standard Interface Association Descriptor (IAD) */\
TUD_AUDIO20_DESC_IAD(/*_firstitf*/ _itfnum, /*_nitfs*/ 0x02, /*_stridx*/ 0x00),\
/* Standard AC Interface Descriptor(4.7.1) */\
TUD_AUDIO20_DESC_STD_AC(/*_itfnum*/ _itfnum, /*_nEPs*/ 0x00, /*_stridx*/ _stridx),\
/* Class-Specific AC Interface Header Descriptor(4.7.2) */\
TUD_AUDIO20_DESC_CS_AC(/*_bcdADC*/ 0x0200, /*_category*/ AUDIO20_FUNC_DESKTOP_SPEAKER, /*_totallen*/ TUD_AUDIO20_DESC_CLK_SRC_LEN+TUD_AUDIO20_DESC_INPUT_TERM_LEN+TUD_AUDIO20_DESC_OUTPUT_TERM_LEN+TUD_AUDIO20_DESC_FEATURE_UNIT_LEN(2), /*_ctrl*/ AUDIO20_CS_AS_INTERFACE_CTRL_LATENCY_POS),\
/* Clock Source Descriptor(4.7.2.1) */\
TUD_AUDIO20_DESC_CLK_SRC(/*_clkid*/ 0x04, /*_attr*/ AUDIO20_CLOCK_SOURCE_ATT_INT_PRO_CLK, /*_ctrl*/ (AUDIO20_CTRL_RW << AUDIO20_CLOCK_SOURCE_CTRL_CLK_FRQ_POS), /*_assocTerm*/ 0x01, /*_stridx*/ 0x00),\
/* Input Terminal Descriptor(4.7.2.4) */\
TUD_AUDIO20_DESC_INPUT_TERM(/*_termid*/ 0x01, /*_termtype*/ AUDIO_TERM_TYPE_USB_STREAMING, /*_assocTerm*/ 0x00, /*_clkid*/ 0x04, /*_nchannelslogical*/ 0x02, /*_channelcfg*/ AUDIO20_CHANNEL_CONFIG_NON_PREDEFINED, /*_idxchannelnames*/ 0x00, /*_ctrl*/ 0 * (AUDIO20_CTRL_R << AUDIO20_IN_TERM_CTRL_CONNECTOR_POS), /*_stridx*/ 0x00),\
/* Output Terminal Descriptor(4.7.2.5) */\
TUD_AUDIO20_DESC_OUTPUT_TERM(/*_termid*/ 0x03, /*_termtype*/ AUDIO_TERM_TYPE_OUT_DESKTOP_SPEAKER, /*_assocTerm*/ 0x01, /*_srcid*/ 0x02, /*_clkid*/ 0x04, /*_ctrl*/ 0x0000, /*_stridx*/ 0x00),\
/* Feature Unit Descriptor(4.7.2.8) */\
TUD_AUDIO20_DESC_FEATURE_UNIT(/*_unitid*/ 0x02, /*_srcid*/ 0x01, /*_stridx*/ 0x00, /*_ctrlch0master*/ AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_VOLUME_POS, /*_ctrlch1*/ AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_VOLUME_POS, /*_ctrlch2*/ AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_VOLUME_POS),\
/* Standard AS Interface Descriptor(4.9.1) */\
/* Interface 1, Alternate 0 - default alternate setting with 0 bandwidth */\
TUD_AUDIO20_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum) + 1), /*_altset*/ 0x00, /*_nEPs*/ 0x00, /*_stridx*/ 0x00),\
/* Standard AS Interface Descriptor(4.9.1) */\
/* Interface 1, Alternate 1 - alternate interface for data streaming */\
TUD_AUDIO20_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum) + 1), /*_altset*/ 0x01, /*_nEPs*/ 0x02, /*_stridx*/ 0x00),\
/* Class-Specific AS Interface Descriptor(4.9.2) */\
TUD_AUDIO20_DESC_CS_AS_INT(/*_termid*/ 0x01, /*_ctrl*/ AUDIO20_CTRL_NONE, /*_formattype*/ AUDIO20_FORMAT_TYPE_I, /*_formats*/ AUDIO20_DATA_FORMAT_TYPE_I_PCM, /*_nchannelsphysical*/ 0x02, /*_channelcfg*/ AUDIO20_CHANNEL_CONFIG_NON_PREDEFINED, /*_stridx*/ 0x00),\
/* Type I Format Type Descriptor(2.3.1.6 - Audio Formats) */\
TUD_AUDIO20_DESC_TYPE_I_FORMAT(_nBytesPerSample, _nBitsUsedPerSample),\
/* Standard AS Isochronous Audio Data Endpoint Descriptor(4.10.1.1) */\
TUD_AUDIO20_DESC_STD_AS_ISO_EP(/*_ep*/ _epout, /*_attr*/ (uint8_t) ((uint8_t)TUSB_XFER_ISOCHRONOUS | (uint8_t)TUSB_ISO_EP_ATT_ASYNCHRONOUS | (uint8_t)TUSB_ISO_EP_ATT_DATA), /*_maxEPsize*/ _epoutsize, /*_interval*/ 0x01),\
/* Class-Specific AS Isochronous Audio Data Endpoint Descriptor(4.10.1.2) */\
TUD_AUDIO20_DESC_CS_AS_ISO_EP(/*_attr*/ AUDIO20_CS_AS_ISO_DATA_EP_ATT_NON_MAX_PACKETS_OK, /*_ctrl*/ AUDIO20_CTRL_NONE, /*_lockdelayunit*/ AUDIO20_CS_AS_ISO_DATA_EP_LOCK_DELAY_UNIT_MILLISEC, /*_lockdelay*/ 0x0001),\
/* Standard AS Isochronous Feedback Endpoint Descriptor(4.10.2.1) */\
TUD_AUDIO20_DESC_STD_AS_ISO_FB_EP(/*_ep*/ _epfb, /*_epsize*/ _epfbsize, /*_interval*/ TUD_OPT_HIGH_SPEED ? 4 : 1)
//--------------------------------------------------------------------+
// UAC1 DESCRIPTOR TEMPLATES
//--------------------------------------------------------------------+
// Defined in TUD_AUDIO10_SPEAKER_STEREO_FB_DESCRIPTOR
#define UAC1_ENTITY_INPUT_TERMINAL 0x01
#define UAC1_ENTITY_FEATURE_UNIT 0x02
#define UAC1_ENTITY_OUTPUT_TERMINAL 0x03
#define TUD_AUDIO10_SPEAKER_STEREO_FB_DESC_LEN(_nfreqs) (\
+ TUD_AUDIO10_DESC_STD_AC_LEN\
+ TUD_AUDIO10_DESC_CS_AC_LEN(1)\
+ TUD_AUDIO10_DESC_INPUT_TERM_LEN\
+ TUD_AUDIO10_DESC_OUTPUT_TERM_LEN\
+ TUD_AUDIO10_DESC_FEATURE_UNIT_LEN(2)\
+ TUD_AUDIO10_DESC_STD_AS_LEN\
+ TUD_AUDIO10_DESC_STD_AS_LEN\
+ TUD_AUDIO10_DESC_CS_AS_INT_LEN\
+ TUD_AUDIO10_DESC_TYPE_I_FORMAT_LEN(_nfreqs)\
+ TUD_AUDIO10_DESC_STD_AS_ISO_EP_LEN\
+ TUD_AUDIO10_DESC_CS_AS_ISO_EP_LEN\
+ TUD_AUDIO10_DESC_STD_AS_ISO_SYNC_EP_LEN)
#define TUD_AUDIO10_SPEAKER_STEREO_FB_DESCRIPTOR(_itfnum, _stridx, _nBytesPerSample, _nBitsUsedPerSample, _epout, _epoutsize, _epfb, ...) \
/* Standard AC Interface Descriptor(4.3.1) */\
TUD_AUDIO10_DESC_STD_AC(/*_itfnum*/ _itfnum, /*_nEPs*/ 0x00, /*_stridx*/ _stridx),\
/* Class-Specific AC Interface Header Descriptor(4.3.2) */\
TUD_AUDIO10_DESC_CS_AC(/*_bcdADC*/ 0x0100, /*_totallen*/ (TUD_AUDIO10_DESC_INPUT_TERM_LEN+TUD_AUDIO10_DESC_OUTPUT_TERM_LEN+TUD_AUDIO10_DESC_FEATURE_UNIT_LEN(2)), /*_itf*/ ((_itfnum)+1)),\
/* Input Terminal Descriptor(4.3.2.1) */\
TUD_AUDIO10_DESC_INPUT_TERM(/*_termid*/ 0x01, /*_termtype*/ AUDIO_TERM_TYPE_USB_STREAMING, /*_assocTerm*/ 0x00, /*_nchannels*/ 0x02, /*_channelcfg*/ AUDIO10_CHANNEL_CONFIG_LEFT_FRONT | AUDIO10_CHANNEL_CONFIG_RIGHT_FRONT, /*_idxchannelnames*/ 0x00, /*_stridx*/ 0x00),\
/* Output Terminal Descriptor(4.3.2.2) */\
TUD_AUDIO10_DESC_OUTPUT_TERM(/*_termid*/ 0x03, /*_termtype*/ AUDIO_TERM_TYPE_OUT_DESKTOP_SPEAKER, /*_assocTerm*/ 0x00, /*_srcid*/ 0x02, /*_stridx*/ 0x00),\
/* Feature Unit Descriptor(4.3.2.5) */\
TUD_AUDIO10_DESC_FEATURE_UNIT(/*_unitid*/ 0x02, /*_srcid*/ 0x01, /*_stridx*/ 0x00, /*_ctrlmaster*/ (AUDIO10_FU_CONTROL_BM_MUTE | AUDIO10_FU_CONTROL_BM_VOLUME), /*_ctrlch1*/ (AUDIO10_FU_CONTROL_BM_MUTE | AUDIO10_FU_CONTROL_BM_VOLUME), /*_ctrlch2*/ (AUDIO10_FU_CONTROL_BM_MUTE | AUDIO10_FU_CONTROL_BM_VOLUME)),\
/* Standard AS Interface Descriptor(4.5.1) */\
/* Interface 1, Alternate 0 - default alternate setting with 0 bandwidth */\
TUD_AUDIO10_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum)+1), /*_altset*/ 0x00, /*_nEPs*/ 0x00, /*_stridx*/ 0x00),\
/* Standard AS Interface Descriptor(4.5.1) */\
/* Interface 1, Alternate 1 - alternate interface for data streaming */\
TUD_AUDIO10_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum)+1), /*_altset*/ 0x01, /*_nEPs*/ 0x02, /*_stridx*/ 0x00),\
/* Class-Specific AS Interface Descriptor(4.5.2) */\
TUD_AUDIO10_DESC_CS_AS_INT(/*_termid*/ 0x01, /*_delay*/ 0x00, /*_formattype*/ AUDIO10_DATA_FORMAT_TYPE_I_PCM),\
/* Type I Format Type Descriptor(2.2.5) */\
TUD_AUDIO10_DESC_TYPE_I_FORMAT(/*_nrchannels*/ 0x02, /*_subframesize*/ _nBytesPerSample, /*_bitresolution*/ _nBitsUsedPerSample, /*_freqs*/ __VA_ARGS__),\
/* Standard AS Isochronous Audio Data Endpoint Descriptor(4.6.1.1) */\
TUD_AUDIO10_DESC_STD_AS_ISO_EP(/*_ep*/ _epout, /*_attr*/ (uint8_t) ((uint8_t)TUSB_XFER_ISOCHRONOUS | (uint8_t)TUSB_ISO_EP_ATT_ASYNCHRONOUS), /*_maxEPsize*/ _epoutsize, /*_interval*/ 0x01, /*_sync_ep*/ _epfb),\
/* Class-Specific AS Isochronous Audio Data Endpoint Descriptor(4.6.1.2) */\
TUD_AUDIO10_DESC_CS_AS_ISO_EP(/*_attr*/ AUDIO10_CS_AS_ISO_DATA_EP_ATT_SAMPLING_FRQ, /*_lockdelayunits*/ AUDIO10_CS_AS_ISO_DATA_EP_LOCK_DELAY_UNIT_UNDEFINED, /*_lockdelay*/ 0x0000),\
/* Standard AS Isochronous Synch Endpoint Descriptor (4.6.2.1) */\
TUD_AUDIO10_DESC_STD_AS_ISO_SYNC_EP(/*_ep*/ _epfb, /*_bRefresh*/ 0)
//---------------------------------------------------------------------------+
// UAC1 Isochronous Synch Endpoint bRefresh Workaround
//
// bRefresh value is set to 0, while UAC1 spec requires it to be between
// 1 (2 ms) and 9 (512 ms)
//
// This value has been tested to work with Windows, macOS and Linux.
//
// Rationale:
// Some USB device controllers (e.g. Synopsys DWC2) require a known transfer
// interval to manually schedule isochronous IN transfers. For data isochronous
// endpoints, the bInterval field in the endpoint descriptor is used. However,
// for synch endpoint it's unclear which field the host uses to determine the
// transfer interval. Windows and macOS use bRefresh, while Linux uses bInterval.
//
// Since bInterval is fixed to 1, if bRefresh is set to 2 then Windows and macOS
// will schedule the feedback transfer every 4 ms, but Linux will schedule it
// every 1 ms. DWC2 controller cannot handle this discrepancy without knwowing
// the actual interval, therefore we set bRefresh to 0 to let the transfer
// execute every 1 ms, which is the same as bInterval.
//
// Rant:
// WTF USB-IF? Why have two fields that mean the same thing? Why not just use
// bInterval for both data and synch endpoints? Why is bRefresh even necessary?
//
// Note:
// For the moment DWC2 driver doesn't have proper support for bInterval > 1
// for isochronous IN endpoints. The implementation would be complex and CPU
// intensive (cfr.
// https://github.com/torvalds/linux/blob/master/drivers/usb/dwc2/gadget.c)
// It MAY work in some cases if you are lucky, but it's not guaranteed.
//---------------------------------------------------------------------------+
#endif