Adds "tts" permission for Input Tools & XKB extension.
[chromium-blink-merge.git] / media / audio / android / audio_android_unittest.cc
blob1da84cacb583c106b3a5b9ff96793a97f7f92b9f
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/mock_audio_source_callback.h"
23 #include "media/base/decoder_buffer.h"
24 #include "media/base/seekable_buffer.h"
25 #include "media/base/test_data_util.h"
26 #include "testing/gmock/include/gmock/gmock.h"
27 #include "testing/gtest/include/gtest/gtest.h"
29 using ::testing::_;
30 using ::testing::AtLeast;
31 using ::testing::DoAll;
32 using ::testing::Invoke;
33 using ::testing::NotNull;
34 using ::testing::Return;
36 namespace media {
38 ACTION_P3(CheckCountAndPostQuitTask, count, limit, loop) {
39 if (++*count >= limit) {
40 loop->PostTask(FROM_HERE, base::MessageLoop::QuitClosure());
44 static const char kSpeechFile_16b_s_48k[] = "speech_16b_stereo_48kHz.raw";
45 static const char kSpeechFile_16b_m_48k[] = "speech_16b_mono_48kHz.raw";
46 static const char kSpeechFile_16b_s_44k[] = "speech_16b_stereo_44kHz.raw";
47 static const char kSpeechFile_16b_m_44k[] = "speech_16b_mono_44kHz.raw";
49 static const float kCallbackTestTimeMs = 2000.0;
50 static const int kBitsPerSample = 16;
51 static const int kBytesPerSample = kBitsPerSample / 8;
53 // Converts AudioParameters::Format enumerator to readable string.
54 static std::string FormatToString(AudioParameters::Format format) {
55 switch (format) {
56 case AudioParameters::AUDIO_PCM_LINEAR:
57 return std::string("AUDIO_PCM_LINEAR");
58 case AudioParameters::AUDIO_PCM_LOW_LATENCY:
59 return std::string("AUDIO_PCM_LOW_LATENCY");
60 case AudioParameters::AUDIO_FAKE:
61 return std::string("AUDIO_FAKE");
62 case AudioParameters::AUDIO_LAST_FORMAT:
63 return std::string("AUDIO_LAST_FORMAT");
64 default:
65 return std::string();
69 // Converts ChannelLayout enumerator to readable string. Does not include
70 // multi-channel cases since these layouts are not supported on Android.
71 static std::string LayoutToString(ChannelLayout channel_layout) {
72 switch (channel_layout) {
73 case CHANNEL_LAYOUT_NONE:
74 return std::string("CHANNEL_LAYOUT_NONE");
75 case CHANNEL_LAYOUT_MONO:
76 return std::string("CHANNEL_LAYOUT_MONO");
77 case CHANNEL_LAYOUT_STEREO:
78 return std::string("CHANNEL_LAYOUT_STEREO");
79 case CHANNEL_LAYOUT_UNSUPPORTED:
80 default:
81 return std::string("CHANNEL_LAYOUT_UNSUPPORTED");
85 static double ExpectedTimeBetweenCallbacks(AudioParameters params) {
86 return (base::TimeDelta::FromMicroseconds(
87 params.frames_per_buffer() * base::Time::kMicrosecondsPerSecond /
88 static_cast<double>(params.sample_rate()))).InMillisecondsF();
91 // Helper method which verifies that the device list starts with a valid
92 // default device name followed by non-default device names.
93 static void CheckDeviceNames(const AudioDeviceNames& device_names) {
94 DVLOG(2) << "Got " << device_names.size() << " audio devices.";
95 if (device_names.empty()) {
96 // Log a warning so we can see the status on the build bots. No need to
97 // break the test though since this does successfully test the code and
98 // some failure cases.
99 LOG(WARNING) << "No input devices detected";
100 return;
103 AudioDeviceNames::const_iterator it = device_names.begin();
105 // The first device in the list should always be the default device.
106 EXPECT_EQ(std::string(AudioManagerBase::kDefaultDeviceName),
107 it->device_name);
108 EXPECT_EQ(std::string(AudioManagerBase::kDefaultDeviceId), it->unique_id);
109 ++it;
111 // Other devices should have non-empty name and id and should not contain
112 // default name or id.
113 while (it != device_names.end()) {
114 EXPECT_FALSE(it->device_name.empty());
115 EXPECT_FALSE(it->unique_id.empty());
116 DVLOG(2) << "Device ID(" << it->unique_id
117 << "), label: " << it->device_name;
118 EXPECT_NE(std::string(AudioManagerBase::kDefaultDeviceName),
119 it->device_name);
120 EXPECT_NE(std::string(AudioManagerBase::kDefaultDeviceId),
121 it->unique_id);
122 ++it;
126 // We clear the data bus to ensure that the test does not cause noise.
127 static int RealOnMoreData(AudioBus* dest, uint32 total_bytes_delay) {
128 dest->Zero();
129 return dest->frames();
132 std::ostream& operator<<(std::ostream& os, const AudioParameters& params) {
133 using namespace std;
134 os << endl << "format: " << FormatToString(params.format()) << endl
135 << "channel layout: " << LayoutToString(params.channel_layout()) << endl
136 << "sample rate: " << params.sample_rate() << endl
137 << "bits per sample: " << params.bits_per_sample() << endl
138 << "frames per buffer: " << params.frames_per_buffer() << endl
139 << "channels: " << params.channels() << endl
140 << "bytes per buffer: " << params.GetBytesPerBuffer() << endl
141 << "bytes per second: " << params.GetBytesPerSecond() << endl
142 << "bytes per frame: " << params.GetBytesPerFrame() << endl
143 << "chunk size in ms: " << ExpectedTimeBetweenCallbacks(params) << endl
144 << "echo_canceller: "
145 << (params.effects() & AudioParameters::ECHO_CANCELLER);
146 return os;
149 // Gmock implementation of AudioInputStream::AudioInputCallback.
150 class MockAudioInputCallback : public AudioInputStream::AudioInputCallback {
151 public:
152 MOCK_METHOD4(OnData,
153 void(AudioInputStream* stream,
154 const AudioBus* src,
155 uint32 hardware_delay_bytes,
156 double volume));
157 MOCK_METHOD1(OnError, void(AudioInputStream* stream));
160 // Implements AudioOutputStream::AudioSourceCallback and provides audio data
161 // by reading from a data file.
162 class FileAudioSource : public AudioOutputStream::AudioSourceCallback {
163 public:
164 explicit FileAudioSource(base::WaitableEvent* event, const std::string& name)
165 : event_(event), pos_(0) {
166 // Reads a test file from media/test/data directory and stores it in
167 // a DecoderBuffer.
168 file_ = ReadTestDataFile(name);
170 // Log the name of the file which is used as input for this test.
171 base::FilePath file_path = GetTestDataFilePath(name);
172 DVLOG(0) << "Reading from file: " << file_path.value().c_str();
175 virtual ~FileAudioSource() {}
177 // AudioOutputStream::AudioSourceCallback implementation.
179 // Use samples read from a data file and fill up the audio buffer
180 // provided to us in the callback.
181 virtual int OnMoreData(AudioBus* audio_bus,
182 uint32 total_bytes_delay) override {
183 bool stop_playing = false;
184 int max_size =
185 audio_bus->frames() * audio_bus->channels() * kBytesPerSample;
187 // Adjust data size and prepare for end signal if file has ended.
188 if (pos_ + max_size > file_size()) {
189 stop_playing = true;
190 max_size = file_size() - pos_;
193 // File data is stored as interleaved 16-bit values. Copy data samples from
194 // the file and deinterleave to match the audio bus format.
195 // FromInterleaved() will zero out any unfilled frames when there is not
196 // sufficient data remaining in the file to fill up the complete frame.
197 int frames = max_size / (audio_bus->channels() * kBytesPerSample);
198 if (max_size) {
199 audio_bus->FromInterleaved(file_->data() + pos_, frames, kBytesPerSample);
200 pos_ += max_size;
203 // Set event to ensure that the test can stop when the file has ended.
204 if (stop_playing)
205 event_->Signal();
207 return frames;
210 virtual void OnError(AudioOutputStream* stream) override {}
212 int file_size() { return file_->data_size(); }
214 private:
215 base::WaitableEvent* event_;
216 int pos_;
217 scoped_refptr<DecoderBuffer> file_;
219 DISALLOW_COPY_AND_ASSIGN(FileAudioSource);
222 // Implements AudioInputStream::AudioInputCallback and writes the recorded
223 // audio data to a local output file. Note that this implementation should
224 // only be used for manually invoked and evaluated tests, hence the created
225 // file will not be destroyed after the test is done since the intention is
226 // that it shall be available for off-line analysis.
227 class FileAudioSink : public AudioInputStream::AudioInputCallback {
228 public:
229 explicit FileAudioSink(base::WaitableEvent* event,
230 const AudioParameters& params,
231 const std::string& file_name)
232 : event_(event), params_(params) {
233 // Allocate space for ~10 seconds of data.
234 const int kMaxBufferSize = 10 * params.GetBytesPerSecond();
235 buffer_.reset(new media::SeekableBuffer(0, kMaxBufferSize));
237 // Open up the binary file which will be written to in the destructor.
238 base::FilePath file_path;
239 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &file_path));
240 file_path = file_path.AppendASCII(file_name.c_str());
241 binary_file_ = base::OpenFile(file_path, "wb");
242 DLOG_IF(ERROR, !binary_file_) << "Failed to open binary PCM data file.";
243 DVLOG(0) << "Writing to file: " << file_path.value().c_str();
246 virtual ~FileAudioSink() {
247 int bytes_written = 0;
248 while (bytes_written < buffer_->forward_capacity()) {
249 const uint8* chunk;
250 int chunk_size;
252 // Stop writing if no more data is available.
253 if (!buffer_->GetCurrentChunk(&chunk, &chunk_size))
254 break;
256 // Write recorded data chunk to the file and prepare for next chunk.
257 // TODO(henrika): use file_util:: instead.
258 fwrite(chunk, 1, chunk_size, binary_file_);
259 buffer_->Seek(chunk_size);
260 bytes_written += chunk_size;
262 base::CloseFile(binary_file_);
265 // AudioInputStream::AudioInputCallback implementation.
266 virtual void OnData(AudioInputStream* stream,
267 const AudioBus* src,
268 uint32 hardware_delay_bytes,
269 double volume) override {
270 const int num_samples = src->frames() * src->channels();
271 scoped_ptr<int16> interleaved(new int16[num_samples]);
272 const int bytes_per_sample = sizeof(*interleaved);
273 src->ToInterleaved(src->frames(), bytes_per_sample, interleaved.get());
275 // Store data data in a temporary buffer to avoid making blocking
276 // fwrite() calls in the audio callback. The complete buffer will be
277 // written to file in the destructor.
278 const int size = bytes_per_sample * num_samples;
279 if (!buffer_->Append((const uint8*)interleaved.get(), size))
280 event_->Signal();
283 virtual void OnError(AudioInputStream* stream) override {}
285 private:
286 base::WaitableEvent* event_;
287 AudioParameters params_;
288 scoped_ptr<media::SeekableBuffer> buffer_;
289 FILE* binary_file_;
291 DISALLOW_COPY_AND_ASSIGN(FileAudioSink);
294 // Implements AudioInputCallback and AudioSourceCallback to support full
295 // duplex audio where captured samples are played out in loopback after
296 // reading from a temporary FIFO storage.
297 class FullDuplexAudioSinkSource
298 : public AudioInputStream::AudioInputCallback,
299 public AudioOutputStream::AudioSourceCallback {
300 public:
301 explicit FullDuplexAudioSinkSource(const AudioParameters& params)
302 : params_(params),
303 previous_time_(base::TimeTicks::Now()),
304 started_(false) {
305 // Start with a reasonably small FIFO size. It will be increased
306 // dynamically during the test if required.
307 fifo_.reset(new media::SeekableBuffer(0, 2 * params.GetBytesPerBuffer()));
308 buffer_.reset(new uint8[params_.GetBytesPerBuffer()]);
311 virtual ~FullDuplexAudioSinkSource() {}
313 // AudioInputStream::AudioInputCallback implementation
314 virtual void OnData(AudioInputStream* stream,
315 const AudioBus* src,
316 uint32 hardware_delay_bytes,
317 double volume) override {
318 const base::TimeTicks now_time = base::TimeTicks::Now();
319 const int diff = (now_time - previous_time_).InMilliseconds();
321 EXPECT_EQ(params_.bits_per_sample(), 16);
322 const int num_samples = src->frames() * src->channels();
323 scoped_ptr<int16> interleaved(new int16[num_samples]);
324 const int bytes_per_sample = sizeof(*interleaved);
325 src->ToInterleaved(src->frames(), bytes_per_sample, interleaved.get());
326 const int size = bytes_per_sample * num_samples;
328 base::AutoLock lock(lock_);
329 if (diff > 1000) {
330 started_ = true;
331 previous_time_ = now_time;
333 // Log out the extra delay added by the FIFO. This is a best effort
334 // estimate. We might be +- 10ms off here.
335 int extra_fifo_delay =
336 static_cast<int>(BytesToMilliseconds(fifo_->forward_bytes() + size));
337 DVLOG(1) << extra_fifo_delay;
340 // We add an initial delay of ~1 second before loopback starts to ensure
341 // a stable callback sequence and to avoid initial bursts which might add
342 // to the extra FIFO delay.
343 if (!started_)
344 return;
346 // Append new data to the FIFO and extend the size if the max capacity
347 // was exceeded. Flush the FIFO when extended just in case.
348 if (!fifo_->Append((const uint8*)interleaved.get(), size)) {
349 fifo_->set_forward_capacity(2 * fifo_->forward_capacity());
350 fifo_->Clear();
354 virtual void OnError(AudioInputStream* stream) override {}
356 // AudioOutputStream::AudioSourceCallback implementation
357 virtual int OnMoreData(AudioBus* dest,
358 uint32 total_bytes_delay) override {
359 const int size_in_bytes =
360 (params_.bits_per_sample() / 8) * dest->frames() * dest->channels();
361 EXPECT_EQ(size_in_bytes, params_.GetBytesPerBuffer());
363 base::AutoLock lock(lock_);
365 // We add an initial delay of ~1 second before loopback starts to ensure
366 // a stable callback sequences and to avoid initial bursts which might add
367 // to the extra FIFO delay.
368 if (!started_) {
369 dest->Zero();
370 return dest->frames();
373 // Fill up destination with zeros if the FIFO does not contain enough
374 // data to fulfill the request.
375 if (fifo_->forward_bytes() < size_in_bytes) {
376 dest->Zero();
377 } else {
378 fifo_->Read(buffer_.get(), size_in_bytes);
379 dest->FromInterleaved(
380 buffer_.get(), dest->frames(), params_.bits_per_sample() / 8);
383 return dest->frames();
386 virtual void OnError(AudioOutputStream* stream) override {}
388 private:
389 // Converts from bytes to milliseconds given number of bytes and existing
390 // audio parameters.
391 double BytesToMilliseconds(int bytes) const {
392 const int frames = bytes / params_.GetBytesPerFrame();
393 return (base::TimeDelta::FromMicroseconds(
394 frames * base::Time::kMicrosecondsPerSecond /
395 static_cast<double>(params_.sample_rate()))).InMillisecondsF();
398 AudioParameters params_;
399 base::TimeTicks previous_time_;
400 base::Lock lock_;
401 scoped_ptr<media::SeekableBuffer> fifo_;
402 scoped_ptr<uint8[]> buffer_;
403 bool started_;
405 DISALLOW_COPY_AND_ASSIGN(FullDuplexAudioSinkSource);
408 // Test fixture class for tests which only exercise the output path.
409 class AudioAndroidOutputTest : public testing::Test {
410 public:
411 AudioAndroidOutputTest()
412 : loop_(new base::MessageLoopForUI()),
413 audio_manager_(AudioManager::CreateForTesting()),
414 audio_output_stream_(NULL) {
417 virtual ~AudioAndroidOutputTest() {
420 protected:
421 AudioManager* audio_manager() { return audio_manager_.get(); }
422 base::MessageLoopForUI* loop() { return loop_.get(); }
423 const AudioParameters& audio_output_parameters() {
424 return audio_output_parameters_;
427 // Synchronously runs the provided callback/closure on the audio thread.
428 void RunOnAudioThread(const base::Closure& closure) {
429 if (!audio_manager()->GetTaskRunner()->BelongsToCurrentThread()) {
430 base::WaitableEvent event(false, false);
431 audio_manager()->GetTaskRunner()->PostTask(
432 FROM_HERE,
433 base::Bind(&AudioAndroidOutputTest::RunOnAudioThreadImpl,
434 base::Unretained(this),
435 closure,
436 &event));
437 event.Wait();
438 } else {
439 closure.Run();
443 void RunOnAudioThreadImpl(const base::Closure& closure,
444 base::WaitableEvent* event) {
445 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
446 closure.Run();
447 event->Signal();
450 void GetDefaultOutputStreamParametersOnAudioThread() {
451 RunOnAudioThread(
452 base::Bind(&AudioAndroidOutputTest::GetDefaultOutputStreamParameters,
453 base::Unretained(this)));
456 void MakeAudioOutputStreamOnAudioThread(const AudioParameters& params) {
457 RunOnAudioThread(
458 base::Bind(&AudioAndroidOutputTest::MakeOutputStream,
459 base::Unretained(this),
460 params));
463 void OpenAndCloseAudioOutputStreamOnAudioThread() {
464 RunOnAudioThread(
465 base::Bind(&AudioAndroidOutputTest::OpenAndClose,
466 base::Unretained(this)));
469 void OpenAndStartAudioOutputStreamOnAudioThread(
470 AudioOutputStream::AudioSourceCallback* source) {
471 RunOnAudioThread(
472 base::Bind(&AudioAndroidOutputTest::OpenAndStart,
473 base::Unretained(this),
474 source));
477 void StopAndCloseAudioOutputStreamOnAudioThread() {
478 RunOnAudioThread(
479 base::Bind(&AudioAndroidOutputTest::StopAndClose,
480 base::Unretained(this)));
483 double AverageTimeBetweenCallbacks(int num_callbacks) const {
484 return ((end_time_ - start_time_) / static_cast<double>(num_callbacks - 1))
485 .InMillisecondsF();
488 void StartOutputStreamCallbacks(const AudioParameters& params) {
489 double expected_time_between_callbacks_ms =
490 ExpectedTimeBetweenCallbacks(params);
491 const int num_callbacks =
492 (kCallbackTestTimeMs / expected_time_between_callbacks_ms);
493 MakeAudioOutputStreamOnAudioThread(params);
495 int count = 0;
496 MockAudioSourceCallback source;
498 EXPECT_CALL(source, OnMoreData(NotNull(), _))
499 .Times(AtLeast(num_callbacks))
500 .WillRepeatedly(
501 DoAll(CheckCountAndPostQuitTask(&count, num_callbacks, loop()),
502 Invoke(RealOnMoreData)));
503 EXPECT_CALL(source, OnError(audio_output_stream_)).Times(0);
505 OpenAndStartAudioOutputStreamOnAudioThread(&source);
507 start_time_ = base::TimeTicks::Now();
508 loop()->Run();
509 end_time_ = base::TimeTicks::Now();
511 StopAndCloseAudioOutputStreamOnAudioThread();
513 double average_time_between_callbacks_ms =
514 AverageTimeBetweenCallbacks(num_callbacks);
515 DVLOG(0) << "expected time between callbacks: "
516 << expected_time_between_callbacks_ms << " ms";
517 DVLOG(0) << "average time between callbacks: "
518 << average_time_between_callbacks_ms << " ms";
519 EXPECT_GE(average_time_between_callbacks_ms,
520 0.70 * expected_time_between_callbacks_ms);
521 EXPECT_LE(average_time_between_callbacks_ms,
522 1.50 * expected_time_between_callbacks_ms);
525 void GetDefaultOutputStreamParameters() {
526 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
527 audio_output_parameters_ =
528 audio_manager()->GetDefaultOutputStreamParameters();
529 EXPECT_TRUE(audio_output_parameters_.IsValid());
532 void MakeOutputStream(const AudioParameters& params) {
533 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
534 audio_output_stream_ = audio_manager()->MakeAudioOutputStream(
535 params, std::string());
536 EXPECT_TRUE(audio_output_stream_);
539 void OpenAndClose() {
540 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
541 EXPECT_TRUE(audio_output_stream_->Open());
542 audio_output_stream_->Close();
543 audio_output_stream_ = NULL;
546 void OpenAndStart(AudioOutputStream::AudioSourceCallback* source) {
547 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
548 EXPECT_TRUE(audio_output_stream_->Open());
549 audio_output_stream_->Start(source);
552 void StopAndClose() {
553 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
554 audio_output_stream_->Stop();
555 audio_output_stream_->Close();
556 audio_output_stream_ = NULL;
559 scoped_ptr<base::MessageLoopForUI> loop_;
560 scoped_ptr<AudioManager> audio_manager_;
561 AudioParameters audio_output_parameters_;
562 AudioOutputStream* audio_output_stream_;
563 base::TimeTicks start_time_;
564 base::TimeTicks end_time_;
566 private:
567 DISALLOW_COPY_AND_ASSIGN(AudioAndroidOutputTest);
570 // AudioRecordInputStream should only be created on Jelly Bean and higher. This
571 // ensures we only test against the AudioRecord path when that is satisfied.
572 std::vector<bool> RunAudioRecordInputPathTests() {
573 std::vector<bool> tests;
574 tests.push_back(false);
575 if (base::android::BuildInfo::GetInstance()->sdk_int() >= 16)
576 tests.push_back(true);
577 return tests;
580 // Test fixture class for tests which exercise the input path, or both input and
581 // output paths. It is value-parameterized to test against both the Java
582 // AudioRecord (when true) and native OpenSLES (when false) input paths.
583 class AudioAndroidInputTest : public AudioAndroidOutputTest,
584 public testing::WithParamInterface<bool> {
585 public:
586 AudioAndroidInputTest() : audio_input_stream_(NULL) {}
588 protected:
589 const AudioParameters& audio_input_parameters() {
590 return audio_input_parameters_;
593 AudioParameters GetInputStreamParameters() {
594 GetDefaultInputStreamParametersOnAudioThread();
596 // Override the platform effects setting to use the AudioRecord or OpenSLES
597 // path as requested.
598 int effects = GetParam() ? AudioParameters::ECHO_CANCELLER :
599 AudioParameters::NO_EFFECTS;
600 AudioParameters params(audio_input_parameters().format(),
601 audio_input_parameters().channel_layout(),
602 audio_input_parameters().sample_rate(),
603 audio_input_parameters().bits_per_sample(),
604 audio_input_parameters().frames_per_buffer(),
605 effects);
606 return params;
609 void GetDefaultInputStreamParametersOnAudioThread() {
610 RunOnAudioThread(
611 base::Bind(&AudioAndroidInputTest::GetDefaultInputStreamParameters,
612 base::Unretained(this)));
615 void MakeAudioInputStreamOnAudioThread(const AudioParameters& params) {
616 RunOnAudioThread(
617 base::Bind(&AudioAndroidInputTest::MakeInputStream,
618 base::Unretained(this),
619 params));
622 void OpenAndCloseAudioInputStreamOnAudioThread() {
623 RunOnAudioThread(
624 base::Bind(&AudioAndroidInputTest::OpenAndClose,
625 base::Unretained(this)));
628 void OpenAndStartAudioInputStreamOnAudioThread(
629 AudioInputStream::AudioInputCallback* sink) {
630 RunOnAudioThread(
631 base::Bind(&AudioAndroidInputTest::OpenAndStart,
632 base::Unretained(this),
633 sink));
636 void StopAndCloseAudioInputStreamOnAudioThread() {
637 RunOnAudioThread(
638 base::Bind(&AudioAndroidInputTest::StopAndClose,
639 base::Unretained(this)));
642 void StartInputStreamCallbacks(const AudioParameters& params) {
643 double expected_time_between_callbacks_ms =
644 ExpectedTimeBetweenCallbacks(params);
645 const int num_callbacks =
646 (kCallbackTestTimeMs / expected_time_between_callbacks_ms);
648 MakeAudioInputStreamOnAudioThread(params);
650 int count = 0;
651 MockAudioInputCallback sink;
653 EXPECT_CALL(sink, OnData(audio_input_stream_, NotNull(), _, _))
654 .Times(AtLeast(num_callbacks))
655 .WillRepeatedly(
656 CheckCountAndPostQuitTask(&count, num_callbacks, loop()));
657 EXPECT_CALL(sink, OnError(audio_input_stream_)).Times(0);
659 OpenAndStartAudioInputStreamOnAudioThread(&sink);
661 start_time_ = base::TimeTicks::Now();
662 loop()->Run();
663 end_time_ = base::TimeTicks::Now();
665 StopAndCloseAudioInputStreamOnAudioThread();
667 double average_time_between_callbacks_ms =
668 AverageTimeBetweenCallbacks(num_callbacks);
669 DVLOG(0) << "expected time between callbacks: "
670 << expected_time_between_callbacks_ms << " ms";
671 DVLOG(0) << "average time between callbacks: "
672 << average_time_between_callbacks_ms << " ms";
673 EXPECT_GE(average_time_between_callbacks_ms,
674 0.70 * expected_time_between_callbacks_ms);
675 EXPECT_LE(average_time_between_callbacks_ms,
676 1.30 * expected_time_between_callbacks_ms);
679 void GetDefaultInputStreamParameters() {
680 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
681 audio_input_parameters_ = audio_manager()->GetInputStreamParameters(
682 AudioManagerBase::kDefaultDeviceId);
685 void MakeInputStream(const AudioParameters& params) {
686 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
687 audio_input_stream_ = audio_manager()->MakeAudioInputStream(
688 params, AudioManagerBase::kDefaultDeviceId);
689 EXPECT_TRUE(audio_input_stream_);
692 void OpenAndClose() {
693 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
694 EXPECT_TRUE(audio_input_stream_->Open());
695 audio_input_stream_->Close();
696 audio_input_stream_ = NULL;
699 void OpenAndStart(AudioInputStream::AudioInputCallback* sink) {
700 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
701 EXPECT_TRUE(audio_input_stream_->Open());
702 audio_input_stream_->Start(sink);
705 void StopAndClose() {
706 DCHECK(audio_manager()->GetTaskRunner()->BelongsToCurrentThread());
707 audio_input_stream_->Stop();
708 audio_input_stream_->Close();
709 audio_input_stream_ = NULL;
712 AudioInputStream* audio_input_stream_;
713 AudioParameters audio_input_parameters_;
715 private:
716 DISALLOW_COPY_AND_ASSIGN(AudioAndroidInputTest);
719 // Get the default audio input parameters and log the result.
720 TEST_P(AudioAndroidInputTest, GetDefaultInputStreamParameters) {
721 // We don't go through AudioAndroidInputTest::GetInputStreamParameters() here
722 // so that we can log the real (non-overridden) values of the effects.
723 GetDefaultInputStreamParametersOnAudioThread();
724 EXPECT_TRUE(audio_input_parameters().IsValid());
725 DVLOG(1) << audio_input_parameters();
728 // Get the default audio output parameters and log the result.
729 TEST_F(AudioAndroidOutputTest, GetDefaultOutputStreamParameters) {
730 GetDefaultOutputStreamParametersOnAudioThread();
731 DVLOG(1) << audio_output_parameters();
734 // Verify input device enumeration.
735 TEST_F(AudioAndroidInputTest, GetAudioInputDeviceNames) {
736 if (!audio_manager()->HasAudioInputDevices())
737 return;
738 AudioDeviceNames devices;
739 RunOnAudioThread(
740 base::Bind(&AudioManager::GetAudioInputDeviceNames,
741 base::Unretained(audio_manager()),
742 &devices));
743 CheckDeviceNames(devices);
746 // Verify output device enumeration.
747 TEST_F(AudioAndroidOutputTest, GetAudioOutputDeviceNames) {
748 if (!audio_manager()->HasAudioOutputDevices())
749 return;
750 AudioDeviceNames devices;
751 RunOnAudioThread(
752 base::Bind(&AudioManager::GetAudioOutputDeviceNames,
753 base::Unretained(audio_manager()),
754 &devices));
755 CheckDeviceNames(devices);
758 // Ensure that a default input stream can be created and closed.
759 TEST_P(AudioAndroidInputTest, CreateAndCloseInputStream) {
760 AudioParameters params = GetInputStreamParameters();
761 MakeAudioInputStreamOnAudioThread(params);
762 RunOnAudioThread(
763 base::Bind(&AudioInputStream::Close,
764 base::Unretained(audio_input_stream_)));
767 // Ensure that a default output stream can be created and closed.
768 // TODO(henrika): should we also verify that this API changes the audio mode
769 // to communication mode, and calls RegisterHeadsetReceiver, the first time
770 // it is called?
771 TEST_F(AudioAndroidOutputTest, CreateAndCloseOutputStream) {
772 GetDefaultOutputStreamParametersOnAudioThread();
773 MakeAudioOutputStreamOnAudioThread(audio_output_parameters());
774 RunOnAudioThread(
775 base::Bind(&AudioOutputStream::Close,
776 base::Unretained(audio_output_stream_)));
779 // Ensure that a default input stream can be opened and closed.
780 TEST_P(AudioAndroidInputTest, OpenAndCloseInputStream) {
781 AudioParameters params = GetInputStreamParameters();
782 MakeAudioInputStreamOnAudioThread(params);
783 OpenAndCloseAudioInputStreamOnAudioThread();
786 // Ensure that a default output stream can be opened and closed.
787 TEST_F(AudioAndroidOutputTest, OpenAndCloseOutputStream) {
788 GetDefaultOutputStreamParametersOnAudioThread();
789 MakeAudioOutputStreamOnAudioThread(audio_output_parameters());
790 OpenAndCloseAudioOutputStreamOnAudioThread();
793 // Start input streaming using default input parameters and ensure that the
794 // callback sequence is sane.
795 TEST_P(AudioAndroidInputTest, DISABLED_StartInputStreamCallbacks) {
796 AudioParameters native_params = GetInputStreamParameters();
797 StartInputStreamCallbacks(native_params);
800 // Start input streaming using non default input parameters and ensure that the
801 // callback sequence is sane. The only change we make in this test is to select
802 // a 10ms buffer size instead of the default size.
803 TEST_P(AudioAndroidInputTest,
804 DISABLED_StartInputStreamCallbacksNonDefaultParameters) {
805 AudioParameters native_params = GetInputStreamParameters();
806 AudioParameters params(native_params.format(),
807 native_params.channel_layout(),
808 native_params.sample_rate(),
809 native_params.bits_per_sample(),
810 native_params.sample_rate() / 100,
811 native_params.effects());
812 StartInputStreamCallbacks(params);
815 // Start output streaming using default output parameters and ensure that the
816 // callback sequence is sane.
817 TEST_F(AudioAndroidOutputTest, StartOutputStreamCallbacks) {
818 GetDefaultOutputStreamParametersOnAudioThread();
819 StartOutputStreamCallbacks(audio_output_parameters());
822 // Start output streaming using non default output parameters and ensure that
823 // the callback sequence is sane. The only change we make in this test is to
824 // select a 10ms buffer size instead of the default size and to open up the
825 // device in mono.
826 // TODO(henrika): possibly add support for more variations.
827 TEST_F(AudioAndroidOutputTest, StartOutputStreamCallbacksNonDefaultParameters) {
828 GetDefaultOutputStreamParametersOnAudioThread();
829 AudioParameters params(audio_output_parameters().format(),
830 CHANNEL_LAYOUT_MONO,
831 audio_output_parameters().sample_rate(),
832 audio_output_parameters().bits_per_sample(),
833 audio_output_parameters().sample_rate() / 100);
834 StartOutputStreamCallbacks(params);
837 // Play out a PCM file segment in real time and allow the user to verify that
838 // the rendered audio sounds OK.
839 // NOTE: this test requires user interaction and is not designed to run as an
840 // automatized test on bots.
841 TEST_F(AudioAndroidOutputTest, DISABLED_RunOutputStreamWithFileAsSource) {
842 GetDefaultOutputStreamParametersOnAudioThread();
843 DVLOG(1) << audio_output_parameters();
844 MakeAudioOutputStreamOnAudioThread(audio_output_parameters());
846 std::string file_name;
847 const AudioParameters params = audio_output_parameters();
848 if (params.sample_rate() == 48000 && params.channels() == 2) {
849 file_name = kSpeechFile_16b_s_48k;
850 } else if (params.sample_rate() == 48000 && params.channels() == 1) {
851 file_name = kSpeechFile_16b_m_48k;
852 } else if (params.sample_rate() == 44100 && params.channels() == 2) {
853 file_name = kSpeechFile_16b_s_44k;
854 } else if (params.sample_rate() == 44100 && params.channels() == 1) {
855 file_name = kSpeechFile_16b_m_44k;
856 } else {
857 FAIL() << "This test supports 44.1kHz and 48kHz mono/stereo only.";
858 return;
861 base::WaitableEvent event(false, false);
862 FileAudioSource source(&event, file_name);
864 OpenAndStartAudioOutputStreamOnAudioThread(&source);
865 DVLOG(0) << ">> Verify that the file is played out correctly...";
866 EXPECT_TRUE(event.TimedWait(TestTimeouts::action_max_timeout()));
867 StopAndCloseAudioOutputStreamOnAudioThread();
870 // Start input streaming and run it for ten seconds while recording to a
871 // local audio file.
872 // NOTE: this test requires user interaction and is not designed to run as an
873 // automatized test on bots.
874 TEST_P(AudioAndroidInputTest, DISABLED_RunSimplexInputStreamWithFileAsSink) {
875 AudioParameters params = GetInputStreamParameters();
876 DVLOG(1) << params;
877 MakeAudioInputStreamOnAudioThread(params);
879 std::string file_name = base::StringPrintf("out_simplex_%d_%d_%d.pcm",
880 params.sample_rate(),
881 params.frames_per_buffer(),
882 params.channels());
884 base::WaitableEvent event(false, false);
885 FileAudioSink sink(&event, params, file_name);
887 OpenAndStartAudioInputStreamOnAudioThread(&sink);
888 DVLOG(0) << ">> Speak into the microphone to record audio...";
889 EXPECT_TRUE(event.TimedWait(TestTimeouts::action_max_timeout()));
890 StopAndCloseAudioInputStreamOnAudioThread();
893 // Same test as RunSimplexInputStreamWithFileAsSink but this time output
894 // streaming is active as well (reads zeros only).
895 // NOTE: this test requires user interaction and is not designed to run as an
896 // automatized test on bots.
897 TEST_P(AudioAndroidInputTest, DISABLED_RunDuplexInputStreamWithFileAsSink) {
898 AudioParameters in_params = GetInputStreamParameters();
899 DVLOG(1) << in_params;
900 MakeAudioInputStreamOnAudioThread(in_params);
902 GetDefaultOutputStreamParametersOnAudioThread();
903 DVLOG(1) << audio_output_parameters();
904 MakeAudioOutputStreamOnAudioThread(audio_output_parameters());
906 std::string file_name = base::StringPrintf("out_duplex_%d_%d_%d.pcm",
907 in_params.sample_rate(),
908 in_params.frames_per_buffer(),
909 in_params.channels());
911 base::WaitableEvent event(false, false);
912 FileAudioSink sink(&event, in_params, file_name);
913 MockAudioSourceCallback source;
915 EXPECT_CALL(source, OnMoreData(NotNull(), _))
916 .WillRepeatedly(Invoke(RealOnMoreData));
917 EXPECT_CALL(source, OnError(audio_output_stream_)).Times(0);
919 OpenAndStartAudioInputStreamOnAudioThread(&sink);
920 OpenAndStartAudioOutputStreamOnAudioThread(&source);
921 DVLOG(0) << ">> Speak into the microphone to record audio";
922 EXPECT_TRUE(event.TimedWait(TestTimeouts::action_max_timeout()));
923 StopAndCloseAudioOutputStreamOnAudioThread();
924 StopAndCloseAudioInputStreamOnAudioThread();
927 // Start audio in both directions while feeding captured data into a FIFO so
928 // it can be read directly (in loopback) by the render side. A small extra
929 // delay will be added by the FIFO and an estimate of this delay will be
930 // printed out during the test.
931 // NOTE: this test requires user interaction and is not designed to run as an
932 // automatized test on bots.
933 TEST_P(AudioAndroidInputTest,
934 DISABLED_RunSymmetricInputAndOutputStreamsInFullDuplex) {
935 // Get native audio parameters for the input side.
936 AudioParameters default_input_params = GetInputStreamParameters();
938 // Modify the parameters so that both input and output can use the same
939 // parameters by selecting 10ms as buffer size. This will also ensure that
940 // the output stream will be a mono stream since mono is default for input
941 // audio on Android.
942 AudioParameters io_params(default_input_params.format(),
943 default_input_params.channel_layout(),
944 ChannelLayoutToChannelCount(
945 default_input_params.channel_layout()),
946 default_input_params.sample_rate(),
947 default_input_params.bits_per_sample(),
948 default_input_params.sample_rate() / 100,
949 default_input_params.effects());
950 DVLOG(1) << io_params;
952 // Create input and output streams using the common audio parameters.
953 MakeAudioInputStreamOnAudioThread(io_params);
954 MakeAudioOutputStreamOnAudioThread(io_params);
956 FullDuplexAudioSinkSource full_duplex(io_params);
958 // Start a full duplex audio session and print out estimates of the extra
959 // delay we should expect from the FIFO. If real-time delay measurements are
960 // performed, the result should be reduced by this extra delay since it is
961 // something that has been added by the test.
962 OpenAndStartAudioInputStreamOnAudioThread(&full_duplex);
963 OpenAndStartAudioOutputStreamOnAudioThread(&full_duplex);
964 DVLOG(1) << "HINT: an estimate of the extra FIFO delay will be updated "
965 << "once per second during this test.";
966 DVLOG(0) << ">> Speak into the mic and listen to the audio in loopback...";
967 fflush(stdout);
968 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
969 printf("\n");
970 StopAndCloseAudioOutputStreamOnAudioThread();
971 StopAndCloseAudioInputStreamOnAudioThread();
974 INSTANTIATE_TEST_CASE_P(AudioAndroidInputTest, AudioAndroidInputTest,
975 testing::ValuesIn(RunAudioRecordInputPathTests()));
977 } // namespace media