blob: f0bf9fd8ced1be7cc33bcee360c9c172b3f5b29a [file] [log] [blame]
henrikaf2f91fa2017-03-17 04:26:22 -07001/*
2 * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Jonas Olssona4d87372019-07-05 19:08:33 +020011#include "modules/audio_device/include/audio_device.h"
12
henrika714e5cd2017-04-20 08:03:11 -070013#include <algorithm>
henrikaf2f91fa2017-03-17 04:26:22 -070014#include <cstring>
henrikaec9c7452018-06-08 16:10:03 +020015#include <memory>
henrika714e5cd2017-04-20 08:03:11 -070016#include <numeric>
henrikaf2f91fa2017-03-17 04:26:22 -070017
Steve Anton40d55332019-01-07 10:21:47 -080018#include "absl/memory/memory.h"
Danil Chapovalov196100e2018-06-21 10:17:24 +020019#include "absl/types/optional.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "api/array_view.h"
Mirko Bonadeid9708072019-01-25 20:26:48 +010021#include "api/scoped_refptr.h"
Danil Chapovalov1c41be62019-04-01 09:16:12 +020022#include "api/task_queue/default_task_queue_factory.h"
23#include "api/task_queue/task_queue_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "modules/audio_device/audio_device_impl.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/audio_device/include/mock_audio_transport.h"
26#include "rtc_base/buffer.h"
Steve Anton10542f22019-01-11 09:11:00 -080027#include "rtc_base/critical_section.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/event.h"
29#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010030#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "rtc_base/race_checker.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/thread_annotations.h"
33#include "rtc_base/thread_checker.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "rtc_base/time_utils.h"
henrika5b6afc02018-09-05 14:34:40 +020035#include "system_wrappers/include/sleep.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "test/gmock.h"
37#include "test/gtest.h"
henrikaec9c7452018-06-08 16:10:03 +020038#ifdef WEBRTC_WIN
39#include "modules/audio_device/include/audio_device_factory.h"
40#include "modules/audio_device/win/core_audio_utility_win.h"
41#endif
henrikaf2f91fa2017-03-17 04:26:22 -070042
43using ::testing::_;
44using ::testing::AtLeast;
45using ::testing::Ge;
46using ::testing::Invoke;
Jonas Olssona4d87372019-07-05 19:08:33 +020047using ::testing::Mock;
henrikaf2f91fa2017-03-17 04:26:22 -070048using ::testing::NiceMock;
49using ::testing::NotNull;
50
51namespace webrtc {
52namespace {
53
henrika5773ad32018-09-21 14:53:10 +020054// Using a #define for AUDIO_DEVICE since we will call *different* versions of
55// the ADM functions, depending on the ID type.
56#if defined(WEBRTC_WIN)
57#define AUDIO_DEVICE_ID (AudioDeviceModule::WindowsDeviceType::kDefaultDevice)
58#else
59#define AUDIO_DEVICE_ID (0u)
60#endif // defined(WEBRTC_WIN)
61
henrikae24991d2017-04-06 01:14:23 -070062// #define ENABLE_DEBUG_PRINTF
63#ifdef ENABLE_DEBUG_PRINTF
64#define PRINTD(...) fprintf(stderr, __VA_ARGS__);
65#else
66#define PRINTD(...) ((void)0)
67#endif
68#define PRINT(...) fprintf(stderr, __VA_ARGS__);
69
henrikaf2f91fa2017-03-17 04:26:22 -070070// Don't run these tests in combination with sanitizers.
Sami Kalliomäkidefb7172018-09-25 13:12:05 +020071// TODO(webrtc:9778): Re-enable on THREAD_SANITIZER?
Yves Gereyee0550c2019-07-17 21:41:59 +020072#if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
73 defined(THREAD_SANITIZER)
henrikaf2f91fa2017-03-17 04:26:22 -070074#define SKIP_TEST_IF_NOT(requirements_satisfied) \
75 do { \
Yves Gereyee0550c2019-07-17 21:41:59 +020076 GTEST_SKIP() << "Skipped for sanitizers."; \
henrikaf2f91fa2017-03-17 04:26:22 -070077 } while (false)
78#else
79// Or if other audio-related requirements are not met.
Yves Gereyee0550c2019-07-17 21:41:59 +020080#define SKIP_TEST_IF_NOT(requirements_satisfied) \
81 do { \
82 if (!requirements_satisfied) { \
83 GTEST_SKIP() << "Skipped. No audio device found."; \
84 } \
henrikaf2f91fa2017-03-17 04:26:22 -070085 } while (false)
86#endif
87
88// Number of callbacks (input or output) the tests waits for before we set
89// an event indicating that the test was OK.
henrikae24991d2017-04-06 01:14:23 -070090static constexpr size_t kNumCallbacks = 10;
henrikaf2f91fa2017-03-17 04:26:22 -070091// Max amount of time we wait for an event to be set while counting callbacks.
henrika714e5cd2017-04-20 08:03:11 -070092static constexpr size_t kTestTimeOutInMilliseconds = 10 * 1000;
henrikae24991d2017-04-06 01:14:23 -070093// Average number of audio callbacks per second assuming 10ms packet size.
94static constexpr size_t kNumCallbacksPerSecond = 100;
95// Run the full-duplex test during this time (unit is in seconds).
henrika714e5cd2017-04-20 08:03:11 -070096static constexpr size_t kFullDuplexTimeInSec = 5;
97// Length of round-trip latency measurements. Number of deteced impulses
98// shall be kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 1 since the
99// last transmitted pulse is not used.
100static constexpr size_t kMeasureLatencyTimeInSec = 10;
101// Sets the number of impulses per second in the latency test.
102static constexpr size_t kImpulseFrequencyInHz = 1;
103// Utilized in round-trip latency measurements to avoid capturing noise samples.
104static constexpr int kImpulseThreshold = 1000;
henrikaf2f91fa2017-03-17 04:26:22 -0700105
106enum class TransportType {
107 kInvalid,
108 kPlay,
109 kRecord,
110 kPlayAndRecord,
111};
henrikae24991d2017-04-06 01:14:23 -0700112
113// Interface for processing the audio stream. Real implementations can e.g.
114// run audio in loopback, read audio from a file or perform latency
115// measurements.
116class AudioStream {
117 public:
henrikaeb98c722018-03-20 12:54:07 +0100118 virtual void Write(rtc::ArrayView<const int16_t> source) = 0;
119 virtual void Read(rtc::ArrayView<int16_t> destination) = 0;
henrikae24991d2017-04-06 01:14:23 -0700120
121 virtual ~AudioStream() = default;
122};
123
henrika714e5cd2017-04-20 08:03:11 -0700124// Converts index corresponding to position within a 10ms buffer into a
125// delay value in milliseconds.
126// Example: index=240, frames_per_10ms_buffer=480 => 5ms as output.
127int IndexToMilliseconds(size_t index, size_t frames_per_10ms_buffer) {
128 return rtc::checked_cast<int>(
129 10.0 * (static_cast<double>(index) / frames_per_10ms_buffer) + 0.5);
130}
131
henrikaf2f91fa2017-03-17 04:26:22 -0700132} // namespace
133
henrikae24991d2017-04-06 01:14:23 -0700134// Simple first in first out (FIFO) class that wraps a list of 16-bit audio
135// buffers of fixed size and allows Write and Read operations. The idea is to
136// store recorded audio buffers (using Write) and then read (using Read) these
137// stored buffers with as short delay as possible when the audio layer needs
138// data to play out. The number of buffers in the FIFO will stabilize under
139// normal conditions since there will be a balance between Write and Read calls.
140// The container is a std::list container and access is protected with a lock
141// since both sides (playout and recording) are driven by its own thread.
142// Note that, we know by design that the size of the audio buffer will not
henrikac7d93582018-09-14 15:37:34 +0200143// change over time and that both sides will in most cases use the same size.
henrikae24991d2017-04-06 01:14:23 -0700144class FifoAudioStream : public AudioStream {
145 public:
henrikaeb98c722018-03-20 12:54:07 +0100146 void Write(rtc::ArrayView<const int16_t> source) override {
henrikae24991d2017-04-06 01:14:23 -0700147 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
148 const size_t size = [&] {
149 rtc::CritScope lock(&lock_);
150 fifo_.push_back(Buffer16(source.data(), source.size()));
151 return fifo_.size();
152 }();
153 if (size > max_size_) {
154 max_size_ = size;
155 }
156 // Add marker once per second to signal that audio is active.
157 if (write_count_++ % 100 == 0) {
henrikad8c6ec42019-07-18 15:17:28 +0200158 PRINTD(".");
henrikae24991d2017-04-06 01:14:23 -0700159 }
160 written_elements_ += size;
161 }
162
henrikaeb98c722018-03-20 12:54:07 +0100163 void Read(rtc::ArrayView<int16_t> destination) override {
henrikae24991d2017-04-06 01:14:23 -0700164 rtc::CritScope lock(&lock_);
165 if (fifo_.empty()) {
166 std::fill(destination.begin(), destination.end(), 0);
167 } else {
168 const Buffer16& buffer = fifo_.front();
henrikac7d93582018-09-14 15:37:34 +0200169 if (buffer.size() == destination.size()) {
170 // Default case where input and output uses same sample rate and
171 // channel configuration. No conversion is needed.
172 std::copy(buffer.begin(), buffer.end(), destination.begin());
173 } else if (destination.size() == 2 * buffer.size()) {
174 // Recorded input signal in |buffer| is in mono. Do channel upmix to
175 // match stereo output (1 -> 2).
176 for (size_t i = 0; i < buffer.size(); ++i) {
177 destination[2 * i] = buffer[i];
178 destination[2 * i + 1] = buffer[i];
179 }
180 } else if (buffer.size() == 2 * destination.size()) {
181 // Recorded input signal in |buffer| is in stereo. Do channel downmix
182 // to match mono output (2 -> 1).
183 for (size_t i = 0; i < destination.size(); ++i) {
184 destination[i] =
185 (static_cast<int32_t>(buffer[2 * i]) + buffer[2 * i + 1]) / 2;
186 }
187 } else {
188 RTC_NOTREACHED() << "Required conversion is not support";
189 }
henrikae24991d2017-04-06 01:14:23 -0700190 fifo_.pop_front();
191 }
192 }
193
194 size_t size() const {
195 rtc::CritScope lock(&lock_);
196 return fifo_.size();
197 }
198
199 size_t max_size() const {
200 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
201 return max_size_;
202 }
203
204 size_t average_size() const {
205 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
206 return 0.5 + static_cast<float>(written_elements_ / write_count_);
207 }
208
209 using Buffer16 = rtc::BufferT<int16_t>;
210
211 rtc::CriticalSection lock_;
212 rtc::RaceChecker race_checker_;
213
danilchap56359be2017-09-07 07:53:45 -0700214 std::list<Buffer16> fifo_ RTC_GUARDED_BY(lock_);
215 size_t write_count_ RTC_GUARDED_BY(race_checker_) = 0;
216 size_t max_size_ RTC_GUARDED_BY(race_checker_) = 0;
217 size_t written_elements_ RTC_GUARDED_BY(race_checker_) = 0;
henrikae24991d2017-04-06 01:14:23 -0700218};
219
henrika714e5cd2017-04-20 08:03:11 -0700220// Inserts periodic impulses and measures the latency between the time of
221// transmission and time of receiving the same impulse.
222class LatencyAudioStream : public AudioStream {
223 public:
224 LatencyAudioStream() {
225 // Delay thread checkers from being initialized until first callback from
226 // respective thread.
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200227 read_thread_checker_.Detach();
228 write_thread_checker_.Detach();
henrika714e5cd2017-04-20 08:03:11 -0700229 }
230
231 // Insert periodic impulses in first two samples of |destination|.
henrikaeb98c722018-03-20 12:54:07 +0100232 void Read(rtc::ArrayView<int16_t> destination) override {
henrika714e5cd2017-04-20 08:03:11 -0700233 RTC_DCHECK_RUN_ON(&read_thread_checker_);
henrika714e5cd2017-04-20 08:03:11 -0700234 if (read_count_ == 0) {
235 PRINT("[");
236 }
237 read_count_++;
238 std::fill(destination.begin(), destination.end(), 0);
239 if (read_count_ % (kNumCallbacksPerSecond / kImpulseFrequencyInHz) == 0) {
240 PRINT(".");
241 {
242 rtc::CritScope lock(&lock_);
243 if (!pulse_time_) {
Oskar Sundbom6ad9f262017-11-16 10:53:39 +0100244 pulse_time_ = rtc::TimeMillis();
henrika714e5cd2017-04-20 08:03:11 -0700245 }
246 }
247 constexpr int16_t impulse = std::numeric_limits<int16_t>::max();
248 std::fill_n(destination.begin(), 2, impulse);
249 }
250 }
251
252 // Detect received impulses in |source|, derive time between transmission and
253 // detection and add the calculated delay to list of latencies.
henrikaeb98c722018-03-20 12:54:07 +0100254 void Write(rtc::ArrayView<const int16_t> source) override {
henrika714e5cd2017-04-20 08:03:11 -0700255 RTC_DCHECK_RUN_ON(&write_thread_checker_);
256 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
257 rtc::CritScope lock(&lock_);
258 write_count_++;
259 if (!pulse_time_) {
260 // Avoid detection of new impulse response until a new impulse has
261 // been transmitted (sets |pulse_time_| to value larger than zero).
262 return;
263 }
264 // Find index (element position in vector) of the max element.
265 const size_t index_of_max =
266 std::max_element(source.begin(), source.end()) - source.begin();
267 // Derive time between transmitted pulse and received pulse if the level
268 // is high enough (removes noise).
269 const size_t max = source[index_of_max];
270 if (max > kImpulseThreshold) {
271 PRINTD("(%zu, %zu)", max, index_of_max);
272 int64_t now_time = rtc::TimeMillis();
273 int extra_delay = IndexToMilliseconds(index_of_max, source.size());
274 PRINTD("[%d]", rtc::checked_cast<int>(now_time - pulse_time_));
275 PRINTD("[%d]", extra_delay);
276 // Total latency is the difference between transmit time and detection
277 // tome plus the extra delay within the buffer in which we detected the
278 // received impulse. It is transmitted at sample 0 but can be received
279 // at sample N where N > 0. The term |extra_delay| accounts for N and it
280 // is a value between 0 and 10ms.
281 latencies_.push_back(now_time - *pulse_time_ + extra_delay);
282 pulse_time_.reset();
283 } else {
284 PRINTD("-");
285 }
286 }
287
288 size_t num_latency_values() const {
289 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
290 return latencies_.size();
291 }
292
293 int min_latency() const {
294 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
295 if (latencies_.empty())
296 return 0;
297 return *std::min_element(latencies_.begin(), latencies_.end());
298 }
299
300 int max_latency() const {
301 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
302 if (latencies_.empty())
303 return 0;
304 return *std::max_element(latencies_.begin(), latencies_.end());
305 }
306
307 int average_latency() const {
308 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
309 if (latencies_.empty())
310 return 0;
311 return 0.5 + static_cast<double>(
312 std::accumulate(latencies_.begin(), latencies_.end(), 0)) /
313 latencies_.size();
314 }
315
316 void PrintResults() const {
317 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
318 PRINT("] ");
319 for (auto it = latencies_.begin(); it != latencies_.end(); ++it) {
320 PRINTD("%d ", *it);
321 }
322 PRINT("\n");
323 PRINT("[..........] [min, max, avg]=[%d, %d, %d] ms\n", min_latency(),
324 max_latency(), average_latency());
325 }
326
327 rtc::CriticalSection lock_;
328 rtc::RaceChecker race_checker_;
329 rtc::ThreadChecker read_thread_checker_;
330 rtc::ThreadChecker write_thread_checker_;
331
Danil Chapovalov196100e2018-06-21 10:17:24 +0200332 absl::optional<int64_t> pulse_time_ RTC_GUARDED_BY(lock_);
danilchap56359be2017-09-07 07:53:45 -0700333 std::vector<int> latencies_ RTC_GUARDED_BY(race_checker_);
Niels Möller1e062892018-02-07 10:18:32 +0100334 size_t read_count_ RTC_GUARDED_BY(read_thread_checker_) = 0;
335 size_t write_count_ RTC_GUARDED_BY(write_thread_checker_) = 0;
henrika714e5cd2017-04-20 08:03:11 -0700336};
337
henrikaf2f91fa2017-03-17 04:26:22 -0700338// Mocks the AudioTransport object and proxies actions for the two callbacks
339// (RecordedDataIsAvailable and NeedMorePlayData) to different implementations
340// of AudioStreamInterface.
341class MockAudioTransport : public test::MockAudioTransport {
342 public:
343 explicit MockAudioTransport(TransportType type) : type_(type) {}
344 ~MockAudioTransport() {}
345
346 // Set default actions of the mock object. We are delegating to fake
347 // implementation where the number of callbacks is counted and an event
348 // is set after a certain number of callbacks. Audio parameters are also
349 // checked.
henrikae24991d2017-04-06 01:14:23 -0700350 void HandleCallbacks(rtc::Event* event,
351 AudioStream* audio_stream,
352 int num_callbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700353 event_ = event;
henrikae24991d2017-04-06 01:14:23 -0700354 audio_stream_ = audio_stream;
henrikaf2f91fa2017-03-17 04:26:22 -0700355 num_callbacks_ = num_callbacks;
356 if (play_mode()) {
357 ON_CALL(*this, NeedMorePlayData(_, _, _, _, _, _, _, _))
358 .WillByDefault(
359 Invoke(this, &MockAudioTransport::RealNeedMorePlayData));
360 }
361 if (rec_mode()) {
362 ON_CALL(*this, RecordedDataIsAvailable(_, _, _, _, _, _, _, _, _, _))
363 .WillByDefault(
364 Invoke(this, &MockAudioTransport::RealRecordedDataIsAvailable));
365 }
366 }
367
henrika5b6afc02018-09-05 14:34:40 +0200368 // Special constructor used in manual tests where the user wants to run audio
369 // until e.g. a keyboard key is pressed. The event flag is set to nullptr by
370 // default since it is up to the user to stop the test. See e.g.
371 // DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey().
372 void HandleCallbacks(AudioStream* audio_stream) {
373 HandleCallbacks(nullptr, audio_stream, 0);
374 }
375
henrikaf2f91fa2017-03-17 04:26:22 -0700376 int32_t RealRecordedDataIsAvailable(const void* audio_buffer,
377 const size_t samples_per_channel,
378 const size_t bytes_per_frame,
379 const size_t channels,
380 const uint32_t sample_rate,
381 const uint32_t total_delay_ms,
382 const int32_t clock_drift,
383 const uint32_t current_mic_level,
384 const bool typing_status,
385 uint32_t& new_mic_level) {
386 EXPECT_TRUE(rec_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700387 // Store audio parameters once in the first callback. For all other
388 // callbacks, verify that the provided audio parameters are maintained and
389 // that each callback corresponds to 10ms for any given sample rate.
390 if (!record_parameters_.is_complete()) {
391 record_parameters_.reset(sample_rate, channels, samples_per_channel);
392 } else {
393 EXPECT_EQ(samples_per_channel, record_parameters_.frames_per_buffer());
394 EXPECT_EQ(bytes_per_frame, record_parameters_.GetBytesPerFrame());
395 EXPECT_EQ(channels, record_parameters_.channels());
396 EXPECT_EQ(static_cast<int>(sample_rate),
397 record_parameters_.sample_rate());
398 EXPECT_EQ(samples_per_channel,
399 record_parameters_.frames_per_10ms_buffer());
400 }
henrika78e0ac12018-09-27 16:23:21 +0200401 {
402 rtc::CritScope lock(&lock_);
403 rec_count_++;
404 }
henrikae24991d2017-04-06 01:14:23 -0700405 // Write audio data to audio stream object if one has been injected.
406 if (audio_stream_) {
407 audio_stream_->Write(
408 rtc::MakeArrayView(static_cast<const int16_t*>(audio_buffer),
henrikaeb98c722018-03-20 12:54:07 +0100409 samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700410 }
henrikaf2f91fa2017-03-17 04:26:22 -0700411 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200412 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700413 event_->Set();
414 }
415 return 0;
416 }
417
418 int32_t RealNeedMorePlayData(const size_t samples_per_channel,
419 const size_t bytes_per_frame,
420 const size_t channels,
421 const uint32_t sample_rate,
422 void* audio_buffer,
henrikaeb98c722018-03-20 12:54:07 +0100423 size_t& samples_out,
henrikaf2f91fa2017-03-17 04:26:22 -0700424 int64_t* elapsed_time_ms,
425 int64_t* ntp_time_ms) {
426 EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700427 // Store audio parameters once in the first callback. For all other
428 // callbacks, verify that the provided audio parameters are maintained and
429 // that each callback corresponds to 10ms for any given sample rate.
430 if (!playout_parameters_.is_complete()) {
431 playout_parameters_.reset(sample_rate, channels, samples_per_channel);
432 } else {
433 EXPECT_EQ(samples_per_channel, playout_parameters_.frames_per_buffer());
434 EXPECT_EQ(bytes_per_frame, playout_parameters_.GetBytesPerFrame());
435 EXPECT_EQ(channels, playout_parameters_.channels());
436 EXPECT_EQ(static_cast<int>(sample_rate),
437 playout_parameters_.sample_rate());
438 EXPECT_EQ(samples_per_channel,
439 playout_parameters_.frames_per_10ms_buffer());
440 }
henrika78e0ac12018-09-27 16:23:21 +0200441 {
442 rtc::CritScope lock(&lock_);
443 play_count_++;
444 }
henrikaeb98c722018-03-20 12:54:07 +0100445 samples_out = samples_per_channel * channels;
henrikae24991d2017-04-06 01:14:23 -0700446 // Read audio data from audio stream object if one has been injected.
447 if (audio_stream_) {
henrikaeb98c722018-03-20 12:54:07 +0100448 audio_stream_->Read(rtc::MakeArrayView(
449 static_cast<int16_t*>(audio_buffer), samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700450 } else {
451 // Fill the audio buffer with zeros to avoid disturbing audio.
452 const size_t num_bytes = samples_per_channel * bytes_per_frame;
453 std::memset(audio_buffer, 0, num_bytes);
454 }
henrikaf2f91fa2017-03-17 04:26:22 -0700455 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200456 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700457 event_->Set();
458 }
459 return 0;
460 }
461
462 bool ReceivedEnoughCallbacks() {
463 bool recording_done = false;
464 if (rec_mode()) {
henrika78e0ac12018-09-27 16:23:21 +0200465 rtc::CritScope lock(&lock_);
henrikaf2f91fa2017-03-17 04:26:22 -0700466 recording_done = rec_count_ >= num_callbacks_;
467 } else {
468 recording_done = true;
469 }
470 bool playout_done = false;
471 if (play_mode()) {
henrika78e0ac12018-09-27 16:23:21 +0200472 rtc::CritScope lock(&lock_);
henrikaf2f91fa2017-03-17 04:26:22 -0700473 playout_done = play_count_ >= num_callbacks_;
474 } else {
475 playout_done = true;
476 }
477 return recording_done && playout_done;
478 }
479
480 bool play_mode() const {
481 return type_ == TransportType::kPlay ||
482 type_ == TransportType::kPlayAndRecord;
483 }
484
485 bool rec_mode() const {
486 return type_ == TransportType::kRecord ||
487 type_ == TransportType::kPlayAndRecord;
488 }
489
henrika5b6afc02018-09-05 14:34:40 +0200490 void ResetCallbackCounters() {
henrika78e0ac12018-09-27 16:23:21 +0200491 rtc::CritScope lock(&lock_);
henrika5b6afc02018-09-05 14:34:40 +0200492 if (play_mode()) {
493 play_count_ = 0;
494 }
495 if (rec_mode()) {
496 rec_count_ = 0;
497 }
498 }
499
henrikaf2f91fa2017-03-17 04:26:22 -0700500 private:
henrika78e0ac12018-09-27 16:23:21 +0200501 rtc::CriticalSection lock_;
henrikaf2f91fa2017-03-17 04:26:22 -0700502 TransportType type_ = TransportType::kInvalid;
503 rtc::Event* event_ = nullptr;
henrikae24991d2017-04-06 01:14:23 -0700504 AudioStream* audio_stream_ = nullptr;
henrikaf2f91fa2017-03-17 04:26:22 -0700505 size_t num_callbacks_ = 0;
henrika78e0ac12018-09-27 16:23:21 +0200506 size_t play_count_ RTC_GUARDED_BY(lock_) = 0;
507 size_t rec_count_ RTC_GUARDED_BY(lock_) = 0;
henrikaf2f91fa2017-03-17 04:26:22 -0700508 AudioParameters playout_parameters_;
509 AudioParameters record_parameters_;
510};
511
512// AudioDeviceTest test fixture.
henrikaec9c7452018-06-08 16:10:03 +0200513class AudioDeviceTest
514 : public ::testing::TestWithParam<webrtc::AudioDeviceModule::AudioLayer> {
henrikaf2f91fa2017-03-17 04:26:22 -0700515 protected:
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200516 AudioDeviceTest()
517 : audio_layer_(GetParam()),
518 task_queue_factory_(CreateDefaultTaskQueueFactory()) {
Sami Kalliomäkia3b9b272018-09-25 15:03:43 +0200519// TODO(webrtc:9778): Re-enable on THREAD_SANITIZER?
Joachim Bauch5d2bb362017-12-20 21:19:49 +0100520#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \
Sami Kalliomäkia3b9b272018-09-25 15:03:43 +0200521 !defined(WEBRTC_DUMMY_AUDIO_BUILD) && !defined(THREAD_SANITIZER)
henrikaf2f91fa2017-03-17 04:26:22 -0700522 rtc::LogMessage::LogToDebug(rtc::LS_INFO);
523 // Add extra logging fields here if needed for debugging.
henrikaec9c7452018-06-08 16:10:03 +0200524 rtc::LogMessage::LogTimestamps();
525 rtc::LogMessage::LogThreads();
526 audio_device_ = CreateAudioDevice();
henrikaf2f91fa2017-03-17 04:26:22 -0700527 EXPECT_NE(audio_device_.get(), nullptr);
528 AudioDeviceModule::AudioLayer audio_layer;
maxmorin33bf69a2017-03-23 04:06:53 -0700529 int got_platform_audio_layer =
530 audio_device_->ActiveAudioLayer(&audio_layer);
henrika919dc2e2017-10-12 14:24:55 +0200531 // First, ensure that a valid audio layer can be activated.
532 if (got_platform_audio_layer != 0) {
henrikaf2f91fa2017-03-17 04:26:22 -0700533 requirements_satisfied_ = false;
534 }
henrika919dc2e2017-10-12 14:24:55 +0200535 // Next, verify that the ADM can be initialized.
henrikaf2f91fa2017-03-17 04:26:22 -0700536 if (requirements_satisfied_) {
henrika919dc2e2017-10-12 14:24:55 +0200537 requirements_satisfied_ = (audio_device_->Init() == 0);
538 }
539 // Finally, ensure that at least one valid device exists in each direction.
540 if (requirements_satisfied_) {
henrikaf2f91fa2017-03-17 04:26:22 -0700541 const int16_t num_playout_devices = audio_device_->PlayoutDevices();
542 const int16_t num_record_devices = audio_device_->RecordingDevices();
543 requirements_satisfied_ =
544 num_playout_devices > 0 && num_record_devices > 0;
545 }
546#else
547 requirements_satisfied_ = false;
548#endif
549 if (requirements_satisfied_) {
henrika5773ad32018-09-21 14:53:10 +0200550 EXPECT_EQ(0, audio_device_->SetPlayoutDevice(AUDIO_DEVICE_ID));
henrikaf2f91fa2017-03-17 04:26:22 -0700551 EXPECT_EQ(0, audio_device_->InitSpeaker());
henrikaf2f91fa2017-03-17 04:26:22 -0700552 EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
553 EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
henrika5773ad32018-09-21 14:53:10 +0200554 EXPECT_EQ(0, audio_device_->SetRecordingDevice(AUDIO_DEVICE_ID));
555 EXPECT_EQ(0, audio_device_->InitMicrophone());
henrika0238ba82017-03-28 04:38:29 -0700556 // Avoid asking for input stereo support and always record in mono
557 // since asking can cause issues in combination with remote desktop.
558 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
559 // details.
560 EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
henrikaf2f91fa2017-03-17 04:26:22 -0700561 }
562 }
563
564 virtual ~AudioDeviceTest() {
565 if (audio_device_) {
566 EXPECT_EQ(0, audio_device_->Terminate());
567 }
568 }
569
570 bool requirements_satisfied() const { return requirements_satisfied_; }
571 rtc::Event* event() { return &event_; }
henrika5b6afc02018-09-05 14:34:40 +0200572 AudioDeviceModule::AudioLayer audio_layer() const { return audio_layer_; }
henrikaf2f91fa2017-03-17 04:26:22 -0700573
henrika5b6afc02018-09-05 14:34:40 +0200574 // AudioDeviceModuleForTest extends the default ADM interface with some extra
575 // test methods. Intended for usage in tests only and requires a unique
576 // factory method. See CreateAudioDevice() for details.
577 const rtc::scoped_refptr<AudioDeviceModuleForTest>& audio_device() const {
henrikaf2f91fa2017-03-17 04:26:22 -0700578 return audio_device_;
579 }
580
henrika5b6afc02018-09-05 14:34:40 +0200581 rtc::scoped_refptr<AudioDeviceModuleForTest> CreateAudioDevice() {
henrikaec9c7452018-06-08 16:10:03 +0200582 // Use the default factory for kPlatformDefaultAudio and a special factory
henrika5b6afc02018-09-05 14:34:40 +0200583 // CreateWindowsCoreAudioAudioDeviceModuleForTest() for kWindowsCoreAudio2.
henrikaec9c7452018-06-08 16:10:03 +0200584 // The value of |audio_layer_| is set at construction by GetParam() and two
585 // different layers are tested on Windows only.
586 if (audio_layer_ == AudioDeviceModule::kPlatformDefaultAudio) {
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200587 return AudioDeviceModule::CreateForTest(audio_layer_,
588 task_queue_factory_.get());
henrikaec9c7452018-06-08 16:10:03 +0200589 } else if (audio_layer_ == AudioDeviceModule::kWindowsCoreAudio2) {
590#ifdef WEBRTC_WIN
591 // We must initialize the COM library on a thread before we calling any of
592 // the library functions. All COM functions in the ADM will return
593 // CO_E_NOTINITIALIZED otherwise.
Karl Wiberg918f50c2018-07-05 11:40:33 +0200594 com_initializer_ = absl::make_unique<webrtc_win::ScopedCOMInitializer>(
henrikaec9c7452018-06-08 16:10:03 +0200595 webrtc_win::ScopedCOMInitializer::kMTA);
596 EXPECT_TRUE(com_initializer_->Succeeded());
597 EXPECT_TRUE(webrtc_win::core_audio_utility::IsSupported());
598 EXPECT_TRUE(webrtc_win::core_audio_utility::IsMMCSSSupported());
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200599 return CreateWindowsCoreAudioAudioDeviceModuleForTest(
henrikad8c6ec42019-07-18 15:17:28 +0200600 task_queue_factory_.get(), true);
henrikaec9c7452018-06-08 16:10:03 +0200601#else
602 return nullptr;
603#endif
604 } else {
605 return nullptr;
606 }
607 }
608
henrikaf2f91fa2017-03-17 04:26:22 -0700609 void StartPlayout() {
610 EXPECT_FALSE(audio_device()->Playing());
611 EXPECT_EQ(0, audio_device()->InitPlayout());
612 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
613 EXPECT_EQ(0, audio_device()->StartPlayout());
614 EXPECT_TRUE(audio_device()->Playing());
615 }
616
617 void StopPlayout() {
618 EXPECT_EQ(0, audio_device()->StopPlayout());
619 EXPECT_FALSE(audio_device()->Playing());
620 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
621 }
622
623 void StartRecording() {
624 EXPECT_FALSE(audio_device()->Recording());
625 EXPECT_EQ(0, audio_device()->InitRecording());
626 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
627 EXPECT_EQ(0, audio_device()->StartRecording());
628 EXPECT_TRUE(audio_device()->Recording());
629 }
630
631 void StopRecording() {
632 EXPECT_EQ(0, audio_device()->StopRecording());
633 EXPECT_FALSE(audio_device()->Recording());
634 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
635 }
636
henrikaec9c7452018-06-08 16:10:03 +0200637 bool NewWindowsAudioDeviceModuleIsUsed() {
638#ifdef WEBRTC_WIN
639 AudioDeviceModule::AudioLayer audio_layer;
640 EXPECT_EQ(0, audio_device()->ActiveAudioLayer(&audio_layer));
641 if (audio_layer == AudioDeviceModule::kWindowsCoreAudio2) {
642 // Default device is always added as first element in the list and the
643 // default communication device as the second element. Hence, the list
644 // contains two extra elements in this case.
645 return true;
646 }
647#endif
648 return false;
649 }
650
henrikaf2f91fa2017-03-17 04:26:22 -0700651 private:
henrikaec9c7452018-06-08 16:10:03 +0200652#ifdef WEBRTC_WIN
653 // Windows Core Audio based ADM needs to run on a COM initialized thread.
654 std::unique_ptr<webrtc_win::ScopedCOMInitializer> com_initializer_;
655#endif
656 AudioDeviceModule::AudioLayer audio_layer_;
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200657 std::unique_ptr<TaskQueueFactory> task_queue_factory_;
henrikaf2f91fa2017-03-17 04:26:22 -0700658 bool requirements_satisfied_ = true;
659 rtc::Event event_;
henrika5b6afc02018-09-05 14:34:40 +0200660 rtc::scoped_refptr<AudioDeviceModuleForTest> audio_device_;
henrikaf2f91fa2017-03-17 04:26:22 -0700661 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700662};
663
henrikaec9c7452018-06-08 16:10:03 +0200664// Instead of using the test fixture, verify that the different factory methods
665// work as intended.
666TEST(AudioDeviceTestWin, ConstructDestructWithFactory) {
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200667 std::unique_ptr<TaskQueueFactory> task_queue_factory =
668 CreateDefaultTaskQueueFactory();
henrikaec9c7452018-06-08 16:10:03 +0200669 rtc::scoped_refptr<AudioDeviceModule> audio_device;
670 // The default factory should work for all platforms when a default ADM is
671 // requested.
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200672 audio_device = AudioDeviceModule::Create(
673 AudioDeviceModule::kPlatformDefaultAudio, task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200674 EXPECT_TRUE(audio_device);
675 audio_device = nullptr;
676#ifdef WEBRTC_WIN
677 // For Windows, the old factory method creates an ADM where the platform-
678 // specific parts are implemented by an AudioDeviceGeneric object. Verify
679 // that the old factory can't be used in combination with the latest audio
680 // layer AudioDeviceModule::kWindowsCoreAudio2.
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200681 audio_device = AudioDeviceModule::Create(
682 AudioDeviceModule::kWindowsCoreAudio2, task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200683 EXPECT_FALSE(audio_device);
684 audio_device = nullptr;
685 // Instead, ensure that the new dedicated factory method called
686 // CreateWindowsCoreAudioAudioDeviceModule() can be used on Windows and that
687 // it sets the audio layer to kWindowsCoreAudio2 implicitly. Note that, the
688 // new ADM for Windows must be created on a COM thread.
689 webrtc_win::ScopedCOMInitializer com_initializer(
690 webrtc_win::ScopedCOMInitializer::kMTA);
691 EXPECT_TRUE(com_initializer.Succeeded());
Danil Chapovalov1c41be62019-04-01 09:16:12 +0200692 audio_device =
693 CreateWindowsCoreAudioAudioDeviceModule(task_queue_factory.get());
henrikaec9c7452018-06-08 16:10:03 +0200694 EXPECT_TRUE(audio_device);
695 AudioDeviceModule::AudioLayer audio_layer;
696 EXPECT_EQ(0, audio_device->ActiveAudioLayer(&audio_layer));
697 EXPECT_EQ(audio_layer, AudioDeviceModule::kWindowsCoreAudio2);
698#endif
699}
henrikaf2f91fa2017-03-17 04:26:22 -0700700
henrikaec9c7452018-06-08 16:10:03 +0200701// Uses the test fixture to create, initialize and destruct the ADM.
702TEST_P(AudioDeviceTest, ConstructDestructDefault) {}
703
704TEST_P(AudioDeviceTest, InitTerminate) {
henrikaf2f91fa2017-03-17 04:26:22 -0700705 SKIP_TEST_IF_NOT(requirements_satisfied());
706 // Initialization is part of the test fixture.
707 EXPECT_TRUE(audio_device()->Initialized());
708 EXPECT_EQ(0, audio_device()->Terminate());
709 EXPECT_FALSE(audio_device()->Initialized());
710}
711
henrikaec9c7452018-06-08 16:10:03 +0200712// Enumerate all available and active output devices.
713TEST_P(AudioDeviceTest, PlayoutDeviceNames) {
henrikaf2f91fa2017-03-17 04:26:22 -0700714 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaec9c7452018-06-08 16:10:03 +0200715 char device_name[kAdmMaxDeviceNameSize];
716 char unique_id[kAdmMaxGuidSize];
717 int num_devices = audio_device()->PlayoutDevices();
718 if (NewWindowsAudioDeviceModuleIsUsed()) {
719 num_devices += 2;
720 }
721 EXPECT_GT(num_devices, 0);
722 for (int i = 0; i < num_devices; ++i) {
723 EXPECT_EQ(0, audio_device()->PlayoutDeviceName(i, device_name, unique_id));
724 }
725 EXPECT_EQ(-1, audio_device()->PlayoutDeviceName(num_devices, device_name,
726 unique_id));
727}
728
729// Enumerate all available and active input devices.
730TEST_P(AudioDeviceTest, RecordingDeviceNames) {
731 SKIP_TEST_IF_NOT(requirements_satisfied());
732 char device_name[kAdmMaxDeviceNameSize];
733 char unique_id[kAdmMaxGuidSize];
734 int num_devices = audio_device()->RecordingDevices();
735 if (NewWindowsAudioDeviceModuleIsUsed()) {
736 num_devices += 2;
737 }
738 EXPECT_GT(num_devices, 0);
739 for (int i = 0; i < num_devices; ++i) {
740 EXPECT_EQ(0,
741 audio_device()->RecordingDeviceName(i, device_name, unique_id));
742 }
743 EXPECT_EQ(-1, audio_device()->RecordingDeviceName(num_devices, device_name,
744 unique_id));
745}
746
747// Counts number of active output devices and ensure that all can be selected.
748TEST_P(AudioDeviceTest, SetPlayoutDevice) {
749 SKIP_TEST_IF_NOT(requirements_satisfied());
750 int num_devices = audio_device()->PlayoutDevices();
751 if (NewWindowsAudioDeviceModuleIsUsed()) {
752 num_devices += 2;
753 }
754 EXPECT_GT(num_devices, 0);
755 // Verify that all available playout devices can be set (not enabled yet).
756 for (int i = 0; i < num_devices; ++i) {
757 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(i));
758 }
759 EXPECT_EQ(-1, audio_device()->SetPlayoutDevice(num_devices));
760#ifdef WEBRTC_WIN
761 // On Windows, verify the alternative method where the user can select device
762 // by role.
763 EXPECT_EQ(
764 0, audio_device()->SetPlayoutDevice(AudioDeviceModule::kDefaultDevice));
765 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(
766 AudioDeviceModule::kDefaultCommunicationDevice));
767#endif
768}
769
770// Counts number of active input devices and ensure that all can be selected.
771TEST_P(AudioDeviceTest, SetRecordingDevice) {
772 SKIP_TEST_IF_NOT(requirements_satisfied());
773 int num_devices = audio_device()->RecordingDevices();
774 if (NewWindowsAudioDeviceModuleIsUsed()) {
775 num_devices += 2;
776 }
777 EXPECT_GT(num_devices, 0);
778 // Verify that all available recording devices can be set (not enabled yet).
779 for (int i = 0; i < num_devices; ++i) {
780 EXPECT_EQ(0, audio_device()->SetRecordingDevice(i));
781 }
782 EXPECT_EQ(-1, audio_device()->SetRecordingDevice(num_devices));
783#ifdef WEBRTC_WIN
784 // On Windows, verify the alternative method where the user can select device
785 // by role.
786 EXPECT_EQ(
787 0, audio_device()->SetRecordingDevice(AudioDeviceModule::kDefaultDevice));
788 EXPECT_EQ(0, audio_device()->SetRecordingDevice(
789 AudioDeviceModule::kDefaultCommunicationDevice));
790#endif
791}
792
793// Tests Start/Stop playout without any registered audio callback.
794TEST_P(AudioDeviceTest, StartStopPlayout) {
795 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaf2f91fa2017-03-17 04:26:22 -0700796 StartPlayout();
797 StopPlayout();
798}
799
800// Tests Start/Stop recording without any registered audio callback.
henrikaec9c7452018-06-08 16:10:03 +0200801TEST_P(AudioDeviceTest, StartStopRecording) {
henrikaf2f91fa2017-03-17 04:26:22 -0700802 SKIP_TEST_IF_NOT(requirements_satisfied());
803 StartRecording();
804 StopRecording();
henrikaf2f91fa2017-03-17 04:26:22 -0700805}
806
henrika6b3e1a22017-09-25 16:34:30 +0200807// Tests Init/Stop/Init recording without any registered audio callback.
808// See https://bugs.chromium.org/p/webrtc/issues/detail?id=8041 for details
809// on why this test is useful.
henrikaec9c7452018-06-08 16:10:03 +0200810TEST_P(AudioDeviceTest, InitStopInitRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200811 SKIP_TEST_IF_NOT(requirements_satisfied());
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}
818
henrikad4049462019-07-12 13:37:11 +0200819// Verify that additional attempts to initialize or start recording while
820// already being active works. Additional calls should just be ignored.
821TEST_P(AudioDeviceTest, StartInitRecording) {
822 SKIP_TEST_IF_NOT(requirements_satisfied());
823 StartRecording();
824 // An additional attempt to initialize at this stage should be ignored.
825 EXPECT_EQ(0, audio_device()->InitRecording());
826 // Same for additional request to start recording while already active.
827 EXPECT_EQ(0, audio_device()->StartRecording());
828 StopRecording();
829}
830
831// Verify that additional attempts to initialize or start playou while
832// already being active works. Additional calls should just be ignored.
833TEST_P(AudioDeviceTest, StartInitPlayout) {
834 SKIP_TEST_IF_NOT(requirements_satisfied());
835 StartPlayout();
836 // An additional attempt to initialize at this stage should be ignored.
837 EXPECT_EQ(0, audio_device()->InitPlayout());
838 // Same for additional request to start playout while already active.
839 EXPECT_EQ(0, audio_device()->StartPlayout());
840 StopPlayout();
841}
842
henrika6b3e1a22017-09-25 16:34:30 +0200843// Tests Init/Stop/Init recording while playout is active.
henrikaec9c7452018-06-08 16:10:03 +0200844TEST_P(AudioDeviceTest, InitStopInitRecordingWhilePlaying) {
henrika6b3e1a22017-09-25 16:34:30 +0200845 SKIP_TEST_IF_NOT(requirements_satisfied());
846 StartPlayout();
847 EXPECT_EQ(0, audio_device()->InitRecording());
848 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
849 StopRecording();
850 EXPECT_EQ(0, audio_device()->InitRecording());
851 StopRecording();
852 StopPlayout();
853}
854
855// Tests Init/Stop/Init playout without any registered audio callback.
henrikaec9c7452018-06-08 16:10:03 +0200856TEST_P(AudioDeviceTest, InitStopInitPlayout) {
henrika6b3e1a22017-09-25 16:34:30 +0200857 SKIP_TEST_IF_NOT(requirements_satisfied());
858 EXPECT_EQ(0, audio_device()->InitPlayout());
859 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
860 StopPlayout();
861 EXPECT_EQ(0, audio_device()->InitPlayout());
862 StopPlayout();
863}
864
865// Tests Init/Stop/Init playout while recording is active.
henrikaec9c7452018-06-08 16:10:03 +0200866TEST_P(AudioDeviceTest, InitStopInitPlayoutWhileRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200867 SKIP_TEST_IF_NOT(requirements_satisfied());
868 StartRecording();
869 EXPECT_EQ(0, audio_device()->InitPlayout());
870 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
871 StopPlayout();
872 EXPECT_EQ(0, audio_device()->InitPlayout());
873 StopPlayout();
874 StopRecording();
875}
876
henrika5b6afc02018-09-05 14:34:40 +0200877// TODO(henrika): restart without intermediate destruction is currently only
878// supported on Windows.
879#ifdef WEBRTC_WIN
880// Tests Start/Stop playout followed by a second session (emulates a restart
881// triggered by a user using public APIs).
882TEST_P(AudioDeviceTest, StartStopPlayoutWithExternalRestart) {
883 SKIP_TEST_IF_NOT(requirements_satisfied());
884 StartPlayout();
885 StopPlayout();
886 // Restart playout without destroying the ADM in between. Ensures that we
887 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
888 StartPlayout();
889 StopPlayout();
890}
891
892// Tests Start/Stop recording followed by a second session (emulates a restart
893// triggered by a user using public APIs).
894TEST_P(AudioDeviceTest, StartStopRecordingWithExternalRestart) {
895 SKIP_TEST_IF_NOT(requirements_satisfied());
896 StartRecording();
897 StopRecording();
898 // Restart recording without destroying the ADM in between. Ensures that we
899 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
900 StartRecording();
901 StopRecording();
902}
903
904// Tests Start/Stop playout followed by a second session (emulates a restart
905// triggered by an internal callback e.g. corresponding to a device switch).
906// Note that, internal restart is only supported in combination with the latest
907// Windows ADM.
908TEST_P(AudioDeviceTest, StartStopPlayoutWithInternalRestart) {
909 SKIP_TEST_IF_NOT(requirements_satisfied());
910 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
911 return;
912 }
913 MockAudioTransport mock(TransportType::kPlay);
914 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
915 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
916 .Times(AtLeast(kNumCallbacks));
917 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
918 StartPlayout();
919 event()->Wait(kTestTimeOutInMilliseconds);
920 EXPECT_TRUE(audio_device()->Playing());
921 // Restart playout but without stopping the internal audio thread.
922 // This procedure uses a non-public test API and it emulates what happens
923 // inside the ADM when e.g. a device is removed.
924 EXPECT_EQ(0, audio_device()->RestartPlayoutInternally());
925
926 // Run basic tests of public APIs while a restart attempt is active.
927 // These calls should now be very thin and not trigger any new actions.
928 EXPECT_EQ(-1, audio_device()->StopPlayout());
929 EXPECT_TRUE(audio_device()->Playing());
930 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
931 EXPECT_EQ(0, audio_device()->InitPlayout());
932 EXPECT_EQ(0, audio_device()->StartPlayout());
933
934 // Wait until audio has restarted and a new sequence of audio callbacks
935 // becomes active.
936 // TODO(henrika): is it possible to verify that the internal state transition
937 // is Stop->Init->Start?
938 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
939 mock.ResetCallbackCounters();
940 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
941 .Times(AtLeast(kNumCallbacks));
942 event()->Wait(kTestTimeOutInMilliseconds);
943 EXPECT_TRUE(audio_device()->Playing());
944 // Stop playout and the audio thread after successful internal restart.
945 StopPlayout();
946}
947
948// Tests Start/Stop recording followed by a second session (emulates a restart
949// triggered by an internal callback e.g. corresponding to a device switch).
950// Note that, internal restart is only supported in combination with the latest
951// Windows ADM.
952TEST_P(AudioDeviceTest, StartStopRecordingWithInternalRestart) {
953 SKIP_TEST_IF_NOT(requirements_satisfied());
954 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
955 return;
956 }
957 MockAudioTransport mock(TransportType::kRecord);
958 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
959 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
960 false, _))
961 .Times(AtLeast(kNumCallbacks));
962 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
963 StartRecording();
964 event()->Wait(kTestTimeOutInMilliseconds);
965 EXPECT_TRUE(audio_device()->Recording());
966 // Restart recording but without stopping the internal audio thread.
967 // This procedure uses a non-public test API and it emulates what happens
968 // inside the ADM when e.g. a device is removed.
969 EXPECT_EQ(0, audio_device()->RestartRecordingInternally());
970
971 // Run basic tests of public APIs while a restart attempt is active.
972 // These calls should now be very thin and not trigger any new actions.
973 EXPECT_EQ(-1, audio_device()->StopRecording());
974 EXPECT_TRUE(audio_device()->Recording());
975 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
976 EXPECT_EQ(0, audio_device()->InitRecording());
977 EXPECT_EQ(0, audio_device()->StartRecording());
978
979 // Wait until audio has restarted and a new sequence of audio callbacks
980 // becomes active.
981 // TODO(henrika): is it possible to verify that the internal state transition
982 // is Stop->Init->Start?
983 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
984 mock.ResetCallbackCounters();
985 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
986 false, _))
987 .Times(AtLeast(kNumCallbacks));
988 event()->Wait(kTestTimeOutInMilliseconds);
989 EXPECT_TRUE(audio_device()->Recording());
990 // Stop recording and the audio thread after successful internal restart.
991 StopRecording();
992}
993#endif // #ifdef WEBRTC_WIN
994
henrikaf2f91fa2017-03-17 04:26:22 -0700995// Start playout and verify that the native audio layer starts asking for real
996// audio samples to play out using the NeedMorePlayData() callback.
997// Note that we can't add expectations on audio parameters in EXPECT_CALL
998// since parameter are not provided in the each callback. We therefore test and
999// verify the parameters in the fake audio transport implementation instead.
henrikaec9c7452018-06-08 16:10:03 +02001000TEST_P(AudioDeviceTest, StartPlayoutVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001001 SKIP_TEST_IF_NOT(requirements_satisfied());
1002 MockAudioTransport mock(TransportType::kPlay);
henrikae24991d2017-04-06 01:14:23 -07001003 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001004 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
1005 .Times(AtLeast(kNumCallbacks));
1006 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1007 StartPlayout();
1008 event()->Wait(kTestTimeOutInMilliseconds);
1009 StopPlayout();
1010}
1011
1012// Start recording and verify that the native audio layer starts providing real
1013// audio samples using the RecordedDataIsAvailable() callback.
henrikaec9c7452018-06-08 16:10:03 +02001014TEST_P(AudioDeviceTest, StartRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001015 SKIP_TEST_IF_NOT(requirements_satisfied());
1016 MockAudioTransport mock(TransportType::kRecord);
henrikae24991d2017-04-06 01:14:23 -07001017 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001018 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
1019 false, _))
1020 .Times(AtLeast(kNumCallbacks));
1021 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1022 StartRecording();
1023 event()->Wait(kTestTimeOutInMilliseconds);
1024 StopRecording();
1025}
1026
1027// Start playout and recording (full-duplex audio) and verify that audio is
1028// active in both directions.
henrikaec9c7452018-06-08 16:10:03 +02001029TEST_P(AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -07001030 SKIP_TEST_IF_NOT(requirements_satisfied());
1031 MockAudioTransport mock(TransportType::kPlayAndRecord);
henrikae24991d2017-04-06 01:14:23 -07001032 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -07001033 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
1034 .Times(AtLeast(kNumCallbacks));
1035 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
1036 false, _))
1037 .Times(AtLeast(kNumCallbacks));
1038 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1039 StartPlayout();
1040 StartRecording();
1041 event()->Wait(kTestTimeOutInMilliseconds);
1042 StopRecording();
1043 StopPlayout();
1044}
1045
henrikae24991d2017-04-06 01:14:23 -07001046// Start playout and recording and store recorded data in an intermediate FIFO
1047// buffer from which the playout side then reads its samples in the same order
1048// as they were stored. Under ideal circumstances, a callback sequence would
1049// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
1050// means 'packet played'. Under such conditions, the FIFO would contain max 1,
1051// with an average somewhere in (0,1) depending on how long the packets are
1052// buffered. However, under more realistic conditions, the size
1053// of the FIFO will vary more due to an unbalance between the two sides.
1054// This test tries to verify that the device maintains a balanced callback-
1055// sequence by running in loopback for a few seconds while measuring the size
1056// (max and average) of the FIFO. The size of the FIFO is increased by the
1057// recording side and decreased by the playout side.
henrikaec9c7452018-06-08 16:10:03 +02001058TEST_P(AudioDeviceTest, RunPlayoutAndRecordingInFullDuplex) {
henrikae24991d2017-04-06 01:14:23 -07001059 SKIP_TEST_IF_NOT(requirements_satisfied());
1060 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1061 FifoAudioStream audio_stream;
1062 mock.HandleCallbacks(event(), &audio_stream,
1063 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
1064 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001065 // Run both sides using the same channel configuration to avoid conversions
1066 // between mono/stereo while running in full duplex mode. Also, some devices
1067 // (mainly on Windows) do not support mono.
1068 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1069 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
Gustaf Ullberg102b7282019-06-03 15:03:02 +02001070 // Mute speakers to prevent howling.
1071 EXPECT_EQ(0, audio_device()->SetSpeakerVolume(0));
henrikae24991d2017-04-06 01:14:23 -07001072 StartPlayout();
1073 StartRecording();
henrika714e5cd2017-04-20 08:03:11 -07001074 event()->Wait(static_cast<int>(
1075 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec)));
henrikae24991d2017-04-06 01:14:23 -07001076 StopRecording();
1077 StopPlayout();
1078 // This thresholds is set rather high to accommodate differences in hardware
1079 // in several devices. The main idea is to capture cases where a very large
henrikab6ca7212017-10-06 12:47:52 +02001080 // latency is built up. See http://bugs.webrtc.org/7744 for examples on
1081 // bots where relatively large average latencies can happen.
1082 EXPECT_LE(audio_stream.average_size(), 25u);
henrikae24991d2017-04-06 01:14:23 -07001083 PRINT("\n");
1084}
1085
henrika5b6afc02018-09-05 14:34:40 +02001086// Runs audio in full duplex until user hits Enter. Intended as a manual test
1087// to ensure that the audio quality is good and that real device switches works
1088// as intended.
1089TEST_P(AudioDeviceTest,
1090 DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey) {
1091 SKIP_TEST_IF_NOT(requirements_satisfied());
1092 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
1093 return;
1094 }
1095 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1096 FifoAudioStream audio_stream;
1097 mock.HandleCallbacks(&audio_stream);
1098 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1099 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1100 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
1101 // Ensure that the sample rate for both directions are identical so that we
1102 // always can listen to our own voice. Will lead to rate conversion (and
1103 // higher latency) if the native sample rate is not 48kHz.
1104 EXPECT_EQ(0, audio_device()->SetPlayoutSampleRate(48000));
1105 EXPECT_EQ(0, audio_device()->SetRecordingSampleRate(48000));
1106 StartPlayout();
1107 StartRecording();
1108 do {
1109 PRINT("Loopback audio is active at 48kHz. Press Enter to stop.\n");
1110 } while (getchar() != '\n');
1111 StopRecording();
1112 StopPlayout();
1113}
1114
henrika714e5cd2017-04-20 08:03:11 -07001115// Measures loopback latency and reports the min, max and average values for
1116// a full duplex audio session.
1117// The latency is measured like so:
1118// - Insert impulses periodically on the output side.
1119// - Detect the impulses on the input side.
1120// - Measure the time difference between the transmit time and receive time.
1121// - Store time differences in a vector and calculate min, max and average.
1122// This test needs the '--gtest_also_run_disabled_tests' flag to run and also
1123// some sort of audio feedback loop. E.g. a headset where the mic is placed
1124// close to the speaker to ensure highest possible echo. It is also recommended
1125// to run the test at highest possible output volume.
henrikaec9c7452018-06-08 16:10:03 +02001126TEST_P(AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
henrika714e5cd2017-04-20 08:03:11 -07001127 SKIP_TEST_IF_NOT(requirements_satisfied());
1128 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1129 LatencyAudioStream audio_stream;
1130 mock.HandleCallbacks(event(), &audio_stream,
1131 kMeasureLatencyTimeInSec * kNumCallbacksPerSecond);
1132 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001133 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1134 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrika714e5cd2017-04-20 08:03:11 -07001135 StartPlayout();
1136 StartRecording();
1137 event()->Wait(static_cast<int>(
1138 std::max(kTestTimeOutInMilliseconds, 1000 * kMeasureLatencyTimeInSec)));
1139 StopRecording();
1140 StopPlayout();
henrikac7d93582018-09-14 15:37:34 +02001141 // Verify that a sufficient number of transmitted impulses are detected.
1142 EXPECT_GE(audio_stream.num_latency_values(),
henrika714e5cd2017-04-20 08:03:11 -07001143 static_cast<size_t>(
henrikac7d93582018-09-14 15:37:34 +02001144 kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 2));
henrika714e5cd2017-04-20 08:03:11 -07001145 // Print out min, max and average delay values for debugging purposes.
1146 audio_stream.PrintResults();
1147}
1148
henrikaec9c7452018-06-08 16:10:03 +02001149#ifdef WEBRTC_WIN
1150// Test two different audio layers (or rather two different Core Audio
1151// implementations) for Windows.
Mirko Bonadeic84f6612019-01-31 12:20:57 +01001152INSTANTIATE_TEST_SUITE_P(
henrikaec9c7452018-06-08 16:10:03 +02001153 AudioLayerWin,
1154 AudioDeviceTest,
1155 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio,
1156 AudioDeviceModule::kWindowsCoreAudio2));
1157#else
1158// For all platforms but Windows, only test the default audio layer.
Mirko Bonadeic84f6612019-01-31 12:20:57 +01001159INSTANTIATE_TEST_SUITE_P(
henrikaec9c7452018-06-08 16:10:03 +02001160 AudioLayer,
1161 AudioDeviceTest,
1162 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio));
1163#endif
1164
henrikaf2f91fa2017-03-17 04:26:22 -07001165} // namespace webrtc