@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.cpp CHANGED
@@ -2,31 +2,85 @@
2
2
  #include "host/rtc.h"
3
3
 
4
4
  #include <atomic>
5
+ #include <algorithm>
6
+ #include <cmath>
7
+ #include <stdexcept>
5
8
  #include <cstdint>
6
9
  #include <mutex>
7
10
  #include <string>
11
+ #include <sstream>
8
12
  #include <unordered_map>
9
13
  #include <utility>
10
14
  #include <vector>
15
+ #ifdef ESP_PLATFORM
16
+ #include "esp_timer.h"
17
+ #include "esp_log.h"
18
+ #endif
11
19
 
12
20
  namespace gea::host {
13
21
 
22
+ namespace rtc {
23
+ struct PeerLifetime {
24
+ explicit PeerLifetime(uint32_t id) : handle(id) {}
25
+ ~PeerLifetime() { destroy_handle(handle); }
26
+ uint32_t handle;
27
+ };
28
+ }
29
+
14
30
  namespace {
15
31
 
32
+ struct PendingDescription {
33
+ NativeRtcPeerHandle peer;
34
+ std::shared_ptr<rtc::DescriptionResult> result;
35
+ rtc::DescriptionCallback callback;
36
+ std::shared_ptr<rtc::PeerLifetime> owner;
37
+ };
38
+ // Owned and dispatched only by the UI thread. Workers publish native strings
39
+ // through DescriptionResult; they never touch a JS promise or callback.
40
+ std::vector<PendingDescription> pendingDescriptions;
41
+
16
42
  struct PeerState {
17
43
  std::string connectionState = "new";
18
44
  std::string iceConnectionState = "new";
19
45
  bool open = true;
46
+ RTCConfiguration config;
47
+ std::string signaling = "stable";
48
+ std::optional<RTCSessionDescriptionObject> local, remote;
49
+ std::vector<uint32_t> transceivers;
20
50
  };
21
51
 
22
52
  std::unordered_map<NativeRtcPeerHandle, PeerState> &peerTable() {
23
- static std::unordered_map<NativeRtcPeerHandle, PeerState> table;
24
- return table;
53
+ // Generated module globals can release their final RTC wrapper after C++
54
+ // function statics have been destroyed. Registry storage must outlive those
55
+ // wrappers; per-peer entries are still erased by destroy_handle as usual.
56
+ static auto* table = new std::unordered_map<NativeRtcPeerHandle, PeerState>();
57
+ return *table;
25
58
  }
26
59
 
27
60
  std::mutex &peerMutex() {
28
- static std::mutex m;
29
- return m;
61
+ static auto* m = new std::mutex();
62
+ return *m;
63
+ }
64
+
65
+ // Separate from peerMutex: object wrappers are also constructed while the
66
+ // state registry is locked. These registries hold only weak references.
67
+ std::mutex& lifetimeMutex() {
68
+ static auto* mutex = new std::mutex();
69
+ return *mutex;
70
+ }
71
+ using LifetimeTable = std::unordered_map<uint32_t, std::weak_ptr<rtc::PeerLifetime>>;
72
+ LifetimeTable& peerLifetimeTable() {
73
+ static auto* table = new LifetimeTable();
74
+ return *table;
75
+ }
76
+ LifetimeTable& objectLifetimeTable() {
77
+ static auto* table = new LifetimeTable();
78
+ return *table;
79
+ }
80
+ void registerObjectLifetime(uint32_t object, uint32_t peer) {
81
+ std::lock_guard<std::mutex> lock(lifetimeMutex());
82
+ const auto it = peerLifetimeTable().find(peer);
83
+ if (it != peerLifetimeTable().end()) objectLifetimeTable()[object] = it->second;
30
84
  }
31
85
 
32
86
  std::atomic<NativeRtcPeerHandle> &nextHandle() {
@@ -34,7 +88,94 @@ std::atomic<NativeRtcPeerHandle> &nextHandle() {
34
88
  return id;
35
89
  }
36
90
 
37
- enum class EventKind { IceCandidate, Track, ConnectionStateChange, IceConnectionStateChange };
91
+ struct TransceiverState {
92
+ uint32_t peer = 0;
93
+ NativeMediaTrackHandle local = 0, remote = 0;
94
+ std::string direction = "sendrecv";
95
+ std::optional<std::string> mid, current;
96
+ bool stopped = false;
97
+ std::vector<MediaStream> streams;
98
+ std::string kind = "audio";
99
+ };
100
+ struct ChannelState {
101
+ uint32_t peer = 0;
102
+ std::string label, state = "connecting", binary_type = "arraybuffer";
103
+ RTCDataChannelInit config;
104
+ std::optional<uint16_t> stream;
105
+ double buffered = 0, low_threshold = 0;
106
+ };
107
+ auto& transceiverTable() {
108
+ static auto* table = new std::unordered_map<uint32_t, TransceiverState>();
109
+ return *table;
110
+ }
111
+ auto& channelTable() {
112
+ static auto* table = new std::unordered_map<uint32_t, ChannelState>();
113
+ return *table;
114
+ }
115
+ auto& channelCallbackTable() {
116
+ static auto* table = new std::unordered_map<uint32_t, rtc::DataChannelCallbacks>();
117
+ return *table;
118
+ }
119
+ std::atomic<uint32_t> nextObject{1};
120
+ void requireDirection(const std::string& direction) {
121
+ if (direction != "sendrecv" && direction != "sendonly" && direction != "recvonly" && direction != "inactive")
122
+ throw std::invalid_argument("Invalid RTCRtpTransceiver direction");
123
+ }
124
+ struct MediaSection {
125
+ std::string mid, direction = "sendrecv";
126
+ bool found = false, rejected = false;
127
+ };
128
+ MediaSection mediaSection(const std::string& sdp, const std::string& kind) {
129
+ MediaSection section;
130
+ bool inSection = false, inMedia = false;
131
+ std::string sessionDirection = "sendrecv", line;
132
+ std::istringstream lines(sdp);
133
+ while (std::getline(lines, line)) {
134
+ if (!line.empty() && line.back() == '\r') line.pop_back();
135
+ if (line.rfind("m=", 0) == 0) {
136
+ if (inSection) break;
137
+ inMedia = true;
138
+ inSection = line.rfind("m=" + kind + " ", 0) == 0;
139
+ if (inSection) { section.found = true; section.rejected = line.rfind("m=" + kind + " 0 ", 0) == 0; section.direction = sessionDirection; }
140
+ } else if (line == "a=sendrecv" || line == "a=recvonly" || line == "a=sendonly" || line == "a=inactive") {
141
+ if (!inMedia) sessionDirection = line.substr(2);
142
+ if (inSection) section.direction = line.substr(2);
143
+ } else if (inSection && line.rfind("a=mid:", 0) == 0) section.mid = line.substr(6);
144
+ }
145
+ return section;
146
+ }
147
+ // Called with peerMutex held, only when an answer has actually been accepted.
148
+ void applyNegotiatedMedia(PeerState& peer) {
149
+ if (peer.signaling != "stable" || !peer.local || !peer.remote) return;
150
+ for (auto id : peer.transceivers) {
151
+ auto& tr = transceiverTable().at(id);
152
+ if (tr.stopped) continue;
153
+ const auto local = mediaSection(peer.local->sdp(), tr.kind), remote = mediaSection(peer.remote->sdp(), tr.kind);
154
+ if (!local.found || !remote.found) continue;
155
+ const bool send = !local.rejected && !remote.rejected && (local.direction == "sendrecv" || local.direction == "sendonly") && (remote.direction == "sendrecv" || remote.direction == "recvonly");
156
+ const bool receive = !local.rejected && !remote.rejected && (local.direction == "sendrecv" || local.direction == "recvonly") && (remote.direction == "sendrecv" || remote.direction == "sendonly");
157
+ tr.mid = local.mid;
158
+ tr.current = send ? (receive ? "sendrecv" : "sendonly") : (receive ? "recvonly" : "inactive");
159
+ }
160
+ }
161
+ PeerState& requirePeer(uint32_t id) {
162
+ auto it = peerTable().find(id);
163
+ if (it == peerTable().end() || !it->second.open) throw std::runtime_error("InvalidStateError: peer is closed");
164
+ return it->second;
165
+ }
166
+ TransceiverState& requireTransceiver(uint32_t id) {
167
+ auto it = transceiverTable().find(id);
168
+ if (it == transceiverTable().end()) throw std::runtime_error("InvalidStateError: transceiver is gone");
169
+ requirePeer(it->second.peer);
170
+ return it->second;
171
+ }
172
+ ChannelState& requireChannel(uint32_t id) {
173
+ auto it = channelTable().find(id);
174
+ if (it == channelTable().end()) throw std::runtime_error("InvalidStateError: data channel is gone");
175
+ return it->second;
176
+ }
177
+
178
+ enum class EventKind { IceCandidate, Track, ConnectionStateChange, IceConnectionStateChange, Signaling, Negotiation, DataChannel, ChannelOpen, ChannelClose, ChannelMessage, ChannelLow };
38
179
 
39
180
  struct PendingEvent {
40
181
  NativeRtcPeerHandle handle = 0;
@@ -43,11 +184,18 @@ struct PendingEvent {
43
184
  std::string sdp_mid;
44
185
  int sdp_mline_index = 0;
45
186
  NativeMediaTrackHandle track = 0;
187
+ uint32_t channel = 0;
188
+ std::vector<uint8_t> bytes;
189
+ bool text = false;
190
+ RTCTrackEvent track_event;
191
+ #ifdef ESP_PLATFORM
192
+ int64_t queued_us = 0;
193
+ #endif
46
194
  };
47
195
 
48
196
  std::mutex &queueMutex() {
49
- static std::mutex m;
50
- return m;
197
+ static auto* m = new std::mutex();
198
+ return *m;
51
199
  }
52
200
 
53
201
  std::vector<PendingEvent> &eventQueue() {
@@ -56,6 +204,9 @@ std::vector<PendingEvent> &eventQueue() {
56
204
  }
57
205
 
58
206
  void enqueue_internal(PendingEvent ev) {
207
+ #ifdef ESP_PLATFORM
208
+ ev.queued_us = esp_timer_get_time();
209
+ #endif
59
210
  std::lock_guard<std::mutex> lock(queueMutex());
60
211
  eventQueue().push_back(std::move(ev));
61
212
  }
@@ -65,12 +216,17 @@ void enqueue_internal(PendingEvent ev) {
65
216
  namespace rtc {
66
217
 
67
218
  std::unordered_map<NativeRtcPeerHandle, CallbackTable> &callbackTable() {
68
- static std::unordered_map<NativeRtcPeerHandle, CallbackTable> table;
69
- return table;
219
+ static auto* table = new std::unordered_map<NativeRtcPeerHandle, CallbackTable>();
220
+ return *table;
70
221
  }
71
222
 
72
223
  #if defined(ESP_PLATFORM) && !defined(GEA_EMBEDDED_WIFI_DISABLED)
73
- NativeRtcPeerHandle platform_create(const std::string &);
224
+ void platform_request_description(NativeRtcPeerHandle, bool, std::shared_ptr<DescriptionResult>);
225
+ void platform_create(NativeRtcPeerHandle, const RTCConfiguration &);
226
+ void platform_direction(NativeRtcPeerHandle, const std::string&, const std::string&);
227
+ void platform_create_channel(NativeRtcPeerHandle, const std::string&, const RTCDataChannelInit&);
228
+ void platform_send_data(NativeRtcPeerHandle, uint16_t, const uint8_t*, size_t, bool);
229
+ void platform_close_channel(NativeRtcPeerHandle, const std::string&);
74
230
  void platform_destroy(NativeRtcPeerHandle);
75
231
  void platform_add_track(NativeRtcPeerHandle, NativeMediaTrackHandle);
76
232
  std::string platform_create_offer(NativeRtcPeerHandle);
@@ -80,7 +236,11 @@ void platform_set_remote_description(NativeRtcPeerHandle, const std::string &, c
80
236
  void platform_add_ice_candidate(NativeRtcPeerHandle, const std::string &, const std::string &, int);
81
237
  void platform_close(NativeRtcPeerHandle);
82
238
  #else
83
- __attribute__((weak)) NativeRtcPeerHandle platform_create(const std::string &) { return 0; }
239
+ __attribute__((weak)) void platform_create(NativeRtcPeerHandle, const RTCConfiguration &) {}
240
+ __attribute__((weak)) void platform_direction(NativeRtcPeerHandle, const std::string&, const std::string&) {}
241
+ __attribute__((weak)) void platform_create_channel(NativeRtcPeerHandle, const std::string&, const RTCDataChannelInit&) { throw std::runtime_error("NotSupportedError: no data channel backend"); }
242
+ __attribute__((weak)) void platform_send_data(NativeRtcPeerHandle, uint16_t, const uint8_t*, size_t, bool) { throw std::runtime_error("NotSupportedError: no data channel backend"); }
243
+ __attribute__((weak)) void platform_close_channel(NativeRtcPeerHandle, const std::string&) {}
84
244
  __attribute__((weak)) void platform_destroy(NativeRtcPeerHandle) {}
85
245
  __attribute__((weak)) void platform_add_track(NativeRtcPeerHandle, NativeMediaTrackHandle) {}
86
246
  __attribute__((weak)) std::string platform_create_offer(NativeRtcPeerHandle) { return "v=0\r\no=- 0 0 IN IP4 0.0.0.0\r\n"; }
@@ -89,51 +249,178 @@ __attribute__((weak)) void platform_set_local_description(NativeRtcPeerHandle, c
89
249
  __attribute__((weak)) void platform_set_remote_description(NativeRtcPeerHandle, const std::string &, const std::string &) {}
90
250
  __attribute__((weak)) void platform_add_ice_candidate(NativeRtcPeerHandle, const std::string &, const std::string &, int) {}
91
251
  __attribute__((weak)) void platform_close(NativeRtcPeerHandle) {}
252
+ __attribute__((weak)) void platform_request_description(NativeRtcPeerHandle id, bool offer, std::shared_ptr<DescriptionResult> result) {
253
+ try { result->sdp = offer ? platform_create_offer(id) : platform_create_answer(id); }
254
+ catch (const std::exception& error) { result->error = error.what(); }
255
+ result->ready.store(true, std::memory_order_release);
256
+ }
257
+
92
258
  #endif
93
259
 
94
- NativeRtcPeerHandle create_handle() {
95
- return create_handle_with_config(std::string());
260
+ NativeRtcPeerHandle create_handle() { return create_handle(RTCConfiguration{}); }
261
+ std::shared_ptr<PeerLifetime> retain_peer(uint32_t id) {
262
+ if (!id) return {};
263
+ std::lock_guard<std::mutex> lock(lifetimeMutex());
264
+ auto& weak = peerLifetimeTable()[id];
265
+ auto owner = weak.lock();
266
+ if (!owner) { owner = std::make_shared<PeerLifetime>(id); weak = owner; }
267
+ return owner;
96
268
  }
97
-
98
- NativeRtcPeerHandle create_handle_with_config(const std::string &ice_servers_json) {
269
+ std::shared_ptr<PeerLifetime> retain_object(uint32_t id) {
270
+ std::lock_guard<std::mutex> lock(lifetimeMutex());
271
+ const auto it = objectLifetimeTable().find(id);
272
+ return it == objectLifetimeTable().end() ? nullptr : it->second.lock();
273
+ }
274
+ NativeRtcPeerHandle create_handle_with_config(const std::string &json) {
275
+ if (!json.empty()) throw std::invalid_argument("Use typed RTCConfiguration; JSON ICE configuration is not supported");
276
+ return create_handle();
277
+ }
278
+ NativeRtcPeerHandle create_handle(const RTCConfiguration& config) {
279
+ if (config.iceTransportPolicy != "all" && config.iceTransportPolicy != "relay")
280
+ throw std::invalid_argument("Invalid ICE transport policy");
99
281
  auto handle = nextHandle()++;
100
- {
101
- std::lock_guard<std::mutex> lock(peerMutex());
102
- peerTable()[handle] = PeerState{};
103
- }
104
- platform_create(ice_servers_json);
282
+ { std::lock_guard<std::mutex> lock(peerMutex()); peerTable()[handle].config = config; }
283
+ try { platform_create(handle, config); }
284
+ catch (...) { std::lock_guard<std::mutex> lock(peerMutex()); peerTable().erase(handle); throw; }
105
285
  return handle;
106
286
  }
107
-
287
+ RTCConfiguration configuration(uint32_t handle) {
288
+ std::lock_guard<std::mutex> lock(peerMutex());
289
+ return requirePeer(handle).config;
290
+ }
108
291
  void destroy_handle(NativeRtcPeerHandle handle) {
109
292
  platform_destroy(handle);
293
+ // Destroy callback captures AFTER releasing registry locks: a callback may
294
+ // own the final peer/channel wrapper and reenter this cleanup.
295
+ CallbackTable discardedPeer;
296
+ std::vector<DataChannelCallbacks> discardedChannels;
297
+ {
110
298
  std::lock_guard<std::mutex> lock(peerMutex());
299
+ std::lock_guard<std::mutex> owners(lifetimeMutex());
300
+ for (auto it = transceiverTable().begin(); it != transceiverTable().end();) {
301
+ if (it->second.peer == handle) {
302
+ objectLifetimeTable().erase(it->first);
303
+ it = transceiverTable().erase(it);
304
+ } else ++it;
305
+ }
306
+ for (auto it = channelTable().begin(); it != channelTable().end();) {
307
+ if (it->second.peer == handle) {
308
+ auto cb = channelCallbackTable().find(it->first);
309
+ if (cb != channelCallbackTable().end()) {
310
+ discardedChannels.push_back(std::move(cb->second)); channelCallbackTable().erase(cb);
311
+ }
312
+ objectLifetimeTable().erase(it->first);
313
+ it = channelTable().erase(it);
314
+ } else ++it;
315
+ }
111
316
  peerTable().erase(handle);
112
- callbackTable().erase(handle);
317
+ auto cb = callbackTable().find(handle);
318
+ if (cb != callbackTable().end()) {
319
+ discardedPeer = std::move(cb->second); callbackTable().erase(cb);
320
+ }
321
+ peerLifetimeTable().erase(handle);
322
+ }
113
323
  }
114
324
 
115
325
  void runCallbacks() {
326
+ std::vector<PendingDescription> completed;
327
+ for (auto it = pendingDescriptions.begin(); it != pendingDescriptions.end();) {
328
+ bool closed;
329
+ {
330
+ std::lock_guard<std::mutex> lock(peerMutex());
331
+ const auto peer = peerTable().find(it->peer);
332
+ closed = peer == peerTable().end() || !peer->second.open;
333
+ }
334
+ if (closed) {
335
+ // Do not mutate the worker's result while it is still publishing.
336
+ auto cancelled = std::make_shared<DescriptionResult>();
337
+ cancelled->error = "AbortError: peer closed during SDP creation";
338
+ it->result = std::move(cancelled);
339
+ }
340
+ if (closed || it->result->ready.load(std::memory_order_acquire)) {
341
+ completed.push_back(std::move(*it));
342
+ it = pendingDescriptions.erase(it);
343
+ } else ++it;
344
+ }
345
+ for (auto& operation : completed) {
346
+ if (operation.result->sdp.empty() && operation.result->error.empty())
347
+ operation.result->error = "OperationError: SDP creation returned no description";
348
+ operation.callback(operation.result->sdp, operation.result->error);
349
+ }
350
+
116
351
  std::vector<PendingEvent> drained;
117
352
  {
118
353
  std::lock_guard<std::mutex> lock(queueMutex());
119
354
  drained.swap(eventQueue());
120
355
  }
356
+ #ifdef ESP_PLATFORM
357
+ if (!drained.empty()) {
358
+ const auto delay_us = esp_timer_get_time() - drained.front().queued_us;
359
+ if (delay_us > 100000)
360
+ ESP_LOGW("gea::host::rtc", "event dispatch delayed: oldest_ms=%lld events=%u",
361
+ static_cast<long long>(delay_us / 1000), unsigned(drained.size()));
362
+ }
363
+ #endif
121
364
  for (const auto &ev : drained) {
365
+ // A handler may close/destroy the peer. Copy callbacks before invoking
366
+ // user code; never keep an unordered_map iterator alive across a callback.
367
+ if (ev.channel && ev.kind != EventKind::DataChannel) {
368
+ auto it = channelCallbackTable().find(ev.channel);
369
+ if (it == channelCallbackTable().end()) continue;
370
+ auto cb = it->second;
371
+ if (ev.kind == EventKind::ChannelOpen && cb.on_open) cb.on_open();
372
+ if (ev.kind == EventKind::ChannelClose && cb.on_close) cb.on_close();
373
+ if (ev.kind == EventKind::ChannelLow && cb.on_buffered_amount_low) cb.on_buffered_amount_low();
374
+ if (ev.kind == EventKind::ChannelMessage && cb.on_message) cb.on_message(ev.bytes, ev.text);
375
+ continue;
376
+ }
122
377
  auto it = callbackTable().find(ev.handle);
123
378
  if (it == callbackTable().end()) continue;
379
+ auto cb = it->second;
380
+ #ifdef ESP_PLATFORM
381
+ ESP_LOGI("gea::host::rtc", "dispatch begin peer=%u kind=%u", unsigned(ev.handle), unsigned(ev.kind));
382
+ #endif
124
383
  switch (ev.kind) {
125
- case EventKind::IceCandidate:
126
- if (it->second.on_ice_candidate) it->second.on_ice_candidate(ev.candidate, ev.sdp_mid, ev.sdp_mline_index);
127
- break;
128
- case EventKind::Track:
129
- if (it->second.on_track) it->second.on_track(ev.track);
130
- break;
131
- case EventKind::ConnectionStateChange:
132
- if (it->second.on_connection_state_change) it->second.on_connection_state_change();
133
- break;
134
- case EventKind::IceConnectionStateChange:
135
- if (it->second.on_ice_connection_state_change) it->second.on_ice_connection_state_change();
136
- break;
384
+ case EventKind::IceCandidate: if (cb.on_ice_candidate) cb.on_ice_candidate(ev.candidate, ev.sdp_mid, ev.sdp_mline_index); break;
385
+ case EventKind::Track: if (cb.on_track) cb.on_track(ev.track_event); break;
386
+ case EventKind::ConnectionStateChange: if (cb.on_connection_state_change) cb.on_connection_state_change(); break;
387
+ case EventKind::IceConnectionStateChange: if (cb.on_ice_connection_state_change) cb.on_ice_connection_state_change(); break;
388
+ case EventKind::Signaling: if (cb.on_signaling_state_change) cb.on_signaling_state_change(); break;
389
+ case EventKind::Negotiation: if (cb.on_negotiation_needed) cb.on_negotiation_needed(); break;
390
+ case EventKind::DataChannel: if (cb.on_data_channel) cb.on_data_channel(RTCDataChannel(ev.channel)); break;
391
+ default: break;
392
+ }
393
+ #ifdef ESP_PLATFORM
394
+ ESP_LOGI("gea::host::rtc", "dispatch end peer=%u kind=%u", unsigned(ev.handle), unsigned(ev.kind));
395
+ #endif
396
+ }
397
+ // close() terminates transport immediately. Deliver its queued close events
398
+ // first, then release subscriptions that can retain the peer through a JS
399
+ // closure. Native state stays available while any peer/RTP/channel object
400
+ // is still referenced; the last wrapper releases that state automatically.
401
+ std::vector<CallbackTable> closedPeers;
402
+ std::vector<DataChannelCallbacks> closedChannels;
403
+ std::vector<uint32_t> pendingPeers;
404
+ {
405
+ std::lock_guard<std::mutex> lock(queueMutex());
406
+ for (const auto& event : eventQueue()) pendingPeers.push_back(event.handle);
407
+ }
408
+ {
409
+ std::lock_guard<std::mutex> lock(peerMutex());
410
+ for (const auto& [id, peer] : peerTable()) if (!peer.open) {
411
+ // A handler may have closed its own peer during this dispatch. Its
412
+ // resulting events are in the next batch and must keep their callbacks.
413
+ if (std::find(pendingPeers.begin(), pendingPeers.end(), id) != pendingPeers.end()) continue;
414
+ auto cb = callbackTable().find(id);
415
+ if (cb != callbackTable().end()) {
416
+ closedPeers.push_back(std::move(cb->second)); callbackTable().erase(cb);
417
+ }
418
+ for (const auto& [channelId, channel] : channelTable()) if (channel.peer == id) {
419
+ auto ch = channelCallbackTable().find(channelId);
420
+ if (ch != channelCallbackTable().end()) {
421
+ closedChannels.push_back(std::move(ch->second)); channelCallbackTable().erase(ch);
422
+ }
423
+ }
137
424
  }
138
425
  }
139
426
  }
@@ -141,14 +428,41 @@ void runCallbacks() {
141
428
  void enqueue_ice_candidate(NativeRtcPeerHandle h, const std::string &candidate, const std::string &sdp_mid, int idx) {
142
429
  enqueue_internal(PendingEvent{h, EventKind::IceCandidate, candidate, sdp_mid, idx, 0});
143
430
  }
144
- void enqueue_track(NativeRtcPeerHandle h, NativeMediaTrackHandle t) {
145
- enqueue_internal(PendingEvent{h, EventKind::Track, {}, {}, 0, t});
431
+ void enqueue_track(NativeRtcPeerHandle h, NativeMediaTrackHandle t, std::vector<MediaStream> streams) {
432
+ const auto kind = MediaStreamTrack(t).kind();
433
+ if (kind != "audio" && kind != "video") throw std::invalid_argument("Unknown received media track kind");
434
+ uint32_t transceiver = 0;
435
+ {
436
+ std::lock_guard<std::mutex> lock(peerMutex());
437
+ auto peer = peerTable().find(h);
438
+ if (peer == peerTable().end() || !peer->second.open) return;
439
+ for (const auto id : peer->second.transceivers) {
440
+ const auto& candidate = transceiverTable().at(id);
441
+ if (!candidate.stopped && candidate.kind == kind) {
442
+ transceiver = id;
443
+ break;
444
+ }
445
+ }
446
+ if (!transceiver) {
447
+ const auto id = nextObject++;
448
+ transceiverTable()[id] = TransceiverState{h, 0, t, "recvonly"};
449
+ transceiverTable()[id].kind = kind;
450
+ registerObjectLifetime(id, h);
451
+ peer->second.transceivers.push_back(id);
452
+ transceiver = id;
453
+ } else transceiverTable().at(transceiver).remote = t;
454
+ applyNegotiatedMedia(peer->second);
455
+ }
456
+ PendingEvent event{h, EventKind::Track, {}, {}, 0, t};
457
+ event.track_event = RTCTrackEvent(MediaStreamTrack(t), RTCRtpTransceiver(transceiver), std::move(streams));
458
+ enqueue_internal(std::move(event));
146
459
  }
147
460
  void enqueue_connection_state_change(NativeRtcPeerHandle h, const std::string &new_state) {
148
461
  {
149
462
  std::lock_guard<std::mutex> lock(peerMutex());
150
463
  auto it = peerTable().find(h);
151
- if (it != peerTable().end()) it->second.connectionState = new_state;
464
+ if (it == peerTable().end() || !it->second.open) return;
465
+ it->second.connectionState = new_state;
152
466
  }
153
467
  enqueue_internal(PendingEvent{h, EventKind::ConnectionStateChange, {}, {}, 0, 0});
154
468
  }
@@ -156,7 +470,8 @@ void enqueue_ice_connection_state_change(NativeRtcPeerHandle h, const std::strin
156
470
  {
157
471
  std::lock_guard<std::mutex> lock(peerMutex());
158
472
  auto it = peerTable().find(h);
159
- if (it != peerTable().end()) it->second.iceConnectionState = new_state;
473
+ if (it == peerTable().end() || !it->second.open) return;
474
+ it->second.iceConnectionState = new_state;
160
475
  }
161
476
  enqueue_internal(PendingEvent{h, EventKind::IceConnectionStateChange, {}, {}, 0, 0});
162
477
  }
@@ -175,24 +490,109 @@ std::string RTCPeerConnection::iceConnectionState() const {
175
490
  return it == peerTable().end() ? std::string("closed") : it->second.iceConnectionState;
176
491
  }
177
492
 
178
- void RTCPeerConnection::addTrack(MediaStreamTrack track, MediaStream) const {
179
- rtc::platform_add_track(nativeHandle, track.nativeHandle);
493
+ RTCRtpSender RTCPeerConnection::addTrack(MediaStreamTrack track, MediaStream stream) const {
494
+ return addTrack(track, stream.nativeHandle ? std::vector<MediaStream>{stream} : std::vector<MediaStream>{});
495
+ }
496
+
497
+ RTCRtpSender RTCPeerConnection::addTrack(MediaStreamTrack track, const std::vector<MediaStream>& streams) const {
498
+ for (const auto stream : streams)
499
+ if (!stream.nativeHandle) throw std::invalid_argument("TypeError: null MediaStream");
500
+ {
501
+ std::lock_guard<std::mutex> lock(peerMutex());
502
+ const auto& peer = requirePeer(nativeHandle);
503
+ for (const auto id : peer.transceivers) {
504
+ const auto& sender = transceiverTable().at(id);
505
+ if (!sender.stopped && sender.local == track.nativeHandle)
506
+ throw std::invalid_argument("InvalidAccessError: track is already attached");
507
+ }
508
+ }
509
+ const auto sender = addTransceiver(track).sender();
510
+ std::lock_guard<std::mutex> lock(peerMutex());
511
+ auto& state = requireTransceiver(sender.nativeHandle);
512
+ for (const auto stream : streams) {
513
+ if (std::none_of(state.streams.begin(), state.streams.end(), [&](const auto& prior) { return prior.nativeHandle == stream.nativeHandle; }))
514
+ state.streams.push_back(stream);
515
+ }
516
+ return sender;
517
+ }
518
+
519
+ namespace {
520
+ std::string describeLocalStreams(uint32_t handle, const std::string& sdp) {
521
+ if (sdp.empty()) return sdp;
522
+ std::string attributes;
523
+ {
524
+ std::lock_guard<std::mutex> lock(peerMutex());
525
+ for (const auto id : requirePeer(handle).transceivers) {
526
+ const auto& sender = transceiverTable().at(id);
527
+ if (sender.stopped || !sender.local) continue;
528
+ const auto track = MediaStreamTrack(sender.local).id();
529
+ if (sender.streams.empty()) attributes += "a=msid:- " + track + "\r\n";
530
+ for (const auto stream : sender.streams) attributes += "a=msid:" + stream.id() + " " + track + "\r\n";
531
+ }
532
+ }
533
+ if (attributes.empty()) return sdp;
534
+ std::istringstream input(sdp);
535
+ std::string output, line;
536
+ bool audio = false, media = false;
537
+ while (std::getline(input, line)) {
538
+ if (!line.empty() && line.back() == '\r') line.pop_back();
539
+ if (line.rfind("a=msid-semantic:", 0) == 0) continue;
540
+ if (!media && line.rfind("m=", 0) == 0) {
541
+ output += "a=msid-semantic: WMS *\r\n";
542
+ media = true;
543
+ }
544
+ if (line.rfind("m=", 0) == 0) audio = line.rfind("m=audio ", 0) == 0;
545
+ if (audio && (line.rfind("a=msid:", 0) == 0 || (line.rfind("a=ssrc:", 0) == 0 && line.find(" msid:") != std::string::npos))) continue;
546
+ output += line + "\r\n";
547
+ if (line.rfind("m=audio ", 0) == 0) output += attributes;
548
+ }
549
+ return output;
550
+ }
551
+ }
552
+
553
+ void RTCPeerConnection::requestDescription(bool offer, rtc::DescriptionCallback callback) const {
554
+ { std::lock_guard<std::mutex> lock(peerMutex()); requirePeer(nativeHandle); }
555
+ auto result = std::make_shared<rtc::DescriptionResult>();
556
+ rtc::platform_request_description(nativeHandle, offer, result);
557
+ pendingDescriptions.push_back({nativeHandle, result,
558
+ [handle = nativeHandle, callback = std::move(callback)](const std::string& sdp, const std::string& error) {
559
+ bool closed;
560
+ {
561
+ std::lock_guard<std::mutex> lock(peerMutex());
562
+ const auto peer = peerTable().find(handle);
563
+ closed = peer == peerTable().end() || !peer->second.open;
564
+ }
565
+ if (closed) callback({}, "AbortError: peer closed during SDP creation");
566
+ else callback(error.empty() ? describeLocalStreams(handle, sdp) : std::string{}, error);
567
+ }, lifetime_});
180
568
  }
181
569
 
182
570
  std::string RTCPeerConnection::createOffer() const {
183
- return rtc::platform_create_offer(nativeHandle);
571
+ return describeLocalStreams(nativeHandle, rtc::platform_create_offer(nativeHandle));
184
572
  }
185
573
 
186
574
  std::string RTCPeerConnection::createAnswer() const {
187
- return rtc::platform_create_answer(nativeHandle);
575
+ return describeLocalStreams(nativeHandle, rtc::platform_create_answer(nativeHandle));
188
576
  }
189
577
 
190
578
  void RTCPeerConnection::setLocalDescription(const std::string &sdp_type, const std::string &sdp) const {
579
+ { std::lock_guard<std::mutex> lock(peerMutex()); requirePeer(nativeHandle); }
580
+ if (sdp_type != "offer" && sdp_type != "answer") throw std::invalid_argument("NotSupportedError: SDP type");
191
581
  rtc::platform_set_local_description(nativeHandle, sdp_type, sdp);
582
+ { std::lock_guard<std::mutex> lock(peerMutex()); auto& p = requirePeer(nativeHandle);
583
+ p.local = RTCSessionDescriptionObject(RTCSessionDescription{sdp_type, sdp}); p.signaling = sdp_type == "offer" ? "have-local-offer" : "stable";
584
+ applyNegotiatedMedia(p); }
585
+ enqueue_internal(PendingEvent{nativeHandle, EventKind::Signaling});
192
586
  }
193
587
 
194
588
  void RTCPeerConnection::setRemoteDescription(const std::string &sdp_type, const std::string &sdp) const {
589
+ { std::lock_guard<std::mutex> lock(peerMutex()); requirePeer(nativeHandle); }
590
+ if (sdp_type != "offer" && sdp_type != "answer") throw std::invalid_argument("NotSupportedError: SDP type");
195
591
  rtc::platform_set_remote_description(nativeHandle, sdp_type, sdp);
592
+ { std::lock_guard<std::mutex> lock(peerMutex()); auto& p = requirePeer(nativeHandle);
593
+ p.remote = RTCSessionDescriptionObject(RTCSessionDescription{sdp_type, sdp}); p.signaling = sdp_type == "offer" ? "have-remote-offer" : "stable";
594
+ applyNegotiatedMedia(p); }
595
+ enqueue_internal(PendingEvent{nativeHandle, EventKind::Signaling});
196
596
  }
197
597
 
198
598
  void RTCPeerConnection::addIceCandidate(const std::string &candidate, const std::string &sdp_mid, double sdp_mline_index) const {
@@ -200,13 +600,23 @@ void RTCPeerConnection::addIceCandidate(const std::string &candidate, const std:
200
600
  }
201
601
 
202
602
  void RTCPeerConnection::close() const {
203
- rtc::platform_close(nativeHandle);
204
- std::lock_guard<std::mutex> lock(peerMutex());
205
- auto it = peerTable().find(nativeHandle);
206
- if (it != peerTable().end()) {
207
- it->second.connectionState = "closed";
208
- it->second.iceConnectionState = "closed";
603
+ {
604
+ std::lock_guard<std::mutex> lock(peerMutex());
605
+ auto it = peerTable().find(nativeHandle);
606
+ if (it != peerTable().end()) {
607
+ it->second.open = false;
608
+ it->second.signaling = "closed";
609
+ for (auto id : it->second.transceivers) { transceiverTable()[id].stopped = true; transceiverTable()[id].current.reset(); }
610
+ for (auto& [id, ch] : channelTable()) if (ch.peer == nativeHandle && ch.state != "closed") {
611
+ ch.state = "closed"; PendingEvent ev{nativeHandle, EventKind::ChannelClose}; ev.channel = id; enqueue_internal(std::move(ev));
612
+ }
613
+ it->second.connectionState = "closed";
614
+ it->second.iceConnectionState = "closed";
615
+ }
209
616
  }
617
+ rtc::platform_close(nativeHandle);
210
618
  }
211
619
 
620
+ #include "rtc_objects.inc"
621
+
212
622
  } // namespace gea::host