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 "AudioPolicyManagerBase" 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// A device mask for all audio input devices that are considered "virtual" when evaluating 28// active inputs in getActiveInput() 29#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX 30// A device mask for all audio output devices that are considered "remote" when evaluating 31// active output devices in isStreamActiveRemotely() 32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX 33 34#include <utils/Log.h> 35#include <hardware_legacy/AudioPolicyManagerBase.h> 36#include <hardware/audio_effect.h> 37#include <hardware/audio.h> 38#include <math.h> 39#include <hardware_legacy/audio_policy_conf.h> 40#include <cutils/properties.h> 41 42namespace android_audio_legacy { 43 44// ---------------------------------------------------------------------------- 45// AudioPolicyInterface implementation 46// ---------------------------------------------------------------------------- 47 48 49status_t AudioPolicyManagerBase::setDeviceConnectionState(audio_devices_t device, 50 AudioSystem::device_connection_state state, 51 const char *device_address) 52{ 53 SortedVector <audio_io_handle_t> outputs; 54 55 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address); 56 57 // connect/disconnect only 1 device at a time 58 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE; 59 60 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) { 61 ALOGE("setDeviceConnectionState() invalid address: %s", device_address); 62 return BAD_VALUE; 63 } 64 65 // handle output devices 66 if (audio_is_output_device(device)) { 67 68 if (!mHasA2dp && audio_is_a2dp_device(device)) { 69 ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device); 70 return BAD_VALUE; 71 } 72 if (!mHasUsb && audio_is_usb_device(device)) { 73 ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device); 74 return BAD_VALUE; 75 } 76 if (!mHasRemoteSubmix && audio_is_remote_submix_device((audio_devices_t)device)) { 77 ALOGE("setDeviceConnectionState() invalid remote submix audio device: %x", device); 78 return BAD_VALUE; 79 } 80 81 // save a copy of the opened output descriptors before any output is opened or closed 82 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies() 83 mPreviousOutputs = mOutputs; 84 switch (state) 85 { 86 // handle output device connection 87 case AudioSystem::DEVICE_STATE_AVAILABLE: 88 if (mAvailableOutputDevices & device) { 89 ALOGW("setDeviceConnectionState() device already connected: %x", device); 90 return INVALID_OPERATION; 91 } 92 ALOGV("setDeviceConnectionState() connecting device %x", device); 93 94 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) { 95 return INVALID_OPERATION; 96 } 97 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %d outputs", 98 outputs.size()); 99 // register new device as available 100 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device); 101 102 if (!outputs.isEmpty()) { 103 String8 paramStr; 104 if (mHasA2dp && audio_is_a2dp_device(device)) { 105 // handle A2DP device connection 106 AudioParameter param; 107 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address)); 108 paramStr = param.toString(); 109 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN); 110 mA2dpSuspended = false; 111 } else if (audio_is_bluetooth_sco_device(device)) { 112 // handle SCO device connection 113 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN); 114 } else if (mHasUsb && audio_is_usb_device(device)) { 115 // handle USB device connection 116 mUsbCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN); 117 paramStr = mUsbCardAndDevice; 118 } 119 // not currently handling multiple simultaneous submixes: ignoring remote submix 120 // case and address 121 if (!paramStr.isEmpty()) { 122 for (size_t i = 0; i < outputs.size(); i++) { 123 mpClientInterface->setParameters(outputs[i], paramStr); 124 } 125 } 126 } 127 break; 128 // handle output device disconnection 129 case AudioSystem::DEVICE_STATE_UNAVAILABLE: { 130 if (!(mAvailableOutputDevices & device)) { 131 ALOGW("setDeviceConnectionState() device not connected: %x", device); 132 return INVALID_OPERATION; 133 } 134 135 ALOGV("setDeviceConnectionState() disconnecting device %x", device); 136 // remove device from available output devices 137 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device); 138 139 checkOutputsForDevice(device, state, outputs); 140 if (mHasA2dp && audio_is_a2dp_device(device)) { 141 // handle A2DP device disconnection 142 mA2dpDeviceAddress = ""; 143 mA2dpSuspended = false; 144 } else if (audio_is_bluetooth_sco_device(device)) { 145 // handle SCO device disconnection 146 mScoDeviceAddress = ""; 147 } else if (mHasUsb && audio_is_usb_device(device)) { 148 // handle USB device disconnection 149 mUsbCardAndDevice = ""; 150 } 151 // not currently handling multiple simultaneous submixes: ignoring remote submix 152 // case and address 153 } break; 154 155 default: 156 ALOGE("setDeviceConnectionState() invalid state: %x", state); 157 return BAD_VALUE; 158 } 159 160 checkA2dpSuspend(); 161 checkOutputForAllStrategies(); 162 // outputs must be closed after checkOutputForAllStrategies() is executed 163 if (!outputs.isEmpty()) { 164 for (size_t i = 0; i < outputs.size(); i++) { 165 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]); 166 // close unused outputs after device disconnection or direct outputs that have been 167 // opened by checkOutputsForDevice() to query dynamic parameters 168 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) || 169 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) && 170 (desc->mDirectOpenCount == 0))) { 171 closeOutput(outputs[i]); 172 } 173 } 174 } 175 176 updateDevicesAndOutputs(); 177 for (size_t i = 0; i < mOutputs.size(); i++) { 178 // do not force device change on duplicated output because if device is 0, it will 179 // also force a device 0 for the two outputs it is duplicated to which may override 180 // a valid device selection on those outputs. 181 setOutputDevice(mOutputs.keyAt(i), 182 getNewDevice(mOutputs.keyAt(i), true /*fromCache*/), 183 !mOutputs.valueAt(i)->isDuplicated(), 184 0); 185 } 186 187 if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) { 188 device = AUDIO_DEVICE_IN_WIRED_HEADSET; 189 } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO || 190 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET || 191 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) { 192 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET; 193 } else { 194 return NO_ERROR; 195 } 196 } 197 // handle input devices 198 if (audio_is_input_device(device)) { 199 200 switch (state) 201 { 202 // handle input device connection 203 case AudioSystem::DEVICE_STATE_AVAILABLE: { 204 if (mAvailableInputDevices & device) { 205 ALOGW("setDeviceConnectionState() device already connected: %d", device); 206 return INVALID_OPERATION; 207 } 208 mAvailableInputDevices = mAvailableInputDevices | (device & ~AUDIO_DEVICE_BIT_IN); 209 } 210 break; 211 212 // handle input device disconnection 213 case AudioSystem::DEVICE_STATE_UNAVAILABLE: { 214 if (!(mAvailableInputDevices & device)) { 215 ALOGW("setDeviceConnectionState() device not connected: %d", device); 216 return INVALID_OPERATION; 217 } 218 mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device); 219 } break; 220 221 default: 222 ALOGE("setDeviceConnectionState() invalid state: %x", state); 223 return BAD_VALUE; 224 } 225 226 audio_io_handle_t activeInput = getActiveInput(); 227 if (activeInput != 0) { 228 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput); 229 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource); 230 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) { 231 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d", 232 inputDesc->mDevice, newDevice, activeInput); 233 inputDesc->mDevice = newDevice; 234 AudioParameter param = AudioParameter(); 235 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice); 236 mpClientInterface->setParameters(activeInput, param.toString()); 237 } 238 } 239 240 return NO_ERROR; 241 } 242 243 ALOGW("setDeviceConnectionState() invalid device: %x", device); 244 return BAD_VALUE; 245} 246 247AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(audio_devices_t device, 248 const char *device_address) 249{ 250 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE; 251 String8 address = String8(device_address); 252 if (audio_is_output_device(device)) { 253 if (device & mAvailableOutputDevices) { 254 if (audio_is_a2dp_device(device) && 255 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) { 256 return state; 257 } 258 if (audio_is_bluetooth_sco_device(device) && 259 address != "" && mScoDeviceAddress != address) { 260 return state; 261 } 262 if (audio_is_usb_device(device) && 263 (!mHasUsb || (address != "" && mUsbCardAndDevice != address))) { 264 ALOGE("getDeviceConnectionState() invalid device: %x", device); 265 return state; 266 } 267 if (audio_is_remote_submix_device((audio_devices_t)device) && !mHasRemoteSubmix) { 268 return state; 269 } 270 state = AudioSystem::DEVICE_STATE_AVAILABLE; 271 } 272 } else if (audio_is_input_device(device)) { 273 if (device & mAvailableInputDevices) { 274 state = AudioSystem::DEVICE_STATE_AVAILABLE; 275 } 276 } 277 278 return state; 279} 280 281void AudioPolicyManagerBase::setPhoneState(int state) 282{ 283 ALOGV("setPhoneState() state %d", state); 284 audio_devices_t newDevice = AUDIO_DEVICE_NONE; 285 if (state < 0 || state >= AudioSystem::NUM_MODES) { 286 ALOGW("setPhoneState() invalid state %d", state); 287 return; 288 } 289 290 if (state == mPhoneState ) { 291 ALOGW("setPhoneState() setting same state %d", state); 292 return; 293 } 294 295 // if leaving call state, handle special case of active streams 296 // pertaining to sonification strategy see handleIncallSonification() 297 if (isInCall()) { 298 ALOGV("setPhoneState() in call state management: new state is %d", state); 299 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) { 300 handleIncallSonification(stream, false, true); 301 } 302 } 303 304 // store previous phone state for management of sonification strategy below 305 int oldState = mPhoneState; 306 mPhoneState = state; 307 bool force = false; 308 309 // are we entering or starting a call 310 if (!isStateInCall(oldState) && isStateInCall(state)) { 311 ALOGV(" Entering call in setPhoneState()"); 312 // force routing command to audio hardware when starting a call 313 // even if no device change is needed 314 force = true; 315 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) { 316 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] = 317 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j]; 318 } 319 } else if (isStateInCall(oldState) && !isStateInCall(state)) { 320 ALOGV(" Exiting call in setPhoneState()"); 321 // force routing command to audio hardware when exiting a call 322 // even if no device change is needed 323 force = true; 324 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) { 325 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] = 326 sVolumeProfiles[AUDIO_STREAM_DTMF][j]; 327 } 328 } else if (isStateInCall(state) && (state != oldState)) { 329 ALOGV(" Switching between telephony and VoIP in setPhoneState()"); 330 // force routing command to audio hardware when switching between telephony and VoIP 331 // even if no device change is needed 332 force = true; 333 } 334 335 // check for device and output changes triggered by new phone state 336 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/); 337 checkA2dpSuspend(); 338 checkOutputForAllStrategies(); 339 updateDevicesAndOutputs(); 340 341 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput); 342 343 // force routing command to audio hardware when ending call 344 // even if no device change is needed 345 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) { 346 newDevice = hwOutputDesc->device(); 347 } 348 349 int delayMs = 0; 350 if (isStateInCall(state)) { 351 nsecs_t sysTime = systemTime(); 352 for (size_t i = 0; i < mOutputs.size(); i++) { 353 AudioOutputDescriptor *desc = mOutputs.valueAt(i); 354 // mute media and sonification strategies and delay device switch by the largest 355 // latency of any output where either strategy is active. 356 // This avoid sending the ring tone or music tail into the earpiece or headset. 357 if ((desc->isStrategyActive(STRATEGY_MEDIA, 358 SONIFICATION_HEADSET_MUSIC_DELAY, 359 sysTime) || 360 desc->isStrategyActive(STRATEGY_SONIFICATION, 361 SONIFICATION_HEADSET_MUSIC_DELAY, 362 sysTime)) && 363 (delayMs < (int)desc->mLatency*2)) { 364 delayMs = desc->mLatency*2; 365 } 366 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i)); 367 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS, 368 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/)); 369 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i)); 370 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS, 371 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/)); 372 } 373 } 374 375 // change routing is necessary 376 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs); 377 378 // if entering in call state, handle special case of active streams 379 // pertaining to sonification strategy see handleIncallSonification() 380 if (isStateInCall(state)) { 381 ALOGV("setPhoneState() in call state management: new state is %d", state); 382 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) { 383 handleIncallSonification(stream, true, true); 384 } 385 } 386 387 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE 388 if (state == AudioSystem::MODE_RINGTONE && 389 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) { 390 mLimitRingtoneVolume = true; 391 } else { 392 mLimitRingtoneVolume = false; 393 } 394} 395 396void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config) 397{ 398 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState); 399 400 bool forceVolumeReeval = false; 401 switch(usage) { 402 case AudioSystem::FOR_COMMUNICATION: 403 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO && 404 config != AudioSystem::FORCE_NONE) { 405 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config); 406 return; 407 } 408 forceVolumeReeval = true; 409 mForceUse[usage] = config; 410 break; 411 case AudioSystem::FOR_MEDIA: 412 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP && 413 config != AudioSystem::FORCE_WIRED_ACCESSORY && 414 config != AudioSystem::FORCE_ANALOG_DOCK && 415 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE && 416 config != AudioSystem::FORCE_NO_BT_A2DP) { 417 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config); 418 return; 419 } 420 mForceUse[usage] = config; 421 break; 422 case AudioSystem::FOR_RECORD: 423 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY && 424 config != AudioSystem::FORCE_NONE) { 425 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config); 426 return; 427 } 428 mForceUse[usage] = config; 429 break; 430 case AudioSystem::FOR_DOCK: 431 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK && 432 config != AudioSystem::FORCE_BT_DESK_DOCK && 433 config != AudioSystem::FORCE_WIRED_ACCESSORY && 434 config != AudioSystem::FORCE_ANALOG_DOCK && 435 config != AudioSystem::FORCE_DIGITAL_DOCK) { 436 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config); 437 } 438 forceVolumeReeval = true; 439 mForceUse[usage] = config; 440 break; 441 case AudioSystem::FOR_SYSTEM: 442 if (config != AudioSystem::FORCE_NONE && 443 config != AudioSystem::FORCE_SYSTEM_ENFORCED) { 444 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config); 445 } 446 forceVolumeReeval = true; 447 mForceUse[usage] = config; 448 break; 449 default: 450 ALOGW("setForceUse() invalid usage %d", usage); 451 break; 452 } 453 454 // check for device and output changes triggered by new force usage 455 checkA2dpSuspend(); 456 checkOutputForAllStrategies(); 457 updateDevicesAndOutputs(); 458 for (size_t i = 0; i < mOutputs.size(); i++) { 459 audio_io_handle_t output = mOutputs.keyAt(i); 460 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/); 461 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE)); 462 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) { 463 applyStreamVolumes(output, newDevice, 0, true); 464 } 465 } 466 467 audio_io_handle_t activeInput = getActiveInput(); 468 if (activeInput != 0) { 469 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput); 470 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource); 471 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) { 472 ALOGV("setForceUse() changing device from %x to %x for input %d", 473 inputDesc->mDevice, newDevice, activeInput); 474 inputDesc->mDevice = newDevice; 475 AudioParameter param = AudioParameter(); 476 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice); 477 mpClientInterface->setParameters(activeInput, param.toString()); 478 } 479 } 480 481} 482 483AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage) 484{ 485 return mForceUse[usage]; 486} 487 488void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value) 489{ 490 ALOGV("setSystemProperty() property %s, value %s", property, value); 491} 492 493// Find a direct output profile compatible with the parameters passed, even if the input flags do 494// not explicitly request a direct output 495AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput( 496 audio_devices_t device, 497 uint32_t samplingRate, 498 uint32_t format, 499 uint32_t channelMask, 500 audio_output_flags_t flags) 501{ 502 for (size_t i = 0; i < mHwModules.size(); i++) { 503 if (mHwModules[i]->mHandle == 0) { 504 continue; 505 } 506 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) { 507 IOProfile *profile = mHwModules[i]->mOutputProfiles[j]; 508 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) { 509 if (profile->isCompatibleProfile(device, samplingRate, format, 510 channelMask, 511 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) { 512 if (mAvailableOutputDevices & profile->mSupportedDevices) { 513 return mHwModules[i]->mOutputProfiles[j]; 514 } 515 } 516 } else { 517 if (profile->isCompatibleProfile(device, samplingRate, format, 518 channelMask, 519 AUDIO_OUTPUT_FLAG_DIRECT)) { 520 if (mAvailableOutputDevices & profile->mSupportedDevices) { 521 return mHwModules[i]->mOutputProfiles[j]; 522 } 523 } 524 } 525 } 526 } 527 return 0; 528} 529 530audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream, 531 uint32_t samplingRate, 532 uint32_t format, 533 uint32_t channelMask, 534 AudioSystem::output_flags flags, 535 const audio_offload_info_t *offloadInfo) 536{ 537 audio_io_handle_t output = 0; 538 uint32_t latency = 0; 539 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream); 540 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/); 541 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x", 542 device, stream, samplingRate, format, channelMask, flags); 543 544#ifdef AUDIO_POLICY_TEST 545 if (mCurOutput != 0) { 546 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d", 547 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput); 548 549 if (mTestOutputs[mCurOutput] == 0) { 550 ALOGV("getOutput() opening test output"); 551 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL); 552 outputDesc->mDevice = mTestDevice; 553 outputDesc->mSamplingRate = mTestSamplingRate; 554 outputDesc->mFormat = mTestFormat; 555 outputDesc->mChannelMask = mTestChannels; 556 outputDesc->mLatency = mTestLatencyMs; 557 outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0); 558 outputDesc->mRefCount[stream] = 0; 559 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice, 560 &outputDesc->mSamplingRate, 561 &outputDesc->mFormat, 562 &outputDesc->mChannelMask, 563 &outputDesc->mLatency, 564 outputDesc->mFlags, 565 offloadInfo); 566 if (mTestOutputs[mCurOutput]) { 567 AudioParameter outputCmd = AudioParameter(); 568 outputCmd.addInt(String8("set_id"),mCurOutput); 569 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString()); 570 addOutput(mTestOutputs[mCurOutput], outputDesc); 571 } 572 } 573 return mTestOutputs[mCurOutput]; 574 } 575#endif //AUDIO_POLICY_TEST 576 577 // open a direct output if required by specified parameters 578 //force direct flag if offload flag is set: offloading implies a direct output stream 579 // and all common behaviors are driven by checking only the direct flag 580 // this should normally be set appropriately in the policy configuration file 581 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) { 582 flags = (AudioSystem::output_flags)(flags | AUDIO_OUTPUT_FLAG_DIRECT); 583 } 584 585 // Do not allow offloading if one non offloadable effect is enabled. This prevents from 586 // creating an offloaded track and tearing it down immediately after start when audioflinger 587 // detects there is an active non offloadable effect. 588 // FIXME: We should check the audio session here but we do not have it in this context. 589 // This may prevent offloading in rare situations where effects are left active by apps 590 // in the background. 591 IOProfile *profile = NULL; 592 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) || 593 !isNonOffloadableEffectEnabled()) { 594 profile = getProfileForDirectOutput(device, 595 samplingRate, 596 format, 597 channelMask, 598 (audio_output_flags_t)flags); 599 } 600 601 if (profile != NULL) { 602 AudioOutputDescriptor *outputDesc = NULL; 603 604 for (size_t i = 0; i < mOutputs.size(); i++) { 605 AudioOutputDescriptor *desc = mOutputs.valueAt(i); 606 if (!desc->isDuplicated() && (profile == desc->mProfile)) { 607 outputDesc = desc; 608 // reuse direct output if currently open and configured with same parameters 609 if ((samplingRate == outputDesc->mSamplingRate) && 610 (format == outputDesc->mFormat) && 611 (channelMask == outputDesc->mChannelMask)) { 612 outputDesc->mDirectOpenCount++; 613 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i)); 614 return mOutputs.keyAt(i); 615 } 616 } 617 } 618 // close direct output if currently open and configured with different parameters 619 if (outputDesc != NULL) { 620 closeOutput(outputDesc->mId); 621 } 622 outputDesc = new AudioOutputDescriptor(profile); 623 outputDesc->mDevice = device; 624 outputDesc->mSamplingRate = samplingRate; 625 outputDesc->mFormat = (audio_format_t)format; 626 outputDesc->mChannelMask = (audio_channel_mask_t)channelMask; 627 outputDesc->mLatency = 0; 628 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags); 629 outputDesc->mRefCount[stream] = 0; 630 outputDesc->mStopTime[stream] = 0; 631 outputDesc->mDirectOpenCount = 1; 632 output = mpClientInterface->openOutput(profile->mModule->mHandle, 633 &outputDesc->mDevice, 634 &outputDesc->mSamplingRate, 635 &outputDesc->mFormat, 636 &outputDesc->mChannelMask, 637 &outputDesc->mLatency, 638 outputDesc->mFlags, 639 offloadInfo); 640 641 // only accept an output with the requested parameters 642 if (output == 0 || 643 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) || 644 (format != 0 && format != outputDesc->mFormat) || 645 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) { 646 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d," 647 "format %d %d, channelMask %04x %04x", output, samplingRate, 648 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask, 649 outputDesc->mChannelMask); 650 if (output != 0) { 651 mpClientInterface->closeOutput(output); 652 } 653 delete outputDesc; 654 return 0; 655 } 656 audio_io_handle_t srcOutput = getOutputForEffect(); 657 addOutput(output, outputDesc); 658 audio_io_handle_t dstOutput = getOutputForEffect(); 659 if (dstOutput == output) { 660 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput); 661 } 662 mPreviousOutputs = mOutputs; 663 ALOGV("getOutput() returns new direct output %d", output); 664 return output; 665 } 666 667 // ignoring channel mask due to downmix capability in mixer 668 669 // open a non direct output 670 671 // for non direct outputs, only PCM is supported 672 if (audio_is_linear_pcm((audio_format_t)format)) { 673 // get which output is suitable for the specified stream. The actual 674 // routing change will happen when startOutput() will be called 675 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs); 676 677 output = selectOutput(outputs, flags); 678 } 679 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d," 680 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags); 681 682 ALOGV("getOutput() returns output %d", output); 683 684 return output; 685} 686 687audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs, 688 AudioSystem::output_flags flags) 689{ 690 // select one output among several that provide a path to a particular device or set of 691 // devices (the list was previously build by getOutputsForDevice()). 692 // The priority is as follows: 693 // 1: the output with the highest number of requested policy flags 694 // 2: the primary output 695 // 3: the first output in the list 696 697 if (outputs.size() == 0) { 698 return 0; 699 } 700 if (outputs.size() == 1) { 701 return outputs[0]; 702 } 703 704 int maxCommonFlags = 0; 705 audio_io_handle_t outputFlags = 0; 706 audio_io_handle_t outputPrimary = 0; 707 708 for (size_t i = 0; i < outputs.size(); i++) { 709 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]); 710 if (!outputDesc->isDuplicated()) { 711 int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags); 712 if (commonFlags > maxCommonFlags) { 713 outputFlags = outputs[i]; 714 maxCommonFlags = commonFlags; 715 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags); 716 } 717 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) { 718 outputPrimary = outputs[i]; 719 } 720 } 721 } 722 723 if (outputFlags != 0) { 724 return outputFlags; 725 } 726 if (outputPrimary != 0) { 727 return outputPrimary; 728 } 729 730 return outputs[0]; 731} 732 733status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output, 734 AudioSystem::stream_type stream, 735 int session) 736{ 737 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session); 738 ssize_t index = mOutputs.indexOfKey(output); 739 if (index < 0) { 740 ALOGW("startOutput() unknow output %d", output); 741 return BAD_VALUE; 742 } 743 744 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index); 745 746 // increment usage count for this stream on the requested output: 747 // NOTE that the usage count is the same for duplicated output and hardware output which is 748 // necessary for a correct control of hardware output routing by startOutput() and stopOutput() 749 outputDesc->changeRefCount(stream, 1); 750 751 if (outputDesc->mRefCount[stream] == 1) { 752 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/); 753 routing_strategy strategy = getStrategy(stream); 754 bool shouldWait = (strategy == STRATEGY_SONIFICATION) || 755 (strategy == STRATEGY_SONIFICATION_RESPECTFUL); 756 uint32_t waitMs = 0; 757 bool force = false; 758 for (size_t i = 0; i < mOutputs.size(); i++) { 759 AudioOutputDescriptor *desc = mOutputs.valueAt(i); 760 if (desc != outputDesc) { 761 // force a device change if any other output is managed by the same hw 762 // module and has a current device selection that differs from selected device. 763 // In this case, the audio HAL must receive the new device selection so that it can 764 // change the device currently selected by the other active output. 765 if (outputDesc->sharesHwModuleWith(desc) && 766 desc->device() != newDevice) { 767 force = true; 768 } 769 // wait for audio on other active outputs to be presented when starting 770 // a notification so that audio focus effect can propagate. 771 uint32_t latency = desc->latency(); 772 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) { 773 waitMs = latency; 774 } 775 } 776 } 777 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force); 778 779 // handle special case for sonification while in call 780 if (isInCall()) { 781 handleIncallSonification(stream, true, false); 782 } 783 784 // apply volume rules for current stream and device if necessary 785 checkAndSetVolume(stream, 786 mStreams[stream].getVolumeIndex(newDevice), 787 output, 788 newDevice); 789 790 // update the outputs if starting an output with a stream that can affect notification 791 // routing 792 handleNotificationRoutingForStream(stream); 793 if (waitMs > muteWaitMs) { 794 usleep((waitMs - muteWaitMs) * 2 * 1000); 795 } 796 } 797 return NO_ERROR; 798} 799 800 801status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output, 802 AudioSystem::stream_type stream, 803 int session) 804{ 805 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session); 806 ssize_t index = mOutputs.indexOfKey(output); 807 if (index < 0) { 808 ALOGW("stopOutput() unknow output %d", output); 809 return BAD_VALUE; 810 } 811 812 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index); 813 814 // handle special case for sonification while in call 815 if (isInCall()) { 816 handleIncallSonification(stream, false, false); 817 } 818 819 if (outputDesc->mRefCount[stream] > 0) { 820 // decrement usage count of this stream on the output 821 outputDesc->changeRefCount(stream, -1); 822 // store time at which the stream was stopped - see isStreamActive() 823 if (outputDesc->mRefCount[stream] == 0) { 824 outputDesc->mStopTime[stream] = systemTime(); 825 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/); 826 // delay the device switch by twice the latency because stopOutput() is executed when 827 // the track stop() command is received and at that time the audio track buffer can 828 // still contain data that needs to be drained. The latency only covers the audio HAL 829 // and kernel buffers. Also the latency does not always include additional delay in the 830 // audio path (audio DSP, CODEC ...) 831 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2); 832 833 // force restoring the device selection on other active outputs if it differs from the 834 // one being selected for this output 835 for (size_t i = 0; i < mOutputs.size(); i++) { 836 audio_io_handle_t curOutput = mOutputs.keyAt(i); 837 AudioOutputDescriptor *desc = mOutputs.valueAt(i); 838 if (curOutput != output && 839 desc->isActive() && 840 outputDesc->sharesHwModuleWith(desc) && 841 (newDevice != desc->device())) { 842 setOutputDevice(curOutput, 843 getNewDevice(curOutput, false /*fromCache*/), 844 true, 845 outputDesc->mLatency*2); 846 } 847 } 848 // update the outputs if stopping one with a stream that can affect notification routing 849 handleNotificationRoutingForStream(stream); 850 } 851 return NO_ERROR; 852 } else { 853 ALOGW("stopOutput() refcount is already 0 for output %d", output); 854 return INVALID_OPERATION; 855 } 856} 857 858void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output) 859{ 860 ALOGV("releaseOutput() %d", output); 861 ssize_t index = mOutputs.indexOfKey(output); 862 if (index < 0) { 863 ALOGW("releaseOutput() releasing unknown output %d", output); 864 return; 865 } 866 867#ifdef AUDIO_POLICY_TEST 868 int testIndex = testOutputIndex(output); 869 if (testIndex != 0) { 870 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index); 871 if (outputDesc->isActive()) { 872 mpClientInterface->closeOutput(output); 873 delete mOutputs.valueAt(index); 874 mOutputs.removeItem(output); 875 mTestOutputs[testIndex] = 0; 876 } 877 return; 878 } 879#endif //AUDIO_POLICY_TEST 880 881 AudioOutputDescriptor *desc = mOutputs.valueAt(index); 882 if (desc->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) { 883 if (desc->mDirectOpenCount <= 0) { 884 ALOGW("releaseOutput() invalid open count %d for output %d", 885 desc->mDirectOpenCount, output); 886 return; 887 } 888 if (--desc->mDirectOpenCount == 0) { 889 closeOutput(output); 890 // If effects where present on the output, audioflinger moved them to the primary 891 // output by default: move them back to the appropriate output. 892 audio_io_handle_t dstOutput = getOutputForEffect(); 893 if (dstOutput != mPrimaryOutput) { 894 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput); 895 } 896 } 897 } 898} 899 900 901audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource, 902 uint32_t samplingRate, 903 uint32_t format, 904 uint32_t channelMask, 905 AudioSystem::audio_in_acoustics acoustics) 906{ 907 audio_io_handle_t input = 0; 908 audio_devices_t device = getDeviceForInputSource(inputSource); 909 910 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x", 911 inputSource, samplingRate, format, channelMask, acoustics); 912 913 if (device == AUDIO_DEVICE_NONE) { 914 ALOGW("getInput() could not find device for inputSource %d", inputSource); 915 return 0; 916 } 917 918 // adapt channel selection to input source 919 switch(inputSource) { 920 case AUDIO_SOURCE_VOICE_UPLINK: 921 channelMask = AudioSystem::CHANNEL_IN_VOICE_UPLINK; 922 break; 923 case AUDIO_SOURCE_VOICE_DOWNLINK: 924 channelMask = AudioSystem::CHANNEL_IN_VOICE_DNLINK; 925 break; 926 case AUDIO_SOURCE_VOICE_CALL: 927 channelMask = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK); 928 break; 929 default: 930 break; 931 } 932 933 IOProfile *profile = getInputProfile(device, 934 samplingRate, 935 format, 936 channelMask); 937 if (profile == NULL) { 938 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d," 939 "channelMask %04x", 940 device, samplingRate, format, channelMask); 941 return 0; 942 } 943 944 if (profile->mModule->mHandle == 0) { 945 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName); 946 return 0; 947 } 948 949 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile); 950 951 inputDesc->mInputSource = inputSource; 952 inputDesc->mDevice = device; 953 inputDesc->mSamplingRate = samplingRate; 954 inputDesc->mFormat = (audio_format_t)format; 955 inputDesc->mChannelMask = (audio_channel_mask_t)channelMask; 956 inputDesc->mRefCount = 0; 957 input = mpClientInterface->openInput(profile->mModule->mHandle, 958 &inputDesc->mDevice, 959 &inputDesc->mSamplingRate, 960 &inputDesc->mFormat, 961 &inputDesc->mChannelMask); 962 963 // only accept input with the exact requested set of parameters 964 if (input == 0 || 965 (samplingRate != inputDesc->mSamplingRate) || 966 (format != inputDesc->mFormat) || 967 (channelMask != inputDesc->mChannelMask)) { 968 ALOGV("getInput() failed opening input: samplingRate %d, format %d, channelMask %d", 969 samplingRate, format, channelMask); 970 if (input != 0) { 971 mpClientInterface->closeInput(input); 972 } 973 delete inputDesc; 974 return 0; 975 } 976 mInputs.add(input, inputDesc); 977 return input; 978} 979 980status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input) 981{ 982 ALOGV("startInput() input %d", input); 983 ssize_t index = mInputs.indexOfKey(input); 984 if (index < 0) { 985 ALOGW("startInput() unknow input %d", input); 986 return BAD_VALUE; 987 } 988 AudioInputDescriptor *inputDesc = mInputs.valueAt(index); 989 990#ifdef AUDIO_POLICY_TEST 991 if (mTestInput == 0) 992#endif //AUDIO_POLICY_TEST 993 { 994 // refuse 2 active AudioRecord clients at the same time except if the active input 995 // uses AUDIO_SOURCE_HOTWORD in which case it is closed. 996 audio_io_handle_t activeInput = getActiveInput(); 997 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) { 998 AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput); 999 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) { 1000 ALOGW("startInput() preempting already started low-priority input %d", activeInput); 1001 stopInput(activeInput); 1002 releaseInput(activeInput); 1003 } else { 1004 ALOGW("startInput() input %d failed: other input already started..", input); 1005 return INVALID_OPERATION; 1006 } 1007 } 1008 } 1009 1010 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource); 1011 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) { 1012 inputDesc->mDevice = newDevice; 1013 } 1014 1015 // automatically enable the remote submix output when input is started 1016 if (audio_is_remote_submix_device(inputDesc->mDevice)) { 1017 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, 1018 AudioSystem::DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS); 1019 } 1020 1021 AudioParameter param = AudioParameter(); 1022 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice); 1023 1024 int aliasSource = (inputDesc->mInputSource == AUDIO_SOURCE_HOTWORD) ? 1025 AUDIO_SOURCE_VOICE_RECOGNITION : inputDesc->mInputSource; 1026 1027 param.addInt(String8(AudioParameter::keyInputSource), aliasSource); 1028 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource); 1029 1030 mpClientInterface->setParameters(input, param.toString()); 1031 1032 inputDesc->mRefCount = 1; 1033 return NO_ERROR; 1034} 1035 1036status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input) 1037{ 1038 ALOGV("stopInput() input %d", input); 1039 ssize_t index = mInputs.indexOfKey(input); 1040 if (index < 0) { 1041 ALOGW("stopInput() unknow input %d", input); 1042 return BAD_VALUE; 1043 } 1044 AudioInputDescriptor *inputDesc = mInputs.valueAt(index); 1045 1046 if (inputDesc->mRefCount == 0) { 1047 ALOGW("stopInput() input %d already stopped", input); 1048 return INVALID_OPERATION; 1049 } else { 1050 // automatically disable the remote submix output when input is stopped 1051 if (audio_is_remote_submix_device(inputDesc->mDevice)) { 1052 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, 1053 AudioSystem::DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS); 1054 } 1055 1056 AudioParameter param = AudioParameter(); 1057 param.addInt(String8(AudioParameter::keyRouting), 0); 1058 mpClientInterface->setParameters(input, param.toString()); 1059 inputDesc->mRefCount = 0; 1060 return NO_ERROR; 1061 } 1062} 1063 1064void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input) 1065{ 1066 ALOGV("releaseInput() %d", input); 1067 ssize_t index = mInputs.indexOfKey(input); 1068 if (index < 0) { 1069 ALOGW("releaseInput() releasing unknown input %d", input); 1070 return; 1071 } 1072 mpClientInterface->closeInput(input); 1073 delete mInputs.valueAt(index); 1074 mInputs.removeItem(input); 1075 ALOGV("releaseInput() exit"); 1076} 1077 1078void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream, 1079 int indexMin, 1080 int indexMax) 1081{ 1082 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax); 1083 if (indexMin < 0 || indexMin >= indexMax) { 1084 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax); 1085 return; 1086 } 1087 mStreams[stream].mIndexMin = indexMin; 1088 mStreams[stream].mIndexMax = indexMax; 1089} 1090 1091status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream, 1092 int index, 1093 audio_devices_t device) 1094{ 1095 1096 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) { 1097 return BAD_VALUE; 1098 } 1099 if (!audio_is_output_device(device)) { 1100 return BAD_VALUE; 1101 } 1102 1103 // Force max volume if stream cannot be muted 1104 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax; 1105 1106 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d", 1107 stream, device, index); 1108 1109 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and 1110 // clear all device specific values 1111 if (device == AUDIO_DEVICE_OUT_DEFAULT) { 1112 mStreams[stream].mIndexCur.clear(); 1113 } 1114 mStreams[stream].mIndexCur.add(device, index); 1115 1116 // compute and apply stream volume on all outputs according to connected device 1117 status_t status = NO_ERROR; 1118 for (size_t i = 0; i < mOutputs.size(); i++) { 1119 audio_devices_t curDevice = 1120 getDeviceForVolume(mOutputs.valueAt(i)->device()); 1121 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) { 1122 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice); 1123 if (volStatus != NO_ERROR) { 1124 status = volStatus; 1125 } 1126 } 1127 } 1128 return status; 1129} 1130 1131status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream, 1132 int *index, 1133 audio_devices_t device) 1134{ 1135 if (index == NULL) { 1136 return BAD_VALUE; 1137 } 1138 if (!audio_is_output_device(device)) { 1139 return BAD_VALUE; 1140 } 1141 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to 1142 // the strategy the stream belongs to. 1143 if (device == AUDIO_DEVICE_OUT_DEFAULT) { 1144 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/); 1145 } 1146 device = getDeviceForVolume(device); 1147 1148 *index = mStreams[stream].getVolumeIndex(device); 1149 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index); 1150 return NO_ERROR; 1151} 1152 1153audio_io_handle_t AudioPolicyManagerBase::selectOutputForEffects( 1154 const SortedVector<audio_io_handle_t>& outputs) 1155{ 1156 // select one output among several suitable for global effects. 1157 // The priority is as follows: 1158 // 1: An offloaded output. If the effect ends up not being offloadable, 1159 // AudioFlinger will invalidate the track and the offloaded output 1160 // will be closed causing the effect to be moved to a PCM output. 1161 // 2: A deep buffer output 1162 // 3: the first output in the list 1163 1164 if (outputs.size() == 0) { 1165 return 0; 1166 } 1167 1168 audio_io_handle_t outputOffloaded = 0; 1169 audio_io_handle_t outputDeepBuffer = 0; 1170 1171 for (size_t i = 0; i < outputs.size(); i++) { 1172 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]); 1173 ALOGV("selectOutputForEffects outputs[%d] flags %x", i, desc->mFlags); 1174 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) { 1175 outputOffloaded = outputs[i]; 1176 } 1177 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) { 1178 outputDeepBuffer = outputs[i]; 1179 } 1180 } 1181 1182 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d", 1183 outputOffloaded, outputDeepBuffer); 1184 if (outputOffloaded != 0) { 1185 return outputOffloaded; 1186 } 1187 if (outputDeepBuffer != 0) { 1188 return outputDeepBuffer; 1189 } 1190 1191 return outputs[0]; 1192} 1193 1194audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(const effect_descriptor_t *desc) 1195{ 1196 // apply simple rule where global effects are attached to the same output as MUSIC streams 1197 1198 routing_strategy strategy = getStrategy(AudioSystem::MUSIC); 1199 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/); 1200 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs); 1201 1202 audio_io_handle_t output = selectOutputForEffects(dstOutputs); 1203 ALOGV("getOutputForEffect() got output %d for fx %s flags %x", 1204 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags); 1205 1206 return output; 1207} 1208 1209status_t AudioPolicyManagerBase::registerEffect(const effect_descriptor_t *desc, 1210 audio_io_handle_t io, 1211 uint32_t strategy, 1212 int session, 1213 int id) 1214{ 1215 ssize_t index = mOutputs.indexOfKey(io); 1216 if (index < 0) { 1217 index = mInputs.indexOfKey(io); 1218 if (index < 0) { 1219 ALOGW("registerEffect() unknown io %d", io); 1220 return INVALID_OPERATION; 1221 } 1222 } 1223 1224 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) { 1225 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB", 1226 desc->name, desc->memoryUsage); 1227 return INVALID_OPERATION; 1228 } 1229 mTotalEffectsMemory += desc->memoryUsage; 1230 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d", 1231 desc->name, io, strategy, session, id); 1232 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory); 1233 1234 EffectDescriptor *pDesc = new EffectDescriptor(); 1235 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t)); 1236 pDesc->mIo = io; 1237 pDesc->mStrategy = (routing_strategy)strategy; 1238 pDesc->mSession = session; 1239 pDesc->mEnabled = false; 1240 1241 mEffects.add(id, pDesc); 1242 1243 return NO_ERROR; 1244} 1245 1246status_t AudioPolicyManagerBase::unregisterEffect(int id) 1247{ 1248 ssize_t index = mEffects.indexOfKey(id); 1249 if (index < 0) { 1250 ALOGW("unregisterEffect() unknown effect ID %d", id); 1251 return INVALID_OPERATION; 1252 } 1253 1254 EffectDescriptor *pDesc = mEffects.valueAt(index); 1255 1256 setEffectEnabled(pDesc, false); 1257 1258 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) { 1259 ALOGW("unregisterEffect() memory %d too big for total %d", 1260 pDesc->mDesc.memoryUsage, mTotalEffectsMemory); 1261 pDesc->mDesc.memoryUsage = mTotalEffectsMemory; 1262 } 1263 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage; 1264 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d", 1265 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory); 1266 1267 mEffects.removeItem(id); 1268 delete pDesc; 1269 1270 return NO_ERROR; 1271} 1272 1273status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled) 1274{ 1275 ssize_t index = mEffects.indexOfKey(id); 1276 if (index < 0) { 1277 ALOGW("unregisterEffect() unknown effect ID %d", id); 1278 return INVALID_OPERATION; 1279 } 1280 1281 return setEffectEnabled(mEffects.valueAt(index), enabled); 1282} 1283 1284status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled) 1285{ 1286 if (enabled == pDesc->mEnabled) { 1287 ALOGV("setEffectEnabled(%s) effect already %s", 1288 enabled?"true":"false", enabled?"enabled":"disabled"); 1289 return INVALID_OPERATION; 1290 } 1291 1292 if (enabled) { 1293 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) { 1294 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS", 1295 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10); 1296 return INVALID_OPERATION; 1297 } 1298 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad; 1299 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad); 1300 } else { 1301 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) { 1302 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d", 1303 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad); 1304 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad; 1305 } 1306 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad; 1307 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad); 1308 } 1309 pDesc->mEnabled = enabled; 1310 return NO_ERROR; 1311} 1312 1313bool AudioPolicyManagerBase::isNonOffloadableEffectEnabled() 1314{ 1315 for (size_t i = 0; i < mEffects.size(); i++) { 1316 const EffectDescriptor * const pDesc = mEffects.valueAt(i); 1317 if (pDesc->mEnabled && (pDesc->mStrategy == STRATEGY_MEDIA) && 1318 ((pDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) { 1319 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d", 1320 pDesc->mDesc.name, pDesc->mSession); 1321 return true; 1322 } 1323 } 1324 return false; 1325} 1326 1327bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const 1328{ 1329 nsecs_t sysTime = systemTime(); 1330 for (size_t i = 0; i < mOutputs.size(); i++) { 1331 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i); 1332 if (outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) { 1333 return true; 1334 } 1335 } 1336 return false; 1337} 1338 1339bool AudioPolicyManagerBase::isStreamActiveRemotely(int stream, uint32_t inPastMs) const 1340{ 1341 nsecs_t sysTime = systemTime(); 1342 for (size_t i = 0; i < mOutputs.size(); i++) { 1343 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i); 1344 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) && 1345 outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) { 1346 return true; 1347 } 1348 } 1349 return false; 1350} 1351 1352bool AudioPolicyManagerBase::isSourceActive(audio_source_t source) const 1353{ 1354 for (size_t i = 0; i < mInputs.size(); i++) { 1355 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i); 1356 if ((inputDescriptor->mInputSource == (int)source || 1357 (source == (audio_source_t)AUDIO_SOURCE_VOICE_RECOGNITION && 1358 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD)) 1359 && (inputDescriptor->mRefCount > 0)) { 1360 return true; 1361 } 1362 } 1363 return false; 1364} 1365 1366 1367status_t AudioPolicyManagerBase::dump(int fd) 1368{ 1369 const size_t SIZE = 256; 1370 char buffer[SIZE]; 1371 String8 result; 1372 1373 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this); 1374 result.append(buffer); 1375 1376 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput); 1377 result.append(buffer); 1378 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string()); 1379 result.append(buffer); 1380 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string()); 1381 result.append(buffer); 1382 snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbCardAndDevice.string()); 1383 result.append(buffer); 1384 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices); 1385 result.append(buffer); 1386 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices); 1387 result.append(buffer); 1388 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState); 1389 result.append(buffer); 1390 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]); 1391 result.append(buffer); 1392 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]); 1393 result.append(buffer); 1394 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]); 1395 result.append(buffer); 1396 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]); 1397 result.append(buffer); 1398 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AudioSystem::FOR_SYSTEM]); 1399 result.append(buffer); 1400 write(fd, result.string(), result.size()); 1401 1402 1403 snprintf(buffer, SIZE, "\nHW Modules dump:\n"); 1404 write(fd, buffer, strlen(buffer)); 1405 for (size_t i = 0; i < mHwModules.size(); i++) { 1406 snprintf(buffer, SIZE, "- HW Module %d:\n", i + 1); 1407 write(fd, buffer, strlen(buffer)); 1408 mHwModules[i]->dump(fd); 1409 } 1410 1411 snprintf(buffer, SIZE, "\nOutputs dump:\n"); 1412 write(fd, buffer, strlen(buffer)); 1413 for (size_t i = 0; i < mOutputs.size(); i++) { 1414 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i)); 1415 write(fd, buffer, strlen(buffer)); 1416 mOutputs.valueAt(i)->dump(fd); 1417 } 1418 1419 snprintf(buffer, SIZE, "\nInputs dump:\n"); 1420 write(fd, buffer, strlen(buffer)); 1421 for (size_t i = 0; i < mInputs.size(); i++) { 1422 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i)); 1423 write(fd, buffer, strlen(buffer)); 1424 mInputs.valueAt(i)->dump(fd); 1425 } 1426 1427 snprintf(buffer, SIZE, "\nStreams dump:\n"); 1428 write(fd, buffer, strlen(buffer)); 1429 snprintf(buffer, SIZE, 1430 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n"); 1431 write(fd, buffer, strlen(buffer)); 1432 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) { 1433 snprintf(buffer, SIZE, " %02d ", i); 1434 write(fd, buffer, strlen(buffer)); 1435 mStreams[i].dump(fd); 1436 } 1437 1438 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n", 1439 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory); 1440 write(fd, buffer, strlen(buffer)); 1441 1442 snprintf(buffer, SIZE, "Registered effects:\n"); 1443 write(fd, buffer, strlen(buffer)); 1444 for (size_t i = 0; i < mEffects.size(); i++) { 1445 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i)); 1446 write(fd, buffer, strlen(buffer)); 1447 mEffects.valueAt(i)->dump(fd); 1448 } 1449 1450 1451 return NO_ERROR; 1452} 1453 1454// This function checks for the parameters which can be offloaded. 1455// This can be enhanced depending on the capability of the DSP and policy 1456// of the system. 1457bool AudioPolicyManagerBase::isOffloadSupported(const audio_offload_info_t& offloadInfo) 1458{ 1459 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d," 1460 " BitRate=%u, duration=%lld us, has_video=%d", 1461 offloadInfo.sample_rate, offloadInfo.channel_mask, 1462 offloadInfo.format, 1463 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us, 1464 offloadInfo.has_video); 1465 1466 // Check if offload has been disabled 1467 char propValue[PROPERTY_VALUE_MAX]; 1468 if (property_get("audio.offload.disable", propValue, "0")) { 1469 if (atoi(propValue) != 0) { 1470 ALOGV("offload disabled by audio.offload.disable=%s", propValue ); 1471 return false; 1472 } 1473 } 1474 1475 // Check if stream type is music, then only allow offload as of now. 1476 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC) 1477 { 1478 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false"); 1479 return false; 1480 } 1481 1482 //TODO: enable audio offloading with video when ready 1483 if (offloadInfo.has_video) 1484 { 1485 ALOGV("isOffloadSupported: has_video == true, returning false"); 1486 return false; 1487 } 1488 1489 //If duration is less than minimum value defined in property, return false 1490 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) { 1491 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) { 1492 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue); 1493 return false; 1494 } 1495 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) { 1496 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS); 1497 return false; 1498 } 1499 1500 // Do not allow offloading if one non offloadable effect is enabled. This prevents from 1501 // creating an offloaded track and tearing it down immediately after start when audioflinger 1502 // detects there is an active non offloadable effect. 1503 // FIXME: We should check the audio session here but we do not have it in this context. 1504 // This may prevent offloading in rare situations where effects are left active by apps 1505 // in the background. 1506 if (isNonOffloadableEffectEnabled()) { 1507 return false; 1508 } 1509 1510 // See if there is a profile to support this. 1511 // AUDIO_DEVICE_NONE 1512 IOProfile *profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */, 1513 offloadInfo.sample_rate, 1514 offloadInfo.format, 1515 offloadInfo.channel_mask, 1516 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD); 1517 ALOGV("isOffloadSupported() profile %sfound", profile != NULL ? "" : "NOT "); 1518 return (profile != NULL); 1519} 1520 1521// ---------------------------------------------------------------------------- 1522// AudioPolicyManagerBase 1523// ---------------------------------------------------------------------------- 1524 1525AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface) 1526 : 1527#ifdef AUDIO_POLICY_TEST 1528 Thread(false), 1529#endif //AUDIO_POLICY_TEST 1530 mPrimaryOutput((audio_io_handle_t)0), 1531 mAvailableOutputDevices(AUDIO_DEVICE_NONE), 1532 mPhoneState(AudioSystem::MODE_NORMAL), 1533 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f), 1534 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0), 1535 mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false), mHasRemoteSubmix(false), 1536 mSpeakerDrcEnabled(false) 1537{ 1538 mpClientInterface = clientInterface; 1539 1540 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) { 1541 mForceUse[i] = AudioSystem::FORCE_NONE; 1542 } 1543 1544 mA2dpDeviceAddress = String8(""); 1545 mScoDeviceAddress = String8(""); 1546 mUsbCardAndDevice = String8(""); 1547 1548 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) { 1549 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) { 1550 ALOGE("could not load audio policy configuration file, setting defaults"); 1551 defaultAudioPolicyConfig(); 1552 } 1553 } 1554 1555 // must be done after reading the policy 1556 initializeVolumeCurves(); 1557 1558 // open all output streams needed to access attached devices 1559 for (size_t i = 0; i < mHwModules.size(); i++) { 1560 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName); 1561 if (mHwModules[i]->mHandle == 0) { 1562 ALOGW("could not open HW module %s", mHwModules[i]->mName); 1563 continue; 1564 } 1565 // open all output streams needed to access attached devices 1566 // except for direct output streams that are only opened when they are actually 1567 // required by an app. 1568 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 1569 { 1570 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j]; 1571 1572 if ((outProfile->mSupportedDevices & mAttachedOutputDevices) && 1573 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) { 1574 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile); 1575 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice & 1576 outProfile->mSupportedDevices); 1577 audio_io_handle_t output = mpClientInterface->openOutput( 1578 outProfile->mModule->mHandle, 1579 &outputDesc->mDevice, 1580 &outputDesc->mSamplingRate, 1581 &outputDesc->mFormat, 1582 &outputDesc->mChannelMask, 1583 &outputDesc->mLatency, 1584 outputDesc->mFlags); 1585 if (output == 0) { 1586 delete outputDesc; 1587 } else { 1588 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | 1589 (outProfile->mSupportedDevices & mAttachedOutputDevices)); 1590 if (mPrimaryOutput == 0 && 1591 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) { 1592 mPrimaryOutput = output; 1593 } 1594 addOutput(output, outputDesc); 1595 setOutputDevice(output, 1596 (audio_devices_t)(mDefaultOutputDevice & 1597 outProfile->mSupportedDevices), 1598 true); 1599 } 1600 } 1601 } 1602 } 1603 1604 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices), 1605 "Not output found for attached devices %08x", 1606 (mAttachedOutputDevices & ~mAvailableOutputDevices)); 1607 1608 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output"); 1609 1610 updateDevicesAndOutputs(); 1611 1612#ifdef AUDIO_POLICY_TEST 1613 if (mPrimaryOutput != 0) { 1614 AudioParameter outputCmd = AudioParameter(); 1615 outputCmd.addInt(String8("set_id"), 0); 1616 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString()); 1617 1618 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER; 1619 mTestSamplingRate = 44100; 1620 mTestFormat = AudioSystem::PCM_16_BIT; 1621 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO; 1622 mTestLatencyMs = 0; 1623 mCurOutput = 0; 1624 mDirectOutput = false; 1625 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) { 1626 mTestOutputs[i] = 0; 1627 } 1628 1629 const size_t SIZE = 256; 1630 char buffer[SIZE]; 1631 snprintf(buffer, SIZE, "AudioPolicyManagerTest"); 1632 run(buffer, ANDROID_PRIORITY_AUDIO); 1633 } 1634#endif //AUDIO_POLICY_TEST 1635} 1636 1637AudioPolicyManagerBase::~AudioPolicyManagerBase() 1638{ 1639#ifdef AUDIO_POLICY_TEST 1640 exit(); 1641#endif //AUDIO_POLICY_TEST 1642 for (size_t i = 0; i < mOutputs.size(); i++) { 1643 mpClientInterface->closeOutput(mOutputs.keyAt(i)); 1644 delete mOutputs.valueAt(i); 1645 } 1646 for (size_t i = 0; i < mInputs.size(); i++) { 1647 mpClientInterface->closeInput(mInputs.keyAt(i)); 1648 delete mInputs.valueAt(i); 1649 } 1650 for (size_t i = 0; i < mHwModules.size(); i++) { 1651 delete mHwModules[i]; 1652 } 1653} 1654 1655status_t AudioPolicyManagerBase::initCheck() 1656{ 1657 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR; 1658} 1659 1660#ifdef AUDIO_POLICY_TEST 1661bool AudioPolicyManagerBase::threadLoop() 1662{ 1663 ALOGV("entering threadLoop()"); 1664 while (!exitPending()) 1665 { 1666 String8 command; 1667 int valueInt; 1668 String8 value; 1669 1670 Mutex::Autolock _l(mLock); 1671 mWaitWorkCV.waitRelative(mLock, milliseconds(50)); 1672 1673 command = mpClientInterface->getParameters(0, String8("test_cmd_policy")); 1674 AudioParameter param = AudioParameter(command); 1675 1676 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR && 1677 valueInt != 0) { 1678 ALOGV("Test command %s received", command.string()); 1679 String8 target; 1680 if (param.get(String8("target"), target) != NO_ERROR) { 1681 target = "Manager"; 1682 } 1683 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) { 1684 param.remove(String8("test_cmd_policy_output")); 1685 mCurOutput = valueInt; 1686 } 1687 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) { 1688 param.remove(String8("test_cmd_policy_direct")); 1689 if (value == "false") { 1690 mDirectOutput = false; 1691 } else if (value == "true") { 1692 mDirectOutput = true; 1693 } 1694 } 1695 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) { 1696 param.remove(String8("test_cmd_policy_input")); 1697 mTestInput = valueInt; 1698 } 1699 1700 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) { 1701 param.remove(String8("test_cmd_policy_format")); 1702 int format = AudioSystem::INVALID_FORMAT; 1703 if (value == "PCM 16 bits") { 1704 format = AudioSystem::PCM_16_BIT; 1705 } else if (value == "PCM 8 bits") { 1706 format = AudioSystem::PCM_8_BIT; 1707 } else if (value == "Compressed MP3") { 1708 format = AudioSystem::MP3; 1709 } 1710 if (format != AudioSystem::INVALID_FORMAT) { 1711 if (target == "Manager") { 1712 mTestFormat = format; 1713 } else if (mTestOutputs[mCurOutput] != 0) { 1714 AudioParameter outputParam = AudioParameter(); 1715 outputParam.addInt(String8("format"), format); 1716 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 1717 } 1718 } 1719 } 1720 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) { 1721 param.remove(String8("test_cmd_policy_channels")); 1722 int channels = 0; 1723 1724 if (value == "Channels Stereo") { 1725 channels = AudioSystem::CHANNEL_OUT_STEREO; 1726 } else if (value == "Channels Mono") { 1727 channels = AudioSystem::CHANNEL_OUT_MONO; 1728 } 1729 if (channels != 0) { 1730 if (target == "Manager") { 1731 mTestChannels = channels; 1732 } else if (mTestOutputs[mCurOutput] != 0) { 1733 AudioParameter outputParam = AudioParameter(); 1734 outputParam.addInt(String8("channels"), channels); 1735 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 1736 } 1737 } 1738 } 1739 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) { 1740 param.remove(String8("test_cmd_policy_sampleRate")); 1741 if (valueInt >= 0 && valueInt <= 96000) { 1742 int samplingRate = valueInt; 1743 if (target == "Manager") { 1744 mTestSamplingRate = samplingRate; 1745 } else if (mTestOutputs[mCurOutput] != 0) { 1746 AudioParameter outputParam = AudioParameter(); 1747 outputParam.addInt(String8("sampling_rate"), samplingRate); 1748 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 1749 } 1750 } 1751 } 1752 1753 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) { 1754 param.remove(String8("test_cmd_policy_reopen")); 1755 1756 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput); 1757 mpClientInterface->closeOutput(mPrimaryOutput); 1758 1759 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle; 1760 1761 delete mOutputs.valueFor(mPrimaryOutput); 1762 mOutputs.removeItem(mPrimaryOutput); 1763 1764 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL); 1765 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER; 1766 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle, 1767 &outputDesc->mDevice, 1768 &outputDesc->mSamplingRate, 1769 &outputDesc->mFormat, 1770 &outputDesc->mChannelMask, 1771 &outputDesc->mLatency, 1772 outputDesc->mFlags); 1773 if (mPrimaryOutput == 0) { 1774 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d", 1775 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask); 1776 } else { 1777 AudioParameter outputCmd = AudioParameter(); 1778 outputCmd.addInt(String8("set_id"), 0); 1779 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString()); 1780 addOutput(mPrimaryOutput, outputDesc); 1781 } 1782 } 1783 1784 1785 mpClientInterface->setParameters(0, String8("test_cmd_policy=")); 1786 } 1787 } 1788 return false; 1789} 1790 1791void AudioPolicyManagerBase::exit() 1792{ 1793 { 1794 AutoMutex _l(mLock); 1795 requestExit(); 1796 mWaitWorkCV.signal(); 1797 } 1798 requestExitAndWait(); 1799} 1800 1801int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output) 1802{ 1803 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) { 1804 if (output == mTestOutputs[i]) return i; 1805 } 1806 return 0; 1807} 1808#endif //AUDIO_POLICY_TEST 1809 1810// --- 1811 1812void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc) 1813{ 1814 outputDesc->mId = id; 1815 mOutputs.add(id, outputDesc); 1816} 1817 1818 1819status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device, 1820 AudioSystem::device_connection_state state, 1821 SortedVector<audio_io_handle_t>& outputs) 1822{ 1823 AudioOutputDescriptor *desc; 1824 1825 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) { 1826 // first list already open outputs that can be routed to this device 1827 for (size_t i = 0; i < mOutputs.size(); i++) { 1828 desc = mOutputs.valueAt(i); 1829 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) { 1830 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i)); 1831 outputs.add(mOutputs.keyAt(i)); 1832 } 1833 } 1834 // then look for output profiles that can be routed to this device 1835 SortedVector<IOProfile *> profiles; 1836 for (size_t i = 0; i < mHwModules.size(); i++) 1837 { 1838 if (mHwModules[i]->mHandle == 0) { 1839 continue; 1840 } 1841 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 1842 { 1843 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) { 1844 ALOGV("checkOutputsForDevice(): adding profile %d from module %d", j, i); 1845 profiles.add(mHwModules[i]->mOutputProfiles[j]); 1846 } 1847 } 1848 } 1849 1850 if (profiles.isEmpty() && outputs.isEmpty()) { 1851 ALOGW("checkOutputsForDevice(): No output available for device %04x", device); 1852 return BAD_VALUE; 1853 } 1854 1855 // open outputs for matching profiles if needed. Direct outputs are also opened to 1856 // query for dynamic parameters and will be closed later by setDeviceConnectionState() 1857 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) { 1858 IOProfile *profile = profiles[profile_index]; 1859 1860 // nothing to do if one output is already opened for this profile 1861 size_t j; 1862 for (j = 0; j < mOutputs.size(); j++) { 1863 desc = mOutputs.valueAt(j); 1864 if (!desc->isDuplicated() && desc->mProfile == profile) { 1865 break; 1866 } 1867 } 1868 if (j != mOutputs.size()) { 1869 continue; 1870 } 1871 1872 ALOGV("opening output for device %08x", device); 1873 desc = new AudioOutputDescriptor(profile); 1874 desc->mDevice = device; 1875 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER; 1876 offloadInfo.sample_rate = desc->mSamplingRate; 1877 offloadInfo.format = desc->mFormat; 1878 offloadInfo.channel_mask = desc->mChannelMask; 1879 1880 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle, 1881 &desc->mDevice, 1882 &desc->mSamplingRate, 1883 &desc->mFormat, 1884 &desc->mChannelMask, 1885 &desc->mLatency, 1886 desc->mFlags, 1887 &offloadInfo); 1888 if (output != 0) { 1889 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) { 1890 String8 reply; 1891 char *value; 1892 if (profile->mSamplingRates[0] == 0) { 1893 reply = mpClientInterface->getParameters(output, 1894 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES)); 1895 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s", 1896 reply.string()); 1897 value = strpbrk((char *)reply.string(), "="); 1898 if (value != NULL) { 1899 loadSamplingRates(value + 1, profile); 1900 } 1901 } 1902 if (profile->mFormats[0] == 0) { 1903 reply = mpClientInterface->getParameters(output, 1904 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS)); 1905 ALOGV("checkOutputsForDevice() direct output sup formats %s", 1906 reply.string()); 1907 value = strpbrk((char *)reply.string(), "="); 1908 if (value != NULL) { 1909 loadFormats(value + 1, profile); 1910 } 1911 } 1912 if (profile->mChannelMasks[0] == 0) { 1913 reply = mpClientInterface->getParameters(output, 1914 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS)); 1915 ALOGV("checkOutputsForDevice() direct output sup channel masks %s", 1916 reply.string()); 1917 value = strpbrk((char *)reply.string(), "="); 1918 if (value != NULL) { 1919 loadOutChannels(value + 1, profile); 1920 } 1921 } 1922 if (((profile->mSamplingRates[0] == 0) && 1923 (profile->mSamplingRates.size() < 2)) || 1924 ((profile->mFormats[0] == 0) && 1925 (profile->mFormats.size() < 2)) || 1926 ((profile->mFormats[0] == 0) && 1927 (profile->mChannelMasks.size() < 2))) { 1928 ALOGW("checkOutputsForDevice() direct output missing param"); 1929 mpClientInterface->closeOutput(output); 1930 output = 0; 1931 } else { 1932 addOutput(output, desc); 1933 } 1934 } else { 1935 audio_io_handle_t duplicatedOutput = 0; 1936 // add output descriptor 1937 addOutput(output, desc); 1938 // set initial stream volume for device 1939 applyStreamVolumes(output, device, 0, true); 1940 1941 //TODO: configure audio effect output stage here 1942 1943 // open a duplicating output thread for the new output and the primary output 1944 duplicatedOutput = mpClientInterface->openDuplicateOutput(output, 1945 mPrimaryOutput); 1946 if (duplicatedOutput != 0) { 1947 // add duplicated output descriptor 1948 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL); 1949 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput); 1950 dupOutputDesc->mOutput2 = mOutputs.valueFor(output); 1951 dupOutputDesc->mSamplingRate = desc->mSamplingRate; 1952 dupOutputDesc->mFormat = desc->mFormat; 1953 dupOutputDesc->mChannelMask = desc->mChannelMask; 1954 dupOutputDesc->mLatency = desc->mLatency; 1955 addOutput(duplicatedOutput, dupOutputDesc); 1956 applyStreamVolumes(duplicatedOutput, device, 0, true); 1957 } else { 1958 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d", 1959 mPrimaryOutput, output); 1960 mpClientInterface->closeOutput(output); 1961 mOutputs.removeItem(output); 1962 output = 0; 1963 } 1964 } 1965 } 1966 if (output == 0) { 1967 ALOGW("checkOutputsForDevice() could not open output for device %x", device); 1968 delete desc; 1969 profiles.removeAt(profile_index); 1970 profile_index--; 1971 } else { 1972 outputs.add(output); 1973 ALOGV("checkOutputsForDevice(): adding output %d", output); 1974 } 1975 } 1976 1977 if (profiles.isEmpty()) { 1978 ALOGW("checkOutputsForDevice(): No output available for device %04x", device); 1979 return BAD_VALUE; 1980 } 1981 } else { 1982 // check if one opened output is not needed any more after disconnecting one device 1983 for (size_t i = 0; i < mOutputs.size(); i++) { 1984 desc = mOutputs.valueAt(i); 1985 if (!desc->isDuplicated() && 1986 !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) { 1987 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i)); 1988 outputs.add(mOutputs.keyAt(i)); 1989 } 1990 } 1991 for (size_t i = 0; i < mHwModules.size(); i++) 1992 { 1993 if (mHwModules[i]->mHandle == 0) { 1994 continue; 1995 } 1996 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 1997 { 1998 IOProfile *profile = mHwModules[i]->mOutputProfiles[j]; 1999 if ((profile->mSupportedDevices & device) && 2000 (profile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) { 2001 ALOGV("checkOutputsForDevice(): clearing direct output profile %d on module %d", 2002 j, i); 2003 if (profile->mSamplingRates[0] == 0) { 2004 profile->mSamplingRates.clear(); 2005 profile->mSamplingRates.add(0); 2006 } 2007 if (profile->mFormats[0] == 0) { 2008 profile->mFormats.clear(); 2009 profile->mFormats.add((audio_format_t)0); 2010 } 2011 if (profile->mChannelMasks[0] == 0) { 2012 profile->mChannelMasks.clear(); 2013 profile->mChannelMasks.add((audio_channel_mask_t)0); 2014 } 2015 } 2016 } 2017 } 2018 } 2019 return NO_ERROR; 2020} 2021 2022void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output) 2023{ 2024 ALOGV("closeOutput(%d)", output); 2025 2026 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 2027 if (outputDesc == NULL) { 2028 ALOGW("closeOutput() unknown output %d", output); 2029 return; 2030 } 2031 2032 // look for duplicated outputs connected to the output being removed. 2033 for (size_t i = 0; i < mOutputs.size(); i++) { 2034 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i); 2035 if (dupOutputDesc->isDuplicated() && 2036 (dupOutputDesc->mOutput1 == outputDesc || 2037 dupOutputDesc->mOutput2 == outputDesc)) { 2038 AudioOutputDescriptor *outputDesc2; 2039 if (dupOutputDesc->mOutput1 == outputDesc) { 2040 outputDesc2 = dupOutputDesc->mOutput2; 2041 } else { 2042 outputDesc2 = dupOutputDesc->mOutput1; 2043 } 2044 // As all active tracks on duplicated output will be deleted, 2045 // and as they were also referenced on the other output, the reference 2046 // count for their stream type must be adjusted accordingly on 2047 // the other output. 2048 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) { 2049 int refCount = dupOutputDesc->mRefCount[j]; 2050 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount); 2051 } 2052 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i); 2053 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput); 2054 2055 mpClientInterface->closeOutput(duplicatedOutput); 2056 delete mOutputs.valueFor(duplicatedOutput); 2057 mOutputs.removeItem(duplicatedOutput); 2058 } 2059 } 2060 2061 AudioParameter param; 2062 param.add(String8("closing"), String8("true")); 2063 mpClientInterface->setParameters(output, param.toString()); 2064 2065 mpClientInterface->closeOutput(output); 2066 delete outputDesc; 2067 mOutputs.removeItem(output); 2068 mPreviousOutputs = mOutputs; 2069} 2070 2071SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device, 2072 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs) 2073{ 2074 SortedVector<audio_io_handle_t> outputs; 2075 2076 ALOGVV("getOutputsForDevice() device %04x", device); 2077 for (size_t i = 0; i < openOutputs.size(); i++) { 2078 ALOGVV("output %d isDuplicated=%d device=%04x", 2079 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices()); 2080 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) { 2081 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i)); 2082 outputs.add(openOutputs.keyAt(i)); 2083 } 2084 } 2085 return outputs; 2086} 2087 2088bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1, 2089 SortedVector<audio_io_handle_t>& outputs2) 2090{ 2091 if (outputs1.size() != outputs2.size()) { 2092 return false; 2093 } 2094 for (size_t i = 0; i < outputs1.size(); i++) { 2095 if (outputs1[i] != outputs2[i]) { 2096 return false; 2097 } 2098 } 2099 return true; 2100} 2101 2102void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy) 2103{ 2104 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/); 2105 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/); 2106 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs); 2107 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs); 2108 2109 if (!vectorsEqual(srcOutputs,dstOutputs)) { 2110 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d", 2111 strategy, srcOutputs[0], dstOutputs[0]); 2112 // mute strategy while moving tracks from one output to another 2113 for (size_t i = 0; i < srcOutputs.size(); i++) { 2114 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]); 2115 if (desc->isStrategyActive(strategy)) { 2116 setStrategyMute(strategy, true, srcOutputs[i]); 2117 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice); 2118 } 2119 } 2120 2121 // Move effects associated to this strategy from previous output to new output 2122 if (strategy == STRATEGY_MEDIA) { 2123 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs); 2124 SortedVector<audio_io_handle_t> moved; 2125 for (size_t i = 0; i < mEffects.size(); i++) { 2126 EffectDescriptor *desc = mEffects.valueAt(i); 2127 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX && 2128 desc->mIo != fxOutput) { 2129 if (moved.indexOf(desc->mIo) < 0) { 2130 ALOGV("checkOutputForStrategy() moving effect %d to output %d", 2131 mEffects.keyAt(i), fxOutput); 2132 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo, 2133 fxOutput); 2134 moved.add(desc->mIo); 2135 } 2136 desc->mIo = fxOutput; 2137 } 2138 } 2139 } 2140 // Move tracks associated to this strategy from previous output to new output 2141 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) { 2142 if (getStrategy((AudioSystem::stream_type)i) == strategy) { 2143 //FIXME see fixme on name change 2144 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, 2145 dstOutputs[0] /* ignored */); 2146 } 2147 } 2148 } 2149} 2150 2151void AudioPolicyManagerBase::checkOutputForAllStrategies() 2152{ 2153 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE); 2154 checkOutputForStrategy(STRATEGY_PHONE); 2155 checkOutputForStrategy(STRATEGY_SONIFICATION); 2156 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL); 2157 checkOutputForStrategy(STRATEGY_MEDIA); 2158 checkOutputForStrategy(STRATEGY_DTMF); 2159} 2160 2161audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput() 2162{ 2163 if (!mHasA2dp) { 2164 return 0; 2165 } 2166 2167 for (size_t i = 0; i < mOutputs.size(); i++) { 2168 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i); 2169 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) { 2170 return mOutputs.keyAt(i); 2171 } 2172 } 2173 2174 return 0; 2175} 2176 2177void AudioPolicyManagerBase::checkA2dpSuspend() 2178{ 2179 if (!mHasA2dp) { 2180 return; 2181 } 2182 audio_io_handle_t a2dpOutput = getA2dpOutput(); 2183 if (a2dpOutput == 0) { 2184 return; 2185 } 2186 2187 // suspend A2DP output if: 2188 // (NOT already suspended) && 2189 // ((SCO device is connected && 2190 // (forced usage for communication || for record is SCO))) || 2191 // (phone state is ringing || in call) 2192 // 2193 // restore A2DP output if: 2194 // (Already suspended) && 2195 // ((SCO device is NOT connected || 2196 // (forced usage NOT for communication && NOT for record is SCO))) && 2197 // (phone state is NOT ringing && NOT in call) 2198 // 2199 if (mA2dpSuspended) { 2200 if (((mScoDeviceAddress == "") || 2201 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) && 2202 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) && 2203 ((mPhoneState != AudioSystem::MODE_IN_CALL) && 2204 (mPhoneState != AudioSystem::MODE_RINGTONE))) { 2205 2206 mpClientInterface->restoreOutput(a2dpOutput); 2207 mA2dpSuspended = false; 2208 } 2209 } else { 2210 if (((mScoDeviceAddress != "") && 2211 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) || 2212 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) || 2213 ((mPhoneState == AudioSystem::MODE_IN_CALL) || 2214 (mPhoneState == AudioSystem::MODE_RINGTONE))) { 2215 2216 mpClientInterface->suspendOutput(a2dpOutput); 2217 mA2dpSuspended = true; 2218 } 2219 } 2220} 2221 2222audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache) 2223{ 2224 audio_devices_t device = AUDIO_DEVICE_NONE; 2225 2226 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 2227 // check the following by order of priority to request a routing change if necessary: 2228 // 1: the strategy enforced audible is active on the output: 2229 // use device for strategy enforced audible 2230 // 2: we are in call or the strategy phone is active on the output: 2231 // use device for strategy phone 2232 // 3: the strategy sonification is active on the output: 2233 // use device for strategy sonification 2234 // 4: the strategy "respectful" sonification is active on the output: 2235 // use device for strategy "respectful" sonification 2236 // 5: the strategy media is active on the output: 2237 // use device for strategy media 2238 // 6: the strategy DTMF is active on the output: 2239 // use device for strategy DTMF 2240 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) { 2241 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache); 2242 } else if (isInCall() || 2243 outputDesc->isStrategyActive(STRATEGY_PHONE)) { 2244 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache); 2245 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) { 2246 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache); 2247 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) { 2248 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache); 2249 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) { 2250 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache); 2251 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) { 2252 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache); 2253 } 2254 2255 ALOGV("getNewDevice() selected device %x", device); 2256 return device; 2257} 2258 2259uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) { 2260 return (uint32_t)getStrategy(stream); 2261} 2262 2263audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) { 2264 audio_devices_t devices; 2265 // By checking the range of stream before calling getStrategy, we avoid 2266 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE 2267 // and then return STRATEGY_MEDIA, but we want to return the empty set. 2268 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) { 2269 devices = AUDIO_DEVICE_NONE; 2270 } else { 2271 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream); 2272 devices = getDeviceForStrategy(strategy, true /*fromCache*/); 2273 } 2274 return devices; 2275} 2276 2277AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy( 2278 AudioSystem::stream_type stream) { 2279 // stream to strategy mapping 2280 switch (stream) { 2281 case AudioSystem::VOICE_CALL: 2282 case AudioSystem::BLUETOOTH_SCO: 2283 return STRATEGY_PHONE; 2284 case AudioSystem::RING: 2285 case AudioSystem::ALARM: 2286 return STRATEGY_SONIFICATION; 2287 case AudioSystem::NOTIFICATION: 2288 return STRATEGY_SONIFICATION_RESPECTFUL; 2289 case AudioSystem::DTMF: 2290 return STRATEGY_DTMF; 2291 default: 2292 ALOGE("unknown stream type"); 2293 case AudioSystem::SYSTEM: 2294 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs 2295 // while key clicks are played produces a poor result 2296 case AudioSystem::TTS: 2297 case AudioSystem::MUSIC: 2298 return STRATEGY_MEDIA; 2299 case AudioSystem::ENFORCED_AUDIBLE: 2300 return STRATEGY_ENFORCED_AUDIBLE; 2301 } 2302} 2303 2304void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) { 2305 switch(stream) { 2306 case AudioSystem::MUSIC: 2307 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL); 2308 updateDevicesAndOutputs(); 2309 break; 2310 default: 2311 break; 2312 } 2313} 2314 2315audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy, 2316 bool fromCache) 2317{ 2318 uint32_t device = AUDIO_DEVICE_NONE; 2319 2320 if (fromCache) { 2321 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x", 2322 strategy, mDeviceForStrategy[strategy]); 2323 return mDeviceForStrategy[strategy]; 2324 } 2325 2326 switch (strategy) { 2327 2328 case STRATEGY_SONIFICATION_RESPECTFUL: 2329 if (isInCall()) { 2330 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/); 2331 } else if (isStreamActiveRemotely(AudioSystem::MUSIC, 2332 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) { 2333 // while media is playing on a remote device, use the the sonification behavior. 2334 // Note that we test this usecase before testing if media is playing because 2335 // the isStreamActive() method only informs about the activity of a stream, not 2336 // if it's for local playback. Note also that we use the same delay between both tests 2337 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/); 2338 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) { 2339 // while media is playing (or has recently played), use the same device 2340 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/); 2341 } else { 2342 // when media is not playing anymore, fall back on the sonification behavior 2343 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/); 2344 } 2345 2346 break; 2347 2348 case STRATEGY_DTMF: 2349 if (!isInCall()) { 2350 // when off call, DTMF strategy follows the same rules as MEDIA strategy 2351 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/); 2352 break; 2353 } 2354 // when in call, DTMF and PHONE strategies follow the same rules 2355 // FALL THROUGH 2356 2357 case STRATEGY_PHONE: 2358 // for phone strategy, we first consider the forced use and then the available devices by order 2359 // of priority 2360 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) { 2361 case AudioSystem::FORCE_BT_SCO: 2362 if (!isInCall() || strategy != STRATEGY_DTMF) { 2363 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT; 2364 if (device) break; 2365 } 2366 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET; 2367 if (device) break; 2368 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO; 2369 if (device) break; 2370 // if SCO device is requested but no SCO device is available, fall back to default case 2371 // FALL THROUGH 2372 2373 default: // FORCE_NONE 2374 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP 2375 if (mHasA2dp && !isInCall() && 2376 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) && 2377 (getA2dpOutput() != 0) && !mA2dpSuspended) { 2378 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP; 2379 if (device) break; 2380 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES; 2381 if (device) break; 2382 } 2383 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE; 2384 if (device) break; 2385 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET; 2386 if (device) break; 2387 if (mPhoneState != AudioSystem::MODE_IN_CALL) { 2388 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY; 2389 if (device) break; 2390 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE; 2391 if (device) break; 2392 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET; 2393 if (device) break; 2394 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL; 2395 if (device) break; 2396 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET; 2397 if (device) break; 2398 } 2399 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE; 2400 if (device) break; 2401 device = mDefaultOutputDevice; 2402 if (device == AUDIO_DEVICE_NONE) { 2403 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE"); 2404 } 2405 break; 2406 2407 case AudioSystem::FORCE_SPEAKER: 2408 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to 2409 // A2DP speaker when forcing to speaker output 2410 if (mHasA2dp && !isInCall() && 2411 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) && 2412 (getA2dpOutput() != 0) && !mA2dpSuspended) { 2413 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER; 2414 if (device) break; 2415 } 2416 if (mPhoneState != AudioSystem::MODE_IN_CALL) { 2417 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY; 2418 if (device) break; 2419 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE; 2420 if (device) break; 2421 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET; 2422 if (device) break; 2423 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL; 2424 if (device) break; 2425 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET; 2426 if (device) break; 2427 } 2428 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER; 2429 if (device) break; 2430 device = mDefaultOutputDevice; 2431 if (device == AUDIO_DEVICE_NONE) { 2432 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER"); 2433 } 2434 break; 2435 } 2436 break; 2437 2438 case STRATEGY_SONIFICATION: 2439 2440 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by 2441 // handleIncallSonification(). 2442 if (isInCall()) { 2443 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/); 2444 break; 2445 } 2446 // FALL THROUGH 2447 2448 case STRATEGY_ENFORCED_AUDIBLE: 2449 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION 2450 // except: 2451 // - when in call where it doesn't default to STRATEGY_PHONE behavior 2452 // - in countries where not enforced in which case it follows STRATEGY_MEDIA 2453 2454 if ((strategy == STRATEGY_SONIFICATION) || 2455 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_SYSTEM_ENFORCED)) { 2456 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER; 2457 if (device == AUDIO_DEVICE_NONE) { 2458 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION"); 2459 } 2460 } 2461 // The second device used for sonification is the same as the device used by media strategy 2462 // FALL THROUGH 2463 2464 case STRATEGY_MEDIA: { 2465 uint32_t device2 = AUDIO_DEVICE_NONE; 2466 if (strategy != STRATEGY_SONIFICATION) { 2467 // no sonification on remote submix (e.g. WFD) 2468 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_REMOTE_SUBMIX; 2469 } 2470 if ((device2 == AUDIO_DEVICE_NONE) && 2471 mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) && 2472 (getA2dpOutput() != 0) && !mA2dpSuspended) { 2473 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP; 2474 if (device2 == AUDIO_DEVICE_NONE) { 2475 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES; 2476 } 2477 if (device2 == AUDIO_DEVICE_NONE) { 2478 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER; 2479 } 2480 } 2481 if (device2 == AUDIO_DEVICE_NONE) { 2482 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE; 2483 } 2484 if (device2 == AUDIO_DEVICE_NONE) { 2485 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET; 2486 } 2487 if (device2 == AUDIO_DEVICE_NONE) { 2488 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY; 2489 } 2490 if (device2 == AUDIO_DEVICE_NONE) { 2491 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE; 2492 } 2493 if (device2 == AUDIO_DEVICE_NONE) { 2494 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET; 2495 } 2496 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) { 2497 // no sonification on aux digital (e.g. HDMI) 2498 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL; 2499 } 2500 if ((device2 == AUDIO_DEVICE_NONE) && 2501 (mForceUse[AudioSystem::FOR_DOCK] == AudioSystem::FORCE_ANALOG_DOCK)) { 2502 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET; 2503 } 2504 if (device2 == AUDIO_DEVICE_NONE) { 2505 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER; 2506 } 2507 2508 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or 2509 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise 2510 device |= device2; 2511 if (device) break; 2512 device = mDefaultOutputDevice; 2513 if (device == AUDIO_DEVICE_NONE) { 2514 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA"); 2515 } 2516 } break; 2517 2518 default: 2519 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy); 2520 break; 2521 } 2522 2523 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device); 2524 return device; 2525} 2526 2527void AudioPolicyManagerBase::updateDevicesAndOutputs() 2528{ 2529 for (int i = 0; i < NUM_STRATEGIES; i++) { 2530 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/); 2531 } 2532 mPreviousOutputs = mOutputs; 2533} 2534 2535uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc, 2536 audio_devices_t prevDevice, 2537 uint32_t delayMs) 2538{ 2539 // mute/unmute strategies using an incompatible device combination 2540 // if muting, wait for the audio in pcm buffer to be drained before proceeding 2541 // if unmuting, unmute only after the specified delay 2542 if (outputDesc->isDuplicated()) { 2543 return 0; 2544 } 2545 2546 uint32_t muteWaitMs = 0; 2547 audio_devices_t device = outputDesc->device(); 2548 bool shouldMute = outputDesc->isActive() && (AudioSystem::popCount(device) >= 2); 2549 // temporary mute output if device selection changes to avoid volume bursts due to 2550 // different per device volumes 2551 bool tempMute = outputDesc->isActive() && (device != prevDevice); 2552 2553 for (size_t i = 0; i < NUM_STRATEGIES; i++) { 2554 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/); 2555 bool mute = shouldMute && (curDevice & device) && (curDevice != device); 2556 bool doMute = false; 2557 2558 if (mute && !outputDesc->mStrategyMutedByDevice[i]) { 2559 doMute = true; 2560 outputDesc->mStrategyMutedByDevice[i] = true; 2561 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){ 2562 doMute = true; 2563 outputDesc->mStrategyMutedByDevice[i] = false; 2564 } 2565 if (doMute || tempMute) { 2566 for (size_t j = 0; j < mOutputs.size(); j++) { 2567 AudioOutputDescriptor *desc = mOutputs.valueAt(j); 2568 // skip output if it does not share any device with current output 2569 if ((desc->supportedDevices() & outputDesc->supportedDevices()) 2570 == AUDIO_DEVICE_NONE) { 2571 continue; 2572 } 2573 audio_io_handle_t curOutput = mOutputs.keyAt(j); 2574 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d", 2575 mute ? "muting" : "unmuting", i, curDevice, curOutput); 2576 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs); 2577 if (desc->isStrategyActive((routing_strategy)i)) { 2578 // do tempMute only for current output 2579 if (tempMute && (desc == outputDesc)) { 2580 setStrategyMute((routing_strategy)i, true, curOutput); 2581 setStrategyMute((routing_strategy)i, false, curOutput, 2582 desc->latency() * 2, device); 2583 } 2584 if ((tempMute && (desc == outputDesc)) || mute) { 2585 if (muteWaitMs < desc->latency()) { 2586 muteWaitMs = desc->latency(); 2587 } 2588 } 2589 } 2590 } 2591 } 2592 } 2593 2594 // FIXME: should not need to double latency if volume could be applied immediately by the 2595 // audioflinger mixer. We must account for the delay between now and the next time 2596 // the audioflinger thread for this output will process a buffer (which corresponds to 2597 // one buffer size, usually 1/2 or 1/4 of the latency). 2598 muteWaitMs *= 2; 2599 // wait for the PCM output buffers to empty before proceeding with the rest of the command 2600 if (muteWaitMs > delayMs) { 2601 muteWaitMs -= delayMs; 2602 usleep(muteWaitMs * 1000); 2603 return muteWaitMs; 2604 } 2605 return 0; 2606} 2607 2608uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output, 2609 audio_devices_t device, 2610 bool force, 2611 int delayMs) 2612{ 2613 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs); 2614 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 2615 AudioParameter param; 2616 uint32_t muteWaitMs; 2617 2618 if (outputDesc->isDuplicated()) { 2619 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs); 2620 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs); 2621 return muteWaitMs; 2622 } 2623 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current 2624 // output profile 2625 if ((device != AUDIO_DEVICE_NONE) && 2626 ((device & outputDesc->mProfile->mSupportedDevices) == 0)) { 2627 return 0; 2628 } 2629 2630 // filter devices according to output selected 2631 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices); 2632 2633 audio_devices_t prevDevice = outputDesc->mDevice; 2634 2635 ALOGV("setOutputDevice() prevDevice %04x", prevDevice); 2636 2637 if (device != AUDIO_DEVICE_NONE) { 2638 outputDesc->mDevice = device; 2639 } 2640 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs); 2641 2642 // Do not change the routing if: 2643 // - the requested device is AUDIO_DEVICE_NONE 2644 // - the requested device is the same as current device and force is not specified. 2645 // Doing this check here allows the caller to call setOutputDevice() without conditions 2646 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) { 2647 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output); 2648 return muteWaitMs; 2649 } 2650 2651 ALOGV("setOutputDevice() changing device"); 2652 // do the routing 2653 param.addInt(String8(AudioParameter::keyRouting), (int)device); 2654 mpClientInterface->setParameters(output, param.toString(), delayMs); 2655 2656 // update stream volumes according to new device 2657 applyStreamVolumes(output, device, delayMs); 2658 2659 return muteWaitMs; 2660} 2661 2662AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device, 2663 uint32_t samplingRate, 2664 uint32_t format, 2665 uint32_t channelMask) 2666{ 2667 // Choose an input profile based on the requested capture parameters: select the first available 2668 // profile supporting all requested parameters. 2669 2670 for (size_t i = 0; i < mHwModules.size(); i++) 2671 { 2672 if (mHwModules[i]->mHandle == 0) { 2673 continue; 2674 } 2675 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) 2676 { 2677 IOProfile *profile = mHwModules[i]->mInputProfiles[j]; 2678 if (profile->isCompatibleProfile(device, samplingRate, format, 2679 channelMask,(audio_output_flags_t)0)) { 2680 return profile; 2681 } 2682 } 2683 } 2684 return NULL; 2685} 2686 2687audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource) 2688{ 2689 uint32_t device = AUDIO_DEVICE_NONE; 2690 2691 switch (inputSource) { 2692 case AUDIO_SOURCE_VOICE_UPLINK: 2693 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) { 2694 device = AUDIO_DEVICE_IN_VOICE_CALL; 2695 break; 2696 } 2697 // FALL THROUGH 2698 2699 case AUDIO_SOURCE_DEFAULT: 2700 case AUDIO_SOURCE_MIC: 2701 case AUDIO_SOURCE_VOICE_RECOGNITION: 2702 case AUDIO_SOURCE_HOTWORD: 2703 case AUDIO_SOURCE_VOICE_COMMUNICATION: 2704 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO && 2705 mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) { 2706 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET; 2707 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) { 2708 device = AUDIO_DEVICE_IN_WIRED_HEADSET; 2709 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) { 2710 device = AUDIO_DEVICE_IN_BUILTIN_MIC; 2711 } 2712 break; 2713 case AUDIO_SOURCE_CAMCORDER: 2714 if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) { 2715 device = AUDIO_DEVICE_IN_BACK_MIC; 2716 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) { 2717 device = AUDIO_DEVICE_IN_BUILTIN_MIC; 2718 } 2719 break; 2720 case AUDIO_SOURCE_VOICE_DOWNLINK: 2721 case AUDIO_SOURCE_VOICE_CALL: 2722 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) { 2723 device = AUDIO_DEVICE_IN_VOICE_CALL; 2724 } 2725 break; 2726 case AUDIO_SOURCE_REMOTE_SUBMIX: 2727 if (mAvailableInputDevices & AUDIO_DEVICE_IN_REMOTE_SUBMIX) { 2728 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX; 2729 } 2730 break; 2731 default: 2732 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource); 2733 break; 2734 } 2735 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device); 2736 return device; 2737} 2738 2739bool AudioPolicyManagerBase::isVirtualInputDevice(audio_devices_t device) 2740{ 2741 if ((device & AUDIO_DEVICE_BIT_IN) != 0) { 2742 device &= ~AUDIO_DEVICE_BIT_IN; 2743 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0)) 2744 return true; 2745 } 2746 return false; 2747} 2748 2749audio_io_handle_t AudioPolicyManagerBase::getActiveInput(bool ignoreVirtualInputs) 2750{ 2751 for (size_t i = 0; i < mInputs.size(); i++) { 2752 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i); 2753 if ((input_descriptor->mRefCount > 0) 2754 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) { 2755 return mInputs.keyAt(i); 2756 } 2757 } 2758 return 0; 2759} 2760 2761 2762audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device) 2763{ 2764 if (device == AUDIO_DEVICE_NONE) { 2765 // this happens when forcing a route update and no track is active on an output. 2766 // In this case the returned category is not important. 2767 device = AUDIO_DEVICE_OUT_SPEAKER; 2768 } else if (AudioSystem::popCount(device) > 1) { 2769 // Multiple device selection is either: 2770 // - speaker + one other device: give priority to speaker in this case. 2771 // - one A2DP device + another device: happens with duplicated output. In this case 2772 // retain the device on the A2DP output as the other must not correspond to an active 2773 // selection if not the speaker. 2774 if (device & AUDIO_DEVICE_OUT_SPEAKER) { 2775 device = AUDIO_DEVICE_OUT_SPEAKER; 2776 } else { 2777 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP); 2778 } 2779 } 2780 2781 ALOGW_IF(AudioSystem::popCount(device) != 1, 2782 "getDeviceForVolume() invalid device combination: %08x", 2783 device); 2784 2785 return device; 2786} 2787 2788AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device) 2789{ 2790 switch(getDeviceForVolume(device)) { 2791 case AUDIO_DEVICE_OUT_EARPIECE: 2792 return DEVICE_CATEGORY_EARPIECE; 2793 case AUDIO_DEVICE_OUT_WIRED_HEADSET: 2794 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE: 2795 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO: 2796 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET: 2797 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP: 2798 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES: 2799 return DEVICE_CATEGORY_HEADSET; 2800 case AUDIO_DEVICE_OUT_SPEAKER: 2801 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT: 2802 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER: 2803 case AUDIO_DEVICE_OUT_AUX_DIGITAL: 2804 case AUDIO_DEVICE_OUT_USB_ACCESSORY: 2805 case AUDIO_DEVICE_OUT_USB_DEVICE: 2806 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX: 2807 default: 2808 return DEVICE_CATEGORY_SPEAKER; 2809 } 2810} 2811 2812float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc, 2813 int indexInUi) 2814{ 2815 device_category deviceCategory = getDeviceCategory(device); 2816 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory]; 2817 2818 // the volume index in the UI is relative to the min and max volume indices for this stream type 2819 int nbSteps = 1 + curve[VOLMAX].mIndex - 2820 curve[VOLMIN].mIndex; 2821 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) / 2822 (streamDesc.mIndexMax - streamDesc.mIndexMin); 2823 2824 // find what part of the curve this index volume belongs to, or if it's out of bounds 2825 int segment = 0; 2826 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds 2827 return 0.0f; 2828 } else if (volIdx < curve[VOLKNEE1].mIndex) { 2829 segment = 0; 2830 } else if (volIdx < curve[VOLKNEE2].mIndex) { 2831 segment = 1; 2832 } else if (volIdx <= curve[VOLMAX].mIndex) { 2833 segment = 2; 2834 } else { // out of bounds 2835 return 1.0f; 2836 } 2837 2838 // linear interpolation in the attenuation table in dB 2839 float decibels = curve[segment].mDBAttenuation + 2840 ((float)(volIdx - curve[segment].mIndex)) * 2841 ( (curve[segment+1].mDBAttenuation - 2842 curve[segment].mDBAttenuation) / 2843 ((float)(curve[segment+1].mIndex - 2844 curve[segment].mIndex)) ); 2845 2846 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 ) 2847 2848 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f", 2849 curve[segment].mIndex, volIdx, 2850 curve[segment+1].mIndex, 2851 curve[segment].mDBAttenuation, 2852 decibels, 2853 curve[segment+1].mDBAttenuation, 2854 amplification); 2855 2856 return amplification; 2857} 2858 2859const AudioPolicyManagerBase::VolumeCurvePoint 2860 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2861 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f} 2862}; 2863 2864const AudioPolicyManagerBase::VolumeCurvePoint 2865 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2866 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f} 2867}; 2868 2869const AudioPolicyManagerBase::VolumeCurvePoint 2870 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2871 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f} 2872}; 2873 2874const AudioPolicyManagerBase::VolumeCurvePoint 2875 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2876 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f} 2877}; 2878 2879const AudioPolicyManagerBase::VolumeCurvePoint 2880 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = { 2881 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f} 2882}; 2883 2884// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks 2885// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets. 2886// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java). 2887// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset. 2888 2889const AudioPolicyManagerBase::VolumeCurvePoint 2890 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2891 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f} 2892}; 2893 2894const AudioPolicyManagerBase::VolumeCurvePoint 2895 AudioPolicyManagerBase::sDefaultSystemVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = { 2896 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f} 2897}; 2898 2899const AudioPolicyManagerBase::VolumeCurvePoint 2900 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2901 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f} 2902}; 2903 2904const AudioPolicyManagerBase::VolumeCurvePoint 2905 AudioPolicyManagerBase::sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2906 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f} 2907}; 2908 2909const AudioPolicyManagerBase::VolumeCurvePoint 2910 AudioPolicyManagerBase::sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2911 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f} 2912}; 2913 2914const AudioPolicyManagerBase::VolumeCurvePoint 2915 *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT] 2916 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = { 2917 { // AUDIO_STREAM_VOICE_CALL 2918 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET 2919 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2920 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE 2921 }, 2922 { // AUDIO_STREAM_SYSTEM 2923 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET 2924 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2925 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE 2926 }, 2927 { // AUDIO_STREAM_RING 2928 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET 2929 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2930 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE 2931 }, 2932 { // AUDIO_STREAM_MUSIC 2933 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET 2934 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2935 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE 2936 }, 2937 { // AUDIO_STREAM_ALARM 2938 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET 2939 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2940 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE 2941 }, 2942 { // AUDIO_STREAM_NOTIFICATION 2943 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET 2944 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2945 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE 2946 }, 2947 { // AUDIO_STREAM_BLUETOOTH_SCO 2948 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET 2949 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2950 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE 2951 }, 2952 { // AUDIO_STREAM_ENFORCED_AUDIBLE 2953 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET 2954 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2955 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE 2956 }, 2957 { // AUDIO_STREAM_DTMF 2958 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET 2959 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2960 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE 2961 }, 2962 { // AUDIO_STREAM_TTS 2963 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET 2964 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2965 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE 2966 }, 2967}; 2968 2969void AudioPolicyManagerBase::initializeVolumeCurves() 2970{ 2971 for (int i = 0; i < AUDIO_STREAM_CNT; i++) { 2972 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) { 2973 mStreams[i].mVolumeCurve[j] = 2974 sVolumeProfiles[i][j]; 2975 } 2976 } 2977 2978 // Check availability of DRC on speaker path: if available, override some of the speaker curves 2979 if (mSpeakerDrcEnabled) { 2980 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] = 2981 sDefaultSystemVolumeCurveDrc; 2982 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] = 2983 sSpeakerSonificationVolumeCurveDrc; 2984 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] = 2985 sSpeakerSonificationVolumeCurveDrc; 2986 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] = 2987 sSpeakerSonificationVolumeCurveDrc; 2988 } 2989} 2990 2991float AudioPolicyManagerBase::computeVolume(int stream, 2992 int index, 2993 audio_io_handle_t output, 2994 audio_devices_t device) 2995{ 2996 float volume = 1.0; 2997 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 2998 StreamDescriptor &streamDesc = mStreams[stream]; 2999 3000 if (device == AUDIO_DEVICE_NONE) { 3001 device = outputDesc->device(); 3002 } 3003 3004 // if volume is not 0 (not muted), force media volume to max on digital output 3005 if (stream == AudioSystem::MUSIC && 3006 index != mStreams[stream].mIndexMin && 3007 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL || 3008 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET || 3009 device == AUDIO_DEVICE_OUT_USB_ACCESSORY || 3010 device == AUDIO_DEVICE_OUT_USB_DEVICE)) { 3011 return 1.0; 3012 } 3013 3014 volume = volIndexToAmpl(device, streamDesc, index); 3015 3016 // if a headset is connected, apply the following rules to ring tones and notifications 3017 // to avoid sound level bursts in user's ears: 3018 // - always attenuate ring tones and notifications volume by 6dB 3019 // - if music is playing, always limit the volume to current music volume, 3020 // with a minimum threshold at -36dB so that notification is always perceived. 3021 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream); 3022 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP | 3023 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES | 3024 AUDIO_DEVICE_OUT_WIRED_HEADSET | 3025 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) && 3026 ((stream_strategy == STRATEGY_SONIFICATION) 3027 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL) 3028 || (stream == AudioSystem::SYSTEM) 3029 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) && 3030 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) && 3031 streamDesc.mCanBeMuted) { 3032 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR; 3033 // when the phone is ringing we must consider that music could have been paused just before 3034 // by the music application and behave as if music was active if the last music track was 3035 // just stopped 3036 if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) || 3037 mLimitRingtoneVolume) { 3038 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/); 3039 float musicVol = computeVolume(AudioSystem::MUSIC, 3040 mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice), 3041 output, 3042 musicDevice); 3043 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? 3044 musicVol : SONIFICATION_HEADSET_VOLUME_MIN; 3045 if (volume > minVol) { 3046 volume = minVol; 3047 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol); 3048 } 3049 } 3050 } 3051 3052 return volume; 3053} 3054 3055status_t AudioPolicyManagerBase::checkAndSetVolume(int stream, 3056 int index, 3057 audio_io_handle_t output, 3058 audio_devices_t device, 3059 int delayMs, 3060 bool force) 3061{ 3062 3063 // do not change actual stream volume if the stream is muted 3064 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) { 3065 ALOGVV("checkAndSetVolume() stream %d muted count %d", 3066 stream, mOutputs.valueFor(output)->mMuteCount[stream]); 3067 return NO_ERROR; 3068 } 3069 3070 // do not change in call volume if bluetooth is connected and vice versa 3071 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) || 3072 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) { 3073 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm", 3074 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]); 3075 return INVALID_OPERATION; 3076 } 3077 3078 float volume = computeVolume(stream, index, output, device); 3079 // We actually change the volume if: 3080 // - the float value returned by computeVolume() changed 3081 // - the force flag is set 3082 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] || 3083 force) { 3084 mOutputs.valueFor(output)->mCurVolume[stream] = volume; 3085 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs); 3086 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is 3087 // enabled 3088 if (stream == AudioSystem::BLUETOOTH_SCO) { 3089 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs); 3090 } 3091 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs); 3092 } 3093 3094 if (stream == AudioSystem::VOICE_CALL || 3095 stream == AudioSystem::BLUETOOTH_SCO) { 3096 float voiceVolume; 3097 // Force voice volume to max for bluetooth SCO as volume is managed by the headset 3098 if (stream == AudioSystem::VOICE_CALL) { 3099 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax; 3100 } else { 3101 voiceVolume = 1.0; 3102 } 3103 3104 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) { 3105 mpClientInterface->setVoiceVolume(voiceVolume, delayMs); 3106 mLastVoiceVolume = voiceVolume; 3107 } 3108 } 3109 3110 return NO_ERROR; 3111} 3112 3113void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output, 3114 audio_devices_t device, 3115 int delayMs, 3116 bool force) 3117{ 3118 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device); 3119 3120 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) { 3121 checkAndSetVolume(stream, 3122 mStreams[stream].getVolumeIndex(device), 3123 output, 3124 device, 3125 delayMs, 3126 force); 3127 } 3128} 3129 3130void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy, 3131 bool on, 3132 audio_io_handle_t output, 3133 int delayMs, 3134 audio_devices_t device) 3135{ 3136 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output); 3137 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) { 3138 if (getStrategy((AudioSystem::stream_type)stream) == strategy) { 3139 setStreamMute(stream, on, output, delayMs, device); 3140 } 3141 } 3142} 3143 3144void AudioPolicyManagerBase::setStreamMute(int stream, 3145 bool on, 3146 audio_io_handle_t output, 3147 int delayMs, 3148 audio_devices_t device) 3149{ 3150 StreamDescriptor &streamDesc = mStreams[stream]; 3151 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 3152 if (device == AUDIO_DEVICE_NONE) { 3153 device = outputDesc->device(); 3154 } 3155 3156 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x", 3157 stream, on, output, outputDesc->mMuteCount[stream], device); 3158 3159 if (on) { 3160 if (outputDesc->mMuteCount[stream] == 0) { 3161 if (streamDesc.mCanBeMuted && 3162 ((stream != AudioSystem::ENFORCED_AUDIBLE) || 3163 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) { 3164 checkAndSetVolume(stream, 0, output, device, delayMs); 3165 } 3166 } 3167 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored 3168 outputDesc->mMuteCount[stream]++; 3169 } else { 3170 if (outputDesc->mMuteCount[stream] == 0) { 3171 ALOGV("setStreamMute() unmuting non muted stream!"); 3172 return; 3173 } 3174 if (--outputDesc->mMuteCount[stream] == 0) { 3175 checkAndSetVolume(stream, 3176 streamDesc.getVolumeIndex(device), 3177 output, 3178 device, 3179 delayMs); 3180 } 3181 } 3182} 3183 3184void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange) 3185{ 3186 // if the stream pertains to sonification strategy and we are in call we must 3187 // mute the stream if it is low visibility. If it is high visibility, we must play a tone 3188 // in the device used for phone strategy and play the tone if the selected device does not 3189 // interfere with the device used for phone strategy 3190 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as 3191 // many times as there are active tracks on the output 3192 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream); 3193 if ((stream_strategy == STRATEGY_SONIFICATION) || 3194 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) { 3195 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput); 3196 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d", 3197 stream, starting, outputDesc->mDevice, stateChange); 3198 if (outputDesc->mRefCount[stream]) { 3199 int muteCount = 1; 3200 if (stateChange) { 3201 muteCount = outputDesc->mRefCount[stream]; 3202 } 3203 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) { 3204 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount); 3205 for (int i = 0; i < muteCount; i++) { 3206 setStreamMute(stream, starting, mPrimaryOutput); 3207 } 3208 } else { 3209 ALOGV("handleIncallSonification() high visibility"); 3210 if (outputDesc->device() & 3211 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) { 3212 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount); 3213 for (int i = 0; i < muteCount; i++) { 3214 setStreamMute(stream, starting, mPrimaryOutput); 3215 } 3216 } 3217 if (starting) { 3218 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL); 3219 } else { 3220 mpClientInterface->stopTone(); 3221 } 3222 } 3223 } 3224 } 3225} 3226 3227bool AudioPolicyManagerBase::isInCall() 3228{ 3229 return isStateInCall(mPhoneState); 3230} 3231 3232bool AudioPolicyManagerBase::isStateInCall(int state) { 3233 return ((state == AudioSystem::MODE_IN_CALL) || 3234 (state == AudioSystem::MODE_IN_COMMUNICATION)); 3235} 3236 3237uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad() 3238{ 3239 return MAX_EFFECTS_CPU_LOAD; 3240} 3241 3242uint32_t AudioPolicyManagerBase::getMaxEffectsMemory() 3243{ 3244 return MAX_EFFECTS_MEMORY; 3245} 3246 3247// --- AudioOutputDescriptor class implementation 3248 3249AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor( 3250 const IOProfile *profile) 3251 : mId(0), mSamplingRate(0), mFormat((audio_format_t)0), 3252 mChannelMask((audio_channel_mask_t)0), mLatency(0), 3253 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), 3254 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0) 3255{ 3256 // clear usage count for all stream types 3257 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) { 3258 mRefCount[i] = 0; 3259 mCurVolume[i] = -1.0; 3260 mMuteCount[i] = 0; 3261 mStopTime[i] = 0; 3262 } 3263 for (int i = 0; i < NUM_STRATEGIES; i++) { 3264 mStrategyMutedByDevice[i] = false; 3265 } 3266 if (profile != NULL) { 3267 mSamplingRate = profile->mSamplingRates[0]; 3268 mFormat = profile->mFormats[0]; 3269 mChannelMask = profile->mChannelMasks[0]; 3270 mFlags = profile->mFlags; 3271 } 3272} 3273 3274audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device() const 3275{ 3276 if (isDuplicated()) { 3277 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice); 3278 } else { 3279 return mDevice; 3280 } 3281} 3282 3283uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency() 3284{ 3285 if (isDuplicated()) { 3286 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency; 3287 } else { 3288 return mLatency; 3289 } 3290} 3291 3292bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith( 3293 const AudioOutputDescriptor *outputDesc) 3294{ 3295 if (isDuplicated()) { 3296 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc); 3297 } else if (outputDesc->isDuplicated()){ 3298 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2); 3299 } else { 3300 return (mProfile->mModule == outputDesc->mProfile->mModule); 3301 } 3302} 3303 3304void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta) 3305{ 3306 // forward usage count change to attached outputs 3307 if (isDuplicated()) { 3308 mOutput1->changeRefCount(stream, delta); 3309 mOutput2->changeRefCount(stream, delta); 3310 } 3311 if ((delta + (int)mRefCount[stream]) < 0) { 3312 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]); 3313 mRefCount[stream] = 0; 3314 return; 3315 } 3316 mRefCount[stream] += delta; 3317 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]); 3318} 3319 3320audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices() 3321{ 3322 if (isDuplicated()) { 3323 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices()); 3324 } else { 3325 return mProfile->mSupportedDevices ; 3326 } 3327} 3328 3329bool AudioPolicyManagerBase::AudioOutputDescriptor::isActive(uint32_t inPastMs) const 3330{ 3331 return isStrategyActive(NUM_STRATEGIES, inPastMs); 3332} 3333 3334bool AudioPolicyManagerBase::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy, 3335 uint32_t inPastMs, 3336 nsecs_t sysTime) const 3337{ 3338 if ((sysTime == 0) && (inPastMs != 0)) { 3339 sysTime = systemTime(); 3340 } 3341 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) { 3342 if (((getStrategy((AudioSystem::stream_type)i) == strategy) || 3343 (NUM_STRATEGIES == strategy)) && 3344 isStreamActive((AudioSystem::stream_type)i, inPastMs, sysTime)) { 3345 return true; 3346 } 3347 } 3348 return false; 3349} 3350 3351bool AudioPolicyManagerBase::AudioOutputDescriptor::isStreamActive(AudioSystem::stream_type stream, 3352 uint32_t inPastMs, 3353 nsecs_t sysTime) const 3354{ 3355 if (mRefCount[stream] != 0) { 3356 return true; 3357 } 3358 if (inPastMs == 0) { 3359 return false; 3360 } 3361 if (sysTime == 0) { 3362 sysTime = systemTime(); 3363 } 3364 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) { 3365 return true; 3366 } 3367 return false; 3368} 3369 3370 3371status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd) 3372{ 3373 const size_t SIZE = 256; 3374 char buffer[SIZE]; 3375 String8 result; 3376 3377 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate); 3378 result.append(buffer); 3379 snprintf(buffer, SIZE, " Format: %08x\n", mFormat); 3380 result.append(buffer); 3381 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask); 3382 result.append(buffer); 3383 snprintf(buffer, SIZE, " Latency: %d\n", mLatency); 3384 result.append(buffer); 3385 snprintf(buffer, SIZE, " Flags %08x\n", mFlags); 3386 result.append(buffer); 3387 snprintf(buffer, SIZE, " Devices %08x\n", device()); 3388 result.append(buffer); 3389 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n"); 3390 result.append(buffer); 3391 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) { 3392 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]); 3393 result.append(buffer); 3394 } 3395 write(fd, result.string(), result.size()); 3396 3397 return NO_ERROR; 3398} 3399 3400// --- AudioInputDescriptor class implementation 3401 3402AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile) 3403 : mSamplingRate(0), mFormat((audio_format_t)0), mChannelMask((audio_channel_mask_t)0), 3404 mDevice(AUDIO_DEVICE_NONE), mRefCount(0), 3405 mInputSource(0), mProfile(profile) 3406{ 3407} 3408 3409status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd) 3410{ 3411 const size_t SIZE = 256; 3412 char buffer[SIZE]; 3413 String8 result; 3414 3415 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate); 3416 result.append(buffer); 3417 snprintf(buffer, SIZE, " Format: %d\n", mFormat); 3418 result.append(buffer); 3419 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask); 3420 result.append(buffer); 3421 snprintf(buffer, SIZE, " Devices %08x\n", mDevice); 3422 result.append(buffer); 3423 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount); 3424 result.append(buffer); 3425 write(fd, result.string(), result.size()); 3426 3427 return NO_ERROR; 3428} 3429 3430// --- StreamDescriptor class implementation 3431 3432AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor() 3433 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true) 3434{ 3435 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0); 3436} 3437 3438int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device) 3439{ 3440 device = AudioPolicyManagerBase::getDeviceForVolume(device); 3441 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT 3442 if (mIndexCur.indexOfKey(device) < 0) { 3443 device = AUDIO_DEVICE_OUT_DEFAULT; 3444 } 3445 return mIndexCur.valueFor(device); 3446} 3447 3448void AudioPolicyManagerBase::StreamDescriptor::dump(int fd) 3449{ 3450 const size_t SIZE = 256; 3451 char buffer[SIZE]; 3452 String8 result; 3453 3454 snprintf(buffer, SIZE, "%s %02d %02d ", 3455 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax); 3456 result.append(buffer); 3457 for (size_t i = 0; i < mIndexCur.size(); i++) { 3458 snprintf(buffer, SIZE, "%04x : %02d, ", 3459 mIndexCur.keyAt(i), 3460 mIndexCur.valueAt(i)); 3461 result.append(buffer); 3462 } 3463 result.append("\n"); 3464 3465 write(fd, result.string(), result.size()); 3466} 3467 3468// --- EffectDescriptor class implementation 3469 3470status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd) 3471{ 3472 const size_t SIZE = 256; 3473 char buffer[SIZE]; 3474 String8 result; 3475 3476 snprintf(buffer, SIZE, " I/O: %d\n", mIo); 3477 result.append(buffer); 3478 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy); 3479 result.append(buffer); 3480 snprintf(buffer, SIZE, " Session: %d\n", mSession); 3481 result.append(buffer); 3482 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name); 3483 result.append(buffer); 3484 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled"); 3485 result.append(buffer); 3486 write(fd, result.string(), result.size()); 3487 3488 return NO_ERROR; 3489} 3490 3491// --- IOProfile class implementation 3492 3493AudioPolicyManagerBase::HwModule::HwModule(const char *name) 3494 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0) 3495{ 3496} 3497 3498AudioPolicyManagerBase::HwModule::~HwModule() 3499{ 3500 for (size_t i = 0; i < mOutputProfiles.size(); i++) { 3501 delete mOutputProfiles[i]; 3502 } 3503 for (size_t i = 0; i < mInputProfiles.size(); i++) { 3504 delete mInputProfiles[i]; 3505 } 3506 free((void *)mName); 3507} 3508 3509void AudioPolicyManagerBase::HwModule::dump(int fd) 3510{ 3511 const size_t SIZE = 256; 3512 char buffer[SIZE]; 3513 String8 result; 3514 3515 snprintf(buffer, SIZE, " - name: %s\n", mName); 3516 result.append(buffer); 3517 snprintf(buffer, SIZE, " - handle: %d\n", mHandle); 3518 result.append(buffer); 3519 write(fd, result.string(), result.size()); 3520 if (mOutputProfiles.size()) { 3521 write(fd, " - outputs:\n", sizeof(" - outputs:\n")); 3522 for (size_t i = 0; i < mOutputProfiles.size(); i++) { 3523 snprintf(buffer, SIZE, " output %d:\n", i); 3524 write(fd, buffer, strlen(buffer)); 3525 mOutputProfiles[i]->dump(fd); 3526 } 3527 } 3528 if (mInputProfiles.size()) { 3529 write(fd, " - inputs:\n", sizeof(" - inputs:\n")); 3530 for (size_t i = 0; i < mInputProfiles.size(); i++) { 3531 snprintf(buffer, SIZE, " input %d:\n", i); 3532 write(fd, buffer, strlen(buffer)); 3533 mInputProfiles[i]->dump(fd); 3534 } 3535 } 3536} 3537 3538AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module) 3539 : mFlags((audio_output_flags_t)0), mModule(module) 3540{ 3541} 3542 3543AudioPolicyManagerBase::IOProfile::~IOProfile() 3544{ 3545} 3546 3547// checks if the IO profile is compatible with specified parameters. 3548// Sampling rate, format and channel mask must be specified in order to 3549// get a valid a match 3550bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device, 3551 uint32_t samplingRate, 3552 uint32_t format, 3553 uint32_t channelMask, 3554 audio_output_flags_t flags) const 3555{ 3556 if (samplingRate == 0 || format == 0 || channelMask == 0) { 3557 return false; 3558 } 3559 3560 if ((mSupportedDevices & device) != device) { 3561 return false; 3562 } 3563 if ((mFlags & flags) != flags) { 3564 return false; 3565 } 3566 size_t i; 3567 for (i = 0; i < mSamplingRates.size(); i++) 3568 { 3569 if (mSamplingRates[i] == samplingRate) { 3570 break; 3571 } 3572 } 3573 if (i == mSamplingRates.size()) { 3574 return false; 3575 } 3576 for (i = 0; i < mFormats.size(); i++) 3577 { 3578 if (mFormats[i] == format) { 3579 break; 3580 } 3581 } 3582 if (i == mFormats.size()) { 3583 return false; 3584 } 3585 for (i = 0; i < mChannelMasks.size(); i++) 3586 { 3587 if (mChannelMasks[i] == channelMask) { 3588 break; 3589 } 3590 } 3591 if (i == mChannelMasks.size()) { 3592 return false; 3593 } 3594 return true; 3595} 3596 3597void AudioPolicyManagerBase::IOProfile::dump(int fd) 3598{ 3599 const size_t SIZE = 256; 3600 char buffer[SIZE]; 3601 String8 result; 3602 3603 snprintf(buffer, SIZE, " - sampling rates: "); 3604 result.append(buffer); 3605 for (size_t i = 0; i < mSamplingRates.size(); i++) { 3606 snprintf(buffer, SIZE, "%d", mSamplingRates[i]); 3607 result.append(buffer); 3608 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", "); 3609 } 3610 3611 snprintf(buffer, SIZE, " - channel masks: "); 3612 result.append(buffer); 3613 for (size_t i = 0; i < mChannelMasks.size(); i++) { 3614 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]); 3615 result.append(buffer); 3616 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", "); 3617 } 3618 3619 snprintf(buffer, SIZE, " - formats: "); 3620 result.append(buffer); 3621 for (size_t i = 0; i < mFormats.size(); i++) { 3622 snprintf(buffer, SIZE, "0x%08x", mFormats[i]); 3623 result.append(buffer); 3624 result.append(i == (mFormats.size() - 1) ? "\n" : ", "); 3625 } 3626 3627 snprintf(buffer, SIZE, " - devices: 0x%04x\n", mSupportedDevices); 3628 result.append(buffer); 3629 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags); 3630 result.append(buffer); 3631 3632 write(fd, result.string(), result.size()); 3633} 3634 3635// --- audio_policy.conf file parsing 3636 3637struct StringToEnum { 3638 const char *name; 3639 uint32_t value; 3640}; 3641 3642#define STRING_TO_ENUM(string) { #string, string } 3643#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) 3644 3645const struct StringToEnum sDeviceNameToEnumTable[] = { 3646 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE), 3647 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER), 3648 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET), 3649 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE), 3650 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO), 3651 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP), 3652 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL), 3653 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET), 3654 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET), 3655 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE), 3656 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY), 3657 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB), 3658 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX), 3659 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC), 3660 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET), 3661 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET), 3662 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL), 3663 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL), 3664 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC), 3665 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX), 3666 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET), 3667 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET), 3668 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY), 3669}; 3670 3671const struct StringToEnum sFlagNameToEnumTable[] = { 3672 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT), 3673 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY), 3674 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST), 3675 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER), 3676 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD), 3677 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING), 3678}; 3679 3680const struct StringToEnum sFormatNameToEnumTable[] = { 3681 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT), 3682 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT), 3683 STRING_TO_ENUM(AUDIO_FORMAT_MP3), 3684 STRING_TO_ENUM(AUDIO_FORMAT_AAC), 3685 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS), 3686}; 3687 3688const struct StringToEnum sOutChannelsNameToEnumTable[] = { 3689 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO), 3690 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO), 3691 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1), 3692 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1), 3693}; 3694 3695const struct StringToEnum sInChannelsNameToEnumTable[] = { 3696 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO), 3697 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO), 3698 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK), 3699}; 3700 3701 3702uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table, 3703 size_t size, 3704 const char *name) 3705{ 3706 for (size_t i = 0; i < size; i++) { 3707 if (strcmp(table[i].name, name) == 0) { 3708 ALOGV("stringToEnum() found %s", table[i].name); 3709 return table[i].value; 3710 } 3711 } 3712 return 0; 3713} 3714 3715bool AudioPolicyManagerBase::stringToBool(const char *value) 3716{ 3717 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0)); 3718} 3719 3720audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name) 3721{ 3722 uint32_t flag = 0; 3723 3724 // it is OK to cast name to non const here as we are not going to use it after 3725 // strtok() modifies it 3726 char *flagName = strtok(name, "|"); 3727 while (flagName != NULL) { 3728 if (strlen(flagName) != 0) { 3729 flag |= stringToEnum(sFlagNameToEnumTable, 3730 ARRAY_SIZE(sFlagNameToEnumTable), 3731 flagName); 3732 } 3733 flagName = strtok(NULL, "|"); 3734 } 3735 //force direct flag if offload flag is set: offloading implies a direct output stream 3736 // and all common behaviors are driven by checking only the direct flag 3737 // this should normally be set appropriately in the policy configuration file 3738 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) { 3739 flag |= AUDIO_OUTPUT_FLAG_DIRECT; 3740 } 3741 3742 return (audio_output_flags_t)flag; 3743} 3744 3745audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name) 3746{ 3747 uint32_t device = 0; 3748 3749 char *devName = strtok(name, "|"); 3750 while (devName != NULL) { 3751 if (strlen(devName) != 0) { 3752 device |= stringToEnum(sDeviceNameToEnumTable, 3753 ARRAY_SIZE(sDeviceNameToEnumTable), 3754 devName); 3755 } 3756 devName = strtok(NULL, "|"); 3757 } 3758 return device; 3759} 3760 3761void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile) 3762{ 3763 char *str = strtok(name, "|"); 3764 3765 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling 3766 // rates should be read from the output stream after it is opened for the first time 3767 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) { 3768 profile->mSamplingRates.add(0); 3769 return; 3770 } 3771 3772 while (str != NULL) { 3773 uint32_t rate = atoi(str); 3774 if (rate != 0) { 3775 ALOGV("loadSamplingRates() adding rate %d", rate); 3776 profile->mSamplingRates.add(rate); 3777 } 3778 str = strtok(NULL, "|"); 3779 } 3780 return; 3781} 3782 3783void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile) 3784{ 3785 char *str = strtok(name, "|"); 3786 3787 // by convention, "0' in the first entry in mFormats indicates the supported formats 3788 // should be read from the output stream after it is opened for the first time 3789 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) { 3790 profile->mFormats.add((audio_format_t)0); 3791 return; 3792 } 3793 3794 while (str != NULL) { 3795 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable, 3796 ARRAY_SIZE(sFormatNameToEnumTable), 3797 str); 3798 if (format != 0) { 3799 profile->mFormats.add(format); 3800 } 3801 str = strtok(NULL, "|"); 3802 } 3803 return; 3804} 3805 3806void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile) 3807{ 3808 const char *str = strtok(name, "|"); 3809 3810 ALOGV("loadInChannels() %s", name); 3811 3812 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) { 3813 profile->mChannelMasks.add((audio_channel_mask_t)0); 3814 return; 3815 } 3816 3817 while (str != NULL) { 3818 audio_channel_mask_t channelMask = 3819 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable, 3820 ARRAY_SIZE(sInChannelsNameToEnumTable), 3821 str); 3822 if (channelMask != 0) { 3823 ALOGV("loadInChannels() adding channelMask %04x", channelMask); 3824 profile->mChannelMasks.add(channelMask); 3825 } 3826 str = strtok(NULL, "|"); 3827 } 3828 return; 3829} 3830 3831void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile) 3832{ 3833 const char *str = strtok(name, "|"); 3834 3835 ALOGV("loadOutChannels() %s", name); 3836 3837 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel 3838 // masks should be read from the output stream after it is opened for the first time 3839 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) { 3840 profile->mChannelMasks.add((audio_channel_mask_t)0); 3841 return; 3842 } 3843 3844 while (str != NULL) { 3845 audio_channel_mask_t channelMask = 3846 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable, 3847 ARRAY_SIZE(sOutChannelsNameToEnumTable), 3848 str); 3849 if (channelMask != 0) { 3850 profile->mChannelMasks.add(channelMask); 3851 } 3852 str = strtok(NULL, "|"); 3853 } 3854 return; 3855} 3856 3857status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module) 3858{ 3859 cnode *node = root->first_child; 3860 3861 IOProfile *profile = new IOProfile(module); 3862 3863 while (node) { 3864 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) { 3865 loadSamplingRates((char *)node->value, profile); 3866 } else if (strcmp(node->name, FORMATS_TAG) == 0) { 3867 loadFormats((char *)node->value, profile); 3868 } else if (strcmp(node->name, CHANNELS_TAG) == 0) { 3869 loadInChannels((char *)node->value, profile); 3870 } else if (strcmp(node->name, DEVICES_TAG) == 0) { 3871 profile->mSupportedDevices = parseDeviceNames((char *)node->value); 3872 } 3873 node = node->next; 3874 } 3875 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE, 3876 "loadInput() invalid supported devices"); 3877 ALOGW_IF(profile->mChannelMasks.size() == 0, 3878 "loadInput() invalid supported channel masks"); 3879 ALOGW_IF(profile->mSamplingRates.size() == 0, 3880 "loadInput() invalid supported sampling rates"); 3881 ALOGW_IF(profile->mFormats.size() == 0, 3882 "loadInput() invalid supported formats"); 3883 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) && 3884 (profile->mChannelMasks.size() != 0) && 3885 (profile->mSamplingRates.size() != 0) && 3886 (profile->mFormats.size() != 0)) { 3887 3888 ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices); 3889 3890 module->mInputProfiles.add(profile); 3891 return NO_ERROR; 3892 } else { 3893 delete profile; 3894 return BAD_VALUE; 3895 } 3896} 3897 3898status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module) 3899{ 3900 cnode *node = root->first_child; 3901 3902 IOProfile *profile = new IOProfile(module); 3903 3904 while (node) { 3905 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) { 3906 loadSamplingRates((char *)node->value, profile); 3907 } else if (strcmp(node->name, FORMATS_TAG) == 0) { 3908 loadFormats((char *)node->value, profile); 3909 } else if (strcmp(node->name, CHANNELS_TAG) == 0) { 3910 loadOutChannels((char *)node->value, profile); 3911 } else if (strcmp(node->name, DEVICES_TAG) == 0) { 3912 profile->mSupportedDevices = parseDeviceNames((char *)node->value); 3913 } else if (strcmp(node->name, FLAGS_TAG) == 0) { 3914 profile->mFlags = parseFlagNames((char *)node->value); 3915 } 3916 node = node->next; 3917 } 3918 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE, 3919 "loadOutput() invalid supported devices"); 3920 ALOGW_IF(profile->mChannelMasks.size() == 0, 3921 "loadOutput() invalid supported channel masks"); 3922 ALOGW_IF(profile->mSamplingRates.size() == 0, 3923 "loadOutput() invalid supported sampling rates"); 3924 ALOGW_IF(profile->mFormats.size() == 0, 3925 "loadOutput() invalid supported formats"); 3926 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) && 3927 (profile->mChannelMasks.size() != 0) && 3928 (profile->mSamplingRates.size() != 0) && 3929 (profile->mFormats.size() != 0)) { 3930 3931 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x", 3932 profile->mSupportedDevices, profile->mFlags); 3933 3934 module->mOutputProfiles.add(profile); 3935 return NO_ERROR; 3936 } else { 3937 delete profile; 3938 return BAD_VALUE; 3939 } 3940} 3941 3942void AudioPolicyManagerBase::loadHwModule(cnode *root) 3943{ 3944 cnode *node = config_find(root, OUTPUTS_TAG); 3945 status_t status = NAME_NOT_FOUND; 3946 3947 HwModule *module = new HwModule(root->name); 3948 3949 if (node != NULL) { 3950 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) { 3951 mHasA2dp = true; 3952 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) { 3953 mHasUsb = true; 3954 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) { 3955 mHasRemoteSubmix = true; 3956 } 3957 3958 node = node->first_child; 3959 while (node) { 3960 ALOGV("loadHwModule() loading output %s", node->name); 3961 status_t tmpStatus = loadOutput(node, module); 3962 if (status == NAME_NOT_FOUND || status == NO_ERROR) { 3963 status = tmpStatus; 3964 } 3965 node = node->next; 3966 } 3967 } 3968 node = config_find(root, INPUTS_TAG); 3969 if (node != NULL) { 3970 node = node->first_child; 3971 while (node) { 3972 ALOGV("loadHwModule() loading input %s", node->name); 3973 status_t tmpStatus = loadInput(node, module); 3974 if (status == NAME_NOT_FOUND || status == NO_ERROR) { 3975 status = tmpStatus; 3976 } 3977 node = node->next; 3978 } 3979 } 3980 if (status == NO_ERROR) { 3981 mHwModules.add(module); 3982 } else { 3983 delete module; 3984 } 3985} 3986 3987void AudioPolicyManagerBase::loadHwModules(cnode *root) 3988{ 3989 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG); 3990 if (node == NULL) { 3991 return; 3992 } 3993 3994 node = node->first_child; 3995 while (node) { 3996 ALOGV("loadHwModules() loading module %s", node->name); 3997 loadHwModule(node); 3998 node = node->next; 3999 } 4000} 4001 4002void AudioPolicyManagerBase::loadGlobalConfig(cnode *root) 4003{ 4004 cnode *node = config_find(root, GLOBAL_CONFIG_TAG); 4005 if (node == NULL) { 4006 return; 4007 } 4008 node = node->first_child; 4009 while (node) { 4010 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) { 4011 mAttachedOutputDevices = parseDeviceNames((char *)node->value); 4012 ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE, 4013 "loadGlobalConfig() no attached output devices"); 4014 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices); 4015 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) { 4016 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable, 4017 ARRAY_SIZE(sDeviceNameToEnumTable), 4018 (char *)node->value); 4019 ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE, 4020 "loadGlobalConfig() default device not specified"); 4021 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice); 4022 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) { 4023 mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN; 4024 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices); 4025 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) { 4026 mSpeakerDrcEnabled = stringToBool((char *)node->value); 4027 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled); 4028 } 4029 node = node->next; 4030 } 4031} 4032 4033status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path) 4034{ 4035 cnode *root; 4036 char *data; 4037 4038 data = (char *)load_file(path, NULL); 4039 if (data == NULL) { 4040 return -ENODEV; 4041 } 4042 root = config_node("", ""); 4043 config_load(root, data); 4044 4045 loadGlobalConfig(root); 4046 loadHwModules(root); 4047 4048 config_free(root); 4049 free(root); 4050 free(data); 4051 4052 ALOGI("loadAudioPolicyConfig() loaded %s\n", path); 4053 4054 return NO_ERROR; 4055} 4056 4057void AudioPolicyManagerBase::defaultAudioPolicyConfig(void) 4058{ 4059 HwModule *module; 4060 IOProfile *profile; 4061 4062 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER; 4063 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER; 4064 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC & ~AUDIO_DEVICE_BIT_IN; 4065 4066 module = new HwModule("primary"); 4067 4068 profile = new IOProfile(module); 4069 profile->mSamplingRates.add(44100); 4070 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT); 4071 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO); 4072 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER; 4073 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY; 4074 module->mOutputProfiles.add(profile); 4075 4076 profile = new IOProfile(module); 4077 profile->mSamplingRates.add(8000); 4078 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT); 4079 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO); 4080 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC; 4081 module->mInputProfiles.add(profile); 4082 4083 mHwModules.add(module); 4084} 4085 4086}; // namespace android 4087