blob: 1bf7321f15016bed421e7a8e44831287e1811570 [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>
22
23#include <aidl/android/media/audio/common/AudioOutputFlags.h>
24
25#include "core-impl/Module.h"
26#include "core-impl/utils.h"
27
28using aidl::android::hardware::audio::common::SinkMetadata;
29using aidl::android::hardware::audio::common::SourceMetadata;
30using aidl::android::media::audio::common::AudioFormatDescription;
31using aidl::android::media::audio::common::AudioIoFlags;
32using aidl::android::media::audio::common::AudioOffloadInfo;
33using aidl::android::media::audio::common::AudioOutputFlags;
34using aidl::android::media::audio::common::AudioPort;
35using aidl::android::media::audio::common::AudioPortConfig;
36using aidl::android::media::audio::common::AudioPortExt;
37using aidl::android::media::audio::common::AudioProfile;
38using aidl::android::media::audio::common::Int;
39
40namespace aidl::android::hardware::audio::core {
41
42namespace {
43
44bool generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) {
45 *config = {};
46 config->portId = port.id;
47 if (port.profiles.empty()) {
48 LOG(ERROR) << __func__ << ": port " << port.id << " has no profiles";
49 return false;
50 }
51 const auto& profile = port.profiles.begin();
52 config->format = profile->format;
53 if (profile->channelMasks.empty()) {
54 LOG(ERROR) << __func__ << ": the first profile in port " << port.id
55 << " has no channel masks";
56 return false;
57 }
58 config->channelMask = *profile->channelMasks.begin();
59 if (profile->sampleRates.empty()) {
60 LOG(ERROR) << __func__ << ": the first profile in port " << port.id
61 << " has no sample rates";
62 return false;
63 }
64 Int sampleRate;
65 sampleRate.value = *profile->sampleRates.begin();
66 config->sampleRate = sampleRate;
67 config->flags = port.flags;
68 config->ext = port.ext;
69 return true;
70}
71
72bool findAudioProfile(const AudioPort& port, const AudioFormatDescription& format,
73 AudioProfile* profile) {
74 if (auto profilesIt =
75 find_if(port.profiles.begin(), port.profiles.end(),
76 [&format](const auto& profile) { return profile.format == format; });
77 profilesIt != port.profiles.end()) {
78 *profile = *profilesIt;
79 return true;
80 }
81 return false;
82}
Mikhail Naganov00603d12022-05-02 22:52:13 +000083
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000084} // namespace
85
86void Module::cleanUpPatch(int32_t patchId) {
87 erase_all_values(mPatches, std::set<int32_t>{patchId});
88}
89
90void Module::cleanUpPatches(int32_t portConfigId) {
91 auto& patches = getConfig().patches;
92 if (patches.size() == 0) return;
93 auto range = mPatches.equal_range(portConfigId);
94 for (auto it = range.first; it != range.second; ++it) {
95 auto patchIt = findById<AudioPatch>(patches, it->second);
96 if (patchIt != patches.end()) {
97 erase_if(patchIt->sourcePortConfigIds,
98 [portConfigId](auto e) { return e == portConfigId; });
99 erase_if(patchIt->sinkPortConfigIds,
100 [portConfigId](auto e) { return e == portConfigId; });
101 }
102 }
103 std::set<int32_t> erasedPatches;
104 for (size_t i = patches.size() - 1; i != 0; --i) {
105 const auto& patch = patches[i];
106 if (patch.sourcePortConfigIds.empty() || patch.sinkPortConfigIds.empty()) {
107 erasedPatches.insert(patch.id);
108 patches.erase(patches.begin() + i);
109 }
110 }
111 erase_all_values(mPatches, erasedPatches);
112}
113
114internal::Configuration& Module::getConfig() {
115 if (!mConfig) {
116 mConfig.reset(new internal::Configuration(internal::getNullPrimaryConfiguration()));
117 }
118 return *mConfig;
119}
120
121void Module::registerPatch(const AudioPatch& patch) {
122 auto& configs = getConfig().portConfigs;
123 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
124 for (auto portConfigId : portConfigIds) {
125 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
126 if (configIt != configs.end()) {
127 mPatches.insert(std::pair{portConfigId, patch.id});
128 if (configIt->portId != portConfigId) {
129 mPatches.insert(std::pair{configIt->portId, patch.id});
130 }
131 }
132 };
133 };
134 do_insert(patch.sourcePortConfigIds);
135 do_insert(patch.sinkPortConfigIds);
136}
137
Mikhail Naganov00603d12022-05-02 22:52:13 +0000138ndk::ScopedAStatus Module::setModuleDebug(
139 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
140 LOG(DEBUG) << __func__ << ": old flags:" << mDebug.toString()
141 << ", new flags: " << in_debug.toString();
142 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
143 !mConnectedDevicePorts.empty()) {
144 LOG(ERROR) << __func__ << ": attempting to change device connections simulation "
145 << "while having external devices connected";
146 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
147 }
148 mDebug = in_debug;
149 return ndk::ScopedAStatus::ok();
150}
151
152ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
153 AudioPort* _aidl_return) {
154 const int32_t templateId = in_templateIdAndAdditionalData.id;
155 auto& ports = getConfig().ports;
156 AudioPort connectedPort;
157 { // Scope the template port so that we don't accidentally modify it.
158 auto templateIt = findById<AudioPort>(ports, templateId);
159 if (templateIt == ports.end()) {
160 LOG(ERROR) << __func__ << ": port id " << templateId << " not found";
161 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
162 }
163 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
164 LOG(ERROR) << __func__ << ": port id " << templateId << " is not a device port";
165 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
166 }
167 if (!templateIt->profiles.empty()) {
168 LOG(ERROR) << __func__ << ": port id " << templateId
169 << " does not have dynamic profiles";
170 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
171 }
172 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
173 if (templateDevicePort.device.type.connection.empty()) {
174 LOG(ERROR) << __func__ << ": port id " << templateId << " is permanently attached";
175 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
176 }
177 // Postpone id allocation until we ensure that there are no client errors.
178 connectedPort = *templateIt;
179 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
180 const auto& inputDevicePort =
181 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
182 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
183 connectedDevicePort.device.address = inputDevicePort.device.address;
184 LOG(DEBUG) << __func__ << ": device port " << connectedPort.id << " device set to "
185 << connectedDevicePort.device.toString();
186 // Check if there is already a connected port with for the same external device.
187 for (auto connectedPortId : mConnectedDevicePorts) {
188 auto connectedPortIt = findById<AudioPort>(ports, connectedPortId);
189 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
190 connectedDevicePort.device) {
191 LOG(ERROR) << __func__ << ": device " << connectedDevicePort.device.toString()
192 << " is already connected at the device port id " << connectedPortId;
193 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
194 }
195 }
196 }
197
198 if (!mDebug.simulateDeviceConnections) {
199 // In a real HAL here we would attempt querying the profiles from the device.
200 LOG(ERROR) << __func__ << ": failed to query supported device profiles";
201 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
202 }
203
204 connectedPort.id = ++getConfig().nextPortId;
205 mConnectedDevicePorts.insert(connectedPort.id);
206 LOG(DEBUG) << __func__ << ": template port " << templateId << " external device connected, "
207 << "connected port ID " << connectedPort.id;
208 auto& connectedProfiles = getConfig().connectedProfiles;
209 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
210 connectedProfilesIt != connectedProfiles.end()) {
211 connectedPort.profiles = connectedProfilesIt->second;
212 }
213 ports.push_back(connectedPort);
214 *_aidl_return = std::move(connectedPort);
215
216 std::vector<AudioRoute> newRoutes;
217 auto& routes = getConfig().routes;
218 for (auto& r : routes) {
219 if (r.sinkPortId == templateId) {
220 AudioRoute newRoute;
221 newRoute.sourcePortIds = r.sourcePortIds;
222 newRoute.sinkPortId = connectedPort.id;
223 newRoute.isExclusive = r.isExclusive;
224 newRoutes.push_back(std::move(newRoute));
225 } else {
226 auto& srcs = r.sourcePortIds;
227 if (std::find(srcs.begin(), srcs.end(), templateId) != srcs.end()) {
228 srcs.push_back(connectedPort.id);
229 }
230 }
231 }
232 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
233
234 return ndk::ScopedAStatus::ok();
235}
236
237ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
238 auto& ports = getConfig().ports;
239 auto portIt = findById<AudioPort>(ports, in_portId);
240 if (portIt == ports.end()) {
241 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
242 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
243 }
244 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
245 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a device port";
246 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
247 }
248 if (mConnectedDevicePorts.count(in_portId) == 0) {
249 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a connected device port";
250 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
251 }
252 auto& configs = getConfig().portConfigs;
253 auto& initials = getConfig().initialConfigs;
254 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
255 if (config.portId == in_portId) {
256 // Check if the configuration was provided by the client.
257 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
258 return initialIt == initials.end() || config != *initialIt;
259 }
260 return false;
261 });
262 if (configIt != configs.end()) {
263 LOG(ERROR) << __func__ << ": port id " << in_portId << " has a non-default config with id "
264 << configIt->id;
265 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
266 }
267 ports.erase(portIt);
268 mConnectedDevicePorts.erase(in_portId);
269 LOG(DEBUG) << __func__ << ": connected device port " << in_portId << " released";
270
271 auto& routes = getConfig().routes;
272 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
273 if (routesIt->sinkPortId == in_portId) {
274 routesIt = routes.erase(routesIt);
275 } else {
276 // Note: the list of sourcePortIds can't become empty because there must
277 // be the id of the template port in the route.
278 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
279 ++routesIt;
280 }
281 }
282
283 return ndk::ScopedAStatus::ok();
284}
285
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000286ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
287 *_aidl_return = getConfig().patches;
288 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " patches";
289 return ndk::ScopedAStatus::ok();
290}
291
292ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
293 auto& ports = getConfig().ports;
294 auto portIt = findById<AudioPort>(ports, in_portId);
295 if (portIt != ports.end()) {
296 *_aidl_return = *portIt;
297 LOG(DEBUG) << __func__ << ": returning port by id " << in_portId;
298 return ndk::ScopedAStatus::ok();
299 }
300 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
301 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
302}
303
304ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
305 *_aidl_return = getConfig().portConfigs;
306 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " port configs";
307 return ndk::ScopedAStatus::ok();
308}
309
310ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
311 *_aidl_return = getConfig().ports;
312 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " ports";
313 return ndk::ScopedAStatus::ok();
314}
315
316ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
317 *_aidl_return = getConfig().routes;
318 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " routes";
319 return ndk::ScopedAStatus::ok();
320}
321
Mikhail Naganov00603d12022-05-02 22:52:13 +0000322ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
323 std::vector<AudioRoute>* _aidl_return) {
324 auto& ports = getConfig().ports;
325 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
326 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
327 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
328 }
329 auto& routes = getConfig().routes;
330 std::copy_if(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
331 [&](const auto& r) {
332 const auto& srcs = r.sourcePortIds;
333 return r.sinkPortId == in_portId ||
334 std::find(srcs.begin(), srcs.end(), in_portId) != srcs.end();
335 });
336 return ndk::ScopedAStatus::ok();
337}
338
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000339ndk::ScopedAStatus Module::openInputStream(int32_t in_portConfigId,
340 const SinkMetadata& in_sinkMetadata,
341 std::shared_ptr<IStreamIn>* _aidl_return) {
342 auto& configs = getConfig().portConfigs;
343 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
344 if (portConfigIt == configs.end()) {
345 LOG(ERROR) << __func__ << ": existing port config id " << in_portConfigId << " not found";
346 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
347 }
348 const int32_t portId = portConfigIt->portId;
349 // In our implementation, configs of mix ports always have unique IDs.
350 CHECK(portId != in_portConfigId);
351 auto& ports = getConfig().ports;
352 auto portIt = findById<AudioPort>(ports, portId);
353 if (portIt == ports.end()) {
354 LOG(ERROR) << __func__ << ": port id " << portId << " used by port config id "
355 << in_portConfigId << " not found";
356 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
357 }
358 if (portIt->flags.getTag() != AudioIoFlags::Tag::input ||
359 portIt->ext.getTag() != AudioPortExt::Tag::mix) {
360 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
361 << " does not correspond to an input mix port";
362 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
363 }
364 if (mStreams.count(in_portConfigId) != 0) {
365 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
366 << " already has a stream opened on it";
367 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
368 }
369 const int32_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
370 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
371 LOG(ERROR) << __func__ << ": port id " << portId
372 << " has already reached maximum allowed opened stream count: "
373 << maxOpenStreamCount;
374 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
375 }
376 auto stream = ndk::SharedRefBase::make<StreamIn>(in_sinkMetadata);
377 mStreams.insert(portId, in_portConfigId, StreamWrapper(stream));
378 *_aidl_return = std::move(stream);
379 return ndk::ScopedAStatus::ok();
380}
381
382ndk::ScopedAStatus Module::openOutputStream(int32_t in_portConfigId,
383 const SourceMetadata& in_sourceMetadata,
384 const std::optional<AudioOffloadInfo>& in_offloadInfo,
385 std::shared_ptr<IStreamOut>* _aidl_return) {
386 auto& configs = getConfig().portConfigs;
387 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
388 if (portConfigIt == configs.end()) {
389 LOG(ERROR) << __func__ << ": existing port config id " << in_portConfigId << " not found";
390 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
391 }
392 const int32_t portId = portConfigIt->portId;
393 // In our implementation, configs of mix ports always have unique IDs.
394 CHECK(portId != in_portConfigId);
395 auto& ports = getConfig().ports;
396 auto portIt = findById<AudioPort>(ports, portId);
397 if (portIt == ports.end()) {
398 LOG(ERROR) << __func__ << ": port id " << portId << " used by port config id "
399 << in_portConfigId << " not found";
400 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
401 }
402 if (portIt->flags.getTag() != AudioIoFlags::Tag::output ||
403 portIt->ext.getTag() != AudioPortExt::Tag::mix) {
404 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
405 << " does not correspond to an output mix port";
406 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
407 }
408 if (mStreams.count(in_portConfigId) != 0) {
409 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
410 << " already has a stream opened on it";
411 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
412 }
413 const int32_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
414 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
415 LOG(ERROR) << __func__ << ": port id " << portId
416 << " has already reached maximum allowed opened stream count: "
417 << maxOpenStreamCount;
418 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
419 }
420 auto stream = ndk::SharedRefBase::make<StreamOut>(in_sourceMetadata, in_offloadInfo);
421 mStreams.insert(portId, in_portConfigId, StreamWrapper(stream));
422 *_aidl_return = std::move(stream);
423 return ndk::ScopedAStatus::ok();
424}
425
426ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
Mikhail Naganov16db9b72022-06-17 21:36:18 +0000427 LOG(DEBUG) << __func__ << ": requested patch " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000428 if (in_requested.sourcePortConfigIds.empty()) {
429 LOG(ERROR) << __func__ << ": requested patch has empty sources list";
430 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
431 }
432 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
433 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sources list";
434 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
435 }
436 if (in_requested.sinkPortConfigIds.empty()) {
437 LOG(ERROR) << __func__ << ": requested patch has empty sinks list";
438 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
439 }
440 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
441 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sinks list";
442 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
443 }
444
445 auto& configs = getConfig().portConfigs;
446 std::vector<int32_t> missingIds;
447 auto sources =
448 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
449 if (!missingIds.empty()) {
450 LOG(ERROR) << __func__ << ": following source port config ids not found: "
451 << ::android::internal::ToString(missingIds);
452 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
453 }
454 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
455 if (!missingIds.empty()) {
456 LOG(ERROR) << __func__ << ": following sink port config ids not found: "
457 << ::android::internal::ToString(missingIds);
458 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
459 }
460 // bool indicates whether a non-exclusive route is available.
461 // If only an exclusive route is available, that means the patch can not be
462 // established if there is any other patch which currently uses the sink port.
463 std::map<int32_t, bool> allowedSinkPorts;
464 auto& routes = getConfig().routes;
465 for (auto src : sources) {
466 for (const auto& r : routes) {
467 const auto& srcs = r.sourcePortIds;
468 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
469 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
470 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
471 }
472 }
473 }
474 }
475 for (auto sink : sinks) {
476 if (allowedSinkPorts.count(sink->portId) == 0) {
477 LOG(ERROR) << __func__ << ": there is no route to the sink port id " << sink->portId;
478 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
479 }
480 }
481
482 auto& patches = getConfig().patches;
483 auto existing = patches.end();
484 std::optional<decltype(mPatches)> patchesBackup;
485 if (in_requested.id != 0) {
486 existing = findById<AudioPatch>(patches, in_requested.id);
487 if (existing != patches.end()) {
488 patchesBackup = mPatches;
489 cleanUpPatch(existing->id);
490 } else {
491 LOG(ERROR) << __func__ << ": not found existing patch id " << in_requested.id;
492 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
493 }
494 }
495 // Validate the requested patch.
496 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
497 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
498 LOG(ERROR) << __func__ << ": sink port id " << sinkPortId
499 << "is exclusive and is already used by some other patch";
500 if (patchesBackup.has_value()) {
501 mPatches = std::move(*patchesBackup);
502 }
503 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
504 }
505 }
506 *_aidl_return = in_requested;
507 if (existing == patches.end()) {
508 _aidl_return->id = getConfig().nextPatchId++;
509 patches.push_back(*_aidl_return);
510 existing = patches.begin() + (patches.size() - 1);
511 } else {
512 *existing = *_aidl_return;
513 }
514 registerPatch(*existing);
515 LOG(DEBUG) << __func__ << ": created or updated patch id " << _aidl_return->id;
516 return ndk::ScopedAStatus::ok();
517}
518
519ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
520 AudioPortConfig* out_suggested, bool* _aidl_return) {
521 LOG(DEBUG) << __func__ << ": requested " << in_requested.toString();
522 auto& configs = getConfig().portConfigs;
523 auto existing = configs.end();
524 if (in_requested.id != 0) {
525 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
526 existing == configs.end()) {
527 LOG(ERROR) << __func__ << ": existing port config id " << in_requested.id
528 << " not found";
529 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
530 }
531 }
532
533 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
534 if (portId == 0) {
535 LOG(ERROR) << __func__ << ": input port config does not specify portId";
536 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
537 }
538 auto& ports = getConfig().ports;
539 auto portIt = findById<AudioPort>(ports, portId);
540 if (portIt == ports.end()) {
541 LOG(ERROR) << __func__ << ": input port config points to non-existent portId " << portId;
542 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
543 }
544 if (existing != configs.end()) {
545 *out_suggested = *existing;
546 } else {
547 AudioPortConfig newConfig;
548 if (generateDefaultPortConfig(*portIt, &newConfig)) {
549 *out_suggested = newConfig;
550 } else {
551 LOG(ERROR) << __func__ << ": unable generate a default config for port " << portId;
552 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
553 }
554 }
555 // From this moment, 'out_suggested' is either an existing port config,
556 // or a new generated config. Now attempt to update it according to the specified
557 // fields of 'in_requested'.
558
559 bool requestedIsValid = true, requestedIsFullySpecified = true;
560
561 AudioIoFlags portFlags = portIt->flags;
562 if (in_requested.flags.has_value()) {
563 if (in_requested.flags.value() != portFlags) {
564 LOG(WARNING) << __func__ << ": requested flags "
565 << in_requested.flags.value().toString() << " do not match port's "
566 << portId << " flags " << portFlags.toString();
567 requestedIsValid = false;
568 }
569 } else {
570 requestedIsFullySpecified = false;
571 }
572
573 AudioProfile portProfile;
574 if (in_requested.format.has_value()) {
575 const auto& format = in_requested.format.value();
576 if (findAudioProfile(*portIt, format, &portProfile)) {
577 out_suggested->format = format;
578 } else {
579 LOG(WARNING) << __func__ << ": requested format " << format.toString()
580 << " is not found in port's " << portId << " profiles";
581 requestedIsValid = false;
582 }
583 } else {
584 requestedIsFullySpecified = false;
585 }
586 if (!findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
587 LOG(ERROR) << __func__ << ": port " << portId << " does not support format "
588 << out_suggested->format.value().toString() << " anymore";
589 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
590 }
591
592 if (in_requested.channelMask.has_value()) {
593 const auto& channelMask = in_requested.channelMask.value();
594 if (find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
595 portProfile.channelMasks.end()) {
596 out_suggested->channelMask = channelMask;
597 } else {
598 LOG(WARNING) << __func__ << ": requested channel mask " << channelMask.toString()
599 << " is not supported for the format " << portProfile.format.toString()
600 << " by the port " << portId;
601 requestedIsValid = false;
602 }
603 } else {
604 requestedIsFullySpecified = false;
605 }
606
607 if (in_requested.sampleRate.has_value()) {
608 const auto& sampleRate = in_requested.sampleRate.value();
609 if (find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
610 sampleRate.value) != portProfile.sampleRates.end()) {
611 out_suggested->sampleRate = sampleRate;
612 } else {
613 LOG(WARNING) << __func__ << ": requested sample rate " << sampleRate.value
614 << " is not supported for the format " << portProfile.format.toString()
615 << " by the port " << portId;
616 requestedIsValid = false;
617 }
618 } else {
619 requestedIsFullySpecified = false;
620 }
621
622 if (in_requested.gain.has_value()) {
623 // Let's pretend that gain can always be applied.
624 out_suggested->gain = in_requested.gain.value();
625 }
626
627 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
628 out_suggested->id = getConfig().nextPortId++;
629 configs.push_back(*out_suggested);
630 *_aidl_return = true;
631 LOG(DEBUG) << __func__ << ": created new port config " << out_suggested->toString();
632 } else if (existing != configs.end() && requestedIsValid) {
633 *existing = *out_suggested;
634 *_aidl_return = true;
635 LOG(DEBUG) << __func__ << ": updated port config " << out_suggested->toString();
636 } else {
637 LOG(DEBUG) << __func__ << ": not applied; existing config ? " << (existing != configs.end())
638 << "; requested is valid? " << requestedIsValid << ", fully specified? "
639 << requestedIsFullySpecified;
640 *_aidl_return = false;
641 }
642 return ndk::ScopedAStatus::ok();
643}
644
645ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
646 auto& patches = getConfig().patches;
647 auto patchIt = findById<AudioPatch>(patches, in_patchId);
648 if (patchIt != patches.end()) {
649 cleanUpPatch(patchIt->id);
650 patches.erase(patchIt);
651 LOG(DEBUG) << __func__ << ": erased patch " << in_patchId;
652 return ndk::ScopedAStatus::ok();
653 }
654 LOG(ERROR) << __func__ << ": patch id " << in_patchId << " not found";
655 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
656}
657
658ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
659 auto& configs = getConfig().portConfigs;
660 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
661 if (configIt != configs.end()) {
662 if (mStreams.count(in_portConfigId) != 0) {
663 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
664 << " has a stream opened on it";
665 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
666 }
667 auto patchIt = mPatches.find(in_portConfigId);
668 if (patchIt != mPatches.end()) {
669 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
670 << " is used by the patch with id " << patchIt->second;
671 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
672 }
673 auto& initials = getConfig().initialConfigs;
674 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
675 if (initialIt == initials.end()) {
676 configs.erase(configIt);
677 LOG(DEBUG) << __func__ << ": erased port config " << in_portConfigId;
678 } else if (*configIt != *initialIt) {
679 *configIt = *initialIt;
680 LOG(DEBUG) << __func__ << ": reset port config " << in_portConfigId;
681 }
682 return ndk::ScopedAStatus::ok();
683 }
684 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId << " not found";
685 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
686}
687
688} // namespace aidl::android::hardware::audio::core