blob: 846f75745f8c821015c668819a7ccf0b51243775 [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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "modules/audio_device/audio_device_impl.h"
21#include "modules/audio_device/include/audio_device.h"
22#include "modules/audio_device/include/mock_audio_transport.h"
23#include "rtc_base/buffer.h"
Steve Anton10542f22019-01-11 09:11:00 -080024#include "rtc_base/critical_section.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "rtc_base/event.h"
26#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010027#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/race_checker.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/thread_annotations.h"
30#include "rtc_base/thread_checker.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "rtc_base/time_utils.h"
henrika5b6afc02018-09-05 14:34:40 +020032#include "system_wrappers/include/sleep.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "test/gmock.h"
34#include "test/gtest.h"
henrikaec9c7452018-06-08 16:10:03 +020035#ifdef WEBRTC_WIN
36#include "modules/audio_device/include/audio_device_factory.h"
37#include "modules/audio_device/win/core_audio_utility_win.h"
38#endif
henrikaf2f91fa2017-03-17 04:26:22 -070039
40using ::testing::_;
41using ::testing::AtLeast;
42using ::testing::Ge;
43using ::testing::Invoke;
44using ::testing::NiceMock;
45using ::testing::NotNull;
henrika5b6afc02018-09-05 14:34:40 +020046using ::testing::Mock;
henrikaf2f91fa2017-03-17 04:26:22 -070047
48namespace webrtc {
49namespace {
50
henrika5773ad32018-09-21 14:53:10 +020051// Using a #define for AUDIO_DEVICE since we will call *different* versions of
52// the ADM functions, depending on the ID type.
53#if defined(WEBRTC_WIN)
54#define AUDIO_DEVICE_ID (AudioDeviceModule::WindowsDeviceType::kDefaultDevice)
55#else
56#define AUDIO_DEVICE_ID (0u)
57#endif // defined(WEBRTC_WIN)
58
henrikae24991d2017-04-06 01:14:23 -070059// #define ENABLE_DEBUG_PRINTF
60#ifdef ENABLE_DEBUG_PRINTF
61#define PRINTD(...) fprintf(stderr, __VA_ARGS__);
62#else
63#define PRINTD(...) ((void)0)
64#endif
65#define PRINT(...) fprintf(stderr, __VA_ARGS__);
66
henrikaf2f91fa2017-03-17 04:26:22 -070067// Don't run these tests in combination with sanitizers.
Sami Kalliomäkidefb7172018-09-25 13:12:05 +020068// TODO(webrtc:9778): Re-enable on THREAD_SANITIZER?
69#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \
70 !defined(THREAD_SANITIZER)
henrikaf2f91fa2017-03-17 04:26:22 -070071#define SKIP_TEST_IF_NOT(requirements_satisfied) \
72 do { \
73 if (!requirements_satisfied) { \
74 return; \
75 } \
76 } while (false)
77#else
78// Or if other audio-related requirements are not met.
79#define SKIP_TEST_IF_NOT(requirements_satisfied) \
80 do { \
81 return; \
82 } while (false)
83#endif
84
85// Number of callbacks (input or output) the tests waits for before we set
86// an event indicating that the test was OK.
henrikae24991d2017-04-06 01:14:23 -070087static constexpr size_t kNumCallbacks = 10;
henrikaf2f91fa2017-03-17 04:26:22 -070088// Max amount of time we wait for an event to be set while counting callbacks.
henrika714e5cd2017-04-20 08:03:11 -070089static constexpr size_t kTestTimeOutInMilliseconds = 10 * 1000;
henrikae24991d2017-04-06 01:14:23 -070090// Average number of audio callbacks per second assuming 10ms packet size.
91static constexpr size_t kNumCallbacksPerSecond = 100;
92// Run the full-duplex test during this time (unit is in seconds).
henrika714e5cd2017-04-20 08:03:11 -070093static constexpr size_t kFullDuplexTimeInSec = 5;
94// Length of round-trip latency measurements. Number of deteced impulses
95// shall be kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 1 since the
96// last transmitted pulse is not used.
97static constexpr size_t kMeasureLatencyTimeInSec = 10;
98// Sets the number of impulses per second in the latency test.
99static constexpr size_t kImpulseFrequencyInHz = 1;
100// Utilized in round-trip latency measurements to avoid capturing noise samples.
101static constexpr int kImpulseThreshold = 1000;
henrikaf2f91fa2017-03-17 04:26:22 -0700102
103enum class TransportType {
104 kInvalid,
105 kPlay,
106 kRecord,
107 kPlayAndRecord,
108};
henrikae24991d2017-04-06 01:14:23 -0700109
110// Interface for processing the audio stream. Real implementations can e.g.
111// run audio in loopback, read audio from a file or perform latency
112// measurements.
113class AudioStream {
114 public:
henrikaeb98c722018-03-20 12:54:07 +0100115 virtual void Write(rtc::ArrayView<const int16_t> source) = 0;
116 virtual void Read(rtc::ArrayView<int16_t> destination) = 0;
henrikae24991d2017-04-06 01:14:23 -0700117
118 virtual ~AudioStream() = default;
119};
120
henrika714e5cd2017-04-20 08:03:11 -0700121// Converts index corresponding to position within a 10ms buffer into a
122// delay value in milliseconds.
123// Example: index=240, frames_per_10ms_buffer=480 => 5ms as output.
124int IndexToMilliseconds(size_t index, size_t frames_per_10ms_buffer) {
125 return rtc::checked_cast<int>(
126 10.0 * (static_cast<double>(index) / frames_per_10ms_buffer) + 0.5);
127}
128
henrikaf2f91fa2017-03-17 04:26:22 -0700129} // namespace
130
henrikae24991d2017-04-06 01:14:23 -0700131// Simple first in first out (FIFO) class that wraps a list of 16-bit audio
132// buffers of fixed size and allows Write and Read operations. The idea is to
133// store recorded audio buffers (using Write) and then read (using Read) these
134// stored buffers with as short delay as possible when the audio layer needs
135// data to play out. The number of buffers in the FIFO will stabilize under
136// normal conditions since there will be a balance between Write and Read calls.
137// The container is a std::list container and access is protected with a lock
138// since both sides (playout and recording) are driven by its own thread.
139// Note that, we know by design that the size of the audio buffer will not
henrikac7d93582018-09-14 15:37:34 +0200140// change over time and that both sides will in most cases use the same size.
henrikae24991d2017-04-06 01:14:23 -0700141class FifoAudioStream : public AudioStream {
142 public:
henrikaeb98c722018-03-20 12:54:07 +0100143 void Write(rtc::ArrayView<const int16_t> source) override {
henrikae24991d2017-04-06 01:14:23 -0700144 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
145 const size_t size = [&] {
146 rtc::CritScope lock(&lock_);
147 fifo_.push_back(Buffer16(source.data(), source.size()));
148 return fifo_.size();
149 }();
150 if (size > max_size_) {
151 max_size_ = size;
152 }
153 // Add marker once per second to signal that audio is active.
154 if (write_count_++ % 100 == 0) {
155 PRINT(".");
156 }
157 written_elements_ += size;
158 }
159
henrikaeb98c722018-03-20 12:54:07 +0100160 void Read(rtc::ArrayView<int16_t> destination) override {
henrikae24991d2017-04-06 01:14:23 -0700161 rtc::CritScope lock(&lock_);
162 if (fifo_.empty()) {
163 std::fill(destination.begin(), destination.end(), 0);
164 } else {
165 const Buffer16& buffer = fifo_.front();
henrikac7d93582018-09-14 15:37:34 +0200166 if (buffer.size() == destination.size()) {
167 // Default case where input and output uses same sample rate and
168 // channel configuration. No conversion is needed.
169 std::copy(buffer.begin(), buffer.end(), destination.begin());
170 } else if (destination.size() == 2 * buffer.size()) {
171 // Recorded input signal in |buffer| is in mono. Do channel upmix to
172 // match stereo output (1 -> 2).
173 for (size_t i = 0; i < buffer.size(); ++i) {
174 destination[2 * i] = buffer[i];
175 destination[2 * i + 1] = buffer[i];
176 }
177 } else if (buffer.size() == 2 * destination.size()) {
178 // Recorded input signal in |buffer| is in stereo. Do channel downmix
179 // to match mono output (2 -> 1).
180 for (size_t i = 0; i < destination.size(); ++i) {
181 destination[i] =
182 (static_cast<int32_t>(buffer[2 * i]) + buffer[2 * i + 1]) / 2;
183 }
184 } else {
185 RTC_NOTREACHED() << "Required conversion is not support";
186 }
henrikae24991d2017-04-06 01:14:23 -0700187 fifo_.pop_front();
188 }
189 }
190
191 size_t size() const {
192 rtc::CritScope lock(&lock_);
193 return fifo_.size();
194 }
195
196 size_t max_size() const {
197 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
198 return max_size_;
199 }
200
201 size_t average_size() const {
202 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
203 return 0.5 + static_cast<float>(written_elements_ / write_count_);
204 }
205
206 using Buffer16 = rtc::BufferT<int16_t>;
207
208 rtc::CriticalSection lock_;
209 rtc::RaceChecker race_checker_;
210
danilchap56359be2017-09-07 07:53:45 -0700211 std::list<Buffer16> fifo_ RTC_GUARDED_BY(lock_);
212 size_t write_count_ RTC_GUARDED_BY(race_checker_) = 0;
213 size_t max_size_ RTC_GUARDED_BY(race_checker_) = 0;
214 size_t written_elements_ RTC_GUARDED_BY(race_checker_) = 0;
henrikae24991d2017-04-06 01:14:23 -0700215};
216
henrika714e5cd2017-04-20 08:03:11 -0700217// Inserts periodic impulses and measures the latency between the time of
218// transmission and time of receiving the same impulse.
219class LatencyAudioStream : public AudioStream {
220 public:
221 LatencyAudioStream() {
222 // Delay thread checkers from being initialized until first callback from
223 // respective thread.
224 read_thread_checker_.DetachFromThread();
225 write_thread_checker_.DetachFromThread();
226 }
227
228 // Insert periodic impulses in first two samples of |destination|.
henrikaeb98c722018-03-20 12:54:07 +0100229 void Read(rtc::ArrayView<int16_t> destination) override {
henrika714e5cd2017-04-20 08:03:11 -0700230 RTC_DCHECK_RUN_ON(&read_thread_checker_);
henrika714e5cd2017-04-20 08:03:11 -0700231 if (read_count_ == 0) {
232 PRINT("[");
233 }
234 read_count_++;
235 std::fill(destination.begin(), destination.end(), 0);
236 if (read_count_ % (kNumCallbacksPerSecond / kImpulseFrequencyInHz) == 0) {
237 PRINT(".");
238 {
239 rtc::CritScope lock(&lock_);
240 if (!pulse_time_) {
Oskar Sundbom6ad9f262017-11-16 10:53:39 +0100241 pulse_time_ = rtc::TimeMillis();
henrika714e5cd2017-04-20 08:03:11 -0700242 }
243 }
244 constexpr int16_t impulse = std::numeric_limits<int16_t>::max();
245 std::fill_n(destination.begin(), 2, impulse);
246 }
247 }
248
249 // Detect received impulses in |source|, derive time between transmission and
250 // detection and add the calculated delay to list of latencies.
henrikaeb98c722018-03-20 12:54:07 +0100251 void Write(rtc::ArrayView<const int16_t> source) override {
henrika714e5cd2017-04-20 08:03:11 -0700252 RTC_DCHECK_RUN_ON(&write_thread_checker_);
253 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
254 rtc::CritScope lock(&lock_);
255 write_count_++;
256 if (!pulse_time_) {
257 // Avoid detection of new impulse response until a new impulse has
258 // been transmitted (sets |pulse_time_| to value larger than zero).
259 return;
260 }
261 // Find index (element position in vector) of the max element.
262 const size_t index_of_max =
263 std::max_element(source.begin(), source.end()) - source.begin();
264 // Derive time between transmitted pulse and received pulse if the level
265 // is high enough (removes noise).
266 const size_t max = source[index_of_max];
267 if (max > kImpulseThreshold) {
268 PRINTD("(%zu, %zu)", max, index_of_max);
269 int64_t now_time = rtc::TimeMillis();
270 int extra_delay = IndexToMilliseconds(index_of_max, source.size());
271 PRINTD("[%d]", rtc::checked_cast<int>(now_time - pulse_time_));
272 PRINTD("[%d]", extra_delay);
273 // Total latency is the difference between transmit time and detection
274 // tome plus the extra delay within the buffer in which we detected the
275 // received impulse. It is transmitted at sample 0 but can be received
276 // at sample N where N > 0. The term |extra_delay| accounts for N and it
277 // is a value between 0 and 10ms.
278 latencies_.push_back(now_time - *pulse_time_ + extra_delay);
279 pulse_time_.reset();
280 } else {
281 PRINTD("-");
282 }
283 }
284
285 size_t num_latency_values() const {
286 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
287 return latencies_.size();
288 }
289
290 int min_latency() const {
291 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
292 if (latencies_.empty())
293 return 0;
294 return *std::min_element(latencies_.begin(), latencies_.end());
295 }
296
297 int max_latency() const {
298 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
299 if (latencies_.empty())
300 return 0;
301 return *std::max_element(latencies_.begin(), latencies_.end());
302 }
303
304 int average_latency() const {
305 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
306 if (latencies_.empty())
307 return 0;
308 return 0.5 + static_cast<double>(
309 std::accumulate(latencies_.begin(), latencies_.end(), 0)) /
310 latencies_.size();
311 }
312
313 void PrintResults() const {
314 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
315 PRINT("] ");
316 for (auto it = latencies_.begin(); it != latencies_.end(); ++it) {
317 PRINTD("%d ", *it);
318 }
319 PRINT("\n");
320 PRINT("[..........] [min, max, avg]=[%d, %d, %d] ms\n", min_latency(),
321 max_latency(), average_latency());
322 }
323
324 rtc::CriticalSection lock_;
325 rtc::RaceChecker race_checker_;
326 rtc::ThreadChecker read_thread_checker_;
327 rtc::ThreadChecker write_thread_checker_;
328
Danil Chapovalov196100e2018-06-21 10:17:24 +0200329 absl::optional<int64_t> pulse_time_ RTC_GUARDED_BY(lock_);
danilchap56359be2017-09-07 07:53:45 -0700330 std::vector<int> latencies_ RTC_GUARDED_BY(race_checker_);
Niels Möller1e062892018-02-07 10:18:32 +0100331 size_t read_count_ RTC_GUARDED_BY(read_thread_checker_) = 0;
332 size_t write_count_ RTC_GUARDED_BY(write_thread_checker_) = 0;
henrika714e5cd2017-04-20 08:03:11 -0700333};
334
henrikaf2f91fa2017-03-17 04:26:22 -0700335// Mocks the AudioTransport object and proxies actions for the two callbacks
336// (RecordedDataIsAvailable and NeedMorePlayData) to different implementations
337// of AudioStreamInterface.
338class MockAudioTransport : public test::MockAudioTransport {
339 public:
340 explicit MockAudioTransport(TransportType type) : type_(type) {}
341 ~MockAudioTransport() {}
342
343 // Set default actions of the mock object. We are delegating to fake
344 // implementation where the number of callbacks is counted and an event
345 // is set after a certain number of callbacks. Audio parameters are also
346 // checked.
henrikae24991d2017-04-06 01:14:23 -0700347 void HandleCallbacks(rtc::Event* event,
348 AudioStream* audio_stream,
349 int num_callbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700350 event_ = event;
henrikae24991d2017-04-06 01:14:23 -0700351 audio_stream_ = audio_stream;
henrikaf2f91fa2017-03-17 04:26:22 -0700352 num_callbacks_ = num_callbacks;
353 if (play_mode()) {
354 ON_CALL(*this, NeedMorePlayData(_, _, _, _, _, _, _, _))
355 .WillByDefault(
356 Invoke(this, &MockAudioTransport::RealNeedMorePlayData));
357 }
358 if (rec_mode()) {
359 ON_CALL(*this, RecordedDataIsAvailable(_, _, _, _, _, _, _, _, _, _))
360 .WillByDefault(
361 Invoke(this, &MockAudioTransport::RealRecordedDataIsAvailable));
362 }
363 }
364
henrika5b6afc02018-09-05 14:34:40 +0200365 // Special constructor used in manual tests where the user wants to run audio
366 // until e.g. a keyboard key is pressed. The event flag is set to nullptr by
367 // default since it is up to the user to stop the test. See e.g.
368 // DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey().
369 void HandleCallbacks(AudioStream* audio_stream) {
370 HandleCallbacks(nullptr, audio_stream, 0);
371 }
372
henrikaf2f91fa2017-03-17 04:26:22 -0700373 int32_t RealRecordedDataIsAvailable(const void* audio_buffer,
374 const size_t samples_per_channel,
375 const size_t bytes_per_frame,
376 const size_t channels,
377 const uint32_t sample_rate,
378 const uint32_t total_delay_ms,
379 const int32_t clock_drift,
380 const uint32_t current_mic_level,
381 const bool typing_status,
382 uint32_t& new_mic_level) {
383 EXPECT_TRUE(rec_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700384 // Store audio parameters once in the first callback. For all other
385 // callbacks, verify that the provided audio parameters are maintained and
386 // that each callback corresponds to 10ms for any given sample rate.
387 if (!record_parameters_.is_complete()) {
388 record_parameters_.reset(sample_rate, channels, samples_per_channel);
389 } else {
390 EXPECT_EQ(samples_per_channel, record_parameters_.frames_per_buffer());
391 EXPECT_EQ(bytes_per_frame, record_parameters_.GetBytesPerFrame());
392 EXPECT_EQ(channels, record_parameters_.channels());
393 EXPECT_EQ(static_cast<int>(sample_rate),
394 record_parameters_.sample_rate());
395 EXPECT_EQ(samples_per_channel,
396 record_parameters_.frames_per_10ms_buffer());
397 }
henrika78e0ac12018-09-27 16:23:21 +0200398 {
399 rtc::CritScope lock(&lock_);
400 rec_count_++;
401 }
henrikae24991d2017-04-06 01:14:23 -0700402 // Write audio data to audio stream object if one has been injected.
403 if (audio_stream_) {
404 audio_stream_->Write(
405 rtc::MakeArrayView(static_cast<const int16_t*>(audio_buffer),
henrikaeb98c722018-03-20 12:54:07 +0100406 samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700407 }
henrikaf2f91fa2017-03-17 04:26:22 -0700408 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200409 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700410 event_->Set();
411 }
412 return 0;
413 }
414
415 int32_t RealNeedMorePlayData(const size_t samples_per_channel,
416 const size_t bytes_per_frame,
417 const size_t channels,
418 const uint32_t sample_rate,
419 void* audio_buffer,
henrikaeb98c722018-03-20 12:54:07 +0100420 size_t& samples_out,
henrikaf2f91fa2017-03-17 04:26:22 -0700421 int64_t* elapsed_time_ms,
422 int64_t* ntp_time_ms) {
423 EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700424 // Store audio parameters once in the first callback. For all other
425 // callbacks, verify that the provided audio parameters are maintained and
426 // that each callback corresponds to 10ms for any given sample rate.
427 if (!playout_parameters_.is_complete()) {
428 playout_parameters_.reset(sample_rate, channels, samples_per_channel);
429 } else {
430 EXPECT_EQ(samples_per_channel, playout_parameters_.frames_per_buffer());
431 EXPECT_EQ(bytes_per_frame, playout_parameters_.GetBytesPerFrame());
432 EXPECT_EQ(channels, playout_parameters_.channels());
433 EXPECT_EQ(static_cast<int>(sample_rate),
434 playout_parameters_.sample_rate());
435 EXPECT_EQ(samples_per_channel,
436 playout_parameters_.frames_per_10ms_buffer());
437 }
henrika78e0ac12018-09-27 16:23:21 +0200438 {
439 rtc::CritScope lock(&lock_);
440 play_count_++;
441 }
henrikaeb98c722018-03-20 12:54:07 +0100442 samples_out = samples_per_channel * channels;
henrikae24991d2017-04-06 01:14:23 -0700443 // Read audio data from audio stream object if one has been injected.
444 if (audio_stream_) {
henrikaeb98c722018-03-20 12:54:07 +0100445 audio_stream_->Read(rtc::MakeArrayView(
446 static_cast<int16_t*>(audio_buffer), samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700447 } else {
448 // Fill the audio buffer with zeros to avoid disturbing audio.
449 const size_t num_bytes = samples_per_channel * bytes_per_frame;
450 std::memset(audio_buffer, 0, num_bytes);
451 }
henrikaf2f91fa2017-03-17 04:26:22 -0700452 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200453 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700454 event_->Set();
455 }
456 return 0;
457 }
458
459 bool ReceivedEnoughCallbacks() {
460 bool recording_done = false;
461 if (rec_mode()) {
henrika78e0ac12018-09-27 16:23:21 +0200462 rtc::CritScope lock(&lock_);
henrikaf2f91fa2017-03-17 04:26:22 -0700463 recording_done = rec_count_ >= num_callbacks_;
464 } else {
465 recording_done = true;
466 }
467 bool playout_done = false;
468 if (play_mode()) {
henrika78e0ac12018-09-27 16:23:21 +0200469 rtc::CritScope lock(&lock_);
henrikaf2f91fa2017-03-17 04:26:22 -0700470 playout_done = play_count_ >= num_callbacks_;
471 } else {
472 playout_done = true;
473 }
474 return recording_done && playout_done;
475 }
476
477 bool play_mode() const {
478 return type_ == TransportType::kPlay ||
479 type_ == TransportType::kPlayAndRecord;
480 }
481
482 bool rec_mode() const {
483 return type_ == TransportType::kRecord ||
484 type_ == TransportType::kPlayAndRecord;
485 }
486
henrika5b6afc02018-09-05 14:34:40 +0200487 void ResetCallbackCounters() {
henrika78e0ac12018-09-27 16:23:21 +0200488 rtc::CritScope lock(&lock_);
henrika5b6afc02018-09-05 14:34:40 +0200489 if (play_mode()) {
490 play_count_ = 0;
491 }
492 if (rec_mode()) {
493 rec_count_ = 0;
494 }
495 }
496
henrikaf2f91fa2017-03-17 04:26:22 -0700497 private:
henrika78e0ac12018-09-27 16:23:21 +0200498 rtc::CriticalSection lock_;
henrikaf2f91fa2017-03-17 04:26:22 -0700499 TransportType type_ = TransportType::kInvalid;
500 rtc::Event* event_ = nullptr;
henrikae24991d2017-04-06 01:14:23 -0700501 AudioStream* audio_stream_ = nullptr;
henrikaf2f91fa2017-03-17 04:26:22 -0700502 size_t num_callbacks_ = 0;
henrika78e0ac12018-09-27 16:23:21 +0200503 size_t play_count_ RTC_GUARDED_BY(lock_) = 0;
504 size_t rec_count_ RTC_GUARDED_BY(lock_) = 0;
henrikaf2f91fa2017-03-17 04:26:22 -0700505 AudioParameters playout_parameters_;
506 AudioParameters record_parameters_;
507};
508
509// AudioDeviceTest test fixture.
henrikaec9c7452018-06-08 16:10:03 +0200510class AudioDeviceTest
511 : public ::testing::TestWithParam<webrtc::AudioDeviceModule::AudioLayer> {
henrikaf2f91fa2017-03-17 04:26:22 -0700512 protected:
Niels Möllerc572ff32018-11-07 08:43:50 +0100513 AudioDeviceTest() : audio_layer_(GetParam()) {
Sami Kalliomäkia3b9b272018-09-25 15:03:43 +0200514// TODO(webrtc:9778): Re-enable on THREAD_SANITIZER?
Joachim Bauch5d2bb362017-12-20 21:19:49 +0100515#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \
Sami Kalliomäkia3b9b272018-09-25 15:03:43 +0200516 !defined(WEBRTC_DUMMY_AUDIO_BUILD) && !defined(THREAD_SANITIZER)
henrikaf2f91fa2017-03-17 04:26:22 -0700517 rtc::LogMessage::LogToDebug(rtc::LS_INFO);
518 // Add extra logging fields here if needed for debugging.
henrikaec9c7452018-06-08 16:10:03 +0200519 rtc::LogMessage::LogTimestamps();
520 rtc::LogMessage::LogThreads();
521 audio_device_ = CreateAudioDevice();
henrikaf2f91fa2017-03-17 04:26:22 -0700522 EXPECT_NE(audio_device_.get(), nullptr);
523 AudioDeviceModule::AudioLayer audio_layer;
maxmorin33bf69a2017-03-23 04:06:53 -0700524 int got_platform_audio_layer =
525 audio_device_->ActiveAudioLayer(&audio_layer);
henrika919dc2e2017-10-12 14:24:55 +0200526 // First, ensure that a valid audio layer can be activated.
527 if (got_platform_audio_layer != 0) {
henrikaf2f91fa2017-03-17 04:26:22 -0700528 requirements_satisfied_ = false;
529 }
henrika919dc2e2017-10-12 14:24:55 +0200530 // Next, verify that the ADM can be initialized.
henrikaf2f91fa2017-03-17 04:26:22 -0700531 if (requirements_satisfied_) {
henrika919dc2e2017-10-12 14:24:55 +0200532 requirements_satisfied_ = (audio_device_->Init() == 0);
533 }
534 // Finally, ensure that at least one valid device exists in each direction.
535 if (requirements_satisfied_) {
henrikaf2f91fa2017-03-17 04:26:22 -0700536 const int16_t num_playout_devices = audio_device_->PlayoutDevices();
537 const int16_t num_record_devices = audio_device_->RecordingDevices();
538 requirements_satisfied_ =
539 num_playout_devices > 0 && num_record_devices > 0;
540 }
541#else
542 requirements_satisfied_ = false;
543#endif
544 if (requirements_satisfied_) {
henrika5773ad32018-09-21 14:53:10 +0200545 EXPECT_EQ(0, audio_device_->SetPlayoutDevice(AUDIO_DEVICE_ID));
henrikaf2f91fa2017-03-17 04:26:22 -0700546 EXPECT_EQ(0, audio_device_->InitSpeaker());
henrikaf2f91fa2017-03-17 04:26:22 -0700547 EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
548 EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
henrika5773ad32018-09-21 14:53:10 +0200549 EXPECT_EQ(0, audio_device_->SetRecordingDevice(AUDIO_DEVICE_ID));
550 EXPECT_EQ(0, audio_device_->InitMicrophone());
henrika0238ba82017-03-28 04:38:29 -0700551 // Avoid asking for input stereo support and always record in mono
552 // since asking can cause issues in combination with remote desktop.
553 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
554 // details.
555 EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
henrikaf2f91fa2017-03-17 04:26:22 -0700556 }
557 }
558
559 virtual ~AudioDeviceTest() {
560 if (audio_device_) {
561 EXPECT_EQ(0, audio_device_->Terminate());
562 }
563 }
564
565 bool requirements_satisfied() const { return requirements_satisfied_; }
566 rtc::Event* event() { return &event_; }
henrika5b6afc02018-09-05 14:34:40 +0200567 AudioDeviceModule::AudioLayer audio_layer() const { return audio_layer_; }
henrikaf2f91fa2017-03-17 04:26:22 -0700568
henrika5b6afc02018-09-05 14:34:40 +0200569 // AudioDeviceModuleForTest extends the default ADM interface with some extra
570 // test methods. Intended for usage in tests only and requires a unique
571 // factory method. See CreateAudioDevice() for details.
572 const rtc::scoped_refptr<AudioDeviceModuleForTest>& audio_device() const {
henrikaf2f91fa2017-03-17 04:26:22 -0700573 return audio_device_;
574 }
575
henrika5b6afc02018-09-05 14:34:40 +0200576 rtc::scoped_refptr<AudioDeviceModuleForTest> CreateAudioDevice() {
henrikaec9c7452018-06-08 16:10:03 +0200577 // Use the default factory for kPlatformDefaultAudio and a special factory
henrika5b6afc02018-09-05 14:34:40 +0200578 // CreateWindowsCoreAudioAudioDeviceModuleForTest() for kWindowsCoreAudio2.
henrikaec9c7452018-06-08 16:10:03 +0200579 // The value of |audio_layer_| is set at construction by GetParam() and two
580 // different layers are tested on Windows only.
581 if (audio_layer_ == AudioDeviceModule::kPlatformDefaultAudio) {
henrika5b6afc02018-09-05 14:34:40 +0200582 return AudioDeviceModule::CreateForTest(audio_layer_);
henrikaec9c7452018-06-08 16:10:03 +0200583 } else if (audio_layer_ == AudioDeviceModule::kWindowsCoreAudio2) {
584#ifdef WEBRTC_WIN
585 // We must initialize the COM library on a thread before we calling any of
586 // the library functions. All COM functions in the ADM will return
587 // CO_E_NOTINITIALIZED otherwise.
Karl Wiberg918f50c2018-07-05 11:40:33 +0200588 com_initializer_ = absl::make_unique<webrtc_win::ScopedCOMInitializer>(
henrikaec9c7452018-06-08 16:10:03 +0200589 webrtc_win::ScopedCOMInitializer::kMTA);
590 EXPECT_TRUE(com_initializer_->Succeeded());
591 EXPECT_TRUE(webrtc_win::core_audio_utility::IsSupported());
592 EXPECT_TRUE(webrtc_win::core_audio_utility::IsMMCSSSupported());
henrika5b6afc02018-09-05 14:34:40 +0200593 return CreateWindowsCoreAudioAudioDeviceModuleForTest();
henrikaec9c7452018-06-08 16:10:03 +0200594#else
595 return nullptr;
596#endif
597 } else {
598 return nullptr;
599 }
600 }
601
henrikaf2f91fa2017-03-17 04:26:22 -0700602 void StartPlayout() {
603 EXPECT_FALSE(audio_device()->Playing());
604 EXPECT_EQ(0, audio_device()->InitPlayout());
605 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
606 EXPECT_EQ(0, audio_device()->StartPlayout());
607 EXPECT_TRUE(audio_device()->Playing());
608 }
609
610 void StopPlayout() {
611 EXPECT_EQ(0, audio_device()->StopPlayout());
612 EXPECT_FALSE(audio_device()->Playing());
613 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
614 }
615
616 void StartRecording() {
617 EXPECT_FALSE(audio_device()->Recording());
618 EXPECT_EQ(0, audio_device()->InitRecording());
619 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
620 EXPECT_EQ(0, audio_device()->StartRecording());
621 EXPECT_TRUE(audio_device()->Recording());
622 }
623
624 void StopRecording() {
625 EXPECT_EQ(0, audio_device()->StopRecording());
626 EXPECT_FALSE(audio_device()->Recording());
627 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
628 }
629
henrikaec9c7452018-06-08 16:10:03 +0200630 bool NewWindowsAudioDeviceModuleIsUsed() {
631#ifdef WEBRTC_WIN
632 AudioDeviceModule::AudioLayer audio_layer;
633 EXPECT_EQ(0, audio_device()->ActiveAudioLayer(&audio_layer));
634 if (audio_layer == AudioDeviceModule::kWindowsCoreAudio2) {
635 // Default device is always added as first element in the list and the
636 // default communication device as the second element. Hence, the list
637 // contains two extra elements in this case.
638 return true;
639 }
640#endif
641 return false;
642 }
643
henrikaf2f91fa2017-03-17 04:26:22 -0700644 private:
henrikaec9c7452018-06-08 16:10:03 +0200645#ifdef WEBRTC_WIN
646 // Windows Core Audio based ADM needs to run on a COM initialized thread.
647 std::unique_ptr<webrtc_win::ScopedCOMInitializer> com_initializer_;
648#endif
649 AudioDeviceModule::AudioLayer audio_layer_;
henrikaf2f91fa2017-03-17 04:26:22 -0700650 bool requirements_satisfied_ = true;
651 rtc::Event event_;
henrika5b6afc02018-09-05 14:34:40 +0200652 rtc::scoped_refptr<AudioDeviceModuleForTest> audio_device_;
henrikaf2f91fa2017-03-17 04:26:22 -0700653 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700654};
655
henrikaec9c7452018-06-08 16:10:03 +0200656// Instead of using the test fixture, verify that the different factory methods
657// work as intended.
658TEST(AudioDeviceTestWin, ConstructDestructWithFactory) {
659 rtc::scoped_refptr<AudioDeviceModule> audio_device;
660 // The default factory should work for all platforms when a default ADM is
661 // requested.
662 audio_device =
663 AudioDeviceModule::Create(AudioDeviceModule::kPlatformDefaultAudio);
664 EXPECT_TRUE(audio_device);
665 audio_device = nullptr;
666#ifdef WEBRTC_WIN
667 // For Windows, the old factory method creates an ADM where the platform-
668 // specific parts are implemented by an AudioDeviceGeneric object. Verify
669 // that the old factory can't be used in combination with the latest audio
670 // layer AudioDeviceModule::kWindowsCoreAudio2.
671 audio_device =
672 AudioDeviceModule::Create(AudioDeviceModule::kWindowsCoreAudio2);
673 EXPECT_FALSE(audio_device);
674 audio_device = nullptr;
675 // Instead, ensure that the new dedicated factory method called
676 // CreateWindowsCoreAudioAudioDeviceModule() can be used on Windows and that
677 // it sets the audio layer to kWindowsCoreAudio2 implicitly. Note that, the
678 // new ADM for Windows must be created on a COM thread.
679 webrtc_win::ScopedCOMInitializer com_initializer(
680 webrtc_win::ScopedCOMInitializer::kMTA);
681 EXPECT_TRUE(com_initializer.Succeeded());
682 audio_device = CreateWindowsCoreAudioAudioDeviceModule();
683 EXPECT_TRUE(audio_device);
684 AudioDeviceModule::AudioLayer audio_layer;
685 EXPECT_EQ(0, audio_device->ActiveAudioLayer(&audio_layer));
686 EXPECT_EQ(audio_layer, AudioDeviceModule::kWindowsCoreAudio2);
687#endif
688}
henrikaf2f91fa2017-03-17 04:26:22 -0700689
henrikaec9c7452018-06-08 16:10:03 +0200690// Uses the test fixture to create, initialize and destruct the ADM.
691TEST_P(AudioDeviceTest, ConstructDestructDefault) {}
692
693TEST_P(AudioDeviceTest, InitTerminate) {
henrikaf2f91fa2017-03-17 04:26:22 -0700694 SKIP_TEST_IF_NOT(requirements_satisfied());
695 // Initialization is part of the test fixture.
696 EXPECT_TRUE(audio_device()->Initialized());
697 EXPECT_EQ(0, audio_device()->Terminate());
698 EXPECT_FALSE(audio_device()->Initialized());
699}
700
henrikaec9c7452018-06-08 16:10:03 +0200701// Enumerate all available and active output devices.
702TEST_P(AudioDeviceTest, PlayoutDeviceNames) {
henrikaf2f91fa2017-03-17 04:26:22 -0700703 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaec9c7452018-06-08 16:10:03 +0200704 char device_name[kAdmMaxDeviceNameSize];
705 char unique_id[kAdmMaxGuidSize];
706 int num_devices = audio_device()->PlayoutDevices();
707 if (NewWindowsAudioDeviceModuleIsUsed()) {
708 num_devices += 2;
709 }
710 EXPECT_GT(num_devices, 0);
711 for (int i = 0; i < num_devices; ++i) {
712 EXPECT_EQ(0, audio_device()->PlayoutDeviceName(i, device_name, unique_id));
713 }
714 EXPECT_EQ(-1, audio_device()->PlayoutDeviceName(num_devices, device_name,
715 unique_id));
716}
717
718// Enumerate all available and active input devices.
719TEST_P(AudioDeviceTest, RecordingDeviceNames) {
720 SKIP_TEST_IF_NOT(requirements_satisfied());
721 char device_name[kAdmMaxDeviceNameSize];
722 char unique_id[kAdmMaxGuidSize];
723 int num_devices = audio_device()->RecordingDevices();
724 if (NewWindowsAudioDeviceModuleIsUsed()) {
725 num_devices += 2;
726 }
727 EXPECT_GT(num_devices, 0);
728 for (int i = 0; i < num_devices; ++i) {
729 EXPECT_EQ(0,
730 audio_device()->RecordingDeviceName(i, device_name, unique_id));
731 }
732 EXPECT_EQ(-1, audio_device()->RecordingDeviceName(num_devices, device_name,
733 unique_id));
734}
735
736// Counts number of active output devices and ensure that all can be selected.
737TEST_P(AudioDeviceTest, SetPlayoutDevice) {
738 SKIP_TEST_IF_NOT(requirements_satisfied());
739 int num_devices = audio_device()->PlayoutDevices();
740 if (NewWindowsAudioDeviceModuleIsUsed()) {
741 num_devices += 2;
742 }
743 EXPECT_GT(num_devices, 0);
744 // Verify that all available playout devices can be set (not enabled yet).
745 for (int i = 0; i < num_devices; ++i) {
746 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(i));
747 }
748 EXPECT_EQ(-1, audio_device()->SetPlayoutDevice(num_devices));
749#ifdef WEBRTC_WIN
750 // On Windows, verify the alternative method where the user can select device
751 // by role.
752 EXPECT_EQ(
753 0, audio_device()->SetPlayoutDevice(AudioDeviceModule::kDefaultDevice));
754 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(
755 AudioDeviceModule::kDefaultCommunicationDevice));
756#endif
757}
758
759// Counts number of active input devices and ensure that all can be selected.
760TEST_P(AudioDeviceTest, SetRecordingDevice) {
761 SKIP_TEST_IF_NOT(requirements_satisfied());
762 int num_devices = audio_device()->RecordingDevices();
763 if (NewWindowsAudioDeviceModuleIsUsed()) {
764 num_devices += 2;
765 }
766 EXPECT_GT(num_devices, 0);
767 // Verify that all available recording devices can be set (not enabled yet).
768 for (int i = 0; i < num_devices; ++i) {
769 EXPECT_EQ(0, audio_device()->SetRecordingDevice(i));
770 }
771 EXPECT_EQ(-1, audio_device()->SetRecordingDevice(num_devices));
772#ifdef WEBRTC_WIN
773 // On Windows, verify the alternative method where the user can select device
774 // by role.
775 EXPECT_EQ(
776 0, audio_device()->SetRecordingDevice(AudioDeviceModule::kDefaultDevice));
777 EXPECT_EQ(0, audio_device()->SetRecordingDevice(
778 AudioDeviceModule::kDefaultCommunicationDevice));
779#endif
780}
781
782// Tests Start/Stop playout without any registered audio callback.
783TEST_P(AudioDeviceTest, StartStopPlayout) {
784 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaf2f91fa2017-03-17 04:26:22 -0700785 StartPlayout();
786 StopPlayout();
787}
788
789// Tests Start/Stop recording without any registered audio callback.
henrikaec9c7452018-06-08 16:10:03 +0200790TEST_P(AudioDeviceTest, StartStopRecording) {
henrikaf2f91fa2017-03-17 04:26:22 -0700791 SKIP_TEST_IF_NOT(requirements_satisfied());
792 StartRecording();
793 StopRecording();
henrikaf2f91fa2017-03-17 04:26:22 -0700794}
795
henrika6b3e1a22017-09-25 16:34:30 +0200796// Tests Init/Stop/Init recording without any registered audio callback.
797// See https://bugs.chromium.org/p/webrtc/issues/detail?id=8041 for details
798// on why this test is useful.
henrikaec9c7452018-06-08 16:10:03 +0200799TEST_P(AudioDeviceTest, InitStopInitRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200800 SKIP_TEST_IF_NOT(requirements_satisfied());
801 EXPECT_EQ(0, audio_device()->InitRecording());
802 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
803 StopRecording();
804 EXPECT_EQ(0, audio_device()->InitRecording());
805 StopRecording();
806}
807
808// Tests Init/Stop/Init recording while playout is active.
henrikaec9c7452018-06-08 16:10:03 +0200809TEST_P(AudioDeviceTest, InitStopInitRecordingWhilePlaying) {
henrika6b3e1a22017-09-25 16:34:30 +0200810 SKIP_TEST_IF_NOT(requirements_satisfied());
811 StartPlayout();
812 EXPECT_EQ(0, audio_device()->InitRecording());
813 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
814 StopRecording();
815 EXPECT_EQ(0, audio_device()->InitRecording());
816 StopRecording();
817 StopPlayout();
818}
819
820// Tests Init/Stop/Init playout without any registered audio callback.
henrikaec9c7452018-06-08 16:10:03 +0200821TEST_P(AudioDeviceTest, InitStopInitPlayout) {
henrika6b3e1a22017-09-25 16:34:30 +0200822 SKIP_TEST_IF_NOT(requirements_satisfied());
823 EXPECT_EQ(0, audio_device()->InitPlayout());
824 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
825 StopPlayout();
826 EXPECT_EQ(0, audio_device()->InitPlayout());
827 StopPlayout();
828}
829
830// Tests Init/Stop/Init playout while recording is active.
henrikaec9c7452018-06-08 16:10:03 +0200831TEST_P(AudioDeviceTest, InitStopInitPlayoutWhileRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200832 SKIP_TEST_IF_NOT(requirements_satisfied());
833 StartRecording();
834 EXPECT_EQ(0, audio_device()->InitPlayout());
835 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
836 StopPlayout();
837 EXPECT_EQ(0, audio_device()->InitPlayout());
838 StopPlayout();
839 StopRecording();
840}
841
henrika5b6afc02018-09-05 14:34:40 +0200842// TODO(henrika): restart without intermediate destruction is currently only
843// supported on Windows.
844#ifdef WEBRTC_WIN
845// Tests Start/Stop playout followed by a second session (emulates a restart
846// triggered by a user using public APIs).
847TEST_P(AudioDeviceTest, StartStopPlayoutWithExternalRestart) {
848 SKIP_TEST_IF_NOT(requirements_satisfied());
849 StartPlayout();
850 StopPlayout();
851 // Restart playout without destroying the ADM in between. Ensures that we
852 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
853 StartPlayout();
854 StopPlayout();
855}
856
857// Tests Start/Stop recording followed by a second session (emulates a restart
858// triggered by a user using public APIs).
859TEST_P(AudioDeviceTest, StartStopRecordingWithExternalRestart) {
860 SKIP_TEST_IF_NOT(requirements_satisfied());
861 StartRecording();
862 StopRecording();
863 // Restart recording without destroying the ADM in between. Ensures that we
864 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
865 StartRecording();
866 StopRecording();
867}
868
869// Tests Start/Stop playout followed by a second session (emulates a restart
870// triggered by an internal callback e.g. corresponding to a device switch).
871// Note that, internal restart is only supported in combination with the latest
872// Windows ADM.
873TEST_P(AudioDeviceTest, StartStopPlayoutWithInternalRestart) {
874 SKIP_TEST_IF_NOT(requirements_satisfied());
875 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
876 return;
877 }
878 MockAudioTransport mock(TransportType::kPlay);
879 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
880 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
881 .Times(AtLeast(kNumCallbacks));
882 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
883 StartPlayout();
884 event()->Wait(kTestTimeOutInMilliseconds);
885 EXPECT_TRUE(audio_device()->Playing());
886 // Restart playout but without stopping the internal audio thread.
887 // This procedure uses a non-public test API and it emulates what happens
888 // inside the ADM when e.g. a device is removed.
889 EXPECT_EQ(0, audio_device()->RestartPlayoutInternally());
890
891 // Run basic tests of public APIs while a restart attempt is active.
892 // These calls should now be very thin and not trigger any new actions.
893 EXPECT_EQ(-1, audio_device()->StopPlayout());
894 EXPECT_TRUE(audio_device()->Playing());
895 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
896 EXPECT_EQ(0, audio_device()->InitPlayout());
897 EXPECT_EQ(0, audio_device()->StartPlayout());
898
899 // Wait until audio has restarted and a new sequence of audio callbacks
900 // becomes active.
901 // TODO(henrika): is it possible to verify that the internal state transition
902 // is Stop->Init->Start?
903 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
904 mock.ResetCallbackCounters();
905 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
906 .Times(AtLeast(kNumCallbacks));
907 event()->Wait(kTestTimeOutInMilliseconds);
908 EXPECT_TRUE(audio_device()->Playing());
909 // Stop playout and the audio thread after successful internal restart.
910 StopPlayout();
911}
912
913// Tests Start/Stop recording followed by a second session (emulates a restart
914// triggered by an internal callback e.g. corresponding to a device switch).
915// Note that, internal restart is only supported in combination with the latest
916// Windows ADM.
917TEST_P(AudioDeviceTest, StartStopRecordingWithInternalRestart) {
918 SKIP_TEST_IF_NOT(requirements_satisfied());
919 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
920 return;
921 }
922 MockAudioTransport mock(TransportType::kRecord);
923 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
924 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
925 false, _))
926 .Times(AtLeast(kNumCallbacks));
927 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
928 StartRecording();
929 event()->Wait(kTestTimeOutInMilliseconds);
930 EXPECT_TRUE(audio_device()->Recording());
931 // Restart recording but without stopping the internal audio thread.
932 // This procedure uses a non-public test API and it emulates what happens
933 // inside the ADM when e.g. a device is removed.
934 EXPECT_EQ(0, audio_device()->RestartRecordingInternally());
935
936 // Run basic tests of public APIs while a restart attempt is active.
937 // These calls should now be very thin and not trigger any new actions.
938 EXPECT_EQ(-1, audio_device()->StopRecording());
939 EXPECT_TRUE(audio_device()->Recording());
940 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
941 EXPECT_EQ(0, audio_device()->InitRecording());
942 EXPECT_EQ(0, audio_device()->StartRecording());
943
944 // Wait until audio has restarted and a new sequence of audio callbacks
945 // becomes active.
946 // TODO(henrika): is it possible to verify that the internal state transition
947 // is Stop->Init->Start?
948 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
949 mock.ResetCallbackCounters();
950 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
951 false, _))
952 .Times(AtLeast(kNumCallbacks));
953 event()->Wait(kTestTimeOutInMilliseconds);
954 EXPECT_TRUE(audio_device()->Recording());
955 // Stop recording and the audio thread after successful internal restart.
956 StopRecording();
957}
958#endif // #ifdef WEBRTC_WIN
959
henrikaf2f91fa2017-03-17 04:26:22 -0700960// Start playout and verify that the native audio layer starts asking for real
961// audio samples to play out using the NeedMorePlayData() callback.
962// Note that we can't add expectations on audio parameters in EXPECT_CALL
963// since parameter are not provided in the each callback. We therefore test and
964// verify the parameters in the fake audio transport implementation instead.
henrikaec9c7452018-06-08 16:10:03 +0200965TEST_P(AudioDeviceTest, StartPlayoutVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700966 SKIP_TEST_IF_NOT(requirements_satisfied());
967 MockAudioTransport mock(TransportType::kPlay);
henrikae24991d2017-04-06 01:14:23 -0700968 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700969 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
970 .Times(AtLeast(kNumCallbacks));
971 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
972 StartPlayout();
973 event()->Wait(kTestTimeOutInMilliseconds);
974 StopPlayout();
975}
976
977// Start recording and verify that the native audio layer starts providing real
978// audio samples using the RecordedDataIsAvailable() callback.
henrikaec9c7452018-06-08 16:10:03 +0200979TEST_P(AudioDeviceTest, StartRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700980 SKIP_TEST_IF_NOT(requirements_satisfied());
981 MockAudioTransport mock(TransportType::kRecord);
henrikae24991d2017-04-06 01:14:23 -0700982 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700983 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
984 false, _))
985 .Times(AtLeast(kNumCallbacks));
986 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
987 StartRecording();
988 event()->Wait(kTestTimeOutInMilliseconds);
989 StopRecording();
990}
991
992// Start playout and recording (full-duplex audio) and verify that audio is
993// active in both directions.
henrikaec9c7452018-06-08 16:10:03 +0200994TEST_P(AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700995 SKIP_TEST_IF_NOT(requirements_satisfied());
996 MockAudioTransport mock(TransportType::kPlayAndRecord);
henrikae24991d2017-04-06 01:14:23 -0700997 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700998 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
999 .Times(AtLeast(kNumCallbacks));
1000 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
1001 false, _))
1002 .Times(AtLeast(kNumCallbacks));
1003 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1004 StartPlayout();
1005 StartRecording();
1006 event()->Wait(kTestTimeOutInMilliseconds);
1007 StopRecording();
1008 StopPlayout();
1009}
1010
henrikae24991d2017-04-06 01:14:23 -07001011// Start playout and recording and store recorded data in an intermediate FIFO
1012// buffer from which the playout side then reads its samples in the same order
1013// as they were stored. Under ideal circumstances, a callback sequence would
1014// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
1015// means 'packet played'. Under such conditions, the FIFO would contain max 1,
1016// with an average somewhere in (0,1) depending on how long the packets are
1017// buffered. However, under more realistic conditions, the size
1018// of the FIFO will vary more due to an unbalance between the two sides.
1019// This test tries to verify that the device maintains a balanced callback-
1020// sequence by running in loopback for a few seconds while measuring the size
1021// (max and average) of the FIFO. The size of the FIFO is increased by the
1022// recording side and decreased by the playout side.
henrikaec9c7452018-06-08 16:10:03 +02001023TEST_P(AudioDeviceTest, RunPlayoutAndRecordingInFullDuplex) {
henrikae24991d2017-04-06 01:14:23 -07001024 SKIP_TEST_IF_NOT(requirements_satisfied());
1025 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1026 FifoAudioStream audio_stream;
1027 mock.HandleCallbacks(event(), &audio_stream,
1028 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
1029 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001030 // Run both sides using the same channel configuration to avoid conversions
1031 // between mono/stereo while running in full duplex mode. Also, some devices
1032 // (mainly on Windows) do not support mono.
1033 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1034 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrikae24991d2017-04-06 01:14:23 -07001035 StartPlayout();
1036 StartRecording();
henrika714e5cd2017-04-20 08:03:11 -07001037 event()->Wait(static_cast<int>(
1038 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec)));
henrikae24991d2017-04-06 01:14:23 -07001039 StopRecording();
1040 StopPlayout();
1041 // This thresholds is set rather high to accommodate differences in hardware
1042 // in several devices. The main idea is to capture cases where a very large
henrikab6ca7212017-10-06 12:47:52 +02001043 // latency is built up. See http://bugs.webrtc.org/7744 for examples on
1044 // bots where relatively large average latencies can happen.
1045 EXPECT_LE(audio_stream.average_size(), 25u);
henrikae24991d2017-04-06 01:14:23 -07001046 PRINT("\n");
1047}
1048
henrika5b6afc02018-09-05 14:34:40 +02001049// Runs audio in full duplex until user hits Enter. Intended as a manual test
1050// to ensure that the audio quality is good and that real device switches works
1051// as intended.
1052TEST_P(AudioDeviceTest,
1053 DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey) {
1054 SKIP_TEST_IF_NOT(requirements_satisfied());
1055 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
1056 return;
1057 }
1058 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1059 FifoAudioStream audio_stream;
1060 mock.HandleCallbacks(&audio_stream);
1061 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1062 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1063 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
1064 // Ensure that the sample rate for both directions are identical so that we
1065 // always can listen to our own voice. Will lead to rate conversion (and
1066 // higher latency) if the native sample rate is not 48kHz.
1067 EXPECT_EQ(0, audio_device()->SetPlayoutSampleRate(48000));
1068 EXPECT_EQ(0, audio_device()->SetRecordingSampleRate(48000));
1069 StartPlayout();
1070 StartRecording();
1071 do {
1072 PRINT("Loopback audio is active at 48kHz. Press Enter to stop.\n");
1073 } while (getchar() != '\n');
1074 StopRecording();
1075 StopPlayout();
1076}
1077
henrika714e5cd2017-04-20 08:03:11 -07001078// Measures loopback latency and reports the min, max and average values for
1079// a full duplex audio session.
1080// The latency is measured like so:
1081// - Insert impulses periodically on the output side.
1082// - Detect the impulses on the input side.
1083// - Measure the time difference between the transmit time and receive time.
1084// - Store time differences in a vector and calculate min, max and average.
1085// This test needs the '--gtest_also_run_disabled_tests' flag to run and also
1086// some sort of audio feedback loop. E.g. a headset where the mic is placed
1087// close to the speaker to ensure highest possible echo. It is also recommended
1088// to run the test at highest possible output volume.
henrikaec9c7452018-06-08 16:10:03 +02001089TEST_P(AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
henrika714e5cd2017-04-20 08:03:11 -07001090 SKIP_TEST_IF_NOT(requirements_satisfied());
1091 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1092 LatencyAudioStream audio_stream;
1093 mock.HandleCallbacks(event(), &audio_stream,
1094 kMeasureLatencyTimeInSec * kNumCallbacksPerSecond);
1095 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001096 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1097 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrika714e5cd2017-04-20 08:03:11 -07001098 StartPlayout();
1099 StartRecording();
1100 event()->Wait(static_cast<int>(
1101 std::max(kTestTimeOutInMilliseconds, 1000 * kMeasureLatencyTimeInSec)));
1102 StopRecording();
1103 StopPlayout();
henrikac7d93582018-09-14 15:37:34 +02001104 // Verify that a sufficient number of transmitted impulses are detected.
1105 EXPECT_GE(audio_stream.num_latency_values(),
henrika714e5cd2017-04-20 08:03:11 -07001106 static_cast<size_t>(
henrikac7d93582018-09-14 15:37:34 +02001107 kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 2));
henrika714e5cd2017-04-20 08:03:11 -07001108 // Print out min, max and average delay values for debugging purposes.
1109 audio_stream.PrintResults();
1110}
1111
henrikaec9c7452018-06-08 16:10:03 +02001112#ifdef WEBRTC_WIN
1113// Test two different audio layers (or rather two different Core Audio
1114// implementations) for Windows.
Mirko Bonadeic84f6612019-01-31 12:20:57 +01001115INSTANTIATE_TEST_SUITE_P(
henrikaec9c7452018-06-08 16:10:03 +02001116 AudioLayerWin,
1117 AudioDeviceTest,
1118 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio,
1119 AudioDeviceModule::kWindowsCoreAudio2));
1120#else
1121// For all platforms but Windows, only test the default audio layer.
Mirko Bonadeic84f6612019-01-31 12:20:57 +01001122INSTANTIATE_TEST_SUITE_P(
henrikaec9c7452018-06-08 16:10:03 +02001123 AudioLayer,
1124 AudioDeviceTest,
1125 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio));
1126#endif
1127
henrikaf2f91fa2017-03-17 04:26:22 -07001128} // namespace webrtc