blob: 9dbd61c4420ab6ebba7ffc9a1297ed1039b836fc [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,
Mikhail Naganov30301a42022-09-13 01:20:45 +0000100 std::shared_ptr<IStreamCallback> asyncCallback,
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000101 StreamContext* out_context) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000102 if (in_bufferSizeFrames <= 0) {
103 LOG(ERROR) << __func__ << ": non-positive buffer size " << in_bufferSizeFrames;
104 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
105 }
106 if (in_bufferSizeFrames < kMinimumStreamBufferSizeFrames) {
107 LOG(ERROR) << __func__ << ": insufficient buffer size " << in_bufferSizeFrames
108 << ", must be at least " << kMinimumStreamBufferSizeFrames;
109 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
110 }
111 auto& configs = getConfig().portConfigs;
112 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000113 // Since this is a private method, it is assumed that
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000114 // validity of the portConfigId has already been checked.
115 const size_t frameSize =
116 getFrameSizeInBytes(portConfigIt->format.value(), portConfigIt->channelMask.value());
117 if (frameSize == 0) {
118 LOG(ERROR) << __func__ << ": could not calculate frame size for port config "
119 << portConfigIt->toString();
120 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
121 }
122 LOG(DEBUG) << __func__ << ": frame size " << frameSize << " bytes";
123 if (frameSize > kMaximumStreamBufferSizeBytes / in_bufferSizeFrames) {
124 LOG(ERROR) << __func__ << ": buffer size " << in_bufferSizeFrames
125 << " frames is too large, maximum size is "
126 << kMaximumStreamBufferSizeBytes / frameSize;
127 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
128 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000129 const auto& flags = portConfigIt->flags.value();
130 if ((flags.getTag() == AudioIoFlags::Tag::input &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000131 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::input>(),
132 AudioInputFlags::MMAP_NOIRQ)) ||
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000133 (flags.getTag() == AudioIoFlags::Tag::output &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000134 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::output>(),
135 AudioOutputFlags::MMAP_NOIRQ))) {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000136 StreamContext temp(
137 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
138 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000139 frameSize, std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames),
Mikhail Naganov30301a42022-09-13 01:20:45 +0000140 asyncCallback, mDebug.streamTransientStateDelayMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000141 if (temp.isValid()) {
142 *out_context = std::move(temp);
143 } else {
144 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
145 }
146 } else {
147 // TODO: Implement simulation of MMAP buffer allocation
148 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000149 return ndk::ScopedAStatus::ok();
150}
151
152ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) {
153 auto& configs = getConfig().portConfigs;
154 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
155 if (portConfigIt == configs.end()) {
156 LOG(ERROR) << __func__ << ": existing port config id " << in_portConfigId << " not found";
157 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
158 }
159 const int32_t portId = portConfigIt->portId;
160 // In our implementation, configs of mix ports always have unique IDs.
161 CHECK(portId != in_portConfigId);
162 auto& ports = getConfig().ports;
163 auto portIt = findById<AudioPort>(ports, portId);
164 if (portIt == ports.end()) {
165 LOG(ERROR) << __func__ << ": port id " << portId << " used by port config id "
166 << in_portConfigId << " not found";
167 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
168 }
169 if (mStreams.count(in_portConfigId) != 0) {
170 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
171 << " already has a stream opened on it";
172 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
173 }
174 if (portIt->ext.getTag() != AudioPortExt::Tag::mix) {
175 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
176 << " does not correspond to a mix port";
177 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
178 }
179 const int32_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
180 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
181 LOG(ERROR) << __func__ << ": port id " << portId
182 << " has already reached maximum allowed opened stream count: "
183 << maxOpenStreamCount;
184 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
185 }
186 *port = &(*portIt);
187 return ndk::ScopedAStatus::ok();
188}
189
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000190internal::Configuration& Module::getConfig() {
191 if (!mConfig) {
192 mConfig.reset(new internal::Configuration(internal::getNullPrimaryConfiguration()));
193 }
194 return *mConfig;
195}
196
197void Module::registerPatch(const AudioPatch& patch) {
198 auto& configs = getConfig().portConfigs;
199 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
200 for (auto portConfigId : portConfigIds) {
201 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
202 if (configIt != configs.end()) {
203 mPatches.insert(std::pair{portConfigId, patch.id});
204 if (configIt->portId != portConfigId) {
205 mPatches.insert(std::pair{configIt->portId, patch.id});
206 }
207 }
208 };
209 };
210 do_insert(patch.sourcePortConfigIds);
211 do_insert(patch.sinkPortConfigIds);
212}
213
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000214void Module::updateStreamsConnectedState(const AudioPatch& oldPatch, const AudioPatch& newPatch) {
215 // Streams from the old patch need to be disconnected, streams from the new
216 // patch need to be connected. If the stream belongs to both patches, no need
217 // to update it.
218 std::set<int32_t> idsToDisconnect, idsToConnect;
219 idsToDisconnect.insert(oldPatch.sourcePortConfigIds.begin(),
220 oldPatch.sourcePortConfigIds.end());
221 idsToDisconnect.insert(oldPatch.sinkPortConfigIds.begin(), oldPatch.sinkPortConfigIds.end());
222 idsToConnect.insert(newPatch.sourcePortConfigIds.begin(), newPatch.sourcePortConfigIds.end());
223 idsToConnect.insert(newPatch.sinkPortConfigIds.begin(), newPatch.sinkPortConfigIds.end());
224 std::for_each(idsToDisconnect.begin(), idsToDisconnect.end(), [&](const auto& portConfigId) {
225 if (idsToConnect.count(portConfigId) == 0) {
226 mStreams.setStreamIsConnected(portConfigId, false);
227 }
228 });
229 std::for_each(idsToConnect.begin(), idsToConnect.end(), [&](const auto& portConfigId) {
230 if (idsToDisconnect.count(portConfigId) == 0) {
231 mStreams.setStreamIsConnected(portConfigId, true);
232 }
233 });
234}
235
Mikhail Naganov00603d12022-05-02 22:52:13 +0000236ndk::ScopedAStatus Module::setModuleDebug(
237 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
238 LOG(DEBUG) << __func__ << ": old flags:" << mDebug.toString()
239 << ", new flags: " << in_debug.toString();
240 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
241 !mConnectedDevicePorts.empty()) {
242 LOG(ERROR) << __func__ << ": attempting to change device connections simulation "
243 << "while having external devices connected";
244 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
245 }
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000246 if (in_debug.streamTransientStateDelayMs < 0) {
247 LOG(ERROR) << __func__ << ": streamTransientStateDelayMs is negative: "
248 << in_debug.streamTransientStateDelayMs;
249 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
250 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000251 mDebug = in_debug;
252 return ndk::ScopedAStatus::ok();
253}
254
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000255ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
256 if (mTelephony == nullptr) {
257 mTelephony = ndk::SharedRefBase::make<Telephony>();
258 }
259 *_aidl_return = mTelephony;
260 LOG(DEBUG) << __func__ << ": returning instance of ITelephony: " << _aidl_return->get();
261 return ndk::ScopedAStatus::ok();
262}
263
Mikhail Naganov00603d12022-05-02 22:52:13 +0000264ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
265 AudioPort* _aidl_return) {
266 const int32_t templateId = in_templateIdAndAdditionalData.id;
267 auto& ports = getConfig().ports;
268 AudioPort connectedPort;
269 { // Scope the template port so that we don't accidentally modify it.
270 auto templateIt = findById<AudioPort>(ports, templateId);
271 if (templateIt == ports.end()) {
272 LOG(ERROR) << __func__ << ": port id " << templateId << " not found";
273 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
274 }
275 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
276 LOG(ERROR) << __func__ << ": port id " << templateId << " is not a device port";
277 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
278 }
279 if (!templateIt->profiles.empty()) {
280 LOG(ERROR) << __func__ << ": port id " << templateId
281 << " does not have dynamic profiles";
282 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
283 }
284 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
285 if (templateDevicePort.device.type.connection.empty()) {
286 LOG(ERROR) << __func__ << ": port id " << templateId << " is permanently attached";
287 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
288 }
289 // Postpone id allocation until we ensure that there are no client errors.
290 connectedPort = *templateIt;
291 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
292 const auto& inputDevicePort =
293 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
294 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
295 connectedDevicePort.device.address = inputDevicePort.device.address;
296 LOG(DEBUG) << __func__ << ": device port " << connectedPort.id << " device set to "
297 << connectedDevicePort.device.toString();
298 // Check if there is already a connected port with for the same external device.
299 for (auto connectedPortId : mConnectedDevicePorts) {
300 auto connectedPortIt = findById<AudioPort>(ports, connectedPortId);
301 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
302 connectedDevicePort.device) {
303 LOG(ERROR) << __func__ << ": device " << connectedDevicePort.device.toString()
304 << " is already connected at the device port id " << connectedPortId;
305 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
306 }
307 }
308 }
309
310 if (!mDebug.simulateDeviceConnections) {
311 // In a real HAL here we would attempt querying the profiles from the device.
312 LOG(ERROR) << __func__ << ": failed to query supported device profiles";
313 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
314 }
315
316 connectedPort.id = ++getConfig().nextPortId;
317 mConnectedDevicePorts.insert(connectedPort.id);
318 LOG(DEBUG) << __func__ << ": template port " << templateId << " external device connected, "
319 << "connected port ID " << connectedPort.id;
320 auto& connectedProfiles = getConfig().connectedProfiles;
321 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
322 connectedProfilesIt != connectedProfiles.end()) {
323 connectedPort.profiles = connectedProfilesIt->second;
324 }
325 ports.push_back(connectedPort);
326 *_aidl_return = std::move(connectedPort);
327
328 std::vector<AudioRoute> newRoutes;
329 auto& routes = getConfig().routes;
330 for (auto& r : routes) {
331 if (r.sinkPortId == templateId) {
332 AudioRoute newRoute;
333 newRoute.sourcePortIds = r.sourcePortIds;
334 newRoute.sinkPortId = connectedPort.id;
335 newRoute.isExclusive = r.isExclusive;
336 newRoutes.push_back(std::move(newRoute));
337 } else {
338 auto& srcs = r.sourcePortIds;
339 if (std::find(srcs.begin(), srcs.end(), templateId) != srcs.end()) {
340 srcs.push_back(connectedPort.id);
341 }
342 }
343 }
344 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
345
346 return ndk::ScopedAStatus::ok();
347}
348
349ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
350 auto& ports = getConfig().ports;
351 auto portIt = findById<AudioPort>(ports, in_portId);
352 if (portIt == ports.end()) {
353 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
354 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
355 }
356 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
357 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a device port";
358 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
359 }
360 if (mConnectedDevicePorts.count(in_portId) == 0) {
361 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a connected device port";
362 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
363 }
364 auto& configs = getConfig().portConfigs;
365 auto& initials = getConfig().initialConfigs;
366 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
367 if (config.portId == in_portId) {
368 // Check if the configuration was provided by the client.
369 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
370 return initialIt == initials.end() || config != *initialIt;
371 }
372 return false;
373 });
374 if (configIt != configs.end()) {
375 LOG(ERROR) << __func__ << ": port id " << in_portId << " has a non-default config with id "
376 << configIt->id;
377 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
378 }
379 ports.erase(portIt);
380 mConnectedDevicePorts.erase(in_portId);
381 LOG(DEBUG) << __func__ << ": connected device port " << in_portId << " released";
382
383 auto& routes = getConfig().routes;
384 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
385 if (routesIt->sinkPortId == in_portId) {
386 routesIt = routes.erase(routesIt);
387 } else {
388 // Note: the list of sourcePortIds can't become empty because there must
389 // be the id of the template port in the route.
390 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
391 ++routesIt;
392 }
393 }
394
395 return ndk::ScopedAStatus::ok();
396}
397
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000398ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
399 *_aidl_return = getConfig().patches;
400 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " patches";
401 return ndk::ScopedAStatus::ok();
402}
403
404ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
405 auto& ports = getConfig().ports;
406 auto portIt = findById<AudioPort>(ports, in_portId);
407 if (portIt != ports.end()) {
408 *_aidl_return = *portIt;
409 LOG(DEBUG) << __func__ << ": returning port by id " << in_portId;
410 return ndk::ScopedAStatus::ok();
411 }
412 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
413 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
414}
415
416ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
417 *_aidl_return = getConfig().portConfigs;
418 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " port configs";
419 return ndk::ScopedAStatus::ok();
420}
421
422ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
423 *_aidl_return = getConfig().ports;
424 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " ports";
425 return ndk::ScopedAStatus::ok();
426}
427
428ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
429 *_aidl_return = getConfig().routes;
430 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " routes";
431 return ndk::ScopedAStatus::ok();
432}
433
Mikhail Naganov00603d12022-05-02 22:52:13 +0000434ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
435 std::vector<AudioRoute>* _aidl_return) {
436 auto& ports = getConfig().ports;
437 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
438 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
439 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
440 }
441 auto& routes = getConfig().routes;
442 std::copy_if(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
443 [&](const auto& r) {
444 const auto& srcs = r.sourcePortIds;
445 return r.sinkPortId == in_portId ||
446 std::find(srcs.begin(), srcs.end(), in_portId) != srcs.end();
447 });
448 return ndk::ScopedAStatus::ok();
449}
450
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000451ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
452 OpenInputStreamReturn* _aidl_return) {
453 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", buffer size "
454 << in_args.bufferSizeFrames << " frames";
455 AudioPort* port = nullptr;
456 if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
457 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000458 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000459 if (port->flags.getTag() != AudioIoFlags::Tag::input) {
460 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000461 << " does not correspond to an input mix port";
462 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
463 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000464 StreamContext context;
Mikhail Naganov30301a42022-09-13 01:20:45 +0000465 if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames, nullptr,
466 &context);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000467 !status.isOk()) {
468 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000469 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000470 context.fillDescriptor(&_aidl_return->desc);
471 auto stream = ndk::SharedRefBase::make<StreamIn>(in_args.sinkMetadata, std::move(context));
472 if (auto status = stream->init(); !status.isOk()) {
473 return status;
474 }
475 StreamWrapper streamWrapper(stream);
476 auto patchIt = mPatches.find(in_args.portConfigId);
477 if (patchIt != mPatches.end()) {
478 streamWrapper.setStreamIsConnected(true);
479 }
480 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000481 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000482 return ndk::ScopedAStatus::ok();
483}
484
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000485ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
486 OpenOutputStreamReturn* _aidl_return) {
487 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", has offload info? "
488 << (in_args.offloadInfo.has_value()) << ", buffer size " << in_args.bufferSizeFrames
489 << " frames";
490 AudioPort* port = nullptr;
491 if (auto status = findPortIdForNewStream(in_args.portConfigId, &port); !status.isOk()) {
492 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000493 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000494 if (port->flags.getTag() != AudioIoFlags::Tag::output) {
495 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000496 << " does not correspond to an output mix port";
497 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
498 }
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000499 const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
500 AudioOutputFlags::COMPRESS_OFFLOAD);
501 if (isOffload && !in_args.offloadInfo.has_value()) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000502 LOG(ERROR) << __func__ << ": port id " << port->id
Mikhail Naganov111e0ce2022-06-17 21:41:19 +0000503 << " has COMPRESS_OFFLOAD flag set, requires offload info";
504 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
505 }
Mikhail Naganov30301a42022-09-13 01:20:45 +0000506 const bool isNonBlocking = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
507 AudioOutputFlags::NON_BLOCKING);
508 if (isNonBlocking && in_args.callback == nullptr) {
509 LOG(ERROR) << __func__ << ": port id " << port->id
510 << " has NON_BLOCKING flag set, requires async callback";
511 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
512 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000513 StreamContext context;
Mikhail Naganov30301a42022-09-13 01:20:45 +0000514 if (auto status = createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
515 isNonBlocking ? in_args.callback : nullptr, &context);
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000516 !status.isOk()) {
517 return status;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000518 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000519 context.fillDescriptor(&_aidl_return->desc);
520 auto stream = ndk::SharedRefBase::make<StreamOut>(in_args.sourceMetadata, std::move(context),
521 in_args.offloadInfo);
522 if (auto status = stream->init(); !status.isOk()) {
523 return status;
524 }
525 StreamWrapper streamWrapper(stream);
526 auto patchIt = mPatches.find(in_args.portConfigId);
527 if (patchIt != mPatches.end()) {
528 streamWrapper.setStreamIsConnected(true);
529 }
530 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000531 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000532 return ndk::ScopedAStatus::ok();
533}
534
535ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
Mikhail Naganov16db9b72022-06-17 21:36:18 +0000536 LOG(DEBUG) << __func__ << ": requested patch " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000537 if (in_requested.sourcePortConfigIds.empty()) {
538 LOG(ERROR) << __func__ << ": requested patch has empty sources list";
539 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
540 }
541 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
542 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sources list";
543 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
544 }
545 if (in_requested.sinkPortConfigIds.empty()) {
546 LOG(ERROR) << __func__ << ": requested patch has empty sinks list";
547 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
548 }
549 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
550 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sinks list";
551 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
552 }
553
554 auto& configs = getConfig().portConfigs;
555 std::vector<int32_t> missingIds;
556 auto sources =
557 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
558 if (!missingIds.empty()) {
559 LOG(ERROR) << __func__ << ": following source port config ids not found: "
560 << ::android::internal::ToString(missingIds);
561 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
562 }
563 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
564 if (!missingIds.empty()) {
565 LOG(ERROR) << __func__ << ": following sink port config ids not found: "
566 << ::android::internal::ToString(missingIds);
567 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
568 }
569 // bool indicates whether a non-exclusive route is available.
570 // If only an exclusive route is available, that means the patch can not be
571 // established if there is any other patch which currently uses the sink port.
572 std::map<int32_t, bool> allowedSinkPorts;
573 auto& routes = getConfig().routes;
574 for (auto src : sources) {
575 for (const auto& r : routes) {
576 const auto& srcs = r.sourcePortIds;
577 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
578 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
579 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
580 }
581 }
582 }
583 }
584 for (auto sink : sinks) {
585 if (allowedSinkPorts.count(sink->portId) == 0) {
586 LOG(ERROR) << __func__ << ": there is no route to the sink port id " << sink->portId;
587 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
588 }
589 }
590
591 auto& patches = getConfig().patches;
592 auto existing = patches.end();
593 std::optional<decltype(mPatches)> patchesBackup;
594 if (in_requested.id != 0) {
595 existing = findById<AudioPatch>(patches, in_requested.id);
596 if (existing != patches.end()) {
597 patchesBackup = mPatches;
598 cleanUpPatch(existing->id);
599 } else {
600 LOG(ERROR) << __func__ << ": not found existing patch id " << in_requested.id;
601 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
602 }
603 }
604 // Validate the requested patch.
605 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
606 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
607 LOG(ERROR) << __func__ << ": sink port id " << sinkPortId
608 << "is exclusive and is already used by some other patch";
609 if (patchesBackup.has_value()) {
610 mPatches = std::move(*patchesBackup);
611 }
612 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
613 }
614 }
615 *_aidl_return = in_requested;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000616 _aidl_return->minimumStreamBufferSizeFrames = kMinimumStreamBufferSizeFrames;
617 _aidl_return->latenciesMs.clear();
618 _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
619 _aidl_return->sinkPortConfigIds.size(), kLatencyMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000620 AudioPatch oldPatch{};
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000621 if (existing == patches.end()) {
622 _aidl_return->id = getConfig().nextPatchId++;
623 patches.push_back(*_aidl_return);
624 existing = patches.begin() + (patches.size() - 1);
625 } else {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000626 oldPatch = *existing;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000627 *existing = *_aidl_return;
628 }
629 registerPatch(*existing);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000630 updateStreamsConnectedState(oldPatch, *_aidl_return);
631
632 LOG(DEBUG) << __func__ << ": " << (oldPatch.id == 0 ? "created" : "updated") << " patch "
633 << _aidl_return->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000634 return ndk::ScopedAStatus::ok();
635}
636
637ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
638 AudioPortConfig* out_suggested, bool* _aidl_return) {
639 LOG(DEBUG) << __func__ << ": requested " << in_requested.toString();
640 auto& configs = getConfig().portConfigs;
641 auto existing = configs.end();
642 if (in_requested.id != 0) {
643 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
644 existing == configs.end()) {
645 LOG(ERROR) << __func__ << ": existing port config id " << in_requested.id
646 << " not found";
647 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
648 }
649 }
650
651 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
652 if (portId == 0) {
653 LOG(ERROR) << __func__ << ": input port config does not specify portId";
654 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
655 }
656 auto& ports = getConfig().ports;
657 auto portIt = findById<AudioPort>(ports, portId);
658 if (portIt == ports.end()) {
659 LOG(ERROR) << __func__ << ": input port config points to non-existent portId " << portId;
660 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
661 }
662 if (existing != configs.end()) {
663 *out_suggested = *existing;
664 } else {
665 AudioPortConfig newConfig;
666 if (generateDefaultPortConfig(*portIt, &newConfig)) {
667 *out_suggested = newConfig;
668 } else {
669 LOG(ERROR) << __func__ << ": unable generate a default config for port " << portId;
670 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
671 }
672 }
673 // From this moment, 'out_suggested' is either an existing port config,
674 // or a new generated config. Now attempt to update it according to the specified
675 // fields of 'in_requested'.
676
677 bool requestedIsValid = true, requestedIsFullySpecified = true;
678
679 AudioIoFlags portFlags = portIt->flags;
680 if (in_requested.flags.has_value()) {
681 if (in_requested.flags.value() != portFlags) {
682 LOG(WARNING) << __func__ << ": requested flags "
683 << in_requested.flags.value().toString() << " do not match port's "
684 << portId << " flags " << portFlags.toString();
685 requestedIsValid = false;
686 }
687 } else {
688 requestedIsFullySpecified = false;
689 }
690
691 AudioProfile portProfile;
692 if (in_requested.format.has_value()) {
693 const auto& format = in_requested.format.value();
694 if (findAudioProfile(*portIt, format, &portProfile)) {
695 out_suggested->format = format;
696 } else {
697 LOG(WARNING) << __func__ << ": requested format " << format.toString()
698 << " is not found in port's " << portId << " profiles";
699 requestedIsValid = false;
700 }
701 } else {
702 requestedIsFullySpecified = false;
703 }
704 if (!findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
705 LOG(ERROR) << __func__ << ": port " << portId << " does not support format "
706 << out_suggested->format.value().toString() << " anymore";
707 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
708 }
709
710 if (in_requested.channelMask.has_value()) {
711 const auto& channelMask = in_requested.channelMask.value();
712 if (find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
713 portProfile.channelMasks.end()) {
714 out_suggested->channelMask = channelMask;
715 } else {
716 LOG(WARNING) << __func__ << ": requested channel mask " << channelMask.toString()
717 << " is not supported for the format " << portProfile.format.toString()
718 << " by the port " << portId;
719 requestedIsValid = false;
720 }
721 } else {
722 requestedIsFullySpecified = false;
723 }
724
725 if (in_requested.sampleRate.has_value()) {
726 const auto& sampleRate = in_requested.sampleRate.value();
727 if (find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
728 sampleRate.value) != portProfile.sampleRates.end()) {
729 out_suggested->sampleRate = sampleRate;
730 } else {
731 LOG(WARNING) << __func__ << ": requested sample rate " << sampleRate.value
732 << " is not supported for the format " << portProfile.format.toString()
733 << " by the port " << portId;
734 requestedIsValid = false;
735 }
736 } else {
737 requestedIsFullySpecified = false;
738 }
739
740 if (in_requested.gain.has_value()) {
741 // Let's pretend that gain can always be applied.
742 out_suggested->gain = in_requested.gain.value();
743 }
744
745 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
746 out_suggested->id = getConfig().nextPortId++;
747 configs.push_back(*out_suggested);
748 *_aidl_return = true;
749 LOG(DEBUG) << __func__ << ": created new port config " << out_suggested->toString();
750 } else if (existing != configs.end() && requestedIsValid) {
751 *existing = *out_suggested;
752 *_aidl_return = true;
753 LOG(DEBUG) << __func__ << ": updated port config " << out_suggested->toString();
754 } else {
755 LOG(DEBUG) << __func__ << ": not applied; existing config ? " << (existing != configs.end())
756 << "; requested is valid? " << requestedIsValid << ", fully specified? "
757 << requestedIsFullySpecified;
758 *_aidl_return = false;
759 }
760 return ndk::ScopedAStatus::ok();
761}
762
763ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
764 auto& patches = getConfig().patches;
765 auto patchIt = findById<AudioPatch>(patches, in_patchId);
766 if (patchIt != patches.end()) {
767 cleanUpPatch(patchIt->id);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000768 updateStreamsConnectedState(*patchIt, AudioPatch{});
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000769 patches.erase(patchIt);
770 LOG(DEBUG) << __func__ << ": erased patch " << in_patchId;
771 return ndk::ScopedAStatus::ok();
772 }
773 LOG(ERROR) << __func__ << ": patch id " << in_patchId << " not found";
774 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
775}
776
777ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
778 auto& configs = getConfig().portConfigs;
779 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
780 if (configIt != configs.end()) {
781 if (mStreams.count(in_portConfigId) != 0) {
782 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
783 << " has a stream opened on it";
784 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
785 }
786 auto patchIt = mPatches.find(in_portConfigId);
787 if (patchIt != mPatches.end()) {
788 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
789 << " is used by the patch with id " << patchIt->second;
790 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
791 }
792 auto& initials = getConfig().initialConfigs;
793 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
794 if (initialIt == initials.end()) {
795 configs.erase(configIt);
796 LOG(DEBUG) << __func__ << ": erased port config " << in_portConfigId;
797 } else if (*configIt != *initialIt) {
798 *configIt = *initialIt;
799 LOG(DEBUG) << __func__ << ": reset port config " << in_portConfigId;
800 }
801 return ndk::ScopedAStatus::ok();
802 }
803 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId << " not found";
804 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
805}
806
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000807ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) {
808 *_aidl_return = mMasterMute;
809 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
810 return ndk::ScopedAStatus::ok();
811}
812
813ndk::ScopedAStatus Module::setMasterMute(bool in_mute) {
814 LOG(DEBUG) << __func__ << ": " << in_mute;
815 mMasterMute = in_mute;
816 return ndk::ScopedAStatus::ok();
817}
818
819ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) {
820 *_aidl_return = mMasterVolume;
821 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
822 return ndk::ScopedAStatus::ok();
823}
824
825ndk::ScopedAStatus Module::setMasterVolume(float in_volume) {
826 LOG(DEBUG) << __func__ << ": " << in_volume;
827 if (in_volume >= 0.0f && in_volume <= 1.0f) {
828 mMasterVolume = in_volume;
829 return ndk::ScopedAStatus::ok();
830 }
831 LOG(ERROR) << __func__ << ": invalid master volume value: " << in_volume;
832 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
833}
834
835ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) {
836 *_aidl_return = mMicMute;
837 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
838 return ndk::ScopedAStatus::ok();
839}
840
841ndk::ScopedAStatus Module::setMicMute(bool in_mute) {
842 LOG(DEBUG) << __func__ << ": " << in_mute;
843 mMicMute = in_mute;
844 return ndk::ScopedAStatus::ok();
845}
846
847ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) {
848 // No checks for supported audio modes here, it's an informative notification.
849 LOG(DEBUG) << __func__ << ": " << toString(in_mode);
850 return ndk::ScopedAStatus::ok();
851}
852
853ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) {
854 LOG(DEBUG) << __func__ << ": " << toString(in_rotation);
855 return ndk::ScopedAStatus::ok();
856}
857
858ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) {
859 LOG(DEBUG) << __func__ << ": " << in_isTurnedOn;
860 return ndk::ScopedAStatus::ok();
861}
862
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000863} // namespace aidl::android::hardware::audio::core