ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
microphone_http_stream.cpp
Go to the documentation of this file.
2
3#ifdef USE_ESP32
4
7
8#include <cinttypes>
9#include <cstdio>
10#include <sys/socket.h>
11
12#ifdef USE_PSRAM
13#include <esp_heap_caps.h>
14#endif
15
17
18ESPHOME_LOG_TAG(TAG, "microphone_http_stream");
19
20static_assert(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__, "S16LE requires a little-endian target");
21
22static constexpr char LAST_CHUNK[] = "0\r\n\r\n";
23
24// Indexed by StopReason
25PROGMEM_STRING_TABLE(StopReasonStrings, "client_closed", "buffer_full", "peer_closed", "send_failed", "audio_timeout");
26
28 this->large_ring_ = this->clients_.size() > 1;
29#ifdef USE_PSRAM
30 // With PSRAM one client also gets the large ring, so it rides out Wi-Fi pauses of several seconds
31 this->large_ring_ |= heap_caps_get_total_size(MALLOC_CAP_SPIRAM) > 0;
32#endif
33 bool allocated = true;
34 for (auto &client : this->clients_) {
36 if (client.ring == nullptr && this->large_ring_ && this->clients_.size() == 1) {
37 // PSRAM already used by other components; the small ring still streams over Ethernet
38 ESP_LOGW(TAG, "Cannot allocate %u bytes in PSRAM, using %u", static_cast<unsigned>(MULTI_RING_SIZE),
39 static_cast<unsigned>(SINGLE_RING_SIZE));
40 this->large_ring_ = false;
42 }
43 if (client.ring == nullptr) {
44 allocated = false;
45 break;
46 }
47 }
48 if (allocated) {
50 [this](const microphone::AudioCapture &capture) { this->on_audio_(capture.data); });
51 this->disable_loop();
52 } else {
53 for (auto &client : this->clients_) {
54 client.ring.reset();
55 }
56 this->mark_failed(LOG_STR("Cannot allocate microphone audio buffers"));
57 }
58 // Registered even after a failure, so requests get a 503 that says why the stream is unavailable
59 this->base_->init();
60 this->base_->add_handler(this);
61}
62
64 ESP_LOGCONFIG(TAG,
65 "Microphone HTTP Stream:\n ID: %s\n Format: S16LE mono, %" PRIu32
66 " Hz\n Path: %s\n Maximum clients: %u\n Buffer per client: %u B",
67 this->stream_id_(), this->source_->get_audio_stream_info().get_sample_rate(), this->stream_path_,
68 static_cast<unsigned>(this->clients_.size()),
69 static_cast<unsigned>(this->large_ring_ ? MULTI_RING_SIZE : SINGLE_RING_SIZE));
70}
71
72bool MicrophoneHttpStream::canHandle(AsyncWebServerRequest *request) const {
73 if (request->method() != HTTP_GET)
74 return false;
75 char url_buf[AsyncWebServerRequest::URL_BUF_SIZE];
76 const StringRef url = request->url_to(url_buf);
77 return url == LIST_PATH || url == this->stream_path_;
78}
79
80void MicrophoneHttpStream::handleRequest(AsyncWebServerRequest *request) {
81 if (this->is_failed()) {
82 request->send(503, "text/plain; charset=utf-8", "Microphone stream unavailable");
83 return;
84 }
85 char url_buf[AsyncWebServerRequest::URL_BUF_SIZE];
86 if (request->url_to(url_buf) == LIST_PATH) {
87 char json[256];
88 snprintf(json, sizeof(json),
89 "[{\"stream_id\":\"%s\",\"format\":\"S16LE\",\"sample_rate_hz\":%" PRIu32
90 ",\"channels\":1,\"content_type\":\"application/octet-stream\",\"url\":\"%s\",\"max_clients\":%u}]",
91 this->stream_id_(), this->source_->get_audio_stream_info().get_sample_rate(), this->stream_path_,
92 static_cast<unsigned>(this->clients_.size()));
93 request->send(200, "application/json", json);
94 return;
95 }
96
97 ClientSlot *client = nullptr;
98 for (auto &slot : this->clients_) {
100 if (slot.state.compare_exchange_strong(expected, StreamState::STREAM_STATE_PREPARING)) {
101 client = &slot;
102 break;
103 }
104 }
105 if (client == nullptr) {
106 request->send(409, "text/plain; charset=utf-8", "No free microphone stream slot");
107 return;
108 }
110 // Drop audio left over from the previous client of this slot.
111 client->ring->reset();
112
113 char sample_rate[12];
114 snprintf(sample_rate, sizeof(sample_rate), "%" PRIu32, this->source_->get_audio_stream_info().get_sample_rate());
115 const HttpHeader headers[] = {
116 {"Transfer-Encoding", "chunked"}, {"X-Audio-Format", "S16LE"}, {"X-Audio-Sample-Rate", sample_rate},
117 {"X-Audio-Channels", "1"}, {"Cache-Control", "no-store"}, {"Connection", "close"},
118 };
119 // Deleted by the main loop once safe_to_delete(), like the SSE sessions.
120 auto *stream = new AsyncStreamResponse(); // NOLINT(cppcoreguidelines-owning-memory)
121 stream->begin(request, HTTPD_200, "application/octet-stream", headers);
122 client->stream = stream;
123 client->last_audio_ms = 0;
126 ESP_LOGI(TAG, "Client %u connected", this->client_index_(client));
127}
128
130 bool has_ready_client = false;
131 bool has_pending_client = false;
132 bool has_finishing_client = false;
133 for (auto &client : this->clients_) {
134 auto state = client.state.load();
136 this->service_client_(&client);
137 state = client.state.load(); // The client may have just finished
138 }
140 // seq_cst pairs with on_audio_(): a writer either is counted here or sees FINISHING and skips the slot.
141 if (client.writers.load() == 0) {
142 client.state.store(StreamState::STREAM_STATE_IDLE);
143 } else {
144 has_finishing_client = true;
145 }
146 }
147 has_ready_client |= state == StreamState::STREAM_STATE_READY;
148 has_pending_client |= state == StreamState::STREAM_STATE_PREPARING;
149 }
150
151 // Both are no-ops when the source is already in that state
152 if (has_ready_client) {
153 this->source_->start();
154 } else if (!has_pending_client) {
155 this->source_->stop();
156 }
157 // A claimed slot calls enable_loop_soon_any_context() once it is READY.
158 if (!has_ready_client && !has_pending_client && !has_finishing_client)
159 this->disable_loop();
160}
161
163 AsyncStreamResponse *stream = client->stream;
164 if (!stream->is_closing()) {
165 if (client->stop_reason.load() != StopReason::STOP_REASON_NONE) {
166 stream->close(); // The audio callback recorded the reason
167 } else if (!stream->is_connected()) {
169 stream->close();
170 } else if (stream->is_attached()) {
171 this->send_audio_(client);
172 }
173 }
174 stream->loop();
175 if (stream->is_closing() && stream->safe_to_delete())
176 this->finish_client_(client);
177}
178
180 AsyncStreamResponse *stream = client->stream;
182 // A stamp that happens to be 0 is only re-taken on the next pass
183 if (client->last_audio_ms == 0)
184 client->last_audio_ms = now;
185 while (true) {
186 if (client->chunk_data == nullptr) {
187 size_t amount = 0;
188 // Writes are whole frames and the ring size is even, so every chunk holds complete samples.
189 void *data = client->ring->receive_acquire(amount, SEND_CHUNK_SIZE);
190 if (data == nullptr) {
191 if (now - client->last_audio_ms >= AUDIO_WAIT_TIMEOUT_MS) {
193 stream->write(LAST_CHUNK, sizeof(LAST_CHUNK) - 1); // Best effort; the stream closes either way
194 stream->close();
195 }
196 return;
197 }
198 client->last_audio_ms = now;
199 client->chunk_data = data;
200 client->chunk_len = static_cast<uint16_t>(amount);
201 client->chunk_sent = 0;
203 }
204
205 struct iovec parts[3] = {
207 {client->chunk_data, client->chunk_len},
209 };
210 struct iovec *iov = parts;
211 int iovcnt = 3;
212 web_server_base::advance_iovecs(iov, iovcnt, client->chunk_sent);
213 const ssize_t sent = stream->write(iov, iovcnt);
214 if (sent < 0) {
215 client->set_stop_reason(StopReason::STOP_REASON_SEND_FAILED); // write() already closed the stream
216 return;
217 }
218 client->chunk_sent += static_cast<uint16_t>(sent);
220 return; // Socket full; continue from chunk_sent on the next pass
221 client->ring->receive_release(client->chunk_data);
222 client->chunk_data = nullptr;
223 }
224}
225
227 if (client->chunk_data != nullptr) {
228 client->ring->receive_release(client->chunk_data);
229 client->chunk_data = nullptr;
230 }
231 delete client->stream; // NOLINT(cppcoreguidelines-owning-memory)
232 client->stream = nullptr;
233 const StopReason stop_reason = client->stop_reason.load();
234 const LogString *reason =
235 StopReasonStrings::get_log_str(static_cast<uint8_t>(stop_reason), StopReasonStrings::LAST_INDEX);
236 const unsigned index = this->client_index_(client);
237 if (stop_reason == StopReason::STOP_REASON_NONE || stop_reason == StopReason::STOP_REASON_PEER_CLOSED) {
238 ESP_LOGI(TAG, "Client %u disconnected: reason=%s", index, LOG_STR_ARG(reason));
239 } else {
240 ESP_LOGW(TAG, "Client %u disconnected: reason=%s", index, LOG_STR_ARG(reason));
241 }
242 // loop() publishes IDLE once no audio callback is still writing to this slot
244}
245
246void MicrophoneHttpStream::on_audio_(std::span<const uint8_t> data) {
247 if (data.empty())
248 return;
249 for (auto &client : this->clients_) {
250 if (client.state.load() != StreamState::STREAM_STATE_READY)
251 continue;
252 client.writers.fetch_add(1);
253 // Re-check once counted, so a slot that is finishing or reused is never written (seq_cst, see loop())
254 if (client.state.load() == StreamState::STREAM_STATE_READY &&
255 client.stop_reason.load() == StopReason::STOP_REASON_NONE)
256 this->write_audio_(&client, data);
257 client.writers.fetch_sub(1, std::memory_order_release);
258 }
259}
260
261void MicrophoneHttpStream::write_audio_(ClientSlot *client, std::span<const uint8_t> data) {
262 // Whole frames only, so the sender always reads complete 2-byte samples.
263 if (client->ring->write_without_replacement(data.data(), data.size(), 0, false) == 0)
264 client->set_stop_reason(StopReason::STOP_REASON_BUFFER_FULL); // Disconnect only the client that cannot keep up.
265}
266
267} // namespace esphome::microphone_http_stream
268
269#endif // USE_ESP32
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:288
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
void disable_loop()
Disable this component's loop.
StringRef is a reference to a string owned by something else.
Definition string_ref.h:31
uint32_t get_sample_rate() const
Definition audio.h:29
void add_data_callback(F &&data_callback)
Same callbacks as Microphone::add_data_callback; stream_info is the processed format.
audio::AudioStreamInfo get_audio_stream_info()
Gets the AudioStreamInfo of the data after processing.
bool canHandle(AsyncWebServerRequest *request) const override
unsigned client_index_(const ClientSlot *client) const
void write_audio_(ClientSlot *client, std::span< const uint8_t > data)
void handleRequest(AsyncWebServerRequest *request) override
static std::unique_ptr< RingBuffer > create(size_t len, MemoryPreference preference=MemoryPreference::EXTERNAL_FIRST)
void add_handler(AsyncWebHandler *handler)
bool state
Definition fan.h:2
__int64 ssize_t
Definition httplib.h:178
PROGMEM_STRING_TABLE(StopReasonStrings, "client_closed", "buffer_full", "peer_closed", "send_failed", "audio_timeout")
ESPHOME_LOG_TAG(TAG, "microphone_http_stream")
constexpr size_t CHUNK_HDR_LEN
Definition chunk.h:13
constexpr char CHUNK_END[]
Definition chunk.h:15
void advance_iovecs(Iovec *&iov, int &count, size_t sent)
Drops the first sent bytes from a gather list after a write; a short write resumes inside the element...
Definition stream_head.h:51
void write_chunk_header(char *buf, size_t chunk_len)
Definition chunk.h:19
constexpr size_t CHUNK_END_LEN
Definition chunk.h:16
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
std::span< const uint8_t > data
Only valid during the callback.
Definition microphone.h:25
char chunk_header[web_server_base::CHUNK_HDR_LEN]
void set_stop_reason(StopReason reason)
Record the first reason the stream stops; later reasons are ignored.
std::unique_ptr< ring_buffer::RingBuffer > ring