blob: cd6be0ab7f5f0cd6c28dcb369dc6eee8d1d8dccd [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
Jonas Olssona4d87372019-07-05 19:08:33 +020011#include "modules/audio_device/include/audio_device.h"
12
henrika714e5cd2017-04-20 08:03:11 -070013#include <algorithm>
henrikaf2f91fa2017-03-17 04:26:22 -070014#include <cstring>
henrikaec9c7452018-06-08 16:10:03 +020015#include <memory>
henrika714e5cd2017-04-20 08:03:11 -070016#include <numeric>
henrikaf2f91fa2017-03-17 04:26:22 -070017
Steve Anton40d55332019-01-07 10:21:47 -080018#include "absl/memory/memory.h"
Danil Chapovalov196100e2018-06-21 10:17:24 +020019#include "absl/types/optional.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "api/array_view.h"
Mirko Bonadeid9708072019-01-25 20:26:48 +010021#include "api/scoped_refptr.h"
Danil Chapovalov1c41be62019-04-01 09:16:12 +020022#include "api/task_queue/default_task_queue_factory.h"
23#include "api/task_queue/task_queue_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "modules/audio_device/audio_device_impl.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/audio_device/include/mock_audio_transport.h"
26#include "rtc_base/buffer.h"
Steve Anton10542f22019-01-11 09:11:00 -080027#include "rtc_base/critical_section.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/event.h"
29#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010030#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "rtc_base/race_checker.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/thread_annotations.h"
33#include "rtc_base/thread_checker.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "rtc_base/time_utils.h"
henrika5b6afc02018-09-05 14:34:40 +020035#include "system_wrappers/include/sleep.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "test/gmock.h"
37#include "test/gtest.h"
henrikaec9c7452018-06-08 16:10:03 +020038#ifdef WEBRTC_WIN
39#include "modules/audio_device/include/audio_device_factory.h"
40#include "modules/audio_device/win/core_audio_utility_win.h"
41#endif
henrikaf2f91fa2017-03-17 04:26:22 -070042
43using ::testing::_;
44using ::testing::AtLeast;
45using ::testing::Ge;
46using ::testing::Invoke;
Jonas Olssona4d87372019-07-05 19:08:33 +020047using ::testing::Mock;
henrikaf2f91fa2017-03-17 04:26:22 -070048using ::testing::NiceMock;
49using ::testing::NotNull;
50
51namespace webrtc {
52namespace {
53
henrika5773ad32018-09-21 14:53:10 +020054// Using a #define for AUDIO_DEVICE since we will call *different* versions of
55// the ADM functions, depending on the ID type.
56#if defined(WEBRTC_WIN)
57#define AUDIO_DEVICE_ID (AudioDeviceModule::WindowsDeviceType::kDefaultDevice)
58#else
59#define AUDIO_DEVICE_ID (0u)
60#endif // defined(WEBRTC_WIN)
61
henrikae24991d2017-04-06 01:14:23 -070062// #define ENABLE_DEBUG_PRINTF
63#ifdef ENABLE_DEBUG_PRINTF
64#define PRINTD(...) fprintf(stderr, __VA_ARGS__);
65#else
66#define PRINTD(...) ((void)0)
67#endif
68#define PRINT(...) fprintf(stderr, __VA_ARGS__);
69
Yves Gerey1afe6572019-07-18 22:01:09 +020070// Don't run these tests if audio-related requirements are not met.
Yves Gereyee0550c2019-07-17 21:41:59 +020071#define SKIP_TEST_IF_NOT(requirements_satisfied) \
72 do { \
73 if (!requirements_satisfied) { \
74 GTEST_SKIP() << "Skipped. No audio device found."; \
75 } \
henrikaf2f91fa2017-03-17 04:26:22 -070076 } while (false)
henrikaf2f91fa2017-03-17 04:26:22 -070077
78// Number of callbacks (input or output) the tests waits for before we set
79// an event indicating that the test was OK.
henrikae24991d2017-04-06 01:14:23 -070080static constexpr size_t kNumCallbacks = 10;
henrikaf2f91fa2017-03-17 04:26:22 -070081// Max amount of time we wait for an event to be set while counting callbacks.
henrika714e5cd2017-04-20 08:03:11 -070082static constexpr size_t kTestTimeOutInMilliseconds = 10 * 1000;
henrikae24991d2017-04-06 01:14:23 -070083// Average number of audio callbacks per second assuming 10ms packet size.
84static constexpr size_t kNumCallbacksPerSecond = 100;
85// Run the full-duplex test during this time (unit is in seconds).
henrika714e5cd2017-04-20 08:03:11 -070086static constexpr size_t kFullDuplexTimeInSec = 5;
87// Length of round-trip latency measurements. Number of deteced impulses
88// shall be kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 1 since the
89// last transmitted pulse is not used.
90static constexpr size_t kMeasureLatencyTimeInSec = 10;
91// Sets the number of impulses per second in the latency test.
92static constexpr size_t kImpulseFrequencyInHz = 1;
93// Utilized in round-trip latency measurements to avoid capturing noise samples.
94static constexpr int kImpulseThreshold = 1000;
henrikaf2f91fa2017-03-17 04:26:22 -070095
96enum class TransportType {
97 kInvalid,
98 kPlay,
99 kRecord,
100 kPlayAndRecord,
101};
henrikae24991d2017-04-06 01:14:23 -0700102
103// Interface for processing the audio stream. Real implementations can e.g.
104// run audio in loopback, read audio from a file or perform latency
105// measurements.
106class AudioStream {
107 public:
henrikaeb98c722018-03-20 12:54:07 +0100108 virtual void Write(rtc::ArrayView<const int16_t> source) = 0;
109 virtual void Read(rtc::ArrayView<int16_t> destination) = 0;
henrikae24991d2017-04-06 01:14:23 -0700110
111 virtual ~AudioStream() = default;
112};
113
henrika714e5cd2017-04-20 08:03:11 -0700114// Converts index corresponding to position within a 10ms buffer into a
115// delay value in milliseconds.
116// Example: index=240, frames_per_10ms_buffer=480 => 5ms as output.
117int IndexToMilliseconds(size_t index, size_t frames_per_10ms_buffer) {
118 return rtc::checked_cast<int>(
119 10.0 * (static_cast<double>(index) / frames_per_10ms_buffer) + 0.5);
120}
121
henrikaf2f91fa2017-03-17 04:26:22 -0700122} // namespace
123
henrikae24991d2017-04-06 01:14:23 -0700124// Simple first in first out (FIFO) class that wraps a list of 16-bit audio
125// buffers of fixed size and allows Write and Read operations. The idea is to
126// store recorded audio buffers (using Write) and then read (using Read) these
127// stored buffers with as short delay as possible when the audio layer needs
128// data to play out. The number of buffers in the FIFO will stabilize under
129// normal conditions since there will be a balance between Write and Read calls.
130// The container is a std::list container and access is protected with a lock
131// since both sides (playout and recording) are driven by its own thread.
132// Note that, we know by design that the size of the audio buffer will not
henrikac7d93582018-09-14 15:37:34 +0200133// change over time and that both sides will in most cases use the same size.
henrikae24991d2017-04-06 01:14:23 -0700134class FifoAudioStream : public AudioStream {
135 public:
henrikaeb98c722018-03-20 12:54:07 +0100136 void Write(rtc::ArrayView<const int16_t> source) override {
henrikae24991d2017-04-06 01:14:23 -0700137 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
138 const size_t size = [&] {
139 rtc::CritScope lock(&lock_);
140 fifo_.push_back(Buffer16(source.data(), source.size()));
141 return fifo_.size();
142 }();
143 if (size > max_size_) {
144 max_size_ = size;
145 }
146 // Add marker once per second to signal that audio is active.
147 if (write_count_++ % 100 == 0) {
henrikad8c6ec42019-07-18 15:17:28 +0200148 PRINTD(".");
henrikae24991d2017-04-06 01:14:23 -0700149 }
150 written_elements_ += size;
151 }
152
henrikaeb98c722018-03-20 12:54:07 +0100153 void Read(rtc::ArrayView<int16_t> destination) override {
henrikae24991d2017-04-06 01:14:23 -0700154 rtc::CritScope lock(&lock_);
155 if (fifo_.empty()) {
156 std::fill(destination.begin(), destination.end(), 0);
157 } else {
158 const Buffer16& buffer = fifo_.front();
henrikac7d93582018-09-14 15:37:34 +0200159 if (buffer.size() == destination.size()) {
160 // Default case where input and output uses same sample rate and
161 // channel configuration. No conversion is needed.
162 std::copy(buffer.begin(), buffer.end(), destination.begin());
163 } else if (destination.size() == 2 * buffer.size()) {
164 // Recorded input signal in |buffer| is in mono. Do channel upmix to
165 // match stereo output (1 -> 2).
166 for (size_t i = 0; i < buffer.size(); ++i) {
167 destination[2 * i] = buffer[i];
168 destination[2 * i + 1] = buffer[i];
169 }
170 } else if (buffer.size() == 2 * destination.size()) {
171 // Recorded input signal in |buffer| is in stereo. Do channel downmix
172 // to match mono output (2 -> 1).
173 for (size_t i = 0; i < destination.size(); ++i) {
174 destination[i] =
175 (static_cast<int32_t>(buffer[2 * i]) + buffer[2 * i + 1]) / 2;
176 }
177 } else {
178 RTC_NOTREACHED() << "Required conversion is not support";
179 }
henrikae24991d2017-04-06 01:14:23 -0700180 fifo_.pop_front();
181 }
182 }
183
184 size_t size() const {
185 rtc::CritScope lock(&lock_);
186 return fifo_.size();
187 }
188
189 size_t max_size() const {
190 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
191 return max_size_;
192 }
193
194 size_t average_size() const {
195 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
196 return 0.5 + static_cast<float>(written_elements_ / write_count_);
197 }
198
199 using Buffer16 = rtc::BufferT<int16_t>;
200
201 rtc::CriticalSection lock_;
202 rtc::RaceChecker race_checker_;
203
danilchap56359be2017-09-07 07:53:45 -0700204 std::list<Buffer16> fifo_ RTC_GUARDED_BY(lock_);
205 size_t write_count_ RTC_GUARDED_BY(race_checker_) = 0;
206 size_t max_size_ RTC_GUARDED_BY(race_checker_) = 0;
207 size_t written_elements_ RTC_GUARDED_BY(race_checker_) = 0;
henrikae24991d2017-04-06 01:14:23 -0700208};
209
henrika714e5cd2017-04-20 08:03:11 -0700210// Inserts periodic impulses and measures the latency between the time of
211// transmission and time of receiving the same impulse.
212class LatencyAudioStream : public AudioStream {
213 public:
214 LatencyAudioStream() {
215 // Delay thread checkers from being initialized until first callback from
216 // respective thread.
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200217 read_thread_checker_.Detach();
218 write_thread_checker_.Detach();
henrika714e5cd2017-04-20 08:03:11 -0700219 }
220
221 // Insert periodic impulses in first two samples of |destination|.
henrikaeb98c722018-03-20 12:54:07 +0100222 void Read(rtc::ArrayView<int16_t> destination) override {
henrika714e5cd2017-04-20 08:03:11 -0700223 RTC_DCHECK_RUN_ON(&read_thread_checker_);
henrika714e5cd2017-04-20 08:03:11 -0700224 if (read_count_ == 0) {
225 PRINT("[");
226 }
227 read_count_++;
228 std::fill(destination.begin(), destination.end(), 0);
229 if (read_count_ % (kNumCallbacksPerSecond / kImpulseFrequencyInHz) == 0) {
230 PRINT(".");
231 {
232 rtc::CritScope lock(&lock_);
233 if (!pulse_time_) {
Oskar Sundbom6ad9f262017-11-16 10:53:39 +0100234 pulse_time_ = rtc::TimeMillis();
henrika714e5cd2017-04-20 08:03:11 -0700235 }
236 }
237 constexpr int16_t impulse = std::numeric_limits<int16_t>::max();
238 std::fill_n(destination.begin(), 2, impulse);
239 }
240 }
241
242 // Detect received impulses in |source|, derive time between transmission and
243 // detection and add the calculated delay to list of latencies.
henrikaeb98c722018-03-20 12:54:07 +0100244 void Write(rtc::ArrayView<const int16_t> source) override {
henrika714e5cd2017-04-20 08:03:11 -0700245 RTC_DCHECK_RUN_ON(&write_thread_checker_);
246 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
247 rtc::CritScope lock(&lock_);
248 write_count_++;
249 if (!pulse_time_) {
250 // Avoid detection of new impulse response until a new impulse has
251 // been transmitted (sets |pulse_time_| to value larger than zero).
252 return;
253 }
254 // Find index (element position in vector) of the max element.
255 const size_t index_of_max =
256 std::max_element(source.begin(), source.end()) - source.begin();
257 // Derive time between transmitted pulse and received pulse if the level
258 // is high enough (removes noise).
259 const size_t max = source[index_of_max];
260 if (max > kImpulseThreshold) {
261 PRINTD("(%zu, %zu)", max, index_of_max);
262 int64_t now_time = rtc::TimeMillis();
263 int extra_delay = IndexToMilliseconds(index_of_max, source.size());
264 PRINTD("[%d]", rtc::checked_cast<int>(now_time - pulse_time_));
265 PRINTD("[%d]", extra_delay);
266 // Total latency is the difference between transmit time and detection
267 // tome plus the extra delay within the buffer in which we detected the
268 // received impulse. It is transmitted at sample 0 but can be received
269 // at sample N where N > 0. The term |extra_delay| accounts for N and it
270 // is a value between 0 and 10ms.
271 latencies_.push_back(now_time - *pulse_time_ + extra_delay);
272 pulse_time_.reset();
273 } else {
274 PRINTD("-");
275 }
276 }
277
278 size_t num_latency_values() const {
279 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
280 return latencies_.size();
281 }
282
283 int min_latency() const {
284 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
285 if (latencies_.empty())
286 return 0;
287 return *std::min_element(latencies_.begin(), latencies_.end());
288 }
289
290 int max_latency() const {
291 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
292 if (latencies_.empty())
293 return 0;
294 return *std::max_element(latencies_.begin(), latencies_.end());
295 }
296
297 int average_latency() const {
298 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
299 if (latencies_.empty())
300 return 0;
301 return 0.5 + static_cast<double>(
302 std::accumulate(latencies_.begin(), latencies_.end(), 0)) /
303 latencies_.size();
304 }
305
306 void PrintResults() const {
307 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
308 PRINT("] ");
309 for (auto it = latencies_.begin(); it != latencies_.end(); ++it) {
310 PRINTD("%d ", *it);
311 }
312 PRINT("\n");
313 PRINT("[..........] [min, max, avg]=[%d, %d, %d] ms\n", min_latency(),
314 max_latency(), average_latency());
315 }
316
317 rtc::CriticalSection lock_;
318 rtc::RaceChecker race_checker_;
319 rtc::ThreadChecker read_thread_checker_;
320 rtc::ThreadChecker write_thread_checker_;
321
Danil Chapovalov196100e2018-06-21 10:17:24 +0200322 absl::optional<int64_t> pulse_time_ RTC_GUARDED_BY(lock_);
danilchap56359be2017-09-07 07:53:45 -0700323 std::vector<int> latencies_ RTC_GUARDED_BY(race_checker_);
Niels Möller1e062892018-02-07 10:18:32 +0100324 size_t read_count_ RTC_GUARDED_BY(read_thread_checker_) = 0;
325 size_t write_count_ RTC_GUARDED_BY(write_thread_checker_) = 0;
henrika714e5cd2017-04-20 08:03:11 -0700326};
327
henrikaf2f91fa2017-03-17 04:26:22 -0700328// Mocks the AudioTransport object and proxies actions for the two callbacks
329// (RecordedDataIsAvailable and NeedMorePlayData) to different implementations
330// of AudioStreamInterface.
331class MockAudioTransport : public test::MockAudioTransport {
332 public:
333 explicit MockAudioTransport(TransportType type) : type_(type) {}
334 ~MockAudioTransport() {}
335
336 // Set default actions of the mock object. We are delegating to fake
337 // implementation where the number of callbacks is counted and an event
338 // is set after a certain number of callbacks. Audio parameters are also
339 // checked.
henrikae24991d2017-04-06 01:14:23 -0700340 void HandleCallbacks(rtc::Event* event,
341 AudioStream* audio_stream,
342 int num_callbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700343 event_ = event;
henrikae24991d2017-04-06 01:14:23 -0700344 audio_stream_ = audio_stream;
henrikaf2f91fa2017-03-17 04:26:22 -0700345 num_callbacks_ = num_callbacks;
346 if (play_mode()) {
347 ON_CALL(*this, NeedMorePlayData(_, _, _, _, _, _, _, _))
348 .WillByDefault(
349 Invoke(this, &MockAudioTransport::RealNeedMorePlayData));
350 }
351 if (rec_mode()) {
352 ON_CALL(*this, RecordedDataIsAvailable(_, _, _, _, _, _, _, _, _, _))
353 .WillByDefault(
354 Invoke(this, &MockAudioTransport::RealRecordedDataIsAvailable));
355 }
356 }
357
henrika5b6afc02018-09-05 14:34:40 +0200358 // Special constructor used in manual tests where the user wants to run audio
359 // until e.g. a keyboard key is pressed. The event flag is set to nullptr by
360 // default since it is up to the user to stop the test. See e.g.
361 // DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey().
362 void HandleCallbacks(AudioStream* audio_stream) {
363 HandleCallbacks(nullptr, audio_stream, 0);
364 }
365
henrikaf2f91fa2017-03-17 04:26:22 -0700366 int32_t RealRecordedDataIsAvailable(const void* audio_buffer,
367 const size_t samples_per_channel,
368 const size_t bytes_per_frame,
369 const size_t channels,
370 const uint32_t sample_rate,
371 const uint32_t total_delay_ms,
372 const int32_t clock_drift,
373 const uint32_t current_mic_level,
374 const bool typing_status,
375 uint32_t& new_mic_level) {
376 EXPECT_TRUE(rec_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700377 // Store audio parameters once in the first callback. For all other
378 // callbacks, verify that the provided audio parameters are maintained and
379 // that each callback corresponds to 10ms for any given sample rate.
380 if (!record_parameters_.is_complete()) {
381 record_parameters_.reset(sample_rate, channels, samples_per_channel);
382 } else {
383 EXPECT_EQ(samples_per_channel, record_parameters_.frames_per_buffer());
384 EXPECT_EQ(bytes_per_frame, record_parameters_.GetBytesPerFrame());
385 EXPECT_EQ(channels, record_parameters_.channels());
386 EXPECT_EQ(static_cast<int>(sample_rate),
387 record_parameters_.sample_rate());
388 EXPECT_EQ(samples_per_channel,
389 record_parameters_.frames_per_10ms_buffer());
390 }
henrika78e0ac12018-09-27 16:23:21 +0200391 {
392 rtc::CritScope lock(&lock_);
393 rec_count_++;
394 }
henrikae24991d2017-04-06 01:14:23 -0700395 // Write audio data to audio stream object if one has been injected.
396 if (audio_stream_) {
397 audio_stream_->Write(
398 rtc::MakeArrayView(static_cast<const int16_t*>(audio_buffer),
henrikaeb98c722018-03-20 12:54:07 +0100399 samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700400 }
henrikaf2f91fa2017-03-17 04:26:22 -0700401 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200402 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700403 event_->Set();
404 }
405 return 0;
406 }
407
408 int32_t RealNeedMorePlayData(const size_t samples_per_channel,
409 const size_t bytes_per_frame,
410 const size_t channels,
411 const uint32_t sample_rate,
412 void* audio_buffer,
henrikaeb98c722018-03-20 12:54:07 +0100413 size_t& samples_out,
henrikaf2f91fa2017-03-17 04:26:22 -0700414 int64_t* elapsed_time_ms,
415 int64_t* ntp_time_ms) {
416 EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700417 // Store audio parameters once in the first callback. For all other
418 // callbacks, verify that the provided audio parameters are maintained and
419 // that each callback corresponds to 10ms for any given sample rate.
420 if (!playout_parameters_.is_complete()) {
421 playout_parameters_.reset(sample_rate, channels, samples_per_channel);
422 } else {
423 EXPECT_EQ(samples_per_channel, playout_parameters_.frames_per_buffer());
424 EXPECT_EQ(bytes_per_frame, playout_parameters_.GetBytesPerFrame());
425 EXPECT_EQ(channels, playout_parameters_.channels());
426 EXPECT_EQ(static_cast<int>(sample_rate),
427 playout_parameters_.sample_rate());
428 EXPECT_EQ(samples_per_channel,
429 playout_parameters_.frames_per_10ms_buffer());
430 }
henrika78e0ac12018-09-27 16:23:21 +0200431 {
432 rtc::CritScope lock(&lock_);
433 play_count_++;
434 }
henrikaeb98c722018-03-20 12:54:07 +0100435 samples_out = samples_per_channel * channels;
henrikae24991d2017-04-06 01:14:23 -0700436 // Read audio data from audio stream object if one has been injected.
437 if (audio_stream_) {
henrikaeb98c722018-03-20 12:54:07 +0100438 audio_stream_->Read(rtc::MakeArrayView(
439 static_cast<int16_t*>(audio_buffer), samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700440 } else {
441 // Fill the audio buffer with zeros to avoid disturbing audio.
442 const size_t num_bytes = samples_per_channel * bytes_per_frame;
443 std::memset(audio_buffer, 0, num_bytes);
444 }
henrikaf2f91fa2017-03-17 04:26:22 -0700445 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200446 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700447 event_->Set();
448 }
449 return 0;
450 }
451
452 bool ReceivedEnoughCallbacks() {
453 bool recording_done = false;
454 if (rec_mode()) {
henrika78e0ac12018-09-27 16:23:21 +0200455 rtc::CritScope lock(&lock_);
henrikaf2f91fa2017-03-17 04:26:22 -0700456 recording_done = rec_count_ >= num_callbacks_;
457 } else {
458 recording_done = true;
459 }
460 bool playout_done = false;
461 if (play_mode()) {
henrika78e0ac12018-09-27 16:23:21 +0200462 rtc::CritScope lock(&lock_);
henrikaf2f91fa2017-03-17 04:26:22 -0700463 playout_done = play_count_ >= num_callbacks_;
464 } else {
465 playout_done = true;
466 }
467 return recording_done && playout_done;
468 }
469
470 bool play_mode() const {
471 return type_ == TransportType::kPlay ||
472 type_ == TransportType::kPlayAndRecord;
473 }
474
475 bool rec_mode() const {
476 return type_ == TransportType::kRecord ||
477 type_ == TransportType::kPlayAndRecord;
478 }
479
henrika5b6afc02018-09-05 14:34:40 +0200480 void ResetCallbackCounters() {
henrika78e0ac12018-09-27 16:23:21 +0200481 rtc::CritScope lock(&lock_);
henrika5b6afc02018-09-05 14:34:40 +0200482 if (play_mode()) {
483 play_count_ = 0;
484 }
485 if (rec_mode()) {
486 rec_count_ = 0;
487 }
488 }
489
henrikaf2f91fa2017-03-17 04:26:22 -0700490 private:
henrika78e0ac12018-09-27 16:23:21 +0200491 rtc::CriticalSection lock_;
henrikaf2f91fa2017-03-17 04:26:22 -0700492 TransportType type_ = TransportType::kInvalid;
493 rtc::Event* event_ = nullptr;
henrikae24991d2017-04-06 01:14:23 -0700494 AudioStream* audio_stream_ = nullptr;
henrikaf2f91fa2017-03-17 04:26:22 -0700495 size_t num_callbacks_ = 0;
henrika78e0ac12018-09-27 16:23:21 +0200496 size_t play_count_ RTC_GUARDED_BY(lock_) = 0;
497 size_t rec_count_ RTC_GUARDED_BY(lock_) = 0;
henrikaf2f91fa2017-03-17 04:26:22 -0700498 AudioParameters playout_parameters_;
499 AudioParameters record_parameters_;
500};
501
502// AudioDeviceTest test fixture.
Yves Gerey1afe6572019-07-18 22:01:09 +0200503
Yves Gereyff060ee2019-09-11 15:53:01 +0200504// bugs.webrtc.org/9808
505// Both the tests and the code under test are very old, unstaffed and not
506// a part of webRTC stack.
507// Here sanitizers make the tests hang, without providing usefull report.
508// So we are just disabling them, without intention to re-enable them.
509#if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
510 defined(THREAD_SANITIZER) || defined(UNDEFINED_SANITIZER)
511#define MAYBE_AudioDeviceTest DISABLED_AudioDeviceTest
512#else
513#define MAYBE_AudioDeviceTest AudioDeviceTest
514#endif
515
516class MAYBE_AudioDeviceTest
henrikaec9c7452018-06-08 16:10:03 +0200517 : public ::testing::TestWithParam<webrtc::AudioDeviceModule::AudioLayer> {
henrikaf2f91fa2017-03-17 04:26:22 -0700518 protected:
Yves Gereyff060ee2019-09-11 15:53:01 +0200519 MAYBE_AudioDeviceTest()
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200520 : audio_layer_(GetParam()),
521 task_queue_factory_(CreateDefaultTaskQueueFactory()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700522 rtc::LogMessage::LogToDebug(rtc::LS_INFO);
523 // Add extra logging fields here if needed for debugging.
henrikaec9c7452018-06-08 16:10:03 +0200524 rtc::LogMessage::LogTimestamps();
525 rtc::LogMessage::LogThreads();
526 audio_device_ = CreateAudioDevice();
henrikaf2f91fa2017-03-17 04:26:22 -0700527 EXPECT_NE(audio_device_.get(), nullptr);
528 AudioDeviceModule::AudioLayer audio_layer;
maxmorin33bf69a2017-03-23 04:06:53 -0700529 int got_platform_audio_layer =
530 audio_device_->ActiveAudioLayer(&audio_layer);
henrika919dc2e2017-10-12 14:24:55 +0200531 // First, ensure that a valid audio layer can be activated.
532 if (got_platform_audio_layer != 0) {
henrikaf2f91fa2017-03-17 04:26:22 -0700533 requirements_satisfied_ = false;
534 }
henrika919dc2e2017-10-12 14:24:55 +0200535 // Next, verify that the ADM can be initialized.
henrikaf2f91fa2017-03-17 04:26:22 -0700536 if (requirements_satisfied_) {
henrika919dc2e2017-10-12 14:24:55 +0200537 requirements_satisfied_ = (audio_device_->Init() == 0);
538 }
539 // Finally, ensure that at least one valid device exists in each direction.
540 if (requirements_satisfied_) {
henrikaf2f91fa2017-03-17 04:26:22 -0700541 const int16_t num_playout_devices = audio_device_->PlayoutDevices();
542 const int16_t num_record_devices = audio_device_->RecordingDevices();
543 requirements_satisfied_ =
544 num_playout_devices > 0 && num_record_devices > 0;
545 }
henrikaf2f91fa2017-03-17 04:26:22 -0700546 if (requirements_satisfied_) {
henrika5773ad32018-09-21 14:53:10 +0200547 EXPECT_EQ(0, audio_device_->SetPlayoutDevice(AUDIO_DEVICE_ID));
henrikaf2f91fa2017-03-17 04:26:22 -0700548 EXPECT_EQ(0, audio_device_->InitSpeaker());
henrikaf2f91fa2017-03-17 04:26:22 -0700549 EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
550 EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
henrika5773ad32018-09-21 14:53:10 +0200551 EXPECT_EQ(0, audio_device_->SetRecordingDevice(AUDIO_DEVICE_ID));
552 EXPECT_EQ(0, audio_device_->InitMicrophone());
henrika0238ba82017-03-28 04:38:29 -0700553 // Avoid asking for input stereo support and always record in mono
554 // since asking can cause issues in combination with remote desktop.
555 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
556 // details.
557 EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
henrikaf2f91fa2017-03-17 04:26:22 -0700558 }
559 }
560
Yves Gereyb93a2452019-07-19 22:46:13 +0200561 // This is needed by all tests using MockAudioTransport,
562 // since there is no way to unregister it.
563 // Without Terminate(), audio_device would still accesses
564 // the destructed mock via "webrtc_audio_module_rec_thread".
565 // An alternative would be for the mock to outlive audio_device.
566 void PreTearDown() { EXPECT_EQ(0, audio_device_->Terminate()); }
567
Yves Gereyff060ee2019-09-11 15:53:01 +0200568 virtual ~MAYBE_AudioDeviceTest() {
henrikaf2f91fa2017-03-17 04:26:22 -0700569 if (audio_device_) {
570 EXPECT_EQ(0, audio_device_->Terminate());
571 }
572 }
573
574 bool requirements_satisfied() const { return requirements_satisfied_; }
575 rtc::Event* event() { return &event_; }
henrika5b6afc02018-09-05 14:34:40 +0200576 AudioDeviceModule::AudioLayer audio_layer() const { return audio_layer_; }
henrikaf2f91fa2017-03-17 04:26:22 -0700577
henrika5b6afc02018-09-05 14:34:40 +0200578 // AudioDeviceModuleForTest extends the default ADM interface with some extra
579 // test methods. Intended for usage in tests only and requires a unique
580 // factory method. See CreateAudioDevice() for details.
581 const rtc::scoped_refptr<AudioDeviceModuleForTest>& audio_device() const {
henrikaf2f91fa2017-03-17 04:26:22 -0700582 return audio_device_;
583 }
584
henrika5b6afc02018-09-05 14:34:40 +0200585 rtc::scoped_refptr<AudioDeviceModuleForTest> CreateAudioDevice() {
henrikaec9c7452018-06-08 16:10:03 +0200586 // Use the default factory for kPlatformDefaultAudio and a special factory
henrika5b6afc02018-09-05 14:34:40 +0200587 // CreateWindowsCoreAudioAudioDeviceModuleForTest() for kWindowsCoreAudio2.
henrikaec9c7452018-06-08 16:10:03 +0200588 // The value of |audio_layer_| is set at construction by GetParam() and two
589 // different layers are tested on Windows only.
590 if (audio_layer_ == AudioDeviceModule::kPlatformDefaultAudio) {
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200591 return AudioDeviceModule::CreateForTest(audio_layer_,
592 task_queue_factory_.get());
henrikaec9c7452018-06-08 16:10:03 +0200593 } else if (audio_layer_ == AudioDeviceModule::kWindowsCoreAudio2) {
594#ifdef WEBRTC_WIN
595 // We must initialize the COM library on a thread before we calling any of
596 // the library functions. All COM functions in the ADM will return
597 // CO_E_NOTINITIALIZED otherwise.
Karl Wiberg918f50c2018-07-05 11:40:33 +0200598 com_initializer_ = absl::make_unique<webrtc_win::ScopedCOMInitializer>(
henrikaec9c7452018-06-08 16:10:03 +0200599 webrtc_win::ScopedCOMInitializer::kMTA);
600 EXPECT_TRUE(com_initializer_->Succeeded());
601 EXPECT_TRUE(webrtc_win::core_audio_utility::IsSupported());
602 EXPECT_TRUE(webrtc_win::core_audio_utility::IsMMCSSSupported());
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200603 return CreateWindowsCoreAudioAudioDeviceModuleForTest(
henrikad8c6ec42019-07-18 15:17:28 +0200604 task_queue_factory_.get(), true);
henrikaec9c7452018-06-08 16:10:03 +0200605#else
606 return nullptr;
607#endif
608 } else {
609 return nullptr;
610 }
611 }
612
henrikaf2f91fa2017-03-17 04:26:22 -0700613 void StartPlayout() {
614 EXPECT_FALSE(audio_device()->Playing());
615 EXPECT_EQ(0, audio_device()->InitPlayout());
616 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
617 EXPECT_EQ(0, audio_device()->StartPlayout());
618 EXPECT_TRUE(audio_device()->Playing());
619 }
620
621 void StopPlayout() {
622 EXPECT_EQ(0, audio_device()->StopPlayout());
623 EXPECT_FALSE(audio_device()->Playing());
624 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
625 }
626
627 void StartRecording() {
628 EXPECT_FALSE(audio_device()->Recording());
629 EXPECT_EQ(0, audio_device()->InitRecording());
630 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
631 EXPECT_EQ(0, audio_device()->StartRecording());
632 EXPECT_TRUE(audio_device()->Recording());
633 }
634
635 void StopRecording() {
636 EXPECT_EQ(0, audio_device()->StopRecording());
637 EXPECT_FALSE(audio_device()->Recording());
638 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
639 }
640
henrikaec9c7452018-06-08 16:10:03 +0200641 bool NewWindowsAudioDeviceModuleIsUsed() {
642#ifdef WEBRTC_WIN
643 AudioDeviceModule::AudioLayer audio_layer;
644 EXPECT_EQ(0, audio_device()->ActiveAudioLayer(&audio_layer));
645 if (audio_layer == AudioDeviceModule::kWindowsCoreAudio2) {
646 // Default device is always added as first element in the list and the
647 // default communication device as the second element. Hence, the list
648 // contains two extra elements in this case.
649 return true;
650 }
651#endif
652 return false;
653 }
654
henrikaf2f91fa2017-03-17 04:26:22 -0700655 private:
henrikaec9c7452018-06-08 16:10:03 +0200656#ifdef WEBRTC_WIN
657 // Windows Core Audio based ADM needs to run on a COM initialized thread.
658 std::unique_ptr<webrtc_win::ScopedCOMInitializer> com_initializer_;
659#endif
660 AudioDeviceModule::AudioLayer audio_layer_;
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200661 std::unique_ptr<TaskQueueFactory> task_queue_factory_;
henrikaf2f91fa2017-03-17 04:26:22 -0700662 bool requirements_satisfied_ = true;
663 rtc::Event event_;
henrika5b6afc02018-09-05 14:34:40 +0200664 rtc::scoped_refptr<AudioDeviceModuleForTest> audio_device_;
henrikaf2f91fa2017-03-17 04:26:22 -0700665 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700666};
667
henrikaec9c7452018-06-08 16:10:03 +0200668// Instead of using the test fixture, verify that the different factory methods
669// work as intended.
Yves Gereyff060ee2019-09-11 15:53:01 +0200670TEST(MAYBE_AudioDeviceTestWin, ConstructDestructWithFactory) {
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200671 std::unique_ptr<TaskQueueFactory> task_queue_factory =
672 CreateDefaultTaskQueueFactory();
henrikaec9c7452018-06-08 16:10:03 +0200673 rtc::scoped_refptr<AudioDeviceModule> audio_device;
674 // The default factory should work for all platforms when a default ADM is
675 // requested.
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200676 audio_device = AudioDeviceModule::Create(
677 AudioDeviceModule::kPlatformDefaultAudio, task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200678 EXPECT_TRUE(audio_device);
679 audio_device = nullptr;
680#ifdef WEBRTC_WIN
681 // For Windows, the old factory method creates an ADM where the platform-
682 // specific parts are implemented by an AudioDeviceGeneric object. Verify
683 // that the old factory can't be used in combination with the latest audio
684 // layer AudioDeviceModule::kWindowsCoreAudio2.
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200685 audio_device = AudioDeviceModule::Create(
686 AudioDeviceModule::kWindowsCoreAudio2, task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200687 EXPECT_FALSE(audio_device);
688 audio_device = nullptr;
689 // Instead, ensure that the new dedicated factory method called
690 // CreateWindowsCoreAudioAudioDeviceModule() can be used on Windows and that
691 // it sets the audio layer to kWindowsCoreAudio2 implicitly. Note that, the
692 // new ADM for Windows must be created on a COM thread.
693 webrtc_win::ScopedCOMInitializer com_initializer(
694 webrtc_win::ScopedCOMInitializer::kMTA);
695 EXPECT_TRUE(com_initializer.Succeeded());
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200696 audio_device =
697 CreateWindowsCoreAudioAudioDeviceModule(task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200698 EXPECT_TRUE(audio_device);
699 AudioDeviceModule::AudioLayer audio_layer;
700 EXPECT_EQ(0, audio_device->ActiveAudioLayer(&audio_layer));
701 EXPECT_EQ(audio_layer, AudioDeviceModule::kWindowsCoreAudio2);
702#endif
703}
henrikaf2f91fa2017-03-17 04:26:22 -0700704
henrikaec9c7452018-06-08 16:10:03 +0200705// Uses the test fixture to create, initialize and destruct the ADM.
Yves Gereyff060ee2019-09-11 15:53:01 +0200706TEST_P(MAYBE_AudioDeviceTest, ConstructDestructDefault) {}
henrikaec9c7452018-06-08 16:10:03 +0200707
Yves Gereyff060ee2019-09-11 15:53:01 +0200708TEST_P(MAYBE_AudioDeviceTest, InitTerminate) {
henrikaf2f91fa2017-03-17 04:26:22 -0700709 SKIP_TEST_IF_NOT(requirements_satisfied());
710 // Initialization is part of the test fixture.
711 EXPECT_TRUE(audio_device()->Initialized());
712 EXPECT_EQ(0, audio_device()->Terminate());
713 EXPECT_FALSE(audio_device()->Initialized());
714}
715
henrikaec9c7452018-06-08 16:10:03 +0200716// Enumerate all available and active output devices.
Yves Gereyff060ee2019-09-11 15:53:01 +0200717TEST_P(MAYBE_AudioDeviceTest, PlayoutDeviceNames) {
henrikaf2f91fa2017-03-17 04:26:22 -0700718 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaec9c7452018-06-08 16:10:03 +0200719 char device_name[kAdmMaxDeviceNameSize];
720 char unique_id[kAdmMaxGuidSize];
721 int num_devices = audio_device()->PlayoutDevices();
722 if (NewWindowsAudioDeviceModuleIsUsed()) {
723 num_devices += 2;
724 }
725 EXPECT_GT(num_devices, 0);
726 for (int i = 0; i < num_devices; ++i) {
727 EXPECT_EQ(0, audio_device()->PlayoutDeviceName(i, device_name, unique_id));
728 }
729 EXPECT_EQ(-1, audio_device()->PlayoutDeviceName(num_devices, device_name,
730 unique_id));
731}
732
733// Enumerate all available and active input devices.
Yves Gereyff060ee2019-09-11 15:53:01 +0200734TEST_P(MAYBE_AudioDeviceTest, RecordingDeviceNames) {
henrikaec9c7452018-06-08 16:10:03 +0200735 SKIP_TEST_IF_NOT(requirements_satisfied());
736 char device_name[kAdmMaxDeviceNameSize];
737 char unique_id[kAdmMaxGuidSize];
738 int num_devices = audio_device()->RecordingDevices();
739 if (NewWindowsAudioDeviceModuleIsUsed()) {
740 num_devices += 2;
741 }
742 EXPECT_GT(num_devices, 0);
743 for (int i = 0; i < num_devices; ++i) {
744 EXPECT_EQ(0,
745 audio_device()->RecordingDeviceName(i, device_name, unique_id));
746 }
747 EXPECT_EQ(-1, audio_device()->RecordingDeviceName(num_devices, device_name,
748 unique_id));
749}
750
751// Counts number of active output devices and ensure that all can be selected.
Yves Gereyff060ee2019-09-11 15:53:01 +0200752TEST_P(MAYBE_AudioDeviceTest, SetPlayoutDevice) {
henrikaec9c7452018-06-08 16:10:03 +0200753 SKIP_TEST_IF_NOT(requirements_satisfied());
754 int num_devices = audio_device()->PlayoutDevices();
755 if (NewWindowsAudioDeviceModuleIsUsed()) {
756 num_devices += 2;
757 }
758 EXPECT_GT(num_devices, 0);
759 // Verify that all available playout devices can be set (not enabled yet).
760 for (int i = 0; i < num_devices; ++i) {
761 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(i));
762 }
763 EXPECT_EQ(-1, audio_device()->SetPlayoutDevice(num_devices));
764#ifdef WEBRTC_WIN
765 // On Windows, verify the alternative method where the user can select device
766 // by role.
767 EXPECT_EQ(
768 0, audio_device()->SetPlayoutDevice(AudioDeviceModule::kDefaultDevice));
769 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(
770 AudioDeviceModule::kDefaultCommunicationDevice));
771#endif
772}
773
774// Counts number of active input devices and ensure that all can be selected.
Yves Gereyff060ee2019-09-11 15:53:01 +0200775TEST_P(MAYBE_AudioDeviceTest, SetRecordingDevice) {
henrikaec9c7452018-06-08 16:10:03 +0200776 SKIP_TEST_IF_NOT(requirements_satisfied());
777 int num_devices = audio_device()->RecordingDevices();
778 if (NewWindowsAudioDeviceModuleIsUsed()) {
779 num_devices += 2;
780 }
781 EXPECT_GT(num_devices, 0);
782 // Verify that all available recording devices can be set (not enabled yet).
783 for (int i = 0; i < num_devices; ++i) {
784 EXPECT_EQ(0, audio_device()->SetRecordingDevice(i));
785 }
786 EXPECT_EQ(-1, audio_device()->SetRecordingDevice(num_devices));
787#ifdef WEBRTC_WIN
788 // On Windows, verify the alternative method where the user can select device
789 // by role.
790 EXPECT_EQ(
791 0, audio_device()->SetRecordingDevice(AudioDeviceModule::kDefaultDevice));
792 EXPECT_EQ(0, audio_device()->SetRecordingDevice(
793 AudioDeviceModule::kDefaultCommunicationDevice));
794#endif
795}
796
797// Tests Start/Stop playout without any registered audio callback.
Yves Gereyff060ee2019-09-11 15:53:01 +0200798TEST_P(MAYBE_AudioDeviceTest, StartStopPlayout) {
henrikaec9c7452018-06-08 16:10:03 +0200799 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaf2f91fa2017-03-17 04:26:22 -0700800 StartPlayout();
801 StopPlayout();
802}
803
804// Tests Start/Stop recording without any registered audio callback.
Yves Gereyff060ee2019-09-11 15:53:01 +0200805TEST_P(MAYBE_AudioDeviceTest, StartStopRecording) {
henrikaf2f91fa2017-03-17 04:26:22 -0700806 SKIP_TEST_IF_NOT(requirements_satisfied());
807 StartRecording();
808 StopRecording();
henrikaf2f91fa2017-03-17 04:26:22 -0700809}
810
henrika6b3e1a22017-09-25 16:34:30 +0200811// Tests Init/Stop/Init recording without any registered audio callback.
812// See https://bugs.chromium.org/p/webrtc/issues/detail?id=8041 for details
813// on why this test is useful.
Yves Gereyff060ee2019-09-11 15:53:01 +0200814TEST_P(MAYBE_AudioDeviceTest, InitStopInitRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200815 SKIP_TEST_IF_NOT(requirements_satisfied());
816 EXPECT_EQ(0, audio_device()->InitRecording());
817 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
818 StopRecording();
819 EXPECT_EQ(0, audio_device()->InitRecording());
820 StopRecording();
821}
822
henrikad4049462019-07-12 13:37:11 +0200823// Verify that additional attempts to initialize or start recording while
824// already being active works. Additional calls should just be ignored.
Yves Gereyff060ee2019-09-11 15:53:01 +0200825TEST_P(MAYBE_AudioDeviceTest, StartInitRecording) {
henrikad4049462019-07-12 13:37:11 +0200826 SKIP_TEST_IF_NOT(requirements_satisfied());
827 StartRecording();
828 // An additional attempt to initialize at this stage should be ignored.
829 EXPECT_EQ(0, audio_device()->InitRecording());
830 // Same for additional request to start recording while already active.
831 EXPECT_EQ(0, audio_device()->StartRecording());
832 StopRecording();
833}
834
835// Verify that additional attempts to initialize or start playou while
836// already being active works. Additional calls should just be ignored.
Yves Gereyff060ee2019-09-11 15:53:01 +0200837TEST_P(MAYBE_AudioDeviceTest, StartInitPlayout) {
henrikad4049462019-07-12 13:37:11 +0200838 SKIP_TEST_IF_NOT(requirements_satisfied());
839 StartPlayout();
840 // An additional attempt to initialize at this stage should be ignored.
841 EXPECT_EQ(0, audio_device()->InitPlayout());
842 // Same for additional request to start playout while already active.
843 EXPECT_EQ(0, audio_device()->StartPlayout());
844 StopPlayout();
845}
846
henrika6b3e1a22017-09-25 16:34:30 +0200847// Tests Init/Stop/Init recording while playout is active.
Yves Gereyff060ee2019-09-11 15:53:01 +0200848TEST_P(MAYBE_AudioDeviceTest, InitStopInitRecordingWhilePlaying) {
henrika6b3e1a22017-09-25 16:34:30 +0200849 SKIP_TEST_IF_NOT(requirements_satisfied());
850 StartPlayout();
851 EXPECT_EQ(0, audio_device()->InitRecording());
852 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
853 StopRecording();
854 EXPECT_EQ(0, audio_device()->InitRecording());
855 StopRecording();
856 StopPlayout();
857}
858
859// Tests Init/Stop/Init playout without any registered audio callback.
Yves Gereyff060ee2019-09-11 15:53:01 +0200860TEST_P(MAYBE_AudioDeviceTest, InitStopInitPlayout) {
henrika6b3e1a22017-09-25 16:34:30 +0200861 SKIP_TEST_IF_NOT(requirements_satisfied());
862 EXPECT_EQ(0, audio_device()->InitPlayout());
863 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
864 StopPlayout();
865 EXPECT_EQ(0, audio_device()->InitPlayout());
866 StopPlayout();
867}
868
869// Tests Init/Stop/Init playout while recording is active.
Yves Gereyff060ee2019-09-11 15:53:01 +0200870TEST_P(MAYBE_AudioDeviceTest, InitStopInitPlayoutWhileRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200871 SKIP_TEST_IF_NOT(requirements_satisfied());
872 StartRecording();
873 EXPECT_EQ(0, audio_device()->InitPlayout());
874 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
875 StopPlayout();
876 EXPECT_EQ(0, audio_device()->InitPlayout());
877 StopPlayout();
878 StopRecording();
879}
880
henrika5b6afc02018-09-05 14:34:40 +0200881// TODO(henrika): restart without intermediate destruction is currently only
882// supported on Windows.
883#ifdef WEBRTC_WIN
884// Tests Start/Stop playout followed by a second session (emulates a restart
885// triggered by a user using public APIs).
Yves Gereyff060ee2019-09-11 15:53:01 +0200886TEST_P(MAYBE_AudioDeviceTest, StartStopPlayoutWithExternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200887 SKIP_TEST_IF_NOT(requirements_satisfied());
888 StartPlayout();
889 StopPlayout();
890 // Restart playout without destroying the ADM in between. Ensures that we
891 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
892 StartPlayout();
893 StopPlayout();
894}
895
896// Tests Start/Stop recording followed by a second session (emulates a restart
897// triggered by a user using public APIs).
Yves Gereyff060ee2019-09-11 15:53:01 +0200898TEST_P(MAYBE_AudioDeviceTest, StartStopRecordingWithExternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200899 SKIP_TEST_IF_NOT(requirements_satisfied());
900 StartRecording();
901 StopRecording();
902 // Restart recording without destroying the ADM in between. Ensures that we
903 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
904 StartRecording();
905 StopRecording();
906}
907
908// Tests Start/Stop playout followed by a second session (emulates a restart
909// triggered by an internal callback e.g. corresponding to a device switch).
910// Note that, internal restart is only supported in combination with the latest
911// Windows ADM.
Yves Gereyff060ee2019-09-11 15:53:01 +0200912TEST_P(MAYBE_AudioDeviceTest, StartStopPlayoutWithInternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200913 SKIP_TEST_IF_NOT(requirements_satisfied());
914 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
915 return;
916 }
917 MockAudioTransport mock(TransportType::kPlay);
918 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
919 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
920 .Times(AtLeast(kNumCallbacks));
921 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
922 StartPlayout();
923 event()->Wait(kTestTimeOutInMilliseconds);
924 EXPECT_TRUE(audio_device()->Playing());
925 // Restart playout but without stopping the internal audio thread.
926 // This procedure uses a non-public test API and it emulates what happens
927 // inside the ADM when e.g. a device is removed.
928 EXPECT_EQ(0, audio_device()->RestartPlayoutInternally());
929
930 // Run basic tests of public APIs while a restart attempt is active.
931 // These calls should now be very thin and not trigger any new actions.
932 EXPECT_EQ(-1, audio_device()->StopPlayout());
933 EXPECT_TRUE(audio_device()->Playing());
934 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
935 EXPECT_EQ(0, audio_device()->InitPlayout());
936 EXPECT_EQ(0, audio_device()->StartPlayout());
937
938 // Wait until audio has restarted and a new sequence of audio callbacks
939 // becomes active.
940 // TODO(henrika): is it possible to verify that the internal state transition
941 // is Stop->Init->Start?
942 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
943 mock.ResetCallbackCounters();
944 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
945 .Times(AtLeast(kNumCallbacks));
946 event()->Wait(kTestTimeOutInMilliseconds);
947 EXPECT_TRUE(audio_device()->Playing());
948 // Stop playout and the audio thread after successful internal restart.
949 StopPlayout();
Yves Gereyb93a2452019-07-19 22:46:13 +0200950 PreTearDown();
henrika5b6afc02018-09-05 14:34:40 +0200951}
952
953// Tests Start/Stop recording followed by a second session (emulates a restart
954// triggered by an internal callback e.g. corresponding to a device switch).
955// Note that, internal restart is only supported in combination with the latest
956// Windows ADM.
Yves Gereyff060ee2019-09-11 15:53:01 +0200957TEST_P(MAYBE_AudioDeviceTest, StartStopRecordingWithInternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200958 SKIP_TEST_IF_NOT(requirements_satisfied());
959 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
960 return;
961 }
962 MockAudioTransport mock(TransportType::kRecord);
963 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
964 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
965 false, _))
966 .Times(AtLeast(kNumCallbacks));
967 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
968 StartRecording();
969 event()->Wait(kTestTimeOutInMilliseconds);
970 EXPECT_TRUE(audio_device()->Recording());
971 // Restart recording but without stopping the internal audio thread.
972 // This procedure uses a non-public test API and it emulates what happens
973 // inside the ADM when e.g. a device is removed.
974 EXPECT_EQ(0, audio_device()->RestartRecordingInternally());
975
976 // Run basic tests of public APIs while a restart attempt is active.
977 // These calls should now be very thin and not trigger any new actions.
978 EXPECT_EQ(-1, audio_device()->StopRecording());
979 EXPECT_TRUE(audio_device()->Recording());
980 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
981 EXPECT_EQ(0, audio_device()->InitRecording());
982 EXPECT_EQ(0, audio_device()->StartRecording());
983
984 // Wait until audio has restarted and a new sequence of audio callbacks
985 // becomes active.
986 // TODO(henrika): is it possible to verify that the internal state transition
987 // is Stop->Init->Start?
988 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
989 mock.ResetCallbackCounters();
990 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
991 false, _))
992 .Times(AtLeast(kNumCallbacks));
993 event()->Wait(kTestTimeOutInMilliseconds);
994 EXPECT_TRUE(audio_device()->Recording());
995 // Stop recording and the audio thread after successful internal restart.
996 StopRecording();
Yves Gereyb93a2452019-07-19 22:46:13 +0200997 PreTearDown();
henrika5b6afc02018-09-05 14:34:40 +0200998}
999#endif // #ifdef WEBRTC_WIN
1000
henrikaf2f91fa2017-03-17 04:26:22 -07001001// Start playout and verify that the native audio layer starts asking for real
1002// audio samples to play out using the NeedMorePlayData() callback.
1003// Note that we can't add expectations on audio parameters in EXPECT_CALL
1004// since parameter are not provided in the each callback. We therefore test and
1005// verify the parameters in the fake audio transport implementation instead.
Yves Gereyff060ee2019-09-11 15:53:01 +02001006TEST_P(MAYBE_AudioDeviceTest, StartPlayoutVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001007 SKIP_TEST_IF_NOT(requirements_satisfied());
1008 MockAudioTransport mock(TransportType::kPlay);
henrikae24991d2017-04-06 01:14:23 -07001009 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001010 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
1011 .Times(AtLeast(kNumCallbacks));
1012 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1013 StartPlayout();
1014 event()->Wait(kTestTimeOutInMilliseconds);
1015 StopPlayout();
Yves Gerey412282a2019-07-22 21:15:22 +02001016 PreTearDown();
henrikaf2f91fa2017-03-17 04:26:22 -07001017}
1018
Yves Gerey704c8c42019-08-13 22:32:46 +02001019// Don't run these tests in combination with sanitizers.
1020// They are already flaky *without* sanitizers.
1021// Sanitizers seem to increase flakiness (which brings noise),
1022// without reporting anything.
1023// TODO(webrtc:10867): Re-enable when flakiness fixed.
1024#if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
1025 defined(THREAD_SANITIZER)
1026#define MAYBE_StartRecordingVerifyCallbacks \
1027 DISABLED_StartRecordingVerifyCallbacks
1028#define MAYBE_StartPlayoutAndRecordingVerifyCallbacks \
1029 DISABLED_StartPlayoutAndRecordingVerifyCallbacks
1030#else
1031#define MAYBE_StartRecordingVerifyCallbacks StartRecordingVerifyCallbacks
1032#define MAYBE_StartPlayoutAndRecordingVerifyCallbacks \
1033 StartPlayoutAndRecordingVerifyCallbacks
1034#endif
1035
henrikaf2f91fa2017-03-17 04:26:22 -07001036// Start recording and verify that the native audio layer starts providing real
1037// audio samples using the RecordedDataIsAvailable() callback.
Yves Gereyff060ee2019-09-11 15:53:01 +02001038TEST_P(MAYBE_AudioDeviceTest, MAYBE_StartRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001039 SKIP_TEST_IF_NOT(requirements_satisfied());
1040 MockAudioTransport mock(TransportType::kRecord);
henrikae24991d2017-04-06 01:14:23 -07001041 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001042 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
1043 false, _))
1044 .Times(AtLeast(kNumCallbacks));
1045 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1046 StartRecording();
1047 event()->Wait(kTestTimeOutInMilliseconds);
1048 StopRecording();
Yves Gereyb93a2452019-07-19 22:46:13 +02001049 PreTearDown();
henrikaf2f91fa2017-03-17 04:26:22 -07001050}
1051
1052// Start playout and recording (full-duplex audio) and verify that audio is
1053// active in both directions.
Yves Gereyff060ee2019-09-11 15:53:01 +02001054TEST_P(MAYBE_AudioDeviceTest, MAYBE_StartPlayoutAndRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001055 SKIP_TEST_IF_NOT(requirements_satisfied());
1056 MockAudioTransport mock(TransportType::kPlayAndRecord);
henrikae24991d2017-04-06 01:14:23 -07001057 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001058 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
1059 .Times(AtLeast(kNumCallbacks));
1060 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
1061 false, _))
1062 .Times(AtLeast(kNumCallbacks));
1063 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1064 StartPlayout();
1065 StartRecording();
1066 event()->Wait(kTestTimeOutInMilliseconds);
1067 StopRecording();
1068 StopPlayout();
Yves Gereyb93a2452019-07-19 22:46:13 +02001069 PreTearDown();
henrikaf2f91fa2017-03-17 04:26:22 -07001070}
1071
henrikae24991d2017-04-06 01:14:23 -07001072// Start playout and recording and store recorded data in an intermediate FIFO
1073// buffer from which the playout side then reads its samples in the same order
1074// as they were stored. Under ideal circumstances, a callback sequence would
1075// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
1076// means 'packet played'. Under such conditions, the FIFO would contain max 1,
1077// with an average somewhere in (0,1) depending on how long the packets are
1078// buffered. However, under more realistic conditions, the size
1079// of the FIFO will vary more due to an unbalance between the two sides.
1080// This test tries to verify that the device maintains a balanced callback-
1081// sequence by running in loopback for a few seconds while measuring the size
1082// (max and average) of the FIFO. The size of the FIFO is increased by the
1083// recording side and decreased by the playout side.
Yves Gereyff060ee2019-09-11 15:53:01 +02001084TEST_P(MAYBE_AudioDeviceTest, RunPlayoutAndRecordingInFullDuplex) {
henrikae24991d2017-04-06 01:14:23 -07001085 SKIP_TEST_IF_NOT(requirements_satisfied());
1086 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1087 FifoAudioStream audio_stream;
1088 mock.HandleCallbacks(event(), &audio_stream,
1089 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
1090 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001091 // Run both sides using the same channel configuration to avoid conversions
1092 // between mono/stereo while running in full duplex mode. Also, some devices
1093 // (mainly on Windows) do not support mono.
1094 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1095 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
Gustaf Ullberg102b7282019-06-03 15:03:02 +02001096 // Mute speakers to prevent howling.
1097 EXPECT_EQ(0, audio_device()->SetSpeakerVolume(0));
henrikae24991d2017-04-06 01:14:23 -07001098 StartPlayout();
1099 StartRecording();
henrika714e5cd2017-04-20 08:03:11 -07001100 event()->Wait(static_cast<int>(
1101 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec)));
henrikae24991d2017-04-06 01:14:23 -07001102 StopRecording();
1103 StopPlayout();
Yves Gerey412282a2019-07-22 21:15:22 +02001104 // Avoid concurrent access to audio_stream.
1105 PreTearDown();
henrikae24991d2017-04-06 01:14:23 -07001106 // This thresholds is set rather high to accommodate differences in hardware
1107 // in several devices. The main idea is to capture cases where a very large
henrikab6ca7212017-10-06 12:47:52 +02001108 // latency is built up. See http://bugs.webrtc.org/7744 for examples on
1109 // bots where relatively large average latencies can happen.
1110 EXPECT_LE(audio_stream.average_size(), 25u);
henrikae24991d2017-04-06 01:14:23 -07001111 PRINT("\n");
1112}
1113
henrika5b6afc02018-09-05 14:34:40 +02001114// Runs audio in full duplex until user hits Enter. Intended as a manual test
1115// to ensure that the audio quality is good and that real device switches works
1116// as intended.
Yves Gereyff060ee2019-09-11 15:53:01 +02001117TEST_P(MAYBE_AudioDeviceTest,
henrika5b6afc02018-09-05 14:34:40 +02001118 DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey) {
1119 SKIP_TEST_IF_NOT(requirements_satisfied());
1120 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
1121 return;
1122 }
1123 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1124 FifoAudioStream audio_stream;
1125 mock.HandleCallbacks(&audio_stream);
1126 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1127 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1128 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
1129 // Ensure that the sample rate for both directions are identical so that we
1130 // always can listen to our own voice. Will lead to rate conversion (and
1131 // higher latency) if the native sample rate is not 48kHz.
1132 EXPECT_EQ(0, audio_device()->SetPlayoutSampleRate(48000));
1133 EXPECT_EQ(0, audio_device()->SetRecordingSampleRate(48000));
1134 StartPlayout();
1135 StartRecording();
1136 do {
1137 PRINT("Loopback audio is active at 48kHz. Press Enter to stop.\n");
1138 } while (getchar() != '\n');
1139 StopRecording();
1140 StopPlayout();
Yves Gereyb93a2452019-07-19 22:46:13 +02001141 PreTearDown();
henrika5b6afc02018-09-05 14:34:40 +02001142}
1143
henrika714e5cd2017-04-20 08:03:11 -07001144// Measures loopback latency and reports the min, max and average values for
1145// a full duplex audio session.
1146// The latency is measured like so:
1147// - Insert impulses periodically on the output side.
1148// - Detect the impulses on the input side.
1149// - Measure the time difference between the transmit time and receive time.
1150// - Store time differences in a vector and calculate min, max and average.
1151// This test needs the '--gtest_also_run_disabled_tests' flag to run and also
1152// some sort of audio feedback loop. E.g. a headset where the mic is placed
1153// close to the speaker to ensure highest possible echo. It is also recommended
1154// to run the test at highest possible output volume.
Yves Gereyff060ee2019-09-11 15:53:01 +02001155TEST_P(MAYBE_AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
henrika714e5cd2017-04-20 08:03:11 -07001156 SKIP_TEST_IF_NOT(requirements_satisfied());
1157 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1158 LatencyAudioStream audio_stream;
1159 mock.HandleCallbacks(event(), &audio_stream,
1160 kMeasureLatencyTimeInSec * kNumCallbacksPerSecond);
1161 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001162 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1163 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrika714e5cd2017-04-20 08:03:11 -07001164 StartPlayout();
1165 StartRecording();
1166 event()->Wait(static_cast<int>(
1167 std::max(kTestTimeOutInMilliseconds, 1000 * kMeasureLatencyTimeInSec)));
1168 StopRecording();
1169 StopPlayout();
Yves Gerey412282a2019-07-22 21:15:22 +02001170 // Avoid concurrent access to audio_stream.
1171 PreTearDown();
henrikac7d93582018-09-14 15:37:34 +02001172 // Verify that a sufficient number of transmitted impulses are detected.
1173 EXPECT_GE(audio_stream.num_latency_values(),
henrika714e5cd2017-04-20 08:03:11 -07001174 static_cast<size_t>(
henrikac7d93582018-09-14 15:37:34 +02001175 kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 2));
henrika714e5cd2017-04-20 08:03:11 -07001176 // Print out min, max and average delay values for debugging purposes.
1177 audio_stream.PrintResults();
1178}
1179
henrikaec9c7452018-06-08 16:10:03 +02001180#ifdef WEBRTC_WIN
1181// Test two different audio layers (or rather two different Core Audio
1182// implementations) for Windows.
Mirko Bonadeic84f6612019-01-31 12:20:57 +01001183INSTANTIATE_TEST_SUITE_P(
henrikaec9c7452018-06-08 16:10:03 +02001184 AudioLayerWin,
Yves Gereyff060ee2019-09-11 15:53:01 +02001185 MAYBE_AudioDeviceTest,
henrikaec9c7452018-06-08 16:10:03 +02001186 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio,
1187 AudioDeviceModule::kWindowsCoreAudio2));
1188#else
1189// For all platforms but Windows, only test the default audio layer.
Mirko Bonadeic84f6612019-01-31 12:20:57 +01001190INSTANTIATE_TEST_SUITE_P(
henrikaec9c7452018-06-08 16:10:03 +02001191 AudioLayer,
Yves Gereyff060ee2019-09-11 15:53:01 +02001192 MAYBE_AudioDeviceTest,
henrikaec9c7452018-06-08 16:10:03 +02001193 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio));
1194#endif
1195
henrikaf2f91fa2017-03-17 04:26:22 -07001196} // namespace webrtc