@webrtc-node/webrtc 0.2.1
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.
- package/CMakeLists.txt +177 -0
- package/LICENSE +373 -0
- package/README.md +87 -0
- package/index.d.ts +388 -0
- package/lib/index.js +4910 -0
- package/lib/load-native.js +42 -0
- package/package.json +91 -0
- package/scripts/install-native.js +154 -0
- package/scripts/prebuild-integrity.js +227 -0
- package/src/native/addon.cc +1632 -0
- package/src/native/certificate.cc +215 -0
- package/src/native/certificate.hpp +20 -0
|
@@ -0,0 +1,1632 @@
|
|
|
1
|
+
#include <napi.h>
|
|
2
|
+
#include <rtc/rtc.hpp>
|
|
3
|
+
|
|
4
|
+
#include "certificate.hpp"
|
|
5
|
+
|
|
6
|
+
#include <algorithm>
|
|
7
|
+
#include <atomic>
|
|
8
|
+
#include <chrono>
|
|
9
|
+
#include <cmath>
|
|
10
|
+
#include <condition_variable>
|
|
11
|
+
#include <cstddef>
|
|
12
|
+
#include <cstdlib>
|
|
13
|
+
#include <cstring>
|
|
14
|
+
#include <functional>
|
|
15
|
+
#include <limits>
|
|
16
|
+
#include <memory>
|
|
17
|
+
#include <mutex>
|
|
18
|
+
#include <optional>
|
|
19
|
+
#include <stdexcept>
|
|
20
|
+
#include <string>
|
|
21
|
+
#include <thread>
|
|
22
|
+
#include <unordered_map>
|
|
23
|
+
#include <utility>
|
|
24
|
+
#include <vector>
|
|
25
|
+
|
|
26
|
+
namespace {
|
|
27
|
+
|
|
28
|
+
class NativeDataChannel;
|
|
29
|
+
class NativeIceUdpMuxListener;
|
|
30
|
+
struct ChannelBinding;
|
|
31
|
+
struct EventDispatcher;
|
|
32
|
+
struct IceUdpMuxBinding;
|
|
33
|
+
struct PeerBinding;
|
|
34
|
+
|
|
35
|
+
std::atomic<uint32_t> nextChannelId{1};
|
|
36
|
+
constexpr auto PEER_CLOSE_TIMEOUT = std::chrono::seconds(5);
|
|
37
|
+
|
|
38
|
+
uint32_t AllocateChannelId() {
|
|
39
|
+
uint32_t id;
|
|
40
|
+
do {
|
|
41
|
+
id = nextChannelId.fetch_add(1, std::memory_order_relaxed);
|
|
42
|
+
} while (id == 0);
|
|
43
|
+
return id;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
struct PeerCloseSignal {
|
|
47
|
+
std::mutex mutex;
|
|
48
|
+
std::condition_variable condition;
|
|
49
|
+
bool closed = false;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
struct PeerTeardownWork {
|
|
53
|
+
std::shared_ptr<rtc::PeerConnection> peerConnection;
|
|
54
|
+
std::vector<std::shared_ptr<rtc::DataChannel>> dataChannels;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
void CloseDataChannelForTeardown(const std::shared_ptr<rtc::DataChannel> &dataChannel) {
|
|
58
|
+
if (!dataChannel)
|
|
59
|
+
return;
|
|
60
|
+
try {
|
|
61
|
+
dataChannel->resetCallbacks();
|
|
62
|
+
dataChannel->close();
|
|
63
|
+
} catch (...) {
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
void RunPeerTeardown(PeerTeardownWork work) {
|
|
68
|
+
auto closeSignal = std::make_shared<PeerCloseSignal>();
|
|
69
|
+
work.peerConnection->onStateChange([closeSignal](rtc::PeerConnection::State state) {
|
|
70
|
+
if (state != rtc::PeerConnection::State::Closed)
|
|
71
|
+
return;
|
|
72
|
+
{
|
|
73
|
+
std::lock_guard<std::mutex> lock(closeSignal->mutex);
|
|
74
|
+
closeSignal->closed = true;
|
|
75
|
+
}
|
|
76
|
+
closeSignal->condition.notify_all();
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
for (auto &dataChannel : work.dataChannels) {
|
|
80
|
+
CloseDataChannelForTeardown(dataChannel);
|
|
81
|
+
}
|
|
82
|
+
work.dataChannels.clear();
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
work.peerConnection->close();
|
|
86
|
+
} catch (...) {
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
{
|
|
90
|
+
std::unique_lock<std::mutex> lock(closeSignal->mutex);
|
|
91
|
+
closeSignal->condition.wait_for(lock, PEER_CLOSE_TIMEOUT, [&]() {
|
|
92
|
+
return closeSignal->closed ||
|
|
93
|
+
work.peerConnection->state() == rtc::PeerConnection::State::Closed;
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
work.peerConnection->resetCallbacks();
|
|
97
|
+
work.peerConnection.reset();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
std::string ToString(rtc::PeerConnection::State state) {
|
|
101
|
+
switch (state) {
|
|
102
|
+
case rtc::PeerConnection::State::New:
|
|
103
|
+
return "new";
|
|
104
|
+
case rtc::PeerConnection::State::Connecting:
|
|
105
|
+
return "connecting";
|
|
106
|
+
case rtc::PeerConnection::State::Connected:
|
|
107
|
+
return "connected";
|
|
108
|
+
case rtc::PeerConnection::State::Disconnected:
|
|
109
|
+
return "disconnected";
|
|
110
|
+
case rtc::PeerConnection::State::Failed:
|
|
111
|
+
return "failed";
|
|
112
|
+
case rtc::PeerConnection::State::Closed:
|
|
113
|
+
return "closed";
|
|
114
|
+
}
|
|
115
|
+
return "closed";
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
std::string ToString(rtc::PeerConnection::IceState state) {
|
|
119
|
+
switch (state) {
|
|
120
|
+
case rtc::PeerConnection::IceState::New:
|
|
121
|
+
return "new";
|
|
122
|
+
case rtc::PeerConnection::IceState::Checking:
|
|
123
|
+
return "checking";
|
|
124
|
+
case rtc::PeerConnection::IceState::Connected:
|
|
125
|
+
return "connected";
|
|
126
|
+
case rtc::PeerConnection::IceState::Completed:
|
|
127
|
+
return "completed";
|
|
128
|
+
case rtc::PeerConnection::IceState::Failed:
|
|
129
|
+
return "failed";
|
|
130
|
+
case rtc::PeerConnection::IceState::Disconnected:
|
|
131
|
+
return "disconnected";
|
|
132
|
+
case rtc::PeerConnection::IceState::Closed:
|
|
133
|
+
return "closed";
|
|
134
|
+
}
|
|
135
|
+
return "closed";
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
std::string ToString(rtc::PeerConnection::GatheringState state) {
|
|
139
|
+
switch (state) {
|
|
140
|
+
case rtc::PeerConnection::GatheringState::New:
|
|
141
|
+
return "new";
|
|
142
|
+
case rtc::PeerConnection::GatheringState::InProgress:
|
|
143
|
+
return "gathering";
|
|
144
|
+
case rtc::PeerConnection::GatheringState::Complete:
|
|
145
|
+
return "complete";
|
|
146
|
+
}
|
|
147
|
+
return "complete";
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
std::string ToString(rtc::PeerConnection::SignalingState state) {
|
|
151
|
+
switch (state) {
|
|
152
|
+
case rtc::PeerConnection::SignalingState::Stable:
|
|
153
|
+
return "stable";
|
|
154
|
+
case rtc::PeerConnection::SignalingState::HaveLocalOffer:
|
|
155
|
+
return "have-local-offer";
|
|
156
|
+
case rtc::PeerConnection::SignalingState::HaveRemoteOffer:
|
|
157
|
+
return "have-remote-offer";
|
|
158
|
+
case rtc::PeerConnection::SignalingState::HaveLocalPranswer:
|
|
159
|
+
return "have-local-pranswer";
|
|
160
|
+
case rtc::PeerConnection::SignalingState::HaveRemotePranswer:
|
|
161
|
+
return "have-remote-pranswer";
|
|
162
|
+
}
|
|
163
|
+
return "stable";
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
rtc::Description::Type ParseDescriptionType(const std::string &type) {
|
|
167
|
+
if (type.empty())
|
|
168
|
+
return rtc::Description::Type::Unspec;
|
|
169
|
+
return rtc::Description::stringToType(type);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
Napi::Object DescriptionToObject(Napi::Env env, const rtc::Description &description) {
|
|
173
|
+
Napi::Object result = Napi::Object::New(env);
|
|
174
|
+
result.Set("type", description.typeString());
|
|
175
|
+
result.Set("sdp", std::string(description));
|
|
176
|
+
return result;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
rtc::LocalDescriptionInit ParseLocalDescriptionInit(const Napi::Value &value) {
|
|
180
|
+
rtc::LocalDescriptionInit init;
|
|
181
|
+
if (!value.IsObject())
|
|
182
|
+
return init;
|
|
183
|
+
|
|
184
|
+
Napi::Object object = value.As<Napi::Object>();
|
|
185
|
+
if (object.Has("iceUfrag") && !object.Get("iceUfrag").IsNull() &&
|
|
186
|
+
!object.Get("iceUfrag").IsUndefined())
|
|
187
|
+
init.iceUfrag = object.Get("iceUfrag").ToString().Utf8Value();
|
|
188
|
+
if (object.Has("icePwd") && !object.Get("icePwd").IsNull() &&
|
|
189
|
+
!object.Get("icePwd").IsUndefined())
|
|
190
|
+
init.icePwd = object.Get("icePwd").ToString().Utf8Value();
|
|
191
|
+
return init;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
struct ChannelOptions {
|
|
195
|
+
bool ordered = true;
|
|
196
|
+
bool negotiated = false;
|
|
197
|
+
std::optional<uint16_t> id;
|
|
198
|
+
std::optional<uint32_t> maxPacketLifeTime;
|
|
199
|
+
std::optional<uint32_t> maxRetransmits;
|
|
200
|
+
std::string protocol;
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
struct NativeEvent {
|
|
204
|
+
std::string target;
|
|
205
|
+
std::string type;
|
|
206
|
+
uint32_t channelId = 0;
|
|
207
|
+
std::shared_ptr<ChannelBinding> channel;
|
|
208
|
+
std::string state;
|
|
209
|
+
std::string descriptionType;
|
|
210
|
+
std::string sdp;
|
|
211
|
+
std::string candidate;
|
|
212
|
+
std::string mid;
|
|
213
|
+
std::string error;
|
|
214
|
+
bool binary = false;
|
|
215
|
+
std::string text;
|
|
216
|
+
rtc::binary bytes;
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
struct EventDispatcher : public std::enable_shared_from_this<EventDispatcher> {
|
|
220
|
+
static std::shared_ptr<EventDispatcher> Create(Napi::Env env, Napi::Function callback) {
|
|
221
|
+
return std::shared_ptr<EventDispatcher>(new EventDispatcher(env, callback));
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
~EventDispatcher() { Close(); }
|
|
225
|
+
|
|
226
|
+
void Emit(NativeEvent event) {
|
|
227
|
+
if (event.target != "datachannel" || event.type != "message") {
|
|
228
|
+
EmitDirect(std::move(event));
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
bool scheduleDispatch = false;
|
|
233
|
+
std::lock_guard<std::mutex> lock(lifecycleMutex);
|
|
234
|
+
if (!active) {
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
pendingEvents.push_back(std::move(event));
|
|
239
|
+
if (!dispatchScheduled) {
|
|
240
|
+
dispatchScheduled = true;
|
|
241
|
+
scheduleDispatch = true;
|
|
242
|
+
}
|
|
243
|
+
if (!scheduleDispatch)
|
|
244
|
+
return;
|
|
245
|
+
|
|
246
|
+
QueueDispatchLocked();
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
void EmitDirect(NativeEvent event) {
|
|
250
|
+
auto *queued = new NativeEvent(std::move(event));
|
|
251
|
+
std::lock_guard<std::mutex> lock(lifecycleMutex);
|
|
252
|
+
if (!active) {
|
|
253
|
+
delete queued;
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
napi_status status = tsfn.NonBlockingCall(queued, DispatchDirect);
|
|
258
|
+
if (status != napi_ok)
|
|
259
|
+
delete queued;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
void Close() {
|
|
263
|
+
std::lock_guard<std::mutex> lock(lifecycleMutex);
|
|
264
|
+
pendingEvents.clear();
|
|
265
|
+
dispatchScheduled = false;
|
|
266
|
+
if (active) {
|
|
267
|
+
active = false;
|
|
268
|
+
tsfn.Release();
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
private:
|
|
273
|
+
EventDispatcher(Napi::Env env, Napi::Function callback)
|
|
274
|
+
: tsfn(Napi::ThreadSafeFunction::New(env, callback, "webrtc-node events", 0, 1)) {
|
|
275
|
+
tsfn.Unref(env);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
void Drain(Napi::Env env, Napi::Function callback) {
|
|
279
|
+
std::vector<NativeEvent> events;
|
|
280
|
+
{
|
|
281
|
+
std::lock_guard<std::mutex> lock(lifecycleMutex);
|
|
282
|
+
if (pendingEvents.empty()) {
|
|
283
|
+
dispatchScheduled = false;
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
events.swap(pendingEvents);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
if (events.size() == 1) {
|
|
290
|
+
callback.Call({EventToObject(env, events.front())});
|
|
291
|
+
} else {
|
|
292
|
+
Napi::Array batch = Napi::Array::New(env, events.size());
|
|
293
|
+
for (uint32_t i = 0; i < events.size(); ++i)
|
|
294
|
+
batch.Set(i, EventToObject(env, events[i]));
|
|
295
|
+
callback.Call({batch});
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
std::lock_guard<std::mutex> lock(lifecycleMutex);
|
|
299
|
+
if (!active || pendingEvents.empty()) {
|
|
300
|
+
dispatchScheduled = false;
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
QueueDispatchLocked();
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
void QueueDispatchLocked() {
|
|
307
|
+
auto *dispatcher = new std::shared_ptr<EventDispatcher>(shared_from_this());
|
|
308
|
+
napi_status status = tsfn.NonBlockingCall(dispatcher, DispatchQueued);
|
|
309
|
+
if (status != napi_ok) {
|
|
310
|
+
dispatchScheduled = false;
|
|
311
|
+
pendingEvents.clear();
|
|
312
|
+
delete dispatcher;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
static void DispatchQueued(Napi::Env env, Napi::Function callback,
|
|
317
|
+
std::shared_ptr<EventDispatcher> *dispatcher) {
|
|
318
|
+
std::shared_ptr<EventDispatcher> scoped = std::move(*dispatcher);
|
|
319
|
+
delete dispatcher;
|
|
320
|
+
scoped->Drain(env, callback);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
static void DispatchDirect(Napi::Env env, Napi::Function callback, NativeEvent *event) {
|
|
324
|
+
std::unique_ptr<NativeEvent> scoped(event);
|
|
325
|
+
callback.Call({EventToObject(env, *scoped)});
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
static Napi::Value MessagePayloadToValue(Napi::Env env, NativeEvent &event) {
|
|
329
|
+
if (!event.binary)
|
|
330
|
+
return Napi::String::New(env, event.text);
|
|
331
|
+
|
|
332
|
+
if (event.bytes.empty())
|
|
333
|
+
return Napi::ArrayBuffer::New(env, 0);
|
|
334
|
+
|
|
335
|
+
auto *bytes = new rtc::binary(std::move(event.bytes));
|
|
336
|
+
return Napi::ArrayBuffer::New(
|
|
337
|
+
env, bytes->data(), bytes->size(),
|
|
338
|
+
[](Napi::Env, void *, rtc::binary *finalizedBytes) { delete finalizedBytes; },
|
|
339
|
+
bytes);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
static Napi::Object EventToObject(Napi::Env env, NativeEvent &event);
|
|
343
|
+
|
|
344
|
+
bool active = true;
|
|
345
|
+
std::mutex lifecycleMutex;
|
|
346
|
+
std::vector<NativeEvent> pendingEvents;
|
|
347
|
+
bool dispatchScheduled = false;
|
|
348
|
+
Napi::ThreadSafeFunction tsfn;
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
struct IceUdpMuxDispatch {
|
|
352
|
+
std::shared_ptr<IceUdpMuxBinding> binding;
|
|
353
|
+
rtc::IceUdpMuxRequest request;
|
|
354
|
+
};
|
|
355
|
+
|
|
356
|
+
struct IceUdpMuxBinding : public std::enable_shared_from_this<IceUdpMuxBinding> {
|
|
357
|
+
static std::shared_ptr<IceUdpMuxBinding> Create(Napi::Env env, Napi::Function callback,
|
|
358
|
+
uint16_t port,
|
|
359
|
+
std::optional<std::string> address) {
|
|
360
|
+
auto binding = std::shared_ptr<IceUdpMuxBinding>(
|
|
361
|
+
new IceUdpMuxBinding(env, callback, port, std::move(address)));
|
|
362
|
+
try {
|
|
363
|
+
binding->iceUdpMuxListener =
|
|
364
|
+
std::make_unique<rtc::IceUdpMuxListener>(binding->port, binding->address);
|
|
365
|
+
binding->AttachCallback();
|
|
366
|
+
} catch (...) {
|
|
367
|
+
binding->Close();
|
|
368
|
+
throw;
|
|
369
|
+
}
|
|
370
|
+
return binding;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
~IceUdpMuxBinding() { Close(); }
|
|
374
|
+
|
|
375
|
+
void Emit(rtc::IceUdpMuxRequest request) {
|
|
376
|
+
std::lock_guard<std::mutex> lock(lifecycleMutex);
|
|
377
|
+
if (!active)
|
|
378
|
+
return;
|
|
379
|
+
|
|
380
|
+
auto *dispatch = new IceUdpMuxDispatch{shared_from_this(), std::move(request)};
|
|
381
|
+
napi_status status = tsfn.NonBlockingCall(dispatch, Dispatch);
|
|
382
|
+
if (status != napi_ok)
|
|
383
|
+
delete dispatch;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
void Close() {
|
|
387
|
+
std::unique_ptr<rtc::IceUdpMuxListener> listener;
|
|
388
|
+
bool release = false;
|
|
389
|
+
{
|
|
390
|
+
std::lock_guard<std::mutex> lock(lifecycleMutex);
|
|
391
|
+
if (!active)
|
|
392
|
+
return;
|
|
393
|
+
active = false;
|
|
394
|
+
listener = std::move(iceUdpMuxListener);
|
|
395
|
+
release = !tsfnReleased;
|
|
396
|
+
tsfnReleased = true;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
if (listener) {
|
|
400
|
+
try {
|
|
401
|
+
listener->OnUnhandledStunRequest(
|
|
402
|
+
std::function<void(rtc::IceUdpMuxRequest)>{});
|
|
403
|
+
listener->stop();
|
|
404
|
+
} catch (...) {
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
if (release)
|
|
408
|
+
tsfn.Release();
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
uint16_t Port() const { return port; }
|
|
412
|
+
|
|
413
|
+
const std::optional<std::string> &Address() const { return address; }
|
|
414
|
+
|
|
415
|
+
bool IsActive() const {
|
|
416
|
+
std::lock_guard<std::mutex> lock(lifecycleMutex);
|
|
417
|
+
return active;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
private:
|
|
421
|
+
IceUdpMuxBinding(Napi::Env env, Napi::Function callback, uint16_t port_,
|
|
422
|
+
std::optional<std::string> address_)
|
|
423
|
+
: port(port_), address(std::move(address_)),
|
|
424
|
+
tsfn(Napi::ThreadSafeFunction::New(env, callback, "webrtc-node ICE UDP mux", 0, 1)) {
|
|
425
|
+
tsfn.Unref(env);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
void AttachCallback() {
|
|
429
|
+
std::weak_ptr<IceUdpMuxBinding> weak = shared_from_this();
|
|
430
|
+
iceUdpMuxListener->OnUnhandledStunRequest([weak](rtc::IceUdpMuxRequest request) {
|
|
431
|
+
if (auto self = weak.lock())
|
|
432
|
+
self->Emit(std::move(request));
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
static void Dispatch(Napi::Env env, Napi::Function callback, IceUdpMuxDispatch *dispatch) {
|
|
437
|
+
std::unique_ptr<IceUdpMuxDispatch> scoped(dispatch);
|
|
438
|
+
{
|
|
439
|
+
std::lock_guard<std::mutex> lock(scoped->binding->lifecycleMutex);
|
|
440
|
+
if (!scoped->binding->active)
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
Napi::Object request = Napi::Object::New(env);
|
|
445
|
+
request.Set("ufrag", scoped->request.remoteUfrag);
|
|
446
|
+
request.Set("localUfrag", scoped->request.localUfrag);
|
|
447
|
+
request.Set("host", scoped->request.remoteAddress);
|
|
448
|
+
request.Set("port", scoped->request.remotePort);
|
|
449
|
+
callback.Call({request});
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const uint16_t port;
|
|
453
|
+
const std::optional<std::string> address;
|
|
454
|
+
bool active = true;
|
|
455
|
+
bool tsfnReleased = false;
|
|
456
|
+
mutable std::mutex lifecycleMutex;
|
|
457
|
+
Napi::ThreadSafeFunction tsfn;
|
|
458
|
+
std::unique_ptr<rtc::IceUdpMuxListener> iceUdpMuxListener;
|
|
459
|
+
};
|
|
460
|
+
|
|
461
|
+
std::mutex &IceUdpMuxRegistryMutex() {
|
|
462
|
+
static std::mutex mutex;
|
|
463
|
+
return mutex;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
std::vector<std::weak_ptr<IceUdpMuxBinding>> &IceUdpMuxRegistry() {
|
|
467
|
+
static std::vector<std::weak_ptr<IceUdpMuxBinding>> registry;
|
|
468
|
+
return registry;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
void RegisterIceUdpMuxBinding(const std::shared_ptr<IceUdpMuxBinding> &binding) {
|
|
472
|
+
std::lock_guard<std::mutex> lock(IceUdpMuxRegistryMutex());
|
|
473
|
+
auto ®istry = IceUdpMuxRegistry();
|
|
474
|
+
registry.erase(std::remove_if(registry.begin(), registry.end(),
|
|
475
|
+
[](const auto &entry) { return entry.expired(); }),
|
|
476
|
+
registry.end());
|
|
477
|
+
registry.push_back(binding);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
std::optional<uint16_t> ActiveIceUdpMuxPort() {
|
|
481
|
+
std::lock_guard<std::mutex> lock(IceUdpMuxRegistryMutex());
|
|
482
|
+
auto ®istry = IceUdpMuxRegistry();
|
|
483
|
+
std::optional<uint16_t> port;
|
|
484
|
+
registry.erase(std::remove_if(registry.begin(), registry.end(),
|
|
485
|
+
[&port](const auto &entry) {
|
|
486
|
+
auto binding = entry.lock();
|
|
487
|
+
if (!binding)
|
|
488
|
+
return true;
|
|
489
|
+
if (!binding->IsActive())
|
|
490
|
+
return true;
|
|
491
|
+
if (!port)
|
|
492
|
+
port = binding->Port();
|
|
493
|
+
return false;
|
|
494
|
+
}),
|
|
495
|
+
registry.end());
|
|
496
|
+
return port;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
void CloseAllIceUdpMuxBindings() {
|
|
500
|
+
std::vector<std::shared_ptr<IceUdpMuxBinding>> bindings;
|
|
501
|
+
{
|
|
502
|
+
std::lock_guard<std::mutex> lock(IceUdpMuxRegistryMutex());
|
|
503
|
+
for (auto &entry : IceUdpMuxRegistry()) {
|
|
504
|
+
if (auto binding = entry.lock())
|
|
505
|
+
bindings.push_back(std::move(binding));
|
|
506
|
+
}
|
|
507
|
+
IceUdpMuxRegistry().clear();
|
|
508
|
+
}
|
|
509
|
+
for (auto &binding : bindings)
|
|
510
|
+
binding->Close();
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
class NativeIceUdpMuxListener : public Napi::ObjectWrap<NativeIceUdpMuxListener> {
|
|
514
|
+
public:
|
|
515
|
+
static void Init(Napi::Env env, Napi::Object exports) {
|
|
516
|
+
Napi::Function func = DefineClass(
|
|
517
|
+
env, "NativeIceUdpMuxListener",
|
|
518
|
+
{
|
|
519
|
+
InstanceMethod("port", &NativeIceUdpMuxListener::Port),
|
|
520
|
+
InstanceMethod("address", &NativeIceUdpMuxListener::Address),
|
|
521
|
+
InstanceMethod("close", &NativeIceUdpMuxListener::Close),
|
|
522
|
+
InstanceMethod("stop", &NativeIceUdpMuxListener::Close),
|
|
523
|
+
});
|
|
524
|
+
exports.Set("NativeIceUdpMuxListener", func);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
NativeIceUdpMuxListener(const Napi::CallbackInfo &info)
|
|
528
|
+
: Napi::ObjectWrap<NativeIceUdpMuxListener>(info) {
|
|
529
|
+
Napi::Env env = info.Env();
|
|
530
|
+
if (info.Length() < 2 || !info[0].IsNumber() || !info[1].IsFunction())
|
|
531
|
+
throw Napi::TypeError::New(
|
|
532
|
+
env, "NativeIceUdpMuxListener requires a port and event callback");
|
|
533
|
+
uint32_t port = info[0].ToNumber().Uint32Value();
|
|
534
|
+
if (port > std::numeric_limits<uint16_t>::max())
|
|
535
|
+
throw Napi::RangeError::New(env, "ICE UDP mux port must be between 0 and 65535");
|
|
536
|
+
|
|
537
|
+
std::optional<std::string> address;
|
|
538
|
+
if (info.Length() > 2 && !info[2].IsUndefined() && !info[2].IsNull()) {
|
|
539
|
+
if (!info[2].IsString())
|
|
540
|
+
throw Napi::TypeError::New(env, "ICE UDP mux address must be a string");
|
|
541
|
+
address = info[2].ToString().Utf8Value();
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
try {
|
|
545
|
+
binding_ = IceUdpMuxBinding::Create(env, info[1].As<Napi::Function>(),
|
|
546
|
+
static_cast<uint16_t>(port), std::move(address));
|
|
547
|
+
RegisterIceUdpMuxBinding(binding_);
|
|
548
|
+
} catch (const std::exception &e) {
|
|
549
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
~NativeIceUdpMuxListener() override {
|
|
554
|
+
if (binding_)
|
|
555
|
+
binding_->Close();
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
private:
|
|
559
|
+
std::shared_ptr<IceUdpMuxBinding> binding_;
|
|
560
|
+
|
|
561
|
+
Napi::Value Port(const Napi::CallbackInfo &info) {
|
|
562
|
+
return Napi::Number::New(info.Env(), binding_->Port());
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
Napi::Value Address(const Napi::CallbackInfo &info) {
|
|
566
|
+
const auto &address = binding_->Address();
|
|
567
|
+
if (!address)
|
|
568
|
+
return info.Env().Undefined();
|
|
569
|
+
return Napi::String::New(info.Env(), *address);
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
Napi::Value Close(const Napi::CallbackInfo &info) {
|
|
573
|
+
binding_->Close();
|
|
574
|
+
return info.Env().Undefined();
|
|
575
|
+
}
|
|
576
|
+
};
|
|
577
|
+
|
|
578
|
+
struct ChannelBinding : public std::enable_shared_from_this<ChannelBinding> {
|
|
579
|
+
using ClosedCallback = std::function<void(uint32_t, const ChannelBinding *)>;
|
|
580
|
+
|
|
581
|
+
static std::shared_ptr<ChannelBinding> Create(std::shared_ptr<rtc::DataChannel> dataChannel,
|
|
582
|
+
std::shared_ptr<EventDispatcher> dispatcher,
|
|
583
|
+
ChannelOptions options,
|
|
584
|
+
ClosedCallback closedCallback) {
|
|
585
|
+
auto binding = std::shared_ptr<ChannelBinding>(new ChannelBinding(
|
|
586
|
+
std::move(dataChannel), std::move(dispatcher), std::move(options),
|
|
587
|
+
std::move(closedCallback)));
|
|
588
|
+
binding->AttachCallbacks();
|
|
589
|
+
return binding;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
static ChannelOptions IncomingOptions(const std::shared_ptr<rtc::DataChannel> &dataChannel) {
|
|
593
|
+
ChannelOptions options;
|
|
594
|
+
options.negotiated = false;
|
|
595
|
+
options.protocol = dataChannel->protocol();
|
|
596
|
+
rtc::Reliability reliability = dataChannel->reliability();
|
|
597
|
+
options.ordered = !reliability.unordered;
|
|
598
|
+
if (reliability.maxPacketLifeTime)
|
|
599
|
+
options.maxPacketLifeTime =
|
|
600
|
+
static_cast<uint32_t>(reliability.maxPacketLifeTime->count());
|
|
601
|
+
if (reliability.maxRetransmits)
|
|
602
|
+
options.maxRetransmits = static_cast<uint32_t>(*reliability.maxRetransmits);
|
|
603
|
+
return options;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
void Close() {
|
|
607
|
+
auto dc = dataChannel;
|
|
608
|
+
if (!dc)
|
|
609
|
+
return;
|
|
610
|
+
std::thread([dc = std::move(dc)]() {
|
|
611
|
+
try {
|
|
612
|
+
dc->close();
|
|
613
|
+
} catch (...) {
|
|
614
|
+
}
|
|
615
|
+
}).detach();
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
void Destroy() {
|
|
619
|
+
{
|
|
620
|
+
std::lock_guard<std::mutex> lock(callbacksMutex);
|
|
621
|
+
if (!callbacksActive)
|
|
622
|
+
return;
|
|
623
|
+
callbacksActive = false;
|
|
624
|
+
}
|
|
625
|
+
auto dc = dataChannel;
|
|
626
|
+
if (dc)
|
|
627
|
+
dc->resetCallbacks();
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
const uint32_t id;
|
|
631
|
+
std::shared_ptr<rtc::DataChannel> dataChannel;
|
|
632
|
+
std::shared_ptr<EventDispatcher> dispatcher;
|
|
633
|
+
ChannelOptions options;
|
|
634
|
+
|
|
635
|
+
private:
|
|
636
|
+
ChannelBinding(std::shared_ptr<rtc::DataChannel> dataChannel_,
|
|
637
|
+
std::shared_ptr<EventDispatcher> dispatcher_, ChannelOptions options_,
|
|
638
|
+
ClosedCallback closedCallback_)
|
|
639
|
+
: id(AllocateChannelId()), dataChannel(std::move(dataChannel_)),
|
|
640
|
+
dispatcher(std::move(dispatcher_)), options(std::move(options_)),
|
|
641
|
+
closedCallback(std::move(closedCallback_)) {}
|
|
642
|
+
|
|
643
|
+
void Emit(NativeEvent event) {
|
|
644
|
+
std::lock_guard<std::mutex> lock(callbacksMutex);
|
|
645
|
+
if (!callbacksActive)
|
|
646
|
+
return;
|
|
647
|
+
dispatcher->Emit(std::move(event));
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
void AttachCallbacks() {
|
|
651
|
+
std::weak_ptr<ChannelBinding> weak = shared_from_this();
|
|
652
|
+
|
|
653
|
+
dataChannel->onOpen([weak]() {
|
|
654
|
+
if (auto self = weak.lock()) {
|
|
655
|
+
NativeEvent event;
|
|
656
|
+
event.target = "datachannel";
|
|
657
|
+
event.type = "open";
|
|
658
|
+
event.channelId = self->id;
|
|
659
|
+
self->Emit(std::move(event));
|
|
660
|
+
}
|
|
661
|
+
});
|
|
662
|
+
|
|
663
|
+
dataChannel->onClosed([weak]() {
|
|
664
|
+
if (auto self = weak.lock()) {
|
|
665
|
+
NativeEvent event;
|
|
666
|
+
event.target = "datachannel";
|
|
667
|
+
event.type = "close";
|
|
668
|
+
event.channelId = self->id;
|
|
669
|
+
self->Emit(std::move(event));
|
|
670
|
+
if (self->closedCallback)
|
|
671
|
+
self->closedCallback(self->id, self.get());
|
|
672
|
+
}
|
|
673
|
+
});
|
|
674
|
+
|
|
675
|
+
dataChannel->onError([weak](std::string error) {
|
|
676
|
+
if (auto self = weak.lock()) {
|
|
677
|
+
NativeEvent event;
|
|
678
|
+
event.target = "datachannel";
|
|
679
|
+
event.type = "error";
|
|
680
|
+
event.channelId = self->id;
|
|
681
|
+
event.error = std::move(error);
|
|
682
|
+
self->Emit(std::move(event));
|
|
683
|
+
}
|
|
684
|
+
});
|
|
685
|
+
|
|
686
|
+
dataChannel->onBufferedAmountLow([weak]() {
|
|
687
|
+
if (auto self = weak.lock()) {
|
|
688
|
+
NativeEvent event;
|
|
689
|
+
event.target = "datachannel";
|
|
690
|
+
event.type = "bufferedamountlow";
|
|
691
|
+
event.channelId = self->id;
|
|
692
|
+
self->Emit(std::move(event));
|
|
693
|
+
}
|
|
694
|
+
});
|
|
695
|
+
|
|
696
|
+
dataChannel->onMessage([weak](rtc::message_variant data) {
|
|
697
|
+
if (auto self = weak.lock()) {
|
|
698
|
+
NativeEvent event;
|
|
699
|
+
event.target = "datachannel";
|
|
700
|
+
event.type = "message";
|
|
701
|
+
event.channelId = self->id;
|
|
702
|
+
if (std::holds_alternative<std::string>(data)) {
|
|
703
|
+
event.binary = false;
|
|
704
|
+
event.text = std::get<std::string>(std::move(data));
|
|
705
|
+
} else {
|
|
706
|
+
event.binary = true;
|
|
707
|
+
event.bytes = std::move(std::get<rtc::binary>(data));
|
|
708
|
+
}
|
|
709
|
+
self->Emit(std::move(event));
|
|
710
|
+
}
|
|
711
|
+
});
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
bool callbacksActive = true;
|
|
715
|
+
std::mutex callbacksMutex;
|
|
716
|
+
ClosedCallback closedCallback;
|
|
717
|
+
};
|
|
718
|
+
|
|
719
|
+
class NativeDataChannel : public Napi::ObjectWrap<NativeDataChannel> {
|
|
720
|
+
public:
|
|
721
|
+
static Napi::FunctionReference constructor;
|
|
722
|
+
|
|
723
|
+
static void Init(Napi::Env env, Napi::Object exports) {
|
|
724
|
+
Napi::Function func = DefineClass(
|
|
725
|
+
env, "NativeDataChannel",
|
|
726
|
+
{
|
|
727
|
+
InstanceMethod("sendString", &NativeDataChannel::SendString),
|
|
728
|
+
InstanceMethod("sendBinary", &NativeDataChannel::SendBinary),
|
|
729
|
+
InstanceMethod("close", &NativeDataChannel::Close),
|
|
730
|
+
InstanceMethod("setBufferedAmountLowThreshold",
|
|
731
|
+
&NativeDataChannel::SetBufferedAmountLowThreshold),
|
|
732
|
+
InstanceAccessor("bindingId", &NativeDataChannel::GetBindingId, nullptr),
|
|
733
|
+
InstanceAccessor("id", &NativeDataChannel::GetId, nullptr),
|
|
734
|
+
InstanceAccessor("label", &NativeDataChannel::GetLabel, nullptr),
|
|
735
|
+
InstanceAccessor("protocol", &NativeDataChannel::GetProtocol, nullptr),
|
|
736
|
+
InstanceAccessor("ordered", &NativeDataChannel::GetOrdered, nullptr),
|
|
737
|
+
InstanceAccessor("negotiated", &NativeDataChannel::GetNegotiated, nullptr),
|
|
738
|
+
InstanceAccessor("maxPacketLifeTime", &NativeDataChannel::GetMaxPacketLifeTime,
|
|
739
|
+
nullptr),
|
|
740
|
+
InstanceAccessor("maxRetransmits", &NativeDataChannel::GetMaxRetransmits, nullptr),
|
|
741
|
+
InstanceAccessor("bufferedAmount", &NativeDataChannel::GetBufferedAmount, nullptr),
|
|
742
|
+
InstanceAccessor("isOpen", &NativeDataChannel::GetIsOpen, nullptr),
|
|
743
|
+
InstanceAccessor("isClosed", &NativeDataChannel::GetIsClosed, nullptr),
|
|
744
|
+
InstanceAccessor("maxMessageSize", &NativeDataChannel::GetMaxMessageSize, nullptr),
|
|
745
|
+
});
|
|
746
|
+
constructor = Napi::Persistent(func);
|
|
747
|
+
constructor.SuppressDestruct();
|
|
748
|
+
exports.Set("NativeDataChannel", func);
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
static Napi::Object NewInstance(Napi::Env env, std::shared_ptr<ChannelBinding> binding) {
|
|
752
|
+
auto *payload = new std::shared_ptr<ChannelBinding>(std::move(binding));
|
|
753
|
+
auto external = Napi::External<std::shared_ptr<ChannelBinding>>::New(
|
|
754
|
+
env, payload, [](Napi::Env, std::shared_ptr<ChannelBinding> *data) { delete data; });
|
|
755
|
+
return constructor.New({external});
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
NativeDataChannel(const Napi::CallbackInfo &info) : Napi::ObjectWrap<NativeDataChannel>(info) {
|
|
759
|
+
if (!info[0].IsExternal())
|
|
760
|
+
throw Napi::TypeError::New(info.Env(), "NativeDataChannel requires a native binding");
|
|
761
|
+
binding_ = *info[0].As<Napi::External<std::shared_ptr<ChannelBinding>>>().Data();
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
private:
|
|
765
|
+
std::shared_ptr<ChannelBinding> binding_;
|
|
766
|
+
|
|
767
|
+
Napi::Value SendString(const Napi::CallbackInfo &info) {
|
|
768
|
+
Napi::Env env = info.Env();
|
|
769
|
+
try {
|
|
770
|
+
std::string value = info[0].ToString().Utf8Value();
|
|
771
|
+
bool sent = binding_->dataChannel->send(value);
|
|
772
|
+
return Napi::Boolean::New(env, sent);
|
|
773
|
+
} catch (const std::exception &e) {
|
|
774
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
775
|
+
return env.Undefined();
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
Napi::Value SendBinary(const Napi::CallbackInfo &info) {
|
|
780
|
+
Napi::Env env = info.Env();
|
|
781
|
+
try {
|
|
782
|
+
if (!info[0].IsTypedArray())
|
|
783
|
+
throw std::invalid_argument("sendBinary expects a Uint8Array");
|
|
784
|
+
auto view = info[0].As<Napi::Uint8Array>();
|
|
785
|
+
const auto *bytes = reinterpret_cast<const rtc::byte *>(view.Data());
|
|
786
|
+
bool sent = binding_->dataChannel->send(bytes, view.ByteLength());
|
|
787
|
+
return Napi::Boolean::New(env, sent);
|
|
788
|
+
} catch (const std::exception &e) {
|
|
789
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
790
|
+
return env.Undefined();
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
Napi::Value Close(const Napi::CallbackInfo &info) {
|
|
795
|
+
try {
|
|
796
|
+
binding_->Close();
|
|
797
|
+
} catch (const std::exception &e) {
|
|
798
|
+
Napi::Error::New(info.Env(), e.what()).ThrowAsJavaScriptException();
|
|
799
|
+
}
|
|
800
|
+
return info.Env().Undefined();
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
Napi::Value SetBufferedAmountLowThreshold(const Napi::CallbackInfo &info) {
|
|
804
|
+
Napi::Env env = info.Env();
|
|
805
|
+
try {
|
|
806
|
+
size_t value = info[0].ToNumber().Uint32Value();
|
|
807
|
+
binding_->dataChannel->setBufferedAmountLowThreshold(value);
|
|
808
|
+
} catch (const std::exception &e) {
|
|
809
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
810
|
+
}
|
|
811
|
+
return env.Undefined();
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
Napi::Value GetBindingId(const Napi::CallbackInfo &info) {
|
|
815
|
+
return Napi::Number::New(info.Env(), binding_->id);
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
Napi::Value GetId(const Napi::CallbackInfo &info) {
|
|
819
|
+
auto id = binding_->dataChannel->id();
|
|
820
|
+
if (!id)
|
|
821
|
+
return info.Env().Null();
|
|
822
|
+
return Napi::Number::New(info.Env(), *id);
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
Napi::Value GetLabel(const Napi::CallbackInfo &info) {
|
|
826
|
+
return Napi::String::New(info.Env(), binding_->dataChannel->label());
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
Napi::Value GetProtocol(const Napi::CallbackInfo &info) {
|
|
830
|
+
return Napi::String::New(info.Env(), binding_->dataChannel->protocol());
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
Napi::Value GetOrdered(const Napi::CallbackInfo &info) {
|
|
834
|
+
return Napi::Boolean::New(info.Env(), binding_->options.ordered);
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
Napi::Value GetNegotiated(const Napi::CallbackInfo &info) {
|
|
838
|
+
return Napi::Boolean::New(info.Env(), binding_->options.negotiated);
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
Napi::Value GetMaxPacketLifeTime(const Napi::CallbackInfo &info) {
|
|
842
|
+
if (!binding_->options.maxPacketLifeTime)
|
|
843
|
+
return info.Env().Null();
|
|
844
|
+
return Napi::Number::New(info.Env(), *binding_->options.maxPacketLifeTime);
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
Napi::Value GetMaxRetransmits(const Napi::CallbackInfo &info) {
|
|
848
|
+
if (!binding_->options.maxRetransmits)
|
|
849
|
+
return info.Env().Null();
|
|
850
|
+
return Napi::Number::New(info.Env(), *binding_->options.maxRetransmits);
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
Napi::Value GetBufferedAmount(const Napi::CallbackInfo &info) {
|
|
854
|
+
return Napi::Number::New(info.Env(), binding_->dataChannel->bufferedAmount());
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
Napi::Value GetIsOpen(const Napi::CallbackInfo &info) {
|
|
858
|
+
return Napi::Boolean::New(info.Env(), binding_->dataChannel->isOpen());
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
Napi::Value GetIsClosed(const Napi::CallbackInfo &info) {
|
|
862
|
+
return Napi::Boolean::New(info.Env(), binding_->dataChannel->isClosed());
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
Napi::Value GetMaxMessageSize(const Napi::CallbackInfo &info) {
|
|
866
|
+
return Napi::Number::New(info.Env(), binding_->dataChannel->maxMessageSize());
|
|
867
|
+
}
|
|
868
|
+
};
|
|
869
|
+
|
|
870
|
+
Napi::FunctionReference NativeDataChannel::constructor;
|
|
871
|
+
|
|
872
|
+
Napi::Object EventDispatcher::EventToObject(Napi::Env env, NativeEvent &event) {
|
|
873
|
+
Napi::Object object = Napi::Object::New(env);
|
|
874
|
+
object.Set("target", event.target);
|
|
875
|
+
object.Set("type", event.type);
|
|
876
|
+
if (event.channelId)
|
|
877
|
+
object.Set("channelId", event.channelId);
|
|
878
|
+
if (!event.state.empty())
|
|
879
|
+
object.Set("state", event.state);
|
|
880
|
+
if (!event.descriptionType.empty()) {
|
|
881
|
+
Napi::Object description = Napi::Object::New(env);
|
|
882
|
+
description.Set("type", event.descriptionType);
|
|
883
|
+
description.Set("sdp", event.sdp);
|
|
884
|
+
object.Set("description", description);
|
|
885
|
+
}
|
|
886
|
+
if (!event.candidate.empty() || !event.mid.empty()) {
|
|
887
|
+
Napi::Object candidate = Napi::Object::New(env);
|
|
888
|
+
candidate.Set("candidate", event.candidate);
|
|
889
|
+
if (!event.mid.empty())
|
|
890
|
+
candidate.Set("sdpMid", event.mid);
|
|
891
|
+
object.Set("candidate", candidate);
|
|
892
|
+
}
|
|
893
|
+
if (!event.error.empty())
|
|
894
|
+
object.Set("error", event.error);
|
|
895
|
+
if (event.type == "message") {
|
|
896
|
+
object.Set("binary", event.binary);
|
|
897
|
+
object.Set("data", MessagePayloadToValue(env, event));
|
|
898
|
+
}
|
|
899
|
+
if (event.channel) {
|
|
900
|
+
object.Set("channel", NativeDataChannel::NewInstance(env, event.channel));
|
|
901
|
+
object.Set("channelId", event.channel->id);
|
|
902
|
+
object.Set("channelReadyState", "open");
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
return object;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
Napi::Object CandidateToObject(Napi::Env env, const rtc::Candidate &candidate) {
|
|
909
|
+
Napi::Object object = Napi::Object::New(env);
|
|
910
|
+
object.Set("candidate", candidate.candidate());
|
|
911
|
+
object.Set("sdpMid", candidate.mid());
|
|
912
|
+
return object;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
void AppendIceServer(rtc::Configuration &config, const Napi::Object &server,
|
|
916
|
+
const Napi::Value &urlValue) {
|
|
917
|
+
if (!urlValue.IsString())
|
|
918
|
+
return;
|
|
919
|
+
|
|
920
|
+
rtc::IceServer iceServer(urlValue.ToString().Utf8Value());
|
|
921
|
+
if (iceServer.type == rtc::IceServer::Type::Turn) {
|
|
922
|
+
if (server.Has("username") && server.Get("username").IsString())
|
|
923
|
+
iceServer.username = server.Get("username").ToString().Utf8Value();
|
|
924
|
+
if (server.Has("credential") && server.Get("credential").IsString())
|
|
925
|
+
iceServer.password = server.Get("credential").ToString().Utf8Value();
|
|
926
|
+
}
|
|
927
|
+
config.iceServers.push_back(std::move(iceServer));
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
rtc::Configuration ParseConfiguration(const Napi::CallbackInfo &info) {
|
|
931
|
+
rtc::Configuration config;
|
|
932
|
+
config.disableAutoNegotiation = true;
|
|
933
|
+
config.disableAutoGathering = true;
|
|
934
|
+
|
|
935
|
+
if (info.Length() == 0 || !info[0].IsObject())
|
|
936
|
+
return config;
|
|
937
|
+
|
|
938
|
+
Napi::Object input = info[0].As<Napi::Object>();
|
|
939
|
+
if (input.Has("iceTransportPolicy")) {
|
|
940
|
+
std::string policy = input.Get("iceTransportPolicy").ToString().Utf8Value();
|
|
941
|
+
if (policy == "relay")
|
|
942
|
+
config.iceTransportPolicy = rtc::TransportPolicy::Relay;
|
|
943
|
+
}
|
|
944
|
+
if (input.Has("enableIceUdpMux") && input.Get("enableIceUdpMux").IsBoolean())
|
|
945
|
+
config.enableIceUdpMux = input.Get("enableIceUdpMux").ToBoolean().Value();
|
|
946
|
+
if (config.enableIceUdpMux) {
|
|
947
|
+
if (auto port = ActiveIceUdpMuxPort()) {
|
|
948
|
+
config.portRangeBegin = *port;
|
|
949
|
+
config.portRangeEnd = *port;
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
if (input.Has("disableFingerprintVerification") &&
|
|
953
|
+
input.Get("disableFingerprintVerification").IsBoolean())
|
|
954
|
+
config.disableFingerprintVerification =
|
|
955
|
+
input.Get("disableFingerprintVerification").ToBoolean().Value();
|
|
956
|
+
if (input.Has("maxMessageSize") && !input.Get("maxMessageSize").IsUndefined() &&
|
|
957
|
+
!input.Get("maxMessageSize").IsNull()) {
|
|
958
|
+
double value = input.Get("maxMessageSize").ToNumber().DoubleValue();
|
|
959
|
+
if (!std::isfinite(value) || value < 0 || std::floor(value) != value ||
|
|
960
|
+
value > static_cast<double>(std::numeric_limits<size_t>::max()))
|
|
961
|
+
throw std::invalid_argument("maxMessageSize must be a non-negative integer");
|
|
962
|
+
config.maxMessageSize = static_cast<size_t>(value);
|
|
963
|
+
}
|
|
964
|
+
if (input.Has("iceServers") && input.Get("iceServers").IsArray()) {
|
|
965
|
+
Napi::Array servers = input.Get("iceServers").As<Napi::Array>();
|
|
966
|
+
for (uint32_t i = 0; i < servers.Length(); ++i) {
|
|
967
|
+
Napi::Value value = servers.Get(i);
|
|
968
|
+
if (!value.IsObject())
|
|
969
|
+
continue;
|
|
970
|
+
Napi::Object server = value.As<Napi::Object>();
|
|
971
|
+
if (!server.Has("urls"))
|
|
972
|
+
continue;
|
|
973
|
+
Napi::Value urls = server.Get("urls");
|
|
974
|
+
if (urls.IsArray()) {
|
|
975
|
+
Napi::Array urlArray = urls.As<Napi::Array>();
|
|
976
|
+
for (uint32_t j = 0; j < urlArray.Length(); ++j) {
|
|
977
|
+
AppendIceServer(config, server, urlArray.Get(j));
|
|
978
|
+
}
|
|
979
|
+
} else if (urls.IsString()) {
|
|
980
|
+
AppendIceServer(config, server, urls);
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
if (input.Has("certificatePem") && input.Has("keyPem") &&
|
|
985
|
+
input.Get("certificatePem").IsString() && input.Get("keyPem").IsString()) {
|
|
986
|
+
config.certificatePemFile = input.Get("certificatePem").ToString().Utf8Value();
|
|
987
|
+
config.keyPemFile = input.Get("keyPem").ToString().Utf8Value();
|
|
988
|
+
} else if (input.Has("certificates") && input.Get("certificates").IsArray()) {
|
|
989
|
+
Napi::Array certificates = input.Get("certificates").As<Napi::Array>();
|
|
990
|
+
if (certificates.Length() > 0 && certificates.Get(uint32_t{0}).IsObject()) {
|
|
991
|
+
Napi::Object certificate = certificates.Get(uint32_t{0}).As<Napi::Object>();
|
|
992
|
+
if (certificate.Has("_certificatePem") && certificate.Has("_keyPem") &&
|
|
993
|
+
certificate.Get("_certificatePem").IsString() &&
|
|
994
|
+
certificate.Get("_keyPem").IsString()) {
|
|
995
|
+
config.certificatePemFile = certificate.Get("_certificatePem").ToString().Utf8Value();
|
|
996
|
+
config.keyPemFile = certificate.Get("_keyPem").ToString().Utf8Value();
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
return config;
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
ChannelOptions ParseChannelOptions(const Napi::Value &value) {
|
|
1005
|
+
ChannelOptions options;
|
|
1006
|
+
if (!value.IsObject())
|
|
1007
|
+
return options;
|
|
1008
|
+
|
|
1009
|
+
Napi::Object input = value.As<Napi::Object>();
|
|
1010
|
+
if (input.Has("ordered") && input.Get("ordered").IsBoolean())
|
|
1011
|
+
options.ordered = input.Get("ordered").ToBoolean().Value();
|
|
1012
|
+
if (input.Has("negotiated") && input.Get("negotiated").IsBoolean())
|
|
1013
|
+
options.negotiated = input.Get("negotiated").ToBoolean().Value();
|
|
1014
|
+
if (input.Has("protocol") && !input.Get("protocol").IsUndefined() &&
|
|
1015
|
+
!input.Get("protocol").IsNull())
|
|
1016
|
+
options.protocol = input.Get("protocol").ToString().Utf8Value();
|
|
1017
|
+
if (input.Has("id") && !input.Get("id").IsUndefined() && !input.Get("id").IsNull())
|
|
1018
|
+
options.id = static_cast<uint16_t>(input.Get("id").ToNumber().Uint32Value());
|
|
1019
|
+
if (input.Has("maxPacketLifeTime") && !input.Get("maxPacketLifeTime").IsUndefined() &&
|
|
1020
|
+
!input.Get("maxPacketLifeTime").IsNull())
|
|
1021
|
+
options.maxPacketLifeTime = input.Get("maxPacketLifeTime").ToNumber().Uint32Value();
|
|
1022
|
+
if (input.Has("maxRetransmits") && !input.Get("maxRetransmits").IsUndefined() &&
|
|
1023
|
+
!input.Get("maxRetransmits").IsNull())
|
|
1024
|
+
options.maxRetransmits = input.Get("maxRetransmits").ToNumber().Uint32Value();
|
|
1025
|
+
if (options.maxPacketLifeTime && options.maxRetransmits)
|
|
1026
|
+
throw std::invalid_argument("maxPacketLifeTime and maxRetransmits are mutually exclusive");
|
|
1027
|
+
return options;
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
rtc::DataChannelInit ToRtcInit(const ChannelOptions &options) {
|
|
1031
|
+
rtc::DataChannelInit init;
|
|
1032
|
+
init.negotiated = options.negotiated;
|
|
1033
|
+
init.protocol = options.protocol;
|
|
1034
|
+
if (options.id)
|
|
1035
|
+
init.id = *options.id;
|
|
1036
|
+
init.reliability.unordered = !options.ordered;
|
|
1037
|
+
if (options.maxPacketLifeTime)
|
|
1038
|
+
init.reliability.maxPacketLifeTime = std::chrono::milliseconds(*options.maxPacketLifeTime);
|
|
1039
|
+
if (options.maxRetransmits)
|
|
1040
|
+
init.reliability.maxRetransmits = *options.maxRetransmits;
|
|
1041
|
+
return init;
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
struct PeerBinding : public std::enable_shared_from_this<PeerBinding> {
|
|
1045
|
+
static std::shared_ptr<PeerBinding> Create(rtc::Configuration config,
|
|
1046
|
+
std::shared_ptr<EventDispatcher> dispatcher) {
|
|
1047
|
+
auto binding =
|
|
1048
|
+
std::shared_ptr<PeerBinding>(new PeerBinding(std::move(config), std::move(dispatcher)));
|
|
1049
|
+
binding->AttachCallbacks();
|
|
1050
|
+
return binding;
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
std::shared_ptr<ChannelBinding> AddChannel(std::shared_ptr<rtc::DataChannel> dataChannel,
|
|
1054
|
+
ChannelOptions options) {
|
|
1055
|
+
if (shutdown.load()) {
|
|
1056
|
+
CloseDataChannelForTeardown(dataChannel);
|
|
1057
|
+
return nullptr;
|
|
1058
|
+
}
|
|
1059
|
+
std::weak_ptr<PeerBinding> weak = shared_from_this();
|
|
1060
|
+
auto channel = ChannelBinding::Create(
|
|
1061
|
+
std::move(dataChannel), dispatcher, std::move(options),
|
|
1062
|
+
[weak](uint32_t id, const ChannelBinding *expected) {
|
|
1063
|
+
if (auto self = weak.lock())
|
|
1064
|
+
self->RemoveChannel(id, expected);
|
|
1065
|
+
});
|
|
1066
|
+
bool closeChannel = false;
|
|
1067
|
+
{
|
|
1068
|
+
std::lock_guard<std::mutex> lock(channelsMutex);
|
|
1069
|
+
if (shutdown.load())
|
|
1070
|
+
closeChannel = true;
|
|
1071
|
+
else
|
|
1072
|
+
channels[channel->id] = channel;
|
|
1073
|
+
}
|
|
1074
|
+
if (closeChannel) {
|
|
1075
|
+
channel->Destroy();
|
|
1076
|
+
CloseDataChannelForTeardown(channel->dataChannel);
|
|
1077
|
+
return nullptr;
|
|
1078
|
+
}
|
|
1079
|
+
if (channel->dataChannel->isClosed())
|
|
1080
|
+
RemoveChannel(channel->id, channel.get());
|
|
1081
|
+
return channel;
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
void ClosePeer() { ScheduleShutdown(); }
|
|
1085
|
+
|
|
1086
|
+
void Destroy() { ScheduleShutdown(); }
|
|
1087
|
+
|
|
1088
|
+
void DestroySync() {
|
|
1089
|
+
auto work = PrepareShutdown();
|
|
1090
|
+
if (work)
|
|
1091
|
+
RunPeerTeardown(std::move(*work));
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
std::shared_ptr<rtc::PeerConnection> peerConnection;
|
|
1095
|
+
std::shared_ptr<EventDispatcher> dispatcher;
|
|
1096
|
+
|
|
1097
|
+
private:
|
|
1098
|
+
PeerBinding(rtc::Configuration config, std::shared_ptr<EventDispatcher> dispatcher_)
|
|
1099
|
+
: peerConnection(std::make_shared<rtc::PeerConnection>(std::move(config))),
|
|
1100
|
+
dispatcher(std::move(dispatcher_)) {}
|
|
1101
|
+
|
|
1102
|
+
void Emit(NativeEvent event) {
|
|
1103
|
+
std::lock_guard<std::mutex> lock(callbacksMutex);
|
|
1104
|
+
if (!callbacksActive)
|
|
1105
|
+
return;
|
|
1106
|
+
dispatcher->Emit(std::move(event));
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
void DeactivateCallbacks() {
|
|
1110
|
+
{
|
|
1111
|
+
std::lock_guard<std::mutex> lock(callbacksMutex);
|
|
1112
|
+
if (!callbacksActive)
|
|
1113
|
+
return;
|
|
1114
|
+
callbacksActive = false;
|
|
1115
|
+
}
|
|
1116
|
+
if (peerConnection)
|
|
1117
|
+
peerConnection->resetCallbacks();
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
void RemoveChannel(uint32_t id, const ChannelBinding *expected) {
|
|
1121
|
+
std::lock_guard<std::mutex> lock(channelsMutex);
|
|
1122
|
+
auto found = channels.find(id);
|
|
1123
|
+
if (found != channels.end() && found->second.get() == expected)
|
|
1124
|
+
channels.erase(found);
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
std::optional<PeerTeardownWork> PrepareShutdown() {
|
|
1128
|
+
if (shutdown.exchange(true))
|
|
1129
|
+
return std::nullopt;
|
|
1130
|
+
|
|
1131
|
+
std::vector<std::shared_ptr<ChannelBinding>> channelSnapshot;
|
|
1132
|
+
{
|
|
1133
|
+
std::lock_guard<std::mutex> lock(channelsMutex);
|
|
1134
|
+
channelSnapshot.reserve(channels.size());
|
|
1135
|
+
for (auto &[_, channel] : channels)
|
|
1136
|
+
channelSnapshot.push_back(channel);
|
|
1137
|
+
channels.clear();
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
PeerTeardownWork work;
|
|
1141
|
+
work.dataChannels.reserve(channelSnapshot.size());
|
|
1142
|
+
for (auto &channel : channelSnapshot) {
|
|
1143
|
+
channel->Destroy();
|
|
1144
|
+
if (channel->dataChannel)
|
|
1145
|
+
work.dataChannels.push_back(channel->dataChannel);
|
|
1146
|
+
}
|
|
1147
|
+
DeactivateCallbacks();
|
|
1148
|
+
dispatcher->Close();
|
|
1149
|
+
work.peerConnection = std::move(peerConnection);
|
|
1150
|
+
return work;
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
void ScheduleShutdown() {
|
|
1154
|
+
auto work = PrepareShutdown();
|
|
1155
|
+
if (!work)
|
|
1156
|
+
return;
|
|
1157
|
+
|
|
1158
|
+
std::thread([work = std::move(*work)]() mutable {
|
|
1159
|
+
RunPeerTeardown(std::move(work));
|
|
1160
|
+
}).detach();
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
void AttachCallbacks() {
|
|
1164
|
+
std::weak_ptr<PeerBinding> weak = shared_from_this();
|
|
1165
|
+
|
|
1166
|
+
peerConnection->onLocalDescription([weak](rtc::Description description) {
|
|
1167
|
+
if (auto self = weak.lock()) {
|
|
1168
|
+
NativeEvent event;
|
|
1169
|
+
event.target = "peerconnection";
|
|
1170
|
+
event.type = "localdescription";
|
|
1171
|
+
event.descriptionType = description.typeString();
|
|
1172
|
+
event.sdp = std::string(description);
|
|
1173
|
+
self->Emit(std::move(event));
|
|
1174
|
+
}
|
|
1175
|
+
});
|
|
1176
|
+
|
|
1177
|
+
peerConnection->onLocalCandidate([weak](rtc::Candidate candidate) {
|
|
1178
|
+
if (auto self = weak.lock()) {
|
|
1179
|
+
NativeEvent event;
|
|
1180
|
+
event.target = "peerconnection";
|
|
1181
|
+
event.type = "localcandidate";
|
|
1182
|
+
event.candidate = candidate.candidate();
|
|
1183
|
+
event.mid = candidate.mid();
|
|
1184
|
+
self->Emit(std::move(event));
|
|
1185
|
+
}
|
|
1186
|
+
});
|
|
1187
|
+
|
|
1188
|
+
peerConnection->onStateChange([weak](rtc::PeerConnection::State state) {
|
|
1189
|
+
if (auto self = weak.lock()) {
|
|
1190
|
+
NativeEvent event;
|
|
1191
|
+
event.target = "peerconnection";
|
|
1192
|
+
event.type = "connectionstatechange";
|
|
1193
|
+
event.state = ToString(state);
|
|
1194
|
+
self->Emit(std::move(event));
|
|
1195
|
+
}
|
|
1196
|
+
});
|
|
1197
|
+
|
|
1198
|
+
peerConnection->onIceStateChange([weak](rtc::PeerConnection::IceState state) {
|
|
1199
|
+
if (auto self = weak.lock()) {
|
|
1200
|
+
NativeEvent event;
|
|
1201
|
+
event.target = "peerconnection";
|
|
1202
|
+
event.type = "iceconnectionstatechange";
|
|
1203
|
+
event.state = ToString(state);
|
|
1204
|
+
self->Emit(std::move(event));
|
|
1205
|
+
}
|
|
1206
|
+
});
|
|
1207
|
+
|
|
1208
|
+
peerConnection->onGatheringStateChange([weak](rtc::PeerConnection::GatheringState state) {
|
|
1209
|
+
if (auto self = weak.lock()) {
|
|
1210
|
+
NativeEvent event;
|
|
1211
|
+
event.target = "peerconnection";
|
|
1212
|
+
event.type = "icegatheringstatechange";
|
|
1213
|
+
event.state = ToString(state);
|
|
1214
|
+
self->Emit(std::move(event));
|
|
1215
|
+
}
|
|
1216
|
+
});
|
|
1217
|
+
|
|
1218
|
+
peerConnection->onSignalingStateChange([weak](rtc::PeerConnection::SignalingState state) {
|
|
1219
|
+
if (auto self = weak.lock()) {
|
|
1220
|
+
NativeEvent event;
|
|
1221
|
+
event.target = "peerconnection";
|
|
1222
|
+
event.type = "signalingstatechange";
|
|
1223
|
+
event.state = ToString(state);
|
|
1224
|
+
self->Emit(std::move(event));
|
|
1225
|
+
}
|
|
1226
|
+
});
|
|
1227
|
+
|
|
1228
|
+
peerConnection->onDataChannel([weak](std::shared_ptr<rtc::DataChannel> dataChannel) {
|
|
1229
|
+
if (auto self = weak.lock()) {
|
|
1230
|
+
auto channel =
|
|
1231
|
+
self->AddChannel(dataChannel, ChannelBinding::IncomingOptions(dataChannel));
|
|
1232
|
+
if (!channel)
|
|
1233
|
+
return;
|
|
1234
|
+
NativeEvent event;
|
|
1235
|
+
event.target = "peerconnection";
|
|
1236
|
+
event.type = "datachannel";
|
|
1237
|
+
event.channelId = channel->id;
|
|
1238
|
+
event.channel = std::move(channel);
|
|
1239
|
+
self->Emit(std::move(event));
|
|
1240
|
+
}
|
|
1241
|
+
});
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
std::atomic<bool> shutdown{false};
|
|
1245
|
+
bool callbacksActive = true;
|
|
1246
|
+
std::mutex callbacksMutex;
|
|
1247
|
+
std::mutex channelsMutex;
|
|
1248
|
+
std::unordered_map<uint32_t, std::shared_ptr<ChannelBinding>> channels;
|
|
1249
|
+
};
|
|
1250
|
+
|
|
1251
|
+
std::mutex &PeerRegistryMutex() {
|
|
1252
|
+
static std::mutex mutex;
|
|
1253
|
+
return mutex;
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
std::vector<std::weak_ptr<PeerBinding>> &PeerRegistry() {
|
|
1257
|
+
static std::vector<std::weak_ptr<PeerBinding>> registry;
|
|
1258
|
+
return registry;
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
void RegisterPeerBinding(const std::shared_ptr<PeerBinding> &binding) {
|
|
1262
|
+
std::lock_guard<std::mutex> lock(PeerRegistryMutex());
|
|
1263
|
+
auto ®istry = PeerRegistry();
|
|
1264
|
+
registry.erase(std::remove_if(registry.begin(), registry.end(),
|
|
1265
|
+
[](const auto &entry) { return entry.expired(); }),
|
|
1266
|
+
registry.end());
|
|
1267
|
+
registry.push_back(binding);
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
void CloseAllPeerBindings() {
|
|
1271
|
+
std::vector<std::shared_ptr<PeerBinding>> bindings;
|
|
1272
|
+
{
|
|
1273
|
+
std::lock_guard<std::mutex> lock(PeerRegistryMutex());
|
|
1274
|
+
for (auto &entry : PeerRegistry()) {
|
|
1275
|
+
if (auto binding = entry.lock())
|
|
1276
|
+
bindings.push_back(std::move(binding));
|
|
1277
|
+
}
|
|
1278
|
+
PeerRegistry().clear();
|
|
1279
|
+
}
|
|
1280
|
+
for (auto &binding : bindings)
|
|
1281
|
+
binding->DestroySync();
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
class NativePeerConnection : public Napi::ObjectWrap<NativePeerConnection> {
|
|
1285
|
+
public:
|
|
1286
|
+
static Napi::FunctionReference constructor;
|
|
1287
|
+
|
|
1288
|
+
static void Init(Napi::Env env, Napi::Object exports) {
|
|
1289
|
+
Napi::Function func = DefineClass(
|
|
1290
|
+
env, "NativePeerConnection",
|
|
1291
|
+
{
|
|
1292
|
+
InstanceMethod("createDataChannel", &NativePeerConnection::CreateDataChannel),
|
|
1293
|
+
InstanceMethod("createOffer", &NativePeerConnection::CreateOffer),
|
|
1294
|
+
InstanceMethod("createAnswer", &NativePeerConnection::CreateAnswer),
|
|
1295
|
+
InstanceMethod("setLocalDescription", &NativePeerConnection::SetLocalDescription),
|
|
1296
|
+
InstanceMethod("setRemoteDescription", &NativePeerConnection::SetRemoteDescription),
|
|
1297
|
+
InstanceMethod("addRemoteCandidate", &NativePeerConnection::AddRemoteCandidate),
|
|
1298
|
+
InstanceMethod("gatherLocalCandidates", &NativePeerConnection::GatherLocalCandidates),
|
|
1299
|
+
InstanceMethod("localDescription", &NativePeerConnection::LocalDescription),
|
|
1300
|
+
InstanceMethod("remoteDescription", &NativePeerConnection::RemoteDescription),
|
|
1301
|
+
InstanceMethod("remoteFingerprint", &NativePeerConnection::RemoteFingerprint),
|
|
1302
|
+
InstanceMethod("selectedCandidatePair", &NativePeerConnection::SelectedCandidatePair),
|
|
1303
|
+
InstanceMethod("close", &NativePeerConnection::Close),
|
|
1304
|
+
InstanceAccessor("connectionState", &NativePeerConnection::GetConnectionState, nullptr),
|
|
1305
|
+
InstanceAccessor("iceConnectionState", &NativePeerConnection::GetIceConnectionState,
|
|
1306
|
+
nullptr),
|
|
1307
|
+
InstanceAccessor("iceGatheringState", &NativePeerConnection::GetIceGatheringState,
|
|
1308
|
+
nullptr),
|
|
1309
|
+
InstanceAccessor("signalingState", &NativePeerConnection::GetSignalingState, nullptr),
|
|
1310
|
+
InstanceAccessor("remoteMaxMessageSize",
|
|
1311
|
+
&NativePeerConnection::GetRemoteMaxMessageSize, nullptr),
|
|
1312
|
+
InstanceAccessor("maxDataChannelId", &NativePeerConnection::GetMaxDataChannelId,
|
|
1313
|
+
nullptr),
|
|
1314
|
+
});
|
|
1315
|
+
constructor = Napi::Persistent(func);
|
|
1316
|
+
constructor.SuppressDestruct();
|
|
1317
|
+
exports.Set("NativePeerConnection", func);
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
NativePeerConnection(const Napi::CallbackInfo &info)
|
|
1321
|
+
: Napi::ObjectWrap<NativePeerConnection>(info) {
|
|
1322
|
+
Napi::Env env = info.Env();
|
|
1323
|
+
if (info.Length() < 2 || !info[1].IsFunction())
|
|
1324
|
+
throw Napi::TypeError::New(env, "NativePeerConnection requires an event callback");
|
|
1325
|
+
auto dispatcher = EventDispatcher::Create(env, info[1].As<Napi::Function>());
|
|
1326
|
+
binding_ = PeerBinding::Create(ParseConfiguration(info), dispatcher);
|
|
1327
|
+
RegisterPeerBinding(binding_);
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
~NativePeerConnection() override {
|
|
1331
|
+
if (binding_)
|
|
1332
|
+
binding_->Destroy();
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
private:
|
|
1336
|
+
std::shared_ptr<PeerBinding> binding_;
|
|
1337
|
+
|
|
1338
|
+
Napi::Value CreateDataChannel(const Napi::CallbackInfo &info) {
|
|
1339
|
+
Napi::Env env = info.Env();
|
|
1340
|
+
try {
|
|
1341
|
+
std::string label = info[0].ToString().Utf8Value();
|
|
1342
|
+
ChannelOptions options =
|
|
1343
|
+
ParseChannelOptions(info.Length() > 1 ? info[1] : env.Undefined());
|
|
1344
|
+
auto dataChannel =
|
|
1345
|
+
binding_->peerConnection->createDataChannel(label, ToRtcInit(options));
|
|
1346
|
+
auto channel = binding_->AddChannel(std::move(dataChannel), std::move(options));
|
|
1347
|
+
return NativeDataChannel::NewInstance(env, std::move(channel));
|
|
1348
|
+
} catch (const std::exception &e) {
|
|
1349
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
1350
|
+
return env.Undefined();
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
Napi::Value CreateOffer(const Napi::CallbackInfo &info) {
|
|
1355
|
+
Napi::Env env = info.Env();
|
|
1356
|
+
try {
|
|
1357
|
+
return DescriptionToObject(env, binding_->peerConnection->createOffer());
|
|
1358
|
+
} catch (const std::exception &e) {
|
|
1359
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
1360
|
+
return env.Undefined();
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
Napi::Value CreateAnswer(const Napi::CallbackInfo &info) {
|
|
1365
|
+
Napi::Env env = info.Env();
|
|
1366
|
+
try {
|
|
1367
|
+
return DescriptionToObject(env, binding_->peerConnection->createAnswer());
|
|
1368
|
+
} catch (const std::exception &e) {
|
|
1369
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
1370
|
+
return env.Undefined();
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
Napi::Value SetLocalDescription(const Napi::CallbackInfo &info) {
|
|
1375
|
+
Napi::Env env = info.Env();
|
|
1376
|
+
try {
|
|
1377
|
+
std::string type;
|
|
1378
|
+
if (info.Length() > 0 && !info[0].IsUndefined() && !info[0].IsNull())
|
|
1379
|
+
type = info[0].ToString().Utf8Value();
|
|
1380
|
+
rtc::LocalDescriptionInit init;
|
|
1381
|
+
if (info.Length() > 1)
|
|
1382
|
+
init = ParseLocalDescriptionInit(info[1]);
|
|
1383
|
+
binding_->peerConnection->setLocalDescription(ParseDescriptionType(type), init);
|
|
1384
|
+
return env.Undefined();
|
|
1385
|
+
} catch (const std::exception &e) {
|
|
1386
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
1387
|
+
return env.Undefined();
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
Napi::Value SetRemoteDescription(const Napi::CallbackInfo &info) {
|
|
1392
|
+
Napi::Env env = info.Env();
|
|
1393
|
+
try {
|
|
1394
|
+
Napi::Object object = info[0].As<Napi::Object>();
|
|
1395
|
+
std::string type = object.Get("type").ToString().Utf8Value();
|
|
1396
|
+
std::string sdp = object.Get("sdp").ToString().Utf8Value();
|
|
1397
|
+
binding_->peerConnection->setRemoteDescription(rtc::Description(sdp, type));
|
|
1398
|
+
return env.Undefined();
|
|
1399
|
+
} catch (const std::exception &e) {
|
|
1400
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
1401
|
+
return env.Undefined();
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
Napi::Value AddRemoteCandidate(const Napi::CallbackInfo &info) {
|
|
1406
|
+
Napi::Env env = info.Env();
|
|
1407
|
+
try {
|
|
1408
|
+
Napi::Object object = info[0].As<Napi::Object>();
|
|
1409
|
+
std::string candidate = object.Get("candidate").ToString().Utf8Value();
|
|
1410
|
+
std::string mid;
|
|
1411
|
+
if (object.Has("sdpMid") && !object.Get("sdpMid").IsNull() &&
|
|
1412
|
+
!object.Get("sdpMid").IsUndefined())
|
|
1413
|
+
mid = object.Get("sdpMid").ToString().Utf8Value();
|
|
1414
|
+
binding_->peerConnection->addRemoteCandidate(rtc::Candidate(candidate, mid));
|
|
1415
|
+
return env.Undefined();
|
|
1416
|
+
} catch (const std::exception &e) {
|
|
1417
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
1418
|
+
return env.Undefined();
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
Napi::Value GatherLocalCandidates(const Napi::CallbackInfo &info) {
|
|
1423
|
+
Napi::Env env = info.Env();
|
|
1424
|
+
try {
|
|
1425
|
+
binding_->peerConnection->gatherLocalCandidates();
|
|
1426
|
+
} catch (const std::exception &e) {
|
|
1427
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
1428
|
+
}
|
|
1429
|
+
return env.Undefined();
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
Napi::Value LocalDescription(const Napi::CallbackInfo &info) {
|
|
1433
|
+
Napi::Env env = info.Env();
|
|
1434
|
+
try {
|
|
1435
|
+
auto description = binding_->peerConnection->localDescription();
|
|
1436
|
+
if (!description)
|
|
1437
|
+
return env.Null();
|
|
1438
|
+
return DescriptionToObject(env, *description);
|
|
1439
|
+
} catch (const std::exception &e) {
|
|
1440
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
1441
|
+
return env.Undefined();
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1445
|
+
Napi::Value RemoteDescription(const Napi::CallbackInfo &info) {
|
|
1446
|
+
Napi::Env env = info.Env();
|
|
1447
|
+
try {
|
|
1448
|
+
auto description = binding_->peerConnection->remoteDescription();
|
|
1449
|
+
if (!description)
|
|
1450
|
+
return env.Null();
|
|
1451
|
+
return DescriptionToObject(env, *description);
|
|
1452
|
+
} catch (const std::exception &e) {
|
|
1453
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
1454
|
+
return env.Undefined();
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
Napi::Value RemoteFingerprint(const Napi::CallbackInfo &info) {
|
|
1459
|
+
Napi::Env env = info.Env();
|
|
1460
|
+
try {
|
|
1461
|
+
auto fingerprint = binding_->peerConnection->remoteFingerprint();
|
|
1462
|
+
if (!fingerprint.isValid())
|
|
1463
|
+
return env.Null();
|
|
1464
|
+
Napi::Object result = Napi::Object::New(env);
|
|
1465
|
+
result.Set("algorithm",
|
|
1466
|
+
rtc::CertificateFingerprint::AlgorithmIdentifier(fingerprint.algorithm));
|
|
1467
|
+
result.Set("value", fingerprint.value);
|
|
1468
|
+
return result;
|
|
1469
|
+
} catch (const std::exception &e) {
|
|
1470
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
1471
|
+
return env.Undefined();
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
Napi::Value SelectedCandidatePair(const Napi::CallbackInfo &info) {
|
|
1476
|
+
Napi::Env env = info.Env();
|
|
1477
|
+
try {
|
|
1478
|
+
rtc::Candidate local;
|
|
1479
|
+
rtc::Candidate remote;
|
|
1480
|
+
if (!binding_->peerConnection->getSelectedCandidatePair(&local, &remote))
|
|
1481
|
+
return env.Null();
|
|
1482
|
+
Napi::Object pair = Napi::Object::New(env);
|
|
1483
|
+
pair.Set("local", CandidateToObject(env, local));
|
|
1484
|
+
pair.Set("remote", CandidateToObject(env, remote));
|
|
1485
|
+
return pair;
|
|
1486
|
+
} catch (const std::exception &e) {
|
|
1487
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
1488
|
+
return env.Undefined();
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
Napi::Value Close(const Napi::CallbackInfo &info) {
|
|
1493
|
+
try {
|
|
1494
|
+
binding_->ClosePeer();
|
|
1495
|
+
} catch (const std::exception &e) {
|
|
1496
|
+
Napi::Error::New(info.Env(), e.what()).ThrowAsJavaScriptException();
|
|
1497
|
+
}
|
|
1498
|
+
return info.Env().Undefined();
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
Napi::Value GetConnectionState(const Napi::CallbackInfo &info) {
|
|
1502
|
+
return Napi::String::New(info.Env(), ToString(binding_->peerConnection->state()));
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
Napi::Value GetIceConnectionState(const Napi::CallbackInfo &info) {
|
|
1506
|
+
return Napi::String::New(info.Env(), ToString(binding_->peerConnection->iceState()));
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
Napi::Value GetIceGatheringState(const Napi::CallbackInfo &info) {
|
|
1510
|
+
return Napi::String::New(info.Env(), ToString(binding_->peerConnection->gatheringState()));
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1513
|
+
Napi::Value GetSignalingState(const Napi::CallbackInfo &info) {
|
|
1514
|
+
return Napi::String::New(info.Env(), ToString(binding_->peerConnection->signalingState()));
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
Napi::Value GetRemoteMaxMessageSize(const Napi::CallbackInfo &info) {
|
|
1518
|
+
return Napi::Number::New(info.Env(), binding_->peerConnection->remoteMaxMessageSize());
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
Napi::Value GetMaxDataChannelId(const Napi::CallbackInfo &info) {
|
|
1522
|
+
return Napi::Number::New(info.Env(), binding_->peerConnection->maxDataChannelId());
|
|
1523
|
+
}
|
|
1524
|
+
};
|
|
1525
|
+
|
|
1526
|
+
Napi::FunctionReference NativePeerConnection::constructor;
|
|
1527
|
+
|
|
1528
|
+
Napi::Value GenerateCertificate(const Napi::CallbackInfo &info) {
|
|
1529
|
+
Napi::Env env = info.Env();
|
|
1530
|
+
try {
|
|
1531
|
+
if (info.Length() == 0 || !info[0].IsObject())
|
|
1532
|
+
throw std::invalid_argument("generateCertificate requires an options object");
|
|
1533
|
+
Napi::Object options = info[0].As<Napi::Object>();
|
|
1534
|
+
std::string algorithm = options.Get("algorithm").ToString().Utf8Value();
|
|
1535
|
+
uint32_t modulusLength = options.Has("modulusLength")
|
|
1536
|
+
? options.Get("modulusLength").ToNumber().Uint32Value()
|
|
1537
|
+
: 2048;
|
|
1538
|
+
double expiresMs =
|
|
1539
|
+
options.Has("expiresMs") ? options.Get("expiresMs").ToNumber().DoubleValue()
|
|
1540
|
+
: 30.0 * 24.0 * 60.0 * 60.0 * 1000.0;
|
|
1541
|
+
|
|
1542
|
+
auto material =
|
|
1543
|
+
webrtc_node::GenerateCertificateMaterial(algorithm, modulusLength, expiresMs);
|
|
1544
|
+
Napi::Object result = Napi::Object::New(env);
|
|
1545
|
+
result.Set("certificatePem", material.certificatePem);
|
|
1546
|
+
result.Set("keyPem", material.keyPem);
|
|
1547
|
+
Napi::Array fingerprints = Napi::Array::New(env, 1);
|
|
1548
|
+
Napi::Object fingerprint = Napi::Object::New(env);
|
|
1549
|
+
fingerprint.Set("algorithm", "sha-256");
|
|
1550
|
+
fingerprint.Set("value", material.fingerprint);
|
|
1551
|
+
fingerprints.Set(uint32_t{0}, fingerprint);
|
|
1552
|
+
result.Set("fingerprints", fingerprints);
|
|
1553
|
+
return result;
|
|
1554
|
+
} catch (const std::exception &e) {
|
|
1555
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
1556
|
+
return env.Undefined();
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
|
|
1560
|
+
Napi::Value ImportCertificate(const Napi::CallbackInfo &info) {
|
|
1561
|
+
Napi::Env env = info.Env();
|
|
1562
|
+
try {
|
|
1563
|
+
if (info.Length() == 0 || !info[0].IsObject())
|
|
1564
|
+
throw std::invalid_argument("importCertificate requires an options object");
|
|
1565
|
+
Napi::Object options = info[0].As<Napi::Object>();
|
|
1566
|
+
if (!options.Has("certificatePem") || !options.Get("certificatePem").IsString())
|
|
1567
|
+
throw std::invalid_argument("certificatePem must be a string");
|
|
1568
|
+
if (!options.Has("keyPem") || !options.Get("keyPem").IsString())
|
|
1569
|
+
throw std::invalid_argument("keyPem must be a string");
|
|
1570
|
+
|
|
1571
|
+
auto material = webrtc_node::ImportCertificateMaterial(
|
|
1572
|
+
options.Get("certificatePem").ToString().Utf8Value(),
|
|
1573
|
+
options.Get("keyPem").ToString().Utf8Value());
|
|
1574
|
+
Napi::Object result = Napi::Object::New(env);
|
|
1575
|
+
result.Set("certificatePem", material.certificatePem);
|
|
1576
|
+
result.Set("keyPem", material.keyPem);
|
|
1577
|
+
result.Set("expires", material.expires);
|
|
1578
|
+
Napi::Array fingerprints = Napi::Array::New(env, 1);
|
|
1579
|
+
Napi::Object fingerprint = Napi::Object::New(env);
|
|
1580
|
+
fingerprint.Set("algorithm", "sha-256");
|
|
1581
|
+
fingerprint.Set("value", material.fingerprint);
|
|
1582
|
+
fingerprints.Set(uint32_t{0}, fingerprint);
|
|
1583
|
+
result.Set("fingerprints", fingerprints);
|
|
1584
|
+
return result;
|
|
1585
|
+
} catch (const std::exception &e) {
|
|
1586
|
+
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
|
|
1587
|
+
return env.Undefined();
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
void ConfigureLibDataChannelLogging() {
|
|
1592
|
+
const char *value = std::getenv("WEBRTC_NODE_LIBDATACHANNEL_LOG");
|
|
1593
|
+
if (!value)
|
|
1594
|
+
return;
|
|
1595
|
+
|
|
1596
|
+
std::string level(value);
|
|
1597
|
+
if (level == "verbose")
|
|
1598
|
+
rtc::InitLogger(rtc::LogLevel::Verbose);
|
|
1599
|
+
else if (level == "debug")
|
|
1600
|
+
rtc::InitLogger(rtc::LogLevel::Debug);
|
|
1601
|
+
else if (level == "info")
|
|
1602
|
+
rtc::InitLogger(rtc::LogLevel::Info);
|
|
1603
|
+
else if (level == "warning")
|
|
1604
|
+
rtc::InitLogger(rtc::LogLevel::Warning);
|
|
1605
|
+
else if (level == "error")
|
|
1606
|
+
rtc::InitLogger(rtc::LogLevel::Error);
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
void CleanupNative() {
|
|
1610
|
+
CloseAllPeerBindings();
|
|
1611
|
+
CloseAllIceUdpMuxBindings();
|
|
1612
|
+
rtc::Cleanup().wait();
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
Napi::Object InitAll(Napi::Env env, Napi::Object exports) {
|
|
1616
|
+
ConfigureLibDataChannelLogging();
|
|
1617
|
+
NativeDataChannel::Init(env, exports);
|
|
1618
|
+
NativeIceUdpMuxListener::Init(env, exports);
|
|
1619
|
+
NativePeerConnection::Init(env, exports);
|
|
1620
|
+
exports.Set("generateCertificate", Napi::Function::New(env, GenerateCertificate));
|
|
1621
|
+
exports.Set("importCertificate", Napi::Function::New(env, ImportCertificate));
|
|
1622
|
+
env.AddCleanupHook([]() { CleanupNative(); });
|
|
1623
|
+
exports.Set("cleanup", Napi::Function::New(env, [](const Napi::CallbackInfo &info) {
|
|
1624
|
+
CleanupNative();
|
|
1625
|
+
return info.Env().Undefined();
|
|
1626
|
+
}));
|
|
1627
|
+
return exports;
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1630
|
+
} // namespace
|
|
1631
|
+
|
|
1632
|
+
NODE_API_MODULE(webrtc_node, InitAll)
|