blob: 55382a59a7ec32278bcb81242016b4146c3724d1 [file] [log] [blame]
henrikaf2f91fa2017-03-17 04:26:22 -07001/*
2 * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Jonas Olssona4d87372019-07-05 19:08:33 +020011#include "modules/audio_device/include/audio_device.h"
12
henrika714e5cd2017-04-20 08:03:11 -070013#include <algorithm>
henrikaf2f91fa2017-03-17 04:26:22 -070014#include <cstring>
henrikaec9c7452018-06-08 16:10:03 +020015#include <memory>
henrika714e5cd2017-04-20 08:03:11 -070016#include <numeric>
henrikaf2f91fa2017-03-17 04:26:22 -070017
Steve Anton40d55332019-01-07 10:21:47 -080018#include "absl/memory/memory.h"
Danil Chapovalov196100e2018-06-21 10:17:24 +020019#include "absl/types/optional.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "api/array_view.h"
Mirko Bonadeid9708072019-01-25 20:26:48 +010021#include "api/scoped_refptr.h"
Danil Chapovalov1c41be62019-04-01 09:16:12 +020022#include "api/task_queue/default_task_queue_factory.h"
23#include "api/task_queue/task_queue_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "modules/audio_device/audio_device_impl.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/audio_device/include/mock_audio_transport.h"
26#include "rtc_base/buffer.h"
Steve Anton10542f22019-01-11 09:11:00 -080027#include "rtc_base/critical_section.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/event.h"
29#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010030#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "rtc_base/race_checker.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/thread_annotations.h"
33#include "rtc_base/thread_checker.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "rtc_base/time_utils.h"
henrika5b6afc02018-09-05 14:34:40 +020035#include "system_wrappers/include/sleep.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "test/gmock.h"
37#include "test/gtest.h"
henrikaec9c7452018-06-08 16:10:03 +020038#ifdef WEBRTC_WIN
39#include "modules/audio_device/include/audio_device_factory.h"
40#include "modules/audio_device/win/core_audio_utility_win.h"
41#endif
henrikaf2f91fa2017-03-17 04:26:22 -070042
43using ::testing::_;
44using ::testing::AtLeast;
45using ::testing::Ge;
46using ::testing::Invoke;
Jonas Olssona4d87372019-07-05 19:08:33 +020047using ::testing::Mock;
henrikaf2f91fa2017-03-17 04:26:22 -070048using ::testing::NiceMock;
49using ::testing::NotNull;
50
51namespace webrtc {
52namespace {
53
henrika5773ad32018-09-21 14:53:10 +020054// Using a #define for AUDIO_DEVICE since we will call *different* versions of
55// the ADM functions, depending on the ID type.
56#if defined(WEBRTC_WIN)
57#define AUDIO_DEVICE_ID (AudioDeviceModule::WindowsDeviceType::kDefaultDevice)
58#else
59#define AUDIO_DEVICE_ID (0u)
60#endif // defined(WEBRTC_WIN)
61
henrikae24991d2017-04-06 01:14:23 -070062// #define ENABLE_DEBUG_PRINTF
63#ifdef ENABLE_DEBUG_PRINTF
64#define PRINTD(...) fprintf(stderr, __VA_ARGS__);
65#else
66#define PRINTD(...) ((void)0)
67#endif
68#define PRINT(...) fprintf(stderr, __VA_ARGS__);
69
Yves Gerey1afe6572019-07-18 22:01:09 +020070// Don't run these tests if audio-related requirements are not met.
Yves Gereyee0550c2019-07-17 21:41:59 +020071#define SKIP_TEST_IF_NOT(requirements_satisfied) \
72 do { \
73 if (!requirements_satisfied) { \
74 GTEST_SKIP() << "Skipped. No audio device found."; \
75 } \
henrikaf2f91fa2017-03-17 04:26:22 -070076 } while (false)
henrikaf2f91fa2017-03-17 04:26:22 -070077
78// Number of callbacks (input or output) the tests waits for before we set
79// an event indicating that the test was OK.
henrikae24991d2017-04-06 01:14:23 -070080static constexpr size_t kNumCallbacks = 10;
henrikaf2f91fa2017-03-17 04:26:22 -070081// Max amount of time we wait for an event to be set while counting callbacks.
henrika714e5cd2017-04-20 08:03:11 -070082static constexpr size_t kTestTimeOutInMilliseconds = 10 * 1000;
henrikae24991d2017-04-06 01:14:23 -070083// Average number of audio callbacks per second assuming 10ms packet size.
84static constexpr size_t kNumCallbacksPerSecond = 100;
85// Run the full-duplex test during this time (unit is in seconds).
henrika714e5cd2017-04-20 08:03:11 -070086static constexpr size_t kFullDuplexTimeInSec = 5;
87// Length of round-trip latency measurements. Number of deteced impulses
88// shall be kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 1 since the
89// last transmitted pulse is not used.
90static constexpr size_t kMeasureLatencyTimeInSec = 10;
91// Sets the number of impulses per second in the latency test.
92static constexpr size_t kImpulseFrequencyInHz = 1;
93// Utilized in round-trip latency measurements to avoid capturing noise samples.
94static constexpr int kImpulseThreshold = 1000;
henrikaf2f91fa2017-03-17 04:26:22 -070095
96enum class TransportType {
97 kInvalid,
98 kPlay,
99 kRecord,
100 kPlayAndRecord,
101};
henrikae24991d2017-04-06 01:14:23 -0700102
103// Interface for processing the audio stream. Real implementations can e.g.
104// run audio in loopback, read audio from a file or perform latency
105// measurements.
106class AudioStream {
107 public:
henrikaeb98c722018-03-20 12:54:07 +0100108 virtual void Write(rtc::ArrayView<const int16_t> source) = 0;
109 virtual void Read(rtc::ArrayView<int16_t> destination) = 0;
henrikae24991d2017-04-06 01:14:23 -0700110
111 virtual ~AudioStream() = default;
112};
113
henrika714e5cd2017-04-20 08:03:11 -0700114// Converts index corresponding to position within a 10ms buffer into a
115// delay value in milliseconds.
116// Example: index=240, frames_per_10ms_buffer=480 => 5ms as output.
117int IndexToMilliseconds(size_t index, size_t frames_per_10ms_buffer) {
118 return rtc::checked_cast<int>(
119 10.0 * (static_cast<double>(index) / frames_per_10ms_buffer) + 0.5);
120}
121
henrikaf2f91fa2017-03-17 04:26:22 -0700122} // namespace
123
henrikae24991d2017-04-06 01:14:23 -0700124// Simple first in first out (FIFO) class that wraps a list of 16-bit audio
125// buffers of fixed size and allows Write and Read operations. The idea is to
126// store recorded audio buffers (using Write) and then read (using Read) these
127// stored buffers with as short delay as possible when the audio layer needs
128// data to play out. The number of buffers in the FIFO will stabilize under
129// normal conditions since there will be a balance between Write and Read calls.
130// The container is a std::list container and access is protected with a lock
131// since both sides (playout and recording) are driven by its own thread.
132// Note that, we know by design that the size of the audio buffer will not
henrikac7d93582018-09-14 15:37:34 +0200133// change over time and that both sides will in most cases use the same size.
henrikae24991d2017-04-06 01:14:23 -0700134class FifoAudioStream : public AudioStream {
135 public:
henrikaeb98c722018-03-20 12:54:07 +0100136 void Write(rtc::ArrayView<const int16_t> source) override {
henrikae24991d2017-04-06 01:14:23 -0700137 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
138 const size_t size = [&] {
139 rtc::CritScope lock(&lock_);
140 fifo_.push_back(Buffer16(source.data(), source.size()));
141 return fifo_.size();
142 }();
143 if (size > max_size_) {
144 max_size_ = size;
145 }
146 // Add marker once per second to signal that audio is active.
147 if (write_count_++ % 100 == 0) {
henrikad8c6ec42019-07-18 15:17:28 +0200148 PRINTD(".");
henrikae24991d2017-04-06 01:14:23 -0700149 }
150 written_elements_ += size;
151 }
152
henrikaeb98c722018-03-20 12:54:07 +0100153 void Read(rtc::ArrayView<int16_t> destination) override {
henrikae24991d2017-04-06 01:14:23 -0700154 rtc::CritScope lock(&lock_);
155 if (fifo_.empty()) {
156 std::fill(destination.begin(), destination.end(), 0);
157 } else {
158 const Buffer16& buffer = fifo_.front();
henrikac7d93582018-09-14 15:37:34 +0200159 if (buffer.size() == destination.size()) {
160 // Default case where input and output uses same sample rate and
161 // channel configuration. No conversion is needed.
162 std::copy(buffer.begin(), buffer.end(), destination.begin());
163 } else if (destination.size() == 2 * buffer.size()) {
164 // Recorded input signal in |buffer| is in mono. Do channel upmix to
165 // match stereo output (1 -> 2).
166 for (size_t i = 0; i < buffer.size(); ++i) {
167 destination[2 * i] = buffer[i];
168 destination[2 * i + 1] = buffer[i];
169 }
170 } else if (buffer.size() == 2 * destination.size()) {
171 // Recorded input signal in |buffer| is in stereo. Do channel downmix
172 // to match mono output (2 -> 1).
173 for (size_t i = 0; i < destination.size(); ++i) {
174 destination[i] =
175 (static_cast<int32_t>(buffer[2 * i]) + buffer[2 * i + 1]) / 2;
176 }
177 } else {
178 RTC_NOTREACHED() << "Required conversion is not support";
179 }
henrikae24991d2017-04-06 01:14:23 -0700180 fifo_.pop_front();
181 }
182 }
183
184 size_t size() const {
185 rtc::CritScope lock(&lock_);
186 return fifo_.size();
187 }
188
189 size_t max_size() const {
190 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
191 return max_size_;
192 }
193
194 size_t average_size() const {
195 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
196 return 0.5 + static_cast<float>(written_elements_ / write_count_);
197 }
198
199 using Buffer16 = rtc::BufferT<int16_t>;
200
201 rtc::CriticalSection lock_;
202 rtc::RaceChecker race_checker_;
203
danilchap56359be2017-09-07 07:53:45 -0700204 std::list<Buffer16> fifo_ RTC_GUARDED_BY(lock_);
205 size_t write_count_ RTC_GUARDED_BY(race_checker_) = 0;
206 size_t max_size_ RTC_GUARDED_BY(race_checker_) = 0;
207 size_t written_elements_ RTC_GUARDED_BY(race_checker_) = 0;
henrikae24991d2017-04-06 01:14:23 -0700208};
209
henrika714e5cd2017-04-20 08:03:11 -0700210// Inserts periodic impulses and measures the latency between the time of
211// transmission and time of receiving the same impulse.
212class LatencyAudioStream : public AudioStream {
213 public:
214 LatencyAudioStream() {
215 // Delay thread checkers from being initialized until first callback from
216 // respective thread.
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200217 read_thread_checker_.Detach();
218 write_thread_checker_.Detach();
henrika714e5cd2017-04-20 08:03:11 -0700219 }
220
221 // Insert periodic impulses in first two samples of |destination|.
henrikaeb98c722018-03-20 12:54:07 +0100222 void Read(rtc::ArrayView<int16_t> destination) override {
henrika714e5cd2017-04-20 08:03:11 -0700223 RTC_DCHECK_RUN_ON(&read_thread_checker_);
henrika714e5cd2017-04-20 08:03:11 -0700224 if (read_count_ == 0) {
225 PRINT("[");
226 }
227 read_count_++;
228 std::fill(destination.begin(), destination.end(), 0);
229 if (read_count_ % (kNumCallbacksPerSecond / kImpulseFrequencyInHz) == 0) {
230 PRINT(".");
231 {
232 rtc::CritScope lock(&lock_);
233 if (!pulse_time_) {
Oskar Sundbom6ad9f262017-11-16 10:53:39 +0100234 pulse_time_ = rtc::TimeMillis();
henrika714e5cd2017-04-20 08:03:11 -0700235 }
236 }
237 constexpr int16_t impulse = std::numeric_limits<int16_t>::max();
238 std::fill_n(destination.begin(), 2, impulse);
239 }
240 }
241
242 // Detect received impulses in |source|, derive time between transmission and
243 // detection and add the calculated delay to list of latencies.
henrikaeb98c722018-03-20 12:54:07 +0100244 void Write(rtc::ArrayView<const int16_t> source) override {
henrika714e5cd2017-04-20 08:03:11 -0700245 RTC_DCHECK_RUN_ON(&write_thread_checker_);
246 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
247 rtc::CritScope lock(&lock_);
248 write_count_++;
249 if (!pulse_time_) {
250 // Avoid detection of new impulse response until a new impulse has
251 // been transmitted (sets |pulse_time_| to value larger than zero).
252 return;
253 }
254 // Find index (element position in vector) of the max element.
255 const size_t index_of_max =
256 std::max_element(source.begin(), source.end()) - source.begin();
257 // Derive time between transmitted pulse and received pulse if the level
258 // is high enough (removes noise).
259 const size_t max = source[index_of_max];
260 if (max > kImpulseThreshold) {
261 PRINTD("(%zu, %zu)", max, index_of_max);
262 int64_t now_time = rtc::TimeMillis();
263 int extra_delay = IndexToMilliseconds(index_of_max, source.size());
264 PRINTD("[%d]", rtc::checked_cast<int>(now_time - pulse_time_));
265 PRINTD("[%d]", extra_delay);
266 // Total latency is the difference between transmit time and detection
267 // tome plus the extra delay within the buffer in which we detected the
268 // received impulse. It is transmitted at sample 0 but can be received
269 // at sample N where N > 0. The term |extra_delay| accounts for N and it
270 // is a value between 0 and 10ms.
271 latencies_.push_back(now_time - *pulse_time_ + extra_delay);
272 pulse_time_.reset();
273 } else {
274 PRINTD("-");
275 }
276 }
277
278 size_t num_latency_values() const {
279 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
280 return latencies_.size();
281 }
282
283 int min_latency() const {
284 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
285 if (latencies_.empty())
286 return 0;
287 return *std::min_element(latencies_.begin(), latencies_.end());
288 }
289
290 int max_latency() const {
291 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
292 if (latencies_.empty())
293 return 0;
294 return *std::max_element(latencies_.begin(), latencies_.end());
295 }
296
297 int average_latency() const {
298 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
299 if (latencies_.empty())
300 return 0;
301 return 0.5 + static_cast<double>(
302 std::accumulate(latencies_.begin(), latencies_.end(), 0)) /
303 latencies_.size();
304 }
305
306 void PrintResults() const {
307 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
308 PRINT("] ");
309 for (auto it = latencies_.begin(); it != latencies_.end(); ++it) {
310 PRINTD("%d ", *it);
311 }
312 PRINT("\n");
313 PRINT("[..........] [min, max, avg]=[%d, %d, %d] ms\n", min_latency(),
314 max_latency(), average_latency());
315 }
316
317 rtc::CriticalSection lock_;
318 rtc::RaceChecker race_checker_;
319 rtc::ThreadChecker read_thread_checker_;
320 rtc::ThreadChecker write_thread_checker_;
321
Danil Chapovalov196100e2018-06-21 10:17:24 +0200322 absl::optional<int64_t> pulse_time_ RTC_GUARDED_BY(lock_);
danilchap56359be2017-09-07 07:53:45 -0700323 std::vector<int> latencies_ RTC_GUARDED_BY(race_checker_);
Niels Möller1e062892018-02-07 10:18:32 +0100324 size_t read_count_ RTC_GUARDED_BY(read_thread_checker_) = 0;
325 size_t write_count_ RTC_GUARDED_BY(write_thread_checker_) = 0;
henrika714e5cd2017-04-20 08:03:11 -0700326};
327
henrikaf2f91fa2017-03-17 04:26:22 -0700328// Mocks the AudioTransport object and proxies actions for the two callbacks
329// (RecordedDataIsAvailable and NeedMorePlayData) to different implementations
330// of AudioStreamInterface.
331class MockAudioTransport : public test::MockAudioTransport {
332 public:
333 explicit MockAudioTransport(TransportType type) : type_(type) {}
334 ~MockAudioTransport() {}
335
336 // Set default actions of the mock object. We are delegating to fake
337 // implementation where the number of callbacks is counted and an event
338 // is set after a certain number of callbacks. Audio parameters are also
339 // checked.
henrikae24991d2017-04-06 01:14:23 -0700340 void HandleCallbacks(rtc::Event* event,
341 AudioStream* audio_stream,
342 int num_callbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700343 event_ = event;
henrikae24991d2017-04-06 01:14:23 -0700344 audio_stream_ = audio_stream;
henrikaf2f91fa2017-03-17 04:26:22 -0700345 num_callbacks_ = num_callbacks;
346 if (play_mode()) {
347 ON_CALL(*this, NeedMorePlayData(_, _, _, _, _, _, _, _))
348 .WillByDefault(
349 Invoke(this, &MockAudioTransport::RealNeedMorePlayData));
350 }
351 if (rec_mode()) {
352 ON_CALL(*this, RecordedDataIsAvailable(_, _, _, _, _, _, _, _, _, _))
353 .WillByDefault(
354 Invoke(this, &MockAudioTransport::RealRecordedDataIsAvailable));
355 }
356 }
357
henrika5b6afc02018-09-05 14:34:40 +0200358 // Special constructor used in manual tests where the user wants to run audio
359 // until e.g. a keyboard key is pressed. The event flag is set to nullptr by
360 // default since it is up to the user to stop the test. See e.g.
361 // DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey().
362 void HandleCallbacks(AudioStream* audio_stream) {
363 HandleCallbacks(nullptr, audio_stream, 0);
364 }
365
henrikaf2f91fa2017-03-17 04:26:22 -0700366 int32_t RealRecordedDataIsAvailable(const void* audio_buffer,
367 const size_t samples_per_channel,
368 const size_t bytes_per_frame,
369 const size_t channels,
370 const uint32_t sample_rate,
371 const uint32_t total_delay_ms,
372 const int32_t clock_drift,
373 const uint32_t current_mic_level,
374 const bool typing_status,
375 uint32_t& new_mic_level) {
376 EXPECT_TRUE(rec_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700377 // Store audio parameters once in the first callback. For all other
378 // callbacks, verify that the provided audio parameters are maintained and
379 // that each callback corresponds to 10ms for any given sample rate.
380 if (!record_parameters_.is_complete()) {
381 record_parameters_.reset(sample_rate, channels, samples_per_channel);
382 } else {
383 EXPECT_EQ(samples_per_channel, record_parameters_.frames_per_buffer());
384 EXPECT_EQ(bytes_per_frame, record_parameters_.GetBytesPerFrame());
385 EXPECT_EQ(channels, record_parameters_.channels());
386 EXPECT_EQ(static_cast<int>(sample_rate),
387 record_parameters_.sample_rate());
388 EXPECT_EQ(samples_per_channel,
389 record_parameters_.frames_per_10ms_buffer());
390 }
henrika78e0ac12018-09-27 16:23:21 +0200391 {
392 rtc::CritScope lock(&lock_);
393 rec_count_++;
394 }
henrikae24991d2017-04-06 01:14:23 -0700395 // Write audio data to audio stream object if one has been injected.
396 if (audio_stream_) {
397 audio_stream_->Write(
398 rtc::MakeArrayView(static_cast<const int16_t*>(audio_buffer),
henrikaeb98c722018-03-20 12:54:07 +0100399 samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700400 }
henrikaf2f91fa2017-03-17 04:26:22 -0700401 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200402 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700403 event_->Set();
404 }
405 return 0;
406 }
407
408 int32_t RealNeedMorePlayData(const size_t samples_per_channel,
409 const size_t bytes_per_frame,
410 const size_t channels,
411 const uint32_t sample_rate,
412 void* audio_buffer,
henrikaeb98c722018-03-20 12:54:07 +0100413 size_t& samples_out,
henrikaf2f91fa2017-03-17 04:26:22 -0700414 int64_t* elapsed_time_ms,
415 int64_t* ntp_time_ms) {
416 EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700417 // Store audio parameters once in the first callback. For all other
418 // callbacks, verify that the provided audio parameters are maintained and
419 // that each callback corresponds to 10ms for any given sample rate.
420 if (!playout_parameters_.is_complete()) {
421 playout_parameters_.reset(sample_rate, channels, samples_per_channel);
422 } else {
423 EXPECT_EQ(samples_per_channel, playout_parameters_.frames_per_buffer());
424 EXPECT_EQ(bytes_per_frame, playout_parameters_.GetBytesPerFrame());
425 EXPECT_EQ(channels, playout_parameters_.channels());
426 EXPECT_EQ(static_cast<int>(sample_rate),
427 playout_parameters_.sample_rate());
428 EXPECT_EQ(samples_per_channel,
429 playout_parameters_.frames_per_10ms_buffer());
430 }
henrika78e0ac12018-09-27 16:23:21 +0200431 {
432 rtc::CritScope lock(&lock_);
433 play_count_++;
434 }
henrikaeb98c722018-03-20 12:54:07 +0100435 samples_out = samples_per_channel * channels;
henrikae24991d2017-04-06 01:14:23 -0700436 // Read audio data from audio stream object if one has been injected.
437 if (audio_stream_) {
henrikaeb98c722018-03-20 12:54:07 +0100438 audio_stream_->Read(rtc::MakeArrayView(
439 static_cast<int16_t*>(audio_buffer), samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700440 } else {
441 // Fill the audio buffer with zeros to avoid disturbing audio.
442 const size_t num_bytes = samples_per_channel * bytes_per_frame;
443 std::memset(audio_buffer, 0, num_bytes);
444 }
henrikaf2f91fa2017-03-17 04:26:22 -0700445 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200446 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700447 event_->Set();
448 }
449 return 0;
450 }
451
452 bool ReceivedEnoughCallbacks() {
453 bool recording_done = false;
454 if (rec_mode()) {
henrika78e0ac12018-09-27 16:23:21 +0200455 rtc::CritScope lock(&lock_);
henrikaf2f91fa2017-03-17 04:26:22 -0700456 recording_done = rec_count_ >= num_callbacks_;
457 } else {
458 recording_done = true;
459 }
460 bool playout_done = false;
461 if (play_mode()) {
henrika78e0ac12018-09-27 16:23:21 +0200462 rtc::CritScope lock(&lock_);
henrikaf2f91fa2017-03-17 04:26:22 -0700463 playout_done = play_count_ >= num_callbacks_;
464 } else {
465 playout_done = true;
466 }
467 return recording_done && playout_done;
468 }
469
470 bool play_mode() const {
471 return type_ == TransportType::kPlay ||
472 type_ == TransportType::kPlayAndRecord;
473 }
474
475 bool rec_mode() const {
476 return type_ == TransportType::kRecord ||
477 type_ == TransportType::kPlayAndRecord;
478 }
479
henrika5b6afc02018-09-05 14:34:40 +0200480 void ResetCallbackCounters() {
henrika78e0ac12018-09-27 16:23:21 +0200481 rtc::CritScope lock(&lock_);
henrika5b6afc02018-09-05 14:34:40 +0200482 if (play_mode()) {
483 play_count_ = 0;
484 }
485 if (rec_mode()) {
486 rec_count_ = 0;
487 }
488 }
489
henrikaf2f91fa2017-03-17 04:26:22 -0700490 private:
henrika78e0ac12018-09-27 16:23:21 +0200491 rtc::CriticalSection lock_;
henrikaf2f91fa2017-03-17 04:26:22 -0700492 TransportType type_ = TransportType::kInvalid;
493 rtc::Event* event_ = nullptr;
henrikae24991d2017-04-06 01:14:23 -0700494 AudioStream* audio_stream_ = nullptr;
henrikaf2f91fa2017-03-17 04:26:22 -0700495 size_t num_callbacks_ = 0;
henrika78e0ac12018-09-27 16:23:21 +0200496 size_t play_count_ RTC_GUARDED_BY(lock_) = 0;
497 size_t rec_count_ RTC_GUARDED_BY(lock_) = 0;
henrikaf2f91fa2017-03-17 04:26:22 -0700498 AudioParameters playout_parameters_;
499 AudioParameters record_parameters_;
500};
501
502// AudioDeviceTest test fixture.
Yves Gerey1afe6572019-07-18 22:01:09 +0200503
Yves Gerey704c8c42019-08-13 22:32:46 +0200504class AudioDeviceTest
henrikaec9c7452018-06-08 16:10:03 +0200505 : public ::testing::TestWithParam<webrtc::AudioDeviceModule::AudioLayer> {
henrikaf2f91fa2017-03-17 04:26:22 -0700506 protected:
Yves Gerey704c8c42019-08-13 22:32:46 +0200507 AudioDeviceTest()
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200508 : audio_layer_(GetParam()),
509 task_queue_factory_(CreateDefaultTaskQueueFactory()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700510 rtc::LogMessage::LogToDebug(rtc::LS_INFO);
511 // Add extra logging fields here if needed for debugging.
henrikaec9c7452018-06-08 16:10:03 +0200512 rtc::LogMessage::LogTimestamps();
513 rtc::LogMessage::LogThreads();
514 audio_device_ = CreateAudioDevice();
henrikaf2f91fa2017-03-17 04:26:22 -0700515 EXPECT_NE(audio_device_.get(), nullptr);
516 AudioDeviceModule::AudioLayer audio_layer;
maxmorin33bf69a2017-03-23 04:06:53 -0700517 int got_platform_audio_layer =
518 audio_device_->ActiveAudioLayer(&audio_layer);
henrika919dc2e2017-10-12 14:24:55 +0200519 // First, ensure that a valid audio layer can be activated.
520 if (got_platform_audio_layer != 0) {
henrikaf2f91fa2017-03-17 04:26:22 -0700521 requirements_satisfied_ = false;
522 }
henrika919dc2e2017-10-12 14:24:55 +0200523 // Next, verify that the ADM can be initialized.
henrikaf2f91fa2017-03-17 04:26:22 -0700524 if (requirements_satisfied_) {
henrika919dc2e2017-10-12 14:24:55 +0200525 requirements_satisfied_ = (audio_device_->Init() == 0);
526 }
527 // Finally, ensure that at least one valid device exists in each direction.
528 if (requirements_satisfied_) {
henrikaf2f91fa2017-03-17 04:26:22 -0700529 const int16_t num_playout_devices = audio_device_->PlayoutDevices();
530 const int16_t num_record_devices = audio_device_->RecordingDevices();
531 requirements_satisfied_ =
532 num_playout_devices > 0 && num_record_devices > 0;
533 }
henrikaf2f91fa2017-03-17 04:26:22 -0700534 if (requirements_satisfied_) {
henrika5773ad32018-09-21 14:53:10 +0200535 EXPECT_EQ(0, audio_device_->SetPlayoutDevice(AUDIO_DEVICE_ID));
henrikaf2f91fa2017-03-17 04:26:22 -0700536 EXPECT_EQ(0, audio_device_->InitSpeaker());
henrikaf2f91fa2017-03-17 04:26:22 -0700537 EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
538 EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
henrika5773ad32018-09-21 14:53:10 +0200539 EXPECT_EQ(0, audio_device_->SetRecordingDevice(AUDIO_DEVICE_ID));
540 EXPECT_EQ(0, audio_device_->InitMicrophone());
henrika0238ba82017-03-28 04:38:29 -0700541 // Avoid asking for input stereo support and always record in mono
542 // since asking can cause issues in combination with remote desktop.
543 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
544 // details.
545 EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
henrikaf2f91fa2017-03-17 04:26:22 -0700546 }
547 }
548
Yves Gereyb93a2452019-07-19 22:46:13 +0200549 // This is needed by all tests using MockAudioTransport,
550 // since there is no way to unregister it.
551 // Without Terminate(), audio_device would still accesses
552 // the destructed mock via "webrtc_audio_module_rec_thread".
553 // An alternative would be for the mock to outlive audio_device.
554 void PreTearDown() { EXPECT_EQ(0, audio_device_->Terminate()); }
555
Yves Gerey704c8c42019-08-13 22:32:46 +0200556 virtual ~AudioDeviceTest() {
henrikaf2f91fa2017-03-17 04:26:22 -0700557 if (audio_device_) {
558 EXPECT_EQ(0, audio_device_->Terminate());
559 }
560 }
561
562 bool requirements_satisfied() const { return requirements_satisfied_; }
563 rtc::Event* event() { return &event_; }
henrika5b6afc02018-09-05 14:34:40 +0200564 AudioDeviceModule::AudioLayer audio_layer() const { return audio_layer_; }
henrikaf2f91fa2017-03-17 04:26:22 -0700565
henrika5b6afc02018-09-05 14:34:40 +0200566 // AudioDeviceModuleForTest extends the default ADM interface with some extra
567 // test methods. Intended for usage in tests only and requires a unique
568 // factory method. See CreateAudioDevice() for details.
569 const rtc::scoped_refptr<AudioDeviceModuleForTest>& audio_device() const {
henrikaf2f91fa2017-03-17 04:26:22 -0700570 return audio_device_;
571 }
572
henrika5b6afc02018-09-05 14:34:40 +0200573 rtc::scoped_refptr<AudioDeviceModuleForTest> CreateAudioDevice() {
henrikaec9c7452018-06-08 16:10:03 +0200574 // Use the default factory for kPlatformDefaultAudio and a special factory
henrika5b6afc02018-09-05 14:34:40 +0200575 // CreateWindowsCoreAudioAudioDeviceModuleForTest() for kWindowsCoreAudio2.
henrikaec9c7452018-06-08 16:10:03 +0200576 // The value of |audio_layer_| is set at construction by GetParam() and two
577 // different layers are tested on Windows only.
578 if (audio_layer_ == AudioDeviceModule::kPlatformDefaultAudio) {
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200579 return AudioDeviceModule::CreateForTest(audio_layer_,
580 task_queue_factory_.get());
henrikaec9c7452018-06-08 16:10:03 +0200581 } else if (audio_layer_ == AudioDeviceModule::kWindowsCoreAudio2) {
582#ifdef WEBRTC_WIN
583 // We must initialize the COM library on a thread before we calling any of
584 // the library functions. All COM functions in the ADM will return
585 // CO_E_NOTINITIALIZED otherwise.
Karl Wiberg918f50c2018-07-05 11:40:33 +0200586 com_initializer_ = absl::make_unique<webrtc_win::ScopedCOMInitializer>(
henrikaec9c7452018-06-08 16:10:03 +0200587 webrtc_win::ScopedCOMInitializer::kMTA);
588 EXPECT_TRUE(com_initializer_->Succeeded());
589 EXPECT_TRUE(webrtc_win::core_audio_utility::IsSupported());
590 EXPECT_TRUE(webrtc_win::core_audio_utility::IsMMCSSSupported());
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200591 return CreateWindowsCoreAudioAudioDeviceModuleForTest(
henrikad8c6ec42019-07-18 15:17:28 +0200592 task_queue_factory_.get(), true);
henrikaec9c7452018-06-08 16:10:03 +0200593#else
594 return nullptr;
595#endif
596 } else {
597 return nullptr;
598 }
599 }
600
henrikaf2f91fa2017-03-17 04:26:22 -0700601 void StartPlayout() {
602 EXPECT_FALSE(audio_device()->Playing());
603 EXPECT_EQ(0, audio_device()->InitPlayout());
604 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
605 EXPECT_EQ(0, audio_device()->StartPlayout());
606 EXPECT_TRUE(audio_device()->Playing());
607 }
608
609 void StopPlayout() {
610 EXPECT_EQ(0, audio_device()->StopPlayout());
611 EXPECT_FALSE(audio_device()->Playing());
612 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
613 }
614
615 void StartRecording() {
616 EXPECT_FALSE(audio_device()->Recording());
617 EXPECT_EQ(0, audio_device()->InitRecording());
618 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
619 EXPECT_EQ(0, audio_device()->StartRecording());
620 EXPECT_TRUE(audio_device()->Recording());
621 }
622
623 void StopRecording() {
624 EXPECT_EQ(0, audio_device()->StopRecording());
625 EXPECT_FALSE(audio_device()->Recording());
626 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
627 }
628
henrikaec9c7452018-06-08 16:10:03 +0200629 bool NewWindowsAudioDeviceModuleIsUsed() {
630#ifdef WEBRTC_WIN
631 AudioDeviceModule::AudioLayer audio_layer;
632 EXPECT_EQ(0, audio_device()->ActiveAudioLayer(&audio_layer));
633 if (audio_layer == AudioDeviceModule::kWindowsCoreAudio2) {
634 // Default device is always added as first element in the list and the
635 // default communication device as the second element. Hence, the list
636 // contains two extra elements in this case.
637 return true;
638 }
639#endif
640 return false;
641 }
642
henrikaf2f91fa2017-03-17 04:26:22 -0700643 private:
henrikaec9c7452018-06-08 16:10:03 +0200644#ifdef WEBRTC_WIN
645 // Windows Core Audio based ADM needs to run on a COM initialized thread.
646 std::unique_ptr<webrtc_win::ScopedCOMInitializer> com_initializer_;
647#endif
648 AudioDeviceModule::AudioLayer audio_layer_;
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200649 std::unique_ptr<TaskQueueFactory> task_queue_factory_;
henrikaf2f91fa2017-03-17 04:26:22 -0700650 bool requirements_satisfied_ = true;
651 rtc::Event event_;
henrika5b6afc02018-09-05 14:34:40 +0200652 rtc::scoped_refptr<AudioDeviceModuleForTest> audio_device_;
henrikaf2f91fa2017-03-17 04:26:22 -0700653 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700654};
655
henrikaec9c7452018-06-08 16:10:03 +0200656// Instead of using the test fixture, verify that the different factory methods
657// work as intended.
658TEST(AudioDeviceTestWin, ConstructDestructWithFactory) {
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200659 std::unique_ptr<TaskQueueFactory> task_queue_factory =
660 CreateDefaultTaskQueueFactory();
henrikaec9c7452018-06-08 16:10:03 +0200661 rtc::scoped_refptr<AudioDeviceModule> audio_device;
662 // The default factory should work for all platforms when a default ADM is
663 // requested.
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200664 audio_device = AudioDeviceModule::Create(
665 AudioDeviceModule::kPlatformDefaultAudio, task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200666 EXPECT_TRUE(audio_device);
667 audio_device = nullptr;
668#ifdef WEBRTC_WIN
669 // For Windows, the old factory method creates an ADM where the platform-
670 // specific parts are implemented by an AudioDeviceGeneric object. Verify
671 // that the old factory can't be used in combination with the latest audio
672 // layer AudioDeviceModule::kWindowsCoreAudio2.
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200673 audio_device = AudioDeviceModule::Create(
674 AudioDeviceModule::kWindowsCoreAudio2, task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200675 EXPECT_FALSE(audio_device);
676 audio_device = nullptr;
677 // Instead, ensure that the new dedicated factory method called
678 // CreateWindowsCoreAudioAudioDeviceModule() can be used on Windows and that
679 // it sets the audio layer to kWindowsCoreAudio2 implicitly. Note that, the
680 // new ADM for Windows must be created on a COM thread.
681 webrtc_win::ScopedCOMInitializer com_initializer(
682 webrtc_win::ScopedCOMInitializer::kMTA);
683 EXPECT_TRUE(com_initializer.Succeeded());
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200684 audio_device =
685 CreateWindowsCoreAudioAudioDeviceModule(task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200686 EXPECT_TRUE(audio_device);
687 AudioDeviceModule::AudioLayer audio_layer;
688 EXPECT_EQ(0, audio_device->ActiveAudioLayer(&audio_layer));
689 EXPECT_EQ(audio_layer, AudioDeviceModule::kWindowsCoreAudio2);
690#endif
691}
henrikaf2f91fa2017-03-17 04:26:22 -0700692
henrikaec9c7452018-06-08 16:10:03 +0200693// Uses the test fixture to create, initialize and destruct the ADM.
Yves Gerey704c8c42019-08-13 22:32:46 +0200694TEST_P(AudioDeviceTest, ConstructDestructDefault) {}
henrikaec9c7452018-06-08 16:10:03 +0200695
Yves Gerey704c8c42019-08-13 22:32:46 +0200696TEST_P(AudioDeviceTest, InitTerminate) {
henrikaf2f91fa2017-03-17 04:26:22 -0700697 SKIP_TEST_IF_NOT(requirements_satisfied());
698 // Initialization is part of the test fixture.
699 EXPECT_TRUE(audio_device()->Initialized());
700 EXPECT_EQ(0, audio_device()->Terminate());
701 EXPECT_FALSE(audio_device()->Initialized());
702}
703
henrikaec9c7452018-06-08 16:10:03 +0200704// Enumerate all available and active output devices.
Yves Gerey704c8c42019-08-13 22:32:46 +0200705TEST_P(AudioDeviceTest, PlayoutDeviceNames) {
henrikaf2f91fa2017-03-17 04:26:22 -0700706 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaec9c7452018-06-08 16:10:03 +0200707 char device_name[kAdmMaxDeviceNameSize];
708 char unique_id[kAdmMaxGuidSize];
709 int num_devices = audio_device()->PlayoutDevices();
710 if (NewWindowsAudioDeviceModuleIsUsed()) {
711 num_devices += 2;
712 }
713 EXPECT_GT(num_devices, 0);
714 for (int i = 0; i < num_devices; ++i) {
715 EXPECT_EQ(0, audio_device()->PlayoutDeviceName(i, device_name, unique_id));
716 }
717 EXPECT_EQ(-1, audio_device()->PlayoutDeviceName(num_devices, device_name,
718 unique_id));
719}
720
721// Enumerate all available and active input devices.
Yves Gerey704c8c42019-08-13 22:32:46 +0200722TEST_P(AudioDeviceTest, RecordingDeviceNames) {
henrikaec9c7452018-06-08 16:10:03 +0200723 SKIP_TEST_IF_NOT(requirements_satisfied());
724 char device_name[kAdmMaxDeviceNameSize];
725 char unique_id[kAdmMaxGuidSize];
726 int num_devices = audio_device()->RecordingDevices();
727 if (NewWindowsAudioDeviceModuleIsUsed()) {
728 num_devices += 2;
729 }
730 EXPECT_GT(num_devices, 0);
731 for (int i = 0; i < num_devices; ++i) {
732 EXPECT_EQ(0,
733 audio_device()->RecordingDeviceName(i, device_name, unique_id));
734 }
735 EXPECT_EQ(-1, audio_device()->RecordingDeviceName(num_devices, device_name,
736 unique_id));
737}
738
739// Counts number of active output devices and ensure that all can be selected.
Yves Gerey704c8c42019-08-13 22:32:46 +0200740TEST_P(AudioDeviceTest, SetPlayoutDevice) {
henrikaec9c7452018-06-08 16:10:03 +0200741 SKIP_TEST_IF_NOT(requirements_satisfied());
742 int num_devices = audio_device()->PlayoutDevices();
743 if (NewWindowsAudioDeviceModuleIsUsed()) {
744 num_devices += 2;
745 }
746 EXPECT_GT(num_devices, 0);
747 // Verify that all available playout devices can be set (not enabled yet).
748 for (int i = 0; i < num_devices; ++i) {
749 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(i));
750 }
751 EXPECT_EQ(-1, audio_device()->SetPlayoutDevice(num_devices));
752#ifdef WEBRTC_WIN
753 // On Windows, verify the alternative method where the user can select device
754 // by role.
755 EXPECT_EQ(
756 0, audio_device()->SetPlayoutDevice(AudioDeviceModule::kDefaultDevice));
757 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(
758 AudioDeviceModule::kDefaultCommunicationDevice));
759#endif
760}
761
762// Counts number of active input devices and ensure that all can be selected.
Yves Gerey704c8c42019-08-13 22:32:46 +0200763TEST_P(AudioDeviceTest, SetRecordingDevice) {
henrikaec9c7452018-06-08 16:10:03 +0200764 SKIP_TEST_IF_NOT(requirements_satisfied());
765 int num_devices = audio_device()->RecordingDevices();
766 if (NewWindowsAudioDeviceModuleIsUsed()) {
767 num_devices += 2;
768 }
769 EXPECT_GT(num_devices, 0);
770 // Verify that all available recording devices can be set (not enabled yet).
771 for (int i = 0; i < num_devices; ++i) {
772 EXPECT_EQ(0, audio_device()->SetRecordingDevice(i));
773 }
774 EXPECT_EQ(-1, audio_device()->SetRecordingDevice(num_devices));
775#ifdef WEBRTC_WIN
776 // On Windows, verify the alternative method where the user can select device
777 // by role.
778 EXPECT_EQ(
779 0, audio_device()->SetRecordingDevice(AudioDeviceModule::kDefaultDevice));
780 EXPECT_EQ(0, audio_device()->SetRecordingDevice(
781 AudioDeviceModule::kDefaultCommunicationDevice));
782#endif
783}
784
785// Tests Start/Stop playout without any registered audio callback.
Yves Gerey704c8c42019-08-13 22:32:46 +0200786TEST_P(AudioDeviceTest, StartStopPlayout) {
henrikaec9c7452018-06-08 16:10:03 +0200787 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaf2f91fa2017-03-17 04:26:22 -0700788 StartPlayout();
789 StopPlayout();
790}
791
792// Tests Start/Stop recording without any registered audio callback.
Yves Gerey704c8c42019-08-13 22:32:46 +0200793TEST_P(AudioDeviceTest, StartStopRecording) {
henrikaf2f91fa2017-03-17 04:26:22 -0700794 SKIP_TEST_IF_NOT(requirements_satisfied());
795 StartRecording();
796 StopRecording();
henrikaf2f91fa2017-03-17 04:26:22 -0700797}
798
henrika6b3e1a22017-09-25 16:34:30 +0200799// Tests Init/Stop/Init recording without any registered audio callback.
800// See https://bugs.chromium.org/p/webrtc/issues/detail?id=8041 for details
801// on why this test is useful.
Yves Gerey704c8c42019-08-13 22:32:46 +0200802TEST_P(AudioDeviceTest, InitStopInitRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200803 SKIP_TEST_IF_NOT(requirements_satisfied());
804 EXPECT_EQ(0, audio_device()->InitRecording());
805 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
806 StopRecording();
807 EXPECT_EQ(0, audio_device()->InitRecording());
808 StopRecording();
809}
810
henrikad4049462019-07-12 13:37:11 +0200811// Verify that additional attempts to initialize or start recording while
812// already being active works. Additional calls should just be ignored.
Yves Gerey704c8c42019-08-13 22:32:46 +0200813TEST_P(AudioDeviceTest, StartInitRecording) {
henrikad4049462019-07-12 13:37:11 +0200814 SKIP_TEST_IF_NOT(requirements_satisfied());
815 StartRecording();
816 // An additional attempt to initialize at this stage should be ignored.
817 EXPECT_EQ(0, audio_device()->InitRecording());
818 // Same for additional request to start recording while already active.
819 EXPECT_EQ(0, audio_device()->StartRecording());
820 StopRecording();
821}
822
823// Verify that additional attempts to initialize or start playou while
824// already being active works. Additional calls should just be ignored.
Yves Gerey704c8c42019-08-13 22:32:46 +0200825TEST_P(AudioDeviceTest, StartInitPlayout) {
henrikad4049462019-07-12 13:37:11 +0200826 SKIP_TEST_IF_NOT(requirements_satisfied());
827 StartPlayout();
828 // An additional attempt to initialize at this stage should be ignored.
829 EXPECT_EQ(0, audio_device()->InitPlayout());
830 // Same for additional request to start playout while already active.
831 EXPECT_EQ(0, audio_device()->StartPlayout());
832 StopPlayout();
833}
834
henrika6b3e1a22017-09-25 16:34:30 +0200835// Tests Init/Stop/Init recording while playout is active.
Yves Gerey704c8c42019-08-13 22:32:46 +0200836TEST_P(AudioDeviceTest, InitStopInitRecordingWhilePlaying) {
henrika6b3e1a22017-09-25 16:34:30 +0200837 SKIP_TEST_IF_NOT(requirements_satisfied());
838 StartPlayout();
839 EXPECT_EQ(0, audio_device()->InitRecording());
840 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
841 StopRecording();
842 EXPECT_EQ(0, audio_device()->InitRecording());
843 StopRecording();
844 StopPlayout();
845}
846
847// Tests Init/Stop/Init playout without any registered audio callback.
Yves Gerey704c8c42019-08-13 22:32:46 +0200848TEST_P(AudioDeviceTest, InitStopInitPlayout) {
henrika6b3e1a22017-09-25 16:34:30 +0200849 SKIP_TEST_IF_NOT(requirements_satisfied());
850 EXPECT_EQ(0, audio_device()->InitPlayout());
851 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
852 StopPlayout();
853 EXPECT_EQ(0, audio_device()->InitPlayout());
854 StopPlayout();
855}
856
857// Tests Init/Stop/Init playout while recording is active.
Yves Gerey704c8c42019-08-13 22:32:46 +0200858TEST_P(AudioDeviceTest, InitStopInitPlayoutWhileRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200859 SKIP_TEST_IF_NOT(requirements_satisfied());
860 StartRecording();
861 EXPECT_EQ(0, audio_device()->InitPlayout());
862 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
863 StopPlayout();
864 EXPECT_EQ(0, audio_device()->InitPlayout());
865 StopPlayout();
866 StopRecording();
867}
868
henrika5b6afc02018-09-05 14:34:40 +0200869// TODO(henrika): restart without intermediate destruction is currently only
870// supported on Windows.
871#ifdef WEBRTC_WIN
872// Tests Start/Stop playout followed by a second session (emulates a restart
873// triggered by a user using public APIs).
Yves Gerey704c8c42019-08-13 22:32:46 +0200874TEST_P(AudioDeviceTest, StartStopPlayoutWithExternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200875 SKIP_TEST_IF_NOT(requirements_satisfied());
876 StartPlayout();
877 StopPlayout();
878 // Restart playout without destroying the ADM in between. Ensures that we
879 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
880 StartPlayout();
881 StopPlayout();
882}
883
884// Tests Start/Stop recording followed by a second session (emulates a restart
885// triggered by a user using public APIs).
Yves Gerey704c8c42019-08-13 22:32:46 +0200886TEST_P(AudioDeviceTest, StartStopRecordingWithExternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200887 SKIP_TEST_IF_NOT(requirements_satisfied());
888 StartRecording();
889 StopRecording();
890 // Restart recording without destroying the ADM in between. Ensures that we
891 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
892 StartRecording();
893 StopRecording();
894}
895
896// Tests Start/Stop playout followed by a second session (emulates a restart
897// triggered by an internal callback e.g. corresponding to a device switch).
898// Note that, internal restart is only supported in combination with the latest
899// Windows ADM.
Yves Gerey704c8c42019-08-13 22:32:46 +0200900TEST_P(AudioDeviceTest, StartStopPlayoutWithInternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200901 SKIP_TEST_IF_NOT(requirements_satisfied());
902 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
903 return;
904 }
905 MockAudioTransport mock(TransportType::kPlay);
906 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
907 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
908 .Times(AtLeast(kNumCallbacks));
909 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
910 StartPlayout();
911 event()->Wait(kTestTimeOutInMilliseconds);
912 EXPECT_TRUE(audio_device()->Playing());
913 // Restart playout but without stopping the internal audio thread.
914 // This procedure uses a non-public test API and it emulates what happens
915 // inside the ADM when e.g. a device is removed.
916 EXPECT_EQ(0, audio_device()->RestartPlayoutInternally());
917
918 // Run basic tests of public APIs while a restart attempt is active.
919 // These calls should now be very thin and not trigger any new actions.
920 EXPECT_EQ(-1, audio_device()->StopPlayout());
921 EXPECT_TRUE(audio_device()->Playing());
922 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
923 EXPECT_EQ(0, audio_device()->InitPlayout());
924 EXPECT_EQ(0, audio_device()->StartPlayout());
925
926 // Wait until audio has restarted and a new sequence of audio callbacks
927 // becomes active.
928 // TODO(henrika): is it possible to verify that the internal state transition
929 // is Stop->Init->Start?
930 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
931 mock.ResetCallbackCounters();
932 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
933 .Times(AtLeast(kNumCallbacks));
934 event()->Wait(kTestTimeOutInMilliseconds);
935 EXPECT_TRUE(audio_device()->Playing());
936 // Stop playout and the audio thread after successful internal restart.
937 StopPlayout();
Yves Gereyb93a2452019-07-19 22:46:13 +0200938 PreTearDown();
henrika5b6afc02018-09-05 14:34:40 +0200939}
940
941// Tests Start/Stop recording followed by a second session (emulates a restart
942// triggered by an internal callback e.g. corresponding to a device switch).
943// Note that, internal restart is only supported in combination with the latest
944// Windows ADM.
Yves Gerey704c8c42019-08-13 22:32:46 +0200945TEST_P(AudioDeviceTest, StartStopRecordingWithInternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200946 SKIP_TEST_IF_NOT(requirements_satisfied());
947 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
948 return;
949 }
950 MockAudioTransport mock(TransportType::kRecord);
951 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
952 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
953 false, _))
954 .Times(AtLeast(kNumCallbacks));
955 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
956 StartRecording();
957 event()->Wait(kTestTimeOutInMilliseconds);
958 EXPECT_TRUE(audio_device()->Recording());
959 // Restart recording but without stopping the internal audio thread.
960 // This procedure uses a non-public test API and it emulates what happens
961 // inside the ADM when e.g. a device is removed.
962 EXPECT_EQ(0, audio_device()->RestartRecordingInternally());
963
964 // Run basic tests of public APIs while a restart attempt is active.
965 // These calls should now be very thin and not trigger any new actions.
966 EXPECT_EQ(-1, audio_device()->StopRecording());
967 EXPECT_TRUE(audio_device()->Recording());
968 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
969 EXPECT_EQ(0, audio_device()->InitRecording());
970 EXPECT_EQ(0, audio_device()->StartRecording());
971
972 // Wait until audio has restarted and a new sequence of audio callbacks
973 // becomes active.
974 // TODO(henrika): is it possible to verify that the internal state transition
975 // is Stop->Init->Start?
976 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
977 mock.ResetCallbackCounters();
978 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
979 false, _))
980 .Times(AtLeast(kNumCallbacks));
981 event()->Wait(kTestTimeOutInMilliseconds);
982 EXPECT_TRUE(audio_device()->Recording());
983 // Stop recording and the audio thread after successful internal restart.
984 StopRecording();
Yves Gereyb93a2452019-07-19 22:46:13 +0200985 PreTearDown();
henrika5b6afc02018-09-05 14:34:40 +0200986}
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 Gerey704c8c42019-08-13 22:32:46 +0200994TEST_P(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();
Yves Gerey412282a2019-07-22 21:15:22 +02001004 PreTearDown();
henrikaf2f91fa2017-03-17 04:26:22 -07001005}
1006
Yves Gerey704c8c42019-08-13 22:32:46 +02001007// Don't run these tests in combination with sanitizers.
1008// They are already flaky *without* sanitizers.
1009// Sanitizers seem to increase flakiness (which brings noise),
1010// without reporting anything.
1011// TODO(webrtc:10867): Re-enable when flakiness fixed.
1012#if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
1013 defined(THREAD_SANITIZER)
1014#define MAYBE_StartRecordingVerifyCallbacks \
1015 DISABLED_StartRecordingVerifyCallbacks
1016#define MAYBE_StartPlayoutAndRecordingVerifyCallbacks \
1017 DISABLED_StartPlayoutAndRecordingVerifyCallbacks
1018#else
1019#define MAYBE_StartRecordingVerifyCallbacks StartRecordingVerifyCallbacks
1020#define MAYBE_StartPlayoutAndRecordingVerifyCallbacks \
1021 StartPlayoutAndRecordingVerifyCallbacks
1022#endif
1023
henrikaf2f91fa2017-03-17 04:26:22 -07001024// Start recording and verify that the native audio layer starts providing real
1025// audio samples using the RecordedDataIsAvailable() callback.
Yves Gerey704c8c42019-08-13 22:32:46 +02001026TEST_P(AudioDeviceTest, MAYBE_StartRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001027 SKIP_TEST_IF_NOT(requirements_satisfied());
1028 MockAudioTransport mock(TransportType::kRecord);
henrikae24991d2017-04-06 01:14:23 -07001029 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001030 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
1031 false, _))
1032 .Times(AtLeast(kNumCallbacks));
1033 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1034 StartRecording();
1035 event()->Wait(kTestTimeOutInMilliseconds);
1036 StopRecording();
Yves Gereyb93a2452019-07-19 22:46:13 +02001037 PreTearDown();
henrikaf2f91fa2017-03-17 04:26:22 -07001038}
1039
1040// Start playout and recording (full-duplex audio) and verify that audio is
1041// active in both directions.
Yves Gerey704c8c42019-08-13 22:32:46 +02001042TEST_P(AudioDeviceTest, MAYBE_StartPlayoutAndRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001043 SKIP_TEST_IF_NOT(requirements_satisfied());
1044 MockAudioTransport mock(TransportType::kPlayAndRecord);
henrikae24991d2017-04-06 01:14:23 -07001045 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001046 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
1047 .Times(AtLeast(kNumCallbacks));
1048 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
1049 false, _))
1050 .Times(AtLeast(kNumCallbacks));
1051 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1052 StartPlayout();
1053 StartRecording();
1054 event()->Wait(kTestTimeOutInMilliseconds);
1055 StopRecording();
1056 StopPlayout();
Yves Gereyb93a2452019-07-19 22:46:13 +02001057 PreTearDown();
henrikaf2f91fa2017-03-17 04:26:22 -07001058}
1059
henrikae24991d2017-04-06 01:14:23 -07001060// Start playout and recording and store recorded data in an intermediate FIFO
1061// buffer from which the playout side then reads its samples in the same order
1062// as they were stored. Under ideal circumstances, a callback sequence would
1063// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
1064// means 'packet played'. Under such conditions, the FIFO would contain max 1,
1065// with an average somewhere in (0,1) depending on how long the packets are
1066// buffered. However, under more realistic conditions, the size
1067// of the FIFO will vary more due to an unbalance between the two sides.
1068// This test tries to verify that the device maintains a balanced callback-
1069// sequence by running in loopback for a few seconds while measuring the size
1070// (max and average) of the FIFO. The size of the FIFO is increased by the
1071// recording side and decreased by the playout side.
Yves Gerey704c8c42019-08-13 22:32:46 +02001072TEST_P(AudioDeviceTest, RunPlayoutAndRecordingInFullDuplex) {
henrikae24991d2017-04-06 01:14:23 -07001073 SKIP_TEST_IF_NOT(requirements_satisfied());
1074 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1075 FifoAudioStream audio_stream;
1076 mock.HandleCallbacks(event(), &audio_stream,
1077 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
1078 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001079 // Run both sides using the same channel configuration to avoid conversions
1080 // between mono/stereo while running in full duplex mode. Also, some devices
1081 // (mainly on Windows) do not support mono.
1082 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1083 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
Gustaf Ullberg102b7282019-06-03 15:03:02 +02001084 // Mute speakers to prevent howling.
1085 EXPECT_EQ(0, audio_device()->SetSpeakerVolume(0));
henrikae24991d2017-04-06 01:14:23 -07001086 StartPlayout();
1087 StartRecording();
henrika714e5cd2017-04-20 08:03:11 -07001088 event()->Wait(static_cast<int>(
1089 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec)));
henrikae24991d2017-04-06 01:14:23 -07001090 StopRecording();
1091 StopPlayout();
Yves Gerey412282a2019-07-22 21:15:22 +02001092 // Avoid concurrent access to audio_stream.
1093 PreTearDown();
henrikae24991d2017-04-06 01:14:23 -07001094 // This thresholds is set rather high to accommodate differences in hardware
1095 // in several devices. The main idea is to capture cases where a very large
henrikab6ca7212017-10-06 12:47:52 +02001096 // latency is built up. See http://bugs.webrtc.org/7744 for examples on
1097 // bots where relatively large average latencies can happen.
1098 EXPECT_LE(audio_stream.average_size(), 25u);
henrikae24991d2017-04-06 01:14:23 -07001099 PRINT("\n");
1100}
1101
henrika5b6afc02018-09-05 14:34:40 +02001102// Runs audio in full duplex until user hits Enter. Intended as a manual test
1103// to ensure that the audio quality is good and that real device switches works
1104// as intended.
Yves Gerey704c8c42019-08-13 22:32:46 +02001105TEST_P(AudioDeviceTest,
henrika5b6afc02018-09-05 14:34:40 +02001106 DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey) {
1107 SKIP_TEST_IF_NOT(requirements_satisfied());
1108 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
1109 return;
1110 }
1111 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1112 FifoAudioStream audio_stream;
1113 mock.HandleCallbacks(&audio_stream);
1114 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1115 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1116 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
1117 // Ensure that the sample rate for both directions are identical so that we
1118 // always can listen to our own voice. Will lead to rate conversion (and
1119 // higher latency) if the native sample rate is not 48kHz.
1120 EXPECT_EQ(0, audio_device()->SetPlayoutSampleRate(48000));
1121 EXPECT_EQ(0, audio_device()->SetRecordingSampleRate(48000));
1122 StartPlayout();
1123 StartRecording();
1124 do {
1125 PRINT("Loopback audio is active at 48kHz. Press Enter to stop.\n");
1126 } while (getchar() != '\n');
1127 StopRecording();
1128 StopPlayout();
Yves Gereyb93a2452019-07-19 22:46:13 +02001129 PreTearDown();
henrika5b6afc02018-09-05 14:34:40 +02001130}
1131
henrika714e5cd2017-04-20 08:03:11 -07001132// Measures loopback latency and reports the min, max and average values for
1133// a full duplex audio session.
1134// The latency is measured like so:
1135// - Insert impulses periodically on the output side.
1136// - Detect the impulses on the input side.
1137// - Measure the time difference between the transmit time and receive time.
1138// - Store time differences in a vector and calculate min, max and average.
1139// This test needs the '--gtest_also_run_disabled_tests' flag to run and also
1140// some sort of audio feedback loop. E.g. a headset where the mic is placed
1141// close to the speaker to ensure highest possible echo. It is also recommended
1142// to run the test at highest possible output volume.
Yves Gerey704c8c42019-08-13 22:32:46 +02001143TEST_P(AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
henrika714e5cd2017-04-20 08:03:11 -07001144 SKIP_TEST_IF_NOT(requirements_satisfied());
1145 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1146 LatencyAudioStream audio_stream;
1147 mock.HandleCallbacks(event(), &audio_stream,
1148 kMeasureLatencyTimeInSec * kNumCallbacksPerSecond);
1149 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001150 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1151 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrika714e5cd2017-04-20 08:03:11 -07001152 StartPlayout();
1153 StartRecording();
1154 event()->Wait(static_cast<int>(
1155 std::max(kTestTimeOutInMilliseconds, 1000 * kMeasureLatencyTimeInSec)));
1156 StopRecording();
1157 StopPlayout();
Yves Gerey412282a2019-07-22 21:15:22 +02001158 // Avoid concurrent access to audio_stream.
1159 PreTearDown();
henrikac7d93582018-09-14 15:37:34 +02001160 // Verify that a sufficient number of transmitted impulses are detected.
1161 EXPECT_GE(audio_stream.num_latency_values(),
henrika714e5cd2017-04-20 08:03:11 -07001162 static_cast<size_t>(
henrikac7d93582018-09-14 15:37:34 +02001163 kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 2));
henrika714e5cd2017-04-20 08:03:11 -07001164 // Print out min, max and average delay values for debugging purposes.
1165 audio_stream.PrintResults();
1166}
1167
henrikaec9c7452018-06-08 16:10:03 +02001168#ifdef WEBRTC_WIN
1169// Test two different audio layers (or rather two different Core Audio
1170// implementations) for Windows.
Mirko Bonadeic84f6612019-01-31 12:20:57 +01001171INSTANTIATE_TEST_SUITE_P(
henrikaec9c7452018-06-08 16:10:03 +02001172 AudioLayerWin,
Yves Gerey704c8c42019-08-13 22:32:46 +02001173 AudioDeviceTest,
henrikaec9c7452018-06-08 16:10:03 +02001174 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio,
1175 AudioDeviceModule::kWindowsCoreAudio2));
1176#else
1177// For all platforms but Windows, only test the default audio layer.
Mirko Bonadeic84f6612019-01-31 12:20:57 +01001178INSTANTIATE_TEST_SUITE_P(
henrikaec9c7452018-06-08 16:10:03 +02001179 AudioLayer,
Yves Gerey704c8c42019-08-13 22:32:46 +02001180 AudioDeviceTest,
henrikaec9c7452018-06-08 16:10:03 +02001181 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio));
1182#endif
1183
henrikaf2f91fa2017-03-17 04:26:22 -07001184} // namespace webrtc