1 /*
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 
28 #include "Hal2AidlMapper.h"
29 
30 using aidl::android::aidl_utils::statusTFromBinderStatus;
31 using aidl::android::media::audio::common::AudioChannelLayout;
32 using aidl::android::media::audio::common::AudioConfig;
33 using aidl::android::media::audio::common::AudioConfigBase;
34 using aidl::android::media::audio::common::AudioDevice;
35 using aidl::android::media::audio::common::AudioDeviceAddress;
36 using aidl::android::media::audio::common::AudioDeviceDescription;
37 using aidl::android::media::audio::common::AudioDeviceType;
38 using aidl::android::media::audio::common::AudioFormatDescription;
39 using aidl::android::media::audio::common::AudioFormatType;
40 using aidl::android::media::audio::common::AudioGainConfig;
41 using aidl::android::media::audio::common::AudioInputFlags;
42 using aidl::android::media::audio::common::AudioIoFlags;
43 using aidl::android::media::audio::common::AudioOutputFlags;
44 using aidl::android::media::audio::common::AudioPort;
45 using aidl::android::media::audio::common::AudioPortConfig;
46 using aidl::android::media::audio::common::AudioPortDeviceExt;
47 using aidl::android::media::audio::common::AudioPortExt;
48 using aidl::android::media::audio::common::AudioPortMixExt;
49 using aidl::android::media::audio::common::AudioPortMixExtUseCase;
50 using aidl::android::media::audio::common::AudioProfile;
51 using aidl::android::media::audio::common::AudioSource;
52 using aidl::android::media::audio::common::Int;
53 using aidl::android::hardware::audio::common::isBitPositionFlagSet;
54 using aidl::android::hardware::audio::common::isDefaultAudioFormat;
55 using aidl::android::hardware::audio::common::makeBitPositionFlagMask;
56 using aidl::android::hardware::audio::core::AudioPatch;
57 using aidl::android::hardware::audio::core::AudioRoute;
58 using aidl::android::hardware::audio::core::IModule;
59 
60 namespace android {
61 
62 namespace {
63 
isConfigEqualToPortConfig(const AudioConfig & config,const AudioPortConfig & portConfig)64 bool isConfigEqualToPortConfig(const AudioConfig& config, const AudioPortConfig& portConfig) {
65     return portConfig.sampleRate.value().value == config.base.sampleRate &&
66             portConfig.channelMask.value() == config.base.channelMask &&
67             portConfig.format.value() == config.base.format;
68 }
69 
setConfigFromPortConfig(AudioConfig * config,const AudioPortConfig & portConfig)70 AudioConfig* setConfigFromPortConfig(AudioConfig* config, const AudioPortConfig& portConfig) {
71     config->base.sampleRate = portConfig.sampleRate.value().value;
72     config->base.channelMask = portConfig.channelMask.value();
73     config->base.format = portConfig.format.value();
74     return config;
75 }
76 
setPortConfigFromConfig(AudioPortConfig * portConfig,const AudioConfig & config)77 void setPortConfigFromConfig(AudioPortConfig* portConfig, const AudioConfig& config) {
78     if (config.base.sampleRate != 0) {
79         portConfig->sampleRate = Int{ .value = config.base.sampleRate };
80     }
81     if (config.base.channelMask != AudioChannelLayout{}) {
82         portConfig->channelMask = config.base.channelMask;
83     }
84     if (config.base.format != AudioFormatDescription{}) {
85         portConfig->format = config.base.format;
86     }
87 }
88 
containHapticChannel(AudioChannelLayout channel)89 bool containHapticChannel(AudioChannelLayout channel) {
90     return channel.getTag() == AudioChannelLayout::Tag::layoutMask &&
91             ((channel.get<AudioChannelLayout::Tag::layoutMask>()
92                     & AudioChannelLayout::CHANNEL_HAPTIC_A)
93                     == AudioChannelLayout::CHANNEL_HAPTIC_A ||
94              (channel.get<AudioChannelLayout::Tag::layoutMask>()
95                     & AudioChannelLayout::CHANNEL_HAPTIC_B)
96                     == AudioChannelLayout::CHANNEL_HAPTIC_B);
97 }
98 
99 }  // namespace
100 
Hal2AidlMapper(const std::string & instance,const std::shared_ptr<IModule> & module)101 Hal2AidlMapper::Hal2AidlMapper(const std::string& instance, const std::shared_ptr<IModule>& module)
102         : mInstance(instance), mModule(module) {
103 }
104 
addStream(const sp<StreamHalInterface> & stream,int32_t mixPortConfigId,int32_t patchId)105 void Hal2AidlMapper::addStream(
106         const sp<StreamHalInterface>& stream, int32_t mixPortConfigId, int32_t patchId) {
107     mStreams.insert(std::pair(stream, std::pair(mixPortConfigId, patchId)));
108 }
109 
audioDeviceMatches(const AudioDevice & device,const AudioPort & p)110 bool 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 
audioDeviceMatches(const AudioDevice & device,const AudioPortConfig & p)115 bool 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 
createOrUpdatePatch(const std::vector<AudioPortConfig> & sources,const std::vector<AudioPortConfig> & sinks,int32_t * patchId,Cleanups * cleanups)125 status_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.
140     ALOGD("%s: patch ID: %d, [disregard IDs] sources: %s, sinks: %s",
141             __func__, *patchId, ::android::internal::ToString(sources).c_str(),
142             ::android::internal::ToString(sinks).c_str());
143     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;
149             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.
155                     ALOGI("fillPortConfigs: retrying to find a mix port config with default "
156                             "configuration");
157                     if (auto it = findPortConfig(std::nullopt, s.flags,
158                                     s.ext.get<AudioPortExt::mix>().handle);
159                             it != mPortConfigs.end()) {
160                         portConfig = it->second;
161                     } else {
162                         const std::string flags = s.flags.has_value() ?
163                                 s.flags->toString() : "<unspecified>";
164                         ALOGE("fillPortConfigs: existing port config for flags %s, handle %d "
165                                 "not found in module %s", flags.c_str(),
166                                 s.ext.get<AudioPortExt::mix>().handle, mInstance.c_str());
167                         return BAD_VALUE;
168                     }
169                 } else {
170                     return status;
171                 }
172             }
173             LOG_ALWAYS_FATAL_IF(portConfig.id == 0,
174                     "fillPortConfigs: initial config: %s, port config: %s",
175                     s.toString().c_str(), portConfig.toString().c_str());
176             ids->push_back(portConfig.id);
177             if (portIds != nullptr) {
178                 portIds->insert(portConfig.portId);
179             }
180         }
181         return OK;
182     };
183     // When looking up port configs, the destinationPortId is only used for mix ports.
184     // Thus, we process device port configs first, and look up the destination port ID from them.
185     const bool sourceIsDevice = std::any_of(sources.begin(), sources.end(),
186             [](const auto& config) { return config.ext.getTag() == AudioPortExt::device; });
187     const bool sinkIsDevice = std::any_of(sinks.begin(), sinks.end(),
188             [](const auto& config) { return config.ext.getTag() == AudioPortExt::device; });
189     const std::vector<AudioPortConfig>& devicePortConfigs =
190             sourceIsDevice ? sources : sinks;
191     std::vector<int32_t>* devicePortConfigIds =
192             sourceIsDevice ? &patch.sourcePortConfigIds : &patch.sinkPortConfigIds;
193     const std::vector<AudioPortConfig>& mixPortConfigs =
194             sourceIsDevice ? sinks : sources;
195     std::vector<int32_t>* mixPortConfigIds =
196             sourceIsDevice ? &patch.sinkPortConfigIds : &patch.sourcePortConfigIds;
197     std::set<int32_t> devicePortIds;
198     RETURN_STATUS_IF_ERROR(fillPortConfigs(
199                     devicePortConfigs, std::set<int32_t>(), devicePortConfigIds, &devicePortIds));
200     RETURN_STATUS_IF_ERROR(fillPortConfigs(
201                     mixPortConfigs, devicePortIds, mixPortConfigIds, nullptr));
202     if (existingPatchIt != mPatches.end()) {
203         RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
204                         mModule->setAudioPatch(patch, &patch)));
205         existingPatchIt->second = patch;
206     } else {
207         bool created = false;
208         // When the framework does not specify a patch ID, only the mix port config
209         // is used for finding an existing patch. That's because the framework assumes
210         // that there can only be one patch for an I/O thread.
211         PatchMatch match = sourceIsDevice && sinkIsDevice ?
212                 MATCH_BOTH : (sourceIsDevice ? MATCH_SINKS : MATCH_SOURCES);
213         auto requestedPatch = patch;
214         RETURN_STATUS_IF_ERROR(findOrCreatePatch(patch, match,
215                                                  &patch, &created));
216         // No cleanup of the patch is needed, it is managed by the framework.
217         *patchId = patch.id;
218         if (!created) {
219             requestedPatch.id = patch.id;
220             if (patch != requestedPatch) {
221                 ALOGI("%s: Updating transient patch. Current: %s, new: %s",
222                         __func__, patch.toString().c_str(), requestedPatch.toString().c_str());
223                 // Since matching may be done by mix port only, update the patch if the device port
224                 // config has changed.
225                 patch = requestedPatch;
226                 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
227                                 mModule->setAudioPatch(patch, &patch)));
228                 existingPatchIt = mPatches.find(patch.id);
229                 existingPatchIt->second = patch;
230             }
231             // The framework might have "created" a patch which already existed due to
232             // stream creation. Need to release the ownership from the stream.
233             for (auto& s : mStreams) {
234                 if (s.second.second == patch.id) s.second.second = -1;
235             }
236         }
237     }
238     return OK;
239 }
240 
createOrUpdatePortConfig(const AudioPortConfig & requestedPortConfig,AudioPortConfig * result,bool * created)241 status_t Hal2AidlMapper::createOrUpdatePortConfig(
242         const AudioPortConfig& requestedPortConfig, AudioPortConfig* result, bool* created) {
243     bool applied = false;
244     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->setAudioPortConfig(
245                             requestedPortConfig, result, &applied)));
246     if (!applied) {
247         result->id = 0;
248         *created = false;
249         return OK;
250     }
251 
252     int32_t id = result->id;
253     if (requestedPortConfig.id != 0 && requestedPortConfig.id != id) {
254         LOG_ALWAYS_FATAL("%s: requested port config id %d changed to %d", __func__,
255                 requestedPortConfig.id, id);
256     }
257 
258     auto [_, inserted] = mPortConfigs.insert_or_assign(id, *result);
259     *created = inserted;
260     return OK;
261 }
262 
createOrUpdatePortConfigRetry(const AudioPortConfig & requestedPortConfig,AudioPortConfig * result,bool * created)263 status_t Hal2AidlMapper::createOrUpdatePortConfigRetry(
264         const AudioPortConfig& requestedPortConfig, AudioPortConfig* result, bool* created) {
265     AudioPortConfig suggestedOrAppliedPortConfig;
266     RETURN_STATUS_IF_ERROR(createOrUpdatePortConfig(requestedPortConfig,
267                     &suggestedOrAppliedPortConfig, created));
268     if (suggestedOrAppliedPortConfig.id == 0) {
269         // Try again with the suggested config
270         suggestedOrAppliedPortConfig.id = requestedPortConfig.id;
271         AudioPortConfig appliedPortConfig;
272         RETURN_STATUS_IF_ERROR(createOrUpdatePortConfig(suggestedOrAppliedPortConfig,
273                         &appliedPortConfig, created));
274         if (appliedPortConfig.id == 0) {
275             ALOGE("%s: module %s did not apply suggested config %s", __func__,
276                     mInstance.c_str(), suggestedOrAppliedPortConfig.toString().c_str());
277             return NO_INIT;
278         }
279         *result = appliedPortConfig;
280     } else {
281         *result = suggestedOrAppliedPortConfig;
282     }
283     return OK;
284 }
285 
eraseConnectedPort(int32_t portId)286 void Hal2AidlMapper::eraseConnectedPort(int32_t portId) {
287     mPorts.erase(portId);
288     mConnectedPorts.erase(portId);
289     if (mDisconnectedPortReplacement.first == portId) {
290         const auto& port = mDisconnectedPortReplacement.second;
291         mPorts.insert(std::make_pair(port.id, port));
292         ALOGD("%s: disconnected port replacement: %s", __func__, port.toString().c_str());
293         mDisconnectedPortReplacement = std::pair<int32_t, AudioPort>();
294     }
295     updateDynamicMixPorts();
296 }
297 
findOrCreatePatch(const AudioPatch & requestedPatch,PatchMatch match,AudioPatch * patch,bool * created)298 status_t Hal2AidlMapper::findOrCreatePatch(
299         const AudioPatch& requestedPatch, PatchMatch match, AudioPatch* patch, bool* created) {
300     std::set<int32_t> sourcePortConfigIds(requestedPatch.sourcePortConfigIds.begin(),
301             requestedPatch.sourcePortConfigIds.end());
302     std::set<int32_t> sinkPortConfigIds(requestedPatch.sinkPortConfigIds.begin(),
303             requestedPatch.sinkPortConfigIds.end());
304     return findOrCreatePatch(sourcePortConfigIds, sinkPortConfigIds, match, patch, created);
305 }
306 
findOrCreatePatch(const std::set<int32_t> & sourcePortConfigIds,const std::set<int32_t> & sinkPortConfigIds,PatchMatch match,AudioPatch * patch,bool * created)307 status_t Hal2AidlMapper::findOrCreatePatch(
308         const std::set<int32_t>& sourcePortConfigIds, const std::set<int32_t>& sinkPortConfigIds,
309         PatchMatch match, AudioPatch* patch, bool* created) {
310     auto patchIt = findPatch(sourcePortConfigIds, sinkPortConfigIds, match);
311     if (patchIt == mPatches.end()) {
312         AudioPatch requestedPatch, appliedPatch;
313         requestedPatch.sourcePortConfigIds.insert(requestedPatch.sourcePortConfigIds.end(),
314                 sourcePortConfigIds.begin(), sourcePortConfigIds.end());
315         requestedPatch.sinkPortConfigIds.insert(requestedPatch.sinkPortConfigIds.end(),
316                 sinkPortConfigIds.begin(), sinkPortConfigIds.end());
317         RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->setAudioPatch(
318                                 requestedPatch, &appliedPatch)));
319         patchIt = mPatches.insert(mPatches.end(), std::make_pair(appliedPatch.id, appliedPatch));
320         *created = true;
321     } else {
322         *created = false;
323     }
324     *patch = patchIt->second;
325     return OK;
326 }
327 
findOrCreateDevicePortConfig(const AudioDevice & device,const AudioConfig * config,const AudioGainConfig * gainConfig,AudioPortConfig * portConfig,bool * created)328 status_t Hal2AidlMapper::findOrCreateDevicePortConfig(
329         const AudioDevice& device, const AudioConfig* config, const AudioGainConfig* gainConfig,
330         AudioPortConfig* portConfig, bool* created) {
331     if (auto portConfigIt = findPortConfig(device); portConfigIt == mPortConfigs.end()) {
332         auto portsIt = findPort(device);
333         if (portsIt == mPorts.end()) {
334             ALOGE("%s: device port for device %s is not found in the module %s",
335                     __func__, device.toString().c_str(), mInstance.c_str());
336             return BAD_VALUE;
337         }
338         AudioPortConfig requestedPortConfig;
339         requestedPortConfig.portId = portsIt->first;
340         if (config != nullptr) {
341             setPortConfigFromConfig(&requestedPortConfig, *config);
342         }
343         if (gainConfig != nullptr) {
344             requestedPortConfig.gain = *gainConfig;
345         }
346         return createOrUpdatePortConfigRetry(requestedPortConfig, portConfig, created);
347     } else {
348         AudioPortConfig requestedPortConfig = portConfigIt->second;
349         if (config != nullptr) {
350             setPortConfigFromConfig(&requestedPortConfig, *config);
351         }
352         if (gainConfig != nullptr) {
353             requestedPortConfig.gain = *gainConfig;
354         }
355 
356         if (requestedPortConfig != portConfigIt->second) {
357             return createOrUpdatePortConfigRetry(requestedPortConfig, portConfig, created);
358         } else {
359             *portConfig = portConfigIt->second;
360             *created = false;
361         }
362     }
363     return OK;
364 }
365 
findOrCreateMixPortConfig(const AudioConfig & config,const std::optional<AudioIoFlags> & flags,int32_t ioHandle,AudioSource source,const std::set<int32_t> & destinationPortIds,AudioPortConfig * portConfig,bool * created)366 status_t Hal2AidlMapper::findOrCreateMixPortConfig(
367         const AudioConfig& config, const std::optional<AudioIoFlags>& flags, int32_t ioHandle,
368         AudioSource source, const std::set<int32_t>& destinationPortIds,
369         AudioPortConfig* portConfig, bool* created) {
370     // These flags get removed one by one in this order when retrying port finding.
371     static const std::vector<AudioInputFlags> kOptionalInputFlags{
372         AudioInputFlags::FAST, AudioInputFlags::RAW, AudioInputFlags::VOIP_TX };
373     if (auto portConfigIt = findPortConfig(config, flags, ioHandle);
374             portConfigIt == mPortConfigs.end() && flags.has_value()) {
375         auto optionalInputFlagsIt = kOptionalInputFlags.begin();
376         AudioIoFlags matchFlags = flags.value();
377         auto portsIt = findPort(config, matchFlags, destinationPortIds);
378         while (portsIt == mPorts.end() && matchFlags.getTag() == AudioIoFlags::Tag::input
379                 && optionalInputFlagsIt != kOptionalInputFlags.end()) {
380             if (!isBitPositionFlagSet(
381                             matchFlags.get<AudioIoFlags::Tag::input>(), *optionalInputFlagsIt)) {
382                 ++optionalInputFlagsIt;
383                 continue;
384             }
385             matchFlags.set<AudioIoFlags::Tag::input>(matchFlags.get<AudioIoFlags::Tag::input>() &
386                     ~makeBitPositionFlagMask(*optionalInputFlagsIt++));
387             portsIt = findPort(config, matchFlags, destinationPortIds);
388             ALOGI("%s: mix port for config %s, flags %s was not found in the module %s, "
389                     "retried with flags %s", __func__, config.toString().c_str(),
390                     flags.value().toString().c_str(), mInstance.c_str(),
391                     matchFlags.toString().c_str());
392         }
393         if (portsIt == mPorts.end()) {
394             ALOGE("%s: mix port for config %s, flags %s is not found in the module %s",
395                     __func__, config.toString().c_str(), matchFlags.toString().c_str(),
396                     mInstance.c_str());
397             return BAD_VALUE;
398         }
399         AudioPortConfig requestedPortConfig;
400         requestedPortConfig.portId = portsIt->first;
401         setPortConfigFromConfig(&requestedPortConfig, config);
402         requestedPortConfig.flags = portsIt->second.flags;
403         requestedPortConfig.ext = AudioPortMixExt{ .handle = ioHandle };
404         if (matchFlags.getTag() == AudioIoFlags::Tag::input
405                 && source != AudioSource::SYS_RESERVED_INVALID) {
406             requestedPortConfig.ext.get<AudioPortExt::Tag::mix>().usecase =
407                     AudioPortMixExtUseCase::make<AudioPortMixExtUseCase::Tag::source>(source);
408         }
409         return createOrUpdatePortConfig(requestedPortConfig, portConfig, created);
410     } else if (portConfigIt == mPortConfigs.end() && !flags.has_value()) {
411         ALOGW("%s: mix port config for %s, handle %d not found in the module %s, "
412                 "and was not created as flags are not specified",
413                 __func__, config.toString().c_str(), ioHandle, mInstance.c_str());
414         return BAD_VALUE;
415     } else {
416         AudioPortConfig requestedPortConfig = portConfigIt->second;
417         setPortConfigFromConfig(&requestedPortConfig, config);
418 
419         AudioPortMixExt& mixExt = requestedPortConfig.ext.get<AudioPortExt::Tag::mix>();
420         if (mixExt.usecase.getTag() == AudioPortMixExtUseCase::Tag::source &&
421                 source != AudioSource::SYS_RESERVED_INVALID) {
422             mixExt.usecase.get<AudioPortMixExtUseCase::Tag::source>() = source;
423         }
424 
425         if (requestedPortConfig != portConfigIt->second) {
426             return createOrUpdatePortConfig(requestedPortConfig, portConfig, created);
427         } else {
428             *portConfig = portConfigIt->second;
429             *created = false;
430         }
431     }
432     return OK;
433 }
434 
findOrCreatePortConfig(const AudioPortConfig & requestedPortConfig,const std::set<int32_t> & destinationPortIds,AudioPortConfig * portConfig,bool * created)435 status_t Hal2AidlMapper::findOrCreatePortConfig(
436         const AudioPortConfig& requestedPortConfig, const std::set<int32_t>& destinationPortIds,
437         AudioPortConfig* portConfig, bool* created) {
438     using Tag = AudioPortExt::Tag;
439     if (requestedPortConfig.ext.getTag() == Tag::mix) {
440         if (const auto& p = requestedPortConfig;
441                 !p.sampleRate.has_value() || !p.channelMask.has_value() ||
442                 !p.format.has_value()) {
443             ALOGW("%s: provided mix port config is not fully specified: %s",
444                     __func__, p.toString().c_str());
445             return BAD_VALUE;
446         }
447         AudioConfig config;
448         setConfigFromPortConfig(&config, requestedPortConfig);
449         AudioSource source = requestedPortConfig.ext.get<Tag::mix>().usecase.getTag() ==
450                 AudioPortMixExtUseCase::Tag::source ?
451                 requestedPortConfig.ext.get<Tag::mix>().usecase.
452                 get<AudioPortMixExtUseCase::Tag::source>() : AudioSource::SYS_RESERVED_INVALID;
453         return findOrCreateMixPortConfig(config, requestedPortConfig.flags,
454                 requestedPortConfig.ext.get<Tag::mix>().handle, source, destinationPortIds,
455                 portConfig, created);
456     } else if (requestedPortConfig.ext.getTag() == Tag::device) {
457         const auto& p = requestedPortConfig;
458         const bool hasAudioConfig =
459                 p.sampleRate.has_value() && p.channelMask.has_value() && p.format.has_value();
460         const bool hasGainConfig = p.gain.has_value();
461         if (hasAudioConfig || hasGainConfig) {
462             AudioConfig config, *configPtr = nullptr;
463             if (hasAudioConfig) {
464                 setConfigFromPortConfig(&config, requestedPortConfig);
465                 configPtr = &config;
466             }
467             const AudioGainConfig* gainConfigPtr = nullptr;
468             if (hasGainConfig) gainConfigPtr = &(*(p.gain));
469             return findOrCreateDevicePortConfig(
470                     requestedPortConfig.ext.get<Tag::device>().device, configPtr, gainConfigPtr,
471                     portConfig, created);
472         } else {
473             ALOGD("%s: device port config does not have audio or gain config specified", __func__);
474             return findOrCreateDevicePortConfig(
475                     requestedPortConfig.ext.get<Tag::device>().device, nullptr /*config*/,
476                     nullptr /*gainConfig*/, portConfig, created);
477         }
478     }
479     ALOGW("%s: unsupported audio port config: %s",
480             __func__, requestedPortConfig.toString().c_str());
481     return BAD_VALUE;
482 }
483 
findPortConfig(const AudioDevice & device,AudioPortConfig * portConfig)484 status_t Hal2AidlMapper::findPortConfig(const AudioDevice& device, AudioPortConfig* portConfig) {
485     if (auto it = findPortConfig(device); it != mPortConfigs.end()) {
486         *portConfig = it->second;
487         return OK;
488     }
489     ALOGE("%s: could not find a device port config for device %s",
490             __func__, device.toString().c_str());
491     return BAD_VALUE;
492 }
493 
findPatch(const std::set<int32_t> & sourcePortConfigIds,const std::set<int32_t> & sinkPortConfigIds,PatchMatch match)494 Hal2AidlMapper::Patches::iterator Hal2AidlMapper::findPatch(
495         const std::set<int32_t>& sourcePortConfigIds, const std::set<int32_t>& sinkPortConfigIds,
496         PatchMatch match) {
497     return std::find_if(mPatches.begin(), mPatches.end(),
498             [&](const auto& pair) {
499                 const auto& p = pair.second;
500                 std::set<int32_t> patchSrcs(
501                         p.sourcePortConfigIds.begin(), p.sourcePortConfigIds.end());
502                 std::set<int32_t> patchSinks(
503                         p.sinkPortConfigIds.begin(), p.sinkPortConfigIds.end());
504                 switch (match) {
505                     case MATCH_SOURCES:
506                         return sourcePortConfigIds == patchSrcs;
507                     case MATCH_SINKS:
508                         return sinkPortConfigIds == patchSinks;
509                     case MATCH_BOTH:
510                         return sourcePortConfigIds == patchSrcs && sinkPortConfigIds == patchSinks;
511                 }
512             });
513 }
514 
findPort(const AudioDevice & device)515 Hal2AidlMapper::Ports::iterator Hal2AidlMapper::findPort(const AudioDevice& device) {
516     if (device.type.type == AudioDeviceType::IN_DEFAULT) {
517         return mPorts.find(mDefaultInputPortId);
518     } else if (device.type.type == AudioDeviceType::OUT_DEFAULT) {
519         return mPorts.find(mDefaultOutputPortId);
520     }
521     if (device.address.getTag() != AudioDeviceAddress::id ||
522             !device.address.get<AudioDeviceAddress::id>().empty()) {
523         return std::find_if(mPorts.begin(), mPorts.end(),
524                 [&](const auto& pair) { return audioDeviceMatches(device, pair.second); });
525     }
526     // For connection w/o an address, two ports can be found: the template port,
527     // and a connected port (if exists). Make sure we return the connected port.
528     Hal2AidlMapper::Ports::iterator portIt = mPorts.end();
529     for (auto it = mPorts.begin(); it != mPorts.end(); ++it) {
530         if (audioDeviceMatches(device, it->second)) {
531             if (mConnectedPorts.find(it->first) != mConnectedPorts.end()) {
532                 return it;
533             } else {
534                 // Will return 'it' if there is no connected port.
535                 portIt = it;
536             }
537         }
538     }
539     return portIt;
540 }
541 
findPort(const AudioConfig & config,const AudioIoFlags & flags,const std::set<int32_t> & destinationPortIds)542 Hal2AidlMapper::Ports::iterator Hal2AidlMapper::findPort(
543             const AudioConfig& config, const AudioIoFlags& flags,
544             const std::set<int32_t>& destinationPortIds) {
545     auto channelMaskMatches = [](const std::vector<AudioChannelLayout>& channelMasks,
546                                  const AudioChannelLayout& channelMask) {
547         // Return true when 1) the channel mask is none and none of the channel mask from the
548         // collection contains haptic channel mask, or 2) the channel mask collection contains
549         // the queried channel mask.
550         return (channelMask.getTag() == AudioChannelLayout::none &&
551                         std::none_of(channelMasks.begin(), channelMasks.end(),
552                                      containHapticChannel)) ||
553                 std::find(channelMasks.begin(), channelMasks.end(), channelMask)
554                     != channelMasks.end();
555     };
556     auto belongsToProfile = [&config, &channelMaskMatches](const AudioProfile& prof) {
557         return (isDefaultAudioFormat(config.base.format) || prof.format == config.base.format) &&
558                 channelMaskMatches(prof.channelMasks, config.base.channelMask) &&
559                 (config.base.sampleRate == 0 ||
560                         std::find(prof.sampleRates.begin(), prof.sampleRates.end(),
561                                 config.base.sampleRate) != prof.sampleRates.end());
562     };
563     static const std::vector<AudioOutputFlags> kOptionalOutputFlags{AudioOutputFlags::BIT_PERFECT};
564     int optionalFlags = 0;
565     auto flagMatches = [&flags, &optionalFlags](const AudioIoFlags& portFlags) {
566         // Ports should be able to match if the optional flags are not requested.
567         return portFlags == flags ||
568                (portFlags.getTag() == AudioIoFlags::Tag::output &&
569                         AudioIoFlags::make<AudioIoFlags::Tag::output>(
570                                 portFlags.get<AudioIoFlags::Tag::output>() &
571                                         ~optionalFlags) == flags);
572     };
573     auto matcher = [&](const auto& pair) {
574         const auto& p = pair.second;
575         return p.ext.getTag() == AudioPortExt::Tag::mix &&
576                 flagMatches(p.flags) &&
577                 (destinationPortIds.empty() ||
578                         std::any_of(destinationPortIds.begin(), destinationPortIds.end(),
579                                 [&](const int32_t destId) { return mRoutingMatrix.count(
580                                             std::make_pair(p.id, destId)) != 0; })) &&
581                 (p.profiles.empty() ||
582                         std::find_if(p.profiles.begin(), p.profiles.end(), belongsToProfile) !=
583                         p.profiles.end()); };
584     auto result = std::find_if(mPorts.begin(), mPorts.end(), matcher);
585     if (result == mPorts.end() && flags.getTag() == AudioIoFlags::Tag::output) {
586         auto optionalOutputFlagsIt = kOptionalOutputFlags.begin();
587         while (result == mPorts.end() && optionalOutputFlagsIt != kOptionalOutputFlags.end()) {
588             if (isBitPositionFlagSet(
589                         flags.get<AudioIoFlags::Tag::output>(), *optionalOutputFlagsIt)) {
590                 // If the flag is set by the request, it must be matched.
591                 ++optionalOutputFlagsIt;
592                 continue;
593             }
594             optionalFlags |= makeBitPositionFlagMask(*optionalOutputFlagsIt++);
595             result = std::find_if(mPorts.begin(), mPorts.end(), matcher);
596             ALOGI("%s: port for config %s, flags %s was not found in the module %s, "
597                   "retried with excluding optional flags %#x", __func__, config.toString().c_str(),
598                     flags.toString().c_str(), mInstance.c_str(), optionalFlags);
599         }
600     }
601     return result;
602 }
603 
findPortConfig(const AudioDevice & device)604 Hal2AidlMapper::PortConfigs::iterator Hal2AidlMapper::findPortConfig(const AudioDevice& device) {
605     return std::find_if(mPortConfigs.begin(), mPortConfigs.end(),
606             [&](const auto& pair) { return audioDeviceMatches(device, pair.second); });
607 }
608 
findPortConfig(const std::optional<AudioConfig> & config,const std::optional<AudioIoFlags> & flags,int32_t ioHandle)609 Hal2AidlMapper::PortConfigs::iterator Hal2AidlMapper::findPortConfig(
610             const std::optional<AudioConfig>& config,
611             const std::optional<AudioIoFlags>& flags,
612             int32_t ioHandle) {
613     using Tag = AudioPortExt::Tag;
614     return std::find_if(mPortConfigs.begin(), mPortConfigs.end(),
615             [&](const auto& pair) {
616                 const auto& p = pair.second;
617                 LOG_ALWAYS_FATAL_IF(p.ext.getTag() == Tag::mix &&
618                         (!p.sampleRate.has_value() || !p.channelMask.has_value() ||
619                                 !p.format.has_value() || !p.flags.has_value()),
620                         "%s: stored mix port config is not fully specified: %s",
621                         __func__, p.toString().c_str());
622                 return p.ext.getTag() == Tag::mix &&
623                         (!config.has_value() ||
624                                 isConfigEqualToPortConfig(config.value(), p)) &&
625                         (!flags.has_value() || p.flags.value() == flags.value()) &&
626                         p.ext.template get<Tag::mix>().handle == ioHandle; });
627 }
628 
getAudioMixPort(int32_t ioHandle,AudioPort * port)629 status_t Hal2AidlMapper::getAudioMixPort(int32_t ioHandle, AudioPort* port) {
630     auto it = findPortConfig(std::nullopt /*config*/, std::nullopt /*flags*/, ioHandle);
631     if (it == mPortConfigs.end()) {
632         ALOGE("%s, cannot find mix port config for handle %u", __func__, ioHandle);
633         return BAD_VALUE;
634     }
635     return updateAudioPort(it->second.portId, port);
636 }
637 
getAudioPortCached(const::aidl::android::media::audio::common::AudioDevice & device,::aidl::android::media::audio::common::AudioPort * port)638 status_t Hal2AidlMapper::getAudioPortCached(
639         const ::aidl::android::media::audio::common::AudioDevice& device,
640         ::aidl::android::media::audio::common::AudioPort* port) {
641 
642     if (auto portsIt = findPort(device); portsIt != mPorts.end()) {
643         *port = portsIt->second;
644         return OK;
645     }
646     ALOGE("%s: device port for device %s is not found in the module %s",
647             __func__, device.toString().c_str(), mInstance.c_str());
648     return BAD_VALUE;
649 }
650 
initialize()651 status_t Hal2AidlMapper::initialize() {
652     std::vector<AudioPort> ports;
653     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->getAudioPorts(&ports)));
654     ALOGW_IF(ports.empty(), "%s: module %s returned an empty list of audio ports",
655             __func__, mInstance.c_str());
656     mDefaultInputPortId = mDefaultOutputPortId = -1;
657     const int defaultDeviceFlag = 1 << AudioPortDeviceExt::FLAG_INDEX_DEFAULT_DEVICE;
658     for (auto it = ports.begin(); it != ports.end(); ) {
659         const auto& port = *it;
660         if (port.ext.getTag() != AudioPortExt::Tag::device) {
661             ++it;
662             continue;
663         }
664         const AudioPortDeviceExt& deviceExt = port.ext.get<AudioPortExt::Tag::device>();
665         if ((deviceExt.flags & defaultDeviceFlag) != 0) {
666             if (port.flags.getTag() == AudioIoFlags::Tag::input) {
667                 mDefaultInputPortId = port.id;
668             } else if (port.flags.getTag() == AudioIoFlags::Tag::output) {
669                 mDefaultOutputPortId = port.id;
670             }
671         }
672         // For compatibility with HIDL, hide "template" remote submix ports from ports list.
673         if (const auto& devDesc = deviceExt.device;
674                 (devDesc.type.type == AudioDeviceType::IN_SUBMIX ||
675                         devDesc.type.type == AudioDeviceType::OUT_SUBMIX) &&
676                 devDesc.type.connection == AudioDeviceDescription::CONNECTION_VIRTUAL) {
677             if (devDesc.type.type == AudioDeviceType::IN_SUBMIX) {
678                 mRemoteSubmixIn = port;
679             } else {
680                 mRemoteSubmixOut = port;
681             }
682             it = ports.erase(it);
683         } else {
684             ++it;
685         }
686     }
687     if (mRemoteSubmixIn.has_value() != mRemoteSubmixOut.has_value()) {
688         ALOGE("%s: The configuration only has input or output remote submix device, must have both",
689                 __func__);
690         mRemoteSubmixIn.reset();
691         mRemoteSubmixOut.reset();
692     }
693     if (mRemoteSubmixIn.has_value()) {
694         AudioPort connectedRSubmixIn = *mRemoteSubmixIn;
695         connectedRSubmixIn.ext.get<AudioPortExt::Tag::device>().device.address =
696                 AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS;
697         ALOGD("%s: connecting remote submix input", __func__);
698         RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->connectExternalDevice(
699                                 connectedRSubmixIn, &connectedRSubmixIn)));
700         // The template port for the remote submix input couldn't be "default" because it is not
701         // attached. The connected port can now be made default because we never disconnect it.
702         if (mDefaultInputPortId == -1) {
703             mDefaultInputPortId = connectedRSubmixIn.id;
704         }
705         ports.push_back(std::move(connectedRSubmixIn));
706 
707         // Remote submix output must not be connected until the framework actually starts
708         // using it, however for legacy compatibility we need to provide an "augmented template"
709         // port with an address and profiles. It is obtained by connecting the output and then
710         // immediately disconnecting it. This is a cheap operation as we don't open any streams.
711         AudioPort tempConnectedRSubmixOut = *mRemoteSubmixOut;
712         tempConnectedRSubmixOut.ext.get<AudioPortExt::Tag::device>().device.address =
713                 AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS;
714         ALOGD("%s: temporarily connecting and disconnecting remote submix output", __func__);
715         RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->connectExternalDevice(
716                                 tempConnectedRSubmixOut, &tempConnectedRSubmixOut)));
717         RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->disconnectExternalDevice(
718                                 tempConnectedRSubmixOut.id)));
719         tempConnectedRSubmixOut.id = mRemoteSubmixOut->id;
720         ports.push_back(std::move(tempConnectedRSubmixOut));
721     }
722 
723     ALOGI("%s: module %s default port ids: input %d, output %d",
724             __func__, mInstance.c_str(), mDefaultInputPortId, mDefaultOutputPortId);
725     std::transform(ports.begin(), ports.end(), std::inserter(mPorts, mPorts.end()),
726             [](const auto& p) { return std::make_pair(p.id, p); });
727     RETURN_STATUS_IF_ERROR(updateRoutes());
728     std::vector<AudioPortConfig> portConfigs;
729     RETURN_STATUS_IF_ERROR(
730             statusTFromBinderStatus(mModule->getAudioPortConfigs(&portConfigs)));  // OK if empty
731     std::transform(portConfigs.begin(), portConfigs.end(),
732             std::inserter(mPortConfigs, mPortConfigs.end()),
733             [](const auto& p) { return std::make_pair(p.id, p); });
734     std::transform(mPortConfigs.begin(), mPortConfigs.end(),
735             std::inserter(mInitialPortConfigIds, mInitialPortConfigIds.end()),
736             [](const auto& pcPair) { return pcPair.first; });
737     std::vector<AudioPatch> patches;
738     RETURN_STATUS_IF_ERROR(
739             statusTFromBinderStatus(mModule->getAudioPatches(&patches)));  // OK if empty
740     std::transform(patches.begin(), patches.end(),
741             std::inserter(mPatches, mPatches.end()),
742             [](const auto& p) { return std::make_pair(p.id, p); });
743     return OK;
744 }
745 
getPatchIdsByPortId(int32_t portId)746 std::set<int32_t> Hal2AidlMapper::getPatchIdsByPortId(int32_t portId) {
747     std::set<int32_t> result;
748     for (const auto& [patchId, patch] : mPatches) {
749         for (int32_t id : patch.sourcePortConfigIds) {
750             if (portConfigBelongsToPort(id, portId)) {
751                 result.insert(patchId);
752                 break;
753             }
754         }
755         for (int32_t id : patch.sinkPortConfigIds) {
756             if (portConfigBelongsToPort(id, portId)) {
757                 result.insert(patchId);
758                 break;
759             }
760         }
761     }
762     return result;
763 }
764 
prepareToDisconnectExternalDevice(const AudioPort & devicePort)765 status_t Hal2AidlMapper::prepareToDisconnectExternalDevice(const AudioPort& devicePort) {
766     auto portsIt = findPort(devicePort.ext.get<AudioPortExt::device>().device);
767     if (portsIt == mPorts.end()) {
768         return BAD_VALUE;
769     }
770     return statusTFromBinderStatus(mModule->prepareToDisconnectExternalDevice(portsIt->second.id));
771 }
772 
prepareToOpenStream(int32_t ioHandle,const AudioDevice & device,const AudioIoFlags & flags,AudioSource source,Cleanups * cleanups,AudioConfig * config,AudioPortConfig * mixPortConfig,AudioPatch * patch)773 status_t Hal2AidlMapper::prepareToOpenStream(
774         int32_t ioHandle, const AudioDevice& device, const AudioIoFlags& flags,
775         AudioSource source, Cleanups* cleanups, AudioConfig* config,
776         AudioPortConfig* mixPortConfig, AudioPatch* patch) {
777     ALOGD("%p %s: handle %d, device %s, flags %s, source %s, config %s, mix port config %s",
778             this, __func__, ioHandle, device.toString().c_str(),
779             flags.toString().c_str(), toString(source).c_str(),
780             config->toString().c_str(), mixPortConfig->toString().c_str());
781     resetUnusedPatchesAndPortConfigs();
782     const AudioConfig initialConfig = *config;
783     // Find / create AudioPortConfigs for the device port and the mix port,
784     // then find / create a patch between them, and open a stream on the mix port.
785     AudioPortConfig devicePortConfig;
786     bool created = false;
787     RETURN_STATUS_IF_ERROR(findOrCreateDevicePortConfig(device, config, nullptr /*gainConfig*/,
788                     &devicePortConfig, &created));
789     LOG_ALWAYS_FATAL_IF(devicePortConfig.id == 0);
790     if (created) {
791         cleanups->add(&Hal2AidlMapper::resetPortConfig, devicePortConfig.id);
792     }
793     status_t status = prepareToOpenStreamHelper(ioHandle, devicePortConfig.portId,
794             devicePortConfig.id, flags, source, initialConfig, cleanups, config,
795             mixPortConfig, patch);
796     if (status != OK) {
797         // If using the client-provided config did not work out for establishing a mix port config
798         // or patching, try with the device port config. Note that in general device port config and
799         // mix port config are not required to be the same, however they must match if the HAL
800         // module can't perform audio stream conversions.
801         AudioConfig deviceConfig = initialConfig;
802         if (setConfigFromPortConfig(&deviceConfig, devicePortConfig)->base != initialConfig.base) {
803             ALOGD("%s: retrying with device port config: %s", __func__,
804                     devicePortConfig.toString().c_str());
805             status = prepareToOpenStreamHelper(ioHandle, devicePortConfig.portId,
806                     devicePortConfig.id, flags, source, initialConfig, cleanups,
807                     &deviceConfig, mixPortConfig, patch);
808             if (status == OK) {
809                 *config = deviceConfig;
810             }
811         }
812     }
813     return status;
814 }
815 
prepareToOpenStreamHelper(int32_t ioHandle,int32_t devicePortId,int32_t devicePortConfigId,const AudioIoFlags & flags,AudioSource source,const AudioConfig & initialConfig,Cleanups * cleanups,AudioConfig * config,AudioPortConfig * mixPortConfig,AudioPatch * patch)816 status_t Hal2AidlMapper::prepareToOpenStreamHelper(
817         int32_t ioHandle, int32_t devicePortId, int32_t devicePortConfigId,
818         const AudioIoFlags& flags, AudioSource source, const AudioConfig& initialConfig,
819         Cleanups* cleanups, AudioConfig* config, AudioPortConfig* mixPortConfig,
820         AudioPatch* patch) {
821     const bool isInput = flags.getTag() == AudioIoFlags::Tag::input;
822     bool created = false;
823     RETURN_STATUS_IF_ERROR(findOrCreateMixPortConfig(*config, flags, ioHandle, source,
824                     std::set<int32_t>{devicePortId}, mixPortConfig, &created));
825     if (created) {
826         cleanups->add(&Hal2AidlMapper::resetPortConfig, mixPortConfig->id);
827     }
828     setConfigFromPortConfig(config, *mixPortConfig);
829     bool retryWithSuggestedConfig = false;   // By default, let the framework to retry.
830     if (mixPortConfig->id == 0 && config->base == AudioConfigBase{}) {
831         // The HAL proposes a default config, can retry here.
832         retryWithSuggestedConfig = true;
833     } else if (isInput && config->base != initialConfig.base) {
834         // If the resulting config is different, we must stop and provide the config to the
835         // framework so that it can retry.
836         mixPortConfig->id = 0;
837     } else if (!isInput && mixPortConfig->id == 0 &&
838                     (initialConfig.base.format.type == AudioFormatType::PCM ||
839                             !isBitPositionFlagSet(flags.get<AudioIoFlags::output>(),
840                                     AudioOutputFlags::DIRECT) ||
841                             isBitPositionFlagSet(flags.get<AudioIoFlags::output>(),
842                                     AudioOutputFlags::COMPRESS_OFFLOAD))) {
843         // The framework does not retry opening non-direct PCM and IEC61937 outputs, need to retry
844         // here (see 'AudioHwDevice::openOutputStream').
845         retryWithSuggestedConfig = true;
846     }
847     if (mixPortConfig->id == 0 && retryWithSuggestedConfig) {
848         ALOGD("%s: retrying to find/create a mix port config using config %s", __func__,
849                 config->toString().c_str());
850         RETURN_STATUS_IF_ERROR(findOrCreateMixPortConfig(*config, flags, ioHandle, source,
851                         std::set<int32_t>{devicePortId}, mixPortConfig, &created));
852         if (created) {
853             cleanups->add(&Hal2AidlMapper::resetPortConfig, mixPortConfig->id);
854         }
855         setConfigFromPortConfig(config, *mixPortConfig);
856     }
857     if (mixPortConfig->id == 0) {
858         ALOGD("%p %s: returning suggested config for the stream: %s", this, __func__,
859                 config->toString().c_str());
860         return OK;
861     }
862     if (isInput) {
863         RETURN_STATUS_IF_ERROR(findOrCreatePatch(
864                         {devicePortConfigId}, {mixPortConfig->id}, MATCH_BOTH, patch, &created));
865     } else {
866         RETURN_STATUS_IF_ERROR(findOrCreatePatch(
867                         {mixPortConfig->id}, {devicePortConfigId}, MATCH_BOTH, patch, &created));
868     }
869     if (created) {
870         cleanups->add(&Hal2AidlMapper::resetPatch, patch->id);
871     }
872     if (config->frameCount <= 0) {
873         config->frameCount = patch->minimumStreamBufferSizeFrames;
874     }
875     return OK;
876 }
877 
setPortConfig(const AudioPortConfig & requestedPortConfig,const std::set<int32_t> & destinationPortIds,AudioPortConfig * portConfig,Cleanups * cleanups)878 status_t Hal2AidlMapper::setPortConfig(
879         const AudioPortConfig& requestedPortConfig, const std::set<int32_t>& destinationPortIds,
880         AudioPortConfig* portConfig, Cleanups* cleanups) {
881     bool created = false;
882     RETURN_STATUS_IF_ERROR(findOrCreatePortConfig(
883                     requestedPortConfig, destinationPortIds, portConfig, &created));
884     if (created && cleanups != nullptr) {
885         cleanups->add(&Hal2AidlMapper::resetPortConfig, portConfig->id);
886     }
887     return OK;
888 }
889 
releaseAudioPatch(int32_t patchId)890 status_t Hal2AidlMapper::releaseAudioPatch(int32_t patchId) {
891     return releaseAudioPatches({patchId});
892 }
893 
894 // Note: does not reset port configs.
releaseAudioPatch(Patches::iterator it)895 status_t Hal2AidlMapper::releaseAudioPatch(Patches::iterator it) {
896     const int32_t patchId = it->first;
897     if (ndk::ScopedAStatus status = mModule->resetAudioPatch(patchId); !status.isOk()) {
898         ALOGE("%s: error while resetting patch %d: %s",
899                 __func__, patchId, status.getDescription().c_str());
900         return statusTFromBinderStatus(status);
901     }
902     mPatches.erase(it);
903     for (auto it = mFwkPatches.begin(); it != mFwkPatches.end(); ++it) {
904         if (it->second == patchId) {
905             mFwkPatches.erase(it);
906             break;
907         }
908     }
909     return OK;
910 }
911 
releaseAudioPatches(const std::set<int32_t> & patchIds)912 status_t Hal2AidlMapper::releaseAudioPatches(const std::set<int32_t>& patchIds) {
913     status_t result = OK;
914     for (const auto patchId : patchIds) {
915         if (auto it = mPatches.find(patchId); it != mPatches.end()) {
916             releaseAudioPatch(it);
917         } else {
918             ALOGE("%s: patch id %d not found", __func__, patchId);
919             result = BAD_VALUE;
920         }
921     }
922     resetUnusedPortConfigs();
923     return result;
924 }
925 
resetPortConfig(int32_t portConfigId)926 void Hal2AidlMapper::resetPortConfig(int32_t portConfigId) {
927     if (auto it = mPortConfigs.find(portConfigId); it != mPortConfigs.end()) {
928         if (ndk::ScopedAStatus status = mModule->resetAudioPortConfig(portConfigId);
929                 !status.isOk()) {
930             ALOGE("%s: error while resetting port config %d: %s",
931                     __func__, portConfigId, status.getDescription().c_str());
932         }
933         mPortConfigs.erase(it);
934         return;
935     }
936     ALOGE("%s: port config id %d not found", __func__, portConfigId);
937 }
938 
resetUnusedPatchesAndPortConfigs()939 void Hal2AidlMapper::resetUnusedPatchesAndPortConfigs() {
940     // Since patches can be created independently of streams via 'createOrUpdatePatch',
941     // here we only clean up patches for released streams.
942     std::set<int32_t> patchesToRelease;
943     for (auto it = mStreams.begin(); it != mStreams.end(); ) {
944         if (auto streamSp = it->first.promote(); streamSp) {
945             ++it;
946         } else {
947             if (const int32_t patchId = it->second.second; patchId != -1) {
948                 patchesToRelease.insert(patchId);
949             }
950             it = mStreams.erase(it);
951         }
952     }
953     // 'releaseAudioPatches' also resets unused port configs.
954     releaseAudioPatches(patchesToRelease);
955 }
956 
resetUnusedPortConfigs()957 void Hal2AidlMapper::resetUnusedPortConfigs() {
958     // The assumption is that port configs are used to create patches
959     // (or to open streams, but that involves creation of patches, too). Thus,
960     // orphaned port configs can and should be reset.
961     std::set<int32_t> portConfigIdsToReset;
962     std::transform(mPortConfigs.begin(), mPortConfigs.end(),
963             std::inserter(portConfigIdsToReset, portConfigIdsToReset.end()),
964             [](const auto& pcPair) { return pcPair.first; });
965     for (const auto& p : mPatches) {
966         for (int32_t id : p.second.sourcePortConfigIds) portConfigIdsToReset.erase(id);
967         for (int32_t id : p.second.sinkPortConfigIds) portConfigIdsToReset.erase(id);
968     }
969     for (int32_t id : mInitialPortConfigIds) {
970         portConfigIdsToReset.erase(id);
971     }
972     for (const auto& s : mStreams) {
973         portConfigIdsToReset.erase(s.second.first);
974     }
975     for (const auto& portConfigId : portConfigIdsToReset) {
976         resetPortConfig(portConfigId);
977     }
978 }
979 
setDevicePortConnectedState(const AudioPort & devicePort,bool connected)980 status_t Hal2AidlMapper::setDevicePortConnectedState(const AudioPort& devicePort, bool connected) {
981     resetUnusedPatchesAndPortConfigs();
982     if (connected) {
983         AudioDevice matchDevice = devicePort.ext.get<AudioPortExt::device>().device;
984         std::optional<AudioPort> templatePort;
985         auto erasePortAfterConnectionIt = mPorts.end();
986         // Connection of remote submix out with address "0" is a special case. Since there is
987         // already an "augmented template" port with this address in mPorts, we need to replace
988         // it with a connected port.
989         // Connection of remote submix outs with any other address is done as usual except that
990         // the template port is in `mRemoteSubmixOut`.
991         if (mRemoteSubmixOut.has_value() && matchDevice.type.type == AudioDeviceType::OUT_SUBMIX) {
992             if (matchDevice.address == AudioDeviceAddress::make<AudioDeviceAddress::id>(
993                             AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS)) {
994                 erasePortAfterConnectionIt = findPort(matchDevice);
995             }
996             templatePort = mRemoteSubmixOut;
997         } else if (mRemoteSubmixIn.has_value() &&
998                 matchDevice.type.type == AudioDeviceType::IN_SUBMIX) {
999             templatePort = mRemoteSubmixIn;
1000         } else {
1001             // Reset the device address to find the "template" port.
1002             matchDevice.address = AudioDeviceAddress::make<AudioDeviceAddress::id>();
1003         }
1004         if (!templatePort.has_value()) {
1005             auto portsIt = findPort(matchDevice);
1006             if (portsIt == mPorts.end()) {
1007                 // Since 'setConnectedState' is called for all modules, it is normal when the device
1008                 // port not found in every one of them.
1009                 return BAD_VALUE;
1010             } else {
1011                 ALOGD("%s: device port for device %s found in the module %s",
1012                         __func__, matchDevice.toString().c_str(), mInstance.c_str());
1013             }
1014             templatePort = portsIt->second;
1015         }
1016 
1017         // Use the ID of the "template" port, use all the information from the provided port.
1018         AudioPort connectedPort = devicePort;
1019         connectedPort.id = templatePort->id;
1020         RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->connectExternalDevice(
1021                                 connectedPort, &connectedPort)));
1022         const auto [it, inserted] = mPorts.insert(std::make_pair(connectedPort.id, connectedPort));
1023         LOG_ALWAYS_FATAL_IF(!inserted,
1024                 "%s: module %s, duplicate port ID received from HAL: %s, existing port: %s",
1025                 __func__, mInstance.c_str(), connectedPort.toString().c_str(),
1026                 it->second.toString().c_str());
1027         mConnectedPorts.insert(connectedPort.id);
1028         if (erasePortAfterConnectionIt != mPorts.end()) {
1029             mPorts.erase(erasePortAfterConnectionIt);
1030         }
1031     } else {  // !connected
1032         AudioDevice matchDevice = devicePort.ext.get<AudioPortExt::device>().device;
1033         auto portsIt = findPort(matchDevice);
1034         if (portsIt == mPorts.end()) {
1035             // Since 'setConnectedState' is called for all modules, it is normal when the device
1036             // port not found in every one of them.
1037             return BAD_VALUE;
1038         } else {
1039             ALOGD("%s: device port for device %s found in the module %s",
1040                     __func__, matchDevice.toString().c_str(), mInstance.c_str());
1041         }
1042 
1043         // Disconnection of remote submix out with address "0" is a special case. We need to replace
1044         // the connected port entry with the "augmented template".
1045         const int32_t portId = portsIt->second.id;
1046         if (mRemoteSubmixOut.has_value() && matchDevice.type.type == AudioDeviceType::OUT_SUBMIX &&
1047                 matchDevice.address == AudioDeviceAddress::make<AudioDeviceAddress::id>(
1048                         AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS)) {
1049             mDisconnectedPortReplacement = std::make_pair(portId, *mRemoteSubmixOut);
1050             auto& port = mDisconnectedPortReplacement.second;
1051             port.ext.get<AudioPortExt::Tag::device>().device = matchDevice;
1052             port.profiles = portsIt->second.profiles;
1053         }
1054 
1055         // Patches may still exist, the framework may reset or update them later.
1056         // For disconnection to succeed, need to release these patches first.
1057         if (std::set<int32_t> patchIdsToRelease = getPatchIdsByPortId(portId);
1058                 !patchIdsToRelease.empty()) {
1059             FwkPatches releasedPatches;
1060             status_t status = OK;
1061             for (int32_t patchId : patchIdsToRelease) {
1062                 if (auto it = mPatches.find(patchId); it != mPatches.end()) {
1063                     if (status = releaseAudioPatch(it); status != OK) break;
1064                     releasedPatches.insert(std::make_pair(patchId, patchId));
1065                 }
1066             }
1067             resetUnusedPortConfigs();
1068             // Patches created by Hal2AidlMapper during stream creation and not "claimed"
1069             // by the framework must not be surfaced to it.
1070             for (auto& s : mStreams) {
1071                 if (auto it = releasedPatches.find(s.second.second); it != releasedPatches.end()) {
1072                     releasedPatches.erase(it);
1073                 }
1074             }
1075             mFwkPatches.merge(releasedPatches);
1076             LOG_ALWAYS_FATAL_IF(!releasedPatches.empty(),
1077                     "mFwkPatches already contains some of released patches");
1078             if (status != OK) return status;
1079         }
1080         RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->disconnectExternalDevice(portId)));
1081         eraseConnectedPort(portId);
1082     }
1083     return updateRoutes();
1084 }
1085 
updateAudioPort(int32_t portId,AudioPort * port)1086 status_t Hal2AidlMapper::updateAudioPort(int32_t portId, AudioPort* port) {
1087     const status_t status = statusTFromBinderStatus(mModule->getAudioPort(portId, port));
1088     if (status == OK) {
1089         auto portIt = mPorts.find(portId);
1090         if (portIt != mPorts.end()) {
1091             if (port->ext.getTag() == AudioPortExt::Tag::mix && portIt->second != *port) {
1092                 mDynamicMixPortIds.insert(portId);
1093             }
1094             portIt->second = *port;
1095         } else {
1096             ALOGW("%s, port(%d) returned successfully from the HAL but not it is not cached",
1097                   __func__, portId);
1098         }
1099     }
1100     return status;
1101 }
1102 
updateRoutes()1103 status_t Hal2AidlMapper::updateRoutes() {
1104     RETURN_STATUS_IF_ERROR(
1105             statusTFromBinderStatus(mModule->getAudioRoutes(&mRoutes)));
1106     ALOGW_IF(mRoutes.empty(), "%s: module %s returned an empty list of audio routes",
1107             __func__, mInstance.c_str());
1108     if (mRemoteSubmixIn.has_value()) {
1109         // Remove mentions of the template remote submix input from routes.
1110         int32_t rSubmixInId = mRemoteSubmixIn->id;
1111         // Remove mentions of the template remote submix out only if it is not in mPorts
1112         // (that means there is a connected port in mPorts).
1113         int32_t rSubmixOutId = mPorts.find(mRemoteSubmixOut->id) == mPorts.end() ?
1114                 mRemoteSubmixOut->id : -1;
1115         for (auto it = mRoutes.begin(); it != mRoutes.end();) {
1116             auto& route = *it;
1117             if (route.sinkPortId == rSubmixOutId) {
1118                 it = mRoutes.erase(it);
1119                 continue;
1120             }
1121             if (auto routeIt = std::find(route.sourcePortIds.begin(), route.sourcePortIds.end(),
1122                             rSubmixInId); routeIt != route.sourcePortIds.end()) {
1123                 route.sourcePortIds.erase(routeIt);
1124                 if (route.sourcePortIds.empty()) {
1125                     it = mRoutes.erase(it);
1126                     continue;
1127                 }
1128             }
1129             ++it;
1130         }
1131     }
1132     mRoutingMatrix.clear();
1133     for (const auto& r : mRoutes) {
1134         for (auto portId : r.sourcePortIds) {
1135             mRoutingMatrix.emplace(r.sinkPortId, portId);
1136             mRoutingMatrix.emplace(portId, r.sinkPortId);
1137         }
1138     }
1139     return OK;
1140 }
1141 
updateDynamicMixPorts()1142 void Hal2AidlMapper::updateDynamicMixPorts() {
1143     for (int32_t portId : mDynamicMixPortIds) {
1144         if (auto it = mPorts.find(portId); it != mPorts.end()) {
1145             updateAudioPort(portId, &it->second);
1146         } else {
1147             // This must not happen
1148             ALOGE("%s, cannot find port for id=%d", __func__, portId);
1149         }
1150     }
1151 }
1152 
1153 } // namespace android
1154