blob: 0d6151e65b1506f7d7e937e38105fa9563801b8e [file] [log] [blame]
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001/*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <algorithm>
18#include <set>
19
20#define LOG_TAG "AHAL_Module"
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000021#include <aidl/android/media/audio/common/AudioInputFlags.h>
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000022#include <aidl/android/media/audio/common/AudioOutputFlags.h>
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -070023#include <android-base/logging.h>
24#include <android/binder_ibinder_platform.h>
25#include <error/expected_utils.h>
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000026
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +000027#include "core-impl/Configuration.h"
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000028#include "core-impl/Module.h"
Mikhail Naganovb03b5c42023-07-26 13:13:35 -070029#include "core-impl/ModuleBluetooth.h"
Mikhail Naganov521fc492023-07-11 17:24:08 -070030#include "core-impl/ModulePrimary.h"
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053031#include "core-impl/ModuleRemoteSubmix.h"
Mikhail Naganov521fc492023-07-11 17:24:08 -070032#include "core-impl/ModuleStub.h"
jiabin253bd322023-01-25 23:57:31 +000033#include "core-impl/ModuleUsb.h"
Vlad Popa943b7e22022-12-08 14:24:12 +010034#include "core-impl/SoundDose.h"
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000035#include "core-impl/utils.h"
36
Mikhail Naganov55045b52023-10-24 17:03:50 -070037using aidl::android::hardware::audio::common::frameCountFromDurationMs;
Mikhail Naganov872d4a62023-03-09 18:19:01 -080038using aidl::android::hardware::audio::common::getFrameSizeInBytes;
39using aidl::android::hardware::audio::common::isBitPositionFlagSet;
40using aidl::android::hardware::audio::common::isValidAudioMode;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000041using aidl::android::hardware::audio::common::SinkMetadata;
42using aidl::android::hardware::audio::common::SourceMetadata;
Vlad Popa2afbd1e2022-12-28 17:04:58 +010043using aidl::android::hardware::audio::core::sounddose::ISoundDose;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000044using aidl::android::media::audio::common::AudioChannelLayout;
Mikhail Naganovef6bc742022-10-06 00:14:19 +000045using aidl::android::media::audio::common::AudioDevice;
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +000046using aidl::android::media::audio::common::AudioDeviceType;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000047using aidl::android::media::audio::common::AudioFormatDescription;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000048using aidl::android::media::audio::common::AudioFormatType;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000049using aidl::android::media::audio::common::AudioInputFlags;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000050using aidl::android::media::audio::common::AudioIoFlags;
jiabin9a8e6862023-01-12 23:06:37 +000051using aidl::android::media::audio::common::AudioMMapPolicy;
52using aidl::android::media::audio::common::AudioMMapPolicyInfo;
53using aidl::android::media::audio::common::AudioMMapPolicyType;
Mikhail Naganov04ae8222023-01-11 15:48:10 -080054using aidl::android::media::audio::common::AudioMode;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000055using aidl::android::media::audio::common::AudioOffloadInfo;
56using aidl::android::media::audio::common::AudioOutputFlags;
57using aidl::android::media::audio::common::AudioPort;
58using aidl::android::media::audio::common::AudioPortConfig;
59using aidl::android::media::audio::common::AudioPortExt;
60using aidl::android::media::audio::common::AudioProfile;
Mikhail Naganov20047bc2023-01-05 20:16:07 +000061using aidl::android::media::audio::common::Boolean;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000062using aidl::android::media::audio::common::Int;
Mikhail Naganov6725ef52023-02-09 17:52:50 -080063using aidl::android::media::audio::common::MicrophoneInfo;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000064using aidl::android::media::audio::common::PcmType;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000065
66namespace aidl::android::hardware::audio::core {
67
68namespace {
69
Mikhail Naganov84bcc042023-10-05 17:36:57 -070070inline bool hasDynamicChannelMasks(const std::vector<AudioChannelLayout>& channelMasks) {
71 return channelMasks.empty() ||
72 std::all_of(channelMasks.begin(), channelMasks.end(),
73 [](const auto& channelMask) { return channelMask == AudioChannelLayout{}; });
74}
75
76inline bool hasDynamicFormat(const AudioFormatDescription& format) {
77 return format == AudioFormatDescription{};
78}
79
80inline bool hasDynamicSampleRates(const std::vector<int32_t>& sampleRates) {
81 return sampleRates.empty() ||
82 std::all_of(sampleRates.begin(), sampleRates.end(),
83 [](const auto& sampleRate) { return sampleRate == 0; });
84}
85
86inline bool isDynamicProfile(const AudioProfile& profile) {
87 return hasDynamicFormat(profile.format) || hasDynamicChannelMasks(profile.channelMasks) ||
88 hasDynamicSampleRates(profile.sampleRates);
89}
90
91bool hasDynamicProfilesOnly(const std::vector<AudioProfile>& profiles) {
92 if (profiles.empty()) return true;
93 return std::all_of(profiles.begin(), profiles.end(), isDynamicProfile);
94}
95
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000096bool findAudioProfile(const AudioPort& port, const AudioFormatDescription& format,
97 AudioProfile* profile) {
98 if (auto profilesIt =
99 find_if(port.profiles.begin(), port.profiles.end(),
100 [&format](const auto& profile) { return profile.format == format; });
101 profilesIt != port.profiles.end()) {
102 *profile = *profilesIt;
103 return true;
104 }
105 return false;
106}
Mikhail Naganov00603d12022-05-02 22:52:13 +0000107
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000108} // namespace
109
jiabin253bd322023-01-25 23:57:31 +0000110// static
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000111std::shared_ptr<Module> Module::createInstance(Type type, std::unique_ptr<Configuration>&& config) {
jiabin253bd322023-01-25 23:57:31 +0000112 switch (type) {
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530113 case Type::DEFAULT:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000114 return ndk::SharedRefBase::make<ModulePrimary>(std::move(config));
Mikhail Naganov521fc492023-07-11 17:24:08 -0700115 case Type::R_SUBMIX:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000116 return ndk::SharedRefBase::make<ModuleRemoteSubmix>(std::move(config));
Mikhail Naganov521fc492023-07-11 17:24:08 -0700117 case Type::STUB:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000118 return ndk::SharedRefBase::make<ModuleStub>(std::move(config));
Mikhail Naganov521fc492023-07-11 17:24:08 -0700119 case Type::USB:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000120 return ndk::SharedRefBase::make<ModuleUsb>(std::move(config));
Mikhail Naganovb03b5c42023-07-26 13:13:35 -0700121 case Type::BLUETOOTH:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000122 return ndk::SharedRefBase::make<ModuleBluetooth>(std::move(config));
jiabin253bd322023-01-25 23:57:31 +0000123 }
124}
125
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000126// static
127std::optional<Module::Type> Module::typeFromString(const std::string& type) {
128 if (type == "default")
129 return Module::Type::DEFAULT;
130 else if (type == "r_submix")
131 return Module::Type::R_SUBMIX;
132 else if (type == "stub")
133 return Module::Type::STUB;
134 else if (type == "usb")
135 return Module::Type::USB;
136 else if (type == "bluetooth")
137 return Module::Type::BLUETOOTH;
138 return {};
139}
140
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700141std::ostream& operator<<(std::ostream& os, Module::Type t) {
142 switch (t) {
143 case Module::Type::DEFAULT:
144 os << "default";
145 break;
146 case Module::Type::R_SUBMIX:
147 os << "r_submix";
148 break;
Mikhail Naganov521fc492023-07-11 17:24:08 -0700149 case Module::Type::STUB:
150 os << "stub";
151 break;
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700152 case Module::Type::USB:
153 os << "usb";
154 break;
Mikhail Naganovb03b5c42023-07-26 13:13:35 -0700155 case Module::Type::BLUETOOTH:
156 os << "bluetooth";
157 break;
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700158 }
159 return os;
160}
161
Lorena Torres-Huertaf7492512023-01-14 02:49:41 +0000162Module::Module(Type type, std::unique_ptr<Configuration>&& config)
163 : mType(type), mConfig(std::move(config)) {
164 populateConnectedProfiles();
165}
166
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000167void Module::cleanUpPatch(int32_t patchId) {
168 erase_all_values(mPatches, std::set<int32_t>{patchId});
169}
170
Mikhail Naganov8651b362023-01-06 23:15:27 +0000171ndk::ScopedAStatus Module::createStreamContext(
172 int32_t in_portConfigId, int64_t in_bufferSizeFrames,
173 std::shared_ptr<IStreamCallback> asyncCallback,
174 std::shared_ptr<IStreamOutEventCallback> outEventCallback, StreamContext* out_context) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000175 if (in_bufferSizeFrames <= 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530176 LOG(ERROR) << __func__ << ": " << mType << ": non-positive buffer size "
177 << in_bufferSizeFrames;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000178 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
179 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000180 auto& configs = getConfig().portConfigs;
181 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
Mikhail Naganova92039a2023-12-20 14:27:22 -0800182 const int32_t nominalLatencyMs = getNominalLatencyMs(*portConfigIt);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000183 // Since this is a private method, it is assumed that
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000184 // validity of the portConfigId has already been checked.
Mikhail Naganova92039a2023-12-20 14:27:22 -0800185 const int32_t minimumStreamBufferSizeFrames =
186 calculateBufferSizeFrames(nominalLatencyMs, portConfigIt->sampleRate.value().value);
Mikhail Naganov13501872023-10-18 16:15:46 -0700187 if (in_bufferSizeFrames < minimumStreamBufferSizeFrames) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530188 LOG(ERROR) << __func__ << ": " << mType << ": insufficient buffer size "
189 << in_bufferSizeFrames << ", must be at least " << minimumStreamBufferSizeFrames;
Mikhail Naganov13501872023-10-18 16:15:46 -0700190 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
191 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000192 const size_t frameSize =
193 getFrameSizeInBytes(portConfigIt->format.value(), portConfigIt->channelMask.value());
194 if (frameSize == 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530195 LOG(ERROR) << __func__ << ": " << mType
196 << ": could not calculate frame size for port config "
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000197 << portConfigIt->toString();
198 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
199 }
Jaideep Sharma559a4912024-03-07 10:05:51 +0530200 LOG(DEBUG) << __func__ << ": " << mType << ": frame size " << frameSize << " bytes";
Mikhail Naganovb511b8a2023-05-15 14:35:24 -0700201 if (frameSize > static_cast<size_t>(kMaximumStreamBufferSizeBytes / in_bufferSizeFrames)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530202 LOG(ERROR) << __func__ << ": " << mType << ": buffer size " << in_bufferSizeFrames
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000203 << " frames is too large, maximum size is "
204 << kMaximumStreamBufferSizeBytes / frameSize;
205 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
206 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000207 const auto& flags = portConfigIt->flags.value();
208 if ((flags.getTag() == AudioIoFlags::Tag::input &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000209 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::input>(),
210 AudioInputFlags::MMAP_NOIRQ)) ||
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000211 (flags.getTag() == AudioIoFlags::Tag::output &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000212 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::output>(),
213 AudioOutputFlags::MMAP_NOIRQ))) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000214 StreamContext::DebugParameters params{mDebug.streamTransientStateDelayMs,
Mikhail Naganov194daaa2023-01-05 22:34:20 +0000215 mVendorDebug.forceTransientBurst,
216 mVendorDebug.forceSynchronousDrain};
Vlad Popace338642023-09-21 18:54:03 -0700217 std::shared_ptr<ISoundDose> soundDose;
218 if (!getSoundDose(&soundDose).isOk()) {
219 LOG(ERROR) << __func__ << ": could not create sound dose instance";
220 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
221 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000222 StreamContext temp(
223 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
224 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
Mikhail Naganov13501872023-10-18 16:15:46 -0700225 portConfigIt->format.value(), portConfigIt->channelMask.value(),
Mikhail Naganova92039a2023-12-20 14:27:22 -0800226 portConfigIt->sampleRate.value().value, flags, nominalLatencyMs,
Mikhail Naganovb42a69e2023-06-16 12:38:25 -0700227 portConfigIt->ext.get<AudioPortExt::mix>().handle,
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000228 std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames),
Vlad Popace338642023-09-21 18:54:03 -0700229 asyncCallback, outEventCallback, mSoundDose.getInstance(), params);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000230 if (temp.isValid()) {
231 *out_context = std::move(temp);
232 } else {
233 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
234 }
235 } else {
236 // TODO: Implement simulation of MMAP buffer allocation
237 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000238 return ndk::ScopedAStatus::ok();
239}
240
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000241std::vector<AudioDevice> Module::findConnectedDevices(int32_t portConfigId) {
242 std::vector<AudioDevice> result;
243 auto& ports = getConfig().ports;
244 auto portIds = portIdsFromPortConfigIds(findConnectedPortConfigIds(portConfigId));
245 for (auto it = portIds.begin(); it != portIds.end(); ++it) {
246 auto portIt = findById<AudioPort>(ports, *it);
247 if (portIt != ports.end() && portIt->ext.getTag() == AudioPortExt::Tag::device) {
248 result.push_back(portIt->ext.template get<AudioPortExt::Tag::device>().device);
249 }
250 }
251 return result;
252}
253
254std::set<int32_t> Module::findConnectedPortConfigIds(int32_t portConfigId) {
255 std::set<int32_t> result;
256 auto patchIdsRange = mPatches.equal_range(portConfigId);
257 auto& patches = getConfig().patches;
258 for (auto it = patchIdsRange.first; it != patchIdsRange.second; ++it) {
259 auto patchIt = findById<AudioPatch>(patches, it->second);
260 if (patchIt == patches.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530261 LOG(FATAL) << __func__ << ": " << mType << ": patch with id " << it->second
262 << " taken from mPatches "
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000263 << "not found in the configuration";
264 }
265 if (std::find(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end(),
266 portConfigId) != patchIt->sourcePortConfigIds.end()) {
267 result.insert(patchIt->sinkPortConfigIds.begin(), patchIt->sinkPortConfigIds.end());
268 } else {
269 result.insert(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end());
270 }
271 }
272 return result;
273}
274
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000275ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) {
276 auto& configs = getConfig().portConfigs;
277 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
278 if (portConfigIt == configs.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530279 LOG(ERROR) << __func__ << ": " << mType << ": existing port config id " << in_portConfigId
280 << " not found";
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000281 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
282 }
283 const int32_t portId = portConfigIt->portId;
284 // In our implementation, configs of mix ports always have unique IDs.
285 CHECK(portId != in_portConfigId);
286 auto& ports = getConfig().ports;
287 auto portIt = findById<AudioPort>(ports, portId);
288 if (portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530289 LOG(ERROR) << __func__ << ": " << mType << ": port id " << portId
290 << " used by port config id " << in_portConfigId << " not found";
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000291 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
292 }
293 if (mStreams.count(in_portConfigId) != 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530294 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000295 << " already has a stream opened on it";
296 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
297 }
298 if (portIt->ext.getTag() != AudioPortExt::Tag::mix) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530299 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000300 << " does not correspond to a mix port";
301 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
302 }
Mikhail Naganovb511b8a2023-05-15 14:35:24 -0700303 const size_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000304 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530305 LOG(ERROR) << __func__ << ": " << mType << ": port id " << portId
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000306 << " has already reached maximum allowed opened stream count: "
307 << maxOpenStreamCount;
308 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
309 }
310 *port = &(*portIt);
311 return ndk::ScopedAStatus::ok();
312}
313
Mikhail Naganova92039a2023-12-20 14:27:22 -0800314bool Module::generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) {
315 const bool allowDynamicConfig = port.ext.getTag() == AudioPortExt::device;
316 for (const auto& profile : port.profiles) {
317 if (isDynamicProfile(profile)) continue;
318 config->format = profile.format;
319 config->channelMask = *profile.channelMasks.begin();
320 config->sampleRate = Int{.value = *profile.sampleRates.begin()};
321 config->flags = port.flags;
322 config->ext = port.ext;
323 return true;
324 }
325 if (allowDynamicConfig) {
326 config->format = AudioFormatDescription{};
327 config->channelMask = AudioChannelLayout{};
328 config->sampleRate = Int{.value = 0};
329 config->flags = port.flags;
330 config->ext = port.ext;
331 return true;
332 }
Jaideep Sharma559a4912024-03-07 10:05:51 +0530333 LOG(ERROR) << __func__ << ": " << mType << ": port " << port.id << " only has dynamic profiles";
Mikhail Naganova92039a2023-12-20 14:27:22 -0800334 return false;
335}
336
Lorena Torres-Huertaf7492512023-01-14 02:49:41 +0000337void Module::populateConnectedProfiles() {
338 Configuration& config = getConfig();
339 for (const AudioPort& port : config.ports) {
340 if (port.ext.getTag() == AudioPortExt::device) {
341 if (auto devicePort = port.ext.get<AudioPortExt::device>();
342 !devicePort.device.type.connection.empty() && port.profiles.empty()) {
343 if (auto connIt = config.connectedProfiles.find(port.id);
344 connIt == config.connectedProfiles.end()) {
345 config.connectedProfiles.emplace(
346 port.id, internal::getStandard16And24BitPcmAudioProfiles());
347 }
348 }
349 }
350 }
351}
352
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000353template <typename C>
354std::set<int32_t> Module::portIdsFromPortConfigIds(C portConfigIds) {
355 std::set<int32_t> result;
356 auto& portConfigs = getConfig().portConfigs;
357 for (auto it = portConfigIds.begin(); it != portConfigIds.end(); ++it) {
358 auto portConfigIt = findById<AudioPortConfig>(portConfigs, *it);
359 if (portConfigIt != portConfigs.end()) {
360 result.insert(portConfigIt->portId);
361 }
362 }
363 return result;
364}
365
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000366std::unique_ptr<Module::Configuration> Module::initializeConfig() {
367 return internal::getConfiguration(getType());
Peter Yoon918a6a52023-07-13 17:04:37 +0900368}
369
Mikhail Naganov13501872023-10-18 16:15:46 -0700370int32_t Module::getNominalLatencyMs(const AudioPortConfig&) {
371 // Arbitrary value. Implementations must override this method to provide their actual latency.
372 static constexpr int32_t kLatencyMs = 5;
373 return kLatencyMs;
374}
375
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700376std::vector<AudioRoute*> Module::getAudioRoutesForAudioPortImpl(int32_t portId) {
377 std::vector<AudioRoute*> result;
378 auto& routes = getConfig().routes;
379 for (auto& r : routes) {
380 const auto& srcs = r.sourcePortIds;
381 if (r.sinkPortId == portId || std::find(srcs.begin(), srcs.end(), portId) != srcs.end()) {
382 result.push_back(&r);
383 }
384 }
385 return result;
386}
387
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000388Module::Configuration& Module::getConfig() {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000389 if (!mConfig) {
Peter Yoon918a6a52023-07-13 17:04:37 +0900390 mConfig = std::move(initializeConfig());
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000391 }
392 return *mConfig;
393}
394
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700395std::set<int32_t> Module::getRoutableAudioPortIds(int32_t portId,
396 std::vector<AudioRoute*>* routes) {
397 std::vector<AudioRoute*> routesStorage;
398 if (routes == nullptr) {
399 routesStorage = getAudioRoutesForAudioPortImpl(portId);
400 routes = &routesStorage;
401 }
402 std::set<int32_t> result;
403 for (AudioRoute* r : *routes) {
404 if (r->sinkPortId == portId) {
405 result.insert(r->sourcePortIds.begin(), r->sourcePortIds.end());
406 } else {
407 result.insert(r->sinkPortId);
408 }
409 }
410 return result;
411}
412
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000413void Module::registerPatch(const AudioPatch& patch) {
414 auto& configs = getConfig().portConfigs;
415 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
416 for (auto portConfigId : portConfigIds) {
417 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
418 if (configIt != configs.end()) {
419 mPatches.insert(std::pair{portConfigId, patch.id});
420 if (configIt->portId != portConfigId) {
421 mPatches.insert(std::pair{configIt->portId, patch.id});
422 }
423 }
424 };
425 };
426 do_insert(patch.sourcePortConfigIds);
427 do_insert(patch.sinkPortConfigIds);
428}
429
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700430ndk::ScopedAStatus Module::updateStreamsConnectedState(const AudioPatch& oldPatch,
431 const AudioPatch& newPatch) {
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700432 // Notify streams about the new set of devices they are connected to.
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700433 auto maybeFailure = ndk::ScopedAStatus::ok();
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700434 using Connections =
435 std::map<int32_t /*mixPortConfigId*/, std::set<int32_t /*devicePortConfigId*/>>;
436 Connections oldConnections, newConnections;
437 auto fillConnectionsHelper = [&](Connections& connections,
438 const std::vector<int32_t>& mixPortCfgIds,
439 const std::vector<int32_t>& devicePortCfgIds) {
440 for (int32_t mixPortCfgId : mixPortCfgIds) {
441 connections[mixPortCfgId].insert(devicePortCfgIds.begin(), devicePortCfgIds.end());
442 }
443 };
444 auto fillConnections = [&](Connections& connections, const AudioPatch& patch) {
445 if (std::find_if(patch.sourcePortConfigIds.begin(), patch.sourcePortConfigIds.end(),
446 [&](int32_t portConfigId) { return mStreams.count(portConfigId) > 0; }) !=
447 patch.sourcePortConfigIds.end()) {
448 // Sources are mix ports.
449 fillConnectionsHelper(connections, patch.sourcePortConfigIds, patch.sinkPortConfigIds);
450 } else if (std::find_if(patch.sinkPortConfigIds.begin(), patch.sinkPortConfigIds.end(),
451 [&](int32_t portConfigId) {
452 return mStreams.count(portConfigId) > 0;
453 }) != patch.sinkPortConfigIds.end()) {
454 // Sources are device ports.
455 fillConnectionsHelper(connections, patch.sinkPortConfigIds, patch.sourcePortConfigIds);
456 } // Otherwise, there are no streams to notify.
457 };
458 fillConnections(oldConnections, oldPatch);
459 fillConnections(newConnections, newPatch);
460
461 std::for_each(oldConnections.begin(), oldConnections.end(), [&](const auto& connectionPair) {
462 const int32_t mixPortConfigId = connectionPair.first;
463 if (auto it = newConnections.find(mixPortConfigId);
464 it == newConnections.end() || it->second != connectionPair.second) {
465 if (auto status = mStreams.setStreamConnectedDevices(mixPortConfigId, {});
466 status.isOk()) {
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700467 LOG(DEBUG) << "updateStreamsConnectedState: The stream on port config id "
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700468 << mixPortConfigId << " has been disconnected";
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700469 } else {
470 // Disconnection is tricky to roll back, just register a failure.
471 maybeFailure = std::move(status);
472 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000473 }
474 });
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700475 if (!maybeFailure.isOk()) return maybeFailure;
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700476 std::set<int32_t> idsToDisconnectOnFailure;
477 std::for_each(newConnections.begin(), newConnections.end(), [&](const auto& connectionPair) {
478 const int32_t mixPortConfigId = connectionPair.first;
479 if (auto it = oldConnections.find(mixPortConfigId);
480 it == oldConnections.end() || it->second != connectionPair.second) {
481 const auto connectedDevices = findConnectedDevices(mixPortConfigId);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700482 if (connectedDevices.empty()) {
483 // This is important as workers use the vector size to derive the connection status.
484 LOG(FATAL) << "updateStreamsConnectedState: No connected devices found for port "
485 "config id "
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700486 << mixPortConfigId;
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700487 }
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700488 if (auto status = mStreams.setStreamConnectedDevices(mixPortConfigId, connectedDevices);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700489 status.isOk()) {
490 LOG(DEBUG) << "updateStreamsConnectedState: The stream on port config id "
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700491 << mixPortConfigId << " has been connected to: "
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700492 << ::android::internal::ToString(connectedDevices);
493 } else {
494 maybeFailure = std::move(status);
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700495 idsToDisconnectOnFailure.insert(mixPortConfigId);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700496 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000497 }
498 });
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700499 if (!maybeFailure.isOk()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530500 LOG(WARNING) << __func__ << ": " << mType
501 << ": Due to a failure, disconnecting streams on port config ids "
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700502 << ::android::internal::ToString(idsToDisconnectOnFailure);
503 std::for_each(idsToDisconnectOnFailure.begin(), idsToDisconnectOnFailure.end(),
504 [&](const auto& portConfigId) {
505 auto status = mStreams.setStreamConnectedDevices(portConfigId, {});
506 (void)status.isOk(); // Can't do much about a failure here.
507 });
508 return maybeFailure;
509 }
510 return ndk::ScopedAStatus::ok();
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000511}
512
Mikhail Naganov00603d12022-05-02 22:52:13 +0000513ndk::ScopedAStatus Module::setModuleDebug(
514 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700515 LOG(DEBUG) << __func__ << ": " << mType << ": old flags:" << mDebug.toString()
Mikhail Naganov00603d12022-05-02 22:52:13 +0000516 << ", new flags: " << in_debug.toString();
517 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
518 !mConnectedDevicePorts.empty()) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700519 LOG(ERROR) << __func__ << ": " << mType
Jaideep Sharma559a4912024-03-07 10:05:51 +0530520 << ": attempting to change device connections simulation while "
521 "having external "
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700522 << "devices connected";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000523 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
524 }
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000525 if (in_debug.streamTransientStateDelayMs < 0) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700526 LOG(ERROR) << __func__ << ": " << mType << ": streamTransientStateDelayMs is negative: "
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000527 << in_debug.streamTransientStateDelayMs;
528 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
529 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000530 mDebug = in_debug;
531 return ndk::ScopedAStatus::ok();
532}
533
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000534ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700535 *_aidl_return = nullptr;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530536 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000537 return ndk::ScopedAStatus::ok();
538}
539
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000540ndk::ScopedAStatus Module::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700541 *_aidl_return = nullptr;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530542 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000543 return ndk::ScopedAStatus::ok();
544}
545
Mikhail Naganov7499a002023-02-27 18:51:44 -0800546ndk::ScopedAStatus Module::getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700547 *_aidl_return = nullptr;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530548 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
Mikhail Naganov7499a002023-02-27 18:51:44 -0800549 return ndk::ScopedAStatus::ok();
550}
551
Mikhail Naganovb5647da2023-03-06 14:37:38 -0800552ndk::ScopedAStatus Module::getBluetoothLe(std::shared_ptr<IBluetoothLe>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700553 *_aidl_return = nullptr;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530554 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
Mikhail Naganovb5647da2023-03-06 14:37:38 -0800555 return ndk::ScopedAStatus::ok();
556}
557
Mikhail Naganov00603d12022-05-02 22:52:13 +0000558ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
559 AudioPort* _aidl_return) {
560 const int32_t templateId = in_templateIdAndAdditionalData.id;
561 auto& ports = getConfig().ports;
562 AudioPort connectedPort;
563 { // Scope the template port so that we don't accidentally modify it.
564 auto templateIt = findById<AudioPort>(ports, templateId);
565 if (templateIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530566 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId << " not found";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000567 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
568 }
569 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530570 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
571 << " is not a device port";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000572 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
573 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000574 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
575 if (templateDevicePort.device.type.connection.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530576 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
577 << " is permanently attached";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000578 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
579 }
Mikhail Naganovfcf980e2023-09-07 16:30:11 -0700580 if (mConnectedDevicePorts.find(templateId) != mConnectedDevicePorts.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530581 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
582 << " is a connected device port";
Mikhail Naganovfcf980e2023-09-07 16:30:11 -0700583 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
584 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000585 // Postpone id allocation until we ensure that there are no client errors.
586 connectedPort = *templateIt;
587 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
588 const auto& inputDevicePort =
589 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
590 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
591 connectedDevicePort.device.address = inputDevicePort.device.address;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530592 LOG(DEBUG) << __func__ << ": " << mType << ": device port " << connectedPort.id
593 << " device set to " << connectedDevicePort.device.toString();
Mikhail Naganov00603d12022-05-02 22:52:13 +0000594 // Check if there is already a connected port with for the same external device.
Jaideep Sharma559a4912024-03-07 10:05:51 +0530595
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700596 for (auto connectedPortPair : mConnectedDevicePorts) {
597 auto connectedPortIt = findById<AudioPort>(ports, connectedPortPair.first);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000598 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
599 connectedDevicePort.device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530600 LOG(ERROR) << __func__ << ": " << mType << ": device "
601 << connectedDevicePort.device.toString()
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700602 << " is already connected at the device port id "
603 << connectedPortPair.first;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000604 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
605 }
606 }
607 }
608
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700609 // Two main cases are considered with regard to the profiles of the connected device port:
610 //
611 // 1. If the template device port has dynamic profiles, and at least one routable mix
612 // port also has dynamic profiles, it means that after connecting the device, the
613 // connected device port must have profiles populated with actual capabilities of
614 // the connected device, and dynamic of routable mix ports will be filled
615 // according to these capabilities. An example of this case is connection of an
616 // HDMI or USB device. For USB handled by ADSP, there can be mix ports with static
617 // profiles, and one dedicated mix port for "hi-fi" playback. The latter is left with
618 // dynamic profiles so that they can be populated with actual capabilities of
619 // the connected device.
620 //
621 // 2. If the template device port has dynamic profiles, while all routable mix ports
622 // have static profiles, it means that after connecting the device, the connected
623 // device port can be left with dynamic profiles, and profiles of mix ports are
624 // left untouched. An example of this case is connection of an analog wired
625 // headset, it should be treated in the same way as a speaker.
626 //
627 // Yet another possible case is when both the template device port and all routable
628 // mix ports have static profiles. This is allowed and handled correctly, however, it
629 // is not very practical, since these profiles are likely duplicates of each other.
630
631 std::vector<AudioRoute*> routesToMixPorts = getAudioRoutesForAudioPortImpl(templateId);
632 std::set<int32_t> routableMixPortIds = getRoutableAudioPortIds(templateId, &routesToMixPorts);
Mikhail Naganova92039a2023-12-20 14:27:22 -0800633 const int32_t nextPortId = getConfig().nextPortId++;
Mikhail Naganov55045b52023-10-24 17:03:50 -0700634 if (!mDebug.simulateDeviceConnections) {
635 // Even if the device port has static profiles, the HAL module might need to update
636 // them, or abort the connection process.
Mikhail Naganova92039a2023-12-20 14:27:22 -0800637 RETURN_STATUS_IF_ERROR(populateConnectedDevicePort(&connectedPort, nextPortId));
Mikhail Naganov55045b52023-10-24 17:03:50 -0700638 } else if (hasDynamicProfilesOnly(connectedPort.profiles)) {
639 auto& connectedProfiles = getConfig().connectedProfiles;
640 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
641 connectedProfilesIt != connectedProfiles.end()) {
642 connectedPort.profiles = connectedProfilesIt->second;
Mikhail Naganovfcf980e2023-09-07 16:30:11 -0700643 }
Mikhail Naganov55045b52023-10-24 17:03:50 -0700644 }
645 if (hasDynamicProfilesOnly(connectedPort.profiles)) {
646 // Possible case 2. Check if all routable mix ports have static profiles.
647 if (auto dynamicMixPortIt = std::find_if(ports.begin(), ports.end(),
648 [&routableMixPortIds](const auto& p) {
649 return routableMixPortIds.count(p.id) > 0 &&
650 hasDynamicProfilesOnly(p.profiles);
651 });
652 dynamicMixPortIt != ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530653 LOG(ERROR) << __func__ << ": " << mType
654 << ": connected port only has dynamic profiles after connecting "
Mikhail Naganov55045b52023-10-24 17:03:50 -0700655 << "external device " << connectedPort.toString() << ", and there exist "
656 << "a routable mix port with dynamic profiles: "
657 << dynamicMixPortIt->toString();
658 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530659 }
660 }
661
Mikhail Naganova92039a2023-12-20 14:27:22 -0800662 connectedPort.id = nextPortId;
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700663 auto [connectedPortsIt, _] =
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700664 mConnectedDevicePorts.insert(std::pair(connectedPort.id, std::set<int32_t>()));
Jaideep Sharma559a4912024-03-07 10:05:51 +0530665 LOG(DEBUG) << __func__ << ": " << mType << ": template port " << templateId
666 << " external device connected, "
Mikhail Naganov00603d12022-05-02 22:52:13 +0000667 << "connected port ID " << connectedPort.id;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000668 ports.push_back(connectedPort);
jiabin783c48b2023-02-28 18:28:06 +0000669 onExternalDeviceConnectionChanged(connectedPort, true /*connected*/);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000670
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700671 // For routes where the template port is a source, add the connected port to sources,
672 // otherwise, create a new route by copying from the route for the template port.
Mikhail Naganov00603d12022-05-02 22:52:13 +0000673 std::vector<AudioRoute> newRoutes;
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700674 for (AudioRoute* r : routesToMixPorts) {
675 if (r->sinkPortId == templateId) {
676 newRoutes.push_back(AudioRoute{.sourcePortIds = r->sourcePortIds,
677 .sinkPortId = connectedPort.id,
678 .isExclusive = r->isExclusive});
Mikhail Naganov00603d12022-05-02 22:52:13 +0000679 } else {
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700680 r->sourcePortIds.push_back(connectedPort.id);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000681 }
682 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700683 auto& routes = getConfig().routes;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000684 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
685
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700686 if (!hasDynamicProfilesOnly(connectedPort.profiles) && !routableMixPortIds.empty()) {
687 // Note: this is a simplistic approach assuming that a mix port can only be populated
688 // from a single device port. Implementing support for stuffing dynamic profiles with
689 // a superset of all profiles from all routable dynamic device ports would be more involved.
690 for (auto& port : ports) {
691 if (routableMixPortIds.count(port.id) == 0) continue;
692 if (hasDynamicProfilesOnly(port.profiles)) {
693 port.profiles = connectedPort.profiles;
694 connectedPortsIt->second.insert(port.id);
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700695 } else {
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700696 // Check if profiles are not all dynamic because they were populated by
697 // a previous connection. Otherwise, it means that they are actually static.
698 for (const auto& cp : mConnectedDevicePorts) {
699 if (cp.second.count(port.id) > 0) {
700 connectedPortsIt->second.insert(port.id);
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700701 break;
702 }
703 }
704 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700705 }
706 }
707 *_aidl_return = std::move(connectedPort);
708
Mikhail Naganov00603d12022-05-02 22:52:13 +0000709 return ndk::ScopedAStatus::ok();
710}
711
712ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
713 auto& ports = getConfig().ports;
714 auto portIt = findById<AudioPort>(ports, in_portId);
715 if (portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530716 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000717 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
718 }
719 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530720 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
721 << " is not a device port";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000722 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
723 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700724 auto connectedPortsIt = mConnectedDevicePorts.find(in_portId);
725 if (connectedPortsIt == mConnectedDevicePorts.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530726 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
727 << " is not a connected device port";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000728 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
729 }
730 auto& configs = getConfig().portConfigs;
731 auto& initials = getConfig().initialConfigs;
732 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
733 if (config.portId == in_portId) {
734 // Check if the configuration was provided by the client.
735 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
736 return initialIt == initials.end() || config != *initialIt;
737 }
738 return false;
739 });
740 if (configIt != configs.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530741 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
742 << " has a non-default config with id " << configIt->id;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000743 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
744 }
jiabin783c48b2023-02-28 18:28:06 +0000745 onExternalDeviceConnectionChanged(*portIt, false /*connected*/);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000746 ports.erase(portIt);
Jaideep Sharma559a4912024-03-07 10:05:51 +0530747 LOG(DEBUG) << __func__ << ": " << mType << ": connected device port " << in_portId
748 << " released";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000749
750 auto& routes = getConfig().routes;
751 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
752 if (routesIt->sinkPortId == in_portId) {
753 routesIt = routes.erase(routesIt);
754 } else {
755 // Note: the list of sourcePortIds can't become empty because there must
756 // be the id of the template port in the route.
757 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
758 ++routesIt;
759 }
760 }
761
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700762 // Clear profiles for mix ports that are not connected to any other ports.
763 std::set<int32_t> mixPortsToClear = std::move(connectedPortsIt->second);
764 mConnectedDevicePorts.erase(connectedPortsIt);
765 for (const auto& connectedPort : mConnectedDevicePorts) {
766 for (int32_t mixPortId : connectedPort.second) {
767 mixPortsToClear.erase(mixPortId);
768 }
769 }
770 for (int32_t mixPortId : mixPortsToClear) {
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700771 auto mixPortIt = findById<AudioPort>(ports, mixPortId);
772 if (mixPortIt != ports.end()) {
773 mixPortIt->profiles = {};
774 }
775 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700776
Mikhail Naganov00603d12022-05-02 22:52:13 +0000777 return ndk::ScopedAStatus::ok();
778}
779
jiabindd23b0e2023-12-11 19:10:05 +0000780ndk::ScopedAStatus Module::prepareToDisconnectExternalDevice(int32_t in_portId) {
781 auto& ports = getConfig().ports;
782 auto portIt = findById<AudioPort>(ports, in_portId);
783 if (portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530784 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
jiabindd23b0e2023-12-11 19:10:05 +0000785 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
786 }
787 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530788 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
789 << " is not a device port";
jiabindd23b0e2023-12-11 19:10:05 +0000790 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
791 }
792 auto connectedPortsIt = mConnectedDevicePorts.find(in_portId);
793 if (connectedPortsIt == mConnectedDevicePorts.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530794 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
795 << " is not a connected device port";
jiabindd23b0e2023-12-11 19:10:05 +0000796 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
797 }
798
799 onPrepareToDisconnectExternalDevice(*portIt);
800
801 return ndk::ScopedAStatus::ok();
802}
803
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000804ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
805 *_aidl_return = getConfig().patches;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530806 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " patches";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000807 return ndk::ScopedAStatus::ok();
808}
809
810ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
811 auto& ports = getConfig().ports;
812 auto portIt = findById<AudioPort>(ports, in_portId);
813 if (portIt != ports.end()) {
814 *_aidl_return = *portIt;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530815 LOG(DEBUG) << __func__ << ": " << mType << ": returning port by id " << in_portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000816 return ndk::ScopedAStatus::ok();
817 }
Jaideep Sharma559a4912024-03-07 10:05:51 +0530818 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000819 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
820}
821
822ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
823 *_aidl_return = getConfig().portConfigs;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530824 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size()
825 << " port configs";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000826 return ndk::ScopedAStatus::ok();
827}
828
829ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
830 *_aidl_return = getConfig().ports;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530831 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " ports";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000832 return ndk::ScopedAStatus::ok();
833}
834
835ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
836 *_aidl_return = getConfig().routes;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530837 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " routes";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000838 return ndk::ScopedAStatus::ok();
839}
840
Mikhail Naganov00603d12022-05-02 22:52:13 +0000841ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
842 std::vector<AudioRoute>* _aidl_return) {
843 auto& ports = getConfig().ports;
844 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530845 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000846 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
847 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700848 std::vector<AudioRoute*> routes = getAudioRoutesForAudioPortImpl(in_portId);
849 std::transform(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
850 [](auto rptr) { return *rptr; });
Mikhail Naganov00603d12022-05-02 22:52:13 +0000851 return ndk::ScopedAStatus::ok();
852}
853
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000854ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
855 OpenInputStreamReturn* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530856 LOG(DEBUG) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
857 << ", buffer size " << in_args.bufferSizeFrames << " frames";
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000858 AudioPort* port = nullptr;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700859 RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000860 if (port->flags.getTag() != AudioIoFlags::Tag::input) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530861 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000862 << " does not correspond to an input mix port";
863 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
864 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000865 StreamContext context;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700866 RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
867 nullptr, nullptr, &context));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000868 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000869 std::shared_ptr<StreamIn> stream;
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700870 RETURN_STATUS_IF_ERROR(createInputStream(std::move(context), in_args.sinkMetadata,
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +0000871 getMicrophoneInfos(), &stream));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000872 StreamWrapper streamWrapper(stream);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700873 if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
874 RETURN_STATUS_IF_ERROR(
875 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
876 }
Mikhail Naganovefb45bc2024-03-27 16:20:33 +0000877 auto streamBinder = streamWrapper.getBinder();
878 AIBinder_setMinSchedulerPolicy(streamBinder.get(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
879 AIBinder_setInheritRt(streamBinder.get(), true);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000880 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000881 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000882 return ndk::ScopedAStatus::ok();
883}
884
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000885ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
886 OpenOutputStreamReturn* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530887 LOG(DEBUG) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
888 << ", has offload info? " << (in_args.offloadInfo.has_value()) << ", buffer size "
889 << in_args.bufferSizeFrames << " frames";
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000890 AudioPort* port = nullptr;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700891 RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000892 if (port->flags.getTag() != AudioIoFlags::Tag::output) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530893 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000894 << " does not correspond to an output mix port";
895 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
896 }
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000897 const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
898 AudioOutputFlags::COMPRESS_OFFLOAD);
899 if (isOffload && !in_args.offloadInfo.has_value()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530900 LOG(ERROR) << __func__ << ": " << mType << ": port id " << port->id
Mikhail Naganov111e0ce2022-06-17 21:41:19 +0000901 << " has COMPRESS_OFFLOAD flag set, requires offload info";
902 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
903 }
Mikhail Naganov30301a42022-09-13 01:20:45 +0000904 const bool isNonBlocking = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
905 AudioOutputFlags::NON_BLOCKING);
906 if (isNonBlocking && in_args.callback == nullptr) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530907 LOG(ERROR) << __func__ << ": " << mType << ": port id " << port->id
Mikhail Naganov30301a42022-09-13 01:20:45 +0000908 << " has NON_BLOCKING flag set, requires async callback";
909 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
910 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000911 StreamContext context;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700912 RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
913 isNonBlocking ? in_args.callback : nullptr,
914 in_args.eventCallback, &context));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000915 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000916 std::shared_ptr<StreamOut> stream;
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700917 RETURN_STATUS_IF_ERROR(createOutputStream(std::move(context), in_args.sourceMetadata,
Mikhail Naganov9d16a6a2023-06-26 17:21:04 -0700918 in_args.offloadInfo, &stream));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000919 StreamWrapper streamWrapper(stream);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700920 if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
921 RETURN_STATUS_IF_ERROR(
922 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
923 }
Mikhail Naganovefb45bc2024-03-27 16:20:33 +0000924 auto streamBinder = streamWrapper.getBinder();
925 AIBinder_setMinSchedulerPolicy(streamBinder.get(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
926 AIBinder_setInheritRt(streamBinder.get(), true);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000927 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000928 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000929 return ndk::ScopedAStatus::ok();
930}
931
Mikhail Naganov74927202022-12-19 16:37:14 +0000932ndk::ScopedAStatus Module::getSupportedPlaybackRateFactors(
933 SupportedPlaybackRateFactors* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530934 LOG(DEBUG) << __func__ << ": " << mType;
Mikhail Naganov74927202022-12-19 16:37:14 +0000935 (void)_aidl_return;
936 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
937}
938
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000939ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530940 LOG(DEBUG) << __func__ << ": " << mType << ": requested patch " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000941 if (in_requested.sourcePortConfigIds.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530942 LOG(ERROR) << __func__ << ": " << mType << ": requested patch has empty sources list";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000943 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
944 }
945 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530946 LOG(ERROR) << __func__ << ": " << mType
947 << ": requested patch has duplicate ids in the sources list";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000948 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
949 }
950 if (in_requested.sinkPortConfigIds.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530951 LOG(ERROR) << __func__ << ": " << mType << ": requested patch has empty sinks list";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000952 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
953 }
954 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530955 LOG(ERROR) << __func__ << ": " << mType
956 << ": requested patch has duplicate ids in the sinks list";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000957 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
958 }
959
960 auto& configs = getConfig().portConfigs;
961 std::vector<int32_t> missingIds;
962 auto sources =
963 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
964 if (!missingIds.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530965 LOG(ERROR) << __func__ << ": " << mType << ": following source port config ids not found: "
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000966 << ::android::internal::ToString(missingIds);
967 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
968 }
969 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
970 if (!missingIds.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530971 LOG(ERROR) << __func__ << ": " << mType << ": following sink port config ids not found: "
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000972 << ::android::internal::ToString(missingIds);
973 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
974 }
975 // bool indicates whether a non-exclusive route is available.
976 // If only an exclusive route is available, that means the patch can not be
977 // established if there is any other patch which currently uses the sink port.
978 std::map<int32_t, bool> allowedSinkPorts;
979 auto& routes = getConfig().routes;
980 for (auto src : sources) {
981 for (const auto& r : routes) {
982 const auto& srcs = r.sourcePortIds;
983 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
984 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
985 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
986 }
987 }
988 }
989 }
990 for (auto sink : sinks) {
991 if (allowedSinkPorts.count(sink->portId) == 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530992 LOG(ERROR) << __func__ << ": " << mType << ": there is no route to the sink port id "
993 << sink->portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000994 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
995 }
996 }
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700997 RETURN_STATUS_IF_ERROR(checkAudioPatchEndpointsMatch(sources, sinks));
jiabin253bd322023-01-25 23:57:31 +0000998
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000999 auto& patches = getConfig().patches;
1000 auto existing = patches.end();
1001 std::optional<decltype(mPatches)> patchesBackup;
1002 if (in_requested.id != 0) {
1003 existing = findById<AudioPatch>(patches, in_requested.id);
1004 if (existing != patches.end()) {
1005 patchesBackup = mPatches;
1006 cleanUpPatch(existing->id);
1007 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301008 LOG(ERROR) << __func__ << ": " << mType << ": not found existing patch id "
1009 << in_requested.id;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001010 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1011 }
1012 }
1013 // Validate the requested patch.
1014 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
1015 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301016 LOG(ERROR) << __func__ << ": " << mType << ": sink port id " << sinkPortId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001017 << "is exclusive and is already used by some other patch";
1018 if (patchesBackup.has_value()) {
1019 mPatches = std::move(*patchesBackup);
1020 }
1021 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1022 }
1023 }
Mikhail Naganov13501872023-10-18 16:15:46 -07001024 // Find the highest sample rate among mix port configs.
1025 std::map<int32_t, AudioPortConfig*> sampleRates;
1026 std::vector<AudioPortConfig*>& mixPortConfigs =
1027 sources[0]->ext.getTag() == AudioPortExt::mix ? sources : sinks;
1028 for (auto mix : mixPortConfigs) {
1029 sampleRates.emplace(mix->sampleRate.value().value, mix);
1030 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001031 *_aidl_return = in_requested;
Mikhail Naganov13501872023-10-18 16:15:46 -07001032 auto maxSampleRateIt = std::max_element(sampleRates.begin(), sampleRates.end());
1033 const int32_t latencyMs = getNominalLatencyMs(*(maxSampleRateIt->second));
1034 _aidl_return->minimumStreamBufferSizeFrames =
1035 calculateBufferSizeFrames(latencyMs, maxSampleRateIt->first);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +00001036 _aidl_return->latenciesMs.clear();
1037 _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
Mikhail Naganov13501872023-10-18 16:15:46 -07001038 _aidl_return->sinkPortConfigIds.size(), latencyMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001039 AudioPatch oldPatch{};
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001040 if (existing == patches.end()) {
1041 _aidl_return->id = getConfig().nextPatchId++;
1042 patches.push_back(*_aidl_return);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001043 } else {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001044 oldPatch = *existing;
Mikhail Naganovdc417732023-09-29 15:49:35 -07001045 *existing = *_aidl_return;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001046 }
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001047 patchesBackup = mPatches;
1048 registerPatch(*_aidl_return);
1049 if (auto status = updateStreamsConnectedState(oldPatch, *_aidl_return); !status.isOk()) {
1050 mPatches = std::move(*patchesBackup);
1051 if (existing == patches.end()) {
1052 patches.pop_back();
1053 } else {
1054 *existing = oldPatch;
1055 }
1056 return status;
1057 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001058
Jaideep Sharma559a4912024-03-07 10:05:51 +05301059 LOG(DEBUG) << __func__ << ": " << mType << ": " << (oldPatch.id == 0 ? "created" : "updated")
1060 << " patch " << _aidl_return->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001061 return ndk::ScopedAStatus::ok();
1062}
1063
1064ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
1065 AudioPortConfig* out_suggested, bool* _aidl_return) {
Mikhail Naganova92039a2023-12-20 14:27:22 -08001066 auto generate = [this](const AudioPort& port, AudioPortConfig* config) {
1067 return generateDefaultPortConfig(port, config);
1068 };
1069 return setAudioPortConfigImpl(in_requested, generate, out_suggested, _aidl_return);
1070}
1071
1072ndk::ScopedAStatus Module::setAudioPortConfigImpl(
1073 const AudioPortConfig& in_requested,
1074 const std::function<bool(const ::aidl::android::media::audio::common::AudioPort& port,
1075 ::aidl::android::media::audio::common::AudioPortConfig* config)>&
1076 fillPortConfig,
1077 AudioPortConfig* out_suggested, bool* applied) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301078 LOG(DEBUG) << __func__ << ": " << mType << ": requested " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001079 auto& configs = getConfig().portConfigs;
1080 auto existing = configs.end();
1081 if (in_requested.id != 0) {
1082 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
1083 existing == configs.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301084 LOG(ERROR) << __func__ << ": " << mType << ": existing port config id "
1085 << in_requested.id << " not found";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001086 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1087 }
1088 }
1089
1090 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
1091 if (portId == 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301092 LOG(ERROR) << __func__ << ": " << mType
1093 << ": requested port config does not specify portId";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001094 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1095 }
1096 auto& ports = getConfig().ports;
1097 auto portIt = findById<AudioPort>(ports, portId);
1098 if (portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301099 LOG(ERROR) << __func__ << ": " << mType
1100 << ": requested port config points to non-existent portId " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001101 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1102 }
1103 if (existing != configs.end()) {
1104 *out_suggested = *existing;
1105 } else {
1106 AudioPortConfig newConfig;
Mikhail Naganova92039a2023-12-20 14:27:22 -08001107 newConfig.portId = portIt->id;
1108 if (fillPortConfig(*portIt, &newConfig)) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001109 *out_suggested = newConfig;
1110 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301111 LOG(ERROR) << __func__ << ": " << mType
1112 << ": unable generate a default config for port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001113 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1114 }
1115 }
1116 // From this moment, 'out_suggested' is either an existing port config,
1117 // or a new generated config. Now attempt to update it according to the specified
1118 // fields of 'in_requested'.
1119
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001120 // Device ports with only dynamic profiles are used for devices that are connected via ADSP,
1121 // which takes care of their actual configuration automatically.
1122 const bool allowDynamicConfig = portIt->ext.getTag() == AudioPortExt::device &&
1123 hasDynamicProfilesOnly(portIt->profiles);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001124 bool requestedIsValid = true, requestedIsFullySpecified = true;
1125
1126 AudioIoFlags portFlags = portIt->flags;
1127 if (in_requested.flags.has_value()) {
1128 if (in_requested.flags.value() != portFlags) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301129 LOG(WARNING) << __func__ << ": " << mType << ": requested flags "
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001130 << in_requested.flags.value().toString() << " do not match port's "
1131 << portId << " flags " << portFlags.toString();
1132 requestedIsValid = false;
1133 }
1134 } else {
1135 requestedIsFullySpecified = false;
1136 }
1137
1138 AudioProfile portProfile;
1139 if (in_requested.format.has_value()) {
1140 const auto& format = in_requested.format.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001141 if ((format == AudioFormatDescription{} && allowDynamicConfig) ||
1142 findAudioProfile(*portIt, format, &portProfile)) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001143 out_suggested->format = format;
1144 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301145 LOG(WARNING) << __func__ << ": " << mType << ": requested format " << format.toString()
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001146 << " is not found in the profiles of port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001147 requestedIsValid = false;
1148 }
1149 } else {
1150 requestedIsFullySpecified = false;
1151 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001152 if (!(out_suggested->format.value() == AudioFormatDescription{} && allowDynamicConfig) &&
1153 !findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301154 LOG(ERROR) << __func__ << ": " << mType << ": port " << portId
1155 << " does not support format " << out_suggested->format.value().toString()
1156 << " anymore";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001157 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1158 }
1159
1160 if (in_requested.channelMask.has_value()) {
1161 const auto& channelMask = in_requested.channelMask.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001162 if ((channelMask == AudioChannelLayout{} && allowDynamicConfig) ||
1163 find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
1164 portProfile.channelMasks.end()) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001165 out_suggested->channelMask = channelMask;
1166 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301167 LOG(WARNING) << __func__ << ": " << mType << ": requested channel mask "
1168 << channelMask.toString() << " is not supported for the format "
1169 << portProfile.format.toString() << " by the port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001170 requestedIsValid = false;
1171 }
1172 } else {
1173 requestedIsFullySpecified = false;
1174 }
1175
1176 if (in_requested.sampleRate.has_value()) {
1177 const auto& sampleRate = in_requested.sampleRate.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001178 if ((sampleRate.value == 0 && allowDynamicConfig) ||
1179 find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001180 sampleRate.value) != portProfile.sampleRates.end()) {
1181 out_suggested->sampleRate = sampleRate;
1182 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301183 LOG(WARNING) << __func__ << ": " << mType << ": requested sample rate "
1184 << sampleRate.value << " is not supported for the format "
1185 << portProfile.format.toString() << " by the port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001186 requestedIsValid = false;
1187 }
1188 } else {
1189 requestedIsFullySpecified = false;
1190 }
1191
1192 if (in_requested.gain.has_value()) {
1193 // Let's pretend that gain can always be applied.
1194 out_suggested->gain = in_requested.gain.value();
1195 }
1196
Mikhail Naganov248e9502023-02-21 16:32:40 -08001197 if (in_requested.ext.getTag() != AudioPortExt::Tag::unspecified) {
1198 if (in_requested.ext.getTag() == out_suggested->ext.getTag()) {
1199 if (out_suggested->ext.getTag() == AudioPortExt::Tag::mix) {
Mikhail Naganovb06a4922024-03-06 16:39:50 -08001200 // 'AudioMixPortExt.handle' and '.usecase' are set by the client,
1201 // copy from in_requested.
1202 const auto& src = in_requested.ext.get<AudioPortExt::Tag::mix>();
1203 auto& dst = out_suggested->ext.get<AudioPortExt::Tag::mix>();
1204 dst.handle = src.handle;
1205 dst.usecase = src.usecase;
Mikhail Naganov248e9502023-02-21 16:32:40 -08001206 }
1207 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301208 LOG(WARNING) << __func__ << ": " << mType << ": requested ext tag "
Mikhail Naganov248e9502023-02-21 16:32:40 -08001209 << toString(in_requested.ext.getTag()) << " do not match port's tag "
1210 << toString(out_suggested->ext.getTag());
1211 requestedIsValid = false;
1212 }
1213 }
1214
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001215 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
1216 out_suggested->id = getConfig().nextPortId++;
1217 configs.push_back(*out_suggested);
Mikhail Naganova92039a2023-12-20 14:27:22 -08001218 *applied = true;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301219 LOG(DEBUG) << __func__ << ": " << mType << ": created new port config "
1220 << out_suggested->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001221 } else if (existing != configs.end() && requestedIsValid) {
1222 *existing = *out_suggested;
Mikhail Naganova92039a2023-12-20 14:27:22 -08001223 *applied = true;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301224 LOG(DEBUG) << __func__ << ": " << mType << ": updated port config "
1225 << out_suggested->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001226 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301227 LOG(DEBUG) << __func__ << ": " << mType << ": not applied; existing config ? "
1228 << (existing != configs.end()) << "; requested is valid? " << requestedIsValid
1229 << ", fully specified? " << requestedIsFullySpecified;
Mikhail Naganova92039a2023-12-20 14:27:22 -08001230 *applied = false;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001231 }
1232 return ndk::ScopedAStatus::ok();
1233}
1234
1235ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
1236 auto& patches = getConfig().patches;
1237 auto patchIt = findById<AudioPatch>(patches, in_patchId);
1238 if (patchIt != patches.end()) {
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001239 auto patchesBackup = mPatches;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001240 cleanUpPatch(patchIt->id);
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001241 if (auto status = updateStreamsConnectedState(*patchIt, AudioPatch{}); !status.isOk()) {
1242 mPatches = std::move(patchesBackup);
1243 return status;
1244 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001245 patches.erase(patchIt);
Jaideep Sharma559a4912024-03-07 10:05:51 +05301246 LOG(DEBUG) << __func__ << ": " << mType << ": erased patch " << in_patchId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001247 return ndk::ScopedAStatus::ok();
1248 }
Jaideep Sharma559a4912024-03-07 10:05:51 +05301249 LOG(ERROR) << __func__ << ": " << mType << ": patch id " << in_patchId << " not found";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001250 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1251}
1252
1253ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
1254 auto& configs = getConfig().portConfigs;
1255 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
1256 if (configIt != configs.end()) {
1257 if (mStreams.count(in_portConfigId) != 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301258 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001259 << " has a stream opened on it";
1260 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1261 }
1262 auto patchIt = mPatches.find(in_portConfigId);
1263 if (patchIt != mPatches.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301264 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001265 << " is used by the patch with id " << patchIt->second;
1266 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1267 }
1268 auto& initials = getConfig().initialConfigs;
1269 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
1270 if (initialIt == initials.end()) {
1271 configs.erase(configIt);
Jaideep Sharma559a4912024-03-07 10:05:51 +05301272 LOG(DEBUG) << __func__ << ": " << mType << ": erased port config " << in_portConfigId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001273 } else if (*configIt != *initialIt) {
1274 *configIt = *initialIt;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301275 LOG(DEBUG) << __func__ << ": " << mType << ": reset port config " << in_portConfigId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001276 }
1277 return ndk::ScopedAStatus::ok();
1278 }
Jaideep Sharma559a4912024-03-07 10:05:51 +05301279 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
1280 << " not found";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001281 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1282}
1283
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001284ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) {
1285 *_aidl_return = mMasterMute;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301286 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001287 return ndk::ScopedAStatus::ok();
1288}
1289
1290ndk::ScopedAStatus Module::setMasterMute(bool in_mute) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301291 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_mute;
jiabin783c48b2023-02-28 18:28:06 +00001292 auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1293 : onMasterMuteChanged(in_mute);
1294 if (result.isOk()) {
1295 mMasterMute = in_mute;
1296 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301297 LOG(ERROR) << __func__ << ": " << mType << ": failed calling onMasterMuteChanged("
1298 << in_mute << "), error=" << result;
jiabin783c48b2023-02-28 18:28:06 +00001299 // Reset master mute if it failed.
1300 onMasterMuteChanged(mMasterMute);
1301 }
Mikhail Naganov55045b52023-10-24 17:03:50 -07001302 return result;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001303}
1304
1305ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) {
1306 *_aidl_return = mMasterVolume;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301307 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001308 return ndk::ScopedAStatus::ok();
1309}
1310
1311ndk::ScopedAStatus Module::setMasterVolume(float in_volume) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301312 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_volume;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001313 if (in_volume >= 0.0f && in_volume <= 1.0f) {
jiabin783c48b2023-02-28 18:28:06 +00001314 auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1315 : onMasterVolumeChanged(in_volume);
1316 if (result.isOk()) {
1317 mMasterVolume = in_volume;
1318 } else {
1319 // Reset master volume if it failed.
Jaideep Sharma559a4912024-03-07 10:05:51 +05301320 LOG(ERROR) << __func__ << ": " << mType << ": failed calling onMasterVolumeChanged("
1321 << in_volume << "), error=" << result;
jiabin783c48b2023-02-28 18:28:06 +00001322 onMasterVolumeChanged(mMasterVolume);
1323 }
Mikhail Naganov55045b52023-10-24 17:03:50 -07001324 return result;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001325 }
Jaideep Sharma559a4912024-03-07 10:05:51 +05301326 LOG(ERROR) << __func__ << ": " << mType << ": invalid master volume value: " << in_volume;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001327 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1328}
1329
1330ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) {
1331 *_aidl_return = mMicMute;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301332 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001333 return ndk::ScopedAStatus::ok();
1334}
1335
1336ndk::ScopedAStatus Module::setMicMute(bool in_mute) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301337 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_mute;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001338 mMicMute = in_mute;
1339 return ndk::ScopedAStatus::ok();
1340}
1341
Mikhail Naganovef6bc742022-10-06 00:14:19 +00001342ndk::ScopedAStatus Module::getMicrophones(std::vector<MicrophoneInfo>* _aidl_return) {
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +00001343 *_aidl_return = getMicrophoneInfos();
Jaideep Sharma559a4912024-03-07 10:05:51 +05301344 LOG(DEBUG) << __func__ << ": " << mType << ": returning "
1345 << ::android::internal::ToString(*_aidl_return);
Mikhail Naganovef6bc742022-10-06 00:14:19 +00001346 return ndk::ScopedAStatus::ok();
1347}
1348
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001349ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) {
Mikhail Naganov04ae8222023-01-11 15:48:10 -08001350 if (!isValidAudioMode(in_mode)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301351 LOG(ERROR) << __func__ << ": " << mType << ": invalid mode " << toString(in_mode);
Mikhail Naganov04ae8222023-01-11 15:48:10 -08001352 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1353 }
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001354 // No checks for supported audio modes here, it's an informative notification.
Jaideep Sharma559a4912024-03-07 10:05:51 +05301355 LOG(DEBUG) << __func__ << ": " << mType << ": " << toString(in_mode);
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001356 return ndk::ScopedAStatus::ok();
1357}
1358
1359ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301360 LOG(DEBUG) << __func__ << ": " << mType << ": " << toString(in_rotation);
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001361 return ndk::ScopedAStatus::ok();
1362}
1363
1364ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301365 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_isTurnedOn;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001366 return ndk::ScopedAStatus::ok();
1367}
1368
Vlad Popa83a6d822022-11-07 13:53:57 +01001369ndk::ScopedAStatus Module::getSoundDose(std::shared_ptr<ISoundDose>* _aidl_return) {
Mikhail Naganov7499a002023-02-27 18:51:44 -08001370 if (!mSoundDose) {
Vlad Popa2afbd1e2022-12-28 17:04:58 +01001371 mSoundDose = ndk::SharedRefBase::make<sounddose::SoundDose>();
Vlad Popa943b7e22022-12-08 14:24:12 +01001372 }
Mikhail Naganov780fefb2023-07-21 17:01:38 -07001373 *_aidl_return = mSoundDose.getInstance();
Jaideep Sharma559a4912024-03-07 10:05:51 +05301374 LOG(DEBUG) << __func__ << ": " << mType
1375 << ": returning instance of ISoundDose: " << _aidl_return->get();
Vlad Popa83a6d822022-11-07 13:53:57 +01001376 return ndk::ScopedAStatus::ok();
1377}
1378
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001379ndk::ScopedAStatus Module::generateHwAvSyncId(int32_t* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301380 LOG(DEBUG) << __func__ << ": " << mType;
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001381 (void)_aidl_return;
1382 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1383}
1384
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001385const std::string Module::VendorDebug::kForceTransientBurstName = "aosp.forceTransientBurst";
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001386const std::string Module::VendorDebug::kForceSynchronousDrainName = "aosp.forceSynchronousDrain";
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001387
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001388ndk::ScopedAStatus Module::getVendorParameters(const std::vector<std::string>& in_ids,
1389 std::vector<VendorParameter>* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301390 LOG(VERBOSE) << __func__ << ": " << mType << ": id count: " << in_ids.size();
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001391 bool allParametersKnown = true;
1392 for (const auto& id : in_ids) {
1393 if (id == VendorDebug::kForceTransientBurstName) {
1394 VendorParameter forceTransientBurst{.id = id};
1395 forceTransientBurst.ext.setParcelable(Boolean{mVendorDebug.forceTransientBurst});
1396 _aidl_return->push_back(std::move(forceTransientBurst));
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001397 } else if (id == VendorDebug::kForceSynchronousDrainName) {
1398 VendorParameter forceSynchronousDrain{.id = id};
1399 forceSynchronousDrain.ext.setParcelable(Boolean{mVendorDebug.forceSynchronousDrain});
1400 _aidl_return->push_back(std::move(forceSynchronousDrain));
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001401 } else {
1402 allParametersKnown = false;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301403 LOG(VERBOSE) << __func__ << ": " << mType << ": unrecognized parameter \"" << id << "\"";
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001404 }
1405 }
1406 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1407 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001408}
1409
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001410namespace {
1411
1412template <typename W>
1413bool extractParameter(const VendorParameter& p, decltype(W::value)* v) {
1414 std::optional<W> value;
1415 binder_status_t result = p.ext.getParcelable(&value);
1416 if (result == STATUS_OK && value.has_value()) {
1417 *v = value.value().value;
1418 return true;
1419 }
1420 LOG(ERROR) << __func__ << ": failed to read the value of the parameter \"" << p.id
1421 << "\": " << result;
1422 return false;
1423}
1424
1425} // namespace
1426
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001427ndk::ScopedAStatus Module::setVendorParameters(const std::vector<VendorParameter>& in_parameters,
1428 bool in_async) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301429 LOG(VERBOSE) << __func__ << ": " << mType << ": parameter count " << in_parameters.size()
1430 << ", async: " << in_async;
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001431 bool allParametersKnown = true;
1432 for (const auto& p : in_parameters) {
1433 if (p.id == VendorDebug::kForceTransientBurstName) {
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001434 if (!extractParameter<Boolean>(p, &mVendorDebug.forceTransientBurst)) {
1435 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1436 }
1437 } else if (p.id == VendorDebug::kForceSynchronousDrainName) {
1438 if (!extractParameter<Boolean>(p, &mVendorDebug.forceSynchronousDrain)) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001439 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1440 }
1441 } else {
1442 allParametersKnown = false;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301443 LOG(VERBOSE) << __func__ << ": " << mType << ": unrecognized parameter \"" << p.id
1444 << "\"";
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001445 }
1446 }
1447 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1448 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001449}
1450
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001451ndk::ScopedAStatus Module::addDeviceEffect(
1452 int32_t in_portConfigId,
1453 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1454 if (in_effect == nullptr) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301455 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1456 << ", null effect";
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001457 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301458 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1459 << ", effect Binder " << in_effect->asBinder().get();
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001460 }
1461 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1462}
1463
1464ndk::ScopedAStatus Module::removeDeviceEffect(
1465 int32_t in_portConfigId,
1466 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1467 if (in_effect == nullptr) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301468 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1469 << ", null effect";
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001470 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301471 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1472 << ", effect Binder " << in_effect->asBinder().get();
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001473 }
1474 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1475}
1476
jiabin9a8e6862023-01-12 23:06:37 +00001477ndk::ScopedAStatus Module::getMmapPolicyInfos(AudioMMapPolicyType mmapPolicyType,
1478 std::vector<AudioMMapPolicyInfo>* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301479 LOG(DEBUG) << __func__ << ": " << mType << ": mmap policy type " << toString(mmapPolicyType);
jiabin9a8e6862023-01-12 23:06:37 +00001480 std::set<int32_t> mmapSinks;
1481 std::set<int32_t> mmapSources;
1482 auto& ports = getConfig().ports;
1483 for (const auto& port : ports) {
1484 if (port.flags.getTag() == AudioIoFlags::Tag::input &&
1485 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::input>(),
1486 AudioInputFlags::MMAP_NOIRQ)) {
1487 mmapSinks.insert(port.id);
1488 } else if (port.flags.getTag() == AudioIoFlags::Tag::output &&
1489 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
1490 AudioOutputFlags::MMAP_NOIRQ)) {
1491 mmapSources.insert(port.id);
1492 }
1493 }
Mikhail Naganov85064912023-09-26 17:10:08 -07001494 if (mmapSources.empty() && mmapSinks.empty()) {
1495 AudioMMapPolicyInfo never;
1496 never.mmapPolicy = AudioMMapPolicy::NEVER;
1497 _aidl_return->push_back(never);
1498 return ndk::ScopedAStatus::ok();
1499 }
jiabin9a8e6862023-01-12 23:06:37 +00001500 for (const auto& route : getConfig().routes) {
1501 if (mmapSinks.count(route.sinkPortId) != 0) {
1502 // The sink is a mix port, add the sources if they are device ports.
1503 for (int sourcePortId : route.sourcePortIds) {
1504 auto sourcePortIt = findById<AudioPort>(ports, sourcePortId);
1505 if (sourcePortIt == ports.end()) {
1506 // This must not happen
Jaideep Sharma559a4912024-03-07 10:05:51 +05301507 LOG(ERROR) << __func__ << ": " << mType << ": port id " << sourcePortId
1508 << " cannot be found";
jiabin9a8e6862023-01-12 23:06:37 +00001509 continue;
1510 }
1511 if (sourcePortIt->ext.getTag() != AudioPortExt::Tag::device) {
1512 // The source is not a device port, skip
1513 continue;
1514 }
1515 AudioMMapPolicyInfo policyInfo;
1516 policyInfo.device = sourcePortIt->ext.get<AudioPortExt::Tag::device>().device;
1517 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1518 // default implementation.
1519 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1520 _aidl_return->push_back(policyInfo);
1521 }
1522 } else {
1523 auto sinkPortIt = findById<AudioPort>(ports, route.sinkPortId);
1524 if (sinkPortIt == ports.end()) {
1525 // This must not happen
Jaideep Sharma559a4912024-03-07 10:05:51 +05301526 LOG(ERROR) << __func__ << ": " << mType << ": port id " << route.sinkPortId
1527 << " cannot be found";
jiabin9a8e6862023-01-12 23:06:37 +00001528 continue;
1529 }
1530 if (sinkPortIt->ext.getTag() != AudioPortExt::Tag::device) {
1531 // The sink is not a device port, skip
1532 continue;
1533 }
1534 if (count_any(mmapSources, route.sourcePortIds)) {
1535 AudioMMapPolicyInfo policyInfo;
1536 policyInfo.device = sinkPortIt->ext.get<AudioPortExt::Tag::device>().device;
1537 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1538 // default implementation.
1539 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1540 _aidl_return->push_back(policyInfo);
1541 }
1542 }
1543 }
1544 return ndk::ScopedAStatus::ok();
1545}
1546
Eric Laurente2432ea2023-01-12 17:47:31 +01001547ndk::ScopedAStatus Module::supportsVariableLatency(bool* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301548 LOG(DEBUG) << __func__ << ": " << mType;
Eric Laurente2432ea2023-01-12 17:47:31 +01001549 *_aidl_return = false;
1550 return ndk::ScopedAStatus::ok();
1551}
1552
jiabinb76981e2023-01-18 00:58:30 +00001553ndk::ScopedAStatus Module::getAAudioMixerBurstCount(int32_t* _aidl_return) {
1554 if (!isMmapSupported()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301555 LOG(DEBUG) << __func__ << ": " << mType << ": mmap is not supported ";
jiabinb76981e2023-01-18 00:58:30 +00001556 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1557 }
1558 *_aidl_return = DEFAULT_AAUDIO_MIXER_BURST_COUNT;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301559 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
jiabinb76981e2023-01-18 00:58:30 +00001560 return ndk::ScopedAStatus::ok();
1561}
1562
1563ndk::ScopedAStatus Module::getAAudioHardwareBurstMinUsec(int32_t* _aidl_return) {
1564 if (!isMmapSupported()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301565 LOG(DEBUG) << __func__ << ": " << mType << ": mmap is not supported ";
jiabinb76981e2023-01-18 00:58:30 +00001566 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1567 }
1568 *_aidl_return = DEFAULT_AAUDIO_HARDWARE_BURST_MIN_DURATION_US;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301569 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
jiabinb76981e2023-01-18 00:58:30 +00001570 return ndk::ScopedAStatus::ok();
1571}
1572
1573bool Module::isMmapSupported() {
1574 if (mIsMmapSupported.has_value()) {
1575 return mIsMmapSupported.value();
1576 }
1577 std::vector<AudioMMapPolicyInfo> mmapPolicyInfos;
1578 if (!getMmapPolicyInfos(AudioMMapPolicyType::DEFAULT, &mmapPolicyInfos).isOk()) {
1579 mIsMmapSupported = false;
1580 } else {
1581 mIsMmapSupported =
1582 std::find_if(mmapPolicyInfos.begin(), mmapPolicyInfos.end(), [](const auto& info) {
1583 return info.mmapPolicy == AudioMMapPolicy::AUTO ||
1584 info.mmapPolicy == AudioMMapPolicy::ALWAYS;
1585 }) != mmapPolicyInfos.end();
1586 }
1587 return mIsMmapSupported.value();
1588}
1589
Mikhail Naganova92039a2023-12-20 14:27:22 -08001590ndk::ScopedAStatus Module::populateConnectedDevicePort(AudioPort* audioPort, int32_t) {
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001591 if (audioPort->ext.getTag() != AudioPortExt::device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301592 LOG(ERROR) << __func__ << ": " << mType << ": not a device port: " << audioPort->toString();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001593 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1594 }
1595 const auto& devicePort = audioPort->ext.get<AudioPortExt::device>();
1596 if (!devicePort.device.type.connection.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301597 LOG(ERROR) << __func__ << ": " << mType << ": module implementation must override "
1598 "'populateConnectedDevicePort' "
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001599 << "to handle connection of external devices.";
1600 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1601 }
Jaideep Sharma559a4912024-03-07 10:05:51 +05301602 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
jiabin253bd322023-01-25 23:57:31 +00001603 return ndk::ScopedAStatus::ok();
1604}
1605
1606ndk::ScopedAStatus Module::checkAudioPatchEndpointsMatch(
1607 const std::vector<AudioPortConfig*>& sources __unused,
1608 const std::vector<AudioPortConfig*>& sinks __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301609 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
jiabin253bd322023-01-25 23:57:31 +00001610 return ndk::ScopedAStatus::ok();
1611}
1612
jiabin783c48b2023-02-28 18:28:06 +00001613void Module::onExternalDeviceConnectionChanged(
1614 const ::aidl::android::media::audio::common::AudioPort& audioPort __unused,
1615 bool connected __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301616 LOG(DEBUG) << __func__ << ": " << mType << ": do nothing and return";
jiabin783c48b2023-02-28 18:28:06 +00001617}
1618
jiabindd23b0e2023-12-11 19:10:05 +00001619void Module::onPrepareToDisconnectExternalDevice(
1620 const ::aidl::android::media::audio::common::AudioPort& audioPort __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301621 LOG(DEBUG) << __func__ << ": " << mType << ": do nothing and return";
jiabindd23b0e2023-12-11 19:10:05 +00001622}
1623
jiabin783c48b2023-02-28 18:28:06 +00001624ndk::ScopedAStatus Module::onMasterMuteChanged(bool mute __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301625 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
jiabin783c48b2023-02-28 18:28:06 +00001626 return ndk::ScopedAStatus::ok();
1627}
1628
1629ndk::ScopedAStatus Module::onMasterVolumeChanged(float volume __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301630 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
jiabin783c48b2023-02-28 18:28:06 +00001631 return ndk::ScopedAStatus::ok();
1632}
1633
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +00001634std::vector<MicrophoneInfo> Module::getMicrophoneInfos() {
1635 std::vector<MicrophoneInfo> result;
1636 Configuration& config = getConfig();
1637 for (const AudioPort& port : config.ports) {
1638 if (port.ext.getTag() == AudioPortExt::Tag::device) {
1639 const AudioDeviceType deviceType =
1640 port.ext.get<AudioPortExt::Tag::device>().device.type.type;
1641 if (deviceType == AudioDeviceType::IN_MICROPHONE ||
1642 deviceType == AudioDeviceType::IN_MICROPHONE_BACK) {
1643 // Placeholder values. Vendor implementations must populate MicrophoneInfo
1644 // accordingly based on their physical microphone parameters.
1645 result.push_back(MicrophoneInfo{
1646 .id = port.name,
1647 .device = port.ext.get<AudioPortExt::Tag::device>().device,
1648 .group = 0,
1649 .indexInTheGroup = 0,
1650 });
1651 }
1652 }
1653 }
1654 return result;
1655}
1656
Ram Mohan18f0d512023-07-01 00:47:09 +05301657ndk::ScopedAStatus Module::bluetoothParametersUpdated() {
1658 return mStreams.bluetoothParametersUpdated();
1659}
1660
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001661} // namespace aidl::android::hardware::audio::core