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