audio_android_unittest.cc revision 5d1f7b1de12d16ceb2c938c56701a3e8bfa558f7
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. 4 5#include "base/android/build_info.h" 6#include "base/basictypes.h" 7#include "base/file_util.h" 8#include "base/memory/scoped_ptr.h" 9#include "base/message_loop/message_loop.h" 10#include "base/path_service.h" 11#include "base/strings/stringprintf.h" 12#include "base/synchronization/lock.h" 13#include "base/synchronization/waitable_event.h" 14#include "base/test/test_timeouts.h" 15#include "base/time/time.h" 16#include "build/build_config.h" 17#include "media/audio/android/audio_manager_android.h" 18#include "media/audio/audio_io.h" 19#include "media/audio/audio_manager_base.h" 20#include "media/audio/mock_audio_source_callback.h" 21#include "media/base/decoder_buffer.h" 22#include "media/base/seekable_buffer.h" 23#include "media/base/test_data_util.h" 24#include "testing/gmock/include/gmock/gmock.h" 25#include "testing/gtest/include/gtest/gtest.h" 26 27using ::testing::_; 28using ::testing::AtLeast; 29using ::testing::DoAll; 30using ::testing::Invoke; 31using ::testing::NotNull; 32using ::testing::Return; 33 34namespace media { 35 36ACTION_P3(CheckCountAndPostQuitTask, count, limit, loop) { 37 if (++*count >= limit) { 38 loop->PostTask(FROM_HERE, base::MessageLoop::QuitClosure()); 39 } 40} 41 42static const char kSpeechFile_16b_s_48k[] = "speech_16b_stereo_48kHz.raw"; 43static const char kSpeechFile_16b_m_48k[] = "speech_16b_mono_48kHz.raw"; 44static const char kSpeechFile_16b_s_44k[] = "speech_16b_stereo_44kHz.raw"; 45static const char kSpeechFile_16b_m_44k[] = "speech_16b_mono_44kHz.raw"; 46 47static const float kCallbackTestTimeMs = 2000.0; 48static const int kBitsPerSample = 16; 49static const int kBytesPerSample = kBitsPerSample / 8; 50 51// Converts AudioParameters::Format enumerator to readable string. 52static std::string FormatToString(AudioParameters::Format format) { 53 switch (format) { 54 case AudioParameters::AUDIO_PCM_LINEAR: 55 return std::string("AUDIO_PCM_LINEAR"); 56 case AudioParameters::AUDIO_PCM_LOW_LATENCY: 57 return std::string("AUDIO_PCM_LOW_LATENCY"); 58 case AudioParameters::AUDIO_FAKE: 59 return std::string("AUDIO_FAKE"); 60 case AudioParameters::AUDIO_LAST_FORMAT: 61 return std::string("AUDIO_LAST_FORMAT"); 62 default: 63 return std::string(); 64 } 65} 66 67// Converts ChannelLayout enumerator to readable string. Does not include 68// multi-channel cases since these layouts are not supported on Android. 69static std::string LayoutToString(ChannelLayout channel_layout) { 70 switch (channel_layout) { 71 case CHANNEL_LAYOUT_NONE: 72 return std::string("CHANNEL_LAYOUT_NONE"); 73 case CHANNEL_LAYOUT_MONO: 74 return std::string("CHANNEL_LAYOUT_MONO"); 75 case CHANNEL_LAYOUT_STEREO: 76 return std::string("CHANNEL_LAYOUT_STEREO"); 77 case CHANNEL_LAYOUT_UNSUPPORTED: 78 default: 79 return std::string("CHANNEL_LAYOUT_UNSUPPORTED"); 80 } 81} 82 83static double ExpectedTimeBetweenCallbacks(AudioParameters params) { 84 return (base::TimeDelta::FromMicroseconds( 85 params.frames_per_buffer() * base::Time::kMicrosecondsPerSecond / 86 static_cast<double>(params.sample_rate()))).InMillisecondsF(); 87} 88 89// Helper method which verifies that the device list starts with a valid 90// default device name followed by non-default device names. 91static void CheckDeviceNames(const AudioDeviceNames& device_names) { 92 VLOG(2) << "Got " << device_names.size() << " audio devices."; 93 if (device_names.empty()) { 94 // Log a warning so we can see the status on the build bots. No need to 95 // break the test though since this does successfully test the code and 96 // some failure cases. 97 LOG(WARNING) << "No input devices detected"; 98 return; 99 } 100 101 AudioDeviceNames::const_iterator it = device_names.begin(); 102 103 // The first device in the list should always be the default device. 104 EXPECT_EQ(std::string(AudioManagerBase::kDefaultDeviceName), 105 it->device_name); 106 EXPECT_EQ(std::string(AudioManagerBase::kDefaultDeviceId), it->unique_id); 107 ++it; 108 109 // Other devices should have non-empty name and id and should not contain 110 // default name or id. 111 while (it != device_names.end()) { 112 EXPECT_FALSE(it->device_name.empty()); 113 EXPECT_FALSE(it->unique_id.empty()); 114 VLOG(2) << "Device ID(" << it->unique_id 115 << "), label: " << it->device_name; 116 EXPECT_NE(std::string(AudioManagerBase::kDefaultDeviceName), 117 it->device_name); 118 EXPECT_NE(std::string(AudioManagerBase::kDefaultDeviceId), 119 it->unique_id); 120 ++it; 121 } 122} 123 124// We clear the data bus to ensure that the test does not cause noise. 125static int RealOnMoreData(AudioBus* dest, AudioBuffersState buffers_state) { 126 dest->Zero(); 127 return dest->frames(); 128} 129 130std::ostream& operator<<(std::ostream& os, const AudioParameters& params) { 131 using namespace std; 132 os << endl << "format: " << FormatToString(params.format()) << endl 133 << "channel layout: " << LayoutToString(params.channel_layout()) << endl 134 << "sample rate: " << params.sample_rate() << endl 135 << "bits per sample: " << params.bits_per_sample() << endl 136 << "frames per buffer: " << params.frames_per_buffer() << endl 137 << "channels: " << params.channels() << endl 138 << "bytes per buffer: " << params.GetBytesPerBuffer() << endl 139 << "bytes per second: " << params.GetBytesPerSecond() << endl 140 << "bytes per frame: " << params.GetBytesPerFrame() << endl 141 << "chunk size in ms: " << ExpectedTimeBetweenCallbacks(params) << endl 142 << "echo_canceller: " 143 << (params.effects() & AudioParameters::ECHO_CANCELLER); 144 return os; 145} 146 147// Gmock implementation of AudioInputStream::AudioInputCallback. 148class MockAudioInputCallback : public AudioInputStream::AudioInputCallback { 149 public: 150 MOCK_METHOD5(OnData, 151 void(AudioInputStream* stream, 152 const uint8* src, 153 uint32 size, 154 uint32 hardware_delay_bytes, 155 double volume)); 156 MOCK_METHOD1(OnError, void(AudioInputStream* stream)); 157}; 158 159// Implements AudioOutputStream::AudioSourceCallback and provides audio data 160// by reading from a data file. 161class 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); 168 169 // Log the name of the file which is used as input for this test. 170 base::FilePath file_path = GetTestDataFilePath(name); 171 VLOG(0) << "Reading from file: " << file_path.value().c_str(); 172 } 173 174 virtual ~FileAudioSource() {} 175 176 // AudioOutputStream::AudioSourceCallback implementation. 177 178 // Use samples read from a data file and fill up the audio buffer 179 // provided to us in the callback. 180 virtual int OnMoreData(AudioBus* audio_bus, 181 AudioBuffersState buffers_state) OVERRIDE { 182 bool stop_playing = false; 183 int max_size = 184 audio_bus->frames() * audio_bus->channels() * kBytesPerSample; 185 186 // Adjust data size and prepare for end signal if file has ended. 187 if (pos_ + max_size > file_size()) { 188 stop_playing = true; 189 max_size = file_size() - pos_; 190 } 191 192 // File data is stored as interleaved 16-bit values. Copy data samples from 193 // the file and deinterleave to match the audio bus format. 194 // FromInterleaved() will zero out any unfilled frames when there is not 195 // sufficient data remaining in the file to fill up the complete frame. 196 int frames = max_size / (audio_bus->channels() * kBytesPerSample); 197 if (max_size) { 198 audio_bus->FromInterleaved(file_->data() + pos_, frames, kBytesPerSample); 199 pos_ += max_size; 200 } 201 202 // Set event to ensure that the test can stop when the file has ended. 203 if (stop_playing) 204 event_->Signal(); 205 206 return frames; 207 } 208 209 virtual int OnMoreIOData(AudioBus* source, 210 AudioBus* dest, 211 AudioBuffersState buffers_state) OVERRIDE { 212 NOTREACHED(); 213 return 0; 214 } 215 216 virtual void OnError(AudioOutputStream* stream) OVERRIDE {} 217 218 int file_size() { return file_->data_size(); } 219 220 private: 221 base::WaitableEvent* event_; 222 int pos_; 223 scoped_refptr<DecoderBuffer> file_; 224 225 DISALLOW_COPY_AND_ASSIGN(FileAudioSource); 226}; 227 228// Implements AudioInputStream::AudioInputCallback and writes the recorded 229// audio data to a local output file. Note that this implementation should 230// only be used for manually invoked and evaluated tests, hence the created 231// file will not be destroyed after the test is done since the intention is 232// that it shall be available for off-line analysis. 233class FileAudioSink : public AudioInputStream::AudioInputCallback { 234 public: 235 explicit FileAudioSink(base::WaitableEvent* event, 236 const AudioParameters& params, 237 const std::string& file_name) 238 : event_(event), params_(params) { 239 // Allocate space for ~10 seconds of data. 240 const int kMaxBufferSize = 10 * params.GetBytesPerSecond(); 241 buffer_.reset(new media::SeekableBuffer(0, kMaxBufferSize)); 242 243 // Open up the binary file which will be written to in the destructor. 244 base::FilePath file_path; 245 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &file_path)); 246 file_path = file_path.AppendASCII(file_name.c_str()); 247 binary_file_ = base::OpenFile(file_path, "wb"); 248 DLOG_IF(ERROR, !binary_file_) << "Failed to open binary PCM data file."; 249 VLOG(0) << "Writing to file: " << file_path.value().c_str(); 250 } 251 252 virtual ~FileAudioSink() { 253 int bytes_written = 0; 254 while (bytes_written < buffer_->forward_capacity()) { 255 const uint8* chunk; 256 int chunk_size; 257 258 // Stop writing if no more data is available. 259 if (!buffer_->GetCurrentChunk(&chunk, &chunk_size)) 260 break; 261 262 // Write recorded data chunk to the file and prepare for next chunk. 263 // TODO(henrika): use file_util:: instead. 264 fwrite(chunk, 1, chunk_size, binary_file_); 265 buffer_->Seek(chunk_size); 266 bytes_written += chunk_size; 267 } 268 base::CloseFile(binary_file_); 269 } 270 271 // AudioInputStream::AudioInputCallback implementation. 272 virtual void OnData(AudioInputStream* stream, 273 const uint8* src, 274 uint32 size, 275 uint32 hardware_delay_bytes, 276 double volume) OVERRIDE { 277 // Store data data in a temporary buffer to avoid making blocking 278 // fwrite() calls in the audio callback. The complete buffer will be 279 // written to file in the destructor. 280 if (!buffer_->Append(src, size)) 281 event_->Signal(); 282 } 283 284 virtual void OnError(AudioInputStream* stream) OVERRIDE {} 285 286 private: 287 base::WaitableEvent* event_; 288 AudioParameters params_; 289 scoped_ptr<media::SeekableBuffer> buffer_; 290 FILE* binary_file_; 291 292 DISALLOW_COPY_AND_ASSIGN(FileAudioSink); 293}; 294 295// Implements AudioInputCallback and AudioSourceCallback to support full 296// duplex audio where captured samples are played out in loopback after 297// reading from a temporary FIFO storage. 298class FullDuplexAudioSinkSource 299 : public AudioInputStream::AudioInputCallback, 300 public AudioOutputStream::AudioSourceCallback { 301 public: 302 explicit FullDuplexAudioSinkSource(const AudioParameters& params) 303 : params_(params), 304 previous_time_(base::TimeTicks::Now()), 305 started_(false) { 306 // Start with a reasonably small FIFO size. It will be increased 307 // dynamically during the test if required. 308 fifo_.reset(new media::SeekableBuffer(0, 2 * params.GetBytesPerBuffer())); 309 buffer_.reset(new uint8[params_.GetBytesPerBuffer()]); 310 } 311 312 virtual ~FullDuplexAudioSinkSource() {} 313 314 // AudioInputStream::AudioInputCallback implementation 315 virtual void OnData(AudioInputStream* stream, 316 const uint8* src, 317 uint32 size, 318 uint32 hardware_delay_bytes, 319 double volume) OVERRIDE { 320 const base::TimeTicks now_time = base::TimeTicks::Now(); 321 const int diff = (now_time - previous_time_).InMilliseconds(); 322 323 base::AutoLock lock(lock_); 324 if (diff > 1000) { 325 started_ = true; 326 previous_time_ = now_time; 327 328 // Log out the extra delay added by the FIFO. This is a best effort 329 // estimate. We might be +- 10ms off here. 330 int extra_fifo_delay = 331 static_cast<int>(BytesToMilliseconds(fifo_->forward_bytes() + size)); 332 DVLOG(1) << extra_fifo_delay; 333 } 334 335 // We add an initial delay of ~1 second before loopback starts to ensure 336 // a stable callback sequence and to avoid initial bursts which might add 337 // to the extra FIFO delay. 338 if (!started_) 339 return; 340 341 // Append new data to the FIFO and extend the size if the max capacity 342 // was exceeded. Flush the FIFO when extended just in case. 343 if (!fifo_->Append(src, size)) { 344 fifo_->set_forward_capacity(2 * fifo_->forward_capacity()); 345 fifo_->Clear(); 346 } 347 } 348 349 virtual void OnError(AudioInputStream* stream) OVERRIDE {} 350 351 // AudioOutputStream::AudioSourceCallback implementation 352 virtual int OnMoreData(AudioBus* dest, 353 AudioBuffersState buffers_state) OVERRIDE { 354 const int size_in_bytes = 355 (params_.bits_per_sample() / 8) * dest->frames() * dest->channels(); 356 EXPECT_EQ(size_in_bytes, params_.GetBytesPerBuffer()); 357 358 base::AutoLock lock(lock_); 359 360 // We add an initial delay of ~1 second before loopback starts to ensure 361 // a stable callback sequences and to avoid initial bursts which might add 362 // to the extra FIFO delay. 363 if (!started_) { 364 dest->Zero(); 365 return dest->frames(); 366 } 367 368 // Fill up destination with zeros if the FIFO does not contain enough 369 // data to fulfill the request. 370 if (fifo_->forward_bytes() < size_in_bytes) { 371 dest->Zero(); 372 } else { 373 fifo_->Read(buffer_.get(), size_in_bytes); 374 dest->FromInterleaved( 375 buffer_.get(), dest->frames(), params_.bits_per_sample() / 8); 376 } 377 378 return dest->frames(); 379 } 380 381 virtual int OnMoreIOData(AudioBus* source, 382 AudioBus* dest, 383 AudioBuffersState buffers_state) OVERRIDE { 384 NOTREACHED(); 385 return 0; 386 } 387 388 virtual void OnError(AudioOutputStream* stream) OVERRIDE {} 389 390 private: 391 // Converts from bytes to milliseconds given number of bytes and existing 392 // audio parameters. 393 double BytesToMilliseconds(int bytes) const { 394 const int frames = bytes / params_.GetBytesPerFrame(); 395 return (base::TimeDelta::FromMicroseconds( 396 frames * base::Time::kMicrosecondsPerSecond / 397 static_cast<double>(params_.sample_rate()))).InMillisecondsF(); 398 } 399 400 AudioParameters params_; 401 base::TimeTicks previous_time_; 402 base::Lock lock_; 403 scoped_ptr<media::SeekableBuffer> fifo_; 404 scoped_ptr<uint8[]> buffer_; 405 bool started_; 406 407 DISALLOW_COPY_AND_ASSIGN(FullDuplexAudioSinkSource); 408}; 409 410// Test fixture class for tests which only exercise the output path. 411class AudioAndroidOutputTest : public testing::Test { 412 public: 413 AudioAndroidOutputTest() {} 414 415 protected: 416 virtual void SetUp() { 417 audio_manager_.reset(AudioManager::CreateForTesting()); 418 loop_.reset(new base::MessageLoopForUI()); 419 } 420 421 virtual void TearDown() {} 422 423 AudioManager* audio_manager() { return audio_manager_.get(); } 424 base::MessageLoopForUI* loop() { return loop_.get(); } 425 426 AudioParameters GetDefaultOutputStreamParameters() { 427 return audio_manager()->GetDefaultOutputStreamParameters(); 428 } 429 430 double AverageTimeBetweenCallbacks(int num_callbacks) const { 431 return ((end_time_ - start_time_) / static_cast<double>(num_callbacks - 1)) 432 .InMillisecondsF(); 433 } 434 435 void StartOutputStreamCallbacks(const AudioParameters& params) { 436 double expected_time_between_callbacks_ms = 437 ExpectedTimeBetweenCallbacks(params); 438 const int num_callbacks = 439 (kCallbackTestTimeMs / expected_time_between_callbacks_ms); 440 AudioOutputStream* stream = audio_manager()->MakeAudioOutputStream( 441 params, std::string()); 442 EXPECT_TRUE(stream); 443 444 int count = 0; 445 MockAudioSourceCallback source; 446 447 EXPECT_CALL(source, OnMoreData(NotNull(), _)) 448 .Times(AtLeast(num_callbacks)) 449 .WillRepeatedly( 450 DoAll(CheckCountAndPostQuitTask(&count, num_callbacks, loop()), 451 Invoke(RealOnMoreData))); 452 EXPECT_CALL(source, OnError(stream)).Times(0); 453 EXPECT_CALL(source, OnMoreIOData(_, _, _)).Times(0); 454 455 EXPECT_TRUE(stream->Open()); 456 stream->Start(&source); 457 start_time_ = base::TimeTicks::Now(); 458 loop()->Run(); 459 end_time_ = base::TimeTicks::Now(); 460 stream->Stop(); 461 stream->Close(); 462 463 double average_time_between_callbacks_ms = 464 AverageTimeBetweenCallbacks(num_callbacks); 465 VLOG(0) << "expected time between callbacks: " 466 << expected_time_between_callbacks_ms << " ms"; 467 VLOG(0) << "average time between callbacks: " 468 << average_time_between_callbacks_ms << " ms"; 469 EXPECT_GE(average_time_between_callbacks_ms, 470 0.70 * expected_time_between_callbacks_ms); 471 EXPECT_LE(average_time_between_callbacks_ms, 472 1.30 * expected_time_between_callbacks_ms); 473 } 474 475 scoped_ptr<base::MessageLoopForUI> loop_; 476 scoped_ptr<AudioManager> audio_manager_; 477 base::TimeTicks start_time_; 478 base::TimeTicks end_time_; 479 480 private: 481 DISALLOW_COPY_AND_ASSIGN(AudioAndroidOutputTest); 482}; 483 484// AudioRecordInputStream should only be created on Jelly Bean and higher. This 485// ensures we only test against the AudioRecord path when that is satisfied. 486std::vector<bool> RunAudioRecordInputPathTests() { 487 std::vector<bool> tests; 488 tests.push_back(false); 489 if (base::android::BuildInfo::GetInstance()->sdk_int() >= 16) 490 tests.push_back(true); 491 return tests; 492} 493 494// Test fixture class for tests which exercise the input path, or both input and 495// output paths. It is value-parameterized to test against both the Java 496// AudioRecord (when true) and native OpenSLES (when false) input paths. 497class AudioAndroidInputTest : public AudioAndroidOutputTest, 498 public testing::WithParamInterface<bool> { 499 public: 500 AudioAndroidInputTest() {} 501 502 protected: 503 AudioParameters GetInputStreamParameters() { 504 AudioParameters input_params = audio_manager()->GetInputStreamParameters( 505 AudioManagerBase::kDefaultDeviceId); 506 // Override the platform effects setting to use the AudioRecord or OpenSLES 507 // path as requested. 508 int effects = GetParam() ? AudioParameters::ECHO_CANCELLER : 509 AudioParameters::NO_EFFECTS; 510 AudioParameters params(input_params.format(), 511 input_params.channel_layout(), 512 input_params.input_channels(), 513 input_params.sample_rate(), 514 input_params.bits_per_sample(), 515 input_params.frames_per_buffer(), 516 effects); 517 return params; 518 } 519 520 void StartInputStreamCallbacks(const AudioParameters& params) { 521 double expected_time_between_callbacks_ms = 522 ExpectedTimeBetweenCallbacks(params); 523 const int num_callbacks = 524 (kCallbackTestTimeMs / expected_time_between_callbacks_ms); 525 AudioInputStream* stream = audio_manager()->MakeAudioInputStream( 526 params, AudioManagerBase::kDefaultDeviceId); 527 EXPECT_TRUE(stream); 528 529 int count = 0; 530 MockAudioInputCallback sink; 531 532 EXPECT_CALL(sink, 533 OnData(stream, NotNull(), params.GetBytesPerBuffer(), _, _)) 534 .Times(AtLeast(num_callbacks)) 535 .WillRepeatedly( 536 CheckCountAndPostQuitTask(&count, num_callbacks, loop())); 537 EXPECT_CALL(sink, OnError(stream)).Times(0); 538 539 EXPECT_TRUE(stream->Open()); 540 stream->Start(&sink); 541 start_time_ = base::TimeTicks::Now(); 542 loop()->Run(); 543 end_time_ = base::TimeTicks::Now(); 544 stream->Stop(); 545 stream->Close(); 546 547 double average_time_between_callbacks_ms = 548 AverageTimeBetweenCallbacks(num_callbacks); 549 VLOG(0) << "expected time between callbacks: " 550 << expected_time_between_callbacks_ms << " ms"; 551 VLOG(0) << "average time between callbacks: " 552 << average_time_between_callbacks_ms << " ms"; 553 EXPECT_GE(average_time_between_callbacks_ms, 554 0.70 * expected_time_between_callbacks_ms); 555 EXPECT_LE(average_time_between_callbacks_ms, 556 1.30 * expected_time_between_callbacks_ms); 557 } 558 559 560 private: 561 DISALLOW_COPY_AND_ASSIGN(AudioAndroidInputTest); 562}; 563 564// Get the default audio input parameters and log the result. 565TEST_P(AudioAndroidInputTest, GetDefaultInputStreamParameters) { 566 // We don't go through AudioAndroidInputTest::GetInputStreamParameters() here 567 // so that we can log the real (non-overridden) values of the effects. 568 AudioParameters params = audio_manager()->GetInputStreamParameters( 569 AudioManagerBase::kDefaultDeviceId); 570 EXPECT_TRUE(params.IsValid()); 571 VLOG(1) << params; 572} 573 574// Get the default audio output parameters and log the result. 575TEST_F(AudioAndroidOutputTest, GetDefaultOutputStreamParameters) { 576 AudioParameters params = GetDefaultOutputStreamParameters(); 577 EXPECT_TRUE(params.IsValid()); 578 VLOG(1) << params; 579} 580 581// Check if low-latency output is supported and log the result as output. 582TEST_F(AudioAndroidOutputTest, IsAudioLowLatencySupported) { 583 AudioManagerAndroid* manager = 584 static_cast<AudioManagerAndroid*>(audio_manager()); 585 bool low_latency = manager->IsAudioLowLatencySupported(); 586 low_latency ? VLOG(0) << "Low latency output is supported" 587 : VLOG(0) << "Low latency output is *not* supported"; 588} 589 590// Verify input device enumeration. 591TEST_F(AudioAndroidInputTest, GetAudioInputDeviceNames) { 592 if (!audio_manager()->HasAudioInputDevices()) 593 return; 594 AudioDeviceNames devices; 595 audio_manager()->GetAudioInputDeviceNames(&devices); 596 CheckDeviceNames(devices); 597} 598 599// Verify output device enumeration. 600TEST_F(AudioAndroidOutputTest, GetAudioOutputDeviceNames) { 601 if (!audio_manager()->HasAudioOutputDevices()) 602 return; 603 AudioDeviceNames devices; 604 audio_manager()->GetAudioOutputDeviceNames(&devices); 605 CheckDeviceNames(devices); 606} 607 608// Ensure that a default input stream can be created and closed. 609TEST_P(AudioAndroidInputTest, CreateAndCloseInputStream) { 610 AudioParameters params = GetInputStreamParameters(); 611 AudioInputStream* ais = audio_manager()->MakeAudioInputStream( 612 params, AudioManagerBase::kDefaultDeviceId); 613 EXPECT_TRUE(ais); 614 ais->Close(); 615} 616 617// Ensure that a default output stream can be created and closed. 618// TODO(henrika): should we also verify that this API changes the audio mode 619// to communication mode, and calls RegisterHeadsetReceiver, the first time 620// it is called? 621TEST_F(AudioAndroidOutputTest, CreateAndCloseOutputStream) { 622 AudioParameters params = GetDefaultOutputStreamParameters(); 623 AudioOutputStream* aos = audio_manager()->MakeAudioOutputStream( 624 params, std::string()); 625 EXPECT_TRUE(aos); 626 aos->Close(); 627} 628 629// Ensure that a default input stream can be opened and closed. 630TEST_P(AudioAndroidInputTest, OpenAndCloseInputStream) { 631 AudioParameters params = GetInputStreamParameters(); 632 AudioInputStream* ais = audio_manager()->MakeAudioInputStream( 633 params, AudioManagerBase::kDefaultDeviceId); 634 EXPECT_TRUE(ais); 635 EXPECT_TRUE(ais->Open()); 636 ais->Close(); 637} 638 639// Ensure that a default output stream can be opened and closed. 640TEST_F(AudioAndroidOutputTest, OpenAndCloseOutputStream) { 641 AudioParameters params = GetDefaultOutputStreamParameters(); 642 AudioOutputStream* aos = audio_manager()->MakeAudioOutputStream( 643 params, std::string()); 644 EXPECT_TRUE(aos); 645 EXPECT_TRUE(aos->Open()); 646 aos->Close(); 647} 648 649// Start input streaming using default input parameters and ensure that the 650// callback sequence is sane. 651// Disabled per crbug/337867 652TEST_P(AudioAndroidInputTest, DISABLED_StartInputStreamCallbacks) { 653 AudioParameters params = GetInputStreamParameters(); 654 StartInputStreamCallbacks(params); 655} 656 657// Start input streaming using non default input parameters and ensure that the 658// callback sequence is sane. The only change we make in this test is to select 659// a 10ms buffer size instead of the default size. 660// TODO(henrika): possibly add support for more variations. 661// Disabled per crbug/337867 662TEST_P(AudioAndroidInputTest, DISABLED_StartInputStreamCallbacksNonDefaultParameters) { 663 AudioParameters native_params = GetInputStreamParameters(); 664 AudioParameters params(native_params.format(), 665 native_params.channel_layout(), 666 native_params.input_channels(), 667 native_params.sample_rate(), 668 native_params.bits_per_sample(), 669 native_params.sample_rate() / 100, 670 native_params.effects()); 671 StartInputStreamCallbacks(params); 672} 673 674// Start output streaming using default output parameters and ensure that the 675// callback sequence is sane. 676TEST_F(AudioAndroidOutputTest, StartOutputStreamCallbacks) { 677 AudioParameters params = GetDefaultOutputStreamParameters(); 678 StartOutputStreamCallbacks(params); 679} 680 681// Start output streaming using non default output parameters and ensure that 682// the callback sequence is sane. The only change we make in this test is to 683// select a 10ms buffer size instead of the default size and to open up the 684// device in mono. 685// TODO(henrika): possibly add support for more variations. 686TEST_F(AudioAndroidOutputTest, StartOutputStreamCallbacksNonDefaultParameters) { 687 AudioParameters native_params = GetDefaultOutputStreamParameters(); 688 AudioParameters params(native_params.format(), 689 CHANNEL_LAYOUT_MONO, 690 native_params.sample_rate(), 691 native_params.bits_per_sample(), 692 native_params.sample_rate() / 100); 693 StartOutputStreamCallbacks(params); 694} 695 696// Play out a PCM file segment in real time and allow the user to verify that 697// the rendered audio sounds OK. 698// NOTE: this test requires user interaction and is not designed to run as an 699// automatized test on bots. 700TEST_F(AudioAndroidOutputTest, DISABLED_RunOutputStreamWithFileAsSource) { 701 AudioParameters params = GetDefaultOutputStreamParameters(); 702 VLOG(1) << params; 703 AudioOutputStream* aos = audio_manager()->MakeAudioOutputStream( 704 params, std::string()); 705 EXPECT_TRUE(aos); 706 707 std::string file_name; 708 if (params.sample_rate() == 48000 && params.channels() == 2) { 709 file_name = kSpeechFile_16b_s_48k; 710 } else if (params.sample_rate() == 48000 && params.channels() == 1) { 711 file_name = kSpeechFile_16b_m_48k; 712 } else if (params.sample_rate() == 44100 && params.channels() == 2) { 713 file_name = kSpeechFile_16b_s_44k; 714 } else if (params.sample_rate() == 44100 && params.channels() == 1) { 715 file_name = kSpeechFile_16b_m_44k; 716 } else { 717 FAIL() << "This test supports 44.1kHz and 48kHz mono/stereo only."; 718 return; 719 } 720 721 base::WaitableEvent event(false, false); 722 FileAudioSource source(&event, file_name); 723 724 EXPECT_TRUE(aos->Open()); 725 aos->SetVolume(1.0); 726 aos->Start(&source); 727 VLOG(0) << ">> Verify that the file is played out correctly..."; 728 EXPECT_TRUE(event.TimedWait(TestTimeouts::action_max_timeout())); 729 aos->Stop(); 730 aos->Close(); 731} 732 733// Start input streaming and run it for ten seconds while recording to a 734// local audio file. 735// NOTE: this test requires user interaction and is not designed to run as an 736// automatized test on bots. 737TEST_P(AudioAndroidInputTest, DISABLED_RunSimplexInputStreamWithFileAsSink) { 738 AudioParameters params = GetInputStreamParameters(); 739 VLOG(1) << params; 740 AudioInputStream* ais = audio_manager()->MakeAudioInputStream( 741 params, AudioManagerBase::kDefaultDeviceId); 742 EXPECT_TRUE(ais); 743 744 std::string file_name = base::StringPrintf("out_simplex_%d_%d_%d.pcm", 745 params.sample_rate(), 746 params.frames_per_buffer(), 747 params.channels()); 748 749 base::WaitableEvent event(false, false); 750 FileAudioSink sink(&event, params, file_name); 751 752 EXPECT_TRUE(ais->Open()); 753 ais->Start(&sink); 754 VLOG(0) << ">> Speak into the microphone to record audio..."; 755 EXPECT_TRUE(event.TimedWait(TestTimeouts::action_max_timeout())); 756 ais->Stop(); 757 ais->Close(); 758} 759 760// Same test as RunSimplexInputStreamWithFileAsSink but this time output 761// streaming is active as well (reads zeros only). 762// NOTE: this test requires user interaction and is not designed to run as an 763// automatized test on bots. 764TEST_P(AudioAndroidInputTest, DISABLED_RunDuplexInputStreamWithFileAsSink) { 765 AudioParameters in_params = GetInputStreamParameters(); 766 AudioInputStream* ais = audio_manager()->MakeAudioInputStream( 767 in_params, AudioManagerBase::kDefaultDeviceId); 768 EXPECT_TRUE(ais); 769 770 AudioParameters out_params = 771 audio_manager()->GetDefaultOutputStreamParameters(); 772 AudioOutputStream* aos = audio_manager()->MakeAudioOutputStream( 773 out_params, std::string()); 774 EXPECT_TRUE(aos); 775 776 std::string file_name = base::StringPrintf("out_duplex_%d_%d_%d.pcm", 777 in_params.sample_rate(), 778 in_params.frames_per_buffer(), 779 in_params.channels()); 780 781 base::WaitableEvent event(false, false); 782 FileAudioSink sink(&event, in_params, file_name); 783 MockAudioSourceCallback source; 784 785 EXPECT_CALL(source, OnMoreData(NotNull(), _)) 786 .WillRepeatedly(Invoke(RealOnMoreData)); 787 EXPECT_CALL(source, OnError(aos)).Times(0); 788 EXPECT_CALL(source, OnMoreIOData(_, _, _)).Times(0); 789 790 EXPECT_TRUE(ais->Open()); 791 EXPECT_TRUE(aos->Open()); 792 ais->Start(&sink); 793 aos->Start(&source); 794 VLOG(0) << ">> Speak into the microphone to record audio"; 795 EXPECT_TRUE(event.TimedWait(TestTimeouts::action_max_timeout())); 796 aos->Stop(); 797 ais->Stop(); 798 aos->Close(); 799 ais->Close(); 800} 801 802// Start audio in both directions while feeding captured data into a FIFO so 803// it can be read directly (in loopback) by the render side. A small extra 804// delay will be added by the FIFO and an estimate of this delay will be 805// printed out during the test. 806// NOTE: this test requires user interaction and is not designed to run as an 807// automatized test on bots. 808TEST_P(AudioAndroidInputTest, 809 DISABLED_RunSymmetricInputAndOutputStreamsInFullDuplex) { 810 // Get native audio parameters for the input side. 811 AudioParameters default_input_params = GetInputStreamParameters(); 812 813 // Modify the parameters so that both input and output can use the same 814 // parameters by selecting 10ms as buffer size. This will also ensure that 815 // the output stream will be a mono stream since mono is default for input 816 // audio on Android. 817 AudioParameters io_params(default_input_params.format(), 818 default_input_params.channel_layout(), 819 ChannelLayoutToChannelCount( 820 default_input_params.channel_layout()), 821 default_input_params.sample_rate(), 822 default_input_params.bits_per_sample(), 823 default_input_params.sample_rate() / 100, 824 default_input_params.effects()); 825 VLOG(1) << io_params; 826 827 // Create input and output streams using the common audio parameters. 828 AudioInputStream* ais = audio_manager()->MakeAudioInputStream( 829 io_params, AudioManagerBase::kDefaultDeviceId); 830 EXPECT_TRUE(ais); 831 AudioOutputStream* aos = audio_manager()->MakeAudioOutputStream( 832 io_params, std::string()); 833 EXPECT_TRUE(aos); 834 835 FullDuplexAudioSinkSource full_duplex(io_params); 836 837 // Start a full duplex audio session and print out estimates of the extra 838 // delay we should expect from the FIFO. If real-time delay measurements are 839 // performed, the result should be reduced by this extra delay since it is 840 // something that has been added by the test. 841 EXPECT_TRUE(ais->Open()); 842 EXPECT_TRUE(aos->Open()); 843 ais->Start(&full_duplex); 844 aos->Start(&full_duplex); 845 VLOG(1) << "HINT: an estimate of the extra FIFO delay will be updated " 846 << "once per second during this test."; 847 VLOG(0) << ">> Speak into the mic and listen to the audio in loopback..."; 848 fflush(stdout); 849 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20)); 850 printf("\n"); 851 aos->Stop(); 852 ais->Stop(); 853 aos->Close(); 854 ais->Close(); 855} 856 857INSTANTIATE_TEST_CASE_P(AudioAndroidInputTest, AudioAndroidInputTest, 858 testing::ValuesIn(RunAudioRecordInputPathTests())); 859 860} // namespace media 861