blob: ad8657c4c2d5e3904e25d71e665e349e14bbe2cc [file] [log] [blame]
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08001/*
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
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +020017#include <cstring>
Mikhail Naganov04a86632017-12-15 18:01:42 -080018#include <memory>
jiabinf4eb15a2019-08-28 15:31:47 -070019#include <string>
Mikhail Naganov21b43362018-06-04 10:37:09 -070020#include <sys/wait.h>
21#include <unistd.h>
Mikhail Naganov04a86632017-12-15 18:01:42 -080022
Mikhail Naganovad3f8a12017-12-12 13:24:23 -080023#include <gtest/gtest.h>
Jiabin Huang3b98d322020-09-03 17:54:16 +000024#include <gmock/gmock.h>
Mikhail Naganovad3f8a12017-12-12 13:24:23 -080025
Mikhail Naganov21b43362018-06-04 10:37:09 -070026#define LOG_TAG "APM_Test"
jiabinf4eb15a2019-08-28 15:31:47 -070027#include <Serializer.h>
28#include <android-base/file.h>
François Gaffie6ebbce02023-07-19 13:27:53 +020029#include <android-base/properties.h>
Svet Ganov3e5f14f2021-05-13 22:51:08 +000030#include <android/content/AttributionSourceState.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010031#include <android_media_audiopolicy.h>
jiabin220eea12024-05-17 17:55:20 +000032#include <com_android_media_audioserver.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010033#include <flag_macros.h>
François Gaffie6ebbce02023-07-19 13:27:53 +020034#include <hardware/audio_effect.h>
jiabinf4eb15a2019-08-28 15:31:47 -070035#include <media/AudioPolicy.h>
Mikhail Naganovdc769682018-05-04 15:34:08 -070036#include <media/PatchBuilder.h>
jiabinf4eb15a2019-08-28 15:31:47 -070037#include <media/RecordingActivityTracker.h>
Mikhail Naganov806170e2024-09-05 17:26:50 -070038#include <media/TypeConverter.h>
jiabinf4eb15a2019-08-28 15:31:47 -070039#include <utils/Log.h>
40#include <utils/Vector.h>
Oscar Azucena4f49ef62023-01-25 23:32:13 -080041#include <cutils/multiuser.h>
Mikhail Naganovdc769682018-05-04 15:34:08 -070042
jiabinf4eb15a2019-08-28 15:31:47 -070043#include "AudioPolicyInterface.h"
jiabinb3f98042019-09-26 17:56:44 -070044#include "AudioPolicyManagerTestClient.h"
Mikhail Naganovad3f8a12017-12-12 13:24:23 -080045#include "AudioPolicyTestClient.h"
46#include "AudioPolicyTestManager.h"
Mikhail Naganov70b52652024-09-06 10:23:24 -070047#include "test_execution_tracer.h"
Mikhail Naganovad3f8a12017-12-12 13:24:23 -080048
49using namespace android;
Jiabin Huang3b98d322020-09-03 17:54:16 +000050using testing::UnorderedElementsAre;
Marvin Raminbdefaf02023-11-01 09:10:32 +010051using testing::IsEmpty;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000052using android::content::AttributionSourceState;
Mikhail Naganovad3f8a12017-12-12 13:24:23 -080053
Jan Sebechlebsky0e7b2f12022-08-18 14:40:37 +020054namespace {
55
56AudioMixMatchCriterion createUidCriterion(uint32_t uid, bool exclude = false) {
57 AudioMixMatchCriterion criterion;
58 criterion.mValue.mUid = uid;
59 criterion.mRule = exclude ? RULE_EXCLUDE_UID : RULE_MATCH_UID;
60 return criterion;
61}
62
Oscar Azucena873d10f2023-01-12 18:34:42 -080063AudioMixMatchCriterion createUserIdCriterion(int userId, bool exclude = false) {
64 AudioMixMatchCriterion criterion;
65 criterion.mValue.mUserId = userId;
66 criterion.mRule = exclude ? RULE_EXCLUDE_USERID : RULE_MATCH_USERID;
67 return criterion;
68}
69
Jan Sebechlebsky0e7b2f12022-08-18 14:40:37 +020070AudioMixMatchCriterion createUsageCriterion(audio_usage_t usage, bool exclude = false) {
71 AudioMixMatchCriterion criterion;
72 criterion.mValue.mUsage = usage;
73 criterion.mRule = exclude ? RULE_EXCLUDE_ATTRIBUTE_USAGE : RULE_MATCH_ATTRIBUTE_USAGE;
74 return criterion;
75}
76
77AudioMixMatchCriterion createCapturePresetCriterion(audio_source_t source, bool exclude = false) {
78 AudioMixMatchCriterion criterion;
79 criterion.mValue.mSource = source;
80 criterion.mRule = exclude ?
81 RULE_EXCLUDE_ATTRIBUTE_CAPTURE_PRESET : RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET;
82 return criterion;
83}
84
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +020085AudioMixMatchCriterion createSessionIdCriterion(audio_session_t session, bool exclude = false) {
86 AudioMixMatchCriterion criterion;
87 criterion.mValue.mAudioSessionId = session;
88 criterion.mRule = exclude ?
89 RULE_EXCLUDE_AUDIO_SESSION_ID : RULE_MATCH_AUDIO_SESSION_ID;
90 return criterion;
91}
92
Jan Sebechlebsky8e10cea2023-03-29 11:43:31 +020093// TODO b/182392769: use attribution source util
94AttributionSourceState createAttributionSourceState(uid_t uid) {
95 AttributionSourceState attributionSourceState;
96 attributionSourceState.uid = uid;
97 attributionSourceState.token = sp<BBinder>::make();
98 return attributionSourceState;
99}
100
jiabin66acc432024-02-06 00:57:36 +0000101bool equals(const audio_config_base_t& config1, const audio_config_base_t& config2) {
102 return config1.format == config2.format
103 && config1.sample_rate == config2.sample_rate
104 && config1.channel_mask == config2.channel_mask;
105}
106
Jan Sebechlebsky0e7b2f12022-08-18 14:40:37 +0200107} // namespace
108
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700109TEST(AudioPolicyConfigTest, DefaultConfigForTestsIsEmpty) {
110 auto config = AudioPolicyConfig::createWritableForTests();
111 EXPECT_TRUE(config->getSource().empty());
112 EXPECT_TRUE(config->getHwModules().isEmpty());
113 EXPECT_TRUE(config->getInputDevices().isEmpty());
114 EXPECT_TRUE(config->getOutputDevices().isEmpty());
115}
116
117TEST(AudioPolicyConfigTest, FallbackToDefault) {
118 auto config = AudioPolicyConfig::loadFromApmXmlConfigWithFallback(
119 base::GetExecutableDirectory() + "/test_invalid_audio_policy_configuration.xml");
120 EXPECT_EQ(AudioPolicyConfig::kDefaultConfigSource, config->getSource());
121}
122
123TEST(AudioPolicyConfigTest, LoadForTests) {
124 {
125 auto result = AudioPolicyConfig::loadFromCustomXmlConfigForTests(
126 base::GetExecutableDirectory() + "/test_invalid_audio_policy_configuration.xml");
127 EXPECT_FALSE(result.ok());
128 }
129 {
130 const std::string source =
131 base::GetExecutableDirectory() + "/test_audio_policy_configuration.xml";
132 auto result = AudioPolicyConfig::loadFromCustomXmlConfigForTests(source);
133 ASSERT_TRUE(result.ok());
134 EXPECT_EQ(source, result.value()->getSource());
135 EXPECT_FALSE(result.value()->getHwModules().isEmpty());
136 EXPECT_FALSE(result.value()->getInputDevices().isEmpty());
137 EXPECT_FALSE(result.value()->getOutputDevices().isEmpty());
138 }
139}
140
Mikhail Naganov47835552019-05-14 10:32:51 -0700141TEST(AudioPolicyManagerTestInit, EngineFailure) {
142 AudioPolicyTestClient client;
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700143 auto config = AudioPolicyConfig::createWritableForTests();
144 config->setDefault();
145 config->setEngineLibraryNameSuffix("non-existent");
146 AudioPolicyTestManager manager(config, &client);
Mikhail Naganov47835552019-05-14 10:32:51 -0700147 ASSERT_EQ(NO_INIT, manager.initialize());
148 ASSERT_EQ(NO_INIT, manager.initCheck());
149}
150
151TEST(AudioPolicyManagerTestInit, ClientFailure) {
Mikhail Naganovad3f8a12017-12-12 13:24:23 -0800152 AudioPolicyTestClient client;
153 AudioPolicyTestManager manager(&client);
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -0800154 // Since the default client fails to open anything,
155 // APM should indicate that the initialization didn't succeed.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -0800156 ASSERT_EQ(NO_INIT, manager.initialize());
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -0800157 ASSERT_EQ(NO_INIT, manager.initCheck());
158}
159
160
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800161class PatchCountCheck {
162 public:
163 explicit PatchCountCheck(AudioPolicyManagerTestClient *client)
164 : mClient{client},
165 mInitialCount{mClient->getActivePatchesCount()} {}
Mikhail Naganovd53525f2019-01-24 13:15:46 -0800166 int deltaFromSnapshot() const {
167 size_t currentCount = mClient->getActivePatchesCount();
168 if (mInitialCount <= currentCount) {
169 return currentCount - mInitialCount;
170 } else {
171 return -(static_cast<int>(mInitialCount - currentCount));
172 }
173 }
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800174 private:
175 const AudioPolicyManagerTestClient *mClient;
176 const size_t mInitialCount;
177};
178
Mikhail Naganov04a86632017-12-15 18:01:42 -0800179class AudioPolicyManagerTest : public testing::Test {
Mikhail Naganov806170e2024-09-05 17:26:50 -0700180 public:
181 constexpr static uint32_t k384000SamplingRate = 384000;
182 constexpr static uint32_t k48000SamplingRate = 48000;
183 constexpr static uint32_t k96000SamplingRate = 96000;
184
Mikhail Naganov04a86632017-12-15 18:01:42 -0800185 protected:
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800186 void SetUp() override;
187 void TearDown() override;
jiabin7c0205e2019-09-05 10:26:04 -0700188 virtual void SetUpManagerConfig();
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800189
190 void dumpToLog();
Mikhail Naganov0756bbf2019-09-06 13:53:26 -0700191 // When explicit routing is needed, selectedDeviceId needs to be set as the wanted port
192 // id. Otherwise, selectedDeviceId needs to be initialized as AUDIO_PORT_HANDLE_NONE.
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800193 void getOutputForAttr(
194 audio_port_handle_t *selectedDeviceId,
195 audio_format_t format,
Mikhail Naganov55773032020-10-01 15:08:13 -0700196 audio_channel_mask_t channelMask,
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800197 int sampleRate,
198 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
Mikhail Naganov0756bbf2019-09-06 13:53:26 -0700199 audio_io_handle_t *output = nullptr,
jiabinf4eb15a2019-08-28 15:31:47 -0700200 audio_port_handle_t *portId = nullptr,
Mikhail Naganov806170e2024-09-05 17:26:50 -0700201 audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER,
jiabin3ff8d7d2022-12-13 06:27:44 +0000202 audio_session_t session = AUDIO_SESSION_NONE,
jiabin5eaf0962022-12-20 20:11:38 +0000203 int uid = 0,
204 bool* isBitPerfect = nullptr);
jiabinf4eb15a2019-08-28 15:31:47 -0700205 void getInputForAttr(
206 const audio_attributes_t &attr,
François Gaffie6ebbce02023-07-19 13:27:53 +0200207 audio_io_handle_t *input,
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +0200208 audio_session_t session,
jiabinf4eb15a2019-08-28 15:31:47 -0700209 audio_unique_id_t riid,
210 audio_port_handle_t *selectedDeviceId,
211 audio_format_t format,
Mikhail Naganov55773032020-10-01 15:08:13 -0700212 audio_channel_mask_t channelMask,
jiabinf4eb15a2019-08-28 15:31:47 -0700213 int sampleRate,
214 audio_input_flags_t flags = AUDIO_INPUT_FLAG_NONE,
Marvin Ramine5a122d2023-12-07 13:57:59 +0100215 audio_port_handle_t *portId = nullptr,
216 uint32_t *virtualDeviceId = nullptr);
Mikhail Naganovd53525f2019-01-24 13:15:46 -0800217 PatchCountCheck snapshotPatchCount() { return PatchCountCheck(mClient.get()); }
Mikhail Naganov04a86632017-12-15 18:01:42 -0800218
Mikhail Naganov0805de12022-02-15 23:00:07 +0000219 void getAudioPorts(audio_port_type_t type, audio_port_role_t role,
220 std::vector<audio_port_v7>* ports);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700221 // Tries to find a device port. If 'foundPort' isn't nullptr,
222 // will generate a failure if the port hasn't been found.
223 bool findDevicePort(audio_port_role_t role, audio_devices_t deviceType,
jiabin19cdba52020-11-24 11:28:58 -0800224 const std::string &address, audio_port_v7 *foundPort);
jiabin7c0205e2019-09-05 10:26:04 -0700225 static audio_port_handle_t getDeviceIdFromPatch(const struct audio_patch* patch);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100226 virtual AudioPolicyManagerTestClient* getClient() { return new AudioPolicyManagerTestClient; }
jiabinf4eb15a2019-08-28 15:31:47 -0700227
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700228 sp<AudioPolicyConfig> mConfig;
Mikhail Naganov04a86632017-12-15 18:01:42 -0800229 std::unique_ptr<AudioPolicyManagerTestClient> mClient;
230 std::unique_ptr<AudioPolicyTestManager> mManager;
Dean Wheatleyd082f472022-02-04 11:10:48 +1100231
jiabin274fed92024-09-09 23:59:35 +0000232 static const std::string sTestEngineConfig;
Mikhail Naganov04a86632017-12-15 18:01:42 -0800233};
234
jiabin274fed92024-09-09 23:59:35 +0000235const std::string AudioPolicyManagerTest::sTestEngineConfig =
236 base::GetExecutableDirectory() + "/engine/test_audio_policy_engine_configuration.xml";
237
Mikhail Naganov04a86632017-12-15 18:01:42 -0800238void AudioPolicyManagerTest::SetUp() {
Kriti Dangef6be8f2020-11-05 11:58:19 +0100239 mClient.reset(getClient());
Mikhail Naganovd4c21aa2021-10-05 15:10:16 -0700240 ASSERT_NO_FATAL_FAILURE(SetUpManagerConfig()); // Subclasses may want to customize the config.
jiabin274fed92024-09-09 23:59:35 +0000241 mManager.reset(new AudioPolicyTestManager(mConfig, mClient.get(), sTestEngineConfig));
Mikhail Naganov04a86632017-12-15 18:01:42 -0800242 ASSERT_EQ(NO_ERROR, mManager->initialize());
243 ASSERT_EQ(NO_ERROR, mManager->initCheck());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -0800244}
Mikhail Naganov04a86632017-12-15 18:01:42 -0800245
246void AudioPolicyManagerTest::TearDown() {
247 mManager.reset();
248 mClient.reset();
249}
250
jiabin7c0205e2019-09-05 10:26:04 -0700251void AudioPolicyManagerTest::SetUpManagerConfig() {
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700252 mConfig = AudioPolicyConfig::createWritableForTests();
253 mConfig->setDefault();
jiabin7c0205e2019-09-05 10:26:04 -0700254}
255
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800256void AudioPolicyManagerTest::dumpToLog() {
Mikhail Naganov21b43362018-06-04 10:37:09 -0700257 int pipefd[2];
258 ASSERT_NE(-1, pipe(pipefd));
259 pid_t cpid = fork();
260 ASSERT_NE(-1, cpid);
261 if (cpid == 0) {
262 // Child process reads from the pipe and logs.
263 close(pipefd[1]);
264 std::string line;
265 char buf;
266 while (read(pipefd[0], &buf, sizeof(buf)) > 0) {
267 if (buf != '\n') {
268 line += buf;
269 } else {
270 ALOGI("%s", line.c_str());
271 line = "";
272 }
273 }
274 if (!line.empty()) ALOGI("%s", line.c_str());
275 close(pipefd[0]);
276 _exit(EXIT_SUCCESS);
277 } else {
278 // Parent does the dump and checks the status code.
279 close(pipefd[0]);
280 ASSERT_EQ(NO_ERROR, mManager->dump(pipefd[1]));
281 close(pipefd[1]);
282 wait(NULL); // Wait for the child to exit.
283 }
284}
285
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800286void AudioPolicyManagerTest::getOutputForAttr(
287 audio_port_handle_t *selectedDeviceId,
288 audio_format_t format,
Mikhail Naganov55773032020-10-01 15:08:13 -0700289 audio_channel_mask_t channelMask,
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800290 int sampleRate,
291 audio_output_flags_t flags,
Mikhail Naganov0756bbf2019-09-06 13:53:26 -0700292 audio_io_handle_t *output,
jiabinf4eb15a2019-08-28 15:31:47 -0700293 audio_port_handle_t *portId,
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +0200294 audio_attributes_t attr,
jiabin3ff8d7d2022-12-13 06:27:44 +0000295 audio_session_t session,
jiabin5eaf0962022-12-20 20:11:38 +0000296 int uid,
297 bool* isBitPerfect) {
Mikhail Naganov0756bbf2019-09-06 13:53:26 -0700298 audio_io_handle_t localOutput;
299 if (!output) output = &localOutput;
300 *output = AUDIO_IO_HANDLE_NONE;
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800301 audio_stream_type_t stream = AUDIO_STREAM_DEFAULT;
302 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
303 config.sample_rate = sampleRate;
304 config.channel_mask = channelMask;
305 config.format = format;
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800306 audio_port_handle_t localPortId;
307 if (!portId) portId = &localPortId;
308 *portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -0800309 AudioPolicyInterface::output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200310 bool isSpatialized;
jiabin5eaf0962022-12-20 20:11:38 +0000311 bool isBitPerfectInternal;
Andy Hung6b137d12024-08-27 22:35:17 +0000312 float volume;
Jan Sebechlebsky8e10cea2023-03-29 11:43:31 +0200313 AttributionSourceState attributionSource = createAttributionSourceState(uid);
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800314 ASSERT_EQ(OK, mManager->getOutputForAttr(
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +0200315 &attr, output, session, &stream, attributionSource, &config, &flags,
jiabin5eaf0962022-12-20 20:11:38 +0000316 selectedDeviceId, portId, {}, &outputType, &isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +0000317 isBitPerfect == nullptr ? &isBitPerfectInternal : isBitPerfect, &volume));
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800318 ASSERT_NE(AUDIO_PORT_HANDLE_NONE, *portId);
Mikhail Naganov0756bbf2019-09-06 13:53:26 -0700319 ASSERT_NE(AUDIO_IO_HANDLE_NONE, *output);
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800320}
321
jiabinf4eb15a2019-08-28 15:31:47 -0700322void AudioPolicyManagerTest::getInputForAttr(
323 const audio_attributes_t &attr,
François Gaffie6ebbce02023-07-19 13:27:53 +0200324 audio_io_handle_t *input,
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +0200325 const audio_session_t session,
jiabinf4eb15a2019-08-28 15:31:47 -0700326 audio_unique_id_t riid,
327 audio_port_handle_t *selectedDeviceId,
328 audio_format_t format,
Mikhail Naganov55773032020-10-01 15:08:13 -0700329 audio_channel_mask_t channelMask,
jiabinf4eb15a2019-08-28 15:31:47 -0700330 int sampleRate,
331 audio_input_flags_t flags,
Marvin Ramine5a122d2023-12-07 13:57:59 +0100332 audio_port_handle_t *portId,
333 uint32_t *virtualDeviceId) {
jiabinf4eb15a2019-08-28 15:31:47 -0700334 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
335 config.sample_rate = sampleRate;
336 config.channel_mask = channelMask;
337 config.format = format;
jiabinf4eb15a2019-08-28 15:31:47 -0700338 audio_port_handle_t localPortId;
339 if (!portId) portId = &localPortId;
340 *portId = AUDIO_PORT_HANDLE_NONE;
Marvin Ramine5a122d2023-12-07 13:57:59 +0100341 if (!virtualDeviceId) virtualDeviceId = 0;
jiabinf4eb15a2019-08-28 15:31:47 -0700342 AudioPolicyInterface::input_type_t inputType;
Jan Sebechlebsky8e10cea2023-03-29 11:43:31 +0200343 AttributionSourceState attributionSource = createAttributionSourceState(/*uid=*/ 0);
jiabinf4eb15a2019-08-28 15:31:47 -0700344 ASSERT_EQ(OK, mManager->getInputForAttr(
François Gaffie6ebbce02023-07-19 13:27:53 +0200345 &attr, input, riid, session, attributionSource, &config, flags,
Marvin Ramine5a122d2023-12-07 13:57:59 +0100346 selectedDeviceId, &inputType, portId, virtualDeviceId));
jiabinf4eb15a2019-08-28 15:31:47 -0700347 ASSERT_NE(AUDIO_PORT_HANDLE_NONE, *portId);
348}
349
Mikhail Naganov0805de12022-02-15 23:00:07 +0000350void AudioPolicyManagerTest::getAudioPorts(audio_port_type_t type, audio_port_role_t role,
351 std::vector<audio_port_v7>* ports) {
jiabinf4eb15a2019-08-28 15:31:47 -0700352 uint32_t numPorts = 0;
353 uint32_t generation1;
354 status_t ret;
355
Mikhail Naganov0805de12022-02-15 23:00:07 +0000356 ret = mManager->listAudioPorts(role, type, &numPorts, nullptr, &generation1);
357 ASSERT_EQ(NO_ERROR, ret) << "mManager->listAudioPorts returned error";
jiabinf4eb15a2019-08-28 15:31:47 -0700358
359 uint32_t generation2;
Mikhail Naganov0805de12022-02-15 23:00:07 +0000360 ports->resize(numPorts);
361 ret = mManager->listAudioPorts(role, type, &numPorts, ports->data(), &generation2);
362 ASSERT_EQ(NO_ERROR, ret) << "mManager->listAudioPorts returned error";
363 ASSERT_EQ(generation1, generation2) << "Generations changed during ports retrieval";
364}
365
366bool AudioPolicyManagerTest::findDevicePort(audio_port_role_t role,
367 audio_devices_t deviceType, const std::string &address, audio_port_v7 *foundPort) {
368 std::vector<audio_port_v7> ports;
369 getAudioPorts(AUDIO_PORT_TYPE_DEVICE, role, &ports);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700370 if (HasFailure()) return false;
jiabinf4eb15a2019-08-28 15:31:47 -0700371
372 for (const auto &port : ports) {
373 if (port.role == role && port.ext.device.type == deviceType &&
374 (strncmp(port.ext.device.address, address.c_str(),
375 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700376 if (foundPort) *foundPort = port;
377 return true;
jiabinf4eb15a2019-08-28 15:31:47 -0700378 }
379 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700380 if (foundPort) {
381 ADD_FAILURE() << "Device port with role " << role << " and address "
382 << address << " not found";
383 }
384 return false;
jiabinf4eb15a2019-08-28 15:31:47 -0700385}
386
jiabin7c0205e2019-09-05 10:26:04 -0700387audio_port_handle_t AudioPolicyManagerTest::getDeviceIdFromPatch(
388 const struct audio_patch* patch) {
389 // The logic here is the same as the one in AudioIoDescriptor.
390 // Note this function is aim to get routed device id for test.
391 // In that case, device to device patch is not expected here.
392 if (patch->num_sources != 0 && patch->num_sinks != 0) {
393 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
394 return patch->sinks[0].id;
395 } else {
396 return patch->sources[0].id;
397 }
398 }
399 return AUDIO_PORT_HANDLE_NONE;
400}
401
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800402
403TEST_F(AudioPolicyManagerTest, InitSuccess) {
404 // SetUp must finish with no assertions.
405}
406
407TEST_F(AudioPolicyManagerTest, Dump) {
408 dumpToLog();
409}
410
Mikhail Naganov04a86632017-12-15 18:01:42 -0800411TEST_F(AudioPolicyManagerTest, CreateAudioPatchFailure) {
412 audio_patch patch{};
413 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovd53525f2019-01-24 13:15:46 -0800414 const PatchCountCheck patchCount = snapshotPatchCount();
Mikhail Naganov04a86632017-12-15 18:01:42 -0800415 ASSERT_EQ(BAD_VALUE, mManager->createAudioPatch(nullptr, &handle, 0));
416 ASSERT_EQ(BAD_VALUE, mManager->createAudioPatch(&patch, nullptr, 0));
417 ASSERT_EQ(BAD_VALUE, mManager->createAudioPatch(&patch, &handle, 0));
418 patch.num_sources = AUDIO_PATCH_PORTS_MAX + 1;
419 patch.num_sinks = 1;
420 ASSERT_EQ(BAD_VALUE, mManager->createAudioPatch(&patch, &handle, 0));
421 patch.num_sources = 1;
422 patch.num_sinks = AUDIO_PATCH_PORTS_MAX + 1;
423 ASSERT_EQ(BAD_VALUE, mManager->createAudioPatch(&patch, &handle, 0));
424 patch.num_sources = 2;
425 patch.num_sinks = 1;
426 ASSERT_EQ(INVALID_OPERATION, mManager->createAudioPatch(&patch, &handle, 0));
427 patch = {};
428 patch.num_sources = 1;
429 patch.sources[0].role = AUDIO_PORT_ROLE_SINK;
430 patch.num_sinks = 1;
431 patch.sinks[0].role = AUDIO_PORT_ROLE_SINK;
432 ASSERT_EQ(INVALID_OPERATION, mManager->createAudioPatch(&patch, &handle, 0));
433 patch = {};
434 patch.num_sources = 1;
435 patch.sources[0].role = AUDIO_PORT_ROLE_SOURCE;
436 patch.num_sinks = 1;
437 patch.sinks[0].role = AUDIO_PORT_ROLE_SOURCE;
438 ASSERT_EQ(INVALID_OPERATION, mManager->createAudioPatch(&patch, &handle, 0));
439 // Verify that the handle is left unchanged.
440 ASSERT_EQ(AUDIO_PATCH_HANDLE_NONE, handle);
Mikhail Naganovd53525f2019-01-24 13:15:46 -0800441 ASSERT_EQ(0, patchCount.deltaFromSnapshot());
Mikhail Naganov04a86632017-12-15 18:01:42 -0800442}
443
444TEST_F(AudioPolicyManagerTest, CreateAudioPatchFromMix) {
Mikhail Naganov04a86632017-12-15 18:01:42 -0800445 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
446 uid_t uid = 42;
Mikhail Naganovd53525f2019-01-24 13:15:46 -0800447 const PatchCountCheck patchCount = snapshotPatchCount();
Mikhail Naganovc0d04982020-03-02 21:02:28 +0000448 ASSERT_FALSE(mManager->getAvailableInputDevices().isEmpty());
Mikhail Naganovdc769682018-05-04 15:34:08 -0700449 PatchBuilder patchBuilder;
Mikhail Naganovc0d04982020-03-02 21:02:28 +0000450 patchBuilder.addSource(mManager->getAvailableInputDevices()[0]).
Mikhail Naganovdc769682018-05-04 15:34:08 -0700451 addSink(mManager->getConfig().getDefaultOutputDevice());
452 ASSERT_EQ(NO_ERROR, mManager->createAudioPatch(patchBuilder.patch(), &handle, uid));
Mikhail Naganov04a86632017-12-15 18:01:42 -0800453 ASSERT_NE(AUDIO_PATCH_HANDLE_NONE, handle);
Mikhail Naganovd53525f2019-01-24 13:15:46 -0800454 ASSERT_EQ(1, patchCount.deltaFromSnapshot());
Mikhail Naganov04a86632017-12-15 18:01:42 -0800455}
456
457// TODO: Add patch creation tests that involve already existing patch
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800458
Michael Chan6fb34492020-12-08 15:44:49 +1100459enum
460{
461 MSD_AUDIO_PATCH_COUNT_NUM_AUDIO_PATCHES_INDEX = 0,
462 MSD_AUDIO_PATCH_COUNT_NAME_INDEX = 1
463};
464using MsdAudioPatchCountSpecification = std::tuple<size_t, std::string>;
465
466class AudioPolicyManagerTestMsd : public AudioPolicyManagerTest,
467 public ::testing::WithParamInterface<MsdAudioPatchCountSpecification> {
468 public:
469 AudioPolicyManagerTestMsd();
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800470 protected:
jiabin7c0205e2019-09-05 10:26:04 -0700471 void SetUpManagerConfig() override;
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800472 void TearDown() override;
Dorin Drimus94d94412022-02-02 09:05:02 +0100473 AudioProfileVector getDirectProfilesForAttributes(const audio_attributes_t& attr);
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800474
475 sp<DeviceDescriptor> mMsdOutputDevice;
476 sp<DeviceDescriptor> mMsdInputDevice;
Eric Laurent74c38dc2020-12-23 18:19:44 +0100477 sp<DeviceDescriptor> mDefaultOutputDevice;
Michael Chan6fb34492020-12-08 15:44:49 +1100478
479 const size_t mExpectedAudioPatchCount;
480 sp<DeviceDescriptor> mSpdifDevice;
Dean Wheatley8bee85a2021-02-10 16:02:23 +1100481
482 sp<DeviceDescriptor> mHdmiInputDevice;
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800483};
484
Michael Chan6fb34492020-12-08 15:44:49 +1100485AudioPolicyManagerTestMsd::AudioPolicyManagerTestMsd()
486 : mExpectedAudioPatchCount(std::get<MSD_AUDIO_PATCH_COUNT_NUM_AUDIO_PATCHES_INDEX>(
487 GetParam())) {}
488
489INSTANTIATE_TEST_CASE_P(
490 MsdAudioPatchCount,
491 AudioPolicyManagerTestMsd,
492 ::testing::Values(
Eric Laurent0ca09402024-05-16 17:48:59 +0000493 MsdAudioPatchCountSpecification(2u, "single"),
494 MsdAudioPatchCountSpecification(3u, "dual")
Michael Chan6fb34492020-12-08 15:44:49 +1100495 ),
496 [](const ::testing::TestParamInfo<MsdAudioPatchCountSpecification> &info) {
497 return std::get<MSD_AUDIO_PATCH_COUNT_NAME_INDEX>(info.param); }
498);
499
jiabin7c0205e2019-09-05 10:26:04 -0700500void AudioPolicyManagerTestMsd::SetUpManagerConfig() {
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800501 // TODO: Consider using Serializer to load part of the config from a string.
Mikhail Naganovd4c21aa2021-10-05 15:10:16 -0700502 ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTest::SetUpManagerConfig());
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800503 mMsdOutputDevice = new DeviceDescriptor(AUDIO_DEVICE_OUT_BUS);
504 sp<AudioProfile> pcmOutputProfile = new AudioProfile(
Dean Wheatleyd082f472022-02-04 11:10:48 +1100505 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO, k48000SamplingRate);
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800506 sp<AudioProfile> ac3OutputProfile = new AudioProfile(
Dean Wheatleyd082f472022-02-04 11:10:48 +1100507 AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1, k48000SamplingRate);
Dean Wheatley8bee85a2021-02-10 16:02:23 +1100508 sp<AudioProfile> iec958OutputProfile = new AudioProfile(
Dean Wheatley16809da2022-12-09 14:55:46 +1100509 AUDIO_FORMAT_IEC60958, AUDIO_CHANNEL_INDEX_MASK_24, k48000SamplingRate);
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800510 mMsdOutputDevice->addAudioProfile(pcmOutputProfile);
511 mMsdOutputDevice->addAudioProfile(ac3OutputProfile);
Dean Wheatley8bee85a2021-02-10 16:02:23 +1100512 mMsdOutputDevice->addAudioProfile(iec958OutputProfile);
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800513 mMsdInputDevice = new DeviceDescriptor(AUDIO_DEVICE_IN_BUS);
514 // Match output profile from AudioPolicyConfig::setDefault.
515 sp<AudioProfile> pcmInputProfile = new AudioProfile(
516 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO, 44100);
517 mMsdInputDevice->addAudioProfile(pcmInputProfile);
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700518 mConfig->addDevice(mMsdOutputDevice);
519 mConfig->addDevice(mMsdInputDevice);
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800520
Eric Laurent0ca09402024-05-16 17:48:59 +0000521 if (mExpectedAudioPatchCount == 3) {
Michael Chan6fb34492020-12-08 15:44:49 +1100522 // Add SPDIF device with PCM output profile as a second device for dual MSD audio patching.
523 mSpdifDevice = new DeviceDescriptor(AUDIO_DEVICE_OUT_SPDIF);
524 mSpdifDevice->addAudioProfile(pcmOutputProfile);
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700525 mConfig->addDevice(mSpdifDevice);
Michael Chan6fb34492020-12-08 15:44:49 +1100526
527 sp<OutputProfile> spdifOutputProfile = new OutputProfile("spdif output");
528 spdifOutputProfile->addAudioProfile(pcmOutputProfile);
529 spdifOutputProfile->addSupportedDevice(mSpdifDevice);
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700530 mConfig->getHwModules().getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)->
Michael Chan6fb34492020-12-08 15:44:49 +1100531 addOutputProfile(spdifOutputProfile);
532 }
533
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800534 sp<HwModule> msdModule = new HwModule(AUDIO_HARDWARE_MODULE_ID_MSD, 2 /*halVersionMajor*/);
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700535 HwModuleCollection modules = mConfig->getHwModules();
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800536 modules.add(msdModule);
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700537 mConfig->setHwModules(modules);
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800538
jiabin5740f082019-08-19 15:08:30 -0700539 sp<OutputProfile> msdOutputProfile = new OutputProfile("msd input");
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800540 msdOutputProfile->addAudioProfile(pcmOutputProfile);
541 msdOutputProfile->addSupportedDevice(mMsdOutputDevice);
542 msdModule->addOutputProfile(msdOutputProfile);
jiabin5740f082019-08-19 15:08:30 -0700543 sp<OutputProfile> msdCompressedOutputProfile = new OutputProfile("msd compressed input");
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800544 msdCompressedOutputProfile->addAudioProfile(ac3OutputProfile);
545 msdCompressedOutputProfile->setFlags(
546 AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
547 AUDIO_OUTPUT_FLAG_NON_BLOCKING);
548 msdCompressedOutputProfile->addSupportedDevice(mMsdOutputDevice);
549 msdModule->addOutputProfile(msdCompressedOutputProfile);
Dean Wheatley8bee85a2021-02-10 16:02:23 +1100550 sp<OutputProfile> msdIec958OutputProfile = new OutputProfile("msd iec958 input");
551 msdIec958OutputProfile->addAudioProfile(iec958OutputProfile);
552 msdIec958OutputProfile->setFlags(AUDIO_OUTPUT_FLAG_DIRECT);
553 msdIec958OutputProfile->addSupportedDevice(mMsdOutputDevice);
554 msdModule->addOutputProfile(msdIec958OutputProfile);
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800555
jiabin5740f082019-08-19 15:08:30 -0700556 sp<InputProfile> msdInputProfile = new InputProfile("msd output");
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800557 msdInputProfile->addAudioProfile(pcmInputProfile);
558 msdInputProfile->addSupportedDevice(mMsdInputDevice);
559 msdModule->addInputProfile(msdInputProfile);
560
561 // Add a profile with another encoding to the default device to test routing
562 // of streams that are not supported by MSD.
563 sp<AudioProfile> dtsOutputProfile = new AudioProfile(
Dean Wheatleyd082f472022-02-04 11:10:48 +1100564 AUDIO_FORMAT_DTS, AUDIO_CHANNEL_OUT_5POINT1, k48000SamplingRate);
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700565 mConfig->getDefaultOutputDevice()->addAudioProfile(dtsOutputProfile);
jiabin5740f082019-08-19 15:08:30 -0700566 sp<OutputProfile> primaryEncodedOutputProfile = new OutputProfile("encoded");
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800567 primaryEncodedOutputProfile->addAudioProfile(dtsOutputProfile);
568 primaryEncodedOutputProfile->setFlags(AUDIO_OUTPUT_FLAG_DIRECT);
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700569 primaryEncodedOutputProfile->addSupportedDevice(mConfig->getDefaultOutputDevice());
570 mConfig->getHwModules().getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)->
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800571 addOutputProfile(primaryEncodedOutputProfile);
Eric Laurent74c38dc2020-12-23 18:19:44 +0100572
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700573 mDefaultOutputDevice = mConfig->getDefaultOutputDevice();
Eric Laurent0ca09402024-05-16 17:48:59 +0000574 if (mExpectedAudioPatchCount == 3) {
Michael Chan6fb34492020-12-08 15:44:49 +1100575 mSpdifDevice->addAudioProfile(dtsOutputProfile);
576 primaryEncodedOutputProfile->addSupportedDevice(mSpdifDevice);
577 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +1100578
579 // Add HDMI input device with IEC60958 profile for HDMI in -> MSD patching.
580 mHdmiInputDevice = new DeviceDescriptor(AUDIO_DEVICE_IN_HDMI);
581 sp<AudioProfile> iec958InputProfile = new AudioProfile(
Dean Wheatley16809da2022-12-09 14:55:46 +1100582 AUDIO_FORMAT_IEC60958, AUDIO_CHANNEL_INDEX_MASK_24, k48000SamplingRate);
Dean Wheatley8bee85a2021-02-10 16:02:23 +1100583 mHdmiInputDevice->addAudioProfile(iec958InputProfile);
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700584 mConfig->addDevice(mHdmiInputDevice);
Dean Wheatley8bee85a2021-02-10 16:02:23 +1100585 sp<InputProfile> hdmiInputProfile = new InputProfile("hdmi input");
586 hdmiInputProfile->addAudioProfile(iec958InputProfile);
587 hdmiInputProfile->setFlags(AUDIO_INPUT_FLAG_DIRECT);
588 hdmiInputProfile->addSupportedDevice(mHdmiInputDevice);
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700589 mConfig->getHwModules().getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)->
Dean Wheatley8bee85a2021-02-10 16:02:23 +1100590 addInputProfile(hdmiInputProfile);
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800591}
592
593void AudioPolicyManagerTestMsd::TearDown() {
594 mMsdOutputDevice.clear();
595 mMsdInputDevice.clear();
Eric Laurent74c38dc2020-12-23 18:19:44 +0100596 mDefaultOutputDevice.clear();
Michael Chan6fb34492020-12-08 15:44:49 +1100597 mSpdifDevice.clear();
Dean Wheatley8bee85a2021-02-10 16:02:23 +1100598 mHdmiInputDevice.clear();
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800599 AudioPolicyManagerTest::TearDown();
600}
601
Dorin Drimus94d94412022-02-02 09:05:02 +0100602AudioProfileVector AudioPolicyManagerTestMsd::getDirectProfilesForAttributes(
603 const audio_attributes_t& attr) {
604 AudioProfileVector audioProfilesVector;
605 mManager->getDirectProfilesForAttributes(&attr, audioProfilesVector);
606 return audioProfilesVector;
607}
608
Michael Chan6fb34492020-12-08 15:44:49 +1100609TEST_P(AudioPolicyManagerTestMsd, InitSuccess) {
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800610 ASSERT_TRUE(mMsdOutputDevice);
611 ASSERT_TRUE(mMsdInputDevice);
Eric Laurent74c38dc2020-12-23 18:19:44 +0100612 ASSERT_TRUE(mDefaultOutputDevice);
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800613}
614
Michael Chan6fb34492020-12-08 15:44:49 +1100615TEST_P(AudioPolicyManagerTestMsd, Dump) {
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800616 dumpToLog();
617}
618
Michael Chan6fb34492020-12-08 15:44:49 +1100619TEST_P(AudioPolicyManagerTestMsd, PatchCreationOnSetForceUse) {
Mikhail Naganovd53525f2019-01-24 13:15:46 -0800620 const PatchCountCheck patchCount = snapshotPatchCount();
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800621 mManager->setForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND,
622 AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS);
Eric Laurent0ca09402024-05-16 17:48:59 +0000623 ASSERT_EQ(mExpectedAudioPatchCount -1 , patchCount.deltaFromSnapshot());
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800624}
625
Dean Wheatley8bee85a2021-02-10 16:02:23 +1100626TEST_P(AudioPolicyManagerTestMsd, PatchCreationSetReleaseMsdOutputPatches) {
Michael Chan6fb34492020-12-08 15:44:49 +1100627 const PatchCountCheck patchCount = snapshotPatchCount();
628 DeviceVector devices = mManager->getAvailableOutputDevices();
629 // Remove MSD output device to avoid patching to itself
630 devices.remove(mMsdOutputDevice);
Eric Laurent0ca09402024-05-16 17:48:59 +0000631 ASSERT_EQ(mExpectedAudioPatchCount -1 , devices.size());
Dean Wheatley8bee85a2021-02-10 16:02:23 +1100632 mManager->setMsdOutputPatches(&devices);
Eric Laurent0ca09402024-05-16 17:48:59 +0000633 ASSERT_EQ(mExpectedAudioPatchCount - 1, patchCount.deltaFromSnapshot());
Michael Chan6fb34492020-12-08 15:44:49 +1100634 // Dual patch: exercise creating one new audio patch and reusing another existing audio patch.
635 DeviceVector singleDevice(devices[0]);
Dean Wheatley8bee85a2021-02-10 16:02:23 +1100636 mManager->releaseMsdOutputPatches(singleDevice);
Eric Laurent0ca09402024-05-16 17:48:59 +0000637 ASSERT_EQ(mExpectedAudioPatchCount - 2, patchCount.deltaFromSnapshot());
Dean Wheatley8bee85a2021-02-10 16:02:23 +1100638 mManager->setMsdOutputPatches(&devices);
Eric Laurent0ca09402024-05-16 17:48:59 +0000639 ASSERT_EQ(mExpectedAudioPatchCount - 1, patchCount.deltaFromSnapshot());
Dean Wheatley8bee85a2021-02-10 16:02:23 +1100640 mManager->releaseMsdOutputPatches(devices);
Michael Chan6fb34492020-12-08 15:44:49 +1100641 ASSERT_EQ(0, patchCount.deltaFromSnapshot());
642}
643
644TEST_P(AudioPolicyManagerTestMsd, GetOutputForAttrEncodedRoutesToMsd) {
Mikhail Naganovd53525f2019-01-24 13:15:46 -0800645 const PatchCountCheck patchCount = snapshotPatchCount();
jiabin7c0205e2019-09-05 10:26:04 -0700646 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
Dean Wheatleyd082f472022-02-04 11:10:48 +1100647 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1,
648 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent74c38dc2020-12-23 18:19:44 +0100649 ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
Michael Chan6fb34492020-12-08 15:44:49 +1100650 ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800651}
652
Michael Chan6fb34492020-12-08 15:44:49 +1100653TEST_P(AudioPolicyManagerTestMsd, GetOutputForAttrPcmRoutesToMsd) {
Mikhail Naganovd53525f2019-01-24 13:15:46 -0800654 const PatchCountCheck patchCount = snapshotPatchCount();
jiabin7c0205e2019-09-05 10:26:04 -0700655 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800656 getOutputForAttr(&selectedDeviceId,
Dean Wheatleyd082f472022-02-04 11:10:48 +1100657 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO, k48000SamplingRate);
Eric Laurent74c38dc2020-12-23 18:19:44 +0100658 ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
Eric Laurent0ca09402024-05-16 17:48:59 +0000659 ASSERT_EQ(mExpectedAudioPatchCount - 1, patchCount.deltaFromSnapshot());
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800660}
661
Michael Chan6fb34492020-12-08 15:44:49 +1100662TEST_P(AudioPolicyManagerTestMsd, GetOutputForAttrEncodedPlusPcmRoutesToMsd) {
Mikhail Naganovd53525f2019-01-24 13:15:46 -0800663 const PatchCountCheck patchCount = snapshotPatchCount();
jiabin7c0205e2019-09-05 10:26:04 -0700664 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
Dean Wheatleyd082f472022-02-04 11:10:48 +1100665 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1,
666 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent74c38dc2020-12-23 18:19:44 +0100667 ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
Michael Chan6fb34492020-12-08 15:44:49 +1100668 ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
669 selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800670 getOutputForAttr(&selectedDeviceId,
Dean Wheatleyd082f472022-02-04 11:10:48 +1100671 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO, k48000SamplingRate);
Eric Laurent74c38dc2020-12-23 18:19:44 +0100672 ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
Michael Chan6fb34492020-12-08 15:44:49 +1100673 ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800674}
675
Michael Chan6fb34492020-12-08 15:44:49 +1100676TEST_P(AudioPolicyManagerTestMsd, GetOutputForAttrUnsupportedFormatBypassesMsd) {
Mikhail Naganovd53525f2019-01-24 13:15:46 -0800677 const PatchCountCheck patchCount = snapshotPatchCount();
jiabin7c0205e2019-09-05 10:26:04 -0700678 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
Dean Wheatleyd082f472022-02-04 11:10:48 +1100679 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_DTS, AUDIO_CHANNEL_OUT_5POINT1,
680 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT);
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800681 ASSERT_NE(selectedDeviceId, mMsdOutputDevice->getId());
Eric Laurent0ca09402024-05-16 17:48:59 +0000682 ASSERT_EQ(1, patchCount.deltaFromSnapshot());
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800683}
684
Michael Chan6fb34492020-12-08 15:44:49 +1100685TEST_P(AudioPolicyManagerTestMsd, GetOutputForAttrFormatSwitching) {
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800686 // Switch between formats that are supported and not supported by MSD.
687 {
Mikhail Naganovd53525f2019-01-24 13:15:46 -0800688 const PatchCountCheck patchCount = snapshotPatchCount();
jiabin7c0205e2019-09-05 10:26:04 -0700689 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
690 audio_port_handle_t portId;
Dean Wheatleyd082f472022-02-04 11:10:48 +1100691 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1,
692 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, nullptr /*output*/, &portId);
Eric Laurent74c38dc2020-12-23 18:19:44 +0100693 ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
Michael Chan6fb34492020-12-08 15:44:49 +1100694 ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800695 mManager->releaseOutput(portId);
Eric Laurent0ca09402024-05-16 17:48:59 +0000696 ASSERT_EQ(mExpectedAudioPatchCount - 1, patchCount.deltaFromSnapshot());
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800697 }
698 {
Mikhail Naganovd53525f2019-01-24 13:15:46 -0800699 const PatchCountCheck patchCount = snapshotPatchCount();
jiabin7c0205e2019-09-05 10:26:04 -0700700 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
701 audio_port_handle_t portId;
Dean Wheatleyd082f472022-02-04 11:10:48 +1100702 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_DTS, AUDIO_CHANNEL_OUT_5POINT1,
703 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, nullptr /*output*/, &portId);
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800704 ASSERT_NE(selectedDeviceId, mMsdOutputDevice->getId());
Eric Laurent0ca09402024-05-16 17:48:59 +0000705 ASSERT_EQ(-static_cast<int>(mExpectedAudioPatchCount) + 2, patchCount.deltaFromSnapshot());
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800706 mManager->releaseOutput(portId);
Mikhail Naganovd53525f2019-01-24 13:15:46 -0800707 ASSERT_EQ(0, patchCount.deltaFromSnapshot());
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800708 }
709 {
Mikhail Naganovd53525f2019-01-24 13:15:46 -0800710 const PatchCountCheck patchCount = snapshotPatchCount();
jiabin7c0205e2019-09-05 10:26:04 -0700711 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
Dean Wheatleyd082f472022-02-04 11:10:48 +1100712 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1,
713 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent74c38dc2020-12-23 18:19:44 +0100714 ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
Eric Laurent0ca09402024-05-16 17:48:59 +0000715 ASSERT_EQ(1, patchCount.deltaFromSnapshot());
Mikhail Naganovdf2e3592018-12-19 14:27:42 -0800716 }
717}
jiabinf4eb15a2019-08-28 15:31:47 -0700718
Dean Wheatley8bee85a2021-02-10 16:02:23 +1100719TEST_P(AudioPolicyManagerTestMsd, PatchCreationFromHdmiInToMsd) {
720 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
721 uid_t uid = 42;
722 const PatchCountCheck patchCount = snapshotPatchCount();
723 ASSERT_FALSE(mManager->getAvailableInputDevices().isEmpty());
724 PatchBuilder patchBuilder;
725 patchBuilder.
726 addSource(mManager->getAvailableInputDevices().
727 getDevice(AUDIO_DEVICE_IN_HDMI, String8(""), AUDIO_FORMAT_DEFAULT)).
728 addSink(mManager->getAvailableOutputDevices().
729 getDevice(AUDIO_DEVICE_OUT_BUS, String8(""), AUDIO_FORMAT_DEFAULT));
730 ASSERT_EQ(NO_ERROR, mManager->createAudioPatch(patchBuilder.patch(), &handle, uid));
731 ASSERT_NE(AUDIO_PATCH_HANDLE_NONE, handle);
732 AudioPatchCollection patches = mManager->getAudioPatches();
733 sp<AudioPatch> patch = patches.valueFor(handle);
734 ASSERT_EQ(1, patch->mPatch.num_sources);
735 ASSERT_EQ(1, patch->mPatch.num_sinks);
736 ASSERT_EQ(AUDIO_PORT_ROLE_SOURCE, patch->mPatch.sources[0].role);
737 ASSERT_EQ(AUDIO_PORT_ROLE_SINK, patch->mPatch.sinks[0].role);
738 ASSERT_EQ(AUDIO_FORMAT_IEC60958, patch->mPatch.sources[0].format);
739 ASSERT_EQ(AUDIO_FORMAT_IEC60958, patch->mPatch.sinks[0].format);
Dean Wheatley16809da2022-12-09 14:55:46 +1100740 ASSERT_EQ(AUDIO_CHANNEL_INDEX_MASK_24, patch->mPatch.sources[0].channel_mask);
741 ASSERT_EQ(AUDIO_CHANNEL_INDEX_MASK_24, patch->mPatch.sinks[0].channel_mask);
Dean Wheatleyd082f472022-02-04 11:10:48 +1100742 ASSERT_EQ(k48000SamplingRate, patch->mPatch.sources[0].sample_rate);
743 ASSERT_EQ(k48000SamplingRate, patch->mPatch.sinks[0].sample_rate);
Dean Wheatley8bee85a2021-02-10 16:02:23 +1100744 ASSERT_EQ(1, patchCount.deltaFromSnapshot());
745}
746
Dorin Drimus94d94412022-02-02 09:05:02 +0100747TEST_P(AudioPolicyManagerTestMsd, GetDirectProfilesForAttributesWithMsd) {
748 const audio_attributes_t attr = {
749 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
750 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
751
752 // count expected direct profiles for the default device
753 int countDirectProfilesPrimary = 0;
754 const auto& primary = mManager->getConfig().getHwModules()
755 .getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700756 for (const auto& outputProfile : primary->getOutputProfiles()) {
Dorin Drimus94d94412022-02-02 09:05:02 +0100757 if (outputProfile->asAudioPort()->isDirectOutput()) {
758 countDirectProfilesPrimary += outputProfile->asAudioPort()->getAudioProfiles().size();
759 }
760 }
761
762 // count expected direct profiles for the msd device
763 int countDirectProfilesMsd = 0;
764 const auto& msd = mManager->getConfig().getHwModules()
765 .getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700766 for (const auto& outputProfile : msd->getOutputProfiles()) {
Dorin Drimus94d94412022-02-02 09:05:02 +0100767 if (outputProfile->asAudioPort()->isDirectOutput()) {
768 countDirectProfilesMsd += outputProfile->asAudioPort()->getAudioProfiles().size();
769 }
770 }
771
772 // before setting up MSD audio patches we only have the primary hal direct profiles
773 ASSERT_EQ(countDirectProfilesPrimary, getDirectProfilesForAttributes(attr).size());
774
775 DeviceVector outputDevices = mManager->getAvailableOutputDevices();
776 // Remove MSD output device to avoid patching to itself
777 outputDevices.remove(mMsdOutputDevice);
778 mManager->setMsdOutputPatches(&outputDevices);
779
780 // after setting up MSD audio patches the MSD direct profiles are added
781 ASSERT_EQ(countDirectProfilesPrimary + countDirectProfilesMsd,
782 getDirectProfilesForAttributes(attr).size());
783
784 mManager->releaseMsdOutputPatches(outputDevices);
785 // releasing the MSD audio patches gets us back to the primary hal direct profiles only
786 ASSERT_EQ(countDirectProfilesPrimary, getDirectProfilesForAttributes(attr).size());
787}
788
Dorin Drimusecc9f422022-03-09 17:57:40 +0100789TEST_P(AudioPolicyManagerTestMsd, IsDirectPlaybackSupportedWithMsd) {
790 const audio_attributes_t attr = {
791 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
792 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
793
794 audio_config_base_t directConfig = AUDIO_CONFIG_BASE_INITIALIZER;
795 directConfig.format = AUDIO_FORMAT_DTS;
Mikhail Naganov806170e2024-09-05 17:26:50 -0700796 directConfig.sample_rate = k48000SamplingRate;
Dorin Drimusecc9f422022-03-09 17:57:40 +0100797 directConfig.channel_mask = AUDIO_CHANNEL_OUT_5POINT1;
798
799 audio_config_base_t nonDirectConfig = AUDIO_CONFIG_BASE_INITIALIZER;
800 nonDirectConfig.format = AUDIO_FORMAT_PCM_16_BIT;
Mikhail Naganov806170e2024-09-05 17:26:50 -0700801 nonDirectConfig.sample_rate = k48000SamplingRate;
Dorin Drimusecc9f422022-03-09 17:57:40 +0100802 nonDirectConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
803
804 audio_config_base_t nonExistentConfig = AUDIO_CONFIG_BASE_INITIALIZER;
805 nonExistentConfig.format = AUDIO_FORMAT_E_AC3;
Mikhail Naganov806170e2024-09-05 17:26:50 -0700806 nonExistentConfig.sample_rate = k48000SamplingRate;
Dorin Drimusecc9f422022-03-09 17:57:40 +0100807 nonExistentConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
808
809 audio_config_base_t msdDirectConfig1 = AUDIO_CONFIG_BASE_INITIALIZER;
810 msdDirectConfig1.format = AUDIO_FORMAT_AC3;
Mikhail Naganov806170e2024-09-05 17:26:50 -0700811 msdDirectConfig1.sample_rate = k48000SamplingRate;
Dorin Drimusecc9f422022-03-09 17:57:40 +0100812 msdDirectConfig1.channel_mask = AUDIO_CHANNEL_OUT_5POINT1;
813
814 audio_config_base_t msdDirectConfig2 = AUDIO_CONFIG_BASE_INITIALIZER;
815 msdDirectConfig2.format = AUDIO_FORMAT_IEC60958;
Mikhail Naganov806170e2024-09-05 17:26:50 -0700816 msdDirectConfig2.sample_rate = k48000SamplingRate;
Dean Wheatley16809da2022-12-09 14:55:46 +1100817 msdDirectConfig2.channel_mask = AUDIO_CHANNEL_INDEX_MASK_24;
Dorin Drimusecc9f422022-03-09 17:57:40 +0100818
819 audio_config_base_t msdNonDirectConfig = AUDIO_CONFIG_BASE_INITIALIZER;
820 msdNonDirectConfig.format = AUDIO_FORMAT_PCM_16_BIT;
821 msdNonDirectConfig.sample_rate = 96000;
822 msdNonDirectConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
823
824 ASSERT_TRUE(mManager->isDirectOutputSupported(directConfig, attr));
825 ASSERT_FALSE(mManager->isDirectOutputSupported(nonDirectConfig, attr));
826 ASSERT_FALSE(mManager->isDirectOutputSupported(nonExistentConfig, attr));
827 // before setting MSD patches the direct MSD configs return false
828 ASSERT_FALSE(mManager->isDirectOutputSupported(msdDirectConfig1, attr));
829 ASSERT_FALSE(mManager->isDirectOutputSupported(msdDirectConfig2, attr));
830 ASSERT_FALSE(mManager->isDirectOutputSupported(msdNonDirectConfig, attr));
831
832 DeviceVector outputDevices = mManager->getAvailableOutputDevices();
833 // Remove MSD output device to avoid patching to itself
834 outputDevices.remove(mMsdOutputDevice);
835 mManager->setMsdOutputPatches(&outputDevices);
836
837 ASSERT_TRUE(mManager->isDirectOutputSupported(directConfig, attr));
838 ASSERT_FALSE(mManager->isDirectOutputSupported(nonDirectConfig, attr));
839 ASSERT_FALSE(mManager->isDirectOutputSupported(nonExistentConfig, attr));
840 // after setting MSD patches the direct MSD configs return true
841 ASSERT_TRUE(mManager->isDirectOutputSupported(msdDirectConfig1, attr));
842 ASSERT_TRUE(mManager->isDirectOutputSupported(msdDirectConfig2, attr));
843 ASSERT_FALSE(mManager->isDirectOutputSupported(msdNonDirectConfig, attr));
844
845 mManager->releaseMsdOutputPatches(outputDevices);
846
847 ASSERT_TRUE(mManager->isDirectOutputSupported(directConfig, attr));
848 ASSERT_FALSE(mManager->isDirectOutputSupported(nonDirectConfig, attr));
849 ASSERT_FALSE(mManager->isDirectOutputSupported(nonExistentConfig, attr));
850 // AFTER releasing MSD patches the direct MSD configs return false
851 ASSERT_FALSE(mManager->isDirectOutputSupported(msdDirectConfig1, attr));
852 ASSERT_FALSE(mManager->isDirectOutputSupported(msdDirectConfig2, attr));
853 ASSERT_FALSE(mManager->isDirectOutputSupported(msdNonDirectConfig, attr));
854}
855
Dorin Drimusfae3c642022-03-17 18:36:30 +0100856TEST_P(AudioPolicyManagerTestMsd, GetDirectPlaybackSupportWithMsd) {
857 const audio_attributes_t attr = {
858 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
859 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
860
861 audio_config_t directConfig = AUDIO_CONFIG_INITIALIZER;
862 directConfig.format = AUDIO_FORMAT_DTS;
Mikhail Naganov806170e2024-09-05 17:26:50 -0700863 directConfig.sample_rate = k48000SamplingRate;
Dorin Drimusfae3c642022-03-17 18:36:30 +0100864 directConfig.channel_mask = AUDIO_CHANNEL_OUT_5POINT1;
865
866 audio_config_t nonDirectConfig = AUDIO_CONFIG_INITIALIZER;
867 nonDirectConfig.format = AUDIO_FORMAT_PCM_16_BIT;
Mikhail Naganov806170e2024-09-05 17:26:50 -0700868 nonDirectConfig.sample_rate = k48000SamplingRate;
Dorin Drimusfae3c642022-03-17 18:36:30 +0100869 nonDirectConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
870
871 audio_config_t nonExistentConfig = AUDIO_CONFIG_INITIALIZER;
872 nonExistentConfig.format = AUDIO_FORMAT_E_AC3;
Mikhail Naganov806170e2024-09-05 17:26:50 -0700873 nonExistentConfig.sample_rate = k48000SamplingRate;
Dorin Drimusfae3c642022-03-17 18:36:30 +0100874 nonExistentConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
875
876 audio_config_t msdDirectConfig1 = AUDIO_CONFIG_INITIALIZER;
877 msdDirectConfig1.format = AUDIO_FORMAT_AC3;
Mikhail Naganov806170e2024-09-05 17:26:50 -0700878 msdDirectConfig1.sample_rate = k48000SamplingRate;
Dorin Drimusfae3c642022-03-17 18:36:30 +0100879 msdDirectConfig1.channel_mask = AUDIO_CHANNEL_OUT_5POINT1;
880
881 audio_config_t msdDirectConfig2 = AUDIO_CONFIG_INITIALIZER;
882 msdDirectConfig2.format = AUDIO_FORMAT_IEC60958;
Mikhail Naganov806170e2024-09-05 17:26:50 -0700883 msdDirectConfig2.sample_rate = k48000SamplingRate;
Dean Wheatley16809da2022-12-09 14:55:46 +1100884 msdDirectConfig2.channel_mask = AUDIO_CHANNEL_INDEX_MASK_24;
Dorin Drimusfae3c642022-03-17 18:36:30 +0100885
886 audio_config_t msdNonDirectConfig = AUDIO_CONFIG_INITIALIZER;
887 msdNonDirectConfig.format = AUDIO_FORMAT_PCM_16_BIT;
888 msdNonDirectConfig.sample_rate = 96000;
889 msdNonDirectConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
890
891 ASSERT_EQ(AUDIO_DIRECT_BITSTREAM_SUPPORTED,
892 mManager->getDirectPlaybackSupport(&attr, &directConfig));
893 ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
894 mManager->getDirectPlaybackSupport(&attr, &nonDirectConfig));
895 ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
896 mManager->getDirectPlaybackSupport(&attr, &nonExistentConfig));
897 // before setting MSD patches the direct MSD configs return AUDIO_DIRECT_NOT_SUPPORTED
898 ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
899 mManager->getDirectPlaybackSupport(&attr, &msdDirectConfig1));
900 ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
901 mManager->getDirectPlaybackSupport(&attr, &msdDirectConfig2));
902 ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
903 mManager->getDirectPlaybackSupport(&attr, &msdNonDirectConfig));
904
905 DeviceVector outputDevices = mManager->getAvailableOutputDevices();
906 // Remove MSD output device to avoid patching to itself
907 outputDevices.remove(mMsdOutputDevice);
908 mManager->setMsdOutputPatches(&outputDevices);
909
910 ASSERT_EQ(AUDIO_DIRECT_BITSTREAM_SUPPORTED,
911 mManager->getDirectPlaybackSupport(&attr, &directConfig));
912 ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
913 mManager->getDirectPlaybackSupport(&attr, &nonDirectConfig));
914 ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
915 mManager->getDirectPlaybackSupport(&attr, &nonExistentConfig));
916 // after setting MSD patches the direct MSD configs return values according to their flags
917 ASSERT_EQ(AUDIO_DIRECT_OFFLOAD_SUPPORTED,
918 mManager->getDirectPlaybackSupport(&attr, &msdDirectConfig1));
919 ASSERT_EQ(AUDIO_DIRECT_BITSTREAM_SUPPORTED,
920 mManager->getDirectPlaybackSupport(&attr, &msdDirectConfig2));
921 ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
922 mManager->getDirectPlaybackSupport(&attr, &msdNonDirectConfig));
923
924 mManager->releaseMsdOutputPatches(outputDevices);
925
926 ASSERT_EQ(AUDIO_DIRECT_BITSTREAM_SUPPORTED,
927 mManager->getDirectPlaybackSupport(&attr, &directConfig));
928 ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
929 mManager->getDirectPlaybackSupport(&attr, &nonDirectConfig));
930 ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
931 mManager->getDirectPlaybackSupport(&attr, &nonExistentConfig));
932 // after releasing MSD patches the direct MSD configs return AUDIO_DIRECT_NOT_SUPPORTED
933 ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
934 mManager->getDirectPlaybackSupport(&attr, &msdDirectConfig1));
935 ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
936 mManager->getDirectPlaybackSupport(&attr, &msdDirectConfig2));
937 ASSERT_EQ(AUDIO_DIRECT_NOT_SUPPORTED,
938 mManager->getDirectPlaybackSupport(&attr, &msdNonDirectConfig));
939}
940
jiabin7c0205e2019-09-05 10:26:04 -0700941class AudioPolicyManagerTestWithConfigurationFile : public AudioPolicyManagerTest {
942protected:
943 void SetUpManagerConfig() override;
944 virtual std::string getConfigFile() { return sDefaultConfig; }
945
946 static const std::string sExecutableDir;
947 static const std::string sDefaultConfig;
948};
949
950const std::string AudioPolicyManagerTestWithConfigurationFile::sExecutableDir =
951 base::GetExecutableDirectory() + "/";
952
953const std::string AudioPolicyManagerTestWithConfigurationFile::sDefaultConfig =
954 sExecutableDir + "test_audio_policy_configuration.xml";
955
956void AudioPolicyManagerTestWithConfigurationFile::SetUpManagerConfig() {
Mikhail Naganov68e3f642023-04-28 13:06:32 -0700957 auto result = AudioPolicyConfig::loadFromCustomXmlConfigForTests(getConfigFile());
958 ASSERT_TRUE(result.ok());
959 mConfig = result.value();
jiabin7c0205e2019-09-05 10:26:04 -0700960}
961
962TEST_F(AudioPolicyManagerTestWithConfigurationFile, InitSuccess) {
963 // SetUp must finish with no assertions.
964}
965
966TEST_F(AudioPolicyManagerTestWithConfigurationFile, Dump) {
967 dumpToLog();
968}
969
Mikhail Naganov0805de12022-02-15 23:00:07 +0000970TEST_F(AudioPolicyManagerTestWithConfigurationFile, ListAudioPortsHasFlags) {
971 // Create an input for VOIP TX because it's not opened automatically like outputs are.
972 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
973 audio_port_handle_t mixPortId = AUDIO_PORT_HANDLE_NONE;
974 audio_source_t source = AUDIO_SOURCE_VOICE_COMMUNICATION;
François Gaffie6ebbce02023-07-19 13:27:53 +0200975 audio_attributes_t attr = {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN, source,
976 AUDIO_FLAG_NONE, ""};
977 audio_io_handle_t input = AUDIO_PORT_HANDLE_NONE;
978 ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input, AUDIO_SESSION_NONE, 1,
979 &selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT,
980 AUDIO_CHANNEL_IN_MONO, 8000, AUDIO_INPUT_FLAG_VOIP_TX,
981 &mixPortId));
Mikhail Naganov0805de12022-02-15 23:00:07 +0000982
983 std::vector<audio_port_v7> ports;
984 ASSERT_NO_FATAL_FAILURE(
985 getAudioPorts(AUDIO_PORT_TYPE_MIX, AUDIO_PORT_ROLE_NONE, &ports));
986 EXPECT_NE(0, ports.size());
987 bool hasFlags = false, foundPrimary = false, foundVoipRx = false, foundVoipTx = false;
988 for (const auto& port : ports) {
989 if ((port.active_config.config_mask & AUDIO_PORT_CONFIG_FLAGS) != 0) {
990 hasFlags = true;
991 if (port.role == AUDIO_PORT_ROLE_SOURCE) {
992 if ((port.active_config.flags.output & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
993 foundPrimary = true;
994 }
995 if ((port.active_config.flags.output & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
996 foundVoipRx = true;
997 }
998 } else if (port.role == AUDIO_PORT_ROLE_SINK) {
999 if ((port.active_config.flags.input & AUDIO_INPUT_FLAG_VOIP_TX) != 0) {
1000 foundVoipTx = true;
1001 }
1002 }
1003 }
1004 }
1005 EXPECT_TRUE(hasFlags);
1006 EXPECT_TRUE(foundPrimary);
1007 EXPECT_TRUE(foundVoipRx);
1008 EXPECT_TRUE(foundVoipTx);
1009}
1010
Ram Mohan M594558d2022-06-14 14:42:44 +05301011TEST_F(AudioPolicyManagerTestWithConfigurationFile, HandleDeviceConfigChange) {
1012 {
1013 const auto prevCounter = mClient->getRoutingUpdatedCounter();
1014
1015 EXPECT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
1016 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1017 "", "", AUDIO_FORMAT_LDAC));
1018 const auto currCounter = mClient->getRoutingUpdatedCounter();
1019 EXPECT_GT(currCounter, prevCounter);
1020 }
1021 {
1022 const auto prevCounter = mClient->getRoutingUpdatedCounter();
1023 // Update device configuration
1024 EXPECT_EQ(NO_ERROR, mManager->handleDeviceConfigChange(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
1025 "" /*address*/, "" /*name*/,
1026 AUDIO_FORMAT_AAC));
1027
1028 // As mClient marks isReconfigA2dpSupported to false, device state needs to be toggled for
1029 // config changes to take effect
1030 const auto currCounter = mClient->getRoutingUpdatedCounter();
1031 EXPECT_GT(currCounter, prevCounter);
1032 }
1033}
1034
jiabina84c3d32022-12-02 18:59:55 +00001035TEST_F(AudioPolicyManagerTestWithConfigurationFile, PreferredMixerAttributes) {
1036 mClient->addSupportedFormat(AUDIO_FORMAT_PCM_16_BIT);
1037 mClient->addSupportedChannelMask(AUDIO_CHANNEL_OUT_STEREO);
1038 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_USB_DEVICE,
1039 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1040 "", "", AUDIO_FORMAT_DEFAULT));
1041 auto devices = mManager->getAvailableOutputDevices();
1042 audio_port_handle_t maxPortId = 0;
1043 audio_port_handle_t speakerPortId;
1044 audio_port_handle_t usbPortId;
1045 for (auto device : devices) {
1046 maxPortId = std::max(maxPortId, device->getId());
1047 if (device->type() == AUDIO_DEVICE_OUT_SPEAKER) {
1048 speakerPortId = device->getId();
1049 } else if (device->type() == AUDIO_DEVICE_OUT_USB_DEVICE) {
1050 usbPortId = device->getId();
1051 }
1052 }
1053
1054 const uid_t uid = 1234;
1055 const uid_t otherUid = 4321;
1056 const audio_attributes_t mediaAttr = {
1057 .content_type = AUDIO_CONTENT_TYPE_MUSIC,
1058 .usage = AUDIO_USAGE_MEDIA,
1059 };
1060 const audio_attributes_t alarmAttr = {
1061 .content_type = AUDIO_CONTENT_TYPE_SONIFICATION,
1062 .usage = AUDIO_USAGE_ALARM,
1063 };
1064
1065 std::vector<audio_mixer_attributes_t> mixerAttributes;
1066 EXPECT_EQ(NO_ERROR, mManager->getSupportedMixerAttributes(usbPortId, mixerAttributes));
1067 for (const auto attrToSet : mixerAttributes) {
1068 audio_mixer_attributes_t attrFromQuery = AUDIO_MIXER_ATTRIBUTES_INITIALIZER;
1069
1070 // The given device is not available
1071 EXPECT_EQ(BAD_VALUE,
1072 mManager->setPreferredMixerAttributes(
1073 &mediaAttr, maxPortId + 1, uid, &attrToSet));
1074 // The only allowed device is USB
1075 EXPECT_EQ(BAD_VALUE,
1076 mManager->setPreferredMixerAttributes(
1077 &mediaAttr, speakerPortId, uid, &attrToSet));
1078 // The only allowed usage is media
1079 EXPECT_EQ(BAD_VALUE,
1080 mManager->setPreferredMixerAttributes(&alarmAttr, usbPortId, uid, &attrToSet));
1081 // Nothing set yet, must get null when query
1082 EXPECT_EQ(NAME_NOT_FOUND,
1083 mManager->getPreferredMixerAttributes(&mediaAttr, usbPortId, &attrFromQuery));
1084 EXPECT_EQ(NO_ERROR,
1085 mManager->setPreferredMixerAttributes(
1086 &mediaAttr, usbPortId, uid, &attrToSet));
1087 EXPECT_EQ(NO_ERROR,
1088 mManager->getPreferredMixerAttributes(&mediaAttr, usbPortId, &attrFromQuery));
1089 EXPECT_EQ(attrToSet.config.format, attrFromQuery.config.format);
1090 EXPECT_EQ(attrToSet.config.sample_rate, attrFromQuery.config.sample_rate);
1091 EXPECT_EQ(attrToSet.config.channel_mask, attrFromQuery.config.channel_mask);
1092 EXPECT_EQ(attrToSet.mixer_behavior, attrFromQuery.mixer_behavior);
1093 EXPECT_EQ(NAME_NOT_FOUND,
1094 mManager->clearPreferredMixerAttributes(&mediaAttr, speakerPortId, uid));
1095 EXPECT_EQ(PERMISSION_DENIED,
1096 mManager->clearPreferredMixerAttributes(&mediaAttr, usbPortId, otherUid));
1097 EXPECT_EQ(NO_ERROR,
1098 mManager->clearPreferredMixerAttributes(&mediaAttr, usbPortId, uid));
1099 }
1100
1101 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_USB_DEVICE,
1102 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1103 "", "", AUDIO_FORMAT_LDAC));
1104}
1105
jiabin3ff8d7d2022-12-13 06:27:44 +00001106TEST_F(AudioPolicyManagerTestWithConfigurationFile, RoutingChangedWithPreferredMixerAttributes) {
1107 mClient->addSupportedFormat(AUDIO_FORMAT_PCM_16_BIT);
1108 mClient->addSupportedChannelMask(AUDIO_CHANNEL_OUT_STEREO);
1109 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_USB_DEVICE,
1110 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1111 "", "", AUDIO_FORMAT_DEFAULT));
1112 auto devices = mManager->getAvailableOutputDevices();
1113 audio_port_handle_t usbPortId = AUDIO_PORT_HANDLE_NONE;
1114 for (auto device : devices) {
1115 if (device->type() == AUDIO_DEVICE_OUT_USB_DEVICE) {
1116 usbPortId = device->getId();
1117 break;
1118 }
1119 }
1120 EXPECT_NE(AUDIO_PORT_HANDLE_NONE, usbPortId);
1121
1122 const uid_t uid = 1234;
1123 const audio_attributes_t mediaAttr = {
1124 .content_type = AUDIO_CONTENT_TYPE_MUSIC,
1125 .usage = AUDIO_USAGE_MEDIA,
1126 };
1127
1128 std::vector<audio_mixer_attributes_t> mixerAttributes;
1129 EXPECT_EQ(NO_ERROR, mManager->getSupportedMixerAttributes(usbPortId, mixerAttributes));
1130 EXPECT_GT(mixerAttributes.size(), 0);
1131 EXPECT_EQ(NO_ERROR,
1132 mManager->setPreferredMixerAttributes(
1133 &mediaAttr, usbPortId, uid, &mixerAttributes[0]));
1134
1135 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
1136 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
1137 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
1138 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
Mikhail Naganov806170e2024-09-05 17:26:50 -07001139 k48000SamplingRate, AUDIO_OUTPUT_FLAG_NONE, &output, &portId, mediaAttr,
jiabin3ff8d7d2022-12-13 06:27:44 +00001140 AUDIO_SESSION_NONE, uid);
1141 status_t status = mManager->startOutput(portId);
1142 if (status == DEAD_OBJECT) {
1143 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
Mikhail Naganov806170e2024-09-05 17:26:50 -07001144 k48000SamplingRate, AUDIO_OUTPUT_FLAG_NONE, &output, &portId, mediaAttr,
jiabin3ff8d7d2022-12-13 06:27:44 +00001145 AUDIO_SESSION_NONE, uid);
1146 status = mManager->startOutput(portId);
1147 }
1148 EXPECT_EQ(NO_ERROR, status);
1149 EXPECT_NE(AUDIO_IO_HANDLE_NONE, output);
1150 EXPECT_NE(nullptr, mManager->getOutputs().valueFor(output));
1151 EXPECT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
1152 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1153 "", "", AUDIO_FORMAT_LDAC));
1154 // When BT device is connected, it will be selected as media device and trigger routing changed.
1155 // When this happens, existing output that is opened with preferred mixer attributes will be
1156 // closed and reopened with default config.
1157 EXPECT_EQ(nullptr, mManager->getOutputs().valueFor(output));
1158
1159 EXPECT_EQ(NO_ERROR,
1160 mManager->clearPreferredMixerAttributes(&mediaAttr, usbPortId, uid));
1161
1162 EXPECT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
1163 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1164 "", "", AUDIO_FORMAT_LDAC));
1165 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_USB_DEVICE,
1166 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1167 "", "", AUDIO_FORMAT_LDAC));
1168}
1169
jiabin66acc432024-02-06 00:57:36 +00001170TEST_F(AudioPolicyManagerTestWithConfigurationFile, PreferExactConfigForInput) {
1171 const audio_channel_mask_t deviceChannelMask = AUDIO_CHANNEL_IN_3POINT1;
1172 mClient->addSupportedFormat(AUDIO_FORMAT_PCM_16_BIT);
1173 mClient->addSupportedChannelMask(deviceChannelMask);
1174 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_IN_USB_DEVICE,
1175 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1176 "", "", AUDIO_FORMAT_DEFAULT));
1177
1178 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
1179 audio_attributes_t attr = {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
1180 AUDIO_SOURCE_VOICE_COMMUNICATION,AUDIO_FLAG_NONE, ""};
1181 AudioPolicyInterface::input_type_t inputType;
1182 audio_io_handle_t input = AUDIO_PORT_HANDLE_NONE;
1183 AttributionSourceState attributionSource = createAttributionSourceState(/*uid=*/ 0);
1184 audio_config_base_t requestedConfig = {
Mikhail Naganov806170e2024-09-05 17:26:50 -07001185 .sample_rate = k48000SamplingRate,
jiabin66acc432024-02-06 00:57:36 +00001186 .channel_mask = AUDIO_CHANNEL_IN_STEREO,
1187 .format = AUDIO_FORMAT_PCM_16_BIT,
jiabin66acc432024-02-06 00:57:36 +00001188 };
1189 audio_config_base_t config = requestedConfig;
1190 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Marvin Ramine5a122d2023-12-07 13:57:59 +01001191 uint32_t *virtualDeviceId = 0;
jiabin66acc432024-02-06 00:57:36 +00001192 ASSERT_EQ(OK, mManager->getInputForAttr(
1193 &attr, &input, 1 /*riid*/, AUDIO_SESSION_NONE, attributionSource, &config,
1194 AUDIO_INPUT_FLAG_NONE,
Marvin Ramine5a122d2023-12-07 13:57:59 +01001195 &selectedDeviceId, &inputType, &portId, virtualDeviceId));
jiabin66acc432024-02-06 00:57:36 +00001196 ASSERT_NE(AUDIO_PORT_HANDLE_NONE, portId);
1197 ASSERT_TRUE(equals(requestedConfig, config));
1198
1199 attr = {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
1200 AUDIO_SOURCE_VOICE_COMMUNICATION, AUDIO_FLAG_NONE, ""};
1201 requestedConfig.channel_mask = deviceChannelMask;
1202 config = requestedConfig;
1203 selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
1204 input = AUDIO_PORT_HANDLE_NONE;
1205 portId = AUDIO_PORT_HANDLE_NONE;
1206 ASSERT_EQ(OK, mManager->getInputForAttr(
1207 &attr, &input, 1 /*riid*/, AUDIO_SESSION_NONE, attributionSource, &config,
1208 AUDIO_INPUT_FLAG_NONE,
Marvin Ramine5a122d2023-12-07 13:57:59 +01001209 &selectedDeviceId, &inputType, &portId, virtualDeviceId));
jiabin66acc432024-02-06 00:57:36 +00001210 ASSERT_NE(AUDIO_PORT_HANDLE_NONE, portId);
1211 ASSERT_TRUE(equals(requestedConfig, config));
1212
1213 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_IN_USB_DEVICE,
1214 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1215 "", "", AUDIO_FORMAT_DEFAULT));
1216}
1217
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07001218TEST_F(AudioPolicyManagerTestWithConfigurationFile, CheckInputsForDeviceClosesStreams) {
1219 mClient->addSupportedFormat(AUDIO_FORMAT_PCM_16_BIT);
1220 mClient->addSupportedFormat(AUDIO_FORMAT_PCM_24_BIT_PACKED);
1221 mClient->addSupportedChannelMask(AUDIO_CHANNEL_IN_MONO);
1222 mClient->addSupportedChannelMask(AUDIO_CHANNEL_IN_STEREO);
1223 // Since 'checkInputsForDevice' is called as part of the 'setDeviceConnectionState',
1224 // call it directly here, as we need to ensure that it does not keep all intermediate
1225 // streams opened, as it may cause a rejection from the HAL based on the cap.
1226 const size_t streamCountBefore = mClient->getOpenedInputsCount();
1227 sp<DeviceDescriptor> device = mManager->getHwModules().getDeviceDescriptor(
1228 AUDIO_DEVICE_IN_USB_DEVICE, "", "", AUDIO_FORMAT_DEFAULT, true /*allowToCreate*/);
1229 ASSERT_NE(nullptr, device.get());
1230 EXPECT_EQ(NO_ERROR,
1231 mManager->checkInputsForDevice(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE));
1232 EXPECT_EQ(streamCountBefore, mClient->getOpenedInputsCount());
1233}
1234
1235TEST_F(AudioPolicyManagerTestWithConfigurationFile, SetDeviceConnectionStateClosesStreams) {
1236 mClient->addSupportedFormat(AUDIO_FORMAT_PCM_16_BIT);
1237 mClient->addSupportedFormat(AUDIO_FORMAT_PCM_24_BIT_PACKED);
1238 mClient->addSupportedChannelMask(AUDIO_CHANNEL_IN_MONO);
1239 mClient->addSupportedChannelMask(AUDIO_CHANNEL_IN_STEREO);
1240 const size_t streamCountBefore = mClient->getOpenedInputsCount();
1241 EXPECT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_IN_USB_DEVICE,
1242 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1243 "", "", AUDIO_FORMAT_DEFAULT));
1244 EXPECT_EQ(streamCountBefore, mClient->getOpenedInputsCount());
1245}
1246
jiabin7c0205e2019-09-05 10:26:04 -07001247class AudioPolicyManagerTestDynamicPolicy : public AudioPolicyManagerTestWithConfigurationFile {
jiabinf4eb15a2019-08-28 15:31:47 -07001248protected:
jiabinf4eb15a2019-08-28 15:31:47 -07001249 void TearDown() override;
1250
1251 status_t addPolicyMix(int mixType, int mixFlag, audio_devices_t deviceType,
1252 std::string mixAddress, const audio_config_t& audioConfig,
Jan Sebechlebsky0e7b2f12022-08-18 14:40:37 +02001253 const std::vector<AudioMixMatchCriterion>& matchCriteria);
Marvin Raminbdefaf02023-11-01 09:10:32 +01001254
Marvin Raminabd9b892023-11-17 16:36:27 +01001255 status_t addPolicyMix(const AudioMix& mix);
1256
1257 status_t removePolicyMixes(const Vector<AudioMix>& mixes);
1258
Marvin Raminbdefaf02023-11-01 09:10:32 +01001259 std::vector<AudioMix> getRegisteredPolicyMixes();
jiabinf4eb15a2019-08-28 15:31:47 -07001260 void clearPolicyMix();
jiabin24ff57a2023-11-27 21:06:51 +00001261 void addPolicyMixAndStartInputForLoopback(
1262 int mixType, int mixFlag, audio_devices_t deviceType, std::string mixAddress,
1263 const audio_config_t& audioConfig,
1264 const std::vector<AudioMixMatchCriterion>& matchCriteria,
1265 audio_session_t session=AUDIO_SESSION_NONE,
1266 audio_config_base_t config=DEFAULT_INPUT_CONFIG,
1267 audio_input_flags_t inputFlags=AUDIO_INPUT_FLAG_NONE);
jiabinf4eb15a2019-08-28 15:31:47 -07001268
1269 Vector<AudioMix> mAudioMixes;
jiabinf4eb15a2019-08-28 15:31:47 -07001270 const std::string mMixAddress = "remote_submix_media";
jiabin24ff57a2023-11-27 21:06:51 +00001271
1272 audio_port_handle_t mLoopbackInputPortId = AUDIO_PORT_HANDLE_NONE;
1273 std::unique_ptr<RecordingActivityTracker> mTracker;
1274 struct audio_port_v7 mInjectionPort;
1275
1276 constexpr static const audio_config_base_t DEFAULT_INPUT_CONFIG = {
1277 .sample_rate = k48000SamplingRate,
1278 .channel_mask = AUDIO_CHANNEL_IN_STEREO,
1279 .format = AUDIO_FORMAT_PCM_16_BIT
1280 };
jiabinf4eb15a2019-08-28 15:31:47 -07001281};
1282
jiabinf4eb15a2019-08-28 15:31:47 -07001283void AudioPolicyManagerTestDynamicPolicy::TearDown() {
jiabin24ff57a2023-11-27 21:06:51 +00001284 clearPolicyMix();
jiabin7c0205e2019-09-05 10:26:04 -07001285 AudioPolicyManagerTestWithConfigurationFile::TearDown();
jiabinf4eb15a2019-08-28 15:31:47 -07001286}
1287
1288status_t AudioPolicyManagerTestDynamicPolicy::addPolicyMix(int mixType, int mixFlag,
1289 audio_devices_t deviceType, std::string mixAddress, const audio_config_t& audioConfig,
Jan Sebechlebsky0e7b2f12022-08-18 14:40:37 +02001290 const std::vector<AudioMixMatchCriterion>& matchCriteria = {}) {
1291 AudioMix myAudioMix(matchCriteria, mixType, audioConfig, mixFlag,
jiabinf4eb15a2019-08-28 15:31:47 -07001292 String8(mixAddress.c_str()), 0);
1293 myAudioMix.mDeviceType = deviceType;
Marvin Ramin0783e202024-03-05 12:45:50 +01001294 myAudioMix.mToken = sp<BBinder>::make();
jiabinf4eb15a2019-08-28 15:31:47 -07001295 // Clear mAudioMix before add new one to make sure we don't add already exist mixes.
1296 mAudioMixes.clear();
Marvin Raminabd9b892023-11-17 16:36:27 +01001297 return addPolicyMix(myAudioMix);
1298}
1299
1300status_t AudioPolicyManagerTestDynamicPolicy::addPolicyMix(const AudioMix& mix) {
1301 mAudioMixes.add(mix);
jiabinf4eb15a2019-08-28 15:31:47 -07001302
1303 // As the policy mixes registration may fail at some case,
1304 // caller need to check the returned status.
1305 status_t ret = mManager->registerPolicyMixes(mAudioMixes);
1306 return ret;
1307}
1308
Marvin Raminabd9b892023-11-17 16:36:27 +01001309status_t AudioPolicyManagerTestDynamicPolicy::removePolicyMixes(const Vector<AudioMix>& mixes) {
1310 status_t ret = mManager->unregisterPolicyMixes(mixes);
1311 return ret;
1312}
1313
Marvin Raminbdefaf02023-11-01 09:10:32 +01001314std::vector<AudioMix> AudioPolicyManagerTestDynamicPolicy::getRegisteredPolicyMixes() {
1315 std::vector<AudioMix> audioMixes;
1316 if (mManager != nullptr) {
1317 status_t ret = mManager->getRegisteredPolicyMixes(audioMixes);
1318 EXPECT_EQ(NO_ERROR, ret);
1319 }
1320 return audioMixes;
1321}
1322
jiabinf4eb15a2019-08-28 15:31:47 -07001323void AudioPolicyManagerTestDynamicPolicy::clearPolicyMix() {
1324 if (mManager != nullptr) {
jiabin24ff57a2023-11-27 21:06:51 +00001325 mManager->stopInput(mLoopbackInputPortId);
jiabinf4eb15a2019-08-28 15:31:47 -07001326 mManager->unregisterPolicyMixes(mAudioMixes);
1327 }
1328 mAudioMixes.clear();
1329}
1330
jiabin24ff57a2023-11-27 21:06:51 +00001331void AudioPolicyManagerTestDynamicPolicy::addPolicyMixAndStartInputForLoopback(
1332 int mixType, int mixFlag, audio_devices_t deviceType, std::string mixAddress,
1333 const audio_config_t& audioConfig,
1334 const std::vector<AudioMixMatchCriterion>& matchCriteria, audio_session_t session,
1335 audio_config_base_t config, audio_input_flags_t inputFlags) {
1336 ASSERT_EQ(NO_ERROR,
1337 addPolicyMix(mixType, mixFlag, deviceType, mixAddress, audioConfig, matchCriteria));
1338 if ((mixFlag & MIX_ROUTE_FLAG_LOOP_BACK) != MIX_ROUTE_FLAG_LOOP_BACK) {
1339 return;
1340 }
1341
1342 mTracker.reset(new RecordingActivityTracker());
1343 struct audio_port_v7 extractionPort;
1344 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SOURCE, AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1345 mixAddress, &extractionPort));
1346 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
1347 audio_source_t source = AUDIO_SOURCE_REMOTE_SUBMIX;
1348 audio_attributes_t attr = {
1349 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN, source, AUDIO_FLAG_NONE, ""};
1350 std::string tags = "addr=" + mMixAddress;
1351 audio_io_handle_t input = AUDIO_PORT_HANDLE_NONE;
1352 strncpy(attr.tags, tags.c_str(), AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1);
1353 ASSERT_NO_FATAL_FAILURE(
1354 getInputForAttr(attr, &input, session, mTracker->getRiid(),
1355 &selectedDeviceId, config.format, config.channel_mask,
1356 config.sample_rate, inputFlags, &mLoopbackInputPortId));
1357 ASSERT_EQ(NO_ERROR, mManager->startInput(mLoopbackInputPortId));
1358 ASSERT_EQ(extractionPort.id, selectedDeviceId);
1359
1360 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1361 mMixAddress, &mInjectionPort));
1362}
1363
jiabinf4eb15a2019-08-28 15:31:47 -07001364TEST_F(AudioPolicyManagerTestDynamicPolicy, InitSuccess) {
jiabin7c0205e2019-09-05 10:26:04 -07001365 // SetUp must finish with no assertions
jiabinf4eb15a2019-08-28 15:31:47 -07001366}
1367
1368TEST_F(AudioPolicyManagerTestDynamicPolicy, Dump) {
1369 dumpToLog();
1370}
1371
1372TEST_F(AudioPolicyManagerTestDynamicPolicy, RegisterPolicyMixes) {
1373 status_t ret;
1374 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1375
1376 // Only capture of playback is allowed in LOOP_BACK &RENDER mode
1377 ret = addPolicyMix(MIX_TYPE_RECORDERS, MIX_ROUTE_FLAG_LOOP_BACK_AND_RENDER,
Jan Sebechlebsky0e7b2f12022-08-18 14:40:37 +02001378 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, "", audioConfig);
jiabinf4eb15a2019-08-28 15:31:47 -07001379 ASSERT_EQ(INVALID_OPERATION, ret);
1380
1381 // Fail due to the device is already connected.
1382 clearPolicyMix();
1383 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
Jan Sebechlebsky0e7b2f12022-08-18 14:40:37 +02001384 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, "", audioConfig);
jiabinf4eb15a2019-08-28 15:31:47 -07001385 ASSERT_EQ(INVALID_OPERATION, ret);
1386
1387 // The first time to register policy mixes with valid parameter should succeed.
1388 clearPolicyMix();
1389 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1390 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001391 audioConfig.sample_rate = k48000SamplingRate;
jiabinf4eb15a2019-08-28 15:31:47 -07001392 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
Jan Sebechlebsky0e7b2f12022-08-18 14:40:37 +02001393 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, mMixAddress, audioConfig);
jiabinf4eb15a2019-08-28 15:31:47 -07001394 ASSERT_EQ(NO_ERROR, ret);
1395 // Registering the same policy mixes should fail.
1396 ret = mManager->registerPolicyMixes(mAudioMixes);
1397 ASSERT_EQ(INVALID_OPERATION, ret);
1398
jiabinf4eb15a2019-08-28 15:31:47 -07001399 // Registration should fail due to device not found.
1400 // Note that earpiece is not present in the test configuration file.
1401 // This will need to be updated if earpiece is added in the test configuration file.
jiabin7c0205e2019-09-05 10:26:04 -07001402 clearPolicyMix();
jiabinf4eb15a2019-08-28 15:31:47 -07001403 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
Jan Sebechlebsky0e7b2f12022-08-18 14:40:37 +02001404 AUDIO_DEVICE_OUT_EARPIECE, "", audioConfig);
jiabinf4eb15a2019-08-28 15:31:47 -07001405 ASSERT_EQ(INVALID_OPERATION, ret);
1406
1407 // Registration should fail due to output not found.
1408 clearPolicyMix();
1409 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
Jan Sebechlebsky0e7b2f12022-08-18 14:40:37 +02001410 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, "", audioConfig);
jiabinf4eb15a2019-08-28 15:31:47 -07001411 ASSERT_EQ(INVALID_OPERATION, ret);
1412
Jan Sebechlebskycd33d8d2023-06-07 10:45:50 +02001413 // The first time to register valid loopback policy mix should succeed.
jiabinf4eb15a2019-08-28 15:31:47 -07001414 clearPolicyMix();
Jan Sebechlebskycd33d8d2023-06-07 10:45:50 +02001415 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
1416 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, "addr", audioConfig);
jiabinf4eb15a2019-08-28 15:31:47 -07001417 ASSERT_EQ(NO_ERROR, ret);
Jan Sebechlebskycd33d8d2023-06-07 10:45:50 +02001418 // Registering the render policy for the loopback address should succeed.
1419 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
1420 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, "addr", audioConfig);
jiabinf4eb15a2019-08-28 15:31:47 -07001421 ASSERT_EQ(INVALID_OPERATION, ret);
1422}
1423
1424TEST_F(AudioPolicyManagerTestDynamicPolicy, UnregisterPolicyMixes) {
1425 status_t ret;
1426 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1427
1428 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1429 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001430 audioConfig.sample_rate = k48000SamplingRate;
jiabinf4eb15a2019-08-28 15:31:47 -07001431 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
Jan Sebechlebsky0e7b2f12022-08-18 14:40:37 +02001432 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, mMixAddress, audioConfig);
jiabinf4eb15a2019-08-28 15:31:47 -07001433 ASSERT_EQ(NO_ERROR, ret);
1434
1435 // After successfully registering policy mixes, it should be able to unregister.
1436 ret = mManager->unregisterPolicyMixes(mAudioMixes);
1437 ASSERT_EQ(NO_ERROR, ret);
1438
1439 // After unregistering policy mixes successfully, it should fail unregistering
1440 // the same policy mixes as they are not registered.
1441 ret = mManager->unregisterPolicyMixes(mAudioMixes);
1442 ASSERT_EQ(INVALID_OPERATION, ret);
jiabin7c0205e2019-09-05 10:26:04 -07001443}
jiabinf4eb15a2019-08-28 15:31:47 -07001444
Jan Sebechlebsky0e7b2f12022-08-18 14:40:37 +02001445TEST_F(AudioPolicyManagerTestDynamicPolicy, RegisterPolicyWithConsistentMixSucceeds) {
1446 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1447 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1448 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
1449 audioConfig.sample_rate = k48000SamplingRate;
1450
1451 std::vector<AudioMixMatchCriterion> mixMatchCriteria = {
1452 createUidCriterion(/*uid=*/42),
1453 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/true)};
1454 status_t ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
1455 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, mMixAddress, audioConfig,
1456 mixMatchCriteria);
1457 ASSERT_EQ(NO_ERROR, ret);
1458}
1459
1460TEST_F(AudioPolicyManagerTestDynamicPolicy, RegisterPolicyWithInconsistentMixFails) {
1461 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1462 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1463 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
1464 audioConfig.sample_rate = k48000SamplingRate;
1465
1466 std::vector<AudioMixMatchCriterion> mixMatchCriteria = {
1467 createUidCriterion(/*uid=*/42),
1468 createUidCriterion(/*uid=*/1235, /*exclude=*/true),
1469 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/true)};
1470 status_t ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
1471 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, mMixAddress, audioConfig,
1472 mixMatchCriteria);
1473 ASSERT_EQ(INVALID_OPERATION, ret);
1474}
1475
Marvin Raminbdefaf02023-11-01 09:10:32 +01001476TEST_F_WITH_FLAGS(
1477 AudioPolicyManagerTestDynamicPolicy,
Marvin Raminabd9b892023-11-17 16:36:27 +01001478 RegisterInvalidMixesDoesNotImpactPriorMixes,
1479 REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(android::media::audiopolicy, audio_mix_test_api),
1480 ACONFIG_FLAG(android::media::audiopolicy, audio_mix_ownership))
1481) {
1482 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1483 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1484 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
1485 audioConfig.sample_rate = k48000SamplingRate;
1486
1487 std::vector<AudioMixMatchCriterion> validMixMatchCriteria = {
1488 createUidCriterion(/*uid=*/42),
1489 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/true)};
1490 AudioMix validAudioMix(validMixMatchCriteria, MIX_TYPE_PLAYERS, audioConfig,
1491 MIX_ROUTE_FLAG_LOOP_BACK, String8(mMixAddress.c_str()), 0);
1492 validAudioMix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1493
1494 mAudioMixes.clear();
Marvin Ramin0783e202024-03-05 12:45:50 +01001495 status_t ret = addPolicyMix(validAudioMix);
Marvin Raminabd9b892023-11-17 16:36:27 +01001496
1497 ASSERT_EQ(NO_ERROR, ret);
1498
1499 std::vector<AudioMix> registeredMixes = getRegisteredPolicyMixes();
1500 ASSERT_EQ(1, registeredMixes.size());
1501
1502 std::vector<AudioMixMatchCriterion> invalidMixMatchCriteria = {
1503 createUidCriterion(/*uid=*/42),
1504 createUidCriterion(/*uid=*/1235, /*exclude=*/true),
1505 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/true)};
1506
1507 AudioMix invalidAudioMix(invalidMixMatchCriteria, MIX_TYPE_PLAYERS, audioConfig,
1508 MIX_ROUTE_FLAG_LOOP_BACK, String8(mMixAddress.c_str()), 0);
1509 validAudioMix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1510
Marvin Ramin0783e202024-03-05 12:45:50 +01001511 ret = addPolicyMix(invalidAudioMix);
Marvin Raminabd9b892023-11-17 16:36:27 +01001512
1513 ASSERT_EQ(INVALID_OPERATION, ret);
1514
1515 std::vector<AudioMix> remainingMixes = getRegisteredPolicyMixes();
1516 ASSERT_EQ(registeredMixes.size(), remainingMixes.size());
1517}
1518
1519TEST_F_WITH_FLAGS(
1520 AudioPolicyManagerTestDynamicPolicy,
1521 UnregisterInvalidMixesReturnsError,
1522 REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(android::media::audiopolicy, audio_mix_test_api),
1523 ACONFIG_FLAG(android::media::audiopolicy, audio_mix_ownership))
1524) {
1525 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1526 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1527 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
1528 audioConfig.sample_rate = k48000SamplingRate;
1529
1530 std::vector<AudioMixMatchCriterion> validMixMatchCriteria = {
1531 createUidCriterion(/*uid=*/42),
1532 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/true)};
1533 AudioMix validAudioMix(validMixMatchCriteria, MIX_TYPE_PLAYERS, audioConfig,
1534 MIX_ROUTE_FLAG_LOOP_BACK, String8(mMixAddress.c_str()), 0);
1535 validAudioMix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1536
1537 mAudioMixes.clear();
Marvin Ramin0783e202024-03-05 12:45:50 +01001538 status_t ret = addPolicyMix(validAudioMix);
Marvin Raminabd9b892023-11-17 16:36:27 +01001539
1540 ASSERT_EQ(NO_ERROR, ret);
1541
1542 std::vector<AudioMix> registeredMixes = getRegisteredPolicyMixes();
1543 ASSERT_EQ(1, registeredMixes.size());
1544
1545 std::vector<AudioMixMatchCriterion> invalidMixMatchCriteria = {
1546 createUidCriterion(/*uid=*/42),
1547 createUidCriterion(/*uid=*/1235, /*exclude=*/true),
1548 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/true)};
1549
1550 AudioMix invalidAudioMix(invalidMixMatchCriteria, MIX_TYPE_PLAYERS, audioConfig,
1551 MIX_ROUTE_FLAG_LOOP_BACK, String8(mMixAddress.c_str()), 0);
Marvin Ramin0783e202024-03-05 12:45:50 +01001552 invalidAudioMix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Marvin Raminabd9b892023-11-17 16:36:27 +01001553
1554 Vector<AudioMix> mixes;
1555 mixes.add(invalidAudioMix);
1556 mixes.add(validAudioMix);
1557 ret = removePolicyMixes(mixes);
1558
1559 ASSERT_EQ(INVALID_OPERATION, ret);
1560
1561 std::vector<AudioMix> remainingMixes = getRegisteredPolicyMixes();
1562 EXPECT_THAT(remainingMixes, IsEmpty());
1563}
1564
1565TEST_F_WITH_FLAGS(
1566 AudioPolicyManagerTestDynamicPolicy,
Marvin Raminbdefaf02023-11-01 09:10:32 +01001567 GetRegisteredPolicyMixes,
1568 REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(android::media::audiopolicy, audio_mix_test_api))
1569) {
1570 std::vector<AudioMix> mixes = getRegisteredPolicyMixes();
1571 EXPECT_THAT(mixes, IsEmpty());
1572}
1573
1574TEST_F_WITH_FLAGS(AudioPolicyManagerTestDynamicPolicy,
1575 AddPolicyMixAndVerifyGetRegisteredPolicyMixes,
1576 REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(android::media::audiopolicy, audio_mix_test_api))
1577) {
1578 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1579 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1580 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
1581 audioConfig.sample_rate = k48000SamplingRate;
1582
1583 std::vector<AudioMixMatchCriterion> mixMatchCriteria = {
1584 createUidCriterion(/*uid=*/42),
1585 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/true)};
1586 status_t ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
1587 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, mMixAddress, audioConfig,
1588 mixMatchCriteria);
1589 ASSERT_EQ(NO_ERROR, ret);
1590
1591 std::vector<AudioMix> mixes = getRegisteredPolicyMixes();
1592 ASSERT_EQ(mixes.size(), 1);
1593
1594 const AudioMix& mix = mixes[0];
1595 ASSERT_EQ(mix.mCriteria.size(), mixMatchCriteria.size());
1596 for (uint32_t i = 0; i < mixMatchCriteria.size(); i++) {
1597 EXPECT_EQ(mix.mCriteria[i].mRule, mixMatchCriteria[i].mRule);
1598 EXPECT_EQ(mix.mCriteria[i].mValue.mUsage, mixMatchCriteria[i].mValue.mUsage);
1599 }
1600 EXPECT_EQ(mix.mDeviceType, AUDIO_DEVICE_OUT_REMOTE_SUBMIX);
1601 EXPECT_EQ(mix.mRouteFlags, MIX_ROUTE_FLAG_LOOP_BACK);
1602 EXPECT_EQ(mix.mMixType, MIX_TYPE_PLAYERS);
1603 EXPECT_EQ(mix.mFormat.channel_mask, audioConfig.channel_mask);
1604 EXPECT_EQ(mix.mFormat.format, audioConfig.format);
1605 EXPECT_EQ(mix.mFormat.sample_rate, audioConfig.sample_rate);
1606 EXPECT_EQ(mix.mFormat.frame_count, audioConfig.frame_count);
1607}
1608
Kriti Dangef6be8f2020-11-05 11:58:19 +01001609class AudioPolicyManagerTestForHdmi
Mikhail Naganov18885d32021-10-01 13:03:09 -07001610 : public AudioPolicyManagerTestWithConfigurationFile,
1611 public testing::WithParamInterface<audio_format_t> {
Kriti Dangef6be8f2020-11-05 11:58:19 +01001612protected:
1613 void SetUp() override;
1614 std::string getConfigFile() override { return sTvConfig; }
Kriti Dang6537def2021-03-02 13:46:59 +01001615 std::map<audio_format_t, bool> getSurroundFormatsHelper();
1616 std::vector<audio_format_t> getReportedSurroundFormatsHelper();
Kriti Dangef6be8f2020-11-05 11:58:19 +01001617 std::unordered_set<audio_format_t> getFormatsFromPorts();
Kriti Dangef6be8f2020-11-05 11:58:19 +01001618 void TearDown() override;
1619
1620 static const std::string sTvConfig;
1621
1622};
1623
1624const std::string AudioPolicyManagerTestForHdmi::sTvConfig =
1625 AudioPolicyManagerTestForHdmi::sExecutableDir +
1626 "test_settop_box_surround_configuration.xml";
1627
1628void AudioPolicyManagerTestForHdmi::SetUp() {
Mikhail Naganovd4c21aa2021-10-05 15:10:16 -07001629 ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTest::SetUp());
Mikhail Naganov83caee02021-10-05 15:52:01 -07001630 mClient->addSupportedFormat(AUDIO_FORMAT_AC3);
Kriti Dangef6be8f2020-11-05 11:58:19 +01001631 mClient->addSupportedFormat(AUDIO_FORMAT_E_AC3);
jiabin12537fc2023-10-12 17:56:08 +00001632 mClient->addSupportedChannelMask(AUDIO_CHANNEL_OUT_STEREO);
Kriti Dangef6be8f2020-11-05 11:58:19 +01001633 mManager->setDeviceConnectionState(
1634 AUDIO_DEVICE_OUT_HDMI, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1635 "" /*address*/, "" /*name*/, AUDIO_FORMAT_DEFAULT);
1636}
1637
1638void AudioPolicyManagerTestForHdmi::TearDown() {
1639 mManager->setDeviceConnectionState(
1640 AUDIO_DEVICE_OUT_HDMI, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1641 "" /*address*/, "" /*name*/, AUDIO_FORMAT_DEFAULT);
1642 AudioPolicyManagerTest::TearDown();
1643}
1644
1645std::map<audio_format_t, bool>
Kriti Dang6537def2021-03-02 13:46:59 +01001646 AudioPolicyManagerTestForHdmi::getSurroundFormatsHelper() {
Kriti Dangef6be8f2020-11-05 11:58:19 +01001647 unsigned int numSurroundFormats = 0;
1648 std::map<audio_format_t, bool> surroundFormatsMap;
1649 status_t ret = mManager->getSurroundFormats(
1650 &numSurroundFormats, nullptr /* surroundFormats */,
Kriti Dang6537def2021-03-02 13:46:59 +01001651 nullptr /* surroundFormatsEnabled */);
Kriti Dangef6be8f2020-11-05 11:58:19 +01001652 EXPECT_EQ(NO_ERROR, ret);
1653 if (ret != NO_ERROR) {
1654 return surroundFormatsMap;
1655 }
1656 audio_format_t surroundFormats[numSurroundFormats];
1657 memset(surroundFormats, 0, sizeof(audio_format_t) * numSurroundFormats);
1658 bool surroundFormatsEnabled[numSurroundFormats];
1659 memset(surroundFormatsEnabled, 0, sizeof(bool) * numSurroundFormats);
1660 ret = mManager->getSurroundFormats(
Kriti Dang6537def2021-03-02 13:46:59 +01001661 &numSurroundFormats, surroundFormats, surroundFormatsEnabled);
Kriti Dangef6be8f2020-11-05 11:58:19 +01001662 EXPECT_EQ(NO_ERROR, ret);
1663 if (ret != NO_ERROR) {
1664 return surroundFormatsMap;
1665 }
1666 for (int i = 0; i< numSurroundFormats; i++) {
1667 surroundFormatsMap[surroundFormats[i]] = surroundFormatsEnabled[i];
1668 }
1669 return surroundFormatsMap;
1670}
1671
Kriti Dang6537def2021-03-02 13:46:59 +01001672std::vector<audio_format_t> AudioPolicyManagerTestForHdmi::getReportedSurroundFormatsHelper() {
1673 unsigned int numSurroundFormats = 0;
1674 std::vector<audio_format_t> surroundFormatsVector;
1675 status_t ret = mManager->getReportedSurroundFormats(
1676 &numSurroundFormats, nullptr /* surroundFormats */);
1677 EXPECT_EQ(NO_ERROR, ret);
1678 if (ret != NO_ERROR) {
1679 return surroundFormatsVector;
1680 }
1681 audio_format_t surroundFormats[numSurroundFormats];
1682 memset(surroundFormats, 0, sizeof(audio_format_t) * numSurroundFormats);
1683 ret = mManager->getReportedSurroundFormats(&numSurroundFormats, surroundFormats);
1684 EXPECT_EQ(NO_ERROR, ret);
1685 if (ret != NO_ERROR) {
1686 return surroundFormatsVector;
1687 }
1688 for (const auto &surroundFormat : surroundFormats) {
1689 surroundFormatsVector.push_back(surroundFormat);
1690 }
1691 return surroundFormatsVector;
1692}
1693
Kriti Dangef6be8f2020-11-05 11:58:19 +01001694std::unordered_set<audio_format_t>
1695 AudioPolicyManagerTestForHdmi::getFormatsFromPorts() {
1696 uint32_t numPorts = 0;
1697 uint32_t generation1;
1698 status_t ret;
1699 std::unordered_set<audio_format_t> formats;
1700 ret = mManager->listAudioPorts(
1701 AUDIO_PORT_ROLE_SINK, AUDIO_PORT_TYPE_DEVICE, &numPorts, nullptr, &generation1);
1702 EXPECT_EQ(NO_ERROR, ret) << "mManager->listAudioPorts returned error";
1703 if (ret != NO_ERROR) {
1704 return formats;
1705 }
jiabin19cdba52020-11-24 11:28:58 -08001706 struct audio_port_v7 ports[numPorts];
Kriti Dangef6be8f2020-11-05 11:58:19 +01001707 ret = mManager->listAudioPorts(
1708 AUDIO_PORT_ROLE_SINK, AUDIO_PORT_TYPE_DEVICE, &numPorts, ports, &generation1);
1709 EXPECT_EQ(NO_ERROR, ret) << "mManager->listAudioPorts returned error";
1710 if (ret != NO_ERROR) {
1711 return formats;
1712 }
1713 for (const auto &port : ports) {
jiabin19cdba52020-11-24 11:28:58 -08001714 for (size_t i = 0; i < port.num_audio_profiles; ++i) {
1715 formats.insert(port.audio_profiles[i].format);
1716 }
Kriti Dangef6be8f2020-11-05 11:58:19 +01001717 }
1718 return formats;
1719}
1720
Mikhail Naganov18885d32021-10-01 13:03:09 -07001721TEST_P(AudioPolicyManagerTestForHdmi, GetSurroundFormatsReturnsSupportedFormats) {
Kriti Dangef6be8f2020-11-05 11:58:19 +01001722 mManager->setForceUse(
1723 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS);
Kriti Dang6537def2021-03-02 13:46:59 +01001724 auto surroundFormats = getSurroundFormatsHelper();
Mikhail Naganov18885d32021-10-01 13:03:09 -07001725 ASSERT_EQ(1, surroundFormats.count(GetParam()));
Kriti Dangef6be8f2020-11-05 11:58:19 +01001726}
1727
Mikhail Naganov18885d32021-10-01 13:03:09 -07001728TEST_P(AudioPolicyManagerTestForHdmi,
Kriti Dangef6be8f2020-11-05 11:58:19 +01001729 GetSurroundFormatsReturnsManipulatedFormats) {
1730 mManager->setForceUse(
1731 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL);
1732
1733 status_t ret =
Mikhail Naganov18885d32021-10-01 13:03:09 -07001734 mManager->setSurroundFormatEnabled(GetParam(), false /*enabled*/);
Kriti Dangef6be8f2020-11-05 11:58:19 +01001735 ASSERT_EQ(NO_ERROR, ret);
Kriti Dang6537def2021-03-02 13:46:59 +01001736 auto surroundFormats = getSurroundFormatsHelper();
Mikhail Naganov18885d32021-10-01 13:03:09 -07001737 ASSERT_EQ(1, surroundFormats.count(GetParam()));
1738 ASSERT_FALSE(surroundFormats[GetParam()]);
Kriti Dangef6be8f2020-11-05 11:58:19 +01001739
Mikhail Naganov18885d32021-10-01 13:03:09 -07001740 ret = mManager->setSurroundFormatEnabled(GetParam(), true /*enabled*/);
Kriti Dangef6be8f2020-11-05 11:58:19 +01001741 ASSERT_EQ(NO_ERROR, ret);
Kriti Dang6537def2021-03-02 13:46:59 +01001742 surroundFormats = getSurroundFormatsHelper();
Mikhail Naganov18885d32021-10-01 13:03:09 -07001743 ASSERT_EQ(1, surroundFormats.count(GetParam()));
1744 ASSERT_TRUE(surroundFormats[GetParam()]);
Kriti Dangef6be8f2020-11-05 11:58:19 +01001745
Mikhail Naganov18885d32021-10-01 13:03:09 -07001746 ret = mManager->setSurroundFormatEnabled(GetParam(), false /*enabled*/);
Kriti Dangef6be8f2020-11-05 11:58:19 +01001747 ASSERT_EQ(NO_ERROR, ret);
Kriti Dang6537def2021-03-02 13:46:59 +01001748 surroundFormats = getSurroundFormatsHelper();
Mikhail Naganov18885d32021-10-01 13:03:09 -07001749 ASSERT_EQ(1, surroundFormats.count(GetParam()));
1750 ASSERT_FALSE(surroundFormats[GetParam()]);
Kriti Dangef6be8f2020-11-05 11:58:19 +01001751}
1752
Mikhail Naganov18885d32021-10-01 13:03:09 -07001753TEST_P(AudioPolicyManagerTestForHdmi,
Kriti Dangef6be8f2020-11-05 11:58:19 +01001754 ListAudioPortsReturnManipulatedHdmiFormats) {
1755 mManager->setForceUse(
1756 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL);
1757
Mikhail Naganov18885d32021-10-01 13:03:09 -07001758 ASSERT_EQ(NO_ERROR, mManager->setSurroundFormatEnabled(GetParam(), true /*enabled*/));
jiabin12537fc2023-10-12 17:56:08 +00001759 auto formats = getFormatsFromPorts();
Mikhail Naganov18885d32021-10-01 13:03:09 -07001760 ASSERT_EQ(1, formats.count(GetParam()));
jiabin12537fc2023-10-12 17:56:08 +00001761
1762 ASSERT_EQ(NO_ERROR, mManager->setSurroundFormatEnabled(GetParam(), false /*enabled*/));
1763 formats = getFormatsFromPorts();
1764 ASSERT_EQ(0, formats.count(GetParam()));
Kriti Dangef6be8f2020-11-05 11:58:19 +01001765}
1766
Mikhail Naganov18885d32021-10-01 13:03:09 -07001767TEST_P(AudioPolicyManagerTestForHdmi,
Kriti Dangef6be8f2020-11-05 11:58:19 +01001768 GetReportedSurroundFormatsReturnsHdmiReportedFormats) {
1769 mManager->setForceUse(
1770 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS);
Kriti Dang6537def2021-03-02 13:46:59 +01001771 auto surroundFormats = getReportedSurroundFormatsHelper();
Mikhail Naganov18885d32021-10-01 13:03:09 -07001772 ASSERT_EQ(1, std::count(surroundFormats.begin(), surroundFormats.end(), GetParam()));
Kriti Dangef6be8f2020-11-05 11:58:19 +01001773}
1774
Mikhail Naganov18885d32021-10-01 13:03:09 -07001775TEST_P(AudioPolicyManagerTestForHdmi,
Kriti Dangef6be8f2020-11-05 11:58:19 +01001776 GetReportedSurroundFormatsReturnsNonManipulatedHdmiReportedFormats) {
1777 mManager->setForceUse(
1778 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL);
1779
Mikhail Naganov18885d32021-10-01 13:03:09 -07001780 status_t ret = mManager->setSurroundFormatEnabled(GetParam(), false /*enabled*/);
Kriti Dangef6be8f2020-11-05 11:58:19 +01001781 ASSERT_EQ(NO_ERROR, ret);
Kriti Dang6537def2021-03-02 13:46:59 +01001782 auto surroundFormats = getReportedSurroundFormatsHelper();
Mikhail Naganov18885d32021-10-01 13:03:09 -07001783 ASSERT_EQ(1, std::count(surroundFormats.begin(), surroundFormats.end(), GetParam()));
Kriti Dangef6be8f2020-11-05 11:58:19 +01001784
Mikhail Naganov18885d32021-10-01 13:03:09 -07001785 ret = mManager->setSurroundFormatEnabled(GetParam(), true /*enabled*/);
Kriti Dangef6be8f2020-11-05 11:58:19 +01001786 ASSERT_EQ(NO_ERROR, ret);
Kriti Dang6537def2021-03-02 13:46:59 +01001787 surroundFormats = getReportedSurroundFormatsHelper();
Mikhail Naganov18885d32021-10-01 13:03:09 -07001788 ASSERT_EQ(1, std::count(surroundFormats.begin(), surroundFormats.end(), GetParam()));
Kriti Dangef6be8f2020-11-05 11:58:19 +01001789}
1790
Mikhail Naganov18885d32021-10-01 13:03:09 -07001791TEST_P(AudioPolicyManagerTestForHdmi, GetSurroundFormatsIgnoresSupportedFormats) {
1792 mManager->setForceUse(
1793 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER);
1794 auto surroundFormats = getSurroundFormatsHelper();
1795 ASSERT_EQ(1, surroundFormats.count(GetParam()));
1796 ASSERT_FALSE(surroundFormats[GetParam()]);
1797}
1798
1799INSTANTIATE_TEST_SUITE_P(SurroundFormatSupport, AudioPolicyManagerTestForHdmi,
1800 testing::Values(AUDIO_FORMAT_AC3, AUDIO_FORMAT_E_AC3),
1801 [](const ::testing::TestParamInfo<AudioPolicyManagerTestForHdmi::ParamType>& info) {
1802 return audio_format_to_string(info.param);
1803 });
1804
jiabin7c0205e2019-09-05 10:26:04 -07001805class AudioPolicyManagerTestDPNoRemoteSubmixModule : public AudioPolicyManagerTestDynamicPolicy {
1806protected:
1807 std::string getConfigFile() override { return sPrimaryOnlyConfig; }
1808
1809 static const std::string sPrimaryOnlyConfig;
1810};
1811
1812const std::string AudioPolicyManagerTestDPNoRemoteSubmixModule::sPrimaryOnlyConfig =
1813 sExecutableDir + "test_audio_policy_primary_only_configuration.xml";
1814
1815TEST_F(AudioPolicyManagerTestDPNoRemoteSubmixModule, InitSuccess) {
1816 // SetUp must finish with no assertions.
1817}
1818
1819TEST_F(AudioPolicyManagerTestDPNoRemoteSubmixModule, Dump) {
1820 dumpToLog();
1821}
1822
1823TEST_F(AudioPolicyManagerTestDPNoRemoteSubmixModule, RegistrationFailure) {
1824 // Registration/Unregistration should fail due to module for remote submix not found.
1825 status_t ret;
1826 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1827 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1828 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001829 audioConfig.sample_rate = k48000SamplingRate;
jiabin7c0205e2019-09-05 10:26:04 -07001830 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
Jan Sebechlebsky0e7b2f12022-08-18 14:40:37 +02001831 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, "", audioConfig);
jiabin7c0205e2019-09-05 10:26:04 -07001832 ASSERT_EQ(INVALID_OPERATION, ret);
1833
jiabinf4eb15a2019-08-28 15:31:47 -07001834 ret = mManager->unregisterPolicyMixes(mAudioMixes);
1835 ASSERT_EQ(INVALID_OPERATION, ret);
1836}
1837
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001838struct DPTestParam {
1839 DPTestParam(const std::vector<AudioMixMatchCriterion>& mixCriteria,
1840 bool expected_match = false)
1841 : mixCriteria(mixCriteria), attributes(defaultAttr), session(AUDIO_SESSION_NONE),
1842 expected_match(expected_match) {}
1843
1844 DPTestParam& withUsage(audio_usage_t usage) {
1845 attributes.usage = usage;
1846 return *this;
1847 }
1848
1849 DPTestParam& withTags(const char *tags) {
1850 std::strncpy(attributes.tags, tags, sizeof(attributes.tags));
1851 return *this;
1852 }
1853
1854 DPTestParam& withSource(audio_source_t source) {
1855 attributes.source = source;
1856 return *this;
1857 }
1858
1859 DPTestParam& withSessionId(audio_session_t sessionId) {
1860 session = sessionId;
1861 return *this;
1862 }
1863
1864 std::vector<AudioMixMatchCriterion> mixCriteria;
1865 audio_attributes_t attributes;
1866 audio_session_t session;
1867 bool expected_match;
1868};
1869
jiabinf4eb15a2019-08-28 15:31:47 -07001870class AudioPolicyManagerTestDPPlaybackReRouting : public AudioPolicyManagerTestDynamicPolicy,
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001871 public testing::WithParamInterface<DPTestParam> {
jiabinf4eb15a2019-08-28 15:31:47 -07001872protected:
1873 void SetUp() override;
jiabinf4eb15a2019-08-28 15:31:47 -07001874};
1875
1876void AudioPolicyManagerTestDPPlaybackReRouting::SetUp() {
Mikhail Naganovd4c21aa2021-10-05 15:10:16 -07001877 ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTestDynamicPolicy::SetUp());
jiabinf4eb15a2019-08-28 15:31:47 -07001878
1879 mTracker.reset(new RecordingActivityTracker());
1880
1881 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
1882 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1883 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001884 audioConfig.sample_rate = k48000SamplingRate;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001885
1886 DPTestParam param = GetParam();
jiabin24ff57a2023-11-27 21:06:51 +00001887 ASSERT_NO_FATAL_FAILURE(
1888 addPolicyMixAndStartInputForLoopback(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_LOOP_BACK,
1889 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, mMixAddress, audioConfig, param.mixCriteria,
1890 param.session));
jiabinf4eb15a2019-08-28 15:31:47 -07001891}
1892
jiabinf4eb15a2019-08-28 15:31:47 -07001893TEST_P(AudioPolicyManagerTestDPPlaybackReRouting, PlaybackReRouting) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001894 const DPTestParam param = GetParam();
1895 const audio_attributes_t& attr = param.attributes;
jiabinf4eb15a2019-08-28 15:31:47 -07001896
jiabin7c0205e2019-09-05 10:26:04 -07001897 audio_port_handle_t playbackRoutedPortId = AUDIO_PORT_HANDLE_NONE;
jiabinf4eb15a2019-08-28 15:31:47 -07001898 getOutputForAttr(&playbackRoutedPortId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
Dean Wheatleyd082f472022-02-04 11:10:48 +11001899 k48000SamplingRate, AUDIO_OUTPUT_FLAG_NONE, nullptr /*output*/, nullptr /*portId*/,
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001900 attr, param.session);
1901 if (param.expected_match) {
jiabinf4eb15a2019-08-28 15:31:47 -07001902 EXPECT_EQ(mInjectionPort.id, playbackRoutedPortId);
1903 } else {
1904 EXPECT_NE(mInjectionPort.id, playbackRoutedPortId);
1905 }
1906}
1907
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001908const std::vector<AudioMixMatchCriterion> USAGE_MEDIA_ALARM_CRITERIA = {
1909 createUsageCriterion(AUDIO_USAGE_MEDIA),
1910 createUsageCriterion(AUDIO_USAGE_ALARM)
1911};
jiabinf4eb15a2019-08-28 15:31:47 -07001912
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001913INSTANTIATE_TEST_SUITE_P(
1914 PlaybackReroutingUsageMatch,
1915 AudioPolicyManagerTestDPPlaybackReRouting,
1916 testing::Values(
1917 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1918 .withUsage(AUDIO_USAGE_MEDIA),
1919 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1920 .withUsage(AUDIO_USAGE_MEDIA).withTags("addr=other"),
1921 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1922 .withUsage(AUDIO_USAGE_ALARM),
1923 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1924 .withUsage(AUDIO_USAGE_VOICE_COMMUNICATION),
1925 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1926 .withUsage(AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING),
1927 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1928 .withUsage(AUDIO_USAGE_NOTIFICATION),
1929 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1930 .withUsage(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE),
1931 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1932 .withUsage(AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST),
1933 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1934 .withUsage(AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT),
1935 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1936 .withUsage(AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED),
1937 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1938 .withUsage(AUDIO_USAGE_NOTIFICATION_EVENT),
1939 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1940 .withUsage(AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY),
1941 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1942 .withUsage(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE),
1943 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1944 .withUsage(AUDIO_USAGE_ASSISTANCE_SONIFICATION),
1945 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1946 .withUsage(AUDIO_USAGE_GAME),
1947 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ false)
1948 .withUsage(AUDIO_USAGE_ASSISTANT)));
jiabinf4eb15a2019-08-28 15:31:47 -07001949
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001950INSTANTIATE_TEST_SUITE_P(
1951 PlaybackReroutingAddressPriorityMatch,
1952 AudioPolicyManagerTestDPPlaybackReRouting,
1953 testing::Values(
1954 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1955 .withUsage(AUDIO_USAGE_MEDIA).withTags("addr=remote_submix_media"),
1956 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1957 .withUsage(AUDIO_USAGE_VOICE_COMMUNICATION).withTags("addr=remote_submix_media"),
1958 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1959 .withUsage(AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING)
1960 .withTags("addr=remote_submix_media"),
1961 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1962 .withUsage(AUDIO_USAGE_ALARM)
1963 .withTags("addr=remote_submix_media"),
1964 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1965 .withUsage(AUDIO_USAGE_NOTIFICATION)
1966 .withTags("addr=remote_submix_media"),
1967 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1968 .withUsage(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE)
1969 .withTags("addr=remote_submix_media"),
1970 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1971 .withUsage(AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST)
1972 .withTags("addr=remote_submix_media"),
1973 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1974 .withUsage(AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT)
1975 .withTags("addr=remote_submix_media"),
1976 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1977 .withUsage(AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED)
1978 .withTags("addr=remote_submix_media"),
1979 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1980 .withUsage(AUDIO_USAGE_NOTIFICATION_EVENT)
1981 .withTags("addr=remote_submix_media"),
1982 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1983 .withUsage(AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY)
1984 .withTags("addr=remote_submix_media"),
1985 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1986 .withUsage(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE)
1987 .withTags("addr=remote_submix_media"),
1988 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1989 .withUsage(AUDIO_USAGE_ASSISTANCE_SONIFICATION)
1990 .withTags("addr=remote_submix_media"),
1991 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1992 .withUsage(AUDIO_USAGE_GAME)
1993 .withTags("addr=remote_submix_media"),
1994 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1995 .withUsage(AUDIO_USAGE_VIRTUAL_SOURCE)
1996 .withTags("addr=remote_submix_media"),
1997 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
1998 .withUsage(AUDIO_USAGE_ASSISTANT)
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02001999 .withTags("addr=remote_submix_media"),
2000 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
2001 .withUsage(AUDIO_USAGE_ASSISTANT)
2002 .withTags("sometag;addr=remote_submix_media;othertag=somevalue"),
2003 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
2004 .withUsage(AUDIO_USAGE_ASSISTANT)
2005 .withTags("addr=remote_submix_media;othertag"),
2006 DPTestParam(USAGE_MEDIA_ALARM_CRITERIA, /*expected_match=*/ true)
2007 .withUsage(AUDIO_USAGE_ASSISTANT)
2008 .withTags("sometag;othertag;addr=remote_submix_media")));
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002009
2010static constexpr audio_session_t TEST_SESSION_ID = static_cast<audio_session_t>(42);
2011static constexpr audio_session_t OTHER_SESSION_ID = static_cast<audio_session_t>(77);
2012
2013INSTANTIATE_TEST_SUITE_P(
2014 PlaybackReRoutingWithSessionId,
2015 AudioPolicyManagerTestDPPlaybackReRouting,
2016 testing::Values(
2017 // Mix is matched because the session id matches the one specified by the mix rule.
2018 DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID)},
2019 /*expected_match=*/ true)
2020 .withSessionId(TEST_SESSION_ID),
2021 // Mix is not matched because the session id doesn't match the one specified
2022 // by the mix rule.
2023 DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID)},
2024 /*expected_match=*/ false)
2025 .withSessionId(OTHER_SESSION_ID),
2026 // Mix is matched, the session id doesn't match the one specified by rule,
2027 // but there's address specified in the tags which takes precedence.
2028 DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID)},
2029 /*expected_match=*/ true)
2030 .withSessionId(OTHER_SESSION_ID).withTags("addr=remote_submix_media"),
2031 // Mix is matched, both the session id and the usage match ones specified by mix rule.
2032 DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID),
2033 createUsageCriterion(AUDIO_USAGE_MEDIA)},
2034 /*expected_match=*/ true)
2035 .withSessionId(TEST_SESSION_ID).withUsage(AUDIO_USAGE_MEDIA),
2036 // Mix is not matched, the session id matches the one specified by mix rule,
2037 // but usage does not.
2038 DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID),
2039 createUsageCriterion(AUDIO_USAGE_MEDIA)},
2040 /*expected_match=*/ false)
2041 .withSessionId(TEST_SESSION_ID).withUsage(AUDIO_USAGE_GAME),
2042 // Mix is not matched, the usage matches the one specified by mix rule,
2043 // but the session id is excluded.
2044 DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID, /*exclude=*/ true),
2045 createUsageCriterion(AUDIO_USAGE_MEDIA)},
2046 /*expected_match=*/ false)
2047 .withSessionId(TEST_SESSION_ID).withUsage(AUDIO_USAGE_MEDIA)));
jiabinf4eb15a2019-08-28 15:31:47 -07002048
Jan Sebechlebsky8e10cea2023-03-29 11:43:31 +02002049struct DPMmapTestParam {
2050 DPMmapTestParam(int mixRouteFlags, audio_devices_t deviceType, const std::string& deviceAddress)
2051 : mixRouteFlags(mixRouteFlags), deviceType(deviceType), deviceAddress(deviceAddress) {}
2052
2053 int mixRouteFlags;
2054 audio_devices_t deviceType;
2055 std::string deviceAddress;
2056};
2057
2058class AudioPolicyManagerTestMMapPlaybackRerouting
2059 : public AudioPolicyManagerTestDynamicPolicy,
2060 public ::testing::WithParamInterface<DPMmapTestParam> {
2061 protected:
2062 void SetUp() override {
2063 AudioPolicyManagerTestDynamicPolicy::SetUp();
2064 audioConfig = AUDIO_CONFIG_INITIALIZER;
2065 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2066 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2067 audioConfig.sample_rate = k48000SamplingRate;
2068 }
2069
2070 audio_config_t audioConfig;
2071 audio_io_handle_t mOutput;
2072 audio_stream_type_t mStream = AUDIO_STREAM_DEFAULT;
2073 audio_port_handle_t mSelectedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebskyb3d3f622023-07-13 11:09:15 +02002074 audio_port_handle_t mPortId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky8e10cea2023-03-29 11:43:31 +02002075 AudioPolicyInterface::output_type_t mOutputType;
2076 audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER;
2077 bool mIsSpatialized;
2078 bool mIsBitPerfect;
Andy Hung6b137d12024-08-27 22:35:17 +00002079 float mVolume;
Jan Sebechlebsky8e10cea2023-03-29 11:43:31 +02002080};
2081
Jan Sebechlebsky370abec2023-06-15 10:18:30 +02002082TEST_P(AudioPolicyManagerTestMMapPlaybackRerouting, MmapPlaybackStreamMatchingLoopbackDapMixFails) {
Jan Sebechlebsky8e10cea2023-03-29 11:43:31 +02002083 // Add mix matching the test uid.
2084 const int testUid = 12345;
2085 const auto param = GetParam();
jiabin24ff57a2023-11-27 21:06:51 +00002086 ASSERT_NO_FATAL_FAILURE(
2087 addPolicyMixAndStartInputForLoopback(MIX_TYPE_PLAYERS, param.mixRouteFlags,
2088 param.deviceType, param.deviceAddress, audioConfig,
2089 {createUidCriterion(testUid)}));
Jan Sebechlebsky8e10cea2023-03-29 11:43:31 +02002090
jiabin24ff57a2023-11-27 21:06:51 +00002091 // Getting output for matching uid and mmap-ed stream should fail.
2092 audio_output_flags_t outputFlags =
2093 (audio_output_flags_t) (AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Jan Sebechlebsky8e10cea2023-03-29 11:43:31 +02002094 ASSERT_EQ(INVALID_OPERATION,
2095 mManager->getOutputForAttr(&attr, &mOutput, AUDIO_SESSION_NONE, &mStream,
2096 createAttributionSourceState(testUid), &audioConfig,
2097 &outputFlags, &mSelectedDeviceId, &mPortId, {},
Andy Hung6b137d12024-08-27 22:35:17 +00002098 &mOutputType, &mIsSpatialized, &mIsBitPerfect, &mVolume));
Jan Sebechlebsky8e10cea2023-03-29 11:43:31 +02002099}
2100
Jan Sebechlebsky370abec2023-06-15 10:18:30 +02002101TEST_P(AudioPolicyManagerTestMMapPlaybackRerouting,
2102 NonMmapPlaybackStreamMatchingLoopbackDapMixSucceeds) {
Jan Sebechlebsky8e10cea2023-03-29 11:43:31 +02002103 // Add mix matching the test uid.
2104 const int testUid = 12345;
2105 const auto param = GetParam();
jiabin24ff57a2023-11-27 21:06:51 +00002106 ASSERT_NO_FATAL_FAILURE(
2107 addPolicyMixAndStartInputForLoopback(MIX_TYPE_PLAYERS, param.mixRouteFlags,
2108 param.deviceType,param.deviceAddress, audioConfig,
2109 {createUidCriterion(testUid)}));
Jan Sebechlebsky8e10cea2023-03-29 11:43:31 +02002110
jiabin24ff57a2023-11-27 21:06:51 +00002111 // Getting output for matching uid should succeed for non-mmaped stream.
Jan Sebechlebsky8e10cea2023-03-29 11:43:31 +02002112 audio_output_flags_t outputFlags = AUDIO_OUTPUT_FLAG_NONE;
2113 ASSERT_EQ(NO_ERROR,
2114 mManager->getOutputForAttr(&attr, &mOutput, AUDIO_SESSION_NONE, &mStream,
2115 createAttributionSourceState(testUid), &audioConfig,
2116 &outputFlags, &mSelectedDeviceId, &mPortId, {},
Andy Hung6b137d12024-08-27 22:35:17 +00002117 &mOutputType, &mIsSpatialized, &mIsBitPerfect, &mVolume));
Jan Sebechlebsky8e10cea2023-03-29 11:43:31 +02002118}
2119
Jan Sebechlebsky370abec2023-06-15 10:18:30 +02002120TEST_F(AudioPolicyManagerTestMMapPlaybackRerouting,
Jan Sebechlebsky697f5d92023-08-04 11:15:00 +02002121 MmapPlaybackStreamMatchingRenderDapMixSupportingMmapSucceeds) {
jiabin24ff57a2023-11-27 21:06:51 +00002122 const std::string usbAddress = "card=1;device=0";
2123 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2124 AUDIO_DEVICE_OUT_USB_DEVICE, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2125 usbAddress.c_str(), "", AUDIO_FORMAT_DEFAULT));
2126 audio_port_v7 usbDevicePort;
2127 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_USB_DEVICE,
2128 usbAddress, &usbDevicePort));
2129
Jan Sebechlebsky697f5d92023-08-04 11:15:00 +02002130 // Add render-only mix matching the test uid.
Jan Sebechlebsky370abec2023-06-15 10:18:30 +02002131 const int testUid = 12345;
Jan Sebechlebsky697f5d92023-08-04 11:15:00 +02002132 // test_audio_policy_configuration.xml declares mmap-capable mix port
2133 // for AUDIO_DEVICE_OUT_USB_DEVICE.
jiabin24ff57a2023-11-27 21:06:51 +00002134 ASSERT_EQ(NO_ERROR,
2135 addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2136 AUDIO_DEVICE_OUT_USB_DEVICE, /*mixAddress=*/"",
2137 audioConfig, {createUidCriterion(testUid)}));
Jan Sebechlebsky370abec2023-06-15 10:18:30 +02002138
jiabin24ff57a2023-11-27 21:06:51 +00002139 static const audio_output_flags_t mmapDirectFlags =
2140 (audio_output_flags_t) (AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2141 // Getting output for matching uid should succeed for mmaped stream, because matched mix
Jan Sebechlebsky697f5d92023-08-04 11:15:00 +02002142 // redirects to mmap capable device.
jiabin24ff57a2023-11-27 21:06:51 +00002143 audio_output_flags_t outputFlags = mmapDirectFlags;
Jan Sebechlebsky370abec2023-06-15 10:18:30 +02002144 ASSERT_EQ(NO_ERROR,
2145 mManager->getOutputForAttr(&attr, &mOutput, AUDIO_SESSION_NONE, &mStream,
2146 createAttributionSourceState(testUid), &audioConfig,
2147 &outputFlags, &mSelectedDeviceId, &mPortId, {},
Andy Hung6b137d12024-08-27 22:35:17 +00002148 &mOutputType, &mIsSpatialized, &mIsBitPerfect, &mVolume));
jiabin24ff57a2023-11-27 21:06:51 +00002149 ASSERT_EQ(usbDevicePort.id, mSelectedDeviceId);
2150 auto outputDesc = mManager->getOutputs().valueFor(mOutput);
2151 ASSERT_NE(nullptr, outputDesc);
2152 ASSERT_EQ(mmapDirectFlags, outputDesc->getFlags().output);
2153
2154 // After releasing the client, the output is closed. APM should reselect output for the policy
2155 // mix.
2156 mManager->releaseOutput(mPortId);
2157 ASSERT_EQ(nullptr, mManager->getOutputs().valueFor(mOutput));
2158 outputFlags = AUDIO_OUTPUT_FLAG_NONE;
2159 mPortId = AUDIO_PORT_HANDLE_NONE;
2160 ASSERT_EQ(NO_ERROR,
2161 mManager->getOutputForAttr(&attr, &mOutput, AUDIO_SESSION_NONE, &mStream,
2162 createAttributionSourceState(testUid), &audioConfig,
2163 &outputFlags, &mSelectedDeviceId, &mPortId, {},
Andy Hung6b137d12024-08-27 22:35:17 +00002164 &mOutputType, &mIsSpatialized, &mIsBitPerfect, &mVolume));
jiabin24ff57a2023-11-27 21:06:51 +00002165 ASSERT_EQ(usbDevicePort.id, mSelectedDeviceId);
2166 outputDesc = mManager->getOutputs().valueFor(mOutput);
2167 ASSERT_NE(nullptr, outputDesc);
2168 ASSERT_NE(mmapDirectFlags, outputDesc->getFlags().output);
2169
2170 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2171 AUDIO_DEVICE_OUT_USB_DEVICE, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2172 usbAddress.c_str(), "", AUDIO_FORMAT_DEFAULT));
Jan Sebechlebsky370abec2023-06-15 10:18:30 +02002173}
2174
Jan Sebechlebsky697f5d92023-08-04 11:15:00 +02002175TEST_F(AudioPolicyManagerTestMMapPlaybackRerouting,
2176 MmapPlaybackStreamMatchingRenderDapMixNotSupportingMmapFails) {
2177 // Add render-only mix matching the test uid.
2178 const int testUid = 12345;
2179 // Per test_audio_policy_configuration.xml AUDIO_DEVICE_OUT_SPEAKER doesn't support mmap.
jiabin24ff57a2023-11-27 21:06:51 +00002180 ASSERT_EQ(NO_ERROR,
2181 addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2182 AUDIO_DEVICE_OUT_SPEAKER, /*mixAddress=*/"", audioConfig,
2183 {createUidCriterion(testUid)}));
Jan Sebechlebsky697f5d92023-08-04 11:15:00 +02002184
jiabin24ff57a2023-11-27 21:06:51 +00002185 // Getting output for matching uid should fail for mmaped stream, because
Jan Sebechlebsky697f5d92023-08-04 11:15:00 +02002186 // matched mix redirects to device which doesn't support mmap.
jiabin24ff57a2023-11-27 21:06:51 +00002187 audio_output_flags_t outputFlags =
2188 (audio_output_flags_t) (AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Jan Sebechlebsky697f5d92023-08-04 11:15:00 +02002189 ASSERT_EQ(INVALID_OPERATION,
2190 mManager->getOutputForAttr(&attr, &mOutput, AUDIO_SESSION_NONE, &mStream,
2191 createAttributionSourceState(testUid), &audioConfig,
2192 &outputFlags, &mSelectedDeviceId, &mPortId, {},
Andy Hung6b137d12024-08-27 22:35:17 +00002193 &mOutputType, &mIsSpatialized, &mIsBitPerfect, &mVolume));
Jan Sebechlebsky697f5d92023-08-04 11:15:00 +02002194}
2195
Jan Sebechlebsky8e10cea2023-03-29 11:43:31 +02002196INSTANTIATE_TEST_SUITE_P(
2197 MmapPlaybackRerouting, AudioPolicyManagerTestMMapPlaybackRerouting,
2198 testing::Values(DPMmapTestParam(MIX_ROUTE_FLAG_LOOP_BACK, AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2199 /*deviceAddress=*/"remote_submix_media"),
2200 DPMmapTestParam(MIX_ROUTE_FLAG_LOOP_BACK_AND_RENDER,
2201 AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
jiabin1ca6c6f2023-09-22 17:25:59 +00002202 /*deviceAddress=*/"remote_submix_media"),
2203 DPMmapTestParam(MIX_ROUTE_FLAG_RENDER, AUDIO_DEVICE_OUT_SPEAKER,
2204 /*deviceAddress=*/"")));
Jan Sebechlebsky8e10cea2023-03-29 11:43:31 +02002205
jiabinf4eb15a2019-08-28 15:31:47 -07002206class AudioPolicyManagerTestDPMixRecordInjection : public AudioPolicyManagerTestDynamicPolicy,
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002207 public testing::WithParamInterface<DPTestParam> {
jiabinf4eb15a2019-08-28 15:31:47 -07002208protected:
2209 void SetUp() override;
2210 void TearDown() override;
2211
2212 std::unique_ptr<RecordingActivityTracker> mTracker;
jiabin19cdba52020-11-24 11:28:58 -08002213 struct audio_port_v7 mExtractionPort;
jiabinf4eb15a2019-08-28 15:31:47 -07002214 audio_port_handle_t mPortId = AUDIO_PORT_HANDLE_NONE;
2215};
2216
2217void AudioPolicyManagerTestDPMixRecordInjection::SetUp() {
Mikhail Naganovd4c21aa2021-10-05 15:10:16 -07002218 ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTestDynamicPolicy::SetUp());
jiabinf4eb15a2019-08-28 15:31:47 -07002219
2220 mTracker.reset(new RecordingActivityTracker());
2221
2222 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2223 audioConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2224 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
Dean Wheatleyd082f472022-02-04 11:10:48 +11002225 audioConfig.sample_rate = k48000SamplingRate;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002226
2227 DPTestParam param = GetParam();
jiabinf4eb15a2019-08-28 15:31:47 -07002228 status_t ret = addPolicyMix(MIX_TYPE_RECORDERS, MIX_ROUTE_FLAG_LOOP_BACK,
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002229 AUDIO_DEVICE_IN_REMOTE_SUBMIX, mMixAddress, audioConfig, param.mixCriteria);
jiabinf4eb15a2019-08-28 15:31:47 -07002230 ASSERT_EQ(NO_ERROR, ret);
2231
jiabin19cdba52020-11-24 11:28:58 -08002232 struct audio_port_v7 injectionPort;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002233 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2234 mMixAddress, &injectionPort));
jiabinf4eb15a2019-08-28 15:31:47 -07002235
2236 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
2237 audio_usage_t usage = AUDIO_USAGE_VIRTUAL_SOURCE;
Mikhail Naganov55773032020-10-01 15:08:13 -07002238 audio_attributes_t attr =
2239 {AUDIO_CONTENT_TYPE_UNKNOWN, usage, AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
jiabinf4eb15a2019-08-28 15:31:47 -07002240 std::string tags = std::string("addr=") + mMixAddress;
2241 strncpy(attr.tags, tags.c_str(), AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1);
2242 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
Dean Wheatleyd082f472022-02-04 11:10:48 +11002243 k48000SamplingRate, AUDIO_OUTPUT_FLAG_NONE, nullptr /*output*/, &mPortId, attr);
jiabinf4eb15a2019-08-28 15:31:47 -07002244 ASSERT_EQ(NO_ERROR, mManager->startOutput(mPortId));
2245 ASSERT_EQ(injectionPort.id, getDeviceIdFromPatch(mClient->getLastAddedPatch()));
2246
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002247 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SOURCE, AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2248 mMixAddress, &mExtractionPort));
jiabinf4eb15a2019-08-28 15:31:47 -07002249}
2250
2251void AudioPolicyManagerTestDPMixRecordInjection::TearDown() {
2252 mManager->stopOutput(mPortId);
2253 AudioPolicyManagerTestDynamicPolicy::TearDown();
2254}
2255
jiabinf4eb15a2019-08-28 15:31:47 -07002256TEST_P(AudioPolicyManagerTestDPMixRecordInjection, RecordingInjection) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002257 const DPTestParam param = GetParam();
jiabinf4eb15a2019-08-28 15:31:47 -07002258
jiabin7c0205e2019-09-05 10:26:04 -07002259 audio_port_handle_t captureRoutedPortId = AUDIO_PORT_HANDLE_NONE;
jiabinf4eb15a2019-08-28 15:31:47 -07002260 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
François Gaffie6ebbce02023-07-19 13:27:53 +02002261 audio_io_handle_t input = AUDIO_PORT_HANDLE_NONE;
2262 getInputForAttr(param.attributes, &input, param.session, mTracker->getRiid(),
2263 &captureRoutedPortId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
2264 k48000SamplingRate, AUDIO_INPUT_FLAG_NONE, &portId);
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002265 if (param.expected_match) {
jiabinf4eb15a2019-08-28 15:31:47 -07002266 EXPECT_EQ(mExtractionPort.id, captureRoutedPortId);
2267 } else {
2268 EXPECT_NE(mExtractionPort.id, captureRoutedPortId);
2269 }
2270}
2271
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002272const std::vector<AudioMixMatchCriterion> SOURCE_CAM_MIC_VOICE_CRITERIA = {
2273 createCapturePresetCriterion(AUDIO_SOURCE_CAMCORDER),
2274 createCapturePresetCriterion(AUDIO_SOURCE_MIC),
2275 createCapturePresetCriterion(AUDIO_SOURCE_VOICE_COMMUNICATION)
2276};
2277
jiabinf4eb15a2019-08-28 15:31:47 -07002278// No address priority rule for remote recording, address is a "don't care"
2279INSTANTIATE_TEST_CASE_P(
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002280 RecordInjectionSource,
jiabinf4eb15a2019-08-28 15:31:47 -07002281 AudioPolicyManagerTestDPMixRecordInjection,
2282 testing::Values(
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002283 DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ true)
2284 .withSource(AUDIO_SOURCE_CAMCORDER),
2285 DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ true)
2286 .withSource(AUDIO_SOURCE_CAMCORDER)
2287 .withTags("addr=remote_submix_media"),
2288 DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ true)
2289 .withSource(AUDIO_SOURCE_MIC),
2290 DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ true)
2291 .withSource(AUDIO_SOURCE_MIC)
2292 .withTags("addr=remote_submix_media"),
2293 DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ true)
2294 .withSource(AUDIO_SOURCE_VOICE_COMMUNICATION),
2295 DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ true)
2296 .withSource(AUDIO_SOURCE_VOICE_COMMUNICATION)
2297 .withTags("addr=remote_submix_media"),
2298 DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ false)
2299 .withSource(AUDIO_SOURCE_VOICE_RECOGNITION),
2300 DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ false)
2301 .withSource(AUDIO_SOURCE_VOICE_RECOGNITION)
2302 .withTags("addr=remote_submix_media"),
2303 DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ false)
2304 .withSource(AUDIO_SOURCE_HOTWORD),
2305 DPTestParam(SOURCE_CAM_MIC_VOICE_CRITERIA, /*expected_match=*/ false)
2306 .withSource(AUDIO_SOURCE_HOTWORD)
2307 .withTags("addr=remote_submix_media")));
jiabinf4eb15a2019-08-28 15:31:47 -07002308
jiabinf4eb15a2019-08-28 15:31:47 -07002309INSTANTIATE_TEST_CASE_P(
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002310 RecordInjectionWithSessionId,
jiabinf4eb15a2019-08-28 15:31:47 -07002311 AudioPolicyManagerTestDPMixRecordInjection,
2312 testing::Values(
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002313 // Mix is matched because the session id matches the one specified by the mix rule.
2314 DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID)},
2315 /*expected_match=*/ true)
2316 .withSessionId(TEST_SESSION_ID),
2317 // Mix is not matched because the session id doesn't match the one specified
2318 // by the mix rule.
2319 DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID)},
2320 /*expected_match=*/ false)
2321 .withSessionId(OTHER_SESSION_ID),
2322 // Mix is not matched, the session id doesn't match the one specified by rule,
2323 // but tand address specified in the tags is ignored for recorder mix.
2324 DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID)},
2325 /*expected_match=*/ false)
2326 .withSessionId(OTHER_SESSION_ID).withTags("addr=remote_submix_media"),
2327 // Mix is matched, both the session id and the source match ones specified by mix rule
2328 DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID),
2329 createCapturePresetCriterion(AUDIO_SOURCE_CAMCORDER)},
2330 /*expected_match=*/ true)
2331 .withSessionId(TEST_SESSION_ID).withSource(AUDIO_SOURCE_CAMCORDER),
2332 // Mix is not matched, the session id matches the one specified by mix rule,
2333 // but source does not.
2334 DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID),
2335 createCapturePresetCriterion(AUDIO_SOURCE_CAMCORDER)},
2336 /*expected_match=*/ false)
2337 .withSessionId(TEST_SESSION_ID).withSource(AUDIO_SOURCE_MIC),
2338 // Mix is not matched, the source matches the one specified by mix rule,
2339 // but the session id is excluded.
2340 DPTestParam(/*mixCriteria=*/ {createSessionIdCriterion(TEST_SESSION_ID,
2341 /*exclude=*/ true),
2342 createCapturePresetCriterion(AUDIO_SOURCE_MIC)},
2343 /*expected_match=*/ false)
2344 .withSessionId(TEST_SESSION_ID).withSource(AUDIO_SOURCE_MIC)));
jiabin43848a52019-09-05 14:07:25 -07002345
2346using DeviceConnectionTestParams =
2347 std::tuple<audio_devices_t /*type*/, std::string /*name*/, std::string /*address*/>;
2348
2349class AudioPolicyManagerTestDeviceConnection : public AudioPolicyManagerTestWithConfigurationFile,
2350 public testing::WithParamInterface<DeviceConnectionTestParams> {
2351};
2352
2353TEST_F(AudioPolicyManagerTestDeviceConnection, InitSuccess) {
2354 // SetUp must finish with no assertions.
2355}
2356
2357TEST_F(AudioPolicyManagerTestDeviceConnection, Dump) {
2358 dumpToLog();
2359}
2360
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002361TEST_F(AudioPolicyManagerTestDeviceConnection, RoutingUpdate) {
2362 mClient->resetRoutingUpdatedCounter();
2363 // Connecting a valid output device with valid parameters should trigger a routing update
2364 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2365 AUDIO_DEVICE_OUT_BLUETOOTH_SCO, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Mikhail Naganovb1ddbb02023-03-15 17:06:59 -07002366 "00:11:22:33:44:55", "b", AUDIO_FORMAT_DEFAULT));
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002367 ASSERT_EQ(1, mClient->getRoutingUpdatedCounter());
2368
2369 // Disconnecting a connected device should succeed and trigger a routing update
2370 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2371 AUDIO_DEVICE_OUT_BLUETOOTH_SCO, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovb1ddbb02023-03-15 17:06:59 -07002372 "00:11:22:33:44:55", "b", AUDIO_FORMAT_DEFAULT));
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002373 ASSERT_EQ(2, mClient->getRoutingUpdatedCounter());
2374
2375 // Disconnecting a disconnected device should fail and not trigger a routing update
2376 ASSERT_EQ(INVALID_OPERATION, mManager->setDeviceConnectionState(
2377 AUDIO_DEVICE_OUT_BLUETOOTH_SCO, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovb1ddbb02023-03-15 17:06:59 -07002378 "00:11:22:33:44:55", "b", AUDIO_FORMAT_DEFAULT));
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002379 ASSERT_EQ(2, mClient->getRoutingUpdatedCounter());
2380
2381 // Changing force use should trigger an update
2382 auto config = mManager->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA);
2383 auto newConfig = config == AUDIO_POLICY_FORCE_BT_A2DP ?
2384 AUDIO_POLICY_FORCE_NONE : AUDIO_POLICY_FORCE_BT_A2DP;
2385 mManager->setForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA, newConfig);
2386 ASSERT_EQ(3, mClient->getRoutingUpdatedCounter());
2387}
2388
jiabin43848a52019-09-05 14:07:25 -07002389TEST_P(AudioPolicyManagerTestDeviceConnection, SetDeviceConnectionState) {
2390 const audio_devices_t type = std::get<0>(GetParam());
2391 const std::string name = std::get<1>(GetParam());
2392 const std::string address = std::get<2>(GetParam());
2393
2394 if (type == AUDIO_DEVICE_OUT_HDMI) {
2395 // Set device connection state failed due to no device descriptor found
2396 // For HDMI case, it is easier to simulate device descriptor not found error
Mikhail Naganov83caee02021-10-05 15:52:01 -07002397 // by using an encoded format which isn't listed in the 'encodedFormats'
2398 // attribute for this devicePort.
jiabin43848a52019-09-05 14:07:25 -07002399 ASSERT_EQ(INVALID_OPERATION, mManager->setDeviceConnectionState(
2400 type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2401 address.c_str(), name.c_str(), AUDIO_FORMAT_MAT_2_1));
2402 }
2403 // Connect with valid parameters should succeed
2404 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2405 type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2406 address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
2407 // Try to connect with the same device again should fail
2408 ASSERT_EQ(INVALID_OPERATION, mManager->setDeviceConnectionState(
2409 type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2410 address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
2411 // Disconnect the connected device should succeed
2412 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2413 type, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2414 address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
2415 // Disconnect device that is not connected should fail
2416 ASSERT_EQ(INVALID_OPERATION, mManager->setDeviceConnectionState(
2417 type, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2418 address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
2419 // Try to set device connection state with a invalid connection state should fail
2420 ASSERT_EQ(BAD_VALUE, mManager->setDeviceConnectionState(
2421 type, AUDIO_POLICY_DEVICE_STATE_CNT,
2422 "", "", AUDIO_FORMAT_DEFAULT));
2423}
2424
2425TEST_P(AudioPolicyManagerTestDeviceConnection, ExplicitlyRoutingAfterConnection) {
2426 const audio_devices_t type = std::get<0>(GetParam());
2427 const std::string name = std::get<1>(GetParam());
2428 const std::string address = std::get<2>(GetParam());
2429
2430 // Connect device to do explicitly routing test
2431 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2432 type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2433 address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
2434
jiabin19cdba52020-11-24 11:28:58 -08002435 audio_port_v7 devicePort;
jiabin43848a52019-09-05 14:07:25 -07002436 const audio_port_role_t role = audio_is_output_device(type)
2437 ? AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002438 ASSERT_TRUE(findDevicePort(role, type, address, &devicePort));
jiabin43848a52019-09-05 14:07:25 -07002439
2440 audio_port_handle_t routedPortId = devicePort.id;
jiabin43848a52019-09-05 14:07:25 -07002441 // Try start input or output according to the device type
2442 if (audio_is_output_devices(type)) {
2443 getOutputForAttr(&routedPortId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
Dean Wheatleyd082f472022-02-04 11:10:48 +11002444 k48000SamplingRate, AUDIO_OUTPUT_FLAG_NONE);
jiabin43848a52019-09-05 14:07:25 -07002445 } else if (audio_is_input_device(type)) {
2446 RecordingActivityTracker tracker;
François Gaffie6ebbce02023-07-19 13:27:53 +02002447 audio_io_handle_t input = AUDIO_PORT_HANDLE_NONE;
2448 getInputForAttr({}, &input, AUDIO_SESSION_NONE, tracker.getRiid(), &routedPortId,
2449 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO, k48000SamplingRate,
2450 AUDIO_INPUT_FLAG_NONE);
jiabin43848a52019-09-05 14:07:25 -07002451 }
2452 ASSERT_EQ(devicePort.id, routedPortId);
2453
2454 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2455 type, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2456 address.c_str(), name.c_str(), AUDIO_FORMAT_DEFAULT));
2457}
2458
Mikhail Naganovddc5f312022-06-11 00:47:52 +00002459android::media::audio::common::ExtraAudioDescriptor make_ExtraAudioDescriptor(
2460 android::media::audio::common::AudioStandard audioStandard,
2461 android::media::audio::common::AudioEncapsulationType audioEncapsulationType) {
2462 android::media::audio::common::ExtraAudioDescriptor result;
2463 result.standard = audioStandard;
2464 result.audioDescriptor = {0xb4, 0xaf, 0x98, 0x1a};
2465 result.encapsulationType = audioEncapsulationType;
2466 return result;
2467}
2468
2469TEST_P(AudioPolicyManagerTestDeviceConnection, PassingExtraAudioDescriptors) {
2470 const audio_devices_t type = std::get<0>(GetParam());
2471 if (!audio_device_is_digital(type)) {
2472 // EADs are used only for HDMI devices.
2473 GTEST_SKIP() << "Not a digital device type: " << audio_device_to_string(type);
2474 }
2475 const std::string name = std::get<1>(GetParam());
2476 const std::string address = std::get<2>(GetParam());
Atneya Nair638a6e42022-12-18 16:45:15 -08002477 android::media::AudioPortFw audioPort;
Mikhail Naganovddc5f312022-06-11 00:47:52 +00002478 ASSERT_EQ(NO_ERROR,
2479 mManager->deviceToAudioPort(type, address.c_str(), name.c_str(), &audioPort));
2480 android::media::audio::common::AudioPort& port = audioPort.hal;
2481 port.extraAudioDescriptors.push_back(make_ExtraAudioDescriptor(
2482 android::media::audio::common::AudioStandard::EDID,
2483 android::media::audio::common::AudioEncapsulationType::IEC61937));
2484 const size_t lastConnectedDevicePortCount = mClient->getConnectedDevicePortCount();
2485 const size_t lastDisconnectedDevicePortCount = mClient->getDisconnectedDevicePortCount();
2486 EXPECT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
2487 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, port, AUDIO_FORMAT_DEFAULT));
2488 EXPECT_EQ(lastConnectedDevicePortCount + 1, mClient->getConnectedDevicePortCount());
2489 EXPECT_EQ(lastDisconnectedDevicePortCount, mClient->getDisconnectedDevicePortCount());
2490 const audio_port_v7* devicePort = mClient->getLastConnectedDevicePort();
2491 EXPECT_EQ(port.extraAudioDescriptors.size(), devicePort->num_extra_audio_descriptors);
2492 EXPECT_EQ(AUDIO_STANDARD_EDID, devicePort->extra_audio_descriptors[0].standard);
2493 EXPECT_EQ(AUDIO_ENCAPSULATION_TYPE_IEC61937,
2494 devicePort->extra_audio_descriptors[0].encapsulation_type);
2495 EXPECT_NE(0, devicePort->extra_audio_descriptors[0].descriptor[0]);
2496}
2497
jiabin43848a52019-09-05 14:07:25 -07002498INSTANTIATE_TEST_CASE_P(
2499 DeviceConnectionState,
2500 AudioPolicyManagerTestDeviceConnection,
2501 testing::Values(
2502 DeviceConnectionTestParams({AUDIO_DEVICE_IN_HDMI, "test_in_hdmi",
2503 "audio_policy_test_in_hdmi"}),
2504 DeviceConnectionTestParams({AUDIO_DEVICE_OUT_HDMI, "test_out_hdmi",
2505 "audio_policy_test_out_hdmi"}),
2506 DeviceConnectionTestParams({AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "bt_hfp_in",
Mikhail Naganovb1ddbb02023-03-15 17:06:59 -07002507 "00:11:22:33:44:55"}),
jiabin43848a52019-09-05 14:07:25 -07002508 DeviceConnectionTestParams({AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "bt_hfp_out",
Mikhail Naganovb1ddbb02023-03-15 17:06:59 -07002509 "00:11:22:33:44:55"})
jiabin43848a52019-09-05 14:07:25 -07002510 )
2511 );
Mikhail Naganov0756bbf2019-09-06 13:53:26 -07002512
Mikhail Naganovf88c2f32024-04-16 15:01:13 -07002513namespace {
2514
2515class AudioPolicyManagerTestClientOpenFails : public AudioPolicyManagerTestClient {
2516 public:
2517 status_t openOutput(audio_module_handle_t module,
2518 audio_io_handle_t *output,
2519 audio_config_t * halConfig,
2520 audio_config_base_t * mixerConfig,
2521 const sp<DeviceDescriptorBase>& device,
2522 uint32_t * latencyMs,
Haofan Wangf6e304f2024-07-09 23:06:58 -07002523 audio_output_flags_t flags,
2524 audio_attributes_t attributes) override {
Mikhail Naganovf88c2f32024-04-16 15:01:13 -07002525 return mSimulateFailure ? BAD_VALUE :
2526 AudioPolicyManagerTestClient::openOutput(
Haofan Wangf6e304f2024-07-09 23:06:58 -07002527 module, output, halConfig, mixerConfig, device, latencyMs, flags,
2528 attributes);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -07002529 }
2530
2531 status_t openInput(audio_module_handle_t module,
2532 audio_io_handle_t *input,
2533 audio_config_t * config,
2534 audio_devices_t * device,
2535 const String8 & address,
2536 audio_source_t source,
2537 audio_input_flags_t flags) override {
2538 return mSimulateFailure ? BAD_VALUE :
2539 AudioPolicyManagerTestClient::openInput(
2540 module, input, config, device, address, source, flags);
2541 }
2542
2543 void setSimulateFailure(bool simulateFailure) { mSimulateFailure = simulateFailure; }
2544
2545 private:
2546 bool mSimulateFailure = false;
2547};
2548
2549} // namespace
2550
2551using DeviceConnectionWithFormatTestParams =
2552 std::tuple<audio_devices_t /*type*/, std::string /*name*/, std::string /*address*/,
2553 audio_format_t /*format*/>;
2554
2555class AudioPolicyManagerTestDeviceConnectionFailed :
2556 public AudioPolicyManagerTestWithConfigurationFile,
2557 public testing::WithParamInterface<DeviceConnectionWithFormatTestParams> {
2558 protected:
2559 std::string getConfigFile() override { return sBluetoothConfig; }
2560 AudioPolicyManagerTestClient* getClient() override {
2561 mFullClient = new AudioPolicyManagerTestClientOpenFails;
2562 return mFullClient;
2563 }
2564 void setSimulateOpenFailure(bool simulateFailure) {
2565 mFullClient->setSimulateFailure(simulateFailure); }
2566
2567 static const std::string sBluetoothConfig;
2568
2569 private:
2570 AudioPolicyManagerTestClientOpenFails* mFullClient;
2571};
2572
2573const std::string AudioPolicyManagerTestDeviceConnectionFailed::sBluetoothConfig =
2574 AudioPolicyManagerTestDeviceConnectionFailed::sExecutableDir +
2575 "test_audio_policy_configuration_bluetooth.xml";
2576
2577TEST_P(AudioPolicyManagerTestDeviceConnectionFailed, SetDeviceConnectedStateHasAddress) {
2578 const audio_devices_t type = std::get<0>(GetParam());
2579 const std::string name = std::get<1>(GetParam());
2580 const std::string address = std::get<2>(GetParam());
2581 const audio_format_t format = std::get<3>(GetParam());
2582
2583 EXPECT_EQ(0, mClient->getConnectedDevicePortCount());
2584 EXPECT_EQ(0, mClient->getDisconnectedDevicePortCount());
2585
2586 setSimulateOpenFailure(true);
2587 ASSERT_EQ(INVALID_OPERATION, mManager->setDeviceConnectionState(
2588 type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2589 address.c_str(), name.c_str(), format));
2590
2591 // Since the failure happens when opening input/output, the device must be connected
2592 // first and then disconnected.
2593 EXPECT_EQ(1, mClient->getConnectedDevicePortCount());
2594 EXPECT_EQ(1, mClient->getDisconnectedDevicePortCount());
2595
2596 if (mClient->getConnectedDevicePortCount() > 0) {
2597 auto port = mClient->getLastConnectedDevicePort();
2598 EXPECT_EQ(type, port->ext.device.type);
2599 EXPECT_EQ(0, strncmp(port->ext.device.address, address.c_str(),
2600 AUDIO_DEVICE_MAX_ADDRESS_LEN)) << "\"" << port->ext.device.address << "\"";
2601 }
2602 if (mClient->getDisconnectedDevicePortCount() > 0) {
2603 auto port = mClient->getLastDisconnectedDevicePort();
2604 EXPECT_EQ(type, port->ext.device.type);
2605 EXPECT_EQ(0, strncmp(port->ext.device.address, address.c_str(),
2606 AUDIO_DEVICE_MAX_ADDRESS_LEN)) << "\"" << port->ext.device.address << "\"";
2607 }
2608}
2609
2610INSTANTIATE_TEST_CASE_P(
2611 DeviceConnectionFailure,
2612 AudioPolicyManagerTestDeviceConnectionFailed,
2613 testing::Values(
2614 DeviceConnectionWithFormatTestParams({AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET,
2615 "bt_hfp_in", "00:11:22:33:44:55", AUDIO_FORMAT_DEFAULT}),
2616 DeviceConnectionWithFormatTestParams({AUDIO_DEVICE_OUT_BLUETOOTH_SCO,
2617 "bt_hfp_out", "00:11:22:33:44:55", AUDIO_FORMAT_DEFAULT}),
2618 DeviceConnectionWithFormatTestParams({AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
2619 "bt_a2dp_out", "00:11:22:33:44:55", AUDIO_FORMAT_DEFAULT}),
2620 DeviceConnectionWithFormatTestParams({AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
2621 "bt_a2dp_out", "00:11:22:33:44:66", AUDIO_FORMAT_LDAC})
2622 )
2623 );
2624
Dean Wheatleyd082f472022-02-04 11:10:48 +11002625class AudioPolicyManagerCarTest : public AudioPolicyManagerTestDynamicPolicy {
2626protected:
2627 std::string getConfigFile() override { return sCarConfig; }
2628
2629 static const std::string sCarConfig;
Oscar Azucena873d10f2023-01-12 18:34:42 -08002630 static const std::string sCarBusMediaOutput;
2631 static const std::string sCarBusNavigationOutput;
Oscar Azucena4f49ef62023-01-25 23:32:13 -08002632 static const std::string sCarRearZoneOneOutput;
2633 static const std::string sCarRearZoneTwoOutput;
jiabin24ff57a2023-11-27 21:06:51 +00002634 static const std::string sCarBusMmapOutput;
Dean Wheatleyd082f472022-02-04 11:10:48 +11002635};
2636
2637const std::string AudioPolicyManagerCarTest::sCarConfig =
2638 AudioPolicyManagerCarTest::sExecutableDir + "test_car_ap_atmos_offload_configuration.xml";
2639
Oscar Azucena873d10f2023-01-12 18:34:42 -08002640const std::string AudioPolicyManagerCarTest::sCarBusMediaOutput = "bus0_media_out";
2641
2642const std::string AudioPolicyManagerCarTest::sCarBusNavigationOutput = "bus1_navigation_out";
2643
Oscar Azucena4f49ef62023-01-25 23:32:13 -08002644const std::string AudioPolicyManagerCarTest::sCarRearZoneOneOutput = "bus100_audio_zone_1";
2645
2646const std::string AudioPolicyManagerCarTest::sCarRearZoneTwoOutput = "bus200_audio_zone_2";
2647
jiabin24ff57a2023-11-27 21:06:51 +00002648const std::string AudioPolicyManagerCarTest::sCarBusMmapOutput = "bus8_mmap_out";
2649
Dean Wheatleyd082f472022-02-04 11:10:48 +11002650TEST_F(AudioPolicyManagerCarTest, InitSuccess) {
2651 // SetUp must finish with no assertions.
2652}
2653
2654TEST_F(AudioPolicyManagerCarTest, Dump) {
2655 dumpToLog();
2656}
2657
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11002658TEST_F(AudioPolicyManagerCarTest, GetOutputForAttrAtmosOutputAfterRegisteringPolicyMix) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11002659 status_t ret;
2660 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
Dean Wheatleyd082f472022-02-04 11:10:48 +11002661 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08002662 AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig);
Dean Wheatleyd082f472022-02-04 11:10:48 +11002663 ASSERT_EQ(NO_ERROR, ret);
2664
2665 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
2666 audio_io_handle_t output;
2667 audio_port_handle_t portId;
2668 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_E_AC3_JOC, AUDIO_CHANNEL_OUT_5POINT1,
2669 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId);
2670 ASSERT_NE(AUDIO_PORT_HANDLE_NONE, selectedDeviceId);
2671 sp<SwAudioOutputDescriptor> outDesc = mManager->getOutputs().valueFor(output);
2672 ASSERT_NE(nullptr, outDesc.get());
2673 ASSERT_EQ(AUDIO_FORMAT_E_AC3_JOC, outDesc->getFormat());
2674 ASSERT_EQ(AUDIO_CHANNEL_OUT_5POINT1, outDesc->getChannelMask());
2675 ASSERT_EQ(k48000SamplingRate, outDesc->getSamplingRate());
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11002676
2677 selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
2678 output = AUDIO_IO_HANDLE_NONE;
2679 portId = AUDIO_PORT_HANDLE_NONE;
2680 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_7POINT1POINT4,
2681 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId);
2682 ASSERT_NE(AUDIO_PORT_HANDLE_NONE, selectedDeviceId);
2683 outDesc = mManager->getOutputs().valueFor(output);
2684 ASSERT_NE(nullptr, outDesc.get());
2685 ASSERT_EQ(AUDIO_FORMAT_PCM_16_BIT, outDesc->getFormat());
2686 ASSERT_EQ(AUDIO_CHANNEL_OUT_7POINT1POINT4, outDesc->getChannelMask());
2687 ASSERT_EQ(k48000SamplingRate, outDesc->getSamplingRate());
Dean Wheatleyd082f472022-02-04 11:10:48 +11002688}
2689
Oscar Azucena873d10f2023-01-12 18:34:42 -08002690TEST_F(AudioPolicyManagerCarTest, GetOutputForAttrAfterRegisteringPolicyMix) {
2691 status_t ret;
2692 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2693 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2694 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2695 audioConfig.sample_rate = k48000SamplingRate;
2696 std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2697 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2698 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2699 AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2700 ASSERT_EQ(NO_ERROR, ret);
2701 std::vector<AudioMixMatchCriterion> navMatchCriteria = {
2702 createUsageCriterion(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
2703 /*exclude=*/ false)};
2704 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2705 AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput, audioConfig, navMatchCriteria);
2706 ASSERT_EQ(NO_ERROR, ret);
2707 audio_port_v7 mediaDevicePort;
2708 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2709 sCarBusMediaOutput, &mediaDevicePort));
2710 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
2711 audio_io_handle_t output;
2712 audio_port_handle_t portId;
2713 const audio_attributes_t mediaAttribute = {
2714 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
2715 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2716
2717 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2718 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, mediaAttribute);
2719
2720 ASSERT_EQ(mediaDevicePort.id, selectedDeviceId);
2721}
2722
2723TEST_F(AudioPolicyManagerCarTest, GetOutputForAttrWithSelectedOutputAfterRegisteringPolicyMix) {
2724 status_t ret;
2725 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2726 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2727 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2728 audioConfig.sample_rate = k48000SamplingRate;
2729 std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2730 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2731 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2732 AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2733 ASSERT_EQ(NO_ERROR, ret);
2734 std::vector<AudioMixMatchCriterion> navMatchCriteria = {
2735 createUsageCriterion(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
2736 /*exclude=*/ false)};
2737 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2738 AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput, audioConfig, navMatchCriteria);
2739 ASSERT_EQ(NO_ERROR, ret);
2740 audio_port_v7 navDevicePort;
2741 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2742 sCarBusNavigationOutput, &navDevicePort));
2743 audio_port_handle_t selectedDeviceId = navDevicePort.id;
2744 audio_io_handle_t output;
2745 audio_port_handle_t portId;
2746 const audio_attributes_t mediaAttribute = {
2747 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
2748 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2749
2750 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2751 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, mediaAttribute);
2752
2753 ASSERT_EQ(navDevicePort.id, selectedDeviceId);
2754}
2755
2756TEST_F(AudioPolicyManagerCarTest, GetOutputForAttrWithSelectedOutputAfterUserAffinities) {
2757 status_t ret;
2758 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2759 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2760 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2761 audioConfig.sample_rate = k48000SamplingRate;
2762 std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2763 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2764 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2765 AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2766 ASSERT_EQ(NO_ERROR, ret);
2767 std::vector<AudioMixMatchCriterion> navMatchCriteria = {
2768 createUsageCriterion(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
2769 /*exclude=*/ false)};
2770 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2771 AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput, audioConfig, navMatchCriteria);
2772 ASSERT_EQ(NO_ERROR, ret);
2773 const AudioDeviceTypeAddr mediaOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput);
2774 const AudioDeviceTypeAddrVector outputDevices = {mediaOutputDevice};
Oscar Azucena4f49ef62023-01-25 23:32:13 -08002775 mManager->setUserIdDeviceAffinities(/* userId */ 0, outputDevices);
Oscar Azucena873d10f2023-01-12 18:34:42 -08002776 audio_port_v7 navDevicePort;
2777 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2778 sCarBusNavigationOutput, &navDevicePort));
2779 audio_port_handle_t selectedDeviceId = navDevicePort.id;
2780 audio_io_handle_t output;
2781 audio_port_handle_t portId;
2782 const audio_attributes_t mediaAttribute = {
2783 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
2784 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2785
2786 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2787 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, mediaAttribute);
2788
2789 ASSERT_NE(navDevicePort.id, selectedDeviceId);
2790}
2791
2792TEST_F(AudioPolicyManagerCarTest, GetOutputForAttrWithExcludeUserIdCriteria) {
2793 status_t ret;
2794 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2795 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2796 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2797 audioConfig.sample_rate = k48000SamplingRate;
2798 std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2799 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2800 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2801 AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2802 ASSERT_EQ(NO_ERROR, ret);
2803 std::vector<AudioMixMatchCriterion> navMatchCriteria = {
2804 createUsageCriterion(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
2805 /*exclude=*/ false),
2806 createUserIdCriterion(/* userId */ 0, /* exclude */ true)};
2807 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2808 AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput, audioConfig, navMatchCriteria);
2809 ASSERT_EQ(NO_ERROR, ret);
2810 audio_port_v7 navDevicePort;
2811 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2812 sCarBusNavigationOutput, &navDevicePort));
2813 audio_io_handle_t output;
2814 audio_port_handle_t portId;
2815 const audio_attributes_t navigationAttribute = {
2816 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
2817 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2818 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
2819
2820 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2821 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, navigationAttribute);
2822
2823 ASSERT_NE(navDevicePort.id, selectedDeviceId);
2824}
2825
2826TEST_F(AudioPolicyManagerCarTest, GetOutputForAttrWithSelectedOutputExcludeUserIdCriteria) {
2827 status_t ret;
2828 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2829 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2830 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2831 audioConfig.sample_rate = k48000SamplingRate;
2832 std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2833 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2834 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2835 AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2836 ASSERT_EQ(NO_ERROR, ret);
2837 std::vector<AudioMixMatchCriterion> navMatchCriteria = {
2838 createUsageCriterion(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
2839 /*exclude=*/ false),
2840 createUserIdCriterion(0 /* userId */, /* exclude */ true)};
2841 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2842 AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput, audioConfig, navMatchCriteria);
2843 ASSERT_EQ(NO_ERROR, ret);
2844 audio_port_v7 navDevicePort;
2845 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2846 sCarBusNavigationOutput, &navDevicePort));
2847 audio_port_handle_t selectedDeviceId = navDevicePort.id;
2848 audio_io_handle_t output;
2849 audio_port_handle_t portId;
2850 const audio_attributes_t mediaAttribute = {
2851 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
2852 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2853
2854 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2855 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, mediaAttribute);
2856
2857 ASSERT_EQ(navDevicePort.id, selectedDeviceId);
2858}
2859
2860TEST_F(AudioPolicyManagerCarTest,
2861 GetOutputForAttrWithMatchingMixAndSelectedOutputAfterUserAffinities) {
2862 status_t ret;
2863 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2864 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2865 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2866 audioConfig.sample_rate = k48000SamplingRate;
2867 std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2868 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2869 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2870 AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2871 ASSERT_EQ(NO_ERROR, ret);
2872 std::vector<AudioMixMatchCriterion> navMatchCriteria = {
2873 createUsageCriterion(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
2874 /*exclude=*/ false)};
2875 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2876 AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput, audioConfig, navMatchCriteria);
2877 ASSERT_EQ(NO_ERROR, ret);
2878 const AudioDeviceTypeAddr mediaOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput);
2879 const AudioDeviceTypeAddr navOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput);
2880 const AudioDeviceTypeAddrVector outputDevices = {mediaOutputDevice, navOutputDevice};
Oscar Azucena4f49ef62023-01-25 23:32:13 -08002881 mManager->setUserIdDeviceAffinities(/* userId */ 0, outputDevices);
Oscar Azucena873d10f2023-01-12 18:34:42 -08002882 audio_port_v7 navDevicePort;
2883 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2884 sCarBusNavigationOutput, &navDevicePort));
2885 audio_port_handle_t selectedDeviceId = navDevicePort.id;
2886 audio_io_handle_t output;
2887 audio_port_handle_t portId;
2888 const audio_attributes_t mediaAttribute = {
2889 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
2890 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2891
2892 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2893 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, mediaAttribute);
2894
2895 ASSERT_EQ(navDevicePort.id, selectedDeviceId);
2896}
2897
2898TEST_F(AudioPolicyManagerCarTest,
2899 GetOutputForAttrWithNoMatchingMaxAndSelectedOutputAfterUserAffinities) {
2900 status_t ret;
2901 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2902 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2903 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2904 audioConfig.sample_rate = k48000SamplingRate;
2905 std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2906 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2907 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2908 AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2909 ASSERT_EQ(NO_ERROR, ret);
2910 std::vector<AudioMixMatchCriterion> navMatchCriteria = {
2911 createUsageCriterion(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
2912 /*exclude=*/ false)};
2913 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2914 AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput, audioConfig, navMatchCriteria);
2915 ASSERT_EQ(NO_ERROR, ret);
2916 const AudioDeviceTypeAddr mediaOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput);
2917 const AudioDeviceTypeAddr navOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput);
2918 const AudioDeviceTypeAddrVector outputDevices = {mediaOutputDevice, navOutputDevice};
Oscar Azucena4f49ef62023-01-25 23:32:13 -08002919 mManager->setUserIdDeviceAffinities(/* userId */ 0, outputDevices);
Oscar Azucena873d10f2023-01-12 18:34:42 -08002920 audio_port_v7 navDevicePort;
2921 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2922 sCarBusNavigationOutput, &navDevicePort));
2923 audio_port_handle_t selectedDeviceId = navDevicePort.id;
2924 audio_io_handle_t output;
2925 audio_port_handle_t portId;
2926 const audio_attributes_t alarmAttribute = {
2927 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_ALARM,
2928 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2929
2930 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2931 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, alarmAttribute);
2932
2933 ASSERT_EQ(navDevicePort.id, selectedDeviceId);
2934}
2935
Oscar Azucena4f49ef62023-01-25 23:32:13 -08002936TEST_F(AudioPolicyManagerCarTest,
2937 GetOutputForAttrWithMatMixAfterUserAffinitiesForOneUser) {
2938 status_t ret;
2939 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2940 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2941 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2942 audioConfig.sample_rate = k48000SamplingRate;
2943 std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2944 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2945 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2946 AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2947 ASSERT_EQ(NO_ERROR, ret);
2948 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2949 AUDIO_DEVICE_OUT_BUS, sCarRearZoneOneOutput, audioConfig, mediaMatchCriteria);
2950 ASSERT_EQ(NO_ERROR, ret);
2951 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2952 AUDIO_DEVICE_OUT_BUS, sCarRearZoneTwoOutput, audioConfig, mediaMatchCriteria);
2953 ASSERT_EQ(NO_ERROR, ret);
2954 const AudioDeviceTypeAddr mediaOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput);
2955 const AudioDeviceTypeAddrVector primaryZoneDevices = {mediaOutputDevice};
2956 mManager->setUserIdDeviceAffinities(/* userId */ 0, primaryZoneDevices);
2957 audio_port_v7 primaryZoneDevicePort;
2958 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
2959 sCarBusMediaOutput, &primaryZoneDevicePort));
2960 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
2961 audio_io_handle_t output;
2962 audio_port_handle_t portId;
2963 const audio_attributes_t mediaAttribute = {
2964 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
2965 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
2966 uid_t user11AppUid = multiuser_get_uid(/* user_id */ 11, /* app_id */ 12345);
2967
2968 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
2969 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, mediaAttribute,
2970 AUDIO_SESSION_NONE, user11AppUid);
2971
2972 ASSERT_EQ(primaryZoneDevicePort.id, selectedDeviceId);
2973}
2974
2975TEST_F(AudioPolicyManagerCarTest,
2976 GetOutputForAttrWithMatMixAfterUserAffinitiesForTwoUsers) {
2977 status_t ret;
2978 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
2979 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2980 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
2981 audioConfig.sample_rate = k48000SamplingRate;
2982 std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
2983 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
2984 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2985 AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
2986 ASSERT_EQ(NO_ERROR, ret);
2987 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2988 AUDIO_DEVICE_OUT_BUS, sCarRearZoneOneOutput, audioConfig, mediaMatchCriteria);
2989 ASSERT_EQ(NO_ERROR, ret);
2990 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
2991 AUDIO_DEVICE_OUT_BUS, sCarRearZoneTwoOutput, audioConfig, mediaMatchCriteria);
2992 ASSERT_EQ(NO_ERROR, ret);
2993 const AudioDeviceTypeAddr mediaOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput);
2994 const AudioDeviceTypeAddrVector primaryZoneDevices = {mediaOutputDevice};
2995 mManager->setUserIdDeviceAffinities(/* userId */ 0, primaryZoneDevices);
2996 const AudioDeviceTypeAddr secondaryOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarRearZoneOneOutput);
2997 const AudioDeviceTypeAddrVector secondaryZoneDevices = {secondaryOutputDevice};
2998 mManager->setUserIdDeviceAffinities(/* userId */ 11, secondaryZoneDevices);
2999 audio_port_v7 secondaryZoneDevicePort;
3000 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
3001 sCarRearZoneOneOutput, &secondaryZoneDevicePort));
3002 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3003 audio_io_handle_t output;
3004 audio_port_handle_t portId;
3005 const audio_attributes_t mediaAttribute = {
3006 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
3007 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
3008 uid_t user11AppUid = multiuser_get_uid(/* user_id */ 11, /* app_id */ 12345);
3009
3010 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
3011 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, mediaAttribute,
3012 AUDIO_SESSION_NONE, user11AppUid);
3013
3014 ASSERT_EQ(secondaryZoneDevicePort.id, selectedDeviceId);
3015}
3016
3017TEST_F(AudioPolicyManagerCarTest,
3018 GetOutputForAttrWithMatMixAfterUserAffinitiesForThreeUsers) {
3019 status_t ret;
3020 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
3021 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3022 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
3023 audioConfig.sample_rate = k48000SamplingRate;
3024 std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
3025 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
3026 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
3027 AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
3028 ASSERT_EQ(NO_ERROR, ret);
3029 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
3030 AUDIO_DEVICE_OUT_BUS, sCarRearZoneOneOutput, audioConfig, mediaMatchCriteria);
3031 ASSERT_EQ(NO_ERROR, ret);
3032 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
3033 AUDIO_DEVICE_OUT_BUS, sCarRearZoneTwoOutput, audioConfig, mediaMatchCriteria);
3034 ASSERT_EQ(NO_ERROR, ret);
3035 const AudioDeviceTypeAddr mediaOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput);
3036 const AudioDeviceTypeAddrVector primaryZoneDevices = {mediaOutputDevice};
3037 mManager->setUserIdDeviceAffinities(/* userId */ 0, primaryZoneDevices);
3038 const AudioDeviceTypeAddr secondaryOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarRearZoneOneOutput);
3039 const AudioDeviceTypeAddrVector secondaryZoneDevices = {secondaryOutputDevice};
3040 mManager->setUserIdDeviceAffinities(/* userId */ 11, secondaryZoneDevices);
3041 const AudioDeviceTypeAddr tertiaryOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarRearZoneTwoOutput);
3042 const AudioDeviceTypeAddrVector tertiaryZoneDevices = {tertiaryOutputDevice};
3043 mManager->setUserIdDeviceAffinities(/* userId */ 15, tertiaryZoneDevices);
3044 audio_port_v7 tertiaryZoneDevicePort;
3045 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
3046 sCarRearZoneTwoOutput, &tertiaryZoneDevicePort));
3047 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3048 audio_io_handle_t output;
3049 audio_port_handle_t portId;
3050 const audio_attributes_t mediaAttribute = {
3051 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
3052 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
3053 uid_t user15AppUid = multiuser_get_uid(/* user_id */ 15, /* app_id */ 12345);
3054
3055 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
3056 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, mediaAttribute,
3057 AUDIO_SESSION_NONE, user15AppUid);
3058
3059 ASSERT_EQ(tertiaryZoneDevicePort.id, selectedDeviceId);
3060}
3061
Oscar Azucena873d10f2023-01-12 18:34:42 -08003062TEST_F(AudioPolicyManagerCarTest, GetOutputForAttrWithNoMatchingMix) {
3063 status_t ret;
3064 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
3065 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3066 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
3067 audioConfig.sample_rate = k48000SamplingRate;
3068 std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
3069 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
3070 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
3071 AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput, audioConfig, mediaMatchCriteria);
3072 ASSERT_EQ(NO_ERROR, ret);
3073 std::vector<AudioMixMatchCriterion> navMatchCriteria = {
3074 createUsageCriterion(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
3075 /*exclude=*/ false)};
3076 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
3077 AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput, audioConfig, navMatchCriteria);
3078 ASSERT_EQ(NO_ERROR, ret);
3079 const AudioDeviceTypeAddr mediaOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusMediaOutput);
3080 const AudioDeviceTypeAddr navOutputDevice(AUDIO_DEVICE_OUT_BUS, sCarBusNavigationOutput);
3081 const AudioDeviceTypeAddrVector outputDevices = {mediaOutputDevice, navOutputDevice};
Oscar Azucena4f49ef62023-01-25 23:32:13 -08003082 mManager->setUserIdDeviceAffinities(/* userId */ 0, outputDevices);
Oscar Azucena873d10f2023-01-12 18:34:42 -08003083 audio_port_v7 navDevicePort;
3084 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
3085 sCarBusNavigationOutput, &navDevicePort));
3086 audio_port_handle_t selectedDeviceId = navDevicePort.id;
3087 audio_io_handle_t output;
3088 audio_port_handle_t portId;
3089 const audio_attributes_t alarmAttribute = {
3090 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_ALARM,
3091 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
3092
3093 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
3094 k48000SamplingRate, AUDIO_OUTPUT_FLAG_DIRECT, &output, &portId, alarmAttribute);
3095
3096 ASSERT_EQ(navDevicePort.id, selectedDeviceId);
3097}
3098
jiabin24ff57a2023-11-27 21:06:51 +00003099TEST_F(AudioPolicyManagerCarTest, GetOutputForAttrForMMapWithPolicyMatched) {
3100 status_t ret;
3101 audio_config_t audioConfig = AUDIO_CONFIG_INITIALIZER;
3102 audioConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3103 audioConfig.format = AUDIO_FORMAT_PCM_16_BIT;
3104 audioConfig.sample_rate = k48000SamplingRate;
3105 std::vector<AudioMixMatchCriterion> mediaMatchCriteria = {
3106 createUsageCriterion(AUDIO_USAGE_MEDIA, /*exclude=*/ false)};
3107 ret = addPolicyMix(MIX_TYPE_PLAYERS, MIX_ROUTE_FLAG_RENDER,
3108 AUDIO_DEVICE_OUT_BUS, sCarBusMmapOutput, audioConfig, mediaMatchCriteria);
3109 ASSERT_EQ(NO_ERROR, ret);
3110 ASSERT_EQ(NO_ERROR, ret);
3111 audio_port_v7 mmapDevicePort;
3112 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SINK, AUDIO_DEVICE_OUT_BUS,
3113 sCarBusMmapOutput, &mmapDevicePort));
3114 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3115 audio_io_handle_t output;
3116 audio_port_handle_t portId;
3117 const audio_attributes_t mediaAttribute = {
3118 AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA,
3119 AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
3120
3121 getOutputForAttr(
3122 &selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
3123 k48000SamplingRate,
3124 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT),
3125 &output, &portId, mediaAttribute);
3126
3127 ASSERT_EQ(mmapDevicePort.id, selectedDeviceId);
3128}
3129
Mikhail Naganov0756bbf2019-09-06 13:53:26 -07003130class AudioPolicyManagerTVTest : public AudioPolicyManagerTestWithConfigurationFile {
3131protected:
3132 std::string getConfigFile() override { return sTvConfig; }
3133 void testHDMIPortSelection(audio_output_flags_t flags, const char* expectedMixPortName);
3134
3135 static const std::string sTvConfig;
3136};
3137
3138const std::string AudioPolicyManagerTVTest::sTvConfig =
3139 AudioPolicyManagerTVTest::sExecutableDir + "test_tv_apm_configuration.xml";
3140
3141// SwAudioOutputDescriptor doesn't populate flags so check against the port name.
3142void AudioPolicyManagerTVTest::testHDMIPortSelection(
3143 audio_output_flags_t flags, const char* expectedMixPortName) {
3144 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
3145 AUDIO_DEVICE_OUT_AUX_DIGITAL, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3146 "" /*address*/, "" /*name*/, AUDIO_FORMAT_DEFAULT));
3147 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3148 audio_io_handle_t output;
3149 audio_port_handle_t portId;
Dean Wheatleyd082f472022-02-04 11:10:48 +11003150 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
3151 k48000SamplingRate, flags, &output, &portId);
Mikhail Naganov0756bbf2019-09-06 13:53:26 -07003152 sp<SwAudioOutputDescriptor> outDesc = mManager->getOutputs().valueFor(output);
3153 ASSERT_NE(nullptr, outDesc.get());
jiabin19cdba52020-11-24 11:28:58 -08003154 audio_port_v7 port = {};
Mikhail Naganov0756bbf2019-09-06 13:53:26 -07003155 outDesc->toAudioPort(&port);
3156 mManager->releaseOutput(portId);
3157 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
3158 AUDIO_DEVICE_OUT_AUX_DIGITAL, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3159 "" /*address*/, "" /*name*/, AUDIO_FORMAT_DEFAULT));
3160 ASSERT_EQ(AUDIO_PORT_TYPE_MIX, port.type);
3161 ASSERT_EQ(AUDIO_PORT_ROLE_SOURCE, port.role);
3162 ASSERT_STREQ(expectedMixPortName, port.name);
3163}
3164
3165TEST_F(AudioPolicyManagerTVTest, InitSuccess) {
3166 // SetUp must finish with no assertions.
3167}
3168
3169TEST_F(AudioPolicyManagerTVTest, Dump) {
3170 dumpToLog();
3171}
3172
Mikhail Naganov57ac2ce2019-09-11 09:29:41 -07003173TEST_F(AudioPolicyManagerTVTest, MatchNoFlags) {
3174 testHDMIPortSelection(AUDIO_OUTPUT_FLAG_NONE, "primary output");
3175}
3176
3177TEST_F(AudioPolicyManagerTVTest, MatchOutputDirectNoHwAvSync) {
Mikhail Naganov0756bbf2019-09-06 13:53:26 -07003178 // b/140447125: The selected port must not have HW AV Sync flag (see the config file).
3179 testHDMIPortSelection(AUDIO_OUTPUT_FLAG_DIRECT, "direct");
3180}
3181
Mikhail Naganov57ac2ce2019-09-11 09:29:41 -07003182TEST_F(AudioPolicyManagerTVTest, MatchOutputDirectHwAvSync) {
Mikhail Naganov0756bbf2019-09-06 13:53:26 -07003183 testHDMIPortSelection(static_cast<audio_output_flags_t>(
3184 AUDIO_OUTPUT_FLAG_DIRECT|AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
3185 "tunnel");
3186}
Mikhail Naganov57ac2ce2019-09-11 09:29:41 -07003187
3188TEST_F(AudioPolicyManagerTVTest, MatchOutputDirectMMapNoIrq) {
3189 testHDMIPortSelection(static_cast<audio_output_flags_t>(
3190 AUDIO_OUTPUT_FLAG_DIRECT|AUDIO_OUTPUT_FLAG_MMAP_NOIRQ),
3191 "low latency");
3192}
Mikhail Naganovc0d04982020-03-02 21:02:28 +00003193
Mikhail Naganov806170e2024-09-05 17:26:50 -07003194class AudioPolicyManagerPhoneTest : public AudioPolicyManagerTestWithConfigurationFile {
3195protected:
3196 std::string getConfigFile() override { return sPhoneConfig; }
3197 void testOutputMixPortSelectionForAttr(audio_output_flags_t flags, audio_format_t format,
3198 int samplingRate, bool isMusic, const char* expectedMixPortName);
3199 void testOutputMixPortSelectionForStream(
3200 audio_stream_type_t stream, const char* expectedMixPortName);
3201 void verifyMixPortNameAndFlags(audio_io_handle_t output, const char* expectedMixPortName);
3202
3203 static const std::string sPhoneConfig;
3204 static const std::map<std::string, audio_output_flags_t> sMixPortFlags;
3205};
3206
3207const std::string AudioPolicyManagerPhoneTest::sPhoneConfig =
3208 AudioPolicyManagerPhoneTest::sExecutableDir + "test_phone_apm_configuration.xml";
3209
3210// Must be in sync with the contents of the sPhoneConfig file.
3211const std::map<std::string, audio_output_flags_t> AudioPolicyManagerPhoneTest::sMixPortFlags = {
3212 {"primary output",
3213 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_PRIMARY | AUDIO_OUTPUT_FLAG_FAST)},
3214 {"direct", AUDIO_OUTPUT_FLAG_DIRECT},
3215 {"deep buffer", AUDIO_OUTPUT_FLAG_DEEP_BUFFER},
3216 {"compressed_offload",
3217 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
3218 AUDIO_OUTPUT_FLAG_NON_BLOCKING |
3219 AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)},
3220 {"raw", (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_FAST)},
3221 {"mmap_no_irq_out",
3222 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_DIRECT|AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)},
3223 {"voip_rx", AUDIO_OUTPUT_FLAG_VOIP_RX},
3224};
3225
3226void AudioPolicyManagerPhoneTest::testOutputMixPortSelectionForAttr(
3227 audio_output_flags_t flags, audio_format_t format, int samplingRate, bool isMusic,
3228 const char* expectedMixPortName) {
3229 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3230 audio_io_handle_t output;
3231 audio_port_handle_t portId;
3232 audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER;
3233 if (isMusic) {
3234 attr.content_type = AUDIO_CONTENT_TYPE_MUSIC;
3235 attr.usage = AUDIO_USAGE_MEDIA;
3236 }
3237 getOutputForAttr(&selectedDeviceId, format, AUDIO_CHANNEL_OUT_STEREO, samplingRate, flags,
3238 &output, &portId, attr);
3239 EXPECT_NO_FATAL_FAILURE(verifyMixPortNameAndFlags(output, expectedMixPortName));
3240 mManager->releaseOutput(portId);
3241}
3242
3243void AudioPolicyManagerPhoneTest::testOutputMixPortSelectionForStream(
3244 audio_stream_type_t stream, const char* expectedMixPortName) {
3245 audio_io_handle_t output = mManager->getOutput(stream);
3246 EXPECT_NO_FATAL_FAILURE(verifyMixPortNameAndFlags(output, expectedMixPortName));
3247}
3248
3249void AudioPolicyManagerPhoneTest::verifyMixPortNameAndFlags(audio_io_handle_t output,
3250 const char* expectedMixPortName) {
3251 ALOGI("%s: checking output %d", __func__, output);
3252 sp<SwAudioOutputDescriptor> outDesc = mManager->getOutputs().valueFor(output);
3253 ASSERT_NE(nullptr, outDesc.get());
3254 audio_port_v7 port = {};
3255 outDesc->toAudioPort(&port);
3256 EXPECT_EQ(AUDIO_PORT_TYPE_MIX, port.type);
3257 EXPECT_EQ(AUDIO_PORT_ROLE_SOURCE, port.role);
3258 ASSERT_STREQ(expectedMixPortName, port.name);
3259
3260 auto iter = sMixPortFlags.find(port.name);
3261 ASSERT_NE(iter, sMixPortFlags.end()) << "\"" << port.name << "\" is not in sMixPortFlags";
3262 auto actualFlags = mClient->getOpenOutputFlags(output);
3263 ASSERT_TRUE(actualFlags.has_value()) << "\"" << port.name << "\" was not opened via client";
3264 EXPECT_EQ(*actualFlags, iter->second);
3265}
3266
3267TEST_F(AudioPolicyManagerPhoneTest, InitSuccess) {
3268 // SetUp must finish with no assertions.
3269}
3270
3271enum {
3272 MIX_PORT_ATTR_EXPECTED_NAME_PARAMETER,
3273 MIX_PORT_ATTR_EXPECTED_NAME_WITH_DBFM_PARAMETER,
3274 MIX_PORT_ATTR_FLAGS_PARAMETER,
3275 MIX_PORT_ATTR_FORMAT_PARAMETER,
3276 MIX_PORT_ATTR_SAMPLING_RATE_PARAMETER,
3277};
3278using MixPortSelectionForAttr =
3279 std::tuple<const char*, const char*, audio_output_flags_t, audio_format_t, int>;
3280
3281class AudioPolicyManagerOutputMixPortForAttrSelectionTest
3282 : public AudioPolicyManagerPhoneTest,
3283 public testing::WithParamInterface<MixPortSelectionForAttr> {
3284};
3285
3286// There is no easy way to create a flat tuple from tuples via ::testing::Combine.
3287// Instead, just run the same selection twice while altering the deep buffer for media setting.
3288TEST_P(AudioPolicyManagerOutputMixPortForAttrSelectionTest, SelectPortByFlags) {
3289 mConfig->setUseDeepBufferForMediaOverrideForTests(false);
3290 ASSERT_NO_FATAL_FAILURE(testOutputMixPortSelectionForAttr(
3291 std::get<MIX_PORT_ATTR_FLAGS_PARAMETER>(GetParam()),
3292 std::get<MIX_PORT_ATTR_FORMAT_PARAMETER>(GetParam()),
3293 std::get<MIX_PORT_ATTR_SAMPLING_RATE_PARAMETER>(GetParam()),
3294 false /*isMusic*/,
3295 std::get<MIX_PORT_ATTR_EXPECTED_NAME_PARAMETER>(GetParam())));
3296}
3297TEST_P(AudioPolicyManagerOutputMixPortForAttrSelectionTest, SelectPortByFlags_Music) {
3298 mConfig->setUseDeepBufferForMediaOverrideForTests(false);
3299 ASSERT_NO_FATAL_FAILURE(testOutputMixPortSelectionForAttr(
3300 std::get<MIX_PORT_ATTR_FLAGS_PARAMETER>(GetParam()),
3301 std::get<MIX_PORT_ATTR_FORMAT_PARAMETER>(GetParam()),
3302 std::get<MIX_PORT_ATTR_SAMPLING_RATE_PARAMETER>(GetParam()),
3303 true /*isMusic*/,
3304 std::get<MIX_PORT_ATTR_EXPECTED_NAME_PARAMETER>(GetParam())));
3305}
3306TEST_P(AudioPolicyManagerOutputMixPortForAttrSelectionTest, SelectPortByFlags_DeepMedia) {
3307 mConfig->setUseDeepBufferForMediaOverrideForTests(true);
3308 const char* fallbackName = std::get<MIX_PORT_ATTR_EXPECTED_NAME_PARAMETER>(GetParam());
3309 ASSERT_NO_FATAL_FAILURE(
3310 testOutputMixPortSelectionForAttr(std::get<MIX_PORT_ATTR_FLAGS_PARAMETER>(GetParam()),
3311 std::get<MIX_PORT_ATTR_FORMAT_PARAMETER>(GetParam()),
3312 std::get<MIX_PORT_ATTR_SAMPLING_RATE_PARAMETER>(GetParam()),
3313 false /*isMusic*/,
3314 std::get<MIX_PORT_ATTR_EXPECTED_NAME_WITH_DBFM_PARAMETER>(
3315 GetParam()) ?: fallbackName));
3316}
3317TEST_P(AudioPolicyManagerOutputMixPortForAttrSelectionTest, SelectPortByFlags_DeepMedia_Music) {
3318 mConfig->setUseDeepBufferForMediaOverrideForTests(true);
3319 const char* fallbackName = std::get<MIX_PORT_ATTR_EXPECTED_NAME_PARAMETER>(GetParam());
3320 ASSERT_NO_FATAL_FAILURE(
3321 testOutputMixPortSelectionForAttr(std::get<MIX_PORT_ATTR_FLAGS_PARAMETER>(GetParam()),
3322 std::get<MIX_PORT_ATTR_FORMAT_PARAMETER>(GetParam()),
3323 std::get<MIX_PORT_ATTR_SAMPLING_RATE_PARAMETER>(GetParam()),
3324 true /*isMusic*/,
3325 std::get<MIX_PORT_ATTR_EXPECTED_NAME_WITH_DBFM_PARAMETER>(
3326 GetParam()) ?: fallbackName));
3327}
3328
3329INSTANTIATE_TEST_CASE_P(AudioPolicyManagerOutputMixPortForAttrSelection,
3330 AudioPolicyManagerOutputMixPortForAttrSelectionTest,
3331 ::testing::Values(
3332 std::make_tuple("primary output", "deep buffer", AUDIO_OUTPUT_FLAG_NONE,
3333 AUDIO_FORMAT_PCM_16_BIT, AudioPolicyManagerTest::k48000SamplingRate),
3334 std::make_tuple("primary output", "deep buffer", AUDIO_OUTPUT_FLAG_NONE,
3335 AUDIO_FORMAT_PCM_FLOAT, AudioPolicyManagerTest::k48000SamplingRate),
3336 // Note: this goes to "direct" because 384000 > SAMPLE_RATE_HZ_MAX (192000)
3337 std::make_tuple("direct", "deep buffer", AUDIO_OUTPUT_FLAG_NONE,
3338 AUDIO_FORMAT_PCM_FLOAT, AudioPolicyManagerTest::k384000SamplingRate),
3339 std::make_tuple("primary output", nullptr, AUDIO_OUTPUT_FLAG_FAST,
3340 AUDIO_FORMAT_PCM_16_BIT, AudioPolicyManagerTest::k48000SamplingRate),
3341 std::make_tuple("direct", nullptr, AUDIO_OUTPUT_FLAG_DIRECT,
3342 AUDIO_FORMAT_PCM_FLOAT, AudioPolicyManagerTest::k96000SamplingRate),
3343 std::make_tuple("direct", nullptr, AUDIO_OUTPUT_FLAG_DIRECT,
3344 AUDIO_FORMAT_PCM_FLOAT, AudioPolicyManagerTest::k384000SamplingRate),
3345 std::make_tuple("deep buffer", nullptr, AUDIO_OUTPUT_FLAG_DEEP_BUFFER,
3346 AUDIO_FORMAT_PCM_16_BIT, AudioPolicyManagerTest::k48000SamplingRate),
3347 std::make_tuple("deep buffer", nullptr, AUDIO_OUTPUT_FLAG_DEEP_BUFFER,
3348 AUDIO_FORMAT_PCM_FLOAT, AudioPolicyManagerTest::k384000SamplingRate),
3349 std::make_tuple("compressed_offload", nullptr,
3350 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
3351 AUDIO_OUTPUT_FLAG_NON_BLOCKING),
3352 AUDIO_FORMAT_MP3, AudioPolicyManagerTest::k48000SamplingRate),
3353 std::make_tuple("raw", nullptr,
3354 AUDIO_OUTPUT_FLAG_RAW, AUDIO_FORMAT_PCM_32_BIT,
3355 AudioPolicyManagerTest::k48000SamplingRate),
3356 std::make_tuple("mmap_no_irq_out", nullptr,
3357 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_DIRECT |
3358 AUDIO_OUTPUT_FLAG_MMAP_NOIRQ),
3359 AUDIO_FORMAT_PCM_FLOAT, AudioPolicyManagerTest::k48000SamplingRate),
3360 std::make_tuple("mmap_no_irq_out", nullptr,
3361 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_DIRECT |
3362 AUDIO_OUTPUT_FLAG_MMAP_NOIRQ),
3363 AUDIO_FORMAT_PCM_FLOAT, AudioPolicyManagerTest::k384000SamplingRate),
3364 std::make_tuple("voip_rx", nullptr, AUDIO_OUTPUT_FLAG_VOIP_RX,
3365 AUDIO_FORMAT_PCM_16_BIT, AudioPolicyManagerTest::k48000SamplingRate)),
3366 [](const ::testing::TestParamInfo<MixPortSelectionForAttr>& info) {
3367 static const std::string flagPrefix = "AUDIO_OUTPUT_FLAG_";
3368 static const std::string formatPrefix = "AUDIO_FORMAT_";
3369 std::string flags;
3370 TypeConverter<OutputFlagTraits>::maskToString(
3371 std::get<MIX_PORT_ATTR_FLAGS_PARAMETER>(info.param), flags, "__");
3372 size_t index = 0;
3373 while (true) {
3374 index = flags.rfind(flagPrefix);
3375 if (index == std::string::npos) break;
3376 flags.erase(index, flagPrefix.length());
3377 }
3378 std::string format;
3379 TypeConverter<FormatTraits>::toString(
3380 std::get<MIX_PORT_ATTR_FORMAT_PARAMETER>(info.param), format);
3381 if (size_t index = format.find(formatPrefix); index != std::string::npos) {
3382 format.erase(index, formatPrefix.length());
3383 }
3384 return flags + "__" + format + "__" +
3385 std::to_string(std::get<MIX_PORT_ATTR_SAMPLING_RATE_PARAMETER>(info.param));
3386 }
3387);
3388
3389
3390enum {
3391 MIX_PORT_STRM_EXPECTED_NAME_PARAMETER,
3392 MIX_PORT_STRM_EXPECTED_NAME_WITH_DBFM_PARAMETER,
3393 MIX_PORT_STRM_STREAM_PARAMETER,
3394};
3395using MixPortSelectionForStream =
3396 std::tuple<const char*, const char*, audio_stream_type_t>;
3397
3398class AudioPolicyManagerOutputMixPortForStreamSelectionTest
3399 : public AudioPolicyManagerPhoneTest,
3400 public testing::WithParamInterface<MixPortSelectionForStream> {
3401};
3402
3403// There is no easy way to create a flat tuple from tuples via ::testing::Combine.
3404// Instead, just run the same selection twice while altering the deep buffer for media setting.
3405TEST_P(AudioPolicyManagerOutputMixPortForStreamSelectionTest, SelectPort_NoDBFM) {
3406 mConfig->setUseDeepBufferForMediaOverrideForTests(false);
3407 ASSERT_NO_FATAL_FAILURE(testOutputMixPortSelectionForStream(
3408 std::get<MIX_PORT_STRM_STREAM_PARAMETER>(GetParam()),
3409 std::get<MIX_PORT_STRM_EXPECTED_NAME_PARAMETER>(GetParam())));
3410}
3411TEST_P(AudioPolicyManagerOutputMixPortForStreamSelectionTest, SelectPort_WithDBFM) {
3412 mConfig->setUseDeepBufferForMediaOverrideForTests(true);
3413 const char* fallbackName = std::get<MIX_PORT_STRM_EXPECTED_NAME_PARAMETER>(GetParam());
3414 ASSERT_NO_FATAL_FAILURE(testOutputMixPortSelectionForStream(
3415 std::get<MIX_PORT_STRM_STREAM_PARAMETER>(GetParam()),
3416 std::get<MIX_PORT_STRM_EXPECTED_NAME_WITH_DBFM_PARAMETER>(
3417 GetParam()) ?: fallbackName));
3418}
3419
3420INSTANTIATE_TEST_CASE_P(
3421 AudioPolicyManagerOutputMixPortForStreamSelection,
3422 AudioPolicyManagerOutputMixPortForStreamSelectionTest,
3423 ::testing::Values(std::make_tuple("primary output", nullptr, AUDIO_STREAM_DEFAULT),
3424 std::make_tuple("primary output", nullptr, AUDIO_STREAM_SYSTEM),
3425 std::make_tuple("primary output", nullptr, AUDIO_STREAM_RING),
3426 std::make_tuple("primary output", "deep buffer", AUDIO_STREAM_MUSIC),
3427 std::make_tuple("primary output", nullptr, AUDIO_STREAM_ALARM),
3428 std::make_tuple("primary output", nullptr, AUDIO_STREAM_NOTIFICATION),
3429 std::make_tuple("primary output", nullptr, AUDIO_STREAM_BLUETOOTH_SCO),
3430 std::make_tuple("primary output", nullptr, AUDIO_STREAM_ENFORCED_AUDIBLE),
3431 std::make_tuple("primary output", nullptr, AUDIO_STREAM_DTMF),
3432 std::make_tuple("primary output", nullptr, AUDIO_STREAM_TTS),
3433 std::make_tuple("primary output", nullptr, AUDIO_STREAM_ACCESSIBILITY),
3434 std::make_tuple("primary output", nullptr, AUDIO_STREAM_ASSISTANT)),
3435 [](const ::testing::TestParamInfo<MixPortSelectionForStream>& info) {
3436 static const std::string streamPrefix = "AUDIO_STREAM_";
3437 std::string stream;
3438 TypeConverter<StreamTraits>::toString(
3439 std::get<MIX_PORT_STRM_STREAM_PARAMETER>(info.param), stream);
3440 if (size_t index = stream.find(streamPrefix); index != std::string::npos) {
3441 stream.erase(index, streamPrefix.length());
3442 }
3443 return stream;
3444 }
3445);
3446
Mikhail Naganovc0d04982020-03-02 21:02:28 +00003447class AudioPolicyManagerDynamicHwModulesTest : public AudioPolicyManagerTestWithConfigurationFile {
3448protected:
3449 void SetUpManagerConfig() override;
3450};
3451
3452void AudioPolicyManagerDynamicHwModulesTest::SetUpManagerConfig() {
Mikhail Naganovd4c21aa2021-10-05 15:10:16 -07003453 ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTestWithConfigurationFile::SetUpManagerConfig());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00003454 // Only allow successful opening of "primary" hw module during APM initialization.
3455 mClient->swapAllowedModuleNames({"primary"});
3456}
3457
3458TEST_F(AudioPolicyManagerDynamicHwModulesTest, InitSuccess) {
3459 // SetUp must finish with no assertions.
3460}
3461
3462TEST_F(AudioPolicyManagerDynamicHwModulesTest, DynamicAddition) {
3463 const auto handleBefore = mClient->peekNextModuleHandle();
3464 mManager->onNewAudioModulesAvailable();
3465 ASSERT_EQ(handleBefore, mClient->peekNextModuleHandle());
3466 // Reset module loading restrictions.
3467 mClient->swapAllowedModuleNames();
3468 mManager->onNewAudioModulesAvailable();
3469 const auto handleAfter = mClient->peekNextModuleHandle();
3470 ASSERT_GT(handleAfter, handleBefore);
3471 mManager->onNewAudioModulesAvailable();
3472 ASSERT_EQ(handleAfter, mClient->peekNextModuleHandle());
3473}
3474
3475TEST_F(AudioPolicyManagerDynamicHwModulesTest, AddedDeviceAvailable) {
3476 ASSERT_EQ(AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, mManager->getDeviceConnectionState(
3477 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "0"));
3478 mClient->swapAllowedModuleNames({"primary", "r_submix"});
3479 mManager->onNewAudioModulesAvailable();
3480 ASSERT_EQ(AUDIO_POLICY_DEVICE_STATE_AVAILABLE, mManager->getDeviceConnectionState(
3481 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "0"));
3482}
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07003483
3484TEST_F(AudioPolicyManagerDynamicHwModulesTest, ListAddedAudioPorts) {
3485 ASSERT_FALSE(
3486 findDevicePort(AUDIO_PORT_ROLE_SOURCE, AUDIO_DEVICE_IN_REMOTE_SUBMIX, "0", nullptr));
3487 mClient->swapAllowedModuleNames({"primary", "r_submix"});
3488 mManager->onNewAudioModulesAvailable();
jiabin19cdba52020-11-24 11:28:58 -08003489 struct audio_port_v7 port;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07003490 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SOURCE, AUDIO_DEVICE_IN_REMOTE_SUBMIX, "0", &port));
3491}
3492
3493TEST_F(AudioPolicyManagerDynamicHwModulesTest, ClientIsUpdated) {
3494 const size_t prevAudioPortListUpdateCount = mClient->getAudioPortListUpdateCount();
3495 const uint32_t prevAudioPortGeneration = mManager->getAudioPortGeneration();
3496 mClient->swapAllowedModuleNames({"primary", "r_submix"});
3497 mManager->onNewAudioModulesAvailable();
3498 EXPECT_GT(mClient->getAudioPortListUpdateCount(), prevAudioPortListUpdateCount);
3499 EXPECT_GT(mManager->getAudioPortGeneration(), prevAudioPortGeneration);
3500}
Jiabin Huang3b98d322020-09-03 17:54:16 +00003501
3502using DevicesRoleForCapturePresetParam = std::tuple<audio_source_t, device_role_t>;
3503
3504class AudioPolicyManagerDevicesRoleForCapturePresetTest
3505 : public AudioPolicyManagerTestWithConfigurationFile,
3506 public testing::WithParamInterface<DevicesRoleForCapturePresetParam> {
3507protected:
3508 // The `inputDevice` and `inputDevice2` indicate the audio devices type to be used for setting
3509 // device role. They must be declared in the test_audio_policy_configuration.xml
3510 AudioDeviceTypeAddr inputDevice = AudioDeviceTypeAddr(AUDIO_DEVICE_IN_BUILTIN_MIC, "");
3511 AudioDeviceTypeAddr inputDevice2 = AudioDeviceTypeAddr(AUDIO_DEVICE_IN_HDMI, "");
3512};
3513
3514TEST_P(AudioPolicyManagerDevicesRoleForCapturePresetTest, DevicesRoleForCapturePreset) {
3515 const audio_source_t audioSource = std::get<0>(GetParam());
3516 const device_role_t role = std::get<1>(GetParam());
3517
3518 // Test invalid device when setting
3519 const AudioDeviceTypeAddr outputDevice(AUDIO_DEVICE_OUT_SPEAKER, "");
3520 const AudioDeviceTypeAddrVector outputDevices = {outputDevice};
3521 ASSERT_EQ(BAD_VALUE,
3522 mManager->setDevicesRoleForCapturePreset(audioSource, role, outputDevices));
3523 ASSERT_EQ(BAD_VALUE,
3524 mManager->addDevicesRoleForCapturePreset(audioSource, role, outputDevices));
3525 AudioDeviceTypeAddrVector devices;
3526 ASSERT_EQ(NAME_NOT_FOUND,
3527 mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
3528 ASSERT_TRUE(devices.empty());
3529 ASSERT_EQ(BAD_VALUE,
3530 mManager->removeDevicesRoleForCapturePreset(audioSource, role, outputDevices));
3531
3532 // Without setting, call get/remove/clear must fail
3533 ASSERT_EQ(NAME_NOT_FOUND,
3534 mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
3535 ASSERT_EQ(NAME_NOT_FOUND,
3536 mManager->removeDevicesRoleForCapturePreset(audioSource, role, devices));
3537 ASSERT_EQ(NAME_NOT_FOUND,
3538 mManager->clearDevicesRoleForCapturePreset(audioSource, role));
3539
3540 // Test set/get devices role
3541 const AudioDeviceTypeAddrVector inputDevices = {inputDevice};
3542 ASSERT_EQ(NO_ERROR,
3543 mManager->setDevicesRoleForCapturePreset(audioSource, role, inputDevices));
3544 ASSERT_EQ(NO_ERROR, mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
3545 EXPECT_THAT(devices, UnorderedElementsAre(inputDevice));
3546
3547 // Test setting will change the previously set devices
3548 const AudioDeviceTypeAddrVector inputDevices2 = {inputDevice2};
3549 ASSERT_EQ(NO_ERROR,
3550 mManager->setDevicesRoleForCapturePreset(audioSource, role, inputDevices2));
3551 devices.clear();
3552 ASSERT_EQ(NO_ERROR, mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
3553 EXPECT_THAT(devices, UnorderedElementsAre(inputDevice2));
3554
3555 // Test add devices
3556 ASSERT_EQ(NO_ERROR,
3557 mManager->addDevicesRoleForCapturePreset(audioSource, role, inputDevices));
3558 devices.clear();
3559 ASSERT_EQ(NO_ERROR, mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
3560 EXPECT_THAT(devices, UnorderedElementsAre(inputDevice, inputDevice2));
3561
3562 // Test remove devices
3563 ASSERT_EQ(NO_ERROR,
3564 mManager->removeDevicesRoleForCapturePreset(audioSource, role, inputDevices));
3565 devices.clear();
3566 ASSERT_EQ(NO_ERROR, mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
3567 EXPECT_THAT(devices, UnorderedElementsAre(inputDevice2));
3568
3569 // Test remove devices that are not set as the device role
3570 ASSERT_EQ(BAD_VALUE,
3571 mManager->removeDevicesRoleForCapturePreset(audioSource, role, inputDevices));
3572
3573 // Test clear devices
3574 ASSERT_EQ(NO_ERROR,
3575 mManager->clearDevicesRoleForCapturePreset(audioSource, role));
3576 devices.clear();
3577 ASSERT_EQ(NAME_NOT_FOUND,
3578 mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
3579}
3580
jiabin14662b52023-03-06 21:35:29 +00003581TEST_F(AudioPolicyManagerDevicesRoleForCapturePresetTest, PreferredDeviceUsedForInput) {
3582 const audio_source_t source = AUDIO_SOURCE_MIC;
3583 const device_role_t role = DEVICE_ROLE_PREFERRED;
3584 const std::string address = "card=1;device=0";
3585 const std::string deviceName = "randomName";
3586
3587 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
3588 AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3589 address.c_str(), deviceName.c_str(), AUDIO_FORMAT_DEFAULT));
3590 auto availableDevices = mManager->getAvailableInputDevices();
3591 ASSERT_GT(availableDevices.size(), 1);
3592
3593 audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER;
3594 attr.source = source;
3595 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffie6ebbce02023-07-19 13:27:53 +02003596 audio_io_handle_t input = AUDIO_PORT_HANDLE_NONE;
3597 ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input, AUDIO_SESSION_NONE, 1, &selectedDeviceId,
jiabin14662b52023-03-06 21:35:29 +00003598 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
Mikhail Naganov806170e2024-09-05 17:26:50 -07003599 k48000SamplingRate));
jiabin14662b52023-03-06 21:35:29 +00003600 auto selectedDevice = availableDevices.getDeviceFromId(selectedDeviceId);
3601 ASSERT_NE(nullptr, selectedDevice);
3602
3603 sp<DeviceDescriptor> preferredDevice = nullptr;
3604 for (const auto& device : availableDevices) {
3605 if (device != selectedDevice) {
3606 preferredDevice = device;
3607 break;
3608 }
3609 }
3610 ASSERT_NE(nullptr, preferredDevice);
3611 // After setting preferred device for capture preset, the selected device for input should be
3612 // the preferred device.
3613 ASSERT_EQ(NO_ERROR,
3614 mManager->setDevicesRoleForCapturePreset(source, role,
3615 {preferredDevice->getDeviceTypeAddr()}));
3616 selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffie6ebbce02023-07-19 13:27:53 +02003617 input = AUDIO_PORT_HANDLE_NONE;
3618 ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input, AUDIO_SESSION_NONE, 1, &selectedDeviceId,
jiabin14662b52023-03-06 21:35:29 +00003619 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
Mikhail Naganov806170e2024-09-05 17:26:50 -07003620 k48000SamplingRate));
jiabin14662b52023-03-06 21:35:29 +00003621 ASSERT_EQ(preferredDevice, availableDevices.getDeviceFromId(selectedDeviceId));
3622
3623 // After clearing preferred device for capture preset, the selected device for input should be
3624 // the same as original one.
3625 ASSERT_EQ(NO_ERROR,
3626 mManager->clearDevicesRoleForCapturePreset(source, role));
3627 selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffie6ebbce02023-07-19 13:27:53 +02003628 input = AUDIO_PORT_HANDLE_NONE;
3629 ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input, AUDIO_SESSION_NONE, 1, &selectedDeviceId,
jiabin14662b52023-03-06 21:35:29 +00003630 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
Mikhail Naganov806170e2024-09-05 17:26:50 -07003631 k48000SamplingRate));
jiabin14662b52023-03-06 21:35:29 +00003632 ASSERT_EQ(selectedDevice, availableDevices.getDeviceFromId(selectedDeviceId));
3633
3634 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
3635 AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3636 address.c_str(), deviceName.c_str(), AUDIO_FORMAT_DEFAULT));
3637}
3638
3639TEST_F(AudioPolicyManagerDevicesRoleForCapturePresetTest, DisabledDeviceNotUsedForInput) {
3640 const audio_source_t source = AUDIO_SOURCE_MIC;
3641 const device_role_t role = DEVICE_ROLE_DISABLED;
3642 const std::string address = "card=1;device=0";
3643 const std::string deviceName = "randomName";
3644
3645 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
3646 AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3647 address.c_str(), deviceName.c_str(), AUDIO_FORMAT_DEFAULT));
3648 auto availableDevices = mManager->getAvailableInputDevices();
3649 ASSERT_GT(availableDevices.size(), 1);
3650
3651 audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER;
3652 attr.source = source;
3653 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffie6ebbce02023-07-19 13:27:53 +02003654 audio_io_handle_t input = AUDIO_PORT_HANDLE_NONE;
3655 ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input, AUDIO_SESSION_NONE, 1, &selectedDeviceId,
jiabin14662b52023-03-06 21:35:29 +00003656 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
Mikhail Naganov806170e2024-09-05 17:26:50 -07003657 k48000SamplingRate));
jiabin14662b52023-03-06 21:35:29 +00003658 auto selectedDevice = availableDevices.getDeviceFromId(selectedDeviceId);
3659 ASSERT_NE(nullptr, selectedDevice);
3660
3661 // After setting disabled device for capture preset, the disabled device must not be
3662 // selected for input.
3663 ASSERT_EQ(NO_ERROR,
3664 mManager->setDevicesRoleForCapturePreset(source, role,
3665 {selectedDevice->getDeviceTypeAddr()}));
3666 selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffie6ebbce02023-07-19 13:27:53 +02003667 input = AUDIO_PORT_HANDLE_NONE;
3668 ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input, AUDIO_SESSION_NONE, 1,
3669 &selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT,
Mikhail Naganov806170e2024-09-05 17:26:50 -07003670 AUDIO_CHANNEL_IN_STEREO, k48000SamplingRate));
jiabin14662b52023-03-06 21:35:29 +00003671 ASSERT_NE(selectedDevice, availableDevices.getDeviceFromId(selectedDeviceId));
3672
3673 // After clearing disabled device for capture preset, the selected device for input should be
3674 // the original one.
3675 ASSERT_EQ(NO_ERROR,
3676 mManager->clearDevicesRoleForCapturePreset(source, role));
3677 selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffie6ebbce02023-07-19 13:27:53 +02003678 input = AUDIO_PORT_HANDLE_NONE;
3679 ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input, AUDIO_SESSION_NONE, 1, &selectedDeviceId,
jiabin14662b52023-03-06 21:35:29 +00003680 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
Mikhail Naganov806170e2024-09-05 17:26:50 -07003681 k48000SamplingRate));
jiabin14662b52023-03-06 21:35:29 +00003682 ASSERT_EQ(selectedDevice, availableDevices.getDeviceFromId(selectedDeviceId));
3683
3684 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
3685 AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3686 address.c_str(), deviceName.c_str(), AUDIO_FORMAT_DEFAULT));
3687}
3688
Jiabin Huang3b98d322020-09-03 17:54:16 +00003689INSTANTIATE_TEST_CASE_P(
3690 DevicesRoleForCapturePresetOperation,
3691 AudioPolicyManagerDevicesRoleForCapturePresetTest,
3692 testing::Values(
3693 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_MIC, DEVICE_ROLE_PREFERRED}),
3694 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_UPLINK,
3695 DEVICE_ROLE_PREFERRED}),
3696 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_DOWNLINK,
3697 DEVICE_ROLE_PREFERRED}),
3698 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_CALL, DEVICE_ROLE_PREFERRED}),
3699 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_CAMCORDER, DEVICE_ROLE_PREFERRED}),
3700 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_RECOGNITION,
3701 DEVICE_ROLE_PREFERRED}),
3702 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_COMMUNICATION,
3703 DEVICE_ROLE_PREFERRED}),
3704 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_REMOTE_SUBMIX,
3705 DEVICE_ROLE_PREFERRED}),
3706 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_UNPROCESSED, DEVICE_ROLE_PREFERRED}),
3707 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_PERFORMANCE,
3708 DEVICE_ROLE_PREFERRED}),
3709 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_ECHO_REFERENCE,
3710 DEVICE_ROLE_PREFERRED}),
3711 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_FM_TUNER, DEVICE_ROLE_PREFERRED}),
3712 DevicesRoleForCapturePresetParam({AUDIO_SOURCE_HOTWORD, DEVICE_ROLE_PREFERRED})
3713 )
3714 );
François Gaffie6ebbce02023-07-19 13:27:53 +02003715
3716
3717const effect_descriptor_t TEST_EFFECT_DESC = {
3718 {0xf2a4bb20, 0x0c3c, 0x11e3, 0x8b07, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}, // type
3719 {0xff93e360, 0x0c3c, 0x11e3, 0x8a97, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}, // uuid
3720 EFFECT_CONTROL_API_VERSION,
3721 EFFECT_FLAG_TYPE_PRE_PROC,
3722 0,
3723 1,
3724 "APM test Effect",
3725 "The Android Open Source Project",
3726};
3727
3728class AudioPolicyManagerPreProcEffectTest : public AudioPolicyManagerTestWithConfigurationFile {
3729};
3730
3731TEST_F(AudioPolicyManagerPreProcEffectTest, DeviceDisconnectWhileClientActive) {
3732 const audio_source_t source = AUDIO_SOURCE_MIC;
3733 const std::string address = "BUS00_MIC";
3734 const std::string deviceName = "randomName";
3735 audio_port_handle_t portId;
3736 audio_devices_t type = AUDIO_DEVICE_IN_BUS;
3737
3738 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(type,
3739 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, address.c_str(), deviceName.c_str(),
3740 AUDIO_FORMAT_DEFAULT));
3741 auto availableDevices = mManager->getAvailableInputDevices();
3742 ASSERT_GT(availableDevices.size(), 1);
3743
3744 audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER;
3745 attr.source = source;
3746 audio_session_t session = TEST_SESSION_ID;
3747 audio_io_handle_t inputClientHandle = 777;
3748 int effectId = 666;
3749 audio_port_v7 devicePort;
3750 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SOURCE, type, address, &devicePort));
3751
3752 audio_port_handle_t routedPortId = devicePort.id;
3753 ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &inputClientHandle, session, 1, &routedPortId,
3754 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
3755 48000, AUDIO_INPUT_FLAG_NONE, &portId));
3756 ASSERT_EQ(devicePort.id, routedPortId);
3757 auto selectedDevice = availableDevices.getDeviceFromId(routedPortId);
3758 ASSERT_NE(nullptr, selectedDevice);
3759
3760 // Add a pre processing effect on the input client session
3761 ASSERT_EQ(NO_ERROR, mManager->registerEffect(&TEST_EFFECT_DESC, inputClientHandle,
3762 PRODUCT_STRATEGY_NONE, session, effectId));
3763
3764 ASSERT_EQ(NO_ERROR, mManager->startInput(portId));
3765
3766 // Force a device disconnection to close the input, no crash expected of APM
3767 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
3768 type, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3769 address.c_str(), deviceName.c_str(), AUDIO_FORMAT_DEFAULT));
3770
3771 // Reconnect the device
3772 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(
3773 type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3774 address.c_str(), deviceName.c_str(), AUDIO_FORMAT_DEFAULT));
3775
3776 inputClientHandle += 1;
3777 ASSERT_TRUE(findDevicePort(AUDIO_PORT_ROLE_SOURCE, type, address, &devicePort));
3778 routedPortId = devicePort.id;
3779
3780 // Reconnect the client changing voluntarily the io, but keeping the session to get the
3781 // effect attached again
3782 ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &inputClientHandle, session, 1, &routedPortId,
3783 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
Mikhail Naganov806170e2024-09-05 17:26:50 -07003784 k48000SamplingRate));
François Gaffie6ebbce02023-07-19 13:27:53 +02003785
3786 // unregister effect should succeed since effect shall have been restore on the client session
3787 ASSERT_EQ(NO_ERROR, mManager->unregisterEffect(effectId));
Mikhail Naganovf88c2f32024-04-16 15:01:13 -07003788}
jiabin220eea12024-05-17 17:55:20 +00003789
3790class AudioPolicyManagerTestBitPerfectBase : public AudioPolicyManagerTestWithConfigurationFile {
3791protected:
3792 void SetUp() override;
3793 void TearDown() override;
3794
3795 void startBitPerfectOutput();
3796 void reset();
3797 void getBitPerfectOutput(status_t expected);
3798
3799 const audio_format_t mBitPerfectFormat = AUDIO_FORMAT_PCM_16_BIT;
3800 const audio_channel_mask_t mBitPerfectChannelMask = AUDIO_CHANNEL_OUT_STEREO;
Mikhail Naganov806170e2024-09-05 17:26:50 -07003801 const uint32_t mBitPerfectSampleRate = k48000SamplingRate;
jiabin220eea12024-05-17 17:55:20 +00003802 const uid_t mUid = 1234;
3803 audio_port_handle_t mUsbPortId = AUDIO_PORT_HANDLE_NONE;
3804
3805 audio_io_handle_t mBitPerfectOutput = AUDIO_IO_HANDLE_NONE;
3806 audio_port_handle_t mSelectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3807 audio_port_handle_t mBitPerfectPortId = AUDIO_PORT_HANDLE_NONE;
3808
3809 static constexpr audio_attributes_t sMediaAttr = {
3810 .content_type = AUDIO_CONTENT_TYPE_MUSIC,
3811 .usage = AUDIO_USAGE_MEDIA,
3812 };
3813};
3814
3815void AudioPolicyManagerTestBitPerfectBase::SetUp() {
3816 ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTestWithConfigurationFile::SetUp());
3817
3818 mClient->addSupportedFormat(mBitPerfectFormat);
3819 mClient->addSupportedChannelMask(mBitPerfectChannelMask);
3820 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_USB_DEVICE,
3821 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3822 "", "", AUDIO_FORMAT_DEFAULT));
3823 auto devices = mManager->getAvailableOutputDevices();
3824 mUsbPortId = AUDIO_PORT_HANDLE_NONE;
3825 for (auto device : devices) {
3826 if (device->type() == AUDIO_DEVICE_OUT_USB_DEVICE) {
3827 mUsbPortId = device->getId();
3828 break;
3829 }
3830 }
3831 EXPECT_NE(AUDIO_PORT_HANDLE_NONE, mUsbPortId);
3832
3833 std::vector<audio_mixer_attributes_t> mixerAttributes;
3834 EXPECT_EQ(NO_ERROR, mManager->getSupportedMixerAttributes(mUsbPortId, mixerAttributes));
3835 EXPECT_GT(mixerAttributes.size(), 0);
3836 size_t bitPerfectIndex = 0;
3837 for (; bitPerfectIndex < mixerAttributes.size(); ++bitPerfectIndex) {
3838 if (mixerAttributes[bitPerfectIndex].mixer_behavior == AUDIO_MIXER_BEHAVIOR_BIT_PERFECT) {
3839 break;
3840 }
3841 }
3842 EXPECT_LT(bitPerfectIndex, mixerAttributes.size());
3843 EXPECT_EQ(mBitPerfectFormat, mixerAttributes[bitPerfectIndex].config.format);
3844 EXPECT_EQ(mBitPerfectChannelMask, mixerAttributes[bitPerfectIndex].config.channel_mask);
3845 EXPECT_EQ(mBitPerfectSampleRate, mixerAttributes[bitPerfectIndex].config.sample_rate);
3846 EXPECT_EQ(NO_ERROR,
3847 mManager->setPreferredMixerAttributes(
3848 &sMediaAttr, mUsbPortId, mUid, &mixerAttributes[bitPerfectIndex]));
3849}
3850
3851void AudioPolicyManagerTestBitPerfectBase::TearDown() {
3852 EXPECT_EQ(NO_ERROR,
3853 mManager->clearPreferredMixerAttributes(&sMediaAttr, mUsbPortId, mUid));
3854 ASSERT_EQ(NO_ERROR, mManager->setDeviceConnectionState(AUDIO_DEVICE_OUT_USB_DEVICE,
3855 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3856 "", "", AUDIO_FORMAT_LDAC));
3857
3858 ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTestWithConfigurationFile::TearDown());
3859}
3860
3861void AudioPolicyManagerTestBitPerfectBase::startBitPerfectOutput() {
3862 reset();
3863 bool isBitPerfect;
3864
3865 getOutputForAttr(&mSelectedDeviceId, mBitPerfectFormat, mBitPerfectChannelMask,
3866 mBitPerfectSampleRate, AUDIO_OUTPUT_FLAG_NONE, &mBitPerfectOutput,
3867 &mBitPerfectPortId, sMediaAttr, AUDIO_SESSION_NONE, mUid, &isBitPerfect);
3868 status_t status = mManager->startOutput(mBitPerfectPortId);
3869 if (status == DEAD_OBJECT) {
3870 getOutputForAttr(&mSelectedDeviceId, mBitPerfectFormat, mBitPerfectChannelMask,
3871 mBitPerfectSampleRate, AUDIO_OUTPUT_FLAG_NONE, &mBitPerfectOutput,
3872 &mBitPerfectPortId, sMediaAttr, AUDIO_SESSION_NONE, mUid, &isBitPerfect);
3873 status = mManager->startOutput(mBitPerfectPortId);
3874 }
3875 EXPECT_EQ(NO_ERROR, status);
3876 EXPECT_TRUE(isBitPerfect);
3877 EXPECT_NE(AUDIO_IO_HANDLE_NONE, mBitPerfectOutput);
3878 const auto bitPerfectOutputDesc = mManager->getOutputs().valueFor(mBitPerfectOutput);
3879 EXPECT_NE(nullptr, bitPerfectOutputDesc);
3880 EXPECT_EQ(AUDIO_OUTPUT_FLAG_BIT_PERFECT,
3881 bitPerfectOutputDesc->mFlags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
3882};
3883
3884void AudioPolicyManagerTestBitPerfectBase::reset() {
3885 mBitPerfectOutput = AUDIO_IO_HANDLE_NONE;
3886 mSelectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3887 mBitPerfectPortId = AUDIO_PORT_HANDLE_NONE;
3888}
3889
3890void AudioPolicyManagerTestBitPerfectBase::getBitPerfectOutput(status_t expected) {
3891 reset();
3892 audio_stream_type_t stream = AUDIO_STREAM_DEFAULT;
3893 AttributionSourceState attributionSource = createAttributionSourceState(mUid);
3894 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3895 config.sample_rate = mBitPerfectSampleRate;
3896 config.channel_mask = mBitPerfectChannelMask;
3897 config.format = mBitPerfectFormat;
3898 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_BIT_PERFECT;
3899 AudioPolicyInterface::output_type_t outputType;
3900 bool isSpatialized;
3901 bool isBitPerfect;
Andy Hung6b137d12024-08-27 22:35:17 +00003902 float volume;
jiabin220eea12024-05-17 17:55:20 +00003903 EXPECT_EQ(expected,
3904 mManager->getOutputForAttr(&sMediaAttr, &mBitPerfectOutput, AUDIO_SESSION_NONE,
3905 &stream, attributionSource, &config, &flags,
3906 &mSelectedDeviceId, &mBitPerfectPortId, {}, &outputType,
Andy Hung6b137d12024-08-27 22:35:17 +00003907 &isSpatialized, &isBitPerfect, &volume));
jiabin220eea12024-05-17 17:55:20 +00003908}
3909
3910class AudioPolicyManagerTestBitPerfect : public AudioPolicyManagerTestBitPerfectBase {
3911};
3912
3913TEST_F(AudioPolicyManagerTestBitPerfect, UseBitPerfectOutput) {
3914 const uid_t anotherUid = 5678;
3915 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3916 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3917 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
3918 bool isBitPerfect;
3919
3920 // When there is no active bit-perfect playback, the output selection will follow default
3921 // routing strategy.
3922 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_QUAD,
3923 48000, AUDIO_OUTPUT_FLAG_NONE, &output, &portId, sMediaAttr,
3924 AUDIO_SESSION_NONE, mUid, &isBitPerfect);
3925 EXPECT_FALSE(isBitPerfect);
3926 EXPECT_NE(AUDIO_IO_HANDLE_NONE, output);
3927 const auto outputDesc = mManager->getOutputs().valueFor(output);
3928 EXPECT_NE(nullptr, outputDesc);
3929 EXPECT_NE(AUDIO_OUTPUT_FLAG_BIT_PERFECT, outputDesc->mFlags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
3930
3931 // Start bit-perfect playback
3932 ASSERT_NO_FATAL_FAILURE(startBitPerfectOutput());
3933
3934 // If the playback is from preferred mixer attributes owner but the request doesn't match
3935 // preferred mixer attributes, it will not be bit-perfect.
3936 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_QUAD,
3937 48000, AUDIO_OUTPUT_FLAG_NONE, &output, &portId, sMediaAttr,
3938 AUDIO_SESSION_NONE, mUid, &isBitPerfect);
3939 EXPECT_FALSE(isBitPerfect);
3940 EXPECT_EQ(mBitPerfectOutput, output);
3941
3942 // When bit-perfect playback is active, all other playback will be routed to bit-perfect output.
3943 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
3944 48000, AUDIO_OUTPUT_FLAG_NONE, &output, &portId, sMediaAttr,
3945 AUDIO_SESSION_NONE, anotherUid, &isBitPerfect);
3946 EXPECT_FALSE(isBitPerfect);
3947 EXPECT_EQ(mBitPerfectOutput, output);
3948
3949 // When bit-pefect playback is active, dtmf will also be routed to bit-perfect output.
3950 const audio_attributes_t dtmfAttr = {
3951 .content_type = AUDIO_CONTENT_TYPE_UNKNOWN,
3952 .usage = AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING,
3953 };
3954 audio_io_handle_t dtmfOutput = AUDIO_IO_HANDLE_NONE;
3955 selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3956 portId = AUDIO_PORT_HANDLE_NONE;
3957 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
3958 48000, AUDIO_OUTPUT_FLAG_NONE, &dtmfOutput, &portId, dtmfAttr,
3959 AUDIO_SESSION_NONE, anotherUid, &isBitPerfect);
3960 EXPECT_FALSE(isBitPerfect);
3961 EXPECT_EQ(mBitPerfectOutput, dtmfOutput);
3962
3963 // When configuration matches preferred mixer attributes, which is bit-perfect, but the client
3964 // is not the owner of preferred mixer attributes, the playback will not be bit-perfect.
3965 getOutputForAttr(&selectedDeviceId, mBitPerfectFormat, mBitPerfectChannelMask,
3966 mBitPerfectSampleRate, AUDIO_OUTPUT_FLAG_NONE, &output, &portId, sMediaAttr,
3967 AUDIO_SESSION_NONE, anotherUid, &isBitPerfect);
3968 EXPECT_FALSE(isBitPerfect);
3969 EXPECT_EQ(mBitPerfectOutput, output);
3970}
3971
3972TEST_F_WITH_FLAGS(
3973 AudioPolicyManagerTestBitPerfect,
3974 InternalMuteWhenBitPerfectCLientIsActive,
3975 REQUIRES_FLAGS_ENABLED(
3976 ACONFIG_FLAG(com::android::media::audioserver,
3977 fix_concurrent_playback_behavior_with_bit_perfect_client))
3978) {
3979 ASSERT_NO_FATAL_FAILURE(startBitPerfectOutput());
3980
3981 // When bit-perfect playback is active, the system sound will be routed to bit-perfect output.
3982 // The system sound will be muted internally in this case. The bit-perfect client will be
3983 // played normally.
3984 const uint32_t anotherSampleRate = 44100;
3985 audio_port_handle_t systemSoundPortId = AUDIO_PORT_HANDLE_NONE;
3986 audio_io_handle_t systemSoundOutput = AUDIO_IO_HANDLE_NONE;
3987 const audio_attributes_t systemSoundAttr = {
3988 .content_type = AUDIO_CONTENT_TYPE_SONIFICATION,
3989 .usage = AUDIO_USAGE_ASSISTANCE_SONIFICATION,
3990 };
3991 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3992 bool isBitPerfect;
3993 getOutputForAttr(&selectedDeviceId, mBitPerfectFormat, mBitPerfectChannelMask,
3994 anotherSampleRate, AUDIO_OUTPUT_FLAG_NONE, &systemSoundOutput,
3995 &systemSoundPortId, systemSoundAttr, AUDIO_SESSION_NONE, mUid, &isBitPerfect);
3996 EXPECT_FALSE(isBitPerfect);
3997 EXPECT_EQ(mBitPerfectOutput, systemSoundOutput);
3998 EXPECT_EQ(NO_ERROR, mManager->startOutput(systemSoundPortId));
3999 EXPECT_TRUE(mClient->getTrackInternalMute(systemSoundPortId));
4000 EXPECT_FALSE(mClient->getTrackInternalMute(mBitPerfectPortId));
4001 EXPECT_EQ(NO_ERROR, mManager->stopOutput(systemSoundPortId));
4002 EXPECT_FALSE(mClient->getTrackInternalMute(mBitPerfectPortId));
4003
4004 // When bit-perfect playback is active, the notification will be routed to bit-perfect output.
4005 // The notification sound will be played normally while the bit-perfect client will be muted
4006 // internally.
4007 audio_port_handle_t notificationPortId = AUDIO_PORT_HANDLE_NONE;
4008 audio_io_handle_t notificationOutput = AUDIO_IO_HANDLE_NONE;
4009 const audio_attributes_t notificationAttr = {
4010 .content_type = AUDIO_CONTENT_TYPE_SONIFICATION,
4011 .usage = AUDIO_USAGE_NOTIFICATION,
4012 };
4013 getOutputForAttr(&selectedDeviceId, mBitPerfectFormat, mBitPerfectChannelMask,
4014 anotherSampleRate, AUDIO_OUTPUT_FLAG_NONE, &notificationOutput,
4015 &notificationPortId, notificationAttr, AUDIO_SESSION_NONE, mUid,
4016 &isBitPerfect);
4017 EXPECT_FALSE(isBitPerfect);
4018 EXPECT_EQ(mBitPerfectOutput, notificationOutput);
4019 EXPECT_EQ(NO_ERROR, mManager->startOutput(notificationPortId));
4020 EXPECT_FALSE(mClient->getTrackInternalMute(notificationPortId));
4021 EXPECT_TRUE(mClient->getTrackInternalMute(mBitPerfectPortId));
4022 EXPECT_EQ(NO_ERROR, mManager->stopOutput(notificationPortId));
4023 EXPECT_FALSE(mClient->getTrackInternalMute(mBitPerfectPortId));
4024
4025 EXPECT_EQ(NO_ERROR, mManager->stopOutput(mBitPerfectPortId));
4026}
4027
4028class AudioPolicyManagerTestBitPerfectPhoneMode : public AudioPolicyManagerTestBitPerfectBase,
4029 public testing::WithParamInterface<audio_mode_t> {
4030};
4031
4032TEST_P(AudioPolicyManagerTestBitPerfectPhoneMode, RejectBitPerfectWhenPhoneModeIsNotNormal) {
4033 if (!com::android::media::audioserver::
4034 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
4035 GTEST_SKIP()
4036 << "Flag fix_concurrent_playback_behavior_with_bit_perfect_client is not enabled";
4037 }
4038
4039 ASSERT_NO_FATAL_FAILURE(startBitPerfectOutput());
4040
4041 audio_mode_t mode = GetParam();
4042 mManager->setPhoneState(mode);
4043 // When the phone mode is not normal, the bit-perfect output will be reopned
4044 EXPECT_EQ(nullptr, mManager->getOutputs().valueFor(mBitPerfectOutput));
4045
4046 // When the phone mode is not normal, the bit-perfect output will be closed.
4047 ASSERT_NO_FATAL_FAILURE(getBitPerfectOutput(INVALID_OPERATION));
4048
4049 mManager->setPhoneState(AUDIO_MODE_NORMAL);
4050}
4051
4052INSTANTIATE_TEST_CASE_P(
4053 PhoneMode,
4054 AudioPolicyManagerTestBitPerfectPhoneMode,
4055 testing::Values(AUDIO_MODE_IN_CALL,
4056 AUDIO_MODE_RINGTONE,
4057 AUDIO_MODE_IN_COMMUNICATION,
4058 AUDIO_MODE_CALL_SCREEN)
4059);
4060
4061class AudioPolicyManagerTestBitPerfectHigherPriorityUseCaseActive :
4062 public AudioPolicyManagerTestBitPerfectBase,
4063 public testing::WithParamInterface<audio_usage_t> {
4064};
4065
4066TEST_P(AudioPolicyManagerTestBitPerfectHigherPriorityUseCaseActive,
4067 RejectBitPerfectWhenHigherPriorityUseCaseIsActive) {
4068 if (!com::android::media::audioserver::
4069 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
4070 GTEST_SKIP()
4071 << "Flag fix_concurrent_playback_behavior_with_bit_perfect_client is not enabled";
4072 }
4073
4074 ASSERT_NO_FATAL_FAILURE(startBitPerfectOutput());
4075
4076 audio_attributes_t attr = {
Mikhail Naganov806170e2024-09-05 17:26:50 -07004077 .content_type = AUDIO_CONTENT_TYPE_UNKNOWN,
jiabin220eea12024-05-17 17:55:20 +00004078 .usage = GetParam(),
jiabin220eea12024-05-17 17:55:20 +00004079 };
4080 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4081 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4082 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4083 ASSERT_NO_FATAL_FAILURE(
4084 getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
4085 48000, AUDIO_OUTPUT_FLAG_NONE, &output, &portId, attr));
4086 EXPECT_NE(mBitPerfectOutput, output);
4087 EXPECT_EQ(NO_ERROR, mManager->startOutput(portId));
4088 // When a high priority use case is active, the bit-perfect output will be closed.
4089 EXPECT_EQ(nullptr, mManager->getOutputs().valueFor(mBitPerfectOutput));
4090
4091 // When any higher priority use case is active, the bit-perfect request will be rejected.
4092 ASSERT_NO_FATAL_FAILURE(getBitPerfectOutput(INVALID_OPERATION));
4093}
4094
4095INSTANTIATE_TEST_CASE_P(
4096 HigherPriorityUseCases,
4097 AudioPolicyManagerTestBitPerfectHigherPriorityUseCaseActive,
4098 testing::Values(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE,
4099 AUDIO_USAGE_ALARM)
4100);
Eric Laurentc71b11b2024-06-03 12:54:53 +00004101
4102class AudioPolicyManagerInputPreemptionTest : public AudioPolicyManagerTestWithConfigurationFile {
4103};
4104
4105TEST_F_WITH_FLAGS(
4106 AudioPolicyManagerInputPreemptionTest,
4107 SameSessionReusesInput,
4108 REQUIRES_FLAGS_ENABLED(
4109 ACONFIG_FLAG(com::android::media::audioserver, fix_input_sharing_logic))
4110) {
4111 mClient->resetInputApiCallsCounters();
4112
4113 audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER;
4114 attr.source = AUDIO_SOURCE_MIC;
4115 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4116 audio_io_handle_t input1 = AUDIO_PORT_HANDLE_NONE;
4117 ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input1, TEST_SESSION_ID, 1, &selectedDeviceId,
4118 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
Mikhail Naganov806170e2024-09-05 17:26:50 -07004119 k48000SamplingRate));
Eric Laurentc71b11b2024-06-03 12:54:53 +00004120
4121 EXPECT_EQ(1, mClient->getOpenInputCallsCount());
4122
4123 audio_io_handle_t input2 = AUDIO_PORT_HANDLE_NONE;
4124 ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input2, TEST_SESSION_ID, 1, &selectedDeviceId,
4125 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
Mikhail Naganov806170e2024-09-05 17:26:50 -07004126 k48000SamplingRate));
Eric Laurentc71b11b2024-06-03 12:54:53 +00004127
4128 EXPECT_EQ(1, mClient->getOpenInputCallsCount());
4129 EXPECT_EQ(0, mClient->getCloseInputCallsCount());
4130 EXPECT_EQ(input1, input2);
4131}
4132
4133TEST_F_WITH_FLAGS(
4134 AudioPolicyManagerInputPreemptionTest,
4135 LesserPriorityReusesInput,
4136 REQUIRES_FLAGS_ENABLED(
4137 ACONFIG_FLAG(com::android::media::audioserver, fix_input_sharing_logic))
4138) {
4139 mClient->resetInputApiCallsCounters();
4140
4141 audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER;
4142 attr.source = AUDIO_SOURCE_MIC;
4143 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4144 audio_io_handle_t input1 = AUDIO_PORT_HANDLE_NONE;
4145 ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input1, TEST_SESSION_ID, 1, &selectedDeviceId,
4146 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
Mikhail Naganov806170e2024-09-05 17:26:50 -07004147 k48000SamplingRate));
Eric Laurentc71b11b2024-06-03 12:54:53 +00004148
4149 EXPECT_EQ(1, mClient->getOpenInputCallsCount());
4150
4151 audio_io_handle_t input2 = AUDIO_PORT_HANDLE_NONE;
4152 attr.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4153 ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input2, OTHER_SESSION_ID, 1, &selectedDeviceId,
4154 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
Mikhail Naganov806170e2024-09-05 17:26:50 -07004155 k48000SamplingRate));
Eric Laurentc71b11b2024-06-03 12:54:53 +00004156
4157 EXPECT_EQ(1, mClient->getOpenInputCallsCount());
4158 EXPECT_EQ(0, mClient->getCloseInputCallsCount());
4159 EXPECT_EQ(input1, input2);
4160}
4161
4162TEST_F_WITH_FLAGS(
4163 AudioPolicyManagerInputPreemptionTest,
4164 HigherPriorityPreemptsInput,
4165 REQUIRES_FLAGS_ENABLED(
4166 ACONFIG_FLAG(com::android::media::audioserver, fix_input_sharing_logic))
4167) {
4168 mClient->resetInputApiCallsCounters();
4169
4170 audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER;
4171 attr.source = AUDIO_SOURCE_MIC;
4172 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4173 audio_io_handle_t input1 = AUDIO_PORT_HANDLE_NONE;
4174 ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input1, TEST_SESSION_ID, 1, &selectedDeviceId,
4175 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
Mikhail Naganov806170e2024-09-05 17:26:50 -07004176 k48000SamplingRate));
Eric Laurentc71b11b2024-06-03 12:54:53 +00004177
4178 EXPECT_EQ(1, mClient->getOpenInputCallsCount());
4179
4180 audio_io_handle_t input2 = AUDIO_PORT_HANDLE_NONE;
4181 attr.source = AUDIO_SOURCE_CAMCORDER;
4182 ASSERT_NO_FATAL_FAILURE(getInputForAttr(attr, &input2, OTHER_SESSION_ID, 1, &selectedDeviceId,
4183 AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_STEREO,
Mikhail Naganov806170e2024-09-05 17:26:50 -07004184 k48000SamplingRate));
Eric Laurentc71b11b2024-06-03 12:54:53 +00004185
4186 EXPECT_EQ(2, mClient->getOpenInputCallsCount());
4187 EXPECT_EQ(1, mClient->getCloseInputCallsCount());
4188 EXPECT_NE(input1, input2);
4189}
Mikhail Naganov70b52652024-09-06 10:23:24 -07004190
4191int main(int argc, char** argv) {
4192 ::testing::InitGoogleTest(&argc, argv);
4193 ::testing::UnitTest::GetInstance()->listeners().Append(new TestExecutionTracer());
4194 return RUN_ALL_TESTS();
4195}