AudioPolicyManager.cpp revision 8e1d94daf47a3b2b9358c82b26590cc995233681
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#define AUDIO_POLICY_XML_CONFIG_FILE "/system/etc/audio_policy_configuration.xml" 28 29#include <inttypes.h> 30#include <math.h> 31 32#include <AudioPolicyManagerInterface.h> 33#include <AudioPolicyEngineInstance.h> 34#include <cutils/properties.h> 35#include <utils/Log.h> 36#include <hardware/audio.h> 37#include <hardware/audio_effect.h> 38#include <media/AudioParameter.h> 39#include <media/AudioPolicyHelper.h> 40#include <soundtrigger/SoundTrigger.h> 41#include "AudioPolicyManager.h" 42#ifndef USE_XML_AUDIO_POLICY_CONF 43#include <ConfigParsingUtils.h> 44#include <StreamDescriptor.h> 45#endif 46#include <Serializer.h> 47#include "TypeConverter.h" 48#include <policy.h> 49 50namespace android { 51 52//FIXME: workaround for truncated touch sounds 53// to be removed when the problem is handled by system UI 54#define TOUCH_SOUND_FIXED_DELAY_MS 100 55// ---------------------------------------------------------------------------- 56// AudioPolicyInterface implementation 57// ---------------------------------------------------------------------------- 58 59status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device, 60 audio_policy_dev_state_t state, 61 const char *device_address, 62 const char *device_name) 63{ 64 return setDeviceConnectionStateInt(device, state, device_address, device_name); 65} 66 67void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device, 68 audio_policy_dev_state_t state, 69 const String8 &device_address) 70{ 71 AudioParameter param(device_address); 72 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ? 73 AUDIO_PARAMETER_DEVICE_CONNECT : AUDIO_PARAMETER_DEVICE_DISCONNECT); 74 param.addInt(key, device); 75 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString()); 76} 77 78status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device, 79 audio_policy_dev_state_t state, 80 const char *device_address, 81 const char *device_name) 82{ 83 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s", 84- device, state, device_address, device_name); 85 86 // connect/disconnect only 1 device at a time 87 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE; 88 89 sp<DeviceDescriptor> devDesc = 90 mHwModules.getDeviceDescriptor(device, device_address, device_name); 91 92 // handle output devices 93 if (audio_is_output_device(device)) { 94 SortedVector <audio_io_handle_t> outputs; 95 96 ssize_t index = mAvailableOutputDevices.indexOf(devDesc); 97 98 // save a copy of the opened output descriptors before any output is opened or closed 99 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies() 100 mPreviousOutputs = mOutputs; 101 switch (state) 102 { 103 // handle output device connection 104 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: { 105 if (index >= 0) { 106 ALOGW("setDeviceConnectionState() device already connected: %x", device); 107 return INVALID_OPERATION; 108 } 109 ALOGV("setDeviceConnectionState() connecting device %x", device); 110 111 // register new device as available 112 index = mAvailableOutputDevices.add(devDesc); 113 if (index >= 0) { 114 sp<HwModule> module = mHwModules.getModuleForDevice(device); 115 if (module == 0) { 116 ALOGD("setDeviceConnectionState() could not find HW module for device %08x", 117 device); 118 mAvailableOutputDevices.remove(devDesc); 119 return INVALID_OPERATION; 120 } 121 mAvailableOutputDevices[index]->attach(module); 122 } else { 123 return NO_MEMORY; 124 } 125 126 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic 127 // parameters on newly connected devices (instead of opening the outputs...) 128 broadcastDeviceConnectionState(device, state, devDesc->mAddress); 129 130 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) { 131 mAvailableOutputDevices.remove(devDesc); 132 133 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, 134 devDesc->mAddress); 135 return INVALID_OPERATION; 136 } 137 // Propagate device availability to Engine 138 mEngine->setDeviceConnectionState(devDesc, state); 139 140 // outputs should never be empty here 141 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():" 142 "checkOutputsForDevice() returned no outputs but status OK"); 143 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs", 144 outputs.size()); 145 146 } break; 147 // handle output device disconnection 148 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: { 149 if (index < 0) { 150 ALOGW("setDeviceConnectionState() device not connected: %x", device); 151 return INVALID_OPERATION; 152 } 153 154 ALOGV("setDeviceConnectionState() disconnecting output device %x", device); 155 156 // Send Disconnect to HALs 157 broadcastDeviceConnectionState(device, state, devDesc->mAddress); 158 159 // remove device from available output devices 160 mAvailableOutputDevices.remove(devDesc); 161 162 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress); 163 164 // Propagate device availability to Engine 165 mEngine->setDeviceConnectionState(devDesc, state); 166 } break; 167 168 default: 169 ALOGE("setDeviceConnectionState() invalid state: %x", state); 170 return BAD_VALUE; 171 } 172 173 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP 174 // output is suspended before any tracks are moved to it 175 checkA2dpSuspend(); 176 checkOutputForAllStrategies(); 177 // outputs must be closed after checkOutputForAllStrategies() is executed 178 if (!outputs.isEmpty()) { 179 for (size_t i = 0; i < outputs.size(); i++) { 180 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]); 181 // close unused outputs after device disconnection or direct outputs that have been 182 // opened by checkOutputsForDevice() to query dynamic parameters 183 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) || 184 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) && 185 (desc->mDirectOpenCount == 0))) { 186 closeOutput(outputs[i]); 187 } 188 } 189 // check again after closing A2DP output to reset mA2dpSuspended if needed 190 checkA2dpSuspend(); 191 } 192 193 updateDevicesAndOutputs(); 194 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) { 195 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/); 196 updateCallRouting(newDevice); 197 } 198 for (size_t i = 0; i < mOutputs.size(); i++) { 199 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i); 200 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) { 201 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/); 202 // do not force device change on duplicated output because if device is 0, it will 203 // also force a device 0 for the two outputs it is duplicated to which may override 204 // a valid device selection on those outputs. 205 bool force = !desc->isDuplicated() 206 && (!device_distinguishes_on_address(device) 207 // always force when disconnecting (a non-duplicated device) 208 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)); 209 setOutputDevice(desc, newDevice, force, 0); 210 } 211 } 212 213 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) { 214 cleanUpForDevice(devDesc); 215 } 216 217 mpClientInterface->onAudioPortListUpdate(); 218 return NO_ERROR; 219 } // end if is output device 220 221 // handle input devices 222 if (audio_is_input_device(device)) { 223 SortedVector <audio_io_handle_t> inputs; 224 225 ssize_t index = mAvailableInputDevices.indexOf(devDesc); 226 switch (state) 227 { 228 // handle input device connection 229 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: { 230 if (index >= 0) { 231 ALOGW("setDeviceConnectionState() device already connected: %d", device); 232 return INVALID_OPERATION; 233 } 234 sp<HwModule> module = mHwModules.getModuleForDevice(device); 235 if (module == NULL) { 236 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x", 237 device); 238 return INVALID_OPERATION; 239 } 240 241 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic 242 // parameters on newly connected devices (instead of opening the inputs...) 243 broadcastDeviceConnectionState(device, state, devDesc->mAddress); 244 245 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) { 246 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, 247 devDesc->mAddress); 248 return INVALID_OPERATION; 249 } 250 251 index = mAvailableInputDevices.add(devDesc); 252 if (index >= 0) { 253 mAvailableInputDevices[index]->attach(module); 254 } else { 255 return NO_MEMORY; 256 } 257 258 // Propagate device availability to Engine 259 mEngine->setDeviceConnectionState(devDesc, state); 260 } break; 261 262 // handle input device disconnection 263 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: { 264 if (index < 0) { 265 ALOGW("setDeviceConnectionState() device not connected: %d", device); 266 return INVALID_OPERATION; 267 } 268 269 ALOGV("setDeviceConnectionState() disconnecting input device %x", device); 270 271 // Set Disconnect to HALs 272 broadcastDeviceConnectionState(device, state, devDesc->mAddress); 273 274 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress); 275 mAvailableInputDevices.remove(devDesc); 276 277 // Propagate device availability to Engine 278 mEngine->setDeviceConnectionState(devDesc, state); 279 } break; 280 281 default: 282 ALOGE("setDeviceConnectionState() invalid state: %x", state); 283 return BAD_VALUE; 284 } 285 286 closeAllInputs(); 287 // As the input device list can impact the output device selection, update 288 // getDeviceForStrategy() cache 289 updateDevicesAndOutputs(); 290 291 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) { 292 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/); 293 updateCallRouting(newDevice); 294 } 295 296 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) { 297 cleanUpForDevice(devDesc); 298 } 299 300 mpClientInterface->onAudioPortListUpdate(); 301 return NO_ERROR; 302 } // end if is input device 303 304 ALOGW("setDeviceConnectionState() invalid device: %x", device); 305 return BAD_VALUE; 306} 307 308audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device, 309 const char *device_address) 310{ 311 sp<DeviceDescriptor> devDesc = 312 mHwModules.getDeviceDescriptor(device, device_address, "", 313 (strlen(device_address) != 0)/*matchAddress*/); 314 315 if (devDesc == 0) { 316 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s", 317 device, device_address); 318 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE; 319 } 320 321 DeviceVector *deviceVector; 322 323 if (audio_is_output_device(device)) { 324 deviceVector = &mAvailableOutputDevices; 325 } else if (audio_is_input_device(device)) { 326 deviceVector = &mAvailableInputDevices; 327 } else { 328 ALOGW("getDeviceConnectionState() invalid device type %08x", device); 329 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE; 330 } 331 332 return (deviceVector->getDevice(device, String8(device_address)) != 0) ? 333 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE; 334} 335 336uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs) 337{ 338 bool createTxPatch = false; 339 status_t status; 340 audio_patch_handle_t afPatchHandle; 341 DeviceVector deviceList; 342 uint32_t muteWaitMs = 0; 343 344 if(!hasPrimaryOutput()) { 345 return muteWaitMs; 346 } 347 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION); 348 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice); 349 350 // release existing RX patch if any 351 if (mCallRxPatch != 0) { 352 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0); 353 mCallRxPatch.clear(); 354 } 355 // release TX patch if any 356 if (mCallTxPatch != 0) { 357 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0); 358 mCallTxPatch.clear(); 359 } 360 361 // If the RX device is on the primary HW module, then use legacy routing method for voice calls 362 // via setOutputDevice() on primary output. 363 // Otherwise, create two audio patches for TX and RX path. 364 if (availablePrimaryOutputDevices() & rxDevice) { 365 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs); 366 // If the TX device is also on the primary HW module, setOutputDevice() will take care 367 // of it due to legacy implementation. If not, create a patch. 368 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN) 369 == AUDIO_DEVICE_NONE) { 370 createTxPatch = true; 371 } 372 } else { // create RX path audio patch 373 struct audio_patch patch; 374 375 patch.num_sources = 1; 376 patch.num_sinks = 1; 377 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice); 378 ALOG_ASSERT(!deviceList.isEmpty(), 379 "updateCallRouting() selected device not in output device list"); 380 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0); 381 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX); 382 ALOG_ASSERT(!deviceList.isEmpty(), 383 "updateCallRouting() no telephony RX device"); 384 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0); 385 386 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]); 387 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]); 388 389 // request to reuse existing output stream if one is already opened to reach the RX device 390 SortedVector<audio_io_handle_t> outputs = 391 getOutputsForDevice(rxDevice, mOutputs); 392 audio_io_handle_t output = selectOutput(outputs, 393 AUDIO_OUTPUT_FLAG_NONE, 394 AUDIO_FORMAT_INVALID); 395 if (output != AUDIO_IO_HANDLE_NONE) { 396 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 397 ALOG_ASSERT(!outputDesc->isDuplicated(), 398 "updateCallRouting() RX device output is duplicated"); 399 outputDesc->toAudioPortConfig(&patch.sources[1]); 400 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH; 401 patch.num_sources = 2; 402 } 403 404 afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 405 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs); 406 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch", 407 status); 408 if (status == NO_ERROR) { 409 mCallRxPatch = new AudioPatch(&patch, mUidCached); 410 mCallRxPatch->mAfPatchHandle = afPatchHandle; 411 mCallRxPatch->mUid = mUidCached; 412 } 413 createTxPatch = true; 414 } 415 if (createTxPatch) { // create TX path audio patch 416 struct audio_patch patch; 417 418 patch.num_sources = 1; 419 patch.num_sinks = 1; 420 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice); 421 ALOG_ASSERT(!deviceList.isEmpty(), 422 "updateCallRouting() selected device not in input device list"); 423 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0); 424 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]); 425 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX); 426 ALOG_ASSERT(!deviceList.isEmpty(), 427 "updateCallRouting() no telephony TX device"); 428 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0); 429 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]); 430 431 SortedVector<audio_io_handle_t> outputs = 432 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs); 433 audio_io_handle_t output = selectOutput(outputs, 434 AUDIO_OUTPUT_FLAG_NONE, 435 AUDIO_FORMAT_INVALID); 436 // request to reuse existing output stream if one is already opened to reach the TX 437 // path output device 438 if (output != AUDIO_IO_HANDLE_NONE) { 439 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 440 ALOG_ASSERT(!outputDesc->isDuplicated(), 441 "updateCallRouting() RX device output is duplicated"); 442 outputDesc->toAudioPortConfig(&patch.sources[1]); 443 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH; 444 patch.num_sources = 2; 445 } 446 447 // terminate active capture if on the same HW module as the call TX source device 448 // FIXME: would be better to refine to only inputs whose profile connects to the 449 // call TX device but this information is not in the audio patch and logic here must be 450 // symmetric to the one in startInput() 451 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs(); 452 for (size_t i = 0; i < activeInputs.size(); i++) { 453 sp<AudioInputDescriptor> activeDesc = activeInputs[i]; 454 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) { 455 AudioSessionCollection activeSessions = 456 activeDesc->getAudioSessions(true /*activeOnly*/); 457 for (size_t j = 0; j < activeSessions.size(); j++) { 458 audio_session_t activeSession = activeSessions.keyAt(j); 459 stopInput(activeDesc->mIoHandle, activeSession); 460 releaseInput(activeDesc->mIoHandle, activeSession); 461 } 462 } 463 } 464 465 afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 466 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs); 467 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch", 468 status); 469 if (status == NO_ERROR) { 470 mCallTxPatch = new AudioPatch(&patch, mUidCached); 471 mCallTxPatch->mAfPatchHandle = afPatchHandle; 472 mCallTxPatch->mUid = mUidCached; 473 } 474 } 475 476 return muteWaitMs; 477} 478 479void AudioPolicyManager::setPhoneState(audio_mode_t state) 480{ 481 ALOGV("setPhoneState() state %d", state); 482 // store previous phone state for management of sonification strategy below 483 int oldState = mEngine->getPhoneState(); 484 485 if (mEngine->setPhoneState(state) != NO_ERROR) { 486 ALOGW("setPhoneState() invalid or same state %d", state); 487 return; 488 } 489 /// Opens: can these line be executed after the switch of volume curves??? 490 // if leaving call state, handle special case of active streams 491 // pertaining to sonification strategy see handleIncallSonification() 492 if (isStateInCall(oldState)) { 493 ALOGV("setPhoneState() in call state management: new state is %d", state); 494 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) { 495 handleIncallSonification((audio_stream_type_t)stream, false, true); 496 } 497 498 // force reevaluating accessibility routing when call stops 499 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY); 500 } 501 502 /** 503 * Switching to or from incall state or switching between telephony and VoIP lead to force 504 * routing command. 505 */ 506 bool force = ((is_state_in_call(oldState) != is_state_in_call(state)) 507 || (is_state_in_call(state) && (state != oldState))); 508 509 // check for device and output changes triggered by new phone state 510 checkA2dpSuspend(); 511 checkOutputForAllStrategies(); 512 updateDevicesAndOutputs(); 513 514 int delayMs = 0; 515 if (isStateInCall(state)) { 516 nsecs_t sysTime = systemTime(); 517 for (size_t i = 0; i < mOutputs.size(); i++) { 518 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i); 519 // mute media and sonification strategies and delay device switch by the largest 520 // latency of any output where either strategy is active. 521 // This avoid sending the ring tone or music tail into the earpiece or headset. 522 if ((isStrategyActive(desc, STRATEGY_MEDIA, 523 SONIFICATION_HEADSET_MUSIC_DELAY, 524 sysTime) || 525 isStrategyActive(desc, STRATEGY_SONIFICATION, 526 SONIFICATION_HEADSET_MUSIC_DELAY, 527 sysTime)) && 528 (delayMs < (int)desc->latency()*2)) { 529 delayMs = desc->latency()*2; 530 } 531 setStrategyMute(STRATEGY_MEDIA, true, desc); 532 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS, 533 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/)); 534 setStrategyMute(STRATEGY_SONIFICATION, true, desc); 535 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS, 536 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/)); 537 } 538 } 539 540 if (hasPrimaryOutput()) { 541 // Note that despite the fact that getNewOutputDevice() is called on the primary output, 542 // the device returned is not necessarily reachable via this output 543 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/); 544 // force routing command to audio hardware when ending call 545 // even if no device change is needed 546 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) { 547 rxDevice = mPrimaryOutput->device(); 548 } 549 550 if (state == AUDIO_MODE_IN_CALL) { 551 updateCallRouting(rxDevice, delayMs); 552 } else if (oldState == AUDIO_MODE_IN_CALL) { 553 if (mCallRxPatch != 0) { 554 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0); 555 mCallRxPatch.clear(); 556 } 557 if (mCallTxPatch != 0) { 558 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0); 559 mCallTxPatch.clear(); 560 } 561 setOutputDevice(mPrimaryOutput, rxDevice, force, 0); 562 } else { 563 setOutputDevice(mPrimaryOutput, rxDevice, force, 0); 564 } 565 } 566 // if entering in call state, handle special case of active streams 567 // pertaining to sonification strategy see handleIncallSonification() 568 if (isStateInCall(state)) { 569 ALOGV("setPhoneState() in call state management: new state is %d", state); 570 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) { 571 handleIncallSonification((audio_stream_type_t)stream, true, true); 572 } 573 574 // force reevaluating accessibility routing when call starts 575 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY); 576 } 577 578 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE 579 if (state == AUDIO_MODE_RINGTONE && 580 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) { 581 mLimitRingtoneVolume = true; 582 } else { 583 mLimitRingtoneVolume = false; 584 } 585} 586 587audio_mode_t AudioPolicyManager::getPhoneState() { 588 return mEngine->getPhoneState(); 589} 590 591void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage, 592 audio_policy_forced_cfg_t config) 593{ 594 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState()); 595 596 if (mEngine->setForceUse(usage, config) != NO_ERROR) { 597 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage); 598 return; 599 } 600 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) || 601 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) || 602 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM); 603 604 // check for device and output changes triggered by new force usage 605 checkA2dpSuspend(); 606 checkOutputForAllStrategies(); 607 updateDevicesAndOutputs(); 608 609 //FIXME: workaround for truncated touch sounds 610 // to be removed when the problem is handled by system UI 611 uint32_t delayMs = 0; 612 uint32_t waitMs = 0; 613 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) { 614 delayMs = TOUCH_SOUND_FIXED_DELAY_MS; 615 } 616 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) { 617 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/); 618 waitMs = updateCallRouting(newDevice, delayMs); 619 } 620 for (size_t i = 0; i < mOutputs.size(); i++) { 621 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i); 622 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/); 623 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) { 624 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 625 delayMs); 626 } 627 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) { 628 applyStreamVolumes(outputDesc, newDevice, waitMs, true); 629 } 630 } 631 632 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs(); 633 for (size_t i = 0; i < activeInputs.size(); i++) { 634 sp<AudioInputDescriptor> activeDesc = activeInputs[i]; 635 audio_devices_t newDevice = getNewInputDevice(activeDesc); 636 // Force new input selection if the new device can not be reached via current input 637 if (activeDesc->mProfile->getSupportedDevices().types() & 638 (newDevice & ~AUDIO_DEVICE_BIT_IN)) { 639 setInputDevice(activeDesc->mIoHandle, newDevice); 640 } else { 641 closeInput(activeDesc->mIoHandle); 642 } 643 } 644} 645 646void AudioPolicyManager::setSystemProperty(const char* property, const char* value) 647{ 648 ALOGV("setSystemProperty() property %s, value %s", property, value); 649} 650 651// Find a direct output profile compatible with the parameters passed, even if the input flags do 652// not explicitly request a direct output 653sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput( 654 audio_devices_t device, 655 uint32_t samplingRate, 656 audio_format_t format, 657 audio_channel_mask_t channelMask, 658 audio_output_flags_t flags) 659{ 660 // only retain flags that will drive the direct output profile selection 661 // if explicitly requested 662 static const uint32_t kRelevantFlags = 663 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD); 664 flags = 665 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT); 666 667 sp<IOProfile> profile; 668 669 for (size_t i = 0; i < mHwModules.size(); i++) { 670 if (mHwModules[i]->mHandle == 0) { 671 continue; 672 } 673 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) { 674 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j]; 675 if (!curProfile->isCompatibleProfile(device, String8(""), 676 samplingRate, NULL /*updatedSamplingRate*/, 677 format, NULL /*updatedFormat*/, 678 channelMask, NULL /*updatedChannelMask*/, 679 flags)) { 680 continue; 681 } 682 // reject profiles not corresponding to a device currently available 683 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) { 684 continue; 685 } 686 // if several profiles are compatible, give priority to one with offload capability 687 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) { 688 continue; 689 } 690 profile = curProfile; 691 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) { 692 break; 693 } 694 } 695 } 696 return profile; 697} 698 699audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream, 700 uint32_t samplingRate, 701 audio_format_t format, 702 audio_channel_mask_t channelMask, 703 audio_output_flags_t flags, 704 const audio_offload_info_t *offloadInfo) 705{ 706 routing_strategy strategy = getStrategy(stream); 707 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/); 708 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x", 709 device, stream, samplingRate, format, channelMask, flags); 710 711 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE, 712 stream, samplingRate,format, channelMask, 713 flags, offloadInfo); 714} 715 716status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr, 717 audio_io_handle_t *output, 718 audio_session_t session, 719 audio_stream_type_t *stream, 720 uid_t uid, 721 uint32_t samplingRate, 722 audio_format_t format, 723 audio_channel_mask_t channelMask, 724 audio_output_flags_t flags, 725 audio_port_handle_t selectedDeviceId, 726 const audio_offload_info_t *offloadInfo) 727{ 728 audio_attributes_t attributes; 729 if (attr != NULL) { 730 if (!isValidAttributes(attr)) { 731 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]", 732 attr->usage, attr->content_type, attr->flags, 733 attr->tags); 734 return BAD_VALUE; 735 } 736 attributes = *attr; 737 } else { 738 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) { 739 ALOGE("getOutputForAttr(): invalid stream type"); 740 return BAD_VALUE; 741 } 742 stream_type_to_audio_attributes(*stream, &attributes); 743 } 744 sp<SwAudioOutputDescriptor> desc; 745 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) { 746 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr"); 747 if (!audio_has_proportional_frames(format)) { 748 return BAD_VALUE; 749 } 750 *stream = streamTypefromAttributesInt(&attributes); 751 *output = desc->mIoHandle; 752 ALOGV("getOutputForAttr() returns output %d", *output); 753 return NO_ERROR; 754 } 755 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) { 756 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE"); 757 return BAD_VALUE; 758 } 759 760 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x" 761 " session %d selectedDeviceId %d", 762 attributes.usage, attributes.content_type, attributes.tags, attributes.flags, 763 session, selectedDeviceId); 764 765 *stream = streamTypefromAttributesInt(&attributes); 766 767 // Explicit routing? 768 sp<DeviceDescriptor> deviceDesc; 769 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) { 770 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) { 771 deviceDesc = mAvailableOutputDevices[i]; 772 break; 773 } 774 } 775 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid); 776 777 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes); 778 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/); 779 780 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) { 781 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC); 782 } 783 784 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x", 785 device, samplingRate, format, channelMask, flags); 786 787 *output = getOutputForDevice(device, session, *stream, 788 samplingRate, format, channelMask, 789 flags, offloadInfo); 790 if (*output == AUDIO_IO_HANDLE_NONE) { 791 mOutputRoutes.removeRoute(session); 792 return INVALID_OPERATION; 793 } 794 795 return NO_ERROR; 796} 797 798audio_io_handle_t AudioPolicyManager::getOutputForDevice( 799 audio_devices_t device, 800 audio_session_t session __unused, 801 audio_stream_type_t stream, 802 uint32_t samplingRate, 803 audio_format_t format, 804 audio_channel_mask_t channelMask, 805 audio_output_flags_t flags, 806 const audio_offload_info_t *offloadInfo) 807{ 808 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE; 809 status_t status; 810 811#ifdef AUDIO_POLICY_TEST 812 if (mCurOutput != 0) { 813 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d", 814 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput); 815 816 if (mTestOutputs[mCurOutput] == 0) { 817 ALOGV("getOutput() opening test output"); 818 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL, 819 mpClientInterface); 820 outputDesc->mDevice = mTestDevice; 821 outputDesc->mLatency = mTestLatencyMs; 822 outputDesc->mFlags = 823 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0); 824 outputDesc->mRefCount[stream] = 0; 825 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 826 config.sample_rate = mTestSamplingRate; 827 config.channel_mask = mTestChannels; 828 config.format = mTestFormat; 829 if (offloadInfo != NULL) { 830 config.offload_info = *offloadInfo; 831 } 832 status = mpClientInterface->openOutput(0, 833 &mTestOutputs[mCurOutput], 834 &config, 835 &outputDesc->mDevice, 836 String8(""), 837 &outputDesc->mLatency, 838 outputDesc->mFlags); 839 if (status == NO_ERROR) { 840 outputDesc->mSamplingRate = config.sample_rate; 841 outputDesc->mFormat = config.format; 842 outputDesc->mChannelMask = config.channel_mask; 843 AudioParameter outputCmd = AudioParameter(); 844 outputCmd.addInt(String8("set_id"),mCurOutput); 845 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString()); 846 addOutput(mTestOutputs[mCurOutput], outputDesc); 847 } 848 } 849 return mTestOutputs[mCurOutput]; 850 } 851#endif //AUDIO_POLICY_TEST 852 853 // open a direct output if required by specified parameters 854 //force direct flag if offload flag is set: offloading implies a direct output stream 855 // and all common behaviors are driven by checking only the direct flag 856 // this should normally be set appropriately in the policy configuration file 857 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) { 858 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT); 859 } 860 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) { 861 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT); 862 } 863 // only allow deep buffering for music stream type 864 if (stream != AUDIO_STREAM_MUSIC) { 865 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER); 866 } else if (/* stream == AUDIO_STREAM_MUSIC && */ 867 flags == AUDIO_OUTPUT_FLAG_NONE && 868 property_get_bool("audio.deep_buffer.media", false /* default_value */)) { 869 // use DEEP_BUFFER as default output for music stream type 870 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER; 871 } 872 if (stream == AUDIO_STREAM_TTS) { 873 flags = AUDIO_OUTPUT_FLAG_TTS; 874 } 875 876 sp<IOProfile> profile; 877 878 // skip direct output selection if the request can obviously be attached to a mixed output 879 // and not explicitly requested 880 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && 881 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX && 882 audio_channel_count_from_out_mask(channelMask) <= 2) { 883 goto non_direct_output; 884 } 885 886 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled. 887 // This prevents creating an offloaded track and tearing it down immediately after start 888 // when audioflinger detects there is an active non offloadable effect. 889 // FIXME: We should check the audio session here but we do not have it in this context. 890 // This may prevent offloading in rare situations where effects are left active by apps 891 // in the background. 892 893 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) || 894 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) { 895 profile = getProfileForDirectOutput(device, 896 samplingRate, 897 format, 898 channelMask, 899 (audio_output_flags_t)flags); 900 } 901 902 if (profile != 0) { 903 sp<SwAudioOutputDescriptor> outputDesc = NULL; 904 905 for (size_t i = 0; i < mOutputs.size(); i++) { 906 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i); 907 if (!desc->isDuplicated() && (profile == desc->mProfile)) { 908 outputDesc = desc; 909 // reuse direct output if currently open and configured with same parameters 910 if ((samplingRate == outputDesc->mSamplingRate) && 911 audio_formats_match(format, outputDesc->mFormat) && 912 (channelMask == outputDesc->mChannelMask)) { 913 outputDesc->mDirectOpenCount++; 914 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i)); 915 return mOutputs.keyAt(i); 916 } 917 } 918 } 919 // close direct output if currently open and configured with different parameters 920 if (outputDesc != NULL) { 921 closeOutput(outputDesc->mIoHandle); 922 } 923 924 // if the selected profile is offloaded and no offload info was specified, 925 // create a default one 926 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER; 927 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) { 928 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD); 929 defaultOffloadInfo.sample_rate = samplingRate; 930 defaultOffloadInfo.channel_mask = channelMask; 931 defaultOffloadInfo.format = format; 932 defaultOffloadInfo.stream_type = stream; 933 defaultOffloadInfo.bit_rate = 0; 934 defaultOffloadInfo.duration_us = -1; 935 defaultOffloadInfo.has_video = true; // conservative 936 defaultOffloadInfo.is_streaming = true; // likely 937 offloadInfo = &defaultOffloadInfo; 938 } 939 940 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface); 941 outputDesc->mDevice = device; 942 outputDesc->mLatency = 0; 943 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags); 944 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 945 config.sample_rate = samplingRate; 946 config.channel_mask = channelMask; 947 config.format = format; 948 if (offloadInfo != NULL) { 949 config.offload_info = *offloadInfo; 950 } 951 status = mpClientInterface->openOutput(profile->getModuleHandle(), 952 &output, 953 &config, 954 &outputDesc->mDevice, 955 String8(""), 956 &outputDesc->mLatency, 957 outputDesc->mFlags); 958 959 // only accept an output with the requested parameters 960 if (status != NO_ERROR || 961 (samplingRate != 0 && samplingRate != config.sample_rate) || 962 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) || 963 (channelMask != 0 && channelMask != config.channel_mask)) { 964 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d," 965 "format %d %d, channelMask %04x %04x", output, samplingRate, 966 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask, 967 outputDesc->mChannelMask); 968 if (output != AUDIO_IO_HANDLE_NONE) { 969 mpClientInterface->closeOutput(output); 970 } 971 // fall back to mixer output if possible when the direct output could not be open 972 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) { 973 goto non_direct_output; 974 } 975 return AUDIO_IO_HANDLE_NONE; 976 } 977 outputDesc->mSamplingRate = config.sample_rate; 978 outputDesc->mChannelMask = config.channel_mask; 979 outputDesc->mFormat = config.format; 980 outputDesc->mRefCount[stream] = 0; 981 outputDesc->mStopTime[stream] = 0; 982 outputDesc->mDirectOpenCount = 1; 983 984 audio_io_handle_t srcOutput = getOutputForEffect(); 985 addOutput(output, outputDesc); 986 audio_io_handle_t dstOutput = getOutputForEffect(); 987 if (dstOutput == output) { 988 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput); 989 } 990 mPreviousOutputs = mOutputs; 991 ALOGV("getOutput() returns new direct output %d", output); 992 mpClientInterface->onAudioPortListUpdate(); 993 return output; 994 } 995 996non_direct_output: 997 998 // A request for HW A/V sync cannot fallback to a mixed output because time 999 // stamps are embedded in audio data 1000 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) { 1001 return AUDIO_IO_HANDLE_NONE; 1002 } 1003 1004 // ignoring channel mask due to downmix capability in mixer 1005 1006 // open a non direct output 1007 1008 // for non direct outputs, only PCM is supported 1009 if (audio_is_linear_pcm(format)) { 1010 // get which output is suitable for the specified stream. The actual 1011 // routing change will happen when startOutput() will be called 1012 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs); 1013 1014 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier 1015 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT); 1016 output = selectOutput(outputs, flags, format); 1017 } 1018 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d," 1019 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags); 1020 1021 ALOGV(" getOutputForDevice() returns output %d", output); 1022 1023 return output; 1024} 1025 1026audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs, 1027 audio_output_flags_t flags, 1028 audio_format_t format) 1029{ 1030 // select one output among several that provide a path to a particular device or set of 1031 // devices (the list was previously build by getOutputsForDevice()). 1032 // The priority is as follows: 1033 // 1: the output with the highest number of requested policy flags 1034 // 2: the output with the bit depth the closest to the requested one 1035 // 3: the primary output 1036 // 4: the first output in the list 1037 1038 if (outputs.size() == 0) { 1039 return 0; 1040 } 1041 if (outputs.size() == 1) { 1042 return outputs[0]; 1043 } 1044 1045 int maxCommonFlags = 0; 1046 audio_io_handle_t outputForFlags = 0; 1047 audio_io_handle_t outputForPrimary = 0; 1048 audio_io_handle_t outputForFormat = 0; 1049 audio_format_t bestFormat = AUDIO_FORMAT_INVALID; 1050 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID; 1051 1052 for (size_t i = 0; i < outputs.size(); i++) { 1053 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]); 1054 if (!outputDesc->isDuplicated()) { 1055 // if a valid format is specified, skip output if not compatible 1056 if (format != AUDIO_FORMAT_INVALID) { 1057 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) { 1058 if (!audio_formats_match(format, outputDesc->mFormat)) { 1059 continue; 1060 } 1061 } else if (!audio_is_linear_pcm(format)) { 1062 continue; 1063 } 1064 if (AudioPort::isBetterFormatMatch( 1065 outputDesc->mFormat, bestFormat, format)) { 1066 outputForFormat = outputs[i]; 1067 bestFormat = outputDesc->mFormat; 1068 } 1069 } 1070 1071 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags); 1072 if (commonFlags >= maxCommonFlags) { 1073 if (commonFlags == maxCommonFlags) { 1074 if (AudioPort::isBetterFormatMatch( 1075 outputDesc->mFormat, bestFormatForFlags, format)) { 1076 outputForFlags = outputs[i]; 1077 bestFormatForFlags = outputDesc->mFormat; 1078 } 1079 } else { 1080 outputForFlags = outputs[i]; 1081 maxCommonFlags = commonFlags; 1082 bestFormatForFlags = outputDesc->mFormat; 1083 } 1084 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags); 1085 } 1086 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) { 1087 outputForPrimary = outputs[i]; 1088 } 1089 } 1090 } 1091 1092 if (outputForFlags != 0) { 1093 return outputForFlags; 1094 } 1095 if (outputForFormat != 0) { 1096 return outputForFormat; 1097 } 1098 if (outputForPrimary != 0) { 1099 return outputForPrimary; 1100 } 1101 1102 return outputs[0]; 1103} 1104 1105status_t AudioPolicyManager::startOutput(audio_io_handle_t output, 1106 audio_stream_type_t stream, 1107 audio_session_t session) 1108{ 1109 ALOGV("startOutput() output %d, stream %d, session %d", 1110 output, stream, session); 1111 ssize_t index = mOutputs.indexOfKey(output); 1112 if (index < 0) { 1113 ALOGW("startOutput() unknown output %d", output); 1114 return BAD_VALUE; 1115 } 1116 1117 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index); 1118 1119 // Routing? 1120 mOutputRoutes.incRouteActivity(session); 1121 1122 audio_devices_t newDevice; 1123 AudioMix *policyMix = NULL; 1124 const char *address = NULL; 1125 if (outputDesc->mPolicyMix != NULL) { 1126 policyMix = outputDesc->mPolicyMix; 1127 address = policyMix->mDeviceAddress.string(); 1128 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) { 1129 newDevice = policyMix->mDeviceType; 1130 } else { 1131 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX; 1132 } 1133 } else if (mOutputRoutes.hasRouteChanged(session)) { 1134 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/); 1135 checkStrategyRoute(getStrategy(stream), output); 1136 } else { 1137 newDevice = AUDIO_DEVICE_NONE; 1138 } 1139 1140 uint32_t delayMs = 0; 1141 1142 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs); 1143 1144 if (status != NO_ERROR) { 1145 mOutputRoutes.decRouteActivity(session); 1146 return status; 1147 } 1148 // Automatically enable the remote submix input when output is started on a re routing mix 1149 // of type MIX_TYPE_RECORDERS 1150 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL && 1151 policyMix->mMixType == MIX_TYPE_RECORDERS) { 1152 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX, 1153 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, 1154 address, 1155 "remote-submix"); 1156 } 1157 1158 if (delayMs != 0) { 1159 usleep(delayMs * 1000); 1160 } 1161 1162 return status; 1163} 1164 1165status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc, 1166 audio_stream_type_t stream, 1167 audio_devices_t device, 1168 const char *address, 1169 uint32_t *delayMs) 1170{ 1171 // cannot start playback of STREAM_TTS if any other output is being used 1172 uint32_t beaconMuteLatency = 0; 1173 1174 *delayMs = 0; 1175 if (stream == AUDIO_STREAM_TTS) { 1176 ALOGV("\t found BEACON stream"); 1177 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) { 1178 return INVALID_OPERATION; 1179 } else { 1180 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON); 1181 } 1182 } else { 1183 // some playback other than beacon starts 1184 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT); 1185 } 1186 1187 // force device change if the output is inactive and no audio patch is already present. 1188 // check active before incrementing usage count 1189 bool force = !outputDesc->isActive() && 1190 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE); 1191 1192 // increment usage count for this stream on the requested output: 1193 // NOTE that the usage count is the same for duplicated output and hardware output which is 1194 // necessary for a correct control of hardware output routing by startOutput() and stopOutput() 1195 outputDesc->changeRefCount(stream, 1); 1196 1197 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) { 1198 // starting an output being rerouted? 1199 if (device == AUDIO_DEVICE_NONE) { 1200 device = getNewOutputDevice(outputDesc, false /*fromCache*/); 1201 } 1202 routing_strategy strategy = getStrategy(stream); 1203 bool shouldWait = (strategy == STRATEGY_SONIFICATION) || 1204 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) || 1205 (beaconMuteLatency > 0); 1206 uint32_t waitMs = beaconMuteLatency; 1207 for (size_t i = 0; i < mOutputs.size(); i++) { 1208 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 1209 if (desc != outputDesc) { 1210 // force a device change if any other output is: 1211 // - managed by the same hw module 1212 // - has a current device selection that differs from selected device. 1213 // - supports currently selected device 1214 // - has an active audio patch 1215 // In this case, the audio HAL must receive the new device selection so that it can 1216 // change the device currently selected by the other active output. 1217 if (outputDesc->sharesHwModuleWith(desc) && 1218 desc->device() != device && 1219 desc->supportedDevices() & device && 1220 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) { 1221 force = true; 1222 } 1223 // wait for audio on other active outputs to be presented when starting 1224 // a notification so that audio focus effect can propagate, or that a mute/unmute 1225 // event occurred for beacon 1226 uint32_t latency = desc->latency(); 1227 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) { 1228 waitMs = latency; 1229 } 1230 } 1231 } 1232 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address); 1233 1234 // handle special case for sonification while in call 1235 if (isInCall()) { 1236 handleIncallSonification(stream, true, false); 1237 } 1238 1239 // apply volume rules for current stream and device if necessary 1240 checkAndSetVolume(stream, 1241 mVolumeCurves->getVolumeIndex(stream, device), 1242 outputDesc, 1243 device); 1244 1245 // update the outputs if starting an output with a stream that can affect notification 1246 // routing 1247 handleNotificationRoutingForStream(stream); 1248 1249 // force reevaluating accessibility routing when ringtone or alarm starts 1250 if (strategy == STRATEGY_SONIFICATION) { 1251 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY); 1252 } 1253 1254 if (waitMs > muteWaitMs) { 1255 *delayMs = waitMs - muteWaitMs; 1256 } 1257 } 1258 1259 return NO_ERROR; 1260} 1261 1262 1263status_t AudioPolicyManager::stopOutput(audio_io_handle_t output, 1264 audio_stream_type_t stream, 1265 audio_session_t session) 1266{ 1267 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session); 1268 ssize_t index = mOutputs.indexOfKey(output); 1269 if (index < 0) { 1270 ALOGW("stopOutput() unknown output %d", output); 1271 return BAD_VALUE; 1272 } 1273 1274 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index); 1275 1276 if (outputDesc->mRefCount[stream] == 1) { 1277 // Automatically disable the remote submix input when output is stopped on a 1278 // re routing mix of type MIX_TYPE_RECORDERS 1279 if (audio_is_remote_submix_device(outputDesc->mDevice) && 1280 outputDesc->mPolicyMix != NULL && 1281 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) { 1282 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX, 1283 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, 1284 outputDesc->mPolicyMix->mDeviceAddress, 1285 "remote-submix"); 1286 } 1287 } 1288 1289 // Routing? 1290 bool forceDeviceUpdate = false; 1291 if (outputDesc->mRefCount[stream] > 0) { 1292 int activityCount = mOutputRoutes.decRouteActivity(session); 1293 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0)); 1294 1295 if (forceDeviceUpdate) { 1296 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE); 1297 } 1298 } 1299 1300 return stopSource(outputDesc, stream, forceDeviceUpdate); 1301} 1302 1303status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc, 1304 audio_stream_type_t stream, 1305 bool forceDeviceUpdate) 1306{ 1307 // always handle stream stop, check which stream type is stopping 1308 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT); 1309 1310 // handle special case for sonification while in call 1311 if (isInCall()) { 1312 handleIncallSonification(stream, false, false); 1313 } 1314 1315 if (outputDesc->mRefCount[stream] > 0) { 1316 // decrement usage count of this stream on the output 1317 outputDesc->changeRefCount(stream, -1); 1318 1319 // store time at which the stream was stopped - see isStreamActive() 1320 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) { 1321 outputDesc->mStopTime[stream] = systemTime(); 1322 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/); 1323 // delay the device switch by twice the latency because stopOutput() is executed when 1324 // the track stop() command is received and at that time the audio track buffer can 1325 // still contain data that needs to be drained. The latency only covers the audio HAL 1326 // and kernel buffers. Also the latency does not always include additional delay in the 1327 // audio path (audio DSP, CODEC ...) 1328 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2); 1329 1330 // force restoring the device selection on other active outputs if it differs from the 1331 // one being selected for this output 1332 for (size_t i = 0; i < mOutputs.size(); i++) { 1333 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 1334 if (desc != outputDesc && 1335 desc->isActive() && 1336 outputDesc->sharesHwModuleWith(desc) && 1337 (newDevice != desc->device())) { 1338 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/); 1339 bool force = desc->device() != newDevice2; 1340 setOutputDevice(desc, 1341 newDevice2, 1342 force, 1343 outputDesc->latency()*2); 1344 } 1345 } 1346 // update the outputs if stopping one with a stream that can affect notification routing 1347 handleNotificationRoutingForStream(stream); 1348 } 1349 return NO_ERROR; 1350 } else { 1351 ALOGW("stopOutput() refcount is already 0"); 1352 return INVALID_OPERATION; 1353 } 1354} 1355 1356void AudioPolicyManager::releaseOutput(audio_io_handle_t output, 1357 audio_stream_type_t stream __unused, 1358 audio_session_t session __unused) 1359{ 1360 ALOGV("releaseOutput() %d", output); 1361 ssize_t index = mOutputs.indexOfKey(output); 1362 if (index < 0) { 1363 ALOGW("releaseOutput() releasing unknown output %d", output); 1364 return; 1365 } 1366 1367#ifdef AUDIO_POLICY_TEST 1368 int testIndex = testOutputIndex(output); 1369 if (testIndex != 0) { 1370 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index); 1371 if (outputDesc->isActive()) { 1372 mpClientInterface->closeOutput(output); 1373 removeOutput(output); 1374 mTestOutputs[testIndex] = 0; 1375 } 1376 return; 1377 } 1378#endif //AUDIO_POLICY_TEST 1379 1380 // Routing 1381 mOutputRoutes.removeRoute(session); 1382 1383 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index); 1384 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) { 1385 if (desc->mDirectOpenCount <= 0) { 1386 ALOGW("releaseOutput() invalid open count %d for output %d", 1387 desc->mDirectOpenCount, output); 1388 return; 1389 } 1390 if (--desc->mDirectOpenCount == 0) { 1391 closeOutput(output); 1392 // If effects where present on the output, audioflinger moved them to the primary 1393 // output by default: move them back to the appropriate output. 1394 audio_io_handle_t dstOutput = getOutputForEffect(); 1395 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) { 1396 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, 1397 mPrimaryOutput->mIoHandle, dstOutput); 1398 } 1399 mpClientInterface->onAudioPortListUpdate(); 1400 } 1401 } 1402} 1403 1404 1405status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr, 1406 audio_io_handle_t *input, 1407 audio_session_t session, 1408 uid_t uid, 1409 uint32_t samplingRate, 1410 audio_format_t format, 1411 audio_channel_mask_t channelMask, 1412 audio_input_flags_t flags, 1413 audio_port_handle_t selectedDeviceId, 1414 input_type_t *inputType) 1415{ 1416 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x," 1417 "session %d, flags %#x", 1418 attr->source, samplingRate, format, channelMask, session, flags); 1419 1420 *input = AUDIO_IO_HANDLE_NONE; 1421 *inputType = API_INPUT_INVALID; 1422 1423 audio_devices_t device; 1424 // handle legacy remote submix case where the address was not always specified 1425 String8 address = String8(""); 1426 audio_source_t inputSource = attr->source; 1427 audio_source_t halInputSource; 1428 AudioMix *policyMix = NULL; 1429 1430 if (inputSource == AUDIO_SOURCE_DEFAULT) { 1431 inputSource = AUDIO_SOURCE_MIC; 1432 } 1433 halInputSource = inputSource; 1434 1435 // Explicit routing? 1436 sp<DeviceDescriptor> deviceDesc; 1437 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) { 1438 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) { 1439 deviceDesc = mAvailableInputDevices[i]; 1440 break; 1441 } 1442 } 1443 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid); 1444 1445 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX && 1446 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) { 1447 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix); 1448 if (ret != NO_ERROR) { 1449 return ret; 1450 } 1451 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE; 1452 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX; 1453 address = String8(attr->tags + strlen("addr=")); 1454 } else { 1455 device = getDeviceAndMixForInputSource(inputSource, &policyMix); 1456 if (device == AUDIO_DEVICE_NONE) { 1457 ALOGW("getInputForAttr() could not find device for source %d", inputSource); 1458 return BAD_VALUE; 1459 } 1460 if (policyMix != NULL) { 1461 address = policyMix->mDeviceAddress; 1462 if (policyMix->mMixType == MIX_TYPE_RECORDERS) { 1463 // there is an external policy, but this input is attached to a mix of recorders, 1464 // meaning it receives audio injected into the framework, so the recorder doesn't 1465 // know about it and is therefore considered "legacy" 1466 *inputType = API_INPUT_LEGACY; 1467 } else { 1468 // recording a mix of players defined by an external policy, we're rerouting for 1469 // an external policy 1470 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE; 1471 } 1472 } else if (audio_is_remote_submix_device(device)) { 1473 address = String8("0"); 1474 *inputType = API_INPUT_MIX_CAPTURE; 1475 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) { 1476 *inputType = API_INPUT_TELEPHONY_RX; 1477 } else { 1478 *inputType = API_INPUT_LEGACY; 1479 } 1480 1481 } 1482 1483 *input = getInputForDevice(device, address, session, uid, inputSource, 1484 samplingRate, format, channelMask, flags, 1485 policyMix); 1486 if (*input == AUDIO_IO_HANDLE_NONE) { 1487 mInputRoutes.removeRoute(session); 1488 return INVALID_OPERATION; 1489 } 1490 ALOGV("getInputForAttr() returns input type = %d", *inputType); 1491 return NO_ERROR; 1492} 1493 1494 1495audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device, 1496 String8 address, 1497 audio_session_t session, 1498 uid_t uid, 1499 audio_source_t inputSource, 1500 uint32_t samplingRate, 1501 audio_format_t format, 1502 audio_channel_mask_t channelMask, 1503 audio_input_flags_t flags, 1504 AudioMix *policyMix) 1505{ 1506 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE; 1507 audio_source_t halInputSource = inputSource; 1508 bool isSoundTrigger = false; 1509 1510 if (inputSource == AUDIO_SOURCE_HOTWORD) { 1511 ssize_t index = mSoundTriggerSessions.indexOfKey(session); 1512 if (index >= 0) { 1513 input = mSoundTriggerSessions.valueFor(session); 1514 isSoundTrigger = true; 1515 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD); 1516 ALOGV("SoundTrigger capture on session %d input %d", session, input); 1517 } else { 1518 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION; 1519 } 1520 } 1521 1522 // find a compatible input profile (not necessarily identical in parameters) 1523 sp<IOProfile> profile; 1524 // samplingRate and flags may be updated by getInputProfile 1525 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate; 1526 audio_format_t profileFormat = format; 1527 audio_channel_mask_t profileChannelMask = channelMask; 1528 audio_input_flags_t profileFlags = flags; 1529 for (;;) { 1530 profile = getInputProfile(device, address, 1531 profileSamplingRate, profileFormat, profileChannelMask, 1532 profileFlags); 1533 if (profile != 0) { 1534 break; // success 1535 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) { 1536 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry 1537 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) { 1538 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry 1539 } else { // fail 1540 ALOGW("getInputForDevice() could not find profile for device 0x%X," 1541 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x", 1542 device, samplingRate, format, channelMask, flags); 1543 return input; 1544 } 1545 } 1546 // Pick input sampling rate if not specified by client 1547 if (samplingRate == 0) { 1548 samplingRate = profileSamplingRate; 1549 } 1550 1551 if (profile->getModuleHandle() == 0) { 1552 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName()); 1553 return input; 1554 } 1555 1556 sp<AudioSession> audioSession = new AudioSession(session, 1557 inputSource, 1558 format, 1559 samplingRate, 1560 channelMask, 1561 flags, 1562 uid, 1563 isSoundTrigger, 1564 policyMix, mpClientInterface); 1565 1566 1567 // reuse an open input if possible 1568 for (size_t i = 0; i < mInputs.size(); i++) { 1569 sp<AudioInputDescriptor> desc = mInputs.valueAt(i); 1570 // reuse input if: 1571 // - it shares the same profile 1572 // AND 1573 // - it is not a reroute submix input 1574 // AND 1575 // - it is: not used for sound trigger 1576 // OR 1577 // used for sound trigger and all clients use the same session ID 1578 // 1579 if ((profile == desc->mProfile) && 1580 (isSoundTrigger == desc->isSoundTrigger()) && 1581 !is_virtual_input_device(device)) { 1582 1583 sp<AudioSession> as = desc->getAudioSession(session); 1584 if (as != 0) { 1585 // do not allow unmatching properties on same session 1586 if (as->matches(audioSession)) { 1587 as->changeOpenCount(1); 1588 } else { 1589 ALOGW("getInputForDevice() record with different attributes" 1590 " exists for session %d", session); 1591 break; 1592 } 1593 } else if (isSoundTrigger) { 1594 break; 1595 } 1596 // force close input if current source is now the highest priority request on this input 1597 // and current input properties are not exactly as requested. 1598 if ((desc->mSamplingRate != samplingRate || 1599 desc->mChannelMask != channelMask || 1600 !audio_formats_match(desc->mFormat, format)) && 1601 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) < 1602 source_priority(inputSource))) { 1603 ALOGV("%s: ", __FUNCTION__); 1604 AudioSessionCollection sessions = desc->getAudioSessions(false /*activeOnly*/); 1605 for (size_t j = 0; j < sessions.size(); j++) { 1606 audio_session_t currentSession = sessions.keyAt(j); 1607 stopInput(desc->mIoHandle, currentSession); 1608 releaseInput(desc->mIoHandle, currentSession); 1609 } 1610 break; 1611 } else { 1612 desc->addAudioSession(session, audioSession); 1613 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i)); 1614 return mInputs.keyAt(i); 1615 } 1616 } 1617 } 1618 1619 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 1620 config.sample_rate = profileSamplingRate; 1621 config.channel_mask = profileChannelMask; 1622 config.format = profileFormat; 1623 1624 status_t status = mpClientInterface->openInput(profile->getModuleHandle(), 1625 &input, 1626 &config, 1627 &device, 1628 address, 1629 halInputSource, 1630 profileFlags); 1631 1632 // only accept input with the exact requested set of parameters 1633 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE || 1634 (profileSamplingRate != config.sample_rate) || 1635 !audio_formats_match(profileFormat, config.format) || 1636 (profileChannelMask != config.channel_mask)) { 1637 ALOGW("getInputForAttr() failed opening input: samplingRate %d" 1638 ", format %d, channelMask %x", 1639 samplingRate, format, channelMask); 1640 if (input != AUDIO_IO_HANDLE_NONE) { 1641 mpClientInterface->closeInput(input); 1642 } 1643 return AUDIO_IO_HANDLE_NONE; 1644 } 1645 1646 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile); 1647 inputDesc->mSamplingRate = profileSamplingRate; 1648 inputDesc->mFormat = profileFormat; 1649 inputDesc->mChannelMask = profileChannelMask; 1650 inputDesc->mDevice = device; 1651 inputDesc->mPolicyMix = policyMix; 1652 inputDesc->addAudioSession(session, audioSession); 1653 1654 addInput(input, inputDesc); 1655 mpClientInterface->onAudioPortListUpdate(); 1656 1657 return input; 1658} 1659 1660bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc, 1661 const sp<AudioSession>& audioSession) 1662{ 1663 // Do not allow capture if an active voice call is using a software patch and 1664 // the call TX source device is on the same HW module. 1665 // FIXME: would be better to refine to only inputs whose profile connects to the 1666 // call TX device but this information is not in the audio patch 1667 if (mCallTxPatch != 0 && 1668 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) { 1669 return false; 1670 } 1671 1672 // starting concurrent capture is enabled if: 1673 // 1) capturing for re-routing 1674 // 2) capturing for HOTWORD source 1675 // 3) capturing for FM TUNER source 1676 // 3) All other active captures are either for re-routing or HOTWORD 1677 1678 if (is_virtual_input_device(inputDesc->mDevice) || 1679 audioSession->inputSource() == AUDIO_SOURCE_HOTWORD || 1680 audioSession->inputSource() == AUDIO_SOURCE_FM_TUNER) { 1681 return true; 1682 } 1683 1684 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs(); 1685 for (size_t i = 0; i < activeInputs.size(); i++) { 1686 sp<AudioInputDescriptor> activeInput = activeInputs[i]; 1687 if ((activeInput->inputSource() != AUDIO_SOURCE_HOTWORD) && 1688 (activeInput->inputSource() != AUDIO_SOURCE_FM_TUNER) && 1689 !is_virtual_input_device(activeInput->mDevice)) { 1690 return false; 1691 } 1692 } 1693 1694 return true; 1695} 1696 1697 1698status_t AudioPolicyManager::startInput(audio_io_handle_t input, 1699 audio_session_t session, 1700 concurrency_type__mask_t *concurrency) 1701{ 1702 ALOGV("startInput() input %d", input); 1703 *concurrency = API_INPUT_CONCURRENCY_NONE; 1704 ssize_t index = mInputs.indexOfKey(input); 1705 if (index < 0) { 1706 ALOGW("startInput() unknown input %d", input); 1707 return BAD_VALUE; 1708 } 1709 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index); 1710 1711 sp<AudioSession> audioSession = inputDesc->getAudioSession(session); 1712 if (audioSession == 0) { 1713 ALOGW("startInput() unknown session %d on input %d", session, input); 1714 return BAD_VALUE; 1715 } 1716 1717 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) { 1718 ALOGW("startInput(%d) failed: other input already started", input); 1719 return INVALID_OPERATION; 1720 } 1721 1722 if (isInCall()) { 1723 *concurrency |= API_INPUT_CONCURRENCY_CALL; 1724 } 1725 if (mInputs.activeInputsCount() != 0) { 1726 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE; 1727 } 1728 1729 // increment activity count before calling getNewInputDevice() below as only active sessions 1730 // are considered for device selection 1731 audioSession->changeActiveCount(1); 1732 1733 // Routing? 1734 mInputRoutes.incRouteActivity(session); 1735 1736 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) { 1737 1738 setInputDevice(input, getNewInputDevice(inputDesc), true /* force */); 1739 1740 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) { 1741 // if input maps to a dynamic policy with an activity listener, notify of state change 1742 if ((inputDesc->mPolicyMix != NULL) 1743 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) { 1744 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress, 1745 MIX_STATE_MIXING); 1746 } 1747 1748 if (mInputs.activeInputsCount() == 0) { 1749 SoundTrigger::setCaptureState(true); 1750 } 1751 1752 // automatically enable the remote submix output when input is started if not 1753 // used by a policy mix of type MIX_TYPE_RECORDERS 1754 // For remote submix (a virtual device), we open only one input per capture request. 1755 if (audio_is_remote_submix_device(inputDesc->mDevice)) { 1756 String8 address = String8(""); 1757 if (inputDesc->mPolicyMix == NULL) { 1758 address = String8("0"); 1759 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) { 1760 address = inputDesc->mPolicyMix->mDeviceAddress; 1761 } 1762 if (address != "") { 1763 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, 1764 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, 1765 address, "remote-submix"); 1766 } 1767 } 1768 } 1769 } 1770 1771 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource()); 1772 1773 return NO_ERROR; 1774} 1775 1776status_t AudioPolicyManager::stopInput(audio_io_handle_t input, 1777 audio_session_t session) 1778{ 1779 ALOGV("stopInput() input %d", input); 1780 ssize_t index = mInputs.indexOfKey(input); 1781 if (index < 0) { 1782 ALOGW("stopInput() unknown input %d", input); 1783 return BAD_VALUE; 1784 } 1785 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index); 1786 1787 sp<AudioSession> audioSession = inputDesc->getAudioSession(session); 1788 if (index < 0) { 1789 ALOGW("stopInput() unknown session %d on input %d", session, input); 1790 return BAD_VALUE; 1791 } 1792 1793 if (audioSession->activeCount() == 0) { 1794 ALOGW("stopInput() input %d already stopped", input); 1795 return INVALID_OPERATION; 1796 } 1797 1798 audioSession->changeActiveCount(-1); 1799 1800 // Routing? 1801 mInputRoutes.decRouteActivity(session); 1802 1803 if (audioSession->activeCount() == 0) { 1804 1805 if (inputDesc->isActive()) { 1806 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */); 1807 } else { 1808 // if input maps to a dynamic policy with an activity listener, notify of state change 1809 if ((inputDesc->mPolicyMix != NULL) 1810 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) { 1811 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress, 1812 MIX_STATE_IDLE); 1813 } 1814 1815 // automatically disable the remote submix output when input is stopped if not 1816 // used by a policy mix of type MIX_TYPE_RECORDERS 1817 if (audio_is_remote_submix_device(inputDesc->mDevice)) { 1818 String8 address = String8(""); 1819 if (inputDesc->mPolicyMix == NULL) { 1820 address = String8("0"); 1821 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) { 1822 address = inputDesc->mPolicyMix->mDeviceAddress; 1823 } 1824 if (address != "") { 1825 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, 1826 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, 1827 address, "remote-submix"); 1828 } 1829 } 1830 1831 resetInputDevice(input); 1832 1833 if (mInputs.activeInputsCount() == 0) { 1834 SoundTrigger::setCaptureState(false); 1835 } 1836 inputDesc->clearPreemptedSessions(); 1837 } 1838 } 1839 return NO_ERROR; 1840} 1841 1842void AudioPolicyManager::releaseInput(audio_io_handle_t input, 1843 audio_session_t session) 1844{ 1845 1846 ALOGV("releaseInput() %d", input); 1847 ssize_t index = mInputs.indexOfKey(input); 1848 if (index < 0) { 1849 ALOGW("releaseInput() releasing unknown input %d", input); 1850 return; 1851 } 1852 1853 // Routing 1854 mInputRoutes.removeRoute(session); 1855 1856 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index); 1857 ALOG_ASSERT(inputDesc != 0); 1858 1859 sp<AudioSession> audioSession = inputDesc->getAudioSession(session); 1860 if (index < 0) { 1861 ALOGW("releaseInput() unknown session %d on input %d", session, input); 1862 return; 1863 } 1864 1865 if (audioSession->openCount() == 0) { 1866 ALOGW("releaseInput() invalid open count %d on session %d", 1867 audioSession->openCount(), session); 1868 return; 1869 } 1870 1871 if (audioSession->changeOpenCount(-1) == 0) { 1872 inputDesc->removeAudioSession(session); 1873 } 1874 1875 if (inputDesc->getOpenRefCount() > 0) { 1876 ALOGV("releaseInput() exit > 0"); 1877 return; 1878 } 1879 1880 closeInput(input); 1881 mpClientInterface->onAudioPortListUpdate(); 1882 ALOGV("releaseInput() exit"); 1883} 1884 1885void AudioPolicyManager::closeAllInputs() { 1886 bool patchRemoved = false; 1887 1888 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) { 1889 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index); 1890 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle()); 1891 if (patch_index >= 0) { 1892 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index); 1893 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 1894 mAudioPatches.removeItemsAt(patch_index); 1895 patchRemoved = true; 1896 } 1897 mpClientInterface->closeInput(mInputs.keyAt(input_index)); 1898 } 1899 mInputs.clear(); 1900 SoundTrigger::setCaptureState(false); 1901 nextAudioPortGeneration(); 1902 1903 if (patchRemoved) { 1904 mpClientInterface->onAudioPatchListUpdate(); 1905 } 1906} 1907 1908void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, 1909 int indexMin, 1910 int indexMax) 1911{ 1912 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax); 1913 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax); 1914 1915 // initialize other private stream volumes which follow this one 1916 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) { 1917 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) { 1918 continue; 1919 } 1920 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax); 1921 } 1922} 1923 1924status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream, 1925 int index, 1926 audio_devices_t device) 1927{ 1928 1929 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) || 1930 (index > mVolumeCurves->getVolumeIndexMax(stream))) { 1931 return BAD_VALUE; 1932 } 1933 if (!audio_is_output_device(device)) { 1934 return BAD_VALUE; 1935 } 1936 1937 // Force max volume if stream cannot be muted 1938 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream); 1939 1940 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d", 1941 stream, device, index); 1942 1943 // update other private stream volumes which follow this one 1944 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) { 1945 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) { 1946 continue; 1947 } 1948 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index); 1949 } 1950 1951 // update volume on all outputs and streams matching the following: 1952 // - The requested stream (or a stream matching for volume control) is active on the output 1953 // - The device (or devices) selected by the strategy corresponding to this stream includes 1954 // the requested device 1955 // - For non default requested device, currently selected device on the output is either the 1956 // requested device or one of the devices selected by the strategy 1957 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if 1958 // no specific device volume value exists for currently selected device. 1959 status_t status = NO_ERROR; 1960 for (size_t i = 0; i < mOutputs.size(); i++) { 1961 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i); 1962 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device()); 1963 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) { 1964 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) { 1965 continue; 1966 } 1967 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || 1968 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) { 1969 continue; 1970 } 1971 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream); 1972 audio_devices_t curStreamDevice = getDeviceForStrategy(curStrategy, true /*fromCache*/); 1973 if ((curStreamDevice & device) == 0) { 1974 continue; 1975 } 1976 bool applyDefault = false; 1977 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) { 1978 curStreamDevice |= device; 1979 } else if (!mVolumeCurves->hasVolumeIndexForDevice( 1980 stream, Volume::getDeviceForVolume(curStreamDevice))) { 1981 applyDefault = true; 1982 } 1983 1984 if (applyDefault || ((curDevice & curStreamDevice) != 0)) { 1985 //FIXME: workaround for truncated touch sounds 1986 // delayed volume change for system stream to be removed when the problem is 1987 // handled by system UI 1988 status_t volStatus = 1989 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice, 1990 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0); 1991 if (volStatus != NO_ERROR) { 1992 status = volStatus; 1993 } 1994 } 1995 } 1996 } 1997 return status; 1998} 1999 2000status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream, 2001 int *index, 2002 audio_devices_t device) 2003{ 2004 if (index == NULL) { 2005 return BAD_VALUE; 2006 } 2007 if (!audio_is_output_device(device)) { 2008 return BAD_VALUE; 2009 } 2010 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to 2011 // the strategy the stream belongs to. 2012 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) { 2013 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/); 2014 } 2015 device = Volume::getDeviceForVolume(device); 2016 2017 *index = mVolumeCurves->getVolumeIndex(stream, device); 2018 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index); 2019 return NO_ERROR; 2020} 2021 2022audio_io_handle_t AudioPolicyManager::selectOutputForEffects( 2023 const SortedVector<audio_io_handle_t>& outputs) 2024{ 2025 // select one output among several suitable for global effects. 2026 // The priority is as follows: 2027 // 1: An offloaded output. If the effect ends up not being offloadable, 2028 // AudioFlinger will invalidate the track and the offloaded output 2029 // will be closed causing the effect to be moved to a PCM output. 2030 // 2: A deep buffer output 2031 // 3: the first output in the list 2032 2033 if (outputs.size() == 0) { 2034 return 0; 2035 } 2036 2037 audio_io_handle_t outputOffloaded = 0; 2038 audio_io_handle_t outputDeepBuffer = 0; 2039 2040 for (size_t i = 0; i < outputs.size(); i++) { 2041 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]); 2042 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags); 2043 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) { 2044 outputOffloaded = outputs[i]; 2045 } 2046 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) { 2047 outputDeepBuffer = outputs[i]; 2048 } 2049 } 2050 2051 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d", 2052 outputOffloaded, outputDeepBuffer); 2053 if (outputOffloaded != 0) { 2054 return outputOffloaded; 2055 } 2056 if (outputDeepBuffer != 0) { 2057 return outputDeepBuffer; 2058 } 2059 2060 return outputs[0]; 2061} 2062 2063audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc) 2064{ 2065 // apply simple rule where global effects are attached to the same output as MUSIC streams 2066 2067 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC); 2068 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/); 2069 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs); 2070 2071 audio_io_handle_t output = selectOutputForEffects(dstOutputs); 2072 ALOGV("getOutputForEffect() got output %d for fx %s flags %x", 2073 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags); 2074 2075 return output; 2076} 2077 2078status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc, 2079 audio_io_handle_t io, 2080 uint32_t strategy, 2081 int session, 2082 int id) 2083{ 2084 ssize_t index = mOutputs.indexOfKey(io); 2085 if (index < 0) { 2086 index = mInputs.indexOfKey(io); 2087 if (index < 0) { 2088 ALOGW("registerEffect() unknown io %d", io); 2089 return INVALID_OPERATION; 2090 } 2091 } 2092 return mEffects.registerEffect(desc, io, strategy, session, id); 2093} 2094 2095bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const 2096{ 2097 bool active = false; 2098 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) { 2099 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) { 2100 continue; 2101 } 2102 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs); 2103 } 2104 return active; 2105} 2106 2107bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const 2108{ 2109 return mOutputs.isStreamActiveRemotely(stream, inPastMs); 2110} 2111 2112bool AudioPolicyManager::isSourceActive(audio_source_t source) const 2113{ 2114 for (size_t i = 0; i < mInputs.size(); i++) { 2115 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i); 2116 if (inputDescriptor->isSourceActive(source)) { 2117 return true; 2118 } 2119 } 2120 return false; 2121} 2122 2123// Register a list of custom mixes with their attributes and format. 2124// When a mix is registered, corresponding input and output profiles are 2125// added to the remote submix hw module. The profile contains only the 2126// parameters (sampling rate, format...) specified by the mix. 2127// The corresponding input remote submix device is also connected. 2128// 2129// When a remote submix device is connected, the address is checked to select the 2130// appropriate profile and the corresponding input or output stream is opened. 2131// 2132// When capture starts, getInputForAttr() will: 2133// - 1 look for a mix matching the address passed in attribtutes tags if any 2134// - 2 if none found, getDeviceForInputSource() will: 2135// - 2.1 look for a mix matching the attributes source 2136// - 2.2 if none found, default to device selection by policy rules 2137// At this time, the corresponding output remote submix device is also connected 2138// and active playback use cases can be transferred to this mix if needed when reconnecting 2139// after AudioTracks are invalidated 2140// 2141// When playback starts, getOutputForAttr() will: 2142// - 1 look for a mix matching the address passed in attribtutes tags if any 2143// - 2 if none found, look for a mix matching the attributes usage 2144// - 3 if none found, default to device and output selection by policy rules. 2145 2146status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes) 2147{ 2148 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size()); 2149 status_t res = NO_ERROR; 2150 2151 sp<HwModule> rSubmixModule; 2152 // examine each mix's route type 2153 for (size_t i = 0; i < mixes.size(); i++) { 2154 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination 2155 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) { 2156 res = INVALID_OPERATION; 2157 break; 2158 } 2159 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) { 2160 // Loop back through "remote submix" 2161 if (rSubmixModule == 0) { 2162 for (size_t j = 0; i < mHwModules.size(); j++) { 2163 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0 2164 && mHwModules[j]->mHandle != 0) { 2165 rSubmixModule = mHwModules[j]; 2166 break; 2167 } 2168 } 2169 } 2170 2171 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size()); 2172 2173 if (rSubmixModule == 0) { 2174 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i); 2175 res = INVALID_OPERATION; 2176 break; 2177 } 2178 2179 String8 address = mixes[i].mDeviceAddress; 2180 2181 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) { 2182 ALOGE(" Error registering mix %zu for address %s", i, address.string()); 2183 res = INVALID_OPERATION; 2184 break; 2185 } 2186 audio_config_t outputConfig = mixes[i].mFormat; 2187 audio_config_t inputConfig = mixes[i].mFormat; 2188 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in 2189 // stereo and let audio flinger do the channel conversion if needed. 2190 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO; 2191 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO; 2192 rSubmixModule->addOutputProfile(address, &outputConfig, 2193 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address); 2194 rSubmixModule->addInputProfile(address, &inputConfig, 2195 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address); 2196 2197 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) { 2198 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX, 2199 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, 2200 address.string(), "remote-submix"); 2201 } else { 2202 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, 2203 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, 2204 address.string(), "remote-submix"); 2205 } 2206 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) { 2207 String8 address = mixes[i].mDeviceAddress; 2208 audio_devices_t device = mixes[i].mDeviceType; 2209 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s", 2210 i, mixes.size(), device, address.string()); 2211 2212 bool foundOutput = false; 2213 for (size_t j = 0 ; j < mOutputs.size() ; j++) { 2214 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j); 2215 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle()); 2216 if ((patch != 0) && (patch->mPatch.num_sinks != 0) 2217 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE) 2218 && (patch->mPatch.sinks[0].ext.device.type == device) 2219 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(), 2220 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) { 2221 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) { 2222 res = INVALID_OPERATION; 2223 } else { 2224 foundOutput = true; 2225 } 2226 break; 2227 } 2228 } 2229 2230 if (res != NO_ERROR) { 2231 ALOGE(" Error registering mix %zu for device 0x%X addr %s", 2232 i, device, address.string()); 2233 res = INVALID_OPERATION; 2234 break; 2235 } else if (!foundOutput) { 2236 ALOGE(" Output not found for mix %zu for device 0x%X addr %s", 2237 i, device, address.string()); 2238 res = INVALID_OPERATION; 2239 break; 2240 } 2241 } 2242 } 2243 if (res != NO_ERROR) { 2244 unregisterPolicyMixes(mixes); 2245 } 2246 return res; 2247} 2248 2249status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes) 2250{ 2251 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size()); 2252 status_t res = NO_ERROR; 2253 sp<HwModule> rSubmixModule; 2254 // examine each mix's route type 2255 for (size_t i = 0; i < mixes.size(); i++) { 2256 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) { 2257 2258 if (rSubmixModule == 0) { 2259 for (size_t j = 0; i < mHwModules.size(); j++) { 2260 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0 2261 && mHwModules[j]->mHandle != 0) { 2262 rSubmixModule = mHwModules[j]; 2263 break; 2264 } 2265 } 2266 } 2267 if (rSubmixModule == 0) { 2268 res = INVALID_OPERATION; 2269 continue; 2270 } 2271 2272 String8 address = mixes[i].mDeviceAddress; 2273 2274 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) { 2275 res = INVALID_OPERATION; 2276 continue; 2277 } 2278 2279 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) == 2280 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) { 2281 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX, 2282 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, 2283 address.string(), "remote-submix"); 2284 } 2285 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) == 2286 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) { 2287 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, 2288 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, 2289 address.string(), "remote-submix"); 2290 } 2291 rSubmixModule->removeOutputProfile(address); 2292 rSubmixModule->removeInputProfile(address); 2293 2294 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) { 2295 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) { 2296 res = INVALID_OPERATION; 2297 continue; 2298 } 2299 } 2300 } 2301 return res; 2302} 2303 2304 2305status_t AudioPolicyManager::dump(int fd) 2306{ 2307 const size_t SIZE = 256; 2308 char buffer[SIZE]; 2309 String8 result; 2310 2311 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this); 2312 result.append(buffer); 2313 2314 snprintf(buffer, SIZE, " Primary Output: %d\n", 2315 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE); 2316 result.append(buffer); 2317 std::string stateLiteral; 2318 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral); 2319 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str()); 2320 result.append(buffer); 2321 snprintf(buffer, SIZE, " Force use for communications %d\n", 2322 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION)); 2323 result.append(buffer); 2324 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA)); 2325 result.append(buffer); 2326 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD)); 2327 result.append(buffer); 2328 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK)); 2329 result.append(buffer); 2330 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM)); 2331 result.append(buffer); 2332 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n", 2333 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO)); 2334 result.append(buffer); 2335 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n", 2336 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND)); 2337 result.append(buffer); 2338 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available"); 2339 result.append(buffer); 2340 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off"); 2341 result.append(buffer); 2342 2343 write(fd, result.string(), result.size()); 2344 2345 mAvailableOutputDevices.dump(fd, String8("Available output")); 2346 mAvailableInputDevices.dump(fd, String8("Available input")); 2347 mHwModules.dump(fd); 2348 mOutputs.dump(fd); 2349 mInputs.dump(fd); 2350 mVolumeCurves->dump(fd); 2351 mEffects.dump(fd); 2352 mAudioPatches.dump(fd); 2353 2354 return NO_ERROR; 2355} 2356 2357// This function checks for the parameters which can be offloaded. 2358// This can be enhanced depending on the capability of the DSP and policy 2359// of the system. 2360bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo) 2361{ 2362 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d," 2363 " BitRate=%u, duration=%" PRId64 " us, has_video=%d", 2364 offloadInfo.sample_rate, offloadInfo.channel_mask, 2365 offloadInfo.format, 2366 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us, 2367 offloadInfo.has_video); 2368 2369 if (mMasterMono) { 2370 return false; // no offloading if mono is set. 2371 } 2372 2373 // Check if offload has been disabled 2374 char propValue[PROPERTY_VALUE_MAX]; 2375 if (property_get("audio.offload.disable", propValue, "0")) { 2376 if (atoi(propValue) != 0) { 2377 ALOGV("offload disabled by audio.offload.disable=%s", propValue ); 2378 return false; 2379 } 2380 } 2381 2382 // Check if stream type is music, then only allow offload as of now. 2383 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC) 2384 { 2385 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false"); 2386 return false; 2387 } 2388 2389 //TODO: enable audio offloading with video when ready 2390 const bool allowOffloadWithVideo = 2391 property_get_bool("audio.offload.video", false /* default_value */); 2392 if (offloadInfo.has_video && !allowOffloadWithVideo) { 2393 ALOGV("isOffloadSupported: has_video == true, returning false"); 2394 return false; 2395 } 2396 2397 //If duration is less than minimum value defined in property, return false 2398 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) { 2399 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) { 2400 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue); 2401 return false; 2402 } 2403 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) { 2404 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS); 2405 return false; 2406 } 2407 2408 // Do not allow offloading if one non offloadable effect is enabled. This prevents from 2409 // creating an offloaded track and tearing it down immediately after start when audioflinger 2410 // detects there is an active non offloadable effect. 2411 // FIXME: We should check the audio session here but we do not have it in this context. 2412 // This may prevent offloading in rare situations where effects are left active by apps 2413 // in the background. 2414 if (mEffects.isNonOffloadableEffectEnabled()) { 2415 return false; 2416 } 2417 2418 // See if there is a profile to support this. 2419 // AUDIO_DEVICE_NONE 2420 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */, 2421 offloadInfo.sample_rate, 2422 offloadInfo.format, 2423 offloadInfo.channel_mask, 2424 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD); 2425 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT "); 2426 return (profile != 0); 2427} 2428 2429status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role, 2430 audio_port_type_t type, 2431 unsigned int *num_ports, 2432 struct audio_port *ports, 2433 unsigned int *generation) 2434{ 2435 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) || 2436 generation == NULL) { 2437 return BAD_VALUE; 2438 } 2439 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports); 2440 if (ports == NULL) { 2441 *num_ports = 0; 2442 } 2443 2444 size_t portsWritten = 0; 2445 size_t portsMax = *num_ports; 2446 *num_ports = 0; 2447 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) { 2448 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB 2449 // as they are used by stub HALs by convention 2450 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) { 2451 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) { 2452 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) { 2453 continue; 2454 } 2455 if (portsWritten < portsMax) { 2456 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]); 2457 } 2458 (*num_ports)++; 2459 } 2460 } 2461 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) { 2462 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) { 2463 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) { 2464 continue; 2465 } 2466 if (portsWritten < portsMax) { 2467 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]); 2468 } 2469 (*num_ports)++; 2470 } 2471 } 2472 } 2473 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) { 2474 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) { 2475 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) { 2476 mInputs[i]->toAudioPort(&ports[portsWritten++]); 2477 } 2478 *num_ports += mInputs.size(); 2479 } 2480 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) { 2481 size_t numOutputs = 0; 2482 for (size_t i = 0; i < mOutputs.size(); i++) { 2483 if (!mOutputs[i]->isDuplicated()) { 2484 numOutputs++; 2485 if (portsWritten < portsMax) { 2486 mOutputs[i]->toAudioPort(&ports[portsWritten++]); 2487 } 2488 } 2489 } 2490 *num_ports += numOutputs; 2491 } 2492 } 2493 *generation = curAudioPortGeneration(); 2494 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports); 2495 return NO_ERROR; 2496} 2497 2498status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused) 2499{ 2500 return NO_ERROR; 2501} 2502 2503status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch, 2504 audio_patch_handle_t *handle, 2505 uid_t uid) 2506{ 2507 ALOGV("createAudioPatch()"); 2508 2509 if (handle == NULL || patch == NULL) { 2510 return BAD_VALUE; 2511 } 2512 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks); 2513 2514 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX || 2515 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) { 2516 return BAD_VALUE; 2517 } 2518 // only one source per audio patch supported for now 2519 if (patch->num_sources > 1) { 2520 return INVALID_OPERATION; 2521 } 2522 2523 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) { 2524 return INVALID_OPERATION; 2525 } 2526 for (size_t i = 0; i < patch->num_sinks; i++) { 2527 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) { 2528 return INVALID_OPERATION; 2529 } 2530 } 2531 2532 sp<AudioPatch> patchDesc; 2533 ssize_t index = mAudioPatches.indexOfKey(*handle); 2534 2535 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id, 2536 patch->sources[0].role, 2537 patch->sources[0].type); 2538#if LOG_NDEBUG == 0 2539 for (size_t i = 0; i < patch->num_sinks; i++) { 2540 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id, 2541 patch->sinks[i].role, 2542 patch->sinks[i].type); 2543 } 2544#endif 2545 2546 if (index >= 0) { 2547 patchDesc = mAudioPatches.valueAt(index); 2548 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d", 2549 mUidCached, patchDesc->mUid, uid); 2550 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) { 2551 return INVALID_OPERATION; 2552 } 2553 } else { 2554 *handle = AUDIO_PATCH_HANDLE_NONE; 2555 } 2556 2557 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) { 2558 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id); 2559 if (outputDesc == NULL) { 2560 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id); 2561 return BAD_VALUE; 2562 } 2563 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports", 2564 outputDesc->mIoHandle); 2565 if (patchDesc != 0) { 2566 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) { 2567 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d", 2568 patchDesc->mPatch.sources[0].id, patch->sources[0].id); 2569 return BAD_VALUE; 2570 } 2571 } 2572 DeviceVector devices; 2573 for (size_t i = 0; i < patch->num_sinks; i++) { 2574 // Only support mix to devices connection 2575 // TODO add support for mix to mix connection 2576 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) { 2577 ALOGV("createAudioPatch() source mix but sink is not a device"); 2578 return INVALID_OPERATION; 2579 } 2580 sp<DeviceDescriptor> devDesc = 2581 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id); 2582 if (devDesc == 0) { 2583 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id); 2584 return BAD_VALUE; 2585 } 2586 2587 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(), 2588 devDesc->mAddress, 2589 patch->sources[0].sample_rate, 2590 NULL, // updatedSamplingRate 2591 patch->sources[0].format, 2592 NULL, // updatedFormat 2593 patch->sources[0].channel_mask, 2594 NULL, // updatedChannelMask 2595 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) { 2596 ALOGV("createAudioPatch() profile not supported for device %08x", 2597 devDesc->type()); 2598 return INVALID_OPERATION; 2599 } 2600 devices.add(devDesc); 2601 } 2602 if (devices.size() == 0) { 2603 return INVALID_OPERATION; 2604 } 2605 2606 // TODO: reconfigure output format and channels here 2607 ALOGV("createAudioPatch() setting device %08x on output %d", 2608 devices.types(), outputDesc->mIoHandle); 2609 setOutputDevice(outputDesc, devices.types(), true, 0, handle); 2610 index = mAudioPatches.indexOfKey(*handle); 2611 if (index >= 0) { 2612 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) { 2613 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided"); 2614 } 2615 patchDesc = mAudioPatches.valueAt(index); 2616 patchDesc->mUid = uid; 2617 ALOGV("createAudioPatch() success"); 2618 } else { 2619 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch"); 2620 return INVALID_OPERATION; 2621 } 2622 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) { 2623 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) { 2624 // input device to input mix connection 2625 // only one sink supported when connecting an input device to a mix 2626 if (patch->num_sinks > 1) { 2627 return INVALID_OPERATION; 2628 } 2629 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id); 2630 if (inputDesc == NULL) { 2631 return BAD_VALUE; 2632 } 2633 if (patchDesc != 0) { 2634 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) { 2635 return BAD_VALUE; 2636 } 2637 } 2638 sp<DeviceDescriptor> devDesc = 2639 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id); 2640 if (devDesc == 0) { 2641 return BAD_VALUE; 2642 } 2643 2644 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(), 2645 devDesc->mAddress, 2646 patch->sinks[0].sample_rate, 2647 NULL, /*updatedSampleRate*/ 2648 patch->sinks[0].format, 2649 NULL, /*updatedFormat*/ 2650 patch->sinks[0].channel_mask, 2651 NULL, /*updatedChannelMask*/ 2652 // FIXME for the parameter type, 2653 // and the NONE 2654 (audio_output_flags_t) 2655 AUDIO_INPUT_FLAG_NONE)) { 2656 return INVALID_OPERATION; 2657 } 2658 // TODO: reconfigure output format and channels here 2659 ALOGV("createAudioPatch() setting device %08x on output %d", 2660 devDesc->type(), inputDesc->mIoHandle); 2661 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle); 2662 index = mAudioPatches.indexOfKey(*handle); 2663 if (index >= 0) { 2664 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) { 2665 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided"); 2666 } 2667 patchDesc = mAudioPatches.valueAt(index); 2668 patchDesc->mUid = uid; 2669 ALOGV("createAudioPatch() success"); 2670 } else { 2671 ALOGW("createAudioPatch() setInputDevice() failed to create a patch"); 2672 return INVALID_OPERATION; 2673 } 2674 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) { 2675 // device to device connection 2676 if (patchDesc != 0) { 2677 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) { 2678 return BAD_VALUE; 2679 } 2680 } 2681 sp<DeviceDescriptor> srcDeviceDesc = 2682 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id); 2683 if (srcDeviceDesc == 0) { 2684 return BAD_VALUE; 2685 } 2686 2687 //update source and sink with our own data as the data passed in the patch may 2688 // be incomplete. 2689 struct audio_patch newPatch = *patch; 2690 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]); 2691 2692 for (size_t i = 0; i < patch->num_sinks; i++) { 2693 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) { 2694 ALOGV("createAudioPatch() source device but one sink is not a device"); 2695 return INVALID_OPERATION; 2696 } 2697 2698 sp<DeviceDescriptor> sinkDeviceDesc = 2699 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id); 2700 if (sinkDeviceDesc == 0) { 2701 return BAD_VALUE; 2702 } 2703 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]); 2704 2705 // create a software bridge in PatchPanel if: 2706 // - source and sink devices are on differnt HW modules OR 2707 // - audio HAL version is < 3.0 2708 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) || 2709 (srcDeviceDesc->mModule->getHalVersion() < AUDIO_DEVICE_API_VERSION_3_0)) { 2710 // support only one sink device for now to simplify output selection logic 2711 if (patch->num_sinks > 1) { 2712 return INVALID_OPERATION; 2713 } 2714 SortedVector<audio_io_handle_t> outputs = 2715 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs); 2716 // if the sink device is reachable via an opened output stream, request to go via 2717 // this output stream by adding a second source to the patch description 2718 audio_io_handle_t output = selectOutput(outputs, 2719 AUDIO_OUTPUT_FLAG_NONE, 2720 AUDIO_FORMAT_INVALID); 2721 if (output != AUDIO_IO_HANDLE_NONE) { 2722 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 2723 if (outputDesc->isDuplicated()) { 2724 return INVALID_OPERATION; 2725 } 2726 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]); 2727 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH; 2728 newPatch.num_sources = 2; 2729 } 2730 } 2731 } 2732 // TODO: check from routing capabilities in config file and other conflicting patches 2733 2734 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 2735 if (index >= 0) { 2736 afPatchHandle = patchDesc->mAfPatchHandle; 2737 } 2738 2739 status_t status = mpClientInterface->createAudioPatch(&newPatch, 2740 &afPatchHandle, 2741 0); 2742 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d", 2743 status, afPatchHandle); 2744 if (status == NO_ERROR) { 2745 if (index < 0) { 2746 patchDesc = new AudioPatch(&newPatch, uid); 2747 addAudioPatch(patchDesc->mHandle, patchDesc); 2748 } else { 2749 patchDesc->mPatch = newPatch; 2750 } 2751 patchDesc->mAfPatchHandle = afPatchHandle; 2752 *handle = patchDesc->mHandle; 2753 nextAudioPortGeneration(); 2754 mpClientInterface->onAudioPatchListUpdate(); 2755 } else { 2756 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d", 2757 status); 2758 return INVALID_OPERATION; 2759 } 2760 } else { 2761 return BAD_VALUE; 2762 } 2763 } else { 2764 return BAD_VALUE; 2765 } 2766 return NO_ERROR; 2767} 2768 2769status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, 2770 uid_t uid) 2771{ 2772 ALOGV("releaseAudioPatch() patch %d", handle); 2773 2774 ssize_t index = mAudioPatches.indexOfKey(handle); 2775 2776 if (index < 0) { 2777 return BAD_VALUE; 2778 } 2779 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 2780 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d", 2781 mUidCached, patchDesc->mUid, uid); 2782 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) { 2783 return INVALID_OPERATION; 2784 } 2785 2786 struct audio_patch *patch = &patchDesc->mPatch; 2787 patchDesc->mUid = mUidCached; 2788 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) { 2789 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id); 2790 if (outputDesc == NULL) { 2791 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id); 2792 return BAD_VALUE; 2793 } 2794 2795 setOutputDevice(outputDesc, 2796 getNewOutputDevice(outputDesc, true /*fromCache*/), 2797 true, 2798 0, 2799 NULL); 2800 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) { 2801 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) { 2802 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id); 2803 if (inputDesc == NULL) { 2804 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id); 2805 return BAD_VALUE; 2806 } 2807 setInputDevice(inputDesc->mIoHandle, 2808 getNewInputDevice(inputDesc), 2809 true, 2810 NULL); 2811 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) { 2812 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 2813 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d", 2814 status, patchDesc->mAfPatchHandle); 2815 removeAudioPatch(patchDesc->mHandle); 2816 nextAudioPortGeneration(); 2817 mpClientInterface->onAudioPatchListUpdate(); 2818 } else { 2819 return BAD_VALUE; 2820 } 2821 } else { 2822 return BAD_VALUE; 2823 } 2824 return NO_ERROR; 2825} 2826 2827status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches, 2828 struct audio_patch *patches, 2829 unsigned int *generation) 2830{ 2831 if (generation == NULL) { 2832 return BAD_VALUE; 2833 } 2834 *generation = curAudioPortGeneration(); 2835 return mAudioPatches.listAudioPatches(num_patches, patches); 2836} 2837 2838status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config) 2839{ 2840 ALOGV("setAudioPortConfig()"); 2841 2842 if (config == NULL) { 2843 return BAD_VALUE; 2844 } 2845 ALOGV("setAudioPortConfig() on port handle %d", config->id); 2846 // Only support gain configuration for now 2847 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) { 2848 return INVALID_OPERATION; 2849 } 2850 2851 sp<AudioPortConfig> audioPortConfig; 2852 if (config->type == AUDIO_PORT_TYPE_MIX) { 2853 if (config->role == AUDIO_PORT_ROLE_SOURCE) { 2854 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id); 2855 if (outputDesc == NULL) { 2856 return BAD_VALUE; 2857 } 2858 ALOG_ASSERT(!outputDesc->isDuplicated(), 2859 "setAudioPortConfig() called on duplicated output %d", 2860 outputDesc->mIoHandle); 2861 audioPortConfig = outputDesc; 2862 } else if (config->role == AUDIO_PORT_ROLE_SINK) { 2863 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id); 2864 if (inputDesc == NULL) { 2865 return BAD_VALUE; 2866 } 2867 audioPortConfig = inputDesc; 2868 } else { 2869 return BAD_VALUE; 2870 } 2871 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) { 2872 sp<DeviceDescriptor> deviceDesc; 2873 if (config->role == AUDIO_PORT_ROLE_SOURCE) { 2874 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id); 2875 } else if (config->role == AUDIO_PORT_ROLE_SINK) { 2876 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id); 2877 } else { 2878 return BAD_VALUE; 2879 } 2880 if (deviceDesc == NULL) { 2881 return BAD_VALUE; 2882 } 2883 audioPortConfig = deviceDesc; 2884 } else { 2885 return BAD_VALUE; 2886 } 2887 2888 struct audio_port_config backupConfig; 2889 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig); 2890 if (status == NO_ERROR) { 2891 struct audio_port_config newConfig; 2892 audioPortConfig->toAudioPortConfig(&newConfig, config); 2893 status = mpClientInterface->setAudioPortConfig(&newConfig, 0); 2894 } 2895 if (status != NO_ERROR) { 2896 audioPortConfig->applyAudioPortConfig(&backupConfig); 2897 } 2898 2899 return status; 2900} 2901 2902void AudioPolicyManager::releaseResourcesForUid(uid_t uid) 2903{ 2904 clearAudioSources(uid); 2905 clearAudioPatches(uid); 2906 clearSessionRoutes(uid); 2907} 2908 2909void AudioPolicyManager::clearAudioPatches(uid_t uid) 2910{ 2911 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) { 2912 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i); 2913 if (patchDesc->mUid == uid) { 2914 releaseAudioPatch(mAudioPatches.keyAt(i), uid); 2915 } 2916 } 2917} 2918 2919void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy, 2920 audio_io_handle_t ouptutToSkip) 2921{ 2922 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/); 2923 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs); 2924 for (size_t j = 0; j < mOutputs.size(); j++) { 2925 if (mOutputs.keyAt(j) == ouptutToSkip) { 2926 continue; 2927 } 2928 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j); 2929 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) { 2930 continue; 2931 } 2932 // If the default device for this strategy is on another output mix, 2933 // invalidate all tracks in this strategy to force re connection. 2934 // Otherwise select new device on the output mix. 2935 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) { 2936 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) { 2937 if (getStrategy((audio_stream_type_t)stream) == strategy) { 2938 mpClientInterface->invalidateStream((audio_stream_type_t)stream); 2939 } 2940 } 2941 } else { 2942 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/); 2943 setOutputDevice(outputDesc, newDevice, false); 2944 } 2945 } 2946} 2947 2948void AudioPolicyManager::clearSessionRoutes(uid_t uid) 2949{ 2950 // remove output routes associated with this uid 2951 SortedVector<routing_strategy> affectedStrategies; 2952 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) { 2953 sp<SessionRoute> route = mOutputRoutes.valueAt(i); 2954 if (route->mUid == uid) { 2955 mOutputRoutes.removeItemsAt(i); 2956 if (route->mDeviceDescriptor != 0) { 2957 affectedStrategies.add(getStrategy(route->mStreamType)); 2958 } 2959 } 2960 } 2961 // reroute outputs if necessary 2962 for (size_t i = 0; i < affectedStrategies.size(); i++) { 2963 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE); 2964 } 2965 2966 // remove input routes associated with this uid 2967 SortedVector<audio_source_t> affectedSources; 2968 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) { 2969 sp<SessionRoute> route = mInputRoutes.valueAt(i); 2970 if (route->mUid == uid) { 2971 mInputRoutes.removeItemsAt(i); 2972 if (route->mDeviceDescriptor != 0) { 2973 affectedSources.add(route->mSource); 2974 } 2975 } 2976 } 2977 // reroute inputs if necessary 2978 SortedVector<audio_io_handle_t> inputsToClose; 2979 for (size_t i = 0; i < mInputs.size(); i++) { 2980 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i); 2981 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) { 2982 inputsToClose.add(inputDesc->mIoHandle); 2983 } 2984 } 2985 for (size_t i = 0; i < inputsToClose.size(); i++) { 2986 closeInput(inputsToClose[i]); 2987 } 2988} 2989 2990void AudioPolicyManager::clearAudioSources(uid_t uid) 2991{ 2992 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) { 2993 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i); 2994 if (sourceDesc->mUid == uid) { 2995 stopAudioSource(mAudioSources.keyAt(i)); 2996 } 2997 } 2998} 2999 3000status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session, 3001 audio_io_handle_t *ioHandle, 3002 audio_devices_t *device) 3003{ 3004 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION); 3005 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT); 3006 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD); 3007 3008 return mSoundTriggerSessions.acquireSession(*session, *ioHandle); 3009} 3010 3011status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source, 3012 const audio_attributes_t *attributes, 3013 audio_io_handle_t *handle, 3014 uid_t uid) 3015{ 3016 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle); 3017 if (source == NULL || attributes == NULL || handle == NULL) { 3018 return BAD_VALUE; 3019 } 3020 3021 *handle = AUDIO_IO_HANDLE_NONE; 3022 3023 if (source->role != AUDIO_PORT_ROLE_SOURCE || 3024 source->type != AUDIO_PORT_TYPE_DEVICE) { 3025 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type); 3026 return INVALID_OPERATION; 3027 } 3028 3029 sp<DeviceDescriptor> srcDeviceDesc = 3030 mAvailableInputDevices.getDevice(source->ext.device.type, 3031 String8(source->ext.device.address)); 3032 if (srcDeviceDesc == 0) { 3033 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type); 3034 return BAD_VALUE; 3035 } 3036 sp<AudioSourceDescriptor> sourceDesc = 3037 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid); 3038 3039 struct audio_patch dummyPatch; 3040 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid); 3041 sourceDesc->mPatchDesc = patchDesc; 3042 3043 status_t status = connectAudioSource(sourceDesc); 3044 if (status == NO_ERROR) { 3045 mAudioSources.add(sourceDesc->getHandle(), sourceDesc); 3046 *handle = sourceDesc->getHandle(); 3047 } 3048 return status; 3049} 3050 3051status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc) 3052{ 3053 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle()); 3054 3055 // make sure we only have one patch per source. 3056 disconnectAudioSource(sourceDesc); 3057 3058 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes); 3059 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes); 3060 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice; 3061 3062 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true); 3063 sp<DeviceDescriptor> sinkDeviceDesc = 3064 mAvailableOutputDevices.getDevice(sinkDevice, String8("")); 3065 3066 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 3067 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch; 3068 3069 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() == 3070 sinkDeviceDesc->getAudioPort()->mModule->getHandle() && 3071 srcDeviceDesc->getAudioPort()->mModule->getHalVersion() >= AUDIO_DEVICE_API_VERSION_3_0 && 3072 srcDeviceDesc->getAudioPort()->mGains.size() > 0) { 3073 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__); 3074 // create patch between src device and output device 3075 // create Hwoutput and add to mHwOutputs 3076 } else { 3077 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs); 3078 audio_io_handle_t output = 3079 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID); 3080 if (output == AUDIO_IO_HANDLE_NONE) { 3081 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice); 3082 return INVALID_OPERATION; 3083 } 3084 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 3085 if (outputDesc->isDuplicated()) { 3086 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice); 3087 return INVALID_OPERATION; 3088 } 3089 // create a special patch with no sink and two sources: 3090 // - the second source indicates to PatchPanel through which output mix this patch should 3091 // be connected as well as the stream type for volume control 3092 // - the sink is defined by whatever output device is currently selected for the output 3093 // though which this patch is routed. 3094 patch->num_sinks = 0; 3095 patch->num_sources = 2; 3096 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL); 3097 outputDesc->toAudioPortConfig(&patch->sources[1], NULL); 3098 patch->sources[1].ext.mix.usecase.stream = stream; 3099 status_t status = mpClientInterface->createAudioPatch(patch, 3100 &afPatchHandle, 3101 0); 3102 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__, 3103 status, afPatchHandle); 3104 if (status != NO_ERROR) { 3105 ALOGW("%s patch panel could not connect device patch, error %d", 3106 __FUNCTION__, status); 3107 return INVALID_OPERATION; 3108 } 3109 uint32_t delayMs = 0; 3110 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs); 3111 3112 if (status != NO_ERROR) { 3113 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0); 3114 return status; 3115 } 3116 sourceDesc->mSwOutput = outputDesc; 3117 if (delayMs != 0) { 3118 usleep(delayMs * 1000); 3119 } 3120 } 3121 3122 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle; 3123 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc); 3124 3125 return NO_ERROR; 3126} 3127 3128status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused) 3129{ 3130 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle); 3131 ALOGV("%s handle %d", __FUNCTION__, handle); 3132 if (sourceDesc == 0) { 3133 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle); 3134 return BAD_VALUE; 3135 } 3136 status_t status = disconnectAudioSource(sourceDesc); 3137 3138 mAudioSources.removeItem(handle); 3139 return status; 3140} 3141 3142status_t AudioPolicyManager::setMasterMono(bool mono) 3143{ 3144 if (mMasterMono == mono) { 3145 return NO_ERROR; 3146 } 3147 mMasterMono = mono; 3148 // if enabling mono we close all offloaded devices, which will invalidate the 3149 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible 3150 // for recreating the new AudioTrack as non-offloaded PCM. 3151 // 3152 // If disabling mono, we leave all tracks as is: we don't know which clients 3153 // and tracks are able to be recreated as offloaded. The next "song" should 3154 // play back offloaded. 3155 if (mMasterMono) { 3156 Vector<audio_io_handle_t> offloaded; 3157 for (size_t i = 0; i < mOutputs.size(); ++i) { 3158 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i); 3159 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) { 3160 offloaded.push(desc->mIoHandle); 3161 } 3162 } 3163 for (size_t i = 0; i < offloaded.size(); ++i) { 3164 closeOutput(offloaded[i]); 3165 } 3166 } 3167 // update master mono for all remaining outputs 3168 for (size_t i = 0; i < mOutputs.size(); ++i) { 3169 updateMono(mOutputs.keyAt(i)); 3170 } 3171 return NO_ERROR; 3172} 3173 3174status_t AudioPolicyManager::getMasterMono(bool *mono) 3175{ 3176 *mono = mMasterMono; 3177 return NO_ERROR; 3178} 3179 3180status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc) 3181{ 3182 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle()); 3183 3184 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle); 3185 if (patchDesc == 0) { 3186 ALOGW("%s source has no patch with handle %d", __FUNCTION__, 3187 sourceDesc->mPatchDesc->mHandle); 3188 return BAD_VALUE; 3189 } 3190 removeAudioPatch(sourceDesc->mPatchDesc->mHandle); 3191 3192 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes); 3193 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote(); 3194 if (swOutputDesc != 0) { 3195 stopSource(swOutputDesc, stream, false); 3196 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 3197 } else { 3198 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote(); 3199 if (hwOutputDesc != 0) { 3200 // release patch between src device and output device 3201 // close Hwoutput and remove from mHwOutputs 3202 } else { 3203 ALOGW("%s source has neither SW nor HW output", __FUNCTION__); 3204 } 3205 } 3206 return NO_ERROR; 3207} 3208 3209sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput( 3210 audio_io_handle_t output, routing_strategy strategy) 3211{ 3212 sp<AudioSourceDescriptor> source; 3213 for (size_t i = 0; i < mAudioSources.size(); i++) { 3214 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i); 3215 routing_strategy sourceStrategy = 3216 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes); 3217 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote(); 3218 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) { 3219 source = sourceDesc; 3220 break; 3221 } 3222 } 3223 return source; 3224} 3225 3226// ---------------------------------------------------------------------------- 3227// AudioPolicyManager 3228// ---------------------------------------------------------------------------- 3229uint32_t AudioPolicyManager::nextAudioPortGeneration() 3230{ 3231 return android_atomic_inc(&mAudioPortGeneration); 3232} 3233 3234AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface) 3235 : 3236#ifdef AUDIO_POLICY_TEST 3237 Thread(false), 3238#endif //AUDIO_POLICY_TEST 3239 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f), 3240 mA2dpSuspended(false), 3241 mAudioPortGeneration(1), 3242 mBeaconMuteRefCount(0), 3243 mBeaconPlayingRefCount(0), 3244 mBeaconMuted(false), 3245 mTtsOutputAvailable(false), 3246 mMasterMono(false) 3247{ 3248 mUidCached = getuid(); 3249 mpClientInterface = clientInterface; 3250 3251 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the 3252 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly. 3253 // Note: remove also speaker_drc_enabled from global configuration of XML config file. 3254 bool speakerDrcEnabled = false; 3255 3256#ifdef USE_XML_AUDIO_POLICY_CONF 3257 mVolumeCurves = new VolumeCurvesCollection(); 3258 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices, 3259 mDefaultOutputDevice, speakerDrcEnabled, 3260 static_cast<VolumeCurvesCollection *>(mVolumeCurves)); 3261 PolicySerializer serializer; 3262 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) { 3263#else 3264 mVolumeCurves = new StreamDescriptorCollection(); 3265 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices, 3266 mDefaultOutputDevice, speakerDrcEnabled); 3267 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) && 3268 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) { 3269#endif 3270 ALOGE("could not load audio policy configuration file, setting defaults"); 3271 config.setDefault(); 3272 } 3273 // must be done after reading the policy (since conditionned by Speaker Drc Enabling) 3274 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled); 3275 3276 // Once policy config has been parsed, retrieve an instance of the engine and initialize it. 3277 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance(); 3278 if (!engineInstance) { 3279 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__); 3280 return; 3281 } 3282 // Retrieve the Policy Manager Interface 3283 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>(); 3284 if (mEngine == NULL) { 3285 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__); 3286 return; 3287 } 3288 mEngine->setObserver(this); 3289 status_t status = mEngine->initCheck(); 3290 (void) status; 3291 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status); 3292 3293 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices 3294 // open all output streams needed to access attached devices 3295 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types(); 3296 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN; 3297 for (size_t i = 0; i < mHwModules.size(); i++) { 3298 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName()); 3299 if (mHwModules[i]->mHandle == 0) { 3300 ALOGW("could not open HW module %s", mHwModules[i]->getName()); 3301 continue; 3302 } 3303 // open all output streams needed to access attached devices 3304 // except for direct output streams that are only opened when they are actually 3305 // required by an app. 3306 // This also validates mAvailableOutputDevices list 3307 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 3308 { 3309 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j]; 3310 3311 if (!outProfile->hasSupportedDevices()) { 3312 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName()); 3313 continue; 3314 } 3315 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) { 3316 mTtsOutputAvailable = true; 3317 } 3318 3319 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) { 3320 continue; 3321 } 3322 audio_devices_t profileType = outProfile->getSupportedDevicesType(); 3323 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) { 3324 profileType = mDefaultOutputDevice->type(); 3325 } else { 3326 // chose first device present in profile's SupportedDevices also part of 3327 // outputDeviceTypes 3328 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes); 3329 } 3330 if ((profileType & outputDeviceTypes) == 0) { 3331 continue; 3332 } 3333 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile, 3334 mpClientInterface); 3335 const DeviceVector &supportedDevices = outProfile->getSupportedDevices(); 3336 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType); 3337 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress 3338 : String8(""); 3339 3340 outputDesc->mDevice = profileType; 3341 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 3342 config.sample_rate = outputDesc->mSamplingRate; 3343 config.channel_mask = outputDesc->mChannelMask; 3344 config.format = outputDesc->mFormat; 3345 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE; 3346 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(), 3347 &output, 3348 &config, 3349 &outputDesc->mDevice, 3350 address, 3351 &outputDesc->mLatency, 3352 outputDesc->mFlags); 3353 3354 if (status != NO_ERROR) { 3355 ALOGW("Cannot open output stream for device %08x on hw module %s", 3356 outputDesc->mDevice, 3357 mHwModules[i]->getName()); 3358 } else { 3359 outputDesc->mSamplingRate = config.sample_rate; 3360 outputDesc->mChannelMask = config.channel_mask; 3361 outputDesc->mFormat = config.format; 3362 3363 for (size_t k = 0; k < supportedDevices.size(); k++) { 3364 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]); 3365 // give a valid ID to an attached device once confirmed it is reachable 3366 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) { 3367 mAvailableOutputDevices[index]->attach(mHwModules[i]); 3368 } 3369 } 3370 if (mPrimaryOutput == 0 && 3371 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) { 3372 mPrimaryOutput = outputDesc; 3373 } 3374 addOutput(output, outputDesc); 3375 setOutputDevice(outputDesc, 3376 outputDesc->mDevice, 3377 true, 3378 0, 3379 NULL, 3380 address.string()); 3381 } 3382 } 3383 // open input streams needed to access attached devices to validate 3384 // mAvailableInputDevices list 3385 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) 3386 { 3387 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j]; 3388 3389 if (!inProfile->hasSupportedDevices()) { 3390 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName()); 3391 continue; 3392 } 3393 // chose first device present in profile's SupportedDevices also part of 3394 // inputDeviceTypes 3395 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes); 3396 3397 if ((profileType & inputDeviceTypes) == 0) { 3398 continue; 3399 } 3400 sp<AudioInputDescriptor> inputDesc = 3401 new AudioInputDescriptor(inProfile); 3402 3403 inputDesc->mDevice = profileType; 3404 3405 // find the address 3406 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType); 3407 // the inputs vector must be of size 1, but we don't want to crash here 3408 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress 3409 : String8(""); 3410 ALOGV(" for input device 0x%x using address %s", profileType, address.string()); 3411 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!"); 3412 3413 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 3414 config.sample_rate = inputDesc->mSamplingRate; 3415 config.channel_mask = inputDesc->mChannelMask; 3416 config.format = inputDesc->mFormat; 3417 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE; 3418 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(), 3419 &input, 3420 &config, 3421 &inputDesc->mDevice, 3422 address, 3423 AUDIO_SOURCE_MIC, 3424 AUDIO_INPUT_FLAG_NONE); 3425 3426 if (status == NO_ERROR) { 3427 const DeviceVector &supportedDevices = inProfile->getSupportedDevices(); 3428 for (size_t k = 0; k < supportedDevices.size(); k++) { 3429 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]); 3430 // give a valid ID to an attached device once confirmed it is reachable 3431 if (index >= 0) { 3432 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index]; 3433 if (!devDesc->isAttached()) { 3434 devDesc->attach(mHwModules[i]); 3435 devDesc->importAudioPort(inProfile); 3436 } 3437 } 3438 } 3439 mpClientInterface->closeInput(input); 3440 } else { 3441 ALOGW("Cannot open input stream for device %08x on hw module %s", 3442 inputDesc->mDevice, 3443 mHwModules[i]->getName()); 3444 } 3445 } 3446 } 3447 // make sure all attached devices have been allocated a unique ID 3448 for (size_t i = 0; i < mAvailableOutputDevices.size();) { 3449 if (!mAvailableOutputDevices[i]->isAttached()) { 3450 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type()); 3451 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]); 3452 continue; 3453 } 3454 // The device is now validated and can be appended to the available devices of the engine 3455 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i], 3456 AUDIO_POLICY_DEVICE_STATE_AVAILABLE); 3457 i++; 3458 } 3459 for (size_t i = 0; i < mAvailableInputDevices.size();) { 3460 if (!mAvailableInputDevices[i]->isAttached()) { 3461 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type()); 3462 mAvailableInputDevices.remove(mAvailableInputDevices[i]); 3463 continue; 3464 } 3465 // The device is now validated and can be appended to the available devices of the engine 3466 mEngine->setDeviceConnectionState(mAvailableInputDevices[i], 3467 AUDIO_POLICY_DEVICE_STATE_AVAILABLE); 3468 i++; 3469 } 3470 // make sure default device is reachable 3471 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) { 3472 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type()); 3473 } 3474 3475 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output"); 3476 3477 updateDevicesAndOutputs(); 3478 3479#ifdef AUDIO_POLICY_TEST 3480 if (mPrimaryOutput != 0) { 3481 AudioParameter outputCmd = AudioParameter(); 3482 outputCmd.addInt(String8("set_id"), 0); 3483 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString()); 3484 3485 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER; 3486 mTestSamplingRate = 44100; 3487 mTestFormat = AUDIO_FORMAT_PCM_16_BIT; 3488 mTestChannels = AUDIO_CHANNEL_OUT_STEREO; 3489 mTestLatencyMs = 0; 3490 mCurOutput = 0; 3491 mDirectOutput = false; 3492 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) { 3493 mTestOutputs[i] = 0; 3494 } 3495 3496 const size_t SIZE = 256; 3497 char buffer[SIZE]; 3498 snprintf(buffer, SIZE, "AudioPolicyManagerTest"); 3499 run(buffer, ANDROID_PRIORITY_AUDIO); 3500 } 3501#endif //AUDIO_POLICY_TEST 3502} 3503 3504AudioPolicyManager::~AudioPolicyManager() 3505{ 3506#ifdef AUDIO_POLICY_TEST 3507 exit(); 3508#endif //AUDIO_POLICY_TEST 3509 for (size_t i = 0; i < mOutputs.size(); i++) { 3510 mpClientInterface->closeOutput(mOutputs.keyAt(i)); 3511 } 3512 for (size_t i = 0; i < mInputs.size(); i++) { 3513 mpClientInterface->closeInput(mInputs.keyAt(i)); 3514 } 3515 mAvailableOutputDevices.clear(); 3516 mAvailableInputDevices.clear(); 3517 mOutputs.clear(); 3518 mInputs.clear(); 3519 mHwModules.clear(); 3520} 3521 3522status_t AudioPolicyManager::initCheck() 3523{ 3524 return hasPrimaryOutput() ? NO_ERROR : NO_INIT; 3525} 3526 3527#ifdef AUDIO_POLICY_TEST 3528bool AudioPolicyManager::threadLoop() 3529{ 3530 ALOGV("entering threadLoop()"); 3531 while (!exitPending()) 3532 { 3533 String8 command; 3534 int valueInt; 3535 String8 value; 3536 3537 Mutex::Autolock _l(mLock); 3538 mWaitWorkCV.waitRelative(mLock, milliseconds(50)); 3539 3540 command = mpClientInterface->getParameters(0, String8("test_cmd_policy")); 3541 AudioParameter param = AudioParameter(command); 3542 3543 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR && 3544 valueInt != 0) { 3545 ALOGV("Test command %s received", command.string()); 3546 String8 target; 3547 if (param.get(String8("target"), target) != NO_ERROR) { 3548 target = "Manager"; 3549 } 3550 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) { 3551 param.remove(String8("test_cmd_policy_output")); 3552 mCurOutput = valueInt; 3553 } 3554 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) { 3555 param.remove(String8("test_cmd_policy_direct")); 3556 if (value == "false") { 3557 mDirectOutput = false; 3558 } else if (value == "true") { 3559 mDirectOutput = true; 3560 } 3561 } 3562 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) { 3563 param.remove(String8("test_cmd_policy_input")); 3564 mTestInput = valueInt; 3565 } 3566 3567 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) { 3568 param.remove(String8("test_cmd_policy_format")); 3569 int format = AUDIO_FORMAT_INVALID; 3570 if (value == "PCM 16 bits") { 3571 format = AUDIO_FORMAT_PCM_16_BIT; 3572 } else if (value == "PCM 8 bits") { 3573 format = AUDIO_FORMAT_PCM_8_BIT; 3574 } else if (value == "Compressed MP3") { 3575 format = AUDIO_FORMAT_MP3; 3576 } 3577 if (format != AUDIO_FORMAT_INVALID) { 3578 if (target == "Manager") { 3579 mTestFormat = format; 3580 } else if (mTestOutputs[mCurOutput] != 0) { 3581 AudioParameter outputParam = AudioParameter(); 3582 outputParam.addInt(String8("format"), format); 3583 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 3584 } 3585 } 3586 } 3587 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) { 3588 param.remove(String8("test_cmd_policy_channels")); 3589 int channels = 0; 3590 3591 if (value == "Channels Stereo") { 3592 channels = AUDIO_CHANNEL_OUT_STEREO; 3593 } else if (value == "Channels Mono") { 3594 channels = AUDIO_CHANNEL_OUT_MONO; 3595 } 3596 if (channels != 0) { 3597 if (target == "Manager") { 3598 mTestChannels = channels; 3599 } else if (mTestOutputs[mCurOutput] != 0) { 3600 AudioParameter outputParam = AudioParameter(); 3601 outputParam.addInt(String8("channels"), channels); 3602 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 3603 } 3604 } 3605 } 3606 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) { 3607 param.remove(String8("test_cmd_policy_sampleRate")); 3608 if (valueInt >= 0 && valueInt <= 96000) { 3609 int samplingRate = valueInt; 3610 if (target == "Manager") { 3611 mTestSamplingRate = samplingRate; 3612 } else if (mTestOutputs[mCurOutput] != 0) { 3613 AudioParameter outputParam = AudioParameter(); 3614 outputParam.addInt(String8("sampling_rate"), samplingRate); 3615 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 3616 } 3617 } 3618 } 3619 3620 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) { 3621 param.remove(String8("test_cmd_policy_reopen")); 3622 3623 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput);); 3624 3625 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle(); 3626 3627 removeOutput(mPrimaryOutput->mIoHandle); 3628 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL, 3629 mpClientInterface); 3630 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER; 3631 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 3632 config.sample_rate = outputDesc->mSamplingRate; 3633 config.channel_mask = outputDesc->mChannelMask; 3634 config.format = outputDesc->mFormat; 3635 audio_io_handle_t handle; 3636 status_t status = mpClientInterface->openOutput(moduleHandle, 3637 &handle, 3638 &config, 3639 &outputDesc->mDevice, 3640 String8(""), 3641 &outputDesc->mLatency, 3642 outputDesc->mFlags); 3643 if (status != NO_ERROR) { 3644 ALOGE("Failed to reopen hardware output stream, " 3645 "samplingRate: %d, format %d, channels %d", 3646 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask); 3647 } else { 3648 outputDesc->mSamplingRate = config.sample_rate; 3649 outputDesc->mChannelMask = config.channel_mask; 3650 outputDesc->mFormat = config.format; 3651 mPrimaryOutput = outputDesc; 3652 AudioParameter outputCmd = AudioParameter(); 3653 outputCmd.addInt(String8("set_id"), 0); 3654 mpClientInterface->setParameters(handle, outputCmd.toString()); 3655 addOutput(handle, outputDesc); 3656 } 3657 } 3658 3659 3660 mpClientInterface->setParameters(0, String8("test_cmd_policy=")); 3661 } 3662 } 3663 return false; 3664} 3665 3666void AudioPolicyManager::exit() 3667{ 3668 { 3669 AutoMutex _l(mLock); 3670 requestExit(); 3671 mWaitWorkCV.signal(); 3672 } 3673 requestExitAndWait(); 3674} 3675 3676int AudioPolicyManager::testOutputIndex(audio_io_handle_t output) 3677{ 3678 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) { 3679 if (output == mTestOutputs[i]) return i; 3680 } 3681 return 0; 3682} 3683#endif //AUDIO_POLICY_TEST 3684 3685// --- 3686 3687void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc) 3688{ 3689 outputDesc->setIoHandle(output); 3690 mOutputs.add(output, outputDesc); 3691 updateMono(output); // update mono status when adding to output list 3692 nextAudioPortGeneration(); 3693} 3694 3695void AudioPolicyManager::removeOutput(audio_io_handle_t output) 3696{ 3697 mOutputs.removeItem(output); 3698} 3699 3700void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc) 3701{ 3702 inputDesc->setIoHandle(input); 3703 mInputs.add(input, inputDesc); 3704 nextAudioPortGeneration(); 3705} 3706 3707void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/, 3708 const audio_devices_t device /*in*/, 3709 const String8& address /*in*/, 3710 SortedVector<audio_io_handle_t>& outputs /*out*/) { 3711 sp<DeviceDescriptor> devDesc = 3712 desc->mProfile->getSupportedDeviceByAddress(device, address); 3713 if (devDesc != 0) { 3714 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s", 3715 desc->mIoHandle, address.string()); 3716 outputs.add(desc->mIoHandle); 3717 } 3718} 3719 3720status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc, 3721 audio_policy_dev_state_t state, 3722 SortedVector<audio_io_handle_t>& outputs, 3723 const String8& address) 3724{ 3725 audio_devices_t device = devDesc->type(); 3726 sp<SwAudioOutputDescriptor> desc; 3727 3728 if (audio_device_is_digital(device)) { 3729 // erase all current sample rates, formats and channel masks 3730 devDesc->clearAudioProfiles(); 3731 } 3732 3733 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) { 3734 // first list already open outputs that can be routed to this device 3735 for (size_t i = 0; i < mOutputs.size(); i++) { 3736 desc = mOutputs.valueAt(i); 3737 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) { 3738 if (!device_distinguishes_on_address(device)) { 3739 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i)); 3740 outputs.add(mOutputs.keyAt(i)); 3741 } else { 3742 ALOGV(" checking address match due to device 0x%x", device); 3743 findIoHandlesByAddress(desc, device, address, outputs); 3744 } 3745 } 3746 } 3747 // then look for output profiles that can be routed to this device 3748 SortedVector< sp<IOProfile> > profiles; 3749 for (size_t i = 0; i < mHwModules.size(); i++) 3750 { 3751 if (mHwModules[i]->mHandle == 0) { 3752 continue; 3753 } 3754 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 3755 { 3756 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j]; 3757 if (profile->supportDevice(device)) { 3758 if (!device_distinguishes_on_address(device) || 3759 profile->supportDeviceAddress(address)) { 3760 profiles.add(profile); 3761 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i); 3762 } 3763 } 3764 } 3765 } 3766 3767 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size()); 3768 3769 if (profiles.isEmpty() && outputs.isEmpty()) { 3770 ALOGW("checkOutputsForDevice(): No output available for device %04x", device); 3771 return BAD_VALUE; 3772 } 3773 3774 // open outputs for matching profiles if needed. Direct outputs are also opened to 3775 // query for dynamic parameters and will be closed later by setDeviceConnectionState() 3776 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) { 3777 sp<IOProfile> profile = profiles[profile_index]; 3778 3779 // nothing to do if one output is already opened for this profile 3780 size_t j; 3781 for (j = 0; j < outputs.size(); j++) { 3782 desc = mOutputs.valueFor(outputs.itemAt(j)); 3783 if (!desc->isDuplicated() && desc->mProfile == profile) { 3784 // matching profile: save the sample rates, format and channel masks supported 3785 // by the profile in our device descriptor 3786 if (audio_device_is_digital(device)) { 3787 devDesc->importAudioPort(profile); 3788 } 3789 break; 3790 } 3791 } 3792 if (j != outputs.size()) { 3793 continue; 3794 } 3795 3796 ALOGV("opening output for device %08x with params %s profile %p", 3797 device, address.string(), profile.get()); 3798 desc = new SwAudioOutputDescriptor(profile, mpClientInterface); 3799 desc->mDevice = device; 3800 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 3801 config.sample_rate = desc->mSamplingRate; 3802 config.channel_mask = desc->mChannelMask; 3803 config.format = desc->mFormat; 3804 config.offload_info.sample_rate = desc->mSamplingRate; 3805 config.offload_info.channel_mask = desc->mChannelMask; 3806 config.offload_info.format = desc->mFormat; 3807 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE; 3808 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(), 3809 &output, 3810 &config, 3811 &desc->mDevice, 3812 address, 3813 &desc->mLatency, 3814 desc->mFlags); 3815 if (status == NO_ERROR) { 3816 desc->mSamplingRate = config.sample_rate; 3817 desc->mChannelMask = config.channel_mask; 3818 desc->mFormat = config.format; 3819 3820 // Here is where the out_set_parameters() for card & device gets called 3821 if (!address.isEmpty()) { 3822 char *param = audio_device_address_to_parameter(device, address); 3823 mpClientInterface->setParameters(output, String8(param)); 3824 free(param); 3825 } 3826 updateAudioProfiles(device, output, profile->getAudioProfiles()); 3827 if (!profile->hasValidAudioProfile()) { 3828 ALOGW("checkOutputsForDevice() missing param"); 3829 mpClientInterface->closeOutput(output); 3830 output = AUDIO_IO_HANDLE_NONE; 3831 } else if (profile->hasDynamicAudioProfile()) { 3832 mpClientInterface->closeOutput(output); 3833 output = AUDIO_IO_HANDLE_NONE; 3834 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format); 3835 config.offload_info.sample_rate = config.sample_rate; 3836 config.offload_info.channel_mask = config.channel_mask; 3837 config.offload_info.format = config.format; 3838 status = mpClientInterface->openOutput(profile->getModuleHandle(), 3839 &output, 3840 &config, 3841 &desc->mDevice, 3842 address, 3843 &desc->mLatency, 3844 desc->mFlags); 3845 if (status == NO_ERROR) { 3846 desc->mSamplingRate = config.sample_rate; 3847 desc->mChannelMask = config.channel_mask; 3848 desc->mFormat = config.format; 3849 } else { 3850 output = AUDIO_IO_HANDLE_NONE; 3851 } 3852 } 3853 3854 if (output != AUDIO_IO_HANDLE_NONE) { 3855 addOutput(output, desc); 3856 if (device_distinguishes_on_address(device) && address != "0") { 3857 sp<AudioPolicyMix> policyMix; 3858 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) { 3859 ALOGE("checkOutputsForDevice() cannot find policy for address %s", 3860 address.string()); 3861 } 3862 policyMix->setOutput(desc); 3863 desc->mPolicyMix = policyMix->getMix(); 3864 3865 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && 3866 hasPrimaryOutput()) { 3867 // no duplicated output for direct outputs and 3868 // outputs used by dynamic policy mixes 3869 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE; 3870 3871 // set initial stream volume for device 3872 applyStreamVolumes(desc, device, 0, true); 3873 3874 //TODO: configure audio effect output stage here 3875 3876 // open a duplicating output thread for the new output and the primary output 3877 duplicatedOutput = 3878 mpClientInterface->openDuplicateOutput(output, 3879 mPrimaryOutput->mIoHandle); 3880 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) { 3881 // add duplicated output descriptor 3882 sp<SwAudioOutputDescriptor> dupOutputDesc = 3883 new SwAudioOutputDescriptor(NULL, mpClientInterface); 3884 dupOutputDesc->mOutput1 = mPrimaryOutput; 3885 dupOutputDesc->mOutput2 = desc; 3886 dupOutputDesc->mSamplingRate = desc->mSamplingRate; 3887 dupOutputDesc->mFormat = desc->mFormat; 3888 dupOutputDesc->mChannelMask = desc->mChannelMask; 3889 dupOutputDesc->mLatency = desc->mLatency; 3890 addOutput(duplicatedOutput, dupOutputDesc); 3891 applyStreamVolumes(dupOutputDesc, device, 0, true); 3892 } else { 3893 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d", 3894 mPrimaryOutput->mIoHandle, output); 3895 mpClientInterface->closeOutput(output); 3896 removeOutput(output); 3897 nextAudioPortGeneration(); 3898 output = AUDIO_IO_HANDLE_NONE; 3899 } 3900 } 3901 } 3902 } else { 3903 output = AUDIO_IO_HANDLE_NONE; 3904 } 3905 if (output == AUDIO_IO_HANDLE_NONE) { 3906 ALOGW("checkOutputsForDevice() could not open output for device %x", device); 3907 profiles.removeAt(profile_index); 3908 profile_index--; 3909 } else { 3910 outputs.add(output); 3911 // Load digital format info only for digital devices 3912 if (audio_device_is_digital(device)) { 3913 devDesc->importAudioPort(profile); 3914 } 3915 3916 if (device_distinguishes_on_address(device)) { 3917 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)", 3918 device, address.string()); 3919 setOutputDevice(desc, device, true/*force*/, 0/*delay*/, 3920 NULL/*patch handle*/, address.string()); 3921 } 3922 ALOGV("checkOutputsForDevice(): adding output %d", output); 3923 } 3924 } 3925 3926 if (profiles.isEmpty()) { 3927 ALOGW("checkOutputsForDevice(): No output available for device %04x", device); 3928 return BAD_VALUE; 3929 } 3930 } else { // Disconnect 3931 // check if one opened output is not needed any more after disconnecting one device 3932 for (size_t i = 0; i < mOutputs.size(); i++) { 3933 desc = mOutputs.valueAt(i); 3934 if (!desc->isDuplicated()) { 3935 // exact match on device 3936 if (device_distinguishes_on_address(device) && 3937 (desc->supportedDevices() == device)) { 3938 findIoHandlesByAddress(desc, device, address, outputs); 3939 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) { 3940 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", 3941 mOutputs.keyAt(i)); 3942 outputs.add(mOutputs.keyAt(i)); 3943 } 3944 } 3945 } 3946 // Clear any profiles associated with the disconnected device. 3947 for (size_t i = 0; i < mHwModules.size(); i++) 3948 { 3949 if (mHwModules[i]->mHandle == 0) { 3950 continue; 3951 } 3952 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 3953 { 3954 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j]; 3955 if (profile->supportDevice(device)) { 3956 ALOGV("checkOutputsForDevice(): " 3957 "clearing direct output profile %zu on module %zu", j, i); 3958 profile->clearAudioProfiles(); 3959 } 3960 } 3961 } 3962 } 3963 return NO_ERROR; 3964} 3965 3966status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc, 3967 audio_policy_dev_state_t state, 3968 SortedVector<audio_io_handle_t>& inputs, 3969 const String8& address) 3970{ 3971 audio_devices_t device = devDesc->type(); 3972 sp<AudioInputDescriptor> desc; 3973 3974 if (audio_device_is_digital(device)) { 3975 // erase all current sample rates, formats and channel masks 3976 devDesc->clearAudioProfiles(); 3977 } 3978 3979 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) { 3980 // first list already open inputs that can be routed to this device 3981 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) { 3982 desc = mInputs.valueAt(input_index); 3983 if (desc->mProfile->supportDevice(device)) { 3984 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index)); 3985 inputs.add(mInputs.keyAt(input_index)); 3986 } 3987 } 3988 3989 // then look for input profiles that can be routed to this device 3990 SortedVector< sp<IOProfile> > profiles; 3991 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++) 3992 { 3993 if (mHwModules[module_idx]->mHandle == 0) { 3994 continue; 3995 } 3996 for (size_t profile_index = 0; 3997 profile_index < mHwModules[module_idx]->mInputProfiles.size(); 3998 profile_index++) 3999 { 4000 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index]; 4001 4002 if (profile->supportDevice(device)) { 4003 if (!device_distinguishes_on_address(device) || 4004 profile->supportDeviceAddress(address)) { 4005 profiles.add(profile); 4006 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu", 4007 profile_index, module_idx); 4008 } 4009 } 4010 } 4011 } 4012 4013 if (profiles.isEmpty() && inputs.isEmpty()) { 4014 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device); 4015 return BAD_VALUE; 4016 } 4017 4018 // open inputs for matching profiles if needed. Direct inputs are also opened to 4019 // query for dynamic parameters and will be closed later by setDeviceConnectionState() 4020 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) { 4021 4022 sp<IOProfile> profile = profiles[profile_index]; 4023 // nothing to do if one input is already opened for this profile 4024 size_t input_index; 4025 for (input_index = 0; input_index < mInputs.size(); input_index++) { 4026 desc = mInputs.valueAt(input_index); 4027 if (desc->mProfile == profile) { 4028 if (audio_device_is_digital(device)) { 4029 devDesc->importAudioPort(profile); 4030 } 4031 break; 4032 } 4033 } 4034 if (input_index != mInputs.size()) { 4035 continue; 4036 } 4037 4038 ALOGV("opening input for device 0x%X with params %s", device, address.string()); 4039 desc = new AudioInputDescriptor(profile); 4040 desc->mDevice = device; 4041 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 4042 config.sample_rate = desc->mSamplingRate; 4043 config.channel_mask = desc->mChannelMask; 4044 config.format = desc->mFormat; 4045 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE; 4046 status_t status = mpClientInterface->openInput(profile->getModuleHandle(), 4047 &input, 4048 &config, 4049 &desc->mDevice, 4050 address, 4051 AUDIO_SOURCE_MIC, 4052 AUDIO_INPUT_FLAG_NONE /*FIXME*/); 4053 4054 if (status == NO_ERROR) { 4055 desc->mSamplingRate = config.sample_rate; 4056 desc->mChannelMask = config.channel_mask; 4057 desc->mFormat = config.format; 4058 4059 if (!address.isEmpty()) { 4060 char *param = audio_device_address_to_parameter(device, address); 4061 mpClientInterface->setParameters(input, String8(param)); 4062 free(param); 4063 } 4064 updateAudioProfiles(device, input, profile->getAudioProfiles()); 4065 if (!profile->hasValidAudioProfile()) { 4066 ALOGW("checkInputsForDevice() direct input missing param"); 4067 mpClientInterface->closeInput(input); 4068 input = AUDIO_IO_HANDLE_NONE; 4069 } 4070 4071 if (input != 0) { 4072 addInput(input, desc); 4073 } 4074 } // endif input != 0 4075 4076 if (input == AUDIO_IO_HANDLE_NONE) { 4077 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device); 4078 profiles.removeAt(profile_index); 4079 profile_index--; 4080 } else { 4081 inputs.add(input); 4082 if (audio_device_is_digital(device)) { 4083 devDesc->importAudioPort(profile); 4084 } 4085 ALOGV("checkInputsForDevice(): adding input %d", input); 4086 } 4087 } // end scan profiles 4088 4089 if (profiles.isEmpty()) { 4090 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device); 4091 return BAD_VALUE; 4092 } 4093 } else { 4094 // Disconnect 4095 // check if one opened input is not needed any more after disconnecting one device 4096 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) { 4097 desc = mInputs.valueAt(input_index); 4098 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) { 4099 ALOGV("checkInputsForDevice(): disconnecting adding input %d", 4100 mInputs.keyAt(input_index)); 4101 inputs.add(mInputs.keyAt(input_index)); 4102 } 4103 } 4104 // Clear any profiles associated with the disconnected device. 4105 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) { 4106 if (mHwModules[module_index]->mHandle == 0) { 4107 continue; 4108 } 4109 for (size_t profile_index = 0; 4110 profile_index < mHwModules[module_index]->mInputProfiles.size(); 4111 profile_index++) { 4112 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index]; 4113 if (profile->supportDevice(device)) { 4114 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu", 4115 profile_index, module_index); 4116 profile->clearAudioProfiles(); 4117 } 4118 } 4119 } 4120 } // end disconnect 4121 4122 return NO_ERROR; 4123} 4124 4125 4126void AudioPolicyManager::closeOutput(audio_io_handle_t output) 4127{ 4128 ALOGV("closeOutput(%d)", output); 4129 4130 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 4131 if (outputDesc == NULL) { 4132 ALOGW("closeOutput() unknown output %d", output); 4133 return; 4134 } 4135 mPolicyMixes.closeOutput(outputDesc); 4136 4137 // look for duplicated outputs connected to the output being removed. 4138 for (size_t i = 0; i < mOutputs.size(); i++) { 4139 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i); 4140 if (dupOutputDesc->isDuplicated() && 4141 (dupOutputDesc->mOutput1 == outputDesc || 4142 dupOutputDesc->mOutput2 == outputDesc)) { 4143 sp<AudioOutputDescriptor> outputDesc2; 4144 if (dupOutputDesc->mOutput1 == outputDesc) { 4145 outputDesc2 = dupOutputDesc->mOutput2; 4146 } else { 4147 outputDesc2 = dupOutputDesc->mOutput1; 4148 } 4149 // As all active tracks on duplicated output will be deleted, 4150 // and as they were also referenced on the other output, the reference 4151 // count for their stream type must be adjusted accordingly on 4152 // the other output. 4153 for (int j = 0; j < AUDIO_STREAM_CNT; j++) { 4154 int refCount = dupOutputDesc->mRefCount[j]; 4155 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount); 4156 } 4157 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i); 4158 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput); 4159 4160 mpClientInterface->closeOutput(duplicatedOutput); 4161 removeOutput(duplicatedOutput); 4162 } 4163 } 4164 4165 nextAudioPortGeneration(); 4166 4167 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle()); 4168 if (index >= 0) { 4169 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 4170 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 4171 mAudioPatches.removeItemsAt(index); 4172 mpClientInterface->onAudioPatchListUpdate(); 4173 } 4174 4175 AudioParameter param; 4176 param.add(String8("closing"), String8("true")); 4177 mpClientInterface->setParameters(output, param.toString()); 4178 4179 mpClientInterface->closeOutput(output); 4180 removeOutput(output); 4181 mPreviousOutputs = mOutputs; 4182} 4183 4184void AudioPolicyManager::closeInput(audio_io_handle_t input) 4185{ 4186 ALOGV("closeInput(%d)", input); 4187 4188 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input); 4189 if (inputDesc == NULL) { 4190 ALOGW("closeInput() unknown input %d", input); 4191 return; 4192 } 4193 4194 nextAudioPortGeneration(); 4195 4196 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle()); 4197 if (index >= 0) { 4198 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 4199 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 4200 mAudioPatches.removeItemsAt(index); 4201 mpClientInterface->onAudioPatchListUpdate(); 4202 } 4203 4204 mpClientInterface->closeInput(input); 4205 mInputs.removeItem(input); 4206} 4207 4208SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice( 4209 audio_devices_t device, 4210 const SwAudioOutputCollection& openOutputs) 4211{ 4212 SortedVector<audio_io_handle_t> outputs; 4213 4214 ALOGVV("getOutputsForDevice() device %04x", device); 4215 for (size_t i = 0; i < openOutputs.size(); i++) { 4216 ALOGVV("output %zu isDuplicated=%d device=%04x", 4217 i, openOutputs.valueAt(i)->isDuplicated(), 4218 openOutputs.valueAt(i)->supportedDevices()); 4219 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) { 4220 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i)); 4221 outputs.add(openOutputs.keyAt(i)); 4222 } 4223 } 4224 return outputs; 4225} 4226 4227bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1, 4228 SortedVector<audio_io_handle_t>& outputs2) 4229{ 4230 if (outputs1.size() != outputs2.size()) { 4231 return false; 4232 } 4233 for (size_t i = 0; i < outputs1.size(); i++) { 4234 if (outputs1[i] != outputs2[i]) { 4235 return false; 4236 } 4237 } 4238 return true; 4239} 4240 4241void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy) 4242{ 4243 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/); 4244 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/); 4245 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs); 4246 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs); 4247 4248 // also take into account external policy-related changes: add all outputs which are 4249 // associated with policies in the "before" and "after" output vectors 4250 ALOGVV("checkOutputForStrategy(): policy related outputs"); 4251 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) { 4252 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i); 4253 if (desc != 0 && desc->mPolicyMix != NULL) { 4254 srcOutputs.add(desc->mIoHandle); 4255 ALOGVV(" previous outputs: adding %d", desc->mIoHandle); 4256 } 4257 } 4258 for (size_t i = 0 ; i < mOutputs.size() ; i++) { 4259 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i); 4260 if (desc != 0 && desc->mPolicyMix != NULL) { 4261 dstOutputs.add(desc->mIoHandle); 4262 ALOGVV(" new outputs: adding %d", desc->mIoHandle); 4263 } 4264 } 4265 4266 if (!vectorsEqual(srcOutputs,dstOutputs)) { 4267 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d", 4268 strategy, srcOutputs[0], dstOutputs[0]); 4269 // mute strategy while moving tracks from one output to another 4270 for (size_t i = 0; i < srcOutputs.size(); i++) { 4271 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]); 4272 if (isStrategyActive(desc, strategy)) { 4273 setStrategyMute(strategy, true, desc); 4274 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice); 4275 } 4276 sp<AudioSourceDescriptor> source = 4277 getSourceForStrategyOnOutput(srcOutputs[i], strategy); 4278 if (source != 0){ 4279 connectAudioSource(source); 4280 } 4281 } 4282 4283 // Move effects associated to this strategy from previous output to new output 4284 if (strategy == STRATEGY_MEDIA) { 4285 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs); 4286 SortedVector<audio_io_handle_t> moved; 4287 for (size_t i = 0; i < mEffects.size(); i++) { 4288 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i); 4289 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX && 4290 effectDesc->mIo != fxOutput) { 4291 if (moved.indexOf(effectDesc->mIo) < 0) { 4292 ALOGV("checkOutputForStrategy() moving effect %d to output %d", 4293 mEffects.keyAt(i), fxOutput); 4294 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo, 4295 fxOutput); 4296 moved.add(effectDesc->mIo); 4297 } 4298 effectDesc->mIo = fxOutput; 4299 } 4300 } 4301 } 4302 // Move tracks associated to this strategy from previous output to new output 4303 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) { 4304 if (getStrategy((audio_stream_type_t)i) == strategy) { 4305 mpClientInterface->invalidateStream((audio_stream_type_t)i); 4306 } 4307 } 4308 } 4309} 4310 4311void AudioPolicyManager::checkOutputForAllStrategies() 4312{ 4313 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) 4314 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE); 4315 checkOutputForStrategy(STRATEGY_PHONE); 4316 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) 4317 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE); 4318 checkOutputForStrategy(STRATEGY_SONIFICATION); 4319 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL); 4320 checkOutputForStrategy(STRATEGY_ACCESSIBILITY); 4321 checkOutputForStrategy(STRATEGY_MEDIA); 4322 checkOutputForStrategy(STRATEGY_DTMF); 4323 checkOutputForStrategy(STRATEGY_REROUTING); 4324} 4325 4326void AudioPolicyManager::checkA2dpSuspend() 4327{ 4328 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput(); 4329 if (a2dpOutput == 0) { 4330 mA2dpSuspended = false; 4331 return; 4332 } 4333 4334 bool isScoConnected = 4335 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET & 4336 ~AUDIO_DEVICE_BIT_IN) != 0) || 4337 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0); 4338 4339 // if suspended, restore A2DP output if: 4340 // ((SCO device is NOT connected) || 4341 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) && 4342 // (phone state is NOT in call) && (phone state is NOT ringing))) 4343 // 4344 // if not suspended, suspend A2DP output if: 4345 // (SCO device is connected) && 4346 // ((forced usage for communication is SCO) || (forced usage for record is SCO) || 4347 // ((phone state is in call) || (phone state is ringing))) 4348 // 4349 if (mA2dpSuspended) { 4350 if (!isScoConnected || 4351 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != 4352 AUDIO_POLICY_FORCE_BT_SCO) && 4353 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != 4354 AUDIO_POLICY_FORCE_BT_SCO) && 4355 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) && 4356 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) { 4357 4358 mpClientInterface->restoreOutput(a2dpOutput); 4359 mA2dpSuspended = false; 4360 } 4361 } else { 4362 if (isScoConnected && 4363 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == 4364 AUDIO_POLICY_FORCE_BT_SCO) || 4365 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == 4366 AUDIO_POLICY_FORCE_BT_SCO) || 4367 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) || 4368 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) { 4369 4370 mpClientInterface->suspendOutput(a2dpOutput); 4371 mA2dpSuspended = true; 4372 } 4373 } 4374} 4375 4376audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc, 4377 bool fromCache) 4378{ 4379 audio_devices_t device = AUDIO_DEVICE_NONE; 4380 4381 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle()); 4382 if (index >= 0) { 4383 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 4384 if (patchDesc->mUid != mUidCached) { 4385 ALOGV("getNewOutputDevice() device %08x forced by patch %d", 4386 outputDesc->device(), outputDesc->getPatchHandle()); 4387 return outputDesc->device(); 4388 } 4389 } 4390 4391 // check the following by order of priority to request a routing change if necessary: 4392 // 1: the strategy enforced audible is active and enforced on the output: 4393 // use device for strategy enforced audible 4394 // 2: we are in call or the strategy phone is active on the output: 4395 // use device for strategy phone 4396 // 3: the strategy for enforced audible is active but not enforced on the output: 4397 // use the device for strategy enforced audible 4398 // 4: the strategy sonification is active on the output: 4399 // use device for strategy sonification 4400 // 5: the strategy accessibility is active on the output: 4401 // use device for strategy accessibility 4402 // 6: the strategy "respectful" sonification is active on the output: 4403 // use device for strategy "respectful" sonification 4404 // 7: the strategy media is active on the output: 4405 // use device for strategy media 4406 // 8: the strategy DTMF is active on the output: 4407 // use device for strategy DTMF 4408 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output: 4409 // use device for strategy t-t-s 4410 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) && 4411 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) { 4412 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache); 4413 } else if (isInCall() || 4414 isStrategyActive(outputDesc, STRATEGY_PHONE)) { 4415 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache); 4416 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) { 4417 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache); 4418 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) { 4419 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache); 4420 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) { 4421 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache); 4422 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) { 4423 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache); 4424 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) { 4425 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache); 4426 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) { 4427 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache); 4428 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) { 4429 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache); 4430 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) { 4431 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache); 4432 } 4433 4434 ALOGV("getNewOutputDevice() selected device %x", device); 4435 return device; 4436} 4437 4438audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc) 4439{ 4440 audio_devices_t device = AUDIO_DEVICE_NONE; 4441 4442 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle()); 4443 if (index >= 0) { 4444 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 4445 if (patchDesc->mUid != mUidCached) { 4446 ALOGV("getNewInputDevice() device %08x forced by patch %d", 4447 inputDesc->mDevice, inputDesc->getPatchHandle()); 4448 return inputDesc->mDevice; 4449 } 4450 } 4451 4452 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/); 4453 if (isInCall()) { 4454 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION); 4455 } else if (source != AUDIO_SOURCE_DEFAULT) { 4456 device = getDeviceAndMixForInputSource(source); 4457 } 4458 4459 return device; 4460} 4461 4462bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1, 4463 audio_stream_type_t stream2) { 4464 return ((stream1 == stream2) || 4465 ((stream1 == AUDIO_STREAM_ACCESSIBILITY) && (stream2 == AUDIO_STREAM_MUSIC)) || 4466 ((stream1 == AUDIO_STREAM_MUSIC) && (stream2 == AUDIO_STREAM_ACCESSIBILITY))); 4467} 4468 4469uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) { 4470 return (uint32_t)getStrategy(stream); 4471} 4472 4473audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) { 4474 // By checking the range of stream before calling getStrategy, we avoid 4475 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE 4476 // and then return STRATEGY_MEDIA, but we want to return the empty set. 4477 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) { 4478 return AUDIO_DEVICE_NONE; 4479 } 4480 audio_devices_t devices = AUDIO_DEVICE_NONE; 4481 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) { 4482 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) { 4483 continue; 4484 } 4485 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream); 4486 audio_devices_t curDevices = 4487 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/); 4488 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs); 4489 for (size_t i = 0; i < outputs.size(); i++) { 4490 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]); 4491 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) { 4492 curDevices |= outputDesc->device(); 4493 } 4494 } 4495 devices |= curDevices; 4496 } 4497 4498 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it 4499 and doesn't really need to.*/ 4500 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) { 4501 devices |= AUDIO_DEVICE_OUT_SPEAKER; 4502 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE; 4503 } 4504 return devices; 4505} 4506 4507routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const 4508{ 4509 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH"); 4510 return mEngine->getStrategyForStream(stream); 4511} 4512 4513uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) { 4514 // flags to strategy mapping 4515 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) { 4516 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER; 4517 } 4518 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) { 4519 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE; 4520 } 4521 // usage to strategy mapping 4522 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage)); 4523} 4524 4525void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) { 4526 switch(stream) { 4527 case AUDIO_STREAM_MUSIC: 4528 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL); 4529 updateDevicesAndOutputs(); 4530 break; 4531 default: 4532 break; 4533 } 4534} 4535 4536uint32_t AudioPolicyManager::handleEventForBeacon(int event) { 4537 4538 // skip beacon mute management if a dedicated TTS output is available 4539 if (mTtsOutputAvailable) { 4540 return 0; 4541 } 4542 4543 switch(event) { 4544 case STARTING_OUTPUT: 4545 mBeaconMuteRefCount++; 4546 break; 4547 case STOPPING_OUTPUT: 4548 if (mBeaconMuteRefCount > 0) { 4549 mBeaconMuteRefCount--; 4550 } 4551 break; 4552 case STARTING_BEACON: 4553 mBeaconPlayingRefCount++; 4554 break; 4555 case STOPPING_BEACON: 4556 if (mBeaconPlayingRefCount > 0) { 4557 mBeaconPlayingRefCount--; 4558 } 4559 break; 4560 } 4561 4562 if (mBeaconMuteRefCount > 0) { 4563 // any playback causes beacon to be muted 4564 return setBeaconMute(true); 4565 } else { 4566 // no other playback: unmute when beacon starts playing, mute when it stops 4567 return setBeaconMute(mBeaconPlayingRefCount == 0); 4568 } 4569} 4570 4571uint32_t AudioPolicyManager::setBeaconMute(bool mute) { 4572 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d", 4573 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount); 4574 // keep track of muted state to avoid repeating mute/unmute operations 4575 if (mBeaconMuted != mute) { 4576 // mute/unmute AUDIO_STREAM_TTS on all outputs 4577 ALOGV("\t muting %d", mute); 4578 uint32_t maxLatency = 0; 4579 for (size_t i = 0; i < mOutputs.size(); i++) { 4580 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i); 4581 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/, 4582 desc, 4583 0 /*delay*/, AUDIO_DEVICE_NONE); 4584 const uint32_t latency = desc->latency() * 2; 4585 if (latency > maxLatency) { 4586 maxLatency = latency; 4587 } 4588 } 4589 mBeaconMuted = mute; 4590 return maxLatency; 4591 } 4592 return 0; 4593} 4594 4595audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy, 4596 bool fromCache) 4597{ 4598 // Routing 4599 // see if we have an explicit route 4600 // scan the whole RouteMap, for each entry, convert the stream type to a strategy 4601 // (getStrategy(stream)). 4602 // if the strategy from the stream type in the RouteMap is the same as the argument above, 4603 // and activity count is non-zero 4604 // the device = the device from the descriptor in the RouteMap, and exit. 4605 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) { 4606 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex); 4607 routing_strategy routeStrategy = getStrategy(route->mStreamType); 4608 if ((routeStrategy == strategy) && route->isActive()) { 4609 return route->mDeviceDescriptor->type(); 4610 } 4611 } 4612 4613 if (fromCache) { 4614 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x", 4615 strategy, mDeviceForStrategy[strategy]); 4616 return mDeviceForStrategy[strategy]; 4617 } 4618 return mEngine->getDeviceForStrategy(strategy); 4619} 4620 4621void AudioPolicyManager::updateDevicesAndOutputs() 4622{ 4623 for (int i = 0; i < NUM_STRATEGIES; i++) { 4624 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/); 4625 } 4626 mPreviousOutputs = mOutputs; 4627} 4628 4629uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc, 4630 audio_devices_t prevDevice, 4631 uint32_t delayMs) 4632{ 4633 // mute/unmute strategies using an incompatible device combination 4634 // if muting, wait for the audio in pcm buffer to be drained before proceeding 4635 // if unmuting, unmute only after the specified delay 4636 if (outputDesc->isDuplicated()) { 4637 return 0; 4638 } 4639 4640 uint32_t muteWaitMs = 0; 4641 audio_devices_t device = outputDesc->device(); 4642 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2); 4643 4644 for (size_t i = 0; i < NUM_STRATEGIES; i++) { 4645 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/); 4646 curDevice = curDevice & outputDesc->supportedDevices(); 4647 bool mute = shouldMute && (curDevice & device) && (curDevice != device); 4648 bool doMute = false; 4649 4650 if (mute && !outputDesc->mStrategyMutedByDevice[i]) { 4651 doMute = true; 4652 outputDesc->mStrategyMutedByDevice[i] = true; 4653 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){ 4654 doMute = true; 4655 outputDesc->mStrategyMutedByDevice[i] = false; 4656 } 4657 if (doMute) { 4658 for (size_t j = 0; j < mOutputs.size(); j++) { 4659 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j); 4660 // skip output if it does not share any device with current output 4661 if ((desc->supportedDevices() & outputDesc->supportedDevices()) 4662 == AUDIO_DEVICE_NONE) { 4663 continue; 4664 } 4665 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)", 4666 mute ? "muting" : "unmuting", i, curDevice); 4667 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs); 4668 if (isStrategyActive(desc, (routing_strategy)i)) { 4669 if (mute) { 4670 // FIXME: should not need to double latency if volume could be applied 4671 // immediately by the audioflinger mixer. We must account for the delay 4672 // between now and the next time the audioflinger thread for this output 4673 // will process a buffer (which corresponds to one buffer size, 4674 // usually 1/2 or 1/4 of the latency). 4675 if (muteWaitMs < desc->latency() * 2) { 4676 muteWaitMs = desc->latency() * 2; 4677 } 4678 } 4679 } 4680 } 4681 } 4682 } 4683 4684 // temporary mute output if device selection changes to avoid volume bursts due to 4685 // different per device volumes 4686 if (outputDesc->isActive() && (device != prevDevice)) { 4687 uint32_t tempMuteWaitMs = outputDesc->latency() * 2; 4688 // temporary mute duration is conservatively set to 4 times the reported latency 4689 uint32_t tempMuteDurationMs = outputDesc->latency() * 4; 4690 if (muteWaitMs < tempMuteWaitMs) { 4691 muteWaitMs = tempMuteWaitMs; 4692 } 4693 4694 for (size_t i = 0; i < NUM_STRATEGIES; i++) { 4695 if (isStrategyActive(outputDesc, (routing_strategy)i)) { 4696 // make sure that we do not start the temporary mute period too early in case of 4697 // delayed device change 4698 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs); 4699 setStrategyMute((routing_strategy)i, false, outputDesc, 4700 delayMs + tempMuteDurationMs, device); 4701 } 4702 } 4703 } 4704 4705 // wait for the PCM output buffers to empty before proceeding with the rest of the command 4706 if (muteWaitMs > delayMs) { 4707 muteWaitMs -= delayMs; 4708 usleep(muteWaitMs * 1000); 4709 return muteWaitMs; 4710 } 4711 return 0; 4712} 4713 4714uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc, 4715 audio_devices_t device, 4716 bool force, 4717 int delayMs, 4718 audio_patch_handle_t *patchHandle, 4719 const char* address) 4720{ 4721 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs); 4722 AudioParameter param; 4723 uint32_t muteWaitMs; 4724 4725 if (outputDesc->isDuplicated()) { 4726 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs); 4727 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs); 4728 return muteWaitMs; 4729 } 4730 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current 4731 // output profile 4732 if ((device != AUDIO_DEVICE_NONE) && 4733 ((device & outputDesc->supportedDevices()) == 0)) { 4734 return 0; 4735 } 4736 4737 // filter devices according to output selected 4738 device = (audio_devices_t)(device & outputDesc->supportedDevices()); 4739 4740 audio_devices_t prevDevice = outputDesc->mDevice; 4741 4742 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice); 4743 4744 if (device != AUDIO_DEVICE_NONE) { 4745 outputDesc->mDevice = device; 4746 } 4747 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs); 4748 4749 // Do not change the routing if: 4750 // the requested device is AUDIO_DEVICE_NONE 4751 // OR the requested device is the same as current device 4752 // AND force is not specified 4753 // AND the output is connected by a valid audio patch. 4754 // Doing this check here allows the caller to call setOutputDevice() without conditions 4755 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && 4756 !force && 4757 outputDesc->getPatchHandle() != 0) { 4758 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device); 4759 return muteWaitMs; 4760 } 4761 4762 ALOGV("setOutputDevice() changing device"); 4763 4764 // do the routing 4765 if (device == AUDIO_DEVICE_NONE) { 4766 resetOutputDevice(outputDesc, delayMs, NULL); 4767 } else { 4768 DeviceVector deviceList; 4769 if ((address == NULL) || (strlen(address) == 0)) { 4770 deviceList = mAvailableOutputDevices.getDevicesFromType(device); 4771 } else { 4772 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address)); 4773 } 4774 4775 if (!deviceList.isEmpty()) { 4776 struct audio_patch patch; 4777 outputDesc->toAudioPortConfig(&patch.sources[0]); 4778 patch.num_sources = 1; 4779 patch.num_sinks = 0; 4780 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) { 4781 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]); 4782 patch.num_sinks++; 4783 } 4784 ssize_t index; 4785 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) { 4786 index = mAudioPatches.indexOfKey(*patchHandle); 4787 } else { 4788 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle()); 4789 } 4790 sp< AudioPatch> patchDesc; 4791 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 4792 if (index >= 0) { 4793 patchDesc = mAudioPatches.valueAt(index); 4794 afPatchHandle = patchDesc->mAfPatchHandle; 4795 } 4796 4797 status_t status = mpClientInterface->createAudioPatch(&patch, 4798 &afPatchHandle, 4799 delayMs); 4800 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d" 4801 "num_sources %d num_sinks %d", 4802 status, afPatchHandle, patch.num_sources, patch.num_sinks); 4803 if (status == NO_ERROR) { 4804 if (index < 0) { 4805 patchDesc = new AudioPatch(&patch, mUidCached); 4806 addAudioPatch(patchDesc->mHandle, patchDesc); 4807 } else { 4808 patchDesc->mPatch = patch; 4809 } 4810 patchDesc->mAfPatchHandle = afPatchHandle; 4811 if (patchHandle) { 4812 *patchHandle = patchDesc->mHandle; 4813 } 4814 outputDesc->setPatchHandle(patchDesc->mHandle); 4815 nextAudioPortGeneration(); 4816 mpClientInterface->onAudioPatchListUpdate(); 4817 } 4818 } 4819 4820 // inform all input as well 4821 for (size_t i = 0; i < mInputs.size(); i++) { 4822 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i); 4823 if (!is_virtual_input_device(inputDescriptor->mDevice)) { 4824 AudioParameter inputCmd = AudioParameter(); 4825 ALOGV("%s: inform input %d of device:%d", __func__, 4826 inputDescriptor->mIoHandle, device); 4827 inputCmd.addInt(String8(AudioParameter::keyRouting),device); 4828 mpClientInterface->setParameters(inputDescriptor->mIoHandle, 4829 inputCmd.toString(), 4830 delayMs); 4831 } 4832 } 4833 } 4834 4835 // update stream volumes according to new device 4836 applyStreamVolumes(outputDesc, device, delayMs); 4837 4838 return muteWaitMs; 4839} 4840 4841status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc, 4842 int delayMs, 4843 audio_patch_handle_t *patchHandle) 4844{ 4845 ssize_t index; 4846 if (patchHandle) { 4847 index = mAudioPatches.indexOfKey(*patchHandle); 4848 } else { 4849 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle()); 4850 } 4851 if (index < 0) { 4852 return INVALID_OPERATION; 4853 } 4854 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index); 4855 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs); 4856 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status); 4857 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE); 4858 removeAudioPatch(patchDesc->mHandle); 4859 nextAudioPortGeneration(); 4860 mpClientInterface->onAudioPatchListUpdate(); 4861 return status; 4862} 4863 4864status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input, 4865 audio_devices_t device, 4866 bool force, 4867 audio_patch_handle_t *patchHandle) 4868{ 4869 status_t status = NO_ERROR; 4870 4871 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input); 4872 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) { 4873 inputDesc->mDevice = device; 4874 4875 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device); 4876 if (!deviceList.isEmpty()) { 4877 struct audio_patch patch; 4878 inputDesc->toAudioPortConfig(&patch.sinks[0]); 4879 // AUDIO_SOURCE_HOTWORD is for internal use only: 4880 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL 4881 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD && 4882 !inputDesc->isSoundTrigger()) { 4883 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION; 4884 } 4885 patch.num_sinks = 1; 4886 //only one input device for now 4887 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]); 4888 patch.num_sources = 1; 4889 ssize_t index; 4890 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) { 4891 index = mAudioPatches.indexOfKey(*patchHandle); 4892 } else { 4893 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle()); 4894 } 4895 sp< AudioPatch> patchDesc; 4896 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 4897 if (index >= 0) { 4898 patchDesc = mAudioPatches.valueAt(index); 4899 afPatchHandle = patchDesc->mAfPatchHandle; 4900 } 4901 4902 status_t status = mpClientInterface->createAudioPatch(&patch, 4903 &afPatchHandle, 4904 0); 4905 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d", 4906 status, afPatchHandle); 4907 if (status == NO_ERROR) { 4908 if (index < 0) { 4909 patchDesc = new AudioPatch(&patch, mUidCached); 4910 addAudioPatch(patchDesc->mHandle, patchDesc); 4911 } else { 4912 patchDesc->mPatch = patch; 4913 } 4914 patchDesc->mAfPatchHandle = afPatchHandle; 4915 if (patchHandle) { 4916 *patchHandle = patchDesc->mHandle; 4917 } 4918 inputDesc->setPatchHandle(patchDesc->mHandle); 4919 nextAudioPortGeneration(); 4920 mpClientInterface->onAudioPatchListUpdate(); 4921 } 4922 } 4923 } 4924 return status; 4925} 4926 4927status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input, 4928 audio_patch_handle_t *patchHandle) 4929{ 4930 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input); 4931 ssize_t index; 4932 if (patchHandle) { 4933 index = mAudioPatches.indexOfKey(*patchHandle); 4934 } else { 4935 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle()); 4936 } 4937 if (index < 0) { 4938 return INVALID_OPERATION; 4939 } 4940 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index); 4941 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 4942 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status); 4943 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE); 4944 removeAudioPatch(patchDesc->mHandle); 4945 nextAudioPortGeneration(); 4946 mpClientInterface->onAudioPatchListUpdate(); 4947 return status; 4948} 4949 4950sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device, 4951 const String8& address, 4952 uint32_t& samplingRate, 4953 audio_format_t& format, 4954 audio_channel_mask_t& channelMask, 4955 audio_input_flags_t flags) 4956{ 4957 // Choose an input profile based on the requested capture parameters: select the first available 4958 // profile supporting all requested parameters. 4959 // 4960 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return 4961 // the best matching profile, not the first one. 4962 4963 for (size_t i = 0; i < mHwModules.size(); i++) 4964 { 4965 if (mHwModules[i]->mHandle == 0) { 4966 continue; 4967 } 4968 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) 4969 { 4970 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j]; 4971 // profile->log(); 4972 if (profile->isCompatibleProfile(device, address, samplingRate, 4973 &samplingRate /*updatedSamplingRate*/, 4974 format, 4975 &format /*updatedFormat*/, 4976 channelMask, 4977 &channelMask /*updatedChannelMask*/, 4978 (audio_output_flags_t) flags)) { 4979 4980 return profile; 4981 } 4982 } 4983 } 4984 return NULL; 4985} 4986 4987 4988audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource, 4989 AudioMix **policyMix) 4990{ 4991 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN; 4992 audio_devices_t selectedDeviceFromMix = 4993 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix); 4994 4995 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) { 4996 return selectedDeviceFromMix; 4997 } 4998 return getDeviceForInputSource(inputSource); 4999} 5000 5001audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource) 5002{ 5003 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) { 5004 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex); 5005 if (inputSource == route->mSource && route->isActive()) { 5006 return route->mDeviceDescriptor->type(); 5007 } 5008 } 5009 5010 return mEngine->getDeviceForInputSource(inputSource); 5011} 5012 5013float AudioPolicyManager::computeVolume(audio_stream_type_t stream, 5014 int index, 5015 audio_devices_t device) 5016{ 5017 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index); 5018 5019 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much 5020 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch 5021 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to 5022 // the ringtone volume 5023 if ((stream == AUDIO_STREAM_ACCESSIBILITY) 5024 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) 5025 && isStreamActive(AUDIO_STREAM_RING, 0)) { 5026 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device); 5027 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB; 5028 } 5029 5030 // if a headset is connected, apply the following rules to ring tones and notifications 5031 // to avoid sound level bursts in user's ears: 5032 // - always attenuate notifications volume by 6dB 5033 // - attenuate ring tones volume by 6dB unless music is not playing and 5034 // speaker is part of the select devices 5035 // - if music is playing, always limit the volume to current music volume, 5036 // with a minimum threshold at -36dB so that notification is always perceived. 5037 const routing_strategy stream_strategy = getStrategy(stream); 5038 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP | 5039 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES | 5040 AUDIO_DEVICE_OUT_WIRED_HEADSET | 5041 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) && 5042 ((stream_strategy == STRATEGY_SONIFICATION) 5043 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL) 5044 || (stream == AUDIO_STREAM_SYSTEM) 5045 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) && 5046 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) && 5047 mVolumeCurves->canBeMuted(stream)) { 5048 // when the phone is ringing we must consider that music could have been paused just before 5049 // by the music application and behave as if music was active if the last music track was 5050 // just stopped 5051 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) || 5052 mLimitRingtoneVolume) { 5053 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB; 5054 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/); 5055 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC, 5056 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC, 5057 musicDevice), 5058 musicDevice); 5059 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ? 5060 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB; 5061 if (volumeDB > minVolDB) { 5062 volumeDB = minVolDB; 5063 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB); 5064 } 5065 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP | 5066 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) { 5067 // on A2DP, also ensure notification volume is not too low compared to media when 5068 // intended to be played 5069 if ((volumeDB > -96.0f) && 5070 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) { 5071 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f", 5072 stream, device, 5073 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB); 5074 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB; 5075 } 5076 } 5077 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) || 5078 stream_strategy != STRATEGY_SONIFICATION) { 5079 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB; 5080 } 5081 } 5082 5083 return volumeDB; 5084} 5085 5086status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream, 5087 int index, 5088 const sp<AudioOutputDescriptor>& outputDesc, 5089 audio_devices_t device, 5090 int delayMs, 5091 bool force) 5092{ 5093 // do not change actual stream volume if the stream is muted 5094 if (outputDesc->mMuteCount[stream] != 0) { 5095 ALOGVV("checkAndSetVolume() stream %d muted count %d", 5096 stream, outputDesc->mMuteCount[stream]); 5097 return NO_ERROR; 5098 } 5099 audio_policy_forced_cfg_t forceUseForComm = 5100 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION); 5101 // do not change in call volume if bluetooth is connected and vice versa 5102 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) || 5103 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) { 5104 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm", 5105 stream, forceUseForComm); 5106 return INVALID_OPERATION; 5107 } 5108 5109 if (device == AUDIO_DEVICE_NONE) { 5110 device = outputDesc->device(); 5111 } 5112 5113 float volumeDb = computeVolume(stream, index, device); 5114 if (outputDesc->isFixedVolume(device)) { 5115 volumeDb = 0.0f; 5116 } 5117 5118 outputDesc->setVolume(volumeDb, stream, device, delayMs, force); 5119 5120 if (stream == AUDIO_STREAM_VOICE_CALL || 5121 stream == AUDIO_STREAM_BLUETOOTH_SCO) { 5122 float voiceVolume; 5123 // Force voice volume to max for bluetooth SCO as volume is managed by the headset 5124 if (stream == AUDIO_STREAM_VOICE_CALL) { 5125 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream); 5126 } else { 5127 voiceVolume = 1.0; 5128 } 5129 5130 if (voiceVolume != mLastVoiceVolume) { 5131 mpClientInterface->setVoiceVolume(voiceVolume, delayMs); 5132 mLastVoiceVolume = voiceVolume; 5133 } 5134 } 5135 5136 return NO_ERROR; 5137} 5138 5139void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc, 5140 audio_devices_t device, 5141 int delayMs, 5142 bool force) 5143{ 5144 ALOGVV("applyStreamVolumes() for device %08x", device); 5145 5146 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) { 5147 checkAndSetVolume((audio_stream_type_t)stream, 5148 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device), 5149 outputDesc, 5150 device, 5151 delayMs, 5152 force); 5153 } 5154} 5155 5156void AudioPolicyManager::setStrategyMute(routing_strategy strategy, 5157 bool on, 5158 const sp<AudioOutputDescriptor>& outputDesc, 5159 int delayMs, 5160 audio_devices_t device) 5161{ 5162 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d", 5163 strategy, on, outputDesc->getId()); 5164 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) { 5165 if (getStrategy((audio_stream_type_t)stream) == strategy) { 5166 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device); 5167 } 5168 } 5169} 5170 5171void AudioPolicyManager::setStreamMute(audio_stream_type_t stream, 5172 bool on, 5173 const sp<AudioOutputDescriptor>& outputDesc, 5174 int delayMs, 5175 audio_devices_t device) 5176{ 5177 if (device == AUDIO_DEVICE_NONE) { 5178 device = outputDesc->device(); 5179 } 5180 5181 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x", 5182 stream, on, outputDesc->mMuteCount[stream], device); 5183 5184 if (on) { 5185 if (outputDesc->mMuteCount[stream] == 0) { 5186 if (mVolumeCurves->canBeMuted(stream) && 5187 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) || 5188 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) { 5189 checkAndSetVolume(stream, 0, outputDesc, device, delayMs); 5190 } 5191 } 5192 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored 5193 outputDesc->mMuteCount[stream]++; 5194 } else { 5195 if (outputDesc->mMuteCount[stream] == 0) { 5196 ALOGV("setStreamMute() unmuting non muted stream!"); 5197 return; 5198 } 5199 if (--outputDesc->mMuteCount[stream] == 0) { 5200 checkAndSetVolume(stream, 5201 mVolumeCurves->getVolumeIndex(stream, device), 5202 outputDesc, 5203 device, 5204 delayMs); 5205 } 5206 } 5207} 5208 5209void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream, 5210 bool starting, bool stateChange) 5211{ 5212 if(!hasPrimaryOutput()) { 5213 return; 5214 } 5215 5216 // if the stream pertains to sonification strategy and we are in call we must 5217 // mute the stream if it is low visibility. If it is high visibility, we must play a tone 5218 // in the device used for phone strategy and play the tone if the selected device does not 5219 // interfere with the device used for phone strategy 5220 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as 5221 // many times as there are active tracks on the output 5222 const routing_strategy stream_strategy = getStrategy(stream); 5223 if ((stream_strategy == STRATEGY_SONIFICATION) || 5224 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) { 5225 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput; 5226 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d", 5227 stream, starting, outputDesc->mDevice, stateChange); 5228 if (outputDesc->mRefCount[stream]) { 5229 int muteCount = 1; 5230 if (stateChange) { 5231 muteCount = outputDesc->mRefCount[stream]; 5232 } 5233 if (audio_is_low_visibility(stream)) { 5234 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount); 5235 for (int i = 0; i < muteCount; i++) { 5236 setStreamMute(stream, starting, mPrimaryOutput); 5237 } 5238 } else { 5239 ALOGV("handleIncallSonification() high visibility"); 5240 if (outputDesc->device() & 5241 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) { 5242 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount); 5243 for (int i = 0; i < muteCount; i++) { 5244 setStreamMute(stream, starting, mPrimaryOutput); 5245 } 5246 } 5247 if (starting) { 5248 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION, 5249 AUDIO_STREAM_VOICE_CALL); 5250 } else { 5251 mpClientInterface->stopTone(); 5252 } 5253 } 5254 } 5255 } 5256} 5257 5258audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr) 5259{ 5260 // flags to stream type mapping 5261 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) { 5262 return AUDIO_STREAM_ENFORCED_AUDIBLE; 5263 } 5264 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) { 5265 return AUDIO_STREAM_BLUETOOTH_SCO; 5266 } 5267 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) { 5268 return AUDIO_STREAM_TTS; 5269 } 5270 5271 // usage to stream type mapping 5272 switch (attr->usage) { 5273 case AUDIO_USAGE_MEDIA: 5274 case AUDIO_USAGE_GAME: 5275 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE: 5276 return AUDIO_STREAM_MUSIC; 5277 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY: 5278 return AUDIO_STREAM_ACCESSIBILITY; 5279 case AUDIO_USAGE_ASSISTANCE_SONIFICATION: 5280 return AUDIO_STREAM_SYSTEM; 5281 case AUDIO_USAGE_VOICE_COMMUNICATION: 5282 return AUDIO_STREAM_VOICE_CALL; 5283 5284 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING: 5285 return AUDIO_STREAM_DTMF; 5286 5287 case AUDIO_USAGE_ALARM: 5288 return AUDIO_STREAM_ALARM; 5289 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE: 5290 return AUDIO_STREAM_RING; 5291 5292 case AUDIO_USAGE_NOTIFICATION: 5293 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST: 5294 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT: 5295 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED: 5296 case AUDIO_USAGE_NOTIFICATION_EVENT: 5297 return AUDIO_STREAM_NOTIFICATION; 5298 5299 case AUDIO_USAGE_UNKNOWN: 5300 default: 5301 return AUDIO_STREAM_MUSIC; 5302 } 5303} 5304 5305bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) 5306{ 5307 // has flags that map to a strategy? 5308 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) { 5309 return true; 5310 } 5311 5312 // has known usage? 5313 switch (paa->usage) { 5314 case AUDIO_USAGE_UNKNOWN: 5315 case AUDIO_USAGE_MEDIA: 5316 case AUDIO_USAGE_VOICE_COMMUNICATION: 5317 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING: 5318 case AUDIO_USAGE_ALARM: 5319 case AUDIO_USAGE_NOTIFICATION: 5320 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE: 5321 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST: 5322 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT: 5323 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED: 5324 case AUDIO_USAGE_NOTIFICATION_EVENT: 5325 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY: 5326 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE: 5327 case AUDIO_USAGE_ASSISTANCE_SONIFICATION: 5328 case AUDIO_USAGE_GAME: 5329 case AUDIO_USAGE_VIRTUAL_SOURCE: 5330 break; 5331 default: 5332 return false; 5333 } 5334 return true; 5335} 5336 5337bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc, 5338 routing_strategy strategy, uint32_t inPastMs, 5339 nsecs_t sysTime) const 5340{ 5341 if ((sysTime == 0) && (inPastMs != 0)) { 5342 sysTime = systemTime(); 5343 } 5344 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) { 5345 if (((getStrategy((audio_stream_type_t)i) == strategy) || 5346 (NUM_STRATEGIES == strategy)) && 5347 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) { 5348 return true; 5349 } 5350 } 5351 return false; 5352} 5353 5354audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage) 5355{ 5356 return mEngine->getForceUse(usage); 5357} 5358 5359bool AudioPolicyManager::isInCall() 5360{ 5361 return isStateInCall(mEngine->getPhoneState()); 5362} 5363 5364bool AudioPolicyManager::isStateInCall(int state) 5365{ 5366 return is_state_in_call(state); 5367} 5368 5369void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc) 5370{ 5371 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) { 5372 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i); 5373 if (sourceDesc->mDevice->equals(deviceDesc)) { 5374 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle()); 5375 stopAudioSource(sourceDesc->getHandle()); 5376 } 5377 } 5378 5379 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) { 5380 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i); 5381 bool release = false; 5382 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) { 5383 const struct audio_port_config *source = &patchDesc->mPatch.sources[j]; 5384 if (source->type == AUDIO_PORT_TYPE_DEVICE && 5385 source->ext.device.type == deviceDesc->type()) { 5386 release = true; 5387 } 5388 } 5389 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) { 5390 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j]; 5391 if (sink->type == AUDIO_PORT_TYPE_DEVICE && 5392 sink->ext.device.type == deviceDesc->type()) { 5393 release = true; 5394 } 5395 } 5396 if (release) { 5397 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle); 5398 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid); 5399 } 5400 } 5401} 5402 5403// Modify the list of surround sound formats supported. 5404void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) { 5405 FormatVector &formats = *formatsPtr; 5406 // TODO Set this based on Config properties. 5407 const bool alwaysForceAC3 = true; 5408 5409 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse( 5410 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND); 5411 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse); 5412 5413 // Analyze original support for various formats. 5414 bool supportsAC3 = false; 5415 bool supportsOtherSurround = false; 5416 bool supportsIEC61937 = false; 5417 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) { 5418 audio_format_t format = formats[formatIndex]; 5419 switch (format) { 5420 case AUDIO_FORMAT_AC3: 5421 supportsAC3 = true; 5422 break; 5423 case AUDIO_FORMAT_E_AC3: 5424 case AUDIO_FORMAT_DTS: 5425 case AUDIO_FORMAT_DTS_HD: 5426 supportsOtherSurround = true; 5427 break; 5428 case AUDIO_FORMAT_IEC61937: 5429 supportsIEC61937 = true; 5430 break; 5431 default: 5432 break; 5433 } 5434 } 5435 5436 // Modify formats based on surround preferences. 5437 // If NEVER, remove support for surround formats. 5438 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { 5439 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) { 5440 // Remove surround sound related formats. 5441 for (size_t formatIndex = 0; formatIndex < formats.size(); ) { 5442 audio_format_t format = formats[formatIndex]; 5443 switch(format) { 5444 case AUDIO_FORMAT_AC3: 5445 case AUDIO_FORMAT_E_AC3: 5446 case AUDIO_FORMAT_DTS: 5447 case AUDIO_FORMAT_DTS_HD: 5448 case AUDIO_FORMAT_IEC61937: 5449 formats.removeAt(formatIndex); 5450 break; 5451 default: 5452 formatIndex++; // keep it 5453 break; 5454 } 5455 } 5456 supportsAC3 = false; 5457 supportsOtherSurround = false; 5458 supportsIEC61937 = false; 5459 } 5460 } else { // AUTO or ALWAYS 5461 // Most TVs support AC3 even if they do not report it in the EDID. 5462 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)) 5463 && !supportsAC3) { 5464 formats.add(AUDIO_FORMAT_AC3); 5465 supportsAC3 = true; 5466 } 5467 5468 // If ALWAYS, add support for raw surround formats if all are missing. 5469 // This assumes that if any of these formats are reported by the HAL 5470 // then the report is valid and should not be modified. 5471 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) 5472 && !supportsOtherSurround) { 5473 formats.add(AUDIO_FORMAT_E_AC3); 5474 formats.add(AUDIO_FORMAT_DTS); 5475 formats.add(AUDIO_FORMAT_DTS_HD); 5476 supportsOtherSurround = true; 5477 } 5478 5479 // Add support for IEC61937 if any raw surround supported. 5480 // The HAL could do this but add it here, just in case. 5481 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) { 5482 formats.add(AUDIO_FORMAT_IEC61937); 5483 supportsIEC61937 = true; 5484 } 5485 } 5486} 5487 5488// Modify the list of channel masks supported. 5489void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) { 5490 ChannelsVector &channelMasks = *channelMasksPtr; 5491 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse( 5492 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND); 5493 5494 // If NEVER, then remove support for channelMasks > stereo. 5495 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { 5496 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) { 5497 audio_channel_mask_t channelMask = channelMasks[maskIndex]; 5498 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) { 5499 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask); 5500 channelMasks.removeAt(maskIndex); 5501 } else { 5502 maskIndex++; 5503 } 5504 } 5505 // If ALWAYS, then make sure we at least support 5.1 5506 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) { 5507 bool supports5dot1 = false; 5508 // Are there any channel masks that can be considered "surround"? 5509 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) { 5510 audio_channel_mask_t channelMask = channelMasks[maskIndex]; 5511 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) { 5512 supports5dot1 = true; 5513 break; 5514 } 5515 } 5516 // If not then add 5.1 support. 5517 if (!supports5dot1) { 5518 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1); 5519 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__); 5520 } 5521 } 5522} 5523 5524void AudioPolicyManager::updateAudioProfiles(audio_devices_t device, 5525 audio_io_handle_t ioHandle, 5526 AudioProfileVector &profiles) 5527{ 5528 String8 reply; 5529 5530 // Format MUST be checked first to update the list of AudioProfile 5531 if (profiles.hasDynamicFormat()) { 5532 reply = mpClientInterface->getParameters(ioHandle, 5533 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS)); 5534 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string()); 5535 AudioParameter repliedParameters(reply); 5536 if (repliedParameters.get( 5537 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS), reply) != NO_ERROR) { 5538 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__); 5539 return; 5540 } 5541 FormatVector formats = formatsFromString(reply.string()); 5542 if (device == AUDIO_DEVICE_OUT_HDMI) { 5543 filterSurroundFormats(&formats); 5544 } 5545 profiles.setFormats(formats); 5546 } 5547 const FormatVector &supportedFormats = profiles.getSupportedFormats(); 5548 5549 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) { 5550 audio_format_t format = supportedFormats[formatIndex]; 5551 ChannelsVector channelMasks; 5552 SampleRateVector samplingRates; 5553 AudioParameter requestedParameters; 5554 requestedParameters.addInt(String8(AUDIO_PARAMETER_STREAM_FORMAT), format); 5555 5556 if (profiles.hasDynamicRateFor(format)) { 5557 reply = mpClientInterface->getParameters(ioHandle, 5558 requestedParameters.toString() + ";" + 5559 AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES); 5560 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string()); 5561 AudioParameter repliedParameters(reply); 5562 if (repliedParameters.get( 5563 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES), reply) == NO_ERROR) { 5564 samplingRates = samplingRatesFromString(reply.string()); 5565 } 5566 } 5567 if (profiles.hasDynamicChannelsFor(format)) { 5568 reply = mpClientInterface->getParameters(ioHandle, 5569 requestedParameters.toString() + ";" + 5570 AUDIO_PARAMETER_STREAM_SUP_CHANNELS); 5571 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string()); 5572 AudioParameter repliedParameters(reply); 5573 if (repliedParameters.get( 5574 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS), reply) == NO_ERROR) { 5575 channelMasks = channelMasksFromString(reply.string()); 5576 if (device == AUDIO_DEVICE_OUT_HDMI) { 5577 filterSurroundChannelMasks(&channelMasks); 5578 } 5579 } 5580 } 5581 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates)); 5582 } 5583} 5584 5585}; // namespace android 5586