blob: 55e5bff1d7ef0fd0d4c8febbc17e1ca36c9363bf [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 Naganov3b125b72022-10-05 02:12:39 +000031#include "core-impl/Telephony.h"
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000032#include "core-impl/utils.h"
33
34using aidl::android::hardware::audio::common::SinkMetadata;
35using aidl::android::hardware::audio::common::SourceMetadata;
Vlad Popa2afbd1e2022-12-28 17:04:58 +010036using aidl::android::hardware::audio::core::sounddose::ISoundDose;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000037using aidl::android::media::audio::common::AudioChannelLayout;
Mikhail Naganovef6bc742022-10-06 00:14:19 +000038using aidl::android::media::audio::common::AudioDevice;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000039using aidl::android::media::audio::common::AudioFormatDescription;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000040using aidl::android::media::audio::common::AudioFormatType;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000041using aidl::android::media::audio::common::AudioInputFlags;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000042using aidl::android::media::audio::common::AudioIoFlags;
43using aidl::android::media::audio::common::AudioOffloadInfo;
44using aidl::android::media::audio::common::AudioOutputFlags;
45using aidl::android::media::audio::common::AudioPort;
46using aidl::android::media::audio::common::AudioPortConfig;
47using aidl::android::media::audio::common::AudioPortExt;
48using aidl::android::media::audio::common::AudioProfile;
Mikhail Naganov20047bc2023-01-05 20:16:07 +000049using aidl::android::media::audio::common::Boolean;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000050using aidl::android::media::audio::common::Int;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000051using aidl::android::media::audio::common::PcmType;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000052using android::hardware::audio::common::getFrameSizeInBytes;
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +000053using android::hardware::audio::common::isBitPositionFlagSet;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000054
55namespace aidl::android::hardware::audio::core {
56
57namespace {
58
59bool generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) {
60 *config = {};
61 config->portId = port.id;
62 if (port.profiles.empty()) {
63 LOG(ERROR) << __func__ << ": port " << port.id << " has no profiles";
64 return false;
65 }
66 const auto& profile = port.profiles.begin();
67 config->format = profile->format;
68 if (profile->channelMasks.empty()) {
69 LOG(ERROR) << __func__ << ": the first profile in port " << port.id
70 << " has no channel masks";
71 return false;
72 }
73 config->channelMask = *profile->channelMasks.begin();
74 if (profile->sampleRates.empty()) {
75 LOG(ERROR) << __func__ << ": the first profile in port " << port.id
76 << " has no sample rates";
77 return false;
78 }
79 Int sampleRate;
80 sampleRate.value = *profile->sampleRates.begin();
81 config->sampleRate = sampleRate;
82 config->flags = port.flags;
83 config->ext = port.ext;
84 return true;
85}
86
87bool findAudioProfile(const AudioPort& port, const AudioFormatDescription& format,
88 AudioProfile* profile) {
89 if (auto profilesIt =
90 find_if(port.profiles.begin(), port.profiles.end(),
91 [&format](const auto& profile) { return profile.format == format; });
92 profilesIt != port.profiles.end()) {
93 *profile = *profilesIt;
94 return true;
95 }
96 return false;
97}
Mikhail Naganov00603d12022-05-02 22:52:13 +000098
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000099} // namespace
100
101void Module::cleanUpPatch(int32_t patchId) {
102 erase_all_values(mPatches, std::set<int32_t>{patchId});
103}
104
Mikhail Naganov8651b362023-01-06 23:15:27 +0000105ndk::ScopedAStatus Module::createStreamContext(
106 int32_t in_portConfigId, int64_t in_bufferSizeFrames,
107 std::shared_ptr<IStreamCallback> asyncCallback,
108 std::shared_ptr<IStreamOutEventCallback> outEventCallback, StreamContext* out_context) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000109 if (in_bufferSizeFrames <= 0) {
110 LOG(ERROR) << __func__ << ": non-positive buffer size " << in_bufferSizeFrames;
111 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
112 }
113 if (in_bufferSizeFrames < kMinimumStreamBufferSizeFrames) {
114 LOG(ERROR) << __func__ << ": insufficient buffer size " << in_bufferSizeFrames
115 << ", must be at least " << kMinimumStreamBufferSizeFrames;
116 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
117 }
118 auto& configs = getConfig().portConfigs;
119 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000120 // Since this is a private method, it is assumed that
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000121 // validity of the portConfigId has already been checked.
122 const size_t frameSize =
123 getFrameSizeInBytes(portConfigIt->format.value(), portConfigIt->channelMask.value());
124 if (frameSize == 0) {
125 LOG(ERROR) << __func__ << ": could not calculate frame size for port config "
126 << portConfigIt->toString();
127 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
128 }
129 LOG(DEBUG) << __func__ << ": frame size " << frameSize << " bytes";
130 if (frameSize > kMaximumStreamBufferSizeBytes / in_bufferSizeFrames) {
131 LOG(ERROR) << __func__ << ": buffer size " << in_bufferSizeFrames
132 << " frames is too large, maximum size is "
133 << kMaximumStreamBufferSizeBytes / frameSize;
134 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
135 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000136 const auto& flags = portConfigIt->flags.value();
137 if ((flags.getTag() == AudioIoFlags::Tag::input &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000138 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::input>(),
139 AudioInputFlags::MMAP_NOIRQ)) ||
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000140 (flags.getTag() == AudioIoFlags::Tag::output &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000141 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::output>(),
142 AudioOutputFlags::MMAP_NOIRQ))) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000143 StreamContext::DebugParameters params{mDebug.streamTransientStateDelayMs,
Mikhail Naganov194daaa2023-01-05 22:34:20 +0000144 mVendorDebug.forceTransientBurst,
145 mVendorDebug.forceSynchronousDrain};
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000146 StreamContext temp(
147 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
148 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000149 portConfigIt->format.value(), portConfigIt->channelMask.value(),
150 std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames),
Mikhail Naganov8651b362023-01-06 23:15:27 +0000151 asyncCallback, outEventCallback, params);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000152 if (temp.isValid()) {
153 *out_context = std::move(temp);
154 } else {
155 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
156 }
157 } else {
158 // TODO: Implement simulation of MMAP buffer allocation
159 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000160 return ndk::ScopedAStatus::ok();
161}
162
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000163std::vector<AudioDevice> Module::findConnectedDevices(int32_t portConfigId) {
164 std::vector<AudioDevice> result;
165 auto& ports = getConfig().ports;
166 auto portIds = portIdsFromPortConfigIds(findConnectedPortConfigIds(portConfigId));
167 for (auto it = portIds.begin(); it != portIds.end(); ++it) {
168 auto portIt = findById<AudioPort>(ports, *it);
169 if (portIt != ports.end() && portIt->ext.getTag() == AudioPortExt::Tag::device) {
170 result.push_back(portIt->ext.template get<AudioPortExt::Tag::device>().device);
171 }
172 }
173 return result;
174}
175
176std::set<int32_t> Module::findConnectedPortConfigIds(int32_t portConfigId) {
177 std::set<int32_t> result;
178 auto patchIdsRange = mPatches.equal_range(portConfigId);
179 auto& patches = getConfig().patches;
180 for (auto it = patchIdsRange.first; it != patchIdsRange.second; ++it) {
181 auto patchIt = findById<AudioPatch>(patches, it->second);
182 if (patchIt == patches.end()) {
183 LOG(FATAL) << __func__ << ": patch with id " << it->second << " taken from mPatches "
184 << "not found in the configuration";
185 }
186 if (std::find(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end(),
187 portConfigId) != patchIt->sourcePortConfigIds.end()) {
188 result.insert(patchIt->sinkPortConfigIds.begin(), patchIt->sinkPortConfigIds.end());
189 } else {
190 result.insert(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end());
191 }
192 }
193 return result;
194}
195
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000196ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) {
197 auto& configs = getConfig().portConfigs;
198 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
199 if (portConfigIt == configs.end()) {
200 LOG(ERROR) << __func__ << ": existing port config id " << in_portConfigId << " not found";
201 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
202 }
203 const int32_t portId = portConfigIt->portId;
204 // In our implementation, configs of mix ports always have unique IDs.
205 CHECK(portId != in_portConfigId);
206 auto& ports = getConfig().ports;
207 auto portIt = findById<AudioPort>(ports, portId);
208 if (portIt == ports.end()) {
209 LOG(ERROR) << __func__ << ": port id " << portId << " used by port config id "
210 << in_portConfigId << " not found";
211 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
212 }
213 if (mStreams.count(in_portConfigId) != 0) {
214 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
215 << " already has a stream opened on it";
216 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
217 }
218 if (portIt->ext.getTag() != AudioPortExt::Tag::mix) {
219 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
220 << " does not correspond to a mix port";
221 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
222 }
223 const int32_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
224 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
225 LOG(ERROR) << __func__ << ": port id " << portId
226 << " has already reached maximum allowed opened stream count: "
227 << maxOpenStreamCount;
228 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
229 }
230 *port = &(*portIt);
231 return ndk::ScopedAStatus::ok();
232}
233
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000234template <typename C>
235std::set<int32_t> Module::portIdsFromPortConfigIds(C portConfigIds) {
236 std::set<int32_t> result;
237 auto& portConfigs = getConfig().portConfigs;
238 for (auto it = portConfigIds.begin(); it != portConfigIds.end(); ++it) {
239 auto portConfigIt = findById<AudioPortConfig>(portConfigs, *it);
240 if (portConfigIt != portConfigs.end()) {
241 result.insert(portConfigIt->portId);
242 }
243 }
244 return result;
245}
246
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000247internal::Configuration& Module::getConfig() {
248 if (!mConfig) {
Mikhail Naganovc8e43122022-12-09 00:33:47 +0000249 switch (mType) {
250 case Type::DEFAULT:
251 mConfig = std::move(internal::getPrimaryConfiguration());
252 break;
253 case Type::R_SUBMIX:
254 mConfig = std::move(internal::getRSubmixConfiguration());
255 break;
256 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000257 }
258 return *mConfig;
259}
260
261void Module::registerPatch(const AudioPatch& patch) {
262 auto& configs = getConfig().portConfigs;
263 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
264 for (auto portConfigId : portConfigIds) {
265 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
266 if (configIt != configs.end()) {
267 mPatches.insert(std::pair{portConfigId, patch.id});
268 if (configIt->portId != portConfigId) {
269 mPatches.insert(std::pair{configIt->portId, patch.id});
270 }
271 }
272 };
273 };
274 do_insert(patch.sourcePortConfigIds);
275 do_insert(patch.sinkPortConfigIds);
276}
277
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000278void Module::updateStreamsConnectedState(const AudioPatch& oldPatch, const AudioPatch& newPatch) {
279 // Streams from the old patch need to be disconnected, streams from the new
280 // patch need to be connected. If the stream belongs to both patches, no need
281 // to update it.
282 std::set<int32_t> idsToDisconnect, idsToConnect;
283 idsToDisconnect.insert(oldPatch.sourcePortConfigIds.begin(),
284 oldPatch.sourcePortConfigIds.end());
285 idsToDisconnect.insert(oldPatch.sinkPortConfigIds.begin(), oldPatch.sinkPortConfigIds.end());
286 idsToConnect.insert(newPatch.sourcePortConfigIds.begin(), newPatch.sourcePortConfigIds.end());
287 idsToConnect.insert(newPatch.sinkPortConfigIds.begin(), newPatch.sinkPortConfigIds.end());
288 std::for_each(idsToDisconnect.begin(), idsToDisconnect.end(), [&](const auto& portConfigId) {
289 if (idsToConnect.count(portConfigId) == 0) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000290 LOG(DEBUG) << "The stream on port config id " << portConfigId << " is not connected";
291 mStreams.setStreamIsConnected(portConfigId, {});
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000292 }
293 });
294 std::for_each(idsToConnect.begin(), idsToConnect.end(), [&](const auto& portConfigId) {
295 if (idsToDisconnect.count(portConfigId) == 0) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000296 const auto connectedDevices = findConnectedDevices(portConfigId);
297 LOG(DEBUG) << "The stream on port config id " << portConfigId
298 << " is connected to: " << ::android::internal::ToString(connectedDevices);
299 mStreams.setStreamIsConnected(portConfigId, connectedDevices);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000300 }
301 });
302}
303
Mikhail Naganov00603d12022-05-02 22:52:13 +0000304ndk::ScopedAStatus Module::setModuleDebug(
305 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
306 LOG(DEBUG) << __func__ << ": old flags:" << mDebug.toString()
307 << ", new flags: " << in_debug.toString();
308 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
309 !mConnectedDevicePorts.empty()) {
310 LOG(ERROR) << __func__ << ": attempting to change device connections simulation "
311 << "while having external devices connected";
312 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
313 }
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000314 if (in_debug.streamTransientStateDelayMs < 0) {
315 LOG(ERROR) << __func__ << ": streamTransientStateDelayMs is negative: "
316 << in_debug.streamTransientStateDelayMs;
317 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
318 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000319 mDebug = in_debug;
320 return ndk::ScopedAStatus::ok();
321}
322
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000323ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
324 if (mTelephony == nullptr) {
325 mTelephony = ndk::SharedRefBase::make<Telephony>();
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000326 mTelephonyBinder = mTelephony->asBinder();
327 AIBinder_setMinSchedulerPolicy(mTelephonyBinder.get(), SCHED_NORMAL,
Shunkai Yao39bf2c32022-12-06 03:25:59 +0000328 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000329 }
330 *_aidl_return = mTelephony;
331 LOG(DEBUG) << __func__ << ": returning instance of ITelephony: " << _aidl_return->get();
332 return ndk::ScopedAStatus::ok();
333}
334
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000335ndk::ScopedAStatus Module::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
336 if (mBluetooth == nullptr) {
337 mBluetooth = ndk::SharedRefBase::make<Bluetooth>();
338 mBluetoothBinder = mBluetooth->asBinder();
339 AIBinder_setMinSchedulerPolicy(mBluetoothBinder.get(), SCHED_NORMAL,
340 ANDROID_PRIORITY_AUDIO);
341 }
342 *_aidl_return = mBluetooth;
343 LOG(DEBUG) << __func__ << ": returning instance of IBluetooth: " << _aidl_return->get();
344 return ndk::ScopedAStatus::ok();
345}
346
Mikhail Naganov00603d12022-05-02 22:52:13 +0000347ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
348 AudioPort* _aidl_return) {
349 const int32_t templateId = in_templateIdAndAdditionalData.id;
350 auto& ports = getConfig().ports;
351 AudioPort connectedPort;
352 { // Scope the template port so that we don't accidentally modify it.
353 auto templateIt = findById<AudioPort>(ports, templateId);
354 if (templateIt == ports.end()) {
355 LOG(ERROR) << __func__ << ": port id " << templateId << " not found";
356 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
357 }
358 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
359 LOG(ERROR) << __func__ << ": port id " << templateId << " is not a device port";
360 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
361 }
362 if (!templateIt->profiles.empty()) {
363 LOG(ERROR) << __func__ << ": port id " << templateId
364 << " does not have dynamic profiles";
365 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
366 }
367 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
368 if (templateDevicePort.device.type.connection.empty()) {
369 LOG(ERROR) << __func__ << ": port id " << templateId << " is permanently attached";
370 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
371 }
372 // Postpone id allocation until we ensure that there are no client errors.
373 connectedPort = *templateIt;
374 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
375 const auto& inputDevicePort =
376 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
377 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
378 connectedDevicePort.device.address = inputDevicePort.device.address;
379 LOG(DEBUG) << __func__ << ": device port " << connectedPort.id << " device set to "
380 << connectedDevicePort.device.toString();
381 // Check if there is already a connected port with for the same external device.
382 for (auto connectedPortId : mConnectedDevicePorts) {
383 auto connectedPortIt = findById<AudioPort>(ports, connectedPortId);
384 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
385 connectedDevicePort.device) {
386 LOG(ERROR) << __func__ << ": device " << connectedDevicePort.device.toString()
387 << " is already connected at the device port id " << connectedPortId;
388 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
389 }
390 }
391 }
392
393 if (!mDebug.simulateDeviceConnections) {
394 // In a real HAL here we would attempt querying the profiles from the device.
395 LOG(ERROR) << __func__ << ": failed to query supported device profiles";
396 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
397 }
398
399 connectedPort.id = ++getConfig().nextPortId;
400 mConnectedDevicePorts.insert(connectedPort.id);
401 LOG(DEBUG) << __func__ << ": template port " << templateId << " external device connected, "
402 << "connected port ID " << connectedPort.id;
403 auto& connectedProfiles = getConfig().connectedProfiles;
404 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
405 connectedProfilesIt != connectedProfiles.end()) {
406 connectedPort.profiles = connectedProfilesIt->second;
407 }
408 ports.push_back(connectedPort);
409 *_aidl_return = std::move(connectedPort);
410
411 std::vector<AudioRoute> newRoutes;
412 auto& routes = getConfig().routes;
413 for (auto& r : routes) {
414 if (r.sinkPortId == templateId) {
415 AudioRoute newRoute;
416 newRoute.sourcePortIds = r.sourcePortIds;
417 newRoute.sinkPortId = connectedPort.id;
418 newRoute.isExclusive = r.isExclusive;
419 newRoutes.push_back(std::move(newRoute));
420 } else {
421 auto& srcs = r.sourcePortIds;
422 if (std::find(srcs.begin(), srcs.end(), templateId) != srcs.end()) {
423 srcs.push_back(connectedPort.id);
424 }
425 }
426 }
427 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
428
429 return ndk::ScopedAStatus::ok();
430}
431
432ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
433 auto& ports = getConfig().ports;
434 auto portIt = findById<AudioPort>(ports, in_portId);
435 if (portIt == ports.end()) {
436 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
437 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
438 }
439 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
440 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a device port";
441 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
442 }
443 if (mConnectedDevicePorts.count(in_portId) == 0) {
444 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a connected device port";
445 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
446 }
447 auto& configs = getConfig().portConfigs;
448 auto& initials = getConfig().initialConfigs;
449 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
450 if (config.portId == in_portId) {
451 // Check if the configuration was provided by the client.
452 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
453 return initialIt == initials.end() || config != *initialIt;
454 }
455 return false;
456 });
457 if (configIt != configs.end()) {
458 LOG(ERROR) << __func__ << ": port id " << in_portId << " has a non-default config with id "
459 << configIt->id;
460 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
461 }
462 ports.erase(portIt);
463 mConnectedDevicePorts.erase(in_portId);
464 LOG(DEBUG) << __func__ << ": connected device port " << in_portId << " released";
465
466 auto& routes = getConfig().routes;
467 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
468 if (routesIt->sinkPortId == in_portId) {
469 routesIt = routes.erase(routesIt);
470 } else {
471 // Note: the list of sourcePortIds can't become empty because there must
472 // be the id of the template port in the route.
473 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
474 ++routesIt;
475 }
476 }
477
478 return ndk::ScopedAStatus::ok();
479}
480
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000481ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
482 *_aidl_return = getConfig().patches;
483 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " patches";
484 return ndk::ScopedAStatus::ok();
485}
486
487ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
488 auto& ports = getConfig().ports;
489 auto portIt = findById<AudioPort>(ports, in_portId);
490 if (portIt != ports.end()) {
491 *_aidl_return = *portIt;
492 LOG(DEBUG) << __func__ << ": returning port by id " << in_portId;
493 return ndk::ScopedAStatus::ok();
494 }
495 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
496 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
497}
498
499ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
500 *_aidl_return = getConfig().portConfigs;
501 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " port configs";
502 return ndk::ScopedAStatus::ok();
503}
504
505ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
506 *_aidl_return = getConfig().ports;
507 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " ports";
508 return ndk::ScopedAStatus::ok();
509}
510
511ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
512 *_aidl_return = getConfig().routes;
513 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " routes";
514 return ndk::ScopedAStatus::ok();
515}
516
Mikhail Naganov00603d12022-05-02 22:52:13 +0000517ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
518 std::vector<AudioRoute>* _aidl_return) {
519 auto& ports = getConfig().ports;
520 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
521 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
522 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
523 }
524 auto& routes = getConfig().routes;
525 std::copy_if(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
526 [&](const auto& r) {
527 const auto& srcs = r.sourcePortIds;
528 return r.sinkPortId == in_portId ||
529 std::find(srcs.begin(), srcs.end(), in_portId) != srcs.end();
530 });
531 return ndk::ScopedAStatus::ok();
532}
533
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000534ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
535 OpenInputStreamReturn* _aidl_return) {
536 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", buffer size "
537 << in_args.bufferSizeFrames << " frames";
538 AudioPort* port = nullptr;
539 if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
540 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000541 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000542 if (port->flags.getTag() != AudioIoFlags::Tag::input) {
543 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000544 << " does not correspond to an input mix port";
545 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
546 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000547 StreamContext context;
Mikhail Naganov30301a42022-09-13 01:20:45 +0000548 if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames, nullptr,
Mikhail Naganov8651b362023-01-06 23:15:27 +0000549 nullptr, &context);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000550 !status.isOk()) {
551 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000552 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000553 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000554 std::shared_ptr<StreamIn> stream;
555 if (auto status = StreamIn::createInstance(in_args.sinkMetadata, std::move(context),
556 mConfig->microphones, &stream);
557 !status.isOk()) {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000558 return status;
559 }
560 StreamWrapper streamWrapper(stream);
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000561 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
562 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000563 auto patchIt = mPatches.find(in_args.portConfigId);
564 if (patchIt != mPatches.end()) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000565 streamWrapper.setStreamIsConnected(findConnectedDevices(in_args.portConfigId));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000566 }
567 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000568 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000569 return ndk::ScopedAStatus::ok();
570}
571
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000572ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
573 OpenOutputStreamReturn* _aidl_return) {
574 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", has offload info? "
575 << (in_args.offloadInfo.has_value()) << ", buffer size " << in_args.bufferSizeFrames
576 << " frames";
577 AudioPort* port = nullptr;
578 if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
579 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000580 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000581 if (port->flags.getTag() != AudioIoFlags::Tag::output) {
582 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000583 << " does not correspond to an output mix port";
584 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
585 }
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000586 const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
587 AudioOutputFlags::COMPRESS_OFFLOAD);
588 if (isOffload && !in_args.offloadInfo.has_value()) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000589 LOG(ERROR) << __func__ << ": port id " << port->id
Mikhail Naganov111e0ce2022-06-17 21:41:19 +0000590 << " has COMPRESS_OFFLOAD flag set, requires offload info";
591 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
592 }
Mikhail Naganov30301a42022-09-13 01:20:45 +0000593 const bool isNonBlocking = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
594 AudioOutputFlags::NON_BLOCKING);
595 if (isNonBlocking && in_args.callback == nullptr) {
596 LOG(ERROR) << __func__ << ": port id " << port->id
597 << " has NON_BLOCKING flag set, requires async callback";
598 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
599 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000600 StreamContext context;
Mikhail Naganov30301a42022-09-13 01:20:45 +0000601 if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
Mikhail Naganov8651b362023-01-06 23:15:27 +0000602 isNonBlocking ? in_args.callback : nullptr,
603 in_args.eventCallback, &context);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000604 !status.isOk()) {
605 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000606 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000607 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000608 std::shared_ptr<StreamOut> stream;
609 if (auto status = StreamOut::createInstance(in_args.sourceMetadata, std::move(context),
610 in_args.offloadInfo, &stream);
611 !status.isOk()) {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000612 return status;
613 }
614 StreamWrapper streamWrapper(stream);
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000615 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
616 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000617 auto patchIt = mPatches.find(in_args.portConfigId);
618 if (patchIt != mPatches.end()) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000619 streamWrapper.setStreamIsConnected(findConnectedDevices(in_args.portConfigId));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000620 }
621 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000622 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000623 return ndk::ScopedAStatus::ok();
624}
625
Mikhail Naganov74927202022-12-19 16:37:14 +0000626ndk::ScopedAStatus Module::getSupportedPlaybackRateFactors(
627 SupportedPlaybackRateFactors* _aidl_return) {
628 LOG(DEBUG) << __func__;
629 (void)_aidl_return;
630 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
631}
632
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000633ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
Mikhail Naganov16db9b72022-06-17 21:36:18 +0000634 LOG(DEBUG) << __func__ << ": requested patch " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000635 if (in_requested.sourcePortConfigIds.empty()) {
636 LOG(ERROR) << __func__ << ": requested patch has empty sources list";
637 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
638 }
639 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
640 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sources list";
641 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
642 }
643 if (in_requested.sinkPortConfigIds.empty()) {
644 LOG(ERROR) << __func__ << ": requested patch has empty sinks list";
645 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
646 }
647 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
648 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sinks list";
649 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
650 }
651
652 auto& configs = getConfig().portConfigs;
653 std::vector<int32_t> missingIds;
654 auto sources =
655 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
656 if (!missingIds.empty()) {
657 LOG(ERROR) << __func__ << ": following source port config ids not found: "
658 << ::android::internal::ToString(missingIds);
659 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
660 }
661 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
662 if (!missingIds.empty()) {
663 LOG(ERROR) << __func__ << ": following sink port config ids not found: "
664 << ::android::internal::ToString(missingIds);
665 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
666 }
667 // bool indicates whether a non-exclusive route is available.
668 // If only an exclusive route is available, that means the patch can not be
669 // established if there is any other patch which currently uses the sink port.
670 std::map<int32_t, bool> allowedSinkPorts;
671 auto& routes = getConfig().routes;
672 for (auto src : sources) {
673 for (const auto& r : routes) {
674 const auto& srcs = r.sourcePortIds;
675 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
676 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
677 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
678 }
679 }
680 }
681 }
682 for (auto sink : sinks) {
683 if (allowedSinkPorts.count(sink->portId) == 0) {
684 LOG(ERROR) << __func__ << ": there is no route to the sink port id " << sink->portId;
685 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
686 }
687 }
688
689 auto& patches = getConfig().patches;
690 auto existing = patches.end();
691 std::optional<decltype(mPatches)> patchesBackup;
692 if (in_requested.id != 0) {
693 existing = findById<AudioPatch>(patches, in_requested.id);
694 if (existing != patches.end()) {
695 patchesBackup = mPatches;
696 cleanUpPatch(existing->id);
697 } else {
698 LOG(ERROR) << __func__ << ": not found existing patch id " << in_requested.id;
699 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
700 }
701 }
702 // Validate the requested patch.
703 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
704 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
705 LOG(ERROR) << __func__ << ": sink port id " << sinkPortId
706 << "is exclusive and is already used by some other patch";
707 if (patchesBackup.has_value()) {
708 mPatches = std::move(*patchesBackup);
709 }
710 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
711 }
712 }
713 *_aidl_return = in_requested;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000714 _aidl_return->minimumStreamBufferSizeFrames = kMinimumStreamBufferSizeFrames;
715 _aidl_return->latenciesMs.clear();
716 _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
717 _aidl_return->sinkPortConfigIds.size(), kLatencyMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000718 AudioPatch oldPatch{};
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000719 if (existing == patches.end()) {
720 _aidl_return->id = getConfig().nextPatchId++;
721 patches.push_back(*_aidl_return);
722 existing = patches.begin() + (patches.size() - 1);
723 } else {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000724 oldPatch = *existing;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000725 *existing = *_aidl_return;
726 }
727 registerPatch(*existing);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000728 updateStreamsConnectedState(oldPatch, *_aidl_return);
729
730 LOG(DEBUG) << __func__ << ": " << (oldPatch.id == 0 ? "created" : "updated") << " patch "
731 << _aidl_return->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000732 return ndk::ScopedAStatus::ok();
733}
734
735ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
736 AudioPortConfig* out_suggested, bool* _aidl_return) {
737 LOG(DEBUG) << __func__ << ": requested " << in_requested.toString();
738 auto& configs = getConfig().portConfigs;
739 auto existing = configs.end();
740 if (in_requested.id != 0) {
741 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
742 existing == configs.end()) {
743 LOG(ERROR) << __func__ << ": existing port config id " << in_requested.id
744 << " not found";
745 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
746 }
747 }
748
749 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
750 if (portId == 0) {
751 LOG(ERROR) << __func__ << ": input port config does not specify portId";
752 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
753 }
754 auto& ports = getConfig().ports;
755 auto portIt = findById<AudioPort>(ports, portId);
756 if (portIt == ports.end()) {
757 LOG(ERROR) << __func__ << ": input port config points to non-existent portId " << portId;
758 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
759 }
760 if (existing != configs.end()) {
761 *out_suggested = *existing;
762 } else {
763 AudioPortConfig newConfig;
764 if (generateDefaultPortConfig(*portIt, &newConfig)) {
765 *out_suggested = newConfig;
766 } else {
767 LOG(ERROR) << __func__ << ": unable generate a default config for port " << portId;
768 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
769 }
770 }
771 // From this moment, 'out_suggested' is either an existing port config,
772 // or a new generated config. Now attempt to update it according to the specified
773 // fields of 'in_requested'.
774
775 bool requestedIsValid = true, requestedIsFullySpecified = true;
776
777 AudioIoFlags portFlags = portIt->flags;
778 if (in_requested.flags.has_value()) {
779 if (in_requested.flags.value() != portFlags) {
780 LOG(WARNING) << __func__ << ": requested flags "
781 << in_requested.flags.value().toString() << " do not match port's "
782 << portId << " flags " << portFlags.toString();
783 requestedIsValid = false;
784 }
785 } else {
786 requestedIsFullySpecified = false;
787 }
788
789 AudioProfile portProfile;
790 if (in_requested.format.has_value()) {
791 const auto& format = in_requested.format.value();
792 if (findAudioProfile(*portIt, format, &portProfile)) {
793 out_suggested->format = format;
794 } else {
795 LOG(WARNING) << __func__ << ": requested format " << format.toString()
796 << " is not found in port's " << portId << " profiles";
797 requestedIsValid = false;
798 }
799 } else {
800 requestedIsFullySpecified = false;
801 }
802 if (!findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
803 LOG(ERROR) << __func__ << ": port " << portId << " does not support format "
804 << out_suggested->format.value().toString() << " anymore";
805 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
806 }
807
808 if (in_requested.channelMask.has_value()) {
809 const auto& channelMask = in_requested.channelMask.value();
810 if (find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
811 portProfile.channelMasks.end()) {
812 out_suggested->channelMask = channelMask;
813 } else {
814 LOG(WARNING) << __func__ << ": requested channel mask " << channelMask.toString()
815 << " is not supported for the format " << portProfile.format.toString()
816 << " by the port " << portId;
817 requestedIsValid = false;
818 }
819 } else {
820 requestedIsFullySpecified = false;
821 }
822
823 if (in_requested.sampleRate.has_value()) {
824 const auto& sampleRate = in_requested.sampleRate.value();
825 if (find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
826 sampleRate.value) != portProfile.sampleRates.end()) {
827 out_suggested->sampleRate = sampleRate;
828 } else {
829 LOG(WARNING) << __func__ << ": requested sample rate " << sampleRate.value
830 << " is not supported for the format " << portProfile.format.toString()
831 << " by the port " << portId;
832 requestedIsValid = false;
833 }
834 } else {
835 requestedIsFullySpecified = false;
836 }
837
838 if (in_requested.gain.has_value()) {
839 // Let's pretend that gain can always be applied.
840 out_suggested->gain = in_requested.gain.value();
841 }
842
843 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
844 out_suggested->id = getConfig().nextPortId++;
845 configs.push_back(*out_suggested);
846 *_aidl_return = true;
847 LOG(DEBUG) << __func__ << ": created new port config " << out_suggested->toString();
848 } else if (existing != configs.end() && requestedIsValid) {
849 *existing = *out_suggested;
850 *_aidl_return = true;
851 LOG(DEBUG) << __func__ << ": updated port config " << out_suggested->toString();
852 } else {
853 LOG(DEBUG) << __func__ << ": not applied; existing config ? " << (existing != configs.end())
854 << "; requested is valid? " << requestedIsValid << ", fully specified? "
855 << requestedIsFullySpecified;
856 *_aidl_return = false;
857 }
858 return ndk::ScopedAStatus::ok();
859}
860
861ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
862 auto& patches = getConfig().patches;
863 auto patchIt = findById<AudioPatch>(patches, in_patchId);
864 if (patchIt != patches.end()) {
865 cleanUpPatch(patchIt->id);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000866 updateStreamsConnectedState(*patchIt, AudioPatch{});
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000867 patches.erase(patchIt);
868 LOG(DEBUG) << __func__ << ": erased patch " << in_patchId;
869 return ndk::ScopedAStatus::ok();
870 }
871 LOG(ERROR) << __func__ << ": patch id " << in_patchId << " not found";
872 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
873}
874
875ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
876 auto& configs = getConfig().portConfigs;
877 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
878 if (configIt != configs.end()) {
879 if (mStreams.count(in_portConfigId) != 0) {
880 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
881 << " has a stream opened on it";
882 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
883 }
884 auto patchIt = mPatches.find(in_portConfigId);
885 if (patchIt != mPatches.end()) {
886 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
887 << " is used by the patch with id " << patchIt->second;
888 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
889 }
890 auto& initials = getConfig().initialConfigs;
891 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
892 if (initialIt == initials.end()) {
893 configs.erase(configIt);
894 LOG(DEBUG) << __func__ << ": erased port config " << in_portConfigId;
895 } else if (*configIt != *initialIt) {
896 *configIt = *initialIt;
897 LOG(DEBUG) << __func__ << ": reset port config " << in_portConfigId;
898 }
899 return ndk::ScopedAStatus::ok();
900 }
901 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId << " not found";
902 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
903}
904
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000905ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) {
906 *_aidl_return = mMasterMute;
907 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
908 return ndk::ScopedAStatus::ok();
909}
910
911ndk::ScopedAStatus Module::setMasterMute(bool in_mute) {
912 LOG(DEBUG) << __func__ << ": " << in_mute;
913 mMasterMute = in_mute;
914 return ndk::ScopedAStatus::ok();
915}
916
917ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) {
918 *_aidl_return = mMasterVolume;
919 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
920 return ndk::ScopedAStatus::ok();
921}
922
923ndk::ScopedAStatus Module::setMasterVolume(float in_volume) {
924 LOG(DEBUG) << __func__ << ": " << in_volume;
925 if (in_volume >= 0.0f && in_volume <= 1.0f) {
926 mMasterVolume = in_volume;
927 return ndk::ScopedAStatus::ok();
928 }
929 LOG(ERROR) << __func__ << ": invalid master volume value: " << in_volume;
930 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
931}
932
933ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) {
934 *_aidl_return = mMicMute;
935 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
936 return ndk::ScopedAStatus::ok();
937}
938
939ndk::ScopedAStatus Module::setMicMute(bool in_mute) {
940 LOG(DEBUG) << __func__ << ": " << in_mute;
941 mMicMute = in_mute;
942 return ndk::ScopedAStatus::ok();
943}
944
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000945ndk::ScopedAStatus Module::getMicrophones(std::vector<MicrophoneInfo>* _aidl_return) {
946 *_aidl_return = mConfig->microphones;
947 LOG(DEBUG) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return);
948 return ndk::ScopedAStatus::ok();
949}
950
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000951ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) {
952 // No checks for supported audio modes here, it's an informative notification.
953 LOG(DEBUG) << __func__ << ": " << toString(in_mode);
954 return ndk::ScopedAStatus::ok();
955}
956
957ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) {
958 LOG(DEBUG) << __func__ << ": " << toString(in_rotation);
959 return ndk::ScopedAStatus::ok();
960}
961
962ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) {
963 LOG(DEBUG) << __func__ << ": " << in_isTurnedOn;
964 return ndk::ScopedAStatus::ok();
965}
966
Vlad Popa83a6d822022-11-07 13:53:57 +0100967ndk::ScopedAStatus Module::getSoundDose(std::shared_ptr<ISoundDose>* _aidl_return) {
Vlad Popa943b7e22022-12-08 14:24:12 +0100968 if (mSoundDose == nullptr) {
Vlad Popa2afbd1e2022-12-28 17:04:58 +0100969 mSoundDose = ndk::SharedRefBase::make<sounddose::SoundDose>();
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000970 mSoundDoseBinder = mSoundDose->asBinder();
971 AIBinder_setMinSchedulerPolicy(mSoundDoseBinder.get(), SCHED_NORMAL,
972 ANDROID_PRIORITY_AUDIO);
Vlad Popa943b7e22022-12-08 14:24:12 +0100973 }
974 *_aidl_return = mSoundDose;
975 LOG(DEBUG) << __func__ << ": returning instance of ISoundDose: " << _aidl_return->get();
Vlad Popa83a6d822022-11-07 13:53:57 +0100976 return ndk::ScopedAStatus::ok();
977}
978
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000979ndk::ScopedAStatus Module::generateHwAvSyncId(int32_t* _aidl_return) {
980 LOG(DEBUG) << __func__;
981 (void)_aidl_return;
982 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
983}
984
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000985const std::string Module::VendorDebug::kForceTransientBurstName = "aosp.forceTransientBurst";
Mikhail Naganov194daaa2023-01-05 22:34:20 +0000986const std::string Module::VendorDebug::kForceSynchronousDrainName = "aosp.forceSynchronousDrain";
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000987
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000988ndk::ScopedAStatus Module::getVendorParameters(const std::vector<std::string>& in_ids,
989 std::vector<VendorParameter>* _aidl_return) {
990 LOG(DEBUG) << __func__ << ": id count: " << in_ids.size();
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000991 bool allParametersKnown = true;
992 for (const auto& id : in_ids) {
993 if (id == VendorDebug::kForceTransientBurstName) {
994 VendorParameter forceTransientBurst{.id = id};
995 forceTransientBurst.ext.setParcelable(Boolean{mVendorDebug.forceTransientBurst});
996 _aidl_return->push_back(std::move(forceTransientBurst));
Mikhail Naganov194daaa2023-01-05 22:34:20 +0000997 } else if (id == VendorDebug::kForceSynchronousDrainName) {
998 VendorParameter forceSynchronousDrain{.id = id};
999 forceSynchronousDrain.ext.setParcelable(Boolean{mVendorDebug.forceSynchronousDrain});
1000 _aidl_return->push_back(std::move(forceSynchronousDrain));
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001001 } else {
1002 allParametersKnown = false;
1003 LOG(ERROR) << __func__ << ": unrecognized parameter \"" << id << "\"";
1004 }
1005 }
1006 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1007 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001008}
1009
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001010namespace {
1011
1012template <typename W>
1013bool extractParameter(const VendorParameter& p, decltype(W::value)* v) {
1014 std::optional<W> value;
1015 binder_status_t result = p.ext.getParcelable(&value);
1016 if (result == STATUS_OK && value.has_value()) {
1017 *v = value.value().value;
1018 return true;
1019 }
1020 LOG(ERROR) << __func__ << ": failed to read the value of the parameter \"" << p.id
1021 << "\": " << result;
1022 return false;
1023}
1024
1025} // namespace
1026
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001027ndk::ScopedAStatus Module::setVendorParameters(const std::vector<VendorParameter>& in_parameters,
1028 bool in_async) {
1029 LOG(DEBUG) << __func__ << ": parameter count " << in_parameters.size()
1030 << ", async: " << in_async;
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001031 bool allParametersKnown = true;
1032 for (const auto& p : in_parameters) {
1033 if (p.id == VendorDebug::kForceTransientBurstName) {
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001034 if (!extractParameter<Boolean>(p, &mVendorDebug.forceTransientBurst)) {
1035 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1036 }
1037 } else if (p.id == VendorDebug::kForceSynchronousDrainName) {
1038 if (!extractParameter<Boolean>(p, &mVendorDebug.forceSynchronousDrain)) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001039 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1040 }
1041 } else {
1042 allParametersKnown = false;
1043 LOG(ERROR) << __func__ << ": unrecognized parameter \"" << p.id << "\"";
1044 }
1045 }
1046 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1047 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001048}
1049
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001050ndk::ScopedAStatus Module::addDeviceEffect(
1051 int32_t in_portConfigId,
1052 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1053 if (in_effect == nullptr) {
1054 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect";
1055 } else {
1056 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder "
1057 << in_effect->asBinder().get();
1058 }
1059 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1060}
1061
1062ndk::ScopedAStatus Module::removeDeviceEffect(
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
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001074} // namespace aidl::android::hardware::audio::core