blob: 3e75d7624db0ddb5b49842a13f83c7a07f0d3d1f [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
Danil Chapovalov196100e2018-06-21 10:17:24 +020018#include "absl/types/optional.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/array_view.h"
Mirko Bonadeid9708072019-01-25 20:26:48 +010020#include "api/scoped_refptr.h"
Danil Chapovalov1c41be62019-04-01 09:16:12 +020021#include "api/task_queue/default_task_queue_factory.h"
22#include "api/task_queue/task_queue_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "modules/audio_device/audio_device_impl.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "modules/audio_device/include/mock_audio_transport.h"
25#include "rtc_base/buffer.h"
Steve Anton10542f22019-01-11 09:11:00 -080026#include "rtc_base/critical_section.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/event.h"
28#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010029#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/race_checker.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "rtc_base/thread_annotations.h"
32#include "rtc_base/thread_checker.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "rtc_base/time_utils.h"
henrika5b6afc02018-09-05 14:34:40 +020034#include "system_wrappers/include/sleep.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "test/gmock.h"
36#include "test/gtest.h"
henrikaec9c7452018-06-08 16:10:03 +020037#ifdef WEBRTC_WIN
38#include "modules/audio_device/include/audio_device_factory.h"
39#include "modules/audio_device/win/core_audio_utility_win.h"
40#endif
henrikaf2f91fa2017-03-17 04:26:22 -070041
42using ::testing::_;
43using ::testing::AtLeast;
44using ::testing::Ge;
45using ::testing::Invoke;
Jonas Olssona4d87372019-07-05 19:08:33 +020046using ::testing::Mock;
henrikaf2f91fa2017-03-17 04:26:22 -070047using ::testing::NiceMock;
48using ::testing::NotNull;
49
50namespace webrtc {
51namespace {
52
henrika5773ad32018-09-21 14:53:10 +020053// Using a #define for AUDIO_DEVICE since we will call *different* versions of
54// the ADM functions, depending on the ID type.
55#if defined(WEBRTC_WIN)
56#define AUDIO_DEVICE_ID (AudioDeviceModule::WindowsDeviceType::kDefaultDevice)
57#else
58#define AUDIO_DEVICE_ID (0u)
59#endif // defined(WEBRTC_WIN)
60
henrikae24991d2017-04-06 01:14:23 -070061// #define ENABLE_DEBUG_PRINTF
62#ifdef ENABLE_DEBUG_PRINTF
63#define PRINTD(...) fprintf(stderr, __VA_ARGS__);
64#else
65#define PRINTD(...) ((void)0)
66#endif
67#define PRINT(...) fprintf(stderr, __VA_ARGS__);
68
Yves Gerey1afe6572019-07-18 22:01:09 +020069// Don't run these tests if audio-related requirements are not met.
Yves Gereyee0550c2019-07-17 21:41:59 +020070#define SKIP_TEST_IF_NOT(requirements_satisfied) \
71 do { \
72 if (!requirements_satisfied) { \
73 GTEST_SKIP() << "Skipped. No audio device found."; \
74 } \
henrikaf2f91fa2017-03-17 04:26:22 -070075 } while (false)
henrikaf2f91fa2017-03-17 04:26:22 -070076
77// Number of callbacks (input or output) the tests waits for before we set
78// an event indicating that the test was OK.
henrikae24991d2017-04-06 01:14:23 -070079static constexpr size_t kNumCallbacks = 10;
henrikaf2f91fa2017-03-17 04:26:22 -070080// Max amount of time we wait for an event to be set while counting callbacks.
henrika714e5cd2017-04-20 08:03:11 -070081static constexpr size_t kTestTimeOutInMilliseconds = 10 * 1000;
henrikae24991d2017-04-06 01:14:23 -070082// Average number of audio callbacks per second assuming 10ms packet size.
83static constexpr size_t kNumCallbacksPerSecond = 100;
84// Run the full-duplex test during this time (unit is in seconds).
henrika714e5cd2017-04-20 08:03:11 -070085static constexpr size_t kFullDuplexTimeInSec = 5;
86// Length of round-trip latency measurements. Number of deteced impulses
87// shall be kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 1 since the
88// last transmitted pulse is not used.
89static constexpr size_t kMeasureLatencyTimeInSec = 10;
90// Sets the number of impulses per second in the latency test.
91static constexpr size_t kImpulseFrequencyInHz = 1;
92// Utilized in round-trip latency measurements to avoid capturing noise samples.
93static constexpr int kImpulseThreshold = 1000;
henrikaf2f91fa2017-03-17 04:26:22 -070094
95enum class TransportType {
96 kInvalid,
97 kPlay,
98 kRecord,
99 kPlayAndRecord,
100};
henrikae24991d2017-04-06 01:14:23 -0700101
102// Interface for processing the audio stream. Real implementations can e.g.
103// run audio in loopback, read audio from a file or perform latency
104// measurements.
105class AudioStream {
106 public:
henrikaeb98c722018-03-20 12:54:07 +0100107 virtual void Write(rtc::ArrayView<const int16_t> source) = 0;
108 virtual void Read(rtc::ArrayView<int16_t> destination) = 0;
henrikae24991d2017-04-06 01:14:23 -0700109
110 virtual ~AudioStream() = default;
111};
112
henrika714e5cd2017-04-20 08:03:11 -0700113// Converts index corresponding to position within a 10ms buffer into a
114// delay value in milliseconds.
115// Example: index=240, frames_per_10ms_buffer=480 => 5ms as output.
116int IndexToMilliseconds(size_t index, size_t frames_per_10ms_buffer) {
117 return rtc::checked_cast<int>(
118 10.0 * (static_cast<double>(index) / frames_per_10ms_buffer) + 0.5);
119}
120
henrikaf2f91fa2017-03-17 04:26:22 -0700121} // namespace
122
henrikae24991d2017-04-06 01:14:23 -0700123// Simple first in first out (FIFO) class that wraps a list of 16-bit audio
124// buffers of fixed size and allows Write and Read operations. The idea is to
125// store recorded audio buffers (using Write) and then read (using Read) these
126// stored buffers with as short delay as possible when the audio layer needs
127// data to play out. The number of buffers in the FIFO will stabilize under
128// normal conditions since there will be a balance between Write and Read calls.
129// The container is a std::list container and access is protected with a lock
130// since both sides (playout and recording) are driven by its own thread.
131// Note that, we know by design that the size of the audio buffer will not
henrikac7d93582018-09-14 15:37:34 +0200132// change over time and that both sides will in most cases use the same size.
henrikae24991d2017-04-06 01:14:23 -0700133class FifoAudioStream : public AudioStream {
134 public:
henrikaeb98c722018-03-20 12:54:07 +0100135 void Write(rtc::ArrayView<const int16_t> source) override {
henrikae24991d2017-04-06 01:14:23 -0700136 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
137 const size_t size = [&] {
138 rtc::CritScope lock(&lock_);
139 fifo_.push_back(Buffer16(source.data(), source.size()));
140 return fifo_.size();
141 }();
142 if (size > max_size_) {
143 max_size_ = size;
144 }
145 // Add marker once per second to signal that audio is active.
146 if (write_count_++ % 100 == 0) {
henrikad8c6ec42019-07-18 15:17:28 +0200147 PRINTD(".");
henrikae24991d2017-04-06 01:14:23 -0700148 }
149 written_elements_ += size;
150 }
151
henrikaeb98c722018-03-20 12:54:07 +0100152 void Read(rtc::ArrayView<int16_t> destination) override {
henrikae24991d2017-04-06 01:14:23 -0700153 rtc::CritScope lock(&lock_);
154 if (fifo_.empty()) {
155 std::fill(destination.begin(), destination.end(), 0);
156 } else {
157 const Buffer16& buffer = fifo_.front();
henrikac7d93582018-09-14 15:37:34 +0200158 if (buffer.size() == destination.size()) {
159 // Default case where input and output uses same sample rate and
160 // channel configuration. No conversion is needed.
161 std::copy(buffer.begin(), buffer.end(), destination.begin());
162 } else if (destination.size() == 2 * buffer.size()) {
163 // Recorded input signal in |buffer| is in mono. Do channel upmix to
164 // match stereo output (1 -> 2).
165 for (size_t i = 0; i < buffer.size(); ++i) {
166 destination[2 * i] = buffer[i];
167 destination[2 * i + 1] = buffer[i];
168 }
169 } else if (buffer.size() == 2 * destination.size()) {
170 // Recorded input signal in |buffer| is in stereo. Do channel downmix
171 // to match mono output (2 -> 1).
172 for (size_t i = 0; i < destination.size(); ++i) {
173 destination[i] =
174 (static_cast<int32_t>(buffer[2 * i]) + buffer[2 * i + 1]) / 2;
175 }
176 } else {
177 RTC_NOTREACHED() << "Required conversion is not support";
178 }
henrikae24991d2017-04-06 01:14:23 -0700179 fifo_.pop_front();
180 }
181 }
182
183 size_t size() const {
184 rtc::CritScope lock(&lock_);
185 return fifo_.size();
186 }
187
188 size_t max_size() const {
189 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
190 return max_size_;
191 }
192
193 size_t average_size() const {
194 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
195 return 0.5 + static_cast<float>(written_elements_ / write_count_);
196 }
197
198 using Buffer16 = rtc::BufferT<int16_t>;
199
200 rtc::CriticalSection lock_;
201 rtc::RaceChecker race_checker_;
202
danilchap56359be2017-09-07 07:53:45 -0700203 std::list<Buffer16> fifo_ RTC_GUARDED_BY(lock_);
204 size_t write_count_ RTC_GUARDED_BY(race_checker_) = 0;
205 size_t max_size_ RTC_GUARDED_BY(race_checker_) = 0;
206 size_t written_elements_ RTC_GUARDED_BY(race_checker_) = 0;
henrikae24991d2017-04-06 01:14:23 -0700207};
208
henrika714e5cd2017-04-20 08:03:11 -0700209// Inserts periodic impulses and measures the latency between the time of
210// transmission and time of receiving the same impulse.
211class LatencyAudioStream : public AudioStream {
212 public:
213 LatencyAudioStream() {
214 // Delay thread checkers from being initialized until first callback from
215 // respective thread.
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200216 read_thread_checker_.Detach();
217 write_thread_checker_.Detach();
henrika714e5cd2017-04-20 08:03:11 -0700218 }
219
220 // Insert periodic impulses in first two samples of |destination|.
henrikaeb98c722018-03-20 12:54:07 +0100221 void Read(rtc::ArrayView<int16_t> destination) override {
henrika714e5cd2017-04-20 08:03:11 -0700222 RTC_DCHECK_RUN_ON(&read_thread_checker_);
henrika714e5cd2017-04-20 08:03:11 -0700223 if (read_count_ == 0) {
224 PRINT("[");
225 }
226 read_count_++;
227 std::fill(destination.begin(), destination.end(), 0);
228 if (read_count_ % (kNumCallbacksPerSecond / kImpulseFrequencyInHz) == 0) {
229 PRINT(".");
230 {
231 rtc::CritScope lock(&lock_);
232 if (!pulse_time_) {
Oskar Sundbom6ad9f262017-11-16 10:53:39 +0100233 pulse_time_ = rtc::TimeMillis();
henrika714e5cd2017-04-20 08:03:11 -0700234 }
235 }
236 constexpr int16_t impulse = std::numeric_limits<int16_t>::max();
237 std::fill_n(destination.begin(), 2, impulse);
238 }
239 }
240
241 // Detect received impulses in |source|, derive time between transmission and
242 // detection and add the calculated delay to list of latencies.
henrikaeb98c722018-03-20 12:54:07 +0100243 void Write(rtc::ArrayView<const int16_t> source) override {
henrika714e5cd2017-04-20 08:03:11 -0700244 RTC_DCHECK_RUN_ON(&write_thread_checker_);
245 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
246 rtc::CritScope lock(&lock_);
247 write_count_++;
248 if (!pulse_time_) {
249 // Avoid detection of new impulse response until a new impulse has
250 // been transmitted (sets |pulse_time_| to value larger than zero).
251 return;
252 }
253 // Find index (element position in vector) of the max element.
254 const size_t index_of_max =
255 std::max_element(source.begin(), source.end()) - source.begin();
256 // Derive time between transmitted pulse and received pulse if the level
257 // is high enough (removes noise).
258 const size_t max = source[index_of_max];
259 if (max > kImpulseThreshold) {
260 PRINTD("(%zu, %zu)", max, index_of_max);
261 int64_t now_time = rtc::TimeMillis();
262 int extra_delay = IndexToMilliseconds(index_of_max, source.size());
263 PRINTD("[%d]", rtc::checked_cast<int>(now_time - pulse_time_));
264 PRINTD("[%d]", extra_delay);
265 // Total latency is the difference between transmit time and detection
266 // tome plus the extra delay within the buffer in which we detected the
267 // received impulse. It is transmitted at sample 0 but can be received
268 // at sample N where N > 0. The term |extra_delay| accounts for N and it
269 // is a value between 0 and 10ms.
270 latencies_.push_back(now_time - *pulse_time_ + extra_delay);
271 pulse_time_.reset();
272 } else {
273 PRINTD("-");
274 }
275 }
276
277 size_t num_latency_values() const {
278 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
279 return latencies_.size();
280 }
281
282 int min_latency() const {
283 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
284 if (latencies_.empty())
285 return 0;
286 return *std::min_element(latencies_.begin(), latencies_.end());
287 }
288
289 int max_latency() const {
290 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
291 if (latencies_.empty())
292 return 0;
293 return *std::max_element(latencies_.begin(), latencies_.end());
294 }
295
296 int average_latency() const {
297 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
298 if (latencies_.empty())
299 return 0;
300 return 0.5 + static_cast<double>(
301 std::accumulate(latencies_.begin(), latencies_.end(), 0)) /
302 latencies_.size();
303 }
304
305 void PrintResults() const {
306 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
307 PRINT("] ");
308 for (auto it = latencies_.begin(); it != latencies_.end(); ++it) {
309 PRINTD("%d ", *it);
310 }
311 PRINT("\n");
312 PRINT("[..........] [min, max, avg]=[%d, %d, %d] ms\n", min_latency(),
313 max_latency(), average_latency());
314 }
315
316 rtc::CriticalSection lock_;
317 rtc::RaceChecker race_checker_;
318 rtc::ThreadChecker read_thread_checker_;
319 rtc::ThreadChecker write_thread_checker_;
320
Danil Chapovalov196100e2018-06-21 10:17:24 +0200321 absl::optional<int64_t> pulse_time_ RTC_GUARDED_BY(lock_);
danilchap56359be2017-09-07 07:53:45 -0700322 std::vector<int> latencies_ RTC_GUARDED_BY(race_checker_);
Niels Möller1e062892018-02-07 10:18:32 +0100323 size_t read_count_ RTC_GUARDED_BY(read_thread_checker_) = 0;
324 size_t write_count_ RTC_GUARDED_BY(write_thread_checker_) = 0;
henrika714e5cd2017-04-20 08:03:11 -0700325};
326
henrikaf2f91fa2017-03-17 04:26:22 -0700327// Mocks the AudioTransport object and proxies actions for the two callbacks
328// (RecordedDataIsAvailable and NeedMorePlayData) to different implementations
329// of AudioStreamInterface.
330class MockAudioTransport : public test::MockAudioTransport {
331 public:
332 explicit MockAudioTransport(TransportType type) : type_(type) {}
333 ~MockAudioTransport() {}
334
335 // Set default actions of the mock object. We are delegating to fake
336 // implementation where the number of callbacks is counted and an event
337 // is set after a certain number of callbacks. Audio parameters are also
338 // checked.
henrikae24991d2017-04-06 01:14:23 -0700339 void HandleCallbacks(rtc::Event* event,
340 AudioStream* audio_stream,
341 int num_callbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700342 event_ = event;
henrikae24991d2017-04-06 01:14:23 -0700343 audio_stream_ = audio_stream;
henrikaf2f91fa2017-03-17 04:26:22 -0700344 num_callbacks_ = num_callbacks;
345 if (play_mode()) {
346 ON_CALL(*this, NeedMorePlayData(_, _, _, _, _, _, _, _))
347 .WillByDefault(
348 Invoke(this, &MockAudioTransport::RealNeedMorePlayData));
349 }
350 if (rec_mode()) {
351 ON_CALL(*this, RecordedDataIsAvailable(_, _, _, _, _, _, _, _, _, _))
352 .WillByDefault(
353 Invoke(this, &MockAudioTransport::RealRecordedDataIsAvailable));
354 }
355 }
356
henrika5b6afc02018-09-05 14:34:40 +0200357 // Special constructor used in manual tests where the user wants to run audio
358 // until e.g. a keyboard key is pressed. The event flag is set to nullptr by
359 // default since it is up to the user to stop the test. See e.g.
360 // DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey().
361 void HandleCallbacks(AudioStream* audio_stream) {
362 HandleCallbacks(nullptr, audio_stream, 0);
363 }
364
henrikaf2f91fa2017-03-17 04:26:22 -0700365 int32_t RealRecordedDataIsAvailable(const void* audio_buffer,
366 const size_t samples_per_channel,
367 const size_t bytes_per_frame,
368 const size_t channels,
369 const uint32_t sample_rate,
370 const uint32_t total_delay_ms,
371 const int32_t clock_drift,
372 const uint32_t current_mic_level,
373 const bool typing_status,
374 uint32_t& new_mic_level) {
375 EXPECT_TRUE(rec_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700376 // Store audio parameters once in the first callback. For all other
377 // callbacks, verify that the provided audio parameters are maintained and
378 // that each callback corresponds to 10ms for any given sample rate.
379 if (!record_parameters_.is_complete()) {
380 record_parameters_.reset(sample_rate, channels, samples_per_channel);
381 } else {
382 EXPECT_EQ(samples_per_channel, record_parameters_.frames_per_buffer());
383 EXPECT_EQ(bytes_per_frame, record_parameters_.GetBytesPerFrame());
384 EXPECT_EQ(channels, record_parameters_.channels());
385 EXPECT_EQ(static_cast<int>(sample_rate),
386 record_parameters_.sample_rate());
387 EXPECT_EQ(samples_per_channel,
388 record_parameters_.frames_per_10ms_buffer());
389 }
henrika78e0ac12018-09-27 16:23:21 +0200390 {
391 rtc::CritScope lock(&lock_);
392 rec_count_++;
393 }
henrikae24991d2017-04-06 01:14:23 -0700394 // Write audio data to audio stream object if one has been injected.
395 if (audio_stream_) {
396 audio_stream_->Write(
397 rtc::MakeArrayView(static_cast<const int16_t*>(audio_buffer),
henrikaeb98c722018-03-20 12:54:07 +0100398 samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700399 }
henrikaf2f91fa2017-03-17 04:26:22 -0700400 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200401 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700402 event_->Set();
403 }
404 return 0;
405 }
406
407 int32_t RealNeedMorePlayData(const size_t samples_per_channel,
408 const size_t bytes_per_frame,
409 const size_t channels,
410 const uint32_t sample_rate,
411 void* audio_buffer,
henrikaeb98c722018-03-20 12:54:07 +0100412 size_t& samples_out,
henrikaf2f91fa2017-03-17 04:26:22 -0700413 int64_t* elapsed_time_ms,
414 int64_t* ntp_time_ms) {
415 EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700416 // Store audio parameters once in the first callback. For all other
417 // callbacks, verify that the provided audio parameters are maintained and
418 // that each callback corresponds to 10ms for any given sample rate.
419 if (!playout_parameters_.is_complete()) {
420 playout_parameters_.reset(sample_rate, channels, samples_per_channel);
421 } else {
422 EXPECT_EQ(samples_per_channel, playout_parameters_.frames_per_buffer());
423 EXPECT_EQ(bytes_per_frame, playout_parameters_.GetBytesPerFrame());
424 EXPECT_EQ(channels, playout_parameters_.channels());
425 EXPECT_EQ(static_cast<int>(sample_rate),
426 playout_parameters_.sample_rate());
427 EXPECT_EQ(samples_per_channel,
428 playout_parameters_.frames_per_10ms_buffer());
429 }
henrika78e0ac12018-09-27 16:23:21 +0200430 {
431 rtc::CritScope lock(&lock_);
432 play_count_++;
433 }
henrikaeb98c722018-03-20 12:54:07 +0100434 samples_out = samples_per_channel * channels;
henrikae24991d2017-04-06 01:14:23 -0700435 // Read audio data from audio stream object if one has been injected.
436 if (audio_stream_) {
henrikaeb98c722018-03-20 12:54:07 +0100437 audio_stream_->Read(rtc::MakeArrayView(
438 static_cast<int16_t*>(audio_buffer), samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700439 } else {
440 // Fill the audio buffer with zeros to avoid disturbing audio.
441 const size_t num_bytes = samples_per_channel * bytes_per_frame;
442 std::memset(audio_buffer, 0, num_bytes);
443 }
henrikaf2f91fa2017-03-17 04:26:22 -0700444 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200445 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700446 event_->Set();
447 }
448 return 0;
449 }
450
451 bool ReceivedEnoughCallbacks() {
452 bool recording_done = false;
453 if (rec_mode()) {
henrika78e0ac12018-09-27 16:23:21 +0200454 rtc::CritScope lock(&lock_);
henrikaf2f91fa2017-03-17 04:26:22 -0700455 recording_done = rec_count_ >= num_callbacks_;
456 } else {
457 recording_done = true;
458 }
459 bool playout_done = false;
460 if (play_mode()) {
henrika78e0ac12018-09-27 16:23:21 +0200461 rtc::CritScope lock(&lock_);
henrikaf2f91fa2017-03-17 04:26:22 -0700462 playout_done = play_count_ >= num_callbacks_;
463 } else {
464 playout_done = true;
465 }
466 return recording_done && playout_done;
467 }
468
469 bool play_mode() const {
470 return type_ == TransportType::kPlay ||
471 type_ == TransportType::kPlayAndRecord;
472 }
473
474 bool rec_mode() const {
475 return type_ == TransportType::kRecord ||
476 type_ == TransportType::kPlayAndRecord;
477 }
478
henrika5b6afc02018-09-05 14:34:40 +0200479 void ResetCallbackCounters() {
henrika78e0ac12018-09-27 16:23:21 +0200480 rtc::CritScope lock(&lock_);
henrika5b6afc02018-09-05 14:34:40 +0200481 if (play_mode()) {
482 play_count_ = 0;
483 }
484 if (rec_mode()) {
485 rec_count_ = 0;
486 }
487 }
488
henrikaf2f91fa2017-03-17 04:26:22 -0700489 private:
henrika78e0ac12018-09-27 16:23:21 +0200490 rtc::CriticalSection lock_;
henrikaf2f91fa2017-03-17 04:26:22 -0700491 TransportType type_ = TransportType::kInvalid;
492 rtc::Event* event_ = nullptr;
henrikae24991d2017-04-06 01:14:23 -0700493 AudioStream* audio_stream_ = nullptr;
henrikaf2f91fa2017-03-17 04:26:22 -0700494 size_t num_callbacks_ = 0;
henrika78e0ac12018-09-27 16:23:21 +0200495 size_t play_count_ RTC_GUARDED_BY(lock_) = 0;
496 size_t rec_count_ RTC_GUARDED_BY(lock_) = 0;
henrikaf2f91fa2017-03-17 04:26:22 -0700497 AudioParameters playout_parameters_;
498 AudioParameters record_parameters_;
499};
500
501// AudioDeviceTest test fixture.
Yves Gerey1afe6572019-07-18 22:01:09 +0200502
Yves Gereyff060ee2019-09-11 15:53:01 +0200503// bugs.webrtc.org/9808
504// Both the tests and the code under test are very old, unstaffed and not
505// a part of webRTC stack.
506// Here sanitizers make the tests hang, without providing usefull report.
507// So we are just disabling them, without intention to re-enable them.
508#if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
509 defined(THREAD_SANITIZER) || defined(UNDEFINED_SANITIZER)
510#define MAYBE_AudioDeviceTest DISABLED_AudioDeviceTest
511#else
512#define MAYBE_AudioDeviceTest AudioDeviceTest
513#endif
514
515class MAYBE_AudioDeviceTest
henrikaec9c7452018-06-08 16:10:03 +0200516 : public ::testing::TestWithParam<webrtc::AudioDeviceModule::AudioLayer> {
henrikaf2f91fa2017-03-17 04:26:22 -0700517 protected:
Yves Gereyff060ee2019-09-11 15:53:01 +0200518 MAYBE_AudioDeviceTest()
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200519 : audio_layer_(GetParam()),
520 task_queue_factory_(CreateDefaultTaskQueueFactory()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700521 rtc::LogMessage::LogToDebug(rtc::LS_INFO);
522 // Add extra logging fields here if needed for debugging.
henrikaec9c7452018-06-08 16:10:03 +0200523 rtc::LogMessage::LogTimestamps();
524 rtc::LogMessage::LogThreads();
525 audio_device_ = CreateAudioDevice();
henrikaf2f91fa2017-03-17 04:26:22 -0700526 EXPECT_NE(audio_device_.get(), nullptr);
527 AudioDeviceModule::AudioLayer audio_layer;
maxmorin33bf69a2017-03-23 04:06:53 -0700528 int got_platform_audio_layer =
529 audio_device_->ActiveAudioLayer(&audio_layer);
henrika919dc2e2017-10-12 14:24:55 +0200530 // First, ensure that a valid audio layer can be activated.
531 if (got_platform_audio_layer != 0) {
henrikaf2f91fa2017-03-17 04:26:22 -0700532 requirements_satisfied_ = false;
533 }
henrika919dc2e2017-10-12 14:24:55 +0200534 // Next, verify that the ADM can be initialized.
henrikaf2f91fa2017-03-17 04:26:22 -0700535 if (requirements_satisfied_) {
henrika919dc2e2017-10-12 14:24:55 +0200536 requirements_satisfied_ = (audio_device_->Init() == 0);
537 }
538 // Finally, ensure that at least one valid device exists in each direction.
539 if (requirements_satisfied_) {
henrikaf2f91fa2017-03-17 04:26:22 -0700540 const int16_t num_playout_devices = audio_device_->PlayoutDevices();
541 const int16_t num_record_devices = audio_device_->RecordingDevices();
542 requirements_satisfied_ =
543 num_playout_devices > 0 && num_record_devices > 0;
544 }
henrikaf2f91fa2017-03-17 04:26:22 -0700545 if (requirements_satisfied_) {
henrika5773ad32018-09-21 14:53:10 +0200546 EXPECT_EQ(0, audio_device_->SetPlayoutDevice(AUDIO_DEVICE_ID));
henrikaf2f91fa2017-03-17 04:26:22 -0700547 EXPECT_EQ(0, audio_device_->InitSpeaker());
henrikaf2f91fa2017-03-17 04:26:22 -0700548 EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
549 EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
henrika5773ad32018-09-21 14:53:10 +0200550 EXPECT_EQ(0, audio_device_->SetRecordingDevice(AUDIO_DEVICE_ID));
551 EXPECT_EQ(0, audio_device_->InitMicrophone());
henrika0238ba82017-03-28 04:38:29 -0700552 // Avoid asking for input stereo support and always record in mono
553 // since asking can cause issues in combination with remote desktop.
554 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
555 // details.
556 EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
henrikaf2f91fa2017-03-17 04:26:22 -0700557 }
558 }
559
Yves Gereyb93a2452019-07-19 22:46:13 +0200560 // This is needed by all tests using MockAudioTransport,
561 // since there is no way to unregister it.
562 // Without Terminate(), audio_device would still accesses
563 // the destructed mock via "webrtc_audio_module_rec_thread".
564 // An alternative would be for the mock to outlive audio_device.
565 void PreTearDown() { EXPECT_EQ(0, audio_device_->Terminate()); }
566
Yves Gereyff060ee2019-09-11 15:53:01 +0200567 virtual ~MAYBE_AudioDeviceTest() {
henrikaf2f91fa2017-03-17 04:26:22 -0700568 if (audio_device_) {
569 EXPECT_EQ(0, audio_device_->Terminate());
570 }
571 }
572
573 bool requirements_satisfied() const { return requirements_satisfied_; }
574 rtc::Event* event() { return &event_; }
henrika5b6afc02018-09-05 14:34:40 +0200575 AudioDeviceModule::AudioLayer audio_layer() const { return audio_layer_; }
henrikaf2f91fa2017-03-17 04:26:22 -0700576
henrika5b6afc02018-09-05 14:34:40 +0200577 // AudioDeviceModuleForTest extends the default ADM interface with some extra
578 // test methods. Intended for usage in tests only and requires a unique
579 // factory method. See CreateAudioDevice() for details.
580 const rtc::scoped_refptr<AudioDeviceModuleForTest>& audio_device() const {
henrikaf2f91fa2017-03-17 04:26:22 -0700581 return audio_device_;
582 }
583
henrika5b6afc02018-09-05 14:34:40 +0200584 rtc::scoped_refptr<AudioDeviceModuleForTest> CreateAudioDevice() {
henrikaec9c7452018-06-08 16:10:03 +0200585 // Use the default factory for kPlatformDefaultAudio and a special factory
henrika5b6afc02018-09-05 14:34:40 +0200586 // CreateWindowsCoreAudioAudioDeviceModuleForTest() for kWindowsCoreAudio2.
henrikaec9c7452018-06-08 16:10:03 +0200587 // The value of |audio_layer_| is set at construction by GetParam() and two
588 // different layers are tested on Windows only.
589 if (audio_layer_ == AudioDeviceModule::kPlatformDefaultAudio) {
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200590 return AudioDeviceModule::CreateForTest(audio_layer_,
591 task_queue_factory_.get());
henrikaec9c7452018-06-08 16:10:03 +0200592 } else if (audio_layer_ == AudioDeviceModule::kWindowsCoreAudio2) {
593#ifdef WEBRTC_WIN
594 // We must initialize the COM library on a thread before we calling any of
595 // the library functions. All COM functions in the ADM will return
596 // CO_E_NOTINITIALIZED otherwise.
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200597 com_initializer_ = std::make_unique<webrtc_win::ScopedCOMInitializer>(
henrikaec9c7452018-06-08 16:10:03 +0200598 webrtc_win::ScopedCOMInitializer::kMTA);
599 EXPECT_TRUE(com_initializer_->Succeeded());
600 EXPECT_TRUE(webrtc_win::core_audio_utility::IsSupported());
601 EXPECT_TRUE(webrtc_win::core_audio_utility::IsMMCSSSupported());
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200602 return CreateWindowsCoreAudioAudioDeviceModuleForTest(
henrikad8c6ec42019-07-18 15:17:28 +0200603 task_queue_factory_.get(), true);
henrikaec9c7452018-06-08 16:10:03 +0200604#else
605 return nullptr;
606#endif
607 } else {
608 return nullptr;
609 }
610 }
611
henrikaf2f91fa2017-03-17 04:26:22 -0700612 void StartPlayout() {
613 EXPECT_FALSE(audio_device()->Playing());
614 EXPECT_EQ(0, audio_device()->InitPlayout());
615 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
616 EXPECT_EQ(0, audio_device()->StartPlayout());
617 EXPECT_TRUE(audio_device()->Playing());
618 }
619
620 void StopPlayout() {
621 EXPECT_EQ(0, audio_device()->StopPlayout());
622 EXPECT_FALSE(audio_device()->Playing());
623 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
624 }
625
626 void StartRecording() {
627 EXPECT_FALSE(audio_device()->Recording());
628 EXPECT_EQ(0, audio_device()->InitRecording());
629 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
630 EXPECT_EQ(0, audio_device()->StartRecording());
631 EXPECT_TRUE(audio_device()->Recording());
632 }
633
634 void StopRecording() {
635 EXPECT_EQ(0, audio_device()->StopRecording());
636 EXPECT_FALSE(audio_device()->Recording());
637 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
638 }
639
henrikaec9c7452018-06-08 16:10:03 +0200640 bool NewWindowsAudioDeviceModuleIsUsed() {
641#ifdef WEBRTC_WIN
642 AudioDeviceModule::AudioLayer audio_layer;
643 EXPECT_EQ(0, audio_device()->ActiveAudioLayer(&audio_layer));
644 if (audio_layer == AudioDeviceModule::kWindowsCoreAudio2) {
645 // Default device is always added as first element in the list and the
646 // default communication device as the second element. Hence, the list
647 // contains two extra elements in this case.
648 return true;
649 }
650#endif
651 return false;
652 }
653
henrikaf2f91fa2017-03-17 04:26:22 -0700654 private:
henrikaec9c7452018-06-08 16:10:03 +0200655#ifdef WEBRTC_WIN
656 // Windows Core Audio based ADM needs to run on a COM initialized thread.
657 std::unique_ptr<webrtc_win::ScopedCOMInitializer> com_initializer_;
658#endif
659 AudioDeviceModule::AudioLayer audio_layer_;
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200660 std::unique_ptr<TaskQueueFactory> task_queue_factory_;
henrikaf2f91fa2017-03-17 04:26:22 -0700661 bool requirements_satisfied_ = true;
662 rtc::Event event_;
henrika5b6afc02018-09-05 14:34:40 +0200663 rtc::scoped_refptr<AudioDeviceModuleForTest> audio_device_;
henrikaf2f91fa2017-03-17 04:26:22 -0700664 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700665};
666
henrikaec9c7452018-06-08 16:10:03 +0200667// Instead of using the test fixture, verify that the different factory methods
668// work as intended.
Yves Gereyff060ee2019-09-11 15:53:01 +0200669TEST(MAYBE_AudioDeviceTestWin, ConstructDestructWithFactory) {
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200670 std::unique_ptr<TaskQueueFactory> task_queue_factory =
671 CreateDefaultTaskQueueFactory();
henrikaec9c7452018-06-08 16:10:03 +0200672 rtc::scoped_refptr<AudioDeviceModule> audio_device;
673 // The default factory should work for all platforms when a default ADM is
674 // requested.
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200675 audio_device = AudioDeviceModule::Create(
676 AudioDeviceModule::kPlatformDefaultAudio, task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200677 EXPECT_TRUE(audio_device);
678 audio_device = nullptr;
679#ifdef WEBRTC_WIN
680 // For Windows, the old factory method creates an ADM where the platform-
681 // specific parts are implemented by an AudioDeviceGeneric object. Verify
682 // that the old factory can't be used in combination with the latest audio
683 // layer AudioDeviceModule::kWindowsCoreAudio2.
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200684 audio_device = AudioDeviceModule::Create(
685 AudioDeviceModule::kWindowsCoreAudio2, task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200686 EXPECT_FALSE(audio_device);
687 audio_device = nullptr;
688 // Instead, ensure that the new dedicated factory method called
689 // CreateWindowsCoreAudioAudioDeviceModule() can be used on Windows and that
690 // it sets the audio layer to kWindowsCoreAudio2 implicitly. Note that, the
691 // new ADM for Windows must be created on a COM thread.
692 webrtc_win::ScopedCOMInitializer com_initializer(
693 webrtc_win::ScopedCOMInitializer::kMTA);
694 EXPECT_TRUE(com_initializer.Succeeded());
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200695 audio_device =
696 CreateWindowsCoreAudioAudioDeviceModule(task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200697 EXPECT_TRUE(audio_device);
698 AudioDeviceModule::AudioLayer audio_layer;
699 EXPECT_EQ(0, audio_device->ActiveAudioLayer(&audio_layer));
700 EXPECT_EQ(audio_layer, AudioDeviceModule::kWindowsCoreAudio2);
701#endif
702}
henrikaf2f91fa2017-03-17 04:26:22 -0700703
henrikaec9c7452018-06-08 16:10:03 +0200704// Uses the test fixture to create, initialize and destruct the ADM.
Yves Gereyff060ee2019-09-11 15:53:01 +0200705TEST_P(MAYBE_AudioDeviceTest, ConstructDestructDefault) {}
henrikaec9c7452018-06-08 16:10:03 +0200706
Yves Gereyff060ee2019-09-11 15:53:01 +0200707TEST_P(MAYBE_AudioDeviceTest, InitTerminate) {
henrikaf2f91fa2017-03-17 04:26:22 -0700708 SKIP_TEST_IF_NOT(requirements_satisfied());
709 // Initialization is part of the test fixture.
710 EXPECT_TRUE(audio_device()->Initialized());
711 EXPECT_EQ(0, audio_device()->Terminate());
712 EXPECT_FALSE(audio_device()->Initialized());
713}
714
henrikaec9c7452018-06-08 16:10:03 +0200715// Enumerate all available and active output devices.
Yves Gereyff060ee2019-09-11 15:53:01 +0200716TEST_P(MAYBE_AudioDeviceTest, PlayoutDeviceNames) {
henrikaf2f91fa2017-03-17 04:26:22 -0700717 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaec9c7452018-06-08 16:10:03 +0200718 char device_name[kAdmMaxDeviceNameSize];
719 char unique_id[kAdmMaxGuidSize];
720 int num_devices = audio_device()->PlayoutDevices();
721 if (NewWindowsAudioDeviceModuleIsUsed()) {
722 num_devices += 2;
723 }
724 EXPECT_GT(num_devices, 0);
725 for (int i = 0; i < num_devices; ++i) {
726 EXPECT_EQ(0, audio_device()->PlayoutDeviceName(i, device_name, unique_id));
727 }
728 EXPECT_EQ(-1, audio_device()->PlayoutDeviceName(num_devices, device_name,
729 unique_id));
730}
731
732// Enumerate all available and active input devices.
Yves Gereyff060ee2019-09-11 15:53:01 +0200733TEST_P(MAYBE_AudioDeviceTest, RecordingDeviceNames) {
henrikaec9c7452018-06-08 16:10:03 +0200734 SKIP_TEST_IF_NOT(requirements_satisfied());
735 char device_name[kAdmMaxDeviceNameSize];
736 char unique_id[kAdmMaxGuidSize];
737 int num_devices = audio_device()->RecordingDevices();
738 if (NewWindowsAudioDeviceModuleIsUsed()) {
739 num_devices += 2;
740 }
741 EXPECT_GT(num_devices, 0);
742 for (int i = 0; i < num_devices; ++i) {
743 EXPECT_EQ(0,
744 audio_device()->RecordingDeviceName(i, device_name, unique_id));
745 }
746 EXPECT_EQ(-1, audio_device()->RecordingDeviceName(num_devices, device_name,
747 unique_id));
748}
749
750// Counts number of active output devices and ensure that all can be selected.
Yves Gereyff060ee2019-09-11 15:53:01 +0200751TEST_P(MAYBE_AudioDeviceTest, SetPlayoutDevice) {
henrikaec9c7452018-06-08 16:10:03 +0200752 SKIP_TEST_IF_NOT(requirements_satisfied());
753 int num_devices = audio_device()->PlayoutDevices();
754 if (NewWindowsAudioDeviceModuleIsUsed()) {
755 num_devices += 2;
756 }
757 EXPECT_GT(num_devices, 0);
758 // Verify that all available playout devices can be set (not enabled yet).
759 for (int i = 0; i < num_devices; ++i) {
760 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(i));
761 }
762 EXPECT_EQ(-1, audio_device()->SetPlayoutDevice(num_devices));
763#ifdef WEBRTC_WIN
764 // On Windows, verify the alternative method where the user can select device
765 // by role.
766 EXPECT_EQ(
767 0, audio_device()->SetPlayoutDevice(AudioDeviceModule::kDefaultDevice));
768 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(
769 AudioDeviceModule::kDefaultCommunicationDevice));
770#endif
771}
772
773// Counts number of active input devices and ensure that all can be selected.
Yves Gereyff060ee2019-09-11 15:53:01 +0200774TEST_P(MAYBE_AudioDeviceTest, SetRecordingDevice) {
henrikaec9c7452018-06-08 16:10:03 +0200775 SKIP_TEST_IF_NOT(requirements_satisfied());
776 int num_devices = audio_device()->RecordingDevices();
777 if (NewWindowsAudioDeviceModuleIsUsed()) {
778 num_devices += 2;
779 }
780 EXPECT_GT(num_devices, 0);
781 // Verify that all available recording devices can be set (not enabled yet).
782 for (int i = 0; i < num_devices; ++i) {
783 EXPECT_EQ(0, audio_device()->SetRecordingDevice(i));
784 }
785 EXPECT_EQ(-1, audio_device()->SetRecordingDevice(num_devices));
786#ifdef WEBRTC_WIN
787 // On Windows, verify the alternative method where the user can select device
788 // by role.
789 EXPECT_EQ(
790 0, audio_device()->SetRecordingDevice(AudioDeviceModule::kDefaultDevice));
791 EXPECT_EQ(0, audio_device()->SetRecordingDevice(
792 AudioDeviceModule::kDefaultCommunicationDevice));
793#endif
794}
795
796// Tests Start/Stop playout without any registered audio callback.
Yves Gereyff060ee2019-09-11 15:53:01 +0200797TEST_P(MAYBE_AudioDeviceTest, StartStopPlayout) {
henrikaec9c7452018-06-08 16:10:03 +0200798 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaf2f91fa2017-03-17 04:26:22 -0700799 StartPlayout();
800 StopPlayout();
801}
802
803// Tests Start/Stop recording without any registered audio callback.
Yves Gereyff060ee2019-09-11 15:53:01 +0200804TEST_P(MAYBE_AudioDeviceTest, StartStopRecording) {
henrikaf2f91fa2017-03-17 04:26:22 -0700805 SKIP_TEST_IF_NOT(requirements_satisfied());
806 StartRecording();
807 StopRecording();
henrikaf2f91fa2017-03-17 04:26:22 -0700808}
809
henrika6b3e1a22017-09-25 16:34:30 +0200810// Tests Init/Stop/Init recording without any registered audio callback.
811// See https://bugs.chromium.org/p/webrtc/issues/detail?id=8041 for details
812// on why this test is useful.
Yves Gereyff060ee2019-09-11 15:53:01 +0200813TEST_P(MAYBE_AudioDeviceTest, InitStopInitRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200814 SKIP_TEST_IF_NOT(requirements_satisfied());
815 EXPECT_EQ(0, audio_device()->InitRecording());
816 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
817 StopRecording();
818 EXPECT_EQ(0, audio_device()->InitRecording());
819 StopRecording();
820}
821
henrikad4049462019-07-12 13:37:11 +0200822// Verify that additional attempts to initialize or start recording while
823// already being active works. Additional calls should just be ignored.
Yves Gereyff060ee2019-09-11 15:53:01 +0200824TEST_P(MAYBE_AudioDeviceTest, StartInitRecording) {
henrikad4049462019-07-12 13:37:11 +0200825 SKIP_TEST_IF_NOT(requirements_satisfied());
826 StartRecording();
827 // An additional attempt to initialize at this stage should be ignored.
828 EXPECT_EQ(0, audio_device()->InitRecording());
829 // Same for additional request to start recording while already active.
830 EXPECT_EQ(0, audio_device()->StartRecording());
831 StopRecording();
832}
833
834// Verify that additional attempts to initialize or start playou while
835// already being active works. Additional calls should just be ignored.
Yves Gereyff060ee2019-09-11 15:53:01 +0200836TEST_P(MAYBE_AudioDeviceTest, StartInitPlayout) {
henrikad4049462019-07-12 13:37:11 +0200837 SKIP_TEST_IF_NOT(requirements_satisfied());
838 StartPlayout();
839 // An additional attempt to initialize at this stage should be ignored.
840 EXPECT_EQ(0, audio_device()->InitPlayout());
841 // Same for additional request to start playout while already active.
842 EXPECT_EQ(0, audio_device()->StartPlayout());
843 StopPlayout();
844}
845
henrika6b3e1a22017-09-25 16:34:30 +0200846// Tests Init/Stop/Init recording while playout is active.
Yves Gereyff060ee2019-09-11 15:53:01 +0200847TEST_P(MAYBE_AudioDeviceTest, InitStopInitRecordingWhilePlaying) {
henrika6b3e1a22017-09-25 16:34:30 +0200848 SKIP_TEST_IF_NOT(requirements_satisfied());
849 StartPlayout();
850 EXPECT_EQ(0, audio_device()->InitRecording());
851 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
852 StopRecording();
853 EXPECT_EQ(0, audio_device()->InitRecording());
854 StopRecording();
855 StopPlayout();
856}
857
858// Tests Init/Stop/Init playout without any registered audio callback.
Yves Gereyff060ee2019-09-11 15:53:01 +0200859TEST_P(MAYBE_AudioDeviceTest, InitStopInitPlayout) {
henrika6b3e1a22017-09-25 16:34:30 +0200860 SKIP_TEST_IF_NOT(requirements_satisfied());
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}
867
868// Tests Init/Stop/Init playout while recording is active.
Yves Gereyff060ee2019-09-11 15:53:01 +0200869TEST_P(MAYBE_AudioDeviceTest, InitStopInitPlayoutWhileRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200870 SKIP_TEST_IF_NOT(requirements_satisfied());
871 StartRecording();
872 EXPECT_EQ(0, audio_device()->InitPlayout());
873 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
874 StopPlayout();
875 EXPECT_EQ(0, audio_device()->InitPlayout());
876 StopPlayout();
877 StopRecording();
878}
879
henrika5b6afc02018-09-05 14:34:40 +0200880// TODO(henrika): restart without intermediate destruction is currently only
881// supported on Windows.
882#ifdef WEBRTC_WIN
883// Tests Start/Stop playout followed by a second session (emulates a restart
884// triggered by a user using public APIs).
Yves Gereyff060ee2019-09-11 15:53:01 +0200885TEST_P(MAYBE_AudioDeviceTest, StartStopPlayoutWithExternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200886 SKIP_TEST_IF_NOT(requirements_satisfied());
887 StartPlayout();
888 StopPlayout();
889 // Restart playout without destroying the ADM in between. Ensures that we
890 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
891 StartPlayout();
892 StopPlayout();
893}
894
895// Tests Start/Stop recording followed by a second session (emulates a restart
896// triggered by a user using public APIs).
Yves Gereyff060ee2019-09-11 15:53:01 +0200897TEST_P(MAYBE_AudioDeviceTest, StartStopRecordingWithExternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200898 SKIP_TEST_IF_NOT(requirements_satisfied());
899 StartRecording();
900 StopRecording();
901 // Restart recording without destroying the ADM in between. Ensures that we
902 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
903 StartRecording();
904 StopRecording();
905}
906
907// Tests Start/Stop playout followed by a second session (emulates a restart
908// triggered by an internal callback e.g. corresponding to a device switch).
909// Note that, internal restart is only supported in combination with the latest
910// Windows ADM.
Yves Gereyff060ee2019-09-11 15:53:01 +0200911TEST_P(MAYBE_AudioDeviceTest, StartStopPlayoutWithInternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200912 SKIP_TEST_IF_NOT(requirements_satisfied());
913 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
914 return;
915 }
916 MockAudioTransport mock(TransportType::kPlay);
917 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
918 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
919 .Times(AtLeast(kNumCallbacks));
920 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
921 StartPlayout();
922 event()->Wait(kTestTimeOutInMilliseconds);
923 EXPECT_TRUE(audio_device()->Playing());
924 // Restart playout but without stopping the internal audio thread.
925 // This procedure uses a non-public test API and it emulates what happens
926 // inside the ADM when e.g. a device is removed.
927 EXPECT_EQ(0, audio_device()->RestartPlayoutInternally());
928
929 // Run basic tests of public APIs while a restart attempt is active.
930 // These calls should now be very thin and not trigger any new actions.
931 EXPECT_EQ(-1, audio_device()->StopPlayout());
932 EXPECT_TRUE(audio_device()->Playing());
933 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
934 EXPECT_EQ(0, audio_device()->InitPlayout());
935 EXPECT_EQ(0, audio_device()->StartPlayout());
936
937 // Wait until audio has restarted and a new sequence of audio callbacks
938 // becomes active.
939 // TODO(henrika): is it possible to verify that the internal state transition
940 // is Stop->Init->Start?
941 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
942 mock.ResetCallbackCounters();
943 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
944 .Times(AtLeast(kNumCallbacks));
945 event()->Wait(kTestTimeOutInMilliseconds);
946 EXPECT_TRUE(audio_device()->Playing());
947 // Stop playout and the audio thread after successful internal restart.
948 StopPlayout();
Yves Gereyb93a2452019-07-19 22:46:13 +0200949 PreTearDown();
henrika5b6afc02018-09-05 14:34:40 +0200950}
951
952// Tests Start/Stop recording followed by a second session (emulates a restart
953// triggered by an internal callback e.g. corresponding to a device switch).
954// Note that, internal restart is only supported in combination with the latest
955// Windows ADM.
Yves Gereyff060ee2019-09-11 15:53:01 +0200956TEST_P(MAYBE_AudioDeviceTest, StartStopRecordingWithInternalRestart) {
henrika5b6afc02018-09-05 14:34:40 +0200957 SKIP_TEST_IF_NOT(requirements_satisfied());
958 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
959 return;
960 }
961 MockAudioTransport mock(TransportType::kRecord);
962 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
963 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
964 false, _))
965 .Times(AtLeast(kNumCallbacks));
966 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
967 StartRecording();
968 event()->Wait(kTestTimeOutInMilliseconds);
969 EXPECT_TRUE(audio_device()->Recording());
970 // Restart recording but without stopping the internal audio thread.
971 // This procedure uses a non-public test API and it emulates what happens
972 // inside the ADM when e.g. a device is removed.
973 EXPECT_EQ(0, audio_device()->RestartRecordingInternally());
974
975 // Run basic tests of public APIs while a restart attempt is active.
976 // These calls should now be very thin and not trigger any new actions.
977 EXPECT_EQ(-1, audio_device()->StopRecording());
978 EXPECT_TRUE(audio_device()->Recording());
979 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
980 EXPECT_EQ(0, audio_device()->InitRecording());
981 EXPECT_EQ(0, audio_device()->StartRecording());
982
983 // Wait until audio has restarted and a new sequence of audio callbacks
984 // becomes active.
985 // TODO(henrika): is it possible to verify that the internal state transition
986 // is Stop->Init->Start?
987 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
988 mock.ResetCallbackCounters();
989 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
990 false, _))
991 .Times(AtLeast(kNumCallbacks));
992 event()->Wait(kTestTimeOutInMilliseconds);
993 EXPECT_TRUE(audio_device()->Recording());
994 // Stop recording and the audio thread after successful internal restart.
995 StopRecording();
Yves Gereyb93a2452019-07-19 22:46:13 +0200996 PreTearDown();
henrika5b6afc02018-09-05 14:34:40 +0200997}
998#endif // #ifdef WEBRTC_WIN
999
henrikaf2f91fa2017-03-17 04:26:22 -07001000// Start playout and verify that the native audio layer starts asking for real
1001// audio samples to play out using the NeedMorePlayData() callback.
1002// Note that we can't add expectations on audio parameters in EXPECT_CALL
1003// since parameter are not provided in the each callback. We therefore test and
1004// verify the parameters in the fake audio transport implementation instead.
Yves Gereyff060ee2019-09-11 15:53:01 +02001005TEST_P(MAYBE_AudioDeviceTest, StartPlayoutVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001006 SKIP_TEST_IF_NOT(requirements_satisfied());
1007 MockAudioTransport mock(TransportType::kPlay);
henrikae24991d2017-04-06 01:14:23 -07001008 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001009 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
1010 .Times(AtLeast(kNumCallbacks));
1011 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1012 StartPlayout();
1013 event()->Wait(kTestTimeOutInMilliseconds);
1014 StopPlayout();
Yves Gerey412282a2019-07-22 21:15:22 +02001015 PreTearDown();
henrikaf2f91fa2017-03-17 04:26:22 -07001016}
1017
Yves Gerey704c8c42019-08-13 22:32:46 +02001018// Don't run these tests in combination with sanitizers.
1019// They are already flaky *without* sanitizers.
1020// Sanitizers seem to increase flakiness (which brings noise),
1021// without reporting anything.
1022// TODO(webrtc:10867): Re-enable when flakiness fixed.
1023#if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
1024 defined(THREAD_SANITIZER)
1025#define MAYBE_StartRecordingVerifyCallbacks \
1026 DISABLED_StartRecordingVerifyCallbacks
1027#define MAYBE_StartPlayoutAndRecordingVerifyCallbacks \
1028 DISABLED_StartPlayoutAndRecordingVerifyCallbacks
1029#else
1030#define MAYBE_StartRecordingVerifyCallbacks StartRecordingVerifyCallbacks
1031#define MAYBE_StartPlayoutAndRecordingVerifyCallbacks \
1032 StartPlayoutAndRecordingVerifyCallbacks
1033#endif
1034
henrikaf2f91fa2017-03-17 04:26:22 -07001035// Start recording and verify that the native audio layer starts providing real
1036// audio samples using the RecordedDataIsAvailable() callback.
Yves Gereyff060ee2019-09-11 15:53:01 +02001037TEST_P(MAYBE_AudioDeviceTest, MAYBE_StartRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001038 SKIP_TEST_IF_NOT(requirements_satisfied());
1039 MockAudioTransport mock(TransportType::kRecord);
henrikae24991d2017-04-06 01:14:23 -07001040 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001041 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
1042 false, _))
1043 .Times(AtLeast(kNumCallbacks));
1044 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1045 StartRecording();
1046 event()->Wait(kTestTimeOutInMilliseconds);
1047 StopRecording();
Yves Gereyb93a2452019-07-19 22:46:13 +02001048 PreTearDown();
henrikaf2f91fa2017-03-17 04:26:22 -07001049}
1050
1051// Start playout and recording (full-duplex audio) and verify that audio is
1052// active in both directions.
Yves Gereyff060ee2019-09-11 15:53:01 +02001053TEST_P(MAYBE_AudioDeviceTest, MAYBE_StartPlayoutAndRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001054 SKIP_TEST_IF_NOT(requirements_satisfied());
1055 MockAudioTransport mock(TransportType::kPlayAndRecord);
henrikae24991d2017-04-06 01:14:23 -07001056 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001057 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
1058 .Times(AtLeast(kNumCallbacks));
1059 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
1060 false, _))
1061 .Times(AtLeast(kNumCallbacks));
1062 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1063 StartPlayout();
1064 StartRecording();
1065 event()->Wait(kTestTimeOutInMilliseconds);
1066 StopRecording();
1067 StopPlayout();
Yves Gereyb93a2452019-07-19 22:46:13 +02001068 PreTearDown();
henrikaf2f91fa2017-03-17 04:26:22 -07001069}
1070
henrikae24991d2017-04-06 01:14:23 -07001071// Start playout and recording and store recorded data in an intermediate FIFO
1072// buffer from which the playout side then reads its samples in the same order
1073// as they were stored. Under ideal circumstances, a callback sequence would
1074// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
1075// means 'packet played'. Under such conditions, the FIFO would contain max 1,
1076// with an average somewhere in (0,1) depending on how long the packets are
1077// buffered. However, under more realistic conditions, the size
1078// of the FIFO will vary more due to an unbalance between the two sides.
1079// This test tries to verify that the device maintains a balanced callback-
1080// sequence by running in loopback for a few seconds while measuring the size
1081// (max and average) of the FIFO. The size of the FIFO is increased by the
1082// recording side and decreased by the playout side.
Yves Gereyff060ee2019-09-11 15:53:01 +02001083TEST_P(MAYBE_AudioDeviceTest, RunPlayoutAndRecordingInFullDuplex) {
henrikae24991d2017-04-06 01:14:23 -07001084 SKIP_TEST_IF_NOT(requirements_satisfied());
1085 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1086 FifoAudioStream audio_stream;
1087 mock.HandleCallbacks(event(), &audio_stream,
1088 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
1089 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001090 // Run both sides using the same channel configuration to avoid conversions
1091 // between mono/stereo while running in full duplex mode. Also, some devices
1092 // (mainly on Windows) do not support mono.
1093 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1094 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
Gustaf Ullberg102b7282019-06-03 15:03:02 +02001095 // Mute speakers to prevent howling.
1096 EXPECT_EQ(0, audio_device()->SetSpeakerVolume(0));
henrikae24991d2017-04-06 01:14:23 -07001097 StartPlayout();
1098 StartRecording();
henrika714e5cd2017-04-20 08:03:11 -07001099 event()->Wait(static_cast<int>(
1100 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec)));
henrikae24991d2017-04-06 01:14:23 -07001101 StopRecording();
1102 StopPlayout();
Yves Gerey412282a2019-07-22 21:15:22 +02001103 // Avoid concurrent access to audio_stream.
1104 PreTearDown();
henrikae24991d2017-04-06 01:14:23 -07001105 // This thresholds is set rather high to accommodate differences in hardware
1106 // in several devices. The main idea is to capture cases where a very large
henrikab6ca7212017-10-06 12:47:52 +02001107 // latency is built up. See http://bugs.webrtc.org/7744 for examples on
1108 // bots where relatively large average latencies can happen.
1109 EXPECT_LE(audio_stream.average_size(), 25u);
henrikae24991d2017-04-06 01:14:23 -07001110 PRINT("\n");
1111}
1112
henrika5b6afc02018-09-05 14:34:40 +02001113// Runs audio in full duplex until user hits Enter. Intended as a manual test
1114// to ensure that the audio quality is good and that real device switches works
1115// as intended.
Yves Gereyff060ee2019-09-11 15:53:01 +02001116TEST_P(MAYBE_AudioDeviceTest,
henrika5b6afc02018-09-05 14:34:40 +02001117 DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey) {
1118 SKIP_TEST_IF_NOT(requirements_satisfied());
1119 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
1120 return;
1121 }
1122 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1123 FifoAudioStream audio_stream;
1124 mock.HandleCallbacks(&audio_stream);
1125 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1126 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1127 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
1128 // Ensure that the sample rate for both directions are identical so that we
1129 // always can listen to our own voice. Will lead to rate conversion (and
1130 // higher latency) if the native sample rate is not 48kHz.
1131 EXPECT_EQ(0, audio_device()->SetPlayoutSampleRate(48000));
1132 EXPECT_EQ(0, audio_device()->SetRecordingSampleRate(48000));
1133 StartPlayout();
1134 StartRecording();
1135 do {
1136 PRINT("Loopback audio is active at 48kHz. Press Enter to stop.\n");
1137 } while (getchar() != '\n');
1138 StopRecording();
1139 StopPlayout();
Yves Gereyb93a2452019-07-19 22:46:13 +02001140 PreTearDown();
henrika5b6afc02018-09-05 14:34:40 +02001141}
1142
henrika714e5cd2017-04-20 08:03:11 -07001143// Measures loopback latency and reports the min, max and average values for
1144// a full duplex audio session.
1145// The latency is measured like so:
1146// - Insert impulses periodically on the output side.
1147// - Detect the impulses on the input side.
1148// - Measure the time difference between the transmit time and receive time.
1149// - Store time differences in a vector and calculate min, max and average.
1150// This test needs the '--gtest_also_run_disabled_tests' flag to run and also
1151// some sort of audio feedback loop. E.g. a headset where the mic is placed
1152// close to the speaker to ensure highest possible echo. It is also recommended
1153// to run the test at highest possible output volume.
Yves Gereyff060ee2019-09-11 15:53:01 +02001154TEST_P(MAYBE_AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
henrika714e5cd2017-04-20 08:03:11 -07001155 SKIP_TEST_IF_NOT(requirements_satisfied());
1156 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1157 LatencyAudioStream audio_stream;
1158 mock.HandleCallbacks(event(), &audio_stream,
1159 kMeasureLatencyTimeInSec * kNumCallbacksPerSecond);
1160 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001161 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1162 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrika714e5cd2017-04-20 08:03:11 -07001163 StartPlayout();
1164 StartRecording();
1165 event()->Wait(static_cast<int>(
1166 std::max(kTestTimeOutInMilliseconds, 1000 * kMeasureLatencyTimeInSec)));
1167 StopRecording();
1168 StopPlayout();
Yves Gerey412282a2019-07-22 21:15:22 +02001169 // Avoid concurrent access to audio_stream.
1170 PreTearDown();
henrikac7d93582018-09-14 15:37:34 +02001171 // Verify that a sufficient number of transmitted impulses are detected.
1172 EXPECT_GE(audio_stream.num_latency_values(),
henrika714e5cd2017-04-20 08:03:11 -07001173 static_cast<size_t>(
henrikac7d93582018-09-14 15:37:34 +02001174 kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 2));
henrika714e5cd2017-04-20 08:03:11 -07001175 // Print out min, max and average delay values for debugging purposes.
1176 audio_stream.PrintResults();
1177}
1178
henrikaec9c7452018-06-08 16:10:03 +02001179#ifdef WEBRTC_WIN
1180// Test two different audio layers (or rather two different Core Audio
1181// implementations) for Windows.
Mirko Bonadeic84f6612019-01-31 12:20:57 +01001182INSTANTIATE_TEST_SUITE_P(
henrikaec9c7452018-06-08 16:10:03 +02001183 AudioLayerWin,
Yves Gereyff060ee2019-09-11 15:53:01 +02001184 MAYBE_AudioDeviceTest,
henrikaec9c7452018-06-08 16:10:03 +02001185 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio,
1186 AudioDeviceModule::kWindowsCoreAudio2));
1187#else
1188// For all platforms but Windows, only test the default audio layer.
Mirko Bonadeic84f6612019-01-31 12:20:57 +01001189INSTANTIATE_TEST_SUITE_P(
henrikaec9c7452018-06-08 16:10:03 +02001190 AudioLayer,
Yves Gereyff060ee2019-09-11 15:53:01 +02001191 MAYBE_AudioDeviceTest,
henrikaec9c7452018-06-08 16:10:03 +02001192 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio));
1193#endif
1194
henrikaf2f91fa2017-03-17 04:26:22 -07001195} // namespace webrtc