blob: 123a5ecbbaa01eff9ad2e7f71e5ed7ce45edc9be [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;
Kuowei Li53a8d4d2024-06-24 14:35:07 +080039using aidl::android::hardware::audio::common::hasMmapFlag;
Mikhail Naganov872d4a62023-03-09 18:19:01 -080040using aidl::android::hardware::audio::common::isBitPositionFlagSet;
41using aidl::android::hardware::audio::common::isValidAudioMode;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000042using aidl::android::hardware::audio::common::SinkMetadata;
43using aidl::android::hardware::audio::common::SourceMetadata;
Vlad Popa2afbd1e2022-12-28 17:04:58 +010044using aidl::android::hardware::audio::core::sounddose::ISoundDose;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000045using aidl::android::media::audio::common::AudioChannelLayout;
Mikhail Naganovef6bc742022-10-06 00:14:19 +000046using aidl::android::media::audio::common::AudioDevice;
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +000047using aidl::android::media::audio::common::AudioDeviceType;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000048using aidl::android::media::audio::common::AudioFormatDescription;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000049using aidl::android::media::audio::common::AudioFormatType;
Weilin Xua33bb5e2024-10-02 17:16:42 +000050using aidl::android::media::audio::common::AudioGainConfig;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000051using aidl::android::media::audio::common::AudioInputFlags;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000052using aidl::android::media::audio::common::AudioIoFlags;
jiabin9a8e6862023-01-12 23:06:37 +000053using aidl::android::media::audio::common::AudioMMapPolicy;
54using aidl::android::media::audio::common::AudioMMapPolicyInfo;
55using aidl::android::media::audio::common::AudioMMapPolicyType;
Mikhail Naganov04ae8222023-01-11 15:48:10 -080056using aidl::android::media::audio::common::AudioMode;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000057using aidl::android::media::audio::common::AudioOffloadInfo;
58using aidl::android::media::audio::common::AudioOutputFlags;
59using aidl::android::media::audio::common::AudioPort;
60using aidl::android::media::audio::common::AudioPortConfig;
61using aidl::android::media::audio::common::AudioPortExt;
62using aidl::android::media::audio::common::AudioProfile;
Mikhail Naganov20047bc2023-01-05 20:16:07 +000063using aidl::android::media::audio::common::Boolean;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000064using aidl::android::media::audio::common::Int;
Mikhail Naganov6725ef52023-02-09 17:52:50 -080065using aidl::android::media::audio::common::MicrophoneInfo;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000066using aidl::android::media::audio::common::PcmType;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000067
68namespace aidl::android::hardware::audio::core {
69
70namespace {
71
Mikhail Naganov84bcc042023-10-05 17:36:57 -070072inline bool hasDynamicChannelMasks(const std::vector<AudioChannelLayout>& channelMasks) {
73 return channelMasks.empty() ||
74 std::all_of(channelMasks.begin(), channelMasks.end(),
75 [](const auto& channelMask) { return channelMask == AudioChannelLayout{}; });
76}
77
78inline bool hasDynamicFormat(const AudioFormatDescription& format) {
79 return format == AudioFormatDescription{};
80}
81
82inline bool hasDynamicSampleRates(const std::vector<int32_t>& sampleRates) {
83 return sampleRates.empty() ||
84 std::all_of(sampleRates.begin(), sampleRates.end(),
85 [](const auto& sampleRate) { return sampleRate == 0; });
86}
87
88inline bool isDynamicProfile(const AudioProfile& profile) {
89 return hasDynamicFormat(profile.format) || hasDynamicChannelMasks(profile.channelMasks) ||
90 hasDynamicSampleRates(profile.sampleRates);
91}
92
93bool hasDynamicProfilesOnly(const std::vector<AudioProfile>& profiles) {
94 if (profiles.empty()) return true;
95 return std::all_of(profiles.begin(), profiles.end(), isDynamicProfile);
96}
97
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000098bool findAudioProfile(const AudioPort& port, const AudioFormatDescription& format,
99 AudioProfile* profile) {
100 if (auto profilesIt =
101 find_if(port.profiles.begin(), port.profiles.end(),
102 [&format](const auto& profile) { return profile.format == format; });
103 profilesIt != port.profiles.end()) {
104 *profile = *profilesIt;
105 return true;
106 }
107 return false;
108}
Mikhail Naganov00603d12022-05-02 22:52:13 +0000109
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000110} // namespace
111
jiabin253bd322023-01-25 23:57:31 +0000112// static
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000113std::shared_ptr<Module> Module::createInstance(Type type, std::unique_ptr<Configuration>&& config) {
jiabin253bd322023-01-25 23:57:31 +0000114 switch (type) {
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530115 case Type::DEFAULT:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000116 return ndk::SharedRefBase::make<ModulePrimary>(std::move(config));
Mikhail Naganov521fc492023-07-11 17:24:08 -0700117 case Type::R_SUBMIX:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000118 return ndk::SharedRefBase::make<ModuleRemoteSubmix>(std::move(config));
Mikhail Naganov521fc492023-07-11 17:24:08 -0700119 case Type::STUB:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000120 return ndk::SharedRefBase::make<ModuleStub>(std::move(config));
Mikhail Naganov521fc492023-07-11 17:24:08 -0700121 case Type::USB:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000122 return ndk::SharedRefBase::make<ModuleUsb>(std::move(config));
Mikhail Naganovb03b5c42023-07-26 13:13:35 -0700123 case Type::BLUETOOTH:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000124 return ndk::SharedRefBase::make<ModuleBluetooth>(std::move(config));
jiabin253bd322023-01-25 23:57:31 +0000125 }
126}
127
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000128// static
129std::optional<Module::Type> Module::typeFromString(const std::string& type) {
130 if (type == "default")
131 return Module::Type::DEFAULT;
132 else if (type == "r_submix")
133 return Module::Type::R_SUBMIX;
134 else if (type == "stub")
135 return Module::Type::STUB;
136 else if (type == "usb")
137 return Module::Type::USB;
138 else if (type == "bluetooth")
139 return Module::Type::BLUETOOTH;
140 return {};
141}
142
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700143std::ostream& operator<<(std::ostream& os, Module::Type t) {
144 switch (t) {
145 case Module::Type::DEFAULT:
146 os << "default";
147 break;
148 case Module::Type::R_SUBMIX:
149 os << "r_submix";
150 break;
Mikhail Naganov521fc492023-07-11 17:24:08 -0700151 case Module::Type::STUB:
152 os << "stub";
153 break;
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700154 case Module::Type::USB:
155 os << "usb";
156 break;
Mikhail Naganovb03b5c42023-07-26 13:13:35 -0700157 case Module::Type::BLUETOOTH:
158 os << "bluetooth";
159 break;
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700160 }
161 return os;
162}
163
Lorena Torres-Huertaf7492512023-01-14 02:49:41 +0000164Module::Module(Type type, std::unique_ptr<Configuration>&& config)
165 : mType(type), mConfig(std::move(config)) {
166 populateConnectedProfiles();
167}
168
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000169void Module::cleanUpPatch(int32_t patchId) {
170 erase_all_values(mPatches, std::set<int32_t>{patchId});
171}
172
Mikhail Naganov8651b362023-01-06 23:15:27 +0000173ndk::ScopedAStatus Module::createStreamContext(
174 int32_t in_portConfigId, int64_t in_bufferSizeFrames,
175 std::shared_ptr<IStreamCallback> asyncCallback,
176 std::shared_ptr<IStreamOutEventCallback> outEventCallback, StreamContext* out_context) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000177 if (in_bufferSizeFrames <= 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530178 LOG(ERROR) << __func__ << ": " << mType << ": non-positive buffer size "
179 << in_bufferSizeFrames;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000180 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
181 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000182 auto& configs = getConfig().portConfigs;
183 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
Mikhail Naganova92039a2023-12-20 14:27:22 -0800184 const int32_t nominalLatencyMs = getNominalLatencyMs(*portConfigIt);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000185 // Since this is a private method, it is assumed that
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000186 // validity of the portConfigId has already been checked.
Kuowei Li10a768a2024-12-09 17:44:40 +0800187 int32_t minimumStreamBufferSizeFrames = 0;
188 if (!calculateBufferSizeFrames(
189 portConfigIt->format.value(), nominalLatencyMs,
190 portConfigIt->sampleRate.value().value, &minimumStreamBufferSizeFrames).isOk()) {
191 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
192 }
Mikhail Naganov13501872023-10-18 16:15:46 -0700193 if (in_bufferSizeFrames < minimumStreamBufferSizeFrames) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530194 LOG(ERROR) << __func__ << ": " << mType << ": insufficient buffer size "
195 << in_bufferSizeFrames << ", must be at least " << minimumStreamBufferSizeFrames;
Mikhail Naganov13501872023-10-18 16:15:46 -0700196 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
197 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000198 const size_t frameSize =
199 getFrameSizeInBytes(portConfigIt->format.value(), portConfigIt->channelMask.value());
200 if (frameSize == 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530201 LOG(ERROR) << __func__ << ": " << mType
202 << ": could not calculate frame size for port config "
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000203 << portConfigIt->toString();
204 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
205 }
Jaideep Sharma559a4912024-03-07 10:05:51 +0530206 LOG(DEBUG) << __func__ << ": " << mType << ": frame size " << frameSize << " bytes";
Mikhail Naganovb511b8a2023-05-15 14:35:24 -0700207 if (frameSize > static_cast<size_t>(kMaximumStreamBufferSizeBytes / in_bufferSizeFrames)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530208 LOG(ERROR) << __func__ << ": " << mType << ": buffer size " << in_bufferSizeFrames
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000209 << " frames is too large, maximum size is "
210 << kMaximumStreamBufferSizeBytes / frameSize;
211 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
212 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000213 const auto& flags = portConfigIt->flags.value();
Mikhail Naganovefc2b322025-02-12 16:08:55 -0800214 StreamContext::DebugParameters params{mDebug.streamTransientStateDelayMs,
215 mVendorDebug.forceTransientBurst,
216 mVendorDebug.forceSynchronousDrain};
Kuowei Li53a8d4d2024-06-24 14:35:07 +0800217 std::unique_ptr<StreamContext::DataMQ> dataMQ = nullptr;
218 std::shared_ptr<IStreamCallback> streamAsyncCallback = nullptr;
219 std::shared_ptr<ISoundDose> soundDose;
220 if (!getSoundDose(&soundDose).isOk()) {
221 LOG(ERROR) << __func__ << ": could not create sound dose instance";
222 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
223 }
224 if (!hasMmapFlag(flags)) {
225 dataMQ = std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames);
226 streamAsyncCallback = asyncCallback;
227 }
228 StreamContext temp(
229 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
230 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
231 portConfigIt->format.value(), portConfigIt->channelMask.value(),
232 portConfigIt->sampleRate.value().value, flags, nominalLatencyMs,
233 portConfigIt->ext.get<AudioPortExt::mix>().handle, std::move(dataMQ),
234 streamAsyncCallback, outEventCallback, mSoundDose.getInstance(), params);
235 if (temp.isValid()) {
236 *out_context = std::move(temp);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000237 } else {
Kuowei Li53a8d4d2024-06-24 14:35:07 +0800238 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000239 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000240 return ndk::ScopedAStatus::ok();
241}
242
Ajender Reddy3d248fd2024-10-29 19:10:04 +0530243std::vector<AudioDevice> Module::getDevicesFromDevicePortConfigIds(
244 const std::set<int32_t>& devicePortConfigIds) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000245 std::vector<AudioDevice> result;
Ajender Reddy3d248fd2024-10-29 19:10:04 +0530246 auto& configs = getConfig().portConfigs;
247 for (const auto& id : devicePortConfigIds) {
248 auto it = findById<AudioPortConfig>(configs, id);
249 if (it != configs.end() && it->ext.getTag() == AudioPortExt::Tag::device) {
250 result.push_back(it->ext.template get<AudioPortExt::Tag::device>().device);
251 } else {
252 LOG(FATAL) << __func__ << ": " << mType
253 << ": failed to find device for id" << id;
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000254 }
255 }
256 return result;
257}
258
Ajender Reddy3d248fd2024-10-29 19:10:04 +0530259std::vector<AudioDevice> Module::findConnectedDevices(int32_t portConfigId) {
260 return getDevicesFromDevicePortConfigIds(findConnectedPortConfigIds(portConfigId));
261}
262
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000263std::set<int32_t> Module::findConnectedPortConfigIds(int32_t portConfigId) {
264 std::set<int32_t> result;
265 auto patchIdsRange = mPatches.equal_range(portConfigId);
266 auto& patches = getConfig().patches;
267 for (auto it = patchIdsRange.first; it != patchIdsRange.second; ++it) {
268 auto patchIt = findById<AudioPatch>(patches, it->second);
269 if (patchIt == patches.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530270 LOG(FATAL) << __func__ << ": " << mType << ": patch with id " << it->second
271 << " taken from mPatches "
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000272 << "not found in the configuration";
273 }
274 if (std::find(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end(),
275 portConfigId) != patchIt->sourcePortConfigIds.end()) {
276 result.insert(patchIt->sinkPortConfigIds.begin(), patchIt->sinkPortConfigIds.end());
277 } else {
278 result.insert(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end());
279 }
280 }
281 return result;
282}
283
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000284ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) {
285 auto& configs = getConfig().portConfigs;
286 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
287 if (portConfigIt == configs.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530288 LOG(ERROR) << __func__ << ": " << mType << ": existing port config id " << in_portConfigId
289 << " not found";
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000290 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
291 }
292 const int32_t portId = portConfigIt->portId;
293 // In our implementation, configs of mix ports always have unique IDs.
294 CHECK(portId != in_portConfigId);
295 auto& ports = getConfig().ports;
296 auto portIt = findById<AudioPort>(ports, portId);
297 if (portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530298 LOG(ERROR) << __func__ << ": " << mType << ": port id " << portId
299 << " used by port config id " << in_portConfigId << " not found";
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000300 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
301 }
302 if (mStreams.count(in_portConfigId) != 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530303 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000304 << " already has a stream opened on it";
305 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
306 }
307 if (portIt->ext.getTag() != AudioPortExt::Tag::mix) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530308 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000309 << " does not correspond to a mix port";
310 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
311 }
Mikhail Naganovb511b8a2023-05-15 14:35:24 -0700312 const size_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000313 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530314 LOG(ERROR) << __func__ << ": " << mType << ": port id " << portId
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000315 << " has already reached maximum allowed opened stream count: "
316 << maxOpenStreamCount;
317 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
318 }
319 *port = &(*portIt);
320 return ndk::ScopedAStatus::ok();
321}
322
Mikhail Naganova92039a2023-12-20 14:27:22 -0800323bool Module::generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) {
324 const bool allowDynamicConfig = port.ext.getTag() == AudioPortExt::device;
325 for (const auto& profile : port.profiles) {
326 if (isDynamicProfile(profile)) continue;
327 config->format = profile.format;
328 config->channelMask = *profile.channelMasks.begin();
329 config->sampleRate = Int{.value = *profile.sampleRates.begin()};
330 config->flags = port.flags;
331 config->ext = port.ext;
332 return true;
333 }
334 if (allowDynamicConfig) {
335 config->format = AudioFormatDescription{};
336 config->channelMask = AudioChannelLayout{};
337 config->sampleRate = Int{.value = 0};
338 config->flags = port.flags;
339 config->ext = port.ext;
340 return true;
341 }
Jaideep Sharma559a4912024-03-07 10:05:51 +0530342 LOG(ERROR) << __func__ << ": " << mType << ": port " << port.id << " only has dynamic profiles";
Mikhail Naganova92039a2023-12-20 14:27:22 -0800343 return false;
344}
345
Lorena Torres-Huertaf7492512023-01-14 02:49:41 +0000346void Module::populateConnectedProfiles() {
347 Configuration& config = getConfig();
348 for (const AudioPort& port : config.ports) {
349 if (port.ext.getTag() == AudioPortExt::device) {
350 if (auto devicePort = port.ext.get<AudioPortExt::device>();
351 !devicePort.device.type.connection.empty() && port.profiles.empty()) {
352 if (auto connIt = config.connectedProfiles.find(port.id);
353 connIt == config.connectedProfiles.end()) {
354 config.connectedProfiles.emplace(
355 port.id, internal::getStandard16And24BitPcmAudioProfiles());
356 }
357 }
358 }
359 }
360}
361
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000362template <typename C>
363std::set<int32_t> Module::portIdsFromPortConfigIds(C portConfigIds) {
364 std::set<int32_t> result;
365 auto& portConfigs = getConfig().portConfigs;
366 for (auto it = portConfigIds.begin(); it != portConfigIds.end(); ++it) {
367 auto portConfigIt = findById<AudioPortConfig>(portConfigs, *it);
368 if (portConfigIt != portConfigs.end()) {
369 result.insert(portConfigIt->portId);
370 }
371 }
372 return result;
373}
374
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000375std::unique_ptr<Module::Configuration> Module::initializeConfig() {
376 return internal::getConfiguration(getType());
Peter Yoon918a6a52023-07-13 17:04:37 +0900377}
378
Mikhail Naganov13501872023-10-18 16:15:46 -0700379int32_t Module::getNominalLatencyMs(const AudioPortConfig&) {
380 // Arbitrary value. Implementations must override this method to provide their actual latency.
381 static constexpr int32_t kLatencyMs = 5;
382 return kLatencyMs;
383}
384
Kuowei Li10a768a2024-12-09 17:44:40 +0800385ndk::ScopedAStatus Module::calculateBufferSizeFrames(
386 const ::aidl::android::media::audio::common::AudioFormatDescription &format,
387 int32_t latencyMs, int32_t sampleRateHz, int32_t *bufferSizeFrames) {
388 if (format.type == AudioFormatType::PCM) {
389 *bufferSizeFrames = calculateBufferSizeFramesForPcm(latencyMs, sampleRateHz);
390 return ndk::ScopedAStatus::ok();
391 }
392 LOG(ERROR) << __func__ << ": " << mType << ": format " << format.toString()
393 << " is not supported";
394 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
395}
396
Kuowei Li53a8d4d2024-06-24 14:35:07 +0800397ndk::ScopedAStatus Module::createMmapBuffer(
398 const ::aidl::android::hardware::audio::core::StreamContext& context __unused,
399 ::aidl::android::hardware::audio::core::StreamDescriptor* desc __unused) {
400 LOG(ERROR) << __func__ << ": " << mType << ": is not implemented";
401 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
402}
403
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700404std::vector<AudioRoute*> Module::getAudioRoutesForAudioPortImpl(int32_t portId) {
405 std::vector<AudioRoute*> result;
406 auto& routes = getConfig().routes;
407 for (auto& r : routes) {
408 const auto& srcs = r.sourcePortIds;
409 if (r.sinkPortId == portId || std::find(srcs.begin(), srcs.end(), portId) != srcs.end()) {
410 result.push_back(&r);
411 }
412 }
413 return result;
414}
415
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000416Module::Configuration& Module::getConfig() {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000417 if (!mConfig) {
Yi Konge62f97f2024-08-14 01:52:04 +0800418 mConfig = initializeConfig();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000419 }
420 return *mConfig;
421}
422
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700423std::set<int32_t> Module::getRoutableAudioPortIds(int32_t portId,
424 std::vector<AudioRoute*>* routes) {
425 std::vector<AudioRoute*> routesStorage;
426 if (routes == nullptr) {
427 routesStorage = getAudioRoutesForAudioPortImpl(portId);
428 routes = &routesStorage;
429 }
430 std::set<int32_t> result;
431 for (AudioRoute* r : *routes) {
432 if (r->sinkPortId == portId) {
433 result.insert(r->sourcePortIds.begin(), r->sourcePortIds.end());
434 } else {
435 result.insert(r->sinkPortId);
436 }
437 }
438 return result;
439}
440
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000441void Module::registerPatch(const AudioPatch& patch) {
442 auto& configs = getConfig().portConfigs;
443 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
444 for (auto portConfigId : portConfigIds) {
445 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
446 if (configIt != configs.end()) {
447 mPatches.insert(std::pair{portConfigId, patch.id});
448 if (configIt->portId != portConfigId) {
449 mPatches.insert(std::pair{configIt->portId, patch.id});
450 }
451 }
452 };
453 };
454 do_insert(patch.sourcePortConfigIds);
455 do_insert(patch.sinkPortConfigIds);
456}
457
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700458ndk::ScopedAStatus Module::updateStreamsConnectedState(const AudioPatch& oldPatch,
459 const AudioPatch& newPatch) {
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700460 // Notify streams about the new set of devices they are connected to.
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700461 auto maybeFailure = ndk::ScopedAStatus::ok();
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700462 using Connections =
463 std::map<int32_t /*mixPortConfigId*/, std::set<int32_t /*devicePortConfigId*/>>;
464 Connections oldConnections, newConnections;
465 auto fillConnectionsHelper = [&](Connections& connections,
466 const std::vector<int32_t>& mixPortCfgIds,
467 const std::vector<int32_t>& devicePortCfgIds) {
468 for (int32_t mixPortCfgId : mixPortCfgIds) {
469 connections[mixPortCfgId].insert(devicePortCfgIds.begin(), devicePortCfgIds.end());
470 }
471 };
472 auto fillConnections = [&](Connections& connections, const AudioPatch& patch) {
473 if (std::find_if(patch.sourcePortConfigIds.begin(), patch.sourcePortConfigIds.end(),
474 [&](int32_t portConfigId) { return mStreams.count(portConfigId) > 0; }) !=
475 patch.sourcePortConfigIds.end()) {
476 // Sources are mix ports.
477 fillConnectionsHelper(connections, patch.sourcePortConfigIds, patch.sinkPortConfigIds);
478 } else if (std::find_if(patch.sinkPortConfigIds.begin(), patch.sinkPortConfigIds.end(),
479 [&](int32_t portConfigId) {
480 return mStreams.count(portConfigId) > 0;
481 }) != patch.sinkPortConfigIds.end()) {
482 // Sources are device ports.
483 fillConnectionsHelper(connections, patch.sinkPortConfigIds, patch.sourcePortConfigIds);
484 } // Otherwise, there are no streams to notify.
485 };
Ajender Reddy32e85fc2024-10-30 16:58:17 +0530486 auto restoreOldConnections = [&](const std::set<int32_t>& mixPortIds,
487 const bool continueWithEmptyDevices) {
488 for (const auto mixPort : mixPortIds) {
489 if (auto it = oldConnections.find(mixPort);
490 continueWithEmptyDevices || it != oldConnections.end()) {
491 const std::vector<AudioDevice> d =
492 it != oldConnections.end() ? getDevicesFromDevicePortConfigIds(it->second)
493 : std::vector<AudioDevice>();
494 if (auto status = mStreams.setStreamConnectedDevices(mixPort, d); status.isOk()) {
495 LOG(WARNING) << ":updateStreamsConnectedState: rollback: mix port config:"
496 << mixPort
497 << (d.empty() ? "; not connected"
498 : std::string("; connected to ") +
499 ::android::internal::ToString(d));
500 } else {
501 // can't do much about rollback failures
502 LOG(ERROR)
503 << ":updateStreamsConnectedState: rollback: failed for mix port config:"
504 << mixPort;
505 }
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700506 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000507 }
Ajender Reddy32e85fc2024-10-30 16:58:17 +0530508 };
509 fillConnections(oldConnections, oldPatch);
510 fillConnections(newConnections, newPatch);
511 /**
512 * Illustration of oldConnections and newConnections
513 *
514 * oldConnections {
515 * a : {A,B,C},
516 * b : {D},
517 * d : {H,I,J},
518 * e : {N,O,P},
519 * f : {Q,R},
520 * g : {T,U,V},
521 * }
522 *
523 * newConnections {
524 * a : {A,B,C},
525 * c : {E,F,G},
526 * d : {K,L,M},
527 * e : {N,P},
528 * f : {Q,R,S},
529 * g : {U,V,W},
530 * }
531 *
532 * Expected routings:
533 * 'a': is ignored both in disconnect step and connect step,
534 * due to same devices both in oldConnections and newConnections.
535 * 'b': handled only in disconnect step with empty devices because 'b' is only present
536 * in oldConnections.
537 * 'c': handled only in connect step with {E,F,G} devices because 'c' is only present
538 * in newConnections.
539 * 'd': handled only in connect step with {K,L,M} devices because 'd' is also present
540 * in newConnections and it is ignored in disconnected step.
541 * 'e': handled only in connect step with {N,P} devices because 'e' is also present
542 * in newConnections and it is ignored in disconnect step. please note that there
543 * is no exclusive disconnection for device {O}.
544 * 'f': handled only in connect step with {Q,R,S} devices because 'f' is also present
545 * in newConnections and it is ignored in disconnect step. Even though stream is
546 * already connected with {Q,R} devices and connection happens with {Q,R,S}.
547 * 'g': handled only in connect step with {U,V,W} devices because 'g' is also present
548 * in newConnections and it is ignored in disconnect step. There is no exclusive
549 * disconnection with devices {T,U,V}.
550 *
551 * If, any failure, will lead to restoreOldConnections (rollback).
552 * The aim of the restoreOldConnections is to make connections back to oldConnections.
553 * Failures in restoreOldConnections aren't handled.
554 */
555
556 std::set<int32_t> idsToConnectBackOnFailure;
557 // disconnection step
558 for (const auto& [oldMixPortConfigId, oldDevicePortConfigIds] : oldConnections) {
559 if (auto it = newConnections.find(oldMixPortConfigId); it == newConnections.end()) {
560 idsToConnectBackOnFailure.insert(oldMixPortConfigId);
561 if (auto status = mStreams.setStreamConnectedDevices(oldMixPortConfigId, {});
562 status.isOk()) {
563 LOG(DEBUG) << __func__ << ": The stream on port config id " << oldMixPortConfigId
564 << " has been disconnected";
565 } else {
566 maybeFailure = std::move(status);
567 // proceed to rollback even on one failure
568 break;
569 }
570 }
571 }
572
573 if (!maybeFailure.isOk()) {
574 restoreOldConnections(idsToConnectBackOnFailure, false /*continueWithEmptyDevices*/);
575 LOG(WARNING) << __func__ << ": failed to disconnect from old patch. attempted rollback";
576 return maybeFailure;
577 }
578
579 std::set<int32_t> idsToRollbackOnFailure;
580 // connection step
581 for (const auto& [newMixPortConfigId, newDevicePortConfigIds] : newConnections) {
582 if (auto it = oldConnections.find(newMixPortConfigId);
583 it == oldConnections.end() || it->second != newDevicePortConfigIds) {
584 const auto connectedDevices = getDevicesFromDevicePortConfigIds(newDevicePortConfigIds);
585 idsToRollbackOnFailure.insert(newMixPortConfigId);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700586 if (connectedDevices.empty()) {
587 // This is important as workers use the vector size to derive the connection status.
Ajender Reddy32e85fc2024-10-30 16:58:17 +0530588 LOG(FATAL) << __func__ << ": No connected devices found for port config id "
589 << newMixPortConfigId;
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700590 }
Ajender Reddy32e85fc2024-10-30 16:58:17 +0530591 if (auto status =
592 mStreams.setStreamConnectedDevices(newMixPortConfigId, connectedDevices);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700593 status.isOk()) {
Ajender Reddy32e85fc2024-10-30 16:58:17 +0530594 LOG(DEBUG) << __func__ << ": The stream on port config id " << newMixPortConfigId
595 << " has been connected to: "
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700596 << ::android::internal::ToString(connectedDevices);
597 } else {
598 maybeFailure = std::move(status);
Ajender Reddy32e85fc2024-10-30 16:58:17 +0530599 // proceed to rollback even on one failure
600 break;
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700601 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000602 }
Ajender Reddy32e85fc2024-10-30 16:58:17 +0530603 }
604
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700605 if (!maybeFailure.isOk()) {
Ajender Reddy32e85fc2024-10-30 16:58:17 +0530606 restoreOldConnections(idsToConnectBackOnFailure, false /*continueWithEmptyDevices*/);
607 restoreOldConnections(idsToRollbackOnFailure, true /*continueWithEmptyDevices*/);
608 LOG(WARNING) << __func__ << ": failed to connect for new patch. attempted rollback";
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700609 return maybeFailure;
610 }
Ajender Reddy32e85fc2024-10-30 16:58:17 +0530611
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700612 return ndk::ScopedAStatus::ok();
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000613}
614
Kuowei Li450f5402025-02-26 14:25:28 +0800615binder_status_t Module::dump(int fd, const char** args, uint32_t numArgs) {
616 for (const auto& portConfig : getConfig().portConfigs) {
617 if (portConfig.ext.getTag() == AudioPortExt::Tag::mix) {
618 getStreams().dump(portConfig.id, fd, args, numArgs);
619 }
620 }
621 return STATUS_OK;
622}
623
Mikhail Naganov00603d12022-05-02 22:52:13 +0000624ndk::ScopedAStatus Module::setModuleDebug(
625 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700626 LOG(DEBUG) << __func__ << ": " << mType << ": old flags:" << mDebug.toString()
Mikhail Naganov00603d12022-05-02 22:52:13 +0000627 << ", new flags: " << in_debug.toString();
628 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
629 !mConnectedDevicePorts.empty()) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700630 LOG(ERROR) << __func__ << ": " << mType
Jaideep Sharma559a4912024-03-07 10:05:51 +0530631 << ": attempting to change device connections simulation while "
632 "having external "
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700633 << "devices connected";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000634 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
635 }
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000636 if (in_debug.streamTransientStateDelayMs < 0) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700637 LOG(ERROR) << __func__ << ": " << mType << ": streamTransientStateDelayMs is negative: "
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000638 << in_debug.streamTransientStateDelayMs;
639 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
640 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000641 mDebug = in_debug;
642 return ndk::ScopedAStatus::ok();
643}
644
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000645ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700646 *_aidl_return = nullptr;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530647 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000648 return ndk::ScopedAStatus::ok();
649}
650
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000651ndk::ScopedAStatus Module::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700652 *_aidl_return = nullptr;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530653 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000654 return ndk::ScopedAStatus::ok();
655}
656
Mikhail Naganov7499a002023-02-27 18:51:44 -0800657ndk::ScopedAStatus Module::getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700658 *_aidl_return = nullptr;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530659 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
Mikhail Naganov7499a002023-02-27 18:51:44 -0800660 return ndk::ScopedAStatus::ok();
661}
662
Mikhail Naganovb5647da2023-03-06 14:37:38 -0800663ndk::ScopedAStatus Module::getBluetoothLe(std::shared_ptr<IBluetoothLe>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700664 *_aidl_return = nullptr;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530665 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
Mikhail Naganovb5647da2023-03-06 14:37:38 -0800666 return ndk::ScopedAStatus::ok();
667}
668
Mikhail Naganov00603d12022-05-02 22:52:13 +0000669ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
670 AudioPort* _aidl_return) {
671 const int32_t templateId = in_templateIdAndAdditionalData.id;
672 auto& ports = getConfig().ports;
673 AudioPort connectedPort;
674 { // Scope the template port so that we don't accidentally modify it.
675 auto templateIt = findById<AudioPort>(ports, templateId);
676 if (templateIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530677 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId << " not found";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000678 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
679 }
680 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530681 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
682 << " is not a device port";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000683 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
684 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000685 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
686 if (templateDevicePort.device.type.connection.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530687 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
688 << " is permanently attached";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000689 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
690 }
Mikhail Naganovfcf980e2023-09-07 16:30:11 -0700691 if (mConnectedDevicePorts.find(templateId) != mConnectedDevicePorts.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530692 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
693 << " is a connected device port";
Mikhail Naganovfcf980e2023-09-07 16:30:11 -0700694 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
695 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000696 // Postpone id allocation until we ensure that there are no client errors.
697 connectedPort = *templateIt;
698 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
699 const auto& inputDevicePort =
700 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
701 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
702 connectedDevicePort.device.address = inputDevicePort.device.address;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530703 LOG(DEBUG) << __func__ << ": " << mType << ": device port " << connectedPort.id
704 << " device set to " << connectedDevicePort.device.toString();
Mikhail Naganov00603d12022-05-02 22:52:13 +0000705 // Check if there is already a connected port with for the same external device.
Jaideep Sharma559a4912024-03-07 10:05:51 +0530706
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700707 for (auto connectedPortPair : mConnectedDevicePorts) {
708 auto connectedPortIt = findById<AudioPort>(ports, connectedPortPair.first);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000709 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
710 connectedDevicePort.device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530711 LOG(ERROR) << __func__ << ": " << mType << ": device "
712 << connectedDevicePort.device.toString()
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700713 << " is already connected at the device port id "
714 << connectedPortPair.first;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000715 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
716 }
717 }
718 }
719
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700720 // Two main cases are considered with regard to the profiles of the connected device port:
721 //
722 // 1. If the template device port has dynamic profiles, and at least one routable mix
723 // port also has dynamic profiles, it means that after connecting the device, the
724 // connected device port must have profiles populated with actual capabilities of
725 // the connected device, and dynamic of routable mix ports will be filled
726 // according to these capabilities. An example of this case is connection of an
727 // HDMI or USB device. For USB handled by ADSP, there can be mix ports with static
728 // profiles, and one dedicated mix port for "hi-fi" playback. The latter is left with
729 // dynamic profiles so that they can be populated with actual capabilities of
730 // the connected device.
731 //
732 // 2. If the template device port has dynamic profiles, while all routable mix ports
733 // have static profiles, it means that after connecting the device, the connected
734 // device port can be left with dynamic profiles, and profiles of mix ports are
735 // left untouched. An example of this case is connection of an analog wired
736 // headset, it should be treated in the same way as a speaker.
737 //
738 // Yet another possible case is when both the template device port and all routable
739 // mix ports have static profiles. This is allowed and handled correctly, however, it
740 // is not very practical, since these profiles are likely duplicates of each other.
741
742 std::vector<AudioRoute*> routesToMixPorts = getAudioRoutesForAudioPortImpl(templateId);
743 std::set<int32_t> routableMixPortIds = getRoutableAudioPortIds(templateId, &routesToMixPorts);
Mikhail Naganova92039a2023-12-20 14:27:22 -0800744 const int32_t nextPortId = getConfig().nextPortId++;
Mikhail Naganov55045b52023-10-24 17:03:50 -0700745 if (!mDebug.simulateDeviceConnections) {
746 // Even if the device port has static profiles, the HAL module might need to update
747 // them, or abort the connection process.
Mikhail Naganova92039a2023-12-20 14:27:22 -0800748 RETURN_STATUS_IF_ERROR(populateConnectedDevicePort(&connectedPort, nextPortId));
Mikhail Naganov55045b52023-10-24 17:03:50 -0700749 } else if (hasDynamicProfilesOnly(connectedPort.profiles)) {
750 auto& connectedProfiles = getConfig().connectedProfiles;
751 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
752 connectedProfilesIt != connectedProfiles.end()) {
753 connectedPort.profiles = connectedProfilesIt->second;
Mikhail Naganovfcf980e2023-09-07 16:30:11 -0700754 }
Mikhail Naganov55045b52023-10-24 17:03:50 -0700755 }
756 if (hasDynamicProfilesOnly(connectedPort.profiles)) {
757 // Possible case 2. Check if all routable mix ports have static profiles.
758 if (auto dynamicMixPortIt = std::find_if(ports.begin(), ports.end(),
759 [&routableMixPortIds](const auto& p) {
760 return routableMixPortIds.count(p.id) > 0 &&
761 hasDynamicProfilesOnly(p.profiles);
762 });
763 dynamicMixPortIt != ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530764 LOG(ERROR) << __func__ << ": " << mType
765 << ": connected port only has dynamic profiles after connecting "
Mikhail Naganov55045b52023-10-24 17:03:50 -0700766 << "external device " << connectedPort.toString() << ", and there exist "
767 << "a routable mix port with dynamic profiles: "
768 << dynamicMixPortIt->toString();
769 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530770 }
771 }
772
Mikhail Naganova92039a2023-12-20 14:27:22 -0800773 connectedPort.id = nextPortId;
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700774 auto [connectedPortsIt, _] =
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700775 mConnectedDevicePorts.insert(std::pair(connectedPort.id, std::set<int32_t>()));
Jaideep Sharma559a4912024-03-07 10:05:51 +0530776 LOG(DEBUG) << __func__ << ": " << mType << ": template port " << templateId
777 << " external device connected, "
Mikhail Naganov00603d12022-05-02 22:52:13 +0000778 << "connected port ID " << connectedPort.id;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000779 ports.push_back(connectedPort);
jiabin783c48b2023-02-28 18:28:06 +0000780 onExternalDeviceConnectionChanged(connectedPort, true /*connected*/);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000781
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700782 // For routes where the template port is a source, add the connected port to sources,
783 // otherwise, create a new route by copying from the route for the template port.
Mikhail Naganov00603d12022-05-02 22:52:13 +0000784 std::vector<AudioRoute> newRoutes;
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700785 for (AudioRoute* r : routesToMixPorts) {
786 if (r->sinkPortId == templateId) {
787 newRoutes.push_back(AudioRoute{.sourcePortIds = r->sourcePortIds,
788 .sinkPortId = connectedPort.id,
789 .isExclusive = r->isExclusive});
Mikhail Naganov00603d12022-05-02 22:52:13 +0000790 } else {
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700791 r->sourcePortIds.push_back(connectedPort.id);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000792 }
793 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700794 auto& routes = getConfig().routes;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000795 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
796
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700797 if (!hasDynamicProfilesOnly(connectedPort.profiles) && !routableMixPortIds.empty()) {
798 // Note: this is a simplistic approach assuming that a mix port can only be populated
799 // from a single device port. Implementing support for stuffing dynamic profiles with
800 // a superset of all profiles from all routable dynamic device ports would be more involved.
801 for (auto& port : ports) {
802 if (routableMixPortIds.count(port.id) == 0) continue;
803 if (hasDynamicProfilesOnly(port.profiles)) {
804 port.profiles = connectedPort.profiles;
805 connectedPortsIt->second.insert(port.id);
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700806 } else {
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700807 // Check if profiles are not all dynamic because they were populated by
808 // a previous connection. Otherwise, it means that they are actually static.
809 for (const auto& cp : mConnectedDevicePorts) {
810 if (cp.second.count(port.id) > 0) {
811 connectedPortsIt->second.insert(port.id);
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700812 break;
813 }
814 }
815 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700816 }
817 }
818 *_aidl_return = std::move(connectedPort);
819
Mikhail Naganov00603d12022-05-02 22:52:13 +0000820 return ndk::ScopedAStatus::ok();
821}
822
823ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
824 auto& ports = getConfig().ports;
825 auto portIt = findById<AudioPort>(ports, in_portId);
826 if (portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530827 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000828 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
829 }
830 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530831 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
832 << " is not a device port";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000833 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
834 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700835 auto connectedPortsIt = mConnectedDevicePorts.find(in_portId);
836 if (connectedPortsIt == mConnectedDevicePorts.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530837 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
838 << " is not a connected device port";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000839 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
840 }
841 auto& configs = getConfig().portConfigs;
842 auto& initials = getConfig().initialConfigs;
843 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
844 if (config.portId == in_portId) {
845 // Check if the configuration was provided by the client.
846 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
847 return initialIt == initials.end() || config != *initialIt;
848 }
849 return false;
850 });
851 if (configIt != configs.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530852 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
853 << " has a non-default config with id " << configIt->id;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000854 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
855 }
jiabin783c48b2023-02-28 18:28:06 +0000856 onExternalDeviceConnectionChanged(*portIt, false /*connected*/);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000857 ports.erase(portIt);
Jaideep Sharma559a4912024-03-07 10:05:51 +0530858 LOG(DEBUG) << __func__ << ": " << mType << ": connected device port " << in_portId
859 << " released";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000860
861 auto& routes = getConfig().routes;
862 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
863 if (routesIt->sinkPortId == in_portId) {
864 routesIt = routes.erase(routesIt);
865 } else {
866 // Note: the list of sourcePortIds can't become empty because there must
867 // be the id of the template port in the route.
868 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
869 ++routesIt;
870 }
871 }
872
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700873 // Clear profiles for mix ports that are not connected to any other ports.
874 std::set<int32_t> mixPortsToClear = std::move(connectedPortsIt->second);
875 mConnectedDevicePorts.erase(connectedPortsIt);
876 for (const auto& connectedPort : mConnectedDevicePorts) {
877 for (int32_t mixPortId : connectedPort.second) {
878 mixPortsToClear.erase(mixPortId);
879 }
880 }
881 for (int32_t mixPortId : mixPortsToClear) {
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700882 auto mixPortIt = findById<AudioPort>(ports, mixPortId);
883 if (mixPortIt != ports.end()) {
884 mixPortIt->profiles = {};
885 }
886 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700887
Mikhail Naganov00603d12022-05-02 22:52:13 +0000888 return ndk::ScopedAStatus::ok();
889}
890
jiabindd23b0e2023-12-11 19:10:05 +0000891ndk::ScopedAStatus Module::prepareToDisconnectExternalDevice(int32_t in_portId) {
892 auto& ports = getConfig().ports;
893 auto portIt = findById<AudioPort>(ports, in_portId);
894 if (portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530895 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
jiabindd23b0e2023-12-11 19:10:05 +0000896 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
897 }
898 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530899 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
900 << " is not a device port";
jiabindd23b0e2023-12-11 19:10:05 +0000901 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
902 }
903 auto connectedPortsIt = mConnectedDevicePorts.find(in_portId);
904 if (connectedPortsIt == mConnectedDevicePorts.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530905 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
906 << " is not a connected device port";
jiabindd23b0e2023-12-11 19:10:05 +0000907 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
908 }
909
910 onPrepareToDisconnectExternalDevice(*portIt);
911
912 return ndk::ScopedAStatus::ok();
913}
914
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000915ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
916 *_aidl_return = getConfig().patches;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530917 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " patches";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000918 return ndk::ScopedAStatus::ok();
919}
920
921ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
922 auto& ports = getConfig().ports;
923 auto portIt = findById<AudioPort>(ports, in_portId);
924 if (portIt != ports.end()) {
925 *_aidl_return = *portIt;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530926 LOG(DEBUG) << __func__ << ": " << mType << ": returning port by id " << in_portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000927 return ndk::ScopedAStatus::ok();
928 }
Jaideep Sharma559a4912024-03-07 10:05:51 +0530929 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000930 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
931}
932
933ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
934 *_aidl_return = getConfig().portConfigs;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530935 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size()
936 << " port configs";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000937 return ndk::ScopedAStatus::ok();
938}
939
940ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
941 *_aidl_return = getConfig().ports;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530942 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " ports";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000943 return ndk::ScopedAStatus::ok();
944}
945
946ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
947 *_aidl_return = getConfig().routes;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530948 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " routes";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000949 return ndk::ScopedAStatus::ok();
950}
951
Mikhail Naganov00603d12022-05-02 22:52:13 +0000952ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
953 std::vector<AudioRoute>* _aidl_return) {
954 auto& ports = getConfig().ports;
955 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530956 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000957 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
958 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700959 std::vector<AudioRoute*> routes = getAudioRoutesForAudioPortImpl(in_portId);
960 std::transform(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
961 [](auto rptr) { return *rptr; });
Mikhail Naganov00603d12022-05-02 22:52:13 +0000962 return ndk::ScopedAStatus::ok();
963}
964
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000965ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
966 OpenInputStreamReturn* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530967 LOG(DEBUG) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
968 << ", buffer size " << in_args.bufferSizeFrames << " frames";
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000969 AudioPort* port = nullptr;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700970 RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000971 if (port->flags.getTag() != AudioIoFlags::Tag::input) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530972 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000973 << " does not correspond to an input mix port";
974 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
975 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000976 StreamContext context;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700977 RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
978 nullptr, nullptr, &context));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000979 context.fillDescriptor(&_aidl_return->desc);
Kuowei Li53a8d4d2024-06-24 14:35:07 +0800980 if (hasMmapFlag(context.getFlags())) {
981 RETURN_STATUS_IF_ERROR(createMmapBuffer(context, &_aidl_return->desc));
982 }
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000983 std::shared_ptr<StreamIn> stream;
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700984 RETURN_STATUS_IF_ERROR(createInputStream(std::move(context), in_args.sinkMetadata,
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +0000985 getMicrophoneInfos(), &stream));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000986 StreamWrapper streamWrapper(stream);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700987 if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
988 RETURN_STATUS_IF_ERROR(
989 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
990 }
Mikhail Naganovefb45bc2024-03-27 16:20:33 +0000991 auto streamBinder = streamWrapper.getBinder();
992 AIBinder_setMinSchedulerPolicy(streamBinder.get(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
993 AIBinder_setInheritRt(streamBinder.get(), true);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000994 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000995 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000996 return ndk::ScopedAStatus::ok();
997}
998
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000999ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
1000 OpenOutputStreamReturn* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301001 LOG(DEBUG) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
1002 << ", has offload info? " << (in_args.offloadInfo.has_value()) << ", buffer size "
1003 << in_args.bufferSizeFrames << " frames";
Mikhail Naganov6a4872d2022-06-15 21:39:04 +00001004 AudioPort* port = nullptr;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -07001005 RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +00001006 if (port->flags.getTag() != AudioIoFlags::Tag::output) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301007 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001008 << " does not correspond to an output mix port";
1009 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1010 }
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +00001011 const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
1012 AudioOutputFlags::COMPRESS_OFFLOAD);
1013 if (isOffload && !in_args.offloadInfo.has_value()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301014 LOG(ERROR) << __func__ << ": " << mType << ": port id " << port->id
Mikhail Naganov111e0ce2022-06-17 21:41:19 +00001015 << " has COMPRESS_OFFLOAD flag set, requires offload info";
1016 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1017 }
Mikhail Naganov30301a42022-09-13 01:20:45 +00001018 const bool isNonBlocking = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
1019 AudioOutputFlags::NON_BLOCKING);
1020 if (isNonBlocking && in_args.callback == nullptr) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301021 LOG(ERROR) << __func__ << ": " << mType << ": port id " << port->id
Mikhail Naganov30301a42022-09-13 01:20:45 +00001022 << " has NON_BLOCKING flag set, requires async callback";
1023 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1024 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001025 StreamContext context;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -07001026 RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
1027 isNonBlocking ? in_args.callback : nullptr,
1028 in_args.eventCallback, &context));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001029 context.fillDescriptor(&_aidl_return->desc);
Kuowei Li53a8d4d2024-06-24 14:35:07 +08001030 if (hasMmapFlag(context.getFlags())) {
1031 RETURN_STATUS_IF_ERROR(createMmapBuffer(context, &_aidl_return->desc));
1032 }
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001033 std::shared_ptr<StreamOut> stream;
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -07001034 RETURN_STATUS_IF_ERROR(createOutputStream(std::move(context), in_args.sourceMetadata,
Mikhail Naganov9d16a6a2023-06-26 17:21:04 -07001035 in_args.offloadInfo, &stream));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001036 StreamWrapper streamWrapper(stream);
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001037 if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
1038 RETURN_STATUS_IF_ERROR(
1039 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
1040 }
Mikhail Naganovefb45bc2024-03-27 16:20:33 +00001041 auto streamBinder = streamWrapper.getBinder();
1042 AIBinder_setMinSchedulerPolicy(streamBinder.get(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
1043 AIBinder_setInheritRt(streamBinder.get(), true);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001044 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +00001045 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001046 return ndk::ScopedAStatus::ok();
1047}
1048
Mikhail Naganov74927202022-12-19 16:37:14 +00001049ndk::ScopedAStatus Module::getSupportedPlaybackRateFactors(
1050 SupportedPlaybackRateFactors* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301051 LOG(DEBUG) << __func__ << ": " << mType;
Mikhail Naganov74927202022-12-19 16:37:14 +00001052 (void)_aidl_return;
1053 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1054}
1055
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001056ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301057 LOG(DEBUG) << __func__ << ": " << mType << ": requested patch " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001058 if (in_requested.sourcePortConfigIds.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301059 LOG(ERROR) << __func__ << ": " << mType << ": requested patch has empty sources list";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001060 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1061 }
1062 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301063 LOG(ERROR) << __func__ << ": " << mType
1064 << ": requested patch has duplicate ids in the sources list";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001065 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1066 }
1067 if (in_requested.sinkPortConfigIds.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301068 LOG(ERROR) << __func__ << ": " << mType << ": requested patch has empty sinks list";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001069 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1070 }
1071 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301072 LOG(ERROR) << __func__ << ": " << mType
1073 << ": requested patch has duplicate ids in the sinks list";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001074 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1075 }
1076
1077 auto& configs = getConfig().portConfigs;
1078 std::vector<int32_t> missingIds;
1079 auto sources =
1080 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
1081 if (!missingIds.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301082 LOG(ERROR) << __func__ << ": " << mType << ": following source port config ids not found: "
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001083 << ::android::internal::ToString(missingIds);
1084 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1085 }
1086 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
1087 if (!missingIds.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301088 LOG(ERROR) << __func__ << ": " << mType << ": following sink port config ids not found: "
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001089 << ::android::internal::ToString(missingIds);
1090 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1091 }
1092 // bool indicates whether a non-exclusive route is available.
1093 // If only an exclusive route is available, that means the patch can not be
1094 // established if there is any other patch which currently uses the sink port.
1095 std::map<int32_t, bool> allowedSinkPorts;
1096 auto& routes = getConfig().routes;
1097 for (auto src : sources) {
1098 for (const auto& r : routes) {
1099 const auto& srcs = r.sourcePortIds;
1100 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
1101 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
1102 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
1103 }
1104 }
1105 }
1106 }
1107 for (auto sink : sinks) {
1108 if (allowedSinkPorts.count(sink->portId) == 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301109 LOG(ERROR) << __func__ << ": " << mType << ": there is no route to the sink port id "
1110 << sink->portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001111 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1112 }
1113 }
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -07001114 RETURN_STATUS_IF_ERROR(checkAudioPatchEndpointsMatch(sources, sinks));
jiabin253bd322023-01-25 23:57:31 +00001115
Priyanka Advani (xWF)781f66a2024-12-05 22:51:28 +00001116 auto& patches = getConfig().patches;
1117 auto existing = patches.end();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001118 std::optional<decltype(mPatches)> patchesBackup;
Priyanka Advani (xWF)781f66a2024-12-05 22:51:28 +00001119 if (in_requested.id != 0) {
1120 existing = findById<AudioPatch>(patches, in_requested.id);
1121 if (existing != patches.end()) {
1122 patchesBackup = mPatches;
1123 cleanUpPatch(existing->id);
1124 } else {
1125 LOG(ERROR) << __func__ << ": " << mType << ": not found existing patch id "
1126 << in_requested.id;
1127 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1128 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001129 }
1130 // Validate the requested patch.
1131 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
1132 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301133 LOG(ERROR) << __func__ << ": " << mType << ": sink port id " << sinkPortId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001134 << "is exclusive and is already used by some other patch";
1135 if (patchesBackup.has_value()) {
1136 mPatches = std::move(*patchesBackup);
1137 }
1138 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1139 }
1140 }
Mikhail Naganov13501872023-10-18 16:15:46 -07001141 // Find the highest sample rate among mix port configs.
1142 std::map<int32_t, AudioPortConfig*> sampleRates;
1143 std::vector<AudioPortConfig*>& mixPortConfigs =
1144 sources[0]->ext.getTag() == AudioPortExt::mix ? sources : sinks;
1145 for (auto mix : mixPortConfigs) {
1146 sampleRates.emplace(mix->sampleRate.value().value, mix);
1147 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001148 *_aidl_return = in_requested;
Mikhail Naganov13501872023-10-18 16:15:46 -07001149 auto maxSampleRateIt = std::max_element(sampleRates.begin(), sampleRates.end());
1150 const int32_t latencyMs = getNominalLatencyMs(*(maxSampleRateIt->second));
Kuowei Li10a768a2024-12-09 17:44:40 +08001151 if (!calculateBufferSizeFrames(
1152 maxSampleRateIt->second->format.value(), latencyMs, maxSampleRateIt->first,
1153 &_aidl_return->minimumStreamBufferSizeFrames).isOk()) {
1154 if (patchesBackup.has_value()) {
1155 mPatches = std::move(*patchesBackup);
1156 }
1157 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1158 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +00001159 _aidl_return->latenciesMs.clear();
1160 _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
Mikhail Naganov13501872023-10-18 16:15:46 -07001161 _aidl_return->sinkPortConfigIds.size(), latencyMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001162 AudioPatch oldPatch{};
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001163 if (existing == patches.end()) {
1164 _aidl_return->id = getConfig().nextPatchId++;
1165 patches.push_back(*_aidl_return);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001166 } else {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001167 oldPatch = *existing;
Mikhail Naganovdc417732023-09-29 15:49:35 -07001168 *existing = *_aidl_return;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001169 }
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001170 patchesBackup = mPatches;
1171 registerPatch(*_aidl_return);
1172 if (auto status = updateStreamsConnectedState(oldPatch, *_aidl_return); !status.isOk()) {
1173 mPatches = std::move(*patchesBackup);
1174 if (existing == patches.end()) {
1175 patches.pop_back();
1176 } else {
1177 *existing = oldPatch;
1178 }
1179 return status;
1180 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001181
Jaideep Sharma559a4912024-03-07 10:05:51 +05301182 LOG(DEBUG) << __func__ << ": " << mType << ": " << (oldPatch.id == 0 ? "created" : "updated")
1183 << " patch " << _aidl_return->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001184 return ndk::ScopedAStatus::ok();
1185}
1186
1187ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
1188 AudioPortConfig* out_suggested, bool* _aidl_return) {
Mikhail Naganova92039a2023-12-20 14:27:22 -08001189 auto generate = [this](const AudioPort& port, AudioPortConfig* config) {
1190 return generateDefaultPortConfig(port, config);
1191 };
1192 return setAudioPortConfigImpl(in_requested, generate, out_suggested, _aidl_return);
1193}
1194
1195ndk::ScopedAStatus Module::setAudioPortConfigImpl(
1196 const AudioPortConfig& in_requested,
1197 const std::function<bool(const ::aidl::android::media::audio::common::AudioPort& port,
1198 ::aidl::android::media::audio::common::AudioPortConfig* config)>&
1199 fillPortConfig,
1200 AudioPortConfig* out_suggested, bool* applied) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301201 LOG(DEBUG) << __func__ << ": " << mType << ": requested " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001202 auto& configs = getConfig().portConfigs;
1203 auto existing = configs.end();
1204 if (in_requested.id != 0) {
1205 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
1206 existing == configs.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301207 LOG(ERROR) << __func__ << ": " << mType << ": existing port config id "
1208 << in_requested.id << " not found";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001209 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1210 }
1211 }
1212
1213 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
1214 if (portId == 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301215 LOG(ERROR) << __func__ << ": " << mType
1216 << ": requested port config does not specify portId";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001217 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1218 }
1219 auto& ports = getConfig().ports;
1220 auto portIt = findById<AudioPort>(ports, portId);
1221 if (portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301222 LOG(ERROR) << __func__ << ": " << mType
1223 << ": requested port config points to non-existent portId " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001224 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1225 }
1226 if (existing != configs.end()) {
1227 *out_suggested = *existing;
1228 } else {
1229 AudioPortConfig newConfig;
Mikhail Naganova92039a2023-12-20 14:27:22 -08001230 newConfig.portId = portIt->id;
1231 if (fillPortConfig(*portIt, &newConfig)) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001232 *out_suggested = newConfig;
1233 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301234 LOG(ERROR) << __func__ << ": " << mType
1235 << ": unable generate a default config for port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001236 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1237 }
1238 }
1239 // From this moment, 'out_suggested' is either an existing port config,
1240 // or a new generated config. Now attempt to update it according to the specified
1241 // fields of 'in_requested'.
1242
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001243 // Device ports with only dynamic profiles are used for devices that are connected via ADSP,
1244 // which takes care of their actual configuration automatically.
1245 const bool allowDynamicConfig = portIt->ext.getTag() == AudioPortExt::device &&
1246 hasDynamicProfilesOnly(portIt->profiles);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001247 bool requestedIsValid = true, requestedIsFullySpecified = true;
1248
1249 AudioIoFlags portFlags = portIt->flags;
1250 if (in_requested.flags.has_value()) {
1251 if (in_requested.flags.value() != portFlags) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301252 LOG(WARNING) << __func__ << ": " << mType << ": requested flags "
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001253 << in_requested.flags.value().toString() << " do not match port's "
1254 << portId << " flags " << portFlags.toString();
1255 requestedIsValid = false;
1256 }
1257 } else {
1258 requestedIsFullySpecified = false;
1259 }
1260
1261 AudioProfile portProfile;
1262 if (in_requested.format.has_value()) {
1263 const auto& format = in_requested.format.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001264 if ((format == AudioFormatDescription{} && allowDynamicConfig) ||
1265 findAudioProfile(*portIt, format, &portProfile)) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001266 out_suggested->format = format;
1267 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301268 LOG(WARNING) << __func__ << ": " << mType << ": requested format " << format.toString()
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001269 << " is not found in the profiles of port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001270 requestedIsValid = false;
1271 }
1272 } else {
1273 requestedIsFullySpecified = false;
1274 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001275 if (!(out_suggested->format.value() == AudioFormatDescription{} && allowDynamicConfig) &&
1276 !findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301277 LOG(ERROR) << __func__ << ": " << mType << ": port " << portId
1278 << " does not support format " << out_suggested->format.value().toString()
1279 << " anymore";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001280 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1281 }
1282
1283 if (in_requested.channelMask.has_value()) {
1284 const auto& channelMask = in_requested.channelMask.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001285 if ((channelMask == AudioChannelLayout{} && allowDynamicConfig) ||
1286 find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
1287 portProfile.channelMasks.end()) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001288 out_suggested->channelMask = channelMask;
1289 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301290 LOG(WARNING) << __func__ << ": " << mType << ": requested channel mask "
1291 << channelMask.toString() << " is not supported for the format "
1292 << portProfile.format.toString() << " by the port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001293 requestedIsValid = false;
1294 }
1295 } else {
1296 requestedIsFullySpecified = false;
1297 }
1298
1299 if (in_requested.sampleRate.has_value()) {
1300 const auto& sampleRate = in_requested.sampleRate.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001301 if ((sampleRate.value == 0 && allowDynamicConfig) ||
1302 find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001303 sampleRate.value) != portProfile.sampleRates.end()) {
1304 out_suggested->sampleRate = sampleRate;
1305 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301306 LOG(WARNING) << __func__ << ": " << mType << ": requested sample rate "
1307 << sampleRate.value << " is not supported for the format "
1308 << portProfile.format.toString() << " by the port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001309 requestedIsValid = false;
1310 }
1311 } else {
1312 requestedIsFullySpecified = false;
1313 }
1314
1315 if (in_requested.gain.has_value()) {
Weilin Xua33bb5e2024-10-02 17:16:42 +00001316 if (!setAudioPortConfigGain(*portIt, in_requested.gain.value())) {
1317 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1318 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001319 out_suggested->gain = in_requested.gain.value();
1320 }
1321
Mikhail Naganov248e9502023-02-21 16:32:40 -08001322 if (in_requested.ext.getTag() != AudioPortExt::Tag::unspecified) {
1323 if (in_requested.ext.getTag() == out_suggested->ext.getTag()) {
1324 if (out_suggested->ext.getTag() == AudioPortExt::Tag::mix) {
Mikhail Naganovb06a4922024-03-06 16:39:50 -08001325 // 'AudioMixPortExt.handle' and '.usecase' are set by the client,
1326 // copy from in_requested.
1327 const auto& src = in_requested.ext.get<AudioPortExt::Tag::mix>();
1328 auto& dst = out_suggested->ext.get<AudioPortExt::Tag::mix>();
1329 dst.handle = src.handle;
1330 dst.usecase = src.usecase;
Mikhail Naganov248e9502023-02-21 16:32:40 -08001331 }
1332 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301333 LOG(WARNING) << __func__ << ": " << mType << ": requested ext tag "
Mikhail Naganov248e9502023-02-21 16:32:40 -08001334 << toString(in_requested.ext.getTag()) << " do not match port's tag "
1335 << toString(out_suggested->ext.getTag());
1336 requestedIsValid = false;
1337 }
1338 }
1339
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001340 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
1341 out_suggested->id = getConfig().nextPortId++;
1342 configs.push_back(*out_suggested);
Mikhail Naganova92039a2023-12-20 14:27:22 -08001343 *applied = true;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301344 LOG(DEBUG) << __func__ << ": " << mType << ": created new port config "
1345 << out_suggested->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001346 } else if (existing != configs.end() && requestedIsValid) {
1347 *existing = *out_suggested;
Mikhail Naganova92039a2023-12-20 14:27:22 -08001348 *applied = true;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301349 LOG(DEBUG) << __func__ << ": " << mType << ": updated port config "
1350 << out_suggested->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001351 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301352 LOG(DEBUG) << __func__ << ": " << mType << ": not applied; existing config ? "
1353 << (existing != configs.end()) << "; requested is valid? " << requestedIsValid
1354 << ", fully specified? " << requestedIsFullySpecified;
Mikhail Naganova92039a2023-12-20 14:27:22 -08001355 *applied = false;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001356 }
1357 return ndk::ScopedAStatus::ok();
1358}
1359
Weilin Xua33bb5e2024-10-02 17:16:42 +00001360bool Module::setAudioPortConfigGain(const AudioPort& port, const AudioGainConfig& gainRequested) {
1361 auto& ports = getConfig().ports;
1362 if (gainRequested.index < 0 || gainRequested.index >= (int)port.gains.size()) {
1363 LOG(ERROR) << __func__ << ": gains for port " << port.id << " is undefined";
1364 return false;
1365 }
1366 int stepValue = port.gains[gainRequested.index].stepValue;
1367 if (stepValue == 0) {
1368 LOG(ERROR) << __func__ << ": port gain step value is 0";
1369 return false;
1370 }
1371 int minValue = port.gains[gainRequested.index].minValue;
1372 int maxValue = port.gains[gainRequested.index].maxValue;
1373 if (gainRequested.values[0] > maxValue || gainRequested.values[0] < minValue) {
1374 LOG(ERROR) << __func__ << ": gain value " << gainRequested.values[0]
1375 << " out of range of min and max gain config";
1376 return false;
1377 }
1378 int gainIndex = (gainRequested.values[0] - minValue) / stepValue;
1379 int totalSteps = (maxValue - minValue) / stepValue;
1380 if (totalSteps == 0) {
1381 LOG(ERROR) << __func__ << ": difference between port gain min value " << minValue
1382 << " and max value " << maxValue << " is less than step value " << stepValue;
1383 return false;
1384 }
1385 // Root-power quantities are used in curve:
1386 // 10^((minMb / 100 + (maxMb / 100 - minMb / 100) * gainIndex / totalSteps) / (10 * 2))
1387 // where 100 is the conversion from mB to dB, 10 comes from the log 10 conversion from power
1388 // ratios, and 2 means are the square of amplitude.
1389 float gain =
1390 pow(10, (minValue + (maxValue - minValue) * (gainIndex / (float)totalSteps)) / 2000);
1391 if (gain < 0) {
1392 LOG(ERROR) << __func__ << ": gain " << gain << " is less than 0";
1393 return false;
1394 }
1395 for (const auto& route : getConfig().routes) {
1396 if (route.sinkPortId != port.id) {
1397 continue;
1398 }
1399 for (const auto sourcePortId : route.sourcePortIds) {
1400 mStreams.setGain(sourcePortId, gain);
1401 }
1402 }
1403 return true;
1404}
1405
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001406ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
1407 auto& patches = getConfig().patches;
1408 auto patchIt = findById<AudioPatch>(patches, in_patchId);
1409 if (patchIt != patches.end()) {
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001410 auto patchesBackup = mPatches;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001411 cleanUpPatch(patchIt->id);
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001412 if (auto status = updateStreamsConnectedState(*patchIt, AudioPatch{}); !status.isOk()) {
1413 mPatches = std::move(patchesBackup);
1414 return status;
1415 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001416 patches.erase(patchIt);
Jaideep Sharma559a4912024-03-07 10:05:51 +05301417 LOG(DEBUG) << __func__ << ": " << mType << ": erased patch " << in_patchId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001418 return ndk::ScopedAStatus::ok();
1419 }
Jaideep Sharma559a4912024-03-07 10:05:51 +05301420 LOG(ERROR) << __func__ << ": " << mType << ": patch id " << in_patchId << " not found";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001421 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1422}
1423
1424ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
1425 auto& configs = getConfig().portConfigs;
1426 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
1427 if (configIt != configs.end()) {
1428 if (mStreams.count(in_portConfigId) != 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301429 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001430 << " has a stream opened on it";
1431 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1432 }
1433 auto patchIt = mPatches.find(in_portConfigId);
1434 if (patchIt != mPatches.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301435 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001436 << " is used by the patch with id " << patchIt->second;
1437 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1438 }
1439 auto& initials = getConfig().initialConfigs;
1440 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
1441 if (initialIt == initials.end()) {
1442 configs.erase(configIt);
Jaideep Sharma559a4912024-03-07 10:05:51 +05301443 LOG(DEBUG) << __func__ << ": " << mType << ": erased port config " << in_portConfigId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001444 } else if (*configIt != *initialIt) {
1445 *configIt = *initialIt;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301446 LOG(DEBUG) << __func__ << ": " << mType << ": reset port config " << in_portConfigId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001447 }
1448 return ndk::ScopedAStatus::ok();
1449 }
Jaideep Sharma559a4912024-03-07 10:05:51 +05301450 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
1451 << " not found";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001452 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1453}
1454
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001455ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) {
1456 *_aidl_return = mMasterMute;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301457 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001458 return ndk::ScopedAStatus::ok();
1459}
1460
1461ndk::ScopedAStatus Module::setMasterMute(bool in_mute) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301462 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_mute;
jiabin783c48b2023-02-28 18:28:06 +00001463 auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1464 : onMasterMuteChanged(in_mute);
1465 if (result.isOk()) {
1466 mMasterMute = in_mute;
1467 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301468 LOG(ERROR) << __func__ << ": " << mType << ": failed calling onMasterMuteChanged("
1469 << in_mute << "), error=" << result;
jiabin783c48b2023-02-28 18:28:06 +00001470 // Reset master mute if it failed.
1471 onMasterMuteChanged(mMasterMute);
1472 }
Mikhail Naganov55045b52023-10-24 17:03:50 -07001473 return result;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001474}
1475
1476ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) {
1477 *_aidl_return = mMasterVolume;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301478 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001479 return ndk::ScopedAStatus::ok();
1480}
1481
1482ndk::ScopedAStatus Module::setMasterVolume(float in_volume) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301483 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_volume;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001484 if (in_volume >= 0.0f && in_volume <= 1.0f) {
jiabin783c48b2023-02-28 18:28:06 +00001485 auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1486 : onMasterVolumeChanged(in_volume);
1487 if (result.isOk()) {
1488 mMasterVolume = in_volume;
1489 } else {
1490 // Reset master volume if it failed.
Jaideep Sharma559a4912024-03-07 10:05:51 +05301491 LOG(ERROR) << __func__ << ": " << mType << ": failed calling onMasterVolumeChanged("
1492 << in_volume << "), error=" << result;
jiabin783c48b2023-02-28 18:28:06 +00001493 onMasterVolumeChanged(mMasterVolume);
1494 }
Mikhail Naganov55045b52023-10-24 17:03:50 -07001495 return result;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001496 }
Jaideep Sharma559a4912024-03-07 10:05:51 +05301497 LOG(ERROR) << __func__ << ": " << mType << ": invalid master volume value: " << in_volume;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001498 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1499}
1500
1501ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) {
1502 *_aidl_return = mMicMute;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301503 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001504 return ndk::ScopedAStatus::ok();
1505}
1506
1507ndk::ScopedAStatus Module::setMicMute(bool in_mute) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301508 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_mute;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001509 mMicMute = in_mute;
1510 return ndk::ScopedAStatus::ok();
1511}
1512
Mikhail Naganovef6bc742022-10-06 00:14:19 +00001513ndk::ScopedAStatus Module::getMicrophones(std::vector<MicrophoneInfo>* _aidl_return) {
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +00001514 *_aidl_return = getMicrophoneInfos();
Jaideep Sharma559a4912024-03-07 10:05:51 +05301515 LOG(DEBUG) << __func__ << ": " << mType << ": returning "
1516 << ::android::internal::ToString(*_aidl_return);
Mikhail Naganovef6bc742022-10-06 00:14:19 +00001517 return ndk::ScopedAStatus::ok();
1518}
1519
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001520ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) {
Mikhail Naganov04ae8222023-01-11 15:48:10 -08001521 if (!isValidAudioMode(in_mode)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301522 LOG(ERROR) << __func__ << ": " << mType << ": invalid mode " << toString(in_mode);
Mikhail Naganov04ae8222023-01-11 15:48:10 -08001523 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1524 }
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001525 // No checks for supported audio modes here, it's an informative notification.
Jaideep Sharma559a4912024-03-07 10:05:51 +05301526 LOG(DEBUG) << __func__ << ": " << mType << ": " << toString(in_mode);
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001527 return ndk::ScopedAStatus::ok();
1528}
1529
1530ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301531 LOG(DEBUG) << __func__ << ": " << mType << ": " << toString(in_rotation);
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001532 return ndk::ScopedAStatus::ok();
1533}
1534
1535ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301536 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_isTurnedOn;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001537 return ndk::ScopedAStatus::ok();
1538}
1539
Vlad Popa83a6d822022-11-07 13:53:57 +01001540ndk::ScopedAStatus Module::getSoundDose(std::shared_ptr<ISoundDose>* _aidl_return) {
Mikhail Naganov7499a002023-02-27 18:51:44 -08001541 if (!mSoundDose) {
Vlad Popa2afbd1e2022-12-28 17:04:58 +01001542 mSoundDose = ndk::SharedRefBase::make<sounddose::SoundDose>();
Vlad Popa943b7e22022-12-08 14:24:12 +01001543 }
Mikhail Naganov780fefb2023-07-21 17:01:38 -07001544 *_aidl_return = mSoundDose.getInstance();
Jaideep Sharma559a4912024-03-07 10:05:51 +05301545 LOG(DEBUG) << __func__ << ": " << mType
1546 << ": returning instance of ISoundDose: " << _aidl_return->get();
Vlad Popa83a6d822022-11-07 13:53:57 +01001547 return ndk::ScopedAStatus::ok();
1548}
1549
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001550ndk::ScopedAStatus Module::generateHwAvSyncId(int32_t* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301551 LOG(DEBUG) << __func__ << ": " << mType;
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001552 (void)_aidl_return;
1553 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1554}
1555
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001556const std::string Module::VendorDebug::kForceTransientBurstName = "aosp.forceTransientBurst";
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001557const std::string Module::VendorDebug::kForceSynchronousDrainName = "aosp.forceSynchronousDrain";
Mikhail Naganov1b8f65d2025-03-03 13:59:44 -08001558const std::string Module::kClipTransitionSupportName = "aosp.clipTransitionSupport";
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001559
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001560ndk::ScopedAStatus Module::getVendorParameters(const std::vector<std::string>& in_ids,
1561 std::vector<VendorParameter>* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301562 LOG(VERBOSE) << __func__ << ": " << mType << ": id count: " << in_ids.size();
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001563 bool allParametersKnown = true;
1564 for (const auto& id : in_ids) {
1565 if (id == VendorDebug::kForceTransientBurstName) {
1566 VendorParameter forceTransientBurst{.id = id};
1567 forceTransientBurst.ext.setParcelable(Boolean{mVendorDebug.forceTransientBurst});
1568 _aidl_return->push_back(std::move(forceTransientBurst));
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001569 } else if (id == VendorDebug::kForceSynchronousDrainName) {
1570 VendorParameter forceSynchronousDrain{.id = id};
1571 forceSynchronousDrain.ext.setParcelable(Boolean{mVendorDebug.forceSynchronousDrain});
1572 _aidl_return->push_back(std::move(forceSynchronousDrain));
Mikhail Naganov1b8f65d2025-03-03 13:59:44 -08001573 } else if (id == kClipTransitionSupportName) {
1574 VendorParameter clipTransitionSupport{.id = id};
1575 clipTransitionSupport.ext.setParcelable(Boolean{true});
1576 _aidl_return->push_back(std::move(clipTransitionSupport));
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001577 } else {
1578 allParametersKnown = false;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301579 LOG(VERBOSE) << __func__ << ": " << mType << ": unrecognized parameter \"" << id << "\"";
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001580 }
1581 }
1582 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1583 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001584}
1585
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001586namespace {
1587
1588template <typename W>
1589bool extractParameter(const VendorParameter& p, decltype(W::value)* v) {
1590 std::optional<W> value;
1591 binder_status_t result = p.ext.getParcelable(&value);
1592 if (result == STATUS_OK && value.has_value()) {
1593 *v = value.value().value;
1594 return true;
1595 }
1596 LOG(ERROR) << __func__ << ": failed to read the value of the parameter \"" << p.id
1597 << "\": " << result;
1598 return false;
1599}
1600
1601} // namespace
1602
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001603ndk::ScopedAStatus Module::setVendorParameters(const std::vector<VendorParameter>& in_parameters,
1604 bool in_async) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301605 LOG(VERBOSE) << __func__ << ": " << mType << ": parameter count " << in_parameters.size()
1606 << ", async: " << in_async;
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001607 bool allParametersKnown = true;
1608 for (const auto& p : in_parameters) {
1609 if (p.id == VendorDebug::kForceTransientBurstName) {
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001610 if (!extractParameter<Boolean>(p, &mVendorDebug.forceTransientBurst)) {
1611 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1612 }
1613 } else if (p.id == VendorDebug::kForceSynchronousDrainName) {
1614 if (!extractParameter<Boolean>(p, &mVendorDebug.forceSynchronousDrain)) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001615 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1616 }
1617 } else {
1618 allParametersKnown = false;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301619 LOG(VERBOSE) << __func__ << ": " << mType << ": unrecognized parameter \"" << p.id
1620 << "\"";
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001621 }
1622 }
1623 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1624 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001625}
1626
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001627ndk::ScopedAStatus Module::addDeviceEffect(
1628 int32_t in_portConfigId,
1629 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1630 if (in_effect == nullptr) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301631 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1632 << ", null effect";
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001633 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301634 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1635 << ", effect Binder " << in_effect->asBinder().get();
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001636 }
1637 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1638}
1639
1640ndk::ScopedAStatus Module::removeDeviceEffect(
1641 int32_t in_portConfigId,
1642 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1643 if (in_effect == nullptr) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301644 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1645 << ", null effect";
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001646 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301647 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1648 << ", effect Binder " << in_effect->asBinder().get();
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001649 }
1650 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1651}
1652
jiabin9a8e6862023-01-12 23:06:37 +00001653ndk::ScopedAStatus Module::getMmapPolicyInfos(AudioMMapPolicyType mmapPolicyType,
1654 std::vector<AudioMMapPolicyInfo>* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301655 LOG(DEBUG) << __func__ << ": " << mType << ": mmap policy type " << toString(mmapPolicyType);
jiabin9a8e6862023-01-12 23:06:37 +00001656 std::set<int32_t> mmapSinks;
1657 std::set<int32_t> mmapSources;
1658 auto& ports = getConfig().ports;
1659 for (const auto& port : ports) {
1660 if (port.flags.getTag() == AudioIoFlags::Tag::input &&
1661 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::input>(),
1662 AudioInputFlags::MMAP_NOIRQ)) {
1663 mmapSinks.insert(port.id);
1664 } else if (port.flags.getTag() == AudioIoFlags::Tag::output &&
1665 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
1666 AudioOutputFlags::MMAP_NOIRQ)) {
1667 mmapSources.insert(port.id);
1668 }
1669 }
Mikhail Naganov85064912023-09-26 17:10:08 -07001670 if (mmapSources.empty() && mmapSinks.empty()) {
1671 AudioMMapPolicyInfo never;
1672 never.mmapPolicy = AudioMMapPolicy::NEVER;
1673 _aidl_return->push_back(never);
1674 return ndk::ScopedAStatus::ok();
1675 }
jiabin9a8e6862023-01-12 23:06:37 +00001676 for (const auto& route : getConfig().routes) {
1677 if (mmapSinks.count(route.sinkPortId) != 0) {
1678 // The sink is a mix port, add the sources if they are device ports.
1679 for (int sourcePortId : route.sourcePortIds) {
1680 auto sourcePortIt = findById<AudioPort>(ports, sourcePortId);
1681 if (sourcePortIt == ports.end()) {
1682 // This must not happen
Jaideep Sharma559a4912024-03-07 10:05:51 +05301683 LOG(ERROR) << __func__ << ": " << mType << ": port id " << sourcePortId
1684 << " cannot be found";
jiabin9a8e6862023-01-12 23:06:37 +00001685 continue;
1686 }
1687 if (sourcePortIt->ext.getTag() != AudioPortExt::Tag::device) {
1688 // The source is not a device port, skip
1689 continue;
1690 }
1691 AudioMMapPolicyInfo policyInfo;
1692 policyInfo.device = sourcePortIt->ext.get<AudioPortExt::Tag::device>().device;
1693 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1694 // default implementation.
1695 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1696 _aidl_return->push_back(policyInfo);
1697 }
1698 } else {
1699 auto sinkPortIt = findById<AudioPort>(ports, route.sinkPortId);
1700 if (sinkPortIt == ports.end()) {
1701 // This must not happen
Jaideep Sharma559a4912024-03-07 10:05:51 +05301702 LOG(ERROR) << __func__ << ": " << mType << ": port id " << route.sinkPortId
1703 << " cannot be found";
jiabin9a8e6862023-01-12 23:06:37 +00001704 continue;
1705 }
1706 if (sinkPortIt->ext.getTag() != AudioPortExt::Tag::device) {
1707 // The sink is not a device port, skip
1708 continue;
1709 }
1710 if (count_any(mmapSources, route.sourcePortIds)) {
1711 AudioMMapPolicyInfo policyInfo;
1712 policyInfo.device = sinkPortIt->ext.get<AudioPortExt::Tag::device>().device;
1713 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1714 // default implementation.
1715 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1716 _aidl_return->push_back(policyInfo);
1717 }
1718 }
1719 }
1720 return ndk::ScopedAStatus::ok();
1721}
1722
Eric Laurente2432ea2023-01-12 17:47:31 +01001723ndk::ScopedAStatus Module::supportsVariableLatency(bool* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301724 LOG(DEBUG) << __func__ << ": " << mType;
Eric Laurente2432ea2023-01-12 17:47:31 +01001725 *_aidl_return = false;
1726 return ndk::ScopedAStatus::ok();
1727}
1728
jiabinb76981e2023-01-18 00:58:30 +00001729ndk::ScopedAStatus Module::getAAudioMixerBurstCount(int32_t* _aidl_return) {
1730 if (!isMmapSupported()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301731 LOG(DEBUG) << __func__ << ": " << mType << ": mmap is not supported ";
jiabinb76981e2023-01-18 00:58:30 +00001732 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1733 }
1734 *_aidl_return = DEFAULT_AAUDIO_MIXER_BURST_COUNT;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301735 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
jiabinb76981e2023-01-18 00:58:30 +00001736 return ndk::ScopedAStatus::ok();
1737}
1738
1739ndk::ScopedAStatus Module::getAAudioHardwareBurstMinUsec(int32_t* _aidl_return) {
1740 if (!isMmapSupported()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301741 LOG(DEBUG) << __func__ << ": " << mType << ": mmap is not supported ";
jiabinb76981e2023-01-18 00:58:30 +00001742 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1743 }
1744 *_aidl_return = DEFAULT_AAUDIO_HARDWARE_BURST_MIN_DURATION_US;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301745 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
jiabinb76981e2023-01-18 00:58:30 +00001746 return ndk::ScopedAStatus::ok();
1747}
1748
1749bool Module::isMmapSupported() {
1750 if (mIsMmapSupported.has_value()) {
1751 return mIsMmapSupported.value();
1752 }
1753 std::vector<AudioMMapPolicyInfo> mmapPolicyInfos;
1754 if (!getMmapPolicyInfos(AudioMMapPolicyType::DEFAULT, &mmapPolicyInfos).isOk()) {
1755 mIsMmapSupported = false;
1756 } else {
1757 mIsMmapSupported =
1758 std::find_if(mmapPolicyInfos.begin(), mmapPolicyInfos.end(), [](const auto& info) {
1759 return info.mmapPolicy == AudioMMapPolicy::AUTO ||
1760 info.mmapPolicy == AudioMMapPolicy::ALWAYS;
1761 }) != mmapPolicyInfos.end();
1762 }
1763 return mIsMmapSupported.value();
1764}
1765
Mikhail Naganova92039a2023-12-20 14:27:22 -08001766ndk::ScopedAStatus Module::populateConnectedDevicePort(AudioPort* audioPort, int32_t) {
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001767 if (audioPort->ext.getTag() != AudioPortExt::device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301768 LOG(ERROR) << __func__ << ": " << mType << ": not a device port: " << audioPort->toString();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001769 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1770 }
1771 const auto& devicePort = audioPort->ext.get<AudioPortExt::device>();
1772 if (!devicePort.device.type.connection.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301773 LOG(ERROR) << __func__ << ": " << mType << ": module implementation must override "
1774 "'populateConnectedDevicePort' "
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001775 << "to handle connection of external devices.";
1776 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1777 }
Jaideep Sharma559a4912024-03-07 10:05:51 +05301778 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
jiabin253bd322023-01-25 23:57:31 +00001779 return ndk::ScopedAStatus::ok();
1780}
1781
1782ndk::ScopedAStatus Module::checkAudioPatchEndpointsMatch(
1783 const std::vector<AudioPortConfig*>& sources __unused,
1784 const std::vector<AudioPortConfig*>& sinks __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301785 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
jiabin253bd322023-01-25 23:57:31 +00001786 return ndk::ScopedAStatus::ok();
1787}
1788
jiabin783c48b2023-02-28 18:28:06 +00001789void Module::onExternalDeviceConnectionChanged(
1790 const ::aidl::android::media::audio::common::AudioPort& audioPort __unused,
1791 bool connected __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301792 LOG(DEBUG) << __func__ << ": " << mType << ": do nothing and return";
jiabin783c48b2023-02-28 18:28:06 +00001793}
1794
jiabindd23b0e2023-12-11 19:10:05 +00001795void Module::onPrepareToDisconnectExternalDevice(
1796 const ::aidl::android::media::audio::common::AudioPort& audioPort __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301797 LOG(DEBUG) << __func__ << ": " << mType << ": do nothing and return";
jiabindd23b0e2023-12-11 19:10:05 +00001798}
1799
jiabin783c48b2023-02-28 18:28:06 +00001800ndk::ScopedAStatus Module::onMasterMuteChanged(bool mute __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301801 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
jiabin783c48b2023-02-28 18:28:06 +00001802 return ndk::ScopedAStatus::ok();
1803}
1804
1805ndk::ScopedAStatus Module::onMasterVolumeChanged(float volume __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301806 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
jiabin783c48b2023-02-28 18:28:06 +00001807 return ndk::ScopedAStatus::ok();
1808}
1809
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +00001810std::vector<MicrophoneInfo> Module::getMicrophoneInfos() {
1811 std::vector<MicrophoneInfo> result;
1812 Configuration& config = getConfig();
1813 for (const AudioPort& port : config.ports) {
1814 if (port.ext.getTag() == AudioPortExt::Tag::device) {
1815 const AudioDeviceType deviceType =
1816 port.ext.get<AudioPortExt::Tag::device>().device.type.type;
1817 if (deviceType == AudioDeviceType::IN_MICROPHONE ||
1818 deviceType == AudioDeviceType::IN_MICROPHONE_BACK) {
1819 // Placeholder values. Vendor implementations must populate MicrophoneInfo
1820 // accordingly based on their physical microphone parameters.
1821 result.push_back(MicrophoneInfo{
1822 .id = port.name,
1823 .device = port.ext.get<AudioPortExt::Tag::device>().device,
1824 .group = 0,
1825 .indexInTheGroup = 0,
1826 });
1827 }
1828 }
1829 }
1830 return result;
1831}
1832
Ram Mohan18f0d512023-07-01 00:47:09 +05301833ndk::ScopedAStatus Module::bluetoothParametersUpdated() {
1834 return mStreams.bluetoothParametersUpdated();
1835}
1836
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001837} // namespace aidl::android::hardware::audio::core