forked from paullouisageneau/libdatachannel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpeerconnection.cpp
464 lines (389 loc) · 13.4 KB
/
peerconnection.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
/**
* Copyright (c) 2019 Paul-Louis Ageneau
* Copyright (c) 2020 Filip Klembara (in2core)
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
#include "peerconnection.hpp"
#include "common.hpp"
#include "rtp.hpp"
#include "impl/certificate.hpp"
#include "impl/dtlstransport.hpp"
#include "impl/icetransport.hpp"
#include "impl/internals.hpp"
#include "impl/peerconnection.hpp"
#include "impl/sctptransport.hpp"
#include "impl/threadpool.hpp"
#include "impl/track.hpp"
#if RTC_ENABLE_MEDIA
#include "impl/dtlssrtptransport.hpp"
#endif
#include <iomanip>
#include <set>
#include <thread>
using namespace std::placeholders;
namespace rtc {
PeerConnection::PeerConnection() : PeerConnection(Configuration()) {}
PeerConnection::PeerConnection(Configuration config)
: CheshireCat<impl::PeerConnection>(std::move(config)) {}
PeerConnection::~PeerConnection() {
try {
impl()->remoteClose();
} catch (const std::exception &e) {
PLOG_ERROR << e.what();
}
}
void PeerConnection::close() { impl()->close(); }
const Configuration *PeerConnection::config() const { return &impl()->config; }
PeerConnection::State PeerConnection::state() const { return impl()->state; }
PeerConnection::IceState PeerConnection::iceState() const { return impl()->iceState; }
PeerConnection::GatheringState PeerConnection::gatheringState() const {
return impl()->gatheringState;
}
PeerConnection::SignalingState PeerConnection::signalingState() const {
return impl()->signalingState;
}
optional<Description> PeerConnection::localDescription() const {
return impl()->localDescription();
}
optional<Description> PeerConnection::remoteDescription() const {
return impl()->remoteDescription();
}
size_t PeerConnection::remoteMaxMessageSize() const { return impl()->remoteMaxMessageSize(); }
bool PeerConnection::hasMedia() const {
auto local = localDescription();
return local && local->hasAudioOrVideo();
}
void PeerConnection::setLocalDescription(Description::Type type) {
std::unique_lock signalingLock(impl()->signalingMutex);
PLOG_VERBOSE << "Setting local description, type=" << Description::typeToString(type);
SignalingState signalingState = impl()->signalingState.load();
if (type == Description::Type::Rollback) {
if (signalingState == SignalingState::HaveLocalOffer ||
signalingState == SignalingState::HaveLocalPranswer) {
impl()->rollbackLocalDescription();
impl()->changeSignalingState(SignalingState::Stable);
}
return;
}
// Guess the description type if unspecified
if (type == Description::Type::Unspec) {
if (signalingState == SignalingState::HaveRemoteOffer)
type = Description::Type::Answer;
else
type = Description::Type::Offer;
}
// Only a local offer resets the negotiation needed flag
if (type == Description::Type::Offer && !impl()->negotiationNeeded.exchange(false)) {
PLOG_DEBUG << "No negotiation needed";
return;
}
// Get the new signaling state
SignalingState newSignalingState;
switch (signalingState) {
case SignalingState::Stable:
if (type != Description::Type::Offer) {
std::ostringstream oss;
oss << "Unexpected local desciption type " << type << " in signaling state "
<< signalingState;
throw std::logic_error(oss.str());
}
newSignalingState = SignalingState::HaveLocalOffer;
break;
case SignalingState::HaveRemoteOffer:
case SignalingState::HaveLocalPranswer:
if (type != Description::Type::Answer && type != Description::Type::Pranswer) {
std::ostringstream oss;
oss << "Unexpected local description type " << type
<< " description in signaling state " << signalingState;
throw std::logic_error(oss.str());
}
newSignalingState = SignalingState::Stable;
break;
default: {
std::ostringstream oss;
oss << "Unexpected local description in signaling state " << signalingState << ", ignoring";
LOG_WARNING << oss.str();
return;
}
}
auto iceTransport = impl()->initIceTransport();
if (!iceTransport)
return; // closed
Description local = iceTransport->getLocalDescription(type);
impl()->processLocalDescription(std::move(local));
impl()->changeSignalingState(newSignalingState);
signalingLock.unlock();
if (impl()->gatheringState == GatheringState::New) {
iceTransport->gatherLocalCandidates(impl()->localBundleMid());
}
}
void PeerConnection::setRemoteDescription(Description description) {
std::unique_lock signalingLock(impl()->signalingMutex);
PLOG_VERBOSE << "Setting remote description: " << string(description);
if (description.type() == Description::Type::Rollback) {
// This is mostly useless because we accept any offer
PLOG_VERBOSE << "Rolling back pending remote description";
impl()->changeSignalingState(SignalingState::Stable);
return;
}
impl()->validateRemoteDescription(description);
// Get the new signaling state
SignalingState signalingState = impl()->signalingState.load();
SignalingState newSignalingState;
switch (signalingState) {
case SignalingState::Stable:
description.hintType(Description::Type::Offer);
if (description.type() != Description::Type::Offer) {
std::ostringstream oss;
oss << "Unexpected remote " << description.type() << " description in signaling state "
<< signalingState;
throw std::logic_error(oss.str());
}
newSignalingState = SignalingState::HaveRemoteOffer;
break;
case SignalingState::HaveLocalOffer:
description.hintType(Description::Type::Answer);
if (description.type() == Description::Type::Offer) {
// The ICE agent will automatically initiate a rollback when a peer that had previously
// created an offer receives an offer from the remote peer
impl()->rollbackLocalDescription();
impl()->changeSignalingState(SignalingState::Stable);
signalingState = SignalingState::Stable;
newSignalingState = SignalingState::HaveRemoteOffer;
break;
}
if (description.type() != Description::Type::Answer &&
description.type() != Description::Type::Pranswer) {
std::ostringstream oss;
oss << "Unexpected remote " << description.type() << " description in signaling state "
<< signalingState;
throw std::logic_error(oss.str());
}
newSignalingState = SignalingState::Stable;
break;
case SignalingState::HaveRemotePranswer:
description.hintType(Description::Type::Answer);
if (description.type() != Description::Type::Answer &&
description.type() != Description::Type::Pranswer) {
std::ostringstream oss;
oss << "Unexpected remote " << description.type() << " description in signaling state "
<< signalingState;
throw std::logic_error(oss.str());
}
newSignalingState = SignalingState::Stable;
break;
default: {
std::ostringstream oss;
oss << "Unexpected remote description in signaling state " << signalingState;
throw std::logic_error(oss.str());
}
}
// Candidates will be added at the end, extract them for now
auto remoteCandidates = description.extractCandidates();
auto type = description.type();
auto iceTransport = impl()->initIceTransport();
if (!iceTransport)
return; // closed
iceTransport->setRemoteDescription(description); // ICE transport might reject the description
impl()->processRemoteDescription(std::move(description));
impl()->changeSignalingState(newSignalingState);
signalingLock.unlock();
if (type == Description::Type::Offer) {
// This is an offer, we need to answer
if (!impl()->config.disableAutoNegotiation)
setLocalDescription(Description::Type::Answer);
}
for (const auto &candidate : remoteCandidates)
addRemoteCandidate(candidate);
}
void PeerConnection::addRemoteCandidate(Candidate candidate) {
std::unique_lock signalingLock(impl()->signalingMutex);
PLOG_VERBOSE << "Adding remote candidate: " << string(candidate);
impl()->processRemoteCandidate(std::move(candidate));
}
void PeerConnection::setMediaHandler(shared_ptr<MediaHandler> handler) {
impl()->setMediaHandler(std::move(handler));
};
shared_ptr<MediaHandler> PeerConnection::getMediaHandler() { return impl()->getMediaHandler(); };
optional<string> PeerConnection::localAddress() const {
auto iceTransport = impl()->getIceTransport();
return iceTransport ? iceTransport->getLocalAddress() : nullopt;
}
optional<string> PeerConnection::remoteAddress() const {
auto iceTransport = impl()->getIceTransport();
return iceTransport ? iceTransport->getRemoteAddress() : nullopt;
}
uint16_t PeerConnection::maxDataChannelId() const { return impl()->maxDataChannelStream(); }
shared_ptr<DataChannel> PeerConnection::createDataChannel(string label, DataChannelInit init) {
auto channelImpl = impl()->emplaceDataChannel(std::move(label), std::move(init));
auto channel = std::make_shared<DataChannel>(channelImpl);
// Renegotiation is needed iff the current local description does not have application
auto local = impl()->localDescription();
if (!local || !local->hasApplication())
impl()->negotiationNeeded = true;
if (!impl()->config.disableAutoNegotiation)
setLocalDescription();
return channel;
}
void PeerConnection::onDataChannel(
std::function<void(shared_ptr<DataChannel> dataChannel)> callback) {
impl()->dataChannelCallback = callback;
impl()->flushPendingDataChannels();
}
std::shared_ptr<Track> PeerConnection::addTrack(Description::Media description) {
auto trackImpl = impl()->emplaceTrack(std::move(description));
auto track = std::make_shared<Track>(trackImpl);
// Renegotiation is needed for the new or updated track
impl()->negotiationNeeded = true;
return track;
}
void PeerConnection::onTrack(std::function<void(std::shared_ptr<Track>)> callback) {
impl()->trackCallback = callback;
impl()->flushPendingTracks();
}
void PeerConnection::onLocalDescription(std::function<void(Description description)> callback) {
impl()->localDescriptionCallback = callback;
}
void PeerConnection::onLocalCandidate(std::function<void(Candidate candidate)> callback) {
impl()->localCandidateCallback = callback;
}
void PeerConnection::onStateChange(std::function<void(State state)> callback) {
impl()->stateChangeCallback = callback;
}
void PeerConnection::onIceStateChange(std::function<void(IceState state)> callback) {
impl()->iceStateChangeCallback = callback;
}
void PeerConnection::onGatheringStateChange(std::function<void(GatheringState state)> callback) {
impl()->gatheringStateChangeCallback = callback;
}
void PeerConnection::onSignalingStateChange(std::function<void(SignalingState state)> callback) {
impl()->signalingStateChangeCallback = callback;
}
void PeerConnection::resetCallbacks() { impl()->resetCallbacks(); }
bool PeerConnection::getSelectedCandidatePair(Candidate *local, Candidate *remote) {
auto iceTransport = impl()->getIceTransport();
return iceTransport ? iceTransport->getSelectedCandidatePair(local, remote) : false;
}
void PeerConnection::clearStats() {
if (auto sctpTransport = impl()->getSctpTransport())
return sctpTransport->clearStats();
}
size_t PeerConnection::bytesSent() {
auto sctpTransport = impl()->getSctpTransport();
return sctpTransport ? sctpTransport->bytesSent() : 0;
}
size_t PeerConnection::bytesReceived() {
auto sctpTransport = impl()->getSctpTransport();
return sctpTransport ? sctpTransport->bytesReceived() : 0;
}
optional<std::chrono::milliseconds> PeerConnection::rtt() {
auto sctpTransport = impl()->getSctpTransport();
return sctpTransport ? sctpTransport->rtt() : nullopt;
}
} // namespace rtc
std::ostream &operator<<(std::ostream &out, rtc::PeerConnection::State state) {
using State = rtc::PeerConnection::State;
const char *str;
switch (state) {
case State::New:
str = "new";
break;
case State::Connecting:
str = "connecting";
break;
case State::Connected:
str = "connected";
break;
case State::Disconnected:
str = "disconnected";
break;
case State::Failed:
str = "failed";
break;
case State::Closed:
str = "closed";
break;
default:
str = "unknown";
break;
}
return out << str;
}
std::ostream &operator<<(std::ostream &out, rtc::PeerConnection::IceState state) {
using IceState = rtc::PeerConnection::IceState;
const char *str;
switch (state) {
case IceState::New:
str = "new";
break;
case IceState::Checking:
str = "checking";
break;
case IceState::Connected:
str = "connected";
break;
case IceState::Completed:
str = "completed";
break;
case IceState::Failed:
str = "failed";
break;
case IceState::Disconnected:
str = "disconnected";
break;
case IceState::Closed:
str = "closed";
break;
default:
str = "unknown";
break;
}
return out << str;
}
std::ostream &operator<<(std::ostream &out, rtc::PeerConnection::GatheringState state) {
using GatheringState = rtc::PeerConnection::GatheringState;
const char *str;
switch (state) {
case GatheringState::New:
str = "new";
break;
case GatheringState::InProgress:
str = "in-progress";
break;
case GatheringState::Complete:
str = "complete";
break;
default:
str = "unknown";
break;
}
return out << str;
}
std::ostream &operator<<(std::ostream &out, rtc::PeerConnection::SignalingState state) {
using SignalingState = rtc::PeerConnection::SignalingState;
const char *str;
switch (state) {
case SignalingState::Stable:
str = "stable";
break;
case SignalingState::HaveLocalOffer:
str = "have-local-offer";
break;
case SignalingState::HaveRemoteOffer:
str = "have-remote-offer";
break;
case SignalingState::HaveLocalPranswer:
str = "have-local-pranswer";
break;
case SignalingState::HaveRemotePranswer:
str = "have-remote-pranswer";
break;
default:
str = "unknown";
break;
}
return out << str;
}