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 "AidlUtils.h"
29 #include "Hal2AidlMapper.h"
30
31 using aidl::android::aidl_utils::statusTFromBinderStatus;
32 using aidl::android::media::audio::common::AudioChannelLayout;
33 using aidl::android::media::audio::common::AudioConfig;
34 using aidl::android::media::audio::common::AudioConfigBase;
35 using aidl::android::media::audio::common::AudioDevice;
36 using aidl::android::media::audio::common::AudioDeviceAddress;
37 using aidl::android::media::audio::common::AudioDeviceDescription;
38 using aidl::android::media::audio::common::AudioDeviceType;
39 using aidl::android::media::audio::common::AudioFormatDescription;
40 using aidl::android::media::audio::common::AudioFormatType;
41 using aidl::android::media::audio::common::AudioGainConfig;
42 using aidl::android::media::audio::common::AudioInputFlags;
43 using aidl::android::media::audio::common::AudioIoFlags;
44 using aidl::android::media::audio::common::AudioOutputFlags;
45 using aidl::android::media::audio::common::AudioPort;
46 using aidl::android::media::audio::common::AudioPortConfig;
47 using aidl::android::media::audio::common::AudioPortDeviceExt;
48 using aidl::android::media::audio::common::AudioPortExt;
49 using aidl::android::media::audio::common::AudioPortMixExt;
50 using aidl::android::media::audio::common::AudioPortMixExtUseCase;
51 using aidl::android::media::audio::common::AudioProfile;
52 using aidl::android::media::audio::common::AudioSource;
53 using aidl::android::media::audio::common::Int;
54 using aidl::android::hardware::audio::common::isBitPositionFlagSet;
55 using aidl::android::hardware::audio::common::isDefaultAudioFormat;
56 using aidl::android::hardware::audio::common::makeBitPositionFlagMask;
57 using aidl::android::hardware::audio::core::AudioPatch;
58 using aidl::android::hardware::audio::core::AudioRoute;
59 using aidl::android::hardware::audio::core::IModule;
60
61 namespace android {
62
63 namespace {
64
isConfigEqualToPortConfig(const AudioConfig & config,const AudioPortConfig & portConfig)65 bool 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
setConfigFromPortConfig(AudioConfig * config,const AudioPortConfig & portConfig)71 AudioConfig* setConfigFromPortConfig(AudioConfig* config, const AudioPortConfig& portConfig) {
72 config->base.sampleRate = portConfig.sampleRate.value().value;
73 config->base.channelMask = portConfig.channelMask.value();
74 config->base.format = portConfig.format.value();
75 return config;
76 }
77
setPortConfigFromConfig(AudioPortConfig * portConfig,const AudioConfig & config)78 void 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
containHapticChannel(AudioChannelLayout channel)90 bool 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
100 } // namespace
101
Hal2AidlMapper(const std::string & instance,const std::shared_ptr<IModule> & module)102 Hal2AidlMapper::Hal2AidlMapper(const std::string& instance, const std::shared_ptr<IModule>& module)
103 : ConversionHelperAidl("Hal2AidlMapper", instance), mModule(module) {}
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 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());
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 AUGMENT_LOG(I,
156 "fillPortConfigs: retrying to find a mix port config with"
157 " default configuration");
158 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 {
163 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);
169 return BAD_VALUE;
170 }
171 } else {
172 return status;
173 }
174 }
175 LOG_ALWAYS_FATAL_IF(portConfig.id == 0,
176 "fillPortConfigs: initial config: %s, port config: %s",
177 s.toString().c_str(), portConfig.toString().c_str());
178 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.
187 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(),
190 [](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;
210 // 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);
215 auto requestedPatch = patch;
216 RETURN_STATUS_IF_ERROR(findOrCreatePatch(patch, match,
217 &patch, &created));
218 // No cleanup of the patch is needed, it is managed by the framework.
219 *patchId = patch.id;
220 if (!created) {
221 requestedPatch.id = patch.id;
222 if (patch != requestedPatch) {
223 AUGMENT_LOG(I, "Updating transient patch. Current: %s, new: %s",
224 patch.toString().c_str(), requestedPatch.toString().c_str());
225 // 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 }
233 // 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 }
239 }
240 return OK;
241 }
242
createOrUpdatePortConfig(const AudioPortConfig & requestedPortConfig,AudioPortConfig * result,bool * created)243 status_t Hal2AidlMapper::createOrUpdatePortConfig(
244 const AudioPortConfig& requestedPortConfig, AudioPortConfig* result, bool* created) {
245 bool applied = false;
246 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->setAudioPortConfig(
247 requestedPortConfig, result, &applied)));
248 if (!applied) {
249 result->id = 0;
250 *created = false;
251 return OK;
252 }
253
254 int32_t id = result->id;
255 if (requestedPortConfig.id != 0 && requestedPortConfig.id != id) {
256 LOG_ALWAYS_FATAL("%s: requested port config id %d changed to %d", __func__,
257 requestedPortConfig.id, id);
258 }
259
260 auto [_, inserted] = mPortConfigs.insert_or_assign(id, *result);
261 *created = inserted;
262 return OK;
263 }
264
createOrUpdatePortConfigRetry(const AudioPortConfig & requestedPortConfig,AudioPortConfig * result,bool * created)265 status_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) {
277 AUGMENT_LOG(E, "did not apply suggested config %s",
278 suggestedOrAppliedPortConfig.toString().c_str());
279 return NO_INIT;
280 }
281 *result = appliedPortConfig;
282 } else {
283 *result = suggestedOrAppliedPortConfig;
284 }
285 return OK;
286 }
287
eraseConnectedPort(int32_t portId)288 void 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));
294 AUGMENT_LOG(D, "disconnected port replacement: %s", port.toString().c_str());
295 mDisconnectedPortReplacement = std::pair<int32_t, AudioPort>();
296 }
297 updateDynamicMixPorts();
298 }
299
findOrCreatePatch(const AudioPatch & requestedPatch,PatchMatch match,AudioPatch * patch,bool * created)300 status_t Hal2AidlMapper::findOrCreatePatch(
301 const AudioPatch& requestedPatch, PatchMatch match, AudioPatch* patch, bool* created) {
302 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());
306 return findOrCreatePatch(sourcePortConfigIds, sinkPortConfigIds, match, patch, created);
307 }
308
findOrCreatePatch(const std::set<int32_t> & sourcePortConfigIds,const std::set<int32_t> & sinkPortConfigIds,PatchMatch match,AudioPatch * patch,bool * created)309 status_t Hal2AidlMapper::findOrCreatePatch(
310 const std::set<int32_t>& sourcePortConfigIds, const std::set<int32_t>& sinkPortConfigIds,
311 PatchMatch match, AudioPatch* patch, bool* created) {
312 auto patchIt = findPatch(sourcePortConfigIds, sinkPortConfigIds, match);
313 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
findOrCreateDevicePortConfig(const AudioDevice & device,const AudioConfig * config,const AudioGainConfig * gainConfig,AudioPortConfig * portConfig,bool * created)330 status_t Hal2AidlMapper::findOrCreateDevicePortConfig(
331 const AudioDevice& device, const AudioConfig* config, const AudioGainConfig* gainConfig,
332 AudioPortConfig* portConfig, bool* created) {
333 if (auto portConfigIt = findPortConfig(device); portConfigIt == mPortConfigs.end()) {
334 auto portsIt = findPort(device);
335 if (portsIt == mPorts.end()) {
336 AUGMENT_LOG(E, "device port for device %s is not found", device.toString().c_str());
337 return BAD_VALUE;
338 }
339 AudioPortConfig requestedPortConfig;
340 requestedPortConfig.portId = portsIt->first;
341 if (config != nullptr) {
342 setPortConfigFromConfig(&requestedPortConfig, *config);
343 }
344 if (gainConfig != nullptr) {
345 requestedPortConfig.gain = *gainConfig;
346 }
347 return createOrUpdatePortConfigRetry(requestedPortConfig, portConfig, created);
348 } else {
349 AudioPortConfig requestedPortConfig = portConfigIt->second;
350 if (config != nullptr) {
351 setPortConfigFromConfig(&requestedPortConfig, *config);
352 }
353 if (gainConfig != nullptr) {
354 requestedPortConfig.gain = *gainConfig;
355 }
356
357 if (requestedPortConfig != portConfigIt->second) {
358 return createOrUpdatePortConfigRetry(requestedPortConfig, portConfig, created);
359 } else {
360 *portConfig = portConfigIt->second;
361 *created = false;
362 }
363 }
364 return OK;
365 }
366
findOrCreateMixPortConfig(const AudioConfig & config,const std::optional<AudioIoFlags> & flags,int32_t ioHandle,AudioSource source,const std::set<int32_t> & destinationPortIds,AudioPortConfig * portConfig,bool * created)367 status_t Hal2AidlMapper::findOrCreateMixPortConfig(
368 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) {
371 if (auto portConfigIt = findPortConfig(config, flags, ioHandle);
372 portConfigIt == mPortConfigs.end() && flags.has_value()) {
373 // 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();
382 AudioIoFlags matchFlags = flags.value();
383 auto portsIt = findPort(config, matchFlags, destinationPortIds);
384 while (portsIt == mPorts.end() && matchFlags.getTag() == AudioIoFlags::Tag::input
385 && optionalInputFlagsIt != optionalInputFlags.end()) {
386 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);
394 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());
399 }
400 // 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
430 if (portsIt == mPorts.end()) {
431 AUGMENT_LOG(E, "mix port for config %s, flags %s is not found",
432 config.toString().c_str(), matchFlags.toString().c_str());
433 return BAD_VALUE;
434 }
435 AudioPortConfig requestedPortConfig;
436 requestedPortConfig.portId = portsIt->first;
437 setPortConfigFromConfig(&requestedPortConfig, config);
438 requestedPortConfig.flags = portsIt->second.flags;
439 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 }
445 return createOrUpdatePortConfig(requestedPortConfig, portConfig, created);
446 } else if (portConfigIt == mPortConfigs.end() && !flags.has_value()) {
447 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);
451 return BAD_VALUE;
452 } else {
453 AudioPortConfig requestedPortConfig = portConfigIt->second;
454 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;
460 }
461
462 if (requestedPortConfig != portConfigIt->second) {
463 return createOrUpdatePortConfig(requestedPortConfig, portConfig, created);
464 } else {
465 *portConfig = portConfigIt->second;
466 *created = false;
467 }
468 }
469 return OK;
470 }
471
findOrCreatePortConfig(const AudioPortConfig & requestedPortConfig,const std::set<int32_t> & destinationPortIds,AudioPortConfig * portConfig,bool * created)472 status_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()) {
480 AUGMENT_LOG(W, "provided mix port config is not fully specified: %s",
481 p.toString().c_str());
482 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;
490 return findOrCreateMixPortConfig(config, requestedPortConfig.flags,
491 requestedPortConfig.ext.get<Tag::mix>().handle, source, destinationPortIds,
492 portConfig, created);
493 } else if (requestedPortConfig.ext.getTag() == Tag::device) {
494 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));
506 return findOrCreateDevicePortConfig(
507 requestedPortConfig.ext.get<Tag::device>().device, configPtr, gainConfigPtr,
508 portConfig, created);
509 } else {
510 AUGMENT_LOG(D, "device port config does not have audio or gain config specified");
511 return findOrCreateDevicePortConfig(
512 requestedPortConfig.ext.get<Tag::device>().device, nullptr /*config*/,
513 nullptr /*gainConfig*/, portConfig, created);
514 }
515 }
516 AUGMENT_LOG(W, "unsupported audio port config: %s", requestedPortConfig.toString().c_str());
517 return BAD_VALUE;
518 }
519
findPortConfig(const AudioDevice & device,AudioPortConfig * portConfig)520 status_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 }
525 AUGMENT_LOG(E, "could not find a device port config for device %s", device.toString().c_str());
526 return BAD_VALUE;
527 }
528
findPatch(const std::set<int32_t> & sourcePortConfigIds,const std::set<int32_t> & sinkPortConfigIds,PatchMatch match)529 Hal2AidlMapper::Patches::iterator Hal2AidlMapper::findPatch(
530 const std::set<int32_t>& sourcePortConfigIds, const std::set<int32_t>& sinkPortConfigIds,
531 PatchMatch match) {
532 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());
539 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 });
548 }
549
findPort(const AudioDevice & device)550 Hal2AidlMapper::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
findPort(const AudioConfig & config,const AudioIoFlags & flags,const std::set<int32_t> & destinationPortIds)577 Hal2AidlMapper::Ports::iterator Hal2AidlMapper::findPort(
578 const AudioConfig& config, const AudioIoFlags& flags,
579 const std::set<int32_t>& destinationPortIds) {
580 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) {
592 return (isDefaultAudioFormat(config.base.format) || prof.format == config.base.format) &&
593 channelMaskMatches(prof.channelMasks, config.base.channelMask) &&
594 (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);
631 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);
635 }
636 }
637 return result;
638 }
639
findPortConfig(const AudioDevice & device)640 Hal2AidlMapper::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
findPortConfig(const std::optional<AudioConfig> & config,const std::optional<AudioIoFlags> & flags,int32_t ioHandle)645 Hal2AidlMapper::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
getAudioMixPort(int32_t ioHandle,AudioPort * port)665 status_t Hal2AidlMapper::getAudioMixPort(int32_t ioHandle, AudioPort* port) {
666 auto it = findPortConfig(std::nullopt /*config*/, std::nullopt /*flags*/, ioHandle);
667 if (it == mPortConfigs.end()) {
668 AUGMENT_LOG(E, "cannot find mix port config for handle %u", ioHandle);
669 return BAD_VALUE;
670 }
671 return updateAudioPort(it->second.portId, port);
672 }
673
getAudioPortCached(const::aidl::android::media::audio::common::AudioDevice & device,::aidl::android::media::audio::common::AudioPort * port)674 status_t Hal2AidlMapper::getAudioPortCached(
675 const ::aidl::android::media::audio::common::AudioDevice& device,
676 ::aidl::android::media::audio::common::AudioPort* port) {
677 if (auto portsIt = findPort(device); portsIt != mPorts.end()) {
678 *port = portsIt->second;
679 return OK;
680 }
681 AUGMENT_LOG(E, "device port for device %s is not found", device.toString().c_str());
682 return BAD_VALUE;
683 }
684
initialize()685 status_t Hal2AidlMapper::initialize() {
686 std::vector<AudioPort> ports;
687 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->getAudioPorts(&ports)));
688 AUGMENT_LOG_IF(W, ports.empty(), "returned an empty list of audio ports");
689 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()) {
721 AUGMENT_LOG(E,
722 "The configuration only has input or output remote submix device, "
723 "must have both");
724 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;
731 AUGMENT_LOG(D, "connecting remote submix input");
732 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;
748 AUGMENT_LOG(D, "temporarily connecting and disconnecting remote submix output");
749 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
757 AUGMENT_LOG(I, "default port ids: input %d, output %d", mDefaultInputPortId,
758 mDefaultOutputPortId);
759 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
getPatchIdsByPortId(int32_t portId)780 std::set<int32_t> Hal2AidlMapper::getPatchIdsByPortId(int32_t portId) {
781 std::set<int32_t> result;
782 for (const auto& [patchId, patch] : mPatches) {
783 for (int32_t id : patch.sourcePortConfigIds) {
784 if (portConfigBelongsToPort(id, portId)) {
785 result.insert(patchId);
786 break;
787 }
788 }
789 for (int32_t id : patch.sinkPortConfigIds) {
790 if (portConfigBelongsToPort(id, portId)) {
791 result.insert(patchId);
792 break;
793 }
794 }
795 }
796 return result;
797 }
798
prepareToDisconnectExternalDevice(const AudioPort & devicePort)799 status_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
prepareToOpenStream(int32_t ioHandle,const AudioDevice & device,const AudioIoFlags & flags,AudioSource source,Cleanups * cleanups,AudioConfig * config,AudioPortConfig * mixPortConfig,AudioPatch * patch)807 status_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) {
811 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());
815 resetUnusedPatchesAndPortConfigs();
816 const AudioConfig initialConfig = *config;
817 // 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;
821 RETURN_STATUS_IF_ERROR(findOrCreateDevicePortConfig(device, config, nullptr /*gainConfig*/,
822 &devicePortConfig, &created));
823 LOG_ALWAYS_FATAL_IF(devicePortConfig.id == 0);
824 if (created) {
825 cleanups->add(&Hal2AidlMapper::resetPortConfig, devicePortConfig.id);
826 }
827 status_t status = prepareToOpenStreamHelper(ioHandle, devicePortConfig.portId,
828 devicePortConfig.id, flags, source, initialConfig, cleanups, config,
829 mixPortConfig, patch);
830 if (status != OK && !(mRemoteSubmixOut.has_value() &&
831 initialConfig.base.format.type != AudioFormatType::PCM)) {
832 // 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) {
838 AUGMENT_LOG(D, "retrying with device port config: %s",
839 devicePortConfig.toString().c_str());
840 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
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)851 status_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;
858 RETURN_STATUS_IF_ERROR(findOrCreateMixPortConfig(*config, flags, ioHandle, source,
859 std::set<int32_t>{devicePortId}, mixPortConfig, &created));
860 if (created) {
861 cleanups->add(&Hal2AidlMapper::resetPortConfig, mixPortConfig->id);
862 }
863 setConfigFromPortConfig(config, *mixPortConfig);
864 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) {
883 AUGMENT_LOG(D, "retrying to find/create a mix port config using config %s",
884 config->toString().c_str());
885 RETURN_STATUS_IF_ERROR(findOrCreateMixPortConfig(*config, flags, ioHandle, source,
886 std::set<int32_t>{devicePortId}, mixPortConfig, &created));
887 if (created) {
888 cleanups->add(&Hal2AidlMapper::resetPortConfig, mixPortConfig->id);
889 }
890 setConfigFromPortConfig(config, *mixPortConfig);
891 }
892 if (mixPortConfig->id == 0) {
893 AUGMENT_LOG(D, "returning suggested config for the stream: %s",
894 config->toString().c_str());
895 return OK;
896 }
897 if (isInput) {
898 RETURN_STATUS_IF_ERROR(findOrCreatePatch(
899 {devicePortConfigId}, {mixPortConfig->id}, MATCH_BOTH, patch, &created));
900 } else {
901 RETURN_STATUS_IF_ERROR(findOrCreatePatch(
902 {mixPortConfig->id}, {devicePortConfigId}, MATCH_BOTH, patch, &created));
903 }
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
setPortConfig(const AudioPortConfig & requestedPortConfig,const std::set<int32_t> & destinationPortIds,AudioPortConfig * portConfig,Cleanups * cleanups)913 status_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
releaseAudioPatch(int32_t patchId)925 status_t Hal2AidlMapper::releaseAudioPatch(int32_t patchId) {
926 return releaseAudioPatches({patchId});
927 }
928
929 // Note: does not reset port configs.
releaseAudioPatch(Patches::iterator it)930 status_t Hal2AidlMapper::releaseAudioPatch(Patches::iterator it) {
931 const int32_t patchId = it->first;
932 AUGMENT_LOG(D, "patchId %d", patchId);
933 if (ndk::ScopedAStatus status = mModule->resetAudioPatch(patchId); !status.isOk()) {
934 AUGMENT_LOG(E, "error while resetting patch %d: %s", patchId,
935 status.getDescription().c_str());
936 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
releaseAudioPatches(const std::set<int32_t> & patchIds)948 status_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()) {
952 releaseAudioPatch(it);
953 } else {
954 AUGMENT_LOG(E, "patch id %d not found", patchId);
955 result = BAD_VALUE;
956 }
957 }
958 resetUnusedPortConfigs();
959 return result;
960 }
961
resetPortConfig(int32_t portConfigId)962 void Hal2AidlMapper::resetPortConfig(int32_t portConfigId) {
963 if (auto it = mPortConfigs.find(portConfigId); it != mPortConfigs.end()) {
964 AUGMENT_LOG(D, "%s", it->second.toString().c_str());
965 if (ndk::ScopedAStatus status = mModule->resetAudioPortConfig(portConfigId);
966 !status.isOk()) {
967 AUGMENT_LOG(E, "error while resetting port config %d: %s", portConfigId,
968 status.getDescription().c_str());
969 return;
970 }
971 mPortConfigs.erase(it);
972 return;
973 }
974 AUGMENT_LOG(E, "port config id %d not found", portConfigId);
975 }
976
resetUnusedPatchesAndPortConfigs()977 void Hal2AidlMapper::resetUnusedPatchesAndPortConfigs() {
978 // Since patches can be created independently of streams via 'createOrUpdatePatch',
979 // here we only clean up patches for released streams.
980 std::set<int32_t> patchesToRelease;
981 for (auto it = mStreams.begin(); it != mStreams.end(); ) {
982 if (auto streamSp = it->first.promote(); streamSp) {
983 ++it;
984 } else {
985 if (const int32_t patchId = it->second.second; patchId != -1) {
986 patchesToRelease.insert(patchId);
987 }
988 it = mStreams.erase(it);
989 }
990 }
991 // 'releaseAudioPatches' also resets unused port configs.
992 releaseAudioPatches(patchesToRelease);
993 }
994
resetUnusedPortConfigs()995 void Hal2AidlMapper::resetUnusedPortConfigs() {
996 // 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.
999 std::set<int32_t> portConfigIdsToReset;
1000 std::transform(mPortConfigs.begin(), mPortConfigs.end(),
1001 std::inserter(portConfigIdsToReset, portConfigIdsToReset.end()),
1002 [](const auto& pcPair) { return pcPair.first; });
1003 for (const auto& p : mPatches) {
1004 for (int32_t id : p.second.sourcePortConfigIds) portConfigIdsToReset.erase(id);
1005 for (int32_t id : p.second.sinkPortConfigIds) portConfigIdsToReset.erase(id);
1006 }
1007 for (int32_t id : mInitialPortConfigIds) {
1008 portConfigIdsToReset.erase(id);
1009 }
1010 for (const auto& s : mStreams) {
1011 portConfigIdsToReset.erase(s.second.first);
1012 }
1013 for (const auto& portConfigId : portConfigIdsToReset) {
1014 resetPortConfig(portConfigId);
1015 }
1016 }
1017
setDevicePortConnectedState(const AudioPort & devicePort,bool connected)1018 status_t Hal2AidlMapper::setDevicePortConnectedState(const AudioPort& devicePort, bool connected) {
1019 AUGMENT_LOG(D, "state %s, device %s", (connected ? "connected" : "disconnected"),
1020 devicePort.toString().c_str());
1021 resetUnusedPatchesAndPortConfigs();
1022 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 {
1051 AUGMENT_LOG(D, "device port for device %s found", matchDevice.toString().c_str());
1052 }
1053 templatePort = portsIt->second;
1054 }
1055
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));
1062 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());
1065 mConnectedPorts.insert(connectedPort.id);
1066 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 {
1077 AUGMENT_LOG(D, "device port for device %s found", matchDevice.toString().c_str());
1078 }
1079
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 }
1091
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();
1105 // 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 }
1112 mFwkPatches.merge(releasedPatches);
1113 LOG_ALWAYS_FATAL_IF(!releasedPatches.empty(),
1114 "mFwkPatches already contains some of released patches");
1115 if (status != OK) return status;
1116 }
1117 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->disconnectExternalDevice(portId)));
1118 eraseConnectedPort(portId);
1119 }
1120 return updateRoutes();
1121 }
1122
updateAudioPort(int32_t portId,AudioPort * port)1123 status_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()) {
1128 if (port->ext.getTag() == AudioPortExt::Tag::mix && portIt->second != *port) {
1129 mDynamicMixPortIds.insert(portId);
1130 }
1131 portIt->second = *port;
1132 } else {
1133 AUGMENT_LOG(W, "port(%d) returned successfully from the HAL but not it is not cached",
1134 portId);
1135 }
1136 }
1137 return status;
1138 }
1139
updateRoutes()1140 status_t Hal2AidlMapper::updateRoutes() {
1141 RETURN_STATUS_IF_ERROR(
1142 statusTFromBinderStatus(mModule->getAudioRoutes(&mRoutes)));
1143 AUGMENT_LOG_IF(W, mRoutes.empty(), "returned an empty list of audio routes");
1144 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
updateDynamicMixPorts()1178 void 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
1184 AUGMENT_LOG(E, "cannot find port for id=%d", portId);
1185 }
1186 }
1187 }
1188
1189 } // namespace android
1190