1 /*
2 * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include "modules/audio_device/include/audio_device.h"
12
13 #include <algorithm>
14 #include <limits>
15 #include <list>
16 #include <memory>
17 #include <numeric>
18 #include <string>
19 #include <vector>
20
21 #include "api/scoped_refptr.h"
22 #include "api/task_queue/default_task_queue_factory.h"
23 #include "api/task_queue/task_queue_factory.h"
24 #include "modules/audio_device/android/audio_common.h"
25 #include "modules/audio_device/android/audio_manager.h"
26 #include "modules/audio_device/android/build_info.h"
27 #include "modules/audio_device/android/ensure_initialized.h"
28 #include "modules/audio_device/audio_device_impl.h"
29 #include "modules/audio_device/include/mock_audio_transport.h"
30 #include "rtc_base/arraysize.h"
31 #include "rtc_base/event.h"
32 #include "rtc_base/format_macros.h"
33 #include "rtc_base/synchronization/mutex.h"
34 #include "rtc_base/time_utils.h"
35 #include "test/gmock.h"
36 #include "test/gtest.h"
37 #include "test/testsupport/file_utils.h"
38
39 using std::cout;
40 using std::endl;
41 using ::testing::_;
42 using ::testing::AtLeast;
43 using ::testing::Gt;
44 using ::testing::Invoke;
45 using ::testing::NiceMock;
46 using ::testing::NotNull;
47 using ::testing::Return;
48
49 // #define ENABLE_DEBUG_PRINTF
50 #ifdef ENABLE_DEBUG_PRINTF
51 #define PRINTD(...) fprintf(stderr, __VA_ARGS__);
52 #else
53 #define PRINTD(...) ((void)0)
54 #endif
55 #define PRINT(...) fprintf(stderr, __VA_ARGS__);
56
57 namespace webrtc {
58
59 // Number of callbacks (input or output) the tests waits for before we set
60 // an event indicating that the test was OK.
61 static const size_t kNumCallbacks = 10;
62 // Max amount of time we wait for an event to be set while counting callbacks.
63 static const int kTestTimeOutInMilliseconds = 10 * 1000;
64 // Average number of audio callbacks per second assuming 10ms packet size.
65 static const size_t kNumCallbacksPerSecond = 100;
66 // Play out a test file during this time (unit is in seconds).
67 static const int kFilePlayTimeInSec = 5;
68 static const size_t kBitsPerSample = 16;
69 static const size_t kBytesPerSample = kBitsPerSample / 8;
70 // Run the full-duplex test during this time (unit is in seconds).
71 // Note that first |kNumIgnoreFirstCallbacks| are ignored.
72 static const int kFullDuplexTimeInSec = 5;
73 // Wait for the callback sequence to stabilize by ignoring this amount of the
74 // initial callbacks (avoids initial FIFO access).
75 // Only used in the RunPlayoutAndRecordingInFullDuplex test.
76 static const size_t kNumIgnoreFirstCallbacks = 50;
77 // Sets the number of impulses per second in the latency test.
78 static const int kImpulseFrequencyInHz = 1;
79 // Length of round-trip latency measurements. Number of transmitted impulses
80 // is kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 1.
81 static const int kMeasureLatencyTimeInSec = 11;
82 // Utilized in round-trip latency measurements to avoid capturing noise samples.
83 static const int kImpulseThreshold = 1000;
84 static const char kTag[] = "[..........] ";
85
86 enum TransportType {
87 kPlayout = 0x1,
88 kRecording = 0x2,
89 };
90
91 // Interface for processing the audio stream. Real implementations can e.g.
92 // run audio in loopback, read audio from a file or perform latency
93 // measurements.
94 class AudioStreamInterface {
95 public:
96 virtual void Write(const void* source, size_t num_frames) = 0;
97 virtual void Read(void* destination, size_t num_frames) = 0;
98
99 protected:
~AudioStreamInterface()100 virtual ~AudioStreamInterface() {}
101 };
102
103 // Reads audio samples from a PCM file where the file is stored in memory at
104 // construction.
105 class FileAudioStream : public AudioStreamInterface {
106 public:
FileAudioStream(size_t num_callbacks,const std::string & file_name,int sample_rate)107 FileAudioStream(size_t num_callbacks,
108 const std::string& file_name,
109 int sample_rate)
110 : file_size_in_bytes_(0), sample_rate_(sample_rate), file_pos_(0) {
111 file_size_in_bytes_ = test::GetFileSize(file_name);
112 sample_rate_ = sample_rate;
113 EXPECT_GE(file_size_in_callbacks(), num_callbacks)
114 << "Size of test file is not large enough to last during the test.";
115 const size_t num_16bit_samples =
116 test::GetFileSize(file_name) / kBytesPerSample;
117 file_.reset(new int16_t[num_16bit_samples]);
118 FILE* audio_file = fopen(file_name.c_str(), "rb");
119 EXPECT_NE(audio_file, nullptr);
120 size_t num_samples_read =
121 fread(file_.get(), sizeof(int16_t), num_16bit_samples, audio_file);
122 EXPECT_EQ(num_samples_read, num_16bit_samples);
123 fclose(audio_file);
124 }
125
126 // AudioStreamInterface::Write() is not implemented.
Write(const void * source,size_t num_frames)127 void Write(const void* source, size_t num_frames) override {}
128
129 // Read samples from file stored in memory (at construction) and copy
130 // |num_frames| (<=> 10ms) to the |destination| byte buffer.
Read(void * destination,size_t num_frames)131 void Read(void* destination, size_t num_frames) override {
132 memcpy(destination, static_cast<int16_t*>(&file_[file_pos_]),
133 num_frames * sizeof(int16_t));
134 file_pos_ += num_frames;
135 }
136
file_size_in_seconds() const137 int file_size_in_seconds() const {
138 return static_cast<int>(file_size_in_bytes_ /
139 (kBytesPerSample * sample_rate_));
140 }
file_size_in_callbacks() const141 size_t file_size_in_callbacks() const {
142 return file_size_in_seconds() * kNumCallbacksPerSecond;
143 }
144
145 private:
146 size_t file_size_in_bytes_;
147 int sample_rate_;
148 std::unique_ptr<int16_t[]> file_;
149 size_t file_pos_;
150 };
151
152 // Simple first in first out (FIFO) class that wraps a list of 16-bit audio
153 // buffers of fixed size and allows Write and Read operations. The idea is to
154 // store recorded audio buffers (using Write) and then read (using Read) these
155 // stored buffers with as short delay as possible when the audio layer needs
156 // data to play out. The number of buffers in the FIFO will stabilize under
157 // normal conditions since there will be a balance between Write and Read calls.
158 // The container is a std::list container and access is protected with a lock
159 // since both sides (playout and recording) are driven by its own thread.
160 class FifoAudioStream : public AudioStreamInterface {
161 public:
FifoAudioStream(size_t frames_per_buffer)162 explicit FifoAudioStream(size_t frames_per_buffer)
163 : frames_per_buffer_(frames_per_buffer),
164 bytes_per_buffer_(frames_per_buffer_ * sizeof(int16_t)),
165 fifo_(new AudioBufferList),
166 largest_size_(0),
167 total_written_elements_(0),
168 write_count_(0) {
169 EXPECT_NE(fifo_.get(), nullptr);
170 }
171
~FifoAudioStream()172 ~FifoAudioStream() { Flush(); }
173
174 // Allocate new memory, copy |num_frames| samples from |source| into memory
175 // and add pointer to the memory location to end of the list.
176 // Increases the size of the FIFO by one element.
Write(const void * source,size_t num_frames)177 void Write(const void* source, size_t num_frames) override {
178 ASSERT_EQ(num_frames, frames_per_buffer_);
179 PRINTD("+");
180 if (write_count_++ < kNumIgnoreFirstCallbacks) {
181 return;
182 }
183 int16_t* memory = new int16_t[frames_per_buffer_];
184 memcpy(static_cast<int16_t*>(&memory[0]), source, bytes_per_buffer_);
185 MutexLock lock(&lock_);
186 fifo_->push_back(memory);
187 const size_t size = fifo_->size();
188 if (size > largest_size_) {
189 largest_size_ = size;
190 PRINTD("(%" RTC_PRIuS ")", largest_size_);
191 }
192 total_written_elements_ += size;
193 }
194
195 // Read pointer to data buffer from front of list, copy |num_frames| of stored
196 // data into |destination| and delete the utilized memory allocation.
197 // Decreases the size of the FIFO by one element.
Read(void * destination,size_t num_frames)198 void Read(void* destination, size_t num_frames) override {
199 ASSERT_EQ(num_frames, frames_per_buffer_);
200 PRINTD("-");
201 MutexLock lock(&lock_);
202 if (fifo_->empty()) {
203 memset(destination, 0, bytes_per_buffer_);
204 } else {
205 int16_t* memory = fifo_->front();
206 fifo_->pop_front();
207 memcpy(destination, static_cast<int16_t*>(&memory[0]), bytes_per_buffer_);
208 delete memory;
209 }
210 }
211
size() const212 size_t size() const { return fifo_->size(); }
213
largest_size() const214 size_t largest_size() const { return largest_size_; }
215
average_size() const216 size_t average_size() const {
217 return (total_written_elements_ == 0)
218 ? 0.0
219 : 0.5 + static_cast<float>(total_written_elements_) /
220 (write_count_ - kNumIgnoreFirstCallbacks);
221 }
222
223 private:
Flush()224 void Flush() {
225 for (auto it = fifo_->begin(); it != fifo_->end(); ++it) {
226 delete *it;
227 }
228 fifo_->clear();
229 }
230
231 using AudioBufferList = std::list<int16_t*>;
232 Mutex lock_;
233 const size_t frames_per_buffer_;
234 const size_t bytes_per_buffer_;
235 std::unique_ptr<AudioBufferList> fifo_;
236 size_t largest_size_;
237 size_t total_written_elements_;
238 size_t write_count_;
239 };
240
241 // Inserts periodic impulses and measures the latency between the time of
242 // transmission and time of receiving the same impulse.
243 // Usage requires a special hardware called Audio Loopback Dongle.
244 // See http://source.android.com/devices/audio/loopback.html for details.
245 class LatencyMeasuringAudioStream : public AudioStreamInterface {
246 public:
LatencyMeasuringAudioStream(size_t frames_per_buffer)247 explicit LatencyMeasuringAudioStream(size_t frames_per_buffer)
248 : frames_per_buffer_(frames_per_buffer),
249 bytes_per_buffer_(frames_per_buffer_ * sizeof(int16_t)),
250 play_count_(0),
251 rec_count_(0),
252 pulse_time_(0) {}
253
254 // Insert periodic impulses in first two samples of |destination|.
Read(void * destination,size_t num_frames)255 void Read(void* destination, size_t num_frames) override {
256 ASSERT_EQ(num_frames, frames_per_buffer_);
257 if (play_count_ == 0) {
258 PRINT("[");
259 }
260 play_count_++;
261 memset(destination, 0, bytes_per_buffer_);
262 if (play_count_ % (kNumCallbacksPerSecond / kImpulseFrequencyInHz) == 0) {
263 if (pulse_time_ == 0) {
264 pulse_time_ = rtc::TimeMillis();
265 }
266 PRINT(".");
267 const int16_t impulse = std::numeric_limits<int16_t>::max();
268 int16_t* ptr16 = static_cast<int16_t*>(destination);
269 for (size_t i = 0; i < 2; ++i) {
270 ptr16[i] = impulse;
271 }
272 }
273 }
274
275 // Detect received impulses in |source|, derive time between transmission and
276 // detection and add the calculated delay to list of latencies.
Write(const void * source,size_t num_frames)277 void Write(const void* source, size_t num_frames) override {
278 ASSERT_EQ(num_frames, frames_per_buffer_);
279 rec_count_++;
280 if (pulse_time_ == 0) {
281 // Avoid detection of new impulse response until a new impulse has
282 // been transmitted (sets |pulse_time_| to value larger than zero).
283 return;
284 }
285 const int16_t* ptr16 = static_cast<const int16_t*>(source);
286 std::vector<int16_t> vec(ptr16, ptr16 + num_frames);
287 // Find max value in the audio buffer.
288 int max = *std::max_element(vec.begin(), vec.end());
289 // Find index (element position in vector) of the max element.
290 int index_of_max =
291 std::distance(vec.begin(), std::find(vec.begin(), vec.end(), max));
292 if (max > kImpulseThreshold) {
293 PRINTD("(%d,%d)", max, index_of_max);
294 int64_t now_time = rtc::TimeMillis();
295 int extra_delay = IndexToMilliseconds(static_cast<double>(index_of_max));
296 PRINTD("[%d]", static_cast<int>(now_time - pulse_time_));
297 PRINTD("[%d]", extra_delay);
298 // Total latency is the difference between transmit time and detection
299 // tome plus the extra delay within the buffer in which we detected the
300 // received impulse. It is transmitted at sample 0 but can be received
301 // at sample N where N > 0. The term |extra_delay| accounts for N and it
302 // is a value between 0 and 10ms.
303 latencies_.push_back(now_time - pulse_time_ + extra_delay);
304 pulse_time_ = 0;
305 } else {
306 PRINTD("-");
307 }
308 }
309
num_latency_values() const310 size_t num_latency_values() const { return latencies_.size(); }
311
min_latency() const312 int min_latency() const {
313 if (latencies_.empty())
314 return 0;
315 return *std::min_element(latencies_.begin(), latencies_.end());
316 }
317
max_latency() const318 int max_latency() const {
319 if (latencies_.empty())
320 return 0;
321 return *std::max_element(latencies_.begin(), latencies_.end());
322 }
323
average_latency() const324 int average_latency() const {
325 if (latencies_.empty())
326 return 0;
327 return 0.5 + static_cast<double>(
328 std::accumulate(latencies_.begin(), latencies_.end(), 0)) /
329 latencies_.size();
330 }
331
PrintResults() const332 void PrintResults() const {
333 PRINT("] ");
334 for (auto it = latencies_.begin(); it != latencies_.end(); ++it) {
335 PRINT("%d ", *it);
336 }
337 PRINT("\n");
338 PRINT("%s[min, max, avg]=[%d, %d, %d] ms\n", kTag, min_latency(),
339 max_latency(), average_latency());
340 }
341
IndexToMilliseconds(double index) const342 int IndexToMilliseconds(double index) const {
343 return static_cast<int>(10.0 * (index / frames_per_buffer_) + 0.5);
344 }
345
346 private:
347 const size_t frames_per_buffer_;
348 const size_t bytes_per_buffer_;
349 size_t play_count_;
350 size_t rec_count_;
351 int64_t pulse_time_;
352 std::vector<int> latencies_;
353 };
354
355 // Mocks the AudioTransport object and proxies actions for the two callbacks
356 // (RecordedDataIsAvailable and NeedMorePlayData) to different implementations
357 // of AudioStreamInterface.
358 class MockAudioTransportAndroid : public test::MockAudioTransport {
359 public:
MockAudioTransportAndroid(int type)360 explicit MockAudioTransportAndroid(int type)
361 : num_callbacks_(0),
362 type_(type),
363 play_count_(0),
364 rec_count_(0),
365 audio_stream_(nullptr) {}
366
~MockAudioTransportAndroid()367 virtual ~MockAudioTransportAndroid() {}
368
369 // Set default actions of the mock object. We are delegating to fake
370 // implementations (of AudioStreamInterface) here.
HandleCallbacks(rtc::Event * test_is_done,AudioStreamInterface * audio_stream,int num_callbacks)371 void HandleCallbacks(rtc::Event* test_is_done,
372 AudioStreamInterface* audio_stream,
373 int num_callbacks) {
374 test_is_done_ = test_is_done;
375 audio_stream_ = audio_stream;
376 num_callbacks_ = num_callbacks;
377 if (play_mode()) {
378 ON_CALL(*this, NeedMorePlayData(_, _, _, _, _, _, _, _))
379 .WillByDefault(
380 Invoke(this, &MockAudioTransportAndroid::RealNeedMorePlayData));
381 }
382 if (rec_mode()) {
383 ON_CALL(*this, RecordedDataIsAvailable(_, _, _, _, _, _, _, _, _, _))
384 .WillByDefault(Invoke(
385 this, &MockAudioTransportAndroid::RealRecordedDataIsAvailable));
386 }
387 }
388
RealRecordedDataIsAvailable(const void * audioSamples,const size_t nSamples,const size_t nBytesPerSample,const size_t nChannels,const uint32_t samplesPerSec,const uint32_t totalDelayMS,const int32_t clockDrift,const uint32_t currentMicLevel,const bool keyPressed,uint32_t & newMicLevel)389 int32_t RealRecordedDataIsAvailable(const void* audioSamples,
390 const size_t nSamples,
391 const size_t nBytesPerSample,
392 const size_t nChannels,
393 const uint32_t samplesPerSec,
394 const uint32_t totalDelayMS,
395 const int32_t clockDrift,
396 const uint32_t currentMicLevel,
397 const bool keyPressed,
398 uint32_t& newMicLevel) { // NOLINT
399 EXPECT_TRUE(rec_mode()) << "No test is expecting these callbacks.";
400 rec_count_++;
401 // Process the recorded audio stream if an AudioStreamInterface
402 // implementation exists.
403 if (audio_stream_) {
404 audio_stream_->Write(audioSamples, nSamples);
405 }
406 if (ReceivedEnoughCallbacks()) {
407 test_is_done_->Set();
408 }
409 return 0;
410 }
411
RealNeedMorePlayData(const size_t nSamples,const size_t nBytesPerSample,const size_t nChannels,const uint32_t samplesPerSec,void * audioSamples,size_t & nSamplesOut,int64_t * elapsed_time_ms,int64_t * ntp_time_ms)412 int32_t RealNeedMorePlayData(const size_t nSamples,
413 const size_t nBytesPerSample,
414 const size_t nChannels,
415 const uint32_t samplesPerSec,
416 void* audioSamples,
417 size_t& nSamplesOut, // NOLINT
418 int64_t* elapsed_time_ms,
419 int64_t* ntp_time_ms) {
420 EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
421 play_count_++;
422 nSamplesOut = nSamples;
423 // Read (possibly processed) audio stream samples to be played out if an
424 // AudioStreamInterface implementation exists.
425 if (audio_stream_) {
426 audio_stream_->Read(audioSamples, nSamples);
427 }
428 if (ReceivedEnoughCallbacks()) {
429 test_is_done_->Set();
430 }
431 return 0;
432 }
433
ReceivedEnoughCallbacks()434 bool ReceivedEnoughCallbacks() {
435 bool recording_done = false;
436 if (rec_mode())
437 recording_done = rec_count_ >= num_callbacks_;
438 else
439 recording_done = true;
440
441 bool playout_done = false;
442 if (play_mode())
443 playout_done = play_count_ >= num_callbacks_;
444 else
445 playout_done = true;
446
447 return recording_done && playout_done;
448 }
449
play_mode() const450 bool play_mode() const { return type_ & kPlayout; }
rec_mode() const451 bool rec_mode() const { return type_ & kRecording; }
452
453 private:
454 rtc::Event* test_is_done_;
455 size_t num_callbacks_;
456 int type_;
457 size_t play_count_;
458 size_t rec_count_;
459 AudioStreamInterface* audio_stream_;
460 std::unique_ptr<LatencyMeasuringAudioStream> latency_audio_stream_;
461 };
462
463 // AudioDeviceTest test fixture.
464 class AudioDeviceTest : public ::testing::Test {
465 protected:
AudioDeviceTest()466 AudioDeviceTest() : task_queue_factory_(CreateDefaultTaskQueueFactory()) {
467 // One-time initialization of JVM and application context. Ensures that we
468 // can do calls between C++ and Java. Initializes both Java and OpenSL ES
469 // implementations.
470 webrtc::audiodevicemodule::EnsureInitialized();
471 // Creates an audio device using a default audio layer.
472 audio_device_ = CreateAudioDevice(AudioDeviceModule::kPlatformDefaultAudio);
473 EXPECT_NE(audio_device_.get(), nullptr);
474 EXPECT_EQ(0, audio_device_->Init());
475 playout_parameters_ = audio_manager()->GetPlayoutAudioParameters();
476 record_parameters_ = audio_manager()->GetRecordAudioParameters();
477 build_info_.reset(new BuildInfo());
478 }
~AudioDeviceTest()479 virtual ~AudioDeviceTest() { EXPECT_EQ(0, audio_device_->Terminate()); }
480
playout_sample_rate() const481 int playout_sample_rate() const { return playout_parameters_.sample_rate(); }
record_sample_rate() const482 int record_sample_rate() const { return record_parameters_.sample_rate(); }
playout_channels() const483 size_t playout_channels() const { return playout_parameters_.channels(); }
record_channels() const484 size_t record_channels() const { return record_parameters_.channels(); }
playout_frames_per_10ms_buffer() const485 size_t playout_frames_per_10ms_buffer() const {
486 return playout_parameters_.frames_per_10ms_buffer();
487 }
record_frames_per_10ms_buffer() const488 size_t record_frames_per_10ms_buffer() const {
489 return record_parameters_.frames_per_10ms_buffer();
490 }
491
total_delay_ms() const492 int total_delay_ms() const {
493 return audio_manager()->GetDelayEstimateInMilliseconds();
494 }
495
audio_device() const496 rtc::scoped_refptr<AudioDeviceModule> audio_device() const {
497 return audio_device_;
498 }
499
audio_device_impl() const500 AudioDeviceModuleImpl* audio_device_impl() const {
501 return static_cast<AudioDeviceModuleImpl*>(audio_device_.get());
502 }
503
audio_manager() const504 AudioManager* audio_manager() const {
505 return audio_device_impl()->GetAndroidAudioManagerForTest();
506 }
507
GetAudioManager(AudioDeviceModule * adm) const508 AudioManager* GetAudioManager(AudioDeviceModule* adm) const {
509 return static_cast<AudioDeviceModuleImpl*>(adm)
510 ->GetAndroidAudioManagerForTest();
511 }
512
audio_device_buffer() const513 AudioDeviceBuffer* audio_device_buffer() const {
514 return audio_device_impl()->GetAudioDeviceBuffer();
515 }
516
CreateAudioDevice(AudioDeviceModule::AudioLayer audio_layer)517 rtc::scoped_refptr<AudioDeviceModule> CreateAudioDevice(
518 AudioDeviceModule::AudioLayer audio_layer) {
519 rtc::scoped_refptr<AudioDeviceModule> module(
520 AudioDeviceModule::Create(audio_layer, task_queue_factory_.get()));
521 return module;
522 }
523
524 // Returns file name relative to the resource root given a sample rate.
GetFileName(int sample_rate)525 std::string GetFileName(int sample_rate) {
526 EXPECT_TRUE(sample_rate == 48000 || sample_rate == 44100);
527 char fname[64];
528 snprintf(fname, sizeof(fname), "audio_device/audio_short%d",
529 sample_rate / 1000);
530 std::string file_name(webrtc::test::ResourcePath(fname, "pcm"));
531 EXPECT_TRUE(test::FileExists(file_name));
532 #ifdef ENABLE_PRINTF
533 PRINT("file name: %s\n", file_name.c_str());
534 const size_t bytes = test::GetFileSize(file_name);
535 PRINT("file size: %" RTC_PRIuS " [bytes]\n", bytes);
536 PRINT("file size: %" RTC_PRIuS " [samples]\n", bytes / kBytesPerSample);
537 const int seconds =
538 static_cast<int>(bytes / (sample_rate * kBytesPerSample));
539 PRINT("file size: %d [secs]\n", seconds);
540 PRINT("file size: %" RTC_PRIuS " [callbacks]\n",
541 seconds * kNumCallbacksPerSecond);
542 #endif
543 return file_name;
544 }
545
GetActiveAudioLayer() const546 AudioDeviceModule::AudioLayer GetActiveAudioLayer() const {
547 AudioDeviceModule::AudioLayer audio_layer;
548 EXPECT_EQ(0, audio_device()->ActiveAudioLayer(&audio_layer));
549 return audio_layer;
550 }
551
TestDelayOnAudioLayer(const AudioDeviceModule::AudioLayer & layer_to_test)552 int TestDelayOnAudioLayer(
553 const AudioDeviceModule::AudioLayer& layer_to_test) {
554 rtc::scoped_refptr<AudioDeviceModule> audio_device;
555 audio_device = CreateAudioDevice(layer_to_test);
556 EXPECT_NE(audio_device.get(), nullptr);
557 AudioManager* audio_manager = GetAudioManager(audio_device.get());
558 EXPECT_NE(audio_manager, nullptr);
559 return audio_manager->GetDelayEstimateInMilliseconds();
560 }
561
TestActiveAudioLayer(const AudioDeviceModule::AudioLayer & layer_to_test)562 AudioDeviceModule::AudioLayer TestActiveAudioLayer(
563 const AudioDeviceModule::AudioLayer& layer_to_test) {
564 rtc::scoped_refptr<AudioDeviceModule> audio_device;
565 audio_device = CreateAudioDevice(layer_to_test);
566 EXPECT_NE(audio_device.get(), nullptr);
567 AudioDeviceModule::AudioLayer active;
568 EXPECT_EQ(0, audio_device->ActiveAudioLayer(&active));
569 return active;
570 }
571
DisableTestForThisDevice(const std::string & model)572 bool DisableTestForThisDevice(const std::string& model) {
573 return (build_info_->GetDeviceModel() == model);
574 }
575
576 // Volume control is currently only supported for the Java output audio layer.
577 // For OpenSL ES, the internal stream volume is always on max level and there
578 // is no need for this test to set it to max.
AudioLayerSupportsVolumeControl() const579 bool AudioLayerSupportsVolumeControl() const {
580 return GetActiveAudioLayer() == AudioDeviceModule::kAndroidJavaAudio;
581 }
582
SetMaxPlayoutVolume()583 void SetMaxPlayoutVolume() {
584 if (!AudioLayerSupportsVolumeControl())
585 return;
586 uint32_t max_volume;
587 EXPECT_EQ(0, audio_device()->MaxSpeakerVolume(&max_volume));
588 EXPECT_EQ(0, audio_device()->SetSpeakerVolume(max_volume));
589 }
590
DisableBuiltInAECIfAvailable()591 void DisableBuiltInAECIfAvailable() {
592 if (audio_device()->BuiltInAECIsAvailable()) {
593 EXPECT_EQ(0, audio_device()->EnableBuiltInAEC(false));
594 }
595 }
596
StartPlayout()597 void StartPlayout() {
598 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
599 EXPECT_FALSE(audio_device()->Playing());
600 EXPECT_EQ(0, audio_device()->InitPlayout());
601 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
602 EXPECT_EQ(0, audio_device()->StartPlayout());
603 EXPECT_TRUE(audio_device()->Playing());
604 }
605
StopPlayout()606 void StopPlayout() {
607 EXPECT_EQ(0, audio_device()->StopPlayout());
608 EXPECT_FALSE(audio_device()->Playing());
609 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
610 }
611
StartRecording()612 void StartRecording() {
613 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
614 EXPECT_FALSE(audio_device()->Recording());
615 EXPECT_EQ(0, audio_device()->InitRecording());
616 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
617 EXPECT_EQ(0, audio_device()->StartRecording());
618 EXPECT_TRUE(audio_device()->Recording());
619 }
620
StopRecording()621 void StopRecording() {
622 EXPECT_EQ(0, audio_device()->StopRecording());
623 EXPECT_FALSE(audio_device()->Recording());
624 }
625
GetMaxSpeakerVolume() const626 int GetMaxSpeakerVolume() const {
627 uint32_t max_volume(0);
628 EXPECT_EQ(0, audio_device()->MaxSpeakerVolume(&max_volume));
629 return max_volume;
630 }
631
GetMinSpeakerVolume() const632 int GetMinSpeakerVolume() const {
633 uint32_t min_volume(0);
634 EXPECT_EQ(0, audio_device()->MinSpeakerVolume(&min_volume));
635 return min_volume;
636 }
637
GetSpeakerVolume() const638 int GetSpeakerVolume() const {
639 uint32_t volume(0);
640 EXPECT_EQ(0, audio_device()->SpeakerVolume(&volume));
641 return volume;
642 }
643
644 rtc::Event test_is_done_;
645 std::unique_ptr<TaskQueueFactory> task_queue_factory_;
646 rtc::scoped_refptr<AudioDeviceModule> audio_device_;
647 AudioParameters playout_parameters_;
648 AudioParameters record_parameters_;
649 std::unique_ptr<BuildInfo> build_info_;
650 };
651
TEST_F(AudioDeviceTest,ConstructDestruct)652 TEST_F(AudioDeviceTest, ConstructDestruct) {
653 // Using the test fixture to create and destruct the audio device module.
654 }
655
656 // We always ask for a default audio layer when the ADM is constructed. But the
657 // ADM will then internally set the best suitable combination of audio layers,
658 // for input and output based on if low-latency output and/or input audio in
659 // combination with OpenSL ES is supported or not. This test ensures that the
660 // correct selection is done.
TEST_F(AudioDeviceTest,VerifyDefaultAudioLayer)661 TEST_F(AudioDeviceTest, VerifyDefaultAudioLayer) {
662 const AudioDeviceModule::AudioLayer audio_layer = GetActiveAudioLayer();
663 bool low_latency_output = audio_manager()->IsLowLatencyPlayoutSupported();
664 bool low_latency_input = audio_manager()->IsLowLatencyRecordSupported();
665 bool aaudio = audio_manager()->IsAAudioSupported();
666 AudioDeviceModule::AudioLayer expected_audio_layer;
667 if (aaudio) {
668 expected_audio_layer = AudioDeviceModule::kAndroidAAudioAudio;
669 } else if (low_latency_output && low_latency_input) {
670 expected_audio_layer = AudioDeviceModule::kAndroidOpenSLESAudio;
671 } else if (low_latency_output && !low_latency_input) {
672 expected_audio_layer =
673 AudioDeviceModule::kAndroidJavaInputAndOpenSLESOutputAudio;
674 } else {
675 expected_audio_layer = AudioDeviceModule::kAndroidJavaAudio;
676 }
677 EXPECT_EQ(expected_audio_layer, audio_layer);
678 }
679
680 // Verify that it is possible to explicitly create the two types of supported
681 // ADMs. These two tests overrides the default selection of native audio layer
682 // by ignoring if the device supports low-latency output or not.
TEST_F(AudioDeviceTest,CorrectAudioLayerIsUsedForCombinedJavaOpenSLCombo)683 TEST_F(AudioDeviceTest, CorrectAudioLayerIsUsedForCombinedJavaOpenSLCombo) {
684 AudioDeviceModule::AudioLayer expected_layer =
685 AudioDeviceModule::kAndroidJavaInputAndOpenSLESOutputAudio;
686 AudioDeviceModule::AudioLayer active_layer =
687 TestActiveAudioLayer(expected_layer);
688 EXPECT_EQ(expected_layer, active_layer);
689 }
690
TEST_F(AudioDeviceTest,CorrectAudioLayerIsUsedForJavaInBothDirections)691 TEST_F(AudioDeviceTest, CorrectAudioLayerIsUsedForJavaInBothDirections) {
692 AudioDeviceModule::AudioLayer expected_layer =
693 AudioDeviceModule::kAndroidJavaAudio;
694 AudioDeviceModule::AudioLayer active_layer =
695 TestActiveAudioLayer(expected_layer);
696 EXPECT_EQ(expected_layer, active_layer);
697 }
698
TEST_F(AudioDeviceTest,CorrectAudioLayerIsUsedForOpenSLInBothDirections)699 TEST_F(AudioDeviceTest, CorrectAudioLayerIsUsedForOpenSLInBothDirections) {
700 AudioDeviceModule::AudioLayer expected_layer =
701 AudioDeviceModule::kAndroidOpenSLESAudio;
702 AudioDeviceModule::AudioLayer active_layer =
703 TestActiveAudioLayer(expected_layer);
704 EXPECT_EQ(expected_layer, active_layer);
705 }
706
707 // TODO(bugs.webrtc.org/8914)
708 #if !defined(WEBRTC_AUDIO_DEVICE_INCLUDE_ANDROID_AAUDIO)
709 #define MAYBE_CorrectAudioLayerIsUsedForAAudioInBothDirections \
710 DISABLED_CorrectAudioLayerIsUsedForAAudioInBothDirections
711 #else
712 #define MAYBE_CorrectAudioLayerIsUsedForAAudioInBothDirections \
713 CorrectAudioLayerIsUsedForAAudioInBothDirections
714 #endif
TEST_F(AudioDeviceTest,MAYBE_CorrectAudioLayerIsUsedForAAudioInBothDirections)715 TEST_F(AudioDeviceTest,
716 MAYBE_CorrectAudioLayerIsUsedForAAudioInBothDirections) {
717 AudioDeviceModule::AudioLayer expected_layer =
718 AudioDeviceModule::kAndroidAAudioAudio;
719 AudioDeviceModule::AudioLayer active_layer =
720 TestActiveAudioLayer(expected_layer);
721 EXPECT_EQ(expected_layer, active_layer);
722 }
723
724 // TODO(bugs.webrtc.org/8914)
725 #if !defined(WEBRTC_AUDIO_DEVICE_INCLUDE_ANDROID_AAUDIO)
726 #define MAYBE_CorrectAudioLayerIsUsedForCombinedJavaAAudioCombo \
727 DISABLED_CorrectAudioLayerIsUsedForCombinedJavaAAudioCombo
728 #else
729 #define MAYBE_CorrectAudioLayerIsUsedForCombinedJavaAAudioCombo \
730 CorrectAudioLayerIsUsedForCombinedJavaAAudioCombo
731 #endif
TEST_F(AudioDeviceTest,MAYBE_CorrectAudioLayerIsUsedForCombinedJavaAAudioCombo)732 TEST_F(AudioDeviceTest,
733 MAYBE_CorrectAudioLayerIsUsedForCombinedJavaAAudioCombo) {
734 AudioDeviceModule::AudioLayer expected_layer =
735 AudioDeviceModule::kAndroidJavaInputAndAAudioOutputAudio;
736 AudioDeviceModule::AudioLayer active_layer =
737 TestActiveAudioLayer(expected_layer);
738 EXPECT_EQ(expected_layer, active_layer);
739 }
740
741 // The Android ADM supports two different delay reporting modes. One for the
742 // low-latency output path (in combination with OpenSL ES), and one for the
743 // high-latency output path (Java backends in both directions). These two tests
744 // verifies that the audio manager reports correct delay estimate given the
745 // selected audio layer. Note that, this delay estimate will only be utilized
746 // if the HW AEC is disabled.
TEST_F(AudioDeviceTest,UsesCorrectDelayEstimateForHighLatencyOutputPath)747 TEST_F(AudioDeviceTest, UsesCorrectDelayEstimateForHighLatencyOutputPath) {
748 EXPECT_EQ(kHighLatencyModeDelayEstimateInMilliseconds,
749 TestDelayOnAudioLayer(AudioDeviceModule::kAndroidJavaAudio));
750 }
751
TEST_F(AudioDeviceTest,UsesCorrectDelayEstimateForLowLatencyOutputPath)752 TEST_F(AudioDeviceTest, UsesCorrectDelayEstimateForLowLatencyOutputPath) {
753 EXPECT_EQ(kLowLatencyModeDelayEstimateInMilliseconds,
754 TestDelayOnAudioLayer(
755 AudioDeviceModule::kAndroidJavaInputAndOpenSLESOutputAudio));
756 }
757
758 // Ensure that the ADM internal audio device buffer is configured to use the
759 // correct set of parameters.
TEST_F(AudioDeviceTest,VerifyAudioDeviceBufferParameters)760 TEST_F(AudioDeviceTest, VerifyAudioDeviceBufferParameters) {
761 EXPECT_EQ(playout_parameters_.sample_rate(),
762 static_cast<int>(audio_device_buffer()->PlayoutSampleRate()));
763 EXPECT_EQ(record_parameters_.sample_rate(),
764 static_cast<int>(audio_device_buffer()->RecordingSampleRate()));
765 EXPECT_EQ(playout_parameters_.channels(),
766 audio_device_buffer()->PlayoutChannels());
767 EXPECT_EQ(record_parameters_.channels(),
768 audio_device_buffer()->RecordingChannels());
769 }
770
TEST_F(AudioDeviceTest,InitTerminate)771 TEST_F(AudioDeviceTest, InitTerminate) {
772 // Initialization is part of the test fixture.
773 EXPECT_TRUE(audio_device()->Initialized());
774 EXPECT_EQ(0, audio_device()->Terminate());
775 EXPECT_FALSE(audio_device()->Initialized());
776 }
777
TEST_F(AudioDeviceTest,Devices)778 TEST_F(AudioDeviceTest, Devices) {
779 // Device enumeration is not supported. Verify fixed values only.
780 EXPECT_EQ(1, audio_device()->PlayoutDevices());
781 EXPECT_EQ(1, audio_device()->RecordingDevices());
782 }
783
TEST_F(AudioDeviceTest,SpeakerVolumeShouldBeAvailable)784 TEST_F(AudioDeviceTest, SpeakerVolumeShouldBeAvailable) {
785 // The OpenSL ES output audio path does not support volume control.
786 if (!AudioLayerSupportsVolumeControl())
787 return;
788 bool available;
789 EXPECT_EQ(0, audio_device()->SpeakerVolumeIsAvailable(&available));
790 EXPECT_TRUE(available);
791 }
792
TEST_F(AudioDeviceTest,MaxSpeakerVolumeIsPositive)793 TEST_F(AudioDeviceTest, MaxSpeakerVolumeIsPositive) {
794 // The OpenSL ES output audio path does not support volume control.
795 if (!AudioLayerSupportsVolumeControl())
796 return;
797 StartPlayout();
798 EXPECT_GT(GetMaxSpeakerVolume(), 0);
799 StopPlayout();
800 }
801
TEST_F(AudioDeviceTest,MinSpeakerVolumeIsZero)802 TEST_F(AudioDeviceTest, MinSpeakerVolumeIsZero) {
803 // The OpenSL ES output audio path does not support volume control.
804 if (!AudioLayerSupportsVolumeControl())
805 return;
806 EXPECT_EQ(GetMinSpeakerVolume(), 0);
807 }
808
TEST_F(AudioDeviceTest,DefaultSpeakerVolumeIsWithinMinMax)809 TEST_F(AudioDeviceTest, DefaultSpeakerVolumeIsWithinMinMax) {
810 // The OpenSL ES output audio path does not support volume control.
811 if (!AudioLayerSupportsVolumeControl())
812 return;
813 const int default_volume = GetSpeakerVolume();
814 EXPECT_GE(default_volume, GetMinSpeakerVolume());
815 EXPECT_LE(default_volume, GetMaxSpeakerVolume());
816 }
817
TEST_F(AudioDeviceTest,SetSpeakerVolumeActuallySetsVolume)818 TEST_F(AudioDeviceTest, SetSpeakerVolumeActuallySetsVolume) {
819 // The OpenSL ES output audio path does not support volume control.
820 if (!AudioLayerSupportsVolumeControl())
821 return;
822 const int default_volume = GetSpeakerVolume();
823 const int max_volume = GetMaxSpeakerVolume();
824 EXPECT_EQ(0, audio_device()->SetSpeakerVolume(max_volume));
825 int new_volume = GetSpeakerVolume();
826 EXPECT_EQ(new_volume, max_volume);
827 EXPECT_EQ(0, audio_device()->SetSpeakerVolume(default_volume));
828 }
829
830 // Tests that playout can be initiated, started and stopped. No audio callback
831 // is registered in this test.
TEST_F(AudioDeviceTest,StartStopPlayout)832 TEST_F(AudioDeviceTest, StartStopPlayout) {
833 StartPlayout();
834 StopPlayout();
835 StartPlayout();
836 StopPlayout();
837 }
838
839 // Tests that recording can be initiated, started and stopped. No audio callback
840 // is registered in this test.
TEST_F(AudioDeviceTest,StartStopRecording)841 TEST_F(AudioDeviceTest, StartStopRecording) {
842 StartRecording();
843 StopRecording();
844 StartRecording();
845 StopRecording();
846 }
847
848 // Verify that calling StopPlayout() will leave us in an uninitialized state
849 // which will require a new call to InitPlayout(). This test does not call
850 // StartPlayout() while being uninitialized since doing so will hit a
851 // RTC_DCHECK and death tests are not supported on Android.
TEST_F(AudioDeviceTest,StopPlayoutRequiresInitToRestart)852 TEST_F(AudioDeviceTest, StopPlayoutRequiresInitToRestart) {
853 EXPECT_EQ(0, audio_device()->InitPlayout());
854 EXPECT_EQ(0, audio_device()->StartPlayout());
855 EXPECT_EQ(0, audio_device()->StopPlayout());
856 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
857 }
858
859 // Verify that calling StopRecording() will leave us in an uninitialized state
860 // which will require a new call to InitRecording(). This test does not call
861 // StartRecording() while being uninitialized since doing so will hit a
862 // RTC_DCHECK and death tests are not supported on Android.
TEST_F(AudioDeviceTest,StopRecordingRequiresInitToRestart)863 TEST_F(AudioDeviceTest, StopRecordingRequiresInitToRestart) {
864 EXPECT_EQ(0, audio_device()->InitRecording());
865 EXPECT_EQ(0, audio_device()->StartRecording());
866 EXPECT_EQ(0, audio_device()->StopRecording());
867 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
868 }
869
870 // Start playout and verify that the native audio layer starts asking for real
871 // audio samples to play out using the NeedMorePlayData callback.
TEST_F(AudioDeviceTest,StartPlayoutVerifyCallbacks)872 TEST_F(AudioDeviceTest, StartPlayoutVerifyCallbacks) {
873 MockAudioTransportAndroid mock(kPlayout);
874 mock.HandleCallbacks(&test_is_done_, nullptr, kNumCallbacks);
875 EXPECT_CALL(mock, NeedMorePlayData(playout_frames_per_10ms_buffer(),
876 kBytesPerSample, playout_channels(),
877 playout_sample_rate(), NotNull(), _, _, _))
878 .Times(AtLeast(kNumCallbacks));
879 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
880 StartPlayout();
881 test_is_done_.Wait(kTestTimeOutInMilliseconds);
882 StopPlayout();
883 }
884
885 // Start recording and verify that the native audio layer starts feeding real
886 // audio samples via the RecordedDataIsAvailable callback.
887 // TODO(henrika): investigate if it is possible to perform a sanity check of
888 // delay estimates as well (argument #6).
TEST_F(AudioDeviceTest,StartRecordingVerifyCallbacks)889 TEST_F(AudioDeviceTest, StartRecordingVerifyCallbacks) {
890 MockAudioTransportAndroid mock(kRecording);
891 mock.HandleCallbacks(&test_is_done_, nullptr, kNumCallbacks);
892 EXPECT_CALL(
893 mock, RecordedDataIsAvailable(NotNull(), record_frames_per_10ms_buffer(),
894 kBytesPerSample, record_channels(),
895 record_sample_rate(), _, 0, 0, false, _))
896 .Times(AtLeast(kNumCallbacks));
897
898 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
899 StartRecording();
900 test_is_done_.Wait(kTestTimeOutInMilliseconds);
901 StopRecording();
902 }
903
904 // Start playout and recording (full-duplex audio) and verify that audio is
905 // active in both directions.
TEST_F(AudioDeviceTest,StartPlayoutAndRecordingVerifyCallbacks)906 TEST_F(AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
907 MockAudioTransportAndroid mock(kPlayout | kRecording);
908 mock.HandleCallbacks(&test_is_done_, nullptr, kNumCallbacks);
909 EXPECT_CALL(mock, NeedMorePlayData(playout_frames_per_10ms_buffer(),
910 kBytesPerSample, playout_channels(),
911 playout_sample_rate(), NotNull(), _, _, _))
912 .Times(AtLeast(kNumCallbacks));
913 EXPECT_CALL(
914 mock, RecordedDataIsAvailable(NotNull(), record_frames_per_10ms_buffer(),
915 kBytesPerSample, record_channels(),
916 record_sample_rate(), _, 0, 0, false, _))
917 .Times(AtLeast(kNumCallbacks));
918 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
919 StartPlayout();
920 StartRecording();
921 test_is_done_.Wait(kTestTimeOutInMilliseconds);
922 StopRecording();
923 StopPlayout();
924 }
925
926 // Start playout and read audio from an external PCM file when the audio layer
927 // asks for data to play out. Real audio is played out in this test but it does
928 // not contain any explicit verification that the audio quality is perfect.
TEST_F(AudioDeviceTest,RunPlayoutWithFileAsSource)929 TEST_F(AudioDeviceTest, RunPlayoutWithFileAsSource) {
930 // TODO(henrika): extend test when mono output is supported.
931 EXPECT_EQ(1u, playout_channels());
932 NiceMock<MockAudioTransportAndroid> mock(kPlayout);
933 const int num_callbacks = kFilePlayTimeInSec * kNumCallbacksPerSecond;
934 std::string file_name = GetFileName(playout_sample_rate());
935 std::unique_ptr<FileAudioStream> file_audio_stream(
936 new FileAudioStream(num_callbacks, file_name, playout_sample_rate()));
937 mock.HandleCallbacks(&test_is_done_, file_audio_stream.get(), num_callbacks);
938 // SetMaxPlayoutVolume();
939 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
940 StartPlayout();
941 test_is_done_.Wait(kTestTimeOutInMilliseconds);
942 StopPlayout();
943 }
944
945 // Start playout and recording and store recorded data in an intermediate FIFO
946 // buffer from which the playout side then reads its samples in the same order
947 // as they were stored. Under ideal circumstances, a callback sequence would
948 // look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
949 // means 'packet played'. Under such conditions, the FIFO would only contain
950 // one packet on average. However, under more realistic conditions, the size
951 // of the FIFO will vary more due to an unbalance between the two sides.
952 // This test tries to verify that the device maintains a balanced callback-
953 // sequence by running in loopback for ten seconds while measuring the size
954 // (max and average) of the FIFO. The size of the FIFO is increased by the
955 // recording side and decreased by the playout side.
956 // TODO(henrika): tune the final test parameters after running tests on several
957 // different devices.
958 // Disabling this test on bots since it is difficult to come up with a robust
959 // test condition that all worked as intended. The main issue is that, when
960 // swarming is used, an initial latency can be built up when the both sides
961 // starts at different times. Hence, the test can fail even if audio works
962 // as intended. Keeping the test so it can be enabled manually.
963 // http://bugs.webrtc.org/7744
TEST_F(AudioDeviceTest,DISABLED_RunPlayoutAndRecordingInFullDuplex)964 TEST_F(AudioDeviceTest, DISABLED_RunPlayoutAndRecordingInFullDuplex) {
965 EXPECT_EQ(record_channels(), playout_channels());
966 EXPECT_EQ(record_sample_rate(), playout_sample_rate());
967 NiceMock<MockAudioTransportAndroid> mock(kPlayout | kRecording);
968 std::unique_ptr<FifoAudioStream> fifo_audio_stream(
969 new FifoAudioStream(playout_frames_per_10ms_buffer()));
970 mock.HandleCallbacks(&test_is_done_, fifo_audio_stream.get(),
971 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
972 SetMaxPlayoutVolume();
973 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
974 StartRecording();
975 StartPlayout();
976 test_is_done_.Wait(
977 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec));
978 StopPlayout();
979 StopRecording();
980
981 // These thresholds are set rather high to accomodate differences in hardware
982 // in several devices, so this test can be used in swarming.
983 // See http://bugs.webrtc.org/6464
984 EXPECT_LE(fifo_audio_stream->average_size(), 60u);
985 EXPECT_LE(fifo_audio_stream->largest_size(), 70u);
986 }
987
988 // Measures loopback latency and reports the min, max and average values for
989 // a full duplex audio session.
990 // The latency is measured like so:
991 // - Insert impulses periodically on the output side.
992 // - Detect the impulses on the input side.
993 // - Measure the time difference between the transmit time and receive time.
994 // - Store time differences in a vector and calculate min, max and average.
995 // This test requires a special hardware called Audio Loopback Dongle.
996 // See http://source.android.com/devices/audio/loopback.html for details.
TEST_F(AudioDeviceTest,DISABLED_MeasureLoopbackLatency)997 TEST_F(AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
998 EXPECT_EQ(record_channels(), playout_channels());
999 EXPECT_EQ(record_sample_rate(), playout_sample_rate());
1000 NiceMock<MockAudioTransportAndroid> mock(kPlayout | kRecording);
1001 std::unique_ptr<LatencyMeasuringAudioStream> latency_audio_stream(
1002 new LatencyMeasuringAudioStream(playout_frames_per_10ms_buffer()));
1003 mock.HandleCallbacks(&test_is_done_, latency_audio_stream.get(),
1004 kMeasureLatencyTimeInSec * kNumCallbacksPerSecond);
1005 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1006 SetMaxPlayoutVolume();
1007 DisableBuiltInAECIfAvailable();
1008 StartRecording();
1009 StartPlayout();
1010 test_is_done_.Wait(
1011 std::max(kTestTimeOutInMilliseconds, 1000 * kMeasureLatencyTimeInSec));
1012 StopPlayout();
1013 StopRecording();
1014 // Verify that the correct number of transmitted impulses are detected.
1015 EXPECT_EQ(latency_audio_stream->num_latency_values(),
1016 static_cast<size_t>(
1017 kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 1));
1018 latency_audio_stream->PrintResults();
1019 }
1020
1021 } // namespace webrtc
1022