• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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 "AudioSystemTest"
18 
19 #include <string.h>
20 
21 #include <set>
22 
23 #include <gtest/gtest.h>
24 #include <log/log.h>
25 #include <media/AidlConversionCppNdk.h>
26 #include <media/IAudioFlinger.h>
27 
28 #include "audio_test_utils.h"
29 
30 using android::media::audio::common::AudioDeviceAddress;
31 using android::media::audio::common::AudioDeviceDescription;
32 using android::media::audio::common::AudioDeviceType;
33 using android::media::audio::common::AudioPortExt;
34 using namespace android;
35 
anyPatchContainsInputDevice(audio_port_handle_t deviceId,bool & res)36 void anyPatchContainsInputDevice(audio_port_handle_t deviceId, bool& res) {
37     std::vector<struct audio_patch> patches;
38     status_t status = listAudioPatches(patches);
39     ASSERT_EQ(OK, status);
40     res = false;
41     for (const auto& patch : patches) {
42         if (patchContainsInputDevice(deviceId, patch)) {
43             res = true;
44             return;
45         }
46     }
47 }
48 
49 class AudioSystemTest : public ::testing::Test {
50   public:
SetUp()51     void SetUp() override {
52         mAF = AudioSystem::get_audio_flinger();
53         ASSERT_NE(mAF, nullptr) << "Permission denied";
54     }
55 
TearDown()56     void TearDown() override {
57         if (mPlayback) {
58             mPlayback->stop();
59             mCbPlayback.clear();
60             mPlayback.clear();
61         }
62         if (mCapture) {
63             mCapture->stop();
64             mCbRecord.clear();
65             mCapture.clear();
66         }
67     }
68 
69     void createPlaybackSession(void);
70     void createRecordSession(void);
71 
72     sp<IAudioFlinger> mAF;
73     sp<AudioPlayback> mPlayback;
74     sp<OnAudioDeviceUpdateNotifier> mCbPlayback;
75     sp<AudioCapture> mCapture;
76     sp<OnAudioDeviceUpdateNotifier> mCbRecord;
77 };
78 
createPlaybackSession(void)79 void AudioSystemTest::createPlaybackSession(void) {
80     audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
81     attributes.usage = AUDIO_USAGE_MEDIA;
82     attributes.content_type = AUDIO_CONTENT_TYPE_MUSIC;
83     mPlayback = sp<AudioPlayback>::make(48000, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
84                                         AUDIO_OUTPUT_FLAG_FAST, AUDIO_SESSION_NONE,
85                                         AudioTrack::TRANSFER_SHARED, &attributes);
86     ASSERT_NE(nullptr, mPlayback);
87     ASSERT_EQ(NO_ERROR, mPlayback->loadResource("/data/local/tmp/bbb_2ch_24kHz_s16le.raw"));
88     EXPECT_EQ(NO_ERROR, mPlayback->create());
89     mCbPlayback = sp<OnAudioDeviceUpdateNotifier>::make();
90     EXPECT_EQ(OK, mPlayback->getAudioTrackHandle()->addAudioDeviceCallback(mCbPlayback));
91     EXPECT_EQ(NO_ERROR, mPlayback->start());
92     EXPECT_EQ(OK, mPlayback->onProcess());
93     EXPECT_EQ(OK, mCbPlayback->waitForAudioDeviceCb());
94 }
95 
createRecordSession(void)96 void AudioSystemTest::createRecordSession(void) {
97     mCapture = new AudioCapture(AUDIO_SOURCE_DEFAULT, 44100, AUDIO_FORMAT_PCM_8_24_BIT,
98                                 AUDIO_CHANNEL_IN_MONO, AUDIO_INPUT_FLAG_FAST);
99     ASSERT_NE(nullptr, mCapture);
100     ASSERT_EQ(OK, mCapture->create()) << "record creation failed";
101     mCbRecord = sp<OnAudioDeviceUpdateNotifier>::make();
102     EXPECT_EQ(OK, mCapture->getAudioRecordHandle()->addAudioDeviceCallback(mCbRecord));
103     EXPECT_EQ(OK, mCapture->start()) << "record creation failed";
104     EXPECT_EQ(OK, mCbRecord->waitForAudioDeviceCb());
105 }
106 
107 // UNIT TESTS
TEST_F(AudioSystemTest,CheckServerSideValues)108 TEST_F(AudioSystemTest, CheckServerSideValues) {
109     ASSERT_NO_FATAL_FAILURE(createPlaybackSession());
110     EXPECT_GT(mAF->sampleRate(mCbPlayback->mAudioIo), 0);
111     EXPECT_NE(mAF->format(mCbPlayback->mAudioIo), AUDIO_FORMAT_INVALID);
112     EXPECT_GT(mAF->frameCount(mCbPlayback->mAudioIo), 0);
113     size_t frameCountHal, frameCountHalCache;
114     frameCountHal = mAF->frameCountHAL(mCbPlayback->mAudioIo);
115     EXPECT_GT(frameCountHal, 0);
116     EXPECT_EQ(OK, AudioSystem::getFrameCountHAL(mCbPlayback->mAudioIo, &frameCountHalCache));
117     EXPECT_EQ(frameCountHal, frameCountHalCache);
118     EXPECT_GT(mAF->latency(mCbPlayback->mAudioIo), 0);
119     // client side latency is at least server side latency
120     EXPECT_LE(mAF->latency(mCbPlayback->mAudioIo), mPlayback->getAudioTrackHandle()->latency());
121 
122     ASSERT_NO_FATAL_FAILURE(createRecordSession());
123     EXPECT_GT(mAF->sampleRate(mCbRecord->mAudioIo), 0);
124     // EXPECT_NE(mAF->format(mCbRecord->mAudioIo), AUDIO_FORMAT_INVALID);
125     EXPECT_GT(mAF->frameCount(mCbRecord->mAudioIo), 0);
126     EXPECT_GT(mAF->frameCountHAL(mCbRecord->mAudioIo), 0);
127     frameCountHal = mAF->frameCountHAL(mCbRecord->mAudioIo);
128     EXPECT_GT(frameCountHal, 0);
129     EXPECT_EQ(OK, AudioSystem::getFrameCountHAL(mCbRecord->mAudioIo, &frameCountHalCache));
130     EXPECT_EQ(frameCountHal, frameCountHalCache);
131     // EXPECT_GT(mAF->latency(mCbRecord->mAudioIo), 0);
132     // client side latency is at least server side latency
133     // EXPECT_LE(mAF->latency(mCbRecord->mAudioIo), mCapture->getAudioRecordHandle()->latency());
134 
135     EXPECT_GT(AudioSystem::getPrimaryOutputSamplingRate(), 0);  // first fast mixer sample rate
136     EXPECT_GT(AudioSystem::getPrimaryOutputFrameCount(), 0);    // fast mixer frame count
137 }
138 
TEST_F(AudioSystemTest,GetSetMasterVolume)139 TEST_F(AudioSystemTest, GetSetMasterVolume) {
140     ASSERT_NO_FATAL_FAILURE(createPlaybackSession());
141     float origVol, tstVol;
142     EXPECT_EQ(NO_ERROR, AudioSystem::getMasterVolume(&origVol));
143     float newVol;
144     if (origVol + 0.2f > 1.0f) {
145         newVol = origVol - 0.2f;
146     } else {
147         newVol = origVol + 0.2f;
148     }
149     EXPECT_EQ(NO_ERROR, AudioSystem::setMasterVolume(newVol));
150     EXPECT_EQ(NO_ERROR, AudioSystem::getMasterVolume(&tstVol));
151     EXPECT_EQ(newVol, tstVol);
152     EXPECT_EQ(NO_ERROR, AudioSystem::setMasterVolume(origVol));
153     EXPECT_EQ(NO_ERROR, AudioSystem::getMasterVolume(&tstVol));
154     EXPECT_EQ(origVol, tstVol);
155 }
156 
TEST_F(AudioSystemTest,GetSetMasterMute)157 TEST_F(AudioSystemTest, GetSetMasterMute) {
158     ASSERT_NO_FATAL_FAILURE(createPlaybackSession());
159     bool origMuteState, tstMuteState;
160     EXPECT_EQ(NO_ERROR, AudioSystem::getMasterMute(&origMuteState));
161     EXPECT_EQ(NO_ERROR, AudioSystem::setMasterMute(!origMuteState));
162     EXPECT_EQ(NO_ERROR, AudioSystem::getMasterMute(&tstMuteState));
163     EXPECT_EQ(!origMuteState, tstMuteState);
164     EXPECT_EQ(NO_ERROR, AudioSystem::setMasterMute(origMuteState));
165     EXPECT_EQ(NO_ERROR, AudioSystem::getMasterMute(&tstMuteState));
166     EXPECT_EQ(origMuteState, tstMuteState);
167 }
168 
TEST_F(AudioSystemTest,GetSetMicMute)169 TEST_F(AudioSystemTest, GetSetMicMute) {
170     ASSERT_NO_FATAL_FAILURE(createPlaybackSession());
171     bool origMuteState, tstMuteState;
172     EXPECT_EQ(NO_ERROR, AudioSystem::isMicrophoneMuted(&origMuteState));
173     EXPECT_EQ(NO_ERROR, AudioSystem::muteMicrophone(!origMuteState));
174     EXPECT_EQ(NO_ERROR, AudioSystem::isMicrophoneMuted(&tstMuteState));
175     EXPECT_EQ(!origMuteState, tstMuteState);
176     EXPECT_EQ(NO_ERROR, AudioSystem::muteMicrophone(origMuteState));
177     EXPECT_EQ(NO_ERROR, AudioSystem::isMicrophoneMuted(&tstMuteState));
178     EXPECT_EQ(origMuteState, tstMuteState);
179 }
180 
TEST_F(AudioSystemTest,GetSetMasterBalance)181 TEST_F(AudioSystemTest, GetSetMasterBalance) {
182     ASSERT_NO_FATAL_FAILURE(createPlaybackSession());
183     float origBalance, tstBalance;
184     EXPECT_EQ(OK, AudioSystem::getMasterBalance(&origBalance));
185     float newBalance;
186     if (origBalance + 0.2f > 1.0f) {
187         newBalance = origBalance - 0.2f;
188     } else {
189         newBalance = origBalance + 0.2f;
190     }
191     EXPECT_EQ(OK, AudioSystem::setMasterBalance(newBalance));
192     EXPECT_EQ(OK, AudioSystem::getMasterBalance(&tstBalance));
193     EXPECT_EQ(newBalance, tstBalance);
194     EXPECT_EQ(OK, AudioSystem::setMasterBalance(origBalance));
195     EXPECT_EQ(OK, AudioSystem::getMasterBalance(&tstBalance));
196     EXPECT_EQ(origBalance, tstBalance);
197 }
198 
TEST_F(AudioSystemTest,GetStreamVolume)199 TEST_F(AudioSystemTest, GetStreamVolume) {
200     ASSERT_NO_FATAL_FAILURE(createPlaybackSession());
201     float origStreamVol;
202     EXPECT_EQ(NO_ERROR, AudioSystem::getStreamVolume(AUDIO_STREAM_MUSIC, &origStreamVol,
203                                                      mCbPlayback->mAudioIo));
204 }
205 
TEST_F(AudioSystemTest,GetStreamMute)206 TEST_F(AudioSystemTest, GetStreamMute) {
207     ASSERT_NO_FATAL_FAILURE(createPlaybackSession());
208     bool origMuteState;
209     EXPECT_EQ(NO_ERROR, AudioSystem::getStreamMute(AUDIO_STREAM_MUSIC, &origMuteState));
210 }
211 
TEST_F(AudioSystemTest,StartAndStopAudioSource)212 TEST_F(AudioSystemTest, StartAndStopAudioSource) {
213     std::vector<struct audio_port_v7> ports;
214     audio_port_config sourcePortConfig;
215     audio_attributes_t attributes = AudioSystem::streamTypeToAttributes(AUDIO_STREAM_MUSIC);
216     audio_port_handle_t sourcePortHandle = AUDIO_PORT_HANDLE_NONE;
217 
218     status_t status = listAudioPorts(ports);
219     ASSERT_EQ(OK, status);
220     if (ports.empty()) {
221         GTEST_SKIP() << "No ports returned by the audio system";
222     }
223 
224     bool sourceFound = false;
225     for (const auto& port : ports) {
226         if (port.role != AUDIO_PORT_ROLE_SOURCE || port.type != AUDIO_PORT_TYPE_DEVICE) continue;
227         if (port.ext.device.type != AUDIO_DEVICE_IN_FM_TUNER) continue;
228         sourceFound = true;
229         sourcePortConfig = port.active_config;
230 
231         bool patchFound;
232 
233         // start audio source.
234         status_t ret =
235                 AudioSystem::startAudioSource(&sourcePortConfig, &attributes, &sourcePortHandle);
236         EXPECT_EQ(OK, ret) << "AudioSystem::startAudioSource for source "
237                            << audio_device_to_string(port.ext.device.type) << " failed";
238         if (ret != OK) continue;
239 
240         // verify that patch is established by the source port.
241         ASSERT_NO_FATAL_FAILURE(anyPatchContainsInputDevice(port.id, patchFound));
242         EXPECT_EQ(true, patchFound);
243         EXPECT_NE(sourcePortHandle, AUDIO_PORT_HANDLE_NONE);
244 
245         if (sourcePortHandle != AUDIO_PORT_HANDLE_NONE) {
246             ret = AudioSystem::stopAudioSource(sourcePortHandle);
247             EXPECT_EQ(OK, ret) << "AudioSystem::stopAudioSource failed for handle "
248                                << sourcePortHandle;
249         }
250 
251         // verify that no source port patch exists.
252         ASSERT_NO_FATAL_FAILURE(anyPatchContainsInputDevice(port.id, patchFound));
253         EXPECT_EQ(false, patchFound);
254     }
255     if (!sourceFound) {
256         GTEST_SKIP() << "No ports suitable for testing";
257     }
258 }
259 
TEST_F(AudioSystemTest,CreateAndReleaseAudioPatch)260 TEST_F(AudioSystemTest, CreateAndReleaseAudioPatch) {
261     status_t status;
262     struct audio_patch audioPatch;
263     std::vector<struct audio_port_v7> ports;
264     audio_patch_handle_t audioPatchHandle = AUDIO_PATCH_HANDLE_NONE;
265 
266     bool patchFound = false;
267     audio_port_v7 sourcePort{};
268     audio_port_v7 sinkPort{};
269 
270     audioPatch.id = 0;
271     audioPatch.num_sources = 1;
272     audioPatch.num_sinks = 1;
273 
274     status = listAudioPorts(ports);
275     ASSERT_EQ(OK, status);
276     if (ports.empty()) {
277         GTEST_SKIP() << "No output devices returned by the audio system";
278     }
279 
280     bool sourceFound = false, sinkFound = false;
281     for (const auto& port : ports) {
282         if (port.role == AUDIO_PORT_ROLE_SOURCE && port.type == AUDIO_PORT_TYPE_DEVICE) {
283             sourcePort = port;
284             sourceFound = true;
285         }
286         if (port.role == AUDIO_PORT_ROLE_SINK && port.type == AUDIO_PORT_TYPE_DEVICE &&
287             port.ext.device.type == AUDIO_DEVICE_OUT_SPEAKER) {
288             sinkPort = port;
289             sinkFound = true;
290         }
291         if (sourceFound && sinkFound) break;
292     }
293     if (!sourceFound || !sinkFound) {
294         GTEST_SKIP() << "No ports suitable for testing";
295     }
296 
297     audioPatch.sources[0] = sourcePort.active_config;
298     audioPatch.sinks[0] = sinkPort.active_config;
299 
300     status = AudioSystem::createAudioPatch(&audioPatch, &audioPatchHandle);
301     EXPECT_EQ(OK, status) << "AudioSystem::createAudioPatch failed between source "
302                           << audio_device_to_string(sourcePort.ext.device.type) << " and sink "
303                           << audio_device_to_string(sinkPort.ext.device.type);
304 
305     // verify that patch is established between source and the sink.
306     ASSERT_NO_FATAL_FAILURE(anyPatchContainsInputDevice(sourcePort.id, patchFound));
307     EXPECT_EQ(true, patchFound);
308 
309     EXPECT_NE(AUDIO_PORT_HANDLE_NONE, audioPatchHandle);
310     status = AudioSystem::releaseAudioPatch(audioPatchHandle);
311     EXPECT_EQ(OK, status) << "AudioSystem::releaseAudioPatch failed between source "
312                           << audio_device_to_string(sourcePort.ext.device.type) << " and sink "
313                           << audio_device_to_string(sinkPort.ext.device.type);
314 
315     // verify that no patch is established between source and the sink after releaseAudioPatch.
316     ASSERT_NO_FATAL_FAILURE(anyPatchContainsInputDevice(sourcePort.id, patchFound));
317     EXPECT_EQ(false, patchFound);
318 }
319 
TEST_F(AudioSystemTest,GetAudioPort)320 TEST_F(AudioSystemTest, GetAudioPort) {
321     std::vector<struct audio_port_v7> ports;
322     status_t status = listAudioPorts(ports);
323     ASSERT_EQ(OK, status);
324     for (const auto& port : ports) {
325         audio_port_v7 portTest{.id = port.id};
326         EXPECT_EQ(OK, AudioSystem::getAudioPort(&portTest));
327         EXPECT_TRUE(audio_ports_v7_are_equal(&portTest, &port));
328     }
329 }
330 
TEST_F(AudioSystemTest,TestPhoneState)331 TEST_F(AudioSystemTest, TestPhoneState) {
332     uid_t uid = getuid();
333     EXPECT_EQ(OK, AudioSystem::setPhoneState(AUDIO_MODE_RINGTONE, uid));
334     audio_mode_t state = AudioSystem::getPhoneState();
335     EXPECT_EQ(AUDIO_MODE_RINGTONE, state);
336     EXPECT_EQ(OK, AudioSystem::setPhoneState(AUDIO_MODE_IN_COMMUNICATION, uid));
337     state = AudioSystem::getPhoneState();
338     EXPECT_EQ(AUDIO_MODE_IN_COMMUNICATION, state);
339     EXPECT_EQ(OK, AudioSystem::setPhoneState(AUDIO_MODE_NORMAL, uid));
340     state = AudioSystem::getPhoneState();
341     EXPECT_EQ(AUDIO_MODE_NORMAL, state);
342 }
343 
TEST_F(AudioSystemTest,GetDirectProfilesForAttributes)344 TEST_F(AudioSystemTest, GetDirectProfilesForAttributes) {
345     std::vector<audio_profile> audioProfiles;
346     audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
347     attributes.usage = AUDIO_USAGE_MEDIA;
348     attributes.content_type = AUDIO_CONTENT_TYPE_MUSIC;
349     EXPECT_EQ(BAD_VALUE, AudioSystem::getDirectProfilesForAttributes(nullptr, nullptr));
350     EXPECT_EQ(BAD_VALUE, AudioSystem::getDirectProfilesForAttributes(nullptr, &audioProfiles));
351     EXPECT_EQ(BAD_VALUE, AudioSystem::getDirectProfilesForAttributes(&attributes, nullptr));
352     EXPECT_EQ(NO_ERROR, AudioSystem::getDirectProfilesForAttributes(&attributes, &audioProfiles));
353 }
354 
isPublicStrategy(const AudioProductStrategy & strategy)355 bool isPublicStrategy(const AudioProductStrategy& strategy) {
356     bool result = true;
357     for (auto& attribute : strategy.getVolumeGroupAttributes()) {
358         if (attribute.getAttributes() == AUDIO_ATTRIBUTES_INITIALIZER &&
359             (uint32_t(attribute.getStreamType()) >= AUDIO_STREAM_PUBLIC_CNT)) {
360             result = false;
361             break;
362         }
363     }
364     return result;
365 }
366 
TEST_F(AudioSystemTest,DevicesForRoleAndStrategy)367 TEST_F(AudioSystemTest, DevicesForRoleAndStrategy) {
368     std::vector<struct audio_port_v7> ports;
369     status_t status = listAudioPorts(ports);
370     ASSERT_EQ(OK, status);
371 
372     std::vector<struct audio_port_v7> devicePorts;
373     for (const auto& port : ports) {
374         if (port.type == AUDIO_PORT_TYPE_DEVICE && audio_is_output_device(port.ext.device.type)) {
375             devicePorts.push_back(port);
376         }
377     }
378     if (devicePorts.empty()) {
379         GTEST_SKIP() << "No output devices returned by the audio system";
380     }
381 
382     AudioProductStrategyVector strategies;
383     EXPECT_EQ(OK, AudioSystem::listAudioProductStrategies(strategies));
384     if (strategies.empty()) {
385         GTEST_SKIP() << "No strategies returned by the audio system";
386     }
387 
388     audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
389     attributes.usage = AUDIO_USAGE_MEDIA;
390 
391     bool hasStrategyForMedia = false;
392     AudioProductStrategy mediaStrategy;
393     for (const auto& strategy : strategies) {
394         if (!isPublicStrategy(strategy)) continue;
395 
396         for (const auto& att : strategy.getVolumeGroupAttributes()) {
397             if (strategy.attributesMatches(att.getAttributes(), attributes)) {
398                 hasStrategyForMedia = true;
399                 mediaStrategy = strategy;
400                 break;
401             }
402         }
403     }
404 
405     if (!hasStrategyForMedia) {
406         GTEST_SKIP() << "No strategies returned for music media";
407     }
408 
409     AudioDeviceTypeAddrVector devices;
410     EXPECT_EQ(BAD_VALUE, AudioSystem::getDevicesForRoleAndStrategy(PRODUCT_STRATEGY_NONE,
411                                                                    DEVICE_ROLE_PREFERRED, devices));
412     EXPECT_EQ(BAD_VALUE, AudioSystem::getDevicesForRoleAndStrategy(mediaStrategy.getId(),
413                                                                    DEVICE_ROLE_NONE, devices));
414     status = AudioSystem::getDevicesForRoleAndStrategy(mediaStrategy.getId(), DEVICE_ROLE_PREFERRED,
415                                                        devices);
416     if (status == NAME_NOT_FOUND) {
417         AudioDeviceTypeAddrVector outputDevices;
418         for (const auto& port : devicePorts) {
419             if (port.ext.device.type == AUDIO_DEVICE_OUT_SPEAKER) {
420                 const AudioDeviceTypeAddr outputDevice(port.ext.device.type,
421                                                        port.ext.device.address);
422                 outputDevices.push_back(outputDevice);
423             }
424         }
425         EXPECT_EQ(OK, AudioSystem::setDevicesRoleForStrategy(mediaStrategy.getId(),
426                                                              DEVICE_ROLE_PREFERRED, outputDevices));
427         EXPECT_EQ(OK, AudioSystem::getDevicesForRoleAndStrategy(mediaStrategy.getId(),
428                                                                 DEVICE_ROLE_PREFERRED, devices));
429         EXPECT_EQ(devices, outputDevices);
430         EXPECT_EQ(OK, AudioSystem::clearDevicesRoleForStrategy(mediaStrategy.getId(),
431                                                                DEVICE_ROLE_PREFERRED));
432         EXPECT_EQ(NAME_NOT_FOUND, AudioSystem::getDevicesForRoleAndStrategy(
433                                           mediaStrategy.getId(), DEVICE_ROLE_PREFERRED, devices));
434     }
435 }
436 
TEST_F(AudioSystemTest,VolumeIndexForAttributes)437 TEST_F(AudioSystemTest, VolumeIndexForAttributes) {
438     AudioVolumeGroupVector groups;
439     EXPECT_EQ(OK, AudioSystem::listAudioVolumeGroups(groups));
440     for (const auto& group : groups) {
441         if (group.getAudioAttributes().empty()) continue;
442         const audio_attributes_t attr = group.getAudioAttributes()[0];
443         if (attr == AUDIO_ATTRIBUTES_INITIALIZER) continue;
444         audio_stream_type_t streamType = AudioSystem::attributesToStreamType(attr);
445         if (streamType >= AUDIO_STREAM_PUBLIC_CNT) continue;
446 
447         volume_group_t vg;
448         EXPECT_EQ(OK, AudioSystem::getVolumeGroupFromAudioAttributes(attr, vg));
449         EXPECT_EQ(group.getId(), vg);
450 
451         int index;
452         EXPECT_EQ(OK,
453                   AudioSystem::getVolumeIndexForAttributes(attr, index, AUDIO_DEVICE_OUT_SPEAKER));
454 
455         int indexTest;
456         EXPECT_EQ(OK, AudioSystem::getStreamVolumeIndex(streamType, &indexTest,
457                                                         AUDIO_DEVICE_OUT_SPEAKER));
458         EXPECT_EQ(index, indexTest);
459     }
460 }
461 
TEST_F(AudioSystemTest,DevicesRoleForCapturePreset)462 TEST_F(AudioSystemTest, DevicesRoleForCapturePreset) {
463     std::vector<struct audio_port_v7> ports;
464     status_t status = listAudioPorts(ports);
465     ASSERT_EQ(OK, status);
466 
467     if (ports.empty()) {
468         GTEST_SKIP() << "No ports returned by the audio system";
469     }
470 
471     audio_devices_t inDeviceA = AUDIO_DEVICE_IN_BUILTIN_MIC;
472     audio_devices_t inDeviceB = AUDIO_DEVICE_IN_BUILTIN_MIC;
473     for (const auto& port : ports) {
474         if (port.role != AUDIO_PORT_ROLE_SOURCE || port.type != AUDIO_PORT_TYPE_DEVICE) continue;
475         if (port.ext.device.type == inDeviceA) continue;
476         inDeviceB = port.ext.device.type;
477         break;
478     }
479     const audio_source_t audioSource = AUDIO_SOURCE_MIC;
480     const device_role_t role = DEVICE_ROLE_PREFERRED;
481     const AudioDeviceTypeAddr inputDevice(inDeviceA, "");
482     const AudioDeviceTypeAddrVector inputDevices = {inputDevice};
483     const AudioDeviceTypeAddr outputDevice(AUDIO_DEVICE_OUT_SPEAKER, "");
484     const AudioDeviceTypeAddrVector outputDevices = {outputDevice};
485 
486     // Test invalid device when setting
487     EXPECT_EQ(BAD_VALUE,
488               AudioSystem::setDevicesRoleForCapturePreset(audioSource, role, outputDevices));
489     EXPECT_EQ(BAD_VALUE,
490               AudioSystem::addDevicesRoleForCapturePreset(audioSource, role, outputDevices));
491     EXPECT_EQ(BAD_VALUE,
492               AudioSystem::removeDevicesRoleForCapturePreset(audioSource, role, outputDevices));
493 
494     // Test invalid role
495     AudioDeviceTypeAddrVector devices;
496     EXPECT_EQ(BAD_VALUE, AudioSystem::getDevicesForRoleAndCapturePreset(audioSource,
497                                                                         DEVICE_ROLE_NONE, devices));
498     EXPECT_EQ(BAD_VALUE, AudioSystem::setDevicesRoleForCapturePreset(audioSource, DEVICE_ROLE_NONE,
499                                                                      inputDevices));
500     EXPECT_EQ(BAD_VALUE, AudioSystem::addDevicesRoleForCapturePreset(audioSource, DEVICE_ROLE_NONE,
501                                                                      inputDevices));
502     EXPECT_EQ(BAD_VALUE, AudioSystem::removeDevicesRoleForCapturePreset(
503                                  audioSource, DEVICE_ROLE_NONE, inputDevices));
504     EXPECT_EQ(BAD_VALUE,
505               AudioSystem::clearDevicesRoleForCapturePreset(audioSource, DEVICE_ROLE_NONE));
506 
507     // Without setting, call get/remove/clear must fail
508     EXPECT_EQ(NAME_NOT_FOUND,
509               AudioSystem::getDevicesForRoleAndCapturePreset(audioSource, role, devices));
510     EXPECT_TRUE(devices.empty());
511     EXPECT_EQ(NAME_NOT_FOUND,
512               AudioSystem::removeDevicesRoleForCapturePreset(audioSource, role, devices));
513     EXPECT_EQ(NAME_NOT_FOUND, AudioSystem::clearDevicesRoleForCapturePreset(audioSource, role));
514 
515     // Test set/get devices role
516     EXPECT_EQ(NO_ERROR,
517               AudioSystem::setDevicesRoleForCapturePreset(audioSource, role, inputDevices));
518     ASSERT_EQ(NO_ERROR, AudioSystem::getDevicesForRoleAndCapturePreset(audioSource, role, devices));
519     EXPECT_EQ(devices, inputDevices);
520 
521     // Test setting will change the previously set devices
522     const AudioDeviceTypeAddr inputDevice2 = AudioDeviceTypeAddr(inDeviceB, "");
523     AudioDeviceTypeAddrVector inputDevices2 = {inputDevice2};
524     EXPECT_EQ(NO_ERROR,
525               AudioSystem::setDevicesRoleForCapturePreset(audioSource, role, inputDevices2));
526     devices.clear();
527     EXPECT_EQ(NO_ERROR, AudioSystem::getDevicesForRoleAndCapturePreset(audioSource, role, devices));
528     EXPECT_EQ(devices, inputDevices2);
529 
530     // Test add devices
531     EXPECT_EQ(NO_ERROR,
532               AudioSystem::addDevicesRoleForCapturePreset(audioSource, role, inputDevices));
533     devices.clear();
534     EXPECT_EQ(NO_ERROR, AudioSystem::getDevicesForRoleAndCapturePreset(audioSource, role, devices));
535     EXPECT_EQ(2, devices.size());
536     EXPECT_TRUE(std::find(devices.begin(), devices.end(), inputDevice) != devices.end());
537     EXPECT_TRUE(std::find(devices.begin(), devices.end(), inputDevice2) != devices.end());
538 
539     // Test remove devices
540     EXPECT_EQ(NO_ERROR,
541               AudioSystem::removeDevicesRoleForCapturePreset(audioSource, role, inputDevices));
542     devices.clear();
543     EXPECT_EQ(NO_ERROR, AudioSystem::getDevicesForRoleAndCapturePreset(audioSource, role, devices));
544     EXPECT_EQ(devices, inputDevices2);
545 
546     // Test remove devices that are not set as the device role
547     EXPECT_EQ(BAD_VALUE,
548               AudioSystem::removeDevicesRoleForCapturePreset(audioSource, role, inputDevices));
549 
550     // Test clear devices
551     EXPECT_EQ(NO_ERROR, AudioSystem::clearDevicesRoleForCapturePreset(audioSource, role));
552     devices.clear();
553     EXPECT_EQ(NAME_NOT_FOUND,
554               AudioSystem::getDevicesForRoleAndCapturePreset(audioSource, role, devices));
555 
556     AudioDeviceTypeAddrVector inputDevices3 = {inputDevice, inputDevice2};
557     EXPECT_EQ(NO_ERROR,
558               AudioSystem::setDevicesRoleForCapturePreset(audioSource, role, inputDevices3));
559     devices.clear();
560     EXPECT_EQ(NO_ERROR, AudioSystem::getDevicesForRoleAndCapturePreset(audioSource, role, devices));
561     EXPECT_EQ(2, devices.size());
562     EXPECT_TRUE(std::find(devices.begin(), devices.end(), inputDevice) != devices.end());
563     EXPECT_TRUE(std::find(devices.begin(), devices.end(), inputDevice2) != devices.end());
564     EXPECT_EQ(NO_ERROR, AudioSystem::clearDevicesRoleForCapturePreset(audioSource, role));
565 }
566 
TEST_F(AudioSystemTest,UidDeviceAffinities)567 TEST_F(AudioSystemTest, UidDeviceAffinities) {
568     uid_t uid = getuid();
569 
570     // Test invalid device for example audio_is_input_device
571     AudioDeviceTypeAddr inputDevice(AUDIO_DEVICE_IN_BUILTIN_MIC, "");
572     AudioDeviceTypeAddrVector inputDevices = {inputDevice};
573     EXPECT_EQ(BAD_VALUE, AudioSystem::setUidDeviceAffinities(uid, inputDevices));
574 
575     // Test valid device for example audio_is_output_device
576     AudioDeviceTypeAddr outputDevice(AUDIO_DEVICE_OUT_SPEAKER, "");
577     AudioDeviceTypeAddrVector outputDevices = {outputDevice};
578     EXPECT_EQ(NO_ERROR, AudioSystem::setUidDeviceAffinities(uid, outputDevices));
579     EXPECT_EQ(NO_ERROR, AudioSystem::removeUidDeviceAffinities(uid));
580 }
581 
TEST_F(AudioSystemTest,UserIdDeviceAffinities)582 TEST_F(AudioSystemTest, UserIdDeviceAffinities) {
583     int userId = 200;
584 
585     // Test invalid device for example audio_is_input_device
586     AudioDeviceTypeAddr inputDevice(AUDIO_DEVICE_IN_BUILTIN_MIC, "");
587     AudioDeviceTypeAddrVector inputDevices = {inputDevice};
588     EXPECT_EQ(BAD_VALUE, AudioSystem::setUserIdDeviceAffinities(userId, inputDevices));
589 
590     // Test valid device for ezample audio_is_output_device
591     AudioDeviceTypeAddr outputDevice(AUDIO_DEVICE_OUT_SPEAKER, "");
592     AudioDeviceTypeAddrVector outputDevices = {outputDevice};
593     EXPECT_EQ(NO_ERROR, AudioSystem::setUserIdDeviceAffinities(userId, outputDevices));
594     EXPECT_EQ(NO_ERROR, AudioSystem::removeUserIdDeviceAffinities(userId));
595 }
596 
597 namespace {
598 
599 class WithSimulatedDeviceConnections {
600   public:
WithSimulatedDeviceConnections()601     WithSimulatedDeviceConnections()
602         : mIsSupported(AudioSystem::setSimulateDeviceConnections(true) == OK) {}
~WithSimulatedDeviceConnections()603     ~WithSimulatedDeviceConnections() {
604         if (mIsSupported) {
605             if (status_t status = AudioSystem::setSimulateDeviceConnections(false); status != OK) {
606                 ALOGE("Error restoring device connections simulation state: %d", status);
607             }
608         }
609     }
isSupported() const610     bool isSupported() const { return mIsSupported; }
611 
612   private:
613     const bool mIsSupported;
614 };
615 
GenerateUniqueDeviceAddress(const android::media::audio::common::AudioPort & port)616 android::media::audio::common::AudioPort GenerateUniqueDeviceAddress(
617         const android::media::audio::common::AudioPort& port) {
618     // Point-to-point connections do not use addresses.
619     static const std::set<std::string> kPointToPointConnections = {
620             AudioDeviceDescription::CONNECTION_ANALOG(), AudioDeviceDescription::CONNECTION_HDMI(),
621             AudioDeviceDescription::CONNECTION_HDMI_ARC(),
622             AudioDeviceDescription::CONNECTION_HDMI_EARC(),
623             AudioDeviceDescription::CONNECTION_SPDIF()};
624     static int nextId = 0;
625     using Tag = AudioDeviceAddress::Tag;
626     const auto& deviceDescription = port.ext.get<AudioPortExt::Tag::device>().device.type;
627     AudioDeviceAddress address;
628     if (kPointToPointConnections.count(deviceDescription.connection) == 0) {
629         switch (suggestDeviceAddressTag(deviceDescription)) {
630             case Tag::id:
631                 address = AudioDeviceAddress::make<Tag::id>(std::to_string(++nextId));
632                 break;
633             case Tag::mac:
634                 address = AudioDeviceAddress::make<Tag::mac>(
635                         std::vector<uint8_t>{1, 2, 3, 4, 5, static_cast<uint8_t>(++nextId & 0xff)});
636                 break;
637             case Tag::ipv4:
638                 address = AudioDeviceAddress::make<Tag::ipv4>(
639                         std::vector<uint8_t>{192, 168, 0, static_cast<uint8_t>(++nextId & 0xff)});
640                 break;
641             case Tag::ipv6:
642                 address = AudioDeviceAddress::make<Tag::ipv6>(std::vector<int32_t>{
643                         0xfc00, 0x0123, 0x4567, 0x89ab, 0xcdef, 0, 0, ++nextId & 0xffff});
644                 break;
645             case Tag::alsa:
646                 address = AudioDeviceAddress::make<Tag::alsa>(std::vector<int32_t>{1, ++nextId});
647                 break;
648         }
649     }
650     android::media::audio::common::AudioPort result = port;
651     result.ext.get<AudioPortExt::Tag::device>().device.address = std::move(address);
652     return result;
653 }
654 
655 }  // namespace
656 
TEST_F(AudioSystemTest,SetDeviceConnectedState)657 TEST_F(AudioSystemTest, SetDeviceConnectedState) {
658     WithSimulatedDeviceConnections connSim;
659     if (!connSim.isSupported()) {
660         GTEST_SKIP() << "Simulation of external device connections not supported";
661     }
662     std::vector<media::AudioPortFw> ports;
663     ASSERT_EQ(OK, AudioSystem::listDeclaredDevicePorts(media::AudioPortRole::NONE, &ports));
664     if (ports.empty()) {
665         GTEST_SKIP() << "No ports returned by the audio system";
666     }
667     const std::set<AudioDeviceType> typesToUse{
668             AudioDeviceType::IN_DEVICE,       AudioDeviceType::IN_HEADSET,
669             AudioDeviceType::IN_MICROPHONE,   AudioDeviceType::OUT_DEVICE,
670             AudioDeviceType::OUT_HEADPHONE,   AudioDeviceType::OUT_HEADSET,
671             AudioDeviceType::OUT_HEARING_AID, AudioDeviceType::OUT_SPEAKER};
672     std::vector<media::AudioPortFw> externalDevicePorts;
673     for (const auto& port : ports) {
674         if (const auto& device = port.hal.ext.get<AudioPortExt::device>().device;
675             !device.type.connection.empty() && typesToUse.count(device.type.type)) {
676             externalDevicePorts.push_back(port);
677         }
678     }
679     if (externalDevicePorts.empty()) {
680         GTEST_SKIP() << "No ports for considered non-attached devices";
681     }
682     for (auto& port : externalDevicePorts) {
683         android::media::audio::common::AudioPort aidlPort = GenerateUniqueDeviceAddress(port.hal);
684         SCOPED_TRACE(aidlPort.toString());
685         audio_devices_t type;
686         char address[AUDIO_DEVICE_MAX_ADDRESS_LEN];
687         status_t status = aidl2legacy_AudioDevice_audio_device(
688                 aidlPort.ext.get<AudioPortExt::Tag::device>().device, &type, address);
689         ASSERT_EQ(OK, status);
690         audio_policy_dev_state_t deviceState = AudioSystem::getDeviceConnectionState(type, address);
691         EXPECT_EQ(AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, deviceState);
692         if (deviceState != AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) continue;
693         // !!! Instead of the default format, use each format from 'ext.encodedFormats'
694         // !!! if they are not empty
695         status = AudioSystem::setDeviceConnectionState(AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
696                                                        aidlPort, AUDIO_FORMAT_DEFAULT);
697         EXPECT_EQ(OK, status);
698         if (status != OK) continue;
699         deviceState = AudioSystem::getDeviceConnectionState(type, address);
700         EXPECT_EQ(AUDIO_POLICY_DEVICE_STATE_AVAILABLE, deviceState);
701         status = AudioSystem::setDeviceConnectionState(AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
702                                                        aidlPort, AUDIO_FORMAT_DEFAULT);
703         EXPECT_EQ(OK, status);
704         deviceState = AudioSystem::getDeviceConnectionState(type, address);
705         EXPECT_EQ(AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, deviceState);
706     }
707 }
708 
709 class TestExecutionTracer : public ::testing::EmptyTestEventListener {
710   public:
OnTestStart(const::testing::TestInfo & test_info)711     void OnTestStart(const ::testing::TestInfo& test_info) override {
712         TraceTestState("Started", test_info);
713     }
OnTestEnd(const::testing::TestInfo & test_info)714     void OnTestEnd(const ::testing::TestInfo& test_info) override {
715         TraceTestState("Completed", test_info);
716     }
717 
718   private:
TraceTestState(const std::string & state,const::testing::TestInfo & test_info)719     static void TraceTestState(const std::string& state, const ::testing::TestInfo& test_info) {
720         ALOGI("%s %s::%s", state.c_str(), test_info.test_suite_name(), test_info.name());
721     }
722 };
723 
main(int argc,char ** argv)724 int main(int argc, char** argv) {
725     ::testing::InitGoogleTest(&argc, argv);
726     ::testing::UnitTest::GetInstance()->listeners().Append(new TestExecutionTracer());
727     return RUN_ALL_TESTS();
728 }
729