blob: 7e829e3ef1c3b50ac20b66f00489d163a8152149 [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;
262 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000263 }
264 return *mConfig;
265}
266
267void Module::registerPatch(const AudioPatch& patch) {
268 auto& configs = getConfig().portConfigs;
269 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
270 for (auto portConfigId : portConfigIds) {
271 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
272 if (configIt != configs.end()) {
273 mPatches.insert(std::pair{portConfigId, patch.id});
274 if (configIt->portId != portConfigId) {
275 mPatches.insert(std::pair{configIt->portId, patch.id});
276 }
277 }
278 };
279 };
280 do_insert(patch.sourcePortConfigIds);
281 do_insert(patch.sinkPortConfigIds);
282}
283
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000284void Module::updateStreamsConnectedState(const AudioPatch& oldPatch, const AudioPatch& newPatch) {
285 // Streams from the old patch need to be disconnected, streams from the new
286 // patch need to be connected. If the stream belongs to both patches, no need
287 // to update it.
288 std::set<int32_t> idsToDisconnect, idsToConnect;
289 idsToDisconnect.insert(oldPatch.sourcePortConfigIds.begin(),
290 oldPatch.sourcePortConfigIds.end());
291 idsToDisconnect.insert(oldPatch.sinkPortConfigIds.begin(), oldPatch.sinkPortConfigIds.end());
292 idsToConnect.insert(newPatch.sourcePortConfigIds.begin(), newPatch.sourcePortConfigIds.end());
293 idsToConnect.insert(newPatch.sinkPortConfigIds.begin(), newPatch.sinkPortConfigIds.end());
294 std::for_each(idsToDisconnect.begin(), idsToDisconnect.end(), [&](const auto& portConfigId) {
295 if (idsToConnect.count(portConfigId) == 0) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000296 LOG(DEBUG) << "The stream on port config id " << portConfigId << " is not connected";
297 mStreams.setStreamIsConnected(portConfigId, {});
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000298 }
299 });
300 std::for_each(idsToConnect.begin(), idsToConnect.end(), [&](const auto& portConfigId) {
301 if (idsToDisconnect.count(portConfigId) == 0) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000302 const auto connectedDevices = findConnectedDevices(portConfigId);
303 LOG(DEBUG) << "The stream on port config id " << portConfigId
304 << " is connected to: " << ::android::internal::ToString(connectedDevices);
305 mStreams.setStreamIsConnected(portConfigId, connectedDevices);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000306 }
307 });
308}
309
Mikhail Naganov00603d12022-05-02 22:52:13 +0000310ndk::ScopedAStatus Module::setModuleDebug(
311 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
312 LOG(DEBUG) << __func__ << ": old flags:" << mDebug.toString()
313 << ", new flags: " << in_debug.toString();
314 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
315 !mConnectedDevicePorts.empty()) {
316 LOG(ERROR) << __func__ << ": attempting to change device connections simulation "
317 << "while having external devices connected";
318 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
319 }
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000320 if (in_debug.streamTransientStateDelayMs < 0) {
321 LOG(ERROR) << __func__ << ": streamTransientStateDelayMs is negative: "
322 << in_debug.streamTransientStateDelayMs;
323 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
324 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000325 mDebug = in_debug;
326 return ndk::ScopedAStatus::ok();
327}
328
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000329ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
330 if (mTelephony == nullptr) {
331 mTelephony = ndk::SharedRefBase::make<Telephony>();
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000332 mTelephonyBinder = mTelephony->asBinder();
333 AIBinder_setMinSchedulerPolicy(mTelephonyBinder.get(), SCHED_NORMAL,
Shunkai Yao39bf2c32022-12-06 03:25:59 +0000334 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000335 }
336 *_aidl_return = mTelephony;
337 LOG(DEBUG) << __func__ << ": returning instance of ITelephony: " << _aidl_return->get();
338 return ndk::ScopedAStatus::ok();
339}
340
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000341ndk::ScopedAStatus Module::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
342 if (mBluetooth == nullptr) {
343 mBluetooth = ndk::SharedRefBase::make<Bluetooth>();
344 mBluetoothBinder = mBluetooth->asBinder();
345 AIBinder_setMinSchedulerPolicy(mBluetoothBinder.get(), SCHED_NORMAL,
346 ANDROID_PRIORITY_AUDIO);
347 }
348 *_aidl_return = mBluetooth;
349 LOG(DEBUG) << __func__ << ": returning instance of IBluetooth: " << _aidl_return->get();
350 return ndk::ScopedAStatus::ok();
351}
352
Mikhail Naganov00603d12022-05-02 22:52:13 +0000353ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
354 AudioPort* _aidl_return) {
355 const int32_t templateId = in_templateIdAndAdditionalData.id;
356 auto& ports = getConfig().ports;
357 AudioPort connectedPort;
358 { // Scope the template port so that we don't accidentally modify it.
359 auto templateIt = findById<AudioPort>(ports, templateId);
360 if (templateIt == ports.end()) {
361 LOG(ERROR) << __func__ << ": port id " << templateId << " not found";
362 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
363 }
364 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
365 LOG(ERROR) << __func__ << ": port id " << templateId << " is not a device port";
366 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
367 }
368 if (!templateIt->profiles.empty()) {
369 LOG(ERROR) << __func__ << ": port id " << templateId
370 << " does not have dynamic profiles";
371 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
372 }
373 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
374 if (templateDevicePort.device.type.connection.empty()) {
375 LOG(ERROR) << __func__ << ": port id " << templateId << " is permanently attached";
376 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
377 }
378 // Postpone id allocation until we ensure that there are no client errors.
379 connectedPort = *templateIt;
380 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
381 const auto& inputDevicePort =
382 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
383 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
384 connectedDevicePort.device.address = inputDevicePort.device.address;
385 LOG(DEBUG) << __func__ << ": device port " << connectedPort.id << " device set to "
386 << connectedDevicePort.device.toString();
387 // Check if there is already a connected port with for the same external device.
388 for (auto connectedPortId : mConnectedDevicePorts) {
389 auto connectedPortIt = findById<AudioPort>(ports, connectedPortId);
390 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
391 connectedDevicePort.device) {
392 LOG(ERROR) << __func__ << ": device " << connectedDevicePort.device.toString()
393 << " is already connected at the device port id " << connectedPortId;
394 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
395 }
396 }
397 }
398
399 if (!mDebug.simulateDeviceConnections) {
400 // In a real HAL here we would attempt querying the profiles from the device.
401 LOG(ERROR) << __func__ << ": failed to query supported device profiles";
402 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
403 }
404
405 connectedPort.id = ++getConfig().nextPortId;
406 mConnectedDevicePorts.insert(connectedPort.id);
407 LOG(DEBUG) << __func__ << ": template port " << templateId << " external device connected, "
408 << "connected port ID " << connectedPort.id;
409 auto& connectedProfiles = getConfig().connectedProfiles;
410 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
411 connectedProfilesIt != connectedProfiles.end()) {
412 connectedPort.profiles = connectedProfilesIt->second;
413 }
414 ports.push_back(connectedPort);
415 *_aidl_return = std::move(connectedPort);
416
417 std::vector<AudioRoute> newRoutes;
418 auto& routes = getConfig().routes;
419 for (auto& r : routes) {
420 if (r.sinkPortId == templateId) {
421 AudioRoute newRoute;
422 newRoute.sourcePortIds = r.sourcePortIds;
423 newRoute.sinkPortId = connectedPort.id;
424 newRoute.isExclusive = r.isExclusive;
425 newRoutes.push_back(std::move(newRoute));
426 } else {
427 auto& srcs = r.sourcePortIds;
428 if (std::find(srcs.begin(), srcs.end(), templateId) != srcs.end()) {
429 srcs.push_back(connectedPort.id);
430 }
431 }
432 }
433 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
434
435 return ndk::ScopedAStatus::ok();
436}
437
438ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
439 auto& ports = getConfig().ports;
440 auto portIt = findById<AudioPort>(ports, in_portId);
441 if (portIt == ports.end()) {
442 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
443 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
444 }
445 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
446 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a device port";
447 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
448 }
449 if (mConnectedDevicePorts.count(in_portId) == 0) {
450 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a connected device port";
451 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
452 }
453 auto& configs = getConfig().portConfigs;
454 auto& initials = getConfig().initialConfigs;
455 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
456 if (config.portId == in_portId) {
457 // Check if the configuration was provided by the client.
458 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
459 return initialIt == initials.end() || config != *initialIt;
460 }
461 return false;
462 });
463 if (configIt != configs.end()) {
464 LOG(ERROR) << __func__ << ": port id " << in_portId << " has a non-default config with id "
465 << configIt->id;
466 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
467 }
468 ports.erase(portIt);
469 mConnectedDevicePorts.erase(in_portId);
470 LOG(DEBUG) << __func__ << ": connected device port " << in_portId << " released";
471
472 auto& routes = getConfig().routes;
473 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
474 if (routesIt->sinkPortId == in_portId) {
475 routesIt = routes.erase(routesIt);
476 } else {
477 // Note: the list of sourcePortIds can't become empty because there must
478 // be the id of the template port in the route.
479 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
480 ++routesIt;
481 }
482 }
483
484 return ndk::ScopedAStatus::ok();
485}
486
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000487ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
488 *_aidl_return = getConfig().patches;
489 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " patches";
490 return ndk::ScopedAStatus::ok();
491}
492
493ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
494 auto& ports = getConfig().ports;
495 auto portIt = findById<AudioPort>(ports, in_portId);
496 if (portIt != ports.end()) {
497 *_aidl_return = *portIt;
498 LOG(DEBUG) << __func__ << ": returning port by id " << in_portId;
499 return ndk::ScopedAStatus::ok();
500 }
501 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
502 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
503}
504
505ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
506 *_aidl_return = getConfig().portConfigs;
507 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " port configs";
508 return ndk::ScopedAStatus::ok();
509}
510
511ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
512 *_aidl_return = getConfig().ports;
513 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " ports";
514 return ndk::ScopedAStatus::ok();
515}
516
517ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
518 *_aidl_return = getConfig().routes;
519 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " routes";
520 return ndk::ScopedAStatus::ok();
521}
522
Mikhail Naganov00603d12022-05-02 22:52:13 +0000523ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
524 std::vector<AudioRoute>* _aidl_return) {
525 auto& ports = getConfig().ports;
526 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
527 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
528 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
529 }
530 auto& routes = getConfig().routes;
531 std::copy_if(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
532 [&](const auto& r) {
533 const auto& srcs = r.sourcePortIds;
534 return r.sinkPortId == in_portId ||
535 std::find(srcs.begin(), srcs.end(), in_portId) != srcs.end();
536 });
537 return ndk::ScopedAStatus::ok();
538}
539
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000540ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
541 OpenInputStreamReturn* _aidl_return) {
542 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", buffer size "
543 << in_args.bufferSizeFrames << " frames";
544 AudioPort* port = nullptr;
545 if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
546 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000547 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000548 if (port->flags.getTag() != AudioIoFlags::Tag::input) {
549 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000550 << " does not correspond to an input mix port";
551 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
552 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000553 StreamContext context;
Mikhail Naganov30301a42022-09-13 01:20:45 +0000554 if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames, nullptr,
Mikhail Naganov8651b362023-01-06 23:15:27 +0000555 nullptr, &context);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000556 !status.isOk()) {
557 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000558 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000559 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000560 std::shared_ptr<StreamIn> stream;
Mikhail Naganovf429c032023-01-07 00:24:50 +0000561 // TODO: Add a mapping from module instance names to a corresponding 'createInstance'.
562 if (auto status = StreamInStub::createInstance(in_args.sinkMetadata, std::move(context),
563 mConfig->microphones, &stream);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000564 !status.isOk()) {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000565 return status;
566 }
567 StreamWrapper streamWrapper(stream);
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000568 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
569 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000570 auto patchIt = mPatches.find(in_args.portConfigId);
571 if (patchIt != mPatches.end()) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000572 streamWrapper.setStreamIsConnected(findConnectedDevices(in_args.portConfigId));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000573 }
574 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000575 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000576 return ndk::ScopedAStatus::ok();
577}
578
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000579ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
580 OpenOutputStreamReturn* _aidl_return) {
581 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", has offload info? "
582 << (in_args.offloadInfo.has_value()) << ", buffer size " << in_args.bufferSizeFrames
583 << " frames";
584 AudioPort* port = nullptr;
585 if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
586 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000587 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000588 if (port->flags.getTag() != AudioIoFlags::Tag::output) {
589 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000590 << " does not correspond to an output mix port";
591 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
592 }
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000593 const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
594 AudioOutputFlags::COMPRESS_OFFLOAD);
595 if (isOffload && !in_args.offloadInfo.has_value()) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000596 LOG(ERROR) << __func__ << ": port id " << port->id
Mikhail Naganov111e0ce2022-06-17 21:41:19 +0000597 << " has COMPRESS_OFFLOAD flag set, requires offload info";
598 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
599 }
Mikhail Naganov30301a42022-09-13 01:20:45 +0000600 const bool isNonBlocking = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
601 AudioOutputFlags::NON_BLOCKING);
602 if (isNonBlocking && in_args.callback == nullptr) {
603 LOG(ERROR) << __func__ << ": port id " << port->id
604 << " has NON_BLOCKING flag set, requires async callback";
605 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
606 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000607 StreamContext context;
Mikhail Naganov30301a42022-09-13 01:20:45 +0000608 if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
Mikhail Naganov8651b362023-01-06 23:15:27 +0000609 isNonBlocking ? in_args.callback : nullptr,
610 in_args.eventCallback, &context);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000611 !status.isOk()) {
612 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000613 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000614 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000615 std::shared_ptr<StreamOut> stream;
Mikhail Naganovf429c032023-01-07 00:24:50 +0000616 // TODO: Add a mapping from module instance names to a corresponding 'createInstance'.
617 if (auto status = StreamOutStub::createInstance(in_args.sourceMetadata, std::move(context),
618 in_args.offloadInfo, &stream);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000619 !status.isOk()) {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000620 return status;
621 }
622 StreamWrapper streamWrapper(stream);
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000623 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
624 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000625 auto patchIt = mPatches.find(in_args.portConfigId);
626 if (patchIt != mPatches.end()) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000627 streamWrapper.setStreamIsConnected(findConnectedDevices(in_args.portConfigId));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000628 }
629 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000630 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000631 return ndk::ScopedAStatus::ok();
632}
633
Mikhail Naganov74927202022-12-19 16:37:14 +0000634ndk::ScopedAStatus Module::getSupportedPlaybackRateFactors(
635 SupportedPlaybackRateFactors* _aidl_return) {
636 LOG(DEBUG) << __func__;
637 (void)_aidl_return;
638 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
639}
640
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000641ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
Mikhail Naganov16db9b72022-06-17 21:36:18 +0000642 LOG(DEBUG) << __func__ << ": requested patch " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000643 if (in_requested.sourcePortConfigIds.empty()) {
644 LOG(ERROR) << __func__ << ": requested patch has empty sources list";
645 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
646 }
647 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
648 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sources list";
649 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
650 }
651 if (in_requested.sinkPortConfigIds.empty()) {
652 LOG(ERROR) << __func__ << ": requested patch has empty sinks list";
653 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
654 }
655 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
656 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sinks list";
657 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
658 }
659
660 auto& configs = getConfig().portConfigs;
661 std::vector<int32_t> missingIds;
662 auto sources =
663 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
664 if (!missingIds.empty()) {
665 LOG(ERROR) << __func__ << ": following source port config ids not found: "
666 << ::android::internal::ToString(missingIds);
667 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
668 }
669 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
670 if (!missingIds.empty()) {
671 LOG(ERROR) << __func__ << ": following sink port config ids not found: "
672 << ::android::internal::ToString(missingIds);
673 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
674 }
675 // bool indicates whether a non-exclusive route is available.
676 // If only an exclusive route is available, that means the patch can not be
677 // established if there is any other patch which currently uses the sink port.
678 std::map<int32_t, bool> allowedSinkPorts;
679 auto& routes = getConfig().routes;
680 for (auto src : sources) {
681 for (const auto& r : routes) {
682 const auto& srcs = r.sourcePortIds;
683 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
684 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
685 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
686 }
687 }
688 }
689 }
690 for (auto sink : sinks) {
691 if (allowedSinkPorts.count(sink->portId) == 0) {
692 LOG(ERROR) << __func__ << ": there is no route to the sink port id " << sink->portId;
693 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
694 }
695 }
696
697 auto& patches = getConfig().patches;
698 auto existing = patches.end();
699 std::optional<decltype(mPatches)> patchesBackup;
700 if (in_requested.id != 0) {
701 existing = findById<AudioPatch>(patches, in_requested.id);
702 if (existing != patches.end()) {
703 patchesBackup = mPatches;
704 cleanUpPatch(existing->id);
705 } else {
706 LOG(ERROR) << __func__ << ": not found existing patch id " << in_requested.id;
707 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
708 }
709 }
710 // Validate the requested patch.
711 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
712 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
713 LOG(ERROR) << __func__ << ": sink port id " << sinkPortId
714 << "is exclusive and is already used by some other patch";
715 if (patchesBackup.has_value()) {
716 mPatches = std::move(*patchesBackup);
717 }
718 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
719 }
720 }
721 *_aidl_return = in_requested;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000722 _aidl_return->minimumStreamBufferSizeFrames = kMinimumStreamBufferSizeFrames;
723 _aidl_return->latenciesMs.clear();
724 _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
725 _aidl_return->sinkPortConfigIds.size(), kLatencyMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000726 AudioPatch oldPatch{};
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000727 if (existing == patches.end()) {
728 _aidl_return->id = getConfig().nextPatchId++;
729 patches.push_back(*_aidl_return);
730 existing = patches.begin() + (patches.size() - 1);
731 } else {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000732 oldPatch = *existing;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000733 *existing = *_aidl_return;
734 }
735 registerPatch(*existing);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000736 updateStreamsConnectedState(oldPatch, *_aidl_return);
737
738 LOG(DEBUG) << __func__ << ": " << (oldPatch.id == 0 ? "created" : "updated") << " patch "
739 << _aidl_return->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000740 return ndk::ScopedAStatus::ok();
741}
742
743ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
744 AudioPortConfig* out_suggested, bool* _aidl_return) {
745 LOG(DEBUG) << __func__ << ": requested " << in_requested.toString();
746 auto& configs = getConfig().portConfigs;
747 auto existing = configs.end();
748 if (in_requested.id != 0) {
749 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
750 existing == configs.end()) {
751 LOG(ERROR) << __func__ << ": existing port config id " << in_requested.id
752 << " not found";
753 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
754 }
755 }
756
757 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
758 if (portId == 0) {
759 LOG(ERROR) << __func__ << ": input port config does not specify portId";
760 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
761 }
762 auto& ports = getConfig().ports;
763 auto portIt = findById<AudioPort>(ports, portId);
764 if (portIt == ports.end()) {
765 LOG(ERROR) << __func__ << ": input port config points to non-existent portId " << portId;
766 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
767 }
768 if (existing != configs.end()) {
769 *out_suggested = *existing;
770 } else {
771 AudioPortConfig newConfig;
772 if (generateDefaultPortConfig(*portIt, &newConfig)) {
773 *out_suggested = newConfig;
774 } else {
775 LOG(ERROR) << __func__ << ": unable generate a default config for port " << portId;
776 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
777 }
778 }
779 // From this moment, 'out_suggested' is either an existing port config,
780 // or a new generated config. Now attempt to update it according to the specified
781 // fields of 'in_requested'.
782
783 bool requestedIsValid = true, requestedIsFullySpecified = true;
784
785 AudioIoFlags portFlags = portIt->flags;
786 if (in_requested.flags.has_value()) {
787 if (in_requested.flags.value() != portFlags) {
788 LOG(WARNING) << __func__ << ": requested flags "
789 << in_requested.flags.value().toString() << " do not match port's "
790 << portId << " flags " << portFlags.toString();
791 requestedIsValid = false;
792 }
793 } else {
794 requestedIsFullySpecified = false;
795 }
796
797 AudioProfile portProfile;
798 if (in_requested.format.has_value()) {
799 const auto& format = in_requested.format.value();
800 if (findAudioProfile(*portIt, format, &portProfile)) {
801 out_suggested->format = format;
802 } else {
803 LOG(WARNING) << __func__ << ": requested format " << format.toString()
804 << " is not found in port's " << portId << " profiles";
805 requestedIsValid = false;
806 }
807 } else {
808 requestedIsFullySpecified = false;
809 }
810 if (!findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
811 LOG(ERROR) << __func__ << ": port " << portId << " does not support format "
812 << out_suggested->format.value().toString() << " anymore";
813 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
814 }
815
816 if (in_requested.channelMask.has_value()) {
817 const auto& channelMask = in_requested.channelMask.value();
818 if (find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
819 portProfile.channelMasks.end()) {
820 out_suggested->channelMask = channelMask;
821 } else {
822 LOG(WARNING) << __func__ << ": requested channel mask " << channelMask.toString()
823 << " is not supported for the format " << portProfile.format.toString()
824 << " by the port " << portId;
825 requestedIsValid = false;
826 }
827 } else {
828 requestedIsFullySpecified = false;
829 }
830
831 if (in_requested.sampleRate.has_value()) {
832 const auto& sampleRate = in_requested.sampleRate.value();
833 if (find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
834 sampleRate.value) != portProfile.sampleRates.end()) {
835 out_suggested->sampleRate = sampleRate;
836 } else {
837 LOG(WARNING) << __func__ << ": requested sample rate " << sampleRate.value
838 << " is not supported for the format " << portProfile.format.toString()
839 << " by the port " << portId;
840 requestedIsValid = false;
841 }
842 } else {
843 requestedIsFullySpecified = false;
844 }
845
846 if (in_requested.gain.has_value()) {
847 // Let's pretend that gain can always be applied.
848 out_suggested->gain = in_requested.gain.value();
849 }
850
851 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
852 out_suggested->id = getConfig().nextPortId++;
853 configs.push_back(*out_suggested);
854 *_aidl_return = true;
855 LOG(DEBUG) << __func__ << ": created new port config " << out_suggested->toString();
856 } else if (existing != configs.end() && requestedIsValid) {
857 *existing = *out_suggested;
858 *_aidl_return = true;
859 LOG(DEBUG) << __func__ << ": updated port config " << out_suggested->toString();
860 } else {
861 LOG(DEBUG) << __func__ << ": not applied; existing config ? " << (existing != configs.end())
862 << "; requested is valid? " << requestedIsValid << ", fully specified? "
863 << requestedIsFullySpecified;
864 *_aidl_return = false;
865 }
866 return ndk::ScopedAStatus::ok();
867}
868
869ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
870 auto& patches = getConfig().patches;
871 auto patchIt = findById<AudioPatch>(patches, in_patchId);
872 if (patchIt != patches.end()) {
873 cleanUpPatch(patchIt->id);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000874 updateStreamsConnectedState(*patchIt, AudioPatch{});
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000875 patches.erase(patchIt);
876 LOG(DEBUG) << __func__ << ": erased patch " << in_patchId;
877 return ndk::ScopedAStatus::ok();
878 }
879 LOG(ERROR) << __func__ << ": patch id " << in_patchId << " not found";
880 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
881}
882
883ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
884 auto& configs = getConfig().portConfigs;
885 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
886 if (configIt != configs.end()) {
887 if (mStreams.count(in_portConfigId) != 0) {
888 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
889 << " has a stream opened on it";
890 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
891 }
892 auto patchIt = mPatches.find(in_portConfigId);
893 if (patchIt != mPatches.end()) {
894 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
895 << " is used by the patch with id " << patchIt->second;
896 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
897 }
898 auto& initials = getConfig().initialConfigs;
899 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
900 if (initialIt == initials.end()) {
901 configs.erase(configIt);
902 LOG(DEBUG) << __func__ << ": erased port config " << in_portConfigId;
903 } else if (*configIt != *initialIt) {
904 *configIt = *initialIt;
905 LOG(DEBUG) << __func__ << ": reset port config " << in_portConfigId;
906 }
907 return ndk::ScopedAStatus::ok();
908 }
909 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId << " not found";
910 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
911}
912
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000913ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) {
914 *_aidl_return = mMasterMute;
915 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
916 return ndk::ScopedAStatus::ok();
917}
918
919ndk::ScopedAStatus Module::setMasterMute(bool in_mute) {
920 LOG(DEBUG) << __func__ << ": " << in_mute;
921 mMasterMute = in_mute;
922 return ndk::ScopedAStatus::ok();
923}
924
925ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) {
926 *_aidl_return = mMasterVolume;
927 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
928 return ndk::ScopedAStatus::ok();
929}
930
931ndk::ScopedAStatus Module::setMasterVolume(float in_volume) {
932 LOG(DEBUG) << __func__ << ": " << in_volume;
933 if (in_volume >= 0.0f && in_volume <= 1.0f) {
934 mMasterVolume = in_volume;
935 return ndk::ScopedAStatus::ok();
936 }
937 LOG(ERROR) << __func__ << ": invalid master volume value: " << in_volume;
938 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
939}
940
941ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) {
942 *_aidl_return = mMicMute;
943 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
944 return ndk::ScopedAStatus::ok();
945}
946
947ndk::ScopedAStatus Module::setMicMute(bool in_mute) {
948 LOG(DEBUG) << __func__ << ": " << in_mute;
949 mMicMute = in_mute;
950 return ndk::ScopedAStatus::ok();
951}
952
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000953ndk::ScopedAStatus Module::getMicrophones(std::vector<MicrophoneInfo>* _aidl_return) {
954 *_aidl_return = mConfig->microphones;
955 LOG(DEBUG) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return);
956 return ndk::ScopedAStatus::ok();
957}
958
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000959ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) {
Mikhail Naganov04ae8222023-01-11 15:48:10 -0800960 if (!isValidAudioMode(in_mode)) {
961 LOG(ERROR) << __func__ << ": invalid mode " << toString(in_mode);
962 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
963 }
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000964 // No checks for supported audio modes here, it's an informative notification.
965 LOG(DEBUG) << __func__ << ": " << toString(in_mode);
966 return ndk::ScopedAStatus::ok();
967}
968
969ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) {
970 LOG(DEBUG) << __func__ << ": " << toString(in_rotation);
971 return ndk::ScopedAStatus::ok();
972}
973
974ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) {
975 LOG(DEBUG) << __func__ << ": " << in_isTurnedOn;
976 return ndk::ScopedAStatus::ok();
977}
978
Vlad Popa83a6d822022-11-07 13:53:57 +0100979ndk::ScopedAStatus Module::getSoundDose(std::shared_ptr<ISoundDose>* _aidl_return) {
Vlad Popa943b7e22022-12-08 14:24:12 +0100980 if (mSoundDose == nullptr) {
Vlad Popa2afbd1e2022-12-28 17:04:58 +0100981 mSoundDose = ndk::SharedRefBase::make<sounddose::SoundDose>();
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000982 mSoundDoseBinder = mSoundDose->asBinder();
983 AIBinder_setMinSchedulerPolicy(mSoundDoseBinder.get(), SCHED_NORMAL,
984 ANDROID_PRIORITY_AUDIO);
Vlad Popa943b7e22022-12-08 14:24:12 +0100985 }
986 *_aidl_return = mSoundDose;
987 LOG(DEBUG) << __func__ << ": returning instance of ISoundDose: " << _aidl_return->get();
Vlad Popa83a6d822022-11-07 13:53:57 +0100988 return ndk::ScopedAStatus::ok();
989}
990
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000991ndk::ScopedAStatus Module::generateHwAvSyncId(int32_t* _aidl_return) {
992 LOG(DEBUG) << __func__;
993 (void)_aidl_return;
994 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
995}
996
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000997const std::string Module::VendorDebug::kForceTransientBurstName = "aosp.forceTransientBurst";
Mikhail Naganov194daaa2023-01-05 22:34:20 +0000998const std::string Module::VendorDebug::kForceSynchronousDrainName = "aosp.forceSynchronousDrain";
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000999
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001000ndk::ScopedAStatus Module::getVendorParameters(const std::vector<std::string>& in_ids,
1001 std::vector<VendorParameter>* _aidl_return) {
1002 LOG(DEBUG) << __func__ << ": id count: " << in_ids.size();
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001003 bool allParametersKnown = true;
1004 for (const auto& id : in_ids) {
1005 if (id == VendorDebug::kForceTransientBurstName) {
1006 VendorParameter forceTransientBurst{.id = id};
1007 forceTransientBurst.ext.setParcelable(Boolean{mVendorDebug.forceTransientBurst});
1008 _aidl_return->push_back(std::move(forceTransientBurst));
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001009 } else if (id == VendorDebug::kForceSynchronousDrainName) {
1010 VendorParameter forceSynchronousDrain{.id = id};
1011 forceSynchronousDrain.ext.setParcelable(Boolean{mVendorDebug.forceSynchronousDrain});
1012 _aidl_return->push_back(std::move(forceSynchronousDrain));
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001013 } else {
1014 allParametersKnown = false;
1015 LOG(ERROR) << __func__ << ": unrecognized parameter \"" << id << "\"";
1016 }
1017 }
1018 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1019 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001020}
1021
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001022namespace {
1023
1024template <typename W>
1025bool extractParameter(const VendorParameter& p, decltype(W::value)* v) {
1026 std::optional<W> value;
1027 binder_status_t result = p.ext.getParcelable(&value);
1028 if (result == STATUS_OK && value.has_value()) {
1029 *v = value.value().value;
1030 return true;
1031 }
1032 LOG(ERROR) << __func__ << ": failed to read the value of the parameter \"" << p.id
1033 << "\": " << result;
1034 return false;
1035}
1036
1037} // namespace
1038
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001039ndk::ScopedAStatus Module::setVendorParameters(const std::vector<VendorParameter>& in_parameters,
1040 bool in_async) {
1041 LOG(DEBUG) << __func__ << ": parameter count " << in_parameters.size()
1042 << ", async: " << in_async;
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001043 bool allParametersKnown = true;
1044 for (const auto& p : in_parameters) {
1045 if (p.id == VendorDebug::kForceTransientBurstName) {
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001046 if (!extractParameter<Boolean>(p, &mVendorDebug.forceTransientBurst)) {
1047 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1048 }
1049 } else if (p.id == VendorDebug::kForceSynchronousDrainName) {
1050 if (!extractParameter<Boolean>(p, &mVendorDebug.forceSynchronousDrain)) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001051 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1052 }
1053 } else {
1054 allParametersKnown = false;
1055 LOG(ERROR) << __func__ << ": unrecognized parameter \"" << p.id << "\"";
1056 }
1057 }
1058 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1059 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001060}
1061
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001062ndk::ScopedAStatus Module::addDeviceEffect(
1063 int32_t in_portConfigId,
1064 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1065 if (in_effect == nullptr) {
1066 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect";
1067 } else {
1068 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder "
1069 << in_effect->asBinder().get();
1070 }
1071 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1072}
1073
1074ndk::ScopedAStatus Module::removeDeviceEffect(
1075 int32_t in_portConfigId,
1076 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1077 if (in_effect == nullptr) {
1078 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect";
1079 } else {
1080 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder "
1081 << in_effect->asBinder().get();
1082 }
1083 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1084}
1085
jiabin9a8e6862023-01-12 23:06:37 +00001086ndk::ScopedAStatus Module::getMmapPolicyInfos(AudioMMapPolicyType mmapPolicyType,
1087 std::vector<AudioMMapPolicyInfo>* _aidl_return) {
1088 LOG(DEBUG) << __func__ << ": mmap policy type " << toString(mmapPolicyType);
1089 std::set<int32_t> mmapSinks;
1090 std::set<int32_t> mmapSources;
1091 auto& ports = getConfig().ports;
1092 for (const auto& port : ports) {
1093 if (port.flags.getTag() == AudioIoFlags::Tag::input &&
1094 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::input>(),
1095 AudioInputFlags::MMAP_NOIRQ)) {
1096 mmapSinks.insert(port.id);
1097 } else if (port.flags.getTag() == AudioIoFlags::Tag::output &&
1098 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
1099 AudioOutputFlags::MMAP_NOIRQ)) {
1100 mmapSources.insert(port.id);
1101 }
1102 }
1103 for (const auto& route : getConfig().routes) {
1104 if (mmapSinks.count(route.sinkPortId) != 0) {
1105 // The sink is a mix port, add the sources if they are device ports.
1106 for (int sourcePortId : route.sourcePortIds) {
1107 auto sourcePortIt = findById<AudioPort>(ports, sourcePortId);
1108 if (sourcePortIt == ports.end()) {
1109 // This must not happen
1110 LOG(ERROR) << __func__ << ": port id " << sourcePortId << " cannot be found";
1111 continue;
1112 }
1113 if (sourcePortIt->ext.getTag() != AudioPortExt::Tag::device) {
1114 // The source is not a device port, skip
1115 continue;
1116 }
1117 AudioMMapPolicyInfo policyInfo;
1118 policyInfo.device = sourcePortIt->ext.get<AudioPortExt::Tag::device>().device;
1119 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1120 // default implementation.
1121 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1122 _aidl_return->push_back(policyInfo);
1123 }
1124 } else {
1125 auto sinkPortIt = findById<AudioPort>(ports, route.sinkPortId);
1126 if (sinkPortIt == ports.end()) {
1127 // This must not happen
1128 LOG(ERROR) << __func__ << ": port id " << route.sinkPortId << " cannot be found";
1129 continue;
1130 }
1131 if (sinkPortIt->ext.getTag() != AudioPortExt::Tag::device) {
1132 // The sink is not a device port, skip
1133 continue;
1134 }
1135 if (count_any(mmapSources, route.sourcePortIds)) {
1136 AudioMMapPolicyInfo policyInfo;
1137 policyInfo.device = sinkPortIt->ext.get<AudioPortExt::Tag::device>().device;
1138 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1139 // default implementation.
1140 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1141 _aidl_return->push_back(policyInfo);
1142 }
1143 }
1144 }
1145 return ndk::ScopedAStatus::ok();
1146}
1147
Eric Laurente2432ea2023-01-12 17:47:31 +01001148ndk::ScopedAStatus Module::supportsVariableLatency(bool* _aidl_return) {
1149 LOG(DEBUG) << __func__;
1150 *_aidl_return = false;
1151 return ndk::ScopedAStatus::ok();
1152}
1153
jiabinb76981e2023-01-18 00:58:30 +00001154ndk::ScopedAStatus Module::getAAudioMixerBurstCount(int32_t* _aidl_return) {
1155 if (!isMmapSupported()) {
1156 LOG(DEBUG) << __func__ << ": mmap is not supported ";
1157 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1158 }
1159 *_aidl_return = DEFAULT_AAUDIO_MIXER_BURST_COUNT;
1160 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1161 return ndk::ScopedAStatus::ok();
1162}
1163
1164ndk::ScopedAStatus Module::getAAudioHardwareBurstMinUsec(int32_t* _aidl_return) {
1165 if (!isMmapSupported()) {
1166 LOG(DEBUG) << __func__ << ": mmap is not supported ";
1167 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1168 }
1169 *_aidl_return = DEFAULT_AAUDIO_HARDWARE_BURST_MIN_DURATION_US;
1170 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1171 return ndk::ScopedAStatus::ok();
1172}
1173
1174bool Module::isMmapSupported() {
1175 if (mIsMmapSupported.has_value()) {
1176 return mIsMmapSupported.value();
1177 }
1178 std::vector<AudioMMapPolicyInfo> mmapPolicyInfos;
1179 if (!getMmapPolicyInfos(AudioMMapPolicyType::DEFAULT, &mmapPolicyInfos).isOk()) {
1180 mIsMmapSupported = false;
1181 } else {
1182 mIsMmapSupported =
1183 std::find_if(mmapPolicyInfos.begin(), mmapPolicyInfos.end(), [](const auto& info) {
1184 return info.mmapPolicy == AudioMMapPolicy::AUTO ||
1185 info.mmapPolicy == AudioMMapPolicy::ALWAYS;
1186 }) != mmapPolicyInfos.end();
1187 }
1188 return mIsMmapSupported.value();
1189}
1190
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001191} // namespace aidl::android::hardware::audio::core