Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / remoting / host / cast_extension_session.cc
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   void OnSuccess() override {
75     VLOG(1) << "Setting session description succeeded.";
76   }
77   void OnFailure(const std::string& error) override {
78     LOG(ERROR) << "Setting session description failed: " << error;
79   }
80
81  protected:
82   CastSetSessionDescriptionObserver() {}
83   ~CastSetSessionDescriptionObserver() override {}
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   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   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   ~CastCreateSessionDescriptionObserver() override {}
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   void OnComplete(const std::vector<webrtc::StatsReport>& reports) override {
138     typedef webrtc::StatsReport::Values::iterator ValuesIterator;
139
140     VLOG(1) << "Received " << reports.size() << " new StatsReports.";
141
142     int index;
143     std::vector<webrtc::StatsReport>::const_iterator it;
144     for (it = reports.begin(), index = 0; it != reports.end(); ++it, ++index) {
145       webrtc::StatsReport::Values v = it->values;
146       VLOG(1) << "Report " << index << ":";
147       for (ValuesIterator vIt = v.begin(); vIt != v.end(); ++vIt) {
148         VLOG(1) << "Stat: " << vIt->name << "=" << vIt->value << ".";
149       }
150     }
151   }
152
153  protected:
154   CastStatsObserver() {}
155   ~CastStatsObserver() override {}
156
157   DISALLOW_COPY_AND_ASSIGN(CastStatsObserver);
158 };
159
160 // TODO(aiguha): Fix PeerConnnection-related tear down crash caused by premature
161 // destruction of cricket::CaptureManager (which occurs on releasing
162 // |peer_conn_factory_|). See crbug.com/403840.
163 CastExtensionSession::~CastExtensionSession() {
164   DCHECK(caller_task_runner_->BelongsToCurrentThread());
165
166   // Explicitly clear |create_session_desc_observer_|'s pointer to |this|,
167   // since the CastExtensionSession is destructing. Otherwise,
168   // |create_session_desc_observer_| would be left with a dangling pointer.
169   create_session_desc_observer_->SetCastExtensionSession(NULL);
170
171   CleanupPeerConnection();
172 }
173
174 // static
175 scoped_ptr<CastExtensionSession> CastExtensionSession::Create(
176     scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner,
177     scoped_refptr<net::URLRequestContextGetter> url_request_context_getter,
178     const protocol::NetworkSettings& network_settings,
179     ClientSessionControl* client_session_control,
180     protocol::ClientStub* client_stub) {
181   scoped_ptr<CastExtensionSession> cast_extension_session(
182       new CastExtensionSession(caller_task_runner,
183                                url_request_context_getter,
184                                network_settings,
185                                client_session_control,
186                                client_stub));
187   if (!cast_extension_session->WrapTasksAndSave() ||
188       !cast_extension_session->InitializePeerConnection()) {
189     return nullptr;
190   }
191   return cast_extension_session.Pass();
192 }
193
194 void CastExtensionSession::OnCreateSessionDescription(
195     webrtc::SessionDescriptionInterface* desc) {
196   if (!caller_task_runner_->BelongsToCurrentThread()) {
197     caller_task_runner_->PostTask(
198         FROM_HERE,
199         base::Bind(&CastExtensionSession::OnCreateSessionDescription,
200                    base::Unretained(this),
201                    desc));
202     return;
203   }
204
205   peer_connection_->SetLocalDescription(
206       CastSetSessionDescriptionObserver::Create(), desc);
207
208   scoped_ptr<base::DictionaryValue> json(new base::DictionaryValue());
209   json->SetString(kWebRtcSessionDescType, desc->type());
210   std::string subject =
211       (desc->type() == "offer") ? kSubjectOffer : kSubjectAnswer;
212   std::string desc_str;
213   desc->ToString(&desc_str);
214   json->SetString(kWebRtcSessionDescSDP, desc_str);
215   std::string json_str;
216   if (!base::JSONWriter::Write(json.get(), &json_str)) {
217     LOG(ERROR) << "Failed to serialize sdp message.";
218     return;
219   }
220
221   SendMessageToClient(subject.c_str(), json_str);
222 }
223
224 void CastExtensionSession::OnCreateSessionDescriptionFailure(
225     const std::string& error) {
226   VLOG(1) << "Creating Session Description failed: " << error;
227 }
228
229 // TODO(aiguha): Support the case(s) where we've grabbed the capturer already,
230 // but another extension reset the video pipeline. We should remove the
231 // stream from the peer connection here, and then attempt to re-setup the
232 // peer connection in the OnRenegotiationNeeded() callback.
233 // See crbug.com/403843.
234 void CastExtensionSession::OnCreateVideoCapturer(
235     scoped_ptr<webrtc::DesktopCapturer>* capturer) {
236   if (has_grabbed_capturer_) {
237     LOG(ERROR) << "The video pipeline was reset unexpectedly.";
238     has_grabbed_capturer_ = false;
239     peer_connection_->RemoveStream(stream_.release());
240     return;
241   }
242
243   if (received_offer_) {
244     has_grabbed_capturer_ = true;
245     if (SetupVideoStream(capturer->Pass())) {
246       peer_connection_->CreateAnswer(create_session_desc_observer_, NULL);
247     } else {
248       has_grabbed_capturer_ = false;
249       // Ignore the received offer, since we failed to setup a video stream.
250       received_offer_ = false;
251     }
252     return;
253   }
254 }
255
256 bool CastExtensionSession::ModifiesVideoPipeline() const {
257   return true;
258 }
259
260 // Returns true if the |message| is a Cast ExtensionMessage, even if
261 // it was badly formed or a resulting action failed. This is done so that
262 // the host does not continue to attempt to pass |message| to other
263 // HostExtensionSessions.
264 bool CastExtensionSession::OnExtensionMessage(
265     ClientSessionControl* client_session_control,
266     protocol::ClientStub* client_stub,
267     const protocol::ExtensionMessage& message) {
268   if (message.type() != kExtensionMessageType) {
269     return false;
270   }
271
272   scoped_ptr<base::Value> value(base::JSONReader::Read(message.data()));
273   base::DictionaryValue* client_message;
274   if (!(value && value->GetAsDictionary(&client_message))) {
275     LOG(ERROR) << "Could not read cast extension message.";
276     return true;
277   }
278
279   std::string subject;
280   if (!client_message->GetString(kTopLevelSubject, &subject)) {
281     LOG(ERROR) << "Invalid Cast Extension Message (missing subject header).";
282     return true;
283   }
284
285   if (subject == kSubjectOffer && !received_offer_) {
286     // Reset the video pipeline so we can grab the screen capturer and setup
287     // a video stream.
288     if (ParseAndSetRemoteDescription(client_message)) {
289       received_offer_ = true;
290       LOG(INFO) << "About to ResetVideoPipeline.";
291       client_session_control_->ResetVideoPipeline();
292
293     }
294   } else if (subject == kSubjectAnswer) {
295     ParseAndSetRemoteDescription(client_message);
296   } else if (subject == kSubjectNewCandidate) {
297     ParseAndAddICECandidate(client_message);
298   } else {
299     VLOG(1) << "Unexpected CastExtension Message: " << message.data();
300   }
301   return true;
302 }
303
304 // Private methods ------------------------------------------------------------
305
306 CastExtensionSession::CastExtensionSession(
307     scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner,
308     scoped_refptr<net::URLRequestContextGetter> url_request_context_getter,
309     const protocol::NetworkSettings& network_settings,
310     ClientSessionControl* client_session_control,
311     protocol::ClientStub* client_stub)
312     : caller_task_runner_(caller_task_runner),
313       url_request_context_getter_(url_request_context_getter),
314       network_settings_(network_settings),
315       client_session_control_(client_session_control),
316       client_stub_(client_stub),
317       stats_observer_(CastStatsObserver::Create()),
318       received_offer_(false),
319       has_grabbed_capturer_(false),
320       signaling_thread_wrapper_(NULL),
321       worker_thread_wrapper_(NULL),
322       worker_thread_(kWorkerThreadName) {
323   DCHECK(caller_task_runner_->BelongsToCurrentThread());
324   DCHECK(url_request_context_getter_.get());
325   DCHECK(client_session_control_);
326   DCHECK(client_stub_);
327
328   // The worker thread is created with base::MessageLoop::TYPE_IO because
329   // the PeerConnection performs some port allocation operations on this thread
330   // that require it. See crbug.com/404013.
331   base::Thread::Options options(base::MessageLoop::TYPE_IO, 0);
332   worker_thread_.StartWithOptions(options);
333   worker_task_runner_ = worker_thread_.task_runner();
334 }
335
336 bool CastExtensionSession::ParseAndSetRemoteDescription(
337     base::DictionaryValue* message) {
338   DCHECK(peer_connection_.get() != NULL);
339
340   base::DictionaryValue* message_data;
341   if (!message->GetDictionary(kTopLevelData, &message_data)) {
342     LOG(ERROR) << "Invalid Cast Extension Message (missing data).";
343     return false;
344   }
345
346   std::string webrtc_type;
347   if (!message_data->GetString(kWebRtcSessionDescType, &webrtc_type)) {
348     LOG(ERROR)
349         << "Invalid Cast Extension Message (missing webrtc type header).";
350     return false;
351   }
352
353   std::string sdp;
354   if (!message_data->GetString(kWebRtcSessionDescSDP, &sdp)) {
355     LOG(ERROR) << "Invalid Cast Extension Message (missing webrtc sdp header).";
356     return false;
357   }
358
359   webrtc::SdpParseError error;
360   webrtc::SessionDescriptionInterface* session_description(
361       webrtc::CreateSessionDescription(webrtc_type, sdp, &error));
362
363   if (!session_description) {
364     LOG(ERROR) << "Invalid Cast Extension Message (could not parse sdp).";
365     VLOG(1) << "SdpParseError was: " << error.description;
366     return false;
367   }
368
369   peer_connection_->SetRemoteDescription(
370       CastSetSessionDescriptionObserver::Create(), session_description);
371   return true;
372 }
373
374 bool CastExtensionSession::ParseAndAddICECandidate(
375     base::DictionaryValue* message) {
376   DCHECK(peer_connection_.get() != NULL);
377
378   base::DictionaryValue* message_data;
379   if (!message->GetDictionary(kTopLevelData, &message_data)) {
380     LOG(ERROR) << "Invalid Cast Extension Message (missing data).";
381     return false;
382   }
383
384   std::string candidate_str;
385   std::string sdp_mid;
386   int sdp_mlineindex = 0;
387   if (!message_data->GetString(kWebRtcSDPMid, &sdp_mid) ||
388       !message_data->GetInteger(kWebRtcSDPMLineIndex, &sdp_mlineindex) ||
389       !message_data->GetString(kWebRtcCandidate, &candidate_str)) {
390     LOG(ERROR) << "Invalid Cast Extension Message (could not parse).";
391     return false;
392   }
393
394   rtc::scoped_ptr<webrtc::IceCandidateInterface> candidate(
395       webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, candidate_str));
396   if (!candidate.get()) {
397     LOG(ERROR)
398         << "Invalid Cast Extension Message (could not create candidate).";
399     return false;
400   }
401
402   if (!peer_connection_->AddIceCandidate(candidate.get())) {
403     LOG(ERROR) << "Failed to apply received ICE Candidate to PeerConnection.";
404     return false;
405   }
406
407   VLOG(1) << "Received and Added ICE Candidate: " << candidate_str;
408
409   return true;
410 }
411
412 bool CastExtensionSession::SendMessageToClient(const std::string& subject,
413                                                const std::string& data) {
414   DCHECK(caller_task_runner_->BelongsToCurrentThread());
415
416   if (client_stub_ == NULL) {
417     LOG(ERROR) << "No Client Stub. Cannot send message to client.";
418     return false;
419   }
420
421   base::DictionaryValue message_dict;
422   message_dict.SetString(kTopLevelSubject, subject);
423   message_dict.SetString(kTopLevelData, data);
424   std::string message_json;
425
426   if (!base::JSONWriter::Write(&message_dict, &message_json)) {
427     LOG(ERROR) << "Failed to serialize JSON message.";
428     return false;
429   }
430
431   protocol::ExtensionMessage message;
432   message.set_type(kExtensionMessageType);
433   message.set_data(message_json);
434   client_stub_->DeliverHostMessage(message);
435   return true;
436 }
437
438 void CastExtensionSession::EnsureTaskAndSetSend(rtc::Thread** ptr,
439                                                 base::WaitableEvent* event) {
440   jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
441   jingle_glue::JingleThreadWrapper::current()->set_send_allowed(true);
442   *ptr = jingle_glue::JingleThreadWrapper::current();
443
444   if (event != NULL) {
445     event->Signal();
446   }
447 }
448
449 bool CastExtensionSession::WrapTasksAndSave() {
450   DCHECK(caller_task_runner_->BelongsToCurrentThread());
451
452   EnsureTaskAndSetSend(&signaling_thread_wrapper_);
453   if (signaling_thread_wrapper_ == NULL)
454     return false;
455
456   base::WaitableEvent wrap_worker_thread_event(true, false);
457   worker_task_runner_->PostTask(
458       FROM_HERE,
459       base::Bind(&CastExtensionSession::EnsureTaskAndSetSend,
460                  base::Unretained(this),
461                  &worker_thread_wrapper_,
462                  &wrap_worker_thread_event));
463   wrap_worker_thread_event.Wait();
464
465   return (worker_thread_wrapper_ != NULL);
466 }
467
468 bool CastExtensionSession::InitializePeerConnection() {
469   DCHECK(caller_task_runner_->BelongsToCurrentThread());
470   DCHECK(!peer_conn_factory_);
471   DCHECK(!peer_connection_);
472   DCHECK(worker_thread_wrapper_ != NULL);
473   DCHECK(signaling_thread_wrapper_ != NULL);
474
475   peer_conn_factory_ = webrtc::CreatePeerConnectionFactory(
476       worker_thread_wrapper_, signaling_thread_wrapper_, NULL, NULL, NULL);
477
478   if (!peer_conn_factory_.get()) {
479     CleanupPeerConnection();
480     return false;
481   }
482
483   VLOG(1) << "Created PeerConnectionFactory successfully.";
484
485   webrtc::PeerConnectionInterface::IceServers servers;
486   webrtc::PeerConnectionInterface::IceServer server;
487   server.uri = kDefaultStunURI;
488   servers.push_back(server);
489   webrtc::PeerConnectionInterface::RTCConfiguration rtc_config;
490   rtc_config.servers = servers;
491
492   // DTLS-SRTP is the preferred encryption method. If set to kValueFalse, the
493   // peer connection uses SDES. Disabling SDES as well will cause the peer
494   // connection to fail to connect.
495   // Note: For protection and unprotection of SRTP packets, the libjingle
496   // ENABLE_EXTERNAL_AUTH flag must not be set.
497   webrtc::FakeConstraints constraints;
498   constraints.AddMandatory(webrtc::MediaConstraintsInterface::kEnableDtlsSrtp,
499                            webrtc::MediaConstraintsInterface::kValueTrue);
500
501   rtc::scoped_refptr<webrtc::PortAllocatorFactoryInterface>
502       port_allocator_factory = ChromiumPortAllocatorFactory::Create(
503           network_settings_, url_request_context_getter_);
504
505   peer_connection_ = peer_conn_factory_->CreatePeerConnection(
506       rtc_config, &constraints, port_allocator_factory, NULL, this);
507
508   if (!peer_connection_.get()) {
509     CleanupPeerConnection();
510     return false;
511   }
512
513   VLOG(1) << "Created PeerConnection successfully.";
514
515   create_session_desc_observer_ =
516       CastCreateSessionDescriptionObserver::Create(this);
517
518   // Send a test message to the client. Then, notify the client to start
519   // webrtc offer/answer negotiation.
520   if (!SendMessageToClient(kSubjectTest, "Hello, client.") ||
521       !SendMessageToClient(kSubjectReady, "Host ready to receive offers.")) {
522     LOG(ERROR) << "Failed to send messages to client.";
523     return false;
524   }
525
526   return true;
527 }
528
529 bool CastExtensionSession::SetupVideoStream(
530     scoped_ptr<webrtc::DesktopCapturer> desktop_capturer) {
531   DCHECK(caller_task_runner_->BelongsToCurrentThread());
532   DCHECK(desktop_capturer);
533
534   if (stream_) {
535     VLOG(1) << "Already added MediaStream. Aborting Setup.";
536     return false;
537   }
538
539   scoped_ptr<CastVideoCapturerAdapter> cast_video_capturer_adapter(
540       new CastVideoCapturerAdapter(desktop_capturer.Pass()));
541
542   // Set video stream constraints.
543   webrtc::FakeConstraints video_constraints;
544   video_constraints.AddMandatory(
545       webrtc::MediaConstraintsInterface::kMinFrameRate, kMinFramesPerSecond);
546
547   rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track =
548       peer_conn_factory_->CreateVideoTrack(
549           kVideoLabel,
550           peer_conn_factory_->CreateVideoSource(
551               cast_video_capturer_adapter.release(), &video_constraints));
552
553   stream_ = peer_conn_factory_->CreateLocalMediaStream(kStreamLabel);
554
555   if (!stream_->AddTrack(video_track) ||
556       !peer_connection_->AddStream(stream_)) {
557     return false;
558   }
559
560   VLOG(1) << "Setup video stream successfully.";
561
562   return true;
563 }
564
565 void CastExtensionSession::PollPeerConnectionStats() {
566   if (!connection_active()) {
567     VLOG(1) << "Cannot poll stats while PeerConnection is inactive.";
568   }
569   rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> video_track =
570       stream_->FindVideoTrack(kVideoLabel);
571   peer_connection_->GetStats(
572       stats_observer_,
573       video_track.release(),
574       webrtc::PeerConnectionInterface::kStatsOutputLevelStandard);
575 }
576
577 void CastExtensionSession::CleanupPeerConnection() {
578   peer_connection_->Close();
579   peer_connection_ = NULL;
580   stream_ = NULL;
581   peer_conn_factory_ = NULL;
582   worker_thread_.Stop();
583 }
584
585 bool CastExtensionSession::connection_active() const {
586   return peer_connection_.get() != NULL;
587 }
588
589 // webrtc::PeerConnectionObserver implementation -------------------------------
590 void CastExtensionSession::OnSignalingChange(
591     webrtc::PeerConnectionInterface::SignalingState new_state) {
592   VLOG(1) << "PeerConnectionObserver: SignalingState changed to:" << new_state;
593 }
594
595 void CastExtensionSession::OnStateChange(
596     webrtc::PeerConnectionObserver::StateType state_changed) {
597   VLOG(1) << "PeerConnectionObserver: StateType changed to: " << state_changed;
598 }
599
600 void CastExtensionSession::OnAddStream(webrtc::MediaStreamInterface* stream) {
601   VLOG(1) << "PeerConnectionObserver: stream added: " << stream->label();
602 }
603
604 void CastExtensionSession::OnRemoveStream(
605     webrtc::MediaStreamInterface* stream) {
606   VLOG(1) << "PeerConnectionObserver: stream removed: " << stream->label();
607 }
608
609 void CastExtensionSession::OnDataChannel(
610     webrtc::DataChannelInterface* data_channel) {
611   VLOG(1) << "PeerConnectionObserver: data channel: " << data_channel->label();
612 }
613
614 void CastExtensionSession::OnRenegotiationNeeded() {
615   VLOG(1) << "PeerConnectionObserver: renegotiation needed.";
616 }
617
618 void CastExtensionSession::OnIceConnectionChange(
619     webrtc::PeerConnectionInterface::IceConnectionState new_state) {
620   VLOG(1) << "PeerConnectionObserver: IceConnectionState changed to: "
621           << new_state;
622
623   // TODO(aiguha): Maybe start timer only if enabled by command-line flag or
624   // at a particular verbosity level.
625   if (!stats_polling_timer_.IsRunning() &&
626       new_state == webrtc::PeerConnectionInterface::kIceConnectionConnected) {
627     stats_polling_timer_.Start(
628         FROM_HERE,
629         base::TimeDelta::FromSeconds(kStatsLogIntervalSec),
630         this,
631         &CastExtensionSession::PollPeerConnectionStats);
632   }
633 }
634
635 void CastExtensionSession::OnIceGatheringChange(
636     webrtc::PeerConnectionInterface::IceGatheringState new_state) {
637   VLOG(1) << "PeerConnectionObserver: IceGatheringState changed to: "
638           << new_state;
639 }
640
641 void CastExtensionSession::OnIceComplete() {
642   VLOG(1) << "PeerConnectionObserver: all ICE candidates found.";
643 }
644
645 void CastExtensionSession::OnIceCandidate(
646     const webrtc::IceCandidateInterface* candidate) {
647   std::string candidate_str;
648   if (!candidate->ToString(&candidate_str)) {
649     LOG(ERROR) << "PeerConnectionObserver: failed to serialize candidate.";
650     return;
651   }
652   scoped_ptr<base::DictionaryValue> json(new base::DictionaryValue());
653   json->SetString(kWebRtcSDPMid, candidate->sdp_mid());
654   json->SetInteger(kWebRtcSDPMLineIndex, candidate->sdp_mline_index());
655   json->SetString(kWebRtcCandidate, candidate_str);
656   std::string json_str;
657   if (!base::JSONWriter::Write(json.get(), &json_str)) {
658     LOG(ERROR) << "Failed to serialize candidate message.";
659     return;
660   }
661   SendMessageToClient(kSubjectNewCandidate, json_str);
662 }
663
664 }  // namespace remoting