peerconnection.cpp 12 KB

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