peerconnection.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. /**
  2. * Copyright (c) 2019 Paul-Louis Ageneau
  3. * Copyright (c) 2020 Filip Klembara (in2core)
  4. *
  5. * This library is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Lesser General Public
  7. * License as published by the Free Software Foundation; either
  8. * version 2.1 of the License, or (at your option) any later version.
  9. *
  10. * This library is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public
  16. * License along with this library; if not, write to the Free Software
  17. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  18. */
  19. #include "peerconnection.hpp"
  20. #include "common.hpp"
  21. #include "rtp.hpp"
  22. #include "impl/certificate.hpp"
  23. #include "impl/dtlstransport.hpp"
  24. #include "impl/icetransport.hpp"
  25. #include "impl/internals.hpp"
  26. #include "impl/peerconnection.hpp"
  27. #include "impl/processor.hpp"
  28. #include "impl/sctptransport.hpp"
  29. #include "impl/threadpool.hpp"
  30. #include "impl/track.hpp"
  31. #if RTC_ENABLE_MEDIA
  32. #include "impl/dtlssrtptransport.hpp"
  33. #endif
  34. #include <iomanip>
  35. #include <set>
  36. #include <thread>
  37. using namespace std::placeholders;
  38. namespace rtc {
  39. PeerConnection::PeerConnection() : PeerConnection(Configuration()) {}
  40. PeerConnection::PeerConnection(Configuration config)
  41. : CheshireCat<impl::PeerConnection>(std::move(config)) {}
  42. PeerConnection::~PeerConnection() { close(); }
  43. void PeerConnection::close() { impl()->close(); }
  44. const Configuration *PeerConnection::config() const { return &impl()->config; }
  45. PeerConnection::State PeerConnection::state() const { return impl()->state; }
  46. PeerConnection::GatheringState PeerConnection::gatheringState() const {
  47. return impl()->gatheringState;
  48. }
  49. PeerConnection::SignalingState PeerConnection::signalingState() const {
  50. return impl()->signalingState;
  51. }
  52. optional<Description> PeerConnection::localDescription() const {
  53. return impl()->localDescription();
  54. }
  55. optional<Description> PeerConnection::remoteDescription() const {
  56. return impl()->remoteDescription();
  57. }
  58. bool PeerConnection::hasMedia() const {
  59. auto local = localDescription();
  60. return local && local->hasAudioOrVideo();
  61. }
  62. void PeerConnection::setLocalDescription(Description::Type type) {
  63. PLOG_VERBOSE << "Setting local description, type=" << Description::typeToString(type);
  64. SignalingState signalingState = impl()->signalingState.load();
  65. if (type == Description::Type::Rollback) {
  66. if (signalingState == SignalingState::HaveLocalOffer ||
  67. signalingState == SignalingState::HaveLocalPranswer) {
  68. impl()->rollbackLocalDescription();
  69. impl()->changeSignalingState(SignalingState::Stable);
  70. }
  71. return;
  72. }
  73. // Guess the description type if unspecified
  74. if (type == Description::Type::Unspec) {
  75. if (signalingState == SignalingState::HaveRemoteOffer)
  76. type = Description::Type::Answer;
  77. else
  78. type = Description::Type::Offer;
  79. }
  80. // Only a local offer resets the negotiation needed flag
  81. if (type == Description::Type::Offer && !impl()->negotiationNeeded.exchange(false)) {
  82. PLOG_DEBUG << "No negotiation needed";
  83. return;
  84. }
  85. // Get the new signaling state
  86. SignalingState newSignalingState;
  87. switch (signalingState) {
  88. case SignalingState::Stable:
  89. if (type != Description::Type::Offer) {
  90. std::ostringstream oss;
  91. oss << "Unexpected local desciption type " << type << " in signaling state "
  92. << signalingState;
  93. throw std::logic_error(oss.str());
  94. }
  95. newSignalingState = SignalingState::HaveLocalOffer;
  96. break;
  97. case SignalingState::HaveRemoteOffer:
  98. case SignalingState::HaveLocalPranswer:
  99. if (type != Description::Type::Answer && type != Description::Type::Pranswer) {
  100. std::ostringstream oss;
  101. oss << "Unexpected local description type " << type
  102. << " description in signaling state " << signalingState;
  103. throw std::logic_error(oss.str());
  104. }
  105. newSignalingState = SignalingState::Stable;
  106. break;
  107. default: {
  108. std::ostringstream oss;
  109. oss << "Unexpected local description in signaling state " << signalingState << ", ignoring";
  110. LOG_WARNING << oss.str();
  111. return;
  112. }
  113. }
  114. auto iceTransport = impl()->initIceTransport();
  115. Description local = iceTransport->getLocalDescription(type);
  116. impl()->processLocalDescription(std::move(local));
  117. impl()->changeSignalingState(newSignalingState);
  118. if (impl()->gatheringState == GatheringState::New) {
  119. iceTransport->gatherLocalCandidates(impl()->localBundleMid());
  120. }
  121. }
  122. void PeerConnection::setRemoteDescription(Description description) {
  123. PLOG_VERBOSE << "Setting remote description: " << string(description);
  124. if (description.type() == Description::Type::Rollback) {
  125. // This is mostly useless because we accept any offer
  126. PLOG_VERBOSE << "Rolling back pending remote description";
  127. impl()->changeSignalingState(SignalingState::Stable);
  128. return;
  129. }
  130. impl()->validateRemoteDescription(description);
  131. // Get the new signaling state
  132. SignalingState signalingState = impl()->signalingState.load();
  133. SignalingState newSignalingState;
  134. switch (signalingState) {
  135. case SignalingState::Stable:
  136. description.hintType(Description::Type::Offer);
  137. if (description.type() != Description::Type::Offer) {
  138. std::ostringstream oss;
  139. oss << "Unexpected remote " << description.type() << " description in signaling state "
  140. << signalingState;
  141. throw std::logic_error(oss.str());
  142. }
  143. newSignalingState = SignalingState::HaveRemoteOffer;
  144. break;
  145. case SignalingState::HaveLocalOffer:
  146. description.hintType(Description::Type::Answer);
  147. if (description.type() == Description::Type::Offer) {
  148. // The ICE agent will automatically initiate a rollback when a peer that had previously
  149. // created an offer receives an offer from the remote peer
  150. setLocalDescription(Description::Type::Rollback);
  151. newSignalingState = SignalingState::HaveRemoteOffer;
  152. break;
  153. }
  154. if (description.type() != Description::Type::Answer &&
  155. description.type() != Description::Type::Pranswer) {
  156. std::ostringstream oss;
  157. oss << "Unexpected remote " << description.type() << " description in signaling state "
  158. << signalingState;
  159. throw std::logic_error(oss.str());
  160. }
  161. newSignalingState = SignalingState::Stable;
  162. break;
  163. case SignalingState::HaveRemotePranswer:
  164. description.hintType(Description::Type::Answer);
  165. if (description.type() != Description::Type::Answer &&
  166. description.type() != Description::Type::Pranswer) {
  167. std::ostringstream oss;
  168. oss << "Unexpected remote " << description.type() << " description in signaling state "
  169. << signalingState;
  170. throw std::logic_error(oss.str());
  171. }
  172. newSignalingState = SignalingState::Stable;
  173. break;
  174. default: {
  175. std::ostringstream oss;
  176. oss << "Unexpected remote description in signaling state " << signalingState;
  177. throw std::logic_error(oss.str());
  178. }
  179. }
  180. // Candidates will be added at the end, extract them for now
  181. auto remoteCandidates = description.extractCandidates();
  182. auto type = description.type();
  183. impl()->processRemoteDescription(std::move(description));
  184. impl()->changeSignalingState(newSignalingState);
  185. if (type == Description::Type::Offer) {
  186. // This is an offer, we need to answer
  187. if (!impl()->config.disableAutoNegotiation)
  188. setLocalDescription(Description::Type::Answer);
  189. }
  190. for (const auto &candidate : remoteCandidates)
  191. addRemoteCandidate(candidate);
  192. }
  193. void PeerConnection::addRemoteCandidate(Candidate candidate) {
  194. PLOG_VERBOSE << "Adding remote candidate: " << string(candidate);
  195. impl()->processRemoteCandidate(std::move(candidate));
  196. }
  197. optional<string> PeerConnection::localAddress() const {
  198. auto iceTransport = impl()->getIceTransport();
  199. return iceTransport ? iceTransport->getLocalAddress() : nullopt;
  200. }
  201. optional<string> PeerConnection::remoteAddress() const {
  202. auto iceTransport = impl()->getIceTransport();
  203. return iceTransport ? iceTransport->getRemoteAddress() : nullopt;
  204. }
  205. shared_ptr<DataChannel> PeerConnection::createDataChannel(string label, DataChannelInit init) {
  206. auto channelImpl = impl()->emplaceDataChannel(std::move(label), std::move(init));
  207. auto channel = std::make_shared<DataChannel>(channelImpl);
  208. if (auto transport = impl()->getSctpTransport())
  209. if (transport->state() == impl::SctpTransport::State::Connected)
  210. channelImpl->open(transport);
  211. // Renegotiation is needed iff the current local description does not have application
  212. auto local = impl()->localDescription();
  213. if (!local || !local->hasApplication())
  214. impl()->negotiationNeeded = true;
  215. if (!impl()->config.disableAutoNegotiation)
  216. setLocalDescription();
  217. return channel;
  218. }
  219. void PeerConnection::onDataChannel(
  220. std::function<void(shared_ptr<DataChannel> dataChannel)> callback) {
  221. impl()->dataChannelCallback = callback;
  222. impl()->flushPendingDataChannels();
  223. }
  224. std::shared_ptr<Track> PeerConnection::addTrack(Description::Media description) {
  225. auto trackImpl = impl()->emplaceTrack(std::move(description));
  226. auto track = std::make_shared<Track>(trackImpl);
  227. // Renegotiation is needed for the new or updated track
  228. impl()->negotiationNeeded = true;
  229. return track;
  230. }
  231. void PeerConnection::onTrack(std::function<void(std::shared_ptr<Track>)> callback) {
  232. impl()->trackCallback = callback;
  233. impl()->flushPendingTracks();
  234. }
  235. void PeerConnection::onLocalDescription(std::function<void(Description description)> callback) {
  236. impl()->localDescriptionCallback = callback;
  237. }
  238. void PeerConnection::onLocalCandidate(std::function<void(Candidate candidate)> callback) {
  239. impl()->localCandidateCallback = callback;
  240. }
  241. void PeerConnection::onStateChange(std::function<void(State state)> callback) {
  242. impl()->stateChangeCallback = callback;
  243. }
  244. void PeerConnection::onGatheringStateChange(std::function<void(GatheringState state)> callback) {
  245. impl()->gatheringStateChangeCallback = callback;
  246. }
  247. void PeerConnection::onSignalingStateChange(std::function<void(SignalingState state)> callback) {
  248. impl()->signalingStateChangeCallback = callback;
  249. }
  250. bool PeerConnection::getSelectedCandidatePair(Candidate *local, Candidate *remote) {
  251. auto iceTransport = impl()->getIceTransport();
  252. return iceTransport ? iceTransport->getSelectedCandidatePair(local, remote) : false;
  253. }
  254. void PeerConnection::clearStats() {
  255. if (auto sctpTransport = impl()->getSctpTransport())
  256. return sctpTransport->clearStats();
  257. }
  258. size_t PeerConnection::bytesSent() {
  259. auto sctpTransport = impl()->getSctpTransport();
  260. return sctpTransport ? sctpTransport->bytesSent() : 0;
  261. }
  262. size_t PeerConnection::bytesReceived() {
  263. auto sctpTransport = impl()->getSctpTransport();
  264. return sctpTransport ? sctpTransport->bytesReceived() : 0;
  265. }
  266. optional<std::chrono::milliseconds> PeerConnection::rtt() {
  267. auto sctpTransport = impl()->getSctpTransport();
  268. return sctpTransport ? sctpTransport->rtt() : nullopt;
  269. }
  270. } // namespace rtc
  271. std::ostream &operator<<(std::ostream &out, rtc::PeerConnection::State state) {
  272. using State = rtc::PeerConnection::State;
  273. const char *str;
  274. switch (state) {
  275. case State::New:
  276. str = "new";
  277. break;
  278. case State::Connecting:
  279. str = "connecting";
  280. break;
  281. case State::Connected:
  282. str = "connected";
  283. break;
  284. case State::Disconnected:
  285. str = "disconnected";
  286. break;
  287. case State::Failed:
  288. str = "failed";
  289. break;
  290. case State::Closed:
  291. str = "closed";
  292. break;
  293. default:
  294. str = "unknown";
  295. break;
  296. }
  297. return out << str;
  298. }
  299. std::ostream &operator<<(std::ostream &out, rtc::PeerConnection::GatheringState state) {
  300. using GatheringState = rtc::PeerConnection::GatheringState;
  301. const char *str;
  302. switch (state) {
  303. case GatheringState::New:
  304. str = "new";
  305. break;
  306. case GatheringState::InProgress:
  307. str = "in-progress";
  308. break;
  309. case GatheringState::Complete:
  310. str = "complete";
  311. break;
  312. default:
  313. str = "unknown";
  314. break;
  315. }
  316. return out << str;
  317. }
  318. std::ostream &operator<<(std::ostream &out, rtc::PeerConnection::SignalingState state) {
  319. using SignalingState = rtc::PeerConnection::SignalingState;
  320. const char *str;
  321. switch (state) {
  322. case SignalingState::Stable:
  323. str = "stable";
  324. break;
  325. case SignalingState::HaveLocalOffer:
  326. str = "have-local-offer";
  327. break;
  328. case SignalingState::HaveRemoteOffer:
  329. str = "have-remote-offer";
  330. break;
  331. case SignalingState::HaveLocalPranswer:
  332. str = "have-local-pranswer";
  333. break;
  334. case SignalingState::HaveRemotePranswer:
  335. str = "have-remote-pranswer";
  336. break;
  337. default:
  338. str = "unknown";
  339. break;
  340. }
  341. return out << str;
  342. }