blob: 6c4d7ac975eb5bce1eb4171920deccb96d9945be [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
96// Note: does not assign an ID to the config.
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000097bool generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) {
Mikhail Naganov84bcc042023-10-05 17:36:57 -070098 const bool allowDynamicConfig = port.ext.getTag() == AudioPortExt::device;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000099 *config = {};
100 config->portId = port.id;
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700101 for (const auto& profile : port.profiles) {
102 if (isDynamicProfile(profile)) continue;
103 config->format = profile.format;
104 config->channelMask = *profile.channelMasks.begin();
105 config->sampleRate = Int{.value = *profile.sampleRates.begin()};
106 config->flags = port.flags;
107 config->ext = port.ext;
108 return true;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000109 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700110 if (allowDynamicConfig) {
111 config->format = AudioFormatDescription{};
112 config->channelMask = AudioChannelLayout{};
113 config->sampleRate = Int{.value = 0};
114 config->flags = port.flags;
115 config->ext = port.ext;
116 return true;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000117 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700118 LOG(ERROR) << __func__ << ": port " << port.id << " only has dynamic profiles";
119 return false;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000120}
121
122bool findAudioProfile(const AudioPort& port, const AudioFormatDescription& format,
123 AudioProfile* profile) {
124 if (auto profilesIt =
125 find_if(port.profiles.begin(), port.profiles.end(),
126 [&format](const auto& profile) { return profile.format == format; });
127 profilesIt != port.profiles.end()) {
128 *profile = *profilesIt;
129 return true;
130 }
131 return false;
132}
Mikhail Naganov00603d12022-05-02 22:52:13 +0000133
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000134} // namespace
135
jiabin253bd322023-01-25 23:57:31 +0000136// static
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000137std::shared_ptr<Module> Module::createInstance(Type type, std::unique_ptr<Configuration>&& config) {
jiabin253bd322023-01-25 23:57:31 +0000138 switch (type) {
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530139 case Type::DEFAULT:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000140 return ndk::SharedRefBase::make<ModulePrimary>(std::move(config));
Mikhail Naganov521fc492023-07-11 17:24:08 -0700141 case Type::R_SUBMIX:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000142 return ndk::SharedRefBase::make<ModuleRemoteSubmix>(std::move(config));
Mikhail Naganov521fc492023-07-11 17:24:08 -0700143 case Type::STUB:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000144 return ndk::SharedRefBase::make<ModuleStub>(std::move(config));
Mikhail Naganov521fc492023-07-11 17:24:08 -0700145 case Type::USB:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000146 return ndk::SharedRefBase::make<ModuleUsb>(std::move(config));
Mikhail Naganovb03b5c42023-07-26 13:13:35 -0700147 case Type::BLUETOOTH:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000148 return ndk::SharedRefBase::make<ModuleBluetooth>(std::move(config));
jiabin253bd322023-01-25 23:57:31 +0000149 }
150}
151
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000152// static
153std::optional<Module::Type> Module::typeFromString(const std::string& type) {
154 if (type == "default")
155 return Module::Type::DEFAULT;
156 else if (type == "r_submix")
157 return Module::Type::R_SUBMIX;
158 else if (type == "stub")
159 return Module::Type::STUB;
160 else if (type == "usb")
161 return Module::Type::USB;
162 else if (type == "bluetooth")
163 return Module::Type::BLUETOOTH;
164 return {};
165}
166
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700167std::ostream& operator<<(std::ostream& os, Module::Type t) {
168 switch (t) {
169 case Module::Type::DEFAULT:
170 os << "default";
171 break;
172 case Module::Type::R_SUBMIX:
173 os << "r_submix";
174 break;
Mikhail Naganov521fc492023-07-11 17:24:08 -0700175 case Module::Type::STUB:
176 os << "stub";
177 break;
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700178 case Module::Type::USB:
179 os << "usb";
180 break;
Mikhail Naganovb03b5c42023-07-26 13:13:35 -0700181 case Module::Type::BLUETOOTH:
182 os << "bluetooth";
183 break;
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700184 }
185 return os;
186}
187
Lorena Torres-Huertaf7492512023-01-14 02:49:41 +0000188Module::Module(Type type, std::unique_ptr<Configuration>&& config)
189 : mType(type), mConfig(std::move(config)) {
190 populateConnectedProfiles();
191}
192
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000193void Module::cleanUpPatch(int32_t patchId) {
194 erase_all_values(mPatches, std::set<int32_t>{patchId});
195}
196
Mikhail Naganov8651b362023-01-06 23:15:27 +0000197ndk::ScopedAStatus Module::createStreamContext(
198 int32_t in_portConfigId, int64_t in_bufferSizeFrames,
199 std::shared_ptr<IStreamCallback> asyncCallback,
200 std::shared_ptr<IStreamOutEventCallback> outEventCallback, StreamContext* out_context) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000201 if (in_bufferSizeFrames <= 0) {
202 LOG(ERROR) << __func__ << ": non-positive buffer size " << in_bufferSizeFrames;
203 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
204 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000205 auto& configs = getConfig().portConfigs;
206 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000207 // Since this is a private method, it is assumed that
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000208 // validity of the portConfigId has already been checked.
Mikhail Naganov13501872023-10-18 16:15:46 -0700209 const int32_t minimumStreamBufferSizeFrames = calculateBufferSizeFrames(
210 getNominalLatencyMs(*portConfigIt), portConfigIt->sampleRate.value().value);
211 if (in_bufferSizeFrames < minimumStreamBufferSizeFrames) {
212 LOG(ERROR) << __func__ << ": insufficient buffer size " << in_bufferSizeFrames
213 << ", must be at least " << minimumStreamBufferSizeFrames;
214 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
215 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000216 const size_t frameSize =
217 getFrameSizeInBytes(portConfigIt->format.value(), portConfigIt->channelMask.value());
218 if (frameSize == 0) {
219 LOG(ERROR) << __func__ << ": could not calculate frame size for port config "
220 << portConfigIt->toString();
221 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
222 }
223 LOG(DEBUG) << __func__ << ": frame size " << frameSize << " bytes";
Mikhail Naganovb511b8a2023-05-15 14:35:24 -0700224 if (frameSize > static_cast<size_t>(kMaximumStreamBufferSizeBytes / in_bufferSizeFrames)) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000225 LOG(ERROR) << __func__ << ": buffer size " << in_bufferSizeFrames
226 << " frames is too large, maximum size is "
227 << kMaximumStreamBufferSizeBytes / frameSize;
228 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
229 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000230 const auto& flags = portConfigIt->flags.value();
231 if ((flags.getTag() == AudioIoFlags::Tag::input &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000232 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::input>(),
233 AudioInputFlags::MMAP_NOIRQ)) ||
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000234 (flags.getTag() == AudioIoFlags::Tag::output &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000235 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::output>(),
236 AudioOutputFlags::MMAP_NOIRQ))) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000237 StreamContext::DebugParameters params{mDebug.streamTransientStateDelayMs,
Mikhail Naganov194daaa2023-01-05 22:34:20 +0000238 mVendorDebug.forceTransientBurst,
239 mVendorDebug.forceSynchronousDrain};
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000240 StreamContext temp(
241 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
242 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
Mikhail Naganov13501872023-10-18 16:15:46 -0700243 portConfigIt->format.value(), portConfigIt->channelMask.value(),
244 portConfigIt->sampleRate.value().value, flags, getNominalLatencyMs(*portConfigIt),
Mikhail Naganovb42a69e2023-06-16 12:38:25 -0700245 portConfigIt->ext.get<AudioPortExt::mix>().handle,
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000246 std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames),
Mikhail Naganov3c8b6ce2023-10-31 11:20:30 -0700247 asyncCallback, outEventCallback,
248 std::weak_ptr<sounddose::StreamDataProcessorInterface>{}, params);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000249 if (temp.isValid()) {
250 *out_context = std::move(temp);
251 } else {
252 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
253 }
254 } else {
255 // TODO: Implement simulation of MMAP buffer allocation
256 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000257 return ndk::ScopedAStatus::ok();
258}
259
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000260std::vector<AudioDevice> Module::findConnectedDevices(int32_t portConfigId) {
261 std::vector<AudioDevice> result;
262 auto& ports = getConfig().ports;
263 auto portIds = portIdsFromPortConfigIds(findConnectedPortConfigIds(portConfigId));
264 for (auto it = portIds.begin(); it != portIds.end(); ++it) {
265 auto portIt = findById<AudioPort>(ports, *it);
266 if (portIt != ports.end() && portIt->ext.getTag() == AudioPortExt::Tag::device) {
267 result.push_back(portIt->ext.template get<AudioPortExt::Tag::device>().device);
268 }
269 }
270 return result;
271}
272
273std::set<int32_t> Module::findConnectedPortConfigIds(int32_t portConfigId) {
274 std::set<int32_t> result;
275 auto patchIdsRange = mPatches.equal_range(portConfigId);
276 auto& patches = getConfig().patches;
277 for (auto it = patchIdsRange.first; it != patchIdsRange.second; ++it) {
278 auto patchIt = findById<AudioPatch>(patches, it->second);
279 if (patchIt == patches.end()) {
280 LOG(FATAL) << __func__ << ": patch with id " << it->second << " taken from mPatches "
281 << "not found in the configuration";
282 }
283 if (std::find(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end(),
284 portConfigId) != patchIt->sourcePortConfigIds.end()) {
285 result.insert(patchIt->sinkPortConfigIds.begin(), patchIt->sinkPortConfigIds.end());
286 } else {
287 result.insert(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end());
288 }
289 }
290 return result;
291}
292
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000293ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) {
294 auto& configs = getConfig().portConfigs;
295 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
296 if (portConfigIt == configs.end()) {
297 LOG(ERROR) << __func__ << ": existing port config id " << in_portConfigId << " not found";
298 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
299 }
300 const int32_t portId = portConfigIt->portId;
301 // In our implementation, configs of mix ports always have unique IDs.
302 CHECK(portId != in_portConfigId);
303 auto& ports = getConfig().ports;
304 auto portIt = findById<AudioPort>(ports, portId);
305 if (portIt == ports.end()) {
306 LOG(ERROR) << __func__ << ": port id " << portId << " used by port config id "
307 << in_portConfigId << " not found";
308 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
309 }
310 if (mStreams.count(in_portConfigId) != 0) {
311 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
312 << " already has a stream opened on it";
313 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
314 }
315 if (portIt->ext.getTag() != AudioPortExt::Tag::mix) {
316 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
317 << " does not correspond to a mix port";
318 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
319 }
Mikhail Naganovb511b8a2023-05-15 14:35:24 -0700320 const size_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000321 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
322 LOG(ERROR) << __func__ << ": port id " << portId
323 << " has already reached maximum allowed opened stream count: "
324 << maxOpenStreamCount;
325 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
326 }
327 *port = &(*portIt);
328 return ndk::ScopedAStatus::ok();
329}
330
Lorena Torres-Huertaf7492512023-01-14 02:49:41 +0000331void Module::populateConnectedProfiles() {
332 Configuration& config = getConfig();
333 for (const AudioPort& port : config.ports) {
334 if (port.ext.getTag() == AudioPortExt::device) {
335 if (auto devicePort = port.ext.get<AudioPortExt::device>();
336 !devicePort.device.type.connection.empty() && port.profiles.empty()) {
337 if (auto connIt = config.connectedProfiles.find(port.id);
338 connIt == config.connectedProfiles.end()) {
339 config.connectedProfiles.emplace(
340 port.id, internal::getStandard16And24BitPcmAudioProfiles());
341 }
342 }
343 }
344 }
345}
346
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000347template <typename C>
348std::set<int32_t> Module::portIdsFromPortConfigIds(C portConfigIds) {
349 std::set<int32_t> result;
350 auto& portConfigs = getConfig().portConfigs;
351 for (auto it = portConfigIds.begin(); it != portConfigIds.end(); ++it) {
352 auto portConfigIt = findById<AudioPortConfig>(portConfigs, *it);
353 if (portConfigIt != portConfigs.end()) {
354 result.insert(portConfigIt->portId);
355 }
356 }
357 return result;
358}
359
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000360std::unique_ptr<Module::Configuration> Module::initializeConfig() {
361 return internal::getConfiguration(getType());
Peter Yoon918a6a52023-07-13 17:04:37 +0900362}
363
Mikhail Naganov13501872023-10-18 16:15:46 -0700364int32_t Module::getNominalLatencyMs(const AudioPortConfig&) {
365 // Arbitrary value. Implementations must override this method to provide their actual latency.
366 static constexpr int32_t kLatencyMs = 5;
367 return kLatencyMs;
368}
369
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700370std::vector<AudioRoute*> Module::getAudioRoutesForAudioPortImpl(int32_t portId) {
371 std::vector<AudioRoute*> result;
372 auto& routes = getConfig().routes;
373 for (auto& r : routes) {
374 const auto& srcs = r.sourcePortIds;
375 if (r.sinkPortId == portId || std::find(srcs.begin(), srcs.end(), portId) != srcs.end()) {
376 result.push_back(&r);
377 }
378 }
379 return result;
380}
381
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000382Module::Configuration& Module::getConfig() {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000383 if (!mConfig) {
Peter Yoon918a6a52023-07-13 17:04:37 +0900384 mConfig = std::move(initializeConfig());
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000385 }
386 return *mConfig;
387}
388
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700389std::set<int32_t> Module::getRoutableAudioPortIds(int32_t portId,
390 std::vector<AudioRoute*>* routes) {
391 std::vector<AudioRoute*> routesStorage;
392 if (routes == nullptr) {
393 routesStorage = getAudioRoutesForAudioPortImpl(portId);
394 routes = &routesStorage;
395 }
396 std::set<int32_t> result;
397 for (AudioRoute* r : *routes) {
398 if (r->sinkPortId == portId) {
399 result.insert(r->sourcePortIds.begin(), r->sourcePortIds.end());
400 } else {
401 result.insert(r->sinkPortId);
402 }
403 }
404 return result;
405}
406
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000407void Module::registerPatch(const AudioPatch& patch) {
408 auto& configs = getConfig().portConfigs;
409 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
410 for (auto portConfigId : portConfigIds) {
411 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
412 if (configIt != configs.end()) {
413 mPatches.insert(std::pair{portConfigId, patch.id});
414 if (configIt->portId != portConfigId) {
415 mPatches.insert(std::pair{configIt->portId, patch.id});
416 }
417 }
418 };
419 };
420 do_insert(patch.sourcePortConfigIds);
421 do_insert(patch.sinkPortConfigIds);
422}
423
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700424ndk::ScopedAStatus Module::updateStreamsConnectedState(const AudioPatch& oldPatch,
425 const AudioPatch& newPatch) {
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700426 // Notify streams about the new set of devices they are connected to.
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700427 auto maybeFailure = ndk::ScopedAStatus::ok();
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700428 using Connections =
429 std::map<int32_t /*mixPortConfigId*/, std::set<int32_t /*devicePortConfigId*/>>;
430 Connections oldConnections, newConnections;
431 auto fillConnectionsHelper = [&](Connections& connections,
432 const std::vector<int32_t>& mixPortCfgIds,
433 const std::vector<int32_t>& devicePortCfgIds) {
434 for (int32_t mixPortCfgId : mixPortCfgIds) {
435 connections[mixPortCfgId].insert(devicePortCfgIds.begin(), devicePortCfgIds.end());
436 }
437 };
438 auto fillConnections = [&](Connections& connections, const AudioPatch& patch) {
439 if (std::find_if(patch.sourcePortConfigIds.begin(), patch.sourcePortConfigIds.end(),
440 [&](int32_t portConfigId) { return mStreams.count(portConfigId) > 0; }) !=
441 patch.sourcePortConfigIds.end()) {
442 // Sources are mix ports.
443 fillConnectionsHelper(connections, patch.sourcePortConfigIds, patch.sinkPortConfigIds);
444 } else if (std::find_if(patch.sinkPortConfigIds.begin(), patch.sinkPortConfigIds.end(),
445 [&](int32_t portConfigId) {
446 return mStreams.count(portConfigId) > 0;
447 }) != patch.sinkPortConfigIds.end()) {
448 // Sources are device ports.
449 fillConnectionsHelper(connections, patch.sinkPortConfigIds, patch.sourcePortConfigIds);
450 } // Otherwise, there are no streams to notify.
451 };
452 fillConnections(oldConnections, oldPatch);
453 fillConnections(newConnections, newPatch);
454
455 std::for_each(oldConnections.begin(), oldConnections.end(), [&](const auto& connectionPair) {
456 const int32_t mixPortConfigId = connectionPair.first;
457 if (auto it = newConnections.find(mixPortConfigId);
458 it == newConnections.end() || it->second != connectionPair.second) {
459 if (auto status = mStreams.setStreamConnectedDevices(mixPortConfigId, {});
460 status.isOk()) {
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700461 LOG(DEBUG) << "updateStreamsConnectedState: The stream on port config id "
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700462 << mixPortConfigId << " has been disconnected";
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700463 } else {
464 // Disconnection is tricky to roll back, just register a failure.
465 maybeFailure = std::move(status);
466 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000467 }
468 });
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700469 if (!maybeFailure.isOk()) return maybeFailure;
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700470 std::set<int32_t> idsToDisconnectOnFailure;
471 std::for_each(newConnections.begin(), newConnections.end(), [&](const auto& connectionPair) {
472 const int32_t mixPortConfigId = connectionPair.first;
473 if (auto it = oldConnections.find(mixPortConfigId);
474 it == oldConnections.end() || it->second != connectionPair.second) {
475 const auto connectedDevices = findConnectedDevices(mixPortConfigId);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700476 if (connectedDevices.empty()) {
477 // This is important as workers use the vector size to derive the connection status.
478 LOG(FATAL) << "updateStreamsConnectedState: No connected devices found for port "
479 "config id "
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700480 << mixPortConfigId;
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700481 }
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700482 if (auto status = mStreams.setStreamConnectedDevices(mixPortConfigId, connectedDevices);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700483 status.isOk()) {
484 LOG(DEBUG) << "updateStreamsConnectedState: The stream on port config id "
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700485 << mixPortConfigId << " has been connected to: "
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700486 << ::android::internal::ToString(connectedDevices);
487 } else {
488 maybeFailure = std::move(status);
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700489 idsToDisconnectOnFailure.insert(mixPortConfigId);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700490 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000491 }
492 });
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700493 if (!maybeFailure.isOk()) {
494 LOG(WARNING) << __func__ << ": Due to a failure, disconnecting streams on port config ids "
495 << ::android::internal::ToString(idsToDisconnectOnFailure);
496 std::for_each(idsToDisconnectOnFailure.begin(), idsToDisconnectOnFailure.end(),
497 [&](const auto& portConfigId) {
498 auto status = mStreams.setStreamConnectedDevices(portConfigId, {});
499 (void)status.isOk(); // Can't do much about a failure here.
500 });
501 return maybeFailure;
502 }
503 return ndk::ScopedAStatus::ok();
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000504}
505
Mikhail Naganov00603d12022-05-02 22:52:13 +0000506ndk::ScopedAStatus Module::setModuleDebug(
507 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700508 LOG(DEBUG) << __func__ << ": " << mType << ": old flags:" << mDebug.toString()
Mikhail Naganov00603d12022-05-02 22:52:13 +0000509 << ", new flags: " << in_debug.toString();
510 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
511 !mConnectedDevicePorts.empty()) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700512 LOG(ERROR) << __func__ << ": " << mType
513 << ": attempting to change device connections simulation while having external "
514 << "devices connected";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000515 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
516 }
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000517 if (in_debug.streamTransientStateDelayMs < 0) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700518 LOG(ERROR) << __func__ << ": " << mType << ": streamTransientStateDelayMs is negative: "
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000519 << in_debug.streamTransientStateDelayMs;
520 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
521 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000522 mDebug = in_debug;
523 return ndk::ScopedAStatus::ok();
524}
525
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000526ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700527 *_aidl_return = nullptr;
528 LOG(DEBUG) << __func__ << ": returning null";
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000529 return ndk::ScopedAStatus::ok();
530}
531
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000532ndk::ScopedAStatus Module::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700533 *_aidl_return = nullptr;
534 LOG(DEBUG) << __func__ << ": returning null";
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000535 return ndk::ScopedAStatus::ok();
536}
537
Mikhail Naganov7499a002023-02-27 18:51:44 -0800538ndk::ScopedAStatus Module::getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700539 *_aidl_return = nullptr;
540 LOG(DEBUG) << __func__ << ": returning null";
Mikhail Naganov7499a002023-02-27 18:51:44 -0800541 return ndk::ScopedAStatus::ok();
542}
543
Mikhail Naganovb5647da2023-03-06 14:37:38 -0800544ndk::ScopedAStatus Module::getBluetoothLe(std::shared_ptr<IBluetoothLe>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700545 *_aidl_return = nullptr;
546 LOG(DEBUG) << __func__ << ": returning null";
Mikhail Naganovb5647da2023-03-06 14:37:38 -0800547 return ndk::ScopedAStatus::ok();
548}
549
Mikhail Naganov00603d12022-05-02 22:52:13 +0000550ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
551 AudioPort* _aidl_return) {
552 const int32_t templateId = in_templateIdAndAdditionalData.id;
553 auto& ports = getConfig().ports;
554 AudioPort connectedPort;
555 { // Scope the template port so that we don't accidentally modify it.
556 auto templateIt = findById<AudioPort>(ports, templateId);
557 if (templateIt == ports.end()) {
558 LOG(ERROR) << __func__ << ": port id " << templateId << " not found";
559 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
560 }
561 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
562 LOG(ERROR) << __func__ << ": port id " << templateId << " is not a device port";
563 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
564 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000565 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
566 if (templateDevicePort.device.type.connection.empty()) {
567 LOG(ERROR) << __func__ << ": port id " << templateId << " is permanently attached";
568 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
569 }
Mikhail Naganovfcf980e2023-09-07 16:30:11 -0700570 if (mConnectedDevicePorts.find(templateId) != mConnectedDevicePorts.end()) {
571 LOG(ERROR) << __func__ << ": port id " << templateId << " is a connected device port";
572 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
573 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000574 // Postpone id allocation until we ensure that there are no client errors.
575 connectedPort = *templateIt;
576 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
577 const auto& inputDevicePort =
578 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
579 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
580 connectedDevicePort.device.address = inputDevicePort.device.address;
581 LOG(DEBUG) << __func__ << ": device port " << connectedPort.id << " device set to "
582 << connectedDevicePort.device.toString();
583 // Check if there is already a connected port with for the same external device.
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700584 for (auto connectedPortPair : mConnectedDevicePorts) {
585 auto connectedPortIt = findById<AudioPort>(ports, connectedPortPair.first);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000586 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
587 connectedDevicePort.device) {
588 LOG(ERROR) << __func__ << ": device " << connectedDevicePort.device.toString()
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700589 << " is already connected at the device port id "
590 << connectedPortPair.first;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000591 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
592 }
593 }
594 }
595
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700596 // Two main cases are considered with regard to the profiles of the connected device port:
597 //
598 // 1. If the template device port has dynamic profiles, and at least one routable mix
599 // port also has dynamic profiles, it means that after connecting the device, the
600 // connected device port must have profiles populated with actual capabilities of
601 // the connected device, and dynamic of routable mix ports will be filled
602 // according to these capabilities. An example of this case is connection of an
603 // HDMI or USB device. For USB handled by ADSP, there can be mix ports with static
604 // profiles, and one dedicated mix port for "hi-fi" playback. The latter is left with
605 // dynamic profiles so that they can be populated with actual capabilities of
606 // the connected device.
607 //
608 // 2. If the template device port has dynamic profiles, while all routable mix ports
609 // have static profiles, it means that after connecting the device, the connected
610 // device port can be left with dynamic profiles, and profiles of mix ports are
611 // left untouched. An example of this case is connection of an analog wired
612 // headset, it should be treated in the same way as a speaker.
613 //
614 // Yet another possible case is when both the template device port and all routable
615 // mix ports have static profiles. This is allowed and handled correctly, however, it
616 // is not very practical, since these profiles are likely duplicates of each other.
617
618 std::vector<AudioRoute*> routesToMixPorts = getAudioRoutesForAudioPortImpl(templateId);
619 std::set<int32_t> routableMixPortIds = getRoutableAudioPortIds(templateId, &routesToMixPorts);
Mikhail Naganov55045b52023-10-24 17:03:50 -0700620 if (!mDebug.simulateDeviceConnections) {
621 // Even if the device port has static profiles, the HAL module might need to update
622 // them, or abort the connection process.
623 RETURN_STATUS_IF_ERROR(populateConnectedDevicePort(&connectedPort));
624 } else if (hasDynamicProfilesOnly(connectedPort.profiles)) {
625 auto& connectedProfiles = getConfig().connectedProfiles;
626 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
627 connectedProfilesIt != connectedProfiles.end()) {
628 connectedPort.profiles = connectedProfilesIt->second;
Mikhail Naganovfcf980e2023-09-07 16:30:11 -0700629 }
Mikhail Naganov55045b52023-10-24 17:03:50 -0700630 }
631 if (hasDynamicProfilesOnly(connectedPort.profiles)) {
632 // Possible case 2. Check if all routable mix ports have static profiles.
633 if (auto dynamicMixPortIt = std::find_if(ports.begin(), ports.end(),
634 [&routableMixPortIds](const auto& p) {
635 return routableMixPortIds.count(p.id) > 0 &&
636 hasDynamicProfilesOnly(p.profiles);
637 });
638 dynamicMixPortIt != ports.end()) {
639 LOG(ERROR) << __func__ << ": connected port only has dynamic profiles after connecting "
640 << "external device " << connectedPort.toString() << ", and there exist "
641 << "a routable mix port with dynamic profiles: "
642 << dynamicMixPortIt->toString();
643 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530644 }
645 }
646
Mikhail Naganovdc417732023-09-29 15:49:35 -0700647 connectedPort.id = getConfig().nextPortId++;
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700648 auto [connectedPortsIt, _] =
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700649 mConnectedDevicePorts.insert(std::pair(connectedPort.id, std::set<int32_t>()));
Mikhail Naganov00603d12022-05-02 22:52:13 +0000650 LOG(DEBUG) << __func__ << ": template port " << templateId << " external device connected, "
651 << "connected port ID " << connectedPort.id;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000652 ports.push_back(connectedPort);
jiabin783c48b2023-02-28 18:28:06 +0000653 onExternalDeviceConnectionChanged(connectedPort, true /*connected*/);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000654
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700655 // For routes where the template port is a source, add the connected port to sources,
656 // otherwise, create a new route by copying from the route for the template port.
Mikhail Naganov00603d12022-05-02 22:52:13 +0000657 std::vector<AudioRoute> newRoutes;
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700658 for (AudioRoute* r : routesToMixPorts) {
659 if (r->sinkPortId == templateId) {
660 newRoutes.push_back(AudioRoute{.sourcePortIds = r->sourcePortIds,
661 .sinkPortId = connectedPort.id,
662 .isExclusive = r->isExclusive});
Mikhail Naganov00603d12022-05-02 22:52:13 +0000663 } else {
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700664 r->sourcePortIds.push_back(connectedPort.id);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000665 }
666 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700667 auto& routes = getConfig().routes;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000668 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
669
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700670 if (!hasDynamicProfilesOnly(connectedPort.profiles) && !routableMixPortIds.empty()) {
671 // Note: this is a simplistic approach assuming that a mix port can only be populated
672 // from a single device port. Implementing support for stuffing dynamic profiles with
673 // a superset of all profiles from all routable dynamic device ports would be more involved.
674 for (auto& port : ports) {
675 if (routableMixPortIds.count(port.id) == 0) continue;
676 if (hasDynamicProfilesOnly(port.profiles)) {
677 port.profiles = connectedPort.profiles;
678 connectedPortsIt->second.insert(port.id);
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700679 } else {
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700680 // Check if profiles are not all dynamic because they were populated by
681 // a previous connection. Otherwise, it means that they are actually static.
682 for (const auto& cp : mConnectedDevicePorts) {
683 if (cp.second.count(port.id) > 0) {
684 connectedPortsIt->second.insert(port.id);
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700685 break;
686 }
687 }
688 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700689 }
690 }
691 *_aidl_return = std::move(connectedPort);
692
Mikhail Naganov00603d12022-05-02 22:52:13 +0000693 return ndk::ScopedAStatus::ok();
694}
695
696ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
697 auto& ports = getConfig().ports;
698 auto portIt = findById<AudioPort>(ports, in_portId);
699 if (portIt == ports.end()) {
700 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
701 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
702 }
703 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
704 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a device port";
705 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
706 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700707 auto connectedPortsIt = mConnectedDevicePorts.find(in_portId);
708 if (connectedPortsIt == mConnectedDevicePorts.end()) {
Mikhail Naganov00603d12022-05-02 22:52:13 +0000709 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a connected device port";
710 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
711 }
712 auto& configs = getConfig().portConfigs;
713 auto& initials = getConfig().initialConfigs;
714 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
715 if (config.portId == in_portId) {
716 // Check if the configuration was provided by the client.
717 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
718 return initialIt == initials.end() || config != *initialIt;
719 }
720 return false;
721 });
722 if (configIt != configs.end()) {
723 LOG(ERROR) << __func__ << ": port id " << in_portId << " has a non-default config with id "
724 << configIt->id;
725 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
726 }
jiabin783c48b2023-02-28 18:28:06 +0000727 onExternalDeviceConnectionChanged(*portIt, false /*connected*/);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000728 ports.erase(portIt);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000729 LOG(DEBUG) << __func__ << ": connected device port " << in_portId << " released";
730
731 auto& routes = getConfig().routes;
732 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
733 if (routesIt->sinkPortId == in_portId) {
734 routesIt = routes.erase(routesIt);
735 } else {
736 // Note: the list of sourcePortIds can't become empty because there must
737 // be the id of the template port in the route.
738 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
739 ++routesIt;
740 }
741 }
742
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700743 // Clear profiles for mix ports that are not connected to any other ports.
744 std::set<int32_t> mixPortsToClear = std::move(connectedPortsIt->second);
745 mConnectedDevicePorts.erase(connectedPortsIt);
746 for (const auto& connectedPort : mConnectedDevicePorts) {
747 for (int32_t mixPortId : connectedPort.second) {
748 mixPortsToClear.erase(mixPortId);
749 }
750 }
751 for (int32_t mixPortId : mixPortsToClear) {
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700752 auto mixPortIt = findById<AudioPort>(ports, mixPortId);
753 if (mixPortIt != ports.end()) {
754 mixPortIt->profiles = {};
755 }
756 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700757
Mikhail Naganov00603d12022-05-02 22:52:13 +0000758 return ndk::ScopedAStatus::ok();
759}
760
jiabindd23b0e2023-12-11 19:10:05 +0000761ndk::ScopedAStatus Module::prepareToDisconnectExternalDevice(int32_t in_portId) {
762 auto& ports = getConfig().ports;
763 auto portIt = findById<AudioPort>(ports, in_portId);
764 if (portIt == ports.end()) {
765 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
766 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
767 }
768 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
769 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a device port";
770 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
771 }
772 auto connectedPortsIt = mConnectedDevicePorts.find(in_portId);
773 if (connectedPortsIt == mConnectedDevicePorts.end()) {
774 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a connected device port";
775 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
776 }
777
778 onPrepareToDisconnectExternalDevice(*portIt);
779
780 return ndk::ScopedAStatus::ok();
781}
782
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000783ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
784 *_aidl_return = getConfig().patches;
785 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " patches";
786 return ndk::ScopedAStatus::ok();
787}
788
789ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
790 auto& ports = getConfig().ports;
791 auto portIt = findById<AudioPort>(ports, in_portId);
792 if (portIt != ports.end()) {
793 *_aidl_return = *portIt;
794 LOG(DEBUG) << __func__ << ": returning port by id " << in_portId;
795 return ndk::ScopedAStatus::ok();
796 }
797 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
798 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
799}
800
801ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
802 *_aidl_return = getConfig().portConfigs;
803 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " port configs";
804 return ndk::ScopedAStatus::ok();
805}
806
807ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
808 *_aidl_return = getConfig().ports;
809 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " ports";
810 return ndk::ScopedAStatus::ok();
811}
812
813ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
814 *_aidl_return = getConfig().routes;
815 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " routes";
816 return ndk::ScopedAStatus::ok();
817}
818
Mikhail Naganov00603d12022-05-02 22:52:13 +0000819ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
820 std::vector<AudioRoute>* _aidl_return) {
821 auto& ports = getConfig().ports;
822 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
823 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
824 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
825 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700826 std::vector<AudioRoute*> routes = getAudioRoutesForAudioPortImpl(in_portId);
827 std::transform(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
828 [](auto rptr) { return *rptr; });
Mikhail Naganov00603d12022-05-02 22:52:13 +0000829 return ndk::ScopedAStatus::ok();
830}
831
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000832ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
833 OpenInputStreamReturn* _aidl_return) {
834 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", buffer size "
835 << in_args.bufferSizeFrames << " frames";
836 AudioPort* port = nullptr;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700837 RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000838 if (port->flags.getTag() != AudioIoFlags::Tag::input) {
839 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000840 << " does not correspond to an input mix port";
841 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
842 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000843 StreamContext context;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700844 RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
845 nullptr, nullptr, &context));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000846 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000847 std::shared_ptr<StreamIn> stream;
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700848 RETURN_STATUS_IF_ERROR(createInputStream(std::move(context), in_args.sinkMetadata,
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +0000849 getMicrophoneInfos(), &stream));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000850 StreamWrapper streamWrapper(stream);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700851 if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
852 RETURN_STATUS_IF_ERROR(
853 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
854 }
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000855 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
856 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000857 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000858 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000859 return ndk::ScopedAStatus::ok();
860}
861
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000862ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
863 OpenOutputStreamReturn* _aidl_return) {
864 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", has offload info? "
865 << (in_args.offloadInfo.has_value()) << ", buffer size " << in_args.bufferSizeFrames
866 << " frames";
867 AudioPort* port = nullptr;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700868 RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000869 if (port->flags.getTag() != AudioIoFlags::Tag::output) {
870 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000871 << " does not correspond to an output mix port";
872 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
873 }
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000874 const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
875 AudioOutputFlags::COMPRESS_OFFLOAD);
876 if (isOffload && !in_args.offloadInfo.has_value()) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000877 LOG(ERROR) << __func__ << ": port id " << port->id
Mikhail Naganov111e0ce2022-06-17 21:41:19 +0000878 << " has COMPRESS_OFFLOAD flag set, requires offload info";
879 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
880 }
Mikhail Naganov30301a42022-09-13 01:20:45 +0000881 const bool isNonBlocking = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
882 AudioOutputFlags::NON_BLOCKING);
883 if (isNonBlocking && in_args.callback == nullptr) {
884 LOG(ERROR) << __func__ << ": port id " << port->id
885 << " has NON_BLOCKING flag set, requires async callback";
886 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
887 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000888 StreamContext context;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700889 RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
890 isNonBlocking ? in_args.callback : nullptr,
891 in_args.eventCallback, &context));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000892 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000893 std::shared_ptr<StreamOut> stream;
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700894 RETURN_STATUS_IF_ERROR(createOutputStream(std::move(context), in_args.sourceMetadata,
Mikhail Naganov9d16a6a2023-06-26 17:21:04 -0700895 in_args.offloadInfo, &stream));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000896 StreamWrapper streamWrapper(stream);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700897 if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
898 RETURN_STATUS_IF_ERROR(
899 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
900 }
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000901 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
902 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000903 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000904 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000905 return ndk::ScopedAStatus::ok();
906}
907
Mikhail Naganov74927202022-12-19 16:37:14 +0000908ndk::ScopedAStatus Module::getSupportedPlaybackRateFactors(
909 SupportedPlaybackRateFactors* _aidl_return) {
910 LOG(DEBUG) << __func__;
911 (void)_aidl_return;
912 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
913}
914
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000915ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
Mikhail Naganov16db9b72022-06-17 21:36:18 +0000916 LOG(DEBUG) << __func__ << ": requested patch " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000917 if (in_requested.sourcePortConfigIds.empty()) {
918 LOG(ERROR) << __func__ << ": requested patch has empty sources list";
919 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
920 }
921 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
922 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sources list";
923 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
924 }
925 if (in_requested.sinkPortConfigIds.empty()) {
926 LOG(ERROR) << __func__ << ": requested patch has empty sinks list";
927 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
928 }
929 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
930 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sinks list";
931 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
932 }
933
934 auto& configs = getConfig().portConfigs;
935 std::vector<int32_t> missingIds;
936 auto sources =
937 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
938 if (!missingIds.empty()) {
939 LOG(ERROR) << __func__ << ": following source port config ids not found: "
940 << ::android::internal::ToString(missingIds);
941 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
942 }
943 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
944 if (!missingIds.empty()) {
945 LOG(ERROR) << __func__ << ": following sink port config ids not found: "
946 << ::android::internal::ToString(missingIds);
947 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
948 }
949 // bool indicates whether a non-exclusive route is available.
950 // If only an exclusive route is available, that means the patch can not be
951 // established if there is any other patch which currently uses the sink port.
952 std::map<int32_t, bool> allowedSinkPorts;
953 auto& routes = getConfig().routes;
954 for (auto src : sources) {
955 for (const auto& r : routes) {
956 const auto& srcs = r.sourcePortIds;
957 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
958 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
959 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
960 }
961 }
962 }
963 }
964 for (auto sink : sinks) {
965 if (allowedSinkPorts.count(sink->portId) == 0) {
966 LOG(ERROR) << __func__ << ": there is no route to the sink port id " << sink->portId;
967 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
968 }
969 }
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700970 RETURN_STATUS_IF_ERROR(checkAudioPatchEndpointsMatch(sources, sinks));
jiabin253bd322023-01-25 23:57:31 +0000971
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000972 auto& patches = getConfig().patches;
973 auto existing = patches.end();
974 std::optional<decltype(mPatches)> patchesBackup;
975 if (in_requested.id != 0) {
976 existing = findById<AudioPatch>(patches, in_requested.id);
977 if (existing != patches.end()) {
978 patchesBackup = mPatches;
979 cleanUpPatch(existing->id);
980 } else {
981 LOG(ERROR) << __func__ << ": not found existing patch id " << in_requested.id;
982 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
983 }
984 }
985 // Validate the requested patch.
986 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
987 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
988 LOG(ERROR) << __func__ << ": sink port id " << sinkPortId
989 << "is exclusive and is already used by some other patch";
990 if (patchesBackup.has_value()) {
991 mPatches = std::move(*patchesBackup);
992 }
993 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
994 }
995 }
Mikhail Naganov13501872023-10-18 16:15:46 -0700996 // Find the highest sample rate among mix port configs.
997 std::map<int32_t, AudioPortConfig*> sampleRates;
998 std::vector<AudioPortConfig*>& mixPortConfigs =
999 sources[0]->ext.getTag() == AudioPortExt::mix ? sources : sinks;
1000 for (auto mix : mixPortConfigs) {
1001 sampleRates.emplace(mix->sampleRate.value().value, mix);
1002 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001003 *_aidl_return = in_requested;
Mikhail Naganov13501872023-10-18 16:15:46 -07001004 auto maxSampleRateIt = std::max_element(sampleRates.begin(), sampleRates.end());
1005 const int32_t latencyMs = getNominalLatencyMs(*(maxSampleRateIt->second));
1006 _aidl_return->minimumStreamBufferSizeFrames =
1007 calculateBufferSizeFrames(latencyMs, maxSampleRateIt->first);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +00001008 _aidl_return->latenciesMs.clear();
1009 _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
Mikhail Naganov13501872023-10-18 16:15:46 -07001010 _aidl_return->sinkPortConfigIds.size(), latencyMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001011 AudioPatch oldPatch{};
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001012 if (existing == patches.end()) {
1013 _aidl_return->id = getConfig().nextPatchId++;
1014 patches.push_back(*_aidl_return);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001015 } else {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001016 oldPatch = *existing;
Mikhail Naganovdc417732023-09-29 15:49:35 -07001017 *existing = *_aidl_return;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001018 }
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001019 patchesBackup = mPatches;
1020 registerPatch(*_aidl_return);
1021 if (auto status = updateStreamsConnectedState(oldPatch, *_aidl_return); !status.isOk()) {
1022 mPatches = std::move(*patchesBackup);
1023 if (existing == patches.end()) {
1024 patches.pop_back();
1025 } else {
1026 *existing = oldPatch;
1027 }
1028 return status;
1029 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +00001030
1031 LOG(DEBUG) << __func__ << ": " << (oldPatch.id == 0 ? "created" : "updated") << " patch "
1032 << _aidl_return->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001033 return ndk::ScopedAStatus::ok();
1034}
1035
1036ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
1037 AudioPortConfig* out_suggested, bool* _aidl_return) {
1038 LOG(DEBUG) << __func__ << ": requested " << in_requested.toString();
1039 auto& configs = getConfig().portConfigs;
1040 auto existing = configs.end();
1041 if (in_requested.id != 0) {
1042 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
1043 existing == configs.end()) {
1044 LOG(ERROR) << __func__ << ": existing port config id " << in_requested.id
1045 << " not found";
1046 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1047 }
1048 }
1049
1050 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
1051 if (portId == 0) {
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001052 LOG(ERROR) << __func__ << ": requested port config does not specify portId";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001053 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1054 }
1055 auto& ports = getConfig().ports;
1056 auto portIt = findById<AudioPort>(ports, portId);
1057 if (portIt == ports.end()) {
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001058 LOG(ERROR) << __func__ << ": requested port config points to non-existent portId "
1059 << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001060 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1061 }
1062 if (existing != configs.end()) {
1063 *out_suggested = *existing;
1064 } else {
1065 AudioPortConfig newConfig;
1066 if (generateDefaultPortConfig(*portIt, &newConfig)) {
1067 *out_suggested = newConfig;
1068 } else {
1069 LOG(ERROR) << __func__ << ": unable generate a default config for port " << portId;
1070 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1071 }
1072 }
1073 // From this moment, 'out_suggested' is either an existing port config,
1074 // or a new generated config. Now attempt to update it according to the specified
1075 // fields of 'in_requested'.
1076
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001077 // Device ports with only dynamic profiles are used for devices that are connected via ADSP,
1078 // which takes care of their actual configuration automatically.
1079 const bool allowDynamicConfig = portIt->ext.getTag() == AudioPortExt::device &&
1080 hasDynamicProfilesOnly(portIt->profiles);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001081 bool requestedIsValid = true, requestedIsFullySpecified = true;
1082
1083 AudioIoFlags portFlags = portIt->flags;
1084 if (in_requested.flags.has_value()) {
1085 if (in_requested.flags.value() != portFlags) {
1086 LOG(WARNING) << __func__ << ": requested flags "
1087 << in_requested.flags.value().toString() << " do not match port's "
1088 << portId << " flags " << portFlags.toString();
1089 requestedIsValid = false;
1090 }
1091 } else {
1092 requestedIsFullySpecified = false;
1093 }
1094
1095 AudioProfile portProfile;
1096 if (in_requested.format.has_value()) {
1097 const auto& format = in_requested.format.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001098 if ((format == AudioFormatDescription{} && allowDynamicConfig) ||
1099 findAudioProfile(*portIt, format, &portProfile)) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001100 out_suggested->format = format;
1101 } else {
1102 LOG(WARNING) << __func__ << ": requested format " << format.toString()
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001103 << " is not found in the profiles of port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001104 requestedIsValid = false;
1105 }
1106 } else {
1107 requestedIsFullySpecified = false;
1108 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001109 if (!(out_suggested->format.value() == AudioFormatDescription{} && allowDynamicConfig) &&
1110 !findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001111 LOG(ERROR) << __func__ << ": port " << portId << " does not support format "
1112 << out_suggested->format.value().toString() << " anymore";
1113 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1114 }
1115
1116 if (in_requested.channelMask.has_value()) {
1117 const auto& channelMask = in_requested.channelMask.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001118 if ((channelMask == AudioChannelLayout{} && allowDynamicConfig) ||
1119 find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
1120 portProfile.channelMasks.end()) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001121 out_suggested->channelMask = channelMask;
1122 } else {
1123 LOG(WARNING) << __func__ << ": requested channel mask " << channelMask.toString()
1124 << " is not supported for the format " << portProfile.format.toString()
1125 << " by the port " << portId;
1126 requestedIsValid = false;
1127 }
1128 } else {
1129 requestedIsFullySpecified = false;
1130 }
1131
1132 if (in_requested.sampleRate.has_value()) {
1133 const auto& sampleRate = in_requested.sampleRate.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001134 if ((sampleRate.value == 0 && allowDynamicConfig) ||
1135 find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001136 sampleRate.value) != portProfile.sampleRates.end()) {
1137 out_suggested->sampleRate = sampleRate;
1138 } else {
1139 LOG(WARNING) << __func__ << ": requested sample rate " << sampleRate.value
1140 << " is not supported for the format " << portProfile.format.toString()
1141 << " by the port " << portId;
1142 requestedIsValid = false;
1143 }
1144 } else {
1145 requestedIsFullySpecified = false;
1146 }
1147
1148 if (in_requested.gain.has_value()) {
1149 // Let's pretend that gain can always be applied.
1150 out_suggested->gain = in_requested.gain.value();
1151 }
1152
Mikhail Naganov248e9502023-02-21 16:32:40 -08001153 if (in_requested.ext.getTag() != AudioPortExt::Tag::unspecified) {
1154 if (in_requested.ext.getTag() == out_suggested->ext.getTag()) {
1155 if (out_suggested->ext.getTag() == AudioPortExt::Tag::mix) {
1156 // 'AudioMixPortExt.handle' is set by the client, copy from in_requested
1157 out_suggested->ext.get<AudioPortExt::Tag::mix>().handle =
1158 in_requested.ext.get<AudioPortExt::Tag::mix>().handle;
1159 }
1160 } else {
1161 LOG(WARNING) << __func__ << ": requested ext tag "
1162 << toString(in_requested.ext.getTag()) << " do not match port's tag "
1163 << toString(out_suggested->ext.getTag());
1164 requestedIsValid = false;
1165 }
1166 }
1167
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001168 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
1169 out_suggested->id = getConfig().nextPortId++;
1170 configs.push_back(*out_suggested);
1171 *_aidl_return = true;
1172 LOG(DEBUG) << __func__ << ": created new port config " << out_suggested->toString();
1173 } else if (existing != configs.end() && requestedIsValid) {
1174 *existing = *out_suggested;
1175 *_aidl_return = true;
1176 LOG(DEBUG) << __func__ << ": updated port config " << out_suggested->toString();
1177 } else {
1178 LOG(DEBUG) << __func__ << ": not applied; existing config ? " << (existing != configs.end())
1179 << "; requested is valid? " << requestedIsValid << ", fully specified? "
1180 << requestedIsFullySpecified;
1181 *_aidl_return = false;
1182 }
1183 return ndk::ScopedAStatus::ok();
1184}
1185
1186ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
1187 auto& patches = getConfig().patches;
1188 auto patchIt = findById<AudioPatch>(patches, in_patchId);
1189 if (patchIt != patches.end()) {
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001190 auto patchesBackup = mPatches;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001191 cleanUpPatch(patchIt->id);
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001192 if (auto status = updateStreamsConnectedState(*patchIt, AudioPatch{}); !status.isOk()) {
1193 mPatches = std::move(patchesBackup);
1194 return status;
1195 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001196 patches.erase(patchIt);
1197 LOG(DEBUG) << __func__ << ": erased patch " << in_patchId;
1198 return ndk::ScopedAStatus::ok();
1199 }
1200 LOG(ERROR) << __func__ << ": patch id " << in_patchId << " not found";
1201 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1202}
1203
1204ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
1205 auto& configs = getConfig().portConfigs;
1206 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
1207 if (configIt != configs.end()) {
1208 if (mStreams.count(in_portConfigId) != 0) {
1209 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
1210 << " has a stream opened on it";
1211 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1212 }
1213 auto patchIt = mPatches.find(in_portConfigId);
1214 if (patchIt != mPatches.end()) {
1215 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
1216 << " is used by the patch with id " << patchIt->second;
1217 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1218 }
1219 auto& initials = getConfig().initialConfigs;
1220 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
1221 if (initialIt == initials.end()) {
1222 configs.erase(configIt);
1223 LOG(DEBUG) << __func__ << ": erased port config " << in_portConfigId;
1224 } else if (*configIt != *initialIt) {
1225 *configIt = *initialIt;
1226 LOG(DEBUG) << __func__ << ": reset port config " << in_portConfigId;
1227 }
1228 return ndk::ScopedAStatus::ok();
1229 }
1230 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId << " not found";
1231 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1232}
1233
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001234ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) {
1235 *_aidl_return = mMasterMute;
1236 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1237 return ndk::ScopedAStatus::ok();
1238}
1239
1240ndk::ScopedAStatus Module::setMasterMute(bool in_mute) {
1241 LOG(DEBUG) << __func__ << ": " << in_mute;
jiabin783c48b2023-02-28 18:28:06 +00001242 auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1243 : onMasterMuteChanged(in_mute);
1244 if (result.isOk()) {
1245 mMasterMute = in_mute;
1246 } else {
1247 LOG(ERROR) << __func__ << ": failed calling onMasterMuteChanged(" << in_mute
1248 << "), error=" << result;
1249 // Reset master mute if it failed.
1250 onMasterMuteChanged(mMasterMute);
1251 }
Mikhail Naganov55045b52023-10-24 17:03:50 -07001252 return result;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001253}
1254
1255ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) {
1256 *_aidl_return = mMasterVolume;
1257 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1258 return ndk::ScopedAStatus::ok();
1259}
1260
1261ndk::ScopedAStatus Module::setMasterVolume(float in_volume) {
1262 LOG(DEBUG) << __func__ << ": " << in_volume;
1263 if (in_volume >= 0.0f && in_volume <= 1.0f) {
jiabin783c48b2023-02-28 18:28:06 +00001264 auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1265 : onMasterVolumeChanged(in_volume);
1266 if (result.isOk()) {
1267 mMasterVolume = in_volume;
1268 } else {
1269 // Reset master volume if it failed.
1270 LOG(ERROR) << __func__ << ": failed calling onMasterVolumeChanged(" << in_volume
1271 << "), error=" << result;
1272 onMasterVolumeChanged(mMasterVolume);
1273 }
Mikhail Naganov55045b52023-10-24 17:03:50 -07001274 return result;
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001275 }
1276 LOG(ERROR) << __func__ << ": invalid master volume value: " << in_volume;
1277 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1278}
1279
1280ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) {
1281 *_aidl_return = mMicMute;
1282 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1283 return ndk::ScopedAStatus::ok();
1284}
1285
1286ndk::ScopedAStatus Module::setMicMute(bool in_mute) {
1287 LOG(DEBUG) << __func__ << ": " << in_mute;
1288 mMicMute = in_mute;
1289 return ndk::ScopedAStatus::ok();
1290}
1291
Mikhail Naganovef6bc742022-10-06 00:14:19 +00001292ndk::ScopedAStatus Module::getMicrophones(std::vector<MicrophoneInfo>* _aidl_return) {
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +00001293 *_aidl_return = getMicrophoneInfos();
Mikhail Naganovef6bc742022-10-06 00:14:19 +00001294 LOG(DEBUG) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return);
1295 return ndk::ScopedAStatus::ok();
1296}
1297
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001298ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) {
Mikhail Naganov04ae8222023-01-11 15:48:10 -08001299 if (!isValidAudioMode(in_mode)) {
1300 LOG(ERROR) << __func__ << ": invalid mode " << toString(in_mode);
1301 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1302 }
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001303 // No checks for supported audio modes here, it's an informative notification.
1304 LOG(DEBUG) << __func__ << ": " << toString(in_mode);
1305 return ndk::ScopedAStatus::ok();
1306}
1307
1308ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) {
1309 LOG(DEBUG) << __func__ << ": " << toString(in_rotation);
1310 return ndk::ScopedAStatus::ok();
1311}
1312
1313ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) {
1314 LOG(DEBUG) << __func__ << ": " << in_isTurnedOn;
1315 return ndk::ScopedAStatus::ok();
1316}
1317
Vlad Popa83a6d822022-11-07 13:53:57 +01001318ndk::ScopedAStatus Module::getSoundDose(std::shared_ptr<ISoundDose>* _aidl_return) {
Mikhail Naganov7499a002023-02-27 18:51:44 -08001319 if (!mSoundDose) {
Vlad Popa2afbd1e2022-12-28 17:04:58 +01001320 mSoundDose = ndk::SharedRefBase::make<sounddose::SoundDose>();
Vlad Popa943b7e22022-12-08 14:24:12 +01001321 }
Mikhail Naganov780fefb2023-07-21 17:01:38 -07001322 *_aidl_return = mSoundDose.getInstance();
Vlad Popa943b7e22022-12-08 14:24:12 +01001323 LOG(DEBUG) << __func__ << ": returning instance of ISoundDose: " << _aidl_return->get();
Vlad Popa83a6d822022-11-07 13:53:57 +01001324 return ndk::ScopedAStatus::ok();
1325}
1326
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001327ndk::ScopedAStatus Module::generateHwAvSyncId(int32_t* _aidl_return) {
1328 LOG(DEBUG) << __func__;
1329 (void)_aidl_return;
1330 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1331}
1332
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001333const std::string Module::VendorDebug::kForceTransientBurstName = "aosp.forceTransientBurst";
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001334const std::string Module::VendorDebug::kForceSynchronousDrainName = "aosp.forceSynchronousDrain";
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001335
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001336ndk::ScopedAStatus Module::getVendorParameters(const std::vector<std::string>& in_ids,
1337 std::vector<VendorParameter>* _aidl_return) {
1338 LOG(DEBUG) << __func__ << ": id count: " << in_ids.size();
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001339 bool allParametersKnown = true;
1340 for (const auto& id : in_ids) {
1341 if (id == VendorDebug::kForceTransientBurstName) {
1342 VendorParameter forceTransientBurst{.id = id};
1343 forceTransientBurst.ext.setParcelable(Boolean{mVendorDebug.forceTransientBurst});
1344 _aidl_return->push_back(std::move(forceTransientBurst));
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001345 } else if (id == VendorDebug::kForceSynchronousDrainName) {
1346 VendorParameter forceSynchronousDrain{.id = id};
1347 forceSynchronousDrain.ext.setParcelable(Boolean{mVendorDebug.forceSynchronousDrain});
1348 _aidl_return->push_back(std::move(forceSynchronousDrain));
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001349 } else {
1350 allParametersKnown = false;
1351 LOG(ERROR) << __func__ << ": unrecognized parameter \"" << id << "\"";
1352 }
1353 }
1354 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1355 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001356}
1357
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001358namespace {
1359
1360template <typename W>
1361bool extractParameter(const VendorParameter& p, decltype(W::value)* v) {
1362 std::optional<W> value;
1363 binder_status_t result = p.ext.getParcelable(&value);
1364 if (result == STATUS_OK && value.has_value()) {
1365 *v = value.value().value;
1366 return true;
1367 }
1368 LOG(ERROR) << __func__ << ": failed to read the value of the parameter \"" << p.id
1369 << "\": " << result;
1370 return false;
1371}
1372
1373} // namespace
1374
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001375ndk::ScopedAStatus Module::setVendorParameters(const std::vector<VendorParameter>& in_parameters,
1376 bool in_async) {
1377 LOG(DEBUG) << __func__ << ": parameter count " << in_parameters.size()
1378 << ", async: " << in_async;
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001379 bool allParametersKnown = true;
1380 for (const auto& p : in_parameters) {
1381 if (p.id == VendorDebug::kForceTransientBurstName) {
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001382 if (!extractParameter<Boolean>(p, &mVendorDebug.forceTransientBurst)) {
1383 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1384 }
1385 } else if (p.id == VendorDebug::kForceSynchronousDrainName) {
1386 if (!extractParameter<Boolean>(p, &mVendorDebug.forceSynchronousDrain)) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001387 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1388 }
1389 } else {
1390 allParametersKnown = false;
1391 LOG(ERROR) << __func__ << ": unrecognized parameter \"" << p.id << "\"";
1392 }
1393 }
1394 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1395 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001396}
1397
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001398ndk::ScopedAStatus Module::addDeviceEffect(
1399 int32_t in_portConfigId,
1400 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1401 if (in_effect == nullptr) {
1402 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect";
1403 } else {
1404 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder "
1405 << in_effect->asBinder().get();
1406 }
1407 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1408}
1409
1410ndk::ScopedAStatus Module::removeDeviceEffect(
1411 int32_t in_portConfigId,
1412 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1413 if (in_effect == nullptr) {
1414 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect";
1415 } else {
1416 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder "
1417 << in_effect->asBinder().get();
1418 }
1419 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1420}
1421
jiabin9a8e6862023-01-12 23:06:37 +00001422ndk::ScopedAStatus Module::getMmapPolicyInfos(AudioMMapPolicyType mmapPolicyType,
1423 std::vector<AudioMMapPolicyInfo>* _aidl_return) {
1424 LOG(DEBUG) << __func__ << ": mmap policy type " << toString(mmapPolicyType);
1425 std::set<int32_t> mmapSinks;
1426 std::set<int32_t> mmapSources;
1427 auto& ports = getConfig().ports;
1428 for (const auto& port : ports) {
1429 if (port.flags.getTag() == AudioIoFlags::Tag::input &&
1430 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::input>(),
1431 AudioInputFlags::MMAP_NOIRQ)) {
1432 mmapSinks.insert(port.id);
1433 } else if (port.flags.getTag() == AudioIoFlags::Tag::output &&
1434 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
1435 AudioOutputFlags::MMAP_NOIRQ)) {
1436 mmapSources.insert(port.id);
1437 }
1438 }
Mikhail Naganov85064912023-09-26 17:10:08 -07001439 if (mmapSources.empty() && mmapSinks.empty()) {
1440 AudioMMapPolicyInfo never;
1441 never.mmapPolicy = AudioMMapPolicy::NEVER;
1442 _aidl_return->push_back(never);
1443 return ndk::ScopedAStatus::ok();
1444 }
jiabin9a8e6862023-01-12 23:06:37 +00001445 for (const auto& route : getConfig().routes) {
1446 if (mmapSinks.count(route.sinkPortId) != 0) {
1447 // The sink is a mix port, add the sources if they are device ports.
1448 for (int sourcePortId : route.sourcePortIds) {
1449 auto sourcePortIt = findById<AudioPort>(ports, sourcePortId);
1450 if (sourcePortIt == ports.end()) {
1451 // This must not happen
1452 LOG(ERROR) << __func__ << ": port id " << sourcePortId << " cannot be found";
1453 continue;
1454 }
1455 if (sourcePortIt->ext.getTag() != AudioPortExt::Tag::device) {
1456 // The source is not a device port, skip
1457 continue;
1458 }
1459 AudioMMapPolicyInfo policyInfo;
1460 policyInfo.device = sourcePortIt->ext.get<AudioPortExt::Tag::device>().device;
1461 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1462 // default implementation.
1463 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1464 _aidl_return->push_back(policyInfo);
1465 }
1466 } else {
1467 auto sinkPortIt = findById<AudioPort>(ports, route.sinkPortId);
1468 if (sinkPortIt == ports.end()) {
1469 // This must not happen
1470 LOG(ERROR) << __func__ << ": port id " << route.sinkPortId << " cannot be found";
1471 continue;
1472 }
1473 if (sinkPortIt->ext.getTag() != AudioPortExt::Tag::device) {
1474 // The sink is not a device port, skip
1475 continue;
1476 }
1477 if (count_any(mmapSources, route.sourcePortIds)) {
1478 AudioMMapPolicyInfo policyInfo;
1479 policyInfo.device = sinkPortIt->ext.get<AudioPortExt::Tag::device>().device;
1480 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1481 // default implementation.
1482 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1483 _aidl_return->push_back(policyInfo);
1484 }
1485 }
1486 }
1487 return ndk::ScopedAStatus::ok();
1488}
1489
Eric Laurente2432ea2023-01-12 17:47:31 +01001490ndk::ScopedAStatus Module::supportsVariableLatency(bool* _aidl_return) {
1491 LOG(DEBUG) << __func__;
1492 *_aidl_return = false;
1493 return ndk::ScopedAStatus::ok();
1494}
1495
jiabinb76981e2023-01-18 00:58:30 +00001496ndk::ScopedAStatus Module::getAAudioMixerBurstCount(int32_t* _aidl_return) {
1497 if (!isMmapSupported()) {
1498 LOG(DEBUG) << __func__ << ": mmap is not supported ";
1499 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1500 }
1501 *_aidl_return = DEFAULT_AAUDIO_MIXER_BURST_COUNT;
1502 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1503 return ndk::ScopedAStatus::ok();
1504}
1505
1506ndk::ScopedAStatus Module::getAAudioHardwareBurstMinUsec(int32_t* _aidl_return) {
1507 if (!isMmapSupported()) {
1508 LOG(DEBUG) << __func__ << ": mmap is not supported ";
1509 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1510 }
1511 *_aidl_return = DEFAULT_AAUDIO_HARDWARE_BURST_MIN_DURATION_US;
1512 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1513 return ndk::ScopedAStatus::ok();
1514}
1515
1516bool Module::isMmapSupported() {
1517 if (mIsMmapSupported.has_value()) {
1518 return mIsMmapSupported.value();
1519 }
1520 std::vector<AudioMMapPolicyInfo> mmapPolicyInfos;
1521 if (!getMmapPolicyInfos(AudioMMapPolicyType::DEFAULT, &mmapPolicyInfos).isOk()) {
1522 mIsMmapSupported = false;
1523 } else {
1524 mIsMmapSupported =
1525 std::find_if(mmapPolicyInfos.begin(), mmapPolicyInfos.end(), [](const auto& info) {
1526 return info.mmapPolicy == AudioMMapPolicy::AUTO ||
1527 info.mmapPolicy == AudioMMapPolicy::ALWAYS;
1528 }) != mmapPolicyInfos.end();
1529 }
1530 return mIsMmapSupported.value();
1531}
1532
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001533ndk::ScopedAStatus Module::populateConnectedDevicePort(AudioPort* audioPort) {
1534 if (audioPort->ext.getTag() != AudioPortExt::device) {
1535 LOG(ERROR) << __func__ << ": not a device port: " << audioPort->toString();
1536 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1537 }
1538 const auto& devicePort = audioPort->ext.get<AudioPortExt::device>();
1539 if (!devicePort.device.type.connection.empty()) {
1540 LOG(ERROR) << __func__
1541 << ": module implementation must override 'populateConnectedDevicePort' "
1542 << "to handle connection of external devices.";
1543 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1544 }
jiabin116d8392023-03-01 22:52:57 +00001545 LOG(VERBOSE) << __func__ << ": do nothing and return ok";
jiabin253bd322023-01-25 23:57:31 +00001546 return ndk::ScopedAStatus::ok();
1547}
1548
1549ndk::ScopedAStatus Module::checkAudioPatchEndpointsMatch(
1550 const std::vector<AudioPortConfig*>& sources __unused,
1551 const std::vector<AudioPortConfig*>& sinks __unused) {
jiabin116d8392023-03-01 22:52:57 +00001552 LOG(VERBOSE) << __func__ << ": do nothing and return ok";
jiabin253bd322023-01-25 23:57:31 +00001553 return ndk::ScopedAStatus::ok();
1554}
1555
jiabin783c48b2023-02-28 18:28:06 +00001556void Module::onExternalDeviceConnectionChanged(
1557 const ::aidl::android::media::audio::common::AudioPort& audioPort __unused,
1558 bool connected __unused) {
1559 LOG(DEBUG) << __func__ << ": do nothing and return";
1560}
1561
jiabindd23b0e2023-12-11 19:10:05 +00001562void Module::onPrepareToDisconnectExternalDevice(
1563 const ::aidl::android::media::audio::common::AudioPort& audioPort __unused) {
1564 LOG(DEBUG) << __func__ << ": do nothing and return";
1565}
1566
jiabin783c48b2023-02-28 18:28:06 +00001567ndk::ScopedAStatus Module::onMasterMuteChanged(bool mute __unused) {
1568 LOG(VERBOSE) << __func__ << ": do nothing and return ok";
1569 return ndk::ScopedAStatus::ok();
1570}
1571
1572ndk::ScopedAStatus Module::onMasterVolumeChanged(float volume __unused) {
1573 LOG(VERBOSE) << __func__ << ": do nothing and return ok";
1574 return ndk::ScopedAStatus::ok();
1575}
1576
Lorena Torres-Huerta533cc782023-01-18 00:11:48 +00001577std::vector<MicrophoneInfo> Module::getMicrophoneInfos() {
1578 std::vector<MicrophoneInfo> result;
1579 Configuration& config = getConfig();
1580 for (const AudioPort& port : config.ports) {
1581 if (port.ext.getTag() == AudioPortExt::Tag::device) {
1582 const AudioDeviceType deviceType =
1583 port.ext.get<AudioPortExt::Tag::device>().device.type.type;
1584 if (deviceType == AudioDeviceType::IN_MICROPHONE ||
1585 deviceType == AudioDeviceType::IN_MICROPHONE_BACK) {
1586 // Placeholder values. Vendor implementations must populate MicrophoneInfo
1587 // accordingly based on their physical microphone parameters.
1588 result.push_back(MicrophoneInfo{
1589 .id = port.name,
1590 .device = port.ext.get<AudioPortExt::Tag::device>().device,
1591 .group = 0,
1592 .indexInTheGroup = 0,
1593 });
1594 }
1595 }
1596 }
1597 return result;
1598}
1599
Ram Mohan18f0d512023-07-01 00:47:09 +05301600ndk::ScopedAStatus Module::bluetoothParametersUpdated() {
1601 return mStreams.bluetoothParametersUpdated();
1602}
1603
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001604} // namespace aidl::android::hardware::audio::core