You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

677 lines
23 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2012, Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "talk/app/webrtc/peerconnection.h"
  28. #include <vector>
  29. #include "talk/app/webrtc/dtmfsender.h"
  30. #include "talk/app/webrtc/jsepicecandidate.h"
  31. #include "talk/app/webrtc/jsepsessiondescription.h"
  32. #include "talk/app/webrtc/mediastreamhandler.h"
  33. #include "talk/app/webrtc/streamcollection.h"
  34. #include "talk/base/logging.h"
  35. #include "talk/base/stringencode.h"
  36. #include "talk/session/media/channelmanager.h"
  37. namespace {
  38. using webrtc::PeerConnectionInterface;
  39. // The min number of tokens in the ice uri.
  40. static const size_t kMinIceUriTokens = 2;
  41. // The min number of tokens must present in Turn host uri.
  42. // e.g. user@turn.example.org
  43. static const size_t kTurnHostTokensNum = 2;
  44. // The default stun port.
  45. static const int kDefaultPort = 3478;
  46. // NOTE: Must be in the same order as the ServiceType enum.
  47. static const char* kValidIceServiceTypes[] = {
  48. "stun", "stuns", "turn", "turns", "invalid" };
  49. enum ServiceType {
  50. STUN, // Indicates a STUN server.
  51. STUNS, // Indicates a STUN server used with a TLS session.
  52. TURN, // Indicates a TURN server
  53. TURNS, // Indicates a TURN server used with a TLS session.
  54. INVALID, // Unknown.
  55. };
  56. enum {
  57. MSG_CREATE_SESSIONDESCRIPTION_SUCCESS = 0,
  58. MSG_CREATE_SESSIONDESCRIPTION_FAILED,
  59. MSG_SET_SESSIONDESCRIPTION_SUCCESS,
  60. MSG_SET_SESSIONDESCRIPTION_FAILED,
  61. MSG_GETSTATS,
  62. MSG_ICECONNECTIONCHANGE,
  63. MSG_ICEGATHERINGCHANGE,
  64. MSG_ICECANDIDATE,
  65. MSG_ICECOMPLETE,
  66. };
  67. struct CandidateMsg : public talk_base::MessageData {
  68. explicit CandidateMsg(const webrtc::JsepIceCandidate* candidate)
  69. : candidate(candidate) {
  70. }
  71. talk_base::scoped_ptr<const webrtc::JsepIceCandidate> candidate;
  72. };
  73. struct CreateSessionDescriptionMsg : public talk_base::MessageData {
  74. explicit CreateSessionDescriptionMsg(
  75. webrtc::CreateSessionDescriptionObserver* observer)
  76. : observer(observer) {
  77. }
  78. talk_base::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
  79. std::string error;
  80. talk_base::scoped_ptr<webrtc::SessionDescriptionInterface> description;
  81. };
  82. struct SetSessionDescriptionMsg : public talk_base::MessageData {
  83. explicit SetSessionDescriptionMsg(
  84. webrtc::SetSessionDescriptionObserver* observer)
  85. : observer(observer) {
  86. }
  87. talk_base::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
  88. std::string error;
  89. };
  90. struct GetStatsMsg : public talk_base::MessageData {
  91. explicit GetStatsMsg(webrtc::StatsObserver* observer)
  92. : observer(observer) {
  93. }
  94. webrtc::StatsReports reports;
  95. talk_base::scoped_refptr<webrtc::StatsObserver> observer;
  96. };
  97. typedef webrtc::PortAllocatorFactoryInterface::StunConfiguration
  98. StunConfiguration;
  99. typedef webrtc::PortAllocatorFactoryInterface::TurnConfiguration
  100. TurnConfiguration;
  101. bool ParseIceServers(const PeerConnectionInterface::IceServers& configuration,
  102. std::vector<StunConfiguration>* stun_config,
  103. std::vector<TurnConfiguration>* turn_config) {
  104. // draft-nandakumar-rtcweb-stun-uri-01
  105. // stunURI = scheme ":" stun-host [ ":" stun-port ]
  106. // scheme = "stun" / "stuns"
  107. // stun-host = IP-literal / IPv4address / reg-name
  108. // stun-port = *DIGIT
  109. // draft-petithuguenin-behave-turn-uris-01
  110. // turnURI = scheme ":" turn-host [ ":" turn-port ]
  111. // [ "?transport=" transport ]
  112. // scheme = "turn" / "turns"
  113. // transport = "udp" / "tcp" / transport-ext
  114. // transport-ext = 1*unreserved
  115. // turn-host = IP-literal / IPv4address / reg-name
  116. // turn-port = *DIGIT
  117. // TODO(ronghuawu): Handle IPV6 address
  118. for (size_t i = 0; i < configuration.size(); ++i) {
  119. webrtc::PeerConnectionInterface::IceServer server = configuration[i];
  120. if (server.uri.empty()) {
  121. LOG(WARNING) << "Empty uri.";
  122. continue;
  123. }
  124. std::vector<std::string> tokens;
  125. talk_base::tokenize(server.uri, '?', &tokens);
  126. // TODO(ronghuawu): Handle [ "?transport=" transport ].
  127. std::string uri_without_transport = tokens[0];
  128. tokens.clear();
  129. talk_base::tokenize(uri_without_transport, ':', &tokens);
  130. if (tokens.size() < kMinIceUriTokens) {
  131. LOG(WARNING) << "Invalid uri: " << server.uri;
  132. continue;
  133. }
  134. ServiceType service_type = INVALID;
  135. const std::string& type = tokens[0];
  136. for (size_t i = 0; i < ARRAY_SIZE(kValidIceServiceTypes); ++i) {
  137. if (type.compare(kValidIceServiceTypes[i]) == 0) {
  138. service_type = static_cast<ServiceType>(i);
  139. break;
  140. }
  141. }
  142. if (service_type == INVALID) {
  143. LOG(WARNING) << "Invalid service type: " << type;
  144. continue;
  145. }
  146. std::string address = tokens[1];
  147. int port = kDefaultPort;
  148. if (tokens.size() > kMinIceUriTokens) {
  149. if (!talk_base::FromString(tokens[2], &port)) {
  150. LOG(LS_WARNING) << "Failed to parse port string: " << tokens[2];
  151. continue;
  152. }
  153. if (port <= 0 || port > 0xffff) {
  154. LOG(WARNING) << "Invalid port: " << port;
  155. continue;
  156. }
  157. }
  158. switch (service_type) {
  159. case STUN:
  160. case STUNS:
  161. stun_config->push_back(StunConfiguration(address, port));
  162. break;
  163. case TURN:
  164. case TURNS: {
  165. // Turn url example from the spec |url:"turn:user@turn.example.org"|.
  166. std::vector<std::string> turn_tokens;
  167. talk_base::tokenize(address, '@', &turn_tokens);
  168. if (turn_tokens.size() != kTurnHostTokensNum) {
  169. LOG(LS_ERROR) << "Invalid TURN configuration : "
  170. << address << " can't proceed.";
  171. return false;
  172. }
  173. std::string username = turn_tokens[0];
  174. address = turn_tokens[1];
  175. turn_config->push_back(TurnConfiguration(address, port,
  176. username, server.password));
  177. // STUN functionality is part of TURN.
  178. stun_config->push_back(StunConfiguration(address, port));
  179. break;
  180. }
  181. case INVALID:
  182. default:
  183. LOG(WARNING) << "Configuration not supported: " << server.uri;
  184. return false;
  185. }
  186. }
  187. return true;
  188. }
  189. // Check if we can send |new_stream| on a PeerConnection.
  190. // Currently only one audio but multiple video track is supported per
  191. // PeerConnection.
  192. bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
  193. webrtc::MediaStreamInterface* new_stream) {
  194. if (!new_stream || !current_streams)
  195. return false;
  196. bool audio_track_exist = false;
  197. for (size_t j = 0; j < current_streams->count(); ++j) {
  198. if (!audio_track_exist) {
  199. audio_track_exist = current_streams->at(j)->audio_tracks()->count() > 0;
  200. }
  201. }
  202. if (audio_track_exist && (new_stream->audio_tracks()->count() > 0)) {
  203. LOG(LS_ERROR) << "AddStream - Currently only one audio track is supported"
  204. << "per PeerConnection.";
  205. return false;
  206. }
  207. return true;
  208. }
  209. } // namespace
  210. namespace webrtc {
  211. PeerConnection::PeerConnection(PeerConnectionFactory* factory)
  212. : factory_(factory),
  213. observer_(NULL),
  214. signaling_state_(kStable),
  215. ice_state_(kIceNew),
  216. ice_connection_state_(kIceConnectionNew),
  217. ice_gathering_state_(kIceGatheringNew),
  218. local_media_streams_(StreamCollection::Create()) {
  219. }
  220. PeerConnection::~PeerConnection() {
  221. }
  222. bool PeerConnection::Initialize(
  223. const PeerConnectionInterface::IceServers& configuration,
  224. const MediaConstraintsInterface* constraints,
  225. webrtc::PortAllocatorFactoryInterface* allocator_factory,
  226. PeerConnectionObserver* observer) {
  227. std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
  228. std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
  229. if (!ParseIceServers(configuration, &stun_config, &turn_config)) {
  230. return false;
  231. }
  232. return DoInitialize(stun_config, turn_config, constraints,
  233. allocator_factory, observer);
  234. }
  235. bool PeerConnection::DoInitialize(
  236. const StunConfigurations& stun_config,
  237. const TurnConfigurations& turn_config,
  238. const MediaConstraintsInterface* constraints,
  239. webrtc::PortAllocatorFactoryInterface* allocator_factory,
  240. PeerConnectionObserver* observer) {
  241. ASSERT(observer != NULL);
  242. if (!observer)
  243. return false;
  244. observer_ = observer;
  245. port_allocator_.reset(
  246. allocator_factory->CreatePortAllocator(stun_config, turn_config));
  247. // To handle both internal and externally created port allocator, we will
  248. // enable BUNDLE here. Also enabling TURN and disable legacy relay service.
  249. port_allocator_->set_flags(cricket::PORTALLOCATOR_ENABLE_BUNDLE |
  250. cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
  251. cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
  252. mediastream_signaling_.reset(new MediaStreamSignaling(
  253. factory_->signaling_thread(), this));
  254. session_.reset(new WebRtcSession(factory_->channel_manager(),
  255. factory_->signaling_thread(),
  256. factory_->worker_thread(),
  257. port_allocator_.get(),
  258. mediastream_signaling_.get()));
  259. stream_handler_.reset(new MediaStreamHandlers(session_.get(),
  260. session_.get()));
  261. stats_.set_session(session_.get());
  262. // Initialize the WebRtcSession. It creates transport channels etc.
  263. if (!session_->Initialize(constraints))
  264. return false;
  265. // Register PeerConnection as receiver of local ice candidates.
  266. // All the callbacks will be posted to the application from PeerConnection.
  267. session_->RegisterIceObserver(this);
  268. session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
  269. return true;
  270. }
  271. talk_base::scoped_refptr<StreamCollectionInterface>
  272. PeerConnection::local_streams() {
  273. return local_media_streams_;
  274. }
  275. talk_base::scoped_refptr<StreamCollectionInterface>
  276. PeerConnection::remote_streams() {
  277. return mediastream_signaling_->remote_streams();
  278. }
  279. bool PeerConnection::AddStream(MediaStreamInterface* local_stream,
  280. const MediaConstraintsInterface* constraints) {
  281. if (!CanAddLocalMediaStream(local_media_streams_, local_stream))
  282. return false;
  283. // TODO(perkj): Implement support for MediaConstraints in AddStream.
  284. local_media_streams_->AddStream(local_stream);
  285. mediastream_signaling_->SetLocalStreams(local_media_streams_);
  286. stats_.AddStream(local_stream);
  287. observer_->OnRenegotiationNeeded();
  288. return true;
  289. }
  290. void PeerConnection::RemoveStream(MediaStreamInterface* remove_stream) {
  291. local_media_streams_->RemoveStream(remove_stream);
  292. mediastream_signaling_->SetLocalStreams(local_media_streams_);
  293. observer_->OnRenegotiationNeeded();
  294. }
  295. talk_base::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
  296. AudioTrackInterface* track) {
  297. if (!track) {
  298. LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
  299. return NULL;
  300. }
  301. if (!local_media_streams_->FindAudioTrack(track->id())) {
  302. LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
  303. return NULL;
  304. }
  305. talk_base::scoped_refptr<DtmfSenderInterface> sender(
  306. DtmfSender::Create(track, signaling_thread(), session_.get()));
  307. if (!sender.get()) {
  308. LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
  309. return NULL;
  310. }
  311. return DtmfSenderProxy::Create(signaling_thread(), sender.get());
  312. }
  313. bool PeerConnection::GetStats(StatsObserver* observer,
  314. MediaStreamTrackInterface* track) {
  315. if (!VERIFY(observer != NULL)) {
  316. LOG(LS_ERROR) << "GetStats - observer is NULL.";
  317. return false;
  318. }
  319. stats_.UpdateStats();
  320. talk_base::scoped_ptr<GetStatsMsg> msg(new GetStatsMsg(observer));
  321. if (!stats_.GetStats(track, &(msg->reports))) {
  322. return false;
  323. }
  324. signaling_thread()->Post(this, MSG_GETSTATS, msg.release());
  325. return true;
  326. }
  327. PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
  328. return signaling_state_;
  329. }
  330. PeerConnectionInterface::IceState PeerConnection::ice_state() {
  331. return ice_state_;
  332. }
  333. PeerConnectionInterface::IceConnectionState
  334. PeerConnection::ice_connection_state() {
  335. return ice_connection_state_;
  336. }
  337. PeerConnectionInterface::IceGatheringState
  338. PeerConnection::ice_gathering_state() {
  339. return ice_gathering_state_;
  340. }
  341. talk_base::scoped_refptr<DataChannelInterface>
  342. PeerConnection::CreateDataChannel(
  343. const std::string& label,
  344. const DataChannelInit* config) {
  345. talk_base::scoped_refptr<DataChannelInterface> channel(
  346. session_->CreateDataChannel(label, config));
  347. if (!channel.get())
  348. return NULL;
  349. observer_->OnRenegotiationNeeded();
  350. return DataChannelProxy::Create(signaling_thread(), channel.get());
  351. }
  352. void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
  353. const MediaConstraintsInterface* constraints) {
  354. if (!VERIFY(observer != NULL)) {
  355. LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
  356. return;
  357. }
  358. CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
  359. msg->description.reset(
  360. session_->CreateOffer(constraints));
  361. if (!msg->description) {
  362. msg->error = "CreateOffer failed.";
  363. signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
  364. return;
  365. }
  366. signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_SUCCESS, msg);
  367. }
  368. void PeerConnection::CreateAnswer(
  369. CreateSessionDescriptionObserver* observer,
  370. const MediaConstraintsInterface* constraints) {
  371. if (!VERIFY(observer != NULL)) {
  372. LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
  373. return;
  374. }
  375. CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
  376. // TODO(perkj): This checks should be done by the session. Not here.
  377. // Clean this up once the old Jsep API has been removed.
  378. const SessionDescriptionInterface* offer = session_->remote_description();
  379. std::string error;
  380. if (!offer) {
  381. msg->error = "CreateAnswer can't be called before SetRemoteDescription.";
  382. signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
  383. return;
  384. }
  385. if (offer->type() != JsepSessionDescription::kOffer) {
  386. msg->error =
  387. "CreateAnswer failed because remote_description is not an offer.";
  388. signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
  389. return;
  390. }
  391. msg->description.reset(session_->CreateAnswer(constraints, offer));
  392. if (!msg->description) {
  393. msg->error = "CreateAnswer failed.";
  394. signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
  395. return;
  396. }
  397. signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_SUCCESS, msg);
  398. }
  399. void PeerConnection::SetLocalDescription(
  400. SetSessionDescriptionObserver* observer,
  401. SessionDescriptionInterface* desc) {
  402. if (!VERIFY(observer != NULL)) {
  403. LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
  404. return;
  405. }
  406. if (!desc) {
  407. PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
  408. return;
  409. }
  410. // Update stats here so that we have the most recent stats for tracks and
  411. // streams that might be removed by updating the session description.
  412. stats_.UpdateStats();
  413. std::string error;
  414. if (!session_->SetLocalDescription(desc, &error)) {
  415. PostSetSessionDescriptionFailure(observer, error);
  416. return;
  417. }
  418. stream_handler_->CommitLocalStreams(local_media_streams_);
  419. SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
  420. signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
  421. }
  422. void PeerConnection::SetRemoteDescription(
  423. SetSessionDescriptionObserver* observer,
  424. SessionDescriptionInterface* desc) {
  425. if (!VERIFY(observer != NULL)) {
  426. LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
  427. return;
  428. }
  429. if (!desc) {
  430. PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
  431. return;
  432. }
  433. // Update stats here so that we have the most recent stats for tracks and
  434. // streams that might be removed by updating the session description.
  435. stats_.UpdateStats();
  436. std::string error;
  437. if (!session_->SetRemoteDescription(desc, &error)) {
  438. PostSetSessionDescriptionFailure(observer, error);
  439. return;
  440. }
  441. SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
  442. signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
  443. }
  444. void PeerConnection::PostSetSessionDescriptionFailure(
  445. SetSessionDescriptionObserver* observer,
  446. const std::string& error) {
  447. SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
  448. msg->error = error;
  449. signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
  450. }
  451. bool PeerConnection::UpdateIce(const IceServers& configuration,
  452. const MediaConstraintsInterface* constraints) {
  453. // TODO(ronghuawu): Implement UpdateIce.
  454. LOG(LS_ERROR) << "UpdateIce is not implemented.";
  455. return false;
  456. }
  457. bool PeerConnection::AddIceCandidate(
  458. const IceCandidateInterface* ice_candidate) {
  459. return session_->ProcessIceMessage(ice_candidate);
  460. }
  461. const SessionDescriptionInterface* PeerConnection::local_description() const {
  462. return session_->local_description();
  463. }
  464. const SessionDescriptionInterface* PeerConnection::remote_description() const {
  465. return session_->remote_description();
  466. }
  467. void PeerConnection::OnSessionStateChange(cricket::BaseSession* /*session*/,
  468. cricket::BaseSession::State state) {
  469. switch (state) {
  470. case cricket::BaseSession::STATE_INIT:
  471. ChangeSignalingState(PeerConnectionInterface::kStable);
  472. case cricket::BaseSession::STATE_SENTINITIATE:
  473. ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
  474. break;
  475. case cricket::BaseSession::STATE_SENTPRACCEPT:
  476. ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
  477. break;
  478. case cricket::BaseSession::STATE_RECEIVEDINITIATE:
  479. ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
  480. break;
  481. case cricket::BaseSession::STATE_RECEIVEDPRACCEPT:
  482. ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
  483. break;
  484. case cricket::BaseSession::STATE_SENTACCEPT:
  485. case cricket::BaseSession::STATE_RECEIVEDACCEPT:
  486. ChangeSignalingState(PeerConnectionInterface::kStable);
  487. break;
  488. default:
  489. break;
  490. }
  491. }
  492. void PeerConnection::OnMessage(talk_base::Message* msg) {
  493. switch (msg->message_id) {
  494. case MSG_CREATE_SESSIONDESCRIPTION_SUCCESS: {
  495. CreateSessionDescriptionMsg* param =
  496. static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
  497. param->observer->OnSuccess(param->description.release());
  498. delete param;
  499. break;
  500. }
  501. case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
  502. CreateSessionDescriptionMsg* param =
  503. static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
  504. param->observer->OnFailure(param->error);
  505. delete param;
  506. break;
  507. }
  508. case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
  509. SetSessionDescriptionMsg* param =
  510. static_cast<SetSessionDescriptionMsg*>(msg->pdata);
  511. param->observer->OnSuccess();
  512. delete param;
  513. break;
  514. }
  515. case MSG_SET_SESSIONDESCRIPTION_FAILED: {
  516. SetSessionDescriptionMsg* param =
  517. static_cast<SetSessionDescriptionMsg*>(msg->pdata);
  518. param->observer->OnFailure(param->error);
  519. delete param;
  520. break;
  521. }
  522. case MSG_GETSTATS: {
  523. GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
  524. param->observer->OnComplete(param->reports);
  525. delete param;
  526. break;
  527. }
  528. case MSG_ICECONNECTIONCHANGE: {
  529. observer_->OnIceConnectionChange(ice_connection_state_);
  530. break;
  531. }
  532. case MSG_ICEGATHERINGCHANGE: {
  533. observer_->OnIceGatheringChange(ice_gathering_state_);
  534. break;
  535. }
  536. case MSG_ICECANDIDATE: {
  537. CandidateMsg* data = static_cast<CandidateMsg*>(msg->pdata);
  538. observer_->OnIceCandidate(data->candidate.get());
  539. delete data;
  540. break;
  541. }
  542. case MSG_ICECOMPLETE: {
  543. observer_->OnIceComplete();
  544. break;
  545. }
  546. default:
  547. ASSERT(!"Not implemented");
  548. break;
  549. }
  550. }
  551. void PeerConnection::OnAddStream(MediaStreamInterface* stream) {
  552. stream_handler_->AddRemoteStream(stream);
  553. stats_.AddStream(stream);
  554. observer_->OnAddStream(stream);
  555. }
  556. void PeerConnection::OnRemoveStream(MediaStreamInterface* stream) {
  557. stream_handler_->RemoveRemoteStream(stream);
  558. observer_->OnRemoveStream(stream);
  559. }
  560. void PeerConnection::OnAddDataChannel(DataChannelInterface* data_channel) {
  561. observer_->OnDataChannel(DataChannelProxy::Create(signaling_thread(),
  562. data_channel));
  563. }
  564. void PeerConnection::OnIceConnectionChange(
  565. PeerConnectionInterface::IceConnectionState new_state) {
  566. ice_connection_state_ = new_state;
  567. signaling_thread()->Post(this, MSG_ICECONNECTIONCHANGE);
  568. }
  569. void PeerConnection::OnIceGatheringChange(
  570. PeerConnectionInterface::IceGatheringState new_state) {
  571. ice_gathering_state_ = new_state;
  572. signaling_thread()->Post(this, MSG_ICEGATHERINGCHANGE);
  573. }
  574. void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
  575. JsepIceCandidate* candidate_copy = NULL;
  576. if (candidate) {
  577. // TODO(ronghuawu): Make IceCandidateInterface reference counted instead
  578. // of making a copy.
  579. candidate_copy = new JsepIceCandidate(candidate->sdp_mid(),
  580. candidate->sdp_mline_index(),
  581. candidate->candidate());
  582. }
  583. // The Post takes the ownership of the |candidate_copy|.
  584. signaling_thread()->Post(this, MSG_ICECANDIDATE,
  585. new CandidateMsg(candidate_copy));
  586. }
  587. void PeerConnection::OnIceComplete() {
  588. signaling_thread()->Post(this, MSG_ICECOMPLETE);
  589. }
  590. void PeerConnection::ChangeSignalingState(
  591. PeerConnectionInterface::SignalingState signaling_state) {
  592. signaling_state_ = signaling_state;
  593. observer_->OnSignalingChange(signaling_state_);
  594. observer_->OnStateChange(PeerConnectionObserver::kSignalingState);
  595. if (signaling_state == kClosed) {
  596. ice_connection_state_ = kIceConnectionClosed;
  597. observer_->OnIceConnectionChange(ice_connection_state_);
  598. }
  599. }
  600. } // namespace webrtc