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