ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
audio_reader.cpp
Go to the documentation of this file.
1#include "audio_reader.h"
2
3#ifdef USE_ESP32
4
5#include <algorithm>
6
8#include "esphome/core/hal.h"
10#include "esphome/core/log.h"
11
12#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
13#include "esp_crt_bundle.h"
14#endif
15
16namespace esphome::audio {
17
18static const uint32_t READ_WRITE_TIMEOUT_MS = 20;
19
20static const uint32_t CONNECTION_TIMEOUT_MS = 5000;
21static const uint8_t MAX_FETCHING_HEADER_ATTEMPTS = 6;
22
23static const size_t HTTP_STREAM_BUFFER_SIZE = 2048;
24// esp_http_client_read() blocks until it fills the request; small requests deliver a phrase tail before a pause ends
25static constexpr size_t HTTP_READ_MAX_BYTES = 1024;
26static constexpr int HTTP_BODY_TIMEOUT_MS = 100;
27
28static const uint8_t MAX_REDIRECTIONS = 5;
29
30ESPHOME_LOG_TAG(TAG, "audio_reader");
31
32// Some common HTTP status codes - borrowed from http_request component accessed 20241224
59
61
62esp_err_t AudioReader::add_sink(const std::weak_ptr<ring_buffer::RingBuffer> &output_ring_buffer) {
63 if (current_audio_file_ != nullptr) {
64 // A transfer buffer isn't ncessary for a local file
65 this->file_ring_buffer_ = output_ring_buffer.lock();
66 if (this->file_ring_buffer_ == nullptr) {
67 return ESP_ERR_INVALID_STATE;
68 }
69 return ESP_OK;
70 }
71
72 if (this->output_transfer_buffer_ != nullptr) {
73 this->output_transfer_buffer_->set_sink(output_ring_buffer);
74 return ESP_OK;
75 }
76
77 return ESP_ERR_INVALID_STATE;
78}
79
80esp_err_t AudioReader::start(const AudioFile *audio_file, AudioFileType &file_type) {
81 file_type = AudioFileType::NONE;
82
83 this->current_audio_file_ = audio_file;
84
85 this->file_current_ = audio_file->data;
86 file_type = audio_file->file_type;
87
88 return ESP_OK;
89}
90
91esp_err_t AudioReader::start(const std::string &uri, AudioFileType &file_type) {
92 file_type = AudioFileType::NONE;
93
94 this->cleanup_connection_();
95
96 if (uri.empty()) {
97 return ESP_ERR_INVALID_ARG;
98 }
99
100 esp_http_client_config_t client_config = {};
101
102 client_config.url = uri.c_str();
103 client_config.cert_pem = nullptr;
104 client_config.disable_auto_redirect = false;
105 client_config.max_redirection_count = MAX_REDIRECTIONS;
106 client_config.event_handler = http_event_handler;
107 client_config.user_data = this;
108 client_config.buffer_size = HTTP_STREAM_BUFFER_SIZE;
109 client_config.keep_alive_enable = true;
110 client_config.timeout_ms = CONNECTION_TIMEOUT_MS; // Shouldn't trigger watchdog resets if caller runs in a task
111
112#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
113 if (uri.find("https:") != std::string::npos) {
114 client_config.crt_bundle_attach = esp_crt_bundle_attach;
115 }
116#endif
117
118 this->client_ = esp_http_client_init(&client_config);
119
120 if (this->client_ == nullptr) {
121 return ESP_FAIL;
122 }
123
124 esp_err_t err = esp_http_client_open(this->client_, 0);
125
126 if (err != ESP_OK) {
127 ESP_LOGE(TAG, "Failed to open URL");
128 this->cleanup_connection_();
129 return err;
130 }
131
132 int64_t header_length = esp_http_client_fetch_headers(this->client_);
133 uint8_t reattempt_count = 0;
134 while ((header_length < 0) && (reattempt_count < MAX_FETCHING_HEADER_ATTEMPTS)) {
135 this->cleanup_connection_();
136 if (header_length != -ESP_ERR_HTTP_EAGAIN) {
137 // Serious error, no recovery
138 return ESP_FAIL;
139 } else {
140 // Reconnect from a fresh state to avoid a bug where it never reads the headers even if made available
141 this->client_ = esp_http_client_init(&client_config);
142 esp_http_client_open(this->client_, 0);
143 header_length = esp_http_client_fetch_headers(this->client_);
144 ++reattempt_count;
145 }
146 }
147
148 if (header_length < 0) {
149 ESP_LOGE(TAG, "Failed to fetch headers");
150 this->cleanup_connection_();
151 return ESP_FAIL;
152 }
153
154 int status_code = esp_http_client_get_status_code(this->client_);
155
156 if ((status_code < HTTP_STATUS_OK) || (status_code > HTTP_STATUS_PERMANENT_REDIRECT)) {
157 this->cleanup_connection_();
158 return ESP_FAIL;
159 }
160
161 ssize_t redirect_count = 0;
162
163 while ((esp_http_client_set_redirection(this->client_) == ESP_OK) && (redirect_count < MAX_REDIRECTIONS)) {
164 err = esp_http_client_open(this->client_, 0);
165 if (err != ESP_OK) {
166 this->cleanup_connection_();
167 return ESP_FAIL;
168 }
169
170 header_length = esp_http_client_fetch_headers(this->client_);
171 if (header_length < 0) {
172 this->cleanup_connection_();
173 return ESP_FAIL;
174 }
175
176 status_code = esp_http_client_get_status_code(this->client_);
177
178 if ((status_code < HTTP_STATUS_OK) || (status_code > HTTP_STATUS_PERMANENT_REDIRECT)) {
179 this->cleanup_connection_();
180 return ESP_FAIL;
181 }
182
183 ++redirect_count;
184 }
185
187 // Failed to determine the file type from the header, fallback to using the url
188 char url[500];
189 err = esp_http_client_get_url(this->client_, url, 500);
190 if (err != ESP_OK) {
191 this->cleanup_connection_();
192 return err;
193 }
194
195 file_type = detect_audio_file_type(nullptr, url);
196 if (file_type == AudioFileType::NONE) {
197 this->cleanup_connection_();
198 return ESP_ERR_NOT_SUPPORTED;
199 }
200 } else {
201 file_type = this->audio_file_type_;
202 }
203
204 // Keep the longer timeout for connection, headers, and redirects.
205 err = esp_http_client_set_timeout_ms(this->client_, HTTP_BODY_TIMEOUT_MS);
206 if (err != ESP_OK) {
207 this->cleanup_connection_();
208 return err;
209 }
210
211 this->last_data_read_ms_ = millis();
212
214 if (this->output_transfer_buffer_ == nullptr) {
215 this->cleanup_connection_();
216 return ESP_ERR_NO_MEM;
217 }
218
219 return ESP_OK;
220}
221
223 if (this->client_ != nullptr) {
224 return this->http_read_();
225 } else if (this->current_audio_file_ != nullptr) {
226 return this->file_read_();
227 }
228
230}
231
232esp_err_t AudioReader::http_event_handler(esp_http_client_event_t *evt) {
233 // Based on https://github.com/maroc81/WeatherLily/tree/main/main/net accessed 20241224
234 AudioReader *this_reader = (AudioReader *) evt->user_data;
235
236 switch (evt->event_id) {
237 case HTTP_EVENT_ON_HEADER:
238 if (strcasecmp(evt->header_key, "Content-Type") == 0) {
239 this_reader->audio_file_type_ = detect_audio_file_type(evt->header_value, nullptr);
240 }
241 break;
242 default:
243 break;
244 }
245 return ESP_OK;
246}
247
249 size_t remaining_bytes = this->current_audio_file_->length - (this->file_current_ - this->current_audio_file_->data);
250 if (remaining_bytes > 0) {
251 size_t bytes_written = this->file_ring_buffer_->write_without_replacement(this->file_current_, remaining_bytes,
252 pdMS_TO_TICKS(READ_WRITE_TIMEOUT_MS));
253 this->file_current_ += bytes_written;
254
256 }
257
259}
260
262 this->output_transfer_buffer_->transfer_data_to_sink(pdMS_TO_TICKS(READ_WRITE_TIMEOUT_MS), false);
263
264 if (esp_http_client_is_complete_data_received(this->client_)) {
265 if (this->output_transfer_buffer_->available() == 0) {
266 this->cleanup_connection_();
268 }
269 } else if (this->output_transfer_buffer_->free() > 0) {
270 size_t read_size = std::min(this->output_transfer_buffer_->free(), HTTP_READ_MAX_BYTES);
271 int received_len =
272 esp_http_client_read(this->client_, (char *) this->output_transfer_buffer_->get_buffer_end(), read_size);
273
274 if (received_len > 0) {
275 this->output_transfer_buffer_->increase_buffer_length(received_len);
276 this->last_data_read_ms_ = millis();
278 } else if (received_len <= 0) {
279 // HTTP read error
280 if (received_len == -1) {
281 // A true connection error occured, no chance at recovery
282 this->cleanup_connection_();
284 }
285
286 // Read timed out, manually verify if it has been too long since the last successful read
287 if ((millis() - this->last_data_read_ms_) > MAX_FETCHING_HEADER_ATTEMPTS * CONNECTION_TIMEOUT_MS) {
288 ESP_LOGE(TAG, "Timed out");
289 this->cleanup_connection_();
291 }
292
293 delay(READ_WRITE_TIMEOUT_MS);
294 }
295 } else {
296 // A full buffer means the consumer is behind, not that the server went quiet
297 this->last_data_read_ms_ = millis();
298 }
299
301}
302
304 if (this->client_ != nullptr) {
305 esp_http_client_close(this->client_);
306 esp_http_client_cleanup(this->client_);
307 this->client_ = nullptr;
308 }
309}
310
311} // namespace esphome::audio
312
313#endif
AudioReaderState http_read_()
AudioReaderState file_read_()
std::unique_ptr< AudioSinkTransferBuffer > output_transfer_buffer_
const uint8_t * file_current_
esp_err_t add_sink(const std::weak_ptr< ring_buffer::RingBuffer > &output_ring_buffer)
Adds a sink ring buffer for audio data.
AudioReaderState read()
Reads new file data from the source and sends to the ring buffer sink.
static esp_err_t http_event_handler(esp_http_client_event_t *evt)
Monitors the http client events to attempt determining the file type from the Content-Type header.
std::shared_ptr< ring_buffer::RingBuffer > file_ring_buffer_
esp_http_client_handle_t client_
esp_err_t start(const std::string &uri, AudioFileType &file_type)
Starts reading an audio file from an http source.
const AudioFile * current_audio_file_
static std::unique_ptr< AudioSinkTransferBuffer > create(size_t buffer_size)
Creates a new sink transfer buffer.
__int64 ssize_t
Definition httplib.h:178
ESPHOME_LOG_TAG(TAG, "audio.decoder")
AudioFileType detect_audio_file_type(const char *content_type, const char *url)
Detect audio file type from a Content-Type header value and/or URL extension.
Definition audio.cpp:67
void HOT delay(uint32_t ms)
Definition hal.cpp:85
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
static void uint32_t
const uint8_t * data
Definition audio.h:127
AudioFileType file_type
Definition audio.h:129