@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
package/host/rtc_esp.cpp CHANGED
@@ -3,8 +3,31 @@
3
3
 
4
4
  #include "host/rtc.h"
5
5
  #include "host/media.h"
6
+ #include "host/rtc_opus.h"
7
+ #include "host/rtc_sdp.h"
8
+ #if __has_include("esp_h264_dec_sw.h")
9
+ #include "host/rtc_h264.h"
10
+ #define GEA_RTC_HAS_H264 1
11
+ #else
12
+ #define GEA_RTC_HAS_H264 0
13
+ #endif
14
+ #if __has_include("gea_vp8_peer.h") && __has_include("vpx/vpx_decoder.h")
15
+ #include "gea_vp8_peer.h"
16
+ #include "host/rtc_receive_sdp.h"
17
+ #include "host/rtc_vp8_decoder.h"
18
+ #define GEA_RTC_HAS_VP8 1
19
+ #if defined(GEA_EMBEDDED_VP8_BENCHMARK) && GEA_EMBEDDED_VP8_BENCHMARK
20
+ #include "host/rtc_vp8_capture.h"
21
+ #endif
22
+ #else
23
+ #define GEA_RTC_HAS_VP8 0
24
+ #endif
25
+ #define GEA_RTC_HAS_VIDEO (GEA_RTC_HAS_H264 || GEA_RTC_HAS_VP8)
26
+ #include "wifi.h"
6
27
 
7
28
  #include "esp_log.h"
29
+ #include "esp_timer.h"
30
+ #include "esp_heap_caps.h"
8
31
  #include "esp_peer.h"
9
32
  #include "esp_peer_default.h"
10
33
  #include "freertos/FreeRTOS.h"
@@ -15,35 +38,145 @@
15
38
  #include <cstdint>
16
39
  #include <cstring>
17
40
  #include <mutex>
41
+ #include <memory>
42
+ #include <optional>
43
+ #include <stdexcept>
44
+ #include <climits>
18
45
  #include <string>
19
46
  #include <unordered_map>
20
47
  #include <vector>
48
+ #include <deque>
21
49
 
22
50
  namespace gea::host::rtc {
23
51
 
24
52
  namespace {
25
53
 
26
54
  constexpr const char *kTag = "gea::host::rtc";
27
- constexpr int kAudioSampleRate = 16000;
28
- constexpr int kAudioChannels = 1;
29
- constexpr std::size_t kSendFrameSamples = 320; // 20 ms @ 16 kHz mono
55
+ // RFC 7587 section 7: SDP/RTP always use opus/48000/2, even for 16 kHz
56
+ // mono PCM. The bitstream carries its actual bandwidth and channel count.
57
+ constexpr int kOpusRtpClockRate = 48000;
58
+ constexpr int kOpusRtpChannels = 2;
59
+ constexpr std::size_t kSendFrameSamples = OpusAudio::frameSamples;
60
+ // DTLS + SCTP call chains exceed 8 KiB on IDF 6. These are PSRAM stacks;
61
+ // retain headroom for Opus callbacks rather than consuming internal DMA RAM.
62
+ constexpr uint32_t kPeerStackBytes = 24 * 1024;
63
+ // The fixed-point SILK encoder uses nested variable-sized stack arrays;
64
+ // 16 KiB overflowed on the first real microphone frame at complexity 3.
65
+ constexpr uint32_t kSendStackBytes = 64 * 1024;
66
+ constexpr uint32_t kControlStackBytes = 32 * 1024;
67
+
68
+ // Read only this worker, without stack scanning or a global task census. The
69
+ // IDF runtime counter uses microseconds; preserve its configured width so
70
+ // subtraction remains correct across the 32-bit counter wrap.
71
+ configRUN_TIME_COUNTER_TYPE currentTaskCpuTicks() {
72
+ #if CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS
73
+ TaskStatus_t info{};
74
+ vTaskGetInfo(nullptr, &info, pdFALSE, eInvalid);
75
+ return info.ulRunTimeCounter;
76
+ #else
77
+ return 0;
78
+ #endif
79
+ }
30
80
 
31
81
  struct EspPeerState {
32
82
  esp_peer_handle_t handle = nullptr;
33
83
  NativeRtcPeerHandle our_handle = 0;
84
+ std::atomic<bool> closing{false};
34
85
  TaskHandle_t main_loop_task = nullptr;
35
86
  TaskHandle_t audio_send_task = nullptr;
87
+ TaskHandle_t audio_receive_task = nullptr;
36
88
 
37
89
  // create_offer blocks on this until on_msg fires with SDP.
38
90
  SemaphoreHandle_t sdp_ready = nullptr;
91
+ SemaphoreHandle_t transport_wake = nullptr;
92
+ bool packet_wake = false;
39
93
  std::string pending_sdp;
94
+ std::mutex sdp_mutex;
40
95
 
41
- NativeMediaTrackHandle local_track = 0;
96
+ std::atomic<NativeMediaTrackHandle> local_track{0};
42
97
  NativeMediaTrackHandle remote_track = 0;
98
+ NativeMediaStreamHandle remote_stream = 0;
43
99
 
44
- bool open = false;
100
+ std::atomic<bool> open{false};
101
+ std::atomic<bool> connected{false};
102
+ std::atomic<bool> data_connected{false};
103
+ RTCConfiguration config;
104
+ std::unique_ptr<OpusAudio> audio;
105
+ bool received_audio = false;
106
+ std::atomic<uint32_t> received_audio_frames{0};
107
+ std::atomic<unsigned> received_opus_config{0};
108
+ std::atomic<uint32_t> decode_time_us{0}, publish_time_us{0}, decode_count{0};
109
+ struct EncodedAudio {
110
+ std::array<uint8_t, 1275> bytes;
111
+ uint32_t pts = 0;
112
+ uint16_t size = 0;
113
+ };
114
+ std::deque<EncodedAudio, media::VideoAllocator<EncodedAudio>> received_audio_queue;
115
+ std::mutex received_audio_mutex;
116
+ std::atomic<uint32_t> received_audio_drops{0};
117
+ int64_t last_audio_us = 0;
118
+ uint32_t last_audio_pts = 0;
119
+ std::string direction = "inactive", video_direction = "inactive";
120
+ NativeMediaTrackHandle remote_video_track = 0;
121
+ NativeMediaStreamHandle remote_video_stream = 0;
122
+ #if GEA_RTC_HAS_VIDEO
123
+ bool vp8_video = false;
124
+ bool native_daily_receive = false;
125
+ unsigned input_video_width = 0, input_video_height = 0;
126
+ std::atomic<bool> request_video_keyframe{false};
127
+ using VideoBytes = std::vector<uint8_t, media::VideoAllocator<uint8_t>>;
128
+ struct EncodedVideo { VideoBytes data; uint32_t pts = 0; };
129
+ std::deque<EncodedVideo> video_frames;
130
+ std::mutex video_mutex;
131
+ bool need_video_keyframe = true;
132
+ TaskHandle_t video_task = nullptr;
133
+ SemaphoreHandle_t video_done = nullptr;
134
+ #endif
135
+ std::vector<esp_peer_ice_server_cfg_t> servers;
136
+ std::vector<std::pair<std::string, RTCDataChannelInit>> pending_channels;
137
+ std::mutex channels_mutex;
138
+ SemaphoreHandle_t main_done = nullptr, audio_done = nullptr, audio_receive_done = nullptr;
45
139
  };
46
140
 
141
+ // SDP creation and teardown may wait for the transport. Serialize those
142
+ // operations on a PSRAM worker, never on the frame/input thread. Close queues
143
+ // behind any pending offer, so neither can free state the other still uses.
144
+ std::mutex controlMutex;
145
+ std::deque<std::function<void()>> controlJobs;
146
+ TaskHandle_t controlTask = nullptr;
147
+
148
+ void controlLoop(void*) {
149
+ for (;;) {
150
+ ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
151
+ for (;;) {
152
+ std::function<void()> job;
153
+ {
154
+ std::lock_guard<std::mutex> lock(controlMutex);
155
+ if (controlJobs.empty()) break;
156
+ job = std::move(controlJobs.front());
157
+ controlJobs.pop_front();
158
+ }
159
+ try { job(); }
160
+ catch (const std::exception& error) { ESP_LOGE(kTag, "RTC control operation failed: %s", error.what()); }
161
+ }
162
+ }
163
+ }
164
+
165
+ void ensureControlTask() {
166
+ if (controlTask) return;
167
+ if (xTaskCreatePinnedToCoreWithCaps(controlLoop, "gea_rtc_control", kControlStackBytes, nullptr, 2,
168
+ &controlTask, 1, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT) != pdPASS)
169
+ throw std::runtime_error("RTC control task allocation failed");
170
+ }
171
+
172
+ void queueControl(std::function<void()> job) {
173
+ {
174
+ std::lock_guard<std::mutex> lock(controlMutex);
175
+ controlJobs.push_back(std::move(job));
176
+ }
177
+ xTaskNotifyGive(controlTask);
178
+ }
179
+
47
180
  std::unordered_map<NativeRtcPeerHandle, EspPeerState *> &espPeerTable() {
48
181
  static std::unordered_map<NativeRtcPeerHandle, EspPeerState *> table;
49
182
  return table;
@@ -64,7 +197,16 @@ EspPeerState *findPeer(NativeRtcPeerHandle handle) {
64
197
  // JS-side frame-loop pump via the existing rtc::enqueue_* hooks.
65
198
 
66
199
  int on_state_cb(esp_peer_state_t state, void *ctx) {
200
+ ESP_LOGI(kTag, "transport state=%d", static_cast<int>(state));
67
201
  auto *peer_state = static_cast<EspPeerState *>(ctx);
202
+ if (state == ESP_PEER_STATE_DATA_CHANNEL_CONNECTED) {
203
+ peer_state->data_connected = true;
204
+ return 0;
205
+ }
206
+ if (state == ESP_PEER_STATE_DATA_CHANNEL_DISCONNECTED) {
207
+ peer_state->data_connected = false;
208
+ return 0;
209
+ }
68
210
  const char *name = "new";
69
211
  switch (state) {
70
212
  case ESP_PEER_STATE_CLOSED: name = "closed"; break;
@@ -78,10 +220,13 @@ int on_state_cb(esp_peer_state_t state, void *ctx) {
78
220
  break;
79
221
  case ESP_PEER_STATE_CONNECTED: name = "connected"; break;
80
222
  case ESP_PEER_STATE_CONNECT_FAILED: name = "failed"; break;
81
- default: name = "new"; break;
223
+ default: return 0; // Data-channel/track events are not connection changes.
82
224
  }
225
+ peer_state->connected = state == ESP_PEER_STATE_CONNECTED;
83
226
  enqueue_connection_state_change(peer_state->our_handle, std::string(name));
84
- enqueue_ice_connection_state_change(peer_state->our_handle, std::string(name));
227
+ enqueue_ice_connection_state_change(peer_state->our_handle,
228
+ state == ESP_PEER_STATE_CONNECTED ? "connected" : state == ESP_PEER_STATE_CONNECT_FAILED ? "failed" :
229
+ state == ESP_PEER_STATE_CLOSED ? "closed" : state == ESP_PEER_STATE_DISCONNECTED ? "disconnected" : "checking");
85
230
  return 0;
86
231
  }
87
232
 
@@ -91,7 +236,16 @@ int on_msg_cb(esp_peer_msg_t *info, void *ctx) {
91
236
  std::string payload(reinterpret_cast<const char *>(info->data), static_cast<std::size_t>(info->size));
92
237
  switch (info->type) {
93
238
  case ESP_PEER_MSG_TYPE_SDP:
94
- peer_state->pending_sdp = payload;
239
+ ESP_LOGI(kTag, "local SDP ready (%d bytes)", info->size);
240
+ // Candidate addresses are safe transport diagnostics; never log SDP
241
+ // wholesale because it also contains ICE authentication credentials.
242
+ for (std::size_t pos = payload.find("a=candidate:"); pos != std::string::npos;
243
+ pos = payload.find("a=candidate:", pos + 1)) {
244
+ const auto end = payload.find_first_of("\r\n", pos);
245
+ ESP_LOGI(kTag, "local %s", payload.substr(pos, end - pos).c_str());
246
+ }
247
+ { std::lock_guard<std::mutex> lock(peer_state->sdp_mutex);
248
+ peer_state->pending_sdp = opusPcmCapabilities(payload, OpusAudio::sampleRate, 1); }
95
249
  if (peer_state->sdp_ready) xSemaphoreGive(peer_state->sdp_ready);
96
250
  break;
97
251
  case ESP_PEER_MSG_TYPE_CANDIDATE:
@@ -102,137 +256,745 @@ int on_msg_cb(esp_peer_msg_t *info, void *ctx) {
102
256
  return 0;
103
257
  }
104
258
 
105
- int on_audio_data_cb(esp_peer_audio_frame_t *frame, void *ctx) {
259
+ int decode_audio_frame(esp_peer_audio_frame_t *frame, void *ctx) {
106
260
  auto *peer_state = static_cast<EspPeerState *>(ctx);
107
261
  if (!frame || !frame->data || frame->size <= 0) return 0;
108
262
  if (!peer_state->remote_track) {
109
263
  // Lazily create a remote track stream + track so JS can attach playback.
110
- auto stream_handle = gea::host::media::create_stream();
111
- peer_state->remote_track = gea::host::media::stream_audio_track(stream_handle);
264
+ peer_state->remote_stream = gea::host::media::create_remote_stream();
265
+ peer_state->remote_track = gea::host::media::stream_audio_track(peer_state->remote_stream);
112
266
  enqueue_track(peer_state->our_handle, peer_state->remote_track);
113
267
  }
114
- // Frame data is decoded PCM int16; track_inject_pcm handles the ring buffer.
115
- gea::host::media::track_inject_pcm(
116
- peer_state->remote_track,
117
- reinterpret_cast<const std::int16_t *>(frame->data),
118
- static_cast<std::size_t>(frame->size) / sizeof(std::int16_t));
268
+ const int64_t arrived = esp_timer_get_time();
269
+ if (peer_state->last_audio_us && arrived - peer_state->last_audio_us > 60000)
270
+ ESP_LOGI(kTag, "RTP audio gap_ms=%lld pts_delta=%u", static_cast<long long>((arrived - peer_state->last_audio_us) / 1000), unsigned(frame->pts - peer_state->last_audio_pts));
271
+ peer_state->last_audio_us = arrived;
272
+ peer_state->last_audio_pts = frame->pts;
273
+ peer_state->received_opus_config.store(frame->data[0] >> 3, std::memory_order_relaxed);
274
+ const int samples = peer_state->audio->decode(frame->data, frame->size);
275
+ const int64_t decodeUs = esp_timer_get_time() - arrived;
276
+ peer_state->decode_time_us += decodeUs;
277
+ ++peer_state->decode_count;
278
+ if (decodeUs > 15000) ESP_LOGI(kTag, "Opus decode_ms=%lld samples=%d", static_cast<long long>(decodeUs / 1000), samples);
279
+ if (samples < 0) { ESP_LOGW(kTag, "Invalid Opus packet: %d", samples); return 0; }
280
+ if (!peer_state->received_audio) {
281
+ peer_state->received_audio = true;
282
+ ESP_LOGI(kTag, "first decoded audio: samples=%d opus_config=%u stereo=%u worker stack free=%u/%u", samples,
283
+ unsigned(frame->data[0] >> 3), unsigned((frame->data[0] >> 2) & 1),
284
+ static_cast<unsigned>(uxTaskGetStackHighWaterMark(nullptr)), static_cast<unsigned>(kPeerStackBytes));
285
+ }
286
+ peer_state->received_audio_frames.fetch_add(1, std::memory_order_relaxed);
287
+ gea::host::media::track_inject_pcm(peer_state->remote_track, peer_state->audio->decoded.data(), samples);
288
+ peer_state->publish_time_us += esp_timer_get_time() - arrived - decodeUs;
119
289
  return 0;
120
290
  }
121
291
 
292
+ int on_audio_data_cb(esp_peer_audio_frame_t* frame, void* ctx) {
293
+ auto* state = static_cast<EspPeerState*>(ctx);
294
+ if (!state->open || state->closing || !frame || !frame->data || frame->size <= 0 || frame->size > 1275)
295
+ return -1;
296
+ // The transport must keep draining authenticated RTP while Opus works.
297
+ // Queue capacity absorbs bursts; the decoder starts immediately (no prefill).
298
+ try {
299
+ std::lock_guard lock(state->received_audio_mutex);
300
+ if (state->received_audio_queue.size() >= 32) {
301
+ ++state->received_audio_drops;
302
+ return -1;
303
+ }
304
+ auto& packet = state->received_audio_queue.emplace_back();
305
+ packet.size = frame->size;
306
+ packet.pts = frame->pts;
307
+ std::memcpy(packet.bytes.data(), frame->data, frame->size);
308
+ } catch (const std::bad_alloc&) {
309
+ ++state->received_audio_drops;
310
+ return -1;
311
+ }
312
+ if (state->audio_receive_task) xTaskNotifyGive(state->audio_receive_task);
313
+ return 0;
314
+ }
315
+
316
+ void audio_receive_trampoline(void* opaque) {
317
+ auto* state = static_cast<EspPeerState*>(opaque);
318
+ auto cpuStart = currentTaskCpuTicks();
319
+ auto measuredAt = esp_timer_get_time();
320
+ unsigned packets = 0;
321
+ while (state->open && !state->closing) {
322
+ EspPeerState::EncodedAudio packet;
323
+ {
324
+ std::lock_guard lock(state->received_audio_mutex);
325
+ if (!state->received_audio_queue.empty()) {
326
+ packet = std::move(state->received_audio_queue.front());
327
+ state->received_audio_queue.pop_front();
328
+ }
329
+ }
330
+ if (!packet.size) {
331
+ ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(20));
332
+ continue;
333
+ }
334
+ esp_peer_audio_frame_t frame{};
335
+ frame.data = packet.bytes.data();
336
+ frame.size = packet.size;
337
+ frame.pts = packet.pts;
338
+ decode_audio_frame(&frame, state);
339
+ ++packets;
340
+ const auto now = esp_timer_get_time();
341
+ if (now - measuredAt >= 2000000) {
342
+ const auto cpuNow = currentTaskCpuTicks();
343
+ ESP_LOGI(kTag, "audio worker peer=%u cpu_us=%llu span_us=%lld packets=%u",
344
+ unsigned(state->our_handle),
345
+ (unsigned long long)configRUN_TIME_COUNTER_TYPE(cpuNow - cpuStart),
346
+ (long long)(now - measuredAt), packets);
347
+ cpuStart = cpuNow; measuredAt = now; packets = 0;
348
+ }
349
+ }
350
+ xSemaphoreGive(state->audio_receive_done);
351
+ for (;;) vTaskSuspend(nullptr);
352
+ }
353
+
354
+ #if GEA_RTC_HAS_VIDEO
355
+ int queue_video_data(esp_peer_video_frame_t* frame, void* ctx,
356
+ EspPeerState::VideoBytes* owned = nullptr) {
357
+ auto* state = static_cast<EspPeerState*>(ctx);
358
+ if (!frame || !frame->data || frame->size <= 0 || frame->size > 512 * 1024 || !state->open) return 0;
359
+ bool keyframe = false, headers = false;
360
+ const size_t length = static_cast<size_t>(frame->size);
361
+ if (state->vp8_video) {
362
+ keyframe = !(frame->data[0] & 1);
363
+ // VP8 keyframe dimensions are in the uncompressed header. Report them
364
+ // before the decode worker runs, including frames rejected for size.
365
+ if (keyframe && length >= 10 && frame->data[3] == 0x9d &&
366
+ frame->data[4] == 0x01 && frame->data[5] == 0x2a) {
367
+ const unsigned width = (frame->data[6] | (unsigned(frame->data[7]) << 8)) & 0x3fff;
368
+ const unsigned height = (frame->data[8] | (unsigned(frame->data[9]) << 8)) & 0x3fff;
369
+ if (width != state->input_video_width || height != state->input_video_height) {
370
+ state->input_video_width = width;
371
+ state->input_video_height = height;
372
+ ESP_LOGI(kTag, "VP8 input dimensions=%ux%u keyframe_bytes=%u", width, height, unsigned(length));
373
+ }
374
+ }
375
+ }
376
+ #if GEA_RTC_HAS_H264
377
+ else {
378
+ unsigned prefix = 0;
379
+ for (size_t position = h264::startCode(frame->data, length, 0, prefix); position < length;) {
380
+ const size_t nal = position + prefix;
381
+ if (nal < length && (frame->data[nal] & 31) == 5) keyframe = true;
382
+ if (nal < length && ((frame->data[nal] & 31) == 7 || (frame->data[nal] & 31) == 8)) headers = true;
383
+ position = h264::startCode(frame->data, length, nal, prefix);
384
+ }
385
+ }
386
+ #endif
387
+ std::lock_guard<std::mutex> lock(state->video_mutex);
388
+ // A complete VP8 keyframe replaces the old reference chain. Skip queued
389
+ // pictures from that old chain now, instead of spending seconds decoding
390
+ // them before reaching an already-arrived independently decodable picture.
391
+ // The single decode worker finishes its current picture before this one.
392
+ if (state->vp8_video && keyframe && length >= 10 && frame->data[3] == 0x9d &&
393
+ frame->data[4] == 0x01 && frame->data[5] == 0x2a && !state->video_frames.empty()) {
394
+ ESP_LOGI(kTag, "VP8 newest keyframe replaces queued_references=%u", unsigned(state->video_frames.size()));
395
+ state->video_frames.clear();
396
+ state->request_video_keyframe = false;
397
+ }
398
+ // Compressed references are not a playback buffer. A keyframe can take
399
+ // longer than three arrival intervals; repeatedly dropping its dependents
400
+ // forces expensive keyframes forever. Retain bounded compressed references
401
+ // while the worker coalesces obsolete decoded display images.
402
+ size_t queuedBytes = 0;
403
+ for (const auto& queued : state->video_frames) queuedBytes += queued.data.size();
404
+ if (state->video_frames.size() >= 32 || queuedBytes + length > 512 * 1024) {
405
+ state->video_frames.clear();
406
+ state->need_video_keyframe = true;
407
+ state->request_video_keyframe = true;
408
+ ESP_LOGW(kTag, "video decoder behind; awaiting keyframe");
409
+ }
410
+ if (state->need_video_keyframe && !keyframe && !headers) return -1;
411
+ if (keyframe) state->need_video_keyframe = false;
412
+ try {
413
+ state->video_frames.push_back({owned ? std::move(*owned)
414
+ : EspPeerState::VideoBytes(frame->data, frame->data + length), frame->pts});
415
+ } catch (...) {
416
+ state->video_frames.clear(); state->need_video_keyframe = true;
417
+ state->request_video_keyframe = true; return -1;
418
+ }
419
+ if (state->video_task) xTaskNotifyGive(state->video_task);
420
+ return 0;
421
+ }
422
+
423
+ int on_video_data_cb(esp_peer_video_frame_t* frame, void* ctx) {
424
+ return queue_video_data(frame, ctx);
425
+ }
426
+
427
+ #if GEA_RTC_HAS_VP8
428
+ int on_owned_video_data_cb(vp8::EncodedFrame&& owned, void* ctx) {
429
+ esp_peer_video_frame_t frame{owned.timestamp / 90, owned.bytes.data(), int(owned.bytes.size())};
430
+ return queue_video_data(&frame, ctx, &owned.bytes);
431
+ }
432
+ #endif
433
+
434
+ void video_decode_trampoline(void* opaque) {
435
+ auto* state = static_cast<EspPeerState*>(opaque);
436
+ #if GEA_RTC_HAS_VP8 && defined(GEA_EMBEDDED_VP8_BENCHMARK) && GEA_EMBEDDED_VP8_BENCHMARK
437
+ vp8::capture().workerStarted();
438
+ #endif
439
+ #if GEA_RTC_HAS_H264
440
+ h264::Decoder decoder;
441
+ #endif
442
+ #if GEA_RTC_HAS_VP8
443
+ vp8::Decoder vp8Decoder;
444
+ ESP_LOGI(kTag, "VP8 internal workspace_bytes=%u", unsigned(vp8Decoder.internalWorkspaceBytes()));
445
+ #endif
446
+ uint64_t sequence = 0;
447
+ uint64_t referenceFrames = 0;
448
+ unsigned completedOnCore[2]{};
449
+ int64_t lastVideoReport = 0;
450
+ [[maybe_unused]] int64_t lastVideoPresented = 0;
451
+ while (state->open && !state->closing) {
452
+ EspPeerState::EncodedVideo encoded;
453
+ // Preserve codec references, but keep showing progress if decoding cannot
454
+ // empty the queue. Waiting exclusively for an empty queue freezes video.
455
+ [[maybe_unused]] bool moreQueued = false;
456
+ {
457
+ std::lock_guard<std::mutex> lock(state->video_mutex);
458
+ if (!state->video_frames.empty()) {
459
+ encoded = std::move(state->video_frames.front()); state->video_frames.pop_front();
460
+ moreQueued = !state->video_frames.empty();
461
+ }
462
+ }
463
+ if (encoded.data.empty()) { ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(20)); continue; }
464
+ // A sustained reference backlog must not monopolize its core between frames.
465
+ // One tick permits ready raster/idle work without dropping codec references
466
+ // or delaying the higher-priority transport and audio tasks.
467
+ struct FrameYield { ~FrameYield() { vTaskDelay(1); } } frameYield;
468
+ try {
469
+ const bool encodedKey = !(encoded.data.front() & 1);
470
+ const auto encodedSize = encoded.data.size();
471
+ std::shared_ptr<media::VideoFrame> frame;
472
+ const auto decodeStarted = esp_timer_get_time();
473
+ const auto decodeCore = xPortGetCoreID();
474
+ const auto decodeCpuStarted = currentTaskCpuTicks();
475
+ #if GEA_RTC_HAS_VP8
476
+ if (state->vp8_video) {
477
+ const auto presentationDelay = moreQueued && sequence
478
+ ? uint64_t(std::max<int64_t>(0, 100000 - (decodeStarted - lastVideoPresented))) : 0;
479
+ frame = vp8Decoder.decode(encoded.data, encoded.pts, true, presentationDelay);
480
+ const auto allocation = vp8Decoder.timing();
481
+ if (allocation.allocationFailedWidth) {
482
+ ESP_LOGW(kTag, "VP8 presentation allocation failed %ux%u bytes=%u psram_free=%u psram_largest=%u",
483
+ allocation.allocationFailedWidth, allocation.allocationFailedHeight,
484
+ allocation.allocationFailedWidth * allocation.allocationFailedHeight * 2,
485
+ unsigned(heap_caps_get_free_size(MALLOC_CAP_SPIRAM)),
486
+ unsigned(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM)));
487
+ }
488
+ if (!vp8Decoder.needsKeyframe()) ++referenceFrames;
489
+ if (!frame && vp8Decoder.needsKeyframe()) {
490
+ ESP_LOGW(kTag, "VP8 rejected frame bytes=%u key=%d elapsed_us=%lld",
491
+ unsigned(encoded.data.size()), !(encoded.data[0] & 1),
492
+ (long long)(esp_timer_get_time() - decodeStarted));
493
+ std::lock_guard<std::mutex> lock(state->video_mutex);
494
+ state->video_frames.clear(); state->need_video_keyframe = true;
495
+ state->request_video_keyframe = true;
496
+ }
497
+ }
498
+ #endif
499
+ #if GEA_RTC_HAS_H264
500
+ if (!state->vp8_video) frame = decoder.decode(encoded.data.data(), encoded.data.size(), encoded.pts);
501
+ #endif
502
+ const auto decodedAt = esp_timer_get_time();
503
+ const auto finishedCore = xPortGetCoreID();
504
+ ++completedOnCore[finishedCore];
505
+ const auto decodeCpu = configRUN_TIME_COUNTER_TYPE(currentTaskCpuTicks() - decodeCpuStarted);
506
+ #if GEA_RTC_HAS_VP8 && defined(GEA_EMBEDDED_VP8_BENCHMARK) && GEA_EMBEDDED_VP8_BENCHMARK
507
+ // Retain the accepted reference prefix, including pictures coalesced at
508
+ // presentation. Capture only after reading all metadata from encoded.
509
+ if (state->vp8_video && !vp8Decoder.needsKeyframe() && vp8::capture().requested()) {
510
+ const auto timing = vp8Decoder.timing();
511
+ vp8::capture().take(encoded.data, encoded.pts, decodedAt - decodeStarted,
512
+ decodeCpu, timing.decodeUs, timing.convertUs);
513
+ }
514
+ #endif
515
+ if (!frame) continue;
516
+ const bool reportVideo = !sequence || decodedAt - lastVideoReport >= 2000000;
517
+ if (reportVideo) ESP_LOGI(kTag, "%s decode+RGB565=%lld us %ux%u frames=%llu cpu_us=%llu key=%u bytes=%u references=%llu",
518
+ state->vp8_video ? "VP8" : "H264", (long long)(esp_timer_get_time() - decodeStarted),
519
+ unsigned(frame->width), unsigned(frame->height), (unsigned long long)(sequence + 1),
520
+ (unsigned long long)decodeCpu, unsigned(encodedKey), unsigned(encodedSize),
521
+ (unsigned long long)referenceFrames);
522
+ if (reportVideo) {
523
+ ESP_LOGI(kTag, "video worker started_core=%d finished_core=%d completed_core0=%u completed_core1=%u",
524
+ int(decodeCore), int(finishedCore), completedOnCore[0], completedOnCore[1]);
525
+ completedOnCore[0] = completedOnCore[1] = 0;
526
+ }
527
+ #if GEA_RTC_HAS_VP8
528
+ if (state->vp8_video && reportVideo) {
529
+ const auto timing = vp8Decoder.timing();
530
+ ESP_LOGI(kTag, "VP8 setup_us=%llu codec_us=%llu rgb565_us=%llu psram_free=%u psram_largest=%u",
531
+ (unsigned long long)timing.setupUs, (unsigned long long)timing.decodeUs,
532
+ (unsigned long long)timing.convertUs,
533
+ unsigned(heap_caps_get_free_size(MALLOC_CAP_SPIRAM)),
534
+ unsigned(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM)));
535
+ if (timing.macroblocks) ESP_LOGI(kTag,
536
+ "VP8 stages wall_us: tokens=%llu reconstruction=%llu loopfilter=%llu other=%llu macroblocks=%u token_blocks=%u filter_rows=%u",
537
+ (unsigned long long)timing.tokenUs,
538
+ (unsigned long long)(timing.macroblockUs >= timing.tokenUs ? timing.macroblockUs - timing.tokenUs : 0),
539
+ (unsigned long long)timing.filterUs,
540
+ (unsigned long long)(timing.decodeUs >= timing.macroblockUs + timing.filterUs ? timing.decodeUs - timing.macroblockUs - timing.filterUs : 0),
541
+ timing.macroblocks, timing.tokenBlocks, timing.filterRows);
542
+ }
543
+ #endif
544
+ if (reportVideo) lastVideoReport = decodedAt;
545
+ if (!state->remote_video_track) {
546
+ state->remote_video_stream = media::create_remote_video_stream();
547
+ state->remote_video_track = MediaStream(state->remote_video_stream).getVideoTracks().front().nativeHandle;
548
+ enqueue_track(state->our_handle, state->remote_video_track);
549
+ }
550
+ frame->sequence = ++sequence;
551
+ media::publish_video_frame(state->remote_video_track, std::move(frame));
552
+ lastVideoPresented = esp_timer_get_time();
553
+ } catch (...) {
554
+ ESP_LOGE(kTag, "Video decode/publish failed: internal_free=%u psram_free=%u psram_largest=%u",
555
+ unsigned(heap_caps_get_free_size(MALLOC_CAP_INTERNAL)),
556
+ unsigned(heap_caps_get_free_size(MALLOC_CAP_SPIRAM)),
557
+ unsigned(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM)));
558
+ #if GEA_RTC_HAS_H264
559
+ decoder.reset();
560
+ #endif
561
+ #if GEA_RTC_HAS_VP8
562
+ vp8Decoder.reset();
563
+ #endif
564
+ std::lock_guard<std::mutex> lock(state->video_mutex);
565
+ state->video_frames.clear(); state->need_video_keyframe = true;
566
+ state->request_video_keyframe = true;
567
+ }
568
+ }
569
+ #if GEA_RTC_HAS_H264
570
+ decoder.reset();
571
+ #endif
572
+ #if GEA_RTC_HAS_VP8
573
+ vp8Decoder.reset();
574
+ #endif
575
+ #if GEA_RTC_HAS_VP8 && defined(GEA_EMBEDDED_VP8_BENCHMARK) && GEA_EMBEDDED_VP8_BENCHMARK
576
+ vp8::capture().workerStopped();
577
+ #endif
578
+ xSemaphoreGive(state->video_done);
579
+ for (;;) vTaskSuspend(nullptr);
580
+ }
581
+ #endif
582
+
122
583
  void main_loop_trampoline(void *arg) {
123
584
  auto *peer_state = static_cast<EspPeerState *>(arg);
124
- while (peer_state->open) {
585
+ int64_t measured_at = esp_timer_get_time(), loop_us = 0, max_loop_us = 0;
586
+ auto cpuStart = currentTaskCpuTicks();
587
+ uint32_t loop_count = 0;
588
+ while (peer_state->open && !peer_state->closing) {
589
+ const auto loop_start = esp_timer_get_time();
125
590
  esp_peer_main_loop(peer_state->handle);
126
- vTaskDelay(pdMS_TO_TICKS(1));
591
+ const auto elapsed = esp_timer_get_time() - loop_start;
592
+ loop_us += elapsed;
593
+ max_loop_us = std::max(max_loop_us, elapsed);
594
+ ++loop_count;
595
+ if (esp_timer_get_time() - measured_at >= 2000000) {
596
+ const auto cpuNow = currentTaskCpuTicks();
597
+ ESP_LOGI(kTag, "transport span_ms=%lld calls=%u loop_us=%lld decode_us=%u publish_us=%u decoded=%u audio_queue_drops=%u max_loop_us=%lld peer=%u cpu_us=%llu",
598
+ (long long)((esp_timer_get_time() - measured_at) / 1000), unsigned(loop_count),
599
+ (long long)loop_us, unsigned(peer_state->decode_time_us.exchange(0)),
600
+ unsigned(peer_state->publish_time_us.exchange(0)), unsigned(peer_state->decode_count.exchange(0)),
601
+ unsigned(peer_state->received_audio_drops.load()), (long long)max_loop_us,
602
+ unsigned(peer_state->our_handle),
603
+ (unsigned long long)configRUN_TIME_COUNTER_TYPE(cpuNow - cpuStart));
604
+ cpuStart = cpuNow;
605
+ measured_at = esp_timer_get_time(); loop_us = max_loop_us = 0; loop_count = 0;
606
+ }
607
+ // SCTP association must be established before DCEP creates channels.
608
+ // DTLS/SRTP connected is an earlier, separate transport event.
609
+ if (peer_state->data_connected) {
610
+ std::lock_guard<std::mutex> lock(peer_state->channels_mutex);
611
+ for (auto it = peer_state->pending_channels.begin(); it != peer_state->pending_channels.end();) {
612
+ esp_peer_data_channel_cfg_t cfg{};
613
+ cfg.label = it->first.data(); cfg.ordered = it->second.ordered;
614
+ cfg.type = ESP_PEER_DATA_CHANNEL_RELIABLE;
615
+ if (it->second.maxRetransmits) { cfg.type = ESP_PEER_DATA_CHANNEL_PARTIAL_RELIABLE_RETX; cfg.max_retransmit_count = *it->second.maxRetransmits; }
616
+ else if (it->second.maxPacketLifeTime) { cfg.type = ESP_PEER_DATA_CHANNEL_PARTIAL_RELIABLE_TIMEOUT; cfg.max_packet_lifetime = *it->second.maxPacketLifeTime; }
617
+ const int result = esp_peer_create_data_channel(peer_state->handle, &cfg);
618
+ if (result == ESP_PEER_ERR_WRONG_STATE || result == ESP_PEER_ERR_WOULD_BLOCK) { ++it; continue; }
619
+ if (result != 0) { ESP_LOGE(kTag, "Data channel creation failed: %d", result); enqueue_connection_state_change(peer_state->our_handle, "failed"); }
620
+ it = peer_state->pending_channels.erase(it);
621
+ }
622
+ }
623
+ // Native Daily transports wake on incoming datagrams and encoded mic
624
+ // packets. Idle polling at 1 ms consumed ~10% of a core on the send peer
625
+ // alone. A 10 ms timer still services loss recovery/RTCP when no packet
626
+ // arrives; it does not add a media prefill or delay an arriving packet.
627
+ if (peer_state->packet_wake)
628
+ xSemaphoreTake(peer_state->transport_wake, pdMS_TO_TICKS(10));
629
+ else
630
+ vTaskDelay(pdMS_TO_TICKS(1));
127
631
  }
128
- vTaskDelete(nullptr);
632
+ xSemaphoreGive(peer_state->main_done);
633
+ for (;;) vTaskSuspend(nullptr); // Owner frees the PSRAM stack after joining.
129
634
  }
130
635
 
131
636
  void audio_send_trampoline(void *arg) {
132
637
  auto *peer_state = static_cast<EspPeerState *>(arg);
133
- std::int16_t buffer[kSendFrameSamples];
134
- while (peer_state->open) {
135
- if (peer_state->local_track == 0) {
638
+ alignas(16) std::int16_t buffer[kSendFrameSamples];
639
+ size_t filled = 0;
640
+ NativeMediaTrackHandle previous_track = 0;
641
+ std::optional<gea::host::media::TrackPcmReader> microphone;
642
+ uint32_t timestamp_ms = 0;
643
+ bool reported_stack = false;
644
+ int64_t window_start = esp_timer_get_time(), encode_us = 0, max_encode_us = 0;
645
+ int64_t send_us = 0, max_send_us = 0;
646
+ uint32_t sent_frames = 0, send_errors = 0;
647
+ uint32_t encoded_on_core[2]{};
648
+ auto cpuStart = currentTaskCpuTicks();
649
+ while (peer_state->open && !peer_state->closing) {
650
+ const auto track = peer_state->local_track.load();
651
+ if (!track || !peer_state->connected) {
652
+ microphone.reset();
653
+ previous_track = 0;
654
+ filled = 0;
136
655
  vTaskDelay(pdMS_TO_TICKS(20));
137
656
  continue;
138
657
  }
139
- std::size_t count = gea::host::media::track_read_pcm(
140
- peer_state->local_track, buffer, kSendFrameSamples);
141
- if (count == 0) {
142
- vTaskDelay(pdMS_TO_TICKS(5));
143
- continue;
658
+ if (track != previous_track) {
659
+ // Subscribe at live capture only after the transport connects. The
660
+ // compatibility cursor includes up to two seconds of preconnection PCM.
661
+ microphone.emplace(track, false);
662
+ previous_track = track;
663
+ filled = 0;
664
+ window_start = esp_timer_get_time();
665
+ cpuStart = currentTaskCpuTicks();
666
+ encode_us = max_encode_us = 0;
667
+ send_us = max_send_us = 0;
668
+ sent_frames = send_errors = 0;
669
+ peer_state->received_audio_frames.store(0);
670
+ }
671
+ filled += microphone->read(buffer + filled, kSendFrameSamples - filled);
672
+ if (filled < kSendFrameSamples) { vTaskDelay(pdMS_TO_TICKS(5)); continue; }
673
+ const int64_t encode_start = esp_timer_get_time();
674
+ ++encoded_on_core[xPortGetCoreID()];
675
+ const int bytes = peer_state->audio->encode(buffer);
676
+ const int64_t encoded_us = esp_timer_get_time() - encode_start;
677
+ encode_us += encoded_us;
678
+ if (encoded_us > max_encode_us) max_encode_us = encoded_us;
679
+ if (!reported_stack && bytes > 0) {
680
+ reported_stack = true;
681
+ ESP_LOGI(kTag, "first encoded audio: bytes=%d, worker stack free=%u/%u", bytes,
682
+ static_cast<unsigned>(uxTaskGetStackHighWaterMark(nullptr)), static_cast<unsigned>(kSendStackBytes));
144
683
  }
684
+ filled = 0;
685
+ if (bytes < 0) { ESP_LOGE(kTag, "Opus encode failed: %d", bytes); continue; }
145
686
  esp_peer_audio_frame_t frame = {};
146
- frame.pts = 0;
147
- frame.data = reinterpret_cast<uint8_t *>(buffer);
148
- frame.size = static_cast<int>(count * sizeof(std::int16_t));
149
- esp_peer_send_audio(peer_state->handle, &frame);
687
+ frame.pts = timestamp_ms;
688
+ frame.data = peer_state->audio->packet.data();
689
+ frame.size = bytes;
690
+ timestamp_ms += OpusAudio::frameDurationMs;
691
+ const auto send_start = esp_timer_get_time();
692
+ const int err = esp_peer_send_audio(peer_state->handle, &frame);
693
+ const auto send_elapsed = esp_timer_get_time() - send_start;
694
+ send_us += send_elapsed;
695
+ max_send_us = std::max(max_send_us, send_elapsed);
696
+ if (err != 0) { ++send_errors; ESP_LOGW(kTag, "Audio send failed: %d", err); }
697
+ else ++sent_frames;
698
+ const int64_t now = esp_timer_get_time();
699
+ if (now - window_start >= 2000000) {
700
+ const auto cpuNow = currentTaskCpuTicks();
701
+ ESP_LOGI(kTag, "duplex span_ms=%lld mic_sent=%u remote_received=%u send_errors=%u encode_avg_us=%lld encode_max_us=%lld mic_pending_ms=%u mic_dropped=%llu encode_core0=%u encode_core1=%u remote_opus_config=%u local_opus_config=%u send_avg_us=%lld send_max_us=%lld cpu_us=%llu",
702
+ static_cast<long long>((now - window_start) / 1000), unsigned(sent_frames),
703
+ unsigned(peer_state->received_audio_frames.exchange(0)), unsigned(send_errors),
704
+ static_cast<long long>(encode_us / (sent_frames + send_errors ? sent_frames + send_errors : 1)),
705
+ static_cast<long long>(max_encode_us),
706
+ unsigned(microphone->pendingSamples() * 1000 / OpusAudio::sampleRate),
707
+ static_cast<unsigned long long>(microphone->droppedSamples()),
708
+ unsigned(encoded_on_core[0]), unsigned(encoded_on_core[1]),
709
+ peer_state->received_opus_config.load(std::memory_order_relaxed), unsigned(peer_state->audio->packet[0] >> 3),
710
+ (long long)(send_us / (sent_frames + send_errors ? sent_frames + send_errors : 1)), (long long)max_send_us,
711
+ (unsigned long long)configRUN_TIME_COUNTER_TYPE(cpuNow - cpuStart));
712
+ cpuStart = cpuNow;
713
+ // Never take a task census here: uxTaskGetSystemState scans every task's
714
+ // stack while holding the FreeRTOS kernel lock, delaying DMA/network work.
715
+
716
+ window_start = now; encode_us = max_encode_us = 0; sent_frames = send_errors = 0;
717
+ send_us = max_send_us = 0;
718
+ encoded_on_core[0] = encoded_on_core[1] = 0;
719
+ }
150
720
  }
151
- vTaskDelete(nullptr);
721
+ microphone.reset(); // Release the reader before this task is suspended/deleted.
722
+ xSemaphoreGive(peer_state->audio_done);
723
+ for (;;) vTaskSuspend(nullptr);
152
724
  }
153
725
 
154
- EspPeerState *ensurePeer(NativeRtcPeerHandle our_handle) {
155
- std::lock_guard<std::mutex> lock(espPeerMutex());
156
- auto it = espPeerTable().find(our_handle);
157
- if (it != espPeerTable().end()) return it->second;
726
+ void releaseTransport(EspPeerState* state);
158
727
 
159
- auto *state = new EspPeerState{};
160
- state->our_handle = our_handle;
728
+ EspPeerState *ensurePeer(EspPeerState* state, bool answer = false) {
729
+ if (!state) return nullptr;
730
+ if (state->closing) throw std::runtime_error("AbortError: peer is closing");
731
+ if (state->handle) return state;
732
+ // Gea initializes lwIP only when Wi-Fi is enabled. Opening sockets sooner
733
+ // asserts in tcpip_send_msg_wait_sem; propagate a normal JS connection error.
734
+ if (!gea::framework::network::wifi().connected())
735
+ throw std::runtime_error("Wi-Fi is not connected. Check the device network settings and try Start again.");
736
+ try {
737
+ ESP_LOGI(kTag, "opening transport");
738
+ const auto opusDirection = state->direction == "sendonly" ? OpusAudio::Direction::Encode :
739
+ state->direction == "recvonly" ? OpusAudio::Direction::Decode : OpusAudio::Direction::Both;
740
+ const auto internalBeforeOpus = heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
741
+ state->audio = std::make_unique<OpusAudio>(OpusAudio::Application::LowDelay, opusDirection);
742
+ ESP_LOGI(kTag, "Opus direction=%s internal_before=%u internal_after=%u", state->direction.c_str(),
743
+ unsigned(internalBeforeOpus), unsigned(heap_caps_get_free_size(MALLOC_CAP_INTERNAL)));
161
744
  state->sdp_ready = xSemaphoreCreateBinary();
745
+ state->main_done = xSemaphoreCreateBinary();
746
+ state->audio_done = xSemaphoreCreateBinary();
747
+ if (!state->sdp_ready || !state->main_done || !state->audio_done) throw std::runtime_error("RTC semaphore allocation failed");
748
+ for (auto& server : state->config.iceServers) for (auto& url : server.urls) {
749
+ state->servers.push_back({url.data(),
750
+ server.username.empty() ? nullptr : server.username.data(),
751
+ server.credential.empty() ? nullptr : server.credential.data()});
752
+ }
753
+ if (state->servers.size() > 255) throw std::invalid_argument("Too many ICE servers");
162
754
  state->open = true;
163
-
164
- static esp_peer_ice_server_cfg_t default_stun = {};
165
- default_stun.stun_url = const_cast<char *>("stun:stun.l.google.com:19302");
166
-
167
755
  esp_peer_cfg_t cfg = {};
168
- cfg.server_lists = &default_stun;
169
- cfg.server_num = 1;
170
- cfg.role = ESP_PEER_ROLE_CONTROLLING;
171
- cfg.ice_trans_policy = ESP_PEER_ICE_TRANS_POLICY_ALL;
756
+ // Keep the transport's default receive timeout: agent_recv_timeout also
757
+ // governs DTLS handshakes. A 5 ms override caused repeated -0x7880 timeouts
758
+ // and prevented an accepted OpenAI session from ever connecting.
759
+ cfg.server_lists = state->servers.data();
760
+ cfg.server_num = static_cast<uint8_t>(state->servers.size());
761
+ cfg.role = answer ? ESP_PEER_ROLE_CONTROLLED : ESP_PEER_ROLE_CONTROLLING;
762
+ cfg.ice_trans_policy = state->config.iceTransportPolicy == "relay" ? ESP_PEER_ICE_TRANS_POLICY_RELAY : ESP_PEER_ICE_TRANS_POLICY_ALL;
172
763
  cfg.audio_info.codec = ESP_PEER_AUDIO_CODEC_OPUS;
173
- cfg.audio_info.sample_rate = kAudioSampleRate;
174
- cfg.audio_info.channel = kAudioChannels;
175
- cfg.audio_dir = ESP_PEER_MEDIA_DIR_SEND_RECV;
764
+ cfg.audio_info.sample_rate = kOpusRtpClockRate;
765
+ cfg.audio_info.channel = kOpusRtpChannels;
766
+ cfg.audio_dir = state->direction == "sendonly" ? ESP_PEER_MEDIA_DIR_SEND_ONLY :
767
+ state->direction == "recvonly" ? ESP_PEER_MEDIA_DIR_RECV_ONLY :
768
+ state->direction == "inactive" ? ESP_PEER_MEDIA_DIR_NONE : ESP_PEER_MEDIA_DIR_SEND_RECV;
769
+ if (state->direction == "recvonly" || state->direction == "sendrecv") {
770
+ state->audio_receive_done = xSemaphoreCreateBinary();
771
+ // Decode each authenticated audio packet before the transport drains its
772
+ // next burst. Running below the RTP worker lets startup bursts fill the
773
+ // bounded queue even when steady-state decoding meets its deadline.
774
+ if (!state->audio_receive_done ||
775
+ xTaskCreatePinnedToCoreWithCaps(audio_receive_trampoline, "gea_rtc_audio", kPeerStackBytes,
776
+ state, 8, &state->audio_receive_task, 1, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT) != pdPASS)
777
+ throw std::runtime_error("RTC audio decoder task allocation failed");
778
+ }
176
779
  cfg.video_dir = ESP_PEER_MEDIA_DIR_NONE;
177
- cfg.enable_data_channel = false;
780
+ #if GEA_RTC_HAS_VIDEO
781
+ if (state->video_direction == "recvonly") {
782
+ cfg.video_dir = ESP_PEER_MEDIA_DIR_RECV_ONLY;
783
+ cfg.video_info.codec = ESP_PEER_VIDEO_CODEC_H264;
784
+ #if GEA_RTC_HAS_VP8
785
+ if (state->vp8_video) cfg.video_info.codec = GEA_PEER_VIDEO_CODEC_VP8;
786
+ #endif
787
+ cfg.on_video_data = on_video_data_cb;
788
+ state->video_done = xSemaphoreCreateBinary();
789
+ if (!state->video_done) throw std::runtime_error("Video semaphore allocation failed");
790
+ // IDF pins coprocessor users, including PIE SIMD, on first use. Keep VP8
791
+ // on CPU1: CPU0 capture/send/UI work starved it in live measurements.
792
+ // Run VP8 above raster work (3), but below audio decode (8), transport (7)
793
+ // and audio send (5). A per-frame tick below lets raster/idle work progress.
794
+ // The vendor H264 decoder keeps its existing affinity.
795
+ if (xTaskCreatePinnedToCoreWithCaps(video_decode_trampoline, "gea_rtc_video", 64 * 1024, state,
796
+ state->vp8_video ? 4 : 3, &state->video_task, 1,
797
+ MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT) != pdPASS)
798
+ throw std::runtime_error("Video task allocation failed");
799
+ }
800
+ #endif
801
+ { std::lock_guard<std::mutex> lock(state->channels_mutex);
802
+ cfg.enable_data_channel = !state->pending_channels.empty(); }
803
+ cfg.manual_ch_create = true;
178
804
  cfg.ctx = state;
179
805
  cfg.on_state = on_state_cb;
180
806
  cfg.on_msg = on_msg_cb;
181
807
  cfg.on_audio_data = on_audio_data_cb;
808
+ cfg.on_channel_open = [](esp_peer_data_channel_info_t* channel, void* ctx) -> int {
809
+ auto* peer = static_cast<EspPeerState*>(ctx);
810
+ enqueue_channel_open(peer->our_handle, channel->label ? channel->label : "", channel->stream_id); return 0;
811
+ };
812
+ cfg.on_channel_close = [](esp_peer_data_channel_info_t* channel, void* ctx) -> int {
813
+ enqueue_channel_close(static_cast<EspPeerState*>(ctx)->our_handle, channel->stream_id); return 0;
814
+ };
815
+ cfg.on_data = [](esp_peer_data_frame_t* frame, void* ctx) -> int {
816
+ if (frame && frame->size >= 0) enqueue_channel_message(static_cast<EspPeerState*>(ctx)->our_handle,
817
+ frame->stream_id, frame->data, static_cast<size_t>(frame->size), frame->type == ESP_PEER_DATA_CHANNEL_STRING);
818
+ return 0;
819
+ };
182
820
 
183
- int err = esp_peer_open(&cfg, esp_peer_get_default_impl(), &state->handle);
821
+ const auto* implementation = esp_peer_get_default_impl();
822
+ #if GEA_RTC_HAS_VP8
823
+ GeaVp8PeerOptions vp8Options{&state->open, &state->request_video_keyframe};
824
+ if (state->native_daily_receive || state->vp8_video || (state->direction == "sendonly" &&
825
+ cfg.video_dir == ESP_PEER_MEDIA_DIR_NONE && !cfg.enable_data_channel &&
826
+ state->servers.empty() &&
827
+ cfg.ice_trans_policy != ESP_PEER_ICE_TRANS_POLICY_RELAY)) {
828
+ implementation = gea_vp8_peer_impl();
829
+ state->transport_wake = xSemaphoreCreateBinary();
830
+ if (!state->transport_wake) throw std::runtime_error("RTC transport wake allocation failed");
831
+ state->packet_wake = true;
832
+ vp8Options.wake = [](void* context) {
833
+ auto* peer = static_cast<EspPeerState*>(context);
834
+ xSemaphoreGive(peer->transport_wake);
835
+ };
836
+ vp8Options.wakeContext = state;
837
+ vp8Options.onOwnedVideo = on_owned_video_data_cb;
838
+ cfg.extra_cfg = &vp8Options;
839
+ cfg.extra_size = sizeof(vp8Options);
840
+ }
841
+ #endif
842
+ int err = esp_peer_open(&cfg, implementation, &state->handle);
184
843
  if (err != 0 || !state->handle) {
185
844
  ESP_LOGE(kTag, "esp_peer_open failed: %d", err);
186
- if (state->sdp_ready) vSemaphoreDelete(state->sdp_ready);
187
- delete state;
188
- return nullptr;
845
+ state->open = false;
846
+ throw std::runtime_error("esp_peer_open failed");
189
847
  }
190
848
 
191
- xTaskCreatePinnedToCore(main_loop_trampoline, "gea_rtc_loop", 8192, state, 7, &state->main_loop_task, 1);
192
- xTaskCreatePinnedToCore(audio_send_trampoline, "gea_rtc_send", 4096, state, 5, &state->audio_send_task, 1);
193
-
194
- espPeerTable()[our_handle] = state;
849
+ // These are network/codec workers, not DMA buffers or interrupt stacks.
850
+ // Keep their stacks in PSRAM, like the existing HTTP worker pool.
851
+ // Separate the native VP8 receive transport from its decoder. Keep receive
852
+ // audio on CPU1: moving both overloaded CPU0 and delayed microphone encoding.
853
+ // On CPU0 transport must stay below capture/send (24/5), above UI (3).
854
+ // Other peers retain their established scheduling.
855
+ const bool separateVideoTransport = state->vp8_video && state->packet_wake;
856
+ if (xTaskCreatePinnedToCoreWithCaps(main_loop_trampoline, "gea_rtc_loop", kPeerStackBytes, state,
857
+ separateVideoTransport ? 4 : 7, &state->main_loop_task,
858
+ separateVideoTransport ? 0 : 1,
859
+ MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT) != pdPASS ||
860
+ // Capture and encode share CPU0; receive/decode use CPU1. Keeping both
861
+ // Opus directions on CPU1 starves video even when CPU0 has spare time.
862
+ // RGB panels must use DMA scanout rather than continuous CPU bounce
863
+ // copies to leave enough CPU0 time for capture/AEC and encoding.
864
+ // NO_AFFINITY is not stable here: Xtensa's first FPU instruction pins
865
+ // an unpinned task to whichever core happened to execute it.
866
+ ((state->direction == "sendonly" || state->direction == "sendrecv") &&
867
+ xTaskCreatePinnedToCoreWithCaps(audio_send_trampoline, "gea_rtc_send", kSendStackBytes, state, 5, &state->audio_send_task, 0,
868
+ MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT) != pdPASS))
869
+ throw std::runtime_error("RTC task allocation failed");
870
+ ESP_LOGI(kTag, "transport tasks started");
195
871
  return state;
872
+ } catch (const std::exception& error) {
873
+ ESP_LOGE(kTag, "transport initialization failed: %s (internal free=%u largest=%u)", error.what(),
874
+ static_cast<unsigned>(heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)),
875
+ static_cast<unsigned>(heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)));
876
+ releaseTransport(state); throw;
877
+ } catch (...) { releaseTransport(state); throw; }
196
878
  }
197
879
 
198
- void destroyPeerLocked(EspPeerState *state) {
880
+ EspPeerState *ensurePeer(NativeRtcPeerHandle id, bool answer = false) {
881
+ return ensurePeer(findPeer(id), answer);
882
+ }
883
+
884
+ void releaseTransport(EspPeerState *state) {
199
885
  state->open = false;
886
+ if (state->transport_wake) xSemaphoreGive(state->transport_wake);
887
+ // Both tasks can still be using the peer and its SDP semaphore. Join them
888
+ // before closing the transport or freeing state (the old code freed first).
889
+ const auto join = [](TaskHandle_t& task, SemaphoreHandle_t done) {
890
+ if (!task) return;
891
+ ESP_LOGI(kTag, "joining %s", pcTaskGetName(task));
892
+ while (xSemaphoreTake(done, pdMS_TO_TICKS(2000)) != pdTRUE)
893
+ ESP_LOGW(kTag, "waiting for %s state=%d", pcTaskGetName(task), static_cast<int>(eTaskGetState(task)));
894
+ // The completion signal precedes suspension. Do not free a stack while
895
+ // its task is still executing on the other core.
896
+ while (eTaskGetState(task) != eSuspended) vTaskDelay(1);
897
+ ESP_LOGI(kTag, "joined %s", pcTaskGetName(task));
898
+ vTaskDeleteWithCaps(task);
899
+ task = nullptr;
900
+ };
901
+ join(state->main_loop_task, state->main_done);
902
+ join(state->audio_send_task, state->audio_done);
903
+ join(state->audio_receive_task, state->audio_receive_done);
904
+ if (state->audio_receive_done) vSemaphoreDelete(state->audio_receive_done);
905
+ state->audio_receive_done = nullptr;
906
+ state->received_audio_queue.clear();
907
+ #if GEA_RTC_HAS_VIDEO
908
+ join(state->video_task, state->video_done);
909
+ if (state->video_done) vSemaphoreDelete(state->video_done);
910
+ state->video_done = nullptr;
911
+ state->video_frames.clear();
912
+ #endif
200
913
  if (state->handle) {
914
+ ESP_LOGI(kTag, "closing peer transport");
201
915
  esp_peer_close(state->handle);
916
+ ESP_LOGI(kTag, "closed peer transport");
202
917
  state->handle = nullptr;
203
918
  }
204
919
  if (state->sdp_ready) {
205
920
  vSemaphoreDelete(state->sdp_ready);
206
921
  state->sdp_ready = nullptr;
207
922
  }
208
- // Tasks will exit on the next loop iteration once state->open is false.
209
- delete state;
923
+ if (state->main_done) vSemaphoreDelete(state->main_done);
924
+ // esp_peer_close joins ICE callbacks before this semaphore is freed.
925
+ if (state->transport_wake) vSemaphoreDelete(state->transport_wake);
926
+ state->transport_wake = nullptr;
927
+ state->packet_wake = false;
928
+ if (state->audio_done) vSemaphoreDelete(state->audio_done);
929
+ state->main_done = nullptr; state->audio_done = nullptr;
930
+ if (state->remote_stream) gea::host::media::destroy_stream(state->remote_stream);
931
+ if (state->remote_video_stream) media::destroy_stream(state->remote_video_stream);
932
+ state->remote_video_stream = 0; state->remote_video_track = 0;
933
+ state->remote_stream = 0; state->remote_track = 0;
934
+ state->audio.reset(); state->servers.clear();
210
935
  }
211
936
 
212
937
  } // namespace
213
938
 
214
- NativeRtcPeerHandle platform_create(const std::string &) {
215
- return 0;
939
+ void platform_create(NativeRtcPeerHandle id, const RTCConfiguration& config) {
940
+ ensureControlTask();
941
+ auto state = std::make_unique<EspPeerState>();
942
+ state->our_handle = id; state->config = config;
943
+ std::lock_guard<std::mutex> lock(espPeerMutex());
944
+ espPeerTable()[id] = state.release();
216
945
  }
217
946
 
218
947
  void platform_destroy(NativeRtcPeerHandle our_handle) {
219
- std::lock_guard<std::mutex> lock(espPeerMutex());
220
- auto it = espPeerTable().find(our_handle);
221
- if (it == espPeerTable().end()) return;
222
- auto *state = it->second;
223
- espPeerTable().erase(it);
224
- destroyPeerLocked(state);
948
+ EspPeerState* state;
949
+ {
950
+ std::lock_guard<std::mutex> lock(espPeerMutex());
951
+ const auto it = espPeerTable().find(our_handle);
952
+ if (it == espPeerTable().end()) return;
953
+ state = it->second;
954
+ state->closing = true;
955
+ state->open = false;
956
+ // Enqueue before erasing so a failed allocation leaves ownership intact.
957
+ queueControl([state] { releaseTransport(state); delete state; });
958
+ espPeerTable().erase(it);
959
+ }
960
+ }
961
+
962
+ void platform_request_description(NativeRtcPeerHandle id, bool offer, std::shared_ptr<DescriptionResult> result) {
963
+ auto* state = findPeer(id);
964
+ if (!state) throw std::runtime_error("InvalidStateError: peer closed");
965
+ queueControl([state, offer, result] {
966
+ try {
967
+ ensurePeer(state, !offer);
968
+ if (offer && esp_peer_new_connection(state->handle) != 0)
969
+ throw std::runtime_error("OperationError: ICE offer failed");
970
+ const auto deadline = esp_timer_get_time() + 5000000;
971
+ while (!state->closing && esp_timer_get_time() < deadline) {
972
+ if (xSemaphoreTake(state->sdp_ready, pdMS_TO_TICKS(20)) == pdTRUE) {
973
+ std::lock_guard<std::mutex> lock(state->sdp_mutex);
974
+ result->sdp = state->pending_sdp;
975
+ break;
976
+ }
977
+ }
978
+ if (state->closing) result->error = "AbortError: peer closed during SDP creation";
979
+ else if (result->sdp.empty()) result->error = "OperationError: SDP creation timed out";
980
+ } catch (const std::exception& error) { result->error = error.what(); }
981
+ catch (...) { result->error = "OperationError: SDP creation failed"; }
982
+ result->ready.store(true, std::memory_order_release);
983
+ });
225
984
  }
226
985
 
227
986
  void platform_add_track(NativeRtcPeerHandle our_handle, NativeMediaTrackHandle track) {
228
- auto *state = ensurePeer(our_handle);
229
- if (state) state->local_track = track;
987
+ auto *state = findPeer(our_handle);
988
+ if (!state) throw std::runtime_error("InvalidStateError: peer closed");
989
+ state->local_track = track;
230
990
  }
231
991
 
232
992
  std::string platform_create_offer(NativeRtcPeerHandle our_handle) {
233
993
  auto *state = ensurePeer(our_handle);
234
994
  if (!state) return std::string();
995
+ ESP_LOGI(kTag, "starting ICE offer");
235
996
  int err = esp_peer_new_connection(state->handle);
997
+ ESP_LOGI(kTag, "ICE offer returned %d", err);
236
998
  if (err != 0) {
237
999
  ESP_LOGE(kTag, "esp_peer_new_connection failed: %d", err);
238
1000
  return std::string();
@@ -243,6 +1005,7 @@ std::string platform_create_offer(NativeRtcPeerHandle our_handle) {
243
1005
  ESP_LOGE(kTag, "create_offer SDP timeout");
244
1006
  return std::string();
245
1007
  }
1008
+ std::lock_guard<std::mutex> lock(state->sdp_mutex);
246
1009
  return state->pending_sdp;
247
1010
  }
248
1011
 
@@ -254,6 +1017,7 @@ std::string platform_create_answer(NativeRtcPeerHandle our_handle) {
254
1017
  if (xSemaphoreTake(state->sdp_ready, pdMS_TO_TICKS(5000)) != pdTRUE) {
255
1018
  return std::string();
256
1019
  }
1020
+ std::lock_guard<std::mutex> lock(state->sdp_mutex);
257
1021
  return state->pending_sdp;
258
1022
  }
259
1023
 
@@ -262,14 +1026,30 @@ void platform_set_local_description(NativeRtcPeerHandle, const std::string &, co
262
1026
  // No explicit set is required.
263
1027
  }
264
1028
 
265
- void platform_set_remote_description(NativeRtcPeerHandle our_handle, const std::string &, const std::string &sdp) {
266
- auto *state = findPeer(our_handle);
1029
+ void platform_set_remote_description(NativeRtcPeerHandle our_handle, const std::string &type, const std::string &sdp) {
1030
+ #if GEA_RTC_HAS_VP8
1031
+ if (type == "offer") {
1032
+ if (auto* pending = findPeer(our_handle); pending && !pending->handle) {
1033
+ const auto offer = receive::parseOffer(sdp);
1034
+ pending->native_daily_receive = bool(offer);
1035
+ pending->vp8_video = offer && std::any_of(offer->tracks.begin(), offer->tracks.end(),
1036
+ [](const auto& track) { return track.kind == "video"; });
1037
+ }
1038
+ }
1039
+ #endif
1040
+ auto *state = ensurePeer(our_handle, type == "offer");
267
1041
  if (!state || !state->handle) return;
1042
+ for (const auto* prefix : {"a=setup:", "m=application ", "a=sctp-port:", "a=ice-lite"}) {
1043
+ for (std::size_t pos = sdp.find(prefix); pos != std::string::npos; pos = sdp.find(prefix, pos + 1)) {
1044
+ const auto end = sdp.find_first_of("\r\n", pos);
1045
+ ESP_LOGI(kTag, "remote %s", sdp.substr(pos, end - pos).c_str());
1046
+ }
1047
+ }
268
1048
  esp_peer_msg_t msg = {};
269
1049
  msg.type = ESP_PEER_MSG_TYPE_SDP;
270
1050
  msg.data = reinterpret_cast<uint8_t *>(const_cast<char *>(sdp.c_str()));
271
1051
  msg.size = static_cast<int>(sdp.size());
272
- esp_peer_send_msg(state->handle, &msg);
1052
+ if (esp_peer_send_msg(state->handle, &msg) != 0) throw std::runtime_error("OperationError: SDP/ICE update rejected");
273
1053
  }
274
1054
 
275
1055
  void platform_add_ice_candidate(NativeRtcPeerHandle our_handle, const std::string &candidate, const std::string &, int) {
@@ -279,7 +1059,49 @@ void platform_add_ice_candidate(NativeRtcPeerHandle our_handle, const std::strin
279
1059
  msg.type = ESP_PEER_MSG_TYPE_CANDIDATE;
280
1060
  msg.data = reinterpret_cast<uint8_t *>(const_cast<char *>(candidate.c_str()));
281
1061
  msg.size = static_cast<int>(candidate.size());
282
- esp_peer_send_msg(state->handle, &msg);
1062
+ if (esp_peer_send_msg(state->handle, &msg) != 0) throw std::runtime_error("OperationError: SDP/ICE update rejected");
1063
+ }
1064
+
1065
+ void platform_direction(NativeRtcPeerHandle id, const std::string& kind, const std::string& direction) {
1066
+ auto* state = findPeer(id);
1067
+ if (!state) throw std::runtime_error("InvalidStateError: peer closed");
1068
+ if (kind == "video" && direction != "inactive" && (!GEA_RTC_HAS_VIDEO || direction != "recvonly"))
1069
+ throw std::runtime_error("NotSupportedError: native video reception is unavailable");
1070
+ auto& current = kind == "video" ? state->video_direction : state->direction;
1071
+ if (state->handle && current != direction)
1072
+ throw std::runtime_error("NotSupportedError: esp_peer cannot renegotiate media direction on an open peer");
1073
+ current = direction;
1074
+ }
1075
+ void platform_create_channel(NativeRtcPeerHandle id, const std::string& label, const RTCDataChannelInit& config) {
1076
+ auto* state = findPeer(id);
1077
+ if (!state) throw std::runtime_error("InvalidStateError: peer closed");
1078
+ std::lock_guard<std::mutex> lock(state->channels_mutex);
1079
+ state->pending_channels.emplace_back(label, config);
1080
+ }
1081
+ void platform_send_data(NativeRtcPeerHandle id, uint16_t stream, const uint8_t* bytes, size_t size, bool text) {
1082
+ auto* state = findPeer(id);
1083
+ if (!state || !state->handle || !state->connected) throw std::runtime_error("InvalidStateError: peer not connected");
1084
+ if (size > INT_MAX) throw std::invalid_argument("Data channel message too large");
1085
+ esp_peer_data_frame_t frame{};
1086
+ frame.stream_id = stream; frame.data = const_cast<uint8_t*>(bytes); frame.size = size;
1087
+ frame.type = text ? ESP_PEER_DATA_CHANNEL_STRING : ESP_PEER_DATA_CHANNEL_DATA;
1088
+ if (esp_peer_send_data(state->handle, &frame) != 0) throw std::runtime_error("OperationError: data channel send failed");
1089
+ }
1090
+ void platform_close_channel(NativeRtcPeerHandle id, const std::string& label) {
1091
+ auto* state = findPeer(id);
1092
+ if (!state) return;
1093
+ { std::lock_guard<std::mutex> lock(state->channels_mutex);
1094
+ for (auto it = state->pending_channels.begin(); it != state->pending_channels.end(); ++it) {
1095
+ if (it->first == label) { state->pending_channels.erase(it); return; }
1096
+ }
1097
+ }
1098
+ if (state->handle) {
1099
+ // esp_peer forwards SCTP's RE_CONFIG write result: a positive byte count
1100
+ // is success too. Treating it as failure strands JS cleanup in Closing.
1101
+ const int result = esp_peer_close_data_channel(state->handle, label.c_str());
1102
+ ESP_LOGI(kTag, "data channel close result=%d", result);
1103
+ if (result < 0) throw std::runtime_error("OperationError: data channel close failed");
1104
+ }
283
1105
  }
284
1106
 
285
1107
  void platform_close(NativeRtcPeerHandle our_handle) {