peerconnection.cpp 23 KB

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