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

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

Powered by Google App Engine
This is Rietveld 408576698