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 <memory>
18 #include <string>
19 #include <sys/wait.h>
20 #include <unistd.h>
21 
22 #include <gtest/gtest.h>
23 
24 #define LOG_TAG "APM_Test"
25 #include <Serializer.h>
26 #include <android-base/file.h>
27 #include <media/AudioPolicy.h>
28 #include <media/PatchBuilder.h>
29 #include <media/RecordingActivityTracker.h>
30 #include <utils/Log.h>
31 #include <utils/Vector.h>
32 
33 #include "AudioPolicyInterface.h"
34 #include "AudioPolicyManagerTestClient.h"
35 #include "AudioPolicyTestClient.h"
36 #include "AudioPolicyTestManager.h"
37 
38 using namespace android;
39 
TEST(AudioPolicyManagerTestInit,EngineFailure)40 TEST(AudioPolicyManagerTestInit, EngineFailure) {
41     AudioPolicyTestClient client;
42     AudioPolicyTestManager manager(&client);
43     manager.getConfig().setDefault();
44     manager.getConfig().setEngineLibraryNameSuffix("non-existent");
45     ASSERT_EQ(NO_INIT, manager.initialize());
46     ASSERT_EQ(NO_INIT, manager.initCheck());
47 }
48 
TEST(AudioPolicyManagerTestInit,ClientFailure)49 TEST(AudioPolicyManagerTestInit, ClientFailure) {
50     AudioPolicyTestClient client;
51     AudioPolicyTestManager manager(&client);
52     manager.getConfig().setDefault();
53     // Since the default client fails to open anything,
54     // APM should indicate that the initialization didn't succeed.
55     ASSERT_EQ(NO_INIT, manager.initialize());
56     ASSERT_EQ(NO_INIT, manager.initCheck());
57 }
58 
59 
60 class PatchCountCheck {
61   public:
PatchCountCheck(AudioPolicyManagerTestClient * client)62     explicit PatchCountCheck(AudioPolicyManagerTestClient *client)
63             : mClient{client},
64               mInitialCount{mClient->getActivePatchesCount()} {}
deltaFromSnapshot() const65     int deltaFromSnapshot() const {
66         size_t currentCount = mClient->getActivePatchesCount();
67         if (mInitialCount <= currentCount) {
68             return currentCount - mInitialCount;
69         } else {
70             return -(static_cast<int>(mInitialCount - currentCount));
71         }
72     }
73   private:
74     const AudioPolicyManagerTestClient *mClient;
75     const size_t mInitialCount;
76 };
77 
78 class AudioPolicyManagerTest : public testing::Test {
79   protected:
80     void SetUp() override;
81     void TearDown() override;
82     virtual void SetUpManagerConfig();
83 
84     void dumpToLog();
85     // When explicitly routing is needed, selectedDeviceId need to be set as the wanted port
86     // id. Otherwise, selectedDeviceId need to be initialized as AUDIO_PORT_HANDLE_NONE.
87     void getOutputForAttr(
88             audio_port_handle_t *selectedDeviceId,
89             audio_format_t format,
90             int channelMask,
91             int sampleRate,
92             audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
93             audio_port_handle_t *portId = nullptr,
94             audio_attributes_t attr = {});
95     void getInputForAttr(
96             const audio_attributes_t &attr,
97             audio_unique_id_t riid,
98             audio_port_handle_t *selectedDeviceId,
99             audio_format_t format,
100             int channelMask,
101             int sampleRate,
102             audio_input_flags_t flags = AUDIO_INPUT_FLAG_NONE,
103             audio_port_handle_t *portId = nullptr);
snapshotPatchCount()104     PatchCountCheck snapshotPatchCount() { return PatchCountCheck(mClient.get()); }
105 
106     bool findDevicePort(audio_port_role_t role, audio_devices_t deviceType,
107             const std::string &address, audio_port &foundPort);
108     static audio_port_handle_t getDeviceIdFromPatch(const struct audio_patch* patch);
109 
110     std::unique_ptr<AudioPolicyManagerTestClient> mClient;
111     std::unique_ptr<AudioPolicyTestManager> mManager;
112 };
113 
SetUp()114 void AudioPolicyManagerTest::SetUp() {
115     mClient.reset(new AudioPolicyManagerTestClient);
116     mManager.reset(new AudioPolicyTestManager(mClient.get()));
117     SetUpManagerConfig();  // Subclasses may want to customize the config.
118     ASSERT_EQ(NO_ERROR, mManager->initialize());
119     ASSERT_EQ(NO_ERROR, mManager->initCheck());
120 }
121 
TearDown()122 void AudioPolicyManagerTest::TearDown() {
123     mManager.reset();
124     mClient.reset();
125 }
126 
SetUpManagerConfig()127 void AudioPolicyManagerTest::SetUpManagerConfig() {
128     mManager->getConfig().setDefault();
129 }
130 
dumpToLog()131 void AudioPolicyManagerTest::dumpToLog() {
132     int pipefd[2];
133     ASSERT_NE(-1, pipe(pipefd));
134     pid_t cpid = fork();
135     ASSERT_NE(-1, cpid);
136     if (cpid == 0) {
137         // Child process reads from the pipe and logs.
138         close(pipefd[1]);
139         std::string line;
140         char buf;
141         while (read(pipefd[0], &buf, sizeof(buf)) > 0) {
142             if (buf != '\n') {
143                 line += buf;
144             } else {
145                 ALOGI("%s", line.c_str());
146                 line = "";
147             }
148         }
149         if (!line.empty()) ALOGI("%s", line.c_str());
150         close(pipefd[0]);
151         _exit(EXIT_SUCCESS);
152     } else {
153         // Parent does the dump and checks the status code.
154         close(pipefd[0]);
155         ASSERT_EQ(NO_ERROR, mManager->dump(pipefd[1]));
156         close(pipefd[1]);
157         wait(NULL);  // Wait for the child to exit.
158     }
159 }
160 
getOutputForAttr(audio_port_handle_t * selectedDeviceId,audio_format_t format,int channelMask,int sampleRate,audio_output_flags_t flags,audio_port_handle_t * portId,audio_attributes_t attr)161 void AudioPolicyManagerTest::getOutputForAttr(
162         audio_port_handle_t *selectedDeviceId,
163         audio_format_t format,
164         int channelMask,
165         int sampleRate,
166         audio_output_flags_t flags,
167         audio_port_handle_t *portId,
168         audio_attributes_t attr) {
169     audio_io_handle_t output = AUDIO_PORT_HANDLE_NONE;
170     audio_stream_type_t stream = AUDIO_STREAM_DEFAULT;
171     audio_config_t config = AUDIO_CONFIG_INITIALIZER;
172     config.sample_rate = sampleRate;
173     config.channel_mask = channelMask;
174     config.format = format;
175     audio_port_handle_t localPortId;
176     if (!portId) portId = &localPortId;
177     *portId = AUDIO_PORT_HANDLE_NONE;
178     ASSERT_EQ(OK, mManager->getOutputForAttr(
179                     &attr, &output, AUDIO_SESSION_NONE, &stream, 0 /*uid*/, &config, &flags,
180                     selectedDeviceId, portId, {}));
181     ASSERT_NE(AUDIO_PORT_HANDLE_NONE, *portId);
182 }
183 
getInputForAttr(const audio_attributes_t & attr,audio_unique_id_t riid,audio_port_handle_t * selectedDeviceId,audio_format_t format,int channelMask,int sampleRate,audio_input_flags_t flags,audio_port_handle_t * portId)184 void AudioPolicyManagerTest::getInputForAttr(
185         const audio_attributes_t &attr,
186         audio_unique_id_t riid,
187         audio_port_handle_t *selectedDeviceId,
188         audio_format_t format,
189         int channelMask,
190         int sampleRate,
191         audio_input_flags_t flags,
192         audio_port_handle_t *portId) {
193     audio_io_handle_t input = AUDIO_PORT_HANDLE_NONE;
194     audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
195     config.sample_rate = sampleRate;
196     config.channel_mask = channelMask;
197     config.format = format;
198     audio_port_handle_t localPortId;
199     if (!portId) portId = &localPortId;
200     *portId = AUDIO_PORT_HANDLE_NONE;
201     AudioPolicyInterface::input_type_t inputType;
202     ASSERT_EQ(OK, mManager->getInputForAttr(
203             &attr, &input, riid, AUDIO_SESSION_NONE, 0 /*uid*/, &config, flags,
204             selectedDeviceId, &inputType, portId));
205     ASSERT_NE(AUDIO_PORT_HANDLE_NONE, *portId);
206 }
207 
findDevicePort(audio_port_role_t role,audio_devices_t deviceType,const std::string & address,audio_port & foundPort)208 bool AudioPolicyManagerTest::findDevicePort(audio_port_role_t role,
209         audio_devices_t deviceType, const std::string &address, audio_port &foundPort) {
210     uint32_t numPorts = 0;
211     uint32_t generation1;
212     status_t ret;
213 
214     ret = mManager->listAudioPorts(role, AUDIO_PORT_TYPE_DEVICE, &numPorts, nullptr, &generation1);
215     EXPECT_EQ(NO_ERROR, ret) << "mManager->listAudioPorts returned error";
216     if (HasFailure()) return false;
217 
218     uint32_t generation2;
219     struct audio_port ports[numPorts];
220     ret = mManager->listAudioPorts(role, AUDIO_PORT_TYPE_DEVICE, &numPorts, ports, &generation2);
221     EXPECT_EQ(NO_ERROR, ret) << "mManager->listAudioPorts returned error";
222     EXPECT_EQ(generation1, generation2) << "Generations changed during ports retrieval";
223     if (HasFailure()) return false;
224 
225     for (const auto &port : ports) {
226         if (port.role == role && port.ext.device.type == deviceType &&
227                 (strncmp(port.ext.device.address, address.c_str(),
228                          AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
229             foundPort = port;
230             return true;
231         }
232     }
233     return false;
234 }
235 
getDeviceIdFromPatch(const struct audio_patch * patch)236 audio_port_handle_t AudioPolicyManagerTest::getDeviceIdFromPatch(
237         const struct audio_patch* patch) {
238     // The logic here is the same as the one in AudioIoDescriptor.
239     // Note this function is aim to get routed device id for test.
240     // In that case, device to device patch is not expected here.
241     if (patch->num_sources != 0 && patch->num_sinks != 0) {
242         if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
243             return patch->sinks[0].id;
244         } else {
245             return patch->sources[0].id;
246         }
247     }
248     return AUDIO_PORT_HANDLE_NONE;
249 }
250 
251 
TEST_F(AudioPolicyManagerTest,InitSuccess)252 TEST_F(AudioPolicyManagerTest, InitSuccess) {
253     // SetUp must finish with no assertions.
254 }
255 
TEST_F(AudioPolicyManagerTest,Dump)256 TEST_F(AudioPolicyManagerTest, Dump) {
257     dumpToLog();
258 }
259 
TEST_F(AudioPolicyManagerTest,CreateAudioPatchFailure)260 TEST_F(AudioPolicyManagerTest, CreateAudioPatchFailure) {
261     audio_patch patch{};
262     audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
263     const PatchCountCheck patchCount = snapshotPatchCount();
264     ASSERT_EQ(BAD_VALUE, mManager->createAudioPatch(nullptr, &handle, 0));
265     ASSERT_EQ(BAD_VALUE, mManager->createAudioPatch(&patch, nullptr, 0));
266     ASSERT_EQ(BAD_VALUE, mManager->createAudioPatch(&patch, &handle, 0));
267     patch.num_sources = AUDIO_PATCH_PORTS_MAX + 1;
268     patch.num_sinks = 1;
269     ASSERT_EQ(BAD_VALUE, mManager->createAudioPatch(&patch, &handle, 0));
270     patch.num_sources = 1;
271     patch.num_sinks = AUDIO_PATCH_PORTS_MAX + 1;
272     ASSERT_EQ(BAD_VALUE, mManager->createAudioPatch(&patch, &handle, 0));
273     patch.num_sources = 2;
274     patch.num_sinks = 1;
275     ASSERT_EQ(INVALID_OPERATION, mManager->createAudioPatch(&patch, &handle, 0));
276     patch = {};
277     patch.num_sources = 1;
278     patch.sources[0].role = AUDIO_PORT_ROLE_SINK;
279     patch.num_sinks = 1;
280     patch.sinks[0].role = AUDIO_PORT_ROLE_SINK;
281     ASSERT_EQ(INVALID_OPERATION, mManager->createAudioPatch(&patch, &handle, 0));
282     patch = {};
283     patch.num_sources = 1;
284     patch.sources[0].role = AUDIO_PORT_ROLE_SOURCE;
285     patch.num_sinks = 1;
286     patch.sinks[0].role = AUDIO_PORT_ROLE_SOURCE;
287     ASSERT_EQ(INVALID_OPERATION, mManager->createAudioPatch(&patch, &handle, 0));
288     // Verify that the handle is left unchanged.
289     ASSERT_EQ(AUDIO_PATCH_HANDLE_NONE, handle);
290     ASSERT_EQ(0, patchCount.deltaFromSnapshot());
291 }
292 
TEST_F(AudioPolicyManagerTest,CreateAudioPatchFromMix)293 TEST_F(AudioPolicyManagerTest, CreateAudioPatchFromMix) {
294     audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
295     uid_t uid = 42;
296     const PatchCountCheck patchCount = snapshotPatchCount();
297     ASSERT_FALSE(mManager->getAvailableInputDevices().isEmpty());
298     PatchBuilder patchBuilder;
299     patchBuilder.addSource(mManager->getAvailableInputDevices()[0]).
300             addSink(mManager->getConfig().getDefaultOutputDevice());
301     ASSERT_EQ(NO_ERROR, mManager->createAudioPatch(patchBuilder.patch(), &handle, uid));
302     ASSERT_NE(AUDIO_PATCH_HANDLE_NONE, handle);
303     ASSERT_EQ(1, patchCount.deltaFromSnapshot());
304 }
305 
306 // TODO: Add patch creation tests that involve already existing patch
307 
308 class AudioPolicyManagerTestMsd : public AudioPolicyManagerTest {
309   protected:
310     void SetUpManagerConfig() override;
311     void TearDown() override;
312 
313     sp<DeviceDescriptor> mMsdOutputDevice;
314     sp<DeviceDescriptor> mMsdInputDevice;
315 };
316 
SetUpManagerConfig()317 void AudioPolicyManagerTestMsd::SetUpManagerConfig() {
318     // TODO: Consider using Serializer to load part of the config from a string.
319     AudioPolicyManagerTest::SetUpManagerConfig();
320     AudioPolicyConfig& config = mManager->getConfig();
321     mMsdOutputDevice = new DeviceDescriptor(AUDIO_DEVICE_OUT_BUS);
322     sp<AudioProfile> pcmOutputProfile = new AudioProfile(
323             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO, 48000);
324     sp<AudioProfile> ac3OutputProfile = new AudioProfile(
325             AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1, 48000);
326     mMsdOutputDevice->addAudioProfile(pcmOutputProfile);
327     mMsdOutputDevice->addAudioProfile(ac3OutputProfile);
328     mMsdInputDevice = new DeviceDescriptor(AUDIO_DEVICE_IN_BUS);
329     // Match output profile from AudioPolicyConfig::setDefault.
330     sp<AudioProfile> pcmInputProfile = new AudioProfile(
331             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO, 44100);
332     mMsdInputDevice->addAudioProfile(pcmInputProfile);
333     config.addDevice(mMsdOutputDevice);
334     config.addDevice(mMsdInputDevice);
335 
336     sp<HwModule> msdModule = new HwModule(AUDIO_HARDWARE_MODULE_ID_MSD, 2 /*halVersionMajor*/);
337     HwModuleCollection modules = config.getHwModules();
338     modules.add(msdModule);
339     config.setHwModules(modules);
340 
341     sp<OutputProfile> msdOutputProfile = new OutputProfile("msd input");
342     msdOutputProfile->addAudioProfile(pcmOutputProfile);
343     msdOutputProfile->addSupportedDevice(mMsdOutputDevice);
344     msdModule->addOutputProfile(msdOutputProfile);
345     sp<OutputProfile> msdCompressedOutputProfile = new OutputProfile("msd compressed input");
346     msdCompressedOutputProfile->addAudioProfile(ac3OutputProfile);
347     msdCompressedOutputProfile->setFlags(
348             AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
349             AUDIO_OUTPUT_FLAG_NON_BLOCKING);
350     msdCompressedOutputProfile->addSupportedDevice(mMsdOutputDevice);
351     msdModule->addOutputProfile(msdCompressedOutputProfile);
352 
353     sp<InputProfile> msdInputProfile = new InputProfile("msd output");
354     msdInputProfile->addAudioProfile(pcmInputProfile);
355     msdInputProfile->addSupportedDevice(mMsdInputDevice);
356     msdModule->addInputProfile(msdInputProfile);
357 
358     // Add a profile with another encoding to the default device to test routing
359     // of streams that are not supported by MSD.
360     sp<AudioProfile> dtsOutputProfile = new AudioProfile(
361             AUDIO_FORMAT_DTS, AUDIO_CHANNEL_OUT_5POINT1, 48000);
362     config.getDefaultOutputDevice()->addAudioProfile(dtsOutputProfile);
363     sp<OutputProfile> primaryEncodedOutputProfile = new OutputProfile("encoded");
364     primaryEncodedOutputProfile->addAudioProfile(dtsOutputProfile);
365     primaryEncodedOutputProfile->setFlags(AUDIO_OUTPUT_FLAG_DIRECT);
366     primaryEncodedOutputProfile->addSupportedDevice(config.getDefaultOutputDevice());
367     config.getHwModules().getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)->
368             addOutputProfile(primaryEncodedOutputProfile);
369 }
370 
TearDown()371 void AudioPolicyManagerTestMsd::TearDown() {
372     mMsdOutputDevice.clear();
373     mMsdInputDevice.clear();
374     AudioPolicyManagerTest::TearDown();
375 }
376 
TEST_F(AudioPolicyManagerTestMsd,InitSuccess)377 TEST_F(AudioPolicyManagerTestMsd, InitSuccess) {
378     ASSERT_TRUE(mMsdOutputDevice);
379     ASSERT_TRUE(mMsdInputDevice);
380 }
381 
TEST_F(AudioPolicyManagerTestMsd,Dump)382 TEST_F(AudioPolicyManagerTestMsd, Dump) {
383     dumpToLog();
384 }
385 
TEST_F(AudioPolicyManagerTestMsd,PatchCreationOnSetForceUse)386 TEST_F(AudioPolicyManagerTestMsd, PatchCreationOnSetForceUse) {
387     const PatchCountCheck patchCount = snapshotPatchCount();
388     mManager->setForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND,
389             AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS);
390     ASSERT_EQ(1, patchCount.deltaFromSnapshot());
391 }
392 
TEST_F(AudioPolicyManagerTestMsd,GetOutputForAttrEncodedRoutesToMsd)393 TEST_F(AudioPolicyManagerTestMsd, GetOutputForAttrEncodedRoutesToMsd) {
394     const PatchCountCheck patchCount = snapshotPatchCount();
395     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
396     getOutputForAttr(&selectedDeviceId,
397             AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1, 48000, AUDIO_OUTPUT_FLAG_DIRECT);
398     ASSERT_EQ(selectedDeviceId, mMsdOutputDevice->getId());
399     ASSERT_EQ(1, patchCount.deltaFromSnapshot());
400 }
401 
TEST_F(AudioPolicyManagerTestMsd,GetOutputForAttrPcmRoutesToMsd)402 TEST_F(AudioPolicyManagerTestMsd, GetOutputForAttrPcmRoutesToMsd) {
403     const PatchCountCheck patchCount = snapshotPatchCount();
404     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
405     getOutputForAttr(&selectedDeviceId,
406             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO, 48000);
407     ASSERT_EQ(selectedDeviceId, mMsdOutputDevice->getId());
408     ASSERT_EQ(1, patchCount.deltaFromSnapshot());
409 }
410 
TEST_F(AudioPolicyManagerTestMsd,GetOutputForAttrEncodedPlusPcmRoutesToMsd)411 TEST_F(AudioPolicyManagerTestMsd, GetOutputForAttrEncodedPlusPcmRoutesToMsd) {
412     const PatchCountCheck patchCount = snapshotPatchCount();
413     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
414     getOutputForAttr(&selectedDeviceId,
415             AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1, 48000, AUDIO_OUTPUT_FLAG_DIRECT);
416     ASSERT_EQ(selectedDeviceId, mMsdOutputDevice->getId());
417     ASSERT_EQ(1, patchCount.deltaFromSnapshot());
418     getOutputForAttr(&selectedDeviceId,
419             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO, 48000);
420     ASSERT_EQ(selectedDeviceId, mMsdOutputDevice->getId());
421     ASSERT_EQ(1, patchCount.deltaFromSnapshot());
422 }
423 
TEST_F(AudioPolicyManagerTestMsd,GetOutputForAttrUnsupportedFormatBypassesMsd)424 TEST_F(AudioPolicyManagerTestMsd, GetOutputForAttrUnsupportedFormatBypassesMsd) {
425     const PatchCountCheck patchCount = snapshotPatchCount();
426     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
427     getOutputForAttr(&selectedDeviceId,
428             AUDIO_FORMAT_DTS, AUDIO_CHANNEL_OUT_5POINT1, 48000, AUDIO_OUTPUT_FLAG_DIRECT);
429     ASSERT_NE(selectedDeviceId, mMsdOutputDevice->getId());
430     ASSERT_EQ(0, patchCount.deltaFromSnapshot());
431 }
432 
TEST_F(AudioPolicyManagerTestMsd,GetOutputForAttrFormatSwitching)433 TEST_F(AudioPolicyManagerTestMsd, GetOutputForAttrFormatSwitching) {
434     // Switch between formats that are supported and not supported by MSD.
435     {
436         const PatchCountCheck patchCount = snapshotPatchCount();
437         audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
438         audio_port_handle_t portId;
439         getOutputForAttr(&selectedDeviceId,
440                 AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1, 48000, AUDIO_OUTPUT_FLAG_DIRECT,
441                 &portId);
442         ASSERT_EQ(selectedDeviceId, mMsdOutputDevice->getId());
443         ASSERT_EQ(1, patchCount.deltaFromSnapshot());
444         mManager->releaseOutput(portId);
445         ASSERT_EQ(1, patchCount.deltaFromSnapshot());
446     }
447     {
448         const PatchCountCheck patchCount = snapshotPatchCount();
449         audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
450         audio_port_handle_t portId;
451         getOutputForAttr(&selectedDeviceId,
452                 AUDIO_FORMAT_DTS, AUDIO_CHANNEL_OUT_5POINT1, 48000, AUDIO_OUTPUT_FLAG_DIRECT,
453                 &portId);
454         ASSERT_NE(selectedDeviceId, mMsdOutputDevice->getId());
455         ASSERT_EQ(-1, patchCount.deltaFromSnapshot());
456         mManager->releaseOutput(portId);
457         ASSERT_EQ(0, patchCount.deltaFromSnapshot());
458     }
459     {
460         const PatchCountCheck patchCount = snapshotPatchCount();
461         audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
462         getOutputForAttr(&selectedDeviceId,
463                 AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1, 48000, AUDIO_OUTPUT_FLAG_DIRECT);
464         ASSERT_EQ(selectedDeviceId, mMsdOutputDevice->getId());
465         ASSERT_EQ(0, patchCount.deltaFromSnapshot());
466     }
467 }
468 
469 class AudioPolicyManagerTestWithConfigurationFile : public AudioPolicyManagerTest {
470 protected:
471     void SetUpManagerConfig() override;
getConfigFile()472     virtual std::string getConfigFile() { return sDefaultConfig; }
473 
474     static const std::string sExecutableDir;
475     static const std::string sDefaultConfig;
476 };
477 
478 const std::string AudioPolicyManagerTestWithConfigurationFile::sExecutableDir =
479         base::GetExecutableDirectory() + "/";
480 
481 const std::string AudioPolicyManagerTestWithConfigurationFile::sDefaultConfig =
482         sExecutableDir + "test_audio_policy_configuration.xml";
483 
SetUpManagerConfig()484 void AudioPolicyManagerTestWithConfigurationFile::SetUpManagerConfig() {
485     status_t status = deserializeAudioPolicyFile(getConfigFile().c_str(), &mManager->getConfig());
486     ASSERT_EQ(NO_ERROR, status);
487 }
488 
TEST_F(AudioPolicyManagerTestWithConfigurationFile,InitSuccess)489 TEST_F(AudioPolicyManagerTestWithConfigurationFile, InitSuccess) {
490     // SetUp must finish with no assertions.
491 }
492 
TEST_F(AudioPolicyManagerTestWithConfigurationFile,Dump)493 TEST_F(AudioPolicyManagerTestWithConfigurationFile, Dump) {
494     dumpToLog();
495 }
496 
497 using PolicyMixTuple = std::tuple<audio_usage_t, audio_source_t, uint32_t>;
498 
499 class AudioPolicyManagerTestDynamicPolicy : public AudioPolicyManagerTestWithConfigurationFile {
500 protected:
501     void TearDown() override;
502 
503     status_t addPolicyMix(int mixType, int mixFlag, audio_devices_t deviceType,
504             std::string mixAddress, const audio_config_t& audioConfig,
505             const std::vector<PolicyMixTuple>& rules);
506     void clearPolicyMix();
507 
508     Vector<AudioMix> mAudioMixes;
509     const std::string mMixAddress = "remote_submix_media";
510 };
511 
TearDown()512 void AudioPolicyManagerTestDynamicPolicy::TearDown() {
513     mManager->unregisterPolicyMixes(mAudioMixes);
514     AudioPolicyManagerTestWithConfigurationFile::TearDown();
515 }
516 
addPolicyMix(int mixType,int mixFlag,audio_devices_t deviceType,std::string mixAddress,const audio_config_t & audioConfig,const std::vector<PolicyMixTuple> & rules)517 status_t AudioPolicyManagerTestDynamicPolicy::addPolicyMix(int mixType, int mixFlag,
518         audio_devices_t deviceType, std::string mixAddress, const audio_config_t& audioConfig,
519         const std::vector<PolicyMixTuple>& rules) {
520     Vector<AudioMixMatchCriterion> myMixMatchCriteria;
521 
522     for(const auto &rule: rules) {
523         myMixMatchCriteria.add(AudioMixMatchCriterion(
524                 std::get<0>(rule), std::get<1>(rule), std::get<2>(rule)));
525     }
526 
527     AudioMix myAudioMix(myMixMatchCriteria, mixType, audioConfig, mixFlag,
528             String8(mixAddress.c_str()), 0);
529     myAudioMix.mDeviceType = deviceType;
530     // Clear mAudioMix before add new one to make sure we don't add already exist mixes.
531     mAudioMixes.clear();
532     mAudioMixes.add(myAudioMix);
533 
534     // As the policy mixes registration may fail at some case,
535     // caller need to check the returned status.
536     status_t ret = mManager->registerPolicyMixes(mAudioMixes);
537     return ret;
538 }
539 
clearPolicyMix()540 void AudioPolicyManagerTestDynamicPolicy::clearPolicyMix() {
541     if (mManager != nullptr) {
542         mManager->unregisterPolicyMixes(mAudioMixes);
543     }
544     mAudioMixes.clear();
545 }
546 
TEST_F(AudioPolicyManagerTestDynamicPolicy,InitSuccess)547 TEST_F(AudioPolicyManagerTestDynamicPolicy, InitSuccess) {
548     // SetUp must finish with no assertions
549 }
550 
TEST_F(AudioPolicyManagerTestDynamicPolicy,Dump)551 TEST_F(AudioPolicyManagerTestDynamicPolicy, Dump) {
552     dumpToLog();
553 }
554 
TEST_F(AudioPolicyManagerTestDynamicPolicy,RegisterPolicyMixes)555 TEST_F(AudioPolicyManagerTestDynamicPolicy, RegisterPolicyMixes) {
556     status_t ret;
557     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
558 
559     // Only capture of playback is allowed in LOOP_BACK &RENDER mode
560     ret = addPolicyMix(MIX_TYPE_RECORDERS, MIX_ROUTE_FLAG_LOOP_BACK_AND_RENDER,
561             AUDIO_DEVICE_OUT_REMOTE_SUBMIX, "", audioConfig, std::vector<PolicyMixTuple>());
562     ASSERT_EQ(INVALID_OPERATION, ret);
563 
564     // Fail due to the device is already connected.
565     clearPolicyMix();
566     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
567             AUDIO_DEVICE_OUT_REMOTE_SUBMIX, "", audioConfig, std::vector<PolicyMixTuple>());
568     ASSERT_EQ(INVALID_OPERATION, ret);
569 
570     // The first time to register policy mixes with valid parameter should succeed.
571     clearPolicyMix();
572     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
573     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
574     audioConfig.sample_rate = 48000;
575     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
576             AUDIO_DEVICE_OUT_REMOTE_SUBMIX, mMixAddress, audioConfig,
577             std::vector<PolicyMixTuple>());
578     ASSERT_EQ(NO_ERROR, ret);
579     // Registering the same policy mixes should fail.
580     ret = mManager->registerPolicyMixes(mAudioMixes);
581     ASSERT_EQ(INVALID_OPERATION, ret);
582 
583     // Registration should fail due to device not found.
584     // Note that earpiece is not present in the test configuration file.
585     // This will need to be updated if earpiece is added in the test configuration file.
586     clearPolicyMix();
587     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
588             AUDIO_DEVICE_OUT_EARPIECE, "", audioConfig, std::vector<PolicyMixTuple>());
589     ASSERT_EQ(INVALID_OPERATION, ret);
590 
591     // Registration should fail due to output not found.
592     clearPolicyMix();
593     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
594             AUDIO_DEVICE_OUT_REMOTE_SUBMIX, "", audioConfig, std::vector<PolicyMixTuple>());
595     ASSERT_EQ(INVALID_OPERATION, ret);
596 
597     // The first time to register valid policy mixes should succeed.
598     clearPolicyMix();
599     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
600             AUDIO_DEVICE_OUT_SPEAKER, "", audioConfig, std::vector<PolicyMixTuple>());
601     ASSERT_EQ(NO_ERROR, ret);
602     // Registering the same policy mixes should fail.
603     ret = mManager->registerPolicyMixes(mAudioMixes);
604     ASSERT_EQ(INVALID_OPERATION, ret);
605 }
606 
TEST_F(AudioPolicyManagerTestDynamicPolicy,UnregisterPolicyMixes)607 TEST_F(AudioPolicyManagerTestDynamicPolicy, UnregisterPolicyMixes) {
608     status_t ret;
609     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
610 
611     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
612     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
613     audioConfig.sample_rate = 48000;
614     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
615             AUDIO_DEVICE_OUT_REMOTE_SUBMIX, mMixAddress, audioConfig,
616             std::vector<PolicyMixTuple>());
617     ASSERT_EQ(NO_ERROR, ret);
618 
619     // After successfully registering policy mixes, it should be able to unregister.
620     ret = mManager->unregisterPolicyMixes(mAudioMixes);
621     ASSERT_EQ(NO_ERROR, ret);
622 
623     // After unregistering policy mixes successfully, it should fail unregistering
624     // the same policy mixes as they are not registered.
625     ret = mManager->unregisterPolicyMixes(mAudioMixes);
626     ASSERT_EQ(INVALID_OPERATION, ret);
627 }
628 
629 class AudioPolicyManagerTestDPNoRemoteSubmixModule : public AudioPolicyManagerTestDynamicPolicy {
630 protected:
getConfigFile()631     std::string getConfigFile() override { return sPrimaryOnlyConfig; }
632 
633     static const std::string sPrimaryOnlyConfig;
634 };
635 
636 const std::string AudioPolicyManagerTestDPNoRemoteSubmixModule::sPrimaryOnlyConfig =
637         sExecutableDir + "test_audio_policy_primary_only_configuration.xml";
638 
TEST_F(AudioPolicyManagerTestDPNoRemoteSubmixModule,InitSuccess)639 TEST_F(AudioPolicyManagerTestDPNoRemoteSubmixModule, InitSuccess) {
640     // SetUp must finish with no assertions.
641 }
642 
TEST_F(AudioPolicyManagerTestDPNoRemoteSubmixModule,Dump)643 TEST_F(AudioPolicyManagerTestDPNoRemoteSubmixModule, Dump) {
644     dumpToLog();
645 }
646 
TEST_F(AudioPolicyManagerTestDPNoRemoteSubmixModule,RegistrationFailure)647 TEST_F(AudioPolicyManagerTestDPNoRemoteSubmixModule, RegistrationFailure) {
648     // Registration/Unregistration should fail due to module for remote submix not found.
649     status_t ret;
650     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
651     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
652     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
653     audioConfig.sample_rate = 48000;
654     ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
655             AUDIO_DEVICE_OUT_REMOTE_SUBMIX, "", audioConfig, std::vector<PolicyMixTuple>());
656     ASSERT_EQ(INVALID_OPERATION, ret);
657 
658     ret = mManager->unregisterPolicyMixes(mAudioMixes);
659     ASSERT_EQ(INVALID_OPERATION, ret);
660 }
661 
662 class AudioPolicyManagerTestDPPlaybackReRouting : public AudioPolicyManagerTestDynamicPolicy,
663         public testing::WithParamInterface<audio_attributes_t> {
664 protected:
665     void SetUp() override;
666     void TearDown() override;
667 
668     std::unique_ptr<RecordingActivityTracker> mTracker;
669 
670     std::vector<PolicyMixTuple> mUsageRules = {
671             {AUDIO_USAGE_MEDIA, AUDIO_SOURCE_DEFAULT, RULE_MATCH_ATTRIBUTE_USAGE},
672             {AUDIO_USAGE_ALARM, AUDIO_SOURCE_DEFAULT, RULE_MATCH_ATTRIBUTE_USAGE}
673     };
674 
675     struct audio_port mInjectionPort;
676     audio_port_handle_t mPortId = AUDIO_PORT_HANDLE_NONE;
677 };
678 
SetUp()679 void AudioPolicyManagerTestDPPlaybackReRouting::SetUp() {
680     AudioPolicyManagerTestDynamicPolicy::SetUp();
681 
682     mTracker.reset(new RecordingActivityTracker());
683 
684     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
685     audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
686     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
687     audioConfig.sample_rate = 48000;
688     status_t ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
689             AUDIO_DEVICE_OUT_REMOTE_SUBMIX, mMixAddress, audioConfig, mUsageRules);
690     ASSERT_EQ(NO_ERROR, ret);
691 
692     struct audio_port extractionPort;
693     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SOURCE, AUDIO_DEVICE_IN_REMOTE_SUBMIX,
694                     mMixAddress, extractionPort));
695 
696     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
697     audio_source_t source = AUDIO_SOURCE_REMOTE_SUBMIX;
698     audio_attributes_t attr = {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN, source, 0, ""};
699     std::string tags = "addr=" + mMixAddress;
700     strncpy(attr.tags, tags.c_str(), AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1);
701     getInputForAttr(attr, mTracker->getRiid(), &selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT,
702             AUDIO_CHANNEL_IN_STEREO, 48000 /*sampleRate*/, AUDIO_INPUT_FLAG_NONE, &mPortId);
703     ASSERT_EQ(NO_ERROR, mManager->startInput(mPortId));
704     ASSERT_EQ(extractionPort.id, selectedDeviceId);
705 
706     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
707                     mMixAddress, mInjectionPort));
708 }
709 
TearDown()710 void AudioPolicyManagerTestDPPlaybackReRouting::TearDown() {
711     mManager->stopInput(mPortId);
712     AudioPolicyManagerTestDynamicPolicy::TearDown();
713 }
714 
TEST_F(AudioPolicyManagerTestDPPlaybackReRouting,InitSuccess)715 TEST_F(AudioPolicyManagerTestDPPlaybackReRouting, InitSuccess) {
716     // SetUp must finish with no assertions
717 }
718 
TEST_F(AudioPolicyManagerTestDPPlaybackReRouting,Dump)719 TEST_F(AudioPolicyManagerTestDPPlaybackReRouting, Dump) {
720     dumpToLog();
721 }
722 
TEST_P(AudioPolicyManagerTestDPPlaybackReRouting,PlaybackReRouting)723 TEST_P(AudioPolicyManagerTestDPPlaybackReRouting, PlaybackReRouting) {
724     const audio_attributes_t attr = GetParam();
725     const audio_usage_t usage = attr.usage;
726 
727     audio_port_handle_t playbackRoutedPortId = AUDIO_PORT_HANDLE_NONE;
728     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
729     getOutputForAttr(&playbackRoutedPortId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
730             48000 /*sampleRate*/, AUDIO_OUTPUT_FLAG_NONE, &portId, attr);
731     if (std::find_if(begin(mUsageRules), end(mUsageRules), [&usage](const auto &usageRule) {
732             return (std::get<0>(usageRule) == usage) &&
733             (std::get<2>(usageRule) == RULE_MATCH_ATTRIBUTE_USAGE);}) != end(mUsageRules) ||
734             (strncmp(attr.tags, "addr=", strlen("addr=")) == 0 &&
735                     strncmp(attr.tags + strlen("addr="), mMixAddress.c_str(),
736                     AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0)) {
737         EXPECT_EQ(mInjectionPort.id, playbackRoutedPortId);
738     } else {
739         EXPECT_NE(mInjectionPort.id, playbackRoutedPortId);
740     }
741 }
742 
743 INSTANTIATE_TEST_CASE_P(
744         PlaybackReroutingUsageMatch,
745         AudioPolicyManagerTestDPPlaybackReRouting,
746         testing::Values(
747                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_MEDIA,
748                                      AUDIO_SOURCE_DEFAULT, 0, ""},
749                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_ALARM,
750                                      AUDIO_SOURCE_DEFAULT, 0, ""}
751                 )
752         );
753 
754 INSTANTIATE_TEST_CASE_P(
755         PlaybackReroutingAddressPriorityMatch,
756         AudioPolicyManagerTestDPPlaybackReRouting,
757         testing::Values(
758                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_MEDIA,
759                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
760                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_VOICE_COMMUNICATION,
761                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
762                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
763                                      AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING,
764                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
765                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_ALARM,
766                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
767                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_NOTIFICATION,
768                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
769                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
770                                      AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE,
771                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
772                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
773                                      AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST,
774                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
775                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
776                                      AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT,
777                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
778                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
779                                      AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED,
780                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
781                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_NOTIFICATION_EVENT,
782                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
783                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
784                                      AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY,
785                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
786                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
787                                      AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
788                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
789                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
790                                      AUDIO_USAGE_ASSISTANCE_SONIFICATION,
791                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
792                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_GAME,
793                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
794                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_VIRTUAL_SOURCE,
795                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
796                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_ASSISTANT,
797                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
798                 (audio_attributes_t){AUDIO_CONTENT_TYPE_SPEECH, AUDIO_USAGE_ASSISTANT,
799                                      AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"}
800                 )
801         );
802 
803 INSTANTIATE_TEST_CASE_P(
804         PlaybackReroutingUnHandledUsages,
805         AudioPolicyManagerTestDPPlaybackReRouting,
806         testing::Values(
807                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_VOICE_COMMUNICATION,
808                                      AUDIO_SOURCE_DEFAULT, 0, ""},
809                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
810                                      AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING,
811                                      AUDIO_SOURCE_DEFAULT, 0, ""},
812                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_NOTIFICATION,
813                                      AUDIO_SOURCE_DEFAULT, 0, ""},
814                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
815                                      AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE,
816                                      AUDIO_SOURCE_DEFAULT, 0, ""},
817                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
818                                      AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST,
819                                      AUDIO_SOURCE_DEFAULT, 0, ""},
820                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
821                                      AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT,
822                                      AUDIO_SOURCE_DEFAULT, 0, ""},
823                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
824                                      AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED,
825                                      AUDIO_SOURCE_DEFAULT, 0, ""},
826                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_NOTIFICATION_EVENT,
827                                      AUDIO_SOURCE_DEFAULT, 0, ""},
828                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
829                                      AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY,
830                                      AUDIO_SOURCE_DEFAULT, 0, ""},
831                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
832                                      AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
833                                      AUDIO_SOURCE_DEFAULT, 0, ""},
834                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
835                                      AUDIO_USAGE_ASSISTANCE_SONIFICATION,
836                                      AUDIO_SOURCE_DEFAULT, 0, ""},
837                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_GAME,
838                                      AUDIO_SOURCE_DEFAULT, 0, ""},
839                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_ASSISTANT,
840                                      AUDIO_SOURCE_DEFAULT, 0, ""},
841                 (audio_attributes_t){AUDIO_CONTENT_TYPE_SPEECH, AUDIO_USAGE_ASSISTANT,
842                                      AUDIO_SOURCE_DEFAULT, 0, ""}
843                 )
844         );
845 
846 class AudioPolicyManagerTestDPMixRecordInjection : public AudioPolicyManagerTestDynamicPolicy,
847         public testing::WithParamInterface<audio_attributes_t> {
848 protected:
849     void SetUp() override;
850     void TearDown() override;
851 
852     std::unique_ptr<RecordingActivityTracker> mTracker;
853 
854     std::vector<PolicyMixTuple> mSourceRules = {
855         {AUDIO_USAGE_UNKNOWN, AUDIO_SOURCE_CAMCORDER, RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET},
856         {AUDIO_USAGE_UNKNOWN, AUDIO_SOURCE_MIC, RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET},
857         {AUDIO_USAGE_UNKNOWN, AUDIO_SOURCE_VOICE_COMMUNICATION, RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET}
858     };
859 
860     struct audio_port mExtractionPort;
861     audio_port_handle_t mPortId = AUDIO_PORT_HANDLE_NONE;
862 };
863 
SetUp()864 void AudioPolicyManagerTestDPMixRecordInjection::SetUp() {
865     AudioPolicyManagerTestDynamicPolicy::SetUp();
866 
867     mTracker.reset(new RecordingActivityTracker());
868 
869     audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
870     audioConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
871     audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
872     audioConfig.sample_rate = 48000;
873     status_t ret = addPolicyMix(MIX_TYPE_RECORDERS, MIX_ROUTE_FLAG_LOOP_BACK,
874             AUDIO_DEVICE_IN_REMOTE_SUBMIX, mMixAddress, audioConfig, mSourceRules);
875     ASSERT_EQ(NO_ERROR, ret);
876 
877     struct audio_port injectionPort;
878     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
879                     mMixAddress, injectionPort));
880 
881     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
882     audio_usage_t usage = AUDIO_USAGE_VIRTUAL_SOURCE;
883     audio_attributes_t attr = {AUDIO_CONTENT_TYPE_UNKNOWN, usage, AUDIO_SOURCE_DEFAULT, 0, ""};
884     std::string tags = std::string("addr=") + mMixAddress;
885     strncpy(attr.tags, tags.c_str(), AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1);
886     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
887             48000 /*sampleRate*/, AUDIO_OUTPUT_FLAG_NONE, &mPortId, attr);
888     ASSERT_EQ(NO_ERROR, mManager->startOutput(mPortId));
889     ASSERT_EQ(injectionPort.id, getDeviceIdFromPatch(mClient->getLastAddedPatch()));
890 
891     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SOURCE, AUDIO_DEVICE_IN_REMOTE_SUBMIX,
892                     mMixAddress, mExtractionPort));
893 }
894 
TearDown()895 void AudioPolicyManagerTestDPMixRecordInjection::TearDown() {
896     mManager->stopOutput(mPortId);
897     AudioPolicyManagerTestDynamicPolicy::TearDown();
898 }
899 
TEST_F(AudioPolicyManagerTestDPMixRecordInjection,InitSuccess)900 TEST_F(AudioPolicyManagerTestDPMixRecordInjection, InitSuccess) {
901     // SetUp mush finish with no assertions.
902 }
903 
TEST_F(AudioPolicyManagerTestDPMixRecordInjection,Dump)904 TEST_F(AudioPolicyManagerTestDPMixRecordInjection, Dump) {
905     dumpToLog();
906 }
907 
TEST_P(AudioPolicyManagerTestDPMixRecordInjection,RecordingInjection)908 TEST_P(AudioPolicyManagerTestDPMixRecordInjection, RecordingInjection) {
909     const audio_attributes_t attr = GetParam();
910     const audio_source_t source = attr.source;
911 
912     audio_port_handle_t captureRoutedPortId = AUDIO_PORT_HANDLE_NONE;
913     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
914     getInputForAttr(attr, mTracker->getRiid(), &captureRoutedPortId, AUDIO_FORMAT_PCM_16_BIT,
915             AUDIO_CHANNEL_IN_STEREO, 48000 /*sampleRate*/, AUDIO_INPUT_FLAG_NONE, &portId);
916     if (std::find_if(begin(mSourceRules), end(mSourceRules), [&source](const auto &sourceRule) {
917             return (std::get<1>(sourceRule) == source) &&
918             (std::get<2>(sourceRule) == RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET);})
919             != end(mSourceRules)) {
920         EXPECT_EQ(mExtractionPort.id, captureRoutedPortId);
921     } else {
922         EXPECT_NE(mExtractionPort.id, captureRoutedPortId);
923     }
924 }
925 
926 // No address priority rule for remote recording, address is a "don't care"
927 INSTANTIATE_TEST_CASE_P(
928         RecordInjectionSourceMatch,
929         AudioPolicyManagerTestDPMixRecordInjection,
930         testing::Values(
931                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
932                                      AUDIO_SOURCE_CAMCORDER, 0, ""},
933                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
934                                      AUDIO_SOURCE_CAMCORDER, 0, "addr=remote_submix_media"},
935                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
936                                      AUDIO_SOURCE_MIC, 0, "addr=remote_submix_media"},
937                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
938                                      AUDIO_SOURCE_MIC, 0, ""},
939                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
940                                      AUDIO_SOURCE_VOICE_COMMUNICATION, 0, ""},
941                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
942                                      AUDIO_SOURCE_VOICE_COMMUNICATION, 0,
943                                      "addr=remote_submix_media"}
944                 )
945         );
946 
947 // No address priority rule for remote recording
948 INSTANTIATE_TEST_CASE_P(
949         RecordInjectionSourceNotMatch,
950         AudioPolicyManagerTestDPMixRecordInjection,
951         testing::Values(
952                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
953                                      AUDIO_SOURCE_VOICE_RECOGNITION, 0, ""},
954                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
955                                      AUDIO_SOURCE_HOTWORD, 0, ""},
956                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
957                                      AUDIO_SOURCE_VOICE_RECOGNITION, 0,
958                                      "addr=remote_submix_media"},
959                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
960                                      AUDIO_SOURCE_HOTWORD, 0, "addr=remote_submix_media"}
961                 )
962         );
963 
964 using DeviceConnectionTestParams =
965         std::tuple<audio_devices_t /*type*/, std::string /*name*/, std::string /*address*/>;
966 
967 class AudioPolicyManagerTestDeviceConnection : public AudioPolicyManagerTestWithConfigurationFile,
968         public testing::WithParamInterface<DeviceConnectionTestParams> {
969 };
970 
TEST_F(AudioPolicyManagerTestDeviceConnection,InitSuccess)971 TEST_F(AudioPolicyManagerTestDeviceConnection, InitSuccess) {
972     // SetUp must finish with no assertions.
973 }
974 
TEST_F(AudioPolicyManagerTestDeviceConnection,Dump)975 TEST_F(AudioPolicyManagerTestDeviceConnection, Dump) {
976     dumpToLog();
977 }
978 
TEST_P(AudioPolicyManagerTestDeviceConnection,SetDeviceConnectionState)979 TEST_P(AudioPolicyManagerTestDeviceConnection, SetDeviceConnectionState) {
980     const audio_devices_t type = std::get<0>(GetParam());
981     const std::string name = std::get<1>(GetParam());
982     const std::string address = std::get<2>(GetParam());
983 
984     if (type == AUDIO_DEVICE_OUT_HDMI) {
985         // Set device connection state failed due to no device descriptor found
986         // For HDMI case, it is easier to simulate device descriptor not found error
987         // by using a undeclared encoded format.
988         ASSERT_EQ(INVALID_OPERATION, mManager->setDeviceConnectionState(
989                 type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
990                 address.c_str(), name.c_str(), AUDIO_FORMAT_MAT_2_1));
991     }
992     // Connect with valid parameters should succeed
993     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
994             type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
995             address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
996     // Try to connect with the same device again should fail
997     ASSERT_EQ(INVALID_OPERATION, mManager->setDeviceConnectionState(
998             type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
999             address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
1000     // Disconnect the connected device should succeed
1001     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
1002             type, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1003             address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
1004     // Disconnect device that is not connected should fail
1005     ASSERT_EQ(INVALID_OPERATION, mManager->setDeviceConnectionState(
1006             type, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1007             address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
1008     // Try to set device connection state  with a invalid connection state should fail
1009     ASSERT_EQ(BAD_VALUE, mManager->setDeviceConnectionState(
1010             type, AUDIO_POLICY_DEVICE_STATE_CNT,
1011             "", "", AUDIO_FORMAT_DEFAULT));
1012 }
1013 
TEST_P(AudioPolicyManagerTestDeviceConnection,ExplicitlyRoutingAfterConnection)1014 TEST_P(AudioPolicyManagerTestDeviceConnection, ExplicitlyRoutingAfterConnection) {
1015     const audio_devices_t type = std::get<0>(GetParam());
1016     const std::string name = std::get<1>(GetParam());
1017     const std::string address = std::get<2>(GetParam());
1018 
1019     // Connect device to do explicitly routing test
1020     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
1021             type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1022             address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
1023 
1024     audio_port devicePort;
1025     const audio_port_role_t role = audio_is_output_device(type)
1026             ? AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
1027     ASSERT_TRUE(findDevicePort(role, type, address, devicePort));
1028 
1029     audio_port_handle_t routedPortId = devicePort.id;
1030     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
1031     // Try start input or output according to the device type
1032     if (audio_is_output_devices(type)) {
1033         getOutputForAttr(&routedPortId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
1034                 48000 /*sampleRate*/, AUDIO_OUTPUT_FLAG_NONE, &portId);
1035     } else if (audio_is_input_device(type)) {
1036         RecordingActivityTracker tracker;
1037         getInputForAttr({}, tracker.getRiid(), &routedPortId, AUDIO_FORMAT_PCM_16_BIT,
1038                 AUDIO_CHANNEL_IN_STEREO, 48000 /*sampleRate*/, AUDIO_INPUT_FLAG_NONE, &portId);
1039     }
1040     ASSERT_EQ(devicePort.id, routedPortId);
1041 
1042     ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
1043             type, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1044             address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
1045 }
1046 
1047 INSTANTIATE_TEST_CASE_P(
1048         DeviceConnectionState,
1049         AudioPolicyManagerTestDeviceConnection,
1050         testing::Values(
1051                 DeviceConnectionTestParams({AUDIO_DEVICE_IN_HDMI, "test_in_hdmi",
1052                                             "audio_policy_test_in_hdmi"}),
1053                 DeviceConnectionTestParams({AUDIO_DEVICE_OUT_HDMI, "test_out_hdmi",
1054                                             "audio_policy_test_out_hdmi"}),
1055                 DeviceConnectionTestParams({AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "bt_hfp_in",
1056                                             "hfp_client_in"}),
1057                 DeviceConnectionTestParams({AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "bt_hfp_out",
1058                                             "hfp_client_out"})
1059                 )
1060         );
1061 
1062 class AudioPolicyManagerDynamicHwModulesTest : public AudioPolicyManagerTestWithConfigurationFile {
1063 protected:
1064     void SetUpManagerConfig() override;
1065 };
1066 
SetUpManagerConfig()1067 void AudioPolicyManagerDynamicHwModulesTest::SetUpManagerConfig() {
1068     AudioPolicyManagerTestWithConfigurationFile::SetUpManagerConfig();
1069     // Only allow successful opening of "primary" hw module during APM initialization.
1070     mClient->swapAllowedModuleNames({"primary"});
1071 }
1072 
TEST_F(AudioPolicyManagerDynamicHwModulesTest,InitSuccess)1073 TEST_F(AudioPolicyManagerDynamicHwModulesTest, InitSuccess) {
1074     // SetUp must finish with no assertions.
1075 }
1076 
TEST_F(AudioPolicyManagerDynamicHwModulesTest,DynamicAddition)1077 TEST_F(AudioPolicyManagerDynamicHwModulesTest, DynamicAddition) {
1078     const auto handleBefore = mClient->peekNextModuleHandle();
1079     mManager->onNewAudioModulesAvailable();
1080     ASSERT_EQ(handleBefore, mClient->peekNextModuleHandle());
1081     // Reset module loading restrictions.
1082     mClient->swapAllowedModuleNames();
1083     mManager->onNewAudioModulesAvailable();
1084     const auto handleAfter = mClient->peekNextModuleHandle();
1085     ASSERT_GT(handleAfter, handleBefore);
1086     mManager->onNewAudioModulesAvailable();
1087     ASSERT_EQ(handleAfter, mClient->peekNextModuleHandle());
1088 }
1089 
TEST_F(AudioPolicyManagerDynamicHwModulesTest,AddedDeviceAvailable)1090 TEST_F(AudioPolicyManagerDynamicHwModulesTest, AddedDeviceAvailable) {
1091     ASSERT_EQ(AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, mManager->getDeviceConnectionState(
1092                     AUDIO_DEVICE_IN_REMOTE_SUBMIX, "0"));
1093     mClient->swapAllowedModuleNames({"primary", "r_submix"});
1094     mManager->onNewAudioModulesAvailable();
1095     ASSERT_EQ(AUDIO_POLICY_DEVICE_STATE_AVAILABLE, mManager->getDeviceConnectionState(
1096                     AUDIO_DEVICE_IN_REMOTE_SUBMIX, "0"));
1097 }
1098 
TEST_F(AudioPolicyManagerDynamicHwModulesTest,ListAddedAudioPorts)1099 TEST_F(AudioPolicyManagerDynamicHwModulesTest, ListAddedAudioPorts) {
1100     struct audio_port port;
1101     ASSERT_FALSE(findDevicePort(AUDIO_PORT_ROLE_SOURCE, AUDIO_DEVICE_IN_REMOTE_SUBMIX, "0", port));
1102     mClient->swapAllowedModuleNames({"primary", "r_submix"});
1103     mManager->onNewAudioModulesAvailable();
1104     ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SOURCE, AUDIO_DEVICE_IN_REMOTE_SUBMIX, "0", port));
1105 }
1106 
TEST_F(AudioPolicyManagerDynamicHwModulesTest,ClientIsUpdated)1107 TEST_F(AudioPolicyManagerDynamicHwModulesTest, ClientIsUpdated) {
1108     const size_t prevAudioPortListUpdateCount = mClient->getAudioPortListUpdateCount();
1109     const uint32_t prevAudioPortGeneration = mManager->getAudioPortGeneration();
1110     mClient->swapAllowedModuleNames({"primary", "r_submix"});
1111     mManager->onNewAudioModulesAvailable();
1112     EXPECT_GT(mClient->getAudioPortListUpdateCount(), prevAudioPortListUpdateCount);
1113     EXPECT_GT(mManager->getAudioPortGeneration(), prevAudioPortGeneration);
1114 }
1115