@geastack/host 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/audio_runtime.cpp +97 -3
  2. package/host/audio.cpp +395 -10
  3. package/host/audio_worklet.cpp +611 -0
  4. package/host/fetch.cpp +17 -0
  5. package/host/media.cpp +308 -27
  6. package/host/mjpeg.cpp +199 -0
  7. package/host/rtc.cpp +458 -48
  8. package/host/rtc_esp.cpp +897 -75
  9. package/host/rtc_objects.inc +246 -0
  10. package/host/timers.cpp +18 -0
  11. package/host/video.cpp +152 -0
  12. package/host/websocket.cpp +623 -72
  13. package/host/worker.cpp +621 -0
  14. package/include/gea/audio-worklet-runtime.h +165 -0
  15. package/include/gea/base64-runtime.h +26 -0
  16. package/include/gea/embedded-host.h +1 -0
  17. package/include/gea/worker-runtime.h +184 -0
  18. package/include/host/audio.h +94 -6
  19. package/include/host/audio_level.h +37 -0
  20. package/include/host/audio_worklet.h +103 -0
  21. package/include/host/display.h +1 -1
  22. package/include/host/h264_layout.h +170 -0
  23. package/include/host/media.h +67 -0
  24. package/include/host/mjpeg.h +22 -0
  25. package/include/host/mjpeg_parser.h +84 -0
  26. package/include/host/pcm_stream.h +122 -0
  27. package/include/host/rtc.h +38 -20
  28. package/include/host/rtc_h264.h +76 -0
  29. package/include/host/rtc_ice_candidate.h +141 -0
  30. package/include/host/rtc_opus.h +136 -0
  31. package/include/host/rtc_receive_sdp.h +245 -0
  32. package/include/host/rtc_rtp.h +170 -0
  33. package/include/host/rtc_sdp.h +71 -0
  34. package/include/host/rtc_types.h +166 -0
  35. package/include/host/rtc_vp8.h +115 -0
  36. package/include/host/rtc_vp8_capture.h +129 -0
  37. package/include/host/rtc_vp8_decoder.h +169 -0
  38. package/include/host/rtc_vp8_receiver.h +55 -0
  39. package/include/host/timers.h +3 -2
  40. package/include/host/video.h +39 -0
  41. package/include/host/video_color.h +90 -0
  42. package/include/host/video_frame_pool.h +50 -0
  43. package/include/host/video_pixels.h +178 -0
  44. package/include/host/websocket.h +20 -1
  45. package/include/host/websocket_message.h +66 -0
  46. package/include/host/worker.h +131 -0
  47. package/package.json +1 -1
  48. package/services/diagnostics.cpp +120 -19
@@ -1,8 +1,14 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  #include "host/websocket.h"
3
+ #include "host/worker.h"
4
+ #include "host/websocket_message.h"
3
5
 
6
+ #include <algorithm>
4
7
  #include <atomic>
8
+ #include <chrono>
9
+ #include <stdexcept>
5
10
  #include <functional>
11
+ #include <deque>
6
12
  #include <mutex>
7
13
  #include <unordered_map>
8
14
  #include <utility>
@@ -15,6 +21,8 @@ namespace {
15
21
  struct WebSocketInstance {
16
22
  std::string url;
17
23
  int readyState = WebSocket::CONNECTING;
24
+ websocket::TextMessageAssembler messages;
25
+ websocket::TextConsumer consumer;
18
26
  };
19
27
 
20
28
  std::unordered_map<NativeWebSocketHandle, WebSocketInstance> &instances() {
@@ -41,19 +49,26 @@ struct PendingEvent {
41
49
  int code = 0;
42
50
  };
43
51
 
44
- std::mutex &queueMutex() {
45
- static std::mutex m;
46
- return m;
47
- }
48
-
49
- std::vector<PendingEvent> &eventQueue() {
50
- static std::vector<PendingEvent> q;
51
- return q;
52
- }
52
+ std::mutex ownerMutex;
53
+ std::unordered_map<NativeWebSocketHandle, std::weak_ptr<workers::Context>> owners;
54
+ void dispatch(PendingEvent ev);
53
55
 
54
56
  void enqueue(PendingEvent ev) {
55
- std::lock_guard<std::mutex> lock(queueMutex());
56
- eventQueue().push_back(std::move(ev));
57
+ std::shared_ptr<workers::Context> owner;
58
+ {
59
+ std::lock_guard lock(ownerMutex);
60
+ auto it = owners.find(ev.handle);
61
+ if (it == owners.end()) return;
62
+ owner = it->second.lock();
63
+ }
64
+ if (!owner || owner->stopped()) return;
65
+ const auto bytes = ev.text.size();
66
+ const auto handle = ev.handle;
67
+ if (!owner->post([ev = std::move(ev)]() mutable { dispatch(std::move(ev)); }, bytes)) {
68
+ owner->post([handle] {
69
+ dispatch(PendingEvent{handle, EventKind::Error, "WebSocket receive queue exceeded bounded capacity", 0});
70
+ });
71
+ }
57
72
  }
58
73
 
59
74
  } // namespace
@@ -61,63 +76,81 @@ void enqueue(PendingEvent ev) {
61
76
  namespace websocket {
62
77
 
63
78
  std::unordered_map<NativeWebSocketHandle, CallbackTable> &callbackTable() {
64
- static std::unordered_map<NativeWebSocketHandle, CallbackTable> table;
65
- return table;
79
+ using Table = std::unordered_map<NativeWebSocketHandle, CallbackTable>;
80
+ static std::mutex mutex;
81
+ static Table mainTable;
82
+ static std::unordered_map<workers::Context *, std::weak_ptr<Table>> tables;
83
+ const auto context = workers::Context::current();
84
+ if (context->isMain()) return mainTable;
85
+ std::lock_guard lock(mutex);
86
+ auto table = tables[context.get()].lock();
87
+ if (!table) {
88
+ table = std::make_shared<Table>();
89
+ tables[context.get()] = table;
90
+ context->addCleanup([table, key = context.get()] {
91
+ table->clear();
92
+ std::lock_guard lock(mutex);
93
+ tables.erase(key);
94
+ });
95
+ }
96
+ return *table;
66
97
  }
67
98
 
68
99
  #if defined(ESP_PLATFORM) && !defined(GEA_EMBEDDED_WIFI_DISABLED)
69
- void platform_open(NativeWebSocketHandle, const std::string &);
100
+ void platform_open(NativeWebSocketHandle, const std::string &, const std::string &);
101
+ std::size_t platform_buffered(NativeWebSocketHandle);
70
102
  void platform_send(NativeWebSocketHandle, const std::string &);
71
103
  void platform_close(NativeWebSocketHandle);
72
104
  void platform_destroy(NativeWebSocketHandle);
105
+ void platform_reap();
106
+ void platform_set_producer(NativeWebSocketHandle, TextProducer);
73
107
  #else
74
- __attribute__((weak)) void platform_open(NativeWebSocketHandle, const std::string &) {}
108
+ __attribute__((weak)) void platform_open(NativeWebSocketHandle, const std::string &, const std::string &) {}
109
+ __attribute__((weak)) std::size_t platform_buffered(NativeWebSocketHandle) { return 0; }
75
110
  __attribute__((weak)) void platform_send(NativeWebSocketHandle, const std::string &) {}
76
111
  __attribute__((weak)) void platform_close(NativeWebSocketHandle) {}
77
112
  __attribute__((weak)) void platform_destroy(NativeWebSocketHandle) {}
113
+ __attribute__((weak)) void platform_reap() {}
114
+ __attribute__((weak)) void platform_set_producer(NativeWebSocketHandle, TextProducer) {}
78
115
  #endif
79
116
 
80
- NativeWebSocketHandle create_handle(const std::string &url) {
117
+ void setTextProducer(NativeWebSocketHandle handle, TextProducer producer) {
118
+ if (producer) workers::Context::current()->prioritizeAudio();
119
+ platform_set_producer(handle, std::move(producer));
120
+ }
121
+
122
+ void setTextConsumer(NativeWebSocketHandle handle, TextConsumer consumer) {
123
+ std::lock_guard lock(instancesMutex());
124
+ auto it = instances().find(handle);
125
+ if (it == instances().end()) throw std::invalid_argument("Closed WebSocket native sink");
126
+ it->second.consumer = std::move(consumer);
127
+ }
128
+
129
+ NativeWebSocketHandle create_handle(const std::string &url, const std::string &protocols) {
81
130
  auto handle = nextHandle()++;
82
131
  {
83
132
  std::lock_guard<std::mutex> lock(instancesMutex());
84
- instances()[handle] = WebSocketInstance{url, WebSocket::CONNECTING};
133
+ instances()[handle] = WebSocketInstance{url, WebSocket::CONNECTING, {}};
85
134
  }
86
- platform_open(handle, url);
135
+ auto owner = workers::Context::current();
136
+ (void)callbackTable();
137
+ { std::lock_guard lock(ownerMutex); owners[handle] = owner; }
138
+ if (!owner->isMain()) owner->addCleanup([handle] { destroy_handle(handle); });
139
+ platform_open(handle, url, protocols);
87
140
  return handle;
88
141
  }
89
142
 
90
143
  void destroy_handle(NativeWebSocketHandle handle) {
91
144
  platform_destroy(handle);
145
+ { std::lock_guard lock(ownerMutex); owners.erase(handle); }
92
146
  std::lock_guard<std::mutex> lock(instancesMutex());
93
147
  instances().erase(handle);
94
148
  callbackTable().erase(handle);
95
149
  }
96
150
 
97
151
  void runCallbacks() {
98
- std::vector<PendingEvent> drained;
99
- {
100
- std::lock_guard<std::mutex> lock(queueMutex());
101
- drained.swap(eventQueue());
102
- }
103
- for (const auto &ev : drained) {
104
- auto it = callbackTable().find(ev.handle);
105
- if (it == callbackTable().end()) continue;
106
- switch (ev.kind) {
107
- case EventKind::Open:
108
- if (it->second.on_open) it->second.on_open();
109
- break;
110
- case EventKind::Message:
111
- if (it->second.on_message) it->second.on_message(ev.text);
112
- break;
113
- case EventKind::Close:
114
- if (it->second.on_close) it->second.on_close(ev.code, ev.text);
115
- break;
116
- case EventKind::Error:
117
- if (it->second.on_error) it->second.on_error(ev.text);
118
- break;
119
- }
120
- }
152
+ platform_reap();
153
+ workers::Context::current()->runPending();
121
154
  }
122
155
 
123
156
  void test_inject_open(NativeWebSocketHandle handle) {
@@ -145,6 +178,38 @@ void test_set_error_callback(NativeWebSocketHandle handle, std::function<void(co
145
178
 
146
179
  } // namespace websocket
147
180
 
181
+ namespace {
182
+ void dispatch(PendingEvent ev) {
183
+ auto &table = websocket::callbackTable();
184
+ const auto it = table.find(ev.handle);
185
+ if (it == table.end()) return;
186
+ switch (ev.kind) {
187
+ case EventKind::Open: {
188
+ const auto callback = it->second.on_open;
189
+ if (callback) callback();
190
+ break;
191
+ }
192
+ case EventKind::Message: {
193
+ const auto callback = it->second.on_message;
194
+ if (callback) callback(ev.text);
195
+ break;
196
+ }
197
+ case EventKind::Close: {
198
+ websocket::platform_close(ev.handle);
199
+ const auto callback = std::move(it->second.on_close);
200
+ table.erase(it);
201
+ if (callback) callback(ev.code, ev.text);
202
+ break;
203
+ }
204
+ case EventKind::Error: {
205
+ const auto callback = it->second.on_error;
206
+ if (callback) callback(ev.text);
207
+ break;
208
+ }
209
+ }
210
+ }
211
+ } // namespace
212
+
148
213
  std::string WebSocket::url() const {
149
214
  std::lock_guard<std::mutex> lock(instancesMutex());
150
215
  auto it = instances().find(nativeHandle);
@@ -157,6 +222,8 @@ double WebSocket::readyState() const {
157
222
  return it == instances().end() ? CLOSED : static_cast<double>(it->second.readyState);
158
223
  }
159
224
 
225
+ double WebSocket::bufferedAmount() const { return websocket::platform_buffered(nativeHandle); }
226
+
160
227
  void WebSocket::send(const std::string &data) const {
161
228
  websocket::platform_send(nativeHandle, data);
162
229
  }
@@ -180,27 +247,226 @@ void WebSocket::close(double, const std::string &) const {
180
247
  #include "esp_event.h"
181
248
  #include "esp_log.h"
182
249
  #include "esp_websocket_client.h"
250
+ #include "esp_crt_bundle.h"
251
+ #include "esp_transport_ssl.h"
252
+ #include "esp_transport_tcp.h"
253
+ #include "esp_transport_ws.h"
254
+ #include "http_parser.h"
255
+ #include "lwip/sockets.h"
256
+ #include "lwip/tcp.h"
257
+ #include "lwip/tcpip.h"
258
+ #include "lwip/api.h"
259
+ #include "freertos/queue.h"
260
+ #include "lwip/priv/tcp_priv.h"
261
+ #include <new>
262
+ #include <cerrno>
263
+ #include "freertos/FreeRTOS.h"
264
+ #include "freertos/task.h"
265
+ #include "freertos/idf_additions.h"
266
+ #include "esp_heap_caps.h"
267
+ #include "esp_timer.h"
183
268
 
184
269
  namespace gea::host::websocket {
185
270
 
186
271
  namespace {
187
272
 
273
+ std::recursive_mutex platformMutex;
274
+
275
+ struct TaskCpuTelemetry {
276
+ std::int64_t wallAt = 0;
277
+ #if CONFIG_FREERTOS_USE_TRACE_FACILITY && CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS && CONFIG_FREERTOS_RUN_TIME_STATS_USING_ESP_TIMER
278
+ configRUN_TIME_COUNTER_TYPE cpuAt = 0;
279
+
280
+ static configRUN_TIME_COUNTER_TYPE currentCpu() {
281
+ TaskStatus_t status{};
282
+ vTaskGetInfo(nullptr, &status, pdFALSE, eRunning);
283
+ return status.ulRunTimeCounter;
284
+ }
285
+ #endif
286
+
287
+ void sample(const char *direction) {
288
+ #if CONFIG_FREERTOS_USE_TRACE_FACILITY && CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS && CONFIG_FREERTOS_RUN_TIME_STATS_USING_ESP_TIMER
289
+ const auto now = esp_timer_get_time();
290
+ if (wallAt && now - wallAt < 1000000) return;
291
+ const auto cpu = currentCpu();
292
+ if (wallAt) {
293
+ const auto elapsed = now - wallAt;
294
+ const auto used = static_cast<configRUN_TIME_COUNTER_TYPE>(cpu - cpuAt);
295
+ ESP_LOGI("gea::host::ws", "%s cpu_us=%llu wall_us=%llu core=%d",
296
+ direction, static_cast<unsigned long long>(used),
297
+ static_cast<unsigned long long>(elapsed), int(xPortGetCoreID()));
298
+ }
299
+ wallAt = now;
300
+ cpuAt = cpu;
301
+ #endif
302
+ }
303
+ };
304
+
188
305
  struct EspWsState {
306
+ NativeWebSocketHandle handle = 0;
307
+ TaskCpuTelemetry receiveCpu;
189
308
  esp_websocket_client_handle_t client = nullptr;
309
+ esp_transport_handle_t transport = nullptr;
310
+ esp_transport_handle_t parentTransport = nullptr;
311
+ std::uint16_t localPort = 0;
312
+ std::chrono::steady_clock::time_point bufferedSnapshotAt{};
313
+ std::chrono::steady_clock::time_point receiveSlowLogAt{};
314
+
315
+ ~EspWsState() {
316
+ // An external transport remains caller-owned. The client and its RX task
317
+ // have already stopped before the final state owner releases these handles.
318
+ if (transport) esp_transport_destroy(transport);
319
+ if (parentTransport) esp_transport_destroy(parentTransport);
320
+ }
321
+ std::mutex mutex;
322
+ std::deque<std::string> outgoing;
323
+ TextProducer producer;
324
+ std::size_t bytes = 0;
325
+ std::atomic<bool> closing{false};
326
+ std::atomic<bool> finished{false};
327
+ TaskHandle_t worker = nullptr;
190
328
  };
191
329
 
192
- std::unordered_map<NativeWebSocketHandle, EspWsState> &espStateTable() {
193
- static std::unordered_map<NativeWebSocketHandle, EspWsState> table;
330
+ std::unordered_map<NativeWebSocketHandle, std::shared_ptr<EspWsState>> &espStateTable() {
331
+ static std::unordered_map<NativeWebSocketHandle, std::shared_ptr<EspWsState>> table;
194
332
  return table;
195
333
  }
196
334
 
335
+ std::vector<std::shared_ptr<EspWsState>> &retiredStates() {
336
+ static std::vector<std::shared_ptr<EspWsState>> states;
337
+ return states;
338
+ }
339
+
340
+ // Inspect lwIP only on its own TCP/IP task. At most one snapshot may be queued;
341
+ // the request carries scalar identity, never a PCB pointer or socket owner.
342
+ std::atomic<bool> tcpSnapshotPending{false};
343
+ std::atomic<bool> tcpSnapshotReady{false};
344
+
345
+ struct TcpSnapshot {
346
+ NativeWebSocketHandle handle = 0;
347
+ std::uint16_t localPort = 0;
348
+ long sendMs = 0;
349
+ bool found = false;
350
+ unsigned state = 0, flags = 0, refused = 0, sndBuf = 0, sndQueue = 0;
351
+ unsigned cwnd = 0, sndWnd = 0, rcvWnd = 0, nrtx = 0;
352
+ unsigned unacked = 0, unsent = 0, unackedBytes = 0, unsentBytes = 0;
353
+ int receiveQueue = -1, rtime = 0, rto = 0, sa = 0, sv = 0;
354
+ };
355
+ TcpSnapshot tcpSnapshot;
356
+ std::int64_t tcpSnapshotAt = 0; // Accessed only while owning pending.
357
+
358
+ void printTcpSnapshot() {
359
+ if (!tcpSnapshotReady.exchange(false, std::memory_order_acquire)) return;
360
+ const auto snapshot = tcpSnapshot;
361
+ // The copied value is now independent of the next TCP/IP callback. Keep
362
+ // both logging and heap inspection on the caller, never on the TCP/IP task.
363
+ tcpSnapshotPending.store(false, std::memory_order_release);
364
+ if (!snapshot.found) {
365
+ ESP_LOGI("gea::host::ws", "tcp handle=%u send_ms=%ld pcb=closed", unsigned(snapshot.handle), snapshot.sendMs);
366
+ return;
367
+ }
368
+ ESP_LOGI("gea::host::ws", "tcp handle=%u send_ms=%ld state=%u flags=%u recv_queue=%d refused=%u snd_buf=%u snd_queue=%u cwnd=%u snd_wnd=%u rcv_wnd=%u nrtx=%u rtime=%d rto=%d sa=%d sv=%d unacked=%u/%u unsent=%u/%u heap=%u largest=%u",
369
+ unsigned(snapshot.handle), snapshot.sendMs, snapshot.state, snapshot.flags,
370
+ snapshot.receiveQueue, snapshot.refused, snapshot.sndBuf, snapshot.sndQueue,
371
+ snapshot.cwnd, snapshot.sndWnd, snapshot.rcvWnd, snapshot.nrtx,
372
+ snapshot.rtime, snapshot.rto, snapshot.sa, snapshot.sv,
373
+ snapshot.unacked, snapshot.unackedBytes, snapshot.unsent, snapshot.unsentBytes,
374
+ unsigned(heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)),
375
+ unsigned(heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)));
376
+ }
377
+
378
+ void requestTcpSnapshot(const EspWsState &state, long sendMs) {
379
+ if (!state.localPort || tcpSnapshotPending.exchange(true)) return;
380
+ const auto now = esp_timer_get_time();
381
+ if (now - tcpSnapshotAt < 1000000) {
382
+ tcpSnapshotPending.store(false);
383
+ return;
384
+ }
385
+ tcpSnapshotAt = now;
386
+ tcpSnapshot = TcpSnapshot{};
387
+ tcpSnapshot.handle = state.handle;
388
+ tcpSnapshot.localPort = state.localPort;
389
+ tcpSnapshot.sendMs = sendMs;
390
+ const auto queued = tcpip_try_callback([](void *arg) {
391
+ auto& snapshot = *static_cast<TcpSnapshot *>(arg);
392
+ unsigned scanned = 0;
393
+ for (auto *pcb = tcp_active_pcbs; pcb && scanned++ < 32; pcb = pcb->next) {
394
+ if (pcb->local_port != snapshot.localPort) continue;
395
+ snapshot.found = true;
396
+ for (auto *segment = pcb->unacked; segment && snapshot.unacked < 64; segment = segment->next) {
397
+ ++snapshot.unacked;
398
+ snapshot.unackedBytes += segment->len;
399
+ }
400
+ for (auto *segment = pcb->unsent; segment && snapshot.unsent < 64; segment = segment->next) {
401
+ ++snapshot.unsent;
402
+ snapshot.unsentBytes += segment->len;
403
+ }
404
+ if (auto *connection = static_cast<netconn *>(pcb->callback_arg);
405
+ connection && connection->pcb.tcp == pcb && sys_mbox_valid(&connection->recvmbox)) {
406
+ snapshot.receiveQueue = int(uxQueueMessagesWaiting(reinterpret_cast<QueueHandle_t>(&connection->recvmbox->os_mbox)));
407
+ }
408
+ snapshot.state = unsigned(pcb->state);
409
+ snapshot.flags = unsigned(pcb->flags);
410
+ snapshot.refused = pcb->refused_data ? unsigned(pcb->refused_data->tot_len) : 0u;
411
+ snapshot.sndBuf = unsigned(pcb->snd_buf);
412
+ snapshot.sndQueue = unsigned(pcb->snd_queuelen);
413
+ snapshot.cwnd = unsigned(pcb->cwnd);
414
+ snapshot.sndWnd = unsigned(pcb->snd_wnd);
415
+ snapshot.rcvWnd = unsigned(pcb->rcv_wnd);
416
+ snapshot.nrtx = unsigned(pcb->nrtx);
417
+ snapshot.rtime = int(pcb->rtime);
418
+ snapshot.rto = int(pcb->rto);
419
+ snapshot.sa = int(pcb->sa);
420
+ snapshot.sv = int(pcb->sv);
421
+ break;
422
+ }
423
+ tcpSnapshotReady.store(true, std::memory_order_release);
424
+ }, &tcpSnapshot);
425
+ if (queued != ERR_OK) {
426
+ tcpSnapshotPending.store(false);
427
+ }
428
+ }
429
+
197
430
  void handleWsEvent(void *arg, esp_event_base_t, int32_t event_id, void *data) {
198
- const auto handle = static_cast<NativeWebSocketHandle>(reinterpret_cast<std::uintptr_t>(arg));
431
+ auto *state = static_cast<EspWsState *>(arg);
432
+ const auto handle = state->handle;
433
+ // The synthetic close from the TX task must not contaminate RX CPU totals.
434
+ if (event_id == WEBSOCKET_EVENT_CONNECTED || event_id == WEBSOCKET_EVENT_DATA)
435
+ state->receiveCpu.sample("rx");
199
436
  switch (event_id) {
200
437
  case WEBSOCKET_EVENT_CONNECTED: {
438
+ // The SDK writes the tiny WebSocket header and payload as separate TLS
439
+ // records. Nagle can otherwise hold the payload behind the header's ACK.
440
+ const int socket = esp_transport_get_socket(state->transport);
441
+ sockaddr_storage address{};
442
+ socklen_t addressLength = sizeof(address);
443
+ if (socket >= 0 && getsockname(socket, reinterpret_cast<sockaddr *>(&address), &addressLength) == 0) {
444
+ if (address.ss_family == AF_INET)
445
+ state->localPort = ntohs(reinterpret_cast<sockaddr_in *>(&address)->sin_port);
446
+ #if LWIP_IPV6
447
+ else if (address.ss_family == AF_INET6)
448
+ state->localPort = ntohs(reinterpret_cast<sockaddr_in6 *>(&address)->sin6_port);
449
+ #endif
450
+ }
451
+ const int enabled = 1;
452
+ int actual = 0;
453
+ socklen_t optionLength = sizeof(actual);
454
+ if (socket < 0 || setsockopt(socket, IPPROTO_TCP, TCP_NODELAY,
455
+ &enabled, sizeof(enabled)) != 0 ||
456
+ getsockopt(socket, IPPROTO_TCP, TCP_NODELAY, &actual, &optionLength) != 0 ||
457
+ actual != 1) {
458
+ ESP_LOGE("gea::host::ws", "TCP_NODELAY failed errno=%d", errno);
459
+ state->closing.store(true);
460
+ enqueue(PendingEvent{handle, EventKind::Error, "WebSocket low-latency socket configuration failed", 0});
461
+ break;
462
+ }
463
+ ESP_LOGI("gea::host::ws", "connected; tcp_nodelay=%d task stack free=%u",
464
+ actual, static_cast<unsigned>(uxTaskGetStackHighWaterMark(nullptr)));
465
+ requestTcpSnapshot(*state, 0);
201
466
  {
202
467
  std::lock_guard<std::mutex> lock(gea::host::instancesMutex());
203
468
  if (auto it = gea::host::instances().find(handle); it != gea::host::instances().end()) {
469
+ if (it->second.readyState != WebSocket::CONNECTING) return;
204
470
  it->second.readyState = WebSocket::OPEN;
205
471
  }
206
472
  }
@@ -209,10 +475,47 @@ void handleWsEvent(void *arg, esp_event_base_t, int32_t event_id, void *data) {
209
475
  }
210
476
  case WEBSOCKET_EVENT_DATA: {
211
477
  const auto *event = static_cast<esp_websocket_event_data_t *>(data);
212
- if (event && event->op_code == 0x01 /* text frame */ && event->data_len > 0) {
213
- gea::host::enqueue(gea::host::PendingEvent{
214
- handle, gea::host::EventKind::Message,
215
- std::string(event->data_ptr, event->data_len), 0});
478
+ if (event && event->data_len >= 0 && event->payload_offset >= 0 && event->payload_len >= 0) {
479
+ const auto began = std::chrono::steady_clock::now();
480
+ const auto lockBegan = std::chrono::steady_clock::now();
481
+ auto acquired = lockBegan;
482
+ std::string complete;
483
+ bool hasMessage = false;
484
+ TextConsumer consumer;
485
+ {
486
+ std::lock_guard<std::mutex> lock(gea::host::instancesMutex());
487
+ acquired = std::chrono::steady_clock::now();
488
+ auto it = gea::host::instances().find(handle);
489
+ if (it == gea::host::instances().end() || it->second.readyState != WebSocket::OPEN) break;
490
+ auto &messages = it->second.messages;
491
+ const auto result = messages.append(event->op_code, event->fin,
492
+ event->payload_offset, event->payload_len,
493
+ std::string_view(event->data_ptr ? event->data_ptr : "", event->data_len));
494
+ if (result == TextMessageAssembler::Result::Complete) {
495
+ complete = messages.take();
496
+ hasMessage = true;
497
+ consumer = it->second.consumer;
498
+ } else if (result == TextMessageAssembler::Result::Invalid) {
499
+ gea::host::enqueue(gea::host::PendingEvent{
500
+ handle, gea::host::EventKind::Error, "Invalid or oversized WebSocket message", 0});
501
+ }
502
+ }
503
+ if (hasMessage) {
504
+ try {
505
+ if (!consumer || !consumer(complete))
506
+ enqueue(PendingEvent{handle, EventKind::Message, std::move(complete), 0});
507
+ } catch (const std::exception& error) {
508
+ enqueue(PendingEvent{handle, EventKind::Error, error.what(), 0});
509
+ }
510
+ }
511
+ const auto finished = std::chrono::steady_clock::now();
512
+ const auto callbackUs = std::chrono::duration_cast<std::chrono::microseconds>(finished - began).count();
513
+ if (callbackUs > 5000 && finished - state->receiveSlowLogAt >= std::chrono::seconds(1)) {
514
+ state->receiveSlowLogAt = finished;
515
+ const auto lockUs = std::chrono::duration_cast<std::chrono::microseconds>(acquired - lockBegan).count();
516
+ ESP_LOGI("gea::host::ws", "rx done handle=%u offset=%d callback_us=%ld lock_us=%ld",
517
+ unsigned(handle), event->payload_offset, long(callbackUs), long(lockUs));
518
+ }
216
519
  }
217
520
  break;
218
521
  }
@@ -220,6 +523,7 @@ void handleWsEvent(void *arg, esp_event_base_t, int32_t event_id, void *data) {
220
523
  {
221
524
  std::lock_guard<std::mutex> lock(gea::host::instancesMutex());
222
525
  if (auto it = gea::host::instances().find(handle); it != gea::host::instances().end()) {
526
+ if (it->second.readyState == WebSocket::CLOSED) return;
223
527
  it->second.readyState = WebSocket::CLOSED;
224
528
  }
225
529
  }
@@ -227,6 +531,17 @@ void handleWsEvent(void *arg, esp_event_base_t, int32_t event_id, void *data) {
227
531
  break;
228
532
  }
229
533
  case WEBSOCKET_EVENT_ERROR: {
534
+ if (const auto* event = static_cast<esp_websocket_event_data_t*>(data)) {
535
+ const auto& error = event->error_handle;
536
+ // SDK leaves transport fields uninitialized for other error kinds.
537
+ const bool transportError = error.error_type == WEBSOCKET_ERROR_TYPE_TCP_TRANSPORT;
538
+ ESP_LOGE("gea::host::ws", "error handle=%u type=%d transport=%d tls=%d errno=%d http=%d",
539
+ unsigned(handle), int(error.error_type), transportError ? int(error.esp_tls_last_esp_err) : 0,
540
+ transportError ? error.esp_tls_stack_err : 0, transportError ? error.esp_transport_sock_errno : 0,
541
+ error.esp_ws_handshake_status_code);
542
+ if (event->data_ptr && event->data_len > 0)
543
+ ESP_LOGE("gea::host::ws", "error detail=%.*s", std::min(event->data_len, 512), event->data_ptr);
544
+ }
230
545
  gea::host::enqueue(gea::host::PendingEvent{handle, gea::host::EventKind::Error, std::string("error"), 0});
231
546
  break;
232
547
  }
@@ -235,43 +550,279 @@ void handleWsEvent(void *arg, esp_event_base_t, int32_t event_id, void *data) {
235
550
 
236
551
  } // namespace
237
552
 
238
- void platform_open(NativeWebSocketHandle handle, const std::string &url) {
553
+ // One worker owns sends and teardown. The UI only enqueues bounded messages;
554
+ // TLS backpressure and close handshakes never hold the render/event thread.
555
+ struct SendWorker {
556
+ NativeWebSocketHandle handle;
557
+ std::shared_ptr<EspWsState> state;
558
+ };
559
+
560
+ void sendWorker(void *arg) {
561
+ std::unique_ptr<SendWorker> job(static_cast<SendWorker *>(arg));
562
+ const auto state = job->state;
563
+ auto telemetryAt = std::chrono::steady_clock::now();
564
+ auto snapshotAt = telemetryAt;
565
+ auto slowSendLogAt = telemetryAt;
566
+ TaskCpuTelemetry sendCpu;
567
+ auto sendCpuAt = telemetryAt;
568
+ unsigned sentPackets = 0;
569
+ std::size_t sentBytes = 0;
570
+ long maxSendMs = 0;
571
+ while (!state->closing.load()) {
572
+ printTcpSnapshot();
573
+ sendCpu.sample("tx");
574
+ std::string message;
575
+ TextProducer producer;
576
+ bool queued = false;
577
+ {
578
+ std::lock_guard<std::mutex> lock(state->mutex);
579
+ if (!state->outgoing.empty()) {
580
+ message = std::move(state->outgoing.front());
581
+ state->outgoing.pop_front();
582
+ queued = true;
583
+ } else {
584
+ producer = state->producer;
585
+ }
586
+ }
587
+ // Protocol/control messages go first. Capture then runs directly on this
588
+ // worker: no UI timer, JS callback, or intermediate outgoing audio queue.
589
+ if (producer) {
590
+ try {
591
+ message = producer();
592
+ } catch (const std::exception &error) {
593
+ enqueue(PendingEvent{job->handle, EventKind::Error, error.what(), 0});
594
+ state->closing.store(true);
595
+ continue;
596
+ }
597
+ }
598
+ if (state->closing.load()) break;
599
+ if (message.empty()) {
600
+ vTaskDelay(pdMS_TO_TICKS(5));
601
+ continue;
602
+ }
603
+ const auto sendStarted = std::chrono::steady_clock::now();
604
+ if (sendStarted - snapshotAt >= std::chrono::seconds(1)) {
605
+ requestTcpSnapshot(*state, -1);
606
+ snapshotAt = sendStarted;
607
+ }
608
+ #if CONFIG_FREERTOS_USE_TRACE_FACILITY && CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS && CONFIG_FREERTOS_RUN_TIME_STATS_USING_ESP_TIMER
609
+ const bool measureSendCpu = sendStarted - sendCpuAt >= std::chrono::seconds(1);
610
+ const auto cpuBefore = measureSendCpu ? TaskCpuTelemetry::currentCpu() : 0;
611
+ #endif
612
+ // TCP's initial retransmit timeout is 1.5 s. A 1 s application deadline
613
+ // aborted healthy connections before TCP could recover a single lost packet.
614
+ const auto sent = esp_websocket_client_send_text(state->client, message.data(),
615
+ static_cast<int>(message.size()), pdMS_TO_TICKS(5000));
616
+ const auto sendMs = std::chrono::duration_cast<std::chrono::milliseconds>(
617
+ std::chrono::steady_clock::now() - sendStarted).count();
618
+ #if CONFIG_FREERTOS_USE_TRACE_FACILITY && CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS && CONFIG_FREERTOS_RUN_TIME_STATS_USING_ESP_TIMER
619
+ if (measureSendCpu) {
620
+ const auto cpuUsed = static_cast<configRUN_TIME_COUNTER_TYPE>(TaskCpuTelemetry::currentCpu() - cpuBefore);
621
+ ESP_LOGI("gea::host::ws", "send cpu_us=%llu wall_ms=%ld bytes=%u",
622
+ static_cast<unsigned long long>(cpuUsed), long(sendMs), unsigned(message.size()));
623
+ sendCpuAt = std::chrono::steady_clock::now();
624
+ }
625
+ #endif
626
+ const auto sendFinished = std::chrono::steady_clock::now();
627
+ if (sendMs > 80 && sendFinished - slowSendLogAt >= std::chrono::seconds(1)) {
628
+ slowSendLogAt = sendFinished;
629
+ ESP_LOGW("gea::host::ws", "send bytes=%u duration_ms=%ld", unsigned(message.size()), long(sendMs));
630
+ requestTcpSnapshot(*state, long(sendMs));
631
+ }
632
+ {
633
+ std::lock_guard<std::mutex> lock(state->mutex);
634
+ if (queued) state->bytes -= message.size();
635
+ }
636
+ if (sent != static_cast<int>(message.size())) {
637
+ enqueue(PendingEvent{job->handle, EventKind::Error, "WebSocket send failed", 0});
638
+ state->closing.store(true);
639
+ } else {
640
+ ++sentPackets;
641
+ sentBytes += message.size();
642
+ maxSendMs = std::max(maxSendMs, long(sendMs));
643
+ const auto now = std::chrono::steady_clock::now();
644
+ const auto spanMs = std::chrono::duration_cast<std::chrono::milliseconds>(now - telemetryAt).count();
645
+ if (spanMs >= 2000) {
646
+ std::size_t queuedBytes;
647
+ {
648
+ std::lock_guard<std::mutex> lock(state->mutex);
649
+ queuedBytes = state->bytes;
650
+ }
651
+ ESP_LOGI("gea::host::ws", "sent packets=%u bytes=%u span_ms=%ld max_send_ms=%ld queued_bytes=%u",
652
+ sentPackets, unsigned(sentBytes), long(spanMs), maxSendMs, unsigned(queuedBytes));
653
+ sentPackets = 0;
654
+ sentBytes = 0;
655
+ maxSendMs = 0;
656
+ telemetryAt = now;
657
+ }
658
+ }
659
+ }
660
+ // Stop also interrupts CONNECTING. Client destruction waits for its event
661
+ // task here, not in a UI handler. State remains alive until both are done.
662
+ esp_websocket_client_stop(state->client);
663
+ esp_websocket_client_destroy(state->client);
664
+ state->client = nullptr;
665
+ printTcpSnapshot();
666
+ handleWsEvent(state.get(), nullptr, WEBSOCKET_EVENT_DISCONNECTED, nullptr);
667
+ job.reset();
668
+ // Release the final local reference before deleting the FreeRTOS task.
669
+ // (C++ automatic destructors don't run after vTaskDelete.)
670
+ // The scope below is provided by the task trampoline in platform_open.
671
+ }
672
+
673
+ void platform_open(NativeWebSocketHandle handle, const std::string &url, const std::string &protocols) {
674
+ std::lock_guard platformLock(platformMutex);
239
675
  esp_websocket_client_config_t config = {};
240
676
  config.uri = url.c_str();
241
-
242
- auto client = esp_websocket_client_init(&config);
243
- if (!client) {
244
- ESP_LOGE("gea::host::ws", "init failed for %s", url.c_str());
677
+ config.subprotocol = protocols.empty() ? nullptr : protocols.c_str();
678
+ config.task_stack = 8192;
679
+ config.buffer_size = 4096;
680
+ config.disable_auto_reconnect = true;
681
+ #if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
682
+ config.crt_bundle_attach = esp_crt_bundle_attach;
683
+ #endif
684
+ auto state = std::make_shared<EspWsState>();
685
+ state->handle = handle;
686
+ http_parser_url parsed{};
687
+ http_parser_url_init(&parsed);
688
+ if (http_parser_parse_url(url.c_str(), url.size(), 0, &parsed) != 0) {
689
+ enqueue(PendingEvent{handle, EventKind::Error, "Invalid WebSocket URL", 0});
690
+ return;
691
+ }
692
+ const auto field = [&](http_parser_url_fields name) {
693
+ return url.substr(parsed.field_data[name].off, parsed.field_data[name].len);
694
+ };
695
+ const auto scheme = field(UF_SCHEMA);
696
+ const bool secure = scheme == "wss";
697
+ if ((!secure && scheme != "ws") || parsed.field_data[UF_USERINFO].len ||
698
+ (parsed.field_set & (1 << UF_FRAGMENT))) {
699
+ enqueue(PendingEvent{handle, EventKind::Error, "WebSocket URL must use ws/wss without credentials or a fragment", 0});
700
+ return;
701
+ }
702
+ // Own the standard SDK transports to access their public socket API. Keep
703
+ // certificate verification, SNI, TLS, frame parsing and masking in the SDK.
704
+ state->parentTransport = secure ? esp_transport_ssl_init() : esp_transport_tcp_init();
705
+ if (state->parentTransport) state->transport = esp_transport_ws_init(state->parentTransport);
706
+ if (!state->transport) {
707
+ enqueue(PendingEvent{handle, EventKind::Error, "WebSocket transport allocation failed", 0});
245
708
  return;
246
709
  }
247
- esp_websocket_register_events(
248
- client, WEBSOCKET_EVENT_ANY, handleWsEvent,
249
- reinterpret_cast<void *>(static_cast<std::uintptr_t>(handle)));
250
- esp_websocket_client_start(client);
251
- espStateTable()[handle] = EspWsState{client};
710
+ #if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
711
+ if (secure) esp_transport_ssl_crt_bundle_attach(state->parentTransport, esp_crt_bundle_attach);
712
+ #endif
713
+ esp_transport_set_default_port(state->parentTransport, secure ? 443 : 80);
714
+ esp_transport_set_default_port(state->transport, secure ? 443 : 80);
715
+ auto path = field(UF_PATH);
716
+ if (path.empty()) path = "/";
717
+ if (parsed.field_set & (1 << UF_QUERY)) path += "?" + field(UF_QUERY);
718
+ esp_transport_ws_config_t transportConfig{};
719
+ transportConfig.ws_path = path.c_str();
720
+ transportConfig.sub_protocol = config.subprotocol;
721
+ transportConfig.propagate_control_frames = true;
722
+ if (esp_transport_ws_set_config(state->transport, &transportConfig) != ESP_OK) {
723
+ enqueue(PendingEvent{handle, EventKind::Error, "WebSocket transport configuration failed", 0});
724
+ return;
725
+ }
726
+ config.ext_transport = state->transport;
727
+ state->client = esp_websocket_client_init(&config);
728
+ if (!state->client) {
729
+ enqueue(PendingEvent{handle, EventKind::Error, "WebSocket initialization failed", 0});
730
+ return;
731
+ }
732
+ esp_websocket_register_events(state->client, WEBSOCKET_EVENT_ANY, handleWsEvent, state.get());
733
+ espStateTable()[handle] = state;
734
+ if (esp_websocket_client_start(state->client) != ESP_OK) {
735
+ esp_websocket_client_destroy(state->client);
736
+ espStateTable().erase(handle);
737
+ enqueue(PendingEvent{handle, EventKind::Error, "WebSocket startup failed", 0});
738
+ return;
739
+ }
740
+ auto *job = new SendWorker{handle, state};
741
+ const auto stackCaps = MALLOC_CAP_8BIT | (heap_caps_get_total_size(MALLOC_CAP_SPIRAM)
742
+ ? MALLOC_CAP_SPIRAM : MALLOC_CAP_INTERNAL);
743
+ if (xTaskCreateWithCaps([](void *p) {
744
+ auto *state = static_cast<SendWorker *>(p)->state.get();
745
+ sendWorker(p); // All C++ owners unwind before publishing completion.
746
+ state->finished.store(true, std::memory_order_release);
747
+ vTaskSuspend(nullptr); // UI reaps the stopped task and its PSRAM stack.
748
+ }, "gea-ws-send", 6144, job, 5, &state->worker,
749
+ stackCaps) != pdPASS) {
750
+ delete job;
751
+ esp_websocket_client_stop(state->client);
752
+ esp_websocket_client_destroy(state->client);
753
+ espStateTable().erase(handle);
754
+ enqueue(PendingEvent{handle, EventKind::Error, "WebSocket worker allocation failed", 0});
755
+ }
756
+ }
757
+
758
+ std::size_t platform_buffered(NativeWebSocketHandle handle) {
759
+ std::lock_guard platformLock(platformMutex);
760
+ const auto it = espStateTable().find(handle);
761
+ if (it == espStateTable().end()) return 0;
762
+ const auto now = std::chrono::steady_clock::now();
763
+ if (now - it->second->bufferedSnapshotAt >= std::chrono::seconds(1)) {
764
+ requestTcpSnapshot(*it->second, -2);
765
+ it->second->bufferedSnapshotAt = now;
766
+ }
767
+ std::lock_guard<std::mutex> lock(it->second->mutex);
768
+ return it->second->bytes;
769
+ }
770
+
771
+ void platform_set_producer(NativeWebSocketHandle handle, TextProducer producer) {
772
+ std::lock_guard platformLock(platformMutex);
773
+ const auto it = espStateTable().find(handle);
774
+ if (it == espStateTable().end() || it->second->closing.load())
775
+ throw std::runtime_error("WebSocket is not available for PCM streaming");
776
+ std::lock_guard<std::mutex> lock(it->second->mutex);
777
+ it->second->producer = std::move(producer);
778
+ // A native PCM producer is a realtime audio resource. The sender must not
779
+ // sit at generic background priority while the UI runs at priority 23.
780
+ // Capture/mixer remain above both tasks at priority 24.
781
+ if (it->second->producer && it->second->worker)
782
+ vTaskPrioritySet(it->second->worker, configMAX_PRIORITIES - 2);
252
783
  }
253
784
 
254
785
  void platform_send(NativeWebSocketHandle handle, const std::string &data) {
255
- auto it = espStateTable().find(handle);
256
- if (it == espStateTable().end() || it->second.client == nullptr) return;
257
- esp_websocket_client_send_text(it->second.client, data.c_str(),
258
- static_cast<int>(data.size()), portMAX_DELAY);
786
+ std::lock_guard platformLock(platformMutex);
787
+ const auto it = espStateTable().find(handle);
788
+ if (it == espStateTable().end() || it->second->closing.load()) return;
789
+ auto &state = *it->second;
790
+ std::lock_guard<std::mutex> lock(state.mutex);
791
+ if (state.bytes + data.size() > 512 * 1024) {
792
+ state.closing.store(true);
793
+ enqueue(PendingEvent{handle, EventKind::Error, "WebSocket send queue exceeded 512 KiB", 0});
794
+ return;
795
+ }
796
+ state.outgoing.push_back(data);
797
+ state.bytes += data.size();
259
798
  }
260
799
 
261
800
  void platform_close(NativeWebSocketHandle handle) {
262
- auto it = espStateTable().find(handle);
263
- if (it == espStateTable().end() || it->second.client == nullptr) return;
264
- esp_websocket_client_close(it->second.client, portMAX_DELAY);
801
+ std::lock_guard platformLock(platformMutex);
802
+ {
803
+ std::lock_guard<std::mutex> lock(instancesMutex());
804
+ const auto it = instances().find(handle);
805
+ if (it != instances().end() && it->second.readyState != WebSocket::CLOSED)
806
+ it->second.readyState = WebSocket::CLOSING;
807
+ }
808
+ const auto it = espStateTable().find(handle);
809
+ if (it == espStateTable().end()) return;
810
+ it->second->closing.store(true);
811
+ retiredStates().push_back(it->second);
812
+ espStateTable().erase(it);
265
813
  }
266
814
 
267
- void platform_destroy(NativeWebSocketHandle handle) {
268
- auto it = espStateTable().find(handle);
269
- if (it == espStateTable().end()) return;
270
- if (it->second.client) {
271
- esp_websocket_client_stop(it->second.client);
272
- esp_websocket_client_destroy(it->second.client);
815
+ void platform_destroy(NativeWebSocketHandle handle) { platform_close(handle); }
816
+
817
+ void platform_reap() {
818
+ std::lock_guard platformLock(platformMutex);
819
+ auto &retired = retiredStates();
820
+ for (auto it = retired.begin(); it != retired.end();) {
821
+ if (!(*it)->finished.load(std::memory_order_acquire) ||
822
+ eTaskGetState((*it)->worker) != eSuspended) { ++it; continue; }
823
+ vTaskDeleteWithCaps((*it)->worker);
824
+ it = retired.erase(it);
273
825
  }
274
- espStateTable().erase(it);
275
826
  }
276
827
 
277
828
  } // namespace gea::host::websocket