blob: 48cb43273c96ae26ea9be7eecac3e37ffd11acde [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
henrikae24991d2017-04-06 01:14:23 -070050// #define ENABLE_DEBUG_PRINTF
51#ifdef ENABLE_DEBUG_PRINTF
52#define PRINTD(...) fprintf(stderr, __VA_ARGS__);
53#else
54#define PRINTD(...) ((void)0)
55#endif
56#define PRINT(...) fprintf(stderr, __VA_ARGS__);
57
henrikaf2f91fa2017-03-17 04:26:22 -070058// Don't run these tests in combination with sanitizers.
59#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
60#define SKIP_TEST_IF_NOT(requirements_satisfied) \
61 do { \
62 if (!requirements_satisfied) { \
63 return; \
64 } \
65 } while (false)
66#else
67// Or if other audio-related requirements are not met.
68#define SKIP_TEST_IF_NOT(requirements_satisfied) \
69 do { \
70 return; \
71 } while (false)
72#endif
73
74// Number of callbacks (input or output) the tests waits for before we set
75// an event indicating that the test was OK.
henrikae24991d2017-04-06 01:14:23 -070076static constexpr size_t kNumCallbacks = 10;
henrikaf2f91fa2017-03-17 04:26:22 -070077// Max amount of time we wait for an event to be set while counting callbacks.
henrika714e5cd2017-04-20 08:03:11 -070078static constexpr size_t kTestTimeOutInMilliseconds = 10 * 1000;
henrikae24991d2017-04-06 01:14:23 -070079// Average number of audio callbacks per second assuming 10ms packet size.
80static constexpr size_t kNumCallbacksPerSecond = 100;
81// Run the full-duplex test during this time (unit is in seconds).
henrika714e5cd2017-04-20 08:03:11 -070082static constexpr size_t kFullDuplexTimeInSec = 5;
83// Length of round-trip latency measurements. Number of deteced impulses
84// shall be kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 1 since the
85// last transmitted pulse is not used.
86static constexpr size_t kMeasureLatencyTimeInSec = 10;
87// Sets the number of impulses per second in the latency test.
88static constexpr size_t kImpulseFrequencyInHz = 1;
89// Utilized in round-trip latency measurements to avoid capturing noise samples.
90static constexpr int kImpulseThreshold = 1000;
henrikaf2f91fa2017-03-17 04:26:22 -070091
92enum class TransportType {
93 kInvalid,
94 kPlay,
95 kRecord,
96 kPlayAndRecord,
97};
henrikae24991d2017-04-06 01:14:23 -070098
99// Interface for processing the audio stream. Real implementations can e.g.
100// run audio in loopback, read audio from a file or perform latency
101// measurements.
102class AudioStream {
103 public:
henrikaeb98c722018-03-20 12:54:07 +0100104 virtual void Write(rtc::ArrayView<const int16_t> source) = 0;
105 virtual void Read(rtc::ArrayView<int16_t> destination) = 0;
henrikae24991d2017-04-06 01:14:23 -0700106
107 virtual ~AudioStream() = default;
108};
109
henrika714e5cd2017-04-20 08:03:11 -0700110// Converts index corresponding to position within a 10ms buffer into a
111// delay value in milliseconds.
112// Example: index=240, frames_per_10ms_buffer=480 => 5ms as output.
113int IndexToMilliseconds(size_t index, size_t frames_per_10ms_buffer) {
114 return rtc::checked_cast<int>(
115 10.0 * (static_cast<double>(index) / frames_per_10ms_buffer) + 0.5);
116}
117
henrikaf2f91fa2017-03-17 04:26:22 -0700118} // namespace
119
henrikae24991d2017-04-06 01:14:23 -0700120// Simple first in first out (FIFO) class that wraps a list of 16-bit audio
121// buffers of fixed size and allows Write and Read operations. The idea is to
122// store recorded audio buffers (using Write) and then read (using Read) these
123// stored buffers with as short delay as possible when the audio layer needs
124// data to play out. The number of buffers in the FIFO will stabilize under
125// normal conditions since there will be a balance between Write and Read calls.
126// The container is a std::list container and access is protected with a lock
127// since both sides (playout and recording) are driven by its own thread.
128// Note that, we know by design that the size of the audio buffer will not
henrikac7d93582018-09-14 15:37:34 +0200129// change over time and that both sides will in most cases use the same size.
henrikae24991d2017-04-06 01:14:23 -0700130class FifoAudioStream : public AudioStream {
131 public:
henrikaeb98c722018-03-20 12:54:07 +0100132 void Write(rtc::ArrayView<const int16_t> source) override {
henrikae24991d2017-04-06 01:14:23 -0700133 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
134 const size_t size = [&] {
135 rtc::CritScope lock(&lock_);
136 fifo_.push_back(Buffer16(source.data(), source.size()));
137 return fifo_.size();
138 }();
139 if (size > max_size_) {
140 max_size_ = size;
141 }
142 // Add marker once per second to signal that audio is active.
143 if (write_count_++ % 100 == 0) {
144 PRINT(".");
145 }
146 written_elements_ += size;
147 }
148
henrikaeb98c722018-03-20 12:54:07 +0100149 void Read(rtc::ArrayView<int16_t> destination) override {
henrikae24991d2017-04-06 01:14:23 -0700150 rtc::CritScope lock(&lock_);
151 if (fifo_.empty()) {
152 std::fill(destination.begin(), destination.end(), 0);
153 } else {
154 const Buffer16& buffer = fifo_.front();
henrikac7d93582018-09-14 15:37:34 +0200155 if (buffer.size() == destination.size()) {
156 // Default case where input and output uses same sample rate and
157 // channel configuration. No conversion is needed.
158 std::copy(buffer.begin(), buffer.end(), destination.begin());
159 } else if (destination.size() == 2 * buffer.size()) {
160 // Recorded input signal in |buffer| is in mono. Do channel upmix to
161 // match stereo output (1 -> 2).
162 for (size_t i = 0; i < buffer.size(); ++i) {
163 destination[2 * i] = buffer[i];
164 destination[2 * i + 1] = buffer[i];
165 }
166 } else if (buffer.size() == 2 * destination.size()) {
167 // Recorded input signal in |buffer| is in stereo. Do channel downmix
168 // to match mono output (2 -> 1).
169 for (size_t i = 0; i < destination.size(); ++i) {
170 destination[i] =
171 (static_cast<int32_t>(buffer[2 * i]) + buffer[2 * i + 1]) / 2;
172 }
173 } else {
174 RTC_NOTREACHED() << "Required conversion is not support";
175 }
henrikae24991d2017-04-06 01:14:23 -0700176 fifo_.pop_front();
177 }
178 }
179
180 size_t size() const {
181 rtc::CritScope lock(&lock_);
182 return fifo_.size();
183 }
184
185 size_t max_size() const {
186 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
187 return max_size_;
188 }
189
190 size_t average_size() const {
191 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
192 return 0.5 + static_cast<float>(written_elements_ / write_count_);
193 }
194
195 using Buffer16 = rtc::BufferT<int16_t>;
196
197 rtc::CriticalSection lock_;
198 rtc::RaceChecker race_checker_;
199
danilchap56359be2017-09-07 07:53:45 -0700200 std::list<Buffer16> fifo_ RTC_GUARDED_BY(lock_);
201 size_t write_count_ RTC_GUARDED_BY(race_checker_) = 0;
202 size_t max_size_ RTC_GUARDED_BY(race_checker_) = 0;
203 size_t written_elements_ RTC_GUARDED_BY(race_checker_) = 0;
henrikae24991d2017-04-06 01:14:23 -0700204};
205
henrika714e5cd2017-04-20 08:03:11 -0700206// Inserts periodic impulses and measures the latency between the time of
207// transmission and time of receiving the same impulse.
208class LatencyAudioStream : public AudioStream {
209 public:
210 LatencyAudioStream() {
211 // Delay thread checkers from being initialized until first callback from
212 // respective thread.
213 read_thread_checker_.DetachFromThread();
214 write_thread_checker_.DetachFromThread();
215 }
216
217 // Insert periodic impulses in first two samples of |destination|.
henrikaeb98c722018-03-20 12:54:07 +0100218 void Read(rtc::ArrayView<int16_t> destination) override {
henrika714e5cd2017-04-20 08:03:11 -0700219 RTC_DCHECK_RUN_ON(&read_thread_checker_);
henrika714e5cd2017-04-20 08:03:11 -0700220 if (read_count_ == 0) {
221 PRINT("[");
222 }
223 read_count_++;
224 std::fill(destination.begin(), destination.end(), 0);
225 if (read_count_ % (kNumCallbacksPerSecond / kImpulseFrequencyInHz) == 0) {
226 PRINT(".");
227 {
228 rtc::CritScope lock(&lock_);
229 if (!pulse_time_) {
Oskar Sundbom6ad9f262017-11-16 10:53:39 +0100230 pulse_time_ = rtc::TimeMillis();
henrika714e5cd2017-04-20 08:03:11 -0700231 }
232 }
233 constexpr int16_t impulse = std::numeric_limits<int16_t>::max();
234 std::fill_n(destination.begin(), 2, impulse);
235 }
236 }
237
238 // Detect received impulses in |source|, derive time between transmission and
239 // detection and add the calculated delay to list of latencies.
henrikaeb98c722018-03-20 12:54:07 +0100240 void Write(rtc::ArrayView<const int16_t> source) override {
henrika714e5cd2017-04-20 08:03:11 -0700241 RTC_DCHECK_RUN_ON(&write_thread_checker_);
242 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
243 rtc::CritScope lock(&lock_);
244 write_count_++;
245 if (!pulse_time_) {
246 // Avoid detection of new impulse response until a new impulse has
247 // been transmitted (sets |pulse_time_| to value larger than zero).
248 return;
249 }
250 // Find index (element position in vector) of the max element.
251 const size_t index_of_max =
252 std::max_element(source.begin(), source.end()) - source.begin();
253 // Derive time between transmitted pulse and received pulse if the level
254 // is high enough (removes noise).
255 const size_t max = source[index_of_max];
256 if (max > kImpulseThreshold) {
257 PRINTD("(%zu, %zu)", max, index_of_max);
258 int64_t now_time = rtc::TimeMillis();
259 int extra_delay = IndexToMilliseconds(index_of_max, source.size());
260 PRINTD("[%d]", rtc::checked_cast<int>(now_time - pulse_time_));
261 PRINTD("[%d]", extra_delay);
262 // Total latency is the difference between transmit time and detection
263 // tome plus the extra delay within the buffer in which we detected the
264 // received impulse. It is transmitted at sample 0 but can be received
265 // at sample N where N > 0. The term |extra_delay| accounts for N and it
266 // is a value between 0 and 10ms.
267 latencies_.push_back(now_time - *pulse_time_ + extra_delay);
268 pulse_time_.reset();
269 } else {
270 PRINTD("-");
271 }
272 }
273
274 size_t num_latency_values() const {
275 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
276 return latencies_.size();
277 }
278
279 int min_latency() const {
280 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
281 if (latencies_.empty())
282 return 0;
283 return *std::min_element(latencies_.begin(), latencies_.end());
284 }
285
286 int max_latency() const {
287 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
288 if (latencies_.empty())
289 return 0;
290 return *std::max_element(latencies_.begin(), latencies_.end());
291 }
292
293 int average_latency() const {
294 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
295 if (latencies_.empty())
296 return 0;
297 return 0.5 + static_cast<double>(
298 std::accumulate(latencies_.begin(), latencies_.end(), 0)) /
299 latencies_.size();
300 }
301
302 void PrintResults() const {
303 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
304 PRINT("] ");
305 for (auto it = latencies_.begin(); it != latencies_.end(); ++it) {
306 PRINTD("%d ", *it);
307 }
308 PRINT("\n");
309 PRINT("[..........] [min, max, avg]=[%d, %d, %d] ms\n", min_latency(),
310 max_latency(), average_latency());
311 }
312
313 rtc::CriticalSection lock_;
314 rtc::RaceChecker race_checker_;
315 rtc::ThreadChecker read_thread_checker_;
316 rtc::ThreadChecker write_thread_checker_;
317
Danil Chapovalov196100e2018-06-21 10:17:24 +0200318 absl::optional<int64_t> pulse_time_ RTC_GUARDED_BY(lock_);
danilchap56359be2017-09-07 07:53:45 -0700319 std::vector<int> latencies_ RTC_GUARDED_BY(race_checker_);
Niels Möller1e062892018-02-07 10:18:32 +0100320 size_t read_count_ RTC_GUARDED_BY(read_thread_checker_) = 0;
321 size_t write_count_ RTC_GUARDED_BY(write_thread_checker_) = 0;
henrika714e5cd2017-04-20 08:03:11 -0700322};
323
henrikaf2f91fa2017-03-17 04:26:22 -0700324// Mocks the AudioTransport object and proxies actions for the two callbacks
325// (RecordedDataIsAvailable and NeedMorePlayData) to different implementations
326// of AudioStreamInterface.
327class MockAudioTransport : public test::MockAudioTransport {
328 public:
329 explicit MockAudioTransport(TransportType type) : type_(type) {}
330 ~MockAudioTransport() {}
331
332 // Set default actions of the mock object. We are delegating to fake
333 // implementation where the number of callbacks is counted and an event
334 // is set after a certain number of callbacks. Audio parameters are also
335 // checked.
henrikae24991d2017-04-06 01:14:23 -0700336 void HandleCallbacks(rtc::Event* event,
337 AudioStream* audio_stream,
338 int num_callbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700339 event_ = event;
henrikae24991d2017-04-06 01:14:23 -0700340 audio_stream_ = audio_stream;
henrikaf2f91fa2017-03-17 04:26:22 -0700341 num_callbacks_ = num_callbacks;
342 if (play_mode()) {
343 ON_CALL(*this, NeedMorePlayData(_, _, _, _, _, _, _, _))
344 .WillByDefault(
345 Invoke(this, &MockAudioTransport::RealNeedMorePlayData));
346 }
347 if (rec_mode()) {
348 ON_CALL(*this, RecordedDataIsAvailable(_, _, _, _, _, _, _, _, _, _))
349 .WillByDefault(
350 Invoke(this, &MockAudioTransport::RealRecordedDataIsAvailable));
351 }
352 }
353
henrika5b6afc02018-09-05 14:34:40 +0200354 // Special constructor used in manual tests where the user wants to run audio
355 // until e.g. a keyboard key is pressed. The event flag is set to nullptr by
356 // default since it is up to the user to stop the test. See e.g.
357 // DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey().
358 void HandleCallbacks(AudioStream* audio_stream) {
359 HandleCallbacks(nullptr, audio_stream, 0);
360 }
361
henrikaf2f91fa2017-03-17 04:26:22 -0700362 int32_t RealRecordedDataIsAvailable(const void* audio_buffer,
363 const size_t samples_per_channel,
364 const size_t bytes_per_frame,
365 const size_t channels,
366 const uint32_t sample_rate,
367 const uint32_t total_delay_ms,
368 const int32_t clock_drift,
369 const uint32_t current_mic_level,
370 const bool typing_status,
371 uint32_t& new_mic_level) {
372 EXPECT_TRUE(rec_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700373 // Store audio parameters once in the first callback. For all other
374 // callbacks, verify that the provided audio parameters are maintained and
375 // that each callback corresponds to 10ms for any given sample rate.
376 if (!record_parameters_.is_complete()) {
377 record_parameters_.reset(sample_rate, channels, samples_per_channel);
378 } else {
379 EXPECT_EQ(samples_per_channel, record_parameters_.frames_per_buffer());
380 EXPECT_EQ(bytes_per_frame, record_parameters_.GetBytesPerFrame());
381 EXPECT_EQ(channels, record_parameters_.channels());
382 EXPECT_EQ(static_cast<int>(sample_rate),
383 record_parameters_.sample_rate());
384 EXPECT_EQ(samples_per_channel,
385 record_parameters_.frames_per_10ms_buffer());
386 }
387 rec_count_++;
henrikae24991d2017-04-06 01:14:23 -0700388 // Write audio data to audio stream object if one has been injected.
389 if (audio_stream_) {
390 audio_stream_->Write(
391 rtc::MakeArrayView(static_cast<const int16_t*>(audio_buffer),
henrikaeb98c722018-03-20 12:54:07 +0100392 samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700393 }
henrikaf2f91fa2017-03-17 04:26:22 -0700394 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200395 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700396 event_->Set();
397 }
398 return 0;
399 }
400
401 int32_t RealNeedMorePlayData(const size_t samples_per_channel,
402 const size_t bytes_per_frame,
403 const size_t channels,
404 const uint32_t sample_rate,
405 void* audio_buffer,
henrikaeb98c722018-03-20 12:54:07 +0100406 size_t& samples_out,
henrikaf2f91fa2017-03-17 04:26:22 -0700407 int64_t* elapsed_time_ms,
408 int64_t* ntp_time_ms) {
409 EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700410 // Store audio parameters once in the first callback. For all other
411 // callbacks, verify that the provided audio parameters are maintained and
412 // that each callback corresponds to 10ms for any given sample rate.
413 if (!playout_parameters_.is_complete()) {
414 playout_parameters_.reset(sample_rate, channels, samples_per_channel);
415 } else {
416 EXPECT_EQ(samples_per_channel, playout_parameters_.frames_per_buffer());
417 EXPECT_EQ(bytes_per_frame, playout_parameters_.GetBytesPerFrame());
418 EXPECT_EQ(channels, playout_parameters_.channels());
419 EXPECT_EQ(static_cast<int>(sample_rate),
420 playout_parameters_.sample_rate());
421 EXPECT_EQ(samples_per_channel,
422 playout_parameters_.frames_per_10ms_buffer());
423 }
424 play_count_++;
henrikaeb98c722018-03-20 12:54:07 +0100425 samples_out = samples_per_channel * channels;
henrikae24991d2017-04-06 01:14:23 -0700426 // Read audio data from audio stream object if one has been injected.
427 if (audio_stream_) {
henrikaeb98c722018-03-20 12:54:07 +0100428 audio_stream_->Read(rtc::MakeArrayView(
429 static_cast<int16_t*>(audio_buffer), samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700430 } else {
431 // Fill the audio buffer with zeros to avoid disturbing audio.
432 const size_t num_bytes = samples_per_channel * bytes_per_frame;
433 std::memset(audio_buffer, 0, num_bytes);
434 }
henrikaf2f91fa2017-03-17 04:26:22 -0700435 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200436 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700437 event_->Set();
438 }
439 return 0;
440 }
441
442 bool ReceivedEnoughCallbacks() {
443 bool recording_done = false;
444 if (rec_mode()) {
445 recording_done = rec_count_ >= num_callbacks_;
446 } else {
447 recording_done = true;
448 }
449 bool playout_done = false;
450 if (play_mode()) {
451 playout_done = play_count_ >= num_callbacks_;
452 } else {
453 playout_done = true;
454 }
455 return recording_done && playout_done;
456 }
457
458 bool play_mode() const {
459 return type_ == TransportType::kPlay ||
460 type_ == TransportType::kPlayAndRecord;
461 }
462
463 bool rec_mode() const {
464 return type_ == TransportType::kRecord ||
465 type_ == TransportType::kPlayAndRecord;
466 }
467
henrika5b6afc02018-09-05 14:34:40 +0200468 void ResetCallbackCounters() {
469 if (play_mode()) {
470 play_count_ = 0;
471 }
472 if (rec_mode()) {
473 rec_count_ = 0;
474 }
475 }
476
henrikaf2f91fa2017-03-17 04:26:22 -0700477 private:
478 TransportType type_ = TransportType::kInvalid;
479 rtc::Event* event_ = nullptr;
henrikae24991d2017-04-06 01:14:23 -0700480 AudioStream* audio_stream_ = nullptr;
henrikaf2f91fa2017-03-17 04:26:22 -0700481 size_t num_callbacks_ = 0;
482 size_t play_count_ = 0;
483 size_t rec_count_ = 0;
484 AudioParameters playout_parameters_;
485 AudioParameters record_parameters_;
486};
487
488// AudioDeviceTest test fixture.
henrikaec9c7452018-06-08 16:10:03 +0200489class AudioDeviceTest
490 : public ::testing::TestWithParam<webrtc::AudioDeviceModule::AudioLayer> {
henrikaf2f91fa2017-03-17 04:26:22 -0700491 protected:
henrikaec9c7452018-06-08 16:10:03 +0200492 AudioDeviceTest() : audio_layer_(GetParam()), event_(false, false) {
Joachim Bauch5d2bb362017-12-20 21:19:49 +0100493#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \
494 !defined(WEBRTC_DUMMY_AUDIO_BUILD)
henrikaf2f91fa2017-03-17 04:26:22 -0700495 rtc::LogMessage::LogToDebug(rtc::LS_INFO);
496 // Add extra logging fields here if needed for debugging.
henrikaec9c7452018-06-08 16:10:03 +0200497 rtc::LogMessage::LogTimestamps();
498 rtc::LogMessage::LogThreads();
499 audio_device_ = CreateAudioDevice();
henrikaf2f91fa2017-03-17 04:26:22 -0700500 EXPECT_NE(audio_device_.get(), nullptr);
501 AudioDeviceModule::AudioLayer audio_layer;
maxmorin33bf69a2017-03-23 04:06:53 -0700502 int got_platform_audio_layer =
503 audio_device_->ActiveAudioLayer(&audio_layer);
henrika919dc2e2017-10-12 14:24:55 +0200504 // First, ensure that a valid audio layer can be activated.
505 if (got_platform_audio_layer != 0) {
henrikaf2f91fa2017-03-17 04:26:22 -0700506 requirements_satisfied_ = false;
507 }
henrika919dc2e2017-10-12 14:24:55 +0200508 // Next, verify that the ADM can be initialized.
henrikaf2f91fa2017-03-17 04:26:22 -0700509 if (requirements_satisfied_) {
henrika919dc2e2017-10-12 14:24:55 +0200510 requirements_satisfied_ = (audio_device_->Init() == 0);
511 }
512 // Finally, ensure that at least one valid device exists in each direction.
513 if (requirements_satisfied_) {
henrikaf2f91fa2017-03-17 04:26:22 -0700514 const int16_t num_playout_devices = audio_device_->PlayoutDevices();
515 const int16_t num_record_devices = audio_device_->RecordingDevices();
516 requirements_satisfied_ =
517 num_playout_devices > 0 && num_record_devices > 0;
518 }
519#else
520 requirements_satisfied_ = false;
521#endif
522 if (requirements_satisfied_) {
523 EXPECT_EQ(0, audio_device_->SetPlayoutDevice(0));
524 EXPECT_EQ(0, audio_device_->InitSpeaker());
525 EXPECT_EQ(0, audio_device_->SetRecordingDevice(0));
526 EXPECT_EQ(0, audio_device_->InitMicrophone());
527 EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
528 EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
henrika0238ba82017-03-28 04:38:29 -0700529 // Avoid asking for input stereo support and always record in mono
530 // since asking can cause issues in combination with remote desktop.
531 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
532 // details.
533 EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
henrikaf2f91fa2017-03-17 04:26:22 -0700534 }
535 }
536
537 virtual ~AudioDeviceTest() {
538 if (audio_device_) {
539 EXPECT_EQ(0, audio_device_->Terminate());
540 }
541 }
542
543 bool requirements_satisfied() const { return requirements_satisfied_; }
544 rtc::Event* event() { return &event_; }
henrika5b6afc02018-09-05 14:34:40 +0200545 AudioDeviceModule::AudioLayer audio_layer() const { return audio_layer_; }
henrikaf2f91fa2017-03-17 04:26:22 -0700546
henrika5b6afc02018-09-05 14:34:40 +0200547 // AudioDeviceModuleForTest extends the default ADM interface with some extra
548 // test methods. Intended for usage in tests only and requires a unique
549 // factory method. See CreateAudioDevice() for details.
550 const rtc::scoped_refptr<AudioDeviceModuleForTest>& audio_device() const {
henrikaf2f91fa2017-03-17 04:26:22 -0700551 return audio_device_;
552 }
553
henrika5b6afc02018-09-05 14:34:40 +0200554 rtc::scoped_refptr<AudioDeviceModuleForTest> CreateAudioDevice() {
henrikaec9c7452018-06-08 16:10:03 +0200555 // Use the default factory for kPlatformDefaultAudio and a special factory
henrika5b6afc02018-09-05 14:34:40 +0200556 // CreateWindowsCoreAudioAudioDeviceModuleForTest() for kWindowsCoreAudio2.
henrikaec9c7452018-06-08 16:10:03 +0200557 // The value of |audio_layer_| is set at construction by GetParam() and two
558 // different layers are tested on Windows only.
559 if (audio_layer_ == AudioDeviceModule::kPlatformDefaultAudio) {
henrika5b6afc02018-09-05 14:34:40 +0200560 return AudioDeviceModule::CreateForTest(audio_layer_);
henrikaec9c7452018-06-08 16:10:03 +0200561 } else if (audio_layer_ == AudioDeviceModule::kWindowsCoreAudio2) {
562#ifdef WEBRTC_WIN
563 // We must initialize the COM library on a thread before we calling any of
564 // the library functions. All COM functions in the ADM will return
565 // CO_E_NOTINITIALIZED otherwise.
Karl Wiberg918f50c2018-07-05 11:40:33 +0200566 com_initializer_ = absl::make_unique<webrtc_win::ScopedCOMInitializer>(
henrikaec9c7452018-06-08 16:10:03 +0200567 webrtc_win::ScopedCOMInitializer::kMTA);
568 EXPECT_TRUE(com_initializer_->Succeeded());
569 EXPECT_TRUE(webrtc_win::core_audio_utility::IsSupported());
570 EXPECT_TRUE(webrtc_win::core_audio_utility::IsMMCSSSupported());
henrika5b6afc02018-09-05 14:34:40 +0200571 return CreateWindowsCoreAudioAudioDeviceModuleForTest();
henrikaec9c7452018-06-08 16:10:03 +0200572#else
573 return nullptr;
574#endif
575 } else {
576 return nullptr;
577 }
578 }
579
henrikaf2f91fa2017-03-17 04:26:22 -0700580 void StartPlayout() {
581 EXPECT_FALSE(audio_device()->Playing());
582 EXPECT_EQ(0, audio_device()->InitPlayout());
583 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
584 EXPECT_EQ(0, audio_device()->StartPlayout());
585 EXPECT_TRUE(audio_device()->Playing());
586 }
587
588 void StopPlayout() {
589 EXPECT_EQ(0, audio_device()->StopPlayout());
590 EXPECT_FALSE(audio_device()->Playing());
591 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
592 }
593
594 void StartRecording() {
595 EXPECT_FALSE(audio_device()->Recording());
596 EXPECT_EQ(0, audio_device()->InitRecording());
597 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
598 EXPECT_EQ(0, audio_device()->StartRecording());
599 EXPECT_TRUE(audio_device()->Recording());
600 }
601
602 void StopRecording() {
603 EXPECT_EQ(0, audio_device()->StopRecording());
604 EXPECT_FALSE(audio_device()->Recording());
605 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
606 }
607
henrikaec9c7452018-06-08 16:10:03 +0200608 bool NewWindowsAudioDeviceModuleIsUsed() {
609#ifdef WEBRTC_WIN
610 AudioDeviceModule::AudioLayer audio_layer;
611 EXPECT_EQ(0, audio_device()->ActiveAudioLayer(&audio_layer));
612 if (audio_layer == AudioDeviceModule::kWindowsCoreAudio2) {
613 // Default device is always added as first element in the list and the
614 // default communication device as the second element. Hence, the list
615 // contains two extra elements in this case.
616 return true;
617 }
618#endif
619 return false;
620 }
621
henrikaf2f91fa2017-03-17 04:26:22 -0700622 private:
henrikaec9c7452018-06-08 16:10:03 +0200623#ifdef WEBRTC_WIN
624 // Windows Core Audio based ADM needs to run on a COM initialized thread.
625 std::unique_ptr<webrtc_win::ScopedCOMInitializer> com_initializer_;
626#endif
627 AudioDeviceModule::AudioLayer audio_layer_;
henrikaf2f91fa2017-03-17 04:26:22 -0700628 bool requirements_satisfied_ = true;
629 rtc::Event event_;
henrika5b6afc02018-09-05 14:34:40 +0200630 rtc::scoped_refptr<AudioDeviceModuleForTest> audio_device_;
henrikaf2f91fa2017-03-17 04:26:22 -0700631 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700632};
633
henrikaec9c7452018-06-08 16:10:03 +0200634// Instead of using the test fixture, verify that the different factory methods
635// work as intended.
636TEST(AudioDeviceTestWin, ConstructDestructWithFactory) {
637 rtc::scoped_refptr<AudioDeviceModule> audio_device;
638 // The default factory should work for all platforms when a default ADM is
639 // requested.
640 audio_device =
641 AudioDeviceModule::Create(AudioDeviceModule::kPlatformDefaultAudio);
642 EXPECT_TRUE(audio_device);
643 audio_device = nullptr;
644#ifdef WEBRTC_WIN
645 // For Windows, the old factory method creates an ADM where the platform-
646 // specific parts are implemented by an AudioDeviceGeneric object. Verify
647 // that the old factory can't be used in combination with the latest audio
648 // layer AudioDeviceModule::kWindowsCoreAudio2.
649 audio_device =
650 AudioDeviceModule::Create(AudioDeviceModule::kWindowsCoreAudio2);
651 EXPECT_FALSE(audio_device);
652 audio_device = nullptr;
653 // Instead, ensure that the new dedicated factory method called
654 // CreateWindowsCoreAudioAudioDeviceModule() can be used on Windows and that
655 // it sets the audio layer to kWindowsCoreAudio2 implicitly. Note that, the
656 // new ADM for Windows must be created on a COM thread.
657 webrtc_win::ScopedCOMInitializer com_initializer(
658 webrtc_win::ScopedCOMInitializer::kMTA);
659 EXPECT_TRUE(com_initializer.Succeeded());
660 audio_device = CreateWindowsCoreAudioAudioDeviceModule();
661 EXPECT_TRUE(audio_device);
662 AudioDeviceModule::AudioLayer audio_layer;
663 EXPECT_EQ(0, audio_device->ActiveAudioLayer(&audio_layer));
664 EXPECT_EQ(audio_layer, AudioDeviceModule::kWindowsCoreAudio2);
665#endif
666}
henrikaf2f91fa2017-03-17 04:26:22 -0700667
henrikaec9c7452018-06-08 16:10:03 +0200668// Uses the test fixture to create, initialize and destruct the ADM.
669TEST_P(AudioDeviceTest, ConstructDestructDefault) {}
670
671TEST_P(AudioDeviceTest, InitTerminate) {
henrikaf2f91fa2017-03-17 04:26:22 -0700672 SKIP_TEST_IF_NOT(requirements_satisfied());
673 // Initialization is part of the test fixture.
674 EXPECT_TRUE(audio_device()->Initialized());
675 EXPECT_EQ(0, audio_device()->Terminate());
676 EXPECT_FALSE(audio_device()->Initialized());
677}
678
henrikaec9c7452018-06-08 16:10:03 +0200679// Enumerate all available and active output devices.
680TEST_P(AudioDeviceTest, PlayoutDeviceNames) {
henrikaf2f91fa2017-03-17 04:26:22 -0700681 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaec9c7452018-06-08 16:10:03 +0200682 char device_name[kAdmMaxDeviceNameSize];
683 char unique_id[kAdmMaxGuidSize];
684 int num_devices = audio_device()->PlayoutDevices();
685 if (NewWindowsAudioDeviceModuleIsUsed()) {
686 num_devices += 2;
687 }
688 EXPECT_GT(num_devices, 0);
689 for (int i = 0; i < num_devices; ++i) {
690 EXPECT_EQ(0, audio_device()->PlayoutDeviceName(i, device_name, unique_id));
691 }
692 EXPECT_EQ(-1, audio_device()->PlayoutDeviceName(num_devices, device_name,
693 unique_id));
694}
695
696// Enumerate all available and active input devices.
697TEST_P(AudioDeviceTest, RecordingDeviceNames) {
698 SKIP_TEST_IF_NOT(requirements_satisfied());
699 char device_name[kAdmMaxDeviceNameSize];
700 char unique_id[kAdmMaxGuidSize];
701 int num_devices = audio_device()->RecordingDevices();
702 if (NewWindowsAudioDeviceModuleIsUsed()) {
703 num_devices += 2;
704 }
705 EXPECT_GT(num_devices, 0);
706 for (int i = 0; i < num_devices; ++i) {
707 EXPECT_EQ(0,
708 audio_device()->RecordingDeviceName(i, device_name, unique_id));
709 }
710 EXPECT_EQ(-1, audio_device()->RecordingDeviceName(num_devices, device_name,
711 unique_id));
712}
713
714// Counts number of active output devices and ensure that all can be selected.
715TEST_P(AudioDeviceTest, SetPlayoutDevice) {
716 SKIP_TEST_IF_NOT(requirements_satisfied());
717 int num_devices = audio_device()->PlayoutDevices();
718 if (NewWindowsAudioDeviceModuleIsUsed()) {
719 num_devices += 2;
720 }
721 EXPECT_GT(num_devices, 0);
722 // Verify that all available playout devices can be set (not enabled yet).
723 for (int i = 0; i < num_devices; ++i) {
724 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(i));
725 }
726 EXPECT_EQ(-1, audio_device()->SetPlayoutDevice(num_devices));
727#ifdef WEBRTC_WIN
728 // On Windows, verify the alternative method where the user can select device
729 // by role.
730 EXPECT_EQ(
731 0, audio_device()->SetPlayoutDevice(AudioDeviceModule::kDefaultDevice));
732 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(
733 AudioDeviceModule::kDefaultCommunicationDevice));
734#endif
735}
736
737// Counts number of active input devices and ensure that all can be selected.
738TEST_P(AudioDeviceTest, SetRecordingDevice) {
739 SKIP_TEST_IF_NOT(requirements_satisfied());
740 int num_devices = audio_device()->RecordingDevices();
741 if (NewWindowsAudioDeviceModuleIsUsed()) {
742 num_devices += 2;
743 }
744 EXPECT_GT(num_devices, 0);
745 // Verify that all available recording devices can be set (not enabled yet).
746 for (int i = 0; i < num_devices; ++i) {
747 EXPECT_EQ(0, audio_device()->SetRecordingDevice(i));
748 }
749 EXPECT_EQ(-1, audio_device()->SetRecordingDevice(num_devices));
750#ifdef WEBRTC_WIN
751 // On Windows, verify the alternative method where the user can select device
752 // by role.
753 EXPECT_EQ(
754 0, audio_device()->SetRecordingDevice(AudioDeviceModule::kDefaultDevice));
755 EXPECT_EQ(0, audio_device()->SetRecordingDevice(
756 AudioDeviceModule::kDefaultCommunicationDevice));
757#endif
758}
759
760// Tests Start/Stop playout without any registered audio callback.
761TEST_P(AudioDeviceTest, StartStopPlayout) {
762 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaf2f91fa2017-03-17 04:26:22 -0700763 StartPlayout();
764 StopPlayout();
765}
766
767// Tests Start/Stop recording without any registered audio callback.
henrikaec9c7452018-06-08 16:10:03 +0200768TEST_P(AudioDeviceTest, StartStopRecording) {
henrikaf2f91fa2017-03-17 04:26:22 -0700769 SKIP_TEST_IF_NOT(requirements_satisfied());
770 StartRecording();
771 StopRecording();
henrikaf2f91fa2017-03-17 04:26:22 -0700772}
773
henrika6b3e1a22017-09-25 16:34:30 +0200774// Tests Init/Stop/Init recording without any registered audio callback.
775// See https://bugs.chromium.org/p/webrtc/issues/detail?id=8041 for details
776// on why this test is useful.
henrikaec9c7452018-06-08 16:10:03 +0200777TEST_P(AudioDeviceTest, InitStopInitRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200778 SKIP_TEST_IF_NOT(requirements_satisfied());
779 EXPECT_EQ(0, audio_device()->InitRecording());
780 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
781 StopRecording();
782 EXPECT_EQ(0, audio_device()->InitRecording());
783 StopRecording();
784}
785
786// Tests Init/Stop/Init recording while playout is active.
henrikaec9c7452018-06-08 16:10:03 +0200787TEST_P(AudioDeviceTest, InitStopInitRecordingWhilePlaying) {
henrika6b3e1a22017-09-25 16:34:30 +0200788 SKIP_TEST_IF_NOT(requirements_satisfied());
789 StartPlayout();
790 EXPECT_EQ(0, audio_device()->InitRecording());
791 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
792 StopRecording();
793 EXPECT_EQ(0, audio_device()->InitRecording());
794 StopRecording();
795 StopPlayout();
796}
797
798// Tests Init/Stop/Init playout without any registered audio callback.
henrikaec9c7452018-06-08 16:10:03 +0200799TEST_P(AudioDeviceTest, InitStopInitPlayout) {
henrika6b3e1a22017-09-25 16:34:30 +0200800 SKIP_TEST_IF_NOT(requirements_satisfied());
801 EXPECT_EQ(0, audio_device()->InitPlayout());
802 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
803 StopPlayout();
804 EXPECT_EQ(0, audio_device()->InitPlayout());
805 StopPlayout();
806}
807
808// Tests Init/Stop/Init playout while recording is active.
henrikaec9c7452018-06-08 16:10:03 +0200809TEST_P(AudioDeviceTest, InitStopInitPlayoutWhileRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200810 SKIP_TEST_IF_NOT(requirements_satisfied());
811 StartRecording();
812 EXPECT_EQ(0, audio_device()->InitPlayout());
813 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
814 StopPlayout();
815 EXPECT_EQ(0, audio_device()->InitPlayout());
816 StopPlayout();
817 StopRecording();
818}
819
henrika5b6afc02018-09-05 14:34:40 +0200820// TODO(henrika): restart without intermediate destruction is currently only
821// supported on Windows.
822#ifdef WEBRTC_WIN
823// Tests Start/Stop playout followed by a second session (emulates a restart
824// triggered by a user using public APIs).
825TEST_P(AudioDeviceTest, StartStopPlayoutWithExternalRestart) {
826 SKIP_TEST_IF_NOT(requirements_satisfied());
827 StartPlayout();
828 StopPlayout();
829 // Restart playout without destroying the ADM in between. Ensures that we
830 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
831 StartPlayout();
832 StopPlayout();
833}
834
835// Tests Start/Stop recording followed by a second session (emulates a restart
836// triggered by a user using public APIs).
837TEST_P(AudioDeviceTest, StartStopRecordingWithExternalRestart) {
838 SKIP_TEST_IF_NOT(requirements_satisfied());
839 StartRecording();
840 StopRecording();
841 // Restart recording without destroying the ADM in between. Ensures that we
842 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
843 StartRecording();
844 StopRecording();
845}
846
847// Tests Start/Stop playout followed by a second session (emulates a restart
848// triggered by an internal callback e.g. corresponding to a device switch).
849// Note that, internal restart is only supported in combination with the latest
850// Windows ADM.
851TEST_P(AudioDeviceTest, StartStopPlayoutWithInternalRestart) {
852 SKIP_TEST_IF_NOT(requirements_satisfied());
853 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
854 return;
855 }
856 MockAudioTransport mock(TransportType::kPlay);
857 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
858 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
859 .Times(AtLeast(kNumCallbacks));
860 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
861 StartPlayout();
862 event()->Wait(kTestTimeOutInMilliseconds);
863 EXPECT_TRUE(audio_device()->Playing());
864 // Restart playout but without stopping the internal audio thread.
865 // This procedure uses a non-public test API and it emulates what happens
866 // inside the ADM when e.g. a device is removed.
867 EXPECT_EQ(0, audio_device()->RestartPlayoutInternally());
868
869 // Run basic tests of public APIs while a restart attempt is active.
870 // These calls should now be very thin and not trigger any new actions.
871 EXPECT_EQ(-1, audio_device()->StopPlayout());
872 EXPECT_TRUE(audio_device()->Playing());
873 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
874 EXPECT_EQ(0, audio_device()->InitPlayout());
875 EXPECT_EQ(0, audio_device()->StartPlayout());
876
877 // Wait until audio has restarted and a new sequence of audio callbacks
878 // becomes active.
879 // TODO(henrika): is it possible to verify that the internal state transition
880 // is Stop->Init->Start?
881 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
882 mock.ResetCallbackCounters();
883 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
884 .Times(AtLeast(kNumCallbacks));
885 event()->Wait(kTestTimeOutInMilliseconds);
886 EXPECT_TRUE(audio_device()->Playing());
887 // Stop playout and the audio thread after successful internal restart.
888 StopPlayout();
889}
890
891// Tests Start/Stop recording followed by a second session (emulates a restart
892// triggered by an internal callback e.g. corresponding to a device switch).
893// Note that, internal restart is only supported in combination with the latest
894// Windows ADM.
895TEST_P(AudioDeviceTest, StartStopRecordingWithInternalRestart) {
896 SKIP_TEST_IF_NOT(requirements_satisfied());
897 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
898 return;
899 }
900 MockAudioTransport mock(TransportType::kRecord);
901 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
902 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
903 false, _))
904 .Times(AtLeast(kNumCallbacks));
905 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
906 StartRecording();
907 event()->Wait(kTestTimeOutInMilliseconds);
908 EXPECT_TRUE(audio_device()->Recording());
909 // Restart recording but without stopping the internal audio thread.
910 // This procedure uses a non-public test API and it emulates what happens
911 // inside the ADM when e.g. a device is removed.
912 EXPECT_EQ(0, audio_device()->RestartRecordingInternally());
913
914 // Run basic tests of public APIs while a restart attempt is active.
915 // These calls should now be very thin and not trigger any new actions.
916 EXPECT_EQ(-1, audio_device()->StopRecording());
917 EXPECT_TRUE(audio_device()->Recording());
918 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
919 EXPECT_EQ(0, audio_device()->InitRecording());
920 EXPECT_EQ(0, audio_device()->StartRecording());
921
922 // Wait until audio has restarted and a new sequence of audio callbacks
923 // becomes active.
924 // TODO(henrika): is it possible to verify that the internal state transition
925 // is Stop->Init->Start?
926 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
927 mock.ResetCallbackCounters();
928 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
929 false, _))
930 .Times(AtLeast(kNumCallbacks));
931 event()->Wait(kTestTimeOutInMilliseconds);
932 EXPECT_TRUE(audio_device()->Recording());
933 // Stop recording and the audio thread after successful internal restart.
934 StopRecording();
935}
936#endif // #ifdef WEBRTC_WIN
937
henrikaf2f91fa2017-03-17 04:26:22 -0700938// Start playout and verify that the native audio layer starts asking for real
939// audio samples to play out using the NeedMorePlayData() callback.
940// Note that we can't add expectations on audio parameters in EXPECT_CALL
941// since parameter are not provided in the each callback. We therefore test and
942// verify the parameters in the fake audio transport implementation instead.
henrikaec9c7452018-06-08 16:10:03 +0200943TEST_P(AudioDeviceTest, StartPlayoutVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700944 SKIP_TEST_IF_NOT(requirements_satisfied());
945 MockAudioTransport mock(TransportType::kPlay);
henrikae24991d2017-04-06 01:14:23 -0700946 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700947 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
948 .Times(AtLeast(kNumCallbacks));
949 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
950 StartPlayout();
951 event()->Wait(kTestTimeOutInMilliseconds);
952 StopPlayout();
953}
954
955// Start recording and verify that the native audio layer starts providing real
956// audio samples using the RecordedDataIsAvailable() callback.
henrikaec9c7452018-06-08 16:10:03 +0200957TEST_P(AudioDeviceTest, StartRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700958 SKIP_TEST_IF_NOT(requirements_satisfied());
959 MockAudioTransport mock(TransportType::kRecord);
henrikae24991d2017-04-06 01:14:23 -0700960 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700961 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
962 false, _))
963 .Times(AtLeast(kNumCallbacks));
964 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
965 StartRecording();
966 event()->Wait(kTestTimeOutInMilliseconds);
967 StopRecording();
968}
969
970// Start playout and recording (full-duplex audio) and verify that audio is
971// active in both directions.
henrikaec9c7452018-06-08 16:10:03 +0200972TEST_P(AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700973 SKIP_TEST_IF_NOT(requirements_satisfied());
974 MockAudioTransport mock(TransportType::kPlayAndRecord);
henrikae24991d2017-04-06 01:14:23 -0700975 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700976 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
977 .Times(AtLeast(kNumCallbacks));
978 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
979 false, _))
980 .Times(AtLeast(kNumCallbacks));
981 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
982 StartPlayout();
983 StartRecording();
984 event()->Wait(kTestTimeOutInMilliseconds);
985 StopRecording();
986 StopPlayout();
987}
988
henrikae24991d2017-04-06 01:14:23 -0700989// Start playout and recording and store recorded data in an intermediate FIFO
990// buffer from which the playout side then reads its samples in the same order
991// as they were stored. Under ideal circumstances, a callback sequence would
992// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
993// means 'packet played'. Under such conditions, the FIFO would contain max 1,
994// with an average somewhere in (0,1) depending on how long the packets are
995// buffered. However, under more realistic conditions, the size
996// of the FIFO will vary more due to an unbalance between the two sides.
997// This test tries to verify that the device maintains a balanced callback-
998// sequence by running in loopback for a few seconds while measuring the size
999// (max and average) of the FIFO. The size of the FIFO is increased by the
1000// recording side and decreased by the playout side.
henrikaec9c7452018-06-08 16:10:03 +02001001TEST_P(AudioDeviceTest, RunPlayoutAndRecordingInFullDuplex) {
henrikae24991d2017-04-06 01:14:23 -07001002 SKIP_TEST_IF_NOT(requirements_satisfied());
1003 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1004 FifoAudioStream audio_stream;
1005 mock.HandleCallbacks(event(), &audio_stream,
1006 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
1007 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001008 // Run both sides using the same channel configuration to avoid conversions
1009 // between mono/stereo while running in full duplex mode. Also, some devices
1010 // (mainly on Windows) do not support mono.
1011 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1012 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrikae24991d2017-04-06 01:14:23 -07001013 StartPlayout();
1014 StartRecording();
henrika714e5cd2017-04-20 08:03:11 -07001015 event()->Wait(static_cast<int>(
1016 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec)));
henrikae24991d2017-04-06 01:14:23 -07001017 StopRecording();
1018 StopPlayout();
1019 // This thresholds is set rather high to accommodate differences in hardware
1020 // in several devices. The main idea is to capture cases where a very large
henrikab6ca7212017-10-06 12:47:52 +02001021 // latency is built up. See http://bugs.webrtc.org/7744 for examples on
1022 // bots where relatively large average latencies can happen.
1023 EXPECT_LE(audio_stream.average_size(), 25u);
henrikae24991d2017-04-06 01:14:23 -07001024 PRINT("\n");
1025}
1026
henrika5b6afc02018-09-05 14:34:40 +02001027// Runs audio in full duplex until user hits Enter. Intended as a manual test
1028// to ensure that the audio quality is good and that real device switches works
1029// as intended.
1030TEST_P(AudioDeviceTest,
1031 DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey) {
1032 SKIP_TEST_IF_NOT(requirements_satisfied());
1033 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
1034 return;
1035 }
1036 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1037 FifoAudioStream audio_stream;
1038 mock.HandleCallbacks(&audio_stream);
1039 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1040 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1041 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
1042 // Ensure that the sample rate for both directions are identical so that we
1043 // always can listen to our own voice. Will lead to rate conversion (and
1044 // higher latency) if the native sample rate is not 48kHz.
1045 EXPECT_EQ(0, audio_device()->SetPlayoutSampleRate(48000));
1046 EXPECT_EQ(0, audio_device()->SetRecordingSampleRate(48000));
1047 StartPlayout();
1048 StartRecording();
1049 do {
1050 PRINT("Loopback audio is active at 48kHz. Press Enter to stop.\n");
1051 } while (getchar() != '\n');
1052 StopRecording();
1053 StopPlayout();
1054}
1055
henrika714e5cd2017-04-20 08:03:11 -07001056// Measures loopback latency and reports the min, max and average values for
1057// a full duplex audio session.
1058// The latency is measured like so:
1059// - Insert impulses periodically on the output side.
1060// - Detect the impulses on the input side.
1061// - Measure the time difference between the transmit time and receive time.
1062// - Store time differences in a vector and calculate min, max and average.
1063// This test needs the '--gtest_also_run_disabled_tests' flag to run and also
1064// some sort of audio feedback loop. E.g. a headset where the mic is placed
1065// close to the speaker to ensure highest possible echo. It is also recommended
1066// to run the test at highest possible output volume.
henrikaec9c7452018-06-08 16:10:03 +02001067TEST_P(AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
henrika714e5cd2017-04-20 08:03:11 -07001068 SKIP_TEST_IF_NOT(requirements_satisfied());
1069 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1070 LatencyAudioStream audio_stream;
1071 mock.HandleCallbacks(event(), &audio_stream,
1072 kMeasureLatencyTimeInSec * kNumCallbacksPerSecond);
1073 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001074 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1075 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrika714e5cd2017-04-20 08:03:11 -07001076 StartPlayout();
1077 StartRecording();
1078 event()->Wait(static_cast<int>(
1079 std::max(kTestTimeOutInMilliseconds, 1000 * kMeasureLatencyTimeInSec)));
1080 StopRecording();
1081 StopPlayout();
henrikac7d93582018-09-14 15:37:34 +02001082 // Verify that a sufficient number of transmitted impulses are detected.
1083 EXPECT_GE(audio_stream.num_latency_values(),
henrika714e5cd2017-04-20 08:03:11 -07001084 static_cast<size_t>(
henrikac7d93582018-09-14 15:37:34 +02001085 kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 2));
henrika714e5cd2017-04-20 08:03:11 -07001086 // Print out min, max and average delay values for debugging purposes.
1087 audio_stream.PrintResults();
1088}
1089
henrikaec9c7452018-06-08 16:10:03 +02001090#ifdef WEBRTC_WIN
1091// Test two different audio layers (or rather two different Core Audio
1092// implementations) for Windows.
1093INSTANTIATE_TEST_CASE_P(
1094 AudioLayerWin,
1095 AudioDeviceTest,
1096 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio,
1097 AudioDeviceModule::kWindowsCoreAudio2));
1098#else
1099// For all platforms but Windows, only test the default audio layer.
1100INSTANTIATE_TEST_CASE_P(
1101 AudioLayer,
1102 AudioDeviceTest,
1103 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio));
1104#endif
1105
henrikaf2f91fa2017-03-17 04:26:22 -07001106} // namespace webrtc