ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
speaker_source_media_player.cpp
Go to the documentation of this file.
2
3#ifdef USE_ESP32
4
6#include "esphome/core/log.h"
7
8#include <algorithm>
9
11
12static constexpr uint32_t MEDIA_CONTROLS_QUEUE_LENGTH = 20;
13
14ESPHOME_LOG_TAG(TAG, "speaker_source_media_player");
15
16// SourceBinding method implementations (defined here because SpeakerSourceMediaPlayer is forward-declared in the
17// header)
18
19// THREAD CONTEXT: Called from media source decode task thread
20size_t SourceBinding::write_audio(const uint8_t *data, size_t length, uint32_t timeout_ms,
21 const audio::AudioStreamInfo &stream_info) {
22 return this->player->handle_media_output_(this->pipeline, this->source, data, length, timeout_ms, stream_info);
23}
24
25// THREAD CONTEXT: Called from main loop (media source's loop() calls set_state_ which calls report_state)
29
30// THREAD CONTEXT: Called from media source task thread; uses defer() to marshal to main loop
32 this->player->defer([this, volume]() { this->player->handle_volume_request_(volume); });
33}
34
35// THREAD CONTEXT: Called from media source task thread; uses defer() to marshal to main loop
36void SourceBinding::request_mute(bool is_muted) {
37 this->player->defer([this, is_muted]() { this->player->handle_mute_request_(is_muted); });
38}
39
40// THREAD CONTEXT: Called from media source task thread; uses defer() to marshal to main loop
41void SourceBinding::request_play_uri(const std::string &uri) {
42 this->player->defer([this, uri]() { this->player->handle_play_uri_request_(this->pipeline, uri); });
43}
44
45// THREAD CONTEXT: Called during code generation setup (main loop)
47 auto &binding =
48 this->pipelines_[pipeline].sources.emplace_back(std::make_unique<SourceBinding>(this, media_source, pipeline));
49 media_source->set_listener(binding.get());
50}
51
53 ESP_LOGCONFIG(TAG,
54 "Speaker Source Media Player:\n"
55 " Volume Increment: %.2f\n"
56 " Volume Min: %.2f\n"
57 " Volume Max: %.2f",
58 this->volume_increment_, this->volume_min_, this->volume_max_);
60 ESP_LOGCONFIG(TAG, " Announcement Volume: %.2f", this->announcement_volume_.get_volume());
61 }
62}
63
66
67 this->media_control_command_queue_ = xQueueCreate(MEDIA_CONTROLS_QUEUE_LENGTH, sizeof(MediaPlayerControlCommand));
68
70
71 VolumeRestoreState volume_restore_state;
72 if (this->pref_.load(&volume_restore_state)) {
73 this->set_volume_(volume_restore_state.volume);
74 this->set_mute_state_(volume_restore_state.is_muted);
75 } else {
76 this->set_volume_(this->volume_initial_);
77 this->set_mute_state_(false);
78 }
79
80 // Register callbacks to receive playback notifications from speakers
81 for (size_t i = 0; i < this->pipelines_.size(); i++) {
82 if (this->pipelines_[i].is_configured()) {
83 this->pipelines_[i].speaker->add_audio_output_callback([this, i](uint32_t frames, int64_t timestamp) {
85 });
86 }
87 }
88}
89
90// THREAD CONTEXT: Called from the speaker's playback callback task (not main loop)
92 PipelineContext &ps = this->pipelines_[pipeline];
93
94 // Load once so the null check and use below are consistent
95 media_source::MediaSource *active_source = ps.active_source.load(std::memory_order_relaxed);
96 if (active_source == nullptr) {
97 return;
98 }
99
100 // CAS loop to safely subtract frames without underflow. If pending_frames is reset to 0 (new source
101 // starting) between the load and the subtract, compare_exchange_weak will fail and reload the current value.
102 uint32_t current = ps.pending_frames.load(std::memory_order_relaxed);
103 uint32_t source_frames;
104 do {
105 source_frames = std::min(frames, current);
106 } while (source_frames > 0 &&
107 !ps.pending_frames.compare_exchange_weak(current, current - source_frames, std::memory_order_relaxed));
108
109 if (source_frames > 0) {
110 // Notify the source about the played audio
111 active_source->notify_audio_played(source_frames, timestamp);
112 }
113}
114
115// THREAD CONTEXT: Called from main loop via defer()
117 // Update the media player's volume
118 this->set_volume_(volume);
119 this->publish_state();
120}
121
122// THREAD CONTEXT: Called from main loop via defer()
124 // Update the media player's mute state
125 this->set_mute_state_(is_muted);
126 this->publish_state();
127}
128
129// THREAD CONTEXT: Called from main loop via defer()
130void SpeakerSourceMediaPlayer::handle_play_uri_request_(uint8_t pipeline, const std::string &uri) {
131 // Smart source is requesting the player to play a different URI
132 auto call = this->make_call();
133 call.set_media_url(uri);
134 call.set_announcement(pipeline == ANNOUNCEMENT_PIPELINE);
135 call.perform();
136}
137
138// THREAD CONTEXT: Called from main loop (media source's loop() calls set_state_ which calls report_state)
141 PipelineContext &ps = this->pipelines_[pipeline];
142
144 // Track whether this IDLE was from an orchestrator-initiated stop (e.g., NEXT/PREV/PLAY_URI)
145 // so we can suppress spurious PLAYLIST_ADVANCE below
146 bool was_stopping = (ps.stopping_source == source);
147
148 // Source went idle - clear stopping flag if this was the source we asked to stop
149 if (was_stopping) {
150 ps.stopping_source = nullptr;
151 }
152
153 // Clear pending flag if this was the source we asked to play
154 if (ps.pending_source == source) {
155 ps.pending_source = nullptr;
156 }
157
158 // Source went idle - clear it if it's the active source
159 if (ps.active_source == source) {
161 ps.active_source = nullptr;
162
163 // Finish the speaker to ensure it's ready for the next playback
164 ps.speaker->finish();
165
166 // Only advance the playlist if the track finished naturally (not stopped by the orchestrator)
167 if (!was_stopping) {
169 }
170 }
172 // Source started playing - make it the active source if no one else is active
173 if (ps.active_source == nullptr) {
174 ps.active_source = source;
175 ps.last_source = nullptr;
176
177 // Clear pending flag now that the source is active
178 if (ps.pending_source == source) {
179 ps.pending_source = nullptr;
180 }
181 }
183 // Logged here, on the transition, because the source stays in ERROR until the next play or stop
184 ESP_LOGE(TAG, "%s source error",
185 pipeline == ANNOUNCEMENT_PIPELINE ? LOG_STR_LITERAL("Announcement") : LOG_STR_LITERAL("Media"));
186 // A source that fails before reaching PLAYING never becomes the active source, so its IDLE never advances the
187 // playlist and every item enqueued after it would wait behind it. Advance past it now, unless it is being stopped.
188 // It stays pending so a stop still reaches it; its later IDLE advances nothing because it was never active.
189 if (ps.pending_source == source && ps.active_source != source && ps.stopping_source != source) {
191 }
192 }
193}
194
195// THREAD CONTEXT: Called from media source decode task thread (not main loop).
196// Reads ps.active_source (atomic), writes ps.pending_frames (atomic), and calls
197// ps.speaker methods (speaker pointer is immutable after setup).
199 const uint8_t *data, size_t length, uint32_t timeout_ms,
200 const audio::AudioStreamInfo &stream_info) {
201 PipelineContext &ps = this->pipelines_[pipeline];
202
203 // Single read; the if-body only uses ps.speaker (immutable after setup) and the source parameter.
204 if (ps.active_source == source) {
205 // This source is active - play the audio
206 if (ps.speaker->get_audio_stream_info() != stream_info) {
207 if (ps.speaker->is_stopped()) {
208 // Setup the speaker to play this stream
209 ps.speaker->set_audio_stream_info(stream_info);
210 } else {
211 // A running speaker drops the audio already written when its format changes, so play that out first
212 // and reopen the speaker in the new format once it stops
213 ps.speaker->finish();
214 }
215 vTaskDelay(pdMS_TO_TICKS(timeout_ms));
216 return 0;
217 }
218 // Reserve frames before the speaker can play them and report their progress,
219 // then release the portion it did not accept.
220 const uint32_t reserved_frames = stream_info.bytes_to_frames(length);
221 ps.pending_frames.fetch_add(reserved_frames, std::memory_order_relaxed);
222 size_t bytes_written = ps.speaker->play(data, length, pdMS_TO_TICKS(timeout_ms));
223 const uint32_t unused_frames = reserved_frames - stream_info.bytes_to_frames(bytes_written);
224 if (unused_frames > 0) {
225 // The main loop may reset pending_frames while play() is blocked.
226 // Clamp the release so that a concurrent reset cannot cause underflow.
227 uint32_t pending = ps.pending_frames.load(std::memory_order_relaxed);
228 while (!ps.pending_frames.compare_exchange_weak(pending, pending - std::min(pending, unused_frames),
229 std::memory_order_relaxed)) {
230 }
231 }
232 return bytes_written;
233 }
234
235 // Not the active source - wait for state callback to set us as active when we transition to PLAYING
236 vTaskDelay(pdMS_TO_TICKS(timeout_ms));
237 return 0;
238}
239
240// THREAD CONTEXT: Called from main loop (loop)
242 media_source::MediaSource *source, bool playlist_active, media_player::MediaPlayerState old_state) const {
243 if (source != nullptr) {
244 switch (source->get_state()) {
251 default:
253 }
254 }
255
256 // No active source. Stay PLAYING during playlist transitions
257 if (playlist_active && old_state == media_player::MEDIA_PLAYER_STATE_PLAYING) {
259 }
261}
262
264 // Process queued control commands
266
267 // Update state based on active sources - announcement pipeline takes priority
268 media_player::MediaPlayerState old_state = this->state;
269
271 PipelineContext &media_ps = this->pipelines_[MEDIA_PIPELINE];
272
273 // Check playlist state to detect transitions between items
274 bool announcement_playlist_active = (ann_ps.playlist_index < ann_ps.playlist.size()) ||
275 (ann_ps.repeat_mode != REPEAT_OFF && !ann_ps.playlist.empty());
276 bool media_playlist_active = (media_ps.playlist_index < media_ps.playlist.size()) ||
277 (media_ps.repeat_mode != REPEAT_OFF && !media_ps.playlist.empty());
278
279 // Check announcement pipeline first
280 media_source::MediaSource *announcement_source = ann_ps.active_source;
281 if (announcement_source != nullptr) {
282 media_source::MediaSourceState announcement_state = announcement_source->get_state();
283 if (announcement_state != media_source::MediaSourceState::IDLE) {
284 // Announcement is active - announcements take priority and never report PAUSED
285 switch (announcement_state) {
287 case media_source::MediaSourceState::PAUSED: // Treat paused announcements as announcing
289 break;
291 // Fall through to media pipeline state
292 this->state = this->get_source_state_(media_ps.active_source, media_playlist_active, old_state);
293 break;
294 default:
295 break;
296 }
297 } else {
298 // Announcement source is idle, fall through to media pipeline
299 this->state = this->get_source_state_(media_ps.active_source, media_playlist_active, old_state);
300 }
301 } else if (announcement_playlist_active && old_state == media_player::MEDIA_PLAYER_STATE_ANNOUNCING) {
303 } else {
304 // No active announcement, check media pipeline
305 this->state = this->get_source_state_(media_ps.active_source, media_playlist_active, old_state);
306 }
307
308 // After the source goes idle the speaker still plays its buffered audio, so also wait until it has stopped
309 if (this->is_media_playing_() ||
310 (ann_ps.is_configured() && ann_ps.active_source == nullptr && ann_ps.pending_source == nullptr &&
311 !announcement_playlist_active && ann_ps.speaker->is_stopped())) {
313 }
314
315 if (this->state != old_state) {
316 this->publish_state();
317 ESP_LOGD(TAG, "State changed to %s", media_player::media_player_state_to_string(this->state));
318 }
319}
320
322 const PipelineContext &ps = this->pipelines_[MEDIA_PIPELINE];
324 if (source != nullptr) {
326 }
327 // After the source goes idle the speaker still plays its buffered audio
328 return ps.is_configured() && !ps.speaker->is_stopped();
329}
330
332 PipelineContext &ps = this->pipelines_[pipeline];
333 media_source::MediaSource *first_match = nullptr;
334 for (auto &binding : ps.sources) {
335 if (binding->source->can_handle(uri)) {
336 // Prefer an idle source; otherwise remember the first match (will be stopped by try_execute_play_uri_)
337 if (binding->source->get_state() == media_source::MediaSourceState::IDLE) {
338 return binding->source;
339 }
340 if (first_match == nullptr) {
341 first_match = binding->source;
342 }
343 }
344 }
345 return first_match;
346}
347
348bool SpeakerSourceMediaPlayer::try_execute_play_uri_(const std::string &uri, uint8_t pipeline) {
349 // Find target source
350 media_source::MediaSource *target_source = this->find_source_for_uri_(uri, pipeline);
351 if (target_source == nullptr) {
352 ESP_LOGW(TAG, "No source for URI");
353 ESP_LOGV(TAG, "URI: %s", uri.c_str());
354 return true; // Remove from queue (unrecoverable)
355 }
356
357 PipelineContext &ps = this->pipelines_[pipeline];
358
359 media_source::MediaSource *active_source = ps.active_source;
360
361 // If active source exists and is not IDLE, stop it and wait
362 if (active_source != nullptr) {
363 media_source::MediaSourceState active_state = active_source->get_state();
364 if (active_state != media_source::MediaSourceState::IDLE) {
365 // Only send END command once per source - check if we've already asked this source to stop
366 if (ps.stopping_source != active_source) {
367 ESP_LOGV(TAG, "Pipeline %u: stopping active source", pipeline);
368 ps.stopping_source = active_source;
370 ps.speaker->stop();
371 }
372 return false; // Leave in queue, retry next loop
373 }
374 }
375
376 // Also check target source directly - handles case where source errored before PLAYING state
377 media_source::MediaSourceState target_state = target_source->get_state();
378 if (target_state != media_source::MediaSourceState::IDLE) {
379 // Only send STOP command once per source
380 if (ps.stopping_source != target_source) {
381 ESP_LOGV(TAG, "Pipeline %u: target source busy, stopping", pipeline);
382 ps.stopping_source = target_source;
384 ps.speaker->stop();
385 }
386 return false; // Leave in queue, retry next loop
387 }
388
389 // Clear stopping flag since we're past the stopping phase
390 ps.stopping_source = nullptr;
391
392 // Check if speaker is ready
393 if (!ps.speaker->is_stopped()) {
394 return false; // Speaker not ready yet, retry later
395 }
396
397 // Without a media pipeline, media also plays on the announcement pipeline and must keep the media volume
398 if (pipeline == ANNOUNCEMENT_PIPELINE && this->pipelines_[MEDIA_PIPELINE].is_configured()) {
402 }
403
404 // Set pending source so handle_media_state_changed_ can recognize it when the source transitions to PLAYING
405 ps.pending_source = target_source;
406
407 // Speaker is ready, try to play
408 if (!target_source->play_uri(uri)) {
409 ESP_LOGE(TAG, "Pipeline %u: Failed to play URI: %s", pipeline, uri.c_str());
410 ps.pending_source = nullptr;
412 }
413
414 // Reset pending frame counter for this pipeline since we're starting a new source
415 ps.pending_frames.store(0, std::memory_order_relaxed);
416
417 return true; // Remove from queue
418}
419
420// THREAD CONTEXT: Called from main loop (process_control_queue_, queue_play_current_, handle_media_state_changed_)
423 cmd.type = type;
424 cmd.pipeline = pipeline;
425 if (xQueueSend(this->media_control_command_queue_, &cmd, 0) != pdTRUE) {
426 ESP_LOGE(TAG, "Queue full, command dropped");
427 }
428}
429
430// THREAD CONTEXT: Called from main loop via automation commands (direct)
432 if (pipeline < this->pipelines_.size()) {
433 this->pipelines_[pipeline].playlist_delay_ms = delay_ms;
434 }
435}
436
437// THREAD CONTEXT: Called from main loop (process_control_queue_).
438// The timeout callback also runs on the main loop.
440 if (delay_ms > 0) {
441 this->set_timeout(PIPELINE_TIMEOUT_IDS[pipeline], delay_ms,
442 [this, pipeline]() { this->queue_command_(MediaPlayerControlCommand::PLAY_CURRENT, pipeline); });
443 } else {
445 }
446}
447
448// THREAD CONTEXT: Called from main loop (loop)
450 MediaPlayerControlCommand control_command{};
451
452 // Use peek to check command without removing it
453 if (xQueuePeek(this->media_control_command_queue_, &control_command, 0) != pdTRUE) {
454 return;
455 }
456
457 bool command_executed = false;
458 uint8_t pipeline = control_command.pipeline;
459
460 // Get pipeline state
461 PipelineContext &ps = this->pipelines_[pipeline];
462 media_source::MediaSource *active_source = ps.active_source;
463
464 switch (control_command.type) {
466 // Always use our local playlist to start playback
467 this->cancel_timeout(PIPELINE_TIMEOUT_IDS[pipeline]);
468 ps.playlist.clear();
469 ps.shuffle_indices.clear(); // Clear shuffle when starting fresh playlist
470 ps.playlist_index = 0; // Reset index
471 ps.playlist.push_back(*control_command.data.uri);
472
473 // Queue PLAY_CURRENT to initiate playback
475 command_executed = true;
476 break;
477 }
478
480 // Always add to our local playlist
481 ps.playlist.push_back(*control_command.data.uri);
482
483 // If shuffle is active, add the new item to the end of the shuffle order
484 if (!ps.shuffle_indices.empty()) {
485 ps.shuffle_indices.push_back(ps.playlist.size() - 1);
486 }
487
488 // If nothing is playing and no upcoming items are queued, start the new item.
489 bool nothing_playing =
490 (active_source == nullptr) || (active_source->get_state() == media_source::MediaSourceState::IDLE);
491 if (nothing_playing && ps.playlist_index >= ps.playlist.size() - 1) {
492 ps.playlist_index = ps.playlist.size() - 1; // Point to newly added item
494 }
495 command_executed = true;
496 break;
497 }
498
500 // Internal message: a track finished, advance to next
501 if (ps.repeat_mode != REPEAT_ONE) {
502 ps.playlist_index++;
503 }
504
505 // Check if we should continue playback
506 if (ps.playlist_index < ps.playlist.size()) {
507 this->queue_play_current_(pipeline, ps.playlist_delay_ms);
508 } else if (ps.repeat_mode == REPEAT_ALL && !ps.playlist.empty()) {
509 if (!ps.shuffle_indices.empty()) {
510 this->shuffle_playlist_(pipeline);
511 }
512 ps.playlist_index = 0;
513 this->queue_play_current_(pipeline, ps.playlist_delay_ms);
514 }
515 command_executed = true;
516 break;
517 }
518
520 // Play the item at current playlist index (mapped through shuffle if active)
521 if (ps.playlist_index < ps.playlist.size()) {
522 size_t actual_position = this->get_playlist_position_(pipeline);
523 command_executed = this->try_execute_play_uri_(ps.playlist[actual_position], pipeline);
524 } else {
525 command_executed = true; // Index out of bounds or empty playlist
526 }
527 break;
528 }
529
531 this->handle_player_command_(control_command.data.command, pipeline);
532 command_executed = true;
533 break;
534 }
535 }
536
537 // Only remove from queue if successfully executed
538 if (command_executed) {
539 xQueueReceive(this->media_control_command_queue_, &control_command, 0);
540
541 // Delete the allocated string for PLAY_URI and ENQUEUE_URI commands
542 if (control_command.type == MediaPlayerControlCommand::PLAY_URI ||
543 control_command.type == MediaPlayerControlCommand::ENQUEUE_URI) {
544 delete control_command.data.uri;
545 }
546 }
547}
548
549// THREAD CONTEXT: Called from main loop only (via process_control_queue_)
551 uint8_t pipeline) {
552 PipelineContext &ps = this->pipelines_[pipeline];
553 media_source::MediaSource *active_source = ps.active_source;
554 bool has_internal_playlist = (active_source != nullptr) && active_source->has_internal_playlist();
555
556 // Prefer the active source, then a pending source awaiting its PLAYING callback, then the last source.
557 media_source::MediaSource *target_source = nullptr;
558 if (active_source != nullptr) {
559 target_source = active_source;
560 } else if (ps.pending_source != nullptr) {
561 target_source = ps.pending_source;
562 } else if (ps.last_source != nullptr) {
563 target_source = ps.last_source;
564 }
565
566 switch (player_command) {
568 // Convert TOGGLE to PLAY or PAUSE based on current state
569 if ((active_source != nullptr) && (active_source->get_state() == media_source::MediaSourceState::PLAYING)) {
570 if (target_source != nullptr) {
572 }
573 } else if (!has_internal_playlist && active_source == nullptr && !ps.playlist.empty()) {
574 bool last_has_internal_playlist = (ps.last_source != nullptr) && ps.last_source->has_internal_playlist();
575 if (last_has_internal_playlist) {
577 } else {
578 if (ps.playlist_index >= ps.playlist.size()) {
579 ps.playlist_index = 0;
580 }
582 }
583 } else {
584 if (target_source != nullptr) {
586 }
587 }
588 break;
589 }
590
592 if (!has_internal_playlist && active_source == nullptr && !ps.playlist.empty()) {
593 bool last_has_internal_playlist = (ps.last_source != nullptr) && ps.last_source->has_internal_playlist();
594 if (last_has_internal_playlist) {
596 } else {
597 if (ps.playlist_index >= ps.playlist.size()) {
598 ps.playlist_index = 0;
599 }
601 }
602 } else if (target_source != nullptr) {
604 }
605 break;
606 }
607
609 if (target_source != nullptr) {
611 }
612 break;
613 }
614
616 // Cleared for every source: the stop suppresses the advance that would otherwise end the playlist
617 this->cancel_timeout(PIPELINE_TIMEOUT_IDS[pipeline]);
618 ps.playlist.clear();
619 ps.shuffle_indices.clear();
620 ps.playlist_index = 0;
621 if (target_source != nullptr) {
622 ps.stopping_source = target_source;
624 // A cancelled startup may already be IDLE and emit no state transition; the decoder sources' stop() joins
625 // their tasks and drops pending events, so no PLAYING follows.
626 if (target_source->get_state() == media_source::MediaSourceState::IDLE) {
627 if (ps.pending_source == target_source)
628 ps.pending_source = nullptr;
629 ps.stopping_source = nullptr;
630 }
631 }
632 break;
633 }
634
636 if (!has_internal_playlist) {
637 this->cancel_timeout(PIPELINE_TIMEOUT_IDS[pipeline]);
638 if (ps.playlist_index + 1 < ps.playlist.size()) {
639 ps.playlist_index++;
641 } else if (ps.repeat_mode == REPEAT_ALL && !ps.playlist.empty()) {
642 ps.playlist_index = 0;
644 }
645 } else if (target_source != nullptr) {
647 }
648 break;
649 }
650
652 if (!has_internal_playlist) {
653 this->cancel_timeout(PIPELINE_TIMEOUT_IDS[pipeline]);
654 if (ps.playlist_index > 0) {
655 ps.playlist_index--;
657 } else if (ps.repeat_mode == REPEAT_ALL && !ps.playlist.empty()) {
658 ps.playlist_index = ps.playlist.size() - 1;
660 }
661 } else if (target_source != nullptr) {
663 }
664 break;
665 }
666
668 if (!has_internal_playlist) {
670 } else if (target_source != nullptr) {
672 }
673 break;
674
676 if (!has_internal_playlist) {
678 } else if (target_source != nullptr) {
680 }
681 break;
682
684 if (!has_internal_playlist) {
686 } else if (target_source != nullptr) {
688 }
689 break;
690
692 if (!has_internal_playlist) {
693 this->cancel_timeout(PIPELINE_TIMEOUT_IDS[pipeline]);
694 if (ps.playlist_index < ps.playlist.size()) {
695 size_t actual_position = this->get_playlist_position_(pipeline);
696 ps.playlist[0] = std::move(ps.playlist[actual_position]);
697 ps.playlist.resize(1);
698 ps.playlist_index = 0;
699 } else {
700 ps.playlist.clear();
701 ps.playlist_index = 0;
702 }
703 ps.shuffle_indices.clear();
704 } else if (target_source != nullptr) {
706 }
707 break;
708 }
709
711 if (!has_internal_playlist) {
712 this->shuffle_playlist_(pipeline);
713 } else if (target_source != nullptr) {
715 }
716 break;
717
719 if (!has_internal_playlist) {
720 this->unshuffle_playlist_(pipeline);
721 } else if (target_source != nullptr) {
723 }
724 break;
725
726 default:
727 // TURN_ON, TURN_OFF, ENQUEUE (handled separately with URL) are no-ops
728 break;
729 }
730}
731
732// THREAD CONTEXT: Called from main loop only. Entry points:
733// - HA/automation commands (direct)
734// - handle_play_uri_request_() via make_call().perform() (deferred from source tasks)
736 if (!this->is_ready()) {
737 return;
738 }
739
740 MediaPlayerControlCommand control_command{};
741
742 // Determine which pipeline to use based on announcement flag, falling back if the preferred pipeline
743 // is not configured
744 auto announcement = call.get_announcement();
745 if (announcement.has_value() && announcement.value()) {
746 if (this->pipelines_[ANNOUNCEMENT_PIPELINE].is_configured()) {
747 control_command.pipeline = ANNOUNCEMENT_PIPELINE;
748 } else {
749 control_command.pipeline = MEDIA_PIPELINE;
750 }
751 } else {
752 if (this->pipelines_[MEDIA_PIPELINE].is_configured()) {
753 control_command.pipeline = MEDIA_PIPELINE;
754 } else {
755 control_command.pipeline = ANNOUNCEMENT_PIPELINE;
756 }
757 }
758
759 const auto &media_url = call.get_media_url();
760 if (media_url.has_value()) {
761 auto command = call.get_command();
762 bool enqueue = command.has_value() && command.value() == media_player::MEDIA_PLAYER_COMMAND_ENQUEUE;
763
765 // Heap allocation is unavoidable: URIs from Home Assistant are arbitrary-length (media URLs with tokens
766 // can easily exceed 500 bytes). Deleted in process_control_queue_() after the command is consumed. FreeRTOS queues
767 // require items to be copyable, so we store a pointer to the string in the queue rather than the string itself.
768 control_command.data.uri = new std::string(media_url.value());
769 if (xQueueSend(this->media_control_command_queue_, &control_command, 0) != pdTRUE) {
770 delete control_command.data.uri;
771 ESP_LOGE(TAG, "Queue full, URI dropped");
772 }
773 return;
774 }
775
776 auto volume = call.get_volume();
777 if (volume.has_value()) {
778 this->set_volume_(volume.value());
779 this->publish_state();
780 return;
781 }
782
783 auto cmd = call.get_command();
784 if (cmd.has_value()) {
785 switch (cmd.value()) {
787 this->set_mute_state_(true);
788 break;
790 this->set_mute_state_(false);
791 break;
793 this->set_volume_(std::min(1.0f, this->volume + this->volume_increment_));
794 break;
796 this->set_volume_(std::max(0.0f, this->volume - this->volume_increment_));
797 break;
798 default:
799 // Queue command for processing in loop()
800 control_command.type = MediaPlayerControlCommand::SEND_COMMAND;
801 control_command.data.command = cmd.value();
802 if (xQueueSend(this->media_control_command_queue_, &control_command, 0) != pdTRUE) {
803 ESP_LOGE(TAG, "Queue full, command dropped");
804 }
805 return;
806 }
807 this->publish_state();
808 }
809}
810
812 // This media player supports more traits like playlists, repeat, and shuffle, but the ESPHome API currently (March
813 // 2026) doesn't support those commands, so we only report pause support for now since that's used by the frontend and
814 // supported by our player.
815 auto traits = media_player::MediaPlayerTraits();
816 traits.set_supports_pause(true);
817
818 for (const auto &ps : this->pipelines_) {
819 if (ps.format.has_value()) {
820 traits.get_supported_formats().push_back(ps.format.value());
821 }
822 }
823
824 return traits;
825}
826
828 VolumeRestoreState volume_restore_state;
829 volume_restore_state.volume = this->volume;
830 volume_restore_state.is_muted = this->is_muted_;
831 this->pref_.save(&volume_restore_state);
832}
833
834void SpeakerSourceMediaPlayer::set_mute_state_(bool mute_state, bool publish) {
835 if (this->is_muted_ == mute_state) {
836 return;
837 }
838
839 for (auto &ps : this->pipelines_) {
840 if (ps.is_configured()) {
841 ps.speaker->set_mute_state(mute_state);
842 }
843 }
844
845 this->is_muted_ = mute_state;
846
847 if (publish) {
849 }
850
851 // Notify all media sources about the mute state change
852 for (auto &ps : this->pipelines_) {
853 for (auto &binding : ps.sources) {
854 binding->source->notify_mute_changed(mute_state);
855 }
856 }
857
858 if (mute_state) {
859 this->defer([this]() { this->mute_trigger_.trigger(); });
860 } else {
861 this->defer([this]() { this->unmute_trigger_.trigger(); });
862 }
863}
864
865void SpeakerSourceMediaPlayer::set_volume_(float volume, bool publish) {
866 // A volume change made while an announcement uses the announcement volume applies right away
868 this->apply_speaker_volume_(volume);
869
870 if (publish) {
871 this->volume = volume;
872 }
873
874 // Notify all media sources about the volume change
875 for (auto &ps : this->pipelines_) {
876 for (auto &binding : ps.sources) {
877 binding->source->notify_volume_changed(volume);
878 }
879 }
880
881 if (publish) {
883 }
884
885 this->defer([this, volume]() { this->volume_trigger_.trigger(volume); });
886}
887
889 // Remap the volume to fit within the configured limits. An effectively zero volume is passed through as zero so
890 // the speaker silences it, otherwise volume_min would make it audible.
891 float bounded_volume = (volume < speaker::SILENT_VOLUME_THRESHOLD)
892 ? 0.0f
893 : remap<float, float>(volume, 0.0f, 1.0f, this->volume_min_, this->volume_max_);
894
895 for (auto &ps : this->pipelines_) {
896 if (ps.is_configured()) {
897 ps.speaker->set_volume(bounded_volume);
898 }
899 }
900}
901
902// THREAD CONTEXT: Called from main loop via automation commands (direct)
904 this->announcement_volume_.set_volume(announcement_volume, this->speaker_volume_applier_());
905}
906
908 const PipelineContext &ps = this->pipelines_[pipeline];
909
910 if (ps.shuffle_indices.empty() || ps.playlist_index >= ps.shuffle_indices.size()) {
911 return ps.playlist_index;
912 }
913 return ps.shuffle_indices[ps.playlist_index];
914}
915
917 PipelineContext &ps = this->pipelines_[pipeline];
918
919 if (ps.playlist.size() <= 1) {
920 ps.shuffle_indices.clear();
921 return;
922 }
923
924 // Capture current actual position BEFORE modifying shuffle_indices
925 size_t current_actual = this->get_playlist_position_(pipeline);
926
927 // Build indices vector
928 ps.shuffle_indices.resize(ps.playlist.size());
929 for (size_t i = 0; i < ps.playlist.size(); i++) {
930 ps.shuffle_indices[i] = i;
931 }
932
933 // Fisher-Yates shuffle using ESPHome's random helper
934 for (size_t i = ps.shuffle_indices.size() - 1; i > 0; i--) {
935 size_t j = random_uint32() % (i + 1);
936 std::swap(ps.shuffle_indices[i], ps.shuffle_indices[j]);
937 }
938
939 // Move current track to current position (so playback continues seamlessly)
940 if (ps.playlist_index < ps.shuffle_indices.size()) {
941 for (size_t i = 0; i < ps.shuffle_indices.size(); i++) {
942 if (ps.shuffle_indices[i] == current_actual) {
943 std::swap(ps.shuffle_indices[i], ps.shuffle_indices[ps.playlist_index]);
944 break;
945 }
946 }
947 }
948}
949
951 PipelineContext &ps = this->pipelines_[pipeline];
952
953 if (!ps.shuffle_indices.empty() && ps.playlist_index < ps.shuffle_indices.size()) {
955 }
956 ps.shuffle_indices.clear();
957}
958
959} // namespace esphome::speaker_source
960
961#endif // USE_ESP32
void defer(const char *name, SchedulerCallback &&f)
Defer a callback to the next loop() call with a const char* name.
bool cancel_timeout(const char *name)
Cancel a timeout function.
bool is_ready() const
void set_timeout(const char *name, uint32_t timeout, SchedulerCallback &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
ESPPreferenceObject make_entity_preference(uint32_t version=0)
Create a preference object for storing this entity's state/settings.
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Inform the parent automation that the event has triggered.
Definition automation.h:588
uint32_t bytes_to_frames(size_t bytes) const
Convert bytes to frames.
Definition audio.h:42
Abstract base class for media sources MediaSource provides audio data to an orchestrator via the Medi...
virtual void notify_audio_played(uint32_t frames, int64_t timestamp)
Notify the source about audio that has been played Called when the speaker reports that audio frames ...
virtual bool has_internal_playlist() const
Whether this source manages its own playlist internally Smart sources that handle next/previous/repea...
void set_listener(MediaSourceListener *listener)
Set the listener that receives callbacks from this source.
virtual void handle_command(MediaSourceCommand command)=0
Handle playback commands; e.g., pause, stop, next, etc.
MediaSourceState get_state() const
Get current playback state.
virtual bool play_uri(const std::string &uri)=0
Start playing the given URI Sources should validate the URI and state, returning false if the source ...
void cancel()
The media player volume was set and already sent to the speakers; it applies until the next announcem...
void begin(bool other_audio_playing, F &&apply)
Called when an announcement starts.
void set_volume(float volume, F &&apply)
Stores a new announcement volume and applies it right away if it is in use.
void end(float media_volume, F &&apply)
Switches back to the media player volume if the announcement volume is in use.
virtual size_t play(const uint8_t *data, size_t length)=0
Plays the provided audio data.
void set_audio_stream_info(const audio::AudioStreamInfo &audio_stream_info)
Definition speaker.h:104
audio::AudioStreamInfo & get_audio_stream_info()
Definition speaker.h:108
virtual void finish()
Definition speaker.h:60
bool is_stopped() const
Definition speaker.h:69
virtual void stop()=0
void shuffle_playlist_(uint8_t pipeline)
Generates shuffled indices for the playlist, keeping current track at current position.
void apply_speaker_volume_(float volume)
Remaps a volume to the configured limits and sends it to the speakers.
void set_playlist_delay_ms(uint8_t pipeline, uint32_t delay_ms)
void queue_play_current_(uint8_t pipeline, uint32_t delay_ms=0)
void set_mute_state_(bool mute_state, bool publish=true)
Sets the mute state.
void queue_command_(MediaPlayerControlCommand::Type type, uint8_t pipeline)
media_source::MediaSource * find_source_for_uri_(const std::string &uri, uint8_t pipeline)
void unshuffle_playlist_(uint8_t pipeline)
Clears shuffle indices and adjusts playlist_index to maintain current track.
media_player::MediaPlayerState get_source_state_(media_source::MediaSource *media_source, bool playlist_active, media_player::MediaPlayerState old_state) const
Determine media player state from a pipeline's active source.
void handle_play_uri_request_(uint8_t pipeline, const std::string &uri)
void control(const media_player::MediaPlayerCall &call) override
void handle_player_command_(media_player::MediaPlayerCommand player_command, uint8_t pipeline)
size_t get_playlist_position_(uint8_t pipeline) const
Maps playlist_index through shuffle indices if shuffle is active.
void add_media_source(uint8_t pipeline, media_source::MediaSource *media_source)
Adds a media source to a pipeline and registers this player as its listener.
auto speaker_volume_applier_()
Returns a callable that sends a volume to the speakers, for announcement_volume_ to apply its changes...
bool is_media_playing_() const
Whether media is audible: the active source plays, or the speaker plays what an idle source left.
bool try_execute_play_uri_(const std::string &uri, uint8_t pipeline)
void set_volume_(float volume, bool publish=true)
Updates this->volume and saves volume/mute state to flash for restoration if publish is true.
void handle_media_state_changed_(uint8_t pipeline, media_source::MediaSource *source, media_source::MediaSourceState state)
media_player::MediaPlayerTraits get_traits() override
void handle_speaker_playback_callback_(uint32_t frames, int64_t timestamp, uint8_t pipeline)
void set_announcement_volume(float announcement_volume)
Sets the volume for announcements that start while nothing else is playing.
void save_volume_restore_state_()
Saves the current volume and mute state to the flash for restoration.
size_t handle_media_output_(uint8_t pipeline, media_source::MediaSource *source, const uint8_t *data, size_t length, uint32_t timeout_ms, const audio::AudioStreamInfo &stream_info)
uint8_t type
bool state
Definition fan.h:2
const char * media_player_state_to_string(MediaPlayerState state)
ESPHOME_LOG_TAG(TAG, "speaker_source_media_player")
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:10
T remap(U value, U min, U max, T min_out, T max_out)
Remap value from the range (min, max) to (min_out, max_out).
Definition helpers.h:1079
static void uint32_t
bool is_configured() const
Check if this pipeline is configured (has a speaker assigned)
std::vector< std::unique_ptr< SourceBinding > > sources
std::atomic< media_source::MediaSource * > active_source
void request_play_uri(const std::string &uri) override
void report_state(media_source::MediaSourceState state) override
size_t write_audio(const uint8_t *data, size_t length, uint32_t timeout_ms, const audio::AudioStreamInfo &stream_info) override
uint16_t length
Definition tt21100.cpp:0
uint16_t timestamp
Definition tt21100.cpp:2