1 /*
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"
21 #include <aidl/android/media/audio/common/AudioInputFlags.h>
22 #include <aidl/android/media/audio/common/AudioOutputFlags.h>
23 #include <android-base/logging.h>
24 #include <android/binder_ibinder_platform.h>
25 #include <error/expected_utils.h>
26
27 #include "core-impl/Configuration.h"
28 #include "core-impl/Module.h"
29 #include "core-impl/ModuleBluetooth.h"
30 #include "core-impl/ModulePrimary.h"
31 #include "core-impl/ModuleRemoteSubmix.h"
32 #include "core-impl/ModuleStub.h"
33 #include "core-impl/ModuleUsb.h"
34 #include "core-impl/SoundDose.h"
35 #include "core-impl/utils.h"
36
37 using aidl::android::hardware::audio::common::frameCountFromDurationMs;
38 using aidl::android::hardware::audio::common::getFrameSizeInBytes;
39 using aidl::android::hardware::audio::common::hasMmapFlag;
40 using aidl::android::hardware::audio::common::isBitPositionFlagSet;
41 using aidl::android::hardware::audio::common::isValidAudioMode;
42 using aidl::android::hardware::audio::common::SinkMetadata;
43 using aidl::android::hardware::audio::common::SourceMetadata;
44 using aidl::android::hardware::audio::core::sounddose::ISoundDose;
45 using aidl::android::media::audio::common::AudioChannelLayout;
46 using aidl::android::media::audio::common::AudioDevice;
47 using aidl::android::media::audio::common::AudioDeviceType;
48 using aidl::android::media::audio::common::AudioFormatDescription;
49 using aidl::android::media::audio::common::AudioFormatType;
50 using aidl::android::media::audio::common::AudioGainConfig;
51 using aidl::android::media::audio::common::AudioInputFlags;
52 using aidl::android::media::audio::common::AudioIoFlags;
53 using aidl::android::media::audio::common::AudioMMapPolicy;
54 using aidl::android::media::audio::common::AudioMMapPolicyInfo;
55 using aidl::android::media::audio::common::AudioMMapPolicyType;
56 using aidl::android::media::audio::common::AudioMode;
57 using aidl::android::media::audio::common::AudioOffloadInfo;
58 using aidl::android::media::audio::common::AudioOutputFlags;
59 using aidl::android::media::audio::common::AudioPort;
60 using aidl::android::media::audio::common::AudioPortConfig;
61 using aidl::android::media::audio::common::AudioPortExt;
62 using aidl::android::media::audio::common::AudioProfile;
63 using aidl::android::media::audio::common::Boolean;
64 using aidl::android::media::audio::common::Int;
65 using aidl::android::media::audio::common::MicrophoneInfo;
66 using aidl::android::media::audio::common::PcmType;
67
68 namespace aidl::android::hardware::audio::core {
69
70 namespace {
71
hasDynamicChannelMasks(const std::vector<AudioChannelLayout> & channelMasks)72 inline bool hasDynamicChannelMasks(const std::vector<AudioChannelLayout>& channelMasks) {
73 return channelMasks.empty() ||
74 std::all_of(channelMasks.begin(), channelMasks.end(),
75 [](const auto& channelMask) { return channelMask == AudioChannelLayout{}; });
76 }
77
hasDynamicFormat(const AudioFormatDescription & format)78 inline bool hasDynamicFormat(const AudioFormatDescription& format) {
79 return format == AudioFormatDescription{};
80 }
81
hasDynamicSampleRates(const std::vector<int32_t> & sampleRates)82 inline bool hasDynamicSampleRates(const std::vector<int32_t>& sampleRates) {
83 return sampleRates.empty() ||
84 std::all_of(sampleRates.begin(), sampleRates.end(),
85 [](const auto& sampleRate) { return sampleRate == 0; });
86 }
87
isDynamicProfile(const AudioProfile & profile)88 inline bool isDynamicProfile(const AudioProfile& profile) {
89 return hasDynamicFormat(profile.format) || hasDynamicChannelMasks(profile.channelMasks) ||
90 hasDynamicSampleRates(profile.sampleRates);
91 }
92
hasDynamicProfilesOnly(const std::vector<AudioProfile> & profiles)93 bool hasDynamicProfilesOnly(const std::vector<AudioProfile>& profiles) {
94 if (profiles.empty()) return true;
95 return std::all_of(profiles.begin(), profiles.end(), isDynamicProfile);
96 }
97
findAudioProfile(const AudioPort & port,const AudioFormatDescription & format,AudioProfile * profile)98 bool findAudioProfile(const AudioPort& port, const AudioFormatDescription& format,
99 AudioProfile* profile) {
100 if (auto profilesIt =
101 find_if(port.profiles.begin(), port.profiles.end(),
102 [&format](const auto& profile) { return profile.format == format; });
103 profilesIt != port.profiles.end()) {
104 *profile = *profilesIt;
105 return true;
106 }
107 return false;
108 }
109
110 } // namespace
111
112 // static
createInstance(Type type,std::unique_ptr<Configuration> && config)113 std::shared_ptr<Module> Module::createInstance(Type type, std::unique_ptr<Configuration>&& config) {
114 switch (type) {
115 case Type::DEFAULT:
116 return ndk::SharedRefBase::make<ModulePrimary>(std::move(config));
117 case Type::R_SUBMIX:
118 return ndk::SharedRefBase::make<ModuleRemoteSubmix>(std::move(config));
119 case Type::STUB:
120 return ndk::SharedRefBase::make<ModuleStub>(std::move(config));
121 case Type::USB:
122 return ndk::SharedRefBase::make<ModuleUsb>(std::move(config));
123 case Type::BLUETOOTH:
124 return ndk::SharedRefBase::make<ModuleBluetooth>(std::move(config));
125 }
126 }
127
128 // static
typeFromString(const std::string & type)129 std::optional<Module::Type> Module::typeFromString(const std::string& type) {
130 if (type == "default")
131 return Module::Type::DEFAULT;
132 else if (type == "r_submix")
133 return Module::Type::R_SUBMIX;
134 else if (type == "stub")
135 return Module::Type::STUB;
136 else if (type == "usb")
137 return Module::Type::USB;
138 else if (type == "bluetooth")
139 return Module::Type::BLUETOOTH;
140 return {};
141 }
142
operator <<(std::ostream & os,Module::Type t)143 std::ostream& operator<<(std::ostream& os, Module::Type t) {
144 switch (t) {
145 case Module::Type::DEFAULT:
146 os << "default";
147 break;
148 case Module::Type::R_SUBMIX:
149 os << "r_submix";
150 break;
151 case Module::Type::STUB:
152 os << "stub";
153 break;
154 case Module::Type::USB:
155 os << "usb";
156 break;
157 case Module::Type::BLUETOOTH:
158 os << "bluetooth";
159 break;
160 }
161 return os;
162 }
163
Module(Type type,std::unique_ptr<Configuration> && config)164 Module::Module(Type type, std::unique_ptr<Configuration>&& config)
165 : mType(type), mConfig(std::move(config)) {
166 populateConnectedProfiles();
167 }
168
cleanUpPatch(int32_t patchId)169 void Module::cleanUpPatch(int32_t patchId) {
170 erase_all_values(mPatches, std::set<int32_t>{patchId});
171 }
172
createStreamContext(int32_t in_portConfigId,int64_t in_bufferSizeFrames,std::shared_ptr<IStreamCallback> asyncCallback,std::shared_ptr<IStreamOutEventCallback> outEventCallback,StreamContext * out_context)173 ndk::ScopedAStatus Module::createStreamContext(
174 int32_t in_portConfigId, int64_t in_bufferSizeFrames,
175 std::shared_ptr<IStreamCallback> asyncCallback,
176 std::shared_ptr<IStreamOutEventCallback> outEventCallback, StreamContext* out_context) {
177 if (in_bufferSizeFrames <= 0) {
178 LOG(ERROR) << __func__ << ": " << mType << ": non-positive buffer size "
179 << in_bufferSizeFrames;
180 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
181 }
182 auto& configs = getConfig().portConfigs;
183 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
184 const int32_t nominalLatencyMs = getNominalLatencyMs(*portConfigIt);
185 // Since this is a private method, it is assumed that
186 // validity of the portConfigId has already been checked.
187 const int32_t minimumStreamBufferSizeFrames =
188 calculateBufferSizeFrames(nominalLatencyMs, portConfigIt->sampleRate.value().value);
189 if (in_bufferSizeFrames < minimumStreamBufferSizeFrames) {
190 LOG(ERROR) << __func__ << ": " << mType << ": insufficient buffer size "
191 << in_bufferSizeFrames << ", must be at least " << minimumStreamBufferSizeFrames;
192 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
193 }
194 const size_t frameSize =
195 getFrameSizeInBytes(portConfigIt->format.value(), portConfigIt->channelMask.value());
196 if (frameSize == 0) {
197 LOG(ERROR) << __func__ << ": " << mType
198 << ": could not calculate frame size for port config "
199 << portConfigIt->toString();
200 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
201 }
202 LOG(DEBUG) << __func__ << ": " << mType << ": frame size " << frameSize << " bytes";
203 if (frameSize > static_cast<size_t>(kMaximumStreamBufferSizeBytes / in_bufferSizeFrames)) {
204 LOG(ERROR) << __func__ << ": " << mType << ": buffer size " << in_bufferSizeFrames
205 << " frames is too large, maximum size is "
206 << kMaximumStreamBufferSizeBytes / frameSize;
207 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
208 }
209 const auto& flags = portConfigIt->flags.value();
210 StreamContext::DebugParameters params{
211 mDebug.streamTransientStateDelayMs, mVendorDebug.forceTransientBurst,
212 mVendorDebug.forceSynchronousDrain, mVendorDebug.forceDrainToDraining};
213 std::unique_ptr<StreamContext::DataMQ> dataMQ = nullptr;
214 std::shared_ptr<IStreamCallback> streamAsyncCallback = nullptr;
215 std::shared_ptr<ISoundDose> soundDose;
216 if (!getSoundDose(&soundDose).isOk()) {
217 LOG(ERROR) << __func__ << ": could not create sound dose instance";
218 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
219 }
220 if (!hasMmapFlag(flags)) {
221 dataMQ = std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames);
222 streamAsyncCallback = asyncCallback;
223 }
224 StreamContext temp(
225 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
226 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
227 portConfigIt->format.value(), portConfigIt->channelMask.value(),
228 portConfigIt->sampleRate.value().value, flags, nominalLatencyMs,
229 portConfigIt->ext.get<AudioPortExt::mix>().handle, std::move(dataMQ),
230 streamAsyncCallback, outEventCallback, mSoundDose.getInstance(), params);
231 if (temp.isValid()) {
232 *out_context = std::move(temp);
233 } else {
234 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
235 }
236 return ndk::ScopedAStatus::ok();
237 }
238
getDevicesFromDevicePortConfigIds(const std::set<int32_t> & devicePortConfigIds)239 std::vector<AudioDevice> Module::getDevicesFromDevicePortConfigIds(
240 const std::set<int32_t>& devicePortConfigIds) {
241 std::vector<AudioDevice> result;
242 auto& configs = getConfig().portConfigs;
243 for (const auto& id : devicePortConfigIds) {
244 auto it = findById<AudioPortConfig>(configs, id);
245 if (it != configs.end() && it->ext.getTag() == AudioPortExt::Tag::device) {
246 result.push_back(it->ext.template get<AudioPortExt::Tag::device>().device);
247 } else {
248 LOG(FATAL) << __func__ << ": " << mType
249 << ": failed to find device for id" << id;
250 }
251 }
252 return result;
253 }
254
findConnectedDevices(int32_t portConfigId)255 std::vector<AudioDevice> Module::findConnectedDevices(int32_t portConfigId) {
256 return getDevicesFromDevicePortConfigIds(findConnectedPortConfigIds(portConfigId));
257 }
258
findConnectedPortConfigIds(int32_t portConfigId)259 std::set<int32_t> Module::findConnectedPortConfigIds(int32_t portConfigId) {
260 std::set<int32_t> result;
261 auto patchIdsRange = mPatches.equal_range(portConfigId);
262 auto& patches = getConfig().patches;
263 for (auto it = patchIdsRange.first; it != patchIdsRange.second; ++it) {
264 auto patchIt = findById<AudioPatch>(patches, it->second);
265 if (patchIt == patches.end()) {
266 LOG(FATAL) << __func__ << ": " << mType << ": patch with id " << it->second
267 << " taken from mPatches "
268 << "not found in the configuration";
269 }
270 if (std::find(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end(),
271 portConfigId) != patchIt->sourcePortConfigIds.end()) {
272 result.insert(patchIt->sinkPortConfigIds.begin(), patchIt->sinkPortConfigIds.end());
273 } else {
274 result.insert(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end());
275 }
276 }
277 return result;
278 }
279
findPortIdForNewStream(int32_t in_portConfigId,AudioPort ** port)280 ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) {
281 auto& configs = getConfig().portConfigs;
282 auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
283 if (portConfigIt == configs.end()) {
284 LOG(ERROR) << __func__ << ": " << mType << ": existing port config id " << in_portConfigId
285 << " not found";
286 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
287 }
288 const int32_t portId = portConfigIt->portId;
289 // In our implementation, configs of mix ports always have unique IDs.
290 CHECK(portId != in_portConfigId);
291 auto& ports = getConfig().ports;
292 auto portIt = findById<AudioPort>(ports, portId);
293 if (portIt == ports.end()) {
294 LOG(ERROR) << __func__ << ": " << mType << ": port id " << portId
295 << " used by port config id " << in_portConfigId << " not found";
296 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
297 }
298 if (mStreams.count(in_portConfigId) != 0) {
299 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
300 << " already has a stream opened on it";
301 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
302 }
303 if (portIt->ext.getTag() != AudioPortExt::Tag::mix) {
304 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
305 << " does not correspond to a mix port";
306 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
307 }
308 const size_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
309 if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
310 LOG(ERROR) << __func__ << ": " << mType << ": port id " << portId
311 << " has already reached maximum allowed opened stream count: "
312 << maxOpenStreamCount;
313 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
314 }
315 *port = &(*portIt);
316 return ndk::ScopedAStatus::ok();
317 }
318
generateDefaultPortConfig(const AudioPort & port,AudioPortConfig * config)319 bool Module::generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) {
320 const bool allowDynamicConfig = port.ext.getTag() == AudioPortExt::device;
321 for (const auto& profile : port.profiles) {
322 if (isDynamicProfile(profile)) continue;
323 config->format = profile.format;
324 config->channelMask = *profile.channelMasks.begin();
325 config->sampleRate = Int{.value = *profile.sampleRates.begin()};
326 config->flags = port.flags;
327 config->ext = port.ext;
328 return true;
329 }
330 if (allowDynamicConfig) {
331 config->format = AudioFormatDescription{};
332 config->channelMask = AudioChannelLayout{};
333 config->sampleRate = Int{.value = 0};
334 config->flags = port.flags;
335 config->ext = port.ext;
336 return true;
337 }
338 LOG(ERROR) << __func__ << ": " << mType << ": port " << port.id << " only has dynamic profiles";
339 return false;
340 }
341
populateConnectedProfiles()342 void Module::populateConnectedProfiles() {
343 Configuration& config = getConfig();
344 for (const AudioPort& port : config.ports) {
345 if (port.ext.getTag() == AudioPortExt::device) {
346 if (auto devicePort = port.ext.get<AudioPortExt::device>();
347 !devicePort.device.type.connection.empty() && port.profiles.empty()) {
348 if (auto connIt = config.connectedProfiles.find(port.id);
349 connIt == config.connectedProfiles.end()) {
350 config.connectedProfiles.emplace(
351 port.id, internal::getStandard16And24BitPcmAudioProfiles());
352 }
353 }
354 }
355 }
356 }
357
358 template <typename C>
portIdsFromPortConfigIds(C portConfigIds)359 std::set<int32_t> Module::portIdsFromPortConfigIds(C portConfigIds) {
360 std::set<int32_t> result;
361 auto& portConfigs = getConfig().portConfigs;
362 for (auto it = portConfigIds.begin(); it != portConfigIds.end(); ++it) {
363 auto portConfigIt = findById<AudioPortConfig>(portConfigs, *it);
364 if (portConfigIt != portConfigs.end()) {
365 result.insert(portConfigIt->portId);
366 }
367 }
368 return result;
369 }
370
initializeConfig()371 std::unique_ptr<Module::Configuration> Module::initializeConfig() {
372 return internal::getConfiguration(getType());
373 }
374
getNominalLatencyMs(const AudioPortConfig &)375 int32_t Module::getNominalLatencyMs(const AudioPortConfig&) {
376 // Arbitrary value. Implementations must override this method to provide their actual latency.
377 static constexpr int32_t kLatencyMs = 5;
378 return kLatencyMs;
379 }
380
createMmapBuffer(const::aidl::android::hardware::audio::core::StreamContext & context __unused,::aidl::android::hardware::audio::core::StreamDescriptor * desc __unused)381 ndk::ScopedAStatus Module::createMmapBuffer(
382 const ::aidl::android::hardware::audio::core::StreamContext& context __unused,
383 ::aidl::android::hardware::audio::core::StreamDescriptor* desc __unused) {
384 LOG(ERROR) << __func__ << ": " << mType << ": is not implemented";
385 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
386 }
387
getAudioRoutesForAudioPortImpl(int32_t portId)388 std::vector<AudioRoute*> Module::getAudioRoutesForAudioPortImpl(int32_t portId) {
389 std::vector<AudioRoute*> result;
390 auto& routes = getConfig().routes;
391 for (auto& r : routes) {
392 const auto& srcs = r.sourcePortIds;
393 if (r.sinkPortId == portId || std::find(srcs.begin(), srcs.end(), portId) != srcs.end()) {
394 result.push_back(&r);
395 }
396 }
397 return result;
398 }
399
getConfig()400 Module::Configuration& Module::getConfig() {
401 if (!mConfig) {
402 mConfig = initializeConfig();
403 }
404 return *mConfig;
405 }
406
getRoutableAudioPortIds(int32_t portId,std::vector<AudioRoute * > * routes)407 std::set<int32_t> Module::getRoutableAudioPortIds(int32_t portId,
408 std::vector<AudioRoute*>* routes) {
409 std::vector<AudioRoute*> routesStorage;
410 if (routes == nullptr) {
411 routesStorage = getAudioRoutesForAudioPortImpl(portId);
412 routes = &routesStorage;
413 }
414 std::set<int32_t> result;
415 for (AudioRoute* r : *routes) {
416 if (r->sinkPortId == portId) {
417 result.insert(r->sourcePortIds.begin(), r->sourcePortIds.end());
418 } else {
419 result.insert(r->sinkPortId);
420 }
421 }
422 return result;
423 }
424
registerPatch(const AudioPatch & patch)425 void Module::registerPatch(const AudioPatch& patch) {
426 auto& configs = getConfig().portConfigs;
427 auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
428 for (auto portConfigId : portConfigIds) {
429 auto configIt = findById<AudioPortConfig>(configs, portConfigId);
430 if (configIt != configs.end()) {
431 mPatches.insert(std::pair{portConfigId, patch.id});
432 if (configIt->portId != portConfigId) {
433 mPatches.insert(std::pair{configIt->portId, patch.id});
434 }
435 }
436 };
437 };
438 do_insert(patch.sourcePortConfigIds);
439 do_insert(patch.sinkPortConfigIds);
440 }
441
updateStreamsConnectedState(const AudioPatch & oldPatch,const AudioPatch & newPatch)442 ndk::ScopedAStatus Module::updateStreamsConnectedState(const AudioPatch& oldPatch,
443 const AudioPatch& newPatch) {
444 // Notify streams about the new set of devices they are connected to.
445 auto maybeFailure = ndk::ScopedAStatus::ok();
446 using Connections =
447 std::map<int32_t /*mixPortConfigId*/, std::set<int32_t /*devicePortConfigId*/>>;
448 Connections oldConnections, newConnections;
449 auto fillConnectionsHelper = [&](Connections& connections,
450 const std::vector<int32_t>& mixPortCfgIds,
451 const std::vector<int32_t>& devicePortCfgIds) {
452 for (int32_t mixPortCfgId : mixPortCfgIds) {
453 connections[mixPortCfgId].insert(devicePortCfgIds.begin(), devicePortCfgIds.end());
454 }
455 };
456 auto fillConnections = [&](Connections& connections, const AudioPatch& patch) {
457 if (std::find_if(patch.sourcePortConfigIds.begin(), patch.sourcePortConfigIds.end(),
458 [&](int32_t portConfigId) { return mStreams.count(portConfigId) > 0; }) !=
459 patch.sourcePortConfigIds.end()) {
460 // Sources are mix ports.
461 fillConnectionsHelper(connections, patch.sourcePortConfigIds, patch.sinkPortConfigIds);
462 } else if (std::find_if(patch.sinkPortConfigIds.begin(), patch.sinkPortConfigIds.end(),
463 [&](int32_t portConfigId) {
464 return mStreams.count(portConfigId) > 0;
465 }) != patch.sinkPortConfigIds.end()) {
466 // Sources are device ports.
467 fillConnectionsHelper(connections, patch.sinkPortConfigIds, patch.sourcePortConfigIds);
468 } // Otherwise, there are no streams to notify.
469 };
470 auto restoreOldConnections = [&](const std::set<int32_t>& mixPortIds,
471 const bool continueWithEmptyDevices) {
472 for (const auto mixPort : mixPortIds) {
473 if (auto it = oldConnections.find(mixPort);
474 continueWithEmptyDevices || it != oldConnections.end()) {
475 const std::vector<AudioDevice> d =
476 it != oldConnections.end() ? getDevicesFromDevicePortConfigIds(it->second)
477 : std::vector<AudioDevice>();
478 if (auto status = mStreams.setStreamConnectedDevices(mixPort, d); status.isOk()) {
479 LOG(WARNING) << ":updateStreamsConnectedState: rollback: mix port config:"
480 << mixPort
481 << (d.empty() ? "; not connected"
482 : std::string("; connected to ") +
483 ::android::internal::ToString(d));
484 } else {
485 // can't do much about rollback failures
486 LOG(ERROR)
487 << ":updateStreamsConnectedState: rollback: failed for mix port config:"
488 << mixPort;
489 }
490 }
491 }
492 };
493 fillConnections(oldConnections, oldPatch);
494 fillConnections(newConnections, newPatch);
495 /**
496 * Illustration of oldConnections and newConnections
497 *
498 * oldConnections {
499 * a : {A,B,C},
500 * b : {D},
501 * d : {H,I,J},
502 * e : {N,O,P},
503 * f : {Q,R},
504 * g : {T,U,V},
505 * }
506 *
507 * newConnections {
508 * a : {A,B,C},
509 * c : {E,F,G},
510 * d : {K,L,M},
511 * e : {N,P},
512 * f : {Q,R,S},
513 * g : {U,V,W},
514 * }
515 *
516 * Expected routings:
517 * 'a': is ignored both in disconnect step and connect step,
518 * due to same devices both in oldConnections and newConnections.
519 * 'b': handled only in disconnect step with empty devices because 'b' is only present
520 * in oldConnections.
521 * 'c': handled only in connect step with {E,F,G} devices because 'c' is only present
522 * in newConnections.
523 * 'd': handled only in connect step with {K,L,M} devices because 'd' is also present
524 * in newConnections and it is ignored in disconnected step.
525 * 'e': handled only in connect step with {N,P} devices because 'e' is also present
526 * in newConnections and it is ignored in disconnect step. please note that there
527 * is no exclusive disconnection for device {O}.
528 * 'f': handled only in connect step with {Q,R,S} devices because 'f' is also present
529 * in newConnections and it is ignored in disconnect step. Even though stream is
530 * already connected with {Q,R} devices and connection happens with {Q,R,S}.
531 * 'g': handled only in connect step with {U,V,W} devices because 'g' is also present
532 * in newConnections and it is ignored in disconnect step. There is no exclusive
533 * disconnection with devices {T,U,V}.
534 *
535 * If, any failure, will lead to restoreOldConnections (rollback).
536 * The aim of the restoreOldConnections is to make connections back to oldConnections.
537 * Failures in restoreOldConnections aren't handled.
538 */
539
540 std::set<int32_t> idsToConnectBackOnFailure;
541 // disconnection step
542 for (const auto& [oldMixPortConfigId, oldDevicePortConfigIds] : oldConnections) {
543 if (auto it = newConnections.find(oldMixPortConfigId); it == newConnections.end()) {
544 idsToConnectBackOnFailure.insert(oldMixPortConfigId);
545 if (auto status = mStreams.setStreamConnectedDevices(oldMixPortConfigId, {});
546 status.isOk()) {
547 LOG(DEBUG) << __func__ << ": The stream on port config id " << oldMixPortConfigId
548 << " has been disconnected";
549 } else {
550 maybeFailure = std::move(status);
551 // proceed to rollback even on one failure
552 break;
553 }
554 }
555 }
556
557 if (!maybeFailure.isOk()) {
558 restoreOldConnections(idsToConnectBackOnFailure, false /*continueWithEmptyDevices*/);
559 LOG(WARNING) << __func__ << ": failed to disconnect from old patch. attempted rollback";
560 return maybeFailure;
561 }
562
563 std::set<int32_t> idsToRollbackOnFailure;
564 // connection step
565 for (const auto& [newMixPortConfigId, newDevicePortConfigIds] : newConnections) {
566 if (auto it = oldConnections.find(newMixPortConfigId);
567 it == oldConnections.end() || it->second != newDevicePortConfigIds) {
568 const auto connectedDevices = getDevicesFromDevicePortConfigIds(newDevicePortConfigIds);
569 idsToRollbackOnFailure.insert(newMixPortConfigId);
570 if (connectedDevices.empty()) {
571 // This is important as workers use the vector size to derive the connection status.
572 LOG(FATAL) << __func__ << ": No connected devices found for port config id "
573 << newMixPortConfigId;
574 }
575 if (auto status =
576 mStreams.setStreamConnectedDevices(newMixPortConfigId, connectedDevices);
577 status.isOk()) {
578 LOG(DEBUG) << __func__ << ": The stream on port config id " << newMixPortConfigId
579 << " has been connected to: "
580 << ::android::internal::ToString(connectedDevices);
581 } else {
582 maybeFailure = std::move(status);
583 // proceed to rollback even on one failure
584 break;
585 }
586 }
587 }
588
589 if (!maybeFailure.isOk()) {
590 restoreOldConnections(idsToConnectBackOnFailure, false /*continueWithEmptyDevices*/);
591 restoreOldConnections(idsToRollbackOnFailure, true /*continueWithEmptyDevices*/);
592 LOG(WARNING) << __func__ << ": failed to connect for new patch. attempted rollback";
593 return maybeFailure;
594 }
595
596 return ndk::ScopedAStatus::ok();
597 }
598
setModuleDebug(const::aidl::android::hardware::audio::core::ModuleDebug & in_debug)599 ndk::ScopedAStatus Module::setModuleDebug(
600 const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
601 LOG(DEBUG) << __func__ << ": " << mType << ": old flags:" << mDebug.toString()
602 << ", new flags: " << in_debug.toString();
603 if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
604 !mConnectedDevicePorts.empty()) {
605 LOG(ERROR) << __func__ << ": " << mType
606 << ": attempting to change device connections simulation while "
607 "having external "
608 << "devices connected";
609 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
610 }
611 if (in_debug.streamTransientStateDelayMs < 0) {
612 LOG(ERROR) << __func__ << ": " << mType << ": streamTransientStateDelayMs is negative: "
613 << in_debug.streamTransientStateDelayMs;
614 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
615 }
616 mDebug = in_debug;
617 return ndk::ScopedAStatus::ok();
618 }
619
getTelephony(std::shared_ptr<ITelephony> * _aidl_return)620 ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
621 *_aidl_return = nullptr;
622 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
623 return ndk::ScopedAStatus::ok();
624 }
625
getBluetooth(std::shared_ptr<IBluetooth> * _aidl_return)626 ndk::ScopedAStatus Module::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
627 *_aidl_return = nullptr;
628 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
629 return ndk::ScopedAStatus::ok();
630 }
631
getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp> * _aidl_return)632 ndk::ScopedAStatus Module::getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp>* _aidl_return) {
633 *_aidl_return = nullptr;
634 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
635 return ndk::ScopedAStatus::ok();
636 }
637
getBluetoothLe(std::shared_ptr<IBluetoothLe> * _aidl_return)638 ndk::ScopedAStatus Module::getBluetoothLe(std::shared_ptr<IBluetoothLe>* _aidl_return) {
639 *_aidl_return = nullptr;
640 LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
641 return ndk::ScopedAStatus::ok();
642 }
643
connectExternalDevice(const AudioPort & in_templateIdAndAdditionalData,AudioPort * _aidl_return)644 ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
645 AudioPort* _aidl_return) {
646 const int32_t templateId = in_templateIdAndAdditionalData.id;
647 auto& ports = getConfig().ports;
648 AudioPort connectedPort;
649 { // Scope the template port so that we don't accidentally modify it.
650 auto templateIt = findById<AudioPort>(ports, templateId);
651 if (templateIt == ports.end()) {
652 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId << " not found";
653 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
654 }
655 if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
656 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
657 << " is not a device port";
658 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
659 }
660 auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
661 if (templateDevicePort.device.type.connection.empty()) {
662 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
663 << " is permanently attached";
664 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
665 }
666 if (mConnectedDevicePorts.find(templateId) != mConnectedDevicePorts.end()) {
667 LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
668 << " is a connected device port";
669 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
670 }
671 // Postpone id allocation until we ensure that there are no client errors.
672 connectedPort = *templateIt;
673 connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
674 const auto& inputDevicePort =
675 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
676 auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
677 connectedDevicePort.device.address = inputDevicePort.device.address;
678 LOG(DEBUG) << __func__ << ": " << mType << ": device port " << connectedPort.id
679 << " device set to " << connectedDevicePort.device.toString();
680 // Check if there is already a connected port with for the same external device.
681
682 for (auto connectedPortPair : mConnectedDevicePorts) {
683 auto connectedPortIt = findById<AudioPort>(ports, connectedPortPair.first);
684 if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
685 connectedDevicePort.device) {
686 LOG(ERROR) << __func__ << ": " << mType << ": device "
687 << connectedDevicePort.device.toString()
688 << " is already connected at the device port id "
689 << connectedPortPair.first;
690 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
691 }
692 }
693 }
694
695 // Two main cases are considered with regard to the profiles of the connected device port:
696 //
697 // 1. If the template device port has dynamic profiles, and at least one routable mix
698 // port also has dynamic profiles, it means that after connecting the device, the
699 // connected device port must have profiles populated with actual capabilities of
700 // the connected device, and dynamic of routable mix ports will be filled
701 // according to these capabilities. An example of this case is connection of an
702 // HDMI or USB device. For USB handled by ADSP, there can be mix ports with static
703 // profiles, and one dedicated mix port for "hi-fi" playback. The latter is left with
704 // dynamic profiles so that they can be populated with actual capabilities of
705 // the connected device.
706 //
707 // 2. If the template device port has dynamic profiles, while all routable mix ports
708 // have static profiles, it means that after connecting the device, the connected
709 // device port can be left with dynamic profiles, and profiles of mix ports are
710 // left untouched. An example of this case is connection of an analog wired
711 // headset, it should be treated in the same way as a speaker.
712 //
713 // Yet another possible case is when both the template device port and all routable
714 // mix ports have static profiles. This is allowed and handled correctly, however, it
715 // is not very practical, since these profiles are likely duplicates of each other.
716
717 std::vector<AudioRoute*> routesToMixPorts = getAudioRoutesForAudioPortImpl(templateId);
718 std::set<int32_t> routableMixPortIds = getRoutableAudioPortIds(templateId, &routesToMixPorts);
719 const int32_t nextPortId = getConfig().nextPortId++;
720 if (!mDebug.simulateDeviceConnections) {
721 // Even if the device port has static profiles, the HAL module might need to update
722 // them, or abort the connection process.
723 RETURN_STATUS_IF_ERROR(populateConnectedDevicePort(&connectedPort, nextPortId));
724 } else if (hasDynamicProfilesOnly(connectedPort.profiles)) {
725 auto& connectedProfiles = getConfig().connectedProfiles;
726 if (auto connectedProfilesIt = connectedProfiles.find(templateId);
727 connectedProfilesIt != connectedProfiles.end()) {
728 connectedPort.profiles = connectedProfilesIt->second;
729 }
730 }
731 if (hasDynamicProfilesOnly(connectedPort.profiles)) {
732 // Possible case 2. Check if all routable mix ports have static profiles.
733 if (auto dynamicMixPortIt = std::find_if(ports.begin(), ports.end(),
734 [&routableMixPortIds](const auto& p) {
735 return routableMixPortIds.count(p.id) > 0 &&
736 hasDynamicProfilesOnly(p.profiles);
737 });
738 dynamicMixPortIt != ports.end()) {
739 LOG(ERROR) << __func__ << ": " << mType
740 << ": connected port only has dynamic profiles after connecting "
741 << "external device " << connectedPort.toString() << ", and there exist "
742 << "a routable mix port with dynamic profiles: "
743 << dynamicMixPortIt->toString();
744 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
745 }
746 }
747
748 connectedPort.id = nextPortId;
749 auto [connectedPortsIt, _] =
750 mConnectedDevicePorts.insert(std::pair(connectedPort.id, std::set<int32_t>()));
751 LOG(DEBUG) << __func__ << ": " << mType << ": template port " << templateId
752 << " external device connected, "
753 << "connected port ID " << connectedPort.id;
754 ports.push_back(connectedPort);
755 onExternalDeviceConnectionChanged(connectedPort, true /*connected*/);
756
757 // For routes where the template port is a source, add the connected port to sources,
758 // otherwise, create a new route by copying from the route for the template port.
759 std::vector<AudioRoute> newRoutes;
760 for (AudioRoute* r : routesToMixPorts) {
761 if (r->sinkPortId == templateId) {
762 newRoutes.push_back(AudioRoute{.sourcePortIds = r->sourcePortIds,
763 .sinkPortId = connectedPort.id,
764 .isExclusive = r->isExclusive});
765 } else {
766 r->sourcePortIds.push_back(connectedPort.id);
767 }
768 }
769 auto& routes = getConfig().routes;
770 routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
771
772 if (!hasDynamicProfilesOnly(connectedPort.profiles) && !routableMixPortIds.empty()) {
773 // Note: this is a simplistic approach assuming that a mix port can only be populated
774 // from a single device port. Implementing support for stuffing dynamic profiles with
775 // a superset of all profiles from all routable dynamic device ports would be more involved.
776 for (auto& port : ports) {
777 if (routableMixPortIds.count(port.id) == 0) continue;
778 if (hasDynamicProfilesOnly(port.profiles)) {
779 port.profiles = connectedPort.profiles;
780 connectedPortsIt->second.insert(port.id);
781 } else {
782 // Check if profiles are not all dynamic because they were populated by
783 // a previous connection. Otherwise, it means that they are actually static.
784 for (const auto& cp : mConnectedDevicePorts) {
785 if (cp.second.count(port.id) > 0) {
786 connectedPortsIt->second.insert(port.id);
787 break;
788 }
789 }
790 }
791 }
792 }
793 *_aidl_return = std::move(connectedPort);
794
795 return ndk::ScopedAStatus::ok();
796 }
797
disconnectExternalDevice(int32_t in_portId)798 ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
799 auto& ports = getConfig().ports;
800 auto portIt = findById<AudioPort>(ports, in_portId);
801 if (portIt == ports.end()) {
802 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
803 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
804 }
805 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
806 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
807 << " is not a device port";
808 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
809 }
810 auto connectedPortsIt = mConnectedDevicePorts.find(in_portId);
811 if (connectedPortsIt == mConnectedDevicePorts.end()) {
812 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
813 << " is not a connected device port";
814 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
815 }
816 auto& configs = getConfig().portConfigs;
817 auto& initials = getConfig().initialConfigs;
818 auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
819 if (config.portId == in_portId) {
820 // Check if the configuration was provided by the client.
821 const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
822 return initialIt == initials.end() || config != *initialIt;
823 }
824 return false;
825 });
826 if (configIt != configs.end()) {
827 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
828 << " has a non-default config with id " << configIt->id;
829 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
830 }
831 onExternalDeviceConnectionChanged(*portIt, false /*connected*/);
832 ports.erase(portIt);
833 LOG(DEBUG) << __func__ << ": " << mType << ": connected device port " << in_portId
834 << " released";
835
836 auto& routes = getConfig().routes;
837 for (auto routesIt = routes.begin(); routesIt != routes.end();) {
838 if (routesIt->sinkPortId == in_portId) {
839 routesIt = routes.erase(routesIt);
840 } else {
841 // Note: the list of sourcePortIds can't become empty because there must
842 // be the id of the template port in the route.
843 erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
844 ++routesIt;
845 }
846 }
847
848 // Clear profiles for mix ports that are not connected to any other ports.
849 std::set<int32_t> mixPortsToClear = std::move(connectedPortsIt->second);
850 mConnectedDevicePorts.erase(connectedPortsIt);
851 for (const auto& connectedPort : mConnectedDevicePorts) {
852 for (int32_t mixPortId : connectedPort.second) {
853 mixPortsToClear.erase(mixPortId);
854 }
855 }
856 for (int32_t mixPortId : mixPortsToClear) {
857 auto mixPortIt = findById<AudioPort>(ports, mixPortId);
858 if (mixPortIt != ports.end()) {
859 mixPortIt->profiles = {};
860 }
861 }
862
863 return ndk::ScopedAStatus::ok();
864 }
865
prepareToDisconnectExternalDevice(int32_t in_portId)866 ndk::ScopedAStatus Module::prepareToDisconnectExternalDevice(int32_t in_portId) {
867 auto& ports = getConfig().ports;
868 auto portIt = findById<AudioPort>(ports, in_portId);
869 if (portIt == ports.end()) {
870 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
871 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
872 }
873 if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
874 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
875 << " is not a device port";
876 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
877 }
878 auto connectedPortsIt = mConnectedDevicePorts.find(in_portId);
879 if (connectedPortsIt == mConnectedDevicePorts.end()) {
880 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
881 << " is not a connected device port";
882 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
883 }
884
885 onPrepareToDisconnectExternalDevice(*portIt);
886
887 return ndk::ScopedAStatus::ok();
888 }
889
getAudioPatches(std::vector<AudioPatch> * _aidl_return)890 ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
891 *_aidl_return = getConfig().patches;
892 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " patches";
893 return ndk::ScopedAStatus::ok();
894 }
895
getAudioPort(int32_t in_portId,AudioPort * _aidl_return)896 ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
897 auto& ports = getConfig().ports;
898 auto portIt = findById<AudioPort>(ports, in_portId);
899 if (portIt != ports.end()) {
900 *_aidl_return = *portIt;
901 LOG(DEBUG) << __func__ << ": " << mType << ": returning port by id " << in_portId;
902 return ndk::ScopedAStatus::ok();
903 }
904 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
905 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
906 }
907
getAudioPortConfigs(std::vector<AudioPortConfig> * _aidl_return)908 ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
909 *_aidl_return = getConfig().portConfigs;
910 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size()
911 << " port configs";
912 return ndk::ScopedAStatus::ok();
913 }
914
getAudioPorts(std::vector<AudioPort> * _aidl_return)915 ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
916 *_aidl_return = getConfig().ports;
917 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " ports";
918 return ndk::ScopedAStatus::ok();
919 }
920
getAudioRoutes(std::vector<AudioRoute> * _aidl_return)921 ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
922 *_aidl_return = getConfig().routes;
923 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " routes";
924 return ndk::ScopedAStatus::ok();
925 }
926
getAudioRoutesForAudioPort(int32_t in_portId,std::vector<AudioRoute> * _aidl_return)927 ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
928 std::vector<AudioRoute>* _aidl_return) {
929 auto& ports = getConfig().ports;
930 if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
931 LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
932 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
933 }
934 std::vector<AudioRoute*> routes = getAudioRoutesForAudioPortImpl(in_portId);
935 std::transform(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
936 [](auto rptr) { return *rptr; });
937 return ndk::ScopedAStatus::ok();
938 }
939
openInputStream(const OpenInputStreamArguments & in_args,OpenInputStreamReturn * _aidl_return)940 ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
941 OpenInputStreamReturn* _aidl_return) {
942 LOG(DEBUG) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
943 << ", buffer size " << in_args.bufferSizeFrames << " frames";
944 AudioPort* port = nullptr;
945 RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
946 if (port->flags.getTag() != AudioIoFlags::Tag::input) {
947 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
948 << " does not correspond to an input mix port";
949 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
950 }
951 StreamContext context;
952 RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
953 nullptr, nullptr, &context));
954 context.fillDescriptor(&_aidl_return->desc);
955 if (hasMmapFlag(context.getFlags())) {
956 RETURN_STATUS_IF_ERROR(createMmapBuffer(context, &_aidl_return->desc));
957 }
958 std::shared_ptr<StreamIn> stream;
959 RETURN_STATUS_IF_ERROR(createInputStream(std::move(context), in_args.sinkMetadata,
960 getMicrophoneInfos(), &stream));
961 StreamWrapper streamWrapper(stream);
962 if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
963 RETURN_STATUS_IF_ERROR(
964 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
965 }
966 auto streamBinder = streamWrapper.getBinder();
967 AIBinder_setMinSchedulerPolicy(streamBinder.get(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
968 AIBinder_setInheritRt(streamBinder.get(), true);
969 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
970 _aidl_return->stream = std::move(stream);
971 return ndk::ScopedAStatus::ok();
972 }
973
openOutputStream(const OpenOutputStreamArguments & in_args,OpenOutputStreamReturn * _aidl_return)974 ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
975 OpenOutputStreamReturn* _aidl_return) {
976 LOG(DEBUG) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
977 << ", has offload info? " << (in_args.offloadInfo.has_value()) << ", buffer size "
978 << in_args.bufferSizeFrames << " frames";
979 AudioPort* port = nullptr;
980 RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
981 if (port->flags.getTag() != AudioIoFlags::Tag::output) {
982 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
983 << " does not correspond to an output mix port";
984 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
985 }
986 const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
987 AudioOutputFlags::COMPRESS_OFFLOAD);
988 if (isOffload && !in_args.offloadInfo.has_value()) {
989 LOG(ERROR) << __func__ << ": " << mType << ": port id " << port->id
990 << " has COMPRESS_OFFLOAD flag set, requires offload info";
991 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
992 }
993 const bool isNonBlocking = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
994 AudioOutputFlags::NON_BLOCKING);
995 if (isNonBlocking && in_args.callback == nullptr) {
996 LOG(ERROR) << __func__ << ": " << mType << ": port id " << port->id
997 << " has NON_BLOCKING flag set, requires async callback";
998 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
999 }
1000 StreamContext context;
1001 RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
1002 isNonBlocking ? in_args.callback : nullptr,
1003 in_args.eventCallback, &context));
1004 context.fillDescriptor(&_aidl_return->desc);
1005 if (hasMmapFlag(context.getFlags())) {
1006 RETURN_STATUS_IF_ERROR(createMmapBuffer(context, &_aidl_return->desc));
1007 }
1008 std::shared_ptr<StreamOut> stream;
1009 RETURN_STATUS_IF_ERROR(createOutputStream(std::move(context), in_args.sourceMetadata,
1010 in_args.offloadInfo, &stream));
1011 StreamWrapper streamWrapper(stream);
1012 if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
1013 RETURN_STATUS_IF_ERROR(
1014 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
1015 }
1016 auto streamBinder = streamWrapper.getBinder();
1017 AIBinder_setMinSchedulerPolicy(streamBinder.get(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
1018 AIBinder_setInheritRt(streamBinder.get(), true);
1019 mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
1020 _aidl_return->stream = std::move(stream);
1021 return ndk::ScopedAStatus::ok();
1022 }
1023
getSupportedPlaybackRateFactors(SupportedPlaybackRateFactors * _aidl_return)1024 ndk::ScopedAStatus Module::getSupportedPlaybackRateFactors(
1025 SupportedPlaybackRateFactors* _aidl_return) {
1026 LOG(DEBUG) << __func__ << ": " << mType;
1027 (void)_aidl_return;
1028 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1029 }
1030
setAudioPatch(const AudioPatch & in_requested,AudioPatch * _aidl_return)1031 ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
1032 LOG(DEBUG) << __func__ << ": " << mType << ": requested patch " << in_requested.toString();
1033 if (in_requested.sourcePortConfigIds.empty()) {
1034 LOG(ERROR) << __func__ << ": " << mType << ": requested patch has empty sources list";
1035 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1036 }
1037 if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
1038 LOG(ERROR) << __func__ << ": " << mType
1039 << ": requested patch has duplicate ids in the sources list";
1040 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1041 }
1042 if (in_requested.sinkPortConfigIds.empty()) {
1043 LOG(ERROR) << __func__ << ": " << mType << ": requested patch has empty sinks list";
1044 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1045 }
1046 if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
1047 LOG(ERROR) << __func__ << ": " << mType
1048 << ": requested patch has duplicate ids in the sinks list";
1049 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1050 }
1051
1052 auto& configs = getConfig().portConfigs;
1053 std::vector<int32_t> missingIds;
1054 auto sources =
1055 selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
1056 if (!missingIds.empty()) {
1057 LOG(ERROR) << __func__ << ": " << mType << ": following source port config ids not found: "
1058 << ::android::internal::ToString(missingIds);
1059 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1060 }
1061 auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
1062 if (!missingIds.empty()) {
1063 LOG(ERROR) << __func__ << ": " << mType << ": following sink port config ids not found: "
1064 << ::android::internal::ToString(missingIds);
1065 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1066 }
1067 // bool indicates whether a non-exclusive route is available.
1068 // If only an exclusive route is available, that means the patch can not be
1069 // established if there is any other patch which currently uses the sink port.
1070 std::map<int32_t, bool> allowedSinkPorts;
1071 auto& routes = getConfig().routes;
1072 for (auto src : sources) {
1073 for (const auto& r : routes) {
1074 const auto& srcs = r.sourcePortIds;
1075 if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
1076 if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive
1077 allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
1078 }
1079 }
1080 }
1081 }
1082 for (auto sink : sinks) {
1083 if (allowedSinkPorts.count(sink->portId) == 0) {
1084 LOG(ERROR) << __func__ << ": " << mType << ": there is no route to the sink port id "
1085 << sink->portId;
1086 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1087 }
1088 }
1089 RETURN_STATUS_IF_ERROR(checkAudioPatchEndpointsMatch(sources, sinks));
1090
1091 auto& patches = getConfig().patches;
1092 auto existing = patches.end();
1093 std::optional<decltype(mPatches)> patchesBackup;
1094 if (in_requested.id != 0) {
1095 existing = findById<AudioPatch>(patches, in_requested.id);
1096 if (existing != patches.end()) {
1097 patchesBackup = mPatches;
1098 cleanUpPatch(existing->id);
1099 } else {
1100 LOG(ERROR) << __func__ << ": " << mType << ": not found existing patch id "
1101 << in_requested.id;
1102 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1103 }
1104 }
1105 // Validate the requested patch.
1106 for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
1107 if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
1108 LOG(ERROR) << __func__ << ": " << mType << ": sink port id " << sinkPortId
1109 << "is exclusive and is already used by some other patch";
1110 if (patchesBackup.has_value()) {
1111 mPatches = std::move(*patchesBackup);
1112 }
1113 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1114 }
1115 }
1116 // Find the highest sample rate among mix port configs.
1117 std::map<int32_t, AudioPortConfig*> sampleRates;
1118 std::vector<AudioPortConfig*>& mixPortConfigs =
1119 sources[0]->ext.getTag() == AudioPortExt::mix ? sources : sinks;
1120 for (auto mix : mixPortConfigs) {
1121 sampleRates.emplace(mix->sampleRate.value().value, mix);
1122 }
1123 *_aidl_return = in_requested;
1124 auto maxSampleRateIt = std::max_element(sampleRates.begin(), sampleRates.end());
1125 const int32_t latencyMs = getNominalLatencyMs(*(maxSampleRateIt->second));
1126 _aidl_return->minimumStreamBufferSizeFrames =
1127 calculateBufferSizeFrames(latencyMs, maxSampleRateIt->first);
1128 _aidl_return->latenciesMs.clear();
1129 _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
1130 _aidl_return->sinkPortConfigIds.size(), latencyMs);
1131 AudioPatch oldPatch{};
1132 if (existing == patches.end()) {
1133 _aidl_return->id = getConfig().nextPatchId++;
1134 patches.push_back(*_aidl_return);
1135 } else {
1136 oldPatch = *existing;
1137 *existing = *_aidl_return;
1138 }
1139 patchesBackup = mPatches;
1140 registerPatch(*_aidl_return);
1141 if (auto status = updateStreamsConnectedState(oldPatch, *_aidl_return); !status.isOk()) {
1142 mPatches = std::move(*patchesBackup);
1143 if (existing == patches.end()) {
1144 patches.pop_back();
1145 } else {
1146 *existing = oldPatch;
1147 }
1148 return status;
1149 }
1150
1151 LOG(DEBUG) << __func__ << ": " << mType << ": " << (oldPatch.id == 0 ? "created" : "updated")
1152 << " patch " << _aidl_return->toString();
1153 return ndk::ScopedAStatus::ok();
1154 }
1155
setAudioPortConfig(const AudioPortConfig & in_requested,AudioPortConfig * out_suggested,bool * _aidl_return)1156 ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
1157 AudioPortConfig* out_suggested, bool* _aidl_return) {
1158 auto generate = [this](const AudioPort& port, AudioPortConfig* config) {
1159 return generateDefaultPortConfig(port, config);
1160 };
1161 return setAudioPortConfigImpl(in_requested, generate, out_suggested, _aidl_return);
1162 }
1163
setAudioPortConfigImpl(const AudioPortConfig & in_requested,const std::function<bool (const::aidl::android::media::audio::common::AudioPort & port,::aidl::android::media::audio::common::AudioPortConfig * config)> & fillPortConfig,AudioPortConfig * out_suggested,bool * applied)1164 ndk::ScopedAStatus Module::setAudioPortConfigImpl(
1165 const AudioPortConfig& in_requested,
1166 const std::function<bool(const ::aidl::android::media::audio::common::AudioPort& port,
1167 ::aidl::android::media::audio::common::AudioPortConfig* config)>&
1168 fillPortConfig,
1169 AudioPortConfig* out_suggested, bool* applied) {
1170 LOG(DEBUG) << __func__ << ": " << mType << ": requested " << in_requested.toString();
1171 auto& configs = getConfig().portConfigs;
1172 auto existing = configs.end();
1173 if (in_requested.id != 0) {
1174 if (existing = findById<AudioPortConfig>(configs, in_requested.id);
1175 existing == configs.end()) {
1176 LOG(ERROR) << __func__ << ": " << mType << ": existing port config id "
1177 << in_requested.id << " not found";
1178 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1179 }
1180 }
1181
1182 const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
1183 if (portId == 0) {
1184 LOG(ERROR) << __func__ << ": " << mType
1185 << ": requested port config does not specify portId";
1186 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1187 }
1188 auto& ports = getConfig().ports;
1189 auto portIt = findById<AudioPort>(ports, portId);
1190 if (portIt == ports.end()) {
1191 LOG(ERROR) << __func__ << ": " << mType
1192 << ": requested port config points to non-existent portId " << portId;
1193 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1194 }
1195 if (existing != configs.end()) {
1196 *out_suggested = *existing;
1197 } else {
1198 AudioPortConfig newConfig;
1199 newConfig.portId = portIt->id;
1200 if (fillPortConfig(*portIt, &newConfig)) {
1201 *out_suggested = newConfig;
1202 } else {
1203 LOG(ERROR) << __func__ << ": " << mType
1204 << ": unable generate a default config for port " << portId;
1205 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1206 }
1207 }
1208 // From this moment, 'out_suggested' is either an existing port config,
1209 // or a new generated config. Now attempt to update it according to the specified
1210 // fields of 'in_requested'.
1211
1212 // Device ports with only dynamic profiles are used for devices that are connected via ADSP,
1213 // which takes care of their actual configuration automatically.
1214 const bool allowDynamicConfig = portIt->ext.getTag() == AudioPortExt::device &&
1215 hasDynamicProfilesOnly(portIt->profiles);
1216 bool requestedIsValid = true, requestedIsFullySpecified = true;
1217
1218 AudioIoFlags portFlags = portIt->flags;
1219 if (in_requested.flags.has_value()) {
1220 if (in_requested.flags.value() != portFlags) {
1221 LOG(WARNING) << __func__ << ": " << mType << ": requested flags "
1222 << in_requested.flags.value().toString() << " do not match port's "
1223 << portId << " flags " << portFlags.toString();
1224 requestedIsValid = false;
1225 }
1226 } else {
1227 requestedIsFullySpecified = false;
1228 }
1229
1230 AudioProfile portProfile;
1231 if (in_requested.format.has_value()) {
1232 const auto& format = in_requested.format.value();
1233 if ((format == AudioFormatDescription{} && allowDynamicConfig) ||
1234 findAudioProfile(*portIt, format, &portProfile)) {
1235 out_suggested->format = format;
1236 } else {
1237 LOG(WARNING) << __func__ << ": " << mType << ": requested format " << format.toString()
1238 << " is not found in the profiles of port " << portId;
1239 requestedIsValid = false;
1240 }
1241 } else {
1242 requestedIsFullySpecified = false;
1243 }
1244 if (!(out_suggested->format.value() == AudioFormatDescription{} && allowDynamicConfig) &&
1245 !findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
1246 LOG(ERROR) << __func__ << ": " << mType << ": port " << portId
1247 << " does not support format " << out_suggested->format.value().toString()
1248 << " anymore";
1249 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1250 }
1251
1252 if (in_requested.channelMask.has_value()) {
1253 const auto& channelMask = in_requested.channelMask.value();
1254 if ((channelMask == AudioChannelLayout{} && allowDynamicConfig) ||
1255 find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
1256 portProfile.channelMasks.end()) {
1257 out_suggested->channelMask = channelMask;
1258 } else {
1259 LOG(WARNING) << __func__ << ": " << mType << ": requested channel mask "
1260 << channelMask.toString() << " is not supported for the format "
1261 << portProfile.format.toString() << " by the port " << portId;
1262 requestedIsValid = false;
1263 }
1264 } else {
1265 requestedIsFullySpecified = false;
1266 }
1267
1268 if (in_requested.sampleRate.has_value()) {
1269 const auto& sampleRate = in_requested.sampleRate.value();
1270 if ((sampleRate.value == 0 && allowDynamicConfig) ||
1271 find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
1272 sampleRate.value) != portProfile.sampleRates.end()) {
1273 out_suggested->sampleRate = sampleRate;
1274 } else {
1275 LOG(WARNING) << __func__ << ": " << mType << ": requested sample rate "
1276 << sampleRate.value << " is not supported for the format "
1277 << portProfile.format.toString() << " by the port " << portId;
1278 requestedIsValid = false;
1279 }
1280 } else {
1281 requestedIsFullySpecified = false;
1282 }
1283
1284 if (in_requested.gain.has_value()) {
1285 if (!setAudioPortConfigGain(*portIt, in_requested.gain.value())) {
1286 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1287 }
1288 out_suggested->gain = in_requested.gain.value();
1289 }
1290
1291 if (in_requested.ext.getTag() != AudioPortExt::Tag::unspecified) {
1292 if (in_requested.ext.getTag() == out_suggested->ext.getTag()) {
1293 if (out_suggested->ext.getTag() == AudioPortExt::Tag::mix) {
1294 // 'AudioMixPortExt.handle' and '.usecase' are set by the client,
1295 // copy from in_requested.
1296 const auto& src = in_requested.ext.get<AudioPortExt::Tag::mix>();
1297 auto& dst = out_suggested->ext.get<AudioPortExt::Tag::mix>();
1298 dst.handle = src.handle;
1299 dst.usecase = src.usecase;
1300 }
1301 } else {
1302 LOG(WARNING) << __func__ << ": " << mType << ": requested ext tag "
1303 << toString(in_requested.ext.getTag()) << " do not match port's tag "
1304 << toString(out_suggested->ext.getTag());
1305 requestedIsValid = false;
1306 }
1307 }
1308
1309 if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
1310 out_suggested->id = getConfig().nextPortId++;
1311 configs.push_back(*out_suggested);
1312 *applied = true;
1313 LOG(DEBUG) << __func__ << ": " << mType << ": created new port config "
1314 << out_suggested->toString();
1315 } else if (existing != configs.end() && requestedIsValid) {
1316 *existing = *out_suggested;
1317 *applied = true;
1318 LOG(DEBUG) << __func__ << ": " << mType << ": updated port config "
1319 << out_suggested->toString();
1320 } else {
1321 LOG(DEBUG) << __func__ << ": " << mType << ": not applied; existing config ? "
1322 << (existing != configs.end()) << "; requested is valid? " << requestedIsValid
1323 << ", fully specified? " << requestedIsFullySpecified;
1324 *applied = false;
1325 }
1326 return ndk::ScopedAStatus::ok();
1327 }
1328
setAudioPortConfigGain(const AudioPort & port,const AudioGainConfig & gainRequested)1329 bool Module::setAudioPortConfigGain(const AudioPort& port, const AudioGainConfig& gainRequested) {
1330 auto& ports = getConfig().ports;
1331 if (gainRequested.index < 0 || gainRequested.index >= (int)port.gains.size()) {
1332 LOG(ERROR) << __func__ << ": gains for port " << port.id << " is undefined";
1333 return false;
1334 }
1335 int stepValue = port.gains[gainRequested.index].stepValue;
1336 if (stepValue == 0) {
1337 LOG(ERROR) << __func__ << ": port gain step value is 0";
1338 return false;
1339 }
1340 int minValue = port.gains[gainRequested.index].minValue;
1341 int maxValue = port.gains[gainRequested.index].maxValue;
1342 if (gainRequested.values[0] > maxValue || gainRequested.values[0] < minValue) {
1343 LOG(ERROR) << __func__ << ": gain value " << gainRequested.values[0]
1344 << " out of range of min and max gain config";
1345 return false;
1346 }
1347 int gainIndex = (gainRequested.values[0] - minValue) / stepValue;
1348 int totalSteps = (maxValue - minValue) / stepValue;
1349 if (totalSteps == 0) {
1350 LOG(ERROR) << __func__ << ": difference between port gain min value " << minValue
1351 << " and max value " << maxValue << " is less than step value " << stepValue;
1352 return false;
1353 }
1354 // Root-power quantities are used in curve:
1355 // 10^((minMb / 100 + (maxMb / 100 - minMb / 100) * gainIndex / totalSteps) / (10 * 2))
1356 // where 100 is the conversion from mB to dB, 10 comes from the log 10 conversion from power
1357 // ratios, and 2 means are the square of amplitude.
1358 float gain =
1359 pow(10, (minValue + (maxValue - minValue) * (gainIndex / (float)totalSteps)) / 2000);
1360 if (gain < 0) {
1361 LOG(ERROR) << __func__ << ": gain " << gain << " is less than 0";
1362 return false;
1363 }
1364 for (const auto& route : getConfig().routes) {
1365 if (route.sinkPortId != port.id) {
1366 continue;
1367 }
1368 for (const auto sourcePortId : route.sourcePortIds) {
1369 mStreams.setGain(sourcePortId, gain);
1370 }
1371 }
1372 return true;
1373 }
1374
resetAudioPatch(int32_t in_patchId)1375 ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
1376 auto& patches = getConfig().patches;
1377 auto patchIt = findById<AudioPatch>(patches, in_patchId);
1378 if (patchIt != patches.end()) {
1379 auto patchesBackup = mPatches;
1380 cleanUpPatch(patchIt->id);
1381 if (auto status = updateStreamsConnectedState(*patchIt, AudioPatch{}); !status.isOk()) {
1382 mPatches = std::move(patchesBackup);
1383 return status;
1384 }
1385 patches.erase(patchIt);
1386 LOG(DEBUG) << __func__ << ": " << mType << ": erased patch " << in_patchId;
1387 return ndk::ScopedAStatus::ok();
1388 }
1389 LOG(ERROR) << __func__ << ": " << mType << ": patch id " << in_patchId << " not found";
1390 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1391 }
1392
resetAudioPortConfig(int32_t in_portConfigId)1393 ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
1394 auto& configs = getConfig().portConfigs;
1395 auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
1396 if (configIt != configs.end()) {
1397 if (mStreams.count(in_portConfigId) != 0) {
1398 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
1399 << " has a stream opened on it";
1400 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1401 }
1402 auto patchIt = mPatches.find(in_portConfigId);
1403 if (patchIt != mPatches.end()) {
1404 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
1405 << " is used by the patch with id " << patchIt->second;
1406 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1407 }
1408 auto& initials = getConfig().initialConfigs;
1409 auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
1410 if (initialIt == initials.end()) {
1411 configs.erase(configIt);
1412 LOG(DEBUG) << __func__ << ": " << mType << ": erased port config " << in_portConfigId;
1413 } else if (*configIt != *initialIt) {
1414 *configIt = *initialIt;
1415 LOG(DEBUG) << __func__ << ": " << mType << ": reset port config " << in_portConfigId;
1416 }
1417 return ndk::ScopedAStatus::ok();
1418 }
1419 LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
1420 << " not found";
1421 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1422 }
1423
getMasterMute(bool * _aidl_return)1424 ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) {
1425 *_aidl_return = mMasterMute;
1426 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
1427 return ndk::ScopedAStatus::ok();
1428 }
1429
setMasterMute(bool in_mute)1430 ndk::ScopedAStatus Module::setMasterMute(bool in_mute) {
1431 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_mute;
1432 auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1433 : onMasterMuteChanged(in_mute);
1434 if (result.isOk()) {
1435 mMasterMute = in_mute;
1436 } else {
1437 LOG(ERROR) << __func__ << ": " << mType << ": failed calling onMasterMuteChanged("
1438 << in_mute << "), error=" << result;
1439 // Reset master mute if it failed.
1440 onMasterMuteChanged(mMasterMute);
1441 }
1442 return result;
1443 }
1444
getMasterVolume(float * _aidl_return)1445 ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) {
1446 *_aidl_return = mMasterVolume;
1447 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
1448 return ndk::ScopedAStatus::ok();
1449 }
1450
setMasterVolume(float in_volume)1451 ndk::ScopedAStatus Module::setMasterVolume(float in_volume) {
1452 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_volume;
1453 if (in_volume >= 0.0f && in_volume <= 1.0f) {
1454 auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1455 : onMasterVolumeChanged(in_volume);
1456 if (result.isOk()) {
1457 mMasterVolume = in_volume;
1458 } else {
1459 // Reset master volume if it failed.
1460 LOG(ERROR) << __func__ << ": " << mType << ": failed calling onMasterVolumeChanged("
1461 << in_volume << "), error=" << result;
1462 onMasterVolumeChanged(mMasterVolume);
1463 }
1464 return result;
1465 }
1466 LOG(ERROR) << __func__ << ": " << mType << ": invalid master volume value: " << in_volume;
1467 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1468 }
1469
getMicMute(bool * _aidl_return)1470 ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) {
1471 *_aidl_return = mMicMute;
1472 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
1473 return ndk::ScopedAStatus::ok();
1474 }
1475
setMicMute(bool in_mute)1476 ndk::ScopedAStatus Module::setMicMute(bool in_mute) {
1477 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_mute;
1478 mMicMute = in_mute;
1479 return ndk::ScopedAStatus::ok();
1480 }
1481
getMicrophones(std::vector<MicrophoneInfo> * _aidl_return)1482 ndk::ScopedAStatus Module::getMicrophones(std::vector<MicrophoneInfo>* _aidl_return) {
1483 *_aidl_return = getMicrophoneInfos();
1484 LOG(DEBUG) << __func__ << ": " << mType << ": returning "
1485 << ::android::internal::ToString(*_aidl_return);
1486 return ndk::ScopedAStatus::ok();
1487 }
1488
updateAudioMode(AudioMode in_mode)1489 ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) {
1490 if (!isValidAudioMode(in_mode)) {
1491 LOG(ERROR) << __func__ << ": " << mType << ": invalid mode " << toString(in_mode);
1492 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1493 }
1494 // No checks for supported audio modes here, it's an informative notification.
1495 LOG(DEBUG) << __func__ << ": " << mType << ": " << toString(in_mode);
1496 return ndk::ScopedAStatus::ok();
1497 }
1498
updateScreenRotation(ScreenRotation in_rotation)1499 ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) {
1500 LOG(DEBUG) << __func__ << ": " << mType << ": " << toString(in_rotation);
1501 return ndk::ScopedAStatus::ok();
1502 }
1503
updateScreenState(bool in_isTurnedOn)1504 ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) {
1505 LOG(DEBUG) << __func__ << ": " << mType << ": " << in_isTurnedOn;
1506 return ndk::ScopedAStatus::ok();
1507 }
1508
getSoundDose(std::shared_ptr<ISoundDose> * _aidl_return)1509 ndk::ScopedAStatus Module::getSoundDose(std::shared_ptr<ISoundDose>* _aidl_return) {
1510 if (!mSoundDose) {
1511 mSoundDose = ndk::SharedRefBase::make<sounddose::SoundDose>();
1512 }
1513 *_aidl_return = mSoundDose.getInstance();
1514 LOG(DEBUG) << __func__ << ": " << mType
1515 << ": returning instance of ISoundDose: " << _aidl_return->get();
1516 return ndk::ScopedAStatus::ok();
1517 }
1518
generateHwAvSyncId(int32_t * _aidl_return)1519 ndk::ScopedAStatus Module::generateHwAvSyncId(int32_t* _aidl_return) {
1520 LOG(DEBUG) << __func__ << ": " << mType;
1521 (void)_aidl_return;
1522 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1523 }
1524
1525 const std::string Module::VendorDebug::kForceTransientBurstName = "aosp.forceTransientBurst";
1526 const std::string Module::VendorDebug::kForceSynchronousDrainName = "aosp.forceSynchronousDrain";
1527 const std::string Module::VendorDebug::kForceDrainToDrainingName = "aosp.forceDrainToDraining";
1528
getVendorParameters(const std::vector<std::string> & in_ids,std::vector<VendorParameter> * _aidl_return)1529 ndk::ScopedAStatus Module::getVendorParameters(const std::vector<std::string>& in_ids,
1530 std::vector<VendorParameter>* _aidl_return) {
1531 LOG(VERBOSE) << __func__ << ": " << mType << ": id count: " << in_ids.size();
1532 bool allParametersKnown = true;
1533 for (const auto& id : in_ids) {
1534 if (id == VendorDebug::kForceTransientBurstName) {
1535 VendorParameter forceTransientBurst{.id = id};
1536 forceTransientBurst.ext.setParcelable(Boolean{mVendorDebug.forceTransientBurst});
1537 _aidl_return->push_back(std::move(forceTransientBurst));
1538 } else if (id == VendorDebug::kForceSynchronousDrainName) {
1539 VendorParameter forceSynchronousDrain{.id = id};
1540 forceSynchronousDrain.ext.setParcelable(Boolean{mVendorDebug.forceSynchronousDrain});
1541 _aidl_return->push_back(std::move(forceSynchronousDrain));
1542 } else if (id == VendorDebug::kForceDrainToDrainingName) {
1543 VendorParameter forceDrainToDraining{.id = id};
1544 forceDrainToDraining.ext.setParcelable(Boolean{mVendorDebug.forceDrainToDraining});
1545 _aidl_return->push_back(std::move(forceDrainToDraining));
1546 } else {
1547 allParametersKnown = false;
1548 LOG(VERBOSE) << __func__ << ": " << mType << ": unrecognized parameter \"" << id << "\"";
1549 }
1550 }
1551 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1552 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1553 }
1554
1555 namespace {
1556
1557 template <typename W>
extractParameter(const VendorParameter & p,decltype(W::value) * v)1558 bool extractParameter(const VendorParameter& p, decltype(W::value)* v) {
1559 std::optional<W> value;
1560 binder_status_t result = p.ext.getParcelable(&value);
1561 if (result == STATUS_OK && value.has_value()) {
1562 *v = value.value().value;
1563 return true;
1564 }
1565 LOG(ERROR) << __func__ << ": failed to read the value of the parameter \"" << p.id
1566 << "\": " << result;
1567 return false;
1568 }
1569
1570 } // namespace
1571
setVendorParameters(const std::vector<VendorParameter> & in_parameters,bool in_async)1572 ndk::ScopedAStatus Module::setVendorParameters(const std::vector<VendorParameter>& in_parameters,
1573 bool in_async) {
1574 LOG(VERBOSE) << __func__ << ": " << mType << ": parameter count " << in_parameters.size()
1575 << ", async: " << in_async;
1576 bool allParametersKnown = true;
1577 for (const auto& p : in_parameters) {
1578 if (p.id == VendorDebug::kForceTransientBurstName) {
1579 if (!extractParameter<Boolean>(p, &mVendorDebug.forceTransientBurst)) {
1580 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1581 }
1582 } else if (p.id == VendorDebug::kForceSynchronousDrainName) {
1583 if (!extractParameter<Boolean>(p, &mVendorDebug.forceSynchronousDrain)) {
1584 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1585 }
1586 } else if (p.id == VendorDebug::kForceDrainToDrainingName) {
1587 if (!extractParameter<Boolean>(p, &mVendorDebug.forceDrainToDraining)) {
1588 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1589 }
1590 } else {
1591 allParametersKnown = false;
1592 LOG(VERBOSE) << __func__ << ": " << mType << ": unrecognized parameter \"" << p.id
1593 << "\"";
1594 }
1595 }
1596 if (allParametersKnown) return ndk::ScopedAStatus::ok();
1597 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1598 }
1599
addDeviceEffect(int32_t in_portConfigId,const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect> & in_effect)1600 ndk::ScopedAStatus Module::addDeviceEffect(
1601 int32_t in_portConfigId,
1602 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1603 if (in_effect == nullptr) {
1604 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1605 << ", null effect";
1606 } else {
1607 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1608 << ", effect Binder " << in_effect->asBinder().get();
1609 }
1610 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1611 }
1612
removeDeviceEffect(int32_t in_portConfigId,const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect> & in_effect)1613 ndk::ScopedAStatus Module::removeDeviceEffect(
1614 int32_t in_portConfigId,
1615 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1616 if (in_effect == nullptr) {
1617 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1618 << ", null effect";
1619 } else {
1620 LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1621 << ", effect Binder " << in_effect->asBinder().get();
1622 }
1623 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1624 }
1625
getMmapPolicyInfos(AudioMMapPolicyType mmapPolicyType,std::vector<AudioMMapPolicyInfo> * _aidl_return)1626 ndk::ScopedAStatus Module::getMmapPolicyInfos(AudioMMapPolicyType mmapPolicyType,
1627 std::vector<AudioMMapPolicyInfo>* _aidl_return) {
1628 LOG(DEBUG) << __func__ << ": " << mType << ": mmap policy type " << toString(mmapPolicyType);
1629 std::set<int32_t> mmapSinks;
1630 std::set<int32_t> mmapSources;
1631 auto& ports = getConfig().ports;
1632 for (const auto& port : ports) {
1633 if (port.flags.getTag() == AudioIoFlags::Tag::input &&
1634 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::input>(),
1635 AudioInputFlags::MMAP_NOIRQ)) {
1636 mmapSinks.insert(port.id);
1637 } else if (port.flags.getTag() == AudioIoFlags::Tag::output &&
1638 isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
1639 AudioOutputFlags::MMAP_NOIRQ)) {
1640 mmapSources.insert(port.id);
1641 }
1642 }
1643 if (mmapSources.empty() && mmapSinks.empty()) {
1644 AudioMMapPolicyInfo never;
1645 never.mmapPolicy = AudioMMapPolicy::NEVER;
1646 _aidl_return->push_back(never);
1647 return ndk::ScopedAStatus::ok();
1648 }
1649 for (const auto& route : getConfig().routes) {
1650 if (mmapSinks.count(route.sinkPortId) != 0) {
1651 // The sink is a mix port, add the sources if they are device ports.
1652 for (int sourcePortId : route.sourcePortIds) {
1653 auto sourcePortIt = findById<AudioPort>(ports, sourcePortId);
1654 if (sourcePortIt == ports.end()) {
1655 // This must not happen
1656 LOG(ERROR) << __func__ << ": " << mType << ": port id " << sourcePortId
1657 << " cannot be found";
1658 continue;
1659 }
1660 if (sourcePortIt->ext.getTag() != AudioPortExt::Tag::device) {
1661 // The source is not a device port, skip
1662 continue;
1663 }
1664 AudioMMapPolicyInfo policyInfo;
1665 policyInfo.device = sourcePortIt->ext.get<AudioPortExt::Tag::device>().device;
1666 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1667 // default implementation.
1668 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1669 _aidl_return->push_back(policyInfo);
1670 }
1671 } else {
1672 auto sinkPortIt = findById<AudioPort>(ports, route.sinkPortId);
1673 if (sinkPortIt == ports.end()) {
1674 // This must not happen
1675 LOG(ERROR) << __func__ << ": " << mType << ": port id " << route.sinkPortId
1676 << " cannot be found";
1677 continue;
1678 }
1679 if (sinkPortIt->ext.getTag() != AudioPortExt::Tag::device) {
1680 // The sink is not a device port, skip
1681 continue;
1682 }
1683 if (count_any(mmapSources, route.sourcePortIds)) {
1684 AudioMMapPolicyInfo policyInfo;
1685 policyInfo.device = sinkPortIt->ext.get<AudioPortExt::Tag::device>().device;
1686 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1687 // default implementation.
1688 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1689 _aidl_return->push_back(policyInfo);
1690 }
1691 }
1692 }
1693 return ndk::ScopedAStatus::ok();
1694 }
1695
supportsVariableLatency(bool * _aidl_return)1696 ndk::ScopedAStatus Module::supportsVariableLatency(bool* _aidl_return) {
1697 LOG(DEBUG) << __func__ << ": " << mType;
1698 *_aidl_return = false;
1699 return ndk::ScopedAStatus::ok();
1700 }
1701
getAAudioMixerBurstCount(int32_t * _aidl_return)1702 ndk::ScopedAStatus Module::getAAudioMixerBurstCount(int32_t* _aidl_return) {
1703 if (!isMmapSupported()) {
1704 LOG(DEBUG) << __func__ << ": " << mType << ": mmap is not supported ";
1705 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1706 }
1707 *_aidl_return = DEFAULT_AAUDIO_MIXER_BURST_COUNT;
1708 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
1709 return ndk::ScopedAStatus::ok();
1710 }
1711
getAAudioHardwareBurstMinUsec(int32_t * _aidl_return)1712 ndk::ScopedAStatus Module::getAAudioHardwareBurstMinUsec(int32_t* _aidl_return) {
1713 if (!isMmapSupported()) {
1714 LOG(DEBUG) << __func__ << ": " << mType << ": mmap is not supported ";
1715 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1716 }
1717 *_aidl_return = DEFAULT_AAUDIO_HARDWARE_BURST_MIN_DURATION_US;
1718 LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
1719 return ndk::ScopedAStatus::ok();
1720 }
1721
isMmapSupported()1722 bool Module::isMmapSupported() {
1723 if (mIsMmapSupported.has_value()) {
1724 return mIsMmapSupported.value();
1725 }
1726 std::vector<AudioMMapPolicyInfo> mmapPolicyInfos;
1727 if (!getMmapPolicyInfos(AudioMMapPolicyType::DEFAULT, &mmapPolicyInfos).isOk()) {
1728 mIsMmapSupported = false;
1729 } else {
1730 mIsMmapSupported =
1731 std::find_if(mmapPolicyInfos.begin(), mmapPolicyInfos.end(), [](const auto& info) {
1732 return info.mmapPolicy == AudioMMapPolicy::AUTO ||
1733 info.mmapPolicy == AudioMMapPolicy::ALWAYS;
1734 }) != mmapPolicyInfos.end();
1735 }
1736 return mIsMmapSupported.value();
1737 }
1738
populateConnectedDevicePort(AudioPort * audioPort,int32_t)1739 ndk::ScopedAStatus Module::populateConnectedDevicePort(AudioPort* audioPort, int32_t) {
1740 if (audioPort->ext.getTag() != AudioPortExt::device) {
1741 LOG(ERROR) << __func__ << ": " << mType << ": not a device port: " << audioPort->toString();
1742 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1743 }
1744 const auto& devicePort = audioPort->ext.get<AudioPortExt::device>();
1745 if (!devicePort.device.type.connection.empty()) {
1746 LOG(ERROR) << __func__ << ": " << mType << ": module implementation must override "
1747 "'populateConnectedDevicePort' "
1748 << "to handle connection of external devices.";
1749 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1750 }
1751 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
1752 return ndk::ScopedAStatus::ok();
1753 }
1754
checkAudioPatchEndpointsMatch(const std::vector<AudioPortConfig * > & sources __unused,const std::vector<AudioPortConfig * > & sinks __unused)1755 ndk::ScopedAStatus Module::checkAudioPatchEndpointsMatch(
1756 const std::vector<AudioPortConfig*>& sources __unused,
1757 const std::vector<AudioPortConfig*>& sinks __unused) {
1758 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
1759 return ndk::ScopedAStatus::ok();
1760 }
1761
onExternalDeviceConnectionChanged(const::aidl::android::media::audio::common::AudioPort & audioPort __unused,bool connected __unused)1762 void Module::onExternalDeviceConnectionChanged(
1763 const ::aidl::android::media::audio::common::AudioPort& audioPort __unused,
1764 bool connected __unused) {
1765 LOG(DEBUG) << __func__ << ": " << mType << ": do nothing and return";
1766 }
1767
onPrepareToDisconnectExternalDevice(const::aidl::android::media::audio::common::AudioPort & audioPort __unused)1768 void Module::onPrepareToDisconnectExternalDevice(
1769 const ::aidl::android::media::audio::common::AudioPort& audioPort __unused) {
1770 LOG(DEBUG) << __func__ << ": " << mType << ": do nothing and return";
1771 }
1772
onMasterMuteChanged(bool mute __unused)1773 ndk::ScopedAStatus Module::onMasterMuteChanged(bool mute __unused) {
1774 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
1775 return ndk::ScopedAStatus::ok();
1776 }
1777
onMasterVolumeChanged(float volume __unused)1778 ndk::ScopedAStatus Module::onMasterVolumeChanged(float volume __unused) {
1779 LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
1780 return ndk::ScopedAStatus::ok();
1781 }
1782
getMicrophoneInfos()1783 std::vector<MicrophoneInfo> Module::getMicrophoneInfos() {
1784 std::vector<MicrophoneInfo> result;
1785 Configuration& config = getConfig();
1786 for (const AudioPort& port : config.ports) {
1787 if (port.ext.getTag() == AudioPortExt::Tag::device) {
1788 const AudioDeviceType deviceType =
1789 port.ext.get<AudioPortExt::Tag::device>().device.type.type;
1790 if (deviceType == AudioDeviceType::IN_MICROPHONE ||
1791 deviceType == AudioDeviceType::IN_MICROPHONE_BACK) {
1792 // Placeholder values. Vendor implementations must populate MicrophoneInfo
1793 // accordingly based on their physical microphone parameters.
1794 result.push_back(MicrophoneInfo{
1795 .id = port.name,
1796 .device = port.ext.get<AudioPortExt::Tag::device>().device,
1797 .group = 0,
1798 .indexInTheGroup = 0,
1799 });
1800 }
1801 }
1802 }
1803 return result;
1804 }
1805
bluetoothParametersUpdated()1806 ndk::ScopedAStatus Module::bluetoothParametersUpdated() {
1807 return mStreams.bluetoothParametersUpdated();
1808 }
1809
1810 } // namespace aidl::android::hardware::audio::core
1811