blob: 0cda3bd8f56af1c2105f1706fbba5d4eb050bd58 [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 Naganov4f5d3f12022-07-22 23:23:25 +000021#include <Utils.h>
22#include <aidl/android/media/audio/common/AudioInputFlags.h>
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000023#include <aidl/android/media/audio/common/AudioOutputFlags.h>
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -070024#include <android-base/logging.h>
25#include <android/binder_ibinder_platform.h>
26#include <error/expected_utils.h>
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000027
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +000028#include "core-impl/Configuration.h"
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000029#include "core-impl/Module.h"
Mikhail Naganovb03b5c42023-07-26 13:13:35 -070030#include "core-impl/ModuleBluetooth.h"
Mikhail Naganov521fc492023-07-11 17:24:08 -070031#include "core-impl/ModulePrimary.h"
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053032#include "core-impl/ModuleRemoteSubmix.h"
Mikhail Naganov521fc492023-07-11 17:24:08 -070033#include "core-impl/ModuleStub.h"
jiabin253bd322023-01-25 23:57:31 +000034#include "core-impl/ModuleUsb.h"
Vlad Popa943b7e22022-12-08 14:24:12 +010035#include "core-impl/SoundDose.h"
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000036#include "core-impl/utils.h"
37
Mikhail Naganov872d4a62023-03-09 18:19:01 -080038using aidl::android::hardware::audio::common::getFrameSizeInBytes;
39using aidl::android::hardware::audio::common::isBitPositionFlagSet;
40using aidl::android::hardware::audio::common::isValidAudioMode;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000041using aidl::android::hardware::audio::common::SinkMetadata;
42using aidl::android::hardware::audio::common::SourceMetadata;
Vlad Popa2afbd1e2022-12-28 17:04:58 +010043using aidl::android::hardware::audio::core::sounddose::ISoundDose;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000044using aidl::android::media::audio::common::AudioChannelLayout;
Mikhail Naganovef6bc742022-10-06 00:14:19 +000045using aidl::android::media::audio::common::AudioDevice;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000046using aidl::android::media::audio::common::AudioFormatDescription;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000047using aidl::android::media::audio::common::AudioFormatType;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000048using aidl::android::media::audio::common::AudioInputFlags;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000049using aidl::android::media::audio::common::AudioIoFlags;
jiabin9a8e6862023-01-12 23:06:37 +000050using aidl::android::media::audio::common::AudioMMapPolicy;
51using aidl::android::media::audio::common::AudioMMapPolicyInfo;
52using aidl::android::media::audio::common::AudioMMapPolicyType;
Mikhail Naganov04ae8222023-01-11 15:48:10 -080053using aidl::android::media::audio::common::AudioMode;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000054using aidl::android::media::audio::common::AudioOffloadInfo;
55using aidl::android::media::audio::common::AudioOutputFlags;
56using aidl::android::media::audio::common::AudioPort;
57using aidl::android::media::audio::common::AudioPortConfig;
58using aidl::android::media::audio::common::AudioPortExt;
59using aidl::android::media::audio::common::AudioProfile;
Mikhail Naganov20047bc2023-01-05 20:16:07 +000060using aidl::android::media::audio::common::Boolean;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000061using aidl::android::media::audio::common::Int;
Mikhail Naganov6725ef52023-02-09 17:52:50 -080062using aidl::android::media::audio::common::MicrophoneInfo;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000063using aidl::android::media::audio::common::PcmType;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000064
65namespace aidl::android::hardware::audio::core {
66
67namespace {
68
Mikhail Naganov84bcc042023-10-05 17:36:57 -070069inline bool hasDynamicChannelMasks(const std::vector<AudioChannelLayout>& channelMasks) {
70 return channelMasks.empty() ||
71 std::all_of(channelMasks.begin(), channelMasks.end(),
72 [](const auto& channelMask) { return channelMask == AudioChannelLayout{}; });
73}
74
75inline bool hasDynamicFormat(const AudioFormatDescription& format) {
76 return format == AudioFormatDescription{};
77}
78
79inline bool hasDynamicSampleRates(const std::vector<int32_t>& sampleRates) {
80 return sampleRates.empty() ||
81 std::all_of(sampleRates.begin(), sampleRates.end(),
82 [](const auto& sampleRate) { return sampleRate == 0; });
83}
84
85inline bool isDynamicProfile(const AudioProfile& profile) {
86 return hasDynamicFormat(profile.format) || hasDynamicChannelMasks(profile.channelMasks) ||
87 hasDynamicSampleRates(profile.sampleRates);
88}
89
90bool hasDynamicProfilesOnly(const std::vector<AudioProfile>& profiles) {
91 if (profiles.empty()) return true;
92 return std::all_of(profiles.begin(), profiles.end(), isDynamicProfile);
93}
94
95// Note: does not assign an ID to the config.
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000096bool generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) {
Mikhail Naganov84bcc042023-10-05 17:36:57 -070097 const bool allowDynamicConfig = port.ext.getTag() == AudioPortExt::device;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000098 *config = {};
99 config->portId = port.id;
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700100 for (const auto& profile : port.profiles) {
101 if (isDynamicProfile(profile)) continue;
102 config->format = profile.format;
103 config->channelMask = *profile.channelMasks.begin();
104 config->sampleRate = Int{.value = *profile.sampleRates.begin()};
105 config->flags = port.flags;
106 config->ext = port.ext;
107 return true;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000108 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700109 if (allowDynamicConfig) {
110 config->format = AudioFormatDescription{};
111 config->channelMask = AudioChannelLayout{};
112 config->sampleRate = Int{.value = 0};
113 config->flags = port.flags;
114 config->ext = port.ext;
115 return true;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000116 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700117 LOG(ERROR) << __func__ << ": port " << port.id << " only has dynamic profiles";
118 return false;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000119}
120
121bool findAudioProfile(const AudioPort& port, const AudioFormatDescription& format,
122 AudioProfile* profile) {
123 if (auto profilesIt =
124 find_if(port.profiles.begin(), port.profiles.end(),
125 [&format](const auto& profile) { return profile.format == format; });
126 profilesIt != port.profiles.end()) {
127 *profile = *profilesIt;
128 return true;
129 }
130 return false;
131}
Mikhail Naganov00603d12022-05-02 22:52:13 +0000132
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000133} // namespace
134
jiabin253bd322023-01-25 23:57:31 +0000135// static
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000136std::shared_ptr<Module> Module::createInstance(Type type, std::unique_ptr<Configuration>&& config) {
jiabin253bd322023-01-25 23:57:31 +0000137 switch (type) {
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530138 case Type::DEFAULT:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000139 return ndk::SharedRefBase::make<ModulePrimary>(std::move(config));
Mikhail Naganov521fc492023-07-11 17:24:08 -0700140 case Type::R_SUBMIX:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000141 return ndk::SharedRefBase::make<ModuleRemoteSubmix>(std::move(config));
Mikhail Naganov521fc492023-07-11 17:24:08 -0700142 case Type::STUB:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000143 return ndk::SharedRefBase::make<ModuleStub>(std::move(config));
Mikhail Naganov521fc492023-07-11 17:24:08 -0700144 case Type::USB:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000145 return ndk::SharedRefBase::make<ModuleUsb>(std::move(config));
Mikhail Naganovb03b5c42023-07-26 13:13:35 -0700146 case Type::BLUETOOTH:
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000147 return ndk::SharedRefBase::make<ModuleBluetooth>(std::move(config));
jiabin253bd322023-01-25 23:57:31 +0000148 }
149}
150
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000151// static
152std::optional<Module::Type> Module::typeFromString(const std::string& type) {
153 if (type == "default")
154 return Module::Type::DEFAULT;
155 else if (type == "r_submix")
156 return Module::Type::R_SUBMIX;
157 else if (type == "stub")
158 return Module::Type::STUB;
159 else if (type == "usb")
160 return Module::Type::USB;
161 else if (type == "bluetooth")
162 return Module::Type::BLUETOOTH;
163 return {};
164}
165
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700166std::ostream& operator<<(std::ostream& os, Module::Type t) {
167 switch (t) {
168 case Module::Type::DEFAULT:
169 os << "default";
170 break;
171 case Module::Type::R_SUBMIX:
172 os << "r_submix";
173 break;
Mikhail Naganov521fc492023-07-11 17:24:08 -0700174 case Module::Type::STUB:
175 os << "stub";
176 break;
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700177 case Module::Type::USB:
178 os << "usb";
179 break;
Mikhail Naganovb03b5c42023-07-26 13:13:35 -0700180 case Module::Type::BLUETOOTH:
181 os << "bluetooth";
182 break;
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700183 }
184 return os;
185}
186
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000187void Module::cleanUpPatch(int32_t patchId) {
188 erase_all_values(mPatches, std::set<int32_t>{patchId});
189}
190
Mikhail Naganov8651b362023-01-06 23:15:27 +0000191ndk::ScopedAStatus Module::createStreamContext(
192 int32_t in_portConfigId, int64_t in_bufferSizeFrames,
193 std::shared_ptr<IStreamCallback> asyncCallback,
194 std::shared_ptr<IStreamOutEventCallback> outEventCallback, StreamContext* out_context) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000195 if (in_bufferSizeFrames <= 0) {
196 LOG(ERROR) << __func__ << ": non-positive buffer size " << in_bufferSizeFrames;
197 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
198 }
199 if (in_bufferSizeFrames < kMinimumStreamBufferSizeFrames) {
200 LOG(ERROR) << __func__ << ": insufficient buffer size " << in_bufferSizeFrames
201 << ", must be at least " << kMinimumStreamBufferSizeFrames;
202 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
203 }
204 auto& configs = getConfig().portConfigs;
205 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000206 // Since this is a private method, it is assumed that
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000207 // validity of the portConfigId has already been checked.
208 const size_t frameSize =
209 getFrameSizeInBytes(portConfigIt->format.value(), portConfigIt->channelMask.value());
210 if (frameSize == 0) {
211 LOG(ERROR) << __func__ << ": could not calculate frame size for port config "
212 << portConfigIt->toString();
213 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
214 }
215 LOG(DEBUG) << __func__ << ": frame size " << frameSize << " bytes";
Mikhail Naganovb511b8a2023-05-15 14:35:24 -0700216 if (frameSize > static_cast<size_t>(kMaximumStreamBufferSizeBytes / in_bufferSizeFrames)) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000217 LOG(ERROR) << __func__ << ": buffer size " << in_bufferSizeFrames
218 << " frames is too large, maximum size is "
219 << kMaximumStreamBufferSizeBytes / frameSize;
220 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
221 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000222 const auto& flags = portConfigIt->flags.value();
223 if ((flags.getTag() == AudioIoFlags::Tag::input &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000224 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::input>(),
225 AudioInputFlags::MMAP_NOIRQ)) ||
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000226 (flags.getTag() == AudioIoFlags::Tag::output &&
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000227 !isBitPositionFlagSet(flags.get<AudioIoFlags::Tag::output>(),
228 AudioOutputFlags::MMAP_NOIRQ))) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +0000229 StreamContext::DebugParameters params{mDebug.streamTransientStateDelayMs,
Mikhail Naganov194daaa2023-01-05 22:34:20 +0000230 mVendorDebug.forceTransientBurst,
231 mVendorDebug.forceSynchronousDrain};
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000232 StreamContext temp(
233 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
234 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530235 portConfigIt->portId, portConfigIt->format.value(),
236 portConfigIt->channelMask.value(), portConfigIt->sampleRate.value().value, flags,
Mikhail Naganovb42a69e2023-06-16 12:38:25 -0700237 portConfigIt->ext.get<AudioPortExt::mix>().handle,
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000238 std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames),
Mikhail Naganov8651b362023-01-06 23:15:27 +0000239 asyncCallback, outEventCallback, params);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000240 if (temp.isValid()) {
241 *out_context = std::move(temp);
242 } else {
243 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
244 }
245 } else {
246 // TODO: Implement simulation of MMAP buffer allocation
247 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000248 return ndk::ScopedAStatus::ok();
249}
250
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000251std::vector<AudioDevice> Module::findConnectedDevices(int32_t portConfigId) {
252 std::vector<AudioDevice> result;
253 auto& ports = getConfig().ports;
254 auto portIds = portIdsFromPortConfigIds(findConnectedPortConfigIds(portConfigId));
255 for (auto it = portIds.begin(); it != portIds.end(); ++it) {
256 auto portIt = findById<AudioPort>(ports, *it);
257 if (portIt != ports.end() && portIt->ext.getTag() == AudioPortExt::Tag::device) {
258 result.push_back(portIt->ext.template get<AudioPortExt::Tag::device>().device);
259 }
260 }
261 return result;
262}
263
264std::set<int32_t> Module::findConnectedPortConfigIds(int32_t portConfigId) {
265 std::set<int32_t> result;
266 auto patchIdsRange = mPatches.equal_range(portConfigId);
267 auto& patches = getConfig().patches;
268 for (auto it = patchIdsRange.first; it != patchIdsRange.second; ++it) {
269 auto patchIt = findById<AudioPatch>(patches, it->second);
270 if (patchIt == patches.end()) {
271 LOG(FATAL) << __func__ << ": patch with id " << it->second << " taken from mPatches "
272 << "not found in the configuration";
273 }
274 if (std::find(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end(),
275 portConfigId) != patchIt->sourcePortConfigIds.end()) {
276 result.insert(patchIt->sinkPortConfigIds.begin(), patchIt->sinkPortConfigIds.end());
277 } else {
278 result.insert(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end());
279 }
280 }
281 return result;
282}
283
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000284ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) {
285 auto& configs = getConfig().portConfigs;
286 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
287 if (portConfigIt == configs.end()) {
288 LOG(ERROR) << __func__ << ": existing port config id " << in_portConfigId << " not found";
289 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
290 }
291 const int32_t portId = portConfigIt->portId;
292 // In our implementation, configs of mix ports always have unique IDs.
293 CHECK(portId != in_portConfigId);
294 auto& ports = getConfig().ports;
295 auto portIt = findById<AudioPort>(ports, portId);
296 if (portIt == ports.end()) {
297 LOG(ERROR) << __func__ << ": port id " << portId << " used by port config id "
298 << in_portConfigId << " not found";
299 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
300 }
301 if (mStreams.count(in_portConfigId) != 0) {
302 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
303 << " already has a stream opened on it";
304 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
305 }
306 if (portIt->ext.getTag() != AudioPortExt::Tag::mix) {
307 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
308 << " does not correspond to a mix port";
309 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
310 }
Mikhail Naganovb511b8a2023-05-15 14:35:24 -0700311 const size_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000312 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
313 LOG(ERROR) << __func__ << ": port id " << portId
314 << " has already reached maximum allowed opened stream count: "
315 << maxOpenStreamCount;
316 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
317 }
318 *port = &(*portIt);
319 return ndk::ScopedAStatus::ok();
320}
321
Mikhail Naganovef6bc742022-10-06 00:14:19 +0000322template <typename C>
323std::set<int32_t> Module::portIdsFromPortConfigIds(C portConfigIds) {
324 std::set<int32_t> result;
325 auto& portConfigs = getConfig().portConfigs;
326 for (auto it = portConfigIds.begin(); it != portConfigIds.end(); ++it) {
327 auto portConfigIt = findById<AudioPortConfig>(portConfigs, *it);
328 if (portConfigIt != portConfigs.end()) {
329 result.insert(portConfigIt->portId);
330 }
331 }
332 return result;
333}
334
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000335std::unique_ptr<Module::Configuration> Module::initializeConfig() {
336 return internal::getConfiguration(getType());
Peter Yoon918a6a52023-07-13 17:04:37 +0900337}
338
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700339std::vector<AudioRoute*> Module::getAudioRoutesForAudioPortImpl(int32_t portId) {
340 std::vector<AudioRoute*> result;
341 auto& routes = getConfig().routes;
342 for (auto& r : routes) {
343 const auto& srcs = r.sourcePortIds;
344 if (r.sinkPortId == portId || std::find(srcs.begin(), srcs.end(), portId) != srcs.end()) {
345 result.push_back(&r);
346 }
347 }
348 return result;
349}
350
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000351Module::Configuration& Module::getConfig() {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000352 if (!mConfig) {
Peter Yoon918a6a52023-07-13 17:04:37 +0900353 mConfig = std::move(initializeConfig());
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000354 }
355 return *mConfig;
356}
357
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700358std::set<int32_t> Module::getRoutableAudioPortIds(int32_t portId,
359 std::vector<AudioRoute*>* routes) {
360 std::vector<AudioRoute*> routesStorage;
361 if (routes == nullptr) {
362 routesStorage = getAudioRoutesForAudioPortImpl(portId);
363 routes = &routesStorage;
364 }
365 std::set<int32_t> result;
366 for (AudioRoute* r : *routes) {
367 if (r->sinkPortId == portId) {
368 result.insert(r->sourcePortIds.begin(), r->sourcePortIds.end());
369 } else {
370 result.insert(r->sinkPortId);
371 }
372 }
373 return result;
374}
375
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000376void Module::registerPatch(const AudioPatch& patch) {
377 auto& configs = getConfig().portConfigs;
378 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
379 for (auto portConfigId : portConfigIds) {
380 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
381 if (configIt != configs.end()) {
382 mPatches.insert(std::pair{portConfigId, patch.id});
383 if (configIt->portId != portConfigId) {
384 mPatches.insert(std::pair{configIt->portId, patch.id});
385 }
386 }
387 };
388 };
389 do_insert(patch.sourcePortConfigIds);
390 do_insert(patch.sinkPortConfigIds);
391}
392
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700393ndk::ScopedAStatus Module::updateStreamsConnectedState(const AudioPatch& oldPatch,
394 const AudioPatch& newPatch) {
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700395 // Notify streams about the new set of devices they are connected to.
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700396 auto maybeFailure = ndk::ScopedAStatus::ok();
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700397 using Connections =
398 std::map<int32_t /*mixPortConfigId*/, std::set<int32_t /*devicePortConfigId*/>>;
399 Connections oldConnections, newConnections;
400 auto fillConnectionsHelper = [&](Connections& connections,
401 const std::vector<int32_t>& mixPortCfgIds,
402 const std::vector<int32_t>& devicePortCfgIds) {
403 for (int32_t mixPortCfgId : mixPortCfgIds) {
404 connections[mixPortCfgId].insert(devicePortCfgIds.begin(), devicePortCfgIds.end());
405 }
406 };
407 auto fillConnections = [&](Connections& connections, const AudioPatch& patch) {
408 if (std::find_if(patch.sourcePortConfigIds.begin(), patch.sourcePortConfigIds.end(),
409 [&](int32_t portConfigId) { return mStreams.count(portConfigId) > 0; }) !=
410 patch.sourcePortConfigIds.end()) {
411 // Sources are mix ports.
412 fillConnectionsHelper(connections, patch.sourcePortConfigIds, patch.sinkPortConfigIds);
413 } else if (std::find_if(patch.sinkPortConfigIds.begin(), patch.sinkPortConfigIds.end(),
414 [&](int32_t portConfigId) {
415 return mStreams.count(portConfigId) > 0;
416 }) != patch.sinkPortConfigIds.end()) {
417 // Sources are device ports.
418 fillConnectionsHelper(connections, patch.sinkPortConfigIds, patch.sourcePortConfigIds);
419 } // Otherwise, there are no streams to notify.
420 };
421 fillConnections(oldConnections, oldPatch);
422 fillConnections(newConnections, newPatch);
423
424 std::for_each(oldConnections.begin(), oldConnections.end(), [&](const auto& connectionPair) {
425 const int32_t mixPortConfigId = connectionPair.first;
426 if (auto it = newConnections.find(mixPortConfigId);
427 it == newConnections.end() || it->second != connectionPair.second) {
428 if (auto status = mStreams.setStreamConnectedDevices(mixPortConfigId, {});
429 status.isOk()) {
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700430 LOG(DEBUG) << "updateStreamsConnectedState: The stream on port config id "
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700431 << mixPortConfigId << " has been disconnected";
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700432 } else {
433 // Disconnection is tricky to roll back, just register a failure.
434 maybeFailure = std::move(status);
435 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000436 }
437 });
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700438 if (!maybeFailure.isOk()) return maybeFailure;
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700439 std::set<int32_t> idsToDisconnectOnFailure;
440 std::for_each(newConnections.begin(), newConnections.end(), [&](const auto& connectionPair) {
441 const int32_t mixPortConfigId = connectionPair.first;
442 if (auto it = oldConnections.find(mixPortConfigId);
443 it == oldConnections.end() || it->second != connectionPair.second) {
444 const auto connectedDevices = findConnectedDevices(mixPortConfigId);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700445 if (connectedDevices.empty()) {
446 // This is important as workers use the vector size to derive the connection status.
447 LOG(FATAL) << "updateStreamsConnectedState: No connected devices found for port "
448 "config id "
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700449 << mixPortConfigId;
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700450 }
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700451 if (auto status = mStreams.setStreamConnectedDevices(mixPortConfigId, connectedDevices);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700452 status.isOk()) {
453 LOG(DEBUG) << "updateStreamsConnectedState: The stream on port config id "
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700454 << mixPortConfigId << " has been connected to: "
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700455 << ::android::internal::ToString(connectedDevices);
456 } else {
457 maybeFailure = std::move(status);
Mikhail Naganov89a8ea92023-09-29 17:02:12 -0700458 idsToDisconnectOnFailure.insert(mixPortConfigId);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700459 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000460 }
461 });
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700462 if (!maybeFailure.isOk()) {
463 LOG(WARNING) << __func__ << ": Due to a failure, disconnecting streams on port config ids "
464 << ::android::internal::ToString(idsToDisconnectOnFailure);
465 std::for_each(idsToDisconnectOnFailure.begin(), idsToDisconnectOnFailure.end(),
466 [&](const auto& portConfigId) {
467 auto status = mStreams.setStreamConnectedDevices(portConfigId, {});
468 (void)status.isOk(); // Can't do much about a failure here.
469 });
470 return maybeFailure;
471 }
472 return ndk::ScopedAStatus::ok();
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000473}
474
Mikhail Naganov00603d12022-05-02 22:52:13 +0000475ndk::ScopedAStatus Module::setModuleDebug(
476 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700477 LOG(DEBUG) << __func__ << ": " << mType << ": old flags:" << mDebug.toString()
Mikhail Naganov00603d12022-05-02 22:52:13 +0000478 << ", new flags: " << in_debug.toString();
479 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
480 !mConnectedDevicePorts.empty()) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700481 LOG(ERROR) << __func__ << ": " << mType
482 << ": attempting to change device connections simulation while having external "
483 << "devices connected";
Mikhail Naganov00603d12022-05-02 22:52:13 +0000484 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
485 }
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000486 if (in_debug.streamTransientStateDelayMs < 0) {
Mikhail Naganovd5536d92023-03-24 18:27:58 -0700487 LOG(ERROR) << __func__ << ": " << mType << ": streamTransientStateDelayMs is negative: "
Mikhail Naganovbd483c02022-11-17 20:33:39 +0000488 << in_debug.streamTransientStateDelayMs;
489 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
490 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000491 mDebug = in_debug;
492 return ndk::ScopedAStatus::ok();
493}
494
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000495ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700496 *_aidl_return = nullptr;
497 LOG(DEBUG) << __func__ << ": returning null";
Mikhail Naganov3b125b72022-10-05 02:12:39 +0000498 return ndk::ScopedAStatus::ok();
499}
500
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000501ndk::ScopedAStatus Module::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700502 *_aidl_return = nullptr;
503 LOG(DEBUG) << __func__ << ": returning null";
Mikhail Naganov10c6fe22022-09-30 23:49:17 +0000504 return ndk::ScopedAStatus::ok();
505}
506
Mikhail Naganov7499a002023-02-27 18:51:44 -0800507ndk::ScopedAStatus Module::getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700508 *_aidl_return = nullptr;
509 LOG(DEBUG) << __func__ << ": returning null";
Mikhail Naganov7499a002023-02-27 18:51:44 -0800510 return ndk::ScopedAStatus::ok();
511}
512
Mikhail Naganovb5647da2023-03-06 14:37:38 -0800513ndk::ScopedAStatus Module::getBluetoothLe(std::shared_ptr<IBluetoothLe>* _aidl_return) {
Mikhail Naganov521fc492023-07-11 17:24:08 -0700514 *_aidl_return = nullptr;
515 LOG(DEBUG) << __func__ << ": returning null";
Mikhail Naganovb5647da2023-03-06 14:37:38 -0800516 return ndk::ScopedAStatus::ok();
517}
518
Mikhail Naganov00603d12022-05-02 22:52:13 +0000519ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
520 AudioPort* _aidl_return) {
521 const int32_t templateId = in_templateIdAndAdditionalData.id;
522 auto& ports = getConfig().ports;
523 AudioPort connectedPort;
524 { // Scope the template port so that we don't accidentally modify it.
525 auto templateIt = findById<AudioPort>(ports, templateId);
526 if (templateIt == ports.end()) {
527 LOG(ERROR) << __func__ << ": port id " << templateId << " not found";
528 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
529 }
530 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
531 LOG(ERROR) << __func__ << ": port id " << templateId << " is not a device port";
532 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
533 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000534 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
535 if (templateDevicePort.device.type.connection.empty()) {
536 LOG(ERROR) << __func__ << ": port id " << templateId << " is permanently attached";
537 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
538 }
Mikhail Naganovfcf980e2023-09-07 16:30:11 -0700539 if (mConnectedDevicePorts.find(templateId) != mConnectedDevicePorts.end()) {
540 LOG(ERROR) << __func__ << ": port id " << templateId << " is a connected device port";
541 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
542 }
Mikhail Naganov00603d12022-05-02 22:52:13 +0000543 // Postpone id allocation until we ensure that there are no client errors.
544 connectedPort = *templateIt;
545 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
546 const auto& inputDevicePort =
547 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
548 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
549 connectedDevicePort.device.address = inputDevicePort.device.address;
550 LOG(DEBUG) << __func__ << ": device port " << connectedPort.id << " device set to "
551 << connectedDevicePort.device.toString();
552 // Check if there is already a connected port with for the same external device.
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700553 for (auto connectedPortPair : mConnectedDevicePorts) {
554 auto connectedPortIt = findById<AudioPort>(ports, connectedPortPair.first);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000555 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
556 connectedDevicePort.device) {
557 LOG(ERROR) << __func__ << ": device " << connectedDevicePort.device.toString()
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700558 << " is already connected at the device port id "
559 << connectedPortPair.first;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000560 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
561 }
562 }
563 }
564
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700565 // Two main cases are considered with regard to the profiles of the connected device port:
566 //
567 // 1. If the template device port has dynamic profiles, and at least one routable mix
568 // port also has dynamic profiles, it means that after connecting the device, the
569 // connected device port must have profiles populated with actual capabilities of
570 // the connected device, and dynamic of routable mix ports will be filled
571 // according to these capabilities. An example of this case is connection of an
572 // HDMI or USB device. For USB handled by ADSP, there can be mix ports with static
573 // profiles, and one dedicated mix port for "hi-fi" playback. The latter is left with
574 // dynamic profiles so that they can be populated with actual capabilities of
575 // the connected device.
576 //
577 // 2. If the template device port has dynamic profiles, while all routable mix ports
578 // have static profiles, it means that after connecting the device, the connected
579 // device port can be left with dynamic profiles, and profiles of mix ports are
580 // left untouched. An example of this case is connection of an analog wired
581 // headset, it should be treated in the same way as a speaker.
582 //
583 // Yet another possible case is when both the template device port and all routable
584 // mix ports have static profiles. This is allowed and handled correctly, however, it
585 // is not very practical, since these profiles are likely duplicates of each other.
586
587 std::vector<AudioRoute*> routesToMixPorts = getAudioRoutesForAudioPortImpl(templateId);
588 std::set<int32_t> routableMixPortIds = getRoutableAudioPortIds(templateId, &routesToMixPorts);
589 if (hasDynamicProfilesOnly(connectedPort.profiles)) {
Mikhail Naganovfcf980e2023-09-07 16:30:11 -0700590 if (!mDebug.simulateDeviceConnections) {
591 RETURN_STATUS_IF_ERROR(populateConnectedDevicePort(&connectedPort));
592 } else {
593 auto& connectedProfiles = getConfig().connectedProfiles;
594 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
595 connectedProfilesIt != connectedProfiles.end()) {
596 connectedPort.profiles = connectedProfilesIt->second;
597 }
598 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700599 if (hasDynamicProfilesOnly(connectedPort.profiles)) {
600 // Possible case 2. Check if all routable mix ports have static profiles.
601 if (auto dynamicMixPortIt = std::find_if(ports.begin(), ports.end(),
602 [&routableMixPortIds](const auto& p) {
603 return routableMixPortIds.count(p.id) >
604 0 &&
605 hasDynamicProfilesOnly(p.profiles);
606 });
607 dynamicMixPortIt != ports.end()) {
608 LOG(ERROR) << __func__
609 << ": connected port only has dynamic profiles after connecting "
610 << "external device " << connectedPort.toString() << ", and there exist "
611 << "a routable mix port with dynamic profiles: "
612 << dynamicMixPortIt->toString();
613 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
614 }
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530615 }
616 }
617
Mikhail Naganovdc417732023-09-29 15:49:35 -0700618 connectedPort.id = getConfig().nextPortId++;
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700619 auto [connectedPortsIt, _] =
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700620 mConnectedDevicePorts.insert(std::pair(connectedPort.id, std::set<int32_t>()));
Mikhail Naganov00603d12022-05-02 22:52:13 +0000621 LOG(DEBUG) << __func__ << ": template port " << templateId << " external device connected, "
622 << "connected port ID " << connectedPort.id;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000623 ports.push_back(connectedPort);
jiabin783c48b2023-02-28 18:28:06 +0000624 onExternalDeviceConnectionChanged(connectedPort, true /*connected*/);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000625
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700626 // For routes where the template port is a source, add the connected port to sources,
627 // otherwise, create a new route by copying from the route for the template port.
Mikhail Naganov00603d12022-05-02 22:52:13 +0000628 std::vector<AudioRoute> newRoutes;
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700629 for (AudioRoute* r : routesToMixPorts) {
630 if (r->sinkPortId == templateId) {
631 newRoutes.push_back(AudioRoute{.sourcePortIds = r->sourcePortIds,
632 .sinkPortId = connectedPort.id,
633 .isExclusive = r->isExclusive});
Mikhail Naganov00603d12022-05-02 22:52:13 +0000634 } else {
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700635 r->sourcePortIds.push_back(connectedPort.id);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000636 }
637 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700638 auto& routes = getConfig().routes;
Mikhail Naganov00603d12022-05-02 22:52:13 +0000639 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
640
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700641 if (!hasDynamicProfilesOnly(connectedPort.profiles) && !routableMixPortIds.empty()) {
642 // Note: this is a simplistic approach assuming that a mix port can only be populated
643 // from a single device port. Implementing support for stuffing dynamic profiles with
644 // a superset of all profiles from all routable dynamic device ports would be more involved.
645 for (auto& port : ports) {
646 if (routableMixPortIds.count(port.id) == 0) continue;
647 if (hasDynamicProfilesOnly(port.profiles)) {
648 port.profiles = connectedPort.profiles;
649 connectedPortsIt->second.insert(port.id);
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700650 } else {
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700651 // Check if profiles are not all dynamic because they were populated by
652 // a previous connection. Otherwise, it means that they are actually static.
653 for (const auto& cp : mConnectedDevicePorts) {
654 if (cp.second.count(port.id) > 0) {
655 connectedPortsIt->second.insert(port.id);
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700656 break;
657 }
658 }
659 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700660 }
661 }
662 *_aidl_return = std::move(connectedPort);
663
Mikhail Naganov00603d12022-05-02 22:52:13 +0000664 return ndk::ScopedAStatus::ok();
665}
666
667ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
668 auto& ports = getConfig().ports;
669 auto portIt = findById<AudioPort>(ports, in_portId);
670 if (portIt == ports.end()) {
671 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
672 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
673 }
674 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
675 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a device port";
676 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
677 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700678 auto connectedPortsIt = mConnectedDevicePorts.find(in_portId);
679 if (connectedPortsIt == mConnectedDevicePorts.end()) {
Mikhail Naganov00603d12022-05-02 22:52:13 +0000680 LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a connected device port";
681 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
682 }
683 auto& configs = getConfig().portConfigs;
684 auto& initials = getConfig().initialConfigs;
685 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
686 if (config.portId == in_portId) {
687 // Check if the configuration was provided by the client.
688 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
689 return initialIt == initials.end() || config != *initialIt;
690 }
691 return false;
692 });
693 if (configIt != configs.end()) {
694 LOG(ERROR) << __func__ << ": port id " << in_portId << " has a non-default config with id "
695 << configIt->id;
696 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
697 }
jiabin783c48b2023-02-28 18:28:06 +0000698 onExternalDeviceConnectionChanged(*portIt, false /*connected*/);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000699 ports.erase(portIt);
Mikhail Naganov00603d12022-05-02 22:52:13 +0000700 LOG(DEBUG) << __func__ << ": connected device port " << in_portId << " released";
701
702 auto& routes = getConfig().routes;
703 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
704 if (routesIt->sinkPortId == in_portId) {
705 routesIt = routes.erase(routesIt);
706 } else {
707 // Note: the list of sourcePortIds can't become empty because there must
708 // be the id of the template port in the route.
709 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
710 ++routesIt;
711 }
712 }
713
Mikhail Naganov0e128dd2023-09-13 18:01:18 -0700714 // Clear profiles for mix ports that are not connected to any other ports.
715 std::set<int32_t> mixPortsToClear = std::move(connectedPortsIt->second);
716 mConnectedDevicePorts.erase(connectedPortsIt);
717 for (const auto& connectedPort : mConnectedDevicePorts) {
718 for (int32_t mixPortId : connectedPort.second) {
719 mixPortsToClear.erase(mixPortId);
720 }
721 }
722 for (int32_t mixPortId : mixPortsToClear) {
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700723 auto mixPortIt = findById<AudioPort>(ports, mixPortId);
724 if (mixPortIt != ports.end()) {
725 mixPortIt->profiles = {};
726 }
727 }
Mikhail Naganov7b2d12b2023-03-24 18:29:14 -0700728
Mikhail Naganov00603d12022-05-02 22:52:13 +0000729 return ndk::ScopedAStatus::ok();
730}
731
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000732ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
733 *_aidl_return = getConfig().patches;
734 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " patches";
735 return ndk::ScopedAStatus::ok();
736}
737
738ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
739 auto& ports = getConfig().ports;
740 auto portIt = findById<AudioPort>(ports, in_portId);
741 if (portIt != ports.end()) {
742 *_aidl_return = *portIt;
743 LOG(DEBUG) << __func__ << ": returning port by id " << in_portId;
744 return ndk::ScopedAStatus::ok();
745 }
746 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
747 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
748}
749
750ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
751 *_aidl_return = getConfig().portConfigs;
752 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " port configs";
753 return ndk::ScopedAStatus::ok();
754}
755
756ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
757 *_aidl_return = getConfig().ports;
758 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " ports";
759 return ndk::ScopedAStatus::ok();
760}
761
762ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
763 *_aidl_return = getConfig().routes;
764 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " routes";
765 return ndk::ScopedAStatus::ok();
766}
767
Mikhail Naganov00603d12022-05-02 22:52:13 +0000768ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
769 std::vector<AudioRoute>* _aidl_return) {
770 auto& ports = getConfig().ports;
771 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
772 LOG(ERROR) << __func__ << ": port id " << in_portId << " not found";
773 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
774 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700775 std::vector<AudioRoute*> routes = getAudioRoutesForAudioPortImpl(in_portId);
776 std::transform(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
777 [](auto rptr) { return *rptr; });
Mikhail Naganov00603d12022-05-02 22:52:13 +0000778 return ndk::ScopedAStatus::ok();
779}
780
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000781ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
782 OpenInputStreamReturn* _aidl_return) {
783 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", buffer size "
784 << in_args.bufferSizeFrames << " frames";
785 AudioPort* port = nullptr;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700786 RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000787 if (port->flags.getTag() != AudioIoFlags::Tag::input) {
788 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000789 << " does not correspond to an input mix port";
790 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
791 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000792 StreamContext context;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700793 RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
794 nullptr, nullptr, &context));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000795 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000796 std::shared_ptr<StreamIn> stream;
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700797 RETURN_STATUS_IF_ERROR(createInputStream(std::move(context), in_args.sinkMetadata,
Lorena Torres-Huerta394e2522022-12-20 02:21:41 +0000798 getConfig().microphones, &stream));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000799 StreamWrapper streamWrapper(stream);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700800 if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
801 RETURN_STATUS_IF_ERROR(
802 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
803 }
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000804 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
805 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000806 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000807 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000808 return ndk::ScopedAStatus::ok();
809}
810
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000811ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
812 OpenOutputStreamReturn* _aidl_return) {
813 LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", has offload info? "
814 << (in_args.offloadInfo.has_value()) << ", buffer size " << in_args.bufferSizeFrames
815 << " frames";
816 AudioPort* port = nullptr;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700817 RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000818 if (port->flags.getTag() != AudioIoFlags::Tag::output) {
819 LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000820 << " does not correspond to an output mix port";
821 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
822 }
Mikhail Naganova2c5ddf2022-09-12 22:57:14 +0000823 const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
824 AudioOutputFlags::COMPRESS_OFFLOAD);
825 if (isOffload && !in_args.offloadInfo.has_value()) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000826 LOG(ERROR) << __func__ << ": port id " << port->id
Mikhail Naganov111e0ce2022-06-17 21:41:19 +0000827 << " has COMPRESS_OFFLOAD flag set, requires offload info";
828 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
829 }
Mikhail Naganov30301a42022-09-13 01:20:45 +0000830 const bool isNonBlocking = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
831 AudioOutputFlags::NON_BLOCKING);
832 if (isNonBlocking && in_args.callback == nullptr) {
833 LOG(ERROR) << __func__ << ": port id " << port->id
834 << " has NON_BLOCKING flag set, requires async callback";
835 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
836 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000837 StreamContext context;
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700838 RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
839 isNonBlocking ? in_args.callback : nullptr,
840 in_args.eventCallback, &context));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000841 context.fillDescriptor(&_aidl_return->desc);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +0000842 std::shared_ptr<StreamOut> stream;
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700843 RETURN_STATUS_IF_ERROR(createOutputStream(std::move(context), in_args.sourceMetadata,
Mikhail Naganov9d16a6a2023-06-26 17:21:04 -0700844 in_args.offloadInfo, &stream));
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000845 StreamWrapper streamWrapper(stream);
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700846 if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
847 RETURN_STATUS_IF_ERROR(
848 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
849 }
Mikhail Naganovdf5feba2022-12-15 00:11:14 +0000850 AIBinder_setMinSchedulerPolicy(streamWrapper.getBinder().get(), SCHED_NORMAL,
851 ANDROID_PRIORITY_AUDIO);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000852 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000853 _aidl_return->stream = std::move(stream);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000854 return ndk::ScopedAStatus::ok();
855}
856
Mikhail Naganov74927202022-12-19 16:37:14 +0000857ndk::ScopedAStatus Module::getSupportedPlaybackRateFactors(
858 SupportedPlaybackRateFactors* _aidl_return) {
859 LOG(DEBUG) << __func__;
860 (void)_aidl_return;
861 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
862}
863
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000864ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
Mikhail Naganov16db9b72022-06-17 21:36:18 +0000865 LOG(DEBUG) << __func__ << ": requested patch " << in_requested.toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000866 if (in_requested.sourcePortConfigIds.empty()) {
867 LOG(ERROR) << __func__ << ": requested patch has empty sources list";
868 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
869 }
870 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
871 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sources list";
872 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
873 }
874 if (in_requested.sinkPortConfigIds.empty()) {
875 LOG(ERROR) << __func__ << ": requested patch has empty sinks list";
876 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
877 }
878 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
879 LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sinks list";
880 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
881 }
882
883 auto& configs = getConfig().portConfigs;
884 std::vector<int32_t> missingIds;
885 auto sources =
886 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
887 if (!missingIds.empty()) {
888 LOG(ERROR) << __func__ << ": following source port config ids not found: "
889 << ::android::internal::ToString(missingIds);
890 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
891 }
892 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
893 if (!missingIds.empty()) {
894 LOG(ERROR) << __func__ << ": following sink port config ids not found: "
895 << ::android::internal::ToString(missingIds);
896 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
897 }
898 // bool indicates whether a non-exclusive route is available.
899 // If only an exclusive route is available, that means the patch can not be
900 // established if there is any other patch which currently uses the sink port.
901 std::map<int32_t, bool> allowedSinkPorts;
902 auto& routes = getConfig().routes;
903 for (auto src : sources) {
904 for (const auto& r : routes) {
905 const auto& srcs = r.sourcePortIds;
906 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
907 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
908 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
909 }
910 }
911 }
912 }
913 for (auto sink : sinks) {
914 if (allowedSinkPorts.count(sink->portId) == 0) {
915 LOG(ERROR) << __func__ << ": there is no route to the sink port id " << sink->portId;
916 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
917 }
918 }
Mikhail Naganov26dc9ad2023-06-23 13:55:37 -0700919 RETURN_STATUS_IF_ERROR(checkAudioPatchEndpointsMatch(sources, sinks));
jiabin253bd322023-01-25 23:57:31 +0000920
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000921 auto& patches = getConfig().patches;
922 auto existing = patches.end();
923 std::optional<decltype(mPatches)> patchesBackup;
924 if (in_requested.id != 0) {
925 existing = findById<AudioPatch>(patches, in_requested.id);
926 if (existing != patches.end()) {
927 patchesBackup = mPatches;
928 cleanUpPatch(existing->id);
929 } else {
930 LOG(ERROR) << __func__ << ": not found existing patch id " << in_requested.id;
931 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
932 }
933 }
934 // Validate the requested patch.
935 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
936 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
937 LOG(ERROR) << __func__ << ": sink port id " << sinkPortId
938 << "is exclusive and is already used by some other patch";
939 if (patchesBackup.has_value()) {
940 mPatches = std::move(*patchesBackup);
941 }
942 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
943 }
944 }
945 *_aidl_return = in_requested;
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000946 _aidl_return->minimumStreamBufferSizeFrames = kMinimumStreamBufferSizeFrames;
947 _aidl_return->latenciesMs.clear();
948 _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
949 _aidl_return->sinkPortConfigIds.size(), kLatencyMs);
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000950 AudioPatch oldPatch{};
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000951 if (existing == patches.end()) {
952 _aidl_return->id = getConfig().nextPatchId++;
953 patches.push_back(*_aidl_return);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000954 } else {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000955 oldPatch = *existing;
Mikhail Naganovdc417732023-09-29 15:49:35 -0700956 *existing = *_aidl_return;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000957 }
Mikhail Naganov75b59df2023-06-23 13:39:40 -0700958 patchesBackup = mPatches;
959 registerPatch(*_aidl_return);
960 if (auto status = updateStreamsConnectedState(oldPatch, *_aidl_return); !status.isOk()) {
961 mPatches = std::move(*patchesBackup);
962 if (existing == patches.end()) {
963 patches.pop_back();
964 } else {
965 *existing = oldPatch;
966 }
967 return status;
968 }
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000969
970 LOG(DEBUG) << __func__ << ": " << (oldPatch.id == 0 ? "created" : "updated") << " patch "
971 << _aidl_return->toString();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000972 return ndk::ScopedAStatus::ok();
973}
974
975ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
976 AudioPortConfig* out_suggested, bool* _aidl_return) {
977 LOG(DEBUG) << __func__ << ": requested " << in_requested.toString();
978 auto& configs = getConfig().portConfigs;
979 auto existing = configs.end();
980 if (in_requested.id != 0) {
981 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
982 existing == configs.end()) {
983 LOG(ERROR) << __func__ << ": existing port config id " << in_requested.id
984 << " not found";
985 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
986 }
987 }
988
989 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
990 if (portId == 0) {
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700991 LOG(ERROR) << __func__ << ": requested port config does not specify portId";
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000992 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
993 }
994 auto& ports = getConfig().ports;
995 auto portIt = findById<AudioPort>(ports, portId);
996 if (portIt == ports.end()) {
Mikhail Naganov84bcc042023-10-05 17:36:57 -0700997 LOG(ERROR) << __func__ << ": requested port config points to non-existent portId "
998 << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000999 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1000 }
1001 if (existing != configs.end()) {
1002 *out_suggested = *existing;
1003 } else {
1004 AudioPortConfig newConfig;
1005 if (generateDefaultPortConfig(*portIt, &newConfig)) {
1006 *out_suggested = newConfig;
1007 } else {
1008 LOG(ERROR) << __func__ << ": unable generate a default config for port " << portId;
1009 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1010 }
1011 }
1012 // From this moment, 'out_suggested' is either an existing port config,
1013 // or a new generated config. Now attempt to update it according to the specified
1014 // fields of 'in_requested'.
1015
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001016 // Device ports with only dynamic profiles are used for devices that are connected via ADSP,
1017 // which takes care of their actual configuration automatically.
1018 const bool allowDynamicConfig = portIt->ext.getTag() == AudioPortExt::device &&
1019 hasDynamicProfilesOnly(portIt->profiles);
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001020 bool requestedIsValid = true, requestedIsFullySpecified = true;
1021
1022 AudioIoFlags portFlags = portIt->flags;
1023 if (in_requested.flags.has_value()) {
1024 if (in_requested.flags.value() != portFlags) {
1025 LOG(WARNING) << __func__ << ": requested flags "
1026 << in_requested.flags.value().toString() << " do not match port's "
1027 << portId << " flags " << portFlags.toString();
1028 requestedIsValid = false;
1029 }
1030 } else {
1031 requestedIsFullySpecified = false;
1032 }
1033
1034 AudioProfile portProfile;
1035 if (in_requested.format.has_value()) {
1036 const auto& format = in_requested.format.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001037 if ((format == AudioFormatDescription{} && allowDynamicConfig) ||
1038 findAudioProfile(*portIt, format, &portProfile)) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001039 out_suggested->format = format;
1040 } else {
1041 LOG(WARNING) << __func__ << ": requested format " << format.toString()
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001042 << " is not found in the profiles of port " << portId;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001043 requestedIsValid = false;
1044 }
1045 } else {
1046 requestedIsFullySpecified = false;
1047 }
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001048 if (!(out_suggested->format.value() == AudioFormatDescription{} && allowDynamicConfig) &&
1049 !findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001050 LOG(ERROR) << __func__ << ": port " << portId << " does not support format "
1051 << out_suggested->format.value().toString() << " anymore";
1052 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1053 }
1054
1055 if (in_requested.channelMask.has_value()) {
1056 const auto& channelMask = in_requested.channelMask.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001057 if ((channelMask == AudioChannelLayout{} && allowDynamicConfig) ||
1058 find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
1059 portProfile.channelMasks.end()) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001060 out_suggested->channelMask = channelMask;
1061 } else {
1062 LOG(WARNING) << __func__ << ": requested channel mask " << channelMask.toString()
1063 << " is not supported for the format " << portProfile.format.toString()
1064 << " by the port " << portId;
1065 requestedIsValid = false;
1066 }
1067 } else {
1068 requestedIsFullySpecified = false;
1069 }
1070
1071 if (in_requested.sampleRate.has_value()) {
1072 const auto& sampleRate = in_requested.sampleRate.value();
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001073 if ((sampleRate.value == 0 && allowDynamicConfig) ||
1074 find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001075 sampleRate.value) != portProfile.sampleRates.end()) {
1076 out_suggested->sampleRate = sampleRate;
1077 } else {
1078 LOG(WARNING) << __func__ << ": requested sample rate " << sampleRate.value
1079 << " is not supported for the format " << portProfile.format.toString()
1080 << " by the port " << portId;
1081 requestedIsValid = false;
1082 }
1083 } else {
1084 requestedIsFullySpecified = false;
1085 }
1086
1087 if (in_requested.gain.has_value()) {
1088 // Let's pretend that gain can always be applied.
1089 out_suggested->gain = in_requested.gain.value();
1090 }
1091
Mikhail Naganov248e9502023-02-21 16:32:40 -08001092 if (in_requested.ext.getTag() != AudioPortExt::Tag::unspecified) {
1093 if (in_requested.ext.getTag() == out_suggested->ext.getTag()) {
1094 if (out_suggested->ext.getTag() == AudioPortExt::Tag::mix) {
1095 // 'AudioMixPortExt.handle' is set by the client, copy from in_requested
1096 out_suggested->ext.get<AudioPortExt::Tag::mix>().handle =
1097 in_requested.ext.get<AudioPortExt::Tag::mix>().handle;
1098 }
1099 } else {
1100 LOG(WARNING) << __func__ << ": requested ext tag "
1101 << toString(in_requested.ext.getTag()) << " do not match port's tag "
1102 << toString(out_suggested->ext.getTag());
1103 requestedIsValid = false;
1104 }
1105 }
1106
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001107 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
1108 out_suggested->id = getConfig().nextPortId++;
1109 configs.push_back(*out_suggested);
1110 *_aidl_return = true;
1111 LOG(DEBUG) << __func__ << ": created new port config " << out_suggested->toString();
1112 } else if (existing != configs.end() && requestedIsValid) {
1113 *existing = *out_suggested;
1114 *_aidl_return = true;
1115 LOG(DEBUG) << __func__ << ": updated port config " << out_suggested->toString();
1116 } else {
1117 LOG(DEBUG) << __func__ << ": not applied; existing config ? " << (existing != configs.end())
1118 << "; requested is valid? " << requestedIsValid << ", fully specified? "
1119 << requestedIsFullySpecified;
1120 *_aidl_return = false;
1121 }
1122 return ndk::ScopedAStatus::ok();
1123}
1124
1125ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
1126 auto& patches = getConfig().patches;
1127 auto patchIt = findById<AudioPatch>(patches, in_patchId);
1128 if (patchIt != patches.end()) {
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001129 auto patchesBackup = mPatches;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001130 cleanUpPatch(patchIt->id);
Mikhail Naganov75b59df2023-06-23 13:39:40 -07001131 if (auto status = updateStreamsConnectedState(*patchIt, AudioPatch{}); !status.isOk()) {
1132 mPatches = std::move(patchesBackup);
1133 return status;
1134 }
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001135 patches.erase(patchIt);
1136 LOG(DEBUG) << __func__ << ": erased patch " << in_patchId;
1137 return ndk::ScopedAStatus::ok();
1138 }
1139 LOG(ERROR) << __func__ << ": patch id " << in_patchId << " not found";
1140 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1141}
1142
1143ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
1144 auto& configs = getConfig().portConfigs;
1145 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
1146 if (configIt != configs.end()) {
1147 if (mStreams.count(in_portConfigId) != 0) {
1148 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
1149 << " has a stream opened on it";
1150 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1151 }
1152 auto patchIt = mPatches.find(in_portConfigId);
1153 if (patchIt != mPatches.end()) {
1154 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId
1155 << " is used by the patch with id " << patchIt->second;
1156 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1157 }
1158 auto& initials = getConfig().initialConfigs;
1159 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
1160 if (initialIt == initials.end()) {
1161 configs.erase(configIt);
1162 LOG(DEBUG) << __func__ << ": erased port config " << in_portConfigId;
1163 } else if (*configIt != *initialIt) {
1164 *configIt = *initialIt;
1165 LOG(DEBUG) << __func__ << ": reset port config " << in_portConfigId;
1166 }
1167 return ndk::ScopedAStatus::ok();
1168 }
1169 LOG(ERROR) << __func__ << ": port config id " << in_portConfigId << " not found";
1170 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1171}
1172
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001173ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) {
1174 *_aidl_return = mMasterMute;
1175 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1176 return ndk::ScopedAStatus::ok();
1177}
1178
1179ndk::ScopedAStatus Module::setMasterMute(bool in_mute) {
1180 LOG(DEBUG) << __func__ << ": " << in_mute;
jiabin783c48b2023-02-28 18:28:06 +00001181 auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1182 : onMasterMuteChanged(in_mute);
1183 if (result.isOk()) {
1184 mMasterMute = in_mute;
1185 } else {
1186 LOG(ERROR) << __func__ << ": failed calling onMasterMuteChanged(" << in_mute
1187 << "), error=" << result;
1188 // Reset master mute if it failed.
1189 onMasterMuteChanged(mMasterMute);
1190 }
1191 return std::move(result);
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001192}
1193
1194ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) {
1195 *_aidl_return = mMasterVolume;
1196 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1197 return ndk::ScopedAStatus::ok();
1198}
1199
1200ndk::ScopedAStatus Module::setMasterVolume(float in_volume) {
1201 LOG(DEBUG) << __func__ << ": " << in_volume;
1202 if (in_volume >= 0.0f && in_volume <= 1.0f) {
jiabin783c48b2023-02-28 18:28:06 +00001203 auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1204 : onMasterVolumeChanged(in_volume);
1205 if (result.isOk()) {
1206 mMasterVolume = in_volume;
1207 } else {
1208 // Reset master volume if it failed.
1209 LOG(ERROR) << __func__ << ": failed calling onMasterVolumeChanged(" << in_volume
1210 << "), error=" << result;
1211 onMasterVolumeChanged(mMasterVolume);
1212 }
1213 return std::move(result);
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001214 }
1215 LOG(ERROR) << __func__ << ": invalid master volume value: " << in_volume;
1216 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1217}
1218
1219ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) {
1220 *_aidl_return = mMicMute;
1221 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1222 return ndk::ScopedAStatus::ok();
1223}
1224
1225ndk::ScopedAStatus Module::setMicMute(bool in_mute) {
1226 LOG(DEBUG) << __func__ << ": " << in_mute;
1227 mMicMute = in_mute;
1228 return ndk::ScopedAStatus::ok();
1229}
1230
Mikhail Naganovef6bc742022-10-06 00:14:19 +00001231ndk::ScopedAStatus Module::getMicrophones(std::vector<MicrophoneInfo>* _aidl_return) {
Mikhail Naganov5eea7fb2023-10-13 23:38:25 +00001232 *_aidl_return = getConfig().microphones;
Mikhail Naganovef6bc742022-10-06 00:14:19 +00001233 LOG(DEBUG) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return);
1234 return ndk::ScopedAStatus::ok();
1235}
1236
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001237ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) {
Mikhail Naganov04ae8222023-01-11 15:48:10 -08001238 if (!isValidAudioMode(in_mode)) {
1239 LOG(ERROR) << __func__ << ": invalid mode " << toString(in_mode);
1240 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1241 }
Mikhail Naganov3b125b72022-10-05 02:12:39 +00001242 // No checks for supported audio modes here, it's an informative notification.
1243 LOG(DEBUG) << __func__ << ": " << toString(in_mode);
1244 return ndk::ScopedAStatus::ok();
1245}
1246
1247ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) {
1248 LOG(DEBUG) << __func__ << ": " << toString(in_rotation);
1249 return ndk::ScopedAStatus::ok();
1250}
1251
1252ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) {
1253 LOG(DEBUG) << __func__ << ": " << in_isTurnedOn;
1254 return ndk::ScopedAStatus::ok();
1255}
1256
Vlad Popa83a6d822022-11-07 13:53:57 +01001257ndk::ScopedAStatus Module::getSoundDose(std::shared_ptr<ISoundDose>* _aidl_return) {
Mikhail Naganov7499a002023-02-27 18:51:44 -08001258 if (!mSoundDose) {
Vlad Popa2afbd1e2022-12-28 17:04:58 +01001259 mSoundDose = ndk::SharedRefBase::make<sounddose::SoundDose>();
Vlad Popa943b7e22022-12-08 14:24:12 +01001260 }
Mikhail Naganov780fefb2023-07-21 17:01:38 -07001261 *_aidl_return = mSoundDose.getInstance();
Vlad Popa943b7e22022-12-08 14:24:12 +01001262 LOG(DEBUG) << __func__ << ": returning instance of ISoundDose: " << _aidl_return->get();
Vlad Popa83a6d822022-11-07 13:53:57 +01001263 return ndk::ScopedAStatus::ok();
1264}
1265
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001266ndk::ScopedAStatus Module::generateHwAvSyncId(int32_t* _aidl_return) {
1267 LOG(DEBUG) << __func__;
1268 (void)_aidl_return;
1269 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1270}
1271
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001272const std::string Module::VendorDebug::kForceTransientBurstName = "aosp.forceTransientBurst";
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001273const std::string Module::VendorDebug::kForceSynchronousDrainName = "aosp.forceSynchronousDrain";
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001274
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001275ndk::ScopedAStatus Module::getVendorParameters(const std::vector<std::string>& in_ids,
1276 std::vector<VendorParameter>* _aidl_return) {
1277 LOG(DEBUG) << __func__ << ": id count: " << in_ids.size();
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001278 bool allParametersKnown = true;
1279 for (const auto& id : in_ids) {
1280 if (id == VendorDebug::kForceTransientBurstName) {
1281 VendorParameter forceTransientBurst{.id = id};
1282 forceTransientBurst.ext.setParcelable(Boolean{mVendorDebug.forceTransientBurst});
1283 _aidl_return->push_back(std::move(forceTransientBurst));
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001284 } else if (id == VendorDebug::kForceSynchronousDrainName) {
1285 VendorParameter forceSynchronousDrain{.id = id};
1286 forceSynchronousDrain.ext.setParcelable(Boolean{mVendorDebug.forceSynchronousDrain});
1287 _aidl_return->push_back(std::move(forceSynchronousDrain));
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001288 } else {
1289 allParametersKnown = false;
1290 LOG(ERROR) << __func__ << ": unrecognized parameter \"" << id << "\"";
1291 }
1292 }
1293 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1294 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001295}
1296
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001297namespace {
1298
1299template <typename W>
1300bool extractParameter(const VendorParameter& p, decltype(W::value)* v) {
1301 std::optional<W> value;
1302 binder_status_t result = p.ext.getParcelable(&value);
1303 if (result == STATUS_OK && value.has_value()) {
1304 *v = value.value().value;
1305 return true;
1306 }
1307 LOG(ERROR) << __func__ << ": failed to read the value of the parameter \"" << p.id
1308 << "\": " << result;
1309 return false;
1310}
1311
1312} // namespace
1313
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001314ndk::ScopedAStatus Module::setVendorParameters(const std::vector<VendorParameter>& in_parameters,
1315 bool in_async) {
1316 LOG(DEBUG) << __func__ << ": parameter count " << in_parameters.size()
1317 << ", async: " << in_async;
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001318 bool allParametersKnown = true;
1319 for (const auto& p : in_parameters) {
1320 if (p.id == VendorDebug::kForceTransientBurstName) {
Mikhail Naganov194daaa2023-01-05 22:34:20 +00001321 if (!extractParameter<Boolean>(p, &mVendorDebug.forceTransientBurst)) {
1322 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1323 }
1324 } else if (p.id == VendorDebug::kForceSynchronousDrainName) {
1325 if (!extractParameter<Boolean>(p, &mVendorDebug.forceSynchronousDrain)) {
Mikhail Naganov20047bc2023-01-05 20:16:07 +00001326 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1327 }
1328 } else {
1329 allParametersKnown = false;
1330 LOG(ERROR) << __func__ << ": unrecognized parameter \"" << p.id << "\"";
1331 }
1332 }
1333 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1334 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
Mikhail Naganove9f10fc2022-10-14 23:31:52 +00001335}
1336
Mikhail Naganovfb1acde2022-12-12 18:57:36 +00001337ndk::ScopedAStatus Module::addDeviceEffect(
1338 int32_t in_portConfigId,
1339 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1340 if (in_effect == nullptr) {
1341 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect";
1342 } else {
1343 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder "
1344 << in_effect->asBinder().get();
1345 }
1346 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1347}
1348
1349ndk::ScopedAStatus Module::removeDeviceEffect(
1350 int32_t in_portConfigId,
1351 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1352 if (in_effect == nullptr) {
1353 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect";
1354 } else {
1355 LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder "
1356 << in_effect->asBinder().get();
1357 }
1358 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1359}
1360
jiabin9a8e6862023-01-12 23:06:37 +00001361ndk::ScopedAStatus Module::getMmapPolicyInfos(AudioMMapPolicyType mmapPolicyType,
1362 std::vector<AudioMMapPolicyInfo>* _aidl_return) {
1363 LOG(DEBUG) << __func__ << ": mmap policy type " << toString(mmapPolicyType);
1364 std::set<int32_t> mmapSinks;
1365 std::set<int32_t> mmapSources;
1366 auto& ports = getConfig().ports;
1367 for (const auto& port : ports) {
1368 if (port.flags.getTag() == AudioIoFlags::Tag::input &&
1369 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::input>(),
1370 AudioInputFlags::MMAP_NOIRQ)) {
1371 mmapSinks.insert(port.id);
1372 } else if (port.flags.getTag() == AudioIoFlags::Tag::output &&
1373 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
1374 AudioOutputFlags::MMAP_NOIRQ)) {
1375 mmapSources.insert(port.id);
1376 }
1377 }
Mikhail Naganov85064912023-09-26 17:10:08 -07001378 if (mmapSources.empty() && mmapSinks.empty()) {
1379 AudioMMapPolicyInfo never;
1380 never.mmapPolicy = AudioMMapPolicy::NEVER;
1381 _aidl_return->push_back(never);
1382 return ndk::ScopedAStatus::ok();
1383 }
jiabin9a8e6862023-01-12 23:06:37 +00001384 for (const auto& route : getConfig().routes) {
1385 if (mmapSinks.count(route.sinkPortId) != 0) {
1386 // The sink is a mix port, add the sources if they are device ports.
1387 for (int sourcePortId : route.sourcePortIds) {
1388 auto sourcePortIt = findById<AudioPort>(ports, sourcePortId);
1389 if (sourcePortIt == ports.end()) {
1390 // This must not happen
1391 LOG(ERROR) << __func__ << ": port id " << sourcePortId << " cannot be found";
1392 continue;
1393 }
1394 if (sourcePortIt->ext.getTag() != AudioPortExt::Tag::device) {
1395 // The source is not a device port, skip
1396 continue;
1397 }
1398 AudioMMapPolicyInfo policyInfo;
1399 policyInfo.device = sourcePortIt->ext.get<AudioPortExt::Tag::device>().device;
1400 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1401 // default implementation.
1402 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1403 _aidl_return->push_back(policyInfo);
1404 }
1405 } else {
1406 auto sinkPortIt = findById<AudioPort>(ports, route.sinkPortId);
1407 if (sinkPortIt == ports.end()) {
1408 // This must not happen
1409 LOG(ERROR) << __func__ << ": port id " << route.sinkPortId << " cannot be found";
1410 continue;
1411 }
1412 if (sinkPortIt->ext.getTag() != AudioPortExt::Tag::device) {
1413 // The sink is not a device port, skip
1414 continue;
1415 }
1416 if (count_any(mmapSources, route.sourcePortIds)) {
1417 AudioMMapPolicyInfo policyInfo;
1418 policyInfo.device = sinkPortIt->ext.get<AudioPortExt::Tag::device>().device;
1419 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1420 // default implementation.
1421 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1422 _aidl_return->push_back(policyInfo);
1423 }
1424 }
1425 }
1426 return ndk::ScopedAStatus::ok();
1427}
1428
Eric Laurente2432ea2023-01-12 17:47:31 +01001429ndk::ScopedAStatus Module::supportsVariableLatency(bool* _aidl_return) {
1430 LOG(DEBUG) << __func__;
1431 *_aidl_return = false;
1432 return ndk::ScopedAStatus::ok();
1433}
1434
jiabinb76981e2023-01-18 00:58:30 +00001435ndk::ScopedAStatus Module::getAAudioMixerBurstCount(int32_t* _aidl_return) {
1436 if (!isMmapSupported()) {
1437 LOG(DEBUG) << __func__ << ": mmap is not supported ";
1438 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1439 }
1440 *_aidl_return = DEFAULT_AAUDIO_MIXER_BURST_COUNT;
1441 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1442 return ndk::ScopedAStatus::ok();
1443}
1444
1445ndk::ScopedAStatus Module::getAAudioHardwareBurstMinUsec(int32_t* _aidl_return) {
1446 if (!isMmapSupported()) {
1447 LOG(DEBUG) << __func__ << ": mmap is not supported ";
1448 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1449 }
1450 *_aidl_return = DEFAULT_AAUDIO_HARDWARE_BURST_MIN_DURATION_US;
1451 LOG(DEBUG) << __func__ << ": returning " << *_aidl_return;
1452 return ndk::ScopedAStatus::ok();
1453}
1454
1455bool Module::isMmapSupported() {
1456 if (mIsMmapSupported.has_value()) {
1457 return mIsMmapSupported.value();
1458 }
1459 std::vector<AudioMMapPolicyInfo> mmapPolicyInfos;
1460 if (!getMmapPolicyInfos(AudioMMapPolicyType::DEFAULT, &mmapPolicyInfos).isOk()) {
1461 mIsMmapSupported = false;
1462 } else {
1463 mIsMmapSupported =
1464 std::find_if(mmapPolicyInfos.begin(), mmapPolicyInfos.end(), [](const auto& info) {
1465 return info.mmapPolicy == AudioMMapPolicy::AUTO ||
1466 info.mmapPolicy == AudioMMapPolicy::ALWAYS;
1467 }) != mmapPolicyInfos.end();
1468 }
1469 return mIsMmapSupported.value();
1470}
1471
Mikhail Naganov84bcc042023-10-05 17:36:57 -07001472ndk::ScopedAStatus Module::populateConnectedDevicePort(AudioPort* audioPort) {
1473 if (audioPort->ext.getTag() != AudioPortExt::device) {
1474 LOG(ERROR) << __func__ << ": not a device port: " << audioPort->toString();
1475 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1476 }
1477 const auto& devicePort = audioPort->ext.get<AudioPortExt::device>();
1478 if (!devicePort.device.type.connection.empty()) {
1479 LOG(ERROR) << __func__
1480 << ": module implementation must override 'populateConnectedDevicePort' "
1481 << "to handle connection of external devices.";
1482 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1483 }
jiabin116d8392023-03-01 22:52:57 +00001484 LOG(VERBOSE) << __func__ << ": do nothing and return ok";
jiabin253bd322023-01-25 23:57:31 +00001485 return ndk::ScopedAStatus::ok();
1486}
1487
1488ndk::ScopedAStatus Module::checkAudioPatchEndpointsMatch(
1489 const std::vector<AudioPortConfig*>& sources __unused,
1490 const std::vector<AudioPortConfig*>& sinks __unused) {
jiabin116d8392023-03-01 22:52:57 +00001491 LOG(VERBOSE) << __func__ << ": do nothing and return ok";
jiabin253bd322023-01-25 23:57:31 +00001492 return ndk::ScopedAStatus::ok();
1493}
1494
jiabin783c48b2023-02-28 18:28:06 +00001495void Module::onExternalDeviceConnectionChanged(
1496 const ::aidl::android::media::audio::common::AudioPort& audioPort __unused,
1497 bool connected __unused) {
1498 LOG(DEBUG) << __func__ << ": do nothing and return";
1499}
1500
1501ndk::ScopedAStatus Module::onMasterMuteChanged(bool mute __unused) {
1502 LOG(VERBOSE) << __func__ << ": do nothing and return ok";
1503 return ndk::ScopedAStatus::ok();
1504}
1505
1506ndk::ScopedAStatus Module::onMasterVolumeChanged(float volume __unused) {
1507 LOG(VERBOSE) << __func__ << ": do nothing and return ok";
1508 return ndk::ScopedAStatus::ok();
1509}
1510
Ram Mohan18f0d512023-07-01 00:47:09 +05301511Module::BtProfileHandles Module::getBtProfileManagerHandles() {
1512 return std::make_tuple(std::weak_ptr<IBluetooth>(), std::weak_ptr<IBluetoothA2dp>(),
1513 std::weak_ptr<IBluetoothLe>());
1514}
1515
1516ndk::ScopedAStatus Module::bluetoothParametersUpdated() {
1517 return mStreams.bluetoothParametersUpdated();
1518}
1519
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001520} // namespace aidl::android::hardware::audio::core