blob: 4b00f35c370790d415075fef9b69d3fb8176fd94 [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
Kevin Rocardf0357882017-02-10 16:19:28 -0800501//////////////////////////////////////////////////////////////////////////////
502////////////////////////// open{Output,Input}Stream //////////////////////////
503//////////////////////////////////////////////////////////////////////////////
504
505template <class Stream>
506class OpenStreamTest : public AudioConfigPrimaryTest,
507 public ::testing::WithParamInterface<AudioConfig> {
508protected:
509 template <class Open>
510 void testOpen(Open openStream, const AudioConfig& config) {
511 // FIXME: Open a stream without an IOHandle
512 // This is not required to be accepted by hal implementations
513 AudioIoHandle ioHandle = (AudioIoHandle)AudioHandleConsts::AUDIO_IO_HANDLE_NONE;
514 AudioConfig suggestedConfig{};
515 ASSERT_OK(openStream(ioHandle, config, returnIn(res, stream, suggestedConfig)));
516
517 // TODO: only allow failure for RecommendedPlaybackAudioConfig
518 switch (res) {
519 case Result::OK:
520 ASSERT_TRUE(stream != nullptr);
521 audioConfig = config;
522 break;
523 case Result::INVALID_ARGUMENTS:
524 ASSERT_TRUE(stream == nullptr);
525 AudioConfig suggestedConfigRetry;
526 // Could not open stream with config, try again with the suggested one
527 ASSERT_OK(openStream(ioHandle, suggestedConfig,
528 returnIn(res, stream, suggestedConfigRetry)));
529 // This time it must succeed
530 ASSERT_OK(res);
531 ASSERT_TRUE(stream == nullptr);
532 audioConfig = suggestedConfig;
533 break;
534 default:
535 FAIL() << "Invalid return status: " << ::testing::PrintToString(res);
536 }
537 open = true;
538 }
539
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800540 Return<Result> closeStream() {
541 open = false;
542 return stream->close();
543 }
Kevin Rocardf0357882017-02-10 16:19:28 -0800544private:
545 void TearDown() override {
546 if (open) {
547 ASSERT_OK(stream->close());
548 }
549 }
550
551protected:
552
553 AudioConfig audioConfig;
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800554 DeviceAddress address = {};
Kevin Rocardf0357882017-02-10 16:19:28 -0800555 sp<Stream> stream;
556 bool open = false;
557};
558
559////////////////////////////// openOutputStream //////////////////////////////
560
561class OutputStreamTest : public OpenStreamTest<IStreamOut> {
562 virtual void SetUp() override {
563 ASSERT_NO_FATAL_FAILURE(OpenStreamTest::SetUp()); // setup base
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800564 address.device = AudioDevice::OUT_DEFAULT;
Kevin Rocardf0357882017-02-10 16:19:28 -0800565 const AudioConfig& config = GetParam();
Kevin Rocardf0357882017-02-10 16:19:28 -0800566 AudioOutputFlag flags = AudioOutputFlag::NONE; // TODO: test all flag combination
567 testOpen([&](AudioIoHandle handle, AudioConfig config, auto cb)
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800568 { return device->openOutputStream(handle, address, config, flags, cb); },
Kevin Rocardf0357882017-02-10 16:19:28 -0800569 config);
570 }
571};
572TEST_P(OutputStreamTest, OpenOutputStreamTest) {
573 doc::test("Check that output streams can be open with the required and recommended config");
574 // Open done in SetUp
575}
576INSTANTIATE_TEST_CASE_P(
577 RequiredOutputStreamConfigSupport, OutputStreamTest,
Kevin Rocard9c369142017-03-08 17:17:25 -0800578 ::testing::ValuesIn(AudioConfigPrimaryTest::getRequiredSupportPlaybackAudioConfig()),
579 &generateTestName);
Kevin Rocardf0357882017-02-10 16:19:28 -0800580INSTANTIATE_TEST_CASE_P(
581 SupportedOutputStreamConfig, OutputStreamTest,
Kevin Rocard9c369142017-03-08 17:17:25 -0800582 ::testing::ValuesIn(AudioConfigPrimaryTest::getSupportedPlaybackAudioConfig()),
583 &generateTestName);
Kevin Rocardf0357882017-02-10 16:19:28 -0800584
585INSTANTIATE_TEST_CASE_P(
586 RecommendedOutputStreamConfigSupport, OutputStreamTest,
Kevin Rocard9c369142017-03-08 17:17:25 -0800587 ::testing::ValuesIn(AudioConfigPrimaryTest::getRecommendedSupportPlaybackAudioConfig()),
588 &generateTestName);
Kevin Rocardf0357882017-02-10 16:19:28 -0800589
590////////////////////////////// openInputStream //////////////////////////////
591
592class InputStreamTest : public OpenStreamTest<IStreamIn> {
593
594 virtual void SetUp() override {
595 ASSERT_NO_FATAL_FAILURE(OpenStreamTest::SetUp()); // setup base
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800596 address.device = AudioDevice::IN_DEFAULT;
Kevin Rocardf0357882017-02-10 16:19:28 -0800597 const AudioConfig& config = GetParam();
Kevin Rocardf0357882017-02-10 16:19:28 -0800598 AudioInputFlag flags = AudioInputFlag::NONE; // TODO: test all flag combination
599 AudioSource source = AudioSource::DEFAULT; // TODO: test all flag combination
600 testOpen([&](AudioIoHandle handle, AudioConfig config, auto cb)
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800601 { return device->openInputStream(handle, address, config, flags, source, cb); },
Kevin Rocardf0357882017-02-10 16:19:28 -0800602 config);
603 }
604};
605
606TEST_P(InputStreamTest, OpenInputStreamTest) {
607 doc::test("Check that input streams can be open with the required and recommended config");
608 // Open done in setup
609}
610INSTANTIATE_TEST_CASE_P(
611 RequiredInputStreamConfigSupport, InputStreamTest,
Kevin Rocard9c369142017-03-08 17:17:25 -0800612 ::testing::ValuesIn(AudioConfigPrimaryTest::getRequiredSupportCaptureAudioConfig()),
613 &generateTestName);
Kevin Rocardf0357882017-02-10 16:19:28 -0800614INSTANTIATE_TEST_CASE_P(
615 SupportedInputStreamConfig, InputStreamTest,
Kevin Rocard9c369142017-03-08 17:17:25 -0800616 ::testing::ValuesIn(AudioConfigPrimaryTest::getSupportedCaptureAudioConfig()),
617 &generateTestName);
Kevin Rocardf0357882017-02-10 16:19:28 -0800618
619INSTANTIATE_TEST_CASE_P(
620 RecommendedInputStreamConfigSupport, InputStreamTest,
Kevin Rocard9c369142017-03-08 17:17:25 -0800621 ::testing::ValuesIn(AudioConfigPrimaryTest::getRecommendedSupportCaptureAudioConfig()),
622 &generateTestName);
Kevin Rocardf0357882017-02-10 16:19:28 -0800623
624//////////////////////////////////////////////////////////////////////////////
625////////////////////////////// IStream getters ///////////////////////////////
626//////////////////////////////////////////////////////////////////////////////
627
628/** Unpack the provided result.
629 * If the result is not OK, register a failure and return an undefined value. */
630template <class R>
631static R extract(Return<R> ret) {
632 if (!ret.isOk()) {
633 ADD_FAILURE();
634 return R{};
635 }
636 return ret;
637}
638
Kevin Rocarda7df7fc2017-03-10 18:37:46 -0800639/* Could not find a way to write a test for two parametrized class fixure
640 * thus use this macro do duplicate tests for Input and Output stream */
641#define TEST_IO_STREAM(test_name, documentation, code) \
642 TEST_P(InputStreamTest, test_name) { \
643 doc::test(documentation); \
644 code; \
645 } \
646 TEST_P(OutputStreamTest, test_name) { \
647 doc::test(documentation); \
648 code; \
649 }
650
651TEST_IO_STREAM(GetFrameCount, "Check that the stream frame count == the one it was opened with",
652 ASSERT_EQ(audioConfig.frameCount, extract(stream->getFrameCount())))
653
654TEST_IO_STREAM(GetSampleRate, "Check that the stream sample rate == the one it was opened with",
655 ASSERT_EQ(audioConfig.sampleRateHz, extract(stream->getSampleRate())))
656
657TEST_IO_STREAM(GetChannelMask, "Check that the stream channel mask == the one it was opened with",
658 ASSERT_EQ(audioConfig.channelMask, extract(stream->getChannelMask())))
659
660TEST_IO_STREAM(GetFormat, "Check that the stream format == the one it was opened with",
661 ASSERT_EQ(audioConfig.format, extract(stream->getFormat())))
662
663// TODO: for now only check that the framesize is not incoherent
664TEST_IO_STREAM(GetFrameSize, "Check that the stream frame size == the one it was opened with",
665 ASSERT_GT(extract(stream->getFrameSize()), 0U))
666
667TEST_IO_STREAM(GetBufferSize, "Check that the stream buffer size== the one it was opened with",
668 ASSERT_GE(extract(stream->getBufferSize()), \
669 extract(stream->getFrameSize())));
670
Kevin Rocardf0357882017-02-10 16:19:28 -0800671template <class Property, class CapabilityGetter, class Getter, class Setter>
Kevin Rocarda7df7fc2017-03-10 18:37:46 -0800672static void testCapabilityGetter(const string& name, IStream* stream, Property currentValue,
Kevin Rocardf0357882017-02-10 16:19:28 -0800673 CapabilityGetter capablityGetter, Getter getter, Setter setter) {
674 hidl_vec<Property> capabilities;
675 ASSERT_OK((stream->*capablityGetter)(returnIn(capabilities)));
676 if (capabilities.size() == 0) {
677 // The default hal should probably return a NOT_SUPPORTED if the hal does not expose
678 // capability retrieval. For now it returns an empty list if not implemented
679 doc::partialTest(name + " is not supported");
680 return;
681 };
682 // TODO: This code has never been tested on a hal that supports getSupportedSampleRates
683 EXPECT_NE(std::find(capabilities.begin(), capabilities.end(), currentValue),
684 capabilities.end())
685 << "current " << name << " is not in the list of the supported ones "
686 << toString(capabilities);
687
688 // Check that all declared supported values are indeed supported
689 for (auto capability : capabilities) {
690 ASSERT_OK((stream->*setter)(capability));
691 ASSERT_EQ(capability, extract((stream->*getter)()));
692 }
693}
694
Kevin Rocarda7df7fc2017-03-10 18:37:46 -0800695TEST_IO_STREAM(SupportedSampleRate, "Check that the stream sample rate is declared as supported",
696 testCapabilityGetter("getSupportedSampleRate", stream.get(), \
697 extract(stream->getSampleRate()), \
698 &IStream::getSupportedSampleRates, \
699 &IStream::getSampleRate, &IStream::setSampleRate))
700
701TEST_IO_STREAM(SupportedChannelMask, "Check that the stream channel mask is declared as supported",
702 testCapabilityGetter("getSupportedChannelMask", stream.get(), \
703 extract(stream->getChannelMask()), \
704 &IStream::getSupportedChannelMasks, \
705 &IStream::getChannelMask, &IStream::setChannelMask))
706
707TEST_IO_STREAM(SupportedFormat, "Check that the stream format is declared as supported",
708 testCapabilityGetter("getSupportedFormat", stream.get(), \
709 extract(stream->getFormat()), \
710 &IStream::getSupportedFormats, \
711 &IStream::getFormat, &IStream::setFormat))
712
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800713static void testGetDevice(IStream* stream, AudioDevice expectedDevice) {
714 auto ret = stream->getDevice();
715 ASSERT_TRUE(ret.isOk());
716 AudioDevice device = ret;
717 ASSERT_EQ(expectedDevice, device);
718}
719
720TEST_IO_STREAM(GetDevice, "Check that the stream device == the one it was opened with",
721 areAudioPatchesSupported() ? doc::partialTest("Audio patches are supported") : \
722 testGetDevice(stream.get(), address.device))
723
724static void testSetDevice(IStream* stream, const DeviceAddress& address) {
725 DeviceAddress otherAddress = address;
726 otherAddress.device = (address.device & AudioDevice::BIT_IN) == 0 ?
727 AudioDevice::OUT_SPEAKER : AudioDevice::IN_BUILTIN_MIC;
728 EXPECT_OK(stream->setDevice(otherAddress));
729
730 ASSERT_OK(stream->setDevice(address)); // Go back to the original value
731}
732
733TEST_IO_STREAM(SetDevice, "Check that the stream can be rerouted to SPEAKER or BUILTIN_MIC",
734 areAudioPatchesSupported() ? doc::partialTest("Audio patches are supported") : \
735 testSetDevice(stream.get(), address))
736
Kevin Rocardf0357882017-02-10 16:19:28 -0800737static void testGetAudioProperties(IStream* stream, AudioConfig expectedConfig) {
738 uint32_t sampleRateHz;
739 AudioChannelMask mask;
740 AudioFormat format;
741
742 stream->getAudioProperties(returnIn(sampleRateHz, mask, format));
743
744 // FIXME: the qcom hal it does not currently negotiate the sampleRate & channel mask
Kevin Rocardd1e98ae2017-03-08 17:17:25 -0800745 EXPECT_EQ(expectedConfig.sampleRateHz, sampleRateHz);
746 EXPECT_EQ(expectedConfig.channelMask, mask);
Kevin Rocardf0357882017-02-10 16:19:28 -0800747 EXPECT_EQ(expectedConfig.format, format);
748}
749
Kevin Rocarda7df7fc2017-03-10 18:37:46 -0800750TEST_IO_STREAM(GetAudioProperties,
751 "Check that the stream audio properties == the ones it was opened with",
752 testGetAudioProperties(stream.get(), audioConfig))
Kevin Rocardf0357882017-02-10 16:19:28 -0800753
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800754static void testConnectedState(IStream* stream) {
755 DeviceAddress address = {};
756 using AD = AudioDevice;
757 for (auto device : {AD::OUT_HDMI, AD::OUT_WIRED_HEADPHONE, AD::IN_USB_HEADSET}) {
758 address.device = device;
759
760 ASSERT_OK(stream->setConnectedState(address, true));
761 ASSERT_OK(stream->setConnectedState(address, false));
762 }
763}
764TEST_IO_STREAM(SetConnectedState,
765 "Check that the stream can be notified of device connection and deconnection",
766 testConnectedState(stream.get()))
767
768
769static auto invalidArgsOrNotSupported = {Result::INVALID_ARGUMENTS, Result::NOT_SUPPORTED};
770TEST_IO_STREAM(SetHwAvSync, "Try to set hardware sync to an invalid value",
771 ASSERT_RESULT(invalidArgsOrNotSupported, stream->setHwAvSync(666)))
772
Kevin Rocarde9a8fb72017-03-21 11:39:55 -0700773TEST_IO_STREAM(GetHwAvSync, "Get hardware sync can not fail",
774 ASSERT_TRUE(device->getHwAvSync().isOk()))
775
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800776static void checkGetParameter(IStream* stream, hidl_vec<hidl_string> keys,
777 vector<Result> expectedResults) {
778 hidl_vec<ParameterValue> parameters;
779 Result res;
780 ASSERT_OK(stream->getParameters(keys, returnIn(res, parameters)));
781 ASSERT_RESULT(expectedResults, res);
782 if (res == Result::OK) {
783 ASSERT_EQ(0U, parameters.size());
784 }
785}
786
787/* Get/Set parameter is intended to be an opaque channel between vendors app and their HALs.
788 * Thus can not be meaningfully tested.
789 * TODO: Doc missing. Should asking for an empty set of params raise an error ?
790 */
791TEST_IO_STREAM(getEmptySetParameter, "Retrieve the values of an empty set",
792 checkGetParameter(stream.get(), {} /* keys */,
793 {Result::OK, Result::INVALID_ARGUMENTS}))
794
795
796TEST_IO_STREAM(getNonExistingParameter, "Retrieve the values of an non existing parameter",
797 checkGetParameter(stream.get(), {"Non existing key"} /* keys */,
798 {Result::INVALID_ARGUMENTS}))
799
Kevin Rocard624800c2017-03-10 18:47:37 -0800800static vector<Result> okOrInvalidArguments = {Result::OK, Result::INVALID_ARGUMENTS};
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800801TEST_IO_STREAM(setEmptySetParameter, "Set the values of an empty set of parameters",
Kevin Rocard624800c2017-03-10 18:47:37 -0800802 ASSERT_RESULT(okOrInvalidArguments, stream->setParameters({})))
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800803
804TEST_IO_STREAM(setNonExistingParameter, "Set the values of an non existing parameter",
805 ASSERT_RESULT(Result::INVALID_ARGUMENTS,
806 stream->setParameters({{"non existing key", "0"}})))
807
Kevin Rocardb9031242017-03-13 12:20:54 -0700808TEST_IO_STREAM(DebugDump,
809 "Check that a stream can dump its state without error",
810 testDebugDump([this](const auto& handle){ return stream->debugDump(handle); }))
811
Kevin Rocardf0357882017-02-10 16:19:28 -0800812//////////////////////////////////////////////////////////////////////////////
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800813////////////////////////////// addRemoveEffect ///////////////////////////////
Kevin Rocardf0357882017-02-10 16:19:28 -0800814//////////////////////////////////////////////////////////////////////////////
815
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800816TEST_IO_STREAM(AddNonExistingEffect, "Adding a non existing effect should fail",
817 ASSERT_RESULT(Result::INVALID_ARGUMENTS, stream->addEffect(666)))
818TEST_IO_STREAM(RemoveNonExistingEffect, "Removing a non existing effect should fail",
819 ASSERT_RESULT(Result::INVALID_ARGUMENTS, stream->removeEffect(666)))
Kevin Rocardf0357882017-02-10 16:19:28 -0800820
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800821//TODO: positive tests
822
823//////////////////////////////////////////////////////////////////////////////
824/////////////////////////////// Control ////////////////////////////////
825//////////////////////////////////////////////////////////////////////////////
826
827TEST_IO_STREAM(standby, "Make sure the stream can be put in stanby",
828 ASSERT_OK(stream->standby())) // can not fail
829
830static vector<Result> invalidStateOrNotSupported = {Result::INVALID_STATE, Result::NOT_SUPPORTED};
831
832TEST_IO_STREAM(startNoMmap, "Starting a mmaped stream before mapping it should fail",
833 ASSERT_RESULT(invalidStateOrNotSupported, stream->start()))
834
835TEST_IO_STREAM(stopNoMmap, "Stopping a mmaped stream before mapping it should fail",
836 ASSERT_RESULT(invalidStateOrNotSupported, stream->stop()))
837
838TEST_IO_STREAM(getMmapPositionNoMmap, "Get a stream Mmap position before mapping it should fail",
839 ASSERT_RESULT(invalidStateOrNotSupported, stream->stop()))
840
841TEST_IO_STREAM(close, "Make sure a stream can be closed", ASSERT_OK(closeStream()))
842TEST_IO_STREAM(closeTwice, "Make sure a stream can not be closed twice",
843 ASSERT_OK(closeStream()); \
844 ASSERT_RESULT(Result::INVALID_STATE, closeStream()))
845
846static void testCreateTooBigMmapBuffer(IStream* stream) {
847 MmapBufferInfo info;
848 Result res;
849 // Assume that int max is a value too big to be allocated
850 // This is true currently with a 32bit media server, but might not when it will run in 64 bit
851 auto minSizeFrames = std::numeric_limits<int32_t>::max();
852 ASSERT_OK(stream->createMmapBuffer(minSizeFrames, returnIn(res, info)));
853 ASSERT_RESULT(invalidArgsOrNotSupported, res);
Kevin Rocardf0357882017-02-10 16:19:28 -0800854}
855
Kevin Rocard8878b4b2017-03-10 18:47:37 -0800856TEST_IO_STREAM(CreateTooBigMmapBuffer, "Create mmap buffer too big should fail",
857 testCreateTooBigMmapBuffer(stream.get()))
858
859
860static void testGetMmapPositionOfNonMmapedStream(IStream* stream) {
861 Result res;
862 MmapPosition position;
863 ASSERT_OK(stream->getMmapPosition(returnIn(res, position)));
864 ASSERT_RESULT(invalidArgsOrNotSupported, res);
865}
866
867TEST_IO_STREAM(GetMmapPositionOfNonMmapedStream,
868 "Retrieving the mmap position of a non mmaped stream should fail",
869 testGetMmapPositionOfNonMmapedStream(stream.get()))
870
Kevin Rocardf0357882017-02-10 16:19:28 -0800871//////////////////////////////////////////////////////////////////////////////
Kevin Rocardc9963522017-03-10 18:47:37 -0800872///////////////////////////////// StreamIn ///////////////////////////////////
873//////////////////////////////////////////////////////////////////////////////
874
875TEST_P(InputStreamTest, GetAudioSource) {
876 doc::test("Retrieving the audio source of an input stream should always succeed");
877 AudioSource source;
878 ASSERT_OK(stream->getAudioSource(returnIn(res, source)));
879 ASSERT_OK(res);
880 ASSERT_EQ(AudioSource::DEFAULT, source);
881}
882
883static void testUnitaryGain(std::function<Return<Result> (float)> setGain) {
884 for (float value : {0.0, 0.01, 0.5, 0.09, 1.0}) {
885 SCOPED_TRACE("value=" + to_string(value));
886 ASSERT_OK(setGain(value));
887 }
888 for (float value : (float[]){-INFINITY,-1.0, -0.0,
889 1.0 + std::numeric_limits<float>::epsilon(), 2.0, INFINITY,
890 NAN}) {
891 SCOPED_TRACE("value=" + to_string(value));
892 // FIXME: NAN should never be accepted
893 // FIXME: Missing api doc. What should the impl do if the volume is outside [0,1] ?
894 ASSERT_RESULT(Result::INVALID_ARGUMENTS, setGain(value));
895 }
896}
897
898TEST_P(InputStreamTest, SetGain) {
899 doc::test("The gain of an input stream should only be set between [0,1]");
900 testUnitaryGain([this](float volume) { return stream->setGain(volume); });
901}
902
903static void testPrepareForReading(IStreamIn* stream, uint32_t frameSize, uint32_t framesCount) {
904 Result res;
905 // Ignore output parameters as the call should fail
906 ASSERT_OK(stream->prepareForReading(frameSize, framesCount,
907 [&res](auto r, auto&, auto&, auto&, auto&) { res = r; }));
908 EXPECT_RESULT(invalidArgsOrNotSupported, res);
909}
910
911TEST_P(InputStreamTest, PrepareForReadingWithHugeBuffer) {
912 doc::test("Preparing a stream for reading with a 2^32 sized buffer should fail");
913 testPrepareForReading(stream.get(), 1, std::numeric_limits<uint32_t>::max());
914}
915
916TEST_P(InputStreamTest, PrepareForReadingCheckOverflow) {
917 doc::test("Preparing a stream for reading with a overflowing sized buffer should fail");
918 auto uintMax = std::numeric_limits<uint32_t>::max();
919 testPrepareForReading(stream.get(), uintMax, uintMax);
920}
921
Kevin Rocarde9a8fb72017-03-21 11:39:55 -0700922TEST_P(InputStreamTest, GetInputFramesLost) {
923 doc::test("The number of frames lost on a never started stream should be 0");
924 auto ret = stream->getInputFramesLost();
925 ASSERT_TRUE(ret.isOk());
926 uint32_t framesLost{ret};
927 ASSERT_EQ(0U, framesLost);
928}
929
Kevin Rocardc9963522017-03-10 18:47:37 -0800930TEST_P(InputStreamTest, getCapturePosition) {
931 doc::test("The capture position of a non prepared stream should not be retrievable");
932 uint64_t frames;
933 uint64_t time;
934 ASSERT_OK(stream->getCapturePosition(returnIn(res, frames, time)));
935 ASSERT_RESULT(invalidStateOrNotSupported, res);
936}
937
938//////////////////////////////////////////////////////////////////////////////
Kevin Rocard624800c2017-03-10 18:47:37 -0800939///////////////////////////////// StreamIn ///////////////////////////////////
940//////////////////////////////////////////////////////////////////////////////
941
942TEST_P(OutputStreamTest, getLatency) {
943 doc::test("Make sure latency is over 0");
944 auto result = stream->getLatency();
945 ASSERT_TRUE(result.isOk());
946 ASSERT_GT(result, 0U);
947}
948
949TEST_P(OutputStreamTest, setVolume) {
950 doc::test("Try to set the output volume");
951 auto result = stream->setVolume(1, 1);
952 ASSERT_TRUE(result.isOk());
953 if (result == Result::NOT_SUPPORTED) {
954 doc::partialTest("setVolume is not supported");
955 return;
956 }
957 testUnitaryGain([this](float volume) { return stream->setVolume(volume, volume); });
958}
959
960static void testPrepareForWriting(IStreamOut* stream, uint32_t frameSize, uint32_t framesCount) {
961 Result res;
962 // Ignore output parameters as the call should fail
963 ASSERT_OK(stream->prepareForWriting(frameSize, framesCount,
964 [&res](auto r, auto&, auto&, auto&, auto&) { res = r; }));
965 EXPECT_RESULT(invalidArgsOrNotSupported, res);
966}
967
968TEST_P(OutputStreamTest, PrepareForWriteWithHugeBuffer) {
969 doc::test("Preparing a stream for writing with a 2^32 sized buffer should fail");
970 testPrepareForWriting(stream.get(), 1, std::numeric_limits<uint32_t>::max());
971}
972
973TEST_P(OutputStreamTest, PrepareForWritingCheckOverflow) {
974 doc::test("Preparing a stream for writing with a overflowing sized buffer should fail");
975 auto uintMax = std::numeric_limits<uint32_t>::max();
976 testPrepareForWriting(stream.get(), uintMax, uintMax);
977}
978
979struct Capability {
980 Capability(IStreamOut* stream) {
981 EXPECT_OK(stream->supportsPauseAndResume(returnIn(pause, resume)));
982 auto ret = stream->supportsDrain();
983 EXPECT_TRUE(ret.isOk());
984 if (ret.isOk()) {
985 drain = ret;
986 }
987 }
988 bool pause = false;
989 bool resume = false;
990 bool drain = false;
991};
992
993TEST_P(OutputStreamTest, SupportsPauseAndResumeAndDrain) {
Kevin Rocard6f226802017-04-03 10:29:34 -0700994 doc::test("Implementation must expose pause, resume and drain capabilities");
Kevin Rocard624800c2017-03-10 18:47:37 -0800995 Capability(stream.get());
996}
997
998TEST_P(OutputStreamTest, GetRenderPosition) {
Kevin Rocard6f226802017-04-03 10:29:34 -0700999 doc::test("The render position should be 0 on a not started");
Kevin Rocard624800c2017-03-10 18:47:37 -08001000 uint32_t dspFrames;
1001 ASSERT_OK(stream->getRenderPosition(returnIn(res, dspFrames)));
1002 if (res == Result::NOT_SUPPORTED) {
1003 doc::partialTest("getRenderPosition is not supported");
1004 return;
1005 }
1006 ASSERT_OK(res);
1007 ASSERT_EQ(0U, dspFrames);
1008}
1009
1010TEST_P(OutputStreamTest, GetNextWriteTimestamp) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001011 doc::test("The render position of a stream just created should be 0");
Kevin Rocard624800c2017-03-10 18:47:37 -08001012 uint64_t timestampUs;
Kevin Rocarde9a8fb72017-03-21 11:39:55 -07001013 ASSERT_OK(stream->getNextWriteTimestamp(returnIn(res, timestampUs)));
Kevin Rocard624800c2017-03-10 18:47:37 -08001014 if (res == Result::NOT_SUPPORTED) {
Kevin Rocarde9a8fb72017-03-21 11:39:55 -07001015 doc::partialTest("getNextWriteTimestamp is not supported");
Kevin Rocard624800c2017-03-10 18:47:37 -08001016 return;
1017 }
Kevin Rocarde9a8fb72017-03-21 11:39:55 -07001018 ASSERT_EQ(Result::INVALID_STATE, res);
Kevin Rocard624800c2017-03-10 18:47:37 -08001019}
1020
1021/** Stub implementation of out stream callback. */
1022class MockOutCallbacks : public IStreamOutCallback {
1023 Return<void> onWriteReady() override { return {}; }
1024 Return<void> onDrainReady() override { return {}; }
1025 Return<void> onError() override { return {}; }
1026};
1027
1028static bool isAsyncModeSupported(IStreamOut *stream) {
1029 auto res = stream->setCallback(new MockOutCallbacks);
1030 stream->clearCallback(); // try to restore the no callback state, ignore any error
1031 auto okOrNotSupported = { Result::OK, Result::NOT_SUPPORTED };
1032 EXPECT_RESULT(okOrNotSupported, res);
1033 return res.isOk() ? res == Result::OK : false;
1034}
1035
1036TEST_P(OutputStreamTest, SetCallback) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001037 doc::test("If supported, registering callback for async operation should never fail");
Kevin Rocard624800c2017-03-10 18:47:37 -08001038 if (!isAsyncModeSupported(stream.get())) {
1039 doc::partialTest("The stream does not support async operations");
1040 return;
1041 }
1042 ASSERT_OK(stream->setCallback(new MockOutCallbacks));
1043 ASSERT_OK(stream->setCallback(new MockOutCallbacks));
1044}
1045
1046TEST_P(OutputStreamTest, clearCallback) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001047 doc::test("If supported, clearing a callback to go back to sync operation should not fail");
Kevin Rocard624800c2017-03-10 18:47:37 -08001048 if (!isAsyncModeSupported(stream.get())) {
1049 doc::partialTest("The stream does not support async operations");
1050 return;
1051 }
1052 // TODO: Clarify if clearing a non existing callback should fail
1053 ASSERT_OK(stream->setCallback(new MockOutCallbacks));
1054 ASSERT_OK(stream->clearCallback());
1055}
1056
1057TEST_P(OutputStreamTest, Resume) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001058 doc::test("If supported, a stream should fail to resume if not previously paused");
Kevin Rocard624800c2017-03-10 18:47:37 -08001059 if (!Capability(stream.get()).resume) {
1060 doc::partialTest("The output stream does not support resume");
1061 return;
1062 }
1063 ASSERT_RESULT(Result::INVALID_STATE, stream->resume());
1064}
1065
1066TEST_P(OutputStreamTest, Pause) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001067 doc::test("If supported, a stream should fail to pause if not previously started");
Kevin Rocard624800c2017-03-10 18:47:37 -08001068 if (!Capability(stream.get()).pause) {
1069 doc::partialTest("The output stream does not support pause");
1070 return;
1071 }
1072 ASSERT_RESULT(Result::INVALID_STATE, stream->resume());
1073}
1074
1075static void testDrain(IStreamOut *stream, AudioDrain type) {
1076 if (!Capability(stream).drain) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001077 doc::partialTest("The output stream does not support drain");
Kevin Rocard624800c2017-03-10 18:47:37 -08001078 return;
1079 }
1080 ASSERT_RESULT(Result::OK, stream->drain(type));
1081}
1082
1083TEST_P(OutputStreamTest, DrainAll) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001084 doc::test("If supported, a stream should always succeed to drain");
Kevin Rocard624800c2017-03-10 18:47:37 -08001085 testDrain(stream.get(), AudioDrain::ALL);
1086}
1087
1088TEST_P(OutputStreamTest, DrainEarlyNotify) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001089 doc::test("If supported, a stream should always succeed to drain");
Kevin Rocard624800c2017-03-10 18:47:37 -08001090 testDrain(stream.get(), AudioDrain::EARLY_NOTIFY);
1091}
1092
1093TEST_P(OutputStreamTest, FlushStop) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001094 doc::test("If supported, a stream should always succeed to flush");
Kevin Rocarde9a8fb72017-03-21 11:39:55 -07001095 auto ret = stream->flush();
1096 ASSERT_TRUE(ret.isOk());
1097 if (ret == Result::NOT_SUPPORTED) {
1098 doc::partialTest("Flush is not supported");
1099 return;
1100 }
1101 ASSERT_OK(ret);
Kevin Rocard624800c2017-03-10 18:47:37 -08001102}
1103
1104TEST_P(OutputStreamTest, GetPresentationPositionStop) {
Kevin Rocard6f226802017-04-03 10:29:34 -07001105 doc::test("If supported, a stream should always succeed to retrieve the presentation position");
Kevin Rocard624800c2017-03-10 18:47:37 -08001106 uint64_t frames;
1107 TimeSpec mesureTS;
1108 ASSERT_OK(stream->getPresentationPosition(returnIn(res, frames, mesureTS)));
1109 if (res == Result::NOT_SUPPORTED) {
1110 doc::partialTest("getpresentationPosition is not supported");
1111 return;
1112 }
1113 ASSERT_EQ(0U, frames);
1114
1115 struct timespec currentTS;
1116 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &currentTS)) << errno;
1117
1118 auto toMicroSec = [](uint64_t sec, auto nsec) { return sec * 1e+6 + nsec / 1e+3; };
1119 auto currentTime = toMicroSec(currentTS.tv_sec, currentTS.tv_nsec);
1120 auto mesureTime = toMicroSec(mesureTS.tvSec, mesureTS.tvNSec);
1121 ASSERT_PRED2([](auto c, auto m){ return c - m < 1e+6; }, currentTime, mesureTime);
1122}
1123
1124
1125//////////////////////////////////////////////////////////////////////////////
Kevin Rocard3c405a72017-03-08 16:46:51 -08001126/////////////////////////////// PrimaryDevice ////////////////////////////////
1127//////////////////////////////////////////////////////////////////////////////
1128
Kevin Rocardc9963522017-03-10 18:47:37 -08001129
Kevin Rocard3c405a72017-03-08 16:46:51 -08001130TEST_F(AudioPrimaryHidlTest, setVoiceVolume) {
1131 doc::test("Make sure setVoiceVolume only succeed if volume is in [0,1]");
Kevin Rocardc9963522017-03-10 18:47:37 -08001132 testUnitaryGain([this](float volume) { return device->setVoiceVolume(volume); });
Kevin Rocard3c405a72017-03-08 16:46:51 -08001133}
1134
1135TEST_F(AudioPrimaryHidlTest, setMode) {
1136 doc::test("Make sure setMode always succeeds if mode is valid");
1137 for (AudioMode mode : {AudioMode::IN_CALL, AudioMode::IN_COMMUNICATION,
1138 AudioMode::RINGTONE, AudioMode::CURRENT,
1139 AudioMode::NORMAL /* Make sure to leave the test in normal mode */ }) {
1140 SCOPED_TRACE("mode=" + toString(mode));
1141 ASSERT_OK(device->setMode(mode));
1142 }
1143
1144 // FIXME: Missing api doc. What should the impl do if the mode is invalid ?
Kevin Rocard20e7af62017-03-10 17:10:43 -08001145 ASSERT_RESULT(Result::INVALID_ARGUMENTS, device->setMode(AudioMode::INVALID));
Kevin Rocard3c405a72017-03-08 16:46:51 -08001146}
1147
1148
1149TEST_F(BoolAccessorPrimaryHidlTest, BtScoNrecEnabled) {
1150 doc::test("Query and set the BT SCO NR&EC state");
1151 testOptionalAccessors("BtScoNrecEnabled", {true, false, true},
1152 &IPrimaryDevice::setBtScoNrecEnabled,
1153 &IPrimaryDevice::getBtScoNrecEnabled);
1154}
1155
1156TEST_F(BoolAccessorPrimaryHidlTest, setGetBtScoWidebandEnabled) {
1157 doc::test("Query and set the SCO whideband state");
1158 testOptionalAccessors("BtScoWideband", {true, false, true},
1159 &IPrimaryDevice::setBtScoWidebandEnabled,
1160 &IPrimaryDevice::getBtScoWidebandEnabled);
1161}
1162
1163using TtyModeAccessorPrimaryHidlTest = AccessorPrimaryHidlTest<TtyMode>;
1164TEST_F(TtyModeAccessorPrimaryHidlTest, setGetTtyMode) {
1165 doc::test("Query and set the TTY mode state");
1166 testOptionalAccessors("TTY mode", {TtyMode::OFF, TtyMode::HCO, TtyMode::VCO, TtyMode::FULL},
1167 &IPrimaryDevice::setTtyMode, &IPrimaryDevice::getTtyMode);
1168}
1169
1170TEST_F(BoolAccessorPrimaryHidlTest, setGetHac) {
1171 doc::test("Query and set the HAC state");
1172 testAccessors("HAC", {true, false, true},
1173 &IPrimaryDevice::setHacEnabled,
1174 &IPrimaryDevice::getHacEnabled);
1175}
1176
1177//////////////////////////////////////////////////////////////////////////////
Kevin Rocardf0357882017-02-10 16:19:28 -08001178//////////////////// Clean caches on global tear down ////////////////////////
1179//////////////////////////////////////////////////////////////////////////////
1180
1181int main(int argc, char** argv) {
1182 environment = new Environment;
1183 ::testing::AddGlobalTestEnvironment(environment);
1184 ::testing::InitGoogleTest(&argc, argv);
1185 int status = RUN_ALL_TESTS();
1186 LOG(INFO) << "Test result = " << status;
1187 return status;
1188}