blob: e6c13db3a8e58e3bbe8d523fbedaf2905ff767d5 [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 Gereyb93a2452019-07-19 22:46:13 +0200558 // This is needed by all tests using MockAudioTransport,
559 // since there is no way to unregister it.
560 // Without Terminate(), audio_device would still accesses
561 // the destructed mock via "webrtc_audio_module_rec_thread".
562 // An alternative would be for the mock to outlive audio_device.
563 void PreTearDown() { EXPECT_EQ(0, audio_device_->Terminate()); }
564
Yves Gerey1afe6572019-07-18 22:01:09 +0200565 virtual ~MAYBE_AudioDeviceTest() {
henrikaf2f91fa2017-03-17 04:26:22 -0700566 if (audio_device_) {
567 EXPECT_EQ(0, audio_device_->Terminate());
568 }
569 }
570
571 bool requirements_satisfied() const { return requirements_satisfied_; }
572 rtc::Event* event() { return &event_; }
henrika5b6afc02018-09-05 14:34:40 +0200573 AudioDeviceModule::AudioLayer audio_layer() const { return audio_layer_; }
henrikaf2f91fa2017-03-17 04:26:22 -0700574
henrika5b6afc02018-09-05 14:34:40 +0200575 // AudioDeviceModuleForTest extends the default ADM interface with some extra
576 // test methods. Intended for usage in tests only and requires a unique
577 // factory method. See CreateAudioDevice() for details.
578 const rtc::scoped_refptr<AudioDeviceModuleForTest>& audio_device() const {
henrikaf2f91fa2017-03-17 04:26:22 -0700579 return audio_device_;
580 }
581
henrika5b6afc02018-09-05 14:34:40 +0200582 rtc::scoped_refptr<AudioDeviceModuleForTest> CreateAudioDevice() {
henrikaec9c7452018-06-08 16:10:03 +0200583 // Use the default factory for kPlatformDefaultAudio and a special factory
henrika5b6afc02018-09-05 14:34:40 +0200584 // CreateWindowsCoreAudioAudioDeviceModuleForTest() for kWindowsCoreAudio2.
henrikaec9c7452018-06-08 16:10:03 +0200585 // The value of |audio_layer_| is set at construction by GetParam() and two
586 // different layers are tested on Windows only.
587 if (audio_layer_ == AudioDeviceModule::kPlatformDefaultAudio) {
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200588 return AudioDeviceModule::CreateForTest(audio_layer_,
589 task_queue_factory_.get());
henrikaec9c7452018-06-08 16:10:03 +0200590 } else if (audio_layer_ == AudioDeviceModule::kWindowsCoreAudio2) {
591#ifdef WEBRTC_WIN
592 // We must initialize the COM library on a thread before we calling any of
593 // the library functions. All COM functions in the ADM will return
594 // CO_E_NOTINITIALIZED otherwise.
Karl Wiberg918f50c2018-07-05 11:40:33 +0200595 com_initializer_ = absl::make_unique<webrtc_win::ScopedCOMInitializer>(
henrikaec9c7452018-06-08 16:10:03 +0200596 webrtc_win::ScopedCOMInitializer::kMTA);
597 EXPECT_TRUE(com_initializer_->Succeeded());
598 EXPECT_TRUE(webrtc_win::core_audio_utility::IsSupported());
599 EXPECT_TRUE(webrtc_win::core_audio_utility::IsMMCSSSupported());
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200600 return CreateWindowsCoreAudioAudioDeviceModuleForTest(
henrikad8c6ec42019-07-18 15:17:28 +0200601 task_queue_factory_.get(), true);
henrikaec9c7452018-06-08 16:10:03 +0200602#else
603 return nullptr;
604#endif
605 } else {
606 return nullptr;
607 }
608 }
609
henrikaf2f91fa2017-03-17 04:26:22 -0700610 void StartPlayout() {
611 EXPECT_FALSE(audio_device()->Playing());
612 EXPECT_EQ(0, audio_device()->InitPlayout());
613 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
614 EXPECT_EQ(0, audio_device()->StartPlayout());
615 EXPECT_TRUE(audio_device()->Playing());
616 }
617
618 void StopPlayout() {
619 EXPECT_EQ(0, audio_device()->StopPlayout());
620 EXPECT_FALSE(audio_device()->Playing());
621 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
622 }
623
624 void StartRecording() {
625 EXPECT_FALSE(audio_device()->Recording());
626 EXPECT_EQ(0, audio_device()->InitRecording());
627 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
628 EXPECT_EQ(0, audio_device()->StartRecording());
629 EXPECT_TRUE(audio_device()->Recording());
630 }
631
632 void StopRecording() {
633 EXPECT_EQ(0, audio_device()->StopRecording());
634 EXPECT_FALSE(audio_device()->Recording());
635 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
636 }
637
henrikaec9c7452018-06-08 16:10:03 +0200638 bool NewWindowsAudioDeviceModuleIsUsed() {
639#ifdef WEBRTC_WIN
640 AudioDeviceModule::AudioLayer audio_layer;
641 EXPECT_EQ(0, audio_device()->ActiveAudioLayer(&audio_layer));
642 if (audio_layer == AudioDeviceModule::kWindowsCoreAudio2) {
643 // Default device is always added as first element in the list and the
644 // default communication device as the second element. Hence, the list
645 // contains two extra elements in this case.
646 return true;
647 }
648#endif
649 return false;
650 }
651
henrikaf2f91fa2017-03-17 04:26:22 -0700652 private:
henrikaec9c7452018-06-08 16:10:03 +0200653#ifdef WEBRTC_WIN
654 // Windows Core Audio based ADM needs to run on a COM initialized thread.
655 std::unique_ptr<webrtc_win::ScopedCOMInitializer> com_initializer_;
656#endif
657 AudioDeviceModule::AudioLayer audio_layer_;
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200658 std::unique_ptr<TaskQueueFactory> task_queue_factory_;
henrikaf2f91fa2017-03-17 04:26:22 -0700659 bool requirements_satisfied_ = true;
660 rtc::Event event_;
henrika5b6afc02018-09-05 14:34:40 +0200661 rtc::scoped_refptr<AudioDeviceModuleForTest> audio_device_;
henrikaf2f91fa2017-03-17 04:26:22 -0700662 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700663};
664
henrikaec9c7452018-06-08 16:10:03 +0200665// Instead of using the test fixture, verify that the different factory methods
666// work as intended.
667TEST(AudioDeviceTestWin, ConstructDestructWithFactory) {
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200668 std::unique_ptr<TaskQueueFactory> task_queue_factory =
669 CreateDefaultTaskQueueFactory();
henrikaec9c7452018-06-08 16:10:03 +0200670 rtc::scoped_refptr<AudioDeviceModule> audio_device;
671 // The default factory should work for all platforms when a default ADM is
672 // requested.
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200673 audio_device = AudioDeviceModule::Create(
674 AudioDeviceModule::kPlatformDefaultAudio, task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200675 EXPECT_TRUE(audio_device);
676 audio_device = nullptr;
677#ifdef WEBRTC_WIN
678 // For Windows, the old factory method creates an ADM where the platform-
679 // specific parts are implemented by an AudioDeviceGeneric object. Verify
680 // that the old factory can't be used in combination with the latest audio
681 // layer AudioDeviceModule::kWindowsCoreAudio2.
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200682 audio_device = AudioDeviceModule::Create(
683 AudioDeviceModule::kWindowsCoreAudio2, task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200684 EXPECT_FALSE(audio_device);
685 audio_device = nullptr;
686 // Instead, ensure that the new dedicated factory method called
687 // CreateWindowsCoreAudioAudioDeviceModule() can be used on Windows and that
688 // it sets the audio layer to kWindowsCoreAudio2 implicitly. Note that, the
689 // new ADM for Windows must be created on a COM thread.
690 webrtc_win::ScopedCOMInitializer com_initializer(
691 webrtc_win::ScopedCOMInitializer::kMTA);
692 EXPECT_TRUE(com_initializer.Succeeded());
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200693 audio_device =
694 CreateWindowsCoreAudioAudioDeviceModule(task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200695 EXPECT_TRUE(audio_device);
696 AudioDeviceModule::AudioLayer audio_layer;
697 EXPECT_EQ(0, audio_device->ActiveAudioLayer(&audio_layer));
698 EXPECT_EQ(audio_layer, AudioDeviceModule::kWindowsCoreAudio2);
699#endif
700}
henrikaf2f91fa2017-03-17 04:26:22 -0700701
henrikaec9c7452018-06-08 16:10:03 +0200702// Uses the test fixture to create, initialize and destruct the ADM.
Yves Gerey1afe6572019-07-18 22:01:09 +0200703TEST_P(MAYBE_AudioDeviceTest, ConstructDestructDefault) {}
henrikaec9c7452018-06-08 16:10:03 +0200704
Yves Gerey1afe6572019-07-18 22:01:09 +0200705TEST_P(MAYBE_AudioDeviceTest, InitTerminate) {
henrikaf2f91fa2017-03-17 04:26:22 -0700706 SKIP_TEST_IF_NOT(requirements_satisfied());
707 // Initialization is part of the test fixture.
708 EXPECT_TRUE(audio_device()->Initialized());
709 EXPECT_EQ(0, audio_device()->Terminate());
710 EXPECT_FALSE(audio_device()->Initialized());
711}
712
henrikaec9c7452018-06-08 16:10:03 +0200713// Enumerate all available and active output devices.
Yves Gerey1afe6572019-07-18 22:01:09 +0200714TEST_P(MAYBE_AudioDeviceTest, PlayoutDeviceNames) {
henrikaf2f91fa2017-03-17 04:26:22 -0700715 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaec9c7452018-06-08 16:10:03 +0200716 char device_name[kAdmMaxDeviceNameSize];
717 char unique_id[kAdmMaxGuidSize];
718 int num_devices = audio_device()->PlayoutDevices();
719 if (NewWindowsAudioDeviceModuleIsUsed()) {
720 num_devices += 2;
721 }
722 EXPECT_GT(num_devices, 0);
723 for (int i = 0; i < num_devices; ++i) {
724 EXPECT_EQ(0, audio_device()->PlayoutDeviceName(i, device_name, unique_id));
725 }
726 EXPECT_EQ(-1, audio_device()->PlayoutDeviceName(num_devices, device_name,
727 unique_id));
728}
729
730// Enumerate all available and active input devices.
Yves Gerey1afe6572019-07-18 22:01:09 +0200731TEST_P(MAYBE_AudioDeviceTest, RecordingDeviceNames) {
henrikaec9c7452018-06-08 16:10:03 +0200732 SKIP_TEST_IF_NOT(requirements_satisfied());
733 char device_name[kAdmMaxDeviceNameSize];
734 char unique_id[kAdmMaxGuidSize];
735 int num_devices = audio_device()->RecordingDevices();
736 if (NewWindowsAudioDeviceModuleIsUsed()) {
737 num_devices += 2;
738 }
739 EXPECT_GT(num_devices, 0);
740 for (int i = 0; i < num_devices; ++i) {
741 EXPECT_EQ(0,
742 audio_device()->RecordingDeviceName(i, device_name, unique_id));
743 }
744 EXPECT_EQ(-1, audio_device()->RecordingDeviceName(num_devices, device_name,
745 unique_id));
746}
747
748// Counts number of active output devices and ensure that all can be selected.
Yves Gerey1afe6572019-07-18 22:01:09 +0200749TEST_P(MAYBE_AudioDeviceTest, SetPlayoutDevice) {
henrikaec9c7452018-06-08 16:10:03 +0200750 SKIP_TEST_IF_NOT(requirements_satisfied());
751 int num_devices = audio_device()->PlayoutDevices();
752 if (NewWindowsAudioDeviceModuleIsUsed()) {
753 num_devices += 2;
754 }
755 EXPECT_GT(num_devices, 0);
756 // Verify that all available playout devices can be set (not enabled yet).
757 for (int i = 0; i < num_devices; ++i) {
758 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(i));
759 }
760 EXPECT_EQ(-1, audio_device()->SetPlayoutDevice(num_devices));
761#ifdef WEBRTC_WIN
762 // On Windows, verify the alternative method where the user can select device
763 // by role.
764 EXPECT_EQ(
765 0, audio_device()->SetPlayoutDevice(AudioDeviceModule::kDefaultDevice));
766 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(
767 AudioDeviceModule::kDefaultCommunicationDevice));
768#endif
769}
770
771// Counts number of active input devices and ensure that all can be selected.
Yves Gerey1afe6572019-07-18 22:01:09 +0200772TEST_P(MAYBE_AudioDeviceTest, SetRecordingDevice) {
henrikaec9c7452018-06-08 16:10:03 +0200773 SKIP_TEST_IF_NOT(requirements_satisfied());
774 int num_devices = audio_device()->RecordingDevices();
775 if (NewWindowsAudioDeviceModuleIsUsed()) {
776 num_devices += 2;
777 }
778 EXPECT_GT(num_devices, 0);
779 // Verify that all available recording devices can be set (not enabled yet).
780 for (int i = 0; i < num_devices; ++i) {
781 EXPECT_EQ(0, audio_device()->SetRecordingDevice(i));
782 }
783 EXPECT_EQ(-1, audio_device()->SetRecordingDevice(num_devices));
784#ifdef WEBRTC_WIN
785 // On Windows, verify the alternative method where the user can select device
786 // by role.
787 EXPECT_EQ(
788 0, audio_device()->SetRecordingDevice(AudioDeviceModule::kDefaultDevice));
789 EXPECT_EQ(0, audio_device()->SetRecordingDevice(
790 AudioDeviceModule::kDefaultCommunicationDevice));
791#endif
792}
793
794// Tests Start/Stop playout without any registered audio callback.
Yves Gerey1afe6572019-07-18 22:01:09 +0200795TEST_P(MAYBE_AudioDeviceTest, StartStopPlayout) {
henrikaec9c7452018-06-08 16:10:03 +0200796 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaf2f91fa2017-03-17 04:26:22 -0700797 StartPlayout();
798 StopPlayout();
799}
800
801// Tests Start/Stop recording without any registered audio callback.
Yves Gerey1afe6572019-07-18 22:01:09 +0200802TEST_P(MAYBE_AudioDeviceTest, StartStopRecording) {
henrikaf2f91fa2017-03-17 04:26:22 -0700803 SKIP_TEST_IF_NOT(requirements_satisfied());
804 StartRecording();
805 StopRecording();
henrikaf2f91fa2017-03-17 04:26:22 -0700806}
807
henrika6b3e1a22017-09-25 16:34:30 +0200808// Tests Init/Stop/Init recording without any registered audio callback.
809// See https://bugs.chromium.org/p/webrtc/issues/detail?id=8041 for details
810// on why this test is useful.
Yves Gerey1afe6572019-07-18 22:01:09 +0200811TEST_P(MAYBE_AudioDeviceTest, InitStopInitRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200812 SKIP_TEST_IF_NOT(requirements_satisfied());
813 EXPECT_EQ(0, audio_device()->InitRecording());
814 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
815 StopRecording();
816 EXPECT_EQ(0, audio_device()->InitRecording());
817 StopRecording();
818}
819
henrikad4049462019-07-12 13:37:11 +0200820// Verify that additional attempts to initialize or start recording while
821// already being active works. Additional calls should just be ignored.
Yves Gerey1afe6572019-07-18 22:01:09 +0200822TEST_P(MAYBE_AudioDeviceTest, StartInitRecording) {
henrikad4049462019-07-12 13:37:11 +0200823 SKIP_TEST_IF_NOT(requirements_satisfied());
824 StartRecording();
825 // An additional attempt to initialize at this stage should be ignored.
826 EXPECT_EQ(0, audio_device()->InitRecording());
827 // Same for additional request to start recording while already active.
828 EXPECT_EQ(0, audio_device()->StartRecording());
829 StopRecording();
830}
831
832// Verify that additional attempts to initialize or start playou while
833// already being active works. Additional calls should just be ignored.
Yves Gerey1afe6572019-07-18 22:01:09 +0200834TEST_P(MAYBE_AudioDeviceTest, StartInitPlayout) {
henrikad4049462019-07-12 13:37:11 +0200835 SKIP_TEST_IF_NOT(requirements_satisfied());
836 StartPlayout();
837 // An additional attempt to initialize at this stage should be ignored.
838 EXPECT_EQ(0, audio_device()->InitPlayout());
839 // Same for additional request to start playout while already active.
840 EXPECT_EQ(0, audio_device()->StartPlayout());
841 StopPlayout();
842}
843
henrika6b3e1a22017-09-25 16:34:30 +0200844// Tests Init/Stop/Init recording while playout is active.
Yves Gerey1afe6572019-07-18 22:01:09 +0200845TEST_P(MAYBE_AudioDeviceTest, InitStopInitRecordingWhilePlaying) {
henrika6b3e1a22017-09-25 16:34:30 +0200846 SKIP_TEST_IF_NOT(requirements_satisfied());
847 StartPlayout();
848 EXPECT_EQ(0, audio_device()->InitRecording());
849 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
850 StopRecording();
851 EXPECT_EQ(0, audio_device()->InitRecording());
852 StopRecording();
853 StopPlayout();
854}
855
856// Tests Init/Stop/Init playout without any registered audio callback.
Yves Gerey1afe6572019-07-18 22:01:09 +0200857TEST_P(MAYBE_AudioDeviceTest, InitStopInitPlayout) {
henrika6b3e1a22017-09-25 16:34:30 +0200858 SKIP_TEST_IF_NOT(requirements_satisfied());
859 EXPECT_EQ(0, audio_device()->InitPlayout());
860 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
861 StopPlayout();
862 EXPECT_EQ(0, audio_device()->InitPlayout());
863 StopPlayout();
864}
865
866// Tests Init/Stop/Init playout while recording is active.
Yves Gerey1afe6572019-07-18 22:01:09 +0200867TEST_P(MAYBE_AudioDeviceTest, InitStopInitPlayoutWhileRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200868 SKIP_TEST_IF_NOT(requirements_satisfied());
869 StartRecording();
870 EXPECT_EQ(0, audio_device()->InitPlayout());
871 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
872 StopPlayout();
873 EXPECT_EQ(0, audio_device()->InitPlayout());
874 StopPlayout();
875 StopRecording();
876}
877
henrika5b6afc02018-09-05 14:34:40 +0200878// TODO(henrika): restart without intermediate destruction is currently only
879// supported on Windows.
880#ifdef WEBRTC_WIN
881// Tests Start/Stop playout followed by a second session (emulates a restart
882// triggered by a user using public APIs).
Yves Gerey1afe6572019-07-18 22:01:09 +0200883TEST_P(MAYBE_AudioDeviceTest, StartStopPlayoutWithExternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200884 SKIP_TEST_IF_NOT(requirements_satisfied());
885 StartPlayout();
886 StopPlayout();
887 // Restart playout without destroying the ADM in between. Ensures that we
888 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
889 StartPlayout();
890 StopPlayout();
891}
892
893// Tests Start/Stop recording followed by a second session (emulates a restart
894// triggered by a user using public APIs).
Yves Gerey1afe6572019-07-18 22:01:09 +0200895TEST_P(MAYBE_AudioDeviceTest, StartStopRecordingWithExternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200896 SKIP_TEST_IF_NOT(requirements_satisfied());
897 StartRecording();
898 StopRecording();
899 // Restart recording without destroying the ADM in between. Ensures that we
900 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
901 StartRecording();
902 StopRecording();
903}
904
905// Tests Start/Stop playout followed by a second session (emulates a restart
906// triggered by an internal callback e.g. corresponding to a device switch).
907// Note that, internal restart is only supported in combination with the latest
908// Windows ADM.
Yves Gerey1afe6572019-07-18 22:01:09 +0200909TEST_P(MAYBE_AudioDeviceTest, StartStopPlayoutWithInternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200910 SKIP_TEST_IF_NOT(requirements_satisfied());
911 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
912 return;
913 }
914 MockAudioTransport mock(TransportType::kPlay);
915 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
916 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
917 .Times(AtLeast(kNumCallbacks));
918 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
919 StartPlayout();
920 event()->Wait(kTestTimeOutInMilliseconds);
921 EXPECT_TRUE(audio_device()->Playing());
922 // Restart playout but without stopping the internal audio thread.
923 // This procedure uses a non-public test API and it emulates what happens
924 // inside the ADM when e.g. a device is removed.
925 EXPECT_EQ(0, audio_device()->RestartPlayoutInternally());
926
927 // Run basic tests of public APIs while a restart attempt is active.
928 // These calls should now be very thin and not trigger any new actions.
929 EXPECT_EQ(-1, audio_device()->StopPlayout());
930 EXPECT_TRUE(audio_device()->Playing());
931 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
932 EXPECT_EQ(0, audio_device()->InitPlayout());
933 EXPECT_EQ(0, audio_device()->StartPlayout());
934
935 // Wait until audio has restarted and a new sequence of audio callbacks
936 // becomes active.
937 // TODO(henrika): is it possible to verify that the internal state transition
938 // is Stop->Init->Start?
939 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
940 mock.ResetCallbackCounters();
941 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
942 .Times(AtLeast(kNumCallbacks));
943 event()->Wait(kTestTimeOutInMilliseconds);
944 EXPECT_TRUE(audio_device()->Playing());
945 // Stop playout and the audio thread after successful internal restart.
946 StopPlayout();
Yves Gereyb93a2452019-07-19 22:46:13 +0200947 PreTearDown();
henrika5b6afc02018-09-05 14:34:40 +0200948}
949
950// Tests Start/Stop recording followed by a second session (emulates a restart
951// triggered by an internal callback e.g. corresponding to a device switch).
952// Note that, internal restart is only supported in combination with the latest
953// Windows ADM.
Yves Gerey1afe6572019-07-18 22:01:09 +0200954TEST_P(MAYBE_AudioDeviceTest, StartStopRecordingWithInternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200955 SKIP_TEST_IF_NOT(requirements_satisfied());
956 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
957 return;
958 }
959 MockAudioTransport mock(TransportType::kRecord);
960 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
961 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
962 false, _))
963 .Times(AtLeast(kNumCallbacks));
964 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
965 StartRecording();
966 event()->Wait(kTestTimeOutInMilliseconds);
967 EXPECT_TRUE(audio_device()->Recording());
968 // Restart recording but without stopping the internal audio thread.
969 // This procedure uses a non-public test API and it emulates what happens
970 // inside the ADM when e.g. a device is removed.
971 EXPECT_EQ(0, audio_device()->RestartRecordingInternally());
972
973 // Run basic tests of public APIs while a restart attempt is active.
974 // These calls should now be very thin and not trigger any new actions.
975 EXPECT_EQ(-1, audio_device()->StopRecording());
976 EXPECT_TRUE(audio_device()->Recording());
977 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
978 EXPECT_EQ(0, audio_device()->InitRecording());
979 EXPECT_EQ(0, audio_device()->StartRecording());
980
981 // Wait until audio has restarted and a new sequence of audio callbacks
982 // becomes active.
983 // TODO(henrika): is it possible to verify that the internal state transition
984 // is Stop->Init->Start?
985 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
986 mock.ResetCallbackCounters();
987 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
988 false, _))
989 .Times(AtLeast(kNumCallbacks));
990 event()->Wait(kTestTimeOutInMilliseconds);
991 EXPECT_TRUE(audio_device()->Recording());
992 // Stop recording and the audio thread after successful internal restart.
993 StopRecording();
Yves Gereyb93a2452019-07-19 22:46:13 +0200994 PreTearDown();
henrika5b6afc02018-09-05 14:34:40 +0200995}
996#endif // #ifdef WEBRTC_WIN
997
henrikaf2f91fa2017-03-17 04:26:22 -0700998// Start playout and verify that the native audio layer starts asking for real
999// audio samples to play out using the NeedMorePlayData() callback.
1000// Note that we can't add expectations on audio parameters in EXPECT_CALL
1001// since parameter are not provided in the each callback. We therefore test and
1002// verify the parameters in the fake audio transport implementation instead.
Yves Gerey1afe6572019-07-18 22:01:09 +02001003TEST_P(MAYBE_AudioDeviceTest, StartPlayoutVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001004 SKIP_TEST_IF_NOT(requirements_satisfied());
1005 MockAudioTransport mock(TransportType::kPlay);
henrikae24991d2017-04-06 01:14:23 -07001006 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001007 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
1008 .Times(AtLeast(kNumCallbacks));
1009 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1010 StartPlayout();
1011 event()->Wait(kTestTimeOutInMilliseconds);
1012 StopPlayout();
Yves Gerey412282a2019-07-22 21:15:22 +02001013 PreTearDown();
henrikaf2f91fa2017-03-17 04:26:22 -07001014}
1015
1016// Start recording and verify that the native audio layer starts providing real
1017// audio samples using the RecordedDataIsAvailable() callback.
Yves Gerey1afe6572019-07-18 22:01:09 +02001018TEST_P(MAYBE_AudioDeviceTest, StartRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001019 SKIP_TEST_IF_NOT(requirements_satisfied());
1020 MockAudioTransport mock(TransportType::kRecord);
henrikae24991d2017-04-06 01:14:23 -07001021 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001022 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
1023 false, _))
1024 .Times(AtLeast(kNumCallbacks));
1025 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1026 StartRecording();
1027 event()->Wait(kTestTimeOutInMilliseconds);
1028 StopRecording();
Yves Gereyb93a2452019-07-19 22:46:13 +02001029 PreTearDown();
henrikaf2f91fa2017-03-17 04:26:22 -07001030}
1031
1032// Start playout and recording (full-duplex audio) and verify that audio is
1033// active in both directions.
Yves Gerey1afe6572019-07-18 22:01:09 +02001034TEST_P(MAYBE_AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001035 SKIP_TEST_IF_NOT(requirements_satisfied());
1036 MockAudioTransport mock(TransportType::kPlayAndRecord);
henrikae24991d2017-04-06 01:14:23 -07001037 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001038 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
1039 .Times(AtLeast(kNumCallbacks));
1040 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
1041 false, _))
1042 .Times(AtLeast(kNumCallbacks));
1043 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1044 StartPlayout();
1045 StartRecording();
1046 event()->Wait(kTestTimeOutInMilliseconds);
1047 StopRecording();
1048 StopPlayout();
Yves Gereyb93a2452019-07-19 22:46:13 +02001049 PreTearDown();
henrikaf2f91fa2017-03-17 04:26:22 -07001050}
1051
henrikae24991d2017-04-06 01:14:23 -07001052// Start playout and recording and store recorded data in an intermediate FIFO
1053// buffer from which the playout side then reads its samples in the same order
1054// as they were stored. Under ideal circumstances, a callback sequence would
1055// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
1056// means 'packet played'. Under such conditions, the FIFO would contain max 1,
1057// with an average somewhere in (0,1) depending on how long the packets are
1058// buffered. However, under more realistic conditions, the size
1059// of the FIFO will vary more due to an unbalance between the two sides.
1060// This test tries to verify that the device maintains a balanced callback-
1061// sequence by running in loopback for a few seconds while measuring the size
1062// (max and average) of the FIFO. The size of the FIFO is increased by the
1063// recording side and decreased by the playout side.
Yves Gerey1afe6572019-07-18 22:01:09 +02001064TEST_P(MAYBE_AudioDeviceTest, RunPlayoutAndRecordingInFullDuplex) {
henrikae24991d2017-04-06 01:14:23 -07001065 SKIP_TEST_IF_NOT(requirements_satisfied());
1066 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1067 FifoAudioStream audio_stream;
1068 mock.HandleCallbacks(event(), &audio_stream,
1069 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
1070 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001071 // Run both sides using the same channel configuration to avoid conversions
1072 // between mono/stereo while running in full duplex mode. Also, some devices
1073 // (mainly on Windows) do not support mono.
1074 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1075 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
Gustaf Ullberg102b7282019-06-03 15:03:02 +02001076 // Mute speakers to prevent howling.
1077 EXPECT_EQ(0, audio_device()->SetSpeakerVolume(0));
henrikae24991d2017-04-06 01:14:23 -07001078 StartPlayout();
1079 StartRecording();
henrika714e5cd2017-04-20 08:03:11 -07001080 event()->Wait(static_cast<int>(
1081 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec)));
henrikae24991d2017-04-06 01:14:23 -07001082 StopRecording();
1083 StopPlayout();
Yves Gerey412282a2019-07-22 21:15:22 +02001084 // Avoid concurrent access to audio_stream.
1085 PreTearDown();
henrikae24991d2017-04-06 01:14:23 -07001086 // This thresholds is set rather high to accommodate differences in hardware
1087 // in several devices. The main idea is to capture cases where a very large
henrikab6ca7212017-10-06 12:47:52 +02001088 // latency is built up. See http://bugs.webrtc.org/7744 for examples on
1089 // bots where relatively large average latencies can happen.
1090 EXPECT_LE(audio_stream.average_size(), 25u);
henrikae24991d2017-04-06 01:14:23 -07001091 PRINT("\n");
1092}
1093
henrika5b6afc02018-09-05 14:34:40 +02001094// Runs audio in full duplex until user hits Enter. Intended as a manual test
1095// to ensure that the audio quality is good and that real device switches works
1096// as intended.
Yves Gerey1afe6572019-07-18 22:01:09 +02001097TEST_P(MAYBE_AudioDeviceTest,
henrika5b6afc02018-09-05 14:34:40 +02001098 DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey) {
1099 SKIP_TEST_IF_NOT(requirements_satisfied());
1100 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
1101 return;
1102 }
1103 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1104 FifoAudioStream audio_stream;
1105 mock.HandleCallbacks(&audio_stream);
1106 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1107 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1108 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
1109 // Ensure that the sample rate for both directions are identical so that we
1110 // always can listen to our own voice. Will lead to rate conversion (and
1111 // higher latency) if the native sample rate is not 48kHz.
1112 EXPECT_EQ(0, audio_device()->SetPlayoutSampleRate(48000));
1113 EXPECT_EQ(0, audio_device()->SetRecordingSampleRate(48000));
1114 StartPlayout();
1115 StartRecording();
1116 do {
1117 PRINT("Loopback audio is active at 48kHz. Press Enter to stop.\n");
1118 } while (getchar() != '\n');
1119 StopRecording();
1120 StopPlayout();
Yves Gereyb93a2452019-07-19 22:46:13 +02001121 PreTearDown();
henrika5b6afc02018-09-05 14:34:40 +02001122}
1123
henrika714e5cd2017-04-20 08:03:11 -07001124// Measures loopback latency and reports the min, max and average values for
1125// a full duplex audio session.
1126// The latency is measured like so:
1127// - Insert impulses periodically on the output side.
1128// - Detect the impulses on the input side.
1129// - Measure the time difference between the transmit time and receive time.
1130// - Store time differences in a vector and calculate min, max and average.
1131// This test needs the '--gtest_also_run_disabled_tests' flag to run and also
1132// some sort of audio feedback loop. E.g. a headset where the mic is placed
1133// close to the speaker to ensure highest possible echo. It is also recommended
1134// to run the test at highest possible output volume.
Yves Gerey1afe6572019-07-18 22:01:09 +02001135TEST_P(MAYBE_AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
henrika714e5cd2017-04-20 08:03:11 -07001136 SKIP_TEST_IF_NOT(requirements_satisfied());
1137 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1138 LatencyAudioStream audio_stream;
1139 mock.HandleCallbacks(event(), &audio_stream,
1140 kMeasureLatencyTimeInSec * kNumCallbacksPerSecond);
1141 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001142 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1143 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrika714e5cd2017-04-20 08:03:11 -07001144 StartPlayout();
1145 StartRecording();
1146 event()->Wait(static_cast<int>(
1147 std::max(kTestTimeOutInMilliseconds, 1000 * kMeasureLatencyTimeInSec)));
1148 StopRecording();
1149 StopPlayout();
Yves Gerey412282a2019-07-22 21:15:22 +02001150 // Avoid concurrent access to audio_stream.
1151 PreTearDown();
henrikac7d93582018-09-14 15:37:34 +02001152 // Verify that a sufficient number of transmitted impulses are detected.
1153 EXPECT_GE(audio_stream.num_latency_values(),
henrika714e5cd2017-04-20 08:03:11 -07001154 static_cast<size_t>(
henrikac7d93582018-09-14 15:37:34 +02001155 kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 2));
henrika714e5cd2017-04-20 08:03:11 -07001156 // Print out min, max and average delay values for debugging purposes.
1157 audio_stream.PrintResults();
1158}
1159
henrikaec9c7452018-06-08 16:10:03 +02001160#ifdef WEBRTC_WIN
1161// Test two different audio layers (or rather two different Core Audio
1162// implementations) for Windows.
Mirko Bonadeic84f6612019-01-31 12:20:57 +01001163INSTANTIATE_TEST_SUITE_P(
henrikaec9c7452018-06-08 16:10:03 +02001164 AudioLayerWin,
Yves Gerey1afe6572019-07-18 22:01:09 +02001165 MAYBE_AudioDeviceTest,
henrikaec9c7452018-06-08 16:10:03 +02001166 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio,
1167 AudioDeviceModule::kWindowsCoreAudio2));
1168#else
1169// For all platforms but Windows, only test the default audio layer.
Mirko Bonadeic84f6612019-01-31 12:20:57 +01001170INSTANTIATE_TEST_SUITE_P(
henrikaec9c7452018-06-08 16:10:03 +02001171 AudioLayer,
Yves Gerey1afe6572019-07-18 22:01:09 +02001172 MAYBE_AudioDeviceTest,
henrikaec9c7452018-06-08 16:10:03 +02001173 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio));
1174#endif
1175
henrikaf2f91fa2017-03-17 04:26:22 -07001176} // namespace webrtc