blob: d9d52cdcdce4a3bc9f2bd351d4826d89385428f0 [file] [log] [blame]
Björn Terelius7534ebd2022-06-28 14:21:07 +00001/*
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
Ali Tofigh82c29712022-07-20 21:08:06 +020021#include "absl/strings/string_view.h"
Björn Terelius7534ebd2022-06-28 14:21:07 +000022#include "api/scoped_refptr.h"
23#include "api/task_queue/default_task_queue_factory.h"
24#include "api/task_queue/task_queue_factory.h"
25#include "modules/audio_device/android/audio_common.h"
26#include "modules/audio_device/android/audio_manager.h"
27#include "modules/audio_device/android/build_info.h"
28#include "modules/audio_device/android/ensure_initialized.h"
29#include "modules/audio_device/audio_device_impl.h"
30#include "modules/audio_device/include/mock_audio_transport.h"
31#include "rtc_base/arraysize.h"
32#include "rtc_base/event.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
39using std::cout;
40using std::endl;
41using ::testing::_;
42using ::testing::AtLeast;
43using ::testing::Gt;
44using ::testing::Invoke;
45using ::testing::NiceMock;
46using ::testing::NotNull;
47using ::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
57namespace 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.
61static const size_t kNumCallbacks = 10;
62// Max amount of time we wait for an event to be set while counting callbacks.
Markus Handell0cd0dd32022-08-19 12:42:31 +000063static constexpr TimeDelta kTestTimeOut = TimeDelta::Seconds(10);
Björn Terelius7534ebd2022-06-28 14:21:07 +000064// Average number of audio callbacks per second assuming 10ms packet size.
65static const size_t kNumCallbacksPerSecond = 100;
66// Play out a test file during this time (unit is in seconds).
67static const int kFilePlayTimeInSec = 5;
68static const size_t kBitsPerSample = 16;
69static 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.
Markus Handell0cd0dd32022-08-19 12:42:31 +000072static constexpr TimeDelta kFullDuplexTime = TimeDelta::Seconds(5);
Björn Terelius7534ebd2022-06-28 14:21:07 +000073// 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.
76static const size_t kNumIgnoreFirstCallbacks = 50;
77// Sets the number of impulses per second in the latency test.
78static const int kImpulseFrequencyInHz = 1;
79// Length of round-trip latency measurements. Number of transmitted impulses
Markus Handell0cd0dd32022-08-19 12:42:31 +000080// is kImpulseFrequencyInHz * kMeasureLatencyTime - 1.
81static constexpr TimeDelta kMeasureLatencyTime = TimeDelta::Seconds(11);
Björn Terelius7534ebd2022-06-28 14:21:07 +000082// Utilized in round-trip latency measurements to avoid capturing noise samples.
83static const int kImpulseThreshold = 1000;
84static const char kTag[] = "[..........] ";
85
86enum 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.
94class 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:
100 virtual ~AudioStreamInterface() {}
101};
102
103// Reads audio samples from a PCM file where the file is stored in memory at
104// construction.
105class FileAudioStream : public AudioStreamInterface {
106 public:
107 FileAudioStream(size_t num_callbacks,
Ali Tofigh82c29712022-07-20 21:08:06 +0200108 absl::string_view file_name,
Björn Terelius7534ebd2022-06-28 14:21:07 +0000109 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]);
Ali Tofigh82c29712022-07-20 21:08:06 +0200118 FILE* audio_file = fopen(std::string(file_name).c_str(), "rb");
Björn Terelius7534ebd2022-06-28 14:21:07 +0000119 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.
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.
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
137 int file_size_in_seconds() const {
138 return static_cast<int>(file_size_in_bytes_ /
139 (kBytesPerSample * sample_rate_));
140 }
141 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.
160class FifoAudioStream : public AudioStreamInterface {
161 public:
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
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.
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("(%zu)", 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.
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
212 size_t size() const { return fifo_->size(); }
213
214 size_t largest_size() const { return largest_size_; }
215
216 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:
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.
245class LatencyMeasuringAudioStream : public AudioStreamInterface {
246 public:
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`.
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.
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
310 size_t num_latency_values() const { return latencies_.size(); }
311
312 int min_latency() const {
313 if (latencies_.empty())
314 return 0;
315 return *std::min_element(latencies_.begin(), latencies_.end());
316 }
317
318 int max_latency() const {
319 if (latencies_.empty())
320 return 0;
321 return *std::max_element(latencies_.begin(), latencies_.end());
322 }
323
324 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
332 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
342 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.
358class MockAudioTransportAndroid : public test::MockAudioTransport {
359 public:
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
367 virtual ~MockAudioTransportAndroid() {}
368
369 // Set default actions of the mock object. We are delegating to fake
370 // implementations (of AudioStreamInterface) here.
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
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
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
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
450 bool play_mode() const { return type_ & kPlayout; }
451 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.
464class AudioDeviceTest : public ::testing::Test {
465 protected:
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 }
479 virtual ~AudioDeviceTest() { EXPECT_EQ(0, audio_device_->Terminate()); }
480
481 int playout_sample_rate() const { return playout_parameters_.sample_rate(); }
482 int record_sample_rate() const { return record_parameters_.sample_rate(); }
483 size_t playout_channels() const { return playout_parameters_.channels(); }
484 size_t record_channels() const { return record_parameters_.channels(); }
485 size_t playout_frames_per_10ms_buffer() const {
486 return playout_parameters_.frames_per_10ms_buffer();
487 }
488 size_t record_frames_per_10ms_buffer() const {
489 return record_parameters_.frames_per_10ms_buffer();
490 }
491
492 int total_delay_ms() const {
493 return audio_manager()->GetDelayEstimateInMilliseconds();
494 }
495
496 rtc::scoped_refptr<AudioDeviceModule> audio_device() const {
497 return audio_device_;
498 }
499
500 AudioDeviceModuleImpl* audio_device_impl() const {
501 return static_cast<AudioDeviceModuleImpl*>(audio_device_.get());
502 }
503
504 AudioManager* audio_manager() const {
505 return audio_device_impl()->GetAndroidAudioManagerForTest();
506 }
507
508 AudioManager* GetAudioManager(AudioDeviceModule* adm) const {
509 return static_cast<AudioDeviceModuleImpl*>(adm)
510 ->GetAndroidAudioManagerForTest();
511 }
512
513 AudioDeviceBuffer* audio_device_buffer() const {
514 return audio_device_impl()->GetAudioDeviceBuffer();
515 }
516
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.
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: %zu [bytes]\n", bytes);
536 PRINT("file size: %zu [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: %zu [callbacks]\n", seconds * kNumCallbacksPerSecond);
541#endif
542 return file_name;
543 }
544
545 AudioDeviceModule::AudioLayer GetActiveAudioLayer() const {
546 AudioDeviceModule::AudioLayer audio_layer;
547 EXPECT_EQ(0, audio_device()->ActiveAudioLayer(&audio_layer));
548 return audio_layer;
549 }
550
551 int TestDelayOnAudioLayer(
552 const AudioDeviceModule::AudioLayer& layer_to_test) {
553 rtc::scoped_refptr<AudioDeviceModule> audio_device;
554 audio_device = CreateAudioDevice(layer_to_test);
555 EXPECT_NE(audio_device.get(), nullptr);
556 AudioManager* audio_manager = GetAudioManager(audio_device.get());
557 EXPECT_NE(audio_manager, nullptr);
558 return audio_manager->GetDelayEstimateInMilliseconds();
559 }
560
561 AudioDeviceModule::AudioLayer TestActiveAudioLayer(
562 const AudioDeviceModule::AudioLayer& layer_to_test) {
563 rtc::scoped_refptr<AudioDeviceModule> audio_device;
564 audio_device = CreateAudioDevice(layer_to_test);
565 EXPECT_NE(audio_device.get(), nullptr);
566 AudioDeviceModule::AudioLayer active;
567 EXPECT_EQ(0, audio_device->ActiveAudioLayer(&active));
568 return active;
569 }
570
Ali Tofigh82c29712022-07-20 21:08:06 +0200571 bool DisableTestForThisDevice(absl::string_view model) {
Björn Terelius7534ebd2022-06-28 14:21:07 +0000572 return (build_info_->GetDeviceModel() == model);
573 }
574
575 // Volume control is currently only supported for the Java output audio layer.
576 // For OpenSL ES, the internal stream volume is always on max level and there
577 // is no need for this test to set it to max.
578 bool AudioLayerSupportsVolumeControl() const {
579 return GetActiveAudioLayer() == AudioDeviceModule::kAndroidJavaAudio;
580 }
581
582 void SetMaxPlayoutVolume() {
583 if (!AudioLayerSupportsVolumeControl())
584 return;
585 uint32_t max_volume;
586 EXPECT_EQ(0, audio_device()->MaxSpeakerVolume(&max_volume));
587 EXPECT_EQ(0, audio_device()->SetSpeakerVolume(max_volume));
588 }
589
590 void DisableBuiltInAECIfAvailable() {
591 if (audio_device()->BuiltInAECIsAvailable()) {
592 EXPECT_EQ(0, audio_device()->EnableBuiltInAEC(false));
593 }
594 }
595
596 void StartPlayout() {
597 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
598 EXPECT_FALSE(audio_device()->Playing());
599 EXPECT_EQ(0, audio_device()->InitPlayout());
600 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
601 EXPECT_EQ(0, audio_device()->StartPlayout());
602 EXPECT_TRUE(audio_device()->Playing());
603 }
604
605 void StopPlayout() {
606 EXPECT_EQ(0, audio_device()->StopPlayout());
607 EXPECT_FALSE(audio_device()->Playing());
608 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
609 }
610
611 void StartRecording() {
612 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
613 EXPECT_FALSE(audio_device()->Recording());
614 EXPECT_EQ(0, audio_device()->InitRecording());
615 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
616 EXPECT_EQ(0, audio_device()->StartRecording());
617 EXPECT_TRUE(audio_device()->Recording());
618 }
619
620 void StopRecording() {
621 EXPECT_EQ(0, audio_device()->StopRecording());
622 EXPECT_FALSE(audio_device()->Recording());
623 }
624
625 int GetMaxSpeakerVolume() const {
626 uint32_t max_volume(0);
627 EXPECT_EQ(0, audio_device()->MaxSpeakerVolume(&max_volume));
628 return max_volume;
629 }
630
631 int GetMinSpeakerVolume() const {
632 uint32_t min_volume(0);
633 EXPECT_EQ(0, audio_device()->MinSpeakerVolume(&min_volume));
634 return min_volume;
635 }
636
637 int GetSpeakerVolume() const {
638 uint32_t volume(0);
639 EXPECT_EQ(0, audio_device()->SpeakerVolume(&volume));
640 return volume;
641 }
642
643 rtc::Event test_is_done_;
644 std::unique_ptr<TaskQueueFactory> task_queue_factory_;
645 rtc::scoped_refptr<AudioDeviceModule> audio_device_;
646 AudioParameters playout_parameters_;
647 AudioParameters record_parameters_;
648 std::unique_ptr<BuildInfo> build_info_;
649};
650
651TEST_F(AudioDeviceTest, ConstructDestruct) {
652 // Using the test fixture to create and destruct the audio device module.
653}
654
655// We always ask for a default audio layer when the ADM is constructed. But the
656// ADM will then internally set the best suitable combination of audio layers,
657// for input and output based on if low-latency output and/or input audio in
658// combination with OpenSL ES is supported or not. This test ensures that the
659// correct selection is done.
660TEST_F(AudioDeviceTest, VerifyDefaultAudioLayer) {
661 const AudioDeviceModule::AudioLayer audio_layer = GetActiveAudioLayer();
662 bool low_latency_output = audio_manager()->IsLowLatencyPlayoutSupported();
663 bool low_latency_input = audio_manager()->IsLowLatencyRecordSupported();
664 bool aaudio = audio_manager()->IsAAudioSupported();
665 AudioDeviceModule::AudioLayer expected_audio_layer;
666 if (aaudio) {
667 expected_audio_layer = AudioDeviceModule::kAndroidAAudioAudio;
668 } else if (low_latency_output && low_latency_input) {
669 expected_audio_layer = AudioDeviceModule::kAndroidOpenSLESAudio;
670 } else if (low_latency_output && !low_latency_input) {
671 expected_audio_layer =
672 AudioDeviceModule::kAndroidJavaInputAndOpenSLESOutputAudio;
673 } else {
674 expected_audio_layer = AudioDeviceModule::kAndroidJavaAudio;
675 }
676 EXPECT_EQ(expected_audio_layer, audio_layer);
677}
678
679// Verify that it is possible to explicitly create the two types of supported
680// ADMs. These two tests overrides the default selection of native audio layer
681// by ignoring if the device supports low-latency output or not.
682TEST_F(AudioDeviceTest, CorrectAudioLayerIsUsedForCombinedJavaOpenSLCombo) {
683 AudioDeviceModule::AudioLayer expected_layer =
684 AudioDeviceModule::kAndroidJavaInputAndOpenSLESOutputAudio;
685 AudioDeviceModule::AudioLayer active_layer =
686 TestActiveAudioLayer(expected_layer);
687 EXPECT_EQ(expected_layer, active_layer);
688}
689
690TEST_F(AudioDeviceTest, CorrectAudioLayerIsUsedForJavaInBothDirections) {
691 AudioDeviceModule::AudioLayer expected_layer =
692 AudioDeviceModule::kAndroidJavaAudio;
693 AudioDeviceModule::AudioLayer active_layer =
694 TestActiveAudioLayer(expected_layer);
695 EXPECT_EQ(expected_layer, active_layer);
696}
697
698TEST_F(AudioDeviceTest, CorrectAudioLayerIsUsedForOpenSLInBothDirections) {
699 AudioDeviceModule::AudioLayer expected_layer =
700 AudioDeviceModule::kAndroidOpenSLESAudio;
701 AudioDeviceModule::AudioLayer active_layer =
702 TestActiveAudioLayer(expected_layer);
703 EXPECT_EQ(expected_layer, active_layer);
704}
705
706// TODO(bugs.webrtc.org/8914)
707#if !defined(WEBRTC_AUDIO_DEVICE_INCLUDE_ANDROID_AAUDIO)
708#define MAYBE_CorrectAudioLayerIsUsedForAAudioInBothDirections \
709 DISABLED_CorrectAudioLayerIsUsedForAAudioInBothDirections
710#else
711#define MAYBE_CorrectAudioLayerIsUsedForAAudioInBothDirections \
712 CorrectAudioLayerIsUsedForAAudioInBothDirections
713#endif
714TEST_F(AudioDeviceTest,
715 MAYBE_CorrectAudioLayerIsUsedForAAudioInBothDirections) {
716 AudioDeviceModule::AudioLayer expected_layer =
717 AudioDeviceModule::kAndroidAAudioAudio;
718 AudioDeviceModule::AudioLayer active_layer =
719 TestActiveAudioLayer(expected_layer);
720 EXPECT_EQ(expected_layer, active_layer);
721}
722
723// TODO(bugs.webrtc.org/8914)
724#if !defined(WEBRTC_AUDIO_DEVICE_INCLUDE_ANDROID_AAUDIO)
725#define MAYBE_CorrectAudioLayerIsUsedForCombinedJavaAAudioCombo \
726 DISABLED_CorrectAudioLayerIsUsedForCombinedJavaAAudioCombo
727#else
728#define MAYBE_CorrectAudioLayerIsUsedForCombinedJavaAAudioCombo \
729 CorrectAudioLayerIsUsedForCombinedJavaAAudioCombo
730#endif
731TEST_F(AudioDeviceTest,
732 MAYBE_CorrectAudioLayerIsUsedForCombinedJavaAAudioCombo) {
733 AudioDeviceModule::AudioLayer expected_layer =
734 AudioDeviceModule::kAndroidJavaInputAndAAudioOutputAudio;
735 AudioDeviceModule::AudioLayer active_layer =
736 TestActiveAudioLayer(expected_layer);
737 EXPECT_EQ(expected_layer, active_layer);
738}
739
740// The Android ADM supports two different delay reporting modes. One for the
741// low-latency output path (in combination with OpenSL ES), and one for the
742// high-latency output path (Java backends in both directions). These two tests
743// verifies that the audio manager reports correct delay estimate given the
744// selected audio layer. Note that, this delay estimate will only be utilized
745// if the HW AEC is disabled.
746TEST_F(AudioDeviceTest, UsesCorrectDelayEstimateForHighLatencyOutputPath) {
747 EXPECT_EQ(kHighLatencyModeDelayEstimateInMilliseconds,
748 TestDelayOnAudioLayer(AudioDeviceModule::kAndroidJavaAudio));
749}
750
751TEST_F(AudioDeviceTest, UsesCorrectDelayEstimateForLowLatencyOutputPath) {
752 EXPECT_EQ(kLowLatencyModeDelayEstimateInMilliseconds,
753 TestDelayOnAudioLayer(
754 AudioDeviceModule::kAndroidJavaInputAndOpenSLESOutputAudio));
755}
756
757// Ensure that the ADM internal audio device buffer is configured to use the
758// correct set of parameters.
759TEST_F(AudioDeviceTest, VerifyAudioDeviceBufferParameters) {
760 EXPECT_EQ(playout_parameters_.sample_rate(),
761 static_cast<int>(audio_device_buffer()->PlayoutSampleRate()));
762 EXPECT_EQ(record_parameters_.sample_rate(),
763 static_cast<int>(audio_device_buffer()->RecordingSampleRate()));
764 EXPECT_EQ(playout_parameters_.channels(),
765 audio_device_buffer()->PlayoutChannels());
766 EXPECT_EQ(record_parameters_.channels(),
767 audio_device_buffer()->RecordingChannels());
768}
769
770TEST_F(AudioDeviceTest, InitTerminate) {
771 // Initialization is part of the test fixture.
772 EXPECT_TRUE(audio_device()->Initialized());
773 EXPECT_EQ(0, audio_device()->Terminate());
774 EXPECT_FALSE(audio_device()->Initialized());
775}
776
777TEST_F(AudioDeviceTest, Devices) {
778 // Device enumeration is not supported. Verify fixed values only.
779 EXPECT_EQ(1, audio_device()->PlayoutDevices());
780 EXPECT_EQ(1, audio_device()->RecordingDevices());
781}
782
783TEST_F(AudioDeviceTest, SpeakerVolumeShouldBeAvailable) {
784 // The OpenSL ES output audio path does not support volume control.
785 if (!AudioLayerSupportsVolumeControl())
786 return;
787 bool available;
788 EXPECT_EQ(0, audio_device()->SpeakerVolumeIsAvailable(&available));
789 EXPECT_TRUE(available);
790}
791
792TEST_F(AudioDeviceTest, MaxSpeakerVolumeIsPositive) {
793 // The OpenSL ES output audio path does not support volume control.
794 if (!AudioLayerSupportsVolumeControl())
795 return;
796 StartPlayout();
797 EXPECT_GT(GetMaxSpeakerVolume(), 0);
798 StopPlayout();
799}
800
801TEST_F(AudioDeviceTest, MinSpeakerVolumeIsZero) {
802 // The OpenSL ES output audio path does not support volume control.
803 if (!AudioLayerSupportsVolumeControl())
804 return;
805 EXPECT_EQ(GetMinSpeakerVolume(), 0);
806}
807
808TEST_F(AudioDeviceTest, DefaultSpeakerVolumeIsWithinMinMax) {
809 // The OpenSL ES output audio path does not support volume control.
810 if (!AudioLayerSupportsVolumeControl())
811 return;
812 const int default_volume = GetSpeakerVolume();
813 EXPECT_GE(default_volume, GetMinSpeakerVolume());
814 EXPECT_LE(default_volume, GetMaxSpeakerVolume());
815}
816
817TEST_F(AudioDeviceTest, SetSpeakerVolumeActuallySetsVolume) {
818 // The OpenSL ES output audio path does not support volume control.
819 if (!AudioLayerSupportsVolumeControl())
820 return;
821 const int default_volume = GetSpeakerVolume();
822 const int max_volume = GetMaxSpeakerVolume();
823 EXPECT_EQ(0, audio_device()->SetSpeakerVolume(max_volume));
824 int new_volume = GetSpeakerVolume();
825 EXPECT_EQ(new_volume, max_volume);
826 EXPECT_EQ(0, audio_device()->SetSpeakerVolume(default_volume));
827}
828
829// Tests that playout can be initiated, started and stopped. No audio callback
830// is registered in this test.
831TEST_F(AudioDeviceTest, StartStopPlayout) {
832 StartPlayout();
833 StopPlayout();
834 StartPlayout();
835 StopPlayout();
836}
837
838// Tests that recording can be initiated, started and stopped. No audio callback
839// is registered in this test.
840TEST_F(AudioDeviceTest, StartStopRecording) {
841 StartRecording();
842 StopRecording();
843 StartRecording();
844 StopRecording();
845}
846
847// Verify that calling StopPlayout() will leave us in an uninitialized state
848// which will require a new call to InitPlayout(). This test does not call
849// StartPlayout() while being uninitialized since doing so will hit a
850// RTC_DCHECK and death tests are not supported on Android.
851TEST_F(AudioDeviceTest, StopPlayoutRequiresInitToRestart) {
852 EXPECT_EQ(0, audio_device()->InitPlayout());
853 EXPECT_EQ(0, audio_device()->StartPlayout());
854 EXPECT_EQ(0, audio_device()->StopPlayout());
855 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
856}
857
858// Verify that calling StopRecording() will leave us in an uninitialized state
859// which will require a new call to InitRecording(). This test does not call
860// StartRecording() while being uninitialized since doing so will hit a
861// RTC_DCHECK and death tests are not supported on Android.
862TEST_F(AudioDeviceTest, StopRecordingRequiresInitToRestart) {
863 EXPECT_EQ(0, audio_device()->InitRecording());
864 EXPECT_EQ(0, audio_device()->StartRecording());
865 EXPECT_EQ(0, audio_device()->StopRecording());
866 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
867}
868
869// Start playout and verify that the native audio layer starts asking for real
870// audio samples to play out using the NeedMorePlayData callback.
871TEST_F(AudioDeviceTest, StartPlayoutVerifyCallbacks) {
872 MockAudioTransportAndroid mock(kPlayout);
873 mock.HandleCallbacks(&test_is_done_, nullptr, kNumCallbacks);
874 EXPECT_CALL(mock, NeedMorePlayData(playout_frames_per_10ms_buffer(),
875 kBytesPerSample, playout_channels(),
876 playout_sample_rate(), NotNull(), _, _, _))
877 .Times(AtLeast(kNumCallbacks));
878 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
879 StartPlayout();
Markus Handell0cd0dd32022-08-19 12:42:31 +0000880 test_is_done_.Wait(kTestTimeOut);
Björn Terelius7534ebd2022-06-28 14:21:07 +0000881 StopPlayout();
882}
883
884// Start recording and verify that the native audio layer starts feeding real
885// audio samples via the RecordedDataIsAvailable callback.
886// TODO(henrika): investigate if it is possible to perform a sanity check of
887// delay estimates as well (argument #6).
888TEST_F(AudioDeviceTest, StartRecordingVerifyCallbacks) {
889 MockAudioTransportAndroid mock(kRecording);
890 mock.HandleCallbacks(&test_is_done_, nullptr, kNumCallbacks);
891 EXPECT_CALL(
892 mock, RecordedDataIsAvailable(NotNull(), record_frames_per_10ms_buffer(),
893 kBytesPerSample, record_channels(),
894 record_sample_rate(), _, 0, 0, false, _, _))
895 .Times(AtLeast(kNumCallbacks));
896
897 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
898 StartRecording();
Markus Handell0cd0dd32022-08-19 12:42:31 +0000899 test_is_done_.Wait(kTestTimeOut);
Björn Terelius7534ebd2022-06-28 14:21:07 +0000900 StopRecording();
901}
902
903// Start playout and recording (full-duplex audio) and verify that audio is
904// active in both directions.
905TEST_F(AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
906 MockAudioTransportAndroid mock(kPlayout | kRecording);
907 mock.HandleCallbacks(&test_is_done_, nullptr, kNumCallbacks);
908 EXPECT_CALL(mock, NeedMorePlayData(playout_frames_per_10ms_buffer(),
909 kBytesPerSample, playout_channels(),
910 playout_sample_rate(), NotNull(), _, _, _))
911 .Times(AtLeast(kNumCallbacks));
912 EXPECT_CALL(
913 mock, RecordedDataIsAvailable(NotNull(), record_frames_per_10ms_buffer(),
914 kBytesPerSample, record_channels(),
915 record_sample_rate(), _, 0, 0, false, _, _))
916 .Times(AtLeast(kNumCallbacks));
917 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
918 StartPlayout();
919 StartRecording();
Markus Handell0cd0dd32022-08-19 12:42:31 +0000920 test_is_done_.Wait(kTestTimeOut);
Björn Terelius7534ebd2022-06-28 14:21:07 +0000921 StopRecording();
922 StopPlayout();
923}
924
925// Start playout and read audio from an external PCM file when the audio layer
926// asks for data to play out. Real audio is played out in this test but it does
927// not contain any explicit verification that the audio quality is perfect.
928TEST_F(AudioDeviceTest, RunPlayoutWithFileAsSource) {
929 // TODO(henrika): extend test when mono output is supported.
930 EXPECT_EQ(1u, playout_channels());
931 NiceMock<MockAudioTransportAndroid> mock(kPlayout);
932 const int num_callbacks = kFilePlayTimeInSec * kNumCallbacksPerSecond;
933 std::string file_name = GetFileName(playout_sample_rate());
934 std::unique_ptr<FileAudioStream> file_audio_stream(
935 new FileAudioStream(num_callbacks, file_name, playout_sample_rate()));
936 mock.HandleCallbacks(&test_is_done_, file_audio_stream.get(), num_callbacks);
937 // SetMaxPlayoutVolume();
938 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
939 StartPlayout();
Markus Handell0cd0dd32022-08-19 12:42:31 +0000940 test_is_done_.Wait(kTestTimeOut);
Björn Terelius7534ebd2022-06-28 14:21:07 +0000941 StopPlayout();
942}
943
944// Start playout and recording and store recorded data in an intermediate FIFO
945// buffer from which the playout side then reads its samples in the same order
946// as they were stored. Under ideal circumstances, a callback sequence would
947// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
948// means 'packet played'. Under such conditions, the FIFO would only contain
949// one packet on average. However, under more realistic conditions, the size
950// of the FIFO will vary more due to an unbalance between the two sides.
951// This test tries to verify that the device maintains a balanced callback-
952// sequence by running in loopback for ten seconds while measuring the size
953// (max and average) of the FIFO. The size of the FIFO is increased by the
954// recording side and decreased by the playout side.
955// TODO(henrika): tune the final test parameters after running tests on several
956// different devices.
957// Disabling this test on bots since it is difficult to come up with a robust
958// test condition that all worked as intended. The main issue is that, when
959// swarming is used, an initial latency can be built up when the both sides
960// starts at different times. Hence, the test can fail even if audio works
961// as intended. Keeping the test so it can be enabled manually.
962// http://bugs.webrtc.org/7744
963TEST_F(AudioDeviceTest, DISABLED_RunPlayoutAndRecordingInFullDuplex) {
964 EXPECT_EQ(record_channels(), playout_channels());
965 EXPECT_EQ(record_sample_rate(), playout_sample_rate());
966 NiceMock<MockAudioTransportAndroid> mock(kPlayout | kRecording);
967 std::unique_ptr<FifoAudioStream> fifo_audio_stream(
968 new FifoAudioStream(playout_frames_per_10ms_buffer()));
969 mock.HandleCallbacks(&test_is_done_, fifo_audio_stream.get(),
Markus Handell0cd0dd32022-08-19 12:42:31 +0000970 kFullDuplexTime.seconds() * kNumCallbacksPerSecond);
Björn Terelius7534ebd2022-06-28 14:21:07 +0000971 SetMaxPlayoutVolume();
972 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
973 StartRecording();
974 StartPlayout();
Markus Handell0cd0dd32022-08-19 12:42:31 +0000975 test_is_done_.Wait(std::max(kTestTimeOut, kFullDuplexTime));
Björn Terelius7534ebd2022-06-28 14:21:07 +0000976 StopPlayout();
977 StopRecording();
978
979 // These thresholds are set rather high to accomodate differences in hardware
980 // in several devices, so this test can be used in swarming.
981 // See http://bugs.webrtc.org/6464
982 EXPECT_LE(fifo_audio_stream->average_size(), 60u);
983 EXPECT_LE(fifo_audio_stream->largest_size(), 70u);
984}
985
986// Measures loopback latency and reports the min, max and average values for
987// a full duplex audio session.
988// The latency is measured like so:
989// - Insert impulses periodically on the output side.
990// - Detect the impulses on the input side.
991// - Measure the time difference between the transmit time and receive time.
992// - Store time differences in a vector and calculate min, max and average.
993// This test requires a special hardware called Audio Loopback Dongle.
994// See http://source.android.com/devices/audio/loopback.html for details.
995TEST_F(AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
996 EXPECT_EQ(record_channels(), playout_channels());
997 EXPECT_EQ(record_sample_rate(), playout_sample_rate());
998 NiceMock<MockAudioTransportAndroid> mock(kPlayout | kRecording);
999 std::unique_ptr<LatencyMeasuringAudioStream> latency_audio_stream(
1000 new LatencyMeasuringAudioStream(playout_frames_per_10ms_buffer()));
1001 mock.HandleCallbacks(&test_is_done_, latency_audio_stream.get(),
Markus Handell0cd0dd32022-08-19 12:42:31 +00001002 kMeasureLatencyTime.seconds() * kNumCallbacksPerSecond);
Björn Terelius7534ebd2022-06-28 14:21:07 +00001003 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1004 SetMaxPlayoutVolume();
1005 DisableBuiltInAECIfAvailable();
1006 StartRecording();
1007 StartPlayout();
Markus Handell0cd0dd32022-08-19 12:42:31 +00001008 test_is_done_.Wait(std::max(kTestTimeOut, kMeasureLatencyTime));
Björn Terelius7534ebd2022-06-28 14:21:07 +00001009 StopPlayout();
1010 StopRecording();
1011 // Verify that the correct number of transmitted impulses are detected.
1012 EXPECT_EQ(latency_audio_stream->num_latency_values(),
1013 static_cast<size_t>(
Markus Handell0cd0dd32022-08-19 12:42:31 +00001014 kImpulseFrequencyInHz * kMeasureLatencyTime.seconds() - 1));
Björn Terelius7534ebd2022-06-28 14:21:07 +00001015 latency_audio_stream->PrintResults();
1016}
1017
1018} // namespace webrtc