ESPHome 2025.7.4
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("Failed to start mixer: not enough memory");
82 break;
83 case ESP_ERR_NOT_SUPPORTED:
84 this->status_set_error("Failed to start mixer: unsupported bits per sample");
85 break;
86 case ESP_ERR_INVALID_ARG:
87 this->status_set_error("Failed to start mixer: audio stream isn't compatible with the other audio stream.");
88 break;
89 case ESP_ERR_INVALID_STATE:
90 this->status_set_error("Failed to start mixer: mixer task failed to start");
91 break;
92 default:
93 this->status_set_error("Failed to start mixer");
94 break;
95 }
96
98 }
99 break;
100 }
102 if (!this->transfer_buffer_->has_buffered_data()) {
103 if ((this->timeout_ms_.has_value() && ((millis() - this->last_seen_data_ms_) > this->timeout_ms_.value())) ||
104 this->stop_gracefully_) {
106 }
107 }
108 break;
110 this->stop_();
111 this->stop_gracefully_ = false;
113 break;
115 break;
116 }
117}
118
119size_t SourceSpeaker::play(const uint8_t *data, size_t length, TickType_t ticks_to_wait) {
120 if (this->is_stopped()) {
121 this->start();
122 }
123 size_t bytes_written = 0;
124 if (this->ring_buffer_.use_count() == 1) {
125 std::shared_ptr<RingBuffer> temp_ring_buffer = this->ring_buffer_.lock();
126 bytes_written = temp_ring_buffer->write_without_replacement(data, length, ticks_to_wait);
127 if (bytes_written > 0) {
128 this->last_seen_data_ms_ = millis();
129 }
130 }
131 return bytes_written;
132}
133
135
137 const size_t ring_buffer_size = this->audio_stream_info_.ms_to_bytes(this->buffer_duration_ms_);
138 if (this->transfer_buffer_.use_count() == 0) {
139 this->transfer_buffer_ =
141
142 if (this->transfer_buffer_ == nullptr) {
143 return ESP_ERR_NO_MEM;
144 }
145 std::shared_ptr<RingBuffer> temp_ring_buffer;
146
147 if (!this->ring_buffer_.use_count()) {
148 temp_ring_buffer = RingBuffer::create(ring_buffer_size);
149 this->ring_buffer_ = temp_ring_buffer;
150 }
151
152 if (!this->ring_buffer_.use_count()) {
153 return ESP_ERR_NO_MEM;
154 } else {
155 this->transfer_buffer_->set_source(temp_ring_buffer);
156 }
157 }
158
159 this->pending_playback_frames_ = 0; // reset
160 return this->parent_->start(this->audio_stream_info_);
161}
162
164 if (this->state_ != speaker::STATE_STOPPED) {
166 }
167}
168
170 this->transfer_buffer_.reset(); // deallocates the transfer buffer
171}
172
174
176 return ((this->transfer_buffer_.use_count() > 0) && this->transfer_buffer_->has_buffered_data());
177}
178
179void SourceSpeaker::set_mute_state(bool mute_state) {
180 this->mute_state_ = mute_state;
181 this->parent_->get_output_speaker()->set_mute_state(mute_state);
182}
183
185
186void SourceSpeaker::set_volume(float volume) {
187 this->volume_ = volume;
188 this->parent_->get_output_speaker()->set_volume(volume);
189}
190
192
193size_t SourceSpeaker::process_data_from_source(TickType_t ticks_to_wait) {
194 if (!this->transfer_buffer_.use_count()) {
195 return 0;
196 }
197
198 // Store current offset, as these samples are already ducked
199 const size_t current_length = this->transfer_buffer_->available();
200
201 size_t bytes_read = this->transfer_buffer_->transfer_data_from_source(ticks_to_wait);
202
203 uint32_t samples_to_duck = this->audio_stream_info_.bytes_to_samples(bytes_read);
204 if (samples_to_duck > 0) {
205 int16_t *current_buffer = reinterpret_cast<int16_t *>(this->transfer_buffer_->get_buffer_start() + current_length);
206
207 duck_samples(current_buffer, samples_to_duck, &this->current_ducking_db_reduction_,
210 }
211
212 return bytes_read;
213}
214
215void SourceSpeaker::apply_ducking(uint8_t decibel_reduction, uint32_t duration) {
216 if (this->target_ducking_db_reduction_ != decibel_reduction) {
218
219 this->target_ducking_db_reduction_ = decibel_reduction;
220
221 uint8_t total_ducking_steps = 0;
223 // The dB reduction level is increasing (which results in quieter audio)
224 total_ducking_steps = this->target_ducking_db_reduction_ - this->current_ducking_db_reduction_ - 1;
226 } else {
227 // The dB reduction level is decreasing (which results in louder audio)
228 total_ducking_steps = this->current_ducking_db_reduction_ - this->target_ducking_db_reduction_ - 1;
230 }
231 if ((duration > 0) && (total_ducking_steps > 0)) {
233
234 this->samples_per_ducking_step_ = this->ducking_transition_samples_remaining_ / total_ducking_steps;
236 this->samples_per_ducking_step_ * total_ducking_steps; // Adjust for integer division rounding
237
239 } else {
242 }
243 }
244}
245
246void SourceSpeaker::duck_samples(int16_t *input_buffer, uint32_t input_samples_to_duck,
247 int8_t *current_ducking_db_reduction, uint32_t *ducking_transition_samples_remaining,
248 uint32_t samples_per_ducking_step, int8_t db_change_per_ducking_step) {
249 if (*ducking_transition_samples_remaining > 0) {
250 // Ducking level is still transitioning
251
252 // Takes the ceiling of input_samples_to_duck/samples_per_ducking_step
253 uint32_t ducking_steps_in_batch =
254 input_samples_to_duck / samples_per_ducking_step + (input_samples_to_duck % samples_per_ducking_step != 0);
255
256 for (uint32_t i = 0; i < ducking_steps_in_batch; ++i) {
257 uint32_t samples_left_in_step = *ducking_transition_samples_remaining % samples_per_ducking_step;
258
259 if (samples_left_in_step == 0) {
260 samples_left_in_step = samples_per_ducking_step;
261 }
262
263 uint32_t samples_to_duck = std::min(input_samples_to_duck, samples_left_in_step);
264 samples_to_duck = std::min(samples_to_duck, *ducking_transition_samples_remaining);
265
266 // Ensure we only point to valid index in the Q15 scaling factor table
267 uint8_t safe_db_reduction_index =
268 clamp<uint8_t>(*current_ducking_db_reduction, 0, DECIBEL_REDUCTION_TABLE.size() - 1);
269 int16_t q15_scale_factor = DECIBEL_REDUCTION_TABLE[safe_db_reduction_index];
270
271 audio::scale_audio_samples(input_buffer, input_buffer, q15_scale_factor, samples_to_duck);
272
273 if (samples_left_in_step - samples_to_duck == 0) {
274 // After scaling the current samples, we are ready to transition to the next step
275 *current_ducking_db_reduction += db_change_per_ducking_step;
276 }
277
278 input_buffer += samples_to_duck;
279 *ducking_transition_samples_remaining -= samples_to_duck;
280 input_samples_to_duck -= samples_to_duck;
281 }
282 }
283
284 if ((*current_ducking_db_reduction > 0) && (input_samples_to_duck > 0)) {
285 // Audio is ducked, but its not in the middle of a transition step
286
287 uint8_t safe_db_reduction_index =
288 clamp<uint8_t>(*current_ducking_db_reduction, 0, DECIBEL_REDUCTION_TABLE.size() - 1);
289 int16_t q15_scale_factor = DECIBEL_REDUCTION_TABLE[safe_db_reduction_index];
290
291 audio::scale_audio_samples(input_buffer, input_buffer, q15_scale_factor, input_samples_to_duck);
292 }
293}
294
296 ESP_LOGCONFIG(TAG,
297 "Speaker Mixer:\n"
298 " Number of output channels: %u",
299 this->output_channels_);
300}
301
303 this->event_group_ = xEventGroupCreate();
304
305 if (this->event_group_ == nullptr) {
306 ESP_LOGE(TAG, "Failed to create event group");
307 this->mark_failed();
308 return;
309 }
310}
311
313 uint32_t event_group_bits = xEventGroupGetBits(this->event_group_);
314
315 if (event_group_bits & MixerEventGroupBits::STATE_STARTING) {
316 ESP_LOGD(TAG, "Starting speaker mixer");
317 xEventGroupClearBits(this->event_group_, MixerEventGroupBits::STATE_STARTING);
318 }
319 if (event_group_bits & MixerEventGroupBits::ERR_ESP_NO_MEM) {
320 this->status_set_error("Failed to allocate the mixer's internal buffer");
321 xEventGroupClearBits(this->event_group_, MixerEventGroupBits::ERR_ESP_NO_MEM);
322 }
323 if (event_group_bits & MixerEventGroupBits::STATE_RUNNING) {
324 ESP_LOGD(TAG, "Started speaker mixer");
325 this->status_clear_error();
326 xEventGroupClearBits(this->event_group_, MixerEventGroupBits::STATE_RUNNING);
327 }
328 if (event_group_bits & MixerEventGroupBits::STATE_STOPPING) {
329 ESP_LOGD(TAG, "Stopping speaker mixer");
330 xEventGroupClearBits(this->event_group_, MixerEventGroupBits::STATE_STOPPING);
331 }
332 if (event_group_bits & MixerEventGroupBits::STATE_STOPPED) {
333 if (this->delete_task_() == ESP_OK) {
334 xEventGroupClearBits(this->event_group_, MixerEventGroupBits::ALL_BITS);
335 }
336 }
337
338 if (this->task_handle_ != nullptr) {
339 bool all_stopped = true;
340
341 for (auto &speaker : this->source_speakers_) {
342 all_stopped &= speaker->is_stopped();
343 }
344
345 if (all_stopped) {
346 this->stop();
347 }
348 }
349}
350
352 if (!this->audio_stream_info_.has_value()) {
353 if (stream_info.get_bits_per_sample() != 16) {
354 // Audio streams that don't have 16 bits per sample are not supported
355 return ESP_ERR_NOT_SUPPORTED;
356 }
357
358 this->audio_stream_info_ = audio::AudioStreamInfo(stream_info.get_bits_per_sample(), this->output_channels_,
359 stream_info.get_sample_rate());
361 } else {
362 if (!this->queue_mode_ && (stream_info.get_sample_rate() != this->audio_stream_info_.value().get_sample_rate())) {
363 // The two audio streams must have the same sample rate to mix properly if not in queue mode
364 return ESP_ERR_INVALID_ARG;
365 }
366 }
367
368 return this->start_task_();
369}
370
372 if (this->task_stack_buffer_ == nullptr) {
373 if (this->task_stack_in_psram_) {
375 this->task_stack_buffer_ = stack_allocator.allocate(TASK_STACK_SIZE);
376 } else {
378 this->task_stack_buffer_ = stack_allocator.allocate(TASK_STACK_SIZE);
379 }
380 }
381
382 if (this->task_stack_buffer_ == nullptr) {
383 return ESP_ERR_NO_MEM;
384 }
385
386 if (this->task_handle_ == nullptr) {
387 this->task_handle_ = xTaskCreateStatic(audio_mixer_task, "mixer", TASK_STACK_SIZE, (void *) this,
388 MIXER_TASK_PRIORITY, this->task_stack_buffer_, &this->task_stack_);
389 }
390
391 if (this->task_handle_ == nullptr) {
392 return ESP_ERR_INVALID_STATE;
393 }
394
395 return ESP_OK;
396}
397
399 if (!this->task_created_) {
400 this->task_handle_ = nullptr;
401
402 if (this->task_stack_buffer_ != nullptr) {
403 if (this->task_stack_in_psram_) {
405 stack_allocator.deallocate(this->task_stack_buffer_, TASK_STACK_SIZE);
406 } else {
408 stack_allocator.deallocate(this->task_stack_buffer_, TASK_STACK_SIZE);
409 }
410
411 this->task_stack_buffer_ = nullptr;
412 }
413
414 return ESP_OK;
415 }
416
417 return ESP_ERR_INVALID_STATE;
418}
419
421
422void MixerSpeaker::copy_frames(const int16_t *input_buffer, audio::AudioStreamInfo input_stream_info,
423 int16_t *output_buffer, audio::AudioStreamInfo output_stream_info,
424 uint32_t frames_to_transfer) {
425 uint8_t input_channels = input_stream_info.get_channels();
426 uint8_t output_channels = output_stream_info.get_channels();
427 const uint8_t max_input_channel_index = input_channels - 1;
428
429 if (input_channels == output_channels) {
430 size_t bytes_to_copy = input_stream_info.frames_to_bytes(frames_to_transfer);
431 memcpy(output_buffer, input_buffer, bytes_to_copy);
432
433 return;
434 }
435
436 for (uint32_t frame_index = 0; frame_index < frames_to_transfer; ++frame_index) {
437 for (uint8_t output_channel_index = 0; output_channel_index < output_channels; ++output_channel_index) {
438 uint8_t input_channel_index = std::min(output_channel_index, max_input_channel_index);
439 output_buffer[output_channels * frame_index + output_channel_index] =
440 input_buffer[input_channels * frame_index + input_channel_index];
441 }
442 }
443}
444
445void MixerSpeaker::mix_audio_samples(const int16_t *primary_buffer, audio::AudioStreamInfo primary_stream_info,
446 const int16_t *secondary_buffer, audio::AudioStreamInfo secondary_stream_info,
447 int16_t *output_buffer, audio::AudioStreamInfo output_stream_info,
448 uint32_t frames_to_mix) {
449 const uint8_t primary_channels = primary_stream_info.get_channels();
450 const uint8_t secondary_channels = secondary_stream_info.get_channels();
451 const uint8_t output_channels = output_stream_info.get_channels();
452
453 const uint8_t max_primary_channel_index = primary_channels - 1;
454 const uint8_t max_secondary_channel_index = secondary_channels - 1;
455
456 for (uint32_t frames_index = 0; frames_index < frames_to_mix; ++frames_index) {
457 for (uint8_t output_channel_index = 0; output_channel_index < output_channels; ++output_channel_index) {
458 const uint32_t secondary_channel_index = std::min(output_channel_index, max_secondary_channel_index);
459 const int32_t secondary_sample = secondary_buffer[frames_index * secondary_channels + secondary_channel_index];
460
461 const uint32_t primary_channel_index = std::min(output_channel_index, max_primary_channel_index);
462 const int32_t primary_sample =
463 static_cast<int32_t>(primary_buffer[frames_index * primary_channels + primary_channel_index]);
464
465 const int32_t added_sample = secondary_sample + primary_sample;
466
467 output_buffer[frames_index * output_channels + output_channel_index] =
468 static_cast<int16_t>(clamp<int32_t>(added_sample, MIN_AUDIO_SAMPLE_VALUE, MAX_AUDIO_SAMPLE_VALUE));
469 }
470 }
471}
472
474 MixerSpeaker *this_mixer = (MixerSpeaker *) params;
475
476 xEventGroupSetBits(this_mixer->event_group_, MixerEventGroupBits::STATE_STARTING);
477
478 this_mixer->task_created_ = true;
479
480 std::unique_ptr<audio::AudioSinkTransferBuffer> output_transfer_buffer = audio::AudioSinkTransferBuffer::create(
481 this_mixer->audio_stream_info_.value().ms_to_bytes(TRANSFER_BUFFER_DURATION_MS));
482
483 if (output_transfer_buffer == nullptr) {
484 xEventGroupSetBits(this_mixer->event_group_,
486
487 this_mixer->task_created_ = false;
488 vTaskDelete(nullptr);
489 }
490
491 output_transfer_buffer->set_sink(this_mixer->output_speaker_);
492
493 xEventGroupSetBits(this_mixer->event_group_, MixerEventGroupBits::STATE_RUNNING);
494
495 bool sent_finished = false;
496
497 while (true) {
498 uint32_t event_group_bits = xEventGroupGetBits(this_mixer->event_group_);
499 if (event_group_bits & MixerEventGroupBits::COMMAND_STOP) {
500 break;
501 }
502
503 // Never shift the data in the output transfer buffer to avoid unnecessary, slow data moves
504 output_transfer_buffer->transfer_data_to_sink(pdMS_TO_TICKS(TASK_DELAY_MS), false);
505
506 const uint32_t output_frames_free =
507 this_mixer->audio_stream_info_.value().bytes_to_frames(output_transfer_buffer->free());
508
509 std::vector<SourceSpeaker *> speakers_with_data;
510 std::vector<std::shared_ptr<audio::AudioSourceTransferBuffer>> transfer_buffers_with_data;
511
512 for (auto &speaker : this_mixer->source_speakers_) {
513 if (speaker->get_transfer_buffer().use_count() > 0) {
514 std::shared_ptr<audio::AudioSourceTransferBuffer> transfer_buffer = speaker->get_transfer_buffer().lock();
515 speaker->process_data_from_source(0); // Transfers and ducks audio from source ring buffers
516
517 if ((transfer_buffer->available() > 0) && !speaker->get_pause_state()) {
518 // Store the locked transfer buffers in their own vector to avoid releasing ownership until after the loop
519 transfer_buffers_with_data.push_back(transfer_buffer);
520 speakers_with_data.push_back(speaker);
521 }
522 }
523 }
524
525 if (transfer_buffers_with_data.empty()) {
526 // No audio available for transferring, block task temporarily
527 delay(TASK_DELAY_MS);
528 continue;
529 }
530
531 uint32_t frames_to_mix = output_frames_free;
532
533 if ((transfer_buffers_with_data.size() == 1) || this_mixer->queue_mode_) {
534 // Only one speaker has audio data, just copy samples over
535
536 audio::AudioStreamInfo active_stream_info = speakers_with_data[0]->get_audio_stream_info();
537
538 if (active_stream_info.get_sample_rate() ==
540 // Speaker's sample rate matches the output speaker's, copy directly
541
542 const uint32_t frames_available_in_buffer =
543 active_stream_info.bytes_to_frames(transfer_buffers_with_data[0]->available());
544 frames_to_mix = std::min(frames_to_mix, frames_available_in_buffer);
545 copy_frames(reinterpret_cast<int16_t *>(transfer_buffers_with_data[0]->get_buffer_start()), active_stream_info,
546 reinterpret_cast<int16_t *>(output_transfer_buffer->get_buffer_end()),
547 this_mixer->audio_stream_info_.value(), frames_to_mix);
548
549 // Update source speaker buffer length
550 transfer_buffers_with_data[0]->decrease_buffer_length(active_stream_info.frames_to_bytes(frames_to_mix));
551 speakers_with_data[0]->pending_playback_frames_ += frames_to_mix;
552
553 // Update output transfer buffer length
554 output_transfer_buffer->increase_buffer_length(
555 this_mixer->audio_stream_info_.value().frames_to_bytes(frames_to_mix));
556 } else {
557 // Speaker's stream info doesn't match the output speaker's, so it's a new source speaker
558 if (!this_mixer->output_speaker_->is_stopped()) {
559 if (!sent_finished) {
560 this_mixer->output_speaker_->finish();
561 sent_finished = true; // Avoid repeatedly sending the finish command
562 }
563 } else {
564 // Speaker has finished writing the current audio, update the stream information and restart the speaker
565 this_mixer->audio_stream_info_ =
566 audio::AudioStreamInfo(active_stream_info.get_bits_per_sample(), this_mixer->output_channels_,
567 active_stream_info.get_sample_rate());
568 this_mixer->output_speaker_->set_audio_stream_info(this_mixer->audio_stream_info_.value());
569 this_mixer->output_speaker_->start();
570 sent_finished = false;
571 }
572 }
573 } else {
574 // Determine how many frames to mix
575 for (int i = 0; i < transfer_buffers_with_data.size(); ++i) {
576 const uint32_t frames_available_in_buffer =
577 speakers_with_data[i]->get_audio_stream_info().bytes_to_frames(transfer_buffers_with_data[i]->available());
578 frames_to_mix = std::min(frames_to_mix, frames_available_in_buffer);
579 }
580 int16_t *primary_buffer = reinterpret_cast<int16_t *>(transfer_buffers_with_data[0]->get_buffer_start());
581 audio::AudioStreamInfo primary_stream_info = speakers_with_data[0]->get_audio_stream_info();
582
583 // Mix two streams together
584 for (int i = 1; i < transfer_buffers_with_data.size(); ++i) {
585 mix_audio_samples(primary_buffer, primary_stream_info,
586 reinterpret_cast<int16_t *>(transfer_buffers_with_data[i]->get_buffer_start()),
587 speakers_with_data[i]->get_audio_stream_info(),
588 reinterpret_cast<int16_t *>(output_transfer_buffer->get_buffer_end()),
589 this_mixer->audio_stream_info_.value(), frames_to_mix);
590
591 if (i != transfer_buffers_with_data.size() - 1) {
592 // Need to mix more streams together, point primary buffer and stream info to the already mixed output
593 primary_buffer = reinterpret_cast<int16_t *>(output_transfer_buffer->get_buffer_end());
594 primary_stream_info = this_mixer->audio_stream_info_.value();
595 }
596 }
597
598 // Update source transfer buffer lengths and add new audio durations to the source speaker pending playbacks
599 for (int i = 0; i < transfer_buffers_with_data.size(); ++i) {
600 transfer_buffers_with_data[i]->decrease_buffer_length(
601 speakers_with_data[i]->get_audio_stream_info().frames_to_bytes(frames_to_mix));
602 speakers_with_data[i]->pending_playback_frames_ += frames_to_mix;
603 }
604
605 // Update output transfer buffer length
606 output_transfer_buffer->increase_buffer_length(
607 this_mixer->audio_stream_info_.value().frames_to_bytes(frames_to_mix));
608 }
609 }
610
611 xEventGroupSetBits(this_mixer->event_group_, MixerEventGroupBits::STATE_STOPPING);
612
613 output_transfer_buffer.reset();
614
615 xEventGroupSetBits(this_mixer->event_group_, MixerEventGroupBits::STATE_STOPPED);
616 this_mixer->task_created_ = false;
617 vTaskDelete(nullptr);
618}
619
620} // namespace mixer_speaker
621} // namespace esphome
622
623#endif
virtual void mark_failed()
Mark this component as failed.
void status_set_error(const char *message="unspecified")
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:764
void deallocate(T *p, size_t n)
Definition helpers.h:822
T * allocate(size_t n)
Definition helpers.h:784
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:29
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:28
uint16_t length
Definition tt21100.cpp:0