blob: de9c197945d87ba3b2e681ed204c1a7e8844604d [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
13#include "webrtc/base/event.h"
14#include "webrtc/base/logging.h"
15#include "webrtc/base/scoped_ref_ptr.h"
16#include "webrtc/modules/audio_device/audio_device_impl.h"
17#include "webrtc/modules/audio_device/include/audio_device.h"
18#include "webrtc/modules/audio_device/include/mock_audio_transport.h"
19#include "webrtc/system_wrappers/include/sleep.h"
20#include "webrtc/test/gmock.h"
21#include "webrtc/test/gtest.h"
22
23using ::testing::_;
24using ::testing::AtLeast;
25using ::testing::Ge;
26using ::testing::Invoke;
27using ::testing::NiceMock;
28using ::testing::NotNull;
29
30namespace webrtc {
31namespace {
32
33// Don't run these tests in combination with sanitizers.
34#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
35#define SKIP_TEST_IF_NOT(requirements_satisfied) \
36 do { \
37 if (!requirements_satisfied) { \
38 return; \
39 } \
40 } while (false)
41#else
42// Or if other audio-related requirements are not met.
43#define SKIP_TEST_IF_NOT(requirements_satisfied) \
44 do { \
45 return; \
46 } while (false)
47#endif
48
49// Number of callbacks (input or output) the tests waits for before we set
50// an event indicating that the test was OK.
51static const size_t kNumCallbacks = 10;
52// Max amount of time we wait for an event to be set while counting callbacks.
53static const int kTestTimeOutInMilliseconds = 10 * 1000;
54
55enum class TransportType {
56 kInvalid,
57 kPlay,
58 kRecord,
59 kPlayAndRecord,
60};
61} // namespace
62
63// Mocks the AudioTransport object and proxies actions for the two callbacks
64// (RecordedDataIsAvailable and NeedMorePlayData) to different implementations
65// of AudioStreamInterface.
66class MockAudioTransport : public test::MockAudioTransport {
67 public:
68 explicit MockAudioTransport(TransportType type) : type_(type) {}
69 ~MockAudioTransport() {}
70
71 // Set default actions of the mock object. We are delegating to fake
72 // implementation where the number of callbacks is counted and an event
73 // is set after a certain number of callbacks. Audio parameters are also
74 // checked.
75 void HandleCallbacks(rtc::Event* event, int num_callbacks) {
76 event_ = event;
77 num_callbacks_ = num_callbacks;
78 if (play_mode()) {
79 ON_CALL(*this, NeedMorePlayData(_, _, _, _, _, _, _, _))
80 .WillByDefault(
81 Invoke(this, &MockAudioTransport::RealNeedMorePlayData));
82 }
83 if (rec_mode()) {
84 ON_CALL(*this, RecordedDataIsAvailable(_, _, _, _, _, _, _, _, _, _))
85 .WillByDefault(
86 Invoke(this, &MockAudioTransport::RealRecordedDataIsAvailable));
87 }
88 }
89
90 int32_t RealRecordedDataIsAvailable(const void* audio_buffer,
91 const size_t samples_per_channel,
92 const size_t bytes_per_frame,
93 const size_t channels,
94 const uint32_t sample_rate,
95 const uint32_t total_delay_ms,
96 const int32_t clock_drift,
97 const uint32_t current_mic_level,
98 const bool typing_status,
99 uint32_t& new_mic_level) {
100 EXPECT_TRUE(rec_mode()) << "No test is expecting these callbacks.";
101 LOG(INFO) << "+";
102 // Store audio parameters once in the first callback. For all other
103 // callbacks, verify that the provided audio parameters are maintained and
104 // that each callback corresponds to 10ms for any given sample rate.
105 if (!record_parameters_.is_complete()) {
106 record_parameters_.reset(sample_rate, channels, samples_per_channel);
107 } else {
108 EXPECT_EQ(samples_per_channel, record_parameters_.frames_per_buffer());
109 EXPECT_EQ(bytes_per_frame, record_parameters_.GetBytesPerFrame());
110 EXPECT_EQ(channels, record_parameters_.channels());
111 EXPECT_EQ(static_cast<int>(sample_rate),
112 record_parameters_.sample_rate());
113 EXPECT_EQ(samples_per_channel,
114 record_parameters_.frames_per_10ms_buffer());
115 }
116 rec_count_++;
117 // Signal the event after given amount of callbacks.
118 if (ReceivedEnoughCallbacks()) {
119 event_->Set();
120 }
121 return 0;
122 }
123
124 int32_t RealNeedMorePlayData(const size_t samples_per_channel,
125 const size_t bytes_per_frame,
126 const size_t channels,
127 const uint32_t sample_rate,
128 void* audio_buffer,
129 size_t& samples_per_channel_out,
130 int64_t* elapsed_time_ms,
131 int64_t* ntp_time_ms) {
132 EXPECT_TRUE(play_mode()) << "No test is expecting these callbacks.";
133 LOG(INFO) << "-";
134 // Store audio parameters once in the first callback. For all other
135 // callbacks, verify that the provided audio parameters are maintained and
136 // that each callback corresponds to 10ms for any given sample rate.
137 if (!playout_parameters_.is_complete()) {
138 playout_parameters_.reset(sample_rate, channels, samples_per_channel);
139 } else {
140 EXPECT_EQ(samples_per_channel, playout_parameters_.frames_per_buffer());
141 EXPECT_EQ(bytes_per_frame, playout_parameters_.GetBytesPerFrame());
142 EXPECT_EQ(channels, playout_parameters_.channels());
143 EXPECT_EQ(static_cast<int>(sample_rate),
144 playout_parameters_.sample_rate());
145 EXPECT_EQ(samples_per_channel,
146 playout_parameters_.frames_per_10ms_buffer());
147 }
148 play_count_++;
149 samples_per_channel_out = samples_per_channel;
150 // Fill the audio buffer with zeros to avoid disturbing audio.
151 const size_t num_bytes = samples_per_channel * bytes_per_frame;
152 std::memset(audio_buffer, 0, num_bytes);
153 // Signal the event after given amount of callbacks.
154 if (ReceivedEnoughCallbacks()) {
155 event_->Set();
156 }
157 return 0;
158 }
159
160 bool ReceivedEnoughCallbacks() {
161 bool recording_done = false;
162 if (rec_mode()) {
163 recording_done = rec_count_ >= num_callbacks_;
164 } else {
165 recording_done = true;
166 }
167 bool playout_done = false;
168 if (play_mode()) {
169 playout_done = play_count_ >= num_callbacks_;
170 } else {
171 playout_done = true;
172 }
173 return recording_done && playout_done;
174 }
175
176 bool play_mode() const {
177 return type_ == TransportType::kPlay ||
178 type_ == TransportType::kPlayAndRecord;
179 }
180
181 bool rec_mode() const {
182 return type_ == TransportType::kRecord ||
183 type_ == TransportType::kPlayAndRecord;
184 }
185
186 private:
187 TransportType type_ = TransportType::kInvalid;
188 rtc::Event* event_ = nullptr;
189 size_t num_callbacks_ = 0;
190 size_t play_count_ = 0;
191 size_t rec_count_ = 0;
192 AudioParameters playout_parameters_;
193 AudioParameters record_parameters_;
194};
195
196// AudioDeviceTest test fixture.
197class AudioDeviceTest : public ::testing::Test {
198 protected:
199 AudioDeviceTest() : event_(false, false) {
200#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
201 rtc::LogMessage::LogToDebug(rtc::LS_INFO);
202 // Add extra logging fields here if needed for debugging.
203 // rtc::LogMessage::LogTimestamps();
204 // rtc::LogMessage::LogThreads();
205 audio_device_ =
206 AudioDeviceModule::Create(0, AudioDeviceModule::kPlatformDefaultAudio);
207 EXPECT_NE(audio_device_.get(), nullptr);
208 AudioDeviceModule::AudioLayer audio_layer;
maxmorin33bf69a2017-03-23 04:06:53 -0700209 int got_platform_audio_layer =
210 audio_device_->ActiveAudioLayer(&audio_layer);
211 if (got_platform_audio_layer != 0 ||
212 audio_layer == AudioDeviceModule::kLinuxAlsaAudio) {
henrikaf2f91fa2017-03-17 04:26:22 -0700213 requirements_satisfied_ = false;
214 }
215 if (requirements_satisfied_) {
216 EXPECT_EQ(0, audio_device_->Init());
217 const int16_t num_playout_devices = audio_device_->PlayoutDevices();
218 const int16_t num_record_devices = audio_device_->RecordingDevices();
219 requirements_satisfied_ =
220 num_playout_devices > 0 && num_record_devices > 0;
221 }
222#else
223 requirements_satisfied_ = false;
224#endif
225 if (requirements_satisfied_) {
226 EXPECT_EQ(0, audio_device_->SetPlayoutDevice(0));
227 EXPECT_EQ(0, audio_device_->InitSpeaker());
228 EXPECT_EQ(0, audio_device_->SetRecordingDevice(0));
229 EXPECT_EQ(0, audio_device_->InitMicrophone());
230 EXPECT_EQ(0, audio_device_->StereoPlayoutIsAvailable(&stereo_playout_));
231 EXPECT_EQ(0, audio_device_->SetStereoPlayout(stereo_playout_));
henrika0238ba82017-03-28 04:38:29 -0700232 // Avoid asking for input stereo support and always record in mono
233 // since asking can cause issues in combination with remote desktop.
234 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7397 for
235 // details.
236 EXPECT_EQ(0, audio_device_->SetStereoRecording(false));
henrikaf2f91fa2017-03-17 04:26:22 -0700237 EXPECT_EQ(0, audio_device_->SetAGC(false));
238 EXPECT_FALSE(audio_device_->AGC());
239 }
240 }
241
242 virtual ~AudioDeviceTest() {
243 if (audio_device_) {
244 EXPECT_EQ(0, audio_device_->Terminate());
245 }
246 }
247
248 bool requirements_satisfied() const { return requirements_satisfied_; }
249 rtc::Event* event() { return &event_; }
250
251 const rtc::scoped_refptr<AudioDeviceModule>& audio_device() const {
252 return audio_device_;
253 }
254
255 void StartPlayout() {
256 EXPECT_FALSE(audio_device()->Playing());
257 EXPECT_EQ(0, audio_device()->InitPlayout());
258 EXPECT_TRUE(audio_device()->PlayoutIsInitialized());
259 EXPECT_EQ(0, audio_device()->StartPlayout());
260 EXPECT_TRUE(audio_device()->Playing());
261 }
262
263 void StopPlayout() {
264 EXPECT_EQ(0, audio_device()->StopPlayout());
265 EXPECT_FALSE(audio_device()->Playing());
266 EXPECT_FALSE(audio_device()->PlayoutIsInitialized());
267 }
268
269 void StartRecording() {
270 EXPECT_FALSE(audio_device()->Recording());
271 EXPECT_EQ(0, audio_device()->InitRecording());
272 EXPECT_TRUE(audio_device()->RecordingIsInitialized());
273 EXPECT_EQ(0, audio_device()->StartRecording());
274 EXPECT_TRUE(audio_device()->Recording());
275 }
276
277 void StopRecording() {
278 EXPECT_EQ(0, audio_device()->StopRecording());
279 EXPECT_FALSE(audio_device()->Recording());
280 EXPECT_FALSE(audio_device()->RecordingIsInitialized());
281 }
282
283 private:
284 bool requirements_satisfied_ = true;
285 rtc::Event event_;
286 rtc::scoped_refptr<AudioDeviceModule> audio_device_;
287 bool stereo_playout_ = false;
henrikaf2f91fa2017-03-17 04:26:22 -0700288};
289
290// Uses the test fixture to create, initialize and destruct the ADM.
291TEST_F(AudioDeviceTest, ConstructDestruct) {}
292
293TEST_F(AudioDeviceTest, InitTerminate) {
294 SKIP_TEST_IF_NOT(requirements_satisfied());
295 // Initialization is part of the test fixture.
296 EXPECT_TRUE(audio_device()->Initialized());
297 EXPECT_EQ(0, audio_device()->Terminate());
298 EXPECT_FALSE(audio_device()->Initialized());
299}
300
301// Tests Start/Stop playout without any registered audio callback.
302TEST_F(AudioDeviceTest, StartStopPlayout) {
303 SKIP_TEST_IF_NOT(requirements_satisfied());
304 StartPlayout();
305 StopPlayout();
306 StartPlayout();
307 StopPlayout();
308}
309
310// Tests Start/Stop recording without any registered audio callback.
311TEST_F(AudioDeviceTest, StartStopRecording) {
312 SKIP_TEST_IF_NOT(requirements_satisfied());
313 StartRecording();
314 StopRecording();
315 StartRecording();
316 StopRecording();
317}
318
319// Start playout and verify that the native audio layer starts asking for real
320// audio samples to play out using the NeedMorePlayData() callback.
321// Note that we can't add expectations on audio parameters in EXPECT_CALL
322// since parameter are not provided in the each callback. We therefore test and
323// verify the parameters in the fake audio transport implementation instead.
324TEST_F(AudioDeviceTest, StartPlayoutVerifyCallbacks) {
325 SKIP_TEST_IF_NOT(requirements_satisfied());
326 MockAudioTransport mock(TransportType::kPlay);
327 mock.HandleCallbacks(event(), kNumCallbacks);
328 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
329 .Times(AtLeast(kNumCallbacks));
330 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
331 StartPlayout();
332 event()->Wait(kTestTimeOutInMilliseconds);
333 StopPlayout();
334}
335
336// Start recording and verify that the native audio layer starts providing real
337// audio samples using the RecordedDataIsAvailable() callback.
338TEST_F(AudioDeviceTest, StartRecordingVerifyCallbacks) {
339 SKIP_TEST_IF_NOT(requirements_satisfied());
340 MockAudioTransport mock(TransportType::kRecord);
341 mock.HandleCallbacks(event(), kNumCallbacks);
342 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
343 false, _))
344 .Times(AtLeast(kNumCallbacks));
345 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
346 StartRecording();
347 event()->Wait(kTestTimeOutInMilliseconds);
348 StopRecording();
349}
350
351// Start playout and recording (full-duplex audio) and verify that audio is
352// active in both directions.
353TEST_F(AudioDeviceTest, StartPlayoutAndRecordingVerifyCallbacks) {
354 SKIP_TEST_IF_NOT(requirements_satisfied());
355 MockAudioTransport mock(TransportType::kPlayAndRecord);
356 mock.HandleCallbacks(event(), kNumCallbacks);
357 EXPECT_CALL(mock, NeedMorePlayData(_, _, _, _, NotNull(), _, _, _))
358 .Times(AtLeast(kNumCallbacks));
359 EXPECT_CALL(mock, RecordedDataIsAvailable(NotNull(), _, _, _, _, Ge(0u), 0, _,
360 false, _))
361 .Times(AtLeast(kNumCallbacks));
362 EXPECT_EQ(0, audio_device()->RegisterAudioCallback(&mock));
363 StartPlayout();
364 StartRecording();
365 event()->Wait(kTestTimeOutInMilliseconds);
366 StopRecording();
367 StopPlayout();
368}
369
370} // namespace webrtc