blob: deaca4998966519c0fd95fe12e5f76d90ae05808 [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
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000023#include <Utils.h>
24#include <aidl/android/media/audio/common/AudioInputFlags.h>
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000025#include <aidl/android/media/audio/common/AudioOutputFlags.h>
26
27#include "core-impl/Module.h"
28#include "core-impl/utils.h"
29
30using aidl::android::hardware::audio::common::SinkMetadata;
31using aidl::android::hardware::audio::common::SourceMetadata;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000032using aidl::android::media::audio::common::AudioChannelLayout;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000033using aidl::android::media::audio::common::AudioFormatDescription;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000034using aidl::android::media::audio::common::AudioFormatType;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000035using aidl::android::media::audio::common::AudioInputFlags;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000036using aidl::android::media::audio::common::AudioIoFlags;
37using aidl::android::media::audio::common::AudioOffloadInfo;
38using aidl::android::media::audio::common::AudioOutputFlags;
39using aidl::android::media::audio::common::AudioPort;
40using aidl::android::media::audio::common::AudioPortConfig;
41using aidl::android::media::audio::common::AudioPortExt;
42using aidl::android::media::audio::common::AudioProfile;
43using aidl::android::media::audio::common::Int;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000044using aidl::android::media::audio::common::PcmType;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000045using android::hardware::audio::common::getFrameSizeInBytes;
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +000046using android::hardware::audio::common::isBitPositionFlagSet;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000047
48namespace aidl::android::hardware::audio::core {
49
50namespace {
51
52bool generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) {
53 *config = {};
54 config->portId = port.id;
55 if (port.profiles.empty()) {
56 LOG(ERROR) << __func__ << ": port " << port.id << " has no profiles";
57 return false;
58 }
59 const auto& profile = port.profiles.begin();
60 config->format = profile->format;
61 if (profile->channelMasks.empty()) {
62 LOG(ERROR) << __func__ << ": the first profile in port " << port.id
63 << " has no channel masks";
64 return false;
65 }
66 config->channelMask = *profile->channelMasks.begin();
67 if (profile->sampleRates.empty()) {
68 LOG(ERROR) << __func__ << ": the first profile in port " << port.id
69 << " has no sample rates";
70 return false;
71 }
72 Int sampleRate;
73 sampleRate.value = *profile->sampleRates.begin();
74 config->sampleRate = sampleRate;
75 config->flags = port.flags;
76 config->ext = port.ext;
77 return true;
78}
79
80bool findAudioProfile(const AudioPort& port, const AudioFormatDescription& format,
81 AudioProfile* profile) {
82 if (auto profilesIt =
83 find_if(port.profiles.begin(), port.profiles.end(),
84 [&format](const auto& profile) { return profile.format == format; });
85 profilesIt != port.profiles.end()) {
86 *profile = *profilesIt;
87 return true;
88 }
89 return false;
90}
Mikhail Naganov00603d12022-05-02 22:52:13 +000091
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000092} // namespace
93
94void Module::cleanUpPatch(int32_t patchId) {
95 erase_all_values(mPatches, std::set<int32_t>{patchId});
96}
97
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000098ndk::ScopedAStatus Module::createStreamContext(int32_t in_portConfigId, int64_t in_bufferSizeFrames,
99 StreamContext* out_context) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000100 if (in_bufferSizeFrames <= 0) {
101 LOG(ERROR) << __func__ << ": non-positive buffer size " << in_bufferSizeFrames;
102 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
103 }
104 if (in_bufferSizeFrames < kMinimumStreamBufferSizeFrames) {
105 LOG(ERROR) << __func__ << ": insufficient buffer size " << in_bufferSizeFrames
106 << ", must be at least " << kMinimumStreamBufferSizeFrames;
107 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
108 }
109 auto& configs = getConfig().portConfigs;
110 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000111 // Since this is a private method, it is assumed that
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000112 // validity of the portConfigId has already been checked.
113 const size_t frameSize =
114 getFrameSizeInBytes(portConfigIt->format.value(), portConfigIt->channelMask.value());
115 if (frameSize == 0) {
116 LOG(ERROR) << __func__ << ": could not calculate frame size for port config "
117 << portConfigIt->toString();
118 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
119 }
120 LOG(DEBUG) << __func__ << ": frame size " << frameSize << " bytes";
121 if (frameSize > kMaximumStreamBufferSizeBytes / in_bufferSizeFrames) {
122 LOG(ERROR) << __func__ << ": buffer size " << in_bufferSizeFrames
123 << " frames is too large, maximum size is "
124 << kMaximumStreamBufferSizeBytes / frameSize;
125 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
126 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000127 const auto& flags = portConfigIt->flags.value();
128 if ((flags.getTag() == AudioIoFlags::Tag::input &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000129 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::input>(),
130 AudioInputFlags::MMAP_NOIRQ)) ||
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000131 (flags.getTag() == AudioIoFlags::Tag::output &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000132 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::output>(),
133 AudioOutputFlags::MMAP_NOIRQ))) {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000134 StreamContext temp(
135 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
136 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
137 frameSize,
138 std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames));
139 if (temp.isValid()) {
140 *out_context = std::move(temp);
141 } else {
142 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
143 }
144 } else {
145 // TODO: Implement simulation of MMAP buffer allocation
146 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000147 return ndk::ScopedAStatus::ok();
148}
149
150ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) {
151 auto& configs = getConfig().portConfigs;
152 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
153 if (portConfigIt == configs.end()) {
154 LOG(ERROR) << __func__ << ": existing port config id " << in_portConfigId << " not found";
155 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
156 }
157 const int32_t portId = portConfigIt->portId;
158 // In our implementation, configs of mix ports always have unique IDs.
159 CHECK(portId != in_portConfigId);
160 auto& ports = getConfig().ports;
161 auto portIt = findById<AudioPort>(ports, portId);
162 if (portIt == ports.end()) {
163 LOG(ERROR) << __func__ << ": port id " << portId << " used by port config id "
164 << in_portConfigId << " not found";
165 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
166 }
167 if (mStreams.count(in_portConfigId) != 0) {
168 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
169 << " already has a stream opened on it";
170 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
171 }
172 if (portIt->ext.getTag() != AudioPortExt::Tag::mix) {
173 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
174 << " does not correspond to a mix port";
175 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
176 }
177 const int32_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
178 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
179 LOG(ERROR) << __func__ << ": port id " << portId
180 << " has already reached maximum allowed opened stream count: "
181 << maxOpenStreamCount;
182 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
183 }
184 *port = &(*portIt);
185 return ndk::ScopedAStatus::ok();
186}
187
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000188internal::Configuration& Module::getConfig() {
189 if (!mConfig) {
190 mConfig.reset(new internal::Configuration(internal::getNullPrimaryConfiguration()));
191 }
192 return *mConfig;
193}
194
195void Module::registerPatch(const AudioPatch& patch) {
196 auto& configs = getConfig().portConfigs;
197 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
198 for (auto portConfigId : portConfigIds) {
199 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
200 if (configIt != configs.end()) {
201 mPatches.insert(std::pair{portConfigId, patch.id});
202 if (configIt->portId != portConfigId) {
203 mPatches.insert(std::pair{configIt->portId, patch.id});
204 }
205 }
206 };
207 };
208 do_insert(patch.sourcePortConfigIds);
209 do_insert(patch.sinkPortConfigIds);
210}
211
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000212void Module::updateStreamsConnectedState(const AudioPatch& oldPatch, const AudioPatch& newPatch) {
213 // Streams from the old patch need to be disconnected, streams from the new
214 // patch need to be connected. If the stream belongs to both patches, no need
215 // to update it.
216 std::set<int32_t> idsToDisconnect, idsToConnect;
217 idsToDisconnect.insert(oldPatch.sourcePortConfigIds.begin(),
218 oldPatch.sourcePortConfigIds.end());
219 idsToDisconnect.insert(oldPatch.sinkPortConfigIds.begin(), oldPatch.sinkPortConfigIds.end());
220 idsToConnect.insert(newPatch.sourcePortConfigIds.begin(), newPatch.sourcePortConfigIds.end());
221 idsToConnect.insert(newPatch.sinkPortConfigIds.begin(), newPatch.sinkPortConfigIds.end());
222 std::for_each(idsToDisconnect.begin(), idsToDisconnect.end(), [&](const auto& portConfigId) {
223 if (idsToConnect.count(portConfigId) == 0) {
224 mStreams.setStreamIsConnected(portConfigId, false);
225 }
226 });
227 std::for_each(idsToConnect.begin(), idsToConnect.end(), [&](const auto& portConfigId) {
228 if (idsToDisconnect.count(portConfigId) == 0) {
229 mStreams.setStreamIsConnected(portConfigId, true);
230 }
231 });
232}
233
Mikhail Naganov00603d12022-05-02 22:52:13 +0000234ndk::ScopedAStatus Module::setModuleDebug(
235 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
236 LOG(DEBUG) << __func__ << ": old flags:" << mDebug.toString()
237 << ", new flags: " << in_debug.toString();
238 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
239 !mConnectedDevicePorts.empty()) {
240 LOG(ERROR) << __func__ << ": attempting to change device connections simulation "
241 << "while having external devices connected";
242 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
243 }
244 mDebug = in_debug;
245 return ndk::ScopedAStatus::ok();
246}
247
248ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
249 AudioPort* _aidl_return) {
250 const int32_t templateId = in_templateIdAndAdditionalData.id;
251 auto& ports = getConfig().ports;
252 AudioPort connectedPort;
253 { // Scope the template port so that we don't accidentally modify it.
254 auto templateIt = findById<AudioPort>(ports, templateId);
255 if (templateIt == ports.end()) {
256 LOG(ERROR) << __func__ << ": port id " << templateId << " not found";
257 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
258 }
259 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
260 LOG(ERROR) << __func__ << ": port id " << templateId << " is not a device port";
261 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
262 }
263 if (!templateIt->profiles.empty()) {
264 LOG(ERROR) << __func__ << ": port id " << templateId
265 << " does not have dynamic profiles";
266 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
267 }
268 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
269 if (templateDevicePort.device.type.connection.empty()) {
270 LOG(ERROR) << __func__ << ": port id " << templateId << " is permanently attached";
271 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
272 }
273 // Postpone id allocation until we ensure that there are no client errors.
274 connectedPort = *templateIt;
275 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
276 const auto& inputDevicePort =
277 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
278 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
279 connectedDevicePort.device.address = inputDevicePort.device.address;
280 LOG(DEBUG) << __func__ << ": device port " << connectedPort.id << " device set to "
281 << connectedDevicePort.device.toString();
282 // Check if there is already a connected port with for the same external device.
283 for (auto connectedPortId : mConnectedDevicePorts) {
284 auto connectedPortIt = findById<AudioPort>(ports, connectedPortId);
285 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
286 connectedDevicePort.device) {
287 LOG(ERROR) << __func__ << ": device " << connectedDevicePort.device.toString()
288 << " is already connected at the device port id " << connectedPortId;
289 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
290 }
291 }
292 }
293
294 if (!mDebug.simulateDeviceConnections) {
295 // In a real HAL here we would attempt querying the profiles from the device.
296 LOG(ERROR) << __func__ << ": failed to query supported device profiles";
297 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
298 }
299
300 connectedPort.id = ++getConfig().nextPortId;
301 mConnectedDevicePorts.insert(connectedPort.id);
302 LOG(DEBUG) << __func__ << ": template port " << templateId << " external device connected, "
303 << "connected port ID " << connectedPort.id;
304 auto& connectedProfiles = getConfig().connectedProfiles;
305 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
306 connectedProfilesIt != connectedProfiles.end()) {
307 connectedPort.profiles = connectedProfilesIt->second;
308 }
309 ports.push_back(connectedPort);
310 *_aidl_return = std::move(connectedPort);
311
312 std::vector<AudioRoute> newRoutes;
313 auto& routes = getConfig().routes;
314 for (auto& r : routes) {
315 if (r.sinkPortId == templateId) {
316 AudioRoute newRoute;
317 newRoute.sourcePortIds = r.sourcePortIds;
318 newRoute.sinkPortId = connectedPort.id;
319 newRoute.isExclusive = r.isExclusive;
320 newRoutes.push_back(std::move(newRoute));
321 } else {
322 auto& srcs = r.sourcePortIds;
323 if (std::find(srcs.begin(), srcs.end(), templateId) != srcs.end()) {
324 srcs.push_back(connectedPort.id);
325 }
326 }
327 }
328 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
329
330 return ndk::ScopedAStatus::ok();
331}
332
333ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
334 auto& ports = getConfig().ports;
335 auto portIt = findById<AudioPort>(ports, in_portId);
336 if (portIt == ports.end()) {
337 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
338 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
339 }
340 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
341 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a device port";
342 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
343 }
344 if (mConnectedDevicePorts.count(in_portId) == 0) {
345 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a connected device port";
346 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
347 }
348 auto& configs = getConfig().portConfigs;
349 auto& initials = getConfig().initialConfigs;
350 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
351 if (config.portId == in_portId) {
352 // Check if the configuration was provided by the client.
353 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
354 return initialIt == initials.end() || config != *initialIt;
355 }
356 return false;
357 });
358 if (configIt != configs.end()) {
359 LOG(ERROR) << __func__ << ": port id " << in_portId << " has a non-default config with id "
360 << configIt->id;
361 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
362 }
363 ports.erase(portIt);
364 mConnectedDevicePorts.erase(in_portId);
365 LOG(DEBUG) << __func__ << ": connected device port " << in_portId << " released";
366
367 auto& routes = getConfig().routes;
368 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
369 if (routesIt->sinkPortId == in_portId) {
370 routesIt = routes.erase(routesIt);
371 } else {
372 // Note: the list of sourcePortIds can't become empty because there must
373 // be the id of the template port in the route.
374 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
375 ++routesIt;
376 }
377 }
378
379 return ndk::ScopedAStatus::ok();
380}
381
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000382ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
383 *_aidl_return = getConfig().patches;
384 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " patches";
385 return ndk::ScopedAStatus::ok();
386}
387
388ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
389 auto& ports = getConfig().ports;
390 auto portIt = findById<AudioPort>(ports, in_portId);
391 if (portIt != ports.end()) {
392 *_aidl_return = *portIt;
393 LOG(DEBUG) << __func__ << ": returning port by id " << in_portId;
394 return ndk::ScopedAStatus::ok();
395 }
396 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
397 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
398}
399
400ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
401 *_aidl_return = getConfig().portConfigs;
402 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " port configs";
403 return ndk::ScopedAStatus::ok();
404}
405
406ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
407 *_aidl_return = getConfig().ports;
408 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " ports";
409 return ndk::ScopedAStatus::ok();
410}
411
412ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
413 *_aidl_return = getConfig().routes;
414 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " routes";
415 return ndk::ScopedAStatus::ok();
416}
417
Mikhail Naganov00603d12022-05-02 22:52:13 +0000418ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
419 std::vector<AudioRoute>* _aidl_return) {
420 auto& ports = getConfig().ports;
421 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
422 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
423 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
424 }
425 auto& routes = getConfig().routes;
426 std::copy_if(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
427 [&](const auto& r) {
428 const auto& srcs = r.sourcePortIds;
429 return r.sinkPortId == in_portId ||
430 std::find(srcs.begin(), srcs.end(), in_portId) != srcs.end();
431 });
432 return ndk::ScopedAStatus::ok();
433}
434
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000435ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
436 OpenInputStreamReturn* _aidl_return) {
437 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", buffer size "
438 << in_args.bufferSizeFrames << " frames";
439 AudioPort* port = nullptr;
440 if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
441 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000442 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000443 if (port->flags.getTag() != AudioIoFlags::Tag::input) {
444 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000445 << " does not correspond to an input mix port";
446 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
447 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000448 StreamContext context;
449 if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames, &context);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000450 !status.isOk()) {
451 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000452 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000453 context.fillDescriptor(&_aidl_return->desc);
454 auto stream = ndk::SharedRefBase::make<StreamIn>(in_args.sinkMetadata, std::move(context));
455 if (auto status = stream->init(); !status.isOk()) {
456 return status;
457 }
458 StreamWrapper streamWrapper(stream);
459 auto patchIt = mPatches.find(in_args.portConfigId);
460 if (patchIt != mPatches.end()) {
461 streamWrapper.setStreamIsConnected(true);
462 }
463 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000464 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000465 return ndk::ScopedAStatus::ok();
466}
467
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000468ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
469 OpenOutputStreamReturn* _aidl_return) {
470 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", has offload info? "
471 << (in_args.offloadInfo.has_value()) << ", buffer size " << in_args.bufferSizeFrames
472 << " frames";
473 AudioPort* port = nullptr;
474 if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
475 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000476 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000477 if (port->flags.getTag() != AudioIoFlags::Tag::output) {
478 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000479 << " does not correspond to an output mix port";
480 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
481 }
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000482 const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
483 AudioOutputFlags::COMPRESS_OFFLOAD);
484 if (isOffload && !in_args.offloadInfo.has_value()) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000485 LOG(ERROR) << __func__ << ": port id " << port->id
Mikhail Naganov111e0ce2022-06-17 21:41:19 +0000486 << " has COMPRESS_OFFLOAD flag set, requires offload info";
487 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
488 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000489 StreamContext context;
490 if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames, &context);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000491 !status.isOk()) {
492 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000493 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000494 context.fillDescriptor(&_aidl_return->desc);
495 auto stream = ndk::SharedRefBase::make<StreamOut>(in_args.sourceMetadata, std::move(context),
496 in_args.offloadInfo);
497 if (auto status = stream->init(); !status.isOk()) {
498 return status;
499 }
500 StreamWrapper streamWrapper(stream);
501 auto patchIt = mPatches.find(in_args.portConfigId);
502 if (patchIt != mPatches.end()) {
503 streamWrapper.setStreamIsConnected(true);
504 }
505 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000506 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000507 return ndk::ScopedAStatus::ok();
508}
509
510ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
Mikhail Naganov16db9b72022-06-17 21:36:18 +0000511 LOG(DEBUG) << __func__ << ": requested patch " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000512 if (in_requested.sourcePortConfigIds.empty()) {
513 LOG(ERROR) << __func__ << ": requested patch has empty sources list";
514 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
515 }
516 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
517 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sources list";
518 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
519 }
520 if (in_requested.sinkPortConfigIds.empty()) {
521 LOG(ERROR) << __func__ << ": requested patch has empty sinks list";
522 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
523 }
524 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
525 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sinks list";
526 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
527 }
528
529 auto& configs = getConfig().portConfigs;
530 std::vector<int32_t> missingIds;
531 auto sources =
532 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
533 if (!missingIds.empty()) {
534 LOG(ERROR) << __func__ << ": following source port config ids not found: "
535 << ::android::internal::ToString(missingIds);
536 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
537 }
538 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
539 if (!missingIds.empty()) {
540 LOG(ERROR) << __func__ << ": following sink port config ids not found: "
541 << ::android::internal::ToString(missingIds);
542 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
543 }
544 // bool indicates whether a non-exclusive route is available.
545 // If only an exclusive route is available, that means the patch can not be
546 // established if there is any other patch which currently uses the sink port.
547 std::map<int32_t, bool> allowedSinkPorts;
548 auto& routes = getConfig().routes;
549 for (auto src : sources) {
550 for (const auto& r : routes) {
551 const auto& srcs = r.sourcePortIds;
552 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
553 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
554 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
555 }
556 }
557 }
558 }
559 for (auto sink : sinks) {
560 if (allowedSinkPorts.count(sink->portId) == 0) {
561 LOG(ERROR) << __func__ << ": there is no route to the sink port id " << sink->portId;
562 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
563 }
564 }
565
566 auto& patches = getConfig().patches;
567 auto existing = patches.end();
568 std::optional<decltype(mPatches)> patchesBackup;
569 if (in_requested.id != 0) {
570 existing = findById<AudioPatch>(patches, in_requested.id);
571 if (existing != patches.end()) {
572 patchesBackup = mPatches;
573 cleanUpPatch(existing->id);
574 } else {
575 LOG(ERROR) << __func__ << ": not found existing patch id " << in_requested.id;
576 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
577 }
578 }
579 // Validate the requested patch.
580 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
581 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
582 LOG(ERROR) << __func__ << ": sink port id " << sinkPortId
583 << "is exclusive and is already used by some other patch";
584 if (patchesBackup.has_value()) {
585 mPatches = std::move(*patchesBackup);
586 }
587 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
588 }
589 }
590 *_aidl_return = in_requested;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000591 _aidl_return->minimumStreamBufferSizeFrames = kMinimumStreamBufferSizeFrames;
592 _aidl_return->latenciesMs.clear();
593 _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
594 _aidl_return->sinkPortConfigIds.size(), kLatencyMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000595 AudioPatch oldPatch{};
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000596 if (existing == patches.end()) {
597 _aidl_return->id = getConfig().nextPatchId++;
598 patches.push_back(*_aidl_return);
599 existing = patches.begin() + (patches.size() - 1);
600 } else {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000601 oldPatch = *existing;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000602 *existing = *_aidl_return;
603 }
604 registerPatch(*existing);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000605 updateStreamsConnectedState(oldPatch, *_aidl_return);
606
607 LOG(DEBUG) << __func__ << ": " << (oldPatch.id == 0 ? "created" : "updated") << " patch "
608 << _aidl_return->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000609 return ndk::ScopedAStatus::ok();
610}
611
612ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
613 AudioPortConfig* out_suggested, bool* _aidl_return) {
614 LOG(DEBUG) << __func__ << ": requested " << in_requested.toString();
615 auto& configs = getConfig().portConfigs;
616 auto existing = configs.end();
617 if (in_requested.id != 0) {
618 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
619 existing == configs.end()) {
620 LOG(ERROR) << __func__ << ": existing port config id " << in_requested.id
621 << " not found";
622 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
623 }
624 }
625
626 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
627 if (portId == 0) {
628 LOG(ERROR) << __func__ << ": input port config does not specify portId";
629 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
630 }
631 auto& ports = getConfig().ports;
632 auto portIt = findById<AudioPort>(ports, portId);
633 if (portIt == ports.end()) {
634 LOG(ERROR) << __func__ << ": input port config points to non-existent portId " << portId;
635 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
636 }
637 if (existing != configs.end()) {
638 *out_suggested = *existing;
639 } else {
640 AudioPortConfig newConfig;
641 if (generateDefaultPortConfig(*portIt, &newConfig)) {
642 *out_suggested = newConfig;
643 } else {
644 LOG(ERROR) << __func__ << ": unable generate a default config for port " << portId;
645 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
646 }
647 }
648 // From this moment, 'out_suggested' is either an existing port config,
649 // or a new generated config. Now attempt to update it according to the specified
650 // fields of 'in_requested'.
651
652 bool requestedIsValid = true, requestedIsFullySpecified = true;
653
654 AudioIoFlags portFlags = portIt->flags;
655 if (in_requested.flags.has_value()) {
656 if (in_requested.flags.value() != portFlags) {
657 LOG(WARNING) << __func__ << ": requested flags "
658 << in_requested.flags.value().toString() << " do not match port's "
659 << portId << " flags " << portFlags.toString();
660 requestedIsValid = false;
661 }
662 } else {
663 requestedIsFullySpecified = false;
664 }
665
666 AudioProfile portProfile;
667 if (in_requested.format.has_value()) {
668 const auto& format = in_requested.format.value();
669 if (findAudioProfile(*portIt, format, &portProfile)) {
670 out_suggested->format = format;
671 } else {
672 LOG(WARNING) << __func__ << ": requested format " << format.toString()
673 << " is not found in port's " << portId << " profiles";
674 requestedIsValid = false;
675 }
676 } else {
677 requestedIsFullySpecified = false;
678 }
679 if (!findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
680 LOG(ERROR) << __func__ << ": port " << portId << " does not support format "
681 << out_suggested->format.value().toString() << " anymore";
682 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
683 }
684
685 if (in_requested.channelMask.has_value()) {
686 const auto& channelMask = in_requested.channelMask.value();
687 if (find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
688 portProfile.channelMasks.end()) {
689 out_suggested->channelMask = channelMask;
690 } else {
691 LOG(WARNING) << __func__ << ": requested channel mask " << channelMask.toString()
692 << " is not supported for the format " << portProfile.format.toString()
693 << " by the port " << portId;
694 requestedIsValid = false;
695 }
696 } else {
697 requestedIsFullySpecified = false;
698 }
699
700 if (in_requested.sampleRate.has_value()) {
701 const auto& sampleRate = in_requested.sampleRate.value();
702 if (find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
703 sampleRate.value) != portProfile.sampleRates.end()) {
704 out_suggested->sampleRate = sampleRate;
705 } else {
706 LOG(WARNING) << __func__ << ": requested sample rate " << sampleRate.value
707 << " is not supported for the format " << portProfile.format.toString()
708 << " by the port " << portId;
709 requestedIsValid = false;
710 }
711 } else {
712 requestedIsFullySpecified = false;
713 }
714
715 if (in_requested.gain.has_value()) {
716 // Let's pretend that gain can always be applied.
717 out_suggested->gain = in_requested.gain.value();
718 }
719
720 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
721 out_suggested->id = getConfig().nextPortId++;
722 configs.push_back(*out_suggested);
723 *_aidl_return = true;
724 LOG(DEBUG) << __func__ << ": created new port config " << out_suggested->toString();
725 } else if (existing != configs.end() && requestedIsValid) {
726 *existing = *out_suggested;
727 *_aidl_return = true;
728 LOG(DEBUG) << __func__ << ": updated port config " << out_suggested->toString();
729 } else {
730 LOG(DEBUG) << __func__ << ": not applied; existing config ? " << (existing != configs.end())
731 << "; requested is valid? " << requestedIsValid << ", fully specified? "
732 << requestedIsFullySpecified;
733 *_aidl_return = false;
734 }
735 return ndk::ScopedAStatus::ok();
736}
737
738ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
739 auto& patches = getConfig().patches;
740 auto patchIt = findById<AudioPatch>(patches, in_patchId);
741 if (patchIt != patches.end()) {
742 cleanUpPatch(patchIt->id);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000743 updateStreamsConnectedState(*patchIt, AudioPatch{});
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000744 patches.erase(patchIt);
745 LOG(DEBUG) << __func__ << ": erased patch " << in_patchId;
746 return ndk::ScopedAStatus::ok();
747 }
748 LOG(ERROR) << __func__ << ": patch id " << in_patchId << " not found";
749 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
750}
751
752ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
753 auto& configs = getConfig().portConfigs;
754 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
755 if (configIt != configs.end()) {
756 if (mStreams.count(in_portConfigId) != 0) {
757 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
758 << " has a stream opened on it";
759 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
760 }
761 auto patchIt = mPatches.find(in_portConfigId);
762 if (patchIt != mPatches.end()) {
763 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
764 << " is used by the patch with id " << patchIt->second;
765 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
766 }
767 auto& initials = getConfig().initialConfigs;
768 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
769 if (initialIt == initials.end()) {
770 configs.erase(configIt);
771 LOG(DEBUG) << __func__ << ": erased port config " << in_portConfigId;
772 } else if (*configIt != *initialIt) {
773 *configIt = *initialIt;
774 LOG(DEBUG) << __func__ << ": reset port config " << in_portConfigId;
775 }
776 return ndk::ScopedAStatus::ok();
777 }
778 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId << " not found";
779 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
780}
781
782} // namespace aidl::android::hardware::audio::core