ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
usb_audio_microphone.h
Go to the documentation of this file.
1#pragma once
2
4
5#ifdef USE_USB_AUDIO
6
8
14
15#include <atomic>
16#include <vector>
17
18namespace esphome::usb_audio {
19
21 public Component,
22 public Parented<USBAudioComponent>,
23 public USBAudioStream {
24 public:
25 USBAudioMicrophone(const audio::AudioStreamInfo &stream_info, uint32_t buffer_size) : USBAudioStream(buffer_size) {
26 this->audio_stream_info_ = stream_info;
27 }
28
29 void setup() override;
30 void dump_config() override;
31 void loop() override;
32
33 // Safe from any task; loop() acts on the request.
34 void start() override;
35 void stop() override;
36
38 void on_stream_state(StreamEvent event) override;
39 bool stream_idle() const override { return this->task_idle_; }
40
41 protected:
42 static constexpr uint8_t COMMAND_START = 1 << 0;
43 static constexpr uint8_t COMMAND_STOP = 1 << 1;
44 // Same limit as i2s_audio's microphone.
45 static constexpr uint8_t MAX_LISTENERS = 16;
46 static constexpr uint32_t READ_TIMEOUT_MS = 20;
47 // A failed start is retried while listeners are held, backing off so a device that keeps failing does not flood the
48 // log.
49 static constexpr uint32_t RETRY_MIN_MS = 1000;
50 static constexpr uint32_t RETRY_MAX_MS = 30000;
51 // Scheduler ids.
52 static constexpr uint32_t RETRY_START_ID = 0;
53 static constexpr uint32_t MIC_TASK_STACK_SIZE = 4096;
54 static constexpr UBaseType_t MIC_TASK_PRIORITY = 18;
55
56 static void mic_task(void *param);
57 void mic_task_loop_();
58 void request_(uint8_t set, uint8_t clear);
59
60 // The data callback takes a std::vector, so this is reserved once in setup() and only ever resized within its
61 // capacity by the mic task.
62 std::vector<uint8_t> frame_;
63 // Created once in setup() and parked between streams.
65 std::atomic<uint8_t> commands_{0};
66 // start() calls not yet matched by a stop(); capture stops when the last listener stops.
67 std::atomic<uint8_t> listeners_{0};
68 std::atomic<bool> running_{false};
69 std::atomic<bool> task_idle_{true};
70 // Main loop only.
72};
73
74} // namespace esphome::usb_audio
75
76#endif
Helper class to easily give an object a parent of type T.
Definition helpers.h:2073
Helper for FreeRTOS static task management.
Definition static_task.h:18
audio::AudioStreamInfo audio_stream_info_
Definition microphone.h:45
USBAudioMicrophone(const audio::AudioStreamInfo &stream_info, uint32_t buffer_size)
audio::AudioStreamInfo get_usb_stream_info() override
void on_stream_state(StreamEvent event) override
static constexpr uint32_t MIC_TASK_STACK_SIZE
void request_(uint8_t set, uint8_t clear)
static constexpr UBaseType_t MIC_TASK_PRIORITY
A speaker or microphone platform that streams through the hub. The hub calls it on the main loop only...
Definition usb_audio.h:39
StreamEvent
What the hub reports to a platform about its stream.
Definition usb_audio.h:29
static void uint32_t