1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <cstring>
18 #include <memory>
19 #include <string>
20 #include <sys/wait.h>
21 #include <unistd.h>
22 
23 #include <gtest/gtest.h>
24 #include <gmock/gmock.h>
25 
26 #define LOG_TAG "APM_Test"
27 #include <Serializer.h>
28 #include <android-base/file.h>
29 #include <android-base/properties.h>
30 #include <android/content/AttributionSourceState.h>
31 #include <android_media_audiopolicy.h>
32 #include <com_android_media_audioserver.h>
33 #include <flag_macros.h>
34 #include <hardware/audio_effect.h>
35 #include <media/AudioPolicy.h>
36 #include <media/PatchBuilder.h>
37 #include <media/RecordingActivityTracker.h>
38 #include <utils/Log.h>
39 #include <utils/Vector.h>
40 #include <cutils/multiuser.h>
41 
42 #include "AudioPolicyInterface.h"
43 #include "AudioPolicyManagerTestClient.h"
44 #include "AudioPolicyTestClient.h"
45 #include "AudioPolicyTestManager.h"
46 
47 using namespace android;
48 using testing::UnorderedElementsAre;
49 using testing::IsEmpty;
50 using android::content::AttributionSourceState;
51 
52 namespace {
53 
createUidCriterion(uint32_t uid,bool exclude=false)54 AudioMixMatchCriterion createUidCriterion(uint32_t uid, bool exclude = false) {
55     AudioMixMatchCriterion criterion;
56     criterion.mValue.mUid = uid;
57     criterion.mRule = exclude ? RULE_EXCLUDE_UID : RULE_MATCH_UID;
58     return criterion;
59 }
60 
createUserIdCriterion(int userId,bool exclude=false)61 AudioMixMatchCriterion createUserIdCriterion(int userId, bool exclude = false) {
62     AudioMixMatchCriterion criterion;
63     criterion.mValue.mUserId = userId;
64     criterion.mRule = exclude ? RULE_EXCLUDE_USERID : RULE_MATCH_USERID;
65     return criterion;
66 }
67 
createUsageCriterion(audio_usage_t usage,bool exclude=false)68 AudioMixMatchCriterion createUsageCriterion(audio_usage_t usage, bool exclude = false) {
69     AudioMixMatchCriterion criterion;
70     criterion.mValue.mUsage = usage;
71     criterion.mRule = exclude ? RULE_EXCLUDE_ATTRIBUTE_USAGE : RULE_MATCH_ATTRIBUTE_USAGE;
72     return criterion;
73 }
74 
createCapturePresetCriterion(audio_source_t source,bool exclude=false)75 AudioMixMatchCriterion createCapturePresetCriterion(audio_source_t source, bool exclude = false) {
76     AudioMixMatchCriterion criterion;
77     criterion.mValue.mSource = source;
78     criterion.mRule = exclude ?
79         RULE_EXCLUDE_ATTRIBUTE_CAPTURE_PRESET : RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET;
80     return criterion;
81 }
82 
createSessionIdCriterion(audio_session_t session,bool exclude=false)83 AudioMixMatchCriterion createSessionIdCriterion(audio_session_t session, bool exclude = false) {
84     AudioMixMatchCriterion criterion;
85     criterion.mValue.mAudioSessionId = session;
86     criterion.mRule = exclude ?
87         RULE_EXCLUDE_AUDIO_SESSION_ID : RULE_MATCH_AUDIO_SESSION_ID;
88     return criterion;
89 }
90 
91 // TODO b/182392769: use attribution source util
createAttributionSourceState(uid_t uid)92 AttributionSourceState createAttributionSourceState(uid_t uid) {
93     AttributionSourceState attributionSourceState;
94     attributionSourceState.uid = uid;
95     attributionSourceState.token = sp<BBinder>::make();
96     return attributionSourceState;
97 }
98 
equals(const audio_config_base_t & config1,const audio_config_base_t & config2)99 bool equals(const audio_config_base_t& config1, const audio_config_base_t& config2) {
100     return config1.format == config2.format
101             && config1.sample_rate == config2.sample_rate
102             && config1.channel_mask == config2.channel_mask;
103 }
104 
105 } // namespace
106 
TEST(AudioPolicyConfigTest,DefaultConfigForTestsIsEmpty)107 TEST(AudioPolicyConfigTest, DefaultConfigForTestsIsEmpty) {
108     auto config = AudioPolicyConfig::createWritableForTests();
109     EXPECT_TRUE(config->getSource().empty());
110     EXPECT_TRUE(config->getHwModules().isEmpty());
111     EXPECT_TRUE(config->getInputDevices().isEmpty());
112     EXPECT_TRUE(config->getOutputDevices().isEmpty());
113 }
114 
TEST(AudioPolicyConfigTest,FallbackToDefault)115 TEST(AudioPolicyConfigTest, FallbackToDefault) {
116     auto config = AudioPolicyConfig::loadFromApmXmlConfigWithFallback(
117             base::GetExecutableDirectory() + "/test_invalid_audio_policy_configuration.xml");
118     EXPECT_EQ(AudioPolicyConfig::kDefaultConfigSource, config->getSource());
119 }
120 
TEST(AudioPolicyConfigTest,LoadForTests)121 TEST(AudioPolicyConfigTest, LoadForTests) {
122     {
123         auto result = AudioPolicyConfig::loadFromCustomXmlConfigForTests(
124                 base::GetExecutableDirectory() + "/test_invalid_audio_policy_configuration.xml");
125         EXPECT_FALSE(result.ok());
126     }
127     {
128         const std::string source =
129                 base::GetExecutableDirectory() + "/test_audio_policy_configuration.xml";
130         auto result = AudioPolicyConfig::loadFromCustomXmlConfigForTests(source);
131         ASSERT_TRUE(result.ok());
132         EXPECT_EQ(source, result.value()->getSource());
133         EXPECT_FALSE(result.value()->getHwModules().isEmpty());
134         EXPECT_FALSE(result.value()->getInputDevices().isEmpty());
135         EXPECT_FALSE(result.value()->getOutputDevices().isEmpty());
136     }
137 }
138 
TEST(AudioPolicyManagerTestInit,EngineFailure)139 TEST(AudioPolicyManagerTestInit, EngineFailure) {
140     AudioPolicyTestClient client;
141     auto config = AudioPolicyConfig::createWritableForTests();
142     config->setDefault();
143     config->setEngineLibraryNameSuffix("non-existent");
144     AudioPolicyTestManager manager(config, &client);
145     ASSERT_EQ(NO_INIT, manager.initialize());
146     ASSERT_EQ(NO_INIT, manager.initCheck());
147 }
148 
TEST(AudioPolicyManagerTestInit,ClientFailure)149 TEST(AudioPolicyManagerTestInit, ClientFailure) {
150     AudioPolicyTestClient client;
151     AudioPolicyTestManager manager(&client);
152     // Since the default client fails to open anything,
153     // APM should indicate that the initialization didn't succeed.
154     ASSERT_EQ(NO_INIT, manager.initialize());
155     ASSERT_EQ(NO_INIT, manager.initCheck());
156 }
157 
158 
159 class PatchCountCheck {
160   public:
PatchCountCheck(AudioPolicyManagerTestClient * client)161     explicit PatchCountCheck(AudioPolicyManagerTestClient *client)
162             : mClient{client},
163               mInitialCount{mClient->getActivePatchesCount()} {}
deltaFromSnapshot() const164     int deltaFromSnapshot() const {
165         size_t currentCount = mClient->getActivePatchesCount();
166         if (mInitialCount <= currentCount) {
167             return currentCount - mInitialCount;
168         } else {
169             return -(static_cast<int>(mInitialCount - currentCount));
170         }
171     }
172   private:
173     const AudioPolicyManagerTestClient *mClient;
174     const size_t mInitialCount;
175 };
176 
177 class AudioPolicyManagerTest : public testing::Test {
178   protected:
179     void SetUp() override;
180     void TearDown() override;
181     virtual void SetUpManagerConfig();
182 
183     void dumpToLog();
184     // When explicit routing is needed, selectedDeviceId needs to be set as the wanted port
185     // id. Otherwise, selectedDeviceId needs to be initialized as AUDIO_PORT_HANDLE_NONE.
186     void getOutputForAttr(
187             audio_port_handle_t *selectedDeviceId,
188             audio_format_t format,
189             audio_channel_mask_t channelMask,
190             int sampleRate,
191             audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
192             audio_io_handle_t *output = nullptr,
193             audio_port_handle_t *portId = nullptr,
194             audio_attributes_t attr = {},
195             audio_session_t session = AUDIO_SESSION_NONE,
196             int uid = 0,
197             bool* isBitPerfect = nullptr);
198     void getInputForAttr(
199             const audio_attributes_t &attr,
200             audio_io_handle_t *input,
201             audio_session_t session,
202             audio_unique_id_t riid,
203             audio_port_handle_t *selectedDeviceId,
204             audio_format_t format,
205             audio_channel_mask_t channelMask,
206             int sampleRate,
207             audio_input_flags_t flags = AUDIO_INPUT_FLAG_NONE,
208             audio_port_handle_t *portId = nullptr,
209             uint32_t *virtualDeviceId = nullptr);
snapshotPatchCount()210     PatchCountCheck snapshotPatchCount() { return PatchCountCheck(mClient.get()); }
211 
212     void getAudioPorts(audio_port_type_t type, audio_port_role_t role,
213             std::vector<audio_port_v7>* ports);
214     // Tries to find a device port. If 'foundPort' isn't nullptr,
215     // will generate a failure if the port hasn't been found.
216     bool findDevicePort(audio_port_role_t role, audio_devices_t deviceType,
217             const std::string &address, audio_port_v7 *foundPort);
218     static audio_port_handle_t getDeviceIdFromPatch(const struct audio_patch* patch);
getClient()219     virtual AudioPolicyManagerTestClient* getClient() { return new AudioPolicyManagerTestClient; }
220 
221     sp<AudioPolicyConfig> mConfig;
222     std::unique_ptr<AudioPolicyManagerTestClient> mClient;
223     std::unique_ptr<AudioPolicyTestManager> mManager;
224 
225     constexpr static const uint32_t k48000SamplingRate = 48000;
226 };
227 
SetUp()228 void AudioPolicyManagerTest::SetUp() {
229     mClient.reset(getClient());
230     ASSERT_NO_FATAL_FAILURE(SetUpManagerConfig());  // Subclasses may want to customize the config.
231     mManager.reset(new AudioPolicyTestManager(mConfig, mClient.get()));
232     ASSERT_EQ(NO_ERROR, mManager->initialize());
233     ASSERT_EQ(NO_ERROR, mManager->initCheck());
234 }
235 
TearDown()236 void AudioPolicyManagerTest::TearDown() {
237     mManager.reset();
238     mClient.reset();
239 }
240 
SetUpManagerConfig()241 void AudioPolicyManagerTest::SetUpManagerConfig() {
242     mConfig = AudioPolicyConfig::createWritableForTests();
243     mConfig->setDefault();
244 }
245 
dumpToLog()246 void AudioPolicyManagerTest::dumpToLog() {
247     int pipefd[2];
248     ASSERT_NE(-1, pipe(pipefd));
249     pid_t cpid = fork();
250     ASSERT_NE(-1, cpid);
251     if (cpid == 0) {
252         // Child process reads from the pipe and logs.
253         close(pipefd[1]);
254         std::string line;
255         char buf;
256         while (read(pipefd[0], &buf, sizeof(buf)) > 0) {
257             if (buf != '\n') {
258                 line += buf;
259             } else {
260                 ALOGI("%s", line.c_str());
261                 line = "";
262             }
263         }
264         if (!line.empty()) ALOGI("%s", line.c_str());
265         close(pipefd[0]);
266         _exit(EXIT_SUCCESS);
267     } else {
268         // Parent does the dump and checks the status code.
269         close(pipefd[0]);
270         ASSERT_EQ(NO_ERROR, mManager->dump(pipefd[1]));
271         close(pipefd[1]);
272         wait(NULL);  // Wait for the child to exit.
273     }
274 }
275 
getOutputForAttr(audio_port_handle_t * selectedDeviceId,audio_format_t format,audio_channel_mask_t channelMask,int sampleRate,audio_output_flags_t flags,audio_io_handle_t * output,audio_port_handle_t * portId,audio_attributes_t attr,audio_session_t session,int uid,bool * isBitPerfect)276 void AudioPolicyManagerTest::getOutputForAttr(
277         audio_port_handle_t *selectedDeviceId,
278         audio_format_t format,
279         audio_channel_mask_t channelMask,
280         int sampleRate,
281         audio_output_flags_t flags,
282         audio_io_handle_t *output,
283         audio_port_handle_t *portId,
284         audio_attributes_t attr,
285         audio_session_t session,
286         int uid,
287         bool* isBitPerfect) {
288     audio_io_handle_t localOutput;
289     if (!output) output = &localOutput;
290     *output = AUDIO_IO_HANDLE_NONE;
291     audio_stream_type_t stream = AUDIO_STREAM_DEFAULT;
292     audio_config_t config = AUDIO_CONFIG_INITIALIZER;
293     config.sample_rate = sampleRate;
294     config.channel_mask = channelMask;
295     config.format = format;
296     audio_port_handle_t localPortId;
297     if (!portId) portId = &localPortId;
298     *portId = AUDIO_PORT_HANDLE_NONE;
299     AudioPolicyInterface::output_type_t outputType;
300     bool isSpatialized;
301     bool isBitPerfectInternal;
302     AttributionSourceState attributionSource = createAttributionSourceState(uid);
303     ASSERT_EQ(OK, mManager->getOutputForAttr(
304                     &attr, output, session, &stream, attributionSource, &config, &flags,
305                     selectedDeviceId, portId, {}, &outputType, &isSpatialized,
306                     isBitPerfect == nullptr ? &isBitPerfectInternal : isBitPerfect));
307     ASSERT_NE(AUDIO_PORT_HANDLE_NONE, *portId);
308     ASSERT_NE(AUDIO_IO_HANDLE_NONE, *output);
309 }
310 
getInputForAttr(const audio_attributes_t & attr,audio_io_handle_t * input,const audio_session_t session,audio_unique_id_t riid,audio_port_handle_t * selectedDeviceId,audio_format_t format,audio_channel_mask_t channelMask,int sampleRate,audio_input_flags_t flags,audio_port_handle_t * portId,uint32_t * virtualDeviceId)311 void AudioPolicyManagerTest::getInputForAttr(
312         const audio_attributes_t &attr,
313         audio_io_handle_t *input,
314         const audio_session_t session,
315         audio_unique_id_t riid,
316         audio_port_handle_t *selectedDeviceId,
317         audio_format_t format,
318         audio_channel_mask_t channelMask,
319         int sampleRate,
320         audio_input_flags_t flags,
321         audio_port_handle_t *portId,
322         uint32_t *virtualDeviceId) {
323     audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
324     config.sample_rate = sampleRate;
325     config.channel_mask = channelMask;
326     config.format = format;
327     audio_port_handle_t localPortId;
328     if (!portId) portId = &localPortId;
329     *portId = AUDIO_PORT_HANDLE_NONE;
330     if (!virtualDeviceId) virtualDeviceId = 0;
331     AudioPolicyInterface::input_type_t inputType;
332     AttributionSourceState attributionSource = createAttributionSourceState(/*uid=*/ 0);
333     ASSERT_EQ(OK, mManager->getInputForAttr(
334             &attr, input, riid, session, attributionSource, &config, flags,
335             selectedDeviceId, &inputType, portId, virtualDeviceId));
336     ASSERT_NE(AUDIO_PORT_HANDLE_NONE, *portId);
337 }
338 
getAudioPorts(audio_port_type_t type,audio_port_role_t role,std::vector<audio_port_v7> * ports)339 void AudioPolicyManagerTest::getAudioPorts(audio_port_type_t type, audio_port_role_t role,
340         std::vector<audio_port_v7>* ports) {
341     uint32_t numPorts = 0;
342     uint32_t generation1;
343     status_t ret;
344 
345     ret = mManager->listAudioPorts(role, type, &numPorts, nullptr, &generation1);
346     ASSERT_EQ(NO_ERROR, ret) << "mManager->listAudioPorts returned error";
347 
348     uint32_t generation2;
349     ports->resize(numPorts);
350     ret = mManager->listAudioPorts(role, type, &numPorts, ports->data(), &generation2);
351     ASSERT_EQ(NO_ERROR, ret) << "mManager->listAudioPorts returned error";
352     ASSERT_EQ(generation1, generation2) << "Generations changed during ports retrieval";
353 }
354 
findDevicePort(audio_port_role_t role,audio_devices_t deviceType,const std::string & address,audio_port_v7 * foundPort)355 bool AudioPolicyManagerTest::findDevicePort(audio_port_role_t role,
356         audio_devices_t deviceType, const std::string &address, audio_port_v7 *foundPort) {
357     std::vector<audio_port_v7> ports;
358     getAudioPorts(AUDIO_PORT_TYPE_DEVICE, role, &ports);
359     if (HasFailure()) return false;
360 
361     for (const auto &port : ports) {
362         if (port.role == role && port.ext.device.type == deviceType &&
363                 (strncmp(port.ext.device.address, address.c_str(),
364                          AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
365             if (foundPort) *foundPort = port;
366             return true;
367         }
368     }
369     if (foundPort) {
370         ADD_FAILURE() << "Device port with role " << role << " and address "
371                       << address << " not found";
372     }
373     return false;
374 }
375 
getDeviceIdFromPatch(const struct audio_patch * patch)376 audio_port_handle_t AudioPolicyManagerTest::getDeviceIdFromPatch(
377         const struct audio_patch* patch) {
378     // The logic here is the same as the one in AudioIoDescriptor.
379     // Note this function is aim to get routed device id for test.
380     // In that case, device to device patch is not expected here.
381     if (patch->num_sources != 0 && patch->num_sinks != 0) {
382         if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
383             return patch->sinks[0].id;
384         } else {
385             return patch->sources[0].id;
386         }
387     }
388     return AUDIO_PORT_HANDLE_NONE;
389 }
390 
391 
TEST_F(AudioPolicyManagerTest,InitSuccess)392 TEST_F(AudioPolicyManagerTest, InitSuccess) {
393     // SetUp must finish with no assertions.
394 }
395 
TEST_F(AudioPolicyManagerTest,Dump)396 TEST_F(AudioPolicyManagerTest, Dump) {
397     dumpToLog();
398 }
399 
TEST_F(AudioPolicyManagerTest,CreateAudioPatchFailure)400 TEST_F(AudioPolicyManagerTest, CreateAudioPatchFailure) {
401     audio_patch patch{};
402     audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
403     const PatchCountCheck patchCount = snapshotPatchCount();
404     ASSERT_EQ(BAD_VALUE, mManager->createAudioPatch(nullptr, &handle, 0));
405     ASSERT_EQ(BAD_VALUE, mManager->createAudioPatch(&patch, nullptr, 0));
406     ASSERT_EQ(BAD_VALUE, mManager->createAudioPatch(&patch, &handle, 0));
407     patch.num_sources = AUDIO_PATCH_PORTS_MAX + 1;
408     patch.num_sinks = 1;
409     ASSERT_EQ(BAD_VALUE, mManager->createAudioPatch(&patch, &handle, 0));
410     patch.num_sources = 1;
411     patch.num_sinks = AUDIO_PATCH_PORTS_MAX + 1;
412     ASSERT_EQ(BAD_VALUE, mManager->createAudioPatch(&patch, &handle, 0));
413     patch.num_sources = 2;
414     patch.num_sinks = 1;
415     ASSERT_EQ(INVALID_OPERATION, mManager->createAudioPatch(&patch, &handle, 0));
416     patch = {};
417     patch.num_sources = 1;
418     patch.sources[0].role = AUDIO_PORT_ROLE_SINK;
419     patch.num_sinks = 1;
420     patch.sinks[0].role = AUDIO_PORT_ROLE_SINK;
421     ASSERT_EQ(INVALID_OPERATION, mManager->createAudioPatch(&patch, &handle, 0));
422     patch = {};
423     patch.num_sources = 1;
424     patch.sources[0].role = AUDIO_PORT_ROLE_SOURCE;
425     patch.num_sinks = 1;
426     patch.sinks[0].role = AUDIO_PORT_ROLE_SOURCE;
427     ASSERT_EQ(INVALID_OPERATION, mManager->createAudioPatch(&patch, &handle, 0));
428     // Verify that the handle is left unchanged.
429     ASSERT_EQ(AUDIO_PATCH_HANDLE_NONE, handle);
430     ASSERT_EQ(0, patchCount.deltaFromSnapshot());
431 }
432 
TEST_F(AudioPolicyManagerTest,CreateAudioPatchFromMix)433 TEST_F(AudioPolicyManagerTest, CreateAudioPatchFromMix) {
434     audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
435     uid_t uid = 42;
436     const PatchCountCheck patchCount = snapshotPatchCount();
437     ASSERT_FALSE(mManager->getAvailableInputDevices().isEmpty());
438     PatchBuilder patchBuilder;
439     patchBuilder.addSource(mManager->getAvailableInputDevices()[0]).
440             addSink(mManager->getConfig().getDefaultOutputDevice());
441     ASSERT_EQ(NO_ERROR, mManager->createAudioPatch(patchBuilder.patch(), &handle, uid));
442     ASSERT_NE(AUDIO_PATCH_HANDLE_NONE, handle);
443     ASSERT_EQ(1, patchCount.deltaFromSnapshot());
444 }
445 
446 // TODO: Add patch creation tests that involve already existing patch
447 
448 enum
449 {
450     MSD_AUDIO_PATCH_COUNT_NUM_AUDIO_PATCHES_INDEX = 0,
451     MSD_AUDIO_PATCH_COUNT_NAME_INDEX = 1
452 };
453 using MsdAudioPatchCountSpecification = std::tuple<size_t, std::string>;
454 
455 class AudioPolicyManagerTestMsd : public AudioPolicyManagerTest,
456         public ::testing::WithParamInterface<MsdAudioPatchCountSpecification> {
457   public:
458     AudioPolicyManagerTestMsd();
459   protected:
460     void SetUpManagerConfig() override;
461     void TearDown() override;
462     AudioProfileVector getDirectProfilesForAttributes(const audio_attributes_t& attr);
463 
464     sp<DeviceDescriptor> mMsdOutputDevice;
465     sp<DeviceDescriptor> mMsdInputDevice;
466     sp<DeviceDescriptor> mDefaultOutputDevice;
467 
468     const size_t mExpectedAudioPatchCount;
469     sp<DeviceDescriptor> mSpdifDevice;
470 
471     sp<DeviceDescriptor> mHdmiInputDevice;
472 };
473 
AudioPolicyManagerTestMsd()474 AudioPolicyManagerTestMsd::AudioPolicyManagerTestMsd()
475     : mExpectedAudioPatchCount(std::get<MSD_AUDIO_PATCH_COUNT_NUM_AUDIO_PATCHES_INDEX>(
476             GetParam())) {}
477 
478 INSTANTIATE_TEST_CASE_P(
479         MsdAudioPatchCount,
480         AudioPolicyManagerTestMsd,
481         ::testing::Values(
482                 MsdAudioPatchCountSpecification(2u, "single"),
483                 MsdAudioPatchCountSpecification(3u, "dual")
484         ),
__anon25e8343b0302(const ::testing::TestParamInfo<MsdAudioPatchCountSpecification> &info) 485         [](const ::testing::TestParamInfo<MsdAudioPatchCountSpecification> &info) {
486                 return std::get<MSD_AUDIO_PATCH_COUNT_NAME_INDEX>(info.param); }
487 );
488 
SetUpManagerConfig()489 void AudioPolicyManagerTestMsd::SetUpManagerConfig() {
490     // TODO: Consider using Serializer to load part of the config from a string.
491     ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTest::SetUpManagerConfig());
492     mMsdOutputDevice = new DeviceDescriptor(AUDIO_DEVICE_OUT_BUS);
493     sp<AudioProfile> pcmOutputProfile = new AudioProfile(
494             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO, k48000SamplingRate);
495     sp<AudioProfile> ac3OutputProfile = new AudioProfile(
496             AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1, k48000SamplingRate);
497     sp<AudioProfile> iec958OutputProfile = new AudioProfile(
498             AUDIO_FORMAT_IEC60958, AUDIO_CHANNEL_INDEX_MASK_24, k48000SamplingRate);
499     mMsdOutputDevice->addAudioProfile(pcmOutputProfile);
500     mMsdOutputDevice->addAudioProfile(ac3OutputProfile);
501     mMsdOutputDevice->addAudioProfile(iec958OutputProfile);
502     mMsdInputDevice = new DeviceDescriptor(AUDIO_DEVICE_IN_BUS);
503     // Match output profile from AudioPolicyConfig::setDefault.
504     sp<AudioProfile> pcmInputProfile = new AudioProfile(
505             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO, 44100);
506     mMsdInputDevice->addAudioProfile(pcmInputProfile);
507     mConfig->addDevice(mMsdOutputDevice);
508     mConfig->addDevice(mMsdInputDevice);
509 
510     if (mExpectedAudioPatchCount == 3) {
511         // Add SPDIF device with PCM output profile as a second device for dual MSD audio patching.
512         mSpdifDevice = new DeviceDescriptor(AUDIO_DEVICE_OUT_SPDIF);
513         mSpdifDevice->addAudioProfile(pcmOutputProfile);
514         mConfig->addDevice(mSpdifDevice);
515 
516         sp<OutputProfile> spdifOutputProfile = new OutputProfile("spdif output");
517         spdifOutputProfile->addAudioProfile(pcmOutputProfile);
518         spdifOutputProfile->addSupportedDevice(mSpdifDevice);
519         mConfig->getHwModules().getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)->
520                 addOutputProfile(spdifOutputProfile);
521     }
522 
523     sp<HwModule> msdModule = new HwModule(AUDIO_HARDWARE_MODULE_ID_MSD, 2 /*halVersionMajor*/);
524     HwModuleCollection modules = mConfig->getHwModules();
525     modules.add(msdModule);
526     mConfig->setHwModules(modules);
527 
528     sp<OutputProfile> msdOutputProfile = new OutputProfile("msd input");
529     msdOutputProfile->addAudioProfile(pcmOutputProfile);
530     msdOutputProfile->addSupportedDevice(mMsdOutputDevice);
531     msdModule->addOutputProfile(msdOutputProfile);
532     sp<OutputProfile> msdCompressedOutputProfile = new OutputProfile("msd compressed input");
533     msdCompressedOutputProfile->addAudioProfile(ac3OutputProfile);
534     msdCompressedOutputProfile->setFlags(
535             AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
536             AUDIO_OUTPUT_FLAG_NON_BLOCKING);
537     msdCompressedOutputProfile->addSupportedDevice(mMsdOutputDevice);
538     msdModule->addOutputProfile(msdCompressedOutputProfile);
539     sp<OutputProfile> msdIec958OutputProfile = new OutputProfile("msd iec958 input");
540     msdIec958OutputProfile->addAudioProfile(iec958OutputProfile);
541     msdIec958OutputProfile->setFlags(AUDIO_OUTPUT_FLAG_DIRECT);
542     msdIec958OutputProfile->addSupportedDevice(mMsdOutputDevice);
543     msdModule->addOutputProfile(msdIec958OutputProfile);
544 
545     sp<InputProfile> msdInputProfile = new InputProfile("msd output");
546     msdInputProfile->addAudioProfile(pcmInputProfile);
547     msdInputProfile->addSupportedDevice(mMsdInputDevice);
548     msdModule->addInputProfile(msdInputProfile);
549 
550     // Add a profile with another encoding to the default device to test routing
551     // of streams that are not supported by MSD.
552     sp<AudioProfile> dtsOutputProfile = new AudioProfile(
553             AUDIO_FORMAT_DTS, AUDIO_CHANNEL_OUT_5POINT1, k48000SamplingRate);
554     mConfig->getDefaultOutputDevice()->addAudioProfile(dtsOutputProfile);
555     sp<OutputProfile> primaryEncodedOutputProfile = new OutputProfile("encoded");
556     primaryEncodedOutputProfile->addAudioProfile(dtsOutputProfile);
557     primaryEncodedOutputProfile->setFlags(AUDIO_OUTPUT_FLAG_DIRECT);
558     primaryEncodedOutputProfile->addSupportedDevice(mConfig->getDefaultOutputDevice());
559     mConfig->getHwModules().getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)->
560             addOutputProfile(primaryEncodedOutputProfile);
561 
562     mDefaultOutputDevice = mConfig->getDefaultOutputDevice();
563     if (mExpectedAudioPatchCount == 3) {
564         mSpdifDevice->addAudioProfile(dtsOutputProfile);
565         primaryEncodedOutputProfile->addSupportedDevice(mSpdifDevice);
566     }
567 
568     // Add HDMI input device with IEC60958 profile for HDMI in -> MSD patching.
569     mHdmiInputDevice = new DeviceDescriptor(AUDIO_DEVICE_IN_HDMI);
570     sp<AudioProfile> iec958InputProfile = new AudioProfile(
571             AUDIO_FORMAT_IEC60958, AUDIO_CHANNEL_INDEX_MASK_24, k48000SamplingRate);
572     mHdmiInputDevice->addAudioProfile(iec958InputProfile);
573     mConfig->addDevice(mHdmiInputDevice);
574     sp<InputProfile> hdmiInputProfile = new InputProfile("hdmi input");
575     hdmiInputProfile->addAudioProfile(iec958InputProfile);
576     hdmiInputProfile->setFlags(AUDIO_INPUT_FLAG_DIRECT);
577     hdmiInputProfile->addSupportedDevice(mHdmiInputDevice);
578     mConfig->getHwModules().getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)->
579             addInputProfile(hdmiInputProfile);
580 }
581 
TearDown()582 void AudioPolicyManagerTestMsd::TearDown() {
583     mMsdOutputDevice.clear();
584     mMsdInputDevice.clear();
585     mDefaultOutputDevice.clear();
586     mSpdifDevice.clear();
587     mHdmiInputDevice.clear();
588     AudioPolicyManagerTest::TearDown();
589 }
590 
getDirectProfilesForAttributes(const audio_attributes_t & attr)591 AudioProfileVector AudioPolicyManagerTestMsd::getDirectProfilesForAttributes(
592                                                     const audio_attributes_t& attr) {
593     AudioProfileVector audioProfilesVector;
594     mManager->getDirectProfilesForAttributes(&attr, audioProfilesVector);
595     return audioProfilesVector;
596 }
597 
TEST_P(AudioPolicyManagerTestMsd,InitSuccess)598 TEST_P(AudioPolicyManagerTestMsd, InitSuccess) {
599     ASSERT_TRUE(mMsdOutputDevice);
600     ASSERT_TRUE(mMsdInputDevice);
601     ASSERT_TRUE(mDefaultOutputDevice);
602 }
603 
TEST_P(AudioPolicyManagerTestMsd,Dump)604 TEST_P(AudioPolicyManagerTestMsd, Dump) {
605     dumpToLog();
606 }
607 
TEST_P(AudioPolicyManagerTestMsd,PatchCreationOnSetForceUse)608 TEST_P(AudioPolicyManagerTestMsd, PatchCreationOnSetForceUse) {
609     const PatchCountCheck patchCount = snapshotPatchCount();
610     mManager->setForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND,
611             AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS);
612     ASSERT_EQ(mExpectedAudioPatchCount -1 , patchCount.deltaFromSnapshot());
613 }
614 
TEST_P(AudioPolicyManagerTestMsd,PatchCreationSetReleaseMsdOutputPatches)615 TEST_P(AudioPolicyManagerTestMsd, PatchCreationSetReleaseMsdOutputPatches) {
616     const PatchCountCheck patchCount = snapshotPatchCount();
617     DeviceVector devices = mManager->getAvailableOutputDevices();
618     // Remove MSD output device to avoid patching to itself
619     devices.remove(mMsdOutputDevice);
620     ASSERT_EQ(mExpectedAudioPatchCount -1 , devices.size());
621     mManager->setMsdOutputPatches(&devices);
622     ASSERT_EQ(mExpectedAudioPatchCount - 1, patchCount.deltaFromSnapshot());
623     // Dual patch: exercise creating one new audio patch and reusing another existing audio patch.
624     DeviceVector singleDevice(devices[0]);
625     mManager->releaseMsdOutputPatches(singleDevice);
626     ASSERT_EQ(mExpectedAudioPatchCount - 2, patchCount.deltaFromSnapshot());
627     mManager->setMsdOutputPatches(&devices);
628     ASSERT_EQ(mExpectedAudioPatchCount - 1, patchCount.deltaFromSnapshot());
629     mManager->releaseMsdOutputPatches(devices);
630     ASSERT_EQ(0, patchCount.deltaFromSnapshot());
631 }
632 
TEST_P(AudioPolicyManagerTestMsd,GetOutputForAttrEncodedRoutesToMsd)633 TEST_P(AudioPolicyManagerTestMsd, GetOutputForAttrEncodedRoutesToMsd) {
634     const PatchCountCheck patchCount = snapshotPatchCount();
635     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
636     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1,
637             k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT);
638     ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
639     ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
640 }
641 
TEST_P(AudioPolicyManagerTestMsd,GetOutputForAttrPcmRoutesToMsd)642 TEST_P(AudioPolicyManagerTestMsd, GetOutputForAttrPcmRoutesToMsd) {
643     const PatchCountCheck patchCount = snapshotPatchCount();
644     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
645     getOutputForAttr(&selectedDeviceId,
646             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO, k48000SamplingRate);
647     ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
648     ASSERT_EQ(mExpectedAudioPatchCount - 1, patchCount.deltaFromSnapshot());
649 }
650 
TEST_P(AudioPolicyManagerTestMsd,GetOutputForAttrEncodedPlusPcmRoutesToMsd)651 TEST_P(AudioPolicyManagerTestMsd, GetOutputForAttrEncodedPlusPcmRoutesToMsd) {
652     const PatchCountCheck patchCount = snapshotPatchCount();
653     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
654     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1,
655             k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT);
656     ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
657     ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
658     selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
659     getOutputForAttr(&selectedDeviceId,
660             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO, k48000SamplingRate);
661     ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
662     ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
663 }
664 
TEST_P(AudioPolicyManagerTestMsd,GetOutputForAttrUnsupportedFormatBypassesMsd)665 TEST_P(AudioPolicyManagerTestMsd, GetOutputForAttrUnsupportedFormatBypassesMsd) {
666     const PatchCountCheck patchCount = snapshotPatchCount();
667     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
668     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_DTS, AUDIO_CHANNEL_OUT_5POINT1,
669             k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT);
670     ASSERT_NE(selectedDeviceId, mMsdOutputDevice->getId());
671     ASSERT_EQ(1, patchCount.deltaFromSnapshot());
672 }
673 
TEST_P(AudioPolicyManagerTestMsd,GetOutputForAttrFormatSwitching)674 TEST_P(AudioPolicyManagerTestMsd, GetOutputForAttrFormatSwitching) {
675     // Switch between formats that are supported and not supported by MSD.
676     {
677         const PatchCountCheck patchCount = snapshotPatchCount();
678         audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
679         audio_port_handle_t portId;
680         getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1,
681                 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, nullptr /*output*/, &portId);
682         ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
683         ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
684         mManager->releaseOutput(portId);
685         ASSERT_EQ(mExpectedAudioPatchCount - 1, patchCount.deltaFromSnapshot());
686     }
687     {
688         const PatchCountCheck patchCount = snapshotPatchCount();
689         audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
690         audio_port_handle_t portId;
691         getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_DTS, AUDIO_CHANNEL_OUT_5POINT1,
692                 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, nullptr /*output*/, &portId);
693         ASSERT_NE(selectedDeviceId, mMsdOutputDevice->getId());
694         ASSERT_EQ(-static_cast<int>(mExpectedAudioPatchCount) + 2, patchCount.deltaFromSnapshot());
695         mManager->releaseOutput(portId);
696         ASSERT_EQ(0, patchCount.deltaFromSnapshot());
697     }
698     {
699         const PatchCountCheck patchCount = snapshotPatchCount();
700         audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
701         getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1,
702                 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT);
703         ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
704         ASSERT_EQ(1, patchCount.deltaFromSnapshot());
705     }
706 }
707 
TEST_P(AudioPolicyManagerTestMsd,PatchCreationFromHdmiInToMsd)708 TEST_P(AudioPolicyManagerTestMsd, PatchCreationFromHdmiInToMsd) {
709     audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
710     uid_t uid = 42;
711     const PatchCountCheck patchCount = snapshotPatchCount();
712     ASSERT_FALSE(mManager->getAvailableInputDevices().isEmpty());
713     PatchBuilder patchBuilder;
714     patchBuilder.
715             addSource(mManager->getAvailableInputDevices().
716                     getDevice(AUDIO_DEVICE_IN_HDMI, String8(""), AUDIO_FORMAT_DEFAULT)).
717             addSink(mManager->getAvailableOutputDevices().
718                     getDevice(AUDIO_DEVICE_OUT_BUS, String8(""), AUDIO_FORMAT_DEFAULT));
719     ASSERT_EQ(NO_ERROR, mManager->createAudioPatch(patchBuilder.patch(), &handle, uid));
720     ASSERT_NE(AUDIO_PATCH_HANDLE_NONE, handle);
721     AudioPatchCollection patches = mManager->getAudioPatches();
722     sp<AudioPatch> patch = patches.valueFor(handle);
723     ASSERT_EQ(1, patch->mPatch.num_sources);
724     ASSERT_EQ(1, patch->mPatch.num_sinks);
725     ASSERT_EQ(AUDIO_PORT_ROLE_SOURCE, patch->mPatch.sources[0].role);
726     ASSERT_EQ(AUDIO_PORT_ROLE_SINK, patch->mPatch.sinks[0].role);
727     ASSERT_EQ(AUDIO_FORMAT_IEC60958, patch->mPatch.sources[0].format);
728     ASSERT_EQ(AUDIO_FORMAT_IEC60958, patch->mPatch.sinks[0].format);
729     ASSERT_EQ(AUDIO_CHANNEL_INDEX_MASK_24, patch->mPatch.sources[0].channel_mask);
730     ASSERT_EQ(AUDIO_CHANNEL_INDEX_MASK_24, patch->mPatch.sinks[0].channel_mask);
731     ASSERT_EQ(k48000SamplingRate, patch->mPatch.sources[0].sample_rate);
732     ASSERT_EQ(k48000SamplingRate, patch->mPatch.sinks[0].sample_rate);
733     ASSERT_EQ(1, patchCount.deltaFromSnapshot());
734 }
735 
TEST_P(AudioPolicyManagerTestMsd,GetDirectProfilesForAttributesWithMsd)736 TEST_P(AudioPolicyManagerTestMsd, GetDirectProfilesForAttributesWithMsd) {
737     const audio_attributes_t attr = {
738         AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
739         AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
740 
741     // count expected direct profiles for the default device
742     int countDirectProfilesPrimary = 0;
743     const auto& primary = mManager->getConfig().getHwModules()
744             .getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
745     for (const auto& outputProfile : primary->getOutputProfiles()) {
746         if (outputProfile->asAudioPort()->isDirectOutput()) {
747             countDirectProfilesPrimary += outputProfile->asAudioPort()->getAudioProfiles().size();
748         }
749     }
750 
751     // count expected direct profiles for the msd device
752     int countDirectProfilesMsd = 0;
753     const auto& msd = mManager->getConfig().getHwModules()
754             .getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
755     for (const auto& outputProfile : msd->getOutputProfiles()) {
756         if (outputProfile->asAudioPort()->isDirectOutput()) {
757             countDirectProfilesMsd += outputProfile->asAudioPort()->getAudioProfiles().size();
758         }
759     }
760 
761     // before setting up MSD audio patches we only have the primary hal direct profiles
762     ASSERT_EQ(countDirectProfilesPrimary, getDirectProfilesForAttributes(attr).size());
763 
764     DeviceVector outputDevices = mManager->getAvailableOutputDevices();
765     // Remove MSD output device to avoid patching to itself
766     outputDevices.remove(mMsdOutputDevice);
767     mManager->setMsdOutputPatches(&outputDevices);
768 
769     // after setting up MSD audio patches the MSD direct profiles are added
770     ASSERT_EQ(countDirectProfilesPrimary + countDirectProfilesMsd,
771                 getDirectProfilesForAttributes(attr).size());
772 
773     mManager->releaseMsdOutputPatches(outputDevices);
774     // releasing the MSD audio patches gets us back to the primary hal direct profiles only
775     ASSERT_EQ(countDirectProfilesPrimary, getDirectProfilesForAttributes(attr).size());
776 }
777 
TEST_P(AudioPolicyManagerTestMsd,IsDirectPlaybackSupportedWithMsd)778 TEST_P(AudioPolicyManagerTestMsd, IsDirectPlaybackSupportedWithMsd) {
779     const audio_attributes_t attr = {
780         AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
781         AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
782 
783     audio_config_base_t directConfig = AUDIO_CONFIG_BASE_INITIALIZER;
784     directConfig.format = AUDIO_FORMAT_DTS;
785     directConfig.sample_rate = 48000;
786     directConfig.channel_mask = AUDIO_CHANNEL_OUT_5POINT1;
787 
788     audio_config_base_t nonDirectConfig = AUDIO_CONFIG_BASE_INITIALIZER;
789     nonDirectConfig.format = AUDIO_FORMAT_PCM_16_BIT;
790     nonDirectConfig.sample_rate = 48000;
791     nonDirectConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
792 
793     audio_config_base_t nonExistentConfig = AUDIO_CONFIG_BASE_INITIALIZER;
794     nonExistentConfig.format = AUDIO_FORMAT_E_AC3;
795     nonExistentConfig.sample_rate = 48000;
796     nonExistentConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
797 
798     audio_config_base_t msdDirectConfig1 = AUDIO_CONFIG_BASE_INITIALIZER;
799     msdDirectConfig1.format = AUDIO_FORMAT_AC3;
800     msdDirectConfig1.sample_rate = 48000;
801     msdDirectConfig1.channel_mask = AUDIO_CHANNEL_OUT_5POINT1;
802 
803     audio_config_base_t msdDirectConfig2 = AUDIO_CONFIG_BASE_INITIALIZER;
804     msdDirectConfig2.format = AUDIO_FORMAT_IEC60958;
805     msdDirectConfig2.sample_rate = 48000;
806     msdDirectConfig2.channel_mask = AUDIO_CHANNEL_INDEX_MASK_24;
807 
808     audio_config_base_t msdNonDirectConfig = AUDIO_CONFIG_BASE_INITIALIZER;
809     msdNonDirectConfig.format = AUDIO_FORMAT_PCM_16_BIT;
810     msdNonDirectConfig.sample_rate = 96000;
811     msdNonDirectConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
812 
813     ASSERT_TRUE(mManager->isDirectOutputSupported(directConfig, attr));
814     ASSERT_FALSE(mManager->isDirectOutputSupported(nonDirectConfig, attr));
815     ASSERT_FALSE(mManager->isDirectOutputSupported(nonExistentConfig, attr));
816     // before setting MSD patches the direct MSD configs return false
817     ASSERT_FALSE(mManager->isDirectOutputSupported(msdDirectConfig1, attr));
818     ASSERT_FALSE(mManager->isDirectOutputSupported(msdDirectConfig2, attr));
819     ASSERT_FALSE(mManager->isDirectOutputSupported(msdNonDirectConfig, attr));
820 
821     DeviceVector outputDevices = mManager->getAvailableOutputDevices();
822     // Remove MSD output device to avoid patching to itself
823     outputDevices.remove(mMsdOutputDevice);
824     mManager->setMsdOutputPatches(&outputDevices);
825 
826     ASSERT_TRUE(mManager->isDirectOutputSupported(directConfig, attr));
827     ASSERT_FALSE(mManager->isDirectOutputSupported(nonDirectConfig, attr));
828     ASSERT_FALSE(mManager->isDirectOutputSupported(nonExistentConfig, attr));
829     // after setting MSD patches the direct MSD configs return true
830     ASSERT_TRUE(mManager->isDirectOutputSupported(msdDirectConfig1, attr));
831     ASSERT_TRUE(mManager->isDirectOutputSupported(msdDirectConfig2, attr));
832     ASSERT_FALSE(mManager->isDirectOutputSupported(msdNonDirectConfig, attr));
833 
834     mManager->releaseMsdOutputPatches(outputDevices);
835 
836     ASSERT_TRUE(mManager->isDirectOutputSupported(directConfig, attr));
837     ASSERT_FALSE(mManager->isDirectOutputSupported(nonDirectConfig, attr));
838     ASSERT_FALSE(mManager->isDirectOutputSupported(nonExistentConfig, attr));
839     // AFTER releasing MSD patches the direct MSD configs return false
840     ASSERT_FALSE(mManager->isDirectOutputSupported(msdDirectConfig1, attr));
841     ASSERT_FALSE(mManager->isDirectOutputSupported(msdDirectConfig2, attr));
842     ASSERT_FALSE(mManager->isDirectOutputSupported(msdNonDirectConfig, attr));
843 }
844 
TEST_P(AudioPolicyManagerTestMsd,GetDirectPlaybackSupportWithMsd)845 TEST_P(AudioPolicyManagerTestMsd, GetDirectPlaybackSupportWithMsd) {
846     const audio_attributes_t attr = {
847         AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
848         AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
849 
850     audio_config_t directConfig = AUDIO_CONFIG_INITIALIZER;
851     directConfig.format = AUDIO_FORMAT_DTS;
852     directConfig.sample_rate = 48000;
853     directConfig.channel_mask = AUDIO_CHANNEL_OUT_5POINT1;
854 
855     audio_config_t nonDirectConfig = AUDIO_CONFIG_INITIALIZER;
856     nonDirectConfig.format = AUDIO_FORMAT_PCM_16_BIT;
857     nonDirectConfig.sample_rate = 48000;
858     nonDirectConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
859 
860     audio_config_t nonExistentConfig = AUDIO_CONFIG_INITIALIZER;
861     nonExistentConfig.format = AUDIO_FORMAT_E_AC3;
862     nonExistentConfig.sample_rate = 48000;
863     nonExistentConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
864 
865     audio_config_t msdDirectConfig1 = AUDIO_CONFIG_INITIALIZER;
866     msdDirectConfig1.format = AUDIO_FORMAT_AC3;
867     msdDirectConfig1.sample_rate = 48000;
868     msdDirectConfig1.channel_mask = AUDIO_CHANNEL_OUT_5POINT1;
869 
870     audio_config_t msdDirectConfig2 = AUDIO_CONFIG_INITIALIZER;
871     msdDirectConfig2.format = AUDIO_FORMAT_IEC60958;
872     msdDirectConfig2.sample_rate = 48000;
873     msdDirectConfig2.channel_mask = AUDIO_CHANNEL_INDEX_MASK_24;
874 
875     audio_config_t msdNonDirectConfig = AUDIO_CONFIG_INITIALIZER;
876     msdNonDirectConfig.format = AUDIO_FORMAT_PCM_16_BIT;
877     msdNonDirectConfig.sample_rate = 96000;
878     msdNonDirectConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
879 
880     ASSERT_EQ(AUDIO_DIRECT_BITSTREAM_SUPPORTED,
881                 mManager->getDirectPlaybackSupport(&attr, &directConfig));
882     ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
883                 mManager->getDirectPlaybackSupport(&attr, &nonDirectConfig));
884     ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
885                 mManager->getDirectPlaybackSupport(&attr, &nonExistentConfig));
886     // before setting MSD patches the direct MSD configs return AUDIO_DIRECT_NOT_SUPPORTED
887     ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
888                 mManager->getDirectPlaybackSupport(&attr, &msdDirectConfig1));
889     ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
890                 mManager->getDirectPlaybackSupport(&attr, &msdDirectConfig2));
891     ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
892                 mManager->getDirectPlaybackSupport(&attr, &msdNonDirectConfig));
893 
894     DeviceVector outputDevices = mManager->getAvailableOutputDevices();
895     // Remove MSD output device to avoid patching to itself
896     outputDevices.remove(mMsdOutputDevice);
897     mManager->setMsdOutputPatches(&outputDevices);
898 
899     ASSERT_EQ(AUDIO_DIRECT_BITSTREAM_SUPPORTED,
900                 mManager->getDirectPlaybackSupport(&attr, &directConfig));
901     ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
902                 mManager->getDirectPlaybackSupport(&attr, &nonDirectConfig));
903     ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
904                 mManager->getDirectPlaybackSupport(&attr, &nonExistentConfig));
905     // after setting MSD patches the direct MSD configs return values according to their flags
906     ASSERT_EQ(AUDIO_DIRECT_OFFLOAD_SUPPORTED,
907                 mManager->getDirectPlaybackSupport(&attr, &msdDirectConfig1));
908     ASSERT_EQ(AUDIO_DIRECT_BITSTREAM_SUPPORTED,
909                 mManager->getDirectPlaybackSupport(&attr, &msdDirectConfig2));
910     ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
911                 mManager->getDirectPlaybackSupport(&attr, &msdNonDirectConfig));
912 
913     mManager->releaseMsdOutputPatches(outputDevices);
914 
915     ASSERT_EQ(AUDIO_DIRECT_BITSTREAM_SUPPORTED,
916                 mManager->getDirectPlaybackSupport(&attr, &directConfig));
917     ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
918                 mManager->getDirectPlaybackSupport(&attr, &nonDirectConfig));
919     ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
920                 mManager->getDirectPlaybackSupport(&attr, &nonExistentConfig));
921     // after releasing MSD patches the direct MSD configs return AUDIO_DIRECT_NOT_SUPPORTED
922     ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
923                 mManager->getDirectPlaybackSupport(&attr, &msdDirectConfig1));
924     ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
925                 mManager->getDirectPlaybackSupport(&attr, &msdDirectConfig2));
926     ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
927                 mManager->getDirectPlaybackSupport(&attr, &msdNonDirectConfig));
928 }
929 
930 class AudioPolicyManagerTestWithConfigurationFile : public AudioPolicyManagerTest {
931 protected:
932     void SetUpManagerConfig() override;
getConfigFile()933     virtual std::string getConfigFile() { return sDefaultConfig; }
934 
935     static const std::string sExecutableDir;
936     static const std::string sDefaultConfig;
937 };
938 
939 const std::string AudioPolicyManagerTestWithConfigurationFile::sExecutableDir =
940         base::GetExecutableDirectory() + "/";
941 
942 const std::string AudioPolicyManagerTestWithConfigurationFile::sDefaultConfig =
943         sExecutableDir + "test_audio_policy_configuration.xml";
944 
SetUpManagerConfig()945 void AudioPolicyManagerTestWithConfigurationFile::SetUpManagerConfig() {
946     auto result = AudioPolicyConfig::loadFromCustomXmlConfigForTests(getConfigFile());
947     ASSERT_TRUE(result.ok());
948     mConfig = result.value();
949 }
950 
TEST_F(AudioPolicyManagerTestWithConfigurationFile,InitSuccess)951 TEST_F(AudioPolicyManagerTestWithConfigurationFile, InitSuccess) {
952     // SetUp must finish with no assertions.
953 }
954 
TEST_F(AudioPolicyManagerTestWithConfigurationFile,Dump)955 TEST_F(AudioPolicyManagerTestWithConfigurationFile, Dump) {
956     dumpToLog();
957 }
958 
TEST_F(AudioPolicyManagerTestWithConfigurationFile,ListAudioPortsHasFlags)959 TEST_F(AudioPolicyManagerTestWithConfigurationFile, ListAudioPortsHasFlags) {
960     // Create an input for VOIP TX because it's not opened automatically like outputs are.
961     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
962     audio_port_handle_t mixPortId = AUDIO_PORT_HANDLE_NONE;
963     audio_source_t source = AUDIO_SOURCE_VOICE_COMMUNICATION;
964     audio_attributes_t attr = {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN, source,
965                                AUDIO_FLAG_NONE, ""};
966     audio_io_handle_t input = AUDIO_PORT_HANDLE_NONE;
967     ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input, AUDIO_SESSION_NONE, 1,
968                                             &selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT,
969                                             AUDIO_CHANNEL_IN_MONO, 8000, AUDIO_INPUT_FLAG_VOIP_TX,
970                                             &mixPortId));
971 
972     std::vector<audio_port_v7> ports;
973     ASSERT_NO_FATAL_FAILURE(
974             getAudioPorts(AUDIO_PORT_TYPE_MIX, AUDIO_PORT_ROLE_NONE, &ports));
975     EXPECT_NE(0, ports.size());
976     bool hasFlags = false, foundPrimary = false, foundVoipRx = false, foundVoipTx = false;
977     for (const auto& port : ports) {
978         if ((port.active_config.config_mask & AUDIO_PORT_CONFIG_FLAGS) != 0) {
979             hasFlags = true;
980             if (port.role == AUDIO_PORT_ROLE_SOURCE) {
981                 if ((port.active_config.flags.output & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
982                     foundPrimary = true;
983                 }
984                 if ((port.active_config.flags.output & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
985                     foundVoipRx = true;
986                 }
987             } else if (port.role == AUDIO_PORT_ROLE_SINK) {
988                 if ((port.active_config.flags.input & AUDIO_INPUT_FLAG_VOIP_TX) != 0) {
989                     foundVoipTx = true;
990                 }
991             }
992         }
993     }
994     EXPECT_TRUE(hasFlags);
995     EXPECT_TRUE(foundPrimary);
996     EXPECT_TRUE(foundVoipRx);
997     EXPECT_TRUE(foundVoipTx);
998 }
999 
TEST_F(AudioPolicyManagerTestWithConfigurationFile,HandleDeviceConfigChange)1000 TEST_F(AudioPolicyManagerTestWithConfigurationFile, HandleDeviceConfigChange) {
1001     {
1002         const auto prevCounter = mClient->getRoutingUpdatedCounter();
1003 
1004         EXPECT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
1005                                                                AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1006                                                                "", "", AUDIO_FORMAT_LDAC));
1007         const auto currCounter = mClient->getRoutingUpdatedCounter();
1008         EXPECT_GT(currCounter, prevCounter);
1009     }
1010     {
1011         const auto prevCounter = mClient->getRoutingUpdatedCounter();
1012         // Update device configuration
1013         EXPECT_EQ(NO_ERROR, mManager->handleDeviceConfigChange(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
1014                                                                "" /*address*/, "" /*name*/,
1015                                                                AUDIO_FORMAT_AAC));
1016 
1017         // As mClient marks isReconfigA2dpSupported to false, device state needs to be toggled for
1018         // config changes to take effect
1019         const auto currCounter = mClient->getRoutingUpdatedCounter();
1020         EXPECT_GT(currCounter, prevCounter);
1021     }
1022 }
1023 
TEST_F(AudioPolicyManagerTestWithConfigurationFile,PreferredMixerAttributes)1024 TEST_F(AudioPolicyManagerTestWithConfigurationFile, PreferredMixerAttributes) {
1025     mClient->addSupportedFormat(AUDIO_FORMAT_PCM_16_BIT);
1026     mClient->addSupportedChannelMask(AUDIO_CHANNEL_OUT_STEREO);
1027     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_USB_DEVICE,
1028                                                            AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1029                                                            "", "", AUDIO_FORMAT_DEFAULT));
1030     auto devices = mManager->getAvailableOutputDevices();
1031     audio_port_handle_t maxPortId = 0;
1032     audio_port_handle_t speakerPortId;
1033     audio_port_handle_t usbPortId;
1034     for (auto device : devices) {
1035         maxPortId = std::max(maxPortId, device->getId());
1036         if (device->type() == AUDIO_DEVICE_OUT_SPEAKER) {
1037             speakerPortId = device->getId();
1038         } else if (device->type() == AUDIO_DEVICE_OUT_USB_DEVICE) {
1039             usbPortId = device->getId();
1040         }
1041     }
1042 
1043     const uid_t uid = 1234;
1044     const uid_t otherUid = 4321;
1045     const audio_attributes_t mediaAttr = {
1046             .content_type = AUDIO_CONTENT_TYPE_MUSIC,
1047             .usage = AUDIO_USAGE_MEDIA,
1048     };
1049     const audio_attributes_t alarmAttr = {
1050             .content_type = AUDIO_CONTENT_TYPE_SONIFICATION,
1051             .usage = AUDIO_USAGE_ALARM,
1052     };
1053 
1054     std::vector<audio_mixer_attributes_t> mixerAttributes;
1055     EXPECT_EQ(NO_ERROR, mManager->getSupportedMixerAttributes(usbPortId, mixerAttributes));
1056     for (const auto attrToSet : mixerAttributes) {
1057         audio_mixer_attributes_t attrFromQuery = AUDIO_MIXER_ATTRIBUTES_INITIALIZER;
1058 
1059         // The given device is not available
1060         EXPECT_EQ(BAD_VALUE,
1061                   mManager->setPreferredMixerAttributes(
1062                           &mediaAttr, maxPortId + 1, uid, &attrToSet));
1063         // The only allowed device is USB
1064         EXPECT_EQ(BAD_VALUE,
1065                   mManager->setPreferredMixerAttributes(
1066                           &mediaAttr, speakerPortId, uid, &attrToSet));
1067         // The only allowed usage is media
1068         EXPECT_EQ(BAD_VALUE,
1069                   mManager->setPreferredMixerAttributes(&alarmAttr, usbPortId, uid, &attrToSet));
1070         // Nothing set yet, must get null when query
1071         EXPECT_EQ(NAME_NOT_FOUND,
1072                   mManager->getPreferredMixerAttributes(&mediaAttr, usbPortId, &attrFromQuery));
1073         EXPECT_EQ(NO_ERROR,
1074                   mManager->setPreferredMixerAttributes(
1075                           &mediaAttr, usbPortId, uid, &attrToSet));
1076         EXPECT_EQ(NO_ERROR,
1077                   mManager->getPreferredMixerAttributes(&mediaAttr, usbPortId, &attrFromQuery));
1078         EXPECT_EQ(attrToSet.config.format, attrFromQuery.config.format);
1079         EXPECT_EQ(attrToSet.config.sample_rate, attrFromQuery.config.sample_rate);
1080         EXPECT_EQ(attrToSet.config.channel_mask, attrFromQuery.config.channel_mask);
1081         EXPECT_EQ(attrToSet.mixer_behavior, attrFromQuery.mixer_behavior);
1082         EXPECT_EQ(NAME_NOT_FOUND,
1083                   mManager->clearPreferredMixerAttributes(&mediaAttr, speakerPortId, uid));
1084         EXPECT_EQ(PERMISSION_DENIED,
1085                   mManager->clearPreferredMixerAttributes(&mediaAttr, usbPortId, otherUid));
1086         EXPECT_EQ(NO_ERROR,
1087                   mManager->clearPreferredMixerAttributes(&mediaAttr, usbPortId, uid));
1088     }
1089 
1090     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_USB_DEVICE,
1091                                                            AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1092                                                            "", "", AUDIO_FORMAT_LDAC));
1093 }
1094 
TEST_F(AudioPolicyManagerTestWithConfigurationFile,RoutingChangedWithPreferredMixerAttributes)1095 TEST_F(AudioPolicyManagerTestWithConfigurationFile, RoutingChangedWithPreferredMixerAttributes) {
1096     mClient->addSupportedFormat(AUDIO_FORMAT_PCM_16_BIT);
1097     mClient->addSupportedChannelMask(AUDIO_CHANNEL_OUT_STEREO);
1098     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_USB_DEVICE,
1099                                                            AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1100                                                            "", "", AUDIO_FORMAT_DEFAULT));
1101     auto devices = mManager->getAvailableOutputDevices();
1102     audio_port_handle_t usbPortId = AUDIO_PORT_HANDLE_NONE;
1103     for (auto device : devices) {
1104         if (device->type() == AUDIO_DEVICE_OUT_USB_DEVICE) {
1105             usbPortId = device->getId();
1106             break;
1107         }
1108     }
1109     EXPECT_NE(AUDIO_PORT_HANDLE_NONE, usbPortId);
1110 
1111     const uid_t uid = 1234;
1112     const audio_attributes_t mediaAttr = {
1113             .content_type = AUDIO_CONTENT_TYPE_MUSIC,
1114             .usage = AUDIO_USAGE_MEDIA,
1115     };
1116 
1117     std::vector<audio_mixer_attributes_t> mixerAttributes;
1118     EXPECT_EQ(NO_ERROR, mManager->getSupportedMixerAttributes(usbPortId, mixerAttributes));
1119     EXPECT_GT(mixerAttributes.size(), 0);
1120     EXPECT_EQ(NO_ERROR,
1121               mManager->setPreferredMixerAttributes(
1122                       &mediaAttr, usbPortId, uid, &mixerAttributes[0]));
1123 
1124     audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
1125     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
1126     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
1127     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
1128             48000, AUDIO_OUTPUT_FLAG_NONE, &output, &portId, mediaAttr,
1129             AUDIO_SESSION_NONE, uid);
1130     status_t status = mManager->startOutput(portId);
1131     if (status == DEAD_OBJECT) {
1132         getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
1133                 48000, AUDIO_OUTPUT_FLAG_NONE, &output, &portId, mediaAttr,
1134                 AUDIO_SESSION_NONE, uid);
1135         status = mManager->startOutput(portId);
1136     }
1137     EXPECT_EQ(NO_ERROR, status);
1138     EXPECT_NE(AUDIO_IO_HANDLE_NONE, output);
1139     EXPECT_NE(nullptr, mManager->getOutputs().valueFor(output));
1140     EXPECT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
1141                                                            AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1142                                                            "", "", AUDIO_FORMAT_LDAC));
1143     // When BT device is connected, it will be selected as media device and trigger routing changed.
1144     // When this happens, existing output that is opened with preferred mixer attributes will be
1145     // closed and reopened with default config.
1146     EXPECT_EQ(nullptr, mManager->getOutputs().valueFor(output));
1147 
1148     EXPECT_EQ(NO_ERROR,
1149               mManager->clearPreferredMixerAttributes(&mediaAttr, usbPortId, uid));
1150 
1151     EXPECT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
1152                                                            AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1153                                                            "", "", AUDIO_FORMAT_LDAC));
1154     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_USB_DEVICE,
1155                                                            AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1156                                                            "", "", AUDIO_FORMAT_LDAC));
1157 }
1158 
TEST_F(AudioPolicyManagerTestWithConfigurationFile,PreferExactConfigForInput)1159 TEST_F(AudioPolicyManagerTestWithConfigurationFile, PreferExactConfigForInput) {
1160     const audio_channel_mask_t deviceChannelMask = AUDIO_CHANNEL_IN_3POINT1;
1161     mClient->addSupportedFormat(AUDIO_FORMAT_PCM_16_BIT);
1162     mClient->addSupportedChannelMask(deviceChannelMask);
1163     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_IN_USB_DEVICE,
1164                                                            AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1165                                                            "", "", AUDIO_FORMAT_DEFAULT));
1166 
1167     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
1168     audio_attributes_t attr = {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
1169                                AUDIO_SOURCE_VOICE_COMMUNICATION,AUDIO_FLAG_NONE, ""};
1170     AudioPolicyInterface::input_type_t inputType;
1171     audio_io_handle_t input = AUDIO_PORT_HANDLE_NONE;
1172     AttributionSourceState attributionSource = createAttributionSourceState(/*uid=*/ 0);
1173     audio_config_base_t requestedConfig = {
1174             .channel_mask = AUDIO_CHANNEL_IN_STEREO,
1175             .format = AUDIO_FORMAT_PCM_16_BIT,
1176             .sample_rate = 48000
1177     };
1178     audio_config_base_t config = requestedConfig;
1179     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
1180     uint32_t *virtualDeviceId = 0;
1181     ASSERT_EQ(OK, mManager->getInputForAttr(
1182             &attr, &input, 1 /*riid*/, AUDIO_SESSION_NONE, attributionSource, &config,
1183             AUDIO_INPUT_FLAG_NONE,
1184             &selectedDeviceId, &inputType, &portId, virtualDeviceId));
1185     ASSERT_NE(AUDIO_PORT_HANDLE_NONE, portId);
1186     ASSERT_TRUE(equals(requestedConfig, config));
1187 
1188     attr = {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
1189             AUDIO_SOURCE_VOICE_COMMUNICATION, AUDIO_FLAG_NONE, ""};
1190     requestedConfig.channel_mask = deviceChannelMask;
1191     config = requestedConfig;
1192     selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
1193     input = AUDIO_PORT_HANDLE_NONE;
1194     portId = AUDIO_PORT_HANDLE_NONE;
1195     ASSERT_EQ(OK, mManager->getInputForAttr(
1196             &attr, &input, 1 /*riid*/, AUDIO_SESSION_NONE, attributionSource, &config,
1197             AUDIO_INPUT_FLAG_NONE,
1198             &selectedDeviceId, &inputType, &portId, virtualDeviceId));
1199     ASSERT_NE(AUDIO_PORT_HANDLE_NONE, portId);
1200     ASSERT_TRUE(equals(requestedConfig, config));
1201 
1202     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_IN_USB_DEVICE,
1203                                                            AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1204                                                            "", "", AUDIO_FORMAT_DEFAULT));
1205 }
1206 
TEST_F(AudioPolicyManagerTestWithConfigurationFile,CheckInputsForDeviceClosesStreams)1207 TEST_F(AudioPolicyManagerTestWithConfigurationFile, CheckInputsForDeviceClosesStreams) {
1208     mClient->addSupportedFormat(AUDIO_FORMAT_PCM_16_BIT);
1209     mClient->addSupportedFormat(AUDIO_FORMAT_PCM_24_BIT_PACKED);
1210     mClient->addSupportedChannelMask(AUDIO_CHANNEL_IN_MONO);
1211     mClient->addSupportedChannelMask(AUDIO_CHANNEL_IN_STEREO);
1212     // Since 'checkInputsForDevice' is called as part of the 'setDeviceConnectionState',
1213     // call it directly here, as we need to ensure that it does not keep all intermediate
1214     // streams opened, as it may cause a rejection from the HAL based on the cap.
1215     const size_t streamCountBefore = mClient->getOpenedInputsCount();
1216     sp<DeviceDescriptor> device = mManager->getHwModules().getDeviceDescriptor(
1217             AUDIO_DEVICE_IN_USB_DEVICE, "", "", AUDIO_FORMAT_DEFAULT, true /*allowToCreate*/);
1218     ASSERT_NE(nullptr, device.get());
1219     EXPECT_EQ(NO_ERROR,
1220             mManager->checkInputsForDevice(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE));
1221     EXPECT_EQ(streamCountBefore, mClient->getOpenedInputsCount());
1222 }
1223 
TEST_F(AudioPolicyManagerTestWithConfigurationFile,SetDeviceConnectionStateClosesStreams)1224 TEST_F(AudioPolicyManagerTestWithConfigurationFile, SetDeviceConnectionStateClosesStreams) {
1225     mClient->addSupportedFormat(AUDIO_FORMAT_PCM_16_BIT);
1226     mClient->addSupportedFormat(AUDIO_FORMAT_PCM_24_BIT_PACKED);
1227     mClient->addSupportedChannelMask(AUDIO_CHANNEL_IN_MONO);
1228     mClient->addSupportedChannelMask(AUDIO_CHANNEL_IN_STEREO);
1229     const size_t streamCountBefore = mClient->getOpenedInputsCount();
1230     EXPECT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_IN_USB_DEVICE,
1231                                                            AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1232                                                            "", "", AUDIO_FORMAT_DEFAULT));
1233     EXPECT_EQ(streamCountBefore, mClient->getOpenedInputsCount());
1234 }
1235 
1236 class AudioPolicyManagerTestDynamicPolicy : public AudioPolicyManagerTestWithConfigurationFile {
1237 protected:
1238     void TearDown() override;
1239 
1240     status_t addPolicyMix(int mixType, int mixFlag, audio_devices_t deviceType,
1241             std::string mixAddress, const audio_config_t& audioConfig,
1242             const std::vector<AudioMixMatchCriterion>& matchCriteria);
1243 
1244     status_t addPolicyMix(const AudioMix& mix);
1245 
1246     status_t removePolicyMixes(const Vector<AudioMix>& mixes);
1247 
1248     std::vector<AudioMix> getRegisteredPolicyMixes();
1249     void clearPolicyMix();
1250     void addPolicyMixAndStartInputForLoopback(
1251             int mixType, int mixFlag, audio_devices_t deviceType, std::string mixAddress,
1252             const audio_config_t& audioConfig,
1253             const std::vector<AudioMixMatchCriterion>& matchCriteria,
1254             audio_session_t session=AUDIO_SESSION_NONE,
1255             audio_config_base_t config=DEFAULT_INPUT_CONFIG,
1256             audio_input_flags_t inputFlags=AUDIO_INPUT_FLAG_NONE);
1257 
1258     Vector<AudioMix> mAudioMixes;
1259     const std::string mMixAddress = "remote_submix_media";
1260 
1261     audio_port_handle_t mLoopbackInputPortId = AUDIO_PORT_HANDLE_NONE;
1262     std::unique_ptr<RecordingActivityTracker> mTracker;
1263     struct audio_port_v7 mInjectionPort;
1264 
1265     constexpr static const audio_config_base_t DEFAULT_INPUT_CONFIG = {
1266             .sample_rate = k48000SamplingRate,
1267             .channel_mask = AUDIO_CHANNEL_IN_STEREO,
1268             .format = AUDIO_FORMAT_PCM_16_BIT
1269     };
1270 };
1271 
TearDown()1272 void AudioPolicyManagerTestDynamicPolicy::TearDown() {
1273     clearPolicyMix();
1274     AudioPolicyManagerTestWithConfigurationFile::TearDown();
1275 }
1276 
addPolicyMix(int mixType,int mixFlag,audio_devices_t deviceType,std::string mixAddress,const audio_config_t & audioConfig,const std::vector<AudioMixMatchCriterion> & matchCriteria={})1277 status_t AudioPolicyManagerTestDynamicPolicy::addPolicyMix(int mixType, int mixFlag,
1278         audio_devices_t deviceType, std::string mixAddress, const audio_config_t& audioConfig,
1279         const std::vector<AudioMixMatchCriterion>& matchCriteria = {}) {
1280     AudioMix myAudioMix(matchCriteria, mixType, audioConfig, mixFlag,
1281             String8(mixAddress.c_str()), 0);
1282     myAudioMix.mDeviceType = deviceType;
1283     myAudioMix.mToken = sp<BBinder>::make();
1284     // Clear mAudioMix before add new one to make sure we don't add already exist mixes.
1285     mAudioMixes.clear();
1286     return addPolicyMix(myAudioMix);
1287 }
1288 
addPolicyMix(const AudioMix & mix)1289 status_t AudioPolicyManagerTestDynamicPolicy::addPolicyMix(const AudioMix& mix) {
1290     mAudioMixes.add(mix);
1291 
1292     // As the policy mixes registration may fail at some case,
1293     // caller need to check the returned status.
1294     status_t ret = mManager->registerPolicyMixes(mAudioMixes);
1295     return ret;
1296 }
1297 
removePolicyMixes(const Vector<AudioMix> & mixes)1298 status_t AudioPolicyManagerTestDynamicPolicy::removePolicyMixes(const Vector<AudioMix>& mixes) {
1299     status_t ret = mManager->unregisterPolicyMixes(mixes);
1300     return ret;
1301 }
1302 
getRegisteredPolicyMixes()1303 std::vector<AudioMix> AudioPolicyManagerTestDynamicPolicy::getRegisteredPolicyMixes() {
1304     std::vector<AudioMix> audioMixes;
1305     if (mManager != nullptr) {
1306         status_t ret = mManager->getRegisteredPolicyMixes(audioMixes);
1307         EXPECT_EQ(NO_ERROR, ret);
1308     }
1309     return audioMixes;
1310 }
1311 
clearPolicyMix()1312 void AudioPolicyManagerTestDynamicPolicy::clearPolicyMix() {
1313     if (mManager != nullptr) {
1314         mManager->stopInput(mLoopbackInputPortId);
1315         mManager->unregisterPolicyMixes(mAudioMixes);
1316     }
1317     mAudioMixes.clear();
1318 }
1319 
addPolicyMixAndStartInputForLoopback(int mixType,int mixFlag,audio_devices_t deviceType,std::string mixAddress,const audio_config_t & audioConfig,const std::vector<AudioMixMatchCriterion> & matchCriteria,audio_session_t session,audio_config_base_t config,audio_input_flags_t inputFlags)1320 void AudioPolicyManagerTestDynamicPolicy::addPolicyMixAndStartInputForLoopback(
1321         int mixType, int mixFlag, audio_devices_t deviceType, std::string mixAddress,
1322         const audio_config_t& audioConfig,
1323         const std::vector<AudioMixMatchCriterion>& matchCriteria, audio_session_t session,
1324         audio_config_base_t config, audio_input_flags_t inputFlags) {
1325     ASSERT_EQ(NO_ERROR,
1326               addPolicyMix(mixType, mixFlag, deviceType, mixAddress, audioConfig, matchCriteria));
1327     if ((mixFlag & MIX_ROUTE_FLAG_LOOP_BACK) != MIX_ROUTE_FLAG_LOOP_BACK) {
1328         return;
1329     }
1330 
1331     mTracker.reset(new RecordingActivityTracker());
1332     struct audio_port_v7 extractionPort;
1333     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SOURCE, AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1334                                mixAddress, &extractionPort));
1335     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
1336     audio_source_t source = AUDIO_SOURCE_REMOTE_SUBMIX;
1337     audio_attributes_t attr = {
1338             AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN, source, AUDIO_FLAG_NONE, ""};
1339     std::string tags = "addr=" + mMixAddress;
1340     audio_io_handle_t input = AUDIO_PORT_HANDLE_NONE;
1341     strncpy(attr.tags, tags.c_str(), AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1);
1342     ASSERT_NO_FATAL_FAILURE(
1343             getInputForAttr(attr, &input, session, mTracker->getRiid(),
1344                             &selectedDeviceId, config.format, config.channel_mask,
1345                             config.sample_rate, inputFlags, &mLoopbackInputPortId));
1346     ASSERT_EQ(NO_ERROR, mManager->startInput(mLoopbackInputPortId));
1347     ASSERT_EQ(extractionPort.id, selectedDeviceId);
1348 
1349     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1350                                mMixAddress, &mInjectionPort));
1351 }
1352 
TEST_F(AudioPolicyManagerTestDynamicPolicy,InitSuccess)1353 TEST_F(AudioPolicyManagerTestDynamicPolicy, InitSuccess) {
1354     // SetUp must finish with no assertions
1355 }
1356 
TEST_F(AudioPolicyManagerTestDynamicPolicy,Dump)1357 TEST_F(AudioPolicyManagerTestDynamicPolicy, Dump) {
1358     dumpToLog();
1359 }
1360 
TEST_F(AudioPolicyManagerTestDynamicPolicy,RegisterPolicyMixes)1361 TEST_F(AudioPolicyManagerTestDynamicPolicy, RegisterPolicyMixes) {
1362     status_t ret;
1363     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1364 
1365     // Only capture of playback is allowed in LOOP_BACK &RENDER mode
1366     ret = addPolicyMix(MIX_TYPE_RECORDERS, MIX_ROUTE_FLAG_LOOP_BACK_AND_RENDER,
1367             AUDIO_DEVICE_OUT_REMOTE_SUBMIX, "", audioConfig);
1368     ASSERT_EQ(INVALID_OPERATION, ret);
1369 
1370     // Fail due to the device is already connected.
1371     clearPolicyMix();
1372     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
1373             AUDIO_DEVICE_OUT_REMOTE_SUBMIX, "", audioConfig);
1374     ASSERT_EQ(INVALID_OPERATION, ret);
1375 
1376     // The first time to register policy mixes with valid parameter should succeed.
1377     clearPolicyMix();
1378     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1379     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
1380     audioConfig.sample_rate = k48000SamplingRate;
1381     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
1382             AUDIO_DEVICE_OUT_REMOTE_SUBMIX, mMixAddress, audioConfig);
1383     ASSERT_EQ(NO_ERROR, ret);
1384     // Registering the same policy mixes should fail.
1385     ret = mManager->registerPolicyMixes(mAudioMixes);
1386     ASSERT_EQ(INVALID_OPERATION, ret);
1387 
1388     // Registration should fail due to device not found.
1389     // Note that earpiece is not present in the test configuration file.
1390     // This will need to be updated if earpiece is added in the test configuration file.
1391     clearPolicyMix();
1392     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
1393             AUDIO_DEVICE_OUT_EARPIECE, "", audioConfig);
1394     ASSERT_EQ(INVALID_OPERATION, ret);
1395 
1396     // Registration should fail due to output not found.
1397     clearPolicyMix();
1398     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
1399             AUDIO_DEVICE_OUT_REMOTE_SUBMIX, "", audioConfig);
1400     ASSERT_EQ(INVALID_OPERATION, ret);
1401 
1402     // The first time to register valid loopback policy mix should succeed.
1403     clearPolicyMix();
1404     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
1405             AUDIO_DEVICE_OUT_REMOTE_SUBMIX, "addr", audioConfig);
1406     ASSERT_EQ(NO_ERROR, ret);
1407     // Registering the render policy for the loopback address should succeed.
1408     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
1409             AUDIO_DEVICE_OUT_REMOTE_SUBMIX, "addr", audioConfig);
1410     ASSERT_EQ(INVALID_OPERATION, ret);
1411 }
1412 
TEST_F(AudioPolicyManagerTestDynamicPolicy,UnregisterPolicyMixes)1413 TEST_F(AudioPolicyManagerTestDynamicPolicy, UnregisterPolicyMixes) {
1414     status_t ret;
1415     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1416 
1417     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1418     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
1419     audioConfig.sample_rate = k48000SamplingRate;
1420     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
1421             AUDIO_DEVICE_OUT_REMOTE_SUBMIX, mMixAddress, audioConfig);
1422     ASSERT_EQ(NO_ERROR, ret);
1423 
1424     // After successfully registering policy mixes, it should be able to unregister.
1425     ret = mManager->unregisterPolicyMixes(mAudioMixes);
1426     ASSERT_EQ(NO_ERROR, ret);
1427 
1428     // After unregistering policy mixes successfully, it should fail unregistering
1429     // the same policy mixes as they are not registered.
1430     ret = mManager->unregisterPolicyMixes(mAudioMixes);
1431     ASSERT_EQ(INVALID_OPERATION, ret);
1432 }
1433 
TEST_F(AudioPolicyManagerTestDynamicPolicy,RegisterPolicyWithConsistentMixSucceeds)1434 TEST_F(AudioPolicyManagerTestDynamicPolicy, RegisterPolicyWithConsistentMixSucceeds) {
1435     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1436     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1437     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
1438     audioConfig.sample_rate = k48000SamplingRate;
1439 
1440     std::vector<AudioMixMatchCriterion> mixMatchCriteria = {
1441         createUidCriterion(/*uid=*/42),
1442         createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/true)};
1443     status_t ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
1444                                 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, mMixAddress, audioConfig,
1445                                 mixMatchCriteria);
1446     ASSERT_EQ(NO_ERROR, ret);
1447 }
1448 
TEST_F(AudioPolicyManagerTestDynamicPolicy,RegisterPolicyWithInconsistentMixFails)1449 TEST_F(AudioPolicyManagerTestDynamicPolicy, RegisterPolicyWithInconsistentMixFails) {
1450     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1451     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1452     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
1453     audioConfig.sample_rate = k48000SamplingRate;
1454 
1455     std::vector<AudioMixMatchCriterion> mixMatchCriteria = {
1456         createUidCriterion(/*uid=*/42),
1457         createUidCriterion(/*uid=*/1235, /*exclude=*/true),
1458         createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/true)};
1459     status_t ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
1460                                 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, mMixAddress, audioConfig,
1461                                 mixMatchCriteria);
1462     ASSERT_EQ(INVALID_OPERATION, ret);
1463 }
1464 
TEST_F_WITH_FLAGS(AudioPolicyManagerTestDynamicPolicy,RegisterInvalidMixesDoesNotImpactPriorMixes,REQUIRES_FLAGS_ENABLED (ACONFIG_FLAG (android::media::audiopolicy,audio_mix_test_api),ACONFIG_FLAG (android::media::audiopolicy,audio_mix_ownership)))1465 TEST_F_WITH_FLAGS(
1466         AudioPolicyManagerTestDynamicPolicy,
1467         RegisterInvalidMixesDoesNotImpactPriorMixes,
1468         REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(android::media::audiopolicy, audio_mix_test_api),
1469                                ACONFIG_FLAG(android::media::audiopolicy, audio_mix_ownership))
1470 ) {
1471     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1472     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1473     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
1474     audioConfig.sample_rate = k48000SamplingRate;
1475 
1476     std::vector<AudioMixMatchCriterion> validMixMatchCriteria = {
1477             createUidCriterion(/*uid=*/42),
1478             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/true)};
1479     AudioMix validAudioMix(validMixMatchCriteria, MIX_TYPE_PLAYERS, audioConfig,
1480                            MIX_ROUTE_FLAG_LOOP_BACK, String8(mMixAddress.c_str()), 0);
1481     validAudioMix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1482 
1483     mAudioMixes.clear();
1484     status_t ret = addPolicyMix(validAudioMix);
1485 
1486     ASSERT_EQ(NO_ERROR, ret);
1487 
1488     std::vector<AudioMix> registeredMixes = getRegisteredPolicyMixes();
1489     ASSERT_EQ(1, registeredMixes.size());
1490 
1491     std::vector<AudioMixMatchCriterion> invalidMixMatchCriteria = {
1492             createUidCriterion(/*uid=*/42),
1493             createUidCriterion(/*uid=*/1235, /*exclude=*/true),
1494             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/true)};
1495 
1496     AudioMix invalidAudioMix(invalidMixMatchCriteria, MIX_TYPE_PLAYERS, audioConfig,
1497                              MIX_ROUTE_FLAG_LOOP_BACK, String8(mMixAddress.c_str()), 0);
1498     validAudioMix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1499 
1500     ret = addPolicyMix(invalidAudioMix);
1501 
1502     ASSERT_EQ(INVALID_OPERATION, ret);
1503 
1504     std::vector<AudioMix> remainingMixes = getRegisteredPolicyMixes();
1505     ASSERT_EQ(registeredMixes.size(), remainingMixes.size());
1506 }
1507 
TEST_F_WITH_FLAGS(AudioPolicyManagerTestDynamicPolicy,UnregisterInvalidMixesReturnsError,REQUIRES_FLAGS_ENABLED (ACONFIG_FLAG (android::media::audiopolicy,audio_mix_test_api),ACONFIG_FLAG (android::media::audiopolicy,audio_mix_ownership)))1508 TEST_F_WITH_FLAGS(
1509         AudioPolicyManagerTestDynamicPolicy,
1510         UnregisterInvalidMixesReturnsError,
1511         REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(android::media::audiopolicy, audio_mix_test_api),
1512                                ACONFIG_FLAG(android::media::audiopolicy, audio_mix_ownership))
1513 ) {
1514     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1515     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1516     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
1517     audioConfig.sample_rate = k48000SamplingRate;
1518 
1519     std::vector<AudioMixMatchCriterion> validMixMatchCriteria = {
1520             createUidCriterion(/*uid=*/42),
1521             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/true)};
1522     AudioMix validAudioMix(validMixMatchCriteria, MIX_TYPE_PLAYERS, audioConfig,
1523                            MIX_ROUTE_FLAG_LOOP_BACK, String8(mMixAddress.c_str()), 0);
1524     validAudioMix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1525 
1526     mAudioMixes.clear();
1527     status_t ret = addPolicyMix(validAudioMix);
1528 
1529     ASSERT_EQ(NO_ERROR, ret);
1530 
1531     std::vector<AudioMix> registeredMixes = getRegisteredPolicyMixes();
1532     ASSERT_EQ(1, registeredMixes.size());
1533 
1534     std::vector<AudioMixMatchCriterion> invalidMixMatchCriteria = {
1535             createUidCriterion(/*uid=*/42),
1536             createUidCriterion(/*uid=*/1235, /*exclude=*/true),
1537             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/true)};
1538 
1539     AudioMix invalidAudioMix(invalidMixMatchCriteria, MIX_TYPE_PLAYERS, audioConfig,
1540                              MIX_ROUTE_FLAG_LOOP_BACK, String8(mMixAddress.c_str()), 0);
1541     invalidAudioMix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1542 
1543     Vector<AudioMix> mixes;
1544     mixes.add(invalidAudioMix);
1545     mixes.add(validAudioMix);
1546     ret = removePolicyMixes(mixes);
1547 
1548     ASSERT_EQ(INVALID_OPERATION, ret);
1549 
1550     std::vector<AudioMix> remainingMixes = getRegisteredPolicyMixes();
1551     EXPECT_THAT(remainingMixes, IsEmpty());
1552 }
1553 
TEST_F_WITH_FLAGS(AudioPolicyManagerTestDynamicPolicy,GetRegisteredPolicyMixes,REQUIRES_FLAGS_ENABLED (ACONFIG_FLAG (android::media::audiopolicy,audio_mix_test_api)))1554 TEST_F_WITH_FLAGS(
1555         AudioPolicyManagerTestDynamicPolicy,
1556         GetRegisteredPolicyMixes,
1557         REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(android::media::audiopolicy, audio_mix_test_api))
1558 ) {
1559     std::vector<AudioMix> mixes = getRegisteredPolicyMixes();
1560     EXPECT_THAT(mixes, IsEmpty());
1561 }
1562 
TEST_F_WITH_FLAGS(AudioPolicyManagerTestDynamicPolicy,AddPolicyMixAndVerifyGetRegisteredPolicyMixes,REQUIRES_FLAGS_ENABLED (ACONFIG_FLAG (android::media::audiopolicy,audio_mix_test_api)))1563 TEST_F_WITH_FLAGS(AudioPolicyManagerTestDynamicPolicy,
1564         AddPolicyMixAndVerifyGetRegisteredPolicyMixes,
1565         REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(android::media::audiopolicy, audio_mix_test_api))
1566 ) {
1567     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1568     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1569     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
1570     audioConfig.sample_rate = k48000SamplingRate;
1571 
1572     std::vector<AudioMixMatchCriterion> mixMatchCriteria = {
1573             createUidCriterion(/*uid=*/42),
1574             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/true)};
1575     status_t ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
1576                                 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, mMixAddress, audioConfig,
1577                                 mixMatchCriteria);
1578     ASSERT_EQ(NO_ERROR, ret);
1579 
1580     std::vector<AudioMix> mixes = getRegisteredPolicyMixes();
1581     ASSERT_EQ(mixes.size(), 1);
1582 
1583     const AudioMix& mix = mixes[0];
1584     ASSERT_EQ(mix.mCriteria.size(), mixMatchCriteria.size());
1585     for (uint32_t i = 0; i < mixMatchCriteria.size(); i++) {
1586         EXPECT_EQ(mix.mCriteria[i].mRule, mixMatchCriteria[i].mRule);
1587         EXPECT_EQ(mix.mCriteria[i].mValue.mUsage, mixMatchCriteria[i].mValue.mUsage);
1588     }
1589     EXPECT_EQ(mix.mDeviceType, AUDIO_DEVICE_OUT_REMOTE_SUBMIX);
1590     EXPECT_EQ(mix.mRouteFlags, MIX_ROUTE_FLAG_LOOP_BACK);
1591     EXPECT_EQ(mix.mMixType, MIX_TYPE_PLAYERS);
1592     EXPECT_EQ(mix.mFormat.channel_mask, audioConfig.channel_mask);
1593     EXPECT_EQ(mix.mFormat.format, audioConfig.format);
1594     EXPECT_EQ(mix.mFormat.sample_rate, audioConfig.sample_rate);
1595     EXPECT_EQ(mix.mFormat.frame_count, audioConfig.frame_count);
1596 }
1597 
1598 class AudioPolicyManagerTestForHdmi
1599         : public AudioPolicyManagerTestWithConfigurationFile,
1600           public testing::WithParamInterface<audio_format_t> {
1601 protected:
1602     void SetUp() override;
getConfigFile()1603     std::string getConfigFile() override { return sTvConfig; }
1604     std::map<audio_format_t, bool> getSurroundFormatsHelper();
1605     std::vector<audio_format_t> getReportedSurroundFormatsHelper();
1606     std::unordered_set<audio_format_t> getFormatsFromPorts();
1607     void TearDown() override;
1608 
1609     static const std::string sTvConfig;
1610 
1611 };
1612 
1613 const std::string AudioPolicyManagerTestForHdmi::sTvConfig =
1614         AudioPolicyManagerTestForHdmi::sExecutableDir +
1615         "test_settop_box_surround_configuration.xml";
1616 
SetUp()1617 void AudioPolicyManagerTestForHdmi::SetUp() {
1618     ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTest::SetUp());
1619     mClient->addSupportedFormat(AUDIO_FORMAT_AC3);
1620     mClient->addSupportedFormat(AUDIO_FORMAT_E_AC3);
1621     mClient->addSupportedChannelMask(AUDIO_CHANNEL_OUT_STEREO);
1622     mManager->setDeviceConnectionState(
1623             AUDIO_DEVICE_OUT_HDMI, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1624             "" /*address*/, "" /*name*/, AUDIO_FORMAT_DEFAULT);
1625 }
1626 
TearDown()1627 void AudioPolicyManagerTestForHdmi::TearDown() {
1628     mManager->setDeviceConnectionState(
1629             AUDIO_DEVICE_OUT_HDMI, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1630             "" /*address*/, "" /*name*/, AUDIO_FORMAT_DEFAULT);
1631     AudioPolicyManagerTest::TearDown();
1632 }
1633 
1634 std::map<audio_format_t, bool>
getSurroundFormatsHelper()1635         AudioPolicyManagerTestForHdmi::getSurroundFormatsHelper() {
1636     unsigned int numSurroundFormats = 0;
1637     std::map<audio_format_t, bool> surroundFormatsMap;
1638     status_t ret = mManager->getSurroundFormats(
1639             &numSurroundFormats, nullptr /* surroundFormats */,
1640             nullptr /* surroundFormatsEnabled */);
1641     EXPECT_EQ(NO_ERROR, ret);
1642     if (ret != NO_ERROR) {
1643         return surroundFormatsMap;
1644     }
1645     audio_format_t surroundFormats[numSurroundFormats];
1646     memset(surroundFormats, 0, sizeof(audio_format_t) * numSurroundFormats);
1647     bool surroundFormatsEnabled[numSurroundFormats];
1648     memset(surroundFormatsEnabled, 0, sizeof(bool) * numSurroundFormats);
1649     ret = mManager->getSurroundFormats(
1650             &numSurroundFormats, surroundFormats, surroundFormatsEnabled);
1651     EXPECT_EQ(NO_ERROR, ret);
1652     if (ret != NO_ERROR) {
1653         return surroundFormatsMap;
1654     }
1655     for (int i = 0; i< numSurroundFormats; i++) {
1656         surroundFormatsMap[surroundFormats[i]] = surroundFormatsEnabled[i];
1657     }
1658     return surroundFormatsMap;
1659 }
1660 
getReportedSurroundFormatsHelper()1661 std::vector<audio_format_t> AudioPolicyManagerTestForHdmi::getReportedSurroundFormatsHelper() {
1662     unsigned int numSurroundFormats = 0;
1663     std::vector<audio_format_t>  surroundFormatsVector;
1664     status_t ret = mManager->getReportedSurroundFormats(
1665             &numSurroundFormats, nullptr /* surroundFormats */);
1666     EXPECT_EQ(NO_ERROR, ret);
1667     if (ret != NO_ERROR) {
1668         return surroundFormatsVector;
1669     }
1670     audio_format_t surroundFormats[numSurroundFormats];
1671     memset(surroundFormats, 0, sizeof(audio_format_t) * numSurroundFormats);
1672     ret = mManager->getReportedSurroundFormats(&numSurroundFormats, surroundFormats);
1673     EXPECT_EQ(NO_ERROR, ret);
1674     if (ret != NO_ERROR) {
1675         return surroundFormatsVector;
1676     }
1677     for (const auto &surroundFormat : surroundFormats) {
1678         surroundFormatsVector.push_back(surroundFormat);
1679     }
1680     return surroundFormatsVector;
1681 }
1682 
1683 std::unordered_set<audio_format_t>
getFormatsFromPorts()1684         AudioPolicyManagerTestForHdmi::getFormatsFromPorts() {
1685     uint32_t numPorts = 0;
1686     uint32_t generation1;
1687     status_t ret;
1688     std::unordered_set<audio_format_t> formats;
1689     ret = mManager->listAudioPorts(
1690             AUDIO_PORT_ROLE_SINK, AUDIO_PORT_TYPE_DEVICE, &numPorts, nullptr, &generation1);
1691     EXPECT_EQ(NO_ERROR, ret) << "mManager->listAudioPorts returned error";
1692     if (ret != NO_ERROR) {
1693         return formats;
1694     }
1695     struct audio_port_v7 ports[numPorts];
1696     ret = mManager->listAudioPorts(
1697             AUDIO_PORT_ROLE_SINK, AUDIO_PORT_TYPE_DEVICE, &numPorts, ports, &generation1);
1698     EXPECT_EQ(NO_ERROR, ret) << "mManager->listAudioPorts returned error";
1699     if (ret != NO_ERROR) {
1700         return formats;
1701     }
1702     for (const auto &port : ports) {
1703         for (size_t i = 0; i < port.num_audio_profiles; ++i) {
1704             formats.insert(port.audio_profiles[i].format);
1705         }
1706     }
1707     return formats;
1708 }
1709 
TEST_P(AudioPolicyManagerTestForHdmi,GetSurroundFormatsReturnsSupportedFormats)1710 TEST_P(AudioPolicyManagerTestForHdmi, GetSurroundFormatsReturnsSupportedFormats) {
1711     mManager->setForceUse(
1712             AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS);
1713     auto surroundFormats = getSurroundFormatsHelper();
1714     ASSERT_EQ(1, surroundFormats.count(GetParam()));
1715 }
1716 
TEST_P(AudioPolicyManagerTestForHdmi,GetSurroundFormatsReturnsManipulatedFormats)1717 TEST_P(AudioPolicyManagerTestForHdmi,
1718         GetSurroundFormatsReturnsManipulatedFormats) {
1719     mManager->setForceUse(
1720             AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL);
1721 
1722     status_t ret =
1723             mManager->setSurroundFormatEnabled(GetParam(), false /*enabled*/);
1724     ASSERT_EQ(NO_ERROR, ret);
1725     auto surroundFormats = getSurroundFormatsHelper();
1726     ASSERT_EQ(1, surroundFormats.count(GetParam()));
1727     ASSERT_FALSE(surroundFormats[GetParam()]);
1728 
1729     ret = mManager->setSurroundFormatEnabled(GetParam(), true /*enabled*/);
1730     ASSERT_EQ(NO_ERROR, ret);
1731     surroundFormats = getSurroundFormatsHelper();
1732     ASSERT_EQ(1, surroundFormats.count(GetParam()));
1733     ASSERT_TRUE(surroundFormats[GetParam()]);
1734 
1735     ret = mManager->setSurroundFormatEnabled(GetParam(), false /*enabled*/);
1736     ASSERT_EQ(NO_ERROR, ret);
1737     surroundFormats = getSurroundFormatsHelper();
1738     ASSERT_EQ(1, surroundFormats.count(GetParam()));
1739     ASSERT_FALSE(surroundFormats[GetParam()]);
1740 }
1741 
TEST_P(AudioPolicyManagerTestForHdmi,ListAudioPortsReturnManipulatedHdmiFormats)1742 TEST_P(AudioPolicyManagerTestForHdmi,
1743         ListAudioPortsReturnManipulatedHdmiFormats) {
1744     mManager->setForceUse(
1745             AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL);
1746 
1747     ASSERT_EQ(NO_ERROR, mManager->setSurroundFormatEnabled(GetParam(), true /*enabled*/));
1748     auto formats = getFormatsFromPorts();
1749     ASSERT_EQ(1, formats.count(GetParam()));
1750 
1751     ASSERT_EQ(NO_ERROR, mManager->setSurroundFormatEnabled(GetParam(), false /*enabled*/));
1752     formats = getFormatsFromPorts();
1753     ASSERT_EQ(0, formats.count(GetParam()));
1754 }
1755 
TEST_P(AudioPolicyManagerTestForHdmi,GetReportedSurroundFormatsReturnsHdmiReportedFormats)1756 TEST_P(AudioPolicyManagerTestForHdmi,
1757         GetReportedSurroundFormatsReturnsHdmiReportedFormats) {
1758     mManager->setForceUse(
1759             AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS);
1760     auto surroundFormats = getReportedSurroundFormatsHelper();
1761     ASSERT_EQ(1, std::count(surroundFormats.begin(), surroundFormats.end(), GetParam()));
1762 }
1763 
TEST_P(AudioPolicyManagerTestForHdmi,GetReportedSurroundFormatsReturnsNonManipulatedHdmiReportedFormats)1764 TEST_P(AudioPolicyManagerTestForHdmi,
1765         GetReportedSurroundFormatsReturnsNonManipulatedHdmiReportedFormats) {
1766     mManager->setForceUse(
1767             AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL);
1768 
1769     status_t ret = mManager->setSurroundFormatEnabled(GetParam(), false /*enabled*/);
1770     ASSERT_EQ(NO_ERROR, ret);
1771     auto surroundFormats = getReportedSurroundFormatsHelper();
1772     ASSERT_EQ(1, std::count(surroundFormats.begin(), surroundFormats.end(), GetParam()));
1773 
1774     ret = mManager->setSurroundFormatEnabled(GetParam(), true /*enabled*/);
1775     ASSERT_EQ(NO_ERROR, ret);
1776     surroundFormats = getReportedSurroundFormatsHelper();
1777     ASSERT_EQ(1, std::count(surroundFormats.begin(), surroundFormats.end(), GetParam()));
1778 }
1779 
TEST_P(AudioPolicyManagerTestForHdmi,GetSurroundFormatsIgnoresSupportedFormats)1780 TEST_P(AudioPolicyManagerTestForHdmi, GetSurroundFormatsIgnoresSupportedFormats) {
1781     mManager->setForceUse(
1782             AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER);
1783     auto surroundFormats = getSurroundFormatsHelper();
1784     ASSERT_EQ(1, surroundFormats.count(GetParam()));
1785     ASSERT_FALSE(surroundFormats[GetParam()]);
1786 }
1787 
1788 INSTANTIATE_TEST_SUITE_P(SurroundFormatSupport, AudioPolicyManagerTestForHdmi,
1789         testing::Values(AUDIO_FORMAT_AC3, AUDIO_FORMAT_E_AC3),
__anon25e8343b0402(const ::testing::TestParamInfo<AudioPolicyManagerTestForHdmi::ParamType>& info) 1790         [](const ::testing::TestParamInfo<AudioPolicyManagerTestForHdmi::ParamType>& info) {
1791             return audio_format_to_string(info.param);
1792         });
1793 
1794 class AudioPolicyManagerTestDPNoRemoteSubmixModule : public AudioPolicyManagerTestDynamicPolicy {
1795 protected:
getConfigFile()1796     std::string getConfigFile() override { return sPrimaryOnlyConfig; }
1797 
1798     static const std::string sPrimaryOnlyConfig;
1799 };
1800 
1801 const std::string AudioPolicyManagerTestDPNoRemoteSubmixModule::sPrimaryOnlyConfig =
1802         sExecutableDir + "test_audio_policy_primary_only_configuration.xml";
1803 
TEST_F(AudioPolicyManagerTestDPNoRemoteSubmixModule,InitSuccess)1804 TEST_F(AudioPolicyManagerTestDPNoRemoteSubmixModule, InitSuccess) {
1805     // SetUp must finish with no assertions.
1806 }
1807 
TEST_F(AudioPolicyManagerTestDPNoRemoteSubmixModule,Dump)1808 TEST_F(AudioPolicyManagerTestDPNoRemoteSubmixModule, Dump) {
1809     dumpToLog();
1810 }
1811 
TEST_F(AudioPolicyManagerTestDPNoRemoteSubmixModule,RegistrationFailure)1812 TEST_F(AudioPolicyManagerTestDPNoRemoteSubmixModule, RegistrationFailure) {
1813     // Registration/Unregistration should fail due to module for remote submix not found.
1814     status_t ret;
1815     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1816     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1817     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
1818     audioConfig.sample_rate = k48000SamplingRate;
1819     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
1820             AUDIO_DEVICE_OUT_REMOTE_SUBMIX, "", audioConfig);
1821     ASSERT_EQ(INVALID_OPERATION, ret);
1822 
1823     ret = mManager->unregisterPolicyMixes(mAudioMixes);
1824     ASSERT_EQ(INVALID_OPERATION, ret);
1825 }
1826 
1827 struct DPTestParam {
DPTestParamDPTestParam1828     DPTestParam(const std::vector<AudioMixMatchCriterion>& mixCriteria,
1829                 bool expected_match = false)
1830      : mixCriteria(mixCriteria), attributes(defaultAttr), session(AUDIO_SESSION_NONE),
1831        expected_match(expected_match) {}
1832 
withUsageDPTestParam1833     DPTestParam& withUsage(audio_usage_t usage) {
1834         attributes.usage = usage;
1835         return *this;
1836     }
1837 
withTagsDPTestParam1838     DPTestParam& withTags(const char *tags) {
1839         std::strncpy(attributes.tags, tags, sizeof(attributes.tags));
1840         return *this;
1841     }
1842 
withSourceDPTestParam1843     DPTestParam& withSource(audio_source_t source) {
1844         attributes.source = source;
1845         return *this;
1846     }
1847 
withSessionIdDPTestParam1848     DPTestParam& withSessionId(audio_session_t sessionId) {
1849         session = sessionId;
1850         return *this;
1851     }
1852 
1853     std::vector<AudioMixMatchCriterion> mixCriteria;
1854     audio_attributes_t attributes;
1855     audio_session_t session;
1856     bool expected_match;
1857 };
1858 
1859 class AudioPolicyManagerTestDPPlaybackReRouting : public AudioPolicyManagerTestDynamicPolicy,
1860         public testing::WithParamInterface<DPTestParam> {
1861 protected:
1862     void SetUp() override;
1863 };
1864 
SetUp()1865 void AudioPolicyManagerTestDPPlaybackReRouting::SetUp() {
1866     ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTestDynamicPolicy::SetUp());
1867 
1868     mTracker.reset(new RecordingActivityTracker());
1869 
1870     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1871     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1872     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
1873     audioConfig.sample_rate = k48000SamplingRate;
1874 
1875     DPTestParam param = GetParam();
1876     ASSERT_NO_FATAL_FAILURE(
1877             addPolicyMixAndStartInputForLoopback(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
1878             AUDIO_DEVICE_OUT_REMOTE_SUBMIX, mMixAddress, audioConfig, param.mixCriteria,
1879             param.session));
1880 }
1881 
TEST_P(AudioPolicyManagerTestDPPlaybackReRouting,PlaybackReRouting)1882 TEST_P(AudioPolicyManagerTestDPPlaybackReRouting, PlaybackReRouting) {
1883     const DPTestParam param = GetParam();
1884     const audio_attributes_t& attr = param.attributes;
1885 
1886     audio_port_handle_t playbackRoutedPortId = AUDIO_PORT_HANDLE_NONE;
1887     getOutputForAttr(&playbackRoutedPortId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
1888             k48000SamplingRate, AUDIO_OUTPUT_FLAG_NONE, nullptr /*output*/, nullptr /*portId*/,
1889             attr, param.session);
1890     if (param.expected_match) {
1891         EXPECT_EQ(mInjectionPort.id, playbackRoutedPortId);
1892     } else {
1893         EXPECT_NE(mInjectionPort.id, playbackRoutedPortId);
1894     }
1895 }
1896 
1897 const std::vector<AudioMixMatchCriterion> USAGE_MEDIA_ALARM_CRITERIA = {
1898             createUsageCriterion(AUDIO_USAGE_MEDIA),
1899             createUsageCriterion(AUDIO_USAGE_ALARM)
1900 };
1901 
1902 INSTANTIATE_TEST_SUITE_P(
1903     PlaybackReroutingUsageMatch,
1904     AudioPolicyManagerTestDPPlaybackReRouting,
1905     testing::Values(
1906         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1907             .withUsage(AUDIO_USAGE_MEDIA),
1908         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1909             .withUsage(AUDIO_USAGE_MEDIA).withTags("addr=other"),
1910         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1911             .withUsage(AUDIO_USAGE_ALARM),
1912         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1913             .withUsage(AUDIO_USAGE_VOICE_COMMUNICATION),
1914         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1915             .withUsage(AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING),
1916         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1917             .withUsage(AUDIO_USAGE_NOTIFICATION),
1918         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1919             .withUsage(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE),
1920         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1921             .withUsage(AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST),
1922         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1923             .withUsage(AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT),
1924         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1925             .withUsage(AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED),
1926         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1927             .withUsage(AUDIO_USAGE_NOTIFICATION_EVENT),
1928         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1929             .withUsage(AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY),
1930         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1931             .withUsage(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE),
1932         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1933             .withUsage(AUDIO_USAGE_ASSISTANCE_SONIFICATION),
1934         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1935             .withUsage(AUDIO_USAGE_GAME),
1936         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1937             .withUsage(AUDIO_USAGE_ASSISTANT)));
1938 
1939 INSTANTIATE_TEST_SUITE_P(
1940     PlaybackReroutingAddressPriorityMatch,
1941     AudioPolicyManagerTestDPPlaybackReRouting,
1942     testing::Values(
1943         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1944             .withUsage(AUDIO_USAGE_MEDIA).withTags("addr=remote_submix_media"),
1945         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1946             .withUsage(AUDIO_USAGE_VOICE_COMMUNICATION).withTags("addr=remote_submix_media"),
1947         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1948             .withUsage(AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING)
1949             .withTags("addr=remote_submix_media"),
1950         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1951             .withUsage(AUDIO_USAGE_ALARM)
1952             .withTags("addr=remote_submix_media"),
1953         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1954             .withUsage(AUDIO_USAGE_NOTIFICATION)
1955             .withTags("addr=remote_submix_media"),
1956         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1957             .withUsage(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE)
1958             .withTags("addr=remote_submix_media"),
1959         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1960             .withUsage(AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST)
1961             .withTags("addr=remote_submix_media"),
1962         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1963             .withUsage(AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT)
1964             .withTags("addr=remote_submix_media"),
1965         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1966             .withUsage(AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED)
1967             .withTags("addr=remote_submix_media"),
1968         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1969             .withUsage(AUDIO_USAGE_NOTIFICATION_EVENT)
1970             .withTags("addr=remote_submix_media"),
1971         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1972             .withUsage(AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY)
1973             .withTags("addr=remote_submix_media"),
1974         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1975             .withUsage(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE)
1976             .withTags("addr=remote_submix_media"),
1977         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1978             .withUsage(AUDIO_USAGE_ASSISTANCE_SONIFICATION)
1979             .withTags("addr=remote_submix_media"),
1980         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1981             .withUsage(AUDIO_USAGE_GAME)
1982             .withTags("addr=remote_submix_media"),
1983         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1984             .withUsage(AUDIO_USAGE_VIRTUAL_SOURCE)
1985             .withTags("addr=remote_submix_media"),
1986         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1987             .withUsage(AUDIO_USAGE_ASSISTANT)
1988             .withTags("addr=remote_submix_media"),
1989         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1990             .withUsage(AUDIO_USAGE_ASSISTANT)
1991             .withTags("sometag;addr=remote_submix_media;othertag=somevalue"),
1992         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1993             .withUsage(AUDIO_USAGE_ASSISTANT)
1994             .withTags("addr=remote_submix_media;othertag"),
1995         DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1996             .withUsage(AUDIO_USAGE_ASSISTANT)
1997             .withTags("sometag;othertag;addr=remote_submix_media")));
1998 
1999 static constexpr audio_session_t TEST_SESSION_ID = static_cast<audio_session_t>(42);
2000 static constexpr audio_session_t OTHER_SESSION_ID = static_cast<audio_session_t>(77);
2001 
2002 INSTANTIATE_TEST_SUITE_P(
2003     PlaybackReRoutingWithSessionId,
2004     AudioPolicyManagerTestDPPlaybackReRouting,
2005     testing::Values(
2006         // Mix is matched because the session id matches the one specified by the mix rule.
2007         DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID)},
2008                     /*expected_match=*/ true)
2009             .withSessionId(TEST_SESSION_ID),
2010         // Mix is not matched because the session id doesn't match the one specified
2011         // by the mix rule.
2012         DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID)},
2013                     /*expected_match=*/ false)
2014             .withSessionId(OTHER_SESSION_ID),
2015         // Mix is matched, the session id doesn't match the one specified by rule,
2016         // but there's address specified in the tags which takes precedence.
2017         DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID)},
2018                     /*expected_match=*/ true)
2019             .withSessionId(OTHER_SESSION_ID).withTags("addr=remote_submix_media"),
2020         // Mix is matched, both the session id and the usage match ones specified by mix rule.
2021         DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID),
2022                                       createUsageCriterion(AUDIO_USAGE_MEDIA)},
2023                     /*expected_match=*/ true)
2024             .withSessionId(TEST_SESSION_ID).withUsage(AUDIO_USAGE_MEDIA),
2025         // Mix is not matched, the session id matches the one specified by mix rule,
2026         // but usage does not.
2027         DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID),
2028                                       createUsageCriterion(AUDIO_USAGE_MEDIA)},
2029                     /*expected_match=*/ false)
2030                     .withSessionId(TEST_SESSION_ID).withUsage(AUDIO_USAGE_GAME),
2031         // Mix is not matched, the usage matches the one specified by mix rule,
2032         // but the session id is excluded.
2033         DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID, /*exclude=*/ true),
2034                                      createUsageCriterion(AUDIO_USAGE_MEDIA)},
2035                     /*expected_match=*/ false)
2036                     .withSessionId(TEST_SESSION_ID).withUsage(AUDIO_USAGE_MEDIA)));
2037 
2038 struct DPMmapTestParam {
DPMmapTestParamDPMmapTestParam2039     DPMmapTestParam(int mixRouteFlags, audio_devices_t deviceType, const std::string& deviceAddress)
2040         : mixRouteFlags(mixRouteFlags), deviceType(deviceType), deviceAddress(deviceAddress) {}
2041 
2042     int mixRouteFlags;
2043     audio_devices_t deviceType;
2044     std::string deviceAddress;
2045 };
2046 
2047 class AudioPolicyManagerTestMMapPlaybackRerouting
2048     : public AudioPolicyManagerTestDynamicPolicy,
2049       public ::testing::WithParamInterface<DPMmapTestParam> {
2050   protected:
SetUp()2051     void SetUp() override {
2052         AudioPolicyManagerTestDynamicPolicy::SetUp();
2053         audioConfig = AUDIO_CONFIG_INITIALIZER;
2054         audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2055         audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2056         audioConfig.sample_rate = k48000SamplingRate;
2057     }
2058 
2059     audio_config_t audioConfig;
2060     audio_io_handle_t mOutput;
2061     audio_stream_type_t mStream = AUDIO_STREAM_DEFAULT;
2062     audio_port_handle_t mSelectedDeviceId = AUDIO_PORT_HANDLE_NONE;
2063     audio_port_handle_t mPortId = AUDIO_PORT_HANDLE_NONE;
2064     AudioPolicyInterface::output_type_t mOutputType;
2065     audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER;
2066     bool mIsSpatialized;
2067     bool mIsBitPerfect;
2068 };
2069 
TEST_P(AudioPolicyManagerTestMMapPlaybackRerouting,MmapPlaybackStreamMatchingLoopbackDapMixFails)2070 TEST_P(AudioPolicyManagerTestMMapPlaybackRerouting, MmapPlaybackStreamMatchingLoopbackDapMixFails) {
2071     // Add mix matching the test uid.
2072     const int testUid = 12345;
2073     const auto param = GetParam();
2074     ASSERT_NO_FATAL_FAILURE(
2075             addPolicyMixAndStartInputForLoopback(MIX_TYPE_PLAYERS, param.mixRouteFlags,
2076                                                  param.deviceType, param.deviceAddress, audioConfig,
2077                                                  {createUidCriterion(testUid)}));
2078 
2079     // Getting output for matching uid and mmap-ed stream should fail.
2080     audio_output_flags_t outputFlags =
2081             (audio_output_flags_t) (AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2082     ASSERT_EQ(INVALID_OPERATION,
2083               mManager->getOutputForAttr(&attr, &mOutput, AUDIO_SESSION_NONE, &mStream,
2084                                          createAttributionSourceState(testUid), &audioConfig,
2085                                          &outputFlags, &mSelectedDeviceId, &mPortId, {},
2086                                          &mOutputType, &mIsSpatialized, &mIsBitPerfect));
2087 }
2088 
TEST_P(AudioPolicyManagerTestMMapPlaybackRerouting,NonMmapPlaybackStreamMatchingLoopbackDapMixSucceeds)2089 TEST_P(AudioPolicyManagerTestMMapPlaybackRerouting,
2090         NonMmapPlaybackStreamMatchingLoopbackDapMixSucceeds) {
2091     // Add mix matching the test uid.
2092     const int testUid = 12345;
2093     const auto param = GetParam();
2094     ASSERT_NO_FATAL_FAILURE(
2095             addPolicyMixAndStartInputForLoopback(MIX_TYPE_PLAYERS, param.mixRouteFlags,
2096                                                  param.deviceType,param.deviceAddress, audioConfig,
2097                                                  {createUidCriterion(testUid)}));
2098 
2099     // Getting output for matching uid should succeed for non-mmaped stream.
2100     audio_output_flags_t outputFlags = AUDIO_OUTPUT_FLAG_NONE;
2101     ASSERT_EQ(NO_ERROR,
2102               mManager->getOutputForAttr(&attr, &mOutput, AUDIO_SESSION_NONE, &mStream,
2103                                          createAttributionSourceState(testUid), &audioConfig,
2104                                          &outputFlags, &mSelectedDeviceId, &mPortId, {},
2105                                          &mOutputType, &mIsSpatialized, &mIsBitPerfect));
2106 }
2107 
TEST_F(AudioPolicyManagerTestMMapPlaybackRerouting,MmapPlaybackStreamMatchingRenderDapMixSupportingMmapSucceeds)2108 TEST_F(AudioPolicyManagerTestMMapPlaybackRerouting,
2109         MmapPlaybackStreamMatchingRenderDapMixSupportingMmapSucceeds) {
2110     const std::string usbAddress = "card=1;device=0";
2111     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2112             AUDIO_DEVICE_OUT_USB_DEVICE, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2113             usbAddress.c_str(), "", AUDIO_FORMAT_DEFAULT));
2114     audio_port_v7 usbDevicePort;
2115     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_USB_DEVICE,
2116                                usbAddress, &usbDevicePort));
2117 
2118     // Add render-only mix matching the test uid.
2119     const int testUid = 12345;
2120     // test_audio_policy_configuration.xml declares mmap-capable mix port
2121     // for AUDIO_DEVICE_OUT_USB_DEVICE.
2122     ASSERT_EQ(NO_ERROR,
2123               addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2124                            AUDIO_DEVICE_OUT_USB_DEVICE, /*mixAddress=*/"",
2125                            audioConfig, {createUidCriterion(testUid)}));
2126 
2127     static const audio_output_flags_t mmapDirectFlags =
2128             (audio_output_flags_t) (AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2129     // Getting output for matching uid should succeed for mmaped stream, because matched mix
2130     // redirects to mmap capable device.
2131     audio_output_flags_t outputFlags = mmapDirectFlags;
2132     ASSERT_EQ(NO_ERROR,
2133               mManager->getOutputForAttr(&attr, &mOutput, AUDIO_SESSION_NONE, &mStream,
2134                                          createAttributionSourceState(testUid), &audioConfig,
2135                                          &outputFlags, &mSelectedDeviceId, &mPortId, {},
2136                                          &mOutputType, &mIsSpatialized, &mIsBitPerfect));
2137     ASSERT_EQ(usbDevicePort.id, mSelectedDeviceId);
2138     auto outputDesc = mManager->getOutputs().valueFor(mOutput);
2139     ASSERT_NE(nullptr, outputDesc);
2140     ASSERT_EQ(mmapDirectFlags, outputDesc->getFlags().output);
2141 
2142     // After releasing the client, the output is closed. APM should reselect output for the policy
2143     // mix.
2144     mManager->releaseOutput(mPortId);
2145     ASSERT_EQ(nullptr, mManager->getOutputs().valueFor(mOutput));
2146     outputFlags = AUDIO_OUTPUT_FLAG_NONE;
2147     mPortId = AUDIO_PORT_HANDLE_NONE;
2148     ASSERT_EQ(NO_ERROR,
2149               mManager->getOutputForAttr(&attr, &mOutput, AUDIO_SESSION_NONE, &mStream,
2150                                          createAttributionSourceState(testUid), &audioConfig,
2151                                          &outputFlags, &mSelectedDeviceId, &mPortId, {},
2152                                          &mOutputType, &mIsSpatialized, &mIsBitPerfect));
2153     ASSERT_EQ(usbDevicePort.id, mSelectedDeviceId);
2154     outputDesc = mManager->getOutputs().valueFor(mOutput);
2155     ASSERT_NE(nullptr, outputDesc);
2156     ASSERT_NE(mmapDirectFlags, outputDesc->getFlags().output);
2157 
2158     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2159             AUDIO_DEVICE_OUT_USB_DEVICE, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2160             usbAddress.c_str(), "", AUDIO_FORMAT_DEFAULT));
2161 }
2162 
TEST_F(AudioPolicyManagerTestMMapPlaybackRerouting,MmapPlaybackStreamMatchingRenderDapMixNotSupportingMmapFails)2163 TEST_F(AudioPolicyManagerTestMMapPlaybackRerouting,
2164         MmapPlaybackStreamMatchingRenderDapMixNotSupportingMmapFails) {
2165     // Add render-only mix matching the test uid.
2166     const int testUid = 12345;
2167     // Per test_audio_policy_configuration.xml AUDIO_DEVICE_OUT_SPEAKER doesn't support mmap.
2168     ASSERT_EQ(NO_ERROR,
2169               addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2170                            AUDIO_DEVICE_OUT_SPEAKER, /*mixAddress=*/"", audioConfig,
2171                            {createUidCriterion(testUid)}));
2172 
2173     // Getting output for matching uid should fail for mmaped stream, because
2174     // matched mix redirects to device which doesn't support mmap.
2175     audio_output_flags_t outputFlags =
2176             (audio_output_flags_t) (AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2177     ASSERT_EQ(INVALID_OPERATION,
2178               mManager->getOutputForAttr(&attr, &mOutput, AUDIO_SESSION_NONE, &mStream,
2179                                          createAttributionSourceState(testUid), &audioConfig,
2180                                          &outputFlags, &mSelectedDeviceId, &mPortId, {},
2181                                          &mOutputType, &mIsSpatialized, &mIsBitPerfect));
2182 }
2183 
2184 INSTANTIATE_TEST_SUITE_P(
2185         MmapPlaybackRerouting, AudioPolicyManagerTestMMapPlaybackRerouting,
2186         testing::Values(DPMmapTestParam(MIX_ROUTE_FLAG_LOOP_BACK, AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2187                                         /*deviceAddress=*/"remote_submix_media"),
2188                         DPMmapTestParam(MIX_ROUTE_FLAG_LOOP_BACK_AND_RENDER,
2189                                         AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2190                                         /*deviceAddress=*/"remote_submix_media"),
2191                         DPMmapTestParam(MIX_ROUTE_FLAG_RENDER, AUDIO_DEVICE_OUT_SPEAKER,
2192                                         /*deviceAddress=*/"")));
2193 
2194 class AudioPolicyManagerTestDPMixRecordInjection : public AudioPolicyManagerTestDynamicPolicy,
2195         public testing::WithParamInterface<DPTestParam> {
2196 protected:
2197     void SetUp() override;
2198     void TearDown() override;
2199 
2200     std::unique_ptr<RecordingActivityTracker> mTracker;
2201     struct audio_port_v7 mExtractionPort;
2202     audio_port_handle_t mPortId = AUDIO_PORT_HANDLE_NONE;
2203 };
2204 
SetUp()2205 void AudioPolicyManagerTestDPMixRecordInjection::SetUp() {
2206     ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTestDynamicPolicy::SetUp());
2207 
2208     mTracker.reset(new RecordingActivityTracker());
2209 
2210     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2211     audioConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2212     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2213     audioConfig.sample_rate = k48000SamplingRate;
2214 
2215     DPTestParam param = GetParam();
2216     status_t ret = addPolicyMix(MIX_TYPE_RECORDERS, MIX_ROUTE_FLAG_LOOP_BACK,
2217             AUDIO_DEVICE_IN_REMOTE_SUBMIX, mMixAddress, audioConfig, param.mixCriteria);
2218     ASSERT_EQ(NO_ERROR, ret);
2219 
2220     struct audio_port_v7 injectionPort;
2221     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2222                     mMixAddress, &injectionPort));
2223 
2224     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
2225     audio_usage_t usage = AUDIO_USAGE_VIRTUAL_SOURCE;
2226     audio_attributes_t attr =
2227             {AUDIO_CONTENT_TYPE_UNKNOWN, usage, AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2228     std::string tags = std::string("addr=") + mMixAddress;
2229     strncpy(attr.tags, tags.c_str(), AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1);
2230     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2231             k48000SamplingRate, AUDIO_OUTPUT_FLAG_NONE, nullptr /*output*/, &mPortId, attr);
2232     ASSERT_EQ(NO_ERROR, mManager->startOutput(mPortId));
2233     ASSERT_EQ(injectionPort.id, getDeviceIdFromPatch(mClient->getLastAddedPatch()));
2234 
2235     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SOURCE, AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2236                     mMixAddress, &mExtractionPort));
2237 }
2238 
TearDown()2239 void AudioPolicyManagerTestDPMixRecordInjection::TearDown() {
2240     mManager->stopOutput(mPortId);
2241     AudioPolicyManagerTestDynamicPolicy::TearDown();
2242 }
2243 
TEST_P(AudioPolicyManagerTestDPMixRecordInjection,RecordingInjection)2244 TEST_P(AudioPolicyManagerTestDPMixRecordInjection, RecordingInjection) {
2245     const DPTestParam param = GetParam();
2246 
2247     audio_port_handle_t captureRoutedPortId = AUDIO_PORT_HANDLE_NONE;
2248     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
2249     audio_io_handle_t input = AUDIO_PORT_HANDLE_NONE;
2250     getInputForAttr(param.attributes, &input, param.session, mTracker->getRiid(),
2251                     &captureRoutedPortId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
2252                     k48000SamplingRate, AUDIO_INPUT_FLAG_NONE, &portId);
2253     if (param.expected_match) {
2254         EXPECT_EQ(mExtractionPort.id, captureRoutedPortId);
2255     } else {
2256         EXPECT_NE(mExtractionPort.id, captureRoutedPortId);
2257     }
2258 }
2259 
2260 const std::vector<AudioMixMatchCriterion> SOURCE_CAM_MIC_VOICE_CRITERIA = {
2261         createCapturePresetCriterion(AUDIO_SOURCE_CAMCORDER),
2262         createCapturePresetCriterion(AUDIO_SOURCE_MIC),
2263         createCapturePresetCriterion(AUDIO_SOURCE_VOICE_COMMUNICATION)
2264 };
2265 
2266 // No address priority rule for remote recording, address is a "don't care"
2267 INSTANTIATE_TEST_CASE_P(
2268         RecordInjectionSource,
2269         AudioPolicyManagerTestDPMixRecordInjection,
2270         testing::Values(
2271             DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ true)
2272                 .withSource(AUDIO_SOURCE_CAMCORDER),
2273             DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ true)
2274                 .withSource(AUDIO_SOURCE_CAMCORDER)
2275                 .withTags("addr=remote_submix_media"),
2276             DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ true)
2277                 .withSource(AUDIO_SOURCE_MIC),
2278             DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ true)
2279                 .withSource(AUDIO_SOURCE_MIC)
2280                 .withTags("addr=remote_submix_media"),
2281             DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ true)
2282                 .withSource(AUDIO_SOURCE_VOICE_COMMUNICATION),
2283             DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ true)
2284                 .withSource(AUDIO_SOURCE_VOICE_COMMUNICATION)
2285                 .withTags("addr=remote_submix_media"),
2286             DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ false)
2287                 .withSource(AUDIO_SOURCE_VOICE_RECOGNITION),
2288             DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ false)
2289                 .withSource(AUDIO_SOURCE_VOICE_RECOGNITION)
2290                 .withTags("addr=remote_submix_media"),
2291             DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ false)
2292                 .withSource(AUDIO_SOURCE_HOTWORD),
2293             DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ false)
2294                 .withSource(AUDIO_SOURCE_HOTWORD)
2295                 .withTags("addr=remote_submix_media")));
2296 
2297 INSTANTIATE_TEST_CASE_P(
2298         RecordInjectionWithSessionId,
2299         AudioPolicyManagerTestDPMixRecordInjection,
2300         testing::Values(
2301             // Mix is matched because the session id matches the one specified by the mix rule.
2302             DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID)},
2303                         /*expected_match=*/ true)
2304                 .withSessionId(TEST_SESSION_ID),
2305             // Mix is not matched because the session id doesn't match the one specified
2306             // by the mix rule.
2307             DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID)},
2308                         /*expected_match=*/ false)
2309                 .withSessionId(OTHER_SESSION_ID),
2310             // Mix is not matched, the session id doesn't match the one specified by rule,
2311             // but tand address specified in the tags is ignored for recorder mix.
2312             DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID)},
2313                         /*expected_match=*/ false)
2314                 .withSessionId(OTHER_SESSION_ID).withTags("addr=remote_submix_media"),
2315             // Mix is matched, both the session id and the source match ones specified by mix rule
2316             DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID),
2317                                           createCapturePresetCriterion(AUDIO_SOURCE_CAMCORDER)},
2318                         /*expected_match=*/ true)
2319                 .withSessionId(TEST_SESSION_ID).withSource(AUDIO_SOURCE_CAMCORDER),
2320             // Mix is not matched, the session id matches the one specified by mix rule,
2321             // but source does not.
2322             DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID),
2323                                           createCapturePresetCriterion(AUDIO_SOURCE_CAMCORDER)},
2324                         /*expected_match=*/ false)
2325                 .withSessionId(TEST_SESSION_ID).withSource(AUDIO_SOURCE_MIC),
2326             // Mix is not matched, the source matches the one specified by mix rule,
2327             // but the session id is excluded.
2328             DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID,
2329                                                                        /*exclude=*/ true),
2330                                           createCapturePresetCriterion(AUDIO_SOURCE_MIC)},
2331                         /*expected_match=*/ false)
2332                 .withSessionId(TEST_SESSION_ID).withSource(AUDIO_SOURCE_MIC)));
2333 
2334 using DeviceConnectionTestParams =
2335         std::tuple<audio_devices_t /*type*/, std::string /*name*/, std::string /*address*/>;
2336 
2337 class AudioPolicyManagerTestDeviceConnection : public AudioPolicyManagerTestWithConfigurationFile,
2338         public testing::WithParamInterface<DeviceConnectionTestParams> {
2339 };
2340 
TEST_F(AudioPolicyManagerTestDeviceConnection,InitSuccess)2341 TEST_F(AudioPolicyManagerTestDeviceConnection, InitSuccess) {
2342     // SetUp must finish with no assertions.
2343 }
2344 
TEST_F(AudioPolicyManagerTestDeviceConnection,Dump)2345 TEST_F(AudioPolicyManagerTestDeviceConnection, Dump) {
2346     dumpToLog();
2347 }
2348 
TEST_F(AudioPolicyManagerTestDeviceConnection,RoutingUpdate)2349 TEST_F(AudioPolicyManagerTestDeviceConnection, RoutingUpdate) {
2350     mClient->resetRoutingUpdatedCounter();
2351     // Connecting a valid output device with valid parameters should trigger a routing update
2352     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2353             AUDIO_DEVICE_OUT_BLUETOOTH_SCO, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2354             "00:11:22:33:44:55", "b", AUDIO_FORMAT_DEFAULT));
2355     ASSERT_EQ(1, mClient->getRoutingUpdatedCounter());
2356 
2357     // Disconnecting a connected device should succeed and trigger a routing update
2358     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2359             AUDIO_DEVICE_OUT_BLUETOOTH_SCO, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2360             "00:11:22:33:44:55", "b", AUDIO_FORMAT_DEFAULT));
2361     ASSERT_EQ(2, mClient->getRoutingUpdatedCounter());
2362 
2363     // Disconnecting a disconnected device should fail and not trigger a routing update
2364     ASSERT_EQ(INVALID_OPERATION, mManager->setDeviceConnectionState(
2365             AUDIO_DEVICE_OUT_BLUETOOTH_SCO, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2366             "00:11:22:33:44:55", "b",  AUDIO_FORMAT_DEFAULT));
2367     ASSERT_EQ(2, mClient->getRoutingUpdatedCounter());
2368 
2369     // Changing force use should trigger an update
2370     auto config = mManager->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA);
2371     auto newConfig = config == AUDIO_POLICY_FORCE_BT_A2DP ?
2372             AUDIO_POLICY_FORCE_NONE : AUDIO_POLICY_FORCE_BT_A2DP;
2373     mManager->setForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA, newConfig);
2374     ASSERT_EQ(3, mClient->getRoutingUpdatedCounter());
2375 }
2376 
TEST_P(AudioPolicyManagerTestDeviceConnection,SetDeviceConnectionState)2377 TEST_P(AudioPolicyManagerTestDeviceConnection, SetDeviceConnectionState) {
2378     const audio_devices_t type = std::get<0>(GetParam());
2379     const std::string name = std::get<1>(GetParam());
2380     const std::string address = std::get<2>(GetParam());
2381 
2382     if (type == AUDIO_DEVICE_OUT_HDMI) {
2383         // Set device connection state failed due to no device descriptor found
2384         // For HDMI case, it is easier to simulate device descriptor not found error
2385         // by using an encoded format which isn't listed in the 'encodedFormats'
2386         // attribute for this devicePort.
2387         ASSERT_EQ(INVALID_OPERATION, mManager->setDeviceConnectionState(
2388                 type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2389                 address.c_str(), name.c_str(), AUDIO_FORMAT_MAT_2_1));
2390     }
2391     // Connect with valid parameters should succeed
2392     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2393             type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2394             address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
2395     // Try to connect with the same device again should fail
2396     ASSERT_EQ(INVALID_OPERATION, mManager->setDeviceConnectionState(
2397             type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2398             address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
2399     // Disconnect the connected device should succeed
2400     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2401             type, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2402             address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
2403     // Disconnect device that is not connected should fail
2404     ASSERT_EQ(INVALID_OPERATION, mManager->setDeviceConnectionState(
2405             type, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2406             address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
2407     // Try to set device connection state  with a invalid connection state should fail
2408     ASSERT_EQ(BAD_VALUE, mManager->setDeviceConnectionState(
2409             type, AUDIO_POLICY_DEVICE_STATE_CNT,
2410             "", "", AUDIO_FORMAT_DEFAULT));
2411 }
2412 
TEST_P(AudioPolicyManagerTestDeviceConnection,ExplicitlyRoutingAfterConnection)2413 TEST_P(AudioPolicyManagerTestDeviceConnection, ExplicitlyRoutingAfterConnection) {
2414     const audio_devices_t type = std::get<0>(GetParam());
2415     const std::string name = std::get<1>(GetParam());
2416     const std::string address = std::get<2>(GetParam());
2417 
2418     // Connect device to do explicitly routing test
2419     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2420             type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2421             address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
2422 
2423     audio_port_v7 devicePort;
2424     const audio_port_role_t role = audio_is_output_device(type)
2425             ? AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
2426     ASSERT_TRUE(findDevicePort(role, type, address, &devicePort));
2427 
2428     audio_port_handle_t routedPortId = devicePort.id;
2429     // Try start input or output according to the device type
2430     if (audio_is_output_devices(type)) {
2431         getOutputForAttr(&routedPortId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2432                 k48000SamplingRate, AUDIO_OUTPUT_FLAG_NONE);
2433     } else if (audio_is_input_device(type)) {
2434         RecordingActivityTracker tracker;
2435         audio_io_handle_t input = AUDIO_PORT_HANDLE_NONE;
2436         getInputForAttr({}, &input, AUDIO_SESSION_NONE, tracker.getRiid(), &routedPortId,
2437                         AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO, k48000SamplingRate,
2438                         AUDIO_INPUT_FLAG_NONE);
2439     }
2440     ASSERT_EQ(devicePort.id, routedPortId);
2441 
2442     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2443             type, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2444             address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
2445 }
2446 
make_ExtraAudioDescriptor(android::media::audio::common::AudioStandard audioStandard,android::media::audio::common::AudioEncapsulationType audioEncapsulationType)2447 android::media::audio::common::ExtraAudioDescriptor make_ExtraAudioDescriptor(
2448         android::media::audio::common::AudioStandard audioStandard,
2449         android::media::audio::common::AudioEncapsulationType audioEncapsulationType) {
2450     android::media::audio::common::ExtraAudioDescriptor result;
2451     result.standard = audioStandard;
2452     result.audioDescriptor = {0xb4, 0xaf, 0x98, 0x1a};
2453     result.encapsulationType = audioEncapsulationType;
2454     return result;
2455 }
2456 
TEST_P(AudioPolicyManagerTestDeviceConnection,PassingExtraAudioDescriptors)2457 TEST_P(AudioPolicyManagerTestDeviceConnection, PassingExtraAudioDescriptors) {
2458     const audio_devices_t type = std::get<0>(GetParam());
2459     if (!audio_device_is_digital(type)) {
2460         // EADs are used only for HDMI devices.
2461         GTEST_SKIP() << "Not a digital device type: " << audio_device_to_string(type);
2462     }
2463     const std::string name = std::get<1>(GetParam());
2464     const std::string address = std::get<2>(GetParam());
2465     android::media::AudioPortFw audioPort;
2466     ASSERT_EQ(NO_ERROR,
2467             mManager->deviceToAudioPort(type, address.c_str(), name.c_str(), &audioPort));
2468     android::media::audio::common::AudioPort& port = audioPort.hal;
2469     port.extraAudioDescriptors.push_back(make_ExtraAudioDescriptor(
2470                     android::media::audio::common::AudioStandard::EDID,
2471                     android::media::audio::common::AudioEncapsulationType::IEC61937));
2472     const size_t lastConnectedDevicePortCount = mClient->getConnectedDevicePortCount();
2473     const size_t lastDisconnectedDevicePortCount = mClient->getDisconnectedDevicePortCount();
2474     EXPECT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2475                     AUDIO_POLICY_DEVICE_STATE_AVAILABLE, port, AUDIO_FORMAT_DEFAULT));
2476     EXPECT_EQ(lastConnectedDevicePortCount + 1, mClient->getConnectedDevicePortCount());
2477     EXPECT_EQ(lastDisconnectedDevicePortCount, mClient->getDisconnectedDevicePortCount());
2478     const audio_port_v7* devicePort = mClient->getLastConnectedDevicePort();
2479     EXPECT_EQ(port.extraAudioDescriptors.size(), devicePort->num_extra_audio_descriptors);
2480     EXPECT_EQ(AUDIO_STANDARD_EDID, devicePort->extra_audio_descriptors[0].standard);
2481     EXPECT_EQ(AUDIO_ENCAPSULATION_TYPE_IEC61937,
2482             devicePort->extra_audio_descriptors[0].encapsulation_type);
2483     EXPECT_NE(0, devicePort->extra_audio_descriptors[0].descriptor[0]);
2484 }
2485 
2486 INSTANTIATE_TEST_CASE_P(
2487         DeviceConnectionState,
2488         AudioPolicyManagerTestDeviceConnection,
2489         testing::Values(
2490                 DeviceConnectionTestParams({AUDIO_DEVICE_IN_HDMI, "test_in_hdmi",
2491                                             "audio_policy_test_in_hdmi"}),
2492                 DeviceConnectionTestParams({AUDIO_DEVICE_OUT_HDMI, "test_out_hdmi",
2493                                             "audio_policy_test_out_hdmi"}),
2494                 DeviceConnectionTestParams({AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "bt_hfp_in",
2495                                             "00:11:22:33:44:55"}),
2496                 DeviceConnectionTestParams({AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "bt_hfp_out",
2497                                             "00:11:22:33:44:55"})
2498                 )
2499         );
2500 
2501 namespace {
2502 
2503 class AudioPolicyManagerTestClientOpenFails : public AudioPolicyManagerTestClient {
2504   public:
openOutput(audio_module_handle_t module,audio_io_handle_t * output,audio_config_t * halConfig,audio_config_base_t * mixerConfig,const sp<DeviceDescriptorBase> & device,uint32_t * latencyMs,audio_output_flags_t flags)2505     status_t openOutput(audio_module_handle_t module,
2506                         audio_io_handle_t *output,
2507                         audio_config_t * halConfig,
2508                         audio_config_base_t * mixerConfig,
2509                         const sp<DeviceDescriptorBase>& device,
2510                         uint32_t * latencyMs,
2511                         audio_output_flags_t flags) override {
2512         return mSimulateFailure ? BAD_VALUE :
2513                 AudioPolicyManagerTestClient::openOutput(
2514                         module, output, halConfig, mixerConfig, device, latencyMs, flags);
2515     }
2516 
openInput(audio_module_handle_t module,audio_io_handle_t * input,audio_config_t * config,audio_devices_t * device,const String8 & address,audio_source_t source,audio_input_flags_t flags)2517     status_t openInput(audio_module_handle_t module,
2518                        audio_io_handle_t *input,
2519                        audio_config_t * config,
2520                        audio_devices_t * device,
2521                        const String8 & address,
2522                        audio_source_t source,
2523                        audio_input_flags_t flags) override {
2524         return mSimulateFailure ? BAD_VALUE :
2525                 AudioPolicyManagerTestClient::openInput(
2526                         module, input, config, device, address, source, flags);
2527     }
2528 
setSimulateFailure(bool simulateFailure)2529     void setSimulateFailure(bool simulateFailure) { mSimulateFailure = simulateFailure; }
2530 
2531   private:
2532     bool mSimulateFailure = false;
2533 };
2534 
2535 }  // namespace
2536 
2537 using DeviceConnectionWithFormatTestParams =
2538         std::tuple<audio_devices_t /*type*/, std::string /*name*/, std::string /*address*/,
2539         audio_format_t /*format*/>;
2540 
2541 class AudioPolicyManagerTestDeviceConnectionFailed :
2542         public AudioPolicyManagerTestWithConfigurationFile,
2543         public testing::WithParamInterface<DeviceConnectionWithFormatTestParams> {
2544   protected:
getConfigFile()2545     std::string getConfigFile() override { return sBluetoothConfig; }
getClient()2546   AudioPolicyManagerTestClient* getClient() override {
2547         mFullClient = new AudioPolicyManagerTestClientOpenFails;
2548         return mFullClient;
2549     }
setSimulateOpenFailure(bool simulateFailure)2550     void setSimulateOpenFailure(bool simulateFailure) {
2551         mFullClient->setSimulateFailure(simulateFailure); }
2552 
2553     static const std::string sBluetoothConfig;
2554 
2555   private:
2556     AudioPolicyManagerTestClientOpenFails* mFullClient;
2557 };
2558 
2559 const std::string AudioPolicyManagerTestDeviceConnectionFailed::sBluetoothConfig =
2560         AudioPolicyManagerTestDeviceConnectionFailed::sExecutableDir +
2561         "test_audio_policy_configuration_bluetooth.xml";
2562 
TEST_P(AudioPolicyManagerTestDeviceConnectionFailed,SetDeviceConnectedStateHasAddress)2563 TEST_P(AudioPolicyManagerTestDeviceConnectionFailed, SetDeviceConnectedStateHasAddress) {
2564     const audio_devices_t type = std::get<0>(GetParam());
2565     const std::string name = std::get<1>(GetParam());
2566     const std::string address = std::get<2>(GetParam());
2567     const audio_format_t format = std::get<3>(GetParam());
2568 
2569     EXPECT_EQ(0, mClient->getConnectedDevicePortCount());
2570     EXPECT_EQ(0, mClient->getDisconnectedDevicePortCount());
2571 
2572     setSimulateOpenFailure(true);
2573     ASSERT_EQ(INVALID_OPERATION, mManager->setDeviceConnectionState(
2574             type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2575             address.c_str(), name.c_str(), format));
2576 
2577     // Since the failure happens when opening input/output, the device must be connected
2578     // first and then disconnected.
2579     EXPECT_EQ(1, mClient->getConnectedDevicePortCount());
2580     EXPECT_EQ(1, mClient->getDisconnectedDevicePortCount());
2581 
2582     if (mClient->getConnectedDevicePortCount() > 0) {
2583         auto port = mClient->getLastConnectedDevicePort();
2584         EXPECT_EQ(type, port->ext.device.type);
2585         EXPECT_EQ(0, strncmp(port->ext.device.address, address.c_str(),
2586                         AUDIO_DEVICE_MAX_ADDRESS_LEN)) << "\"" << port->ext.device.address << "\"";
2587     }
2588     if (mClient->getDisconnectedDevicePortCount() > 0) {
2589         auto port = mClient->getLastDisconnectedDevicePort();
2590         EXPECT_EQ(type, port->ext.device.type);
2591         EXPECT_EQ(0, strncmp(port->ext.device.address, address.c_str(),
2592                         AUDIO_DEVICE_MAX_ADDRESS_LEN)) << "\"" << port->ext.device.address << "\"";
2593     }
2594 }
2595 
2596 INSTANTIATE_TEST_CASE_P(
2597         DeviceConnectionFailure,
2598         AudioPolicyManagerTestDeviceConnectionFailed,
2599         testing::Values(
2600                 DeviceConnectionWithFormatTestParams({AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET,
2601                             "bt_hfp_in", "00:11:22:33:44:55", AUDIO_FORMAT_DEFAULT}),
2602                 DeviceConnectionWithFormatTestParams({AUDIO_DEVICE_OUT_BLUETOOTH_SCO,
2603                             "bt_hfp_out", "00:11:22:33:44:55", AUDIO_FORMAT_DEFAULT}),
2604                 DeviceConnectionWithFormatTestParams({AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
2605                             "bt_a2dp_out", "00:11:22:33:44:55", AUDIO_FORMAT_DEFAULT}),
2606                 DeviceConnectionWithFormatTestParams({AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
2607                             "bt_a2dp_out", "00:11:22:33:44:66", AUDIO_FORMAT_LDAC})
2608                 )
2609         );
2610 
2611 class AudioPolicyManagerCarTest : public AudioPolicyManagerTestDynamicPolicy {
2612 protected:
getConfigFile()2613     std::string getConfigFile() override { return sCarConfig; }
2614 
2615     static const std::string sCarConfig;
2616     static const std::string sCarBusMediaOutput;
2617     static const std::string sCarBusNavigationOutput;
2618     static const std::string sCarRearZoneOneOutput;
2619     static const std::string sCarRearZoneTwoOutput;
2620     static const std::string sCarBusMmapOutput;
2621 };
2622 
2623 const std::string AudioPolicyManagerCarTest::sCarConfig =
2624         AudioPolicyManagerCarTest::sExecutableDir + "test_car_ap_atmos_offload_configuration.xml";
2625 
2626 const std::string AudioPolicyManagerCarTest::sCarBusMediaOutput = "bus0_media_out";
2627 
2628 const std::string AudioPolicyManagerCarTest::sCarBusNavigationOutput = "bus1_navigation_out";
2629 
2630 const std::string AudioPolicyManagerCarTest::sCarRearZoneOneOutput = "bus100_audio_zone_1";
2631 
2632 const std::string AudioPolicyManagerCarTest::sCarRearZoneTwoOutput = "bus200_audio_zone_2";
2633 
2634 const std::string AudioPolicyManagerCarTest::sCarBusMmapOutput = "bus8_mmap_out";
2635 
TEST_F(AudioPolicyManagerCarTest,InitSuccess)2636 TEST_F(AudioPolicyManagerCarTest, InitSuccess) {
2637     // SetUp must finish with no assertions.
2638 }
2639 
TEST_F(AudioPolicyManagerCarTest,Dump)2640 TEST_F(AudioPolicyManagerCarTest, Dump) {
2641     dumpToLog();
2642 }
2643 
TEST_F(AudioPolicyManagerCarTest,GetOutputForAttrAtmosOutputAfterRegisteringPolicyMix)2644 TEST_F(AudioPolicyManagerCarTest, GetOutputForAttrAtmosOutputAfterRegisteringPolicyMix) {
2645     status_t ret;
2646     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2647     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2648             AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig);
2649     ASSERT_EQ(NO_ERROR, ret);
2650 
2651     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
2652     audio_io_handle_t output;
2653     audio_port_handle_t portId;
2654     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_E_AC3_JOC, AUDIO_CHANNEL_OUT_5POINT1,
2655             k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId);
2656     ASSERT_NE(AUDIO_PORT_HANDLE_NONE, selectedDeviceId);
2657     sp<SwAudioOutputDescriptor> outDesc = mManager->getOutputs().valueFor(output);
2658     ASSERT_NE(nullptr, outDesc.get());
2659     ASSERT_EQ(AUDIO_FORMAT_E_AC3_JOC, outDesc->getFormat());
2660     ASSERT_EQ(AUDIO_CHANNEL_OUT_5POINT1, outDesc->getChannelMask());
2661     ASSERT_EQ(k48000SamplingRate, outDesc->getSamplingRate());
2662 
2663     selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
2664     output = AUDIO_IO_HANDLE_NONE;
2665     portId = AUDIO_PORT_HANDLE_NONE;
2666     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_7POINT1POINT4,
2667             k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId);
2668     ASSERT_NE(AUDIO_PORT_HANDLE_NONE, selectedDeviceId);
2669     outDesc = mManager->getOutputs().valueFor(output);
2670     ASSERT_NE(nullptr, outDesc.get());
2671     ASSERT_EQ(AUDIO_FORMAT_PCM_16_BIT, outDesc->getFormat());
2672     ASSERT_EQ(AUDIO_CHANNEL_OUT_7POINT1POINT4, outDesc->getChannelMask());
2673     ASSERT_EQ(k48000SamplingRate, outDesc->getSamplingRate());
2674 }
2675 
TEST_F(AudioPolicyManagerCarTest,GetOutputForAttrAfterRegisteringPolicyMix)2676 TEST_F(AudioPolicyManagerCarTest, GetOutputForAttrAfterRegisteringPolicyMix) {
2677     status_t ret;
2678     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2679     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2680     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2681     audioConfig.sample_rate = k48000SamplingRate;
2682     std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2683             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2684     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2685             AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2686     ASSERT_EQ(NO_ERROR, ret);
2687     std::vector<AudioMixMatchCriterion> navMatchCriteria = {
2688                 createUsageCriterion(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
2689                     /*exclude=*/ false)};
2690     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2691                 AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput, audioConfig, navMatchCriteria);
2692     ASSERT_EQ(NO_ERROR, ret);
2693     audio_port_v7 mediaDevicePort;
2694     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2695             sCarBusMediaOutput, &mediaDevicePort));
2696     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
2697     audio_io_handle_t output;
2698     audio_port_handle_t portId;
2699     const audio_attributes_t mediaAttribute = {
2700             AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
2701             AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2702 
2703     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2704             k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, mediaAttribute);
2705 
2706     ASSERT_EQ(mediaDevicePort.id, selectedDeviceId);
2707 }
2708 
TEST_F(AudioPolicyManagerCarTest,GetOutputForAttrWithSelectedOutputAfterRegisteringPolicyMix)2709 TEST_F(AudioPolicyManagerCarTest, GetOutputForAttrWithSelectedOutputAfterRegisteringPolicyMix) {
2710     status_t ret;
2711     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2712     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2713     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2714     audioConfig.sample_rate = k48000SamplingRate;
2715     std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2716             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2717     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2718             AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2719     ASSERT_EQ(NO_ERROR, ret);
2720     std::vector<AudioMixMatchCriterion> navMatchCriteria = {
2721                 createUsageCriterion(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
2722                     /*exclude=*/ false)};
2723     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2724                 AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput, audioConfig, navMatchCriteria);
2725     ASSERT_EQ(NO_ERROR, ret);
2726     audio_port_v7 navDevicePort;
2727     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2728             sCarBusNavigationOutput, &navDevicePort));
2729     audio_port_handle_t selectedDeviceId = navDevicePort.id;
2730     audio_io_handle_t output;
2731     audio_port_handle_t portId;
2732     const audio_attributes_t mediaAttribute = {
2733             AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
2734             AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2735 
2736     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2737             k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, mediaAttribute);
2738 
2739     ASSERT_EQ(navDevicePort.id, selectedDeviceId);
2740 }
2741 
TEST_F(AudioPolicyManagerCarTest,GetOutputForAttrWithSelectedOutputAfterUserAffinities)2742 TEST_F(AudioPolicyManagerCarTest, GetOutputForAttrWithSelectedOutputAfterUserAffinities) {
2743     status_t ret;
2744     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2745     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2746     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2747     audioConfig.sample_rate = k48000SamplingRate;
2748     std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2749             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2750     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2751             AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2752     ASSERT_EQ(NO_ERROR, ret);
2753     std::vector<AudioMixMatchCriterion> navMatchCriteria = {
2754                 createUsageCriterion(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
2755                     /*exclude=*/ false)};
2756     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2757                 AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput, audioConfig, navMatchCriteria);
2758     ASSERT_EQ(NO_ERROR, ret);
2759     const AudioDeviceTypeAddr mediaOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput);
2760     const AudioDeviceTypeAddrVector outputDevices = {mediaOutputDevice};
2761     mManager->setUserIdDeviceAffinities(/* userId */ 0, outputDevices);
2762     audio_port_v7 navDevicePort;
2763     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2764             sCarBusNavigationOutput, &navDevicePort));
2765     audio_port_handle_t selectedDeviceId = navDevicePort.id;
2766     audio_io_handle_t output;
2767     audio_port_handle_t portId;
2768     const audio_attributes_t mediaAttribute = {
2769                 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
2770                 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2771 
2772     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2773             k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, mediaAttribute);
2774 
2775     ASSERT_NE(navDevicePort.id, selectedDeviceId);
2776 }
2777 
TEST_F(AudioPolicyManagerCarTest,GetOutputForAttrWithExcludeUserIdCriteria)2778 TEST_F(AudioPolicyManagerCarTest, GetOutputForAttrWithExcludeUserIdCriteria) {
2779     status_t ret;
2780     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2781     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2782     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2783     audioConfig.sample_rate = k48000SamplingRate;
2784     std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2785             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2786     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2787             AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2788     ASSERT_EQ(NO_ERROR, ret);
2789     std::vector<AudioMixMatchCriterion> navMatchCriteria = {
2790                 createUsageCriterion(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
2791                     /*exclude=*/ false),
2792                 createUserIdCriterion(/* userId */ 0, /* exclude */ true)};
2793     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2794                 AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput, audioConfig, navMatchCriteria);
2795     ASSERT_EQ(NO_ERROR, ret);
2796     audio_port_v7 navDevicePort;
2797     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2798             sCarBusNavigationOutput, &navDevicePort));
2799     audio_io_handle_t output;
2800     audio_port_handle_t portId;
2801     const audio_attributes_t navigationAttribute = {
2802                 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
2803                 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2804     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
2805 
2806     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2807             k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, navigationAttribute);
2808 
2809     ASSERT_NE(navDevicePort.id, selectedDeviceId);
2810 }
2811 
TEST_F(AudioPolicyManagerCarTest,GetOutputForAttrWithSelectedOutputExcludeUserIdCriteria)2812 TEST_F(AudioPolicyManagerCarTest, GetOutputForAttrWithSelectedOutputExcludeUserIdCriteria) {
2813     status_t ret;
2814     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2815     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2816     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2817     audioConfig.sample_rate = k48000SamplingRate;
2818     std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2819             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2820     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2821             AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2822     ASSERT_EQ(NO_ERROR, ret);
2823     std::vector<AudioMixMatchCriterion> navMatchCriteria = {
2824                 createUsageCriterion(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
2825                     /*exclude=*/ false),
2826                 createUserIdCriterion(0 /* userId */, /* exclude */ true)};
2827     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2828                 AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput, audioConfig, navMatchCriteria);
2829     ASSERT_EQ(NO_ERROR, ret);
2830     audio_port_v7 navDevicePort;
2831     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2832             sCarBusNavigationOutput, &navDevicePort));
2833     audio_port_handle_t selectedDeviceId = navDevicePort.id;
2834     audio_io_handle_t output;
2835     audio_port_handle_t portId;
2836     const audio_attributes_t mediaAttribute = {
2837                 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
2838                 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2839 
2840     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2841             k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, mediaAttribute);
2842 
2843     ASSERT_EQ(navDevicePort.id, selectedDeviceId);
2844 }
2845 
TEST_F(AudioPolicyManagerCarTest,GetOutputForAttrWithMatchingMixAndSelectedOutputAfterUserAffinities)2846 TEST_F(AudioPolicyManagerCarTest,
2847         GetOutputForAttrWithMatchingMixAndSelectedOutputAfterUserAffinities) {
2848     status_t ret;
2849     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2850     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2851     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2852     audioConfig.sample_rate = k48000SamplingRate;
2853     std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2854             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2855     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2856             AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2857     ASSERT_EQ(NO_ERROR, ret);
2858     std::vector<AudioMixMatchCriterion> navMatchCriteria = {
2859                 createUsageCriterion(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
2860                     /*exclude=*/ false)};
2861     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2862                 AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput, audioConfig, navMatchCriteria);
2863     ASSERT_EQ(NO_ERROR, ret);
2864     const AudioDeviceTypeAddr mediaOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput);
2865     const AudioDeviceTypeAddr navOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput);
2866     const AudioDeviceTypeAddrVector outputDevices = {mediaOutputDevice, navOutputDevice};
2867     mManager->setUserIdDeviceAffinities(/* userId */ 0, outputDevices);
2868     audio_port_v7 navDevicePort;
2869     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2870             sCarBusNavigationOutput, &navDevicePort));
2871     audio_port_handle_t selectedDeviceId = navDevicePort.id;
2872     audio_io_handle_t output;
2873     audio_port_handle_t portId;
2874     const audio_attributes_t mediaAttribute = {
2875                 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
2876                 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2877 
2878     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2879             k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, mediaAttribute);
2880 
2881     ASSERT_EQ(navDevicePort.id, selectedDeviceId);
2882 }
2883 
TEST_F(AudioPolicyManagerCarTest,GetOutputForAttrWithNoMatchingMaxAndSelectedOutputAfterUserAffinities)2884 TEST_F(AudioPolicyManagerCarTest,
2885         GetOutputForAttrWithNoMatchingMaxAndSelectedOutputAfterUserAffinities) {
2886     status_t ret;
2887     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2888     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2889     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2890     audioConfig.sample_rate = k48000SamplingRate;
2891     std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2892             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2893     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2894             AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2895     ASSERT_EQ(NO_ERROR, ret);
2896     std::vector<AudioMixMatchCriterion> navMatchCriteria = {
2897                 createUsageCriterion(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
2898                     /*exclude=*/ false)};
2899     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2900                 AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput, audioConfig, navMatchCriteria);
2901     ASSERT_EQ(NO_ERROR, ret);
2902     const AudioDeviceTypeAddr mediaOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput);
2903     const AudioDeviceTypeAddr navOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput);
2904     const AudioDeviceTypeAddrVector outputDevices = {mediaOutputDevice, navOutputDevice};
2905     mManager->setUserIdDeviceAffinities(/* userId */ 0, outputDevices);
2906     audio_port_v7 navDevicePort;
2907     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2908             sCarBusNavigationOutput, &navDevicePort));
2909     audio_port_handle_t selectedDeviceId = navDevicePort.id;
2910     audio_io_handle_t output;
2911     audio_port_handle_t portId;
2912     const audio_attributes_t alarmAttribute = {
2913                 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_ALARM,
2914                 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2915 
2916     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2917             k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, alarmAttribute);
2918 
2919     ASSERT_EQ(navDevicePort.id, selectedDeviceId);
2920 }
2921 
TEST_F(AudioPolicyManagerCarTest,GetOutputForAttrWithMatMixAfterUserAffinitiesForOneUser)2922 TEST_F(AudioPolicyManagerCarTest,
2923         GetOutputForAttrWithMatMixAfterUserAffinitiesForOneUser) {
2924     status_t ret;
2925     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2926     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2927     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2928     audioConfig.sample_rate = k48000SamplingRate;
2929     std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2930             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2931     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2932             AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2933     ASSERT_EQ(NO_ERROR, ret);
2934     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2935             AUDIO_DEVICE_OUT_BUS, sCarRearZoneOneOutput, audioConfig, mediaMatchCriteria);
2936     ASSERT_EQ(NO_ERROR, ret);
2937     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2938             AUDIO_DEVICE_OUT_BUS, sCarRearZoneTwoOutput, audioConfig, mediaMatchCriteria);
2939     ASSERT_EQ(NO_ERROR, ret);
2940     const AudioDeviceTypeAddr mediaOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput);
2941     const AudioDeviceTypeAddrVector primaryZoneDevices = {mediaOutputDevice};
2942     mManager->setUserIdDeviceAffinities(/* userId */ 0, primaryZoneDevices);
2943     audio_port_v7 primaryZoneDevicePort;
2944     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2945             sCarBusMediaOutput, &primaryZoneDevicePort));
2946     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
2947     audio_io_handle_t output;
2948     audio_port_handle_t portId;
2949     const audio_attributes_t mediaAttribute = {
2950                     AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
2951                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2952     uid_t user11AppUid = multiuser_get_uid(/* user_id */ 11, /* app_id */ 12345);
2953 
2954     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2955             k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, mediaAttribute,
2956             AUDIO_SESSION_NONE, user11AppUid);
2957 
2958     ASSERT_EQ(primaryZoneDevicePort.id, selectedDeviceId);
2959 }
2960 
TEST_F(AudioPolicyManagerCarTest,GetOutputForAttrWithMatMixAfterUserAffinitiesForTwoUsers)2961 TEST_F(AudioPolicyManagerCarTest,
2962         GetOutputForAttrWithMatMixAfterUserAffinitiesForTwoUsers) {
2963     status_t ret;
2964     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2965     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2966     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2967     audioConfig.sample_rate = k48000SamplingRate;
2968     std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2969             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2970     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2971             AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2972     ASSERT_EQ(NO_ERROR, ret);
2973     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2974             AUDIO_DEVICE_OUT_BUS, sCarRearZoneOneOutput, audioConfig, mediaMatchCriteria);
2975     ASSERT_EQ(NO_ERROR, ret);
2976     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2977             AUDIO_DEVICE_OUT_BUS, sCarRearZoneTwoOutput, audioConfig, mediaMatchCriteria);
2978     ASSERT_EQ(NO_ERROR, ret);
2979     const AudioDeviceTypeAddr mediaOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput);
2980     const AudioDeviceTypeAddrVector primaryZoneDevices = {mediaOutputDevice};
2981     mManager->setUserIdDeviceAffinities(/* userId */ 0, primaryZoneDevices);
2982     const AudioDeviceTypeAddr secondaryOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarRearZoneOneOutput);
2983     const AudioDeviceTypeAddrVector secondaryZoneDevices = {secondaryOutputDevice};
2984     mManager->setUserIdDeviceAffinities(/* userId */ 11, secondaryZoneDevices);
2985     audio_port_v7 secondaryZoneDevicePort;
2986     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2987             sCarRearZoneOneOutput, &secondaryZoneDevicePort));
2988     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
2989     audio_io_handle_t output;
2990     audio_port_handle_t portId;
2991     const audio_attributes_t mediaAttribute = {
2992                     AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
2993                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2994     uid_t user11AppUid = multiuser_get_uid(/* user_id */ 11, /* app_id */ 12345);
2995 
2996     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2997             k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, mediaAttribute,
2998             AUDIO_SESSION_NONE, user11AppUid);
2999 
3000     ASSERT_EQ(secondaryZoneDevicePort.id, selectedDeviceId);
3001 }
3002 
TEST_F(AudioPolicyManagerCarTest,GetOutputForAttrWithMatMixAfterUserAffinitiesForThreeUsers)3003 TEST_F(AudioPolicyManagerCarTest,
3004         GetOutputForAttrWithMatMixAfterUserAffinitiesForThreeUsers) {
3005     status_t ret;
3006     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
3007     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3008     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
3009     audioConfig.sample_rate = k48000SamplingRate;
3010     std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
3011             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
3012     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
3013             AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
3014     ASSERT_EQ(NO_ERROR, ret);
3015     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
3016             AUDIO_DEVICE_OUT_BUS, sCarRearZoneOneOutput, audioConfig, mediaMatchCriteria);
3017     ASSERT_EQ(NO_ERROR, ret);
3018     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
3019             AUDIO_DEVICE_OUT_BUS, sCarRearZoneTwoOutput, audioConfig, mediaMatchCriteria);
3020     ASSERT_EQ(NO_ERROR, ret);
3021     const AudioDeviceTypeAddr mediaOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput);
3022     const AudioDeviceTypeAddrVector primaryZoneDevices = {mediaOutputDevice};
3023     mManager->setUserIdDeviceAffinities(/* userId */ 0, primaryZoneDevices);
3024     const AudioDeviceTypeAddr secondaryOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarRearZoneOneOutput);
3025     const AudioDeviceTypeAddrVector secondaryZoneDevices = {secondaryOutputDevice};
3026     mManager->setUserIdDeviceAffinities(/* userId */ 11, secondaryZoneDevices);
3027     const AudioDeviceTypeAddr tertiaryOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarRearZoneTwoOutput);
3028     const AudioDeviceTypeAddrVector tertiaryZoneDevices = {tertiaryOutputDevice};
3029     mManager->setUserIdDeviceAffinities(/* userId */ 15, tertiaryZoneDevices);
3030     audio_port_v7 tertiaryZoneDevicePort;
3031     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
3032             sCarRearZoneTwoOutput, &tertiaryZoneDevicePort));
3033     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3034     audio_io_handle_t output;
3035     audio_port_handle_t portId;
3036     const audio_attributes_t mediaAttribute = {
3037                     AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
3038                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
3039     uid_t user15AppUid = multiuser_get_uid(/* user_id */ 15, /* app_id */ 12345);
3040 
3041     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
3042             k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, mediaAttribute,
3043             AUDIO_SESSION_NONE, user15AppUid);
3044 
3045     ASSERT_EQ(tertiaryZoneDevicePort.id, selectedDeviceId);
3046 }
3047 
TEST_F(AudioPolicyManagerCarTest,GetOutputForAttrWithNoMatchingMix)3048 TEST_F(AudioPolicyManagerCarTest, GetOutputForAttrWithNoMatchingMix) {
3049     status_t ret;
3050     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
3051     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3052     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
3053     audioConfig.sample_rate = k48000SamplingRate;
3054     std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
3055             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
3056     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
3057             AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
3058     ASSERT_EQ(NO_ERROR, ret);
3059     std::vector<AudioMixMatchCriterion> navMatchCriteria = {
3060                 createUsageCriterion(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
3061                     /*exclude=*/ false)};
3062     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
3063                 AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput, audioConfig, navMatchCriteria);
3064     ASSERT_EQ(NO_ERROR, ret);
3065     const AudioDeviceTypeAddr mediaOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput);
3066     const AudioDeviceTypeAddr navOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput);
3067     const AudioDeviceTypeAddrVector outputDevices = {mediaOutputDevice, navOutputDevice};
3068     mManager->setUserIdDeviceAffinities(/* userId */ 0, outputDevices);
3069     audio_port_v7 navDevicePort;
3070     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
3071             sCarBusNavigationOutput, &navDevicePort));
3072     audio_port_handle_t selectedDeviceId = navDevicePort.id;
3073     audio_io_handle_t output;
3074     audio_port_handle_t portId;
3075     const audio_attributes_t alarmAttribute = {
3076                 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_ALARM,
3077                 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
3078 
3079     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
3080             k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, alarmAttribute);
3081 
3082     ASSERT_EQ(navDevicePort.id, selectedDeviceId);
3083 }
3084 
TEST_F(AudioPolicyManagerCarTest,GetOutputForAttrForMMapWithPolicyMatched)3085 TEST_F(AudioPolicyManagerCarTest, GetOutputForAttrForMMapWithPolicyMatched) {
3086     status_t ret;
3087     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
3088     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3089     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
3090     audioConfig.sample_rate = k48000SamplingRate;
3091     std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
3092             createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
3093     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
3094                        AUDIO_DEVICE_OUT_BUS, sCarBusMmapOutput, audioConfig, mediaMatchCriteria);
3095     ASSERT_EQ(NO_ERROR, ret);
3096     ASSERT_EQ(NO_ERROR, ret);
3097     audio_port_v7 mmapDevicePort;
3098     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
3099                                sCarBusMmapOutput, &mmapDevicePort));
3100     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3101     audio_io_handle_t output;
3102     audio_port_handle_t portId;
3103     const audio_attributes_t mediaAttribute = {
3104             AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
3105             AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
3106 
3107     getOutputForAttr(
3108             &selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
3109             k48000SamplingRate,
3110             (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT),
3111             &output, &portId, mediaAttribute);
3112 
3113     ASSERT_EQ(mmapDevicePort.id, selectedDeviceId);
3114 }
3115 
3116 class AudioPolicyManagerTVTest : public AudioPolicyManagerTestWithConfigurationFile {
3117 protected:
getConfigFile()3118     std::string getConfigFile() override { return sTvConfig; }
3119     void testHDMIPortSelection(audio_output_flags_t flags, const char* expectedMixPortName);
3120 
3121     static const std::string sTvConfig;
3122 };
3123 
3124 const std::string AudioPolicyManagerTVTest::sTvConfig =
3125         AudioPolicyManagerTVTest::sExecutableDir + "test_tv_apm_configuration.xml";
3126 
3127 // SwAudioOutputDescriptor doesn't populate flags so check against the port name.
testHDMIPortSelection(audio_output_flags_t flags,const char * expectedMixPortName)3128 void AudioPolicyManagerTVTest::testHDMIPortSelection(
3129         audio_output_flags_t flags, const char* expectedMixPortName) {
3130     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
3131             AUDIO_DEVICE_OUT_AUX_DIGITAL, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3132             "" /*address*/, "" /*name*/, AUDIO_FORMAT_DEFAULT));
3133     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3134     audio_io_handle_t output;
3135     audio_port_handle_t portId;
3136     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
3137             k48000SamplingRate, flags, &output, &portId);
3138     sp<SwAudioOutputDescriptor> outDesc = mManager->getOutputs().valueFor(output);
3139     ASSERT_NE(nullptr, outDesc.get());
3140     audio_port_v7 port = {};
3141     outDesc->toAudioPort(&port);
3142     mManager->releaseOutput(portId);
3143     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
3144             AUDIO_DEVICE_OUT_AUX_DIGITAL, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3145             "" /*address*/, "" /*name*/, AUDIO_FORMAT_DEFAULT));
3146     ASSERT_EQ(AUDIO_PORT_TYPE_MIX, port.type);
3147     ASSERT_EQ(AUDIO_PORT_ROLE_SOURCE, port.role);
3148     ASSERT_STREQ(expectedMixPortName, port.name);
3149 }
3150 
TEST_F(AudioPolicyManagerTVTest,InitSuccess)3151 TEST_F(AudioPolicyManagerTVTest, InitSuccess) {
3152     // SetUp must finish with no assertions.
3153 }
3154 
TEST_F(AudioPolicyManagerTVTest,Dump)3155 TEST_F(AudioPolicyManagerTVTest, Dump) {
3156     dumpToLog();
3157 }
3158 
TEST_F(AudioPolicyManagerTVTest,MatchNoFlags)3159 TEST_F(AudioPolicyManagerTVTest, MatchNoFlags) {
3160     testHDMIPortSelection(AUDIO_OUTPUT_FLAG_NONE, "primary output");
3161 }
3162 
TEST_F(AudioPolicyManagerTVTest,MatchOutputDirectNoHwAvSync)3163 TEST_F(AudioPolicyManagerTVTest, MatchOutputDirectNoHwAvSync) {
3164     // b/140447125: The selected port must not have HW AV Sync flag (see the config file).
3165     testHDMIPortSelection(AUDIO_OUTPUT_FLAG_DIRECT, "direct");
3166 }
3167 
TEST_F(AudioPolicyManagerTVTest,MatchOutputDirectHwAvSync)3168 TEST_F(AudioPolicyManagerTVTest, MatchOutputDirectHwAvSync) {
3169     testHDMIPortSelection(static_cast<audio_output_flags_t>(
3170                     AUDIO_OUTPUT_FLAG_DIRECT|AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
3171             "tunnel");
3172 }
3173 
TEST_F(AudioPolicyManagerTVTest,MatchOutputDirectMMapNoIrq)3174 TEST_F(AudioPolicyManagerTVTest, MatchOutputDirectMMapNoIrq) {
3175     testHDMIPortSelection(static_cast<audio_output_flags_t>(
3176                     AUDIO_OUTPUT_FLAG_DIRECT|AUDIO_OUTPUT_FLAG_MMAP_NOIRQ),
3177             "low latency");
3178 }
3179 
3180 class AudioPolicyManagerDynamicHwModulesTest : public AudioPolicyManagerTestWithConfigurationFile {
3181 protected:
3182     void SetUpManagerConfig() override;
3183 };
3184 
SetUpManagerConfig()3185 void AudioPolicyManagerDynamicHwModulesTest::SetUpManagerConfig() {
3186     ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTestWithConfigurationFile::SetUpManagerConfig());
3187     // Only allow successful opening of "primary" hw module during APM initialization.
3188     mClient->swapAllowedModuleNames({"primary"});
3189 }
3190 
TEST_F(AudioPolicyManagerDynamicHwModulesTest,InitSuccess)3191 TEST_F(AudioPolicyManagerDynamicHwModulesTest, InitSuccess) {
3192     // SetUp must finish with no assertions.
3193 }
3194 
TEST_F(AudioPolicyManagerDynamicHwModulesTest,DynamicAddition)3195 TEST_F(AudioPolicyManagerDynamicHwModulesTest, DynamicAddition) {
3196     const auto handleBefore = mClient->peekNextModuleHandle();
3197     mManager->onNewAudioModulesAvailable();
3198     ASSERT_EQ(handleBefore, mClient->peekNextModuleHandle());
3199     // Reset module loading restrictions.
3200     mClient->swapAllowedModuleNames();
3201     mManager->onNewAudioModulesAvailable();
3202     const auto handleAfter = mClient->peekNextModuleHandle();
3203     ASSERT_GT(handleAfter, handleBefore);
3204     mManager->onNewAudioModulesAvailable();
3205     ASSERT_EQ(handleAfter, mClient->peekNextModuleHandle());
3206 }
3207 
TEST_F(AudioPolicyManagerDynamicHwModulesTest,AddedDeviceAvailable)3208 TEST_F(AudioPolicyManagerDynamicHwModulesTest, AddedDeviceAvailable) {
3209     ASSERT_EQ(AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, mManager->getDeviceConnectionState(
3210                     AUDIO_DEVICE_IN_REMOTE_SUBMIX, "0"));
3211     mClient->swapAllowedModuleNames({"primary", "r_submix"});
3212     mManager->onNewAudioModulesAvailable();
3213     ASSERT_EQ(AUDIO_POLICY_DEVICE_STATE_AVAILABLE, mManager->getDeviceConnectionState(
3214                     AUDIO_DEVICE_IN_REMOTE_SUBMIX, "0"));
3215 }
3216 
TEST_F(AudioPolicyManagerDynamicHwModulesTest,ListAddedAudioPorts)3217 TEST_F(AudioPolicyManagerDynamicHwModulesTest, ListAddedAudioPorts) {
3218     ASSERT_FALSE(
3219             findDevicePort(AUDIO_PORT_ROLE_SOURCE, AUDIO_DEVICE_IN_REMOTE_SUBMIX, "0", nullptr));
3220     mClient->swapAllowedModuleNames({"primary", "r_submix"});
3221     mManager->onNewAudioModulesAvailable();
3222     struct audio_port_v7 port;
3223     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SOURCE, AUDIO_DEVICE_IN_REMOTE_SUBMIX, "0", &port));
3224 }
3225 
TEST_F(AudioPolicyManagerDynamicHwModulesTest,ClientIsUpdated)3226 TEST_F(AudioPolicyManagerDynamicHwModulesTest, ClientIsUpdated) {
3227     const size_t prevAudioPortListUpdateCount = mClient->getAudioPortListUpdateCount();
3228     const uint32_t prevAudioPortGeneration = mManager->getAudioPortGeneration();
3229     mClient->swapAllowedModuleNames({"primary", "r_submix"});
3230     mManager->onNewAudioModulesAvailable();
3231     EXPECT_GT(mClient->getAudioPortListUpdateCount(), prevAudioPortListUpdateCount);
3232     EXPECT_GT(mManager->getAudioPortGeneration(), prevAudioPortGeneration);
3233 }
3234 
3235 using DevicesRoleForCapturePresetParam = std::tuple<audio_source_t, device_role_t>;
3236 
3237 class AudioPolicyManagerDevicesRoleForCapturePresetTest
3238         : public AudioPolicyManagerTestWithConfigurationFile,
3239           public testing::WithParamInterface<DevicesRoleForCapturePresetParam> {
3240 protected:
3241     // The `inputDevice` and `inputDevice2` indicate the audio devices type to be used for setting
3242     // device role. They must be declared in the test_audio_policy_configuration.xml
3243     AudioDeviceTypeAddr inputDevice = AudioDeviceTypeAddr(AUDIO_DEVICE_IN_BUILTIN_MIC, "");
3244     AudioDeviceTypeAddr inputDevice2 = AudioDeviceTypeAddr(AUDIO_DEVICE_IN_HDMI, "");
3245 };
3246 
TEST_P(AudioPolicyManagerDevicesRoleForCapturePresetTest,DevicesRoleForCapturePreset)3247 TEST_P(AudioPolicyManagerDevicesRoleForCapturePresetTest, DevicesRoleForCapturePreset) {
3248     const audio_source_t audioSource = std::get<0>(GetParam());
3249     const device_role_t role = std::get<1>(GetParam());
3250 
3251     // Test invalid device when setting
3252     const AudioDeviceTypeAddr outputDevice(AUDIO_DEVICE_OUT_SPEAKER, "");
3253     const AudioDeviceTypeAddrVector outputDevices = {outputDevice};
3254     ASSERT_EQ(BAD_VALUE,
3255               mManager->setDevicesRoleForCapturePreset(audioSource, role, outputDevices));
3256     ASSERT_EQ(BAD_VALUE,
3257               mManager->addDevicesRoleForCapturePreset(audioSource, role, outputDevices));
3258     AudioDeviceTypeAddrVector devices;
3259     ASSERT_EQ(NAME_NOT_FOUND,
3260               mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
3261     ASSERT_TRUE(devices.empty());
3262     ASSERT_EQ(BAD_VALUE,
3263               mManager->removeDevicesRoleForCapturePreset(audioSource, role, outputDevices));
3264 
3265     // Without setting, call get/remove/clear must fail
3266     ASSERT_EQ(NAME_NOT_FOUND,
3267               mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
3268     ASSERT_EQ(NAME_NOT_FOUND,
3269               mManager->removeDevicesRoleForCapturePreset(audioSource, role, devices));
3270     ASSERT_EQ(NAME_NOT_FOUND,
3271               mManager->clearDevicesRoleForCapturePreset(audioSource, role));
3272 
3273     // Test set/get devices role
3274     const AudioDeviceTypeAddrVector inputDevices = {inputDevice};
3275     ASSERT_EQ(NO_ERROR,
3276               mManager->setDevicesRoleForCapturePreset(audioSource, role, inputDevices));
3277     ASSERT_EQ(NO_ERROR, mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
3278     EXPECT_THAT(devices, UnorderedElementsAre(inputDevice));
3279 
3280     // Test setting will change the previously set devices
3281     const AudioDeviceTypeAddrVector inputDevices2 = {inputDevice2};
3282     ASSERT_EQ(NO_ERROR,
3283               mManager->setDevicesRoleForCapturePreset(audioSource, role, inputDevices2));
3284     devices.clear();
3285     ASSERT_EQ(NO_ERROR, mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
3286     EXPECT_THAT(devices, UnorderedElementsAre(inputDevice2));
3287 
3288     // Test add devices
3289     ASSERT_EQ(NO_ERROR,
3290               mManager->addDevicesRoleForCapturePreset(audioSource, role, inputDevices));
3291     devices.clear();
3292     ASSERT_EQ(NO_ERROR, mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
3293     EXPECT_THAT(devices, UnorderedElementsAre(inputDevice, inputDevice2));
3294 
3295     // Test remove devices
3296     ASSERT_EQ(NO_ERROR,
3297               mManager->removeDevicesRoleForCapturePreset(audioSource, role, inputDevices));
3298     devices.clear();
3299     ASSERT_EQ(NO_ERROR, mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
3300     EXPECT_THAT(devices, UnorderedElementsAre(inputDevice2));
3301 
3302     // Test remove devices that are not set as the device role
3303     ASSERT_EQ(BAD_VALUE,
3304               mManager->removeDevicesRoleForCapturePreset(audioSource, role, inputDevices));
3305 
3306     // Test clear devices
3307     ASSERT_EQ(NO_ERROR,
3308               mManager->clearDevicesRoleForCapturePreset(audioSource, role));
3309     devices.clear();
3310     ASSERT_EQ(NAME_NOT_FOUND,
3311               mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
3312 }
3313 
TEST_F(AudioPolicyManagerDevicesRoleForCapturePresetTest,PreferredDeviceUsedForInput)3314 TEST_F(AudioPolicyManagerDevicesRoleForCapturePresetTest, PreferredDeviceUsedForInput) {
3315     const audio_source_t source = AUDIO_SOURCE_MIC;
3316     const device_role_t role = DEVICE_ROLE_PREFERRED;
3317     const std::string address = "card=1;device=0";
3318     const std::string deviceName = "randomName";
3319 
3320     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
3321             AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3322             address.c_str(), deviceName.c_str(), AUDIO_FORMAT_DEFAULT));
3323     auto availableDevices = mManager->getAvailableInputDevices();
3324     ASSERT_GT(availableDevices.size(), 1);
3325 
3326     audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER;
3327     attr.source = source;
3328     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3329     audio_io_handle_t input = AUDIO_PORT_HANDLE_NONE;
3330     ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input, AUDIO_SESSION_NONE, 1, &selectedDeviceId,
3331                                             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
3332                                             48000));
3333     auto selectedDevice = availableDevices.getDeviceFromId(selectedDeviceId);
3334     ASSERT_NE(nullptr, selectedDevice);
3335 
3336     sp<DeviceDescriptor> preferredDevice = nullptr;
3337     for (const auto& device : availableDevices) {
3338         if (device != selectedDevice) {
3339             preferredDevice = device;
3340             break;
3341         }
3342     }
3343     ASSERT_NE(nullptr, preferredDevice);
3344     // After setting preferred device for capture preset, the selected device for input should be
3345     // the preferred device.
3346     ASSERT_EQ(NO_ERROR,
3347               mManager->setDevicesRoleForCapturePreset(source, role,
3348                                                        {preferredDevice->getDeviceTypeAddr()}));
3349     selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3350     input = AUDIO_PORT_HANDLE_NONE;
3351     ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input, AUDIO_SESSION_NONE, 1, &selectedDeviceId,
3352                                             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
3353                                             48000));
3354     ASSERT_EQ(preferredDevice, availableDevices.getDeviceFromId(selectedDeviceId));
3355 
3356     // After clearing preferred device for capture preset, the selected device for input should be
3357     // the same as original one.
3358     ASSERT_EQ(NO_ERROR,
3359               mManager->clearDevicesRoleForCapturePreset(source, role));
3360     selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3361     input = AUDIO_PORT_HANDLE_NONE;
3362     ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input, AUDIO_SESSION_NONE, 1, &selectedDeviceId,
3363                                             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
3364                                             48000));
3365     ASSERT_EQ(selectedDevice, availableDevices.getDeviceFromId(selectedDeviceId));
3366 
3367     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
3368             AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3369             address.c_str(), deviceName.c_str(), AUDIO_FORMAT_DEFAULT));
3370 }
3371 
TEST_F(AudioPolicyManagerDevicesRoleForCapturePresetTest,DisabledDeviceNotUsedForInput)3372 TEST_F(AudioPolicyManagerDevicesRoleForCapturePresetTest, DisabledDeviceNotUsedForInput) {
3373     const audio_source_t source = AUDIO_SOURCE_MIC;
3374     const device_role_t role = DEVICE_ROLE_DISABLED;
3375     const std::string address = "card=1;device=0";
3376     const std::string deviceName = "randomName";
3377 
3378     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
3379             AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3380             address.c_str(), deviceName.c_str(), AUDIO_FORMAT_DEFAULT));
3381     auto availableDevices = mManager->getAvailableInputDevices();
3382     ASSERT_GT(availableDevices.size(), 1);
3383 
3384     audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER;
3385     attr.source = source;
3386     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3387     audio_io_handle_t input = AUDIO_PORT_HANDLE_NONE;
3388     ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input, AUDIO_SESSION_NONE, 1, &selectedDeviceId,
3389                                             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
3390                                             48000));
3391     auto selectedDevice = availableDevices.getDeviceFromId(selectedDeviceId);
3392     ASSERT_NE(nullptr, selectedDevice);
3393 
3394     // After setting disabled device for capture preset, the disabled device must not be
3395     // selected for input.
3396     ASSERT_EQ(NO_ERROR,
3397               mManager->setDevicesRoleForCapturePreset(source, role,
3398                                                        {selectedDevice->getDeviceTypeAddr()}));
3399     selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3400     input = AUDIO_PORT_HANDLE_NONE;
3401     ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input, AUDIO_SESSION_NONE, 1,
3402                                             &selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT,
3403                                             AUDIO_CHANNEL_IN_STEREO, 48000));
3404     ASSERT_NE(selectedDevice, availableDevices.getDeviceFromId(selectedDeviceId));
3405 
3406     // After clearing disabled device for capture preset, the selected device for input should be
3407     // the original one.
3408     ASSERT_EQ(NO_ERROR,
3409               mManager->clearDevicesRoleForCapturePreset(source, role));
3410     selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3411     input = AUDIO_PORT_HANDLE_NONE;
3412     ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input, AUDIO_SESSION_NONE, 1, &selectedDeviceId,
3413                                             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
3414                                             48000));
3415     ASSERT_EQ(selectedDevice, availableDevices.getDeviceFromId(selectedDeviceId));
3416 
3417     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
3418             AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3419             address.c_str(), deviceName.c_str(), AUDIO_FORMAT_DEFAULT));
3420 }
3421 
3422 INSTANTIATE_TEST_CASE_P(
3423         DevicesRoleForCapturePresetOperation,
3424         AudioPolicyManagerDevicesRoleForCapturePresetTest,
3425         testing::Values(
3426                 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_MIC, DEVICE_ROLE_PREFERRED}),
3427                 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_UPLINK,
3428                                                   DEVICE_ROLE_PREFERRED}),
3429                 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_DOWNLINK,
3430                                                   DEVICE_ROLE_PREFERRED}),
3431                 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_CALL, DEVICE_ROLE_PREFERRED}),
3432                 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_CAMCORDER, DEVICE_ROLE_PREFERRED}),
3433                 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_RECOGNITION,
3434                                                   DEVICE_ROLE_PREFERRED}),
3435                 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_COMMUNICATION,
3436                                                   DEVICE_ROLE_PREFERRED}),
3437                 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_REMOTE_SUBMIX,
3438                                                   DEVICE_ROLE_PREFERRED}),
3439                 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_UNPROCESSED, DEVICE_ROLE_PREFERRED}),
3440                 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_PERFORMANCE,
3441                                                   DEVICE_ROLE_PREFERRED}),
3442                 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_ECHO_REFERENCE,
3443                                                   DEVICE_ROLE_PREFERRED}),
3444                 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_FM_TUNER, DEVICE_ROLE_PREFERRED}),
3445                 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_HOTWORD, DEVICE_ROLE_PREFERRED})
3446                 )
3447         );
3448 
3449 
3450 const effect_descriptor_t TEST_EFFECT_DESC = {
3451         {0xf2a4bb20, 0x0c3c, 0x11e3, 0x8b07, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}, // type
3452         {0xff93e360, 0x0c3c, 0x11e3, 0x8a97, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}, // uuid
3453         EFFECT_CONTROL_API_VERSION,
3454         EFFECT_FLAG_TYPE_PRE_PROC,
3455         0,
3456         1,
3457         "APM test Effect",
3458         "The Android Open Source Project",
3459 };
3460 
3461 class AudioPolicyManagerPreProcEffectTest : public AudioPolicyManagerTestWithConfigurationFile {
3462 };
3463 
TEST_F(AudioPolicyManagerPreProcEffectTest,DeviceDisconnectWhileClientActive)3464 TEST_F(AudioPolicyManagerPreProcEffectTest, DeviceDisconnectWhileClientActive) {
3465     const audio_source_t source = AUDIO_SOURCE_MIC;
3466     const std::string address = "BUS00_MIC";
3467     const std::string deviceName = "randomName";
3468     audio_port_handle_t portId;
3469     audio_devices_t type = AUDIO_DEVICE_IN_BUS;
3470 
3471     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(type,
3472             AUDIO_POLICY_DEVICE_STATE_AVAILABLE, address.c_str(), deviceName.c_str(),
3473             AUDIO_FORMAT_DEFAULT));
3474     auto availableDevices = mManager->getAvailableInputDevices();
3475     ASSERT_GT(availableDevices.size(), 1);
3476 
3477     audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER;
3478     attr.source = source;
3479     audio_session_t session = TEST_SESSION_ID;
3480     audio_io_handle_t inputClientHandle = 777;
3481     int effectId = 666;
3482     audio_port_v7 devicePort;
3483     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SOURCE, type, address, &devicePort));
3484 
3485     audio_port_handle_t routedPortId = devicePort.id;
3486     ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &inputClientHandle, session, 1, &routedPortId,
3487                                             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
3488                                             48000, AUDIO_INPUT_FLAG_NONE, &portId));
3489     ASSERT_EQ(devicePort.id, routedPortId);
3490     auto selectedDevice = availableDevices.getDeviceFromId(routedPortId);
3491     ASSERT_NE(nullptr, selectedDevice);
3492 
3493     // Add a pre processing effect on the input client session
3494     ASSERT_EQ(NO_ERROR, mManager->registerEffect(&TEST_EFFECT_DESC, inputClientHandle,
3495             PRODUCT_STRATEGY_NONE, session, effectId));
3496 
3497     ASSERT_EQ(NO_ERROR, mManager->startInput(portId));
3498 
3499     // Force a device disconnection to close the input, no crash expected of APM
3500     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
3501             type, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3502             address.c_str(), deviceName.c_str(), AUDIO_FORMAT_DEFAULT));
3503 
3504     // Reconnect the device
3505     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
3506             type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3507             address.c_str(), deviceName.c_str(), AUDIO_FORMAT_DEFAULT));
3508 
3509     inputClientHandle += 1;
3510     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SOURCE, type, address, &devicePort));
3511     routedPortId = devicePort.id;
3512 
3513     // Reconnect the client changing voluntarily the io, but keeping the session to get the
3514     // effect attached again
3515     ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &inputClientHandle, session, 1, &routedPortId,
3516                                             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
3517                                             48000));
3518 
3519     // unregister effect should succeed since effect shall have been restore on the client session
3520     ASSERT_EQ(NO_ERROR, mManager->unregisterEffect(effectId));
3521 }
3522 
3523 class AudioPolicyManagerTestBitPerfectBase : public AudioPolicyManagerTestWithConfigurationFile {
3524 protected:
3525     void SetUp() override;
3526     void TearDown() override;
3527 
3528     void startBitPerfectOutput();
3529     void reset();
3530     void getBitPerfectOutput(status_t expected);
3531 
3532     const audio_format_t mBitPerfectFormat = AUDIO_FORMAT_PCM_16_BIT;
3533     const audio_channel_mask_t mBitPerfectChannelMask = AUDIO_CHANNEL_OUT_STEREO;
3534     const uint32_t mBitPerfectSampleRate = 48000;
3535     const uid_t mUid = 1234;
3536     audio_port_handle_t mUsbPortId = AUDIO_PORT_HANDLE_NONE;
3537 
3538     audio_io_handle_t mBitPerfectOutput = AUDIO_IO_HANDLE_NONE;
3539     audio_port_handle_t mSelectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3540     audio_port_handle_t mBitPerfectPortId = AUDIO_PORT_HANDLE_NONE;
3541 
3542     static constexpr audio_attributes_t sMediaAttr = {
3543             .content_type = AUDIO_CONTENT_TYPE_MUSIC,
3544             .usage = AUDIO_USAGE_MEDIA,
3545     };
3546 };
3547 
SetUp()3548 void AudioPolicyManagerTestBitPerfectBase::SetUp() {
3549     ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTestWithConfigurationFile::SetUp());
3550 
3551     mClient->addSupportedFormat(mBitPerfectFormat);
3552     mClient->addSupportedChannelMask(mBitPerfectChannelMask);
3553     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_USB_DEVICE,
3554                                                            AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3555                                                            "", "", AUDIO_FORMAT_DEFAULT));
3556     auto devices = mManager->getAvailableOutputDevices();
3557     mUsbPortId = AUDIO_PORT_HANDLE_NONE;
3558     for (auto device : devices) {
3559         if (device->type() == AUDIO_DEVICE_OUT_USB_DEVICE) {
3560             mUsbPortId = device->getId();
3561             break;
3562         }
3563     }
3564     EXPECT_NE(AUDIO_PORT_HANDLE_NONE, mUsbPortId);
3565 
3566     std::vector<audio_mixer_attributes_t> mixerAttributes;
3567     EXPECT_EQ(NO_ERROR, mManager->getSupportedMixerAttributes(mUsbPortId, mixerAttributes));
3568     EXPECT_GT(mixerAttributes.size(), 0);
3569     size_t bitPerfectIndex = 0;
3570     for (; bitPerfectIndex < mixerAttributes.size(); ++bitPerfectIndex) {
3571         if (mixerAttributes[bitPerfectIndex].mixer_behavior == AUDIO_MIXER_BEHAVIOR_BIT_PERFECT) {
3572             break;
3573         }
3574     }
3575     EXPECT_LT(bitPerfectIndex, mixerAttributes.size());
3576     EXPECT_EQ(mBitPerfectFormat, mixerAttributes[bitPerfectIndex].config.format);
3577     EXPECT_EQ(mBitPerfectChannelMask, mixerAttributes[bitPerfectIndex].config.channel_mask);
3578     EXPECT_EQ(mBitPerfectSampleRate, mixerAttributes[bitPerfectIndex].config.sample_rate);
3579     EXPECT_EQ(NO_ERROR,
3580               mManager->setPreferredMixerAttributes(
3581                       &sMediaAttr, mUsbPortId, mUid, &mixerAttributes[bitPerfectIndex]));
3582 }
3583 
TearDown()3584 void AudioPolicyManagerTestBitPerfectBase::TearDown() {
3585     EXPECT_EQ(NO_ERROR,
3586               mManager->clearPreferredMixerAttributes(&sMediaAttr, mUsbPortId, mUid));
3587     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_USB_DEVICE,
3588                                                            AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3589                                                            "", "", AUDIO_FORMAT_LDAC));
3590 
3591     ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTestWithConfigurationFile::TearDown());
3592 }
3593 
startBitPerfectOutput()3594 void AudioPolicyManagerTestBitPerfectBase::startBitPerfectOutput() {
3595     reset();
3596     bool isBitPerfect;
3597 
3598     getOutputForAttr(&mSelectedDeviceId, mBitPerfectFormat, mBitPerfectChannelMask,
3599                      mBitPerfectSampleRate, AUDIO_OUTPUT_FLAG_NONE, &mBitPerfectOutput,
3600                      &mBitPerfectPortId, sMediaAttr, AUDIO_SESSION_NONE, mUid, &isBitPerfect);
3601     status_t status = mManager->startOutput(mBitPerfectPortId);
3602     if (status == DEAD_OBJECT) {
3603         getOutputForAttr(&mSelectedDeviceId, mBitPerfectFormat, mBitPerfectChannelMask,
3604                          mBitPerfectSampleRate, AUDIO_OUTPUT_FLAG_NONE, &mBitPerfectOutput,
3605                          &mBitPerfectPortId, sMediaAttr, AUDIO_SESSION_NONE, mUid, &isBitPerfect);
3606         status = mManager->startOutput(mBitPerfectPortId);
3607     }
3608     EXPECT_EQ(NO_ERROR, status);
3609     EXPECT_TRUE(isBitPerfect);
3610     EXPECT_NE(AUDIO_IO_HANDLE_NONE, mBitPerfectOutput);
3611     const auto bitPerfectOutputDesc = mManager->getOutputs().valueFor(mBitPerfectOutput);
3612     EXPECT_NE(nullptr, bitPerfectOutputDesc);
3613     EXPECT_EQ(AUDIO_OUTPUT_FLAG_BIT_PERFECT,
3614               bitPerfectOutputDesc->mFlags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
3615 };
3616 
reset()3617 void AudioPolicyManagerTestBitPerfectBase::reset() {
3618     mBitPerfectOutput = AUDIO_IO_HANDLE_NONE;
3619     mSelectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3620     mBitPerfectPortId = AUDIO_PORT_HANDLE_NONE;
3621 }
3622 
getBitPerfectOutput(status_t expected)3623 void AudioPolicyManagerTestBitPerfectBase::getBitPerfectOutput(status_t expected) {
3624     reset();
3625     audio_stream_type_t stream = AUDIO_STREAM_DEFAULT;
3626     AttributionSourceState attributionSource = createAttributionSourceState(mUid);
3627     audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3628     config.sample_rate = mBitPerfectSampleRate;
3629     config.channel_mask = mBitPerfectChannelMask;
3630     config.format = mBitPerfectFormat;
3631     audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_BIT_PERFECT;
3632     AudioPolicyInterface::output_type_t outputType;
3633     bool isSpatialized;
3634     bool isBitPerfect;
3635     EXPECT_EQ(expected,
3636               mManager->getOutputForAttr(&sMediaAttr, &mBitPerfectOutput, AUDIO_SESSION_NONE,
3637                                          &stream, attributionSource, &config, &flags,
3638                                          &mSelectedDeviceId, &mBitPerfectPortId, {}, &outputType,
3639                                          &isSpatialized, &isBitPerfect));
3640 }
3641 
3642 class AudioPolicyManagerTestBitPerfect : public AudioPolicyManagerTestBitPerfectBase {
3643 };
3644 
TEST_F(AudioPolicyManagerTestBitPerfect,UseBitPerfectOutput)3645 TEST_F(AudioPolicyManagerTestBitPerfect, UseBitPerfectOutput) {
3646     const uid_t anotherUid = 5678;
3647     audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3648     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3649     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
3650     bool isBitPerfect;
3651 
3652     // When there is no active bit-perfect playback, the output selection will follow default
3653     // routing strategy.
3654     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_QUAD,
3655                      48000, AUDIO_OUTPUT_FLAG_NONE, &output, &portId, sMediaAttr,
3656                      AUDIO_SESSION_NONE, mUid, &isBitPerfect);
3657     EXPECT_FALSE(isBitPerfect);
3658     EXPECT_NE(AUDIO_IO_HANDLE_NONE, output);
3659     const auto outputDesc = mManager->getOutputs().valueFor(output);
3660     EXPECT_NE(nullptr, outputDesc);
3661     EXPECT_NE(AUDIO_OUTPUT_FLAG_BIT_PERFECT, outputDesc->mFlags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
3662 
3663     // Start bit-perfect playback
3664     ASSERT_NO_FATAL_FAILURE(startBitPerfectOutput());
3665 
3666     // If the playback is from preferred mixer attributes owner but the request doesn't match
3667     // preferred mixer attributes, it will not be bit-perfect.
3668     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_QUAD,
3669                      48000, AUDIO_OUTPUT_FLAG_NONE, &output, &portId, sMediaAttr,
3670                      AUDIO_SESSION_NONE, mUid, &isBitPerfect);
3671     EXPECT_FALSE(isBitPerfect);
3672     EXPECT_EQ(mBitPerfectOutput, output);
3673 
3674     // When bit-perfect playback is active, all other playback will be routed to bit-perfect output.
3675     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
3676                      48000, AUDIO_OUTPUT_FLAG_NONE, &output, &portId, sMediaAttr,
3677                      AUDIO_SESSION_NONE, anotherUid, &isBitPerfect);
3678     EXPECT_FALSE(isBitPerfect);
3679     EXPECT_EQ(mBitPerfectOutput, output);
3680 
3681     // When bit-pefect playback is active, dtmf will also be routed to bit-perfect output.
3682     const audio_attributes_t dtmfAttr = {
3683             .content_type = AUDIO_CONTENT_TYPE_UNKNOWN,
3684             .usage = AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING,
3685     };
3686     audio_io_handle_t dtmfOutput = AUDIO_IO_HANDLE_NONE;
3687     selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3688     portId = AUDIO_PORT_HANDLE_NONE;
3689     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
3690                      48000, AUDIO_OUTPUT_FLAG_NONE, &dtmfOutput, &portId, dtmfAttr,
3691                      AUDIO_SESSION_NONE, anotherUid, &isBitPerfect);
3692     EXPECT_FALSE(isBitPerfect);
3693     EXPECT_EQ(mBitPerfectOutput, dtmfOutput);
3694 
3695     // When configuration matches preferred mixer attributes, which is bit-perfect, but the client
3696     // is not the owner of preferred mixer attributes, the playback will not be bit-perfect.
3697     getOutputForAttr(&selectedDeviceId, mBitPerfectFormat, mBitPerfectChannelMask,
3698                      mBitPerfectSampleRate, AUDIO_OUTPUT_FLAG_NONE, &output, &portId, sMediaAttr,
3699                      AUDIO_SESSION_NONE, anotherUid, &isBitPerfect);
3700     EXPECT_FALSE(isBitPerfect);
3701     EXPECT_EQ(mBitPerfectOutput, output);
3702 }
3703 
TEST_F_WITH_FLAGS(AudioPolicyManagerTestBitPerfect,InternalMuteWhenBitPerfectCLientIsActive,REQUIRES_FLAGS_ENABLED (ACONFIG_FLAG (com::android::media::audioserver,fix_concurrent_playback_behavior_with_bit_perfect_client)))3704 TEST_F_WITH_FLAGS(
3705         AudioPolicyManagerTestBitPerfect,
3706         InternalMuteWhenBitPerfectCLientIsActive,
3707         REQUIRES_FLAGS_ENABLED(
3708                 ACONFIG_FLAG(com::android::media::audioserver,
3709                              fix_concurrent_playback_behavior_with_bit_perfect_client))
3710 ) {
3711     ASSERT_NO_FATAL_FAILURE(startBitPerfectOutput());
3712 
3713     // When bit-perfect playback is active, the system sound will be routed to bit-perfect output.
3714     // The system sound will be muted internally in this case. The bit-perfect client will be
3715     // played normally.
3716     const uint32_t anotherSampleRate = 44100;
3717     audio_port_handle_t systemSoundPortId = AUDIO_PORT_HANDLE_NONE;
3718     audio_io_handle_t systemSoundOutput = AUDIO_IO_HANDLE_NONE;
3719     const audio_attributes_t systemSoundAttr = {
3720             .content_type = AUDIO_CONTENT_TYPE_SONIFICATION,
3721             .usage = AUDIO_USAGE_ASSISTANCE_SONIFICATION,
3722     };
3723     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3724     bool isBitPerfect;
3725     getOutputForAttr(&selectedDeviceId, mBitPerfectFormat, mBitPerfectChannelMask,
3726                      anotherSampleRate, AUDIO_OUTPUT_FLAG_NONE, &systemSoundOutput,
3727                      &systemSoundPortId, systemSoundAttr, AUDIO_SESSION_NONE, mUid, &isBitPerfect);
3728     EXPECT_FALSE(isBitPerfect);
3729     EXPECT_EQ(mBitPerfectOutput, systemSoundOutput);
3730     EXPECT_EQ(NO_ERROR, mManager->startOutput(systemSoundPortId));
3731     EXPECT_TRUE(mClient->getTrackInternalMute(systemSoundPortId));
3732     EXPECT_FALSE(mClient->getTrackInternalMute(mBitPerfectPortId));
3733     EXPECT_EQ(NO_ERROR, mManager->stopOutput(systemSoundPortId));
3734     EXPECT_FALSE(mClient->getTrackInternalMute(mBitPerfectPortId));
3735 
3736     // When bit-perfect playback is active, the notification will be routed to bit-perfect output.
3737     // The notification sound will be played normally while the bit-perfect client will be muted
3738     // internally.
3739     audio_port_handle_t notificationPortId = AUDIO_PORT_HANDLE_NONE;
3740     audio_io_handle_t notificationOutput = AUDIO_IO_HANDLE_NONE;
3741     const audio_attributes_t notificationAttr = {
3742             .content_type = AUDIO_CONTENT_TYPE_SONIFICATION,
3743             .usage = AUDIO_USAGE_NOTIFICATION,
3744     };
3745     getOutputForAttr(&selectedDeviceId, mBitPerfectFormat, mBitPerfectChannelMask,
3746                      anotherSampleRate, AUDIO_OUTPUT_FLAG_NONE, &notificationOutput,
3747                      &notificationPortId, notificationAttr, AUDIO_SESSION_NONE, mUid,
3748                      &isBitPerfect);
3749     EXPECT_FALSE(isBitPerfect);
3750     EXPECT_EQ(mBitPerfectOutput, notificationOutput);
3751     EXPECT_EQ(NO_ERROR, mManager->startOutput(notificationPortId));
3752     EXPECT_FALSE(mClient->getTrackInternalMute(notificationPortId));
3753     EXPECT_TRUE(mClient->getTrackInternalMute(mBitPerfectPortId));
3754     EXPECT_EQ(NO_ERROR, mManager->stopOutput(notificationPortId));
3755     EXPECT_FALSE(mClient->getTrackInternalMute(mBitPerfectPortId));
3756 
3757     EXPECT_EQ(NO_ERROR, mManager->stopOutput(mBitPerfectPortId));
3758 }
3759 
3760 class AudioPolicyManagerTestBitPerfectPhoneMode : public AudioPolicyManagerTestBitPerfectBase,
3761         public testing::WithParamInterface<audio_mode_t> {
3762 };
3763 
TEST_P(AudioPolicyManagerTestBitPerfectPhoneMode,RejectBitPerfectWhenPhoneModeIsNotNormal)3764 TEST_P(AudioPolicyManagerTestBitPerfectPhoneMode, RejectBitPerfectWhenPhoneModeIsNotNormal) {
3765     if (!com::android::media::audioserver::
3766             fix_concurrent_playback_behavior_with_bit_perfect_client()) {
3767         GTEST_SKIP()
3768                 << "Flag fix_concurrent_playback_behavior_with_bit_perfect_client is not enabled";
3769     }
3770 
3771     ASSERT_NO_FATAL_FAILURE(startBitPerfectOutput());
3772 
3773     audio_mode_t mode = GetParam();
3774     mManager->setPhoneState(mode);
3775     // When the phone mode is not normal, the bit-perfect output will be reopned
3776     EXPECT_EQ(nullptr, mManager->getOutputs().valueFor(mBitPerfectOutput));
3777 
3778     // When the phone mode is not normal, the bit-perfect output will be closed.
3779     ASSERT_NO_FATAL_FAILURE(getBitPerfectOutput(INVALID_OPERATION));
3780 
3781     mManager->setPhoneState(AUDIO_MODE_NORMAL);
3782 }
3783 
3784 INSTANTIATE_TEST_CASE_P(
3785         PhoneMode,
3786         AudioPolicyManagerTestBitPerfectPhoneMode,
3787         testing::Values(AUDIO_MODE_IN_CALL,
3788                         AUDIO_MODE_RINGTONE,
3789                         AUDIO_MODE_IN_COMMUNICATION,
3790                         AUDIO_MODE_CALL_SCREEN)
3791 );
3792 
3793 class AudioPolicyManagerTestBitPerfectHigherPriorityUseCaseActive :
3794         public AudioPolicyManagerTestBitPerfectBase,
3795         public testing::WithParamInterface<audio_usage_t> {
3796 };
3797 
TEST_P(AudioPolicyManagerTestBitPerfectHigherPriorityUseCaseActive,RejectBitPerfectWhenHigherPriorityUseCaseIsActive)3798 TEST_P(AudioPolicyManagerTestBitPerfectHigherPriorityUseCaseActive,
3799        RejectBitPerfectWhenHigherPriorityUseCaseIsActive) {
3800     if (!com::android::media::audioserver::
3801                 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
3802         GTEST_SKIP()
3803                 << "Flag fix_concurrent_playback_behavior_with_bit_perfect_client is not enabled";
3804     }
3805 
3806     ASSERT_NO_FATAL_FAILURE(startBitPerfectOutput());
3807 
3808     audio_attributes_t attr = {
3809             .usage = GetParam(),
3810             .content_type = AUDIO_CONTENT_TYPE_UNKNOWN
3811     };
3812     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3813     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
3814     audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3815     ASSERT_NO_FATAL_FAILURE(
3816             getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
3817                    48000, AUDIO_OUTPUT_FLAG_NONE, &output, &portId, attr));
3818     EXPECT_NE(mBitPerfectOutput, output);
3819     EXPECT_EQ(NO_ERROR, mManager->startOutput(portId));
3820     // When a high priority use case is active, the bit-perfect output will be closed.
3821     EXPECT_EQ(nullptr, mManager->getOutputs().valueFor(mBitPerfectOutput));
3822 
3823     // When any higher priority use case is active, the bit-perfect request will be rejected.
3824     ASSERT_NO_FATAL_FAILURE(getBitPerfectOutput(INVALID_OPERATION));
3825 }
3826 
3827 INSTANTIATE_TEST_CASE_P(
3828         HigherPriorityUseCases,
3829         AudioPolicyManagerTestBitPerfectHigherPriorityUseCaseActive,
3830         testing::Values(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE,
3831                         AUDIO_USAGE_ALARM)
3832 );
3833