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

Side by Side Diff: content/renderer/media/rtc_peer_connection_handler.cc

Issue 675013005: Split libjingle's signaling thread from the UI thread (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Broken changes for review Created 6 years, 1 month 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 unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "content/renderer/media/rtc_peer_connection_handler.h" 5 #include "content/renderer/media/rtc_peer_connection_handler.h"
6 6
7 #include <string> 7 #include <string>
8 #include <utility> 8 #include <utility>
9 #include <vector> 9 #include <vector>
10 10
(...skipping 13 matching lines...) Expand all
24 #include "content/renderer/media/rtc_data_channel_handler.h" 24 #include "content/renderer/media/rtc_data_channel_handler.h"
25 #include "content/renderer/media/rtc_dtmf_sender_handler.h" 25 #include "content/renderer/media/rtc_dtmf_sender_handler.h"
26 #include "content/renderer/media/rtc_media_constraints.h" 26 #include "content/renderer/media/rtc_media_constraints.h"
27 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h" 27 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
28 #include "content/renderer/media/webrtc/webrtc_media_stream_adapter.h" 28 #include "content/renderer/media/webrtc/webrtc_media_stream_adapter.h"
29 #include "content/renderer/media/webrtc_audio_capturer.h" 29 #include "content/renderer/media/webrtc_audio_capturer.h"
30 #include "content/renderer/media/webrtc_audio_device_impl.h" 30 #include "content/renderer/media/webrtc_audio_device_impl.h"
31 #include "content/renderer/media/webrtc_uma_histograms.h" 31 #include "content/renderer/media/webrtc_uma_histograms.h"
32 #include "content/renderer/render_thread_impl.h" 32 #include "content/renderer/render_thread_impl.h"
33 #include "third_party/WebKit/public/platform/WebMediaConstraints.h" 33 #include "third_party/WebKit/public/platform/WebMediaConstraints.h"
34 #include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
35 #include "third_party/WebKit/public/platform/WebRTCConfiguration.h" 34 #include "third_party/WebKit/public/platform/WebRTCConfiguration.h"
36 #include "third_party/WebKit/public/platform/WebRTCDataChannelInit.h" 35 #include "third_party/WebKit/public/platform/WebRTCDataChannelInit.h"
37 #include "third_party/WebKit/public/platform/WebRTCICECandidate.h" 36 #include "third_party/WebKit/public/platform/WebRTCICECandidate.h"
38 #include "third_party/WebKit/public/platform/WebRTCOfferOptions.h" 37 #include "third_party/WebKit/public/platform/WebRTCOfferOptions.h"
39 #include "third_party/WebKit/public/platform/WebRTCSessionDescription.h" 38 #include "third_party/WebKit/public/platform/WebRTCSessionDescription.h"
40 #include "third_party/WebKit/public/platform/WebRTCSessionDescriptionRequest.h" 39 #include "third_party/WebKit/public/platform/WebRTCSessionDescriptionRequest.h"
41 #include "third_party/WebKit/public/platform/WebRTCVoidRequest.h" 40 #include "third_party/WebKit/public/platform/WebRTCVoidRequest.h"
42 #include "third_party/WebKit/public/platform/WebURL.h" 41 #include "third_party/WebKit/public/platform/WebURL.h"
43 42
43 using webrtc::DataChannelInterface;
44 using webrtc::IceCandidateInterface;
45 using webrtc::MediaStreamInterface;
46 using webrtc::PeerConnectionInterface;
47 using webrtc::PeerConnectionObserver;
44 using webrtc::StatsReport; 48 using webrtc::StatsReport;
49 using webrtc::StatsReportCopyable;
45 using webrtc::StatsReports; 50 using webrtc::StatsReports;
46 51
47 namespace content { 52 namespace content {
48 53
49 // Converter functions from libjingle types to WebKit types. 54 // Converter functions from libjingle types to WebKit types.
50 blink::WebRTCPeerConnectionHandlerClient::ICEGatheringState 55 blink::WebRTCPeerConnectionHandlerClient::ICEGatheringState
51 GetWebKitIceGatheringState( 56 GetWebKitIceGatheringState(
52 webrtc::PeerConnectionInterface::IceGatheringState state) { 57 webrtc::PeerConnectionInterface::IceGatheringState state) {
53 using blink::WebRTCPeerConnectionHandlerClient; 58 using blink::WebRTCPeerConnectionHandlerClient;
54 switch (state) { 59 switch (state) {
(...skipping 109 matching lines...) Expand 10 before | Expand all | Expand 10 after
164 } 169 }
165 } 170 }
166 171
167 class SessionDescriptionRequestTracker { 172 class SessionDescriptionRequestTracker {
168 public: 173 public:
169 SessionDescriptionRequestTracker(RTCPeerConnectionHandler* handler, 174 SessionDescriptionRequestTracker(RTCPeerConnectionHandler* handler,
170 PeerConnectionTracker::Action action) 175 PeerConnectionTracker::Action action)
171 : handler_(handler), action_(action) {} 176 : handler_(handler), action_(action) {}
172 177
173 void TrackOnSuccess(const webrtc::SessionDescriptionInterface* desc) { 178 void TrackOnSuccess(const webrtc::SessionDescriptionInterface* desc) {
179 DCHECK(thread_checker_.CalledOnValidThread());
174 std::string value; 180 std::string value;
175 if (desc) { 181 if (desc) {
176 desc->ToString(&value); 182 desc->ToString(&value);
177 value = "type: " + desc->type() + ", sdp: " + value; 183 value = "type: " + desc->type() + ", sdp: " + value;
178 } 184 }
179 if (handler_->peer_connection_tracker()) 185 if (handler_->peer_connection_tracker()) {
180 handler_->peer_connection_tracker()->TrackSessionDescriptionCallback( 186 handler_->peer_connection_tracker()->TrackSessionDescriptionCallback(
181 handler_, action_, "OnSuccess", value); 187 handler_, action_, "OnSuccess", value);
188 }
182 } 189 }
183 190
184 void TrackOnFailure(const std::string& error) { 191 void TrackOnFailure(const std::string& error) {
185 if (handler_->peer_connection_tracker()) 192 DCHECK(thread_checker_.CalledOnValidThread());
193 if (handler_->peer_connection_tracker()) {
186 handler_->peer_connection_tracker()->TrackSessionDescriptionCallback( 194 handler_->peer_connection_tracker()->TrackSessionDescriptionCallback(
187 handler_, action_, "OnFailure", error); 195 handler_, action_, "OnFailure", error);
196 }
188 } 197 }
189 198
190 private: 199 private:
191 RTCPeerConnectionHandler* handler_; 200 RTCPeerConnectionHandler* handler_;
192 PeerConnectionTracker::Action action_; 201 PeerConnectionTracker::Action action_;
202 base::ThreadChecker thread_checker_;
193 }; 203 };
194 204
195 // Class mapping responses from calls to libjingle CreateOffer/Answer and 205 // Class mapping responses from calls to libjingle CreateOffer/Answer and
196 // the blink::WebRTCSessionDescriptionRequest. 206 // the blink::WebRTCSessionDescriptionRequest.
197 class CreateSessionDescriptionRequest 207 class CreateSessionDescriptionRequest
198 : public webrtc::CreateSessionDescriptionObserver { 208 : public webrtc::CreateSessionDescriptionObserver {
199 public: 209 public:
200 explicit CreateSessionDescriptionRequest( 210 explicit CreateSessionDescriptionRequest(
211 const scoped_refptr<base::SingleThreadTaskRunner>& main_thread,
201 const blink::WebRTCSessionDescriptionRequest& request, 212 const blink::WebRTCSessionDescriptionRequest& request,
202 RTCPeerConnectionHandler* handler, 213 RTCPeerConnectionHandler* handler,
203 PeerConnectionTracker::Action action) 214 PeerConnectionTracker::Action action)
204 : webkit_request_(request), tracker_(handler, action) {} 215 : main_thread_(main_thread),
216 webkit_request_(request),
217 tracker_(handler, action) {
218 }
205 219
206 void OnSuccess(webrtc::SessionDescriptionInterface* desc) override { 220 void OnSuccess(webrtc::SessionDescriptionInterface* desc) override {
221 if (!main_thread_->BelongsToCurrentThread()) {
222 main_thread_->PostTask(FROM_HERE,
223 base::Bind(&CreateSessionDescriptionRequest::OnSuccess, this, desc));
224 return;
225 }
226
207 tracker_.TrackOnSuccess(desc); 227 tracker_.TrackOnSuccess(desc);
208 webkit_request_.requestSucceeded(CreateWebKitSessionDescription(desc)); 228 webkit_request_.requestSucceeded(CreateWebKitSessionDescription(desc));
209 delete desc; 229 delete desc;
210 } 230 }
211 void OnFailure(const std::string& error) override { 231 void OnFailure(const std::string& error) override {
232 if (!main_thread_->BelongsToCurrentThread()) {
233 main_thread_->PostTask(FROM_HERE,
234 base::Bind(&CreateSessionDescriptionRequest::OnFailure, this, error));
235 return;
236 }
237
212 tracker_.TrackOnFailure(error); 238 tracker_.TrackOnFailure(error);
213 webkit_request_.requestFailed(base::UTF8ToUTF16(error)); 239 webkit_request_.requestFailed(base::UTF8ToUTF16(error));
214 } 240 }
215 241
216 protected: 242 protected:
217 ~CreateSessionDescriptionRequest() override {} 243 ~CreateSessionDescriptionRequest() override {}
218 244
219 private: 245 const scoped_refptr<base::SingleThreadTaskRunner> main_thread_;
220 blink::WebRTCSessionDescriptionRequest webkit_request_; 246 blink::WebRTCSessionDescriptionRequest webkit_request_;
221 SessionDescriptionRequestTracker tracker_; 247 SessionDescriptionRequestTracker tracker_;
222 }; 248 };
223 249
224 // Class mapping responses from calls to libjingle 250 // Class mapping responses from calls to libjingle
225 // SetLocalDescription/SetRemoteDescription and a blink::WebRTCVoidRequest. 251 // SetLocalDescription/SetRemoteDescription and a blink::WebRTCVoidRequest.
226 class SetSessionDescriptionRequest 252 class SetSessionDescriptionRequest
227 : public webrtc::SetSessionDescriptionObserver { 253 : public webrtc::SetSessionDescriptionObserver {
228 public: 254 public:
229 explicit SetSessionDescriptionRequest( 255 explicit SetSessionDescriptionRequest(
256 const scoped_refptr<base::SingleThreadTaskRunner>& main_thread,
230 const blink::WebRTCVoidRequest& request, 257 const blink::WebRTCVoidRequest& request,
231 RTCPeerConnectionHandler* handler, 258 RTCPeerConnectionHandler* handler,
232 PeerConnectionTracker::Action action) 259 PeerConnectionTracker::Action action)
233 : webkit_request_(request), tracker_(handler, action) {} 260 : main_thread_(main_thread),
261 webkit_request_(request),
262 tracker_(handler, action) {
263 }
234 264
235 void OnSuccess() override { 265 void OnSuccess() override {
266 if (!main_thread_->BelongsToCurrentThread()) {
267 main_thread_->PostTask(FROM_HERE,
268 base::Bind(&SetSessionDescriptionRequest::OnSuccess, this));
269 return;
270 }
236 tracker_.TrackOnSuccess(NULL); 271 tracker_.TrackOnSuccess(NULL);
237 webkit_request_.requestSucceeded(); 272 webkit_request_.requestSucceeded();
238 } 273 }
239 void OnFailure(const std::string& error) override { 274 void OnFailure(const std::string& error) override {
275 if (!main_thread_->BelongsToCurrentThread()) {
276 main_thread_->PostTask(FROM_HERE,
277 base::Bind(&SetSessionDescriptionRequest::OnFailure, this, error));
278 return;
279 }
240 tracker_.TrackOnFailure(error); 280 tracker_.TrackOnFailure(error);
241 webkit_request_.requestFailed(base::UTF8ToUTF16(error)); 281 webkit_request_.requestFailed(base::UTF8ToUTF16(error));
242 } 282 }
243 283
244 protected: 284 protected:
245 ~SetSessionDescriptionRequest() override {} 285 ~SetSessionDescriptionRequest() override {}
246 286
247 private: 287 private:
288 const scoped_refptr<base::SingleThreadTaskRunner> main_thread_;
248 blink::WebRTCVoidRequest webkit_request_; 289 blink::WebRTCVoidRequest webkit_request_;
249 SessionDescriptionRequestTracker tracker_; 290 SessionDescriptionRequestTracker tracker_;
250 }; 291 };
251 292
252 // Class mapping responses from calls to libjingle 293 // Class mapping responses from calls to libjingle
253 // GetStats into a blink::WebRTCStatsCallback. 294 // GetStats into a blink::WebRTCStatsCallback.
254 class StatsResponse : public webrtc::StatsObserver { 295 class StatsResponse : public webrtc::StatsObserver {
255 public: 296 public:
256 explicit StatsResponse(const scoped_refptr<LocalRTCStatsRequest>& request) 297 explicit StatsResponse(const scoped_refptr<LocalRTCStatsRequest>& request)
257 : request_(request.get()), response_(request_->createResponse().get()) { 298 : request_(request.get()),
299 main_thread_(base::ThreadTaskRunnerHandle::Get()) {
258 // Measure the overall time it takes to satisfy a getStats request. 300 // Measure the overall time it takes to satisfy a getStats request.
259 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "getStats_Native", this); 301 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "getStats_Native", this);
302 signaling_thread_checker_.DetachFromThread();
260 } 303 }
261 304
262 void OnComplete(const StatsReports& reports) override { 305 void OnComplete(const StatsReports& reports) override {
263 TRACE_EVENT0("webrtc", "StatsResponse::OnComplete") 306 DCHECK(signaling_thread_checker_.CalledOnValidThread());
264 for (StatsReports::const_iterator it = reports.begin(); 307 TRACE_EVENT0("webrtc", "StatsResponse::OnComplete");
265 it != reports.end(); ++it) { 308 scoped_ptr<std::vector<StatsReportCopyable>> report_copies(
266 if ((*it)->values.size() > 0) { 309 new std::vector<StatsReportCopyable>());
267 AddReport(*(*it)); 310 report_copies->reserve(reports.size());
268 } 311 for (auto it : reports)
312 report_copies->push_back(StatsReportCopyable(*it));
313
314 main_thread_->PostTask(FROM_HERE,
315 base::Bind(&StatsResponse::DeliverCallback, this,
316 base::Passed(&report_copies)));
317 }
318
319 private:
320 void DeliverCallback(scoped_ptr<std::vector<StatsReportCopyable>> reports) {
321 DCHECK(main_thread_->BelongsToCurrentThread());
322 TRACE_EVENT0("webrtc", "StatsResponse::DeliverCallback");
323
324 rtc::scoped_refptr<LocalRTCStatsResponse> response(
325 request_->createResponse().get());
326 for (const auto& report : *reports.get()) {
327 if (report.values.size() > 0)
328 AddReport(response.get(), report);
269 } 329 }
270 330
271 // Record the getSync operation as done before calling into Blink so that 331 // Record the getSync operation as done before calling into Blink so that
272 // we don't skew the perf measurements of the native code with whatever the 332 // we don't skew the perf measurements of the native code with whatever the
273 // callback might be doing. 333 // callback might be doing.
274 TRACE_EVENT_ASYNC_END0("webrtc", "getStats_Native", this); 334 TRACE_EVENT_ASYNC_END0("webrtc", "getStats_Native", this);
275 335 request_->requestSucceeded(response);
276 request_->requestSucceeded(response_);
277 } 336 }
278 337
279 private: 338 void AddReport(LocalRTCStatsResponse* response, const StatsReport& report) {
280 void AddReport(const StatsReport& report) { 339 int idx = response->addReport(blink::WebString::fromUTF8(report.id),
281 int idx = response_->addReport(blink::WebString::fromUTF8(report.id), 340 blink::WebString::fromUTF8(report.type),
282 blink::WebString::fromUTF8(report.type), 341 report.timestamp);
283 report.timestamp); 342 for (const auto& value : report.values) {
284 for (StatsReport::Values::const_iterator value_it = report.values.begin(); 343 response->addStatistic(idx,
285 value_it != report.values.end(); ++value_it) { 344 blink::WebString::fromUTF8(value.display_name()),
286 AddStatistic(idx, value_it->display_name(), value_it->value); 345 blink::WebString::fromUTF8(value.value));
287 } 346 }
288 } 347 }
289 348
290 void AddStatistic(int idx, const char* name, const std::string& value) {
291 response_->addStatistic(idx,
292 blink::WebString::fromUTF8(name),
293 blink::WebString::fromUTF8(value));
294 }
295
296 rtc::scoped_refptr<LocalRTCStatsRequest> request_; 349 rtc::scoped_refptr<LocalRTCStatsRequest> request_;
297 rtc::scoped_refptr<LocalRTCStatsResponse> response_; 350 const scoped_refptr<base::SingleThreadTaskRunner> main_thread_;
351 base::ThreadChecker signaling_thread_checker_;
298 }; 352 };
299 353
300 // Implementation of LocalRTCStatsRequest. 354 // Implementation of LocalRTCStatsRequest.
301 LocalRTCStatsRequest::LocalRTCStatsRequest(blink::WebRTCStatsRequest impl) 355 LocalRTCStatsRequest::LocalRTCStatsRequest(blink::WebRTCStatsRequest impl)
302 : impl_(impl), 356 : impl_(impl) {
303 response_(NULL) {
304 } 357 }
305 358
306 LocalRTCStatsRequest::LocalRTCStatsRequest() {} 359 LocalRTCStatsRequest::LocalRTCStatsRequest() {}
307 LocalRTCStatsRequest::~LocalRTCStatsRequest() {} 360 LocalRTCStatsRequest::~LocalRTCStatsRequest() {}
308 361
309 bool LocalRTCStatsRequest::hasSelector() const { 362 bool LocalRTCStatsRequest::hasSelector() const {
310 return impl_.hasSelector(); 363 return impl_.hasSelector();
311 } 364 }
312 365
313 blink::WebMediaStreamTrack LocalRTCStatsRequest::component() const { 366 blink::WebMediaStreamTrack LocalRTCStatsRequest::component() const {
314 return impl_.component(); 367 return impl_.component();
315 } 368 }
316 369
317 scoped_refptr<LocalRTCStatsResponse> LocalRTCStatsRequest::createResponse() { 370 scoped_refptr<LocalRTCStatsResponse> LocalRTCStatsRequest::createResponse() {
318 DCHECK(!response_); 371 return scoped_refptr<LocalRTCStatsResponse>(
319 response_ = new rtc::RefCountedObject<LocalRTCStatsResponse>( 372 new rtc::RefCountedObject<LocalRTCStatsResponse>(impl_.createResponse()));
320 impl_.createResponse());
321 return response_.get();
322 } 373 }
323 374
324 void LocalRTCStatsRequest::requestSucceeded( 375 void LocalRTCStatsRequest::requestSucceeded(
325 const LocalRTCStatsResponse* response) { 376 const LocalRTCStatsResponse* response) {
326 impl_.requestSucceeded(response->webKitStatsResponse()); 377 impl_.requestSucceeded(response->webKitStatsResponse());
327 } 378 }
328 379
329 // Implementation of LocalRTCStatsResponse. 380 // Implementation of LocalRTCStatsResponse.
330 blink::WebRTCStatsResponse LocalRTCStatsResponse::webKitStatsResponse() const { 381 blink::WebRTCStatsResponse LocalRTCStatsResponse::webKitStatsResponse() const {
331 return impl_; 382 return impl_;
332 } 383 }
333 384
334 size_t LocalRTCStatsResponse::addReport(blink::WebString type, 385 size_t LocalRTCStatsResponse::addReport(blink::WebString type,
335 blink::WebString id, 386 blink::WebString id,
336 double timestamp) { 387 double timestamp) {
337 return impl_.addReport(type, id, timestamp); 388 return impl_.addReport(type, id, timestamp);
338 } 389 }
339 390
340 void LocalRTCStatsResponse::addStatistic(size_t report, 391 void LocalRTCStatsResponse::addStatistic(size_t report,
341 blink::WebString name, 392 blink::WebString name,
342 blink::WebString value) { 393 blink::WebString value) {
343 impl_.addStatistic(report, name, value); 394 impl_.addStatistic(report, name, value);
344 } 395 }
345 396
346 namespace { 397 namespace {
347 398
399 void GetStatsOnSignalingThread(
400 const scoped_refptr<webrtc::PeerConnectionInterface>& pc,
401 webrtc::PeerConnectionInterface::StatsOutputLevel level,
402 const scoped_refptr<webrtc::StatsObserver>& observer,
403 const std::string track_id, blink::WebMediaStreamSource::Type track_type) {
404 TRACE_EVENT0("webrtc", "GetStatsOnSignalingThread");
405
406 scoped_refptr<webrtc::MediaStreamTrackInterface> track;
407 if (!track_id.empty()) {
408 if (track_type == blink::WebMediaStreamSource::TypeAudio) {
409 track = pc->local_streams()->FindAudioTrack(track_id);
410 if (!track.get())
411 track = pc->remote_streams()->FindAudioTrack(track_id);
412 } else {
413 DCHECK_EQ(blink::WebMediaStreamSource::TypeVideo, track_type);
414 track = pc->local_streams()->FindVideoTrack(track_id);
415 if (!track.get())
416 track = pc->remote_streams()->FindVideoTrack(track_id);
417 }
418
419 if (!track.get()) {
420 DVLOG(1) << "GetStats: Track not found.";
421 observer->OnComplete(StatsReports());
422 return;
423 }
424 }
425
426 if (!pc->GetStats(observer.get(), track.get(), level)) {
427 DVLOG(1) << "GetStats failed.";
428 observer->OnComplete(StatsReports());
429 }
430 }
431
348 class PeerConnectionUMAObserver : public webrtc::UMAObserver { 432 class PeerConnectionUMAObserver : public webrtc::UMAObserver {
349 public: 433 public:
350 PeerConnectionUMAObserver() {} 434 PeerConnectionUMAObserver() {}
351 ~PeerConnectionUMAObserver() override {} 435 ~PeerConnectionUMAObserver() override {}
352 436
353 void IncrementCounter( 437 void IncrementCounter(
354 webrtc::PeerConnectionUMAMetricsCounter counter) override { 438 webrtc::PeerConnectionUMAMetricsCounter counter) override {
439 // Runs on libjingle's signaling thread.
355 UMA_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", 440 UMA_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
356 counter, 441 counter,
357 webrtc::kBoundary); 442 webrtc::kBoundary);
358 } 443 }
359 444
360 void AddHistogramSample(webrtc::PeerConnectionUMAMetricsName type, 445 void AddHistogramSample(webrtc::PeerConnectionUMAMetricsName type,
361 int value) override { 446 int value) override {
447 // Runs on libjingle's signaling thread.
362 switch (type) { 448 switch (type) {
363 case webrtc::kTimeToConnect: 449 case webrtc::kTimeToConnect:
364 UMA_HISTOGRAM_MEDIUM_TIMES( 450 UMA_HISTOGRAM_MEDIUM_TIMES(
365 "WebRTC.PeerConnection.TimeToConnect", 451 "WebRTC.PeerConnection.TimeToConnect",
366 base::TimeDelta::FromMilliseconds(value)); 452 base::TimeDelta::FromMilliseconds(value));
367 break; 453 break;
368 case webrtc::kNetworkInterfaces_IPv4: 454 case webrtc::kNetworkInterfaces_IPv4:
369 UMA_HISTOGRAM_COUNTS_100("WebRTC.PeerConnection.IPv4Interfaces", 455 UMA_HISTOGRAM_COUNTS_100("WebRTC.PeerConnection.IPv4Interfaces",
370 value); 456 value);
371 break; 457 break;
372 case webrtc::kNetworkInterfaces_IPv6: 458 case webrtc::kNetworkInterfaces_IPv6:
373 UMA_HISTOGRAM_COUNTS_100("WebRTC.PeerConnection.IPv6Interfaces", 459 UMA_HISTOGRAM_COUNTS_100("WebRTC.PeerConnection.IPv6Interfaces",
374 value); 460 value);
375 break; 461 break;
376 default: 462 default:
377 NOTREACHED(); 463 NOTREACHED();
378 } 464 }
379 } 465 }
380 }; 466 };
381 467
382 base::LazyInstance<std::set<RTCPeerConnectionHandler*> >::Leaky 468 base::LazyInstance<std::set<RTCPeerConnectionHandler*> >::Leaky
383 g_peer_connection_handlers = LAZY_INSTANCE_INITIALIZER; 469 g_peer_connection_handlers = LAZY_INSTANCE_INITIALIZER;
384 470
385 } // namespace 471 } // namespace
386 472
473 // Receives notifications from a PeerConnection object about state changes,
474 // track addition/removal etc. The callbacks we receive here come on the
475 // signaling thread, so this class takes care of delivering them to an
476 // RTCPeerConnectionHandler instance on the main thread.
477 // In order to do safe PostTask-ing, the class is reference counted and
478 // checks for the existence of the RTCPeerConnectionHandler instance before
479 // delivering callbacks on the main thread.
480 class RTCPeerConnectionHandler::Observer
481 : public base::RefCountedThreadSafe<RTCPeerConnectionHandler::Observer>,
482 public PeerConnectionObserver {
483 public:
484 Observer(const base::WeakPtr<RTCPeerConnectionHandler>& handler)
485 : handler_(handler), main_thread_(base::ThreadTaskRunnerHandle::Get()) {}
486
487 protected:
488 friend class base::RefCountedThreadSafe<RTCPeerConnectionHandler::Observer>;
489 virtual ~Observer() {}
490
491 void OnError() override {
492 // TODO(perkj): Remove from the PC interface?
493 NOTIMPLEMENTED();
494 }
495
496 void OnSignalingChange(
497 PeerConnectionInterface::SignalingState new_state) override {
498 if (!main_thread_->BelongsToCurrentThread()) {
499 main_thread_->PostTask(FROM_HERE,
500 base::Bind(&RTCPeerConnectionHandler::Observer::OnSignalingChange,
501 this, new_state));
502 } else if (handler_) {
503 handler_->OnSignalingChange(new_state);
504 }
505 }
506
507 void OnAddStream(MediaStreamInterface* stream) override {
508 DCHECK(stream);
509 scoped_ptr<RemoteMediaStreamImpl> remote_stream(
510 new RemoteMediaStreamImpl(main_thread_, stream));
511
512 // The webkit object owned by RemoteMediaStreamImpl, will be initialized
513 // asynchronously and the posted task will execude after that initialization
514 // is done.
515 main_thread_->PostTask(FROM_HERE,
516 base::Bind(&RTCPeerConnectionHandler::Observer::OnAddStreamImpl,
517 this, base::Passed(&remote_stream)));
518 }
519
520 void OnRemoveStream(MediaStreamInterface* stream) override {
521 main_thread_->PostTask(FROM_HERE,
522 base::Bind(&RTCPeerConnectionHandler::Observer::OnRemoveStreamImpl,
523 this, make_scoped_refptr(stream)));
524 }
525
526 void OnDataChannel(DataChannelInterface* data_channel) override {
527 scoped_ptr<RtcDataChannelHandler> handler(
528 new RtcDataChannelHandler(main_thread_, data_channel));
529 main_thread_->PostTask(FROM_HERE,
530 base::Bind(&RTCPeerConnectionHandler::Observer::OnDataChannelImpl,
531 this, base::Passed(&handler)));
532 }
533
534 void OnRenegotiationNeeded() override {
535 if (!main_thread_->BelongsToCurrentThread()) {
536 main_thread_->PostTask(FROM_HERE,
537 base::Bind(&RTCPeerConnectionHandler::Observer::OnRenegotiationNeeded,
538 this));
539 } else if (handler_) {
540 handler_->OnRenegotiationNeeded();
541 }
542 }
543
544 void OnIceConnectionChange(
545 PeerConnectionInterface::IceConnectionState new_state) override {
546 if (!main_thread_->BelongsToCurrentThread()) {
547 main_thread_->PostTask(FROM_HERE,
548 base::Bind(
549 &RTCPeerConnectionHandler::Observer::OnIceConnectionChange, this,
550 new_state));
551 } else if (handler_) {
552 handler_->OnIceConnectionChange(new_state);
553 }
554 }
555
556 void OnIceGatheringChange(
557 PeerConnectionInterface::IceGatheringState new_state) override {
558 if (!main_thread_->BelongsToCurrentThread()) {
559 main_thread_->PostTask(FROM_HERE,
560 base::Bind(&RTCPeerConnectionHandler::Observer::OnIceGatheringChange,
561 this, new_state));
562 } else if (handler_) {
563 handler_->OnIceGatheringChange(new_state);
564 }
565 }
566
567 void OnIceCandidate(const IceCandidateInterface* candidate) override {
568 std::string sdp;
569 if (!candidate->ToString(&sdp)) {
570 NOTREACHED() << "OnIceCandidate: Could not get SDP string.";
571 return;
572 }
573
574 main_thread_->PostTask(FROM_HERE,
575 base::Bind(&RTCPeerConnectionHandler::Observer::OnIceCandidateImpl,
576 this, sdp, candidate->sdp_mid(), candidate->sdp_mline_index(),
577 candidate->candidate().component(),
578 candidate->candidate().address().family()));
579 }
580
581 void OnAddStreamImpl(scoped_ptr<RemoteMediaStreamImpl> stream) {
582 DCHECK(stream->webkit_stream().extraData()) << "Initialization not done";
583 if (handler_)
584 handler_->OnAddStream(stream.Pass());
585 }
586
587 void OnRemoveStreamImpl(const scoped_refptr<MediaStreamInterface>& stream) {
588 if (handler_)
589 handler_->OnRemoveStream(stream);
590 }
591
592 void OnDataChannelImpl(scoped_ptr<RtcDataChannelHandler> handler) {
593 if (handler_)
594 handler_->OnDataChannel(handler.Pass());
595 }
596
597 void OnIceCandidateImpl(const std::string& sdp, const std::string& sdp_mid,
598 int sdp_mline_index, int component, int address_family) {
599 if (handler_) {
600 handler_->OnIceCandidate(sdp, sdp_mid, sdp_mline_index, component,
601 address_family);
602 }
603 }
604
605 private:
606 const base::WeakPtr<RTCPeerConnectionHandler> handler_;
607 const scoped_refptr<base::SingleThreadTaskRunner> main_thread_;
608 };
609
387 RTCPeerConnectionHandler::RTCPeerConnectionHandler( 610 RTCPeerConnectionHandler::RTCPeerConnectionHandler(
388 blink::WebRTCPeerConnectionHandlerClient* client, 611 blink::WebRTCPeerConnectionHandlerClient* client,
389 PeerConnectionDependencyFactory* dependency_factory) 612 PeerConnectionDependencyFactory* dependency_factory,
613 const scoped_refptr<base::SingleThreadTaskRunner>& signaling_thread)
390 : client_(client), 614 : client_(client),
391 dependency_factory_(dependency_factory), 615 dependency_factory_(dependency_factory),
392 frame_(NULL), 616 frame_(NULL),
617 signaling_thread_(signaling_thread),
393 peer_connection_tracker_(NULL), 618 peer_connection_tracker_(NULL),
394 num_data_channels_created_(0), 619 num_data_channels_created_(0),
395 num_local_candidates_ipv4_(0), 620 num_local_candidates_ipv4_(0),
396 num_local_candidates_ipv6_(0) { 621 num_local_candidates_ipv6_(0),
622 weak_factory_(this) {
623 DCHECK(signaling_thread_);
397 g_peer_connection_handlers.Get().insert(this); 624 g_peer_connection_handlers.Get().insert(this);
398 } 625 }
399 626
400 RTCPeerConnectionHandler::~RTCPeerConnectionHandler() { 627 RTCPeerConnectionHandler::~RTCPeerConnectionHandler() {
628 DCHECK(thread_checker_.CalledOnValidThread());
401 g_peer_connection_handlers.Get().erase(this); 629 g_peer_connection_handlers.Get().erase(this);
402 if (peer_connection_tracker_) 630 if (peer_connection_tracker_)
403 peer_connection_tracker_->UnregisterPeerConnection(this); 631 peer_connection_tracker_->UnregisterPeerConnection(this);
404 STLDeleteValues(&remote_streams_); 632 STLDeleteValues(&remote_streams_);
405 633
406 UMA_HISTOGRAM_COUNTS_10000( 634 UMA_HISTOGRAM_COUNTS_10000(
407 "WebRTC.NumDataChannelsPerPeerConnection", num_data_channels_created_); 635 "WebRTC.NumDataChannelsPerPeerConnection", num_data_channels_created_);
408 } 636 }
409 637
410 // static 638 // static
411 void RTCPeerConnectionHandler::DestructAllHandlers() { 639 void RTCPeerConnectionHandler::DestructAllHandlers() {
412 std::set<RTCPeerConnectionHandler*> handlers( 640 std::set<RTCPeerConnectionHandler*> handlers(
413 g_peer_connection_handlers.Get().begin(), 641 g_peer_connection_handlers.Get().begin(),
414 g_peer_connection_handlers.Get().end()); 642 g_peer_connection_handlers.Get().end());
415 for (std::set<RTCPeerConnectionHandler*>::iterator handler = handlers.begin(); 643 for (auto handler : handlers) {
416 handler != handlers.end(); 644 if (handler->client_)
417 ++handler) { 645 handler->client_->releasePeerConnectionHandler();
418 (*handler)->client_->releasePeerConnectionHandler();
419 } 646 }
420 } 647 }
421 648
649 // static
422 void RTCPeerConnectionHandler::ConvertOfferOptionsToConstraints( 650 void RTCPeerConnectionHandler::ConvertOfferOptionsToConstraints(
423 const blink::WebRTCOfferOptions& options, 651 const blink::WebRTCOfferOptions& options,
424 RTCMediaConstraints* output) { 652 RTCMediaConstraints* output) {
425 output->AddMandatory( 653 output->AddMandatory(
426 webrtc::MediaConstraintsInterface::kOfferToReceiveAudio, 654 webrtc::MediaConstraintsInterface::kOfferToReceiveAudio,
427 options.offerToReceiveAudio() > 0 ? "true" : "false", 655 options.offerToReceiveAudio() > 0 ? "true" : "false",
428 true); 656 true);
429 657
430 output->AddMandatory( 658 output->AddMandatory(
431 webrtc::MediaConstraintsInterface::kOfferToReceiveVideo, 659 webrtc::MediaConstraintsInterface::kOfferToReceiveVideo,
432 options.offerToReceiveVideo() > 0 ? "true" : "false", 660 options.offerToReceiveVideo() > 0 ? "true" : "false",
433 true); 661 true);
434 662
435 if (!options.voiceActivityDetection()) { 663 if (!options.voiceActivityDetection()) {
436 output->AddMandatory( 664 output->AddMandatory(
437 webrtc::MediaConstraintsInterface::kVoiceActivityDetection, 665 webrtc::MediaConstraintsInterface::kVoiceActivityDetection,
438 "false", 666 "false",
439 true); 667 true);
440 } 668 }
441 669
442 if (options.iceRestart()) { 670 if (options.iceRestart()) {
443 output->AddMandatory( 671 output->AddMandatory(
444 webrtc::MediaConstraintsInterface::kIceRestart, "true", true); 672 webrtc::MediaConstraintsInterface::kIceRestart, "true", true);
445 } 673 }
446 } 674 }
447 675
448 void RTCPeerConnectionHandler::associateWithFrame(blink::WebFrame* frame) { 676 void RTCPeerConnectionHandler::associateWithFrame(blink::WebFrame* frame) {
677 DCHECK(thread_checker_.CalledOnValidThread());
449 DCHECK(frame); 678 DCHECK(frame);
450 frame_ = frame; 679 frame_ = frame;
451 } 680 }
452 681
453 bool RTCPeerConnectionHandler::initialize( 682 bool RTCPeerConnectionHandler::initialize(
454 const blink::WebRTCConfiguration& server_configuration, 683 const blink::WebRTCConfiguration& server_configuration,
455 const blink::WebMediaConstraints& options) { 684 const blink::WebMediaConstraints& options) {
685 DCHECK(thread_checker_.CalledOnValidThread());
456 DCHECK(frame_); 686 DCHECK(frame_);
457 687
458 peer_connection_tracker_ = 688 peer_connection_tracker_ =
459 RenderThreadImpl::current()->peer_connection_tracker(); 689 RenderThreadImpl::current()->peer_connection_tracker();
460 690
461 webrtc::PeerConnectionInterface::RTCConfiguration config; 691 webrtc::PeerConnectionInterface::RTCConfiguration config;
462 GetNativeRtcConfiguration(server_configuration, &config); 692 GetNativeRtcConfiguration(server_configuration, &config);
463 693
464 RTCMediaConstraints constraints(options); 694 RTCMediaConstraints constraints(options);
465 695
466 native_peer_connection_ = 696 peer_connection_observer_ = new Observer(weak_factory_.GetWeakPtr());
467 dependency_factory_->CreatePeerConnection( 697 native_peer_connection_ = dependency_factory_->CreatePeerConnection(
468 config, &constraints, frame_, this); 698 config, &constraints, frame_, peer_connection_observer_.get());
469 699
470 if (!native_peer_connection_.get()) { 700 if (!native_peer_connection_.get()) {
471 LOG(ERROR) << "Failed to initialize native PeerConnection."; 701 LOG(ERROR) << "Failed to initialize native PeerConnection.";
472 return false; 702 return false;
473 } 703 }
474 if (peer_connection_tracker_) 704
705 if (peer_connection_tracker_) {
475 peer_connection_tracker_->RegisterPeerConnection( 706 peer_connection_tracker_->RegisterPeerConnection(
476 this, config, constraints, frame_); 707 this, config, constraints, frame_);
708 }
477 709
478 uma_observer_ = new rtc::RefCountedObject<PeerConnectionUMAObserver>(); 710 uma_observer_ = new rtc::RefCountedObject<PeerConnectionUMAObserver>();
479 native_peer_connection_->RegisterUMAObserver(uma_observer_.get()); 711 native_peer_connection_->RegisterUMAObserver(uma_observer_.get());
480 return true; 712 return true;
481 } 713 }
482 714
483 bool RTCPeerConnectionHandler::InitializeForTest( 715 bool RTCPeerConnectionHandler::InitializeForTest(
484 const blink::WebRTCConfiguration& server_configuration, 716 const blink::WebRTCConfiguration& server_configuration,
485 const blink::WebMediaConstraints& options, 717 const blink::WebMediaConstraints& options,
486 PeerConnectionTracker* peer_connection_tracker) { 718 PeerConnectionTracker* peer_connection_tracker) {
719 DCHECK(thread_checker_.CalledOnValidThread());
487 webrtc::PeerConnectionInterface::RTCConfiguration config; 720 webrtc::PeerConnectionInterface::RTCConfiguration config;
488 GetNativeRtcConfiguration(server_configuration, &config); 721 GetNativeRtcConfiguration(server_configuration, &config);
489 722
723 peer_connection_observer_ = new Observer(weak_factory_.GetWeakPtr());
490 RTCMediaConstraints constraints(options); 724 RTCMediaConstraints constraints(options);
491 native_peer_connection_ = 725 native_peer_connection_ = dependency_factory_->CreatePeerConnection(
492 dependency_factory_->CreatePeerConnection( 726 config, &constraints, NULL, peer_connection_observer_.get());
493 config, &constraints, NULL, this);
494 if (!native_peer_connection_.get()) { 727 if (!native_peer_connection_.get()) {
495 LOG(ERROR) << "Failed to initialize native PeerConnection."; 728 LOG(ERROR) << "Failed to initialize native PeerConnection.";
496 return false; 729 return false;
497 } 730 }
498 peer_connection_tracker_ = peer_connection_tracker; 731 peer_connection_tracker_ = peer_connection_tracker;
499 return true; 732 return true;
500 } 733 }
501 734
502 void RTCPeerConnectionHandler::createOffer( 735 void RTCPeerConnectionHandler::createOffer(
503 const blink::WebRTCSessionDescriptionRequest& request, 736 const blink::WebRTCSessionDescriptionRequest& request,
504 const blink::WebMediaConstraints& options) { 737 const blink::WebMediaConstraints& options) {
738 DCHECK(thread_checker_.CalledOnValidThread());
505 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createOffer"); 739 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createOffer");
740
506 scoped_refptr<CreateSessionDescriptionRequest> description_request( 741 scoped_refptr<CreateSessionDescriptionRequest> description_request(
507 new rtc::RefCountedObject<CreateSessionDescriptionRequest>( 742 new rtc::RefCountedObject<CreateSessionDescriptionRequest>(
508 request, this, PeerConnectionTracker::ACTION_CREATE_OFFER)); 743 base::ThreadTaskRunnerHandle::Get(), request, this,
744 PeerConnectionTracker::ACTION_CREATE_OFFER));
745
509 RTCMediaConstraints constraints(options); 746 RTCMediaConstraints constraints(options);
510 native_peer_connection_->CreateOffer(description_request.get(), &constraints); 747 native_peer_connection_->CreateOffer(description_request.get(), &constraints);
511 748
512 if (peer_connection_tracker_) 749 if (peer_connection_tracker_)
513 peer_connection_tracker_->TrackCreateOffer(this, constraints); 750 peer_connection_tracker_->TrackCreateOffer(this, constraints);
514 } 751 }
515 752
516 void RTCPeerConnectionHandler::createOffer( 753 void RTCPeerConnectionHandler::createOffer(
517 const blink::WebRTCSessionDescriptionRequest& request, 754 const blink::WebRTCSessionDescriptionRequest& request,
518 const blink::WebRTCOfferOptions& options) { 755 const blink::WebRTCOfferOptions& options) {
756 DCHECK(thread_checker_.CalledOnValidThread());
519 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createOffer"); 757 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createOffer");
758
520 scoped_refptr<CreateSessionDescriptionRequest> description_request( 759 scoped_refptr<CreateSessionDescriptionRequest> description_request(
521 new rtc::RefCountedObject<CreateSessionDescriptionRequest>( 760 new rtc::RefCountedObject<CreateSessionDescriptionRequest>(
522 request, this, PeerConnectionTracker::ACTION_CREATE_OFFER)); 761 base::ThreadTaskRunnerHandle::Get(), request, this,
762 PeerConnectionTracker::ACTION_CREATE_OFFER));
523 763
524 RTCMediaConstraints constraints; 764 RTCMediaConstraints constraints;
525 ConvertOfferOptionsToConstraints(options, &constraints); 765 ConvertOfferOptionsToConstraints(options, &constraints);
526 native_peer_connection_->CreateOffer(description_request.get(), &constraints); 766 native_peer_connection_->CreateOffer(description_request.get(), &constraints);
527 767
528 if (peer_connection_tracker_) 768 if (peer_connection_tracker_)
529 peer_connection_tracker_->TrackCreateOffer(this, constraints); 769 peer_connection_tracker_->TrackCreateOffer(this, constraints);
530 } 770 }
531 771
532 void RTCPeerConnectionHandler::createAnswer( 772 void RTCPeerConnectionHandler::createAnswer(
533 const blink::WebRTCSessionDescriptionRequest& request, 773 const blink::WebRTCSessionDescriptionRequest& request,
534 const blink::WebMediaConstraints& options) { 774 const blink::WebMediaConstraints& options) {
775 DCHECK(thread_checker_.CalledOnValidThread());
535 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createAnswer"); 776 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createAnswer");
536 scoped_refptr<CreateSessionDescriptionRequest> description_request( 777 scoped_refptr<CreateSessionDescriptionRequest> description_request(
537 new rtc::RefCountedObject<CreateSessionDescriptionRequest>( 778 new rtc::RefCountedObject<CreateSessionDescriptionRequest>(
538 request, this, PeerConnectionTracker::ACTION_CREATE_ANSWER)); 779 base::ThreadTaskRunnerHandle::Get(), request, this,
780 PeerConnectionTracker::ACTION_CREATE_ANSWER));
539 RTCMediaConstraints constraints(options); 781 RTCMediaConstraints constraints(options);
540 native_peer_connection_->CreateAnswer(description_request.get(), 782 native_peer_connection_->CreateAnswer(description_request.get(),
541 &constraints); 783 &constraints);
542 784
543 if (peer_connection_tracker_) 785 if (peer_connection_tracker_)
544 peer_connection_tracker_->TrackCreateAnswer(this, constraints); 786 peer_connection_tracker_->TrackCreateAnswer(this, constraints);
545 } 787 }
546 788
789 void SetLocalDescriptionOnSignalingThread(
790 const scoped_refptr<webrtc::PeerConnectionInterface>& pc,
791 const scoped_refptr<SetSessionDescriptionRequest>& set_request,
792 webrtc::SessionDescriptionInterface* native_desc) {
793 TRACE_EVENT0("webrtc", "SetLocalDescriptionOnSignalingThread");
794 pc->SetLocalDescription(set_request.get(), native_desc);
795 }
796
547 void RTCPeerConnectionHandler::setLocalDescription( 797 void RTCPeerConnectionHandler::setLocalDescription(
548 const blink::WebRTCVoidRequest& request, 798 const blink::WebRTCVoidRequest& request,
549 const blink::WebRTCSessionDescription& description) { 799 const blink::WebRTCSessionDescription& description) {
800 DCHECK(thread_checker_.CalledOnValidThread());
550 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::setLocalDescription"); 801 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::setLocalDescription");
802
803 std::string sdp = base::UTF16ToUTF8(description.sdp());
804 std::string type = base::UTF16ToUTF8(description.type());
805
551 webrtc::SdpParseError error; 806 webrtc::SdpParseError error;
807 // Since CreateNativeSessionDescription uses the dependency factory, we need
808 // to make this call on the current thread to be safe.
552 webrtc::SessionDescriptionInterface* native_desc = 809 webrtc::SessionDescriptionInterface* native_desc =
553 CreateNativeSessionDescription(description, &error); 810 CreateNativeSessionDescription(sdp, type, &error);
554 if (!native_desc) { 811 if (!native_desc) {
555 std::string reason_str = "Failed to parse SessionDescription. "; 812 std::string reason_str = "Failed to parse SessionDescription. ";
556 reason_str.append(error.line); 813 reason_str.append(error.line);
557 reason_str.append(" "); 814 reason_str.append(" ");
558 reason_str.append(error.description); 815 reason_str.append(error.description);
559 LOG(ERROR) << reason_str; 816 LOG(ERROR) << reason_str;
560 request.requestFailed(blink::WebString::fromUTF8(reason_str)); 817 request.requestFailed(blink::WebString::fromUTF8(reason_str));
561 return; 818 return;
562 } 819 }
563 if (peer_connection_tracker_)
564 peer_connection_tracker_->TrackSetSessionDescription(
565 this, description, PeerConnectionTracker::SOURCE_LOCAL);
566 820
567 scoped_refptr<SetSessionDescriptionRequest> set_request( 821 scoped_refptr<SetSessionDescriptionRequest> set_request(
568 new rtc::RefCountedObject<SetSessionDescriptionRequest>( 822 new rtc::RefCountedObject<SetSessionDescriptionRequest>(
569 request, this, PeerConnectionTracker::ACTION_SET_LOCAL_DESCRIPTION)); 823 base::ThreadTaskRunnerHandle::Get(), request, this,
570 native_peer_connection_->SetLocalDescription(set_request.get(), native_desc); 824 PeerConnectionTracker::ACTION_SET_LOCAL_DESCRIPTION));
825
826 signaling_thread_->PostTask(FROM_HERE,
827 base::Bind(&SetLocalDescriptionOnSignalingThread,
828 native_peer_connection_, set_request, base::Unretained(native_desc)));
829
830 if (peer_connection_tracker_) {
831 peer_connection_tracker_->TrackSetSessionDescription(
832 this, sdp, type, PeerConnectionTracker::SOURCE_LOCAL);
833 }
834 }
835
836 void SetRemoteDescriptionOnSignalingThread(
837 const scoped_refptr<webrtc::PeerConnectionInterface>& pc,
838 const scoped_refptr<SetSessionDescriptionRequest>& set_request,
839 webrtc::SessionDescriptionInterface* native_desc) {
840 TRACE_EVENT0("webrtc", "SetRemoteDescriptionOnSignalingThread");
841 pc->SetRemoteDescription(set_request.get(), native_desc);
571 } 842 }
572 843
573 void RTCPeerConnectionHandler::setRemoteDescription( 844 void RTCPeerConnectionHandler::setRemoteDescription(
574 const blink::WebRTCVoidRequest& request, 845 const blink::WebRTCVoidRequest& request,
575 const blink::WebRTCSessionDescription& description) { 846 const blink::WebRTCSessionDescription& description) {
847 DCHECK(thread_checker_.CalledOnValidThread());
576 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::setRemoteDescription"); 848 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::setRemoteDescription");
849 std::string sdp = base::UTF16ToUTF8(description.sdp());
850 std::string type = base::UTF16ToUTF8(description.type());
851
577 webrtc::SdpParseError error; 852 webrtc::SdpParseError error;
853 // Since CreateNativeSessionDescription uses the dependency factory, we need
854 // to make this call on the current thread to be safe.
578 webrtc::SessionDescriptionInterface* native_desc = 855 webrtc::SessionDescriptionInterface* native_desc =
579 CreateNativeSessionDescription(description, &error); 856 CreateNativeSessionDescription(sdp, type, &error);
580 if (!native_desc) { 857 if (!native_desc) {
581 std::string reason_str = "Failed to parse SessionDescription. "; 858 std::string reason_str = "Failed to parse SessionDescription. ";
582 reason_str.append(error.line); 859 reason_str.append(error.line);
583 reason_str.append(" "); 860 reason_str.append(" ");
584 reason_str.append(error.description); 861 reason_str.append(error.description);
585 LOG(ERROR) << reason_str; 862 LOG(ERROR) << reason_str;
586 request.requestFailed(blink::WebString::fromUTF8(reason_str)); 863 request.requestFailed(blink::WebString::fromUTF8(reason_str));
587 return; 864 return;
588 } 865 }
589 if (peer_connection_tracker_)
590 peer_connection_tracker_->TrackSetSessionDescription(
591 this, description, PeerConnectionTracker::SOURCE_REMOTE);
592 866
593 scoped_refptr<SetSessionDescriptionRequest> set_request( 867 scoped_refptr<SetSessionDescriptionRequest> set_request(
594 new rtc::RefCountedObject<SetSessionDescriptionRequest>( 868 new rtc::RefCountedObject<SetSessionDescriptionRequest>(
595 request, this, PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION)); 869 base::ThreadTaskRunnerHandle::Get(), request, this,
596 native_peer_connection_->SetRemoteDescription(set_request.get(), native_desc); 870 PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION));
871
872 signaling_thread_->PostTask(FROM_HERE,
873 base::Bind(&SetRemoteDescriptionOnSignalingThread,
874 native_peer_connection_, set_request, base::Unretained(native_desc)));
875
876 if (peer_connection_tracker_) {
877 peer_connection_tracker_->TrackSetSessionDescription(
878 this, sdp, type, PeerConnectionTracker::SOURCE_REMOTE);
879 }
597 } 880 }
598 881
599 blink::WebRTCSessionDescription 882 blink::WebRTCSessionDescription
600 RTCPeerConnectionHandler::localDescription() { 883 RTCPeerConnectionHandler::localDescription() {
884 DCHECK(thread_checker_.CalledOnValidThread());
601 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::localDescription"); 885 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::localDescription");
602 const webrtc::SessionDescriptionInterface* native_desc = 886 const webrtc::SessionDescriptionInterface* native_desc =
603 native_peer_connection_->local_description(); 887 native_peer_connection_->local_description();
604 blink::WebRTCSessionDescription description = 888 blink::WebRTCSessionDescription description =
605 CreateWebKitSessionDescription(native_desc); 889 CreateWebKitSessionDescription(native_desc);
606 return description; 890 return description;
607 } 891 }
608 892
609 blink::WebRTCSessionDescription 893 blink::WebRTCSessionDescription
610 RTCPeerConnectionHandler::remoteDescription() { 894 RTCPeerConnectionHandler::remoteDescription() {
895 DCHECK(thread_checker_.CalledOnValidThread());
611 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::remoteDescription"); 896 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::remoteDescription");
612 const webrtc::SessionDescriptionInterface* native_desc = 897 const webrtc::SessionDescriptionInterface* native_desc =
613 native_peer_connection_->remote_description(); 898 native_peer_connection_->remote_description();
614 blink::WebRTCSessionDescription description = 899 blink::WebRTCSessionDescription description =
615 CreateWebKitSessionDescription(native_desc); 900 CreateWebKitSessionDescription(native_desc);
616 return description; 901 return description;
617 } 902 }
618 903
619 bool RTCPeerConnectionHandler::updateICE( 904 bool RTCPeerConnectionHandler::updateICE(
620 const blink::WebRTCConfiguration& server_configuration, 905 const blink::WebRTCConfiguration& server_configuration,
621 const blink::WebMediaConstraints& options) { 906 const blink::WebMediaConstraints& options) {
907 DCHECK(thread_checker_.CalledOnValidThread());
622 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::updateICE"); 908 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::updateICE");
623 webrtc::PeerConnectionInterface::RTCConfiguration config; 909 webrtc::PeerConnectionInterface::RTCConfiguration config;
624 GetNativeRtcConfiguration(server_configuration, &config); 910 GetNativeRtcConfiguration(server_configuration, &config);
625 RTCMediaConstraints constraints(options); 911 RTCMediaConstraints constraints(options);
626 912
627 if (peer_connection_tracker_) 913 if (peer_connection_tracker_)
628 peer_connection_tracker_->TrackUpdateIce(this, config, constraints); 914 peer_connection_tracker_->TrackUpdateIce(this, config, constraints);
629 915
630 return native_peer_connection_->UpdateIce(config.servers, 916 return native_peer_connection_->UpdateIce(config.servers, &constraints);
631 &constraints);
632 } 917 }
633 918
634 bool RTCPeerConnectionHandler::addICECandidate( 919 bool RTCPeerConnectionHandler::addICECandidate(
635 const blink::WebRTCVoidRequest& request, 920 const blink::WebRTCVoidRequest& request,
636 const blink::WebRTCICECandidate& candidate) { 921 const blink::WebRTCICECandidate& candidate) {
922 DCHECK(thread_checker_.CalledOnValidThread());
637 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::addICECandidate"); 923 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::addICECandidate");
638 // Libjingle currently does not accept callbacks for addICECandidate. 924 // Libjingle currently does not accept callbacks for addICECandidate.
639 // For that reason we are going to call callbacks from here. 925 // For that reason we are going to call callbacks from here.
640 bool result = addICECandidate(candidate); 926 bool result = addICECandidate(candidate);
641 base::MessageLoop::current()->PostTask( 927 base::MessageLoop::current()->PostTask(
642 FROM_HERE, 928 FROM_HERE,
643 base::Bind(&RTCPeerConnectionHandler::OnaddICECandidateResult, 929 base::Bind(&RTCPeerConnectionHandler::OnaddICECandidateResult,
644 base::Unretained(this), request, result)); 930 weak_factory_.GetWeakPtr(), request, result));
645 // On failure callback will be triggered. 931 // On failure callback will be triggered.
646 return true; 932 return true;
647 } 933 }
648 934
649 bool RTCPeerConnectionHandler::addICECandidate( 935 bool RTCPeerConnectionHandler::addICECandidate(
650 const blink::WebRTCICECandidate& candidate) { 936 const blink::WebRTCICECandidate& candidate) {
937 DCHECK(thread_checker_.CalledOnValidThread());
651 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::addICECandidate"); 938 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::addICECandidate");
652 scoped_ptr<webrtc::IceCandidateInterface> native_candidate( 939 scoped_ptr<webrtc::IceCandidateInterface> native_candidate(
653 dependency_factory_->CreateIceCandidate( 940 dependency_factory_->CreateIceCandidate(
654 base::UTF16ToUTF8(candidate.sdpMid()), 941 base::UTF16ToUTF8(candidate.sdpMid()),
655 candidate.sdpMLineIndex(), 942 candidate.sdpMLineIndex(),
656 base::UTF16ToUTF8(candidate.candidate()))); 943 base::UTF16ToUTF8(candidate.candidate())));
657 bool return_value = false; 944 bool return_value = false;
658 945
659 if (native_candidate) { 946 if (native_candidate) {
660 return_value = 947 return_value =
661 native_peer_connection_->AddIceCandidate(native_candidate.get()); 948 native_peer_connection_->AddIceCandidate(native_candidate.get());
662 LOG_IF(ERROR, !return_value) << "Error processing ICE candidate."; 949 LOG_IF(ERROR, !return_value) << "Error processing ICE candidate.";
663 } else { 950 } else {
664 LOG(ERROR) << "Could not create native ICE candidate."; 951 LOG(ERROR) << "Could not create native ICE candidate.";
665 } 952 }
666 953
667 if (peer_connection_tracker_) { 954 if (peer_connection_tracker_) {
668 peer_connection_tracker_->TrackAddIceCandidate( 955 peer_connection_tracker_->TrackAddIceCandidate(
669 this, candidate, PeerConnectionTracker::SOURCE_REMOTE, return_value); 956 this, candidate, PeerConnectionTracker::SOURCE_REMOTE, return_value);
670 } 957 }
671 return return_value; 958 return return_value;
672 } 959 }
673 960
674 void RTCPeerConnectionHandler::OnaddICECandidateResult( 961 void RTCPeerConnectionHandler::OnaddICECandidateResult(
675 const blink::WebRTCVoidRequest& webkit_request, bool result) { 962 const blink::WebRTCVoidRequest& webkit_request, bool result) {
963 DCHECK(thread_checker_.CalledOnValidThread());
676 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnaddICECandidateResult"); 964 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnaddICECandidateResult");
677 if (!result) { 965 if (!result) {
678 // We don't have the actual error code from the libjingle, so for now 966 // We don't have the actual error code from the libjingle, so for now
679 // using a generic error string. 967 // using a generic error string.
680 return webkit_request.requestFailed( 968 return webkit_request.requestFailed(
681 base::UTF8ToUTF16("Error processing ICE candidate")); 969 base::UTF8ToUTF16("Error processing ICE candidate"));
682 } 970 }
683 971
684 return webkit_request.requestSucceeded(); 972 return webkit_request.requestSucceeded();
685 } 973 }
686 974
687 bool RTCPeerConnectionHandler::addStream( 975 bool RTCPeerConnectionHandler::addStream(
688 const blink::WebMediaStream& stream, 976 const blink::WebMediaStream& stream,
689 const blink::WebMediaConstraints& options) { 977 const blink::WebMediaConstraints& options) {
978 DCHECK(thread_checker_.CalledOnValidThread());
690 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::addStream"); 979 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::addStream");
691 for (ScopedVector<WebRtcMediaStreamAdapter>::iterator adapter_it = 980 for (ScopedVector<WebRtcMediaStreamAdapter>::iterator adapter_it =
692 local_streams_.begin(); adapter_it != local_streams_.end(); 981 local_streams_.begin(); adapter_it != local_streams_.end();
693 ++adapter_it) { 982 ++adapter_it) {
694 if ((*adapter_it)->IsEqual(stream)) { 983 if ((*adapter_it)->IsEqual(stream)) {
695 DVLOG(1) << "RTCPeerConnectionHandler::addStream called with the same " 984 DVLOG(1) << "RTCPeerConnectionHandler::addStream called with the same "
696 << "stream twice. id=" << stream.id().utf8(); 985 << "stream twice. id=" << stream.id().utf8();
697 return false; 986 return false;
698 } 987 }
699 } 988 }
700 989
701 if (peer_connection_tracker_) 990 if (peer_connection_tracker_) {
702 peer_connection_tracker_->TrackAddStream( 991 peer_connection_tracker_->TrackAddStream(
703 this, stream, PeerConnectionTracker::SOURCE_LOCAL); 992 this, stream, PeerConnectionTracker::SOURCE_LOCAL);
993 }
704 994
705 PerSessionWebRTCAPIMetrics::GetInstance()->IncrementStreamCounter(); 995 PerSessionWebRTCAPIMetrics::GetInstance()->IncrementStreamCounter();
706 996
707 WebRtcMediaStreamAdapter* adapter = 997 WebRtcMediaStreamAdapter* adapter =
708 new WebRtcMediaStreamAdapter(stream, dependency_factory_); 998 new WebRtcMediaStreamAdapter(stream, dependency_factory_);
709 local_streams_.push_back(adapter); 999 local_streams_.push_back(adapter);
710 1000
711 webrtc::MediaStreamInterface* webrtc_stream = adapter->webrtc_media_stream(); 1001 webrtc::MediaStreamInterface* webrtc_stream = adapter->webrtc_media_stream();
712 track_metrics_.AddStream(MediaStreamTrackMetrics::SENT_STREAM, 1002 track_metrics_.AddStream(MediaStreamTrackMetrics::SENT_STREAM,
713 webrtc_stream); 1003 webrtc_stream);
714 1004
715 RTCMediaConstraints constraints(options); 1005 RTCMediaConstraints constraints(options);
716 return native_peer_connection_->AddStream(webrtc_stream, &constraints); 1006 return native_peer_connection_->AddStream(webrtc_stream, &constraints);
717 } 1007 }
718 1008
719 void RTCPeerConnectionHandler::removeStream( 1009 void RTCPeerConnectionHandler::removeStream(
720 const blink::WebMediaStream& stream) { 1010 const blink::WebMediaStream& stream) {
1011 DCHECK(thread_checker_.CalledOnValidThread());
721 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::removeStream"); 1012 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::removeStream");
722 // Find the webrtc stream. 1013 // Find the webrtc stream.
723 scoped_refptr<webrtc::MediaStreamInterface> webrtc_stream; 1014 scoped_refptr<webrtc::MediaStreamInterface> webrtc_stream;
724 for (ScopedVector<WebRtcMediaStreamAdapter>::iterator adapter_it = 1015 for (ScopedVector<WebRtcMediaStreamAdapter>::iterator adapter_it =
725 local_streams_.begin(); adapter_it != local_streams_.end(); 1016 local_streams_.begin(); adapter_it != local_streams_.end();
726 ++adapter_it) { 1017 ++adapter_it) {
727 if ((*adapter_it)->IsEqual(stream)) { 1018 if ((*adapter_it)->IsEqual(stream)) {
728 webrtc_stream = (*adapter_it)->webrtc_media_stream(); 1019 webrtc_stream = (*adapter_it)->webrtc_media_stream();
729 local_streams_.erase(adapter_it); 1020 local_streams_.erase(adapter_it);
730 break; 1021 break;
731 } 1022 }
732 } 1023 }
733 DCHECK(webrtc_stream.get()); 1024 DCHECK(webrtc_stream.get());
734 native_peer_connection_->RemoveStream(webrtc_stream.get()); 1025 native_peer_connection_->RemoveStream(webrtc_stream.get());
735 1026
736 if (peer_connection_tracker_) 1027 if (peer_connection_tracker_) {
737 peer_connection_tracker_->TrackRemoveStream( 1028 peer_connection_tracker_->TrackRemoveStream(
738 this, stream, PeerConnectionTracker::SOURCE_LOCAL); 1029 this, stream, PeerConnectionTracker::SOURCE_LOCAL);
1030 }
739 PerSessionWebRTCAPIMetrics::GetInstance()->DecrementStreamCounter(); 1031 PerSessionWebRTCAPIMetrics::GetInstance()->DecrementStreamCounter();
740 track_metrics_.RemoveStream(MediaStreamTrackMetrics::SENT_STREAM, 1032 track_metrics_.RemoveStream(MediaStreamTrackMetrics::SENT_STREAM,
741 webrtc_stream.get()); 1033 webrtc_stream.get());
742 } 1034 }
743 1035
744 void RTCPeerConnectionHandler::getStats( 1036 void RTCPeerConnectionHandler::getStats(
745 const blink::WebRTCStatsRequest& request) { 1037 const blink::WebRTCStatsRequest& request) {
1038 DCHECK(thread_checker_.CalledOnValidThread());
746 scoped_refptr<LocalRTCStatsRequest> inner_request( 1039 scoped_refptr<LocalRTCStatsRequest> inner_request(
747 new rtc::RefCountedObject<LocalRTCStatsRequest>(request)); 1040 new rtc::RefCountedObject<LocalRTCStatsRequest>(request));
748 getStats(inner_request.get()); 1041 getStats(inner_request);
749 } 1042 }
750 1043
751 void RTCPeerConnectionHandler::getStats(LocalRTCStatsRequest* request) { 1044 void RTCPeerConnectionHandler::getStats(
1045 const scoped_refptr<LocalRTCStatsRequest>& request) {
1046 DCHECK(thread_checker_.CalledOnValidThread());
1047 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::getStats");
1048
1049
752 rtc::scoped_refptr<webrtc::StatsObserver> observer( 1050 rtc::scoped_refptr<webrtc::StatsObserver> observer(
753 new rtc::RefCountedObject<StatsResponse>(request)); 1051 new rtc::RefCountedObject<StatsResponse>(request));
754 webrtc::MediaStreamTrackInterface* track = NULL; 1052
1053 std::string track_id;
1054 blink::WebMediaStreamSource::Type track_type =
1055 blink::WebMediaStreamSource::TypeAudio;
755 if (request->hasSelector()) { 1056 if (request->hasSelector()) {
756 blink::WebMediaStreamSource::Type type = 1057 track_type = request->component().source().type();
757 request->component().source().type(); 1058 track_id = request->component().id().utf8();
758 std::string track_id = request->component().id().utf8();
759 if (type == blink::WebMediaStreamSource::TypeAudio) {
760 track =
761 native_peer_connection_->local_streams()->FindAudioTrack(track_id);
762 if (!track) {
763 track =
764 native_peer_connection_->remote_streams()->FindAudioTrack(track_id);
765 }
766 } else {
767 DCHECK_EQ(blink::WebMediaStreamSource::TypeVideo, type);
768 track =
769 native_peer_connection_->local_streams()->FindVideoTrack(track_id);
770 if (!track) {
771 track =
772 native_peer_connection_->remote_streams()->FindVideoTrack(track_id);
773 }
774 }
775 if (!track) {
776 DVLOG(1) << "GetStats: Track not found.";
777 // TODO(hta): Consider how to get an error back.
778 observer->OnComplete(StatsReports());
779 return;
780 }
781 } 1059 }
782 GetStats(observer, 1060
783 track, 1061 GetStats(observer, webrtc::PeerConnectionInterface::kStatsOutputLevelStandard,
784 webrtc::PeerConnectionInterface::kStatsOutputLevelStandard); 1062 track_id, track_type);
785 } 1063 }
786 1064
787 void RTCPeerConnectionHandler::GetStats( 1065 void RTCPeerConnectionHandler::GetStats(
788 webrtc::StatsObserver* observer, 1066 webrtc::StatsObserver* observer,
789 webrtc::MediaStreamTrackInterface* track, 1067 webrtc::PeerConnectionInterface::StatsOutputLevel level,
790 webrtc::PeerConnectionInterface::StatsOutputLevel level) { 1068 const std::string& track_id,
791 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::GetStats"); 1069 blink::WebMediaStreamSource::Type track_type) {
792 if (!native_peer_connection_->GetStats(observer, track, level)) { 1070 DCHECK(thread_checker_.CalledOnValidThread());
793 DVLOG(1) << "GetStats failed."; 1071 signaling_thread_->PostTask(FROM_HERE,
794 // TODO(hta): Consider how to get an error back. 1072 base::Bind(&GetStatsOnSignalingThread, native_peer_connection_, level,
795 observer->OnComplete(StatsReports()); 1073 make_scoped_refptr(observer), track_id, track_type));
796 return;
797 }
798 } 1074 }
799 1075
800 void RTCPeerConnectionHandler::CloseClientPeerConnection() { 1076 void RTCPeerConnectionHandler::CloseClientPeerConnection() {
801 client_->closePeerConnection(); 1077 DCHECK(thread_checker_.CalledOnValidThread());
1078 if (client_)
1079 client_->closePeerConnection();
802 } 1080 }
803 1081
804 blink::WebRTCDataChannelHandler* RTCPeerConnectionHandler::createDataChannel( 1082 blink::WebRTCDataChannelHandler* RTCPeerConnectionHandler::createDataChannel(
805 const blink::WebString& label, const blink::WebRTCDataChannelInit& init) { 1083 const blink::WebString& label, const blink::WebRTCDataChannelInit& init) {
1084 DCHECK(thread_checker_.CalledOnValidThread());
806 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createDataChannel"); 1085 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createDataChannel");
807 DVLOG(1) << "createDataChannel label " << base::UTF16ToUTF8(label); 1086 DVLOG(1) << "createDataChannel label " << base::UTF16ToUTF8(label);
808 1087
809 webrtc::DataChannelInit config; 1088 webrtc::DataChannelInit config;
810 // TODO(jiayl): remove the deprecated reliable field once Libjingle is updated 1089 // TODO(jiayl): remove the deprecated reliable field once Libjingle is updated
811 // to handle that. 1090 // to handle that.
812 config.reliable = false; 1091 config.reliable = false;
813 config.id = init.id; 1092 config.id = init.id;
814 config.ordered = init.ordered; 1093 config.ordered = init.ordered;
815 config.negotiated = init.negotiated; 1094 config.negotiated = init.negotiated;
816 config.maxRetransmits = init.maxRetransmits; 1095 config.maxRetransmits = init.maxRetransmits;
817 config.maxRetransmitTime = init.maxRetransmitTime; 1096 config.maxRetransmitTime = init.maxRetransmitTime;
818 config.protocol = base::UTF16ToUTF8(init.protocol); 1097 config.protocol = base::UTF16ToUTF8(init.protocol);
819 1098
820 rtc::scoped_refptr<webrtc::DataChannelInterface> webrtc_channel( 1099 rtc::scoped_refptr<webrtc::DataChannelInterface> webrtc_channel(
821 native_peer_connection_->CreateDataChannel(base::UTF16ToUTF8(label), 1100 native_peer_connection_->CreateDataChannel(base::UTF16ToUTF8(label),
822 &config)); 1101 &config));
823 if (!webrtc_channel) { 1102 if (!webrtc_channel) {
824 DLOG(ERROR) << "Could not create native data channel."; 1103 DLOG(ERROR) << "Could not create native data channel.";
825 return NULL; 1104 return NULL;
826 } 1105 }
827 if (peer_connection_tracker_) 1106 if (peer_connection_tracker_) {
828 peer_connection_tracker_->TrackCreateDataChannel( 1107 peer_connection_tracker_->TrackCreateDataChannel(
829 this, webrtc_channel.get(), PeerConnectionTracker::SOURCE_LOCAL); 1108 this, webrtc_channel.get(), PeerConnectionTracker::SOURCE_LOCAL);
1109 }
830 1110
831 ++num_data_channels_created_; 1111 ++num_data_channels_created_;
832 1112
833 return new RtcDataChannelHandler(base::ThreadTaskRunnerHandle::Get(), 1113 return new RtcDataChannelHandler(base::ThreadTaskRunnerHandle::Get(),
834 webrtc_channel); 1114 webrtc_channel);
835 } 1115 }
836 1116
837 blink::WebRTCDTMFSenderHandler* RTCPeerConnectionHandler::createDTMFSender( 1117 blink::WebRTCDTMFSenderHandler* RTCPeerConnectionHandler::createDTMFSender(
838 const blink::WebMediaStreamTrack& track) { 1118 const blink::WebMediaStreamTrack& track) {
1119 DCHECK(thread_checker_.CalledOnValidThread());
839 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createDTMFSender"); 1120 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createDTMFSender");
840 DVLOG(1) << "createDTMFSender."; 1121 DVLOG(1) << "createDTMFSender.";
841 1122
842 MediaStreamTrack* native_track = MediaStreamTrack::GetTrack(track); 1123 MediaStreamTrack* native_track = MediaStreamTrack::GetTrack(track);
843 if (!native_track || 1124 if (!native_track || !native_track->is_local_track() ||
844 track.source().type() != blink::WebMediaStreamSource::TypeAudio) { 1125 track.source().type() != blink::WebMediaStreamSource::TypeAudio) {
845 DLOG(ERROR) << "Could not create DTMF sender from a non-audio track."; 1126 DLOG(ERROR) << "The DTMF sender requires a local audio track.";
846 return NULL; 1127 return nullptr;
847 } 1128 }
848 1129
849 webrtc::AudioTrackInterface* audio_track = native_track->GetAudioAdapter(); 1130 webrtc::AudioTrackInterface* audio_track = native_track->GetAudioAdapter();
850 rtc::scoped_refptr<webrtc::DtmfSenderInterface> sender( 1131 rtc::scoped_refptr<webrtc::DtmfSenderInterface> sender(
851 native_peer_connection_->CreateDtmfSender(audio_track)); 1132 native_peer_connection_->CreateDtmfSender(audio_track));
852 if (!sender) { 1133 if (!sender) {
853 DLOG(ERROR) << "Could not create native DTMF sender."; 1134 DLOG(ERROR) << "Could not create native DTMF sender.";
854 return NULL; 1135 return nullptr;
855 } 1136 }
856 if (peer_connection_tracker_) 1137 if (peer_connection_tracker_)
857 peer_connection_tracker_->TrackCreateDTMFSender(this, track); 1138 peer_connection_tracker_->TrackCreateDTMFSender(this, track);
858 1139
859 return new RtcDtmfSenderHandler(sender); 1140 return new RtcDtmfSenderHandler(sender);
860 } 1141 }
861 1142
862 void RTCPeerConnectionHandler::stop() { 1143 void RTCPeerConnectionHandler::stop() {
1144 DCHECK(thread_checker_.CalledOnValidThread());
863 DVLOG(1) << "RTCPeerConnectionHandler::stop"; 1145 DVLOG(1) << "RTCPeerConnectionHandler::stop";
864 1146
865 if (peer_connection_tracker_) 1147 if (peer_connection_tracker_)
866 peer_connection_tracker_->TrackStop(this); 1148 peer_connection_tracker_->TrackStop(this);
867 native_peer_connection_->Close(); 1149 native_peer_connection_->Close();
868 } 1150 // The client_ pointer is not considered valid after this point and no further
869 1151 // callbacks must be made.
870 void RTCPeerConnectionHandler::OnError() { 1152 client_ = nullptr;
871 // TODO(perkj): Implement.
872 NOTIMPLEMENTED();
873 } 1153 }
874 1154
875 void RTCPeerConnectionHandler::OnSignalingChange( 1155 void RTCPeerConnectionHandler::OnSignalingChange(
876 webrtc::PeerConnectionInterface::SignalingState new_state) { 1156 webrtc::PeerConnectionInterface::SignalingState new_state) {
1157 DCHECK(thread_checker_.CalledOnValidThread());
877 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnSignalingChange"); 1158 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnSignalingChange");
1159
878 blink::WebRTCPeerConnectionHandlerClient::SignalingState state = 1160 blink::WebRTCPeerConnectionHandlerClient::SignalingState state =
879 GetWebKitSignalingState(new_state); 1161 GetWebKitSignalingState(new_state);
880 if (peer_connection_tracker_) 1162 if (peer_connection_tracker_)
881 peer_connection_tracker_->TrackSignalingStateChange(this, state); 1163 peer_connection_tracker_->TrackSignalingStateChange(this, state);
882 client_->didChangeSignalingState(state); 1164 if (client_)
1165 client_->didChangeSignalingState(state);
883 } 1166 }
884 1167
885 // Called any time the IceConnectionState changes 1168 // Called any time the IceConnectionState changes
886 void RTCPeerConnectionHandler::OnIceConnectionChange( 1169 void RTCPeerConnectionHandler::OnIceConnectionChange(
887 webrtc::PeerConnectionInterface::IceConnectionState new_state) { 1170 webrtc::PeerConnectionInterface::IceConnectionState new_state) {
888 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnIceConnectionChange"); 1171 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnIceConnectionChange");
1172 DCHECK(thread_checker_.CalledOnValidThread());
889 if (new_state == webrtc::PeerConnectionInterface::kIceConnectionChecking) { 1173 if (new_state == webrtc::PeerConnectionInterface::kIceConnectionChecking) {
890 ice_connection_checking_start_ = base::TimeTicks::Now(); 1174 ice_connection_checking_start_ = base::TimeTicks::Now();
891 } else if (new_state == 1175 } else if (new_state ==
892 webrtc::PeerConnectionInterface::kIceConnectionConnected) { 1176 webrtc::PeerConnectionInterface::kIceConnectionConnected) {
893 // If the state becomes connected, send the time needed for PC to become 1177 // If the state becomes connected, send the time needed for PC to become
894 // connected from checking to UMA. UMA data will help to know how much 1178 // connected from checking to UMA. UMA data will help to know how much
895 // time needed for PC to connect with remote peer. 1179 // time needed for PC to connect with remote peer.
896 UMA_HISTOGRAM_MEDIUM_TIMES( 1180 UMA_HISTOGRAM_MEDIUM_TIMES(
897 "WebRTC.PeerConnection.TimeToConnect", 1181 "WebRTC.PeerConnection.TimeToConnect",
898 base::TimeTicks::Now() - ice_connection_checking_start_); 1182 base::TimeTicks::Now() - ice_connection_checking_start_);
899 } 1183 }
900 1184
901 track_metrics_.IceConnectionChange(new_state); 1185 track_metrics_.IceConnectionChange(new_state);
902 blink::WebRTCPeerConnectionHandlerClient::ICEConnectionState state = 1186 blink::WebRTCPeerConnectionHandlerClient::ICEConnectionState state =
903 GetWebKitIceConnectionState(new_state); 1187 GetWebKitIceConnectionState(new_state);
904 if (peer_connection_tracker_) 1188 if (peer_connection_tracker_)
905 peer_connection_tracker_->TrackIceConnectionStateChange(this, state); 1189 peer_connection_tracker_->TrackIceConnectionStateChange(this, state);
906 client_->didChangeICEConnectionState(state); 1190 if(client_)
1191 client_->didChangeICEConnectionState(state);
907 } 1192 }
908 1193
909 // Called any time the IceGatheringState changes 1194 // Called any time the IceGatheringState changes
910 void RTCPeerConnectionHandler::OnIceGatheringChange( 1195 void RTCPeerConnectionHandler::OnIceGatheringChange(
911 webrtc::PeerConnectionInterface::IceGatheringState new_state) { 1196 webrtc::PeerConnectionInterface::IceGatheringState new_state) {
1197 DCHECK(thread_checker_.CalledOnValidThread());
912 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnIceGatheringChange"); 1198 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnIceGatheringChange");
1199
913 if (new_state == webrtc::PeerConnectionInterface::kIceGatheringComplete) { 1200 if (new_state == webrtc::PeerConnectionInterface::kIceGatheringComplete) {
914 // If ICE gathering is completed, generate a NULL ICE candidate, 1201 // If ICE gathering is completed, generate a NULL ICE candidate,
915 // to signal end of candidates. 1202 // to signal end of candidates.
916 blink::WebRTCICECandidate null_candidate; 1203 if (client_) {
917 client_->didGenerateICECandidate(null_candidate); 1204 blink::WebRTCICECandidate null_candidate;
1205 client_->didGenerateICECandidate(null_candidate);
1206 }
918 1207
919 UMA_HISTOGRAM_COUNTS_100("WebRTC.PeerConnection.IPv4LocalCandidates", 1208 UMA_HISTOGRAM_COUNTS_100("WebRTC.PeerConnection.IPv4LocalCandidates",
920 num_local_candidates_ipv4_); 1209 num_local_candidates_ipv4_);
921 1210
922 UMA_HISTOGRAM_COUNTS_100("WebRTC.PeerConnection.IPv6LocalCandidates", 1211 UMA_HISTOGRAM_COUNTS_100("WebRTC.PeerConnection.IPv6LocalCandidates",
923 num_local_candidates_ipv6_); 1212 num_local_candidates_ipv6_);
924 } else if (new_state == 1213 } else if (new_state ==
925 webrtc::PeerConnectionInterface::kIceGatheringGathering) { 1214 webrtc::PeerConnectionInterface::kIceGatheringGathering) {
926 // ICE restarts will change gathering state back to "gathering", 1215 // ICE restarts will change gathering state back to "gathering",
927 // reset the counter. 1216 // reset the counter.
928 num_local_candidates_ipv6_ = 0; 1217 num_local_candidates_ipv6_ = 0;
929 num_local_candidates_ipv4_ = 0; 1218 num_local_candidates_ipv4_ = 0;
930 } 1219 }
931 1220
932 blink::WebRTCPeerConnectionHandlerClient::ICEGatheringState state = 1221 blink::WebRTCPeerConnectionHandlerClient::ICEGatheringState state =
933 GetWebKitIceGatheringState(new_state); 1222 GetWebKitIceGatheringState(new_state);
934 if (peer_connection_tracker_) 1223 if (peer_connection_tracker_)
935 peer_connection_tracker_->TrackIceGatheringStateChange(this, state); 1224 peer_connection_tracker_->TrackIceGatheringStateChange(this, state);
936 client_->didChangeICEGatheringState(state); 1225 if (client_)
1226 client_->didChangeICEGatheringState(state);
1227 }
1228
1229 void RTCPeerConnectionHandler::OnRenegotiationNeeded() {
1230 DCHECK(thread_checker_.CalledOnValidThread());
1231 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnRenegotiationNeeded");
1232 if (peer_connection_tracker_)
1233 peer_connection_tracker_->TrackOnRenegotiationNeeded(this);
1234 if (client_)
1235 client_->negotiationNeeded();
1236 }
1237
1238 PeerConnectionTracker* RTCPeerConnectionHandler::peer_connection_tracker() {
1239 DCHECK(thread_checker_.CalledOnValidThread());
1240 return peer_connection_tracker_;
937 } 1241 }
938 1242
939 void RTCPeerConnectionHandler::OnAddStream( 1243 void RTCPeerConnectionHandler::OnAddStream(
940 webrtc::MediaStreamInterface* stream_interface) { 1244 scoped_ptr<RemoteMediaStreamImpl> stream) {
941 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnAddStream"); 1245 DCHECK(thread_checker_.CalledOnValidThread());
942 DCHECK(stream_interface); 1246 DCHECK(remote_streams_.find(stream->webrtc_stream().get()) ==
943 DCHECK(remote_streams_.find(stream_interface) == remote_streams_.end()); 1247 remote_streams_.end());
1248 DCHECK(stream->webkit_stream().extraData()) << "Initialization not done";
1249 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnAddStreamImpl");
944 1250
945 RemoteMediaStreamImpl* remote_stream = 1251 // Ownership is with remote_streams_ now.
946 new RemoteMediaStreamImpl(stream_interface); 1252 RemoteMediaStreamImpl* s = stream.release();
947 remote_streams_.insert( 1253 remote_streams_.insert(
948 std::pair<webrtc::MediaStreamInterface*, RemoteMediaStreamImpl*> ( 1254 std::pair<webrtc::MediaStreamInterface*, RemoteMediaStreamImpl*> (
949 stream_interface, remote_stream)); 1255 s->webrtc_stream().get(), s));
950 1256
951 if (peer_connection_tracker_) 1257 if (peer_connection_tracker_) {
952 peer_connection_tracker_->TrackAddStream( 1258 peer_connection_tracker_->TrackAddStream(
953 this, remote_stream->webkit_stream(), 1259 this, s->webkit_stream(), PeerConnectionTracker::SOURCE_REMOTE);
954 PeerConnectionTracker::SOURCE_REMOTE); 1260 }
955 1261
956 PerSessionWebRTCAPIMetrics::GetInstance()->IncrementStreamCounter(); 1262 PerSessionWebRTCAPIMetrics::GetInstance()->IncrementStreamCounter();
957 1263
958 track_metrics_.AddStream(MediaStreamTrackMetrics::RECEIVED_STREAM, 1264 track_metrics_.AddStream(MediaStreamTrackMetrics::RECEIVED_STREAM,
959 stream_interface); 1265 s->webrtc_stream().get());
960 1266 if (client_)
961 client_->didAddRemoteStream(remote_stream->webkit_stream()); 1267 client_->didAddRemoteStream(s->webkit_stream());
962 } 1268 }
963 1269
964 void RTCPeerConnectionHandler::OnRemoveStream( 1270 void RTCPeerConnectionHandler::OnRemoveStream(
965 webrtc::MediaStreamInterface* stream_interface) { 1271 const scoped_refptr<webrtc::MediaStreamInterface>& stream) {
966 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnRemoveStream"); 1272 DCHECK(thread_checker_.CalledOnValidThread());
967 DCHECK(stream_interface); 1273 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnRemoveStreamImpl");
968 RemoteStreamMap::iterator it = remote_streams_.find(stream_interface); 1274 RemoteStreamMap::iterator it = remote_streams_.find(stream.get());
969 if (it == remote_streams_.end()) { 1275 if (it == remote_streams_.end()) {
970 NOTREACHED() << "Stream not found"; 1276 NOTREACHED() << "Stream not found";
971 return; 1277 return;
972 } 1278 }
973 1279
974 track_metrics_.RemoveStream(MediaStreamTrackMetrics::RECEIVED_STREAM, 1280 track_metrics_.RemoveStream(MediaStreamTrackMetrics::RECEIVED_STREAM,
975 stream_interface); 1281 stream.get());
976 PerSessionWebRTCAPIMetrics::GetInstance()->DecrementStreamCounter(); 1282 PerSessionWebRTCAPIMetrics::GetInstance()->DecrementStreamCounter();
977 1283
978 scoped_ptr<RemoteMediaStreamImpl> remote_stream(it->second); 1284 scoped_ptr<RemoteMediaStreamImpl> remote_stream(it->second);
979 const blink::WebMediaStream& webkit_stream = remote_stream->webkit_stream(); 1285 const blink::WebMediaStream& webkit_stream = remote_stream->webkit_stream();
980 DCHECK(!webkit_stream.isNull()); 1286 DCHECK(!webkit_stream.isNull());
981 remote_streams_.erase(it); 1287 remote_streams_.erase(it);
982 1288
983 if (peer_connection_tracker_) 1289 if (peer_connection_tracker_) {
984 peer_connection_tracker_->TrackRemoveStream( 1290 peer_connection_tracker_->TrackRemoveStream(
985 this, webkit_stream, PeerConnectionTracker::SOURCE_REMOTE); 1291 this, webkit_stream, PeerConnectionTracker::SOURCE_REMOTE);
1292 }
986 1293
987 client_->didRemoveRemoteStream(webkit_stream); 1294 if (client_)
1295 client_->didRemoveRemoteStream(webkit_stream);
1296 }
1297
1298 void RTCPeerConnectionHandler::OnDataChannel(
1299 scoped_ptr<RtcDataChannelHandler> handler) {
1300 DCHECK(thread_checker_.CalledOnValidThread());
1301 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnDataChannelImpl");
1302
1303 if (peer_connection_tracker_) {
1304 peer_connection_tracker_->TrackCreateDataChannel(
1305 this, handler->channel().get(), PeerConnectionTracker::SOURCE_REMOTE);
1306 }
1307
1308 if (client_)
1309 client_->didAddRemoteDataChannel(handler.release());
988 } 1310 }
989 1311
990 void RTCPeerConnectionHandler::OnIceCandidate( 1312 void RTCPeerConnectionHandler::OnIceCandidate(
991 const webrtc::IceCandidateInterface* candidate) { 1313 const std::string& sdp, const std::string& sdp_mid, int sdp_mline_index,
992 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnIceCandidate"); 1314 int component, int address_family) {
993 DCHECK(candidate); 1315 DCHECK(thread_checker_.CalledOnValidThread());
994 std::string sdp; 1316 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnIceCandidateImpl");
995 if (!candidate->ToString(&sdp)) {
996 NOTREACHED() << "OnIceCandidate: Could not get SDP string.";
997 return;
998 }
999 blink::WebRTCICECandidate web_candidate; 1317 blink::WebRTCICECandidate web_candidate;
1000 web_candidate.initialize(base::UTF8ToUTF16(sdp), 1318 web_candidate.initialize(base::UTF8ToUTF16(sdp),
1001 base::UTF8ToUTF16(candidate->sdp_mid()), 1319 base::UTF8ToUTF16(sdp_mid),
1002 candidate->sdp_mline_index()); 1320 sdp_mline_index);
1003 if (peer_connection_tracker_) 1321 if (peer_connection_tracker_) {
1004 peer_connection_tracker_->TrackAddIceCandidate( 1322 peer_connection_tracker_->TrackAddIceCandidate(
1005 this, web_candidate, PeerConnectionTracker::SOURCE_LOCAL, true); 1323 this, web_candidate, PeerConnectionTracker::SOURCE_LOCAL, true);
1324 }
1006 1325
1007 // Only the first m line's first component is tracked to avoid 1326 // Only the first m line's first component is tracked to avoid
1008 // miscounting when doing BUNDLE or rtcp mux. 1327 // miscounting when doing BUNDLE or rtcp mux.
1009 if (candidate->sdp_mline_index() == 0 && 1328 if (sdp_mline_index == 0 && component == 1) {
1010 candidate->candidate().component() == 1) { 1329 if (address_family == AF_INET) {
1011 if (candidate->candidate().address().family() == AF_INET) { 1330 ++num_local_candidates_ipv4_;
1012 num_local_candidates_ipv4_++; 1331 } else if (address_family == AF_INET6) {
1013 } else if (candidate->candidate().address().family() == AF_INET6) { 1332 ++num_local_candidates_ipv6_;
1014 num_local_candidates_ipv6_++;
1015 } else { 1333 } else {
1016 NOTREACHED(); 1334 NOTREACHED();
1017 } 1335 }
1018 } 1336 }
1019 client_->didGenerateICECandidate(web_candidate); 1337 if (client_)
1020 } 1338 client_->didGenerateICECandidate(web_candidate);
1021
1022 void RTCPeerConnectionHandler::OnDataChannel(
1023 webrtc::DataChannelInterface* data_channel) {
1024 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnDataChannel");
1025 if (peer_connection_tracker_)
1026 peer_connection_tracker_->TrackCreateDataChannel(
1027 this, data_channel, PeerConnectionTracker::SOURCE_REMOTE);
1028
1029 DVLOG(1) << "RTCPeerConnectionHandler::OnDataChannel "
1030 << data_channel->label();
1031 client_->didAddRemoteDataChannel(new RtcDataChannelHandler(
1032 base::ThreadTaskRunnerHandle::Get(), data_channel));
1033 }
1034
1035 void RTCPeerConnectionHandler::OnRenegotiationNeeded() {
1036 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnRenegotiationNeeded");
1037 if (peer_connection_tracker_)
1038 peer_connection_tracker_->TrackOnRenegotiationNeeded(this);
1039 client_->negotiationNeeded();
1040 }
1041
1042 PeerConnectionTracker* RTCPeerConnectionHandler::peer_connection_tracker() {
1043 return peer_connection_tracker_;
1044 } 1339 }
1045 1340
1046 webrtc::SessionDescriptionInterface* 1341 webrtc::SessionDescriptionInterface*
1047 RTCPeerConnectionHandler::CreateNativeSessionDescription( 1342 RTCPeerConnectionHandler::CreateNativeSessionDescription(
1048 const blink::WebRTCSessionDescription& description, 1343 const std::string& sdp, const std::string& type,
1049 webrtc::SdpParseError* error) { 1344 webrtc::SdpParseError* error) {
1050 std::string sdp = base::UTF16ToUTF8(description.sdp());
1051 std::string type = base::UTF16ToUTF8(description.type());
1052 webrtc::SessionDescriptionInterface* native_desc = 1345 webrtc::SessionDescriptionInterface* native_desc =
1053 dependency_factory_->CreateSessionDescription(type, sdp, error); 1346 dependency_factory_->CreateSessionDescription(type, sdp, error);
1054 1347
1055 LOG_IF(ERROR, !native_desc) << "Failed to create native session description." 1348 LOG_IF(ERROR, !native_desc) << "Failed to create native session description."
1056 << " Type: " << type << " SDP: " << sdp; 1349 << " Type: " << type << " SDP: " << sdp;
1057 1350
1058 return native_desc; 1351 return native_desc;
1059 } 1352 }
1060 1353
1061 } // namespace content 1354 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698