ESPHome 2026.1.0-dev
Loading...
Searching...
No Matches
mixer_speaker.cpp
Go to the documentation of this file.
1#include "mixer_speaker.h"
2
3#ifdef USE_ESP32
4
5#include "esphome/core/hal.h"
7#include "esphome/core/log.h"
8
9#include <algorithm>
10#include <cstring>
11
12namespace esphome {
13namespace mixer_speaker {
14
15static const UBaseType_t MIXER_TASK_PRIORITY = 10;
16
17static const uint32_t TRANSFER_BUFFER_DURATION_MS = 50;
18static const uint32_t TASK_DELAY_MS = 25;
19
20static const size_t TASK_STACK_SIZE = 4096;
21
22static const int16_t MAX_AUDIO_SAMPLE_VALUE = INT16_MAX;
23static const int16_t MIN_AUDIO_SAMPLE_VALUE = INT16_MIN;
24
25static const char *const TAG = "speaker_mixer";
26
27// Gives the Q15 fixed point scaling factor to reduce by 0 dB, 1dB, ..., 50 dB
28// dB to PCM scaling factor formula: floating_point_scale_factor = 2^(-db/6.014)
29// float to Q15 fixed point formula: q15_scale_factor = floating_point_scale_factor * 2^(15)
30static const std::vector<int16_t> DECIBEL_REDUCTION_TABLE = {
31 32767, 29201, 26022, 23189, 20665, 18415, 16410, 14624, 13032, 11613, 10349, 9222, 8218, 7324, 6527, 5816, 5183,
32 4619, 4116, 3668, 3269, 2913, 2596, 2313, 2061, 1837, 1637, 1459, 1300, 1158, 1032, 920, 820, 731,
33 651, 580, 517, 461, 411, 366, 326, 291, 259, 231, 206, 183, 163, 146, 130, 116, 103};
34
35enum MixerEventGroupBits : uint32_t {
36 COMMAND_STOP = (1 << 0), // stops the mixer task
37 STATE_STARTING = (1 << 10),
38 STATE_RUNNING = (1 << 11),
39 STATE_STOPPING = (1 << 12),
40 STATE_STOPPED = (1 << 13),
41 ERR_ESP_NO_MEM = (1 << 19),
42 ALL_BITS = 0x00FFFFFF, // All valid FreeRTOS event group bits
43};
44
46 ESP_LOGCONFIG(TAG,
47 "Mixer Source Speaker\n"
48 " Buffer Duration: %" PRIu32 " ms",
50 if (this->timeout_ms_.has_value()) {
51 ESP_LOGCONFIG(TAG, " Timeout: %" PRIu32 " ms", this->timeout_ms_.value());
52 } else {
53 ESP_LOGCONFIG(TAG, " Timeout: never");
54 }
55}
56
58 this->parent_->get_output_speaker()->add_audio_output_callback([this](uint32_t new_frames, int64_t write_timestamp) {
59 // The SourceSpeaker may not have included any audio in the mixed output, so verify there were pending frames
60 uint32_t speakers_playback_frames = std::min(new_frames, this->pending_playback_frames_);
61 this->pending_playback_frames_ -= speakers_playback_frames;
62
63 if (speakers_playback_frames > 0) {
64 this->audio_output_callback_(speakers_playback_frames, write_timestamp);
65 }
66 });
67}
68
70 switch (this->state_) {
72 esp_err_t err = this->start_();
73 if (err == ESP_OK) {
75 this->stop_gracefully_ = false;
76 this->last_seen_data_ms_ = millis();
77 this->status_clear_error();
78 } else {
79 switch (err) {
80 case ESP_ERR_NO_MEM:
81 this->status_set_error(LOG_STR("Failed to start mixer: not enough memory"));
82 break;
83 case ESP_ERR_NOT_SUPPORTED:
84 this->status_set_error(LOG_STR("Failed to start mixer: unsupported bits per sample"));
85 break;
86 case ESP_ERR_INVALID_ARG:
87 this->status_set_error(
88 LOG_STR("Failed to start mixer: audio stream isn't compatible with the other audio stream."));
89 break;
90 case ESP_ERR_INVALID_STATE:
91 this->status_set_error(LOG_STR("Failed to start mixer: mixer task failed to start"));
92 break;
93 default:
94 this->status_set_error(LOG_STR("Failed to start mixer"));
95 break;
96 }
97
99 }
100 break;
101 }
103 if (!this->transfer_buffer_->has_buffered_data()) {
104 if ((this->timeout_ms_.has_value() && ((millis() - this->last_seen_data_ms_) > this->timeout_ms_.value())) ||
105 this->stop_gracefully_) {
107 }
108 }
109 break;
111 this->stop_();
112 this->stop_gracefully_ = false;
114 break;
116 break;
117 }
118}
119
120size_t SourceSpeaker::play(const uint8_t *data, size_t length, TickType_t ticks_to_wait) {
121 if (this->is_stopped()) {
122 this->start();
123 }
124 size_t bytes_written = 0;
125 if (this->ring_buffer_.use_count() == 1) {
126 std::shared_ptr<RingBuffer> temp_ring_buffer = this->ring_buffer_.lock();
127 bytes_written = temp_ring_buffer->write_without_replacement(data, length, ticks_to_wait);
128 if (bytes_written > 0) {
129 this->last_seen_data_ms_ = millis();
130 }
131 }
132 return bytes_written;
133}
134
136
138 const size_t ring_buffer_size = this->audio_stream_info_.ms_to_bytes(this->buffer_duration_ms_);
139 if (this->transfer_buffer_.use_count() == 0) {
140 this->transfer_buffer_ =
142
143 if (this->transfer_buffer_ == nullptr) {
144 return ESP_ERR_NO_MEM;
145 }
146 std::shared_ptr<RingBuffer> temp_ring_buffer;
147
148 if (!this->ring_buffer_.use_count()) {
149 temp_ring_buffer = RingBuffer::create(ring_buffer_size);
150 this->ring_buffer_ = temp_ring_buffer;
151 }
152
153 if (!this->ring_buffer_.use_count()) {
154 return ESP_ERR_NO_MEM;
155 } else {
156 this->transfer_buffer_->set_source(temp_ring_buffer);
157 }
158 }
159
160 this->pending_playback_frames_ = 0; // reset
161 return this->parent_->start(this->audio_stream_info_);
162}
163
165 if (this->state_ != speaker::STATE_STOPPED) {
167 }
168}
169
171 this->transfer_buffer_.reset(); // deallocates the transfer buffer
172}
173
175
177 return ((this->transfer_buffer_.use_count() > 0) && this->transfer_buffer_->has_buffered_data());
178}
179
180void SourceSpeaker::set_mute_state(bool mute_state) {
181 this->mute_state_ = mute_state;
182 this->parent_->get_output_speaker()->set_mute_state(mute_state);
183}
184
186
187void SourceSpeaker::set_volume(float volume) {
188 this->volume_ = volume;
189 this->parent_->get_output_speaker()->set_volume(volume);
190}
191
193
194size_t SourceSpeaker::process_data_from_source(TickType_t ticks_to_wait) {
195 if (!this->transfer_buffer_.use_count()) {
196 return 0;
197 }
198
199 // Store current offset, as these samples are already ducked
200 const size_t current_length = this->transfer_buffer_->available();
201
202 size_t bytes_read = this->transfer_buffer_->transfer_data_from_source(ticks_to_wait);
203
204 uint32_t samples_to_duck = this->audio_stream_info_.bytes_to_samples(bytes_read);
205 if (samples_to_duck > 0) {
206 int16_t *current_buffer = reinterpret_cast<int16_t *>(this->transfer_buffer_->get_buffer_start() + current_length);
207
208 duck_samples(current_buffer, samples_to_duck, &this->current_ducking_db_reduction_,
211 }
212
213 return bytes_read;
214}
215
216void SourceSpeaker::apply_ducking(uint8_t decibel_reduction, uint32_t duration) {
217 if (this->target_ducking_db_reduction_ != decibel_reduction) {
219
220 this->target_ducking_db_reduction_ = decibel_reduction;
221
222 uint8_t total_ducking_steps = 0;
224 // The dB reduction level is increasing (which results in quieter audio)
225 total_ducking_steps = this->target_ducking_db_reduction_ - this->current_ducking_db_reduction_ - 1;
227 } else {
228 // The dB reduction level is decreasing (which results in louder audio)
229 total_ducking_steps = this->current_ducking_db_reduction_ - this->target_ducking_db_reduction_ - 1;
231 }
232 if ((duration > 0) && (total_ducking_steps > 0)) {
234
235 this->samples_per_ducking_step_ = this->ducking_transition_samples_remaining_ / total_ducking_steps;
237 this->samples_per_ducking_step_ * total_ducking_steps; // Adjust for integer division rounding
238
240 } else {
243 }
244 }
245}
246
247void SourceSpeaker::duck_samples(int16_t *input_buffer, uint32_t input_samples_to_duck,
248 int8_t *current_ducking_db_reduction, uint32_t *ducking_transition_samples_remaining,
249 uint32_t samples_per_ducking_step, int8_t db_change_per_ducking_step) {
250 if (*ducking_transition_samples_remaining > 0) {
251 // Ducking level is still transitioning
252
253 // Takes the ceiling of input_samples_to_duck/samples_per_ducking_step
254 uint32_t ducking_steps_in_batch =
255 input_samples_to_duck / samples_per_ducking_step + (input_samples_to_duck % samples_per_ducking_step != 0);
256
257 for (uint32_t i = 0; i < ducking_steps_in_batch; ++i) {
258 uint32_t samples_left_in_step = *ducking_transition_samples_remaining % samples_per_ducking_step;
259
260 if (samples_left_in_step == 0) {
261 samples_left_in_step = samples_per_ducking_step;
262 }
263
264 uint32_t samples_to_duck = std::min(input_samples_to_duck, samples_left_in_step);
265 samples_to_duck = std::min(samples_to_duck, *ducking_transition_samples_remaining);
266
267 // Ensure we only point to valid index in the Q15 scaling factor table
268 uint8_t safe_db_reduction_index =
269 clamp<uint8_t>(*current_ducking_db_reduction, 0, DECIBEL_REDUCTION_TABLE.size() - 1);
270 int16_t q15_scale_factor = DECIBEL_REDUCTION_TABLE[safe_db_reduction_index];
271
272 audio::scale_audio_samples(input_buffer, input_buffer, q15_scale_factor, samples_to_duck);
273
274 if (samples_left_in_step - samples_to_duck == 0) {
275 // After scaling the current samples, we are ready to transition to the next step
276 *current_ducking_db_reduction += db_change_per_ducking_step;
277 }
278
279 input_buffer += samples_to_duck;
280 *ducking_transition_samples_remaining -= samples_to_duck;
281 input_samples_to_duck -= samples_to_duck;
282 }
283 }
284
285 if ((*current_ducking_db_reduction > 0) && (input_samples_to_duck > 0)) {
286 // Audio is ducked, but its not in the middle of a transition step
287
288 uint8_t safe_db_reduction_index =
289 clamp<uint8_t>(*current_ducking_db_reduction, 0, DECIBEL_REDUCTION_TABLE.size() - 1);
290 int16_t q15_scale_factor = DECIBEL_REDUCTION_TABLE[safe_db_reduction_index];
291
292 audio::scale_audio_samples(input_buffer, input_buffer, q15_scale_factor, input_samples_to_duck);
293 }
294}
295
297 ESP_LOGCONFIG(TAG,
298 "Speaker Mixer:\n"
299 " Number of output channels: %u",
300 this->output_channels_);
301}
302
304 this->event_group_ = xEventGroupCreate();
305
306 if (this->event_group_ == nullptr) {
307 ESP_LOGE(TAG, "Failed to create event group");
308 this->mark_failed();
309 return;
310 }
311}
312
314 uint32_t event_group_bits = xEventGroupGetBits(this->event_group_);
315
316 if (event_group_bits & MixerEventGroupBits::STATE_STARTING) {
317 ESP_LOGD(TAG, "Starting speaker mixer");
318 xEventGroupClearBits(this->event_group_, MixerEventGroupBits::STATE_STARTING);
319 }
320 if (event_group_bits & MixerEventGroupBits::ERR_ESP_NO_MEM) {
321 this->status_set_error(LOG_STR("Failed to allocate the mixer's internal buffer"));
322 xEventGroupClearBits(this->event_group_, MixerEventGroupBits::ERR_ESP_NO_MEM);
323 }
324 if (event_group_bits & MixerEventGroupBits::STATE_RUNNING) {
325 ESP_LOGD(TAG, "Started speaker mixer");
326 this->status_clear_error();
327 xEventGroupClearBits(this->event_group_, MixerEventGroupBits::STATE_RUNNING);
328 }
329 if (event_group_bits & MixerEventGroupBits::STATE_STOPPING) {
330 ESP_LOGD(TAG, "Stopping speaker mixer");
331 xEventGroupClearBits(this->event_group_, MixerEventGroupBits::STATE_STOPPING);
332 }
333 if (event_group_bits & MixerEventGroupBits::STATE_STOPPED) {
334 if (this->delete_task_() == ESP_OK) {
335 xEventGroupClearBits(this->event_group_, MixerEventGroupBits::ALL_BITS);
336 }
337 }
338
339 if (this->task_handle_ != nullptr) {
340 bool all_stopped = true;
341
342 for (auto &speaker : this->source_speakers_) {
343 all_stopped &= speaker->is_stopped();
344 }
345
346 if (all_stopped) {
347 this->stop();
348 }
349 }
350}
351
353 if (!this->audio_stream_info_.has_value()) {
354 if (stream_info.get_bits_per_sample() != 16) {
355 // Audio streams that don't have 16 bits per sample are not supported
356 return ESP_ERR_NOT_SUPPORTED;
357 }
358
359 this->audio_stream_info_ = audio::AudioStreamInfo(stream_info.get_bits_per_sample(), this->output_channels_,
360 stream_info.get_sample_rate());
362 } else {
363 if (!this->queue_mode_ && (stream_info.get_sample_rate() != this->audio_stream_info_.value().get_sample_rate())) {
364 // The two audio streams must have the same sample rate to mix properly if not in queue mode
365 return ESP_ERR_INVALID_ARG;
366 }
367 }
368
369 return this->start_task_();
370}
371
373 if (this->task_stack_buffer_ == nullptr) {
374 if (this->task_stack_in_psram_) {
376 this->task_stack_buffer_ = stack_allocator.allocate(TASK_STACK_SIZE);
377 } else {
379 this->task_stack_buffer_ = stack_allocator.allocate(TASK_STACK_SIZE);
380 }
381 }
382
383 if (this->task_stack_buffer_ == nullptr) {
384 return ESP_ERR_NO_MEM;
385 }
386
387 if (this->task_handle_ == nullptr) {
388 this->task_handle_ = xTaskCreateStatic(audio_mixer_task, "mixer", TASK_STACK_SIZE, (void *) this,
389 MIXER_TASK_PRIORITY, this->task_stack_buffer_, &this->task_stack_);
390 }
391
392 if (this->task_handle_ == nullptr) {
393 return ESP_ERR_INVALID_STATE;
394 }
395
396 return ESP_OK;
397}
398
400 if (!this->task_created_) {
401 this->task_handle_ = nullptr;
402
403 if (this->task_stack_buffer_ != nullptr) {
404 if (this->task_stack_in_psram_) {
406 stack_allocator.deallocate(this->task_stack_buffer_, TASK_STACK_SIZE);
407 } else {
409 stack_allocator.deallocate(this->task_stack_buffer_, TASK_STACK_SIZE);
410 }
411
412 this->task_stack_buffer_ = nullptr;
413 }
414
415 return ESP_OK;
416 }
417
418 return ESP_ERR_INVALID_STATE;
419}
420
422
423void MixerSpeaker::copy_frames(const int16_t *input_buffer, audio::AudioStreamInfo input_stream_info,
424 int16_t *output_buffer, audio::AudioStreamInfo output_stream_info,
425 uint32_t frames_to_transfer) {
426 uint8_t input_channels = input_stream_info.get_channels();
427 uint8_t output_channels = output_stream_info.get_channels();
428 const uint8_t max_input_channel_index = input_channels - 1;
429
430 if (input_channels == output_channels) {
431 size_t bytes_to_copy = input_stream_info.frames_to_bytes(frames_to_transfer);
432 memcpy(output_buffer, input_buffer, bytes_to_copy);
433
434 return;
435 }
436
437 for (uint32_t frame_index = 0; frame_index < frames_to_transfer; ++frame_index) {
438 for (uint8_t output_channel_index = 0; output_channel_index < output_channels; ++output_channel_index) {
439 uint8_t input_channel_index = std::min(output_channel_index, max_input_channel_index);
440 output_buffer[output_channels * frame_index + output_channel_index] =
441 input_buffer[input_channels * frame_index + input_channel_index];
442 }
443 }
444}
445
446void MixerSpeaker::mix_audio_samples(const int16_t *primary_buffer, audio::AudioStreamInfo primary_stream_info,
447 const int16_t *secondary_buffer, audio::AudioStreamInfo secondary_stream_info,
448 int16_t *output_buffer, audio::AudioStreamInfo output_stream_info,
449 uint32_t frames_to_mix) {
450 const uint8_t primary_channels = primary_stream_info.get_channels();
451 const uint8_t secondary_channels = secondary_stream_info.get_channels();
452 const uint8_t output_channels = output_stream_info.get_channels();
453
454 const uint8_t max_primary_channel_index = primary_channels - 1;
455 const uint8_t max_secondary_channel_index = secondary_channels - 1;
456
457 for (uint32_t frames_index = 0; frames_index < frames_to_mix; ++frames_index) {
458 for (uint8_t output_channel_index = 0; output_channel_index < output_channels; ++output_channel_index) {
459 const uint32_t secondary_channel_index = std::min(output_channel_index, max_secondary_channel_index);
460 const int32_t secondary_sample = secondary_buffer[frames_index * secondary_channels + secondary_channel_index];
461
462 const uint32_t primary_channel_index = std::min(output_channel_index, max_primary_channel_index);
463 const int32_t primary_sample =
464 static_cast<int32_t>(primary_buffer[frames_index * primary_channels + primary_channel_index]);
465
466 const int32_t added_sample = secondary_sample + primary_sample;
467
468 output_buffer[frames_index * output_channels + output_channel_index] =
469 static_cast<int16_t>(clamp<int32_t>(added_sample, MIN_AUDIO_SAMPLE_VALUE, MAX_AUDIO_SAMPLE_VALUE));
470 }
471 }
472}
473
475 MixerSpeaker *this_mixer = (MixerSpeaker *) params;
476
477 xEventGroupSetBits(this_mixer->event_group_, MixerEventGroupBits::STATE_STARTING);
478
479 this_mixer->task_created_ = true;
480
481 std::unique_ptr<audio::AudioSinkTransferBuffer> output_transfer_buffer = audio::AudioSinkTransferBuffer::create(
482 this_mixer->audio_stream_info_.value().ms_to_bytes(TRANSFER_BUFFER_DURATION_MS));
483
484 if (output_transfer_buffer == nullptr) {
485 xEventGroupSetBits(this_mixer->event_group_,
487
488 this_mixer->task_created_ = false;
489 vTaskDelete(nullptr);
490 }
491
492 output_transfer_buffer->set_sink(this_mixer->output_speaker_);
493
494 xEventGroupSetBits(this_mixer->event_group_, MixerEventGroupBits::STATE_RUNNING);
495
496 bool sent_finished = false;
497
498 while (true) {
499 uint32_t event_group_bits = xEventGroupGetBits(this_mixer->event_group_);
500 if (event_group_bits & MixerEventGroupBits::COMMAND_STOP) {
501 break;
502 }
503
504 // Never shift the data in the output transfer buffer to avoid unnecessary, slow data moves
505 output_transfer_buffer->transfer_data_to_sink(pdMS_TO_TICKS(TASK_DELAY_MS), false);
506
507 const uint32_t output_frames_free =
508 this_mixer->audio_stream_info_.value().bytes_to_frames(output_transfer_buffer->free());
509
510 std::vector<SourceSpeaker *> speakers_with_data;
511 std::vector<std::shared_ptr<audio::AudioSourceTransferBuffer>> transfer_buffers_with_data;
512
513 for (auto &speaker : this_mixer->source_speakers_) {
514 if (speaker->get_transfer_buffer().use_count() > 0) {
515 std::shared_ptr<audio::AudioSourceTransferBuffer> transfer_buffer = speaker->get_transfer_buffer().lock();
516 speaker->process_data_from_source(0); // Transfers and ducks audio from source ring buffers
517
518 if ((transfer_buffer->available() > 0) && !speaker->get_pause_state()) {
519 // Store the locked transfer buffers in their own vector to avoid releasing ownership until after the loop
520 transfer_buffers_with_data.push_back(transfer_buffer);
521 speakers_with_data.push_back(speaker);
522 }
523 }
524 }
525
526 if (transfer_buffers_with_data.empty()) {
527 // No audio available for transferring, block task temporarily
528 delay(TASK_DELAY_MS);
529 continue;
530 }
531
532 uint32_t frames_to_mix = output_frames_free;
533
534 if ((transfer_buffers_with_data.size() == 1) || this_mixer->queue_mode_) {
535 // Only one speaker has audio data, just copy samples over
536
537 audio::AudioStreamInfo active_stream_info = speakers_with_data[0]->get_audio_stream_info();
538
539 if (active_stream_info.get_sample_rate() ==
541 // Speaker's sample rate matches the output speaker's, copy directly
542
543 const uint32_t frames_available_in_buffer =
544 active_stream_info.bytes_to_frames(transfer_buffers_with_data[0]->available());
545 frames_to_mix = std::min(frames_to_mix, frames_available_in_buffer);
546 copy_frames(reinterpret_cast<int16_t *>(transfer_buffers_with_data[0]->get_buffer_start()), active_stream_info,
547 reinterpret_cast<int16_t *>(output_transfer_buffer->get_buffer_end()),
548 this_mixer->audio_stream_info_.value(), frames_to_mix);
549
550 // Update source speaker buffer length
551 transfer_buffers_with_data[0]->decrease_buffer_length(active_stream_info.frames_to_bytes(frames_to_mix));
552 speakers_with_data[0]->pending_playback_frames_ += frames_to_mix;
553
554 // Update output transfer buffer length
555 output_transfer_buffer->increase_buffer_length(
556 this_mixer->audio_stream_info_.value().frames_to_bytes(frames_to_mix));
557 } else {
558 // Speaker's stream info doesn't match the output speaker's, so it's a new source speaker
559 if (!this_mixer->output_speaker_->is_stopped()) {
560 if (!sent_finished) {
561 this_mixer->output_speaker_->finish();
562 sent_finished = true; // Avoid repeatedly sending the finish command
563 }
564 } else {
565 // Speaker has finished writing the current audio, update the stream information and restart the speaker
566 this_mixer->audio_stream_info_ =
567 audio::AudioStreamInfo(active_stream_info.get_bits_per_sample(), this_mixer->output_channels_,
568 active_stream_info.get_sample_rate());
569 this_mixer->output_speaker_->set_audio_stream_info(this_mixer->audio_stream_info_.value());
570 this_mixer->output_speaker_->start();
571 sent_finished = false;
572 }
573 }
574 } else {
575 // Determine how many frames to mix
576 for (size_t i = 0; i < transfer_buffers_with_data.size(); ++i) {
577 const uint32_t frames_available_in_buffer =
578 speakers_with_data[i]->get_audio_stream_info().bytes_to_frames(transfer_buffers_with_data[i]->available());
579 frames_to_mix = std::min(frames_to_mix, frames_available_in_buffer);
580 }
581 int16_t *primary_buffer = reinterpret_cast<int16_t *>(transfer_buffers_with_data[0]->get_buffer_start());
582 audio::AudioStreamInfo primary_stream_info = speakers_with_data[0]->get_audio_stream_info();
583
584 // Mix two streams together
585 for (size_t i = 1; i < transfer_buffers_with_data.size(); ++i) {
586 mix_audio_samples(primary_buffer, primary_stream_info,
587 reinterpret_cast<int16_t *>(transfer_buffers_with_data[i]->get_buffer_start()),
588 speakers_with_data[i]->get_audio_stream_info(),
589 reinterpret_cast<int16_t *>(output_transfer_buffer->get_buffer_end()),
590 this_mixer->audio_stream_info_.value(), frames_to_mix);
591
592 if (i != transfer_buffers_with_data.size() - 1) {
593 // Need to mix more streams together, point primary buffer and stream info to the already mixed output
594 primary_buffer = reinterpret_cast<int16_t *>(output_transfer_buffer->get_buffer_end());
595 primary_stream_info = this_mixer->audio_stream_info_.value();
596 }
597 }
598
599 // Update source transfer buffer lengths and add new audio durations to the source speaker pending playbacks
600 for (size_t i = 0; i < transfer_buffers_with_data.size(); ++i) {
601 transfer_buffers_with_data[i]->decrease_buffer_length(
602 speakers_with_data[i]->get_audio_stream_info().frames_to_bytes(frames_to_mix));
603 speakers_with_data[i]->pending_playback_frames_ += frames_to_mix;
604 }
605
606 // Update output transfer buffer length
607 output_transfer_buffer->increase_buffer_length(
608 this_mixer->audio_stream_info_.value().frames_to_bytes(frames_to_mix));
609 }
610 }
611
612 xEventGroupSetBits(this_mixer->event_group_, MixerEventGroupBits::STATE_STOPPING);
613
614 output_transfer_buffer.reset();
615
616 xEventGroupSetBits(this_mixer->event_group_, MixerEventGroupBits::STATE_STOPPED);
617 this_mixer->task_created_ = false;
618 vTaskDelete(nullptr);
619}
620
621} // namespace mixer_speaker
622} // namespace esphome
623
624#endif
virtual void mark_failed()
Mark this component as failed.
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:1274
void deallocate(T *p, size_t n)
Definition helpers.h:1332
T * allocate(size_t n)
Definition helpers.h:1294
static std::unique_ptr< RingBuffer > create(size_t len)
static std::unique_ptr< AudioSinkTransferBuffer > create(size_t buffer_size)
Creates a new sink transfer buffer.
static std::unique_ptr< AudioSourceTransferBuffer > create(size_t buffer_size)
Creates a new source transfer buffer.
size_t ms_to_bytes(uint32_t ms) const
Converts duration to bytes.
Definition audio.h:73
size_t frames_to_bytes(uint32_t frames) const
Converts frames to bytes.
Definition audio.h:53
uint8_t get_bits_per_sample() const
Definition audio.h:28
uint32_t ms_to_samples(uint32_t ms) const
Converts duration to samples.
Definition audio.h:68
uint32_t bytes_to_frames(size_t bytes) const
Convert bytes to frames.
Definition audio.h:43
uint8_t get_channels() const
Definition audio.h:29
uint32_t get_sample_rate() const
Definition audio.h:30
uint32_t bytes_to_samples(size_t bytes) const
Convert bytes to samples.
Definition audio.h:48
esp_err_t start_task_()
Starts the mixer task after allocating memory for the task stack.
esp_err_t delete_task_()
If the task is stopped, it sets the task handle to the nullptr and deallocates its stack.
esp_err_t start(audio::AudioStreamInfo &stream_info)
Starts the mixer task.
speaker::Speaker * get_output_speaker() const
std::vector< SourceSpeaker * > source_speakers_
static void mix_audio_samples(const int16_t *primary_buffer, audio::AudioStreamInfo primary_stream_info, const int16_t *secondary_buffer, audio::AudioStreamInfo secondary_stream_info, int16_t *output_buffer, audio::AudioStreamInfo output_stream_info, uint32_t frames_to_mix)
Mixes the primary and secondary streams taking into account the number of channels in each stream.
static void copy_frames(const int16_t *input_buffer, audio::AudioStreamInfo input_stream_info, int16_t *output_buffer, audio::AudioStreamInfo output_stream_info, uint32_t frames_to_transfer)
Copies audio frames from the input buffer to the output buffer taking into account the number of chan...
static void audio_mixer_task(void *params)
optional< audio::AudioStreamInfo > audio_stream_info_
std::shared_ptr< audio::AudioSourceTransferBuffer > transfer_buffer_
void set_mute_state(bool mute_state) override
Mute state changes are passed to the parent's output speaker.
static void duck_samples(int16_t *input_buffer, uint32_t input_samples_to_duck, int8_t *current_ducking_db_reduction, uint32_t *ducking_transition_samples_remaining, uint32_t samples_per_ducking_step, int8_t db_change_per_ducking_step)
Ducks audio samples by a specified amount.
size_t process_data_from_source(TickType_t ticks_to_wait)
Transfers audio from the ring buffer into the transfer buffer.
void apply_ducking(uint8_t decibel_reduction, uint32_t duration)
Sets the ducking level for the source speaker.
std::weak_ptr< RingBuffer > ring_buffer_
size_t play(const uint8_t *data, size_t length, TickType_t ticks_to_wait) override
void set_volume(float volume) override
Volume state changes are passed to the parent's output speaker.
bool has_value() const
Definition optional.h:92
value_type const & value() const
Definition optional.h:94
virtual void set_volume(float volume)
Definition speaker.h:71
void add_audio_output_callback(std::function< void(uint32_t, int64_t)> &&callback)
Callback function for sending the duration of the audio written to the speaker since the last callbac...
Definition speaker.h:109
virtual float get_volume()
Definition speaker.h:79
CallbackManager< void(uint32_t, int64_t)> audio_output_callback_
Definition speaker.h:123
void set_audio_stream_info(const audio::AudioStreamInfo &audio_stream_info)
Definition speaker.h:99
audio::AudioStreamInfo & get_audio_stream_info()
Definition speaker.h:103
virtual bool get_mute_state()
Definition speaker.h:93
virtual void set_mute_state(bool mute_state)
Definition speaker.h:81
audio::AudioStreamInfo audio_stream_info_
Definition speaker.h:115
virtual void start()=0
virtual void finish()
Definition speaker.h:58
bool is_stopped() const
Definition speaker.h:67
uint8_t duration
Definition msa3xx.h:0
void scale_audio_samples(const int16_t *audio_samples, int16_t *output_buffer, int16_t scale_factor, size_t samples_to_scale)
Scales Q15 fixed point audio samples.
Definition audio.cpp:57
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:26
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:25
uint16_t length
Definition tt21100.cpp:0