OLD | NEW |
(Empty) | |
| 1 // Copyright 2014 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include "remoting/host/cast_extension_session.h" |
| 6 |
| 7 #include "base/bind.h" |
| 8 #include "base/json/json_reader.h" |
| 9 #include "base/json/json_writer.h" |
| 10 #include "base/logging.h" |
| 11 #include "base/synchronization/waitable_event.h" |
| 12 #include "net/url_request/url_request_context_getter.h" |
| 13 #include "remoting/host/cast_video_capturer_adapter.h" |
| 14 #include "remoting/host/chromium_port_allocator_factory.h" |
| 15 #include "remoting/host/client_session.h" |
| 16 #include "remoting/proto/control.pb.h" |
| 17 #include "remoting/protocol/client_stub.h" |
| 18 #include "third_party/libjingle/source/talk/app/webrtc/mediastreaminterface.h" |
| 19 #include "third_party/libjingle/source/talk/app/webrtc/test/fakeconstraints.h" |
| 20 #include "third_party/libjingle/source/talk/app/webrtc/videosourceinterface.h" |
| 21 |
| 22 namespace remoting { |
| 23 |
| 24 // Used as the type attribute of all Cast protocol::ExtensionMessages. |
| 25 const char kExtensionMessageType[] = "cast_message"; |
| 26 |
| 27 // Top-level keys used in all extension messages between host and client. |
| 28 // Must keep synced with webapp. |
| 29 const char kTopLevelData[] = "chromoting_data"; |
| 30 const char kTopLevelSubject[] = "subject"; |
| 31 |
| 32 // Keys used to describe the subject of a cast extension message. WebRTC-related |
| 33 // message subjects are prepended with "webrtc_". |
| 34 // Must keep synced with webapp. |
| 35 const char kSubjectReady[] = "ready"; |
| 36 const char kSubjectTest[] = "test"; |
| 37 const char kSubjectNewCandidate[] = "webrtc_candidate"; |
| 38 const char kSubjectOffer[] = "webrtc_offer"; |
| 39 const char kSubjectAnswer[] = "webrtc_answer"; |
| 40 |
| 41 // WebRTC headers used inside messages with subject = "webrtc_*". |
| 42 const char kWebRtcCandidate[] = "candidate"; |
| 43 const char kWebRtcSessionDescType[] = "type"; |
| 44 const char kWebRtcSessionDescSDP[] = "sdp"; |
| 45 const char kWebRtcSDPMid[] = "sdpMid"; |
| 46 const char kWebRtcSDPMLineIndex[] = "sdpMLineIndex"; |
| 47 |
| 48 // Media labels used over the PeerConnection. |
| 49 const char kVideoLabel[] = "cast_video_label"; |
| 50 const char kStreamLabel[] = "stream_label"; |
| 51 |
| 52 // Default STUN server used to construct |
| 53 // webrtc::PeerConnectionInterface::RTCConfiguration for the PeerConnection. |
| 54 const char kDefaultStunURI[] = "stun:stun.l.google.com:19302"; |
| 55 |
| 56 const char kWorkerThreadName[] = "CastExtensionSessionWorkerThread"; |
| 57 |
| 58 // Interval between each call to PollPeerConnectionStats(). |
| 59 const int kStatsLogIntervalSec = 10; |
| 60 |
| 61 // Minimum frame rate for video streaming over the PeerConnection in frames per |
| 62 // second, added as a media constraint when constructing the video source for |
| 63 // the Peer Connection. |
| 64 const int kMinFramesPerSecond = 5; |
| 65 |
| 66 // A webrtc::SetSessionDescriptionObserver implementation used to receive the |
| 67 // results of setting local and remote descriptions of the PeerConnection. |
| 68 class CastSetSessionDescriptionObserver |
| 69 : public webrtc::SetSessionDescriptionObserver { |
| 70 public: |
| 71 static CastSetSessionDescriptionObserver* Create() { |
| 72 return new rtc::RefCountedObject<CastSetSessionDescriptionObserver>(); |
| 73 } |
| 74 virtual void OnSuccess() OVERRIDE { |
| 75 VLOG(1) << "Setting session description succeeded."; |
| 76 } |
| 77 virtual void OnFailure(const std::string& error) OVERRIDE { |
| 78 LOG(ERROR) << "Setting session description failed: " << error; |
| 79 } |
| 80 |
| 81 protected: |
| 82 CastSetSessionDescriptionObserver() {} |
| 83 virtual ~CastSetSessionDescriptionObserver() {} |
| 84 |
| 85 DISALLOW_COPY_AND_ASSIGN(CastSetSessionDescriptionObserver); |
| 86 }; |
| 87 |
| 88 // A webrtc::CreateSessionDescriptionObserver implementation used to receive the |
| 89 // results of creating descriptions for this end of the PeerConnection. |
| 90 class CastCreateSessionDescriptionObserver |
| 91 : public webrtc::CreateSessionDescriptionObserver { |
| 92 public: |
| 93 static CastCreateSessionDescriptionObserver* Create( |
| 94 CastExtensionSession* session) { |
| 95 return new rtc::RefCountedObject<CastCreateSessionDescriptionObserver>( |
| 96 session); |
| 97 } |
| 98 virtual void OnSuccess(webrtc::SessionDescriptionInterface* desc) OVERRIDE { |
| 99 if (cast_extension_session_ == NULL) { |
| 100 LOG(ERROR) |
| 101 << "No CastExtensionSession. Creating session description succeeded."; |
| 102 return; |
| 103 } |
| 104 cast_extension_session_->OnCreateSessionDescription(desc); |
| 105 } |
| 106 virtual void OnFailure(const std::string& error) OVERRIDE { |
| 107 if (cast_extension_session_ == NULL) { |
| 108 LOG(ERROR) |
| 109 << "No CastExtensionSession. Creating session description failed."; |
| 110 return; |
| 111 } |
| 112 cast_extension_session_->OnCreateSessionDescriptionFailure(error); |
| 113 } |
| 114 void SetCastExtensionSession(CastExtensionSession* cast_extension_session) { |
| 115 cast_extension_session_ = cast_extension_session; |
| 116 } |
| 117 |
| 118 protected: |
| 119 explicit CastCreateSessionDescriptionObserver(CastExtensionSession* session) |
| 120 : cast_extension_session_(session) {} |
| 121 virtual ~CastCreateSessionDescriptionObserver() {} |
| 122 |
| 123 private: |
| 124 CastExtensionSession* cast_extension_session_; |
| 125 |
| 126 DISALLOW_COPY_AND_ASSIGN(CastCreateSessionDescriptionObserver); |
| 127 }; |
| 128 |
| 129 // A webrtc::StatsObserver implementation used to receive statistics about the |
| 130 // current PeerConnection. |
| 131 class CastStatsObserver : public webrtc::StatsObserver { |
| 132 public: |
| 133 static CastStatsObserver* Create() { |
| 134 return new rtc::RefCountedObject<CastStatsObserver>(); |
| 135 } |
| 136 |
| 137 virtual void OnComplete( |
| 138 const std::vector<webrtc::StatsReport>& reports) OVERRIDE { |
| 139 typedef webrtc::StatsReport::Values::iterator ValuesIterator; |
| 140 |
| 141 VLOG(1) << "Received " << reports.size() << " new StatsReports."; |
| 142 |
| 143 int index; |
| 144 std::vector<webrtc::StatsReport>::const_iterator it; |
| 145 for (it = reports.begin(), index = 0; it != reports.end(); ++it, ++index) { |
| 146 webrtc::StatsReport::Values v = it->values; |
| 147 VLOG(1) << "Report " << index << ":"; |
| 148 for (ValuesIterator vIt = v.begin(); vIt != v.end(); ++vIt) { |
| 149 VLOG(1) << "Stat: " << vIt->name << "=" << vIt->value << "."; |
| 150 } |
| 151 } |
| 152 } |
| 153 |
| 154 protected: |
| 155 CastStatsObserver() {} |
| 156 virtual ~CastStatsObserver() {} |
| 157 |
| 158 DISALLOW_COPY_AND_ASSIGN(CastStatsObserver); |
| 159 }; |
| 160 |
| 161 // TODO(aiguha): Fix PeerConnnection-related tear down crash caused by premature |
| 162 // destruction of cricket::CaptureManager (which occurs on releasing |
| 163 // |peer_conn_factory_|). See crbug.com/403840. |
| 164 CastExtensionSession::~CastExtensionSession() { |
| 165 DCHECK(caller_task_runner_->BelongsToCurrentThread()); |
| 166 |
| 167 // Explicitly clear |create_session_desc_observer_|'s pointer to |this|, |
| 168 // since the CastExtensionSession is destructing. Otherwise, |
| 169 // |create_session_desc_observer_| would be left with a dangling pointer. |
| 170 create_session_desc_observer_->SetCastExtensionSession(NULL); |
| 171 |
| 172 CleanupPeerConnection(); |
| 173 } |
| 174 |
| 175 // static |
| 176 scoped_ptr<CastExtensionSession> CastExtensionSession::Create( |
| 177 scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner, |
| 178 scoped_refptr<net::URLRequestContextGetter> url_request_context_getter, |
| 179 const protocol::NetworkSettings& network_settings, |
| 180 ClientSessionControl* client_session_control, |
| 181 protocol::ClientStub* client_stub) { |
| 182 scoped_ptr<CastExtensionSession> cast_extension_session( |
| 183 new CastExtensionSession(caller_task_runner, |
| 184 url_request_context_getter, |
| 185 network_settings, |
| 186 client_session_control, |
| 187 client_stub)); |
| 188 if (!cast_extension_session->WrapTasksAndSave()) { |
| 189 return scoped_ptr<CastExtensionSession>(); |
| 190 } |
| 191 if (!cast_extension_session->InitializePeerConnection()) { |
| 192 return scoped_ptr<CastExtensionSession>(); |
| 193 } |
| 194 return cast_extension_session.Pass(); |
| 195 } |
| 196 |
| 197 void CastExtensionSession::OnCreateSessionDescription( |
| 198 webrtc::SessionDescriptionInterface* desc) { |
| 199 if (!caller_task_runner_->BelongsToCurrentThread()) { |
| 200 caller_task_runner_->PostTask( |
| 201 FROM_HERE, |
| 202 base::Bind(&CastExtensionSession::OnCreateSessionDescription, |
| 203 base::Unretained(this), |
| 204 desc)); |
| 205 return; |
| 206 } |
| 207 |
| 208 peer_connection_->SetLocalDescription( |
| 209 CastSetSessionDescriptionObserver::Create(), desc); |
| 210 |
| 211 scoped_ptr<base::DictionaryValue> json(new base::DictionaryValue()); |
| 212 json->SetString(kWebRtcSessionDescType, desc->type()); |
| 213 std::string subject = |
| 214 (desc->type() == "offer") ? kSubjectOffer : kSubjectAnswer; |
| 215 std::string desc_str; |
| 216 desc->ToString(&desc_str); |
| 217 json->SetString(kWebRtcSessionDescSDP, desc_str); |
| 218 std::string json_str; |
| 219 if (!base::JSONWriter::Write(json.get(), &json_str)) { |
| 220 LOG(ERROR) << "Failed to serialize sdp message."; |
| 221 return; |
| 222 } |
| 223 |
| 224 SendMessageToClient(subject.c_str(), json_str); |
| 225 } |
| 226 |
| 227 void CastExtensionSession::OnCreateSessionDescriptionFailure( |
| 228 const std::string& error) { |
| 229 VLOG(1) << "Creating Session Description failed: " << error; |
| 230 } |
| 231 |
| 232 // TODO(aiguha): Support the case(s) where we've grabbed the capturer already, |
| 233 // but another extension reset the video pipeline. We should remove the |
| 234 // stream from the peer connection here, and then attempt to re-setup the |
| 235 // peer connection in the OnRenegotiationNeeded() callback. |
| 236 // See crbug.com/403843. |
| 237 scoped_ptr<webrtc::DesktopCapturer> CastExtensionSession::OnCreateVideoCapturer( |
| 238 scoped_ptr<webrtc::DesktopCapturer> capturer) { |
| 239 if (has_grabbed_capturer_) { |
| 240 LOG(ERROR) << "The video pipeline was reset unexpectedly."; |
| 241 has_grabbed_capturer_ = false; |
| 242 peer_connection_->RemoveStream(stream_.release()); |
| 243 return capturer.Pass(); |
| 244 } |
| 245 |
| 246 if (received_offer_) { |
| 247 has_grabbed_capturer_ = true; |
| 248 if (SetupVideoStream(capturer.Pass())) { |
| 249 peer_connection_->CreateAnswer(create_session_desc_observer_, NULL); |
| 250 } else { |
| 251 has_grabbed_capturer_ = false; |
| 252 // Ignore the received offer, since we failed to setup a video stream. |
| 253 received_offer_ = false; |
| 254 } |
| 255 return scoped_ptr<webrtc::DesktopCapturer>(); |
| 256 } |
| 257 |
| 258 return capturer.Pass(); |
| 259 } |
| 260 |
| 261 bool CastExtensionSession::ModifiesVideoPipeline() const { |
| 262 return true; |
| 263 } |
| 264 |
| 265 // Returns true if the |message| is a Cast ExtensionMessage, even if |
| 266 // it was badly formed or a resulting action failed. This is done so that |
| 267 // the host does not continue to attempt to pass |message| to other |
| 268 // HostExtensionSessions. |
| 269 bool CastExtensionSession::OnExtensionMessage( |
| 270 ClientSessionControl* client_session_control, |
| 271 protocol::ClientStub* client_stub, |
| 272 const protocol::ExtensionMessage& message) { |
| 273 if (message.type() != kExtensionMessageType) { |
| 274 return false; |
| 275 } |
| 276 |
| 277 scoped_ptr<base::Value> value(base::JSONReader::Read(message.data())); |
| 278 base::DictionaryValue* client_message; |
| 279 if (!(value && value->GetAsDictionary(&client_message))) { |
| 280 LOG(ERROR) << "Could not read cast extension message."; |
| 281 return true; |
| 282 } |
| 283 |
| 284 std::string subject; |
| 285 if (!client_message->GetString(kTopLevelSubject, &subject)) { |
| 286 LOG(ERROR) << "Invalid Cast Extension Message (missing subject header)."; |
| 287 return true; |
| 288 } |
| 289 |
| 290 if (subject == kSubjectOffer && !received_offer_) { |
| 291 // Reset the video pipeline so we can grab the screen capturer and setup |
| 292 // a video stream. |
| 293 if (ParseAndSetRemoteDescription(client_message)) { |
| 294 received_offer_ = true; |
| 295 LOG(INFO) << "About to ResetVideoPipeline."; |
| 296 client_session_control_->ResetVideoPipeline(); |
| 297 |
| 298 } |
| 299 } else if (subject == kSubjectAnswer) { |
| 300 ParseAndSetRemoteDescription(client_message); |
| 301 } else if (subject == kSubjectNewCandidate) { |
| 302 ParseAndAddICECandidate(client_message); |
| 303 } else { |
| 304 VLOG(1) << "Unexpected CastExtension Message: " << message.data(); |
| 305 } |
| 306 return true; |
| 307 } |
| 308 |
| 309 // Private methods ------------------------------------------------------------ |
| 310 |
| 311 CastExtensionSession::CastExtensionSession( |
| 312 scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner, |
| 313 scoped_refptr<net::URLRequestContextGetter> url_request_context_getter, |
| 314 const protocol::NetworkSettings& network_settings, |
| 315 ClientSessionControl* client_session_control, |
| 316 protocol::ClientStub* client_stub) |
| 317 : caller_task_runner_(caller_task_runner), |
| 318 url_request_context_getter_(url_request_context_getter), |
| 319 network_settings_(network_settings), |
| 320 client_session_control_(client_session_control), |
| 321 client_stub_(client_stub), |
| 322 stats_observer_(CastStatsObserver::Create()), |
| 323 received_offer_(false), |
| 324 has_grabbed_capturer_(false), |
| 325 signaling_thread_wrapper_(NULL), |
| 326 worker_thread_wrapper_(NULL), |
| 327 worker_thread_(kWorkerThreadName) { |
| 328 DCHECK(caller_task_runner_->BelongsToCurrentThread()); |
| 329 DCHECK(url_request_context_getter_); |
| 330 DCHECK(client_session_control_); |
| 331 DCHECK(client_stub_); |
| 332 |
| 333 // The worker thread is created with base::MessageLoop::TYPE_IO because |
| 334 // the PeerConnection performs some port allocation operations on this thread |
| 335 // that require it. See crbug.com/404013. |
| 336 base::Thread::Options options(base::MessageLoop::TYPE_IO, 0); |
| 337 worker_thread_.StartWithOptions(options); |
| 338 worker_task_runner_ = worker_thread_.task_runner(); |
| 339 } |
| 340 |
| 341 bool CastExtensionSession::ParseAndSetRemoteDescription( |
| 342 base::DictionaryValue* message) { |
| 343 DCHECK(peer_connection_.get() != NULL); |
| 344 |
| 345 base::DictionaryValue* message_data; |
| 346 if (!message->GetDictionary(kTopLevelData, &message_data)) { |
| 347 LOG(ERROR) << "Invalid Cast Extension Message (missing data)."; |
| 348 return false; |
| 349 } |
| 350 |
| 351 std::string webrtc_type; |
| 352 if (!message_data->GetString(kWebRtcSessionDescType, &webrtc_type)) { |
| 353 LOG(ERROR) |
| 354 << "Invalid Cast Extension Message (missing webrtc type header)."; |
| 355 return false; |
| 356 } |
| 357 |
| 358 std::string sdp; |
| 359 if (!message_data->GetString(kWebRtcSessionDescSDP, &sdp)) { |
| 360 LOG(ERROR) << "Invalid Cast Extension Message (missing webrtc sdp header)."; |
| 361 return false; |
| 362 } |
| 363 |
| 364 webrtc::SdpParseError error; |
| 365 webrtc::SessionDescriptionInterface* session_description( |
| 366 webrtc::CreateSessionDescription(webrtc_type, sdp, &error)); |
| 367 |
| 368 if (!session_description) { |
| 369 LOG(ERROR) << "Invalid Cast Extension Message (could not parse sdp)."; |
| 370 VLOG(1) << "SdpParseError was: " << error.description; |
| 371 return false; |
| 372 } |
| 373 |
| 374 peer_connection_->SetRemoteDescription( |
| 375 CastSetSessionDescriptionObserver::Create(), session_description); |
| 376 return true; |
| 377 } |
| 378 |
| 379 bool CastExtensionSession::ParseAndAddICECandidate( |
| 380 base::DictionaryValue* message) { |
| 381 DCHECK(peer_connection_.get() != NULL); |
| 382 |
| 383 base::DictionaryValue* message_data; |
| 384 if (!message->GetDictionary(kTopLevelData, &message_data)) { |
| 385 LOG(ERROR) << "Invalid Cast Extension Message (missing data)."; |
| 386 return false; |
| 387 } |
| 388 |
| 389 std::string candidate_str; |
| 390 std::string sdp_mid; |
| 391 int sdp_mlineindex = 0; |
| 392 if (!message_data->GetString(kWebRtcSDPMid, &sdp_mid) || |
| 393 !message_data->GetInteger(kWebRtcSDPMLineIndex, &sdp_mlineindex) || |
| 394 !message_data->GetString(kWebRtcCandidate, &candidate_str)) { |
| 395 LOG(ERROR) << "Invalid Cast Extension Message (could not parse)."; |
| 396 return false; |
| 397 } |
| 398 |
| 399 rtc::scoped_ptr<webrtc::IceCandidateInterface> candidate( |
| 400 webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, candidate_str)); |
| 401 if (!candidate.get()) { |
| 402 LOG(ERROR) |
| 403 << "Invalid Cast Extension Message (could not create candidate)."; |
| 404 return false; |
| 405 } |
| 406 |
| 407 if (!peer_connection_->AddIceCandidate(candidate.get())) { |
| 408 LOG(ERROR) << "Failed to apply received ICE Candidate to PeerConnection."; |
| 409 return false; |
| 410 } |
| 411 |
| 412 VLOG(1) << "Received and Added ICE Candidate: " << candidate_str; |
| 413 |
| 414 return true; |
| 415 } |
| 416 |
| 417 bool CastExtensionSession::SendMessageToClient(const std::string& subject, |
| 418 const std::string& data) { |
| 419 DCHECK(caller_task_runner_->BelongsToCurrentThread()); |
| 420 |
| 421 if (client_stub_ == NULL) { |
| 422 LOG(ERROR) << "No Client Stub. Cannot send message to client."; |
| 423 return false; |
| 424 } |
| 425 |
| 426 base::DictionaryValue message_dict; |
| 427 message_dict.SetString(kTopLevelSubject, subject); |
| 428 message_dict.SetString(kTopLevelData, data); |
| 429 std::string message_json; |
| 430 |
| 431 if (!base::JSONWriter::Write(&message_dict, &message_json)) { |
| 432 LOG(ERROR) << "Failed to serialize JSON message."; |
| 433 return false; |
| 434 } |
| 435 |
| 436 protocol::ExtensionMessage message; |
| 437 message.set_type(kExtensionMessageType); |
| 438 message.set_data(message_json); |
| 439 client_stub_->DeliverHostMessage(message); |
| 440 return true; |
| 441 } |
| 442 |
| 443 void CastExtensionSession::EnsureTaskAndSetSend(rtc::Thread** ptr, |
| 444 base::WaitableEvent* event) { |
| 445 jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop(); |
| 446 jingle_glue::JingleThreadWrapper::current()->set_send_allowed(true); |
| 447 *ptr = jingle_glue::JingleThreadWrapper::current(); |
| 448 |
| 449 if (event != NULL) { |
| 450 event->Signal(); |
| 451 } |
| 452 } |
| 453 |
| 454 bool CastExtensionSession::WrapTasksAndSave() { |
| 455 DCHECK(caller_task_runner_->BelongsToCurrentThread()); |
| 456 |
| 457 EnsureTaskAndSetSend(&signaling_thread_wrapper_); |
| 458 if (signaling_thread_wrapper_ == NULL) |
| 459 return false; |
| 460 |
| 461 base::WaitableEvent wrap_worker_thread_event(true, false); |
| 462 worker_task_runner_->PostTask( |
| 463 FROM_HERE, |
| 464 base::Bind(&CastExtensionSession::EnsureTaskAndSetSend, |
| 465 base::Unretained(this), |
| 466 &worker_thread_wrapper_, |
| 467 &wrap_worker_thread_event)); |
| 468 wrap_worker_thread_event.Wait(); |
| 469 |
| 470 return (worker_thread_wrapper_ != NULL); |
| 471 } |
| 472 |
| 473 bool CastExtensionSession::InitializePeerConnection() { |
| 474 DCHECK(caller_task_runner_->BelongsToCurrentThread()); |
| 475 DCHECK(!peer_conn_factory_); |
| 476 DCHECK(!peer_connection_); |
| 477 DCHECK(worker_thread_wrapper_ != NULL); |
| 478 DCHECK(signaling_thread_wrapper_ != NULL); |
| 479 |
| 480 peer_conn_factory_ = webrtc::CreatePeerConnectionFactory( |
| 481 worker_thread_wrapper_, signaling_thread_wrapper_, NULL, NULL, NULL); |
| 482 |
| 483 if (!peer_conn_factory_.get()) { |
| 484 CleanupPeerConnection(); |
| 485 return false; |
| 486 } |
| 487 |
| 488 VLOG(1) << "Created PeerConnectionFactory successfully."; |
| 489 |
| 490 webrtc::PeerConnectionInterface::IceServers servers; |
| 491 webrtc::PeerConnectionInterface::IceServer server; |
| 492 server.uri = kDefaultStunURI; |
| 493 servers.push_back(server); |
| 494 webrtc::PeerConnectionInterface::RTCConfiguration rtc_config; |
| 495 rtc_config.servers = servers; |
| 496 |
| 497 // DTLS-SRTP is the preferred encryption method. If set to kValueFalse, the |
| 498 // peer connection uses SDES. Disabling SDES as well will cause the peer |
| 499 // connection to fail to connect. |
| 500 // Note: For protection and unprotection of SRTP packets, the libjingle |
| 501 // ENABLE_EXTERNAL_AUTH flag must not be set. |
| 502 webrtc::FakeConstraints constraints; |
| 503 constraints.AddMandatory(webrtc::MediaConstraintsInterface::kEnableDtlsSrtp, |
| 504 webrtc::MediaConstraintsInterface::kValueTrue); |
| 505 |
| 506 rtc::scoped_refptr<webrtc::PortAllocatorFactoryInterface> |
| 507 port_allocator_factory = ChromiumPortAllocatorFactory::Create( |
| 508 network_settings_, url_request_context_getter_); |
| 509 |
| 510 peer_connection_ = peer_conn_factory_->CreatePeerConnection( |
| 511 rtc_config, &constraints, port_allocator_factory, NULL, this); |
| 512 |
| 513 if (!peer_connection_.get()) { |
| 514 CleanupPeerConnection(); |
| 515 return false; |
| 516 } |
| 517 |
| 518 VLOG(1) << "Created PeerConnection successfully."; |
| 519 |
| 520 create_session_desc_observer_ = |
| 521 CastCreateSessionDescriptionObserver::Create(this); |
| 522 |
| 523 // Send a test message to the client. Then, notify the client to start |
| 524 // webrtc offer/answer negotiation. |
| 525 if (!SendMessageToClient(kSubjectTest, "Hello, client.") || |
| 526 !SendMessageToClient(kSubjectReady, "Host ready to receive offers.")) { |
| 527 LOG(ERROR) << "Failed to send messages to client."; |
| 528 return false; |
| 529 } |
| 530 |
| 531 return true; |
| 532 } |
| 533 |
| 534 bool CastExtensionSession::SetupVideoStream( |
| 535 scoped_ptr<webrtc::DesktopCapturer> desktop_capturer) { |
| 536 DCHECK(caller_task_runner_->BelongsToCurrentThread()); |
| 537 DCHECK(desktop_capturer); |
| 538 |
| 539 if (stream_) { |
| 540 VLOG(1) << "Already added MediaStream. Aborting Setup."; |
| 541 return false; |
| 542 } |
| 543 |
| 544 scoped_ptr<CastVideoCapturerAdapter> cast_video_capturer_adapter( |
| 545 new CastVideoCapturerAdapter(desktop_capturer.Pass())); |
| 546 |
| 547 // Set video stream constraints. |
| 548 webrtc::FakeConstraints video_constraints; |
| 549 video_constraints.AddMandatory( |
| 550 webrtc::MediaConstraintsInterface::kMinFrameRate, kMinFramesPerSecond); |
| 551 |
| 552 rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track = |
| 553 peer_conn_factory_->CreateVideoTrack( |
| 554 kVideoLabel, |
| 555 peer_conn_factory_->CreateVideoSource( |
| 556 cast_video_capturer_adapter.release(), &video_constraints)); |
| 557 |
| 558 stream_ = peer_conn_factory_->CreateLocalMediaStream(kStreamLabel); |
| 559 |
| 560 if (!stream_->AddTrack(video_track) || |
| 561 !peer_connection_->AddStream(stream_, NULL)) { |
| 562 return false; |
| 563 } |
| 564 |
| 565 VLOG(1) << "Setup video stream successfully."; |
| 566 |
| 567 return true; |
| 568 } |
| 569 |
| 570 void CastExtensionSession::PollPeerConnectionStats() { |
| 571 if (!connection_active()) { |
| 572 VLOG(1) << "Cannot poll stats while PeerConnection is inactive."; |
| 573 } |
| 574 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> video_track = |
| 575 stream_->FindVideoTrack(kVideoLabel); |
| 576 peer_connection_->GetStats( |
| 577 stats_observer_, |
| 578 video_track.release(), |
| 579 webrtc::PeerConnectionInterface::kStatsOutputLevelStandard); |
| 580 } |
| 581 |
| 582 void CastExtensionSession::CleanupPeerConnection() { |
| 583 peer_connection_->Close(); |
| 584 peer_connection_ = NULL; |
| 585 stream_ = NULL; |
| 586 peer_conn_factory_ = NULL; |
| 587 worker_thread_.Stop(); |
| 588 } |
| 589 |
| 590 bool CastExtensionSession::connection_active() const { |
| 591 return peer_connection_.get() != NULL; |
| 592 } |
| 593 |
| 594 // webrtc::PeerConnectionObserver implementation ------------------------------- |
| 595 |
| 596 void CastExtensionSession::OnError() { |
| 597 VLOG(1) << "PeerConnectionObserver: an error occurred."; |
| 598 } |
| 599 |
| 600 void CastExtensionSession::OnSignalingChange( |
| 601 webrtc::PeerConnectionInterface::SignalingState new_state) { |
| 602 VLOG(1) << "PeerConnectionObserver: SignalingState changed to:" << new_state; |
| 603 } |
| 604 |
| 605 void CastExtensionSession::OnStateChange( |
| 606 webrtc::PeerConnectionObserver::StateType state_changed) { |
| 607 VLOG(1) << "PeerConnectionObserver: StateType changed to: " << state_changed; |
| 608 } |
| 609 |
| 610 void CastExtensionSession::OnAddStream(webrtc::MediaStreamInterface* stream) { |
| 611 VLOG(1) << "PeerConnectionObserver: stream added: " << stream->label(); |
| 612 } |
| 613 |
| 614 void CastExtensionSession::OnRemoveStream( |
| 615 webrtc::MediaStreamInterface* stream) { |
| 616 VLOG(1) << "PeerConnectionObserver: stream removed: " << stream->label(); |
| 617 } |
| 618 |
| 619 void CastExtensionSession::OnDataChannel( |
| 620 webrtc::DataChannelInterface* data_channel) { |
| 621 VLOG(1) << "PeerConnectionObserver: data channel: " << data_channel->label(); |
| 622 } |
| 623 |
| 624 void CastExtensionSession::OnRenegotiationNeeded() { |
| 625 VLOG(1) << "PeerConnectionObserver: renegotiation needed."; |
| 626 } |
| 627 |
| 628 void CastExtensionSession::OnIceConnectionChange( |
| 629 webrtc::PeerConnectionInterface::IceConnectionState new_state) { |
| 630 VLOG(1) << "PeerConnectionObserver: IceConnectionState changed to: " |
| 631 << new_state; |
| 632 |
| 633 // TODO(aiguha): Maybe start timer only if enabled by command-line flag or |
| 634 // at a particular verbosity level. |
| 635 if (!stats_polling_timer_.IsRunning() && |
| 636 new_state == webrtc::PeerConnectionInterface::kIceConnectionConnected) { |
| 637 stats_polling_timer_.Start( |
| 638 FROM_HERE, |
| 639 base::TimeDelta::FromSeconds(kStatsLogIntervalSec), |
| 640 this, |
| 641 &CastExtensionSession::PollPeerConnectionStats); |
| 642 } |
| 643 } |
| 644 |
| 645 void CastExtensionSession::OnIceGatheringChange( |
| 646 webrtc::PeerConnectionInterface::IceGatheringState new_state) { |
| 647 VLOG(1) << "PeerConnectionObserver: IceGatheringState changed to: " |
| 648 << new_state; |
| 649 } |
| 650 |
| 651 void CastExtensionSession::OnIceComplete() { |
| 652 VLOG(1) << "PeerConnectionObserver: all ICE candidates found."; |
| 653 } |
| 654 |
| 655 void CastExtensionSession::OnIceCandidate( |
| 656 const webrtc::IceCandidateInterface* candidate) { |
| 657 std::string candidate_str; |
| 658 if (!candidate->ToString(&candidate_str)) { |
| 659 LOG(ERROR) << "PeerConnectionObserver: failed to serialize candidate."; |
| 660 return; |
| 661 } |
| 662 scoped_ptr<base::DictionaryValue> json(new base::DictionaryValue()); |
| 663 json->SetString(kWebRtcSDPMid, candidate->sdp_mid()); |
| 664 json->SetInteger(kWebRtcSDPMLineIndex, candidate->sdp_mline_index()); |
| 665 json->SetString(kWebRtcCandidate, candidate_str); |
| 666 std::string json_str; |
| 667 if (!base::JSONWriter::Write(json.get(), &json_str)) { |
| 668 LOG(ERROR) << "Failed to serialize candidate message."; |
| 669 return; |
| 670 } |
| 671 SendMessageToClient(kSubjectNewCandidate, json_str); |
| 672 } |
| 673 |
| 674 } // namespace remoting |
| 675 |
OLD | NEW |