Re-subimission of https://codereview.chromium.org/1041213003/
[chromium-blink-merge.git] / content / renderer / media / webrtc / peer_connection_dependency_factory.cc
blob0bf8b061a87e711bc17c7725f27da0430119829e
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/strings/utf_string_conversions.h"
11 #include "base/synchronization/waitable_event.h"
12 #include "content/common/media/media_stream_messages.h"
13 #include "content/public/common/content_switches.h"
14 #include "content/public/common/renderer_preferences.h"
15 #include "content/renderer/media/media_stream.h"
16 #include "content/renderer/media/media_stream_audio_processor.h"
17 #include "content/renderer/media/media_stream_audio_processor_options.h"
18 #include "content/renderer/media/media_stream_audio_source.h"
19 #include "content/renderer/media/media_stream_video_source.h"
20 #include "content/renderer/media/media_stream_video_track.h"
21 #include "content/renderer/media/peer_connection_identity_service.h"
22 #include "content/renderer/media/rtc_media_constraints.h"
23 #include "content/renderer/media/rtc_peer_connection_handler.h"
24 #include "content/renderer/media/rtc_video_decoder_factory.h"
25 #include "content/renderer/media/rtc_video_encoder_factory.h"
26 #include "content/renderer/media/webaudio_capturer_source.h"
27 #include "content/renderer/media/webrtc/webrtc_local_audio_track_adapter.h"
28 #include "content/renderer/media/webrtc/webrtc_video_capturer_adapter.h"
29 #include "content/renderer/media/webrtc_audio_device_impl.h"
30 #include "content/renderer/media/webrtc_local_audio_track.h"
31 #include "content/renderer/media/webrtc_logging.h"
32 #include "content/renderer/media/webrtc_uma_histograms.h"
33 #include "content/renderer/p2p/ipc_network_manager.h"
34 #include "content/renderer/p2p/ipc_socket_factory.h"
35 #include "content/renderer/p2p/port_allocator.h"
36 #include "content/renderer/render_thread_impl.h"
37 #include "content/renderer/render_view_impl.h"
38 #include "jingle/glue/thread_wrapper.h"
39 #include "media/renderers/gpu_video_accelerator_factories.h"
40 #include "third_party/WebKit/public/platform/WebMediaConstraints.h"
41 #include "third_party/WebKit/public/platform/WebMediaStream.h"
42 #include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
43 #include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
44 #include "third_party/WebKit/public/platform/WebURL.h"
45 #include "third_party/WebKit/public/web/WebDocument.h"
46 #include "third_party/WebKit/public/web/WebFrame.h"
47 #include "third_party/libjingle/source/talk/app/webrtc/mediaconstraintsinterface.h"
49 #if defined(USE_OPENSSL)
50 #include "third_party/webrtc/base/ssladapter.h"
51 #else
52 #include "net/socket/nss_ssl_util.h"
53 #endif
55 #if defined(OS_ANDROID)
56 #include "media/base/android/media_codec_bridge.h"
57 #endif
59 namespace content {
61 // Map of corresponding media constraints and platform effects.
62 struct {
63 const char* constraint;
64 const media::AudioParameters::PlatformEffectsMask effect;
65 } const kConstraintEffectMap[] = {
66 { content::kMediaStreamAudioDucking,
67 media::AudioParameters::DUCKING },
68 { webrtc::MediaConstraintsInterface::kEchoCancellation,
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;
104 } else if (kConstraintEffectMap[i].effect ==
105 media::AudioParameters::DUCKING && value && !is_mandatory) {
106 // Special handling of the DUCKING flag that sets the optional
107 // constraint to |false| to match what the device will support.
108 constraints->AddOptional(kConstraintEffectMap[i].constraint,
109 webrtc::MediaConstraintsInterface::kValueFalse, true);
110 // No need to modify |effects| since the ducking flag is already off.
111 DCHECK((*effects & media::AudioParameters::DUCKING) == 0);
117 class P2PPortAllocatorFactory : public webrtc::PortAllocatorFactoryInterface {
118 public:
119 P2PPortAllocatorFactory(P2PSocketDispatcher* socket_dispatcher,
120 rtc::NetworkManager* network_manager,
121 rtc::PacketSocketFactory* socket_factory,
122 const GURL& origin,
123 bool enable_multiple_routes)
124 : socket_dispatcher_(socket_dispatcher),
125 network_manager_(network_manager),
126 socket_factory_(socket_factory),
127 origin_(origin),
128 enable_multiple_routes_(enable_multiple_routes) {}
130 cricket::PortAllocator* CreatePortAllocator(
131 const std::vector<StunConfiguration>& stun_servers,
132 const std::vector<TurnConfiguration>& turn_configurations) override {
133 P2PPortAllocator::Config config;
134 for (size_t i = 0; i < stun_servers.size(); ++i) {
135 config.stun_servers.insert(rtc::SocketAddress(
136 stun_servers[i].server.hostname(),
137 stun_servers[i].server.port()));
139 for (size_t i = 0; i < turn_configurations.size(); ++i) {
140 P2PPortAllocator::Config::RelayServerConfig relay_config;
141 relay_config.server_address = turn_configurations[i].server.hostname();
142 relay_config.port = turn_configurations[i].server.port();
143 relay_config.username = turn_configurations[i].username;
144 relay_config.password = turn_configurations[i].password;
145 relay_config.transport_type = turn_configurations[i].transport_type;
146 relay_config.secure = turn_configurations[i].secure;
147 config.relays.push_back(relay_config);
149 // Use turn servers as stun servers.
150 config.stun_servers.insert(rtc::SocketAddress(
151 turn_configurations[i].server.hostname(),
152 turn_configurations[i].server.port()));
154 config.enable_multiple_routes = enable_multiple_routes_;
156 return new P2PPortAllocator(
157 socket_dispatcher_.get(), network_manager_,
158 socket_factory_, config, origin_);
161 protected:
162 ~P2PPortAllocatorFactory() override {}
164 private:
165 scoped_refptr<P2PSocketDispatcher> socket_dispatcher_;
166 // |network_manager_| and |socket_factory_| are a weak references, owned by
167 // PeerConnectionDependencyFactory.
168 rtc::NetworkManager* network_manager_;
169 rtc::PacketSocketFactory* socket_factory_;
170 // The origin URL of the WebFrame that created the
171 // P2PPortAllocatorFactory.
172 GURL origin_;
173 // When false, only 'any' address (all 0s) will be bound for address
174 // discovery.
175 bool enable_multiple_routes_;
178 PeerConnectionDependencyFactory::PeerConnectionDependencyFactory(
179 P2PSocketDispatcher* p2p_socket_dispatcher)
180 : network_manager_(NULL),
181 p2p_socket_dispatcher_(p2p_socket_dispatcher),
182 signaling_thread_(NULL),
183 worker_thread_(NULL),
184 chrome_signaling_thread_("Chrome_libJingle_Signaling"),
185 chrome_worker_thread_("Chrome_libJingle_WorkerThread") {
188 PeerConnectionDependencyFactory::~PeerConnectionDependencyFactory() {
189 DVLOG(1) << "~PeerConnectionDependencyFactory()";
190 DCHECK(pc_factory_ == NULL);
193 blink::WebRTCPeerConnectionHandler*
194 PeerConnectionDependencyFactory::CreateRTCPeerConnectionHandler(
195 blink::WebRTCPeerConnectionHandlerClient* client) {
196 // Save histogram data so we can see how much PeerConnetion is used.
197 // The histogram counts the number of calls to the JS API
198 // webKitRTCPeerConnection.
199 UpdateWebRTCMethodCount(WEBKIT_RTC_PEER_CONNECTION);
201 return new RTCPeerConnectionHandler(client, this);
204 bool PeerConnectionDependencyFactory::InitializeMediaStreamAudioSource(
205 int render_frame_id,
206 const blink::WebMediaConstraints& audio_constraints,
207 MediaStreamAudioSource* source_data) {
208 DVLOG(1) << "InitializeMediaStreamAudioSources()";
210 // Do additional source initialization if the audio source is a valid
211 // microphone or tab audio.
212 RTCMediaConstraints native_audio_constraints(audio_constraints);
213 MediaAudioConstraints::ApplyFixedAudioConstraints(&native_audio_constraints);
215 StreamDeviceInfo device_info = source_data->device_info();
216 RTCMediaConstraints constraints = native_audio_constraints;
217 // May modify both |constraints| and |effects|.
218 HarmonizeConstraintsAndEffects(&constraints,
219 &device_info.device.input.effects);
221 scoped_refptr<WebRtcAudioCapturer> capturer(CreateAudioCapturer(
222 render_frame_id, device_info, audio_constraints, source_data));
223 if (!capturer.get()) {
224 const std::string log_string =
225 "PCDF::InitializeMediaStreamAudioSource: fails to create capturer";
226 WebRtcLogMessage(log_string);
227 DVLOG(1) << log_string;
228 // TODO(xians): Don't we need to check if source_observer is observing
229 // something? If not, then it looks like we have a leak here.
230 // OTOH, if it _is_ observing something, then the callback might
231 // be called multiple times which is likely also a bug.
232 return false;
234 source_data->SetAudioCapturer(capturer.get());
236 // Creates a LocalAudioSource object which holds audio options.
237 // TODO(xians): The option should apply to the track instead of the source.
238 // TODO(perkj): Move audio constraints parsing to Chrome.
239 // Currently there are a few constraints that are parsed by libjingle and
240 // the state is set to ended if parsing fails.
241 scoped_refptr<webrtc::AudioSourceInterface> rtc_source(
242 CreateLocalAudioSource(&constraints).get());
243 if (rtc_source->state() != webrtc::MediaSourceInterface::kLive) {
244 DLOG(WARNING) << "Failed to create rtc LocalAudioSource.";
245 return false;
247 source_data->SetLocalAudioSource(rtc_source.get());
248 return true;
251 WebRtcVideoCapturerAdapter*
252 PeerConnectionDependencyFactory::CreateVideoCapturer(
253 bool is_screeencast) {
254 // We need to make sure the libjingle thread wrappers have been created
255 // before we can use an instance of a WebRtcVideoCapturerAdapter. This is
256 // since the base class of WebRtcVideoCapturerAdapter is a
257 // cricket::VideoCapturer and it uses the libjingle thread wrappers.
258 if (!GetPcFactory().get())
259 return NULL;
260 return new WebRtcVideoCapturerAdapter(is_screeencast);
263 scoped_refptr<webrtc::VideoSourceInterface>
264 PeerConnectionDependencyFactory::CreateVideoSource(
265 cricket::VideoCapturer* capturer,
266 const blink::WebMediaConstraints& constraints) {
267 RTCMediaConstraints webrtc_constraints(constraints);
268 scoped_refptr<webrtc::VideoSourceInterface> source =
269 GetPcFactory()->CreateVideoSource(capturer, &webrtc_constraints).get();
270 return source;
273 const scoped_refptr<webrtc::PeerConnectionFactoryInterface>&
274 PeerConnectionDependencyFactory::GetPcFactory() {
275 if (!pc_factory_.get())
276 CreatePeerConnectionFactory();
277 CHECK(pc_factory_.get());
278 return pc_factory_;
282 void PeerConnectionDependencyFactory::WillDestroyCurrentMessageLoop() {
283 CleanupPeerConnectionFactory();
286 void PeerConnectionDependencyFactory::CreatePeerConnectionFactory() {
287 DCHECK(!pc_factory_.get());
288 DCHECK(!signaling_thread_);
289 DCHECK(!worker_thread_);
290 DCHECK(!network_manager_);
291 DCHECK(!socket_factory_);
292 DCHECK(!chrome_signaling_thread_.IsRunning());
293 DCHECK(!chrome_worker_thread_.IsRunning());
295 DVLOG(1) << "PeerConnectionDependencyFactory::CreatePeerConnectionFactory()";
297 base::MessageLoop::current()->AddDestructionObserver(this);
298 // To allow sending to the signaling/worker threads.
299 jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
300 jingle_glue::JingleThreadWrapper::current()->set_send_allowed(true);
302 CHECK(chrome_signaling_thread_.Start());
303 CHECK(chrome_worker_thread_.Start());
305 base::WaitableEvent start_worker_event(true, false);
306 chrome_worker_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
307 &PeerConnectionDependencyFactory::InitializeWorkerThread,
308 base::Unretained(this),
309 &worker_thread_,
310 &start_worker_event));
312 base::WaitableEvent create_network_manager_event(true, false);
313 chrome_worker_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
314 &PeerConnectionDependencyFactory::CreateIpcNetworkManagerOnWorkerThread,
315 base::Unretained(this),
316 &create_network_manager_event));
318 start_worker_event.Wait();
319 create_network_manager_event.Wait();
321 CHECK(worker_thread_);
323 // Init SSL, which will be needed by PeerConnection.
324 #if defined(USE_OPENSSL)
325 if (!rtc::InitializeSSL()) {
326 LOG(ERROR) << "Failed on InitializeSSL.";
327 NOTREACHED();
328 return;
330 #else
331 // TODO(ronghuawu): Replace this call with InitializeSSL.
332 net::EnsureNSSSSLInit();
333 #endif
335 base::WaitableEvent start_signaling_event(true, false);
336 chrome_signaling_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
337 &PeerConnectionDependencyFactory::InitializeSignalingThread,
338 base::Unretained(this),
339 RenderThreadImpl::current()->GetGpuFactories(),
340 &start_signaling_event));
342 start_signaling_event.Wait();
343 CHECK(signaling_thread_);
346 void PeerConnectionDependencyFactory::InitializeSignalingThread(
347 const scoped_refptr<media::GpuVideoAcceleratorFactories>& gpu_factories,
348 base::WaitableEvent* event) {
349 DCHECK(chrome_signaling_thread_.task_runner()->BelongsToCurrentThread());
350 DCHECK(worker_thread_);
351 DCHECK(p2p_socket_dispatcher_.get());
353 jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
354 jingle_glue::JingleThreadWrapper::current()->set_send_allowed(true);
355 signaling_thread_ = jingle_glue::JingleThreadWrapper::current();
357 EnsureWebRtcAudioDeviceImpl();
359 socket_factory_.reset(
360 new IpcPacketSocketFactory(p2p_socket_dispatcher_.get()));
362 scoped_ptr<cricket::WebRtcVideoDecoderFactory> decoder_factory;
363 scoped_ptr<cricket::WebRtcVideoEncoderFactory> encoder_factory;
365 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
366 if (gpu_factories.get()) {
367 if (!cmd_line->HasSwitch(switches::kDisableWebRtcHWDecoding))
368 decoder_factory.reset(new RTCVideoDecoderFactory(gpu_factories));
370 if (!cmd_line->HasSwitch(switches::kDisableWebRtcHWEncoding))
371 encoder_factory.reset(new RTCVideoEncoderFactory(gpu_factories));
374 #if defined(OS_ANDROID)
375 if (!media::MediaCodecBridge::SupportsSetParameters())
376 encoder_factory.reset();
377 #endif
379 pc_factory_ = webrtc::CreatePeerConnectionFactory(
380 worker_thread_, signaling_thread_, audio_device_.get(),
381 encoder_factory.release(), decoder_factory.release());
382 CHECK(pc_factory_.get());
384 webrtc::PeerConnectionFactoryInterface::Options factory_options;
385 factory_options.disable_sctp_data_channels = false;
386 factory_options.disable_encryption =
387 cmd_line->HasSwitch(switches::kDisableWebRtcEncryption);
388 pc_factory_->SetOptions(factory_options);
390 event->Signal();
393 bool PeerConnectionDependencyFactory::PeerConnectionFactoryCreated() {
394 return pc_factory_.get() != NULL;
397 scoped_refptr<webrtc::PeerConnectionInterface>
398 PeerConnectionDependencyFactory::CreatePeerConnection(
399 const webrtc::PeerConnectionInterface::RTCConfiguration& config,
400 const webrtc::MediaConstraintsInterface* constraints,
401 blink::WebFrame* web_frame,
402 webrtc::PeerConnectionObserver* observer) {
403 CHECK(web_frame);
404 CHECK(observer);
405 if (!GetPcFactory().get())
406 return NULL;
408 // Copy the flag from Preference associated with this WebFrame.
409 bool enable_multiple_routes = true;
410 if (web_frame && web_frame->view()) {
411 RenderViewImpl* renderer_view_impl =
412 RenderViewImpl::FromWebView(web_frame->view());
413 if (renderer_view_impl) {
414 enable_multiple_routes = renderer_view_impl->renderer_preferences()
415 .enable_webrtc_multiple_routes;
419 scoped_refptr<P2PPortAllocatorFactory> pa_factory =
420 new rtc::RefCountedObject<P2PPortAllocatorFactory>(
421 p2p_socket_dispatcher_.get(), network_manager_, socket_factory_.get(),
422 GURL(web_frame->document().url().spec()).GetOrigin(),
423 enable_multiple_routes);
425 PeerConnectionIdentityService* identity_service =
426 new PeerConnectionIdentityService(
427 GURL(web_frame->document().url().spec()).GetOrigin());
429 return GetPcFactory()->CreatePeerConnection(config,
430 constraints,
431 pa_factory.get(),
432 identity_service,
433 observer).get();
436 scoped_refptr<webrtc::MediaStreamInterface>
437 PeerConnectionDependencyFactory::CreateLocalMediaStream(
438 const std::string& label) {
439 return GetPcFactory()->CreateLocalMediaStream(label).get();
442 scoped_refptr<webrtc::AudioSourceInterface>
443 PeerConnectionDependencyFactory::CreateLocalAudioSource(
444 const webrtc::MediaConstraintsInterface* constraints) {
445 scoped_refptr<webrtc::AudioSourceInterface> source =
446 GetPcFactory()->CreateAudioSource(constraints).get();
447 return source;
450 void PeerConnectionDependencyFactory::CreateLocalAudioTrack(
451 const blink::WebMediaStreamTrack& track) {
452 blink::WebMediaStreamSource source = track.source();
453 DCHECK_EQ(source.type(), blink::WebMediaStreamSource::TypeAudio);
454 MediaStreamAudioSource* source_data =
455 static_cast<MediaStreamAudioSource*>(source.extraData());
457 scoped_refptr<WebAudioCapturerSource> webaudio_source;
458 if (!source_data) {
459 if (source.requiresAudioConsumer()) {
460 // We're adding a WebAudio MediaStream.
461 // Create a specific capturer for each WebAudio consumer.
462 webaudio_source = CreateWebAudioSource(&source);
463 source_data =
464 static_cast<MediaStreamAudioSource*>(source.extraData());
465 } else {
466 // TODO(perkj): Implement support for sources from
467 // remote MediaStreams.
468 NOTIMPLEMENTED();
469 return;
473 // Creates an adapter to hold all the libjingle objects.
474 scoped_refptr<WebRtcLocalAudioTrackAdapter> adapter(
475 WebRtcLocalAudioTrackAdapter::Create(track.id().utf8(),
476 source_data->local_audio_source()));
477 static_cast<webrtc::AudioTrackInterface*>(adapter.get())->set_enabled(
478 track.isEnabled());
480 // TODO(xians): Merge |source| to the capturer(). We can't do this today
481 // because only one capturer() is supported while one |source| is created
482 // for each audio track.
483 scoped_ptr<WebRtcLocalAudioTrack> audio_track(new WebRtcLocalAudioTrack(
484 adapter.get(), source_data->GetAudioCapturer(), webaudio_source.get()));
486 StartLocalAudioTrack(audio_track.get());
488 // Pass the ownership of the native local audio track to the blink track.
489 blink::WebMediaStreamTrack writable_track = track;
490 writable_track.setExtraData(audio_track.release());
493 void PeerConnectionDependencyFactory::StartLocalAudioTrack(
494 WebRtcLocalAudioTrack* audio_track) {
495 // Start the audio track. This will hook the |audio_track| to the capturer
496 // as the sink of the audio, and only start the source of the capturer if
497 // it is the first audio track connecting to the capturer.
498 audio_track->Start();
501 scoped_refptr<WebAudioCapturerSource>
502 PeerConnectionDependencyFactory::CreateWebAudioSource(
503 blink::WebMediaStreamSource* source) {
504 DVLOG(1) << "PeerConnectionDependencyFactory::CreateWebAudioSource()";
506 scoped_refptr<WebAudioCapturerSource>
507 webaudio_capturer_source(new WebAudioCapturerSource());
508 MediaStreamAudioSource* source_data = new MediaStreamAudioSource();
510 // Use the current default capturer for the WebAudio track so that the
511 // WebAudio track can pass a valid delay value and |need_audio_processing|
512 // flag to PeerConnection.
513 // TODO(xians): Remove this after moving APM to Chrome.
514 if (GetWebRtcAudioDevice()) {
515 source_data->SetAudioCapturer(
516 GetWebRtcAudioDevice()->GetDefaultCapturer());
519 // Create a LocalAudioSource object which holds audio options.
520 // SetLocalAudioSource() affects core audio parts in third_party/Libjingle.
521 source_data->SetLocalAudioSource(CreateLocalAudioSource(NULL).get());
522 source->setExtraData(source_data);
524 // Replace the default source with WebAudio as source instead.
525 source->addAudioConsumer(webaudio_capturer_source.get());
527 return webaudio_capturer_source;
530 scoped_refptr<webrtc::VideoTrackInterface>
531 PeerConnectionDependencyFactory::CreateLocalVideoTrack(
532 const std::string& id,
533 webrtc::VideoSourceInterface* source) {
534 return GetPcFactory()->CreateVideoTrack(id, source).get();
537 scoped_refptr<webrtc::VideoTrackInterface>
538 PeerConnectionDependencyFactory::CreateLocalVideoTrack(
539 const std::string& id, cricket::VideoCapturer* capturer) {
540 if (!capturer) {
541 LOG(ERROR) << "CreateLocalVideoTrack called with null VideoCapturer.";
542 return NULL;
545 // Create video source from the |capturer|.
546 scoped_refptr<webrtc::VideoSourceInterface> source =
547 GetPcFactory()->CreateVideoSource(capturer, NULL).get();
549 // Create native track from the source.
550 return GetPcFactory()->CreateVideoTrack(id, source.get()).get();
553 webrtc::SessionDescriptionInterface*
554 PeerConnectionDependencyFactory::CreateSessionDescription(
555 const std::string& type,
556 const std::string& sdp,
557 webrtc::SdpParseError* error) {
558 return webrtc::CreateSessionDescription(type, sdp, error);
561 webrtc::IceCandidateInterface*
562 PeerConnectionDependencyFactory::CreateIceCandidate(
563 const std::string& sdp_mid,
564 int sdp_mline_index,
565 const std::string& sdp) {
566 return webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, sdp);
569 WebRtcAudioDeviceImpl*
570 PeerConnectionDependencyFactory::GetWebRtcAudioDevice() {
571 return audio_device_.get();
574 void PeerConnectionDependencyFactory::InitializeWorkerThread(
575 rtc::Thread** thread,
576 base::WaitableEvent* event) {
577 jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
578 jingle_glue::JingleThreadWrapper::current()->set_send_allowed(true);
579 *thread = jingle_glue::JingleThreadWrapper::current();
580 event->Signal();
583 void PeerConnectionDependencyFactory::CreateIpcNetworkManagerOnWorkerThread(
584 base::WaitableEvent* event) {
585 DCHECK_EQ(base::MessageLoop::current(), chrome_worker_thread_.message_loop());
586 network_manager_ = new IpcNetworkManager(p2p_socket_dispatcher_.get());
587 event->Signal();
590 void PeerConnectionDependencyFactory::DeleteIpcNetworkManager() {
591 DCHECK_EQ(base::MessageLoop::current(), chrome_worker_thread_.message_loop());
592 delete network_manager_;
593 network_manager_ = NULL;
596 void PeerConnectionDependencyFactory::CleanupPeerConnectionFactory() {
597 DVLOG(1) << "PeerConnectionDependencyFactory::CleanupPeerConnectionFactory()";
598 pc_factory_ = NULL;
599 if (network_manager_) {
600 // The network manager needs to free its resources on the thread they were
601 // created, which is the worked thread.
602 if (chrome_worker_thread_.IsRunning()) {
603 chrome_worker_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
604 &PeerConnectionDependencyFactory::DeleteIpcNetworkManager,
605 base::Unretained(this)));
606 // Stopping the thread will wait until all tasks have been
607 // processed before returning. We wait for the above task to finish before
608 // letting the the function continue to avoid any potential race issues.
609 chrome_worker_thread_.Stop();
610 } else {
611 NOTREACHED() << "Worker thread not running.";
616 scoped_refptr<WebRtcAudioCapturer>
617 PeerConnectionDependencyFactory::CreateAudioCapturer(
618 int render_frame_id,
619 const StreamDeviceInfo& device_info,
620 const blink::WebMediaConstraints& constraints,
621 MediaStreamAudioSource* audio_source) {
622 // TODO(xians): Handle the cases when gUM is called without a proper render
623 // view, for example, by an extension.
624 DCHECK_GE(render_frame_id, 0);
626 EnsureWebRtcAudioDeviceImpl();
627 DCHECK(GetWebRtcAudioDevice());
628 return WebRtcAudioCapturer::CreateCapturer(
629 render_frame_id, device_info, constraints, GetWebRtcAudioDevice(),
630 audio_source);
633 scoped_refptr<base::MessageLoopProxy>
634 PeerConnectionDependencyFactory::GetWebRtcWorkerThread() const {
635 DCHECK(CalledOnValidThread());
636 return chrome_worker_thread_.message_loop_proxy();
639 scoped_refptr<base::MessageLoopProxy>
640 PeerConnectionDependencyFactory::GetWebRtcSignalingThread() const {
641 DCHECK(CalledOnValidThread());
642 return chrome_signaling_thread_.message_loop_proxy();
645 void PeerConnectionDependencyFactory::EnsureWebRtcAudioDeviceImpl() {
646 if (audio_device_.get())
647 return;
649 audio_device_ = new WebRtcAudioDeviceImpl();
652 } // namespace content