arduino-audio-tools
Loading...
Searching...
No Matches
USBAudioDeviceBase.h
Go to the documentation of this file.
1#pragma once
2
3// Some cores (e.g. Arduino's Renesas UNO R4 core, Arduino.h) #define abs(x)
4// as a function-like macro for AVR-era C compatibility. Since Arduino.h is
5// always included ahead of library headers in a .ino, that macro is already
6// active here and breaks libstdc++'s own templated abs(duration<...>)
7// overload inside <chrono> (pulled in by <mutex>) -- the preprocessor sees
8// the comma inside duration<_Rep, _Period> as a second macro argument.
9// Suppress the macro for just this header's STL includes, then restore it
10// so nothing else in the translation unit is affected.
11#pragma push_macro("abs")
12#undef abs
13
14#include <cmath>
15#include <cstddef>
16#include <cstdint>
17#include <cstring>
18#include <functional>
19#include <mutex>
20#include <vector>
21
22#pragma pop_macro("abs")
23
26
27#ifdef ESP32
28#ifndef ARDUINO_USB_MODE
29#error This Microcontroller has no Native USB interface
30#else
31#if ARDUINO_USB_MODE == 1
32#error This sketch should be used when USB is in OTG mode
33#endif
34#endif
35#else
36#if !defined(USE_TINYUSB) && !defined(ARDUINO_ARCH_STM32) && \
37 !defined(ARDUINO_ARCH_RENESAS) && !defined(IS_ZEPHYR)
38#error This Microcontroller has no Native USB interface
39#endif
40#endif
41
42#include "AudioLogger.h"
48
49#define USB_DESCR_MAX_LEN 512
50
51namespace audio_tools {
52
53
69public:
80
94
103 uint8_t const* p_desc; // Pointer to Standard AC Interface Descriptor
104 // ep_in/ep_out are written from the USB interrupt handler (openEpIn/
105 // openEpOut/closeEpIn/closeEpOut, reached via audiod_set_interface() in
106 // ISR context) and read from normal application code (write()/
107 // readBytes()/isStreamingActiveTx()/isStreamingActiveRx(), called from
108 // loop()). Without a memory-visibility guarantee across that boundary, a
109 // compiler is free to cache a stale read indefinitely -- observed in
110 // practice on the arm-none-eabi-gcc 7.2.1 toolchain used by the Arduino
111 // Renesas UNO R4 core: isStreamingActiveTx() kept reporting false while
112 // real ISO-IN transfers were actively completing, so write() silently
113 // discarded all audio data (see the "disregard data" branch below) while
114 // still reporting success.
115 volatile uint8_t ep_in; // TX audio data EP.
116 uint16_t ep_in_sz; // Current size of TX EP
117 uint8_t
118 ep_in_as_intf_num; // Standard AS Interface Descriptor number for IN
119 volatile uint8_t ep_out; // RX audio data EP.
120 uint16_t ep_out_sz; // Current size of RX EP
121 uint8_t
122 ep_out_as_intf_num; // Standard AS Interface Descriptor number for OUT
123 uint8_t ep_fb; // Feedback EP.
124 // Feedback EP with a transfer queued, or 0. Unlike ep_fb, it isn't
125 // cleared when the stream closes, so a completion that arrives after
126 // that is still recognised; it's cleared when the endpoint is activated
127 // again (openEpFeedback()). See audiod_fb_kick().
129 uint8_t ep_int; // Audio control interrupt EP.
130 bool mounted; // Device opened
131 uint16_t desc_length; // Length of audio function descriptor
132 struct {
136 // Nominal value (fb_param.sample_freq) and the setFeedbackPpm() offset
137 // from it, in the same 16.16 format. See setupFeedback().
143 union {
146 struct {
150 struct {
153 uint16_t fifo_lvl_thr;
154 uint16_t rate_const[2];
159 uint16_t packet_sz_tx[3];
165 // Fractional sample accumulator for IN-endpoint flow control. Carries the
166 // sub-frame remainder (e.g. the 0.1 sample/frame of 44100 Hz) so the
167 // long-term average packet size matches the real sample rate.
169 // Cached OUT endpoint descriptor (populated by audiod_open()'s descriptor
170 // scan) so closeEpOut() can re-activate the endpoint -- resetting its
171 // busy/claimed state for the next SET_INTERFACE -- without needing to
172 // re-walk the descriptor. See closeEpOut() for why this is needed.
174 // From this point, data is not cleared by bus reset
176 std::vector<uint8_t> ctrl_buf;
177 std::vector<uint8_t> alt_setting;
178 std::vector<uint8_t> lin_buf_out;
179 std::vector<uint8_t> lin_buf_in;
180 std::vector<uint32_t> fb_buf;
181 };
182
191 uint32_t sample_freq; // sample frequency in Hz
192
193 union {
194 struct {
195 uint32_t mclk_freq; // Main clock frequency in Hz i.e. master clock to
196 // which sample clock is based on
198 };
199 };
200
203
208
215 USBAudioConfig cfg;
216 switch (mode) {
217 case RX_MODE:
218 cfg.enable_ep_out = true;
219 cfg.enable_ep_in = false;
220 break;
221 case TX_MODE:
222 cfg.enable_ep_out = false;
223 cfg.enable_ep_in = true;
224 break;
225 case RXTX_MODE:
226 cfg.enable_ep_out = true;
227 cfg.enable_ep_in = true;
228 break;
229 default:
230 break;
231 }
232 return cfg;
233 }
234
236 void setAudioInfo(AudioInfo info) override {
238 LOGE("Unsupported bits_per_sample: %d (must be 16, 24, or 32)",
240 return;
241 }
242 // full flexibility when not started yet
243 if (!is_started_) {
247 return;
248 }
249
250 // when started only sample rate can be changed on the fly
252 if (config_.channels != info.channels) {
253 LOGE(
254 "Could not change channel count from %d to %d: channel count is "
255 "fixed at startup!",
257 }
259 LOGE(
260 "Could not change bits per sample from %d to %d: bits per sample is "
261 "fixed at startup!",
263 }
264 // notifiy subscribed entities
266 // notify host about sample rate change via control request callback;
268 }
269
278 bool begin(const USBAudioConfig& cfg) {
279 if (!is_started_) {
280 config_ = cfg;
281 } else if (!configChanged(cfg)) {
282 return true; // already running with same config
283 } else {
285 }
286 return begin();
287 }
288
295 bool begin() {
296 if (!is_started_) {
298 LOGE("Unsupported bits_per_sample: %d (must be 16, 24, or 32)",
300 return false;
301 }
302
304 LOGI("USB on core: %d", core);
305
306 // Resize platform buffers — virtual so each platform uses the right API.
308
309 const int n = getAudioCount();
310 // GET_RANGE response is 2 + count*12 bytes; 64 is the floor needed for
311 // everything else sharing this buffer (Feature Unit GET_RANGE, etc.).
312 uint16_t cb_sz = 64u;
314 uint16_t needed =
315 (uint16_t)(2 + config_.supported_sample_rates.size() * 12);
316 if (needed > cb_sz) cb_sz = needed;
317 }
318 ctrl_buf_sz_.assign(n, cb_sz);
319
321 uint16_t desc_len = descr_builder.buildFullDescriptor(desc);
322 desc_len_.assign(n, desc_len);
323
324 // master (index 0) + one per channel
326
327
328 audiod_init();
329
330 if (!beginUSB()) {
331 LOGE("beginUSB failed");
332 return false;
333 }
334 is_started_ = true;
335 rx_primed_ = false; // re-arm the one-shot startup prime for this session
336 }
337
338 // Push current state to the host. sendInterruptNotification()
339 // is a no-op when not yet mounted, so this is harmless on first boot.
341 for (uint8_t ch = 0; ch < (uint8_t)volume_.size(); ch++) {
342 setVolume(volume(ch), ch);
343 setMute(isMute(ch), ch);
344 }
345 is_active_ = true;
346 return true;
347 }
355
356
362
369
370
371
373 bool isStreamingActiveTx() const override {
374 for (const auto& fct : audiod_fct_) {
375 if (fct.ep_in != 0) return true;
376 }
377 return false;
378 }
379
381 bool isStreamingActiveRx() const override {
382 for (const auto& fct : audiod_fct_) {
383 if (fct.ep_out != 0) return true;
384 }
385 return false;
386 }
389
391 uint8_t getAudioCount() const { return 1; }
392
394 bool mounted() override { return backend().mounted(); }
395
401 UsbSetupPacket const&)>
402 cb) {
403 get_req_itf_cb_ = cb;
404 }
405
411 UsbSetupPacket const&)>
412 cb) {
413 get_req_ep_cb_ = cb;
414 }
415
420 void setFbDoneCallback(std::function<void(USBAudioDeviceBase*, uint8_t)> cb) {
421 fb_done_cb_ = cb;
422 }
423
429 std::function<void(USBAudioDeviceBase*, uint8_t)> cb) {
430 int_done_cb_ = cb;
431 }
432
438 std::function<bool(USBAudioDeviceBase*, uint8_t, audiod_function_t*, uint16_t)>
439 cb) {
440 tx_done_cb_ = cb;
441 }
442
448 audiod_function_t*, uint16_t)>
449 cb) {
450 rx_done_cb_ = cb;
451 }
452
458 std::function<bool(USBAudioDeviceBase*, uint8_t)> cb) {
459 req_entity_cb_ = cb;
460 }
461
467 std::function<bool(USBAudioDeviceBase*, uint8_t,
468 UsbSetupPacket const&)>
469 cb) {
471 }
472
478 std::function<bool(USBAudioDeviceBase*, uint8_t,
479 UsbSetupPacket const&, uint8_t*)>
480 cb) {
482 }
483
489 std::function<bool(USBAudioDeviceBase*, uint8_t,
490 UsbSetupPacket const&, uint8_t*)>
491 cb) {
493 }
494
500 std::function<bool(USBAudioDeviceBase*, uint8_t,
501 UsbSetupPacket const&, uint8_t*)>
502 cb) {
504 }
505
511 UsbSetupPacket const&)>
512 cb) {
514 }
515
526
535
558 void setFeedbackPercent(int percent) {
559 int normalized = percent;
560 if (normalized < 0) normalized = 0;
561 if (normalized > 100) normalized = 100;
562 manual_feedback_ppm_ = INT32_MIN;
563 manual_feedback_percent_ = normalized;
564 }
565
576 if (ppm == INT32_MIN) ppm = INT32_MIN + 1;
577 // The offset is computed here, not in the SOF interrupt, to keep the
578 // 64 bit divide out of it.
579 for (uint8_t i = 0; i < getAudioCount(); i++) {
580 audiod_function_t* audio = &audiod_fct_[i];
581 audio->feedback.ppm_offset = feedbackPpmOffset(audio, ppm);
582 }
585 }
586
591 manual_feedback_ppm_ = INT32_MIN;
592 }
593
594
596 void end() {
597 for (auto& audio : audiod_fct_) {
598 std::fill(audio.lin_buf_in.begin(), audio.lin_buf_in.end(), 0);
599 std::fill(audio.lin_buf_out.begin(), audio.lin_buf_out.end(), 0);
600 }
601 bufferTx().reset();
602 bufferRx().reset();
603 is_started_ = false;
604 }
605
608 uint16_t audioPacketSize() const { return packetSize(); }
609
621 uint16_t getDescriptor(uint8_t* desc) {
622 active_config_ = config_; // save active config
624 }
625
632 return (uint8_t)(1 + (config_.enable_ep_out ? 1 : 0) +
633 (config_.enable_ep_in ? 1 : 0));
634 }
635
637 bool isTxXferArmed() const { return tx_xfer_armed_; }
638
652
655 uint16_t getTxFrameBytesLast() const { return tx_frame_bytes_last_; }
661 return audiod_fct_.empty() ? 0 : audiod_fct_[0].sample_rate_tx;
662 }
665 return audiod_fct_.empty() ? 0 : audiod_fct_[0].n_channels_tx;
666 }
669 return audiod_fct_.empty() ? 0 : audiod_fct_[0].n_bytes_per_sample_tx;
670 }
673 return audiod_fct_.empty() ? 0 : audiod_fct_[0].interval_tx;
674 }
675
676 virtual int getActualCore() const { return -1;}
677
678 protected:
679 bool tx_xfer_armed_ = false;
685 volatile uint16_t tx_frame_bytes_last_ = 0;
689 std::function<void(USBAudioDeviceBase*, uint8_t rhport)> int_done_cb_;
690 std::function<bool(USBAudioDeviceBase*, uint8_t rhport, audiod_function_t*, uint16_t bytes)>
692 std::function<bool(USBAudioDeviceBase*, uint8_t rhport, audiod_function_t*,
693 uint16_t xferred_bytes)>
695 // Callback for interface GET requests
696 std::function<bool(USBAudioDeviceBase*, uint8_t rhport,
697 UsbSetupPacket const&)>
699 // Callback for endpoint GET requests
700 std::function<bool(USBAudioDeviceBase*, uint8_t rhport,
701 UsbSetupPacket const&)>
703
704 // Callback for feedback done event
705 std::function<void(USBAudioDeviceBase*, uint8_t func_id)> fb_done_cb_;
707 std::function<bool(USBAudioDeviceBase*, uint8_t rhport,
708 UsbSetupPacket const& p_request)>
710 std::function<bool(USBAudioDeviceBase*, uint8_t rhport,
711 UsbSetupPacket const& p_request, uint8_t* pBuff)>
713
714 std::function<bool(USBAudioDeviceBase*, uint8_t rhport,
715 UsbSetupPacket const& p_request, uint8_t* pBuff)>
717
718 std::function<bool(USBAudioDeviceBase*, uint8_t rhport,
719 UsbSetupPacket const& p_request, uint8_t* pBuff)>
721
722 std::function<bool(USBAudioDeviceBase*, uint8_t rhport,
723 UsbSetupPacket const& p_request)>
725
726 std::function<void(USBAudioDeviceBase*, uint8_t func_id, uint8_t alt_itf,
727 audio_feedback_params_t* feedback_param)>
729
730 std::function<bool(USBAudioDeviceBase*, uint8_t func_id)>
733
734 // Manual feedback override: -1 means "automatic" (use the negotiated
735 // compute_method, e.g. AUDIO_FEEDBACK_METHOD_FIFO_COUNT); 0..100 means
736 // the caller is driving the feedback value directly via
737 // setFeedbackPercent(). See tud_audio_feedback_interval_isr().
739 // setFeedbackPpm() override, or INT32_MIN for none.
740 volatile int32_t manual_feedback_ppm_ = INT32_MIN;
741 // enable_ep_in_rate_tracking: frames to wait before the next correction.
743 // enable_ep_in_rate_tracking: false until bufferTx() first fills to the
744 // target level; then the smoothed level, in frames, Q8.
745 bool tx_rate_armed_ = false;
747
748 // calculate!
749 std::vector<uint16_t> desc_len_;
750 // 64
751 std::vector<uint16_t> ctrl_buf_sz_;
752
753 std::vector<audiod_function_t> audiod_fct_;
754
755 // s_active_ lets the class-driver trampolines and the static process()
756 // trampoline reach the last-constructed instance without a singleton.
757 inline static USBAudioDeviceBase* s_active_ = nullptr;
758
759
774 void serviceUSB() override = 0;
775
779 virtual USBAudioBackend& backend() = 0;
780
781
791 bool rate_updated = rate != config_.sample_rate;
792 config_.sample_rate = rate;
793 LOGW("Sample rate changed to %u Hz", rate);
794 if (rate_updated) {
797 }
798 for (auto& fct : audiod_fct_) fct.sample_rate_tx = rate;
802 }
803
809
815
822
831 uint8_t entityID) {
832 if (!backend().mounted()) return;
833 for (uint8_t i = 0; i < (uint8_t)audiod_fct_.size(); i++) {
834 if (audiod_fct_[i].ep_int == 0) continue;
835 int_notify_buf_[0] = 0x00; // bInfo: interface, not vendor
836 int_notify_buf_[1] = kAudioCsReqCur; // bAttribute: CUR changed
837 int_notify_buf_[2] = channel; // wValue low = CN
838 int_notify_buf_[3] = ctrlSel; // wValue high = CS
839 int_notify_buf_[4] = config_.itf_num_ac; // wIndex low = interface
840 int_notify_buf_[5] = entityID; // wIndex high = entity ID
841 (void)backend().transfer(0, audiod_fct_[i].ep_int, int_notify_buf_, 6);
842 break;
843 }
844 }
845
846 // Returns the control buffer size for a given function number
847 uint16_t getCtrlBufSz(uint8_t fn) const {
848 return (fn < ctrl_buf_sz_.size()) ? ctrl_buf_sz_[fn] : 64;
849 }
850
851 // Returns the descriptor length for a given function number
852 uint16_t getDescLen(uint8_t fn) const {
853 return (fn < desc_len_.size()) ? desc_len_[fn] : 0;
854 }
855
856 // Max Bytes for one 1 ms isochronous USB packet.
857 uint16_t packetSize() const { return descr_builder.calcMaxPacketSize(); }
858
859 // Returns the reset size for audiod_function_t up to and including
860 // ctrl_buf_sz
861 static constexpr size_t getResetSize() {
862 return offsetof(audiod_function_t, ctrl_buf_sz) +
863 sizeof(((audiod_function_t*)0)->ctrl_buf_sz);
864 }
865
866 // Called by audiod_sof_isr() at the feedback interval, in the USB
867 // interrupt. Only computes the feedback value: sending it means claiming
868 // the endpoint, which takes TinyUSB's endpoint mutex, and doing that here
869 // deadlocks if the interrupt arrived while the TinyUSB task held it. The
870 // value is sent from task context instead, each time the previous feedback
871 // transfer completes (audiod_xfer_cb()), as TinyUSB's own audio driver does.
873 uint32_t /*frame_count*/,
874 uint8_t frame_shift) {
875 audiod_function_t* audio = &audiod_fct_[func_id];
876 // Computed here and stored to audio->feedback.value once: it's read
877 // from task context (audiod_fb_send()), which mustn't see a value
878 // that's only partly computed (eg: before clamping).
879 uint32_t value = audio->feedback.value;
880
881 if (manual_feedback_ppm_ != INT32_MIN) {
882 // setFeedbackPpm() override: offset from the nominal rate.
883 int32_t offset = audio->feedback.ppm_offset;
884 value = offset < 0 && (uint32_t)-offset > audio->feedback.nom_value
885 ? 0
886 : audio->feedback.nom_value + offset;
887 value = clampFeedback(audio, value);
888 } else if (manual_feedback_percent_ >= 0) {
889 // setFeedbackPercent() override: scale linearly across the negotiated
890 // [min_value, max_value] range instead of running the automatic
891 // compute_method below.
892 uint32_t range = audio->feedback.max_value - audio->feedback.min_value;
893 value = audio->feedback.min_value +
894 (range * (uint32_t)manual_feedback_percent_) / 100;
895 } else {
896 switch (audio->feedback.compute_method) {
898 // In linear-buffer mode, audio data flows lin_buf_out → bufferRx(),
899 // completely bypassing ep_out_ff. Reading ep_out_ff would always
900 // return 0, driving the feedback to min_value and causing the host
901 // to gradually reduce its send rate until the buffer drains
902 // (audible periodic drop every 5-10 s). Use the platform RX ring
903 // buffer level.
904 uint32_t ff_count = (uint32_t)bufferRx().available();
905 // Exponential weighted average keeps the level estimate stable
909 ((uint32_t)ff_count << 8);
913 if (avg > thr) {
914 // Buffer fuller than the target level: ask the host to slow
915 // down. rate_const[1] is scaled so avg==fifo_depth (full) maps
916 // exactly to min_value.
917 uint32_t drop =
919 (avg - thr);
920 value = (nom > drop) ? nom - drop : audio->feedback.min_value;
921 } else {
922 // Buffer emptier than the target level: ask the host to speed
923 // up. rate_const[0] is scaled so avg==0 (empty) maps exactly to
924 // max_value.
925 value = nom +
927 (thr - avg);
928 }
929 value = clampFeedback(audio, value);
930 } break;
931
933 value = 1UL << audio->feedback.compute.power_of_2;
934 break;
935
937 value = (uint32_t)(audio->feedback.compute.float_const *
938 (float)(1UL << (16u - (frame_shift - 1u))));
939 break;
940
942 uint32_t frame_div = backend().isFullSpeed() ? 1000u : 8000u;
943 value = (audio->feedback.compute.fixed.sample_freq << 16) / frame_div;
944 } break;
945
946 default:
947 break;
948 }
949 }
950 audio->feedback.value = value;
951 }
952
954 uint32_t value) {
955 if (value < audio->feedback.min_value) return audio->feedback.min_value;
956 if (value > audio->feedback.max_value) return audio->feedback.max_value;
957 return value;
958 }
959
960 // setFeedbackPpm()'s offset from feedback.nom_value, in 16.16 format.
962 int32_t ppm) {
963 return (int32_t)((int64_t)audio->feedback.nom_value * ppm / 1000000);
964 }
965
966 // Queues a feedback transfer with the latest value, unless one is already
967 // queued. Task context only (see tud_audio_feedback_interval_isr()).
968 // Called when the OUT stream opens, when each feedback transfer
969 // completes, and, so that a broken chain (eg: a failed transfer) restarts,
970 // when each OUT packet arrives.
972 if (!audio->ep_fb || audio->ep_fb_xfer) return;
973 if (!backend().claimEndpoint(audio->rhport, audio->ep_fb)) return;
974 if (audiod_fb_send(audio))
975 audio->ep_fb_xfer = audio->ep_fb;
976 else
977 backend().releaseEndpoint(audio->rhport, audio->ep_fb);
978 }
979
980 // USBD Driver API — public so a backend's class-driver registration glue
981 // (e.g. USBAudioBackendTinyUSB.h's trampoline into TinyUSB's
982 // usbd_class_driver_t) can call these without being a member of this
983 // class. A native-HAL backend with no such registration concept would
984 // instead call these directly from its own ISR/init code.
985 public:
986 void audiod_init(void) {
987 audiod_fct_.resize(getAudioCount());
988
989 // Initialize control buffers
990 for (uint8_t i = 0; i < getAudioCount(); i++) {
991 audiod_function_t* audio = &audiod_fct_[i];
992 // Initialize control buffers
993 int size = getCtrlBufSz(i);
994 audio->ctrl_buf.resize(size);
995 audio->ctrl_buf_sz = size;
996 // Initialize active alternate interface buffers
998 // Initialize IN EP — lin_buf_in is the DMA staging buffer (one frame).
999 // Audio data flows through bufferTx() (resized in begin()), not ep_in_ff.
1000 if (isEpInEnabled()) {
1001 // Max packet across all advertised rates (see supported_sample_rates).
1002 uint16_t max_pkt = descr_builder.calcPacketSizeForRate(
1004 audio->lin_buf_in.resize(max_pkt);
1005 }
1006 // Initialize OUT EP linear (DMA staging) buffer.
1007 if (isEpOutEnabled()) {
1008 uint16_t max_pkt = descr_builder.calcPacketSizeForRate(
1010 audio->lin_buf_out.resize(max_pkt);
1011 }
1012 if (isFeedbackEpEnabled()) {
1013 audio->fb_buf.resize(1); // one uint32_t = 4 bytes of feedback data
1014 }
1015 }
1016 }
1017
1018 bool audiod_deinit(void) {
1019 return false; // TODO not implemented yet
1020 }
1021
1022 void audiod_reset(uint8_t rhport) {
1023 (void)rhport;
1024 for (uint8_t i = 0; i < getAudioCount(); i++) {
1025 audiod_function_t* audio = &audiod_fct_[i];
1026 memset(audio, 0, getResetSize());
1027 if (isEpInEnabled()) {
1028 bufferTx().reset();
1029 }
1030 if (isEpOutEnabled()) {
1031 bufferRx().reset();
1032 }
1033 }
1034 }
1035
1036 uint16_t audiod_open(uint8_t rhport, UsbInterfaceDescriptorView const& itf_desc,
1037 uint8_t const* raw_desc, uint16_t max_len) {
1038 (void)max_len;
1039 if (!(kUsbClassAudio == itf_desc.bInterfaceClass &&
1041 return 0;
1042 if (itf_desc.bInterfaceProtocol != kAudioIntProtocolCodeV2) return 0;
1043 if (itf_desc.bNumEndpoints > 1) return 0;
1044 if (itf_desc.bNumEndpoints == 1 && !isInterruptEpEnabled()) return 0;
1045 if (itf_desc.bAlternateSetting != 0) return 0;
1046 uint8_t i;
1047 for (i = 0; i < getAudioCount(); i++) {
1048 if (!audiod_fct_[i].p_desc) {
1049 audiod_fct_[i].p_desc = raw_desc;
1050 audiod_fct_[i].rhport = rhport;
1051 audiod_fct_[i].desc_length = getDescLen(i);
1052 // audiod_reset() zeroes ctrl_buf_sz via memset — restore it so
1053 // controlTransfer() receives the correct buffer length.
1054 audiod_fct_[i].ctrl_buf_sz = getCtrlBufSz(i);
1056 uint8_t ep_in = 0, ep_out = 0, ep_fb = 0;
1057 uint16_t ep_in_size = 0, ep_out_size = 0;
1058 UsbEndpointDescriptorView desc_ep_out{};
1059 bool has_ep_out_view = false;
1060 uint8_t const* p_desc = audiod_fct_[i].p_desc;
1061 uint8_t const* p_desc_end =
1062 p_desc + audiod_fct_[i].desc_length - kAudioDescIadLen;
1063 while (p_desc_end - p_desc > 0) {
1064 if (descType(p_desc) == kUsbDescTypeEndpoint) {
1065 UsbEndpointDescriptorView desc_ep = decodeEndpoint(p_desc);
1066 if (desc_ep.xferType == UsbXferType::Isochronous) {
1067 if (isFeedbackEpEnabled() && desc_ep.usage == 1) {
1068 ep_fb = desc_ep.bEndpointAddress;
1069 }
1070 if (desc_ep.usage == 0) {
1071 if (isEpInEnabled() && desc_ep.direction() == UsbDir::In) {
1072 ep_in = desc_ep.bEndpointAddress;
1073 uint16_t sz = desc_ep.packetSize();
1074 ep_in_size = sz > ep_in_size ? sz : ep_in_size;
1075 } else if (isEpOutEnabled() &&
1076 desc_ep.direction() == UsbDir::Out) {
1077 ep_out = desc_ep.bEndpointAddress;
1078 uint16_t sz = desc_ep.packetSize();
1079 ep_out_size = sz > ep_out_size ? sz : ep_out_size;
1080 desc_ep_out = desc_ep;
1081 has_ep_out_view = true;
1082 }
1083 }
1084 }
1085 }
1086 p_desc = descNext(p_desc);
1087 }
1088 if (isEpInEnabled() && ep_in) {
1089 bool alloc_ok = backend().isoAllocEndpoint(rhport, ep_in, ep_in_size);
1090 LOGD("iso_alloc IN ep=0x%02x sz=%u: %s", ep_in, ep_in_size,
1091 alloc_ok ? "OK" : "FAIL");
1092 }
1093 if (isEpOutEnabled() && ep_out) {
1094 bool alloc_ok = backend().isoAllocEndpoint(rhport, ep_out, ep_out_size);
1095 LOGD("iso_alloc OUT ep=0x%02x sz=%u: %s", ep_out, ep_out_size,
1096 alloc_ok ? "OK" : "FAIL");
1097 if (has_ep_out_view) audiod_fct_[i].ep_out_view = desc_ep_out;
1098 if (backend().usesIsoAlloc() && has_ep_out_view) {
1099 // Pre-activate during enumeration (no isochronous traffic).
1100 // Cannot be done in SET_INTERFACE because iso_activate blocks
1101 // on ESP32's DWC2 when the host is already sending. Activation
1102 // itself resets the endpoint's busy/claimed state to a known
1103 // (not busy) baseline, so nothing further is needed here for
1104 // the first open -- see closeEpOut() for why re-activation is
1105 // also needed on every subsequent re-open.
1106 backend().isoActivateEndpoint(rhport, desc_ep_out);
1107 LOGD("iso_activate OUT: done");
1108 }
1109 }
1110 if (isFeedbackEpEnabled() && ep_fb) {
1111 backend().isoAllocEndpoint(rhport, ep_fb, 4);
1112 }
1113 }
1114 // Scan for bclock_id_tx (clock entity referenced by the USB-streaming
1115 // terminal) and interval_tx. Runs in TX, RX, and RXTX mode so that
1116 // clock-validity/frequency GET requests always succeed.
1117 // TX/RXTX: Output Terminal type=USB_STREAMING → bCSourceID at [8]
1118 // RX: Input Terminal type=USB_STREAMING → bCSourceID at [7]
1119 // interval_tx is only meaningful for the ISO IN endpoint (TX/RXTX).
1120 if (isEpInEnabled() || isEpOutEnabled()) {
1121 uint8_t const* p_desc = audiod_fct_[i].p_desc;
1122 uint8_t const* p_desc_end =
1123 p_desc + audiod_fct_[i].desc_length - kAudioDescIadLen;
1124 while (p_desc_end - p_desc > 0) {
1125 if (descType(p_desc) == kUsbDescTypeEndpoint) {
1126 if (isEpInEnabled()) {
1127 UsbEndpointDescriptorView desc_ep = decodeEndpoint(p_desc);
1128 if (desc_ep.xferType == UsbXferType::Isochronous &&
1129 desc_ep.usage == 0 && desc_ep.direction() == UsbDir::In) {
1130 audiod_fct_[i].interval_tx = desc_ep.bInterval;
1131 }
1132 }
1133 } else if (descType(p_desc) == kUsbDescTypeCsInterface) {
1134 if (descSubtype(p_desc) == kAudioCsAcOutputTerminal) {
1135 if (descU16(p_desc + 4) == kAudioTermTypeUsbStreaming) {
1136 audiod_fct_[i].bclock_id_tx = p_desc[8]; // OT bCSourceID
1137 }
1138 } else if (descSubtype(p_desc) == kAudioCsAcInputTerminal) {
1139 if (descU16(p_desc + 4) == kAudioTermTypeUsbStreaming) {
1140 audiod_fct_[i].bclock_id_tx = p_desc[7]; // IT bCSourceID
1141 }
1142 }
1143 }
1144 p_desc = descNext(p_desc);
1145 }
1146 }
1147
1148 if (isInterruptEpEnabled()) {
1149 uint8_t const* p_desc = audiod_fct_[i].p_desc;
1150 uint8_t const* p_desc_end =
1151 p_desc + audiod_fct_[i].desc_length - kAudioDescIadLen;
1152 while (p_desc_end - p_desc > 0) {
1153 if (descType(p_desc) == kUsbDescTypeEndpoint) {
1154 UsbEndpointDescriptorView desc_ep = decodeEndpoint(p_desc);
1155 uint8_t const ep_addr = desc_ep.bEndpointAddress;
1156 if (desc_ep.direction() == UsbDir::In &&
1157 desc_ep.xferType == UsbXferType::Interrupt) {
1158 if (backend().openEndpoint(audiod_fct_[i].rhport, desc_ep)) {
1159 audiod_fct_[i].ep_int = ep_addr;
1160 } else {
1161 LOGE(" UAC2: interrupt EP 0x%02x open failed", ep_addr);
1162
1163 }
1164 }
1165 }
1166 p_desc = descNext(p_desc);
1167 }
1168 }
1169 audiod_fct_[i].mounted = true;
1170 break;
1171 }
1172 }
1173 if (i >= getAudioCount()) return 0;
1174 uint16_t drv_len = audiod_fct_[i].desc_length - kAudioDescIadLen;
1175 return drv_len;
1176 }
1177
1179 UsbSetupPacket const& request) {
1180 if (stage == kControlStageSetup) {
1181 return audiod_control_request(rhport, request);
1182 } else if (stage == kControlStageData) {
1183 return audiod_control_complete(rhport, request);
1184 }
1185 return true;
1186 }
1187 // Invoked when class request DATA stage is finished.
1188 // return false to stall control EP (e.g Host send non-sense DATA)
1190 UsbSetupPacket const& p_request) {
1191 // Handle audio class specific set requests
1192 if (p_request.type() == UsbSetupPacket::Type::Class &&
1193 p_request.direction() == UsbDir::Out) {
1194 uint8_t func_id;
1195
1196 switch (p_request.recipient()) {
1198 uint8_t itf = u16Low(p_request.wIndex);
1199 uint8_t entityID = u16High(p_request.wIndex);
1200
1201 if (entityID != 0) {
1202 func_id = 0;
1203 uint8_t ctrlSel = u16High(p_request.wValue);
1204 uint8_t* cb = audiod_fct_[func_id].ctrl_buf.data();
1205
1206 // ── Clock Source SET_CUR (sample rate) ──────────────
1208 ctrlSel == kAudioCsCtrlSamFreq &&
1209 p_request.bRequest == kAudioCsReqCur) {
1211 }
1212
1213 // ── Feature Unit SET_CUR (mute / volume) ────────────
1214 if (isFeatureUnit(entityID) &&
1215 p_request.bRequest == kAudioCsReqCur) {
1216 uint8_t channel = u16Low(p_request.wValue);
1217 if (ctrlSel == AUDIO_FU_CTRL_MUTE) {
1218 setMute(cb[0] != 0, channel);
1219 } else if (ctrlSel == AUDIO_FU_CTRL_VOLUME) {
1220 int16_t v;
1221 memcpy(&v, cb, 2);
1222 setVolume(uac2ToFloat(v), channel);
1223 }
1224 }
1225
1226 // Invoke callback
1228 return tud_audio_set_req_entity_cb_(this, rhport, p_request, cb);
1229 }
1230 } else {
1231 // Find index of audio driver structure and verify interface really
1232 // exists
1233 if (!audiod_verify_itf_exists(itf, &func_id)) return false;
1234
1235 // Invoke callback
1238 this, rhport, p_request,
1239 audiod_fct_[func_id].ctrl_buf.data());
1240 }
1241 }
1242 } break;
1243
1245 uint8_t ep = u16Low(p_request.wIndex);
1246
1247 // Check if entity is present and get corresponding driver index
1248 if (!audiod_verify_ep_exists(ep, &func_id)) return false;
1249
1250 // Invoke callback
1253 this, rhport, p_request, audiod_fct_[func_id].ctrl_buf.data());
1254 }
1255 } break;
1256 // Unknown/Unsupported recipient
1257 default:
1258 return false;
1259 }
1260 }
1261 return true;
1262 }
1263
1265 bool audiod_xfer_cb(uint8_t rhport, uint8_t ep_addr, UsbXferResult result,
1266 uint32_t xferred_bytes) {
1267 (void)result;
1268 (void)xferred_bytes;
1269 for (uint8_t func_id = 0; func_id < getAudioCount(); func_id++) {
1270 audiod_function_t* audio = &audiod_fct_[func_id];
1271 if (isInterruptEpEnabled() && audio->ep_int == ep_addr) {
1272 if (int_done_cb_) int_done_cb_(this, rhport);
1273 return true;
1274 }
1275 if (isEpInEnabled() && audio->ep_in == ep_addr &&
1276 audio->alt_setting.size() != 0) {
1278
1279 uint16_t frame_bytes = isEpInFlowControlEnabled()
1281 : audio->ep_in_sz;
1282 if (frame_bytes > audio->ep_in_sz) frame_bytes = audio->ep_in_sz;
1283 if (tx_done_cb_) tx_done_cb_(this, rhport, audio, frame_bytes);
1284
1285 tx_frame_bytes_last_ = frame_bytes;
1286 tx_xferred_last_ = xferred_bytes;
1287
1288 // Drain platform buffer into lin_buf_in, zero-pad, send via DMA.
1289 {
1290 uint8_t* dst = audio->lin_buf_in.data();
1291 uint16_t n = (uint16_t)bufferTx().readArray(dst, frame_bytes);
1293 if (n < frame_bytes) memset(dst + n, 0, frame_bytes - n);
1294 (void)backend().transfer(rhport, audio->ep_in, dst, frame_bytes);
1295 }
1296 return true;
1297 }
1298 if (isEpOutEnabled() && audio->ep_out == ep_addr) {
1300 rx_total_bytes_ += xferred_bytes;
1301 // Copy DMA-received data into the platform buffer, re-arm DMA.
1302 if (xferred_bytes > 0) {
1303 int written = bufferRx().writeArray(audio->lin_buf_out.data(),
1304 (int)xferred_bytes);
1305 if ((uint32_t)written < xferred_bytes)
1306 rx_dropped_bytes_ += xferred_bytes - (uint32_t)written;
1307 }
1308 // Re-arm the OUT endpoint before invoking the callback: rx_done_cb_
1309 // is user code (e.g. it may push the packet through a resampler)
1310 // and its duration is out of our control. If the next transfer
1311 // isn't queued until after it returns, a slow callback delays
1312 // re-arming past the next isochronous OUT window and the host's
1313 // packet for that frame is lost - audible as clicks/dropouts,
1314 // and more likely to happen the larger each packet is (e.g. at
1315 // 44.1/48kHz vs. 32kHz).
1316 (void)backend().transfer(rhport, audio->ep_out,
1317 audio->lin_buf_out.data(), audio->ep_out_sz);
1318 if (isFeedbackEpEnabled()) audiod_fb_kick(audio);
1319 if (rx_done_cb_)
1320 rx_done_cb_(this, rhport, audio, (uint16_t)xferred_bytes);
1321 return true;
1322 }
1323 if (isFeedbackEpEnabled() && audio->ep_fb_xfer == ep_addr) {
1324 // Queue the next feedback packet with the latest value (unless the
1325 // stream has closed), before the callback: see the OUT case above.
1326 audio->ep_fb_xfer = 0;
1327 audiod_fb_kick(audio);
1328 if (fb_done_cb_) fb_done_cb_(this, func_id);
1329 return true;
1330 }
1331 }
1332 return false;
1333 }
1334
1335 void audiod_sof_isr(uint8_t rhport, uint32_t frame_count) {
1336 (void)rhport;
1337 (void)frame_count;
1339 for (uint8_t i = 0; i < getAudioCount(); i++) {
1340 audiod_function_t* audio = &audiod_fct_[i];
1341 if (audio->ep_fb != 0) {
1342 uint8_t const hs_adjust = backend().isHighSpeed() ? 3 : 0;
1343 uint32_t const interval =
1344 1UL << (audio->feedback.frame_shift - hs_adjust);
1345 if (0 == (frame_count & (interval - 1))) {
1346 tud_audio_feedback_interval_isr(i, frame_count,
1347 audio->feedback.frame_shift);
1348 }
1349 }
1350 }
1351 }
1352 }
1353
1354 protected:
1355 // ── Clock Source GET handler ────────────────────────────────────────────
1357 UsbSetupPacket const& p_request,
1358 uint8_t* cb) {
1359 uint8_t ctrlSel = u16High(p_request.wValue);
1360 if (ctrlSel == kAudioCsCtrlClkValid &&
1361 p_request.bRequest == kAudioCsReqCur) {
1362 cb[0] = 1;
1363 return backend().controlTransfer(rhport, p_request, cb, 1);
1364 }
1365 if (ctrlSel == kAudioCsCtrlSamFreq) {
1367 if (p_request.bRequest == kAudioCsReqCur) {
1368 memcpy(cb, &rate, 4);
1369 return backend().controlTransfer(rhport, p_request, cb, 4);
1370 }
1371 if (p_request.bRequest == kAudioCsReqRange) {
1373 // List all supported discrete rates
1374 const auto& rates = config_.supported_sample_rates;
1375 uint16_t cnt = (uint16_t)rates.size();
1376 memcpy(cb, &cnt, 2);
1377 for (size_t i = 0; i < rates.size(); i++) {
1378 uint32_t r = rates[i];
1379 uint32_t z = 0;
1380 memcpy(cb + 2 + i * 12, &r, 4);
1381 memcpy(cb + 2 + i * 12 + 4, &r, 4);
1382 memcpy(cb + 2 + i * 12 + 8, &z, 4);
1383 }
1384 return backend().controlTransfer(
1385 rhport, p_request, cb,
1386 (uint16_t)(2 + rates.size() * 12));
1387 } else {
1388 // Single fixed rate from config
1389 uint16_t cnt = 1;
1390 uint32_t z = 0;
1391 memcpy(cb, &cnt, 2);
1392 memcpy(cb + 2, &rate, 4); // dMIN
1393 memcpy(cb + 6, &rate, 4); // dMAX
1394 memcpy(cb + 10, &z, 4); // dRES = 0 (fixed)
1395 return backend().controlTransfer(rhport, p_request, cb, 14);
1396 }
1397 }
1398 }
1399 return false;
1400 }
1401
1402 // ── Feature Unit GET handler ──────────────────────────────────────────
1404 UsbSetupPacket const& p_request,
1405 uint8_t* cb) {
1406 uint8_t ctrlSel = u16High(p_request.wValue);
1407 uint8_t channel = u16Low(p_request.wValue);
1408 if (ctrlSel == AUDIO_FU_CTRL_MUTE &&
1409 p_request.bRequest == kAudioCsReqCur) {
1410 cb[0] = isMute(channel) ? 1 : 0;
1411 return backend().controlTransfer(rhport, p_request, cb, 1);
1412 }
1413 if (ctrlSel == AUDIO_FU_CTRL_VOLUME) {
1414 if (p_request.bRequest == kAudioCsReqCur) {
1415 int16_t v = floatToUac2(volume(channel));
1416 memcpy(cb, &v, 2);
1417 return backend().controlTransfer(rhport, p_request, cb, 2);
1418 }
1419 if (p_request.bRequest == kAudioCsReqRange) {
1420 uint16_t cnt = 1;
1421 int16_t vmin = -25600, vmax = 0, vres = 256;
1422 memcpy(cb + 0, &cnt, 2);
1423 memcpy(cb + 2, &vmin, 2);
1424 memcpy(cb + 4, &vmax, 2);
1425 memcpy(cb + 6, &vres, 2);
1426 return backend().controlTransfer(rhport, p_request, cb, 8);
1427 }
1428 }
1429 return false;
1430 }
1431
1432 // ── Entity request handler (Clock Source + Feature Unit) ──────────────
1434 UsbSetupPacket const& p_request,
1435 uint8_t entityID) {
1436 uint8_t func_id = 0;
1437 uint8_t* cb = audiod_fct_[func_id].ctrl_buf.data();
1438 bool is_get = (p_request.direction() == UsbDir::In);
1439
1441 if (is_get && handleClockSourceGet(rhport, p_request, cb)) return true;
1442 // SET — schedule data receive for audiod_control_complete()
1443 return backend().controlTransfer(rhport, p_request, cb,
1444 audiod_fct_[func_id].ctrl_buf_sz);
1445 }
1446
1447 if (isFeatureUnit(entityID)) {
1448 if (is_get && handleFeatureUnitGet(rhport, p_request, cb)) return true;
1449 // SET — schedule data receive
1450 return backend().controlTransfer(rhport, p_request, cb,
1451 audiod_fct_[func_id].ctrl_buf_sz);
1452 }
1453
1454 // Unknown entity — try generic verify
1455 uint8_t itf = u16Low(p_request.wIndex);
1456 if (!audiod_verify_entity_exists(itf, entityID, &func_id)) {
1457 backend().controlStatus(rhport, p_request);
1458 return true;
1459 }
1460 if (is_get && req_entity_cb_) return req_entity_cb_(this, func_id);
1461 return backend().controlTransfer(rhport, p_request,
1462 audiod_fct_[func_id].ctrl_buf.data(),
1463 audiod_fct_[func_id].ctrl_buf_sz);
1464 }
1465
1466 // ── Interface request handler (entityID == 0) ─────────────────────────
1468 UsbSetupPacket const& p_request) {
1469 uint8_t itf = u16Low(p_request.wIndex);
1470 uint8_t func_id;
1471 if (!audiod_verify_itf_exists(itf, &func_id)) return false;
1472 if (p_request.direction() == UsbDir::In) {
1473 if (get_req_itf_cb_) return get_req_itf_cb_(this, rhport, p_request);
1474 return false;
1475 }
1476 return backend().controlTransfer(rhport, p_request,
1477 audiod_fct_[func_id].ctrl_buf.data(),
1478 audiod_fct_[func_id].ctrl_buf_sz);
1479 }
1480
1481 // ── Endpoint request handler ──────────────────────────────────────────
1483 UsbSetupPacket const& p_request) {
1484 uint8_t ep = u16Low(p_request.wIndex);
1485 uint8_t func_id;
1486 if (!audiod_verify_ep_exists(ep, &func_id)) return false;
1487 if (p_request.direction() == UsbDir::In) {
1488 if (get_req_ep_cb_) return get_req_ep_cb_(this, rhport, p_request);
1489 return false;
1490 }
1491 return backend().controlTransfer(rhport, p_request,
1492 audiod_fct_[func_id].ctrl_buf.data(),
1493 audiod_fct_[func_id].ctrl_buf_sz);
1494 }
1495
1496 // ── Main control request dispatcher ───────────────────────────────────
1498 UsbSetupPacket const& p_request) {
1499 if (p_request.type() == UsbSetupPacket::Type::Standard) {
1500 switch (p_request.bRequest) {
1502 return audiod_get_interface(rhport, p_request);
1504 return audiod_set_interface(rhport, p_request);
1506 return true;
1507 default:
1508 return false;
1509 }
1510 }
1511
1512 if (p_request.type() == UsbSetupPacket::Type::Class) {
1513 switch (p_request.recipient()) {
1515 uint8_t entityID = u16High(p_request.wIndex);
1516 return (entityID != 0)
1517 ? handleEntityRequest(rhport, p_request, entityID)
1518 : handleInterfaceRequest(rhport, p_request);
1519 }
1521 return handleEndpointRequest(rhport, p_request);
1522 default:
1523 return false;
1524 }
1525 }
1526
1527 return false;
1528 }
1529
1530 // Verify an entity with the given ID exists and returns also the
1531 // corresponding driver index
1533 uint8_t* func_id) {
1534 uint8_t i;
1535 for (i = 0; i < getAudioCount(); i++) {
1536 // Look for the correct driver by checking if the unique standard AC
1537 // interface number fits
1538 if (audiod_fct_[i].p_desc &&
1539 decodeInterface(audiod_fct_[i].p_desc).bInterfaceNumber == itf) {
1540 // Get pointers after class specific AC descriptors and end of AC
1541 // descriptors - entities are defined in between
1542 uint8_t const* p_desc =
1543 descNext(audiod_fct_[i].p_desc); // Points to CS AC descriptor
1544 // AC interface header wTotalLength lives at byte offset 6 (UAC2
1545 // Table 4-5: bLength,bDescriptorType,bDescriptorSubType,bcdADC(2),
1546 // bCategory,wTotalLength(2),bmControls).
1547 uint8_t const* p_desc_end = descU16(p_desc + 6) + p_desc;
1548 p_desc = descNext(p_desc); // Get past CS AC descriptor
1549
1550 // Condition modified from p_desc < p_desc_end to prevent gcc>=12
1551 // strict-overflow warning
1552 while (p_desc_end - p_desc > 0) {
1553 if (p_desc[3] == entityID) // Entity IDs are always at offset 3
1554 {
1555 *func_id = i;
1556 return true;
1557 }
1558 p_desc = descNext(p_desc);
1559 }
1560 }
1561 }
1562 return false;
1563 }
1564
1566 uint8_t i;
1567 for (i = 0; i < getAudioCount(); i++) {
1568 if (audiod_fct_[i].p_desc) {
1569 // Get pointer at end
1570 uint8_t const* p_desc_end =
1571 audiod_fct_[i].p_desc + audiod_fct_[i].desc_length;
1572
1573 // Advance past AC descriptors - EP we look for are streaming EPs
1574 uint8_t const* p_desc = descNext(audiod_fct_[i].p_desc);
1575 p_desc += descU16(p_desc + 6); // AC header wTotalLength, see above
1576
1577 // Condition modified from p_desc < p_desc_end to prevent gcc>=12
1578 // strict-overflow warning
1579 while (p_desc_end - p_desc > 0) {
1580 if (descType(p_desc) == kUsbDescTypeEndpoint &&
1581 decodeEndpoint(p_desc).bEndpointAddress == ep) {
1582 *func_id = i;
1583 return true;
1584 }
1585 p_desc = descNext(p_desc);
1586 }
1587 }
1588 }
1589 return false;
1590 }
1591
1593 uint8_t i;
1594 for (i = 0; i < getAudioCount(); i++) {
1595 if (audiod_fct_[i].p_desc) {
1596 // Get pointer at beginning and end
1597 uint8_t const* p_desc = audiod_fct_[i].p_desc;
1598 uint8_t const* p_desc_end = audiod_fct_[i].p_desc +
1599 audiod_fct_[i].desc_length -
1601 // Condition modified from p_desc < p_desc_end to prevent gcc>=12
1602 // strict-overflow warning
1603 while (p_desc_end - p_desc > 0) {
1604 if (descType(p_desc) == kUsbDescTypeInterface &&
1605 decodeInterface(audiod_fct_[i].p_desc).bInterfaceNumber == itf) {
1606 *func_id = i;
1607 return true;
1608 }
1609 p_desc = descNext(p_desc);
1610 }
1611 }
1612 }
1613 return false;
1614 }
1615
1617 uint8_t const* p_desc) {
1618 // Seed the TX sample rate from the configured AudioInfo so packet-size
1619 // calculation works even when the host never issues a SET_CUR(SAM_FREQ)
1620 // request (typical for single-frequency clock sources). The host may still
1621 // override this later via audiod_control_complete().
1622 if (audio->sample_rate_tx == 0)
1624
1625 p_desc = descNext(p_desc); // Exclude standard AS interface descriptor
1626 // of current alternate interface descriptor
1627
1628 // Look for a Class-Specific AS Interface Descriptor(4.9.2) to verify format
1629 // type and format and also to get number of physical channels.
1630 // Layout (UAC2 Table 4-27): bLength,bDescriptorType,bDescriptorSubType,
1631 // bTerminalLink,bmControls,bFormatType[5],bmFormats(4),bNrChannels[10],...
1632 if (descType(p_desc) == kUsbDescTypeCsInterface &&
1633 descSubtype(p_desc) == kAudioCsAsGeneral) {
1634 audio->n_channels_tx = p_desc[10];
1635 audio->format_type_tx = (audio_format_type_t)p_desc[5];
1636 // Look for a Type I Format Type Descriptor(2.3.1.6 - Audio Formats)
1637 // Layout: bLength,bDescriptorType,bDescriptorSubType,bFormatType,
1638 // bSubslotSize[4],bBitResolution.
1639 p_desc = descNext(p_desc);
1640 if (descType(p_desc) == kUsbDescTypeCsInterface &&
1641 descSubtype(p_desc) == kAudioCsAsFormatType &&
1642 p_desc[3] == AUDIO_FORMAT_TYPE_I) {
1643 audio->n_bytes_per_sample_tx = p_desc[4];
1644 }
1645 }
1646
1647 // Fallback from config if descriptor parsing missed any field.
1648 // The descriptor struct layout may differ across TinyUSB versions.
1649 if (audio->n_channels_tx == 0) audio->n_channels_tx = config_.channels;
1650 if (audio->n_bytes_per_sample_tx == 0)
1652 if (audio->format_type_tx == 0) audio->format_type_tx = AUDIO_FORMAT_TYPE_I;
1653 }
1654
1655 // This helper function finds for a given audio function and AS interface
1656 // number the index of the attached driver structure, the index of the
1657 // interface in the audio function
1658 // (e.g. the std. AS interface with interface number 15 is the first AS
1659 // interface for the given audio function and thus gets index zero), and
1660 // finally a pointer to the std. AS interface, where the pointer always points
1661 // to the first alternate setting i.e. alternate interface zero.
1663 uint8_t* idxItf,
1664 uint8_t const** pp_desc_int) {
1665 if (audio->p_desc) {
1666 // Get pointer at end
1667 uint8_t const* p_desc_end =
1668 audio->p_desc + audio->desc_length - kAudioDescIadLen;
1669
1670 // Advance past AC descriptors
1671 uint8_t const* p_desc = descNext(audio->p_desc);
1672 p_desc += descU16(p_desc + 6); // AC header wTotalLength
1673
1674 uint8_t tmp = 0;
1675 // Condition modified from p_desc < p_desc_end to prevent gcc>=12
1676 // strict-overflow warning
1677 while (p_desc_end - p_desc > 0) {
1678 // We assume the number of alternate settings is increasing thus we
1679 // return the index of alternate setting zero!
1680 if (descType(p_desc) == kUsbDescTypeInterface &&
1681 decodeInterface(p_desc).bAlternateSetting == 0) {
1682 if (decodeInterface(p_desc).bInterfaceNumber == itf) {
1683 *idxItf = tmp;
1684 *pp_desc_int = p_desc;
1685 return true;
1686 }
1687 // Increase index, bytes read, and pointer
1688 tmp++;
1689 }
1690 p_desc = descNext(p_desc);
1691 }
1692 }
1693 return false;
1694 }
1695
1696 // This helper function finds for a given AS interface number the index of the
1697 // attached driver structure, the index of the interface in the audio function
1698 // (e.g. the std. AS interface with interface number 15 is the first AS
1699 // interface for the given audio function and thus gets index zero), and
1700 // finally a pointer to the std. AS interface, where the pointer always points
1701 // to the first alternate setting i.e. alternate interface zero.
1703 uint8_t* idxItf,
1704 uint8_t const** pp_desc_int) {
1705 // Loop over audio driver interfaces
1706 uint8_t i;
1707 for (i = 0; i < getAudioCount(); i++) {
1708 if (audiod_get_AS_interface_index(itf, &audiod_fct_[i], idxItf,
1709 pp_desc_int)) {
1710 *func_id = i;
1711 return true;
1712 }
1713 }
1714
1715 return false;
1716 }
1717
1719 UsbSetupPacket const& p_request) {
1720 uint8_t const itf = u16Low(p_request.wIndex);
1721
1722 // Find index of audio streaming interface
1723 uint8_t func_id, idxItf;
1724 uint8_t const* dummy;
1725
1726 if (!audiod_get_AS_interface_index_global(itf, &func_id, &idxItf, &dummy))
1727 return false;
1728 if (!backend().controlTransfer(
1729 rhport, p_request, &audiod_fct_[func_id].alt_setting[idxItf], 1))
1730 return false;
1731
1732 LOGI(" Get itf: %u - current alt: %u", itf,
1733 audiod_fct_[func_id].alt_setting[idxItf]);
1734
1735 return true;
1736 }
1737
1739 bool apply_correction =
1741 // Format the feedback value
1742 if (apply_correction) {
1743 uint8_t* fb = (uint8_t*)audio->fb_buf.data();
1744
1745 // For FS format is 10.14
1746 *(fb++) = (audio->feedback.value >> 2) & 0xFF;
1747 *(fb++) = (audio->feedback.value >> 10) & 0xFF;
1748 *(fb++) = (audio->feedback.value >> 18) & 0xFF;
1749 *fb = 0;
1750 } else {
1751 audio->fb_buf[0] = audio->feedback.value;
1752 }
1753
1754 // About feedback format on FS
1755 //
1756 // 3 variables: Format | packetSize | sendSize | Working OS:
1757 // 16.16 4 4 Linux, Windows
1758 // 16.16 4 3 Linux
1759 // 16.16 3 4 Linux
1760 // 16.16 3 3 Linux
1761 // 10.14 4 4 Linux
1762 // 10.14 4 3 Linux
1763 // 10.14 3 4 Linux, OSX
1764 // 10.14 3 3 Linux, OSX
1765 //
1766 // We send 3 bytes since sending packet larger than wMaxPacketSize is pretty
1767 // ugly
1768 return backend().transfer(audio->rhport, audio->ep_fb,
1769 (uint8_t*)audio->fb_buf.data(),
1770 apply_correction ? 3 : 4);
1771 }
1772
1773 // ── Close existing EPs for this interface ──────────────────────────────
1774 void closeEpIn(uint8_t rhport, audiod_function_t* audio, uint8_t itf,
1775 UsbSetupPacket const& p_request) {
1776 if (!isEpInEnabled() || audio->ep_in_as_intf_num != itf) return;
1777 audio->ep_in_as_intf_num = 0;
1778 if (!backend().usesIsoAlloc()) backend().closeEndpoint(rhport, audio->ep_in);
1779 bufferTx().reset();
1781 tud_audio_set_itf_close_EP_cb_(this, rhport, p_request);
1782 audio->ep_in = 0;
1784 audio->packet_sz_tx[0] = 0;
1785 audio->packet_sz_tx[1] = 0;
1786 audio->packet_sz_tx[2] = 0;
1787 }
1789 }
1790
1792 UsbSetupPacket const& p_request) {
1793 if (!isEpOutEnabled() || audio->ep_out_as_intf_num != itf) return;
1794 audio->ep_out_as_intf_num = 0;
1795 if (!backend().usesIsoAlloc()) {
1796 backend().closeEndpoint(rhport, audio->ep_out);
1797 } else {
1798 // usesIsoAlloc() backends never close the OUT endpoint between
1799 // sessions (DPRAM stays allocated), so nothing resets the DCD's
1800 // internal busy/claimed bookkeeping for it. If the transfer armed by
1801 // the *previous* openEpOut() never completed (no host data arrived,
1802 // or the session was torn down mid-flight), that endpoint stays
1803 // "busy" forever and every later usbd_edpt_xfer() call in openEpOut()
1804 // silently fails, permanently breaking RX after the first
1805 // open/close cycle. Re-activating here -- while the host is quiet
1806 // (it just asked to close the stream) rather than right as a new
1807 // session starts -- resets busy/claimed to a known-good state for
1808 // the next open, matching the reasoning in audiod_open() for why
1809 // this can't be done at SET_INTERFACE(alt=1) time instead.
1810 backend().isoActivateEndpoint(rhport, audio->ep_out_view);
1811 }
1813 tud_audio_set_itf_close_EP_cb_(this, rhport, p_request);
1814 audio->ep_out = 0;
1815 if (isFeedbackEpEnabled()) {
1816 audio->ep_fb = 0;
1817 memset(&audio->feedback, 0, sizeof(audio->feedback));
1818 }
1820 }
1821
1822 // ── Activate a single endpoint found in the descriptor ────────────────
1824 UsbDir dir = UsbDir::In) {
1825 if (backend().usesIsoAlloc()) {
1826 // Skip iso_activate for isochronous OUT — on ESP32's DWC2 it blocks
1827 // for the entire playback duration. The endpoint DPRAM was already
1828 // allocated by iso_alloc in audiod_open(). The XFER call in
1829 // openEpOut will configure the DCD to receive.
1830 if (dir == UsbDir::Out && desc_ep.xferType == UsbXferType::Isochronous)
1831 return true;
1832 return backend().isoActivateEndpoint(rhport, desc_ep);
1833 }
1834 (void)dir;
1835 return backend().openEndpoint(rhport, desc_ep);
1836 }
1837
1838 // ── Open the IN (TX) data endpoint ────────────────────────────────────
1839 void openEpIn(uint8_t rhport, audiod_function_t* audio, uint8_t itf,
1840 const UsbEndpointDescriptorView& desc_ep,
1841 uint8_t const* p_desc_for_params) {
1842 audio->ep_in = desc_ep.bEndpointAddress;
1843 audio->ep_in_as_intf_num = itf;
1844 audio->ep_in_sz = desc_ep.packetSize();
1845 if (audio->ep_in_sz == 0) return;
1846
1848 audiod_parse_flow_control_params(audio, p_desc_for_params);
1849
1850 // Arm initial transfer (silence — copier fills the buffer).
1851 uint16_t first_pkt = packetSize();
1852 if (first_pkt > audio->ep_in_sz) first_pkt = audio->ep_in_sz;
1853 audio->lin_buf_in.assign(audio->ep_in_sz, 0);
1854 tx_xfer_armed_ = backend().transfer(rhport, audio->ep_in,
1855 audio->lin_buf_in.data(), first_pkt);
1857 }
1858
1859 // ── Open the OUT (RX) data endpoint ───────────────────────────────────
1860 void openEpOut(uint8_t rhport, audiod_function_t* audio, uint8_t itf,
1861 const UsbEndpointDescriptorView& desc_ep) {
1862 audio->ep_out = desc_ep.bEndpointAddress;
1863 audio->ep_out_as_intf_num = itf;
1864 audio->ep_out_sz = desc_ep.packetSize();
1865 if (audio->ep_out_sz == 0) return;
1866
1867 // iso_activate was done in audiod_open() (no traffic, instant).
1868 // Just arm the transfer here.
1869 if (audio->lin_buf_out.size() < audio->ep_out_sz)
1870 audio->lin_buf_out.assign(audio->ep_out_sz, 0);
1871 backend().transfer(rhport, audio->ep_out, audio->lin_buf_out.data(),
1872 audio->ep_out_sz);
1874 }
1875
1876 // ── Open the explicit feedback endpoint ───────────────────────────────
1878 const UsbEndpointDescriptorView& desc_ep) {
1879 audio->ep_fb = desc_ep.bEndpointAddress;
1880 audio->feedback.frame_shift = desc_ep.bInterval - 1;
1881 // Activating the endpoint (just done) aborted any transfer still queued
1882 // from the last time the stream was open.
1883 audio->ep_fb_xfer = 0;
1884 }
1885
1886 // ── Configure feedback computation parameters ─────────────────────────
1887 void setupFeedback(audiod_function_t* audio, uint8_t func_id, uint8_t alt) {
1888 if (!isFeedbackEpEnabled() || audio->ep_fb == 0) return;
1889
1890 audio_feedback_params_t fb_param = {};
1892 fb_param.sample_freq = config_.sample_rate;
1894 tud_audio_feedback_params_cb_(this, func_id, alt, &fb_param);
1895 audio->feedback.compute_method = fb_param.method;
1896
1900
1901 uint32_t const frame_div = backend().isFullSpeed() ? 1000 : 8000;
1902 audio->feedback.min_value = ((fb_param.sample_freq - 1) / frame_div) << 16;
1903 audio->feedback.max_value = (fb_param.sample_freq / frame_div + 1) << 16;
1904 audio->feedback.nom_value =
1905 (uint32_t)(((uint64_t)fb_param.sample_freq << 16) / frame_div);
1906 if (manual_feedback_ppm_ != INT32_MIN)
1907 audio->feedback.ppm_offset =
1909
1910 switch (fb_param.method) {
1914 audiod_set_fb_params_freq(audio, fb_param.sample_freq,
1915 fb_param.frequency.mclk_freq);
1916 break;
1918 // Use bufferRx() size — ep_out_ff may be uninitialized in linear buffer mode
1919 uint16_t fifo_depth = bufferRx().size();
1920 if (fifo_depth == 0) fifo_depth = 1; // guard against div-by-zero
1921 uint16_t fifo_lvl_thr = fifo_depth / 2;
1922 audio->feedback.compute.fifo_count.fifo_lvl_thr = fifo_lvl_thr;
1923 // fifo_lvl_avg is a Q8 exponential moving average (see the update
1924 // formula in tud_audio_feedback_interval_isr: `avg = fifo_lvl_avg
1925 // >> 8`, fed by `ff_count << 8` each tick) -- seed it in the same
1926 // Q8 scale. It was previously seeded as `fifo_lvl_thr << 16` (Q16,
1927 // 256x too large), which pinned the very first ~1400 feedback
1928 // updates (~1.4s at 1kHz) at feedback.max_value before decaying
1929 // into a sane range.
1931 ((uint32_t)fifo_lvl_thr) << 8;
1932 uint32_t nominal =
1933 ((fb_param.sample_freq / 100) << 16) / (frame_div / 100);
1934 audio->feedback.compute.fifo_count.nom_value = nominal;
1936 (uint16_t)((audio->feedback.max_value - nominal) / fifo_lvl_thr);
1938 (uint16_t)((nominal - audio->feedback.min_value) / fifo_lvl_thr);
1939 if (backend().isHighSpeed()) {
1940 audio->feedback.compute.fifo_count.rate_const[0] /= 8;
1941 audio->feedback.compute.fifo_count.rate_const[1] /= 8;
1942 }
1943 } break;
1944 default:
1945 break;
1946 }
1947 }
1948
1949 // ── Scan descriptor for endpoints and open them ───────────────────────
1951 uint8_t func_id, uint8_t itf, uint8_t alt) {
1952 uint8_t const* p_desc = audio->p_desc;
1953 uint8_t const* p_desc_end =
1954 p_desc + audio->desc_length - kAudioDescIadLen;
1955 LOGD(" openEPs: p_desc=%p end=%p len=%u itf=%u alt=%u",
1956 p_desc, p_desc_end, audio->desc_length, itf, alt);
1957
1958 while (p_desc_end - p_desc > 0) {
1959 if (descType(p_desc) == kUsbDescTypeInterface &&
1960 decodeInterface(p_desc).bInterfaceNumber == itf &&
1961 decodeInterface(p_desc).bAlternateSetting == alt) {
1962 uint8_t const* p_desc_for_params =
1963 (isEpInEnabled() && isEpInFlowControlEnabled()) ? p_desc : nullptr;
1964 uint8_t foundEPs = 0;
1965 uint8_t nEps = decodeInterface(p_desc).bNumEndpoints;
1966 LOGD(" matched itf=%u alt=%u nEps=%u", itf, alt, nEps);
1967
1968 while (foundEPs < nEps && (p_desc_end - p_desc > 0)) {
1969 LOGD(" scan: type=0x%02x len=%u offset=%d",
1970 p_desc[1], p_desc[0], (int)(p_desc - audio->p_desc));
1971 if (descType(p_desc) == kUsbDescTypeEndpoint) {
1972 UsbEndpointDescriptorView desc_ep = decodeEndpoint(p_desc);
1973
1974 LOGD(" activating ep=0x%02x type=%u...",
1975 desc_ep.bEndpointAddress, (unsigned)desc_ep.xferType);
1976 if (!activateEndpoint(rhport, desc_ep, desc_ep.direction())) {
1977 LOGD(" activateEndpoint FAILED");
1978 p_desc = descNext(p_desc);
1979 continue;
1980 }
1981 LOGD(" activated OK");
1982 // Skip clear_stall for isochronous OUT (iso_activate was also
1983 // skipped). For other endpoints, clear the stall as usual.
1984 if (!(desc_ep.direction() == UsbDir::Out &&
1986 backend().clearStall(rhport, desc_ep.bEndpointAddress);
1987
1988 uint8_t ep_addr = desc_ep.bEndpointAddress;
1989 if (isEpInEnabled() && desc_ep.direction() == UsbDir::In &&
1990 desc_ep.usage == 0x00)
1991 openEpIn(rhport, audio, itf, desc_ep, p_desc_for_params);
1992
1993 if (isEpOutEnabled()) {
1994 if (desc_ep.direction() == UsbDir::Out)
1995 openEpOut(rhport, audio, itf, desc_ep);
1996 if (isFeedbackEpEnabled() &&
1997 desc_ep.direction() == UsbDir::In && desc_ep.usage == 1)
1998 openEpFeedback(audio, desc_ep);
1999 }
2000 foundEPs += 1;
2001 }
2002 p_desc = descNext(p_desc);
2003 }
2004
2005 if (foundEPs != nEps) return true; // ZLP already sent
2006
2008 tud_audio_set_itf_cb_(this, rhport, UsbSetupPacket{});
2009
2010 setupFeedback(audio, func_id, alt);
2011 // Start the feedback transfers when the OUT stream opens; each
2012 // completion queues the next. Until the SOF interrupt has computed
2013 // a value, send the nominal one.
2014 if (isFeedbackEpEnabled() && audio->ep_fb &&
2015 audio->ep_out_as_intf_num == itf) {
2016 if (audio->feedback.value == 0)
2017 audio->feedback.value = audio->feedback.nom_value;
2018 audiod_fb_kick(audio);
2019 }
2020 return true;
2021 }
2022 p_desc = descNext(p_desc);
2023 }
2024 return true;
2025 }
2026
2027 // ── Main SET_INTERFACE handler ────────────────────────────────────────
2029 UsbSetupPacket const& p_request) {
2030 uint8_t const itf = u16Low(p_request.wIndex);
2031 uint8_t const alt = u16Low(p_request.wValue);
2032 LOGD("SET_ITF itf=%u alt=%u [start]", itf, alt);
2033
2034 uint8_t func_id, idxItf;
2035 uint8_t const* p_desc;
2036 if (!audiod_get_AS_interface_index_global(itf, &func_id, &idxItf,
2037 &p_desc)) {
2038 LOGD(" AS interface %u not found", itf);
2039 backend().controlStatus(rhport, p_request);
2040 return true;
2041 }
2042 LOGD(" found func=%u idx=%u", func_id, idxItf);
2043
2044 audiod_function_t* audio = &audiod_fct_[func_id];
2045
2046 // 1. Close existing EPs
2047 LOGD(" close EPs");
2048 closeEpIn(rhport, audio, itf, p_request);
2049 closeEpOut(rhport, audio, itf, p_request);
2050
2051 // 2. Save alt setting and acknowledge
2052 audio->alt_setting[idxItf] = alt;
2053
2054 backend().controlStatus(rhport, p_request);
2055 openEndpointsForAltSetting(rhport, audio, func_id, itf, alt);
2056
2057 // 4. Update SOF and flow control
2058 if (isFeedbackEpEnabled()) {
2059 bool enable_sof = false;
2060 for (uint8_t i = 0; i < getAudioCount(); i++) {
2061 if (audiod_fct_[i].ep_fb != 0) {
2062 enable_sof = true;
2063 break;
2064 }
2065 }
2066 backend().enableSof(rhport, enable_sof);
2067 }
2070
2071 return true;
2072 }
2073
2074 static bool isPowerOfTwo(uint32_t value) {
2075 return value != 0 && (value & (value - 1)) == 0;
2076 }
2077
2079 uint8_t result = 0;
2080 while ((value >>= 1u) != 0u) result++;
2081 return result;
2082 }
2083
2085 uint32_t mclk_freq) {
2086 // Check if frame interval is within sane limits
2087 // The interval value n_frames was taken from the descriptors within
2088
2089 // n_frames_min is ceil(2^10 * f_s / f_m) for full speed and ceil(2^13 * f_s
2090 // / f_m) for high speed this lower limit ensures the measures feedback
2091 // value has sufficient precision
2092 uint32_t const k = backend().isFullSpeed() ? 10 : 13;
2093 uint32_t const n_frame = (1UL << audio->feedback.frame_shift);
2094
2095 if ((((1UL << k) * sample_freq / mclk_freq) + 1) > n_frame) {
2096 LOGE(" UAC2 feedback interval too small");
2097 return false;
2098 }
2099
2100 // Check if parameters really allow for a power of two division
2101 if ((mclk_freq % sample_freq) == 0 &&
2102 isPowerOfTwo(mclk_freq / sample_freq)) {
2103 audio->feedback.compute_method =
2105 audio->feedback.compute.power_of_2 =
2106 (uint8_t)(16 - (audio->feedback.frame_shift - 1) -
2107 log2Floor(mclk_freq / sample_freq));
2108 } else if (audio->feedback.compute_method ==
2111 (float)sample_freq / (float)mclk_freq *
2112 (1UL << (16 - (audio->feedback.frame_shift - 1)));
2113 } else {
2114 audio->feedback.compute.fixed.sample_freq = sample_freq;
2115 audio->feedback.compute.fixed.mclk_freq = mclk_freq;
2116 }
2117
2118 return true;
2119 }
2120
2122 if (audio->format_type_tx != AUDIO_FORMAT_TYPE_I) return false;
2123 if (!audio->n_channels_tx) return false;
2124 if (!audio->n_bytes_per_sample_tx) return false;
2125 if (!audio->interval_tx) return false;
2126 if (!audio->sample_rate_tx) return false;
2127
2128 // Restart the fractional accumulator for this streaming session.
2129 audio->tx_sample_acc = 0;
2130 tx_rate_holdoff_ = 0;
2131 tx_rate_armed_ = false;
2132
2133 bool full_speed = backend().isFullSpeed();
2134 const uint8_t interval =
2135 full_speed ? audio->interval_tx : 1 << (audio->interval_tx - 1);
2136
2137 const uint16_t sample_normimal = (uint16_t)(audio->sample_rate_tx *
2138 interval / (full_speed ? 1000 : 8000));
2139 const uint16_t sample_reminder = (uint16_t)(audio->sample_rate_tx *
2140 interval % (full_speed ? 1000 : 8000));
2141
2142 const uint16_t packet_sz_tx_min =
2143 (uint16_t)((sample_normimal - 1) * audio->n_channels_tx *
2144 audio->n_bytes_per_sample_tx);
2145 const uint16_t packet_sz_tx_norm =
2146 (uint16_t)(sample_normimal * audio->n_channels_tx *
2147 audio->n_bytes_per_sample_tx);
2148 const uint16_t packet_sz_tx_max =
2149 (uint16_t)((sample_normimal + 1) * audio->n_channels_tx *
2150 audio->n_bytes_per_sample_tx);
2151
2152 // Endpoint size must larger than packet size
2153 if (packet_sz_tx_max > audio->ep_in_sz) return false;
2154
2155 // Frmt20.pdf 2.3.1.1 USB Packets
2156 if (sample_reminder) {
2157 // All virtual frame packets must either contain INT(nav) audio slots
2158 // (small VFP) or INT(nav)+1 (large VFP) audio slots
2159 audio->packet_sz_tx[0] = packet_sz_tx_norm;
2160 audio->packet_sz_tx[1] = packet_sz_tx_norm;
2161 audio->packet_sz_tx[2] = packet_sz_tx_max;
2162 } else {
2163 // In the case where nav = INT(nav), ni may vary between INT(nav)-1 (small
2164 // VFP), INT(nav) (medium VFP) and INT(nav)+1 (large VFP).
2165 audio->packet_sz_tx[0] = packet_sz_tx_min;
2166 audio->packet_sz_tx[1] = packet_sz_tx_norm;
2167 audio->packet_sz_tx[2] = packet_sz_tx_max;
2168 }
2169
2170 return true;
2171 }
2172
2173 // Number of audio bytes to transmit in the current (micro)frame when IN
2174 // flow control is enabled. A fractional accumulator distributes the
2175 // sub-frame sample remainder over successive frames so the long-term average
2176 // matches the configured sample rate (e.g. alternating 176/180 bytes for
2177 // 44100 Hz stereo 16-bit, averaging 176.4 bytes = 44.1 samples per frame).
2179 if (audio->sample_rate_tx == 0 || audio->n_channels_tx == 0 ||
2180 audio->n_bytes_per_sample_tx == 0) {
2181 // Not enough info to size precisely: fall back to the max packet.
2182 return audio->ep_in_sz;
2183 }
2184 bool full_speed = backend().isFullSpeed();
2185 const uint32_t denom = full_speed ? 1000u : 8000u;
2186 const uint8_t iv = audio->interval_tx ? audio->interval_tx : 1;
2187 const uint32_t interval = full_speed ? iv : (1u << (iv - 1));
2188
2189 audio->tx_sample_acc += audio->sample_rate_tx * interval;
2190 uint32_t samples = audio->tx_sample_acc / denom;
2191 audio->tx_sample_acc -= samples * denom;
2192
2193 const uint32_t frame_bytes =
2194 audio->n_channels_tx * audio->n_bytes_per_sample_tx;
2196 // Asynchronous IN: the application writes bufferTx() at the device's
2197 // clock, which differs slightly from the host's. Follow it by sending
2198 // one sample more when the buffer is above half full, one less when
2199 // below. Corrections start once the buffer has first filled to half
2200 // (so not while the application is still filling it), and use the
2201 // smoothed level (so not on the jitter from the application writing
2202 // in blocks). The hold-off, longer than the smoothing's time
2203 // constant, stops a correction being repeated before the average
2204 // shows it, and limits the rate to 1 sample per 33 packets, ie:
2205 // 630 ppm at 48 kHz, far more than any crystal's error.
2206 const int32_t level = (int32_t)(bufferTx().available() / frame_bytes);
2207 const int32_t target = (int32_t)(bufferTx().size() / frame_bytes / 2);
2208 if (!tx_rate_armed_) {
2209 if (level >= target) {
2210 tx_rate_armed_ = true;
2211 tx_level_avg_ = level * 256;
2212 }
2213 } else {
2214 // Exponential moving average, time constant 16 packets.
2215 tx_level_avg_ += (level * 256 - tx_level_avg_) / 16;
2216 if (tx_rate_holdoff_) {
2218 } else if (tx_level_avg_ > (target + 1) * 256) {
2219 samples++;
2220 tx_rate_holdoff_ = 32;
2221 } else if (tx_level_avg_ < (target - 1) * 256 && samples > 1) {
2222 samples--;
2223 tx_rate_holdoff_ = 32;
2224 }
2225 }
2226 }
2227
2228 uint32_t bytes = samples * frame_bytes;
2229 if (bytes > audio->ep_in_sz) bytes = audio->ep_in_sz;
2230 return (uint16_t)bytes;
2231 }
2232
2233};
2234
2235} // namespace audio_tools
#define LOGW(...)
Definition AudioLoggerIDF.h:29
#define LOGI(...)
Definition AudioLoggerIDF.h:28
#define LOGD(...)
Definition AudioLoggerIDF.h:27
#define LOGE(...)
Definition AudioLoggerIDF.h:30
#define USB_DESCR_MAX_LEN
Definition USBAudioDeviceBase.h:49
void notifyAudioChange(AudioInfo info)
Definition AudioTypes.h:180
AudioInfo info
Definition BaseStream.h:171
virtual void setAudioInfo(AudioInfo newInfo) override
Defines the input AudioInfo.
Definition BaseStream.h:128
virtual int readArray(T data[], int len)
reads multiple values
Definition Buffers.h:34
virtual void reset()=0
clears the buffer
virtual int writeArray(const T data[], int len)
Fills the buffer data.
Definition Buffers.h:56
virtual size_t size()=0
virtual int available()=0
provides the number of entries that are available to read
USB Audio Class 2.0 descriptor generator.
Definition USBAudio2DescriptorBuilder.h:29
const uint16_t buildFullDescriptor(uint8_t *desc)
Definition USBAudio2DescriptorBuilder.h:53
static constexpr uint8_t ENTITY_FU2
second Feature Unit (RXTX)
Definition USBAudio2DescriptorBuilder.h:39
static constexpr uint8_t ENTITY_FU1
first Feature Unit
Definition USBAudio2DescriptorBuilder.h:36
int audioFunctionsCount() const
Definition USBAudio2DescriptorBuilder.h:144
static constexpr uint8_t ENTITY_CLOCK
Definition USBAudio2DescriptorBuilder.h:34
uint16_t calcPacketSizeForRate(uint32_t rate) const
Definition USBAudio2DescriptorBuilder.h:169
uint16_t calcMaxPacketSize() const
Definition USBAudio2DescriptorBuilder.h:181
bool enableFeedbackEp() const
Definition USBAudio2DescriptorBuilder.h:159
Abstract seam for every raw USB-stack call the UAC2 driver (USBAudioDeviceBase) needs....
Definition USBAudioBackend.h:160
virtual bool isoActivateEndpoint(uint8_t rhport, const UsbEndpointDescriptorView &ep)=0
virtual bool controlTransfer(uint8_t rhport, const UsbSetupPacket &request, uint8_t *buffer, uint16_t length)=0
Complete a GET/SET control transfer's data stage with buffer.
virtual bool releaseEndpoint(uint8_t rhport, uint8_t ep_addr)=0
bool isFullSpeed() const
Convenience: speed() == UsbSpeed::Full.
Definition USBAudioBackend.h:218
virtual bool closeEndpoint(uint8_t rhport, uint8_t ep_addr)=0
virtual bool openEndpoint(uint8_t rhport, const UsbEndpointDescriptorView &ep)=0
virtual bool controlStatus(uint8_t rhport, const UsbSetupPacket &request)=0
Send a zero-length-packet status acknowledgement.
virtual bool usesIsoAlloc() const =0
virtual bool transfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t length)=0
bool isHighSpeed() const
Convenience: speed() == UsbSpeed::High.
Definition USBAudioBackend.h:220
virtual bool clearStall(uint8_t rhport, uint8_t ep_addr)=0
Clear a halted/stalled condition on an endpoint.
virtual bool mounted() const =0
True once the device has completed USB enumeration.
virtual void enableSof(uint8_t rhport, bool enable)=0
virtual bool isoAllocEndpoint(uint8_t rhport, uint8_t ep_addr, uint16_t max_packet_size)=0
USB Audio Device class for audio streaming over USB.
Definition USBAudioDeviceBase.h:68
std::function< void(USBAudioDeviceBase *, uint8_t func_id, uint8_t alt_itf, audio_feedback_params_t *feedback_param)> tud_audio_feedback_params_cb_
Definition USBAudioDeviceBase.h:728
bool begin(const USBAudioConfig &cfg)
Apply a config and start the USB audio device.
Definition USBAudioDeviceBase.h:278
std::function< bool(USBAudioDeviceBase *, uint8_t rhport, UsbSetupPacket const &p_request)> tud_audio_set_itf_cb_
Definition USBAudioDeviceBase.h:709
void setRxDoneCallback(std::function< bool(USBAudioDeviceBase *, uint8_t, audiod_function_t *, uint16_t)> cb)
Register a callback for RX done events.
Definition USBAudioDeviceBase.h:447
volatile uint32_t xfer_cb_rx_count_
Definition USBAudioDeviceBase.h:682
volatile uint32_t xfer_cb_tx_count_
Definition USBAudioDeviceBase.h:680
USBAudioDeviceBase(USBAudioConfig cfg)
Constructor which provides configuration at construction time.
Definition USBAudioDeviceBase.h:205
bool audiod_control_xfer_cb(uint8_t rhport, uint8_t stage, UsbSetupPacket const &request)
Definition USBAudioDeviceBase.h:1178
bool handleInterfaceRequest(uint8_t rhport, UsbSetupPacket const &p_request)
Definition USBAudioDeviceBase.h:1467
void audiod_sof_isr(uint8_t rhport, uint32_t frame_count)
Definition USBAudioDeviceBase.h:1335
bool audiod_fb_send(audiod_function_t *audio)
Definition USBAudioDeviceBase.h:1738
bool audiod_set_interface(uint8_t rhport, UsbSetupPacket const &p_request)
Definition USBAudioDeviceBase.h:2028
void onVolumeChanged(uint8_t channel) override
Notify the host about a device-initiated volume change.
Definition USBAudioDeviceBase.h:805
void setReqEntityCallback(std::function< bool(USBAudioDeviceBase *, uint8_t)> cb)
Register a callback for entity requests.
Definition USBAudioDeviceBase.h:457
std::function< bool(USBAudioDeviceBase *, uint8_t rhport, UsbSetupPacket const &p_request, uint8_t *pBuff)> tud_audio_set_req_itf_cb_
Definition USBAudioDeviceBase.h:716
bool isFeatureUnit(uint8_t id) const
Returns true if the given entity ID is a Feature Unit (FU1 or FU2).
Definition USBAudioDeviceBase.h:818
uint8_t tx_rate_holdoff_
Definition USBAudioDeviceBase.h:742
void setAudioFeedbackFormatCorrectionCallback(std::function< bool(USBAudioDeviceBase *, uint8_t)> cb)
Register a callback for audio feedback format correction events.
Definition USBAudioDeviceBase.h:531
uint16_t audiod_open(uint8_t rhport, UsbInterfaceDescriptorView const &itf_desc, uint8_t const *raw_desc, uint16_t max_len)
Definition USBAudioDeviceBase.h:1036
uint32_t getTxSampleRate() const
TX sample rate parsed from the descriptor (must be non-zero for flow control).
Definition USBAudioDeviceBase.h:660
std::function< void(USBAudioDeviceBase *, uint8_t func_id)> fb_done_cb_
Definition USBAudioDeviceBase.h:705
void openEpIn(uint8_t rhport, audiod_function_t *audio, uint8_t itf, const UsbEndpointDescriptorView &desc_ep, uint8_t const *p_desc_for_params)
Definition USBAudioDeviceBase.h:1839
void closeEpOut(uint8_t rhport, audiod_function_t *audio, uint8_t itf, UsbSetupPacket const &p_request)
Definition USBAudioDeviceBase.h:1791
volatile int32_t manual_feedback_ppm_
Definition USBAudioDeviceBase.h:740
void setGetReqEpCallback(std::function< bool(USBAudioDeviceBase *, uint8_t, UsbSetupPacket const &)> cb)
Register a callback for GET requests on an endpoint.
Definition USBAudioDeviceBase.h:410
void setTxDoneCallback(std::function< bool(USBAudioDeviceBase *, uint8_t, audiod_function_t *, uint16_t)> cb)
Register a callback for TX done events.
Definition USBAudioDeviceBase.h:437
bool isStreamingActiveTx() const override
Returns true if the host has opened the IN (capture) stream.
Definition USBAudioDeviceBase.h:373
bool audiod_get_AS_interface_index_global(uint8_t itf, uint8_t *func_id, uint8_t *idxItf, uint8_t const **pp_desc_int)
Definition USBAudioDeviceBase.h:1702
static USBAudioDeviceBase * s_active_
Definition USBAudioDeviceBase.h:757
virtual USBAudioBackend & backend()=0
Returns the backend used for all raw USB-stack calls (TinyUSB today, or a future native-HAL backend)....
std::function< bool(USBAudioDeviceBase *, uint8_t rhport, UsbSetupPacket const &)> get_req_ep_cb_
Definition USBAudioDeviceBase.h:702
int16_t manual_feedback_percent_
Definition USBAudioDeviceBase.h:738
uint16_t getDescLen(uint8_t fn) const
Definition USBAudioDeviceBase.h:852
void audiod_parse_flow_control_params(audiod_function_t *audio, uint8_t const *p_desc)
Definition USBAudioDeviceBase.h:1616
void setIntDoneCallback(std::function< void(USBAudioDeviceBase *, uint8_t)> cb)
Register a callback for interrupt done events.
Definition USBAudioDeviceBase.h:428
volatile uint32_t tx_fifo_read_total_
Definition USBAudioDeviceBase.h:681
std::function< bool(USBAudioDeviceBase *, uint8_t rhport, UsbSetupPacket const &p_request)> tud_audio_set_itf_close_EP_cb_
Definition USBAudioDeviceBase.h:724
uint32_t getRxXferCount() const
Number of times audiod_xfer_cb fired for the OUT endpoint.
Definition USBAudioDeviceBase.h:642
void serviceUSB() override=0
Process pending USB events on platforms where the application drives the stack (RP2040,...
void setItfCloseEpCallback(std::function< bool(USBAudioDeviceBase *, uint8_t, UsbSetupPacket const &)> cb)
Register a callback for interface close endpoint events.
Definition USBAudioDeviceBase.h:510
std::function< bool(USBAudioDeviceBase *, uint8_t rhport, audiod_function_t *, uint16_t bytes)> tx_done_cb_
Definition USBAudioDeviceBase.h:691
void audiod_init(void)
Definition USBAudioDeviceBase.h:986
volatile uint32_t rx_total_bytes_
Definition USBAudioDeviceBase.h:683
void onMuteChanged(uint8_t channel) override
Notify the host about a device-initiated mute change.
Definition USBAudioDeviceBase.h:811
bool activateEndpoint(uint8_t rhport, const UsbEndpointDescriptorView &desc_ep, UsbDir dir=UsbDir::In)
Definition USBAudioDeviceBase.h:1823
bool tx_xfer_armed_
Definition USBAudioDeviceBase.h:679
void setGetReqItfCallback(std::function< bool(USBAudioDeviceBase *, uint8_t, UsbSetupPacket const &)> cb)
Register a callback for GET requests on the interface.
Definition USBAudioDeviceBase.h:400
bool handleClockSourceGet(uint8_t rhport, UsbSetupPacket const &p_request, uint8_t *cb)
Definition USBAudioDeviceBase.h:1356
volatile uint16_t tx_frame_bytes_last_
Definition USBAudioDeviceBase.h:685
uint32_t getRxTotalBytes() const
Total bytes received from host via OUT endpoint.
Definition USBAudioDeviceBase.h:644
bool begin()
(Re-)start the USB audio device with the current config.
Definition USBAudioDeviceBase.h:295
void setFeedbackPercent(int percent)
Overrides the automatic (FIFO_COUNT) feedback computation with a fixed value driven by the caller,...
Definition USBAudioDeviceBase.h:558
bool handleEndpointRequest(uint8_t rhport, UsbSetupPacket const &p_request)
Definition USBAudioDeviceBase.h:1482
uint8_t getAudioCount() const
Returns the number of audio functions (always 1).
Definition USBAudioDeviceBase.h:391
bool audiod_deinit(void)
Definition USBAudioDeviceBase.h:1018
void setFeedbackAutomatic()
Reverts setFeedbackPercent()/setFeedbackPpm() and restores the automatic (FIFO_COUNT) feedback comput...
Definition USBAudioDeviceBase.h:589
int32_t tx_level_avg_
Definition USBAudioDeviceBase.h:746
static uint32_t clampFeedback(const audiod_function_t *audio, uint32_t value)
Definition USBAudioDeviceBase.h:953
bool mounted() override
Returns true if the device is mounted by the USB host.
Definition USBAudioDeviceBase.h:394
void sendInterruptNotification(uint8_t ctrlSel, uint8_t channel, uint8_t entityID)
Send a UAC2 status/change notification via the AC interrupt EP.
Definition USBAudioDeviceBase.h:830
void setFeedbackPpm(int32_t ppm)
Like setFeedbackPercent(), but as an offset from the nominal sample rate in parts per million: positi...
Definition USBAudioDeviceBase.h:575
bool audiod_calc_tx_packet_sz(audiod_function_t *audio)
Definition USBAudioDeviceBase.h:2121
std::function< bool(USBAudioDeviceBase *, uint8_t func_id)> req_entity_cb_
Definition USBAudioDeviceBase.h:706
void openEpOut(uint8_t rhport, audiod_function_t *audio, uint8_t itf, const UsbEndpointDescriptorView &desc_ep)
Definition USBAudioDeviceBase.h:1860
void setFbDoneCallback(std::function< void(USBAudioDeviceBase *, uint8_t)> cb)
Register a callback for feedback done events.
Definition USBAudioDeviceBase.h:420
volatile uint32_t rx_dropped_bytes_
Definition USBAudioDeviceBase.h:684
void setTudAudioSetItfCallback(std::function< bool(USBAudioDeviceBase *, uint8_t, UsbSetupPacket const &)> cb)
Register a callback for interface set requests.
Definition USBAudioDeviceBase.h:466
bool audiod_control_complete(uint8_t rhport, UsbSetupPacket const &p_request)
Definition USBAudioDeviceBase.h:1189
USBAudioDeviceBase()
Default Constructor.
Definition USBAudioDeviceBase.h:202
void setReqEpCallback(std::function< bool(USBAudioDeviceBase *, uint8_t, UsbSetupPacket const &, uint8_t *)> cb)
Register a callback for endpoint set requests.
Definition USBAudioDeviceBase.h:499
bool audiod_verify_entity_exists(uint8_t itf, uint8_t entityID, uint8_t *func_id)
Definition USBAudioDeviceBase.h:1532
audio_feedback_method_t
Methods for USB audio feedback endpoint operation.
Definition USBAudioDeviceBase.h:87
@ AUDIO_FEEDBACK_METHOD_FIFO_COUNT
Definition USBAudioDeviceBase.h:92
@ AUDIO_FEEDBACK_METHOD_FREQUENCY_FIXED
Definition USBAudioDeviceBase.h:89
@ AUDIO_FEEDBACK_METHOD_DISABLED
Definition USBAudioDeviceBase.h:88
@ AUDIO_FEEDBACK_METHOD_FREQUENCY_POWER_OF_2
Definition USBAudioDeviceBase.h:91
@ AUDIO_FEEDBACK_METHOD_FREQUENCY_FLOAT
Definition USBAudioDeviceBase.h:90
uint32_t getRxDroppedBytes() const
Definition USBAudioDeviceBase.h:648
uint16_t getDescriptor(uint8_t *desc)
Returns the audio-function descriptor block for use in tud_descriptor_configuration_cb().
Definition USBAudioDeviceBase.h:621
static constexpr size_t getResetSize()
Definition USBAudioDeviceBase.h:861
void setSampleRate(uint32_t rate)
Device-initiated sample rate change.
Definition USBAudioDeviceBase.h:790
void tud_audio_feedback_interval_isr(uint8_t func_id, uint32_t, uint8_t frame_shift)
Definition USBAudioDeviceBase.h:872
void setReqEntityCallback(std::function< bool(USBAudioDeviceBase *, uint8_t, UsbSetupPacket const &, uint8_t *)> cb)
Register a callback for entity set requests.
Definition USBAudioDeviceBase.h:477
void audiod_reset(uint8_t rhport)
Definition USBAudioDeviceBase.h:1022
std::function< bool(USBAudioDeviceBase *, uint8_t func_id)> tud_audio_feedback_format_correction_cb_
Definition USBAudioDeviceBase.h:731
bool openEndpointsForAltSetting(uint8_t rhport, audiod_function_t *audio, uint8_t func_id, uint8_t itf, uint8_t alt)
Definition USBAudioDeviceBase.h:1950
bool isInterruptEpEnabled() const
Returns true if the interrupt endpoint is enabled.
Definition USBAudioDeviceBase.h:388
std::function< bool(USBAudioDeviceBase *, uint8_t rhport, UsbSetupPacket const &p_request, uint8_t *pBuff)> tud_audio_set_req_entity_cb_
Definition USBAudioDeviceBase.h:712
uint32_t getTxFifoReadTotal() const
Definition USBAudioDeviceBase.h:651
uint8_t numInterfaces() const
Total number of USB interfaces claimed by the audio function (1 AC + 1 or 2 AS), for use in the bNumI...
Definition USBAudioDeviceBase.h:631
std::vector< uint16_t > desc_len_
Definition USBAudioDeviceBase.h:749
std::function< bool(USBAudioDeviceBase *, uint8_t rhport, audiod_function_t *, uint16_t xferred_bytes)> rx_done_cb_
Definition USBAudioDeviceBase.h:694
bool isEpInFlowControlEnabled() const
Returns true if IN endpoint flow control is enabled. When on, the per-frame isochronous packet size i...
Definition USBAudioDeviceBase.h:366
void end()
Stop audio streaming and clear buffers. Does not disconnect USB.
Definition USBAudioDeviceBase.h:596
void audiod_fb_kick(audiod_function_t *audio)
Definition USBAudioDeviceBase.h:971
bool tx_rate_armed_
Definition USBAudioDeviceBase.h:745
USBAudioConfig active_config_
Definition USBAudioDeviceBase.h:687
bool isTxXferArmed() const
True if the initial isochronous IN transfer was armed successfully.
Definition USBAudioDeviceBase.h:637
bool audiod_control_request(uint8_t rhport, UsbSetupPacket const &p_request)
Definition USBAudioDeviceBase.h:1497
uint32_t getTxXferCount() const
Number of times audiod_xfer_cb fired for the IN endpoint.
Definition USBAudioDeviceBase.h:640
USBAudioConfig defaultConfig(RxTxMode mode=RXTX_MODE)
Returns a default configuration pre-filled for the requested direction (RX_MODE, TX_MODE,...
Definition USBAudioDeviceBase.h:214
bool audiod_get_interface(uint8_t rhport, UsbSetupPacket const &p_request)
Definition USBAudioDeviceBase.h:1718
void setupFeedback(audiod_function_t *audio, uint8_t func_id, uint8_t alt)
Definition USBAudioDeviceBase.h:1887
void closeEpIn(uint8_t rhport, audiod_function_t *audio, uint8_t itf, UsbSetupPacket const &p_request)
Definition USBAudioDeviceBase.h:1774
virtual int getActualCore() const
Returns the actual core on which the call is running (for RP2040)
Definition USBAudioDeviceBase.h:676
static USBAudioDeviceBase & activeInstance()
Returns the most-recently-constructed instance (base or subclass).
Definition USBAudioDeviceBase.h:354
bool audiod_get_AS_interface_index(uint8_t itf, audiod_function_t *audio, uint8_t *idxItf, uint8_t const **pp_desc_int)
Definition USBAudioDeviceBase.h:1662
uint8_t getTxInterval() const
TX isochronous interval (bInterval) parsed from the descriptor.
Definition USBAudioDeviceBase.h:672
uint16_t audiod_tx_packet_size_fc(audiod_function_t *audio)
Definition USBAudioDeviceBase.h:2178
void setAudioInfo(AudioInfo info) override
Change the sample rate and notify the host.
Definition USBAudioDeviceBase.h:236
bool handleEntityRequest(uint8_t rhport, UsbSetupPacket const &p_request, uint8_t entityID)
Definition USBAudioDeviceBase.h:1433
volatile uint32_t tx_xferred_last_
Definition USBAudioDeviceBase.h:686
std::vector< uint16_t > ctrl_buf_sz_
Definition USBAudioDeviceBase.h:751
uint16_t getTxFrameBytesLast() const
Definition USBAudioDeviceBase.h:655
std::function< void(USBAudioDeviceBase *, uint8_t rhport)> int_done_cb_
Definition USBAudioDeviceBase.h:689
uint16_t packetSize() const
Definition USBAudioDeviceBase.h:857
bool isFeedbackEpEnabled() const
Returns true if the feedback endpoint is enabled: RX-only mode, or RXTX mode with enable_feedback_ep_...
Definition USBAudioDeviceBase.h:361
void setReqItfCallback(std::function< bool(USBAudioDeviceBase *, uint8_t, UsbSetupPacket const &, uint8_t *)> cb)
Register a callback for interface set requests.
Definition USBAudioDeviceBase.h:488
void openEpFeedback(audiod_function_t *audio, const UsbEndpointDescriptorView &desc_ep)
Definition USBAudioDeviceBase.h:1877
audio_format_type_t
Supported USB audio format types.
Definition USBAudioDeviceBase.h:75
@ AUDIO_FORMAT_TYPE_III
Definition USBAudioDeviceBase.h:78
@ AUDIO_FORMAT_TYPE_II
Definition USBAudioDeviceBase.h:77
@ AUDIO_FORMAT_TYPE_I
Definition USBAudioDeviceBase.h:76
uint8_t int_notify_buf_[6]
Definition USBAudioDeviceBase.h:732
bool audiod_verify_itf_exists(uint8_t itf, uint8_t *func_id)
Definition USBAudioDeviceBase.h:1592
bool isStreamingActiveRx() const override
Returns true if the host has opened the OUT (playback) stream.
Definition USBAudioDeviceBase.h:381
void setAudioFeedbackParamsCallback(std::function< void(USBAudioDeviceBase *, uint8_t, uint8_t, audio_feedback_params_t *)> cb)
Register a callback for audio feedback parameter events.
Definition USBAudioDeviceBase.h:520
bool audiod_set_fb_params_freq(audiod_function_t *audio, uint32_t sample_freq, uint32_t mclk_freq)
Definition USBAudioDeviceBase.h:2084
static int32_t feedbackPpmOffset(const audiod_function_t *audio, int32_t ppm)
Definition USBAudioDeviceBase.h:961
bool audiod_verify_ep_exists(uint8_t ep, uint8_t *func_id)
Definition USBAudioDeviceBase.h:1565
static uint8_t log2Floor(uint32_t value)
Definition USBAudioDeviceBase.h:2078
std::function< bool(USBAudioDeviceBase *, uint8_t rhport, UsbSetupPacket const &)> get_req_itf_cb_
Definition USBAudioDeviceBase.h:698
std::vector< audiod_function_t > audiod_fct_
Definition USBAudioDeviceBase.h:753
std::function< bool(USBAudioDeviceBase *, uint8_t rhport, UsbSetupPacket const &p_request, uint8_t *pBuff)> tud_audio_set_req_ep_cb_
Definition USBAudioDeviceBase.h:720
uint16_t getCtrlBufSz(uint8_t fn) const
Definition USBAudioDeviceBase.h:847
uint32_t getTxXferredLast() const
Definition USBAudioDeviceBase.h:658
uint8_t getTxBytesPerSample() const
TX bytes per sample parsed from the descriptor.
Definition USBAudioDeviceBase.h:668
bool audiod_xfer_cb(uint8_t rhport, uint8_t ep_addr, UsbXferResult result, uint32_t xferred_bytes)
TODO refactor control request handling to separate function and reduce nesting.
Definition USBAudioDeviceBase.h:1265
static bool isPowerOfTwo(uint32_t value)
Definition USBAudioDeviceBase.h:2074
uint8_t getTxChannels() const
TX channel count parsed from the descriptor.
Definition USBAudioDeviceBase.h:664
uint16_t audioPacketSize() const
One isochronous USB packet size in bytes (same formula as the descriptor builder).
Definition USBAudioDeviceBase.h:608
bool handleFeatureUnitGet(uint8_t rhport, UsbSetupPacket const &p_request, uint8_t *cb)
Definition USBAudioDeviceBase.h:1403
USBAudio2DescriptorBuilder descr_builder
Definition USBAudioDeviceBase.h:688
Role-independent front end shared by USB Audio devices (USBAudioDeviceBase, aliased as USBAudioStream...
Definition USBAudioStreamBase.h:39
std::vector< float > volume_
Definition USBAudioStreamBase.h:229
bool isEpInEnabled() const
Returns true if the IN endpoint is enabled.
Definition USBAudioStreamBase.h:42
int core
Definition USBAudioStreamBase.h:224
bool isMute(uint8_t channel=0) const
Returns the current mute state for the given channel.
Definition USBAudioStreamBase.h:80
static int16_t floatToUac2(float vol)
Convert linear volume (0.0–1.0) to UAC2 int16 (1/256 dB). Linear mapping: 0.0 → -100 dB (min),...
Definition USBAudioStreamBase.h:311
virtual BaseBuffer< uint8_t > & bufferTx()=0
Returns the TX audio buffer. Must be overridden by subclasses.
USBAudioConfig config_
Definition USBAudioStreamBase.h:235
bool is_started_
Definition USBAudioStreamBase.h:221
bool rx_primed_
Definition USBAudioStreamBase.h:225
bool setVolume(float volume) override
sets the volume for the master channel (channel 0)
Definition USBAudioStreamBase.h:56
bool is_active_
Definition USBAudioStreamBase.h:226
void setupVolumeState()
(Re)sizes the volume and mute state: master (index 0) + one per channel
Definition USBAudioStreamBase.h:257
float volume() override
gets the volume for the master channel (channel 0)
Definition USBAudioStreamBase.h:53
static bool isValidBitsPerSample(uint8_t bps)
Definition USBAudioStreamBase.h:326
virtual BaseBuffer< uint8_t > & bufferRx()=0
Returns the RX audio buffer. Must be overridden by subclasses.
std::function< void(uint32_t)> sample_rate_cb_
Definition USBAudioStreamBase.h:233
virtual bool beginUSB()=0
Override in platform subclasses to start the USB stack.
static float uac2ToFloat(int16_t v)
Convert UAC2 int16 (1/256 dB) to linear volume (0.0–1.0). Linear mapping within the -100....
Definition USBAudioStreamBase.h:319
virtual void resizeBuffers()=0
Resize the platform audio buffers.
void notifyStreamingState()
Definition USBAudioStreamBase.h:330
bool isEpOutEnabled() const
Returns true if the OUT endpoint is enabled.
Definition USBAudioStreamBase.h:45
bool configChanged(const USBAudioConfig &n)
Definition USBAudioStreamBase.h:254
bool setMute(bool m, uint8_t channel=0)
Set the mute state for a channel and notify the USB peer.
Definition USBAudioStreamBase.h:88
RxTxMode
The Microcontroller is the Audio Source (TX_MODE) or Audio Sink (RX_MODE). RXTX_MODE is Source and Si...
Definition AudioTypes.h:26
@ RXTX_MODE
Definition AudioTypes.h:26
@ TX_MODE
Definition AudioTypes.h:26
@ RX_MODE
Definition AudioTypes.h:26
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition LMSEchoCancellationStream.h:6
static constexpr uint8_t kAudioSubclassControl
Definition USBAudioConstants.h:22
uint8_t descSubtype(uint8_t const *p)
Definition USBAudioBackend.h:107
static constexpr uint8_t kAudioCsCtrlSamFreq
Definition USBAudioConstants.h:45
uint32_t descU32(uint8_t const *p)
Definition USBAudioBackend.h:113
static constexpr uint16_t kAudioDescIadLen
Definition USBAudioConstants.h:55
UsbDir
USB transfer direction, mirrors TinyUSB's TUSB_DIR_OUT/TUSB_DIR_IN (0/1).
Definition USBAudioBackend.h:8
static constexpr uint8_t kUsbClassAudio
Definition USBAudioConstants.h:21
static constexpr uint8_t kAudioIntProtocolCodeV2
Definition USBAudioConstants.h:24
UsbEndpointDescriptorView decodeEndpoint(uint8_t const *p)
Definition USBAudioBackend.h:121
static constexpr uint8_t kAudioCsReqCur
Definition USBAudioConstants.h:39
UsbInterfaceDescriptorView decodeInterface(uint8_t const *p)
Definition USBAudioBackend.h:136
static constexpr uint8_t kAudioCsAcOutputTerminal
Definition USBAudioConstants.h:29
UsbXferResult
Definition USBAudioBackend.h:24
static constexpr uint8_t kControlStageData
Definition USBAudioConstants.h:63
static constexpr uint8_t AUDIO_FU_CTRL_VOLUME
Definition USBAudioConstants.h:51
static uint8_t u16Low(uint16_t v)
Definition USBAudioConstants.h:65
static constexpr uint8_t kUsbDescTypeEndpoint
Definition USBAudioConstants.h:15
uint16_t descU16(uint8_t const *p)
Definition USBAudioBackend.h:109
uint8_t descType(uint8_t const *p)
Definition USBAudioBackend.h:106
static uint8_t u16High(uint16_t v)
Definition USBAudioConstants.h:66
uint8_t const * descNext(uint8_t const *p)
Definition USBAudioBackend.h:105
static constexpr uint8_t kAudioCsCtrlClkValid
Definition USBAudioConstants.h:46
static constexpr uint8_t AUDIO_FU_CTRL_MUTE
Definition USBAudioConstants.h:50
static constexpr uint16_t kAudioTermTypeUsbStreaming
Definition USBAudioConstants.h:53
static constexpr uint8_t kAudioCsAcInputTerminal
Definition USBAudioConstants.h:28
uint32_t highestSupportedSampleRate(const USBAudioConfig &cfg)
Definition USBAudioConfig.h:342
static constexpr uint8_t kUsbDescTypeCsInterface
Definition USBAudioConstants.h:17
static constexpr uint8_t kUsbDescTypeInterface
Definition USBAudioConstants.h:14
static constexpr uint8_t kAudioCsAsGeneral
Definition USBAudioConstants.h:33
static constexpr uint8_t kAudioCsAsFormatType
Definition USBAudioConstants.h:34
static constexpr uint8_t kControlStageSetup
Definition USBAudioConstants.h:62
static constexpr uint8_t kAudioCsReqRange
Definition USBAudioConstants.h:40
Basic Audio information which drives e.g. I2S.
Definition AudioTypes.h:56
sample_rate_t sample_rate
Sample Rate: e.g 44100.
Definition AudioTypes.h:58
uint16_t channels
Number of channels: 2=stereo, 1=mono.
Definition AudioTypes.h:60
uint8_t bits_per_sample
Number of bits per sample (int16_t = 16 bits)
Definition AudioTypes.h:62
Configuration for USB Audio (inherits sample_rate / channels / bits_per_sample from AudioInfo).
Definition USBAudioConfig.h:128
bool enable_interrupt_ep
Definition USBAudioConfig.h:221
bool enable_multi_sample_rate
Definition USBAudioConfig.h:201
std::vector< uint32_t > supported_sample_rates
Definition USBAudioConfig.h:215
bool enable_ep_in_rate_tracking
Definition USBAudioConfig.h:239
bool enable_ep_in
device → host (capture / microphone)
Definition USBAudioConfig.h:131
uint8_t itf_num_ac
Definition USBAudioConfig.h:151
bool enable_ep_in_flow_control
Definition USBAudioConfig.h:228
bool enable_ep_out
host → device (playback / speaker)
Definition USBAudioConfig.h:132
Parameters for audio feedback endpoint configuration.
Definition USBAudioDeviceBase.h:189
uint8_t method
Definition USBAudioDeviceBase.h:190
struct audio_tools::USBAudioDeviceBase::audio_feedback_params_t::@6::@8 frequency
uint32_t mclk_freq
Definition USBAudioDeviceBase.h:195
uint32_t sample_freq
Definition USBAudioDeviceBase.h:191
Internal structure representing a USB audio function instance.
Definition USBAudioDeviceBase.h:101
uint8_t compute_method
Definition USBAudioDeviceBase.h:141
struct audio_tools::USBAudioDeviceBase::audiod_function_t::@2::@3::@4 fixed
uint8_t ep_fb
Definition USBAudioDeviceBase.h:123
bool mounted
Definition USBAudioDeviceBase.h:130
struct audio_tools::USBAudioDeviceBase::audiod_function_t::@2 feedback
uint8_t ep_out_as_intf_num
Definition USBAudioDeviceBase.h:122
uint16_t rate_const[2]
Definition USBAudioDeviceBase.h:154
uint8_t ep_in_as_intf_num
Definition USBAudioDeviceBase.h:118
uint32_t tx_sample_acc
Definition USBAudioDeviceBase.h:168
std::vector< uint8_t > ctrl_buf
Definition USBAudioDeviceBase.h:176
uint8_t ep_fb_xfer
Definition USBAudioDeviceBase.h:128
volatile int32_t ppm_offset
Definition USBAudioDeviceBase.h:139
uint32_t fifo_lvl_avg
Definition USBAudioDeviceBase.h:152
uint8_t interval_tx
Definition USBAudioDeviceBase.h:161
float float_const
Definition USBAudioDeviceBase.h:145
uint16_t ep_in_sz
Definition USBAudioDeviceBase.h:116
uint16_t ep_out_sz
Definition USBAudioDeviceBase.h:120
uint8_t bclock_id_tx
Definition USBAudioDeviceBase.h:160
uint8_t ctrl_buf_sz
Definition USBAudioDeviceBase.h:175
std::vector< uint32_t > fb_buf
Definition USBAudioDeviceBase.h:180
uint16_t fifo_lvl_thr
Definition USBAudioDeviceBase.h:153
uint8_t n_bytes_per_sample_tx
Definition USBAudioDeviceBase.h:164
struct audio_tools::USBAudioDeviceBase::audiod_function_t::@2::@3::@5 fifo_count
uint8_t ep_int
Definition USBAudioDeviceBase.h:129
uint16_t desc_length
Definition USBAudioDeviceBase.h:131
uint32_t max_value
Definition USBAudioDeviceBase.h:135
std::vector< uint8_t > lin_buf_in
Definition USBAudioDeviceBase.h:179
uint32_t min_value
Definition USBAudioDeviceBase.h:134
uint32_t sample_rate_tx
Definition USBAudioDeviceBase.h:158
bool format_correction
Definition USBAudioDeviceBase.h:142
audio_format_type_t format_type_tx
Definition USBAudioDeviceBase.h:162
uint8_t frame_shift
Definition USBAudioDeviceBase.h:140
uint32_t nom_value
Definition USBAudioDeviceBase.h:138
uint32_t mclk_freq
Definition USBAudioDeviceBase.h:148
std::vector< uint8_t > lin_buf_out
Definition USBAudioDeviceBase.h:178
union audio_tools::USBAudioDeviceBase::audiod_function_t::@2::@3 compute
uint8_t power_of_2
Definition USBAudioDeviceBase.h:144
volatile uint8_t ep_out
Definition USBAudioDeviceBase.h:119
uint8_t rhport
Definition USBAudioDeviceBase.h:102
uint8_t n_channels_tx
Definition USBAudioDeviceBase.h:163
uint32_t sample_freq
Definition USBAudioDeviceBase.h:147
uint8_t const * p_desc
Definition USBAudioDeviceBase.h:103
uint16_t packet_sz_tx[3]
Definition USBAudioDeviceBase.h:159
uint32_t value
Definition USBAudioDeviceBase.h:133
UsbEndpointDescriptorView ep_out_view
Definition USBAudioDeviceBase.h:173
std::vector< uint8_t > alt_setting
Definition USBAudioDeviceBase.h:177
volatile uint8_t ep_in
Definition USBAudioDeviceBase.h:115
Backend-agnostic mirror of tusb_desc_endpoint_t (USB 2.0 spec Table 9-13). wMaxPacketSize is kept in ...
Definition USBAudioBackend.h:86
uint8_t bEndpointAddress
Definition USBAudioBackend.h:87
UsbXferType xferType
Definition USBAudioBackend.h:88
UsbDir direction() const
Definition USBAudioBackend.h:94
uint16_t packetSize() const
Definition USBAudioBackend.h:97
uint8_t usage
Definition USBAudioBackend.h:90
uint8_t bInterval
Definition USBAudioBackend.h:91
Backend-agnostic mirror of tusb_desc_interface_t — only the fields the UAC2 driver reads (USB 2....
Definition USBAudioBackend.h:66
uint8_t bInterfaceSubClass
Definition USBAudioBackend.h:71
uint8_t bInterfaceNumber
Definition USBAudioBackend.h:67
uint8_t bAlternateSetting
Definition USBAudioBackend.h:68
uint8_t bInterfaceProtocol
Definition USBAudioBackend.h:72
uint8_t bNumEndpoints
Definition USBAudioBackend.h:69
uint8_t bInterfaceClass
Definition USBAudioBackend.h:70
Backend-agnostic mirror of the standard 8-byte USB SETUP packet (TinyUSB's tusb_control_request_t)....
Definition USBAudioBackend.h:34
uint8_t bRequest
Definition USBAudioBackend.h:36
Recipient recipient() const
Definition USBAudioBackend.h:51
uint16_t wValue
Definition USBAudioBackend.h:37
UsbDir direction() const
Definition USBAudioBackend.h:50
uint16_t wIndex
Definition USBAudioBackend.h:38
Type type() const
Definition USBAudioBackend.h:49