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