blob: efa1d993b7fe0ab0e2dfe1960fea7e41dfed4750 [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 }
397 rec_count_++;
henrikae24991d2017-04-06 01:14:23 -0700398 // Write audio data to audio stream object if one has been injected.
399 if (audio_stream_) {
400 audio_stream_->Write(
401 rtc::MakeArrayView(static_cast<const int16_t*>(audio_buffer),
henrikaeb98c722018-03-20 12:54:07 +0100402 samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700403 }
henrikaf2f91fa2017-03-17 04:26:22 -0700404 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200405 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700406 event_->Set();
407 }
408 return 0;
409 }
410
411 int32_t RealNeedMorePlayData(const size_t samples_per_channel,
412 const size_t bytes_per_frame,
413 const size_t channels,
414 const uint32_t sample_rate,
415 void* audio_buffer,
henrikaeb98c722018-03-20 12:54:07 +0100416 size_t& samples_out,
henrikaf2f91fa2017-03-17 04:26:22 -0700417 int64_t* elapsed_time_ms,
418 int64_t* ntp_time_ms) {
419 EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
henrikaf2f91fa2017-03-17 04:26:22 -0700420 // Store audio parameters once in the first callback. For all other
421 // callbacks, verify that the provided audio parameters are maintained and
422 // that each callback corresponds to 10ms for any given sample rate.
423 if (!playout_parameters_.is_complete()) {
424 playout_parameters_.reset(sample_rate, channels, samples_per_channel);
425 } else {
426 EXPECT_EQ(samples_per_channel, playout_parameters_.frames_per_buffer());
427 EXPECT_EQ(bytes_per_frame, playout_parameters_.GetBytesPerFrame());
428 EXPECT_EQ(channels, playout_parameters_.channels());
429 EXPECT_EQ(static_cast<int>(sample_rate),
430 playout_parameters_.sample_rate());
431 EXPECT_EQ(samples_per_channel,
432 playout_parameters_.frames_per_10ms_buffer());
433 }
434 play_count_++;
henrikaeb98c722018-03-20 12:54:07 +0100435 samples_out = samples_per_channel * channels;
henrikae24991d2017-04-06 01:14:23 -0700436 // Read audio data from audio stream object if one has been injected.
437 if (audio_stream_) {
henrikaeb98c722018-03-20 12:54:07 +0100438 audio_stream_->Read(rtc::MakeArrayView(
439 static_cast<int16_t*>(audio_buffer), samples_per_channel * channels));
henrikae24991d2017-04-06 01:14:23 -0700440 } else {
441 // Fill the audio buffer with zeros to avoid disturbing audio.
442 const size_t num_bytes = samples_per_channel * bytes_per_frame;
443 std::memset(audio_buffer, 0, num_bytes);
444 }
henrikaf2f91fa2017-03-17 04:26:22 -0700445 // Signal the event after given amount of callbacks.
henrika5b6afc02018-09-05 14:34:40 +0200446 if (event_ && ReceivedEnoughCallbacks()) {
henrikaf2f91fa2017-03-17 04:26:22 -0700447 event_->Set();
448 }
449 return 0;
450 }
451
452 bool ReceivedEnoughCallbacks() {
453 bool recording_done = false;
454 if (rec_mode()) {
455 recording_done = rec_count_ >= num_callbacks_;
456 } else {
457 recording_done = true;
458 }
459 bool playout_done = false;
460 if (play_mode()) {
461 playout_done = play_count_ >= num_callbacks_;
462 } else {
463 playout_done = true;
464 }
465 return recording_done && playout_done;
466 }
467
468 bool play_mode() const {
469 return type_ == TransportType::kPlay ||
470 type_ == TransportType::kPlayAndRecord;
471 }
472
473 bool rec_mode() const {
474 return type_ == TransportType::kRecord ||
475 type_ == TransportType::kPlayAndRecord;
476 }
477
henrika5b6afc02018-09-05 14:34:40 +0200478 void ResetCallbackCounters() {
479 if (play_mode()) {
480 play_count_ = 0;
481 }
482 if (rec_mode()) {
483 rec_count_ = 0;
484 }
485 }
486
henrikaf2f91fa2017-03-17 04:26:22 -0700487 private:
488 TransportType type_ = TransportType::kInvalid;
489 rtc::Event* event_ = nullptr;
henrikae24991d2017-04-06 01:14:23 -0700490 AudioStream* audio_stream_ = nullptr;
henrikaf2f91fa2017-03-17 04:26:22 -0700491 size_t num_callbacks_ = 0;
492 size_t play_count_ = 0;
493 size_t rec_count_ = 0;
494 AudioParameters playout_parameters_;
495 AudioParameters record_parameters_;
496};
497
498// AudioDeviceTest test fixture.
henrikaec9c7452018-06-08 16:10:03 +0200499class AudioDeviceTest
500 : public ::testing::TestWithParam<webrtc::AudioDeviceModule::AudioLayer> {
henrikaf2f91fa2017-03-17 04:26:22 -0700501 protected:
henrikaec9c7452018-06-08 16:10:03 +0200502 AudioDeviceTest() : audio_layer_(GetParam()), event_(false, false) {
Joachim Bauch5d2bb362017-12-20 21:19:49 +0100503#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \
504 !defined(WEBRTC_DUMMY_AUDIO_BUILD)
henrikaf2f91fa2017-03-17 04:26:22 -0700505 rtc::LogMessage::LogToDebug(rtc::LS_INFO);
506 // Add extra logging fields here if needed for debugging.
henrikaec9c7452018-06-08 16:10:03 +0200507 rtc::LogMessage::LogTimestamps();
508 rtc::LogMessage::LogThreads();
509 audio_device_ = CreateAudioDevice();
henrikaf2f91fa2017-03-17 04:26:22 -0700510 EXPECT_NE(audio_device_.get(), nullptr);
511 AudioDeviceModule::AudioLayer audio_layer;
maxmorin33bf69a2017-03-23 04:06:53 -0700512 int got_platform_audio_layer =
513 audio_device_->ActiveAudioLayer(&audio_layer);
henrika919dc2e2017-10-12 14:24:55 +0200514 // First, ensure that a valid audio layer can be activated.
515 if (got_platform_audio_layer != 0) {
henrikaf2f91fa2017-03-17 04:26:22 -0700516 requirements_satisfied_ = false;
517 }
henrika919dc2e2017-10-12 14:24:55 +0200518 // Next, verify that the ADM can be initialized.
henrikaf2f91fa2017-03-17 04:26:22 -0700519 if (requirements_satisfied_) {
henrika919dc2e2017-10-12 14:24:55 +0200520 requirements_satisfied_ = (audio_device_->Init() == 0);
521 }
522 // Finally, ensure that at least one valid device exists in each direction.
523 if (requirements_satisfied_) {
henrikaf2f91fa2017-03-17 04:26:22 -0700524 const int16_t num_playout_devices = audio_device_->PlayoutDevices();
525 const int16_t num_record_devices = audio_device_->RecordingDevices();
526 requirements_satisfied_ =
527 num_playout_devices > 0 && num_record_devices > 0;
528 }
529#else
530 requirements_satisfied_ = false;
531#endif
532 if (requirements_satisfied_) {
henrika5773ad32018-09-21 14:53:10 +0200533 EXPECT_EQ(0, audio_device_->SetPlayoutDevice(AUDIO_DEVICE_ID));
henrikaf2f91fa2017-03-17 04:26:22 -0700534 EXPECT_EQ(0, audio_device_->InitSpeaker());
henrikaf2f91fa2017-03-17 04:26:22 -0700535 EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
536 EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
henrika5773ad32018-09-21 14:53:10 +0200537 EXPECT_EQ(0, audio_device_->SetRecordingDevice(AUDIO_DEVICE_ID));
538 EXPECT_EQ(0, audio_device_->InitMicrophone());
henrika0238ba82017-03-28 04:38:29 -0700539 // Avoid asking for input stereo support and always record in mono
540 // since asking can cause issues in combination with remote desktop.
541 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
542 // details.
543 EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
henrikaf2f91fa2017-03-17 04:26:22 -0700544 }
545 }
546
547 virtual ~AudioDeviceTest() {
548 if (audio_device_) {
549 EXPECT_EQ(0, audio_device_->Terminate());
550 }
551 }
552
553 bool requirements_satisfied() const { return requirements_satisfied_; }
554 rtc::Event* event() { return &event_; }
henrika5b6afc02018-09-05 14:34:40 +0200555 AudioDeviceModule::AudioLayer audio_layer() const { return audio_layer_; }
henrikaf2f91fa2017-03-17 04:26:22 -0700556
henrika5b6afc02018-09-05 14:34:40 +0200557 // AudioDeviceModuleForTest extends the default ADM interface with some extra
558 // test methods. Intended for usage in tests only and requires a unique
559 // factory method. See CreateAudioDevice() for details.
560 const rtc::scoped_refptr<AudioDeviceModuleForTest>& audio_device() const {
henrikaf2f91fa2017-03-17 04:26:22 -0700561 return audio_device_;
562 }
563
henrika5b6afc02018-09-05 14:34:40 +0200564 rtc::scoped_refptr<AudioDeviceModuleForTest> CreateAudioDevice() {
henrikaec9c7452018-06-08 16:10:03 +0200565 // Use the default factory for kPlatformDefaultAudio and a special factory
henrika5b6afc02018-09-05 14:34:40 +0200566 // CreateWindowsCoreAudioAudioDeviceModuleForTest() for kWindowsCoreAudio2.
henrikaec9c7452018-06-08 16:10:03 +0200567 // The value of |audio_layer_| is set at construction by GetParam() and two
568 // different layers are tested on Windows only.
569 if (audio_layer_ == AudioDeviceModule::kPlatformDefaultAudio) {
henrika5b6afc02018-09-05 14:34:40 +0200570 return AudioDeviceModule::CreateForTest(audio_layer_);
henrikaec9c7452018-06-08 16:10:03 +0200571 } else if (audio_layer_ == AudioDeviceModule::kWindowsCoreAudio2) {
572#ifdef WEBRTC_WIN
573 // We must initialize the COM library on a thread before we calling any of
574 // the library functions. All COM functions in the ADM will return
575 // CO_E_NOTINITIALIZED otherwise.
Karl Wiberg918f50c2018-07-05 11:40:33 +0200576 com_initializer_ = absl::make_unique<webrtc_win::ScopedCOMInitializer>(
henrikaec9c7452018-06-08 16:10:03 +0200577 webrtc_win::ScopedCOMInitializer::kMTA);
578 EXPECT_TRUE(com_initializer_->Succeeded());
579 EXPECT_TRUE(webrtc_win::core_audio_utility::IsSupported());
580 EXPECT_TRUE(webrtc_win::core_audio_utility::IsMMCSSSupported());
henrika5b6afc02018-09-05 14:34:40 +0200581 return CreateWindowsCoreAudioAudioDeviceModuleForTest();
henrikaec9c7452018-06-08 16:10:03 +0200582#else
583 return nullptr;
584#endif
585 } else {
586 return nullptr;
587 }
588 }
589
henrikaf2f91fa2017-03-17 04:26:22 -0700590 void StartPlayout() {
591 EXPECT_FALSE(audio_device()->Playing());
592 EXPECT_EQ(0, audio_device()->InitPlayout());
593 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
594 EXPECT_EQ(0, audio_device()->StartPlayout());
595 EXPECT_TRUE(audio_device()->Playing());
596 }
597
598 void StopPlayout() {
599 EXPECT_EQ(0, audio_device()->StopPlayout());
600 EXPECT_FALSE(audio_device()->Playing());
601 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
602 }
603
604 void StartRecording() {
605 EXPECT_FALSE(audio_device()->Recording());
606 EXPECT_EQ(0, audio_device()->InitRecording());
607 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
608 EXPECT_EQ(0, audio_device()->StartRecording());
609 EXPECT_TRUE(audio_device()->Recording());
610 }
611
612 void StopRecording() {
613 EXPECT_EQ(0, audio_device()->StopRecording());
614 EXPECT_FALSE(audio_device()->Recording());
615 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
616 }
617
henrikaec9c7452018-06-08 16:10:03 +0200618 bool NewWindowsAudioDeviceModuleIsUsed() {
619#ifdef WEBRTC_WIN
620 AudioDeviceModule::AudioLayer audio_layer;
621 EXPECT_EQ(0, audio_device()->ActiveAudioLayer(&audio_layer));
622 if (audio_layer == AudioDeviceModule::kWindowsCoreAudio2) {
623 // Default device is always added as first element in the list and the
624 // default communication device as the second element. Hence, the list
625 // contains two extra elements in this case.
626 return true;
627 }
628#endif
629 return false;
630 }
631
henrikaf2f91fa2017-03-17 04:26:22 -0700632 private:
henrikaec9c7452018-06-08 16:10:03 +0200633#ifdef WEBRTC_WIN
634 // Windows Core Audio based ADM needs to run on a COM initialized thread.
635 std::unique_ptr<webrtc_win::ScopedCOMInitializer> com_initializer_;
636#endif
637 AudioDeviceModule::AudioLayer audio_layer_;
henrikaf2f91fa2017-03-17 04:26:22 -0700638 bool requirements_satisfied_ = true;
639 rtc::Event event_;
henrika5b6afc02018-09-05 14:34:40 +0200640 rtc::scoped_refptr<AudioDeviceModuleForTest> audio_device_;
henrikaf2f91fa2017-03-17 04:26:22 -0700641 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700642};
643
henrikaec9c7452018-06-08 16:10:03 +0200644// Instead of using the test fixture, verify that the different factory methods
645// work as intended.
646TEST(AudioDeviceTestWin, ConstructDestructWithFactory) {
647 rtc::scoped_refptr<AudioDeviceModule> audio_device;
648 // The default factory should work for all platforms when a default ADM is
649 // requested.
650 audio_device =
651 AudioDeviceModule::Create(AudioDeviceModule::kPlatformDefaultAudio);
652 EXPECT_TRUE(audio_device);
653 audio_device = nullptr;
654#ifdef WEBRTC_WIN
655 // For Windows, the old factory method creates an ADM where the platform-
656 // specific parts are implemented by an AudioDeviceGeneric object. Verify
657 // that the old factory can't be used in combination with the latest audio
658 // layer AudioDeviceModule::kWindowsCoreAudio2.
659 audio_device =
660 AudioDeviceModule::Create(AudioDeviceModule::kWindowsCoreAudio2);
661 EXPECT_FALSE(audio_device);
662 audio_device = nullptr;
663 // Instead, ensure that the new dedicated factory method called
664 // CreateWindowsCoreAudioAudioDeviceModule() can be used on Windows and that
665 // it sets the audio layer to kWindowsCoreAudio2 implicitly. Note that, the
666 // new ADM for Windows must be created on a COM thread.
667 webrtc_win::ScopedCOMInitializer com_initializer(
668 webrtc_win::ScopedCOMInitializer::kMTA);
669 EXPECT_TRUE(com_initializer.Succeeded());
670 audio_device = CreateWindowsCoreAudioAudioDeviceModule();
671 EXPECT_TRUE(audio_device);
672 AudioDeviceModule::AudioLayer audio_layer;
673 EXPECT_EQ(0, audio_device->ActiveAudioLayer(&audio_layer));
674 EXPECT_EQ(audio_layer, AudioDeviceModule::kWindowsCoreAudio2);
675#endif
676}
henrikaf2f91fa2017-03-17 04:26:22 -0700677
henrikaec9c7452018-06-08 16:10:03 +0200678// Uses the test fixture to create, initialize and destruct the ADM.
679TEST_P(AudioDeviceTest, ConstructDestructDefault) {}
680
681TEST_P(AudioDeviceTest, InitTerminate) {
henrikaf2f91fa2017-03-17 04:26:22 -0700682 SKIP_TEST_IF_NOT(requirements_satisfied());
683 // Initialization is part of the test fixture.
684 EXPECT_TRUE(audio_device()->Initialized());
685 EXPECT_EQ(0, audio_device()->Terminate());
686 EXPECT_FALSE(audio_device()->Initialized());
687}
688
henrikaec9c7452018-06-08 16:10:03 +0200689// Enumerate all available and active output devices.
690TEST_P(AudioDeviceTest, PlayoutDeviceNames) {
henrikaf2f91fa2017-03-17 04:26:22 -0700691 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaec9c7452018-06-08 16:10:03 +0200692 char device_name[kAdmMaxDeviceNameSize];
693 char unique_id[kAdmMaxGuidSize];
694 int num_devices = audio_device()->PlayoutDevices();
695 if (NewWindowsAudioDeviceModuleIsUsed()) {
696 num_devices += 2;
697 }
698 EXPECT_GT(num_devices, 0);
699 for (int i = 0; i < num_devices; ++i) {
700 EXPECT_EQ(0, audio_device()->PlayoutDeviceName(i, device_name, unique_id));
701 }
702 EXPECT_EQ(-1, audio_device()->PlayoutDeviceName(num_devices, device_name,
703 unique_id));
704}
705
706// Enumerate all available and active input devices.
707TEST_P(AudioDeviceTest, RecordingDeviceNames) {
708 SKIP_TEST_IF_NOT(requirements_satisfied());
709 char device_name[kAdmMaxDeviceNameSize];
710 char unique_id[kAdmMaxGuidSize];
711 int num_devices = audio_device()->RecordingDevices();
712 if (NewWindowsAudioDeviceModuleIsUsed()) {
713 num_devices += 2;
714 }
715 EXPECT_GT(num_devices, 0);
716 for (int i = 0; i < num_devices; ++i) {
717 EXPECT_EQ(0,
718 audio_device()->RecordingDeviceName(i, device_name, unique_id));
719 }
720 EXPECT_EQ(-1, audio_device()->RecordingDeviceName(num_devices, device_name,
721 unique_id));
722}
723
724// Counts number of active output devices and ensure that all can be selected.
725TEST_P(AudioDeviceTest, SetPlayoutDevice) {
726 SKIP_TEST_IF_NOT(requirements_satisfied());
727 int num_devices = audio_device()->PlayoutDevices();
728 if (NewWindowsAudioDeviceModuleIsUsed()) {
729 num_devices += 2;
730 }
731 EXPECT_GT(num_devices, 0);
732 // Verify that all available playout devices can be set (not enabled yet).
733 for (int i = 0; i < num_devices; ++i) {
734 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(i));
735 }
736 EXPECT_EQ(-1, audio_device()->SetPlayoutDevice(num_devices));
737#ifdef WEBRTC_WIN
738 // On Windows, verify the alternative method where the user can select device
739 // by role.
740 EXPECT_EQ(
741 0, audio_device()->SetPlayoutDevice(AudioDeviceModule::kDefaultDevice));
742 EXPECT_EQ(0, audio_device()->SetPlayoutDevice(
743 AudioDeviceModule::kDefaultCommunicationDevice));
744#endif
745}
746
747// Counts number of active input devices and ensure that all can be selected.
748TEST_P(AudioDeviceTest, SetRecordingDevice) {
749 SKIP_TEST_IF_NOT(requirements_satisfied());
750 int num_devices = audio_device()->RecordingDevices();
751 if (NewWindowsAudioDeviceModuleIsUsed()) {
752 num_devices += 2;
753 }
754 EXPECT_GT(num_devices, 0);
755 // Verify that all available recording devices can be set (not enabled yet).
756 for (int i = 0; i < num_devices; ++i) {
757 EXPECT_EQ(0, audio_device()->SetRecordingDevice(i));
758 }
759 EXPECT_EQ(-1, audio_device()->SetRecordingDevice(num_devices));
760#ifdef WEBRTC_WIN
761 // On Windows, verify the alternative method where the user can select device
762 // by role.
763 EXPECT_EQ(
764 0, audio_device()->SetRecordingDevice(AudioDeviceModule::kDefaultDevice));
765 EXPECT_EQ(0, audio_device()->SetRecordingDevice(
766 AudioDeviceModule::kDefaultCommunicationDevice));
767#endif
768}
769
770// Tests Start/Stop playout without any registered audio callback.
771TEST_P(AudioDeviceTest, StartStopPlayout) {
772 SKIP_TEST_IF_NOT(requirements_satisfied());
henrikaf2f91fa2017-03-17 04:26:22 -0700773 StartPlayout();
774 StopPlayout();
775}
776
777// Tests Start/Stop recording without any registered audio callback.
henrikaec9c7452018-06-08 16:10:03 +0200778TEST_P(AudioDeviceTest, StartStopRecording) {
henrikaf2f91fa2017-03-17 04:26:22 -0700779 SKIP_TEST_IF_NOT(requirements_satisfied());
780 StartRecording();
781 StopRecording();
henrikaf2f91fa2017-03-17 04:26:22 -0700782}
783
henrika6b3e1a22017-09-25 16:34:30 +0200784// Tests Init/Stop/Init recording without any registered audio callback.
785// See https://bugs.chromium.org/p/webrtc/issues/detail?id=8041 for details
786// on why this test is useful.
henrikaec9c7452018-06-08 16:10:03 +0200787TEST_P(AudioDeviceTest, InitStopInitRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200788 SKIP_TEST_IF_NOT(requirements_satisfied());
789 EXPECT_EQ(0, audio_device()->InitRecording());
790 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
791 StopRecording();
792 EXPECT_EQ(0, audio_device()->InitRecording());
793 StopRecording();
794}
795
796// Tests Init/Stop/Init recording while playout is active.
henrikaec9c7452018-06-08 16:10:03 +0200797TEST_P(AudioDeviceTest, InitStopInitRecordingWhilePlaying) {
henrika6b3e1a22017-09-25 16:34:30 +0200798 SKIP_TEST_IF_NOT(requirements_satisfied());
799 StartPlayout();
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 StopPlayout();
806}
807
808// Tests Init/Stop/Init playout without any registered audio callback.
henrikaec9c7452018-06-08 16:10:03 +0200809TEST_P(AudioDeviceTest, InitStopInitPlayout) {
henrika6b3e1a22017-09-25 16:34:30 +0200810 SKIP_TEST_IF_NOT(requirements_satisfied());
811 EXPECT_EQ(0, audio_device()->InitPlayout());
812 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
813 StopPlayout();
814 EXPECT_EQ(0, audio_device()->InitPlayout());
815 StopPlayout();
816}
817
818// Tests Init/Stop/Init playout while recording is active.
henrikaec9c7452018-06-08 16:10:03 +0200819TEST_P(AudioDeviceTest, InitStopInitPlayoutWhileRecording) {
henrika6b3e1a22017-09-25 16:34:30 +0200820 SKIP_TEST_IF_NOT(requirements_satisfied());
821 StartRecording();
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 StopRecording();
828}
829
henrika5b6afc02018-09-05 14:34:40 +0200830// TODO(henrika): restart without intermediate destruction is currently only
831// supported on Windows.
832#ifdef WEBRTC_WIN
833// Tests Start/Stop playout followed by a second session (emulates a restart
834// triggered by a user using public APIs).
835TEST_P(AudioDeviceTest, StartStopPlayoutWithExternalRestart) {
836 SKIP_TEST_IF_NOT(requirements_satisfied());
837 StartPlayout();
838 StopPlayout();
839 // Restart playout without destroying the ADM in between. Ensures that we
840 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
841 StartPlayout();
842 StopPlayout();
843}
844
845// Tests Start/Stop recording followed by a second session (emulates a restart
846// triggered by a user using public APIs).
847TEST_P(AudioDeviceTest, StartStopRecordingWithExternalRestart) {
848 SKIP_TEST_IF_NOT(requirements_satisfied());
849 StartRecording();
850 StopRecording();
851 // Restart recording without destroying the ADM in between. Ensures that we
852 // support: Init(), Start(), Stop(), Init(), Start(), Stop().
853 StartRecording();
854 StopRecording();
855}
856
857// Tests Start/Stop playout followed by a second session (emulates a restart
858// triggered by an internal callback e.g. corresponding to a device switch).
859// Note that, internal restart is only supported in combination with the latest
860// Windows ADM.
861TEST_P(AudioDeviceTest, StartStopPlayoutWithInternalRestart) {
862 SKIP_TEST_IF_NOT(requirements_satisfied());
863 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
864 return;
865 }
866 MockAudioTransport mock(TransportType::kPlay);
867 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
868 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
869 .Times(AtLeast(kNumCallbacks));
870 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
871 StartPlayout();
872 event()->Wait(kTestTimeOutInMilliseconds);
873 EXPECT_TRUE(audio_device()->Playing());
874 // Restart playout but without stopping the internal audio thread.
875 // This procedure uses a non-public test API and it emulates what happens
876 // inside the ADM when e.g. a device is removed.
877 EXPECT_EQ(0, audio_device()->RestartPlayoutInternally());
878
879 // Run basic tests of public APIs while a restart attempt is active.
880 // These calls should now be very thin and not trigger any new actions.
881 EXPECT_EQ(-1, audio_device()->StopPlayout());
882 EXPECT_TRUE(audio_device()->Playing());
883 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
884 EXPECT_EQ(0, audio_device()->InitPlayout());
885 EXPECT_EQ(0, audio_device()->StartPlayout());
886
887 // Wait until audio has restarted and a new sequence of audio callbacks
888 // becomes active.
889 // TODO(henrika): is it possible to verify that the internal state transition
890 // is Stop->Init->Start?
891 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
892 mock.ResetCallbackCounters();
893 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
894 .Times(AtLeast(kNumCallbacks));
895 event()->Wait(kTestTimeOutInMilliseconds);
896 EXPECT_TRUE(audio_device()->Playing());
897 // Stop playout and the audio thread after successful internal restart.
898 StopPlayout();
899}
900
901// Tests Start/Stop recording followed by a second session (emulates a restart
902// triggered by an internal callback e.g. corresponding to a device switch).
903// Note that, internal restart is only supported in combination with the latest
904// Windows ADM.
905TEST_P(AudioDeviceTest, StartStopRecordingWithInternalRestart) {
906 SKIP_TEST_IF_NOT(requirements_satisfied());
907 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
908 return;
909 }
910 MockAudioTransport mock(TransportType::kRecord);
911 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
912 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
913 false, _))
914 .Times(AtLeast(kNumCallbacks));
915 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
916 StartRecording();
917 event()->Wait(kTestTimeOutInMilliseconds);
918 EXPECT_TRUE(audio_device()->Recording());
919 // Restart recording but without stopping the internal audio thread.
920 // This procedure uses a non-public test API and it emulates what happens
921 // inside the ADM when e.g. a device is removed.
922 EXPECT_EQ(0, audio_device()->RestartRecordingInternally());
923
924 // Run basic tests of public APIs while a restart attempt is active.
925 // These calls should now be very thin and not trigger any new actions.
926 EXPECT_EQ(-1, audio_device()->StopRecording());
927 EXPECT_TRUE(audio_device()->Recording());
928 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
929 EXPECT_EQ(0, audio_device()->InitRecording());
930 EXPECT_EQ(0, audio_device()->StartRecording());
931
932 // Wait until audio has restarted and a new sequence of audio callbacks
933 // becomes active.
934 // TODO(henrika): is it possible to verify that the internal state transition
935 // is Stop->Init->Start?
936 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&mock));
937 mock.ResetCallbackCounters();
938 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
939 false, _))
940 .Times(AtLeast(kNumCallbacks));
941 event()->Wait(kTestTimeOutInMilliseconds);
942 EXPECT_TRUE(audio_device()->Recording());
943 // Stop recording and the audio thread after successful internal restart.
944 StopRecording();
945}
946#endif // #ifdef WEBRTC_WIN
947
henrikaf2f91fa2017-03-17 04:26:22 -0700948// Start playout and verify that the native audio layer starts asking for real
949// audio samples to play out using the NeedMorePlayData() callback.
950// Note that we can't add expectations on audio parameters in EXPECT_CALL
951// since parameter are not provided in the each callback. We therefore test and
952// verify the parameters in the fake audio transport implementation instead.
henrikaec9c7452018-06-08 16:10:03 +0200953TEST_P(AudioDeviceTest, StartPlayoutVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700954 SKIP_TEST_IF_NOT(requirements_satisfied());
955 MockAudioTransport mock(TransportType::kPlay);
henrikae24991d2017-04-06 01:14:23 -0700956 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700957 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
958 .Times(AtLeast(kNumCallbacks));
959 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
960 StartPlayout();
961 event()->Wait(kTestTimeOutInMilliseconds);
962 StopPlayout();
963}
964
965// Start recording and verify that the native audio layer starts providing real
966// audio samples using the RecordedDataIsAvailable() callback.
henrikaec9c7452018-06-08 16:10:03 +0200967TEST_P(AudioDeviceTest, StartRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700968 SKIP_TEST_IF_NOT(requirements_satisfied());
969 MockAudioTransport mock(TransportType::kRecord);
henrikae24991d2017-04-06 01:14:23 -0700970 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700971 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
972 false, _))
973 .Times(AtLeast(kNumCallbacks));
974 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
975 StartRecording();
976 event()->Wait(kTestTimeOutInMilliseconds);
977 StopRecording();
978}
979
980// Start playout and recording (full-duplex audio) and verify that audio is
981// active in both directions.
henrikaec9c7452018-06-08 16:10:03 +0200982TEST_P(AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700983 SKIP_TEST_IF_NOT(requirements_satisfied());
984 MockAudioTransport mock(TransportType::kPlayAndRecord);
henrikae24991d2017-04-06 01:14:23 -0700985 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700986 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
987 .Times(AtLeast(kNumCallbacks));
988 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
989 false, _))
990 .Times(AtLeast(kNumCallbacks));
991 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
992 StartPlayout();
993 StartRecording();
994 event()->Wait(kTestTimeOutInMilliseconds);
995 StopRecording();
996 StopPlayout();
997}
998
henrikae24991d2017-04-06 01:14:23 -0700999// Start playout and recording and store recorded data in an intermediate FIFO
1000// buffer from which the playout side then reads its samples in the same order
1001// as they were stored. Under ideal circumstances, a callback sequence would
1002// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
1003// means 'packet played'. Under such conditions, the FIFO would contain max 1,
1004// with an average somewhere in (0,1) depending on how long the packets are
1005// buffered. However, under more realistic conditions, the size
1006// of the FIFO will vary more due to an unbalance between the two sides.
1007// This test tries to verify that the device maintains a balanced callback-
1008// sequence by running in loopback for a few seconds while measuring the size
1009// (max and average) of the FIFO. The size of the FIFO is increased by the
1010// recording side and decreased by the playout side.
henrikaec9c7452018-06-08 16:10:03 +02001011TEST_P(AudioDeviceTest, RunPlayoutAndRecordingInFullDuplex) {
henrikae24991d2017-04-06 01:14:23 -07001012 SKIP_TEST_IF_NOT(requirements_satisfied());
1013 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1014 FifoAudioStream audio_stream;
1015 mock.HandleCallbacks(event(), &audio_stream,
1016 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
1017 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001018 // Run both sides using the same channel configuration to avoid conversions
1019 // between mono/stereo while running in full duplex mode. Also, some devices
1020 // (mainly on Windows) do not support mono.
1021 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1022 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrikae24991d2017-04-06 01:14:23 -07001023 StartPlayout();
1024 StartRecording();
henrika714e5cd2017-04-20 08:03:11 -07001025 event()->Wait(static_cast<int>(
1026 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec)));
henrikae24991d2017-04-06 01:14:23 -07001027 StopRecording();
1028 StopPlayout();
1029 // This thresholds is set rather high to accommodate differences in hardware
1030 // in several devices. The main idea is to capture cases where a very large
henrikab6ca7212017-10-06 12:47:52 +02001031 // latency is built up. See http://bugs.webrtc.org/7744 for examples on
1032 // bots where relatively large average latencies can happen.
1033 EXPECT_LE(audio_stream.average_size(), 25u);
henrikae24991d2017-04-06 01:14:23 -07001034 PRINT("\n");
1035}
1036
henrika5b6afc02018-09-05 14:34:40 +02001037// Runs audio in full duplex until user hits Enter. Intended as a manual test
1038// to ensure that the audio quality is good and that real device switches works
1039// as intended.
1040TEST_P(AudioDeviceTest,
1041 DISABLED_RunPlayoutAndRecordingInFullDuplexAndWaitForEnterKey) {
1042 SKIP_TEST_IF_NOT(requirements_satisfied());
1043 if (audio_layer() != AudioDeviceModule::kWindowsCoreAudio2) {
1044 return;
1045 }
1046 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1047 FifoAudioStream audio_stream;
1048 mock.HandleCallbacks(&audio_stream);
1049 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
1050 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1051 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
1052 // Ensure that the sample rate for both directions are identical so that we
1053 // always can listen to our own voice. Will lead to rate conversion (and
1054 // higher latency) if the native sample rate is not 48kHz.
1055 EXPECT_EQ(0, audio_device()->SetPlayoutSampleRate(48000));
1056 EXPECT_EQ(0, audio_device()->SetRecordingSampleRate(48000));
1057 StartPlayout();
1058 StartRecording();
1059 do {
1060 PRINT("Loopback audio is active at 48kHz. Press Enter to stop.\n");
1061 } while (getchar() != '\n');
1062 StopRecording();
1063 StopPlayout();
1064}
1065
henrika714e5cd2017-04-20 08:03:11 -07001066// Measures loopback latency and reports the min, max and average values for
1067// a full duplex audio session.
1068// The latency is measured like so:
1069// - Insert impulses periodically on the output side.
1070// - Detect the impulses on the input side.
1071// - Measure the time difference between the transmit time and receive time.
1072// - Store time differences in a vector and calculate min, max and average.
1073// This test needs the '--gtest_also_run_disabled_tests' flag to run and also
1074// some sort of audio feedback loop. E.g. a headset where the mic is placed
1075// close to the speaker to ensure highest possible echo. It is also recommended
1076// to run the test at highest possible output volume.
henrikaec9c7452018-06-08 16:10:03 +02001077TEST_P(AudioDeviceTest, DISABLED_MeasureLoopbackLatency) {
henrika714e5cd2017-04-20 08:03:11 -07001078 SKIP_TEST_IF_NOT(requirements_satisfied());
1079 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
1080 LatencyAudioStream audio_stream;
1081 mock.HandleCallbacks(event(), &audio_stream,
1082 kMeasureLatencyTimeInSec * kNumCallbacksPerSecond);
1083 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
henrikaeb98c722018-03-20 12:54:07 +01001084 EXPECT_EQ(0, audio_device()->SetStereoPlayout(true));
1085 EXPECT_EQ(0, audio_device()->SetStereoRecording(true));
henrika714e5cd2017-04-20 08:03:11 -07001086 StartPlayout();
1087 StartRecording();
1088 event()->Wait(static_cast<int>(
1089 std::max(kTestTimeOutInMilliseconds, 1000 * kMeasureLatencyTimeInSec)));
1090 StopRecording();
1091 StopPlayout();
henrikac7d93582018-09-14 15:37:34 +02001092 // Verify that a sufficient number of transmitted impulses are detected.
1093 EXPECT_GE(audio_stream.num_latency_values(),
henrika714e5cd2017-04-20 08:03:11 -07001094 static_cast<size_t>(
henrikac7d93582018-09-14 15:37:34 +02001095 kImpulseFrequencyInHz * kMeasureLatencyTimeInSec - 2));
henrika714e5cd2017-04-20 08:03:11 -07001096 // Print out min, max and average delay values for debugging purposes.
1097 audio_stream.PrintResults();
1098}
1099
henrikaec9c7452018-06-08 16:10:03 +02001100#ifdef WEBRTC_WIN
1101// Test two different audio layers (or rather two different Core Audio
1102// implementations) for Windows.
1103INSTANTIATE_TEST_CASE_P(
1104 AudioLayerWin,
1105 AudioDeviceTest,
1106 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio,
1107 AudioDeviceModule::kWindowsCoreAudio2));
1108#else
1109// For all platforms but Windows, only test the default audio layer.
1110INSTANTIATE_TEST_CASE_P(
1111 AudioLayer,
1112 AudioDeviceTest,
1113 ::testing::Values(AudioDeviceModule::kPlatformDefaultAudio));
1114#endif
1115
henrikaf2f91fa2017-03-17 04:26:22 -07001116} // namespace webrtc