ESPHome 2026.12.0-dev
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#if defined(USE_WIFI) && defined(USE_WIFI_RUNTIME_ROAMING_SUPPRESSION)
9#endif
10
11#include <freertos/FreeRTOS.h>
12#include <freertos/task.h>
13
14#include <algorithm>
15
17
18ESPHOME_LOG_TAG(TAG, "audio_http_media_source");
19
20// Decoder task / buffer tuning. Kept here as constants so the header stays free of magic numbers.
21static constexpr size_t DEFAULT_TRANSFER_BUFFER_SIZE = 8 * 1024; // Staging buffer between HTTP reader and decoder
22static constexpr uint32_t HTTP_TIMEOUT_MS = 5000; // HTTP connect/read timeout
23static constexpr uint32_t AUDIO_WRITE_TIMEOUT_MS = 50; // Max blocking time per on_audio_write() call
24static constexpr uint32_t READER_WRITE_TIMEOUT_MS = 50; // Max blocking time when writing into the ring buffer
25static constexpr uint8_t READER_TASK_PRIORITY = 2;
26static constexpr uint8_t DECODER_TASK_PRIORITY = 2;
27// A TLS handshake overflows 4 KB of reader stack: TLS 1.3 peaks at about 4.3 KB, and so does an ECDSA TLS 1.2 one on
28// ESP-IDF 6.1
29static constexpr size_t READER_TASK_STACK_SIZE = 6144;
30static constexpr size_t DECODER_TASK_STACK_SIZE = 5120;
31static constexpr uint32_t PAUSE_POLL_DELAY_MS = 20;
32static constexpr const char *const HTTP_URI_PREFIX = "http://";
33static constexpr const char *const HTTPS_URI_PREFIX = "https://";
34
36 ESP_LOGCONFIG(TAG,
37 "Audio HTTP Media Source:\n"
38 " Buffer Size: %zu bytes\n"
39 " Persistent Ring Buffer: %s\n"
40 " Decoder Task Stack in PSRAM: %s",
41 this->buffer_size_, YESNO(this->persistent_ring_buffer_), YESNO(this->decoder_task_stack_in_psram_));
42#ifdef USE_AUDIO_HTTP_CA_CERTIFICATE
43 ESP_LOGCONFIG(TAG, " Custom CA Certificate: %s", YESNO(this->http_ca_certificate_ != nullptr));
44#endif
45}
46
48 this->disable_loop();
49
50 micro_decoder::DecoderConfig config;
51 config.ring_buffer_size = this->buffer_size_;
52 config.persistent_ring_buffer = this->persistent_ring_buffer_;
53 // Keep the transfer buffer smaller than the ring buffer so the reader can top up the ring
54 // while the decoder is still draining it, instead of oscillating between empty and full.
55 config.transfer_buffer_size = std::min(DEFAULT_TRANSFER_BUFFER_SIZE, this->buffer_size_ / 2);
56 config.http_timeout_ms = HTTP_TIMEOUT_MS;
57 config.audio_write_timeout_ms = AUDIO_WRITE_TIMEOUT_MS;
58 config.reader_write_timeout_ms = READER_WRITE_TIMEOUT_MS;
59 config.reader_priority = READER_TASK_PRIORITY;
60 config.decoder_priority = DECODER_TASK_PRIORITY;
61 config.reader_stack_size = READER_TASK_STACK_SIZE;
62 config.decoder_stack_size = DECODER_TASK_STACK_SIZE;
63 config.decoder_stack_in_psram = this->decoder_task_stack_in_psram_;
64#ifdef USE_AUDIO_HTTP_CA_CERTIFICATE
65 // micro-decoder verifies HTTPS against this PEM only, skipping the built-in certificate bundle.
66 if (this->http_ca_certificate_ != nullptr) {
67 config.http_ca_certificate = this->http_ca_certificate_;
68 }
69#endif
70
71 this->decoder_ = std::make_unique<micro_decoder::DecoderSource>(config);
72 if (this->decoder_ == nullptr) {
73 ESP_LOGE(TAG, "Failed to allocate decoder");
74 this->mark_failed();
75 return;
76 }
77 this->decoder_->set_listener(this); // We inherit from micro_decoder::DecoderListener
78}
79
80void AudioHTTPMediaSource::loop() { this->decoder_->loop(); }
81
82bool AudioHTTPMediaSource::can_handle(const std::string &uri) const {
83 return uri.starts_with(HTTP_URI_PREFIX) || uri.starts_with(HTTPS_URI_PREFIX);
84}
85
86// Called from the orchestrator's main loop, so no synchronization needed with loop()
87bool AudioHTTPMediaSource::play_uri(const std::string &uri) {
88 if (!this->is_ready() || this->is_failed() || this->status_has_error() || !this->has_listener()) {
89 return false;
90 }
91
92 // Check if source is already playing
94 ESP_LOGE(TAG, "Cannot play '%s': source is busy", uri.c_str());
95 return false;
96 }
97
98 // Validate URI starts with "http://" or "https://"
99 if (!uri.starts_with(HTTP_URI_PREFIX) && !uri.starts_with(HTTPS_URI_PREFIX)) {
100 ESP_LOGE(TAG, "Invalid URI: '%s'", uri.c_str());
101 return false;
102 }
103
104 if (this->decoder_->play_url(uri)) {
105 this->pause_.store(false, std::memory_order_relaxed);
106 this->enable_loop();
107 return true;
108 }
109
110 ESP_LOGE(TAG, "Failed to start playback of '%s'", uri.c_str());
111 return false;
112}
113
114// Called from the orchestrator's main loop, so no synchronization needed with loop()
116 switch (command) {
118 this->decoder_->stop();
119 break;
121 // Only valid while actively playing; ignoring from IDLE/ERROR/PAUSED prevents the state
122 // machine from getting stuck in PAUSED when no playback is active (which would block the
123 // next play_uri() call via its IDLE-state precondition).
125 break;
126 // PAUSE does not stop the decoder task. Instead, on_audio_write() returns 0 and temporarily
127 // yields, which fills the ring buffer and applies back pressure that effectively pauses both
128 // the decoder and HTTP reader tasks.
130 this->pause_.store(true, std::memory_order_relaxed);
131 break;
133 // Only resume from PAUSED; don't fabricate a PLAYING state from IDLE/ERROR.
135 break;
137 this->pause_.store(false, std::memory_order_relaxed);
138 break;
139 default:
140 break;
141 }
142}
143
144// Called from the decoder task. Forwards to the orchestrator's listener, which is responsible for
145// being thread-safe with respect to its own audio writer.
146size_t AudioHTTPMediaSource::on_audio_write(const uint8_t *data, size_t length, uint32_t timeout_ms) {
147 if (this->pause_.load(std::memory_order_relaxed)) {
148 vTaskDelay(pdMS_TO_TICKS(PAUSE_POLL_DELAY_MS));
149 return 0;
150 }
151 return this->write_output(data, length, timeout_ms, this->stream_info_);
152}
153
154// Called from the decoder task before the first on_audio_write().
155void AudioHTTPMediaSource::on_stream_info(const micro_decoder::AudioStreamInfo &info) {
156 this->stream_info_ = audio::AudioStreamInfo(info.get_bits_per_sample(), info.get_channels(), info.get_sample_rate());
157}
158
159// microDecoder invokes on_state_change() from inside decoder_->loop(), so this runs on the main
160// loop thread and it's safe to call update_state_() directly.
161void AudioHTTPMediaSource::on_state_change(micro_decoder::DecoderState state) {
162 switch (state) {
163 case micro_decoder::DecoderState::IDLE:
164 // Retire completed workers before an IDLE listener can start another playback.
165 this->decoder_->stop();
166 this->disable_loop();
168 break;
169 case micro_decoder::DecoderState::PLAYING:
171 break;
172 case micro_decoder::DecoderState::FAILED:
174 break;
175 default:
176 break;
177 }
178}
179
181#if defined(USE_WIFI) && defined(USE_WIFI_RUNTIME_ROAMING_SUPPRESSION)
182 auto streaming = [](media_source::MediaSourceState s) {
184 };
185 const bool now_streaming = streaming(state);
186 if (now_streaming != streaming(this->get_state()) && wifi::global_wifi_component != nullptr) {
188 }
189#endif
190 this->set_state_(state);
191}
192
193} // namespace esphome::audio_http
194
195#endif // USE_ESP32
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:288
bool is_ready() const
void enable_loop()
Enable this component's loop.
Definition component.h:262
bool status_has_error() const
Definition component.h:296
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 update_state_(media_source::MediaSourceState state)
Sets the state and keeps Wi-Fi roaming scans suppressed while the stream is open (PLAYING or PAUSED).
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.
void set_roaming_suppressed(bool suppressed)
Add or release one request to suppress post-connect roaming scans.
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.
WiFiComponent * global_wifi_component
static void uint32_t
uint16_t length
Definition tt21100.cpp:0