blob: a8f3b9b376157f30159adbbec7a04a63f816e1cd [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"
Mikhail Naganov3b125b72022-10-05 02:12:39 +000028#include "core-impl/Telephony.h"
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000029#include "core-impl/utils.h"
30
31using aidl::android::hardware::audio::common::SinkMetadata;
32using aidl::android::hardware::audio::common::SourceMetadata;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000033using aidl::android::media::audio::common::AudioChannelLayout;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000034using aidl::android::media::audio::common::AudioFormatDescription;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000035using aidl::android::media::audio::common::AudioFormatType;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000036using aidl::android::media::audio::common::AudioInputFlags;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000037using aidl::android::media::audio::common::AudioIoFlags;
38using aidl::android::media::audio::common::AudioOffloadInfo;
39using aidl::android::media::audio::common::AudioOutputFlags;
40using aidl::android::media::audio::common::AudioPort;
41using aidl::android::media::audio::common::AudioPortConfig;
42using aidl::android::media::audio::common::AudioPortExt;
43using aidl::android::media::audio::common::AudioProfile;
44using aidl::android::media::audio::common::Int;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000045using aidl::android::media::audio::common::PcmType;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000046using android::hardware::audio::common::getFrameSizeInBytes;
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +000047using android::hardware::audio::common::isBitPositionFlagSet;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000048
49namespace aidl::android::hardware::audio::core {
50
51namespace {
52
53bool generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) {
54 *config = {};
55 config->portId = port.id;
56 if (port.profiles.empty()) {
57 LOG(ERROR) << __func__ << ": port " << port.id << " has no profiles";
58 return false;
59 }
60 const auto& profile = port.profiles.begin();
61 config->format = profile->format;
62 if (profile->channelMasks.empty()) {
63 LOG(ERROR) << __func__ << ": the first profile in port " << port.id
64 << " has no channel masks";
65 return false;
66 }
67 config->channelMask = *profile->channelMasks.begin();
68 if (profile->sampleRates.empty()) {
69 LOG(ERROR) << __func__ << ": the first profile in port " << port.id
70 << " has no sample rates";
71 return false;
72 }
73 Int sampleRate;
74 sampleRate.value = *profile->sampleRates.begin();
75 config->sampleRate = sampleRate;
76 config->flags = port.flags;
77 config->ext = port.ext;
78 return true;
79}
80
81bool findAudioProfile(const AudioPort& port, const AudioFormatDescription& format,
82 AudioProfile* profile) {
83 if (auto profilesIt =
84 find_if(port.profiles.begin(), port.profiles.end(),
85 [&format](const auto& profile) { return profile.format == format; });
86 profilesIt != port.profiles.end()) {
87 *profile = *profilesIt;
88 return true;
89 }
90 return false;
91}
Mikhail Naganov00603d12022-05-02 22:52:13 +000092
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000093} // namespace
94
95void Module::cleanUpPatch(int32_t patchId) {
96 erase_all_values(mPatches, std::set<int32_t>{patchId});
97}
98
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000099ndk::ScopedAStatus Module::createStreamContext(int32_t in_portConfigId, int64_t in_bufferSizeFrames,
100 StreamContext* out_context) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000101 if (in_bufferSizeFrames <= 0) {
102 LOG(ERROR) << __func__ << ": non-positive buffer size " << in_bufferSizeFrames;
103 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
104 }
105 if (in_bufferSizeFrames < kMinimumStreamBufferSizeFrames) {
106 LOG(ERROR) << __func__ << ": insufficient buffer size " << in_bufferSizeFrames
107 << ", must be at least " << kMinimumStreamBufferSizeFrames;
108 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
109 }
110 auto& configs = getConfig().portConfigs;
111 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000112 // Since this is a private method, it is assumed that
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000113 // validity of the portConfigId has already been checked.
114 const size_t frameSize =
115 getFrameSizeInBytes(portConfigIt->format.value(), portConfigIt->channelMask.value());
116 if (frameSize == 0) {
117 LOG(ERROR) << __func__ << ": could not calculate frame size for port config "
118 << portConfigIt->toString();
119 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
120 }
121 LOG(DEBUG) << __func__ << ": frame size " << frameSize << " bytes";
122 if (frameSize > kMaximumStreamBufferSizeBytes / in_bufferSizeFrames) {
123 LOG(ERROR) << __func__ << ": buffer size " << in_bufferSizeFrames
124 << " frames is too large, maximum size is "
125 << kMaximumStreamBufferSizeBytes / frameSize;
126 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
127 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000128 const auto& flags = portConfigIt->flags.value();
129 if ((flags.getTag() == AudioIoFlags::Tag::input &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000130 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::input>(),
131 AudioInputFlags::MMAP_NOIRQ)) ||
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000132 (flags.getTag() == AudioIoFlags::Tag::output &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000133 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::output>(),
134 AudioOutputFlags::MMAP_NOIRQ))) {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000135 StreamContext temp(
136 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
137 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000138 frameSize, std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames),
139 mDebug.streamTransientStateDelayMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000140 if (temp.isValid()) {
141 *out_context = std::move(temp);
142 } else {
143 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
144 }
145 } else {
146 // TODO: Implement simulation of MMAP buffer allocation
147 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000148 return ndk::ScopedAStatus::ok();
149}
150
151ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) {
152 auto& configs = getConfig().portConfigs;
153 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
154 if (portConfigIt == configs.end()) {
155 LOG(ERROR) << __func__ << ": existing port config id " << in_portConfigId << " not found";
156 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
157 }
158 const int32_t portId = portConfigIt->portId;
159 // In our implementation, configs of mix ports always have unique IDs.
160 CHECK(portId != in_portConfigId);
161 auto& ports = getConfig().ports;
162 auto portIt = findById<AudioPort>(ports, portId);
163 if (portIt == ports.end()) {
164 LOG(ERROR) << __func__ << ": port id " << portId << " used by port config id "
165 << in_portConfigId << " not found";
166 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
167 }
168 if (mStreams.count(in_portConfigId) != 0) {
169 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
170 << " already has a stream opened on it";
171 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
172 }
173 if (portIt->ext.getTag() != AudioPortExt::Tag::mix) {
174 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
175 << " does not correspond to a mix port";
176 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
177 }
178 const int32_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
179 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
180 LOG(ERROR) << __func__ << ": port id " << portId
181 << " has already reached maximum allowed opened stream count: "
182 << maxOpenStreamCount;
183 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
184 }
185 *port = &(*portIt);
186 return ndk::ScopedAStatus::ok();
187}
188
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000189internal::Configuration& Module::getConfig() {
190 if (!mConfig) {
191 mConfig.reset(new internal::Configuration(internal::getNullPrimaryConfiguration()));
192 }
193 return *mConfig;
194}
195
196void Module::registerPatch(const AudioPatch& patch) {
197 auto& configs = getConfig().portConfigs;
198 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
199 for (auto portConfigId : portConfigIds) {
200 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
201 if (configIt != configs.end()) {
202 mPatches.insert(std::pair{portConfigId, patch.id});
203 if (configIt->portId != portConfigId) {
204 mPatches.insert(std::pair{configIt->portId, patch.id});
205 }
206 }
207 };
208 };
209 do_insert(patch.sourcePortConfigIds);
210 do_insert(patch.sinkPortConfigIds);
211}
212
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000213void Module::updateStreamsConnectedState(const AudioPatch& oldPatch, const AudioPatch& newPatch) {
214 // Streams from the old patch need to be disconnected, streams from the new
215 // patch need to be connected. If the stream belongs to both patches, no need
216 // to update it.
217 std::set<int32_t> idsToDisconnect, idsToConnect;
218 idsToDisconnect.insert(oldPatch.sourcePortConfigIds.begin(),
219 oldPatch.sourcePortConfigIds.end());
220 idsToDisconnect.insert(oldPatch.sinkPortConfigIds.begin(), oldPatch.sinkPortConfigIds.end());
221 idsToConnect.insert(newPatch.sourcePortConfigIds.begin(), newPatch.sourcePortConfigIds.end());
222 idsToConnect.insert(newPatch.sinkPortConfigIds.begin(), newPatch.sinkPortConfigIds.end());
223 std::for_each(idsToDisconnect.begin(), idsToDisconnect.end(), [&](const auto& portConfigId) {
224 if (idsToConnect.count(portConfigId) == 0) {
225 mStreams.setStreamIsConnected(portConfigId, false);
226 }
227 });
228 std::for_each(idsToConnect.begin(), idsToConnect.end(), [&](const auto& portConfigId) {
229 if (idsToDisconnect.count(portConfigId) == 0) {
230 mStreams.setStreamIsConnected(portConfigId, true);
231 }
232 });
233}
234
Mikhail Naganov00603d12022-05-02 22:52:13 +0000235ndk::ScopedAStatus Module::setModuleDebug(
236 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
237 LOG(DEBUG) << __func__ << ": old flags:" << mDebug.toString()
238 << ", new flags: " << in_debug.toString();
239 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
240 !mConnectedDevicePorts.empty()) {
241 LOG(ERROR) << __func__ << ": attempting to change device connections simulation "
242 << "while having external devices connected";
243 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
244 }
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000245 if (in_debug.streamTransientStateDelayMs < 0) {
246 LOG(ERROR) << __func__ << ": streamTransientStateDelayMs is negative: "
247 << in_debug.streamTransientStateDelayMs;
248 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
249 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000250 mDebug = in_debug;
251 return ndk::ScopedAStatus::ok();
252}
253
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000254ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
255 if (mTelephony == nullptr) {
256 mTelephony = ndk::SharedRefBase::make<Telephony>();
257 }
258 *_aidl_return = mTelephony;
259 LOG(DEBUG) << __func__ << ": returning instance of ITelephony: " << _aidl_return->get();
260 return ndk::ScopedAStatus::ok();
261}
262
Mikhail Naganov00603d12022-05-02 22:52:13 +0000263ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
264 AudioPort* _aidl_return) {
265 const int32_t templateId = in_templateIdAndAdditionalData.id;
266 auto& ports = getConfig().ports;
267 AudioPort connectedPort;
268 { // Scope the template port so that we don't accidentally modify it.
269 auto templateIt = findById<AudioPort>(ports, templateId);
270 if (templateIt == ports.end()) {
271 LOG(ERROR) << __func__ << ": port id " << templateId << " not found";
272 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
273 }
274 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
275 LOG(ERROR) << __func__ << ": port id " << templateId << " is not a device port";
276 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
277 }
278 if (!templateIt->profiles.empty()) {
279 LOG(ERROR) << __func__ << ": port id " << templateId
280 << " does not have dynamic profiles";
281 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
282 }
283 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
284 if (templateDevicePort.device.type.connection.empty()) {
285 LOG(ERROR) << __func__ << ": port id " << templateId << " is permanently attached";
286 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
287 }
288 // Postpone id allocation until we ensure that there are no client errors.
289 connectedPort = *templateIt;
290 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
291 const auto& inputDevicePort =
292 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
293 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
294 connectedDevicePort.device.address = inputDevicePort.device.address;
295 LOG(DEBUG) << __func__ << ": device port " << connectedPort.id << " device set to "
296 << connectedDevicePort.device.toString();
297 // Check if there is already a connected port with for the same external device.
298 for (auto connectedPortId : mConnectedDevicePorts) {
299 auto connectedPortIt = findById<AudioPort>(ports, connectedPortId);
300 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
301 connectedDevicePort.device) {
302 LOG(ERROR) << __func__ << ": device " << connectedDevicePort.device.toString()
303 << " is already connected at the device port id " << connectedPortId;
304 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
305 }
306 }
307 }
308
309 if (!mDebug.simulateDeviceConnections) {
310 // In a real HAL here we would attempt querying the profiles from the device.
311 LOG(ERROR) << __func__ << ": failed to query supported device profiles";
312 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
313 }
314
315 connectedPort.id = ++getConfig().nextPortId;
316 mConnectedDevicePorts.insert(connectedPort.id);
317 LOG(DEBUG) << __func__ << ": template port " << templateId << " external device connected, "
318 << "connected port ID " << connectedPort.id;
319 auto& connectedProfiles = getConfig().connectedProfiles;
320 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
321 connectedProfilesIt != connectedProfiles.end()) {
322 connectedPort.profiles = connectedProfilesIt->second;
323 }
324 ports.push_back(connectedPort);
325 *_aidl_return = std::move(connectedPort);
326
327 std::vector<AudioRoute> newRoutes;
328 auto& routes = getConfig().routes;
329 for (auto& r : routes) {
330 if (r.sinkPortId == templateId) {
331 AudioRoute newRoute;
332 newRoute.sourcePortIds = r.sourcePortIds;
333 newRoute.sinkPortId = connectedPort.id;
334 newRoute.isExclusive = r.isExclusive;
335 newRoutes.push_back(std::move(newRoute));
336 } else {
337 auto& srcs = r.sourcePortIds;
338 if (std::find(srcs.begin(), srcs.end(), templateId) != srcs.end()) {
339 srcs.push_back(connectedPort.id);
340 }
341 }
342 }
343 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
344
345 return ndk::ScopedAStatus::ok();
346}
347
348ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
349 auto& ports = getConfig().ports;
350 auto portIt = findById<AudioPort>(ports, in_portId);
351 if (portIt == ports.end()) {
352 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
353 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
354 }
355 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
356 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a device port";
357 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
358 }
359 if (mConnectedDevicePorts.count(in_portId) == 0) {
360 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a connected device port";
361 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
362 }
363 auto& configs = getConfig().portConfigs;
364 auto& initials = getConfig().initialConfigs;
365 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
366 if (config.portId == in_portId) {
367 // Check if the configuration was provided by the client.
368 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
369 return initialIt == initials.end() || config != *initialIt;
370 }
371 return false;
372 });
373 if (configIt != configs.end()) {
374 LOG(ERROR) << __func__ << ": port id " << in_portId << " has a non-default config with id "
375 << configIt->id;
376 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
377 }
378 ports.erase(portIt);
379 mConnectedDevicePorts.erase(in_portId);
380 LOG(DEBUG) << __func__ << ": connected device port " << in_portId << " released";
381
382 auto& routes = getConfig().routes;
383 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
384 if (routesIt->sinkPortId == in_portId) {
385 routesIt = routes.erase(routesIt);
386 } else {
387 // Note: the list of sourcePortIds can't become empty because there must
388 // be the id of the template port in the route.
389 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
390 ++routesIt;
391 }
392 }
393
394 return ndk::ScopedAStatus::ok();
395}
396
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000397ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
398 *_aidl_return = getConfig().patches;
399 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " patches";
400 return ndk::ScopedAStatus::ok();
401}
402
403ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
404 auto& ports = getConfig().ports;
405 auto portIt = findById<AudioPort>(ports, in_portId);
406 if (portIt != ports.end()) {
407 *_aidl_return = *portIt;
408 LOG(DEBUG) << __func__ << ": returning port by id " << in_portId;
409 return ndk::ScopedAStatus::ok();
410 }
411 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
412 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
413}
414
415ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
416 *_aidl_return = getConfig().portConfigs;
417 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " port configs";
418 return ndk::ScopedAStatus::ok();
419}
420
421ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
422 *_aidl_return = getConfig().ports;
423 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " ports";
424 return ndk::ScopedAStatus::ok();
425}
426
427ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
428 *_aidl_return = getConfig().routes;
429 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " routes";
430 return ndk::ScopedAStatus::ok();
431}
432
Mikhail Naganov00603d12022-05-02 22:52:13 +0000433ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
434 std::vector<AudioRoute>* _aidl_return) {
435 auto& ports = getConfig().ports;
436 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
437 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
438 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
439 }
440 auto& routes = getConfig().routes;
441 std::copy_if(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
442 [&](const auto& r) {
443 const auto& srcs = r.sourcePortIds;
444 return r.sinkPortId == in_portId ||
445 std::find(srcs.begin(), srcs.end(), in_portId) != srcs.end();
446 });
447 return ndk::ScopedAStatus::ok();
448}
449
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000450ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
451 OpenInputStreamReturn* _aidl_return) {
452 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", buffer size "
453 << in_args.bufferSizeFrames << " frames";
454 AudioPort* port = nullptr;
455 if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
456 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000457 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000458 if (port->flags.getTag() != AudioIoFlags::Tag::input) {
459 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000460 << " does not correspond to an input mix port";
461 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
462 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000463 StreamContext context;
464 if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames, &context);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000465 !status.isOk()) {
466 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000467 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000468 context.fillDescriptor(&_aidl_return->desc);
469 auto stream = ndk::SharedRefBase::make<StreamIn>(in_args.sinkMetadata, std::move(context));
470 if (auto status = stream->init(); !status.isOk()) {
471 return status;
472 }
473 StreamWrapper streamWrapper(stream);
474 auto patchIt = mPatches.find(in_args.portConfigId);
475 if (patchIt != mPatches.end()) {
476 streamWrapper.setStreamIsConnected(true);
477 }
478 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000479 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000480 return ndk::ScopedAStatus::ok();
481}
482
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000483ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
484 OpenOutputStreamReturn* _aidl_return) {
485 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", has offload info? "
486 << (in_args.offloadInfo.has_value()) << ", buffer size " << in_args.bufferSizeFrames
487 << " frames";
488 AudioPort* port = nullptr;
489 if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
490 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000491 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000492 if (port->flags.getTag() != AudioIoFlags::Tag::output) {
493 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000494 << " does not correspond to an output mix port";
495 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
496 }
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000497 const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
498 AudioOutputFlags::COMPRESS_OFFLOAD);
499 if (isOffload && !in_args.offloadInfo.has_value()) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000500 LOG(ERROR) << __func__ << ": port id " << port->id
Mikhail Naganov111e0ce2022-06-17 21:41:19 +0000501 << " has COMPRESS_OFFLOAD flag set, requires offload info";
502 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
503 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000504 StreamContext context;
505 if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames, &context);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000506 !status.isOk()) {
507 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000508 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000509 context.fillDescriptor(&_aidl_return->desc);
510 auto stream = ndk::SharedRefBase::make<StreamOut>(in_args.sourceMetadata, std::move(context),
511 in_args.offloadInfo);
512 if (auto status = stream->init(); !status.isOk()) {
513 return status;
514 }
515 StreamWrapper streamWrapper(stream);
516 auto patchIt = mPatches.find(in_args.portConfigId);
517 if (patchIt != mPatches.end()) {
518 streamWrapper.setStreamIsConnected(true);
519 }
520 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000521 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000522 return ndk::ScopedAStatus::ok();
523}
524
525ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
Mikhail Naganov16db9b72022-06-17 21:36:18 +0000526 LOG(DEBUG) << __func__ << ": requested patch " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000527 if (in_requested.sourcePortConfigIds.empty()) {
528 LOG(ERROR) << __func__ << ": requested patch has empty sources list";
529 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
530 }
531 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
532 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sources list";
533 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
534 }
535 if (in_requested.sinkPortConfigIds.empty()) {
536 LOG(ERROR) << __func__ << ": requested patch has empty sinks list";
537 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
538 }
539 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
540 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sinks list";
541 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
542 }
543
544 auto& configs = getConfig().portConfigs;
545 std::vector<int32_t> missingIds;
546 auto sources =
547 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
548 if (!missingIds.empty()) {
549 LOG(ERROR) << __func__ << ": following source port config ids not found: "
550 << ::android::internal::ToString(missingIds);
551 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
552 }
553 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
554 if (!missingIds.empty()) {
555 LOG(ERROR) << __func__ << ": following sink port config ids not found: "
556 << ::android::internal::ToString(missingIds);
557 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
558 }
559 // bool indicates whether a non-exclusive route is available.
560 // If only an exclusive route is available, that means the patch can not be
561 // established if there is any other patch which currently uses the sink port.
562 std::map<int32_t, bool> allowedSinkPorts;
563 auto& routes = getConfig().routes;
564 for (auto src : sources) {
565 for (const auto& r : routes) {
566 const auto& srcs = r.sourcePortIds;
567 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
568 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
569 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
570 }
571 }
572 }
573 }
574 for (auto sink : sinks) {
575 if (allowedSinkPorts.count(sink->portId) == 0) {
576 LOG(ERROR) << __func__ << ": there is no route to the sink port id " << sink->portId;
577 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
578 }
579 }
580
581 auto& patches = getConfig().patches;
582 auto existing = patches.end();
583 std::optional<decltype(mPatches)> patchesBackup;
584 if (in_requested.id != 0) {
585 existing = findById<AudioPatch>(patches, in_requested.id);
586 if (existing != patches.end()) {
587 patchesBackup = mPatches;
588 cleanUpPatch(existing->id);
589 } else {
590 LOG(ERROR) << __func__ << ": not found existing patch id " << in_requested.id;
591 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
592 }
593 }
594 // Validate the requested patch.
595 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
596 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
597 LOG(ERROR) << __func__ << ": sink port id " << sinkPortId
598 << "is exclusive and is already used by some other patch";
599 if (patchesBackup.has_value()) {
600 mPatches = std::move(*patchesBackup);
601 }
602 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
603 }
604 }
605 *_aidl_return = in_requested;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000606 _aidl_return->minimumStreamBufferSizeFrames = kMinimumStreamBufferSizeFrames;
607 _aidl_return->latenciesMs.clear();
608 _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
609 _aidl_return->sinkPortConfigIds.size(), kLatencyMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000610 AudioPatch oldPatch{};
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000611 if (existing == patches.end()) {
612 _aidl_return->id = getConfig().nextPatchId++;
613 patches.push_back(*_aidl_return);
614 existing = patches.begin() + (patches.size() - 1);
615 } else {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000616 oldPatch = *existing;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000617 *existing = *_aidl_return;
618 }
619 registerPatch(*existing);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000620 updateStreamsConnectedState(oldPatch, *_aidl_return);
621
622 LOG(DEBUG) << __func__ << ": " << (oldPatch.id == 0 ? "created" : "updated") << " patch "
623 << _aidl_return->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000624 return ndk::ScopedAStatus::ok();
625}
626
627ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
628 AudioPortConfig* out_suggested, bool* _aidl_return) {
629 LOG(DEBUG) << __func__ << ": requested " << in_requested.toString();
630 auto& configs = getConfig().portConfigs;
631 auto existing = configs.end();
632 if (in_requested.id != 0) {
633 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
634 existing == configs.end()) {
635 LOG(ERROR) << __func__ << ": existing port config id " << in_requested.id
636 << " not found";
637 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
638 }
639 }
640
641 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
642 if (portId == 0) {
643 LOG(ERROR) << __func__ << ": input port config does not specify portId";
644 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
645 }
646 auto& ports = getConfig().ports;
647 auto portIt = findById<AudioPort>(ports, portId);
648 if (portIt == ports.end()) {
649 LOG(ERROR) << __func__ << ": input port config points to non-existent portId " << portId;
650 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
651 }
652 if (existing != configs.end()) {
653 *out_suggested = *existing;
654 } else {
655 AudioPortConfig newConfig;
656 if (generateDefaultPortConfig(*portIt, &newConfig)) {
657 *out_suggested = newConfig;
658 } else {
659 LOG(ERROR) << __func__ << ": unable generate a default config for port " << portId;
660 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
661 }
662 }
663 // From this moment, 'out_suggested' is either an existing port config,
664 // or a new generated config. Now attempt to update it according to the specified
665 // fields of 'in_requested'.
666
667 bool requestedIsValid = true, requestedIsFullySpecified = true;
668
669 AudioIoFlags portFlags = portIt->flags;
670 if (in_requested.flags.has_value()) {
671 if (in_requested.flags.value() != portFlags) {
672 LOG(WARNING) << __func__ << ": requested flags "
673 << in_requested.flags.value().toString() << " do not match port's "
674 << portId << " flags " << portFlags.toString();
675 requestedIsValid = false;
676 }
677 } else {
678 requestedIsFullySpecified = false;
679 }
680
681 AudioProfile portProfile;
682 if (in_requested.format.has_value()) {
683 const auto& format = in_requested.format.value();
684 if (findAudioProfile(*portIt, format, &portProfile)) {
685 out_suggested->format = format;
686 } else {
687 LOG(WARNING) << __func__ << ": requested format " << format.toString()
688 << " is not found in port's " << portId << " profiles";
689 requestedIsValid = false;
690 }
691 } else {
692 requestedIsFullySpecified = false;
693 }
694 if (!findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
695 LOG(ERROR) << __func__ << ": port " << portId << " does not support format "
696 << out_suggested->format.value().toString() << " anymore";
697 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
698 }
699
700 if (in_requested.channelMask.has_value()) {
701 const auto& channelMask = in_requested.channelMask.value();
702 if (find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
703 portProfile.channelMasks.end()) {
704 out_suggested->channelMask = channelMask;
705 } else {
706 LOG(WARNING) << __func__ << ": requested channel mask " << channelMask.toString()
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.sampleRate.has_value()) {
716 const auto& sampleRate = in_requested.sampleRate.value();
717 if (find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
718 sampleRate.value) != portProfile.sampleRates.end()) {
719 out_suggested->sampleRate = sampleRate;
720 } else {
721 LOG(WARNING) << __func__ << ": requested sample rate " << sampleRate.value
722 << " is not supported for the format " << portProfile.format.toString()
723 << " by the port " << portId;
724 requestedIsValid = false;
725 }
726 } else {
727 requestedIsFullySpecified = false;
728 }
729
730 if (in_requested.gain.has_value()) {
731 // Let's pretend that gain can always be applied.
732 out_suggested->gain = in_requested.gain.value();
733 }
734
735 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
736 out_suggested->id = getConfig().nextPortId++;
737 configs.push_back(*out_suggested);
738 *_aidl_return = true;
739 LOG(DEBUG) << __func__ << ": created new port config " << out_suggested->toString();
740 } else if (existing != configs.end() && requestedIsValid) {
741 *existing = *out_suggested;
742 *_aidl_return = true;
743 LOG(DEBUG) << __func__ << ": updated port config " << out_suggested->toString();
744 } else {
745 LOG(DEBUG) << __func__ << ": not applied; existing config ? " << (existing != configs.end())
746 << "; requested is valid? " << requestedIsValid << ", fully specified? "
747 << requestedIsFullySpecified;
748 *_aidl_return = false;
749 }
750 return ndk::ScopedAStatus::ok();
751}
752
753ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
754 auto& patches = getConfig().patches;
755 auto patchIt = findById<AudioPatch>(patches, in_patchId);
756 if (patchIt != patches.end()) {
757 cleanUpPatch(patchIt->id);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000758 updateStreamsConnectedState(*patchIt, AudioPatch{});
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000759 patches.erase(patchIt);
760 LOG(DEBUG) << __func__ << ": erased patch " << in_patchId;
761 return ndk::ScopedAStatus::ok();
762 }
763 LOG(ERROR) << __func__ << ": patch id " << in_patchId << " not found";
764 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
765}
766
767ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
768 auto& configs = getConfig().portConfigs;
769 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
770 if (configIt != configs.end()) {
771 if (mStreams.count(in_portConfigId) != 0) {
772 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
773 << " has a stream opened on it";
774 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
775 }
776 auto patchIt = mPatches.find(in_portConfigId);
777 if (patchIt != mPatches.end()) {
778 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
779 << " is used by the patch with id " << patchIt->second;
780 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
781 }
782 auto& initials = getConfig().initialConfigs;
783 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
784 if (initialIt == initials.end()) {
785 configs.erase(configIt);
786 LOG(DEBUG) << __func__ << ": erased port config " << in_portConfigId;
787 } else if (*configIt != *initialIt) {
788 *configIt = *initialIt;
789 LOG(DEBUG) << __func__ << ": reset port config " << in_portConfigId;
790 }
791 return ndk::ScopedAStatus::ok();
792 }
793 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId << " not found";
794 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
795}
796
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000797ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) {
798 *_aidl_return = mMasterMute;
799 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
800 return ndk::ScopedAStatus::ok();
801}
802
803ndk::ScopedAStatus Module::setMasterMute(bool in_mute) {
804 LOG(DEBUG) << __func__ << ": " << in_mute;
805 mMasterMute = in_mute;
806 return ndk::ScopedAStatus::ok();
807}
808
809ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) {
810 *_aidl_return = mMasterVolume;
811 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
812 return ndk::ScopedAStatus::ok();
813}
814
815ndk::ScopedAStatus Module::setMasterVolume(float in_volume) {
816 LOG(DEBUG) << __func__ << ": " << in_volume;
817 if (in_volume >= 0.0f && in_volume <= 1.0f) {
818 mMasterVolume = in_volume;
819 return ndk::ScopedAStatus::ok();
820 }
821 LOG(ERROR) << __func__ << ": invalid master volume value: " << in_volume;
822 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
823}
824
825ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) {
826 *_aidl_return = mMicMute;
827 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
828 return ndk::ScopedAStatus::ok();
829}
830
831ndk::ScopedAStatus Module::setMicMute(bool in_mute) {
832 LOG(DEBUG) << __func__ << ": " << in_mute;
833 mMicMute = in_mute;
834 return ndk::ScopedAStatus::ok();
835}
836
837ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) {
838 // No checks for supported audio modes here, it's an informative notification.
839 LOG(DEBUG) << __func__ << ": " << toString(in_mode);
840 return ndk::ScopedAStatus::ok();
841}
842
843ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) {
844 LOG(DEBUG) << __func__ << ": " << toString(in_rotation);
845 return ndk::ScopedAStatus::ok();
846}
847
848ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) {
849 LOG(DEBUG) << __func__ << ": " << in_isTurnedOn;
850 return ndk::ScopedAStatus::ok();
851}
852
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000853} // namespace aidl::android::hardware::audio::core