blob: 0c842b6305894c76655127e7c286e99e31671cab [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
henrika714e5cd2017-04-20 08:03:11 -070011#include <algorithm>
henrikaf2f91fa2017-03-17 04:26:22 -070012#include <cstring>
henrikaec9c7452018-06-08 16:10:03 +020013#include <memory>
henrika714e5cd2017-04-20 08:03:11 -070014#include <numeric>
henrikaf2f91fa2017-03-17 04:26:22 -070015
Steve Anton40d55332019-01-07 10:21:47 -080016#include "absl/memory/memory.h"
Danil Chapovalov196100e2018-06-21 10:17:24 +020017#include "absl/types/optional.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "api/array_view.h"
Mirko Bonadeid9708072019-01-25 20:26:48 +010019#include "api/scoped_refptr.h"
Danil Chapovalov1c41be62019-04-01 09:16:12 +020020#include "api/task_queue/default_task_queue_factory.h"
21#include "api/task_queue/task_queue_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "modules/audio_device/audio_device_impl.h"
23#include "modules/audio_device/include/audio_device.h"
24#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;
46using ::testing::NiceMock;
47using ::testing::NotNull;
henrika5b6afc02018-09-05 14:34:40 +020048using ::testing::Mock;
henrikaf2f91fa2017-03-17 04:26:22 -070049
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
henrikaf2f91fa2017-03-17 04:26:22 -070069// Don't run these tests in combination with sanitizers.
Sami Kalliomäkidefb7172018-09-25 13:12:05 +020070// TODO(webrtc:9778): Re-enable on THREAD_SANITIZER?
71#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \
72 !defined(THREAD_SANITIZER)
henrikaf2f91fa2017-03-17 04:26:22 -070073#define SKIP_TEST_IF_NOT(requirements_satisfied) \
74 do { \
75 if (!requirements_satisfied) { \
76 return; \
77 } \
78 } while (false)
79#else
80// Or if other audio-related requirements are not met.
81#define SKIP_TEST_IF_NOT(requirements_satisfied) \
82 do { \
83 return; \
84 } while (false)
85#endif
86
87// Number of callbacks (input or output) the tests waits for before we set
88// an event indicating that the test was OK.
henrikae24991d2017-04-06 01:14:23 -070089static constexpr size_t kNumCallbacks = 10;
henrikaf2f91fa2017-03-17 04:26:22 -070090// Max amount of time we wait for an event to be set while counting callbacks.
henrika714e5cd2017-04-20 08:03:11 -070091static constexpr size_t kTestTimeOutInMilliseconds = 10 * 1000;
henrikae24991d2017-04-06 01:14:23 -070092// Average number of audio callbacks per second assuming 10ms packet size.
93static constexpr size_t kNumCallbacksPerSecond = 100;
94// Run the full-duplex test during this time (unit is in seconds).
henrika714e5cd2017-04-20 08:03:11 -070095static constexpr size_t kFullDuplexTimeInSec = 5;
96// Length of round-trip latency measurements. Number of deteced impulses
97// shall be kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 1 since the
98// last transmitted pulse is not used.
99static constexpr size_t kMeasureLatencyTimeInSec = 10;
100// Sets the number of impulses per second in the latency test.
101static constexpr size_t kImpulseFrequencyInHz = 1;
102// Utilized in round-trip latency measurements to avoid capturing noise samples.
103static constexpr int kImpulseThreshold = 1000;
henrikaf2f91fa2017-03-17 04:26:22 -0700104
105enum class TransportType {
106 kInvalid,
107 kPlay,
108 kRecord,
109 kPlayAndRecord,
110};
henrikae24991d2017-04-06 01:14:23 -0700111
112// Interface for processing the audio stream. Real implementations can e.g.
113// run audio in loopback, read audio from a file or perform latency
114// measurements.
115class AudioStream {
116 public:
henrikaeb98c722018-03-20 12:54:07 +0100117 virtual void Write(rtc::ArrayView<const int16_t> source) = 0;
118 virtual void Read(rtc::ArrayView<int16_t> destination) = 0;
henrikae24991d2017-04-06 01:14:23 -0700119
120 virtual ~AudioStream() = default;
121};
122
henrika714e5cd2017-04-20 08:03:11 -0700123// Converts index corresponding to position within a 10ms buffer into a
124// delay value in milliseconds.
125// Example: index=240, frames_per_10ms_buffer=480 => 5ms as output.
126int IndexToMilliseconds(size_t index, size_t frames_per_10ms_buffer) {
127 return rtc::checked_cast<int>(
128 10.0 * (static_cast<double>(index) / frames_per_10ms_buffer) + 0.5);
129}
130
henrikaf2f91fa2017-03-17 04:26:22 -0700131} // namespace
132
henrikae24991d2017-04-06 01:14:23 -0700133// Simple first in first out (FIFO) class that wraps a list of 16-bit audio
134// buffers of fixed size and allows Write and Read operations. The idea is to
135// store recorded audio buffers (using Write) and then read (using Read) these
136// stored buffers with as short delay as possible when the audio layer needs
137// data to play out. The number of buffers in the FIFO will stabilize under
138// normal conditions since there will be a balance between Write and Read calls.
139// The container is a std::list container and access is protected with a lock
140// since both sides (playout and recording) are driven by its own thread.
141// Note that, we know by design that the size of the audio buffer will not
henrikac7d93582018-09-14 15:37:34 +0200142// change over time and that both sides will in most cases use the same size.
henrikae24991d2017-04-06 01:14:23 -0700143class FifoAudioStream : public AudioStream {
144 public:
henrikaeb98c722018-03-20 12:54:07 +0100145 void Write(rtc::ArrayView<const int16_t> source) override {
henrikae24991d2017-04-06 01:14:23 -0700146 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
147 const size_t size = [&] {
148 rtc::CritScope lock(&lock_);
149 fifo_.push_back(Buffer16(source.data(), source.size()));
150 return fifo_.size();
151 }();
152 if (size > max_size_) {
153 max_size_ = size;
154 }
155 // Add marker once per second to signal that audio is active.
156 if (write_count_++ % 100 == 0) {
157 PRINT(".");
158 }
159 written_elements_ += size;
160 }
161
henrikaeb98c722018-03-20 12:54:07 +0100162 void Read(rtc::ArrayView<int16_t> destination) override {
henrikae24991d2017-04-06 01:14:23 -0700163 rtc::CritScope lock(&lock_);
164 if (fifo_.empty()) {
165 std::fill(destination.begin(), destination.end(), 0);
166 } else {
167 const Buffer16& buffer = fifo_.front();
henrikac7d93582018-09-14 15:37:34 +0200168 if (buffer.size() == destination.size()) {
169 // Default case where input and output uses same sample rate and
170 // channel configuration. No conversion is needed.
171 std::copy(buffer.begin(), buffer.end(), destination.begin());
172 } else if (destination.size() == 2 * buffer.size()) {
173 // Recorded input signal in |buffer| is in mono. Do channel upmix to
174 // match stereo output (1 -> 2).
175 for (size_t i = 0; i < buffer.size(); ++i) {
176 destination[2 * i] = buffer[i];
177 destination[2 * i + 1] = buffer[i];
178 }
179 } else if (buffer.size() == 2 * destination.size()) {
180 // Recorded input signal in |buffer| is in stereo. Do channel downmix
181 // to match mono output (2 -> 1).
182 for (size_t i = 0; i < destination.size(); ++i) {
183 destination[i] =
184 (static_cast<int32_t>(buffer[2 * i]) + buffer[2 * i + 1]) / 2;
185 }
186 } else {
187 RTC_NOTREACHED() << "Required conversion is not support";
188 }
henrikae24991d2017-04-06 01:14:23 -0700189 fifo_.pop_front();
190 }
191 }
192
193 size_t size() const {
194 rtc::CritScope lock(&lock_);
195 return fifo_.size();
196 }
197
198 size_t max_size() const {
199 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
200 return max_size_;
201 }
202
203 size_t average_size() const {
204 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
205 return 0.5 + static_cast<float>(written_elements_ / write_count_);
206 }
207
208 using Buffer16 = rtc::BufferT<int16_t>;
209
210 rtc::CriticalSection lock_;
211 rtc::RaceChecker race_checker_;
212
danilchap56359be2017-09-07 07:53:45 -0700213 std::list<Buffer16> fifo_ RTC_GUARDED_BY(lock_);
214 size_t write_count_ RTC_GUARDED_BY(race_checker_) = 0;
215 size_t max_size_ RTC_GUARDED_BY(race_checker_) = 0;
216 size_t written_elements_ RTC_GUARDED_BY(race_checker_) = 0;
henrikae24991d2017-04-06 01:14:23 -0700217};
218
henrika714e5cd2017-04-20 08:03:11 -0700219// Inserts periodic impulses and measures the latency between the time of
220// transmission and time of receiving the same impulse.
221class LatencyAudioStream : public AudioStream {
222 public:
223 LatencyAudioStream() {
224 // Delay thread checkers from being initialized until first callback from
225 // respective thread.
226 read_thread_checker_.DetachFromThread();
227 write_thread_checker_.DetachFromThread();
228 }
229
230 // Insert periodic impulses in first two samples of |destination|.
henrikaeb98c722018-03-20 12:54:07 +0100231 void Read(rtc::ArrayView<int16_t> destination) override {
henrika714e5cd2017-04-20 08:03:11 -0700232 RTC_DCHECK_RUN_ON(&read_thread_checker_);
henrika714e5cd2017-04-20 08:03:11 -0700233 if (read_count_ == 0) {
234 PRINT("[");
235 }
236 read_count_++;
237 std::fill(destination.begin(), destination.end(), 0);
238 if (read_count_ % (kNumCallbacksPerSecond / kImpulseFrequencyInHz) == 0) {
239 PRINT(".");
240 {
241 rtc::CritScope lock(&lock_);
242 if (!pulse_time_) {
Oskar Sundbom6ad9f262017-11-16 10:53:39 +0100243 pulse_time_ = rtc::TimeMillis();
henrika714e5cd2017-04-20 08:03:11 -0700244 }
245 }
246 constexpr int16_t impulse = std::numeric_limits<int16_t>::max();
247 std::fill_n(destination.begin(), 2, impulse);
248 }
249 }
250
251 // Detect received impulses in |source|, derive time between transmission and
252 // detection and add the calculated delay to list of latencies.
henrikaeb98c722018-03-20 12:54:07 +0100253 void Write(rtc::ArrayView<const int16_t> source) override {
henrika714e5cd2017-04-20 08:03:11 -0700254 RTC_DCHECK_RUN_ON(&write_thread_checker_);
255 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
256 rtc::CritScope lock(&lock_);
257 write_count_++;
258 if (!pulse_time_) {
259 // Avoid detection of new impulse response until a new impulse has
260 // been transmitted (sets |pulse_time_| to value larger than zero).
261 return;
262 }
263 // Find index (element position in vector) of the max element.
264 const size_t index_of_max =
265 std::max_element(source.begin(), source.end()) - source.begin();
266 // Derive time between transmitted pulse and received pulse if the level
267 // is high enough (removes noise).
268 const size_t max = source[index_of_max];
269 if (max > kImpulseThreshold) {
270 PRINTD("(%zu, %zu)", max, index_of_max);
271 int64_t now_time = rtc::TimeMillis();
272 int extra_delay = IndexToMilliseconds(index_of_max, source.size());
273 PRINTD("[%d]", rtc::checked_cast<int>(now_time - pulse_time_));
274 PRINTD("[%d]", extra_delay);
275 // Total latency is the difference between transmit time and detection
276 // tome plus the extra delay within the buffer in which we detected the
277 // received impulse. It is transmitted at sample 0 but can be received
278 // at sample N where N > 0. The term |extra_delay| accounts for N and it
279 // is a value between 0 and 10ms.
280 latencies_.push_back(now_time - *pulse_time_ + extra_delay);
281 pulse_time_.reset();
282 } else {
283 PRINTD("-");
284 }
285 }
286
287 size_t num_latency_values() const {
288 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
289 return latencies_.size();
290 }
291
292 int min_latency() const {
293 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
294 if (latencies_.empty())
295 return 0;
296 return *std::min_element(latencies_.begin(), latencies_.end());
297 }
298
299 int max_latency() const {
300 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
301 if (latencies_.empty())
302 return 0;
303 return *std::max_element(latencies_.begin(), latencies_.end());
304 }
305
306 int average_latency() const {
307 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
308 if (latencies_.empty())
309 return 0;
310 return 0.5 + static_cast<double>(
311 std::accumulate(latencies_.begin(), latencies_.end(), 0)) /
312 latencies_.size();
313 }
314
315 void PrintResults() const {
316 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
317 PRINT("] ");
318 for (auto it = latencies_.begin(); it != latencies_.end(); ++it) {
319 PRINTD("%d ", *it);
320 }
321 PRINT("\n");
322 PRINT("[..........] [min, max, avg]=[%d, %d, %d] ms\n", min_latency(),
323 max_latency(), average_latency());
324 }
325
326 rtc::CriticalSection lock_;
327 rtc::RaceChecker race_checker_;
328 rtc::ThreadChecker read_thread_checker_;
329 rtc::ThreadChecker write_thread_checker_;
330
Danil Chapovalov196100e2018-06-21 10:17:24 +0200331 absl::optional<int64_t> pulse_time_ RTC_GUARDED_BY(lock_);
danilchap56359be2017-09-07 07:53:45 -0700332 std::vector<int> latencies_ RTC_GUARDED_BY(race_checker_);
Niels Möller1e062892018-02-07 10:18:32 +0100333 size_t read_count_ RTC_GUARDED_BY(read_thread_checker_) = 0;
334 size_t write_count_ RTC_GUARDED_BY(write_thread_checker_) = 0;
henrika714e5cd2017-04-20 08:03:11 -0700335};
336
henrikaf2f91fa2017-03-17 04:26:22 -0700337// Mocks the AudioTransport object and proxies actions for the two callbacks
338// (RecordedDataIsAvailable and NeedMorePlayData) to different implementations
339// of AudioStreamInterface.
340class MockAudioTransport : public test::MockAudioTransport {
341 public:
342 explicit MockAudioTransport(TransportType type) : type_(type) {}
343 ~MockAudioTransport() {}
344
345 // Set default actions of the mock object. We are delegating to fake
346 // implementation where the number of callbacks is counted and an event
347 // is set after a certain number of callbacks. Audio parameters are also
348 // checked.
henrikae24991d2017-04-06 01:14:23 -0700349 void HandleCallbacks(rtc::Event* event,
350 AudioStream* audio_stream,
351 int num_callbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700352 event_ = event;
henrikae24991d2017-04-06 01:14:23 -0700353 audio_stream_ = audio_stream;
henrikaf2f91fa2017-03-17 04:26:22 -0700354 num_callbacks_ = num_callbacks;
355 if (play_mode()) {
356 ON_CALL(*this, NeedMorePlayData(_, _, _, _, _, _, _, _))
357 .WillByDefault(
358 Invoke(this, &MockAudioTransport::RealNeedMorePlayData));
359 }
360 if (rec_mode()) {
361 ON_CALL(*this, RecordedDataIsAvailable(_, _, _, _, _, _, _, _, _, _))
362 .WillByDefault(
363 Invoke(this, &MockAudioTransport::RealRecordedDataIsAvailable));
364 }
365 }
366
henrika5b6afc02018-09-05 14:34:40 +0200367 // Special constructor used in manual tests where the user wants to run audio
368 // until e.g. a keyboard key is pressed. The event flag is set to nullptr by
369 // default since it is up to the user to stop the test. See e.g.
370 // DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey().
371 void HandleCallbacks(AudioStream* audio_stream) {
372 HandleCallbacks(nullptr, audio_stream, 0);
373 }
374
henrikaf2f91fa2017-03-17 04:26:22 -0700375 int32_t RealRecordedDataIsAvailable(const void* audio_buffer,
376 const size_t samples_per_channel,
377 const size_t bytes_per_frame,
378 const size_t channels,
379 const uint32_t sample_rate,
380 const uint32_t total_delay_ms,
381 const int32_t clock_drift,
382 const uint32_t current_mic_level,
383 const bool typing_status,
384 uint32_t& new_mic_level) {
385 EXPECT_TRUE(rec_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700386 // Store audio parameters once in the first callback. For all other
387 // callbacks, verify that the provided audio parameters are maintained and
388 // that each callback corresponds to 10ms for any given sample rate.
389 if (!record_parameters_.is_complete()) {
390 record_parameters_.reset(sample_rate, channels, samples_per_channel);
391 } else {
392 EXPECT_EQ(samples_per_channel, record_parameters_.frames_per_buffer());
393 EXPECT_EQ(bytes_per_frame, record_parameters_.GetBytesPerFrame());
394 EXPECT_EQ(channels, record_parameters_.channels());
395 EXPECT_EQ(static_cast<int>(sample_rate),
396 record_parameters_.sample_rate());
397 EXPECT_EQ(samples_per_channel,
398 record_parameters_.frames_per_10ms_buffer());
399 }
henrika78e0ac12018-09-27 16:23:21 +0200400 {
401 rtc::CritScope lock(&lock_);
402 rec_count_++;
403 }
henrikae24991d2017-04-06 01:14:23 -0700404 // Write audio data to audio stream object if one has been injected.
405 if (audio_stream_) {
406 audio_stream_->Write(
407 rtc::MakeArrayView(static_cast<const int16_t*>(audio_buffer),
henrikaeb98c722018-03-20 12:54:07 +0100408 samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700409 }
henrikaf2f91fa2017-03-17 04:26:22 -0700410 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200411 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700412 event_->Set();
413 }
414 return 0;
415 }
416
417 int32_t RealNeedMorePlayData(const size_t samples_per_channel,
418 const size_t bytes_per_frame,
419 const size_t channels,
420 const uint32_t sample_rate,
421 void* audio_buffer,
henrikaeb98c722018-03-20 12:54:07 +0100422 size_t& samples_out,
henrikaf2f91fa2017-03-17 04:26:22 -0700423 int64_t* elapsed_time_ms,
424 int64_t* ntp_time_ms) {
425 EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700426 // Store audio parameters once in the first callback. For all other
427 // callbacks, verify that the provided audio parameters are maintained and
428 // that each callback corresponds to 10ms for any given sample rate.
429 if (!playout_parameters_.is_complete()) {
430 playout_parameters_.reset(sample_rate, channels, samples_per_channel);
431 } else {
432 EXPECT_EQ(samples_per_channel, playout_parameters_.frames_per_buffer());
433 EXPECT_EQ(bytes_per_frame, playout_parameters_.GetBytesPerFrame());
434 EXPECT_EQ(channels, playout_parameters_.channels());
435 EXPECT_EQ(static_cast<int>(sample_rate),
436 playout_parameters_.sample_rate());
437 EXPECT_EQ(samples_per_channel,
438 playout_parameters_.frames_per_10ms_buffer());
439 }
henrika78e0ac12018-09-27 16:23:21 +0200440 {
441 rtc::CritScope lock(&lock_);
442 play_count_++;
443 }
henrikaeb98c722018-03-20 12:54:07 +0100444 samples_out = samples_per_channel * channels;
henrikae24991d2017-04-06 01:14:23 -0700445 // Read audio data from audio stream object if one has been injected.
446 if (audio_stream_) {
henrikaeb98c722018-03-20 12:54:07 +0100447 audio_stream_->Read(rtc::MakeArrayView(
448 static_cast<int16_t*>(audio_buffer), samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700449 } else {
450 // Fill the audio buffer with zeros to avoid disturbing audio.
451 const size_t num_bytes = samples_per_channel * bytes_per_frame;
452 std::memset(audio_buffer, 0, num_bytes);
453 }
henrikaf2f91fa2017-03-17 04:26:22 -0700454 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200455 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700456 event_->Set();
457 }
458 return 0;
459 }
460
461 bool ReceivedEnoughCallbacks() {
462 bool recording_done = false;
463 if (rec_mode()) {
henrika78e0ac12018-09-27 16:23:21 +0200464 rtc::CritScope lock(&lock_);
henrikaf2f91fa2017-03-17 04:26:22 -0700465 recording_done = rec_count_ >= num_callbacks_;
466 } else {
467 recording_done = true;
468 }
469 bool playout_done = false;
470 if (play_mode()) {
henrika78e0ac12018-09-27 16:23:21 +0200471 rtc::CritScope lock(&lock_);
henrikaf2f91fa2017-03-17 04:26:22 -0700472 playout_done = play_count_ >= num_callbacks_;
473 } else {
474 playout_done = true;
475 }
476 return recording_done && playout_done;
477 }
478
479 bool play_mode() const {
480 return type_ == TransportType::kPlay ||
481 type_ == TransportType::kPlayAndRecord;
482 }
483
484 bool rec_mode() const {
485 return type_ == TransportType::kRecord ||
486 type_ == TransportType::kPlayAndRecord;
487 }
488
henrika5b6afc02018-09-05 14:34:40 +0200489 void ResetCallbackCounters() {
henrika78e0ac12018-09-27 16:23:21 +0200490 rtc::CritScope lock(&lock_);
henrika5b6afc02018-09-05 14:34:40 +0200491 if (play_mode()) {
492 play_count_ = 0;
493 }
494 if (rec_mode()) {
495 rec_count_ = 0;
496 }
497 }
498
henrikaf2f91fa2017-03-17 04:26:22 -0700499 private:
henrika78e0ac12018-09-27 16:23:21 +0200500 rtc::CriticalSection lock_;
henrikaf2f91fa2017-03-17 04:26:22 -0700501 TransportType type_ = TransportType::kInvalid;
502 rtc::Event* event_ = nullptr;
henrikae24991d2017-04-06 01:14:23 -0700503 AudioStream* audio_stream_ = nullptr;
henrikaf2f91fa2017-03-17 04:26:22 -0700504 size_t num_callbacks_ = 0;
henrika78e0ac12018-09-27 16:23:21 +0200505 size_t play_count_ RTC_GUARDED_BY(lock_) = 0;
506 size_t rec_count_ RTC_GUARDED_BY(lock_) = 0;
henrikaf2f91fa2017-03-17 04:26:22 -0700507 AudioParameters playout_parameters_;
508 AudioParameters record_parameters_;
509};
510
511// AudioDeviceTest test fixture.
henrikaec9c7452018-06-08 16:10:03 +0200512class AudioDeviceTest
513 : public ::testing::TestWithParam<webrtc::AudioDeviceModule::AudioLayer> {
henrikaf2f91fa2017-03-17 04:26:22 -0700514 protected:
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200515 AudioDeviceTest()
516 : audio_layer_(GetParam()),
517 task_queue_factory_(CreateDefaultTaskQueueFactory()) {
Sami Kalliomäkia3b9b272018-09-25 15:03:43 +0200518// TODO(webrtc:9778): Re-enable on THREAD_SANITIZER?
Joachim Bauch5d2bb362017-12-20 21:19:49 +0100519#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \
Sami Kalliomäkia3b9b272018-09-25 15:03:43 +0200520 !defined(WEBRTC_DUMMY_AUDIO_BUILD) && !defined(THREAD_SANITIZER)
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 }
545#else
546 requirements_satisfied_ = false;
547#endif
548 if (requirements_satisfied_) {
henrika5773ad32018-09-21 14:53:10 +0200549 EXPECT_EQ(0, audio_device_->SetPlayoutDevice(AUDIO_DEVICE_ID));
henrikaf2f91fa2017-03-17 04:26:22 -0700550 EXPECT_EQ(0, audio_device_->InitSpeaker());
henrikaf2f91fa2017-03-17 04:26:22 -0700551 EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
552 EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
henrika5773ad32018-09-21 14:53:10 +0200553 EXPECT_EQ(0, audio_device_->SetRecordingDevice(AUDIO_DEVICE_ID));
554 EXPECT_EQ(0, audio_device_->InitMicrophone());
henrika0238ba82017-03-28 04:38:29 -0700555 // Avoid asking for input stereo support and always record in mono
556 // since asking can cause issues in combination with remote desktop.
557 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
558 // details.
559 EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
henrikaf2f91fa2017-03-17 04:26:22 -0700560 }
561 }
562
563 virtual ~AudioDeviceTest() {
564 if (audio_device_) {
565 EXPECT_EQ(0, audio_device_->Terminate());
566 }
567 }
568
569 bool requirements_satisfied() const { return requirements_satisfied_; }
570 rtc::Event* event() { return &event_; }
henrika5b6afc02018-09-05 14:34:40 +0200571 AudioDeviceModule::AudioLayer audio_layer() const { return audio_layer_; }
henrikaf2f91fa2017-03-17 04:26:22 -0700572
henrika5b6afc02018-09-05 14:34:40 +0200573 // AudioDeviceModuleForTest extends the default ADM interface with some extra
574 // test methods. Intended for usage in tests only and requires a unique
575 // factory method. See CreateAudioDevice() for details.
576 const rtc::scoped_refptr<AudioDeviceModuleForTest>& audio_device() const {
henrikaf2f91fa2017-03-17 04:26:22 -0700577 return audio_device_;
578 }
579
henrika5b6afc02018-09-05 14:34:40 +0200580 rtc::scoped_refptr<AudioDeviceModuleForTest> CreateAudioDevice() {
henrikaec9c7452018-06-08 16:10:03 +0200581 // Use the default factory for kPlatformDefaultAudio and a special factory
henrika5b6afc02018-09-05 14:34:40 +0200582 // CreateWindowsCoreAudioAudioDeviceModuleForTest() for kWindowsCoreAudio2.
henrikaec9c7452018-06-08 16:10:03 +0200583 // The value of |audio_layer_| is set at construction by GetParam() and two
584 // different layers are tested on Windows only.
585 if (audio_layer_ == AudioDeviceModule::kPlatformDefaultAudio) {
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200586 return AudioDeviceModule::CreateForTest(audio_layer_,
587 task_queue_factory_.get());
henrikaec9c7452018-06-08 16:10:03 +0200588 } else if (audio_layer_ == AudioDeviceModule::kWindowsCoreAudio2) {
589#ifdef WEBRTC_WIN
590 // We must initialize the COM library on a thread before we calling any of
591 // the library functions. All COM functions in the ADM will return
592 // CO_E_NOTINITIALIZED otherwise.
Karl Wiberg918f50c2018-07-05 11:40:33 +0200593 com_initializer_ = absl::make_unique<webrtc_win::ScopedCOMInitializer>(
henrikaec9c7452018-06-08 16:10:03 +0200594 webrtc_win::ScopedCOMInitializer::kMTA);
595 EXPECT_TRUE(com_initializer_->Succeeded());
596 EXPECT_TRUE(webrtc_win::core_audio_utility::IsSupported());
597 EXPECT_TRUE(webrtc_win::core_audio_utility::IsMMCSSSupported());
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200598 return CreateWindowsCoreAudioAudioDeviceModuleForTest(
599 task_queue_factory_.get());
henrikaec9c7452018-06-08 16:10:03 +0200600#else
601 return nullptr;
602#endif
603 } else {
604 return nullptr;
605 }
606 }
607
henrikaf2f91fa2017-03-17 04:26:22 -0700608 void StartPlayout() {
609 EXPECT_FALSE(audio_device()->Playing());
610 EXPECT_EQ(0, audio_device()->InitPlayout());
611 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
612 EXPECT_EQ(0, audio_device()->StartPlayout());
613 EXPECT_TRUE(audio_device()->Playing());
614 }
615
616 void StopPlayout() {
617 EXPECT_EQ(0, audio_device()->StopPlayout());
618 EXPECT_FALSE(audio_device()->Playing());
619 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
620 }
621
622 void StartRecording() {
623 EXPECT_FALSE(audio_device()->Recording());
624 EXPECT_EQ(0, audio_device()->InitRecording());
625 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
626 EXPECT_EQ(0, audio_device()->StartRecording());
627 EXPECT_TRUE(audio_device()->Recording());
628 }
629
630 void StopRecording() {
631 EXPECT_EQ(0, audio_device()->StopRecording());
632 EXPECT_FALSE(audio_device()->Recording());
633 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
634 }
635
henrikaec9c7452018-06-08 16:10:03 +0200636 bool NewWindowsAudioDeviceModuleIsUsed() {
637#ifdef WEBRTC_WIN
638 AudioDeviceModule::AudioLayer audio_layer;
639 EXPECT_EQ(0, audio_device()->ActiveAudioLayer(&audio_layer));
640 if (audio_layer == AudioDeviceModule::kWindowsCoreAudio2) {
641 // Default device is always added as first element in the list and the
642 // default communication device as the second element. Hence, the list
643 // contains two extra elements in this case.
644 return true;
645 }
646#endif
647 return false;
648 }
649
henrikaf2f91fa2017-03-17 04:26:22 -0700650 private:
henrikaec9c7452018-06-08 16:10:03 +0200651#ifdef WEBRTC_WIN
652 // Windows Core Audio based ADM needs to run on a COM initialized thread.
653 std::unique_ptr<webrtc_win::ScopedCOMInitializer> com_initializer_;
654#endif
655 AudioDeviceModule::AudioLayer audio_layer_;
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200656 std::unique_ptr<TaskQueueFactory> task_queue_factory_;
henrikaf2f91fa2017-03-17 04:26:22 -0700657 bool requirements_satisfied_ = true;
658 rtc::Event event_;
henrika5b6afc02018-09-05 14:34:40 +0200659 rtc::scoped_refptr<AudioDeviceModuleForTest> audio_device_;
henrikaf2f91fa2017-03-17 04:26:22 -0700660 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700661};
662
henrikaec9c7452018-06-08 16:10:03 +0200663// Instead of using the test fixture, verify that the different factory methods
664// work as intended.
665TEST(AudioDeviceTestWin, ConstructDestructWithFactory) {
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200666 std::unique_ptr<TaskQueueFactory> task_queue_factory =
667 CreateDefaultTaskQueueFactory();
henrikaec9c7452018-06-08 16:10:03 +0200668 rtc::scoped_refptr<AudioDeviceModule> audio_device;
669 // The default factory should work for all platforms when a default ADM is
670 // requested.
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200671 audio_device = AudioDeviceModule::Create(
672 AudioDeviceModule::kPlatformDefaultAudio, task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200673 EXPECT_TRUE(audio_device);
674 audio_device = nullptr;
675#ifdef WEBRTC_WIN
676 // For Windows, the old factory method creates an ADM where the platform-
677 // specific parts are implemented by an AudioDeviceGeneric object. Verify
678 // that the old factory can't be used in combination with the latest audio
679 // layer AudioDeviceModule::kWindowsCoreAudio2.
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200680 audio_device = AudioDeviceModule::Create(
681 AudioDeviceModule::kWindowsCoreAudio2, task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200682 EXPECT_FALSE(audio_device);
683 audio_device = nullptr;
684 // Instead, ensure that the new dedicated factory method called
685 // CreateWindowsCoreAudioAudioDeviceModule() can be used on Windows and that
686 // it sets the audio layer to kWindowsCoreAudio2 implicitly. Note that, the
687 // new ADM for Windows must be created on a COM thread.
688 webrtc_win::ScopedCOMInitializer com_initializer(
689 webrtc_win::ScopedCOMInitializer::kMTA);
690 EXPECT_TRUE(com_initializer.Succeeded());
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200691 audio_device =
692 CreateWindowsCoreAudioAudioDeviceModule(task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200693 EXPECT_TRUE(audio_device);
694 AudioDeviceModule::AudioLayer audio_layer;
695 EXPECT_EQ(0, audio_device->ActiveAudioLayer(&audio_layer));
696 EXPECT_EQ(audio_layer, AudioDeviceModule::kWindowsCoreAudio2);
697#endif
698}
henrikaf2f91fa2017-03-17 04:26:22 -0700699
henrikaec9c7452018-06-08 16:10:03 +0200700// Uses the test fixture to create, initialize and destruct the ADM.
701TEST_P(AudioDeviceTest, ConstructDestructDefault) {}
702
703TEST_P(AudioDeviceTest, InitTerminate) {
henrikaf2f91fa2017-03-17 04:26:22 -0700704 SKIP_TEST_IF_NOT(requirements_satisfied());
705 // Initialization is part of the test fixture.
706 EXPECT_TRUE(audio_device()->Initialized());
707 EXPECT_EQ(0, audio_device()->Terminate());
708 EXPECT_FALSE(audio_device()->Initialized());
709}
710
henrikaec9c7452018-06-08 16:10:03 +0200711// Enumerate all available and active output devices.
712TEST_P(AudioDeviceTest, PlayoutDeviceNames) {
henrikaf2f91fa2017-03-17 04:26:22 -0700713 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaec9c7452018-06-08 16:10:03 +0200714 char device_name[kAdmMaxDeviceNameSize];
715 char unique_id[kAdmMaxGuidSize];
716 int num_devices = audio_device()->PlayoutDevices();
717 if (NewWindowsAudioDeviceModuleIsUsed()) {
718 num_devices += 2;
719 }
720 EXPECT_GT(num_devices, 0);
721 for (int i = 0; i < num_devices; ++i) {
722 EXPECT_EQ(0, audio_device()->PlayoutDeviceName(i, device_name, unique_id));
723 }
724 EXPECT_EQ(-1, audio_device()->PlayoutDeviceName(num_devices, device_name,
725 unique_id));
726}
727
728// Enumerate all available and active input devices.
729TEST_P(AudioDeviceTest, RecordingDeviceNames) {
730 SKIP_TEST_IF_NOT(requirements_satisfied());
731 char device_name[kAdmMaxDeviceNameSize];
732 char unique_id[kAdmMaxGuidSize];
733 int num_devices = audio_device()->RecordingDevices();
734 if (NewWindowsAudioDeviceModuleIsUsed()) {
735 num_devices += 2;
736 }
737 EXPECT_GT(num_devices, 0);
738 for (int i = 0; i < num_devices; ++i) {
739 EXPECT_EQ(0,
740 audio_device()->RecordingDeviceName(i, device_name, unique_id));
741 }
742 EXPECT_EQ(-1, audio_device()->RecordingDeviceName(num_devices, device_name,
743 unique_id));
744}
745
746// Counts number of active output devices and ensure that all can be selected.
747TEST_P(AudioDeviceTest, SetPlayoutDevice) {
748 SKIP_TEST_IF_NOT(requirements_satisfied());
749 int num_devices = audio_device()->PlayoutDevices();
750 if (NewWindowsAudioDeviceModuleIsUsed()) {
751 num_devices += 2;
752 }
753 EXPECT_GT(num_devices, 0);
754 // Verify that all available playout devices can be set (not enabled yet).
755 for (int i = 0; i < num_devices; ++i) {
756 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(i));
757 }
758 EXPECT_EQ(-1, audio_device()->SetPlayoutDevice(num_devices));
759#ifdef WEBRTC_WIN
760 // On Windows, verify the alternative method where the user can select device
761 // by role.
762 EXPECT_EQ(
763 0, audio_device()->SetPlayoutDevice(AudioDeviceModule::kDefaultDevice));
764 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(
765 AudioDeviceModule::kDefaultCommunicationDevice));
766#endif
767}
768
769// Counts number of active input devices and ensure that all can be selected.
770TEST_P(AudioDeviceTest, SetRecordingDevice) {
771 SKIP_TEST_IF_NOT(requirements_satisfied());
772 int num_devices = audio_device()->RecordingDevices();
773 if (NewWindowsAudioDeviceModuleIsUsed()) {
774 num_devices += 2;
775 }
776 EXPECT_GT(num_devices, 0);
777 // Verify that all available recording devices can be set (not enabled yet).
778 for (int i = 0; i < num_devices; ++i) {
779 EXPECT_EQ(0, audio_device()->SetRecordingDevice(i));
780 }
781 EXPECT_EQ(-1, audio_device()->SetRecordingDevice(num_devices));
782#ifdef WEBRTC_WIN
783 // On Windows, verify the alternative method where the user can select device
784 // by role.
785 EXPECT_EQ(
786 0, audio_device()->SetRecordingDevice(AudioDeviceModule::kDefaultDevice));
787 EXPECT_EQ(0, audio_device()->SetRecordingDevice(
788 AudioDeviceModule::kDefaultCommunicationDevice));
789#endif
790}
791
792// Tests Start/Stop playout without any registered audio callback.
793TEST_P(AudioDeviceTest, StartStopPlayout) {
794 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaf2f91fa2017-03-17 04:26:22 -0700795 StartPlayout();
796 StopPlayout();
797}
798
799// Tests Start/Stop recording without any registered audio callback.
henrikaec9c7452018-06-08 16:10:03 +0200800TEST_P(AudioDeviceTest, StartStopRecording) {
henrikaf2f91fa2017-03-17 04:26:22 -0700801 SKIP_TEST_IF_NOT(requirements_satisfied());
802 StartRecording();
803 StopRecording();
henrikaf2f91fa2017-03-17 04:26:22 -0700804}
805
henrika6b3e1a22017-09-25 16:34:30 +0200806// Tests Init/Stop/Init recording without any registered audio callback.
807// See https://bugs.chromium.org/p/webrtc/issues/detail?id=8041 for details
808// on why this test is useful.
henrikaec9c7452018-06-08 16:10:03 +0200809TEST_P(AudioDeviceTest, InitStopInitRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200810 SKIP_TEST_IF_NOT(requirements_satisfied());
811 EXPECT_EQ(0, audio_device()->InitRecording());
812 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
813 StopRecording();
814 EXPECT_EQ(0, audio_device()->InitRecording());
815 StopRecording();
816}
817
818// Tests Init/Stop/Init recording while playout is active.
henrikaec9c7452018-06-08 16:10:03 +0200819TEST_P(AudioDeviceTest, InitStopInitRecordingWhilePlaying) {
henrika6b3e1a22017-09-25 16:34:30 +0200820 SKIP_TEST_IF_NOT(requirements_satisfied());
821 StartPlayout();
822 EXPECT_EQ(0, audio_device()->InitRecording());
823 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
824 StopRecording();
825 EXPECT_EQ(0, audio_device()->InitRecording());
826 StopRecording();
827 StopPlayout();
828}
829
830// Tests Init/Stop/Init playout without any registered audio callback.
henrikaec9c7452018-06-08 16:10:03 +0200831TEST_P(AudioDeviceTest, InitStopInitPlayout) {
henrika6b3e1a22017-09-25 16:34:30 +0200832 SKIP_TEST_IF_NOT(requirements_satisfied());
833 EXPECT_EQ(0, audio_device()->InitPlayout());
834 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
835 StopPlayout();
836 EXPECT_EQ(0, audio_device()->InitPlayout());
837 StopPlayout();
838}
839
840// Tests Init/Stop/Init playout while recording is active.
henrikaec9c7452018-06-08 16:10:03 +0200841TEST_P(AudioDeviceTest, InitStopInitPlayoutWhileRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200842 SKIP_TEST_IF_NOT(requirements_satisfied());
843 StartRecording();
844 EXPECT_EQ(0, audio_device()->InitPlayout());
845 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
846 StopPlayout();
847 EXPECT_EQ(0, audio_device()->InitPlayout());
848 StopPlayout();
849 StopRecording();
850}
851
henrika5b6afc02018-09-05 14:34:40 +0200852// TODO(henrika): restart without intermediate destruction is currently only
853// supported on Windows.
854#ifdef WEBRTC_WIN
855// Tests Start/Stop playout followed by a second session (emulates a restart
856// triggered by a user using public APIs).
857TEST_P(AudioDeviceTest, StartStopPlayoutWithExternalRestart) {
858 SKIP_TEST_IF_NOT(requirements_satisfied());
859 StartPlayout();
860 StopPlayout();
861 // Restart playout without destroying the ADM in between. Ensures that we
862 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
863 StartPlayout();
864 StopPlayout();
865}
866
867// Tests Start/Stop recording followed by a second session (emulates a restart
868// triggered by a user using public APIs).
869TEST_P(AudioDeviceTest, StartStopRecordingWithExternalRestart) {
870 SKIP_TEST_IF_NOT(requirements_satisfied());
871 StartRecording();
872 StopRecording();
873 // Restart recording without destroying the ADM in between. Ensures that we
874 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
875 StartRecording();
876 StopRecording();
877}
878
879// Tests Start/Stop playout followed by a second session (emulates a restart
880// triggered by an internal callback e.g. corresponding to a device switch).
881// Note that, internal restart is only supported in combination with the latest
882// Windows ADM.
883TEST_P(AudioDeviceTest, StartStopPlayoutWithInternalRestart) {
884 SKIP_TEST_IF_NOT(requirements_satisfied());
885 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
886 return;
887 }
888 MockAudioTransport mock(TransportType::kPlay);
889 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
890 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
891 .Times(AtLeast(kNumCallbacks));
892 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
893 StartPlayout();
894 event()->Wait(kTestTimeOutInMilliseconds);
895 EXPECT_TRUE(audio_device()->Playing());
896 // Restart playout but without stopping the internal audio thread.
897 // This procedure uses a non-public test API and it emulates what happens
898 // inside the ADM when e.g. a device is removed.
899 EXPECT_EQ(0, audio_device()->RestartPlayoutInternally());
900
901 // Run basic tests of public APIs while a restart attempt is active.
902 // These calls should now be very thin and not trigger any new actions.
903 EXPECT_EQ(-1, audio_device()->StopPlayout());
904 EXPECT_TRUE(audio_device()->Playing());
905 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
906 EXPECT_EQ(0, audio_device()->InitPlayout());
907 EXPECT_EQ(0, audio_device()->StartPlayout());
908
909 // Wait until audio has restarted and a new sequence of audio callbacks
910 // becomes active.
911 // TODO(henrika): is it possible to verify that the internal state transition
912 // is Stop->Init->Start?
913 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
914 mock.ResetCallbackCounters();
915 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
916 .Times(AtLeast(kNumCallbacks));
917 event()->Wait(kTestTimeOutInMilliseconds);
918 EXPECT_TRUE(audio_device()->Playing());
919 // Stop playout and the audio thread after successful internal restart.
920 StopPlayout();
921}
922
923// Tests Start/Stop recording followed by a second session (emulates a restart
924// triggered by an internal callback e.g. corresponding to a device switch).
925// Note that, internal restart is only supported in combination with the latest
926// Windows ADM.
927TEST_P(AudioDeviceTest, StartStopRecordingWithInternalRestart) {
928 SKIP_TEST_IF_NOT(requirements_satisfied());
929 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
930 return;
931 }
932 MockAudioTransport mock(TransportType::kRecord);
933 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
934 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
935 false, _))
936 .Times(AtLeast(kNumCallbacks));
937 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
938 StartRecording();
939 event()->Wait(kTestTimeOutInMilliseconds);
940 EXPECT_TRUE(audio_device()->Recording());
941 // Restart recording but without stopping the internal audio thread.
942 // This procedure uses a non-public test API and it emulates what happens
943 // inside the ADM when e.g. a device is removed.
944 EXPECT_EQ(0, audio_device()->RestartRecordingInternally());
945
946 // Run basic tests of public APIs while a restart attempt is active.
947 // These calls should now be very thin and not trigger any new actions.
948 EXPECT_EQ(-1, audio_device()->StopRecording());
949 EXPECT_TRUE(audio_device()->Recording());
950 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
951 EXPECT_EQ(0, audio_device()->InitRecording());
952 EXPECT_EQ(0, audio_device()->StartRecording());
953
954 // Wait until audio has restarted and a new sequence of audio callbacks
955 // becomes active.
956 // TODO(henrika): is it possible to verify that the internal state transition
957 // is Stop->Init->Start?
958 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
959 mock.ResetCallbackCounters();
960 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
961 false, _))
962 .Times(AtLeast(kNumCallbacks));
963 event()->Wait(kTestTimeOutInMilliseconds);
964 EXPECT_TRUE(audio_device()->Recording());
965 // Stop recording and the audio thread after successful internal restart.
966 StopRecording();
967}
968#endif // #ifdef WEBRTC_WIN
969
henrikaf2f91fa2017-03-17 04:26:22 -0700970// Start playout and verify that the native audio layer starts asking for real
971// audio samples to play out using the NeedMorePlayData() callback.
972// Note that we can't add expectations on audio parameters in EXPECT_CALL
973// since parameter are not provided in the each callback. We therefore test and
974// verify the parameters in the fake audio transport implementation instead.
henrikaec9c7452018-06-08 16:10:03 +0200975TEST_P(AudioDeviceTest, StartPlayoutVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700976 SKIP_TEST_IF_NOT(requirements_satisfied());
977 MockAudioTransport mock(TransportType::kPlay);
henrikae24991d2017-04-06 01:14:23 -0700978 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700979 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
980 .Times(AtLeast(kNumCallbacks));
981 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
982 StartPlayout();
983 event()->Wait(kTestTimeOutInMilliseconds);
984 StopPlayout();
985}
986
987// Start recording and verify that the native audio layer starts providing real
988// audio samples using the RecordedDataIsAvailable() callback.
henrikaec9c7452018-06-08 16:10:03 +0200989TEST_P(AudioDeviceTest, StartRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700990 SKIP_TEST_IF_NOT(requirements_satisfied());
991 MockAudioTransport mock(TransportType::kRecord);
henrikae24991d2017-04-06 01:14:23 -0700992 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700993 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
994 false, _))
995 .Times(AtLeast(kNumCallbacks));
996 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
997 StartRecording();
998 event()->Wait(kTestTimeOutInMilliseconds);
999 StopRecording();
1000}
1001
1002// Start playout and recording (full-duplex audio) and verify that audio is
1003// active in both directions.
henrikaec9c7452018-06-08 16:10:03 +02001004TEST_P(AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001005 SKIP_TEST_IF_NOT(requirements_satisfied());
1006 MockAudioTransport mock(TransportType::kPlayAndRecord);
henrikae24991d2017-04-06 01:14:23 -07001007 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001008 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
1009 .Times(AtLeast(kNumCallbacks));
1010 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
1011 false, _))
1012 .Times(AtLeast(kNumCallbacks));
1013 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1014 StartPlayout();
1015 StartRecording();
1016 event()->Wait(kTestTimeOutInMilliseconds);
1017 StopRecording();
1018 StopPlayout();
1019}
1020
henrikae24991d2017-04-06 01:14:23 -07001021// Start playout and recording and store recorded data in an intermediate FIFO
1022// buffer from which the playout side then reads its samples in the same order
1023// as they were stored. Under ideal circumstances, a callback sequence would
1024// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
1025// means 'packet played'. Under such conditions, the FIFO would contain max 1,
1026// with an average somewhere in (0,1) depending on how long the packets are
1027// buffered. However, under more realistic conditions, the size
1028// of the FIFO will vary more due to an unbalance between the two sides.
1029// This test tries to verify that the device maintains a balanced callback-
1030// sequence by running in loopback for a few seconds while measuring the size
1031// (max and average) of the FIFO. The size of the FIFO is increased by the
1032// recording side and decreased by the playout side.
henrikaec9c7452018-06-08 16:10:03 +02001033TEST_P(AudioDeviceTest, RunPlayoutAndRecordingInFullDuplex) {
henrikae24991d2017-04-06 01:14:23 -07001034 SKIP_TEST_IF_NOT(requirements_satisfied());
1035 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1036 FifoAudioStream audio_stream;
1037 mock.HandleCallbacks(event(), &audio_stream,
1038 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
1039 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001040 // Run both sides using the same channel configuration to avoid conversions
1041 // between mono/stereo while running in full duplex mode. Also, some devices
1042 // (mainly on Windows) do not support mono.
1043 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1044 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrikae24991d2017-04-06 01:14:23 -07001045 StartPlayout();
1046 StartRecording();
henrika714e5cd2017-04-20 08:03:11 -07001047 event()->Wait(static_cast<int>(
1048 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec)));
henrikae24991d2017-04-06 01:14:23 -07001049 StopRecording();
1050 StopPlayout();
1051 // This thresholds is set rather high to accommodate differences in hardware
1052 // in several devices. The main idea is to capture cases where a very large
henrikab6ca7212017-10-06 12:47:52 +02001053 // latency is built up. See http://bugs.webrtc.org/7744 for examples on
1054 // bots where relatively large average latencies can happen.
1055 EXPECT_LE(audio_stream.average_size(), 25u);
henrikae24991d2017-04-06 01:14:23 -07001056 PRINT("\n");
1057}
1058
henrika5b6afc02018-09-05 14:34:40 +02001059// Runs audio in full duplex until user hits Enter. Intended as a manual test
1060// to ensure that the audio quality is good and that real device switches works
1061// as intended.
1062TEST_P(AudioDeviceTest,
1063 DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey) {
1064 SKIP_TEST_IF_NOT(requirements_satisfied());
1065 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
1066 return;
1067 }
1068 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1069 FifoAudioStream audio_stream;
1070 mock.HandleCallbacks(&audio_stream);
1071 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1072 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1073 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
1074 // Ensure that the sample rate for both directions are identical so that we
1075 // always can listen to our own voice. Will lead to rate conversion (and
1076 // higher latency) if the native sample rate is not 48kHz.
1077 EXPECT_EQ(0, audio_device()->SetPlayoutSampleRate(48000));
1078 EXPECT_EQ(0, audio_device()->SetRecordingSampleRate(48000));
1079 StartPlayout();
1080 StartRecording();
1081 do {
1082 PRINT("Loopback audio is active at 48kHz. Press Enter to stop.\n");
1083 } while (getchar() != '\n');
1084 StopRecording();
1085 StopPlayout();
1086}
1087
henrika714e5cd2017-04-20 08:03:11 -07001088// Measures loopback latency and reports the min, max and average values for
1089// a full duplex audio session.
1090// The latency is measured like so:
1091// - Insert impulses periodically on the output side.
1092// - Detect the impulses on the input side.
1093// - Measure the time difference between the transmit time and receive time.
1094// - Store time differences in a vector and calculate min, max and average.
1095// This test needs the '--gtest_also_run_disabled_tests' flag to run and also
1096// some sort of audio feedback loop. E.g. a headset where the mic is placed
1097// close to the speaker to ensure highest possible echo. It is also recommended
1098// to run the test at highest possible output volume.
henrikaec9c7452018-06-08 16:10:03 +02001099TEST_P(AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
henrika714e5cd2017-04-20 08:03:11 -07001100 SKIP_TEST_IF_NOT(requirements_satisfied());
1101 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1102 LatencyAudioStream audio_stream;
1103 mock.HandleCallbacks(event(), &audio_stream,
1104 kMeasureLatencyTimeInSec * kNumCallbacksPerSecond);
1105 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001106 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1107 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrika714e5cd2017-04-20 08:03:11 -07001108 StartPlayout();
1109 StartRecording();
1110 event()->Wait(static_cast<int>(
1111 std::max(kTestTimeOutInMilliseconds, 1000 * kMeasureLatencyTimeInSec)));
1112 StopRecording();
1113 StopPlayout();
henrikac7d93582018-09-14 15:37:34 +02001114 // Verify that a sufficient number of transmitted impulses are detected.
1115 EXPECT_GE(audio_stream.num_latency_values(),
henrika714e5cd2017-04-20 08:03:11 -07001116 static_cast<size_t>(
henrikac7d93582018-09-14 15:37:34 +02001117 kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 2));
henrika714e5cd2017-04-20 08:03:11 -07001118 // Print out min, max and average delay values for debugging purposes.
1119 audio_stream.PrintResults();
1120}
1121
henrikaec9c7452018-06-08 16:10:03 +02001122#ifdef WEBRTC_WIN
1123// Test two different audio layers (or rather two different Core Audio
1124// implementations) for Windows.
Mirko Bonadeic84f6612019-01-31 12:20:57 +01001125INSTANTIATE_TEST_SUITE_P(
henrikaec9c7452018-06-08 16:10:03 +02001126 AudioLayerWin,
1127 AudioDeviceTest,
1128 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio,
1129 AudioDeviceModule::kWindowsCoreAudio2));
1130#else
1131// For all platforms but Windows, only test the default audio layer.
Mirko Bonadeic84f6612019-01-31 12:20:57 +01001132INSTANTIATE_TEST_SUITE_P(
henrikaec9c7452018-06-08 16:10:03 +02001133 AudioLayer,
1134 AudioDeviceTest,
1135 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio));
1136#endif
1137
henrikaf2f91fa2017-03-17 04:26:22 -07001138} // namespace webrtc