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