blob: 28b12c264dd0f4ecbd2edcdcb42805548234f6f3 [file] [log] [blame]
Mikhail Naganovac9d4e72023-10-23 12:00:09 -07001/*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Hal2AidlMapper"
18// #define LOG_NDEBUG 0
19
20#include <algorithm>
21
22#include <media/audiohal/StreamHalInterface.h>
23#include <error/expected_utils.h>
24#include <system/audio.h> // For AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS
25#include <Utils.h>
26#include <utils/Log.h>
27
28#include "Hal2AidlMapper.h"
29
30using aidl::android::aidl_utils::statusTFromBinderStatus;
31using aidl::android::media::audio::common::AudioChannelLayout;
32using aidl::android::media::audio::common::AudioConfig;
33using aidl::android::media::audio::common::AudioDevice;
34using aidl::android::media::audio::common::AudioDeviceAddress;
35using aidl::android::media::audio::common::AudioDeviceDescription;
36using aidl::android::media::audio::common::AudioDeviceType;
37using aidl::android::media::audio::common::AudioFormatDescription;
38using aidl::android::media::audio::common::AudioInputFlags;
39using aidl::android::media::audio::common::AudioIoFlags;
40using aidl::android::media::audio::common::AudioOutputFlags;
41using aidl::android::media::audio::common::AudioPort;
42using aidl::android::media::audio::common::AudioPortConfig;
43using aidl::android::media::audio::common::AudioPortDeviceExt;
44using aidl::android::media::audio::common::AudioPortExt;
45using aidl::android::media::audio::common::AudioPortMixExt;
46using aidl::android::media::audio::common::AudioPortMixExtUseCase;
47using aidl::android::media::audio::common::AudioProfile;
48using aidl::android::media::audio::common::AudioSource;
49using aidl::android::media::audio::common::Int;
50using aidl::android::hardware::audio::common::isBitPositionFlagSet;
51using aidl::android::hardware::audio::common::isDefaultAudioFormat;
52using aidl::android::hardware::audio::common::makeBitPositionFlagMask;
53using aidl::android::hardware::audio::core::AudioPatch;
54using aidl::android::hardware::audio::core::AudioRoute;
55using aidl::android::hardware::audio::core::IModule;
56
57namespace android {
58
59namespace {
60
61bool isConfigEqualToPortConfig(const AudioConfig& config, const AudioPortConfig& portConfig) {
62 return portConfig.sampleRate.value().value == config.base.sampleRate &&
63 portConfig.channelMask.value() == config.base.channelMask &&
64 portConfig.format.value() == config.base.format;
65}
66
67void setConfigFromPortConfig(AudioConfig* config, const AudioPortConfig& portConfig) {
68 config->base.sampleRate = portConfig.sampleRate.value().value;
69 config->base.channelMask = portConfig.channelMask.value();
70 config->base.format = portConfig.format.value();
71}
72
73void setPortConfigFromConfig(AudioPortConfig* portConfig, const AudioConfig& config) {
74 if (config.base.sampleRate != 0) {
75 portConfig->sampleRate = Int{ .value = config.base.sampleRate };
76 }
77 if (config.base.channelMask != AudioChannelLayout{}) {
78 portConfig->channelMask = config.base.channelMask;
79 }
80 if (config.base.format != AudioFormatDescription{}) {
81 portConfig->format = config.base.format;
82 }
83}
84
85} // namespace
86
87Hal2AidlMapper::Hal2AidlMapper(const std::string& instance, const std::shared_ptr<IModule>& module)
88 : mInstance(instance), mModule(module) {
89}
90
91void Hal2AidlMapper::addStream(const sp<StreamHalInterface>& stream, int32_t patchId) {
92 mStreams.insert(std::pair(stream, patchId));
93}
94
95bool Hal2AidlMapper::audioDeviceMatches(const AudioDevice& device, const AudioPort& p) {
96 if (p.ext.getTag() != AudioPortExt::Tag::device) return false;
97 return p.ext.get<AudioPortExt::Tag::device>().device == device;
98}
99
100bool Hal2AidlMapper::audioDeviceMatches(const AudioDevice& device, const AudioPortConfig& p) {
101 if (p.ext.getTag() != AudioPortExt::Tag::device) return false;
102 if (device.type.type == AudioDeviceType::IN_DEFAULT) {
103 return p.portId == mDefaultInputPortId;
104 } else if (device.type.type == AudioDeviceType::OUT_DEFAULT) {
105 return p.portId == mDefaultOutputPortId;
106 }
107 return p.ext.get<AudioPortExt::Tag::device>().device == device;
108}
109
110status_t Hal2AidlMapper::createOrUpdatePatch(
111 const std::vector<AudioPortConfig>& sources,
112 const std::vector<AudioPortConfig>& sinks,
113 int32_t* patchId, Cleanups* cleanups) {
114 auto existingPatchIt = *patchId != 0 ? mPatches.find(*patchId): mPatches.end();
115 AudioPatch patch;
116 if (existingPatchIt != mPatches.end()) {
117 patch = existingPatchIt->second;
118 patch.sourcePortConfigIds.clear();
119 patch.sinkPortConfigIds.clear();
120 }
121 // The IDs will be found by 'fillPortConfigs', however the original 'sources' and
122 // 'sinks' will not be updated because 'setAudioPatch' only needs IDs. Here we log
123 // the source arguments, where only the audio configuration and device specifications
124 // are relevant.
125 ALOGD("%s: [disregard IDs] sources: %s, sinks: %s",
126 __func__, ::android::internal::ToString(sources).c_str(),
127 ::android::internal::ToString(sinks).c_str());
128 auto fillPortConfigs = [&](
129 const std::vector<AudioPortConfig>& configs,
130 const std::set<int32_t>& destinationPortIds,
131 std::vector<int32_t>* ids, std::set<int32_t>* portIds) -> status_t {
132 for (const auto& s : configs) {
133 AudioPortConfig portConfig;
134 RETURN_STATUS_IF_ERROR(findOrCreatePortConfig(
135 s, destinationPortIds, &portConfig, cleanups));
136 ids->push_back(portConfig.id);
137 if (portIds != nullptr) {
138 portIds->insert(portConfig.portId);
139 }
140 }
141 return OK;
142 };
143 // When looking up port configs, the destinationPortId is only used for mix ports.
144 // Thus, we process device port configs first, and look up the destination port ID from them.
145 bool sourceIsDevice = std::any_of(sources.begin(), sources.end(),
146 [](const auto& config) { return config.ext.getTag() == AudioPortExt::device; });
147 const std::vector<AudioPortConfig>& devicePortConfigs =
148 sourceIsDevice ? sources : sinks;
149 std::vector<int32_t>* devicePortConfigIds =
150 sourceIsDevice ? &patch.sourcePortConfigIds : &patch.sinkPortConfigIds;
151 const std::vector<AudioPortConfig>& mixPortConfigs =
152 sourceIsDevice ? sinks : sources;
153 std::vector<int32_t>* mixPortConfigIds =
154 sourceIsDevice ? &patch.sinkPortConfigIds : &patch.sourcePortConfigIds;
155 std::set<int32_t> devicePortIds;
156 RETURN_STATUS_IF_ERROR(fillPortConfigs(
157 devicePortConfigs, std::set<int32_t>(), devicePortConfigIds, &devicePortIds));
158 RETURN_STATUS_IF_ERROR(fillPortConfigs(
159 mixPortConfigs, devicePortIds, mixPortConfigIds, nullptr));
160 if (existingPatchIt != mPatches.end()) {
161 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
162 mModule->setAudioPatch(patch, &patch)));
163 existingPatchIt->second = patch;
164 } else {
165 bool created = false;
166 RETURN_STATUS_IF_ERROR(findOrCreatePatch(patch, &patch, &created));
167 // Since no cleanup of the patch is needed, 'created' is ignored.
168 *patchId = patch.id;
169 }
170 return OK;
171}
172
173status_t Hal2AidlMapper::createOrUpdatePortConfig(
174 const AudioPortConfig& requestedPortConfig, PortConfigs::iterator* result, bool* created) {
175 AudioPortConfig appliedPortConfig;
176 bool applied = false;
177 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->setAudioPortConfig(
178 requestedPortConfig, &appliedPortConfig, &applied)));
179 if (!applied) {
180 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->setAudioPortConfig(
181 appliedPortConfig, &appliedPortConfig, &applied)));
182 if (!applied) {
183 ALOGE("%s: module %s did not apply suggested config %s",
184 __func__, mInstance.c_str(), appliedPortConfig.toString().c_str());
185 return NO_INIT;
186 }
187 }
188
189 int32_t id = appliedPortConfig.id;
190 if (requestedPortConfig.id != 0 && requestedPortConfig.id != id) {
191 LOG_ALWAYS_FATAL("%s: requested port config id %d changed to %d", __func__,
192 requestedPortConfig.id, id);
193 }
194
195 auto [it, inserted] = mPortConfigs.insert_or_assign(std::move(id),
196 std::move(appliedPortConfig));
197 *result = it;
198 *created = inserted;
199 return OK;
200}
201
202void Hal2AidlMapper::eraseConnectedPort(int32_t portId) {
203 mPorts.erase(portId);
204 mConnectedPorts.erase(portId);
205 if (mDisconnectedPortReplacement.first == portId) {
206 const auto& port = mDisconnectedPortReplacement.second;
207 mPorts.insert(std::make_pair(port.id, port));
208 ALOGD("%s: disconnected port replacement: %s", __func__, port.toString().c_str());
209 mDisconnectedPortReplacement = std::pair<int32_t, AudioPort>();
210 }
211}
212
213status_t Hal2AidlMapper::findOrCreatePatch(
214 const AudioPatch& requestedPatch, AudioPatch* patch, bool* created) {
215 std::set<int32_t> sourcePortConfigIds(requestedPatch.sourcePortConfigIds.begin(),
216 requestedPatch.sourcePortConfigIds.end());
217 std::set<int32_t> sinkPortConfigIds(requestedPatch.sinkPortConfigIds.begin(),
218 requestedPatch.sinkPortConfigIds.end());
219 return findOrCreatePatch(sourcePortConfigIds, sinkPortConfigIds, patch, created);
220}
221
222status_t Hal2AidlMapper::findOrCreatePatch(
223 const std::set<int32_t>& sourcePortConfigIds, const std::set<int32_t>& sinkPortConfigIds,
224 AudioPatch* patch, bool* created) {
225 auto patchIt = findPatch(sourcePortConfigIds, sinkPortConfigIds);
226 if (patchIt == mPatches.end()) {
227 AudioPatch requestedPatch, appliedPatch;
228 requestedPatch.sourcePortConfigIds.insert(requestedPatch.sourcePortConfigIds.end(),
229 sourcePortConfigIds.begin(), sourcePortConfigIds.end());
230 requestedPatch.sinkPortConfigIds.insert(requestedPatch.sinkPortConfigIds.end(),
231 sinkPortConfigIds.begin(), sinkPortConfigIds.end());
232 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->setAudioPatch(
233 requestedPatch, &appliedPatch)));
234 patchIt = mPatches.insert(mPatches.end(), std::make_pair(appliedPatch.id, appliedPatch));
235 *created = true;
236 } else {
237 *created = false;
238 }
239 *patch = patchIt->second;
240 return OK;
241}
242
243status_t Hal2AidlMapper::findOrCreatePortConfig(
244 const AudioDevice& device, const AudioConfig* config, AudioPortConfig* portConfig,
245 bool* created) {
246 auto portConfigIt = findPortConfig(device);
247 if (portConfigIt == mPortConfigs.end()) {
248 auto portsIt = findPort(device);
249 if (portsIt == mPorts.end()) {
250 ALOGE("%s: device port for device %s is not found in the module %s",
251 __func__, device.toString().c_str(), mInstance.c_str());
252 return BAD_VALUE;
253 }
254 AudioPortConfig requestedPortConfig;
255 requestedPortConfig.portId = portsIt->first;
256 if (config != nullptr) {
257 setPortConfigFromConfig(&requestedPortConfig, *config);
258 }
259 RETURN_STATUS_IF_ERROR(createOrUpdatePortConfig(requestedPortConfig, &portConfigIt,
260 created));
261 } else {
262 *created = false;
263 }
264 *portConfig = portConfigIt->second;
265 return OK;
266}
267
268status_t Hal2AidlMapper::findOrCreatePortConfig(
269 const AudioConfig& config, const std::optional<AudioIoFlags>& flags, int32_t ioHandle,
270 AudioSource source, const std::set<int32_t>& destinationPortIds,
271 AudioPortConfig* portConfig, bool* created) {
272 // These flags get removed one by one in this order when retrying port finding.
273 static const std::vector<AudioInputFlags> kOptionalInputFlags{
274 AudioInputFlags::FAST, AudioInputFlags::RAW, AudioInputFlags::VOIP_TX };
275 auto portConfigIt = findPortConfig(config, flags, ioHandle);
276 if (portConfigIt == mPortConfigs.end() && flags.has_value()) {
277 auto optionalInputFlagsIt = kOptionalInputFlags.begin();
278 AudioIoFlags matchFlags = flags.value();
279 auto portsIt = findPort(config, matchFlags, destinationPortIds);
280 while (portsIt == mPorts.end() && matchFlags.getTag() == AudioIoFlags::Tag::input
281 && optionalInputFlagsIt != kOptionalInputFlags.end()) {
282 if (!isBitPositionFlagSet(
283 matchFlags.get<AudioIoFlags::Tag::input>(), *optionalInputFlagsIt)) {
284 ++optionalInputFlagsIt;
285 continue;
286 }
287 matchFlags.set<AudioIoFlags::Tag::input>(matchFlags.get<AudioIoFlags::Tag::input>() &
288 ~makeBitPositionFlagMask(*optionalInputFlagsIt++));
289 portsIt = findPort(config, matchFlags, destinationPortIds);
290 ALOGI("%s: mix port for config %s, flags %s was not found in the module %s, "
291 "retried with flags %s", __func__, config.toString().c_str(),
292 flags.value().toString().c_str(), mInstance.c_str(),
293 matchFlags.toString().c_str());
294 }
295 if (portsIt == mPorts.end()) {
296 ALOGE("%s: mix port for config %s, flags %s is not found in the module %s",
297 __func__, config.toString().c_str(), matchFlags.toString().c_str(),
298 mInstance.c_str());
299 return BAD_VALUE;
300 }
301 AudioPortConfig requestedPortConfig;
302 requestedPortConfig.portId = portsIt->first;
303 setPortConfigFromConfig(&requestedPortConfig, config);
304 requestedPortConfig.ext = AudioPortMixExt{ .handle = ioHandle };
305 if (matchFlags.getTag() == AudioIoFlags::Tag::input
306 && source != AudioSource::SYS_RESERVED_INVALID) {
307 requestedPortConfig.ext.get<AudioPortExt::Tag::mix>().usecase =
308 AudioPortMixExtUseCase::make<AudioPortMixExtUseCase::Tag::source>(source);
309 }
310 RETURN_STATUS_IF_ERROR(createOrUpdatePortConfig(requestedPortConfig, &portConfigIt,
311 created));
312 } else if (portConfigIt == mPortConfigs.end() && !flags.has_value()) {
313 ALOGW("%s: mix port config for %s, handle %d not found in the module %s, "
314 "and was not created as flags are not specified",
315 __func__, config.toString().c_str(), ioHandle, mInstance.c_str());
316 return BAD_VALUE;
317 } else {
318 AudioPortConfig requestedPortConfig = portConfigIt->second;
319 if (requestedPortConfig.ext.getTag() == AudioPortExt::Tag::mix) {
320 AudioPortMixExt& mixExt = requestedPortConfig.ext.get<AudioPortExt::Tag::mix>();
321 if (mixExt.usecase.getTag() == AudioPortMixExtUseCase::Tag::source &&
322 source != AudioSource::SYS_RESERVED_INVALID) {
323 mixExt.usecase.get<AudioPortMixExtUseCase::Tag::source>() = source;
324 }
325 }
326
327 if (requestedPortConfig != portConfigIt->second) {
328 RETURN_STATUS_IF_ERROR(createOrUpdatePortConfig(requestedPortConfig, &portConfigIt,
329 created));
330 } else {
331 *created = false;
332 }
333 }
334 *portConfig = portConfigIt->second;
335 return OK;
336}
337
338status_t Hal2AidlMapper::findOrCreatePortConfig(
339 const AudioPortConfig& requestedPortConfig, const std::set<int32_t>& destinationPortIds,
340 AudioPortConfig* portConfig, bool* created) {
341 using Tag = AudioPortExt::Tag;
342 if (requestedPortConfig.ext.getTag() == Tag::mix) {
343 if (const auto& p = requestedPortConfig;
344 !p.sampleRate.has_value() || !p.channelMask.has_value() ||
345 !p.format.has_value()) {
346 ALOGW("%s: provided mix port config is not fully specified: %s",
347 __func__, p.toString().c_str());
348 return BAD_VALUE;
349 }
350 AudioConfig config;
351 setConfigFromPortConfig(&config, requestedPortConfig);
352 AudioSource source = requestedPortConfig.ext.get<Tag::mix>().usecase.getTag() ==
353 AudioPortMixExtUseCase::Tag::source ?
354 requestedPortConfig.ext.get<Tag::mix>().usecase.
355 get<AudioPortMixExtUseCase::Tag::source>() : AudioSource::SYS_RESERVED_INVALID;
356 return findOrCreatePortConfig(config, requestedPortConfig.flags,
357 requestedPortConfig.ext.get<Tag::mix>().handle, source, destinationPortIds,
358 portConfig, created);
359 } else if (requestedPortConfig.ext.getTag() == Tag::device) {
360 return findOrCreatePortConfig(
361 requestedPortConfig.ext.get<Tag::device>().device, nullptr /*config*/,
362 portConfig, created);
363 }
364 ALOGW("%s: unsupported audio port config: %s",
365 __func__, requestedPortConfig.toString().c_str());
366 return BAD_VALUE;
367}
368
369status_t Hal2AidlMapper::findOrCreatePortConfig(
370 const AudioPortConfig& requestedPortConfig, const std::set<int32_t>& destinationPortIds,
371 AudioPortConfig* portConfig, Cleanups* cleanups) {
372 bool created = false;
373 RETURN_STATUS_IF_ERROR(findOrCreatePortConfig(
374 requestedPortConfig, destinationPortIds, portConfig, &created));
375 if (created && cleanups != nullptr) {
376 cleanups->add(&Hal2AidlMapper::resetPortConfig, portConfig->id);
377 }
378 return OK;
379}
380
381status_t Hal2AidlMapper::findPortConfig(const AudioDevice& device, AudioPortConfig* portConfig) {
382 if (auto it = findPortConfig(device); it != mPortConfigs.end()) {
383 *portConfig = it->second;
384 return OK;
385 }
386 ALOGE("%s: could not find a configured device port for device %s",
387 __func__, device.toString().c_str());
388 return BAD_VALUE;
389}
390
391Hal2AidlMapper::Patches::iterator Hal2AidlMapper::findPatch(
392 const std::set<int32_t>& sourcePortConfigIds, const std::set<int32_t>& sinkPortConfigIds) {
393 return std::find_if(mPatches.begin(), mPatches.end(),
394 [&](const auto& pair) {
395 const auto& p = pair.second;
396 std::set<int32_t> patchSrcs(
397 p.sourcePortConfigIds.begin(), p.sourcePortConfigIds.end());
398 std::set<int32_t> patchSinks(
399 p.sinkPortConfigIds.begin(), p.sinkPortConfigIds.end());
400 return sourcePortConfigIds == patchSrcs && sinkPortConfigIds == patchSinks; });
401}
402
403Hal2AidlMapper::Ports::iterator Hal2AidlMapper::findPort(const AudioDevice& device) {
404 if (device.type.type == AudioDeviceType::IN_DEFAULT) {
405 return mPorts.find(mDefaultInputPortId);
406 } else if (device.type.type == AudioDeviceType::OUT_DEFAULT) {
407 return mPorts.find(mDefaultOutputPortId);
408 }
409 if (device.address.getTag() != AudioDeviceAddress::id ||
410 !device.address.get<AudioDeviceAddress::id>().empty()) {
411 return std::find_if(mPorts.begin(), mPorts.end(),
412 [&](const auto& pair) { return audioDeviceMatches(device, pair.second); });
413 }
414 // For connection w/o an address, two ports can be found: the template port,
415 // and a connected port (if exists). Make sure we return the connected port.
416 Hal2AidlMapper::Ports::iterator portIt = mPorts.end();
417 for (auto it = mPorts.begin(); it != mPorts.end(); ++it) {
418 if (audioDeviceMatches(device, it->second)) {
419 if (mConnectedPorts.find(it->first) != mConnectedPorts.end()) {
420 return it;
421 } else {
422 // Will return 'it' if there is no connected port.
423 portIt = it;
424 }
425 }
426 }
427 return portIt;
428}
429
430Hal2AidlMapper::Ports::iterator Hal2AidlMapper::findPort(
431 const AudioConfig& config, const AudioIoFlags& flags,
432 const std::set<int32_t>& destinationPortIds) {
433 auto belongsToProfile = [&config](const AudioProfile& prof) {
434 return (isDefaultAudioFormat(config.base.format) || prof.format == config.base.format) &&
435 (config.base.channelMask.getTag() == AudioChannelLayout::none ||
436 std::find(prof.channelMasks.begin(), prof.channelMasks.end(),
437 config.base.channelMask) != prof.channelMasks.end()) &&
438 (config.base.sampleRate == 0 ||
439 std::find(prof.sampleRates.begin(), prof.sampleRates.end(),
440 config.base.sampleRate) != prof.sampleRates.end());
441 };
442 static const std::vector<AudioOutputFlags> kOptionalOutputFlags{AudioOutputFlags::BIT_PERFECT};
443 int optionalFlags = 0;
444 auto flagMatches = [&flags, &optionalFlags](const AudioIoFlags& portFlags) {
445 // Ports should be able to match if the optional flags are not requested.
446 return portFlags == flags ||
447 (portFlags.getTag() == AudioIoFlags::Tag::output &&
448 AudioIoFlags::make<AudioIoFlags::Tag::output>(
449 portFlags.get<AudioIoFlags::Tag::output>() &
450 ~optionalFlags) == flags);
451 };
452 auto matcher = [&](const auto& pair) {
453 const auto& p = pair.second;
454 return p.ext.getTag() == AudioPortExt::Tag::mix &&
455 flagMatches(p.flags) &&
456 (destinationPortIds.empty() ||
457 std::any_of(destinationPortIds.begin(), destinationPortIds.end(),
458 [&](const int32_t destId) { return mRoutingMatrix.count(
459 std::make_pair(p.id, destId)) != 0; })) &&
460 (p.profiles.empty() ||
461 std::find_if(p.profiles.begin(), p.profiles.end(), belongsToProfile) !=
462 p.profiles.end()); };
463 auto result = std::find_if(mPorts.begin(), mPorts.end(), matcher);
464 if (result == mPorts.end() && flags.getTag() == AudioIoFlags::Tag::output) {
465 auto optionalOutputFlagsIt = kOptionalOutputFlags.begin();
466 while (result == mPorts.end() && optionalOutputFlagsIt != kOptionalOutputFlags.end()) {
467 if (isBitPositionFlagSet(
468 flags.get<AudioIoFlags::Tag::output>(), *optionalOutputFlagsIt)) {
469 // If the flag is set by the request, it must be matched.
470 ++optionalOutputFlagsIt;
471 continue;
472 }
473 optionalFlags |= makeBitPositionFlagMask(*optionalOutputFlagsIt++);
474 result = std::find_if(mPorts.begin(), mPorts.end(), matcher);
475 ALOGI("%s: port for config %s, flags %s was not found in the module %s, "
476 "retried with excluding optional flags %#x", __func__, config.toString().c_str(),
477 flags.toString().c_str(), mInstance.c_str(), optionalFlags);
478 }
479 }
480 return result;
481}
482
483Hal2AidlMapper::PortConfigs::iterator Hal2AidlMapper::findPortConfig(const AudioDevice& device) {
484 return std::find_if(mPortConfigs.begin(), mPortConfigs.end(),
485 [&](const auto& pair) { return audioDeviceMatches(device, pair.second); });
486}
487
488Hal2AidlMapper::PortConfigs::iterator Hal2AidlMapper::findPortConfig(
489 const std::optional<AudioConfig>& config,
490 const std::optional<AudioIoFlags>& flags,
491 int32_t ioHandle) {
492 using Tag = AudioPortExt::Tag;
493 return std::find_if(mPortConfigs.begin(), mPortConfigs.end(),
494 [&](const auto& pair) {
495 const auto& p = pair.second;
496 LOG_ALWAYS_FATAL_IF(p.ext.getTag() == Tag::mix &&
497 (!p.sampleRate.has_value() || !p.channelMask.has_value() ||
498 !p.format.has_value() || !p.flags.has_value()),
499 "%s: stored mix port config is not fully specified: %s",
500 __func__, p.toString().c_str());
501 return p.ext.getTag() == Tag::mix &&
502 (!config.has_value() ||
503 isConfigEqualToPortConfig(config.value(), p)) &&
504 (!flags.has_value() || p.flags.value() == flags.value()) &&
505 p.ext.template get<Tag::mix>().handle == ioHandle; });
506}
507
508status_t Hal2AidlMapper::getAudioMixPort(int32_t ioHandle, AudioPort* port) {
509 auto it = findPortConfig(std::nullopt /*config*/, std::nullopt /*flags*/, ioHandle);
510 if (it == mPortConfigs.end()) {
511 ALOGE("%s, cannot find mix port config for handle %u", __func__, ioHandle);
512 return BAD_VALUE;
513 }
514 return updateAudioPort(it->second.portId, port);
515}
516
517status_t Hal2AidlMapper::getAudioPortCached(
518 const ::aidl::android::media::audio::common::AudioDevice& device,
519 ::aidl::android::media::audio::common::AudioPort* port) {
520
521 if (auto portsIt = findPort(device); portsIt != mPorts.end()) {
522 *port = portsIt->second;
523 return OK;
524 }
525 ALOGE("%s: device port for device %s is not found in the module %s",
526 __func__, device.toString().c_str(), mInstance.c_str());
527 return BAD_VALUE;
528}
529
530status_t Hal2AidlMapper::initialize() {
531 std::vector<AudioPort> ports;
532 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->getAudioPorts(&ports)));
533 ALOGW_IF(ports.empty(), "%s: module %s returned an empty list of audio ports",
534 __func__, mInstance.c_str());
535 mDefaultInputPortId = mDefaultOutputPortId = -1;
536 const int defaultDeviceFlag = 1 << AudioPortDeviceExt::FLAG_INDEX_DEFAULT_DEVICE;
537 for (auto it = ports.begin(); it != ports.end(); ) {
538 const auto& port = *it;
539 if (port.ext.getTag() != AudioPortExt::Tag::device) {
540 ++it;
541 continue;
542 }
543 const AudioPortDeviceExt& deviceExt = port.ext.get<AudioPortExt::Tag::device>();
544 if ((deviceExt.flags & defaultDeviceFlag) != 0) {
545 if (port.flags.getTag() == AudioIoFlags::Tag::input) {
546 mDefaultInputPortId = port.id;
547 } else if (port.flags.getTag() == AudioIoFlags::Tag::output) {
548 mDefaultOutputPortId = port.id;
549 }
550 }
551 // For compatibility with HIDL, hide "template" remote submix ports from ports list.
552 if (const auto& devDesc = deviceExt.device;
553 (devDesc.type.type == AudioDeviceType::IN_SUBMIX ||
554 devDesc.type.type == AudioDeviceType::OUT_SUBMIX) &&
555 devDesc.type.connection == AudioDeviceDescription::CONNECTION_VIRTUAL) {
556 if (devDesc.type.type == AudioDeviceType::IN_SUBMIX) {
557 mRemoteSubmixIn = port;
558 } else {
559 mRemoteSubmixOut = port;
560 }
561 it = ports.erase(it);
562 } else {
563 ++it;
564 }
565 }
566 if (mRemoteSubmixIn.has_value() != mRemoteSubmixOut.has_value()) {
567 ALOGE("%s: The configuration only has input or output remote submix device, must have both",
568 __func__);
569 mRemoteSubmixIn.reset();
570 mRemoteSubmixOut.reset();
571 }
572 if (mRemoteSubmixIn.has_value()) {
573 AudioPort connectedRSubmixIn = *mRemoteSubmixIn;
574 connectedRSubmixIn.ext.get<AudioPortExt::Tag::device>().device.address =
575 AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS;
576 ALOGD("%s: connecting remote submix input", __func__);
577 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->connectExternalDevice(
578 connectedRSubmixIn, &connectedRSubmixIn)));
579 // The template port for the remote submix input couldn't be "default" because it is not
580 // attached. The connected port can now be made default because we never disconnect it.
581 if (mDefaultInputPortId == -1) {
582 mDefaultInputPortId = connectedRSubmixIn.id;
583 }
584 ports.push_back(std::move(connectedRSubmixIn));
585
586 // Remote submix output must not be connected until the framework actually starts
587 // using it, however for legacy compatibility we need to provide an "augmented template"
588 // port with an address and profiles. It is obtained by connecting the output and then
589 // immediately disconnecting it. This is a cheap operation as we don't open any streams.
590 AudioPort tempConnectedRSubmixOut = *mRemoteSubmixOut;
591 tempConnectedRSubmixOut.ext.get<AudioPortExt::Tag::device>().device.address =
592 AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS;
593 ALOGD("%s: temporarily connecting and disconnecting remote submix output", __func__);
594 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->connectExternalDevice(
595 tempConnectedRSubmixOut, &tempConnectedRSubmixOut)));
596 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->disconnectExternalDevice(
597 tempConnectedRSubmixOut.id)));
598 tempConnectedRSubmixOut.id = mRemoteSubmixOut->id;
599 ports.push_back(std::move(tempConnectedRSubmixOut));
600 }
601
602 ALOGI("%s: module %s default port ids: input %d, output %d",
603 __func__, mInstance.c_str(), mDefaultInputPortId, mDefaultOutputPortId);
604 std::transform(ports.begin(), ports.end(), std::inserter(mPorts, mPorts.end()),
605 [](const auto& p) { return std::make_pair(p.id, p); });
606 RETURN_STATUS_IF_ERROR(updateRoutes());
607 std::vector<AudioPortConfig> portConfigs;
608 RETURN_STATUS_IF_ERROR(
609 statusTFromBinderStatus(mModule->getAudioPortConfigs(&portConfigs))); // OK if empty
610 std::transform(portConfigs.begin(), portConfigs.end(),
611 std::inserter(mPortConfigs, mPortConfigs.end()),
612 [](const auto& p) { return std::make_pair(p.id, p); });
613 std::transform(mPortConfigs.begin(), mPortConfigs.end(),
614 std::inserter(mInitialPortConfigIds, mInitialPortConfigIds.end()),
615 [](const auto& pcPair) { return pcPair.first; });
616 std::vector<AudioPatch> patches;
617 RETURN_STATUS_IF_ERROR(
618 statusTFromBinderStatus(mModule->getAudioPatches(&patches))); // OK if empty
619 std::transform(patches.begin(), patches.end(),
620 std::inserter(mPatches, mPatches.end()),
621 [](const auto& p) { return std::make_pair(p.id, p); });
622 return OK;
623}
624
625bool Hal2AidlMapper::isPortHeldByAStream(int32_t portId) {
626 // It is assumed that mStreams has already been cleaned up.
627 for (const auto& streamPair : mStreams) {
628 int32_t patchId = streamPair.second;
629 auto patchIt = mPatches.find(patchId);
630 if (patchIt == mPatches.end()) continue;
631 for (int32_t id : patchIt->second.sourcePortConfigIds) {
632 auto portConfigIt = mPortConfigs.find(id);
633 if (portConfigIt != mPortConfigs.end() && portConfigIt->second.portId == portId) {
634 return true;
635 }
636 }
637 for (int32_t id : patchIt->second.sinkPortConfigIds) {
638 auto portConfigIt = mPortConfigs.find(id);
639 if (portConfigIt != mPortConfigs.end() && portConfigIt->second.portId == portId) {
640 return true;
641 }
642 }
643 }
644 return false;
645}
646
647status_t Hal2AidlMapper::prepareToOpenStream(
648 int32_t ioHandle, const AudioDevice& device, const AudioIoFlags& flags,
649 AudioSource source, Cleanups* cleanups, AudioConfig* config,
650 AudioPortConfig* mixPortConfig, AudioPatch* patch) {
651 ALOGD("%p %s: handle %d, device %s, flags %s, source %s, config %s, mix port config %s",
652 this, __func__, ioHandle, device.toString().c_str(),
653 flags.toString().c_str(), toString(source).c_str(),
654 config->toString().c_str(), mixPortConfig->toString().c_str());
655 resetUnusedPatchesAndPortConfigs();
656 const bool isInput = flags.getTag() == AudioIoFlags::Tag::input;
657 // Find / create AudioPortConfigs for the device port and the mix port,
658 // then find / create a patch between them, and open a stream on the mix port.
659 AudioPortConfig devicePortConfig;
660 bool created = false;
661 RETURN_STATUS_IF_ERROR(findOrCreatePortConfig(device, config,
662 &devicePortConfig, &created));
663 if (created) {
664 cleanups->add(&Hal2AidlMapper::resetPortConfig, devicePortConfig.id);
665 }
666 RETURN_STATUS_IF_ERROR(findOrCreatePortConfig(*config, flags, ioHandle, source,
667 std::set<int32_t>{devicePortConfig.portId}, mixPortConfig, &created));
668 if (created) {
669 cleanups->add(&Hal2AidlMapper::resetPortConfig, mixPortConfig->id);
670 }
671 setConfigFromPortConfig(config, *mixPortConfig);
672 if (isInput) {
673 RETURN_STATUS_IF_ERROR(findOrCreatePatch(
674 {devicePortConfig.id}, {mixPortConfig->id}, patch, &created));
675 } else {
676 RETURN_STATUS_IF_ERROR(findOrCreatePatch(
677 {mixPortConfig->id}, {devicePortConfig.id}, patch, &created));
678 }
679 if (created) {
680 cleanups->add(&Hal2AidlMapper::resetPatch, patch->id);
681 }
682 if (config->frameCount <= 0) {
683 config->frameCount = patch->minimumStreamBufferSizeFrames;
684 }
685 return OK;
686}
687
688status_t Hal2AidlMapper::releaseAudioPatch(int32_t patchId) {
689 if (auto it = mPatches.find(patchId); it != mPatches.end()) {
690 mPatches.erase(it);
691 if (ndk::ScopedAStatus status = mModule->resetAudioPatch(patchId); !status.isOk()) {
692 ALOGE("%s: error while resetting patch %d: %s",
693 __func__, patchId, status.getDescription().c_str());
694 return statusTFromBinderStatus(status);
695 }
696 return OK;
697 }
698 ALOGE("%s: patch id %d not found", __func__, patchId);
699 return BAD_VALUE;
700}
701
702void Hal2AidlMapper::resetPatch(int32_t patchId) {
703 (void)releaseAudioPatch(patchId);
704}
705
706void Hal2AidlMapper::resetPortConfig(int32_t portConfigId) {
707 if (auto it = mPortConfigs.find(portConfigId); it != mPortConfigs.end()) {
708 mPortConfigs.erase(it);
709 if (ndk::ScopedAStatus status = mModule->resetAudioPortConfig(portConfigId);
710 !status.isOk()) {
711 ALOGE("%s: error while resetting port config %d: %s",
712 __func__, portConfigId, status.getDescription().c_str());
713 }
714 return;
715 }
716 ALOGE("%s: port config id %d not found", __func__, portConfigId);
717}
718
719void Hal2AidlMapper::resetUnusedPatches() {
720 // Since patches can be created independently of streams via 'createAudioPatch',
721 // here we only clean up patches for released streams.
722 for (auto it = mStreams.begin(); it != mStreams.end(); ) {
723 if (auto streamSp = it->first.promote(); streamSp) {
724 ++it;
725 } else {
726 resetPatch(it->second);
727 it = mStreams.erase(it);
728 }
729 }
730}
731
732void Hal2AidlMapper::resetUnusedPatchesAndPortConfigs() {
733 resetUnusedPatches();
734 resetUnusedPortConfigs();
735}
736
737void Hal2AidlMapper::resetUnusedPortConfigs() {
738 // The assumption is that port configs are used to create patches
739 // (or to open streams, but that involves creation of patches, too). Thus,
740 // orphaned port configs can and should be reset.
741 std::map<int32_t, int32_t /*portID*/> portConfigIds;
742 std::transform(mPortConfigs.begin(), mPortConfigs.end(),
743 std::inserter(portConfigIds, portConfigIds.end()),
744 [](const auto& pcPair) { return std::make_pair(pcPair.first, pcPair.second.portId); });
745 for (const auto& p : mPatches) {
746 for (int32_t id : p.second.sourcePortConfigIds) portConfigIds.erase(id);
747 for (int32_t id : p.second.sinkPortConfigIds) portConfigIds.erase(id);
748 }
749 for (int32_t id : mInitialPortConfigIds) {
750 portConfigIds.erase(id);
751 }
752 std::set<int32_t> retryDeviceDisconnection;
753 for (const auto& portConfigAndIdPair : portConfigIds) {
754 resetPortConfig(portConfigAndIdPair.first);
755 if (const auto it = mConnectedPorts.find(portConfigAndIdPair.second);
756 it != mConnectedPorts.end() && it->second) {
757 retryDeviceDisconnection.insert(portConfigAndIdPair.second);
758 }
759 }
760 for (int32_t portId : retryDeviceDisconnection) {
761 if (!isPortHeldByAStream(portId)) {
762 if (auto status = mModule->disconnectExternalDevice(portId); status.isOk()) {
763 eraseConnectedPort(portId);
764 ALOGD("%s: executed postponed external device disconnection for port ID %d",
765 __func__, portId);
766 }
767 }
768 }
769 if (!retryDeviceDisconnection.empty()) {
770 updateRoutes();
771 }
772}
773
774status_t Hal2AidlMapper::setDevicePortConnectedState(const AudioPort& devicePort, bool connected) {
775 if (connected) {
776 AudioDevice matchDevice = devicePort.ext.get<AudioPortExt::device>().device;
777 std::optional<AudioPort> templatePort;
778 auto erasePortAfterConnectionIt = mPorts.end();
779 // Connection of remote submix out with address "0" is a special case. Since there is
780 // already an "augmented template" port with this address in mPorts, we need to replace
781 // it with a connected port.
782 // Connection of remote submix outs with any other address is done as usual except that
783 // the template port is in `mRemoteSubmixOut`.
784 if (mRemoteSubmixOut.has_value() && matchDevice.type.type == AudioDeviceType::OUT_SUBMIX) {
785 if (matchDevice.address == AudioDeviceAddress::make<AudioDeviceAddress::id>(
786 AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS)) {
787 erasePortAfterConnectionIt = findPort(matchDevice);
788 }
789 templatePort = mRemoteSubmixOut;
790 } else if (mRemoteSubmixIn.has_value() &&
791 matchDevice.type.type == AudioDeviceType::IN_SUBMIX) {
792 templatePort = mRemoteSubmixIn;
793 } else {
794 // Reset the device address to find the "template" port.
795 matchDevice.address = AudioDeviceAddress::make<AudioDeviceAddress::id>();
796 }
797 if (!templatePort.has_value()) {
798 auto portsIt = findPort(matchDevice);
799 if (portsIt == mPorts.end()) {
800 // Since 'setConnectedState' is called for all modules, it is normal when the device
801 // port not found in every one of them.
802 return BAD_VALUE;
803 } else {
804 ALOGD("%s: device port for device %s found in the module %s",
805 __func__, matchDevice.toString().c_str(), mInstance.c_str());
806 }
807 templatePort = portsIt->second;
808 }
809 resetUnusedPatchesAndPortConfigs();
810
811 // Use the ID of the "template" port, use all the information from the provided port.
812 AudioPort connectedPort = devicePort;
813 connectedPort.id = templatePort->id;
814 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mModule->connectExternalDevice(
815 connectedPort, &connectedPort)));
816 const auto [it, inserted] = mPorts.insert(std::make_pair(connectedPort.id, connectedPort));
817 LOG_ALWAYS_FATAL_IF(!inserted,
818 "%s: module %s, duplicate port ID received from HAL: %s, existing port: %s",
819 __func__, mInstance.c_str(), connectedPort.toString().c_str(),
820 it->second.toString().c_str());
821 mConnectedPorts[connectedPort.id] = false;
822 if (erasePortAfterConnectionIt != mPorts.end()) {
823 mPorts.erase(erasePortAfterConnectionIt);
824 }
825 } else { // !connected
826 AudioDevice matchDevice = devicePort.ext.get<AudioPortExt::device>().device;
827 auto portsIt = findPort(matchDevice);
828 if (portsIt == mPorts.end()) {
829 // Since 'setConnectedState' is called for all modules, it is normal when the device
830 // port not found in every one of them.
831 return BAD_VALUE;
832 } else {
833 ALOGD("%s: device port for device %s found in the module %s",
834 __func__, matchDevice.toString().c_str(), mInstance.c_str());
835 }
836 resetUnusedPatchesAndPortConfigs();
837
838 // Disconnection of remote submix out with address "0" is a special case. We need to replace
839 // the connected port entry with the "augmented template".
840 const int32_t portId = portsIt->second.id;
841 if (mRemoteSubmixOut.has_value() && matchDevice.type.type == AudioDeviceType::OUT_SUBMIX &&
842 matchDevice.address == AudioDeviceAddress::make<AudioDeviceAddress::id>(
843 AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS)) {
844 mDisconnectedPortReplacement = std::make_pair(portId, *mRemoteSubmixOut);
845 auto& port = mDisconnectedPortReplacement.second;
846 port.ext.get<AudioPortExt::Tag::device>().device = matchDevice;
847 port.profiles = portsIt->second.profiles;
848 }
849 // Streams are closed by AudioFlinger independently from device disconnections.
850 // It is possible that the stream has not been closed yet.
851 if (!isPortHeldByAStream(portId)) {
852 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
853 mModule->disconnectExternalDevice(portId)));
854 eraseConnectedPort(portId);
855 } else {
856 ALOGD("%s: since device port ID %d is used by a stream, "
857 "external device disconnection postponed", __func__, portId);
858 mConnectedPorts[portId] = true;
859 }
860 }
861 return updateRoutes();
862}
863
864status_t Hal2AidlMapper::updateAudioPort(int32_t portId, AudioPort* port) {
865 const status_t status = statusTFromBinderStatus(mModule->getAudioPort(portId, port));
866 if (status == OK) {
867 auto portIt = mPorts.find(portId);
868 if (portIt != mPorts.end()) {
869 portIt->second = *port;
870 } else {
871 ALOGW("%s, port(%d) returned successfully from the HAL but not it is not cached",
872 __func__, portId);
873 }
874 }
875 return status;
876}
877
878status_t Hal2AidlMapper::updateRoutes() {
879 RETURN_STATUS_IF_ERROR(
880 statusTFromBinderStatus(mModule->getAudioRoutes(&mRoutes)));
881 ALOGW_IF(mRoutes.empty(), "%s: module %s returned an empty list of audio routes",
882 __func__, mInstance.c_str());
883 if (mRemoteSubmixIn.has_value()) {
884 // Remove mentions of the template remote submix input from routes.
885 int32_t rSubmixInId = mRemoteSubmixIn->id;
886 // Remove mentions of the template remote submix out only if it is not in mPorts
887 // (that means there is a connected port in mPorts).
888 int32_t rSubmixOutId = mPorts.find(mRemoteSubmixOut->id) == mPorts.end() ?
889 mRemoteSubmixOut->id : -1;
890 for (auto it = mRoutes.begin(); it != mRoutes.end();) {
891 auto& route = *it;
892 if (route.sinkPortId == rSubmixOutId) {
893 it = mRoutes.erase(it);
894 continue;
895 }
896 if (auto routeIt = std::find(route.sourcePortIds.begin(), route.sourcePortIds.end(),
897 rSubmixInId); routeIt != route.sourcePortIds.end()) {
898 route.sourcePortIds.erase(routeIt);
899 if (route.sourcePortIds.empty()) {
900 it = mRoutes.erase(it);
901 continue;
902 }
903 }
904 ++it;
905 }
906 }
907 mRoutingMatrix.clear();
908 for (const auto& r : mRoutes) {
909 for (auto portId : r.sourcePortIds) {
910 mRoutingMatrix.emplace(r.sinkPortId, portId);
911 mRoutingMatrix.emplace(portId, r.sinkPortId);
912 }
913 }
914 return OK;
915}
916
917} // namespace android