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