Process Alt-Svc headers.
[chromium-blink-merge.git] / content / renderer / media / webrtc / peer_connection_dependency_factory.cc
blob3f6634b1e46c17fa4524df0e45abb6d05fa1fe4c
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_service.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 { content::kMediaStreamAudioDucking,
69 media::AudioParameters::DUCKING },
70 { webrtc::MediaConstraintsInterface::kGoogEchoCancellation,
71 media::AudioParameters::ECHO_CANCELLER },
74 // If any platform effects are available, check them against the constraints.
75 // Disable effects to match false constraints, but if a constraint is true, set
76 // the constraint to false to later disable the software effect.
78 // This function may modify both |constraints| and |effects|.
79 void HarmonizeConstraintsAndEffects(RTCMediaConstraints* constraints,
80 int* effects) {
81 if (*effects != media::AudioParameters::NO_EFFECTS) {
82 for (size_t i = 0; i < arraysize(kConstraintEffectMap); ++i) {
83 bool value;
84 size_t is_mandatory = 0;
85 if (!webrtc::FindConstraint(constraints,
86 kConstraintEffectMap[i].constraint,
87 &value,
88 &is_mandatory) || !value) {
89 // If the constraint is false, or does not exist, disable the platform
90 // effect.
91 *effects &= ~kConstraintEffectMap[i].effect;
92 DVLOG(1) << "Disabling platform effect: "
93 << kConstraintEffectMap[i].effect;
94 } else if (*effects & kConstraintEffectMap[i].effect) {
95 // If the constraint is true, leave the platform effect enabled, and
96 // set the constraint to false to later disable the software effect.
97 if (is_mandatory) {
98 constraints->AddMandatory(kConstraintEffectMap[i].constraint,
99 webrtc::MediaConstraintsInterface::kValueFalse, true);
100 } else {
101 constraints->AddOptional(kConstraintEffectMap[i].constraint,
102 webrtc::MediaConstraintsInterface::kValueFalse, true);
104 DVLOG(1) << "Disabling constraint: "
105 << kConstraintEffectMap[i].constraint;
106 } else if (kConstraintEffectMap[i].effect ==
107 media::AudioParameters::DUCKING && value && !is_mandatory) {
108 // Special handling of the DUCKING flag that sets the optional
109 // constraint to |false| to match what the device will support.
110 constraints->AddOptional(kConstraintEffectMap[i].constraint,
111 webrtc::MediaConstraintsInterface::kValueFalse, true);
112 // No need to modify |effects| since the ducking flag is already off.
113 DCHECK((*effects & media::AudioParameters::DUCKING) == 0);
119 class P2PPortAllocatorFactory : public webrtc::PortAllocatorFactoryInterface {
120 public:
121 P2PPortAllocatorFactory(P2PSocketDispatcher* socket_dispatcher,
122 rtc::NetworkManager* network_manager,
123 rtc::PacketSocketFactory* socket_factory,
124 const GURL& origin,
125 bool enable_multiple_routes)
126 : socket_dispatcher_(socket_dispatcher),
127 network_manager_(network_manager),
128 socket_factory_(socket_factory),
129 origin_(origin),
130 enable_multiple_routes_(enable_multiple_routes) {}
132 cricket::PortAllocator* CreatePortAllocator(
133 const std::vector<StunConfiguration>& stun_servers,
134 const std::vector<TurnConfiguration>& turn_configurations) override {
135 P2PPortAllocator::Config config;
136 for (size_t i = 0; i < stun_servers.size(); ++i) {
137 config.stun_servers.insert(rtc::SocketAddress(
138 stun_servers[i].server.hostname(),
139 stun_servers[i].server.port()));
141 for (size_t i = 0; i < turn_configurations.size(); ++i) {
142 P2PPortAllocator::Config::RelayServerConfig relay_config;
143 relay_config.server_address = turn_configurations[i].server.hostname();
144 relay_config.port = turn_configurations[i].server.port();
145 relay_config.username = turn_configurations[i].username;
146 relay_config.password = turn_configurations[i].password;
147 relay_config.transport_type = turn_configurations[i].transport_type;
148 relay_config.secure = turn_configurations[i].secure;
149 config.relays.push_back(relay_config);
151 // Use turn servers as stun servers.
152 config.stun_servers.insert(rtc::SocketAddress(
153 turn_configurations[i].server.hostname(),
154 turn_configurations[i].server.port()));
156 config.enable_multiple_routes = enable_multiple_routes_;
158 return new P2PPortAllocator(
159 socket_dispatcher_.get(), network_manager_,
160 socket_factory_, config, origin_);
163 protected:
164 ~P2PPortAllocatorFactory() override {}
166 private:
167 scoped_refptr<P2PSocketDispatcher> socket_dispatcher_;
168 // |network_manager_| and |socket_factory_| are a weak references, owned by
169 // PeerConnectionDependencyFactory.
170 rtc::NetworkManager* network_manager_;
171 rtc::PacketSocketFactory* socket_factory_;
172 // The origin URL of the WebFrame that created the
173 // P2PPortAllocatorFactory.
174 GURL origin_;
175 // When false, only 'any' address (all 0s) will be bound for address
176 // discovery.
177 bool enable_multiple_routes_;
180 PeerConnectionDependencyFactory::PeerConnectionDependencyFactory(
181 P2PSocketDispatcher* p2p_socket_dispatcher)
182 : network_manager_(NULL),
183 p2p_socket_dispatcher_(p2p_socket_dispatcher),
184 signaling_thread_(NULL),
185 worker_thread_(NULL),
186 chrome_signaling_thread_("Chrome_libJingle_Signaling"),
187 chrome_worker_thread_("Chrome_libJingle_WorkerThread") {
188 TryScheduleStunProbeTrial();
191 PeerConnectionDependencyFactory::~PeerConnectionDependencyFactory() {
192 DVLOG(1) << "~PeerConnectionDependencyFactory()";
193 DCHECK(pc_factory_ == NULL);
196 blink::WebRTCPeerConnectionHandler*
197 PeerConnectionDependencyFactory::CreateRTCPeerConnectionHandler(
198 blink::WebRTCPeerConnectionHandlerClient* client) {
199 // Save histogram data so we can see how much PeerConnetion is used.
200 // The histogram counts the number of calls to the JS API
201 // webKitRTCPeerConnection.
202 UpdateWebRTCMethodCount(WEBKIT_RTC_PEER_CONNECTION);
204 return new RTCPeerConnectionHandler(client, this);
207 bool PeerConnectionDependencyFactory::InitializeMediaStreamAudioSource(
208 int render_frame_id,
209 const blink::WebMediaConstraints& audio_constraints,
210 MediaStreamAudioSource* source_data) {
211 DVLOG(1) << "InitializeMediaStreamAudioSources()";
213 // Do additional source initialization if the audio source is a valid
214 // microphone or tab audio.
215 RTCMediaConstraints native_audio_constraints(audio_constraints);
216 MediaAudioConstraints::ApplyFixedAudioConstraints(&native_audio_constraints);
218 StreamDeviceInfo device_info = source_data->device_info();
219 RTCMediaConstraints constraints = native_audio_constraints;
220 // May modify both |constraints| and |effects|.
221 HarmonizeConstraintsAndEffects(&constraints,
222 &device_info.device.input.effects);
224 scoped_refptr<WebRtcAudioCapturer> capturer(CreateAudioCapturer(
225 render_frame_id, device_info, audio_constraints, source_data));
226 if (!capturer.get()) {
227 const std::string log_string =
228 "PCDF::InitializeMediaStreamAudioSource: fails to create capturer";
229 WebRtcLogMessage(log_string);
230 DVLOG(1) << log_string;
231 // TODO(xians): Don't we need to check if source_observer is observing
232 // something? If not, then it looks like we have a leak here.
233 // OTOH, if it _is_ observing something, then the callback might
234 // be called multiple times which is likely also a bug.
235 return false;
237 source_data->SetAudioCapturer(capturer.get());
239 // Creates a LocalAudioSource object which holds audio options.
240 // TODO(xians): The option should apply to the track instead of the source.
241 // TODO(perkj): Move audio constraints parsing to Chrome.
242 // Currently there are a few constraints that are parsed by libjingle and
243 // the state is set to ended if parsing fails.
244 scoped_refptr<webrtc::AudioSourceInterface> rtc_source(
245 CreateLocalAudioSource(&constraints).get());
246 if (rtc_source->state() != webrtc::MediaSourceInterface::kLive) {
247 DLOG(WARNING) << "Failed to create rtc LocalAudioSource.";
248 return false;
250 source_data->SetLocalAudioSource(rtc_source.get());
251 return true;
254 WebRtcVideoCapturerAdapter*
255 PeerConnectionDependencyFactory::CreateVideoCapturer(
256 bool is_screeencast) {
257 // We need to make sure the libjingle thread wrappers have been created
258 // before we can use an instance of a WebRtcVideoCapturerAdapter. This is
259 // since the base class of WebRtcVideoCapturerAdapter is a
260 // cricket::VideoCapturer and it uses the libjingle thread wrappers.
261 if (!GetPcFactory().get())
262 return NULL;
263 return new WebRtcVideoCapturerAdapter(is_screeencast);
266 scoped_refptr<webrtc::VideoSourceInterface>
267 PeerConnectionDependencyFactory::CreateVideoSource(
268 cricket::VideoCapturer* capturer,
269 const blink::WebMediaConstraints& constraints) {
270 RTCMediaConstraints webrtc_constraints(constraints);
271 scoped_refptr<webrtc::VideoSourceInterface> source =
272 GetPcFactory()->CreateVideoSource(capturer, &webrtc_constraints).get();
273 return source;
276 const scoped_refptr<webrtc::PeerConnectionFactoryInterface>&
277 PeerConnectionDependencyFactory::GetPcFactory() {
278 if (!pc_factory_.get())
279 CreatePeerConnectionFactory();
280 CHECK(pc_factory_.get());
281 return pc_factory_;
285 void PeerConnectionDependencyFactory::WillDestroyCurrentMessageLoop() {
286 CleanupPeerConnectionFactory();
289 void PeerConnectionDependencyFactory::CreatePeerConnectionFactory() {
290 DCHECK(!pc_factory_.get());
291 DCHECK(!signaling_thread_);
292 DCHECK(!worker_thread_);
293 DCHECK(!network_manager_);
294 DCHECK(!socket_factory_);
295 DCHECK(!chrome_signaling_thread_.IsRunning());
296 DCHECK(!chrome_worker_thread_.IsRunning());
298 DVLOG(1) << "PeerConnectionDependencyFactory::CreatePeerConnectionFactory()";
300 base::MessageLoop::current()->AddDestructionObserver(this);
301 // To allow sending to the signaling/worker threads.
302 jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
303 jingle_glue::JingleThreadWrapper::current()->set_send_allowed(true);
305 CHECK(chrome_signaling_thread_.Start());
306 CHECK(chrome_worker_thread_.Start());
308 base::WaitableEvent start_worker_event(true, false);
309 chrome_worker_thread_.task_runner()->PostTask(
310 FROM_HERE,
311 base::Bind(&PeerConnectionDependencyFactory::InitializeWorkerThread,
312 base::Unretained(this), &worker_thread_, &start_worker_event));
314 base::WaitableEvent create_network_manager_event(true, false);
315 chrome_worker_thread_.task_runner()->PostTask(
316 FROM_HERE,
317 base::Bind(&PeerConnectionDependencyFactory::
318 CreateIpcNetworkManagerOnWorkerThread,
319 base::Unretained(this), &create_network_manager_event));
321 start_worker_event.Wait();
322 create_network_manager_event.Wait();
324 CHECK(worker_thread_);
326 // Init SSL, which will be needed by PeerConnection.
327 #if defined(USE_OPENSSL)
328 if (!rtc::InitializeSSL()) {
329 LOG(ERROR) << "Failed on InitializeSSL.";
330 NOTREACHED();
331 return;
333 #else
334 // TODO(ronghuawu): Replace this call with InitializeSSL.
335 net::EnsureNSSSSLInit();
336 #endif
338 base::WaitableEvent start_signaling_event(true, false);
339 chrome_signaling_thread_.task_runner()->PostTask(
340 FROM_HERE,
341 base::Bind(&PeerConnectionDependencyFactory::InitializeSignalingThread,
342 base::Unretained(this),
343 RenderThreadImpl::current()->GetGpuFactories(),
344 &start_signaling_event));
346 start_signaling_event.Wait();
347 CHECK(signaling_thread_);
350 void PeerConnectionDependencyFactory::InitializeSignalingThread(
351 const scoped_refptr<media::GpuVideoAcceleratorFactories>& gpu_factories,
352 base::WaitableEvent* event) {
353 DCHECK(chrome_signaling_thread_.task_runner()->BelongsToCurrentThread());
354 DCHECK(worker_thread_);
355 DCHECK(p2p_socket_dispatcher_.get());
357 jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
358 jingle_glue::JingleThreadWrapper::current()->set_send_allowed(true);
359 signaling_thread_ = jingle_glue::JingleThreadWrapper::current();
361 EnsureWebRtcAudioDeviceImpl();
363 socket_factory_.reset(
364 new IpcPacketSocketFactory(p2p_socket_dispatcher_.get()));
366 scoped_ptr<cricket::WebRtcVideoDecoderFactory> decoder_factory;
367 scoped_ptr<cricket::WebRtcVideoEncoderFactory> encoder_factory;
369 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
370 if (gpu_factories && gpu_factories->IsGpuVideoAcceleratorEnabled()) {
371 if (!cmd_line->HasSwitch(switches::kDisableWebRtcHWDecoding))
372 decoder_factory.reset(new RTCVideoDecoderFactory(gpu_factories));
374 if (!cmd_line->HasSwitch(switches::kDisableWebRtcHWEncoding))
375 encoder_factory.reset(new RTCVideoEncoderFactory(gpu_factories));
378 #if defined(OS_ANDROID)
379 if (!media::MediaCodecBridge::SupportsSetParameters())
380 encoder_factory.reset();
381 #endif
383 pc_factory_ = webrtc::CreatePeerConnectionFactory(
384 worker_thread_, signaling_thread_, audio_device_.get(),
385 encoder_factory.release(), decoder_factory.release());
386 CHECK(pc_factory_.get());
388 webrtc::PeerConnectionFactoryInterface::Options factory_options;
389 factory_options.disable_sctp_data_channels = false;
390 factory_options.disable_encryption =
391 cmd_line->HasSwitch(switches::kDisableWebRtcEncryption);
392 if (cmd_line->HasSwitch(switches::kEnableWebRtcDtls12))
393 factory_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
394 pc_factory_->SetOptions(factory_options);
396 event->Signal();
399 bool PeerConnectionDependencyFactory::PeerConnectionFactoryCreated() {
400 return pc_factory_.get() != NULL;
403 scoped_refptr<webrtc::PeerConnectionInterface>
404 PeerConnectionDependencyFactory::CreatePeerConnection(
405 const webrtc::PeerConnectionInterface::RTCConfiguration& config,
406 const webrtc::MediaConstraintsInterface* constraints,
407 blink::WebFrame* web_frame,
408 webrtc::PeerConnectionObserver* observer) {
409 CHECK(web_frame);
410 CHECK(observer);
411 if (!GetPcFactory().get())
412 return NULL;
414 // Copy the flag from Preference associated with this WebFrame.
415 bool enable_multiple_routes = true;
416 PeerConnectionIdentityService* identity_service =
417 new PeerConnectionIdentityService(
418 GURL(web_frame->document().url()),
419 GURL(web_frame->document().firstPartyForCookies()));
421 if (web_frame && web_frame->view()) {
422 RenderViewImpl* renderer_view_impl =
423 RenderViewImpl::FromWebView(web_frame->view());
424 if (renderer_view_impl) {
425 enable_multiple_routes = renderer_view_impl->renderer_preferences()
426 .enable_webrtc_multiple_routes;
430 scoped_refptr<P2PPortAllocatorFactory> pa_factory =
431 new rtc::RefCountedObject<P2PPortAllocatorFactory>(
432 p2p_socket_dispatcher_.get(), network_manager_, socket_factory_.get(),
433 GURL(web_frame->document().url().spec()).GetOrigin(),
434 enable_multiple_routes);
436 return GetPcFactory()->CreatePeerConnection(config,
437 constraints,
438 pa_factory.get(),
439 identity_service,
440 observer).get();
443 scoped_refptr<webrtc::MediaStreamInterface>
444 PeerConnectionDependencyFactory::CreateLocalMediaStream(
445 const std::string& label) {
446 return GetPcFactory()->CreateLocalMediaStream(label).get();
449 scoped_refptr<webrtc::AudioSourceInterface>
450 PeerConnectionDependencyFactory::CreateLocalAudioSource(
451 const webrtc::MediaConstraintsInterface* constraints) {
452 scoped_refptr<webrtc::AudioSourceInterface> source =
453 GetPcFactory()->CreateAudioSource(constraints).get();
454 return source;
457 void PeerConnectionDependencyFactory::CreateLocalAudioTrack(
458 const blink::WebMediaStreamTrack& track) {
459 blink::WebMediaStreamSource source = track.source();
460 DCHECK_EQ(source.type(), blink::WebMediaStreamSource::TypeAudio);
461 MediaStreamAudioSource* source_data =
462 static_cast<MediaStreamAudioSource*>(source.extraData());
464 scoped_refptr<WebAudioCapturerSource> webaudio_source;
465 if (!source_data) {
466 if (source.requiresAudioConsumer()) {
467 // We're adding a WebAudio MediaStream.
468 // Create a specific capturer for each WebAudio consumer.
469 webaudio_source = CreateWebAudioSource(&source);
470 source_data =
471 static_cast<MediaStreamAudioSource*>(source.extraData());
472 } else {
473 // TODO(perkj): Implement support for sources from
474 // remote MediaStreams.
475 NOTIMPLEMENTED();
476 return;
480 // Creates an adapter to hold all the libjingle objects.
481 scoped_refptr<WebRtcLocalAudioTrackAdapter> adapter(
482 WebRtcLocalAudioTrackAdapter::Create(track.id().utf8(),
483 source_data->local_audio_source()));
484 static_cast<webrtc::AudioTrackInterface*>(adapter.get())->set_enabled(
485 track.isEnabled());
487 // TODO(xians): Merge |source| to the capturer(). We can't do this today
488 // because only one capturer() is supported while one |source| is created
489 // for each audio track.
490 scoped_ptr<WebRtcLocalAudioTrack> audio_track(new WebRtcLocalAudioTrack(
491 adapter.get(), source_data->GetAudioCapturer(), webaudio_source.get()));
493 StartLocalAudioTrack(audio_track.get());
495 // Pass the ownership of the native local audio track to the blink track.
496 blink::WebMediaStreamTrack writable_track = track;
497 writable_track.setExtraData(audio_track.release());
500 void PeerConnectionDependencyFactory::StartLocalAudioTrack(
501 WebRtcLocalAudioTrack* audio_track) {
502 // Start the audio track. This will hook the |audio_track| to the capturer
503 // as the sink of the audio, and only start the source of the capturer if
504 // it is the first audio track connecting to the capturer.
505 audio_track->Start();
508 scoped_refptr<WebAudioCapturerSource>
509 PeerConnectionDependencyFactory::CreateWebAudioSource(
510 blink::WebMediaStreamSource* source) {
511 DVLOG(1) << "PeerConnectionDependencyFactory::CreateWebAudioSource()";
513 scoped_refptr<WebAudioCapturerSource>
514 webaudio_capturer_source(new WebAudioCapturerSource(*source));
515 MediaStreamAudioSource* source_data = new MediaStreamAudioSource();
517 // Use the current default capturer for the WebAudio track so that the
518 // WebAudio track can pass a valid delay value and |need_audio_processing|
519 // flag to PeerConnection.
520 // TODO(xians): Remove this after moving APM to Chrome.
521 if (GetWebRtcAudioDevice()) {
522 source_data->SetAudioCapturer(
523 GetWebRtcAudioDevice()->GetDefaultCapturer());
526 // Create a LocalAudioSource object which holds audio options.
527 // SetLocalAudioSource() affects core audio parts in third_party/Libjingle.
528 source_data->SetLocalAudioSource(CreateLocalAudioSource(NULL).get());
529 source->setExtraData(source_data);
531 // Replace the default source with WebAudio as source instead.
532 source->addAudioConsumer(webaudio_capturer_source.get());
534 return webaudio_capturer_source;
537 scoped_refptr<webrtc::VideoTrackInterface>
538 PeerConnectionDependencyFactory::CreateLocalVideoTrack(
539 const std::string& id,
540 webrtc::VideoSourceInterface* source) {
541 return GetPcFactory()->CreateVideoTrack(id, source).get();
544 scoped_refptr<webrtc::VideoTrackInterface>
545 PeerConnectionDependencyFactory::CreateLocalVideoTrack(
546 const std::string& id, cricket::VideoCapturer* capturer) {
547 if (!capturer) {
548 LOG(ERROR) << "CreateLocalVideoTrack called with null VideoCapturer.";
549 return NULL;
552 // Create video source from the |capturer|.
553 scoped_refptr<webrtc::VideoSourceInterface> source =
554 GetPcFactory()->CreateVideoSource(capturer, NULL).get();
556 // Create native track from the source.
557 return GetPcFactory()->CreateVideoTrack(id, source.get()).get();
560 webrtc::SessionDescriptionInterface*
561 PeerConnectionDependencyFactory::CreateSessionDescription(
562 const std::string& type,
563 const std::string& sdp,
564 webrtc::SdpParseError* error) {
565 return webrtc::CreateSessionDescription(type, sdp, error);
568 webrtc::IceCandidateInterface*
569 PeerConnectionDependencyFactory::CreateIceCandidate(
570 const std::string& sdp_mid,
571 int sdp_mline_index,
572 const std::string& sdp) {
573 return webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, sdp, nullptr);
576 WebRtcAudioDeviceImpl*
577 PeerConnectionDependencyFactory::GetWebRtcAudioDevice() {
578 return audio_device_.get();
581 void PeerConnectionDependencyFactory::InitializeWorkerThread(
582 rtc::Thread** thread,
583 base::WaitableEvent* event) {
584 jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
585 jingle_glue::JingleThreadWrapper::current()->set_send_allowed(true);
586 *thread = jingle_glue::JingleThreadWrapper::current();
587 event->Signal();
590 void PeerConnectionDependencyFactory::TryScheduleStunProbeTrial() {
591 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
593 if (!cmd_line->HasSwitch(switches::kWebRtcStunProbeTrialParameter))
594 return;
596 GetPcFactory();
598 // The underneath IPC channel has to be connected before sending any IPC
599 // message.
600 if (!p2p_socket_dispatcher_->connected()) {
601 base::MessageLoop::current()->PostDelayedTask(
602 FROM_HERE,
603 base::Bind(&PeerConnectionDependencyFactory::TryScheduleStunProbeTrial,
604 base::Unretained(this)),
605 base::TimeDelta::FromSeconds(1));
606 return;
609 const std::string params =
610 cmd_line->GetSwitchValueASCII(switches::kWebRtcStunProbeTrialParameter);
612 chrome_worker_thread_.task_runner()->PostDelayedTask(
613 FROM_HERE,
614 base::Bind(
615 &PeerConnectionDependencyFactory::StartStunProbeTrialOnWorkerThread,
616 base::Unretained(this), params),
617 base::TimeDelta::FromMilliseconds(kExperimentStartDelayMs));
620 void PeerConnectionDependencyFactory::StartStunProbeTrialOnWorkerThread(
621 const std::string& params) {
622 DCHECK(chrome_worker_thread_.task_runner()->BelongsToCurrentThread());
623 rtc::NetworkManager::NetworkList networks;
624 network_manager_->GetNetworks(&networks);
625 stun_prober_ = StartStunProbeTrial(networks, params, socket_factory_.get());
628 void PeerConnectionDependencyFactory::CreateIpcNetworkManagerOnWorkerThread(
629 base::WaitableEvent* event) {
630 DCHECK(chrome_worker_thread_.task_runner()->BelongsToCurrentThread());
631 network_manager_ = new IpcNetworkManager(p2p_socket_dispatcher_.get());
632 event->Signal();
635 void PeerConnectionDependencyFactory::DeleteIpcNetworkManager() {
636 DCHECK(chrome_worker_thread_.task_runner()->BelongsToCurrentThread());
637 delete network_manager_;
638 network_manager_ = NULL;
641 void PeerConnectionDependencyFactory::CleanupPeerConnectionFactory() {
642 DVLOG(1) << "PeerConnectionDependencyFactory::CleanupPeerConnectionFactory()";
643 pc_factory_ = NULL;
644 if (network_manager_) {
645 // The network manager needs to free its resources on the thread they were
646 // created, which is the worked thread.
647 if (chrome_worker_thread_.IsRunning()) {
648 chrome_worker_thread_.task_runner()->PostTask(
649 FROM_HERE,
650 base::Bind(&PeerConnectionDependencyFactory::DeleteIpcNetworkManager,
651 base::Unretained(this)));
652 // Stopping the thread will wait until all tasks have been
653 // processed before returning. We wait for the above task to finish before
654 // letting the the function continue to avoid any potential race issues.
655 chrome_worker_thread_.Stop();
656 } else {
657 NOTREACHED() << "Worker thread not running.";
662 scoped_refptr<WebRtcAudioCapturer>
663 PeerConnectionDependencyFactory::CreateAudioCapturer(
664 int render_frame_id,
665 const StreamDeviceInfo& device_info,
666 const blink::WebMediaConstraints& constraints,
667 MediaStreamAudioSource* audio_source) {
668 // TODO(xians): Handle the cases when gUM is called without a proper render
669 // view, for example, by an extension.
670 DCHECK_GE(render_frame_id, 0);
672 EnsureWebRtcAudioDeviceImpl();
673 DCHECK(GetWebRtcAudioDevice());
674 return WebRtcAudioCapturer::CreateCapturer(
675 render_frame_id, device_info, constraints, GetWebRtcAudioDevice(),
676 audio_source);
679 scoped_refptr<base::SingleThreadTaskRunner>
680 PeerConnectionDependencyFactory::GetWebRtcWorkerThread() const {
681 DCHECK(CalledOnValidThread());
682 return chrome_worker_thread_.IsRunning() ? chrome_worker_thread_.task_runner()
683 : nullptr;
686 scoped_refptr<base::SingleThreadTaskRunner>
687 PeerConnectionDependencyFactory::GetWebRtcSignalingThread() const {
688 DCHECK(CalledOnValidThread());
689 return chrome_signaling_thread_.IsRunning()
690 ? chrome_signaling_thread_.task_runner()
691 : nullptr;
694 void PeerConnectionDependencyFactory::EnsureWebRtcAudioDeviceImpl() {
695 if (audio_device_.get())
696 return;
698 audio_device_ = new WebRtcAudioDeviceImpl();
701 } // namespace content