IndexedDBFactory now ForceCloses databases.
[chromium-blink-merge.git] / content / test / webrtc_audio_device_test.cc
blob3883443c320b317309187f2bc5a2ea99ad7628a1
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
3 // found in the LICENSE file.
5 #include "content/test/webrtc_audio_device_test.h"
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/compiler_specific.h"
10 #include "base/file_util.h"
11 #include "base/run_loop.h"
12 #include "base/synchronization/waitable_event.h"
13 #include "base/test/test_timeouts.h"
14 #include "content/browser/media/media_internals.h"
15 #include "content/browser/renderer_host/media/audio_input_renderer_host.h"
16 #include "content/browser/renderer_host/media/audio_mirroring_manager.h"
17 #include "content/browser/renderer_host/media/audio_renderer_host.h"
18 #include "content/browser/renderer_host/media/media_stream_manager.h"
19 #include "content/browser/renderer_host/media/mock_media_observer.h"
20 #include "content/common/media/media_param_traits.h"
21 #include "content/common/view_messages.h"
22 #include "content/public/browser/browser_thread.h"
23 #include "content/public/browser/resource_context.h"
24 #include "content/public/common/content_paths.h"
25 #include "content/public/test/test_browser_thread.h"
26 #include "content/renderer/media/audio_input_message_filter.h"
27 #include "content/renderer/media/audio_message_filter.h"
28 #include "content/renderer/media/webrtc_audio_device_impl.h"
29 #include "content/renderer/render_process.h"
30 #include "content/renderer/render_thread_impl.h"
31 #include "content/renderer/renderer_webkitplatformsupport_impl.h"
32 #include "media/audio/audio_parameters.h"
33 #include "media/base/audio_hardware_config.h"
34 #include "net/url_request/url_request_test_util.h"
35 #include "testing/gmock/include/gmock/gmock.h"
36 #include "testing/gtest/include/gtest/gtest.h"
37 #include "third_party/webrtc/voice_engine/include/voe_audio_processing.h"
38 #include "third_party/webrtc/voice_engine/include/voe_base.h"
39 #include "third_party/webrtc/voice_engine/include/voe_file.h"
40 #include "third_party/webrtc/voice_engine/include/voe_network.h"
42 #if defined(OS_WIN)
43 #include "base/win/scoped_com_initializer.h"
44 #endif
46 using media::AudioParameters;
47 using media::ChannelLayout;
48 using testing::_;
49 using testing::InvokeWithoutArgs;
50 using testing::Return;
51 using testing::StrEq;
53 namespace content {
55 // This class is a mock of the child process singleton which is needed
56 // to be able to create a RenderThread object.
57 class WebRTCMockRenderProcess : public RenderProcess {
58 public:
59 WebRTCMockRenderProcess() {}
60 virtual ~WebRTCMockRenderProcess() {}
62 // RenderProcess implementation.
63 virtual skia::PlatformCanvas* GetDrawingCanvas(
64 TransportDIB** memory, const gfx::Rect& rect) OVERRIDE {
65 return NULL;
67 virtual void ReleaseTransportDIB(TransportDIB* memory) OVERRIDE {}
68 virtual void AddBindings(int bindings) OVERRIDE {}
69 virtual int GetEnabledBindings() const OVERRIDE { return 0; }
70 virtual TransportDIB* CreateTransportDIB(size_t size) OVERRIDE {
71 return NULL;
73 virtual void FreeTransportDIB(TransportDIB*) OVERRIDE {}
75 private:
76 DISALLOW_COPY_AND_ASSIGN(WebRTCMockRenderProcess);
79 class TestAudioRendererHost : public AudioRendererHost {
80 public:
81 TestAudioRendererHost(
82 int render_process_id,
83 media::AudioManager* audio_manager,
84 AudioMirroringManager* mirroring_manager,
85 MediaInternals* media_internals,
86 MediaStreamManager* media_stream_manager,
87 IPC::Channel* channel)
88 : AudioRendererHost(render_process_id, audio_manager, mirroring_manager,
89 media_internals, media_stream_manager),
90 channel_(channel) {}
91 virtual bool Send(IPC::Message* message) OVERRIDE {
92 if (channel_)
93 return channel_->Send(message);
94 return false;
96 void ResetChannel() {
97 channel_ = NULL;
100 protected:
101 virtual ~TestAudioRendererHost() {}
103 private:
104 IPC::Channel* channel_;
107 class TestAudioInputRendererHost : public AudioInputRendererHost {
108 public:
109 TestAudioInputRendererHost(
110 media::AudioManager* audio_manager,
111 MediaStreamManager* media_stream_manager,
112 AudioMirroringManager* audio_mirroring_manager,
113 media::UserInputMonitor* user_input_monitor,
114 IPC::Channel* channel)
115 : AudioInputRendererHost(audio_manager, media_stream_manager,
116 audio_mirroring_manager, user_input_monitor),
117 channel_(channel) {}
118 virtual bool Send(IPC::Message* message) OVERRIDE {
119 if (channel_)
120 return channel_->Send(message);
121 return false;
123 void ResetChannel() {
124 channel_ = NULL;
127 protected:
128 virtual ~TestAudioInputRendererHost() {}
130 private:
131 IPC::Channel* channel_;
134 // Utility scoped class to replace the global content client's renderer for the
135 // duration of the test.
136 class ReplaceContentClientRenderer {
137 public:
138 explicit ReplaceContentClientRenderer(ContentRendererClient* new_renderer) {
139 saved_renderer_ = SetRendererClientForTesting(new_renderer);
141 ~ReplaceContentClientRenderer() {
142 // Restore the original renderer.
143 SetRendererClientForTesting(saved_renderer_);
145 private:
146 ContentRendererClient* saved_renderer_;
147 DISALLOW_COPY_AND_ASSIGN(ReplaceContentClientRenderer);
150 class MockRTCResourceContext : public ResourceContext {
151 public:
152 MockRTCResourceContext() : test_request_context_(NULL) {}
153 virtual ~MockRTCResourceContext() {}
155 void set_request_context(net::URLRequestContext* request_context) {
156 test_request_context_ = request_context;
159 // ResourceContext implementation:
160 virtual net::HostResolver* GetHostResolver() OVERRIDE {
161 return NULL;
163 virtual net::URLRequestContext* GetRequestContext() OVERRIDE {
164 return test_request_context_;
167 virtual bool AllowMicAccess(const GURL& origin) OVERRIDE {
168 return false;
171 virtual bool AllowCameraAccess(const GURL& origin) OVERRIDE {
172 return false;
175 virtual std::string GetMediaDeviceIDSalt() OVERRIDE {
176 return "";
179 private:
180 net::URLRequestContext* test_request_context_;
182 DISALLOW_COPY_AND_ASSIGN(MockRTCResourceContext);
185 ACTION_P(QuitMessageLoop, loop_or_proxy) {
186 loop_or_proxy->PostTask(FROM_HERE, base::MessageLoop::QuitClosure());
189 MAYBE_WebRTCAudioDeviceTest::MAYBE_WebRTCAudioDeviceTest()
190 : render_thread_(NULL), audio_hardware_config_(NULL),
191 has_input_devices_(false), has_output_devices_(false) {
194 MAYBE_WebRTCAudioDeviceTest::~MAYBE_WebRTCAudioDeviceTest() {}
196 void MAYBE_WebRTCAudioDeviceTest::SetUp() {
197 // This part sets up a RenderThread environment to ensure that
198 // RenderThread::current() (<=> TLS pointer) is valid.
199 // Main parts are inspired by the RenderViewFakeResourcesTest.
200 // Note that, the IPC part is not utilized in this test.
201 saved_content_renderer_.reset(
202 new ReplaceContentClientRenderer(&content_renderer_client_));
203 mock_process_.reset(new WebRTCMockRenderProcess());
204 ui_thread_.reset(
205 new TestBrowserThread(BrowserThread::UI, base::MessageLoop::current()));
207 // Construct the resource context on the UI thread.
208 resource_context_.reset(new MockRTCResourceContext);
210 static const char kThreadName[] = "RenderThread";
211 ChildProcess::current()->io_message_loop()->PostTask(FROM_HERE,
212 base::Bind(&MAYBE_WebRTCAudioDeviceTest::InitializeIOThread,
213 base::Unretained(this), kThreadName));
214 WaitForIOThreadCompletion();
216 sandbox_was_enabled_ =
217 RendererWebKitPlatformSupportImpl::SetSandboxEnabledForTesting(false);
218 render_thread_ = new RenderThreadImpl(kThreadName);
221 void MAYBE_WebRTCAudioDeviceTest::TearDown() {
222 SetAudioHardwareConfig(NULL);
224 // Run any pending cleanup tasks that may have been posted to the main thread.
225 base::RunLoop().RunUntilIdle();
227 // Kick of the cleanup process by closing the channel. This queues up
228 // OnStreamClosed calls to be executed on the audio thread.
229 ChildProcess::current()->io_message_loop()->PostTask(FROM_HERE,
230 base::Bind(&MAYBE_WebRTCAudioDeviceTest::DestroyChannel,
231 base::Unretained(this)));
232 WaitForIOThreadCompletion();
234 // When audio [input] render hosts are notified that the channel has
235 // been closed, they post tasks to the audio thread to close the
236 // AudioOutputController and once that's completed, a task is posted back to
237 // the IO thread to actually delete the AudioEntry for the audio stream. Only
238 // then is the reference to the audio manager released, so we wait for the
239 // whole thing to be torn down before we finally uninitialize the io thread.
240 WaitForAudioManagerCompletion();
242 ChildProcess::current()->io_message_loop()->PostTask(FROM_HERE,
243 base::Bind(&MAYBE_WebRTCAudioDeviceTest::UninitializeIOThread,
244 base::Unretained((this))));
245 WaitForIOThreadCompletion();
246 mock_process_.reset();
247 media_stream_manager_.reset();
248 mirroring_manager_.reset();
249 RendererWebKitPlatformSupportImpl::SetSandboxEnabledForTesting(
250 sandbox_was_enabled_);
253 bool MAYBE_WebRTCAudioDeviceTest::Send(IPC::Message* message) {
254 return channel_->Send(message);
257 void MAYBE_WebRTCAudioDeviceTest::SetAudioHardwareConfig(
258 media::AudioHardwareConfig* hardware_config) {
259 audio_hardware_config_ = hardware_config;
262 scoped_refptr<WebRtcAudioRenderer>
263 MAYBE_WebRTCAudioDeviceTest::CreateDefaultWebRtcAudioRenderer(
264 int render_view_id) {
265 media::AudioHardwareConfig* hardware_config =
266 RenderThreadImpl::current()->GetAudioHardwareConfig();
267 int sample_rate = hardware_config->GetOutputSampleRate();
268 int frames_per_buffer = hardware_config->GetOutputBufferSize();
270 return new WebRtcAudioRenderer(render_view_id, 0, sample_rate,
271 frames_per_buffer);
274 void MAYBE_WebRTCAudioDeviceTest::InitializeIOThread(const char* thread_name) {
275 #if defined(OS_WIN)
276 // We initialize COM (STA) on our IO thread as is done in Chrome.
277 // See BrowserProcessSubThread::Init.
278 initialize_com_.reset(new base::win::ScopedCOMInitializer());
279 #endif
281 // Set the current thread as the IO thread.
282 io_thread_.reset(
283 new TestBrowserThread(BrowserThread::IO, base::MessageLoop::current()));
285 // Populate our resource context.
286 test_request_context_.reset(new net::TestURLRequestContext());
287 MockRTCResourceContext* resource_context =
288 static_cast<MockRTCResourceContext*>(resource_context_.get());
289 resource_context->set_request_context(test_request_context_.get());
291 // Create our own AudioManager, AudioMirroringManager and MediaStreamManager.
292 audio_manager_.reset(media::AudioManager::CreateForTesting());
293 mirroring_manager_.reset(new AudioMirroringManager());
294 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
296 has_input_devices_ = audio_manager_->HasAudioInputDevices();
297 has_output_devices_ = audio_manager_->HasAudioOutputDevices();
299 // Create an IPC channel that handles incoming messages on the IO thread.
300 CreateChannel(thread_name);
303 void MAYBE_WebRTCAudioDeviceTest::UninitializeIOThread() {
304 resource_context_.reset();
306 test_request_context_.reset();
308 #if defined(OS_WIN)
309 initialize_com_.reset();
310 #endif
312 audio_manager_.reset();
315 void MAYBE_WebRTCAudioDeviceTest::CreateChannel(const char* name) {
316 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
318 channel_.reset(new IPC::Channel(name, IPC::Channel::MODE_SERVER, this));
319 ASSERT_TRUE(channel_->Connect());
321 static const int kRenderProcessId = 1;
322 audio_render_host_ = new TestAudioRendererHost(kRenderProcessId,
323 audio_manager_.get(),
324 mirroring_manager_.get(),
325 MediaInternals::GetInstance(),
326 media_stream_manager_.get(),
327 channel_.get());
328 audio_render_host_->set_peer_pid_for_testing(base::GetCurrentProcId());
330 audio_input_renderer_host_ =
331 new TestAudioInputRendererHost(audio_manager_.get(),
332 media_stream_manager_.get(),
333 mirroring_manager_.get(),
334 NULL,
335 channel_.get());
336 audio_input_renderer_host_->set_peer_pid_for_testing(
337 base::GetCurrentProcId());
340 void MAYBE_WebRTCAudioDeviceTest::DestroyChannel() {
341 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
342 audio_render_host_->OnChannelClosing();
343 audio_render_host_->OnFilterRemoved();
344 audio_input_renderer_host_->OnChannelClosing();
345 audio_input_renderer_host_->OnFilterRemoved();
346 audio_render_host_->ResetChannel();
347 audio_input_renderer_host_->ResetChannel();
348 channel_.reset();
349 audio_render_host_ = NULL;
350 audio_input_renderer_host_ = NULL;
353 void MAYBE_WebRTCAudioDeviceTest::OnGetAudioHardwareConfig(
354 AudioParameters* input_params, AudioParameters* output_params) {
355 ASSERT_TRUE(audio_hardware_config_);
356 *input_params = audio_hardware_config_->GetInputConfig();
357 *output_params = audio_hardware_config_->GetOutputConfig();
360 // IPC::Listener implementation.
361 bool MAYBE_WebRTCAudioDeviceTest::OnMessageReceived(
362 const IPC::Message& message) {
363 if (render_thread_) {
364 IPC::ChannelProxy::MessageFilter* filter =
365 render_thread_->audio_input_message_filter();
366 if (filter->OnMessageReceived(message))
367 return true;
369 filter = render_thread_->audio_message_filter();
370 if (filter->OnMessageReceived(message))
371 return true;
374 if (audio_render_host_.get()) {
375 bool message_was_ok = false;
376 if (audio_render_host_->OnMessageReceived(message, &message_was_ok))
377 return true;
380 if (audio_input_renderer_host_.get()) {
381 bool message_was_ok = false;
382 if (audio_input_renderer_host_->OnMessageReceived(message, &message_was_ok))
383 return true;
386 bool handled ALLOW_UNUSED = true;
387 bool message_is_ok = true;
388 IPC_BEGIN_MESSAGE_MAP_EX(MAYBE_WebRTCAudioDeviceTest, message, message_is_ok)
389 IPC_MESSAGE_HANDLER(ViewHostMsg_GetAudioHardwareConfig,
390 OnGetAudioHardwareConfig)
391 IPC_MESSAGE_UNHANDLED(handled = false)
392 IPC_END_MESSAGE_MAP_EX()
394 EXPECT_TRUE(message_is_ok);
396 return true;
399 // Posts a final task to the IO message loop and waits for completion.
400 void MAYBE_WebRTCAudioDeviceTest::WaitForIOThreadCompletion() {
401 WaitForTaskRunnerCompletion(
402 ChildProcess::current()->io_message_loop()->message_loop_proxy());
405 void MAYBE_WebRTCAudioDeviceTest::WaitForAudioManagerCompletion() {
406 if (audio_manager_)
407 WaitForTaskRunnerCompletion(audio_manager_->GetTaskRunner());
410 void MAYBE_WebRTCAudioDeviceTest::WaitForTaskRunnerCompletion(
411 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner) {
412 base::WaitableEvent* event = new base::WaitableEvent(false, false);
413 task_runner->PostTask(
414 FROM_HERE,
415 base::Bind(&base::WaitableEvent::Signal, base::Unretained(event)));
416 if (event->TimedWait(TestTimeouts::action_max_timeout())) {
417 delete event;
418 } else {
419 // Don't delete the event object in case the message ever gets processed.
420 // If we do, we will crash the test process.
421 ADD_FAILURE() << "Failed to wait for message loop";
425 std::string MAYBE_WebRTCAudioDeviceTest::GetTestDataPath(
426 const base::FilePath::StringType& file_name) {
427 base::FilePath path;
428 EXPECT_TRUE(PathService::Get(DIR_TEST_DATA, &path));
429 path = path.Append(file_name);
430 EXPECT_TRUE(base::PathExists(path));
431 #if defined(OS_WIN)
432 return base::WideToUTF8(path.value());
433 #else
434 return path.value();
435 #endif
438 WebRTCTransportImpl::WebRTCTransportImpl(webrtc::VoENetwork* network)
439 : network_(network) {
442 WebRTCTransportImpl::~WebRTCTransportImpl() {}
444 int WebRTCTransportImpl::SendPacket(int channel, const void* data, int len) {
445 return network_->ReceivedRTPPacket(channel, data, len);
448 int WebRTCTransportImpl::SendRTCPPacket(int channel, const void* data,
449 int len) {
450 return network_->ReceivedRTCPPacket(channel, data, len);
453 } // namespace content