10#include <sys/socket.h>
13#include <esp_heap_caps.h>
20static_assert(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__,
"S16LE requires a little-endian target");
22static constexpr char LAST_CHUNK[] =
"0\r\n\r\n";
25PROGMEM_STRING_TABLE(StopReasonStrings,
"client_closed",
"buffer_full",
"peer_closed",
"send_failed",
"audio_timeout");
31 this->
large_ring_ |= heap_caps_get_total_size(MALLOC_CAP_SPIRAM) > 0;
33 bool allocated =
true;
34 for (
auto &client : this->
clients_) {
36 if (client.ring ==
nullptr && this->large_ring_ && this->clients_.size() == 1) {
38 ESP_LOGW(TAG,
"Cannot allocate %u bytes in PSRAM, using %u",
static_cast<unsigned>(
MULTI_RING_SIZE),
43 if (client.ring ==
nullptr) {
53 for (
auto &client : this->clients_) {
56 this->
mark_failed(LOG_STR(
"Cannot allocate microphone audio buffers"));
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",
68 static_cast<unsigned>(this->clients_.size()),
73 if (request->method() != HTTP_GET)
75 char url_buf[AsyncWebServerRequest::URL_BUF_SIZE];
76 const StringRef url = request->url_to(url_buf);
82 request->send(503,
"text/plain; charset=utf-8",
"Microphone stream unavailable");
85 char url_buf[AsyncWebServerRequest::URL_BUF_SIZE];
86 if (request->url_to(url_buf) == LIST_PATH) {
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}]",
92 static_cast<unsigned>(this->clients_.size()));
93 request->send(200,
"application/json", json);
105 if (client ==
nullptr) {
106 request->send(409,
"text/plain; charset=utf-8",
"No free microphone stream slot");
111 client->
ring->reset();
113 char sample_rate[12];
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"},
120 auto *stream =
new AsyncStreamResponse();
121 stream->begin(request, HTTPD_200,
"application/octet-stream", headers);
126 ESP_LOGI(TAG,
"Client %u connected", this->
client_index_(client));
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();
137 state = client.state.load();
141 if (client.writers.load() == 0) {
144 has_finishing_client =
true;
152 if (has_ready_client) {
154 }
else if (!has_pending_client) {
158 if (!has_ready_client && !has_pending_client && !has_finishing_client)
163 AsyncStreamResponse *stream = client->
stream;
164 if (!stream->is_closing()) {
167 }
else if (!stream->is_connected()) {
170 }
else if (stream->is_attached()) {
175 if (stream->is_closing() && stream->safe_to_delete())
180 AsyncStreamResponse *stream = client->
stream;
190 if (data ==
nullptr) {
193 stream->write(LAST_CHUNK,
sizeof(LAST_CHUNK) - 1);
200 client->
chunk_len =
static_cast<uint16_t
>(amount);
205 struct iovec parts[3] = {
210 struct iovec *iov = parts;
213 const ssize_t sent = stream->write(iov, iovcnt);
218 client->
chunk_sent +=
static_cast<uint16_t
>(sent);
234 const LogString *reason =
235 StopReasonStrings::get_log_str(
static_cast<uint8_t
>(stop_reason), StopReasonStrings::LAST_INDEX);
238 ESP_LOGI(TAG,
"Client %u disconnected: reason=%s", index, LOG_STR_ARG(reason));
240 ESP_LOGW(TAG,
"Client %u disconnected: reason=%s", index, LOG_STR_ARG(reason));
249 for (
auto &client : this->
clients_) {
252 client.writers.fetch_add(1);
257 client.writers.fetch_sub(1, std::memory_order_release);
263 if (client->
ring->write_without_replacement(data.data(), data.size(), 0,
false) == 0)
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.
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.
uint32_t get_sample_rate() const
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.
void on_audio_(std::span< const uint8_t > data)
bool canHandle(AsyncWebServerRequest *request) const override
void send_audio_(ClientSlot *client)
microphone::MicrophoneSource * source_
void dump_config() override
std::span< ClientSlot > clients_
static constexpr size_t SEND_CHUNK_SIZE
void finish_client_(ClientSlot *client)
web_server_base::WebServerBase * base_
unsigned client_index_(const ClientSlot *client) const
const char * stream_id_() const
static constexpr size_t SINGLE_RING_SIZE
void service_client_(ClientSlot *client)
const char * stream_path_
void write_audio_(ClientSlot *client, std::span< const uint8_t > data)
static constexpr size_t MULTI_RING_SIZE
void handleRequest(AsyncWebServerRequest *request) override
static constexpr uint32_t AUDIO_WAIT_TIMEOUT_MS
static std::unique_ptr< RingBuffer > create(size_t len, MemoryPreference preference=MemoryPreference::EXTERNAL_FIRST)
void add_handler(AsyncWebHandler *handler)
PROGMEM_STRING_TABLE(StopReasonStrings, "client_closed", "buffer_full", "peer_closed", "send_failed", "audio_timeout")
ESPHOME_LOG_TAG(TAG, "microphone_http_stream")
@ STOP_REASON_AUDIO_TIMEOUT
@ STOP_REASON_BUFFER_FULL
@ STOP_REASON_SEND_FAILED
@ STOP_REASON_PEER_CLOSED
constexpr size_t CHUNK_HDR_LEN
constexpr char CHUNK_END[]
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...
void write_chunk_header(char *buf, size_t chunk_len)
constexpr size_t CHUNK_END_LEN
Application App
Global storage of Application pointer - only one Application can exist.
std::span< const uint8_t > data
Only valid during the callback.
std::atomic< StreamState > state
std::atomic< StopReason > stop_reason
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.
AsyncStreamResponse * stream
std::unique_ptr< ring_buffer::RingBuffer > ring