ESPHome 2026.6.0-dev
Loading...
Searching...
No Matches
resampler_speaker.cpp
Go to the documentation of this file.
1#include "resampler_speaker.h"
2
3#ifdef USE_ESP32
4
6
10#include "esphome/core/log.h"
11
12#include <algorithm>
13#include <cstring>
14
16
17static const UBaseType_t RESAMPLER_TASK_PRIORITY = 1;
18
19static const uint32_t TRANSFER_BUFFER_DURATION_MS = 50;
20
21static const uint32_t TASK_STACK_SIZE = 3072;
22
23static const uint32_t STATE_TRANSITION_TIMEOUT_MS = 5000;
24
25static const char *const TAG = "resampler_speaker";
26
28 COMMAND_STOP = (1 << 0), // signals stop request
29 COMMAND_START = (1 << 1), // signals start request
30 COMMAND_FINISH = (1 << 2), // signals finish request (graceful stop)
31 TASK_COMMAND_STOP = (1 << 5), // signals the task to stop
32 STATE_STARTING = (1 << 10),
33 STATE_RUNNING = (1 << 11),
34 STATE_STOPPING = (1 << 12),
35 STATE_STOPPED = (1 << 13),
36 ERR_ESP_NO_MEM = (1 << 19),
38 ERR_ESP_FAIL = (1 << 21),
39 ALL_BITS = 0x00FFFFFF, // All valid FreeRTOS event group bits
40};
41
43 ESP_LOGCONFIG(TAG,
44 "Resampler Speaker:\n"
45 " Target Bits Per Sample: %u\n"
46 " Target Sample Rate: %" PRIu32 " Hz",
48}
49
51 this->event_group_ = xEventGroupCreate();
52 if (this->event_group_ == nullptr) {
53 ESP_LOGE(TAG, "Failed to create event group");
54 this->mark_failed();
55 return;
56 }
57
58 this->output_speaker_->add_audio_output_callback([this](uint32_t new_frames, int64_t write_timestamp) {
59 if (this->audio_stream_info_.get_sample_rate() != this->target_stream_info_.get_sample_rate()) {
60 // Convert the number of frames from the target sample rate to the source sample rate. Track the remainder to
61 // avoid losing frames from integer division truncation.
62 const uint64_t numerator = new_frames * this->audio_stream_info_.get_sample_rate() + this->callback_remainder_;
63 const uint64_t denominator = this->target_stream_info_.get_sample_rate();
64 this->callback_remainder_ = numerator % denominator;
65 this->audio_output_callback_(numerator / denominator, write_timestamp);
66 } else {
67 this->audio_output_callback_(new_frames, write_timestamp);
68 }
69 });
70
71 // Start with loop disabled since no task is running and no commands are pending
72 this->disable_loop();
73}
74
76 uint32_t event_group_bits = xEventGroupGetBits(this->event_group_);
77
78 // Process commands with priority: STOP > FINISH > START
79 // This ensures stop commands take precedence over conflicting start commands
80 if (event_group_bits & ResamplingEventGroupBits::COMMAND_STOP) {
82 // Clear STOP, START, and FINISH bits - stop takes precedence
83 xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::COMMAND_STOP |
86 this->waiting_for_output_ = false;
88 } else if (this->state_ == speaker::STATE_STOPPED) {
89 // Already stopped, just clear the command bits
90 xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::COMMAND_STOP |
93 }
94 // Leave bits set if STATE_STOPPING - will be processed once stopped
95 } else if (event_group_bits & ResamplingEventGroupBits::COMMAND_FINISH) {
96 if (this->state_ == speaker::STATE_RUNNING) {
97 xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::COMMAND_FINISH);
98 this->output_speaker_->finish();
99 } else if (this->state_ == speaker::STATE_STOPPED) {
100 // Already stopped, just clear the command bit
101 xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::COMMAND_FINISH);
102 }
103 // Leave bit set if transitioning states - will be processed once state allows
104 } else if (event_group_bits & ResamplingEventGroupBits::COMMAND_START) {
105 if (this->state_ == speaker::STATE_STOPPED) {
106 xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::COMMAND_START);
108 } else if (this->state_ == speaker::STATE_RUNNING) {
109 // Already running, just clear the command bit
110 xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::COMMAND_START);
111 }
112 // Leave bit set if transitioning states - will be processed once state allows
113 }
114
115 // Re-read bits after command processing (enter_stopping_state_ may have set task bits)
116 event_group_bits = xEventGroupGetBits(this->event_group_);
117
118 if (event_group_bits & ResamplingEventGroupBits::STATE_STARTING) {
119 ESP_LOGD(TAG, "Starting");
120 xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::STATE_STARTING);
121 }
122
123 if (event_group_bits & ResamplingEventGroupBits::ERR_ESP_NO_MEM) {
124 this->status_set_error(LOG_STR("Not enough memory"));
125 xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::ERR_ESP_NO_MEM);
126 this->enter_stopping_state_();
127 }
129 this->status_set_error(LOG_STR("Unsupported stream"));
130 xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::ERR_ESP_NOT_SUPPORTED);
131 this->enter_stopping_state_();
132 }
133 if (event_group_bits & ResamplingEventGroupBits::ERR_ESP_FAIL) {
134 this->status_set_error(LOG_STR("Resampler failure"));
135 xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::ERR_ESP_FAIL);
136 this->enter_stopping_state_();
137 }
138
139 if (event_group_bits & ResamplingEventGroupBits::STATE_RUNNING) {
140 ESP_LOGV(TAG, "Started");
141 this->status_clear_error();
142 xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::STATE_RUNNING);
143 }
144 if (event_group_bits & ResamplingEventGroupBits::STATE_STOPPING) {
145 ESP_LOGV(TAG, "Stopping");
146 xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::STATE_STOPPING);
147 }
148 if (event_group_bits & ResamplingEventGroupBits::STATE_STOPPED) {
149 this->task_.deallocate();
150 ESP_LOGD(TAG, "Stopped");
151 xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::ALL_BITS);
152 }
153
154 switch (this->state_) {
156 if (!this->waiting_for_output_) {
157 esp_err_t err = this->start_();
158 if (err == ESP_OK) {
159 this->callback_remainder_ = 0; // reset callback remainder
160 this->status_clear_error();
161 this->waiting_for_output_ = true;
163 } else {
164 this->set_start_error_(err);
165 this->waiting_for_output_ = false;
166 this->enter_stopping_state_();
167 }
168 } else {
169 if (this->output_speaker_->is_running()) {
171 this->waiting_for_output_ = false;
172 } else if ((App.get_loop_component_start_time() - this->state_start_ms_) > STATE_TRANSITION_TIMEOUT_MS) {
173 // Timed out waiting for the output speaker to start
174 this->waiting_for_output_ = false;
175 this->enter_stopping_state_();
176 }
177 }
178 break;
179 }
181 if (this->output_speaker_->is_stopped()) {
182 this->enter_stopping_state_();
183 }
184 break;
186 if ((this->output_speaker_->get_pause_state()) ||
187 ((App.get_loop_component_start_time() - this->state_start_ms_) > STATE_TRANSITION_TIMEOUT_MS)) {
188 // If output speaker is paused or stopping timeout exceeded, force stop
189 this->output_speaker_->stop();
190 }
191
192 if (this->output_speaker_->is_stopped() && !this->task_.is_created()) {
193 // Only transition to stopped state once the output speaker and resampler task are fully stopped
194 this->waiting_for_output_ = false;
196 }
197 break;
198 }
200 event_group_bits = xEventGroupGetBits(this->event_group_);
201 if (event_group_bits == 0) {
202 // No pending events, disable loop to save CPU cycles
203 this->disable_loop();
204 }
205 break;
206 }
207}
208
210 switch (err) {
211 case ESP_ERR_NO_MEM:
212 this->status_set_error(LOG_STR("Not enough memory"));
213 break;
214 default:
215 this->status_set_error(LOG_STR("Failed to start"));
216 break;
217 }
218}
219
220size_t ResamplerSpeaker::play(const uint8_t *data, size_t length, TickType_t ticks_to_wait) {
221 if (this->is_stopped()) {
222 this->start();
223 }
224
225 size_t bytes_written = 0;
226 if ((this->output_speaker_->is_running()) && (!this->requires_resampling_())) {
227 bytes_written = this->output_speaker_->play(data, length, ticks_to_wait);
228 } else {
229 std::shared_ptr<ring_buffer::RingBuffer> temp_ring_buffer = this->ring_buffer_.lock();
230 if (temp_ring_buffer) {
231 // Only write to the ring buffer if the reference is valid
232 bytes_written = temp_ring_buffer->write_without_replacement(data, length, ticks_to_wait);
233 } else {
234 // Delay to avoid repeatedly hammering while waiting for the speaker to start
235 vTaskDelay(ticks_to_wait);
236 }
237 }
238
239 return bytes_written;
240}
241
242void ResamplerSpeaker::send_command_(uint32_t command_bit, bool wake_loop) {
244 uint32_t event_bits = xEventGroupGetBits(this->event_group_);
245 if (!(event_bits & command_bit)) {
246 xEventGroupSetBits(this->event_group_, command_bit);
247 if (wake_loop) {
249 }
250 }
251}
252
254
257 this->target_bits_per_sample_, this->audio_stream_info_.get_channels(), this->target_sample_rate_);
258
260 this->output_speaker_->start();
261
262 if (this->requires_resampling_()) {
263 // Start the resampler task to handle converting sample rates
264 if (!this->task_.create(resample_task, "resampler", TASK_STACK_SIZE, (void *) this, RESAMPLER_TASK_PRIORITY,
265 this->task_stack_in_psram_)) {
266 return ESP_ERR_NO_MEM;
267 }
268 }
269
270 return ESP_OK;
271}
272
274
283
285
287 bool has_ring_buffer_data = false;
288 if (this->requires_resampling_()) {
289 std::shared_ptr<ring_buffer::RingBuffer> temp_ring_buffer = this->ring_buffer_.lock();
290 if (temp_ring_buffer) {
291 has_ring_buffer_data = (temp_ring_buffer->available() > 0);
292 }
293 }
294 return (has_ring_buffer_data || this->output_speaker_->has_buffered_data());
295}
296
297void ResamplerSpeaker::set_mute_state(bool mute_state) {
298 this->mute_state_ = mute_state;
299 this->output_speaker_->set_mute_state(mute_state);
300}
301
303 this->volume_ = volume;
304 this->output_speaker_->set_volume(volume);
305}
306
308 return (this->audio_stream_info_.get_sample_rate() != this->target_sample_rate_) ||
310}
311
313 ResamplerSpeaker *this_resampler = static_cast<ResamplerSpeaker *>(params);
314
315 xEventGroupSetBits(this_resampler->event_group_, ResamplingEventGroupBits::STATE_STARTING);
316
317 { // Ensure C++ objects fall out of scope for proper cleanup before stopping the task
318 std::unique_ptr<audio::AudioResampler> resampler = make_unique<audio::AudioResampler>(
319 this_resampler->audio_stream_info_.ms_to_bytes(TRANSFER_BUFFER_DURATION_MS),
320 this_resampler->target_stream_info_.ms_to_bytes(TRANSFER_BUFFER_DURATION_MS));
321
322 esp_err_t err = resampler->start(this_resampler->audio_stream_info_, this_resampler->target_stream_info_,
323 this_resampler->taps_, this_resampler->filters_);
324
325 if (err == ESP_OK) {
326 std::shared_ptr<ring_buffer::RingBuffer> temp_ring_buffer = ring_buffer::RingBuffer::create(
327 this_resampler->audio_stream_info_.ms_to_bytes(this_resampler->buffer_duration_ms_));
328
329 if (!temp_ring_buffer) {
330 err = ESP_ERR_NO_MEM;
331 } else {
332 this_resampler->ring_buffer_ = temp_ring_buffer;
333 resampler->add_source(this_resampler->ring_buffer_);
334
335 this_resampler->output_speaker_->set_audio_stream_info(this_resampler->target_stream_info_);
336 resampler->add_sink(this_resampler->output_speaker_);
337 }
338 }
339
340 if (err == ESP_OK) {
341 xEventGroupSetBits(this_resampler->event_group_, ResamplingEventGroupBits::STATE_RUNNING);
342 } else if (err == ESP_ERR_NO_MEM) {
343 xEventGroupSetBits(this_resampler->event_group_, ResamplingEventGroupBits::ERR_ESP_NO_MEM);
344 } else if (err == ESP_ERR_NOT_SUPPORTED) {
345 xEventGroupSetBits(this_resampler->event_group_, ResamplingEventGroupBits::ERR_ESP_NOT_SUPPORTED);
346 }
347
348 while (err == ESP_OK) {
349 uint32_t event_bits = xEventGroupGetBits(this_resampler->event_group_);
350
352 break;
353 }
354
355 // Stop gracefully if the decoder is done
356 int32_t ms_differential = 0;
357 audio::AudioResamplerState resampler_state = resampler->resample(false, &ms_differential);
358
359 if (resampler_state == audio::AudioResamplerState::FINISHED) {
360 break;
361 } else if (resampler_state == audio::AudioResamplerState::FAILED) {
362 xEventGroupSetBits(this_resampler->event_group_, ResamplingEventGroupBits::ERR_ESP_FAIL);
363 break;
364 }
365 }
366
367 xEventGroupSetBits(this_resampler->event_group_, ResamplingEventGroupBits::STATE_STOPPING);
368 }
369
370 xEventGroupSetBits(this_resampler->event_group_, ResamplingEventGroupBits::STATE_STOPPED);
371
372 vTaskSuspend(nullptr); // Suspend this task indefinitely until the loop method deletes it
373}
374
375} // namespace esphome::resampler
376
377#endif
void wake_loop_threadsafe()
Wake the main event loop from another thread or callback.
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void mark_failed()
Mark this component as failed.
void status_clear_error()
Definition component.h:295
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
void disable_loop()
Disable this component's loop.
bool create(TaskFunction_t fn, const char *name, uint32_t stack_size, void *param, UBaseType_t priority, bool use_psram)
Allocate stack and create task.
bool is_created() const
Check if the task has been created and not yet destroyed.
Definition static_task.h:18
void deallocate()
Delete the task (if running) and free the stack buffer.
size_t ms_to_bytes(uint32_t ms) const
Converts duration to bytes.
Definition audio.h:73
uint8_t get_bits_per_sample() const
Definition audio.h:28
uint8_t get_channels() const
Definition audio.h:29
uint32_t get_sample_rate() const
Definition audio.h:30
void set_start_error_(esp_err_t err)
Sets the appropriate status error based on the start failure reason.
void set_volume(float volume) override
Volume state changes are passed to the parent's output speaker.
audio::AudioStreamInfo target_stream_info_
esp_err_t start_()
Starts the output speaker after setting the resampled stream info.
size_t play(const uint8_t *data, size_t length, TickType_t ticks_to_wait) override
void enter_stopping_state_()
Transitions to STATE_STOPPING, records the stopping timestamp, sends the task stop command if the tas...
std::weak_ptr< ring_buffer::RingBuffer > ring_buffer_
void send_command_(uint32_t command_bit, bool wake_loop=false)
Sends a command via event group bits, enables the loop, and optionally wakes the main loop.
void set_mute_state(bool mute_state) override
Mute state changes are passed to the parent's output speaker.
static std::unique_ptr< RingBuffer > create(size_t len, MemoryPreference preference=MemoryPreference::EXTERNAL_FIRST)
virtual size_t play(const uint8_t *data, size_t length)=0
Plays the provided audio data.
bool is_running() const
Definition speaker.h:65
virtual void set_volume(float volume)
Definition speaker.h:70
virtual bool get_pause_state() const
Definition speaker.h:61
CallbackManager< void(uint32_t, int64_t)> audio_output_callback_
Definition speaker.h:122
void set_audio_stream_info(const audio::AudioStreamInfo &audio_stream_info)
Definition speaker.h:98
void add_audio_output_callback(F &&callback)
Callback function for sending the duration of the audio written to the speaker since the last callbac...
Definition speaker.h:108
virtual void set_mute_state(bool mute_state)
Definition speaker.h:80
virtual bool has_buffered_data() const =0
audio::AudioStreamInfo audio_stream_info_
Definition speaker.h:114
virtual void start()=0
virtual void finish()
Definition speaker.h:57
bool is_stopped() const
Definition speaker.h:66
virtual void stop()=0
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
uint16_t length
Definition tt21100.cpp:0