blob: a6e1d0dcd85fbffdea71e26bf2d49d15291b8524 [file] [log] [blame]
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001/*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <algorithm>
18#include <set>
19
20#define LOG_TAG "AHAL_Module"
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000021#include <android-base/logging.h>
Shunkai Yao39bf2c32022-12-06 03:25:59 +000022#include <android/binder_ibinder_platform.h>
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000023
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000024#include <Utils.h>
25#include <aidl/android/media/audio/common/AudioInputFlags.h>
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000026#include <aidl/android/media/audio/common/AudioOutputFlags.h>
27
Mikhail Naganov10c6fe22022-09-30 23:49:17 +000028#include "core-impl/Bluetooth.h"
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000029#include "core-impl/Module.h"
Vlad Popa943b7e22022-12-08 14:24:12 +010030#include "core-impl/SoundDose.h"
Mikhail Naganovf429c032023-01-07 00:24:50 +000031#include "core-impl/StreamStub.h"
Mikhail Naganov3b125b72022-10-05 02:12:39 +000032#include "core-impl/Telephony.h"
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000033#include "core-impl/utils.h"
34
35using aidl::android::hardware::audio::common::SinkMetadata;
36using aidl::android::hardware::audio::common::SourceMetadata;
Vlad Popa2afbd1e2022-12-28 17:04:58 +010037using aidl::android::hardware::audio::core::sounddose::ISoundDose;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000038using aidl::android::media::audio::common::AudioChannelLayout;
Mikhail Naganovef6bc742022-10-06 00:14:19 +000039using aidl::android::media::audio::common::AudioDevice;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000040using aidl::android::media::audio::common::AudioFormatDescription;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000041using aidl::android::media::audio::common::AudioFormatType;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000042using aidl::android::media::audio::common::AudioInputFlags;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000043using aidl::android::media::audio::common::AudioIoFlags;
Mikhail Naganov04ae8222023-01-11 15:48:10 -080044using aidl::android::media::audio::common::AudioMode;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000045using aidl::android::media::audio::common::AudioOffloadInfo;
46using aidl::android::media::audio::common::AudioOutputFlags;
47using aidl::android::media::audio::common::AudioPort;
48using aidl::android::media::audio::common::AudioPortConfig;
49using aidl::android::media::audio::common::AudioPortExt;
50using aidl::android::media::audio::common::AudioProfile;
Mikhail Naganov20047bc2023-01-05 20:16:07 +000051using aidl::android::media::audio::common::Boolean;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000052using aidl::android::media::audio::common::Int;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000053using aidl::android::media::audio::common::PcmType;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000054using android::hardware::audio::common::getFrameSizeInBytes;
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +000055using android::hardware::audio::common::isBitPositionFlagSet;
Mikhail Naganov04ae8222023-01-11 15:48:10 -080056using android::hardware::audio::common::isValidAudioMode;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000057
58namespace aidl::android::hardware::audio::core {
59
60namespace {
61
62bool generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) {
63 *config = {};
64 config->portId = port.id;
65 if (port.profiles.empty()) {
66 LOG(ERROR) << __func__ << ": port " << port.id << " has no profiles";
67 return false;
68 }
69 const auto& profile = port.profiles.begin();
70 config->format = profile->format;
71 if (profile->channelMasks.empty()) {
72 LOG(ERROR) << __func__ << ": the first profile in port " << port.id
73 << " has no channel masks";
74 return false;
75 }
76 config->channelMask = *profile->channelMasks.begin();
77 if (profile->sampleRates.empty()) {
78 LOG(ERROR) << __func__ << ": the first profile in port " << port.id
79 << " has no sample rates";
80 return false;
81 }
82 Int sampleRate;
83 sampleRate.value = *profile->sampleRates.begin();
84 config->sampleRate = sampleRate;
85 config->flags = port.flags;
86 config->ext = port.ext;
87 return true;
88}
89
90bool findAudioProfile(const AudioPort& port, const AudioFormatDescription& format,
91 AudioProfile* profile) {
92 if (auto profilesIt =
93 find_if(port.profiles.begin(), port.profiles.end(),
94 [&format](const auto& profile) { return profile.format == format; });
95 profilesIt != port.profiles.end()) {
96 *profile = *profilesIt;
97 return true;
98 }
99 return false;
100}
Mikhail Naganov00603d12022-05-02 22:52:13 +0000101
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000102} // namespace
103
104void Module::cleanUpPatch(int32_t patchId) {
105 erase_all_values(mPatches, std::set<int32_t>{patchId});
106}
107
Mikhail Naganov8651b362023-01-06 23:15:27 +0000108ndk::ScopedAStatus Module::createStreamContext(
109 int32_t in_portConfigId, int64_t in_bufferSizeFrames,
110 std::shared_ptr<IStreamCallback> asyncCallback,
111 std::shared_ptr<IStreamOutEventCallback> outEventCallback, StreamContext* out_context) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000112 if (in_bufferSizeFrames <= 0) {
113 LOG(ERROR) << __func__ << ": non-positive buffer size " << in_bufferSizeFrames;
114 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
115 }
116 if (in_bufferSizeFrames < kMinimumStreamBufferSizeFrames) {
117 LOG(ERROR) << __func__ << ": insufficient buffer size " << in_bufferSizeFrames
118 << ", must be at least " << kMinimumStreamBufferSizeFrames;
119 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
120 }
121 auto& configs = getConfig().portConfigs;
122 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000123 // Since this is a private method, it is assumed that
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000124 // validity of the portConfigId has already been checked.
125 const size_t frameSize =
126 getFrameSizeInBytes(portConfigIt->format.value(), portConfigIt->channelMask.value());
127 if (frameSize == 0) {
128 LOG(ERROR) << __func__ << ": could not calculate frame size for port config "
129 << portConfigIt->toString();
130 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
131 }
132 LOG(DEBUG) << __func__ << ": frame size " << frameSize << " bytes";
133 if (frameSize > kMaximumStreamBufferSizeBytes / in_bufferSizeFrames) {
134 LOG(ERROR) << __func__ << ": buffer size " << in_bufferSizeFrames
135 << " frames is too large, maximum size is "
136 << kMaximumStreamBufferSizeBytes / frameSize;
137 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
138 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000139 const auto& flags = portConfigIt->flags.value();
140 if ((flags.getTag() == AudioIoFlags::Tag::input &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000141 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::input>(),
142 AudioInputFlags::MMAP_NOIRQ)) ||
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000143 (flags.getTag() == AudioIoFlags::Tag::output &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000144 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::output>(),
145 AudioOutputFlags::MMAP_NOIRQ))) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000146 StreamContext::DebugParameters params{mDebug.streamTransientStateDelayMs,
Mikhail Naganov194daaa2023-01-05 22:34:20 +0000147 mVendorDebug.forceTransientBurst,
148 mVendorDebug.forceSynchronousDrain};
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000149 StreamContext temp(
150 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
151 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000152 portConfigIt->format.value(), portConfigIt->channelMask.value(),
153 std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames),
Mikhail Naganov8651b362023-01-06 23:15:27 +0000154 asyncCallback, outEventCallback, params);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000155 if (temp.isValid()) {
156 *out_context = std::move(temp);
157 } else {
158 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
159 }
160 } else {
161 // TODO: Implement simulation of MMAP buffer allocation
162 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000163 return ndk::ScopedAStatus::ok();
164}
165
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000166std::vector<AudioDevice> Module::findConnectedDevices(int32_t portConfigId) {
167 std::vector<AudioDevice> result;
168 auto& ports = getConfig().ports;
169 auto portIds = portIdsFromPortConfigIds(findConnectedPortConfigIds(portConfigId));
170 for (auto it = portIds.begin(); it != portIds.end(); ++it) {
171 auto portIt = findById<AudioPort>(ports, *it);
172 if (portIt != ports.end() && portIt->ext.getTag() == AudioPortExt::Tag::device) {
173 result.push_back(portIt->ext.template get<AudioPortExt::Tag::device>().device);
174 }
175 }
176 return result;
177}
178
179std::set<int32_t> Module::findConnectedPortConfigIds(int32_t portConfigId) {
180 std::set<int32_t> result;
181 auto patchIdsRange = mPatches.equal_range(portConfigId);
182 auto& patches = getConfig().patches;
183 for (auto it = patchIdsRange.first; it != patchIdsRange.second; ++it) {
184 auto patchIt = findById<AudioPatch>(patches, it->second);
185 if (patchIt == patches.end()) {
186 LOG(FATAL) << __func__ << ": patch with id " << it->second << " taken from mPatches "
187 << "not found in the configuration";
188 }
189 if (std::find(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end(),
190 portConfigId) != patchIt->sourcePortConfigIds.end()) {
191 result.insert(patchIt->sinkPortConfigIds.begin(), patchIt->sinkPortConfigIds.end());
192 } else {
193 result.insert(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end());
194 }
195 }
196 return result;
197}
198
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000199ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) {
200 auto& configs = getConfig().portConfigs;
201 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
202 if (portConfigIt == configs.end()) {
203 LOG(ERROR) << __func__ << ": existing port config id " << in_portConfigId << " not found";
204 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
205 }
206 const int32_t portId = portConfigIt->portId;
207 // In our implementation, configs of mix ports always have unique IDs.
208 CHECK(portId != in_portConfigId);
209 auto& ports = getConfig().ports;
210 auto portIt = findById<AudioPort>(ports, portId);
211 if (portIt == ports.end()) {
212 LOG(ERROR) << __func__ << ": port id " << portId << " used by port config id "
213 << in_portConfigId << " not found";
214 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
215 }
216 if (mStreams.count(in_portConfigId) != 0) {
217 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
218 << " already has a stream opened on it";
219 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
220 }
221 if (portIt->ext.getTag() != AudioPortExt::Tag::mix) {
222 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
223 << " does not correspond to a mix port";
224 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
225 }
226 const int32_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
227 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
228 LOG(ERROR) << __func__ << ": port id " << portId
229 << " has already reached maximum allowed opened stream count: "
230 << maxOpenStreamCount;
231 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
232 }
233 *port = &(*portIt);
234 return ndk::ScopedAStatus::ok();
235}
236
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000237template <typename C>
238std::set<int32_t> Module::portIdsFromPortConfigIds(C portConfigIds) {
239 std::set<int32_t> result;
240 auto& portConfigs = getConfig().portConfigs;
241 for (auto it = portConfigIds.begin(); it != portConfigIds.end(); ++it) {
242 auto portConfigIt = findById<AudioPortConfig>(portConfigs, *it);
243 if (portConfigIt != portConfigs.end()) {
244 result.insert(portConfigIt->portId);
245 }
246 }
247 return result;
248}
249
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000250internal::Configuration& Module::getConfig() {
251 if (!mConfig) {
Mikhail Naganovc8e43122022-12-09 00:33:47 +0000252 switch (mType) {
253 case Type::DEFAULT:
254 mConfig = std::move(internal::getPrimaryConfiguration());
255 break;
256 case Type::R_SUBMIX:
257 mConfig = std::move(internal::getRSubmixConfiguration());
258 break;
259 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000260 }
261 return *mConfig;
262}
263
264void Module::registerPatch(const AudioPatch& patch) {
265 auto& configs = getConfig().portConfigs;
266 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
267 for (auto portConfigId : portConfigIds) {
268 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
269 if (configIt != configs.end()) {
270 mPatches.insert(std::pair{portConfigId, patch.id});
271 if (configIt->portId != portConfigId) {
272 mPatches.insert(std::pair{configIt->portId, patch.id});
273 }
274 }
275 };
276 };
277 do_insert(patch.sourcePortConfigIds);
278 do_insert(patch.sinkPortConfigIds);
279}
280
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000281void Module::updateStreamsConnectedState(const AudioPatch& oldPatch, const AudioPatch& newPatch) {
282 // Streams from the old patch need to be disconnected, streams from the new
283 // patch need to be connected. If the stream belongs to both patches, no need
284 // to update it.
285 std::set<int32_t> idsToDisconnect, idsToConnect;
286 idsToDisconnect.insert(oldPatch.sourcePortConfigIds.begin(),
287 oldPatch.sourcePortConfigIds.end());
288 idsToDisconnect.insert(oldPatch.sinkPortConfigIds.begin(), oldPatch.sinkPortConfigIds.end());
289 idsToConnect.insert(newPatch.sourcePortConfigIds.begin(), newPatch.sourcePortConfigIds.end());
290 idsToConnect.insert(newPatch.sinkPortConfigIds.begin(), newPatch.sinkPortConfigIds.end());
291 std::for_each(idsToDisconnect.begin(), idsToDisconnect.end(), [&](const auto& portConfigId) {
292 if (idsToConnect.count(portConfigId) == 0) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000293 LOG(DEBUG) << "The stream on port config id " << portConfigId << " is not connected";
294 mStreams.setStreamIsConnected(portConfigId, {});
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000295 }
296 });
297 std::for_each(idsToConnect.begin(), idsToConnect.end(), [&](const auto& portConfigId) {
298 if (idsToDisconnect.count(portConfigId) == 0) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000299 const auto connectedDevices = findConnectedDevices(portConfigId);
300 LOG(DEBUG) << "The stream on port config id " << portConfigId
301 << " is connected to: " << ::android::internal::ToString(connectedDevices);
302 mStreams.setStreamIsConnected(portConfigId, connectedDevices);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000303 }
304 });
305}
306
Mikhail Naganov00603d12022-05-02 22:52:13 +0000307ndk::ScopedAStatus Module::setModuleDebug(
308 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
309 LOG(DEBUG) << __func__ << ": old flags:" << mDebug.toString()
310 << ", new flags: " << in_debug.toString();
311 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
312 !mConnectedDevicePorts.empty()) {
313 LOG(ERROR) << __func__ << ": attempting to change device connections simulation "
314 << "while having external devices connected";
315 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
316 }
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000317 if (in_debug.streamTransientStateDelayMs < 0) {
318 LOG(ERROR) << __func__ << ": streamTransientStateDelayMs is negative: "
319 << in_debug.streamTransientStateDelayMs;
320 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
321 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000322 mDebug = in_debug;
323 return ndk::ScopedAStatus::ok();
324}
325
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000326ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
327 if (mTelephony == nullptr) {
328 mTelephony = ndk::SharedRefBase::make<Telephony>();
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000329 mTelephonyBinder = mTelephony->asBinder();
330 AIBinder_setMinSchedulerPolicy(mTelephonyBinder.get(), SCHED_NORMAL,
Shunkai Yao39bf2c32022-12-06 03:25:59 +0000331 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000332 }
333 *_aidl_return = mTelephony;
334 LOG(DEBUG) << __func__ << ": returning instance of ITelephony: " << _aidl_return->get();
335 return ndk::ScopedAStatus::ok();
336}
337
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000338ndk::ScopedAStatus Module::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
339 if (mBluetooth == nullptr) {
340 mBluetooth = ndk::SharedRefBase::make<Bluetooth>();
341 mBluetoothBinder = mBluetooth->asBinder();
342 AIBinder_setMinSchedulerPolicy(mBluetoothBinder.get(), SCHED_NORMAL,
343 ANDROID_PRIORITY_AUDIO);
344 }
345 *_aidl_return = mBluetooth;
346 LOG(DEBUG) << __func__ << ": returning instance of IBluetooth: " << _aidl_return->get();
347 return ndk::ScopedAStatus::ok();
348}
349
Mikhail Naganov00603d12022-05-02 22:52:13 +0000350ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
351 AudioPort* _aidl_return) {
352 const int32_t templateId = in_templateIdAndAdditionalData.id;
353 auto& ports = getConfig().ports;
354 AudioPort connectedPort;
355 { // Scope the template port so that we don't accidentally modify it.
356 auto templateIt = findById<AudioPort>(ports, templateId);
357 if (templateIt == ports.end()) {
358 LOG(ERROR) << __func__ << ": port id " << templateId << " not found";
359 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
360 }
361 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
362 LOG(ERROR) << __func__ << ": port id " << templateId << " is not a device port";
363 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
364 }
365 if (!templateIt->profiles.empty()) {
366 LOG(ERROR) << __func__ << ": port id " << templateId
367 << " does not have dynamic profiles";
368 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
369 }
370 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
371 if (templateDevicePort.device.type.connection.empty()) {
372 LOG(ERROR) << __func__ << ": port id " << templateId << " is permanently attached";
373 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
374 }
375 // Postpone id allocation until we ensure that there are no client errors.
376 connectedPort = *templateIt;
377 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
378 const auto& inputDevicePort =
379 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
380 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
381 connectedDevicePort.device.address = inputDevicePort.device.address;
382 LOG(DEBUG) << __func__ << ": device port " << connectedPort.id << " device set to "
383 << connectedDevicePort.device.toString();
384 // Check if there is already a connected port with for the same external device.
385 for (auto connectedPortId : mConnectedDevicePorts) {
386 auto connectedPortIt = findById<AudioPort>(ports, connectedPortId);
387 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
388 connectedDevicePort.device) {
389 LOG(ERROR) << __func__ << ": device " << connectedDevicePort.device.toString()
390 << " is already connected at the device port id " << connectedPortId;
391 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
392 }
393 }
394 }
395
396 if (!mDebug.simulateDeviceConnections) {
397 // In a real HAL here we would attempt querying the profiles from the device.
398 LOG(ERROR) << __func__ << ": failed to query supported device profiles";
399 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
400 }
401
402 connectedPort.id = ++getConfig().nextPortId;
403 mConnectedDevicePorts.insert(connectedPort.id);
404 LOG(DEBUG) << __func__ << ": template port " << templateId << " external device connected, "
405 << "connected port ID " << connectedPort.id;
406 auto& connectedProfiles = getConfig().connectedProfiles;
407 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
408 connectedProfilesIt != connectedProfiles.end()) {
409 connectedPort.profiles = connectedProfilesIt->second;
410 }
411 ports.push_back(connectedPort);
412 *_aidl_return = std::move(connectedPort);
413
414 std::vector<AudioRoute> newRoutes;
415 auto& routes = getConfig().routes;
416 for (auto& r : routes) {
417 if (r.sinkPortId == templateId) {
418 AudioRoute newRoute;
419 newRoute.sourcePortIds = r.sourcePortIds;
420 newRoute.sinkPortId = connectedPort.id;
421 newRoute.isExclusive = r.isExclusive;
422 newRoutes.push_back(std::move(newRoute));
423 } else {
424 auto& srcs = r.sourcePortIds;
425 if (std::find(srcs.begin(), srcs.end(), templateId) != srcs.end()) {
426 srcs.push_back(connectedPort.id);
427 }
428 }
429 }
430 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
431
432 return ndk::ScopedAStatus::ok();
433}
434
435ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
436 auto& ports = getConfig().ports;
437 auto portIt = findById<AudioPort>(ports, in_portId);
438 if (portIt == ports.end()) {
439 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
440 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
441 }
442 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
443 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a device port";
444 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
445 }
446 if (mConnectedDevicePorts.count(in_portId) == 0) {
447 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a connected device port";
448 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
449 }
450 auto& configs = getConfig().portConfigs;
451 auto& initials = getConfig().initialConfigs;
452 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
453 if (config.portId == in_portId) {
454 // Check if the configuration was provided by the client.
455 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
456 return initialIt == initials.end() || config != *initialIt;
457 }
458 return false;
459 });
460 if (configIt != configs.end()) {
461 LOG(ERROR) << __func__ << ": port id " << in_portId << " has a non-default config with id "
462 << configIt->id;
463 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
464 }
465 ports.erase(portIt);
466 mConnectedDevicePorts.erase(in_portId);
467 LOG(DEBUG) << __func__ << ": connected device port " << in_portId << " released";
468
469 auto& routes = getConfig().routes;
470 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
471 if (routesIt->sinkPortId == in_portId) {
472 routesIt = routes.erase(routesIt);
473 } else {
474 // Note: the list of sourcePortIds can't become empty because there must
475 // be the id of the template port in the route.
476 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
477 ++routesIt;
478 }
479 }
480
481 return ndk::ScopedAStatus::ok();
482}
483
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000484ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
485 *_aidl_return = getConfig().patches;
486 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " patches";
487 return ndk::ScopedAStatus::ok();
488}
489
490ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
491 auto& ports = getConfig().ports;
492 auto portIt = findById<AudioPort>(ports, in_portId);
493 if (portIt != ports.end()) {
494 *_aidl_return = *portIt;
495 LOG(DEBUG) << __func__ << ": returning port by id " << in_portId;
496 return ndk::ScopedAStatus::ok();
497 }
498 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
499 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
500}
501
502ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
503 *_aidl_return = getConfig().portConfigs;
504 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " port configs";
505 return ndk::ScopedAStatus::ok();
506}
507
508ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
509 *_aidl_return = getConfig().ports;
510 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " ports";
511 return ndk::ScopedAStatus::ok();
512}
513
514ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
515 *_aidl_return = getConfig().routes;
516 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " routes";
517 return ndk::ScopedAStatus::ok();
518}
519
Mikhail Naganov00603d12022-05-02 22:52:13 +0000520ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
521 std::vector<AudioRoute>* _aidl_return) {
522 auto& ports = getConfig().ports;
523 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
524 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
525 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
526 }
527 auto& routes = getConfig().routes;
528 std::copy_if(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
529 [&](const auto& r) {
530 const auto& srcs = r.sourcePortIds;
531 return r.sinkPortId == in_portId ||
532 std::find(srcs.begin(), srcs.end(), in_portId) != srcs.end();
533 });
534 return ndk::ScopedAStatus::ok();
535}
536
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000537ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
538 OpenInputStreamReturn* _aidl_return) {
539 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", buffer size "
540 << in_args.bufferSizeFrames << " frames";
541 AudioPort* port = nullptr;
542 if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
543 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000544 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000545 if (port->flags.getTag() != AudioIoFlags::Tag::input) {
546 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000547 << " does not correspond to an input mix port";
548 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
549 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000550 StreamContext context;
Mikhail Naganov30301a42022-09-13 01:20:45 +0000551 if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames, nullptr,
Mikhail Naganov8651b362023-01-06 23:15:27 +0000552 nullptr, &context);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000553 !status.isOk()) {
554 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000555 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000556 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000557 std::shared_ptr<StreamIn> stream;
Mikhail Naganovf429c032023-01-07 00:24:50 +0000558 // TODO: Add a mapping from module instance names to a corresponding 'createInstance'.
559 if (auto status = StreamInStub::createInstance(in_args.sinkMetadata, std::move(context),
560 mConfig->microphones, &stream);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000561 !status.isOk()) {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000562 return status;
563 }
564 StreamWrapper streamWrapper(stream);
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000565 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
566 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000567 auto patchIt = mPatches.find(in_args.portConfigId);
568 if (patchIt != mPatches.end()) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000569 streamWrapper.setStreamIsConnected(findConnectedDevices(in_args.portConfigId));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000570 }
571 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000572 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000573 return ndk::ScopedAStatus::ok();
574}
575
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000576ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
577 OpenOutputStreamReturn* _aidl_return) {
578 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", has offload info? "
579 << (in_args.offloadInfo.has_value()) << ", buffer size " << in_args.bufferSizeFrames
580 << " frames";
581 AudioPort* port = nullptr;
582 if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
583 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000584 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000585 if (port->flags.getTag() != AudioIoFlags::Tag::output) {
586 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000587 << " does not correspond to an output mix port";
588 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
589 }
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000590 const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
591 AudioOutputFlags::COMPRESS_OFFLOAD);
592 if (isOffload && !in_args.offloadInfo.has_value()) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000593 LOG(ERROR) << __func__ << ": port id " << port->id
Mikhail Naganov111e0ce2022-06-17 21:41:19 +0000594 << " has COMPRESS_OFFLOAD flag set, requires offload info";
595 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
596 }
Mikhail Naganov30301a42022-09-13 01:20:45 +0000597 const bool isNonBlocking = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
598 AudioOutputFlags::NON_BLOCKING);
599 if (isNonBlocking && in_args.callback == nullptr) {
600 LOG(ERROR) << __func__ << ": port id " << port->id
601 << " has NON_BLOCKING flag set, requires async callback";
602 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
603 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000604 StreamContext context;
Mikhail Naganov30301a42022-09-13 01:20:45 +0000605 if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
Mikhail Naganov8651b362023-01-06 23:15:27 +0000606 isNonBlocking ? in_args.callback : nullptr,
607 in_args.eventCallback, &context);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000608 !status.isOk()) {
609 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000610 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000611 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000612 std::shared_ptr<StreamOut> stream;
Mikhail Naganovf429c032023-01-07 00:24:50 +0000613 // TODO: Add a mapping from module instance names to a corresponding 'createInstance'.
614 if (auto status = StreamOutStub::createInstance(in_args.sourceMetadata, std::move(context),
615 in_args.offloadInfo, &stream);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000616 !status.isOk()) {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000617 return status;
618 }
619 StreamWrapper streamWrapper(stream);
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000620 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
621 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000622 auto patchIt = mPatches.find(in_args.portConfigId);
623 if (patchIt != mPatches.end()) {
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000624 streamWrapper.setStreamIsConnected(findConnectedDevices(in_args.portConfigId));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000625 }
626 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000627 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000628 return ndk::ScopedAStatus::ok();
629}
630
Mikhail Naganov74927202022-12-19 16:37:14 +0000631ndk::ScopedAStatus Module::getSupportedPlaybackRateFactors(
632 SupportedPlaybackRateFactors* _aidl_return) {
633 LOG(DEBUG) << __func__;
634 (void)_aidl_return;
635 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
636}
637
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000638ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
Mikhail Naganov16db9b72022-06-17 21:36:18 +0000639 LOG(DEBUG) << __func__ << ": requested patch " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000640 if (in_requested.sourcePortConfigIds.empty()) {
641 LOG(ERROR) << __func__ << ": requested patch has empty sources list";
642 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
643 }
644 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
645 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sources list";
646 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
647 }
648 if (in_requested.sinkPortConfigIds.empty()) {
649 LOG(ERROR) << __func__ << ": requested patch has empty sinks list";
650 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
651 }
652 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
653 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sinks list";
654 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
655 }
656
657 auto& configs = getConfig().portConfigs;
658 std::vector<int32_t> missingIds;
659 auto sources =
660 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
661 if (!missingIds.empty()) {
662 LOG(ERROR) << __func__ << ": following source port config ids not found: "
663 << ::android::internal::ToString(missingIds);
664 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
665 }
666 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
667 if (!missingIds.empty()) {
668 LOG(ERROR) << __func__ << ": following sink port config ids not found: "
669 << ::android::internal::ToString(missingIds);
670 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
671 }
672 // bool indicates whether a non-exclusive route is available.
673 // If only an exclusive route is available, that means the patch can not be
674 // established if there is any other patch which currently uses the sink port.
675 std::map<int32_t, bool> allowedSinkPorts;
676 auto& routes = getConfig().routes;
677 for (auto src : sources) {
678 for (const auto& r : routes) {
679 const auto& srcs = r.sourcePortIds;
680 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
681 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
682 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
683 }
684 }
685 }
686 }
687 for (auto sink : sinks) {
688 if (allowedSinkPorts.count(sink->portId) == 0) {
689 LOG(ERROR) << __func__ << ": there is no route to the sink port id " << sink->portId;
690 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
691 }
692 }
693
694 auto& patches = getConfig().patches;
695 auto existing = patches.end();
696 std::optional<decltype(mPatches)> patchesBackup;
697 if (in_requested.id != 0) {
698 existing = findById<AudioPatch>(patches, in_requested.id);
699 if (existing != patches.end()) {
700 patchesBackup = mPatches;
701 cleanUpPatch(existing->id);
702 } else {
703 LOG(ERROR) << __func__ << ": not found existing patch id " << in_requested.id;
704 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
705 }
706 }
707 // Validate the requested patch.
708 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
709 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
710 LOG(ERROR) << __func__ << ": sink port id " << sinkPortId
711 << "is exclusive and is already used by some other patch";
712 if (patchesBackup.has_value()) {
713 mPatches = std::move(*patchesBackup);
714 }
715 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
716 }
717 }
718 *_aidl_return = in_requested;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000719 _aidl_return->minimumStreamBufferSizeFrames = kMinimumStreamBufferSizeFrames;
720 _aidl_return->latenciesMs.clear();
721 _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
722 _aidl_return->sinkPortConfigIds.size(), kLatencyMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000723 AudioPatch oldPatch{};
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000724 if (existing == patches.end()) {
725 _aidl_return->id = getConfig().nextPatchId++;
726 patches.push_back(*_aidl_return);
727 existing = patches.begin() + (patches.size() - 1);
728 } else {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000729 oldPatch = *existing;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000730 *existing = *_aidl_return;
731 }
732 registerPatch(*existing);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000733 updateStreamsConnectedState(oldPatch, *_aidl_return);
734
735 LOG(DEBUG) << __func__ << ": " << (oldPatch.id == 0 ? "created" : "updated") << " patch "
736 << _aidl_return->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000737 return ndk::ScopedAStatus::ok();
738}
739
740ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
741 AudioPortConfig* out_suggested, bool* _aidl_return) {
742 LOG(DEBUG) << __func__ << ": requested " << in_requested.toString();
743 auto& configs = getConfig().portConfigs;
744 auto existing = configs.end();
745 if (in_requested.id != 0) {
746 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
747 existing == configs.end()) {
748 LOG(ERROR) << __func__ << ": existing port config id " << in_requested.id
749 << " not found";
750 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
751 }
752 }
753
754 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
755 if (portId == 0) {
756 LOG(ERROR) << __func__ << ": input port config does not specify portId";
757 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
758 }
759 auto& ports = getConfig().ports;
760 auto portIt = findById<AudioPort>(ports, portId);
761 if (portIt == ports.end()) {
762 LOG(ERROR) << __func__ << ": input port config points to non-existent portId " << portId;
763 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
764 }
765 if (existing != configs.end()) {
766 *out_suggested = *existing;
767 } else {
768 AudioPortConfig newConfig;
769 if (generateDefaultPortConfig(*portIt, &newConfig)) {
770 *out_suggested = newConfig;
771 } else {
772 LOG(ERROR) << __func__ << ": unable generate a default config for port " << portId;
773 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
774 }
775 }
776 // From this moment, 'out_suggested' is either an existing port config,
777 // or a new generated config. Now attempt to update it according to the specified
778 // fields of 'in_requested'.
779
780 bool requestedIsValid = true, requestedIsFullySpecified = true;
781
782 AudioIoFlags portFlags = portIt->flags;
783 if (in_requested.flags.has_value()) {
784 if (in_requested.flags.value() != portFlags) {
785 LOG(WARNING) << __func__ << ": requested flags "
786 << in_requested.flags.value().toString() << " do not match port's "
787 << portId << " flags " << portFlags.toString();
788 requestedIsValid = false;
789 }
790 } else {
791 requestedIsFullySpecified = false;
792 }
793
794 AudioProfile portProfile;
795 if (in_requested.format.has_value()) {
796 const auto& format = in_requested.format.value();
797 if (findAudioProfile(*portIt, format, &portProfile)) {
798 out_suggested->format = format;
799 } else {
800 LOG(WARNING) << __func__ << ": requested format " << format.toString()
801 << " is not found in port's " << portId << " profiles";
802 requestedIsValid = false;
803 }
804 } else {
805 requestedIsFullySpecified = false;
806 }
807 if (!findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
808 LOG(ERROR) << __func__ << ": port " << portId << " does not support format "
809 << out_suggested->format.value().toString() << " anymore";
810 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
811 }
812
813 if (in_requested.channelMask.has_value()) {
814 const auto& channelMask = in_requested.channelMask.value();
815 if (find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
816 portProfile.channelMasks.end()) {
817 out_suggested->channelMask = channelMask;
818 } else {
819 LOG(WARNING) << __func__ << ": requested channel mask " << channelMask.toString()
820 << " is not supported for the format " << portProfile.format.toString()
821 << " by the port " << portId;
822 requestedIsValid = false;
823 }
824 } else {
825 requestedIsFullySpecified = false;
826 }
827
828 if (in_requested.sampleRate.has_value()) {
829 const auto& sampleRate = in_requested.sampleRate.value();
830 if (find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
831 sampleRate.value) != portProfile.sampleRates.end()) {
832 out_suggested->sampleRate = sampleRate;
833 } else {
834 LOG(WARNING) << __func__ << ": requested sample rate " << sampleRate.value
835 << " is not supported for the format " << portProfile.format.toString()
836 << " by the port " << portId;
837 requestedIsValid = false;
838 }
839 } else {
840 requestedIsFullySpecified = false;
841 }
842
843 if (in_requested.gain.has_value()) {
844 // Let's pretend that gain can always be applied.
845 out_suggested->gain = in_requested.gain.value();
846 }
847
848 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
849 out_suggested->id = getConfig().nextPortId++;
850 configs.push_back(*out_suggested);
851 *_aidl_return = true;
852 LOG(DEBUG) << __func__ << ": created new port config " << out_suggested->toString();
853 } else if (existing != configs.end() && requestedIsValid) {
854 *existing = *out_suggested;
855 *_aidl_return = true;
856 LOG(DEBUG) << __func__ << ": updated port config " << out_suggested->toString();
857 } else {
858 LOG(DEBUG) << __func__ << ": not applied; existing config ? " << (existing != configs.end())
859 << "; requested is valid? " << requestedIsValid << ", fully specified? "
860 << requestedIsFullySpecified;
861 *_aidl_return = false;
862 }
863 return ndk::ScopedAStatus::ok();
864}
865
866ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
867 auto& patches = getConfig().patches;
868 auto patchIt = findById<AudioPatch>(patches, in_patchId);
869 if (patchIt != patches.end()) {
870 cleanUpPatch(patchIt->id);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000871 updateStreamsConnectedState(*patchIt, AudioPatch{});
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000872 patches.erase(patchIt);
873 LOG(DEBUG) << __func__ << ": erased patch " << in_patchId;
874 return ndk::ScopedAStatus::ok();
875 }
876 LOG(ERROR) << __func__ << ": patch id " << in_patchId << " not found";
877 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
878}
879
880ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
881 auto& configs = getConfig().portConfigs;
882 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
883 if (configIt != configs.end()) {
884 if (mStreams.count(in_portConfigId) != 0) {
885 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
886 << " has a stream opened on it";
887 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
888 }
889 auto patchIt = mPatches.find(in_portConfigId);
890 if (patchIt != mPatches.end()) {
891 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
892 << " is used by the patch with id " << patchIt->second;
893 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
894 }
895 auto& initials = getConfig().initialConfigs;
896 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
897 if (initialIt == initials.end()) {
898 configs.erase(configIt);
899 LOG(DEBUG) << __func__ << ": erased port config " << in_portConfigId;
900 } else if (*configIt != *initialIt) {
901 *configIt = *initialIt;
902 LOG(DEBUG) << __func__ << ": reset port config " << in_portConfigId;
903 }
904 return ndk::ScopedAStatus::ok();
905 }
906 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId << " not found";
907 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
908}
909
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000910ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) {
911 *_aidl_return = mMasterMute;
912 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
913 return ndk::ScopedAStatus::ok();
914}
915
916ndk::ScopedAStatus Module::setMasterMute(bool in_mute) {
917 LOG(DEBUG) << __func__ << ": " << in_mute;
918 mMasterMute = in_mute;
919 return ndk::ScopedAStatus::ok();
920}
921
922ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) {
923 *_aidl_return = mMasterVolume;
924 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
925 return ndk::ScopedAStatus::ok();
926}
927
928ndk::ScopedAStatus Module::setMasterVolume(float in_volume) {
929 LOG(DEBUG) << __func__ << ": " << in_volume;
930 if (in_volume >= 0.0f && in_volume <= 1.0f) {
931 mMasterVolume = in_volume;
932 return ndk::ScopedAStatus::ok();
933 }
934 LOG(ERROR) << __func__ << ": invalid master volume value: " << in_volume;
935 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
936}
937
938ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) {
939 *_aidl_return = mMicMute;
940 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
941 return ndk::ScopedAStatus::ok();
942}
943
944ndk::ScopedAStatus Module::setMicMute(bool in_mute) {
945 LOG(DEBUG) << __func__ << ": " << in_mute;
946 mMicMute = in_mute;
947 return ndk::ScopedAStatus::ok();
948}
949
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000950ndk::ScopedAStatus Module::getMicrophones(std::vector<MicrophoneInfo>* _aidl_return) {
951 *_aidl_return = mConfig->microphones;
952 LOG(DEBUG) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return);
953 return ndk::ScopedAStatus::ok();
954}
955
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000956ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) {
Mikhail Naganov04ae8222023-01-11 15:48:10 -0800957 if (!isValidAudioMode(in_mode)) {
958 LOG(ERROR) << __func__ << ": invalid mode " << toString(in_mode);
959 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
960 }
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000961 // No checks for supported audio modes here, it's an informative notification.
962 LOG(DEBUG) << __func__ << ": " << toString(in_mode);
963 return ndk::ScopedAStatus::ok();
964}
965
966ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) {
967 LOG(DEBUG) << __func__ << ": " << toString(in_rotation);
968 return ndk::ScopedAStatus::ok();
969}
970
971ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) {
972 LOG(DEBUG) << __func__ << ": " << in_isTurnedOn;
973 return ndk::ScopedAStatus::ok();
974}
975
Vlad Popa83a6d822022-11-07 13:53:57 +0100976ndk::ScopedAStatus Module::getSoundDose(std::shared_ptr<ISoundDose>* _aidl_return) {
Vlad Popa943b7e22022-12-08 14:24:12 +0100977 if (mSoundDose == nullptr) {
Vlad Popa2afbd1e2022-12-28 17:04:58 +0100978 mSoundDose = ndk::SharedRefBase::make<sounddose::SoundDose>();
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000979 mSoundDoseBinder = mSoundDose->asBinder();
980 AIBinder_setMinSchedulerPolicy(mSoundDoseBinder.get(), SCHED_NORMAL,
981 ANDROID_PRIORITY_AUDIO);
Vlad Popa943b7e22022-12-08 14:24:12 +0100982 }
983 *_aidl_return = mSoundDose;
984 LOG(DEBUG) << __func__ << ": returning instance of ISoundDose: " << _aidl_return->get();
Vlad Popa83a6d822022-11-07 13:53:57 +0100985 return ndk::ScopedAStatus::ok();
986}
987
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000988ndk::ScopedAStatus Module::generateHwAvSyncId(int32_t* _aidl_return) {
989 LOG(DEBUG) << __func__;
990 (void)_aidl_return;
991 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
992}
993
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000994const std::string Module::VendorDebug::kForceTransientBurstName = "aosp.forceTransientBurst";
Mikhail Naganov194daaa2023-01-05 22:34:20 +0000995const std::string Module::VendorDebug::kForceSynchronousDrainName = "aosp.forceSynchronousDrain";
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000996
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000997ndk::ScopedAStatus Module::getVendorParameters(const std::vector<std::string>& in_ids,
998 std::vector<VendorParameter>* _aidl_return) {
999 LOG(DEBUG) << __func__ << ": id count: " << in_ids.size();
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001000 bool allParametersKnown = true;
1001 for (const auto& id : in_ids) {
1002 if (id == VendorDebug::kForceTransientBurstName) {
1003 VendorParameter forceTransientBurst{.id = id};
1004 forceTransientBurst.ext.setParcelable(Boolean{mVendorDebug.forceTransientBurst});
1005 _aidl_return->push_back(std::move(forceTransientBurst));
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001006 } else if (id == VendorDebug::kForceSynchronousDrainName) {
1007 VendorParameter forceSynchronousDrain{.id = id};
1008 forceSynchronousDrain.ext.setParcelable(Boolean{mVendorDebug.forceSynchronousDrain});
1009 _aidl_return->push_back(std::move(forceSynchronousDrain));
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001010 } else {
1011 allParametersKnown = false;
1012 LOG(ERROR) << __func__ << ": unrecognized parameter \"" << id << "\"";
1013 }
1014 }
1015 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1016 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001017}
1018
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001019namespace {
1020
1021template <typename W>
1022bool extractParameter(const VendorParameter& p, decltype(W::value)* v) {
1023 std::optional<W> value;
1024 binder_status_t result = p.ext.getParcelable(&value);
1025 if (result == STATUS_OK && value.has_value()) {
1026 *v = value.value().value;
1027 return true;
1028 }
1029 LOG(ERROR) << __func__ << ": failed to read the value of the parameter \"" << p.id
1030 << "\": " << result;
1031 return false;
1032}
1033
1034} // namespace
1035
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001036ndk::ScopedAStatus Module::setVendorParameters(const std::vector<VendorParameter>& in_parameters,
1037 bool in_async) {
1038 LOG(DEBUG) << __func__ << ": parameter count " << in_parameters.size()
1039 << ", async: " << in_async;
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001040 bool allParametersKnown = true;
1041 for (const auto& p : in_parameters) {
1042 if (p.id == VendorDebug::kForceTransientBurstName) {
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001043 if (!extractParameter<Boolean>(p, &mVendorDebug.forceTransientBurst)) {
1044 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1045 }
1046 } else if (p.id == VendorDebug::kForceSynchronousDrainName) {
1047 if (!extractParameter<Boolean>(p, &mVendorDebug.forceSynchronousDrain)) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001048 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1049 }
1050 } else {
1051 allParametersKnown = false;
1052 LOG(ERROR) << __func__ << ": unrecognized parameter \"" << p.id << "\"";
1053 }
1054 }
1055 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1056 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001057}
1058
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001059ndk::ScopedAStatus Module::addDeviceEffect(
1060 int32_t in_portConfigId,
1061 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1062 if (in_effect == nullptr) {
1063 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect";
1064 } else {
1065 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder "
1066 << in_effect->asBinder().get();
1067 }
1068 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1069}
1070
1071ndk::ScopedAStatus Module::removeDeviceEffect(
1072 int32_t in_portConfigId,
1073 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1074 if (in_effect == nullptr) {
1075 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect";
1076 } else {
1077 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder "
1078 << in_effect->asBinder().get();
1079 }
1080 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1081}
1082
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001083} // namespace aidl::android::hardware::audio::core