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