blob: 711a8d927a7fb9485599382f8a81b58803947f5a [file] [log] [blame]
Kevin Rocardf0357882017-02-10 16:19:28 -08001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "VtsHalAudioV2_0TargetTest"
18
19#include <algorithm>
20#include <cmath>
21#include <cstddef>
22#include <cstdio>
23#include <limits>
24#include <list>
25#include <string>
26#include <type_traits>
27#include <vector>
28
Yuexi Ma161b5642017-03-10 13:44:22 -080029#include <VtsHalHidlTargetTestBase.h>
Kevin Rocardf0357882017-02-10 16:19:28 -080030
31#include <android-base/logging.h>
32
33#include <android/hardware/audio/2.0/IDevice.h>
34#include <android/hardware/audio/2.0/IDevicesFactory.h>
Kevin Rocard3c405a72017-03-08 16:46:51 -080035#include <android/hardware/audio/2.0/IPrimaryDevice.h>
Kevin Rocardf0357882017-02-10 16:19:28 -080036#include <android/hardware/audio/2.0/types.h>
37#include <android/hardware/audio/common/2.0/types.h>
38
39#include "utility/ReturnIn.h"
40#include "utility/AssertOk.h"
41#include "utility/PrettyPrintAudioTypes.h"
42
43using std::string;
44using std::to_string;
45using std::vector;
46
47using ::android::sp;
48using ::android::hardware::Return;
49using ::android::hardware::hidl_handle;
50using ::android::hardware::hidl_string;
51using ::android::hardware::hidl_vec;
Kevin Rocardc9963522017-03-10 18:47:37 -080052using ::android::hardware::MQDescriptorSync;
Kevin Rocard624800c2017-03-10 18:47:37 -080053using ::android::hardware::audio::V2_0::AudioDrain;
Kevin Rocardf0357882017-02-10 16:19:28 -080054using ::android::hardware::audio::V2_0::DeviceAddress;
55using ::android::hardware::audio::V2_0::IDevice;
Kevin Rocard3c405a72017-03-08 16:46:51 -080056using ::android::hardware::audio::V2_0::IPrimaryDevice;
57using TtyMode = ::android::hardware::audio::V2_0::IPrimaryDevice::TtyMode;
Kevin Rocardf0357882017-02-10 16:19:28 -080058using ::android::hardware::audio::V2_0::IDevicesFactory;
59using ::android::hardware::audio::V2_0::IStream;
60using ::android::hardware::audio::V2_0::IStreamIn;
Kevin Rocard624800c2017-03-10 18:47:37 -080061using ::android::hardware::audio::V2_0::TimeSpec;
Kevin Rocardc9963522017-03-10 18:47:37 -080062using ReadParameters = ::android::hardware::audio::V2_0::IStreamIn::ReadParameters;
63using ReadStatus = ::android::hardware::audio::V2_0::IStreamIn::ReadStatus;
Kevin Rocardf0357882017-02-10 16:19:28 -080064using ::android::hardware::audio::V2_0::IStreamOut;
Kevin Rocard624800c2017-03-10 18:47:37 -080065using ::android::hardware::audio::V2_0::IStreamOutCallback;
Kevin Rocard8878b4b2017-03-10 18:47:37 -080066using ::android::hardware::audio::V2_0::MmapBufferInfo;
67using ::android::hardware::audio::V2_0::MmapPosition;
Kevin Rocardf0357882017-02-10 16:19:28 -080068using ::android::hardware::audio::V2_0::ParameterValue;
69using ::android::hardware::audio::V2_0::Result;
70using ::android::hardware::audio::common::V2_0::AudioChannelMask;
71using ::android::hardware::audio::common::V2_0::AudioConfig;
72using ::android::hardware::audio::common::V2_0::AudioDevice;
73using ::android::hardware::audio::common::V2_0::AudioFormat;
74using ::android::hardware::audio::common::V2_0::AudioHandleConsts;
75using ::android::hardware::audio::common::V2_0::AudioInputFlag;
76using ::android::hardware::audio::common::V2_0::AudioIoHandle;
Kevin Rocard3c405a72017-03-08 16:46:51 -080077using ::android::hardware::audio::common::V2_0::AudioMode;
Kevin Rocardf0357882017-02-10 16:19:28 -080078using ::android::hardware::audio::common::V2_0::AudioOffloadInfo;
79using ::android::hardware::audio::common::V2_0::AudioOutputFlag;
80using ::android::hardware::audio::common::V2_0::AudioSource;
Kevin Rocardc9963522017-03-10 18:47:37 -080081using ::android::hardware::audio::common::V2_0::ThreadInfo;
Kevin Rocardf0357882017-02-10 16:19:28 -080082
83using utility::returnIn;
84
85namespace doc {
86/** Document the current test case.
87 * Eg: calling `doc::test("Dump the state of the hal")` in the "debugDump" test will output:
88 * <testcase name="debugDump" status="run" time="6" classname="AudioPrimaryHidlTest"
89 description="Dump the state of the hal." />
90 * see https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#logging-additional-information
91 */
92void test(const std::string& testCaseDocumentation) {
93 ::testing::Test::RecordProperty("description", testCaseDocumentation);
94}
95
96/** Document why a test was not fully run. Usually due to an optional feature not implemented. */
97void partialTest(const std::string& reason) {
98 ::testing::Test::RecordProperty("partialyRunTest", reason);
99}
100}
101
102// Register callback for static object destruction
103// Avoid destroying static objects after main return.
104// Post main return destruction leads to incorrect gtest timing measurements as well as harder
105// debuging if anything goes wrong during destruction.
106class Environment : public ::testing::Environment {
107public:
108 using TearDownFunc = std::function<void ()>;
109 void registerTearDown(TearDownFunc&& tearDown) {
110 tearDowns.push_back(std::move(tearDown));
111 }
112
113private:
114 void TearDown() override {
115 // Call the tear downs in reverse order of insertion
116 for (auto& tearDown : tearDowns) {
117 tearDown();
118 }
119 }
120 std::list<TearDownFunc> tearDowns;
121};
122// Instance to register global tearDown
123static Environment* environment;
124
Yuexi Ma161b5642017-03-10 13:44:22 -0800125class HidlTest : public ::testing::VtsHalHidlTargetTestBase {
Kevin Rocardf0357882017-02-10 16:19:28 -0800126protected:
127 // Convenient member to store results
128 Result res;
129};
130
131//////////////////////////////////////////////////////////////////////////////
132////////////////////// getService audio_devices_factory //////////////////////
133//////////////////////////////////////////////////////////////////////////////
134
135// Test all audio devices
136class AudioHidlTest : public HidlTest {
137public:
138 void SetUp() override {
139 ASSERT_NO_FATAL_FAILURE(HidlTest::SetUp()); // setup base
140
141 if (devicesFactory == nullptr) {
142 environment->registerTearDown([]{ devicesFactory.clear(); });
Yuexi Ma161b5642017-03-10 13:44:22 -0800143 devicesFactory = ::testing::VtsHalHidlTargetTestBase::getService<IDevicesFactory>();
Kevin Rocardf0357882017-02-10 16:19:28 -0800144 }
145 ASSERT_TRUE(devicesFactory != nullptr);
146 }
147
148protected:
149 // Cache the devicesFactory retrieval to speed up each test by ~0.5s
150 static sp<IDevicesFactory> devicesFactory;
151};
152sp<IDevicesFactory> AudioHidlTest::devicesFactory;
153
154TEST_F(AudioHidlTest, GetAudioDevicesFactoryService) {
155 doc::test("test the getService (called in SetUp)");
156}
157
158//////////////////////////////////////////////////////////////////////////////
159/////////////////////////////// openDevice primary ///////////////////////////
160//////////////////////////////////////////////////////////////////////////////
161
162// Test the primary device
163class AudioPrimaryHidlTest : public AudioHidlTest {
164public:
165 /** Primary HAL test are NOT thread safe. */
166 void SetUp() override {
167 ASSERT_NO_FATAL_FAILURE(AudioHidlTest::SetUp()); // setup base
168
169 if (device == nullptr) {
Kevin Rocardf0357882017-02-10 16:19:28 -0800170 IDevicesFactory::Result result;
Kevin Rocard3c405a72017-03-08 16:46:51 -0800171 sp<IDevice> baseDevice;
Kevin Rocardf0357882017-02-10 16:19:28 -0800172 ASSERT_OK(devicesFactory->openDevice(IDevicesFactory::Device::PRIMARY,
Kevin Rocard3c405a72017-03-08 16:46:51 -0800173 returnIn(result, baseDevice)));
Kevin Rocardfba442a2017-03-31 19:34:41 -0700174 ASSERT_OK(result);
Kevin Rocard3c405a72017-03-08 16:46:51 -0800175 ASSERT_TRUE(baseDevice != nullptr);
176
177 environment->registerTearDown([]{ device.clear(); });
178 device = IPrimaryDevice::castFrom(baseDevice);
179 ASSERT_TRUE(device != nullptr);
Kevin Rocardf0357882017-02-10 16:19:28 -0800180 }
Kevin Rocardf0357882017-02-10 16:19:28 -0800181 }
182
183protected:
184 // Cache the device opening to speed up each test by ~0.5s
Kevin Rocard3c405a72017-03-08 16:46:51 -0800185 static sp<IPrimaryDevice> device;
Kevin Rocardf0357882017-02-10 16:19:28 -0800186};
Kevin Rocard3c405a72017-03-08 16:46:51 -0800187sp<IPrimaryDevice> AudioPrimaryHidlTest::device;
Kevin Rocardf0357882017-02-10 16:19:28 -0800188
189TEST_F(AudioPrimaryHidlTest, OpenPrimaryDevice) {
190 doc::test("Test the openDevice (called in SetUp)");
191}
192
193TEST_F(AudioPrimaryHidlTest, Init) {
194 doc::test("Test that the audio primary hal initialized correctly");
195 ASSERT_OK(device->initCheck());
196}
197
198//////////////////////////////////////////////////////////////////////////////
Kevin Rocard92ce35d2017-03-08 17:17:25 -0800199///////////////////// {set,get}{Master,Mic}{Mute,Volume} /////////////////////
Kevin Rocardf0357882017-02-10 16:19:28 -0800200//////////////////////////////////////////////////////////////////////////////
201
Kevin Rocard3c405a72017-03-08 16:46:51 -0800202template <class Property>
203class AccessorPrimaryHidlTest : public AudioPrimaryHidlTest {
Kevin Rocardf0357882017-02-10 16:19:28 -0800204protected:
Kevin Rocard3c405a72017-03-08 16:46:51 -0800205
206 /** Test a property getter and setter. */
Kevin Rocardf0357882017-02-10 16:19:28 -0800207 template <class Getter, class Setter>
Kevin Rocard3c405a72017-03-08 16:46:51 -0800208 void testAccessors(const string& propertyName, const vector<Property>& valuesToTest,
Kevin Rocard92ce35d2017-03-08 17:17:25 -0800209 Setter setter, Getter getter,
210 const vector<Property>& invalidValues = {}) {
Kevin Rocard3c405a72017-03-08 16:46:51 -0800211
212 Property initialValue; // Save initial value to restore it at the end of the test
213 ASSERT_OK((device.get()->*getter)(returnIn(res, initialValue)));
214 ASSERT_OK(res);
215
216 for (Property setValue : valuesToTest) {
Kevin Rocard92ce35d2017-03-08 17:17:25 -0800217 SCOPED_TRACE("Test " + propertyName + " getter and setter for " +
218 testing::PrintToString(setValue));
Kevin Rocard3c405a72017-03-08 16:46:51 -0800219 ASSERT_OK((device.get()->*setter)(setValue));
220 Property getValue;
221 // Make sure the getter returns the same value just set
222 ASSERT_OK((device.get()->*getter)(returnIn(res, getValue)));
Kevin Rocardf0357882017-02-10 16:19:28 -0800223 ASSERT_OK(res);
Kevin Rocard3c405a72017-03-08 16:46:51 -0800224 EXPECT_EQ(setValue, getValue);
Kevin Rocardf0357882017-02-10 16:19:28 -0800225 }
Kevin Rocard3c405a72017-03-08 16:46:51 -0800226
Kevin Rocard92ce35d2017-03-08 17:17:25 -0800227 for (Property invalidValue : invalidValues) {
228 SCOPED_TRACE("Try to set " + propertyName + " with the invalid value " +
229 testing::PrintToString(invalidValue));
Kevin Rocard20e7af62017-03-10 17:10:43 -0800230 EXPECT_RESULT(Result::INVALID_ARGUMENTS, (device.get()->*setter)(invalidValue));
Kevin Rocard92ce35d2017-03-08 17:17:25 -0800231 }
232
Kevin Rocard3c405a72017-03-08 16:46:51 -0800233 ASSERT_OK((device.get()->*setter)(initialValue)); // restore initial value
234 }
235
236 /** Test the getter and setter of an optional feature. */
237 template <class Getter, class Setter>
238 void testOptionalAccessors(const string& propertyName, const vector<Property>& valuesToTest,
Kevin Rocard92ce35d2017-03-08 17:17:25 -0800239 Setter setter, Getter getter,
240 const vector<Property>& invalidValues = {}) {
Kevin Rocard3c405a72017-03-08 16:46:51 -0800241 doc::test("Test the optional " + propertyName + " getters and setter");
242 {
243 SCOPED_TRACE("Test feature support by calling the getter");
244 Property initialValue;
245 ASSERT_OK((device.get()->*getter)(returnIn(res, initialValue)));
246 if (res == Result::NOT_SUPPORTED) {
247 doc::partialTest(propertyName + " getter is not supported");
248 return;
249 }
250 ASSERT_OK(res); // If it is supported it must succeed
251 }
252 // The feature is supported, test it
Kevin Rocard92ce35d2017-03-08 17:17:25 -0800253 testAccessors(propertyName, valuesToTest, setter, getter, invalidValues);
Kevin Rocardf0357882017-02-10 16:19:28 -0800254 }
255};
256
Kevin Rocard3c405a72017-03-08 16:46:51 -0800257using BoolAccessorPrimaryHidlTest = AccessorPrimaryHidlTest<bool>;
258
Kevin Rocardf0357882017-02-10 16:19:28 -0800259TEST_F(BoolAccessorPrimaryHidlTest, MicMuteTest) {
260 doc::test("Check that the mic can be muted and unmuted");
Kevin Rocard3c405a72017-03-08 16:46:51 -0800261 testAccessors("mic mute", {true, false, true}, &IDevice::setMicMute, &IDevice::getMicMute);
Kevin Rocardf0357882017-02-10 16:19:28 -0800262 // TODO: check that the mic is really muted (all sample are 0)
263}
264
265TEST_F(BoolAccessorPrimaryHidlTest, MasterMuteTest) {
266 doc::test("If master mute is supported, try to mute and unmute the master output");
Kevin Rocard3c405a72017-03-08 16:46:51 -0800267 testOptionalAccessors("master mute", {true, false, true},
268 &IDevice::setMasterMute, &IDevice::getMasterMute);
Kevin Rocardf0357882017-02-10 16:19:28 -0800269 // TODO: check that the master volume is really muted
270}
271
Kevin Rocard92ce35d2017-03-08 17:17:25 -0800272using FloatAccessorPrimaryHidlTest = AccessorPrimaryHidlTest<float>;
273TEST_F(FloatAccessorPrimaryHidlTest, MasterVolumeTest) {
274 doc::test("Test the master volume if supported");
275 testOptionalAccessors("master volume", {0, 0.5, 1},
276 &IDevice::setMasterVolume, &IDevice::getMasterVolume,
277 {-0.1, 1.1, NAN, INFINITY, -INFINITY,
278 1 + std::numeric_limits<float>::epsilon()});
279 // TODO: check that the master volume is really changed
280}
281
Kevin Rocardf0357882017-02-10 16:19:28 -0800282//////////////////////////////////////////////////////////////////////////////
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800283//////////////////////////////// AudioPatches ////////////////////////////////
284//////////////////////////////////////////////////////////////////////////////
285
286class AudioPatchPrimaryHidlTest : public AudioPrimaryHidlTest {
287protected:
288 bool areAudioPatchesSupported() {
289 auto result = device->supportsAudioPatches();
290 EXPECT_TRUE(result.isOk());
291 return result;
292 }
293};
294
295TEST_F(AudioPatchPrimaryHidlTest, AudioPatches) {
296 doc::test("Test if audio patches are supported");
297 if (!areAudioPatchesSupported()) {
298 doc::partialTest("Audio patches are not supported");
299 return;
300 }
301 // TODO: test audio patches
302}
303
304
305//////////////////////////////////////////////////////////////////////////////
Kevin Rocardf0357882017-02-10 16:19:28 -0800306//////////////// Required and recommended audio format support ///////////////
307// From: https://source.android.com/compatibility/android-cdd.html#5_4_audio_recording
308// From: https://source.android.com/compatibility/android-cdd.html#5_5_audio_playback
309/////////// TODO: move to the beginning of the file for easier update ////////
310//////////////////////////////////////////////////////////////////////////////
311
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800312class AudioConfigPrimaryTest : public AudioPatchPrimaryHidlTest {
Kevin Rocardf0357882017-02-10 16:19:28 -0800313public:
314 // Cache result ?
315 static const vector<AudioConfig> getRequiredSupportPlaybackAudioConfig() {
316 return combineAudioConfig({AudioChannelMask::OUT_STEREO, AudioChannelMask::OUT_MONO},
317 {8000, 11025, 16000, 22050, 32000, 44100},
318 {AudioFormat::PCM_16_BIT});
319 }
320
321 static const vector<AudioConfig> getRecommendedSupportPlaybackAudioConfig() {
322 return combineAudioConfig({AudioChannelMask::OUT_STEREO, AudioChannelMask::OUT_MONO},
323 {24000, 48000},
324 {AudioFormat::PCM_16_BIT});
325 }
326
327 static const vector<AudioConfig> getSupportedPlaybackAudioConfig() {
328 // TODO: retrieve audio config supported by the platform
329 // as declared in the policy configuration
330 return {};
331 }
332
333 static const vector<AudioConfig> getRequiredSupportCaptureAudioConfig() {
334 return combineAudioConfig({AudioChannelMask::IN_MONO},
335 {8000, 11025, 16000, 44100},
336 {AudioFormat::PCM_16_BIT});
337 }
338 static const vector<AudioConfig> getRecommendedSupportCaptureAudioConfig() {
339 return combineAudioConfig({AudioChannelMask::IN_STEREO},
340 {22050, 48000},
341 {AudioFormat::PCM_16_BIT});
342 }
343 static const vector<AudioConfig> getSupportedCaptureAudioConfig() {
344 // TODO: retrieve audio config supported by the platform
345 // as declared in the policy configuration
346 return {};
347 }
348private:
349 static const vector<AudioConfig> combineAudioConfig(
350 vector<AudioChannelMask> channelMasks,
351 vector<uint32_t> sampleRates,
352 vector<AudioFormat> formats) {
353 vector<AudioConfig> configs;
354 for (auto channelMask: channelMasks) {
355 for (auto sampleRate : sampleRates) {
356 for (auto format : formats) {
357 AudioConfig config{};
358 // leave offloadInfo to 0
359 config.channelMask = channelMask;
360 config.sampleRateHz = sampleRate;
361 config.format = format;
362 // FIXME: leave frameCount to 0 ?
363 configs.push_back(config);
364 }
365 }
366 }
367 return configs;
368 }
369};
370
Kevin Rocard9c369142017-03-08 17:17:25 -0800371/** Generate a test name based on an audio config.
372 *
373 * As the only parameter changing are channel mask and sample rate,
374 * only print those ones in the test name.
375 */
376static string generateTestName(const testing::TestParamInfo<AudioConfig>& info) {
377 const AudioConfig& config = info.param;
378 return to_string(info.index) + "__" + to_string(config.sampleRateHz)+ "_" +
379 // "MONO" is more clear than "FRONT_LEFT"
380 ((config.channelMask == AudioChannelMask::OUT_MONO ||
381 config.channelMask == AudioChannelMask::IN_MONO) ?
382 "MONO" : toString(config.channelMask));
383}
384
Kevin Rocardf0357882017-02-10 16:19:28 -0800385//////////////////////////////////////////////////////////////////////////////
386///////////////////////////// getInputBufferSize /////////////////////////////
387//////////////////////////////////////////////////////////////////////////////
388
389// FIXME: execute input test only if platform declares android.hardware.microphone
390// how to get this value ? is it a property ???
391
392class AudioCaptureConfigPrimaryTest : public AudioConfigPrimaryTest,
393 public ::testing::WithParamInterface<AudioConfig> {
394protected:
395 void inputBufferSizeTest(const AudioConfig& audioConfig, bool supportRequired) {
396 uint64_t bufferSize;
397 ASSERT_OK(device->getInputBufferSize(audioConfig, returnIn(res, bufferSize)));
398
399 switch (res) {
400 case Result::INVALID_ARGUMENTS:
401 EXPECT_FALSE(supportRequired);
402 break;
403 case Result::OK:
404 // Check that the buffer is of a sane size
405 // For now only that it is > 0
406 EXPECT_GT(bufferSize, uint64_t(0));
407 break;
408 default:
409 FAIL() << "Invalid return status: " << ::testing::PrintToString(res);
410 }
411 }
412};
413
414// Test that the required capture config and those declared in the policy are indeed supported
415class RequiredInputBufferSizeTest : public AudioCaptureConfigPrimaryTest {};
416TEST_P(RequiredInputBufferSizeTest, RequiredInputBufferSizeTest) {
417 doc::test("Input buffer size must be retrievable for a format with required support.");
418 inputBufferSizeTest(GetParam(), true);
419}
420INSTANTIATE_TEST_CASE_P(
421 RequiredInputBufferSize, RequiredInputBufferSizeTest,
Kevin Rocard9c369142017-03-08 17:17:25 -0800422 ::testing::ValuesIn(AudioConfigPrimaryTest::getRequiredSupportCaptureAudioConfig()),
423 &generateTestName);
Kevin Rocardf0357882017-02-10 16:19:28 -0800424INSTANTIATE_TEST_CASE_P(
425 SupportedInputBufferSize, RequiredInputBufferSizeTest,
Kevin Rocard9c369142017-03-08 17:17:25 -0800426 ::testing::ValuesIn(AudioConfigPrimaryTest::getSupportedCaptureAudioConfig()),
427 &generateTestName);
Kevin Rocardf0357882017-02-10 16:19:28 -0800428
429// Test that the recommended capture config are supported or lead to a INVALID_ARGUMENTS return
430class OptionalInputBufferSizeTest : public AudioCaptureConfigPrimaryTest {};
431TEST_P(OptionalInputBufferSizeTest, OptionalInputBufferSizeTest) {
432 doc::test("Input buffer size should be retrievable for a format with recommended support.");
433 inputBufferSizeTest(GetParam(), false);
434}
435INSTANTIATE_TEST_CASE_P(
436 RecommendedCaptureAudioConfigSupport, OptionalInputBufferSizeTest,
Kevin Rocard9c369142017-03-08 17:17:25 -0800437 ::testing::ValuesIn(AudioConfigPrimaryTest::getRecommendedSupportCaptureAudioConfig()),
438 &generateTestName);
Kevin Rocardf0357882017-02-10 16:19:28 -0800439
440//////////////////////////////////////////////////////////////////////////////
441/////////////////////////////// setScreenState ///////////////////////////////
442//////////////////////////////////////////////////////////////////////////////
443
444TEST_F(AudioPrimaryHidlTest, setScreenState) {
445 doc::test("Check that the hal can receive the screen state");
446 for (bool turnedOn : {false, true, true, false, false}) {
447 auto ret = device->setScreenState(turnedOn);
448 ASSERT_TRUE(ret.isOk());
449 Result result = ret;
450 ASSERT_TRUE(result == Result::OK || result == Result::NOT_SUPPORTED) << toString(result);
451 }
452}
453
454//////////////////////////////////////////////////////////////////////////////
455//////////////////////////// {get,set}Parameters /////////////////////////////
456//////////////////////////////////////////////////////////////////////////////
457
458TEST_F(AudioPrimaryHidlTest, getParameters) {
459 doc::test("Check that the hal can set and get parameters");
460 hidl_vec<hidl_string> keys;
461 hidl_vec<ParameterValue> values;
462 ASSERT_OK(device->getParameters(keys, returnIn(res, values)));
463 ASSERT_OK(device->setParameters(values));
464 values.resize(0);
465 ASSERT_OK(device->setParameters(values));
466}
467
468//////////////////////////////////////////////////////////////////////////////
469//////////////////////////////// debugDebug //////////////////////////////////
470//////////////////////////////////////////////////////////////////////////////
471
Kevin Rocardb9031242017-03-13 12:20:54 -0700472template <class DebugDump>
473static void testDebugDump(DebugDump debugDump) {
Kevin Rocardf0357882017-02-10 16:19:28 -0800474 FILE* file = tmpfile();
475 ASSERT_NE(nullptr, file) << errno;
476
477 auto* nativeHandle = native_handle_create(1, 0);
478 ASSERT_NE(nullptr, nativeHandle);
479 nativeHandle->data[0] = fileno(file);
480
481 hidl_handle handle;
482 handle.setTo(nativeHandle, true /*take ownership*/);
483
Kevin Rocardee771e92017-03-08 17:17:25 -0800484 // TODO: debugDump does not return a Result.
Kevin Rocardf0357882017-02-10 16:19:28 -0800485 // This mean that the hal can not report that it not implementing the function.
Kevin Rocardb9031242017-03-13 12:20:54 -0700486 ASSERT_OK(debugDump(handle));
Kevin Rocardee771e92017-03-08 17:17:25 -0800487
488 rewind(file); // can not fail
Kevin Rocardf0357882017-02-10 16:19:28 -0800489
490 // Check that at least one bit was written by the hal
491 char buff;
Kevin Rocardee771e92017-03-08 17:17:25 -0800492 ASSERT_EQ(size_t{1}, fread(&buff, sizeof(buff), 1, file));
Kevin Rocardf0357882017-02-10 16:19:28 -0800493 EXPECT_EQ(0, fclose(file)) << errno;
494}
495
Kevin Rocardb9031242017-03-13 12:20:54 -0700496TEST_F(AudioPrimaryHidlTest, debugDump) {
497 doc::test("Check that the hal can dump its state without error");
498 testDebugDump([this](const auto& handle){ return device->debugDump(handle); });
499}
500
Mikhail Naganov3e6fe752017-04-24 10:44:08 -0700501TEST_F(AudioPrimaryHidlTest, debugDumpInvalidArguments) {
502 doc::test("Check that the hal dump doesn't crash on invalid arguments");
503 ASSERT_OK(device->debugDump(hidl_handle()));
504}
505
Kevin Rocardf0357882017-02-10 16:19:28 -0800506//////////////////////////////////////////////////////////////////////////////
507////////////////////////// open{Output,Input}Stream //////////////////////////
508//////////////////////////////////////////////////////////////////////////////
509
510template <class Stream>
511class OpenStreamTest : public AudioConfigPrimaryTest,
512 public ::testing::WithParamInterface<AudioConfig> {
513protected:
514 template <class Open>
515 void testOpen(Open openStream, const AudioConfig& config) {
516 // FIXME: Open a stream without an IOHandle
517 // This is not required to be accepted by hal implementations
518 AudioIoHandle ioHandle = (AudioIoHandle)AudioHandleConsts::AUDIO_IO_HANDLE_NONE;
519 AudioConfig suggestedConfig{};
520 ASSERT_OK(openStream(ioHandle, config, returnIn(res, stream, suggestedConfig)));
521
522 // TODO: only allow failure for RecommendedPlaybackAudioConfig
523 switch (res) {
524 case Result::OK:
525 ASSERT_TRUE(stream != nullptr);
526 audioConfig = config;
527 break;
528 case Result::INVALID_ARGUMENTS:
529 ASSERT_TRUE(stream == nullptr);
530 AudioConfig suggestedConfigRetry;
531 // Could not open stream with config, try again with the suggested one
532 ASSERT_OK(openStream(ioHandle, suggestedConfig,
533 returnIn(res, stream, suggestedConfigRetry)));
534 // This time it must succeed
535 ASSERT_OK(res);
536 ASSERT_TRUE(stream == nullptr);
537 audioConfig = suggestedConfig;
538 break;
539 default:
540 FAIL() << "Invalid return status: " << ::testing::PrintToString(res);
541 }
542 open = true;
543 }
544
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800545 Return<Result> closeStream() {
546 open = false;
547 return stream->close();
548 }
Kevin Rocardf0357882017-02-10 16:19:28 -0800549private:
550 void TearDown() override {
551 if (open) {
552 ASSERT_OK(stream->close());
553 }
554 }
555
556protected:
557
558 AudioConfig audioConfig;
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800559 DeviceAddress address = {};
Kevin Rocardf0357882017-02-10 16:19:28 -0800560 sp<Stream> stream;
561 bool open = false;
562};
563
564////////////////////////////// openOutputStream //////////////////////////////
565
566class OutputStreamTest : public OpenStreamTest<IStreamOut> {
567 virtual void SetUp() override {
568 ASSERT_NO_FATAL_FAILURE(OpenStreamTest::SetUp()); // setup base
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800569 address.device = AudioDevice::OUT_DEFAULT;
Kevin Rocardf0357882017-02-10 16:19:28 -0800570 const AudioConfig& config = GetParam();
Kevin Rocardf0357882017-02-10 16:19:28 -0800571 AudioOutputFlag flags = AudioOutputFlag::NONE; // TODO: test all flag combination
572 testOpen([&](AudioIoHandle handle, AudioConfig config, auto cb)
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800573 { return device->openOutputStream(handle, address, config, flags, cb); },
Kevin Rocardf0357882017-02-10 16:19:28 -0800574 config);
575 }
576};
577TEST_P(OutputStreamTest, OpenOutputStreamTest) {
578 doc::test("Check that output streams can be open with the required and recommended config");
579 // Open done in SetUp
580}
581INSTANTIATE_TEST_CASE_P(
582 RequiredOutputStreamConfigSupport, OutputStreamTest,
Kevin Rocard9c369142017-03-08 17:17:25 -0800583 ::testing::ValuesIn(AudioConfigPrimaryTest::getRequiredSupportPlaybackAudioConfig()),
584 &generateTestName);
Kevin Rocardf0357882017-02-10 16:19:28 -0800585INSTANTIATE_TEST_CASE_P(
586 SupportedOutputStreamConfig, OutputStreamTest,
Kevin Rocard9c369142017-03-08 17:17:25 -0800587 ::testing::ValuesIn(AudioConfigPrimaryTest::getSupportedPlaybackAudioConfig()),
588 &generateTestName);
Kevin Rocardf0357882017-02-10 16:19:28 -0800589
590INSTANTIATE_TEST_CASE_P(
591 RecommendedOutputStreamConfigSupport, OutputStreamTest,
Kevin Rocard9c369142017-03-08 17:17:25 -0800592 ::testing::ValuesIn(AudioConfigPrimaryTest::getRecommendedSupportPlaybackAudioConfig()),
593 &generateTestName);
Kevin Rocardf0357882017-02-10 16:19:28 -0800594
595////////////////////////////// openInputStream //////////////////////////////
596
597class InputStreamTest : public OpenStreamTest<IStreamIn> {
598
599 virtual void SetUp() override {
600 ASSERT_NO_FATAL_FAILURE(OpenStreamTest::SetUp()); // setup base
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800601 address.device = AudioDevice::IN_DEFAULT;
Kevin Rocardf0357882017-02-10 16:19:28 -0800602 const AudioConfig& config = GetParam();
Kevin Rocardf0357882017-02-10 16:19:28 -0800603 AudioInputFlag flags = AudioInputFlag::NONE; // TODO: test all flag combination
604 AudioSource source = AudioSource::DEFAULT; // TODO: test all flag combination
605 testOpen([&](AudioIoHandle handle, AudioConfig config, auto cb)
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800606 { return device->openInputStream(handle, address, config, flags, source, cb); },
Kevin Rocardf0357882017-02-10 16:19:28 -0800607 config);
608 }
609};
610
611TEST_P(InputStreamTest, OpenInputStreamTest) {
612 doc::test("Check that input streams can be open with the required and recommended config");
613 // Open done in setup
614}
615INSTANTIATE_TEST_CASE_P(
616 RequiredInputStreamConfigSupport, InputStreamTest,
Kevin Rocard9c369142017-03-08 17:17:25 -0800617 ::testing::ValuesIn(AudioConfigPrimaryTest::getRequiredSupportCaptureAudioConfig()),
618 &generateTestName);
Kevin Rocardf0357882017-02-10 16:19:28 -0800619INSTANTIATE_TEST_CASE_P(
620 SupportedInputStreamConfig, InputStreamTest,
Kevin Rocard9c369142017-03-08 17:17:25 -0800621 ::testing::ValuesIn(AudioConfigPrimaryTest::getSupportedCaptureAudioConfig()),
622 &generateTestName);
Kevin Rocardf0357882017-02-10 16:19:28 -0800623
624INSTANTIATE_TEST_CASE_P(
625 RecommendedInputStreamConfigSupport, InputStreamTest,
Kevin Rocard9c369142017-03-08 17:17:25 -0800626 ::testing::ValuesIn(AudioConfigPrimaryTest::getRecommendedSupportCaptureAudioConfig()),
627 &generateTestName);
Kevin Rocardf0357882017-02-10 16:19:28 -0800628
629//////////////////////////////////////////////////////////////////////////////
630////////////////////////////// IStream getters ///////////////////////////////
631//////////////////////////////////////////////////////////////////////////////
632
633/** Unpack the provided result.
634 * If the result is not OK, register a failure and return an undefined value. */
635template <class R>
636static R extract(Return<R> ret) {
637 if (!ret.isOk()) {
638 ADD_FAILURE();
639 return R{};
640 }
641 return ret;
642}
643
Kevin Rocarda7df7fc2017-03-10 18:37:46 -0800644/* Could not find a way to write a test for two parametrized class fixure
645 * thus use this macro do duplicate tests for Input and Output stream */
646#define TEST_IO_STREAM(test_name, documentation, code) \
647 TEST_P(InputStreamTest, test_name) { \
648 doc::test(documentation); \
649 code; \
650 } \
651 TEST_P(OutputStreamTest, test_name) { \
652 doc::test(documentation); \
653 code; \
654 }
655
656TEST_IO_STREAM(GetFrameCount, "Check that the stream frame count == the one it was opened with",
657 ASSERT_EQ(audioConfig.frameCount, extract(stream->getFrameCount())))
658
659TEST_IO_STREAM(GetSampleRate, "Check that the stream sample rate == the one it was opened with",
660 ASSERT_EQ(audioConfig.sampleRateHz, extract(stream->getSampleRate())))
661
662TEST_IO_STREAM(GetChannelMask, "Check that the stream channel mask == the one it was opened with",
663 ASSERT_EQ(audioConfig.channelMask, extract(stream->getChannelMask())))
664
665TEST_IO_STREAM(GetFormat, "Check that the stream format == the one it was opened with",
666 ASSERT_EQ(audioConfig.format, extract(stream->getFormat())))
667
668// TODO: for now only check that the framesize is not incoherent
669TEST_IO_STREAM(GetFrameSize, "Check that the stream frame size == the one it was opened with",
670 ASSERT_GT(extract(stream->getFrameSize()), 0U))
671
672TEST_IO_STREAM(GetBufferSize, "Check that the stream buffer size== the one it was opened with",
673 ASSERT_GE(extract(stream->getBufferSize()), \
674 extract(stream->getFrameSize())));
675
Kevin Rocardf0357882017-02-10 16:19:28 -0800676template <class Property, class CapabilityGetter, class Getter, class Setter>
Kevin Rocarda7df7fc2017-03-10 18:37:46 -0800677static void testCapabilityGetter(const string& name, IStream* stream, Property currentValue,
Kevin Rocardf0357882017-02-10 16:19:28 -0800678 CapabilityGetter capablityGetter, Getter getter, Setter setter) {
679 hidl_vec<Property> capabilities;
680 ASSERT_OK((stream->*capablityGetter)(returnIn(capabilities)));
681 if (capabilities.size() == 0) {
682 // The default hal should probably return a NOT_SUPPORTED if the hal does not expose
683 // capability retrieval. For now it returns an empty list if not implemented
684 doc::partialTest(name + " is not supported");
685 return;
686 };
687 // TODO: This code has never been tested on a hal that supports getSupportedSampleRates
688 EXPECT_NE(std::find(capabilities.begin(), capabilities.end(), currentValue),
689 capabilities.end())
690 << "current " << name << " is not in the list of the supported ones "
691 << toString(capabilities);
692
693 // Check that all declared supported values are indeed supported
694 for (auto capability : capabilities) {
695 ASSERT_OK((stream->*setter)(capability));
696 ASSERT_EQ(capability, extract((stream->*getter)()));
697 }
698}
699
Kevin Rocarda7df7fc2017-03-10 18:37:46 -0800700TEST_IO_STREAM(SupportedSampleRate, "Check that the stream sample rate is declared as supported",
701 testCapabilityGetter("getSupportedSampleRate", stream.get(), \
702 extract(stream->getSampleRate()), \
703 &IStream::getSupportedSampleRates, \
704 &IStream::getSampleRate, &IStream::setSampleRate))
705
706TEST_IO_STREAM(SupportedChannelMask, "Check that the stream channel mask is declared as supported",
707 testCapabilityGetter("getSupportedChannelMask", stream.get(), \
708 extract(stream->getChannelMask()), \
709 &IStream::getSupportedChannelMasks, \
710 &IStream::getChannelMask, &IStream::setChannelMask))
711
712TEST_IO_STREAM(SupportedFormat, "Check that the stream format is declared as supported",
713 testCapabilityGetter("getSupportedFormat", stream.get(), \
714 extract(stream->getFormat()), \
715 &IStream::getSupportedFormats, \
716 &IStream::getFormat, &IStream::setFormat))
717
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800718static void testGetDevice(IStream* stream, AudioDevice expectedDevice) {
719 auto ret = stream->getDevice();
720 ASSERT_TRUE(ret.isOk());
721 AudioDevice device = ret;
722 ASSERT_EQ(expectedDevice, device);
723}
724
725TEST_IO_STREAM(GetDevice, "Check that the stream device == the one it was opened with",
726 areAudioPatchesSupported() ? doc::partialTest("Audio patches are supported") : \
727 testGetDevice(stream.get(), address.device))
728
729static void testSetDevice(IStream* stream, const DeviceAddress& address) {
730 DeviceAddress otherAddress = address;
731 otherAddress.device = (address.device & AudioDevice::BIT_IN) == 0 ?
732 AudioDevice::OUT_SPEAKER : AudioDevice::IN_BUILTIN_MIC;
733 EXPECT_OK(stream->setDevice(otherAddress));
734
735 ASSERT_OK(stream->setDevice(address)); // Go back to the original value
736}
737
738TEST_IO_STREAM(SetDevice, "Check that the stream can be rerouted to SPEAKER or BUILTIN_MIC",
739 areAudioPatchesSupported() ? doc::partialTest("Audio patches are supported") : \
740 testSetDevice(stream.get(), address))
741
Kevin Rocardf0357882017-02-10 16:19:28 -0800742static void testGetAudioProperties(IStream* stream, AudioConfig expectedConfig) {
743 uint32_t sampleRateHz;
744 AudioChannelMask mask;
745 AudioFormat format;
746
747 stream->getAudioProperties(returnIn(sampleRateHz, mask, format));
748
749 // FIXME: the qcom hal it does not currently negotiate the sampleRate & channel mask
Kevin Rocardd1e98ae2017-03-08 17:17:25 -0800750 EXPECT_EQ(expectedConfig.sampleRateHz, sampleRateHz);
751 EXPECT_EQ(expectedConfig.channelMask, mask);
Kevin Rocardf0357882017-02-10 16:19:28 -0800752 EXPECT_EQ(expectedConfig.format, format);
753}
754
Kevin Rocarda7df7fc2017-03-10 18:37:46 -0800755TEST_IO_STREAM(GetAudioProperties,
756 "Check that the stream audio properties == the ones it was opened with",
757 testGetAudioProperties(stream.get(), audioConfig))
Kevin Rocardf0357882017-02-10 16:19:28 -0800758
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800759static void testConnectedState(IStream* stream) {
760 DeviceAddress address = {};
761 using AD = AudioDevice;
762 for (auto device : {AD::OUT_HDMI, AD::OUT_WIRED_HEADPHONE, AD::IN_USB_HEADSET}) {
763 address.device = device;
764
765 ASSERT_OK(stream->setConnectedState(address, true));
766 ASSERT_OK(stream->setConnectedState(address, false));
767 }
768}
769TEST_IO_STREAM(SetConnectedState,
770 "Check that the stream can be notified of device connection and deconnection",
771 testConnectedState(stream.get()))
772
773
774static auto invalidArgsOrNotSupported = {Result::INVALID_ARGUMENTS, Result::NOT_SUPPORTED};
775TEST_IO_STREAM(SetHwAvSync, "Try to set hardware sync to an invalid value",
776 ASSERT_RESULT(invalidArgsOrNotSupported, stream->setHwAvSync(666)))
777
Kevin Rocarde9a8fb72017-03-21 11:39:55 -0700778TEST_IO_STREAM(GetHwAvSync, "Get hardware sync can not fail",
779 ASSERT_TRUE(device->getHwAvSync().isOk()))
780
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800781static void checkGetParameter(IStream* stream, hidl_vec<hidl_string> keys,
782 vector<Result> expectedResults) {
783 hidl_vec<ParameterValue> parameters;
784 Result res;
785 ASSERT_OK(stream->getParameters(keys, returnIn(res, parameters)));
786 ASSERT_RESULT(expectedResults, res);
787 if (res == Result::OK) {
788 ASSERT_EQ(0U, parameters.size());
789 }
790}
791
792/* Get/Set parameter is intended to be an opaque channel between vendors app and their HALs.
793 * Thus can not be meaningfully tested.
794 * TODO: Doc missing. Should asking for an empty set of params raise an error ?
795 */
796TEST_IO_STREAM(getEmptySetParameter, "Retrieve the values of an empty set",
797 checkGetParameter(stream.get(), {} /* keys */,
798 {Result::OK, Result::INVALID_ARGUMENTS}))
799
800
801TEST_IO_STREAM(getNonExistingParameter, "Retrieve the values of an non existing parameter",
802 checkGetParameter(stream.get(), {"Non existing key"} /* keys */,
803 {Result::INVALID_ARGUMENTS}))
804
Kevin Rocard624800c2017-03-10 18:47:37 -0800805static vector<Result> okOrInvalidArguments = {Result::OK, Result::INVALID_ARGUMENTS};
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800806TEST_IO_STREAM(setEmptySetParameter, "Set the values of an empty set of parameters",
Kevin Rocard624800c2017-03-10 18:47:37 -0800807 ASSERT_RESULT(okOrInvalidArguments, stream->setParameters({})))
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800808
809TEST_IO_STREAM(setNonExistingParameter, "Set the values of an non existing parameter",
810 ASSERT_RESULT(Result::INVALID_ARGUMENTS,
811 stream->setParameters({{"non existing key", "0"}})))
812
Kevin Rocardb9031242017-03-13 12:20:54 -0700813TEST_IO_STREAM(DebugDump,
814 "Check that a stream can dump its state without error",
815 testDebugDump([this](const auto& handle){ return stream->debugDump(handle); }))
816
Mikhail Naganov3e6fe752017-04-24 10:44:08 -0700817TEST_IO_STREAM(DebugDumpInvalidArguments,
818 "Check that the stream dump doesn't crash on invalid arguments",
819 ASSERT_OK(stream->debugDump(hidl_handle())))
820
Kevin Rocardf0357882017-02-10 16:19:28 -0800821//////////////////////////////////////////////////////////////////////////////
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800822////////////////////////////// addRemoveEffect ///////////////////////////////
Kevin Rocardf0357882017-02-10 16:19:28 -0800823//////////////////////////////////////////////////////////////////////////////
824
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800825TEST_IO_STREAM(AddNonExistingEffect, "Adding a non existing effect should fail",
826 ASSERT_RESULT(Result::INVALID_ARGUMENTS, stream->addEffect(666)))
827TEST_IO_STREAM(RemoveNonExistingEffect, "Removing a non existing effect should fail",
828 ASSERT_RESULT(Result::INVALID_ARGUMENTS, stream->removeEffect(666)))
Kevin Rocardf0357882017-02-10 16:19:28 -0800829
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800830//TODO: positive tests
831
832//////////////////////////////////////////////////////////////////////////////
833/////////////////////////////// Control ////////////////////////////////
834//////////////////////////////////////////////////////////////////////////////
835
836TEST_IO_STREAM(standby, "Make sure the stream can be put in stanby",
837 ASSERT_OK(stream->standby())) // can not fail
838
839static vector<Result> invalidStateOrNotSupported = {Result::INVALID_STATE, Result::NOT_SUPPORTED};
840
841TEST_IO_STREAM(startNoMmap, "Starting a mmaped stream before mapping it should fail",
842 ASSERT_RESULT(invalidStateOrNotSupported, stream->start()))
843
844TEST_IO_STREAM(stopNoMmap, "Stopping a mmaped stream before mapping it should fail",
845 ASSERT_RESULT(invalidStateOrNotSupported, stream->stop()))
846
847TEST_IO_STREAM(getMmapPositionNoMmap, "Get a stream Mmap position before mapping it should fail",
848 ASSERT_RESULT(invalidStateOrNotSupported, stream->stop()))
849
850TEST_IO_STREAM(close, "Make sure a stream can be closed", ASSERT_OK(closeStream()))
851TEST_IO_STREAM(closeTwice, "Make sure a stream can not be closed twice",
852 ASSERT_OK(closeStream()); \
853 ASSERT_RESULT(Result::INVALID_STATE, closeStream()))
854
855static void testCreateTooBigMmapBuffer(IStream* stream) {
856 MmapBufferInfo info;
857 Result res;
858 // Assume that int max is a value too big to be allocated
859 // This is true currently with a 32bit media server, but might not when it will run in 64 bit
860 auto minSizeFrames = std::numeric_limits<int32_t>::max();
861 ASSERT_OK(stream->createMmapBuffer(minSizeFrames, returnIn(res, info)));
862 ASSERT_RESULT(invalidArgsOrNotSupported, res);
Kevin Rocardf0357882017-02-10 16:19:28 -0800863}
864
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800865TEST_IO_STREAM(CreateTooBigMmapBuffer, "Create mmap buffer too big should fail",
866 testCreateTooBigMmapBuffer(stream.get()))
867
868
869static void testGetMmapPositionOfNonMmapedStream(IStream* stream) {
870 Result res;
871 MmapPosition position;
872 ASSERT_OK(stream->getMmapPosition(returnIn(res, position)));
873 ASSERT_RESULT(invalidArgsOrNotSupported, res);
874}
875
876TEST_IO_STREAM(GetMmapPositionOfNonMmapedStream,
877 "Retrieving the mmap position of a non mmaped stream should fail",
878 testGetMmapPositionOfNonMmapedStream(stream.get()))
879
Kevin Rocardf0357882017-02-10 16:19:28 -0800880//////////////////////////////////////////////////////////////////////////////
Kevin Rocardc9963522017-03-10 18:47:37 -0800881///////////////////////////////// StreamIn ///////////////////////////////////
882//////////////////////////////////////////////////////////////////////////////
883
884TEST_P(InputStreamTest, GetAudioSource) {
885 doc::test("Retrieving the audio source of an input stream should always succeed");
886 AudioSource source;
887 ASSERT_OK(stream->getAudioSource(returnIn(res, source)));
888 ASSERT_OK(res);
889 ASSERT_EQ(AudioSource::DEFAULT, source);
890}
891
892static void testUnitaryGain(std::function<Return<Result> (float)> setGain) {
893 for (float value : {0.0, 0.01, 0.5, 0.09, 1.0}) {
894 SCOPED_TRACE("value=" + to_string(value));
895 ASSERT_OK(setGain(value));
896 }
897 for (float value : (float[]){-INFINITY,-1.0, -0.0,
898 1.0 + std::numeric_limits<float>::epsilon(), 2.0, INFINITY,
899 NAN}) {
900 SCOPED_TRACE("value=" + to_string(value));
901 // FIXME: NAN should never be accepted
902 // FIXME: Missing api doc. What should the impl do if the volume is outside [0,1] ?
903 ASSERT_RESULT(Result::INVALID_ARGUMENTS, setGain(value));
904 }
905}
906
907TEST_P(InputStreamTest, SetGain) {
908 doc::test("The gain of an input stream should only be set between [0,1]");
909 testUnitaryGain([this](float volume) { return stream->setGain(volume); });
910}
911
912static void testPrepareForReading(IStreamIn* stream, uint32_t frameSize, uint32_t framesCount) {
913 Result res;
914 // Ignore output parameters as the call should fail
915 ASSERT_OK(stream->prepareForReading(frameSize, framesCount,
916 [&res](auto r, auto&, auto&, auto&, auto&) { res = r; }));
917 EXPECT_RESULT(invalidArgsOrNotSupported, res);
918}
919
920TEST_P(InputStreamTest, PrepareForReadingWithHugeBuffer) {
921 doc::test("Preparing a stream for reading with a 2^32 sized buffer should fail");
922 testPrepareForReading(stream.get(), 1, std::numeric_limits<uint32_t>::max());
923}
924
925TEST_P(InputStreamTest, PrepareForReadingCheckOverflow) {
926 doc::test("Preparing a stream for reading with a overflowing sized buffer should fail");
927 auto uintMax = std::numeric_limits<uint32_t>::max();
928 testPrepareForReading(stream.get(), uintMax, uintMax);
929}
930
Kevin Rocarde9a8fb72017-03-21 11:39:55 -0700931TEST_P(InputStreamTest, GetInputFramesLost) {
932 doc::test("The number of frames lost on a never started stream should be 0");
933 auto ret = stream->getInputFramesLost();
934 ASSERT_TRUE(ret.isOk());
935 uint32_t framesLost{ret};
936 ASSERT_EQ(0U, framesLost);
937}
938
Kevin Rocardc9963522017-03-10 18:47:37 -0800939TEST_P(InputStreamTest, getCapturePosition) {
940 doc::test("The capture position of a non prepared stream should not be retrievable");
941 uint64_t frames;
942 uint64_t time;
943 ASSERT_OK(stream->getCapturePosition(returnIn(res, frames, time)));
944 ASSERT_RESULT(invalidStateOrNotSupported, res);
945}
946
947//////////////////////////////////////////////////////////////////////////////
Kevin Rocard624800c2017-03-10 18:47:37 -0800948///////////////////////////////// StreamIn ///////////////////////////////////
949//////////////////////////////////////////////////////////////////////////////
950
951TEST_P(OutputStreamTest, getLatency) {
952 doc::test("Make sure latency is over 0");
953 auto result = stream->getLatency();
954 ASSERT_TRUE(result.isOk());
955 ASSERT_GT(result, 0U);
956}
957
958TEST_P(OutputStreamTest, setVolume) {
959 doc::test("Try to set the output volume");
960 auto result = stream->setVolume(1, 1);
961 ASSERT_TRUE(result.isOk());
962 if (result == Result::NOT_SUPPORTED) {
963 doc::partialTest("setVolume is not supported");
964 return;
965 }
966 testUnitaryGain([this](float volume) { return stream->setVolume(volume, volume); });
967}
968
969static void testPrepareForWriting(IStreamOut* stream, uint32_t frameSize, uint32_t framesCount) {
970 Result res;
971 // Ignore output parameters as the call should fail
972 ASSERT_OK(stream->prepareForWriting(frameSize, framesCount,
973 [&res](auto r, auto&, auto&, auto&, auto&) { res = r; }));
974 EXPECT_RESULT(invalidArgsOrNotSupported, res);
975}
976
977TEST_P(OutputStreamTest, PrepareForWriteWithHugeBuffer) {
978 doc::test("Preparing a stream for writing with a 2^32 sized buffer should fail");
979 testPrepareForWriting(stream.get(), 1, std::numeric_limits<uint32_t>::max());
980}
981
982TEST_P(OutputStreamTest, PrepareForWritingCheckOverflow) {
983 doc::test("Preparing a stream for writing with a overflowing sized buffer should fail");
984 auto uintMax = std::numeric_limits<uint32_t>::max();
985 testPrepareForWriting(stream.get(), uintMax, uintMax);
986}
987
988struct Capability {
989 Capability(IStreamOut* stream) {
990 EXPECT_OK(stream->supportsPauseAndResume(returnIn(pause, resume)));
991 auto ret = stream->supportsDrain();
992 EXPECT_TRUE(ret.isOk());
993 if (ret.isOk()) {
994 drain = ret;
995 }
996 }
997 bool pause = false;
998 bool resume = false;
999 bool drain = false;
1000};
1001
1002TEST_P(OutputStreamTest, SupportsPauseAndResumeAndDrain) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001003 doc::test("Implementation must expose pause, resume and drain capabilities");
Kevin Rocard624800c2017-03-10 18:47:37 -08001004 Capability(stream.get());
1005}
1006
1007TEST_P(OutputStreamTest, GetRenderPosition) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001008 doc::test("The render position should be 0 on a not started");
Kevin Rocard624800c2017-03-10 18:47:37 -08001009 uint32_t dspFrames;
1010 ASSERT_OK(stream->getRenderPosition(returnIn(res, dspFrames)));
1011 if (res == Result::NOT_SUPPORTED) {
1012 doc::partialTest("getRenderPosition is not supported");
1013 return;
1014 }
1015 ASSERT_OK(res);
1016 ASSERT_EQ(0U, dspFrames);
1017}
1018
1019TEST_P(OutputStreamTest, GetNextWriteTimestamp) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001020 doc::test("The render position of a stream just created should be 0");
Kevin Rocard624800c2017-03-10 18:47:37 -08001021 uint64_t timestampUs;
Kevin Rocarde9a8fb72017-03-21 11:39:55 -07001022 ASSERT_OK(stream->getNextWriteTimestamp(returnIn(res, timestampUs)));
Kevin Rocard624800c2017-03-10 18:47:37 -08001023 if (res == Result::NOT_SUPPORTED) {
Kevin Rocarde9a8fb72017-03-21 11:39:55 -07001024 doc::partialTest("getNextWriteTimestamp is not supported");
Kevin Rocard624800c2017-03-10 18:47:37 -08001025 return;
1026 }
Kevin Rocarde9a8fb72017-03-21 11:39:55 -07001027 ASSERT_EQ(Result::INVALID_STATE, res);
Kevin Rocard624800c2017-03-10 18:47:37 -08001028}
1029
1030/** Stub implementation of out stream callback. */
1031class MockOutCallbacks : public IStreamOutCallback {
1032 Return<void> onWriteReady() override { return {}; }
1033 Return<void> onDrainReady() override { return {}; }
1034 Return<void> onError() override { return {}; }
1035};
1036
1037static bool isAsyncModeSupported(IStreamOut *stream) {
1038 auto res = stream->setCallback(new MockOutCallbacks);
1039 stream->clearCallback(); // try to restore the no callback state, ignore any error
1040 auto okOrNotSupported = { Result::OK, Result::NOT_SUPPORTED };
1041 EXPECT_RESULT(okOrNotSupported, res);
1042 return res.isOk() ? res == Result::OK : false;
1043}
1044
1045TEST_P(OutputStreamTest, SetCallback) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001046 doc::test("If supported, registering callback for async operation should never fail");
Kevin Rocard624800c2017-03-10 18:47:37 -08001047 if (!isAsyncModeSupported(stream.get())) {
1048 doc::partialTest("The stream does not support async operations");
1049 return;
1050 }
1051 ASSERT_OK(stream->setCallback(new MockOutCallbacks));
1052 ASSERT_OK(stream->setCallback(new MockOutCallbacks));
1053}
1054
1055TEST_P(OutputStreamTest, clearCallback) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001056 doc::test("If supported, clearing a callback to go back to sync operation should not fail");
Kevin Rocard624800c2017-03-10 18:47:37 -08001057 if (!isAsyncModeSupported(stream.get())) {
1058 doc::partialTest("The stream does not support async operations");
1059 return;
1060 }
1061 // TODO: Clarify if clearing a non existing callback should fail
1062 ASSERT_OK(stream->setCallback(new MockOutCallbacks));
1063 ASSERT_OK(stream->clearCallback());
1064}
1065
1066TEST_P(OutputStreamTest, Resume) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001067 doc::test("If supported, a stream should fail to resume if not previously paused");
Kevin Rocard624800c2017-03-10 18:47:37 -08001068 if (!Capability(stream.get()).resume) {
1069 doc::partialTest("The output stream does not support resume");
1070 return;
1071 }
1072 ASSERT_RESULT(Result::INVALID_STATE, stream->resume());
1073}
1074
1075TEST_P(OutputStreamTest, Pause) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001076 doc::test("If supported, a stream should fail to pause if not previously started");
Kevin Rocard624800c2017-03-10 18:47:37 -08001077 if (!Capability(stream.get()).pause) {
1078 doc::partialTest("The output stream does not support pause");
1079 return;
1080 }
1081 ASSERT_RESULT(Result::INVALID_STATE, stream->resume());
1082}
1083
1084static void testDrain(IStreamOut *stream, AudioDrain type) {
1085 if (!Capability(stream).drain) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001086 doc::partialTest("The output stream does not support drain");
Kevin Rocard624800c2017-03-10 18:47:37 -08001087 return;
1088 }
1089 ASSERT_RESULT(Result::OK, stream->drain(type));
1090}
1091
1092TEST_P(OutputStreamTest, DrainAll) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001093 doc::test("If supported, a stream should always succeed to drain");
Kevin Rocard624800c2017-03-10 18:47:37 -08001094 testDrain(stream.get(), AudioDrain::ALL);
1095}
1096
1097TEST_P(OutputStreamTest, DrainEarlyNotify) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001098 doc::test("If supported, a stream should always succeed to drain");
Kevin Rocard624800c2017-03-10 18:47:37 -08001099 testDrain(stream.get(), AudioDrain::EARLY_NOTIFY);
1100}
1101
1102TEST_P(OutputStreamTest, FlushStop) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001103 doc::test("If supported, a stream should always succeed to flush");
Kevin Rocarde9a8fb72017-03-21 11:39:55 -07001104 auto ret = stream->flush();
1105 ASSERT_TRUE(ret.isOk());
1106 if (ret == Result::NOT_SUPPORTED) {
1107 doc::partialTest("Flush is not supported");
1108 return;
1109 }
1110 ASSERT_OK(ret);
Kevin Rocard624800c2017-03-10 18:47:37 -08001111}
1112
1113TEST_P(OutputStreamTest, GetPresentationPositionStop) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001114 doc::test("If supported, a stream should always succeed to retrieve the presentation position");
Kevin Rocard624800c2017-03-10 18:47:37 -08001115 uint64_t frames;
1116 TimeSpec mesureTS;
1117 ASSERT_OK(stream->getPresentationPosition(returnIn(res, frames, mesureTS)));
1118 if (res == Result::NOT_SUPPORTED) {
1119 doc::partialTest("getpresentationPosition is not supported");
1120 return;
1121 }
1122 ASSERT_EQ(0U, frames);
1123
1124 struct timespec currentTS;
1125 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &currentTS)) << errno;
1126
1127 auto toMicroSec = [](uint64_t sec, auto nsec) { return sec * 1e+6 + nsec / 1e+3; };
1128 auto currentTime = toMicroSec(currentTS.tv_sec, currentTS.tv_nsec);
1129 auto mesureTime = toMicroSec(mesureTS.tvSec, mesureTS.tvNSec);
1130 ASSERT_PRED2([](auto c, auto m){ return c - m < 1e+6; }, currentTime, mesureTime);
1131}
1132
1133
1134//////////////////////////////////////////////////////////////////////////////
Kevin Rocard3c405a72017-03-08 16:46:51 -08001135/////////////////////////////// PrimaryDevice ////////////////////////////////
1136//////////////////////////////////////////////////////////////////////////////
1137
Kevin Rocardc9963522017-03-10 18:47:37 -08001138
Kevin Rocard3c405a72017-03-08 16:46:51 -08001139TEST_F(AudioPrimaryHidlTest, setVoiceVolume) {
1140 doc::test("Make sure setVoiceVolume only succeed if volume is in [0,1]");
Kevin Rocardc9963522017-03-10 18:47:37 -08001141 testUnitaryGain([this](float volume) { return device->setVoiceVolume(volume); });
Kevin Rocard3c405a72017-03-08 16:46:51 -08001142}
1143
1144TEST_F(AudioPrimaryHidlTest, setMode) {
1145 doc::test("Make sure setMode always succeeds if mode is valid");
1146 for (AudioMode mode : {AudioMode::IN_CALL, AudioMode::IN_COMMUNICATION,
1147 AudioMode::RINGTONE, AudioMode::CURRENT,
1148 AudioMode::NORMAL /* Make sure to leave the test in normal mode */ }) {
1149 SCOPED_TRACE("mode=" + toString(mode));
1150 ASSERT_OK(device->setMode(mode));
1151 }
1152
1153 // FIXME: Missing api doc. What should the impl do if the mode is invalid ?
Kevin Rocard20e7af62017-03-10 17:10:43 -08001154 ASSERT_RESULT(Result::INVALID_ARGUMENTS, device->setMode(AudioMode::INVALID));
Kevin Rocard3c405a72017-03-08 16:46:51 -08001155}
1156
1157
1158TEST_F(BoolAccessorPrimaryHidlTest, BtScoNrecEnabled) {
1159 doc::test("Query and set the BT SCO NR&EC state");
1160 testOptionalAccessors("BtScoNrecEnabled", {true, false, true},
1161 &IPrimaryDevice::setBtScoNrecEnabled,
1162 &IPrimaryDevice::getBtScoNrecEnabled);
1163}
1164
1165TEST_F(BoolAccessorPrimaryHidlTest, setGetBtScoWidebandEnabled) {
1166 doc::test("Query and set the SCO whideband state");
1167 testOptionalAccessors("BtScoWideband", {true, false, true},
1168 &IPrimaryDevice::setBtScoWidebandEnabled,
1169 &IPrimaryDevice::getBtScoWidebandEnabled);
1170}
1171
1172using TtyModeAccessorPrimaryHidlTest = AccessorPrimaryHidlTest<TtyMode>;
1173TEST_F(TtyModeAccessorPrimaryHidlTest, setGetTtyMode) {
1174 doc::test("Query and set the TTY mode state");
1175 testOptionalAccessors("TTY mode", {TtyMode::OFF, TtyMode::HCO, TtyMode::VCO, TtyMode::FULL},
1176 &IPrimaryDevice::setTtyMode, &IPrimaryDevice::getTtyMode);
1177}
1178
1179TEST_F(BoolAccessorPrimaryHidlTest, setGetHac) {
1180 doc::test("Query and set the HAC state");
1181 testAccessors("HAC", {true, false, true},
1182 &IPrimaryDevice::setHacEnabled,
1183 &IPrimaryDevice::getHacEnabled);
1184}
1185
1186//////////////////////////////////////////////////////////////////////////////
Kevin Rocardf0357882017-02-10 16:19:28 -08001187//////////////////// Clean caches on global tear down ////////////////////////
1188//////////////////////////////////////////////////////////////////////////////
1189
1190int main(int argc, char** argv) {
1191 environment = new Environment;
1192 ::testing::AddGlobalTestEnvironment(environment);
1193 ::testing::InitGoogleTest(&argc, argv);
1194 int status = RUN_ALL_TESTS();
1195 LOG(INFO) << "Test result = " << status;
1196 return status;
1197}