blob: 48e54c7dc47a8280ac56002805d3afeb0e056dfd [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
504// Don't run these tests in combination with sanitizers.
505// TODO(webrtc:9778): Re-enable on THREAD_SANITIZER?
506#if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
507 defined(THREAD_SANITIZER)
508#define MAYBE_AudioDeviceTest DISABLED_AudioDeviceTest
509#else
510#define MAYBE_AudioDeviceTest AudioDeviceTest
511#endif
512
513class MAYBE_AudioDeviceTest
henrikaec9c7452018-06-08 16:10:03 +0200514 : public ::testing::TestWithParam<webrtc::AudioDeviceModule::AudioLayer> {
henrikaf2f91fa2017-03-17 04:26:22 -0700515 protected:
Yves Gerey1afe6572019-07-18 22:01:09 +0200516 MAYBE_AudioDeviceTest()
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200517 : audio_layer_(GetParam()),
518 task_queue_factory_(CreateDefaultTaskQueueFactory()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700519 rtc::LogMessage::LogToDebug(rtc::LS_INFO);
520 // Add extra logging fields here if needed for debugging.
henrikaec9c7452018-06-08 16:10:03 +0200521 rtc::LogMessage::LogTimestamps();
522 rtc::LogMessage::LogThreads();
523 audio_device_ = CreateAudioDevice();
henrikaf2f91fa2017-03-17 04:26:22 -0700524 EXPECT_NE(audio_device_.get(), nullptr);
525 AudioDeviceModule::AudioLayer audio_layer;
maxmorin33bf69a2017-03-23 04:06:53 -0700526 int got_platform_audio_layer =
527 audio_device_->ActiveAudioLayer(&audio_layer);
henrika919dc2e2017-10-12 14:24:55 +0200528 // First, ensure that a valid audio layer can be activated.
529 if (got_platform_audio_layer != 0) {
henrikaf2f91fa2017-03-17 04:26:22 -0700530 requirements_satisfied_ = false;
531 }
henrika919dc2e2017-10-12 14:24:55 +0200532 // Next, verify that the ADM can be initialized.
henrikaf2f91fa2017-03-17 04:26:22 -0700533 if (requirements_satisfied_) {
henrika919dc2e2017-10-12 14:24:55 +0200534 requirements_satisfied_ = (audio_device_->Init() == 0);
535 }
536 // Finally, ensure that at least one valid device exists in each direction.
537 if (requirements_satisfied_) {
henrikaf2f91fa2017-03-17 04:26:22 -0700538 const int16_t num_playout_devices = audio_device_->PlayoutDevices();
539 const int16_t num_record_devices = audio_device_->RecordingDevices();
540 requirements_satisfied_ =
541 num_playout_devices > 0 && num_record_devices > 0;
542 }
henrikaf2f91fa2017-03-17 04:26:22 -0700543 if (requirements_satisfied_) {
henrika5773ad32018-09-21 14:53:10 +0200544 EXPECT_EQ(0, audio_device_->SetPlayoutDevice(AUDIO_DEVICE_ID));
henrikaf2f91fa2017-03-17 04:26:22 -0700545 EXPECT_EQ(0, audio_device_->InitSpeaker());
henrikaf2f91fa2017-03-17 04:26:22 -0700546 EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
547 EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
henrika5773ad32018-09-21 14:53:10 +0200548 EXPECT_EQ(0, audio_device_->SetRecordingDevice(AUDIO_DEVICE_ID));
549 EXPECT_EQ(0, audio_device_->InitMicrophone());
henrika0238ba82017-03-28 04:38:29 -0700550 // Avoid asking for input stereo support and always record in mono
551 // since asking can cause issues in combination with remote desktop.
552 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
553 // details.
554 EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
henrikaf2f91fa2017-03-17 04:26:22 -0700555 }
556 }
557
Yves Gerey1afe6572019-07-18 22:01:09 +0200558 virtual ~MAYBE_AudioDeviceTest() {
henrikaf2f91fa2017-03-17 04:26:22 -0700559 if (audio_device_) {
560 EXPECT_EQ(0, audio_device_->Terminate());
561 }
562 }
563
564 bool requirements_satisfied() const { return requirements_satisfied_; }
565 rtc::Event* event() { return &event_; }
henrika5b6afc02018-09-05 14:34:40 +0200566 AudioDeviceModule::AudioLayer audio_layer() const { return audio_layer_; }
henrikaf2f91fa2017-03-17 04:26:22 -0700567
henrika5b6afc02018-09-05 14:34:40 +0200568 // AudioDeviceModuleForTest extends the default ADM interface with some extra
569 // test methods. Intended for usage in tests only and requires a unique
570 // factory method. See CreateAudioDevice() for details.
571 const rtc::scoped_refptr<AudioDeviceModuleForTest>& audio_device() const {
henrikaf2f91fa2017-03-17 04:26:22 -0700572 return audio_device_;
573 }
574
henrika5b6afc02018-09-05 14:34:40 +0200575 rtc::scoped_refptr<AudioDeviceModuleForTest> CreateAudioDevice() {
henrikaec9c7452018-06-08 16:10:03 +0200576 // Use the default factory for kPlatformDefaultAudio and a special factory
henrika5b6afc02018-09-05 14:34:40 +0200577 // CreateWindowsCoreAudioAudioDeviceModuleForTest() for kWindowsCoreAudio2.
henrikaec9c7452018-06-08 16:10:03 +0200578 // The value of |audio_layer_| is set at construction by GetParam() and two
579 // different layers are tested on Windows only.
580 if (audio_layer_ == AudioDeviceModule::kPlatformDefaultAudio) {
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200581 return AudioDeviceModule::CreateForTest(audio_layer_,
582 task_queue_factory_.get());
henrikaec9c7452018-06-08 16:10:03 +0200583 } else if (audio_layer_ == AudioDeviceModule::kWindowsCoreAudio2) {
584#ifdef WEBRTC_WIN
585 // We must initialize the COM library on a thread before we calling any of
586 // the library functions. All COM functions in the ADM will return
587 // CO_E_NOTINITIALIZED otherwise.
Karl Wiberg918f50c2018-07-05 11:40:33 +0200588 com_initializer_ = absl::make_unique<webrtc_win::ScopedCOMInitializer>(
henrikaec9c7452018-06-08 16:10:03 +0200589 webrtc_win::ScopedCOMInitializer::kMTA);
590 EXPECT_TRUE(com_initializer_->Succeeded());
591 EXPECT_TRUE(webrtc_win::core_audio_utility::IsSupported());
592 EXPECT_TRUE(webrtc_win::core_audio_utility::IsMMCSSSupported());
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200593 return CreateWindowsCoreAudioAudioDeviceModuleForTest(
henrikad8c6ec42019-07-18 15:17:28 +0200594 task_queue_factory_.get(), true);
henrikaec9c7452018-06-08 16:10:03 +0200595#else
596 return nullptr;
597#endif
598 } else {
599 return nullptr;
600 }
601 }
602
henrikaf2f91fa2017-03-17 04:26:22 -0700603 void StartPlayout() {
604 EXPECT_FALSE(audio_device()->Playing());
605 EXPECT_EQ(0, audio_device()->InitPlayout());
606 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
607 EXPECT_EQ(0, audio_device()->StartPlayout());
608 EXPECT_TRUE(audio_device()->Playing());
609 }
610
611 void StopPlayout() {
612 EXPECT_EQ(0, audio_device()->StopPlayout());
613 EXPECT_FALSE(audio_device()->Playing());
614 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
615 }
616
617 void StartRecording() {
618 EXPECT_FALSE(audio_device()->Recording());
619 EXPECT_EQ(0, audio_device()->InitRecording());
620 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
621 EXPECT_EQ(0, audio_device()->StartRecording());
622 EXPECT_TRUE(audio_device()->Recording());
623 }
624
625 void StopRecording() {
626 EXPECT_EQ(0, audio_device()->StopRecording());
627 EXPECT_FALSE(audio_device()->Recording());
628 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
629 }
630
henrikaec9c7452018-06-08 16:10:03 +0200631 bool NewWindowsAudioDeviceModuleIsUsed() {
632#ifdef WEBRTC_WIN
633 AudioDeviceModule::AudioLayer audio_layer;
634 EXPECT_EQ(0, audio_device()->ActiveAudioLayer(&audio_layer));
635 if (audio_layer == AudioDeviceModule::kWindowsCoreAudio2) {
636 // Default device is always added as first element in the list and the
637 // default communication device as the second element. Hence, the list
638 // contains two extra elements in this case.
639 return true;
640 }
641#endif
642 return false;
643 }
644
henrikaf2f91fa2017-03-17 04:26:22 -0700645 private:
henrikaec9c7452018-06-08 16:10:03 +0200646#ifdef WEBRTC_WIN
647 // Windows Core Audio based ADM needs to run on a COM initialized thread.
648 std::unique_ptr<webrtc_win::ScopedCOMInitializer> com_initializer_;
649#endif
650 AudioDeviceModule::AudioLayer audio_layer_;
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200651 std::unique_ptr<TaskQueueFactory> task_queue_factory_;
henrikaf2f91fa2017-03-17 04:26:22 -0700652 bool requirements_satisfied_ = true;
653 rtc::Event event_;
henrika5b6afc02018-09-05 14:34:40 +0200654 rtc::scoped_refptr<AudioDeviceModuleForTest> audio_device_;
henrikaf2f91fa2017-03-17 04:26:22 -0700655 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700656};
657
henrikaec9c7452018-06-08 16:10:03 +0200658// Instead of using the test fixture, verify that the different factory methods
659// work as intended.
660TEST(AudioDeviceTestWin, ConstructDestructWithFactory) {
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200661 std::unique_ptr<TaskQueueFactory> task_queue_factory =
662 CreateDefaultTaskQueueFactory();
henrikaec9c7452018-06-08 16:10:03 +0200663 rtc::scoped_refptr<AudioDeviceModule> audio_device;
664 // The default factory should work for all platforms when a default ADM is
665 // requested.
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200666 audio_device = AudioDeviceModule::Create(
667 AudioDeviceModule::kPlatformDefaultAudio, task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200668 EXPECT_TRUE(audio_device);
669 audio_device = nullptr;
670#ifdef WEBRTC_WIN
671 // For Windows, the old factory method creates an ADM where the platform-
672 // specific parts are implemented by an AudioDeviceGeneric object. Verify
673 // that the old factory can't be used in combination with the latest audio
674 // layer AudioDeviceModule::kWindowsCoreAudio2.
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200675 audio_device = AudioDeviceModule::Create(
676 AudioDeviceModule::kWindowsCoreAudio2, task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200677 EXPECT_FALSE(audio_device);
678 audio_device = nullptr;
679 // Instead, ensure that the new dedicated factory method called
680 // CreateWindowsCoreAudioAudioDeviceModule() can be used on Windows and that
681 // it sets the audio layer to kWindowsCoreAudio2 implicitly. Note that, the
682 // new ADM for Windows must be created on a COM thread.
683 webrtc_win::ScopedCOMInitializer com_initializer(
684 webrtc_win::ScopedCOMInitializer::kMTA);
685 EXPECT_TRUE(com_initializer.Succeeded());
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200686 audio_device =
687 CreateWindowsCoreAudioAudioDeviceModule(task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200688 EXPECT_TRUE(audio_device);
689 AudioDeviceModule::AudioLayer audio_layer;
690 EXPECT_EQ(0, audio_device->ActiveAudioLayer(&audio_layer));
691 EXPECT_EQ(audio_layer, AudioDeviceModule::kWindowsCoreAudio2);
692#endif
693}
henrikaf2f91fa2017-03-17 04:26:22 -0700694
henrikaec9c7452018-06-08 16:10:03 +0200695// Uses the test fixture to create, initialize and destruct the ADM.
Yves Gerey1afe6572019-07-18 22:01:09 +0200696TEST_P(MAYBE_AudioDeviceTest, ConstructDestructDefault) {}
henrikaec9c7452018-06-08 16:10:03 +0200697
Yves Gerey1afe6572019-07-18 22:01:09 +0200698TEST_P(MAYBE_AudioDeviceTest, InitTerminate) {
henrikaf2f91fa2017-03-17 04:26:22 -0700699 SKIP_TEST_IF_NOT(requirements_satisfied());
700 // Initialization is part of the test fixture.
701 EXPECT_TRUE(audio_device()->Initialized());
702 EXPECT_EQ(0, audio_device()->Terminate());
703 EXPECT_FALSE(audio_device()->Initialized());
704}
705
henrikaec9c7452018-06-08 16:10:03 +0200706// Enumerate all available and active output devices.
Yves Gerey1afe6572019-07-18 22:01:09 +0200707TEST_P(MAYBE_AudioDeviceTest, PlayoutDeviceNames) {
henrikaf2f91fa2017-03-17 04:26:22 -0700708 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaec9c7452018-06-08 16:10:03 +0200709 char device_name[kAdmMaxDeviceNameSize];
710 char unique_id[kAdmMaxGuidSize];
711 int num_devices = audio_device()->PlayoutDevices();
712 if (NewWindowsAudioDeviceModuleIsUsed()) {
713 num_devices += 2;
714 }
715 EXPECT_GT(num_devices, 0);
716 for (int i = 0; i < num_devices; ++i) {
717 EXPECT_EQ(0, audio_device()->PlayoutDeviceName(i, device_name, unique_id));
718 }
719 EXPECT_EQ(-1, audio_device()->PlayoutDeviceName(num_devices, device_name,
720 unique_id));
721}
722
723// Enumerate all available and active input devices.
Yves Gerey1afe6572019-07-18 22:01:09 +0200724TEST_P(MAYBE_AudioDeviceTest, RecordingDeviceNames) {
henrikaec9c7452018-06-08 16:10:03 +0200725 SKIP_TEST_IF_NOT(requirements_satisfied());
726 char device_name[kAdmMaxDeviceNameSize];
727 char unique_id[kAdmMaxGuidSize];
728 int num_devices = audio_device()->RecordingDevices();
729 if (NewWindowsAudioDeviceModuleIsUsed()) {
730 num_devices += 2;
731 }
732 EXPECT_GT(num_devices, 0);
733 for (int i = 0; i < num_devices; ++i) {
734 EXPECT_EQ(0,
735 audio_device()->RecordingDeviceName(i, device_name, unique_id));
736 }
737 EXPECT_EQ(-1, audio_device()->RecordingDeviceName(num_devices, device_name,
738 unique_id));
739}
740
741// Counts number of active output devices and ensure that all can be selected.
Yves Gerey1afe6572019-07-18 22:01:09 +0200742TEST_P(MAYBE_AudioDeviceTest, SetPlayoutDevice) {
henrikaec9c7452018-06-08 16:10:03 +0200743 SKIP_TEST_IF_NOT(requirements_satisfied());
744 int num_devices = audio_device()->PlayoutDevices();
745 if (NewWindowsAudioDeviceModuleIsUsed()) {
746 num_devices += 2;
747 }
748 EXPECT_GT(num_devices, 0);
749 // Verify that all available playout devices can be set (not enabled yet).
750 for (int i = 0; i < num_devices; ++i) {
751 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(i));
752 }
753 EXPECT_EQ(-1, audio_device()->SetPlayoutDevice(num_devices));
754#ifdef WEBRTC_WIN
755 // On Windows, verify the alternative method where the user can select device
756 // by role.
757 EXPECT_EQ(
758 0, audio_device()->SetPlayoutDevice(AudioDeviceModule::kDefaultDevice));
759 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(
760 AudioDeviceModule::kDefaultCommunicationDevice));
761#endif
762}
763
764// Counts number of active input devices and ensure that all can be selected.
Yves Gerey1afe6572019-07-18 22:01:09 +0200765TEST_P(MAYBE_AudioDeviceTest, SetRecordingDevice) {
henrikaec9c7452018-06-08 16:10:03 +0200766 SKIP_TEST_IF_NOT(requirements_satisfied());
767 int num_devices = audio_device()->RecordingDevices();
768 if (NewWindowsAudioDeviceModuleIsUsed()) {
769 num_devices += 2;
770 }
771 EXPECT_GT(num_devices, 0);
772 // Verify that all available recording devices can be set (not enabled yet).
773 for (int i = 0; i < num_devices; ++i) {
774 EXPECT_EQ(0, audio_device()->SetRecordingDevice(i));
775 }
776 EXPECT_EQ(-1, audio_device()->SetRecordingDevice(num_devices));
777#ifdef WEBRTC_WIN
778 // On Windows, verify the alternative method where the user can select device
779 // by role.
780 EXPECT_EQ(
781 0, audio_device()->SetRecordingDevice(AudioDeviceModule::kDefaultDevice));
782 EXPECT_EQ(0, audio_device()->SetRecordingDevice(
783 AudioDeviceModule::kDefaultCommunicationDevice));
784#endif
785}
786
787// Tests Start/Stop playout without any registered audio callback.
Yves Gerey1afe6572019-07-18 22:01:09 +0200788TEST_P(MAYBE_AudioDeviceTest, StartStopPlayout) {
henrikaec9c7452018-06-08 16:10:03 +0200789 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaf2f91fa2017-03-17 04:26:22 -0700790 StartPlayout();
791 StopPlayout();
792}
793
794// Tests Start/Stop recording without any registered audio callback.
Yves Gerey1afe6572019-07-18 22:01:09 +0200795TEST_P(MAYBE_AudioDeviceTest, StartStopRecording) {
henrikaf2f91fa2017-03-17 04:26:22 -0700796 SKIP_TEST_IF_NOT(requirements_satisfied());
797 StartRecording();
798 StopRecording();
henrikaf2f91fa2017-03-17 04:26:22 -0700799}
800
henrika6b3e1a22017-09-25 16:34:30 +0200801// Tests Init/Stop/Init recording without any registered audio callback.
802// See https://bugs.chromium.org/p/webrtc/issues/detail?id=8041 for details
803// on why this test is useful.
Yves Gerey1afe6572019-07-18 22:01:09 +0200804TEST_P(MAYBE_AudioDeviceTest, InitStopInitRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200805 SKIP_TEST_IF_NOT(requirements_satisfied());
806 EXPECT_EQ(0, audio_device()->InitRecording());
807 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
808 StopRecording();
809 EXPECT_EQ(0, audio_device()->InitRecording());
810 StopRecording();
811}
812
henrikad4049462019-07-12 13:37:11 +0200813// Verify that additional attempts to initialize or start recording while
814// already being active works. Additional calls should just be ignored.
Yves Gerey1afe6572019-07-18 22:01:09 +0200815TEST_P(MAYBE_AudioDeviceTest, StartInitRecording) {
henrikad4049462019-07-12 13:37:11 +0200816 SKIP_TEST_IF_NOT(requirements_satisfied());
817 StartRecording();
818 // An additional attempt to initialize at this stage should be ignored.
819 EXPECT_EQ(0, audio_device()->InitRecording());
820 // Same for additional request to start recording while already active.
821 EXPECT_EQ(0, audio_device()->StartRecording());
822 StopRecording();
823}
824
825// Verify that additional attempts to initialize or start playou while
826// already being active works. Additional calls should just be ignored.
Yves Gerey1afe6572019-07-18 22:01:09 +0200827TEST_P(MAYBE_AudioDeviceTest, StartInitPlayout) {
henrikad4049462019-07-12 13:37:11 +0200828 SKIP_TEST_IF_NOT(requirements_satisfied());
829 StartPlayout();
830 // An additional attempt to initialize at this stage should be ignored.
831 EXPECT_EQ(0, audio_device()->InitPlayout());
832 // Same for additional request to start playout while already active.
833 EXPECT_EQ(0, audio_device()->StartPlayout());
834 StopPlayout();
835}
836
henrika6b3e1a22017-09-25 16:34:30 +0200837// Tests Init/Stop/Init recording while playout is active.
Yves Gerey1afe6572019-07-18 22:01:09 +0200838TEST_P(MAYBE_AudioDeviceTest, InitStopInitRecordingWhilePlaying) {
henrika6b3e1a22017-09-25 16:34:30 +0200839 SKIP_TEST_IF_NOT(requirements_satisfied());
840 StartPlayout();
841 EXPECT_EQ(0, audio_device()->InitRecording());
842 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
843 StopRecording();
844 EXPECT_EQ(0, audio_device()->InitRecording());
845 StopRecording();
846 StopPlayout();
847}
848
849// Tests Init/Stop/Init playout without any registered audio callback.
Yves Gerey1afe6572019-07-18 22:01:09 +0200850TEST_P(MAYBE_AudioDeviceTest, InitStopInitPlayout) {
henrika6b3e1a22017-09-25 16:34:30 +0200851 SKIP_TEST_IF_NOT(requirements_satisfied());
852 EXPECT_EQ(0, audio_device()->InitPlayout());
853 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
854 StopPlayout();
855 EXPECT_EQ(0, audio_device()->InitPlayout());
856 StopPlayout();
857}
858
859// Tests Init/Stop/Init playout while recording is active.
Yves Gerey1afe6572019-07-18 22:01:09 +0200860TEST_P(MAYBE_AudioDeviceTest, InitStopInitPlayoutWhileRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200861 SKIP_TEST_IF_NOT(requirements_satisfied());
862 StartRecording();
863 EXPECT_EQ(0, audio_device()->InitPlayout());
864 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
865 StopPlayout();
866 EXPECT_EQ(0, audio_device()->InitPlayout());
867 StopPlayout();
868 StopRecording();
869}
870
henrika5b6afc02018-09-05 14:34:40 +0200871// TODO(henrika): restart without intermediate destruction is currently only
872// supported on Windows.
873#ifdef WEBRTC_WIN
874// Tests Start/Stop playout followed by a second session (emulates a restart
875// triggered by a user using public APIs).
Yves Gerey1afe6572019-07-18 22:01:09 +0200876TEST_P(MAYBE_AudioDeviceTest, StartStopPlayoutWithExternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200877 SKIP_TEST_IF_NOT(requirements_satisfied());
878 StartPlayout();
879 StopPlayout();
880 // Restart playout without destroying the ADM in between. Ensures that we
881 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
882 StartPlayout();
883 StopPlayout();
884}
885
886// Tests Start/Stop recording followed by a second session (emulates a restart
887// triggered by a user using public APIs).
Yves Gerey1afe6572019-07-18 22:01:09 +0200888TEST_P(MAYBE_AudioDeviceTest, StartStopRecordingWithExternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200889 SKIP_TEST_IF_NOT(requirements_satisfied());
890 StartRecording();
891 StopRecording();
892 // Restart recording without destroying the ADM in between. Ensures that we
893 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
894 StartRecording();
895 StopRecording();
896}
897
898// Tests Start/Stop playout followed by a second session (emulates a restart
899// triggered by an internal callback e.g. corresponding to a device switch).
900// Note that, internal restart is only supported in combination with the latest
901// Windows ADM.
Yves Gerey1afe6572019-07-18 22:01:09 +0200902TEST_P(MAYBE_AudioDeviceTest, StartStopPlayoutWithInternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200903 SKIP_TEST_IF_NOT(requirements_satisfied());
904 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
905 return;
906 }
907 MockAudioTransport mock(TransportType::kPlay);
908 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
909 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
910 .Times(AtLeast(kNumCallbacks));
911 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
912 StartPlayout();
913 event()->Wait(kTestTimeOutInMilliseconds);
914 EXPECT_TRUE(audio_device()->Playing());
915 // Restart playout but without stopping the internal audio thread.
916 // This procedure uses a non-public test API and it emulates what happens
917 // inside the ADM when e.g. a device is removed.
918 EXPECT_EQ(0, audio_device()->RestartPlayoutInternally());
919
920 // Run basic tests of public APIs while a restart attempt is active.
921 // These calls should now be very thin and not trigger any new actions.
922 EXPECT_EQ(-1, audio_device()->StopPlayout());
923 EXPECT_TRUE(audio_device()->Playing());
924 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
925 EXPECT_EQ(0, audio_device()->InitPlayout());
926 EXPECT_EQ(0, audio_device()->StartPlayout());
927
928 // Wait until audio has restarted and a new sequence of audio callbacks
929 // becomes active.
930 // TODO(henrika): is it possible to verify that the internal state transition
931 // is Stop->Init->Start?
932 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
933 mock.ResetCallbackCounters();
934 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
935 .Times(AtLeast(kNumCallbacks));
936 event()->Wait(kTestTimeOutInMilliseconds);
937 EXPECT_TRUE(audio_device()->Playing());
938 // Stop playout and the audio thread after successful internal restart.
939 StopPlayout();
940}
941
942// Tests Start/Stop recording followed by a second session (emulates a restart
943// triggered by an internal callback e.g. corresponding to a device switch).
944// Note that, internal restart is only supported in combination with the latest
945// Windows ADM.
Yves Gerey1afe6572019-07-18 22:01:09 +0200946TEST_P(MAYBE_AudioDeviceTest, StartStopRecordingWithInternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200947 SKIP_TEST_IF_NOT(requirements_satisfied());
948 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
949 return;
950 }
951 MockAudioTransport mock(TransportType::kRecord);
952 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
953 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
954 false, _))
955 .Times(AtLeast(kNumCallbacks));
956 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
957 StartRecording();
958 event()->Wait(kTestTimeOutInMilliseconds);
959 EXPECT_TRUE(audio_device()->Recording());
960 // Restart recording but without stopping the internal audio thread.
961 // This procedure uses a non-public test API and it emulates what happens
962 // inside the ADM when e.g. a device is removed.
963 EXPECT_EQ(0, audio_device()->RestartRecordingInternally());
964
965 // Run basic tests of public APIs while a restart attempt is active.
966 // These calls should now be very thin and not trigger any new actions.
967 EXPECT_EQ(-1, audio_device()->StopRecording());
968 EXPECT_TRUE(audio_device()->Recording());
969 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
970 EXPECT_EQ(0, audio_device()->InitRecording());
971 EXPECT_EQ(0, audio_device()->StartRecording());
972
973 // Wait until audio has restarted and a new sequence of audio callbacks
974 // becomes active.
975 // TODO(henrika): is it possible to verify that the internal state transition
976 // is Stop->Init->Start?
977 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
978 mock.ResetCallbackCounters();
979 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
980 false, _))
981 .Times(AtLeast(kNumCallbacks));
982 event()->Wait(kTestTimeOutInMilliseconds);
983 EXPECT_TRUE(audio_device()->Recording());
984 // Stop recording and the audio thread after successful internal restart.
985 StopRecording();
986}
987#endif // #ifdef WEBRTC_WIN
988
henrikaf2f91fa2017-03-17 04:26:22 -0700989// Start playout and verify that the native audio layer starts asking for real
990// audio samples to play out using the NeedMorePlayData() callback.
991// Note that we can't add expectations on audio parameters in EXPECT_CALL
992// since parameter are not provided in the each callback. We therefore test and
993// verify the parameters in the fake audio transport implementation instead.
Yves Gerey1afe6572019-07-18 22:01:09 +0200994TEST_P(MAYBE_AudioDeviceTest, StartPlayoutVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700995 SKIP_TEST_IF_NOT(requirements_satisfied());
996 MockAudioTransport mock(TransportType::kPlay);
henrikae24991d2017-04-06 01:14:23 -0700997 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700998 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
999 .Times(AtLeast(kNumCallbacks));
1000 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1001 StartPlayout();
1002 event()->Wait(kTestTimeOutInMilliseconds);
1003 StopPlayout();
1004}
1005
1006// Start recording and verify that the native audio layer starts providing real
1007// audio samples using the RecordedDataIsAvailable() callback.
Yves Gerey1afe6572019-07-18 22:01:09 +02001008TEST_P(MAYBE_AudioDeviceTest, StartRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001009 SKIP_TEST_IF_NOT(requirements_satisfied());
1010 MockAudioTransport mock(TransportType::kRecord);
henrikae24991d2017-04-06 01:14:23 -07001011 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001012 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
1013 false, _))
1014 .Times(AtLeast(kNumCallbacks));
1015 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1016 StartRecording();
1017 event()->Wait(kTestTimeOutInMilliseconds);
1018 StopRecording();
1019}
1020
1021// Start playout and recording (full-duplex audio) and verify that audio is
1022// active in both directions.
Yves Gerey1afe6572019-07-18 22:01:09 +02001023TEST_P(MAYBE_AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001024 SKIP_TEST_IF_NOT(requirements_satisfied());
1025 MockAudioTransport mock(TransportType::kPlayAndRecord);
henrikae24991d2017-04-06 01:14:23 -07001026 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001027 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
1028 .Times(AtLeast(kNumCallbacks));
1029 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
1030 false, _))
1031 .Times(AtLeast(kNumCallbacks));
1032 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1033 StartPlayout();
1034 StartRecording();
1035 event()->Wait(kTestTimeOutInMilliseconds);
1036 StopRecording();
1037 StopPlayout();
1038}
1039
henrikae24991d2017-04-06 01:14:23 -07001040// Start playout and recording and store recorded data in an intermediate FIFO
1041// buffer from which the playout side then reads its samples in the same order
1042// as they were stored. Under ideal circumstances, a callback sequence would
1043// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
1044// means 'packet played'. Under such conditions, the FIFO would contain max 1,
1045// with an average somewhere in (0,1) depending on how long the packets are
1046// buffered. However, under more realistic conditions, the size
1047// of the FIFO will vary more due to an unbalance between the two sides.
1048// This test tries to verify that the device maintains a balanced callback-
1049// sequence by running in loopback for a few seconds while measuring the size
1050// (max and average) of the FIFO. The size of the FIFO is increased by the
1051// recording side and decreased by the playout side.
Yves Gerey1afe6572019-07-18 22:01:09 +02001052TEST_P(MAYBE_AudioDeviceTest, RunPlayoutAndRecordingInFullDuplex) {
henrikae24991d2017-04-06 01:14:23 -07001053 SKIP_TEST_IF_NOT(requirements_satisfied());
1054 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1055 FifoAudioStream audio_stream;
1056 mock.HandleCallbacks(event(), &audio_stream,
1057 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
1058 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001059 // Run both sides using the same channel configuration to avoid conversions
1060 // between mono/stereo while running in full duplex mode. Also, some devices
1061 // (mainly on Windows) do not support mono.
1062 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1063 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
Gustaf Ullberg102b7282019-06-03 15:03:02 +02001064 // Mute speakers to prevent howling.
1065 EXPECT_EQ(0, audio_device()->SetSpeakerVolume(0));
henrikae24991d2017-04-06 01:14:23 -07001066 StartPlayout();
1067 StartRecording();
henrika714e5cd2017-04-20 08:03:11 -07001068 event()->Wait(static_cast<int>(
1069 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec)));
henrikae24991d2017-04-06 01:14:23 -07001070 StopRecording();
1071 StopPlayout();
1072 // This thresholds is set rather high to accommodate differences in hardware
1073 // in several devices. The main idea is to capture cases where a very large
henrikab6ca7212017-10-06 12:47:52 +02001074 // latency is built up. See http://bugs.webrtc.org/7744 for examples on
1075 // bots where relatively large average latencies can happen.
1076 EXPECT_LE(audio_stream.average_size(), 25u);
henrikae24991d2017-04-06 01:14:23 -07001077 PRINT("\n");
1078}
1079
henrika5b6afc02018-09-05 14:34:40 +02001080// Runs audio in full duplex until user hits Enter. Intended as a manual test
1081// to ensure that the audio quality is good and that real device switches works
1082// as intended.
Yves Gerey1afe6572019-07-18 22:01:09 +02001083TEST_P(MAYBE_AudioDeviceTest,
henrika5b6afc02018-09-05 14:34:40 +02001084 DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey) {
1085 SKIP_TEST_IF_NOT(requirements_satisfied());
1086 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
1087 return;
1088 }
1089 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1090 FifoAudioStream audio_stream;
1091 mock.HandleCallbacks(&audio_stream);
1092 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1093 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1094 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
1095 // Ensure that the sample rate for both directions are identical so that we
1096 // always can listen to our own voice. Will lead to rate conversion (and
1097 // higher latency) if the native sample rate is not 48kHz.
1098 EXPECT_EQ(0, audio_device()->SetPlayoutSampleRate(48000));
1099 EXPECT_EQ(0, audio_device()->SetRecordingSampleRate(48000));
1100 StartPlayout();
1101 StartRecording();
1102 do {
1103 PRINT("Loopback audio is active at 48kHz. Press Enter to stop.\n");
1104 } while (getchar() != '\n');
1105 StopRecording();
1106 StopPlayout();
1107}
1108
henrika714e5cd2017-04-20 08:03:11 -07001109// Measures loopback latency and reports the min, max and average values for
1110// a full duplex audio session.
1111// The latency is measured like so:
1112// - Insert impulses periodically on the output side.
1113// - Detect the impulses on the input side.
1114// - Measure the time difference between the transmit time and receive time.
1115// - Store time differences in a vector and calculate min, max and average.
1116// This test needs the '--gtest_also_run_disabled_tests' flag to run and also
1117// some sort of audio feedback loop. E.g. a headset where the mic is placed
1118// close to the speaker to ensure highest possible echo. It is also recommended
1119// to run the test at highest possible output volume.
Yves Gerey1afe6572019-07-18 22:01:09 +02001120TEST_P(MAYBE_AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
henrika714e5cd2017-04-20 08:03:11 -07001121 SKIP_TEST_IF_NOT(requirements_satisfied());
1122 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1123 LatencyAudioStream audio_stream;
1124 mock.HandleCallbacks(event(), &audio_stream,
1125 kMeasureLatencyTimeInSec * kNumCallbacksPerSecond);
1126 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001127 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1128 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrika714e5cd2017-04-20 08:03:11 -07001129 StartPlayout();
1130 StartRecording();
1131 event()->Wait(static_cast<int>(
1132 std::max(kTestTimeOutInMilliseconds, 1000 * kMeasureLatencyTimeInSec)));
1133 StopRecording();
1134 StopPlayout();
henrikac7d93582018-09-14 15:37:34 +02001135 // Verify that a sufficient number of transmitted impulses are detected.
1136 EXPECT_GE(audio_stream.num_latency_values(),
henrika714e5cd2017-04-20 08:03:11 -07001137 static_cast<size_t>(
henrikac7d93582018-09-14 15:37:34 +02001138 kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 2));
henrika714e5cd2017-04-20 08:03:11 -07001139 // Print out min, max and average delay values for debugging purposes.
1140 audio_stream.PrintResults();
1141}
1142
henrikaec9c7452018-06-08 16:10:03 +02001143#ifdef WEBRTC_WIN
1144// Test two different audio layers (or rather two different Core Audio
1145// implementations) for Windows.
Mirko Bonadeic84f6612019-01-31 12:20:57 +01001146INSTANTIATE_TEST_SUITE_P(
henrikaec9c7452018-06-08 16:10:03 +02001147 AudioLayerWin,
Yves Gerey1afe6572019-07-18 22:01:09 +02001148 MAYBE_AudioDeviceTest,
henrikaec9c7452018-06-08 16:10:03 +02001149 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio,
1150 AudioDeviceModule::kWindowsCoreAudio2));
1151#else
1152// For all platforms but Windows, only test the default audio layer.
Mirko Bonadeic84f6612019-01-31 12:20:57 +01001153INSTANTIATE_TEST_SUITE_P(
henrikaec9c7452018-06-08 16:10:03 +02001154 AudioLayer,
Yves Gerey1afe6572019-07-18 22:01:09 +02001155 MAYBE_AudioDeviceTest,
henrikaec9c7452018-06-08 16:10:03 +02001156 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio));
1157#endif
1158
henrikaf2f91fa2017-03-17 04:26:22 -07001159} // namespace webrtc