Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / media / audio / android / audio_android_unittest.cc
blob64b3b4ba61361c3e58f6aa257b82aa5382a67356
1 // Copyright 2013 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 "base/android/build_info.h"
6 #include "base/basictypes.h"
7 #include "base/bind.h"
8 #include "base/files/file_util.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/path_service.h"
12 #include "base/run_loop.h"
13 #include "base/strings/stringprintf.h"
14 #include "base/synchronization/lock.h"
15 #include "base/synchronization/waitable_event.h"
16 #include "base/test/test_timeouts.h"
17 #include "base/time/time.h"
18 #include "build/build_config.h"
19 #include "media/audio/android/audio_manager_android.h"
20 #include "media/audio/audio_io.h"
21 #include "media/audio/audio_manager_base.h"
22 #include "media/audio/audio_unittest_util.h"
23 #include "media/audio/mock_audio_source_callback.h"
24 #include "media/base/decoder_buffer.h"
25 #include "media/base/seekable_buffer.h"
26 #include "media/base/test_data_util.h"
27 #include "testing/gmock/include/gmock/gmock.h"
28 #include "testing/gtest/include/gtest/gtest.h"
30 using ::testing::_;
31 using ::testing::AtLeast;
32 using ::testing::DoAll;
33 using ::testing::Invoke;
34 using ::testing::NotNull;
35 using ::testing::Return;
37 namespace media {
39 ACTION_P3(CheckCountAndPostQuitTask, count, limit, loop) {
40 if (++*count >= limit) {
41 loop->PostTask(FROM_HERE, base::MessageLoop::QuitClosure());
45 static const char kSpeechFile_16b_s_48k[] = "speech_16b_stereo_48kHz.raw";
46 static const char kSpeechFile_16b_m_48k[] = "speech_16b_mono_48kHz.raw";
47 static const char kSpeechFile_16b_s_44k[] = "speech_16b_stereo_44kHz.raw";
48 static const char kSpeechFile_16b_m_44k[] = "speech_16b_mono_44kHz.raw";
50 static const float kCallbackTestTimeMs = 2000.0;
51 static const int kBitsPerSample = 16;
52 static const int kBytesPerSample = kBitsPerSample / 8;
54 // Converts AudioParameters::Format enumerator to readable string.
55 static std::string FormatToString(AudioParameters::Format format) {
56 switch (format) {
57 case AudioParameters::AUDIO_PCM_LINEAR:
58 return std::string("AUDIO_PCM_LINEAR");
59 case AudioParameters::AUDIO_PCM_LOW_LATENCY:
60 return std::string("AUDIO_PCM_LOW_LATENCY");
61 case AudioParameters::AUDIO_FAKE:
62 return std::string("AUDIO_FAKE");
63 default:
64 return std::string();
68 // Converts ChannelLayout enumerator to readable string. Does not include
69 // multi-channel cases since these layouts are not supported on Android.
70 static std::string LayoutToString(ChannelLayout channel_layout) {
71 switch (channel_layout) {
72 case CHANNEL_LAYOUT_NONE:
73 return std::string("CHANNEL_LAYOUT_NONE");
74 case CHANNEL_LAYOUT_MONO:
75 return std::string("CHANNEL_LAYOUT_MONO");
76 case CHANNEL_LAYOUT_STEREO:
77 return std::string("CHANNEL_LAYOUT_STEREO");
78 case CHANNEL_LAYOUT_UNSUPPORTED:
79 default:
80 return std::string("CHANNEL_LAYOUT_UNSUPPORTED");
84 static double ExpectedTimeBetweenCallbacks(AudioParameters params) {
85 return (base::TimeDelta::FromMicroseconds(
86 params.frames_per_buffer() * base::Time::kMicrosecondsPerSecond /
87 static_cast<double>(params.sample_rate()))).InMillisecondsF();
90 // Helper method which verifies that the device list starts with a valid
91 // default device name followed by non-default device names.
92 static void CheckDeviceNames(const AudioDeviceNames& device_names) {
93 DVLOG(2) << "Got " << device_names.size() << " audio devices.";
94 if (device_names.empty()) {
95 // Log a warning so we can see the status on the build bots. No need to
96 // break the test though since this does successfully test the code and
97 // some failure cases.
98 LOG(WARNING) << "No input devices detected";
99 return;
102 AudioDeviceNames::const_iterator it = device_names.begin();
104 // The first device in the list should always be the default device.
105 EXPECT_EQ(std::string(AudioManagerBase::kDefaultDeviceName),
106 it->device_name);
107 EXPECT_EQ(std::string(AudioManagerBase::kDefaultDeviceId), it->unique_id);
108 ++it;
110 // Other devices should have non-empty name and id and should not contain
111 // default name or id.
112 while (it != device_names.end()) {
113 EXPECT_FALSE(it->device_name.empty());
114 EXPECT_FALSE(it->unique_id.empty());
115 DVLOG(2) << "Device ID(" << it->unique_id
116 << "), label: " << it->device_name;
117 EXPECT_NE(std::string(AudioManagerBase::kDefaultDeviceName),
118 it->device_name);
119 EXPECT_NE(std::string(AudioManagerBase::kDefaultDeviceId),
120 it->unique_id);
121 ++it;
125 // We clear the data bus to ensure that the test does not cause noise.
126 static int RealOnMoreData(AudioBus* dest, uint32 total_bytes_delay) {
127 dest->Zero();
128 return dest->frames();
131 std::ostream& operator<<(std::ostream& os, const AudioParameters& params) {
132 using namespace std;
133 os << endl << "format: " << FormatToString(params.format()) << endl
134 << "channel layout: " << LayoutToString(params.channel_layout()) << endl
135 << "sample rate: " << params.sample_rate() << endl
136 << "bits per sample: " << params.bits_per_sample() << endl
137 << "frames per buffer: " << params.frames_per_buffer() << endl
138 << "channels: " << params.channels() << endl
139 << "bytes per buffer: " << params.GetBytesPerBuffer() << endl
140 << "bytes per second: " << params.GetBytesPerSecond() << endl
141 << "bytes per frame: " << params.GetBytesPerFrame() << endl
142 << "chunk size in ms: " << ExpectedTimeBetweenCallbacks(params) << endl
143 << "echo_canceller: "
144 << (params.effects() & AudioParameters::ECHO_CANCELLER);
145 return os;
148 // Gmock implementation of AudioInputStream::AudioInputCallback.
149 class MockAudioInputCallback : public AudioInputStream::AudioInputCallback {
150 public:
151 MOCK_METHOD4(OnData,
152 void(AudioInputStream* stream,
153 const AudioBus* src,
154 uint32 hardware_delay_bytes,
155 double volume));
156 MOCK_METHOD1(OnError, void(AudioInputStream* stream));
159 // Implements AudioOutputStream::AudioSourceCallback and provides audio data
160 // by reading from a data file.
161 class FileAudioSource : public AudioOutputStream::AudioSourceCallback {
162 public:
163 explicit FileAudioSource(base::WaitableEvent* event, const std::string& name)
164 : event_(event), pos_(0) {
165 // Reads a test file from media/test/data directory and stores it in
166 // a DecoderBuffer.
167 file_ = ReadTestDataFile(name);
169 // Log the name of the file which is used as input for this test.
170 base::FilePath file_path = GetTestDataFilePath(name);
171 DVLOG(0) << "Reading from file: " << file_path.value().c_str();
174 ~FileAudioSource() override {}
176 // AudioOutputStream::AudioSourceCallback implementation.
178 // Use samples read from a data file and fill up the audio buffer
179 // provided to us in the callback.
180 int OnMoreData(AudioBus* audio_bus, uint32 total_bytes_delay) override {
181 bool stop_playing = false;
182 int max_size =
183 audio_bus->frames() * audio_bus->channels() * kBytesPerSample;
185 // Adjust data size and prepare for end signal if file has ended.
186 if (pos_ + max_size > file_size()) {
187 stop_playing = true;
188 max_size = file_size() - pos_;
191 // File data is stored as interleaved 16-bit values. Copy data samples from
192 // the file and deinterleave to match the audio bus format.
193 // FromInterleaved() will zero out any unfilled frames when there is not
194 // sufficient data remaining in the file to fill up the complete frame.
195 int frames = max_size / (audio_bus->channels() * kBytesPerSample);
196 if (max_size) {
197 audio_bus->FromInterleaved(file_->data() + pos_, frames, kBytesPerSample);
198 pos_ += max_size;
201 // Set event to ensure that the test can stop when the file has ended.
202 if (stop_playing)
203 event_->Signal();
205 return frames;
208 void OnError(AudioOutputStream* stream) override {}
210 int file_size() { return file_->data_size(); }
212 private:
213 base::WaitableEvent* event_;
214 int pos_;
215 scoped_refptr<DecoderBuffer> file_;
217 DISALLOW_COPY_AND_ASSIGN(FileAudioSource);
220 // Implements AudioInputStream::AudioInputCallback and writes the recorded
221 // audio data to a local output file. Note that this implementation should
222 // only be used for manually invoked and evaluated tests, hence the created
223 // file will not be destroyed after the test is done since the intention is
224 // that it shall be available for off-line analysis.
225 class FileAudioSink : public AudioInputStream::AudioInputCallback {
226 public:
227 explicit FileAudioSink(base::WaitableEvent* event,
228 const AudioParameters& params,
229 const std::string& file_name)
230 : event_(event), params_(params) {
231 // Allocate space for ~10 seconds of data.
232 const int kMaxBufferSize = 10 * params.GetBytesPerSecond();
233 buffer_.reset(new media::SeekableBuffer(0, kMaxBufferSize));
235 // Open up the binary file which will be written to in the destructor.
236 base::FilePath file_path;
237 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &file_path));
238 file_path = file_path.AppendASCII(file_name.c_str());
239 binary_file_ = base::OpenFile(file_path, "wb");
240 DLOG_IF(ERROR, !binary_file_) << "Failed to open binary PCM data file.";
241 DVLOG(0) << "Writing to file: " << file_path.value().c_str();
244 ~FileAudioSink() override {
245 int bytes_written = 0;
246 while (bytes_written < buffer_->forward_capacity()) {
247 const uint8* chunk;
248 int chunk_size;
250 // Stop writing if no more data is available.
251 if (!buffer_->GetCurrentChunk(&chunk, &chunk_size))
252 break;
254 // Write recorded data chunk to the file and prepare for next chunk.
255 // TODO(henrika): use file_util:: instead.
256 fwrite(chunk, 1, chunk_size, binary_file_);
257 buffer_->Seek(chunk_size);
258 bytes_written += chunk_size;
260 base::CloseFile(binary_file_);
263 // AudioInputStream::AudioInputCallback implementation.
264 void OnData(AudioInputStream* stream,
265 const AudioBus* src,
266 uint32 hardware_delay_bytes,
267 double volume) override {
268 const int num_samples = src->frames() * src->channels();
269 scoped_ptr<int16> interleaved(new int16[num_samples]);
270 const int bytes_per_sample = sizeof(*interleaved);
271 src->ToInterleaved(src->frames(), bytes_per_sample, interleaved.get());
273 // Store data data in a temporary buffer to avoid making blocking
274 // fwrite() calls in the audio callback. The complete buffer will be
275 // written to file in the destructor.
276 const int size = bytes_per_sample * num_samples;
277 if (!buffer_->Append((const uint8*)interleaved.get(), size))
278 event_->Signal();
281 void OnError(AudioInputStream* stream) override {}
283 private:
284 base::WaitableEvent* event_;
285 AudioParameters params_;
286 scoped_ptr<media::SeekableBuffer> buffer_;
287 FILE* binary_file_;
289 DISALLOW_COPY_AND_ASSIGN(FileAudioSink);
292 // Implements AudioInputCallback and AudioSourceCallback to support full
293 // duplex audio where captured samples are played out in loopback after
294 // reading from a temporary FIFO storage.
295 class FullDuplexAudioSinkSource
296 : public AudioInputStream::AudioInputCallback,
297 public AudioOutputStream::AudioSourceCallback {
298 public:
299 explicit FullDuplexAudioSinkSource(const AudioParameters& params)
300 : params_(params),
301 previous_time_(base::TimeTicks::Now()),
302 started_(false) {
303 // Start with a reasonably small FIFO size. It will be increased
304 // dynamically during the test if required.
305 fifo_.reset(new media::SeekableBuffer(0, 2 * params.GetBytesPerBuffer()));
306 buffer_.reset(new uint8[params_.GetBytesPerBuffer()]);
309 ~FullDuplexAudioSinkSource() override {}
311 // AudioInputStream::AudioInputCallback implementation
312 void OnData(AudioInputStream* stream,
313 const AudioBus* src,
314 uint32 hardware_delay_bytes,
315 double volume) override {
316 const base::TimeTicks now_time = base::TimeTicks::Now();
317 const int diff = (now_time - previous_time_).InMilliseconds();
319 EXPECT_EQ(params_.bits_per_sample(), 16);
320 const int num_samples = src->frames() * src->channels();
321 scoped_ptr<int16> interleaved(new int16[num_samples]);
322 const int bytes_per_sample = sizeof(*interleaved);
323 src->ToInterleaved(src->frames(), bytes_per_sample, interleaved.get());
324 const int size = bytes_per_sample * num_samples;
326 base::AutoLock lock(lock_);
327 if (diff > 1000) {
328 started_ = true;
329 previous_time_ = now_time;
331 // Log out the extra delay added by the FIFO. This is a best effort
332 // estimate. We might be +- 10ms off here.
333 int extra_fifo_delay =
334 static_cast<int>(BytesToMilliseconds(fifo_->forward_bytes() + size));
335 DVLOG(1) << extra_fifo_delay;
338 // We add an initial delay of ~1 second before loopback starts to ensure
339 // a stable callback sequence and to avoid initial bursts which might add
340 // to the extra FIFO delay.
341 if (!started_)
342 return;
344 // Append new data to the FIFO and extend the size if the max capacity
345 // was exceeded. Flush the FIFO when extended just in case.
346 if (!fifo_->Append((const uint8*)interleaved.get(), size)) {
347 fifo_->set_forward_capacity(2 * fifo_->forward_capacity());
348 fifo_->Clear();
352 void OnError(AudioInputStream* stream) override {}
354 // AudioOutputStream::AudioSourceCallback implementation
355 int OnMoreData(AudioBus* dest, uint32 total_bytes_delay) override {
356 const int size_in_bytes =
357 (params_.bits_per_sample() / 8) * dest->frames() * dest->channels();
358 EXPECT_EQ(size_in_bytes, params_.GetBytesPerBuffer());
360 base::AutoLock lock(lock_);
362 // We add an initial delay of ~1 second before loopback starts to ensure
363 // a stable callback sequences and to avoid initial bursts which might add
364 // to the extra FIFO delay.
365 if (!started_) {
366 dest->Zero();
367 return dest->frames();
370 // Fill up destination with zeros if the FIFO does not contain enough
371 // data to fulfill the request.
372 if (fifo_->forward_bytes() < size_in_bytes) {
373 dest->Zero();
374 } else {
375 fifo_->Read(buffer_.get(), size_in_bytes);
376 dest->FromInterleaved(
377 buffer_.get(), dest->frames(), params_.bits_per_sample() / 8);
380 return dest->frames();
383 void OnError(AudioOutputStream* stream) override {}
385 private:
386 // Converts from bytes to milliseconds given number of bytes and existing
387 // audio parameters.
388 double BytesToMilliseconds(int bytes) const {
389 const int frames = bytes / params_.GetBytesPerFrame();
390 return (base::TimeDelta::FromMicroseconds(
391 frames * base::Time::kMicrosecondsPerSecond /
392 static_cast<double>(params_.sample_rate()))).InMillisecondsF();
395 AudioParameters params_;
396 base::TimeTicks previous_time_;
397 base::Lock lock_;
398 scoped_ptr<media::SeekableBuffer> fifo_;
399 scoped_ptr<uint8[]> buffer_;
400 bool started_;
402 DISALLOW_COPY_AND_ASSIGN(FullDuplexAudioSinkSource);
405 // Test fixture class for tests which only exercise the output path.
406 class AudioAndroidOutputTest : public testing::Test {
407 public:
408 AudioAndroidOutputTest()
409 : loop_(new base::MessageLoopForUI()),
410 audio_manager_(AudioManager::CreateForTesting()),
411 audio_output_stream_(NULL) {
414 ~AudioAndroidOutputTest() override {}
416 protected:
417 AudioManager* audio_manager() { return audio_manager_.get(); }
418 base::MessageLoopForUI* loop() { return loop_.get(); }
419 const AudioParameters& audio_output_parameters() {
420 return audio_output_parameters_;
423 // Synchronously runs the provided callback/closure on the audio thread.
424 void RunOnAudioThread(const base::Closure& closure) {
425 if (!audio_manager()->GetTaskRunner()->BelongsToCurrentThread()) {
426 base::WaitableEvent event(false, false);
427 audio_manager()->GetTaskRunner()->PostTask(
428 FROM_HERE,
429 base::Bind(&AudioAndroidOutputTest::RunOnAudioThreadImpl,
430 base::Unretained(this),
431 closure,
432 &event));
433 event.Wait();
434 } else {
435 closure.Run();
439 void RunOnAudioThreadImpl(const base::Closure& closure,
440 base::WaitableEvent* event) {
441 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
442 closure.Run();
443 event->Signal();
446 void GetDefaultOutputStreamParametersOnAudioThread() {
447 RunOnAudioThread(
448 base::Bind(&AudioAndroidOutputTest::GetDefaultOutputStreamParameters,
449 base::Unretained(this)));
452 void MakeAudioOutputStreamOnAudioThread(const AudioParameters& params) {
453 RunOnAudioThread(
454 base::Bind(&AudioAndroidOutputTest::MakeOutputStream,
455 base::Unretained(this),
456 params));
459 void OpenAndCloseAudioOutputStreamOnAudioThread() {
460 RunOnAudioThread(
461 base::Bind(&AudioAndroidOutputTest::OpenAndClose,
462 base::Unretained(this)));
465 void OpenAndStartAudioOutputStreamOnAudioThread(
466 AudioOutputStream::AudioSourceCallback* source) {
467 RunOnAudioThread(
468 base::Bind(&AudioAndroidOutputTest::OpenAndStart,
469 base::Unretained(this),
470 source));
473 void StopAndCloseAudioOutputStreamOnAudioThread() {
474 RunOnAudioThread(
475 base::Bind(&AudioAndroidOutputTest::StopAndClose,
476 base::Unretained(this)));
479 double AverageTimeBetweenCallbacks(int num_callbacks) const {
480 return ((end_time_ - start_time_) / static_cast<double>(num_callbacks - 1))
481 .InMillisecondsF();
484 void StartOutputStreamCallbacks(const AudioParameters& params) {
485 double expected_time_between_callbacks_ms =
486 ExpectedTimeBetweenCallbacks(params);
487 const int num_callbacks =
488 (kCallbackTestTimeMs / expected_time_between_callbacks_ms);
489 MakeAudioOutputStreamOnAudioThread(params);
491 int count = 0;
492 MockAudioSourceCallback source;
494 EXPECT_CALL(source, OnMoreData(NotNull(), _))
495 .Times(AtLeast(num_callbacks))
496 .WillRepeatedly(
497 DoAll(CheckCountAndPostQuitTask(&count, num_callbacks, loop()),
498 Invoke(RealOnMoreData)));
499 EXPECT_CALL(source, OnError(audio_output_stream_)).Times(0);
501 OpenAndStartAudioOutputStreamOnAudioThread(&source);
503 start_time_ = base::TimeTicks::Now();
504 loop()->Run();
505 end_time_ = base::TimeTicks::Now();
507 StopAndCloseAudioOutputStreamOnAudioThread();
509 double average_time_between_callbacks_ms =
510 AverageTimeBetweenCallbacks(num_callbacks);
511 DVLOG(0) << "expected time between callbacks: "
512 << expected_time_between_callbacks_ms << " ms";
513 DVLOG(0) << "average time between callbacks: "
514 << average_time_between_callbacks_ms << " ms";
515 EXPECT_GE(average_time_between_callbacks_ms,
516 0.70 * expected_time_between_callbacks_ms);
517 EXPECT_LE(average_time_between_callbacks_ms,
518 1.50 * expected_time_between_callbacks_ms);
521 void GetDefaultOutputStreamParameters() {
522 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
523 audio_output_parameters_ =
524 audio_manager()->GetDefaultOutputStreamParameters();
525 EXPECT_TRUE(audio_output_parameters_.IsValid());
528 void MakeOutputStream(const AudioParameters& params) {
529 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
530 audio_output_stream_ = audio_manager()->MakeAudioOutputStream(
531 params, std::string());
532 EXPECT_TRUE(audio_output_stream_);
535 void OpenAndClose() {
536 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
537 EXPECT_TRUE(audio_output_stream_->Open());
538 audio_output_stream_->Close();
539 audio_output_stream_ = NULL;
542 void OpenAndStart(AudioOutputStream::AudioSourceCallback* source) {
543 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
544 EXPECT_TRUE(audio_output_stream_->Open());
545 audio_output_stream_->Start(source);
548 void StopAndClose() {
549 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
550 audio_output_stream_->Stop();
551 audio_output_stream_->Close();
552 audio_output_stream_ = NULL;
555 scoped_ptr<base::MessageLoopForUI> loop_;
556 scoped_ptr<AudioManager> audio_manager_;
557 AudioParameters audio_output_parameters_;
558 AudioOutputStream* audio_output_stream_;
559 base::TimeTicks start_time_;
560 base::TimeTicks end_time_;
562 private:
563 DISALLOW_COPY_AND_ASSIGN(AudioAndroidOutputTest);
566 // AudioRecordInputStream should only be created on Jelly Bean and higher. This
567 // ensures we only test against the AudioRecord path when that is satisfied.
568 std::vector<bool> RunAudioRecordInputPathTests() {
569 std::vector<bool> tests;
570 tests.push_back(false);
571 if (base::android::BuildInfo::GetInstance()->sdk_int() >= 16)
572 tests.push_back(true);
573 return tests;
576 // Test fixture class for tests which exercise the input path, or both input and
577 // output paths. It is value-parameterized to test against both the Java
578 // AudioRecord (when true) and native OpenSLES (when false) input paths.
579 class AudioAndroidInputTest : public AudioAndroidOutputTest,
580 public testing::WithParamInterface<bool> {
581 public:
582 AudioAndroidInputTest() : audio_input_stream_(NULL) {}
584 protected:
585 const AudioParameters& audio_input_parameters() {
586 return audio_input_parameters_;
589 AudioParameters GetInputStreamParameters() {
590 GetDefaultInputStreamParametersOnAudioThread();
592 // Override the platform effects setting to use the AudioRecord or OpenSLES
593 // path as requested.
594 int effects = GetParam() ? AudioParameters::ECHO_CANCELLER :
595 AudioParameters::NO_EFFECTS;
596 AudioParameters params(audio_input_parameters().format(),
597 audio_input_parameters().channel_layout(),
598 audio_input_parameters().sample_rate(),
599 audio_input_parameters().bits_per_sample(),
600 audio_input_parameters().frames_per_buffer(),
601 effects);
602 return params;
605 void GetDefaultInputStreamParametersOnAudioThread() {
606 RunOnAudioThread(
607 base::Bind(&AudioAndroidInputTest::GetDefaultInputStreamParameters,
608 base::Unretained(this)));
611 void MakeAudioInputStreamOnAudioThread(const AudioParameters& params) {
612 RunOnAudioThread(
613 base::Bind(&AudioAndroidInputTest::MakeInputStream,
614 base::Unretained(this),
615 params));
618 void OpenAndCloseAudioInputStreamOnAudioThread() {
619 RunOnAudioThread(
620 base::Bind(&AudioAndroidInputTest::OpenAndClose,
621 base::Unretained(this)));
624 void OpenAndStartAudioInputStreamOnAudioThread(
625 AudioInputStream::AudioInputCallback* sink) {
626 RunOnAudioThread(
627 base::Bind(&AudioAndroidInputTest::OpenAndStart,
628 base::Unretained(this),
629 sink));
632 void StopAndCloseAudioInputStreamOnAudioThread() {
633 RunOnAudioThread(
634 base::Bind(&AudioAndroidInputTest::StopAndClose,
635 base::Unretained(this)));
638 void StartInputStreamCallbacks(const AudioParameters& params) {
639 double expected_time_between_callbacks_ms =
640 ExpectedTimeBetweenCallbacks(params);
641 const int num_callbacks =
642 (kCallbackTestTimeMs / expected_time_between_callbacks_ms);
644 MakeAudioInputStreamOnAudioThread(params);
646 int count = 0;
647 MockAudioInputCallback sink;
649 EXPECT_CALL(sink, OnData(audio_input_stream_, NotNull(), _, _))
650 .Times(AtLeast(num_callbacks))
651 .WillRepeatedly(
652 CheckCountAndPostQuitTask(&count, num_callbacks, loop()));
653 EXPECT_CALL(sink, OnError(audio_input_stream_)).Times(0);
655 OpenAndStartAudioInputStreamOnAudioThread(&sink);
657 start_time_ = base::TimeTicks::Now();
658 loop()->Run();
659 end_time_ = base::TimeTicks::Now();
661 StopAndCloseAudioInputStreamOnAudioThread();
663 double average_time_between_callbacks_ms =
664 AverageTimeBetweenCallbacks(num_callbacks);
665 DVLOG(0) << "expected time between callbacks: "
666 << expected_time_between_callbacks_ms << " ms";
667 DVLOG(0) << "average time between callbacks: "
668 << average_time_between_callbacks_ms << " ms";
669 EXPECT_GE(average_time_between_callbacks_ms,
670 0.70 * expected_time_between_callbacks_ms);
671 EXPECT_LE(average_time_between_callbacks_ms,
672 1.30 * expected_time_between_callbacks_ms);
675 void GetDefaultInputStreamParameters() {
676 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
677 audio_input_parameters_ = audio_manager()->GetInputStreamParameters(
678 AudioManagerBase::kDefaultDeviceId);
681 void MakeInputStream(const AudioParameters& params) {
682 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
683 audio_input_stream_ = audio_manager()->MakeAudioInputStream(
684 params, AudioManagerBase::kDefaultDeviceId);
685 EXPECT_TRUE(audio_input_stream_);
688 void OpenAndClose() {
689 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
690 EXPECT_TRUE(audio_input_stream_->Open());
691 audio_input_stream_->Close();
692 audio_input_stream_ = NULL;
695 void OpenAndStart(AudioInputStream::AudioInputCallback* sink) {
696 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
697 EXPECT_TRUE(audio_input_stream_->Open());
698 audio_input_stream_->Start(sink);
701 void StopAndClose() {
702 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
703 audio_input_stream_->Stop();
704 audio_input_stream_->Close();
705 audio_input_stream_ = NULL;
708 AudioInputStream* audio_input_stream_;
709 AudioParameters audio_input_parameters_;
711 private:
712 DISALLOW_COPY_AND_ASSIGN(AudioAndroidInputTest);
715 // Get the default audio input parameters and log the result.
716 TEST_P(AudioAndroidInputTest, GetDefaultInputStreamParameters) {
717 // We don't go through AudioAndroidInputTest::GetInputStreamParameters() here
718 // so that we can log the real (non-overridden) values of the effects.
719 GetDefaultInputStreamParametersOnAudioThread();
720 EXPECT_TRUE(audio_input_parameters().IsValid());
721 DVLOG(1) << audio_input_parameters();
724 // Get the default audio output parameters and log the result.
725 TEST_F(AudioAndroidOutputTest, GetDefaultOutputStreamParameters) {
726 GetDefaultOutputStreamParametersOnAudioThread();
727 DVLOG(1) << audio_output_parameters();
730 // Verify input device enumeration.
731 TEST_F(AudioAndroidInputTest, GetAudioInputDeviceNames) {
732 ABORT_AUDIO_TEST_IF_NOT(audio_manager()->HasAudioInputDevices());
733 AudioDeviceNames devices;
734 RunOnAudioThread(
735 base::Bind(&AudioManager::GetAudioInputDeviceNames,
736 base::Unretained(audio_manager()),
737 &devices));
738 CheckDeviceNames(devices);
741 // Verify output device enumeration.
742 TEST_F(AudioAndroidOutputTest, GetAudioOutputDeviceNames) {
743 ABORT_AUDIO_TEST_IF_NOT(audio_manager()->HasAudioOutputDevices());
744 AudioDeviceNames devices;
745 RunOnAudioThread(
746 base::Bind(&AudioManager::GetAudioOutputDeviceNames,
747 base::Unretained(audio_manager()),
748 &devices));
749 CheckDeviceNames(devices);
752 // Ensure that a default input stream can be created and closed.
753 TEST_P(AudioAndroidInputTest, CreateAndCloseInputStream) {
754 AudioParameters params = GetInputStreamParameters();
755 MakeAudioInputStreamOnAudioThread(params);
756 RunOnAudioThread(
757 base::Bind(&AudioInputStream::Close,
758 base::Unretained(audio_input_stream_)));
761 // Ensure that a default output stream can be created and closed.
762 // TODO(henrika): should we also verify that this API changes the audio mode
763 // to communication mode, and calls RegisterHeadsetReceiver, the first time
764 // it is called?
765 TEST_F(AudioAndroidOutputTest, CreateAndCloseOutputStream) {
766 GetDefaultOutputStreamParametersOnAudioThread();
767 MakeAudioOutputStreamOnAudioThread(audio_output_parameters());
768 RunOnAudioThread(
769 base::Bind(&AudioOutputStream::Close,
770 base::Unretained(audio_output_stream_)));
773 // Ensure that a default input stream can be opened and closed.
774 TEST_P(AudioAndroidInputTest, OpenAndCloseInputStream) {
775 AudioParameters params = GetInputStreamParameters();
776 MakeAudioInputStreamOnAudioThread(params);
777 OpenAndCloseAudioInputStreamOnAudioThread();
780 // Ensure that a default output stream can be opened and closed.
781 TEST_F(AudioAndroidOutputTest, OpenAndCloseOutputStream) {
782 GetDefaultOutputStreamParametersOnAudioThread();
783 MakeAudioOutputStreamOnAudioThread(audio_output_parameters());
784 OpenAndCloseAudioOutputStreamOnAudioThread();
787 // Start input streaming using default input parameters and ensure that the
788 // callback sequence is sane.
789 TEST_P(AudioAndroidInputTest, DISABLED_StartInputStreamCallbacks) {
790 AudioParameters native_params = GetInputStreamParameters();
791 StartInputStreamCallbacks(native_params);
794 // Start input streaming using non default input parameters and ensure that the
795 // callback sequence is sane. The only change we make in this test is to select
796 // a 10ms buffer size instead of the default size.
797 TEST_P(AudioAndroidInputTest,
798 DISABLED_StartInputStreamCallbacksNonDefaultParameters) {
799 AudioParameters native_params = GetInputStreamParameters();
800 AudioParameters params(native_params.format(),
801 native_params.channel_layout(),
802 native_params.sample_rate(),
803 native_params.bits_per_sample(),
804 native_params.sample_rate() / 100,
805 native_params.effects());
806 StartInputStreamCallbacks(params);
809 // Start output streaming using default output parameters and ensure that the
810 // callback sequence is sane.
811 TEST_F(AudioAndroidOutputTest, StartOutputStreamCallbacks) {
812 GetDefaultOutputStreamParametersOnAudioThread();
813 StartOutputStreamCallbacks(audio_output_parameters());
816 // Start output streaming using non default output parameters and ensure that
817 // the callback sequence is sane. The only change we make in this test is to
818 // select a 10ms buffer size instead of the default size and to open up the
819 // device in mono.
820 // TODO(henrika): possibly add support for more variations.
821 TEST_F(AudioAndroidOutputTest, StartOutputStreamCallbacksNonDefaultParameters) {
822 GetDefaultOutputStreamParametersOnAudioThread();
823 AudioParameters params(audio_output_parameters().format(),
824 CHANNEL_LAYOUT_MONO,
825 audio_output_parameters().sample_rate(),
826 audio_output_parameters().bits_per_sample(),
827 audio_output_parameters().sample_rate() / 100);
828 StartOutputStreamCallbacks(params);
831 // Play out a PCM file segment in real time and allow the user to verify that
832 // the rendered audio sounds OK.
833 // NOTE: this test requires user interaction and is not designed to run as an
834 // automatized test on bots.
835 TEST_F(AudioAndroidOutputTest, DISABLED_RunOutputStreamWithFileAsSource) {
836 GetDefaultOutputStreamParametersOnAudioThread();
837 DVLOG(1) << audio_output_parameters();
838 MakeAudioOutputStreamOnAudioThread(audio_output_parameters());
840 std::string file_name;
841 const AudioParameters params = audio_output_parameters();
842 if (params.sample_rate() == 48000 && params.channels() == 2) {
843 file_name = kSpeechFile_16b_s_48k;
844 } else if (params.sample_rate() == 48000 && params.channels() == 1) {
845 file_name = kSpeechFile_16b_m_48k;
846 } else if (params.sample_rate() == 44100 && params.channels() == 2) {
847 file_name = kSpeechFile_16b_s_44k;
848 } else if (params.sample_rate() == 44100 && params.channels() == 1) {
849 file_name = kSpeechFile_16b_m_44k;
850 } else {
851 FAIL() << "This test supports 44.1kHz and 48kHz mono/stereo only.";
852 return;
855 base::WaitableEvent event(false, false);
856 FileAudioSource source(&event, file_name);
858 OpenAndStartAudioOutputStreamOnAudioThread(&source);
859 DVLOG(0) << ">> Verify that the file is played out correctly...";
860 EXPECT_TRUE(event.TimedWait(TestTimeouts::action_max_timeout()));
861 StopAndCloseAudioOutputStreamOnAudioThread();
864 // Start input streaming and run it for ten seconds while recording to a
865 // local audio file.
866 // NOTE: this test requires user interaction and is not designed to run as an
867 // automatized test on bots.
868 TEST_P(AudioAndroidInputTest, DISABLED_RunSimplexInputStreamWithFileAsSink) {
869 AudioParameters params = GetInputStreamParameters();
870 DVLOG(1) << params;
871 MakeAudioInputStreamOnAudioThread(params);
873 std::string file_name = base::StringPrintf("out_simplex_%d_%d_%d.pcm",
874 params.sample_rate(),
875 params.frames_per_buffer(),
876 params.channels());
878 base::WaitableEvent event(false, false);
879 FileAudioSink sink(&event, params, file_name);
881 OpenAndStartAudioInputStreamOnAudioThread(&sink);
882 DVLOG(0) << ">> Speak into the microphone to record audio...";
883 EXPECT_TRUE(event.TimedWait(TestTimeouts::action_max_timeout()));
884 StopAndCloseAudioInputStreamOnAudioThread();
887 // Same test as RunSimplexInputStreamWithFileAsSink but this time output
888 // streaming is active as well (reads zeros only).
889 // NOTE: this test requires user interaction and is not designed to run as an
890 // automatized test on bots.
891 TEST_P(AudioAndroidInputTest, DISABLED_RunDuplexInputStreamWithFileAsSink) {
892 AudioParameters in_params = GetInputStreamParameters();
893 DVLOG(1) << in_params;
894 MakeAudioInputStreamOnAudioThread(in_params);
896 GetDefaultOutputStreamParametersOnAudioThread();
897 DVLOG(1) << audio_output_parameters();
898 MakeAudioOutputStreamOnAudioThread(audio_output_parameters());
900 std::string file_name = base::StringPrintf("out_duplex_%d_%d_%d.pcm",
901 in_params.sample_rate(),
902 in_params.frames_per_buffer(),
903 in_params.channels());
905 base::WaitableEvent event(false, false);
906 FileAudioSink sink(&event, in_params, file_name);
907 MockAudioSourceCallback source;
909 EXPECT_CALL(source, OnMoreData(NotNull(), _))
910 .WillRepeatedly(Invoke(RealOnMoreData));
911 EXPECT_CALL(source, OnError(audio_output_stream_)).Times(0);
913 OpenAndStartAudioInputStreamOnAudioThread(&sink);
914 OpenAndStartAudioOutputStreamOnAudioThread(&source);
915 DVLOG(0) << ">> Speak into the microphone to record audio";
916 EXPECT_TRUE(event.TimedWait(TestTimeouts::action_max_timeout()));
917 StopAndCloseAudioOutputStreamOnAudioThread();
918 StopAndCloseAudioInputStreamOnAudioThread();
921 // Start audio in both directions while feeding captured data into a FIFO so
922 // it can be read directly (in loopback) by the render side. A small extra
923 // delay will be added by the FIFO and an estimate of this delay will be
924 // printed out during the test.
925 // NOTE: this test requires user interaction and is not designed to run as an
926 // automatized test on bots.
927 TEST_P(AudioAndroidInputTest,
928 DISABLED_RunSymmetricInputAndOutputStreamsInFullDuplex) {
929 // Get native audio parameters for the input side.
930 AudioParameters default_input_params = GetInputStreamParameters();
932 // Modify the parameters so that both input and output can use the same
933 // parameters by selecting 10ms as buffer size. This will also ensure that
934 // the output stream will be a mono stream since mono is default for input
935 // audio on Android.
936 AudioParameters io_params(default_input_params.format(),
937 default_input_params.channel_layout(),
938 ChannelLayoutToChannelCount(
939 default_input_params.channel_layout()),
940 default_input_params.sample_rate(),
941 default_input_params.bits_per_sample(),
942 default_input_params.sample_rate() / 100,
943 default_input_params.effects());
944 DVLOG(1) << io_params;
946 // Create input and output streams using the common audio parameters.
947 MakeAudioInputStreamOnAudioThread(io_params);
948 MakeAudioOutputStreamOnAudioThread(io_params);
950 FullDuplexAudioSinkSource full_duplex(io_params);
952 // Start a full duplex audio session and print out estimates of the extra
953 // delay we should expect from the FIFO. If real-time delay measurements are
954 // performed, the result should be reduced by this extra delay since it is
955 // something that has been added by the test.
956 OpenAndStartAudioInputStreamOnAudioThread(&full_duplex);
957 OpenAndStartAudioOutputStreamOnAudioThread(&full_duplex);
958 DVLOG(1) << "HINT: an estimate of the extra FIFO delay will be updated "
959 << "once per second during this test.";
960 DVLOG(0) << ">> Speak into the mic and listen to the audio in loopback...";
961 fflush(stdout);
962 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
963 printf("\n");
964 StopAndCloseAudioOutputStreamOnAudioThread();
965 StopAndCloseAudioInputStreamOnAudioThread();
968 INSTANTIATE_TEST_CASE_P(AudioAndroidInputTest, AudioAndroidInputTest,
969 testing::ValuesIn(RunAudioRecordInputPathTests()));
971 } // namespace media