peerconnection.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. if (!iceTransport)
  116. return; // closed
  117. Description local = iceTransport->getLocalDescription(type);
  118. impl()->processLocalDescription(std::move(local));
  119. impl()->changeSignalingState(newSignalingState);
  120. if (impl()->gatheringState == GatheringState::New) {
  121. iceTransport->gatherLocalCandidates(impl()->localBundleMid());
  122. }
  123. }
  124. void PeerConnection::setRemoteDescription(Description description) {
  125. PLOG_VERBOSE << "Setting remote description: " << string(description);
  126. if (description.type() == Description::Type::Rollback) {
  127. // This is mostly useless because we accept any offer
  128. PLOG_VERBOSE << "Rolling back pending remote description";
  129. impl()->changeSignalingState(SignalingState::Stable);
  130. return;
  131. }
  132. impl()->validateRemoteDescription(description);
  133. // Get the new signaling state
  134. SignalingState signalingState = impl()->signalingState.load();
  135. SignalingState newSignalingState;
  136. switch (signalingState) {
  137. case SignalingState::Stable:
  138. description.hintType(Description::Type::Offer);
  139. if (description.type() != Description::Type::Offer) {
  140. std::ostringstream oss;
  141. oss << "Unexpected remote " << description.type() << " description in signaling state "
  142. << signalingState;
  143. throw std::logic_error(oss.str());
  144. }
  145. newSignalingState = SignalingState::HaveRemoteOffer;
  146. break;
  147. case SignalingState::HaveLocalOffer:
  148. description.hintType(Description::Type::Answer);
  149. if (description.type() == Description::Type::Offer) {
  150. // The ICE agent will automatically initiate a rollback when a peer that had previously
  151. // created an offer receives an offer from the remote peer
  152. setLocalDescription(Description::Type::Rollback);
  153. newSignalingState = SignalingState::HaveRemoteOffer;
  154. break;
  155. }
  156. if (description.type() != Description::Type::Answer &&
  157. description.type() != Description::Type::Pranswer) {
  158. std::ostringstream oss;
  159. oss << "Unexpected remote " << description.type() << " description in signaling state "
  160. << signalingState;
  161. throw std::logic_error(oss.str());
  162. }
  163. newSignalingState = SignalingState::Stable;
  164. break;
  165. case SignalingState::HaveRemotePranswer:
  166. description.hintType(Description::Type::Answer);
  167. if (description.type() != Description::Type::Answer &&
  168. description.type() != Description::Type::Pranswer) {
  169. std::ostringstream oss;
  170. oss << "Unexpected remote " << description.type() << " description in signaling state "
  171. << signalingState;
  172. throw std::logic_error(oss.str());
  173. }
  174. newSignalingState = SignalingState::Stable;
  175. break;
  176. default: {
  177. std::ostringstream oss;
  178. oss << "Unexpected remote description in signaling state " << signalingState;
  179. throw std::logic_error(oss.str());
  180. }
  181. }
  182. // Candidates will be added at the end, extract them for now
  183. auto remoteCandidates = description.extractCandidates();
  184. auto type = description.type();
  185. impl()->processRemoteDescription(std::move(description));
  186. impl()->changeSignalingState(newSignalingState);
  187. if (type == Description::Type::Offer) {
  188. // This is an offer, we need to answer
  189. if (!impl()->config.disableAutoNegotiation)
  190. setLocalDescription(Description::Type::Answer);
  191. }
  192. for (const auto &candidate : remoteCandidates)
  193. addRemoteCandidate(candidate);
  194. }
  195. void PeerConnection::addRemoteCandidate(Candidate candidate) {
  196. PLOG_VERBOSE << "Adding remote candidate: " << string(candidate);
  197. impl()->processRemoteCandidate(std::move(candidate));
  198. }
  199. optional<string> PeerConnection::localAddress() const {
  200. auto iceTransport = impl()->getIceTransport();
  201. return iceTransport ? iceTransport->getLocalAddress() : nullopt;
  202. }
  203. optional<string> PeerConnection::remoteAddress() const {
  204. auto iceTransport = impl()->getIceTransport();
  205. return iceTransport ? iceTransport->getRemoteAddress() : nullopt;
  206. }
  207. shared_ptr<DataChannel> PeerConnection::createDataChannel(string label, DataChannelInit init) {
  208. auto channelImpl = impl()->emplaceDataChannel(std::move(label), std::move(init));
  209. auto channel = std::make_shared<DataChannel>(channelImpl);
  210. if (auto transport = impl()->getSctpTransport())
  211. if (transport->state() == impl::SctpTransport::State::Connected)
  212. channelImpl->open(transport);
  213. // Renegotiation is needed iff the current local description does not have application
  214. auto local = impl()->localDescription();
  215. if (!local || !local->hasApplication())
  216. impl()->negotiationNeeded = true;
  217. if (!impl()->config.disableAutoNegotiation)
  218. setLocalDescription();
  219. return channel;
  220. }
  221. void PeerConnection::onDataChannel(
  222. std::function<void(shared_ptr<DataChannel> dataChannel)> callback) {
  223. impl()->dataChannelCallback = callback;
  224. impl()->flushPendingDataChannels();
  225. }
  226. std::shared_ptr<Track> PeerConnection::addTrack(Description::Media description) {
  227. auto trackImpl = impl()->emplaceTrack(std::move(description));
  228. auto track = std::make_shared<Track>(trackImpl);
  229. // Renegotiation is needed for the new or updated track
  230. impl()->negotiationNeeded = true;
  231. return track;
  232. }
  233. void PeerConnection::onTrack(std::function<void(std::shared_ptr<Track>)> callback) {
  234. impl()->trackCallback = callback;
  235. impl()->flushPendingTracks();
  236. }
  237. void PeerConnection::onLocalDescription(std::function<void(Description description)> callback) {
  238. impl()->localDescriptionCallback = callback;
  239. }
  240. void PeerConnection::onLocalCandidate(std::function<void(Candidate candidate)> callback) {
  241. impl()->localCandidateCallback = callback;
  242. }
  243. void PeerConnection::onStateChange(std::function<void(State state)> callback) {
  244. impl()->stateChangeCallback = callback;
  245. }
  246. void PeerConnection::onGatheringStateChange(std::function<void(GatheringState state)> callback) {
  247. impl()->gatheringStateChangeCallback = callback;
  248. }
  249. void PeerConnection::onSignalingStateChange(std::function<void(SignalingState state)> callback) {
  250. impl()->signalingStateChangeCallback = callback;
  251. }
  252. bool PeerConnection::getSelectedCandidatePair(Candidate *local, Candidate *remote) {
  253. auto iceTransport = impl()->getIceTransport();
  254. return iceTransport ? iceTransport->getSelectedCandidatePair(local, remote) : false;
  255. }
  256. void PeerConnection::clearStats() {
  257. if (auto sctpTransport = impl()->getSctpTransport())
  258. return sctpTransport->clearStats();
  259. }
  260. size_t PeerConnection::bytesSent() {
  261. auto sctpTransport = impl()->getSctpTransport();
  262. return sctpTransport ? sctpTransport->bytesSent() : 0;
  263. }
  264. size_t PeerConnection::bytesReceived() {
  265. auto sctpTransport = impl()->getSctpTransport();
  266. return sctpTransport ? sctpTransport->bytesReceived() : 0;
  267. }
  268. optional<std::chrono::milliseconds> PeerConnection::rtt() {
  269. auto sctpTransport = impl()->getSctpTransport();
  270. return sctpTransport ? sctpTransport->rtt() : nullopt;
  271. }
  272. } // namespace rtc
  273. std::ostream &operator<<(std::ostream &out, rtc::PeerConnection::State state) {
  274. using State = rtc::PeerConnection::State;
  275. const char *str;
  276. switch (state) {
  277. case State::New:
  278. str = "new";
  279. break;
  280. case State::Connecting:
  281. str = "connecting";
  282. break;
  283. case State::Connected:
  284. str = "connected";
  285. break;
  286. case State::Disconnected:
  287. str = "disconnected";
  288. break;
  289. case State::Failed:
  290. str = "failed";
  291. break;
  292. case State::Closed:
  293. str = "closed";
  294. break;
  295. default:
  296. str = "unknown";
  297. break;
  298. }
  299. return out << str;
  300. }
  301. std::ostream &operator<<(std::ostream &out, rtc::PeerConnection::GatheringState state) {
  302. using GatheringState = rtc::PeerConnection::GatheringState;
  303. const char *str;
  304. switch (state) {
  305. case GatheringState::New:
  306. str = "new";
  307. break;
  308. case GatheringState::InProgress:
  309. str = "in-progress";
  310. break;
  311. case GatheringState::Complete:
  312. str = "complete";
  313. break;
  314. default:
  315. str = "unknown";
  316. break;
  317. }
  318. return out << str;
  319. }
  320. std::ostream &operator<<(std::ostream &out, rtc::PeerConnection::SignalingState state) {
  321. using SignalingState = rtc::PeerConnection::SignalingState;
  322. const char *str;
  323. switch (state) {
  324. case SignalingState::Stable:
  325. str = "stable";
  326. break;
  327. case SignalingState::HaveLocalOffer:
  328. str = "have-local-offer";
  329. break;
  330. case SignalingState::HaveRemoteOffer:
  331. str = "have-remote-offer";
  332. break;
  333. case SignalingState::HaveLocalPranswer:
  334. str = "have-local-pranswer";
  335. break;
  336. case SignalingState::HaveRemotePranswer:
  337. str = "have-remote-pranswer";
  338. break;
  339. default:
  340. str = "unknown";
  341. break;
  342. }
  343. return out << str;
  344. }