blob: d48729fd5f49a51795ed26ad8845737531a75d04 [file] [log] [blame]
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001/*
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#include <algorithm>
18#include <set>
19
20#define LOG_TAG "AHAL_Module"
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000021#include <aidl/android/media/audio/common/AudioInputFlags.h>
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000022#include <aidl/android/media/audio/common/AudioOutputFlags.h>
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -070023#include <android-base/logging.h>
24#include <android/binder_ibinder_platform.h>
25#include <error/expected_utils.h>
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000026
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +000027#include "core-impl/Configuration.h"
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000028#include "core-impl/Module.h"
Mikhail Naganovb03b5c42023-07-26 13:13:35 -070029#include "core-impl/ModuleBluetooth.h"
Mikhail Naganov521fc492023-07-11 17:24:08 -070030#include "core-impl/ModulePrimary.h"
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053031#include "core-impl/ModuleRemoteSubmix.h"
Mikhail Naganov521fc492023-07-11 17:24:08 -070032#include "core-impl/ModuleStub.h"
jiabin253bd322023-01-25 23:57:31 +000033#include "core-impl/ModuleUsb.h"
Vlad Popa943b7e22022-12-08 14:24:12 +010034#include "core-impl/SoundDose.h"
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000035#include "core-impl/utils.h"
36
Mikhail Naganov55045b52023-10-24 17:03:50 -070037using aidl::android::hardware::audio::common::frameCountFromDurationMs;
Mikhail Naganov872d4a62023-03-09 18:19:01 -080038using aidl::android::hardware::audio::common::getFrameSizeInBytes;
39using aidl::android::hardware::audio::common::isBitPositionFlagSet;
40using aidl::android::hardware::audio::common::isValidAudioMode;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000041using aidl::android::hardware::audio::common::SinkMetadata;
42using aidl::android::hardware::audio::common::SourceMetadata;
Vlad Popa2afbd1e2022-12-28 17:04:58 +010043using aidl::android::hardware::audio::core::sounddose::ISoundDose;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000044using aidl::android::media::audio::common::AudioChannelLayout;
Mikhail Naganovef6bc742022-10-06 00:14:19 +000045using aidl::android::media::audio::common::AudioDevice;
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +000046using aidl::android::media::audio::common::AudioDeviceType;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000047using aidl::android::media::audio::common::AudioFormatDescription;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000048using aidl::android::media::audio::common::AudioFormatType;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000049using aidl::android::media::audio::common::AudioInputFlags;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000050using aidl::android::media::audio::common::AudioIoFlags;
jiabin9a8e6862023-01-12 23:06:37 +000051using aidl::android::media::audio::common::AudioMMapPolicy;
52using aidl::android::media::audio::common::AudioMMapPolicyInfo;
53using aidl::android::media::audio::common::AudioMMapPolicyType;
Mikhail Naganov04ae8222023-01-11 15:48:10 -080054using aidl::android::media::audio::common::AudioMode;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000055using aidl::android::media::audio::common::AudioOffloadInfo;
56using aidl::android::media::audio::common::AudioOutputFlags;
57using aidl::android::media::audio::common::AudioPort;
58using aidl::android::media::audio::common::AudioPortConfig;
59using aidl::android::media::audio::common::AudioPortExt;
60using aidl::android::media::audio::common::AudioProfile;
Mikhail Naganov20047bc2023-01-05 20:16:07 +000061using aidl::android::media::audio::common::Boolean;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000062using aidl::android::media::audio::common::Int;
Mikhail Naganov6725ef52023-02-09 17:52:50 -080063using aidl::android::media::audio::common::MicrophoneInfo;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000064using aidl::android::media::audio::common::PcmType;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000065
66namespace aidl::android::hardware::audio::core {
67
68namespace {
69
Mikhail Naganov84bcc042023-10-05 17:36:57 -070070inline bool hasDynamicChannelMasks(const std::vector<AudioChannelLayout>& channelMasks) {
71 return channelMasks.empty() ||
72 std::all_of(channelMasks.begin(), channelMasks.end(),
73 [](const auto& channelMask) { return channelMask == AudioChannelLayout{}; });
74}
75
76inline bool hasDynamicFormat(const AudioFormatDescription& format) {
77 return format == AudioFormatDescription{};
78}
79
80inline bool hasDynamicSampleRates(const std::vector<int32_t>& sampleRates) {
81 return sampleRates.empty() ||
82 std::all_of(sampleRates.begin(), sampleRates.end(),
83 [](const auto& sampleRate) { return sampleRate == 0; });
84}
85
86inline bool isDynamicProfile(const AudioProfile& profile) {
87 return hasDynamicFormat(profile.format) || hasDynamicChannelMasks(profile.channelMasks) ||
88 hasDynamicSampleRates(profile.sampleRates);
89}
90
91bool hasDynamicProfilesOnly(const std::vector<AudioProfile>& profiles) {
92 if (profiles.empty()) return true;
93 return std::all_of(profiles.begin(), profiles.end(), isDynamicProfile);
94}
95
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000096bool findAudioProfile(const AudioPort& port, const AudioFormatDescription& format,
97 AudioProfile* profile) {
98 if (auto profilesIt =
99 find_if(port.profiles.begin(), port.profiles.end(),
100 [&format](const auto& profile) { return profile.format == format; });
101 profilesIt != port.profiles.end()) {
102 *profile = *profilesIt;
103 return true;
104 }
105 return false;
106}
Mikhail Naganov00603d12022-05-02 22:52:13 +0000107
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000108} // namespace
109
jiabin253bd322023-01-25 23:57:31 +0000110// static
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000111std::shared_ptr<Module> Module::createInstance(Type type, std::unique_ptr<Configuration>&& config) {
jiabin253bd322023-01-25 23:57:31 +0000112 switch (type) {
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530113 case Type::DEFAULT:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000114 return ndk::SharedRefBase::make<ModulePrimary>(std::move(config));
Mikhail Naganov521fc492023-07-11 17:24:08 -0700115 case Type::R_SUBMIX:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000116 return ndk::SharedRefBase::make<ModuleRemoteSubmix>(std::move(config));
Mikhail Naganov521fc492023-07-11 17:24:08 -0700117 case Type::STUB:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000118 return ndk::SharedRefBase::make<ModuleStub>(std::move(config));
Mikhail Naganov521fc492023-07-11 17:24:08 -0700119 case Type::USB:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000120 return ndk::SharedRefBase::make<ModuleUsb>(std::move(config));
Mikhail Naganovb03b5c42023-07-26 13:13:35 -0700121 case Type::BLUETOOTH:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000122 return ndk::SharedRefBase::make<ModuleBluetooth>(std::move(config));
jiabin253bd322023-01-25 23:57:31 +0000123 }
124}
125
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000126// static
127std::optional<Module::Type> Module::typeFromString(const std::string& type) {
128 if (type == "default")
129 return Module::Type::DEFAULT;
130 else if (type == "r_submix")
131 return Module::Type::R_SUBMIX;
132 else if (type == "stub")
133 return Module::Type::STUB;
134 else if (type == "usb")
135 return Module::Type::USB;
136 else if (type == "bluetooth")
137 return Module::Type::BLUETOOTH;
138 return {};
139}
140
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700141std::ostream& operator<<(std::ostream& os, Module::Type t) {
142 switch (t) {
143 case Module::Type::DEFAULT:
144 os << "default";
145 break;
146 case Module::Type::R_SUBMIX:
147 os << "r_submix";
148 break;
Mikhail Naganov521fc492023-07-11 17:24:08 -0700149 case Module::Type::STUB:
150 os << "stub";
151 break;
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700152 case Module::Type::USB:
153 os << "usb";
154 break;
Mikhail Naganovb03b5c42023-07-26 13:13:35 -0700155 case Module::Type::BLUETOOTH:
156 os << "bluetooth";
157 break;
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700158 }
159 return os;
160}
161
Lorena Torres-Huertaf7492512023-01-14 02:49:41 +0000162Module::Module(Type type, std::unique_ptr<Configuration>&& config)
163 : mType(type), mConfig(std::move(config)) {
164 populateConnectedProfiles();
165}
166
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000167void Module::cleanUpPatch(int32_t patchId) {
168 erase_all_values(mPatches, std::set<int32_t>{patchId});
169}
170
Mikhail Naganov8651b362023-01-06 23:15:27 +0000171ndk::ScopedAStatus Module::createStreamContext(
172 int32_t in_portConfigId, int64_t in_bufferSizeFrames,
173 std::shared_ptr<IStreamCallback> asyncCallback,
174 std::shared_ptr<IStreamOutEventCallback> outEventCallback, StreamContext* out_context) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000175 if (in_bufferSizeFrames <= 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530176 LOG(ERROR) << __func__ << ": " << mType << ": non-positive buffer size "
177 << in_bufferSizeFrames;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000178 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
179 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000180 auto& configs = getConfig().portConfigs;
181 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
Mikhail Naganova92039a2023-12-20 14:27:22 -0800182 const int32_t nominalLatencyMs = getNominalLatencyMs(*portConfigIt);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000183 // Since this is a private method, it is assumed that
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000184 // validity of the portConfigId has already been checked.
Mikhail Naganova92039a2023-12-20 14:27:22 -0800185 const int32_t minimumStreamBufferSizeFrames =
186 calculateBufferSizeFrames(nominalLatencyMs, portConfigIt->sampleRate.value().value);
Mikhail Naganov13501872023-10-18 16:15:46 -0700187 if (in_bufferSizeFrames < minimumStreamBufferSizeFrames) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530188 LOG(ERROR) << __func__ << ": " << mType << ": insufficient buffer size "
189 << in_bufferSizeFrames << ", must be at least " << minimumStreamBufferSizeFrames;
Mikhail Naganov13501872023-10-18 16:15:46 -0700190 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
191 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000192 const size_t frameSize =
193 getFrameSizeInBytes(portConfigIt->format.value(), portConfigIt->channelMask.value());
194 if (frameSize == 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530195 LOG(ERROR) << __func__ << ": " << mType
196 << ": could not calculate frame size for port config "
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000197 << portConfigIt->toString();
198 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
199 }
Jaideep Sharma559a4912024-03-07 10:05:51 +0530200 LOG(DEBUG) << __func__ << ": " << mType << ": frame size " << frameSize << " bytes";
Mikhail Naganovb511b8a2023-05-15 14:35:24 -0700201 if (frameSize > static_cast<size_t>(kMaximumStreamBufferSizeBytes / in_bufferSizeFrames)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530202 LOG(ERROR) << __func__ << ": " << mType << ": buffer size " << in_bufferSizeFrames
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000203 << " frames is too large, maximum size is "
204 << kMaximumStreamBufferSizeBytes / frameSize;
205 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
206 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000207 const auto& flags = portConfigIt->flags.value();
208 if ((flags.getTag() == AudioIoFlags::Tag::input &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000209 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::input>(),
210 AudioInputFlags::MMAP_NOIRQ)) ||
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000211 (flags.getTag() == AudioIoFlags::Tag::output &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000212 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::output>(),
213 AudioOutputFlags::MMAP_NOIRQ))) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000214 StreamContext::DebugParameters params{mDebug.streamTransientStateDelayMs,
Mikhail Naganov194daaa2023-01-05 22:34:20 +0000215 mVendorDebug.forceTransientBurst,
216 mVendorDebug.forceSynchronousDrain};
Vlad Popace338642023-09-21 18:54:03 -0700217 std::shared_ptr<ISoundDose> soundDose;
218 if (!getSoundDose(&soundDose).isOk()) {
219 LOG(ERROR) << __func__ << ": could not create sound dose instance";
220 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
221 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000222 StreamContext temp(
223 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
224 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
Mikhail Naganov13501872023-10-18 16:15:46 -0700225 portConfigIt->format.value(), portConfigIt->channelMask.value(),
Mikhail Naganova92039a2023-12-20 14:27:22 -0800226 portConfigIt->sampleRate.value().value, flags, nominalLatencyMs,
Mikhail Naganovb42a69e2023-06-16 12:38:25 -0700227 portConfigIt->ext.get<AudioPortExt::mix>().handle,
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000228 std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames),
Vlad Popace338642023-09-21 18:54:03 -0700229 asyncCallback, outEventCallback, mSoundDose.getInstance(), params);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000230 if (temp.isValid()) {
231 *out_context = std::move(temp);
232 } else {
233 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
234 }
235 } else {
236 // TODO: Implement simulation of MMAP buffer allocation
237 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000238 return ndk::ScopedAStatus::ok();
239}
240
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000241std::vector<AudioDevice> Module::findConnectedDevices(int32_t portConfigId) {
242 std::vector<AudioDevice> result;
243 auto& ports = getConfig().ports;
244 auto portIds = portIdsFromPortConfigIds(findConnectedPortConfigIds(portConfigId));
245 for (auto it = portIds.begin(); it != portIds.end(); ++it) {
246 auto portIt = findById<AudioPort>(ports, *it);
247 if (portIt != ports.end() && portIt->ext.getTag() == AudioPortExt::Tag::device) {
248 result.push_back(portIt->ext.template get<AudioPortExt::Tag::device>().device);
249 }
250 }
251 return result;
252}
253
254std::set<int32_t> Module::findConnectedPortConfigIds(int32_t portConfigId) {
255 std::set<int32_t> result;
256 auto patchIdsRange = mPatches.equal_range(portConfigId);
257 auto& patches = getConfig().patches;
258 for (auto it = patchIdsRange.first; it != patchIdsRange.second; ++it) {
259 auto patchIt = findById<AudioPatch>(patches, it->second);
260 if (patchIt == patches.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530261 LOG(FATAL) << __func__ << ": " << mType << ": patch with id " << it->second
262 << " taken from mPatches "
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000263 << "not found in the configuration";
264 }
265 if (std::find(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end(),
266 portConfigId) != patchIt->sourcePortConfigIds.end()) {
267 result.insert(patchIt->sinkPortConfigIds.begin(), patchIt->sinkPortConfigIds.end());
268 } else {
269 result.insert(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end());
270 }
271 }
272 return result;
273}
274
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000275ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) {
276 auto& configs = getConfig().portConfigs;
277 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
278 if (portConfigIt == configs.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530279 LOG(ERROR) << __func__ << ": " << mType << ": existing port config id " << in_portConfigId
280 << " not found";
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000281 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
282 }
283 const int32_t portId = portConfigIt->portId;
284 // In our implementation, configs of mix ports always have unique IDs.
285 CHECK(portId != in_portConfigId);
286 auto& ports = getConfig().ports;
287 auto portIt = findById<AudioPort>(ports, portId);
288 if (portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530289 LOG(ERROR) << __func__ << ": " << mType << ": port id " << portId
290 << " used by port config id " << in_portConfigId << " not found";
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000291 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
292 }
293 if (mStreams.count(in_portConfigId) != 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530294 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000295 << " already has a stream opened on it";
296 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
297 }
298 if (portIt->ext.getTag() != AudioPortExt::Tag::mix) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530299 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000300 << " does not correspond to a mix port";
301 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
302 }
Mikhail Naganovb511b8a2023-05-15 14:35:24 -0700303 const size_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000304 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530305 LOG(ERROR) << __func__ << ": " << mType << ": port id " << portId
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000306 << " has already reached maximum allowed opened stream count: "
307 << maxOpenStreamCount;
308 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
309 }
310 *port = &(*portIt);
311 return ndk::ScopedAStatus::ok();
312}
313
Mikhail Naganova92039a2023-12-20 14:27:22 -0800314bool Module::generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) {
315 const bool allowDynamicConfig = port.ext.getTag() == AudioPortExt::device;
316 for (const auto& profile : port.profiles) {
317 if (isDynamicProfile(profile)) continue;
318 config->format = profile.format;
319 config->channelMask = *profile.channelMasks.begin();
320 config->sampleRate = Int{.value = *profile.sampleRates.begin()};
321 config->flags = port.flags;
322 config->ext = port.ext;
323 return true;
324 }
325 if (allowDynamicConfig) {
326 config->format = AudioFormatDescription{};
327 config->channelMask = AudioChannelLayout{};
328 config->sampleRate = Int{.value = 0};
329 config->flags = port.flags;
330 config->ext = port.ext;
331 return true;
332 }
Jaideep Sharma559a4912024-03-07 10:05:51 +0530333 LOG(ERROR) << __func__ << ": " << mType << ": port " << port.id << " only has dynamic profiles";
Mikhail Naganova92039a2023-12-20 14:27:22 -0800334 return false;
335}
336
Lorena Torres-Huertaf7492512023-01-14 02:49:41 +0000337void Module::populateConnectedProfiles() {
338 Configuration& config = getConfig();
339 for (const AudioPort& port : config.ports) {
340 if (port.ext.getTag() == AudioPortExt::device) {
341 if (auto devicePort = port.ext.get<AudioPortExt::device>();
342 !devicePort.device.type.connection.empty() && port.profiles.empty()) {
343 if (auto connIt = config.connectedProfiles.find(port.id);
344 connIt == config.connectedProfiles.end()) {
345 config.connectedProfiles.emplace(
346 port.id, internal::getStandard16And24BitPcmAudioProfiles());
347 }
348 }
349 }
350 }
351}
352
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000353template <typename C>
354std::set<int32_t> Module::portIdsFromPortConfigIds(C portConfigIds) {
355 std::set<int32_t> result;
356 auto& portConfigs = getConfig().portConfigs;
357 for (auto it = portConfigIds.begin(); it != portConfigIds.end(); ++it) {
358 auto portConfigIt = findById<AudioPortConfig>(portConfigs, *it);
359 if (portConfigIt != portConfigs.end()) {
360 result.insert(portConfigIt->portId);
361 }
362 }
363 return result;
364}
365
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000366std::unique_ptr<Module::Configuration> Module::initializeConfig() {
367 return internal::getConfiguration(getType());
Peter Yoon918a6a52023-07-13 17:04:37 +0900368}
369
Mikhail Naganov13501872023-10-18 16:15:46 -0700370int32_t Module::getNominalLatencyMs(const AudioPortConfig&) {
371 // Arbitrary value. Implementations must override this method to provide their actual latency.
372 static constexpr int32_t kLatencyMs = 5;
373 return kLatencyMs;
374}
375
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700376std::vector<AudioRoute*> Module::getAudioRoutesForAudioPortImpl(int32_t portId) {
377 std::vector<AudioRoute*> result;
378 auto& routes = getConfig().routes;
379 for (auto& r : routes) {
380 const auto& srcs = r.sourcePortIds;
381 if (r.sinkPortId == portId || std::find(srcs.begin(), srcs.end(), portId) != srcs.end()) {
382 result.push_back(&r);
383 }
384 }
385 return result;
386}
387
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000388Module::Configuration& Module::getConfig() {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000389 if (!mConfig) {
Peter Yoon918a6a52023-07-13 17:04:37 +0900390 mConfig = std::move(initializeConfig());
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000391 }
392 return *mConfig;
393}
394
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700395std::set<int32_t> Module::getRoutableAudioPortIds(int32_t portId,
396 std::vector<AudioRoute*>* routes) {
397 std::vector<AudioRoute*> routesStorage;
398 if (routes == nullptr) {
399 routesStorage = getAudioRoutesForAudioPortImpl(portId);
400 routes = &routesStorage;
401 }
402 std::set<int32_t> result;
403 for (AudioRoute* r : *routes) {
404 if (r->sinkPortId == portId) {
405 result.insert(r->sourcePortIds.begin(), r->sourcePortIds.end());
406 } else {
407 result.insert(r->sinkPortId);
408 }
409 }
410 return result;
411}
412
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000413void Module::registerPatch(const AudioPatch& patch) {
414 auto& configs = getConfig().portConfigs;
415 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
416 for (auto portConfigId : portConfigIds) {
417 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
418 if (configIt != configs.end()) {
419 mPatches.insert(std::pair{portConfigId, patch.id});
420 if (configIt->portId != portConfigId) {
421 mPatches.insert(std::pair{configIt->portId, patch.id});
422 }
423 }
424 };
425 };
426 do_insert(patch.sourcePortConfigIds);
427 do_insert(patch.sinkPortConfigIds);
428}
429
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700430ndk::ScopedAStatus Module::updateStreamsConnectedState(const AudioPatch& oldPatch,
431 const AudioPatch& newPatch) {
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700432 // Notify streams about the new set of devices they are connected to.
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700433 auto maybeFailure = ndk::ScopedAStatus::ok();
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700434 using Connections =
435 std::map<int32_t /*mixPortConfigId*/, std::set<int32_t /*devicePortConfigId*/>>;
436 Connections oldConnections, newConnections;
437 auto fillConnectionsHelper = [&](Connections& connections,
438 const std::vector<int32_t>& mixPortCfgIds,
439 const std::vector<int32_t>& devicePortCfgIds) {
440 for (int32_t mixPortCfgId : mixPortCfgIds) {
441 connections[mixPortCfgId].insert(devicePortCfgIds.begin(), devicePortCfgIds.end());
442 }
443 };
444 auto fillConnections = [&](Connections& connections, const AudioPatch& patch) {
445 if (std::find_if(patch.sourcePortConfigIds.begin(), patch.sourcePortConfigIds.end(),
446 [&](int32_t portConfigId) { return mStreams.count(portConfigId) > 0; }) !=
447 patch.sourcePortConfigIds.end()) {
448 // Sources are mix ports.
449 fillConnectionsHelper(connections, patch.sourcePortConfigIds, patch.sinkPortConfigIds);
450 } else if (std::find_if(patch.sinkPortConfigIds.begin(), patch.sinkPortConfigIds.end(),
451 [&](int32_t portConfigId) {
452 return mStreams.count(portConfigId) > 0;
453 }) != patch.sinkPortConfigIds.end()) {
454 // Sources are device ports.
455 fillConnectionsHelper(connections, patch.sinkPortConfigIds, patch.sourcePortConfigIds);
456 } // Otherwise, there are no streams to notify.
457 };
458 fillConnections(oldConnections, oldPatch);
459 fillConnections(newConnections, newPatch);
460
461 std::for_each(oldConnections.begin(), oldConnections.end(), [&](const auto& connectionPair) {
462 const int32_t mixPortConfigId = connectionPair.first;
463 if (auto it = newConnections.find(mixPortConfigId);
464 it == newConnections.end() || it->second != connectionPair.second) {
465 if (auto status = mStreams.setStreamConnectedDevices(mixPortConfigId, {});
466 status.isOk()) {
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700467 LOG(DEBUG) << "updateStreamsConnectedState: The stream on port config id "
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700468 << mixPortConfigId << " has been disconnected";
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700469 } else {
470 // Disconnection is tricky to roll back, just register a failure.
471 maybeFailure = std::move(status);
472 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000473 }
474 });
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700475 if (!maybeFailure.isOk()) return maybeFailure;
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700476 std::set<int32_t> idsToDisconnectOnFailure;
477 std::for_each(newConnections.begin(), newConnections.end(), [&](const auto& connectionPair) {
478 const int32_t mixPortConfigId = connectionPair.first;
479 if (auto it = oldConnections.find(mixPortConfigId);
480 it == oldConnections.end() || it->second != connectionPair.second) {
481 const auto connectedDevices = findConnectedDevices(mixPortConfigId);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700482 if (connectedDevices.empty()) {
483 // This is important as workers use the vector size to derive the connection status.
484 LOG(FATAL) << "updateStreamsConnectedState: No connected devices found for port "
485 "config id "
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700486 << mixPortConfigId;
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700487 }
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700488 if (auto status = mStreams.setStreamConnectedDevices(mixPortConfigId, connectedDevices);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700489 status.isOk()) {
490 LOG(DEBUG) << "updateStreamsConnectedState: The stream on port config id "
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700491 << mixPortConfigId << " has been connected to: "
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700492 << ::android::internal::ToString(connectedDevices);
493 } else {
494 maybeFailure = std::move(status);
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700495 idsToDisconnectOnFailure.insert(mixPortConfigId);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700496 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000497 }
498 });
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700499 if (!maybeFailure.isOk()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530500 LOG(WARNING) << __func__ << ": " << mType
501 << ": Due to a failure, disconnecting streams on port config ids "
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700502 << ::android::internal::ToString(idsToDisconnectOnFailure);
503 std::for_each(idsToDisconnectOnFailure.begin(), idsToDisconnectOnFailure.end(),
504 [&](const auto& portConfigId) {
505 auto status = mStreams.setStreamConnectedDevices(portConfigId, {});
506 (void)status.isOk(); // Can't do much about a failure here.
507 });
508 return maybeFailure;
509 }
510 return ndk::ScopedAStatus::ok();
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000511}
512
Mikhail Naganov00603d12022-05-02 22:52:13 +0000513ndk::ScopedAStatus Module::setModuleDebug(
514 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700515 LOG(DEBUG) << __func__ << ": " << mType << ": old flags:" << mDebug.toString()
Mikhail Naganov00603d12022-05-02 22:52:13 +0000516 << ", new flags: " << in_debug.toString();
517 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
518 !mConnectedDevicePorts.empty()) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700519 LOG(ERROR) << __func__ << ": " << mType
Jaideep Sharma559a4912024-03-07 10:05:51 +0530520 << ": attempting to change device connections simulation while "
521 "having external "
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700522 << "devices connected";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000523 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
524 }
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000525 if (in_debug.streamTransientStateDelayMs < 0) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700526 LOG(ERROR) << __func__ << ": " << mType << ": streamTransientStateDelayMs is negative: "
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000527 << in_debug.streamTransientStateDelayMs;
528 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
529 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000530 mDebug = in_debug;
531 return ndk::ScopedAStatus::ok();
532}
533
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000534ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700535 *_aidl_return = nullptr;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530536 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000537 return ndk::ScopedAStatus::ok();
538}
539
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000540ndk::ScopedAStatus Module::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700541 *_aidl_return = nullptr;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530542 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000543 return ndk::ScopedAStatus::ok();
544}
545
Mikhail Naganov7499a002023-02-27 18:51:44 -0800546ndk::ScopedAStatus Module::getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700547 *_aidl_return = nullptr;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530548 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
Mikhail Naganov7499a002023-02-27 18:51:44 -0800549 return ndk::ScopedAStatus::ok();
550}
551
Mikhail Naganovb5647da2023-03-06 14:37:38 -0800552ndk::ScopedAStatus Module::getBluetoothLe(std::shared_ptr<IBluetoothLe>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700553 *_aidl_return = nullptr;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530554 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
Mikhail Naganovb5647da2023-03-06 14:37:38 -0800555 return ndk::ScopedAStatus::ok();
556}
557
Mikhail Naganov00603d12022-05-02 22:52:13 +0000558ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
559 AudioPort* _aidl_return) {
560 const int32_t templateId = in_templateIdAndAdditionalData.id;
561 auto& ports = getConfig().ports;
562 AudioPort connectedPort;
563 { // Scope the template port so that we don't accidentally modify it.
564 auto templateIt = findById<AudioPort>(ports, templateId);
565 if (templateIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530566 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId << " not found";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000567 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
568 }
569 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530570 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
571 << " is not a device port";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000572 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
573 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000574 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
575 if (templateDevicePort.device.type.connection.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530576 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
577 << " is permanently attached";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000578 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
579 }
Mikhail Naganovfcf980e2023-09-07 16:30:11 -0700580 if (mConnectedDevicePorts.find(templateId) != mConnectedDevicePorts.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530581 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
582 << " is a connected device port";
Mikhail Naganovfcf980e2023-09-07 16:30:11 -0700583 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
584 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000585 // Postpone id allocation until we ensure that there are no client errors.
586 connectedPort = *templateIt;
587 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
588 const auto& inputDevicePort =
589 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
590 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
591 connectedDevicePort.device.address = inputDevicePort.device.address;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530592 LOG(DEBUG) << __func__ << ": " << mType << ": device port " << connectedPort.id
593 << " device set to " << connectedDevicePort.device.toString();
Mikhail Naganov00603d12022-05-02 22:52:13 +0000594 // Check if there is already a connected port with for the same external device.
Jaideep Sharma559a4912024-03-07 10:05:51 +0530595
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700596 for (auto connectedPortPair : mConnectedDevicePorts) {
597 auto connectedPortIt = findById<AudioPort>(ports, connectedPortPair.first);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000598 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
599 connectedDevicePort.device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530600 LOG(ERROR) << __func__ << ": " << mType << ": device "
601 << connectedDevicePort.device.toString()
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700602 << " is already connected at the device port id "
603 << connectedPortPair.first;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000604 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
605 }
606 }
607 }
608
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700609 // Two main cases are considered with regard to the profiles of the connected device port:
610 //
611 // 1. If the template device port has dynamic profiles, and at least one routable mix
612 // port also has dynamic profiles, it means that after connecting the device, the
613 // connected device port must have profiles populated with actual capabilities of
614 // the connected device, and dynamic of routable mix ports will be filled
615 // according to these capabilities. An example of this case is connection of an
616 // HDMI or USB device. For USB handled by ADSP, there can be mix ports with static
617 // profiles, and one dedicated mix port for "hi-fi" playback. The latter is left with
618 // dynamic profiles so that they can be populated with actual capabilities of
619 // the connected device.
620 //
621 // 2. If the template device port has dynamic profiles, while all routable mix ports
622 // have static profiles, it means that after connecting the device, the connected
623 // device port can be left with dynamic profiles, and profiles of mix ports are
624 // left untouched. An example of this case is connection of an analog wired
625 // headset, it should be treated in the same way as a speaker.
626 //
627 // Yet another possible case is when both the template device port and all routable
628 // mix ports have static profiles. This is allowed and handled correctly, however, it
629 // is not very practical, since these profiles are likely duplicates of each other.
630
631 std::vector<AudioRoute*> routesToMixPorts = getAudioRoutesForAudioPortImpl(templateId);
632 std::set<int32_t> routableMixPortIds = getRoutableAudioPortIds(templateId, &routesToMixPorts);
Mikhail Naganova92039a2023-12-20 14:27:22 -0800633 const int32_t nextPortId = getConfig().nextPortId++;
Mikhail Naganov55045b52023-10-24 17:03:50 -0700634 if (!mDebug.simulateDeviceConnections) {
635 // Even if the device port has static profiles, the HAL module might need to update
636 // them, or abort the connection process.
Mikhail Naganova92039a2023-12-20 14:27:22 -0800637 RETURN_STATUS_IF_ERROR(populateConnectedDevicePort(&connectedPort, nextPortId));
Mikhail Naganov55045b52023-10-24 17:03:50 -0700638 } else if (hasDynamicProfilesOnly(connectedPort.profiles)) {
639 auto& connectedProfiles = getConfig().connectedProfiles;
640 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
641 connectedProfilesIt != connectedProfiles.end()) {
642 connectedPort.profiles = connectedProfilesIt->second;
Mikhail Naganovfcf980e2023-09-07 16:30:11 -0700643 }
Mikhail Naganov55045b52023-10-24 17:03:50 -0700644 }
645 if (hasDynamicProfilesOnly(connectedPort.profiles)) {
646 // Possible case 2. Check if all routable mix ports have static profiles.
647 if (auto dynamicMixPortIt = std::find_if(ports.begin(), ports.end(),
648 [&routableMixPortIds](const auto& p) {
649 return routableMixPortIds.count(p.id) > 0 &&
650 hasDynamicProfilesOnly(p.profiles);
651 });
652 dynamicMixPortIt != ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530653 LOG(ERROR) << __func__ << ": " << mType
654 << ": connected port only has dynamic profiles after connecting "
Mikhail Naganov55045b52023-10-24 17:03:50 -0700655 << "external device " << connectedPort.toString() << ", and there exist "
656 << "a routable mix port with dynamic profiles: "
657 << dynamicMixPortIt->toString();
658 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530659 }
660 }
661
Mikhail Naganova92039a2023-12-20 14:27:22 -0800662 connectedPort.id = nextPortId;
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700663 auto [connectedPortsIt, _] =
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700664 mConnectedDevicePorts.insert(std::pair(connectedPort.id, std::set<int32_t>()));
Jaideep Sharma559a4912024-03-07 10:05:51 +0530665 LOG(DEBUG) << __func__ << ": " << mType << ": template port " << templateId
666 << " external device connected, "
Mikhail Naganov00603d12022-05-02 22:52:13 +0000667 << "connected port ID " << connectedPort.id;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000668 ports.push_back(connectedPort);
jiabin783c48b2023-02-28 18:28:06 +0000669 onExternalDeviceConnectionChanged(connectedPort, true /*connected*/);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000670
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700671 // For routes where the template port is a source, add the connected port to sources,
672 // otherwise, create a new route by copying from the route for the template port.
Mikhail Naganov00603d12022-05-02 22:52:13 +0000673 std::vector<AudioRoute> newRoutes;
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700674 for (AudioRoute* r : routesToMixPorts) {
675 if (r->sinkPortId == templateId) {
676 newRoutes.push_back(AudioRoute{.sourcePortIds = r->sourcePortIds,
677 .sinkPortId = connectedPort.id,
678 .isExclusive = r->isExclusive});
Mikhail Naganov00603d12022-05-02 22:52:13 +0000679 } else {
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700680 r->sourcePortIds.push_back(connectedPort.id);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000681 }
682 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700683 auto& routes = getConfig().routes;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000684 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
685
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700686 if (!hasDynamicProfilesOnly(connectedPort.profiles) && !routableMixPortIds.empty()) {
687 // Note: this is a simplistic approach assuming that a mix port can only be populated
688 // from a single device port. Implementing support for stuffing dynamic profiles with
689 // a superset of all profiles from all routable dynamic device ports would be more involved.
690 for (auto& port : ports) {
691 if (routableMixPortIds.count(port.id) == 0) continue;
692 if (hasDynamicProfilesOnly(port.profiles)) {
693 port.profiles = connectedPort.profiles;
694 connectedPortsIt->second.insert(port.id);
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700695 } else {
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700696 // Check if profiles are not all dynamic because they were populated by
697 // a previous connection. Otherwise, it means that they are actually static.
698 for (const auto& cp : mConnectedDevicePorts) {
699 if (cp.second.count(port.id) > 0) {
700 connectedPortsIt->second.insert(port.id);
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700701 break;
702 }
703 }
704 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700705 }
706 }
707 *_aidl_return = std::move(connectedPort);
708
Mikhail Naganov00603d12022-05-02 22:52:13 +0000709 return ndk::ScopedAStatus::ok();
710}
711
712ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
713 auto& ports = getConfig().ports;
714 auto portIt = findById<AudioPort>(ports, in_portId);
715 if (portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530716 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000717 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
718 }
719 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530720 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
721 << " is not a device port";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000722 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
723 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700724 auto connectedPortsIt = mConnectedDevicePorts.find(in_portId);
725 if (connectedPortsIt == mConnectedDevicePorts.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530726 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
727 << " is not a connected device port";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000728 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
729 }
730 auto& configs = getConfig().portConfigs;
731 auto& initials = getConfig().initialConfigs;
732 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
733 if (config.portId == in_portId) {
734 // Check if the configuration was provided by the client.
735 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
736 return initialIt == initials.end() || config != *initialIt;
737 }
738 return false;
739 });
740 if (configIt != configs.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530741 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
742 << " has a non-default config with id " << configIt->id;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000743 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
744 }
jiabin783c48b2023-02-28 18:28:06 +0000745 onExternalDeviceConnectionChanged(*portIt, false /*connected*/);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000746 ports.erase(portIt);
Jaideep Sharma559a4912024-03-07 10:05:51 +0530747 LOG(DEBUG) << __func__ << ": " << mType << ": connected device port " << in_portId
748 << " released";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000749
750 auto& routes = getConfig().routes;
751 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
752 if (routesIt->sinkPortId == in_portId) {
753 routesIt = routes.erase(routesIt);
754 } else {
755 // Note: the list of sourcePortIds can't become empty because there must
756 // be the id of the template port in the route.
757 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
758 ++routesIt;
759 }
760 }
761
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700762 // Clear profiles for mix ports that are not connected to any other ports.
763 std::set<int32_t> mixPortsToClear = std::move(connectedPortsIt->second);
764 mConnectedDevicePorts.erase(connectedPortsIt);
765 for (const auto& connectedPort : mConnectedDevicePorts) {
766 for (int32_t mixPortId : connectedPort.second) {
767 mixPortsToClear.erase(mixPortId);
768 }
769 }
770 for (int32_t mixPortId : mixPortsToClear) {
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700771 auto mixPortIt = findById<AudioPort>(ports, mixPortId);
772 if (mixPortIt != ports.end()) {
773 mixPortIt->profiles = {};
774 }
775 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700776
Mikhail Naganov00603d12022-05-02 22:52:13 +0000777 return ndk::ScopedAStatus::ok();
778}
779
jiabindd23b0e2023-12-11 19:10:05 +0000780ndk::ScopedAStatus Module::prepareToDisconnectExternalDevice(int32_t in_portId) {
781 auto& ports = getConfig().ports;
782 auto portIt = findById<AudioPort>(ports, in_portId);
783 if (portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530784 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
jiabindd23b0e2023-12-11 19:10:05 +0000785 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
786 }
787 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530788 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
789 << " is not a device port";
jiabindd23b0e2023-12-11 19:10:05 +0000790 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
791 }
792 auto connectedPortsIt = mConnectedDevicePorts.find(in_portId);
793 if (connectedPortsIt == mConnectedDevicePorts.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530794 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
795 << " is not a connected device port";
jiabindd23b0e2023-12-11 19:10:05 +0000796 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
797 }
798
799 onPrepareToDisconnectExternalDevice(*portIt);
800
801 return ndk::ScopedAStatus::ok();
802}
803
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000804ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
805 *_aidl_return = getConfig().patches;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530806 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " patches";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000807 return ndk::ScopedAStatus::ok();
808}
809
810ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
811 auto& ports = getConfig().ports;
812 auto portIt = findById<AudioPort>(ports, in_portId);
813 if (portIt != ports.end()) {
814 *_aidl_return = *portIt;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530815 LOG(DEBUG) << __func__ << ": " << mType << ": returning port by id " << in_portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000816 return ndk::ScopedAStatus::ok();
817 }
Jaideep Sharma559a4912024-03-07 10:05:51 +0530818 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000819 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
820}
821
822ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
823 *_aidl_return = getConfig().portConfigs;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530824 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size()
825 << " port configs";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000826 return ndk::ScopedAStatus::ok();
827}
828
829ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
830 *_aidl_return = getConfig().ports;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530831 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " ports";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000832 return ndk::ScopedAStatus::ok();
833}
834
835ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
836 *_aidl_return = getConfig().routes;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530837 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " routes";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000838 return ndk::ScopedAStatus::ok();
839}
840
Mikhail Naganov00603d12022-05-02 22:52:13 +0000841ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
842 std::vector<AudioRoute>* _aidl_return) {
843 auto& ports = getConfig().ports;
844 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530845 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000846 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
847 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700848 std::vector<AudioRoute*> routes = getAudioRoutesForAudioPortImpl(in_portId);
849 std::transform(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
850 [](auto rptr) { return *rptr; });
Mikhail Naganov00603d12022-05-02 22:52:13 +0000851 return ndk::ScopedAStatus::ok();
852}
853
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000854ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
855 OpenInputStreamReturn* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530856 LOG(DEBUG) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
857 << ", buffer size " << in_args.bufferSizeFrames << " frames";
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000858 AudioPort* port = nullptr;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700859 RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000860 if (port->flags.getTag() != AudioIoFlags::Tag::input) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530861 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000862 << " does not correspond to an input mix port";
863 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
864 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000865 StreamContext context;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700866 RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
867 nullptr, nullptr, &context));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000868 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000869 std::shared_ptr<StreamIn> stream;
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700870 RETURN_STATUS_IF_ERROR(createInputStream(std::move(context), in_args.sinkMetadata,
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +0000871 getMicrophoneInfos(), &stream));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000872 StreamWrapper streamWrapper(stream);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700873 if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
874 RETURN_STATUS_IF_ERROR(
875 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
876 }
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000877 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
878 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000879 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000880 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000881 return ndk::ScopedAStatus::ok();
882}
883
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000884ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
885 OpenOutputStreamReturn* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530886 LOG(DEBUG) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
887 << ", has offload info? " << (in_args.offloadInfo.has_value()) << ", buffer size "
888 << in_args.bufferSizeFrames << " frames";
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000889 AudioPort* port = nullptr;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700890 RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000891 if (port->flags.getTag() != AudioIoFlags::Tag::output) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530892 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000893 << " does not correspond to an output mix port";
894 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
895 }
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000896 const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
897 AudioOutputFlags::COMPRESS_OFFLOAD);
898 if (isOffload && !in_args.offloadInfo.has_value()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530899 LOG(ERROR) << __func__ << ": " << mType << ": port id " << port->id
Mikhail Naganov111e0ce2022-06-17 21:41:19 +0000900 << " has COMPRESS_OFFLOAD flag set, requires offload info";
901 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
902 }
Mikhail Naganov30301a42022-09-13 01:20:45 +0000903 const bool isNonBlocking = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
904 AudioOutputFlags::NON_BLOCKING);
905 if (isNonBlocking && in_args.callback == nullptr) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530906 LOG(ERROR) << __func__ << ": " << mType << ": port id " << port->id
Mikhail Naganov30301a42022-09-13 01:20:45 +0000907 << " has NON_BLOCKING flag set, requires async callback";
908 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
909 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000910 StreamContext context;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700911 RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
912 isNonBlocking ? in_args.callback : nullptr,
913 in_args.eventCallback, &context));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000914 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000915 std::shared_ptr<StreamOut> stream;
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700916 RETURN_STATUS_IF_ERROR(createOutputStream(std::move(context), in_args.sourceMetadata,
Mikhail Naganov9d16a6a2023-06-26 17:21:04 -0700917 in_args.offloadInfo, &stream));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000918 StreamWrapper streamWrapper(stream);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700919 if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
920 RETURN_STATUS_IF_ERROR(
921 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
922 }
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000923 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
924 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000925 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000926 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000927 return ndk::ScopedAStatus::ok();
928}
929
Mikhail Naganov74927202022-12-19 16:37:14 +0000930ndk::ScopedAStatus Module::getSupportedPlaybackRateFactors(
931 SupportedPlaybackRateFactors* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530932 LOG(DEBUG) << __func__ << ": " << mType;
Mikhail Naganov74927202022-12-19 16:37:14 +0000933 (void)_aidl_return;
934 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
935}
936
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000937ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530938 LOG(DEBUG) << __func__ << ": " << mType << ": requested patch " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000939 if (in_requested.sourcePortConfigIds.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530940 LOG(ERROR) << __func__ << ": " << mType << ": requested patch has empty sources list";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000941 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
942 }
943 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530944 LOG(ERROR) << __func__ << ": " << mType
945 << ": requested patch has duplicate ids in the sources list";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000946 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
947 }
948 if (in_requested.sinkPortConfigIds.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530949 LOG(ERROR) << __func__ << ": " << mType << ": requested patch has empty sinks list";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000950 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
951 }
952 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530953 LOG(ERROR) << __func__ << ": " << mType
954 << ": requested patch has duplicate ids in the sinks list";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000955 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
956 }
957
958 auto& configs = getConfig().portConfigs;
959 std::vector<int32_t> missingIds;
960 auto sources =
961 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
962 if (!missingIds.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530963 LOG(ERROR) << __func__ << ": " << mType << ": following source port config ids not found: "
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000964 << ::android::internal::ToString(missingIds);
965 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
966 }
967 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
968 if (!missingIds.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530969 LOG(ERROR) << __func__ << ": " << mType << ": following sink port config ids not found: "
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000970 << ::android::internal::ToString(missingIds);
971 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
972 }
973 // bool indicates whether a non-exclusive route is available.
974 // If only an exclusive route is available, that means the patch can not be
975 // established if there is any other patch which currently uses the sink port.
976 std::map<int32_t, bool> allowedSinkPorts;
977 auto& routes = getConfig().routes;
978 for (auto src : sources) {
979 for (const auto& r : routes) {
980 const auto& srcs = r.sourcePortIds;
981 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
982 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
983 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
984 }
985 }
986 }
987 }
988 for (auto sink : sinks) {
989 if (allowedSinkPorts.count(sink->portId) == 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530990 LOG(ERROR) << __func__ << ": " << mType << ": there is no route to the sink port id "
991 << sink->portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000992 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
993 }
994 }
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700995 RETURN_STATUS_IF_ERROR(checkAudioPatchEndpointsMatch(sources, sinks));
jiabin253bd322023-01-25 23:57:31 +0000996
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000997 auto& patches = getConfig().patches;
998 auto existing = patches.end();
999 std::optional<decltype(mPatches)> patchesBackup;
1000 if (in_requested.id != 0) {
1001 existing = findById<AudioPatch>(patches, in_requested.id);
1002 if (existing != patches.end()) {
1003 patchesBackup = mPatches;
1004 cleanUpPatch(existing->id);
1005 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301006 LOG(ERROR) << __func__ << ": " << mType << ": not found existing patch id "
1007 << in_requested.id;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001008 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1009 }
1010 }
1011 // Validate the requested patch.
1012 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
1013 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301014 LOG(ERROR) << __func__ << ": " << mType << ": sink port id " << sinkPortId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001015 << "is exclusive and is already used by some other patch";
1016 if (patchesBackup.has_value()) {
1017 mPatches = std::move(*patchesBackup);
1018 }
1019 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1020 }
1021 }
Mikhail Naganov13501872023-10-18 16:15:46 -07001022 // Find the highest sample rate among mix port configs.
1023 std::map<int32_t, AudioPortConfig*> sampleRates;
1024 std::vector<AudioPortConfig*>& mixPortConfigs =
1025 sources[0]->ext.getTag() == AudioPortExt::mix ? sources : sinks;
1026 for (auto mix : mixPortConfigs) {
1027 sampleRates.emplace(mix->sampleRate.value().value, mix);
1028 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001029 *_aidl_return = in_requested;
Mikhail Naganov13501872023-10-18 16:15:46 -07001030 auto maxSampleRateIt = std::max_element(sampleRates.begin(), sampleRates.end());
1031 const int32_t latencyMs = getNominalLatencyMs(*(maxSampleRateIt->second));
1032 _aidl_return->minimumStreamBufferSizeFrames =
1033 calculateBufferSizeFrames(latencyMs, maxSampleRateIt->first);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +00001034 _aidl_return->latenciesMs.clear();
1035 _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
Mikhail Naganov13501872023-10-18 16:15:46 -07001036 _aidl_return->sinkPortConfigIds.size(), latencyMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001037 AudioPatch oldPatch{};
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001038 if (existing == patches.end()) {
1039 _aidl_return->id = getConfig().nextPatchId++;
1040 patches.push_back(*_aidl_return);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001041 } else {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001042 oldPatch = *existing;
Mikhail Naganovdc417732023-09-29 15:49:35 -07001043 *existing = *_aidl_return;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001044 }
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001045 patchesBackup = mPatches;
1046 registerPatch(*_aidl_return);
1047 if (auto status = updateStreamsConnectedState(oldPatch, *_aidl_return); !status.isOk()) {
1048 mPatches = std::move(*patchesBackup);
1049 if (existing == patches.end()) {
1050 patches.pop_back();
1051 } else {
1052 *existing = oldPatch;
1053 }
1054 return status;
1055 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001056
Jaideep Sharma559a4912024-03-07 10:05:51 +05301057 LOG(DEBUG) << __func__ << ": " << mType << ": " << (oldPatch.id == 0 ? "created" : "updated")
1058 << " patch " << _aidl_return->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001059 return ndk::ScopedAStatus::ok();
1060}
1061
1062ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
1063 AudioPortConfig* out_suggested, bool* _aidl_return) {
Mikhail Naganova92039a2023-12-20 14:27:22 -08001064 auto generate = [this](const AudioPort& port, AudioPortConfig* config) {
1065 return generateDefaultPortConfig(port, config);
1066 };
1067 return setAudioPortConfigImpl(in_requested, generate, out_suggested, _aidl_return);
1068}
1069
1070ndk::ScopedAStatus Module::setAudioPortConfigImpl(
1071 const AudioPortConfig& in_requested,
1072 const std::function<bool(const ::aidl::android::media::audio::common::AudioPort& port,
1073 ::aidl::android::media::audio::common::AudioPortConfig* config)>&
1074 fillPortConfig,
1075 AudioPortConfig* out_suggested, bool* applied) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301076 LOG(DEBUG) << __func__ << ": " << mType << ": requested " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001077 auto& configs = getConfig().portConfigs;
1078 auto existing = configs.end();
1079 if (in_requested.id != 0) {
1080 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
1081 existing == configs.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301082 LOG(ERROR) << __func__ << ": " << mType << ": existing port config id "
1083 << in_requested.id << " not found";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001084 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1085 }
1086 }
1087
1088 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
1089 if (portId == 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301090 LOG(ERROR) << __func__ << ": " << mType
1091 << ": requested port config does not specify portId";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001092 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1093 }
1094 auto& ports = getConfig().ports;
1095 auto portIt = findById<AudioPort>(ports, portId);
1096 if (portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301097 LOG(ERROR) << __func__ << ": " << mType
1098 << ": requested port config points to non-existent portId " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001099 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1100 }
1101 if (existing != configs.end()) {
1102 *out_suggested = *existing;
1103 } else {
1104 AudioPortConfig newConfig;
Mikhail Naganova92039a2023-12-20 14:27:22 -08001105 newConfig.portId = portIt->id;
1106 if (fillPortConfig(*portIt, &newConfig)) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001107 *out_suggested = newConfig;
1108 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301109 LOG(ERROR) << __func__ << ": " << mType
1110 << ": unable generate a default config for port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001111 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1112 }
1113 }
1114 // From this moment, 'out_suggested' is either an existing port config,
1115 // or a new generated config. Now attempt to update it according to the specified
1116 // fields of 'in_requested'.
1117
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001118 // Device ports with only dynamic profiles are used for devices that are connected via ADSP,
1119 // which takes care of their actual configuration automatically.
1120 const bool allowDynamicConfig = portIt->ext.getTag() == AudioPortExt::device &&
1121 hasDynamicProfilesOnly(portIt->profiles);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001122 bool requestedIsValid = true, requestedIsFullySpecified = true;
1123
1124 AudioIoFlags portFlags = portIt->flags;
1125 if (in_requested.flags.has_value()) {
1126 if (in_requested.flags.value() != portFlags) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301127 LOG(WARNING) << __func__ << ": " << mType << ": requested flags "
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001128 << in_requested.flags.value().toString() << " do not match port's "
1129 << portId << " flags " << portFlags.toString();
1130 requestedIsValid = false;
1131 }
1132 } else {
1133 requestedIsFullySpecified = false;
1134 }
1135
1136 AudioProfile portProfile;
1137 if (in_requested.format.has_value()) {
1138 const auto& format = in_requested.format.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001139 if ((format == AudioFormatDescription{} && allowDynamicConfig) ||
1140 findAudioProfile(*portIt, format, &portProfile)) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001141 out_suggested->format = format;
1142 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301143 LOG(WARNING) << __func__ << ": " << mType << ": requested format " << format.toString()
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001144 << " is not found in the profiles of port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001145 requestedIsValid = false;
1146 }
1147 } else {
1148 requestedIsFullySpecified = false;
1149 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001150 if (!(out_suggested->format.value() == AudioFormatDescription{} && allowDynamicConfig) &&
1151 !findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301152 LOG(ERROR) << __func__ << ": " << mType << ": port " << portId
1153 << " does not support format " << out_suggested->format.value().toString()
1154 << " anymore";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001155 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1156 }
1157
1158 if (in_requested.channelMask.has_value()) {
1159 const auto& channelMask = in_requested.channelMask.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001160 if ((channelMask == AudioChannelLayout{} && allowDynamicConfig) ||
1161 find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
1162 portProfile.channelMasks.end()) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001163 out_suggested->channelMask = channelMask;
1164 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301165 LOG(WARNING) << __func__ << ": " << mType << ": requested channel mask "
1166 << channelMask.toString() << " is not supported for the format "
1167 << portProfile.format.toString() << " by the port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001168 requestedIsValid = false;
1169 }
1170 } else {
1171 requestedIsFullySpecified = false;
1172 }
1173
1174 if (in_requested.sampleRate.has_value()) {
1175 const auto& sampleRate = in_requested.sampleRate.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001176 if ((sampleRate.value == 0 && allowDynamicConfig) ||
1177 find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001178 sampleRate.value) != portProfile.sampleRates.end()) {
1179 out_suggested->sampleRate = sampleRate;
1180 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301181 LOG(WARNING) << __func__ << ": " << mType << ": requested sample rate "
1182 << sampleRate.value << " is not supported for the format "
1183 << portProfile.format.toString() << " by the port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001184 requestedIsValid = false;
1185 }
1186 } else {
1187 requestedIsFullySpecified = false;
1188 }
1189
1190 if (in_requested.gain.has_value()) {
1191 // Let's pretend that gain can always be applied.
1192 out_suggested->gain = in_requested.gain.value();
1193 }
1194
Mikhail Naganov248e9502023-02-21 16:32:40 -08001195 if (in_requested.ext.getTag() != AudioPortExt::Tag::unspecified) {
1196 if (in_requested.ext.getTag() == out_suggested->ext.getTag()) {
1197 if (out_suggested->ext.getTag() == AudioPortExt::Tag::mix) {
Mikhail Naganovb06a4922024-03-06 16:39:50 -08001198 // 'AudioMixPortExt.handle' and '.usecase' are set by the client,
1199 // copy from in_requested.
1200 const auto& src = in_requested.ext.get<AudioPortExt::Tag::mix>();
1201 auto& dst = out_suggested->ext.get<AudioPortExt::Tag::mix>();
1202 dst.handle = src.handle;
1203 dst.usecase = src.usecase;
Mikhail Naganov248e9502023-02-21 16:32:40 -08001204 }
1205 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301206 LOG(WARNING) << __func__ << ": " << mType << ": requested ext tag "
Mikhail Naganov248e9502023-02-21 16:32:40 -08001207 << toString(in_requested.ext.getTag()) << " do not match port's tag "
1208 << toString(out_suggested->ext.getTag());
1209 requestedIsValid = false;
1210 }
1211 }
1212
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001213 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
1214 out_suggested->id = getConfig().nextPortId++;
1215 configs.push_back(*out_suggested);
Mikhail Naganova92039a2023-12-20 14:27:22 -08001216 *applied = true;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301217 LOG(DEBUG) << __func__ << ": " << mType << ": created new port config "
1218 << out_suggested->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001219 } else if (existing != configs.end() && requestedIsValid) {
1220 *existing = *out_suggested;
Mikhail Naganova92039a2023-12-20 14:27:22 -08001221 *applied = true;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301222 LOG(DEBUG) << __func__ << ": " << mType << ": updated port config "
1223 << out_suggested->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001224 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301225 LOG(DEBUG) << __func__ << ": " << mType << ": not applied; existing config ? "
1226 << (existing != configs.end()) << "; requested is valid? " << requestedIsValid
1227 << ", fully specified? " << requestedIsFullySpecified;
Mikhail Naganova92039a2023-12-20 14:27:22 -08001228 *applied = false;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001229 }
1230 return ndk::ScopedAStatus::ok();
1231}
1232
1233ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
1234 auto& patches = getConfig().patches;
1235 auto patchIt = findById<AudioPatch>(patches, in_patchId);
1236 if (patchIt != patches.end()) {
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001237 auto patchesBackup = mPatches;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001238 cleanUpPatch(patchIt->id);
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001239 if (auto status = updateStreamsConnectedState(*patchIt, AudioPatch{}); !status.isOk()) {
1240 mPatches = std::move(patchesBackup);
1241 return status;
1242 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001243 patches.erase(patchIt);
Jaideep Sharma559a4912024-03-07 10:05:51 +05301244 LOG(DEBUG) << __func__ << ": " << mType << ": erased patch " << in_patchId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001245 return ndk::ScopedAStatus::ok();
1246 }
Jaideep Sharma559a4912024-03-07 10:05:51 +05301247 LOG(ERROR) << __func__ << ": " << mType << ": patch id " << in_patchId << " not found";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001248 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1249}
1250
1251ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
1252 auto& configs = getConfig().portConfigs;
1253 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
1254 if (configIt != configs.end()) {
1255 if (mStreams.count(in_portConfigId) != 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301256 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001257 << " has a stream opened on it";
1258 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1259 }
1260 auto patchIt = mPatches.find(in_portConfigId);
1261 if (patchIt != mPatches.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301262 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001263 << " is used by the patch with id " << patchIt->second;
1264 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1265 }
1266 auto& initials = getConfig().initialConfigs;
1267 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
1268 if (initialIt == initials.end()) {
1269 configs.erase(configIt);
Jaideep Sharma559a4912024-03-07 10:05:51 +05301270 LOG(DEBUG) << __func__ << ": " << mType << ": erased port config " << in_portConfigId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001271 } else if (*configIt != *initialIt) {
1272 *configIt = *initialIt;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301273 LOG(DEBUG) << __func__ << ": " << mType << ": reset port config " << in_portConfigId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001274 }
1275 return ndk::ScopedAStatus::ok();
1276 }
Jaideep Sharma559a4912024-03-07 10:05:51 +05301277 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
1278 << " not found";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001279 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1280}
1281
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001282ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) {
1283 *_aidl_return = mMasterMute;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301284 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001285 return ndk::ScopedAStatus::ok();
1286}
1287
1288ndk::ScopedAStatus Module::setMasterMute(bool in_mute) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301289 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_mute;
jiabin783c48b2023-02-28 18:28:06 +00001290 auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1291 : onMasterMuteChanged(in_mute);
1292 if (result.isOk()) {
1293 mMasterMute = in_mute;
1294 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301295 LOG(ERROR) << __func__ << ": " << mType << ": failed calling onMasterMuteChanged("
1296 << in_mute << "), error=" << result;
jiabin783c48b2023-02-28 18:28:06 +00001297 // Reset master mute if it failed.
1298 onMasterMuteChanged(mMasterMute);
1299 }
Mikhail Naganov55045b52023-10-24 17:03:50 -07001300 return result;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001301}
1302
1303ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) {
1304 *_aidl_return = mMasterVolume;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301305 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001306 return ndk::ScopedAStatus::ok();
1307}
1308
1309ndk::ScopedAStatus Module::setMasterVolume(float in_volume) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301310 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_volume;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001311 if (in_volume >= 0.0f && in_volume <= 1.0f) {
jiabin783c48b2023-02-28 18:28:06 +00001312 auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1313 : onMasterVolumeChanged(in_volume);
1314 if (result.isOk()) {
1315 mMasterVolume = in_volume;
1316 } else {
1317 // Reset master volume if it failed.
Jaideep Sharma559a4912024-03-07 10:05:51 +05301318 LOG(ERROR) << __func__ << ": " << mType << ": failed calling onMasterVolumeChanged("
1319 << in_volume << "), error=" << result;
jiabin783c48b2023-02-28 18:28:06 +00001320 onMasterVolumeChanged(mMasterVolume);
1321 }
Mikhail Naganov55045b52023-10-24 17:03:50 -07001322 return result;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001323 }
Jaideep Sharma559a4912024-03-07 10:05:51 +05301324 LOG(ERROR) << __func__ << ": " << mType << ": invalid master volume value: " << in_volume;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001325 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1326}
1327
1328ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) {
1329 *_aidl_return = mMicMute;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301330 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001331 return ndk::ScopedAStatus::ok();
1332}
1333
1334ndk::ScopedAStatus Module::setMicMute(bool in_mute) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301335 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_mute;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001336 mMicMute = in_mute;
1337 return ndk::ScopedAStatus::ok();
1338}
1339
Mikhail Naganovef6bc742022-10-06 00:14:19 +00001340ndk::ScopedAStatus Module::getMicrophones(std::vector<MicrophoneInfo>* _aidl_return) {
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +00001341 *_aidl_return = getMicrophoneInfos();
Jaideep Sharma559a4912024-03-07 10:05:51 +05301342 LOG(DEBUG) << __func__ << ": " << mType << ": returning "
1343 << ::android::internal::ToString(*_aidl_return);
Mikhail Naganovef6bc742022-10-06 00:14:19 +00001344 return ndk::ScopedAStatus::ok();
1345}
1346
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001347ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) {
Mikhail Naganov04ae8222023-01-11 15:48:10 -08001348 if (!isValidAudioMode(in_mode)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301349 LOG(ERROR) << __func__ << ": " << mType << ": invalid mode " << toString(in_mode);
Mikhail Naganov04ae8222023-01-11 15:48:10 -08001350 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1351 }
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001352 // No checks for supported audio modes here, it's an informative notification.
Jaideep Sharma559a4912024-03-07 10:05:51 +05301353 LOG(DEBUG) << __func__ << ": " << mType << ": " << toString(in_mode);
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001354 return ndk::ScopedAStatus::ok();
1355}
1356
1357ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301358 LOG(DEBUG) << __func__ << ": " << mType << ": " << toString(in_rotation);
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001359 return ndk::ScopedAStatus::ok();
1360}
1361
1362ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301363 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_isTurnedOn;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001364 return ndk::ScopedAStatus::ok();
1365}
1366
Vlad Popa83a6d822022-11-07 13:53:57 +01001367ndk::ScopedAStatus Module::getSoundDose(std::shared_ptr<ISoundDose>* _aidl_return) {
Mikhail Naganov7499a002023-02-27 18:51:44 -08001368 if (!mSoundDose) {
Vlad Popa2afbd1e2022-12-28 17:04:58 +01001369 mSoundDose = ndk::SharedRefBase::make<sounddose::SoundDose>();
Vlad Popa943b7e22022-12-08 14:24:12 +01001370 }
Mikhail Naganov780fefb2023-07-21 17:01:38 -07001371 *_aidl_return = mSoundDose.getInstance();
Jaideep Sharma559a4912024-03-07 10:05:51 +05301372 LOG(DEBUG) << __func__ << ": " << mType
1373 << ": returning instance of ISoundDose: " << _aidl_return->get();
Vlad Popa83a6d822022-11-07 13:53:57 +01001374 return ndk::ScopedAStatus::ok();
1375}
1376
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001377ndk::ScopedAStatus Module::generateHwAvSyncId(int32_t* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301378 LOG(DEBUG) << __func__ << ": " << mType;
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001379 (void)_aidl_return;
1380 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1381}
1382
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001383const std::string Module::VendorDebug::kForceTransientBurstName = "aosp.forceTransientBurst";
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001384const std::string Module::VendorDebug::kForceSynchronousDrainName = "aosp.forceSynchronousDrain";
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001385
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001386ndk::ScopedAStatus Module::getVendorParameters(const std::vector<std::string>& in_ids,
1387 std::vector<VendorParameter>* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301388 LOG(VERBOSE) << __func__ << ": " << mType << ": id count: " << in_ids.size();
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001389 bool allParametersKnown = true;
1390 for (const auto& id : in_ids) {
1391 if (id == VendorDebug::kForceTransientBurstName) {
1392 VendorParameter forceTransientBurst{.id = id};
1393 forceTransientBurst.ext.setParcelable(Boolean{mVendorDebug.forceTransientBurst});
1394 _aidl_return->push_back(std::move(forceTransientBurst));
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001395 } else if (id == VendorDebug::kForceSynchronousDrainName) {
1396 VendorParameter forceSynchronousDrain{.id = id};
1397 forceSynchronousDrain.ext.setParcelable(Boolean{mVendorDebug.forceSynchronousDrain});
1398 _aidl_return->push_back(std::move(forceSynchronousDrain));
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001399 } else {
1400 allParametersKnown = false;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301401 LOG(VERBOSE) << __func__ << ": " << mType << ": unrecognized parameter \"" << id << "\"";
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001402 }
1403 }
1404 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1405 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001406}
1407
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001408namespace {
1409
1410template <typename W>
1411bool extractParameter(const VendorParameter& p, decltype(W::value)* v) {
1412 std::optional<W> value;
1413 binder_status_t result = p.ext.getParcelable(&value);
1414 if (result == STATUS_OK && value.has_value()) {
1415 *v = value.value().value;
1416 return true;
1417 }
1418 LOG(ERROR) << __func__ << ": failed to read the value of the parameter \"" << p.id
1419 << "\": " << result;
1420 return false;
1421}
1422
1423} // namespace
1424
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001425ndk::ScopedAStatus Module::setVendorParameters(const std::vector<VendorParameter>& in_parameters,
1426 bool in_async) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301427 LOG(VERBOSE) << __func__ << ": " << mType << ": parameter count " << in_parameters.size()
1428 << ", async: " << in_async;
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001429 bool allParametersKnown = true;
1430 for (const auto& p : in_parameters) {
1431 if (p.id == VendorDebug::kForceTransientBurstName) {
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001432 if (!extractParameter<Boolean>(p, &mVendorDebug.forceTransientBurst)) {
1433 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1434 }
1435 } else if (p.id == VendorDebug::kForceSynchronousDrainName) {
1436 if (!extractParameter<Boolean>(p, &mVendorDebug.forceSynchronousDrain)) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001437 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1438 }
1439 } else {
1440 allParametersKnown = false;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301441 LOG(VERBOSE) << __func__ << ": " << mType << ": unrecognized parameter \"" << p.id
1442 << "\"";
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001443 }
1444 }
1445 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1446 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001447}
1448
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001449ndk::ScopedAStatus Module::addDeviceEffect(
1450 int32_t in_portConfigId,
1451 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1452 if (in_effect == nullptr) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301453 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1454 << ", null effect";
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001455 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301456 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1457 << ", effect Binder " << in_effect->asBinder().get();
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001458 }
1459 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1460}
1461
1462ndk::ScopedAStatus Module::removeDeviceEffect(
1463 int32_t in_portConfigId,
1464 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1465 if (in_effect == nullptr) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301466 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1467 << ", null effect";
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001468 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301469 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1470 << ", effect Binder " << in_effect->asBinder().get();
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001471 }
1472 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1473}
1474
jiabin9a8e6862023-01-12 23:06:37 +00001475ndk::ScopedAStatus Module::getMmapPolicyInfos(AudioMMapPolicyType mmapPolicyType,
1476 std::vector<AudioMMapPolicyInfo>* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301477 LOG(DEBUG) << __func__ << ": " << mType << ": mmap policy type " << toString(mmapPolicyType);
jiabin9a8e6862023-01-12 23:06:37 +00001478 std::set<int32_t> mmapSinks;
1479 std::set<int32_t> mmapSources;
1480 auto& ports = getConfig().ports;
1481 for (const auto& port : ports) {
1482 if (port.flags.getTag() == AudioIoFlags::Tag::input &&
1483 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::input>(),
1484 AudioInputFlags::MMAP_NOIRQ)) {
1485 mmapSinks.insert(port.id);
1486 } else if (port.flags.getTag() == AudioIoFlags::Tag::output &&
1487 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
1488 AudioOutputFlags::MMAP_NOIRQ)) {
1489 mmapSources.insert(port.id);
1490 }
1491 }
Mikhail Naganov85064912023-09-26 17:10:08 -07001492 if (mmapSources.empty() && mmapSinks.empty()) {
1493 AudioMMapPolicyInfo never;
1494 never.mmapPolicy = AudioMMapPolicy::NEVER;
1495 _aidl_return->push_back(never);
1496 return ndk::ScopedAStatus::ok();
1497 }
jiabin9a8e6862023-01-12 23:06:37 +00001498 for (const auto& route : getConfig().routes) {
1499 if (mmapSinks.count(route.sinkPortId) != 0) {
1500 // The sink is a mix port, add the sources if they are device ports.
1501 for (int sourcePortId : route.sourcePortIds) {
1502 auto sourcePortIt = findById<AudioPort>(ports, sourcePortId);
1503 if (sourcePortIt == ports.end()) {
1504 // This must not happen
Jaideep Sharma559a4912024-03-07 10:05:51 +05301505 LOG(ERROR) << __func__ << ": " << mType << ": port id " << sourcePortId
1506 << " cannot be found";
jiabin9a8e6862023-01-12 23:06:37 +00001507 continue;
1508 }
1509 if (sourcePortIt->ext.getTag() != AudioPortExt::Tag::device) {
1510 // The source is not a device port, skip
1511 continue;
1512 }
1513 AudioMMapPolicyInfo policyInfo;
1514 policyInfo.device = sourcePortIt->ext.get<AudioPortExt::Tag::device>().device;
1515 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1516 // default implementation.
1517 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1518 _aidl_return->push_back(policyInfo);
1519 }
1520 } else {
1521 auto sinkPortIt = findById<AudioPort>(ports, route.sinkPortId);
1522 if (sinkPortIt == ports.end()) {
1523 // This must not happen
Jaideep Sharma559a4912024-03-07 10:05:51 +05301524 LOG(ERROR) << __func__ << ": " << mType << ": port id " << route.sinkPortId
1525 << " cannot be found";
jiabin9a8e6862023-01-12 23:06:37 +00001526 continue;
1527 }
1528 if (sinkPortIt->ext.getTag() != AudioPortExt::Tag::device) {
1529 // The sink is not a device port, skip
1530 continue;
1531 }
1532 if (count_any(mmapSources, route.sourcePortIds)) {
1533 AudioMMapPolicyInfo policyInfo;
1534 policyInfo.device = sinkPortIt->ext.get<AudioPortExt::Tag::device>().device;
1535 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1536 // default implementation.
1537 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1538 _aidl_return->push_back(policyInfo);
1539 }
1540 }
1541 }
1542 return ndk::ScopedAStatus::ok();
1543}
1544
Eric Laurente2432ea2023-01-12 17:47:31 +01001545ndk::ScopedAStatus Module::supportsVariableLatency(bool* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301546 LOG(DEBUG) << __func__ << ": " << mType;
Eric Laurente2432ea2023-01-12 17:47:31 +01001547 *_aidl_return = false;
1548 return ndk::ScopedAStatus::ok();
1549}
1550
jiabinb76981e2023-01-18 00:58:30 +00001551ndk::ScopedAStatus Module::getAAudioMixerBurstCount(int32_t* _aidl_return) {
1552 if (!isMmapSupported()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301553 LOG(DEBUG) << __func__ << ": " << mType << ": mmap is not supported ";
jiabinb76981e2023-01-18 00:58:30 +00001554 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1555 }
1556 *_aidl_return = DEFAULT_AAUDIO_MIXER_BURST_COUNT;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301557 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
jiabinb76981e2023-01-18 00:58:30 +00001558 return ndk::ScopedAStatus::ok();
1559}
1560
1561ndk::ScopedAStatus Module::getAAudioHardwareBurstMinUsec(int32_t* _aidl_return) {
1562 if (!isMmapSupported()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301563 LOG(DEBUG) << __func__ << ": " << mType << ": mmap is not supported ";
jiabinb76981e2023-01-18 00:58:30 +00001564 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1565 }
1566 *_aidl_return = DEFAULT_AAUDIO_HARDWARE_BURST_MIN_DURATION_US;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301567 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
jiabinb76981e2023-01-18 00:58:30 +00001568 return ndk::ScopedAStatus::ok();
1569}
1570
1571bool Module::isMmapSupported() {
1572 if (mIsMmapSupported.has_value()) {
1573 return mIsMmapSupported.value();
1574 }
1575 std::vector<AudioMMapPolicyInfo> mmapPolicyInfos;
1576 if (!getMmapPolicyInfos(AudioMMapPolicyType::DEFAULT, &mmapPolicyInfos).isOk()) {
1577 mIsMmapSupported = false;
1578 } else {
1579 mIsMmapSupported =
1580 std::find_if(mmapPolicyInfos.begin(), mmapPolicyInfos.end(), [](const auto& info) {
1581 return info.mmapPolicy == AudioMMapPolicy::AUTO ||
1582 info.mmapPolicy == AudioMMapPolicy::ALWAYS;
1583 }) != mmapPolicyInfos.end();
1584 }
1585 return mIsMmapSupported.value();
1586}
1587
Mikhail Naganova92039a2023-12-20 14:27:22 -08001588ndk::ScopedAStatus Module::populateConnectedDevicePort(AudioPort* audioPort, int32_t) {
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001589 if (audioPort->ext.getTag() != AudioPortExt::device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301590 LOG(ERROR) << __func__ << ": " << mType << ": not a device port: " << audioPort->toString();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001591 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1592 }
1593 const auto& devicePort = audioPort->ext.get<AudioPortExt::device>();
1594 if (!devicePort.device.type.connection.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301595 LOG(ERROR) << __func__ << ": " << mType << ": module implementation must override "
1596 "'populateConnectedDevicePort' "
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001597 << "to handle connection of external devices.";
1598 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1599 }
Jaideep Sharma559a4912024-03-07 10:05:51 +05301600 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
jiabin253bd322023-01-25 23:57:31 +00001601 return ndk::ScopedAStatus::ok();
1602}
1603
1604ndk::ScopedAStatus Module::checkAudioPatchEndpointsMatch(
1605 const std::vector<AudioPortConfig*>& sources __unused,
1606 const std::vector<AudioPortConfig*>& sinks __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301607 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
jiabin253bd322023-01-25 23:57:31 +00001608 return ndk::ScopedAStatus::ok();
1609}
1610
jiabin783c48b2023-02-28 18:28:06 +00001611void Module::onExternalDeviceConnectionChanged(
1612 const ::aidl::android::media::audio::common::AudioPort& audioPort __unused,
1613 bool connected __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301614 LOG(DEBUG) << __func__ << ": " << mType << ": do nothing and return";
jiabin783c48b2023-02-28 18:28:06 +00001615}
1616
jiabindd23b0e2023-12-11 19:10:05 +00001617void Module::onPrepareToDisconnectExternalDevice(
1618 const ::aidl::android::media::audio::common::AudioPort& audioPort __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301619 LOG(DEBUG) << __func__ << ": " << mType << ": do nothing and return";
jiabindd23b0e2023-12-11 19:10:05 +00001620}
1621
jiabin783c48b2023-02-28 18:28:06 +00001622ndk::ScopedAStatus Module::onMasterMuteChanged(bool mute __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301623 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
jiabin783c48b2023-02-28 18:28:06 +00001624 return ndk::ScopedAStatus::ok();
1625}
1626
1627ndk::ScopedAStatus Module::onMasterVolumeChanged(float volume __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301628 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
jiabin783c48b2023-02-28 18:28:06 +00001629 return ndk::ScopedAStatus::ok();
1630}
1631
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +00001632std::vector<MicrophoneInfo> Module::getMicrophoneInfos() {
1633 std::vector<MicrophoneInfo> result;
1634 Configuration& config = getConfig();
1635 for (const AudioPort& port : config.ports) {
1636 if (port.ext.getTag() == AudioPortExt::Tag::device) {
1637 const AudioDeviceType deviceType =
1638 port.ext.get<AudioPortExt::Tag::device>().device.type.type;
1639 if (deviceType == AudioDeviceType::IN_MICROPHONE ||
1640 deviceType == AudioDeviceType::IN_MICROPHONE_BACK) {
1641 // Placeholder values. Vendor implementations must populate MicrophoneInfo
1642 // accordingly based on their physical microphone parameters.
1643 result.push_back(MicrophoneInfo{
1644 .id = port.name,
1645 .device = port.ext.get<AudioPortExt::Tag::device>().device,
1646 .group = 0,
1647 .indexInTheGroup = 0,
1648 });
1649 }
1650 }
1651 }
1652 return result;
1653}
1654
Ram Mohan18f0d512023-07-01 00:47:09 +05301655ndk::ScopedAStatus Module::bluetoothParametersUpdated() {
1656 return mStreams.bluetoothParametersUpdated();
1657}
1658
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001659} // namespace aidl::android::hardware::audio::core