blob: f721a6889fc25f358857ed9cf376f08202809921 [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
henrikae24991d2017-04-06 01:14:23 -070015#include "webrtc/base/array_view.h"
16#include "webrtc/base/buffer.h"
17#include "webrtc/base/criticalsection.h"
henrikaf2f91fa2017-03-17 04:26:22 -070018#include "webrtc/base/event.h"
19#include "webrtc/base/logging.h"
henrika714e5cd2017-04-20 08:03:11 -070020#include "webrtc/base/optional.h"
henrikae24991d2017-04-06 01:14:23 -070021#include "webrtc/base/race_checker.h"
henrika714e5cd2017-04-20 08:03:11 -070022#include "webrtc/base/safe_conversions.h"
henrikaf2f91fa2017-03-17 04:26:22 -070023#include "webrtc/base/scoped_ref_ptr.h"
henrikae24991d2017-04-06 01:14:23 -070024#include "webrtc/base/thread_annotations.h"
henrika714e5cd2017-04-20 08:03:11 -070025#include "webrtc/base/thread_checker.h"
26#include "webrtc/base/timeutils.h"
henrikaf2f91fa2017-03-17 04:26:22 -070027#include "webrtc/modules/audio_device/audio_device_impl.h"
28#include "webrtc/modules/audio_device/include/audio_device.h"
29#include "webrtc/modules/audio_device/include/mock_audio_transport.h"
30#include "webrtc/system_wrappers/include/sleep.h"
31#include "webrtc/test/gmock.h"
32#include "webrtc/test/gtest.h"
33
34using ::testing::_;
35using ::testing::AtLeast;
36using ::testing::Ge;
37using ::testing::Invoke;
38using ::testing::NiceMock;
39using ::testing::NotNull;
40
41namespace webrtc {
42namespace {
43
henrikae24991d2017-04-06 01:14:23 -070044// #define ENABLE_DEBUG_PRINTF
45#ifdef ENABLE_DEBUG_PRINTF
46#define PRINTD(...) fprintf(stderr, __VA_ARGS__);
47#else
48#define PRINTD(...) ((void)0)
49#endif
50#define PRINT(...) fprintf(stderr, __VA_ARGS__);
51
henrikaf2f91fa2017-03-17 04:26:22 -070052// Don't run these tests in combination with sanitizers.
53#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
54#define SKIP_TEST_IF_NOT(requirements_satisfied) \
55 do { \
56 if (!requirements_satisfied) { \
57 return; \
58 } \
59 } while (false)
60#else
61// Or if other audio-related requirements are not met.
62#define SKIP_TEST_IF_NOT(requirements_satisfied) \
63 do { \
64 return; \
65 } while (false)
66#endif
67
68// Number of callbacks (input or output) the tests waits for before we set
69// an event indicating that the test was OK.
henrikae24991d2017-04-06 01:14:23 -070070static constexpr size_t kNumCallbacks = 10;
henrikaf2f91fa2017-03-17 04:26:22 -070071// Max amount of time we wait for an event to be set while counting callbacks.
henrika714e5cd2017-04-20 08:03:11 -070072static constexpr size_t kTestTimeOutInMilliseconds = 10 * 1000;
henrikae24991d2017-04-06 01:14:23 -070073// Average number of audio callbacks per second assuming 10ms packet size.
74static constexpr size_t kNumCallbacksPerSecond = 100;
75// Run the full-duplex test during this time (unit is in seconds).
henrika714e5cd2017-04-20 08:03:11 -070076static constexpr size_t kFullDuplexTimeInSec = 5;
77// Length of round-trip latency measurements. Number of deteced impulses
78// shall be kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 1 since the
79// last transmitted pulse is not used.
80static constexpr size_t kMeasureLatencyTimeInSec = 10;
81// Sets the number of impulses per second in the latency test.
82static constexpr size_t kImpulseFrequencyInHz = 1;
83// Utilized in round-trip latency measurements to avoid capturing noise samples.
84static constexpr int kImpulseThreshold = 1000;
henrikaf2f91fa2017-03-17 04:26:22 -070085
86enum class TransportType {
87 kInvalid,
88 kPlay,
89 kRecord,
90 kPlayAndRecord,
91};
henrikae24991d2017-04-06 01:14:23 -070092
93// Interface for processing the audio stream. Real implementations can e.g.
94// run audio in loopback, read audio from a file or perform latency
95// measurements.
96class AudioStream {
97 public:
98 virtual void Write(rtc::ArrayView<const int16_t> source, size_t channels) = 0;
99 virtual void Read(rtc::ArrayView<int16_t> destination, size_t channels) = 0;
100
101 virtual ~AudioStream() = default;
102};
103
henrika714e5cd2017-04-20 08:03:11 -0700104// Converts index corresponding to position within a 10ms buffer into a
105// delay value in milliseconds.
106// Example: index=240, frames_per_10ms_buffer=480 => 5ms as output.
107int IndexToMilliseconds(size_t index, size_t frames_per_10ms_buffer) {
108 return rtc::checked_cast<int>(
109 10.0 * (static_cast<double>(index) / frames_per_10ms_buffer) + 0.5);
110}
111
henrikaf2f91fa2017-03-17 04:26:22 -0700112} // namespace
113
henrikae24991d2017-04-06 01:14:23 -0700114// Simple first in first out (FIFO) class that wraps a list of 16-bit audio
115// buffers of fixed size and allows Write and Read operations. The idea is to
116// store recorded audio buffers (using Write) and then read (using Read) these
117// stored buffers with as short delay as possible when the audio layer needs
118// data to play out. The number of buffers in the FIFO will stabilize under
119// normal conditions since there will be a balance between Write and Read calls.
120// The container is a std::list container and access is protected with a lock
121// since both sides (playout and recording) are driven by its own thread.
122// Note that, we know by design that the size of the audio buffer will not
123// change over time and that both sides will use the same size.
124class FifoAudioStream : public AudioStream {
125 public:
126 void Write(rtc::ArrayView<const int16_t> source, size_t channels) override {
127 EXPECT_EQ(channels, 1u);
128 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
129 const size_t size = [&] {
130 rtc::CritScope lock(&lock_);
131 fifo_.push_back(Buffer16(source.data(), source.size()));
132 return fifo_.size();
133 }();
134 if (size > max_size_) {
135 max_size_ = size;
136 }
137 // Add marker once per second to signal that audio is active.
138 if (write_count_++ % 100 == 0) {
139 PRINT(".");
140 }
141 written_elements_ += size;
142 }
143
144 void Read(rtc::ArrayView<int16_t> destination, size_t channels) override {
145 EXPECT_EQ(channels, 1u);
146 rtc::CritScope lock(&lock_);
147 if (fifo_.empty()) {
148 std::fill(destination.begin(), destination.end(), 0);
149 } else {
150 const Buffer16& buffer = fifo_.front();
151 RTC_CHECK_EQ(buffer.size(), destination.size());
152 std::copy(buffer.begin(), buffer.end(), destination.begin());
153 fifo_.pop_front();
154 }
155 }
156
157 size_t size() const {
158 rtc::CritScope lock(&lock_);
159 return fifo_.size();
160 }
161
162 size_t max_size() const {
163 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
164 return max_size_;
165 }
166
167 size_t average_size() const {
168 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
169 return 0.5 + static_cast<float>(written_elements_ / write_count_);
170 }
171
172 using Buffer16 = rtc::BufferT<int16_t>;
173
174 rtc::CriticalSection lock_;
175 rtc::RaceChecker race_checker_;
176
177 std::list<Buffer16> fifo_ GUARDED_BY(lock_);
178 size_t write_count_ GUARDED_BY(race_checker_) = 0;
179 size_t max_size_ GUARDED_BY(race_checker_) = 0;
180 size_t written_elements_ GUARDED_BY(race_checker_) = 0;
181};
182
henrika714e5cd2017-04-20 08:03:11 -0700183// Inserts periodic impulses and measures the latency between the time of
184// transmission and time of receiving the same impulse.
185class LatencyAudioStream : public AudioStream {
186 public:
187 LatencyAudioStream() {
188 // Delay thread checkers from being initialized until first callback from
189 // respective thread.
190 read_thread_checker_.DetachFromThread();
191 write_thread_checker_.DetachFromThread();
192 }
193
194 // Insert periodic impulses in first two samples of |destination|.
195 void Read(rtc::ArrayView<int16_t> destination, size_t channels) override {
196 RTC_DCHECK_RUN_ON(&read_thread_checker_);
197 EXPECT_EQ(channels, 1u);
198 if (read_count_ == 0) {
199 PRINT("[");
200 }
201 read_count_++;
202 std::fill(destination.begin(), destination.end(), 0);
203 if (read_count_ % (kNumCallbacksPerSecond / kImpulseFrequencyInHz) == 0) {
204 PRINT(".");
205 {
206 rtc::CritScope lock(&lock_);
207 if (!pulse_time_) {
208 pulse_time_ = rtc::Optional<int64_t>(rtc::TimeMillis());
209 }
210 }
211 constexpr int16_t impulse = std::numeric_limits<int16_t>::max();
212 std::fill_n(destination.begin(), 2, impulse);
213 }
214 }
215
216 // Detect received impulses in |source|, derive time between transmission and
217 // detection and add the calculated delay to list of latencies.
218 void Write(rtc::ArrayView<const int16_t> source, size_t channels) override {
219 EXPECT_EQ(channels, 1u);
220 RTC_DCHECK_RUN_ON(&write_thread_checker_);
221 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
222 rtc::CritScope lock(&lock_);
223 write_count_++;
224 if (!pulse_time_) {
225 // Avoid detection of new impulse response until a new impulse has
226 // been transmitted (sets |pulse_time_| to value larger than zero).
227 return;
228 }
229 // Find index (element position in vector) of the max element.
230 const size_t index_of_max =
231 std::max_element(source.begin(), source.end()) - source.begin();
232 // Derive time between transmitted pulse and received pulse if the level
233 // is high enough (removes noise).
234 const size_t max = source[index_of_max];
235 if (max > kImpulseThreshold) {
236 PRINTD("(%zu, %zu)", max, index_of_max);
237 int64_t now_time = rtc::TimeMillis();
238 int extra_delay = IndexToMilliseconds(index_of_max, source.size());
239 PRINTD("[%d]", rtc::checked_cast<int>(now_time - pulse_time_));
240 PRINTD("[%d]", extra_delay);
241 // Total latency is the difference between transmit time and detection
242 // tome plus the extra delay within the buffer in which we detected the
243 // received impulse. It is transmitted at sample 0 but can be received
244 // at sample N where N > 0. The term |extra_delay| accounts for N and it
245 // is a value between 0 and 10ms.
246 latencies_.push_back(now_time - *pulse_time_ + extra_delay);
247 pulse_time_.reset();
248 } else {
249 PRINTD("-");
250 }
251 }
252
253 size_t num_latency_values() const {
254 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
255 return latencies_.size();
256 }
257
258 int min_latency() const {
259 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
260 if (latencies_.empty())
261 return 0;
262 return *std::min_element(latencies_.begin(), latencies_.end());
263 }
264
265 int max_latency() const {
266 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
267 if (latencies_.empty())
268 return 0;
269 return *std::max_element(latencies_.begin(), latencies_.end());
270 }
271
272 int average_latency() const {
273 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
274 if (latencies_.empty())
275 return 0;
276 return 0.5 + static_cast<double>(
277 std::accumulate(latencies_.begin(), latencies_.end(), 0)) /
278 latencies_.size();
279 }
280
281 void PrintResults() const {
282 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
283 PRINT("] ");
284 for (auto it = latencies_.begin(); it != latencies_.end(); ++it) {
285 PRINTD("%d ", *it);
286 }
287 PRINT("\n");
288 PRINT("[..........] [min, max, avg]=[%d, %d, %d] ms\n", min_latency(),
289 max_latency(), average_latency());
290 }
291
292 rtc::CriticalSection lock_;
293 rtc::RaceChecker race_checker_;
294 rtc::ThreadChecker read_thread_checker_;
295 rtc::ThreadChecker write_thread_checker_;
296
297 rtc::Optional<int64_t> pulse_time_ GUARDED_BY(lock_);
298 std::vector<int> latencies_ GUARDED_BY(race_checker_);
299 size_t read_count_ ACCESS_ON(read_thread_checker_) = 0;
300 size_t write_count_ ACCESS_ON(write_thread_checker_) = 0;
301};
302
henrikaf2f91fa2017-03-17 04:26:22 -0700303// Mocks the AudioTransport object and proxies actions for the two callbacks
304// (RecordedDataIsAvailable and NeedMorePlayData) to different implementations
305// of AudioStreamInterface.
306class MockAudioTransport : public test::MockAudioTransport {
307 public:
308 explicit MockAudioTransport(TransportType type) : type_(type) {}
309 ~MockAudioTransport() {}
310
311 // Set default actions of the mock object. We are delegating to fake
312 // implementation where the number of callbacks is counted and an event
313 // is set after a certain number of callbacks. Audio parameters are also
314 // checked.
henrikae24991d2017-04-06 01:14:23 -0700315 void HandleCallbacks(rtc::Event* event,
316 AudioStream* audio_stream,
317 int num_callbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700318 event_ = event;
henrikae24991d2017-04-06 01:14:23 -0700319 audio_stream_ = audio_stream;
henrikaf2f91fa2017-03-17 04:26:22 -0700320 num_callbacks_ = num_callbacks;
321 if (play_mode()) {
322 ON_CALL(*this, NeedMorePlayData(_, _, _, _, _, _, _, _))
323 .WillByDefault(
324 Invoke(this, &MockAudioTransport::RealNeedMorePlayData));
325 }
326 if (rec_mode()) {
327 ON_CALL(*this, RecordedDataIsAvailable(_, _, _, _, _, _, _, _, _, _))
328 .WillByDefault(
329 Invoke(this, &MockAudioTransport::RealRecordedDataIsAvailable));
330 }
331 }
332
333 int32_t RealRecordedDataIsAvailable(const void* audio_buffer,
334 const size_t samples_per_channel,
335 const size_t bytes_per_frame,
336 const size_t channels,
337 const uint32_t sample_rate,
338 const uint32_t total_delay_ms,
339 const int32_t clock_drift,
340 const uint32_t current_mic_level,
341 const bool typing_status,
342 uint32_t& new_mic_level) {
343 EXPECT_TRUE(rec_mode()) << "No test is expecting these callbacks.";
344 LOG(INFO) << "+";
345 // Store audio parameters once in the first callback. For all other
346 // callbacks, verify that the provided audio parameters are maintained and
347 // that each callback corresponds to 10ms for any given sample rate.
348 if (!record_parameters_.is_complete()) {
349 record_parameters_.reset(sample_rate, channels, samples_per_channel);
350 } else {
351 EXPECT_EQ(samples_per_channel, record_parameters_.frames_per_buffer());
352 EXPECT_EQ(bytes_per_frame, record_parameters_.GetBytesPerFrame());
353 EXPECT_EQ(channels, record_parameters_.channels());
354 EXPECT_EQ(static_cast<int>(sample_rate),
355 record_parameters_.sample_rate());
356 EXPECT_EQ(samples_per_channel,
357 record_parameters_.frames_per_10ms_buffer());
358 }
359 rec_count_++;
henrikae24991d2017-04-06 01:14:23 -0700360 // Write audio data to audio stream object if one has been injected.
361 if (audio_stream_) {
362 audio_stream_->Write(
363 rtc::MakeArrayView(static_cast<const int16_t*>(audio_buffer),
364 samples_per_channel * channels),
365 channels);
366 }
henrikaf2f91fa2017-03-17 04:26:22 -0700367 // Signal the event after given amount of callbacks.
368 if (ReceivedEnoughCallbacks()) {
369 event_->Set();
370 }
371 return 0;
372 }
373
374 int32_t RealNeedMorePlayData(const size_t samples_per_channel,
375 const size_t bytes_per_frame,
376 const size_t channels,
377 const uint32_t sample_rate,
378 void* audio_buffer,
379 size_t& samples_per_channel_out,
380 int64_t* elapsed_time_ms,
381 int64_t* ntp_time_ms) {
382 EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
383 LOG(INFO) << "-";
384 // Store audio parameters once in the first callback. For all other
385 // callbacks, verify that the provided audio parameters are maintained and
386 // that each callback corresponds to 10ms for any given sample rate.
387 if (!playout_parameters_.is_complete()) {
388 playout_parameters_.reset(sample_rate, channels, samples_per_channel);
389 } else {
390 EXPECT_EQ(samples_per_channel, playout_parameters_.frames_per_buffer());
391 EXPECT_EQ(bytes_per_frame, playout_parameters_.GetBytesPerFrame());
392 EXPECT_EQ(channels, playout_parameters_.channels());
393 EXPECT_EQ(static_cast<int>(sample_rate),
394 playout_parameters_.sample_rate());
395 EXPECT_EQ(samples_per_channel,
396 playout_parameters_.frames_per_10ms_buffer());
397 }
398 play_count_++;
399 samples_per_channel_out = samples_per_channel;
henrikae24991d2017-04-06 01:14:23 -0700400 // Read audio data from audio stream object if one has been injected.
401 if (audio_stream_) {
402 audio_stream_->Read(
403 rtc::MakeArrayView(static_cast<int16_t*>(audio_buffer),
404 samples_per_channel * channels),
405 channels);
406 } else {
407 // Fill the audio buffer with zeros to avoid disturbing audio.
408 const size_t num_bytes = samples_per_channel * bytes_per_frame;
409 std::memset(audio_buffer, 0, num_bytes);
410 }
henrikaf2f91fa2017-03-17 04:26:22 -0700411 // Signal the event after given amount of callbacks.
412 if (ReceivedEnoughCallbacks()) {
413 event_->Set();
414 }
415 return 0;
416 }
417
418 bool ReceivedEnoughCallbacks() {
419 bool recording_done = false;
420 if (rec_mode()) {
421 recording_done = rec_count_ >= num_callbacks_;
422 } else {
423 recording_done = true;
424 }
425 bool playout_done = false;
426 if (play_mode()) {
427 playout_done = play_count_ >= num_callbacks_;
428 } else {
429 playout_done = true;
430 }
431 return recording_done && playout_done;
432 }
433
434 bool play_mode() const {
435 return type_ == TransportType::kPlay ||
436 type_ == TransportType::kPlayAndRecord;
437 }
438
439 bool rec_mode() const {
440 return type_ == TransportType::kRecord ||
441 type_ == TransportType::kPlayAndRecord;
442 }
443
444 private:
445 TransportType type_ = TransportType::kInvalid;
446 rtc::Event* event_ = nullptr;
henrikae24991d2017-04-06 01:14:23 -0700447 AudioStream* audio_stream_ = nullptr;
henrikaf2f91fa2017-03-17 04:26:22 -0700448 size_t num_callbacks_ = 0;
449 size_t play_count_ = 0;
450 size_t rec_count_ = 0;
451 AudioParameters playout_parameters_;
452 AudioParameters record_parameters_;
453};
454
455// AudioDeviceTest test fixture.
456class AudioDeviceTest : public ::testing::Test {
457 protected:
458 AudioDeviceTest() : event_(false, false) {
459#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
460 rtc::LogMessage::LogToDebug(rtc::LS_INFO);
461 // Add extra logging fields here if needed for debugging.
462 // rtc::LogMessage::LogTimestamps();
463 // rtc::LogMessage::LogThreads();
464 audio_device_ =
465 AudioDeviceModule::Create(0, AudioDeviceModule::kPlatformDefaultAudio);
466 EXPECT_NE(audio_device_.get(), nullptr);
467 AudioDeviceModule::AudioLayer audio_layer;
maxmorin33bf69a2017-03-23 04:06:53 -0700468 int got_platform_audio_layer =
469 audio_device_->ActiveAudioLayer(&audio_layer);
470 if (got_platform_audio_layer != 0 ||
471 audio_layer == AudioDeviceModule::kLinuxAlsaAudio) {
henrikaf2f91fa2017-03-17 04:26:22 -0700472 requirements_satisfied_ = false;
473 }
474 if (requirements_satisfied_) {
475 EXPECT_EQ(0, audio_device_->Init());
476 const int16_t num_playout_devices = audio_device_->PlayoutDevices();
477 const int16_t num_record_devices = audio_device_->RecordingDevices();
478 requirements_satisfied_ =
479 num_playout_devices > 0 && num_record_devices > 0;
480 }
481#else
482 requirements_satisfied_ = false;
483#endif
484 if (requirements_satisfied_) {
485 EXPECT_EQ(0, audio_device_->SetPlayoutDevice(0));
486 EXPECT_EQ(0, audio_device_->InitSpeaker());
487 EXPECT_EQ(0, audio_device_->SetRecordingDevice(0));
488 EXPECT_EQ(0, audio_device_->InitMicrophone());
489 EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
490 EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
henrika0238ba82017-03-28 04:38:29 -0700491 // Avoid asking for input stereo support and always record in mono
492 // since asking can cause issues in combination with remote desktop.
493 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
494 // details.
495 EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
henrikaf2f91fa2017-03-17 04:26:22 -0700496 EXPECT_EQ(0, audio_device_->SetAGC(false));
497 EXPECT_FALSE(audio_device_->AGC());
498 }
499 }
500
501 virtual ~AudioDeviceTest() {
502 if (audio_device_) {
503 EXPECT_EQ(0, audio_device_->Terminate());
504 }
505 }
506
507 bool requirements_satisfied() const { return requirements_satisfied_; }
508 rtc::Event* event() { return &event_; }
509
510 const rtc::scoped_refptr<AudioDeviceModule>& audio_device() const {
511 return audio_device_;
512 }
513
514 void StartPlayout() {
515 EXPECT_FALSE(audio_device()->Playing());
516 EXPECT_EQ(0, audio_device()->InitPlayout());
517 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
518 EXPECT_EQ(0, audio_device()->StartPlayout());
519 EXPECT_TRUE(audio_device()->Playing());
520 }
521
522 void StopPlayout() {
523 EXPECT_EQ(0, audio_device()->StopPlayout());
524 EXPECT_FALSE(audio_device()->Playing());
525 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
526 }
527
528 void StartRecording() {
529 EXPECT_FALSE(audio_device()->Recording());
530 EXPECT_EQ(0, audio_device()->InitRecording());
531 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
532 EXPECT_EQ(0, audio_device()->StartRecording());
533 EXPECT_TRUE(audio_device()->Recording());
534 }
535
536 void StopRecording() {
537 EXPECT_EQ(0, audio_device()->StopRecording());
538 EXPECT_FALSE(audio_device()->Recording());
539 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
540 }
541
542 private:
543 bool requirements_satisfied_ = true;
544 rtc::Event event_;
545 rtc::scoped_refptr<AudioDeviceModule> audio_device_;
546 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700547};
548
549// Uses the test fixture to create, initialize and destruct the ADM.
550TEST_F(AudioDeviceTest, ConstructDestruct) {}
551
552TEST_F(AudioDeviceTest, InitTerminate) {
553 SKIP_TEST_IF_NOT(requirements_satisfied());
554 // Initialization is part of the test fixture.
555 EXPECT_TRUE(audio_device()->Initialized());
556 EXPECT_EQ(0, audio_device()->Terminate());
557 EXPECT_FALSE(audio_device()->Initialized());
558}
559
560// Tests Start/Stop playout without any registered audio callback.
561TEST_F(AudioDeviceTest, StartStopPlayout) {
562 SKIP_TEST_IF_NOT(requirements_satisfied());
563 StartPlayout();
564 StopPlayout();
565 StartPlayout();
566 StopPlayout();
567}
568
569// Tests Start/Stop recording without any registered audio callback.
570TEST_F(AudioDeviceTest, StartStopRecording) {
571 SKIP_TEST_IF_NOT(requirements_satisfied());
572 StartRecording();
573 StopRecording();
574 StartRecording();
575 StopRecording();
576}
577
578// Start playout and verify that the native audio layer starts asking for real
579// audio samples to play out using the NeedMorePlayData() callback.
580// Note that we can't add expectations on audio parameters in EXPECT_CALL
581// since parameter are not provided in the each callback. We therefore test and
582// verify the parameters in the fake audio transport implementation instead.
583TEST_F(AudioDeviceTest, StartPlayoutVerifyCallbacks) {
584 SKIP_TEST_IF_NOT(requirements_satisfied());
585 MockAudioTransport mock(TransportType::kPlay);
henrikae24991d2017-04-06 01:14:23 -0700586 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700587 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
588 .Times(AtLeast(kNumCallbacks));
589 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
590 StartPlayout();
591 event()->Wait(kTestTimeOutInMilliseconds);
592 StopPlayout();
593}
594
595// Start recording and verify that the native audio layer starts providing real
596// audio samples using the RecordedDataIsAvailable() callback.
597TEST_F(AudioDeviceTest, StartRecordingVerifyCallbacks) {
598 SKIP_TEST_IF_NOT(requirements_satisfied());
599 MockAudioTransport mock(TransportType::kRecord);
henrikae24991d2017-04-06 01:14:23 -0700600 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700601 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
602 false, _))
603 .Times(AtLeast(kNumCallbacks));
604 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
605 StartRecording();
606 event()->Wait(kTestTimeOutInMilliseconds);
607 StopRecording();
608}
609
610// Start playout and recording (full-duplex audio) and verify that audio is
611// active in both directions.
612TEST_F(AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
613 SKIP_TEST_IF_NOT(requirements_satisfied());
614 MockAudioTransport mock(TransportType::kPlayAndRecord);
henrikae24991d2017-04-06 01:14:23 -0700615 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700616 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
617 .Times(AtLeast(kNumCallbacks));
618 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
619 false, _))
620 .Times(AtLeast(kNumCallbacks));
621 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
622 StartPlayout();
623 StartRecording();
624 event()->Wait(kTestTimeOutInMilliseconds);
625 StopRecording();
626 StopPlayout();
627}
628
henrikae24991d2017-04-06 01:14:23 -0700629// Start playout and recording and store recorded data in an intermediate FIFO
630// buffer from which the playout side then reads its samples in the same order
631// as they were stored. Under ideal circumstances, a callback sequence would
632// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
633// means 'packet played'. Under such conditions, the FIFO would contain max 1,
634// with an average somewhere in (0,1) depending on how long the packets are
635// buffered. However, under more realistic conditions, the size
636// of the FIFO will vary more due to an unbalance between the two sides.
637// This test tries to verify that the device maintains a balanced callback-
638// sequence by running in loopback for a few seconds while measuring the size
639// (max and average) of the FIFO. The size of the FIFO is increased by the
640// recording side and decreased by the playout side.
641TEST_F(AudioDeviceTest, RunPlayoutAndRecordingInFullDuplex) {
642 SKIP_TEST_IF_NOT(requirements_satisfied());
643 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
644 FifoAudioStream audio_stream;
645 mock.HandleCallbacks(event(), &audio_stream,
646 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
647 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
648 // Run both sides in mono to make the loopback packet handling less complex.
649 // The test works for stereo as well; the only requirement is that both sides
650 // use the same configuration.
651 EXPECT_EQ(0, audio_device()->SetStereoPlayout(false));
652 EXPECT_EQ(0, audio_device()->SetStereoRecording(false));
653 StartPlayout();
654 StartRecording();
henrika714e5cd2017-04-20 08:03:11 -0700655 event()->Wait(static_cast<int>(
656 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec)));
henrikae24991d2017-04-06 01:14:23 -0700657 StopRecording();
658 StopPlayout();
659 // This thresholds is set rather high to accommodate differences in hardware
660 // in several devices. The main idea is to capture cases where a very large
661 // latency is built up.
662 EXPECT_LE(audio_stream.average_size(), 5u);
663 PRINT("\n");
664}
665
henrika714e5cd2017-04-20 08:03:11 -0700666// Measures loopback latency and reports the min, max and average values for
667// a full duplex audio session.
668// The latency is measured like so:
669// - Insert impulses periodically on the output side.
670// - Detect the impulses on the input side.
671// - Measure the time difference between the transmit time and receive time.
672// - Store time differences in a vector and calculate min, max and average.
673// This test needs the '--gtest_also_run_disabled_tests' flag to run and also
674// some sort of audio feedback loop. E.g. a headset where the mic is placed
675// close to the speaker to ensure highest possible echo. It is also recommended
676// to run the test at highest possible output volume.
677TEST_F(AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
678 SKIP_TEST_IF_NOT(requirements_satisfied());
679 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
680 LatencyAudioStream audio_stream;
681 mock.HandleCallbacks(event(), &audio_stream,
682 kMeasureLatencyTimeInSec * kNumCallbacksPerSecond);
683 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
684 EXPECT_EQ(0, audio_device()->SetStereoPlayout(false));
685 EXPECT_EQ(0, audio_device()->SetStereoRecording(false));
686 StartPlayout();
687 StartRecording();
688 event()->Wait(static_cast<int>(
689 std::max(kTestTimeOutInMilliseconds, 1000 * kMeasureLatencyTimeInSec)));
690 StopRecording();
691 StopPlayout();
692 // Verify that the correct number of transmitted impulses are detected.
693 EXPECT_EQ(audio_stream.num_latency_values(),
694 static_cast<size_t>(
695 kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 1));
696 // Print out min, max and average delay values for debugging purposes.
697 audio_stream.PrintResults();
698}
699
henrikaf2f91fa2017-03-17 04:26:22 -0700700} // namespace webrtc