blob: 48d14580a776e18bbecf7cd8eac9c2368917e91b [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 <Utils.h>
22#include <aidl/android/media/audio/common/AudioInputFlags.h>
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000023#include <aidl/android/media/audio/common/AudioOutputFlags.h>
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -070024#include <android-base/logging.h>
25#include <android/binder_ibinder_platform.h>
26#include <error/expected_utils.h>
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000027
Mikhail Naganov10c6fe22022-09-30 23:49:17 +000028#include "core-impl/Bluetooth.h"
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000029#include "core-impl/Module.h"
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053030#include "core-impl/ModuleRemoteSubmix.h"
jiabin253bd322023-01-25 23:57:31 +000031#include "core-impl/ModuleUsb.h"
Vlad Popa943b7e22022-12-08 14:24:12 +010032#include "core-impl/SoundDose.h"
Mikhail Naganovf429c032023-01-07 00:24:50 +000033#include "core-impl/StreamStub.h"
Mikhail Naganov3b125b72022-10-05 02:12:39 +000034#include "core-impl/Telephony.h"
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000035#include "core-impl/utils.h"
36
Mikhail Naganov872d4a62023-03-09 18:19:01 -080037using aidl::android::hardware::audio::common::getFrameSizeInBytes;
38using aidl::android::hardware::audio::common::isBitPositionFlagSet;
39using aidl::android::hardware::audio::common::isValidAudioMode;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000040using aidl::android::hardware::audio::common::SinkMetadata;
41using aidl::android::hardware::audio::common::SourceMetadata;
Vlad Popa2afbd1e2022-12-28 17:04:58 +010042using aidl::android::hardware::audio::core::sounddose::ISoundDose;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000043using aidl::android::media::audio::common::AudioChannelLayout;
Mikhail Naganovef6bc742022-10-06 00:14:19 +000044using aidl::android::media::audio::common::AudioDevice;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000045using aidl::android::media::audio::common::AudioFormatDescription;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000046using aidl::android::media::audio::common::AudioFormatType;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000047using aidl::android::media::audio::common::AudioInputFlags;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000048using aidl::android::media::audio::common::AudioIoFlags;
jiabin9a8e6862023-01-12 23:06:37 +000049using aidl::android::media::audio::common::AudioMMapPolicy;
50using aidl::android::media::audio::common::AudioMMapPolicyInfo;
51using aidl::android::media::audio::common::AudioMMapPolicyType;
Mikhail Naganov04ae8222023-01-11 15:48:10 -080052using aidl::android::media::audio::common::AudioMode;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000053using aidl::android::media::audio::common::AudioOffloadInfo;
54using aidl::android::media::audio::common::AudioOutputFlags;
55using aidl::android::media::audio::common::AudioPort;
56using aidl::android::media::audio::common::AudioPortConfig;
57using aidl::android::media::audio::common::AudioPortExt;
58using aidl::android::media::audio::common::AudioProfile;
Mikhail Naganov20047bc2023-01-05 20:16:07 +000059using aidl::android::media::audio::common::Boolean;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000060using aidl::android::media::audio::common::Int;
Mikhail Naganov6725ef52023-02-09 17:52:50 -080061using aidl::android::media::audio::common::MicrophoneInfo;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000062using aidl::android::media::audio::common::PcmType;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000063
64namespace aidl::android::hardware::audio::core {
65
66namespace {
67
68bool generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) {
69 *config = {};
70 config->portId = port.id;
71 if (port.profiles.empty()) {
72 LOG(ERROR) << __func__ << ": port " << port.id << " has no profiles";
73 return false;
74 }
75 const auto& profile = port.profiles.begin();
76 config->format = profile->format;
77 if (profile->channelMasks.empty()) {
78 LOG(ERROR) << __func__ << ": the first profile in port " << port.id
79 << " has no channel masks";
80 return false;
81 }
82 config->channelMask = *profile->channelMasks.begin();
83 if (profile->sampleRates.empty()) {
84 LOG(ERROR) << __func__ << ": the first profile in port " << port.id
85 << " has no sample rates";
86 return false;
87 }
88 Int sampleRate;
89 sampleRate.value = *profile->sampleRates.begin();
90 config->sampleRate = sampleRate;
91 config->flags = port.flags;
92 config->ext = port.ext;
93 return true;
94}
95
96bool 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
111std::shared_ptr<Module> Module::createInstance(Type type) {
112 switch (type) {
113 case Module::Type::USB:
114 return ndk::SharedRefBase::make<ModuleUsb>(type);
jiabin253bd322023-01-25 23:57:31 +0000115 case Type::R_SUBMIX:
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530116 return ndk::SharedRefBase::make<ModuleRemoteSubmix>(type);
117 case Type::DEFAULT:
jiabin253bd322023-01-25 23:57:31 +0000118 default:
119 return ndk::SharedRefBase::make<Module>(type);
120 }
121}
122
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700123std::ostream& operator<<(std::ostream& os, Module::Type t) {
124 switch (t) {
125 case Module::Type::DEFAULT:
126 os << "default";
127 break;
128 case Module::Type::R_SUBMIX:
129 os << "r_submix";
130 break;
131 case Module::Type::USB:
132 os << "usb";
133 break;
134 }
135 return os;
136}
137
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000138void Module::cleanUpPatch(int32_t patchId) {
139 erase_all_values(mPatches, std::set<int32_t>{patchId});
140}
141
Mikhail Naganov8651b362023-01-06 23:15:27 +0000142ndk::ScopedAStatus Module::createStreamContext(
143 int32_t in_portConfigId, int64_t in_bufferSizeFrames,
144 std::shared_ptr<IStreamCallback> asyncCallback,
145 std::shared_ptr<IStreamOutEventCallback> outEventCallback, StreamContext* out_context) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000146 if (in_bufferSizeFrames <= 0) {
147 LOG(ERROR) << __func__ << ": non-positive buffer size " << in_bufferSizeFrames;
148 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
149 }
150 if (in_bufferSizeFrames < kMinimumStreamBufferSizeFrames) {
151 LOG(ERROR) << __func__ << ": insufficient buffer size " << in_bufferSizeFrames
152 << ", must be at least " << kMinimumStreamBufferSizeFrames;
153 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
154 }
155 auto& configs = getConfig().portConfigs;
156 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000157 // Since this is a private method, it is assumed that
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000158 // validity of the portConfigId has already been checked.
159 const size_t frameSize =
160 getFrameSizeInBytes(portConfigIt->format.value(), portConfigIt->channelMask.value());
161 if (frameSize == 0) {
162 LOG(ERROR) << __func__ << ": could not calculate frame size for port config "
163 << portConfigIt->toString();
164 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
165 }
166 LOG(DEBUG) << __func__ << ": frame size " << frameSize << " bytes";
Mikhail Naganovb511b8a2023-05-15 14:35:24 -0700167 if (frameSize > static_cast<size_t>(kMaximumStreamBufferSizeBytes / in_bufferSizeFrames)) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000168 LOG(ERROR) << __func__ << ": buffer size " << in_bufferSizeFrames
169 << " frames is too large, maximum size is "
170 << kMaximumStreamBufferSizeBytes / frameSize;
171 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
172 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000173 const auto& flags = portConfigIt->flags.value();
174 if ((flags.getTag() == AudioIoFlags::Tag::input &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000175 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::input>(),
176 AudioInputFlags::MMAP_NOIRQ)) ||
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000177 (flags.getTag() == AudioIoFlags::Tag::output &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000178 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::output>(),
179 AudioOutputFlags::MMAP_NOIRQ))) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000180 StreamContext::DebugParameters params{mDebug.streamTransientStateDelayMs,
Mikhail Naganov194daaa2023-01-05 22:34:20 +0000181 mVendorDebug.forceTransientBurst,
182 mVendorDebug.forceSynchronousDrain};
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000183 StreamContext temp(
184 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
185 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530186 portConfigIt->portId, portConfigIt->format.value(),
187 portConfigIt->channelMask.value(), portConfigIt->sampleRate.value().value, flags,
Mikhail Naganovb42a69e2023-06-16 12:38:25 -0700188 portConfigIt->ext.get<AudioPortExt::mix>().handle,
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000189 std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames),
Mikhail Naganov8651b362023-01-06 23:15:27 +0000190 asyncCallback, outEventCallback, params);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000191 if (temp.isValid()) {
192 *out_context = std::move(temp);
193 } else {
194 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
195 }
196 } else {
197 // TODO: Implement simulation of MMAP buffer allocation
198 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000199 return ndk::ScopedAStatus::ok();
200}
201
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000202std::vector<AudioDevice> Module::findConnectedDevices(int32_t portConfigId) {
203 std::vector<AudioDevice> result;
204 auto& ports = getConfig().ports;
205 auto portIds = portIdsFromPortConfigIds(findConnectedPortConfigIds(portConfigId));
206 for (auto it = portIds.begin(); it != portIds.end(); ++it) {
207 auto portIt = findById<AudioPort>(ports, *it);
208 if (portIt != ports.end() && portIt->ext.getTag() == AudioPortExt::Tag::device) {
209 result.push_back(portIt->ext.template get<AudioPortExt::Tag::device>().device);
210 }
211 }
212 return result;
213}
214
215std::set<int32_t> Module::findConnectedPortConfigIds(int32_t portConfigId) {
216 std::set<int32_t> result;
217 auto patchIdsRange = mPatches.equal_range(portConfigId);
218 auto& patches = getConfig().patches;
219 for (auto it = patchIdsRange.first; it != patchIdsRange.second; ++it) {
220 auto patchIt = findById<AudioPatch>(patches, it->second);
221 if (patchIt == patches.end()) {
222 LOG(FATAL) << __func__ << ": patch with id " << it->second << " taken from mPatches "
223 << "not found in the configuration";
224 }
225 if (std::find(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end(),
226 portConfigId) != patchIt->sourcePortConfigIds.end()) {
227 result.insert(patchIt->sinkPortConfigIds.begin(), patchIt->sinkPortConfigIds.end());
228 } else {
229 result.insert(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end());
230 }
231 }
232 return result;
233}
234
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000235ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) {
236 auto& configs = getConfig().portConfigs;
237 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
238 if (portConfigIt == configs.end()) {
239 LOG(ERROR) << __func__ << ": existing port config id " << in_portConfigId << " not found";
240 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
241 }
242 const int32_t portId = portConfigIt->portId;
243 // In our implementation, configs of mix ports always have unique IDs.
244 CHECK(portId != in_portConfigId);
245 auto& ports = getConfig().ports;
246 auto portIt = findById<AudioPort>(ports, portId);
247 if (portIt == ports.end()) {
248 LOG(ERROR) << __func__ << ": port id " << portId << " used by port config id "
249 << in_portConfigId << " not found";
250 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
251 }
252 if (mStreams.count(in_portConfigId) != 0) {
253 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
254 << " already has a stream opened on it";
255 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
256 }
257 if (portIt->ext.getTag() != AudioPortExt::Tag::mix) {
258 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
259 << " does not correspond to a mix port";
260 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
261 }
Mikhail Naganovb511b8a2023-05-15 14:35:24 -0700262 const size_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000263 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
264 LOG(ERROR) << __func__ << ": port id " << portId
265 << " has already reached maximum allowed opened stream count: "
266 << maxOpenStreamCount;
267 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
268 }
269 *port = &(*portIt);
270 return ndk::ScopedAStatus::ok();
271}
272
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000273template <typename C>
274std::set<int32_t> Module::portIdsFromPortConfigIds(C portConfigIds) {
275 std::set<int32_t> result;
276 auto& portConfigs = getConfig().portConfigs;
277 for (auto it = portConfigIds.begin(); it != portConfigIds.end(); ++it) {
278 auto portConfigIt = findById<AudioPortConfig>(portConfigs, *it);
279 if (portConfigIt != portConfigs.end()) {
280 result.insert(portConfigIt->portId);
281 }
282 }
283 return result;
284}
285
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000286internal::Configuration& Module::getConfig() {
287 if (!mConfig) {
Mikhail Naganovc8e43122022-12-09 00:33:47 +0000288 switch (mType) {
289 case Type::DEFAULT:
290 mConfig = std::move(internal::getPrimaryConfiguration());
291 break;
292 case Type::R_SUBMIX:
293 mConfig = std::move(internal::getRSubmixConfiguration());
294 break;
jiabinb309d8d2023-01-20 19:07:15 +0000295 case Type::USB:
296 mConfig = std::move(internal::getUsbConfiguration());
jiabin253bd322023-01-25 23:57:31 +0000297 break;
Mikhail Naganovc8e43122022-12-09 00:33:47 +0000298 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000299 }
300 return *mConfig;
301}
302
303void Module::registerPatch(const AudioPatch& patch) {
304 auto& configs = getConfig().portConfigs;
305 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
306 for (auto portConfigId : portConfigIds) {
307 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
308 if (configIt != configs.end()) {
309 mPatches.insert(std::pair{portConfigId, patch.id});
310 if (configIt->portId != portConfigId) {
311 mPatches.insert(std::pair{configIt->portId, patch.id});
312 }
313 }
314 };
315 };
316 do_insert(patch.sourcePortConfigIds);
317 do_insert(patch.sinkPortConfigIds);
318}
319
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700320ndk::ScopedAStatus Module::updateStreamsConnectedState(const AudioPatch& oldPatch,
321 const AudioPatch& newPatch) {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000322 // Streams from the old patch need to be disconnected, streams from the new
323 // patch need to be connected. If the stream belongs to both patches, no need
324 // to update it.
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700325 auto maybeFailure = ndk::ScopedAStatus::ok();
326 std::set<int32_t> idsToDisconnect, idsToConnect, idsToDisconnectOnFailure;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000327 idsToDisconnect.insert(oldPatch.sourcePortConfigIds.begin(),
328 oldPatch.sourcePortConfigIds.end());
329 idsToDisconnect.insert(oldPatch.sinkPortConfigIds.begin(), oldPatch.sinkPortConfigIds.end());
330 idsToConnect.insert(newPatch.sourcePortConfigIds.begin(), newPatch.sourcePortConfigIds.end());
331 idsToConnect.insert(newPatch.sinkPortConfigIds.begin(), newPatch.sinkPortConfigIds.end());
332 std::for_each(idsToDisconnect.begin(), idsToDisconnect.end(), [&](const auto& portConfigId) {
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700333 if (idsToConnect.count(portConfigId) == 0 && mStreams.count(portConfigId) != 0) {
334 if (auto status = mStreams.setStreamConnectedDevices(portConfigId, {}); status.isOk()) {
335 LOG(DEBUG) << "updateStreamsConnectedState: The stream on port config id "
336 << portConfigId << " has been disconnected";
337 } else {
338 // Disconnection is tricky to roll back, just register a failure.
339 maybeFailure = std::move(status);
340 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000341 }
342 });
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700343 if (!maybeFailure.isOk()) return maybeFailure;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000344 std::for_each(idsToConnect.begin(), idsToConnect.end(), [&](const auto& portConfigId) {
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700345 if (idsToDisconnect.count(portConfigId) == 0 && mStreams.count(portConfigId) != 0) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000346 const auto connectedDevices = findConnectedDevices(portConfigId);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700347 if (connectedDevices.empty()) {
348 // This is important as workers use the vector size to derive the connection status.
349 LOG(FATAL) << "updateStreamsConnectedState: No connected devices found for port "
350 "config id "
351 << portConfigId;
352 }
353 if (auto status = mStreams.setStreamConnectedDevices(portConfigId, connectedDevices);
354 status.isOk()) {
355 LOG(DEBUG) << "updateStreamsConnectedState: The stream on port config id "
356 << portConfigId << " has been connected to: "
357 << ::android::internal::ToString(connectedDevices);
358 } else {
359 maybeFailure = std::move(status);
360 idsToDisconnectOnFailure.insert(portConfigId);
361 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000362 }
363 });
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700364 if (!maybeFailure.isOk()) {
365 LOG(WARNING) << __func__ << ": Due to a failure, disconnecting streams on port config ids "
366 << ::android::internal::ToString(idsToDisconnectOnFailure);
367 std::for_each(idsToDisconnectOnFailure.begin(), idsToDisconnectOnFailure.end(),
368 [&](const auto& portConfigId) {
369 auto status = mStreams.setStreamConnectedDevices(portConfigId, {});
370 (void)status.isOk(); // Can't do much about a failure here.
371 });
372 return maybeFailure;
373 }
374 return ndk::ScopedAStatus::ok();
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000375}
376
Mikhail Naganov00603d12022-05-02 22:52:13 +0000377ndk::ScopedAStatus Module::setModuleDebug(
378 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700379 LOG(DEBUG) << __func__ << ": " << mType << ": old flags:" << mDebug.toString()
Mikhail Naganov00603d12022-05-02 22:52:13 +0000380 << ", new flags: " << in_debug.toString();
381 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
382 !mConnectedDevicePorts.empty()) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700383 LOG(ERROR) << __func__ << ": " << mType
384 << ": attempting to change device connections simulation while having external "
385 << "devices connected";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000386 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
387 }
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000388 if (in_debug.streamTransientStateDelayMs < 0) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700389 LOG(ERROR) << __func__ << ": " << mType << ": streamTransientStateDelayMs is negative: "
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000390 << in_debug.streamTransientStateDelayMs;
391 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
392 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000393 mDebug = in_debug;
394 return ndk::ScopedAStatus::ok();
395}
396
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000397ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
Mikhail Naganov7499a002023-02-27 18:51:44 -0800398 if (!mTelephony) {
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000399 mTelephony = ndk::SharedRefBase::make<Telephony>();
400 }
Mikhail Naganov7499a002023-02-27 18:51:44 -0800401 *_aidl_return = mTelephony.getPtr();
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000402 LOG(DEBUG) << __func__ << ": returning instance of ITelephony: " << _aidl_return->get();
403 return ndk::ScopedAStatus::ok();
404}
405
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000406ndk::ScopedAStatus Module::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
Mikhail Naganov7499a002023-02-27 18:51:44 -0800407 if (!mBluetooth) {
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000408 mBluetooth = ndk::SharedRefBase::make<Bluetooth>();
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000409 }
Mikhail Naganov7499a002023-02-27 18:51:44 -0800410 *_aidl_return = mBluetooth.getPtr();
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000411 LOG(DEBUG) << __func__ << ": returning instance of IBluetooth: " << _aidl_return->get();
412 return ndk::ScopedAStatus::ok();
413}
414
Mikhail Naganov7499a002023-02-27 18:51:44 -0800415ndk::ScopedAStatus Module::getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp>* _aidl_return) {
416 if (!mBluetoothA2dp) {
417 mBluetoothA2dp = ndk::SharedRefBase::make<BluetoothA2dp>();
418 }
419 *_aidl_return = mBluetoothA2dp.getPtr();
420 LOG(DEBUG) << __func__ << ": returning instance of IBluetoothA2dp: " << _aidl_return->get();
421 return ndk::ScopedAStatus::ok();
422}
423
Mikhail Naganovb5647da2023-03-06 14:37:38 -0800424ndk::ScopedAStatus Module::getBluetoothLe(std::shared_ptr<IBluetoothLe>* _aidl_return) {
425 if (!mBluetoothLe) {
426 mBluetoothLe = ndk::SharedRefBase::make<BluetoothLe>();
427 }
428 *_aidl_return = mBluetoothLe.getPtr();
429 LOG(DEBUG) << __func__ << ": returning instance of IBluetoothLe: " << _aidl_return->get();
430 return ndk::ScopedAStatus::ok();
431}
432
Mikhail Naganov00603d12022-05-02 22:52:13 +0000433ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
434 AudioPort* _aidl_return) {
435 const int32_t templateId = in_templateIdAndAdditionalData.id;
436 auto& ports = getConfig().ports;
437 AudioPort connectedPort;
438 { // Scope the template port so that we don't accidentally modify it.
439 auto templateIt = findById<AudioPort>(ports, templateId);
440 if (templateIt == ports.end()) {
441 LOG(ERROR) << __func__ << ": port id " << templateId << " not found";
442 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
443 }
444 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
445 LOG(ERROR) << __func__ << ": port id " << templateId << " is not a device port";
446 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
447 }
448 if (!templateIt->profiles.empty()) {
449 LOG(ERROR) << __func__ << ": port id " << templateId
450 << " does not have dynamic profiles";
451 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
452 }
453 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
454 if (templateDevicePort.device.type.connection.empty()) {
455 LOG(ERROR) << __func__ << ": port id " << templateId << " is permanently attached";
456 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
457 }
458 // Postpone id allocation until we ensure that there are no client errors.
459 connectedPort = *templateIt;
460 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
461 const auto& inputDevicePort =
462 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
463 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
464 connectedDevicePort.device.address = inputDevicePort.device.address;
465 LOG(DEBUG) << __func__ << ": device port " << connectedPort.id << " device set to "
466 << connectedDevicePort.device.toString();
467 // Check if there is already a connected port with for the same external device.
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700468 for (auto connectedPortPair : mConnectedDevicePorts) {
469 auto connectedPortIt = findById<AudioPort>(ports, connectedPortPair.first);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000470 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
471 connectedDevicePort.device) {
472 LOG(ERROR) << __func__ << ": device " << connectedDevicePort.device.toString()
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700473 << " is already connected at the device port id "
474 << connectedPortPair.first;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000475 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
476 }
477 }
478 }
479
480 if (!mDebug.simulateDeviceConnections) {
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700481 RETURN_STATUS_IF_ERROR(populateConnectedDevicePort(&connectedPort));
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700482 } else {
483 auto& connectedProfiles = getConfig().connectedProfiles;
484 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
485 connectedProfilesIt != connectedProfiles.end()) {
486 connectedPort.profiles = connectedProfilesIt->second;
487 }
488 }
489 if (connectedPort.profiles.empty()) {
490 LOG(ERROR) << "Profiles of a connected port still empty after connecting external device "
491 << connectedPort.toString();
Mikhail Naganov00603d12022-05-02 22:52:13 +0000492 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
493 }
494
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530495 for (auto profile : connectedPort.profiles) {
496 if (profile.channelMasks.empty()) {
497 LOG(ERROR) << __func__ << ": the profile " << profile.name << " has no channel masks";
498 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
499 }
500 if (profile.sampleRates.empty()) {
501 LOG(ERROR) << __func__ << ": the profile " << profile.name << " has no sample rates";
502 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
503 }
504 }
505
Mikhail Naganov00603d12022-05-02 22:52:13 +0000506 connectedPort.id = ++getConfig().nextPortId;
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700507 auto [connectedPortsIt, _] =
508 mConnectedDevicePorts.insert(std::pair(connectedPort.id, std::vector<int32_t>()));
Mikhail Naganov00603d12022-05-02 22:52:13 +0000509 LOG(DEBUG) << __func__ << ": template port " << templateId << " external device connected, "
510 << "connected port ID " << connectedPort.id;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000511 ports.push_back(connectedPort);
jiabin783c48b2023-02-28 18:28:06 +0000512 onExternalDeviceConnectionChanged(connectedPort, true /*connected*/);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000513
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700514 std::vector<int32_t> routablePortIds;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000515 std::vector<AudioRoute> newRoutes;
516 auto& routes = getConfig().routes;
517 for (auto& r : routes) {
518 if (r.sinkPortId == templateId) {
519 AudioRoute newRoute;
520 newRoute.sourcePortIds = r.sourcePortIds;
521 newRoute.sinkPortId = connectedPort.id;
522 newRoute.isExclusive = r.isExclusive;
523 newRoutes.push_back(std::move(newRoute));
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700524 routablePortIds.insert(routablePortIds.end(), r.sourcePortIds.begin(),
525 r.sourcePortIds.end());
Mikhail Naganov00603d12022-05-02 22:52:13 +0000526 } else {
527 auto& srcs = r.sourcePortIds;
528 if (std::find(srcs.begin(), srcs.end(), templateId) != srcs.end()) {
529 srcs.push_back(connectedPort.id);
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700530 routablePortIds.push_back(r.sinkPortId);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000531 }
532 }
533 }
534 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
535
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700536 // Note: this is a simplistic approach assuming that a mix port can only be populated
537 // from a single device port. Implementing support for stuffing dynamic profiles with a superset
538 // of all profiles from all routable dynamic device ports would be more involved.
539 for (const auto mixPortId : routablePortIds) {
540 auto portsIt = findById<AudioPort>(ports, mixPortId);
541 if (portsIt != ports.end() && portsIt->profiles.empty()) {
542 portsIt->profiles = connectedPort.profiles;
543 connectedPortsIt->second.push_back(portsIt->id);
544 }
545 }
546 *_aidl_return = std::move(connectedPort);
547
Mikhail Naganov00603d12022-05-02 22:52:13 +0000548 return ndk::ScopedAStatus::ok();
549}
550
551ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
552 auto& ports = getConfig().ports;
553 auto portIt = findById<AudioPort>(ports, in_portId);
554 if (portIt == ports.end()) {
555 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
556 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
557 }
558 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
559 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a device port";
560 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
561 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700562 auto connectedPortsIt = mConnectedDevicePorts.find(in_portId);
563 if (connectedPortsIt == mConnectedDevicePorts.end()) {
Mikhail Naganov00603d12022-05-02 22:52:13 +0000564 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a connected device port";
565 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
566 }
567 auto& configs = getConfig().portConfigs;
568 auto& initials = getConfig().initialConfigs;
569 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
570 if (config.portId == in_portId) {
571 // Check if the configuration was provided by the client.
572 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
573 return initialIt == initials.end() || config != *initialIt;
574 }
575 return false;
576 });
577 if (configIt != configs.end()) {
578 LOG(ERROR) << __func__ << ": port id " << in_portId << " has a non-default config with id "
579 << configIt->id;
580 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
581 }
jiabin783c48b2023-02-28 18:28:06 +0000582 onExternalDeviceConnectionChanged(*portIt, false /*connected*/);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000583 ports.erase(portIt);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000584 LOG(DEBUG) << __func__ << ": connected device port " << in_portId << " released";
585
586 auto& routes = getConfig().routes;
587 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
588 if (routesIt->sinkPortId == in_portId) {
589 routesIt = routes.erase(routesIt);
590 } else {
591 // Note: the list of sourcePortIds can't become empty because there must
592 // be the id of the template port in the route.
593 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
594 ++routesIt;
595 }
596 }
597
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700598 for (const auto mixPortId : connectedPortsIt->second) {
599 auto mixPortIt = findById<AudioPort>(ports, mixPortId);
600 if (mixPortIt != ports.end()) {
601 mixPortIt->profiles = {};
602 }
603 }
604 mConnectedDevicePorts.erase(connectedPortsIt);
605
Mikhail Naganov00603d12022-05-02 22:52:13 +0000606 return ndk::ScopedAStatus::ok();
607}
608
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000609ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
610 *_aidl_return = getConfig().patches;
611 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " patches";
612 return ndk::ScopedAStatus::ok();
613}
614
615ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
616 auto& ports = getConfig().ports;
617 auto portIt = findById<AudioPort>(ports, in_portId);
618 if (portIt != ports.end()) {
619 *_aidl_return = *portIt;
620 LOG(DEBUG) << __func__ << ": returning port by id " << in_portId;
621 return ndk::ScopedAStatus::ok();
622 }
623 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
624 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
625}
626
627ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
628 *_aidl_return = getConfig().portConfigs;
629 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " port configs";
630 return ndk::ScopedAStatus::ok();
631}
632
633ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
634 *_aidl_return = getConfig().ports;
635 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " ports";
636 return ndk::ScopedAStatus::ok();
637}
638
639ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
640 *_aidl_return = getConfig().routes;
641 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " routes";
642 return ndk::ScopedAStatus::ok();
643}
644
Mikhail Naganov00603d12022-05-02 22:52:13 +0000645ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
646 std::vector<AudioRoute>* _aidl_return) {
647 auto& ports = getConfig().ports;
648 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
649 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
650 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
651 }
652 auto& routes = getConfig().routes;
653 std::copy_if(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
654 [&](const auto& r) {
655 const auto& srcs = r.sourcePortIds;
656 return r.sinkPortId == in_portId ||
657 std::find(srcs.begin(), srcs.end(), in_portId) != srcs.end();
658 });
659 return ndk::ScopedAStatus::ok();
660}
661
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000662ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
663 OpenInputStreamReturn* _aidl_return) {
664 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", buffer size "
665 << in_args.bufferSizeFrames << " frames";
666 AudioPort* port = nullptr;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700667 RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000668 if (port->flags.getTag() != AudioIoFlags::Tag::input) {
669 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000670 << " does not correspond to an input mix port";
671 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
672 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000673 StreamContext context;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700674 RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
675 nullptr, nullptr, &context));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000676 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000677 std::shared_ptr<StreamIn> stream;
Mikhail Naganov9d16a6a2023-06-26 17:21:04 -0700678 RETURN_STATUS_IF_ERROR(createInputStream(in_args.sinkMetadata, std::move(context),
679 mConfig->microphones, &stream));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000680 StreamWrapper streamWrapper(stream);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700681 if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
682 RETURN_STATUS_IF_ERROR(
683 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
684 }
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000685 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
686 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000687 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000688 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000689 return ndk::ScopedAStatus::ok();
690}
691
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000692ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
693 OpenOutputStreamReturn* _aidl_return) {
694 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", has offload info? "
695 << (in_args.offloadInfo.has_value()) << ", buffer size " << in_args.bufferSizeFrames
696 << " frames";
697 AudioPort* port = nullptr;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700698 RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000699 if (port->flags.getTag() != AudioIoFlags::Tag::output) {
700 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000701 << " does not correspond to an output mix port";
702 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
703 }
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000704 const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
705 AudioOutputFlags::COMPRESS_OFFLOAD);
706 if (isOffload && !in_args.offloadInfo.has_value()) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000707 LOG(ERROR) << __func__ << ": port id " << port->id
Mikhail Naganov111e0ce2022-06-17 21:41:19 +0000708 << " has COMPRESS_OFFLOAD flag set, requires offload info";
709 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
710 }
Mikhail Naganov30301a42022-09-13 01:20:45 +0000711 const bool isNonBlocking = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
712 AudioOutputFlags::NON_BLOCKING);
713 if (isNonBlocking && in_args.callback == nullptr) {
714 LOG(ERROR) << __func__ << ": port id " << port->id
715 << " has NON_BLOCKING flag set, requires async callback";
716 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
717 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000718 StreamContext context;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700719 RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
720 isNonBlocking ? in_args.callback : nullptr,
721 in_args.eventCallback, &context));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000722 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000723 std::shared_ptr<StreamOut> stream;
Mikhail Naganov9d16a6a2023-06-26 17:21:04 -0700724 RETURN_STATUS_IF_ERROR(createOutputStream(in_args.sourceMetadata, std::move(context),
725 in_args.offloadInfo, &stream));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000726 StreamWrapper streamWrapper(stream);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700727 if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
728 RETURN_STATUS_IF_ERROR(
729 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
730 }
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000731 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
732 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000733 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000734 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000735 return ndk::ScopedAStatus::ok();
736}
737
Mikhail Naganov74927202022-12-19 16:37:14 +0000738ndk::ScopedAStatus Module::getSupportedPlaybackRateFactors(
739 SupportedPlaybackRateFactors* _aidl_return) {
740 LOG(DEBUG) << __func__;
741 (void)_aidl_return;
742 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
743}
744
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000745ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
Mikhail Naganov16db9b72022-06-17 21:36:18 +0000746 LOG(DEBUG) << __func__ << ": requested patch " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000747 if (in_requested.sourcePortConfigIds.empty()) {
748 LOG(ERROR) << __func__ << ": requested patch has empty sources list";
749 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
750 }
751 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
752 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sources list";
753 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
754 }
755 if (in_requested.sinkPortConfigIds.empty()) {
756 LOG(ERROR) << __func__ << ": requested patch has empty sinks list";
757 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
758 }
759 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
760 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sinks list";
761 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
762 }
763
764 auto& configs = getConfig().portConfigs;
765 std::vector<int32_t> missingIds;
766 auto sources =
767 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
768 if (!missingIds.empty()) {
769 LOG(ERROR) << __func__ << ": following source port config ids not found: "
770 << ::android::internal::ToString(missingIds);
771 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
772 }
773 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
774 if (!missingIds.empty()) {
775 LOG(ERROR) << __func__ << ": following sink port config ids not found: "
776 << ::android::internal::ToString(missingIds);
777 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
778 }
779 // bool indicates whether a non-exclusive route is available.
780 // If only an exclusive route is available, that means the patch can not be
781 // established if there is any other patch which currently uses the sink port.
782 std::map<int32_t, bool> allowedSinkPorts;
783 auto& routes = getConfig().routes;
784 for (auto src : sources) {
785 for (const auto& r : routes) {
786 const auto& srcs = r.sourcePortIds;
787 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
788 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
789 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
790 }
791 }
792 }
793 }
794 for (auto sink : sinks) {
795 if (allowedSinkPorts.count(sink->portId) == 0) {
796 LOG(ERROR) << __func__ << ": there is no route to the sink port id " << sink->portId;
797 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
798 }
799 }
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700800 RETURN_STATUS_IF_ERROR(checkAudioPatchEndpointsMatch(sources, sinks));
jiabin253bd322023-01-25 23:57:31 +0000801
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000802 auto& patches = getConfig().patches;
803 auto existing = patches.end();
804 std::optional<decltype(mPatches)> patchesBackup;
805 if (in_requested.id != 0) {
806 existing = findById<AudioPatch>(patches, in_requested.id);
807 if (existing != patches.end()) {
808 patchesBackup = mPatches;
809 cleanUpPatch(existing->id);
810 } else {
811 LOG(ERROR) << __func__ << ": not found existing patch id " << in_requested.id;
812 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
813 }
814 }
815 // Validate the requested patch.
816 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
817 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
818 LOG(ERROR) << __func__ << ": sink port id " << sinkPortId
819 << "is exclusive and is already used by some other patch";
820 if (patchesBackup.has_value()) {
821 mPatches = std::move(*patchesBackup);
822 }
823 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
824 }
825 }
826 *_aidl_return = in_requested;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000827 _aidl_return->minimumStreamBufferSizeFrames = kMinimumStreamBufferSizeFrames;
828 _aidl_return->latenciesMs.clear();
829 _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
830 _aidl_return->sinkPortConfigIds.size(), kLatencyMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000831 AudioPatch oldPatch{};
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000832 if (existing == patches.end()) {
833 _aidl_return->id = getConfig().nextPatchId++;
834 patches.push_back(*_aidl_return);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000835 } else {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000836 oldPatch = *existing;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000837 }
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700838 patchesBackup = mPatches;
839 registerPatch(*_aidl_return);
840 if (auto status = updateStreamsConnectedState(oldPatch, *_aidl_return); !status.isOk()) {
841 mPatches = std::move(*patchesBackup);
842 if (existing == patches.end()) {
843 patches.pop_back();
844 } else {
845 *existing = oldPatch;
846 }
847 return status;
848 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000849
850 LOG(DEBUG) << __func__ << ": " << (oldPatch.id == 0 ? "created" : "updated") << " patch "
851 << _aidl_return->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000852 return ndk::ScopedAStatus::ok();
853}
854
855ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
856 AudioPortConfig* out_suggested, bool* _aidl_return) {
857 LOG(DEBUG) << __func__ << ": requested " << in_requested.toString();
858 auto& configs = getConfig().portConfigs;
859 auto existing = configs.end();
860 if (in_requested.id != 0) {
861 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
862 existing == configs.end()) {
863 LOG(ERROR) << __func__ << ": existing port config id " << in_requested.id
864 << " not found";
865 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
866 }
867 }
868
869 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
870 if (portId == 0) {
871 LOG(ERROR) << __func__ << ": input port config does not specify portId";
872 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
873 }
874 auto& ports = getConfig().ports;
875 auto portIt = findById<AudioPort>(ports, portId);
876 if (portIt == ports.end()) {
877 LOG(ERROR) << __func__ << ": input port config points to non-existent portId " << portId;
878 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
879 }
880 if (existing != configs.end()) {
881 *out_suggested = *existing;
882 } else {
883 AudioPortConfig newConfig;
884 if (generateDefaultPortConfig(*portIt, &newConfig)) {
885 *out_suggested = newConfig;
886 } else {
887 LOG(ERROR) << __func__ << ": unable generate a default config for port " << portId;
888 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
889 }
890 }
891 // From this moment, 'out_suggested' is either an existing port config,
892 // or a new generated config. Now attempt to update it according to the specified
893 // fields of 'in_requested'.
894
895 bool requestedIsValid = true, requestedIsFullySpecified = true;
896
897 AudioIoFlags portFlags = portIt->flags;
898 if (in_requested.flags.has_value()) {
899 if (in_requested.flags.value() != portFlags) {
900 LOG(WARNING) << __func__ << ": requested flags "
901 << in_requested.flags.value().toString() << " do not match port's "
902 << portId << " flags " << portFlags.toString();
903 requestedIsValid = false;
904 }
905 } else {
906 requestedIsFullySpecified = false;
907 }
908
909 AudioProfile portProfile;
910 if (in_requested.format.has_value()) {
911 const auto& format = in_requested.format.value();
912 if (findAudioProfile(*portIt, format, &portProfile)) {
913 out_suggested->format = format;
914 } else {
915 LOG(WARNING) << __func__ << ": requested format " << format.toString()
916 << " is not found in port's " << portId << " profiles";
917 requestedIsValid = false;
918 }
919 } else {
920 requestedIsFullySpecified = false;
921 }
922 if (!findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
923 LOG(ERROR) << __func__ << ": port " << portId << " does not support format "
924 << out_suggested->format.value().toString() << " anymore";
925 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
926 }
927
928 if (in_requested.channelMask.has_value()) {
929 const auto& channelMask = in_requested.channelMask.value();
930 if (find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
931 portProfile.channelMasks.end()) {
932 out_suggested->channelMask = channelMask;
933 } else {
934 LOG(WARNING) << __func__ << ": requested channel mask " << channelMask.toString()
935 << " is not supported for the format " << portProfile.format.toString()
936 << " by the port " << portId;
937 requestedIsValid = false;
938 }
939 } else {
940 requestedIsFullySpecified = false;
941 }
942
943 if (in_requested.sampleRate.has_value()) {
944 const auto& sampleRate = in_requested.sampleRate.value();
945 if (find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
946 sampleRate.value) != portProfile.sampleRates.end()) {
947 out_suggested->sampleRate = sampleRate;
948 } else {
949 LOG(WARNING) << __func__ << ": requested sample rate " << sampleRate.value
950 << " is not supported for the format " << portProfile.format.toString()
951 << " by the port " << portId;
952 requestedIsValid = false;
953 }
954 } else {
955 requestedIsFullySpecified = false;
956 }
957
958 if (in_requested.gain.has_value()) {
959 // Let's pretend that gain can always be applied.
960 out_suggested->gain = in_requested.gain.value();
961 }
962
Mikhail Naganov248e9502023-02-21 16:32:40 -0800963 if (in_requested.ext.getTag() != AudioPortExt::Tag::unspecified) {
964 if (in_requested.ext.getTag() == out_suggested->ext.getTag()) {
965 if (out_suggested->ext.getTag() == AudioPortExt::Tag::mix) {
966 // 'AudioMixPortExt.handle' is set by the client, copy from in_requested
967 out_suggested->ext.get<AudioPortExt::Tag::mix>().handle =
968 in_requested.ext.get<AudioPortExt::Tag::mix>().handle;
969 }
970 } else {
971 LOG(WARNING) << __func__ << ": requested ext tag "
972 << toString(in_requested.ext.getTag()) << " do not match port's tag "
973 << toString(out_suggested->ext.getTag());
974 requestedIsValid = false;
975 }
976 }
977
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000978 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
979 out_suggested->id = getConfig().nextPortId++;
980 configs.push_back(*out_suggested);
981 *_aidl_return = true;
982 LOG(DEBUG) << __func__ << ": created new port config " << out_suggested->toString();
983 } else if (existing != configs.end() && requestedIsValid) {
984 *existing = *out_suggested;
985 *_aidl_return = true;
986 LOG(DEBUG) << __func__ << ": updated port config " << out_suggested->toString();
987 } else {
988 LOG(DEBUG) << __func__ << ": not applied; existing config ? " << (existing != configs.end())
989 << "; requested is valid? " << requestedIsValid << ", fully specified? "
990 << requestedIsFullySpecified;
991 *_aidl_return = false;
992 }
993 return ndk::ScopedAStatus::ok();
994}
995
996ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
997 auto& patches = getConfig().patches;
998 auto patchIt = findById<AudioPatch>(patches, in_patchId);
999 if (patchIt != patches.end()) {
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001000 auto patchesBackup = mPatches;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001001 cleanUpPatch(patchIt->id);
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001002 if (auto status = updateStreamsConnectedState(*patchIt, AudioPatch{}); !status.isOk()) {
1003 mPatches = std::move(patchesBackup);
1004 return status;
1005 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001006 patches.erase(patchIt);
1007 LOG(DEBUG) << __func__ << ": erased patch " << in_patchId;
1008 return ndk::ScopedAStatus::ok();
1009 }
1010 LOG(ERROR) << __func__ << ": patch id " << in_patchId << " not found";
1011 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1012}
1013
1014ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
1015 auto& configs = getConfig().portConfigs;
1016 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
1017 if (configIt != configs.end()) {
1018 if (mStreams.count(in_portConfigId) != 0) {
1019 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
1020 << " has a stream opened on it";
1021 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1022 }
1023 auto patchIt = mPatches.find(in_portConfigId);
1024 if (patchIt != mPatches.end()) {
1025 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
1026 << " is used by the patch with id " << patchIt->second;
1027 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1028 }
1029 auto& initials = getConfig().initialConfigs;
1030 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
1031 if (initialIt == initials.end()) {
1032 configs.erase(configIt);
1033 LOG(DEBUG) << __func__ << ": erased port config " << in_portConfigId;
1034 } else if (*configIt != *initialIt) {
1035 *configIt = *initialIt;
1036 LOG(DEBUG) << __func__ << ": reset port config " << in_portConfigId;
1037 }
1038 return ndk::ScopedAStatus::ok();
1039 }
1040 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId << " not found";
1041 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1042}
1043
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001044ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) {
1045 *_aidl_return = mMasterMute;
1046 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1047 return ndk::ScopedAStatus::ok();
1048}
1049
1050ndk::ScopedAStatus Module::setMasterMute(bool in_mute) {
1051 LOG(DEBUG) << __func__ << ": " << in_mute;
jiabin783c48b2023-02-28 18:28:06 +00001052 auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1053 : onMasterMuteChanged(in_mute);
1054 if (result.isOk()) {
1055 mMasterMute = in_mute;
1056 } else {
1057 LOG(ERROR) << __func__ << ": failed calling onMasterMuteChanged(" << in_mute
1058 << "), error=" << result;
1059 // Reset master mute if it failed.
1060 onMasterMuteChanged(mMasterMute);
1061 }
1062 return std::move(result);
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001063}
1064
1065ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) {
1066 *_aidl_return = mMasterVolume;
1067 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1068 return ndk::ScopedAStatus::ok();
1069}
1070
1071ndk::ScopedAStatus Module::setMasterVolume(float in_volume) {
1072 LOG(DEBUG) << __func__ << ": " << in_volume;
1073 if (in_volume >= 0.0f && in_volume <= 1.0f) {
jiabin783c48b2023-02-28 18:28:06 +00001074 auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1075 : onMasterVolumeChanged(in_volume);
1076 if (result.isOk()) {
1077 mMasterVolume = in_volume;
1078 } else {
1079 // Reset master volume if it failed.
1080 LOG(ERROR) << __func__ << ": failed calling onMasterVolumeChanged(" << in_volume
1081 << "), error=" << result;
1082 onMasterVolumeChanged(mMasterVolume);
1083 }
1084 return std::move(result);
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001085 }
1086 LOG(ERROR) << __func__ << ": invalid master volume value: " << in_volume;
1087 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1088}
1089
1090ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) {
1091 *_aidl_return = mMicMute;
1092 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1093 return ndk::ScopedAStatus::ok();
1094}
1095
1096ndk::ScopedAStatus Module::setMicMute(bool in_mute) {
1097 LOG(DEBUG) << __func__ << ": " << in_mute;
1098 mMicMute = in_mute;
1099 return ndk::ScopedAStatus::ok();
1100}
1101
Mikhail Naganovef6bc742022-10-06 00:14:19 +00001102ndk::ScopedAStatus Module::getMicrophones(std::vector<MicrophoneInfo>* _aidl_return) {
Pawan Wagh6f57cd92023-02-01 21:14:34 +00001103 *_aidl_return = getConfig().microphones;
Mikhail Naganovef6bc742022-10-06 00:14:19 +00001104 LOG(DEBUG) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return);
1105 return ndk::ScopedAStatus::ok();
1106}
1107
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001108ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) {
Mikhail Naganov04ae8222023-01-11 15:48:10 -08001109 if (!isValidAudioMode(in_mode)) {
1110 LOG(ERROR) << __func__ << ": invalid mode " << toString(in_mode);
1111 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1112 }
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001113 // No checks for supported audio modes here, it's an informative notification.
1114 LOG(DEBUG) << __func__ << ": " << toString(in_mode);
1115 return ndk::ScopedAStatus::ok();
1116}
1117
1118ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) {
1119 LOG(DEBUG) << __func__ << ": " << toString(in_rotation);
1120 return ndk::ScopedAStatus::ok();
1121}
1122
1123ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) {
1124 LOG(DEBUG) << __func__ << ": " << in_isTurnedOn;
1125 return ndk::ScopedAStatus::ok();
1126}
1127
Vlad Popa83a6d822022-11-07 13:53:57 +01001128ndk::ScopedAStatus Module::getSoundDose(std::shared_ptr<ISoundDose>* _aidl_return) {
Mikhail Naganov7499a002023-02-27 18:51:44 -08001129 if (!mSoundDose) {
Vlad Popa2afbd1e2022-12-28 17:04:58 +01001130 mSoundDose = ndk::SharedRefBase::make<sounddose::SoundDose>();
Vlad Popa943b7e22022-12-08 14:24:12 +01001131 }
Mikhail Naganov7499a002023-02-27 18:51:44 -08001132 *_aidl_return = mSoundDose.getPtr();
Vlad Popa943b7e22022-12-08 14:24:12 +01001133 LOG(DEBUG) << __func__ << ": returning instance of ISoundDose: " << _aidl_return->get();
Vlad Popa83a6d822022-11-07 13:53:57 +01001134 return ndk::ScopedAStatus::ok();
1135}
1136
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001137ndk::ScopedAStatus Module::generateHwAvSyncId(int32_t* _aidl_return) {
1138 LOG(DEBUG) << __func__;
1139 (void)_aidl_return;
1140 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1141}
1142
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001143const std::string Module::VendorDebug::kForceTransientBurstName = "aosp.forceTransientBurst";
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001144const std::string Module::VendorDebug::kForceSynchronousDrainName = "aosp.forceSynchronousDrain";
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001145
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001146ndk::ScopedAStatus Module::getVendorParameters(const std::vector<std::string>& in_ids,
1147 std::vector<VendorParameter>* _aidl_return) {
1148 LOG(DEBUG) << __func__ << ": id count: " << in_ids.size();
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001149 bool allParametersKnown = true;
1150 for (const auto& id : in_ids) {
1151 if (id == VendorDebug::kForceTransientBurstName) {
1152 VendorParameter forceTransientBurst{.id = id};
1153 forceTransientBurst.ext.setParcelable(Boolean{mVendorDebug.forceTransientBurst});
1154 _aidl_return->push_back(std::move(forceTransientBurst));
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001155 } else if (id == VendorDebug::kForceSynchronousDrainName) {
1156 VendorParameter forceSynchronousDrain{.id = id};
1157 forceSynchronousDrain.ext.setParcelable(Boolean{mVendorDebug.forceSynchronousDrain});
1158 _aidl_return->push_back(std::move(forceSynchronousDrain));
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001159 } else {
1160 allParametersKnown = false;
1161 LOG(ERROR) << __func__ << ": unrecognized parameter \"" << id << "\"";
1162 }
1163 }
1164 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1165 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001166}
1167
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001168namespace {
1169
1170template <typename W>
1171bool extractParameter(const VendorParameter& p, decltype(W::value)* v) {
1172 std::optional<W> value;
1173 binder_status_t result = p.ext.getParcelable(&value);
1174 if (result == STATUS_OK && value.has_value()) {
1175 *v = value.value().value;
1176 return true;
1177 }
1178 LOG(ERROR) << __func__ << ": failed to read the value of the parameter \"" << p.id
1179 << "\": " << result;
1180 return false;
1181}
1182
1183} // namespace
1184
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001185ndk::ScopedAStatus Module::setVendorParameters(const std::vector<VendorParameter>& in_parameters,
1186 bool in_async) {
1187 LOG(DEBUG) << __func__ << ": parameter count " << in_parameters.size()
1188 << ", async: " << in_async;
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001189 bool allParametersKnown = true;
1190 for (const auto& p : in_parameters) {
1191 if (p.id == VendorDebug::kForceTransientBurstName) {
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001192 if (!extractParameter<Boolean>(p, &mVendorDebug.forceTransientBurst)) {
1193 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1194 }
1195 } else if (p.id == VendorDebug::kForceSynchronousDrainName) {
1196 if (!extractParameter<Boolean>(p, &mVendorDebug.forceSynchronousDrain)) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001197 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1198 }
1199 } else {
1200 allParametersKnown = false;
1201 LOG(ERROR) << __func__ << ": unrecognized parameter \"" << p.id << "\"";
1202 }
1203 }
1204 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1205 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001206}
1207
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001208ndk::ScopedAStatus Module::addDeviceEffect(
1209 int32_t in_portConfigId,
1210 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1211 if (in_effect == nullptr) {
1212 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect";
1213 } else {
1214 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder "
1215 << in_effect->asBinder().get();
1216 }
1217 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1218}
1219
1220ndk::ScopedAStatus Module::removeDeviceEffect(
1221 int32_t in_portConfigId,
1222 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1223 if (in_effect == nullptr) {
1224 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect";
1225 } else {
1226 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder "
1227 << in_effect->asBinder().get();
1228 }
1229 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1230}
1231
jiabin9a8e6862023-01-12 23:06:37 +00001232ndk::ScopedAStatus Module::getMmapPolicyInfos(AudioMMapPolicyType mmapPolicyType,
1233 std::vector<AudioMMapPolicyInfo>* _aidl_return) {
1234 LOG(DEBUG) << __func__ << ": mmap policy type " << toString(mmapPolicyType);
1235 std::set<int32_t> mmapSinks;
1236 std::set<int32_t> mmapSources;
1237 auto& ports = getConfig().ports;
1238 for (const auto& port : ports) {
1239 if (port.flags.getTag() == AudioIoFlags::Tag::input &&
1240 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::input>(),
1241 AudioInputFlags::MMAP_NOIRQ)) {
1242 mmapSinks.insert(port.id);
1243 } else if (port.flags.getTag() == AudioIoFlags::Tag::output &&
1244 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
1245 AudioOutputFlags::MMAP_NOIRQ)) {
1246 mmapSources.insert(port.id);
1247 }
1248 }
1249 for (const auto& route : getConfig().routes) {
1250 if (mmapSinks.count(route.sinkPortId) != 0) {
1251 // The sink is a mix port, add the sources if they are device ports.
1252 for (int sourcePortId : route.sourcePortIds) {
1253 auto sourcePortIt = findById<AudioPort>(ports, sourcePortId);
1254 if (sourcePortIt == ports.end()) {
1255 // This must not happen
1256 LOG(ERROR) << __func__ << ": port id " << sourcePortId << " cannot be found";
1257 continue;
1258 }
1259 if (sourcePortIt->ext.getTag() != AudioPortExt::Tag::device) {
1260 // The source is not a device port, skip
1261 continue;
1262 }
1263 AudioMMapPolicyInfo policyInfo;
1264 policyInfo.device = sourcePortIt->ext.get<AudioPortExt::Tag::device>().device;
1265 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1266 // default implementation.
1267 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1268 _aidl_return->push_back(policyInfo);
1269 }
1270 } else {
1271 auto sinkPortIt = findById<AudioPort>(ports, route.sinkPortId);
1272 if (sinkPortIt == ports.end()) {
1273 // This must not happen
1274 LOG(ERROR) << __func__ << ": port id " << route.sinkPortId << " cannot be found";
1275 continue;
1276 }
1277 if (sinkPortIt->ext.getTag() != AudioPortExt::Tag::device) {
1278 // The sink is not a device port, skip
1279 continue;
1280 }
1281 if (count_any(mmapSources, route.sourcePortIds)) {
1282 AudioMMapPolicyInfo policyInfo;
1283 policyInfo.device = sinkPortIt->ext.get<AudioPortExt::Tag::device>().device;
1284 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1285 // default implementation.
1286 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1287 _aidl_return->push_back(policyInfo);
1288 }
1289 }
1290 }
1291 return ndk::ScopedAStatus::ok();
1292}
1293
Eric Laurente2432ea2023-01-12 17:47:31 +01001294ndk::ScopedAStatus Module::supportsVariableLatency(bool* _aidl_return) {
1295 LOG(DEBUG) << __func__;
1296 *_aidl_return = false;
1297 return ndk::ScopedAStatus::ok();
1298}
1299
jiabinb76981e2023-01-18 00:58:30 +00001300ndk::ScopedAStatus Module::getAAudioMixerBurstCount(int32_t* _aidl_return) {
1301 if (!isMmapSupported()) {
1302 LOG(DEBUG) << __func__ << ": mmap is not supported ";
1303 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1304 }
1305 *_aidl_return = DEFAULT_AAUDIO_MIXER_BURST_COUNT;
1306 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1307 return ndk::ScopedAStatus::ok();
1308}
1309
1310ndk::ScopedAStatus Module::getAAudioHardwareBurstMinUsec(int32_t* _aidl_return) {
1311 if (!isMmapSupported()) {
1312 LOG(DEBUG) << __func__ << ": mmap is not supported ";
1313 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1314 }
1315 *_aidl_return = DEFAULT_AAUDIO_HARDWARE_BURST_MIN_DURATION_US;
1316 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1317 return ndk::ScopedAStatus::ok();
1318}
1319
1320bool Module::isMmapSupported() {
1321 if (mIsMmapSupported.has_value()) {
1322 return mIsMmapSupported.value();
1323 }
1324 std::vector<AudioMMapPolicyInfo> mmapPolicyInfos;
1325 if (!getMmapPolicyInfos(AudioMMapPolicyType::DEFAULT, &mmapPolicyInfos).isOk()) {
1326 mIsMmapSupported = false;
1327 } else {
1328 mIsMmapSupported =
1329 std::find_if(mmapPolicyInfos.begin(), mmapPolicyInfos.end(), [](const auto& info) {
1330 return info.mmapPolicy == AudioMMapPolicy::AUTO ||
1331 info.mmapPolicy == AudioMMapPolicy::ALWAYS;
1332 }) != mmapPolicyInfos.end();
1333 }
1334 return mIsMmapSupported.value();
1335}
1336
Mikhail Naganov9d16a6a2023-06-26 17:21:04 -07001337ndk::ScopedAStatus Module::createInputStream(const SinkMetadata& sinkMetadata,
1338 StreamContext&& context,
1339 const std::vector<MicrophoneInfo>& microphones,
1340 std::shared_ptr<StreamIn>* result) {
1341 return createStreamInstance<StreamInStub>(result, sinkMetadata, std::move(context),
1342 microphones);
1343}
1344
1345ndk::ScopedAStatus Module::createOutputStream(const SourceMetadata& sourceMetadata,
1346 StreamContext&& context,
1347 const std::optional<AudioOffloadInfo>& offloadInfo,
1348 std::shared_ptr<StreamOut>* result) {
1349 return createStreamInstance<StreamOutStub>(result, sourceMetadata, std::move(context),
1350 offloadInfo);
1351}
1352
jiabin253bd322023-01-25 23:57:31 +00001353ndk::ScopedAStatus Module::populateConnectedDevicePort(AudioPort* audioPort __unused) {
jiabin116d8392023-03-01 22:52:57 +00001354 LOG(VERBOSE) << __func__ << ": do nothing and return ok";
jiabin253bd322023-01-25 23:57:31 +00001355 return ndk::ScopedAStatus::ok();
1356}
1357
1358ndk::ScopedAStatus Module::checkAudioPatchEndpointsMatch(
1359 const std::vector<AudioPortConfig*>& sources __unused,
1360 const std::vector<AudioPortConfig*>& sinks __unused) {
jiabin116d8392023-03-01 22:52:57 +00001361 LOG(VERBOSE) << __func__ << ": do nothing and return ok";
jiabin253bd322023-01-25 23:57:31 +00001362 return ndk::ScopedAStatus::ok();
1363}
1364
jiabin783c48b2023-02-28 18:28:06 +00001365void Module::onExternalDeviceConnectionChanged(
1366 const ::aidl::android::media::audio::common::AudioPort& audioPort __unused,
1367 bool connected __unused) {
1368 LOG(DEBUG) << __func__ << ": do nothing and return";
1369}
1370
1371ndk::ScopedAStatus Module::onMasterMuteChanged(bool mute __unused) {
1372 LOG(VERBOSE) << __func__ << ": do nothing and return ok";
1373 return ndk::ScopedAStatus::ok();
1374}
1375
1376ndk::ScopedAStatus Module::onMasterVolumeChanged(float volume __unused) {
1377 LOG(VERBOSE) << __func__ << ": do nothing and return ok";
1378 return ndk::ScopedAStatus::ok();
1379}
1380
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001381} // namespace aidl::android::hardware::audio::core