Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1831)

Unified Diff: remoting/host/cast_extension_session.cc

Issue 399253002: CastExtension Impl for Chromoting Host (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Changes based on review Created 6 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: remoting/host/cast_extension_session.cc
diff --git a/remoting/host/cast_extension_session.cc b/remoting/host/cast_extension_session.cc
new file mode 100644
index 0000000000000000000000000000000000000000..3652d4616c6645c7160dc7c2850121f930d197ab
--- /dev/null
+++ b/remoting/host/cast_extension_session.cc
@@ -0,0 +1,679 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "remoting/host/cast_extension_session.h"
+
+#include "base/bind.h"
+#include "base/json/json_reader.h"
+#include "base/json/json_writer.h"
+#include "base/logging.h"
+#include "base/synchronization/waitable_event.h"
+#include "net/url_request/url_request_context_getter.h"
+#include "remoting/host/cast_video_capturer_adapter.h"
+#include "remoting/host/chromium_port_allocator_factory.h"
+#include "remoting/host/client_session.h"
+#include "remoting/proto/control.pb.h"
+#include "remoting/protocol/client_stub.h"
+#include "third_party/libjingle/source/talk/app/webrtc/mediastreaminterface.h"
+#include "third_party/libjingle/source/talk/app/webrtc/test/fakeconstraints.h"
+#include "third_party/libjingle/source/talk/app/webrtc/videosourceinterface.h"
+#include "third_party/webrtc/modules/desktop_capture/mouse_cursor_shape.h"
+
+namespace remoting {
+
+// Used as type attribute of all Cast extension messages.
+const char kMessageType[] = "cast_message";
+
+// Top-level keys used in all extension messages between host and client.
+// Must keep synced with webapp.
+const char kMessageData[] = "chromoting_data";
Wez 2014/08/12 22:15:01 These two names are confusing; suggest kCastMessag
aiguha 2014/08/13 18:33:27 Yes, I can see how that's confusing. kMessageType
Wez 2014/08/14 19:22:03 Come to think of it, "cast" arguably shouldn't fea
aiguha 2014/08/15 04:11:39 I originally had it named WebRtcHostExtension[Sess
+const char kMessageSubject[] = "subject";
+
+// Keys used to describe the subject of a cast extension message. WebRTC-related
+// message subjects are prepended with "webrtc_".
+const char kSubjectReady[] = "ready";
+const char kSubjectTest[] = "test";
+const char kSubjectNewCandidate[] = "webrtc_candidate";
+const char kSubjectOffer[] = "webrtc_offer";
+const char kSubjectAnswer[] = "webrtc_answer";
+
+// WebRTC headers used inside cast extension messages.
+const char kWebRtcCandidate[] = "candidate";
+const char kWebRtcSessionDescType[] = "type";
+const char kWebRtcSessionDescSDP[] = "sdp";
+const char kWebRtcSDPMid[] = "sdpMid";
+const char kWebRtcSDPMLineIndex[] = "sdpMLineIndex";
+
+// Constants used over the PeerConnection.
+const char kVideoLabel[] = "cast_video_label";
+const char kStreamLabel[] = "stream_label";
+const char kDefaultStunURI[] = "stun:stun.l.google.com:19302";
+
+const char kWorkerThreadName[] = "CastExtensionSessionWorkerThread";
+
+// Interval between each call to PollPeerConnectionStats().
+const int kStatsLogIntervalSec = 10;
+
+// Minimum frame rate for video streaming over the PeerConnection.
Wez 2014/08/12 22:15:00 What are the units? Why is this a char rather than
aiguha 2014/08/13 18:33:27 Clarified in the comment now. It's in fps. We're u
+const char kMinFrameRate[] = "5";
+
+// A webrtc::SetSessionDescriptionObserver implementation used to receive the
+// results of setting local and remote descriptions of the PeerConnection.
+class CastSetSessionDescriptionObserver
+ : public webrtc::SetSessionDescriptionObserver {
+ public:
+ static CastSetSessionDescriptionObserver* Create() {
+ return new rtc::RefCountedObject<CastSetSessionDescriptionObserver>();
+ }
+ virtual void OnSuccess() OVERRIDE {
+ VLOG(1) << "Setting session description succeeded.";
+ }
+ virtual void OnFailure(const std::string& error) OVERRIDE {
+ LOG(ERROR) << "Setting session description failed: " << error;
+ }
+
+ protected:
+ CastSetSessionDescriptionObserver() {}
+ virtual ~CastSetSessionDescriptionObserver() {}
+
+ DISALLOW_COPY_AND_ASSIGN(CastSetSessionDescriptionObserver);
+};
+
+// A webrtc::CreateSessionDescriptionObserver implementation used to receive the
+// results of creating descriptions for this end of the PeerConnection.
+class CastCreateSessionDescriptionObserver
+ : public webrtc::CreateSessionDescriptionObserver {
+ public:
+ static CastCreateSessionDescriptionObserver* Create(
+ CastExtensionSession* session) {
+ return new rtc::RefCountedObject<CastCreateSessionDescriptionObserver>(
+ session);
+ }
+ virtual void OnSuccess(webrtc::SessionDescriptionInterface* desc) OVERRIDE {
+ if (session_ == NULL) {
+ LOG(ERROR) << "No Session, cannot create session description.";
+ return;
+ }
+ session_->OnCreateSessionDescription(desc);
+ }
+ virtual void OnFailure(const std::string& error) OVERRIDE {
+ if (session_ == NULL) {
+ LOG(ERROR) << "No Session, cannot create session description.";
+ return;
+ }
+ session_->OnCreateSessionDescriptionFailure(error);
+ }
+
+ protected:
+ explicit CastCreateSessionDescriptionObserver(CastExtensionSession* session)
+ : session_(session) {}
+ virtual ~CastCreateSessionDescriptionObserver() {}
+
+ private:
+ CastExtensionSession* session_;
+
+ DISALLOW_COPY_AND_ASSIGN(CastCreateSessionDescriptionObserver);
+};
+
+// A webrtc::StatsObserver implementation used to receive statistics about the
+// current PeerConnection.
+class CastStatsObserver : public webrtc::StatsObserver {
+ public:
+ static CastStatsObserver* Create() {
+ return new rtc::RefCountedObject<CastStatsObserver>();
+ }
+
+ virtual void OnComplete(
+ const std::vector<webrtc::StatsReport>& reports) OVERRIDE {
+ typedef webrtc::StatsReport::Values::iterator ValuesIterator;
+
+ VLOG(1) << "Received " << reports.size() << " new StatsReports.";
+
+ int index;
+ std::vector<webrtc::StatsReport>::const_iterator it;
+ for (it = reports.begin(), index = 0; it != reports.end(); ++it, ++index) {
+ webrtc::StatsReport::Values v = it->values;
+ VLOG(1) << "Report " << index << ":";
+ for (ValuesIterator vIt = v.begin(); vIt != v.end(); ++vIt) {
+ VLOG(1) << "Stat: " << vIt->name << "=" << vIt->value << ".";
+ }
+ }
+ }
+
+ protected:
+ CastStatsObserver() {}
+ virtual ~CastStatsObserver() {}
+
+ DISALLOW_COPY_AND_ASSIGN(CastStatsObserver);
+};
+
+// TODO(aiguha): Fix PeerConnnection-related tear down crash caused by premature
+// destruction of cricket::CaptureManager (which occurs on releasing
+// |peer_conn_factory_|). For more details, see bug:.
aiguha 2014/08/12 01:42:41 Filing the bug shortly.
+CastExtensionSession::~CastExtensionSession() {
+ DCHECK(network_task_runner_->BelongsToCurrentThread());
+ CleanupPeerConnection();
+}
+
+// static
+scoped_ptr<CastExtensionSession> CastExtensionSession::Create(
+ scoped_refptr<base::SingleThreadTaskRunner> network_task_runner,
+ scoped_refptr<net::URLRequestContextGetter> url_request_context_getter,
+ const protocol::NetworkSettings& network_settings,
+ ClientSessionControl* client_session_control,
+ protocol::ClientStub* client_stub) {
+ scoped_ptr<CastExtensionSession> cast_extension_session(
+ new CastExtensionSession(network_task_runner,
+ url_request_context_getter,
+ network_settings,
+ client_session_control,
+ client_stub));
+ if (!cast_extension_session->WrapTasksAndSave()) {
+ return scoped_ptr<CastExtensionSession>();
+ }
+ if (!cast_extension_session->InitializePeerConnection()) {
+ return scoped_ptr<CastExtensionSession>();
+ }
+ return cast_extension_session.Pass();
+}
+
+void CastExtensionSession::OnCreateSessionDescription(
+ webrtc::SessionDescriptionInterface* desc) {
Wez 2014/08/12 22:15:00 nit: Separate out the logical chunks of code in th
aiguha 2014/08/13 18:33:27 Done.
+ if (!network_task_runner_->BelongsToCurrentThread()) {
+ network_task_runner_->PostTask(
+ FROM_HERE,
+ base::Bind(&CastExtensionSession::OnCreateSessionDescription,
+ base::Unretained(this),
+ desc));
+ return;
+ }
+ peer_connection_->SetLocalDescription(
+ CastSetSessionDescriptionObserver::Create(), desc);
+ scoped_ptr<base::DictionaryValue> json(new base::DictionaryValue());
+ json->SetString(kWebRtcSessionDescType, desc->type());
+ std::string subject =
+ (desc->type() == "offer") ? kSubjectOffer : kSubjectAnswer;
+ std::string desc_str;
+ desc->ToString(&desc_str);
+ json->SetString(kWebRtcSessionDescSDP, desc_str);
+ std::string json_str;
+ if (!base::JSONWriter::Write(json.get(), &json_str)) {
+ LOG(ERROR) << "Failed to serialize sdp message.";
+ return;
+ }
+ SendMessageToClient(subject.c_str(), json_str);
+}
+
+void CastExtensionSession::OnCreateSessionDescriptionFailure(
+ const std::string& error) {
+ VLOG(1) << "Creating Session Description failed: " << error;
+}
+
+// TODO(aiguha): Support the case(s) where we've grabbed the capturer already,
+// but another extension reset the video pipeline. We should remove the
+// stream from the peer connection here, and then attempt to re-setup the
+// peer connection in the OnRenegotiationNeeded() callback.
Wez 2014/08/12 22:15:01 nit: File a bug for that work and refer to it here
aiguha 2014/08/13 18:33:28 Acknowledged.
+scoped_ptr<webrtc::ScreenCapturer> CastExtensionSession::OnCreateVideoCapturer(
+ scoped_ptr<webrtc::ScreenCapturer> capturer) {
+ if (has_grabbed_capturer_) {
+ LOG(ERROR) << "The video pipeline was reset unexpectedly.";
+ has_grabbed_capturer_ = false;
+ peer_connection_->RemoveStream(stream_.release());
+ return capturer.Pass();
+ }
+
+ if (received_offer_) {
+ has_grabbed_capturer_ = true;
+ if (SetupVideoStream(capturer.Pass())) {
+ peer_connection_->CreateAnswer(
+ CastCreateSessionDescriptionObserver::Create(this), NULL);
+ } else {
+ has_grabbed_capturer_ = false;
+ // Ignore the received offer, since we failed to setup a video stream.
+ received_offer_ = false;
+ }
+ return scoped_ptr<webrtc::ScreenCapturer>();
+ }
+
+ return capturer.Pass();
+}
+
+bool CastExtensionSession::ModifiesVideoPipeline() const {
+ return true;
+}
+
+// Returns true if the ExtensionMessage was of type |kMessageType|, even if
Wez 2014/08/12 22:15:00 nit: You mean if its a Cast extension message?
aiguha 2014/08/13 18:33:27 Yes, that would be simpler!
+// it was badly formed or a resulting action failed. This is done so that
+// the host does not continue to attempt to pass |message| to other
+// HostExtensionSessions.
+bool CastExtensionSession::OnExtensionMessage(
+ ClientSessionControl* client_session_control,
+ protocol::ClientStub* client_stub,
+ const protocol::ExtensionMessage& message) {
+ if (message.type() != kMessageType) {
+ return false;
+ }
+
+ scoped_ptr<base::Value> value(base::JSONReader::Read(message.data()));
+ base::DictionaryValue* client_message;
+ if (!(value && value->GetAsDictionary(&client_message))) {
+ LOG(ERROR) << "Could not read cast extension message.";
+ return true;
+ }
+
+ std::string subject;
+ if (!client_message->GetString(kMessageSubject, &subject)) {
+ LOG(ERROR) << "Invalid Cast Extension Message (missing subject header).";
+ return true;
+ }
+
+ if (subject == kSubjectOffer && !received_offer_) {
+ // Reset the video pipeline so we can grab the screen capturer and setup
+ // a video stream.
+ if (ParseAndSetRemoteDescription(client_message)) {
+ received_offer_ = true;
+ client_session_control_->ResetVideoPipeline();
+ }
+ } else if (subject == kSubjectAnswer) {
+ ParseAndSetRemoteDescription(client_message);
+ } else if (subject == kSubjectNewCandidate) {
+ ParseAndAddICECandidate(client_message);
+ } else {
+ VLOG(1) << "Unexpected CastExtension Message: " << message.data();
+ }
+ return true;
+}
+
+// TODO(aiguha): To reduce duplication, it would perhaps be
+// better to create a single MouseShapeObserver outside of VideoScheduler
+// that can be attached to the ScreenCapturer on its creation in
+// ClientSession.
+void CastExtensionSession::OnCursorShapeChanged(
Wez 2014/08/12 22:15:00 I can find a call to SetMouseShapeObserver in this
aiguha 2014/08/13 18:33:27 Acknowledged.
+ webrtc::MouseCursorShape* cursor_shape) {
+ DCHECK(worker_task_runner_->BelongsToCurrentThread());
+ scoped_ptr<webrtc::MouseCursorShape> owned_cursor(cursor_shape);
+
+ scoped_ptr<protocol::CursorShapeInfo> cursor_proto(
+ new protocol::CursorShapeInfo());
+ cursor_proto->set_width(cursor_shape->size.width());
+ cursor_proto->set_height(cursor_shape->size.height());
+ cursor_proto->set_hotspot_x(cursor_shape->hotspot.x());
+ cursor_proto->set_hotspot_y(cursor_shape->hotspot.y());
+ cursor_proto->set_data(cursor_shape->data);
+
+ network_task_runner_->PostTask(
+ FROM_HERE,
+ base::Bind(&CastExtensionSession::SendCursorShape,
+ base::Unretained(this),
+ base::Passed(&cursor_proto)));
+}
+
+// Private methods ------------------------------------------------------------
+
+CastExtensionSession::CastExtensionSession(
+ scoped_refptr<base::SingleThreadTaskRunner> network_task_runner,
+ scoped_refptr<net::URLRequestContextGetter> url_request_context_getter,
+ const protocol::NetworkSettings& network_settings,
+ ClientSessionControl* client_session_control,
+ protocol::ClientStub* client_stub)
+ : network_task_runner_(network_task_runner),
+ url_request_context_getter_(url_request_context_getter),
+ network_settings_(network_settings),
+ client_session_control_(client_session_control),
+ client_stub_(client_stub),
+ stats_observer_(CastStatsObserver::Create()),
+ received_offer_(false),
+ has_grabbed_capturer_(false),
+ network_thread_wrapper_(NULL),
+ worker_thread_wrapper_(NULL),
+ worker_thread_(kWorkerThreadName) {
+ DCHECK(network_task_runner_->BelongsToCurrentThread());
+ DCHECK(url_request_context_getter_);
+ DCHECK(client_session_control_);
+ DCHECK(client_stub_);
+
+ base::Thread::Options options(base::MessageLoop::TYPE_IO, 0);
Wez 2014/08/12 22:15:01 nit: You could clarify why this needs to be an IO
aiguha 2014/08/13 18:33:27 Done.
+ worker_thread_.StartWithOptions(options);
+ worker_task_runner_ = worker_thread_.task_runner();
+}
+
+bool CastExtensionSession::ParseAndSetRemoteDescription(
+ base::DictionaryValue* message) {
+ DCHECK(peer_connection_.get() != NULL);
+
+ base::DictionaryValue* message_data;
+ if (!message->GetDictionary(kMessageData, &message_data)) {
+ LOG(ERROR) << "Invalid Cast Extension Message (missing data).";
+ return false;
+ }
+
+ std::string webrtc_type;
+ if (!message_data->GetString(kWebRtcSessionDescType, &webrtc_type)) {
+ LOG(ERROR)
+ << "Invalid Cast Extension Message (missing webrtc type header).";
+ return false;
+ }
+
+ std::string sdp;
+ if (!message_data->GetString(kWebRtcSessionDescSDP, &sdp)) {
+ LOG(ERROR) << "Invalid Cast Extension Message (missing webrtc sdp header).";
+ return false;
+ }
+
+ webrtc::SdpParseError error;
+ webrtc::SessionDescriptionInterface* session_description(
+ webrtc::CreateSessionDescription(webrtc_type, sdp, &error));
+
+ if (!session_description) {
+ LOG(ERROR) << "Invalid Cast Extension Message (could not parse sdp).";
+ VLOG(1) << "SdpParseError was: " << error.description;
+ return false;
+ }
+
+ peer_connection_->SetRemoteDescription(
+ CastSetSessionDescriptionObserver::Create(), session_description);
+ return true;
+}
+
+bool CastExtensionSession::ParseAndAddICECandidate(
+ base::DictionaryValue* message) {
+ DCHECK(peer_connection_.get() != NULL);
+
+ base::DictionaryValue* message_data;
+ if (!message->GetDictionary(kMessageData, &message_data)) {
+ LOG(ERROR) << "Invalid Cast Extension Message (missing data).";
+ return false;
+ }
+
+ std::string candidate_str;
+ std::string sdp_mid;
+ int sdp_mlineindex = 0;
+ if (!message_data->GetString(kWebRtcSDPMid, &sdp_mid) ||
+ !message_data->GetInteger(kWebRtcSDPMLineIndex, &sdp_mlineindex) ||
+ !message_data->GetString(kWebRtcCandidate, &candidate_str)) {
+ LOG(ERROR) << "Invalid Cast Extension Message (could not parse).";
+ return false;
+ }
+
+ rtc::scoped_ptr<webrtc::IceCandidateInterface> candidate(
+ webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, candidate_str));
+ if (!candidate.get()) {
+ LOG(ERROR)
+ << "Invalid Cast Extension Message (could not create candidate).";
+ return false;
+ }
+
+ if (!peer_connection_->AddIceCandidate(candidate.get())) {
+ LOG(ERROR) << "Failed to apply received ICE Candidate to PeerConnection.";
+ return false;
+ }
+
+ VLOG(1) << "Received and Added ICE Candidate: " << candidate_str;
+
+ return true;
+}
+
+bool CastExtensionSession::SendMessageToClient(const std::string& subject,
+ const std::string& data) {
+ DCHECK(network_task_runner_->BelongsToCurrentThread());
+
+ if (client_stub_ == NULL) {
+ LOG(ERROR) << "No Client Stub. Cannot send message to client.";
+ return false;
+ }
+
+ base::DictionaryValue message_dict;
+ message_dict.SetString(kMessageSubject, subject);
+ message_dict.SetString(kMessageData, data);
+ std::string message_json;
+
+ if (!base::JSONWriter::Write(&message_dict, &message_json)) {
+ LOG(ERROR) << "Failed to serialize JSON message.";
+ return false;
+ }
+
+ protocol::ExtensionMessage message;
+ message.set_type(kMessageType);
+ message.set_data(message_json);
+ client_stub_->DeliverHostMessage(message);
+ return true;
+}
+
+void CastExtensionSession::SendCursorShape(
+ scoped_ptr<protocol::CursorShapeInfo> cursor_shape) {
+ DCHECK(network_task_runner_->BelongsToCurrentThread());
+ if (!client_stub_)
+ return;
+
+ client_stub_->SetCursorShape(*cursor_shape);
+}
+
+void CastExtensionSession::EnsureTaskAndSetSend(rtc::Thread** ptr,
+ base::WaitableEvent* event) {
+ jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
+ jingle_glue::JingleThreadWrapper::current()->set_send_allowed(true);
+ *ptr = jingle_glue::JingleThreadWrapper::current();
+
+ if (event != NULL) {
+ event->Signal();
+ }
+}
+
+bool CastExtensionSession::WrapTasksAndSave() {
+ DCHECK(network_task_runner_->BelongsToCurrentThread());
+
+ EnsureTaskAndSetSend(&network_thread_wrapper_);
+ if (network_thread_wrapper_ == NULL)
+ return false;
+
+ base::WaitableEvent wrap_worker_thread_event(true, false);
+ worker_task_runner_->PostTask(
+ FROM_HERE,
+ base::Bind(&CastExtensionSession::EnsureTaskAndSetSend,
+ base::Unretained(this),
+ &worker_thread_wrapper_,
+ &wrap_worker_thread_event));
+ wrap_worker_thread_event.Wait();
+
+ return (worker_thread_wrapper_ != NULL);
+}
+
+bool CastExtensionSession::InitializePeerConnection() {
+ DCHECK(network_task_runner_->BelongsToCurrentThread());
+ DCHECK(!peer_conn_factory_);
+ DCHECK(!peer_connection_);
+ DCHECK(worker_thread_wrapper_ != NULL);
+ DCHECK(network_thread_wrapper_ != NULL);
+
+ peer_conn_factory_ = webrtc::CreatePeerConnectionFactory(
+ worker_thread_wrapper_, network_thread_wrapper_, NULL, NULL, NULL);
+
+ if (!peer_conn_factory_.get()) {
+ CleanupPeerConnection();
+ return false;
+ }
+
+ VLOG(1) << "Created PeerConnectionFactory successfully.";
+
+ webrtc::PeerConnectionInterface::IceServers servers;
+ webrtc::PeerConnectionInterface::IceServer server;
+ server.uri = kDefaultStunURI;
+ servers.push_back(server);
+ webrtc::PeerConnectionInterface::RTCConfiguration rtc_config;
+ rtc_config.servers = servers;
+
+ // DTLS-SRTP is the preferred encryption method. If set to kValueFalse, the
+ // peer connection uses SDES. Disabling SDES as well will cause the peer
+ // connection to fail to connect.
+ // Note: For protection and unprotection of SRTP packets, the libjingle
+ // ENABLE_EXTERNAL_AUTH flag must not be set.
+ webrtc::FakeConstraints constraints;
Wez 2014/08/12 22:15:00 Why are you using FakeConstraints here? Fakes are
aiguha 2014/08/13 18:33:27 The only other existing impl of webrtc::MediaConst
Wez 2014/08/14 19:22:03 Let's use FakeConstraints for now, but add a TODO
+ constraints.AddMandatory(webrtc::MediaConstraintsInterface::kEnableDtlsSrtp,
+ webrtc::MediaConstraintsInterface::kValueTrue);
+
+ rtc::scoped_refptr<webrtc::PortAllocatorFactoryInterface>
+ port_allocator_factory = ChromiumPortAllocatorFactory::Create(
+ network_settings_, url_request_context_getter_);
+
+ peer_connection_ = peer_conn_factory_->CreatePeerConnection(
+ rtc_config, &constraints, port_allocator_factory, NULL, this);
+
+ if (!peer_connection_.get()) {
+ CleanupPeerConnection();
+ return false;
+ }
+
+ VLOG(1) << "Created PeerConnection successfully.";
+
+ // Send a test message to the client. Then, notify the client to start
+ // webrtc offer/answer negotiation.
+ if (!SendMessageToClient(kSubjectTest, "Hello, client.") ||
Wez 2014/08/12 22:15:00 What purposes does the test message serve?
aiguha 2014/08/13 18:33:27 The test message always receives an echo from the
Wez 2014/08/14 19:22:03 So... what purpose does the test message serve? Wh
+ !SendMessageToClient(kSubjectReady, "Host ready to receive offers.")) {
+ LOG(ERROR) << "Failed to send messages to client.";
+ return false;
+ }
+
+ return true;
+}
+
+bool CastExtensionSession::SetupVideoStream(
+ scoped_ptr<webrtc::ScreenCapturer> screen_capturer) {
+ DCHECK(network_task_runner_->BelongsToCurrentThread());
+ DCHECK(screen_capturer);
+
+ if (stream_) {
+ VLOG(1) << "Already added MediaStream. Aborting Setup.";
+ return false;
+ }
+
+ scoped_ptr<CastVideoCapturerAdapter> cast_video_capturer_adapter(
+ new CastVideoCapturerAdapter(screen_capturer.Pass()));
+
+ // Set video stream constraints.
+ webrtc::FakeConstraints video_constraints;
+ video_constraints.AddMandatory(
+ webrtc::MediaConstraintsInterface::kMinFrameRate, kMinFrameRate);
+
+ rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track =
+ peer_conn_factory_->CreateVideoTrack(
+ kVideoLabel,
+ peer_conn_factory_->CreateVideoSource(
+ cast_video_capturer_adapter.release(), &video_constraints));
+
+ stream_ = peer_conn_factory_->CreateLocalMediaStream(kStreamLabel);
+
+ if (!stream_->AddTrack(video_track) ||
+ !peer_connection_->AddStream(stream_, NULL))
Wez 2014/08/12 22:15:00 nit: This is now a multi-line if() so it needs {}
aiguha 2014/08/13 18:33:28 Absolutely agree, sorry about that!
+ return false;
+
+ VLOG(1) << "Setup video stream successfully.";
+
+ return true;
+}
+
+void CastExtensionSession::PollPeerConnectionStats() {
+ if (!connection_active()) {
+ VLOG(1) << "Cannot poll stats while PeerConnection is inactive.";
+ }
+ rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> video_track =
+ stream_->FindVideoTrack(kVideoLabel);
+ peer_connection_->GetStats(
+ stats_observer_,
+ video_track.release(),
+ webrtc::PeerConnectionInterface::kStatsOutputLevelStandard);
+}
+
+void CastExtensionSession::CleanupPeerConnection() {
+ peer_connection_->Close();
+ peer_connection_ = NULL;
+ stream_ = NULL;
+ peer_conn_factory_ = NULL;
+ worker_thread_.Stop();
+}
+
+bool CastExtensionSession::connection_active() const {
+ return peer_connection_.get() != NULL;
+}
+
+// webrtc::PeerConnectionObserver implementation -------------------------------
+
+void CastExtensionSession::OnError() {
+ VLOG(1) << "PeerConnectionObserver: an error occurred.";
+}
+
+void CastExtensionSession::OnSignalingChange(
+ webrtc::PeerConnectionInterface::SignalingState new_state) {
+ VLOG(1) << "PeerConnectionObserver: SignalingState changed to:" << new_state;
+}
+
+void CastExtensionSession::OnStateChange(
+ webrtc::PeerConnectionObserver::StateType state_changed) {
+ VLOG(1) << "PeerConnectionObserver: StateType changed to: " << state_changed;
+}
+
+void CastExtensionSession::OnAddStream(webrtc::MediaStreamInterface* stream) {
+ VLOG(1) << "PeerConnectionObserver: stream added: " << stream->label();
+}
+
+void CastExtensionSession::OnRemoveStream(
+ webrtc::MediaStreamInterface* stream) {
+ VLOG(1) << "PeerConnectionObserver: stream removed: " << stream->label();
+}
+
+void CastExtensionSession::OnDataChannel(
+ webrtc::DataChannelInterface* data_channel) {
+ VLOG(1) << "PeerConnectionObserver: data channel: " << data_channel->label();
+}
+
+void CastExtensionSession::OnRenegotiationNeeded() {
+ VLOG(1) << "PeerConnectionObserver: renegotiation needed.";
+}
+
+void CastExtensionSession::OnIceConnectionChange(
+ webrtc::PeerConnectionInterface::IceConnectionState new_state) {
+ VLOG(1) << "PeerConnectionObserver: IceConnectionState changed to: "
+ << new_state;
+
+ // TODO(aiguha): Maybe start timer only if enabled by command-line flag or
+ // at a particular verbosity level.
+ if (!stats_polling_timer_.IsRunning() &&
+ new_state == webrtc::PeerConnectionInterface::kIceConnectionConnected) {
+ stats_polling_timer_.Start(
+ FROM_HERE,
+ base::TimeDelta::FromSeconds(kStatsLogIntervalSec),
+ this,
+ &CastExtensionSession::PollPeerConnectionStats);
+ }
+}
+
+void CastExtensionSession::OnIceGatheringChange(
+ webrtc::PeerConnectionInterface::IceGatheringState new_state) {
+ VLOG(1) << "PeerConnectionObserver: IceGatheringState changed to: "
+ << new_state;
+}
+
+void CastExtensionSession::OnIceComplete() {
+ VLOG(1) << "PeerConnectionObserver: all ICE candidates found.";
+}
+
+void CastExtensionSession::OnIceCandidate(
+ const webrtc::IceCandidateInterface* candidate) {
+ std::string candidate_str;
+ if (!candidate->ToString(&candidate_str)) {
+ LOG(ERROR) << "PeerConnectionObserver: failed to serialize candidate.";
+ return;
+ }
+ scoped_ptr<base::DictionaryValue> json(new base::DictionaryValue());
+ json->SetString(kWebRtcSDPMid, candidate->sdp_mid());
+ json->SetInteger(kWebRtcSDPMLineIndex, candidate->sdp_mline_index());
+ json->SetString(kWebRtcCandidate, candidate_str);
+ std::string json_str;
+ if (!base::JSONWriter::Write(json.get(), &json_str)) {
+ LOG(ERROR) << "Failed to serialize candidate message.";
+ return;
+ }
+ SendMessageToClient(kSubjectNewCandidate, json_str);
+}
+
+} // namespace remoting

Powered by Google App Engine
This is Rietveld 408576698