peerconnection.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. /**
  2. * Copyright (c) 2019 Paul-Louis Ageneau
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include "peerconnection.hpp"
  19. #include "certificate.hpp"
  20. #include "dtlstransport.hpp"
  21. #include "icetransport.hpp"
  22. #include "include.hpp"
  23. #include "sctptransport.hpp"
  24. #if RTC_ENABLE_MEDIA
  25. #include "dtlssrtptransport.hpp"
  26. #endif
  27. #include <thread>
  28. namespace rtc {
  29. using namespace std::placeholders;
  30. using std::shared_ptr;
  31. using std::weak_ptr;
  32. PeerConnection::PeerConnection() : PeerConnection(Configuration()) {}
  33. PeerConnection::PeerConnection(const Configuration &config)
  34. : mConfig(config), mCertificate(make_certificate()), mState(State::New),
  35. mGatheringState(GatheringState::New) {
  36. PLOG_VERBOSE << "Creating PeerConnection";
  37. if (config.portRangeEnd && config.portRangeBegin > config.portRangeEnd)
  38. throw std::invalid_argument("Invalid port range");
  39. }
  40. PeerConnection::~PeerConnection() {
  41. close();
  42. PLOG_VERBOSE << "Destroying PeerConnection";
  43. }
  44. void PeerConnection::close() {
  45. PLOG_VERBOSE << "Closing PeerConnection";
  46. closeDataChannels();
  47. closeTransports();
  48. }
  49. const Configuration *PeerConnection::config() const { return &mConfig; }
  50. PeerConnection::State PeerConnection::state() const { return mState; }
  51. PeerConnection::GatheringState PeerConnection::gatheringState() const { return mGatheringState; }
  52. std::optional<Description> PeerConnection::localDescription() const {
  53. std::lock_guard lock(mLocalDescriptionMutex);
  54. return mLocalDescription;
  55. }
  56. std::optional<Description> PeerConnection::remoteDescription() const {
  57. std::lock_guard lock(mRemoteDescriptionMutex);
  58. return mRemoteDescription;
  59. }
  60. void PeerConnection::setLocalDescription(std::optional<Description> description) {
  61. if (auto iceTransport = std::atomic_load(&mIceTransport)) {
  62. throw std::logic_error("Local description is already set");
  63. } else {
  64. // RFC 5763: The endpoint that is the offerer MUST use the setup attribute value of
  65. // setup:actpass.
  66. // See https://tools.ietf.org/html/rfc5763#section-5
  67. iceTransport = initIceTransport(Description::Role::ActPass);
  68. Description localDescription = iceTransport->getLocalDescription(Description::Type::Offer);
  69. if (description)
  70. localDescription.addMedia(*description);
  71. processLocalDescription(localDescription);
  72. iceTransport->gatherLocalCandidates();
  73. }
  74. }
  75. void PeerConnection::setRemoteDescription(Description description) {
  76. description.hintType(localDescription() ? Description::Type::Answer : Description::Type::Offer);
  77. auto remoteCandidates = description.extractCandidates();
  78. std::lock_guard lock(mRemoteDescriptionMutex);
  79. mRemoteDescription.emplace(std::move(description));
  80. auto iceTransport = std::atomic_load(&mIceTransport);
  81. if (!iceTransport)
  82. iceTransport = initIceTransport(Description::Role::ActPass);
  83. iceTransport->setRemoteDescription(*mRemoteDescription);
  84. if (mRemoteDescription->type() == Description::Type::Offer) {
  85. // This is an offer and we are the answerer.
  86. Description localDescription = iceTransport->getLocalDescription(Description::Type::Answer);
  87. localDescription.addMedia(description); // blindly accept media
  88. processLocalDescription(localDescription);
  89. iceTransport->gatherLocalCandidates();
  90. } else {
  91. // This is an answer and we are the offerer.
  92. auto sctpTransport = std::atomic_load(&mSctpTransport);
  93. if (!sctpTransport && iceTransport->role() == Description::Role::Active) {
  94. // Since we assumed passive role during DataChannel creation, we need to shift the
  95. // stream numbers by one to shift them from odd to even.
  96. std::unique_lock lock(mDataChannelsMutex); // we are going to swap the container
  97. decltype(mDataChannels) newDataChannels;
  98. auto it = mDataChannels.begin();
  99. while (it != mDataChannels.end()) {
  100. auto channel = it->second.lock();
  101. if (channel->stream() % 2 == 1)
  102. channel->mStream -= 1;
  103. newDataChannels.emplace(channel->stream(), channel);
  104. ++it;
  105. }
  106. std::swap(mDataChannels, newDataChannels);
  107. }
  108. }
  109. for (const auto &candidate : remoteCandidates)
  110. addRemoteCandidate(candidate);
  111. }
  112. void PeerConnection::addRemoteCandidate(Candidate candidate) {
  113. auto iceTransport = std::atomic_load(&mIceTransport);
  114. if (!mRemoteDescription || !iceTransport)
  115. throw std::logic_error("Remote candidate set without remote description");
  116. if (candidate.resolve(Candidate::ResolveMode::Simple)) {
  117. iceTransport->addRemoteCandidate(candidate);
  118. } else {
  119. // OK, we might need a lookup, do it asynchronously
  120. weak_ptr<IceTransport> weakIceTransport{iceTransport};
  121. std::thread t([weakIceTransport, candidate]() mutable {
  122. if (candidate.resolve(Candidate::ResolveMode::Lookup))
  123. if (auto iceTransport = weakIceTransport.lock())
  124. iceTransport->addRemoteCandidate(candidate);
  125. });
  126. t.detach();
  127. }
  128. std::lock_guard lock(mRemoteDescriptionMutex);
  129. mRemoteDescription->addCandidate(candidate);
  130. }
  131. std::optional<string> PeerConnection::localAddress() const {
  132. auto iceTransport = std::atomic_load(&mIceTransport);
  133. return iceTransport ? iceTransport->getLocalAddress() : nullopt;
  134. }
  135. std::optional<string> PeerConnection::remoteAddress() const {
  136. auto iceTransport = std::atomic_load(&mIceTransport);
  137. return iceTransport ? iceTransport->getRemoteAddress() : nullopt;
  138. }
  139. shared_ptr<DataChannel> PeerConnection::createDataChannel(const string &label,
  140. const string &protocol,
  141. const Reliability &reliability) {
  142. // RFC 5763: The answerer MUST use either a setup attribute value of setup:active or
  143. // setup:passive. [...] Thus, setup:active is RECOMMENDED.
  144. // See https://tools.ietf.org/html/rfc5763#section-5
  145. // Therefore, we assume passive role when we are the offerer.
  146. auto iceTransport = std::atomic_load(&mIceTransport);
  147. auto role = iceTransport ? iceTransport->role() : Description::Role::Passive;
  148. auto channel = emplaceDataChannel(role, label, protocol, reliability);
  149. if (!iceTransport) {
  150. // RFC 5763: The endpoint that is the offerer MUST use the setup attribute value of
  151. // setup:actpass.
  152. // See https://tools.ietf.org/html/rfc5763#section-5
  153. iceTransport = initIceTransport(Description::Role::ActPass);
  154. processLocalDescription(iceTransport->getLocalDescription(Description::Type::Offer));
  155. iceTransport->gatherLocalCandidates();
  156. } else {
  157. if (auto transport = std::atomic_load(&mSctpTransport))
  158. if (transport->state() == SctpTransport::State::Connected)
  159. channel->open(transport);
  160. }
  161. return channel;
  162. }
  163. void PeerConnection::onDataChannel(
  164. std::function<void(shared_ptr<DataChannel> dataChannel)> callback) {
  165. mDataChannelCallback = callback;
  166. }
  167. void PeerConnection::onLocalDescription(
  168. std::function<void(const Description &description)> callback) {
  169. mLocalDescriptionCallback = callback;
  170. }
  171. void PeerConnection::onLocalCandidate(std::function<void(const Candidate &candidate)> callback) {
  172. mLocalCandidateCallback = callback;
  173. }
  174. void PeerConnection::onStateChange(std::function<void(State state)> callback) {
  175. mStateChangeCallback = callback;
  176. }
  177. void PeerConnection::onGatheringStateChange(std::function<void(GatheringState state)> callback) {
  178. mGatheringStateChangeCallback = callback;
  179. }
  180. bool PeerConnection::hasMedia() const {
  181. auto local = localDescription();
  182. auto remote = remoteDescription();
  183. return (local && local->hasMedia()) || (remote && remote->hasMedia());
  184. }
  185. void PeerConnection::sendMedia(const binary &packet) {
  186. outgoingMedia(make_message(packet.begin(), packet.end(), Message::Binary));
  187. }
  188. void PeerConnection::send(const byte *packet, size_t size) {
  189. outgoingMedia(make_message(packet, packet + size, Message::Binary));
  190. }
  191. void PeerConnection::onMedia(std::function<void(const binary &packet)> callback) {
  192. mMediaCallback = callback;
  193. }
  194. void PeerConnection::outgoingMedia(message_ptr message) {
  195. if (!hasMedia())
  196. throw std::runtime_error("PeerConnection has no media support");
  197. #if RTC_ENABLE_MEDIA
  198. auto transport = std::atomic_load(&mDtlsTransport);
  199. if (!transport)
  200. throw std::runtime_error("PeerConnection is not open");
  201. std::dynamic_pointer_cast<DtlsSrtpTransport>(transport)->send(message);
  202. #else
  203. PLOG_WARNING << "Ignoring sent media (not compiled with SRTP support)";
  204. #endif
  205. }
  206. shared_ptr<IceTransport> PeerConnection::initIceTransport(Description::Role role) {
  207. try {
  208. if (auto transport = std::atomic_load(&mIceTransport))
  209. return transport;
  210. auto transport = std::make_shared<IceTransport>(
  211. mConfig, role, weak_bind(&PeerConnection::processLocalCandidate, this, _1),
  212. [this, weak_this = weak_from_this()](IceTransport::State state) {
  213. auto shared_this = weak_this.lock();
  214. if (!shared_this)
  215. return;
  216. switch (state) {
  217. case IceTransport::State::Connecting:
  218. changeState(State::Connecting);
  219. break;
  220. case IceTransport::State::Failed:
  221. changeState(State::Failed);
  222. break;
  223. case IceTransport::State::Connected:
  224. initDtlsTransport();
  225. break;
  226. case IceTransport::State::Disconnected:
  227. changeState(State::Disconnected);
  228. break;
  229. default:
  230. // Ignore
  231. break;
  232. }
  233. },
  234. [this, weak_this = weak_from_this()](IceTransport::GatheringState state) {
  235. auto shared_this = weak_this.lock();
  236. if (!shared_this)
  237. return;
  238. switch (state) {
  239. case IceTransport::GatheringState::InProgress:
  240. changeGatheringState(GatheringState::InProgress);
  241. break;
  242. case IceTransport::GatheringState::Complete:
  243. endLocalCandidates();
  244. changeGatheringState(GatheringState::Complete);
  245. break;
  246. default:
  247. // Ignore
  248. break;
  249. }
  250. });
  251. std::atomic_store(&mIceTransport, transport);
  252. if (mState == State::Closed) {
  253. mIceTransport.reset();
  254. transport->stop();
  255. throw std::runtime_error("Connection is closed");
  256. }
  257. return transport;
  258. } catch (const std::exception &e) {
  259. PLOG_ERROR << e.what();
  260. changeState(State::Failed);
  261. throw std::runtime_error("ICE transport initialization failed");
  262. }
  263. }
  264. shared_ptr<DtlsTransport> PeerConnection::initDtlsTransport() {
  265. try {
  266. if (auto transport = std::atomic_load(&mDtlsTransport))
  267. return transport;
  268. auto certificate = mCertificate.get();
  269. auto lower = std::atomic_load(&mIceTransport);
  270. auto verifierCallback = weak_bind(&PeerConnection::checkFingerprint, this, _1);
  271. auto stateChangeCallback = [this,
  272. weak_this = weak_from_this()](DtlsTransport::State state) {
  273. auto shared_this = weak_this.lock();
  274. if (!shared_this)
  275. return;
  276. switch (state) {
  277. case DtlsTransport::State::Connected:
  278. initSctpTransport();
  279. break;
  280. case DtlsTransport::State::Failed:
  281. changeState(State::Failed);
  282. break;
  283. case DtlsTransport::State::Disconnected:
  284. changeState(State::Disconnected);
  285. break;
  286. default:
  287. // Ignore
  288. break;
  289. }
  290. };
  291. shared_ptr<DtlsTransport> transport;
  292. if (hasMedia()) {
  293. #if RTC_ENABLE_MEDIA
  294. PLOG_INFO << "This connection requires media support";
  295. // DTLS-SRTP
  296. transport = std::make_shared<DtlsSrtpTransport>(
  297. lower, certificate, verifierCallback,
  298. std::bind(&PeerConnection::forwardMedia, this, _1), stateChangeCallback);
  299. #else
  300. PLOG_WARNING << "Ignoring media support (not compiled with SRTP support)";
  301. #endif
  302. }
  303. if (!transport) {
  304. // DTLS only
  305. transport = std::make_shared<DtlsTransport>(lower, certificate, verifierCallback,
  306. stateChangeCallback);
  307. }
  308. std::atomic_store(&mDtlsTransport, transport);
  309. if (mState == State::Closed) {
  310. mDtlsTransport.reset();
  311. transport->stop();
  312. throw std::runtime_error("Connection is closed");
  313. }
  314. return transport;
  315. } catch (const std::exception &e) {
  316. PLOG_ERROR << e.what();
  317. changeState(State::Failed);
  318. throw std::runtime_error("DTLS transport initialization failed");
  319. }
  320. }
  321. shared_ptr<SctpTransport> PeerConnection::initSctpTransport() {
  322. try {
  323. if (auto transport = std::atomic_load(&mSctpTransport))
  324. return transport;
  325. uint16_t sctpPort = remoteDescription()->sctpPort().value_or(DEFAULT_SCTP_PORT);
  326. auto lower = std::atomic_load(&mDtlsTransport);
  327. auto transport = std::make_shared<SctpTransport>(
  328. lower, sctpPort, weak_bind(&PeerConnection::forwardMessage, this, _1),
  329. weak_bind(&PeerConnection::forwardBufferedAmount, this, _1, _2),
  330. [this, weak_this = weak_from_this()](SctpTransport::State state) {
  331. auto shared_this = weak_this.lock();
  332. if (!shared_this)
  333. return;
  334. switch (state) {
  335. case SctpTransport::State::Connected:
  336. changeState(State::Connected);
  337. openDataChannels();
  338. break;
  339. case SctpTransport::State::Failed:
  340. LOG_WARNING << "SCTP transport failed";
  341. remoteCloseDataChannels();
  342. #if RTC_ENABLE_MEDIA
  343. // Ignore SCTP failure if media is present
  344. if (!hasMedia())
  345. changeState(State::Failed);
  346. #else
  347. changeState(State::Failed);
  348. #endif
  349. break;
  350. case SctpTransport::State::Disconnected:
  351. remoteCloseDataChannels();
  352. changeState(State::Disconnected);
  353. break;
  354. default:
  355. // Ignore
  356. break;
  357. }
  358. });
  359. std::atomic_store(&mSctpTransport, transport);
  360. if (mState == State::Closed) {
  361. mSctpTransport.reset();
  362. transport->stop();
  363. throw std::runtime_error("Connection is closed");
  364. }
  365. return transport;
  366. } catch (const std::exception &e) {
  367. PLOG_ERROR << e.what();
  368. changeState(State::Failed);
  369. throw std::runtime_error("SCTP transport initialization failed");
  370. }
  371. }
  372. void PeerConnection::closeTransports() {
  373. PLOG_VERBOSE << "Closing transports";
  374. // Change state to sink state Closed to block init methods
  375. changeState(State::Closed);
  376. // Reset callbacks now that state is changed
  377. resetCallbacks();
  378. // Pass the references to a thread, allowing to terminate a transport from its own thread
  379. auto sctp = std::atomic_exchange(&mSctpTransport, decltype(mSctpTransport)(nullptr));
  380. auto dtls = std::atomic_exchange(&mDtlsTransport, decltype(mDtlsTransport)(nullptr));
  381. auto ice = std::atomic_exchange(&mIceTransport, decltype(mIceTransport)(nullptr));
  382. if (sctp || dtls || ice) {
  383. std::thread t([sctp, dtls, ice, token = mInitToken]() mutable {
  384. if (sctp)
  385. sctp->stop();
  386. if (dtls)
  387. dtls->stop();
  388. if (ice)
  389. ice->stop();
  390. sctp.reset();
  391. dtls.reset();
  392. ice.reset();
  393. });
  394. t.detach();
  395. }
  396. }
  397. void PeerConnection::endLocalCandidates() {
  398. std::lock_guard lock(mLocalDescriptionMutex);
  399. if (mLocalDescription)
  400. mLocalDescription->endCandidates();
  401. }
  402. bool PeerConnection::checkFingerprint(const std::string &fingerprint) const {
  403. std::lock_guard lock(mRemoteDescriptionMutex);
  404. if (auto expectedFingerprint =
  405. mRemoteDescription ? mRemoteDescription->fingerprint() : nullopt) {
  406. return *expectedFingerprint == fingerprint;
  407. }
  408. return false;
  409. }
  410. void PeerConnection::forwardMessage(message_ptr message) {
  411. if (!message) {
  412. remoteCloseDataChannels();
  413. return;
  414. }
  415. auto channel = findDataChannel(message->stream);
  416. auto iceTransport = std::atomic_load(&mIceTransport);
  417. auto sctpTransport = std::atomic_load(&mSctpTransport);
  418. if (!iceTransport || !sctpTransport)
  419. return;
  420. if (!channel) {
  421. const byte dataChannelOpenMessage{0x03};
  422. unsigned int remoteParity = (iceTransport->role() == Description::Role::Active) ? 1 : 0;
  423. if (message->type == Message::Control && *message->data() == dataChannelOpenMessage &&
  424. message->stream % 2 == remoteParity) {
  425. channel =
  426. std::make_shared<DataChannel>(shared_from_this(), sctpTransport, message->stream);
  427. channel->onOpen(weak_bind(&PeerConnection::triggerDataChannel, this,
  428. weak_ptr<DataChannel>{channel}));
  429. mDataChannels.insert(std::make_pair(message->stream, channel));
  430. } else {
  431. // Invalid, close the DataChannel
  432. sctpTransport->close(message->stream);
  433. return;
  434. }
  435. }
  436. channel->incoming(message);
  437. }
  438. void PeerConnection::forwardMedia(message_ptr message) {
  439. if (message)
  440. mMediaCallback(*message);
  441. }
  442. void PeerConnection::forwardBufferedAmount(uint16_t stream, size_t amount) {
  443. if (auto channel = findDataChannel(stream))
  444. channel->triggerBufferedAmount(amount);
  445. }
  446. shared_ptr<DataChannel> PeerConnection::emplaceDataChannel(Description::Role role,
  447. const string &label,
  448. const string &protocol,
  449. const Reliability &reliability) {
  450. // The active side must use streams with even identifiers, whereas the passive side must use
  451. // streams with odd identifiers.
  452. // See https://tools.ietf.org/html/draft-ietf-rtcweb-data-protocol-09#section-6
  453. std::unique_lock lock(mDataChannelsMutex); // we are going to emplace
  454. unsigned int stream = (role == Description::Role::Active) ? 0 : 1;
  455. while (mDataChannels.find(stream) != mDataChannels.end()) {
  456. stream += 2;
  457. if (stream >= 65535)
  458. throw std::runtime_error("Too many DataChannels");
  459. }
  460. auto channel =
  461. std::make_shared<DataChannel>(shared_from_this(), stream, label, protocol, reliability);
  462. mDataChannels.emplace(std::make_pair(stream, channel));
  463. return channel;
  464. }
  465. shared_ptr<DataChannel> PeerConnection::findDataChannel(uint16_t stream) {
  466. std::shared_lock lock(mDataChannelsMutex); // read-only
  467. if (auto it = mDataChannels.find(stream); it != mDataChannels.end())
  468. if (auto channel = it->second.lock())
  469. return channel;
  470. return nullptr;
  471. }
  472. void PeerConnection::iterateDataChannels(
  473. std::function<void(shared_ptr<DataChannel> channel)> func) {
  474. // Iterate
  475. {
  476. std::shared_lock lock(mDataChannelsMutex); // read-only
  477. auto it = mDataChannels.begin();
  478. while (it != mDataChannels.end()) {
  479. auto channel = it->second.lock();
  480. if (channel && !channel->isClosed())
  481. func(channel);
  482. ++it;
  483. }
  484. }
  485. // Cleanup
  486. {
  487. std::unique_lock lock(mDataChannelsMutex); // we are going to erase
  488. auto it = mDataChannels.begin();
  489. while (it != mDataChannels.end()) {
  490. if (!it->second.lock()) {
  491. it = mDataChannels.erase(it);
  492. continue;
  493. }
  494. ++it;
  495. }
  496. }
  497. }
  498. void PeerConnection::openDataChannels() {
  499. if (auto transport = std::atomic_load(&mSctpTransport))
  500. iterateDataChannels([&](shared_ptr<DataChannel> channel) { channel->open(transport); });
  501. }
  502. void PeerConnection::closeDataChannels() {
  503. iterateDataChannels([&](shared_ptr<DataChannel> channel) { channel->close(); });
  504. }
  505. void PeerConnection::remoteCloseDataChannels() {
  506. iterateDataChannels([&](shared_ptr<DataChannel> channel) { channel->remoteClose(); });
  507. }
  508. void PeerConnection::processLocalDescription(Description description) {
  509. std::optional<uint16_t> remoteSctpPort;
  510. if (auto remote = remoteDescription())
  511. remoteSctpPort = remote->sctpPort();
  512. auto certificate = mCertificate.get(); // wait for certificate if not ready
  513. std::lock_guard lock(mLocalDescriptionMutex);
  514. mLocalDescription.emplace(std::move(description));
  515. mLocalDescription->setFingerprint(certificate->fingerprint());
  516. mLocalDescription->setSctpPort(remoteSctpPort.value_or(DEFAULT_SCTP_PORT));
  517. mLocalDescription->setMaxMessageSize(LOCAL_MAX_MESSAGE_SIZE);
  518. mLocalDescriptionCallback(*mLocalDescription);
  519. }
  520. void PeerConnection::processLocalCandidate(Candidate candidate) {
  521. std::lock_guard lock(mLocalDescriptionMutex);
  522. if (!mLocalDescription)
  523. throw std::logic_error("Got a local candidate without local description");
  524. mLocalDescription->addCandidate(candidate);
  525. mLocalCandidateCallback(candidate);
  526. }
  527. void PeerConnection::triggerDataChannel(weak_ptr<DataChannel> weakDataChannel) {
  528. auto dataChannel = weakDataChannel.lock();
  529. if (!dataChannel)
  530. return;
  531. mDataChannelCallback(dataChannel);
  532. }
  533. bool PeerConnection::changeState(State state) {
  534. State current;
  535. do {
  536. current = mState.load();
  537. if (current == state)
  538. return true;
  539. if (current == State::Closed)
  540. return false;
  541. } while (!mState.compare_exchange_weak(current, state));
  542. mStateChangeCallback(state);
  543. return true;
  544. }
  545. bool PeerConnection::changeGatheringState(GatheringState state) {
  546. if (mGatheringState.exchange(state) != state)
  547. mGatheringStateChangeCallback(state);
  548. return true;
  549. }
  550. void PeerConnection::resetCallbacks() {
  551. // Unregister all callbacks
  552. mDataChannelCallback = nullptr;
  553. mLocalDescriptionCallback = nullptr;
  554. mLocalCandidateCallback = nullptr;
  555. mStateChangeCallback = nullptr;
  556. mGatheringStateChangeCallback = nullptr;
  557. }
  558. bool PeerConnection::getSelectedCandidatePair(CandidateInfo *local, CandidateInfo *remote) {
  559. #if not USE_JUICE
  560. auto iceTransport = std::atomic_load(&mIceTransport);
  561. return iceTransport->getSelectedCandidatePair(local, remote);
  562. #else
  563. PLOG_WARNING << "getSelectedCandidatePair is not implemented for libjuice";
  564. return false;
  565. #endif
  566. }
  567. void PeerConnection::clearStats() {
  568. auto sctpTransport = std::atomic_load(&mSctpTransport);
  569. if (sctpTransport)
  570. return sctpTransport->clearStats();
  571. }
  572. size_t PeerConnection::bytesSent() {
  573. auto sctpTransport = std::atomic_load(&mSctpTransport);
  574. if (sctpTransport)
  575. return sctpTransport->bytesSent();
  576. return 0;
  577. }
  578. size_t PeerConnection::bytesReceived() {
  579. auto sctpTransport = std::atomic_load(&mSctpTransport);
  580. if (sctpTransport)
  581. return sctpTransport->bytesReceived();
  582. return 0;
  583. }
  584. std::optional<std::chrono::milliseconds> PeerConnection::rtt() {
  585. auto sctpTransport = std::atomic_load(&mSctpTransport);
  586. if (sctpTransport)
  587. return sctpTransport->rtt();
  588. PLOG_WARNING << "Could not load sctpTransport";
  589. return std::nullopt;
  590. }
  591. } // namespace rtc
  592. std::ostream &operator<<(std::ostream &out, const rtc::PeerConnection::State &state) {
  593. using State = rtc::PeerConnection::State;
  594. std::string str;
  595. switch (state) {
  596. case State::New:
  597. str = "new";
  598. break;
  599. case State::Connecting:
  600. str = "connecting";
  601. break;
  602. case State::Connected:
  603. str = "connected";
  604. break;
  605. case State::Disconnected:
  606. str = "disconnected";
  607. break;
  608. case State::Failed:
  609. str = "failed";
  610. break;
  611. case State::Closed:
  612. str = "closed";
  613. break;
  614. default:
  615. str = "unknown";
  616. break;
  617. }
  618. return out << str;
  619. }
  620. std::ostream &operator<<(std::ostream &out, const rtc::PeerConnection::GatheringState &state) {
  621. using GatheringState = rtc::PeerConnection::GatheringState;
  622. std::string str;
  623. switch (state) {
  624. case GatheringState::New:
  625. str = "new";
  626. break;
  627. case GatheringState::InProgress:
  628. str = "in_progress";
  629. break;
  630. case GatheringState::Complete:
  631. str = "complete";
  632. break;
  633. default:
  634. str = "unknown";
  635. break;
  636. }
  637. return out << str;
  638. }