blob: 3bbea1d973d993e7e5d60b96a3e2b2a7fbbd4c5b [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};
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000217 StreamContext temp(
218 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
219 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
Mikhail Naganov13501872023-10-18 16:15:46 -0700220 portConfigIt->format.value(), portConfigIt->channelMask.value(),
Mikhail Naganova92039a2023-12-20 14:27:22 -0800221 portConfigIt->sampleRate.value().value, flags, nominalLatencyMs,
Mikhail Naganovb42a69e2023-06-16 12:38:25 -0700222 portConfigIt->ext.get<AudioPortExt::mix>().handle,
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000223 std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames),
Mikhail Naganov3c8b6ce2023-10-31 11:20:30 -0700224 asyncCallback, outEventCallback,
225 std::weak_ptr<sounddose::StreamDataProcessorInterface>{}, params);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000226 if (temp.isValid()) {
227 *out_context = std::move(temp);
228 } else {
229 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
230 }
231 } else {
232 // TODO: Implement simulation of MMAP buffer allocation
233 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000234 return ndk::ScopedAStatus::ok();
235}
236
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000237std::vector<AudioDevice> Module::findConnectedDevices(int32_t portConfigId) {
238 std::vector<AudioDevice> result;
239 auto& ports = getConfig().ports;
240 auto portIds = portIdsFromPortConfigIds(findConnectedPortConfigIds(portConfigId));
241 for (auto it = portIds.begin(); it != portIds.end(); ++it) {
242 auto portIt = findById<AudioPort>(ports, *it);
243 if (portIt != ports.end() && portIt->ext.getTag() == AudioPortExt::Tag::device) {
244 result.push_back(portIt->ext.template get<AudioPortExt::Tag::device>().device);
245 }
246 }
247 return result;
248}
249
250std::set<int32_t> Module::findConnectedPortConfigIds(int32_t portConfigId) {
251 std::set<int32_t> result;
252 auto patchIdsRange = mPatches.equal_range(portConfigId);
253 auto& patches = getConfig().patches;
254 for (auto it = patchIdsRange.first; it != patchIdsRange.second; ++it) {
255 auto patchIt = findById<AudioPatch>(patches, it->second);
256 if (patchIt == patches.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530257 LOG(FATAL) << __func__ << ": " << mType << ": patch with id " << it->second
258 << " taken from mPatches "
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000259 << "not found in the configuration";
260 }
261 if (std::find(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end(),
262 portConfigId) != patchIt->sourcePortConfigIds.end()) {
263 result.insert(patchIt->sinkPortConfigIds.begin(), patchIt->sinkPortConfigIds.end());
264 } else {
265 result.insert(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end());
266 }
267 }
268 return result;
269}
270
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000271ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) {
272 auto& configs = getConfig().portConfigs;
273 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
274 if (portConfigIt == configs.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530275 LOG(ERROR) << __func__ << ": " << mType << ": existing port config id " << in_portConfigId
276 << " not found";
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000277 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
278 }
279 const int32_t portId = portConfigIt->portId;
280 // In our implementation, configs of mix ports always have unique IDs.
281 CHECK(portId != in_portConfigId);
282 auto& ports = getConfig().ports;
283 auto portIt = findById<AudioPort>(ports, portId);
284 if (portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530285 LOG(ERROR) << __func__ << ": " << mType << ": port id " << portId
286 << " used by port config id " << in_portConfigId << " not found";
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000287 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
288 }
289 if (mStreams.count(in_portConfigId) != 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530290 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000291 << " already has a stream opened on it";
292 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
293 }
294 if (portIt->ext.getTag() != AudioPortExt::Tag::mix) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530295 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000296 << " does not correspond to a mix port";
297 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
298 }
Mikhail Naganovb511b8a2023-05-15 14:35:24 -0700299 const size_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000300 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530301 LOG(ERROR) << __func__ << ": " << mType << ": port id " << portId
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000302 << " has already reached maximum allowed opened stream count: "
303 << maxOpenStreamCount;
304 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
305 }
306 *port = &(*portIt);
307 return ndk::ScopedAStatus::ok();
308}
309
Mikhail Naganova92039a2023-12-20 14:27:22 -0800310bool Module::generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) {
311 const bool allowDynamicConfig = port.ext.getTag() == AudioPortExt::device;
312 for (const auto& profile : port.profiles) {
313 if (isDynamicProfile(profile)) continue;
314 config->format = profile.format;
315 config->channelMask = *profile.channelMasks.begin();
316 config->sampleRate = Int{.value = *profile.sampleRates.begin()};
317 config->flags = port.flags;
318 config->ext = port.ext;
319 return true;
320 }
321 if (allowDynamicConfig) {
322 config->format = AudioFormatDescription{};
323 config->channelMask = AudioChannelLayout{};
324 config->sampleRate = Int{.value = 0};
325 config->flags = port.flags;
326 config->ext = port.ext;
327 return true;
328 }
Jaideep Sharma559a4912024-03-07 10:05:51 +0530329 LOG(ERROR) << __func__ << ": " << mType << ": port " << port.id << " only has dynamic profiles";
Mikhail Naganova92039a2023-12-20 14:27:22 -0800330 return false;
331}
332
Lorena Torres-Huertaf7492512023-01-14 02:49:41 +0000333void Module::populateConnectedProfiles() {
334 Configuration& config = getConfig();
335 for (const AudioPort& port : config.ports) {
336 if (port.ext.getTag() == AudioPortExt::device) {
337 if (auto devicePort = port.ext.get<AudioPortExt::device>();
338 !devicePort.device.type.connection.empty() && port.profiles.empty()) {
339 if (auto connIt = config.connectedProfiles.find(port.id);
340 connIt == config.connectedProfiles.end()) {
341 config.connectedProfiles.emplace(
342 port.id, internal::getStandard16And24BitPcmAudioProfiles());
343 }
344 }
345 }
346 }
347}
348
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000349template <typename C>
350std::set<int32_t> Module::portIdsFromPortConfigIds(C portConfigIds) {
351 std::set<int32_t> result;
352 auto& portConfigs = getConfig().portConfigs;
353 for (auto it = portConfigIds.begin(); it != portConfigIds.end(); ++it) {
354 auto portConfigIt = findById<AudioPortConfig>(portConfigs, *it);
355 if (portConfigIt != portConfigs.end()) {
356 result.insert(portConfigIt->portId);
357 }
358 }
359 return result;
360}
361
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000362std::unique_ptr<Module::Configuration> Module::initializeConfig() {
363 return internal::getConfiguration(getType());
Peter Yoon918a6a52023-07-13 17:04:37 +0900364}
365
Mikhail Naganov13501872023-10-18 16:15:46 -0700366int32_t Module::getNominalLatencyMs(const AudioPortConfig&) {
367 // Arbitrary value. Implementations must override this method to provide their actual latency.
368 static constexpr int32_t kLatencyMs = 5;
369 return kLatencyMs;
370}
371
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700372std::vector<AudioRoute*> Module::getAudioRoutesForAudioPortImpl(int32_t portId) {
373 std::vector<AudioRoute*> result;
374 auto& routes = getConfig().routes;
375 for (auto& r : routes) {
376 const auto& srcs = r.sourcePortIds;
377 if (r.sinkPortId == portId || std::find(srcs.begin(), srcs.end(), portId) != srcs.end()) {
378 result.push_back(&r);
379 }
380 }
381 return result;
382}
383
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000384Module::Configuration& Module::getConfig() {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000385 if (!mConfig) {
Peter Yoon918a6a52023-07-13 17:04:37 +0900386 mConfig = std::move(initializeConfig());
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000387 }
388 return *mConfig;
389}
390
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700391std::set<int32_t> Module::getRoutableAudioPortIds(int32_t portId,
392 std::vector<AudioRoute*>* routes) {
393 std::vector<AudioRoute*> routesStorage;
394 if (routes == nullptr) {
395 routesStorage = getAudioRoutesForAudioPortImpl(portId);
396 routes = &routesStorage;
397 }
398 std::set<int32_t> result;
399 for (AudioRoute* r : *routes) {
400 if (r->sinkPortId == portId) {
401 result.insert(r->sourcePortIds.begin(), r->sourcePortIds.end());
402 } else {
403 result.insert(r->sinkPortId);
404 }
405 }
406 return result;
407}
408
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000409void Module::registerPatch(const AudioPatch& patch) {
410 auto& configs = getConfig().portConfigs;
411 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
412 for (auto portConfigId : portConfigIds) {
413 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
414 if (configIt != configs.end()) {
415 mPatches.insert(std::pair{portConfigId, patch.id});
416 if (configIt->portId != portConfigId) {
417 mPatches.insert(std::pair{configIt->portId, patch.id});
418 }
419 }
420 };
421 };
422 do_insert(patch.sourcePortConfigIds);
423 do_insert(patch.sinkPortConfigIds);
424}
425
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700426ndk::ScopedAStatus Module::updateStreamsConnectedState(const AudioPatch& oldPatch,
427 const AudioPatch& newPatch) {
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700428 // Notify streams about the new set of devices they are connected to.
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700429 auto maybeFailure = ndk::ScopedAStatus::ok();
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700430 using Connections =
431 std::map<int32_t /*mixPortConfigId*/, std::set<int32_t /*devicePortConfigId*/>>;
432 Connections oldConnections, newConnections;
433 auto fillConnectionsHelper = [&](Connections& connections,
434 const std::vector<int32_t>& mixPortCfgIds,
435 const std::vector<int32_t>& devicePortCfgIds) {
436 for (int32_t mixPortCfgId : mixPortCfgIds) {
437 connections[mixPortCfgId].insert(devicePortCfgIds.begin(), devicePortCfgIds.end());
438 }
439 };
440 auto fillConnections = [&](Connections& connections, const AudioPatch& patch) {
441 if (std::find_if(patch.sourcePortConfigIds.begin(), patch.sourcePortConfigIds.end(),
442 [&](int32_t portConfigId) { return mStreams.count(portConfigId) > 0; }) !=
443 patch.sourcePortConfigIds.end()) {
444 // Sources are mix ports.
445 fillConnectionsHelper(connections, patch.sourcePortConfigIds, patch.sinkPortConfigIds);
446 } else if (std::find_if(patch.sinkPortConfigIds.begin(), patch.sinkPortConfigIds.end(),
447 [&](int32_t portConfigId) {
448 return mStreams.count(portConfigId) > 0;
449 }) != patch.sinkPortConfigIds.end()) {
450 // Sources are device ports.
451 fillConnectionsHelper(connections, patch.sinkPortConfigIds, patch.sourcePortConfigIds);
452 } // Otherwise, there are no streams to notify.
453 };
454 fillConnections(oldConnections, oldPatch);
455 fillConnections(newConnections, newPatch);
456
457 std::for_each(oldConnections.begin(), oldConnections.end(), [&](const auto& connectionPair) {
458 const int32_t mixPortConfigId = connectionPair.first;
459 if (auto it = newConnections.find(mixPortConfigId);
460 it == newConnections.end() || it->second != connectionPair.second) {
461 if (auto status = mStreams.setStreamConnectedDevices(mixPortConfigId, {});
462 status.isOk()) {
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700463 LOG(DEBUG) << "updateStreamsConnectedState: The stream on port config id "
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700464 << mixPortConfigId << " has been disconnected";
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700465 } else {
466 // Disconnection is tricky to roll back, just register a failure.
467 maybeFailure = std::move(status);
468 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000469 }
470 });
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700471 if (!maybeFailure.isOk()) return maybeFailure;
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700472 std::set<int32_t> idsToDisconnectOnFailure;
473 std::for_each(newConnections.begin(), newConnections.end(), [&](const auto& connectionPair) {
474 const int32_t mixPortConfigId = connectionPair.first;
475 if (auto it = oldConnections.find(mixPortConfigId);
476 it == oldConnections.end() || it->second != connectionPair.second) {
477 const auto connectedDevices = findConnectedDevices(mixPortConfigId);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700478 if (connectedDevices.empty()) {
479 // This is important as workers use the vector size to derive the connection status.
480 LOG(FATAL) << "updateStreamsConnectedState: No connected devices found for port "
481 "config id "
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700482 << mixPortConfigId;
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700483 }
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700484 if (auto status = mStreams.setStreamConnectedDevices(mixPortConfigId, connectedDevices);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700485 status.isOk()) {
486 LOG(DEBUG) << "updateStreamsConnectedState: The stream on port config id "
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700487 << mixPortConfigId << " has been connected to: "
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700488 << ::android::internal::ToString(connectedDevices);
489 } else {
490 maybeFailure = std::move(status);
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700491 idsToDisconnectOnFailure.insert(mixPortConfigId);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700492 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000493 }
494 });
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700495 if (!maybeFailure.isOk()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530496 LOG(WARNING) << __func__ << ": " << mType
497 << ": Due to a failure, disconnecting streams on port config ids "
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700498 << ::android::internal::ToString(idsToDisconnectOnFailure);
499 std::for_each(idsToDisconnectOnFailure.begin(), idsToDisconnectOnFailure.end(),
500 [&](const auto& portConfigId) {
501 auto status = mStreams.setStreamConnectedDevices(portConfigId, {});
502 (void)status.isOk(); // Can't do much about a failure here.
503 });
504 return maybeFailure;
505 }
506 return ndk::ScopedAStatus::ok();
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000507}
508
Mikhail Naganov00603d12022-05-02 22:52:13 +0000509ndk::ScopedAStatus Module::setModuleDebug(
510 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700511 LOG(DEBUG) << __func__ << ": " << mType << ": old flags:" << mDebug.toString()
Mikhail Naganov00603d12022-05-02 22:52:13 +0000512 << ", new flags: " << in_debug.toString();
513 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
514 !mConnectedDevicePorts.empty()) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700515 LOG(ERROR) << __func__ << ": " << mType
Jaideep Sharma559a4912024-03-07 10:05:51 +0530516 << ": attempting to change device connections simulation while "
517 "having external "
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700518 << "devices connected";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000519 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
520 }
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000521 if (in_debug.streamTransientStateDelayMs < 0) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700522 LOG(ERROR) << __func__ << ": " << mType << ": streamTransientStateDelayMs is negative: "
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000523 << in_debug.streamTransientStateDelayMs;
524 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
525 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000526 mDebug = in_debug;
527 return ndk::ScopedAStatus::ok();
528}
529
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000530ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700531 *_aidl_return = nullptr;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530532 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000533 return ndk::ScopedAStatus::ok();
534}
535
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000536ndk::ScopedAStatus Module::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700537 *_aidl_return = nullptr;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530538 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000539 return ndk::ScopedAStatus::ok();
540}
541
Mikhail Naganov7499a002023-02-27 18:51:44 -0800542ndk::ScopedAStatus Module::getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700543 *_aidl_return = nullptr;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530544 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
Mikhail Naganov7499a002023-02-27 18:51:44 -0800545 return ndk::ScopedAStatus::ok();
546}
547
Mikhail Naganovb5647da2023-03-06 14:37:38 -0800548ndk::ScopedAStatus Module::getBluetoothLe(std::shared_ptr<IBluetoothLe>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700549 *_aidl_return = nullptr;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530550 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
Mikhail Naganovb5647da2023-03-06 14:37:38 -0800551 return ndk::ScopedAStatus::ok();
552}
553
Mikhail Naganov00603d12022-05-02 22:52:13 +0000554ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
555 AudioPort* _aidl_return) {
556 const int32_t templateId = in_templateIdAndAdditionalData.id;
557 auto& ports = getConfig().ports;
558 AudioPort connectedPort;
559 { // Scope the template port so that we don't accidentally modify it.
560 auto templateIt = findById<AudioPort>(ports, templateId);
561 if (templateIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530562 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId << " not found";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000563 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
564 }
565 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530566 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
567 << " is not a device port";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000568 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
569 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000570 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
571 if (templateDevicePort.device.type.connection.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530572 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
573 << " is permanently attached";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000574 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
575 }
Mikhail Naganovfcf980e2023-09-07 16:30:11 -0700576 if (mConnectedDevicePorts.find(templateId) != mConnectedDevicePorts.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530577 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
578 << " is a connected device port";
Mikhail Naganovfcf980e2023-09-07 16:30:11 -0700579 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
580 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000581 // Postpone id allocation until we ensure that there are no client errors.
582 connectedPort = *templateIt;
583 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
584 const auto& inputDevicePort =
585 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
586 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
587 connectedDevicePort.device.address = inputDevicePort.device.address;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530588 LOG(DEBUG) << __func__ << ": " << mType << ": device port " << connectedPort.id
589 << " device set to " << connectedDevicePort.device.toString();
Mikhail Naganov00603d12022-05-02 22:52:13 +0000590 // Check if there is already a connected port with for the same external device.
Jaideep Sharma559a4912024-03-07 10:05:51 +0530591
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700592 for (auto connectedPortPair : mConnectedDevicePorts) {
593 auto connectedPortIt = findById<AudioPort>(ports, connectedPortPair.first);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000594 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
595 connectedDevicePort.device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530596 LOG(ERROR) << __func__ << ": " << mType << ": device "
597 << connectedDevicePort.device.toString()
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700598 << " is already connected at the device port id "
599 << connectedPortPair.first;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000600 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
601 }
602 }
603 }
604
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700605 // Two main cases are considered with regard to the profiles of the connected device port:
606 //
607 // 1. If the template device port has dynamic profiles, and at least one routable mix
608 // port also has dynamic profiles, it means that after connecting the device, the
609 // connected device port must have profiles populated with actual capabilities of
610 // the connected device, and dynamic of routable mix ports will be filled
611 // according to these capabilities. An example of this case is connection of an
612 // HDMI or USB device. For USB handled by ADSP, there can be mix ports with static
613 // profiles, and one dedicated mix port for "hi-fi" playback. The latter is left with
614 // dynamic profiles so that they can be populated with actual capabilities of
615 // the connected device.
616 //
617 // 2. If the template device port has dynamic profiles, while all routable mix ports
618 // have static profiles, it means that after connecting the device, the connected
619 // device port can be left with dynamic profiles, and profiles of mix ports are
620 // left untouched. An example of this case is connection of an analog wired
621 // headset, it should be treated in the same way as a speaker.
622 //
623 // Yet another possible case is when both the template device port and all routable
624 // mix ports have static profiles. This is allowed and handled correctly, however, it
625 // is not very practical, since these profiles are likely duplicates of each other.
626
627 std::vector<AudioRoute*> routesToMixPorts = getAudioRoutesForAudioPortImpl(templateId);
628 std::set<int32_t> routableMixPortIds = getRoutableAudioPortIds(templateId, &routesToMixPorts);
Mikhail Naganova92039a2023-12-20 14:27:22 -0800629 const int32_t nextPortId = getConfig().nextPortId++;
Mikhail Naganov55045b52023-10-24 17:03:50 -0700630 if (!mDebug.simulateDeviceConnections) {
631 // Even if the device port has static profiles, the HAL module might need to update
632 // them, or abort the connection process.
Mikhail Naganova92039a2023-12-20 14:27:22 -0800633 RETURN_STATUS_IF_ERROR(populateConnectedDevicePort(&connectedPort, nextPortId));
Mikhail Naganov55045b52023-10-24 17:03:50 -0700634 } else if (hasDynamicProfilesOnly(connectedPort.profiles)) {
635 auto& connectedProfiles = getConfig().connectedProfiles;
636 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
637 connectedProfilesIt != connectedProfiles.end()) {
638 connectedPort.profiles = connectedProfilesIt->second;
Mikhail Naganovfcf980e2023-09-07 16:30:11 -0700639 }
Mikhail Naganov55045b52023-10-24 17:03:50 -0700640 }
641 if (hasDynamicProfilesOnly(connectedPort.profiles)) {
642 // Possible case 2. Check if all routable mix ports have static profiles.
643 if (auto dynamicMixPortIt = std::find_if(ports.begin(), ports.end(),
644 [&routableMixPortIds](const auto& p) {
645 return routableMixPortIds.count(p.id) > 0 &&
646 hasDynamicProfilesOnly(p.profiles);
647 });
648 dynamicMixPortIt != ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530649 LOG(ERROR) << __func__ << ": " << mType
650 << ": connected port only has dynamic profiles after connecting "
Mikhail Naganov55045b52023-10-24 17:03:50 -0700651 << "external device " << connectedPort.toString() << ", and there exist "
652 << "a routable mix port with dynamic profiles: "
653 << dynamicMixPortIt->toString();
654 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530655 }
656 }
657
Mikhail Naganova92039a2023-12-20 14:27:22 -0800658 connectedPort.id = nextPortId;
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700659 auto [connectedPortsIt, _] =
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700660 mConnectedDevicePorts.insert(std::pair(connectedPort.id, std::set<int32_t>()));
Jaideep Sharma559a4912024-03-07 10:05:51 +0530661 LOG(DEBUG) << __func__ << ": " << mType << ": template port " << templateId
662 << " external device connected, "
Mikhail Naganov00603d12022-05-02 22:52:13 +0000663 << "connected port ID " << connectedPort.id;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000664 ports.push_back(connectedPort);
jiabin783c48b2023-02-28 18:28:06 +0000665 onExternalDeviceConnectionChanged(connectedPort, true /*connected*/);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000666
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700667 // For routes where the template port is a source, add the connected port to sources,
668 // otherwise, create a new route by copying from the route for the template port.
Mikhail Naganov00603d12022-05-02 22:52:13 +0000669 std::vector<AudioRoute> newRoutes;
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700670 for (AudioRoute* r : routesToMixPorts) {
671 if (r->sinkPortId == templateId) {
672 newRoutes.push_back(AudioRoute{.sourcePortIds = r->sourcePortIds,
673 .sinkPortId = connectedPort.id,
674 .isExclusive = r->isExclusive});
Mikhail Naganov00603d12022-05-02 22:52:13 +0000675 } else {
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700676 r->sourcePortIds.push_back(connectedPort.id);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000677 }
678 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700679 auto& routes = getConfig().routes;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000680 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
681
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700682 if (!hasDynamicProfilesOnly(connectedPort.profiles) && !routableMixPortIds.empty()) {
683 // Note: this is a simplistic approach assuming that a mix port can only be populated
684 // from a single device port. Implementing support for stuffing dynamic profiles with
685 // a superset of all profiles from all routable dynamic device ports would be more involved.
686 for (auto& port : ports) {
687 if (routableMixPortIds.count(port.id) == 0) continue;
688 if (hasDynamicProfilesOnly(port.profiles)) {
689 port.profiles = connectedPort.profiles;
690 connectedPortsIt->second.insert(port.id);
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700691 } else {
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700692 // Check if profiles are not all dynamic because they were populated by
693 // a previous connection. Otherwise, it means that they are actually static.
694 for (const auto& cp : mConnectedDevicePorts) {
695 if (cp.second.count(port.id) > 0) {
696 connectedPortsIt->second.insert(port.id);
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700697 break;
698 }
699 }
700 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700701 }
702 }
703 *_aidl_return = std::move(connectedPort);
704
Mikhail Naganov00603d12022-05-02 22:52:13 +0000705 return ndk::ScopedAStatus::ok();
706}
707
708ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
709 auto& ports = getConfig().ports;
710 auto portIt = findById<AudioPort>(ports, in_portId);
711 if (portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530712 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000713 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
714 }
715 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530716 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
717 << " is not a device port";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000718 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
719 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700720 auto connectedPortsIt = mConnectedDevicePorts.find(in_portId);
721 if (connectedPortsIt == mConnectedDevicePorts.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530722 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
723 << " is not a connected device port";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000724 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
725 }
726 auto& configs = getConfig().portConfigs;
727 auto& initials = getConfig().initialConfigs;
728 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
729 if (config.portId == in_portId) {
730 // Check if the configuration was provided by the client.
731 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
732 return initialIt == initials.end() || config != *initialIt;
733 }
734 return false;
735 });
736 if (configIt != configs.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530737 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
738 << " has a non-default config with id " << configIt->id;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000739 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
740 }
jiabin783c48b2023-02-28 18:28:06 +0000741 onExternalDeviceConnectionChanged(*portIt, false /*connected*/);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000742 ports.erase(portIt);
Jaideep Sharma559a4912024-03-07 10:05:51 +0530743 LOG(DEBUG) << __func__ << ": " << mType << ": connected device port " << in_portId
744 << " released";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000745
746 auto& routes = getConfig().routes;
747 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
748 if (routesIt->sinkPortId == in_portId) {
749 routesIt = routes.erase(routesIt);
750 } else {
751 // Note: the list of sourcePortIds can't become empty because there must
752 // be the id of the template port in the route.
753 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
754 ++routesIt;
755 }
756 }
757
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700758 // Clear profiles for mix ports that are not connected to any other ports.
759 std::set<int32_t> mixPortsToClear = std::move(connectedPortsIt->second);
760 mConnectedDevicePorts.erase(connectedPortsIt);
761 for (const auto& connectedPort : mConnectedDevicePorts) {
762 for (int32_t mixPortId : connectedPort.second) {
763 mixPortsToClear.erase(mixPortId);
764 }
765 }
766 for (int32_t mixPortId : mixPortsToClear) {
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700767 auto mixPortIt = findById<AudioPort>(ports, mixPortId);
768 if (mixPortIt != ports.end()) {
769 mixPortIt->profiles = {};
770 }
771 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700772
Mikhail Naganov00603d12022-05-02 22:52:13 +0000773 return ndk::ScopedAStatus::ok();
774}
775
jiabindd23b0e2023-12-11 19:10:05 +0000776ndk::ScopedAStatus Module::prepareToDisconnectExternalDevice(int32_t in_portId) {
777 auto& ports = getConfig().ports;
778 auto portIt = findById<AudioPort>(ports, in_portId);
779 if (portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530780 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
jiabindd23b0e2023-12-11 19:10:05 +0000781 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
782 }
783 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530784 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
785 << " is not a device port";
jiabindd23b0e2023-12-11 19:10:05 +0000786 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
787 }
788 auto connectedPortsIt = mConnectedDevicePorts.find(in_portId);
789 if (connectedPortsIt == mConnectedDevicePorts.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530790 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
791 << " is not a connected device port";
jiabindd23b0e2023-12-11 19:10:05 +0000792 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
793 }
794
795 onPrepareToDisconnectExternalDevice(*portIt);
796
797 return ndk::ScopedAStatus::ok();
798}
799
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000800ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
801 *_aidl_return = getConfig().patches;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530802 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " patches";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000803 return ndk::ScopedAStatus::ok();
804}
805
806ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
807 auto& ports = getConfig().ports;
808 auto portIt = findById<AudioPort>(ports, in_portId);
809 if (portIt != ports.end()) {
810 *_aidl_return = *portIt;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530811 LOG(DEBUG) << __func__ << ": " << mType << ": returning port by id " << in_portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000812 return ndk::ScopedAStatus::ok();
813 }
Jaideep Sharma559a4912024-03-07 10:05:51 +0530814 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000815 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
816}
817
818ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
819 *_aidl_return = getConfig().portConfigs;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530820 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size()
821 << " port configs";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000822 return ndk::ScopedAStatus::ok();
823}
824
825ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
826 *_aidl_return = getConfig().ports;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530827 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " ports";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000828 return ndk::ScopedAStatus::ok();
829}
830
831ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
832 *_aidl_return = getConfig().routes;
Jaideep Sharma559a4912024-03-07 10:05:51 +0530833 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " routes";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000834 return ndk::ScopedAStatus::ok();
835}
836
Mikhail Naganov00603d12022-05-02 22:52:13 +0000837ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
838 std::vector<AudioRoute>* _aidl_return) {
839 auto& ports = getConfig().ports;
840 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530841 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000842 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
843 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700844 std::vector<AudioRoute*> routes = getAudioRoutesForAudioPortImpl(in_portId);
845 std::transform(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
846 [](auto rptr) { return *rptr; });
Mikhail Naganov00603d12022-05-02 22:52:13 +0000847 return ndk::ScopedAStatus::ok();
848}
849
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000850ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
851 OpenInputStreamReturn* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530852 LOG(DEBUG) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
853 << ", buffer size " << in_args.bufferSizeFrames << " frames";
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000854 AudioPort* port = nullptr;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700855 RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000856 if (port->flags.getTag() != AudioIoFlags::Tag::input) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530857 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000858 << " does not correspond to an input mix port";
859 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
860 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000861 StreamContext context;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700862 RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
863 nullptr, nullptr, &context));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000864 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000865 std::shared_ptr<StreamIn> stream;
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700866 RETURN_STATUS_IF_ERROR(createInputStream(std::move(context), in_args.sinkMetadata,
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +0000867 getMicrophoneInfos(), &stream));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000868 StreamWrapper streamWrapper(stream);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700869 if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
870 RETURN_STATUS_IF_ERROR(
871 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
872 }
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000873 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
874 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000875 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000876 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000877 return ndk::ScopedAStatus::ok();
878}
879
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000880ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
881 OpenOutputStreamReturn* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530882 LOG(DEBUG) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
883 << ", has offload info? " << (in_args.offloadInfo.has_value()) << ", buffer size "
884 << in_args.bufferSizeFrames << " frames";
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000885 AudioPort* port = nullptr;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700886 RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000887 if (port->flags.getTag() != AudioIoFlags::Tag::output) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530888 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000889 << " does not correspond to an output mix port";
890 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
891 }
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000892 const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
893 AudioOutputFlags::COMPRESS_OFFLOAD);
894 if (isOffload && !in_args.offloadInfo.has_value()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530895 LOG(ERROR) << __func__ << ": " << mType << ": port id " << port->id
Mikhail Naganov111e0ce2022-06-17 21:41:19 +0000896 << " has COMPRESS_OFFLOAD flag set, requires offload info";
897 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
898 }
Mikhail Naganov30301a42022-09-13 01:20:45 +0000899 const bool isNonBlocking = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
900 AudioOutputFlags::NON_BLOCKING);
901 if (isNonBlocking && in_args.callback == nullptr) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530902 LOG(ERROR) << __func__ << ": " << mType << ": port id " << port->id
Mikhail Naganov30301a42022-09-13 01:20:45 +0000903 << " has NON_BLOCKING flag set, requires async callback";
904 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
905 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000906 StreamContext context;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700907 RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
908 isNonBlocking ? in_args.callback : nullptr,
909 in_args.eventCallback, &context));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000910 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000911 std::shared_ptr<StreamOut> stream;
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700912 RETURN_STATUS_IF_ERROR(createOutputStream(std::move(context), in_args.sourceMetadata,
Mikhail Naganov9d16a6a2023-06-26 17:21:04 -0700913 in_args.offloadInfo, &stream));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000914 StreamWrapper streamWrapper(stream);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700915 if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
916 RETURN_STATUS_IF_ERROR(
917 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
918 }
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000919 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
920 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000921 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000922 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000923 return ndk::ScopedAStatus::ok();
924}
925
Mikhail Naganov74927202022-12-19 16:37:14 +0000926ndk::ScopedAStatus Module::getSupportedPlaybackRateFactors(
927 SupportedPlaybackRateFactors* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530928 LOG(DEBUG) << __func__ << ": " << mType;
Mikhail Naganov74927202022-12-19 16:37:14 +0000929 (void)_aidl_return;
930 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
931}
932
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000933ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530934 LOG(DEBUG) << __func__ << ": " << mType << ": requested patch " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000935 if (in_requested.sourcePortConfigIds.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530936 LOG(ERROR) << __func__ << ": " << mType << ": requested patch has empty sources list";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000937 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
938 }
939 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530940 LOG(ERROR) << __func__ << ": " << mType
941 << ": requested patch has duplicate ids in the sources list";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000942 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
943 }
944 if (in_requested.sinkPortConfigIds.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530945 LOG(ERROR) << __func__ << ": " << mType << ": requested patch has empty sinks list";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000946 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
947 }
948 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530949 LOG(ERROR) << __func__ << ": " << mType
950 << ": requested patch has duplicate ids in the sinks list";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000951 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
952 }
953
954 auto& configs = getConfig().portConfigs;
955 std::vector<int32_t> missingIds;
956 auto sources =
957 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
958 if (!missingIds.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530959 LOG(ERROR) << __func__ << ": " << mType << ": following source port config ids not found: "
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000960 << ::android::internal::ToString(missingIds);
961 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
962 }
963 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
964 if (!missingIds.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530965 LOG(ERROR) << __func__ << ": " << mType << ": following sink 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 // bool indicates whether a non-exclusive route is available.
970 // If only an exclusive route is available, that means the patch can not be
971 // established if there is any other patch which currently uses the sink port.
972 std::map<int32_t, bool> allowedSinkPorts;
973 auto& routes = getConfig().routes;
974 for (auto src : sources) {
975 for (const auto& r : routes) {
976 const auto& srcs = r.sourcePortIds;
977 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
978 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
979 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
980 }
981 }
982 }
983 }
984 for (auto sink : sinks) {
985 if (allowedSinkPorts.count(sink->portId) == 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +0530986 LOG(ERROR) << __func__ << ": " << mType << ": there is no route to the sink port id "
987 << sink->portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000988 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
989 }
990 }
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700991 RETURN_STATUS_IF_ERROR(checkAudioPatchEndpointsMatch(sources, sinks));
jiabin253bd322023-01-25 23:57:31 +0000992
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000993 auto& patches = getConfig().patches;
994 auto existing = patches.end();
995 std::optional<decltype(mPatches)> patchesBackup;
996 if (in_requested.id != 0) {
997 existing = findById<AudioPatch>(patches, in_requested.id);
998 if (existing != patches.end()) {
999 patchesBackup = mPatches;
1000 cleanUpPatch(existing->id);
1001 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301002 LOG(ERROR) << __func__ << ": " << mType << ": not found existing patch id "
1003 << in_requested.id;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001004 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1005 }
1006 }
1007 // Validate the requested patch.
1008 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
1009 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301010 LOG(ERROR) << __func__ << ": " << mType << ": sink port id " << sinkPortId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001011 << "is exclusive and is already used by some other patch";
1012 if (patchesBackup.has_value()) {
1013 mPatches = std::move(*patchesBackup);
1014 }
1015 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1016 }
1017 }
Mikhail Naganov13501872023-10-18 16:15:46 -07001018 // Find the highest sample rate among mix port configs.
1019 std::map<int32_t, AudioPortConfig*> sampleRates;
1020 std::vector<AudioPortConfig*>& mixPortConfigs =
1021 sources[0]->ext.getTag() == AudioPortExt::mix ? sources : sinks;
1022 for (auto mix : mixPortConfigs) {
1023 sampleRates.emplace(mix->sampleRate.value().value, mix);
1024 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001025 *_aidl_return = in_requested;
Mikhail Naganov13501872023-10-18 16:15:46 -07001026 auto maxSampleRateIt = std::max_element(sampleRates.begin(), sampleRates.end());
1027 const int32_t latencyMs = getNominalLatencyMs(*(maxSampleRateIt->second));
1028 _aidl_return->minimumStreamBufferSizeFrames =
1029 calculateBufferSizeFrames(latencyMs, maxSampleRateIt->first);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +00001030 _aidl_return->latenciesMs.clear();
1031 _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
Mikhail Naganov13501872023-10-18 16:15:46 -07001032 _aidl_return->sinkPortConfigIds.size(), latencyMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001033 AudioPatch oldPatch{};
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001034 if (existing == patches.end()) {
1035 _aidl_return->id = getConfig().nextPatchId++;
1036 patches.push_back(*_aidl_return);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001037 } else {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001038 oldPatch = *existing;
Mikhail Naganovdc417732023-09-29 15:49:35 -07001039 *existing = *_aidl_return;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001040 }
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001041 patchesBackup = mPatches;
1042 registerPatch(*_aidl_return);
1043 if (auto status = updateStreamsConnectedState(oldPatch, *_aidl_return); !status.isOk()) {
1044 mPatches = std::move(*patchesBackup);
1045 if (existing == patches.end()) {
1046 patches.pop_back();
1047 } else {
1048 *existing = oldPatch;
1049 }
1050 return status;
1051 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001052
Jaideep Sharma559a4912024-03-07 10:05:51 +05301053 LOG(DEBUG) << __func__ << ": " << mType << ": " << (oldPatch.id == 0 ? "created" : "updated")
1054 << " patch " << _aidl_return->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001055 return ndk::ScopedAStatus::ok();
1056}
1057
1058ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
1059 AudioPortConfig* out_suggested, bool* _aidl_return) {
Mikhail Naganova92039a2023-12-20 14:27:22 -08001060 auto generate = [this](const AudioPort& port, AudioPortConfig* config) {
1061 return generateDefaultPortConfig(port, config);
1062 };
1063 return setAudioPortConfigImpl(in_requested, generate, out_suggested, _aidl_return);
1064}
1065
1066ndk::ScopedAStatus Module::setAudioPortConfigImpl(
1067 const AudioPortConfig& in_requested,
1068 const std::function<bool(const ::aidl::android::media::audio::common::AudioPort& port,
1069 ::aidl::android::media::audio::common::AudioPortConfig* config)>&
1070 fillPortConfig,
1071 AudioPortConfig* out_suggested, bool* applied) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301072 LOG(DEBUG) << __func__ << ": " << mType << ": requested " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001073 auto& configs = getConfig().portConfigs;
1074 auto existing = configs.end();
1075 if (in_requested.id != 0) {
1076 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
1077 existing == configs.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301078 LOG(ERROR) << __func__ << ": " << mType << ": existing port config id "
1079 << in_requested.id << " not found";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001080 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1081 }
1082 }
1083
1084 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
1085 if (portId == 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301086 LOG(ERROR) << __func__ << ": " << mType
1087 << ": requested port config does not specify portId";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001088 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1089 }
1090 auto& ports = getConfig().ports;
1091 auto portIt = findById<AudioPort>(ports, portId);
1092 if (portIt == ports.end()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301093 LOG(ERROR) << __func__ << ": " << mType
1094 << ": requested port config points to non-existent portId " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001095 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1096 }
1097 if (existing != configs.end()) {
1098 *out_suggested = *existing;
1099 } else {
1100 AudioPortConfig newConfig;
Mikhail Naganova92039a2023-12-20 14:27:22 -08001101 newConfig.portId = portIt->id;
1102 if (fillPortConfig(*portIt, &newConfig)) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001103 *out_suggested = newConfig;
1104 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301105 LOG(ERROR) << __func__ << ": " << mType
1106 << ": unable generate a default config for port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001107 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1108 }
1109 }
1110 // From this moment, 'out_suggested' is either an existing port config,
1111 // or a new generated config. Now attempt to update it according to the specified
1112 // fields of 'in_requested'.
1113
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001114 // Device ports with only dynamic profiles are used for devices that are connected via ADSP,
1115 // which takes care of their actual configuration automatically.
1116 const bool allowDynamicConfig = portIt->ext.getTag() == AudioPortExt::device &&
1117 hasDynamicProfilesOnly(portIt->profiles);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001118 bool requestedIsValid = true, requestedIsFullySpecified = true;
1119
1120 AudioIoFlags portFlags = portIt->flags;
1121 if (in_requested.flags.has_value()) {
1122 if (in_requested.flags.value() != portFlags) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301123 LOG(WARNING) << __func__ << ": " << mType << ": requested flags "
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001124 << in_requested.flags.value().toString() << " do not match port's "
1125 << portId << " flags " << portFlags.toString();
1126 requestedIsValid = false;
1127 }
1128 } else {
1129 requestedIsFullySpecified = false;
1130 }
1131
1132 AudioProfile portProfile;
1133 if (in_requested.format.has_value()) {
1134 const auto& format = in_requested.format.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001135 if ((format == AudioFormatDescription{} && allowDynamicConfig) ||
1136 findAudioProfile(*portIt, format, &portProfile)) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001137 out_suggested->format = format;
1138 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301139 LOG(WARNING) << __func__ << ": " << mType << ": requested format " << format.toString()
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001140 << " is not found in the profiles of port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001141 requestedIsValid = false;
1142 }
1143 } else {
1144 requestedIsFullySpecified = false;
1145 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001146 if (!(out_suggested->format.value() == AudioFormatDescription{} && allowDynamicConfig) &&
1147 !findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301148 LOG(ERROR) << __func__ << ": " << mType << ": port " << portId
1149 << " does not support format " << out_suggested->format.value().toString()
1150 << " anymore";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001151 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1152 }
1153
1154 if (in_requested.channelMask.has_value()) {
1155 const auto& channelMask = in_requested.channelMask.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001156 if ((channelMask == AudioChannelLayout{} && allowDynamicConfig) ||
1157 find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
1158 portProfile.channelMasks.end()) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001159 out_suggested->channelMask = channelMask;
1160 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301161 LOG(WARNING) << __func__ << ": " << mType << ": requested channel mask "
1162 << channelMask.toString() << " is not supported for the format "
1163 << portProfile.format.toString() << " by the port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001164 requestedIsValid = false;
1165 }
1166 } else {
1167 requestedIsFullySpecified = false;
1168 }
1169
1170 if (in_requested.sampleRate.has_value()) {
1171 const auto& sampleRate = in_requested.sampleRate.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001172 if ((sampleRate.value == 0 && allowDynamicConfig) ||
1173 find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001174 sampleRate.value) != portProfile.sampleRates.end()) {
1175 out_suggested->sampleRate = sampleRate;
1176 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301177 LOG(WARNING) << __func__ << ": " << mType << ": requested sample rate "
1178 << sampleRate.value << " is not supported for the format "
1179 << portProfile.format.toString() << " by the port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001180 requestedIsValid = false;
1181 }
1182 } else {
1183 requestedIsFullySpecified = false;
1184 }
1185
1186 if (in_requested.gain.has_value()) {
1187 // Let's pretend that gain can always be applied.
1188 out_suggested->gain = in_requested.gain.value();
1189 }
1190
Mikhail Naganov248e9502023-02-21 16:32:40 -08001191 if (in_requested.ext.getTag() != AudioPortExt::Tag::unspecified) {
1192 if (in_requested.ext.getTag() == out_suggested->ext.getTag()) {
1193 if (out_suggested->ext.getTag() == AudioPortExt::Tag::mix) {
Mikhail Naganovb06a4922024-03-06 16:39:50 -08001194 // 'AudioMixPortExt.handle' and '.usecase' are set by the client,
1195 // copy from in_requested.
1196 const auto& src = in_requested.ext.get<AudioPortExt::Tag::mix>();
1197 auto& dst = out_suggested->ext.get<AudioPortExt::Tag::mix>();
1198 dst.handle = src.handle;
1199 dst.usecase = src.usecase;
Mikhail Naganov248e9502023-02-21 16:32:40 -08001200 }
1201 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301202 LOG(WARNING) << __func__ << ": " << mType << ": requested ext tag "
Mikhail Naganov248e9502023-02-21 16:32:40 -08001203 << toString(in_requested.ext.getTag()) << " do not match port's tag "
1204 << toString(out_suggested->ext.getTag());
1205 requestedIsValid = false;
1206 }
1207 }
1208
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001209 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
1210 out_suggested->id = getConfig().nextPortId++;
1211 configs.push_back(*out_suggested);
Mikhail Naganova92039a2023-12-20 14:27:22 -08001212 *applied = true;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301213 LOG(DEBUG) << __func__ << ": " << mType << ": created new port config "
1214 << out_suggested->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001215 } else if (existing != configs.end() && requestedIsValid) {
1216 *existing = *out_suggested;
Mikhail Naganova92039a2023-12-20 14:27:22 -08001217 *applied = true;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301218 LOG(DEBUG) << __func__ << ": " << mType << ": updated port config "
1219 << out_suggested->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001220 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301221 LOG(DEBUG) << __func__ << ": " << mType << ": not applied; existing config ? "
1222 << (existing != configs.end()) << "; requested is valid? " << requestedIsValid
1223 << ", fully specified? " << requestedIsFullySpecified;
Mikhail Naganova92039a2023-12-20 14:27:22 -08001224 *applied = false;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001225 }
1226 return ndk::ScopedAStatus::ok();
1227}
1228
1229ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
1230 auto& patches = getConfig().patches;
1231 auto patchIt = findById<AudioPatch>(patches, in_patchId);
1232 if (patchIt != patches.end()) {
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001233 auto patchesBackup = mPatches;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001234 cleanUpPatch(patchIt->id);
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001235 if (auto status = updateStreamsConnectedState(*patchIt, AudioPatch{}); !status.isOk()) {
1236 mPatches = std::move(patchesBackup);
1237 return status;
1238 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001239 patches.erase(patchIt);
Jaideep Sharma559a4912024-03-07 10:05:51 +05301240 LOG(DEBUG) << __func__ << ": " << mType << ": erased patch " << in_patchId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001241 return ndk::ScopedAStatus::ok();
1242 }
Jaideep Sharma559a4912024-03-07 10:05:51 +05301243 LOG(ERROR) << __func__ << ": " << mType << ": patch id " << in_patchId << " not found";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001244 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1245}
1246
1247ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
1248 auto& configs = getConfig().portConfigs;
1249 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
1250 if (configIt != configs.end()) {
1251 if (mStreams.count(in_portConfigId) != 0) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301252 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001253 << " has a stream opened on it";
1254 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1255 }
1256 auto patchIt = mPatches.find(in_portConfigId);
1257 if (patchIt != mPatches.end()) {
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 << " is used by the patch with id " << patchIt->second;
1260 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1261 }
1262 auto& initials = getConfig().initialConfigs;
1263 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
1264 if (initialIt == initials.end()) {
1265 configs.erase(configIt);
Jaideep Sharma559a4912024-03-07 10:05:51 +05301266 LOG(DEBUG) << __func__ << ": " << mType << ": erased port config " << in_portConfigId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001267 } else if (*configIt != *initialIt) {
1268 *configIt = *initialIt;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301269 LOG(DEBUG) << __func__ << ": " << mType << ": reset port config " << in_portConfigId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001270 }
1271 return ndk::ScopedAStatus::ok();
1272 }
Jaideep Sharma559a4912024-03-07 10:05:51 +05301273 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
1274 << " not found";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001275 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1276}
1277
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001278ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) {
1279 *_aidl_return = mMasterMute;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301280 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001281 return ndk::ScopedAStatus::ok();
1282}
1283
1284ndk::ScopedAStatus Module::setMasterMute(bool in_mute) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301285 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_mute;
jiabin783c48b2023-02-28 18:28:06 +00001286 auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1287 : onMasterMuteChanged(in_mute);
1288 if (result.isOk()) {
1289 mMasterMute = in_mute;
1290 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301291 LOG(ERROR) << __func__ << ": " << mType << ": failed calling onMasterMuteChanged("
1292 << in_mute << "), error=" << result;
jiabin783c48b2023-02-28 18:28:06 +00001293 // Reset master mute if it failed.
1294 onMasterMuteChanged(mMasterMute);
1295 }
Mikhail Naganov55045b52023-10-24 17:03:50 -07001296 return result;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001297}
1298
1299ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) {
1300 *_aidl_return = mMasterVolume;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301301 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001302 return ndk::ScopedAStatus::ok();
1303}
1304
1305ndk::ScopedAStatus Module::setMasterVolume(float in_volume) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301306 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_volume;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001307 if (in_volume >= 0.0f && in_volume <= 1.0f) {
jiabin783c48b2023-02-28 18:28:06 +00001308 auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1309 : onMasterVolumeChanged(in_volume);
1310 if (result.isOk()) {
1311 mMasterVolume = in_volume;
1312 } else {
1313 // Reset master volume if it failed.
Jaideep Sharma559a4912024-03-07 10:05:51 +05301314 LOG(ERROR) << __func__ << ": " << mType << ": failed calling onMasterVolumeChanged("
1315 << in_volume << "), error=" << result;
jiabin783c48b2023-02-28 18:28:06 +00001316 onMasterVolumeChanged(mMasterVolume);
1317 }
Mikhail Naganov55045b52023-10-24 17:03:50 -07001318 return result;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001319 }
Jaideep Sharma559a4912024-03-07 10:05:51 +05301320 LOG(ERROR) << __func__ << ": " << mType << ": invalid master volume value: " << in_volume;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001321 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1322}
1323
1324ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) {
1325 *_aidl_return = mMicMute;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301326 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001327 return ndk::ScopedAStatus::ok();
1328}
1329
1330ndk::ScopedAStatus Module::setMicMute(bool in_mute) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301331 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_mute;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001332 mMicMute = in_mute;
1333 return ndk::ScopedAStatus::ok();
1334}
1335
Mikhail Naganovef6bc742022-10-06 00:14:19 +00001336ndk::ScopedAStatus Module::getMicrophones(std::vector<MicrophoneInfo>* _aidl_return) {
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +00001337 *_aidl_return = getMicrophoneInfos();
Jaideep Sharma559a4912024-03-07 10:05:51 +05301338 LOG(DEBUG) << __func__ << ": " << mType << ": returning "
1339 << ::android::internal::ToString(*_aidl_return);
Mikhail Naganovef6bc742022-10-06 00:14:19 +00001340 return ndk::ScopedAStatus::ok();
1341}
1342
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001343ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) {
Mikhail Naganov04ae8222023-01-11 15:48:10 -08001344 if (!isValidAudioMode(in_mode)) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301345 LOG(ERROR) << __func__ << ": " << mType << ": invalid mode " << toString(in_mode);
Mikhail Naganov04ae8222023-01-11 15:48:10 -08001346 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1347 }
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001348 // No checks for supported audio modes here, it's an informative notification.
Jaideep Sharma559a4912024-03-07 10:05:51 +05301349 LOG(DEBUG) << __func__ << ": " << mType << ": " << toString(in_mode);
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001350 return ndk::ScopedAStatus::ok();
1351}
1352
1353ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301354 LOG(DEBUG) << __func__ << ": " << mType << ": " << toString(in_rotation);
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001355 return ndk::ScopedAStatus::ok();
1356}
1357
1358ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301359 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_isTurnedOn;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001360 return ndk::ScopedAStatus::ok();
1361}
1362
Vlad Popa83a6d822022-11-07 13:53:57 +01001363ndk::ScopedAStatus Module::getSoundDose(std::shared_ptr<ISoundDose>* _aidl_return) {
Mikhail Naganov7499a002023-02-27 18:51:44 -08001364 if (!mSoundDose) {
Vlad Popa2afbd1e2022-12-28 17:04:58 +01001365 mSoundDose = ndk::SharedRefBase::make<sounddose::SoundDose>();
Vlad Popa943b7e22022-12-08 14:24:12 +01001366 }
Mikhail Naganov780fefb2023-07-21 17:01:38 -07001367 *_aidl_return = mSoundDose.getInstance();
Jaideep Sharma559a4912024-03-07 10:05:51 +05301368 LOG(DEBUG) << __func__ << ": " << mType
1369 << ": returning instance of ISoundDose: " << _aidl_return->get();
Vlad Popa83a6d822022-11-07 13:53:57 +01001370 return ndk::ScopedAStatus::ok();
1371}
1372
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001373ndk::ScopedAStatus Module::generateHwAvSyncId(int32_t* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301374 LOG(DEBUG) << __func__ << ": " << mType;
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001375 (void)_aidl_return;
1376 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1377}
1378
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001379const std::string Module::VendorDebug::kForceTransientBurstName = "aosp.forceTransientBurst";
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001380const std::string Module::VendorDebug::kForceSynchronousDrainName = "aosp.forceSynchronousDrain";
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001381
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001382ndk::ScopedAStatus Module::getVendorParameters(const std::vector<std::string>& in_ids,
1383 std::vector<VendorParameter>* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301384 LOG(VERBOSE) << __func__ << ": " << mType << ": id count: " << in_ids.size();
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001385 bool allParametersKnown = true;
1386 for (const auto& id : in_ids) {
1387 if (id == VendorDebug::kForceTransientBurstName) {
1388 VendorParameter forceTransientBurst{.id = id};
1389 forceTransientBurst.ext.setParcelable(Boolean{mVendorDebug.forceTransientBurst});
1390 _aidl_return->push_back(std::move(forceTransientBurst));
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001391 } else if (id == VendorDebug::kForceSynchronousDrainName) {
1392 VendorParameter forceSynchronousDrain{.id = id};
1393 forceSynchronousDrain.ext.setParcelable(Boolean{mVendorDebug.forceSynchronousDrain});
1394 _aidl_return->push_back(std::move(forceSynchronousDrain));
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001395 } else {
1396 allParametersKnown = false;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301397 LOG(VERBOSE) << __func__ << ": " << mType << ": unrecognized parameter \"" << id << "\"";
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001398 }
1399 }
1400 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1401 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001402}
1403
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001404namespace {
1405
1406template <typename W>
1407bool extractParameter(const VendorParameter& p, decltype(W::value)* v) {
1408 std::optional<W> value;
1409 binder_status_t result = p.ext.getParcelable(&value);
1410 if (result == STATUS_OK && value.has_value()) {
1411 *v = value.value().value;
1412 return true;
1413 }
1414 LOG(ERROR) << __func__ << ": failed to read the value of the parameter \"" << p.id
1415 << "\": " << result;
1416 return false;
1417}
1418
1419} // namespace
1420
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001421ndk::ScopedAStatus Module::setVendorParameters(const std::vector<VendorParameter>& in_parameters,
1422 bool in_async) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301423 LOG(VERBOSE) << __func__ << ": " << mType << ": parameter count " << in_parameters.size()
1424 << ", async: " << in_async;
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001425 bool allParametersKnown = true;
1426 for (const auto& p : in_parameters) {
1427 if (p.id == VendorDebug::kForceTransientBurstName) {
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001428 if (!extractParameter<Boolean>(p, &mVendorDebug.forceTransientBurst)) {
1429 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1430 }
1431 } else if (p.id == VendorDebug::kForceSynchronousDrainName) {
1432 if (!extractParameter<Boolean>(p, &mVendorDebug.forceSynchronousDrain)) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001433 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1434 }
1435 } else {
1436 allParametersKnown = false;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301437 LOG(VERBOSE) << __func__ << ": " << mType << ": unrecognized parameter \"" << p.id
1438 << "\"";
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001439 }
1440 }
1441 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1442 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001443}
1444
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001445ndk::ScopedAStatus Module::addDeviceEffect(
1446 int32_t in_portConfigId,
1447 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1448 if (in_effect == nullptr) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301449 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1450 << ", null effect";
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001451 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301452 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1453 << ", effect Binder " << in_effect->asBinder().get();
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001454 }
1455 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1456}
1457
1458ndk::ScopedAStatus Module::removeDeviceEffect(
1459 int32_t in_portConfigId,
1460 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1461 if (in_effect == nullptr) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301462 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1463 << ", null effect";
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001464 } else {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301465 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1466 << ", effect Binder " << in_effect->asBinder().get();
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001467 }
1468 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1469}
1470
jiabin9a8e6862023-01-12 23:06:37 +00001471ndk::ScopedAStatus Module::getMmapPolicyInfos(AudioMMapPolicyType mmapPolicyType,
1472 std::vector<AudioMMapPolicyInfo>* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301473 LOG(DEBUG) << __func__ << ": " << mType << ": mmap policy type " << toString(mmapPolicyType);
jiabin9a8e6862023-01-12 23:06:37 +00001474 std::set<int32_t> mmapSinks;
1475 std::set<int32_t> mmapSources;
1476 auto& ports = getConfig().ports;
1477 for (const auto& port : ports) {
1478 if (port.flags.getTag() == AudioIoFlags::Tag::input &&
1479 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::input>(),
1480 AudioInputFlags::MMAP_NOIRQ)) {
1481 mmapSinks.insert(port.id);
1482 } else if (port.flags.getTag() == AudioIoFlags::Tag::output &&
1483 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
1484 AudioOutputFlags::MMAP_NOIRQ)) {
1485 mmapSources.insert(port.id);
1486 }
1487 }
Mikhail Naganov85064912023-09-26 17:10:08 -07001488 if (mmapSources.empty() && mmapSinks.empty()) {
1489 AudioMMapPolicyInfo never;
1490 never.mmapPolicy = AudioMMapPolicy::NEVER;
1491 _aidl_return->push_back(never);
1492 return ndk::ScopedAStatus::ok();
1493 }
jiabin9a8e6862023-01-12 23:06:37 +00001494 for (const auto& route : getConfig().routes) {
1495 if (mmapSinks.count(route.sinkPortId) != 0) {
1496 // The sink is a mix port, add the sources if they are device ports.
1497 for (int sourcePortId : route.sourcePortIds) {
1498 auto sourcePortIt = findById<AudioPort>(ports, sourcePortId);
1499 if (sourcePortIt == ports.end()) {
1500 // This must not happen
Jaideep Sharma559a4912024-03-07 10:05:51 +05301501 LOG(ERROR) << __func__ << ": " << mType << ": port id " << sourcePortId
1502 << " cannot be found";
jiabin9a8e6862023-01-12 23:06:37 +00001503 continue;
1504 }
1505 if (sourcePortIt->ext.getTag() != AudioPortExt::Tag::device) {
1506 // The source is not a device port, skip
1507 continue;
1508 }
1509 AudioMMapPolicyInfo policyInfo;
1510 policyInfo.device = sourcePortIt->ext.get<AudioPortExt::Tag::device>().device;
1511 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1512 // default implementation.
1513 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1514 _aidl_return->push_back(policyInfo);
1515 }
1516 } else {
1517 auto sinkPortIt = findById<AudioPort>(ports, route.sinkPortId);
1518 if (sinkPortIt == ports.end()) {
1519 // This must not happen
Jaideep Sharma559a4912024-03-07 10:05:51 +05301520 LOG(ERROR) << __func__ << ": " << mType << ": port id " << route.sinkPortId
1521 << " cannot be found";
jiabin9a8e6862023-01-12 23:06:37 +00001522 continue;
1523 }
1524 if (sinkPortIt->ext.getTag() != AudioPortExt::Tag::device) {
1525 // The sink is not a device port, skip
1526 continue;
1527 }
1528 if (count_any(mmapSources, route.sourcePortIds)) {
1529 AudioMMapPolicyInfo policyInfo;
1530 policyInfo.device = sinkPortIt->ext.get<AudioPortExt::Tag::device>().device;
1531 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1532 // default implementation.
1533 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1534 _aidl_return->push_back(policyInfo);
1535 }
1536 }
1537 }
1538 return ndk::ScopedAStatus::ok();
1539}
1540
Eric Laurente2432ea2023-01-12 17:47:31 +01001541ndk::ScopedAStatus Module::supportsVariableLatency(bool* _aidl_return) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301542 LOG(DEBUG) << __func__ << ": " << mType;
Eric Laurente2432ea2023-01-12 17:47:31 +01001543 *_aidl_return = false;
1544 return ndk::ScopedAStatus::ok();
1545}
1546
jiabinb76981e2023-01-18 00:58:30 +00001547ndk::ScopedAStatus Module::getAAudioMixerBurstCount(int32_t* _aidl_return) {
1548 if (!isMmapSupported()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301549 LOG(DEBUG) << __func__ << ": " << mType << ": mmap is not supported ";
jiabinb76981e2023-01-18 00:58:30 +00001550 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1551 }
1552 *_aidl_return = DEFAULT_AAUDIO_MIXER_BURST_COUNT;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301553 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
jiabinb76981e2023-01-18 00:58:30 +00001554 return ndk::ScopedAStatus::ok();
1555}
1556
1557ndk::ScopedAStatus Module::getAAudioHardwareBurstMinUsec(int32_t* _aidl_return) {
1558 if (!isMmapSupported()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301559 LOG(DEBUG) << __func__ << ": " << mType << ": mmap is not supported ";
jiabinb76981e2023-01-18 00:58:30 +00001560 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1561 }
1562 *_aidl_return = DEFAULT_AAUDIO_HARDWARE_BURST_MIN_DURATION_US;
Jaideep Sharma559a4912024-03-07 10:05:51 +05301563 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
jiabinb76981e2023-01-18 00:58:30 +00001564 return ndk::ScopedAStatus::ok();
1565}
1566
1567bool Module::isMmapSupported() {
1568 if (mIsMmapSupported.has_value()) {
1569 return mIsMmapSupported.value();
1570 }
1571 std::vector<AudioMMapPolicyInfo> mmapPolicyInfos;
1572 if (!getMmapPolicyInfos(AudioMMapPolicyType::DEFAULT, &mmapPolicyInfos).isOk()) {
1573 mIsMmapSupported = false;
1574 } else {
1575 mIsMmapSupported =
1576 std::find_if(mmapPolicyInfos.begin(), mmapPolicyInfos.end(), [](const auto& info) {
1577 return info.mmapPolicy == AudioMMapPolicy::AUTO ||
1578 info.mmapPolicy == AudioMMapPolicy::ALWAYS;
1579 }) != mmapPolicyInfos.end();
1580 }
1581 return mIsMmapSupported.value();
1582}
1583
Mikhail Naganova92039a2023-12-20 14:27:22 -08001584ndk::ScopedAStatus Module::populateConnectedDevicePort(AudioPort* audioPort, int32_t) {
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001585 if (audioPort->ext.getTag() != AudioPortExt::device) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301586 LOG(ERROR) << __func__ << ": " << mType << ": not a device port: " << audioPort->toString();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001587 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1588 }
1589 const auto& devicePort = audioPort->ext.get<AudioPortExt::device>();
1590 if (!devicePort.device.type.connection.empty()) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301591 LOG(ERROR) << __func__ << ": " << mType << ": module implementation must override "
1592 "'populateConnectedDevicePort' "
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001593 << "to handle connection of external devices.";
1594 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1595 }
Jaideep Sharma559a4912024-03-07 10:05:51 +05301596 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
jiabin253bd322023-01-25 23:57:31 +00001597 return ndk::ScopedAStatus::ok();
1598}
1599
1600ndk::ScopedAStatus Module::checkAudioPatchEndpointsMatch(
1601 const std::vector<AudioPortConfig*>& sources __unused,
1602 const std::vector<AudioPortConfig*>& sinks __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301603 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
jiabin253bd322023-01-25 23:57:31 +00001604 return ndk::ScopedAStatus::ok();
1605}
1606
jiabin783c48b2023-02-28 18:28:06 +00001607void Module::onExternalDeviceConnectionChanged(
1608 const ::aidl::android::media::audio::common::AudioPort& audioPort __unused,
1609 bool connected __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301610 LOG(DEBUG) << __func__ << ": " << mType << ": do nothing and return";
jiabin783c48b2023-02-28 18:28:06 +00001611}
1612
jiabindd23b0e2023-12-11 19:10:05 +00001613void Module::onPrepareToDisconnectExternalDevice(
1614 const ::aidl::android::media::audio::common::AudioPort& audioPort __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301615 LOG(DEBUG) << __func__ << ": " << mType << ": do nothing and return";
jiabindd23b0e2023-12-11 19:10:05 +00001616}
1617
jiabin783c48b2023-02-28 18:28:06 +00001618ndk::ScopedAStatus Module::onMasterMuteChanged(bool mute __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301619 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
jiabin783c48b2023-02-28 18:28:06 +00001620 return ndk::ScopedAStatus::ok();
1621}
1622
1623ndk::ScopedAStatus Module::onMasterVolumeChanged(float volume __unused) {
Jaideep Sharma559a4912024-03-07 10:05:51 +05301624 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
jiabin783c48b2023-02-28 18:28:06 +00001625 return ndk::ScopedAStatus::ok();
1626}
1627
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +00001628std::vector<MicrophoneInfo> Module::getMicrophoneInfos() {
1629 std::vector<MicrophoneInfo> result;
1630 Configuration& config = getConfig();
1631 for (const AudioPort& port : config.ports) {
1632 if (port.ext.getTag() == AudioPortExt::Tag::device) {
1633 const AudioDeviceType deviceType =
1634 port.ext.get<AudioPortExt::Tag::device>().device.type.type;
1635 if (deviceType == AudioDeviceType::IN_MICROPHONE ||
1636 deviceType == AudioDeviceType::IN_MICROPHONE_BACK) {
1637 // Placeholder values. Vendor implementations must populate MicrophoneInfo
1638 // accordingly based on their physical microphone parameters.
1639 result.push_back(MicrophoneInfo{
1640 .id = port.name,
1641 .device = port.ext.get<AudioPortExt::Tag::device>().device,
1642 .group = 0,
1643 .indexInTheGroup = 0,
1644 });
1645 }
1646 }
1647 }
1648 return result;
1649}
1650
Ram Mohan18f0d512023-07-01 00:47:09 +05301651ndk::ScopedAStatus Module::bluetoothParametersUpdated() {
1652 return mStreams.bluetoothParametersUpdated();
1653}
1654
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001655} // namespace aidl::android::hardware::audio::core