PeerConnectionObject.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. #include "pch.h"
  2. #include <rtc_base/strings/json.h>
  3. #include "Context.h"
  4. #include "PeerConnectionObject.h"
  5. #include "SetSessionDescriptionObserver.h"
  6. namespace unity
  7. {
  8. namespace webrtc
  9. {
  10. webrtc::SdpType ConvertSdpType(RTCSdpType type)
  11. {
  12. switch (type)
  13. {
  14. case RTCSdpType::Offer:
  15. return webrtc::SdpType::kOffer;
  16. case RTCSdpType::PrAnswer:
  17. return webrtc::SdpType::kPrAnswer;
  18. case RTCSdpType::Answer:
  19. return webrtc::SdpType::kAnswer;
  20. case RTCSdpType::Rollback:
  21. return webrtc::SdpType::kRollback;
  22. }
  23. throw std::invalid_argument("Unknown RTCSdpType");
  24. }
  25. RTCSdpType ConvertSdpType(webrtc::SdpType type)
  26. {
  27. switch (type)
  28. {
  29. case webrtc::SdpType::kOffer:
  30. return RTCSdpType::Offer;
  31. case webrtc::SdpType::kPrAnswer:
  32. return RTCSdpType::PrAnswer;
  33. case webrtc::SdpType::kAnswer:
  34. return RTCSdpType::Answer;
  35. case webrtc::SdpType::kRollback:
  36. return RTCSdpType::Rollback;
  37. }
  38. throw std::invalid_argument("Unknown SdpType");
  39. }
  40. PeerConnectionObject::PeerConnectionObject(Context& context)
  41. : context(context)
  42. {
  43. }
  44. PeerConnectionObject::~PeerConnectionObject()
  45. {
  46. if (connection == nullptr)
  47. {
  48. return;
  49. }
  50. auto senders = connection->GetSenders();
  51. for (const auto& sender : senders)
  52. {
  53. connection->RemoveTrack(sender);
  54. }
  55. const auto state = connection->peer_connection_state();
  56. if (state != webrtc::PeerConnectionInterface::PeerConnectionState::kClosed)
  57. {
  58. connection->Close();
  59. }
  60. connection = nullptr;
  61. }
  62. void PeerConnectionObject::OnDataChannel(rtc::scoped_refptr<webrtc::DataChannelInterface> channel)
  63. {
  64. context.AddDataChannel(channel, *this);
  65. if (onDataChannel != nullptr)
  66. {
  67. onDataChannel(this, channel);
  68. }
  69. }
  70. void PeerConnectionObject::OnIceCandidate(const webrtc::IceCandidateInterface* candidate)
  71. {
  72. std::string out;
  73. if (!candidate->ToString(&out))
  74. {
  75. DebugError("Can't make string form of sdp.");
  76. }
  77. if (onIceCandidate != nullptr)
  78. {
  79. onIceCandidate(this, out.c_str(), candidate->sdp_mid().c_str(), candidate->sdp_mline_index());
  80. }
  81. }
  82. void PeerConnectionObject::OnRenegotiationNeeded()
  83. {
  84. if (onRenegotiationNeeded != nullptr)
  85. {
  86. onRenegotiationNeeded(this);
  87. }
  88. }
  89. void PeerConnectionObject::OnTrack(rtc::scoped_refptr<webrtc::RtpTransceiverInterface> transceiver)
  90. {
  91. context.AddRefPtr(transceiver);
  92. context.AddRefPtr(transceiver->receiver());
  93. context.AddRefPtr(transceiver->receiver()->track());
  94. if (onTrack != nullptr)
  95. {
  96. onTrack(this, transceiver.get());
  97. }
  98. }
  99. void PeerConnectionObject::OnRemoveTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver)
  100. {
  101. if (onRemoveTrack != nullptr)
  102. {
  103. onRemoveTrack(this, receiver.get());
  104. }
  105. }
  106. // Called any time the IceConnectionState changes.
  107. void PeerConnectionObject::OnIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState new_state)
  108. {
  109. DebugLog("OnIceConnectionChange %d", new_state);
  110. if (onIceConnectionChange != nullptr)
  111. {
  112. onIceConnectionChange(this, new_state);
  113. }
  114. }
  115. void PeerConnectionObject::OnConnectionChange(PeerConnectionInterface::PeerConnectionState new_state)
  116. {
  117. DebugLog("OnConnectionChange %d", new_state);
  118. if (onConnectionStateChange != nullptr)
  119. {
  120. onConnectionStateChange(this, new_state);
  121. }
  122. }
  123. // Called any time the IceGatheringState changes.
  124. void PeerConnectionObject::OnIceGatheringChange(webrtc::PeerConnectionInterface::IceGatheringState new_state)
  125. {
  126. DebugLog("OnIceGatheringChange %d", new_state);
  127. if (onIceGatheringChange != nullptr)
  128. {
  129. onIceGatheringChange(this, new_state);
  130. }
  131. }
  132. void PeerConnectionObject::OnSignalingChange(webrtc::PeerConnectionInterface::SignalingState new_state)
  133. {
  134. DebugLog("OnSignalingChange %d", new_state);
  135. }
  136. void PeerConnectionObject::OnAddStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> stream)
  137. {
  138. DebugLog("OnAddStream");
  139. }
  140. void PeerConnectionObject::OnRemoveStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> stream)
  141. {
  142. DebugLog("OnRemoveStream");
  143. }
  144. void PeerConnectionObject::Close()
  145. {
  146. if (connection != nullptr &&
  147. connection->peer_connection_state() != webrtc::PeerConnectionInterface::PeerConnectionState::kClosed)
  148. {
  149. // Cleanup delegates/callbacks
  150. onCreateSDSuccess = nullptr;
  151. onCreateSDFailure = nullptr;
  152. onLocalSdpReady = nullptr;
  153. onIceCandidate = nullptr;
  154. onIceConnectionChange = nullptr;
  155. onDataChannel = nullptr;
  156. onRenegotiationNeeded = nullptr;
  157. onTrack = nullptr;
  158. connection->Close();
  159. }
  160. }
  161. RTCErrorType PeerConnectionObject::SetLocalDescription(
  162. const RTCSessionDescription& desc, ::webrtc::SetSessionDescriptionObserver* observer, std::string& error)
  163. {
  164. SdpParseError error_;
  165. std::unique_ptr<SessionDescriptionInterface> _desc =
  166. CreateSessionDescription(ConvertSdpType(desc.type), desc.sdp, &error_);
  167. if (!_desc.get())
  168. {
  169. DebugLog("Can't parse received session description message.");
  170. DebugLog("SdpParseError:\n%s", error_.description.c_str());
  171. error = error_.description;
  172. return RTCErrorType::SYNTAX_ERROR;
  173. }
  174. connection->SetLocalDescription(observer, _desc.release());
  175. return RTCErrorType::NONE;
  176. }
  177. RTCErrorType PeerConnectionObject::SetLocalDescriptionWithoutDescription(
  178. ::webrtc::SetSessionDescriptionObserver* observer, std::string& error)
  179. {
  180. connection->SetLocalDescription(observer);
  181. return RTCErrorType::NONE;
  182. }
  183. RTCErrorType PeerConnectionObject::SetRemoteDescription(
  184. const RTCSessionDescription& desc, ::webrtc::SetSessionDescriptionObserver* observer, std::string& error)
  185. {
  186. SdpParseError error_;
  187. std::unique_ptr<SessionDescriptionInterface> _desc =
  188. CreateSessionDescription(ConvertSdpType(desc.type), desc.sdp, &error_);
  189. if (!_desc.get())
  190. {
  191. DebugLog("Can't parse received session description message.");
  192. DebugLog("SdpParseError:\n%s", error_.description.c_str());
  193. error = error_.description;
  194. return RTCErrorType::SYNTAX_ERROR;
  195. }
  196. connection->SetRemoteDescription(observer, _desc.release());
  197. return RTCErrorType::NONE;
  198. }
  199. webrtc::RTCErrorType PeerConnectionObject::SetConfiguration(const std::string& config)
  200. {
  201. webrtc::PeerConnectionInterface::RTCConfiguration _config;
  202. if (!Convert(config, _config))
  203. return webrtc::RTCErrorType::INVALID_PARAMETER;
  204. const auto error = connection->SetConfiguration(_config);
  205. if (!error.ok())
  206. {
  207. LogPrint(error.message());
  208. }
  209. return error.type();
  210. }
  211. std::string PeerConnectionObject::GetConfiguration() const
  212. {
  213. auto _config = connection->GetConfiguration();
  214. Json::Value root;
  215. root["iceServers"] = Json::Value(Json::arrayValue);
  216. for (webrtc::PeerConnectionInterface::IceServer iceServer : _config.servers)
  217. {
  218. Json::Value jsonIceServer = Json::Value(Json::objectValue);
  219. jsonIceServer["username"] = iceServer.username;
  220. jsonIceServer["credential"] = iceServer.password;
  221. jsonIceServer["credentialType"] = static_cast<int>(RTCIceCredentialType::Password);
  222. jsonIceServer["urls"] = Json::Value(Json::arrayValue);
  223. for (auto url : iceServer.urls)
  224. {
  225. jsonIceServer["urls"].append(url);
  226. }
  227. root["iceServers"].append(jsonIceServer);
  228. }
  229. root["iceTransportPolicy"] = Json::Value(Json::objectValue);
  230. root["iceTransportPolicy"]["hasValue"] = true;
  231. root["iceTransportPolicy"]["value"] = _config.type;
  232. root["enableDtlsSrtp"] = Json::Value(Json::objectValue);
  233. root["enableDtlsSrtp"]["hasValue"] = _config.enable_dtls_srtp.has_value();
  234. root["enableDtlsSrtp"]["value"] = _config.enable_dtls_srtp.value_or(false);
  235. root["iceCandidatePoolSize"] = Json::Value(Json::objectValue);
  236. root["iceCandidatePoolSize"]["hasValue"] = true;
  237. root["iceCandidatePoolSize"]["value"] = _config.ice_candidate_pool_size;
  238. root["bundlePolicy"] = Json::Value(Json::objectValue);
  239. root["bundlePolicy"]["hasValue"] = true;
  240. root["bundlePolicy"]["value"] = _config.bundle_policy;
  241. Json::StreamWriterBuilder builder;
  242. return Json::writeString(builder, root);
  243. }
  244. void
  245. PeerConnectionObject::CreateOffer(const RTCOfferAnswerOptions& options, CreateSessionDescriptionObserver* observer)
  246. {
  247. webrtc::PeerConnectionInterface::RTCOfferAnswerOptions _options;
  248. _options.ice_restart = options.iceRestart;
  249. _options.voice_activity_detection = options.voiceActivityDetection;
  250. connection->CreateOffer(observer, _options);
  251. }
  252. void
  253. PeerConnectionObject::CreateAnswer(const RTCOfferAnswerOptions& options, CreateSessionDescriptionObserver* observer)
  254. {
  255. webrtc::PeerConnectionInterface::RTCOfferAnswerOptions _options;
  256. _options.ice_restart = options.iceRestart;
  257. _options.voice_activity_detection = options.voiceActivityDetection;
  258. connection->CreateAnswer(observer, _options);
  259. }
  260. void PeerConnectionObject::ReceiveStatsReport(const rtc::scoped_refptr<const webrtc::RTCStatsReport>& report)
  261. {
  262. context.AddStatsReport(report);
  263. }
  264. bool PeerConnectionObject::GetSessionDescription(
  265. const webrtc::SessionDescriptionInterface* sdp, RTCSessionDescription& desc) const
  266. {
  267. if (sdp == nullptr)
  268. {
  269. return false;
  270. }
  271. std::string out;
  272. sdp->ToString(&out);
  273. desc.type = ConvertSdpType(sdp->GetType());
  274. desc.sdp = static_cast<char*>(CoTaskMemAlloc(out.size() + 1));
  275. out.copy(desc.sdp, out.size());
  276. desc.sdp[out.size()] = '\0';
  277. return true;
  278. }
  279. } // end namespace webrtc
  280. } // end namespace unity