blob: a82bc4a33ba3a7dbb46fc91b33bfee7b9565719d [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
Danil Chapovalov196100e2018-06-21 10:17:24 +020016#include "absl/types/optional.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "api/array_view.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "modules/audio_device/audio_device_impl.h"
19#include "modules/audio_device/include/audio_device.h"
20#include "modules/audio_device/include/mock_audio_transport.h"
21#include "rtc_base/buffer.h"
22#include "rtc_base/criticalsection.h"
23#include "rtc_base/event.h"
24#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010025#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "rtc_base/race_checker.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/scoped_ref_ptr.h"
28#include "rtc_base/thread_annotations.h"
29#include "rtc_base/thread_checker.h"
30#include "rtc_base/timeutils.h"
henrika5b6afc02018-09-05 14:34:40 +020031#include "system_wrappers/include/sleep.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "test/gmock.h"
33#include "test/gtest.h"
henrikaec9c7452018-06-08 16:10:03 +020034#ifdef WEBRTC_WIN
35#include "modules/audio_device/include/audio_device_factory.h"
36#include "modules/audio_device/win/core_audio_utility_win.h"
37#endif
henrikaf2f91fa2017-03-17 04:26:22 -070038
39using ::testing::_;
40using ::testing::AtLeast;
41using ::testing::Ge;
42using ::testing::Invoke;
43using ::testing::NiceMock;
44using ::testing::NotNull;
henrika5b6afc02018-09-05 14:34:40 +020045using ::testing::Mock;
henrikaf2f91fa2017-03-17 04:26:22 -070046
47namespace webrtc {
48namespace {
49
henrika5773ad32018-09-21 14:53:10 +020050// Using a #define for AUDIO_DEVICE since we will call *different* versions of
51// the ADM functions, depending on the ID type.
52#if defined(WEBRTC_WIN)
53#define AUDIO_DEVICE_ID (AudioDeviceModule::WindowsDeviceType::kDefaultDevice)
54#else
55#define AUDIO_DEVICE_ID (0u)
56#endif // defined(WEBRTC_WIN)
57
henrikae24991d2017-04-06 01:14:23 -070058// #define ENABLE_DEBUG_PRINTF
59#ifdef ENABLE_DEBUG_PRINTF
60#define PRINTD(...) fprintf(stderr, __VA_ARGS__);
61#else
62#define PRINTD(...) ((void)0)
63#endif
64#define PRINT(...) fprintf(stderr, __VA_ARGS__);
65
henrikaf2f91fa2017-03-17 04:26:22 -070066// Don't run these tests in combination with sanitizers.
Sami Kalliomäkidefb7172018-09-25 13:12:05 +020067// TODO(webrtc:9778): Re-enable on THREAD_SANITIZER?
68#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \
69 !defined(THREAD_SANITIZER)
henrikaf2f91fa2017-03-17 04:26:22 -070070#define SKIP_TEST_IF_NOT(requirements_satisfied) \
71 do { \
72 if (!requirements_satisfied) { \
73 return; \
74 } \
75 } while (false)
76#else
77// Or if other audio-related requirements are not met.
78#define SKIP_TEST_IF_NOT(requirements_satisfied) \
79 do { \
80 return; \
81 } while (false)
82#endif
83
84// Number of callbacks (input or output) the tests waits for before we set
85// an event indicating that the test was OK.
henrikae24991d2017-04-06 01:14:23 -070086static constexpr size_t kNumCallbacks = 10;
henrikaf2f91fa2017-03-17 04:26:22 -070087// Max amount of time we wait for an event to be set while counting callbacks.
henrika714e5cd2017-04-20 08:03:11 -070088static constexpr size_t kTestTimeOutInMilliseconds = 10 * 1000;
henrikae24991d2017-04-06 01:14:23 -070089// Average number of audio callbacks per second assuming 10ms packet size.
90static constexpr size_t kNumCallbacksPerSecond = 100;
91// Run the full-duplex test during this time (unit is in seconds).
henrika714e5cd2017-04-20 08:03:11 -070092static constexpr size_t kFullDuplexTimeInSec = 5;
93// Length of round-trip latency measurements. Number of deteced impulses
94// shall be kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 1 since the
95// last transmitted pulse is not used.
96static constexpr size_t kMeasureLatencyTimeInSec = 10;
97// Sets the number of impulses per second in the latency test.
98static constexpr size_t kImpulseFrequencyInHz = 1;
99// Utilized in round-trip latency measurements to avoid capturing noise samples.
100static constexpr int kImpulseThreshold = 1000;
henrikaf2f91fa2017-03-17 04:26:22 -0700101
102enum class TransportType {
103 kInvalid,
104 kPlay,
105 kRecord,
106 kPlayAndRecord,
107};
henrikae24991d2017-04-06 01:14:23 -0700108
109// Interface for processing the audio stream. Real implementations can e.g.
110// run audio in loopback, read audio from a file or perform latency
111// measurements.
112class AudioStream {
113 public:
henrikaeb98c722018-03-20 12:54:07 +0100114 virtual void Write(rtc::ArrayView<const int16_t> source) = 0;
115 virtual void Read(rtc::ArrayView<int16_t> destination) = 0;
henrikae24991d2017-04-06 01:14:23 -0700116
117 virtual ~AudioStream() = default;
118};
119
henrika714e5cd2017-04-20 08:03:11 -0700120// Converts index corresponding to position within a 10ms buffer into a
121// delay value in milliseconds.
122// Example: index=240, frames_per_10ms_buffer=480 => 5ms as output.
123int IndexToMilliseconds(size_t index, size_t frames_per_10ms_buffer) {
124 return rtc::checked_cast<int>(
125 10.0 * (static_cast<double>(index) / frames_per_10ms_buffer) + 0.5);
126}
127
henrikaf2f91fa2017-03-17 04:26:22 -0700128} // namespace
129
henrikae24991d2017-04-06 01:14:23 -0700130// Simple first in first out (FIFO) class that wraps a list of 16-bit audio
131// buffers of fixed size and allows Write and Read operations. The idea is to
132// store recorded audio buffers (using Write) and then read (using Read) these
133// stored buffers with as short delay as possible when the audio layer needs
134// data to play out. The number of buffers in the FIFO will stabilize under
135// normal conditions since there will be a balance between Write and Read calls.
136// The container is a std::list container and access is protected with a lock
137// since both sides (playout and recording) are driven by its own thread.
138// Note that, we know by design that the size of the audio buffer will not
henrikac7d93582018-09-14 15:37:34 +0200139// change over time and that both sides will in most cases use the same size.
henrikae24991d2017-04-06 01:14:23 -0700140class FifoAudioStream : public AudioStream {
141 public:
henrikaeb98c722018-03-20 12:54:07 +0100142 void Write(rtc::ArrayView<const int16_t> source) override {
henrikae24991d2017-04-06 01:14:23 -0700143 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
144 const size_t size = [&] {
145 rtc::CritScope lock(&lock_);
146 fifo_.push_back(Buffer16(source.data(), source.size()));
147 return fifo_.size();
148 }();
149 if (size > max_size_) {
150 max_size_ = size;
151 }
152 // Add marker once per second to signal that audio is active.
153 if (write_count_++ % 100 == 0) {
154 PRINT(".");
155 }
156 written_elements_ += size;
157 }
158
henrikaeb98c722018-03-20 12:54:07 +0100159 void Read(rtc::ArrayView<int16_t> destination) override {
henrikae24991d2017-04-06 01:14:23 -0700160 rtc::CritScope lock(&lock_);
161 if (fifo_.empty()) {
162 std::fill(destination.begin(), destination.end(), 0);
163 } else {
164 const Buffer16& buffer = fifo_.front();
henrikac7d93582018-09-14 15:37:34 +0200165 if (buffer.size() == destination.size()) {
166 // Default case where input and output uses same sample rate and
167 // channel configuration. No conversion is needed.
168 std::copy(buffer.begin(), buffer.end(), destination.begin());
169 } else if (destination.size() == 2 * buffer.size()) {
170 // Recorded input signal in |buffer| is in mono. Do channel upmix to
171 // match stereo output (1 -> 2).
172 for (size_t i = 0; i < buffer.size(); ++i) {
173 destination[2 * i] = buffer[i];
174 destination[2 * i + 1] = buffer[i];
175 }
176 } else if (buffer.size() == 2 * destination.size()) {
177 // Recorded input signal in |buffer| is in stereo. Do channel downmix
178 // to match mono output (2 -> 1).
179 for (size_t i = 0; i < destination.size(); ++i) {
180 destination[i] =
181 (static_cast<int32_t>(buffer[2 * i]) + buffer[2 * i + 1]) / 2;
182 }
183 } else {
184 RTC_NOTREACHED() << "Required conversion is not support";
185 }
henrikae24991d2017-04-06 01:14:23 -0700186 fifo_.pop_front();
187 }
188 }
189
190 size_t size() const {
191 rtc::CritScope lock(&lock_);
192 return fifo_.size();
193 }
194
195 size_t max_size() const {
196 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
197 return max_size_;
198 }
199
200 size_t average_size() const {
201 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
202 return 0.5 + static_cast<float>(written_elements_ / write_count_);
203 }
204
205 using Buffer16 = rtc::BufferT<int16_t>;
206
207 rtc::CriticalSection lock_;
208 rtc::RaceChecker race_checker_;
209
danilchap56359be2017-09-07 07:53:45 -0700210 std::list<Buffer16> fifo_ RTC_GUARDED_BY(lock_);
211 size_t write_count_ RTC_GUARDED_BY(race_checker_) = 0;
212 size_t max_size_ RTC_GUARDED_BY(race_checker_) = 0;
213 size_t written_elements_ RTC_GUARDED_BY(race_checker_) = 0;
henrikae24991d2017-04-06 01:14:23 -0700214};
215
henrika714e5cd2017-04-20 08:03:11 -0700216// Inserts periodic impulses and measures the latency between the time of
217// transmission and time of receiving the same impulse.
218class LatencyAudioStream : public AudioStream {
219 public:
220 LatencyAudioStream() {
221 // Delay thread checkers from being initialized until first callback from
222 // respective thread.
223 read_thread_checker_.DetachFromThread();
224 write_thread_checker_.DetachFromThread();
225 }
226
227 // Insert periodic impulses in first two samples of |destination|.
henrikaeb98c722018-03-20 12:54:07 +0100228 void Read(rtc::ArrayView<int16_t> destination) override {
henrika714e5cd2017-04-20 08:03:11 -0700229 RTC_DCHECK_RUN_ON(&read_thread_checker_);
henrika714e5cd2017-04-20 08:03:11 -0700230 if (read_count_ == 0) {
231 PRINT("[");
232 }
233 read_count_++;
234 std::fill(destination.begin(), destination.end(), 0);
235 if (read_count_ % (kNumCallbacksPerSecond / kImpulseFrequencyInHz) == 0) {
236 PRINT(".");
237 {
238 rtc::CritScope lock(&lock_);
239 if (!pulse_time_) {
Oskar Sundbom6ad9f262017-11-16 10:53:39 +0100240 pulse_time_ = rtc::TimeMillis();
henrika714e5cd2017-04-20 08:03:11 -0700241 }
242 }
243 constexpr int16_t impulse = std::numeric_limits<int16_t>::max();
244 std::fill_n(destination.begin(), 2, impulse);
245 }
246 }
247
248 // Detect received impulses in |source|, derive time between transmission and
249 // detection and add the calculated delay to list of latencies.
henrikaeb98c722018-03-20 12:54:07 +0100250 void Write(rtc::ArrayView<const int16_t> source) override {
henrika714e5cd2017-04-20 08:03:11 -0700251 RTC_DCHECK_RUN_ON(&write_thread_checker_);
252 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
253 rtc::CritScope lock(&lock_);
254 write_count_++;
255 if (!pulse_time_) {
256 // Avoid detection of new impulse response until a new impulse has
257 // been transmitted (sets |pulse_time_| to value larger than zero).
258 return;
259 }
260 // Find index (element position in vector) of the max element.
261 const size_t index_of_max =
262 std::max_element(source.begin(), source.end()) - source.begin();
263 // Derive time between transmitted pulse and received pulse if the level
264 // is high enough (removes noise).
265 const size_t max = source[index_of_max];
266 if (max > kImpulseThreshold) {
267 PRINTD("(%zu, %zu)", max, index_of_max);
268 int64_t now_time = rtc::TimeMillis();
269 int extra_delay = IndexToMilliseconds(index_of_max, source.size());
270 PRINTD("[%d]", rtc::checked_cast<int>(now_time - pulse_time_));
271 PRINTD("[%d]", extra_delay);
272 // Total latency is the difference between transmit time and detection
273 // tome plus the extra delay within the buffer in which we detected the
274 // received impulse. It is transmitted at sample 0 but can be received
275 // at sample N where N > 0. The term |extra_delay| accounts for N and it
276 // is a value between 0 and 10ms.
277 latencies_.push_back(now_time - *pulse_time_ + extra_delay);
278 pulse_time_.reset();
279 } else {
280 PRINTD("-");
281 }
282 }
283
284 size_t num_latency_values() const {
285 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
286 return latencies_.size();
287 }
288
289 int min_latency() const {
290 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
291 if (latencies_.empty())
292 return 0;
293 return *std::min_element(latencies_.begin(), latencies_.end());
294 }
295
296 int max_latency() const {
297 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
298 if (latencies_.empty())
299 return 0;
300 return *std::max_element(latencies_.begin(), latencies_.end());
301 }
302
303 int average_latency() const {
304 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
305 if (latencies_.empty())
306 return 0;
307 return 0.5 + static_cast<double>(
308 std::accumulate(latencies_.begin(), latencies_.end(), 0)) /
309 latencies_.size();
310 }
311
312 void PrintResults() const {
313 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
314 PRINT("] ");
315 for (auto it = latencies_.begin(); it != latencies_.end(); ++it) {
316 PRINTD("%d ", *it);
317 }
318 PRINT("\n");
319 PRINT("[..........] [min, max, avg]=[%d, %d, %d] ms\n", min_latency(),
320 max_latency(), average_latency());
321 }
322
323 rtc::CriticalSection lock_;
324 rtc::RaceChecker race_checker_;
325 rtc::ThreadChecker read_thread_checker_;
326 rtc::ThreadChecker write_thread_checker_;
327
Danil Chapovalov196100e2018-06-21 10:17:24 +0200328 absl::optional<int64_t> pulse_time_ RTC_GUARDED_BY(lock_);
danilchap56359be2017-09-07 07:53:45 -0700329 std::vector<int> latencies_ RTC_GUARDED_BY(race_checker_);
Niels Möller1e062892018-02-07 10:18:32 +0100330 size_t read_count_ RTC_GUARDED_BY(read_thread_checker_) = 0;
331 size_t write_count_ RTC_GUARDED_BY(write_thread_checker_) = 0;
henrika714e5cd2017-04-20 08:03:11 -0700332};
333
henrikaf2f91fa2017-03-17 04:26:22 -0700334// Mocks the AudioTransport object and proxies actions for the two callbacks
335// (RecordedDataIsAvailable and NeedMorePlayData) to different implementations
336// of AudioStreamInterface.
337class MockAudioTransport : public test::MockAudioTransport {
338 public:
339 explicit MockAudioTransport(TransportType type) : type_(type) {}
340 ~MockAudioTransport() {}
341
342 // Set default actions of the mock object. We are delegating to fake
343 // implementation where the number of callbacks is counted and an event
344 // is set after a certain number of callbacks. Audio parameters are also
345 // checked.
henrikae24991d2017-04-06 01:14:23 -0700346 void HandleCallbacks(rtc::Event* event,
347 AudioStream* audio_stream,
348 int num_callbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700349 event_ = event;
henrikae24991d2017-04-06 01:14:23 -0700350 audio_stream_ = audio_stream;
henrikaf2f91fa2017-03-17 04:26:22 -0700351 num_callbacks_ = num_callbacks;
352 if (play_mode()) {
353 ON_CALL(*this, NeedMorePlayData(_, _, _, _, _, _, _, _))
354 .WillByDefault(
355 Invoke(this, &MockAudioTransport::RealNeedMorePlayData));
356 }
357 if (rec_mode()) {
358 ON_CALL(*this, RecordedDataIsAvailable(_, _, _, _, _, _, _, _, _, _))
359 .WillByDefault(
360 Invoke(this, &MockAudioTransport::RealRecordedDataIsAvailable));
361 }
362 }
363
henrika5b6afc02018-09-05 14:34:40 +0200364 // Special constructor used in manual tests where the user wants to run audio
365 // until e.g. a keyboard key is pressed. The event flag is set to nullptr by
366 // default since it is up to the user to stop the test. See e.g.
367 // DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey().
368 void HandleCallbacks(AudioStream* audio_stream) {
369 HandleCallbacks(nullptr, audio_stream, 0);
370 }
371
henrikaf2f91fa2017-03-17 04:26:22 -0700372 int32_t RealRecordedDataIsAvailable(const void* audio_buffer,
373 const size_t samples_per_channel,
374 const size_t bytes_per_frame,
375 const size_t channels,
376 const uint32_t sample_rate,
377 const uint32_t total_delay_ms,
378 const int32_t clock_drift,
379 const uint32_t current_mic_level,
380 const bool typing_status,
381 uint32_t& new_mic_level) {
382 EXPECT_TRUE(rec_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700383 // Store audio parameters once in the first callback. For all other
384 // callbacks, verify that the provided audio parameters are maintained and
385 // that each callback corresponds to 10ms for any given sample rate.
386 if (!record_parameters_.is_complete()) {
387 record_parameters_.reset(sample_rate, channels, samples_per_channel);
388 } else {
389 EXPECT_EQ(samples_per_channel, record_parameters_.frames_per_buffer());
390 EXPECT_EQ(bytes_per_frame, record_parameters_.GetBytesPerFrame());
391 EXPECT_EQ(channels, record_parameters_.channels());
392 EXPECT_EQ(static_cast<int>(sample_rate),
393 record_parameters_.sample_rate());
394 EXPECT_EQ(samples_per_channel,
395 record_parameters_.frames_per_10ms_buffer());
396 }
henrika78e0ac12018-09-27 16:23:21 +0200397 {
398 rtc::CritScope lock(&lock_);
399 rec_count_++;
400 }
henrikae24991d2017-04-06 01:14:23 -0700401 // Write audio data to audio stream object if one has been injected.
402 if (audio_stream_) {
403 audio_stream_->Write(
404 rtc::MakeArrayView(static_cast<const int16_t*>(audio_buffer),
henrikaeb98c722018-03-20 12:54:07 +0100405 samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700406 }
henrikaf2f91fa2017-03-17 04:26:22 -0700407 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200408 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700409 event_->Set();
410 }
411 return 0;
412 }
413
414 int32_t RealNeedMorePlayData(const size_t samples_per_channel,
415 const size_t bytes_per_frame,
416 const size_t channels,
417 const uint32_t sample_rate,
418 void* audio_buffer,
henrikaeb98c722018-03-20 12:54:07 +0100419 size_t& samples_out,
henrikaf2f91fa2017-03-17 04:26:22 -0700420 int64_t* elapsed_time_ms,
421 int64_t* ntp_time_ms) {
422 EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700423 // Store audio parameters once in the first callback. For all other
424 // callbacks, verify that the provided audio parameters are maintained and
425 // that each callback corresponds to 10ms for any given sample rate.
426 if (!playout_parameters_.is_complete()) {
427 playout_parameters_.reset(sample_rate, channels, samples_per_channel);
428 } else {
429 EXPECT_EQ(samples_per_channel, playout_parameters_.frames_per_buffer());
430 EXPECT_EQ(bytes_per_frame, playout_parameters_.GetBytesPerFrame());
431 EXPECT_EQ(channels, playout_parameters_.channels());
432 EXPECT_EQ(static_cast<int>(sample_rate),
433 playout_parameters_.sample_rate());
434 EXPECT_EQ(samples_per_channel,
435 playout_parameters_.frames_per_10ms_buffer());
436 }
henrika78e0ac12018-09-27 16:23:21 +0200437 {
438 rtc::CritScope lock(&lock_);
439 play_count_++;
440 }
henrikaeb98c722018-03-20 12:54:07 +0100441 samples_out = samples_per_channel * channels;
henrikae24991d2017-04-06 01:14:23 -0700442 // Read audio data from audio stream object if one has been injected.
443 if (audio_stream_) {
henrikaeb98c722018-03-20 12:54:07 +0100444 audio_stream_->Read(rtc::MakeArrayView(
445 static_cast<int16_t*>(audio_buffer), samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700446 } else {
447 // Fill the audio buffer with zeros to avoid disturbing audio.
448 const size_t num_bytes = samples_per_channel * bytes_per_frame;
449 std::memset(audio_buffer, 0, num_bytes);
450 }
henrikaf2f91fa2017-03-17 04:26:22 -0700451 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200452 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700453 event_->Set();
454 }
455 return 0;
456 }
457
458 bool ReceivedEnoughCallbacks() {
459 bool recording_done = false;
460 if (rec_mode()) {
henrika78e0ac12018-09-27 16:23:21 +0200461 rtc::CritScope lock(&lock_);
henrikaf2f91fa2017-03-17 04:26:22 -0700462 recording_done = rec_count_ >= num_callbacks_;
463 } else {
464 recording_done = true;
465 }
466 bool playout_done = false;
467 if (play_mode()) {
henrika78e0ac12018-09-27 16:23:21 +0200468 rtc::CritScope lock(&lock_);
henrikaf2f91fa2017-03-17 04:26:22 -0700469 playout_done = play_count_ >= num_callbacks_;
470 } else {
471 playout_done = true;
472 }
473 return recording_done && playout_done;
474 }
475
476 bool play_mode() const {
477 return type_ == TransportType::kPlay ||
478 type_ == TransportType::kPlayAndRecord;
479 }
480
481 bool rec_mode() const {
482 return type_ == TransportType::kRecord ||
483 type_ == TransportType::kPlayAndRecord;
484 }
485
henrika5b6afc02018-09-05 14:34:40 +0200486 void ResetCallbackCounters() {
henrika78e0ac12018-09-27 16:23:21 +0200487 rtc::CritScope lock(&lock_);
henrika5b6afc02018-09-05 14:34:40 +0200488 if (play_mode()) {
489 play_count_ = 0;
490 }
491 if (rec_mode()) {
492 rec_count_ = 0;
493 }
494 }
495
henrikaf2f91fa2017-03-17 04:26:22 -0700496 private:
henrika78e0ac12018-09-27 16:23:21 +0200497 rtc::CriticalSection lock_;
henrikaf2f91fa2017-03-17 04:26:22 -0700498 TransportType type_ = TransportType::kInvalid;
499 rtc::Event* event_ = nullptr;
henrikae24991d2017-04-06 01:14:23 -0700500 AudioStream* audio_stream_ = nullptr;
henrikaf2f91fa2017-03-17 04:26:22 -0700501 size_t num_callbacks_ = 0;
henrika78e0ac12018-09-27 16:23:21 +0200502 size_t play_count_ RTC_GUARDED_BY(lock_) = 0;
503 size_t rec_count_ RTC_GUARDED_BY(lock_) = 0;
henrikaf2f91fa2017-03-17 04:26:22 -0700504 AudioParameters playout_parameters_;
505 AudioParameters record_parameters_;
506};
507
508// AudioDeviceTest test fixture.
henrikaec9c7452018-06-08 16:10:03 +0200509class AudioDeviceTest
510 : public ::testing::TestWithParam<webrtc::AudioDeviceModule::AudioLayer> {
henrikaf2f91fa2017-03-17 04:26:22 -0700511 protected:
henrikaec9c7452018-06-08 16:10:03 +0200512 AudioDeviceTest() : audio_layer_(GetParam()), event_(false, false) {
Sami Kalliomäkia3b9b272018-09-25 15:03:43 +0200513// TODO(webrtc:9778): Re-enable on THREAD_SANITIZER?
Joachim Bauch5d2bb362017-12-20 21:19:49 +0100514#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \
Sami Kalliomäkia3b9b272018-09-25 15:03:43 +0200515 !defined(WEBRTC_DUMMY_AUDIO_BUILD) && !defined(THREAD_SANITIZER)
henrikaf2f91fa2017-03-17 04:26:22 -0700516 rtc::LogMessage::LogToDebug(rtc::LS_INFO);
517 // Add extra logging fields here if needed for debugging.
henrikaec9c7452018-06-08 16:10:03 +0200518 rtc::LogMessage::LogTimestamps();
519 rtc::LogMessage::LogThreads();
520 audio_device_ = CreateAudioDevice();
henrikaf2f91fa2017-03-17 04:26:22 -0700521 EXPECT_NE(audio_device_.get(), nullptr);
522 AudioDeviceModule::AudioLayer audio_layer;
maxmorin33bf69a2017-03-23 04:06:53 -0700523 int got_platform_audio_layer =
524 audio_device_->ActiveAudioLayer(&audio_layer);
henrika919dc2e2017-10-12 14:24:55 +0200525 // First, ensure that a valid audio layer can be activated.
526 if (got_platform_audio_layer != 0) {
henrikaf2f91fa2017-03-17 04:26:22 -0700527 requirements_satisfied_ = false;
528 }
henrika919dc2e2017-10-12 14:24:55 +0200529 // Next, verify that the ADM can be initialized.
henrikaf2f91fa2017-03-17 04:26:22 -0700530 if (requirements_satisfied_) {
henrika919dc2e2017-10-12 14:24:55 +0200531 requirements_satisfied_ = (audio_device_->Init() == 0);
532 }
533 // Finally, ensure that at least one valid device exists in each direction.
534 if (requirements_satisfied_) {
henrikaf2f91fa2017-03-17 04:26:22 -0700535 const int16_t num_playout_devices = audio_device_->PlayoutDevices();
536 const int16_t num_record_devices = audio_device_->RecordingDevices();
537 requirements_satisfied_ =
538 num_playout_devices > 0 && num_record_devices > 0;
539 }
540#else
541 requirements_satisfied_ = false;
542#endif
543 if (requirements_satisfied_) {
henrika5773ad32018-09-21 14:53:10 +0200544 EXPECT_EQ(0, audio_device_->SetPlayoutDevice(AUDIO_DEVICE_ID));
henrikaf2f91fa2017-03-17 04:26:22 -0700545 EXPECT_EQ(0, audio_device_->InitSpeaker());
henrikaf2f91fa2017-03-17 04:26:22 -0700546 EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
547 EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
henrika5773ad32018-09-21 14:53:10 +0200548 EXPECT_EQ(0, audio_device_->SetRecordingDevice(AUDIO_DEVICE_ID));
549 EXPECT_EQ(0, audio_device_->InitMicrophone());
henrika0238ba82017-03-28 04:38:29 -0700550 // Avoid asking for input stereo support and always record in mono
551 // since asking can cause issues in combination with remote desktop.
552 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
553 // details.
554 EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
henrikaf2f91fa2017-03-17 04:26:22 -0700555 }
556 }
557
558 virtual ~AudioDeviceTest() {
559 if (audio_device_) {
560 EXPECT_EQ(0, audio_device_->Terminate());
561 }
562 }
563
564 bool requirements_satisfied() const { return requirements_satisfied_; }
565 rtc::Event* event() { return &event_; }
henrika5b6afc02018-09-05 14:34:40 +0200566 AudioDeviceModule::AudioLayer audio_layer() const { return audio_layer_; }
henrikaf2f91fa2017-03-17 04:26:22 -0700567
henrika5b6afc02018-09-05 14:34:40 +0200568 // AudioDeviceModuleForTest extends the default ADM interface with some extra
569 // test methods. Intended for usage in tests only and requires a unique
570 // factory method. See CreateAudioDevice() for details.
571 const rtc::scoped_refptr<AudioDeviceModuleForTest>& audio_device() const {
henrikaf2f91fa2017-03-17 04:26:22 -0700572 return audio_device_;
573 }
574
henrika5b6afc02018-09-05 14:34:40 +0200575 rtc::scoped_refptr<AudioDeviceModuleForTest> CreateAudioDevice() {
henrikaec9c7452018-06-08 16:10:03 +0200576 // Use the default factory for kPlatformDefaultAudio and a special factory
henrika5b6afc02018-09-05 14:34:40 +0200577 // CreateWindowsCoreAudioAudioDeviceModuleForTest() for kWindowsCoreAudio2.
henrikaec9c7452018-06-08 16:10:03 +0200578 // The value of |audio_layer_| is set at construction by GetParam() and two
579 // different layers are tested on Windows only.
580 if (audio_layer_ == AudioDeviceModule::kPlatformDefaultAudio) {
henrika5b6afc02018-09-05 14:34:40 +0200581 return AudioDeviceModule::CreateForTest(audio_layer_);
henrikaec9c7452018-06-08 16:10:03 +0200582 } else if (audio_layer_ == AudioDeviceModule::kWindowsCoreAudio2) {
583#ifdef WEBRTC_WIN
584 // We must initialize the COM library on a thread before we calling any of
585 // the library functions. All COM functions in the ADM will return
586 // CO_E_NOTINITIALIZED otherwise.
Karl Wiberg918f50c2018-07-05 11:40:33 +0200587 com_initializer_ = absl::make_unique<webrtc_win::ScopedCOMInitializer>(
henrikaec9c7452018-06-08 16:10:03 +0200588 webrtc_win::ScopedCOMInitializer::kMTA);
589 EXPECT_TRUE(com_initializer_->Succeeded());
590 EXPECT_TRUE(webrtc_win::core_audio_utility::IsSupported());
591 EXPECT_TRUE(webrtc_win::core_audio_utility::IsMMCSSSupported());
henrika5b6afc02018-09-05 14:34:40 +0200592 return CreateWindowsCoreAudioAudioDeviceModuleForTest();
henrikaec9c7452018-06-08 16:10:03 +0200593#else
594 return nullptr;
595#endif
596 } else {
597 return nullptr;
598 }
599 }
600
henrikaf2f91fa2017-03-17 04:26:22 -0700601 void StartPlayout() {
602 EXPECT_FALSE(audio_device()->Playing());
603 EXPECT_EQ(0, audio_device()->InitPlayout());
604 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
605 EXPECT_EQ(0, audio_device()->StartPlayout());
606 EXPECT_TRUE(audio_device()->Playing());
607 }
608
609 void StopPlayout() {
610 EXPECT_EQ(0, audio_device()->StopPlayout());
611 EXPECT_FALSE(audio_device()->Playing());
612 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
613 }
614
615 void StartRecording() {
616 EXPECT_FALSE(audio_device()->Recording());
617 EXPECT_EQ(0, audio_device()->InitRecording());
618 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
619 EXPECT_EQ(0, audio_device()->StartRecording());
620 EXPECT_TRUE(audio_device()->Recording());
621 }
622
623 void StopRecording() {
624 EXPECT_EQ(0, audio_device()->StopRecording());
625 EXPECT_FALSE(audio_device()->Recording());
626 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
627 }
628
henrikaec9c7452018-06-08 16:10:03 +0200629 bool NewWindowsAudioDeviceModuleIsUsed() {
630#ifdef WEBRTC_WIN
631 AudioDeviceModule::AudioLayer audio_layer;
632 EXPECT_EQ(0, audio_device()->ActiveAudioLayer(&audio_layer));
633 if (audio_layer == AudioDeviceModule::kWindowsCoreAudio2) {
634 // Default device is always added as first element in the list and the
635 // default communication device as the second element. Hence, the list
636 // contains two extra elements in this case.
637 return true;
638 }
639#endif
640 return false;
641 }
642
henrikaf2f91fa2017-03-17 04:26:22 -0700643 private:
henrikaec9c7452018-06-08 16:10:03 +0200644#ifdef WEBRTC_WIN
645 // Windows Core Audio based ADM needs to run on a COM initialized thread.
646 std::unique_ptr<webrtc_win::ScopedCOMInitializer> com_initializer_;
647#endif
648 AudioDeviceModule::AudioLayer audio_layer_;
henrikaf2f91fa2017-03-17 04:26:22 -0700649 bool requirements_satisfied_ = true;
650 rtc::Event event_;
henrika5b6afc02018-09-05 14:34:40 +0200651 rtc::scoped_refptr<AudioDeviceModuleForTest> audio_device_;
henrikaf2f91fa2017-03-17 04:26:22 -0700652 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700653};
654
henrikaec9c7452018-06-08 16:10:03 +0200655// Instead of using the test fixture, verify that the different factory methods
656// work as intended.
657TEST(AudioDeviceTestWin, ConstructDestructWithFactory) {
658 rtc::scoped_refptr<AudioDeviceModule> audio_device;
659 // The default factory should work for all platforms when a default ADM is
660 // requested.
661 audio_device =
662 AudioDeviceModule::Create(AudioDeviceModule::kPlatformDefaultAudio);
663 EXPECT_TRUE(audio_device);
664 audio_device = nullptr;
665#ifdef WEBRTC_WIN
666 // For Windows, the old factory method creates an ADM where the platform-
667 // specific parts are implemented by an AudioDeviceGeneric object. Verify
668 // that the old factory can't be used in combination with the latest audio
669 // layer AudioDeviceModule::kWindowsCoreAudio2.
670 audio_device =
671 AudioDeviceModule::Create(AudioDeviceModule::kWindowsCoreAudio2);
672 EXPECT_FALSE(audio_device);
673 audio_device = nullptr;
674 // Instead, ensure that the new dedicated factory method called
675 // CreateWindowsCoreAudioAudioDeviceModule() can be used on Windows and that
676 // it sets the audio layer to kWindowsCoreAudio2 implicitly. Note that, the
677 // new ADM for Windows must be created on a COM thread.
678 webrtc_win::ScopedCOMInitializer com_initializer(
679 webrtc_win::ScopedCOMInitializer::kMTA);
680 EXPECT_TRUE(com_initializer.Succeeded());
681 audio_device = CreateWindowsCoreAudioAudioDeviceModule();
682 EXPECT_TRUE(audio_device);
683 AudioDeviceModule::AudioLayer audio_layer;
684 EXPECT_EQ(0, audio_device->ActiveAudioLayer(&audio_layer));
685 EXPECT_EQ(audio_layer, AudioDeviceModule::kWindowsCoreAudio2);
686#endif
687}
henrikaf2f91fa2017-03-17 04:26:22 -0700688
henrikaec9c7452018-06-08 16:10:03 +0200689// Uses the test fixture to create, initialize and destruct the ADM.
690TEST_P(AudioDeviceTest, ConstructDestructDefault) {}
691
692TEST_P(AudioDeviceTest, InitTerminate) {
henrikaf2f91fa2017-03-17 04:26:22 -0700693 SKIP_TEST_IF_NOT(requirements_satisfied());
694 // Initialization is part of the test fixture.
695 EXPECT_TRUE(audio_device()->Initialized());
696 EXPECT_EQ(0, audio_device()->Terminate());
697 EXPECT_FALSE(audio_device()->Initialized());
698}
699
henrikaec9c7452018-06-08 16:10:03 +0200700// Enumerate all available and active output devices.
701TEST_P(AudioDeviceTest, PlayoutDeviceNames) {
henrikaf2f91fa2017-03-17 04:26:22 -0700702 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaec9c7452018-06-08 16:10:03 +0200703 char device_name[kAdmMaxDeviceNameSize];
704 char unique_id[kAdmMaxGuidSize];
705 int num_devices = audio_device()->PlayoutDevices();
706 if (NewWindowsAudioDeviceModuleIsUsed()) {
707 num_devices += 2;
708 }
709 EXPECT_GT(num_devices, 0);
710 for (int i = 0; i < num_devices; ++i) {
711 EXPECT_EQ(0, audio_device()->PlayoutDeviceName(i, device_name, unique_id));
712 }
713 EXPECT_EQ(-1, audio_device()->PlayoutDeviceName(num_devices, device_name,
714 unique_id));
715}
716
717// Enumerate all available and active input devices.
718TEST_P(AudioDeviceTest, RecordingDeviceNames) {
719 SKIP_TEST_IF_NOT(requirements_satisfied());
720 char device_name[kAdmMaxDeviceNameSize];
721 char unique_id[kAdmMaxGuidSize];
722 int num_devices = audio_device()->RecordingDevices();
723 if (NewWindowsAudioDeviceModuleIsUsed()) {
724 num_devices += 2;
725 }
726 EXPECT_GT(num_devices, 0);
727 for (int i = 0; i < num_devices; ++i) {
728 EXPECT_EQ(0,
729 audio_device()->RecordingDeviceName(i, device_name, unique_id));
730 }
731 EXPECT_EQ(-1, audio_device()->RecordingDeviceName(num_devices, device_name,
732 unique_id));
733}
734
735// Counts number of active output devices and ensure that all can be selected.
736TEST_P(AudioDeviceTest, SetPlayoutDevice) {
737 SKIP_TEST_IF_NOT(requirements_satisfied());
738 int num_devices = audio_device()->PlayoutDevices();
739 if (NewWindowsAudioDeviceModuleIsUsed()) {
740 num_devices += 2;
741 }
742 EXPECT_GT(num_devices, 0);
743 // Verify that all available playout devices can be set (not enabled yet).
744 for (int i = 0; i < num_devices; ++i) {
745 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(i));
746 }
747 EXPECT_EQ(-1, audio_device()->SetPlayoutDevice(num_devices));
748#ifdef WEBRTC_WIN
749 // On Windows, verify the alternative method where the user can select device
750 // by role.
751 EXPECT_EQ(
752 0, audio_device()->SetPlayoutDevice(AudioDeviceModule::kDefaultDevice));
753 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(
754 AudioDeviceModule::kDefaultCommunicationDevice));
755#endif
756}
757
758// Counts number of active input devices and ensure that all can be selected.
759TEST_P(AudioDeviceTest, SetRecordingDevice) {
760 SKIP_TEST_IF_NOT(requirements_satisfied());
761 int num_devices = audio_device()->RecordingDevices();
762 if (NewWindowsAudioDeviceModuleIsUsed()) {
763 num_devices += 2;
764 }
765 EXPECT_GT(num_devices, 0);
766 // Verify that all available recording devices can be set (not enabled yet).
767 for (int i = 0; i < num_devices; ++i) {
768 EXPECT_EQ(0, audio_device()->SetRecordingDevice(i));
769 }
770 EXPECT_EQ(-1, audio_device()->SetRecordingDevice(num_devices));
771#ifdef WEBRTC_WIN
772 // On Windows, verify the alternative method where the user can select device
773 // by role.
774 EXPECT_EQ(
775 0, audio_device()->SetRecordingDevice(AudioDeviceModule::kDefaultDevice));
776 EXPECT_EQ(0, audio_device()->SetRecordingDevice(
777 AudioDeviceModule::kDefaultCommunicationDevice));
778#endif
779}
780
781// Tests Start/Stop playout without any registered audio callback.
782TEST_P(AudioDeviceTest, StartStopPlayout) {
783 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaf2f91fa2017-03-17 04:26:22 -0700784 StartPlayout();
785 StopPlayout();
786}
787
788// Tests Start/Stop recording without any registered audio callback.
henrikaec9c7452018-06-08 16:10:03 +0200789TEST_P(AudioDeviceTest, StartStopRecording) {
henrikaf2f91fa2017-03-17 04:26:22 -0700790 SKIP_TEST_IF_NOT(requirements_satisfied());
791 StartRecording();
792 StopRecording();
henrikaf2f91fa2017-03-17 04:26:22 -0700793}
794
henrika6b3e1a22017-09-25 16:34:30 +0200795// Tests Init/Stop/Init recording without any registered audio callback.
796// See https://bugs.chromium.org/p/webrtc/issues/detail?id=8041 for details
797// on why this test is useful.
henrikaec9c7452018-06-08 16:10:03 +0200798TEST_P(AudioDeviceTest, InitStopInitRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200799 SKIP_TEST_IF_NOT(requirements_satisfied());
800 EXPECT_EQ(0, audio_device()->InitRecording());
801 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
802 StopRecording();
803 EXPECT_EQ(0, audio_device()->InitRecording());
804 StopRecording();
805}
806
807// Tests Init/Stop/Init recording while playout is active.
henrikaec9c7452018-06-08 16:10:03 +0200808TEST_P(AudioDeviceTest, InitStopInitRecordingWhilePlaying) {
henrika6b3e1a22017-09-25 16:34:30 +0200809 SKIP_TEST_IF_NOT(requirements_satisfied());
810 StartPlayout();
811 EXPECT_EQ(0, audio_device()->InitRecording());
812 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
813 StopRecording();
814 EXPECT_EQ(0, audio_device()->InitRecording());
815 StopRecording();
816 StopPlayout();
817}
818
819// Tests Init/Stop/Init playout without any registered audio callback.
henrikaec9c7452018-06-08 16:10:03 +0200820TEST_P(AudioDeviceTest, InitStopInitPlayout) {
henrika6b3e1a22017-09-25 16:34:30 +0200821 SKIP_TEST_IF_NOT(requirements_satisfied());
822 EXPECT_EQ(0, audio_device()->InitPlayout());
823 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
824 StopPlayout();
825 EXPECT_EQ(0, audio_device()->InitPlayout());
826 StopPlayout();
827}
828
829// Tests Init/Stop/Init playout while recording is active.
henrikaec9c7452018-06-08 16:10:03 +0200830TEST_P(AudioDeviceTest, InitStopInitPlayoutWhileRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200831 SKIP_TEST_IF_NOT(requirements_satisfied());
832 StartRecording();
833 EXPECT_EQ(0, audio_device()->InitPlayout());
834 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
835 StopPlayout();
836 EXPECT_EQ(0, audio_device()->InitPlayout());
837 StopPlayout();
838 StopRecording();
839}
840
henrika5b6afc02018-09-05 14:34:40 +0200841// TODO(henrika): restart without intermediate destruction is currently only
842// supported on Windows.
843#ifdef WEBRTC_WIN
844// Tests Start/Stop playout followed by a second session (emulates a restart
845// triggered by a user using public APIs).
846TEST_P(AudioDeviceTest, StartStopPlayoutWithExternalRestart) {
847 SKIP_TEST_IF_NOT(requirements_satisfied());
848 StartPlayout();
849 StopPlayout();
850 // Restart playout without destroying the ADM in between. Ensures that we
851 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
852 StartPlayout();
853 StopPlayout();
854}
855
856// Tests Start/Stop recording followed by a second session (emulates a restart
857// triggered by a user using public APIs).
858TEST_P(AudioDeviceTest, StartStopRecordingWithExternalRestart) {
859 SKIP_TEST_IF_NOT(requirements_satisfied());
860 StartRecording();
861 StopRecording();
862 // Restart recording without destroying the ADM in between. Ensures that we
863 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
864 StartRecording();
865 StopRecording();
866}
867
868// Tests Start/Stop playout followed by a second session (emulates a restart
869// triggered by an internal callback e.g. corresponding to a device switch).
870// Note that, internal restart is only supported in combination with the latest
871// Windows ADM.
872TEST_P(AudioDeviceTest, StartStopPlayoutWithInternalRestart) {
873 SKIP_TEST_IF_NOT(requirements_satisfied());
874 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
875 return;
876 }
877 MockAudioTransport mock(TransportType::kPlay);
878 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
879 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
880 .Times(AtLeast(kNumCallbacks));
881 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
882 StartPlayout();
883 event()->Wait(kTestTimeOutInMilliseconds);
884 EXPECT_TRUE(audio_device()->Playing());
885 // Restart playout but without stopping the internal audio thread.
886 // This procedure uses a non-public test API and it emulates what happens
887 // inside the ADM when e.g. a device is removed.
888 EXPECT_EQ(0, audio_device()->RestartPlayoutInternally());
889
890 // Run basic tests of public APIs while a restart attempt is active.
891 // These calls should now be very thin and not trigger any new actions.
892 EXPECT_EQ(-1, audio_device()->StopPlayout());
893 EXPECT_TRUE(audio_device()->Playing());
894 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
895 EXPECT_EQ(0, audio_device()->InitPlayout());
896 EXPECT_EQ(0, audio_device()->StartPlayout());
897
898 // Wait until audio has restarted and a new sequence of audio callbacks
899 // becomes active.
900 // TODO(henrika): is it possible to verify that the internal state transition
901 // is Stop->Init->Start?
902 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
903 mock.ResetCallbackCounters();
904 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
905 .Times(AtLeast(kNumCallbacks));
906 event()->Wait(kTestTimeOutInMilliseconds);
907 EXPECT_TRUE(audio_device()->Playing());
908 // Stop playout and the audio thread after successful internal restart.
909 StopPlayout();
910}
911
912// Tests Start/Stop recording followed by a second session (emulates a restart
913// triggered by an internal callback e.g. corresponding to a device switch).
914// Note that, internal restart is only supported in combination with the latest
915// Windows ADM.
916TEST_P(AudioDeviceTest, StartStopRecordingWithInternalRestart) {
917 SKIP_TEST_IF_NOT(requirements_satisfied());
918 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
919 return;
920 }
921 MockAudioTransport mock(TransportType::kRecord);
922 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
923 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
924 false, _))
925 .Times(AtLeast(kNumCallbacks));
926 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
927 StartRecording();
928 event()->Wait(kTestTimeOutInMilliseconds);
929 EXPECT_TRUE(audio_device()->Recording());
930 // Restart recording but without stopping the internal audio thread.
931 // This procedure uses a non-public test API and it emulates what happens
932 // inside the ADM when e.g. a device is removed.
933 EXPECT_EQ(0, audio_device()->RestartRecordingInternally());
934
935 // Run basic tests of public APIs while a restart attempt is active.
936 // These calls should now be very thin and not trigger any new actions.
937 EXPECT_EQ(-1, audio_device()->StopRecording());
938 EXPECT_TRUE(audio_device()->Recording());
939 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
940 EXPECT_EQ(0, audio_device()->InitRecording());
941 EXPECT_EQ(0, audio_device()->StartRecording());
942
943 // Wait until audio has restarted and a new sequence of audio callbacks
944 // becomes active.
945 // TODO(henrika): is it possible to verify that the internal state transition
946 // is Stop->Init->Start?
947 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
948 mock.ResetCallbackCounters();
949 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
950 false, _))
951 .Times(AtLeast(kNumCallbacks));
952 event()->Wait(kTestTimeOutInMilliseconds);
953 EXPECT_TRUE(audio_device()->Recording());
954 // Stop recording and the audio thread after successful internal restart.
955 StopRecording();
956}
957#endif // #ifdef WEBRTC_WIN
958
henrikaf2f91fa2017-03-17 04:26:22 -0700959// Start playout and verify that the native audio layer starts asking for real
960// audio samples to play out using the NeedMorePlayData() callback.
961// Note that we can't add expectations on audio parameters in EXPECT_CALL
962// since parameter are not provided in the each callback. We therefore test and
963// verify the parameters in the fake audio transport implementation instead.
henrikaec9c7452018-06-08 16:10:03 +0200964TEST_P(AudioDeviceTest, StartPlayoutVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700965 SKIP_TEST_IF_NOT(requirements_satisfied());
966 MockAudioTransport mock(TransportType::kPlay);
henrikae24991d2017-04-06 01:14:23 -0700967 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700968 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
969 .Times(AtLeast(kNumCallbacks));
970 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
971 StartPlayout();
972 event()->Wait(kTestTimeOutInMilliseconds);
973 StopPlayout();
974}
975
976// Start recording and verify that the native audio layer starts providing real
977// audio samples using the RecordedDataIsAvailable() callback.
henrikaec9c7452018-06-08 16:10:03 +0200978TEST_P(AudioDeviceTest, StartRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700979 SKIP_TEST_IF_NOT(requirements_satisfied());
980 MockAudioTransport mock(TransportType::kRecord);
henrikae24991d2017-04-06 01:14:23 -0700981 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700982 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
983 false, _))
984 .Times(AtLeast(kNumCallbacks));
985 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
986 StartRecording();
987 event()->Wait(kTestTimeOutInMilliseconds);
988 StopRecording();
989}
990
991// Start playout and recording (full-duplex audio) and verify that audio is
992// active in both directions.
henrikaec9c7452018-06-08 16:10:03 +0200993TEST_P(AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700994 SKIP_TEST_IF_NOT(requirements_satisfied());
995 MockAudioTransport mock(TransportType::kPlayAndRecord);
henrikae24991d2017-04-06 01:14:23 -0700996 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700997 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
998 .Times(AtLeast(kNumCallbacks));
999 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
1000 false, _))
1001 .Times(AtLeast(kNumCallbacks));
1002 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1003 StartPlayout();
1004 StartRecording();
1005 event()->Wait(kTestTimeOutInMilliseconds);
1006 StopRecording();
1007 StopPlayout();
1008}
1009
henrikae24991d2017-04-06 01:14:23 -07001010// Start playout and recording and store recorded data in an intermediate FIFO
1011// buffer from which the playout side then reads its samples in the same order
1012// as they were stored. Under ideal circumstances, a callback sequence would
1013// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
1014// means 'packet played'. Under such conditions, the FIFO would contain max 1,
1015// with an average somewhere in (0,1) depending on how long the packets are
1016// buffered. However, under more realistic conditions, the size
1017// of the FIFO will vary more due to an unbalance between the two sides.
1018// This test tries to verify that the device maintains a balanced callback-
1019// sequence by running in loopback for a few seconds while measuring the size
1020// (max and average) of the FIFO. The size of the FIFO is increased by the
1021// recording side and decreased by the playout side.
henrikaec9c7452018-06-08 16:10:03 +02001022TEST_P(AudioDeviceTest, RunPlayoutAndRecordingInFullDuplex) {
henrikae24991d2017-04-06 01:14:23 -07001023 SKIP_TEST_IF_NOT(requirements_satisfied());
1024 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1025 FifoAudioStream audio_stream;
1026 mock.HandleCallbacks(event(), &audio_stream,
1027 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
1028 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001029 // Run both sides using the same channel configuration to avoid conversions
1030 // between mono/stereo while running in full duplex mode. Also, some devices
1031 // (mainly on Windows) do not support mono.
1032 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1033 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrikae24991d2017-04-06 01:14:23 -07001034 StartPlayout();
1035 StartRecording();
henrika714e5cd2017-04-20 08:03:11 -07001036 event()->Wait(static_cast<int>(
1037 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec)));
henrikae24991d2017-04-06 01:14:23 -07001038 StopRecording();
1039 StopPlayout();
1040 // This thresholds is set rather high to accommodate differences in hardware
1041 // in several devices. The main idea is to capture cases where a very large
henrikab6ca7212017-10-06 12:47:52 +02001042 // latency is built up. See http://bugs.webrtc.org/7744 for examples on
1043 // bots where relatively large average latencies can happen.
1044 EXPECT_LE(audio_stream.average_size(), 25u);
henrikae24991d2017-04-06 01:14:23 -07001045 PRINT("\n");
1046}
1047
henrika5b6afc02018-09-05 14:34:40 +02001048// Runs audio in full duplex until user hits Enter. Intended as a manual test
1049// to ensure that the audio quality is good and that real device switches works
1050// as intended.
1051TEST_P(AudioDeviceTest,
1052 DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey) {
1053 SKIP_TEST_IF_NOT(requirements_satisfied());
1054 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
1055 return;
1056 }
1057 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1058 FifoAudioStream audio_stream;
1059 mock.HandleCallbacks(&audio_stream);
1060 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1061 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1062 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
1063 // Ensure that the sample rate for both directions are identical so that we
1064 // always can listen to our own voice. Will lead to rate conversion (and
1065 // higher latency) if the native sample rate is not 48kHz.
1066 EXPECT_EQ(0, audio_device()->SetPlayoutSampleRate(48000));
1067 EXPECT_EQ(0, audio_device()->SetRecordingSampleRate(48000));
1068 StartPlayout();
1069 StartRecording();
1070 do {
1071 PRINT("Loopback audio is active at 48kHz. Press Enter to stop.\n");
1072 } while (getchar() != '\n');
1073 StopRecording();
1074 StopPlayout();
1075}
1076
henrika714e5cd2017-04-20 08:03:11 -07001077// Measures loopback latency and reports the min, max and average values for
1078// a full duplex audio session.
1079// The latency is measured like so:
1080// - Insert impulses periodically on the output side.
1081// - Detect the impulses on the input side.
1082// - Measure the time difference between the transmit time and receive time.
1083// - Store time differences in a vector and calculate min, max and average.
1084// This test needs the '--gtest_also_run_disabled_tests' flag to run and also
1085// some sort of audio feedback loop. E.g. a headset where the mic is placed
1086// close to the speaker to ensure highest possible echo. It is also recommended
1087// to run the test at highest possible output volume.
henrikaec9c7452018-06-08 16:10:03 +02001088TEST_P(AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
henrika714e5cd2017-04-20 08:03:11 -07001089 SKIP_TEST_IF_NOT(requirements_satisfied());
1090 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1091 LatencyAudioStream audio_stream;
1092 mock.HandleCallbacks(event(), &audio_stream,
1093 kMeasureLatencyTimeInSec * kNumCallbacksPerSecond);
1094 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001095 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1096 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrika714e5cd2017-04-20 08:03:11 -07001097 StartPlayout();
1098 StartRecording();
1099 event()->Wait(static_cast<int>(
1100 std::max(kTestTimeOutInMilliseconds, 1000 * kMeasureLatencyTimeInSec)));
1101 StopRecording();
1102 StopPlayout();
henrikac7d93582018-09-14 15:37:34 +02001103 // Verify that a sufficient number of transmitted impulses are detected.
1104 EXPECT_GE(audio_stream.num_latency_values(),
henrika714e5cd2017-04-20 08:03:11 -07001105 static_cast<size_t>(
henrikac7d93582018-09-14 15:37:34 +02001106 kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 2));
henrika714e5cd2017-04-20 08:03:11 -07001107 // Print out min, max and average delay values for debugging purposes.
1108 audio_stream.PrintResults();
1109}
1110
henrikaec9c7452018-06-08 16:10:03 +02001111#ifdef WEBRTC_WIN
1112// Test two different audio layers (or rather two different Core Audio
1113// implementations) for Windows.
1114INSTANTIATE_TEST_CASE_P(
1115 AudioLayerWin,
1116 AudioDeviceTest,
1117 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio,
1118 AudioDeviceModule::kWindowsCoreAudio2));
1119#else
1120// For all platforms but Windows, only test the default audio layer.
1121INSTANTIATE_TEST_CASE_P(
1122 AudioLayer,
1123 AudioDeviceTest,
1124 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio));
1125#endif
1126
henrikaf2f91fa2017-03-17 04:26:22 -07001127} // namespace webrtc