blob: effbf1e08ff052e515315150ec56db16f83b8715 [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
11#include <cstring>
12
henrikae24991d2017-04-06 01:14:23 -070013#include "webrtc/base/array_view.h"
14#include "webrtc/base/buffer.h"
15#include "webrtc/base/criticalsection.h"
henrikaf2f91fa2017-03-17 04:26:22 -070016#include "webrtc/base/event.h"
17#include "webrtc/base/logging.h"
henrikae24991d2017-04-06 01:14:23 -070018#include "webrtc/base/race_checker.h"
henrikaf2f91fa2017-03-17 04:26:22 -070019#include "webrtc/base/scoped_ref_ptr.h"
henrikae24991d2017-04-06 01:14:23 -070020#include "webrtc/base/thread_annotations.h"
henrikaf2f91fa2017-03-17 04:26:22 -070021#include "webrtc/modules/audio_device/audio_device_impl.h"
22#include "webrtc/modules/audio_device/include/audio_device.h"
23#include "webrtc/modules/audio_device/include/mock_audio_transport.h"
24#include "webrtc/system_wrappers/include/sleep.h"
25#include "webrtc/test/gmock.h"
26#include "webrtc/test/gtest.h"
27
28using ::testing::_;
29using ::testing::AtLeast;
30using ::testing::Ge;
31using ::testing::Invoke;
32using ::testing::NiceMock;
33using ::testing::NotNull;
34
35namespace webrtc {
36namespace {
37
henrikae24991d2017-04-06 01:14:23 -070038// #define ENABLE_DEBUG_PRINTF
39#ifdef ENABLE_DEBUG_PRINTF
40#define PRINTD(...) fprintf(stderr, __VA_ARGS__);
41#else
42#define PRINTD(...) ((void)0)
43#endif
44#define PRINT(...) fprintf(stderr, __VA_ARGS__);
45
henrikaf2f91fa2017-03-17 04:26:22 -070046// Don't run these tests in combination with sanitizers.
47#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
48#define SKIP_TEST_IF_NOT(requirements_satisfied) \
49 do { \
50 if (!requirements_satisfied) { \
51 return; \
52 } \
53 } while (false)
54#else
55// Or if other audio-related requirements are not met.
56#define SKIP_TEST_IF_NOT(requirements_satisfied) \
57 do { \
58 return; \
59 } while (false)
60#endif
61
62// Number of callbacks (input or output) the tests waits for before we set
63// an event indicating that the test was OK.
henrikae24991d2017-04-06 01:14:23 -070064static constexpr size_t kNumCallbacks = 10;
henrikaf2f91fa2017-03-17 04:26:22 -070065// Max amount of time we wait for an event to be set while counting callbacks.
henrikae24991d2017-04-06 01:14:23 -070066static constexpr int kTestTimeOutInMilliseconds = 10 * 1000;
67// Average number of audio callbacks per second assuming 10ms packet size.
68static constexpr size_t kNumCallbacksPerSecond = 100;
69// Run the full-duplex test during this time (unit is in seconds).
70static constexpr int kFullDuplexTimeInSec = 5;
henrikaf2f91fa2017-03-17 04:26:22 -070071
72enum class TransportType {
73 kInvalid,
74 kPlay,
75 kRecord,
76 kPlayAndRecord,
77};
henrikae24991d2017-04-06 01:14:23 -070078
79// Interface for processing the audio stream. Real implementations can e.g.
80// run audio in loopback, read audio from a file or perform latency
81// measurements.
82class AudioStream {
83 public:
84 virtual void Write(rtc::ArrayView<const int16_t> source, size_t channels) = 0;
85 virtual void Read(rtc::ArrayView<int16_t> destination, size_t channels) = 0;
86
87 virtual ~AudioStream() = default;
88};
89
henrikaf2f91fa2017-03-17 04:26:22 -070090} // namespace
91
henrikae24991d2017-04-06 01:14:23 -070092// Simple first in first out (FIFO) class that wraps a list of 16-bit audio
93// buffers of fixed size and allows Write and Read operations. The idea is to
94// store recorded audio buffers (using Write) and then read (using Read) these
95// stored buffers with as short delay as possible when the audio layer needs
96// data to play out. The number of buffers in the FIFO will stabilize under
97// normal conditions since there will be a balance between Write and Read calls.
98// The container is a std::list container and access is protected with a lock
99// since both sides (playout and recording) are driven by its own thread.
100// Note that, we know by design that the size of the audio buffer will not
101// change over time and that both sides will use the same size.
102class FifoAudioStream : public AudioStream {
103 public:
104 void Write(rtc::ArrayView<const int16_t> source, size_t channels) override {
105 EXPECT_EQ(channels, 1u);
106 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
107 const size_t size = [&] {
108 rtc::CritScope lock(&lock_);
109 fifo_.push_back(Buffer16(source.data(), source.size()));
110 return fifo_.size();
111 }();
112 if (size > max_size_) {
113 max_size_ = size;
114 }
115 // Add marker once per second to signal that audio is active.
116 if (write_count_++ % 100 == 0) {
117 PRINT(".");
118 }
119 written_elements_ += size;
120 }
121
122 void Read(rtc::ArrayView<int16_t> destination, size_t channels) override {
123 EXPECT_EQ(channels, 1u);
124 rtc::CritScope lock(&lock_);
125 if (fifo_.empty()) {
126 std::fill(destination.begin(), destination.end(), 0);
127 } else {
128 const Buffer16& buffer = fifo_.front();
129 RTC_CHECK_EQ(buffer.size(), destination.size());
130 std::copy(buffer.begin(), buffer.end(), destination.begin());
131 fifo_.pop_front();
132 }
133 }
134
135 size_t size() const {
136 rtc::CritScope lock(&lock_);
137 return fifo_.size();
138 }
139
140 size_t max_size() const {
141 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
142 return max_size_;
143 }
144
145 size_t average_size() const {
146 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
147 return 0.5 + static_cast<float>(written_elements_ / write_count_);
148 }
149
150 using Buffer16 = rtc::BufferT<int16_t>;
151
152 rtc::CriticalSection lock_;
153 rtc::RaceChecker race_checker_;
154
155 std::list<Buffer16> fifo_ GUARDED_BY(lock_);
156 size_t write_count_ GUARDED_BY(race_checker_) = 0;
157 size_t max_size_ GUARDED_BY(race_checker_) = 0;
158 size_t written_elements_ GUARDED_BY(race_checker_) = 0;
159};
160
henrikaf2f91fa2017-03-17 04:26:22 -0700161// Mocks the AudioTransport object and proxies actions for the two callbacks
162// (RecordedDataIsAvailable and NeedMorePlayData) to different implementations
163// of AudioStreamInterface.
164class MockAudioTransport : public test::MockAudioTransport {
165 public:
166 explicit MockAudioTransport(TransportType type) : type_(type) {}
167 ~MockAudioTransport() {}
168
169 // Set default actions of the mock object. We are delegating to fake
170 // implementation where the number of callbacks is counted and an event
171 // is set after a certain number of callbacks. Audio parameters are also
172 // checked.
henrikae24991d2017-04-06 01:14:23 -0700173 void HandleCallbacks(rtc::Event* event,
174 AudioStream* audio_stream,
175 int num_callbacks) {
henrikaf2f91fa2017-03-17 04:26:22 -0700176 event_ = event;
henrikae24991d2017-04-06 01:14:23 -0700177 audio_stream_ = audio_stream;
henrikaf2f91fa2017-03-17 04:26:22 -0700178 num_callbacks_ = num_callbacks;
179 if (play_mode()) {
180 ON_CALL(*this, NeedMorePlayData(_, _, _, _, _, _, _, _))
181 .WillByDefault(
182 Invoke(this, &MockAudioTransport::RealNeedMorePlayData));
183 }
184 if (rec_mode()) {
185 ON_CALL(*this, RecordedDataIsAvailable(_, _, _, _, _, _, _, _, _, _))
186 .WillByDefault(
187 Invoke(this, &MockAudioTransport::RealRecordedDataIsAvailable));
188 }
189 }
190
191 int32_t RealRecordedDataIsAvailable(const void* audio_buffer,
192 const size_t samples_per_channel,
193 const size_t bytes_per_frame,
194 const size_t channels,
195 const uint32_t sample_rate,
196 const uint32_t total_delay_ms,
197 const int32_t clock_drift,
198 const uint32_t current_mic_level,
199 const bool typing_status,
200 uint32_t& new_mic_level) {
201 EXPECT_TRUE(rec_mode()) << "No test is expecting these callbacks.";
202 LOG(INFO) << "+";
203 // Store audio parameters once in the first callback. For all other
204 // callbacks, verify that the provided audio parameters are maintained and
205 // that each callback corresponds to 10ms for any given sample rate.
206 if (!record_parameters_.is_complete()) {
207 record_parameters_.reset(sample_rate, channels, samples_per_channel);
208 } else {
209 EXPECT_EQ(samples_per_channel, record_parameters_.frames_per_buffer());
210 EXPECT_EQ(bytes_per_frame, record_parameters_.GetBytesPerFrame());
211 EXPECT_EQ(channels, record_parameters_.channels());
212 EXPECT_EQ(static_cast<int>(sample_rate),
213 record_parameters_.sample_rate());
214 EXPECT_EQ(samples_per_channel,
215 record_parameters_.frames_per_10ms_buffer());
216 }
217 rec_count_++;
henrikae24991d2017-04-06 01:14:23 -0700218 // Write audio data to audio stream object if one has been injected.
219 if (audio_stream_) {
220 audio_stream_->Write(
221 rtc::MakeArrayView(static_cast<const int16_t*>(audio_buffer),
222 samples_per_channel * channels),
223 channels);
224 }
henrikaf2f91fa2017-03-17 04:26:22 -0700225 // Signal the event after given amount of callbacks.
226 if (ReceivedEnoughCallbacks()) {
227 event_->Set();
228 }
229 return 0;
230 }
231
232 int32_t RealNeedMorePlayData(const size_t samples_per_channel,
233 const size_t bytes_per_frame,
234 const size_t channels,
235 const uint32_t sample_rate,
236 void* audio_buffer,
237 size_t& samples_per_channel_out,
238 int64_t* elapsed_time_ms,
239 int64_t* ntp_time_ms) {
240 EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
241 LOG(INFO) << "-";
242 // Store audio parameters once in the first callback. For all other
243 // callbacks, verify that the provided audio parameters are maintained and
244 // that each callback corresponds to 10ms for any given sample rate.
245 if (!playout_parameters_.is_complete()) {
246 playout_parameters_.reset(sample_rate, channels, samples_per_channel);
247 } else {
248 EXPECT_EQ(samples_per_channel, playout_parameters_.frames_per_buffer());
249 EXPECT_EQ(bytes_per_frame, playout_parameters_.GetBytesPerFrame());
250 EXPECT_EQ(channels, playout_parameters_.channels());
251 EXPECT_EQ(static_cast<int>(sample_rate),
252 playout_parameters_.sample_rate());
253 EXPECT_EQ(samples_per_channel,
254 playout_parameters_.frames_per_10ms_buffer());
255 }
256 play_count_++;
257 samples_per_channel_out = samples_per_channel;
henrikae24991d2017-04-06 01:14:23 -0700258 // Read audio data from audio stream object if one has been injected.
259 if (audio_stream_) {
260 audio_stream_->Read(
261 rtc::MakeArrayView(static_cast<int16_t*>(audio_buffer),
262 samples_per_channel * channels),
263 channels);
264 } else {
265 // Fill the audio buffer with zeros to avoid disturbing audio.
266 const size_t num_bytes = samples_per_channel * bytes_per_frame;
267 std::memset(audio_buffer, 0, num_bytes);
268 }
henrikaf2f91fa2017-03-17 04:26:22 -0700269 // Signal the event after given amount of callbacks.
270 if (ReceivedEnoughCallbacks()) {
271 event_->Set();
272 }
273 return 0;
274 }
275
276 bool ReceivedEnoughCallbacks() {
277 bool recording_done = false;
278 if (rec_mode()) {
279 recording_done = rec_count_ >= num_callbacks_;
280 } else {
281 recording_done = true;
282 }
283 bool playout_done = false;
284 if (play_mode()) {
285 playout_done = play_count_ >= num_callbacks_;
286 } else {
287 playout_done = true;
288 }
289 return recording_done && playout_done;
290 }
291
292 bool play_mode() const {
293 return type_ == TransportType::kPlay ||
294 type_ == TransportType::kPlayAndRecord;
295 }
296
297 bool rec_mode() const {
298 return type_ == TransportType::kRecord ||
299 type_ == TransportType::kPlayAndRecord;
300 }
301
302 private:
303 TransportType type_ = TransportType::kInvalid;
304 rtc::Event* event_ = nullptr;
henrikae24991d2017-04-06 01:14:23 -0700305 AudioStream* audio_stream_ = nullptr;
henrikaf2f91fa2017-03-17 04:26:22 -0700306 size_t num_callbacks_ = 0;
307 size_t play_count_ = 0;
308 size_t rec_count_ = 0;
309 AudioParameters playout_parameters_;
310 AudioParameters record_parameters_;
311};
312
313// AudioDeviceTest test fixture.
314class AudioDeviceTest : public ::testing::Test {
315 protected:
316 AudioDeviceTest() : event_(false, false) {
317#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
318 rtc::LogMessage::LogToDebug(rtc::LS_INFO);
319 // Add extra logging fields here if needed for debugging.
320 // rtc::LogMessage::LogTimestamps();
321 // rtc::LogMessage::LogThreads();
322 audio_device_ =
323 AudioDeviceModule::Create(0, AudioDeviceModule::kPlatformDefaultAudio);
324 EXPECT_NE(audio_device_.get(), nullptr);
325 AudioDeviceModule::AudioLayer audio_layer;
maxmorin33bf69a2017-03-23 04:06:53 -0700326 int got_platform_audio_layer =
327 audio_device_->ActiveAudioLayer(&audio_layer);
328 if (got_platform_audio_layer != 0 ||
329 audio_layer == AudioDeviceModule::kLinuxAlsaAudio) {
henrikaf2f91fa2017-03-17 04:26:22 -0700330 requirements_satisfied_ = false;
331 }
332 if (requirements_satisfied_) {
333 EXPECT_EQ(0, audio_device_->Init());
334 const int16_t num_playout_devices = audio_device_->PlayoutDevices();
335 const int16_t num_record_devices = audio_device_->RecordingDevices();
336 requirements_satisfied_ =
337 num_playout_devices > 0 && num_record_devices > 0;
338 }
339#else
340 requirements_satisfied_ = false;
341#endif
342 if (requirements_satisfied_) {
343 EXPECT_EQ(0, audio_device_->SetPlayoutDevice(0));
344 EXPECT_EQ(0, audio_device_->InitSpeaker());
345 EXPECT_EQ(0, audio_device_->SetRecordingDevice(0));
346 EXPECT_EQ(0, audio_device_->InitMicrophone());
347 EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
348 EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
henrika0238ba82017-03-28 04:38:29 -0700349 // Avoid asking for input stereo support and always record in mono
350 // since asking can cause issues in combination with remote desktop.
351 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
352 // details.
353 EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
henrikaf2f91fa2017-03-17 04:26:22 -0700354 EXPECT_EQ(0, audio_device_->SetAGC(false));
355 EXPECT_FALSE(audio_device_->AGC());
356 }
357 }
358
359 virtual ~AudioDeviceTest() {
360 if (audio_device_) {
361 EXPECT_EQ(0, audio_device_->Terminate());
362 }
363 }
364
365 bool requirements_satisfied() const { return requirements_satisfied_; }
366 rtc::Event* event() { return &event_; }
367
368 const rtc::scoped_refptr<AudioDeviceModule>& audio_device() const {
369 return audio_device_;
370 }
371
372 void StartPlayout() {
373 EXPECT_FALSE(audio_device()->Playing());
374 EXPECT_EQ(0, audio_device()->InitPlayout());
375 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
376 EXPECT_EQ(0, audio_device()->StartPlayout());
377 EXPECT_TRUE(audio_device()->Playing());
378 }
379
380 void StopPlayout() {
381 EXPECT_EQ(0, audio_device()->StopPlayout());
382 EXPECT_FALSE(audio_device()->Playing());
383 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
384 }
385
386 void StartRecording() {
387 EXPECT_FALSE(audio_device()->Recording());
388 EXPECT_EQ(0, audio_device()->InitRecording());
389 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
390 EXPECT_EQ(0, audio_device()->StartRecording());
391 EXPECT_TRUE(audio_device()->Recording());
392 }
393
394 void StopRecording() {
395 EXPECT_EQ(0, audio_device()->StopRecording());
396 EXPECT_FALSE(audio_device()->Recording());
397 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
398 }
399
400 private:
401 bool requirements_satisfied_ = true;
402 rtc::Event event_;
403 rtc::scoped_refptr<AudioDeviceModule> audio_device_;
404 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700405};
406
407// Uses the test fixture to create, initialize and destruct the ADM.
408TEST_F(AudioDeviceTest, ConstructDestruct) {}
409
410TEST_F(AudioDeviceTest, InitTerminate) {
411 SKIP_TEST_IF_NOT(requirements_satisfied());
412 // Initialization is part of the test fixture.
413 EXPECT_TRUE(audio_device()->Initialized());
414 EXPECT_EQ(0, audio_device()->Terminate());
415 EXPECT_FALSE(audio_device()->Initialized());
416}
417
418// Tests Start/Stop playout without any registered audio callback.
419TEST_F(AudioDeviceTest, StartStopPlayout) {
420 SKIP_TEST_IF_NOT(requirements_satisfied());
421 StartPlayout();
422 StopPlayout();
423 StartPlayout();
424 StopPlayout();
425}
426
427// Tests Start/Stop recording without any registered audio callback.
428TEST_F(AudioDeviceTest, StartStopRecording) {
429 SKIP_TEST_IF_NOT(requirements_satisfied());
430 StartRecording();
431 StopRecording();
432 StartRecording();
433 StopRecording();
434}
435
436// Start playout and verify that the native audio layer starts asking for real
437// audio samples to play out using the NeedMorePlayData() callback.
438// Note that we can't add expectations on audio parameters in EXPECT_CALL
439// since parameter are not provided in the each callback. We therefore test and
440// verify the parameters in the fake audio transport implementation instead.
441TEST_F(AudioDeviceTest, StartPlayoutVerifyCallbacks) {
442 SKIP_TEST_IF_NOT(requirements_satisfied());
443 MockAudioTransport mock(TransportType::kPlay);
henrikae24991d2017-04-06 01:14:23 -0700444 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700445 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
446 .Times(AtLeast(kNumCallbacks));
447 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
448 StartPlayout();
449 event()->Wait(kTestTimeOutInMilliseconds);
450 StopPlayout();
451}
452
453// Start recording and verify that the native audio layer starts providing real
454// audio samples using the RecordedDataIsAvailable() callback.
455TEST_F(AudioDeviceTest, StartRecordingVerifyCallbacks) {
456 SKIP_TEST_IF_NOT(requirements_satisfied());
457 MockAudioTransport mock(TransportType::kRecord);
henrikae24991d2017-04-06 01:14:23 -0700458 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700459 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
460 false, _))
461 .Times(AtLeast(kNumCallbacks));
462 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
463 StartRecording();
464 event()->Wait(kTestTimeOutInMilliseconds);
465 StopRecording();
466}
467
468// Start playout and recording (full-duplex audio) and verify that audio is
469// active in both directions.
470TEST_F(AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
471 SKIP_TEST_IF_NOT(requirements_satisfied());
472 MockAudioTransport mock(TransportType::kPlayAndRecord);
henrikae24991d2017-04-06 01:14:23 -0700473 mock.HandleCallbacks(event(), nullptr, kNumCallbacks);
henrikaf2f91fa2017-03-17 04:26:22 -0700474 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
475 .Times(AtLeast(kNumCallbacks));
476 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
477 false, _))
478 .Times(AtLeast(kNumCallbacks));
479 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
480 StartPlayout();
481 StartRecording();
482 event()->Wait(kTestTimeOutInMilliseconds);
483 StopRecording();
484 StopPlayout();
485}
486
henrikae24991d2017-04-06 01:14:23 -0700487// Start playout and recording and store recorded data in an intermediate FIFO
488// buffer from which the playout side then reads its samples in the same order
489// as they were stored. Under ideal circumstances, a callback sequence would
490// look like: ...+-+-+-+-+-+-+-..., where '+' means 'packet recorded' and '-'
491// means 'packet played'. Under such conditions, the FIFO would contain max 1,
492// with an average somewhere in (0,1) depending on how long the packets are
493// buffered. However, under more realistic conditions, the size
494// of the FIFO will vary more due to an unbalance between the two sides.
495// This test tries to verify that the device maintains a balanced callback-
496// sequence by running in loopback for a few seconds while measuring the size
497// (max and average) of the FIFO. The size of the FIFO is increased by the
498// recording side and decreased by the playout side.
499TEST_F(AudioDeviceTest, RunPlayoutAndRecordingInFullDuplex) {
500 SKIP_TEST_IF_NOT(requirements_satisfied());
501 NiceMock<MockAudioTransport> mock(TransportType::kPlayAndRecord);
502 FifoAudioStream audio_stream;
503 mock.HandleCallbacks(event(), &audio_stream,
504 kFullDuplexTimeInSec * kNumCallbacksPerSecond);
505 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
506 // Run both sides in mono to make the loopback packet handling less complex.
507 // The test works for stereo as well; the only requirement is that both sides
508 // use the same configuration.
509 EXPECT_EQ(0, audio_device()->SetStereoPlayout(false));
510 EXPECT_EQ(0, audio_device()->SetStereoRecording(false));
511 StartPlayout();
512 StartRecording();
513 event()->Wait(
514 std::max(kTestTimeOutInMilliseconds, 1000 * kFullDuplexTimeInSec));
515 StopRecording();
516 StopPlayout();
517 // This thresholds is set rather high to accommodate differences in hardware
518 // in several devices. The main idea is to capture cases where a very large
519 // latency is built up.
520 EXPECT_LE(audio_stream.average_size(), 5u);
521 PRINT("\n");
522}
523
henrikaf2f91fa2017-03-17 04:26:22 -0700524} // namespace webrtc