AudioPolicyManager.cpp revision dacc06f5e8d00ace9d16a149fc41ff65323ffbb3
1/* 2 * Copyright (C) 2009 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#define LOG_TAG "APM::AudioPolicyManager" 18//#define LOG_NDEBUG 0 19 20//#define VERY_VERBOSE_LOGGING 21#ifdef VERY_VERBOSE_LOGGING 22#define ALOGVV ALOGV 23#else 24#define ALOGVV(a...) do { } while(0) 25#endif 26 27#include <inttypes.h> 28#include <math.h> 29 30#include <AudioPolicyManagerInterface.h> 31#include <AudioPolicyEngineInstance.h> 32#include <cutils/properties.h> 33#include <utils/Log.h> 34#include <hardware/audio.h> 35#include <hardware/audio_effect.h> 36#include <media/AudioParameter.h> 37#include <media/AudioPolicyHelper.h> 38#include <soundtrigger/SoundTrigger.h> 39#include "AudioPolicyManager.h" 40#include "audio_policy_conf.h" 41#include <ConfigParsingUtils.h> 42#include <policy.h> 43 44namespace android { 45 46// ---------------------------------------------------------------------------- 47// AudioPolicyInterface implementation 48// ---------------------------------------------------------------------------- 49 50status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device, 51 audio_policy_dev_state_t state, 52 const char *device_address, 53 const char *device_name) 54{ 55 return setDeviceConnectionStateInt(device, state, device_address, device_name); 56} 57 58status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device, 59 audio_policy_dev_state_t state, 60 const char *device_address, 61 const char *device_name) 62{ 63 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s", 64- device, state, device_address, device_name); 65 66 // connect/disconnect only 1 device at a time 67 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE; 68 69 sp<DeviceDescriptor> devDesc = 70 mHwModules.getDeviceDescriptor(device, device_address, device_name); 71 72 // handle output devices 73 if (audio_is_output_device(device)) { 74 SortedVector <audio_io_handle_t> outputs; 75 76 ssize_t index = mAvailableOutputDevices.indexOf(devDesc); 77 78 // save a copy of the opened output descriptors before any output is opened or closed 79 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies() 80 mPreviousOutputs = mOutputs; 81 switch (state) 82 { 83 // handle output device connection 84 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: { 85 if (index >= 0) { 86 ALOGW("setDeviceConnectionState() device already connected: %x", device); 87 return INVALID_OPERATION; 88 } 89 ALOGV("setDeviceConnectionState() connecting device %x", device); 90 91 // register new device as available 92 index = mAvailableOutputDevices.add(devDesc); 93 if (index >= 0) { 94 sp<HwModule> module = mHwModules.getModuleForDevice(device); 95 if (module == 0) { 96 ALOGD("setDeviceConnectionState() could not find HW module for device %08x", 97 device); 98 mAvailableOutputDevices.remove(devDesc); 99 return INVALID_OPERATION; 100 } 101 mAvailableOutputDevices[index]->attach(module); 102 } else { 103 return NO_MEMORY; 104 } 105 106 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) { 107 mAvailableOutputDevices.remove(devDesc); 108 return INVALID_OPERATION; 109 } 110 // Propagate device availability to Engine 111 mEngine->setDeviceConnectionState(devDesc, state); 112 113 // outputs should never be empty here 114 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():" 115 "checkOutputsForDevice() returned no outputs but status OK"); 116 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs", 117 outputs.size()); 118 119 // Send connect to HALs 120 AudioParameter param = AudioParameter(devDesc->mAddress); 121 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device); 122 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString()); 123 124 } break; 125 // handle output device disconnection 126 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: { 127 if (index < 0) { 128 ALOGW("setDeviceConnectionState() device not connected: %x", device); 129 return INVALID_OPERATION; 130 } 131 132 ALOGV("setDeviceConnectionState() disconnecting output device %x", device); 133 134 // Send Disconnect to HALs 135 AudioParameter param = AudioParameter(devDesc->mAddress); 136 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device); 137 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString()); 138 139 // remove device from available output devices 140 mAvailableOutputDevices.remove(devDesc); 141 142 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress); 143 144 // Propagate device availability to Engine 145 mEngine->setDeviceConnectionState(devDesc, state); 146 } break; 147 148 default: 149 ALOGE("setDeviceConnectionState() invalid state: %x", state); 150 return BAD_VALUE; 151 } 152 153 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP 154 // output is suspended before any tracks are moved to it 155 checkA2dpSuspend(); 156 checkOutputForAllStrategies(); 157 // outputs must be closed after checkOutputForAllStrategies() is executed 158 if (!outputs.isEmpty()) { 159 for (size_t i = 0; i < outputs.size(); i++) { 160 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]); 161 // close unused outputs after device disconnection or direct outputs that have been 162 // opened by checkOutputsForDevice() to query dynamic parameters 163 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) || 164 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) && 165 (desc->mDirectOpenCount == 0))) { 166 closeOutput(outputs[i]); 167 } 168 } 169 // check again after closing A2DP output to reset mA2dpSuspended if needed 170 checkA2dpSuspend(); 171 } 172 173 updateDevicesAndOutputs(); 174 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) { 175 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/); 176 updateCallRouting(newDevice); 177 } 178 for (size_t i = 0; i < mOutputs.size(); i++) { 179 audio_io_handle_t output = mOutputs.keyAt(i); 180 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) { 181 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i), 182 true /*fromCache*/); 183 // do not force device change on duplicated output because if device is 0, it will 184 // also force a device 0 for the two outputs it is duplicated to which may override 185 // a valid device selection on those outputs. 186 bool force = !mOutputs.valueAt(i)->isDuplicated() 187 && (!device_distinguishes_on_address(device) 188 // always force when disconnecting (a non-duplicated device) 189 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)); 190 setOutputDevice(output, newDevice, force, 0); 191 } 192 } 193 194 mpClientInterface->onAudioPortListUpdate(); 195 return NO_ERROR; 196 } // end if is output device 197 198 // handle input devices 199 if (audio_is_input_device(device)) { 200 SortedVector <audio_io_handle_t> inputs; 201 202 ssize_t index = mAvailableInputDevices.indexOf(devDesc); 203 switch (state) 204 { 205 // handle input device connection 206 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: { 207 if (index >= 0) { 208 ALOGW("setDeviceConnectionState() device already connected: %d", device); 209 return INVALID_OPERATION; 210 } 211 sp<HwModule> module = mHwModules.getModuleForDevice(device); 212 if (module == NULL) { 213 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x", 214 device); 215 return INVALID_OPERATION; 216 } 217 if (checkInputsForDevice(device, state, inputs, devDesc->mAddress) != NO_ERROR) { 218 return INVALID_OPERATION; 219 } 220 221 index = mAvailableInputDevices.add(devDesc); 222 if (index >= 0) { 223 mAvailableInputDevices[index]->attach(module); 224 } else { 225 return NO_MEMORY; 226 } 227 228 // Set connect to HALs 229 AudioParameter param = AudioParameter(devDesc->mAddress); 230 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device); 231 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString()); 232 233 // Propagate device availability to Engine 234 mEngine->setDeviceConnectionState(devDesc, state); 235 } break; 236 237 // handle input device disconnection 238 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: { 239 if (index < 0) { 240 ALOGW("setDeviceConnectionState() device not connected: %d", device); 241 return INVALID_OPERATION; 242 } 243 244 ALOGV("setDeviceConnectionState() disconnecting input device %x", device); 245 246 // Set Disconnect to HALs 247 AudioParameter param = AudioParameter(devDesc->mAddress); 248 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device); 249 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString()); 250 251 checkInputsForDevice(device, state, inputs, devDesc->mAddress); 252 mAvailableInputDevices.remove(devDesc); 253 254 // Propagate device availability to Engine 255 mEngine->setDeviceConnectionState(devDesc, state); 256 } break; 257 258 default: 259 ALOGE("setDeviceConnectionState() invalid state: %x", state); 260 return BAD_VALUE; 261 } 262 263 closeAllInputs(); 264 265 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) { 266 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/); 267 updateCallRouting(newDevice); 268 } 269 270 mpClientInterface->onAudioPortListUpdate(); 271 return NO_ERROR; 272 } // end if is input device 273 274 ALOGW("setDeviceConnectionState() invalid device: %x", device); 275 return BAD_VALUE; 276} 277 278audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device, 279 const char *device_address) 280{ 281 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(device, device_address, ""); 282 283 DeviceVector *deviceVector; 284 285 if (audio_is_output_device(device)) { 286 deviceVector = &mAvailableOutputDevices; 287 } else if (audio_is_input_device(device)) { 288 deviceVector = &mAvailableInputDevices; 289 } else { 290 ALOGW("getDeviceConnectionState() invalid device type %08x", device); 291 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE; 292 } 293 return deviceVector->getDeviceConnectionState(devDesc); 294} 295 296void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs) 297{ 298 bool createTxPatch = false; 299 struct audio_patch patch; 300 patch.num_sources = 1; 301 patch.num_sinks = 1; 302 status_t status; 303 audio_patch_handle_t afPatchHandle; 304 DeviceVector deviceList; 305 306 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION); 307 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice); 308 309 // release existing RX patch if any 310 if (mCallRxPatch != 0) { 311 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0); 312 mCallRxPatch.clear(); 313 } 314 // release TX patch if any 315 if (mCallTxPatch != 0) { 316 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0); 317 mCallTxPatch.clear(); 318 } 319 320 // If the RX device is on the primary HW module, then use legacy routing method for voice calls 321 // via setOutputDevice() on primary output. 322 // Otherwise, create two audio patches for TX and RX path. 323 if (availablePrimaryOutputDevices() & rxDevice) { 324 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs); 325 // If the TX device is also on the primary HW module, setOutputDevice() will take care 326 // of it due to legacy implementation. If not, create a patch. 327 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN) 328 == AUDIO_DEVICE_NONE) { 329 createTxPatch = true; 330 } 331 } else { 332 // create RX path audio patch 333 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice); 334 ALOG_ASSERT(!deviceList.isEmpty(), 335 "updateCallRouting() selected device not in output device list"); 336 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0); 337 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX); 338 ALOG_ASSERT(!deviceList.isEmpty(), 339 "updateCallRouting() no telephony RX device"); 340 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0); 341 342 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]); 343 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]); 344 345 // request to reuse existing output stream if one is already opened to reach the RX device 346 SortedVector<audio_io_handle_t> outputs = 347 getOutputsForDevice(rxDevice, mOutputs); 348 audio_io_handle_t output = selectOutput(outputs, 349 AUDIO_OUTPUT_FLAG_NONE, 350 AUDIO_FORMAT_INVALID); 351 if (output != AUDIO_IO_HANDLE_NONE) { 352 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 353 ALOG_ASSERT(!outputDesc->isDuplicated(), 354 "updateCallRouting() RX device output is duplicated"); 355 outputDesc->toAudioPortConfig(&patch.sources[1]); 356 patch.num_sources = 2; 357 } 358 359 afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 360 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0); 361 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch", 362 status); 363 if (status == NO_ERROR) { 364 mCallRxPatch = new AudioPatch(&patch, mUidCached); 365 mCallRxPatch->mAfPatchHandle = afPatchHandle; 366 mCallRxPatch->mUid = mUidCached; 367 } 368 createTxPatch = true; 369 } 370 if (createTxPatch) { 371 372 struct audio_patch patch; 373 patch.num_sources = 1; 374 patch.num_sinks = 1; 375 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice); 376 ALOG_ASSERT(!deviceList.isEmpty(), 377 "updateCallRouting() selected device not in input device list"); 378 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0); 379 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]); 380 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX); 381 ALOG_ASSERT(!deviceList.isEmpty(), 382 "updateCallRouting() no telephony TX device"); 383 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0); 384 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]); 385 386 SortedVector<audio_io_handle_t> outputs = 387 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs); 388 audio_io_handle_t output = selectOutput(outputs, 389 AUDIO_OUTPUT_FLAG_NONE, 390 AUDIO_FORMAT_INVALID); 391 // request to reuse existing output stream if one is already opened to reach the TX 392 // path output device 393 if (output != AUDIO_IO_HANDLE_NONE) { 394 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 395 ALOG_ASSERT(!outputDesc->isDuplicated(), 396 "updateCallRouting() RX device output is duplicated"); 397 outputDesc->toAudioPortConfig(&patch.sources[1]); 398 patch.num_sources = 2; 399 } 400 401 afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 402 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0); 403 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch", 404 status); 405 if (status == NO_ERROR) { 406 mCallTxPatch = new AudioPatch(&patch, mUidCached); 407 mCallTxPatch->mAfPatchHandle = afPatchHandle; 408 mCallTxPatch->mUid = mUidCached; 409 } 410 } 411} 412 413void AudioPolicyManager::setPhoneState(audio_mode_t state) 414{ 415 ALOGV("setPhoneState() state %d", state); 416 // store previous phone state for management of sonification strategy below 417 int oldState = mEngine->getPhoneState(); 418 419 if (mEngine->setPhoneState(state) != NO_ERROR) { 420 ALOGW("setPhoneState() invalid or same state %d", state); 421 return; 422 } 423 /// Opens: can these line be executed after the switch of volume curves??? 424 // if leaving call state, handle special case of active streams 425 // pertaining to sonification strategy see handleIncallSonification() 426 if (isInCall()) { 427 ALOGV("setPhoneState() in call state management: new state is %d", state); 428 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) { 429 if (stream == AUDIO_STREAM_PATCH) { 430 continue; 431 } 432 handleIncallSonification((audio_stream_type_t)stream, false, true); 433 } 434 435 // force reevaluating accessibility routing when call starts 436 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY); 437 } 438 439 /** 440 * Switching to or from incall state or switching between telephony and VoIP lead to force 441 * routing command. 442 */ 443 bool force = ((is_state_in_call(oldState) != is_state_in_call(state)) 444 || (is_state_in_call(state) && (state != oldState))); 445 446 // check for device and output changes triggered by new phone state 447 checkA2dpSuspend(); 448 checkOutputForAllStrategies(); 449 updateDevicesAndOutputs(); 450 451 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput); 452 453 int delayMs = 0; 454 if (isStateInCall(state)) { 455 nsecs_t sysTime = systemTime(); 456 for (size_t i = 0; i < mOutputs.size(); i++) { 457 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 458 // mute media and sonification strategies and delay device switch by the largest 459 // latency of any output where either strategy is active. 460 // This avoid sending the ring tone or music tail into the earpiece or headset. 461 if ((isStrategyActive(desc, STRATEGY_MEDIA, 462 SONIFICATION_HEADSET_MUSIC_DELAY, 463 sysTime) || 464 isStrategyActive(desc, STRATEGY_SONIFICATION, 465 SONIFICATION_HEADSET_MUSIC_DELAY, 466 sysTime)) && 467 (delayMs < (int)desc->mLatency*2)) { 468 delayMs = desc->mLatency*2; 469 } 470 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i)); 471 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS, 472 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/)); 473 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i)); 474 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS, 475 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/)); 476 } 477 } 478 479 // Note that despite the fact that getNewOutputDevice() is called on the primary output, 480 // the device returned is not necessarily reachable via this output 481 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/); 482 // force routing command to audio hardware when ending call 483 // even if no device change is needed 484 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) { 485 rxDevice = hwOutputDesc->device(); 486 } 487 488 if (state == AUDIO_MODE_IN_CALL) { 489 updateCallRouting(rxDevice, delayMs); 490 } else if (oldState == AUDIO_MODE_IN_CALL) { 491 if (mCallRxPatch != 0) { 492 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0); 493 mCallRxPatch.clear(); 494 } 495 if (mCallTxPatch != 0) { 496 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0); 497 mCallTxPatch.clear(); 498 } 499 setOutputDevice(mPrimaryOutput, rxDevice, force, 0); 500 } else { 501 setOutputDevice(mPrimaryOutput, rxDevice, force, 0); 502 } 503 // if entering in call state, handle special case of active streams 504 // pertaining to sonification strategy see handleIncallSonification() 505 if (isStateInCall(state)) { 506 ALOGV("setPhoneState() in call state management: new state is %d", state); 507 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) { 508 if (stream == AUDIO_STREAM_PATCH) { 509 continue; 510 } 511 handleIncallSonification((audio_stream_type_t)stream, true, true); 512 } 513 } 514 515 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE 516 if (state == AUDIO_MODE_RINGTONE && 517 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) { 518 mLimitRingtoneVolume = true; 519 } else { 520 mLimitRingtoneVolume = false; 521 } 522} 523 524audio_mode_t AudioPolicyManager::getPhoneState() { 525 return mEngine->getPhoneState(); 526} 527 528void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage, 529 audio_policy_forced_cfg_t config) 530{ 531 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState()); 532 533 if (mEngine->setForceUse(usage, config) != NO_ERROR) { 534 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage); 535 return; 536 } 537 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) || 538 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) || 539 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM); 540 541 // check for device and output changes triggered by new force usage 542 checkA2dpSuspend(); 543 checkOutputForAllStrategies(); 544 updateDevicesAndOutputs(); 545 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) { 546 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/); 547 updateCallRouting(newDevice); 548 } 549 for (size_t i = 0; i < mOutputs.size(); i++) { 550 audio_io_handle_t output = mOutputs.keyAt(i); 551 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/); 552 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) { 553 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE)); 554 } 555 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) { 556 applyStreamVolumes(output, newDevice, 0, true); 557 } 558 } 559 560 audio_io_handle_t activeInput = mInputs.getActiveInput(); 561 if (activeInput != 0) { 562 setInputDevice(activeInput, getNewInputDevice(activeInput)); 563 } 564 565} 566 567void AudioPolicyManager::setSystemProperty(const char* property, const char* value) 568{ 569 ALOGV("setSystemProperty() property %s, value %s", property, value); 570} 571 572// Find a direct output profile compatible with the parameters passed, even if the input flags do 573// not explicitly request a direct output 574sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput( 575 audio_devices_t device, 576 uint32_t samplingRate, 577 audio_format_t format, 578 audio_channel_mask_t channelMask, 579 audio_output_flags_t flags) 580{ 581 for (size_t i = 0; i < mHwModules.size(); i++) { 582 if (mHwModules[i]->mHandle == 0) { 583 continue; 584 } 585 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) { 586 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j]; 587 bool found = profile->isCompatibleProfile(device, String8(""), samplingRate, 588 NULL /*updatedSamplingRate*/, format, channelMask, 589 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ? 590 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT); 591 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) { 592 return profile; 593 } 594 } 595 } 596 return 0; 597} 598 599audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream, 600 uint32_t samplingRate, 601 audio_format_t format, 602 audio_channel_mask_t channelMask, 603 audio_output_flags_t flags, 604 const audio_offload_info_t *offloadInfo) 605{ 606 routing_strategy strategy = getStrategy(stream); 607 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/); 608 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x", 609 device, stream, samplingRate, format, channelMask, flags); 610 611 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE, 612 stream, samplingRate,format, channelMask, 613 flags, offloadInfo); 614} 615 616status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr, 617 audio_io_handle_t *output, 618 audio_session_t session, 619 audio_stream_type_t *stream, 620 uint32_t samplingRate, 621 audio_format_t format, 622 audio_channel_mask_t channelMask, 623 audio_output_flags_t flags, 624 const audio_offload_info_t *offloadInfo) 625{ 626 audio_attributes_t attributes; 627 if (attr != NULL) { 628 if (!isValidAttributes(attr)) { 629 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]", 630 attr->usage, attr->content_type, attr->flags, 631 attr->tags); 632 return BAD_VALUE; 633 } 634 attributes = *attr; 635 } else { 636 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) { 637 ALOGE("getOutputForAttr(): invalid stream type"); 638 return BAD_VALUE; 639 } 640 stream_type_to_audio_attributes(*stream, &attributes); 641 } 642 sp<AudioOutputDescriptor> desc; 643 if (mPolicyMixes.getOutputForAttr(attributes, desc) == NO_ERROR) { 644 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr"); 645 if (!audio_is_linear_pcm(format)) { 646 return BAD_VALUE; 647 } 648 *stream = streamTypefromAttributesInt(&attributes); 649 *output = desc->mIoHandle; 650 ALOGV("getOutputForAttr() returns output %d", *output); 651 return NO_ERROR; 652 } 653 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) { 654 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE"); 655 return BAD_VALUE; 656 } 657 658 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x", 659 attributes.usage, attributes.content_type, attributes.tags, attributes.flags); 660 661 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes); 662 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/); 663 664 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) { 665 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC); 666 } 667 668 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x", 669 device, samplingRate, format, channelMask, flags); 670 671 *stream = streamTypefromAttributesInt(&attributes); 672 *output = getOutputForDevice(device, session, *stream, 673 samplingRate, format, channelMask, 674 flags, offloadInfo); 675 if (*output == AUDIO_IO_HANDLE_NONE) { 676 return INVALID_OPERATION; 677 } 678 return NO_ERROR; 679} 680 681audio_io_handle_t AudioPolicyManager::getOutputForDevice( 682 audio_devices_t device, 683 audio_session_t session __unused, 684 audio_stream_type_t stream, 685 uint32_t samplingRate, 686 audio_format_t format, 687 audio_channel_mask_t channelMask, 688 audio_output_flags_t flags, 689 const audio_offload_info_t *offloadInfo) 690{ 691 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE; 692 uint32_t latency = 0; 693 status_t status; 694 695#ifdef AUDIO_POLICY_TEST 696 if (mCurOutput != 0) { 697 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d", 698 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput); 699 700 if (mTestOutputs[mCurOutput] == 0) { 701 ALOGV("getOutput() opening test output"); 702 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL); 703 outputDesc->mDevice = mTestDevice; 704 outputDesc->mLatency = mTestLatencyMs; 705 outputDesc->mFlags = 706 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0); 707 outputDesc->mRefCount[stream] = 0; 708 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 709 config.sample_rate = mTestSamplingRate; 710 config.channel_mask = mTestChannels; 711 config.format = mTestFormat; 712 if (offloadInfo != NULL) { 713 config.offload_info = *offloadInfo; 714 } 715 status = mpClientInterface->openOutput(0, 716 &mTestOutputs[mCurOutput], 717 &config, 718 &outputDesc->mDevice, 719 String8(""), 720 &outputDesc->mLatency, 721 outputDesc->mFlags); 722 if (status == NO_ERROR) { 723 outputDesc->mSamplingRate = config.sample_rate; 724 outputDesc->mFormat = config.format; 725 outputDesc->mChannelMask = config.channel_mask; 726 AudioParameter outputCmd = AudioParameter(); 727 outputCmd.addInt(String8("set_id"),mCurOutput); 728 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString()); 729 addOutput(mTestOutputs[mCurOutput], outputDesc); 730 } 731 } 732 return mTestOutputs[mCurOutput]; 733 } 734#endif //AUDIO_POLICY_TEST 735 736 // open a direct output if required by specified parameters 737 //force direct flag if offload flag is set: offloading implies a direct output stream 738 // and all common behaviors are driven by checking only the direct flag 739 // this should normally be set appropriately in the policy configuration file 740 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) { 741 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT); 742 } 743 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) { 744 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT); 745 } 746 // only allow deep buffering for music stream type 747 if (stream != AUDIO_STREAM_MUSIC) { 748 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER); 749 } 750 751 sp<IOProfile> profile; 752 753 // skip direct output selection if the request can obviously be attached to a mixed output 754 // and not explicitly requested 755 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && 756 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE && 757 audio_channel_count_from_out_mask(channelMask) <= 2) { 758 goto non_direct_output; 759 } 760 761 // Do not allow offloading if one non offloadable effect is enabled. This prevents from 762 // creating an offloaded track and tearing it down immediately after start when audioflinger 763 // detects there is an active non offloadable effect. 764 // FIXME: We should check the audio session here but we do not have it in this context. 765 // This may prevent offloading in rare situations where effects are left active by apps 766 // in the background. 767 768 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) || 769 !mEffects.isNonOffloadableEffectEnabled()) { 770 profile = getProfileForDirectOutput(device, 771 samplingRate, 772 format, 773 channelMask, 774 (audio_output_flags_t)flags); 775 } 776 777 if (profile != 0) { 778 sp<AudioOutputDescriptor> outputDesc = NULL; 779 780 for (size_t i = 0; i < mOutputs.size(); i++) { 781 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 782 if (!desc->isDuplicated() && (profile == desc->mProfile)) { 783 outputDesc = desc; 784 // reuse direct output if currently open and configured with same parameters 785 if ((samplingRate == outputDesc->mSamplingRate) && 786 (format == outputDesc->mFormat) && 787 (channelMask == outputDesc->mChannelMask)) { 788 outputDesc->mDirectOpenCount++; 789 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i)); 790 return mOutputs.keyAt(i); 791 } 792 } 793 } 794 // close direct output if currently open and configured with different parameters 795 if (outputDesc != NULL) { 796 closeOutput(outputDesc->mIoHandle); 797 } 798 outputDesc = new AudioOutputDescriptor(profile); 799 outputDesc->mDevice = device; 800 outputDesc->mLatency = 0; 801 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags); 802 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 803 config.sample_rate = samplingRate; 804 config.channel_mask = channelMask; 805 config.format = format; 806 if (offloadInfo != NULL) { 807 config.offload_info = *offloadInfo; 808 } 809 status = mpClientInterface->openOutput(profile->mModule->mHandle, 810 &output, 811 &config, 812 &outputDesc->mDevice, 813 String8(""), 814 &outputDesc->mLatency, 815 outputDesc->mFlags); 816 817 // only accept an output with the requested parameters 818 if (status != NO_ERROR || 819 (samplingRate != 0 && samplingRate != config.sample_rate) || 820 (format != AUDIO_FORMAT_DEFAULT && format != config.format) || 821 (channelMask != 0 && channelMask != config.channel_mask)) { 822 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d," 823 "format %d %d, channelMask %04x %04x", output, samplingRate, 824 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask, 825 outputDesc->mChannelMask); 826 if (output != AUDIO_IO_HANDLE_NONE) { 827 mpClientInterface->closeOutput(output); 828 } 829 // fall back to mixer output if possible when the direct output could not be open 830 if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE) { 831 goto non_direct_output; 832 } 833 // fall back to mixer output if possible when the direct output could not be open 834 if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE) { 835 goto non_direct_output; 836 } 837 return AUDIO_IO_HANDLE_NONE; 838 } 839 outputDesc->mSamplingRate = config.sample_rate; 840 outputDesc->mChannelMask = config.channel_mask; 841 outputDesc->mFormat = config.format; 842 outputDesc->mRefCount[stream] = 0; 843 outputDesc->mStopTime[stream] = 0; 844 outputDesc->mDirectOpenCount = 1; 845 846 audio_io_handle_t srcOutput = getOutputForEffect(); 847 addOutput(output, outputDesc); 848 audio_io_handle_t dstOutput = getOutputForEffect(); 849 if (dstOutput == output) { 850 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput); 851 } 852 mPreviousOutputs = mOutputs; 853 ALOGV("getOutput() returns new direct output %d", output); 854 mpClientInterface->onAudioPortListUpdate(); 855 return output; 856 } 857 858non_direct_output: 859 860 // ignoring channel mask due to downmix capability in mixer 861 862 // open a non direct output 863 864 // for non direct outputs, only PCM is supported 865 if (audio_is_linear_pcm(format)) { 866 // get which output is suitable for the specified stream. The actual 867 // routing change will happen when startOutput() will be called 868 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs); 869 870 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier 871 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT); 872 output = selectOutput(outputs, flags, format); 873 } 874 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d," 875 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags); 876 877 ALOGV("getOutput() returns output %d", output); 878 879 return output; 880} 881 882audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs, 883 audio_output_flags_t flags, 884 audio_format_t format) 885{ 886 // select one output among several that provide a path to a particular device or set of 887 // devices (the list was previously build by getOutputsForDevice()). 888 // The priority is as follows: 889 // 1: the output with the highest number of requested policy flags 890 // 2: the primary output 891 // 3: the first output in the list 892 893 if (outputs.size() == 0) { 894 return 0; 895 } 896 if (outputs.size() == 1) { 897 return outputs[0]; 898 } 899 900 int maxCommonFlags = 0; 901 audio_io_handle_t outputFlags = 0; 902 audio_io_handle_t outputPrimary = 0; 903 904 for (size_t i = 0; i < outputs.size(); i++) { 905 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]); 906 if (!outputDesc->isDuplicated()) { 907 // if a valid format is specified, skip output if not compatible 908 if (format != AUDIO_FORMAT_INVALID) { 909 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) { 910 if (format != outputDesc->mFormat) { 911 continue; 912 } 913 } else if (!audio_is_linear_pcm(format)) { 914 continue; 915 } 916 } 917 918 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags); 919 if (commonFlags > maxCommonFlags) { 920 outputFlags = outputs[i]; 921 maxCommonFlags = commonFlags; 922 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags); 923 } 924 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) { 925 outputPrimary = outputs[i]; 926 } 927 } 928 } 929 930 if (outputFlags != 0) { 931 return outputFlags; 932 } 933 if (outputPrimary != 0) { 934 return outputPrimary; 935 } 936 937 return outputs[0]; 938} 939 940status_t AudioPolicyManager::startOutput(audio_io_handle_t output, 941 audio_stream_type_t stream, 942 audio_session_t session) 943{ 944 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session); 945 ssize_t index = mOutputs.indexOfKey(output); 946 if (index < 0) { 947 ALOGW("startOutput() unknown output %d", output); 948 return BAD_VALUE; 949 } 950 951 // cannot start playback of STREAM_TTS if any other output is being used 952 uint32_t beaconMuteLatency = 0; 953 if (stream == AUDIO_STREAM_TTS) { 954 ALOGV("\t found BEACON stream"); 955 if (mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) { 956 return INVALID_OPERATION; 957 } else { 958 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON); 959 } 960 } else { 961 // some playback other than beacon starts 962 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT); 963 } 964 965 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index); 966 967 // increment usage count for this stream on the requested output: 968 // NOTE that the usage count is the same for duplicated output and hardware output which is 969 // necessary for a correct control of hardware output routing by startOutput() and stopOutput() 970 outputDesc->changeRefCount(stream, 1); 971 972 if (outputDesc->mRefCount[stream] == 1) { 973 // starting an output being rerouted? 974 audio_devices_t newDevice; 975 if (outputDesc->mPolicyMix != NULL) { 976 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX; 977 } else { 978 newDevice = getNewOutputDevice(output, false /*fromCache*/); 979 } 980 routing_strategy strategy = getStrategy(stream); 981 bool shouldWait = (strategy == STRATEGY_SONIFICATION) || 982 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) || 983 (beaconMuteLatency > 0); 984 uint32_t waitMs = beaconMuteLatency; 985 bool force = false; 986 for (size_t i = 0; i < mOutputs.size(); i++) { 987 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 988 if (desc != outputDesc) { 989 // force a device change if any other output is managed by the same hw 990 // module and has a current device selection that differs from selected device. 991 // In this case, the audio HAL must receive the new device selection so that it can 992 // change the device currently selected by the other active output. 993 if (outputDesc->sharesHwModuleWith(desc) && 994 desc->device() != newDevice) { 995 force = true; 996 } 997 // wait for audio on other active outputs to be presented when starting 998 // a notification so that audio focus effect can propagate, or that a mute/unmute 999 // event occurred for beacon 1000 uint32_t latency = desc->latency(); 1001 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) { 1002 waitMs = latency; 1003 } 1004 } 1005 } 1006 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force); 1007 1008 // handle special case for sonification while in call 1009 if (isInCall()) { 1010 handleIncallSonification(stream, true, false); 1011 } 1012 1013 // apply volume rules for current stream and device if necessary 1014 checkAndSetVolume(stream, 1015 mStreams[stream].getVolumeIndex(newDevice), 1016 output, 1017 newDevice); 1018 1019 // update the outputs if starting an output with a stream that can affect notification 1020 // routing 1021 handleNotificationRoutingForStream(stream); 1022 1023 // Automatically enable the remote submix input when output is started on a re routing mix 1024 // of type MIX_TYPE_RECORDERS 1025 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL && 1026 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) { 1027 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX, 1028 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, 1029 outputDesc->mPolicyMix->mRegistrationId, 1030 "remote-submix"); 1031 } 1032 1033 // force reevaluating accessibility routing when ringtone or alarm starts 1034 if (strategy == STRATEGY_SONIFICATION) { 1035 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY); 1036 } 1037 1038 if (waitMs > muteWaitMs) { 1039 usleep((waitMs - muteWaitMs) * 2 * 1000); 1040 } 1041 } 1042 return NO_ERROR; 1043} 1044 1045 1046status_t AudioPolicyManager::stopOutput(audio_io_handle_t output, 1047 audio_stream_type_t stream, 1048 audio_session_t session) 1049{ 1050 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session); 1051 ssize_t index = mOutputs.indexOfKey(output); 1052 if (index < 0) { 1053 ALOGW("stopOutput() unknown output %d", output); 1054 return BAD_VALUE; 1055 } 1056 1057 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index); 1058 1059 // always handle stream stop, check which stream type is stopping 1060 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT); 1061 1062 // handle special case for sonification while in call 1063 if (isInCall()) { 1064 handleIncallSonification(stream, false, false); 1065 } 1066 1067 if (outputDesc->mRefCount[stream] > 0) { 1068 // decrement usage count of this stream on the output 1069 outputDesc->changeRefCount(stream, -1); 1070 // store time at which the stream was stopped - see isStreamActive() 1071 if (outputDesc->mRefCount[stream] == 0) { 1072 // Automatically disable the remote submix input when output is stopped on a 1073 // re routing mix of type MIX_TYPE_RECORDERS 1074 if (audio_is_remote_submix_device(outputDesc->mDevice) && 1075 outputDesc->mPolicyMix != NULL && 1076 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) { 1077 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX, 1078 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, 1079 outputDesc->mPolicyMix->mRegistrationId, 1080 "remote-submix"); 1081 } 1082 1083 outputDesc->mStopTime[stream] = systemTime(); 1084 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/); 1085 // delay the device switch by twice the latency because stopOutput() is executed when 1086 // the track stop() command is received and at that time the audio track buffer can 1087 // still contain data that needs to be drained. The latency only covers the audio HAL 1088 // and kernel buffers. Also the latency does not always include additional delay in the 1089 // audio path (audio DSP, CODEC ...) 1090 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2); 1091 1092 // force restoring the device selection on other active outputs if it differs from the 1093 // one being selected for this output 1094 for (size_t i = 0; i < mOutputs.size(); i++) { 1095 audio_io_handle_t curOutput = mOutputs.keyAt(i); 1096 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 1097 if (curOutput != output && 1098 desc->isActive() && 1099 outputDesc->sharesHwModuleWith(desc) && 1100 (newDevice != desc->device())) { 1101 setOutputDevice(curOutput, 1102 getNewOutputDevice(curOutput, false /*fromCache*/), 1103 true, 1104 outputDesc->mLatency*2); 1105 } 1106 } 1107 // update the outputs if stopping one with a stream that can affect notification routing 1108 handleNotificationRoutingForStream(stream); 1109 } 1110 return NO_ERROR; 1111 } else { 1112 ALOGW("stopOutput() refcount is already 0 for output %d", output); 1113 return INVALID_OPERATION; 1114 } 1115} 1116 1117void AudioPolicyManager::releaseOutput(audio_io_handle_t output, 1118 audio_stream_type_t stream __unused, 1119 audio_session_t session __unused) 1120{ 1121 ALOGV("releaseOutput() %d", output); 1122 ssize_t index = mOutputs.indexOfKey(output); 1123 if (index < 0) { 1124 ALOGW("releaseOutput() releasing unknown output %d", output); 1125 return; 1126 } 1127 1128#ifdef AUDIO_POLICY_TEST 1129 int testIndex = testOutputIndex(output); 1130 if (testIndex != 0) { 1131 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index); 1132 if (outputDesc->isActive()) { 1133 mpClientInterface->closeOutput(output); 1134 removeOutput(output); 1135 mTestOutputs[testIndex] = 0; 1136 } 1137 return; 1138 } 1139#endif //AUDIO_POLICY_TEST 1140 1141 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index); 1142 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) { 1143 if (desc->mDirectOpenCount <= 0) { 1144 ALOGW("releaseOutput() invalid open count %d for output %d", 1145 desc->mDirectOpenCount, output); 1146 return; 1147 } 1148 if (--desc->mDirectOpenCount == 0) { 1149 closeOutput(output); 1150 // If effects where present on the output, audioflinger moved them to the primary 1151 // output by default: move them back to the appropriate output. 1152 audio_io_handle_t dstOutput = getOutputForEffect(); 1153 if (dstOutput != mPrimaryOutput) { 1154 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput); 1155 } 1156 mpClientInterface->onAudioPortListUpdate(); 1157 } 1158 } 1159} 1160 1161 1162status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr, 1163 audio_io_handle_t *input, 1164 audio_session_t session, 1165 uint32_t samplingRate, 1166 audio_format_t format, 1167 audio_channel_mask_t channelMask, 1168 audio_input_flags_t flags, 1169 input_type_t *inputType) 1170{ 1171 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x," 1172 "session %d, flags %#x", 1173 attr->source, samplingRate, format, channelMask, session, flags); 1174 1175 *input = AUDIO_IO_HANDLE_NONE; 1176 *inputType = API_INPUT_INVALID; 1177 audio_devices_t device; 1178 // handle legacy remote submix case where the address was not always specified 1179 String8 address = String8(""); 1180 bool isSoundTrigger = false; 1181 audio_source_t inputSource = attr->source; 1182 audio_source_t halInputSource; 1183 AudioMix *policyMix = NULL; 1184 1185 if (inputSource == AUDIO_SOURCE_DEFAULT) { 1186 inputSource = AUDIO_SOURCE_MIC; 1187 } 1188 halInputSource = inputSource; 1189 1190 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX && 1191 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) { 1192 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix); 1193 if (ret != NO_ERROR) { 1194 return ret; 1195 } 1196 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE; 1197 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX; 1198 address = String8(attr->tags + strlen("addr=")); 1199 } else { 1200 device = getDeviceAndMixForInputSource(inputSource, &policyMix); 1201 if (device == AUDIO_DEVICE_NONE) { 1202 ALOGW("getInputForAttr() could not find device for source %d", inputSource); 1203 return BAD_VALUE; 1204 } 1205 if (policyMix != NULL) { 1206 address = policyMix->mRegistrationId; 1207 if (policyMix->mMixType == MIX_TYPE_RECORDERS) { 1208 // there is an external policy, but this input is attached to a mix of recorders, 1209 // meaning it receives audio injected into the framework, so the recorder doesn't 1210 // know about it and is therefore considered "legacy" 1211 *inputType = API_INPUT_LEGACY; 1212 } else { 1213 // recording a mix of players defined by an external policy, we're rerouting for 1214 // an external policy 1215 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE; 1216 } 1217 } else if (audio_is_remote_submix_device(device)) { 1218 address = String8("0"); 1219 *inputType = API_INPUT_MIX_CAPTURE; 1220 } else { 1221 *inputType = API_INPUT_LEGACY; 1222 } 1223 // adapt channel selection to input source 1224 switch (inputSource) { 1225 case AUDIO_SOURCE_VOICE_UPLINK: 1226 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK; 1227 break; 1228 case AUDIO_SOURCE_VOICE_DOWNLINK: 1229 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK; 1230 break; 1231 case AUDIO_SOURCE_VOICE_CALL: 1232 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK; 1233 break; 1234 default: 1235 break; 1236 } 1237 if (inputSource == AUDIO_SOURCE_HOTWORD) { 1238 ssize_t index = mSoundTriggerSessions.indexOfKey(session); 1239 if (index >= 0) { 1240 *input = mSoundTriggerSessions.valueFor(session); 1241 isSoundTrigger = true; 1242 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD); 1243 ALOGV("SoundTrigger capture on session %d input %d", session, *input); 1244 } else { 1245 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION; 1246 } 1247 } 1248 } 1249 1250 sp<IOProfile> profile = getInputProfile(device, address, 1251 samplingRate, format, channelMask, 1252 flags); 1253 if (profile == 0) { 1254 //retry without flags 1255 audio_input_flags_t log_flags = flags; 1256 flags = AUDIO_INPUT_FLAG_NONE; 1257 profile = getInputProfile(device, address, 1258 samplingRate, format, channelMask, 1259 flags); 1260 if (profile == 0) { 1261 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u," 1262 "format %#x, channelMask 0x%X, flags %#x", 1263 device, samplingRate, format, channelMask, log_flags); 1264 return BAD_VALUE; 1265 } 1266 } 1267 1268 if (profile->mModule->mHandle == 0) { 1269 ALOGE("getInputForAttr(): HW module %s not opened", profile->mModule->mName); 1270 return NO_INIT; 1271 } 1272 1273 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 1274 config.sample_rate = samplingRate; 1275 config.channel_mask = channelMask; 1276 config.format = format; 1277 1278 status_t status = mpClientInterface->openInput(profile->mModule->mHandle, 1279 input, 1280 &config, 1281 &device, 1282 address, 1283 halInputSource, 1284 flags); 1285 1286 // only accept input with the exact requested set of parameters 1287 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE || 1288 (samplingRate != config.sample_rate) || 1289 (format != config.format) || 1290 (channelMask != config.channel_mask)) { 1291 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d, channelMask %x", 1292 samplingRate, format, channelMask); 1293 if (*input != AUDIO_IO_HANDLE_NONE) { 1294 mpClientInterface->closeInput(*input); 1295 } 1296 return BAD_VALUE; 1297 } 1298 1299 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile); 1300 inputDesc->mInputSource = inputSource; 1301 inputDesc->mRefCount = 0; 1302 inputDesc->mOpenRefCount = 1; 1303 inputDesc->mSamplingRate = samplingRate; 1304 inputDesc->mFormat = format; 1305 inputDesc->mChannelMask = channelMask; 1306 inputDesc->mDevice = device; 1307 inputDesc->mSessions.add(session); 1308 inputDesc->mIsSoundTrigger = isSoundTrigger; 1309 inputDesc->mPolicyMix = policyMix; 1310 1311 ALOGV("getInputForAttr() returns input type = %d", *inputType); 1312 1313 addInput(*input, inputDesc); 1314 mpClientInterface->onAudioPortListUpdate(); 1315 return NO_ERROR; 1316} 1317 1318status_t AudioPolicyManager::startInput(audio_io_handle_t input, 1319 audio_session_t session) 1320{ 1321 ALOGV("startInput() input %d", input); 1322 ssize_t index = mInputs.indexOfKey(input); 1323 if (index < 0) { 1324 ALOGW("startInput() unknown input %d", input); 1325 return BAD_VALUE; 1326 } 1327 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index); 1328 1329 index = inputDesc->mSessions.indexOf(session); 1330 if (index < 0) { 1331 ALOGW("startInput() unknown session %d on input %d", session, input); 1332 return BAD_VALUE; 1333 } 1334 1335 // virtual input devices are compatible with other input devices 1336 if (!is_virtual_input_device(inputDesc->mDevice)) { 1337 1338 // for a non-virtual input device, check if there is another (non-virtual) active input 1339 audio_io_handle_t activeInput = mInputs.getActiveInput(); 1340 if (activeInput != 0 && activeInput != input) { 1341 1342 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed, 1343 // otherwise the active input continues and the new input cannot be started. 1344 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput); 1345 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) { 1346 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput); 1347 stopInput(activeInput, activeDesc->mSessions.itemAt(0)); 1348 releaseInput(activeInput, activeDesc->mSessions.itemAt(0)); 1349 } else { 1350 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput); 1351 return INVALID_OPERATION; 1352 } 1353 } 1354 } 1355 1356 if (inputDesc->mRefCount == 0) { 1357 if (mInputs.activeInputsCount() == 0) { 1358 SoundTrigger::setCaptureState(true); 1359 } 1360 setInputDevice(input, getNewInputDevice(input), true /* force */); 1361 1362 // automatically enable the remote submix output when input is started if not 1363 // used by a policy mix of type MIX_TYPE_RECORDERS 1364 // For remote submix (a virtual device), we open only one input per capture request. 1365 if (audio_is_remote_submix_device(inputDesc->mDevice)) { 1366 String8 address = String8(""); 1367 if (inputDesc->mPolicyMix == NULL) { 1368 address = String8("0"); 1369 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) { 1370 address = inputDesc->mPolicyMix->mRegistrationId; 1371 } 1372 if (address != "") { 1373 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, 1374 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, 1375 address, "remote-submix"); 1376 } 1377 } 1378 } 1379 1380 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource); 1381 1382 inputDesc->mRefCount++; 1383 return NO_ERROR; 1384} 1385 1386status_t AudioPolicyManager::stopInput(audio_io_handle_t input, 1387 audio_session_t session) 1388{ 1389 ALOGV("stopInput() input %d", input); 1390 ssize_t index = mInputs.indexOfKey(input); 1391 if (index < 0) { 1392 ALOGW("stopInput() unknown input %d", input); 1393 return BAD_VALUE; 1394 } 1395 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index); 1396 1397 index = inputDesc->mSessions.indexOf(session); 1398 if (index < 0) { 1399 ALOGW("stopInput() unknown session %d on input %d", session, input); 1400 return BAD_VALUE; 1401 } 1402 1403 if (inputDesc->mRefCount == 0) { 1404 ALOGW("stopInput() input %d already stopped", input); 1405 return INVALID_OPERATION; 1406 } 1407 1408 inputDesc->mRefCount--; 1409 if (inputDesc->mRefCount == 0) { 1410 1411 // automatically disable the remote submix output when input is stopped if not 1412 // used by a policy mix of type MIX_TYPE_RECORDERS 1413 if (audio_is_remote_submix_device(inputDesc->mDevice)) { 1414 String8 address = String8(""); 1415 if (inputDesc->mPolicyMix == NULL) { 1416 address = String8("0"); 1417 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) { 1418 address = inputDesc->mPolicyMix->mRegistrationId; 1419 } 1420 if (address != "") { 1421 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, 1422 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, 1423 address, "remote-submix"); 1424 } 1425 } 1426 1427 resetInputDevice(input); 1428 1429 if (mInputs.activeInputsCount() == 0) { 1430 SoundTrigger::setCaptureState(false); 1431 } 1432 } 1433 return NO_ERROR; 1434} 1435 1436void AudioPolicyManager::releaseInput(audio_io_handle_t input, 1437 audio_session_t session) 1438{ 1439 ALOGV("releaseInput() %d", input); 1440 ssize_t index = mInputs.indexOfKey(input); 1441 if (index < 0) { 1442 ALOGW("releaseInput() releasing unknown input %d", input); 1443 return; 1444 } 1445 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index); 1446 ALOG_ASSERT(inputDesc != 0); 1447 1448 index = inputDesc->mSessions.indexOf(session); 1449 if (index < 0) { 1450 ALOGW("releaseInput() unknown session %d on input %d", session, input); 1451 return; 1452 } 1453 inputDesc->mSessions.remove(session); 1454 if (inputDesc->mOpenRefCount == 0) { 1455 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount); 1456 return; 1457 } 1458 inputDesc->mOpenRefCount--; 1459 if (inputDesc->mOpenRefCount > 0) { 1460 ALOGV("releaseInput() exit > 0"); 1461 return; 1462 } 1463 1464 closeInput(input); 1465 mpClientInterface->onAudioPortListUpdate(); 1466 ALOGV("releaseInput() exit"); 1467} 1468 1469void AudioPolicyManager::closeAllInputs() { 1470 bool patchRemoved = false; 1471 1472 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) { 1473 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index); 1474 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle); 1475 if (patch_index >= 0) { 1476 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index); 1477 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 1478 mAudioPatches.removeItemsAt(patch_index); 1479 patchRemoved = true; 1480 } 1481 mpClientInterface->closeInput(mInputs.keyAt(input_index)); 1482 } 1483 mInputs.clear(); 1484 nextAudioPortGeneration(); 1485 1486 if (patchRemoved) { 1487 mpClientInterface->onAudioPatchListUpdate(); 1488 } 1489} 1490 1491void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, 1492 int indexMin, 1493 int indexMax) 1494{ 1495 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax); 1496 mEngine->initStreamVolume(stream, indexMin, indexMax); 1497 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now 1498 if (stream == AUDIO_STREAM_MUSIC) { 1499 mEngine->initStreamVolume(AUDIO_STREAM_ACCESSIBILITY, indexMin, indexMax); 1500 } 1501} 1502 1503status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream, 1504 int index, 1505 audio_devices_t device) 1506{ 1507 1508 if ((index < mStreams[stream].getVolumeIndexMin()) || 1509 (index > mStreams[stream].getVolumeIndexMax())) { 1510 return BAD_VALUE; 1511 } 1512 if (!audio_is_output_device(device)) { 1513 return BAD_VALUE; 1514 } 1515 1516 // Force max volume if stream cannot be muted 1517 if (!mStreams.canBeMuted(stream)) index = mStreams[stream].getVolumeIndexMax(); 1518 1519 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d", 1520 stream, device, index); 1521 1522 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and 1523 // clear all device specific values 1524 if (device == AUDIO_DEVICE_OUT_DEFAULT) { 1525 mStreams.clearCurrentVolumeIndex(stream); 1526 } 1527 mStreams.addCurrentVolumeIndex(stream, device, index); 1528 1529 // update volume on all outputs whose current device is also selected by the same 1530 // strategy as the device specified by the caller 1531 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/); 1532 1533 1534 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now 1535 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE; 1536 if (stream == AUDIO_STREAM_MUSIC) { 1537 mStreams.addCurrentVolumeIndex(AUDIO_STREAM_ACCESSIBILITY, device, index); 1538 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/); 1539 } 1540 if ((device != AUDIO_DEVICE_OUT_DEFAULT) && 1541 (device & (strategyDevice | accessibilityDevice)) == 0) { 1542 return NO_ERROR; 1543 } 1544 status_t status = NO_ERROR; 1545 for (size_t i = 0; i < mOutputs.size(); i++) { 1546 audio_devices_t curDevice = Volume::getDeviceForVolume(mOutputs.valueAt(i)->device()); 1547 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) { 1548 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice); 1549 if (volStatus != NO_ERROR) { 1550 status = volStatus; 1551 } 1552 } 1553 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) { 1554 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY, 1555 index, mOutputs.keyAt(i), curDevice); 1556 } 1557 } 1558 return status; 1559} 1560 1561status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream, 1562 int *index, 1563 audio_devices_t device) 1564{ 1565 if (index == NULL) { 1566 return BAD_VALUE; 1567 } 1568 if (!audio_is_output_device(device)) { 1569 return BAD_VALUE; 1570 } 1571 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to 1572 // the strategy the stream belongs to. 1573 if (device == AUDIO_DEVICE_OUT_DEFAULT) { 1574 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/); 1575 } 1576 device = Volume::getDeviceForVolume(device); 1577 1578 *index = mStreams[stream].getVolumeIndex(device); 1579 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index); 1580 return NO_ERROR; 1581} 1582 1583audio_io_handle_t AudioPolicyManager::selectOutputForEffects( 1584 const SortedVector<audio_io_handle_t>& outputs) 1585{ 1586 // select one output among several suitable for global effects. 1587 // The priority is as follows: 1588 // 1: An offloaded output. If the effect ends up not being offloadable, 1589 // AudioFlinger will invalidate the track and the offloaded output 1590 // will be closed causing the effect to be moved to a PCM output. 1591 // 2: A deep buffer output 1592 // 3: the first output in the list 1593 1594 if (outputs.size() == 0) { 1595 return 0; 1596 } 1597 1598 audio_io_handle_t outputOffloaded = 0; 1599 audio_io_handle_t outputDeepBuffer = 0; 1600 1601 for (size_t i = 0; i < outputs.size(); i++) { 1602 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]); 1603 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags); 1604 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) { 1605 outputOffloaded = outputs[i]; 1606 } 1607 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) { 1608 outputDeepBuffer = outputs[i]; 1609 } 1610 } 1611 1612 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d", 1613 outputOffloaded, outputDeepBuffer); 1614 if (outputOffloaded != 0) { 1615 return outputOffloaded; 1616 } 1617 if (outputDeepBuffer != 0) { 1618 return outputDeepBuffer; 1619 } 1620 1621 return outputs[0]; 1622} 1623 1624audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc) 1625{ 1626 // apply simple rule where global effects are attached to the same output as MUSIC streams 1627 1628 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC); 1629 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/); 1630 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs); 1631 1632 audio_io_handle_t output = selectOutputForEffects(dstOutputs); 1633 ALOGV("getOutputForEffect() got output %d for fx %s flags %x", 1634 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags); 1635 1636 return output; 1637} 1638 1639status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc, 1640 audio_io_handle_t io, 1641 uint32_t strategy, 1642 int session, 1643 int id) 1644{ 1645 ssize_t index = mOutputs.indexOfKey(io); 1646 if (index < 0) { 1647 index = mInputs.indexOfKey(io); 1648 if (index < 0) { 1649 ALOGW("registerEffect() unknown io %d", io); 1650 return INVALID_OPERATION; 1651 } 1652 } 1653 return mEffects.registerEffect(desc, io, strategy, session, id); 1654} 1655 1656bool AudioPolicyManager::isSourceActive(audio_source_t source) const 1657{ 1658 for (size_t i = 0; i < mInputs.size(); i++) { 1659 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i); 1660 if (inputDescriptor->mRefCount == 0) { 1661 continue; 1662 } 1663 if (inputDescriptor->mInputSource == (int)source) { 1664 return true; 1665 } 1666 // AUDIO_SOURCE_HOTWORD is equivalent to AUDIO_SOURCE_VOICE_RECOGNITION only if it 1667 // corresponds to an active capture triggered by a hardware hotword recognition 1668 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) && 1669 (inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD)) { 1670 // FIXME: we should not assume that the first session is the active one and keep 1671 // activity count per session. Same in startInput(). 1672 ssize_t index = mSoundTriggerSessions.indexOfKey(inputDescriptor->mSessions.itemAt(0)); 1673 if (index >= 0) { 1674 return true; 1675 } 1676 } 1677 } 1678 return false; 1679} 1680 1681// Register a list of custom mixes with their attributes and format. 1682// When a mix is registered, corresponding input and output profiles are 1683// added to the remote submix hw module. The profile contains only the 1684// parameters (sampling rate, format...) specified by the mix. 1685// The corresponding input remote submix device is also connected. 1686// 1687// When a remote submix device is connected, the address is checked to select the 1688// appropriate profile and the corresponding input or output stream is opened. 1689// 1690// When capture starts, getInputForAttr() will: 1691// - 1 look for a mix matching the address passed in attribtutes tags if any 1692// - 2 if none found, getDeviceForInputSource() will: 1693// - 2.1 look for a mix matching the attributes source 1694// - 2.2 if none found, default to device selection by policy rules 1695// At this time, the corresponding output remote submix device is also connected 1696// and active playback use cases can be transferred to this mix if needed when reconnecting 1697// after AudioTracks are invalidated 1698// 1699// When playback starts, getOutputForAttr() will: 1700// - 1 look for a mix matching the address passed in attribtutes tags if any 1701// - 2 if none found, look for a mix matching the attributes usage 1702// - 3 if none found, default to device and output selection by policy rules. 1703 1704status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes) 1705{ 1706 sp<HwModule> module; 1707 for (size_t i = 0; i < mHwModules.size(); i++) { 1708 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 && 1709 mHwModules[i]->mHandle != 0) { 1710 module = mHwModules[i]; 1711 break; 1712 } 1713 } 1714 1715 if (module == 0) { 1716 return INVALID_OPERATION; 1717 } 1718 1719 ALOGV("registerPolicyMixes() num mixes %d", mixes.size()); 1720 1721 for (size_t i = 0; i < mixes.size(); i++) { 1722 String8 address = mixes[i].mRegistrationId; 1723 1724 if (mPolicyMixes.registerMix(address, mixes[i]) != NO_ERROR) { 1725 continue; 1726 } 1727 audio_config_t outputConfig = mixes[i].mFormat; 1728 audio_config_t inputConfig = mixes[i].mFormat; 1729 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in 1730 // stereo and let audio flinger do the channel conversion if needed. 1731 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO; 1732 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO; 1733 module->addOutputProfile(address, &outputConfig, 1734 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address); 1735 module->addInputProfile(address, &inputConfig, 1736 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address); 1737 1738 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) { 1739 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX, 1740 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, 1741 address.string(), "remote-submix"); 1742 } else { 1743 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, 1744 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, 1745 address.string(), "remote-submix"); 1746 } 1747 } 1748 return NO_ERROR; 1749} 1750 1751status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes) 1752{ 1753 sp<HwModule> module; 1754 for (size_t i = 0; i < mHwModules.size(); i++) { 1755 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 && 1756 mHwModules[i]->mHandle != 0) { 1757 module = mHwModules[i]; 1758 break; 1759 } 1760 } 1761 1762 if (module == 0) { 1763 return INVALID_OPERATION; 1764 } 1765 1766 ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size()); 1767 1768 for (size_t i = 0; i < mixes.size(); i++) { 1769 String8 address = mixes[i].mRegistrationId; 1770 1771 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) { 1772 continue; 1773 } 1774 1775 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) == 1776 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) 1777 { 1778 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX, 1779 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, 1780 address.string(), "remote-submix"); 1781 } 1782 1783 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) == 1784 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) 1785 { 1786 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, 1787 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, 1788 address.string(), "remote-submix"); 1789 } 1790 module->removeOutputProfile(address); 1791 module->removeInputProfile(address); 1792 } 1793 return NO_ERROR; 1794} 1795 1796 1797status_t AudioPolicyManager::dump(int fd) 1798{ 1799 const size_t SIZE = 256; 1800 char buffer[SIZE]; 1801 String8 result; 1802 1803 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this); 1804 result.append(buffer); 1805 1806 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput); 1807 result.append(buffer); 1808 snprintf(buffer, SIZE, " Phone state: %d\n", mEngine->getPhoneState()); 1809 result.append(buffer); 1810 snprintf(buffer, SIZE, " Force use for communications %d\n", 1811 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION)); 1812 result.append(buffer); 1813 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA)); 1814 result.append(buffer); 1815 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD)); 1816 result.append(buffer); 1817 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK)); 1818 result.append(buffer); 1819 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM)); 1820 result.append(buffer); 1821 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n", 1822 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO)); 1823 result.append(buffer); 1824 write(fd, result.string(), result.size()); 1825 1826 mAvailableOutputDevices.dump(fd, String8("output")); 1827 mAvailableInputDevices.dump(fd, String8("input")); 1828 mHwModules.dump(fd); 1829 mOutputs.dump(fd); 1830 mInputs.dump(fd); 1831 mStreams.dump(fd); 1832 mEffects.dump(fd); 1833 mAudioPatches.dump(fd); 1834 1835 return NO_ERROR; 1836} 1837 1838// This function checks for the parameters which can be offloaded. 1839// This can be enhanced depending on the capability of the DSP and policy 1840// of the system. 1841bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo) 1842{ 1843 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d," 1844 " BitRate=%u, duration=%" PRId64 " us, has_video=%d", 1845 offloadInfo.sample_rate, offloadInfo.channel_mask, 1846 offloadInfo.format, 1847 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us, 1848 offloadInfo.has_video); 1849 1850 // Check if offload has been disabled 1851 char propValue[PROPERTY_VALUE_MAX]; 1852 if (property_get("audio.offload.disable", propValue, "0")) { 1853 if (atoi(propValue) != 0) { 1854 ALOGV("offload disabled by audio.offload.disable=%s", propValue ); 1855 return false; 1856 } 1857 } 1858 1859 // Check if stream type is music, then only allow offload as of now. 1860 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC) 1861 { 1862 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false"); 1863 return false; 1864 } 1865 1866 //TODO: enable audio offloading with video when ready 1867 if (offloadInfo.has_video) 1868 { 1869 ALOGV("isOffloadSupported: has_video == true, returning false"); 1870 return false; 1871 } 1872 1873 //If duration is less than minimum value defined in property, return false 1874 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) { 1875 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) { 1876 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue); 1877 return false; 1878 } 1879 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) { 1880 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS); 1881 return false; 1882 } 1883 1884 // Do not allow offloading if one non offloadable effect is enabled. This prevents from 1885 // creating an offloaded track and tearing it down immediately after start when audioflinger 1886 // detects there is an active non offloadable effect. 1887 // FIXME: We should check the audio session here but we do not have it in this context. 1888 // This may prevent offloading in rare situations where effects are left active by apps 1889 // in the background. 1890 if (mEffects.isNonOffloadableEffectEnabled()) { 1891 return false; 1892 } 1893 1894 // See if there is a profile to support this. 1895 // AUDIO_DEVICE_NONE 1896 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */, 1897 offloadInfo.sample_rate, 1898 offloadInfo.format, 1899 offloadInfo.channel_mask, 1900 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD); 1901 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT "); 1902 return (profile != 0); 1903} 1904 1905status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role, 1906 audio_port_type_t type, 1907 unsigned int *num_ports, 1908 struct audio_port *ports, 1909 unsigned int *generation) 1910{ 1911 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) || 1912 generation == NULL) { 1913 return BAD_VALUE; 1914 } 1915 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports); 1916 if (ports == NULL) { 1917 *num_ports = 0; 1918 } 1919 1920 size_t portsWritten = 0; 1921 size_t portsMax = *num_ports; 1922 *num_ports = 0; 1923 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) { 1924 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) { 1925 for (size_t i = 0; 1926 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) { 1927 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]); 1928 } 1929 *num_ports += mAvailableOutputDevices.size(); 1930 } 1931 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) { 1932 for (size_t i = 0; 1933 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) { 1934 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]); 1935 } 1936 *num_ports += mAvailableInputDevices.size(); 1937 } 1938 } 1939 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) { 1940 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) { 1941 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) { 1942 mInputs[i]->toAudioPort(&ports[portsWritten++]); 1943 } 1944 *num_ports += mInputs.size(); 1945 } 1946 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) { 1947 size_t numOutputs = 0; 1948 for (size_t i = 0; i < mOutputs.size(); i++) { 1949 if (!mOutputs[i]->isDuplicated()) { 1950 numOutputs++; 1951 if (portsWritten < portsMax) { 1952 mOutputs[i]->toAudioPort(&ports[portsWritten++]); 1953 } 1954 } 1955 } 1956 *num_ports += numOutputs; 1957 } 1958 } 1959 *generation = curAudioPortGeneration(); 1960 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports); 1961 return NO_ERROR; 1962} 1963 1964status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused) 1965{ 1966 return NO_ERROR; 1967} 1968 1969status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch, 1970 audio_patch_handle_t *handle, 1971 uid_t uid) 1972{ 1973 ALOGV("createAudioPatch()"); 1974 1975 if (handle == NULL || patch == NULL) { 1976 return BAD_VALUE; 1977 } 1978 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks); 1979 1980 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX || 1981 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) { 1982 return BAD_VALUE; 1983 } 1984 // only one source per audio patch supported for now 1985 if (patch->num_sources > 1) { 1986 return INVALID_OPERATION; 1987 } 1988 1989 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) { 1990 return INVALID_OPERATION; 1991 } 1992 for (size_t i = 0; i < patch->num_sinks; i++) { 1993 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) { 1994 return INVALID_OPERATION; 1995 } 1996 } 1997 1998 sp<AudioPatch> patchDesc; 1999 ssize_t index = mAudioPatches.indexOfKey(*handle); 2000 2001 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id, 2002 patch->sources[0].role, 2003 patch->sources[0].type); 2004#if LOG_NDEBUG == 0 2005 for (size_t i = 0; i < patch->num_sinks; i++) { 2006 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id, 2007 patch->sinks[i].role, 2008 patch->sinks[i].type); 2009 } 2010#endif 2011 2012 if (index >= 0) { 2013 patchDesc = mAudioPatches.valueAt(index); 2014 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d", 2015 mUidCached, patchDesc->mUid, uid); 2016 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) { 2017 return INVALID_OPERATION; 2018 } 2019 } else { 2020 *handle = 0; 2021 } 2022 2023 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) { 2024 sp<AudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id); 2025 if (outputDesc == NULL) { 2026 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id); 2027 return BAD_VALUE; 2028 } 2029 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports", 2030 outputDesc->mIoHandle); 2031 if (patchDesc != 0) { 2032 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) { 2033 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d", 2034 patchDesc->mPatch.sources[0].id, patch->sources[0].id); 2035 return BAD_VALUE; 2036 } 2037 } 2038 DeviceVector devices; 2039 for (size_t i = 0; i < patch->num_sinks; i++) { 2040 // Only support mix to devices connection 2041 // TODO add support for mix to mix connection 2042 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) { 2043 ALOGV("createAudioPatch() source mix but sink is not a device"); 2044 return INVALID_OPERATION; 2045 } 2046 sp<DeviceDescriptor> devDesc = 2047 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id); 2048 if (devDesc == 0) { 2049 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id); 2050 return BAD_VALUE; 2051 } 2052 2053 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(), 2054 devDesc->mAddress, 2055 patch->sources[0].sample_rate, 2056 NULL, // updatedSamplingRate 2057 patch->sources[0].format, 2058 patch->sources[0].channel_mask, 2059 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) { 2060 ALOGV("createAudioPatch() profile not supported for device %08x", devDesc->type()); 2061 return INVALID_OPERATION; 2062 } 2063 devices.add(devDesc); 2064 } 2065 if (devices.size() == 0) { 2066 return INVALID_OPERATION; 2067 } 2068 2069 // TODO: reconfigure output format and channels here 2070 ALOGV("createAudioPatch() setting device %08x on output %d", 2071 devices.types(), outputDesc->mIoHandle); 2072 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle); 2073 index = mAudioPatches.indexOfKey(*handle); 2074 if (index >= 0) { 2075 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) { 2076 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided"); 2077 } 2078 patchDesc = mAudioPatches.valueAt(index); 2079 patchDesc->mUid = uid; 2080 ALOGV("createAudioPatch() success"); 2081 } else { 2082 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch"); 2083 return INVALID_OPERATION; 2084 } 2085 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) { 2086 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) { 2087 // input device to input mix connection 2088 // only one sink supported when connecting an input device to a mix 2089 if (patch->num_sinks > 1) { 2090 return INVALID_OPERATION; 2091 } 2092 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id); 2093 if (inputDesc == NULL) { 2094 return BAD_VALUE; 2095 } 2096 if (patchDesc != 0) { 2097 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) { 2098 return BAD_VALUE; 2099 } 2100 } 2101 sp<DeviceDescriptor> devDesc = 2102 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id); 2103 if (devDesc == 0) { 2104 return BAD_VALUE; 2105 } 2106 2107 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(), 2108 devDesc->mAddress, 2109 patch->sinks[0].sample_rate, 2110 NULL, /*updatedSampleRate*/ 2111 patch->sinks[0].format, 2112 patch->sinks[0].channel_mask, 2113 // FIXME for the parameter type, 2114 // and the NONE 2115 (audio_output_flags_t) 2116 AUDIO_INPUT_FLAG_NONE)) { 2117 return INVALID_OPERATION; 2118 } 2119 // TODO: reconfigure output format and channels here 2120 ALOGV("createAudioPatch() setting device %08x on output %d", 2121 devDesc->type(), inputDesc->mIoHandle); 2122 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle); 2123 index = mAudioPatches.indexOfKey(*handle); 2124 if (index >= 0) { 2125 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) { 2126 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided"); 2127 } 2128 patchDesc = mAudioPatches.valueAt(index); 2129 patchDesc->mUid = uid; 2130 ALOGV("createAudioPatch() success"); 2131 } else { 2132 ALOGW("createAudioPatch() setInputDevice() failed to create a patch"); 2133 return INVALID_OPERATION; 2134 } 2135 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) { 2136 // device to device connection 2137 if (patchDesc != 0) { 2138 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) { 2139 return BAD_VALUE; 2140 } 2141 } 2142 sp<DeviceDescriptor> srcDeviceDesc = 2143 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id); 2144 if (srcDeviceDesc == 0) { 2145 return BAD_VALUE; 2146 } 2147 2148 //update source and sink with our own data as the data passed in the patch may 2149 // be incomplete. 2150 struct audio_patch newPatch = *patch; 2151 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]); 2152 2153 for (size_t i = 0; i < patch->num_sinks; i++) { 2154 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) { 2155 ALOGV("createAudioPatch() source device but one sink is not a device"); 2156 return INVALID_OPERATION; 2157 } 2158 2159 sp<DeviceDescriptor> sinkDeviceDesc = 2160 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id); 2161 if (sinkDeviceDesc == 0) { 2162 return BAD_VALUE; 2163 } 2164 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]); 2165 2166 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) { 2167 // only one sink supported when connected devices across HW modules 2168 if (patch->num_sinks > 1) { 2169 return INVALID_OPERATION; 2170 } 2171 SortedVector<audio_io_handle_t> outputs = 2172 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs); 2173 // if the sink device is reachable via an opened output stream, request to go via 2174 // this output stream by adding a second source to the patch description 2175 audio_io_handle_t output = selectOutput(outputs, 2176 AUDIO_OUTPUT_FLAG_NONE, 2177 AUDIO_FORMAT_INVALID); 2178 if (output != AUDIO_IO_HANDLE_NONE) { 2179 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 2180 if (outputDesc->isDuplicated()) { 2181 return INVALID_OPERATION; 2182 } 2183 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]); 2184 newPatch.num_sources = 2; 2185 } 2186 } 2187 } 2188 // TODO: check from routing capabilities in config file and other conflicting patches 2189 2190 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 2191 if (index >= 0) { 2192 afPatchHandle = patchDesc->mAfPatchHandle; 2193 } 2194 2195 status_t status = mpClientInterface->createAudioPatch(&newPatch, 2196 &afPatchHandle, 2197 0); 2198 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d", 2199 status, afPatchHandle); 2200 if (status == NO_ERROR) { 2201 if (index < 0) { 2202 patchDesc = new AudioPatch(&newPatch, uid); 2203 addAudioPatch(patchDesc->mHandle, patchDesc); 2204 } else { 2205 patchDesc->mPatch = newPatch; 2206 } 2207 patchDesc->mAfPatchHandle = afPatchHandle; 2208 *handle = patchDesc->mHandle; 2209 nextAudioPortGeneration(); 2210 mpClientInterface->onAudioPatchListUpdate(); 2211 } else { 2212 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d", 2213 status); 2214 return INVALID_OPERATION; 2215 } 2216 } else { 2217 return BAD_VALUE; 2218 } 2219 } else { 2220 return BAD_VALUE; 2221 } 2222 return NO_ERROR; 2223} 2224 2225status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, 2226 uid_t uid) 2227{ 2228 ALOGV("releaseAudioPatch() patch %d", handle); 2229 2230 ssize_t index = mAudioPatches.indexOfKey(handle); 2231 2232 if (index < 0) { 2233 return BAD_VALUE; 2234 } 2235 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 2236 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d", 2237 mUidCached, patchDesc->mUid, uid); 2238 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) { 2239 return INVALID_OPERATION; 2240 } 2241 2242 struct audio_patch *patch = &patchDesc->mPatch; 2243 patchDesc->mUid = mUidCached; 2244 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) { 2245 sp<AudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id); 2246 if (outputDesc == NULL) { 2247 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id); 2248 return BAD_VALUE; 2249 } 2250 2251 setOutputDevice(outputDesc->mIoHandle, 2252 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/), 2253 true, 2254 0, 2255 NULL); 2256 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) { 2257 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) { 2258 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id); 2259 if (inputDesc == NULL) { 2260 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id); 2261 return BAD_VALUE; 2262 } 2263 setInputDevice(inputDesc->mIoHandle, 2264 getNewInputDevice(inputDesc->mIoHandle), 2265 true, 2266 NULL); 2267 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) { 2268 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle; 2269 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 2270 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d", 2271 status, patchDesc->mAfPatchHandle); 2272 removeAudioPatch(patchDesc->mHandle); 2273 nextAudioPortGeneration(); 2274 mpClientInterface->onAudioPatchListUpdate(); 2275 } else { 2276 return BAD_VALUE; 2277 } 2278 } else { 2279 return BAD_VALUE; 2280 } 2281 return NO_ERROR; 2282} 2283 2284status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches, 2285 struct audio_patch *patches, 2286 unsigned int *generation) 2287{ 2288 if (generation == NULL) { 2289 return BAD_VALUE; 2290 } 2291 *generation = curAudioPortGeneration(); 2292 return mAudioPatches.listAudioPatches(num_patches, patches); 2293} 2294 2295status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config) 2296{ 2297 ALOGV("setAudioPortConfig()"); 2298 2299 if (config == NULL) { 2300 return BAD_VALUE; 2301 } 2302 ALOGV("setAudioPortConfig() on port handle %d", config->id); 2303 // Only support gain configuration for now 2304 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) { 2305 return INVALID_OPERATION; 2306 } 2307 2308 sp<AudioPortConfig> audioPortConfig; 2309 if (config->type == AUDIO_PORT_TYPE_MIX) { 2310 if (config->role == AUDIO_PORT_ROLE_SOURCE) { 2311 sp<AudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id); 2312 if (outputDesc == NULL) { 2313 return BAD_VALUE; 2314 } 2315 ALOG_ASSERT(!outputDesc->isDuplicated(), 2316 "setAudioPortConfig() called on duplicated output %d", 2317 outputDesc->mIoHandle); 2318 audioPortConfig = outputDesc; 2319 } else if (config->role == AUDIO_PORT_ROLE_SINK) { 2320 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id); 2321 if (inputDesc == NULL) { 2322 return BAD_VALUE; 2323 } 2324 audioPortConfig = inputDesc; 2325 } else { 2326 return BAD_VALUE; 2327 } 2328 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) { 2329 sp<DeviceDescriptor> deviceDesc; 2330 if (config->role == AUDIO_PORT_ROLE_SOURCE) { 2331 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id); 2332 } else if (config->role == AUDIO_PORT_ROLE_SINK) { 2333 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id); 2334 } else { 2335 return BAD_VALUE; 2336 } 2337 if (deviceDesc == NULL) { 2338 return BAD_VALUE; 2339 } 2340 audioPortConfig = deviceDesc; 2341 } else { 2342 return BAD_VALUE; 2343 } 2344 2345 struct audio_port_config backupConfig; 2346 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig); 2347 if (status == NO_ERROR) { 2348 struct audio_port_config newConfig; 2349 audioPortConfig->toAudioPortConfig(&newConfig, config); 2350 status = mpClientInterface->setAudioPortConfig(&newConfig, 0); 2351 } 2352 if (status != NO_ERROR) { 2353 audioPortConfig->applyAudioPortConfig(&backupConfig); 2354 } 2355 2356 return status; 2357} 2358 2359void AudioPolicyManager::clearAudioPatches(uid_t uid) 2360{ 2361 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) { 2362 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i); 2363 if (patchDesc->mUid == uid) { 2364 releaseAudioPatch(mAudioPatches.keyAt(i), uid); 2365 } 2366 } 2367} 2368 2369status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session, 2370 audio_io_handle_t *ioHandle, 2371 audio_devices_t *device) 2372{ 2373 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(); 2374 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(); 2375 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD); 2376 2377 return mSoundTriggerSessions.acquireSession(*session, *ioHandle); 2378} 2379 2380// ---------------------------------------------------------------------------- 2381// AudioPolicyManager 2382// ---------------------------------------------------------------------------- 2383uint32_t AudioPolicyManager::nextAudioPortGeneration() 2384{ 2385 return android_atomic_inc(&mAudioPortGeneration); 2386} 2387 2388AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface) 2389 : 2390#ifdef AUDIO_POLICY_TEST 2391 Thread(false), 2392#endif //AUDIO_POLICY_TEST 2393 mPrimaryOutput((audio_io_handle_t)0), 2394 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f), 2395 mA2dpSuspended(false), 2396 mSpeakerDrcEnabled(false), 2397 mAudioPortGeneration(1), 2398 mBeaconMuteRefCount(0), 2399 mBeaconPlayingRefCount(0), 2400 mBeaconMuted(false) 2401{ 2402 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance(); 2403 if (!engineInstance) { 2404 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__); 2405 return; 2406 } 2407 // Retrieve the Policy Manager Interface 2408 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>(); 2409 if (mEngine == NULL) { 2410 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__); 2411 return; 2412 } 2413 mEngine->setObserver(this); 2414 status_t status = mEngine->initCheck(); 2415 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status); 2416 2417 mUidCached = getuid(); 2418 mpClientInterface = clientInterface; 2419 2420 mDefaultOutputDevice = new DeviceDescriptor(String8("Speaker"), AUDIO_DEVICE_OUT_SPEAKER); 2421 if (ConfigParsingUtils::loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, 2422 mHwModules, mAvailableInputDevices, mAvailableOutputDevices, 2423 mDefaultOutputDevice, mSpeakerDrcEnabled) != NO_ERROR) { 2424 if (ConfigParsingUtils::loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE, 2425 mHwModules, mAvailableInputDevices, mAvailableOutputDevices, 2426 mDefaultOutputDevice, mSpeakerDrcEnabled) != NO_ERROR) { 2427 ALOGE("could not load audio policy configuration file, setting defaults"); 2428 defaultAudioPolicyConfig(); 2429 } 2430 } 2431 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices 2432 2433 // must be done after reading the policy (since conditionned by Speaker Drc Enabling) 2434 mEngine->initializeVolumeCurves(mSpeakerDrcEnabled); 2435 2436 // open all output streams needed to access attached devices 2437 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types(); 2438 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN; 2439 for (size_t i = 0; i < mHwModules.size(); i++) { 2440 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName); 2441 if (mHwModules[i]->mHandle == 0) { 2442 ALOGW("could not open HW module %s", mHwModules[i]->mName); 2443 continue; 2444 } 2445 // open all output streams needed to access attached devices 2446 // except for direct output streams that are only opened when they are actually 2447 // required by an app. 2448 // This also validates mAvailableOutputDevices list 2449 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 2450 { 2451 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j]; 2452 2453 if (outProfile->mSupportedDevices.isEmpty()) { 2454 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName); 2455 continue; 2456 } 2457 2458 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) { 2459 continue; 2460 } 2461 audio_devices_t profileType = outProfile->mSupportedDevices.types(); 2462 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) { 2463 profileType = mDefaultOutputDevice->type(); 2464 } else { 2465 // chose first device present in mSupportedDevices also part of 2466 // outputDeviceTypes 2467 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) { 2468 profileType = outProfile->mSupportedDevices[k]->type(); 2469 if ((profileType & outputDeviceTypes) != 0) { 2470 break; 2471 } 2472 } 2473 } 2474 if ((profileType & outputDeviceTypes) == 0) { 2475 continue; 2476 } 2477 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile); 2478 2479 outputDesc->mDevice = profileType; 2480 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 2481 config.sample_rate = outputDesc->mSamplingRate; 2482 config.channel_mask = outputDesc->mChannelMask; 2483 config.format = outputDesc->mFormat; 2484 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE; 2485 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle, 2486 &output, 2487 &config, 2488 &outputDesc->mDevice, 2489 String8(""), 2490 &outputDesc->mLatency, 2491 outputDesc->mFlags); 2492 2493 if (status != NO_ERROR) { 2494 ALOGW("Cannot open output stream for device %08x on hw module %s", 2495 outputDesc->mDevice, 2496 mHwModules[i]->mName); 2497 } else { 2498 outputDesc->mSamplingRate = config.sample_rate; 2499 outputDesc->mChannelMask = config.channel_mask; 2500 outputDesc->mFormat = config.format; 2501 2502 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) { 2503 audio_devices_t type = outProfile->mSupportedDevices[k]->type(); 2504 ssize_t index = 2505 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]); 2506 // give a valid ID to an attached device once confirmed it is reachable 2507 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) { 2508 mAvailableOutputDevices[index]->attach(mHwModules[i]); 2509 } 2510 } 2511 if (mPrimaryOutput == 0 && 2512 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) { 2513 mPrimaryOutput = output; 2514 } 2515 addOutput(output, outputDesc); 2516 setOutputDevice(output, 2517 outputDesc->mDevice, 2518 true); 2519 } 2520 } 2521 // open input streams needed to access attached devices to validate 2522 // mAvailableInputDevices list 2523 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) 2524 { 2525 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j]; 2526 2527 if (inProfile->mSupportedDevices.isEmpty()) { 2528 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName); 2529 continue; 2530 } 2531 // chose first device present in mSupportedDevices also part of 2532 // inputDeviceTypes 2533 audio_devices_t profileType = AUDIO_DEVICE_NONE; 2534 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) { 2535 profileType = inProfile->mSupportedDevices[k]->type(); 2536 if (profileType & inputDeviceTypes) { 2537 break; 2538 } 2539 } 2540 if ((profileType & inputDeviceTypes) == 0) { 2541 continue; 2542 } 2543 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile); 2544 2545 inputDesc->mInputSource = AUDIO_SOURCE_MIC; 2546 inputDesc->mDevice = profileType; 2547 2548 // find the address 2549 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType); 2550 // the inputs vector must be of size 1, but we don't want to crash here 2551 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress 2552 : String8(""); 2553 ALOGV(" for input device 0x%x using address %s", profileType, address.string()); 2554 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!"); 2555 2556 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 2557 config.sample_rate = inputDesc->mSamplingRate; 2558 config.channel_mask = inputDesc->mChannelMask; 2559 config.format = inputDesc->mFormat; 2560 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE; 2561 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle, 2562 &input, 2563 &config, 2564 &inputDesc->mDevice, 2565 address, 2566 AUDIO_SOURCE_MIC, 2567 AUDIO_INPUT_FLAG_NONE); 2568 2569 if (status == NO_ERROR) { 2570 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) { 2571 audio_devices_t type = inProfile->mSupportedDevices[k]->type(); 2572 ssize_t index = 2573 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]); 2574 // give a valid ID to an attached device once confirmed it is reachable 2575 if (index >= 0 && !mAvailableInputDevices[index]->isAttached()) { 2576 mAvailableInputDevices[index]->attach(mHwModules[i]); 2577 } 2578 } 2579 mpClientInterface->closeInput(input); 2580 } else { 2581 ALOGW("Cannot open input stream for device %08x on hw module %s", 2582 inputDesc->mDevice, 2583 mHwModules[i]->mName); 2584 } 2585 } 2586 } 2587 // make sure all attached devices have been allocated a unique ID 2588 for (size_t i = 0; i < mAvailableOutputDevices.size();) { 2589 if (!mAvailableOutputDevices[i]->isAttached()) { 2590 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->type()); 2591 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]); 2592 continue; 2593 } 2594 // The device is now validated and can be appended to the available devices of the engine 2595 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i], 2596 AUDIO_POLICY_DEVICE_STATE_AVAILABLE); 2597 i++; 2598 } 2599 for (size_t i = 0; i < mAvailableInputDevices.size();) { 2600 if (!mAvailableInputDevices[i]->isAttached()) { 2601 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type()); 2602 mAvailableInputDevices.remove(mAvailableInputDevices[i]); 2603 continue; 2604 } 2605 // The device is now validated and can be appended to the available devices of the engine 2606 mEngine->setDeviceConnectionState(mAvailableInputDevices[i], 2607 AUDIO_POLICY_DEVICE_STATE_AVAILABLE); 2608 i++; 2609 } 2610 // make sure default device is reachable 2611 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) { 2612 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type()); 2613 } 2614 2615 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output"); 2616 2617 updateDevicesAndOutputs(); 2618 2619#ifdef AUDIO_POLICY_TEST 2620 if (mPrimaryOutput != 0) { 2621 AudioParameter outputCmd = AudioParameter(); 2622 outputCmd.addInt(String8("set_id"), 0); 2623 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString()); 2624 2625 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER; 2626 mTestSamplingRate = 44100; 2627 mTestFormat = AUDIO_FORMAT_PCM_16_BIT; 2628 mTestChannels = AUDIO_CHANNEL_OUT_STEREO; 2629 mTestLatencyMs = 0; 2630 mCurOutput = 0; 2631 mDirectOutput = false; 2632 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) { 2633 mTestOutputs[i] = 0; 2634 } 2635 2636 const size_t SIZE = 256; 2637 char buffer[SIZE]; 2638 snprintf(buffer, SIZE, "AudioPolicyManagerTest"); 2639 run(buffer, ANDROID_PRIORITY_AUDIO); 2640 } 2641#endif //AUDIO_POLICY_TEST 2642} 2643 2644AudioPolicyManager::~AudioPolicyManager() 2645{ 2646#ifdef AUDIO_POLICY_TEST 2647 exit(); 2648#endif //AUDIO_POLICY_TEST 2649 for (size_t i = 0; i < mOutputs.size(); i++) { 2650 mpClientInterface->closeOutput(mOutputs.keyAt(i)); 2651 } 2652 for (size_t i = 0; i < mInputs.size(); i++) { 2653 mpClientInterface->closeInput(mInputs.keyAt(i)); 2654 } 2655 mAvailableOutputDevices.clear(); 2656 mAvailableInputDevices.clear(); 2657 mOutputs.clear(); 2658 mInputs.clear(); 2659 mHwModules.clear(); 2660} 2661 2662status_t AudioPolicyManager::initCheck() 2663{ 2664 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR; 2665} 2666 2667#ifdef AUDIO_POLICY_TEST 2668bool AudioPolicyManager::threadLoop() 2669{ 2670 ALOGV("entering threadLoop()"); 2671 while (!exitPending()) 2672 { 2673 String8 command; 2674 int valueInt; 2675 String8 value; 2676 2677 Mutex::Autolock _l(mLock); 2678 mWaitWorkCV.waitRelative(mLock, milliseconds(50)); 2679 2680 command = mpClientInterface->getParameters(0, String8("test_cmd_policy")); 2681 AudioParameter param = AudioParameter(command); 2682 2683 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR && 2684 valueInt != 0) { 2685 ALOGV("Test command %s received", command.string()); 2686 String8 target; 2687 if (param.get(String8("target"), target) != NO_ERROR) { 2688 target = "Manager"; 2689 } 2690 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) { 2691 param.remove(String8("test_cmd_policy_output")); 2692 mCurOutput = valueInt; 2693 } 2694 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) { 2695 param.remove(String8("test_cmd_policy_direct")); 2696 if (value == "false") { 2697 mDirectOutput = false; 2698 } else if (value == "true") { 2699 mDirectOutput = true; 2700 } 2701 } 2702 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) { 2703 param.remove(String8("test_cmd_policy_input")); 2704 mTestInput = valueInt; 2705 } 2706 2707 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) { 2708 param.remove(String8("test_cmd_policy_format")); 2709 int format = AUDIO_FORMAT_INVALID; 2710 if (value == "PCM 16 bits") { 2711 format = AUDIO_FORMAT_PCM_16_BIT; 2712 } else if (value == "PCM 8 bits") { 2713 format = AUDIO_FORMAT_PCM_8_BIT; 2714 } else if (value == "Compressed MP3") { 2715 format = AUDIO_FORMAT_MP3; 2716 } 2717 if (format != AUDIO_FORMAT_INVALID) { 2718 if (target == "Manager") { 2719 mTestFormat = format; 2720 } else if (mTestOutputs[mCurOutput] != 0) { 2721 AudioParameter outputParam = AudioParameter(); 2722 outputParam.addInt(String8("format"), format); 2723 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 2724 } 2725 } 2726 } 2727 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) { 2728 param.remove(String8("test_cmd_policy_channels")); 2729 int channels = 0; 2730 2731 if (value == "Channels Stereo") { 2732 channels = AUDIO_CHANNEL_OUT_STEREO; 2733 } else if (value == "Channels Mono") { 2734 channels = AUDIO_CHANNEL_OUT_MONO; 2735 } 2736 if (channels != 0) { 2737 if (target == "Manager") { 2738 mTestChannels = channels; 2739 } else if (mTestOutputs[mCurOutput] != 0) { 2740 AudioParameter outputParam = AudioParameter(); 2741 outputParam.addInt(String8("channels"), channels); 2742 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 2743 } 2744 } 2745 } 2746 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) { 2747 param.remove(String8("test_cmd_policy_sampleRate")); 2748 if (valueInt >= 0 && valueInt <= 96000) { 2749 int samplingRate = valueInt; 2750 if (target == "Manager") { 2751 mTestSamplingRate = samplingRate; 2752 } else if (mTestOutputs[mCurOutput] != 0) { 2753 AudioParameter outputParam = AudioParameter(); 2754 outputParam.addInt(String8("sampling_rate"), samplingRate); 2755 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 2756 } 2757 } 2758 } 2759 2760 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) { 2761 param.remove(String8("test_cmd_policy_reopen")); 2762 2763 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput); 2764 mpClientInterface->closeOutput(mPrimaryOutput); 2765 2766 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle; 2767 2768 removeOutput(mPrimaryOutput); 2769 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL); 2770 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER; 2771 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 2772 config.sample_rate = outputDesc->mSamplingRate; 2773 config.channel_mask = outputDesc->mChannelMask; 2774 config.format = outputDesc->mFormat; 2775 status_t status = mpClientInterface->openOutput(moduleHandle, 2776 &mPrimaryOutput, 2777 &config, 2778 &outputDesc->mDevice, 2779 String8(""), 2780 &outputDesc->mLatency, 2781 outputDesc->mFlags); 2782 if (status != NO_ERROR) { 2783 ALOGE("Failed to reopen hardware output stream, " 2784 "samplingRate: %d, format %d, channels %d", 2785 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask); 2786 } else { 2787 outputDesc->mSamplingRate = config.sample_rate; 2788 outputDesc->mChannelMask = config.channel_mask; 2789 outputDesc->mFormat = config.format; 2790 AudioParameter outputCmd = AudioParameter(); 2791 outputCmd.addInt(String8("set_id"), 0); 2792 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString()); 2793 addOutput(mPrimaryOutput, outputDesc); 2794 } 2795 } 2796 2797 2798 mpClientInterface->setParameters(0, String8("test_cmd_policy=")); 2799 } 2800 } 2801 return false; 2802} 2803 2804void AudioPolicyManager::exit() 2805{ 2806 { 2807 AutoMutex _l(mLock); 2808 requestExit(); 2809 mWaitWorkCV.signal(); 2810 } 2811 requestExitAndWait(); 2812} 2813 2814int AudioPolicyManager::testOutputIndex(audio_io_handle_t output) 2815{ 2816 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) { 2817 if (output == mTestOutputs[i]) return i; 2818 } 2819 return 0; 2820} 2821#endif //AUDIO_POLICY_TEST 2822 2823// --- 2824 2825void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc) 2826{ 2827 outputDesc->setIoHandle(output); 2828 mOutputs.add(output, outputDesc); 2829 nextAudioPortGeneration(); 2830} 2831 2832void AudioPolicyManager::removeOutput(audio_io_handle_t output) 2833{ 2834 mOutputs.removeItem(output); 2835} 2836 2837void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc) 2838{ 2839 inputDesc->setIoHandle(input); 2840 mInputs.add(input, inputDesc); 2841 nextAudioPortGeneration(); 2842} 2843 2844void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/, 2845 const audio_devices_t device /*in*/, 2846 const String8 address /*in*/, 2847 SortedVector<audio_io_handle_t>& outputs /*out*/) { 2848 sp<DeviceDescriptor> devDesc = 2849 desc->mProfile->mSupportedDevices.getDevice(device, address); 2850 if (devDesc != 0) { 2851 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s", 2852 desc->mIoHandle, address.string()); 2853 outputs.add(desc->mIoHandle); 2854 } 2855} 2856 2857status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc, 2858 audio_policy_dev_state_t state, 2859 SortedVector<audio_io_handle_t>& outputs, 2860 const String8 address) 2861{ 2862 audio_devices_t device = devDesc->type(); 2863 sp<AudioOutputDescriptor> desc; 2864 // erase all current sample rates, formats and channel masks 2865 devDesc->clearCapabilities(); 2866 2867 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) { 2868 // first list already open outputs that can be routed to this device 2869 for (size_t i = 0; i < mOutputs.size(); i++) { 2870 desc = mOutputs.valueAt(i); 2871 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) { 2872 if (!device_distinguishes_on_address(device)) { 2873 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i)); 2874 outputs.add(mOutputs.keyAt(i)); 2875 } else { 2876 ALOGV(" checking address match due to device 0x%x", device); 2877 findIoHandlesByAddress(desc, device, address, outputs); 2878 } 2879 } 2880 } 2881 // then look for output profiles that can be routed to this device 2882 SortedVector< sp<IOProfile> > profiles; 2883 for (size_t i = 0; i < mHwModules.size(); i++) 2884 { 2885 if (mHwModules[i]->mHandle == 0) { 2886 continue; 2887 } 2888 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 2889 { 2890 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j]; 2891 if (profile->mSupportedDevices.types() & device) { 2892 if (!device_distinguishes_on_address(device) || 2893 address == profile->mSupportedDevices[0]->mAddress) { 2894 profiles.add(profile); 2895 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i); 2896 } 2897 } 2898 } 2899 } 2900 2901 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size()); 2902 2903 if (profiles.isEmpty() && outputs.isEmpty()) { 2904 ALOGW("checkOutputsForDevice(): No output available for device %04x", device); 2905 return BAD_VALUE; 2906 } 2907 2908 // open outputs for matching profiles if needed. Direct outputs are also opened to 2909 // query for dynamic parameters and will be closed later by setDeviceConnectionState() 2910 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) { 2911 sp<IOProfile> profile = profiles[profile_index]; 2912 2913 // nothing to do if one output is already opened for this profile 2914 size_t j; 2915 for (j = 0; j < outputs.size(); j++) { 2916 desc = mOutputs.valueFor(outputs.itemAt(j)); 2917 if (!desc->isDuplicated() && desc->mProfile == profile) { 2918 // matching profile: save the sample rates, format and channel masks supported 2919 // by the profile in our device descriptor 2920 devDesc->importAudioPort(profile); 2921 break; 2922 } 2923 } 2924 if (j != outputs.size()) { 2925 continue; 2926 } 2927 2928 ALOGV("opening output for device %08x with params %s profile %p", 2929 device, address.string(), profile.get()); 2930 desc = new AudioOutputDescriptor(profile); 2931 desc->mDevice = device; 2932 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 2933 config.sample_rate = desc->mSamplingRate; 2934 config.channel_mask = desc->mChannelMask; 2935 config.format = desc->mFormat; 2936 config.offload_info.sample_rate = desc->mSamplingRate; 2937 config.offload_info.channel_mask = desc->mChannelMask; 2938 config.offload_info.format = desc->mFormat; 2939 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE; 2940 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle, 2941 &output, 2942 &config, 2943 &desc->mDevice, 2944 address, 2945 &desc->mLatency, 2946 desc->mFlags); 2947 if (status == NO_ERROR) { 2948 desc->mSamplingRate = config.sample_rate; 2949 desc->mChannelMask = config.channel_mask; 2950 desc->mFormat = config.format; 2951 2952 // Here is where the out_set_parameters() for card & device gets called 2953 if (!address.isEmpty()) { 2954 char *param = audio_device_address_to_parameter(device, address); 2955 mpClientInterface->setParameters(output, String8(param)); 2956 free(param); 2957 } 2958 2959 // Here is where we step through and resolve any "dynamic" fields 2960 String8 reply; 2961 char *value; 2962 if (profile->mSamplingRates[0] == 0) { 2963 reply = mpClientInterface->getParameters(output, 2964 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES)); 2965 ALOGV("checkOutputsForDevice() supported sampling rates %s", 2966 reply.string()); 2967 value = strpbrk((char *)reply.string(), "="); 2968 if (value != NULL) { 2969 profile->loadSamplingRates(value + 1); 2970 } 2971 } 2972 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) { 2973 reply = mpClientInterface->getParameters(output, 2974 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS)); 2975 ALOGV("checkOutputsForDevice() supported formats %s", 2976 reply.string()); 2977 value = strpbrk((char *)reply.string(), "="); 2978 if (value != NULL) { 2979 profile->loadFormats(value + 1); 2980 } 2981 } 2982 if (profile->mChannelMasks[0] == 0) { 2983 reply = mpClientInterface->getParameters(output, 2984 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS)); 2985 ALOGV("checkOutputsForDevice() supported channel masks %s", 2986 reply.string()); 2987 value = strpbrk((char *)reply.string(), "="); 2988 if (value != NULL) { 2989 profile->loadOutChannels(value + 1); 2990 } 2991 } 2992 if (((profile->mSamplingRates[0] == 0) && 2993 (profile->mSamplingRates.size() < 2)) || 2994 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) && 2995 (profile->mFormats.size() < 2)) || 2996 ((profile->mChannelMasks[0] == 0) && 2997 (profile->mChannelMasks.size() < 2))) { 2998 ALOGW("checkOutputsForDevice() missing param"); 2999 mpClientInterface->closeOutput(output); 3000 output = AUDIO_IO_HANDLE_NONE; 3001 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 || 3002 profile->mChannelMasks[0] == 0) { 3003 mpClientInterface->closeOutput(output); 3004 config.sample_rate = profile->pickSamplingRate(); 3005 config.channel_mask = profile->pickChannelMask(); 3006 config.format = profile->pickFormat(); 3007 config.offload_info.sample_rate = config.sample_rate; 3008 config.offload_info.channel_mask = config.channel_mask; 3009 config.offload_info.format = config.format; 3010 status = mpClientInterface->openOutput(profile->mModule->mHandle, 3011 &output, 3012 &config, 3013 &desc->mDevice, 3014 address, 3015 &desc->mLatency, 3016 desc->mFlags); 3017 if (status == NO_ERROR) { 3018 desc->mSamplingRate = config.sample_rate; 3019 desc->mChannelMask = config.channel_mask; 3020 desc->mFormat = config.format; 3021 } else { 3022 output = AUDIO_IO_HANDLE_NONE; 3023 } 3024 } 3025 3026 if (output != AUDIO_IO_HANDLE_NONE) { 3027 addOutput(output, desc); 3028 if (device_distinguishes_on_address(device) && address != "0") { 3029 sp<AudioPolicyMix> policyMix; 3030 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) { 3031 ALOGE("checkOutputsForDevice() cannot find policy for address %s", 3032 address.string()); 3033 } 3034 policyMix->setOutput(desc); 3035 desc->mPolicyMix = policyMix->getMix(); 3036 3037 } else if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) { 3038 // no duplicated output for direct outputs and 3039 // outputs used by dynamic policy mixes 3040 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE; 3041 3042 // set initial stream volume for device 3043 applyStreamVolumes(output, device, 0, true); 3044 3045 //TODO: configure audio effect output stage here 3046 3047 // open a duplicating output thread for the new output and the primary output 3048 duplicatedOutput = mpClientInterface->openDuplicateOutput(output, 3049 mPrimaryOutput); 3050 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) { 3051 // add duplicated output descriptor 3052 sp<AudioOutputDescriptor> dupOutputDesc = 3053 new AudioOutputDescriptor(NULL); 3054 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput); 3055 dupOutputDesc->mOutput2 = mOutputs.valueFor(output); 3056 dupOutputDesc->mSamplingRate = desc->mSamplingRate; 3057 dupOutputDesc->mFormat = desc->mFormat; 3058 dupOutputDesc->mChannelMask = desc->mChannelMask; 3059 dupOutputDesc->mLatency = desc->mLatency; 3060 addOutput(duplicatedOutput, dupOutputDesc); 3061 applyStreamVolumes(duplicatedOutput, device, 0, true); 3062 } else { 3063 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d", 3064 mPrimaryOutput, output); 3065 mpClientInterface->closeOutput(output); 3066 removeOutput(output); 3067 nextAudioPortGeneration(); 3068 output = AUDIO_IO_HANDLE_NONE; 3069 } 3070 } 3071 } 3072 } else { 3073 output = AUDIO_IO_HANDLE_NONE; 3074 } 3075 if (output == AUDIO_IO_HANDLE_NONE) { 3076 ALOGW("checkOutputsForDevice() could not open output for device %x", device); 3077 profiles.removeAt(profile_index); 3078 profile_index--; 3079 } else { 3080 outputs.add(output); 3081 devDesc->importAudioPort(profile); 3082 3083 if (device_distinguishes_on_address(device)) { 3084 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)", 3085 device, address.string()); 3086 setOutputDevice(output, device, true/*force*/, 0/*delay*/, 3087 NULL/*patch handle*/, address.string()); 3088 } 3089 ALOGV("checkOutputsForDevice(): adding output %d", output); 3090 } 3091 } 3092 3093 if (profiles.isEmpty()) { 3094 ALOGW("checkOutputsForDevice(): No output available for device %04x", device); 3095 return BAD_VALUE; 3096 } 3097 } else { // Disconnect 3098 // check if one opened output is not needed any more after disconnecting one device 3099 for (size_t i = 0; i < mOutputs.size(); i++) { 3100 desc = mOutputs.valueAt(i); 3101 if (!desc->isDuplicated()) { 3102 // exact match on device 3103 if (device_distinguishes_on_address(device) && 3104 (desc->mProfile->mSupportedDevices.types() == device)) { 3105 findIoHandlesByAddress(desc, device, address, outputs); 3106 } else if (!(desc->mProfile->mSupportedDevices.types() 3107 & mAvailableOutputDevices.types())) { 3108 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", 3109 mOutputs.keyAt(i)); 3110 outputs.add(mOutputs.keyAt(i)); 3111 } 3112 } 3113 } 3114 // Clear any profiles associated with the disconnected device. 3115 for (size_t i = 0; i < mHwModules.size(); i++) 3116 { 3117 if (mHwModules[i]->mHandle == 0) { 3118 continue; 3119 } 3120 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 3121 { 3122 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j]; 3123 if (profile->mSupportedDevices.types() & device) { 3124 ALOGV("checkOutputsForDevice(): " 3125 "clearing direct output profile %zu on module %zu", j, i); 3126 if (profile->mSamplingRates[0] == 0) { 3127 profile->mSamplingRates.clear(); 3128 profile->mSamplingRates.add(0); 3129 } 3130 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) { 3131 profile->mFormats.clear(); 3132 profile->mFormats.add(AUDIO_FORMAT_DEFAULT); 3133 } 3134 if (profile->mChannelMasks[0] == 0) { 3135 profile->mChannelMasks.clear(); 3136 profile->mChannelMasks.add(0); 3137 } 3138 } 3139 } 3140 } 3141 } 3142 return NO_ERROR; 3143} 3144 3145status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device, 3146 audio_policy_dev_state_t state, 3147 SortedVector<audio_io_handle_t>& inputs, 3148 const String8 address) 3149{ 3150 sp<AudioInputDescriptor> desc; 3151 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) { 3152 // first list already open inputs that can be routed to this device 3153 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) { 3154 desc = mInputs.valueAt(input_index); 3155 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) { 3156 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index)); 3157 inputs.add(mInputs.keyAt(input_index)); 3158 } 3159 } 3160 3161 // then look for input profiles that can be routed to this device 3162 SortedVector< sp<IOProfile> > profiles; 3163 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++) 3164 { 3165 if (mHwModules[module_idx]->mHandle == 0) { 3166 continue; 3167 } 3168 for (size_t profile_index = 0; 3169 profile_index < mHwModules[module_idx]->mInputProfiles.size(); 3170 profile_index++) 3171 { 3172 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index]; 3173 3174 if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) { 3175 if (!device_distinguishes_on_address(device) || 3176 address == profile->mSupportedDevices[0]->mAddress) { 3177 profiles.add(profile); 3178 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu", 3179 profile_index, module_idx); 3180 } 3181 } 3182 } 3183 } 3184 3185 if (profiles.isEmpty() && inputs.isEmpty()) { 3186 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device); 3187 return BAD_VALUE; 3188 } 3189 3190 // open inputs for matching profiles if needed. Direct inputs are also opened to 3191 // query for dynamic parameters and will be closed later by setDeviceConnectionState() 3192 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) { 3193 3194 sp<IOProfile> profile = profiles[profile_index]; 3195 // nothing to do if one input is already opened for this profile 3196 size_t input_index; 3197 for (input_index = 0; input_index < mInputs.size(); input_index++) { 3198 desc = mInputs.valueAt(input_index); 3199 if (desc->mProfile == profile) { 3200 break; 3201 } 3202 } 3203 if (input_index != mInputs.size()) { 3204 continue; 3205 } 3206 3207 ALOGV("opening input for device 0x%X with params %s", device, address.string()); 3208 desc = new AudioInputDescriptor(profile); 3209 desc->mDevice = device; 3210 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 3211 config.sample_rate = desc->mSamplingRate; 3212 config.channel_mask = desc->mChannelMask; 3213 config.format = desc->mFormat; 3214 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE; 3215 status_t status = mpClientInterface->openInput(profile->mModule->mHandle, 3216 &input, 3217 &config, 3218 &desc->mDevice, 3219 address, 3220 AUDIO_SOURCE_MIC, 3221 AUDIO_INPUT_FLAG_NONE /*FIXME*/); 3222 3223 if (status == NO_ERROR) { 3224 desc->mSamplingRate = config.sample_rate; 3225 desc->mChannelMask = config.channel_mask; 3226 desc->mFormat = config.format; 3227 3228 if (!address.isEmpty()) { 3229 char *param = audio_device_address_to_parameter(device, address); 3230 mpClientInterface->setParameters(input, String8(param)); 3231 free(param); 3232 } 3233 3234 // Here is where we step through and resolve any "dynamic" fields 3235 String8 reply; 3236 char *value; 3237 if (profile->mSamplingRates[0] == 0) { 3238 reply = mpClientInterface->getParameters(input, 3239 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES)); 3240 ALOGV("checkInputsForDevice() direct input sup sampling rates %s", 3241 reply.string()); 3242 value = strpbrk((char *)reply.string(), "="); 3243 if (value != NULL) { 3244 profile->loadSamplingRates(value + 1); 3245 } 3246 } 3247 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) { 3248 reply = mpClientInterface->getParameters(input, 3249 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS)); 3250 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string()); 3251 value = strpbrk((char *)reply.string(), "="); 3252 if (value != NULL) { 3253 profile->loadFormats(value + 1); 3254 } 3255 } 3256 if (profile->mChannelMasks[0] == 0) { 3257 reply = mpClientInterface->getParameters(input, 3258 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS)); 3259 ALOGV("checkInputsForDevice() direct input sup channel masks %s", 3260 reply.string()); 3261 value = strpbrk((char *)reply.string(), "="); 3262 if (value != NULL) { 3263 profile->loadInChannels(value + 1); 3264 } 3265 } 3266 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) || 3267 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) || 3268 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) { 3269 ALOGW("checkInputsForDevice() direct input missing param"); 3270 mpClientInterface->closeInput(input); 3271 input = AUDIO_IO_HANDLE_NONE; 3272 } 3273 3274 if (input != 0) { 3275 addInput(input, desc); 3276 } 3277 } // endif input != 0 3278 3279 if (input == AUDIO_IO_HANDLE_NONE) { 3280 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device); 3281 profiles.removeAt(profile_index); 3282 profile_index--; 3283 } else { 3284 inputs.add(input); 3285 ALOGV("checkInputsForDevice(): adding input %d", input); 3286 } 3287 } // end scan profiles 3288 3289 if (profiles.isEmpty()) { 3290 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device); 3291 return BAD_VALUE; 3292 } 3293 } else { 3294 // Disconnect 3295 // check if one opened input is not needed any more after disconnecting one device 3296 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) { 3297 desc = mInputs.valueAt(input_index); 3298 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() & 3299 ~AUDIO_DEVICE_BIT_IN)) { 3300 ALOGV("checkInputsForDevice(): disconnecting adding input %d", 3301 mInputs.keyAt(input_index)); 3302 inputs.add(mInputs.keyAt(input_index)); 3303 } 3304 } 3305 // Clear any profiles associated with the disconnected device. 3306 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) { 3307 if (mHwModules[module_index]->mHandle == 0) { 3308 continue; 3309 } 3310 for (size_t profile_index = 0; 3311 profile_index < mHwModules[module_index]->mInputProfiles.size(); 3312 profile_index++) { 3313 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index]; 3314 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) { 3315 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu", 3316 profile_index, module_index); 3317 if (profile->mSamplingRates[0] == 0) { 3318 profile->mSamplingRates.clear(); 3319 profile->mSamplingRates.add(0); 3320 } 3321 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) { 3322 profile->mFormats.clear(); 3323 profile->mFormats.add(AUDIO_FORMAT_DEFAULT); 3324 } 3325 if (profile->mChannelMasks[0] == 0) { 3326 profile->mChannelMasks.clear(); 3327 profile->mChannelMasks.add(0); 3328 } 3329 } 3330 } 3331 } 3332 } // end disconnect 3333 3334 return NO_ERROR; 3335} 3336 3337 3338void AudioPolicyManager::closeOutput(audio_io_handle_t output) 3339{ 3340 ALOGV("closeOutput(%d)", output); 3341 3342 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 3343 if (outputDesc == NULL) { 3344 ALOGW("closeOutput() unknown output %d", output); 3345 return; 3346 } 3347 mPolicyMixes.closeOutput(outputDesc); 3348 3349 // look for duplicated outputs connected to the output being removed. 3350 for (size_t i = 0; i < mOutputs.size(); i++) { 3351 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i); 3352 if (dupOutputDesc->isDuplicated() && 3353 (dupOutputDesc->mOutput1 == outputDesc || 3354 dupOutputDesc->mOutput2 == outputDesc)) { 3355 sp<AudioOutputDescriptor> outputDesc2; 3356 if (dupOutputDesc->mOutput1 == outputDesc) { 3357 outputDesc2 = dupOutputDesc->mOutput2; 3358 } else { 3359 outputDesc2 = dupOutputDesc->mOutput1; 3360 } 3361 // As all active tracks on duplicated output will be deleted, 3362 // and as they were also referenced on the other output, the reference 3363 // count for their stream type must be adjusted accordingly on 3364 // the other output. 3365 for (int j = 0; j < AUDIO_STREAM_CNT; j++) { 3366 int refCount = dupOutputDesc->mRefCount[j]; 3367 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount); 3368 } 3369 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i); 3370 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput); 3371 3372 mpClientInterface->closeOutput(duplicatedOutput); 3373 removeOutput(duplicatedOutput); 3374 } 3375 } 3376 3377 nextAudioPortGeneration(); 3378 3379 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle); 3380 if (index >= 0) { 3381 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 3382 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 3383 mAudioPatches.removeItemsAt(index); 3384 mpClientInterface->onAudioPatchListUpdate(); 3385 } 3386 3387 AudioParameter param; 3388 param.add(String8("closing"), String8("true")); 3389 mpClientInterface->setParameters(output, param.toString()); 3390 3391 mpClientInterface->closeOutput(output); 3392 removeOutput(output); 3393 mPreviousOutputs = mOutputs; 3394} 3395 3396void AudioPolicyManager::closeInput(audio_io_handle_t input) 3397{ 3398 ALOGV("closeInput(%d)", input); 3399 3400 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input); 3401 if (inputDesc == NULL) { 3402 ALOGW("closeInput() unknown input %d", input); 3403 return; 3404 } 3405 3406 nextAudioPortGeneration(); 3407 3408 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle); 3409 if (index >= 0) { 3410 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 3411 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 3412 mAudioPatches.removeItemsAt(index); 3413 mpClientInterface->onAudioPatchListUpdate(); 3414 } 3415 3416 mpClientInterface->closeInput(input); 3417 mInputs.removeItem(input); 3418} 3419 3420SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device, 3421 AudioOutputCollection openOutputs) 3422{ 3423 SortedVector<audio_io_handle_t> outputs; 3424 3425 ALOGVV("getOutputsForDevice() device %04x", device); 3426 for (size_t i = 0; i < openOutputs.size(); i++) { 3427 ALOGVV("output %d isDuplicated=%d device=%04x", 3428 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices()); 3429 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) { 3430 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i)); 3431 outputs.add(openOutputs.keyAt(i)); 3432 } 3433 } 3434 return outputs; 3435} 3436 3437bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1, 3438 SortedVector<audio_io_handle_t>& outputs2) 3439{ 3440 if (outputs1.size() != outputs2.size()) { 3441 return false; 3442 } 3443 for (size_t i = 0; i < outputs1.size(); i++) { 3444 if (outputs1[i] != outputs2[i]) { 3445 return false; 3446 } 3447 } 3448 return true; 3449} 3450 3451void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy) 3452{ 3453 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/); 3454 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/); 3455 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs); 3456 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs); 3457 3458 // also take into account external policy-related changes: add all outputs which are 3459 // associated with policies in the "before" and "after" output vectors 3460 ALOGVV("checkOutputForStrategy(): policy related outputs"); 3461 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) { 3462 const sp<AudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i); 3463 if (desc != 0 && desc->mPolicyMix != NULL) { 3464 srcOutputs.add(desc->mIoHandle); 3465 ALOGVV(" previous outputs: adding %d", desc->mIoHandle); 3466 } 3467 } 3468 for (size_t i = 0 ; i < mOutputs.size() ; i++) { 3469 const sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 3470 if (desc != 0 && desc->mPolicyMix != NULL) { 3471 dstOutputs.add(desc->mIoHandle); 3472 ALOGVV(" new outputs: adding %d", desc->mIoHandle); 3473 } 3474 } 3475 3476 if (!vectorsEqual(srcOutputs,dstOutputs)) { 3477 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d", 3478 strategy, srcOutputs[0], dstOutputs[0]); 3479 // mute strategy while moving tracks from one output to another 3480 for (size_t i = 0; i < srcOutputs.size(); i++) { 3481 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]); 3482 if (isStrategyActive(desc, strategy)) { 3483 setStrategyMute(strategy, true, srcOutputs[i]); 3484 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice); 3485 } 3486 } 3487 3488 // Move effects associated to this strategy from previous output to new output 3489 if (strategy == STRATEGY_MEDIA) { 3490 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs); 3491 SortedVector<audio_io_handle_t> moved; 3492 for (size_t i = 0; i < mEffects.size(); i++) { 3493 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i); 3494 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX && 3495 effectDesc->mIo != fxOutput) { 3496 if (moved.indexOf(effectDesc->mIo) < 0) { 3497 ALOGV("checkOutputForStrategy() moving effect %d to output %d", 3498 mEffects.keyAt(i), fxOutput); 3499 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo, 3500 fxOutput); 3501 moved.add(effectDesc->mIo); 3502 } 3503 effectDesc->mIo = fxOutput; 3504 } 3505 } 3506 } 3507 // Move tracks associated to this strategy from previous output to new output 3508 for (int i = 0; i < AUDIO_STREAM_CNT; i++) { 3509 if (i == AUDIO_STREAM_PATCH) { 3510 continue; 3511 } 3512 if (getStrategy((audio_stream_type_t)i) == strategy) { 3513 mpClientInterface->invalidateStream((audio_stream_type_t)i); 3514 } 3515 } 3516 } 3517} 3518 3519void AudioPolicyManager::checkOutputForAllStrategies() 3520{ 3521 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) 3522 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE); 3523 checkOutputForStrategy(STRATEGY_PHONE); 3524 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) 3525 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE); 3526 checkOutputForStrategy(STRATEGY_SONIFICATION); 3527 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL); 3528 checkOutputForStrategy(STRATEGY_ACCESSIBILITY); 3529 checkOutputForStrategy(STRATEGY_MEDIA); 3530 checkOutputForStrategy(STRATEGY_DTMF); 3531 checkOutputForStrategy(STRATEGY_REROUTING); 3532} 3533 3534void AudioPolicyManager::checkA2dpSuspend() 3535{ 3536 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput(); 3537 if (a2dpOutput == 0) { 3538 mA2dpSuspended = false; 3539 return; 3540 } 3541 3542 bool isScoConnected = 3543 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET & 3544 ~AUDIO_DEVICE_BIT_IN) != 0) || 3545 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0); 3546 // suspend A2DP output if: 3547 // (NOT already suspended) && 3548 // ((SCO device is connected && 3549 // (forced usage for communication || for record is SCO))) || 3550 // (phone state is ringing || in call) 3551 // 3552 // restore A2DP output if: 3553 // (Already suspended) && 3554 // ((SCO device is NOT connected || 3555 // (forced usage NOT for communication && NOT for record is SCO))) && 3556 // (phone state is NOT ringing && NOT in call) 3557 // 3558 if (mA2dpSuspended) { 3559 if ((!isScoConnected || 3560 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != AUDIO_POLICY_FORCE_BT_SCO) && 3561 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != AUDIO_POLICY_FORCE_BT_SCO))) && 3562 ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) && 3563 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) { 3564 3565 mpClientInterface->restoreOutput(a2dpOutput); 3566 mA2dpSuspended = false; 3567 } 3568 } else { 3569 if ((isScoConnected && 3570 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) || 3571 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO))) || 3572 ((mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) || 3573 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) { 3574 3575 mpClientInterface->suspendOutput(a2dpOutput); 3576 mA2dpSuspended = true; 3577 } 3578 } 3579} 3580 3581audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache) 3582{ 3583 audio_devices_t device = AUDIO_DEVICE_NONE; 3584 3585 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 3586 3587 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle); 3588 if (index >= 0) { 3589 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 3590 if (patchDesc->mUid != mUidCached) { 3591 ALOGV("getNewOutputDevice() device %08x forced by patch %d", 3592 outputDesc->device(), outputDesc->mPatchHandle); 3593 return outputDesc->device(); 3594 } 3595 } 3596 3597 // check the following by order of priority to request a routing change if necessary: 3598 // 1: the strategy enforced audible is active and enforced on the output: 3599 // use device for strategy enforced audible 3600 // 2: we are in call or the strategy phone is active on the output: 3601 // use device for strategy phone 3602 // 3: the strategy for enforced audible is active but not enforced on the output: 3603 // use the device for strategy enforced audible 3604 // 4: the strategy sonification is active on the output: 3605 // use device for strategy sonification 3606 // 5: the strategy "respectful" sonification is active on the output: 3607 // use device for strategy "respectful" sonification 3608 // 6: the strategy accessibility is active on the output: 3609 // use device for strategy accessibility 3610 // 7: the strategy media is active on the output: 3611 // use device for strategy media 3612 // 8: the strategy DTMF is active on the output: 3613 // use device for strategy DTMF 3614 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output: 3615 // use device for strategy t-t-s 3616 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) && 3617 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) { 3618 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache); 3619 } else if (isInCall() || 3620 isStrategyActive(outputDesc, STRATEGY_PHONE)) { 3621 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache); 3622 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) { 3623 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache); 3624 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) { 3625 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache); 3626 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) { 3627 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache); 3628 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) { 3629 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache); 3630 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) { 3631 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache); 3632 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) { 3633 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache); 3634 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) { 3635 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache); 3636 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) { 3637 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache); 3638 } 3639 3640 ALOGV("getNewOutputDevice() selected device %x", device); 3641 return device; 3642} 3643 3644audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input) 3645{ 3646 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input); 3647 3648 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle); 3649 if (index >= 0) { 3650 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 3651 if (patchDesc->mUid != mUidCached) { 3652 ALOGV("getNewInputDevice() device %08x forced by patch %d", 3653 inputDesc->mDevice, inputDesc->mPatchHandle); 3654 return inputDesc->mDevice; 3655 } 3656 } 3657 3658 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->mInputSource); 3659 3660 ALOGV("getNewInputDevice() selected device %x", device); 3661 return device; 3662} 3663 3664uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) { 3665 return (uint32_t)getStrategy(stream); 3666} 3667 3668audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) { 3669 // By checking the range of stream before calling getStrategy, we avoid 3670 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE 3671 // and then return STRATEGY_MEDIA, but we want to return the empty set. 3672 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) { 3673 return AUDIO_DEVICE_NONE; 3674 } 3675 audio_devices_t devices; 3676 routing_strategy strategy = getStrategy(stream); 3677 devices = getDeviceForStrategy(strategy, true /*fromCache*/); 3678 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs); 3679 for (size_t i = 0; i < outputs.size(); i++) { 3680 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]); 3681 if (isStrategyActive(outputDesc, strategy)) { 3682 devices = outputDesc->device(); 3683 break; 3684 } 3685 } 3686 3687 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it 3688 and doesn't really need to.*/ 3689 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) { 3690 devices |= AUDIO_DEVICE_OUT_SPEAKER; 3691 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE; 3692 } 3693 3694 return devices; 3695} 3696 3697routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const 3698{ 3699 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH"); 3700 return mEngine->getStrategyForStream(stream); 3701} 3702 3703uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) { 3704 // flags to strategy mapping 3705 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) { 3706 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER; 3707 } 3708 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) { 3709 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE; 3710 } 3711 // usage to strategy mapping 3712 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage)); 3713} 3714 3715void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) { 3716 switch(stream) { 3717 case AUDIO_STREAM_MUSIC: 3718 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL); 3719 updateDevicesAndOutputs(); 3720 break; 3721 default: 3722 break; 3723 } 3724} 3725 3726uint32_t AudioPolicyManager::handleEventForBeacon(int event) { 3727 switch(event) { 3728 case STARTING_OUTPUT: 3729 mBeaconMuteRefCount++; 3730 break; 3731 case STOPPING_OUTPUT: 3732 if (mBeaconMuteRefCount > 0) { 3733 mBeaconMuteRefCount--; 3734 } 3735 break; 3736 case STARTING_BEACON: 3737 mBeaconPlayingRefCount++; 3738 break; 3739 case STOPPING_BEACON: 3740 if (mBeaconPlayingRefCount > 0) { 3741 mBeaconPlayingRefCount--; 3742 } 3743 break; 3744 } 3745 3746 if (mBeaconMuteRefCount > 0) { 3747 // any playback causes beacon to be muted 3748 return setBeaconMute(true); 3749 } else { 3750 // no other playback: unmute when beacon starts playing, mute when it stops 3751 return setBeaconMute(mBeaconPlayingRefCount == 0); 3752 } 3753} 3754 3755uint32_t AudioPolicyManager::setBeaconMute(bool mute) { 3756 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d", 3757 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount); 3758 // keep track of muted state to avoid repeating mute/unmute operations 3759 if (mBeaconMuted != mute) { 3760 // mute/unmute AUDIO_STREAM_TTS on all outputs 3761 ALOGV("\t muting %d", mute); 3762 uint32_t maxLatency = 0; 3763 for (size_t i = 0; i < mOutputs.size(); i++) { 3764 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 3765 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/, 3766 desc->mIoHandle, 3767 0 /*delay*/, AUDIO_DEVICE_NONE); 3768 const uint32_t latency = desc->latency() * 2; 3769 if (latency > maxLatency) { 3770 maxLatency = latency; 3771 } 3772 } 3773 mBeaconMuted = mute; 3774 return maxLatency; 3775 } 3776 return 0; 3777} 3778 3779audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy, 3780 bool fromCache) 3781{ 3782 if (fromCache) { 3783 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x", 3784 strategy, mDeviceForStrategy[strategy]); 3785 return mDeviceForStrategy[strategy]; 3786 } 3787 return mEngine->getDeviceForStrategy(strategy); 3788} 3789 3790void AudioPolicyManager::updateDevicesAndOutputs() 3791{ 3792 for (int i = 0; i < NUM_STRATEGIES; i++) { 3793 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/); 3794 } 3795 mPreviousOutputs = mOutputs; 3796} 3797 3798uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc, 3799 audio_devices_t prevDevice, 3800 uint32_t delayMs) 3801{ 3802 // mute/unmute strategies using an incompatible device combination 3803 // if muting, wait for the audio in pcm buffer to be drained before proceeding 3804 // if unmuting, unmute only after the specified delay 3805 if (outputDesc->isDuplicated()) { 3806 return 0; 3807 } 3808 3809 uint32_t muteWaitMs = 0; 3810 audio_devices_t device = outputDesc->device(); 3811 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2); 3812 3813 for (size_t i = 0; i < NUM_STRATEGIES; i++) { 3814 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/); 3815 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types(); 3816 bool mute = shouldMute && (curDevice & device) && (curDevice != device); 3817 bool doMute = false; 3818 3819 if (mute && !outputDesc->mStrategyMutedByDevice[i]) { 3820 doMute = true; 3821 outputDesc->mStrategyMutedByDevice[i] = true; 3822 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){ 3823 doMute = true; 3824 outputDesc->mStrategyMutedByDevice[i] = false; 3825 } 3826 if (doMute) { 3827 for (size_t j = 0; j < mOutputs.size(); j++) { 3828 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j); 3829 // skip output if it does not share any device with current output 3830 if ((desc->supportedDevices() & outputDesc->supportedDevices()) 3831 == AUDIO_DEVICE_NONE) { 3832 continue; 3833 } 3834 audio_io_handle_t curOutput = mOutputs.keyAt(j); 3835 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d", 3836 mute ? "muting" : "unmuting", i, curDevice, curOutput); 3837 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs); 3838 if (isStrategyActive(desc, (routing_strategy)i)) { 3839 if (mute) { 3840 // FIXME: should not need to double latency if volume could be applied 3841 // immediately by the audioflinger mixer. We must account for the delay 3842 // between now and the next time the audioflinger thread for this output 3843 // will process a buffer (which corresponds to one buffer size, 3844 // usually 1/2 or 1/4 of the latency). 3845 if (muteWaitMs < desc->latency() * 2) { 3846 muteWaitMs = desc->latency() * 2; 3847 } 3848 } 3849 } 3850 } 3851 } 3852 } 3853 3854 // temporary mute output if device selection changes to avoid volume bursts due to 3855 // different per device volumes 3856 if (outputDesc->isActive() && (device != prevDevice)) { 3857 if (muteWaitMs < outputDesc->latency() * 2) { 3858 muteWaitMs = outputDesc->latency() * 2; 3859 } 3860 for (size_t i = 0; i < NUM_STRATEGIES; i++) { 3861 if (isStrategyActive(outputDesc, (routing_strategy)i)) { 3862 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle); 3863 // do tempMute unmute after twice the mute wait time 3864 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle, 3865 muteWaitMs *2, device); 3866 } 3867 } 3868 } 3869 3870 // wait for the PCM output buffers to empty before proceeding with the rest of the command 3871 if (muteWaitMs > delayMs) { 3872 muteWaitMs -= delayMs; 3873 usleep(muteWaitMs * 1000); 3874 return muteWaitMs; 3875 } 3876 return 0; 3877} 3878 3879uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output, 3880 audio_devices_t device, 3881 bool force, 3882 int delayMs, 3883 audio_patch_handle_t *patchHandle, 3884 const char* address) 3885{ 3886 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs); 3887 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 3888 AudioParameter param; 3889 uint32_t muteWaitMs; 3890 3891 if (outputDesc->isDuplicated()) { 3892 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs); 3893 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs); 3894 return muteWaitMs; 3895 } 3896 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current 3897 // output profile 3898 if ((device != AUDIO_DEVICE_NONE) && 3899 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) { 3900 return 0; 3901 } 3902 3903 // filter devices according to output selected 3904 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types()); 3905 3906 audio_devices_t prevDevice = outputDesc->mDevice; 3907 3908 ALOGV("setOutputDevice() prevDevice %04x", prevDevice); 3909 3910 if (device != AUDIO_DEVICE_NONE) { 3911 outputDesc->mDevice = device; 3912 } 3913 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs); 3914 3915 // Do not change the routing if: 3916 // the requested device is AUDIO_DEVICE_NONE 3917 // OR the requested device is the same as current device 3918 // AND force is not specified 3919 // AND the output is connected by a valid audio patch. 3920 // Doing this check here allows the caller to call setOutputDevice() without conditions 3921 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force && 3922 outputDesc->mPatchHandle != 0) { 3923 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", 3924 device, output); 3925 return muteWaitMs; 3926 } 3927 3928 ALOGV("setOutputDevice() changing device"); 3929 3930 // do the routing 3931 if (device == AUDIO_DEVICE_NONE) { 3932 resetOutputDevice(output, delayMs, NULL); 3933 } else { 3934 DeviceVector deviceList = (address == NULL) ? 3935 mAvailableOutputDevices.getDevicesFromType(device) 3936 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address)); 3937 if (!deviceList.isEmpty()) { 3938 struct audio_patch patch; 3939 outputDesc->toAudioPortConfig(&patch.sources[0]); 3940 patch.num_sources = 1; 3941 patch.num_sinks = 0; 3942 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) { 3943 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]); 3944 patch.num_sinks++; 3945 } 3946 ssize_t index; 3947 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) { 3948 index = mAudioPatches.indexOfKey(*patchHandle); 3949 } else { 3950 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle); 3951 } 3952 sp< AudioPatch> patchDesc; 3953 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 3954 if (index >= 0) { 3955 patchDesc = mAudioPatches.valueAt(index); 3956 afPatchHandle = patchDesc->mAfPatchHandle; 3957 } 3958 3959 status_t status = mpClientInterface->createAudioPatch(&patch, 3960 &afPatchHandle, 3961 delayMs); 3962 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d" 3963 "num_sources %d num_sinks %d", 3964 status, afPatchHandle, patch.num_sources, patch.num_sinks); 3965 if (status == NO_ERROR) { 3966 if (index < 0) { 3967 patchDesc = new AudioPatch(&patch, mUidCached); 3968 addAudioPatch(patchDesc->mHandle, patchDesc); 3969 } else { 3970 patchDesc->mPatch = patch; 3971 } 3972 patchDesc->mAfPatchHandle = afPatchHandle; 3973 patchDesc->mUid = mUidCached; 3974 if (patchHandle) { 3975 *patchHandle = patchDesc->mHandle; 3976 } 3977 outputDesc->mPatchHandle = patchDesc->mHandle; 3978 nextAudioPortGeneration(); 3979 mpClientInterface->onAudioPatchListUpdate(); 3980 } 3981 } 3982 3983 // inform all input as well 3984 for (size_t i = 0; i < mInputs.size(); i++) { 3985 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i); 3986 if (!is_virtual_input_device(inputDescriptor->mDevice)) { 3987 AudioParameter inputCmd = AudioParameter(); 3988 ALOGV("%s: inform input %d of device:%d", __func__, 3989 inputDescriptor->mIoHandle, device); 3990 inputCmd.addInt(String8(AudioParameter::keyRouting),device); 3991 mpClientInterface->setParameters(inputDescriptor->mIoHandle, 3992 inputCmd.toString(), 3993 delayMs); 3994 } 3995 } 3996 } 3997 3998 // update stream volumes according to new device 3999 applyStreamVolumes(output, device, delayMs); 4000 4001 return muteWaitMs; 4002} 4003 4004status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output, 4005 int delayMs, 4006 audio_patch_handle_t *patchHandle) 4007{ 4008 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 4009 ssize_t index; 4010 if (patchHandle) { 4011 index = mAudioPatches.indexOfKey(*patchHandle); 4012 } else { 4013 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle); 4014 } 4015 if (index < 0) { 4016 return INVALID_OPERATION; 4017 } 4018 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index); 4019 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs); 4020 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status); 4021 outputDesc->mPatchHandle = 0; 4022 removeAudioPatch(patchDesc->mHandle); 4023 nextAudioPortGeneration(); 4024 mpClientInterface->onAudioPatchListUpdate(); 4025 return status; 4026} 4027 4028status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input, 4029 audio_devices_t device, 4030 bool force, 4031 audio_patch_handle_t *patchHandle) 4032{ 4033 status_t status = NO_ERROR; 4034 4035 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input); 4036 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) { 4037 inputDesc->mDevice = device; 4038 4039 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device); 4040 if (!deviceList.isEmpty()) { 4041 struct audio_patch patch; 4042 inputDesc->toAudioPortConfig(&patch.sinks[0]); 4043 // AUDIO_SOURCE_HOTWORD is for internal use only: 4044 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL 4045 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD && 4046 !inputDesc->mIsSoundTrigger) { 4047 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION; 4048 } 4049 patch.num_sinks = 1; 4050 //only one input device for now 4051 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]); 4052 patch.num_sources = 1; 4053 ssize_t index; 4054 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) { 4055 index = mAudioPatches.indexOfKey(*patchHandle); 4056 } else { 4057 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle); 4058 } 4059 sp< AudioPatch> patchDesc; 4060 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 4061 if (index >= 0) { 4062 patchDesc = mAudioPatches.valueAt(index); 4063 afPatchHandle = patchDesc->mAfPatchHandle; 4064 } 4065 4066 status_t status = mpClientInterface->createAudioPatch(&patch, 4067 &afPatchHandle, 4068 0); 4069 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d", 4070 status, afPatchHandle); 4071 if (status == NO_ERROR) { 4072 if (index < 0) { 4073 patchDesc = new AudioPatch(&patch, mUidCached); 4074 addAudioPatch(patchDesc->mHandle, patchDesc); 4075 } else { 4076 patchDesc->mPatch = patch; 4077 } 4078 patchDesc->mAfPatchHandle = afPatchHandle; 4079 patchDesc->mUid = mUidCached; 4080 if (patchHandle) { 4081 *patchHandle = patchDesc->mHandle; 4082 } 4083 inputDesc->mPatchHandle = patchDesc->mHandle; 4084 nextAudioPortGeneration(); 4085 mpClientInterface->onAudioPatchListUpdate(); 4086 } 4087 } 4088 } 4089 return status; 4090} 4091 4092status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input, 4093 audio_patch_handle_t *patchHandle) 4094{ 4095 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input); 4096 ssize_t index; 4097 if (patchHandle) { 4098 index = mAudioPatches.indexOfKey(*patchHandle); 4099 } else { 4100 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle); 4101 } 4102 if (index < 0) { 4103 return INVALID_OPERATION; 4104 } 4105 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index); 4106 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 4107 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status); 4108 inputDesc->mPatchHandle = 0; 4109 removeAudioPatch(patchDesc->mHandle); 4110 nextAudioPortGeneration(); 4111 mpClientInterface->onAudioPatchListUpdate(); 4112 return status; 4113} 4114 4115sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device, 4116 String8 address, 4117 uint32_t& samplingRate, 4118 audio_format_t format, 4119 audio_channel_mask_t channelMask, 4120 audio_input_flags_t flags) 4121{ 4122 // Choose an input profile based on the requested capture parameters: select the first available 4123 // profile supporting all requested parameters. 4124 4125 for (size_t i = 0; i < mHwModules.size(); i++) 4126 { 4127 if (mHwModules[i]->mHandle == 0) { 4128 continue; 4129 } 4130 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) 4131 { 4132 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j]; 4133 // profile->log(); 4134 if (profile->isCompatibleProfile(device, address, samplingRate, 4135 &samplingRate /*updatedSamplingRate*/, 4136 format, channelMask, (audio_output_flags_t) flags)) { 4137 4138 return profile; 4139 } 4140 } 4141 } 4142 return NULL; 4143} 4144 4145 4146audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource, 4147 AudioMix **policyMix) 4148{ 4149 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN; 4150 audio_devices_t selectedDeviceFromMix = 4151 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix); 4152 4153 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) { 4154 return selectedDeviceFromMix; 4155 } 4156 return getDeviceForInputSource(inputSource); 4157} 4158 4159audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource) 4160{ 4161 return mEngine->getDeviceForInputSource(inputSource); 4162} 4163 4164float AudioPolicyManager::computeVolume(audio_stream_type_t stream, 4165 int index, 4166 audio_io_handle_t output, 4167 audio_devices_t device) 4168{ 4169 float volume = 1.0; 4170 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 4171 4172 if (device == AUDIO_DEVICE_NONE) { 4173 device = outputDesc->device(); 4174 } 4175 volume = mEngine->volIndexToAmpl(Volume::getDeviceCategory(device), stream, index); 4176 4177 // if a headset is connected, apply the following rules to ring tones and notifications 4178 // to avoid sound level bursts in user's ears: 4179 // - always attenuate ring tones and notifications volume by 6dB 4180 // - if music is playing, always limit the volume to current music volume, 4181 // with a minimum threshold at -36dB so that notification is always perceived. 4182 const routing_strategy stream_strategy = getStrategy(stream); 4183 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP | 4184 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES | 4185 AUDIO_DEVICE_OUT_WIRED_HEADSET | 4186 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) && 4187 ((stream_strategy == STRATEGY_SONIFICATION) 4188 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL) 4189 || (stream == AUDIO_STREAM_SYSTEM) 4190 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) && 4191 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) && 4192 mStreams.canBeMuted(stream)) { 4193 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR; 4194 // when the phone is ringing we must consider that music could have been paused just before 4195 // by the music application and behave as if music was active if the last music track was 4196 // just stopped 4197 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) || 4198 mLimitRingtoneVolume) { 4199 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/); 4200 float musicVol = computeVolume(AUDIO_STREAM_MUSIC, 4201 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice), 4202 output, 4203 musicDevice); 4204 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? 4205 musicVol : SONIFICATION_HEADSET_VOLUME_MIN; 4206 if (volume > minVol) { 4207 volume = minVol; 4208 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol); 4209 } 4210 } 4211 } 4212 4213 return volume; 4214} 4215 4216status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream, 4217 int index, 4218 audio_io_handle_t output, 4219 audio_devices_t device, 4220 int delayMs, 4221 bool force) 4222{ 4223 4224 // do not change actual stream volume if the stream is muted 4225 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) { 4226 ALOGVV("checkAndSetVolume() stream %d muted count %d", 4227 stream, mOutputs.valueFor(output)->mMuteCount[stream]); 4228 return NO_ERROR; 4229 } 4230 audio_policy_forced_cfg_t forceUseForComm = 4231 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION); 4232 // do not change in call volume if bluetooth is connected and vice versa 4233 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) || 4234 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) { 4235 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm", 4236 stream, forceUseForComm); 4237 return INVALID_OPERATION; 4238 } 4239 4240 float volume = computeVolume(stream, index, output, device); 4241 // unit gain if rerouting to external policy 4242 if (device == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) { 4243 ssize_t index = mOutputs.indexOfKey(output); 4244 if (index >= 0) { 4245 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index); 4246 if (outputDesc->mPolicyMix != NULL) { 4247 ALOGV("max gain when rerouting for output=%d", output); 4248 volume = 1.0f; 4249 } 4250 } 4251 4252 } 4253 // We actually change the volume if: 4254 // - the float value returned by computeVolume() changed 4255 // - the force flag is set 4256 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] || 4257 force) { 4258 mOutputs.valueFor(output)->mCurVolume[stream] = volume; 4259 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs); 4260 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is 4261 // enabled 4262 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) { 4263 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs); 4264 } 4265 mpClientInterface->setStreamVolume(stream, volume, output, delayMs); 4266 } 4267 4268 if (stream == AUDIO_STREAM_VOICE_CALL || 4269 stream == AUDIO_STREAM_BLUETOOTH_SCO) { 4270 float voiceVolume; 4271 // Force voice volume to max for bluetooth SCO as volume is managed by the headset 4272 if (stream == AUDIO_STREAM_VOICE_CALL) { 4273 voiceVolume = (float)index/(float)mStreams[stream].getVolumeIndexMax(); 4274 } else { 4275 voiceVolume = 1.0; 4276 } 4277 4278 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) { 4279 mpClientInterface->setVoiceVolume(voiceVolume, delayMs); 4280 mLastVoiceVolume = voiceVolume; 4281 } 4282 } 4283 4284 return NO_ERROR; 4285} 4286 4287void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output, 4288 audio_devices_t device, 4289 int delayMs, 4290 bool force) 4291{ 4292 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device); 4293 4294 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) { 4295 if (stream == AUDIO_STREAM_PATCH) { 4296 continue; 4297 } 4298 checkAndSetVolume((audio_stream_type_t)stream, 4299 mStreams[stream].getVolumeIndex(device), 4300 output, 4301 device, 4302 delayMs, 4303 force); 4304 } 4305} 4306 4307void AudioPolicyManager::setStrategyMute(routing_strategy strategy, 4308 bool on, 4309 audio_io_handle_t output, 4310 int delayMs, 4311 audio_devices_t device) 4312{ 4313 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output); 4314 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) { 4315 if (stream == AUDIO_STREAM_PATCH) { 4316 continue; 4317 } 4318 if (getStrategy((audio_stream_type_t)stream) == strategy) { 4319 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device); 4320 } 4321 } 4322} 4323 4324void AudioPolicyManager::setStreamMute(audio_stream_type_t stream, 4325 bool on, 4326 audio_io_handle_t output, 4327 int delayMs, 4328 audio_devices_t device) 4329{ 4330 const StreamDescriptor &streamDesc = mStreams[stream]; 4331 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 4332 if (device == AUDIO_DEVICE_NONE) { 4333 device = outputDesc->device(); 4334 } 4335 4336 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x", 4337 stream, on, output, outputDesc->mMuteCount[stream], device); 4338 4339 if (on) { 4340 if (outputDesc->mMuteCount[stream] == 0) { 4341 if (streamDesc.canBeMuted() && 4342 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) || 4343 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) { 4344 checkAndSetVolume(stream, 0, output, device, delayMs); 4345 } 4346 } 4347 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored 4348 outputDesc->mMuteCount[stream]++; 4349 } else { 4350 if (outputDesc->mMuteCount[stream] == 0) { 4351 ALOGV("setStreamMute() unmuting non muted stream!"); 4352 return; 4353 } 4354 if (--outputDesc->mMuteCount[stream] == 0) { 4355 checkAndSetVolume(stream, 4356 streamDesc.getVolumeIndex(device), 4357 output, 4358 device, 4359 delayMs); 4360 } 4361 } 4362} 4363 4364void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream, 4365 bool starting, bool stateChange) 4366{ 4367 // if the stream pertains to sonification strategy and we are in call we must 4368 // mute the stream if it is low visibility. If it is high visibility, we must play a tone 4369 // in the device used for phone strategy and play the tone if the selected device does not 4370 // interfere with the device used for phone strategy 4371 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as 4372 // many times as there are active tracks on the output 4373 const routing_strategy stream_strategy = getStrategy(stream); 4374 if ((stream_strategy == STRATEGY_SONIFICATION) || 4375 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) { 4376 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput); 4377 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d", 4378 stream, starting, outputDesc->mDevice, stateChange); 4379 if (outputDesc->mRefCount[stream]) { 4380 int muteCount = 1; 4381 if (stateChange) { 4382 muteCount = outputDesc->mRefCount[stream]; 4383 } 4384 if (audio_is_low_visibility(stream)) { 4385 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount); 4386 for (int i = 0; i < muteCount; i++) { 4387 setStreamMute(stream, starting, mPrimaryOutput); 4388 } 4389 } else { 4390 ALOGV("handleIncallSonification() high visibility"); 4391 if (outputDesc->device() & 4392 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) { 4393 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount); 4394 for (int i = 0; i < muteCount; i++) { 4395 setStreamMute(stream, starting, mPrimaryOutput); 4396 } 4397 } 4398 if (starting) { 4399 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION, 4400 AUDIO_STREAM_VOICE_CALL); 4401 } else { 4402 mpClientInterface->stopTone(); 4403 } 4404 } 4405 } 4406 } 4407} 4408 4409void AudioPolicyManager::defaultAudioPolicyConfig(void) 4410{ 4411 sp<HwModule> module; 4412 sp<IOProfile> profile; 4413 sp<DeviceDescriptor> defaultInputDevice = 4414 new DeviceDescriptor(String8("builtin-mic"), AUDIO_DEVICE_IN_BUILTIN_MIC); 4415 mAvailableOutputDevices.add(mDefaultOutputDevice); 4416 mAvailableInputDevices.add(defaultInputDevice); 4417 4418 module = new HwModule("primary"); 4419 4420 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module); 4421 profile->mSamplingRates.add(44100); 4422 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT); 4423 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO); 4424 profile->mSupportedDevices.add(mDefaultOutputDevice); 4425 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY; 4426 module->mOutputProfiles.add(profile); 4427 4428 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module); 4429 profile->mSamplingRates.add(8000); 4430 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT); 4431 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO); 4432 profile->mSupportedDevices.add(defaultInputDevice); 4433 module->mInputProfiles.add(profile); 4434 4435 mHwModules.add(module); 4436} 4437 4438audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr) 4439{ 4440 // flags to stream type mapping 4441 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) { 4442 return AUDIO_STREAM_ENFORCED_AUDIBLE; 4443 } 4444 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) { 4445 return AUDIO_STREAM_BLUETOOTH_SCO; 4446 } 4447 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) { 4448 return AUDIO_STREAM_TTS; 4449 } 4450 4451 // usage to stream type mapping 4452 switch (attr->usage) { 4453 case AUDIO_USAGE_MEDIA: 4454 case AUDIO_USAGE_GAME: 4455 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE: 4456 return AUDIO_STREAM_MUSIC; 4457 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY: 4458 if (isStreamActive(AUDIO_STREAM_ALARM)) { 4459 return AUDIO_STREAM_ALARM; 4460 } 4461 if (isStreamActive(AUDIO_STREAM_RING)) { 4462 return AUDIO_STREAM_RING; 4463 } 4464 if (isInCall()) { 4465 return AUDIO_STREAM_VOICE_CALL; 4466 } 4467 return AUDIO_STREAM_ACCESSIBILITY; 4468 case AUDIO_USAGE_ASSISTANCE_SONIFICATION: 4469 return AUDIO_STREAM_SYSTEM; 4470 case AUDIO_USAGE_VOICE_COMMUNICATION: 4471 return AUDIO_STREAM_VOICE_CALL; 4472 4473 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING: 4474 return AUDIO_STREAM_DTMF; 4475 4476 case AUDIO_USAGE_ALARM: 4477 return AUDIO_STREAM_ALARM; 4478 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE: 4479 return AUDIO_STREAM_RING; 4480 4481 case AUDIO_USAGE_NOTIFICATION: 4482 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST: 4483 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT: 4484 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED: 4485 case AUDIO_USAGE_NOTIFICATION_EVENT: 4486 return AUDIO_STREAM_NOTIFICATION; 4487 4488 case AUDIO_USAGE_UNKNOWN: 4489 default: 4490 return AUDIO_STREAM_MUSIC; 4491 } 4492} 4493 4494bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) 4495{ 4496 // has flags that map to a strategy? 4497 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) { 4498 return true; 4499 } 4500 4501 // has known usage? 4502 switch (paa->usage) { 4503 case AUDIO_USAGE_UNKNOWN: 4504 case AUDIO_USAGE_MEDIA: 4505 case AUDIO_USAGE_VOICE_COMMUNICATION: 4506 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING: 4507 case AUDIO_USAGE_ALARM: 4508 case AUDIO_USAGE_NOTIFICATION: 4509 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE: 4510 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST: 4511 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT: 4512 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED: 4513 case AUDIO_USAGE_NOTIFICATION_EVENT: 4514 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY: 4515 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE: 4516 case AUDIO_USAGE_ASSISTANCE_SONIFICATION: 4517 case AUDIO_USAGE_GAME: 4518 case AUDIO_USAGE_VIRTUAL_SOURCE: 4519 break; 4520 default: 4521 return false; 4522 } 4523 return true; 4524} 4525 4526bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor> outputDesc, 4527 routing_strategy strategy, uint32_t inPastMs, 4528 nsecs_t sysTime) const 4529{ 4530 if ((sysTime == 0) && (inPastMs != 0)) { 4531 sysTime = systemTime(); 4532 } 4533 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) { 4534 if (i == AUDIO_STREAM_PATCH) { 4535 continue; 4536 } 4537 if (((getStrategy((audio_stream_type_t)i) == strategy) || 4538 (NUM_STRATEGIES == strategy)) && 4539 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) { 4540 return true; 4541 } 4542 } 4543 return false; 4544} 4545 4546audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage) 4547{ 4548 return mEngine->getForceUse(usage); 4549} 4550 4551bool AudioPolicyManager::isInCall() 4552{ 4553 return isStateInCall(mEngine->getPhoneState()); 4554} 4555 4556bool AudioPolicyManager::isStateInCall(int state) 4557{ 4558 return is_state_in_call(state); 4559} 4560 4561}; // namespace android 4562