blob: b42a1c7fbc2f20f9aa922e4dbcd52801918df0d5 [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"
24#include "rtc_base/race_checker.h"
25#include "rtc_base/safe_conversions.h"
26#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:
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
danilchap56359be2017-09-07 07:53:45 -0700176 std::list<Buffer16> fifo_ RTC_GUARDED_BY(lock_);
177 size_t write_count_ RTC_GUARDED_BY(race_checker_) = 0;
178 size_t max_size_ RTC_GUARDED_BY(race_checker_) = 0;
179 size_t written_elements_ RTC_GUARDED_BY(race_checker_) = 0;
henrikae24991d2017-04-06 01:14:23 -0700180};
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
danilchap56359be2017-09-07 07:53:45 -0700296 rtc::Optional<int64_t> pulse_time_ RTC_GUARDED_BY(lock_);
297 std::vector<int> latencies_ RTC_GUARDED_BY(race_checker_);
298 size_t read_count_ RTC_ACCESS_ON(read_thread_checker_) = 0;
299 size_t write_count_ RTC_ACCESS_ON(write_thread_checker_) = 0;
henrika714e5cd2017-04-20 08:03:11 -0700300};
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.";
Mirko Bonadei675513b2017-11-09 11:09:25 +0100343 RTC_LOG(INFO) << "+";
henrikaf2f91fa2017-03-17 04:26:22 -0700344 // 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.";
Mirko Bonadei675513b2017-11-09 11:09:25 +0100382 RTC_LOG(INFO) << "-";
henrikaf2f91fa2017-03-17 04:26:22 -0700383 // 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_ =
henrika616e3132017-11-13 12:47:59 +0100464 AudioDeviceModule::Create(AudioDeviceModule::kPlatformDefaultAudio);
henrikaf2f91fa2017-03-17 04:26:22 -0700465 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);
henrika919dc2e2017-10-12 14:24:55 +0200469 // First, ensure that a valid audio layer can be activated.
470 if (got_platform_audio_layer != 0) {
henrikaf2f91fa2017-03-17 04:26:22 -0700471 requirements_satisfied_ = false;
472 }
henrika919dc2e2017-10-12 14:24:55 +0200473 // Next, verify that the ADM can be initialized.
henrikaf2f91fa2017-03-17 04:26:22 -0700474 if (requirements_satisfied_) {
henrika919dc2e2017-10-12 14:24:55 +0200475 requirements_satisfied_ = (audio_device_->Init() == 0);
476 }
477 // Finally, ensure that at least one valid device exists in each direction.
478 if (requirements_satisfied_) {
henrikaf2f91fa2017-03-17 04:26:22 -0700479 const int16_t num_playout_devices = audio_device_->PlayoutDevices();
480 const int16_t num_record_devices = audio_device_->RecordingDevices();
481 requirements_satisfied_ =
482 num_playout_devices > 0 && num_record_devices > 0;
483 }
484#else
485 requirements_satisfied_ = false;
486#endif
487 if (requirements_satisfied_) {
488 EXPECT_EQ(0, audio_device_->SetPlayoutDevice(0));
489 EXPECT_EQ(0, audio_device_->InitSpeaker());
490 EXPECT_EQ(0, audio_device_->SetRecordingDevice(0));
491 EXPECT_EQ(0, audio_device_->InitMicrophone());
492 EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
493 EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
henrika0238ba82017-03-28 04:38:29 -0700494 // Avoid asking for input stereo support and always record in mono
495 // since asking can cause issues in combination with remote desktop.
496 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
497 // details.
498 EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
henrikaf2f91fa2017-03-17 04:26:22 -0700499 EXPECT_EQ(0, audio_device_->SetAGC(false));
500 EXPECT_FALSE(audio_device_->AGC());
501 }
502 }
503
504 virtual ~AudioDeviceTest() {
505 if (audio_device_) {
506 EXPECT_EQ(0, audio_device_->Terminate());
507 }
508 }
509
510 bool requirements_satisfied() const { return requirements_satisfied_; }
511 rtc::Event* event() { return &event_; }
512
513 const rtc::scoped_refptr<AudioDeviceModule>& audio_device() const {
514 return audio_device_;
515 }
516
517 void StartPlayout() {
518 EXPECT_FALSE(audio_device()->Playing());
519 EXPECT_EQ(0, audio_device()->InitPlayout());
520 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
521 EXPECT_EQ(0, audio_device()->StartPlayout());
522 EXPECT_TRUE(audio_device()->Playing());
523 }
524
525 void StopPlayout() {
526 EXPECT_EQ(0, audio_device()->StopPlayout());
527 EXPECT_FALSE(audio_device()->Playing());
528 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
529 }
530
531 void StartRecording() {
532 EXPECT_FALSE(audio_device()->Recording());
533 EXPECT_EQ(0, audio_device()->InitRecording());
534 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
535 EXPECT_EQ(0, audio_device()->StartRecording());
536 EXPECT_TRUE(audio_device()->Recording());
537 }
538
539 void StopRecording() {
540 EXPECT_EQ(0, audio_device()->StopRecording());
541 EXPECT_FALSE(audio_device()->Recording());
542 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
543 }
544
545 private:
546 bool requirements_satisfied_ = true;
547 rtc::Event event_;
548 rtc::scoped_refptr<AudioDeviceModule> audio_device_;
549 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700550};
551
552// Uses the test fixture to create, initialize and destruct the ADM.
553TEST_F(AudioDeviceTest, ConstructDestruct) {}
554
555TEST_F(AudioDeviceTest, InitTerminate) {
556 SKIP_TEST_IF_NOT(requirements_satisfied());
557 // Initialization is part of the test fixture.
558 EXPECT_TRUE(audio_device()->Initialized());
559 EXPECT_EQ(0, audio_device()->Terminate());
560 EXPECT_FALSE(audio_device()->Initialized());
561}
562
563// Tests Start/Stop playout without any registered audio callback.
564TEST_F(AudioDeviceTest, StartStopPlayout) {
565 SKIP_TEST_IF_NOT(requirements_satisfied());
566 StartPlayout();
567 StopPlayout();
568 StartPlayout();
569 StopPlayout();
570}
571
572// Tests Start/Stop recording without any registered audio callback.
573TEST_F(AudioDeviceTest, StartStopRecording) {
574 SKIP_TEST_IF_NOT(requirements_satisfied());
575 StartRecording();
576 StopRecording();
577 StartRecording();
578 StopRecording();
579}
580
henrika6b3e1a22017-09-25 16:34:30 +0200581// Tests Init/Stop/Init recording without any registered audio callback.
582// See https://bugs.chromium.org/p/webrtc/issues/detail?id=8041 for details
583// on why this test is useful.
584TEST_F(AudioDeviceTest, InitStopInitRecording) {
585 SKIP_TEST_IF_NOT(requirements_satisfied());
586 EXPECT_EQ(0, audio_device()->InitRecording());
587 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
588 StopRecording();
589 EXPECT_EQ(0, audio_device()->InitRecording());
590 StopRecording();
591}
592
593// Tests Init/Stop/Init recording while playout is active.
594TEST_F(AudioDeviceTest, InitStopInitRecordingWhilePlaying) {
595 SKIP_TEST_IF_NOT(requirements_satisfied());
596 StartPlayout();
597 EXPECT_EQ(0, audio_device()->InitRecording());
598 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
599 StopRecording();
600 EXPECT_EQ(0, audio_device()->InitRecording());
601 StopRecording();
602 StopPlayout();
603}
604
605// Tests Init/Stop/Init playout without any registered audio callback.
606TEST_F(AudioDeviceTest, InitStopInitPlayout) {
607 SKIP_TEST_IF_NOT(requirements_satisfied());
608 EXPECT_EQ(0, audio_device()->InitPlayout());
609 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
610 StopPlayout();
611 EXPECT_EQ(0, audio_device()->InitPlayout());
612 StopPlayout();
613}
614
615// Tests Init/Stop/Init playout while recording is active.
616TEST_F(AudioDeviceTest, InitStopInitPlayoutWhileRecording) {
617 SKIP_TEST_IF_NOT(requirements_satisfied());
618 StartRecording();
619 EXPECT_EQ(0, audio_device()->InitPlayout());
620 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
621 StopPlayout();
622 EXPECT_EQ(0, audio_device()->InitPlayout());
623 StopPlayout();
624 StopRecording();
625}
626
henrikaf2f91fa2017-03-17 04:26:22 -0700627// Start playout and verify that the native audio layer starts asking for real
628// audio samples to play out using the NeedMorePlayData() callback.
629// Note that we can't add expectations on audio parameters in EXPECT_CALL
630// since parameter are not provided in the each callback. We therefore test and
631// verify the parameters in the fake audio transport implementation instead.
632TEST_F(AudioDeviceTest, StartPlayoutVerifyCallbacks) {
633 SKIP_TEST_IF_NOT(requirements_satisfied());
634 MockAudioTransport mock(TransportType::kPlay);
henrikae24991d2017-04-06 01:14:23 -0700635 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700636 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
637 .Times(AtLeast(kNumCallbacks));
638 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
639 StartPlayout();
640 event()->Wait(kTestTimeOutInMilliseconds);
641 StopPlayout();
642}
643
644// Start recording and verify that the native audio layer starts providing real
645// audio samples using the RecordedDataIsAvailable() callback.
646TEST_F(AudioDeviceTest, StartRecordingVerifyCallbacks) {
647 SKIP_TEST_IF_NOT(requirements_satisfied());
648 MockAudioTransport mock(TransportType::kRecord);
henrikae24991d2017-04-06 01:14:23 -0700649 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700650 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
651 false, _))
652 .Times(AtLeast(kNumCallbacks));
653 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
654 StartRecording();
655 event()->Wait(kTestTimeOutInMilliseconds);
656 StopRecording();
657}
658
659// Start playout and recording (full-duplex audio) and verify that audio is
660// active in both directions.
661TEST_F(AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
662 SKIP_TEST_IF_NOT(requirements_satisfied());
663 MockAudioTransport mock(TransportType::kPlayAndRecord);
henrikae24991d2017-04-06 01:14:23 -0700664 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700665 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
666 .Times(AtLeast(kNumCallbacks));
667 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
668 false, _))
669 .Times(AtLeast(kNumCallbacks));
670 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
671 StartPlayout();
672 StartRecording();
673 event()->Wait(kTestTimeOutInMilliseconds);
674 StopRecording();
675 StopPlayout();
676}
677
henrikae24991d2017-04-06 01:14:23 -0700678// Start playout and recording and store recorded data in an intermediate FIFO
679// buffer from which the playout side then reads its samples in the same order
680// as they were stored. Under ideal circumstances, a callback sequence would
681// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
682// means 'packet played'. Under such conditions, the FIFO would contain max 1,
683// with an average somewhere in (0,1) depending on how long the packets are
684// buffered. However, under more realistic conditions, the size
685// of the FIFO will vary more due to an unbalance between the two sides.
686// This test tries to verify that the device maintains a balanced callback-
687// sequence by running in loopback for a few seconds while measuring the size
688// (max and average) of the FIFO. The size of the FIFO is increased by the
689// recording side and decreased by the playout side.
690TEST_F(AudioDeviceTest, RunPlayoutAndRecordingInFullDuplex) {
691 SKIP_TEST_IF_NOT(requirements_satisfied());
692 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
693 FifoAudioStream audio_stream;
694 mock.HandleCallbacks(event(), &audio_stream,
695 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
696 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
697 // Run both sides in mono to make the loopback packet handling less complex.
698 // The test works for stereo as well; the only requirement is that both sides
699 // use the same configuration.
700 EXPECT_EQ(0, audio_device()->SetStereoPlayout(false));
701 EXPECT_EQ(0, audio_device()->SetStereoRecording(false));
702 StartPlayout();
703 StartRecording();
henrika714e5cd2017-04-20 08:03:11 -0700704 event()->Wait(static_cast<int>(
705 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec)));
henrikae24991d2017-04-06 01:14:23 -0700706 StopRecording();
707 StopPlayout();
708 // This thresholds is set rather high to accommodate differences in hardware
709 // in several devices. The main idea is to capture cases where a very large
henrikab6ca7212017-10-06 12:47:52 +0200710 // latency is built up. See http://bugs.webrtc.org/7744 for examples on
711 // bots where relatively large average latencies can happen.
712 EXPECT_LE(audio_stream.average_size(), 25u);
henrikae24991d2017-04-06 01:14:23 -0700713 PRINT("\n");
714}
715
henrika714e5cd2017-04-20 08:03:11 -0700716// Measures loopback latency and reports the min, max and average values for
717// a full duplex audio session.
718// The latency is measured like so:
719// - Insert impulses periodically on the output side.
720// - Detect the impulses on the input side.
721// - Measure the time difference between the transmit time and receive time.
722// - Store time differences in a vector and calculate min, max and average.
723// This test needs the '--gtest_also_run_disabled_tests' flag to run and also
724// some sort of audio feedback loop. E.g. a headset where the mic is placed
725// close to the speaker to ensure highest possible echo. It is also recommended
726// to run the test at highest possible output volume.
727TEST_F(AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
728 SKIP_TEST_IF_NOT(requirements_satisfied());
729 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
730 LatencyAudioStream audio_stream;
731 mock.HandleCallbacks(event(), &audio_stream,
732 kMeasureLatencyTimeInSec * kNumCallbacksPerSecond);
733 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
734 EXPECT_EQ(0, audio_device()->SetStereoPlayout(false));
735 EXPECT_EQ(0, audio_device()->SetStereoRecording(false));
736 StartPlayout();
737 StartRecording();
738 event()->Wait(static_cast<int>(
739 std::max(kTestTimeOutInMilliseconds, 1000 * kMeasureLatencyTimeInSec)));
740 StopRecording();
741 StopPlayout();
742 // Verify that the correct number of transmitted impulses are detected.
743 EXPECT_EQ(audio_stream.num_latency_values(),
744 static_cast<size_t>(
745 kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 1));
746 // Print out min, max and average delay values for debugging purposes.
747 audio_stream.PrintResults();
748}
749
henrikaf2f91fa2017-03-17 04:26:22 -0700750} // namespace webrtc