ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
audio_http_media_source.cpp
Go to the documentation of this file.
2
3#ifdef USE_ESP32
4
5#include "esphome/core/log.h"
6
7#include <freertos/FreeRTOS.h>
8#include <freertos/task.h>
9
10#include <algorithm>
11
13
14ESPHOME_LOG_TAG(TAG, "audio_http_media_source");
15
16// Decoder task / buffer tuning. Kept here as constants so the header stays free of magic numbers.
17static constexpr size_t DEFAULT_TRANSFER_BUFFER_SIZE = 8 * 1024; // Staging buffer between HTTP reader and decoder
18static constexpr uint32_t HTTP_TIMEOUT_MS = 5000; // HTTP connect/read timeout
19static constexpr uint32_t AUDIO_WRITE_TIMEOUT_MS = 50; // Max blocking time per on_audio_write() call
20static constexpr uint32_t READER_WRITE_TIMEOUT_MS = 50; // Max blocking time when writing into the ring buffer
21static constexpr uint8_t READER_TASK_PRIORITY = 2;
22static constexpr uint8_t DECODER_TASK_PRIORITY = 2;
23#ifdef CONFIG_MBEDTLS_SSL_PROTO_TLS1_3
24// A TLS 1.3 handshake peaks at about 4.3 KB of reader stack
25static constexpr size_t READER_TASK_STACK_SIZE = 6144;
26#else
27static constexpr size_t READER_TASK_STACK_SIZE = 4096;
28#endif
29static constexpr size_t DECODER_TASK_STACK_SIZE = 5120;
30static constexpr uint32_t PAUSE_POLL_DELAY_MS = 20;
31static constexpr const char *const HTTP_URI_PREFIX = "http://";
32static constexpr const char *const HTTPS_URI_PREFIX = "https://";
33
35 ESP_LOGCONFIG(TAG,
36 "Audio HTTP Media Source:\n"
37 " Buffer Size: %zu bytes\n"
38 " Persistent Ring Buffer: %s\n"
39 " Decoder Task Stack in PSRAM: %s",
40 this->buffer_size_, YESNO(this->persistent_ring_buffer_), YESNO(this->decoder_task_stack_in_psram_));
41#ifdef USE_AUDIO_HTTP_CA_CERTIFICATE
42 ESP_LOGCONFIG(TAG, " Custom CA Certificate: %s", YESNO(this->http_ca_certificate_ != nullptr));
43#endif
44}
45
47 this->disable_loop();
48
49 micro_decoder::DecoderConfig config;
50 config.ring_buffer_size = this->buffer_size_;
51 config.persistent_ring_buffer = this->persistent_ring_buffer_;
52 // Keep the transfer buffer smaller than the ring buffer so the reader can top up the ring
53 // while the decoder is still draining it, instead of oscillating between empty and full.
54 config.transfer_buffer_size = std::min(DEFAULT_TRANSFER_BUFFER_SIZE, this->buffer_size_ / 2);
55 config.http_timeout_ms = HTTP_TIMEOUT_MS;
56 config.audio_write_timeout_ms = AUDIO_WRITE_TIMEOUT_MS;
57 config.reader_write_timeout_ms = READER_WRITE_TIMEOUT_MS;
58 config.reader_priority = READER_TASK_PRIORITY;
59 config.decoder_priority = DECODER_TASK_PRIORITY;
60 config.reader_stack_size = READER_TASK_STACK_SIZE;
61 config.decoder_stack_size = DECODER_TASK_STACK_SIZE;
62 config.decoder_stack_in_psram = this->decoder_task_stack_in_psram_;
63#ifdef USE_AUDIO_HTTP_CA_CERTIFICATE
64 // micro-decoder verifies HTTPS against this PEM only, skipping the built-in certificate bundle.
65 if (this->http_ca_certificate_ != nullptr) {
66 config.http_ca_certificate = this->http_ca_certificate_;
67 }
68#endif
69
70 this->decoder_ = std::make_unique<micro_decoder::DecoderSource>(config);
71 if (this->decoder_ == nullptr) {
72 ESP_LOGE(TAG, "Failed to allocate decoder");
73 this->mark_failed();
74 return;
75 }
76 this->decoder_->set_listener(this); // We inherit from micro_decoder::DecoderListener
77}
78
79void AudioHTTPMediaSource::loop() { this->decoder_->loop(); }
80
81bool AudioHTTPMediaSource::can_handle(const std::string &uri) const {
82 return uri.starts_with(HTTP_URI_PREFIX) || uri.starts_with(HTTPS_URI_PREFIX);
83}
84
85// Called from the orchestrator's main loop, so no synchronization needed with loop()
86bool AudioHTTPMediaSource::play_uri(const std::string &uri) {
87 if (!this->is_ready() || this->is_failed() || this->status_has_error() || !this->has_listener()) {
88 return false;
89 }
90
91 // Check if source is already playing
93 ESP_LOGE(TAG, "Cannot play '%s': source is busy", uri.c_str());
94 return false;
95 }
96
97 // Validate URI starts with "http://" or "https://"
98 if (!uri.starts_with(HTTP_URI_PREFIX) && !uri.starts_with(HTTPS_URI_PREFIX)) {
99 ESP_LOGE(TAG, "Invalid URI: '%s'", uri.c_str());
100 return false;
101 }
102
103 if (this->decoder_->play_url(uri)) {
104 this->pause_.store(false, std::memory_order_relaxed);
105 this->enable_loop();
106 return true;
107 }
108
109 ESP_LOGE(TAG, "Failed to start playback of '%s'", uri.c_str());
110 return false;
111}
112
113// Called from the orchestrator's main loop, so no synchronization needed with loop()
115 switch (command) {
117 this->decoder_->stop();
118 break;
120 // Only valid while actively playing; ignoring from IDLE/ERROR/PAUSED prevents the state
121 // machine from getting stuck in PAUSED when no playback is active (which would block the
122 // next play_uri() call via its IDLE-state precondition).
124 break;
125 // PAUSE does not stop the decoder task. Instead, on_audio_write() returns 0 and temporarily
126 // yields, which fills the ring buffer and applies back pressure that effectively pauses both
127 // the decoder and HTTP reader tasks.
129 this->pause_.store(true, std::memory_order_relaxed);
130 break;
132 // Only resume from PAUSED; don't fabricate a PLAYING state from IDLE/ERROR.
134 break;
136 this->pause_.store(false, std::memory_order_relaxed);
137 break;
138 default:
139 break;
140 }
141}
142
143// Called from the decoder task. Forwards to the orchestrator's listener, which is responsible for
144// being thread-safe with respect to its own audio writer.
145size_t AudioHTTPMediaSource::on_audio_write(const uint8_t *data, size_t length, uint32_t timeout_ms) {
146 if (this->pause_.load(std::memory_order_relaxed)) {
147 vTaskDelay(pdMS_TO_TICKS(PAUSE_POLL_DELAY_MS));
148 return 0;
149 }
150 return this->write_output(data, length, timeout_ms, this->stream_info_);
151}
152
153// Called from the decoder task before the first on_audio_write().
154void AudioHTTPMediaSource::on_stream_info(const micro_decoder::AudioStreamInfo &info) {
155 this->stream_info_ = audio::AudioStreamInfo(info.get_bits_per_sample(), info.get_channels(), info.get_sample_rate());
156}
157
158// microDecoder invokes on_state_change() from inside decoder_->loop(), so this runs on the main
159// loop thread and it's safe to call set_state_() directly.
160void AudioHTTPMediaSource::on_state_change(micro_decoder::DecoderState state) {
161 switch (state) {
162 case micro_decoder::DecoderState::IDLE:
164 this->disable_loop();
165 break;
166 case micro_decoder::DecoderState::PLAYING:
168 break;
169 case micro_decoder::DecoderState::FAILED:
171 break;
172 default:
173 break;
174 }
175}
176
177} // namespace esphome::audio_http
178
179#endif // USE_ESP32
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:287
bool is_ready() const
void enable_loop()
Enable this component's loop.
Definition component.h:261
bool status_has_error() const
Definition component.h:295
void disable_loop()
Disable this component's loop.
size_t on_audio_write(const uint8_t *data, size_t length, uint32_t timeout_ms) override
bool can_handle(const std::string &uri) const override
bool play_uri(const std::string &uri) override
std::unique_ptr< micro_decoder::DecoderSource > decoder_
void handle_command(media_source::MediaSourceCommand command) override
void on_state_change(micro_decoder::DecoderState state) override
void on_stream_info(const micro_decoder::AudioStreamInfo &info) override
void set_state_(MediaSourceState state)
Update state and notify listener This is the only way to change state_, ensuring listener notificatio...
MediaSourceState get_state() const
Get current playback state.
size_t write_output(const uint8_t *data, size_t length, uint32_t timeout_ms, const audio::AudioStreamInfo &stream_info)
Write audio data to the listener.
bool has_listener() const
Check if a listener has been registered.
bool state
Definition fan.h:2
ESPHOME_LOG_TAG(TAG, "audio_http_media_source")
MediaSourceCommand
Commands that are sent from the orchestrator to a media source.
static void uint32_t
uint16_t length
Definition tt21100.cpp:0