blob: 5ba5461fad11271e38016df808a6f7e1e6d9de7a [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>
henrikaec9c7452018-06-08 16:10:03 +020013#include <memory>
henrika714e5cd2017-04-20 08:03:11 -070014#include <numeric>
henrikaf2f91fa2017-03-17 04:26:22 -070015
Danil Chapovalov196100e2018-06-21 10:17:24 +020016#include "absl/types/optional.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "api/array_view.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "modules/audio_device/audio_device_impl.h"
19#include "modules/audio_device/include/audio_device.h"
20#include "modules/audio_device/include/mock_audio_transport.h"
21#include "rtc_base/buffer.h"
22#include "rtc_base/criticalsection.h"
23#include "rtc_base/event.h"
24#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010025#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "rtc_base/race_checker.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/scoped_ref_ptr.h"
28#include "rtc_base/thread_annotations.h"
29#include "rtc_base/thread_checker.h"
30#include "rtc_base/timeutils.h"
henrika5b6afc02018-09-05 14:34:40 +020031#include "system_wrappers/include/sleep.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "test/gmock.h"
33#include "test/gtest.h"
henrikaec9c7452018-06-08 16:10:03 +020034#ifdef WEBRTC_WIN
35#include "modules/audio_device/include/audio_device_factory.h"
36#include "modules/audio_device/win/core_audio_utility_win.h"
37#endif
henrikaf2f91fa2017-03-17 04:26:22 -070038
39using ::testing::_;
40using ::testing::AtLeast;
41using ::testing::Ge;
42using ::testing::Invoke;
43using ::testing::NiceMock;
44using ::testing::NotNull;
henrika5b6afc02018-09-05 14:34:40 +020045using ::testing::Mock;
henrikaf2f91fa2017-03-17 04:26:22 -070046
47namespace webrtc {
48namespace {
49
henrika5773ad32018-09-21 14:53:10 +020050// Using a #define for AUDIO_DEVICE since we will call *different* versions of
51// the ADM functions, depending on the ID type.
52#if defined(WEBRTC_WIN)
53#define AUDIO_DEVICE_ID (AudioDeviceModule::WindowsDeviceType::kDefaultDevice)
54#else
55#define AUDIO_DEVICE_ID (0u)
56#endif // defined(WEBRTC_WIN)
57
henrikae24991d2017-04-06 01:14:23 -070058// #define ENABLE_DEBUG_PRINTF
59#ifdef ENABLE_DEBUG_PRINTF
60#define PRINTD(...) fprintf(stderr, __VA_ARGS__);
61#else
62#define PRINTD(...) ((void)0)
63#endif
64#define PRINT(...) fprintf(stderr, __VA_ARGS__);
65
henrikaf2f91fa2017-03-17 04:26:22 -070066// Don't run these tests in combination with sanitizers.
67#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
68#define SKIP_TEST_IF_NOT(requirements_satisfied) \
69 do { \
70 if (!requirements_satisfied) { \
71 return; \
72 } \
73 } while (false)
74#else
75// Or if other audio-related requirements are not met.
76#define SKIP_TEST_IF_NOT(requirements_satisfied) \
77 do { \
78 return; \
79 } while (false)
80#endif
81
82// Number of callbacks (input or output) the tests waits for before we set
83// an event indicating that the test was OK.
henrikae24991d2017-04-06 01:14:23 -070084static constexpr size_t kNumCallbacks = 10;
henrikaf2f91fa2017-03-17 04:26:22 -070085// Max amount of time we wait for an event to be set while counting callbacks.
henrika714e5cd2017-04-20 08:03:11 -070086static constexpr size_t kTestTimeOutInMilliseconds = 10 * 1000;
henrikae24991d2017-04-06 01:14:23 -070087// Average number of audio callbacks per second assuming 10ms packet size.
88static constexpr size_t kNumCallbacksPerSecond = 100;
89// Run the full-duplex test during this time (unit is in seconds).
henrika714e5cd2017-04-20 08:03:11 -070090static constexpr size_t kFullDuplexTimeInSec = 5;
91// Length of round-trip latency measurements. Number of deteced impulses
92// shall be kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 1 since the
93// last transmitted pulse is not used.
94static constexpr size_t kMeasureLatencyTimeInSec = 10;
95// Sets the number of impulses per second in the latency test.
96static constexpr size_t kImpulseFrequencyInHz = 1;
97// Utilized in round-trip latency measurements to avoid capturing noise samples.
98static constexpr int kImpulseThreshold = 1000;
henrikaf2f91fa2017-03-17 04:26:22 -070099
100enum class TransportType {
101 kInvalid,
102 kPlay,
103 kRecord,
104 kPlayAndRecord,
105};
henrikae24991d2017-04-06 01:14:23 -0700106
107// Interface for processing the audio stream. Real implementations can e.g.
108// run audio in loopback, read audio from a file or perform latency
109// measurements.
110class AudioStream {
111 public:
henrikaeb98c722018-03-20 12:54:07 +0100112 virtual void Write(rtc::ArrayView<const int16_t> source) = 0;
113 virtual void Read(rtc::ArrayView<int16_t> destination) = 0;
henrikae24991d2017-04-06 01:14:23 -0700114
115 virtual ~AudioStream() = default;
116};
117
henrika714e5cd2017-04-20 08:03:11 -0700118// Converts index corresponding to position within a 10ms buffer into a
119// delay value in milliseconds.
120// Example: index=240, frames_per_10ms_buffer=480 => 5ms as output.
121int IndexToMilliseconds(size_t index, size_t frames_per_10ms_buffer) {
122 return rtc::checked_cast<int>(
123 10.0 * (static_cast<double>(index) / frames_per_10ms_buffer) + 0.5);
124}
125
henrikaf2f91fa2017-03-17 04:26:22 -0700126} // namespace
127
henrikae24991d2017-04-06 01:14:23 -0700128// Simple first in first out (FIFO) class that wraps a list of 16-bit audio
129// buffers of fixed size and allows Write and Read operations. The idea is to
130// store recorded audio buffers (using Write) and then read (using Read) these
131// stored buffers with as short delay as possible when the audio layer needs
132// data to play out. The number of buffers in the FIFO will stabilize under
133// normal conditions since there will be a balance between Write and Read calls.
134// The container is a std::list container and access is protected with a lock
135// since both sides (playout and recording) are driven by its own thread.
136// Note that, we know by design that the size of the audio buffer will not
henrikac7d93582018-09-14 15:37:34 +0200137// change over time and that both sides will in most cases use the same size.
henrikae24991d2017-04-06 01:14:23 -0700138class FifoAudioStream : public AudioStream {
139 public:
henrikaeb98c722018-03-20 12:54:07 +0100140 void Write(rtc::ArrayView<const int16_t> source) override {
henrikae24991d2017-04-06 01:14:23 -0700141 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
142 const size_t size = [&] {
143 rtc::CritScope lock(&lock_);
144 fifo_.push_back(Buffer16(source.data(), source.size()));
145 return fifo_.size();
146 }();
147 if (size > max_size_) {
148 max_size_ = size;
149 }
150 // Add marker once per second to signal that audio is active.
151 if (write_count_++ % 100 == 0) {
152 PRINT(".");
153 }
154 written_elements_ += size;
155 }
156
henrikaeb98c722018-03-20 12:54:07 +0100157 void Read(rtc::ArrayView<int16_t> destination) override {
henrikae24991d2017-04-06 01:14:23 -0700158 rtc::CritScope lock(&lock_);
159 if (fifo_.empty()) {
160 std::fill(destination.begin(), destination.end(), 0);
161 } else {
162 const Buffer16& buffer = fifo_.front();
henrikac7d93582018-09-14 15:37:34 +0200163 if (buffer.size() == destination.size()) {
164 // Default case where input and output uses same sample rate and
165 // channel configuration. No conversion is needed.
166 std::copy(buffer.begin(), buffer.end(), destination.begin());
167 } else if (destination.size() == 2 * buffer.size()) {
168 // Recorded input signal in |buffer| is in mono. Do channel upmix to
169 // match stereo output (1 -> 2).
170 for (size_t i = 0; i < buffer.size(); ++i) {
171 destination[2 * i] = buffer[i];
172 destination[2 * i + 1] = buffer[i];
173 }
174 } else if (buffer.size() == 2 * destination.size()) {
175 // Recorded input signal in |buffer| is in stereo. Do channel downmix
176 // to match mono output (2 -> 1).
177 for (size_t i = 0; i < destination.size(); ++i) {
178 destination[i] =
179 (static_cast<int32_t>(buffer[2 * i]) + buffer[2 * i + 1]) / 2;
180 }
181 } else {
182 RTC_NOTREACHED() << "Required conversion is not support";
183 }
henrikae24991d2017-04-06 01:14:23 -0700184 fifo_.pop_front();
185 }
186 }
187
188 size_t size() const {
189 rtc::CritScope lock(&lock_);
190 return fifo_.size();
191 }
192
193 size_t max_size() const {
194 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
195 return max_size_;
196 }
197
198 size_t average_size() const {
199 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
200 return 0.5 + static_cast<float>(written_elements_ / write_count_);
201 }
202
203 using Buffer16 = rtc::BufferT<int16_t>;
204
205 rtc::CriticalSection lock_;
206 rtc::RaceChecker race_checker_;
207
danilchap56359be2017-09-07 07:53:45 -0700208 std::list<Buffer16> fifo_ RTC_GUARDED_BY(lock_);
209 size_t write_count_ RTC_GUARDED_BY(race_checker_) = 0;
210 size_t max_size_ RTC_GUARDED_BY(race_checker_) = 0;
211 size_t written_elements_ RTC_GUARDED_BY(race_checker_) = 0;
henrikae24991d2017-04-06 01:14:23 -0700212};
213
henrika714e5cd2017-04-20 08:03:11 -0700214// Inserts periodic impulses and measures the latency between the time of
215// transmission and time of receiving the same impulse.
216class LatencyAudioStream : public AudioStream {
217 public:
218 LatencyAudioStream() {
219 // Delay thread checkers from being initialized until first callback from
220 // respective thread.
221 read_thread_checker_.DetachFromThread();
222 write_thread_checker_.DetachFromThread();
223 }
224
225 // Insert periodic impulses in first two samples of |destination|.
henrikaeb98c722018-03-20 12:54:07 +0100226 void Read(rtc::ArrayView<int16_t> destination) override {
henrika714e5cd2017-04-20 08:03:11 -0700227 RTC_DCHECK_RUN_ON(&read_thread_checker_);
henrika714e5cd2017-04-20 08:03:11 -0700228 if (read_count_ == 0) {
229 PRINT("[");
230 }
231 read_count_++;
232 std::fill(destination.begin(), destination.end(), 0);
233 if (read_count_ % (kNumCallbacksPerSecond / kImpulseFrequencyInHz) == 0) {
234 PRINT(".");
235 {
236 rtc::CritScope lock(&lock_);
237 if (!pulse_time_) {
Oskar Sundbom6ad9f262017-11-16 10:53:39 +0100238 pulse_time_ = rtc::TimeMillis();
henrika714e5cd2017-04-20 08:03:11 -0700239 }
240 }
241 constexpr int16_t impulse = std::numeric_limits<int16_t>::max();
242 std::fill_n(destination.begin(), 2, impulse);
243 }
244 }
245
246 // Detect received impulses in |source|, derive time between transmission and
247 // detection and add the calculated delay to list of latencies.
henrikaeb98c722018-03-20 12:54:07 +0100248 void Write(rtc::ArrayView<const int16_t> source) override {
henrika714e5cd2017-04-20 08:03:11 -0700249 RTC_DCHECK_RUN_ON(&write_thread_checker_);
250 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
251 rtc::CritScope lock(&lock_);
252 write_count_++;
253 if (!pulse_time_) {
254 // Avoid detection of new impulse response until a new impulse has
255 // been transmitted (sets |pulse_time_| to value larger than zero).
256 return;
257 }
258 // Find index (element position in vector) of the max element.
259 const size_t index_of_max =
260 std::max_element(source.begin(), source.end()) - source.begin();
261 // Derive time between transmitted pulse and received pulse if the level
262 // is high enough (removes noise).
263 const size_t max = source[index_of_max];
264 if (max > kImpulseThreshold) {
265 PRINTD("(%zu, %zu)", max, index_of_max);
266 int64_t now_time = rtc::TimeMillis();
267 int extra_delay = IndexToMilliseconds(index_of_max, source.size());
268 PRINTD("[%d]", rtc::checked_cast<int>(now_time - pulse_time_));
269 PRINTD("[%d]", extra_delay);
270 // Total latency is the difference between transmit time and detection
271 // tome plus the extra delay within the buffer in which we detected the
272 // received impulse. It is transmitted at sample 0 but can be received
273 // at sample N where N > 0. The term |extra_delay| accounts for N and it
274 // is a value between 0 and 10ms.
275 latencies_.push_back(now_time - *pulse_time_ + extra_delay);
276 pulse_time_.reset();
277 } else {
278 PRINTD("-");
279 }
280 }
281
282 size_t num_latency_values() const {
283 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
284 return latencies_.size();
285 }
286
287 int min_latency() const {
288 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
289 if (latencies_.empty())
290 return 0;
291 return *std::min_element(latencies_.begin(), latencies_.end());
292 }
293
294 int max_latency() const {
295 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
296 if (latencies_.empty())
297 return 0;
298 return *std::max_element(latencies_.begin(), latencies_.end());
299 }
300
301 int average_latency() const {
302 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
303 if (latencies_.empty())
304 return 0;
305 return 0.5 + static_cast<double>(
306 std::accumulate(latencies_.begin(), latencies_.end(), 0)) /
307 latencies_.size();
308 }
309
310 void PrintResults() const {
311 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
312 PRINT("] ");
313 for (auto it = latencies_.begin(); it != latencies_.end(); ++it) {
314 PRINTD("%d ", *it);
315 }
316 PRINT("\n");
317 PRINT("[..........] [min, max, avg]=[%d, %d, %d] ms\n", min_latency(),
318 max_latency(), average_latency());
319 }
320
321 rtc::CriticalSection lock_;
322 rtc::RaceChecker race_checker_;
323 rtc::ThreadChecker read_thread_checker_;
324 rtc::ThreadChecker write_thread_checker_;
325
Danil Chapovalov196100e2018-06-21 10:17:24 +0200326 absl::optional<int64_t> pulse_time_ RTC_GUARDED_BY(lock_);
danilchap56359be2017-09-07 07:53:45 -0700327 std::vector<int> latencies_ RTC_GUARDED_BY(race_checker_);
Niels Möller1e062892018-02-07 10:18:32 +0100328 size_t read_count_ RTC_GUARDED_BY(read_thread_checker_) = 0;
329 size_t write_count_ RTC_GUARDED_BY(write_thread_checker_) = 0;
henrika714e5cd2017-04-20 08:03:11 -0700330};
331
henrikaf2f91fa2017-03-17 04:26:22 -0700332// Mocks the AudioTransport object and proxies actions for the two callbacks
333// (RecordedDataIsAvailable and NeedMorePlayData) to different implementations
334// of AudioStreamInterface.
335class MockAudioTransport : public test::MockAudioTransport {
336 public:
337 explicit MockAudioTransport(TransportType type) : type_(type) {}
338 ~MockAudioTransport() {}
339
340 // Set default actions of the mock object. We are delegating to fake
341 // implementation where the number of callbacks is counted and an event
342 // is set after a certain number of callbacks. Audio parameters are also
343 // checked.
henrikae24991d2017-04-06 01:14:23 -0700344 void HandleCallbacks(rtc::Event* event,
345 AudioStream* audio_stream,
346 int num_callbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700347 event_ = event;
henrikae24991d2017-04-06 01:14:23 -0700348 audio_stream_ = audio_stream;
henrikaf2f91fa2017-03-17 04:26:22 -0700349 num_callbacks_ = num_callbacks;
350 if (play_mode()) {
351 ON_CALL(*this, NeedMorePlayData(_, _, _, _, _, _, _, _))
352 .WillByDefault(
353 Invoke(this, &MockAudioTransport::RealNeedMorePlayData));
354 }
355 if (rec_mode()) {
356 ON_CALL(*this, RecordedDataIsAvailable(_, _, _, _, _, _, _, _, _, _))
357 .WillByDefault(
358 Invoke(this, &MockAudioTransport::RealRecordedDataIsAvailable));
359 }
360 }
361
henrika5b6afc02018-09-05 14:34:40 +0200362 // Special constructor used in manual tests where the user wants to run audio
363 // until e.g. a keyboard key is pressed. The event flag is set to nullptr by
364 // default since it is up to the user to stop the test. See e.g.
365 // DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey().
366 void HandleCallbacks(AudioStream* audio_stream) {
367 HandleCallbacks(nullptr, audio_stream, 0);
368 }
369
henrikaf2f91fa2017-03-17 04:26:22 -0700370 int32_t RealRecordedDataIsAvailable(const void* audio_buffer,
371 const size_t samples_per_channel,
372 const size_t bytes_per_frame,
373 const size_t channels,
374 const uint32_t sample_rate,
375 const uint32_t total_delay_ms,
376 const int32_t clock_drift,
377 const uint32_t current_mic_level,
378 const bool typing_status,
379 uint32_t& new_mic_level) {
380 EXPECT_TRUE(rec_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700381 // Store audio parameters once in the first callback. For all other
382 // callbacks, verify that the provided audio parameters are maintained and
383 // that each callback corresponds to 10ms for any given sample rate.
384 if (!record_parameters_.is_complete()) {
385 record_parameters_.reset(sample_rate, channels, samples_per_channel);
386 } else {
387 EXPECT_EQ(samples_per_channel, record_parameters_.frames_per_buffer());
388 EXPECT_EQ(bytes_per_frame, record_parameters_.GetBytesPerFrame());
389 EXPECT_EQ(channels, record_parameters_.channels());
390 EXPECT_EQ(static_cast<int>(sample_rate),
391 record_parameters_.sample_rate());
392 EXPECT_EQ(samples_per_channel,
393 record_parameters_.frames_per_10ms_buffer());
394 }
395 rec_count_++;
henrikae24991d2017-04-06 01:14:23 -0700396 // Write audio data to audio stream object if one has been injected.
397 if (audio_stream_) {
398 audio_stream_->Write(
399 rtc::MakeArrayView(static_cast<const int16_t*>(audio_buffer),
henrikaeb98c722018-03-20 12:54:07 +0100400 samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700401 }
henrikaf2f91fa2017-03-17 04:26:22 -0700402 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200403 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700404 event_->Set();
405 }
406 return 0;
407 }
408
409 int32_t RealNeedMorePlayData(const size_t samples_per_channel,
410 const size_t bytes_per_frame,
411 const size_t channels,
412 const uint32_t sample_rate,
413 void* audio_buffer,
henrikaeb98c722018-03-20 12:54:07 +0100414 size_t& samples_out,
henrikaf2f91fa2017-03-17 04:26:22 -0700415 int64_t* elapsed_time_ms,
416 int64_t* ntp_time_ms) {
417 EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700418 // Store audio parameters once in the first callback. For all other
419 // callbacks, verify that the provided audio parameters are maintained and
420 // that each callback corresponds to 10ms for any given sample rate.
421 if (!playout_parameters_.is_complete()) {
422 playout_parameters_.reset(sample_rate, channels, samples_per_channel);
423 } else {
424 EXPECT_EQ(samples_per_channel, playout_parameters_.frames_per_buffer());
425 EXPECT_EQ(bytes_per_frame, playout_parameters_.GetBytesPerFrame());
426 EXPECT_EQ(channels, playout_parameters_.channels());
427 EXPECT_EQ(static_cast<int>(sample_rate),
428 playout_parameters_.sample_rate());
429 EXPECT_EQ(samples_per_channel,
430 playout_parameters_.frames_per_10ms_buffer());
431 }
432 play_count_++;
henrikaeb98c722018-03-20 12:54:07 +0100433 samples_out = samples_per_channel * channels;
henrikae24991d2017-04-06 01:14:23 -0700434 // Read audio data from audio stream object if one has been injected.
435 if (audio_stream_) {
henrikaeb98c722018-03-20 12:54:07 +0100436 audio_stream_->Read(rtc::MakeArrayView(
437 static_cast<int16_t*>(audio_buffer), samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700438 } else {
439 // Fill the audio buffer with zeros to avoid disturbing audio.
440 const size_t num_bytes = samples_per_channel * bytes_per_frame;
441 std::memset(audio_buffer, 0, num_bytes);
442 }
henrikaf2f91fa2017-03-17 04:26:22 -0700443 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200444 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700445 event_->Set();
446 }
447 return 0;
448 }
449
450 bool ReceivedEnoughCallbacks() {
451 bool recording_done = false;
452 if (rec_mode()) {
453 recording_done = rec_count_ >= num_callbacks_;
454 } else {
455 recording_done = true;
456 }
457 bool playout_done = false;
458 if (play_mode()) {
459 playout_done = play_count_ >= num_callbacks_;
460 } else {
461 playout_done = true;
462 }
463 return recording_done && playout_done;
464 }
465
466 bool play_mode() const {
467 return type_ == TransportType::kPlay ||
468 type_ == TransportType::kPlayAndRecord;
469 }
470
471 bool rec_mode() const {
472 return type_ == TransportType::kRecord ||
473 type_ == TransportType::kPlayAndRecord;
474 }
475
henrika5b6afc02018-09-05 14:34:40 +0200476 void ResetCallbackCounters() {
477 if (play_mode()) {
478 play_count_ = 0;
479 }
480 if (rec_mode()) {
481 rec_count_ = 0;
482 }
483 }
484
henrikaf2f91fa2017-03-17 04:26:22 -0700485 private:
486 TransportType type_ = TransportType::kInvalid;
487 rtc::Event* event_ = nullptr;
henrikae24991d2017-04-06 01:14:23 -0700488 AudioStream* audio_stream_ = nullptr;
henrikaf2f91fa2017-03-17 04:26:22 -0700489 size_t num_callbacks_ = 0;
490 size_t play_count_ = 0;
491 size_t rec_count_ = 0;
492 AudioParameters playout_parameters_;
493 AudioParameters record_parameters_;
494};
495
496// AudioDeviceTest test fixture.
henrikaec9c7452018-06-08 16:10:03 +0200497class AudioDeviceTest
498 : public ::testing::TestWithParam<webrtc::AudioDeviceModule::AudioLayer> {
henrikaf2f91fa2017-03-17 04:26:22 -0700499 protected:
henrikaec9c7452018-06-08 16:10:03 +0200500 AudioDeviceTest() : audio_layer_(GetParam()), event_(false, false) {
Joachim Bauch5d2bb362017-12-20 21:19:49 +0100501#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \
502 !defined(WEBRTC_DUMMY_AUDIO_BUILD)
henrikaf2f91fa2017-03-17 04:26:22 -0700503 rtc::LogMessage::LogToDebug(rtc::LS_INFO);
504 // Add extra logging fields here if needed for debugging.
henrikaec9c7452018-06-08 16:10:03 +0200505 rtc::LogMessage::LogTimestamps();
506 rtc::LogMessage::LogThreads();
507 audio_device_ = CreateAudioDevice();
henrikaf2f91fa2017-03-17 04:26:22 -0700508 EXPECT_NE(audio_device_.get(), nullptr);
509 AudioDeviceModule::AudioLayer audio_layer;
maxmorin33bf69a2017-03-23 04:06:53 -0700510 int got_platform_audio_layer =
511 audio_device_->ActiveAudioLayer(&audio_layer);
henrika919dc2e2017-10-12 14:24:55 +0200512 // First, ensure that a valid audio layer can be activated.
513 if (got_platform_audio_layer != 0) {
henrikaf2f91fa2017-03-17 04:26:22 -0700514 requirements_satisfied_ = false;
515 }
henrika919dc2e2017-10-12 14:24:55 +0200516 // Next, verify that the ADM can be initialized.
henrikaf2f91fa2017-03-17 04:26:22 -0700517 if (requirements_satisfied_) {
henrika919dc2e2017-10-12 14:24:55 +0200518 requirements_satisfied_ = (audio_device_->Init() == 0);
519 }
520 // Finally, ensure that at least one valid device exists in each direction.
521 if (requirements_satisfied_) {
henrikaf2f91fa2017-03-17 04:26:22 -0700522 const int16_t num_playout_devices = audio_device_->PlayoutDevices();
523 const int16_t num_record_devices = audio_device_->RecordingDevices();
524 requirements_satisfied_ =
525 num_playout_devices > 0 && num_record_devices > 0;
526 }
527#else
528 requirements_satisfied_ = false;
529#endif
530 if (requirements_satisfied_) {
henrika5773ad32018-09-21 14:53:10 +0200531 EXPECT_EQ(0, audio_device_->SetPlayoutDevice(AUDIO_DEVICE_ID));
henrikaf2f91fa2017-03-17 04:26:22 -0700532 EXPECT_EQ(0, audio_device_->InitSpeaker());
henrikaf2f91fa2017-03-17 04:26:22 -0700533 EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
534 EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
henrika5773ad32018-09-21 14:53:10 +0200535 EXPECT_EQ(0, audio_device_->SetRecordingDevice(AUDIO_DEVICE_ID));
536 EXPECT_EQ(0, audio_device_->InitMicrophone());
henrika0238ba82017-03-28 04:38:29 -0700537 // Avoid asking for input stereo support and always record in mono
538 // since asking can cause issues in combination with remote desktop.
539 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
540 // details.
541 EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
henrikaf2f91fa2017-03-17 04:26:22 -0700542 }
543 }
544
545 virtual ~AudioDeviceTest() {
546 if (audio_device_) {
547 EXPECT_EQ(0, audio_device_->Terminate());
548 }
549 }
550
551 bool requirements_satisfied() const { return requirements_satisfied_; }
552 rtc::Event* event() { return &event_; }
henrika5b6afc02018-09-05 14:34:40 +0200553 AudioDeviceModule::AudioLayer audio_layer() const { return audio_layer_; }
henrikaf2f91fa2017-03-17 04:26:22 -0700554
henrika5b6afc02018-09-05 14:34:40 +0200555 // AudioDeviceModuleForTest extends the default ADM interface with some extra
556 // test methods. Intended for usage in tests only and requires a unique
557 // factory method. See CreateAudioDevice() for details.
558 const rtc::scoped_refptr<AudioDeviceModuleForTest>& audio_device() const {
henrikaf2f91fa2017-03-17 04:26:22 -0700559 return audio_device_;
560 }
561
henrika5b6afc02018-09-05 14:34:40 +0200562 rtc::scoped_refptr<AudioDeviceModuleForTest> CreateAudioDevice() {
henrikaec9c7452018-06-08 16:10:03 +0200563 // Use the default factory for kPlatformDefaultAudio and a special factory
henrika5b6afc02018-09-05 14:34:40 +0200564 // CreateWindowsCoreAudioAudioDeviceModuleForTest() for kWindowsCoreAudio2.
henrikaec9c7452018-06-08 16:10:03 +0200565 // The value of |audio_layer_| is set at construction by GetParam() and two
566 // different layers are tested on Windows only.
567 if (audio_layer_ == AudioDeviceModule::kPlatformDefaultAudio) {
henrika5b6afc02018-09-05 14:34:40 +0200568 return AudioDeviceModule::CreateForTest(audio_layer_);
henrikaec9c7452018-06-08 16:10:03 +0200569 } else if (audio_layer_ == AudioDeviceModule::kWindowsCoreAudio2) {
570#ifdef WEBRTC_WIN
571 // We must initialize the COM library on a thread before we calling any of
572 // the library functions. All COM functions in the ADM will return
573 // CO_E_NOTINITIALIZED otherwise.
Karl Wiberg918f50c2018-07-05 11:40:33 +0200574 com_initializer_ = absl::make_unique<webrtc_win::ScopedCOMInitializer>(
henrikaec9c7452018-06-08 16:10:03 +0200575 webrtc_win::ScopedCOMInitializer::kMTA);
576 EXPECT_TRUE(com_initializer_->Succeeded());
577 EXPECT_TRUE(webrtc_win::core_audio_utility::IsSupported());
578 EXPECT_TRUE(webrtc_win::core_audio_utility::IsMMCSSSupported());
henrika5b6afc02018-09-05 14:34:40 +0200579 return CreateWindowsCoreAudioAudioDeviceModuleForTest();
henrikaec9c7452018-06-08 16:10:03 +0200580#else
581 return nullptr;
582#endif
583 } else {
584 return nullptr;
585 }
586 }
587
henrikaf2f91fa2017-03-17 04:26:22 -0700588 void StartPlayout() {
589 EXPECT_FALSE(audio_device()->Playing());
590 EXPECT_EQ(0, audio_device()->InitPlayout());
591 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
592 EXPECT_EQ(0, audio_device()->StartPlayout());
593 EXPECT_TRUE(audio_device()->Playing());
594 }
595
596 void StopPlayout() {
597 EXPECT_EQ(0, audio_device()->StopPlayout());
598 EXPECT_FALSE(audio_device()->Playing());
599 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
600 }
601
602 void StartRecording() {
603 EXPECT_FALSE(audio_device()->Recording());
604 EXPECT_EQ(0, audio_device()->InitRecording());
605 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
606 EXPECT_EQ(0, audio_device()->StartRecording());
607 EXPECT_TRUE(audio_device()->Recording());
608 }
609
610 void StopRecording() {
611 EXPECT_EQ(0, audio_device()->StopRecording());
612 EXPECT_FALSE(audio_device()->Recording());
613 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
614 }
615
henrikaec9c7452018-06-08 16:10:03 +0200616 bool NewWindowsAudioDeviceModuleIsUsed() {
617#ifdef WEBRTC_WIN
618 AudioDeviceModule::AudioLayer audio_layer;
619 EXPECT_EQ(0, audio_device()->ActiveAudioLayer(&audio_layer));
620 if (audio_layer == AudioDeviceModule::kWindowsCoreAudio2) {
621 // Default device is always added as first element in the list and the
622 // default communication device as the second element. Hence, the list
623 // contains two extra elements in this case.
624 return true;
625 }
626#endif
627 return false;
628 }
629
henrikaf2f91fa2017-03-17 04:26:22 -0700630 private:
henrikaec9c7452018-06-08 16:10:03 +0200631#ifdef WEBRTC_WIN
632 // Windows Core Audio based ADM needs to run on a COM initialized thread.
633 std::unique_ptr<webrtc_win::ScopedCOMInitializer> com_initializer_;
634#endif
635 AudioDeviceModule::AudioLayer audio_layer_;
henrikaf2f91fa2017-03-17 04:26:22 -0700636 bool requirements_satisfied_ = true;
637 rtc::Event event_;
henrika5b6afc02018-09-05 14:34:40 +0200638 rtc::scoped_refptr<AudioDeviceModuleForTest> audio_device_;
henrikaf2f91fa2017-03-17 04:26:22 -0700639 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700640};
641
henrikaec9c7452018-06-08 16:10:03 +0200642// Instead of using the test fixture, verify that the different factory methods
643// work as intended.
644TEST(AudioDeviceTestWin, ConstructDestructWithFactory) {
645 rtc::scoped_refptr<AudioDeviceModule> audio_device;
646 // The default factory should work for all platforms when a default ADM is
647 // requested.
648 audio_device =
649 AudioDeviceModule::Create(AudioDeviceModule::kPlatformDefaultAudio);
650 EXPECT_TRUE(audio_device);
651 audio_device = nullptr;
652#ifdef WEBRTC_WIN
653 // For Windows, the old factory method creates an ADM where the platform-
654 // specific parts are implemented by an AudioDeviceGeneric object. Verify
655 // that the old factory can't be used in combination with the latest audio
656 // layer AudioDeviceModule::kWindowsCoreAudio2.
657 audio_device =
658 AudioDeviceModule::Create(AudioDeviceModule::kWindowsCoreAudio2);
659 EXPECT_FALSE(audio_device);
660 audio_device = nullptr;
661 // Instead, ensure that the new dedicated factory method called
662 // CreateWindowsCoreAudioAudioDeviceModule() can be used on Windows and that
663 // it sets the audio layer to kWindowsCoreAudio2 implicitly. Note that, the
664 // new ADM for Windows must be created on a COM thread.
665 webrtc_win::ScopedCOMInitializer com_initializer(
666 webrtc_win::ScopedCOMInitializer::kMTA);
667 EXPECT_TRUE(com_initializer.Succeeded());
668 audio_device = CreateWindowsCoreAudioAudioDeviceModule();
669 EXPECT_TRUE(audio_device);
670 AudioDeviceModule::AudioLayer audio_layer;
671 EXPECT_EQ(0, audio_device->ActiveAudioLayer(&audio_layer));
672 EXPECT_EQ(audio_layer, AudioDeviceModule::kWindowsCoreAudio2);
673#endif
674}
henrikaf2f91fa2017-03-17 04:26:22 -0700675
henrikaec9c7452018-06-08 16:10:03 +0200676// Uses the test fixture to create, initialize and destruct the ADM.
677TEST_P(AudioDeviceTest, ConstructDestructDefault) {}
678
679TEST_P(AudioDeviceTest, InitTerminate) {
henrikaf2f91fa2017-03-17 04:26:22 -0700680 SKIP_TEST_IF_NOT(requirements_satisfied());
681 // Initialization is part of the test fixture.
682 EXPECT_TRUE(audio_device()->Initialized());
683 EXPECT_EQ(0, audio_device()->Terminate());
684 EXPECT_FALSE(audio_device()->Initialized());
685}
686
henrikaec9c7452018-06-08 16:10:03 +0200687// Enumerate all available and active output devices.
688TEST_P(AudioDeviceTest, PlayoutDeviceNames) {
henrikaf2f91fa2017-03-17 04:26:22 -0700689 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaec9c7452018-06-08 16:10:03 +0200690 char device_name[kAdmMaxDeviceNameSize];
691 char unique_id[kAdmMaxGuidSize];
692 int num_devices = audio_device()->PlayoutDevices();
693 if (NewWindowsAudioDeviceModuleIsUsed()) {
694 num_devices += 2;
695 }
696 EXPECT_GT(num_devices, 0);
697 for (int i = 0; i < num_devices; ++i) {
698 EXPECT_EQ(0, audio_device()->PlayoutDeviceName(i, device_name, unique_id));
699 }
700 EXPECT_EQ(-1, audio_device()->PlayoutDeviceName(num_devices, device_name,
701 unique_id));
702}
703
704// Enumerate all available and active input devices.
705TEST_P(AudioDeviceTest, RecordingDeviceNames) {
706 SKIP_TEST_IF_NOT(requirements_satisfied());
707 char device_name[kAdmMaxDeviceNameSize];
708 char unique_id[kAdmMaxGuidSize];
709 int num_devices = audio_device()->RecordingDevices();
710 if (NewWindowsAudioDeviceModuleIsUsed()) {
711 num_devices += 2;
712 }
713 EXPECT_GT(num_devices, 0);
714 for (int i = 0; i < num_devices; ++i) {
715 EXPECT_EQ(0,
716 audio_device()->RecordingDeviceName(i, device_name, unique_id));
717 }
718 EXPECT_EQ(-1, audio_device()->RecordingDeviceName(num_devices, device_name,
719 unique_id));
720}
721
722// Counts number of active output devices and ensure that all can be selected.
723TEST_P(AudioDeviceTest, SetPlayoutDevice) {
724 SKIP_TEST_IF_NOT(requirements_satisfied());
725 int num_devices = audio_device()->PlayoutDevices();
726 if (NewWindowsAudioDeviceModuleIsUsed()) {
727 num_devices += 2;
728 }
729 EXPECT_GT(num_devices, 0);
730 // Verify that all available playout devices can be set (not enabled yet).
731 for (int i = 0; i < num_devices; ++i) {
732 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(i));
733 }
734 EXPECT_EQ(-1, audio_device()->SetPlayoutDevice(num_devices));
735#ifdef WEBRTC_WIN
736 // On Windows, verify the alternative method where the user can select device
737 // by role.
738 EXPECT_EQ(
739 0, audio_device()->SetPlayoutDevice(AudioDeviceModule::kDefaultDevice));
740 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(
741 AudioDeviceModule::kDefaultCommunicationDevice));
742#endif
743}
744
745// Counts number of active input devices and ensure that all can be selected.
746TEST_P(AudioDeviceTest, SetRecordingDevice) {
747 SKIP_TEST_IF_NOT(requirements_satisfied());
748 int num_devices = audio_device()->RecordingDevices();
749 if (NewWindowsAudioDeviceModuleIsUsed()) {
750 num_devices += 2;
751 }
752 EXPECT_GT(num_devices, 0);
753 // Verify that all available recording devices can be set (not enabled yet).
754 for (int i = 0; i < num_devices; ++i) {
755 EXPECT_EQ(0, audio_device()->SetRecordingDevice(i));
756 }
757 EXPECT_EQ(-1, audio_device()->SetRecordingDevice(num_devices));
758#ifdef WEBRTC_WIN
759 // On Windows, verify the alternative method where the user can select device
760 // by role.
761 EXPECT_EQ(
762 0, audio_device()->SetRecordingDevice(AudioDeviceModule::kDefaultDevice));
763 EXPECT_EQ(0, audio_device()->SetRecordingDevice(
764 AudioDeviceModule::kDefaultCommunicationDevice));
765#endif
766}
767
768// Tests Start/Stop playout without any registered audio callback.
769TEST_P(AudioDeviceTest, StartStopPlayout) {
770 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaf2f91fa2017-03-17 04:26:22 -0700771 StartPlayout();
772 StopPlayout();
773}
774
775// Tests Start/Stop recording without any registered audio callback.
henrikaec9c7452018-06-08 16:10:03 +0200776TEST_P(AudioDeviceTest, StartStopRecording) {
henrikaf2f91fa2017-03-17 04:26:22 -0700777 SKIP_TEST_IF_NOT(requirements_satisfied());
778 StartRecording();
779 StopRecording();
henrikaf2f91fa2017-03-17 04:26:22 -0700780}
781
henrika6b3e1a22017-09-25 16:34:30 +0200782// Tests Init/Stop/Init recording without any registered audio callback.
783// See https://bugs.chromium.org/p/webrtc/issues/detail?id=8041 for details
784// on why this test is useful.
henrikaec9c7452018-06-08 16:10:03 +0200785TEST_P(AudioDeviceTest, InitStopInitRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200786 SKIP_TEST_IF_NOT(requirements_satisfied());
787 EXPECT_EQ(0, audio_device()->InitRecording());
788 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
789 StopRecording();
790 EXPECT_EQ(0, audio_device()->InitRecording());
791 StopRecording();
792}
793
794// Tests Init/Stop/Init recording while playout is active.
henrikaec9c7452018-06-08 16:10:03 +0200795TEST_P(AudioDeviceTest, InitStopInitRecordingWhilePlaying) {
henrika6b3e1a22017-09-25 16:34:30 +0200796 SKIP_TEST_IF_NOT(requirements_satisfied());
797 StartPlayout();
798 EXPECT_EQ(0, audio_device()->InitRecording());
799 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
800 StopRecording();
801 EXPECT_EQ(0, audio_device()->InitRecording());
802 StopRecording();
803 StopPlayout();
804}
805
806// Tests Init/Stop/Init playout without any registered audio callback.
henrikaec9c7452018-06-08 16:10:03 +0200807TEST_P(AudioDeviceTest, InitStopInitPlayout) {
henrika6b3e1a22017-09-25 16:34:30 +0200808 SKIP_TEST_IF_NOT(requirements_satisfied());
809 EXPECT_EQ(0, audio_device()->InitPlayout());
810 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
811 StopPlayout();
812 EXPECT_EQ(0, audio_device()->InitPlayout());
813 StopPlayout();
814}
815
816// Tests Init/Stop/Init playout while recording is active.
henrikaec9c7452018-06-08 16:10:03 +0200817TEST_P(AudioDeviceTest, InitStopInitPlayoutWhileRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200818 SKIP_TEST_IF_NOT(requirements_satisfied());
819 StartRecording();
820 EXPECT_EQ(0, audio_device()->InitPlayout());
821 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
822 StopPlayout();
823 EXPECT_EQ(0, audio_device()->InitPlayout());
824 StopPlayout();
825 StopRecording();
826}
827
henrika5b6afc02018-09-05 14:34:40 +0200828// TODO(henrika): restart without intermediate destruction is currently only
829// supported on Windows.
830#ifdef WEBRTC_WIN
831// Tests Start/Stop playout followed by a second session (emulates a restart
832// triggered by a user using public APIs).
833TEST_P(AudioDeviceTest, StartStopPlayoutWithExternalRestart) {
834 SKIP_TEST_IF_NOT(requirements_satisfied());
835 StartPlayout();
836 StopPlayout();
837 // Restart playout without destroying the ADM in between. Ensures that we
838 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
839 StartPlayout();
840 StopPlayout();
841}
842
843// Tests Start/Stop recording followed by a second session (emulates a restart
844// triggered by a user using public APIs).
845TEST_P(AudioDeviceTest, StartStopRecordingWithExternalRestart) {
846 SKIP_TEST_IF_NOT(requirements_satisfied());
847 StartRecording();
848 StopRecording();
849 // Restart recording without destroying the ADM in between. Ensures that we
850 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
851 StartRecording();
852 StopRecording();
853}
854
855// Tests Start/Stop playout followed by a second session (emulates a restart
856// triggered by an internal callback e.g. corresponding to a device switch).
857// Note that, internal restart is only supported in combination with the latest
858// Windows ADM.
859TEST_P(AudioDeviceTest, StartStopPlayoutWithInternalRestart) {
860 SKIP_TEST_IF_NOT(requirements_satisfied());
861 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
862 return;
863 }
864 MockAudioTransport mock(TransportType::kPlay);
865 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
866 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
867 .Times(AtLeast(kNumCallbacks));
868 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
869 StartPlayout();
870 event()->Wait(kTestTimeOutInMilliseconds);
871 EXPECT_TRUE(audio_device()->Playing());
872 // Restart playout but without stopping the internal audio thread.
873 // This procedure uses a non-public test API and it emulates what happens
874 // inside the ADM when e.g. a device is removed.
875 EXPECT_EQ(0, audio_device()->RestartPlayoutInternally());
876
877 // Run basic tests of public APIs while a restart attempt is active.
878 // These calls should now be very thin and not trigger any new actions.
879 EXPECT_EQ(-1, audio_device()->StopPlayout());
880 EXPECT_TRUE(audio_device()->Playing());
881 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
882 EXPECT_EQ(0, audio_device()->InitPlayout());
883 EXPECT_EQ(0, audio_device()->StartPlayout());
884
885 // Wait until audio has restarted and a new sequence of audio callbacks
886 // becomes active.
887 // TODO(henrika): is it possible to verify that the internal state transition
888 // is Stop->Init->Start?
889 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
890 mock.ResetCallbackCounters();
891 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
892 .Times(AtLeast(kNumCallbacks));
893 event()->Wait(kTestTimeOutInMilliseconds);
894 EXPECT_TRUE(audio_device()->Playing());
895 // Stop playout and the audio thread after successful internal restart.
896 StopPlayout();
897}
898
899// Tests Start/Stop recording followed by a second session (emulates a restart
900// triggered by an internal callback e.g. corresponding to a device switch).
901// Note that, internal restart is only supported in combination with the latest
902// Windows ADM.
903TEST_P(AudioDeviceTest, StartStopRecordingWithInternalRestart) {
904 SKIP_TEST_IF_NOT(requirements_satisfied());
905 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
906 return;
907 }
908 MockAudioTransport mock(TransportType::kRecord);
909 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
910 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
911 false, _))
912 .Times(AtLeast(kNumCallbacks));
913 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
914 StartRecording();
915 event()->Wait(kTestTimeOutInMilliseconds);
916 EXPECT_TRUE(audio_device()->Recording());
917 // Restart recording but without stopping the internal audio thread.
918 // This procedure uses a non-public test API and it emulates what happens
919 // inside the ADM when e.g. a device is removed.
920 EXPECT_EQ(0, audio_device()->RestartRecordingInternally());
921
922 // Run basic tests of public APIs while a restart attempt is active.
923 // These calls should now be very thin and not trigger any new actions.
924 EXPECT_EQ(-1, audio_device()->StopRecording());
925 EXPECT_TRUE(audio_device()->Recording());
926 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
927 EXPECT_EQ(0, audio_device()->InitRecording());
928 EXPECT_EQ(0, audio_device()->StartRecording());
929
930 // Wait until audio has restarted and a new sequence of audio callbacks
931 // becomes active.
932 // TODO(henrika): is it possible to verify that the internal state transition
933 // is Stop->Init->Start?
934 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
935 mock.ResetCallbackCounters();
936 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
937 false, _))
938 .Times(AtLeast(kNumCallbacks));
939 event()->Wait(kTestTimeOutInMilliseconds);
940 EXPECT_TRUE(audio_device()->Recording());
941 // Stop recording and the audio thread after successful internal restart.
942 StopRecording();
943}
944#endif // #ifdef WEBRTC_WIN
945
henrikaf2f91fa2017-03-17 04:26:22 -0700946// Start playout and verify that the native audio layer starts asking for real
947// audio samples to play out using the NeedMorePlayData() callback.
948// Note that we can't add expectations on audio parameters in EXPECT_CALL
949// since parameter are not provided in the each callback. We therefore test and
950// verify the parameters in the fake audio transport implementation instead.
henrikaec9c7452018-06-08 16:10:03 +0200951TEST_P(AudioDeviceTest, StartPlayoutVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700952 SKIP_TEST_IF_NOT(requirements_satisfied());
953 MockAudioTransport mock(TransportType::kPlay);
henrikae24991d2017-04-06 01:14:23 -0700954 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700955 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
956 .Times(AtLeast(kNumCallbacks));
957 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
958 StartPlayout();
959 event()->Wait(kTestTimeOutInMilliseconds);
960 StopPlayout();
961}
962
963// Start recording and verify that the native audio layer starts providing real
964// audio samples using the RecordedDataIsAvailable() callback.
henrikaec9c7452018-06-08 16:10:03 +0200965TEST_P(AudioDeviceTest, StartRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700966 SKIP_TEST_IF_NOT(requirements_satisfied());
967 MockAudioTransport mock(TransportType::kRecord);
henrikae24991d2017-04-06 01:14:23 -0700968 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700969 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
970 false, _))
971 .Times(AtLeast(kNumCallbacks));
972 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
973 StartRecording();
974 event()->Wait(kTestTimeOutInMilliseconds);
975 StopRecording();
976}
977
978// Start playout and recording (full-duplex audio) and verify that audio is
979// active in both directions.
henrikaec9c7452018-06-08 16:10:03 +0200980TEST_P(AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700981 SKIP_TEST_IF_NOT(requirements_satisfied());
982 MockAudioTransport mock(TransportType::kPlayAndRecord);
henrikae24991d2017-04-06 01:14:23 -0700983 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700984 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
985 .Times(AtLeast(kNumCallbacks));
986 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
987 false, _))
988 .Times(AtLeast(kNumCallbacks));
989 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
990 StartPlayout();
991 StartRecording();
992 event()->Wait(kTestTimeOutInMilliseconds);
993 StopRecording();
994 StopPlayout();
995}
996
henrikae24991d2017-04-06 01:14:23 -0700997// Start playout and recording and store recorded data in an intermediate FIFO
998// buffer from which the playout side then reads its samples in the same order
999// as they were stored. Under ideal circumstances, a callback sequence would
1000// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
1001// means 'packet played'. Under such conditions, the FIFO would contain max 1,
1002// with an average somewhere in (0,1) depending on how long the packets are
1003// buffered. However, under more realistic conditions, the size
1004// of the FIFO will vary more due to an unbalance between the two sides.
1005// This test tries to verify that the device maintains a balanced callback-
1006// sequence by running in loopback for a few seconds while measuring the size
1007// (max and average) of the FIFO. The size of the FIFO is increased by the
1008// recording side and decreased by the playout side.
henrikaec9c7452018-06-08 16:10:03 +02001009TEST_P(AudioDeviceTest, RunPlayoutAndRecordingInFullDuplex) {
henrikae24991d2017-04-06 01:14:23 -07001010 SKIP_TEST_IF_NOT(requirements_satisfied());
1011 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1012 FifoAudioStream audio_stream;
1013 mock.HandleCallbacks(event(), &audio_stream,
1014 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
1015 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001016 // Run both sides using the same channel configuration to avoid conversions
1017 // between mono/stereo while running in full duplex mode. Also, some devices
1018 // (mainly on Windows) do not support mono.
1019 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1020 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrikae24991d2017-04-06 01:14:23 -07001021 StartPlayout();
1022 StartRecording();
henrika714e5cd2017-04-20 08:03:11 -07001023 event()->Wait(static_cast<int>(
1024 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec)));
henrikae24991d2017-04-06 01:14:23 -07001025 StopRecording();
1026 StopPlayout();
1027 // This thresholds is set rather high to accommodate differences in hardware
1028 // in several devices. The main idea is to capture cases where a very large
henrikab6ca7212017-10-06 12:47:52 +02001029 // latency is built up. See http://bugs.webrtc.org/7744 for examples on
1030 // bots where relatively large average latencies can happen.
1031 EXPECT_LE(audio_stream.average_size(), 25u);
henrikae24991d2017-04-06 01:14:23 -07001032 PRINT("\n");
1033}
1034
henrika5b6afc02018-09-05 14:34:40 +02001035// Runs audio in full duplex until user hits Enter. Intended as a manual test
1036// to ensure that the audio quality is good and that real device switches works
1037// as intended.
1038TEST_P(AudioDeviceTest,
1039 DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey) {
1040 SKIP_TEST_IF_NOT(requirements_satisfied());
1041 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
1042 return;
1043 }
1044 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1045 FifoAudioStream audio_stream;
1046 mock.HandleCallbacks(&audio_stream);
1047 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1048 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1049 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
1050 // Ensure that the sample rate for both directions are identical so that we
1051 // always can listen to our own voice. Will lead to rate conversion (and
1052 // higher latency) if the native sample rate is not 48kHz.
1053 EXPECT_EQ(0, audio_device()->SetPlayoutSampleRate(48000));
1054 EXPECT_EQ(0, audio_device()->SetRecordingSampleRate(48000));
1055 StartPlayout();
1056 StartRecording();
1057 do {
1058 PRINT("Loopback audio is active at 48kHz. Press Enter to stop.\n");
1059 } while (getchar() != '\n');
1060 StopRecording();
1061 StopPlayout();
1062}
1063
henrika714e5cd2017-04-20 08:03:11 -07001064// Measures loopback latency and reports the min, max and average values for
1065// a full duplex audio session.
1066// The latency is measured like so:
1067// - Insert impulses periodically on the output side.
1068// - Detect the impulses on the input side.
1069// - Measure the time difference between the transmit time and receive time.
1070// - Store time differences in a vector and calculate min, max and average.
1071// This test needs the '--gtest_also_run_disabled_tests' flag to run and also
1072// some sort of audio feedback loop. E.g. a headset where the mic is placed
1073// close to the speaker to ensure highest possible echo. It is also recommended
1074// to run the test at highest possible output volume.
henrikaec9c7452018-06-08 16:10:03 +02001075TEST_P(AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
henrika714e5cd2017-04-20 08:03:11 -07001076 SKIP_TEST_IF_NOT(requirements_satisfied());
1077 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1078 LatencyAudioStream audio_stream;
1079 mock.HandleCallbacks(event(), &audio_stream,
1080 kMeasureLatencyTimeInSec * kNumCallbacksPerSecond);
1081 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001082 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1083 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrika714e5cd2017-04-20 08:03:11 -07001084 StartPlayout();
1085 StartRecording();
1086 event()->Wait(static_cast<int>(
1087 std::max(kTestTimeOutInMilliseconds, 1000 * kMeasureLatencyTimeInSec)));
1088 StopRecording();
1089 StopPlayout();
henrikac7d93582018-09-14 15:37:34 +02001090 // Verify that a sufficient number of transmitted impulses are detected.
1091 EXPECT_GE(audio_stream.num_latency_values(),
henrika714e5cd2017-04-20 08:03:11 -07001092 static_cast<size_t>(
henrikac7d93582018-09-14 15:37:34 +02001093 kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 2));
henrika714e5cd2017-04-20 08:03:11 -07001094 // Print out min, max and average delay values for debugging purposes.
1095 audio_stream.PrintResults();
1096}
1097
henrikaec9c7452018-06-08 16:10:03 +02001098#ifdef WEBRTC_WIN
1099// Test two different audio layers (or rather two different Core Audio
1100// implementations) for Windows.
1101INSTANTIATE_TEST_CASE_P(
1102 AudioLayerWin,
1103 AudioDeviceTest,
1104 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio,
1105 AudioDeviceModule::kWindowsCoreAudio2));
1106#else
1107// For all platforms but Windows, only test the default audio layer.
1108INSTANTIATE_TEST_CASE_P(
1109 AudioLayer,
1110 AudioDeviceTest,
1111 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio));
1112#endif
1113
henrikaf2f91fa2017-03-17 04:26:22 -07001114} // namespace webrtc