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

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: rebase 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(
perkj_chrome 2014/10/31 08:37:25 This could also easily be avoided if this was rtc:
tommi (sloooow) - chröme 2014/10/31 10:06:33 It is, but it's considerably less than what we hav
perkj_chrome 2014/10/31 10:24:26 Put a scoped_ptr still make sense right if you loo
tommi (sloooow) - chröme 2014/10/31 13:20:41 Done.
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) {
397 g_peer_connection_handlers.Get().insert(this); 623 g_peer_connection_handlers.Get().insert(this);
398 } 624 }
399 625
400 RTCPeerConnectionHandler::~RTCPeerConnectionHandler() { 626 RTCPeerConnectionHandler::~RTCPeerConnectionHandler() {
627 DCHECK(thread_checker_.CalledOnValidThread());
401 g_peer_connection_handlers.Get().erase(this); 628 g_peer_connection_handlers.Get().erase(this);
402 if (peer_connection_tracker_) 629 if (peer_connection_tracker_)
403 peer_connection_tracker_->UnregisterPeerConnection(this); 630 peer_connection_tracker_->UnregisterPeerConnection(this);
404 STLDeleteValues(&remote_streams_); 631 STLDeleteValues(&remote_streams_);
405 632
406 UMA_HISTOGRAM_COUNTS_10000( 633 UMA_HISTOGRAM_COUNTS_10000(
407 "WebRTC.NumDataChannelsPerPeerConnection", num_data_channels_created_); 634 "WebRTC.NumDataChannelsPerPeerConnection", num_data_channels_created_);
408 } 635 }
409 636
410 // static 637 // static
411 void RTCPeerConnectionHandler::DestructAllHandlers() { 638 void RTCPeerConnectionHandler::DestructAllHandlers() {
412 std::set<RTCPeerConnectionHandler*> handlers( 639 std::set<RTCPeerConnectionHandler*> handlers(
413 g_peer_connection_handlers.Get().begin(), 640 g_peer_connection_handlers.Get().begin(),
414 g_peer_connection_handlers.Get().end()); 641 g_peer_connection_handlers.Get().end());
415 for (std::set<RTCPeerConnectionHandler*>::iterator handler = handlers.begin(); 642 for (auto handler : handlers) {
416 handler != handlers.end(); 643 if (handler->client_)
417 ++handler) { 644 handler->client_->releasePeerConnectionHandler();
418 (*handler)->client_->releasePeerConnectionHandler();
419 } 645 }
420 } 646 }
421 647
648 // static
422 void RTCPeerConnectionHandler::ConvertOfferOptionsToConstraints( 649 void RTCPeerConnectionHandler::ConvertOfferOptionsToConstraints(
423 const blink::WebRTCOfferOptions& options, 650 const blink::WebRTCOfferOptions& options,
424 RTCMediaConstraints* output) { 651 RTCMediaConstraints* output) {
425 output->AddMandatory( 652 output->AddMandatory(
426 webrtc::MediaConstraintsInterface::kOfferToReceiveAudio, 653 webrtc::MediaConstraintsInterface::kOfferToReceiveAudio,
427 options.offerToReceiveAudio() > 0 ? "true" : "false", 654 options.offerToReceiveAudio() > 0 ? "true" : "false",
428 true); 655 true);
429 656
430 output->AddMandatory( 657 output->AddMandatory(
431 webrtc::MediaConstraintsInterface::kOfferToReceiveVideo, 658 webrtc::MediaConstraintsInterface::kOfferToReceiveVideo,
432 options.offerToReceiveVideo() > 0 ? "true" : "false", 659 options.offerToReceiveVideo() > 0 ? "true" : "false",
433 true); 660 true);
434 661
435 if (!options.voiceActivityDetection()) { 662 if (!options.voiceActivityDetection()) {
436 output->AddMandatory( 663 output->AddMandatory(
437 webrtc::MediaConstraintsInterface::kVoiceActivityDetection, 664 webrtc::MediaConstraintsInterface::kVoiceActivityDetection,
438 "false", 665 "false",
439 true); 666 true);
440 } 667 }
441 668
442 if (options.iceRestart()) { 669 if (options.iceRestart()) {
443 output->AddMandatory( 670 output->AddMandatory(
444 webrtc::MediaConstraintsInterface::kIceRestart, "true", true); 671 webrtc::MediaConstraintsInterface::kIceRestart, "true", true);
445 } 672 }
446 } 673 }
447 674
448 void RTCPeerConnectionHandler::associateWithFrame(blink::WebFrame* frame) { 675 void RTCPeerConnectionHandler::associateWithFrame(blink::WebFrame* frame) {
676 DCHECK(thread_checker_.CalledOnValidThread());
449 DCHECK(frame); 677 DCHECK(frame);
450 frame_ = frame; 678 frame_ = frame;
451 } 679 }
452 680
453 bool RTCPeerConnectionHandler::initialize( 681 bool RTCPeerConnectionHandler::initialize(
454 const blink::WebRTCConfiguration& server_configuration, 682 const blink::WebRTCConfiguration& server_configuration,
455 const blink::WebMediaConstraints& options) { 683 const blink::WebMediaConstraints& options) {
684 DCHECK(thread_checker_.CalledOnValidThread());
456 DCHECK(frame_); 685 DCHECK(frame_);
457 686
458 peer_connection_tracker_ = 687 peer_connection_tracker_ =
459 RenderThreadImpl::current()->peer_connection_tracker(); 688 RenderThreadImpl::current()->peer_connection_tracker();
460 689
461 webrtc::PeerConnectionInterface::RTCConfiguration config; 690 webrtc::PeerConnectionInterface::RTCConfiguration config;
462 GetNativeRtcConfiguration(server_configuration, &config); 691 GetNativeRtcConfiguration(server_configuration, &config);
463 692
464 RTCMediaConstraints constraints(options); 693 RTCMediaConstraints constraints(options);
465 694
466 native_peer_connection_ = 695 peer_connection_observer_ = new Observer(weak_factory_.GetWeakPtr());
467 dependency_factory_->CreatePeerConnection( 696 native_peer_connection_ = dependency_factory_->CreatePeerConnection(
468 config, &constraints, frame_, this); 697 config, &constraints, frame_, peer_connection_observer_.get());
469 698
470 if (!native_peer_connection_.get()) { 699 if (!native_peer_connection_.get()) {
471 LOG(ERROR) << "Failed to initialize native PeerConnection."; 700 LOG(ERROR) << "Failed to initialize native PeerConnection.";
472 return false; 701 return false;
473 } 702 }
474 if (peer_connection_tracker_) 703
704 if (peer_connection_tracker_) {
475 peer_connection_tracker_->RegisterPeerConnection( 705 peer_connection_tracker_->RegisterPeerConnection(
476 this, config, constraints, frame_); 706 this, config, constraints, frame_);
707 }
477 708
478 uma_observer_ = new rtc::RefCountedObject<PeerConnectionUMAObserver>(); 709 uma_observer_ = new rtc::RefCountedObject<PeerConnectionUMAObserver>();
479 native_peer_connection_->RegisterUMAObserver(uma_observer_.get()); 710 native_peer_connection_->RegisterUMAObserver(uma_observer_.get());
480 return true; 711 return true;
481 } 712 }
482 713
483 bool RTCPeerConnectionHandler::InitializeForTest( 714 bool RTCPeerConnectionHandler::InitializeForTest(
484 const blink::WebRTCConfiguration& server_configuration, 715 const blink::WebRTCConfiguration& server_configuration,
485 const blink::WebMediaConstraints& options, 716 const blink::WebMediaConstraints& options,
486 PeerConnectionTracker* peer_connection_tracker) { 717 PeerConnectionTracker* peer_connection_tracker) {
718 DCHECK(thread_checker_.CalledOnValidThread());
487 webrtc::PeerConnectionInterface::RTCConfiguration config; 719 webrtc::PeerConnectionInterface::RTCConfiguration config;
488 GetNativeRtcConfiguration(server_configuration, &config); 720 GetNativeRtcConfiguration(server_configuration, &config);
489 721
722 peer_connection_observer_ = new Observer(weak_factory_.GetWeakPtr());
490 RTCMediaConstraints constraints(options); 723 RTCMediaConstraints constraints(options);
491 native_peer_connection_ = 724 native_peer_connection_ = dependency_factory_->CreatePeerConnection(
492 dependency_factory_->CreatePeerConnection( 725 config, &constraints, NULL, peer_connection_observer_.get());
493 config, &constraints, NULL, this);
494 if (!native_peer_connection_.get()) { 726 if (!native_peer_connection_.get()) {
495 LOG(ERROR) << "Failed to initialize native PeerConnection."; 727 LOG(ERROR) << "Failed to initialize native PeerConnection.";
496 return false; 728 return false;
497 } 729 }
498 peer_connection_tracker_ = peer_connection_tracker; 730 peer_connection_tracker_ = peer_connection_tracker;
499 return true; 731 return true;
500 } 732 }
501 733
502 void RTCPeerConnectionHandler::createOffer( 734 void RTCPeerConnectionHandler::createOffer(
503 const blink::WebRTCSessionDescriptionRequest& request, 735 const blink::WebRTCSessionDescriptionRequest& request,
504 const blink::WebMediaConstraints& options) { 736 const blink::WebMediaConstraints& options) {
737 DCHECK(thread_checker_.CalledOnValidThread());
505 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createOffer"); 738 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createOffer");
739
506 scoped_refptr<CreateSessionDescriptionRequest> description_request( 740 scoped_refptr<CreateSessionDescriptionRequest> description_request(
507 new rtc::RefCountedObject<CreateSessionDescriptionRequest>( 741 new rtc::RefCountedObject<CreateSessionDescriptionRequest>(
508 request, this, PeerConnectionTracker::ACTION_CREATE_OFFER)); 742 base::ThreadTaskRunnerHandle::Get(), request, this,
743 PeerConnectionTracker::ACTION_CREATE_OFFER));
744
509 RTCMediaConstraints constraints(options); 745 RTCMediaConstraints constraints(options);
510 native_peer_connection_->CreateOffer(description_request.get(), &constraints); 746 native_peer_connection_->CreateOffer(description_request.get(), &constraints);
511 747
512 if (peer_connection_tracker_) 748 if (peer_connection_tracker_)
513 peer_connection_tracker_->TrackCreateOffer(this, constraints); 749 peer_connection_tracker_->TrackCreateOffer(this, constraints);
514 } 750 }
515 751
516 void RTCPeerConnectionHandler::createOffer( 752 void RTCPeerConnectionHandler::createOffer(
517 const blink::WebRTCSessionDescriptionRequest& request, 753 const blink::WebRTCSessionDescriptionRequest& request,
518 const blink::WebRTCOfferOptions& options) { 754 const blink::WebRTCOfferOptions& options) {
755 DCHECK(thread_checker_.CalledOnValidThread());
519 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createOffer"); 756 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createOffer");
757
520 scoped_refptr<CreateSessionDescriptionRequest> description_request( 758 scoped_refptr<CreateSessionDescriptionRequest> description_request(
521 new rtc::RefCountedObject<CreateSessionDescriptionRequest>( 759 new rtc::RefCountedObject<CreateSessionDescriptionRequest>(
522 request, this, PeerConnectionTracker::ACTION_CREATE_OFFER)); 760 base::ThreadTaskRunnerHandle::Get(), request, this,
761 PeerConnectionTracker::ACTION_CREATE_OFFER));
523 762
524 RTCMediaConstraints constraints; 763 RTCMediaConstraints constraints;
525 ConvertOfferOptionsToConstraints(options, &constraints); 764 ConvertOfferOptionsToConstraints(options, &constraints);
526 native_peer_connection_->CreateOffer(description_request.get(), &constraints); 765 native_peer_connection_->CreateOffer(description_request.get(), &constraints);
527 766
528 if (peer_connection_tracker_) 767 if (peer_connection_tracker_)
529 peer_connection_tracker_->TrackCreateOffer(this, constraints); 768 peer_connection_tracker_->TrackCreateOffer(this, constraints);
530 } 769 }
531 770
532 void RTCPeerConnectionHandler::createAnswer( 771 void RTCPeerConnectionHandler::createAnswer(
533 const blink::WebRTCSessionDescriptionRequest& request, 772 const blink::WebRTCSessionDescriptionRequest& request,
534 const blink::WebMediaConstraints& options) { 773 const blink::WebMediaConstraints& options) {
774 DCHECK(thread_checker_.CalledOnValidThread());
535 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createAnswer"); 775 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createAnswer");
536 scoped_refptr<CreateSessionDescriptionRequest> description_request( 776 scoped_refptr<CreateSessionDescriptionRequest> description_request(
537 new rtc::RefCountedObject<CreateSessionDescriptionRequest>( 777 new rtc::RefCountedObject<CreateSessionDescriptionRequest>(
538 request, this, PeerConnectionTracker::ACTION_CREATE_ANSWER)); 778 base::ThreadTaskRunnerHandle::Get(), request, this,
779 PeerConnectionTracker::ACTION_CREATE_ANSWER));
539 RTCMediaConstraints constraints(options); 780 RTCMediaConstraints constraints(options);
540 native_peer_connection_->CreateAnswer(description_request.get(), 781 native_peer_connection_->CreateAnswer(description_request.get(),
541 &constraints); 782 &constraints);
542 783
543 if (peer_connection_tracker_) 784 if (peer_connection_tracker_)
544 peer_connection_tracker_->TrackCreateAnswer(this, constraints); 785 peer_connection_tracker_->TrackCreateAnswer(this, constraints);
545 } 786 }
546 787
547 void RTCPeerConnectionHandler::setLocalDescription( 788 void RTCPeerConnectionHandler::setLocalDescription(
548 const blink::WebRTCVoidRequest& request, 789 const blink::WebRTCVoidRequest& request,
549 const blink::WebRTCSessionDescription& description) { 790 const blink::WebRTCSessionDescription& description) {
791 DCHECK(thread_checker_.CalledOnValidThread());
550 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::setLocalDescription"); 792 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::setLocalDescription");
793
794 // TODO(tommi): Make this (and other methods such as setRemoteDescription),
795 // run on the signaling thread.
796
551 webrtc::SdpParseError error; 797 webrtc::SdpParseError error;
552 webrtc::SessionDescriptionInterface* native_desc = 798 webrtc::SessionDescriptionInterface* native_desc =
553 CreateNativeSessionDescription(description, &error); 799 CreateNativeSessionDescription(description, &error);
554 if (!native_desc) { 800 if (!native_desc) {
555 std::string reason_str = "Failed to parse SessionDescription. "; 801 std::string reason_str = "Failed to parse SessionDescription. ";
556 reason_str.append(error.line); 802 reason_str.append(error.line);
557 reason_str.append(" "); 803 reason_str.append(" ");
558 reason_str.append(error.description); 804 reason_str.append(error.description);
559 LOG(ERROR) << reason_str; 805 LOG(ERROR) << reason_str;
560 request.requestFailed(blink::WebString::fromUTF8(reason_str)); 806 request.requestFailed(blink::WebString::fromUTF8(reason_str));
561 return; 807 return;
562 } 808 }
563 if (peer_connection_tracker_) 809
810 if (peer_connection_tracker_) {
564 peer_connection_tracker_->TrackSetSessionDescription( 811 peer_connection_tracker_->TrackSetSessionDescription(
565 this, description, PeerConnectionTracker::SOURCE_LOCAL); 812 this, description, PeerConnectionTracker::SOURCE_LOCAL);
813 }
566 814
567 scoped_refptr<SetSessionDescriptionRequest> set_request( 815 scoped_refptr<SetSessionDescriptionRequest> set_request(
568 new rtc::RefCountedObject<SetSessionDescriptionRequest>( 816 new rtc::RefCountedObject<SetSessionDescriptionRequest>(
569 request, this, PeerConnectionTracker::ACTION_SET_LOCAL_DESCRIPTION)); 817 base::ThreadTaskRunnerHandle::Get(), request, this,
818 PeerConnectionTracker::ACTION_SET_LOCAL_DESCRIPTION));
570 native_peer_connection_->SetLocalDescription(set_request.get(), native_desc); 819 native_peer_connection_->SetLocalDescription(set_request.get(), native_desc);
571 } 820 }
572 821
573 void RTCPeerConnectionHandler::setRemoteDescription( 822 void RTCPeerConnectionHandler::setRemoteDescription(
574 const blink::WebRTCVoidRequest& request, 823 const blink::WebRTCVoidRequest& request,
575 const blink::WebRTCSessionDescription& description) { 824 const blink::WebRTCSessionDescription& description) {
825 DCHECK(thread_checker_.CalledOnValidThread());
576 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::setRemoteDescription"); 826 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::setRemoteDescription");
577 webrtc::SdpParseError error; 827 webrtc::SdpParseError error;
578 webrtc::SessionDescriptionInterface* native_desc = 828 webrtc::SessionDescriptionInterface* native_desc =
579 CreateNativeSessionDescription(description, &error); 829 CreateNativeSessionDescription(description, &error);
580 if (!native_desc) { 830 if (!native_desc) {
581 std::string reason_str = "Failed to parse SessionDescription. "; 831 std::string reason_str = "Failed to parse SessionDescription. ";
582 reason_str.append(error.line); 832 reason_str.append(error.line);
583 reason_str.append(" "); 833 reason_str.append(" ");
584 reason_str.append(error.description); 834 reason_str.append(error.description);
585 LOG(ERROR) << reason_str; 835 LOG(ERROR) << reason_str;
586 request.requestFailed(blink::WebString::fromUTF8(reason_str)); 836 request.requestFailed(blink::WebString::fromUTF8(reason_str));
587 return; 837 return;
588 } 838 }
589 if (peer_connection_tracker_) 839
840 if (peer_connection_tracker_) {
590 peer_connection_tracker_->TrackSetSessionDescription( 841 peer_connection_tracker_->TrackSetSessionDescription(
591 this, description, PeerConnectionTracker::SOURCE_REMOTE); 842 this, description, PeerConnectionTracker::SOURCE_REMOTE);
843 }
592 844
593 scoped_refptr<SetSessionDescriptionRequest> set_request( 845 scoped_refptr<SetSessionDescriptionRequest> set_request(
594 new rtc::RefCountedObject<SetSessionDescriptionRequest>( 846 new rtc::RefCountedObject<SetSessionDescriptionRequest>(
595 request, this, PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION)); 847 base::ThreadTaskRunnerHandle::Get(), request, this,
848 PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION));
849 // TODO(tommi): Make this (and other methods such as setLocalDescription),
850 // run on the signaling thread.
596 native_peer_connection_->SetRemoteDescription(set_request.get(), native_desc); 851 native_peer_connection_->SetRemoteDescription(set_request.get(), native_desc);
597 } 852 }
598 853
599 blink::WebRTCSessionDescription 854 blink::WebRTCSessionDescription
600 RTCPeerConnectionHandler::localDescription() { 855 RTCPeerConnectionHandler::localDescription() {
856 DCHECK(thread_checker_.CalledOnValidThread());
601 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::localDescription"); 857 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::localDescription");
602 const webrtc::SessionDescriptionInterface* native_desc = 858 const webrtc::SessionDescriptionInterface* native_desc =
603 native_peer_connection_->local_description(); 859 native_peer_connection_->local_description();
604 blink::WebRTCSessionDescription description = 860 blink::WebRTCSessionDescription description =
605 CreateWebKitSessionDescription(native_desc); 861 CreateWebKitSessionDescription(native_desc);
606 return description; 862 return description;
607 } 863 }
608 864
609 blink::WebRTCSessionDescription 865 blink::WebRTCSessionDescription
610 RTCPeerConnectionHandler::remoteDescription() { 866 RTCPeerConnectionHandler::remoteDescription() {
867 DCHECK(thread_checker_.CalledOnValidThread());
611 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::remoteDescription"); 868 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::remoteDescription");
612 const webrtc::SessionDescriptionInterface* native_desc = 869 const webrtc::SessionDescriptionInterface* native_desc =
613 native_peer_connection_->remote_description(); 870 native_peer_connection_->remote_description();
614 blink::WebRTCSessionDescription description = 871 blink::WebRTCSessionDescription description =
615 CreateWebKitSessionDescription(native_desc); 872 CreateWebKitSessionDescription(native_desc);
616 return description; 873 return description;
617 } 874 }
618 875
619 bool RTCPeerConnectionHandler::updateICE( 876 bool RTCPeerConnectionHandler::updateICE(
620 const blink::WebRTCConfiguration& server_configuration, 877 const blink::WebRTCConfiguration& server_configuration,
621 const blink::WebMediaConstraints& options) { 878 const blink::WebMediaConstraints& options) {
879 DCHECK(thread_checker_.CalledOnValidThread());
622 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::updateICE"); 880 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::updateICE");
623 webrtc::PeerConnectionInterface::RTCConfiguration config; 881 webrtc::PeerConnectionInterface::RTCConfiguration config;
624 GetNativeRtcConfiguration(server_configuration, &config); 882 GetNativeRtcConfiguration(server_configuration, &config);
625 RTCMediaConstraints constraints(options); 883 RTCMediaConstraints constraints(options);
626 884
627 if (peer_connection_tracker_) 885 if (peer_connection_tracker_)
628 peer_connection_tracker_->TrackUpdateIce(this, config, constraints); 886 peer_connection_tracker_->TrackUpdateIce(this, config, constraints);
629 887
630 return native_peer_connection_->UpdateIce(config.servers, 888 return native_peer_connection_->UpdateIce(config.servers, &constraints);
631 &constraints);
632 } 889 }
633 890
634 bool RTCPeerConnectionHandler::addICECandidate( 891 bool RTCPeerConnectionHandler::addICECandidate(
635 const blink::WebRTCVoidRequest& request, 892 const blink::WebRTCVoidRequest& request,
636 const blink::WebRTCICECandidate& candidate) { 893 const blink::WebRTCICECandidate& candidate) {
894 DCHECK(thread_checker_.CalledOnValidThread());
637 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::addICECandidate"); 895 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::addICECandidate");
638 // Libjingle currently does not accept callbacks for addICECandidate. 896 // Libjingle currently does not accept callbacks for addICECandidate.
639 // For that reason we are going to call callbacks from here. 897 // For that reason we are going to call callbacks from here.
640 bool result = addICECandidate(candidate); 898 bool result = addICECandidate(candidate);
641 base::MessageLoop::current()->PostTask( 899 base::MessageLoop::current()->PostTask(
642 FROM_HERE, 900 FROM_HERE,
643 base::Bind(&RTCPeerConnectionHandler::OnaddICECandidateResult, 901 base::Bind(&RTCPeerConnectionHandler::OnaddICECandidateResult,
644 base::Unretained(this), request, result)); 902 weak_factory_.GetWeakPtr(), request, result));
645 // On failure callback will be triggered. 903 // On failure callback will be triggered.
646 return true; 904 return true;
647 } 905 }
648 906
649 bool RTCPeerConnectionHandler::addICECandidate( 907 bool RTCPeerConnectionHandler::addICECandidate(
650 const blink::WebRTCICECandidate& candidate) { 908 const blink::WebRTCICECandidate& candidate) {
909 DCHECK(thread_checker_.CalledOnValidThread());
651 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::addICECandidate"); 910 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::addICECandidate");
652 scoped_ptr<webrtc::IceCandidateInterface> native_candidate( 911 scoped_ptr<webrtc::IceCandidateInterface> native_candidate(
653 dependency_factory_->CreateIceCandidate( 912 dependency_factory_->CreateIceCandidate(
654 base::UTF16ToUTF8(candidate.sdpMid()), 913 base::UTF16ToUTF8(candidate.sdpMid()),
655 candidate.sdpMLineIndex(), 914 candidate.sdpMLineIndex(),
656 base::UTF16ToUTF8(candidate.candidate()))); 915 base::UTF16ToUTF8(candidate.candidate())));
657 bool return_value = false; 916 bool return_value = false;
658 917
659 if (native_candidate) { 918 if (native_candidate) {
660 return_value = 919 return_value =
661 native_peer_connection_->AddIceCandidate(native_candidate.get()); 920 native_peer_connection_->AddIceCandidate(native_candidate.get());
662 LOG_IF(ERROR, !return_value) << "Error processing ICE candidate."; 921 LOG_IF(ERROR, !return_value) << "Error processing ICE candidate.";
663 } else { 922 } else {
664 LOG(ERROR) << "Could not create native ICE candidate."; 923 LOG(ERROR) << "Could not create native ICE candidate.";
665 } 924 }
666 925
667 if (peer_connection_tracker_) { 926 if (peer_connection_tracker_) {
668 peer_connection_tracker_->TrackAddIceCandidate( 927 peer_connection_tracker_->TrackAddIceCandidate(
669 this, candidate, PeerConnectionTracker::SOURCE_REMOTE, return_value); 928 this, candidate, PeerConnectionTracker::SOURCE_REMOTE, return_value);
670 } 929 }
671 return return_value; 930 return return_value;
672 } 931 }
673 932
674 void RTCPeerConnectionHandler::OnaddICECandidateResult( 933 void RTCPeerConnectionHandler::OnaddICECandidateResult(
675 const blink::WebRTCVoidRequest& webkit_request, bool result) { 934 const blink::WebRTCVoidRequest& webkit_request, bool result) {
935 DCHECK(thread_checker_.CalledOnValidThread());
676 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnaddICECandidateResult"); 936 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnaddICECandidateResult");
677 if (!result) { 937 if (!result) {
678 // We don't have the actual error code from the libjingle, so for now 938 // We don't have the actual error code from the libjingle, so for now
679 // using a generic error string. 939 // using a generic error string.
680 return webkit_request.requestFailed( 940 return webkit_request.requestFailed(
681 base::UTF8ToUTF16("Error processing ICE candidate")); 941 base::UTF8ToUTF16("Error processing ICE candidate"));
682 } 942 }
683 943
684 return webkit_request.requestSucceeded(); 944 return webkit_request.requestSucceeded();
685 } 945 }
686 946
687 bool RTCPeerConnectionHandler::addStream( 947 bool RTCPeerConnectionHandler::addStream(
688 const blink::WebMediaStream& stream, 948 const blink::WebMediaStream& stream,
689 const blink::WebMediaConstraints& options) { 949 const blink::WebMediaConstraints& options) {
950 DCHECK(thread_checker_.CalledOnValidThread());
690 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::addStream"); 951 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::addStream");
691 for (ScopedVector<WebRtcMediaStreamAdapter>::iterator adapter_it = 952 for (ScopedVector<WebRtcMediaStreamAdapter>::iterator adapter_it =
692 local_streams_.begin(); adapter_it != local_streams_.end(); 953 local_streams_.begin(); adapter_it != local_streams_.end();
693 ++adapter_it) { 954 ++adapter_it) {
694 if ((*adapter_it)->IsEqual(stream)) { 955 if ((*adapter_it)->IsEqual(stream)) {
695 DVLOG(1) << "RTCPeerConnectionHandler::addStream called with the same " 956 DVLOG(1) << "RTCPeerConnectionHandler::addStream called with the same "
696 << "stream twice. id=" << stream.id().utf8(); 957 << "stream twice. id=" << stream.id().utf8();
697 return false; 958 return false;
698 } 959 }
699 } 960 }
700 961
701 if (peer_connection_tracker_) 962 if (peer_connection_tracker_) {
702 peer_connection_tracker_->TrackAddStream( 963 peer_connection_tracker_->TrackAddStream(
703 this, stream, PeerConnectionTracker::SOURCE_LOCAL); 964 this, stream, PeerConnectionTracker::SOURCE_LOCAL);
965 }
704 966
705 PerSessionWebRTCAPIMetrics::GetInstance()->IncrementStreamCounter(); 967 PerSessionWebRTCAPIMetrics::GetInstance()->IncrementStreamCounter();
706 968
707 WebRtcMediaStreamAdapter* adapter = 969 WebRtcMediaStreamAdapter* adapter =
708 new WebRtcMediaStreamAdapter(stream, dependency_factory_); 970 new WebRtcMediaStreamAdapter(stream, dependency_factory_);
709 local_streams_.push_back(adapter); 971 local_streams_.push_back(adapter);
710 972
711 webrtc::MediaStreamInterface* webrtc_stream = adapter->webrtc_media_stream(); 973 webrtc::MediaStreamInterface* webrtc_stream = adapter->webrtc_media_stream();
712 track_metrics_.AddStream(MediaStreamTrackMetrics::SENT_STREAM, 974 track_metrics_.AddStream(MediaStreamTrackMetrics::SENT_STREAM,
713 webrtc_stream); 975 webrtc_stream);
714 976
715 RTCMediaConstraints constraints(options); 977 RTCMediaConstraints constraints(options);
716 return native_peer_connection_->AddStream(webrtc_stream, &constraints); 978 return native_peer_connection_->AddStream(webrtc_stream, &constraints);
717 } 979 }
718 980
719 void RTCPeerConnectionHandler::removeStream( 981 void RTCPeerConnectionHandler::removeStream(
720 const blink::WebMediaStream& stream) { 982 const blink::WebMediaStream& stream) {
983 DCHECK(thread_checker_.CalledOnValidThread());
721 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::removeStream"); 984 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::removeStream");
722 // Find the webrtc stream. 985 // Find the webrtc stream.
723 scoped_refptr<webrtc::MediaStreamInterface> webrtc_stream; 986 scoped_refptr<webrtc::MediaStreamInterface> webrtc_stream;
724 for (ScopedVector<WebRtcMediaStreamAdapter>::iterator adapter_it = 987 for (ScopedVector<WebRtcMediaStreamAdapter>::iterator adapter_it =
725 local_streams_.begin(); adapter_it != local_streams_.end(); 988 local_streams_.begin(); adapter_it != local_streams_.end();
726 ++adapter_it) { 989 ++adapter_it) {
727 if ((*adapter_it)->IsEqual(stream)) { 990 if ((*adapter_it)->IsEqual(stream)) {
728 webrtc_stream = (*adapter_it)->webrtc_media_stream(); 991 webrtc_stream = (*adapter_it)->webrtc_media_stream();
729 local_streams_.erase(adapter_it); 992 local_streams_.erase(adapter_it);
730 break; 993 break;
731 } 994 }
732 } 995 }
733 DCHECK(webrtc_stream.get()); 996 DCHECK(webrtc_stream.get());
734 native_peer_connection_->RemoveStream(webrtc_stream.get()); 997 native_peer_connection_->RemoveStream(webrtc_stream.get());
735 998
736 if (peer_connection_tracker_) 999 if (peer_connection_tracker_) {
737 peer_connection_tracker_->TrackRemoveStream( 1000 peer_connection_tracker_->TrackRemoveStream(
738 this, stream, PeerConnectionTracker::SOURCE_LOCAL); 1001 this, stream, PeerConnectionTracker::SOURCE_LOCAL);
1002 }
739 PerSessionWebRTCAPIMetrics::GetInstance()->DecrementStreamCounter(); 1003 PerSessionWebRTCAPIMetrics::GetInstance()->DecrementStreamCounter();
740 track_metrics_.RemoveStream(MediaStreamTrackMetrics::SENT_STREAM, 1004 track_metrics_.RemoveStream(MediaStreamTrackMetrics::SENT_STREAM,
741 webrtc_stream.get()); 1005 webrtc_stream.get());
742 } 1006 }
743 1007
744 void RTCPeerConnectionHandler::getStats( 1008 void RTCPeerConnectionHandler::getStats(
745 const blink::WebRTCStatsRequest& request) { 1009 const blink::WebRTCStatsRequest& request) {
1010 DCHECK(thread_checker_.CalledOnValidThread());
746 scoped_refptr<LocalRTCStatsRequest> inner_request( 1011 scoped_refptr<LocalRTCStatsRequest> inner_request(
747 new rtc::RefCountedObject<LocalRTCStatsRequest>(request)); 1012 new rtc::RefCountedObject<LocalRTCStatsRequest>(request));
748 getStats(inner_request.get()); 1013 getStats(inner_request);
749 } 1014 }
750 1015
751 void RTCPeerConnectionHandler::getStats(LocalRTCStatsRequest* request) { 1016 void RTCPeerConnectionHandler::getStats(
1017 const scoped_refptr<LocalRTCStatsRequest>& request) {
1018 DCHECK(thread_checker_.CalledOnValidThread());
1019 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::getStats");
1020
1021
752 rtc::scoped_refptr<webrtc::StatsObserver> observer( 1022 rtc::scoped_refptr<webrtc::StatsObserver> observer(
753 new rtc::RefCountedObject<StatsResponse>(request)); 1023 new rtc::RefCountedObject<StatsResponse>(request));
754 webrtc::MediaStreamTrackInterface* track = NULL; 1024
1025 std::string track_id;
1026 blink::WebMediaStreamSource::Type track_type =
1027 blink::WebMediaStreamSource::TypeAudio;
755 if (request->hasSelector()) { 1028 if (request->hasSelector()) {
756 blink::WebMediaStreamSource::Type type = 1029 track_type = request->component().source().type();
757 request->component().source().type(); 1030 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 } 1031 }
782 GetStats(observer, 1032
783 track, 1033 GetStats(observer, webrtc::PeerConnectionInterface::kStatsOutputLevelStandard,
784 webrtc::PeerConnectionInterface::kStatsOutputLevelStandard); 1034 track_id, track_type);
785 } 1035 }
786 1036
787 void RTCPeerConnectionHandler::GetStats( 1037 void RTCPeerConnectionHandler::GetStats(
perkj_chrome 2014/10/31 08:37:25 nit: Can this method be merged into getStats inste
tommi (sloooow) - chröme 2014/10/31 13:20:41 It can but currently the pc tracker depends on it.
788 webrtc::StatsObserver* observer, 1038 webrtc::StatsObserver* observer,
789 webrtc::MediaStreamTrackInterface* track, 1039 webrtc::PeerConnectionInterface::StatsOutputLevel level,
790 webrtc::PeerConnectionInterface::StatsOutputLevel level) { 1040 const std::string& track_id,
791 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::GetStats"); 1041 blink::WebMediaStreamSource::Type track_type) {
792 if (!native_peer_connection_->GetStats(observer, track, level)) { 1042 DCHECK(thread_checker_.CalledOnValidThread());
793 DVLOG(1) << "GetStats failed."; 1043 signaling_thread_->PostTask(FROM_HERE,
794 // TODO(hta): Consider how to get an error back. 1044 base::Bind(&GetStatsOnSignalingThread, native_peer_connection_, level,
795 observer->OnComplete(StatsReports()); 1045 make_scoped_refptr(observer), track_id, track_type));
796 return;
797 }
798 } 1046 }
799 1047
800 void RTCPeerConnectionHandler::CloseClientPeerConnection() { 1048 void RTCPeerConnectionHandler::CloseClientPeerConnection() {
801 client_->closePeerConnection(); 1049 DCHECK(thread_checker_.CalledOnValidThread());
1050 if (client_)
1051 client_->closePeerConnection();
802 } 1052 }
803 1053
804 blink::WebRTCDataChannelHandler* RTCPeerConnectionHandler::createDataChannel( 1054 blink::WebRTCDataChannelHandler* RTCPeerConnectionHandler::createDataChannel(
805 const blink::WebString& label, const blink::WebRTCDataChannelInit& init) { 1055 const blink::WebString& label, const blink::WebRTCDataChannelInit& init) {
1056 DCHECK(thread_checker_.CalledOnValidThread());
806 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createDataChannel"); 1057 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createDataChannel");
807 DVLOG(1) << "createDataChannel label " << base::UTF16ToUTF8(label); 1058 DVLOG(1) << "createDataChannel label " << base::UTF16ToUTF8(label);
808 1059
809 webrtc::DataChannelInit config; 1060 webrtc::DataChannelInit config;
810 // TODO(jiayl): remove the deprecated reliable field once Libjingle is updated 1061 // TODO(jiayl): remove the deprecated reliable field once Libjingle is updated
811 // to handle that. 1062 // to handle that.
812 config.reliable = false; 1063 config.reliable = false;
813 config.id = init.id; 1064 config.id = init.id;
814 config.ordered = init.ordered; 1065 config.ordered = init.ordered;
815 config.negotiated = init.negotiated; 1066 config.negotiated = init.negotiated;
816 config.maxRetransmits = init.maxRetransmits; 1067 config.maxRetransmits = init.maxRetransmits;
817 config.maxRetransmitTime = init.maxRetransmitTime; 1068 config.maxRetransmitTime = init.maxRetransmitTime;
818 config.protocol = base::UTF16ToUTF8(init.protocol); 1069 config.protocol = base::UTF16ToUTF8(init.protocol);
819 1070
820 rtc::scoped_refptr<webrtc::DataChannelInterface> webrtc_channel( 1071 rtc::scoped_refptr<webrtc::DataChannelInterface> webrtc_channel(
821 native_peer_connection_->CreateDataChannel(base::UTF16ToUTF8(label), 1072 native_peer_connection_->CreateDataChannel(base::UTF16ToUTF8(label),
822 &config)); 1073 &config));
823 if (!webrtc_channel) { 1074 if (!webrtc_channel) {
824 DLOG(ERROR) << "Could not create native data channel."; 1075 DLOG(ERROR) << "Could not create native data channel.";
825 return NULL; 1076 return NULL;
826 } 1077 }
827 if (peer_connection_tracker_) 1078 if (peer_connection_tracker_) {
828 peer_connection_tracker_->TrackCreateDataChannel( 1079 peer_connection_tracker_->TrackCreateDataChannel(
829 this, webrtc_channel.get(), PeerConnectionTracker::SOURCE_LOCAL); 1080 this, webrtc_channel.get(), PeerConnectionTracker::SOURCE_LOCAL);
1081 }
830 1082
831 ++num_data_channels_created_; 1083 ++num_data_channels_created_;
832 1084
833 return new RtcDataChannelHandler(base::ThreadTaskRunnerHandle::Get(), 1085 return new RtcDataChannelHandler(base::ThreadTaskRunnerHandle::Get(),
834 webrtc_channel); 1086 webrtc_channel);
835 } 1087 }
836 1088
837 blink::WebRTCDTMFSenderHandler* RTCPeerConnectionHandler::createDTMFSender( 1089 blink::WebRTCDTMFSenderHandler* RTCPeerConnectionHandler::createDTMFSender(
838 const blink::WebMediaStreamTrack& track) { 1090 const blink::WebMediaStreamTrack& track) {
1091 DCHECK(thread_checker_.CalledOnValidThread());
839 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createDTMFSender"); 1092 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::createDTMFSender");
840 DVLOG(1) << "createDTMFSender."; 1093 DVLOG(1) << "createDTMFSender.";
841 1094
842 MediaStreamTrack* native_track = MediaStreamTrack::GetTrack(track); 1095 MediaStreamTrack* native_track = MediaStreamTrack::GetTrack(track);
843 if (!native_track || 1096 if (!native_track || !native_track->is_local_track() ||
844 track.source().type() != blink::WebMediaStreamSource::TypeAudio) { 1097 track.source().type() != blink::WebMediaStreamSource::TypeAudio) {
845 DLOG(ERROR) << "Could not create DTMF sender from a non-audio track."; 1098 DLOG(ERROR) << "The DTMF sender requires a local audio track.";
846 return NULL; 1099 return nullptr;
847 } 1100 }
848 1101
849 webrtc::AudioTrackInterface* audio_track = native_track->GetAudioAdapter(); 1102 webrtc::AudioTrackInterface* audio_track = native_track->GetAudioAdapter();
850 rtc::scoped_refptr<webrtc::DtmfSenderInterface> sender( 1103 rtc::scoped_refptr<webrtc::DtmfSenderInterface> sender(
851 native_peer_connection_->CreateDtmfSender(audio_track)); 1104 native_peer_connection_->CreateDtmfSender(audio_track));
852 if (!sender) { 1105 if (!sender) {
853 DLOG(ERROR) << "Could not create native DTMF sender."; 1106 DLOG(ERROR) << "Could not create native DTMF sender.";
854 return NULL; 1107 return nullptr;
855 } 1108 }
856 if (peer_connection_tracker_) 1109 if (peer_connection_tracker_)
857 peer_connection_tracker_->TrackCreateDTMFSender(this, track); 1110 peer_connection_tracker_->TrackCreateDTMFSender(this, track);
858 1111
859 return new RtcDtmfSenderHandler(sender); 1112 return new RtcDtmfSenderHandler(sender);
860 } 1113 }
861 1114
862 void RTCPeerConnectionHandler::stop() { 1115 void RTCPeerConnectionHandler::stop() {
1116 DCHECK(thread_checker_.CalledOnValidThread());
863 DVLOG(1) << "RTCPeerConnectionHandler::stop"; 1117 DVLOG(1) << "RTCPeerConnectionHandler::stop";
864 1118
865 if (peer_connection_tracker_) 1119 if (peer_connection_tracker_)
866 peer_connection_tracker_->TrackStop(this); 1120 peer_connection_tracker_->TrackStop(this);
867 native_peer_connection_->Close(); 1121 native_peer_connection_->Close();
868 } 1122 // The client_ pointer is not considered valid after this point and no further
869 1123 // callbacks must be made.
870 void RTCPeerConnectionHandler::OnError() { 1124 client_ = nullptr;
871 // TODO(perkj): Implement.
872 NOTIMPLEMENTED();
873 } 1125 }
874 1126
875 void RTCPeerConnectionHandler::OnSignalingChange( 1127 void RTCPeerConnectionHandler::OnSignalingChange(
876 webrtc::PeerConnectionInterface::SignalingState new_state) { 1128 webrtc::PeerConnectionInterface::SignalingState new_state) {
1129 DCHECK(thread_checker_.CalledOnValidThread());
877 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnSignalingChange"); 1130 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnSignalingChange");
1131
878 blink::WebRTCPeerConnectionHandlerClient::SignalingState state = 1132 blink::WebRTCPeerConnectionHandlerClient::SignalingState state =
879 GetWebKitSignalingState(new_state); 1133 GetWebKitSignalingState(new_state);
880 if (peer_connection_tracker_) 1134 if (peer_connection_tracker_)
881 peer_connection_tracker_->TrackSignalingStateChange(this, state); 1135 peer_connection_tracker_->TrackSignalingStateChange(this, state);
882 client_->didChangeSignalingState(state); 1136 if (client_)
1137 client_->didChangeSignalingState(state);
883 } 1138 }
884 1139
885 // Called any time the IceConnectionState changes 1140 // Called any time the IceConnectionState changes
886 void RTCPeerConnectionHandler::OnIceConnectionChange( 1141 void RTCPeerConnectionHandler::OnIceConnectionChange(
887 webrtc::PeerConnectionInterface::IceConnectionState new_state) { 1142 webrtc::PeerConnectionInterface::IceConnectionState new_state) {
888 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnIceConnectionChange"); 1143 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnIceConnectionChange");
1144 DCHECK(thread_checker_.CalledOnValidThread());
889 if (new_state == webrtc::PeerConnectionInterface::kIceConnectionChecking) { 1145 if (new_state == webrtc::PeerConnectionInterface::kIceConnectionChecking) {
890 ice_connection_checking_start_ = base::TimeTicks::Now(); 1146 ice_connection_checking_start_ = base::TimeTicks::Now();
891 } else if (new_state == 1147 } else if (new_state ==
892 webrtc::PeerConnectionInterface::kIceConnectionConnected) { 1148 webrtc::PeerConnectionInterface::kIceConnectionConnected) {
893 // If the state becomes connected, send the time needed for PC to become 1149 // 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 1150 // connected from checking to UMA. UMA data will help to know how much
895 // time needed for PC to connect with remote peer. 1151 // time needed for PC to connect with remote peer.
896 UMA_HISTOGRAM_MEDIUM_TIMES( 1152 UMA_HISTOGRAM_MEDIUM_TIMES(
897 "WebRTC.PeerConnection.TimeToConnect", 1153 "WebRTC.PeerConnection.TimeToConnect",
898 base::TimeTicks::Now() - ice_connection_checking_start_); 1154 base::TimeTicks::Now() - ice_connection_checking_start_);
899 } 1155 }
900 1156
901 track_metrics_.IceConnectionChange(new_state); 1157 track_metrics_.IceConnectionChange(new_state);
902 blink::WebRTCPeerConnectionHandlerClient::ICEConnectionState state = 1158 blink::WebRTCPeerConnectionHandlerClient::ICEConnectionState state =
903 GetWebKitIceConnectionState(new_state); 1159 GetWebKitIceConnectionState(new_state);
904 if (peer_connection_tracker_) 1160 if (peer_connection_tracker_)
905 peer_connection_tracker_->TrackIceConnectionStateChange(this, state); 1161 peer_connection_tracker_->TrackIceConnectionStateChange(this, state);
906 client_->didChangeICEConnectionState(state); 1162 if(client_)
1163 client_->didChangeICEConnectionState(state);
907 } 1164 }
908 1165
909 // Called any time the IceGatheringState changes 1166 // Called any time the IceGatheringState changes
910 void RTCPeerConnectionHandler::OnIceGatheringChange( 1167 void RTCPeerConnectionHandler::OnIceGatheringChange(
911 webrtc::PeerConnectionInterface::IceGatheringState new_state) { 1168 webrtc::PeerConnectionInterface::IceGatheringState new_state) {
1169 DCHECK(thread_checker_.CalledOnValidThread());
912 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnIceGatheringChange"); 1170 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnIceGatheringChange");
1171
913 if (new_state == webrtc::PeerConnectionInterface::kIceGatheringComplete) { 1172 if (new_state == webrtc::PeerConnectionInterface::kIceGatheringComplete) {
914 // If ICE gathering is completed, generate a NULL ICE candidate, 1173 // If ICE gathering is completed, generate a NULL ICE candidate,
915 // to signal end of candidates. 1174 // to signal end of candidates.
916 blink::WebRTCICECandidate null_candidate; 1175 if (client_) {
917 client_->didGenerateICECandidate(null_candidate); 1176 blink::WebRTCICECandidate null_candidate;
1177 client_->didGenerateICECandidate(null_candidate);
1178 }
918 1179
919 UMA_HISTOGRAM_COUNTS_100("WebRTC.PeerConnection.IPv4LocalCandidates", 1180 UMA_HISTOGRAM_COUNTS_100("WebRTC.PeerConnection.IPv4LocalCandidates",
920 num_local_candidates_ipv4_); 1181 num_local_candidates_ipv4_);
921 1182
922 UMA_HISTOGRAM_COUNTS_100("WebRTC.PeerConnection.IPv6LocalCandidates", 1183 UMA_HISTOGRAM_COUNTS_100("WebRTC.PeerConnection.IPv6LocalCandidates",
923 num_local_candidates_ipv6_); 1184 num_local_candidates_ipv6_);
924 } else if (new_state == 1185 } else if (new_state ==
925 webrtc::PeerConnectionInterface::kIceGatheringGathering) { 1186 webrtc::PeerConnectionInterface::kIceGatheringGathering) {
926 // ICE restarts will change gathering state back to "gathering", 1187 // ICE restarts will change gathering state back to "gathering",
927 // reset the counter. 1188 // reset the counter.
928 num_local_candidates_ipv6_ = 0; 1189 num_local_candidates_ipv6_ = 0;
929 num_local_candidates_ipv4_ = 0; 1190 num_local_candidates_ipv4_ = 0;
930 } 1191 }
931 1192
932 blink::WebRTCPeerConnectionHandlerClient::ICEGatheringState state = 1193 blink::WebRTCPeerConnectionHandlerClient::ICEGatheringState state =
933 GetWebKitIceGatheringState(new_state); 1194 GetWebKitIceGatheringState(new_state);
934 if (peer_connection_tracker_) 1195 if (peer_connection_tracker_)
935 peer_connection_tracker_->TrackIceGatheringStateChange(this, state); 1196 peer_connection_tracker_->TrackIceGatheringStateChange(this, state);
936 client_->didChangeICEGatheringState(state); 1197 if (client_)
1198 client_->didChangeICEGatheringState(state);
1199 }
1200
1201 void RTCPeerConnectionHandler::OnRenegotiationNeeded() {
1202 DCHECK(thread_checker_.CalledOnValidThread());
1203 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnRenegotiationNeeded");
1204 if (peer_connection_tracker_)
1205 peer_connection_tracker_->TrackOnRenegotiationNeeded(this);
1206 if (client_)
1207 client_->negotiationNeeded();
1208 }
1209
1210 PeerConnectionTracker* RTCPeerConnectionHandler::peer_connection_tracker() {
1211 DCHECK(thread_checker_.CalledOnValidThread());
1212 return peer_connection_tracker_;
937 } 1213 }
938 1214
939 void RTCPeerConnectionHandler::OnAddStream( 1215 void RTCPeerConnectionHandler::OnAddStream(
940 webrtc::MediaStreamInterface* stream_interface) { 1216 scoped_ptr<RemoteMediaStreamImpl> stream) {
941 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnAddStream"); 1217 DCHECK(thread_checker_.CalledOnValidThread());
942 DCHECK(stream_interface); 1218 DCHECK(remote_streams_.find(stream->webrtc_stream().get()) ==
943 DCHECK(remote_streams_.find(stream_interface) == remote_streams_.end()); 1219 remote_streams_.end());
1220 DCHECK(stream->webkit_stream().extraData()) << "Initialization not done";
1221 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnAddStreamImpl");
944 1222
945 RemoteMediaStreamImpl* remote_stream = 1223 // Ownership is with remote_streams_ now.
946 new RemoteMediaStreamImpl(stream_interface); 1224 RemoteMediaStreamImpl* s = stream.release();
947 remote_streams_.insert( 1225 remote_streams_.insert(
948 std::pair<webrtc::MediaStreamInterface*, RemoteMediaStreamImpl*> ( 1226 std::pair<webrtc::MediaStreamInterface*, RemoteMediaStreamImpl*> (
949 stream_interface, remote_stream)); 1227 s->webrtc_stream().get(), s));
950 1228
951 if (peer_connection_tracker_) 1229 if (peer_connection_tracker_) {
952 peer_connection_tracker_->TrackAddStream( 1230 peer_connection_tracker_->TrackAddStream(
953 this, remote_stream->webkit_stream(), 1231 this, s->webkit_stream(), PeerConnectionTracker::SOURCE_REMOTE);
954 PeerConnectionTracker::SOURCE_REMOTE); 1232 }
955 1233
956 PerSessionWebRTCAPIMetrics::GetInstance()->IncrementStreamCounter(); 1234 PerSessionWebRTCAPIMetrics::GetInstance()->IncrementStreamCounter();
957 1235
958 track_metrics_.AddStream(MediaStreamTrackMetrics::RECEIVED_STREAM, 1236 track_metrics_.AddStream(MediaStreamTrackMetrics::RECEIVED_STREAM,
959 stream_interface); 1237 s->webrtc_stream().get());
960 1238 if (client_)
961 client_->didAddRemoteStream(remote_stream->webkit_stream()); 1239 client_->didAddRemoteStream(s->webkit_stream());
962 } 1240 }
963 1241
964 void RTCPeerConnectionHandler::OnRemoveStream( 1242 void RTCPeerConnectionHandler::OnRemoveStream(
965 webrtc::MediaStreamInterface* stream_interface) { 1243 const scoped_refptr<webrtc::MediaStreamInterface>& stream) {
966 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnRemoveStream"); 1244 DCHECK(thread_checker_.CalledOnValidThread());
967 DCHECK(stream_interface); 1245 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnRemoveStreamImpl");
968 RemoteStreamMap::iterator it = remote_streams_.find(stream_interface); 1246 RemoteStreamMap::iterator it = remote_streams_.find(stream.get());
969 if (it == remote_streams_.end()) { 1247 if (it == remote_streams_.end()) {
970 NOTREACHED() << "Stream not found"; 1248 NOTREACHED() << "Stream not found";
971 return; 1249 return;
972 } 1250 }
973 1251
974 track_metrics_.RemoveStream(MediaStreamTrackMetrics::RECEIVED_STREAM, 1252 track_metrics_.RemoveStream(MediaStreamTrackMetrics::RECEIVED_STREAM,
975 stream_interface); 1253 stream.get());
976 PerSessionWebRTCAPIMetrics::GetInstance()->DecrementStreamCounter(); 1254 PerSessionWebRTCAPIMetrics::GetInstance()->DecrementStreamCounter();
977 1255
978 scoped_ptr<RemoteMediaStreamImpl> remote_stream(it->second); 1256 scoped_ptr<RemoteMediaStreamImpl> remote_stream(it->second);
979 const blink::WebMediaStream& webkit_stream = remote_stream->webkit_stream(); 1257 const blink::WebMediaStream& webkit_stream = remote_stream->webkit_stream();
980 DCHECK(!webkit_stream.isNull()); 1258 DCHECK(!webkit_stream.isNull());
981 remote_streams_.erase(it); 1259 remote_streams_.erase(it);
982 1260
983 if (peer_connection_tracker_) 1261 if (peer_connection_tracker_) {
984 peer_connection_tracker_->TrackRemoveStream( 1262 peer_connection_tracker_->TrackRemoveStream(
985 this, webkit_stream, PeerConnectionTracker::SOURCE_REMOTE); 1263 this, webkit_stream, PeerConnectionTracker::SOURCE_REMOTE);
1264 }
986 1265
987 client_->didRemoveRemoteStream(webkit_stream); 1266 if (client_)
1267 client_->didRemoveRemoteStream(webkit_stream);
1268 }
1269
1270 void RTCPeerConnectionHandler::OnDataChannel(
1271 scoped_ptr<RtcDataChannelHandler> handler) {
1272 DCHECK(thread_checker_.CalledOnValidThread());
1273 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnDataChannelImpl");
1274
1275 if (peer_connection_tracker_) {
1276 peer_connection_tracker_->TrackCreateDataChannel(
1277 this, handler->channel().get(), PeerConnectionTracker::SOURCE_REMOTE);
1278 }
1279
1280 if (client_)
1281 client_->didAddRemoteDataChannel(handler.release());
988 } 1282 }
989 1283
990 void RTCPeerConnectionHandler::OnIceCandidate( 1284 void RTCPeerConnectionHandler::OnIceCandidate(
991 const webrtc::IceCandidateInterface* candidate) { 1285 const std::string& sdp, const std::string& sdp_mid, int sdp_mline_index,
992 TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnIceCandidate"); 1286 int component, int address_family) {
993 DCHECK(candidate); 1287 DCHECK(thread_checker_.CalledOnValidThread());
994 std::string sdp; 1288 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; 1289 blink::WebRTCICECandidate web_candidate;
1000 web_candidate.initialize(base::UTF8ToUTF16(sdp), 1290 web_candidate.initialize(base::UTF8ToUTF16(sdp),
1001 base::UTF8ToUTF16(candidate->sdp_mid()), 1291 base::UTF8ToUTF16(sdp_mid),
1002 candidate->sdp_mline_index()); 1292 sdp_mline_index);
1003 if (peer_connection_tracker_) 1293 if (peer_connection_tracker_) {
1004 peer_connection_tracker_->TrackAddIceCandidate( 1294 peer_connection_tracker_->TrackAddIceCandidate(
1005 this, web_candidate, PeerConnectionTracker::SOURCE_LOCAL, true); 1295 this, web_candidate, PeerConnectionTracker::SOURCE_LOCAL, true);
1296 }
1006 1297
1007 // Only the first m line's first component is tracked to avoid 1298 // Only the first m line's first component is tracked to avoid
1008 // miscounting when doing BUNDLE or rtcp mux. 1299 // miscounting when doing BUNDLE or rtcp mux.
1009 if (candidate->sdp_mline_index() == 0 && 1300 if (sdp_mline_index == 0 && component == 1) {
1010 candidate->candidate().component() == 1) { 1301 if (address_family == AF_INET) {
1011 if (candidate->candidate().address().family() == AF_INET) { 1302 ++num_local_candidates_ipv4_;
1012 num_local_candidates_ipv4_++; 1303 } else if (address_family == AF_INET6) {
1013 } else if (candidate->candidate().address().family() == AF_INET6) { 1304 ++num_local_candidates_ipv6_;
1014 num_local_candidates_ipv6_++;
1015 } else { 1305 } else {
1016 NOTREACHED(); 1306 NOTREACHED();
1017 } 1307 }
1018 } 1308 }
1019 client_->didGenerateICECandidate(web_candidate); 1309 if (client_)
1020 } 1310 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 } 1311 }
1045 1312
1046 webrtc::SessionDescriptionInterface* 1313 webrtc::SessionDescriptionInterface*
1047 RTCPeerConnectionHandler::CreateNativeSessionDescription( 1314 RTCPeerConnectionHandler::CreateNativeSessionDescription(
1048 const blink::WebRTCSessionDescription& description, 1315 const blink::WebRTCSessionDescription& description,
1049 webrtc::SdpParseError* error) { 1316 webrtc::SdpParseError* error) {
1050 std::string sdp = base::UTF16ToUTF8(description.sdp()); 1317 std::string sdp = base::UTF16ToUTF8(description.sdp());
1051 std::string type = base::UTF16ToUTF8(description.type()); 1318 std::string type = base::UTF16ToUTF8(description.type());
1052 webrtc::SessionDescriptionInterface* native_desc = 1319 webrtc::SessionDescriptionInterface* native_desc =
1053 dependency_factory_->CreateSessionDescription(type, sdp, error); 1320 dependency_factory_->CreateSessionDescription(type, sdp, error);
1054 1321
1055 LOG_IF(ERROR, !native_desc) << "Failed to create native session description." 1322 LOG_IF(ERROR, !native_desc) << "Failed to create native session description."
1056 << " Type: " << type << " SDP: " << sdp; 1323 << " Type: " << type << " SDP: " << sdp;
1057 1324
1058 return native_desc; 1325 return native_desc;
1059 } 1326 }
1060 1327
1061 } // namespace content 1328 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698