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