• 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 #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         if (outputDevices.empty()) {
416             GTEST_SKIP() << "No speaker device found";
417         }
418         EXPECT_EQ(OK, AudioSystem::setDevicesRoleForStrategy(mediaStrategy.getId(),
419                                                              DEVICE_ROLE_PREFERRED, outputDevices));
420         EXPECT_EQ(OK, AudioSystem::getDevicesForRoleAndStrategy(mediaStrategy.getId(),
421                                                                 DEVICE_ROLE_PREFERRED, devices));
422         EXPECT_EQ(devices, outputDevices);
423         EXPECT_EQ(OK, AudioSystem::clearDevicesRoleForStrategy(mediaStrategy.getId(),
424                                                                DEVICE_ROLE_PREFERRED));
425         EXPECT_EQ(NAME_NOT_FOUND, AudioSystem::getDevicesForRoleAndStrategy(
426                                           mediaStrategy.getId(), DEVICE_ROLE_PREFERRED, devices));
427     }
428 }
429 
TEST_F(AudioSystemTest,VolumeIndexForAttributes)430 TEST_F(AudioSystemTest, VolumeIndexForAttributes) {
431     std::optional<audio_port_v7> speakerPort = audio_port_v7{};
432     if (getPortByAttributes(AUDIO_PORT_ROLE_SINK, AUDIO_PORT_TYPE_DEVICE, AUDIO_DEVICE_OUT_SPEAKER,
433                             "", *speakerPort) != OK) {
434         speakerPort.reset();
435     }
436     AudioVolumeGroupVector groups;
437     ASSERT_EQ(OK, AudioSystem::listAudioVolumeGroups(groups));
438     for (const auto& group : groups) {
439         if (group.getAudioAttributes().empty()) continue;
440         const audio_attributes_t attr = group.getAudioAttributes()[0];
441         if (attr == AUDIO_ATTRIBUTES_INITIALIZER) continue;
442         audio_stream_type_t streamType = AudioSystem::attributesToStreamType(attr);
443         if (streamType >= AUDIO_STREAM_PUBLIC_CNT) continue;
444 
445         volume_group_t vg;
446         EXPECT_EQ(OK, AudioSystem::getVolumeGroupFromAudioAttributes(attr, vg));
447         EXPECT_EQ(group.getId(), vg);
448 
449         if (speakerPort.has_value()) {
450             int index;
451             EXPECT_EQ(OK, AudioSystem::getVolumeIndexForAttributes(attr, index,
452                                                                    speakerPort->ext.device.type));
453             int indexTest;
454             EXPECT_EQ(OK, AudioSystem::getStreamVolumeIndex(streamType, &indexTest,
455                                                             speakerPort->ext.device.type));
456             EXPECT_EQ(index, indexTest);
457         }
458     }
459 }
460 
TEST_F(AudioSystemTest,DevicesRoleForCapturePreset)461 TEST_F(AudioSystemTest, DevicesRoleForCapturePreset) {
462     std::vector<struct audio_port_v7> ports;
463     status_t status = listAudioPorts(ports);
464     ASSERT_EQ(OK, status);
465 
466     if (ports.empty()) {
467         GTEST_SKIP() << "No ports returned by the audio system";
468     }
469 
470     audio_devices_t inDeviceA = AUDIO_DEVICE_IN_BUILTIN_MIC;
471     audio_devices_t inDeviceB = AUDIO_DEVICE_IN_BUILTIN_MIC;
472     for (const auto& port : ports) {
473         if (port.role != AUDIO_PORT_ROLE_SOURCE || port.type != AUDIO_PORT_TYPE_DEVICE) continue;
474         if (port.ext.device.type == inDeviceA) continue;
475         inDeviceB = port.ext.device.type;
476         break;
477     }
478     const audio_source_t audioSource = AUDIO_SOURCE_MIC;
479     const device_role_t role = DEVICE_ROLE_PREFERRED;
480     const AudioDeviceTypeAddr inputDevice(inDeviceA, "");
481     const AudioDeviceTypeAddrVector inputDevices = {inputDevice};
482     const AudioDeviceTypeAddr outputDevice(AUDIO_DEVICE_OUT_SPEAKER, "");
483     const AudioDeviceTypeAddrVector outputDevices = {outputDevice};
484 
485     // Test invalid device when setting
486     EXPECT_EQ(BAD_VALUE,
487               AudioSystem::setDevicesRoleForCapturePreset(audioSource, role, outputDevices));
488     EXPECT_EQ(BAD_VALUE,
489               AudioSystem::addDevicesRoleForCapturePreset(audioSource, role, outputDevices));
490     EXPECT_EQ(BAD_VALUE,
491               AudioSystem::removeDevicesRoleForCapturePreset(audioSource, role, outputDevices));
492 
493     // Test invalid role
494     AudioDeviceTypeAddrVector devices;
495     EXPECT_EQ(BAD_VALUE, AudioSystem::getDevicesForRoleAndCapturePreset(audioSource,
496                                                                         DEVICE_ROLE_NONE, devices));
497     EXPECT_EQ(BAD_VALUE, AudioSystem::setDevicesRoleForCapturePreset(audioSource, DEVICE_ROLE_NONE,
498                                                                      inputDevices));
499     EXPECT_EQ(BAD_VALUE, AudioSystem::addDevicesRoleForCapturePreset(audioSource, DEVICE_ROLE_NONE,
500                                                                      inputDevices));
501     EXPECT_EQ(BAD_VALUE, AudioSystem::removeDevicesRoleForCapturePreset(
502                                  audioSource, DEVICE_ROLE_NONE, inputDevices));
503     EXPECT_EQ(BAD_VALUE,
504               AudioSystem::clearDevicesRoleForCapturePreset(audioSource, DEVICE_ROLE_NONE));
505 
506     // Without setting, call get/remove/clear must fail
507     EXPECT_EQ(NAME_NOT_FOUND,
508               AudioSystem::getDevicesForRoleAndCapturePreset(audioSource, role, devices));
509     EXPECT_TRUE(devices.empty());
510     EXPECT_EQ(NAME_NOT_FOUND,
511               AudioSystem::removeDevicesRoleForCapturePreset(audioSource, role, devices));
512     EXPECT_EQ(NAME_NOT_FOUND, AudioSystem::clearDevicesRoleForCapturePreset(audioSource, role));
513 
514     // Test set/get devices role
515     EXPECT_EQ(NO_ERROR,
516               AudioSystem::setDevicesRoleForCapturePreset(audioSource, role, inputDevices));
517     ASSERT_EQ(NO_ERROR, AudioSystem::getDevicesForRoleAndCapturePreset(audioSource, role, devices));
518     EXPECT_EQ(devices, inputDevices);
519 
520     // Test setting will change the previously set devices
521     const AudioDeviceTypeAddr inputDevice2 = AudioDeviceTypeAddr(inDeviceB, "");
522     AudioDeviceTypeAddrVector inputDevices2 = {inputDevice2};
523     EXPECT_EQ(NO_ERROR,
524               AudioSystem::setDevicesRoleForCapturePreset(audioSource, role, inputDevices2));
525     devices.clear();
526     EXPECT_EQ(NO_ERROR, AudioSystem::getDevicesForRoleAndCapturePreset(audioSource, role, devices));
527     EXPECT_EQ(devices, inputDevices2);
528 
529     // Test add devices
530     EXPECT_EQ(NO_ERROR,
531               AudioSystem::addDevicesRoleForCapturePreset(audioSource, role, inputDevices));
532     devices.clear();
533     EXPECT_EQ(NO_ERROR, AudioSystem::getDevicesForRoleAndCapturePreset(audioSource, role, devices));
534     EXPECT_EQ(2, devices.size());
535     EXPECT_TRUE(std::find(devices.begin(), devices.end(), inputDevice) != devices.end());
536     EXPECT_TRUE(std::find(devices.begin(), devices.end(), inputDevice2) != devices.end());
537 
538     // Test remove devices
539     EXPECT_EQ(NO_ERROR,
540               AudioSystem::removeDevicesRoleForCapturePreset(audioSource, role, inputDevices));
541     devices.clear();
542     EXPECT_EQ(NO_ERROR, AudioSystem::getDevicesForRoleAndCapturePreset(audioSource, role, devices));
543     EXPECT_EQ(devices, inputDevices2);
544 
545     // Test remove devices that are not set as the device role
546     EXPECT_EQ(BAD_VALUE,
547               AudioSystem::removeDevicesRoleForCapturePreset(audioSource, role, inputDevices));
548 
549     // Test clear devices
550     EXPECT_EQ(NO_ERROR, AudioSystem::clearDevicesRoleForCapturePreset(audioSource, role));
551     devices.clear();
552     EXPECT_EQ(NAME_NOT_FOUND,
553               AudioSystem::getDevicesForRoleAndCapturePreset(audioSource, role, devices));
554 
555     AudioDeviceTypeAddrVector inputDevices3 = {inputDevice, inputDevice2};
556     EXPECT_EQ(NO_ERROR,
557               AudioSystem::setDevicesRoleForCapturePreset(audioSource, role, inputDevices3));
558     devices.clear();
559     EXPECT_EQ(NO_ERROR, AudioSystem::getDevicesForRoleAndCapturePreset(audioSource, role, devices));
560     EXPECT_EQ(2, devices.size());
561     EXPECT_TRUE(std::find(devices.begin(), devices.end(), inputDevice) != devices.end());
562     EXPECT_TRUE(std::find(devices.begin(), devices.end(), inputDevice2) != devices.end());
563     EXPECT_EQ(NO_ERROR, AudioSystem::clearDevicesRoleForCapturePreset(audioSource, role));
564 }
565 
TEST_F(AudioSystemTest,UidDeviceAffinities)566 TEST_F(AudioSystemTest, UidDeviceAffinities) {
567     uid_t uid = getuid();
568 
569     // Test invalid device for example audio_is_input_device
570     AudioDeviceTypeAddr inputDevice(AUDIO_DEVICE_IN_BUILTIN_MIC, "");
571     AudioDeviceTypeAddrVector inputDevices = {inputDevice};
572     EXPECT_EQ(BAD_VALUE, AudioSystem::setUidDeviceAffinities(uid, inputDevices));
573 
574     audio_port_v7 port;
575     if (OK == getAnyPort(AUDIO_PORT_ROLE_SINK, AUDIO_PORT_TYPE_DEVICE, port)) {
576         // Test valid device for example audio_is_output_device
577         AudioDeviceTypeAddr outputDevice(port.ext.device.type, port.ext.device.address);
578         AudioDeviceTypeAddrVector outputDevices = {outputDevice};
579         EXPECT_EQ(NO_ERROR, AudioSystem::setUidDeviceAffinities(uid, outputDevices));
580         EXPECT_EQ(NO_ERROR, AudioSystem::removeUidDeviceAffinities(uid));
581     }
582 }
583 
TEST_F(AudioSystemTest,UserIdDeviceAffinities)584 TEST_F(AudioSystemTest, UserIdDeviceAffinities) {
585     int userId = 200;
586 
587     // Test invalid device for example audio_is_input_device
588     AudioDeviceTypeAddr inputDevice(AUDIO_DEVICE_IN_BUILTIN_MIC, "");
589     AudioDeviceTypeAddrVector inputDevices = {inputDevice};
590     EXPECT_EQ(BAD_VALUE, AudioSystem::setUserIdDeviceAffinities(userId, inputDevices));
591 
592     audio_port_v7 port;
593     if (OK == getAnyPort(AUDIO_PORT_ROLE_SINK, AUDIO_PORT_TYPE_DEVICE, port)) {
594         // Test valid device for example audio_is_output_device
595         AudioDeviceTypeAddr outputDevice(port.ext.device.type, port.ext.device.address);
596         AudioDeviceTypeAddrVector outputDevices = {outputDevice};
597         EXPECT_EQ(NO_ERROR, AudioSystem::setUserIdDeviceAffinities(userId, outputDevices));
598         EXPECT_EQ(NO_ERROR, AudioSystem::removeUserIdDeviceAffinities(userId));
599     }
600 }
601 
602 namespace {
603 
604 class WithSimulatedDeviceConnections {
605   public:
WithSimulatedDeviceConnections()606     WithSimulatedDeviceConnections()
607         : mIsSupported(AudioSystem::setSimulateDeviceConnections(true) == OK) {}
~WithSimulatedDeviceConnections()608     ~WithSimulatedDeviceConnections() {
609         if (mIsSupported) {
610             if (status_t status = AudioSystem::setSimulateDeviceConnections(false); status != OK) {
611                 ALOGE("Error restoring device connections simulation state: %d", status);
612             }
613         }
614     }
isSupported() const615     bool isSupported() const { return mIsSupported; }
616 
617   private:
618     const bool mIsSupported;
619 };
620 
GenerateUniqueDeviceAddress(const android::media::audio::common::AudioPort & port)621 android::media::audio::common::AudioPort GenerateUniqueDeviceAddress(
622         const android::media::audio::common::AudioPort& port) {
623     // Point-to-point connections do not use addresses.
624     static const std::set<std::string> kPointToPointConnections = {
625             AudioDeviceDescription::CONNECTION_ANALOG(), AudioDeviceDescription::CONNECTION_HDMI(),
626             AudioDeviceDescription::CONNECTION_HDMI_ARC(),
627             AudioDeviceDescription::CONNECTION_HDMI_EARC(),
628             AudioDeviceDescription::CONNECTION_SPDIF()};
629     static int nextId = 0;
630     using Tag = AudioDeviceAddress::Tag;
631     const auto& deviceDescription = port.ext.get<AudioPortExt::Tag::device>().device.type;
632     AudioDeviceAddress address;
633     if (kPointToPointConnections.count(deviceDescription.connection) == 0) {
634         switch (suggestDeviceAddressTag(deviceDescription)) {
635             case Tag::id:
636                 address = AudioDeviceAddress::make<Tag::id>(std::to_string(++nextId));
637                 break;
638             case Tag::mac:
639                 address = AudioDeviceAddress::make<Tag::mac>(
640                         std::vector<uint8_t>{1, 2, 3, 4, 5, static_cast<uint8_t>(++nextId & 0xff)});
641                 break;
642             case Tag::ipv4:
643                 address = AudioDeviceAddress::make<Tag::ipv4>(
644                         std::vector<uint8_t>{192, 168, 0, static_cast<uint8_t>(++nextId & 0xff)});
645                 break;
646             case Tag::ipv6:
647                 address = AudioDeviceAddress::make<Tag::ipv6>(std::vector<int32_t>{
648                         0xfc00, 0x0123, 0x4567, 0x89ab, 0xcdef, 0, 0, ++nextId & 0xffff});
649                 break;
650             case Tag::alsa:
651                 address = AudioDeviceAddress::make<Tag::alsa>(std::vector<int32_t>{1, ++nextId});
652                 break;
653         }
654     }
655     android::media::audio::common::AudioPort result = port;
656     result.ext.get<AudioPortExt::Tag::device>().device.address = std::move(address);
657     return result;
658 }
659 
660 }  // namespace
661 
TEST_F(AudioSystemTest,SetDeviceConnectedState)662 TEST_F(AudioSystemTest, SetDeviceConnectedState) {
663     WithSimulatedDeviceConnections connSim;
664     if (!connSim.isSupported()) {
665         GTEST_SKIP() << "Simulation of external device connections not supported";
666     }
667     std::vector<media::AudioPortFw> ports;
668     ASSERT_EQ(OK, AudioSystem::listDeclaredDevicePorts(media::AudioPortRole::NONE, &ports));
669     if (ports.empty()) {
670         GTEST_SKIP() << "No ports returned by the audio system";
671     }
672     const std::set<AudioDeviceType> typesToUse{
673             AudioDeviceType::IN_DEVICE,       AudioDeviceType::IN_HEADSET,
674             AudioDeviceType::IN_MICROPHONE,   AudioDeviceType::OUT_DEVICE,
675             AudioDeviceType::OUT_HEADPHONE,   AudioDeviceType::OUT_HEADSET,
676             AudioDeviceType::OUT_HEARING_AID, AudioDeviceType::OUT_SPEAKER};
677     std::vector<media::AudioPortFw> externalDevicePorts;
678     for (const auto& port : ports) {
679         if (const auto& device = port.hal.ext.get<AudioPortExt::device>().device;
680             !device.type.connection.empty() && typesToUse.count(device.type.type)) {
681             externalDevicePorts.push_back(port);
682         }
683     }
684     if (externalDevicePorts.empty()) {
685         GTEST_SKIP() << "No ports for considered non-attached devices";
686     }
687     for (auto& port : externalDevicePorts) {
688         android::media::audio::common::AudioPort aidlPort = GenerateUniqueDeviceAddress(port.hal);
689         SCOPED_TRACE(aidlPort.toString());
690         audio_devices_t type;
691         char address[AUDIO_DEVICE_MAX_ADDRESS_LEN];
692         status_t status = aidl2legacy_AudioDevice_audio_device(
693                 aidlPort.ext.get<AudioPortExt::Tag::device>().device, &type, address);
694         ASSERT_EQ(OK, status);
695         audio_policy_dev_state_t deviceState = AudioSystem::getDeviceConnectionState(type, address);
696         EXPECT_EQ(AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, deviceState);
697         if (deviceState != AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) continue;
698         // !!! Instead of the default format, use each format from 'ext.encodedFormats'
699         // !!! if they are not empty
700         status = AudioSystem::setDeviceConnectionState(AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
701                                                        aidlPort, AUDIO_FORMAT_DEFAULT, false);
702         EXPECT_EQ(OK, status);
703         if (status != OK) continue;
704         deviceState = AudioSystem::getDeviceConnectionState(type, address);
705         EXPECT_EQ(AUDIO_POLICY_DEVICE_STATE_AVAILABLE, deviceState);
706         status = AudioSystem::setDeviceConnectionState(AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
707                                                        aidlPort, AUDIO_FORMAT_DEFAULT, false);
708         EXPECT_EQ(OK, status);
709         deviceState = AudioSystem::getDeviceConnectionState(type, address);
710         EXPECT_EQ(AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, deviceState);
711     }
712 }
713 
main(int argc,char ** argv)714 int main(int argc, char** argv) {
715     ::testing::InitGoogleTest(&argc, argv);
716     ::testing::UnitTest::GetInstance()->listeners().Append(new TestExecutionTracer());
717     return RUN_ALL_TESTS();
718 }
719