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