blob: 13b04cd61ba747a0e43395c89394ef553fbe77f7 [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 Naganov4f5d3f12022-07-22 23:23:25 +0000105ndk::ScopedAStatus Module::createStreamContext(int32_t in_portConfigId, int64_t in_bufferSizeFrames,
Mikhail Naganov30301a42022-09-13 01:20:45 +0000106 std::shared_ptr<IStreamCallback> asyncCallback,
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000107 StreamContext* out_context) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000108 if (in_bufferSizeFrames <= 0) {
109 LOG(ERROR) << __func__ << ": non-positive buffer size " << in_bufferSizeFrames;
110 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
111 }
112 if (in_bufferSizeFrames < kMinimumStreamBufferSizeFrames) {
113 LOG(ERROR) << __func__ << ": insufficient buffer size " << in_bufferSizeFrames
114 << ", must be at least " << kMinimumStreamBufferSizeFrames;
115 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
116 }
117 auto& configs = getConfig().portConfigs;
118 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000119 // Since this is a private method, it is assumed that
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000120 // validity of the portConfigId has already been checked.
121 const size_t frameSize =
122 getFrameSizeInBytes(portConfigIt->format.value(), portConfigIt->channelMask.value());
123 if (frameSize == 0) {
124 LOG(ERROR) << __func__ << ": could not calculate frame size for port config "
125 << portConfigIt->toString();
126 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
127 }
128 LOG(DEBUG) << __func__ << ": frame size " << frameSize << " bytes";
129 if (frameSize > kMaximumStreamBufferSizeBytes / in_bufferSizeFrames) {
130 LOG(ERROR) << __func__ << ": buffer size " << in_bufferSizeFrames
131 << " frames is too large, maximum size is "
132 << kMaximumStreamBufferSizeBytes / frameSize;
133 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
134 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000135 const auto& flags = portConfigIt->flags.value();
136 if ((flags.getTag() == AudioIoFlags::Tag::input &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000137 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::input>(),
138 AudioInputFlags::MMAP_NOIRQ)) ||
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000139 (flags.getTag() == AudioIoFlags::Tag::output &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000140 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::output>(),
141 AudioOutputFlags::MMAP_NOIRQ))) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000142 StreamContext::DebugParameters params{mDebug.streamTransientStateDelayMs,
Mikhail Naganov194daaa2023-01-05 22:34:20 +0000143 mVendorDebug.forceTransientBurst,
144 mVendorDebug.forceSynchronousDrain};
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000145 StreamContext temp(
146 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
147 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000148 portConfigIt->format.value(), portConfigIt->channelMask.value(),
149 std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames),
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000150 asyncCallback, params);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000151 if (temp.isValid()) {
152 *out_context = std::move(temp);
153 } else {
154 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
155 }
156 } else {
157 // TODO: Implement simulation of MMAP buffer allocation
158 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000159 return ndk::ScopedAStatus::ok();
160}
161
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000162std::vector<AudioDevice> Module::findConnectedDevices(int32_t portConfigId) {
163 std::vector<AudioDevice> result;
164 auto& ports = getConfig().ports;
165 auto portIds = portIdsFromPortConfigIds(findConnectedPortConfigIds(portConfigId));
166 for (auto it = portIds.begin(); it != portIds.end(); ++it) {
167 auto portIt = findById<AudioPort>(ports, *it);
168 if (portIt != ports.end() && portIt->ext.getTag() == AudioPortExt::Tag::device) {
169 result.push_back(portIt->ext.template get<AudioPortExt::Tag::device>().device);
170 }
171 }
172 return result;
173}
174
175std::set<int32_t> Module::findConnectedPortConfigIds(int32_t portConfigId) {
176 std::set<int32_t> result;
177 auto patchIdsRange = mPatches.equal_range(portConfigId);
178 auto& patches = getConfig().patches;
179 for (auto it = patchIdsRange.first; it != patchIdsRange.second; ++it) {
180 auto patchIt = findById<AudioPatch>(patches, it->second);
181 if (patchIt == patches.end()) {
182 LOG(FATAL) << __func__ << ": patch with id " << it->second << " taken from mPatches "
183 << "not found in the configuration";
184 }
185 if (std::find(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end(),
186 portConfigId) != patchIt->sourcePortConfigIds.end()) {
187 result.insert(patchIt->sinkPortConfigIds.begin(), patchIt->sinkPortConfigIds.end());
188 } else {
189 result.insert(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end());
190 }
191 }
192 return result;
193}
194
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000195ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) {
196 auto& configs = getConfig().portConfigs;
197 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
198 if (portConfigIt == configs.end()) {
199 LOG(ERROR) << __func__ << ": existing port config id " << in_portConfigId << " not found";
200 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
201 }
202 const int32_t portId = portConfigIt->portId;
203 // In our implementation, configs of mix ports always have unique IDs.
204 CHECK(portId != in_portConfigId);
205 auto& ports = getConfig().ports;
206 auto portIt = findById<AudioPort>(ports, portId);
207 if (portIt == ports.end()) {
208 LOG(ERROR) << __func__ << ": port id " << portId << " used by port config id "
209 << in_portConfigId << " not found";
210 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
211 }
212 if (mStreams.count(in_portConfigId) != 0) {
213 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
214 << " already has a stream opened on it";
215 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
216 }
217 if (portIt->ext.getTag() != AudioPortExt::Tag::mix) {
218 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
219 << " does not correspond to a mix port";
220 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
221 }
222 const int32_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
223 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
224 LOG(ERROR) << __func__ << ": port id " << portId
225 << " has already reached maximum allowed opened stream count: "
226 << maxOpenStreamCount;
227 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
228 }
229 *port = &(*portIt);
230 return ndk::ScopedAStatus::ok();
231}
232
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000233template <typename C>
234std::set<int32_t> Module::portIdsFromPortConfigIds(C portConfigIds) {
235 std::set<int32_t> result;
236 auto& portConfigs = getConfig().portConfigs;
237 for (auto it = portConfigIds.begin(); it != portConfigIds.end(); ++it) {
238 auto portConfigIt = findById<AudioPortConfig>(portConfigs, *it);
239 if (portConfigIt != portConfigs.end()) {
240 result.insert(portConfigIt->portId);
241 }
242 }
243 return result;
244}
245
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000246internal::Configuration& Module::getConfig() {
247 if (!mConfig) {
Mikhail Naganovc8e43122022-12-09 00:33:47 +0000248 switch (mType) {
249 case Type::DEFAULT:
250 mConfig = std::move(internal::getPrimaryConfiguration());
251 break;
252 case Type::R_SUBMIX:
253 mConfig = std::move(internal::getRSubmixConfiguration());
254 break;
255 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000256 }
257 return *mConfig;
258}
259
260void Module::registerPatch(const AudioPatch& patch) {
261 auto& configs = getConfig().portConfigs;
262 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
263 for (auto portConfigId : portConfigIds) {
264 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
265 if (configIt != configs.end()) {
266 mPatches.insert(std::pair{portConfigId, patch.id});
267 if (configIt->portId != portConfigId) {
268 mPatches.insert(std::pair{configIt->portId, patch.id});
269 }
270 }
271 };
272 };
273 do_insert(patch.sourcePortConfigIds);
274 do_insert(patch.sinkPortConfigIds);
275}
276
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000277void Module::updateStreamsConnectedState(const AudioPatch& oldPatch, const AudioPatch& newPatch) {
278 // Streams from the old patch need to be disconnected, streams from the new
279 // patch need to be connected. If the stream belongs to both patches, no need
280 // to update it.
281 std::set<int32_t> idsToDisconnect, idsToConnect;
282 idsToDisconnect.insert(oldPatch.sourcePortConfigIds.begin(),
283 oldPatch.sourcePortConfigIds.end());
284 idsToDisconnect.insert(oldPatch.sinkPortConfigIds.begin(), oldPatch.sinkPortConfigIds.end());
285 idsToConnect.insert(newPatch.sourcePortConfigIds.begin(), newPatch.sourcePortConfigIds.end());
286 idsToConnect.insert(newPatch.sinkPortConfigIds.begin(), newPatch.sinkPortConfigIds.end());
287 std::for_each(idsToDisconnect.begin(), idsToDisconnect.end(), [&](const auto& portConfigId) {
288 if (idsToConnect.count(portConfigId) == 0) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000289 LOG(DEBUG) << "The stream on port config id " << portConfigId << " is not connected";
290 mStreams.setStreamIsConnected(portConfigId, {});
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000291 }
292 });
293 std::for_each(idsToConnect.begin(), idsToConnect.end(), [&](const auto& portConfigId) {
294 if (idsToDisconnect.count(portConfigId) == 0) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000295 const auto connectedDevices = findConnectedDevices(portConfigId);
296 LOG(DEBUG) << "The stream on port config id " << portConfigId
297 << " is connected to: " << ::android::internal::ToString(connectedDevices);
298 mStreams.setStreamIsConnected(portConfigId, connectedDevices);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000299 }
300 });
301}
302
Mikhail Naganov00603d12022-05-02 22:52:13 +0000303ndk::ScopedAStatus Module::setModuleDebug(
304 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
305 LOG(DEBUG) << __func__ << ": old flags:" << mDebug.toString()
306 << ", new flags: " << in_debug.toString();
307 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
308 !mConnectedDevicePorts.empty()) {
309 LOG(ERROR) << __func__ << ": attempting to change device connections simulation "
310 << "while having external devices connected";
311 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
312 }
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000313 if (in_debug.streamTransientStateDelayMs < 0) {
314 LOG(ERROR) << __func__ << ": streamTransientStateDelayMs is negative: "
315 << in_debug.streamTransientStateDelayMs;
316 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
317 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000318 mDebug = in_debug;
319 return ndk::ScopedAStatus::ok();
320}
321
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000322ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
323 if (mTelephony == nullptr) {
324 mTelephony = ndk::SharedRefBase::make<Telephony>();
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000325 mTelephonyBinder = mTelephony->asBinder();
326 AIBinder_setMinSchedulerPolicy(mTelephonyBinder.get(), SCHED_NORMAL,
Shunkai Yao39bf2c32022-12-06 03:25:59 +0000327 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000328 }
329 *_aidl_return = mTelephony;
330 LOG(DEBUG) << __func__ << ": returning instance of ITelephony: " << _aidl_return->get();
331 return ndk::ScopedAStatus::ok();
332}
333
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000334ndk::ScopedAStatus Module::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
335 if (mBluetooth == nullptr) {
336 mBluetooth = ndk::SharedRefBase::make<Bluetooth>();
337 mBluetoothBinder = mBluetooth->asBinder();
338 AIBinder_setMinSchedulerPolicy(mBluetoothBinder.get(), SCHED_NORMAL,
339 ANDROID_PRIORITY_AUDIO);
340 }
341 *_aidl_return = mBluetooth;
342 LOG(DEBUG) << __func__ << ": returning instance of IBluetooth: " << _aidl_return->get();
343 return ndk::ScopedAStatus::ok();
344}
345
Mikhail Naganov00603d12022-05-02 22:52:13 +0000346ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
347 AudioPort* _aidl_return) {
348 const int32_t templateId = in_templateIdAndAdditionalData.id;
349 auto& ports = getConfig().ports;
350 AudioPort connectedPort;
351 { // Scope the template port so that we don't accidentally modify it.
352 auto templateIt = findById<AudioPort>(ports, templateId);
353 if (templateIt == ports.end()) {
354 LOG(ERROR) << __func__ << ": port id " << templateId << " not found";
355 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
356 }
357 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
358 LOG(ERROR) << __func__ << ": port id " << templateId << " is not a device port";
359 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
360 }
361 if (!templateIt->profiles.empty()) {
362 LOG(ERROR) << __func__ << ": port id " << templateId
363 << " does not have dynamic profiles";
364 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
365 }
366 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
367 if (templateDevicePort.device.type.connection.empty()) {
368 LOG(ERROR) << __func__ << ": port id " << templateId << " is permanently attached";
369 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
370 }
371 // Postpone id allocation until we ensure that there are no client errors.
372 connectedPort = *templateIt;
373 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
374 const auto& inputDevicePort =
375 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
376 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
377 connectedDevicePort.device.address = inputDevicePort.device.address;
378 LOG(DEBUG) << __func__ << ": device port " << connectedPort.id << " device set to "
379 << connectedDevicePort.device.toString();
380 // Check if there is already a connected port with for the same external device.
381 for (auto connectedPortId : mConnectedDevicePorts) {
382 auto connectedPortIt = findById<AudioPort>(ports, connectedPortId);
383 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
384 connectedDevicePort.device) {
385 LOG(ERROR) << __func__ << ": device " << connectedDevicePort.device.toString()
386 << " is already connected at the device port id " << connectedPortId;
387 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
388 }
389 }
390 }
391
392 if (!mDebug.simulateDeviceConnections) {
393 // In a real HAL here we would attempt querying the profiles from the device.
394 LOG(ERROR) << __func__ << ": failed to query supported device profiles";
395 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
396 }
397
398 connectedPort.id = ++getConfig().nextPortId;
399 mConnectedDevicePorts.insert(connectedPort.id);
400 LOG(DEBUG) << __func__ << ": template port " << templateId << " external device connected, "
401 << "connected port ID " << connectedPort.id;
402 auto& connectedProfiles = getConfig().connectedProfiles;
403 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
404 connectedProfilesIt != connectedProfiles.end()) {
405 connectedPort.profiles = connectedProfilesIt->second;
406 }
407 ports.push_back(connectedPort);
408 *_aidl_return = std::move(connectedPort);
409
410 std::vector<AudioRoute> newRoutes;
411 auto& routes = getConfig().routes;
412 for (auto& r : routes) {
413 if (r.sinkPortId == templateId) {
414 AudioRoute newRoute;
415 newRoute.sourcePortIds = r.sourcePortIds;
416 newRoute.sinkPortId = connectedPort.id;
417 newRoute.isExclusive = r.isExclusive;
418 newRoutes.push_back(std::move(newRoute));
419 } else {
420 auto& srcs = r.sourcePortIds;
421 if (std::find(srcs.begin(), srcs.end(), templateId) != srcs.end()) {
422 srcs.push_back(connectedPort.id);
423 }
424 }
425 }
426 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
427
428 return ndk::ScopedAStatus::ok();
429}
430
431ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
432 auto& ports = getConfig().ports;
433 auto portIt = findById<AudioPort>(ports, in_portId);
434 if (portIt == ports.end()) {
435 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
436 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
437 }
438 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
439 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a device port";
440 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
441 }
442 if (mConnectedDevicePorts.count(in_portId) == 0) {
443 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a connected device port";
444 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
445 }
446 auto& configs = getConfig().portConfigs;
447 auto& initials = getConfig().initialConfigs;
448 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
449 if (config.portId == in_portId) {
450 // Check if the configuration was provided by the client.
451 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
452 return initialIt == initials.end() || config != *initialIt;
453 }
454 return false;
455 });
456 if (configIt != configs.end()) {
457 LOG(ERROR) << __func__ << ": port id " << in_portId << " has a non-default config with id "
458 << configIt->id;
459 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
460 }
461 ports.erase(portIt);
462 mConnectedDevicePorts.erase(in_portId);
463 LOG(DEBUG) << __func__ << ": connected device port " << in_portId << " released";
464
465 auto& routes = getConfig().routes;
466 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
467 if (routesIt->sinkPortId == in_portId) {
468 routesIt = routes.erase(routesIt);
469 } else {
470 // Note: the list of sourcePortIds can't become empty because there must
471 // be the id of the template port in the route.
472 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
473 ++routesIt;
474 }
475 }
476
477 return ndk::ScopedAStatus::ok();
478}
479
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000480ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
481 *_aidl_return = getConfig().patches;
482 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " patches";
483 return ndk::ScopedAStatus::ok();
484}
485
486ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
487 auto& ports = getConfig().ports;
488 auto portIt = findById<AudioPort>(ports, in_portId);
489 if (portIt != ports.end()) {
490 *_aidl_return = *portIt;
491 LOG(DEBUG) << __func__ << ": returning port by id " << in_portId;
492 return ndk::ScopedAStatus::ok();
493 }
494 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
495 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
496}
497
498ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
499 *_aidl_return = getConfig().portConfigs;
500 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " port configs";
501 return ndk::ScopedAStatus::ok();
502}
503
504ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
505 *_aidl_return = getConfig().ports;
506 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " ports";
507 return ndk::ScopedAStatus::ok();
508}
509
510ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
511 *_aidl_return = getConfig().routes;
512 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " routes";
513 return ndk::ScopedAStatus::ok();
514}
515
Mikhail Naganov00603d12022-05-02 22:52:13 +0000516ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
517 std::vector<AudioRoute>* _aidl_return) {
518 auto& ports = getConfig().ports;
519 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
520 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
521 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
522 }
523 auto& routes = getConfig().routes;
524 std::copy_if(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
525 [&](const auto& r) {
526 const auto& srcs = r.sourcePortIds;
527 return r.sinkPortId == in_portId ||
528 std::find(srcs.begin(), srcs.end(), in_portId) != srcs.end();
529 });
530 return ndk::ScopedAStatus::ok();
531}
532
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000533ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
534 OpenInputStreamReturn* _aidl_return) {
535 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", buffer size "
536 << in_args.bufferSizeFrames << " frames";
537 AudioPort* port = nullptr;
538 if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
539 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000540 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000541 if (port->flags.getTag() != AudioIoFlags::Tag::input) {
542 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000543 << " does not correspond to an input mix port";
544 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
545 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000546 StreamContext context;
Mikhail Naganov30301a42022-09-13 01:20:45 +0000547 if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames, nullptr,
548 &context);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000549 !status.isOk()) {
550 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000551 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000552 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000553 std::shared_ptr<StreamIn> stream;
554 if (auto status = StreamIn::createInstance(in_args.sinkMetadata, std::move(context),
555 mConfig->microphones, &stream);
556 !status.isOk()) {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000557 return status;
558 }
559 StreamWrapper streamWrapper(stream);
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000560 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
561 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000562 auto patchIt = mPatches.find(in_args.portConfigId);
563 if (patchIt != mPatches.end()) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000564 streamWrapper.setStreamIsConnected(findConnectedDevices(in_args.portConfigId));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000565 }
566 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000567 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000568 return ndk::ScopedAStatus::ok();
569}
570
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000571ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
572 OpenOutputStreamReturn* _aidl_return) {
573 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", has offload info? "
574 << (in_args.offloadInfo.has_value()) << ", buffer size " << in_args.bufferSizeFrames
575 << " frames";
576 AudioPort* port = nullptr;
577 if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
578 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000579 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000580 if (port->flags.getTag() != AudioIoFlags::Tag::output) {
581 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000582 << " does not correspond to an output mix port";
583 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
584 }
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000585 const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
586 AudioOutputFlags::COMPRESS_OFFLOAD);
587 if (isOffload && !in_args.offloadInfo.has_value()) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000588 LOG(ERROR) << __func__ << ": port id " << port->id
Mikhail Naganov111e0ce2022-06-17 21:41:19 +0000589 << " has COMPRESS_OFFLOAD flag set, requires offload info";
590 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
591 }
Mikhail Naganov30301a42022-09-13 01:20:45 +0000592 const bool isNonBlocking = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
593 AudioOutputFlags::NON_BLOCKING);
594 if (isNonBlocking && in_args.callback == nullptr) {
595 LOG(ERROR) << __func__ << ": port id " << port->id
596 << " has NON_BLOCKING flag set, requires async callback";
597 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
598 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000599 StreamContext context;
Mikhail Naganov30301a42022-09-13 01:20:45 +0000600 if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
601 isNonBlocking ? in_args.callback : nullptr, &context);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000602 !status.isOk()) {
603 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000604 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000605 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000606 std::shared_ptr<StreamOut> stream;
607 if (auto status = StreamOut::createInstance(in_args.sourceMetadata, std::move(context),
608 in_args.offloadInfo, &stream);
609 !status.isOk()) {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000610 return status;
611 }
612 StreamWrapper streamWrapper(stream);
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000613 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
614 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000615 auto patchIt = mPatches.find(in_args.portConfigId);
616 if (patchIt != mPatches.end()) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000617 streamWrapper.setStreamIsConnected(findConnectedDevices(in_args.portConfigId));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000618 }
619 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000620 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000621 return ndk::ScopedAStatus::ok();
622}
623
Mikhail Naganov74927202022-12-19 16:37:14 +0000624ndk::ScopedAStatus Module::getSupportedPlaybackRateFactors(
625 SupportedPlaybackRateFactors* _aidl_return) {
626 LOG(DEBUG) << __func__;
627 (void)_aidl_return;
628 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
629}
630
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000631ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
Mikhail Naganov16db9b72022-06-17 21:36:18 +0000632 LOG(DEBUG) << __func__ << ": requested patch " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000633 if (in_requested.sourcePortConfigIds.empty()) {
634 LOG(ERROR) << __func__ << ": requested patch has empty sources list";
635 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
636 }
637 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
638 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sources list";
639 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
640 }
641 if (in_requested.sinkPortConfigIds.empty()) {
642 LOG(ERROR) << __func__ << ": requested patch has empty sinks list";
643 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
644 }
645 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
646 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sinks list";
647 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
648 }
649
650 auto& configs = getConfig().portConfigs;
651 std::vector<int32_t> missingIds;
652 auto sources =
653 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
654 if (!missingIds.empty()) {
655 LOG(ERROR) << __func__ << ": following source port config ids not found: "
656 << ::android::internal::ToString(missingIds);
657 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
658 }
659 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
660 if (!missingIds.empty()) {
661 LOG(ERROR) << __func__ << ": following sink port config ids not found: "
662 << ::android::internal::ToString(missingIds);
663 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
664 }
665 // bool indicates whether a non-exclusive route is available.
666 // If only an exclusive route is available, that means the patch can not be
667 // established if there is any other patch which currently uses the sink port.
668 std::map<int32_t, bool> allowedSinkPorts;
669 auto& routes = getConfig().routes;
670 for (auto src : sources) {
671 for (const auto& r : routes) {
672 const auto& srcs = r.sourcePortIds;
673 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
674 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
675 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
676 }
677 }
678 }
679 }
680 for (auto sink : sinks) {
681 if (allowedSinkPorts.count(sink->portId) == 0) {
682 LOG(ERROR) << __func__ << ": there is no route to the sink port id " << sink->portId;
683 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
684 }
685 }
686
687 auto& patches = getConfig().patches;
688 auto existing = patches.end();
689 std::optional<decltype(mPatches)> patchesBackup;
690 if (in_requested.id != 0) {
691 existing = findById<AudioPatch>(patches, in_requested.id);
692 if (existing != patches.end()) {
693 patchesBackup = mPatches;
694 cleanUpPatch(existing->id);
695 } else {
696 LOG(ERROR) << __func__ << ": not found existing patch id " << in_requested.id;
697 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
698 }
699 }
700 // Validate the requested patch.
701 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
702 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
703 LOG(ERROR) << __func__ << ": sink port id " << sinkPortId
704 << "is exclusive and is already used by some other patch";
705 if (patchesBackup.has_value()) {
706 mPatches = std::move(*patchesBackup);
707 }
708 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
709 }
710 }
711 *_aidl_return = in_requested;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000712 _aidl_return->minimumStreamBufferSizeFrames = kMinimumStreamBufferSizeFrames;
713 _aidl_return->latenciesMs.clear();
714 _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
715 _aidl_return->sinkPortConfigIds.size(), kLatencyMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000716 AudioPatch oldPatch{};
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000717 if (existing == patches.end()) {
718 _aidl_return->id = getConfig().nextPatchId++;
719 patches.push_back(*_aidl_return);
720 existing = patches.begin() + (patches.size() - 1);
721 } else {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000722 oldPatch = *existing;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000723 *existing = *_aidl_return;
724 }
725 registerPatch(*existing);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000726 updateStreamsConnectedState(oldPatch, *_aidl_return);
727
728 LOG(DEBUG) << __func__ << ": " << (oldPatch.id == 0 ? "created" : "updated") << " patch "
729 << _aidl_return->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000730 return ndk::ScopedAStatus::ok();
731}
732
733ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
734 AudioPortConfig* out_suggested, bool* _aidl_return) {
735 LOG(DEBUG) << __func__ << ": requested " << in_requested.toString();
736 auto& configs = getConfig().portConfigs;
737 auto existing = configs.end();
738 if (in_requested.id != 0) {
739 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
740 existing == configs.end()) {
741 LOG(ERROR) << __func__ << ": existing port config id " << in_requested.id
742 << " not found";
743 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
744 }
745 }
746
747 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
748 if (portId == 0) {
749 LOG(ERROR) << __func__ << ": input port config does not specify portId";
750 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
751 }
752 auto& ports = getConfig().ports;
753 auto portIt = findById<AudioPort>(ports, portId);
754 if (portIt == ports.end()) {
755 LOG(ERROR) << __func__ << ": input port config points to non-existent portId " << portId;
756 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
757 }
758 if (existing != configs.end()) {
759 *out_suggested = *existing;
760 } else {
761 AudioPortConfig newConfig;
762 if (generateDefaultPortConfig(*portIt, &newConfig)) {
763 *out_suggested = newConfig;
764 } else {
765 LOG(ERROR) << __func__ << ": unable generate a default config for port " << portId;
766 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
767 }
768 }
769 // From this moment, 'out_suggested' is either an existing port config,
770 // or a new generated config. Now attempt to update it according to the specified
771 // fields of 'in_requested'.
772
773 bool requestedIsValid = true, requestedIsFullySpecified = true;
774
775 AudioIoFlags portFlags = portIt->flags;
776 if (in_requested.flags.has_value()) {
777 if (in_requested.flags.value() != portFlags) {
778 LOG(WARNING) << __func__ << ": requested flags "
779 << in_requested.flags.value().toString() << " do not match port's "
780 << portId << " flags " << portFlags.toString();
781 requestedIsValid = false;
782 }
783 } else {
784 requestedIsFullySpecified = false;
785 }
786
787 AudioProfile portProfile;
788 if (in_requested.format.has_value()) {
789 const auto& format = in_requested.format.value();
790 if (findAudioProfile(*portIt, format, &portProfile)) {
791 out_suggested->format = format;
792 } else {
793 LOG(WARNING) << __func__ << ": requested format " << format.toString()
794 << " is not found in port's " << portId << " profiles";
795 requestedIsValid = false;
796 }
797 } else {
798 requestedIsFullySpecified = false;
799 }
800 if (!findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
801 LOG(ERROR) << __func__ << ": port " << portId << " does not support format "
802 << out_suggested->format.value().toString() << " anymore";
803 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
804 }
805
806 if (in_requested.channelMask.has_value()) {
807 const auto& channelMask = in_requested.channelMask.value();
808 if (find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
809 portProfile.channelMasks.end()) {
810 out_suggested->channelMask = channelMask;
811 } else {
812 LOG(WARNING) << __func__ << ": requested channel mask " << channelMask.toString()
813 << " is not supported for the format " << portProfile.format.toString()
814 << " by the port " << portId;
815 requestedIsValid = false;
816 }
817 } else {
818 requestedIsFullySpecified = false;
819 }
820
821 if (in_requested.sampleRate.has_value()) {
822 const auto& sampleRate = in_requested.sampleRate.value();
823 if (find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
824 sampleRate.value) != portProfile.sampleRates.end()) {
825 out_suggested->sampleRate = sampleRate;
826 } else {
827 LOG(WARNING) << __func__ << ": requested sample rate " << sampleRate.value
828 << " is not supported for the format " << portProfile.format.toString()
829 << " by the port " << portId;
830 requestedIsValid = false;
831 }
832 } else {
833 requestedIsFullySpecified = false;
834 }
835
836 if (in_requested.gain.has_value()) {
837 // Let's pretend that gain can always be applied.
838 out_suggested->gain = in_requested.gain.value();
839 }
840
841 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
842 out_suggested->id = getConfig().nextPortId++;
843 configs.push_back(*out_suggested);
844 *_aidl_return = true;
845 LOG(DEBUG) << __func__ << ": created new port config " << out_suggested->toString();
846 } else if (existing != configs.end() && requestedIsValid) {
847 *existing = *out_suggested;
848 *_aidl_return = true;
849 LOG(DEBUG) << __func__ << ": updated port config " << out_suggested->toString();
850 } else {
851 LOG(DEBUG) << __func__ << ": not applied; existing config ? " << (existing != configs.end())
852 << "; requested is valid? " << requestedIsValid << ", fully specified? "
853 << requestedIsFullySpecified;
854 *_aidl_return = false;
855 }
856 return ndk::ScopedAStatus::ok();
857}
858
859ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
860 auto& patches = getConfig().patches;
861 auto patchIt = findById<AudioPatch>(patches, in_patchId);
862 if (patchIt != patches.end()) {
863 cleanUpPatch(patchIt->id);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000864 updateStreamsConnectedState(*patchIt, AudioPatch{});
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000865 patches.erase(patchIt);
866 LOG(DEBUG) << __func__ << ": erased patch " << in_patchId;
867 return ndk::ScopedAStatus::ok();
868 }
869 LOG(ERROR) << __func__ << ": patch id " << in_patchId << " not found";
870 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
871}
872
873ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
874 auto& configs = getConfig().portConfigs;
875 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
876 if (configIt != configs.end()) {
877 if (mStreams.count(in_portConfigId) != 0) {
878 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
879 << " has a stream opened on it";
880 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
881 }
882 auto patchIt = mPatches.find(in_portConfigId);
883 if (patchIt != mPatches.end()) {
884 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
885 << " is used by the patch with id " << patchIt->second;
886 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
887 }
888 auto& initials = getConfig().initialConfigs;
889 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
890 if (initialIt == initials.end()) {
891 configs.erase(configIt);
892 LOG(DEBUG) << __func__ << ": erased port config " << in_portConfigId;
893 } else if (*configIt != *initialIt) {
894 *configIt = *initialIt;
895 LOG(DEBUG) << __func__ << ": reset port config " << in_portConfigId;
896 }
897 return ndk::ScopedAStatus::ok();
898 }
899 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId << " not found";
900 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
901}
902
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000903ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) {
904 *_aidl_return = mMasterMute;
905 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
906 return ndk::ScopedAStatus::ok();
907}
908
909ndk::ScopedAStatus Module::setMasterMute(bool in_mute) {
910 LOG(DEBUG) << __func__ << ": " << in_mute;
911 mMasterMute = in_mute;
912 return ndk::ScopedAStatus::ok();
913}
914
915ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) {
916 *_aidl_return = mMasterVolume;
917 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
918 return ndk::ScopedAStatus::ok();
919}
920
921ndk::ScopedAStatus Module::setMasterVolume(float in_volume) {
922 LOG(DEBUG) << __func__ << ": " << in_volume;
923 if (in_volume >= 0.0f && in_volume <= 1.0f) {
924 mMasterVolume = in_volume;
925 return ndk::ScopedAStatus::ok();
926 }
927 LOG(ERROR) << __func__ << ": invalid master volume value: " << in_volume;
928 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
929}
930
931ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) {
932 *_aidl_return = mMicMute;
933 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
934 return ndk::ScopedAStatus::ok();
935}
936
937ndk::ScopedAStatus Module::setMicMute(bool in_mute) {
938 LOG(DEBUG) << __func__ << ": " << in_mute;
939 mMicMute = in_mute;
940 return ndk::ScopedAStatus::ok();
941}
942
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000943ndk::ScopedAStatus Module::getMicrophones(std::vector<MicrophoneInfo>* _aidl_return) {
944 *_aidl_return = mConfig->microphones;
945 LOG(DEBUG) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return);
946 return ndk::ScopedAStatus::ok();
947}
948
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000949ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) {
950 // No checks for supported audio modes here, it's an informative notification.
951 LOG(DEBUG) << __func__ << ": " << toString(in_mode);
952 return ndk::ScopedAStatus::ok();
953}
954
955ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) {
956 LOG(DEBUG) << __func__ << ": " << toString(in_rotation);
957 return ndk::ScopedAStatus::ok();
958}
959
960ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) {
961 LOG(DEBUG) << __func__ << ": " << in_isTurnedOn;
962 return ndk::ScopedAStatus::ok();
963}
964
Vlad Popa83a6d822022-11-07 13:53:57 +0100965ndk::ScopedAStatus Module::getSoundDose(std::shared_ptr<ISoundDose>* _aidl_return) {
Vlad Popa943b7e22022-12-08 14:24:12 +0100966 if (mSoundDose == nullptr) {
Vlad Popa2afbd1e2022-12-28 17:04:58 +0100967 mSoundDose = ndk::SharedRefBase::make<sounddose::SoundDose>();
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000968 mSoundDoseBinder = mSoundDose->asBinder();
969 AIBinder_setMinSchedulerPolicy(mSoundDoseBinder.get(), SCHED_NORMAL,
970 ANDROID_PRIORITY_AUDIO);
Vlad Popa943b7e22022-12-08 14:24:12 +0100971 }
972 *_aidl_return = mSoundDose;
973 LOG(DEBUG) << __func__ << ": returning instance of ISoundDose: " << _aidl_return->get();
Vlad Popa83a6d822022-11-07 13:53:57 +0100974 return ndk::ScopedAStatus::ok();
975}
976
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000977ndk::ScopedAStatus Module::generateHwAvSyncId(int32_t* _aidl_return) {
978 LOG(DEBUG) << __func__;
979 (void)_aidl_return;
980 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
981}
982
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000983const std::string Module::VendorDebug::kForceTransientBurstName = "aosp.forceTransientBurst";
Mikhail Naganov194daaa2023-01-05 22:34:20 +0000984const std::string Module::VendorDebug::kForceSynchronousDrainName = "aosp.forceSynchronousDrain";
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000985
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000986ndk::ScopedAStatus Module::getVendorParameters(const std::vector<std::string>& in_ids,
987 std::vector<VendorParameter>* _aidl_return) {
988 LOG(DEBUG) << __func__ << ": id count: " << in_ids.size();
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000989 bool allParametersKnown = true;
990 for (const auto& id : in_ids) {
991 if (id == VendorDebug::kForceTransientBurstName) {
992 VendorParameter forceTransientBurst{.id = id};
993 forceTransientBurst.ext.setParcelable(Boolean{mVendorDebug.forceTransientBurst});
994 _aidl_return->push_back(std::move(forceTransientBurst));
Mikhail Naganov194daaa2023-01-05 22:34:20 +0000995 } else if (id == VendorDebug::kForceSynchronousDrainName) {
996 VendorParameter forceSynchronousDrain{.id = id};
997 forceSynchronousDrain.ext.setParcelable(Boolean{mVendorDebug.forceSynchronousDrain});
998 _aidl_return->push_back(std::move(forceSynchronousDrain));
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000999 } else {
1000 allParametersKnown = false;
1001 LOG(ERROR) << __func__ << ": unrecognized parameter \"" << id << "\"";
1002 }
1003 }
1004 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1005 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001006}
1007
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001008namespace {
1009
1010template <typename W>
1011bool extractParameter(const VendorParameter& p, decltype(W::value)* v) {
1012 std::optional<W> value;
1013 binder_status_t result = p.ext.getParcelable(&value);
1014 if (result == STATUS_OK && value.has_value()) {
1015 *v = value.value().value;
1016 return true;
1017 }
1018 LOG(ERROR) << __func__ << ": failed to read the value of the parameter \"" << p.id
1019 << "\": " << result;
1020 return false;
1021}
1022
1023} // namespace
1024
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001025ndk::ScopedAStatus Module::setVendorParameters(const std::vector<VendorParameter>& in_parameters,
1026 bool in_async) {
1027 LOG(DEBUG) << __func__ << ": parameter count " << in_parameters.size()
1028 << ", async: " << in_async;
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001029 bool allParametersKnown = true;
1030 for (const auto& p : in_parameters) {
1031 if (p.id == VendorDebug::kForceTransientBurstName) {
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001032 if (!extractParameter<Boolean>(p, &mVendorDebug.forceTransientBurst)) {
1033 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1034 }
1035 } else if (p.id == VendorDebug::kForceSynchronousDrainName) {
1036 if (!extractParameter<Boolean>(p, &mVendorDebug.forceSynchronousDrain)) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001037 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1038 }
1039 } else {
1040 allParametersKnown = false;
1041 LOG(ERROR) << __func__ << ": unrecognized parameter \"" << p.id << "\"";
1042 }
1043 }
1044 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1045 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001046}
1047
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001048ndk::ScopedAStatus Module::addDeviceEffect(
1049 int32_t in_portConfigId,
1050 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1051 if (in_effect == nullptr) {
1052 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect";
1053 } else {
1054 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder "
1055 << in_effect->asBinder().get();
1056 }
1057 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1058}
1059
1060ndk::ScopedAStatus Module::removeDeviceEffect(
1061 int32_t in_portConfigId,
1062 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1063 if (in_effect == nullptr) {
1064 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect";
1065 } else {
1066 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder "
1067 << in_effect->asBinder().get();
1068 }
1069 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1070}
1071
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001072} // namespace aidl::android::hardware::audio::core