blob: 905ff2ccaa3e1038f1124713e864328fdc57f2a0 [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 Naganovdf5adfd2021-11-11 22:09:22 +000021#include <android-base/logging.h>
Shunkai Yao39bf2c32022-12-06 03:25:59 +000022#include <android/binder_ibinder_platform.h>
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000023
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000024#include <Utils.h>
25#include <aidl/android/media/audio/common/AudioInputFlags.h>
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000026#include <aidl/android/media/audio/common/AudioOutputFlags.h>
27
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"
Vlad Popa943b7e22022-12-08 14:24:12 +010030#include "core-impl/SoundDose.h"
Mikhail Naganovf429c032023-01-07 00:24:50 +000031#include "core-impl/StreamStub.h"
Mikhail Naganov3b125b72022-10-05 02:12:39 +000032#include "core-impl/Telephony.h"
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000033#include "core-impl/utils.h"
34
35using aidl::android::hardware::audio::common::SinkMetadata;
36using aidl::android::hardware::audio::common::SourceMetadata;
Vlad Popa2afbd1e2022-12-28 17:04:58 +010037using aidl::android::hardware::audio::core::sounddose::ISoundDose;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000038using aidl::android::media::audio::common::AudioChannelLayout;
Mikhail Naganovef6bc742022-10-06 00:14:19 +000039using aidl::android::media::audio::common::AudioDevice;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000040using aidl::android::media::audio::common::AudioFormatDescription;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000041using aidl::android::media::audio::common::AudioFormatType;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000042using aidl::android::media::audio::common::AudioInputFlags;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000043using aidl::android::media::audio::common::AudioIoFlags;
jiabin9a8e6862023-01-12 23:06:37 +000044using aidl::android::media::audio::common::AudioMMapPolicy;
45using aidl::android::media::audio::common::AudioMMapPolicyInfo;
46using aidl::android::media::audio::common::AudioMMapPolicyType;
Mikhail Naganov04ae8222023-01-11 15:48:10 -080047using aidl::android::media::audio::common::AudioMode;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000048using aidl::android::media::audio::common::AudioOffloadInfo;
49using aidl::android::media::audio::common::AudioOutputFlags;
50using aidl::android::media::audio::common::AudioPort;
51using aidl::android::media::audio::common::AudioPortConfig;
52using aidl::android::media::audio::common::AudioPortExt;
53using aidl::android::media::audio::common::AudioProfile;
Mikhail Naganov20047bc2023-01-05 20:16:07 +000054using aidl::android::media::audio::common::Boolean;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000055using aidl::android::media::audio::common::Int;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000056using aidl::android::media::audio::common::PcmType;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000057using android::hardware::audio::common::getFrameSizeInBytes;
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +000058using android::hardware::audio::common::isBitPositionFlagSet;
Mikhail Naganov04ae8222023-01-11 15:48:10 -080059using android::hardware::audio::common::isValidAudioMode;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000060
61namespace aidl::android::hardware::audio::core {
62
63namespace {
64
65bool generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) {
66 *config = {};
67 config->portId = port.id;
68 if (port.profiles.empty()) {
69 LOG(ERROR) << __func__ << ": port " << port.id << " has no profiles";
70 return false;
71 }
72 const auto& profile = port.profiles.begin();
73 config->format = profile->format;
74 if (profile->channelMasks.empty()) {
75 LOG(ERROR) << __func__ << ": the first profile in port " << port.id
76 << " has no channel masks";
77 return false;
78 }
79 config->channelMask = *profile->channelMasks.begin();
80 if (profile->sampleRates.empty()) {
81 LOG(ERROR) << __func__ << ": the first profile in port " << port.id
82 << " has no sample rates";
83 return false;
84 }
85 Int sampleRate;
86 sampleRate.value = *profile->sampleRates.begin();
87 config->sampleRate = sampleRate;
88 config->flags = port.flags;
89 config->ext = port.ext;
90 return true;
91}
92
93bool findAudioProfile(const AudioPort& port, const AudioFormatDescription& format,
94 AudioProfile* profile) {
95 if (auto profilesIt =
96 find_if(port.profiles.begin(), port.profiles.end(),
97 [&format](const auto& profile) { return profile.format == format; });
98 profilesIt != port.profiles.end()) {
99 *profile = *profilesIt;
100 return true;
101 }
102 return false;
103}
Mikhail Naganov00603d12022-05-02 22:52:13 +0000104
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000105} // namespace
106
107void Module::cleanUpPatch(int32_t patchId) {
108 erase_all_values(mPatches, std::set<int32_t>{patchId});
109}
110
Mikhail Naganov8651b362023-01-06 23:15:27 +0000111ndk::ScopedAStatus Module::createStreamContext(
112 int32_t in_portConfigId, int64_t in_bufferSizeFrames,
113 std::shared_ptr<IStreamCallback> asyncCallback,
114 std::shared_ptr<IStreamOutEventCallback> outEventCallback, StreamContext* out_context) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000115 if (in_bufferSizeFrames <= 0) {
116 LOG(ERROR) << __func__ << ": non-positive buffer size " << in_bufferSizeFrames;
117 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
118 }
119 if (in_bufferSizeFrames < kMinimumStreamBufferSizeFrames) {
120 LOG(ERROR) << __func__ << ": insufficient buffer size " << in_bufferSizeFrames
121 << ", must be at least " << kMinimumStreamBufferSizeFrames;
122 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
123 }
124 auto& configs = getConfig().portConfigs;
125 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000126 // Since this is a private method, it is assumed that
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000127 // validity of the portConfigId has already been checked.
128 const size_t frameSize =
129 getFrameSizeInBytes(portConfigIt->format.value(), portConfigIt->channelMask.value());
130 if (frameSize == 0) {
131 LOG(ERROR) << __func__ << ": could not calculate frame size for port config "
132 << portConfigIt->toString();
133 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
134 }
135 LOG(DEBUG) << __func__ << ": frame size " << frameSize << " bytes";
136 if (frameSize > kMaximumStreamBufferSizeBytes / in_bufferSizeFrames) {
137 LOG(ERROR) << __func__ << ": buffer size " << in_bufferSizeFrames
138 << " frames is too large, maximum size is "
139 << kMaximumStreamBufferSizeBytes / frameSize;
140 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
141 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000142 const auto& flags = portConfigIt->flags.value();
143 if ((flags.getTag() == AudioIoFlags::Tag::input &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000144 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::input>(),
145 AudioInputFlags::MMAP_NOIRQ)) ||
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000146 (flags.getTag() == AudioIoFlags::Tag::output &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000147 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::output>(),
148 AudioOutputFlags::MMAP_NOIRQ))) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000149 StreamContext::DebugParameters params{mDebug.streamTransientStateDelayMs,
Mikhail Naganov194daaa2023-01-05 22:34:20 +0000150 mVendorDebug.forceTransientBurst,
151 mVendorDebug.forceSynchronousDrain};
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000152 StreamContext temp(
153 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
154 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000155 portConfigIt->format.value(), portConfigIt->channelMask.value(),
156 std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames),
Mikhail Naganov8651b362023-01-06 23:15:27 +0000157 asyncCallback, outEventCallback, params);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000158 if (temp.isValid()) {
159 *out_context = std::move(temp);
160 } else {
161 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
162 }
163 } else {
164 // TODO: Implement simulation of MMAP buffer allocation
165 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000166 return ndk::ScopedAStatus::ok();
167}
168
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000169std::vector<AudioDevice> Module::findConnectedDevices(int32_t portConfigId) {
170 std::vector<AudioDevice> result;
171 auto& ports = getConfig().ports;
172 auto portIds = portIdsFromPortConfigIds(findConnectedPortConfigIds(portConfigId));
173 for (auto it = portIds.begin(); it != portIds.end(); ++it) {
174 auto portIt = findById<AudioPort>(ports, *it);
175 if (portIt != ports.end() && portIt->ext.getTag() == AudioPortExt::Tag::device) {
176 result.push_back(portIt->ext.template get<AudioPortExt::Tag::device>().device);
177 }
178 }
179 return result;
180}
181
182std::set<int32_t> Module::findConnectedPortConfigIds(int32_t portConfigId) {
183 std::set<int32_t> result;
184 auto patchIdsRange = mPatches.equal_range(portConfigId);
185 auto& patches = getConfig().patches;
186 for (auto it = patchIdsRange.first; it != patchIdsRange.second; ++it) {
187 auto patchIt = findById<AudioPatch>(patches, it->second);
188 if (patchIt == patches.end()) {
189 LOG(FATAL) << __func__ << ": patch with id " << it->second << " taken from mPatches "
190 << "not found in the configuration";
191 }
192 if (std::find(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end(),
193 portConfigId) != patchIt->sourcePortConfigIds.end()) {
194 result.insert(patchIt->sinkPortConfigIds.begin(), patchIt->sinkPortConfigIds.end());
195 } else {
196 result.insert(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end());
197 }
198 }
199 return result;
200}
201
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000202ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) {
203 auto& configs = getConfig().portConfigs;
204 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
205 if (portConfigIt == configs.end()) {
206 LOG(ERROR) << __func__ << ": existing port config id " << in_portConfigId << " not found";
207 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
208 }
209 const int32_t portId = portConfigIt->portId;
210 // In our implementation, configs of mix ports always have unique IDs.
211 CHECK(portId != in_portConfigId);
212 auto& ports = getConfig().ports;
213 auto portIt = findById<AudioPort>(ports, portId);
214 if (portIt == ports.end()) {
215 LOG(ERROR) << __func__ << ": port id " << portId << " used by port config id "
216 << in_portConfigId << " not found";
217 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
218 }
219 if (mStreams.count(in_portConfigId) != 0) {
220 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
221 << " already has a stream opened on it";
222 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
223 }
224 if (portIt->ext.getTag() != AudioPortExt::Tag::mix) {
225 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
226 << " does not correspond to a mix port";
227 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
228 }
229 const int32_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
230 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
231 LOG(ERROR) << __func__ << ": port id " << portId
232 << " has already reached maximum allowed opened stream count: "
233 << maxOpenStreamCount;
234 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
235 }
236 *port = &(*portIt);
237 return ndk::ScopedAStatus::ok();
238}
239
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000240template <typename C>
241std::set<int32_t> Module::portIdsFromPortConfigIds(C portConfigIds) {
242 std::set<int32_t> result;
243 auto& portConfigs = getConfig().portConfigs;
244 for (auto it = portConfigIds.begin(); it != portConfigIds.end(); ++it) {
245 auto portConfigIt = findById<AudioPortConfig>(portConfigs, *it);
246 if (portConfigIt != portConfigs.end()) {
247 result.insert(portConfigIt->portId);
248 }
249 }
250 return result;
251}
252
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000253internal::Configuration& Module::getConfig() {
254 if (!mConfig) {
Mikhail Naganovc8e43122022-12-09 00:33:47 +0000255 switch (mType) {
256 case Type::DEFAULT:
257 mConfig = std::move(internal::getPrimaryConfiguration());
258 break;
259 case Type::R_SUBMIX:
260 mConfig = std::move(internal::getRSubmixConfiguration());
261 break;
jiabinb309d8d2023-01-20 19:07:15 +0000262 case Type::USB:
263 mConfig = std::move(internal::getUsbConfiguration());
Mikhail Naganovc8e43122022-12-09 00:33:47 +0000264 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000265 }
266 return *mConfig;
267}
268
269void Module::registerPatch(const AudioPatch& patch) {
270 auto& configs = getConfig().portConfigs;
271 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
272 for (auto portConfigId : portConfigIds) {
273 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
274 if (configIt != configs.end()) {
275 mPatches.insert(std::pair{portConfigId, patch.id});
276 if (configIt->portId != portConfigId) {
277 mPatches.insert(std::pair{configIt->portId, patch.id});
278 }
279 }
280 };
281 };
282 do_insert(patch.sourcePortConfigIds);
283 do_insert(patch.sinkPortConfigIds);
284}
285
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000286void Module::updateStreamsConnectedState(const AudioPatch& oldPatch, const AudioPatch& newPatch) {
287 // Streams from the old patch need to be disconnected, streams from the new
288 // patch need to be connected. If the stream belongs to both patches, no need
289 // to update it.
290 std::set<int32_t> idsToDisconnect, idsToConnect;
291 idsToDisconnect.insert(oldPatch.sourcePortConfigIds.begin(),
292 oldPatch.sourcePortConfigIds.end());
293 idsToDisconnect.insert(oldPatch.sinkPortConfigIds.begin(), oldPatch.sinkPortConfigIds.end());
294 idsToConnect.insert(newPatch.sourcePortConfigIds.begin(), newPatch.sourcePortConfigIds.end());
295 idsToConnect.insert(newPatch.sinkPortConfigIds.begin(), newPatch.sinkPortConfigIds.end());
296 std::for_each(idsToDisconnect.begin(), idsToDisconnect.end(), [&](const auto& portConfigId) {
297 if (idsToConnect.count(portConfigId) == 0) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000298 LOG(DEBUG) << "The stream on port config id " << portConfigId << " is not connected";
299 mStreams.setStreamIsConnected(portConfigId, {});
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000300 }
301 });
302 std::for_each(idsToConnect.begin(), idsToConnect.end(), [&](const auto& portConfigId) {
303 if (idsToDisconnect.count(portConfigId) == 0) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000304 const auto connectedDevices = findConnectedDevices(portConfigId);
305 LOG(DEBUG) << "The stream on port config id " << portConfigId
306 << " is connected to: " << ::android::internal::ToString(connectedDevices);
307 mStreams.setStreamIsConnected(portConfigId, connectedDevices);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000308 }
309 });
310}
311
Mikhail Naganov00603d12022-05-02 22:52:13 +0000312ndk::ScopedAStatus Module::setModuleDebug(
313 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
314 LOG(DEBUG) << __func__ << ": old flags:" << mDebug.toString()
315 << ", new flags: " << in_debug.toString();
316 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
317 !mConnectedDevicePorts.empty()) {
318 LOG(ERROR) << __func__ << ": attempting to change device connections simulation "
319 << "while having external devices connected";
320 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
321 }
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000322 if (in_debug.streamTransientStateDelayMs < 0) {
323 LOG(ERROR) << __func__ << ": streamTransientStateDelayMs is negative: "
324 << in_debug.streamTransientStateDelayMs;
325 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
326 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000327 mDebug = in_debug;
328 return ndk::ScopedAStatus::ok();
329}
330
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000331ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
332 if (mTelephony == nullptr) {
333 mTelephony = ndk::SharedRefBase::make<Telephony>();
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000334 mTelephonyBinder = mTelephony->asBinder();
335 AIBinder_setMinSchedulerPolicy(mTelephonyBinder.get(), SCHED_NORMAL,
Shunkai Yao39bf2c32022-12-06 03:25:59 +0000336 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000337 }
338 *_aidl_return = mTelephony;
339 LOG(DEBUG) << __func__ << ": returning instance of ITelephony: " << _aidl_return->get();
340 return ndk::ScopedAStatus::ok();
341}
342
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000343ndk::ScopedAStatus Module::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
344 if (mBluetooth == nullptr) {
345 mBluetooth = ndk::SharedRefBase::make<Bluetooth>();
346 mBluetoothBinder = mBluetooth->asBinder();
347 AIBinder_setMinSchedulerPolicy(mBluetoothBinder.get(), SCHED_NORMAL,
348 ANDROID_PRIORITY_AUDIO);
349 }
350 *_aidl_return = mBluetooth;
351 LOG(DEBUG) << __func__ << ": returning instance of IBluetooth: " << _aidl_return->get();
352 return ndk::ScopedAStatus::ok();
353}
354
Mikhail Naganov00603d12022-05-02 22:52:13 +0000355ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
356 AudioPort* _aidl_return) {
357 const int32_t templateId = in_templateIdAndAdditionalData.id;
358 auto& ports = getConfig().ports;
359 AudioPort connectedPort;
360 { // Scope the template port so that we don't accidentally modify it.
361 auto templateIt = findById<AudioPort>(ports, templateId);
362 if (templateIt == ports.end()) {
363 LOG(ERROR) << __func__ << ": port id " << templateId << " not found";
364 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
365 }
366 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
367 LOG(ERROR) << __func__ << ": port id " << templateId << " is not a device port";
368 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
369 }
370 if (!templateIt->profiles.empty()) {
371 LOG(ERROR) << __func__ << ": port id " << templateId
372 << " does not have dynamic profiles";
373 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
374 }
375 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
376 if (templateDevicePort.device.type.connection.empty()) {
377 LOG(ERROR) << __func__ << ": port id " << templateId << " is permanently attached";
378 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
379 }
380 // Postpone id allocation until we ensure that there are no client errors.
381 connectedPort = *templateIt;
382 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
383 const auto& inputDevicePort =
384 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
385 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
386 connectedDevicePort.device.address = inputDevicePort.device.address;
387 LOG(DEBUG) << __func__ << ": device port " << connectedPort.id << " device set to "
388 << connectedDevicePort.device.toString();
389 // Check if there is already a connected port with for the same external device.
390 for (auto connectedPortId : mConnectedDevicePorts) {
391 auto connectedPortIt = findById<AudioPort>(ports, connectedPortId);
392 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
393 connectedDevicePort.device) {
394 LOG(ERROR) << __func__ << ": device " << connectedDevicePort.device.toString()
395 << " is already connected at the device port id " << connectedPortId;
396 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
397 }
398 }
399 }
400
401 if (!mDebug.simulateDeviceConnections) {
402 // In a real HAL here we would attempt querying the profiles from the device.
403 LOG(ERROR) << __func__ << ": failed to query supported device profiles";
404 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
405 }
406
407 connectedPort.id = ++getConfig().nextPortId;
408 mConnectedDevicePorts.insert(connectedPort.id);
409 LOG(DEBUG) << __func__ << ": template port " << templateId << " external device connected, "
410 << "connected port ID " << connectedPort.id;
411 auto& connectedProfiles = getConfig().connectedProfiles;
412 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
413 connectedProfilesIt != connectedProfiles.end()) {
414 connectedPort.profiles = connectedProfilesIt->second;
415 }
416 ports.push_back(connectedPort);
417 *_aidl_return = std::move(connectedPort);
418
419 std::vector<AudioRoute> newRoutes;
420 auto& routes = getConfig().routes;
421 for (auto& r : routes) {
422 if (r.sinkPortId == templateId) {
423 AudioRoute newRoute;
424 newRoute.sourcePortIds = r.sourcePortIds;
425 newRoute.sinkPortId = connectedPort.id;
426 newRoute.isExclusive = r.isExclusive;
427 newRoutes.push_back(std::move(newRoute));
428 } else {
429 auto& srcs = r.sourcePortIds;
430 if (std::find(srcs.begin(), srcs.end(), templateId) != srcs.end()) {
431 srcs.push_back(connectedPort.id);
432 }
433 }
434 }
435 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
436
437 return ndk::ScopedAStatus::ok();
438}
439
440ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
441 auto& ports = getConfig().ports;
442 auto portIt = findById<AudioPort>(ports, in_portId);
443 if (portIt == ports.end()) {
444 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
445 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
446 }
447 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
448 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a device port";
449 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
450 }
451 if (mConnectedDevicePorts.count(in_portId) == 0) {
452 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a connected device port";
453 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
454 }
455 auto& configs = getConfig().portConfigs;
456 auto& initials = getConfig().initialConfigs;
457 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
458 if (config.portId == in_portId) {
459 // Check if the configuration was provided by the client.
460 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
461 return initialIt == initials.end() || config != *initialIt;
462 }
463 return false;
464 });
465 if (configIt != configs.end()) {
466 LOG(ERROR) << __func__ << ": port id " << in_portId << " has a non-default config with id "
467 << configIt->id;
468 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
469 }
470 ports.erase(portIt);
471 mConnectedDevicePorts.erase(in_portId);
472 LOG(DEBUG) << __func__ << ": connected device port " << in_portId << " released";
473
474 auto& routes = getConfig().routes;
475 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
476 if (routesIt->sinkPortId == in_portId) {
477 routesIt = routes.erase(routesIt);
478 } else {
479 // Note: the list of sourcePortIds can't become empty because there must
480 // be the id of the template port in the route.
481 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
482 ++routesIt;
483 }
484 }
485
486 return ndk::ScopedAStatus::ok();
487}
488
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000489ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
490 *_aidl_return = getConfig().patches;
491 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " patches";
492 return ndk::ScopedAStatus::ok();
493}
494
495ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
496 auto& ports = getConfig().ports;
497 auto portIt = findById<AudioPort>(ports, in_portId);
498 if (portIt != ports.end()) {
499 *_aidl_return = *portIt;
500 LOG(DEBUG) << __func__ << ": returning port by id " << in_portId;
501 return ndk::ScopedAStatus::ok();
502 }
503 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
504 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
505}
506
507ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
508 *_aidl_return = getConfig().portConfigs;
509 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " port configs";
510 return ndk::ScopedAStatus::ok();
511}
512
513ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
514 *_aidl_return = getConfig().ports;
515 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " ports";
516 return ndk::ScopedAStatus::ok();
517}
518
519ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
520 *_aidl_return = getConfig().routes;
521 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " routes";
522 return ndk::ScopedAStatus::ok();
523}
524
Mikhail Naganov00603d12022-05-02 22:52:13 +0000525ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
526 std::vector<AudioRoute>* _aidl_return) {
527 auto& ports = getConfig().ports;
528 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
529 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
530 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
531 }
532 auto& routes = getConfig().routes;
533 std::copy_if(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
534 [&](const auto& r) {
535 const auto& srcs = r.sourcePortIds;
536 return r.sinkPortId == in_portId ||
537 std::find(srcs.begin(), srcs.end(), in_portId) != srcs.end();
538 });
539 return ndk::ScopedAStatus::ok();
540}
541
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000542ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
543 OpenInputStreamReturn* _aidl_return) {
544 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", buffer size "
545 << in_args.bufferSizeFrames << " frames";
546 AudioPort* port = nullptr;
547 if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
548 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000549 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000550 if (port->flags.getTag() != AudioIoFlags::Tag::input) {
551 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000552 << " does not correspond to an input mix port";
553 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
554 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000555 StreamContext context;
Mikhail Naganov30301a42022-09-13 01:20:45 +0000556 if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames, nullptr,
Mikhail Naganov8651b362023-01-06 23:15:27 +0000557 nullptr, &context);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000558 !status.isOk()) {
559 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000560 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000561 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000562 std::shared_ptr<StreamIn> stream;
Mikhail Naganovf429c032023-01-07 00:24:50 +0000563 // TODO: Add a mapping from module instance names to a corresponding 'createInstance'.
564 if (auto status = StreamInStub::createInstance(in_args.sinkMetadata, std::move(context),
565 mConfig->microphones, &stream);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000566 !status.isOk()) {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000567 return status;
568 }
569 StreamWrapper streamWrapper(stream);
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000570 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
571 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000572 auto patchIt = mPatches.find(in_args.portConfigId);
573 if (patchIt != mPatches.end()) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000574 streamWrapper.setStreamIsConnected(findConnectedDevices(in_args.portConfigId));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000575 }
576 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000577 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000578 return ndk::ScopedAStatus::ok();
579}
580
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000581ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
582 OpenOutputStreamReturn* _aidl_return) {
583 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", has offload info? "
584 << (in_args.offloadInfo.has_value()) << ", buffer size " << in_args.bufferSizeFrames
585 << " frames";
586 AudioPort* port = nullptr;
587 if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
588 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000589 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000590 if (port->flags.getTag() != AudioIoFlags::Tag::output) {
591 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000592 << " does not correspond to an output mix port";
593 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
594 }
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000595 const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
596 AudioOutputFlags::COMPRESS_OFFLOAD);
597 if (isOffload && !in_args.offloadInfo.has_value()) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000598 LOG(ERROR) << __func__ << ": port id " << port->id
Mikhail Naganov111e0ce2022-06-17 21:41:19 +0000599 << " has COMPRESS_OFFLOAD flag set, requires offload info";
600 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
601 }
Mikhail Naganov30301a42022-09-13 01:20:45 +0000602 const bool isNonBlocking = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
603 AudioOutputFlags::NON_BLOCKING);
604 if (isNonBlocking && in_args.callback == nullptr) {
605 LOG(ERROR) << __func__ << ": port id " << port->id
606 << " has NON_BLOCKING flag set, requires async callback";
607 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
608 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000609 StreamContext context;
Mikhail Naganov30301a42022-09-13 01:20:45 +0000610 if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
Mikhail Naganov8651b362023-01-06 23:15:27 +0000611 isNonBlocking ? in_args.callback : nullptr,
612 in_args.eventCallback, &context);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000613 !status.isOk()) {
614 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000615 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000616 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000617 std::shared_ptr<StreamOut> stream;
Mikhail Naganovf429c032023-01-07 00:24:50 +0000618 // TODO: Add a mapping from module instance names to a corresponding 'createInstance'.
619 if (auto status = StreamOutStub::createInstance(in_args.sourceMetadata, std::move(context),
620 in_args.offloadInfo, &stream);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000621 !status.isOk()) {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000622 return status;
623 }
624 StreamWrapper streamWrapper(stream);
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000625 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
626 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000627 auto patchIt = mPatches.find(in_args.portConfigId);
628 if (patchIt != mPatches.end()) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000629 streamWrapper.setStreamIsConnected(findConnectedDevices(in_args.portConfigId));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000630 }
631 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000632 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000633 return ndk::ScopedAStatus::ok();
634}
635
Mikhail Naganov74927202022-12-19 16:37:14 +0000636ndk::ScopedAStatus Module::getSupportedPlaybackRateFactors(
637 SupportedPlaybackRateFactors* _aidl_return) {
638 LOG(DEBUG) << __func__;
639 (void)_aidl_return;
640 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
641}
642
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000643ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
Mikhail Naganov16db9b72022-06-17 21:36:18 +0000644 LOG(DEBUG) << __func__ << ": requested patch " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000645 if (in_requested.sourcePortConfigIds.empty()) {
646 LOG(ERROR) << __func__ << ": requested patch has empty sources list";
647 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
648 }
649 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
650 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sources list";
651 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
652 }
653 if (in_requested.sinkPortConfigIds.empty()) {
654 LOG(ERROR) << __func__ << ": requested patch has empty sinks list";
655 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
656 }
657 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
658 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sinks list";
659 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
660 }
661
662 auto& configs = getConfig().portConfigs;
663 std::vector<int32_t> missingIds;
664 auto sources =
665 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
666 if (!missingIds.empty()) {
667 LOG(ERROR) << __func__ << ": following source port config ids not found: "
668 << ::android::internal::ToString(missingIds);
669 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
670 }
671 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
672 if (!missingIds.empty()) {
673 LOG(ERROR) << __func__ << ": following sink port config ids not found: "
674 << ::android::internal::ToString(missingIds);
675 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
676 }
677 // bool indicates whether a non-exclusive route is available.
678 // If only an exclusive route is available, that means the patch can not be
679 // established if there is any other patch which currently uses the sink port.
680 std::map<int32_t, bool> allowedSinkPorts;
681 auto& routes = getConfig().routes;
682 for (auto src : sources) {
683 for (const auto& r : routes) {
684 const auto& srcs = r.sourcePortIds;
685 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
686 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
687 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
688 }
689 }
690 }
691 }
692 for (auto sink : sinks) {
693 if (allowedSinkPorts.count(sink->portId) == 0) {
694 LOG(ERROR) << __func__ << ": there is no route to the sink port id " << sink->portId;
695 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
696 }
697 }
698
699 auto& patches = getConfig().patches;
700 auto existing = patches.end();
701 std::optional<decltype(mPatches)> patchesBackup;
702 if (in_requested.id != 0) {
703 existing = findById<AudioPatch>(patches, in_requested.id);
704 if (existing != patches.end()) {
705 patchesBackup = mPatches;
706 cleanUpPatch(existing->id);
707 } else {
708 LOG(ERROR) << __func__ << ": not found existing patch id " << in_requested.id;
709 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
710 }
711 }
712 // Validate the requested patch.
713 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
714 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
715 LOG(ERROR) << __func__ << ": sink port id " << sinkPortId
716 << "is exclusive and is already used by some other patch";
717 if (patchesBackup.has_value()) {
718 mPatches = std::move(*patchesBackup);
719 }
720 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
721 }
722 }
723 *_aidl_return = in_requested;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000724 _aidl_return->minimumStreamBufferSizeFrames = kMinimumStreamBufferSizeFrames;
725 _aidl_return->latenciesMs.clear();
726 _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
727 _aidl_return->sinkPortConfigIds.size(), kLatencyMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000728 AudioPatch oldPatch{};
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000729 if (existing == patches.end()) {
730 _aidl_return->id = getConfig().nextPatchId++;
731 patches.push_back(*_aidl_return);
732 existing = patches.begin() + (patches.size() - 1);
733 } else {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000734 oldPatch = *existing;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000735 *existing = *_aidl_return;
736 }
737 registerPatch(*existing);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000738 updateStreamsConnectedState(oldPatch, *_aidl_return);
739
740 LOG(DEBUG) << __func__ << ": " << (oldPatch.id == 0 ? "created" : "updated") << " patch "
741 << _aidl_return->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000742 return ndk::ScopedAStatus::ok();
743}
744
745ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
746 AudioPortConfig* out_suggested, bool* _aidl_return) {
747 LOG(DEBUG) << __func__ << ": requested " << in_requested.toString();
748 auto& configs = getConfig().portConfigs;
749 auto existing = configs.end();
750 if (in_requested.id != 0) {
751 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
752 existing == configs.end()) {
753 LOG(ERROR) << __func__ << ": existing port config id " << in_requested.id
754 << " not found";
755 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
756 }
757 }
758
759 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
760 if (portId == 0) {
761 LOG(ERROR) << __func__ << ": input port config does not specify portId";
762 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
763 }
764 auto& ports = getConfig().ports;
765 auto portIt = findById<AudioPort>(ports, portId);
766 if (portIt == ports.end()) {
767 LOG(ERROR) << __func__ << ": input port config points to non-existent portId " << portId;
768 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
769 }
770 if (existing != configs.end()) {
771 *out_suggested = *existing;
772 } else {
773 AudioPortConfig newConfig;
774 if (generateDefaultPortConfig(*portIt, &newConfig)) {
775 *out_suggested = newConfig;
776 } else {
777 LOG(ERROR) << __func__ << ": unable generate a default config for port " << portId;
778 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
779 }
780 }
781 // From this moment, 'out_suggested' is either an existing port config,
782 // or a new generated config. Now attempt to update it according to the specified
783 // fields of 'in_requested'.
784
785 bool requestedIsValid = true, requestedIsFullySpecified = true;
786
787 AudioIoFlags portFlags = portIt->flags;
788 if (in_requested.flags.has_value()) {
789 if (in_requested.flags.value() != portFlags) {
790 LOG(WARNING) << __func__ << ": requested flags "
791 << in_requested.flags.value().toString() << " do not match port's "
792 << portId << " flags " << portFlags.toString();
793 requestedIsValid = false;
794 }
795 } else {
796 requestedIsFullySpecified = false;
797 }
798
799 AudioProfile portProfile;
800 if (in_requested.format.has_value()) {
801 const auto& format = in_requested.format.value();
802 if (findAudioProfile(*portIt, format, &portProfile)) {
803 out_suggested->format = format;
804 } else {
805 LOG(WARNING) << __func__ << ": requested format " << format.toString()
806 << " is not found in port's " << portId << " profiles";
807 requestedIsValid = false;
808 }
809 } else {
810 requestedIsFullySpecified = false;
811 }
812 if (!findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
813 LOG(ERROR) << __func__ << ": port " << portId << " does not support format "
814 << out_suggested->format.value().toString() << " anymore";
815 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
816 }
817
818 if (in_requested.channelMask.has_value()) {
819 const auto& channelMask = in_requested.channelMask.value();
820 if (find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
821 portProfile.channelMasks.end()) {
822 out_suggested->channelMask = channelMask;
823 } else {
824 LOG(WARNING) << __func__ << ": requested channel mask " << channelMask.toString()
825 << " is not supported for the format " << portProfile.format.toString()
826 << " by the port " << portId;
827 requestedIsValid = false;
828 }
829 } else {
830 requestedIsFullySpecified = false;
831 }
832
833 if (in_requested.sampleRate.has_value()) {
834 const auto& sampleRate = in_requested.sampleRate.value();
835 if (find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
836 sampleRate.value) != portProfile.sampleRates.end()) {
837 out_suggested->sampleRate = sampleRate;
838 } else {
839 LOG(WARNING) << __func__ << ": requested sample rate " << sampleRate.value
840 << " is not supported for the format " << portProfile.format.toString()
841 << " by the port " << portId;
842 requestedIsValid = false;
843 }
844 } else {
845 requestedIsFullySpecified = false;
846 }
847
848 if (in_requested.gain.has_value()) {
849 // Let's pretend that gain can always be applied.
850 out_suggested->gain = in_requested.gain.value();
851 }
852
853 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
854 out_suggested->id = getConfig().nextPortId++;
855 configs.push_back(*out_suggested);
856 *_aidl_return = true;
857 LOG(DEBUG) << __func__ << ": created new port config " << out_suggested->toString();
858 } else if (existing != configs.end() && requestedIsValid) {
859 *existing = *out_suggested;
860 *_aidl_return = true;
861 LOG(DEBUG) << __func__ << ": updated port config " << out_suggested->toString();
862 } else {
863 LOG(DEBUG) << __func__ << ": not applied; existing config ? " << (existing != configs.end())
864 << "; requested is valid? " << requestedIsValid << ", fully specified? "
865 << requestedIsFullySpecified;
866 *_aidl_return = false;
867 }
868 return ndk::ScopedAStatus::ok();
869}
870
871ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
872 auto& patches = getConfig().patches;
873 auto patchIt = findById<AudioPatch>(patches, in_patchId);
874 if (patchIt != patches.end()) {
875 cleanUpPatch(patchIt->id);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000876 updateStreamsConnectedState(*patchIt, AudioPatch{});
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000877 patches.erase(patchIt);
878 LOG(DEBUG) << __func__ << ": erased patch " << in_patchId;
879 return ndk::ScopedAStatus::ok();
880 }
881 LOG(ERROR) << __func__ << ": patch id " << in_patchId << " not found";
882 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
883}
884
885ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
886 auto& configs = getConfig().portConfigs;
887 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
888 if (configIt != configs.end()) {
889 if (mStreams.count(in_portConfigId) != 0) {
890 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
891 << " has a stream opened on it";
892 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
893 }
894 auto patchIt = mPatches.find(in_portConfigId);
895 if (patchIt != mPatches.end()) {
896 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
897 << " is used by the patch with id " << patchIt->second;
898 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
899 }
900 auto& initials = getConfig().initialConfigs;
901 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
902 if (initialIt == initials.end()) {
903 configs.erase(configIt);
904 LOG(DEBUG) << __func__ << ": erased port config " << in_portConfigId;
905 } else if (*configIt != *initialIt) {
906 *configIt = *initialIt;
907 LOG(DEBUG) << __func__ << ": reset port config " << in_portConfigId;
908 }
909 return ndk::ScopedAStatus::ok();
910 }
911 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId << " not found";
912 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
913}
914
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000915ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) {
916 *_aidl_return = mMasterMute;
917 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
918 return ndk::ScopedAStatus::ok();
919}
920
921ndk::ScopedAStatus Module::setMasterMute(bool in_mute) {
922 LOG(DEBUG) << __func__ << ": " << in_mute;
923 mMasterMute = in_mute;
924 return ndk::ScopedAStatus::ok();
925}
926
927ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) {
928 *_aidl_return = mMasterVolume;
929 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
930 return ndk::ScopedAStatus::ok();
931}
932
933ndk::ScopedAStatus Module::setMasterVolume(float in_volume) {
934 LOG(DEBUG) << __func__ << ": " << in_volume;
935 if (in_volume >= 0.0f && in_volume <= 1.0f) {
936 mMasterVolume = in_volume;
937 return ndk::ScopedAStatus::ok();
938 }
939 LOG(ERROR) << __func__ << ": invalid master volume value: " << in_volume;
940 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
941}
942
943ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) {
944 *_aidl_return = mMicMute;
945 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
946 return ndk::ScopedAStatus::ok();
947}
948
949ndk::ScopedAStatus Module::setMicMute(bool in_mute) {
950 LOG(DEBUG) << __func__ << ": " << in_mute;
951 mMicMute = in_mute;
952 return ndk::ScopedAStatus::ok();
953}
954
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000955ndk::ScopedAStatus Module::getMicrophones(std::vector<MicrophoneInfo>* _aidl_return) {
Pawan Wagh6f57cd92023-02-01 21:14:34 +0000956 *_aidl_return = getConfig().microphones;
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000957 LOG(DEBUG) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return);
958 return ndk::ScopedAStatus::ok();
959}
960
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000961ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) {
Mikhail Naganov04ae8222023-01-11 15:48:10 -0800962 if (!isValidAudioMode(in_mode)) {
963 LOG(ERROR) << __func__ << ": invalid mode " << toString(in_mode);
964 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
965 }
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000966 // No checks for supported audio modes here, it's an informative notification.
967 LOG(DEBUG) << __func__ << ": " << toString(in_mode);
968 return ndk::ScopedAStatus::ok();
969}
970
971ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) {
972 LOG(DEBUG) << __func__ << ": " << toString(in_rotation);
973 return ndk::ScopedAStatus::ok();
974}
975
976ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) {
977 LOG(DEBUG) << __func__ << ": " << in_isTurnedOn;
978 return ndk::ScopedAStatus::ok();
979}
980
Vlad Popa83a6d822022-11-07 13:53:57 +0100981ndk::ScopedAStatus Module::getSoundDose(std::shared_ptr<ISoundDose>* _aidl_return) {
Vlad Popa943b7e22022-12-08 14:24:12 +0100982 if (mSoundDose == nullptr) {
Vlad Popa2afbd1e2022-12-28 17:04:58 +0100983 mSoundDose = ndk::SharedRefBase::make<sounddose::SoundDose>();
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000984 mSoundDoseBinder = mSoundDose->asBinder();
985 AIBinder_setMinSchedulerPolicy(mSoundDoseBinder.get(), SCHED_NORMAL,
986 ANDROID_PRIORITY_AUDIO);
Vlad Popa943b7e22022-12-08 14:24:12 +0100987 }
988 *_aidl_return = mSoundDose;
989 LOG(DEBUG) << __func__ << ": returning instance of ISoundDose: " << _aidl_return->get();
Vlad Popa83a6d822022-11-07 13:53:57 +0100990 return ndk::ScopedAStatus::ok();
991}
992
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000993ndk::ScopedAStatus Module::generateHwAvSyncId(int32_t* _aidl_return) {
994 LOG(DEBUG) << __func__;
995 (void)_aidl_return;
996 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
997}
998
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000999const std::string Module::VendorDebug::kForceTransientBurstName = "aosp.forceTransientBurst";
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001000const std::string Module::VendorDebug::kForceSynchronousDrainName = "aosp.forceSynchronousDrain";
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001001
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001002ndk::ScopedAStatus Module::getVendorParameters(const std::vector<std::string>& in_ids,
1003 std::vector<VendorParameter>* _aidl_return) {
1004 LOG(DEBUG) << __func__ << ": id count: " << in_ids.size();
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001005 bool allParametersKnown = true;
1006 for (const auto& id : in_ids) {
1007 if (id == VendorDebug::kForceTransientBurstName) {
1008 VendorParameter forceTransientBurst{.id = id};
1009 forceTransientBurst.ext.setParcelable(Boolean{mVendorDebug.forceTransientBurst});
1010 _aidl_return->push_back(std::move(forceTransientBurst));
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001011 } else if (id == VendorDebug::kForceSynchronousDrainName) {
1012 VendorParameter forceSynchronousDrain{.id = id};
1013 forceSynchronousDrain.ext.setParcelable(Boolean{mVendorDebug.forceSynchronousDrain});
1014 _aidl_return->push_back(std::move(forceSynchronousDrain));
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001015 } else {
1016 allParametersKnown = false;
1017 LOG(ERROR) << __func__ << ": unrecognized parameter \"" << id << "\"";
1018 }
1019 }
1020 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1021 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001022}
1023
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001024namespace {
1025
1026template <typename W>
1027bool extractParameter(const VendorParameter& p, decltype(W::value)* v) {
1028 std::optional<W> value;
1029 binder_status_t result = p.ext.getParcelable(&value);
1030 if (result == STATUS_OK && value.has_value()) {
1031 *v = value.value().value;
1032 return true;
1033 }
1034 LOG(ERROR) << __func__ << ": failed to read the value of the parameter \"" << p.id
1035 << "\": " << result;
1036 return false;
1037}
1038
1039} // namespace
1040
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001041ndk::ScopedAStatus Module::setVendorParameters(const std::vector<VendorParameter>& in_parameters,
1042 bool in_async) {
1043 LOG(DEBUG) << __func__ << ": parameter count " << in_parameters.size()
1044 << ", async: " << in_async;
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001045 bool allParametersKnown = true;
1046 for (const auto& p : in_parameters) {
1047 if (p.id == VendorDebug::kForceTransientBurstName) {
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001048 if (!extractParameter<Boolean>(p, &mVendorDebug.forceTransientBurst)) {
1049 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1050 }
1051 } else if (p.id == VendorDebug::kForceSynchronousDrainName) {
1052 if (!extractParameter<Boolean>(p, &mVendorDebug.forceSynchronousDrain)) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001053 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1054 }
1055 } else {
1056 allParametersKnown = false;
1057 LOG(ERROR) << __func__ << ": unrecognized parameter \"" << p.id << "\"";
1058 }
1059 }
1060 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1061 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001062}
1063
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001064ndk::ScopedAStatus Module::addDeviceEffect(
1065 int32_t in_portConfigId,
1066 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1067 if (in_effect == nullptr) {
1068 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect";
1069 } else {
1070 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder "
1071 << in_effect->asBinder().get();
1072 }
1073 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1074}
1075
1076ndk::ScopedAStatus Module::removeDeviceEffect(
1077 int32_t in_portConfigId,
1078 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1079 if (in_effect == nullptr) {
1080 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect";
1081 } else {
1082 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder "
1083 << in_effect->asBinder().get();
1084 }
1085 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1086}
1087
jiabin9a8e6862023-01-12 23:06:37 +00001088ndk::ScopedAStatus Module::getMmapPolicyInfos(AudioMMapPolicyType mmapPolicyType,
1089 std::vector<AudioMMapPolicyInfo>* _aidl_return) {
1090 LOG(DEBUG) << __func__ << ": mmap policy type " << toString(mmapPolicyType);
1091 std::set<int32_t> mmapSinks;
1092 std::set<int32_t> mmapSources;
1093 auto& ports = getConfig().ports;
1094 for (const auto& port : ports) {
1095 if (port.flags.getTag() == AudioIoFlags::Tag::input &&
1096 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::input>(),
1097 AudioInputFlags::MMAP_NOIRQ)) {
1098 mmapSinks.insert(port.id);
1099 } else if (port.flags.getTag() == AudioIoFlags::Tag::output &&
1100 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
1101 AudioOutputFlags::MMAP_NOIRQ)) {
1102 mmapSources.insert(port.id);
1103 }
1104 }
1105 for (const auto& route : getConfig().routes) {
1106 if (mmapSinks.count(route.sinkPortId) != 0) {
1107 // The sink is a mix port, add the sources if they are device ports.
1108 for (int sourcePortId : route.sourcePortIds) {
1109 auto sourcePortIt = findById<AudioPort>(ports, sourcePortId);
1110 if (sourcePortIt == ports.end()) {
1111 // This must not happen
1112 LOG(ERROR) << __func__ << ": port id " << sourcePortId << " cannot be found";
1113 continue;
1114 }
1115 if (sourcePortIt->ext.getTag() != AudioPortExt::Tag::device) {
1116 // The source is not a device port, skip
1117 continue;
1118 }
1119 AudioMMapPolicyInfo policyInfo;
1120 policyInfo.device = sourcePortIt->ext.get<AudioPortExt::Tag::device>().device;
1121 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1122 // default implementation.
1123 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1124 _aidl_return->push_back(policyInfo);
1125 }
1126 } else {
1127 auto sinkPortIt = findById<AudioPort>(ports, route.sinkPortId);
1128 if (sinkPortIt == ports.end()) {
1129 // This must not happen
1130 LOG(ERROR) << __func__ << ": port id " << route.sinkPortId << " cannot be found";
1131 continue;
1132 }
1133 if (sinkPortIt->ext.getTag() != AudioPortExt::Tag::device) {
1134 // The sink is not a device port, skip
1135 continue;
1136 }
1137 if (count_any(mmapSources, route.sourcePortIds)) {
1138 AudioMMapPolicyInfo policyInfo;
1139 policyInfo.device = sinkPortIt->ext.get<AudioPortExt::Tag::device>().device;
1140 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1141 // default implementation.
1142 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1143 _aidl_return->push_back(policyInfo);
1144 }
1145 }
1146 }
1147 return ndk::ScopedAStatus::ok();
1148}
1149
Eric Laurente2432ea2023-01-12 17:47:31 +01001150ndk::ScopedAStatus Module::supportsVariableLatency(bool* _aidl_return) {
1151 LOG(DEBUG) << __func__;
1152 *_aidl_return = false;
1153 return ndk::ScopedAStatus::ok();
1154}
1155
jiabinb76981e2023-01-18 00:58:30 +00001156ndk::ScopedAStatus Module::getAAudioMixerBurstCount(int32_t* _aidl_return) {
1157 if (!isMmapSupported()) {
1158 LOG(DEBUG) << __func__ << ": mmap is not supported ";
1159 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1160 }
1161 *_aidl_return = DEFAULT_AAUDIO_MIXER_BURST_COUNT;
1162 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1163 return ndk::ScopedAStatus::ok();
1164}
1165
1166ndk::ScopedAStatus Module::getAAudioHardwareBurstMinUsec(int32_t* _aidl_return) {
1167 if (!isMmapSupported()) {
1168 LOG(DEBUG) << __func__ << ": mmap is not supported ";
1169 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1170 }
1171 *_aidl_return = DEFAULT_AAUDIO_HARDWARE_BURST_MIN_DURATION_US;
1172 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1173 return ndk::ScopedAStatus::ok();
1174}
1175
1176bool Module::isMmapSupported() {
1177 if (mIsMmapSupported.has_value()) {
1178 return mIsMmapSupported.value();
1179 }
1180 std::vector<AudioMMapPolicyInfo> mmapPolicyInfos;
1181 if (!getMmapPolicyInfos(AudioMMapPolicyType::DEFAULT, &mmapPolicyInfos).isOk()) {
1182 mIsMmapSupported = false;
1183 } else {
1184 mIsMmapSupported =
1185 std::find_if(mmapPolicyInfos.begin(), mmapPolicyInfos.end(), [](const auto& info) {
1186 return info.mmapPolicy == AudioMMapPolicy::AUTO ||
1187 info.mmapPolicy == AudioMMapPolicy::ALWAYS;
1188 }) != mmapPolicyInfos.end();
1189 }
1190 return mIsMmapSupported.value();
1191}
1192
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001193} // namespace aidl::android::hardware::audio::core