blob: f4893c587b9f57e8bcf3a1f29480902fe7c8f703 [file] [log] [blame]
henrikaf2f91fa2017-03-17 04:26:22 -07001/*
2 * Copyright (c) 2017 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
henrika714e5cd2017-04-20 08:03:11 -070011#include <algorithm>
henrikaf2f91fa2017-03-17 04:26:22 -070012#include <cstring>
henrika714e5cd2017-04-20 08:03:11 -070013#include <numeric>
henrikaf2f91fa2017-03-17 04:26:22 -070014
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020015#include "api/array_view.h"
16#include "api/optional.h"
17#include "modules/audio_device/audio_device_impl.h"
18#include "modules/audio_device/include/audio_device.h"
19#include "modules/audio_device/include/mock_audio_transport.h"
20#include "rtc_base/buffer.h"
21#include "rtc_base/criticalsection.h"
22#include "rtc_base/event.h"
23#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010024#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "rtc_base/race_checker.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "rtc_base/scoped_ref_ptr.h"
27#include "rtc_base/thread_annotations.h"
28#include "rtc_base/thread_checker.h"
29#include "rtc_base/timeutils.h"
30#include "test/gmock.h"
31#include "test/gtest.h"
henrikaf2f91fa2017-03-17 04:26:22 -070032
33using ::testing::_;
34using ::testing::AtLeast;
35using ::testing::Ge;
36using ::testing::Invoke;
37using ::testing::NiceMock;
38using ::testing::NotNull;
39
40namespace webrtc {
41namespace {
42
henrikae24991d2017-04-06 01:14:23 -070043// #define ENABLE_DEBUG_PRINTF
44#ifdef ENABLE_DEBUG_PRINTF
45#define PRINTD(...) fprintf(stderr, __VA_ARGS__);
46#else
47#define PRINTD(...) ((void)0)
48#endif
49#define PRINT(...) fprintf(stderr, __VA_ARGS__);
50
henrikaf2f91fa2017-03-17 04:26:22 -070051// Don't run these tests in combination with sanitizers.
52#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
53#define SKIP_TEST_IF_NOT(requirements_satisfied) \
54 do { \
55 if (!requirements_satisfied) { \
56 return; \
57 } \
58 } while (false)
59#else
60// Or if other audio-related requirements are not met.
61#define SKIP_TEST_IF_NOT(requirements_satisfied) \
62 do { \
63 return; \
64 } while (false)
65#endif
66
67// Number of callbacks (input or output) the tests waits for before we set
68// an event indicating that the test was OK.
henrikae24991d2017-04-06 01:14:23 -070069static constexpr size_t kNumCallbacks = 10;
henrikaf2f91fa2017-03-17 04:26:22 -070070// Max amount of time we wait for an event to be set while counting callbacks.
henrika714e5cd2017-04-20 08:03:11 -070071static constexpr size_t kTestTimeOutInMilliseconds = 10 * 1000;
henrikae24991d2017-04-06 01:14:23 -070072// Average number of audio callbacks per second assuming 10ms packet size.
73static constexpr size_t kNumCallbacksPerSecond = 100;
74// Run the full-duplex test during this time (unit is in seconds).
henrika714e5cd2017-04-20 08:03:11 -070075static constexpr size_t kFullDuplexTimeInSec = 5;
76// Length of round-trip latency measurements. Number of deteced impulses
77// shall be kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 1 since the
78// last transmitted pulse is not used.
79static constexpr size_t kMeasureLatencyTimeInSec = 10;
80// Sets the number of impulses per second in the latency test.
81static constexpr size_t kImpulseFrequencyInHz = 1;
82// Utilized in round-trip latency measurements to avoid capturing noise samples.
83static constexpr int kImpulseThreshold = 1000;
henrikaf2f91fa2017-03-17 04:26:22 -070084
85enum class TransportType {
86 kInvalid,
87 kPlay,
88 kRecord,
89 kPlayAndRecord,
90};
henrikae24991d2017-04-06 01:14:23 -070091
92// Interface for processing the audio stream. Real implementations can e.g.
93// run audio in loopback, read audio from a file or perform latency
94// measurements.
95class AudioStream {
96 public:
henrikaeb98c722018-03-20 12:54:07 +010097 virtual void Write(rtc::ArrayView<const int16_t> source) = 0;
98 virtual void Read(rtc::ArrayView<int16_t> destination) = 0;
henrikae24991d2017-04-06 01:14:23 -070099
100 virtual ~AudioStream() = default;
101};
102
henrika714e5cd2017-04-20 08:03:11 -0700103// Converts index corresponding to position within a 10ms buffer into a
104// delay value in milliseconds.
105// Example: index=240, frames_per_10ms_buffer=480 => 5ms as output.
106int IndexToMilliseconds(size_t index, size_t frames_per_10ms_buffer) {
107 return rtc::checked_cast<int>(
108 10.0 * (static_cast<double>(index) / frames_per_10ms_buffer) + 0.5);
109}
110
henrikaf2f91fa2017-03-17 04:26:22 -0700111} // namespace
112
henrikae24991d2017-04-06 01:14:23 -0700113// Simple first in first out (FIFO) class that wraps a list of 16-bit audio
114// buffers of fixed size and allows Write and Read operations. The idea is to
115// store recorded audio buffers (using Write) and then read (using Read) these
116// stored buffers with as short delay as possible when the audio layer needs
117// data to play out. The number of buffers in the FIFO will stabilize under
118// normal conditions since there will be a balance between Write and Read calls.
119// The container is a std::list container and access is protected with a lock
120// since both sides (playout and recording) are driven by its own thread.
121// Note that, we know by design that the size of the audio buffer will not
122// change over time and that both sides will use the same size.
123class FifoAudioStream : public AudioStream {
124 public:
henrikaeb98c722018-03-20 12:54:07 +0100125 void Write(rtc::ArrayView<const int16_t> source) override {
henrikae24991d2017-04-06 01:14:23 -0700126 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
127 const size_t size = [&] {
128 rtc::CritScope lock(&lock_);
129 fifo_.push_back(Buffer16(source.data(), source.size()));
130 return fifo_.size();
131 }();
132 if (size > max_size_) {
133 max_size_ = size;
134 }
135 // Add marker once per second to signal that audio is active.
136 if (write_count_++ % 100 == 0) {
137 PRINT(".");
138 }
139 written_elements_ += size;
140 }
141
henrikaeb98c722018-03-20 12:54:07 +0100142 void Read(rtc::ArrayView<int16_t> destination) override {
henrikae24991d2017-04-06 01:14:23 -0700143 rtc::CritScope lock(&lock_);
144 if (fifo_.empty()) {
145 std::fill(destination.begin(), destination.end(), 0);
146 } else {
147 const Buffer16& buffer = fifo_.front();
148 RTC_CHECK_EQ(buffer.size(), destination.size());
149 std::copy(buffer.begin(), buffer.end(), destination.begin());
150 fifo_.pop_front();
151 }
152 }
153
154 size_t size() const {
155 rtc::CritScope lock(&lock_);
156 return fifo_.size();
157 }
158
159 size_t max_size() const {
160 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
161 return max_size_;
162 }
163
164 size_t average_size() const {
165 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
166 return 0.5 + static_cast<float>(written_elements_ / write_count_);
167 }
168
169 using Buffer16 = rtc::BufferT<int16_t>;
170
171 rtc::CriticalSection lock_;
172 rtc::RaceChecker race_checker_;
173
danilchap56359be2017-09-07 07:53:45 -0700174 std::list<Buffer16> fifo_ RTC_GUARDED_BY(lock_);
175 size_t write_count_ RTC_GUARDED_BY(race_checker_) = 0;
176 size_t max_size_ RTC_GUARDED_BY(race_checker_) = 0;
177 size_t written_elements_ RTC_GUARDED_BY(race_checker_) = 0;
henrikae24991d2017-04-06 01:14:23 -0700178};
179
henrika714e5cd2017-04-20 08:03:11 -0700180// Inserts periodic impulses and measures the latency between the time of
181// transmission and time of receiving the same impulse.
182class LatencyAudioStream : public AudioStream {
183 public:
184 LatencyAudioStream() {
185 // Delay thread checkers from being initialized until first callback from
186 // respective thread.
187 read_thread_checker_.DetachFromThread();
188 write_thread_checker_.DetachFromThread();
189 }
190
191 // Insert periodic impulses in first two samples of |destination|.
henrikaeb98c722018-03-20 12:54:07 +0100192 void Read(rtc::ArrayView<int16_t> destination) override {
henrika714e5cd2017-04-20 08:03:11 -0700193 RTC_DCHECK_RUN_ON(&read_thread_checker_);
henrika714e5cd2017-04-20 08:03:11 -0700194 if (read_count_ == 0) {
195 PRINT("[");
196 }
197 read_count_++;
198 std::fill(destination.begin(), destination.end(), 0);
199 if (read_count_ % (kNumCallbacksPerSecond / kImpulseFrequencyInHz) == 0) {
200 PRINT(".");
201 {
202 rtc::CritScope lock(&lock_);
203 if (!pulse_time_) {
Oskar Sundbom6ad9f262017-11-16 10:53:39 +0100204 pulse_time_ = rtc::TimeMillis();
henrika714e5cd2017-04-20 08:03:11 -0700205 }
206 }
207 constexpr int16_t impulse = std::numeric_limits<int16_t>::max();
208 std::fill_n(destination.begin(), 2, impulse);
209 }
210 }
211
212 // Detect received impulses in |source|, derive time between transmission and
213 // detection and add the calculated delay to list of latencies.
henrikaeb98c722018-03-20 12:54:07 +0100214 void Write(rtc::ArrayView<const int16_t> source) override {
henrika714e5cd2017-04-20 08:03:11 -0700215 RTC_DCHECK_RUN_ON(&write_thread_checker_);
216 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
217 rtc::CritScope lock(&lock_);
218 write_count_++;
219 if (!pulse_time_) {
220 // Avoid detection of new impulse response until a new impulse has
221 // been transmitted (sets |pulse_time_| to value larger than zero).
222 return;
223 }
224 // Find index (element position in vector) of the max element.
225 const size_t index_of_max =
226 std::max_element(source.begin(), source.end()) - source.begin();
227 // Derive time between transmitted pulse and received pulse if the level
228 // is high enough (removes noise).
229 const size_t max = source[index_of_max];
230 if (max > kImpulseThreshold) {
231 PRINTD("(%zu, %zu)", max, index_of_max);
232 int64_t now_time = rtc::TimeMillis();
233 int extra_delay = IndexToMilliseconds(index_of_max, source.size());
234 PRINTD("[%d]", rtc::checked_cast<int>(now_time - pulse_time_));
235 PRINTD("[%d]", extra_delay);
236 // Total latency is the difference between transmit time and detection
237 // tome plus the extra delay within the buffer in which we detected the
238 // received impulse. It is transmitted at sample 0 but can be received
239 // at sample N where N > 0. The term |extra_delay| accounts for N and it
240 // is a value between 0 and 10ms.
241 latencies_.push_back(now_time - *pulse_time_ + extra_delay);
242 pulse_time_.reset();
243 } else {
244 PRINTD("-");
245 }
246 }
247
248 size_t num_latency_values() const {
249 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
250 return latencies_.size();
251 }
252
253 int min_latency() const {
254 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
255 if (latencies_.empty())
256 return 0;
257 return *std::min_element(latencies_.begin(), latencies_.end());
258 }
259
260 int max_latency() const {
261 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
262 if (latencies_.empty())
263 return 0;
264 return *std::max_element(latencies_.begin(), latencies_.end());
265 }
266
267 int average_latency() const {
268 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
269 if (latencies_.empty())
270 return 0;
271 return 0.5 + static_cast<double>(
272 std::accumulate(latencies_.begin(), latencies_.end(), 0)) /
273 latencies_.size();
274 }
275
276 void PrintResults() const {
277 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
278 PRINT("] ");
279 for (auto it = latencies_.begin(); it != latencies_.end(); ++it) {
280 PRINTD("%d ", *it);
281 }
282 PRINT("\n");
283 PRINT("[..........] [min, max, avg]=[%d, %d, %d] ms\n", min_latency(),
284 max_latency(), average_latency());
285 }
286
287 rtc::CriticalSection lock_;
288 rtc::RaceChecker race_checker_;
289 rtc::ThreadChecker read_thread_checker_;
290 rtc::ThreadChecker write_thread_checker_;
291
danilchap56359be2017-09-07 07:53:45 -0700292 rtc::Optional<int64_t> pulse_time_ RTC_GUARDED_BY(lock_);
293 std::vector<int> latencies_ RTC_GUARDED_BY(race_checker_);
Niels Möller1e062892018-02-07 10:18:32 +0100294 size_t read_count_ RTC_GUARDED_BY(read_thread_checker_) = 0;
295 size_t write_count_ RTC_GUARDED_BY(write_thread_checker_) = 0;
henrika714e5cd2017-04-20 08:03:11 -0700296};
297
henrikaf2f91fa2017-03-17 04:26:22 -0700298// Mocks the AudioTransport object and proxies actions for the two callbacks
299// (RecordedDataIsAvailable and NeedMorePlayData) to different implementations
300// of AudioStreamInterface.
301class MockAudioTransport : public test::MockAudioTransport {
302 public:
303 explicit MockAudioTransport(TransportType type) : type_(type) {}
304 ~MockAudioTransport() {}
305
306 // Set default actions of the mock object. We are delegating to fake
307 // implementation where the number of callbacks is counted and an event
308 // is set after a certain number of callbacks. Audio parameters are also
309 // checked.
henrikae24991d2017-04-06 01:14:23 -0700310 void HandleCallbacks(rtc::Event* event,
311 AudioStream* audio_stream,
312 int num_callbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700313 event_ = event;
henrikae24991d2017-04-06 01:14:23 -0700314 audio_stream_ = audio_stream;
henrikaf2f91fa2017-03-17 04:26:22 -0700315 num_callbacks_ = num_callbacks;
316 if (play_mode()) {
317 ON_CALL(*this, NeedMorePlayData(_, _, _, _, _, _, _, _))
318 .WillByDefault(
319 Invoke(this, &MockAudioTransport::RealNeedMorePlayData));
320 }
321 if (rec_mode()) {
322 ON_CALL(*this, RecordedDataIsAvailable(_, _, _, _, _, _, _, _, _, _))
323 .WillByDefault(
324 Invoke(this, &MockAudioTransport::RealRecordedDataIsAvailable));
325 }
326 }
327
328 int32_t RealRecordedDataIsAvailable(const void* audio_buffer,
329 const size_t samples_per_channel,
330 const size_t bytes_per_frame,
331 const size_t channels,
332 const uint32_t sample_rate,
333 const uint32_t total_delay_ms,
334 const int32_t clock_drift,
335 const uint32_t current_mic_level,
336 const bool typing_status,
337 uint32_t& new_mic_level) {
338 EXPECT_TRUE(rec_mode()) << "No test is expecting these callbacks.";
Mirko Bonadei675513b2017-11-09 11:09:25 +0100339 RTC_LOG(INFO) << "+";
henrikaf2f91fa2017-03-17 04:26:22 -0700340 // Store audio parameters once in the first callback. For all other
341 // callbacks, verify that the provided audio parameters are maintained and
342 // that each callback corresponds to 10ms for any given sample rate.
343 if (!record_parameters_.is_complete()) {
344 record_parameters_.reset(sample_rate, channels, samples_per_channel);
345 } else {
346 EXPECT_EQ(samples_per_channel, record_parameters_.frames_per_buffer());
347 EXPECT_EQ(bytes_per_frame, record_parameters_.GetBytesPerFrame());
348 EXPECT_EQ(channels, record_parameters_.channels());
349 EXPECT_EQ(static_cast<int>(sample_rate),
350 record_parameters_.sample_rate());
351 EXPECT_EQ(samples_per_channel,
352 record_parameters_.frames_per_10ms_buffer());
353 }
354 rec_count_++;
henrikae24991d2017-04-06 01:14:23 -0700355 // Write audio data to audio stream object if one has been injected.
356 if (audio_stream_) {
357 audio_stream_->Write(
358 rtc::MakeArrayView(static_cast<const int16_t*>(audio_buffer),
henrikaeb98c722018-03-20 12:54:07 +0100359 samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700360 }
henrikaf2f91fa2017-03-17 04:26:22 -0700361 // Signal the event after given amount of callbacks.
362 if (ReceivedEnoughCallbacks()) {
363 event_->Set();
364 }
365 return 0;
366 }
367
368 int32_t RealNeedMorePlayData(const size_t samples_per_channel,
369 const size_t bytes_per_frame,
370 const size_t channels,
371 const uint32_t sample_rate,
372 void* audio_buffer,
henrikaeb98c722018-03-20 12:54:07 +0100373 size_t& samples_out,
henrikaf2f91fa2017-03-17 04:26:22 -0700374 int64_t* elapsed_time_ms,
375 int64_t* ntp_time_ms) {
376 EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
Mirko Bonadei675513b2017-11-09 11:09:25 +0100377 RTC_LOG(INFO) << "-";
henrikaf2f91fa2017-03-17 04:26:22 -0700378 // Store audio parameters once in the first callback. For all other
379 // callbacks, verify that the provided audio parameters are maintained and
380 // that each callback corresponds to 10ms for any given sample rate.
381 if (!playout_parameters_.is_complete()) {
382 playout_parameters_.reset(sample_rate, channels, samples_per_channel);
383 } else {
384 EXPECT_EQ(samples_per_channel, playout_parameters_.frames_per_buffer());
385 EXPECT_EQ(bytes_per_frame, playout_parameters_.GetBytesPerFrame());
386 EXPECT_EQ(channels, playout_parameters_.channels());
387 EXPECT_EQ(static_cast<int>(sample_rate),
388 playout_parameters_.sample_rate());
389 EXPECT_EQ(samples_per_channel,
390 playout_parameters_.frames_per_10ms_buffer());
391 }
392 play_count_++;
henrikaeb98c722018-03-20 12:54:07 +0100393 samples_out = samples_per_channel * channels;
henrikae24991d2017-04-06 01:14:23 -0700394 // Read audio data from audio stream object if one has been injected.
395 if (audio_stream_) {
henrikaeb98c722018-03-20 12:54:07 +0100396 audio_stream_->Read(rtc::MakeArrayView(
397 static_cast<int16_t*>(audio_buffer), samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700398 } else {
399 // Fill the audio buffer with zeros to avoid disturbing audio.
400 const size_t num_bytes = samples_per_channel * bytes_per_frame;
401 std::memset(audio_buffer, 0, num_bytes);
402 }
henrikaf2f91fa2017-03-17 04:26:22 -0700403 // Signal the event after given amount of callbacks.
404 if (ReceivedEnoughCallbacks()) {
405 event_->Set();
406 }
407 return 0;
408 }
409
410 bool ReceivedEnoughCallbacks() {
411 bool recording_done = false;
412 if (rec_mode()) {
413 recording_done = rec_count_ >= num_callbacks_;
414 } else {
415 recording_done = true;
416 }
417 bool playout_done = false;
418 if (play_mode()) {
419 playout_done = play_count_ >= num_callbacks_;
420 } else {
421 playout_done = true;
422 }
423 return recording_done && playout_done;
424 }
425
426 bool play_mode() const {
427 return type_ == TransportType::kPlay ||
428 type_ == TransportType::kPlayAndRecord;
429 }
430
431 bool rec_mode() const {
432 return type_ == TransportType::kRecord ||
433 type_ == TransportType::kPlayAndRecord;
434 }
435
436 private:
437 TransportType type_ = TransportType::kInvalid;
438 rtc::Event* event_ = nullptr;
henrikae24991d2017-04-06 01:14:23 -0700439 AudioStream* audio_stream_ = nullptr;
henrikaf2f91fa2017-03-17 04:26:22 -0700440 size_t num_callbacks_ = 0;
441 size_t play_count_ = 0;
442 size_t rec_count_ = 0;
443 AudioParameters playout_parameters_;
444 AudioParameters record_parameters_;
445};
446
447// AudioDeviceTest test fixture.
448class AudioDeviceTest : public ::testing::Test {
449 protected:
450 AudioDeviceTest() : event_(false, false) {
Joachim Bauch5d2bb362017-12-20 21:19:49 +0100451#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \
452 !defined(WEBRTC_DUMMY_AUDIO_BUILD)
henrikaf2f91fa2017-03-17 04:26:22 -0700453 rtc::LogMessage::LogToDebug(rtc::LS_INFO);
454 // Add extra logging fields here if needed for debugging.
455 // rtc::LogMessage::LogTimestamps();
456 // rtc::LogMessage::LogThreads();
457 audio_device_ =
henrika616e3132017-11-13 12:47:59 +0100458 AudioDeviceModule::Create(AudioDeviceModule::kPlatformDefaultAudio);
henrikaf2f91fa2017-03-17 04:26:22 -0700459 EXPECT_NE(audio_device_.get(), nullptr);
460 AudioDeviceModule::AudioLayer audio_layer;
maxmorin33bf69a2017-03-23 04:06:53 -0700461 int got_platform_audio_layer =
462 audio_device_->ActiveAudioLayer(&audio_layer);
henrika919dc2e2017-10-12 14:24:55 +0200463 // First, ensure that a valid audio layer can be activated.
464 if (got_platform_audio_layer != 0) {
henrikaf2f91fa2017-03-17 04:26:22 -0700465 requirements_satisfied_ = false;
466 }
henrika919dc2e2017-10-12 14:24:55 +0200467 // Next, verify that the ADM can be initialized.
henrikaf2f91fa2017-03-17 04:26:22 -0700468 if (requirements_satisfied_) {
henrika919dc2e2017-10-12 14:24:55 +0200469 requirements_satisfied_ = (audio_device_->Init() == 0);
470 }
471 // Finally, ensure that at least one valid device exists in each direction.
472 if (requirements_satisfied_) {
henrikaf2f91fa2017-03-17 04:26:22 -0700473 const int16_t num_playout_devices = audio_device_->PlayoutDevices();
474 const int16_t num_record_devices = audio_device_->RecordingDevices();
475 requirements_satisfied_ =
476 num_playout_devices > 0 && num_record_devices > 0;
477 }
478#else
479 requirements_satisfied_ = false;
480#endif
481 if (requirements_satisfied_) {
482 EXPECT_EQ(0, audio_device_->SetPlayoutDevice(0));
483 EXPECT_EQ(0, audio_device_->InitSpeaker());
484 EXPECT_EQ(0, audio_device_->SetRecordingDevice(0));
485 EXPECT_EQ(0, audio_device_->InitMicrophone());
486 EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
487 EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
henrika0238ba82017-03-28 04:38:29 -0700488 // Avoid asking for input stereo support and always record in mono
489 // since asking can cause issues in combination with remote desktop.
490 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
491 // details.
492 EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
henrikaf2f91fa2017-03-17 04:26:22 -0700493 }
494 }
495
496 virtual ~AudioDeviceTest() {
497 if (audio_device_) {
498 EXPECT_EQ(0, audio_device_->Terminate());
499 }
500 }
501
502 bool requirements_satisfied() const { return requirements_satisfied_; }
503 rtc::Event* event() { return &event_; }
504
505 const rtc::scoped_refptr<AudioDeviceModule>& audio_device() const {
506 return audio_device_;
507 }
508
509 void StartPlayout() {
510 EXPECT_FALSE(audio_device()->Playing());
511 EXPECT_EQ(0, audio_device()->InitPlayout());
512 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
513 EXPECT_EQ(0, audio_device()->StartPlayout());
514 EXPECT_TRUE(audio_device()->Playing());
515 }
516
517 void StopPlayout() {
518 EXPECT_EQ(0, audio_device()->StopPlayout());
519 EXPECT_FALSE(audio_device()->Playing());
520 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
521 }
522
523 void StartRecording() {
524 EXPECT_FALSE(audio_device()->Recording());
525 EXPECT_EQ(0, audio_device()->InitRecording());
526 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
527 EXPECT_EQ(0, audio_device()->StartRecording());
528 EXPECT_TRUE(audio_device()->Recording());
529 }
530
531 void StopRecording() {
532 EXPECT_EQ(0, audio_device()->StopRecording());
533 EXPECT_FALSE(audio_device()->Recording());
534 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
535 }
536
537 private:
538 bool requirements_satisfied_ = true;
539 rtc::Event event_;
540 rtc::scoped_refptr<AudioDeviceModule> audio_device_;
541 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700542};
543
544// Uses the test fixture to create, initialize and destruct the ADM.
545TEST_F(AudioDeviceTest, ConstructDestruct) {}
546
547TEST_F(AudioDeviceTest, InitTerminate) {
548 SKIP_TEST_IF_NOT(requirements_satisfied());
549 // Initialization is part of the test fixture.
550 EXPECT_TRUE(audio_device()->Initialized());
551 EXPECT_EQ(0, audio_device()->Terminate());
552 EXPECT_FALSE(audio_device()->Initialized());
553}
554
555// Tests Start/Stop playout without any registered audio callback.
556TEST_F(AudioDeviceTest, StartStopPlayout) {
557 SKIP_TEST_IF_NOT(requirements_satisfied());
558 StartPlayout();
559 StopPlayout();
560 StartPlayout();
561 StopPlayout();
562}
563
564// Tests Start/Stop recording without any registered audio callback.
565TEST_F(AudioDeviceTest, StartStopRecording) {
566 SKIP_TEST_IF_NOT(requirements_satisfied());
567 StartRecording();
568 StopRecording();
569 StartRecording();
570 StopRecording();
571}
572
henrika6b3e1a22017-09-25 16:34:30 +0200573// Tests Init/Stop/Init recording without any registered audio callback.
574// See https://bugs.chromium.org/p/webrtc/issues/detail?id=8041 for details
575// on why this test is useful.
576TEST_F(AudioDeviceTest, InitStopInitRecording) {
577 SKIP_TEST_IF_NOT(requirements_satisfied());
578 EXPECT_EQ(0, audio_device()->InitRecording());
579 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
580 StopRecording();
581 EXPECT_EQ(0, audio_device()->InitRecording());
582 StopRecording();
583}
584
585// Tests Init/Stop/Init recording while playout is active.
586TEST_F(AudioDeviceTest, InitStopInitRecordingWhilePlaying) {
587 SKIP_TEST_IF_NOT(requirements_satisfied());
588 StartPlayout();
589 EXPECT_EQ(0, audio_device()->InitRecording());
590 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
591 StopRecording();
592 EXPECT_EQ(0, audio_device()->InitRecording());
593 StopRecording();
594 StopPlayout();
595}
596
597// Tests Init/Stop/Init playout without any registered audio callback.
598TEST_F(AudioDeviceTest, InitStopInitPlayout) {
599 SKIP_TEST_IF_NOT(requirements_satisfied());
600 EXPECT_EQ(0, audio_device()->InitPlayout());
601 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
602 StopPlayout();
603 EXPECT_EQ(0, audio_device()->InitPlayout());
604 StopPlayout();
605}
606
607// Tests Init/Stop/Init playout while recording is active.
608TEST_F(AudioDeviceTest, InitStopInitPlayoutWhileRecording) {
609 SKIP_TEST_IF_NOT(requirements_satisfied());
610 StartRecording();
611 EXPECT_EQ(0, audio_device()->InitPlayout());
612 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
613 StopPlayout();
614 EXPECT_EQ(0, audio_device()->InitPlayout());
615 StopPlayout();
616 StopRecording();
617}
618
henrikaf2f91fa2017-03-17 04:26:22 -0700619// Start playout and verify that the native audio layer starts asking for real
620// audio samples to play out using the NeedMorePlayData() callback.
621// Note that we can't add expectations on audio parameters in EXPECT_CALL
622// since parameter are not provided in the each callback. We therefore test and
623// verify the parameters in the fake audio transport implementation instead.
624TEST_F(AudioDeviceTest, StartPlayoutVerifyCallbacks) {
625 SKIP_TEST_IF_NOT(requirements_satisfied());
626 MockAudioTransport mock(TransportType::kPlay);
henrikae24991d2017-04-06 01:14:23 -0700627 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700628 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
629 .Times(AtLeast(kNumCallbacks));
630 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
631 StartPlayout();
632 event()->Wait(kTestTimeOutInMilliseconds);
633 StopPlayout();
634}
635
636// Start recording and verify that the native audio layer starts providing real
637// audio samples using the RecordedDataIsAvailable() callback.
638TEST_F(AudioDeviceTest, StartRecordingVerifyCallbacks) {
639 SKIP_TEST_IF_NOT(requirements_satisfied());
640 MockAudioTransport mock(TransportType::kRecord);
henrikae24991d2017-04-06 01:14:23 -0700641 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700642 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
643 false, _))
644 .Times(AtLeast(kNumCallbacks));
645 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
646 StartRecording();
647 event()->Wait(kTestTimeOutInMilliseconds);
648 StopRecording();
649}
650
651// Start playout and recording (full-duplex audio) and verify that audio is
652// active in both directions.
653TEST_F(AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
654 SKIP_TEST_IF_NOT(requirements_satisfied());
655 MockAudioTransport mock(TransportType::kPlayAndRecord);
henrikae24991d2017-04-06 01:14:23 -0700656 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700657 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
658 .Times(AtLeast(kNumCallbacks));
659 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
660 false, _))
661 .Times(AtLeast(kNumCallbacks));
662 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
663 StartPlayout();
664 StartRecording();
665 event()->Wait(kTestTimeOutInMilliseconds);
666 StopRecording();
667 StopPlayout();
668}
669
henrikae24991d2017-04-06 01:14:23 -0700670// Start playout and recording and store recorded data in an intermediate FIFO
671// buffer from which the playout side then reads its samples in the same order
672// as they were stored. Under ideal circumstances, a callback sequence would
673// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
674// means 'packet played'. Under such conditions, the FIFO would contain max 1,
675// with an average somewhere in (0,1) depending on how long the packets are
676// buffered. However, under more realistic conditions, the size
677// of the FIFO will vary more due to an unbalance between the two sides.
678// This test tries to verify that the device maintains a balanced callback-
679// sequence by running in loopback for a few seconds while measuring the size
680// (max and average) of the FIFO. The size of the FIFO is increased by the
681// recording side and decreased by the playout side.
682TEST_F(AudioDeviceTest, RunPlayoutAndRecordingInFullDuplex) {
683 SKIP_TEST_IF_NOT(requirements_satisfied());
684 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
685 FifoAudioStream audio_stream;
686 mock.HandleCallbacks(event(), &audio_stream,
687 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
688 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +0100689 // Run both sides using the same channel configuration to avoid conversions
690 // between mono/stereo while running in full duplex mode. Also, some devices
691 // (mainly on Windows) do not support mono.
692 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
693 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrikae24991d2017-04-06 01:14:23 -0700694 StartPlayout();
695 StartRecording();
henrika714e5cd2017-04-20 08:03:11 -0700696 event()->Wait(static_cast<int>(
697 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec)));
henrikae24991d2017-04-06 01:14:23 -0700698 StopRecording();
699 StopPlayout();
700 // This thresholds is set rather high to accommodate differences in hardware
701 // in several devices. The main idea is to capture cases where a very large
henrikab6ca7212017-10-06 12:47:52 +0200702 // latency is built up. See http://bugs.webrtc.org/7744 for examples on
703 // bots where relatively large average latencies can happen.
704 EXPECT_LE(audio_stream.average_size(), 25u);
henrikae24991d2017-04-06 01:14:23 -0700705 PRINT("\n");
706}
707
henrika714e5cd2017-04-20 08:03:11 -0700708// Measures loopback latency and reports the min, max and average values for
709// a full duplex audio session.
710// The latency is measured like so:
711// - Insert impulses periodically on the output side.
712// - Detect the impulses on the input side.
713// - Measure the time difference between the transmit time and receive time.
714// - Store time differences in a vector and calculate min, max and average.
715// This test needs the '--gtest_also_run_disabled_tests' flag to run and also
716// some sort of audio feedback loop. E.g. a headset where the mic is placed
717// close to the speaker to ensure highest possible echo. It is also recommended
718// to run the test at highest possible output volume.
719TEST_F(AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
720 SKIP_TEST_IF_NOT(requirements_satisfied());
721 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
722 LatencyAudioStream audio_stream;
723 mock.HandleCallbacks(event(), &audio_stream,
724 kMeasureLatencyTimeInSec * kNumCallbacksPerSecond);
725 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +0100726 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
727 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrika714e5cd2017-04-20 08:03:11 -0700728 StartPlayout();
729 StartRecording();
730 event()->Wait(static_cast<int>(
731 std::max(kTestTimeOutInMilliseconds, 1000 * kMeasureLatencyTimeInSec)));
732 StopRecording();
733 StopPlayout();
734 // Verify that the correct number of transmitted impulses are detected.
735 EXPECT_EQ(audio_stream.num_latency_values(),
736 static_cast<size_t>(
737 kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 1));
738 // Print out min, max and average delay values for debugging purposes.
739 audio_stream.PrintResults();
740}
741
henrikaf2f91fa2017-03-17 04:26:22 -0700742} // namespace webrtc