ESPHome 2026.11.0b6
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 }
182 }
183}
184
185// THREAD CONTEXT: Called from media source decode task thread (not main loop).
186// Reads ps.active_source (atomic), writes ps.pending_frames (atomic), and calls
187// ps.speaker methods (speaker pointer is immutable after setup).
189 const uint8_t *data, size_t length, uint32_t timeout_ms,
190 const audio::AudioStreamInfo &stream_info) {
191 PipelineContext &ps = this->pipelines_[pipeline];
192
193 // Single read; the if-body only uses ps.speaker (immutable after setup) and the source parameter.
194 if (ps.active_source == source) {
195 // This source is active - play the audio
196 if (ps.speaker->get_audio_stream_info() != stream_info) {
197 // Setup the speaker to play this stream
198 ps.speaker->set_audio_stream_info(stream_info);
199 vTaskDelay(pdMS_TO_TICKS(timeout_ms));
200 return 0;
201 }
202 // Reserve frames before the speaker can play them and report their progress,
203 // then release the portion it did not accept.
204 const uint32_t reserved_frames = stream_info.bytes_to_frames(length);
205 ps.pending_frames.fetch_add(reserved_frames, std::memory_order_relaxed);
206 size_t bytes_written = ps.speaker->play(data, length, pdMS_TO_TICKS(timeout_ms));
207 const uint32_t unused_frames = reserved_frames - stream_info.bytes_to_frames(bytes_written);
208 if (unused_frames > 0) {
209 // The main loop may reset pending_frames while play() is blocked.
210 // Clamp the release so that a concurrent reset cannot cause underflow.
211 uint32_t pending = ps.pending_frames.load(std::memory_order_relaxed);
212 while (!ps.pending_frames.compare_exchange_weak(pending, pending - std::min(pending, unused_frames),
213 std::memory_order_relaxed)) {
214 }
215 }
216 return bytes_written;
217 }
218
219 // Not the active source - wait for state callback to set us as active when we transition to PLAYING
220 vTaskDelay(pdMS_TO_TICKS(timeout_ms));
221 return 0;
222}
223
224// THREAD CONTEXT: Called from main loop (loop)
226 media_source::MediaSource *source, bool playlist_active, media_player::MediaPlayerState old_state) const {
227 if (source != nullptr) {
228 switch (source->get_state()) {
234 ESP_LOGE(TAG, "Media source error");
237 default:
239 }
240 }
241
242 // No active source. Stay PLAYING during playlist transitions
243 if (playlist_active && old_state == media_player::MEDIA_PLAYER_STATE_PLAYING) {
245 }
247}
248
250 // Process queued control commands
252
253 // Update state based on active sources - announcement pipeline takes priority
254 media_player::MediaPlayerState old_state = this->state;
255
257 PipelineContext &media_ps = this->pipelines_[MEDIA_PIPELINE];
258
259 // Check playlist state to detect transitions between items
260 bool announcement_playlist_active = (ann_ps.playlist_index < ann_ps.playlist.size()) ||
261 (ann_ps.repeat_mode != REPEAT_OFF && !ann_ps.playlist.empty());
262 bool media_playlist_active = (media_ps.playlist_index < media_ps.playlist.size()) ||
263 (media_ps.repeat_mode != REPEAT_OFF && !media_ps.playlist.empty());
264
265 // Check announcement pipeline first
266 media_source::MediaSource *announcement_source = ann_ps.active_source;
267 if (announcement_source != nullptr) {
268 media_source::MediaSourceState announcement_state = announcement_source->get_state();
269 if (announcement_state != media_source::MediaSourceState::IDLE) {
270 // Announcement is active - announcements take priority and never report PAUSED
271 switch (announcement_state) {
273 case media_source::MediaSourceState::PAUSED: // Treat paused announcements as announcing
275 break;
277 ESP_LOGE(TAG, "Announcement source error");
278 // Fall through to media pipeline state
279 this->state = this->get_source_state_(media_ps.active_source, media_playlist_active, old_state);
280 break;
281 default:
282 break;
283 }
284 } else {
285 // Announcement source is idle, fall through to media pipeline
286 this->state = this->get_source_state_(media_ps.active_source, media_playlist_active, old_state);
287 }
288 } else if (announcement_playlist_active && old_state == media_player::MEDIA_PLAYER_STATE_ANNOUNCING) {
290 } else {
291 // No active announcement, check media pipeline
292 this->state = this->get_source_state_(media_ps.active_source, media_playlist_active, old_state);
293 }
294
295 // After the source goes idle the speaker still plays its buffered audio, so also wait until it has stopped
296 if (this->is_media_playing_() ||
297 (ann_ps.is_configured() && ann_ps.active_source == nullptr && ann_ps.pending_source == nullptr &&
298 !announcement_playlist_active && ann_ps.speaker->is_stopped())) {
300 }
301
302 if (this->state != old_state) {
303 this->publish_state();
304 ESP_LOGD(TAG, "State changed to %s", media_player::media_player_state_to_string(this->state));
305 }
306}
307
309 const PipelineContext &ps = this->pipelines_[MEDIA_PIPELINE];
311 if (source != nullptr) {
313 }
314 // After the source goes idle the speaker still plays its buffered audio
315 return ps.is_configured() && !ps.speaker->is_stopped();
316}
317
319 PipelineContext &ps = this->pipelines_[pipeline];
320 media_source::MediaSource *first_match = nullptr;
321 for (auto &binding : ps.sources) {
322 if (binding->source->can_handle(uri)) {
323 // Prefer an idle source; otherwise remember the first match (will be stopped by try_execute_play_uri_)
324 if (binding->source->get_state() == media_source::MediaSourceState::IDLE) {
325 return binding->source;
326 }
327 if (first_match == nullptr) {
328 first_match = binding->source;
329 }
330 }
331 }
332 return first_match;
333}
334
335bool SpeakerSourceMediaPlayer::try_execute_play_uri_(const std::string &uri, uint8_t pipeline) {
336 // Find target source
337 media_source::MediaSource *target_source = this->find_source_for_uri_(uri, pipeline);
338 if (target_source == nullptr) {
339 ESP_LOGW(TAG, "No source for URI");
340 ESP_LOGV(TAG, "URI: %s", uri.c_str());
341 return true; // Remove from queue (unrecoverable)
342 }
343
344 PipelineContext &ps = this->pipelines_[pipeline];
345
346 media_source::MediaSource *active_source = ps.active_source;
347
348 // If active source exists and is not IDLE, stop it and wait
349 if (active_source != nullptr) {
350 media_source::MediaSourceState active_state = active_source->get_state();
351 if (active_state != media_source::MediaSourceState::IDLE) {
352 // Only send END command once per source - check if we've already asked this source to stop
353 if (ps.stopping_source != active_source) {
354 ESP_LOGV(TAG, "Pipeline %u: stopping active source", pipeline);
355 ps.stopping_source = active_source;
357 ps.speaker->stop();
358 }
359 return false; // Leave in queue, retry next loop
360 }
361 }
362
363 // Also check target source directly - handles case where source errored before PLAYING state
364 media_source::MediaSourceState target_state = target_source->get_state();
365 if (target_state != media_source::MediaSourceState::IDLE) {
366 // Only send STOP command once per source
367 if (ps.stopping_source != target_source) {
368 ESP_LOGV(TAG, "Pipeline %u: target source busy, stopping", pipeline);
369 ps.stopping_source = target_source;
371 ps.speaker->stop();
372 }
373 return false; // Leave in queue, retry next loop
374 }
375
376 // Clear stopping flag since we're past the stopping phase
377 ps.stopping_source = nullptr;
378
379 // Check if speaker is ready
380 if (!ps.speaker->is_stopped()) {
381 return false; // Speaker not ready yet, retry later
382 }
383
384 // Without a media pipeline, media also plays on the announcement pipeline and must keep the media volume
385 if (pipeline == ANNOUNCEMENT_PIPELINE && this->pipelines_[MEDIA_PIPELINE].is_configured()) {
389 }
390
391 // Set pending source so handle_media_state_changed_ can recognize it when the source transitions to PLAYING
392 ps.pending_source = target_source;
393
394 // Speaker is ready, try to play
395 if (!target_source->play_uri(uri)) {
396 ESP_LOGE(TAG, "Pipeline %u: Failed to play URI: %s", pipeline, uri.c_str());
397 ps.pending_source = nullptr;
399 }
400
401 // Reset pending frame counter for this pipeline since we're starting a new source
402 ps.pending_frames.store(0, std::memory_order_relaxed);
403
404 return true; // Remove from queue
405}
406
407// THREAD CONTEXT: Called from main loop (process_control_queue_, queue_play_current_, handle_media_state_changed_)
410 cmd.type = type;
411 cmd.pipeline = pipeline;
412 if (xQueueSend(this->media_control_command_queue_, &cmd, 0) != pdTRUE) {
413 ESP_LOGE(TAG, "Queue full, command dropped");
414 }
415}
416
417// THREAD CONTEXT: Called from main loop via automation commands (direct)
419 if (pipeline < this->pipelines_.size()) {
420 this->pipelines_[pipeline].playlist_delay_ms = delay_ms;
421 }
422}
423
424// THREAD CONTEXT: Called from main loop (process_control_queue_).
425// The timeout callback also runs on the main loop.
427 if (delay_ms > 0) {
428 this->set_timeout(PIPELINE_TIMEOUT_IDS[pipeline], delay_ms,
429 [this, pipeline]() { this->queue_command_(MediaPlayerControlCommand::PLAY_CURRENT, pipeline); });
430 } else {
432 }
433}
434
435// THREAD CONTEXT: Called from main loop (loop)
437 MediaPlayerControlCommand control_command{};
438
439 // Use peek to check command without removing it
440 if (xQueuePeek(this->media_control_command_queue_, &control_command, 0) != pdTRUE) {
441 return;
442 }
443
444 bool command_executed = false;
445 uint8_t pipeline = control_command.pipeline;
446
447 // Get pipeline state
448 PipelineContext &ps = this->pipelines_[pipeline];
449 media_source::MediaSource *active_source = ps.active_source;
450
451 switch (control_command.type) {
453 // Always use our local playlist to start playback
454 this->cancel_timeout(PIPELINE_TIMEOUT_IDS[pipeline]);
455 ps.playlist.clear();
456 ps.shuffle_indices.clear(); // Clear shuffle when starting fresh playlist
457 ps.playlist_index = 0; // Reset index
458 ps.playlist.push_back(*control_command.data.uri);
459
460 // Queue PLAY_CURRENT to initiate playback
462 command_executed = true;
463 break;
464 }
465
467 // Always add to our local playlist
468 ps.playlist.push_back(*control_command.data.uri);
469
470 // If shuffle is active, add the new item to the end of the shuffle order
471 if (!ps.shuffle_indices.empty()) {
472 ps.shuffle_indices.push_back(ps.playlist.size() - 1);
473 }
474
475 // If nothing is playing and no upcoming items are queued, start the new item.
476 bool nothing_playing =
477 (active_source == nullptr) || (active_source->get_state() == media_source::MediaSourceState::IDLE);
478 if (nothing_playing && ps.playlist_index >= ps.playlist.size() - 1) {
479 ps.playlist_index = ps.playlist.size() - 1; // Point to newly added item
481 }
482 command_executed = true;
483 break;
484 }
485
487 // Internal message: a track finished, advance to next
488 if (ps.repeat_mode != REPEAT_ONE) {
489 ps.playlist_index++;
490 }
491
492 // Check if we should continue playback
493 if (ps.playlist_index < ps.playlist.size()) {
494 this->queue_play_current_(pipeline, ps.playlist_delay_ms);
495 } else if (ps.repeat_mode == REPEAT_ALL && !ps.playlist.empty()) {
496 if (!ps.shuffle_indices.empty()) {
497 this->shuffle_playlist_(pipeline);
498 }
499 ps.playlist_index = 0;
500 this->queue_play_current_(pipeline, ps.playlist_delay_ms);
501 }
502 command_executed = true;
503 break;
504 }
505
507 // Play the item at current playlist index (mapped through shuffle if active)
508 if (ps.playlist_index < ps.playlist.size()) {
509 size_t actual_position = this->get_playlist_position_(pipeline);
510 command_executed = this->try_execute_play_uri_(ps.playlist[actual_position], pipeline);
511 } else {
512 command_executed = true; // Index out of bounds or empty playlist
513 }
514 break;
515 }
516
518 this->handle_player_command_(control_command.data.command, pipeline);
519 command_executed = true;
520 break;
521 }
522 }
523
524 // Only remove from queue if successfully executed
525 if (command_executed) {
526 xQueueReceive(this->media_control_command_queue_, &control_command, 0);
527
528 // Delete the allocated string for PLAY_URI and ENQUEUE_URI commands
529 if (control_command.type == MediaPlayerControlCommand::PLAY_URI ||
530 control_command.type == MediaPlayerControlCommand::ENQUEUE_URI) {
531 delete control_command.data.uri;
532 }
533 }
534}
535
536// THREAD CONTEXT: Called from main loop only (via process_control_queue_)
538 uint8_t pipeline) {
539 PipelineContext &ps = this->pipelines_[pipeline];
540 media_source::MediaSource *active_source = ps.active_source;
541 bool has_internal_playlist = (active_source != nullptr) && active_source->has_internal_playlist();
542
543 // Prefer the active source, then a pending source awaiting its PLAYING callback, then the last source.
544 media_source::MediaSource *target_source = nullptr;
545 if (active_source != nullptr) {
546 target_source = active_source;
547 } else if (ps.pending_source != nullptr) {
548 target_source = ps.pending_source;
549 } else if (ps.last_source != nullptr) {
550 target_source = ps.last_source;
551 }
552
553 switch (player_command) {
555 // Convert TOGGLE to PLAY or PAUSE based on current state
556 if ((active_source != nullptr) && (active_source->get_state() == media_source::MediaSourceState::PLAYING)) {
557 if (target_source != nullptr) {
559 }
560 } else if (!has_internal_playlist && active_source == nullptr && !ps.playlist.empty()) {
561 bool last_has_internal_playlist = (ps.last_source != nullptr) && ps.last_source->has_internal_playlist();
562 if (last_has_internal_playlist) {
564 } else {
565 if (ps.playlist_index >= ps.playlist.size()) {
566 ps.playlist_index = 0;
567 }
569 }
570 } else {
571 if (target_source != nullptr) {
573 }
574 }
575 break;
576 }
577
579 if (!has_internal_playlist && active_source == nullptr && !ps.playlist.empty()) {
580 bool last_has_internal_playlist = (ps.last_source != nullptr) && ps.last_source->has_internal_playlist();
581 if (last_has_internal_playlist) {
583 } else {
584 if (ps.playlist_index >= ps.playlist.size()) {
585 ps.playlist_index = 0;
586 }
588 }
589 } else if (target_source != nullptr) {
591 }
592 break;
593 }
594
596 if (target_source != nullptr) {
598 }
599 break;
600 }
601
603 // Cleared for every source: the stop suppresses the advance that would otherwise end the playlist
604 this->cancel_timeout(PIPELINE_TIMEOUT_IDS[pipeline]);
605 ps.playlist.clear();
606 ps.shuffle_indices.clear();
607 ps.playlist_index = 0;
608 if (target_source != nullptr) {
609 ps.stopping_source = target_source;
611 // A cancelled startup may already be IDLE and emit no state transition; the decoder sources' stop() joins
612 // their tasks and drops pending events, so no PLAYING follows.
613 if (target_source->get_state() == media_source::MediaSourceState::IDLE) {
614 if (ps.pending_source == target_source)
615 ps.pending_source = nullptr;
616 ps.stopping_source = nullptr;
617 }
618 }
619 break;
620 }
621
623 if (!has_internal_playlist) {
624 this->cancel_timeout(PIPELINE_TIMEOUT_IDS[pipeline]);
625 if (ps.playlist_index + 1 < ps.playlist.size()) {
626 ps.playlist_index++;
628 } else if (ps.repeat_mode == REPEAT_ALL && !ps.playlist.empty()) {
629 ps.playlist_index = 0;
631 }
632 } else if (target_source != nullptr) {
634 }
635 break;
636 }
637
639 if (!has_internal_playlist) {
640 this->cancel_timeout(PIPELINE_TIMEOUT_IDS[pipeline]);
641 if (ps.playlist_index > 0) {
642 ps.playlist_index--;
644 } else if (ps.repeat_mode == REPEAT_ALL && !ps.playlist.empty()) {
645 ps.playlist_index = ps.playlist.size() - 1;
647 }
648 } else if (target_source != nullptr) {
650 }
651 break;
652 }
653
655 if (!has_internal_playlist) {
657 } else if (target_source != nullptr) {
659 }
660 break;
661
663 if (!has_internal_playlist) {
665 } else if (target_source != nullptr) {
667 }
668 break;
669
671 if (!has_internal_playlist) {
673 } else if (target_source != nullptr) {
675 }
676 break;
677
679 if (!has_internal_playlist) {
680 this->cancel_timeout(PIPELINE_TIMEOUT_IDS[pipeline]);
681 if (ps.playlist_index < ps.playlist.size()) {
682 size_t actual_position = this->get_playlist_position_(pipeline);
683 ps.playlist[0] = std::move(ps.playlist[actual_position]);
684 ps.playlist.resize(1);
685 ps.playlist_index = 0;
686 } else {
687 ps.playlist.clear();
688 ps.playlist_index = 0;
689 }
690 ps.shuffle_indices.clear();
691 } else if (target_source != nullptr) {
693 }
694 break;
695 }
696
698 if (!has_internal_playlist) {
699 this->shuffle_playlist_(pipeline);
700 } else if (target_source != nullptr) {
702 }
703 break;
704
706 if (!has_internal_playlist) {
707 this->unshuffle_playlist_(pipeline);
708 } else if (target_source != nullptr) {
710 }
711 break;
712
713 default:
714 // TURN_ON, TURN_OFF, ENQUEUE (handled separately with URL) are no-ops
715 break;
716 }
717}
718
719// THREAD CONTEXT: Called from main loop only. Entry points:
720// - HA/automation commands (direct)
721// - handle_play_uri_request_() via make_call().perform() (deferred from source tasks)
723 if (!this->is_ready()) {
724 return;
725 }
726
727 MediaPlayerControlCommand control_command{};
728
729 // Determine which pipeline to use based on announcement flag, falling back if the preferred pipeline
730 // is not configured
731 auto announcement = call.get_announcement();
732 if (announcement.has_value() && announcement.value()) {
733 if (this->pipelines_[ANNOUNCEMENT_PIPELINE].is_configured()) {
734 control_command.pipeline = ANNOUNCEMENT_PIPELINE;
735 } else {
736 control_command.pipeline = MEDIA_PIPELINE;
737 }
738 } else {
739 if (this->pipelines_[MEDIA_PIPELINE].is_configured()) {
740 control_command.pipeline = MEDIA_PIPELINE;
741 } else {
742 control_command.pipeline = ANNOUNCEMENT_PIPELINE;
743 }
744 }
745
746 const auto &media_url = call.get_media_url();
747 if (media_url.has_value()) {
748 auto command = call.get_command();
749 bool enqueue = command.has_value() && command.value() == media_player::MEDIA_PLAYER_COMMAND_ENQUEUE;
750
751 if (enqueue) {
752 control_command.type = MediaPlayerControlCommand::ENQUEUE_URI;
753 } else {
754 control_command.type = MediaPlayerControlCommand::PLAY_URI;
755 }
756 // Heap allocation is unavoidable: URIs from Home Assistant are arbitrary-length (media URLs with tokens
757 // can easily exceed 500 bytes). Deleted in process_control_queue_() after the command is consumed. FreeRTOS queues
758 // require items to be copyable, so we store a pointer to the string in the queue rather than the string itself.
759 control_command.data.uri = new std::string(media_url.value());
760 if (xQueueSend(this->media_control_command_queue_, &control_command, 0) != pdTRUE) {
761 delete control_command.data.uri;
762 ESP_LOGE(TAG, "Queue full, URI dropped");
763 }
764 return;
765 }
766
767 auto volume = call.get_volume();
768 if (volume.has_value()) {
769 this->set_volume_(volume.value());
770 this->publish_state();
771 return;
772 }
773
774 auto cmd = call.get_command();
775 if (cmd.has_value()) {
776 switch (cmd.value()) {
778 this->set_mute_state_(true);
779 break;
781 this->set_mute_state_(false);
782 break;
784 this->set_volume_(std::min(1.0f, this->volume + this->volume_increment_));
785 break;
787 this->set_volume_(std::max(0.0f, this->volume - this->volume_increment_));
788 break;
789 default:
790 // Queue command for processing in loop()
791 control_command.type = MediaPlayerControlCommand::SEND_COMMAND;
792 control_command.data.command = cmd.value();
793 if (xQueueSend(this->media_control_command_queue_, &control_command, 0) != pdTRUE) {
794 ESP_LOGE(TAG, "Queue full, command dropped");
795 }
796 return;
797 }
798 this->publish_state();
799 }
800}
801
803 // This media player supports more traits like playlists, repeat, and shuffle, but the ESPHome API currently (March
804 // 2026) doesn't support those commands, so we only report pause support for now since that's used by the frontend and
805 // supported by our player.
806 auto traits = media_player::MediaPlayerTraits();
807 traits.set_supports_pause(true);
808
809 for (const auto &ps : this->pipelines_) {
810 if (ps.format.has_value()) {
811 traits.get_supported_formats().push_back(ps.format.value());
812 }
813 }
814
815 return traits;
816}
817
819 VolumeRestoreState volume_restore_state;
820 volume_restore_state.volume = this->volume;
821 volume_restore_state.is_muted = this->is_muted_;
822 this->pref_.save(&volume_restore_state);
823}
824
825void SpeakerSourceMediaPlayer::set_mute_state_(bool mute_state, bool publish) {
826 if (this->is_muted_ == mute_state) {
827 return;
828 }
829
830 for (auto &ps : this->pipelines_) {
831 if (ps.is_configured()) {
832 ps.speaker->set_mute_state(mute_state);
833 }
834 }
835
836 this->is_muted_ = mute_state;
837
838 if (publish) {
840 }
841
842 // Notify all media sources about the mute state change
843 for (auto &ps : this->pipelines_) {
844 for (auto &binding : ps.sources) {
845 binding->source->notify_mute_changed(mute_state);
846 }
847 }
848
849 if (mute_state) {
850 this->defer([this]() { this->mute_trigger_.trigger(); });
851 } else {
852 this->defer([this]() { this->unmute_trigger_.trigger(); });
853 }
854}
855
856void SpeakerSourceMediaPlayer::set_volume_(float volume, bool publish) {
857 // A volume change made while an announcement uses the announcement volume applies right away
859 this->apply_speaker_volume_(volume);
860
861 if (publish) {
862 this->volume = volume;
863 }
864
865 // Notify all media sources about the volume change
866 for (auto &ps : this->pipelines_) {
867 for (auto &binding : ps.sources) {
868 binding->source->notify_volume_changed(volume);
869 }
870 }
871
872 if (publish) {
874 }
875
876 this->defer([this, volume]() { this->volume_trigger_.trigger(volume); });
877}
878
880 // Remap the volume to fit within the configured limits. An effectively zero volume is passed through as zero so
881 // the speaker silences it, otherwise volume_min would make it audible.
882 float bounded_volume = (volume < speaker::SILENT_VOLUME_THRESHOLD)
883 ? 0.0f
884 : remap<float, float>(volume, 0.0f, 1.0f, this->volume_min_, this->volume_max_);
885
886 for (auto &ps : this->pipelines_) {
887 if (ps.is_configured()) {
888 ps.speaker->set_volume(bounded_volume);
889 }
890 }
891}
892
893// THREAD CONTEXT: Called from main loop via automation commands (direct)
895 this->announcement_volume_.set_volume(announcement_volume, this->speaker_volume_applier_());
896}
897
899 const PipelineContext &ps = this->pipelines_[pipeline];
900
901 if (ps.shuffle_indices.empty() || ps.playlist_index >= ps.shuffle_indices.size()) {
902 return ps.playlist_index;
903 }
904 return ps.shuffle_indices[ps.playlist_index];
905}
906
908 PipelineContext &ps = this->pipelines_[pipeline];
909
910 if (ps.playlist.size() <= 1) {
911 ps.shuffle_indices.clear();
912 return;
913 }
914
915 // Capture current actual position BEFORE modifying shuffle_indices
916 size_t current_actual = this->get_playlist_position_(pipeline);
917
918 // Build indices vector
919 ps.shuffle_indices.resize(ps.playlist.size());
920 for (size_t i = 0; i < ps.playlist.size(); i++) {
921 ps.shuffle_indices[i] = i;
922 }
923
924 // Fisher-Yates shuffle using ESPHome's random helper
925 for (size_t i = ps.shuffle_indices.size() - 1; i > 0; i--) {
926 size_t j = random_uint32() % (i + 1);
927 std::swap(ps.shuffle_indices[i], ps.shuffle_indices[j]);
928 }
929
930 // Move current track to current position (so playback continues seamlessly)
931 if (ps.playlist_index < ps.shuffle_indices.size()) {
932 for (size_t i = 0; i < ps.shuffle_indices.size(); i++) {
933 if (ps.shuffle_indices[i] == current_actual) {
934 std::swap(ps.shuffle_indices[i], ps.shuffle_indices[ps.playlist_index]);
935 break;
936 }
937 }
938 }
939}
940
942 PipelineContext &ps = this->pipelines_[pipeline];
943
944 if (!ps.shuffle_indices.empty() && ps.playlist_index < ps.shuffle_indices.size()) {
946 }
947 ps.shuffle_indices.clear();
948}
949
950} // namespace esphome::speaker_source
951
952#endif // USE_ESP32
bool cancel_timeout(const char *name)
Cancel a timeout function.
bool is_ready() const
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
void defer(const char *name, std::function< void()> &&f)
Defer a callback to the next loop() call with a const char* name.
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:557
uint32_t bytes_to_frames(size_t bytes) const
Convert bytes to frames.
Definition audio.h:43
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:932
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