blob: 0cdf0f2c7fdf4d827504e8ca4e32eba1e1a69d5f [file] [log] [blame]
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001/*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Hal2AidlMapper"
18// #define LOG_NDEBUG 0
19
20#include <algorithm>
21
22#include <media/audiohal/StreamHalInterface.h>
23#include <error/expected_utils.h>
24#include <system/audio.h> // For AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS
25#include <Utils.h>
26#include <utils/Log.h>
27
Jaideep Sharma145313e2024-08-14 14:51:24 +053028#include "AidlUtils.h"
Mikhail Naganovac9d4e72023-10-23 12:00:09 -070029#include "Hal2AidlMapper.h"
30
31using aidl::android::aidl_utils::statusTFromBinderStatus;
32using aidl::android::media::audio::common::AudioChannelLayout;
33using aidl::android::media::audio::common::AudioConfig;
Mikhail Naganovca92a5c2023-12-07 14:00:48 -080034using aidl::android::media::audio::common::AudioConfigBase;
Mikhail Naganovac9d4e72023-10-23 12:00:09 -070035using aidl::android::media::audio::common::AudioDevice;
36using aidl::android::media::audio::common::AudioDeviceAddress;
37using aidl::android::media::audio::common::AudioDeviceDescription;
38using aidl::android::media::audio::common::AudioDeviceType;
39using aidl::android::media::audio::common::AudioFormatDescription;
Mikhail Naganovca92a5c2023-12-07 14:00:48 -080040using aidl::android::media::audio::common::AudioFormatType;
Mikhail Naganov1a2e0ff2024-06-11 15:53:46 -070041using aidl::android::media::audio::common::AudioGainConfig;
Mikhail Naganovac9d4e72023-10-23 12:00:09 -070042using aidl::android::media::audio::common::AudioInputFlags;
43using aidl::android::media::audio::common::AudioIoFlags;
44using aidl::android::media::audio::common::AudioOutputFlags;
45using aidl::android::media::audio::common::AudioPort;
46using aidl::android::media::audio::common::AudioPortConfig;
47using aidl::android::media::audio::common::AudioPortDeviceExt;
48using aidl::android::media::audio::common::AudioPortExt;
49using aidl::android::media::audio::common::AudioPortMixExt;
50using aidl::android::media::audio::common::AudioPortMixExtUseCase;
51using aidl::android::media::audio::common::AudioProfile;
52using aidl::android::media::audio::common::AudioSource;
53using aidl::android::media::audio::common::Int;
54using aidl::android::hardware::audio::common::isBitPositionFlagSet;
55using aidl::android::hardware::audio::common::isDefaultAudioFormat;
56using aidl::android::hardware::audio::common::makeBitPositionFlagMask;
57using aidl::android::hardware::audio::core::AudioPatch;
58using aidl::android::hardware::audio::core::AudioRoute;
59using aidl::android::hardware::audio::core::IModule;
60
61namespace android {
62
63namespace {
64
65bool isConfigEqualToPortConfig(const AudioConfig& config, const AudioPortConfig& portConfig) {
66 return portConfig.sampleRate.value().value == config.base.sampleRate &&
67 portConfig.channelMask.value() == config.base.channelMask &&
68 portConfig.format.value() == config.base.format;
69}
70
Mikhail Naganovca92a5c2023-12-07 14:00:48 -080071AudioConfig* setConfigFromPortConfig(AudioConfig* config, const AudioPortConfig& portConfig) {
Mikhail Naganovac9d4e72023-10-23 12:00:09 -070072 config->base.sampleRate = portConfig.sampleRate.value().value;
73 config->base.channelMask = portConfig.channelMask.value();
74 config->base.format = portConfig.format.value();
Mikhail Naganovca92a5c2023-12-07 14:00:48 -080075 return config;
Mikhail Naganovac9d4e72023-10-23 12:00:09 -070076}
77
78void setPortConfigFromConfig(AudioPortConfig* portConfig, const AudioConfig& config) {
79 if (config.base.sampleRate != 0) {
80 portConfig->sampleRate = Int{ .value = config.base.sampleRate };
81 }
82 if (config.base.channelMask != AudioChannelLayout{}) {
83 portConfig->channelMask = config.base.channelMask;
84 }
85 if (config.base.format != AudioFormatDescription{}) {
86 portConfig->format = config.base.format;
87 }
88}
89
jiabin80797002023-12-01 22:02:41 +000090bool containHapticChannel(AudioChannelLayout channel) {
91 return channel.getTag() == AudioChannelLayout::Tag::layoutMask &&
92 ((channel.get<AudioChannelLayout::Tag::layoutMask>()
93 & AudioChannelLayout::CHANNEL_HAPTIC_A)
94 == AudioChannelLayout::CHANNEL_HAPTIC_A ||
95 (channel.get<AudioChannelLayout::Tag::layoutMask>()
96 & AudioChannelLayout::CHANNEL_HAPTIC_B)
97 == AudioChannelLayout::CHANNEL_HAPTIC_B);
98}
99
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700100} // namespace
101
102Hal2AidlMapper::Hal2AidlMapper(const std::string& instance, const std::shared_ptr<IModule>& module)
Jaideep Sharma145313e2024-08-14 14:51:24 +0530103 : ConversionHelperAidl("Hal2AidlMapper", instance), mModule(module) {}
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700104
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -0800105void Hal2AidlMapper::addStream(
Mikhail Naganova317a802024-03-15 18:03:10 +0000106 const sp<StreamHalInterface>& stream, int32_t mixPortConfigId, int32_t patchId) {
107 mStreams.insert(std::pair(stream, std::pair(mixPortConfigId, patchId)));
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700108}
109
110bool Hal2AidlMapper::audioDeviceMatches(const AudioDevice& device, const AudioPort& p) {
111 if (p.ext.getTag() != AudioPortExt::Tag::device) return false;
112 return p.ext.get<AudioPortExt::Tag::device>().device == device;
113}
114
115bool Hal2AidlMapper::audioDeviceMatches(const AudioDevice& device, const AudioPortConfig& p) {
116 if (p.ext.getTag() != AudioPortExt::Tag::device) return false;
117 if (device.type.type == AudioDeviceType::IN_DEFAULT) {
118 return p.portId == mDefaultInputPortId;
119 } else if (device.type.type == AudioDeviceType::OUT_DEFAULT) {
120 return p.portId == mDefaultOutputPortId;
121 }
122 return p.ext.get<AudioPortExt::Tag::device>().device == device;
123}
124
125status_t Hal2AidlMapper::createOrUpdatePatch(
126 const std::vector<AudioPortConfig>& sources,
127 const std::vector<AudioPortConfig>& sinks,
128 int32_t* patchId, Cleanups* cleanups) {
129 auto existingPatchIt = *patchId != 0 ? mPatches.find(*patchId): mPatches.end();
130 AudioPatch patch;
131 if (existingPatchIt != mPatches.end()) {
132 patch = existingPatchIt->second;
133 patch.sourcePortConfigIds.clear();
134 patch.sinkPortConfigIds.clear();
135 }
136 // The IDs will be found by 'fillPortConfigs', however the original 'sources' and
137 // 'sinks' will not be updated because 'setAudioPatch' only needs IDs. Here we log
138 // the source arguments, where only the audio configuration and device specifications
139 // are relevant.
Jaideep Sharma145313e2024-08-14 14:51:24 +0530140 AUGMENT_LOG(D, "patch ID: %d, [disregard IDs] sources: %s, sinks: %s", *patchId,
141 ::android::internal::ToString(sources).c_str(),
142 ::android::internal::ToString(sinks).c_str());
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700143 auto fillPortConfigs = [&](
144 const std::vector<AudioPortConfig>& configs,
145 const std::set<int32_t>& destinationPortIds,
146 std::vector<int32_t>* ids, std::set<int32_t>* portIds) -> status_t {
147 for (const auto& s : configs) {
148 AudioPortConfig portConfig;
Mikhail Naganov38220af2023-12-07 14:00:48 -0800149 if (status_t status = setPortConfig(
150 s, destinationPortIds, &portConfig, cleanups); status != OK) {
151 if (s.ext.getTag() == AudioPortExt::mix) {
152 // See b/315528763. Despite that the framework knows the actual format of
153 // the mix port, it still uses the original format. Luckily, there is
154 // the I/O handle which can be used to find the mix port.
Jaideep Sharma145313e2024-08-14 14:51:24 +0530155 AUGMENT_LOG(I,
156 "fillPortConfigs: retrying to find a mix port config with"
157 " default configuration");
Mikhail Naganov38220af2023-12-07 14:00:48 -0800158 if (auto it = findPortConfig(std::nullopt, s.flags,
159 s.ext.get<AudioPortExt::mix>().handle);
160 it != mPortConfigs.end()) {
161 portConfig = it->second;
162 } else {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530163 const std::string flags =
164 s.flags.has_value() ? s.flags->toString() : "<unspecified>";
165 AUGMENT_LOG(E,
166 "fillPortConfigs: existing port config for flags %s, "
167 " handle %d not found",
168 flags.c_str(), s.ext.get<AudioPortExt::mix>().handle);
Mikhail Naganov38220af2023-12-07 14:00:48 -0800169 return BAD_VALUE;
170 }
171 } else {
172 return status;
173 }
174 }
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800175 LOG_ALWAYS_FATAL_IF(portConfig.id == 0,
Jaideep Sharma145313e2024-08-14 14:51:24 +0530176 "fillPortConfigs: initial config: %s, port config: %s",
177 s.toString().c_str(), portConfig.toString().c_str());
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700178 ids->push_back(portConfig.id);
179 if (portIds != nullptr) {
180 portIds->insert(portConfig.portId);
181 }
182 }
183 return OK;
184 };
185 // When looking up port configs, the destinationPortId is only used for mix ports.
186 // Thus, we process device port configs first, and look up the destination port ID from them.
Mikhail Naganov03b0a002024-05-03 20:22:58 +0000187 const bool sourceIsDevice = std::any_of(sources.begin(), sources.end(),
188 [](const auto& config) { return config.ext.getTag() == AudioPortExt::device; });
189 const bool sinkIsDevice = std::any_of(sinks.begin(), sinks.end(),
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700190 [](const auto& config) { return config.ext.getTag() == AudioPortExt::device; });
191 const std::vector<AudioPortConfig>& devicePortConfigs =
192 sourceIsDevice ? sources : sinks;
193 std::vector<int32_t>* devicePortConfigIds =
194 sourceIsDevice ? &patch.sourcePortConfigIds : &patch.sinkPortConfigIds;
195 const std::vector<AudioPortConfig>& mixPortConfigs =
196 sourceIsDevice ? sinks : sources;
197 std::vector<int32_t>* mixPortConfigIds =
198 sourceIsDevice ? &patch.sinkPortConfigIds : &patch.sourcePortConfigIds;
199 std::set<int32_t> devicePortIds;
200 RETURN_STATUS_IF_ERROR(fillPortConfigs(
201 devicePortConfigs, std::set<int32_t>(), devicePortConfigIds, &devicePortIds));
202 RETURN_STATUS_IF_ERROR(fillPortConfigs(
203 mixPortConfigs, devicePortIds, mixPortConfigIds, nullptr));
204 if (existingPatchIt != mPatches.end()) {
205 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
206 mModule->setAudioPatch(patch, &patch)));
207 existingPatchIt->second = patch;
208 } else {
209 bool created = false;
Mikhail Naganov03b0a002024-05-03 20:22:58 +0000210 // When the framework does not specify a patch ID, only the mix port config
211 // is used for finding an existing patch. That's because the framework assumes
212 // that there can only be one patch for an I/O thread.
213 PatchMatch match = sourceIsDevice && sinkIsDevice ?
214 MATCH_BOTH : (sourceIsDevice ? MATCH_SINKS : MATCH_SOURCES);
Mikhail Naganov6ed595c2024-05-31 16:16:03 +0000215 auto requestedPatch = patch;
Mikhail Naganov03b0a002024-05-03 20:22:58 +0000216 RETURN_STATUS_IF_ERROR(findOrCreatePatch(patch, match,
217 &patch, &created));
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -0800218 // No cleanup of the patch is needed, it is managed by the framework.
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700219 *patchId = patch.id;
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -0800220 if (!created) {
Mikhail Naganov6ed595c2024-05-31 16:16:03 +0000221 requestedPatch.id = patch.id;
222 if (patch != requestedPatch) {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530223 AUGMENT_LOG(I, "Updating transient patch. Current: %s, new: %s",
224 patch.toString().c_str(), requestedPatch.toString().c_str());
Mikhail Naganov6ed595c2024-05-31 16:16:03 +0000225 // Since matching may be done by mix port only, update the patch if the device port
226 // config has changed.
227 patch = requestedPatch;
228 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
229 mModule->setAudioPatch(patch, &patch)));
230 existingPatchIt = mPatches.find(patch.id);
231 existingPatchIt->second = patch;
232 }
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -0800233 // The framework might have "created" a patch which already existed due to
234 // stream creation. Need to release the ownership from the stream.
235 for (auto& s : mStreams) {
236 if (s.second.second == patch.id) s.second.second = -1;
237 }
238 }
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700239 }
240 return OK;
241}
242
243status_t Hal2AidlMapper::createOrUpdatePortConfig(
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800244 const AudioPortConfig& requestedPortConfig, AudioPortConfig* result, bool* created) {
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700245 bool applied = false;
246 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->setAudioPortConfig(
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800247 requestedPortConfig, result, &applied)));
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700248 if (!applied) {
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800249 result->id = 0;
250 *created = false;
251 return OK;
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700252 }
253
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800254 int32_t id = result->id;
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700255 if (requestedPortConfig.id != 0 && requestedPortConfig.id != id) {
256 LOG_ALWAYS_FATAL("%s: requested port config id %d changed to %d", __func__,
Jaideep Sharma145313e2024-08-14 14:51:24 +0530257 requestedPortConfig.id, id);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700258 }
259
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800260 auto [_, inserted] = mPortConfigs.insert_or_assign(id, *result);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700261 *created = inserted;
262 return OK;
263}
264
David Lifef5d0c2024-01-11 16:57:17 +0000265status_t Hal2AidlMapper::createOrUpdatePortConfigRetry(
266 const AudioPortConfig& requestedPortConfig, AudioPortConfig* result, bool* created) {
267 AudioPortConfig suggestedOrAppliedPortConfig;
268 RETURN_STATUS_IF_ERROR(createOrUpdatePortConfig(requestedPortConfig,
269 &suggestedOrAppliedPortConfig, created));
270 if (suggestedOrAppliedPortConfig.id == 0) {
271 // Try again with the suggested config
272 suggestedOrAppliedPortConfig.id = requestedPortConfig.id;
273 AudioPortConfig appliedPortConfig;
274 RETURN_STATUS_IF_ERROR(createOrUpdatePortConfig(suggestedOrAppliedPortConfig,
275 &appliedPortConfig, created));
276 if (appliedPortConfig.id == 0) {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530277 AUGMENT_LOG(E, "did not apply suggested config %s",
278 suggestedOrAppliedPortConfig.toString().c_str());
David Lifef5d0c2024-01-11 16:57:17 +0000279 return NO_INIT;
280 }
281 *result = appliedPortConfig;
282 } else {
283 *result = suggestedOrAppliedPortConfig;
284 }
285 return OK;
286}
287
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700288void Hal2AidlMapper::eraseConnectedPort(int32_t portId) {
289 mPorts.erase(portId);
290 mConnectedPorts.erase(portId);
291 if (mDisconnectedPortReplacement.first == portId) {
292 const auto& port = mDisconnectedPortReplacement.second;
293 mPorts.insert(std::make_pair(port.id, port));
Jaideep Sharma145313e2024-08-14 14:51:24 +0530294 AUGMENT_LOG(D, "disconnected port replacement: %s", port.toString().c_str());
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700295 mDisconnectedPortReplacement = std::pair<int32_t, AudioPort>();
296 }
jiabin255ff7f2024-01-11 00:24:47 +0000297 updateDynamicMixPorts();
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700298}
299
300status_t Hal2AidlMapper::findOrCreatePatch(
Mikhail Naganov03b0a002024-05-03 20:22:58 +0000301 const AudioPatch& requestedPatch, PatchMatch match, AudioPatch* patch, bool* created) {
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700302 std::set<int32_t> sourcePortConfigIds(requestedPatch.sourcePortConfigIds.begin(),
303 requestedPatch.sourcePortConfigIds.end());
304 std::set<int32_t> sinkPortConfigIds(requestedPatch.sinkPortConfigIds.begin(),
305 requestedPatch.sinkPortConfigIds.end());
Mikhail Naganov03b0a002024-05-03 20:22:58 +0000306 return findOrCreatePatch(sourcePortConfigIds, sinkPortConfigIds, match, patch, created);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700307}
308
309status_t Hal2AidlMapper::findOrCreatePatch(
310 const std::set<int32_t>& sourcePortConfigIds, const std::set<int32_t>& sinkPortConfigIds,
Mikhail Naganov03b0a002024-05-03 20:22:58 +0000311 PatchMatch match, AudioPatch* patch, bool* created) {
312 auto patchIt = findPatch(sourcePortConfigIds, sinkPortConfigIds, match);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700313 if (patchIt == mPatches.end()) {
314 AudioPatch requestedPatch, appliedPatch;
315 requestedPatch.sourcePortConfigIds.insert(requestedPatch.sourcePortConfigIds.end(),
316 sourcePortConfigIds.begin(), sourcePortConfigIds.end());
317 requestedPatch.sinkPortConfigIds.insert(requestedPatch.sinkPortConfigIds.end(),
318 sinkPortConfigIds.begin(), sinkPortConfigIds.end());
319 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->setAudioPatch(
320 requestedPatch, &appliedPatch)));
321 patchIt = mPatches.insert(mPatches.end(), std::make_pair(appliedPatch.id, appliedPatch));
322 *created = true;
323 } else {
324 *created = false;
325 }
326 *patch = patchIt->second;
327 return OK;
328}
329
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800330status_t Hal2AidlMapper::findOrCreateDevicePortConfig(
Mikhail Naganov1a2e0ff2024-06-11 15:53:46 -0700331 const AudioDevice& device, const AudioConfig* config, const AudioGainConfig* gainConfig,
332 AudioPortConfig* portConfig, bool* created) {
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800333 if (auto portConfigIt = findPortConfig(device); portConfigIt == mPortConfigs.end()) {
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700334 auto portsIt = findPort(device);
335 if (portsIt == mPorts.end()) {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530336 AUGMENT_LOG(E, "device port for device %s is not found", device.toString().c_str());
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700337 return BAD_VALUE;
338 }
339 AudioPortConfig requestedPortConfig;
340 requestedPortConfig.portId = portsIt->first;
341 if (config != nullptr) {
342 setPortConfigFromConfig(&requestedPortConfig, *config);
343 }
Mikhail Naganov1a2e0ff2024-06-11 15:53:46 -0700344 if (gainConfig != nullptr) {
345 requestedPortConfig.gain = *gainConfig;
346 }
David Lifef5d0c2024-01-11 16:57:17 +0000347 return createOrUpdatePortConfigRetry(requestedPortConfig, portConfig, created);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700348 } else {
David Lifef5d0c2024-01-11 16:57:17 +0000349 AudioPortConfig requestedPortConfig = portConfigIt->second;
350 if (config != nullptr) {
351 setPortConfigFromConfig(&requestedPortConfig, *config);
352 }
Mikhail Naganov1a2e0ff2024-06-11 15:53:46 -0700353 if (gainConfig != nullptr) {
354 requestedPortConfig.gain = *gainConfig;
355 }
David Lifef5d0c2024-01-11 16:57:17 +0000356
357 if (requestedPortConfig != portConfigIt->second) {
358 return createOrUpdatePortConfigRetry(requestedPortConfig, portConfig, created);
359 } else {
360 *portConfig = portConfigIt->second;
361 *created = false;
362 }
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700363 }
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700364 return OK;
365}
366
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800367status_t Hal2AidlMapper::findOrCreateMixPortConfig(
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700368 const AudioConfig& config, const std::optional<AudioIoFlags>& flags, int32_t ioHandle,
369 AudioSource source, const std::set<int32_t>& destinationPortIds,
370 AudioPortConfig* portConfig, bool* created) {
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800371 if (auto portConfigIt = findPortConfig(config, flags, ioHandle);
372 portConfigIt == mPortConfigs.end() && flags.has_value()) {
Dean Wheatleyd27bbb92024-01-19 15:54:35 +1100373 // These input flags get removed one by one in this order when retrying port finding.
374 std::vector<AudioInputFlags> optionalInputFlags {
375 AudioInputFlags::FAST, AudioInputFlags::RAW, AudioInputFlags::VOIP_TX };
376 // For remote submix input, retry with direct input flag removed as the remote submix
377 // input is not expected to manipulate the contents of the audio stream.
378 if (mRemoteSubmixIn.has_value()) {
379 optionalInputFlags.push_back(AudioInputFlags::DIRECT);
380 }
381 auto optionalInputFlagsIt = optionalInputFlags.begin();
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700382 AudioIoFlags matchFlags = flags.value();
383 auto portsIt = findPort(config, matchFlags, destinationPortIds);
384 while (portsIt == mPorts.end() && matchFlags.getTag() == AudioIoFlags::Tag::input
Dean Wheatleyd27bbb92024-01-19 15:54:35 +1100385 && optionalInputFlagsIt != optionalInputFlags.end()) {
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700386 if (!isBitPositionFlagSet(
387 matchFlags.get<AudioIoFlags::Tag::input>(), *optionalInputFlagsIt)) {
388 ++optionalInputFlagsIt;
389 continue;
390 }
391 matchFlags.set<AudioIoFlags::Tag::input>(matchFlags.get<AudioIoFlags::Tag::input>() &
392 ~makeBitPositionFlagMask(*optionalInputFlagsIt++));
393 portsIt = findPort(config, matchFlags, destinationPortIds);
Jaideep Sharma145313e2024-08-14 14:51:24 +0530394 AUGMENT_LOG(I,
395 "mix port for config %s, flags %s was not found"
396 "retried with flags %s",
397 config.toString().c_str(), flags.value().toString().c_str(),
398 matchFlags.toString().c_str());
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700399 }
Dean Wheatleyd27bbb92024-01-19 15:54:35 +1100400 // These output flags get removed one by one in this order when retrying port finding.
401 std::vector<AudioOutputFlags> optionalOutputFlags { };
402 // For remote submix output, retry with these output flags removed one by one:
403 // 1. DIRECT: remote submix outputs are expected not to manipulate the contents of the
404 // audio stream.
405 // 2. IEC958_NONAUDIO: remote submix outputs are not connected to ALSA and do not require
406 // non audio signalling.
407 if (mRemoteSubmixOut.has_value()) {
408 optionalOutputFlags.push_back(AudioOutputFlags::DIRECT);
409 optionalOutputFlags.push_back(AudioOutputFlags::IEC958_NONAUDIO);
410 }
411 auto optionalOutputFlagsIt = optionalOutputFlags.begin();
412 matchFlags = flags.value();
413 while (portsIt == mPorts.end() && matchFlags.getTag() == AudioIoFlags::Tag::output
414 && optionalOutputFlagsIt != optionalOutputFlags.end()) {
415 if (!isBitPositionFlagSet(
416 matchFlags.get<AudioIoFlags::Tag::output>(),*optionalOutputFlagsIt)) {
417 ++optionalOutputFlagsIt;
418 continue;
419 }
420 matchFlags.set<AudioIoFlags::Tag::output>(matchFlags.get<AudioIoFlags::Tag::output>() &
421 ~makeBitPositionFlagMask(*optionalOutputFlagsIt++));
422 portsIt = findPort(config, matchFlags, destinationPortIds);
423 AUGMENT_LOG(I,
424 "mix port for config %s, flags %s was not found"
425 "retried with flags %s",
426 config.toString().c_str(), flags.value().toString().c_str(),
427 matchFlags.toString().c_str());
428 }
429
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700430 if (portsIt == mPorts.end()) {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530431 AUGMENT_LOG(E, "mix port for config %s, flags %s is not found",
432 config.toString().c_str(), matchFlags.toString().c_str());
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700433 return BAD_VALUE;
434 }
435 AudioPortConfig requestedPortConfig;
436 requestedPortConfig.portId = portsIt->first;
437 setPortConfigFromConfig(&requestedPortConfig, config);
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800438 requestedPortConfig.flags = portsIt->second.flags;
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700439 requestedPortConfig.ext = AudioPortMixExt{ .handle = ioHandle };
440 if (matchFlags.getTag() == AudioIoFlags::Tag::input
441 && source != AudioSource::SYS_RESERVED_INVALID) {
442 requestedPortConfig.ext.get<AudioPortExt::Tag::mix>().usecase =
443 AudioPortMixExtUseCase::make<AudioPortMixExtUseCase::Tag::source>(source);
444 }
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800445 return createOrUpdatePortConfig(requestedPortConfig, portConfig, created);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700446 } else if (portConfigIt == mPortConfigs.end() && !flags.has_value()) {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530447 AUGMENT_LOG(W,
448 "mix port config for %s, handle %d not found "
449 "and was not created as flags are not specified",
450 config.toString().c_str(), ioHandle);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700451 return BAD_VALUE;
452 } else {
453 AudioPortConfig requestedPortConfig = portConfigIt->second;
David Lifef5d0c2024-01-11 16:57:17 +0000454 setPortConfigFromConfig(&requestedPortConfig, config);
455
456 AudioPortMixExt& mixExt = requestedPortConfig.ext.get<AudioPortExt::Tag::mix>();
457 if (mixExt.usecase.getTag() == AudioPortMixExtUseCase::Tag::source &&
458 source != AudioSource::SYS_RESERVED_INVALID) {
459 mixExt.usecase.get<AudioPortMixExtUseCase::Tag::source>() = source;
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700460 }
461
462 if (requestedPortConfig != portConfigIt->second) {
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800463 return createOrUpdatePortConfig(requestedPortConfig, portConfig, created);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700464 } else {
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800465 *portConfig = portConfigIt->second;
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700466 *created = false;
467 }
468 }
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700469 return OK;
470}
471
472status_t Hal2AidlMapper::findOrCreatePortConfig(
473 const AudioPortConfig& requestedPortConfig, const std::set<int32_t>& destinationPortIds,
474 AudioPortConfig* portConfig, bool* created) {
475 using Tag = AudioPortExt::Tag;
476 if (requestedPortConfig.ext.getTag() == Tag::mix) {
477 if (const auto& p = requestedPortConfig;
478 !p.sampleRate.has_value() || !p.channelMask.has_value() ||
479 !p.format.has_value()) {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530480 AUGMENT_LOG(W, "provided mix port config is not fully specified: %s",
481 p.toString().c_str());
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700482 return BAD_VALUE;
483 }
484 AudioConfig config;
485 setConfigFromPortConfig(&config, requestedPortConfig);
486 AudioSource source = requestedPortConfig.ext.get<Tag::mix>().usecase.getTag() ==
487 AudioPortMixExtUseCase::Tag::source ?
488 requestedPortConfig.ext.get<Tag::mix>().usecase.
489 get<AudioPortMixExtUseCase::Tag::source>() : AudioSource::SYS_RESERVED_INVALID;
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800490 return findOrCreateMixPortConfig(config, requestedPortConfig.flags,
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700491 requestedPortConfig.ext.get<Tag::mix>().handle, source, destinationPortIds,
492 portConfig, created);
493 } else if (requestedPortConfig.ext.getTag() == Tag::device) {
Mikhail Naganov1a2e0ff2024-06-11 15:53:46 -0700494 const auto& p = requestedPortConfig;
495 const bool hasAudioConfig =
496 p.sampleRate.has_value() && p.channelMask.has_value() && p.format.has_value();
497 const bool hasGainConfig = p.gain.has_value();
498 if (hasAudioConfig || hasGainConfig) {
499 AudioConfig config, *configPtr = nullptr;
500 if (hasAudioConfig) {
501 setConfigFromPortConfig(&config, requestedPortConfig);
502 configPtr = &config;
503 }
504 const AudioGainConfig* gainConfigPtr = nullptr;
505 if (hasGainConfig) gainConfigPtr = &(*(p.gain));
David Lifef5d0c2024-01-11 16:57:17 +0000506 return findOrCreateDevicePortConfig(
Mikhail Naganov1a2e0ff2024-06-11 15:53:46 -0700507 requestedPortConfig.ext.get<Tag::device>().device, configPtr, gainConfigPtr,
David Lifef5d0c2024-01-11 16:57:17 +0000508 portConfig, created);
509 } else {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530510 AUGMENT_LOG(D, "device port config does not have audio or gain config specified");
David Lifef5d0c2024-01-11 16:57:17 +0000511 return findOrCreateDevicePortConfig(
512 requestedPortConfig.ext.get<Tag::device>().device, nullptr /*config*/,
Mikhail Naganov1a2e0ff2024-06-11 15:53:46 -0700513 nullptr /*gainConfig*/, portConfig, created);
David Lifef5d0c2024-01-11 16:57:17 +0000514 }
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700515 }
Jaideep Sharma145313e2024-08-14 14:51:24 +0530516 AUGMENT_LOG(W, "unsupported audio port config: %s", requestedPortConfig.toString().c_str());
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700517 return BAD_VALUE;
518}
519
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700520status_t Hal2AidlMapper::findPortConfig(const AudioDevice& device, AudioPortConfig* portConfig) {
521 if (auto it = findPortConfig(device); it != mPortConfigs.end()) {
522 *portConfig = it->second;
523 return OK;
524 }
Jaideep Sharma145313e2024-08-14 14:51:24 +0530525 AUGMENT_LOG(E, "could not find a device port config for device %s", device.toString().c_str());
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700526 return BAD_VALUE;
527}
528
529Hal2AidlMapper::Patches::iterator Hal2AidlMapper::findPatch(
Mikhail Naganov03b0a002024-05-03 20:22:58 +0000530 const std::set<int32_t>& sourcePortConfigIds, const std::set<int32_t>& sinkPortConfigIds,
531 PatchMatch match) {
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700532 return std::find_if(mPatches.begin(), mPatches.end(),
533 [&](const auto& pair) {
534 const auto& p = pair.second;
535 std::set<int32_t> patchSrcs(
536 p.sourcePortConfigIds.begin(), p.sourcePortConfigIds.end());
537 std::set<int32_t> patchSinks(
538 p.sinkPortConfigIds.begin(), p.sinkPortConfigIds.end());
Mikhail Naganov03b0a002024-05-03 20:22:58 +0000539 switch (match) {
540 case MATCH_SOURCES:
541 return sourcePortConfigIds == patchSrcs;
542 case MATCH_SINKS:
543 return sinkPortConfigIds == patchSinks;
544 case MATCH_BOTH:
545 return sourcePortConfigIds == patchSrcs && sinkPortConfigIds == patchSinks;
546 }
547 });
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700548}
549
550Hal2AidlMapper::Ports::iterator Hal2AidlMapper::findPort(const AudioDevice& device) {
551 if (device.type.type == AudioDeviceType::IN_DEFAULT) {
552 return mPorts.find(mDefaultInputPortId);
553 } else if (device.type.type == AudioDeviceType::OUT_DEFAULT) {
554 return mPorts.find(mDefaultOutputPortId);
555 }
556 if (device.address.getTag() != AudioDeviceAddress::id ||
557 !device.address.get<AudioDeviceAddress::id>().empty()) {
558 return std::find_if(mPorts.begin(), mPorts.end(),
559 [&](const auto& pair) { return audioDeviceMatches(device, pair.second); });
560 }
561 // For connection w/o an address, two ports can be found: the template port,
562 // and a connected port (if exists). Make sure we return the connected port.
563 Hal2AidlMapper::Ports::iterator portIt = mPorts.end();
564 for (auto it = mPorts.begin(); it != mPorts.end(); ++it) {
565 if (audioDeviceMatches(device, it->second)) {
566 if (mConnectedPorts.find(it->first) != mConnectedPorts.end()) {
567 return it;
568 } else {
569 // Will return 'it' if there is no connected port.
570 portIt = it;
571 }
572 }
573 }
574 return portIt;
575}
576
577Hal2AidlMapper::Ports::iterator Hal2AidlMapper::findPort(
578 const AudioConfig& config, const AudioIoFlags& flags,
579 const std::set<int32_t>& destinationPortIds) {
jiabin80797002023-12-01 22:02:41 +0000580 auto channelMaskMatches = [](const std::vector<AudioChannelLayout>& channelMasks,
581 const AudioChannelLayout& channelMask) {
582 // Return true when 1) the channel mask is none and none of the channel mask from the
583 // collection contains haptic channel mask, or 2) the channel mask collection contains
584 // the queried channel mask.
585 return (channelMask.getTag() == AudioChannelLayout::none &&
586 std::none_of(channelMasks.begin(), channelMasks.end(),
587 containHapticChannel)) ||
588 std::find(channelMasks.begin(), channelMasks.end(), channelMask)
589 != channelMasks.end();
590 };
591 auto belongsToProfile = [&config, &channelMaskMatches](const AudioProfile& prof) {
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700592 return (isDefaultAudioFormat(config.base.format) || prof.format == config.base.format) &&
jiabin80797002023-12-01 22:02:41 +0000593 channelMaskMatches(prof.channelMasks, config.base.channelMask) &&
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700594 (config.base.sampleRate == 0 ||
595 std::find(prof.sampleRates.begin(), prof.sampleRates.end(),
596 config.base.sampleRate) != prof.sampleRates.end());
597 };
598 static const std::vector<AudioOutputFlags> kOptionalOutputFlags{AudioOutputFlags::BIT_PERFECT};
599 int optionalFlags = 0;
600 auto flagMatches = [&flags, &optionalFlags](const AudioIoFlags& portFlags) {
601 // Ports should be able to match if the optional flags are not requested.
602 return portFlags == flags ||
603 (portFlags.getTag() == AudioIoFlags::Tag::output &&
604 AudioIoFlags::make<AudioIoFlags::Tag::output>(
605 portFlags.get<AudioIoFlags::Tag::output>() &
606 ~optionalFlags) == flags);
607 };
608 auto matcher = [&](const auto& pair) {
609 const auto& p = pair.second;
610 return p.ext.getTag() == AudioPortExt::Tag::mix &&
611 flagMatches(p.flags) &&
612 (destinationPortIds.empty() ||
613 std::any_of(destinationPortIds.begin(), destinationPortIds.end(),
614 [&](const int32_t destId) { return mRoutingMatrix.count(
615 std::make_pair(p.id, destId)) != 0; })) &&
616 (p.profiles.empty() ||
617 std::find_if(p.profiles.begin(), p.profiles.end(), belongsToProfile) !=
618 p.profiles.end()); };
619 auto result = std::find_if(mPorts.begin(), mPorts.end(), matcher);
620 if (result == mPorts.end() && flags.getTag() == AudioIoFlags::Tag::output) {
621 auto optionalOutputFlagsIt = kOptionalOutputFlags.begin();
622 while (result == mPorts.end() && optionalOutputFlagsIt != kOptionalOutputFlags.end()) {
623 if (isBitPositionFlagSet(
624 flags.get<AudioIoFlags::Tag::output>(), *optionalOutputFlagsIt)) {
625 // If the flag is set by the request, it must be matched.
626 ++optionalOutputFlagsIt;
627 continue;
628 }
629 optionalFlags |= makeBitPositionFlagMask(*optionalOutputFlagsIt++);
630 result = std::find_if(mPorts.begin(), mPorts.end(), matcher);
Jaideep Sharma145313e2024-08-14 14:51:24 +0530631 AUGMENT_LOG(I,
632 "port for config %s, flags %s was not found "
633 "retried with excluding optional flags %#x",
634 config.toString().c_str(), flags.toString().c_str(), optionalFlags);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700635 }
636 }
637 return result;
638}
639
640Hal2AidlMapper::PortConfigs::iterator Hal2AidlMapper::findPortConfig(const AudioDevice& device) {
641 return std::find_if(mPortConfigs.begin(), mPortConfigs.end(),
642 [&](const auto& pair) { return audioDeviceMatches(device, pair.second); });
643}
644
645Hal2AidlMapper::PortConfigs::iterator Hal2AidlMapper::findPortConfig(
646 const std::optional<AudioConfig>& config,
647 const std::optional<AudioIoFlags>& flags,
648 int32_t ioHandle) {
649 using Tag = AudioPortExt::Tag;
650 return std::find_if(mPortConfigs.begin(), mPortConfigs.end(),
651 [&](const auto& pair) {
652 const auto& p = pair.second;
653 LOG_ALWAYS_FATAL_IF(p.ext.getTag() == Tag::mix &&
654 (!p.sampleRate.has_value() || !p.channelMask.has_value() ||
655 !p.format.has_value() || !p.flags.has_value()),
656 "%s: stored mix port config is not fully specified: %s",
657 __func__, p.toString().c_str());
658 return p.ext.getTag() == Tag::mix &&
659 (!config.has_value() ||
660 isConfigEqualToPortConfig(config.value(), p)) &&
661 (!flags.has_value() || p.flags.value() == flags.value()) &&
662 p.ext.template get<Tag::mix>().handle == ioHandle; });
663}
664
665status_t Hal2AidlMapper::getAudioMixPort(int32_t ioHandle, AudioPort* port) {
666 auto it = findPortConfig(std::nullopt /*config*/, std::nullopt /*flags*/, ioHandle);
667 if (it == mPortConfigs.end()) {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530668 AUGMENT_LOG(E, "cannot find mix port config for handle %u", ioHandle);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700669 return BAD_VALUE;
670 }
671 return updateAudioPort(it->second.portId, port);
672}
673
674status_t Hal2AidlMapper::getAudioPortCached(
675 const ::aidl::android::media::audio::common::AudioDevice& device,
676 ::aidl::android::media::audio::common::AudioPort* port) {
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700677 if (auto portsIt = findPort(device); portsIt != mPorts.end()) {
678 *port = portsIt->second;
679 return OK;
680 }
Jaideep Sharma145313e2024-08-14 14:51:24 +0530681 AUGMENT_LOG(E, "device port for device %s is not found", device.toString().c_str());
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700682 return BAD_VALUE;
683}
684
685status_t Hal2AidlMapper::initialize() {
686 std::vector<AudioPort> ports;
687 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->getAudioPorts(&ports)));
Jaideep Sharma145313e2024-08-14 14:51:24 +0530688 AUGMENT_LOG_IF(W, ports.empty(), "returned an empty list of audio ports");
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700689 mDefaultInputPortId = mDefaultOutputPortId = -1;
690 const int defaultDeviceFlag = 1 << AudioPortDeviceExt::FLAG_INDEX_DEFAULT_DEVICE;
691 for (auto it = ports.begin(); it != ports.end(); ) {
692 const auto& port = *it;
693 if (port.ext.getTag() != AudioPortExt::Tag::device) {
694 ++it;
695 continue;
696 }
697 const AudioPortDeviceExt& deviceExt = port.ext.get<AudioPortExt::Tag::device>();
698 if ((deviceExt.flags & defaultDeviceFlag) != 0) {
699 if (port.flags.getTag() == AudioIoFlags::Tag::input) {
700 mDefaultInputPortId = port.id;
701 } else if (port.flags.getTag() == AudioIoFlags::Tag::output) {
702 mDefaultOutputPortId = port.id;
703 }
704 }
705 // For compatibility with HIDL, hide "template" remote submix ports from ports list.
706 if (const auto& devDesc = deviceExt.device;
707 (devDesc.type.type == AudioDeviceType::IN_SUBMIX ||
708 devDesc.type.type == AudioDeviceType::OUT_SUBMIX) &&
709 devDesc.type.connection == AudioDeviceDescription::CONNECTION_VIRTUAL) {
710 if (devDesc.type.type == AudioDeviceType::IN_SUBMIX) {
711 mRemoteSubmixIn = port;
712 } else {
713 mRemoteSubmixOut = port;
714 }
715 it = ports.erase(it);
716 } else {
717 ++it;
718 }
719 }
720 if (mRemoteSubmixIn.has_value() != mRemoteSubmixOut.has_value()) {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530721 AUGMENT_LOG(E,
722 "The configuration only has input or output remote submix device, "
723 "must have both");
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700724 mRemoteSubmixIn.reset();
725 mRemoteSubmixOut.reset();
726 }
727 if (mRemoteSubmixIn.has_value()) {
728 AudioPort connectedRSubmixIn = *mRemoteSubmixIn;
729 connectedRSubmixIn.ext.get<AudioPortExt::Tag::device>().device.address =
730 AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS;
Jaideep Sharma145313e2024-08-14 14:51:24 +0530731 AUGMENT_LOG(D, "connecting remote submix input");
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700732 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->connectExternalDevice(
733 connectedRSubmixIn, &connectedRSubmixIn)));
734 // The template port for the remote submix input couldn't be "default" because it is not
735 // attached. The connected port can now be made default because we never disconnect it.
736 if (mDefaultInputPortId == -1) {
737 mDefaultInputPortId = connectedRSubmixIn.id;
738 }
739 ports.push_back(std::move(connectedRSubmixIn));
740
741 // Remote submix output must not be connected until the framework actually starts
742 // using it, however for legacy compatibility we need to provide an "augmented template"
743 // port with an address and profiles. It is obtained by connecting the output and then
744 // immediately disconnecting it. This is a cheap operation as we don't open any streams.
745 AudioPort tempConnectedRSubmixOut = *mRemoteSubmixOut;
746 tempConnectedRSubmixOut.ext.get<AudioPortExt::Tag::device>().device.address =
747 AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS;
Jaideep Sharma145313e2024-08-14 14:51:24 +0530748 AUGMENT_LOG(D, "temporarily connecting and disconnecting remote submix output");
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700749 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->connectExternalDevice(
750 tempConnectedRSubmixOut, &tempConnectedRSubmixOut)));
751 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->disconnectExternalDevice(
752 tempConnectedRSubmixOut.id)));
753 tempConnectedRSubmixOut.id = mRemoteSubmixOut->id;
754 ports.push_back(std::move(tempConnectedRSubmixOut));
755 }
756
Jaideep Sharma145313e2024-08-14 14:51:24 +0530757 AUGMENT_LOG(I, "default port ids: input %d, output %d", mDefaultInputPortId,
758 mDefaultOutputPortId);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700759 std::transform(ports.begin(), ports.end(), std::inserter(mPorts, mPorts.end()),
760 [](const auto& p) { return std::make_pair(p.id, p); });
761 RETURN_STATUS_IF_ERROR(updateRoutes());
762 std::vector<AudioPortConfig> portConfigs;
763 RETURN_STATUS_IF_ERROR(
764 statusTFromBinderStatus(mModule->getAudioPortConfigs(&portConfigs))); // OK if empty
765 std::transform(portConfigs.begin(), portConfigs.end(),
766 std::inserter(mPortConfigs, mPortConfigs.end()),
767 [](const auto& p) { return std::make_pair(p.id, p); });
768 std::transform(mPortConfigs.begin(), mPortConfigs.end(),
769 std::inserter(mInitialPortConfigIds, mInitialPortConfigIds.end()),
770 [](const auto& pcPair) { return pcPair.first; });
771 std::vector<AudioPatch> patches;
772 RETURN_STATUS_IF_ERROR(
773 statusTFromBinderStatus(mModule->getAudioPatches(&patches))); // OK if empty
774 std::transform(patches.begin(), patches.end(),
775 std::inserter(mPatches, mPatches.end()),
776 [](const auto& p) { return std::make_pair(p.id, p); });
777 return OK;
778}
779
Mikhail Naganova317a802024-03-15 18:03:10 +0000780std::set<int32_t> Hal2AidlMapper::getPatchIdsByPortId(int32_t portId) {
781 std::set<int32_t> result;
782 for (const auto& [patchId, patch] : mPatches) {
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -0800783 for (int32_t id : patch.sourcePortConfigIds) {
Mikhail Naganova317a802024-03-15 18:03:10 +0000784 if (portConfigBelongsToPort(id, portId)) {
785 result.insert(patchId);
786 break;
787 }
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700788 }
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -0800789 for (int32_t id : patch.sinkPortConfigIds) {
Mikhail Naganova317a802024-03-15 18:03:10 +0000790 if (portConfigBelongsToPort(id, portId)) {
791 result.insert(patchId);
792 break;
793 }
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700794 }
795 }
Mikhail Naganova317a802024-03-15 18:03:10 +0000796 return result;
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700797}
798
jiabin62750c22023-12-21 22:06:07 +0000799status_t Hal2AidlMapper::prepareToDisconnectExternalDevice(const AudioPort& devicePort) {
800 auto portsIt = findPort(devicePort.ext.get<AudioPortExt::device>().device);
801 if (portsIt == mPorts.end()) {
802 return BAD_VALUE;
803 }
804 return statusTFromBinderStatus(mModule->prepareToDisconnectExternalDevice(portsIt->second.id));
805}
806
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700807status_t Hal2AidlMapper::prepareToOpenStream(
808 int32_t ioHandle, const AudioDevice& device, const AudioIoFlags& flags,
809 AudioSource source, Cleanups* cleanups, AudioConfig* config,
810 AudioPortConfig* mixPortConfig, AudioPatch* patch) {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530811 AUGMENT_LOG(D, "handle %d, device %s, flags %s, source %s, config %s, mixport config %s",
812 ioHandle, device.toString().c_str(), flags.toString().c_str(),
813 toString(source).c_str(), config->toString().c_str(),
814 mixPortConfig->toString().c_str());
Mikhail Naganova317a802024-03-15 18:03:10 +0000815 resetUnusedPatchesAndPortConfigs();
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800816 const AudioConfig initialConfig = *config;
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700817 // Find / create AudioPortConfigs for the device port and the mix port,
818 // then find / create a patch between them, and open a stream on the mix port.
819 AudioPortConfig devicePortConfig;
820 bool created = false;
Mikhail Naganov1a2e0ff2024-06-11 15:53:46 -0700821 RETURN_STATUS_IF_ERROR(findOrCreateDevicePortConfig(device, config, nullptr /*gainConfig*/,
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800822 &devicePortConfig, &created));
823 LOG_ALWAYS_FATAL_IF(devicePortConfig.id == 0);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700824 if (created) {
825 cleanups->add(&Hal2AidlMapper::resetPortConfig, devicePortConfig.id);
826 }
Mikhail Naganov38220af2023-12-07 14:00:48 -0800827 status_t status = prepareToOpenStreamHelper(ioHandle, devicePortConfig.portId,
828 devicePortConfig.id, flags, source, initialConfig, cleanups, config,
829 mixPortConfig, patch);
Dean Wheatleyd27bbb92024-01-19 15:54:35 +1100830 if (status != OK && !(mRemoteSubmixOut.has_value() &&
831 initialConfig.base.format.type != AudioFormatType::PCM)) {
Mikhail Naganov38220af2023-12-07 14:00:48 -0800832 // If using the client-provided config did not work out for establishing a mix port config
833 // or patching, try with the device port config. Note that in general device port config and
834 // mix port config are not required to be the same, however they must match if the HAL
835 // module can't perform audio stream conversions.
836 AudioConfig deviceConfig = initialConfig;
837 if (setConfigFromPortConfig(&deviceConfig, devicePortConfig)->base != initialConfig.base) {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530838 AUGMENT_LOG(D, "retrying with device port config: %s",
839 devicePortConfig.toString().c_str());
Mikhail Naganov38220af2023-12-07 14:00:48 -0800840 status = prepareToOpenStreamHelper(ioHandle, devicePortConfig.portId,
841 devicePortConfig.id, flags, source, initialConfig, cleanups,
842 &deviceConfig, mixPortConfig, patch);
843 if (status == OK) {
844 *config = deviceConfig;
845 }
846 }
847 }
848 return status;
849}
850
851status_t Hal2AidlMapper::prepareToOpenStreamHelper(
852 int32_t ioHandle, int32_t devicePortId, int32_t devicePortConfigId,
853 const AudioIoFlags& flags, AudioSource source, const AudioConfig& initialConfig,
854 Cleanups* cleanups, AudioConfig* config, AudioPortConfig* mixPortConfig,
855 AudioPatch* patch) {
856 const bool isInput = flags.getTag() == AudioIoFlags::Tag::input;
857 bool created = false;
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800858 RETURN_STATUS_IF_ERROR(findOrCreateMixPortConfig(*config, flags, ioHandle, source,
Mikhail Naganov38220af2023-12-07 14:00:48 -0800859 std::set<int32_t>{devicePortId}, mixPortConfig, &created));
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700860 if (created) {
861 cleanups->add(&Hal2AidlMapper::resetPortConfig, mixPortConfig->id);
862 }
863 setConfigFromPortConfig(config, *mixPortConfig);
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800864 bool retryWithSuggestedConfig = false; // By default, let the framework to retry.
865 if (mixPortConfig->id == 0 && config->base == AudioConfigBase{}) {
866 // The HAL proposes a default config, can retry here.
867 retryWithSuggestedConfig = true;
868 } else if (isInput && config->base != initialConfig.base) {
869 // If the resulting config is different, we must stop and provide the config to the
870 // framework so that it can retry.
871 mixPortConfig->id = 0;
872 } else if (!isInput && mixPortConfig->id == 0 &&
873 (initialConfig.base.format.type == AudioFormatType::PCM ||
874 !isBitPositionFlagSet(flags.get<AudioIoFlags::output>(),
875 AudioOutputFlags::DIRECT) ||
876 isBitPositionFlagSet(flags.get<AudioIoFlags::output>(),
877 AudioOutputFlags::COMPRESS_OFFLOAD))) {
878 // The framework does not retry opening non-direct PCM and IEC61937 outputs, need to retry
879 // here (see 'AudioHwDevice::openOutputStream').
880 retryWithSuggestedConfig = true;
881 }
882 if (mixPortConfig->id == 0 && retryWithSuggestedConfig) {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530883 AUGMENT_LOG(D, "retrying to find/create a mix port config using config %s",
884 config->toString().c_str());
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800885 RETURN_STATUS_IF_ERROR(findOrCreateMixPortConfig(*config, flags, ioHandle, source,
Mikhail Naganov38220af2023-12-07 14:00:48 -0800886 std::set<int32_t>{devicePortId}, mixPortConfig, &created));
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800887 if (created) {
888 cleanups->add(&Hal2AidlMapper::resetPortConfig, mixPortConfig->id);
889 }
890 setConfigFromPortConfig(config, *mixPortConfig);
891 }
892 if (mixPortConfig->id == 0) {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530893 AUGMENT_LOG(D, "returning suggested config for the stream: %s",
894 config->toString().c_str());
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800895 return OK;
896 }
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700897 if (isInput) {
898 RETURN_STATUS_IF_ERROR(findOrCreatePatch(
Mikhail Naganov03b0a002024-05-03 20:22:58 +0000899 {devicePortConfigId}, {mixPortConfig->id}, MATCH_BOTH, patch, &created));
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700900 } else {
901 RETURN_STATUS_IF_ERROR(findOrCreatePatch(
Mikhail Naganov03b0a002024-05-03 20:22:58 +0000902 {mixPortConfig->id}, {devicePortConfigId}, MATCH_BOTH, patch, &created));
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700903 }
904 if (created) {
905 cleanups->add(&Hal2AidlMapper::resetPatch, patch->id);
906 }
907 if (config->frameCount <= 0) {
908 config->frameCount = patch->minimumStreamBufferSizeFrames;
909 }
910 return OK;
911}
912
Mikhail Naganovca92a5c2023-12-07 14:00:48 -0800913status_t Hal2AidlMapper::setPortConfig(
914 const AudioPortConfig& requestedPortConfig, const std::set<int32_t>& destinationPortIds,
915 AudioPortConfig* portConfig, Cleanups* cleanups) {
916 bool created = false;
917 RETURN_STATUS_IF_ERROR(findOrCreatePortConfig(
918 requestedPortConfig, destinationPortIds, portConfig, &created));
919 if (created && cleanups != nullptr) {
920 cleanups->add(&Hal2AidlMapper::resetPortConfig, portConfig->id);
921 }
922 return OK;
923}
924
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700925status_t Hal2AidlMapper::releaseAudioPatch(int32_t patchId) {
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -0800926 return releaseAudioPatches({patchId});
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700927}
928
Mikhail Naganova317a802024-03-15 18:03:10 +0000929// Note: does not reset port configs.
930status_t Hal2AidlMapper::releaseAudioPatch(Patches::iterator it) {
931 const int32_t patchId = it->first;
Jaideep Sharma145313e2024-08-14 14:51:24 +0530932 AUGMENT_LOG(D, "patchId %d", patchId);
Mikhail Naganova317a802024-03-15 18:03:10 +0000933 if (ndk::ScopedAStatus status = mModule->resetAudioPatch(patchId); !status.isOk()) {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530934 AUGMENT_LOG(E, "error while resetting patch %d: %s", patchId,
935 status.getDescription().c_str());
Mikhail Naganova317a802024-03-15 18:03:10 +0000936 return statusTFromBinderStatus(status);
937 }
938 mPatches.erase(it);
939 for (auto it = mFwkPatches.begin(); it != mFwkPatches.end(); ++it) {
940 if (it->second == patchId) {
941 mFwkPatches.erase(it);
942 break;
943 }
944 }
945 return OK;
946}
947
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -0800948status_t Hal2AidlMapper::releaseAudioPatches(const std::set<int32_t>& patchIds) {
949 status_t result = OK;
950 for (const auto patchId : patchIds) {
951 if (auto it = mPatches.find(patchId); it != mPatches.end()) {
Mikhail Naganova317a802024-03-15 18:03:10 +0000952 releaseAudioPatch(it);
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -0800953 } else {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530954 AUGMENT_LOG(E, "patch id %d not found", patchId);
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -0800955 result = BAD_VALUE;
956 }
957 }
Mikhail Naganova317a802024-03-15 18:03:10 +0000958 resetUnusedPortConfigs();
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -0800959 return result;
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700960}
961
962void Hal2AidlMapper::resetPortConfig(int32_t portConfigId) {
963 if (auto it = mPortConfigs.find(portConfigId); it != mPortConfigs.end()) {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530964 AUGMENT_LOG(D, "%s", it->second.toString().c_str());
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700965 if (ndk::ScopedAStatus status = mModule->resetAudioPortConfig(portConfigId);
966 !status.isOk()) {
Jaideep Sharma145313e2024-08-14 14:51:24 +0530967 AUGMENT_LOG(E, "error while resetting port config %d: %s", portConfigId,
968 status.getDescription().c_str());
Qiang Chend6a604e2024-06-12 15:26:46 +0800969 return;
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700970 }
Mikhail Naganova317a802024-03-15 18:03:10 +0000971 mPortConfigs.erase(it);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700972 return;
973 }
Jaideep Sharma145313e2024-08-14 14:51:24 +0530974 AUGMENT_LOG(E, "port config id %d not found", portConfigId);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700975}
976
Mikhail Naganova317a802024-03-15 18:03:10 +0000977void Hal2AidlMapper::resetUnusedPatchesAndPortConfigs() {
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -0800978 // Since patches can be created independently of streams via 'createOrUpdatePatch',
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700979 // here we only clean up patches for released streams.
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -0800980 std::set<int32_t> patchesToRelease;
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700981 for (auto it = mStreams.begin(); it != mStreams.end(); ) {
982 if (auto streamSp = it->first.promote(); streamSp) {
983 ++it;
984 } else {
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -0800985 if (const int32_t patchId = it->second.second; patchId != -1) {
986 patchesToRelease.insert(patchId);
987 }
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700988 it = mStreams.erase(it);
989 }
990 }
Mikhail Naganova317a802024-03-15 18:03:10 +0000991 // 'releaseAudioPatches' also resets unused port configs.
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -0800992 releaseAudioPatches(patchesToRelease);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700993}
994
Mikhail Naganova317a802024-03-15 18:03:10 +0000995void Hal2AidlMapper::resetUnusedPortConfigs() {
Mikhail Naganovac9d4e72023-10-23 12:00:09 -0700996 // The assumption is that port configs are used to create patches
997 // (or to open streams, but that involves creation of patches, too). Thus,
998 // orphaned port configs can and should be reset.
Mikhail Naganova317a802024-03-15 18:03:10 +0000999 std::set<int32_t> portConfigIdsToReset;
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001000 std::transform(mPortConfigs.begin(), mPortConfigs.end(),
Mikhail Naganova317a802024-03-15 18:03:10 +00001001 std::inserter(portConfigIdsToReset, portConfigIdsToReset.end()),
1002 [](const auto& pcPair) { return pcPair.first; });
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001003 for (const auto& p : mPatches) {
Mikhail Naganova317a802024-03-15 18:03:10 +00001004 for (int32_t id : p.second.sourcePortConfigIds) portConfigIdsToReset.erase(id);
1005 for (int32_t id : p.second.sinkPortConfigIds) portConfigIdsToReset.erase(id);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001006 }
1007 for (int32_t id : mInitialPortConfigIds) {
Mikhail Naganova317a802024-03-15 18:03:10 +00001008 portConfigIdsToReset.erase(id);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001009 }
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -08001010 for (const auto& s : mStreams) {
Mikhail Naganova317a802024-03-15 18:03:10 +00001011 portConfigIdsToReset.erase(s.second.first);
Mikhail Naganov78f7f9a2023-11-16 15:49:23 -08001012 }
Mikhail Naganova317a802024-03-15 18:03:10 +00001013 for (const auto& portConfigId : portConfigIdsToReset) {
1014 resetPortConfig(portConfigId);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001015 }
1016}
1017
1018status_t Hal2AidlMapper::setDevicePortConnectedState(const AudioPort& devicePort, bool connected) {
Jaideep Sharma145313e2024-08-14 14:51:24 +05301019 AUGMENT_LOG(D, "state %s, device %s", (connected ? "connected" : "disconnected"),
1020 devicePort.toString().c_str());
Mikhail Naganova317a802024-03-15 18:03:10 +00001021 resetUnusedPatchesAndPortConfigs();
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001022 if (connected) {
1023 AudioDevice matchDevice = devicePort.ext.get<AudioPortExt::device>().device;
1024 std::optional<AudioPort> templatePort;
1025 auto erasePortAfterConnectionIt = mPorts.end();
1026 // Connection of remote submix out with address "0" is a special case. Since there is
1027 // already an "augmented template" port with this address in mPorts, we need to replace
1028 // it with a connected port.
1029 // Connection of remote submix outs with any other address is done as usual except that
1030 // the template port is in `mRemoteSubmixOut`.
1031 if (mRemoteSubmixOut.has_value() && matchDevice.type.type == AudioDeviceType::OUT_SUBMIX) {
1032 if (matchDevice.address == AudioDeviceAddress::make<AudioDeviceAddress::id>(
1033 AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS)) {
1034 erasePortAfterConnectionIt = findPort(matchDevice);
1035 }
1036 templatePort = mRemoteSubmixOut;
1037 } else if (mRemoteSubmixIn.has_value() &&
1038 matchDevice.type.type == AudioDeviceType::IN_SUBMIX) {
1039 templatePort = mRemoteSubmixIn;
1040 } else {
1041 // Reset the device address to find the "template" port.
1042 matchDevice.address = AudioDeviceAddress::make<AudioDeviceAddress::id>();
1043 }
1044 if (!templatePort.has_value()) {
1045 auto portsIt = findPort(matchDevice);
1046 if (portsIt == mPorts.end()) {
1047 // Since 'setConnectedState' is called for all modules, it is normal when the device
1048 // port not found in every one of them.
1049 return BAD_VALUE;
1050 } else {
Jaideep Sharma145313e2024-08-14 14:51:24 +05301051 AUGMENT_LOG(D, "device port for device %s found", matchDevice.toString().c_str());
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001052 }
1053 templatePort = portsIt->second;
1054 }
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001055
1056 // Use the ID of the "template" port, use all the information from the provided port.
1057 AudioPort connectedPort = devicePort;
1058 connectedPort.id = templatePort->id;
1059 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->connectExternalDevice(
1060 connectedPort, &connectedPort)));
1061 const auto [it, inserted] = mPorts.insert(std::make_pair(connectedPort.id, connectedPort));
Jaideep Sharma145313e2024-08-14 14:51:24 +05301062 LOG_ALWAYS_FATAL_IF(
1063 !inserted, "%s duplicate port ID received from HAL: %s, existing port: %s",
1064 __func__, connectedPort.toString().c_str(), it->second.toString().c_str());
Mikhail Naganova317a802024-03-15 18:03:10 +00001065 mConnectedPorts.insert(connectedPort.id);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001066 if (erasePortAfterConnectionIt != mPorts.end()) {
1067 mPorts.erase(erasePortAfterConnectionIt);
1068 }
1069 } else { // !connected
1070 AudioDevice matchDevice = devicePort.ext.get<AudioPortExt::device>().device;
1071 auto portsIt = findPort(matchDevice);
1072 if (portsIt == mPorts.end()) {
1073 // Since 'setConnectedState' is called for all modules, it is normal when the device
1074 // port not found in every one of them.
1075 return BAD_VALUE;
1076 } else {
Jaideep Sharma145313e2024-08-14 14:51:24 +05301077 AUGMENT_LOG(D, "device port for device %s found", matchDevice.toString().c_str());
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001078 }
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001079
1080 // Disconnection of remote submix out with address "0" is a special case. We need to replace
1081 // the connected port entry with the "augmented template".
1082 const int32_t portId = portsIt->second.id;
1083 if (mRemoteSubmixOut.has_value() && matchDevice.type.type == AudioDeviceType::OUT_SUBMIX &&
1084 matchDevice.address == AudioDeviceAddress::make<AudioDeviceAddress::id>(
1085 AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS)) {
1086 mDisconnectedPortReplacement = std::make_pair(portId, *mRemoteSubmixOut);
1087 auto& port = mDisconnectedPortReplacement.second;
1088 port.ext.get<AudioPortExt::Tag::device>().device = matchDevice;
1089 port.profiles = portsIt->second.profiles;
1090 }
Mikhail Naganova317a802024-03-15 18:03:10 +00001091
1092 // Patches may still exist, the framework may reset or update them later.
1093 // For disconnection to succeed, need to release these patches first.
1094 if (std::set<int32_t> patchIdsToRelease = getPatchIdsByPortId(portId);
1095 !patchIdsToRelease.empty()) {
1096 FwkPatches releasedPatches;
1097 status_t status = OK;
1098 for (int32_t patchId : patchIdsToRelease) {
1099 if (auto it = mPatches.find(patchId); it != mPatches.end()) {
1100 if (status = releaseAudioPatch(it); status != OK) break;
1101 releasedPatches.insert(std::make_pair(patchId, patchId));
1102 }
1103 }
1104 resetUnusedPortConfigs();
Mikhail Naganov67c2f6d2024-03-18 09:48:27 -07001105 // Patches created by Hal2AidlMapper during stream creation and not "claimed"
1106 // by the framework must not be surfaced to it.
1107 for (auto& s : mStreams) {
1108 if (auto it = releasedPatches.find(s.second.second); it != releasedPatches.end()) {
1109 releasedPatches.erase(it);
1110 }
1111 }
Mikhail Naganova317a802024-03-15 18:03:10 +00001112 mFwkPatches.merge(releasedPatches);
1113 LOG_ALWAYS_FATAL_IF(!releasedPatches.empty(),
1114 "mFwkPatches already contains some of released patches");
1115 if (status != OK) return status;
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001116 }
Mikhail Naganova317a802024-03-15 18:03:10 +00001117 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->disconnectExternalDevice(portId)));
1118 eraseConnectedPort(portId);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001119 }
1120 return updateRoutes();
1121}
1122
1123status_t Hal2AidlMapper::updateAudioPort(int32_t portId, AudioPort* port) {
1124 const status_t status = statusTFromBinderStatus(mModule->getAudioPort(portId, port));
1125 if (status == OK) {
1126 auto portIt = mPorts.find(portId);
1127 if (portIt != mPorts.end()) {
jiabin255ff7f2024-01-11 00:24:47 +00001128 if (port->ext.getTag() == AudioPortExt::Tag::mix && portIt->second != *port) {
1129 mDynamicMixPortIds.insert(portId);
1130 }
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001131 portIt->second = *port;
1132 } else {
Jaideep Sharma145313e2024-08-14 14:51:24 +05301133 AUGMENT_LOG(W, "port(%d) returned successfully from the HAL but not it is not cached",
1134 portId);
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001135 }
1136 }
1137 return status;
1138}
1139
1140status_t Hal2AidlMapper::updateRoutes() {
1141 RETURN_STATUS_IF_ERROR(
1142 statusTFromBinderStatus(mModule->getAudioRoutes(&mRoutes)));
Jaideep Sharma145313e2024-08-14 14:51:24 +05301143 AUGMENT_LOG_IF(W, mRoutes.empty(), "returned an empty list of audio routes");
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001144 if (mRemoteSubmixIn.has_value()) {
1145 // Remove mentions of the template remote submix input from routes.
1146 int32_t rSubmixInId = mRemoteSubmixIn->id;
1147 // Remove mentions of the template remote submix out only if it is not in mPorts
1148 // (that means there is a connected port in mPorts).
1149 int32_t rSubmixOutId = mPorts.find(mRemoteSubmixOut->id) == mPorts.end() ?
1150 mRemoteSubmixOut->id : -1;
1151 for (auto it = mRoutes.begin(); it != mRoutes.end();) {
1152 auto& route = *it;
1153 if (route.sinkPortId == rSubmixOutId) {
1154 it = mRoutes.erase(it);
1155 continue;
1156 }
1157 if (auto routeIt = std::find(route.sourcePortIds.begin(), route.sourcePortIds.end(),
1158 rSubmixInId); routeIt != route.sourcePortIds.end()) {
1159 route.sourcePortIds.erase(routeIt);
1160 if (route.sourcePortIds.empty()) {
1161 it = mRoutes.erase(it);
1162 continue;
1163 }
1164 }
1165 ++it;
1166 }
1167 }
1168 mRoutingMatrix.clear();
1169 for (const auto& r : mRoutes) {
1170 for (auto portId : r.sourcePortIds) {
1171 mRoutingMatrix.emplace(r.sinkPortId, portId);
1172 mRoutingMatrix.emplace(portId, r.sinkPortId);
1173 }
1174 }
1175 return OK;
1176}
1177
jiabin255ff7f2024-01-11 00:24:47 +00001178void Hal2AidlMapper::updateDynamicMixPorts() {
1179 for (int32_t portId : mDynamicMixPortIds) {
1180 if (auto it = mPorts.find(portId); it != mPorts.end()) {
1181 updateAudioPort(portId, &it->second);
1182 } else {
1183 // This must not happen
Jaideep Sharma145313e2024-08-14 14:51:24 +05301184 AUGMENT_LOG(E, "cannot find port for id=%d", portId);
jiabin255ff7f2024-01-11 00:24:47 +00001185 }
1186 }
1187}
1188
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001189} // namespace android