Roll src/third_party/WebKit eac3800:0237a66 (svn 202606:202607)
[chromium-blink-merge.git] / content / renderer / media / webrtc / peer_connection_dependency_factory.cc
blob663f61869c45cc70b43a6b0e2931f2af057effe6
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
7 #include <vector>
9 #include "base/command_line.h"
10 #include "base/location.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/synchronization/waitable_event.h"
13 #include "content/common/media/media_stream_messages.h"
14 #include "content/public/common/content_switches.h"
15 #include "content/public/common/renderer_preferences.h"
16 #include "content/renderer/media/media_stream.h"
17 #include "content/renderer/media/media_stream_audio_processor.h"
18 #include "content/renderer/media/media_stream_audio_processor_options.h"
19 #include "content/renderer/media/media_stream_audio_source.h"
20 #include "content/renderer/media/media_stream_video_source.h"
21 #include "content/renderer/media/media_stream_video_track.h"
22 #include "content/renderer/media/peer_connection_identity_store.h"
23 #include "content/renderer/media/rtc_media_constraints.h"
24 #include "content/renderer/media/rtc_peer_connection_handler.h"
25 #include "content/renderer/media/rtc_video_decoder_factory.h"
26 #include "content/renderer/media/rtc_video_encoder_factory.h"
27 #include "content/renderer/media/webaudio_capturer_source.h"
28 #include "content/renderer/media/webrtc/stun_field_trial.h"
29 #include "content/renderer/media/webrtc/webrtc_local_audio_track_adapter.h"
30 #include "content/renderer/media/webrtc/webrtc_video_capturer_adapter.h"
31 #include "content/renderer/media/webrtc_audio_device_impl.h"
32 #include "content/renderer/media/webrtc_local_audio_track.h"
33 #include "content/renderer/media/webrtc_logging.h"
34 #include "content/renderer/media/webrtc_uma_histograms.h"
35 #include "content/renderer/p2p/ipc_network_manager.h"
36 #include "content/renderer/p2p/ipc_socket_factory.h"
37 #include "content/renderer/p2p/port_allocator.h"
38 #include "content/renderer/render_thread_impl.h"
39 #include "content/renderer/render_view_impl.h"
40 #include "jingle/glue/thread_wrapper.h"
41 #include "media/renderers/gpu_video_accelerator_factories.h"
42 #include "third_party/WebKit/public/platform/WebMediaConstraints.h"
43 #include "third_party/WebKit/public/platform/WebMediaStream.h"
44 #include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
45 #include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
46 #include "third_party/WebKit/public/platform/WebURL.h"
47 #include "third_party/WebKit/public/web/WebDocument.h"
48 #include "third_party/WebKit/public/web/WebFrame.h"
49 #include "third_party/libjingle/source/talk/app/webrtc/mediaconstraintsinterface.h"
51 #if defined(USE_OPENSSL)
52 #include "third_party/webrtc/base/ssladapter.h"
53 #else
54 #include "net/socket/nss_ssl_util.h"
55 #endif
57 #if defined(OS_ANDROID)
58 #include "media/base/android/media_codec_bridge.h"
59 #endif
61 namespace content {
63 // Map of corresponding media constraints and platform effects.
64 struct {
65 const char* constraint;
66 const media::AudioParameters::PlatformEffectsMask effect;
67 } const kConstraintEffectMap[] = {
68 { webrtc::MediaConstraintsInterface::kGoogEchoCancellation,
69 media::AudioParameters::ECHO_CANCELLER },
72 // If any platform effects are available, check them against the constraints.
73 // Disable effects to match false constraints, but if a constraint is true, set
74 // the constraint to false to later disable the software effect.
76 // This function may modify both |constraints| and |effects|.
77 void HarmonizeConstraintsAndEffects(RTCMediaConstraints* constraints,
78 int* effects) {
79 if (*effects != media::AudioParameters::NO_EFFECTS) {
80 for (size_t i = 0; i < arraysize(kConstraintEffectMap); ++i) {
81 bool value;
82 size_t is_mandatory = 0;
83 if (!webrtc::FindConstraint(constraints,
84 kConstraintEffectMap[i].constraint,
85 &value,
86 &is_mandatory) || !value) {
87 // If the constraint is false, or does not exist, disable the platform
88 // effect.
89 *effects &= ~kConstraintEffectMap[i].effect;
90 DVLOG(1) << "Disabling platform effect: "
91 << kConstraintEffectMap[i].effect;
92 } else if (*effects & kConstraintEffectMap[i].effect) {
93 // If the constraint is true, leave the platform effect enabled, and
94 // set the constraint to false to later disable the software effect.
95 if (is_mandatory) {
96 constraints->AddMandatory(kConstraintEffectMap[i].constraint,
97 webrtc::MediaConstraintsInterface::kValueFalse, true);
98 } else {
99 constraints->AddOptional(kConstraintEffectMap[i].constraint,
100 webrtc::MediaConstraintsInterface::kValueFalse, true);
102 DVLOG(1) << "Disabling constraint: "
103 << kConstraintEffectMap[i].constraint;
109 class P2PPortAllocatorFactory : public webrtc::PortAllocatorFactoryInterface {
110 public:
111 P2PPortAllocatorFactory(P2PSocketDispatcher* socket_dispatcher,
112 rtc::NetworkManager* network_manager,
113 rtc::PacketSocketFactory* socket_factory,
114 const GURL& origin,
115 const P2PPortAllocator::Config& config)
116 : socket_dispatcher_(socket_dispatcher),
117 network_manager_(network_manager),
118 socket_factory_(socket_factory),
119 origin_(origin),
120 config_(config) {}
122 cricket::PortAllocator* CreatePortAllocator(
123 const std::vector<StunConfiguration>& stun_servers,
124 const std::vector<TurnConfiguration>& turn_configurations) override {
125 P2PPortAllocator::Config config = config_;
126 for (size_t i = 0; i < stun_servers.size(); ++i) {
127 config.stun_servers.insert(rtc::SocketAddress(
128 stun_servers[i].server.hostname(),
129 stun_servers[i].server.port()));
131 for (size_t i = 0; i < turn_configurations.size(); ++i) {
132 P2PPortAllocator::Config::RelayServerConfig relay_config;
133 relay_config.server_address = turn_configurations[i].server.hostname();
134 relay_config.port = turn_configurations[i].server.port();
135 relay_config.username = turn_configurations[i].username;
136 relay_config.password = turn_configurations[i].password;
137 relay_config.transport_type = turn_configurations[i].transport_type;
138 relay_config.secure = turn_configurations[i].secure;
139 config.relays.push_back(relay_config);
142 return new P2PPortAllocator(
143 socket_dispatcher_.get(), network_manager_,
144 socket_factory_, config, origin_);
147 protected:
148 ~P2PPortAllocatorFactory() override {}
150 private:
151 scoped_refptr<P2PSocketDispatcher> socket_dispatcher_;
152 // |network_manager_| and |socket_factory_| are a weak references, owned by
153 // PeerConnectionDependencyFactory.
154 rtc::NetworkManager* network_manager_;
155 rtc::PacketSocketFactory* socket_factory_;
156 // The origin URL of the WebFrame that created the
157 // P2PPortAllocatorFactory.
158 GURL origin_;
160 // Keep track of configuration common to all PortAllocators created by this
161 // factory; additional, per-allocator configuration is passed into
162 // CreatePortAllocator.
163 P2PPortAllocator::Config config_;
166 PeerConnectionDependencyFactory::PeerConnectionDependencyFactory(
167 P2PSocketDispatcher* p2p_socket_dispatcher)
168 : network_manager_(NULL),
169 p2p_socket_dispatcher_(p2p_socket_dispatcher),
170 signaling_thread_(NULL),
171 worker_thread_(NULL),
172 chrome_signaling_thread_("Chrome_libJingle_Signaling"),
173 chrome_worker_thread_("Chrome_libJingle_WorkerThread") {
174 TryScheduleStunProbeTrial();
177 PeerConnectionDependencyFactory::~PeerConnectionDependencyFactory() {
178 DVLOG(1) << "~PeerConnectionDependencyFactory()";
179 DCHECK(pc_factory_ == NULL);
182 blink::WebRTCPeerConnectionHandler*
183 PeerConnectionDependencyFactory::CreateRTCPeerConnectionHandler(
184 blink::WebRTCPeerConnectionHandlerClient* client) {
185 // Save histogram data so we can see how much PeerConnetion is used.
186 // The histogram counts the number of calls to the JS API
187 // webKitRTCPeerConnection.
188 UpdateWebRTCMethodCount(WEBKIT_RTC_PEER_CONNECTION);
190 return new RTCPeerConnectionHandler(client, this);
193 bool PeerConnectionDependencyFactory::InitializeMediaStreamAudioSource(
194 int render_frame_id,
195 const blink::WebMediaConstraints& audio_constraints,
196 MediaStreamAudioSource* source_data) {
197 DVLOG(1) << "InitializeMediaStreamAudioSources()";
199 // Do additional source initialization if the audio source is a valid
200 // microphone or tab audio.
201 RTCMediaConstraints native_audio_constraints(audio_constraints);
202 MediaAudioConstraints::ApplyFixedAudioConstraints(&native_audio_constraints);
204 StreamDeviceInfo device_info = source_data->device_info();
205 RTCMediaConstraints constraints = native_audio_constraints;
206 // May modify both |constraints| and |effects|.
207 HarmonizeConstraintsAndEffects(&constraints,
208 &device_info.device.input.effects);
210 scoped_refptr<WebRtcAudioCapturer> capturer(CreateAudioCapturer(
211 render_frame_id, device_info, audio_constraints, source_data));
212 if (!capturer.get()) {
213 const std::string log_string =
214 "PCDF::InitializeMediaStreamAudioSource: fails to create capturer";
215 WebRtcLogMessage(log_string);
216 DVLOG(1) << log_string;
217 // TODO(xians): Don't we need to check if source_observer is observing
218 // something? If not, then it looks like we have a leak here.
219 // OTOH, if it _is_ observing something, then the callback might
220 // be called multiple times which is likely also a bug.
221 return false;
223 source_data->SetAudioCapturer(capturer.get());
225 // Creates a LocalAudioSource object which holds audio options.
226 // TODO(xians): The option should apply to the track instead of the source.
227 // TODO(perkj): Move audio constraints parsing to Chrome.
228 // Currently there are a few constraints that are parsed by libjingle and
229 // the state is set to ended if parsing fails.
230 scoped_refptr<webrtc::AudioSourceInterface> rtc_source(
231 CreateLocalAudioSource(&constraints).get());
232 if (rtc_source->state() != webrtc::MediaSourceInterface::kLive) {
233 DLOG(WARNING) << "Failed to create rtc LocalAudioSource.";
234 return false;
236 source_data->SetLocalAudioSource(rtc_source.get());
237 return true;
240 WebRtcVideoCapturerAdapter*
241 PeerConnectionDependencyFactory::CreateVideoCapturer(
242 bool is_screeencast) {
243 // We need to make sure the libjingle thread wrappers have been created
244 // before we can use an instance of a WebRtcVideoCapturerAdapter. This is
245 // since the base class of WebRtcVideoCapturerAdapter is a
246 // cricket::VideoCapturer and it uses the libjingle thread wrappers.
247 if (!GetPcFactory().get())
248 return NULL;
249 return new WebRtcVideoCapturerAdapter(is_screeencast);
252 scoped_refptr<webrtc::VideoSourceInterface>
253 PeerConnectionDependencyFactory::CreateVideoSource(
254 cricket::VideoCapturer* capturer,
255 const blink::WebMediaConstraints& constraints) {
256 RTCMediaConstraints webrtc_constraints(constraints);
257 scoped_refptr<webrtc::VideoSourceInterface> source =
258 GetPcFactory()->CreateVideoSource(capturer, &webrtc_constraints).get();
259 return source;
262 const scoped_refptr<webrtc::PeerConnectionFactoryInterface>&
263 PeerConnectionDependencyFactory::GetPcFactory() {
264 if (!pc_factory_.get())
265 CreatePeerConnectionFactory();
266 CHECK(pc_factory_.get());
267 return pc_factory_;
271 void PeerConnectionDependencyFactory::WillDestroyCurrentMessageLoop() {
272 CleanupPeerConnectionFactory();
275 void PeerConnectionDependencyFactory::CreatePeerConnectionFactory() {
276 DCHECK(!pc_factory_.get());
277 DCHECK(!signaling_thread_);
278 DCHECK(!worker_thread_);
279 DCHECK(!network_manager_);
280 DCHECK(!socket_factory_);
281 DCHECK(!chrome_signaling_thread_.IsRunning());
282 DCHECK(!chrome_worker_thread_.IsRunning());
284 DVLOG(1) << "PeerConnectionDependencyFactory::CreatePeerConnectionFactory()";
286 base::MessageLoop::current()->AddDestructionObserver(this);
287 // To allow sending to the signaling/worker threads.
288 jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
289 jingle_glue::JingleThreadWrapper::current()->set_send_allowed(true);
291 CHECK(chrome_signaling_thread_.Start());
292 CHECK(chrome_worker_thread_.Start());
294 base::WaitableEvent start_worker_event(true, false);
295 chrome_worker_thread_.task_runner()->PostTask(
296 FROM_HERE,
297 base::Bind(&PeerConnectionDependencyFactory::InitializeWorkerThread,
298 base::Unretained(this), &worker_thread_, &start_worker_event));
300 base::WaitableEvent create_network_manager_event(true, false);
301 chrome_worker_thread_.task_runner()->PostTask(
302 FROM_HERE,
303 base::Bind(&PeerConnectionDependencyFactory::
304 CreateIpcNetworkManagerOnWorkerThread,
305 base::Unretained(this), &create_network_manager_event));
307 start_worker_event.Wait();
308 create_network_manager_event.Wait();
310 CHECK(worker_thread_);
312 // Init SSL, which will be needed by PeerConnection.
313 #if defined(USE_OPENSSL)
314 if (!rtc::InitializeSSL()) {
315 LOG(ERROR) << "Failed on InitializeSSL.";
316 NOTREACHED();
317 return;
319 #else
320 // TODO(ronghuawu): Replace this call with InitializeSSL.
321 net::EnsureNSSSSLInit();
322 #endif
324 base::WaitableEvent start_signaling_event(true, false);
325 chrome_signaling_thread_.task_runner()->PostTask(
326 FROM_HERE,
327 base::Bind(&PeerConnectionDependencyFactory::InitializeSignalingThread,
328 base::Unretained(this),
329 RenderThreadImpl::current()->GetGpuFactories(),
330 &start_signaling_event));
332 start_signaling_event.Wait();
333 CHECK(signaling_thread_);
336 void PeerConnectionDependencyFactory::InitializeSignalingThread(
337 const scoped_refptr<media::GpuVideoAcceleratorFactories>& gpu_factories,
338 base::WaitableEvent* event) {
339 DCHECK(chrome_signaling_thread_.task_runner()->BelongsToCurrentThread());
340 DCHECK(worker_thread_);
341 DCHECK(p2p_socket_dispatcher_.get());
343 jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
344 jingle_glue::JingleThreadWrapper::current()->set_send_allowed(true);
345 signaling_thread_ = jingle_glue::JingleThreadWrapper::current();
347 EnsureWebRtcAudioDeviceImpl();
349 socket_factory_.reset(
350 new IpcPacketSocketFactory(p2p_socket_dispatcher_.get()));
352 scoped_ptr<cricket::WebRtcVideoDecoderFactory> decoder_factory;
353 scoped_ptr<cricket::WebRtcVideoEncoderFactory> encoder_factory;
355 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
356 if (gpu_factories && gpu_factories->IsGpuVideoAcceleratorEnabled()) {
357 if (!cmd_line->HasSwitch(switches::kDisableWebRtcHWDecoding))
358 decoder_factory.reset(new RTCVideoDecoderFactory(gpu_factories));
360 if (!cmd_line->HasSwitch(switches::kDisableWebRtcHWEncoding))
361 encoder_factory.reset(new RTCVideoEncoderFactory(gpu_factories));
364 #if defined(OS_ANDROID)
365 if (!media::MediaCodecBridge::SupportsSetParameters())
366 encoder_factory.reset();
367 #endif
369 pc_factory_ = webrtc::CreatePeerConnectionFactory(
370 worker_thread_, signaling_thread_, audio_device_.get(),
371 encoder_factory.release(), decoder_factory.release());
372 CHECK(pc_factory_.get());
374 webrtc::PeerConnectionFactoryInterface::Options factory_options;
375 factory_options.disable_sctp_data_channels = false;
376 factory_options.disable_encryption =
377 cmd_line->HasSwitch(switches::kDisableWebRtcEncryption);
378 if (cmd_line->HasSwitch(switches::kEnableWebRtcDtls12))
379 factory_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
380 pc_factory_->SetOptions(factory_options);
382 event->Signal();
385 bool PeerConnectionDependencyFactory::PeerConnectionFactoryCreated() {
386 return pc_factory_.get() != NULL;
389 scoped_refptr<webrtc::PeerConnectionInterface>
390 PeerConnectionDependencyFactory::CreatePeerConnection(
391 const webrtc::PeerConnectionInterface::RTCConfiguration& config,
392 const webrtc::MediaConstraintsInterface* constraints,
393 blink::WebFrame* web_frame,
394 webrtc::PeerConnectionObserver* observer) {
395 CHECK(web_frame);
396 CHECK(observer);
397 if (!GetPcFactory().get())
398 return NULL;
400 rtc::scoped_ptr<PeerConnectionIdentityStore> identity_store(
401 new PeerConnectionIdentityStore(
402 GURL(web_frame->document().url()),
403 GURL(web_frame->document().firstPartyForCookies())));
405 // Copy the flag from Preference associated with this WebFrame.
406 P2PPortAllocator::Config pref_config;
407 if (web_frame && web_frame->view()) {
408 RenderViewImpl* renderer_view_impl =
409 RenderViewImpl::FromWebView(web_frame->view());
410 if (renderer_view_impl) {
411 pref_config.enable_multiple_routes =
412 renderer_view_impl->renderer_preferences()
413 .enable_webrtc_multiple_routes;
414 pref_config.enable_nonproxied_udp =
415 renderer_view_impl->renderer_preferences()
416 .enable_webrtc_nonproxied_udp;
420 scoped_refptr<P2PPortAllocatorFactory> pa_factory =
421 new rtc::RefCountedObject<P2PPortAllocatorFactory>(
422 p2p_socket_dispatcher_.get(), network_manager_, socket_factory_.get(),
423 GURL(web_frame->document().url().spec()).GetOrigin(), pref_config);
425 return GetPcFactory()->CreatePeerConnection(config,
426 constraints,
427 pa_factory.get(),
428 identity_store.Pass(),
429 observer).get();
432 scoped_refptr<webrtc::MediaStreamInterface>
433 PeerConnectionDependencyFactory::CreateLocalMediaStream(
434 const std::string& label) {
435 return GetPcFactory()->CreateLocalMediaStream(label).get();
438 scoped_refptr<webrtc::AudioSourceInterface>
439 PeerConnectionDependencyFactory::CreateLocalAudioSource(
440 const webrtc::MediaConstraintsInterface* constraints) {
441 scoped_refptr<webrtc::AudioSourceInterface> source =
442 GetPcFactory()->CreateAudioSource(constraints).get();
443 return source;
446 void PeerConnectionDependencyFactory::CreateLocalAudioTrack(
447 const blink::WebMediaStreamTrack& track) {
448 blink::WebMediaStreamSource source = track.source();
449 DCHECK_EQ(source.type(), blink::WebMediaStreamSource::TypeAudio);
450 MediaStreamAudioSource* source_data =
451 static_cast<MediaStreamAudioSource*>(source.extraData());
453 scoped_refptr<WebAudioCapturerSource> webaudio_source;
454 if (!source_data) {
455 if (source.requiresAudioConsumer()) {
456 // We're adding a WebAudio MediaStream.
457 // Create a specific capturer for each WebAudio consumer.
458 webaudio_source = CreateWebAudioSource(&source);
459 source_data =
460 static_cast<MediaStreamAudioSource*>(source.extraData());
461 } else {
462 // TODO(perkj): Implement support for sources from
463 // remote MediaStreams.
464 NOTIMPLEMENTED();
465 return;
469 // Creates an adapter to hold all the libjingle objects.
470 scoped_refptr<WebRtcLocalAudioTrackAdapter> adapter(
471 WebRtcLocalAudioTrackAdapter::Create(track.id().utf8(),
472 source_data->local_audio_source()));
473 static_cast<webrtc::AudioTrackInterface*>(adapter.get())->set_enabled(
474 track.isEnabled());
476 // TODO(xians): Merge |source| to the capturer(). We can't do this today
477 // because only one capturer() is supported while one |source| is created
478 // for each audio track.
479 scoped_ptr<WebRtcLocalAudioTrack> audio_track(new WebRtcLocalAudioTrack(
480 adapter.get(), source_data->GetAudioCapturer(), webaudio_source.get()));
482 StartLocalAudioTrack(audio_track.get());
484 // Pass the ownership of the native local audio track to the blink track.
485 blink::WebMediaStreamTrack writable_track = track;
486 writable_track.setExtraData(audio_track.release());
489 void PeerConnectionDependencyFactory::StartLocalAudioTrack(
490 WebRtcLocalAudioTrack* audio_track) {
491 // Start the audio track. This will hook the |audio_track| to the capturer
492 // as the sink of the audio, and only start the source of the capturer if
493 // it is the first audio track connecting to the capturer.
494 audio_track->Start();
497 scoped_refptr<WebAudioCapturerSource>
498 PeerConnectionDependencyFactory::CreateWebAudioSource(
499 blink::WebMediaStreamSource* source) {
500 DVLOG(1) << "PeerConnectionDependencyFactory::CreateWebAudioSource()";
502 scoped_refptr<WebAudioCapturerSource>
503 webaudio_capturer_source(new WebAudioCapturerSource(*source));
504 MediaStreamAudioSource* source_data = new MediaStreamAudioSource();
506 // Use the current default capturer for the WebAudio track so that the
507 // WebAudio track can pass a valid delay value and |need_audio_processing|
508 // flag to PeerConnection.
509 // TODO(xians): Remove this after moving APM to Chrome.
510 if (GetWebRtcAudioDevice()) {
511 source_data->SetAudioCapturer(
512 GetWebRtcAudioDevice()->GetDefaultCapturer());
515 // Create a LocalAudioSource object which holds audio options.
516 // SetLocalAudioSource() affects core audio parts in third_party/Libjingle.
517 source_data->SetLocalAudioSource(CreateLocalAudioSource(NULL).get());
518 source->setExtraData(source_data);
520 // Replace the default source with WebAudio as source instead.
521 source->addAudioConsumer(webaudio_capturer_source.get());
523 return webaudio_capturer_source;
526 scoped_refptr<webrtc::VideoTrackInterface>
527 PeerConnectionDependencyFactory::CreateLocalVideoTrack(
528 const std::string& id,
529 webrtc::VideoSourceInterface* source) {
530 return GetPcFactory()->CreateVideoTrack(id, source).get();
533 scoped_refptr<webrtc::VideoTrackInterface>
534 PeerConnectionDependencyFactory::CreateLocalVideoTrack(
535 const std::string& id, cricket::VideoCapturer* capturer) {
536 if (!capturer) {
537 LOG(ERROR) << "CreateLocalVideoTrack called with null VideoCapturer.";
538 return NULL;
541 // Create video source from the |capturer|.
542 scoped_refptr<webrtc::VideoSourceInterface> source =
543 GetPcFactory()->CreateVideoSource(capturer, NULL).get();
545 // Create native track from the source.
546 return GetPcFactory()->CreateVideoTrack(id, source.get()).get();
549 webrtc::SessionDescriptionInterface*
550 PeerConnectionDependencyFactory::CreateSessionDescription(
551 const std::string& type,
552 const std::string& sdp,
553 webrtc::SdpParseError* error) {
554 return webrtc::CreateSessionDescription(type, sdp, error);
557 webrtc::IceCandidateInterface*
558 PeerConnectionDependencyFactory::CreateIceCandidate(
559 const std::string& sdp_mid,
560 int sdp_mline_index,
561 const std::string& sdp) {
562 return webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, sdp, nullptr);
565 WebRtcAudioDeviceImpl*
566 PeerConnectionDependencyFactory::GetWebRtcAudioDevice() {
567 return audio_device_.get();
570 void PeerConnectionDependencyFactory::InitializeWorkerThread(
571 rtc::Thread** thread,
572 base::WaitableEvent* event) {
573 jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
574 jingle_glue::JingleThreadWrapper::current()->set_send_allowed(true);
575 *thread = jingle_glue::JingleThreadWrapper::current();
576 event->Signal();
579 void PeerConnectionDependencyFactory::TryScheduleStunProbeTrial() {
580 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
582 if (!cmd_line->HasSwitch(switches::kWebRtcStunProbeTrialParameter))
583 return;
585 GetPcFactory();
587 // The underneath IPC channel has to be connected before sending any IPC
588 // message.
589 if (!p2p_socket_dispatcher_->connected()) {
590 base::MessageLoop::current()->PostDelayedTask(
591 FROM_HERE,
592 base::Bind(&PeerConnectionDependencyFactory::TryScheduleStunProbeTrial,
593 base::Unretained(this)),
594 base::TimeDelta::FromSeconds(1));
595 return;
598 const std::string params =
599 cmd_line->GetSwitchValueASCII(switches::kWebRtcStunProbeTrialParameter);
601 chrome_worker_thread_.task_runner()->PostDelayedTask(
602 FROM_HERE,
603 base::Bind(
604 &PeerConnectionDependencyFactory::StartStunProbeTrialOnWorkerThread,
605 base::Unretained(this), params),
606 base::TimeDelta::FromMilliseconds(kExperimentStartDelayMs));
609 void PeerConnectionDependencyFactory::StartStunProbeTrialOnWorkerThread(
610 const std::string& params) {
611 DCHECK(chrome_worker_thread_.task_runner()->BelongsToCurrentThread());
612 rtc::NetworkManager::NetworkList networks;
613 network_manager_->GetNetworks(&networks);
614 stun_prober_ = StartStunProbeTrial(networks, params, socket_factory_.get());
617 void PeerConnectionDependencyFactory::CreateIpcNetworkManagerOnWorkerThread(
618 base::WaitableEvent* event) {
619 DCHECK(chrome_worker_thread_.task_runner()->BelongsToCurrentThread());
620 network_manager_ = new IpcNetworkManager(p2p_socket_dispatcher_.get());
621 event->Signal();
624 void PeerConnectionDependencyFactory::DeleteIpcNetworkManager() {
625 DCHECK(chrome_worker_thread_.task_runner()->BelongsToCurrentThread());
626 delete network_manager_;
627 network_manager_ = NULL;
630 void PeerConnectionDependencyFactory::CleanupPeerConnectionFactory() {
631 DVLOG(1) << "PeerConnectionDependencyFactory::CleanupPeerConnectionFactory()";
632 pc_factory_ = NULL;
633 if (network_manager_) {
634 // The network manager needs to free its resources on the thread they were
635 // created, which is the worked thread.
636 if (chrome_worker_thread_.IsRunning()) {
637 chrome_worker_thread_.task_runner()->PostTask(
638 FROM_HERE,
639 base::Bind(&PeerConnectionDependencyFactory::DeleteIpcNetworkManager,
640 base::Unretained(this)));
641 // Stopping the thread will wait until all tasks have been
642 // processed before returning. We wait for the above task to finish before
643 // letting the the function continue to avoid any potential race issues.
644 chrome_worker_thread_.Stop();
645 } else {
646 NOTREACHED() << "Worker thread not running.";
651 scoped_refptr<WebRtcAudioCapturer>
652 PeerConnectionDependencyFactory::CreateAudioCapturer(
653 int render_frame_id,
654 const StreamDeviceInfo& device_info,
655 const blink::WebMediaConstraints& constraints,
656 MediaStreamAudioSource* audio_source) {
657 // TODO(xians): Handle the cases when gUM is called without a proper render
658 // view, for example, by an extension.
659 DCHECK_GE(render_frame_id, 0);
661 EnsureWebRtcAudioDeviceImpl();
662 DCHECK(GetWebRtcAudioDevice());
663 return WebRtcAudioCapturer::CreateCapturer(
664 render_frame_id, device_info, constraints, GetWebRtcAudioDevice(),
665 audio_source);
668 scoped_refptr<base::SingleThreadTaskRunner>
669 PeerConnectionDependencyFactory::GetWebRtcWorkerThread() const {
670 DCHECK(CalledOnValidThread());
671 return chrome_worker_thread_.IsRunning() ? chrome_worker_thread_.task_runner()
672 : nullptr;
675 scoped_refptr<base::SingleThreadTaskRunner>
676 PeerConnectionDependencyFactory::GetWebRtcSignalingThread() const {
677 DCHECK(CalledOnValidThread());
678 return chrome_signaling_thread_.IsRunning()
679 ? chrome_signaling_thread_.task_runner()
680 : nullptr;
683 void PeerConnectionDependencyFactory::EnsureWebRtcAudioDeviceImpl() {
684 if (audio_device_.get())
685 return;
687 audio_device_ = new WebRtcAudioDeviceImpl();
690 } // namespace content