AudioPolicyManagerBase.cpp revision 000bb51ca507645f3aa4ccfcbbb8859e8d539629
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{ 1537 mpClientInterface = clientInterface; 1538 1539 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) { 1540 mForceUse[i] = AudioSystem::FORCE_NONE; 1541 } 1542 1543 initializeVolumeCurves(); 1544 1545 mA2dpDeviceAddress = String8(""); 1546 mScoDeviceAddress = String8(""); 1547 mUsbCardAndDevice = String8(""); 1548 1549 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) { 1550 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) { 1551 ALOGE("could not load audio policy configuration file, setting defaults"); 1552 defaultAudioPolicyConfig(); 1553 } 1554 } 1555 1556 // open all output streams needed to access attached devices 1557 for (size_t i = 0; i < mHwModules.size(); i++) { 1558 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName); 1559 if (mHwModules[i]->mHandle == 0) { 1560 ALOGW("could not open HW module %s", mHwModules[i]->mName); 1561 continue; 1562 } 1563 // open all output streams needed to access attached devices 1564 // except for direct output streams that are only opened when they are actually 1565 // required by an app. 1566 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 1567 { 1568 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j]; 1569 1570 if ((outProfile->mSupportedDevices & mAttachedOutputDevices) && 1571 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) { 1572 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile); 1573 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice & 1574 outProfile->mSupportedDevices); 1575 audio_io_handle_t output = mpClientInterface->openOutput( 1576 outProfile->mModule->mHandle, 1577 &outputDesc->mDevice, 1578 &outputDesc->mSamplingRate, 1579 &outputDesc->mFormat, 1580 &outputDesc->mChannelMask, 1581 &outputDesc->mLatency, 1582 outputDesc->mFlags); 1583 if (output == 0) { 1584 delete outputDesc; 1585 } else { 1586 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | 1587 (outProfile->mSupportedDevices & mAttachedOutputDevices)); 1588 if (mPrimaryOutput == 0 && 1589 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) { 1590 mPrimaryOutput = output; 1591 } 1592 addOutput(output, outputDesc); 1593 setOutputDevice(output, 1594 (audio_devices_t)(mDefaultOutputDevice & 1595 outProfile->mSupportedDevices), 1596 true); 1597 } 1598 } 1599 } 1600 } 1601 1602 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices), 1603 "Not output found for attached devices %08x", 1604 (mAttachedOutputDevices & ~mAvailableOutputDevices)); 1605 1606 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output"); 1607 1608 updateDevicesAndOutputs(); 1609 1610#ifdef AUDIO_POLICY_TEST 1611 if (mPrimaryOutput != 0) { 1612 AudioParameter outputCmd = AudioParameter(); 1613 outputCmd.addInt(String8("set_id"), 0); 1614 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString()); 1615 1616 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER; 1617 mTestSamplingRate = 44100; 1618 mTestFormat = AudioSystem::PCM_16_BIT; 1619 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO; 1620 mTestLatencyMs = 0; 1621 mCurOutput = 0; 1622 mDirectOutput = false; 1623 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) { 1624 mTestOutputs[i] = 0; 1625 } 1626 1627 const size_t SIZE = 256; 1628 char buffer[SIZE]; 1629 snprintf(buffer, SIZE, "AudioPolicyManagerTest"); 1630 run(buffer, ANDROID_PRIORITY_AUDIO); 1631 } 1632#endif //AUDIO_POLICY_TEST 1633} 1634 1635AudioPolicyManagerBase::~AudioPolicyManagerBase() 1636{ 1637#ifdef AUDIO_POLICY_TEST 1638 exit(); 1639#endif //AUDIO_POLICY_TEST 1640 for (size_t i = 0; i < mOutputs.size(); i++) { 1641 mpClientInterface->closeOutput(mOutputs.keyAt(i)); 1642 delete mOutputs.valueAt(i); 1643 } 1644 for (size_t i = 0; i < mInputs.size(); i++) { 1645 mpClientInterface->closeInput(mInputs.keyAt(i)); 1646 delete mInputs.valueAt(i); 1647 } 1648 for (size_t i = 0; i < mHwModules.size(); i++) { 1649 delete mHwModules[i]; 1650 } 1651} 1652 1653status_t AudioPolicyManagerBase::initCheck() 1654{ 1655 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR; 1656} 1657 1658#ifdef AUDIO_POLICY_TEST 1659bool AudioPolicyManagerBase::threadLoop() 1660{ 1661 ALOGV("entering threadLoop()"); 1662 while (!exitPending()) 1663 { 1664 String8 command; 1665 int valueInt; 1666 String8 value; 1667 1668 Mutex::Autolock _l(mLock); 1669 mWaitWorkCV.waitRelative(mLock, milliseconds(50)); 1670 1671 command = mpClientInterface->getParameters(0, String8("test_cmd_policy")); 1672 AudioParameter param = AudioParameter(command); 1673 1674 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR && 1675 valueInt != 0) { 1676 ALOGV("Test command %s received", command.string()); 1677 String8 target; 1678 if (param.get(String8("target"), target) != NO_ERROR) { 1679 target = "Manager"; 1680 } 1681 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) { 1682 param.remove(String8("test_cmd_policy_output")); 1683 mCurOutput = valueInt; 1684 } 1685 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) { 1686 param.remove(String8("test_cmd_policy_direct")); 1687 if (value == "false") { 1688 mDirectOutput = false; 1689 } else if (value == "true") { 1690 mDirectOutput = true; 1691 } 1692 } 1693 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) { 1694 param.remove(String8("test_cmd_policy_input")); 1695 mTestInput = valueInt; 1696 } 1697 1698 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) { 1699 param.remove(String8("test_cmd_policy_format")); 1700 int format = AudioSystem::INVALID_FORMAT; 1701 if (value == "PCM 16 bits") { 1702 format = AudioSystem::PCM_16_BIT; 1703 } else if (value == "PCM 8 bits") { 1704 format = AudioSystem::PCM_8_BIT; 1705 } else if (value == "Compressed MP3") { 1706 format = AudioSystem::MP3; 1707 } 1708 if (format != AudioSystem::INVALID_FORMAT) { 1709 if (target == "Manager") { 1710 mTestFormat = format; 1711 } else if (mTestOutputs[mCurOutput] != 0) { 1712 AudioParameter outputParam = AudioParameter(); 1713 outputParam.addInt(String8("format"), format); 1714 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 1715 } 1716 } 1717 } 1718 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) { 1719 param.remove(String8("test_cmd_policy_channels")); 1720 int channels = 0; 1721 1722 if (value == "Channels Stereo") { 1723 channels = AudioSystem::CHANNEL_OUT_STEREO; 1724 } else if (value == "Channels Mono") { 1725 channels = AudioSystem::CHANNEL_OUT_MONO; 1726 } 1727 if (channels != 0) { 1728 if (target == "Manager") { 1729 mTestChannels = channels; 1730 } else if (mTestOutputs[mCurOutput] != 0) { 1731 AudioParameter outputParam = AudioParameter(); 1732 outputParam.addInt(String8("channels"), channels); 1733 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 1734 } 1735 } 1736 } 1737 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) { 1738 param.remove(String8("test_cmd_policy_sampleRate")); 1739 if (valueInt >= 0 && valueInt <= 96000) { 1740 int samplingRate = valueInt; 1741 if (target == "Manager") { 1742 mTestSamplingRate = samplingRate; 1743 } else if (mTestOutputs[mCurOutput] != 0) { 1744 AudioParameter outputParam = AudioParameter(); 1745 outputParam.addInt(String8("sampling_rate"), samplingRate); 1746 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 1747 } 1748 } 1749 } 1750 1751 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) { 1752 param.remove(String8("test_cmd_policy_reopen")); 1753 1754 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput); 1755 mpClientInterface->closeOutput(mPrimaryOutput); 1756 1757 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle; 1758 1759 delete mOutputs.valueFor(mPrimaryOutput); 1760 mOutputs.removeItem(mPrimaryOutput); 1761 1762 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL); 1763 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER; 1764 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle, 1765 &outputDesc->mDevice, 1766 &outputDesc->mSamplingRate, 1767 &outputDesc->mFormat, 1768 &outputDesc->mChannelMask, 1769 &outputDesc->mLatency, 1770 outputDesc->mFlags); 1771 if (mPrimaryOutput == 0) { 1772 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d", 1773 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask); 1774 } else { 1775 AudioParameter outputCmd = AudioParameter(); 1776 outputCmd.addInt(String8("set_id"), 0); 1777 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString()); 1778 addOutput(mPrimaryOutput, outputDesc); 1779 } 1780 } 1781 1782 1783 mpClientInterface->setParameters(0, String8("test_cmd_policy=")); 1784 } 1785 } 1786 return false; 1787} 1788 1789void AudioPolicyManagerBase::exit() 1790{ 1791 { 1792 AutoMutex _l(mLock); 1793 requestExit(); 1794 mWaitWorkCV.signal(); 1795 } 1796 requestExitAndWait(); 1797} 1798 1799int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output) 1800{ 1801 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) { 1802 if (output == mTestOutputs[i]) return i; 1803 } 1804 return 0; 1805} 1806#endif //AUDIO_POLICY_TEST 1807 1808// --- 1809 1810void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc) 1811{ 1812 outputDesc->mId = id; 1813 mOutputs.add(id, outputDesc); 1814} 1815 1816 1817status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device, 1818 AudioSystem::device_connection_state state, 1819 SortedVector<audio_io_handle_t>& outputs) 1820{ 1821 AudioOutputDescriptor *desc; 1822 1823 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) { 1824 // first list already open outputs that can be routed to this device 1825 for (size_t i = 0; i < mOutputs.size(); i++) { 1826 desc = mOutputs.valueAt(i); 1827 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) { 1828 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i)); 1829 outputs.add(mOutputs.keyAt(i)); 1830 } 1831 } 1832 // then look for output profiles that can be routed to this device 1833 SortedVector<IOProfile *> profiles; 1834 for (size_t i = 0; i < mHwModules.size(); i++) 1835 { 1836 if (mHwModules[i]->mHandle == 0) { 1837 continue; 1838 } 1839 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 1840 { 1841 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) { 1842 ALOGV("checkOutputsForDevice(): adding profile %d from module %d", j, i); 1843 profiles.add(mHwModules[i]->mOutputProfiles[j]); 1844 } 1845 } 1846 } 1847 1848 if (profiles.isEmpty() && outputs.isEmpty()) { 1849 ALOGW("checkOutputsForDevice(): No output available for device %04x", device); 1850 return BAD_VALUE; 1851 } 1852 1853 // open outputs for matching profiles if needed. Direct outputs are also opened to 1854 // query for dynamic parameters and will be closed later by setDeviceConnectionState() 1855 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) { 1856 IOProfile *profile = profiles[profile_index]; 1857 1858 // nothing to do if one output is already opened for this profile 1859 size_t j; 1860 for (j = 0; j < mOutputs.size(); j++) { 1861 desc = mOutputs.valueAt(j); 1862 if (!desc->isDuplicated() && desc->mProfile == profile) { 1863 break; 1864 } 1865 } 1866 if (j != mOutputs.size()) { 1867 continue; 1868 } 1869 1870 ALOGV("opening output for device %08x", device); 1871 desc = new AudioOutputDescriptor(profile); 1872 desc->mDevice = device; 1873 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER; 1874 offloadInfo.sample_rate = desc->mSamplingRate; 1875 offloadInfo.format = desc->mFormat; 1876 offloadInfo.channel_mask = desc->mChannelMask; 1877 1878 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle, 1879 &desc->mDevice, 1880 &desc->mSamplingRate, 1881 &desc->mFormat, 1882 &desc->mChannelMask, 1883 &desc->mLatency, 1884 desc->mFlags, 1885 &offloadInfo); 1886 if (output != 0) { 1887 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) { 1888 String8 reply; 1889 char *value; 1890 if (profile->mSamplingRates[0] == 0) { 1891 reply = mpClientInterface->getParameters(output, 1892 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES)); 1893 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s", 1894 reply.string()); 1895 value = strpbrk((char *)reply.string(), "="); 1896 if (value != NULL) { 1897 loadSamplingRates(value + 1, profile); 1898 } 1899 } 1900 if (profile->mFormats[0] == 0) { 1901 reply = mpClientInterface->getParameters(output, 1902 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS)); 1903 ALOGV("checkOutputsForDevice() direct output sup formats %s", 1904 reply.string()); 1905 value = strpbrk((char *)reply.string(), "="); 1906 if (value != NULL) { 1907 loadFormats(value + 1, profile); 1908 } 1909 } 1910 if (profile->mChannelMasks[0] == 0) { 1911 reply = mpClientInterface->getParameters(output, 1912 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS)); 1913 ALOGV("checkOutputsForDevice() direct output sup channel masks %s", 1914 reply.string()); 1915 value = strpbrk((char *)reply.string(), "="); 1916 if (value != NULL) { 1917 loadOutChannels(value + 1, profile); 1918 } 1919 } 1920 if (((profile->mSamplingRates[0] == 0) && 1921 (profile->mSamplingRates.size() < 2)) || 1922 ((profile->mFormats[0] == 0) && 1923 (profile->mFormats.size() < 2)) || 1924 ((profile->mFormats[0] == 0) && 1925 (profile->mChannelMasks.size() < 2))) { 1926 ALOGW("checkOutputsForDevice() direct output missing param"); 1927 mpClientInterface->closeOutput(output); 1928 output = 0; 1929 } else { 1930 addOutput(output, desc); 1931 } 1932 } else { 1933 audio_io_handle_t duplicatedOutput = 0; 1934 // add output descriptor 1935 addOutput(output, desc); 1936 // set initial stream volume for device 1937 applyStreamVolumes(output, device, 0, true); 1938 1939 //TODO: configure audio effect output stage here 1940 1941 // open a duplicating output thread for the new output and the primary output 1942 duplicatedOutput = mpClientInterface->openDuplicateOutput(output, 1943 mPrimaryOutput); 1944 if (duplicatedOutput != 0) { 1945 // add duplicated output descriptor 1946 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL); 1947 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput); 1948 dupOutputDesc->mOutput2 = mOutputs.valueFor(output); 1949 dupOutputDesc->mSamplingRate = desc->mSamplingRate; 1950 dupOutputDesc->mFormat = desc->mFormat; 1951 dupOutputDesc->mChannelMask = desc->mChannelMask; 1952 dupOutputDesc->mLatency = desc->mLatency; 1953 addOutput(duplicatedOutput, dupOutputDesc); 1954 applyStreamVolumes(duplicatedOutput, device, 0, true); 1955 } else { 1956 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d", 1957 mPrimaryOutput, output); 1958 mpClientInterface->closeOutput(output); 1959 mOutputs.removeItem(output); 1960 output = 0; 1961 } 1962 } 1963 } 1964 if (output == 0) { 1965 ALOGW("checkOutputsForDevice() could not open output for device %x", device); 1966 delete desc; 1967 profiles.removeAt(profile_index); 1968 profile_index--; 1969 } else { 1970 outputs.add(output); 1971 ALOGV("checkOutputsForDevice(): adding output %d", output); 1972 } 1973 } 1974 1975 if (profiles.isEmpty()) { 1976 ALOGW("checkOutputsForDevice(): No output available for device %04x", device); 1977 return BAD_VALUE; 1978 } 1979 } else { 1980 // check if one opened output is not needed any more after disconnecting one device 1981 for (size_t i = 0; i < mOutputs.size(); i++) { 1982 desc = mOutputs.valueAt(i); 1983 if (!desc->isDuplicated() && 1984 !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) { 1985 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i)); 1986 outputs.add(mOutputs.keyAt(i)); 1987 } 1988 } 1989 for (size_t i = 0; i < mHwModules.size(); i++) 1990 { 1991 if (mHwModules[i]->mHandle == 0) { 1992 continue; 1993 } 1994 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 1995 { 1996 IOProfile *profile = mHwModules[i]->mOutputProfiles[j]; 1997 if ((profile->mSupportedDevices & device) && 1998 (profile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) { 1999 ALOGV("checkOutputsForDevice(): clearing direct output profile %d on module %d", 2000 j, i); 2001 if (profile->mSamplingRates[0] == 0) { 2002 profile->mSamplingRates.clear(); 2003 profile->mSamplingRates.add(0); 2004 } 2005 if (profile->mFormats[0] == 0) { 2006 profile->mFormats.clear(); 2007 profile->mFormats.add((audio_format_t)0); 2008 } 2009 if (profile->mChannelMasks[0] == 0) { 2010 profile->mChannelMasks.clear(); 2011 profile->mChannelMasks.add((audio_channel_mask_t)0); 2012 } 2013 } 2014 } 2015 } 2016 } 2017 return NO_ERROR; 2018} 2019 2020void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output) 2021{ 2022 ALOGV("closeOutput(%d)", output); 2023 2024 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 2025 if (outputDesc == NULL) { 2026 ALOGW("closeOutput() unknown output %d", output); 2027 return; 2028 } 2029 2030 // look for duplicated outputs connected to the output being removed. 2031 for (size_t i = 0; i < mOutputs.size(); i++) { 2032 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i); 2033 if (dupOutputDesc->isDuplicated() && 2034 (dupOutputDesc->mOutput1 == outputDesc || 2035 dupOutputDesc->mOutput2 == outputDesc)) { 2036 AudioOutputDescriptor *outputDesc2; 2037 if (dupOutputDesc->mOutput1 == outputDesc) { 2038 outputDesc2 = dupOutputDesc->mOutput2; 2039 } else { 2040 outputDesc2 = dupOutputDesc->mOutput1; 2041 } 2042 // As all active tracks on duplicated output will be deleted, 2043 // and as they were also referenced on the other output, the reference 2044 // count for their stream type must be adjusted accordingly on 2045 // the other output. 2046 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) { 2047 int refCount = dupOutputDesc->mRefCount[j]; 2048 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount); 2049 } 2050 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i); 2051 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput); 2052 2053 mpClientInterface->closeOutput(duplicatedOutput); 2054 delete mOutputs.valueFor(duplicatedOutput); 2055 mOutputs.removeItem(duplicatedOutput); 2056 } 2057 } 2058 2059 AudioParameter param; 2060 param.add(String8("closing"), String8("true")); 2061 mpClientInterface->setParameters(output, param.toString()); 2062 2063 mpClientInterface->closeOutput(output); 2064 delete outputDesc; 2065 mOutputs.removeItem(output); 2066 mPreviousOutputs = mOutputs; 2067} 2068 2069SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device, 2070 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs) 2071{ 2072 SortedVector<audio_io_handle_t> outputs; 2073 2074 ALOGVV("getOutputsForDevice() device %04x", device); 2075 for (size_t i = 0; i < openOutputs.size(); i++) { 2076 ALOGVV("output %d isDuplicated=%d device=%04x", 2077 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices()); 2078 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) { 2079 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i)); 2080 outputs.add(openOutputs.keyAt(i)); 2081 } 2082 } 2083 return outputs; 2084} 2085 2086bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1, 2087 SortedVector<audio_io_handle_t>& outputs2) 2088{ 2089 if (outputs1.size() != outputs2.size()) { 2090 return false; 2091 } 2092 for (size_t i = 0; i < outputs1.size(); i++) { 2093 if (outputs1[i] != outputs2[i]) { 2094 return false; 2095 } 2096 } 2097 return true; 2098} 2099 2100void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy) 2101{ 2102 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/); 2103 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/); 2104 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs); 2105 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs); 2106 2107 if (!vectorsEqual(srcOutputs,dstOutputs)) { 2108 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d", 2109 strategy, srcOutputs[0], dstOutputs[0]); 2110 // mute strategy while moving tracks from one output to another 2111 for (size_t i = 0; i < srcOutputs.size(); i++) { 2112 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]); 2113 if (desc->isStrategyActive(strategy)) { 2114 setStrategyMute(strategy, true, srcOutputs[i]); 2115 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice); 2116 } 2117 } 2118 2119 // Move effects associated to this strategy from previous output to new output 2120 if (strategy == STRATEGY_MEDIA) { 2121 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs); 2122 SortedVector<audio_io_handle_t> moved; 2123 for (size_t i = 0; i < mEffects.size(); i++) { 2124 EffectDescriptor *desc = mEffects.valueAt(i); 2125 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX && 2126 desc->mIo != fxOutput) { 2127 if (moved.indexOf(desc->mIo) < 0) { 2128 ALOGV("checkOutputForStrategy() moving effect %d to output %d", 2129 mEffects.keyAt(i), fxOutput); 2130 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo, 2131 fxOutput); 2132 moved.add(desc->mIo); 2133 } 2134 desc->mIo = fxOutput; 2135 } 2136 } 2137 } 2138 // Move tracks associated to this strategy from previous output to new output 2139 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) { 2140 if (getStrategy((AudioSystem::stream_type)i) == strategy) { 2141 //FIXME see fixme on name change 2142 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, 2143 dstOutputs[0] /* ignored */); 2144 } 2145 } 2146 } 2147} 2148 2149void AudioPolicyManagerBase::checkOutputForAllStrategies() 2150{ 2151 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE); 2152 checkOutputForStrategy(STRATEGY_PHONE); 2153 checkOutputForStrategy(STRATEGY_SONIFICATION); 2154 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL); 2155 checkOutputForStrategy(STRATEGY_MEDIA); 2156 checkOutputForStrategy(STRATEGY_DTMF); 2157} 2158 2159audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput() 2160{ 2161 if (!mHasA2dp) { 2162 return 0; 2163 } 2164 2165 for (size_t i = 0; i < mOutputs.size(); i++) { 2166 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i); 2167 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) { 2168 return mOutputs.keyAt(i); 2169 } 2170 } 2171 2172 return 0; 2173} 2174 2175void AudioPolicyManagerBase::checkA2dpSuspend() 2176{ 2177 if (!mHasA2dp) { 2178 return; 2179 } 2180 audio_io_handle_t a2dpOutput = getA2dpOutput(); 2181 if (a2dpOutput == 0) { 2182 return; 2183 } 2184 2185 // suspend A2DP output if: 2186 // (NOT already suspended) && 2187 // ((SCO device is connected && 2188 // (forced usage for communication || for record is SCO))) || 2189 // (phone state is ringing || in call) 2190 // 2191 // restore A2DP output if: 2192 // (Already suspended) && 2193 // ((SCO device is NOT connected || 2194 // (forced usage NOT for communication && NOT for record is SCO))) && 2195 // (phone state is NOT ringing && NOT in call) 2196 // 2197 if (mA2dpSuspended) { 2198 if (((mScoDeviceAddress == "") || 2199 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) && 2200 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) && 2201 ((mPhoneState != AudioSystem::MODE_IN_CALL) && 2202 (mPhoneState != AudioSystem::MODE_RINGTONE))) { 2203 2204 mpClientInterface->restoreOutput(a2dpOutput); 2205 mA2dpSuspended = false; 2206 } 2207 } else { 2208 if (((mScoDeviceAddress != "") && 2209 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) || 2210 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) || 2211 ((mPhoneState == AudioSystem::MODE_IN_CALL) || 2212 (mPhoneState == AudioSystem::MODE_RINGTONE))) { 2213 2214 mpClientInterface->suspendOutput(a2dpOutput); 2215 mA2dpSuspended = true; 2216 } 2217 } 2218} 2219 2220audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache) 2221{ 2222 audio_devices_t device = AUDIO_DEVICE_NONE; 2223 2224 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 2225 // check the following by order of priority to request a routing change if necessary: 2226 // 1: the strategy enforced audible is active on the output: 2227 // use device for strategy enforced audible 2228 // 2: we are in call or the strategy phone is active on the output: 2229 // use device for strategy phone 2230 // 3: the strategy sonification is active on the output: 2231 // use device for strategy sonification 2232 // 4: the strategy "respectful" sonification is active on the output: 2233 // use device for strategy "respectful" sonification 2234 // 5: the strategy media is active on the output: 2235 // use device for strategy media 2236 // 6: the strategy DTMF is active on the output: 2237 // use device for strategy DTMF 2238 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) { 2239 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache); 2240 } else if (isInCall() || 2241 outputDesc->isStrategyActive(STRATEGY_PHONE)) { 2242 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache); 2243 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) { 2244 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache); 2245 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) { 2246 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache); 2247 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) { 2248 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache); 2249 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) { 2250 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache); 2251 } 2252 2253 ALOGV("getNewDevice() selected device %x", device); 2254 return device; 2255} 2256 2257uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) { 2258 return (uint32_t)getStrategy(stream); 2259} 2260 2261audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) { 2262 audio_devices_t devices; 2263 // By checking the range of stream before calling getStrategy, we avoid 2264 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE 2265 // and then return STRATEGY_MEDIA, but we want to return the empty set. 2266 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) { 2267 devices = AUDIO_DEVICE_NONE; 2268 } else { 2269 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream); 2270 devices = getDeviceForStrategy(strategy, true /*fromCache*/); 2271 } 2272 return devices; 2273} 2274 2275AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy( 2276 AudioSystem::stream_type stream) { 2277 // stream to strategy mapping 2278 switch (stream) { 2279 case AudioSystem::VOICE_CALL: 2280 case AudioSystem::BLUETOOTH_SCO: 2281 return STRATEGY_PHONE; 2282 case AudioSystem::RING: 2283 case AudioSystem::ALARM: 2284 return STRATEGY_SONIFICATION; 2285 case AudioSystem::NOTIFICATION: 2286 return STRATEGY_SONIFICATION_RESPECTFUL; 2287 case AudioSystem::DTMF: 2288 return STRATEGY_DTMF; 2289 default: 2290 ALOGE("unknown stream type"); 2291 case AudioSystem::SYSTEM: 2292 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs 2293 // while key clicks are played produces a poor result 2294 case AudioSystem::TTS: 2295 case AudioSystem::MUSIC: 2296 return STRATEGY_MEDIA; 2297 case AudioSystem::ENFORCED_AUDIBLE: 2298 return STRATEGY_ENFORCED_AUDIBLE; 2299 } 2300} 2301 2302void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) { 2303 switch(stream) { 2304 case AudioSystem::MUSIC: 2305 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL); 2306 updateDevicesAndOutputs(); 2307 break; 2308 default: 2309 break; 2310 } 2311} 2312 2313audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy, 2314 bool fromCache) 2315{ 2316 uint32_t device = AUDIO_DEVICE_NONE; 2317 2318 if (fromCache) { 2319 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x", 2320 strategy, mDeviceForStrategy[strategy]); 2321 return mDeviceForStrategy[strategy]; 2322 } 2323 2324 switch (strategy) { 2325 2326 case STRATEGY_SONIFICATION_RESPECTFUL: 2327 if (isInCall()) { 2328 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/); 2329 } else if (isStreamActiveRemotely(AudioSystem::MUSIC, 2330 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) { 2331 // while media is playing on a remote device, use the the sonification behavior. 2332 // Note that we test this usecase before testing if media is playing because 2333 // the isStreamActive() method only informs about the activity of a stream, not 2334 // if it's for local playback. Note also that we use the same delay between both tests 2335 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/); 2336 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) { 2337 // while media is playing (or has recently played), use the same device 2338 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/); 2339 } else { 2340 // when media is not playing anymore, fall back on the sonification behavior 2341 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/); 2342 } 2343 2344 break; 2345 2346 case STRATEGY_DTMF: 2347 if (!isInCall()) { 2348 // when off call, DTMF strategy follows the same rules as MEDIA strategy 2349 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/); 2350 break; 2351 } 2352 // when in call, DTMF and PHONE strategies follow the same rules 2353 // FALL THROUGH 2354 2355 case STRATEGY_PHONE: 2356 // for phone strategy, we first consider the forced use and then the available devices by order 2357 // of priority 2358 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) { 2359 case AudioSystem::FORCE_BT_SCO: 2360 if (!isInCall() || strategy != STRATEGY_DTMF) { 2361 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT; 2362 if (device) break; 2363 } 2364 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET; 2365 if (device) break; 2366 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO; 2367 if (device) break; 2368 // if SCO device is requested but no SCO device is available, fall back to default case 2369 // FALL THROUGH 2370 2371 default: // FORCE_NONE 2372 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP 2373 if (mHasA2dp && !isInCall() && 2374 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) && 2375 (getA2dpOutput() != 0) && !mA2dpSuspended) { 2376 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP; 2377 if (device) break; 2378 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES; 2379 if (device) break; 2380 } 2381 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE; 2382 if (device) break; 2383 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET; 2384 if (device) break; 2385 if (mPhoneState != AudioSystem::MODE_IN_CALL) { 2386 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY; 2387 if (device) break; 2388 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE; 2389 if (device) break; 2390 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET; 2391 if (device) break; 2392 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL; 2393 if (device) break; 2394 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET; 2395 if (device) break; 2396 } 2397 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE; 2398 if (device) break; 2399 device = mDefaultOutputDevice; 2400 if (device == AUDIO_DEVICE_NONE) { 2401 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE"); 2402 } 2403 break; 2404 2405 case AudioSystem::FORCE_SPEAKER: 2406 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to 2407 // A2DP speaker when forcing to speaker output 2408 if (mHasA2dp && !isInCall() && 2409 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) && 2410 (getA2dpOutput() != 0) && !mA2dpSuspended) { 2411 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER; 2412 if (device) break; 2413 } 2414 if (mPhoneState != AudioSystem::MODE_IN_CALL) { 2415 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY; 2416 if (device) break; 2417 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE; 2418 if (device) break; 2419 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET; 2420 if (device) break; 2421 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL; 2422 if (device) break; 2423 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET; 2424 if (device) break; 2425 } 2426 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER; 2427 if (device) break; 2428 device = mDefaultOutputDevice; 2429 if (device == AUDIO_DEVICE_NONE) { 2430 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER"); 2431 } 2432 break; 2433 } 2434 break; 2435 2436 case STRATEGY_SONIFICATION: 2437 2438 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by 2439 // handleIncallSonification(). 2440 if (isInCall()) { 2441 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/); 2442 break; 2443 } 2444 // FALL THROUGH 2445 2446 case STRATEGY_ENFORCED_AUDIBLE: 2447 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION 2448 // except: 2449 // - when in call where it doesn't default to STRATEGY_PHONE behavior 2450 // - in countries where not enforced in which case it follows STRATEGY_MEDIA 2451 2452 if ((strategy == STRATEGY_SONIFICATION) || 2453 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_SYSTEM_ENFORCED)) { 2454 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER; 2455 if (device == AUDIO_DEVICE_NONE) { 2456 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION"); 2457 } 2458 } 2459 // The second device used for sonification is the same as the device used by media strategy 2460 // FALL THROUGH 2461 2462 case STRATEGY_MEDIA: { 2463 uint32_t device2 = AUDIO_DEVICE_NONE; 2464 if (strategy != STRATEGY_SONIFICATION) { 2465 // no sonification on remote submix (e.g. WFD) 2466 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_REMOTE_SUBMIX; 2467 } 2468 if ((device2 == AUDIO_DEVICE_NONE) && 2469 mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) && 2470 (getA2dpOutput() != 0) && !mA2dpSuspended) { 2471 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP; 2472 if (device2 == AUDIO_DEVICE_NONE) { 2473 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES; 2474 } 2475 if (device2 == AUDIO_DEVICE_NONE) { 2476 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER; 2477 } 2478 } 2479 if (device2 == AUDIO_DEVICE_NONE) { 2480 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE; 2481 } 2482 if (device2 == AUDIO_DEVICE_NONE) { 2483 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET; 2484 } 2485 if (device2 == AUDIO_DEVICE_NONE) { 2486 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY; 2487 } 2488 if (device2 == AUDIO_DEVICE_NONE) { 2489 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE; 2490 } 2491 if (device2 == AUDIO_DEVICE_NONE) { 2492 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET; 2493 } 2494 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) { 2495 // no sonification on aux digital (e.g. HDMI) 2496 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL; 2497 } 2498 if ((device2 == AUDIO_DEVICE_NONE) && 2499 (mForceUse[AudioSystem::FOR_DOCK] == AudioSystem::FORCE_ANALOG_DOCK)) { 2500 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET; 2501 } 2502 if (device2 == AUDIO_DEVICE_NONE) { 2503 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER; 2504 } 2505 2506 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or 2507 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise 2508 device |= device2; 2509 if (device) break; 2510 device = mDefaultOutputDevice; 2511 if (device == AUDIO_DEVICE_NONE) { 2512 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA"); 2513 } 2514 } break; 2515 2516 default: 2517 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy); 2518 break; 2519 } 2520 2521 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device); 2522 return device; 2523} 2524 2525void AudioPolicyManagerBase::updateDevicesAndOutputs() 2526{ 2527 for (int i = 0; i < NUM_STRATEGIES; i++) { 2528 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/); 2529 } 2530 mPreviousOutputs = mOutputs; 2531} 2532 2533uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc, 2534 audio_devices_t prevDevice, 2535 uint32_t delayMs) 2536{ 2537 // mute/unmute strategies using an incompatible device combination 2538 // if muting, wait for the audio in pcm buffer to be drained before proceeding 2539 // if unmuting, unmute only after the specified delay 2540 if (outputDesc->isDuplicated()) { 2541 return 0; 2542 } 2543 2544 uint32_t muteWaitMs = 0; 2545 audio_devices_t device = outputDesc->device(); 2546 bool shouldMute = outputDesc->isActive() && (AudioSystem::popCount(device) >= 2); 2547 // temporary mute output if device selection changes to avoid volume bursts due to 2548 // different per device volumes 2549 bool tempMute = outputDesc->isActive() && (device != prevDevice); 2550 2551 for (size_t i = 0; i < NUM_STRATEGIES; i++) { 2552 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/); 2553 bool mute = shouldMute && (curDevice & device) && (curDevice != device); 2554 bool doMute = false; 2555 2556 if (mute && !outputDesc->mStrategyMutedByDevice[i]) { 2557 doMute = true; 2558 outputDesc->mStrategyMutedByDevice[i] = true; 2559 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){ 2560 doMute = true; 2561 outputDesc->mStrategyMutedByDevice[i] = false; 2562 } 2563 if (doMute || tempMute) { 2564 for (size_t j = 0; j < mOutputs.size(); j++) { 2565 AudioOutputDescriptor *desc = mOutputs.valueAt(j); 2566 // skip output if it does not share any device with current output 2567 if ((desc->supportedDevices() & outputDesc->supportedDevices()) 2568 == AUDIO_DEVICE_NONE) { 2569 continue; 2570 } 2571 audio_io_handle_t curOutput = mOutputs.keyAt(j); 2572 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d", 2573 mute ? "muting" : "unmuting", i, curDevice, curOutput); 2574 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs); 2575 if (desc->isStrategyActive((routing_strategy)i)) { 2576 // do tempMute only for current output 2577 if (tempMute && (desc == outputDesc)) { 2578 setStrategyMute((routing_strategy)i, true, curOutput); 2579 setStrategyMute((routing_strategy)i, false, curOutput, 2580 desc->latency() * 2, device); 2581 } 2582 if ((tempMute && (desc == outputDesc)) || mute) { 2583 if (muteWaitMs < desc->latency()) { 2584 muteWaitMs = desc->latency(); 2585 } 2586 } 2587 } 2588 } 2589 } 2590 } 2591 2592 // FIXME: should not need to double latency if volume could be applied immediately by the 2593 // audioflinger mixer. We must account for the delay between now and the next time 2594 // the audioflinger thread for this output will process a buffer (which corresponds to 2595 // one buffer size, usually 1/2 or 1/4 of the latency). 2596 muteWaitMs *= 2; 2597 // wait for the PCM output buffers to empty before proceeding with the rest of the command 2598 if (muteWaitMs > delayMs) { 2599 muteWaitMs -= delayMs; 2600 usleep(muteWaitMs * 1000); 2601 return muteWaitMs; 2602 } 2603 return 0; 2604} 2605 2606uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output, 2607 audio_devices_t device, 2608 bool force, 2609 int delayMs) 2610{ 2611 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs); 2612 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 2613 AudioParameter param; 2614 uint32_t muteWaitMs; 2615 2616 if (outputDesc->isDuplicated()) { 2617 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs); 2618 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs); 2619 return muteWaitMs; 2620 } 2621 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current 2622 // output profile 2623 if ((device != AUDIO_DEVICE_NONE) && 2624 ((device & outputDesc->mProfile->mSupportedDevices) == 0)) { 2625 return 0; 2626 } 2627 2628 // filter devices according to output selected 2629 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices); 2630 2631 audio_devices_t prevDevice = outputDesc->mDevice; 2632 2633 ALOGV("setOutputDevice() prevDevice %04x", prevDevice); 2634 2635 if (device != AUDIO_DEVICE_NONE) { 2636 outputDesc->mDevice = device; 2637 } 2638 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs); 2639 2640 // Do not change the routing if: 2641 // - the requested device is AUDIO_DEVICE_NONE 2642 // - the requested device is the same as current device and force is not specified. 2643 // Doing this check here allows the caller to call setOutputDevice() without conditions 2644 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) { 2645 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output); 2646 return muteWaitMs; 2647 } 2648 2649 ALOGV("setOutputDevice() changing device"); 2650 // do the routing 2651 param.addInt(String8(AudioParameter::keyRouting), (int)device); 2652 mpClientInterface->setParameters(output, param.toString(), delayMs); 2653 2654 // update stream volumes according to new device 2655 applyStreamVolumes(output, device, delayMs); 2656 2657 return muteWaitMs; 2658} 2659 2660AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device, 2661 uint32_t samplingRate, 2662 uint32_t format, 2663 uint32_t channelMask) 2664{ 2665 // Choose an input profile based on the requested capture parameters: select the first available 2666 // profile supporting all requested parameters. 2667 2668 for (size_t i = 0; i < mHwModules.size(); i++) 2669 { 2670 if (mHwModules[i]->mHandle == 0) { 2671 continue; 2672 } 2673 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) 2674 { 2675 IOProfile *profile = mHwModules[i]->mInputProfiles[j]; 2676 if (profile->isCompatibleProfile(device, samplingRate, format, 2677 channelMask,(audio_output_flags_t)0)) { 2678 return profile; 2679 } 2680 } 2681 } 2682 return NULL; 2683} 2684 2685audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource) 2686{ 2687 uint32_t device = AUDIO_DEVICE_NONE; 2688 2689 switch (inputSource) { 2690 case AUDIO_SOURCE_VOICE_UPLINK: 2691 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) { 2692 device = AUDIO_DEVICE_IN_VOICE_CALL; 2693 break; 2694 } 2695 // FALL THROUGH 2696 2697 case AUDIO_SOURCE_DEFAULT: 2698 case AUDIO_SOURCE_MIC: 2699 case AUDIO_SOURCE_VOICE_RECOGNITION: 2700 case AUDIO_SOURCE_HOTWORD: 2701 case AUDIO_SOURCE_VOICE_COMMUNICATION: 2702 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO && 2703 mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) { 2704 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET; 2705 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) { 2706 device = AUDIO_DEVICE_IN_WIRED_HEADSET; 2707 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) { 2708 device = AUDIO_DEVICE_IN_BUILTIN_MIC; 2709 } 2710 break; 2711 case AUDIO_SOURCE_CAMCORDER: 2712 if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) { 2713 device = AUDIO_DEVICE_IN_BACK_MIC; 2714 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) { 2715 device = AUDIO_DEVICE_IN_BUILTIN_MIC; 2716 } 2717 break; 2718 case AUDIO_SOURCE_VOICE_DOWNLINK: 2719 case AUDIO_SOURCE_VOICE_CALL: 2720 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) { 2721 device = AUDIO_DEVICE_IN_VOICE_CALL; 2722 } 2723 break; 2724 case AUDIO_SOURCE_REMOTE_SUBMIX: 2725 if (mAvailableInputDevices & AUDIO_DEVICE_IN_REMOTE_SUBMIX) { 2726 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX; 2727 } 2728 break; 2729 default: 2730 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource); 2731 break; 2732 } 2733 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device); 2734 return device; 2735} 2736 2737bool AudioPolicyManagerBase::isVirtualInputDevice(audio_devices_t device) 2738{ 2739 if ((device & AUDIO_DEVICE_BIT_IN) != 0) { 2740 device &= ~AUDIO_DEVICE_BIT_IN; 2741 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0)) 2742 return true; 2743 } 2744 return false; 2745} 2746 2747audio_io_handle_t AudioPolicyManagerBase::getActiveInput(bool ignoreVirtualInputs) 2748{ 2749 for (size_t i = 0; i < mInputs.size(); i++) { 2750 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i); 2751 if ((input_descriptor->mRefCount > 0) 2752 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) { 2753 return mInputs.keyAt(i); 2754 } 2755 } 2756 return 0; 2757} 2758 2759 2760audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device) 2761{ 2762 if (device == AUDIO_DEVICE_NONE) { 2763 // this happens when forcing a route update and no track is active on an output. 2764 // In this case the returned category is not important. 2765 device = AUDIO_DEVICE_OUT_SPEAKER; 2766 } else if (AudioSystem::popCount(device) > 1) { 2767 // Multiple device selection is either: 2768 // - speaker + one other device: give priority to speaker in this case. 2769 // - one A2DP device + another device: happens with duplicated output. In this case 2770 // retain the device on the A2DP output as the other must not correspond to an active 2771 // selection if not the speaker. 2772 if (device & AUDIO_DEVICE_OUT_SPEAKER) { 2773 device = AUDIO_DEVICE_OUT_SPEAKER; 2774 } else { 2775 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP); 2776 } 2777 } 2778 2779 ALOGW_IF(AudioSystem::popCount(device) != 1, 2780 "getDeviceForVolume() invalid device combination: %08x", 2781 device); 2782 2783 return device; 2784} 2785 2786AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device) 2787{ 2788 switch(getDeviceForVolume(device)) { 2789 case AUDIO_DEVICE_OUT_EARPIECE: 2790 return DEVICE_CATEGORY_EARPIECE; 2791 case AUDIO_DEVICE_OUT_WIRED_HEADSET: 2792 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE: 2793 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO: 2794 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET: 2795 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP: 2796 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES: 2797 return DEVICE_CATEGORY_HEADSET; 2798 case AUDIO_DEVICE_OUT_SPEAKER: 2799 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT: 2800 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER: 2801 case AUDIO_DEVICE_OUT_AUX_DIGITAL: 2802 case AUDIO_DEVICE_OUT_USB_ACCESSORY: 2803 case AUDIO_DEVICE_OUT_USB_DEVICE: 2804 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX: 2805 default: 2806 return DEVICE_CATEGORY_SPEAKER; 2807 } 2808} 2809 2810float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc, 2811 int indexInUi) 2812{ 2813 device_category deviceCategory = getDeviceCategory(device); 2814 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory]; 2815 2816 // the volume index in the UI is relative to the min and max volume indices for this stream type 2817 int nbSteps = 1 + curve[VOLMAX].mIndex - 2818 curve[VOLMIN].mIndex; 2819 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) / 2820 (streamDesc.mIndexMax - streamDesc.mIndexMin); 2821 2822 // find what part of the curve this index volume belongs to, or if it's out of bounds 2823 int segment = 0; 2824 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds 2825 return 0.0f; 2826 } else if (volIdx < curve[VOLKNEE1].mIndex) { 2827 segment = 0; 2828 } else if (volIdx < curve[VOLKNEE2].mIndex) { 2829 segment = 1; 2830 } else if (volIdx <= curve[VOLMAX].mIndex) { 2831 segment = 2; 2832 } else { // out of bounds 2833 return 1.0f; 2834 } 2835 2836 // linear interpolation in the attenuation table in dB 2837 float decibels = curve[segment].mDBAttenuation + 2838 ((float)(volIdx - curve[segment].mIndex)) * 2839 ( (curve[segment+1].mDBAttenuation - 2840 curve[segment].mDBAttenuation) / 2841 ((float)(curve[segment+1].mIndex - 2842 curve[segment].mIndex)) ); 2843 2844 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 ) 2845 2846 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f", 2847 curve[segment].mIndex, volIdx, 2848 curve[segment+1].mIndex, 2849 curve[segment].mDBAttenuation, 2850 decibels, 2851 curve[segment+1].mDBAttenuation, 2852 amplification); 2853 2854 return amplification; 2855} 2856 2857const AudioPolicyManagerBase::VolumeCurvePoint 2858 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2859 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f} 2860}; 2861 2862const AudioPolicyManagerBase::VolumeCurvePoint 2863 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2864 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f} 2865}; 2866 2867const AudioPolicyManagerBase::VolumeCurvePoint 2868 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2869 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f} 2870}; 2871 2872const AudioPolicyManagerBase::VolumeCurvePoint 2873 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2874 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f} 2875}; 2876 2877// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks 2878// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets. 2879// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java). 2880// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset. 2881 2882const AudioPolicyManagerBase::VolumeCurvePoint 2883 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2884 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f} 2885}; 2886 2887const AudioPolicyManagerBase::VolumeCurvePoint 2888 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2889 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f} 2890}; 2891 2892const AudioPolicyManagerBase::VolumeCurvePoint 2893 AudioPolicyManagerBase::sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2894 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f} 2895}; 2896 2897const AudioPolicyManagerBase::VolumeCurvePoint 2898 AudioPolicyManagerBase::sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2899 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f} 2900}; 2901 2902const AudioPolicyManagerBase::VolumeCurvePoint 2903 *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT] 2904 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = { 2905 { // AUDIO_STREAM_VOICE_CALL 2906 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET 2907 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2908 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE 2909 }, 2910 { // AUDIO_STREAM_SYSTEM 2911 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET 2912 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2913 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE 2914 }, 2915 { // AUDIO_STREAM_RING 2916 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET 2917 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2918 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE 2919 }, 2920 { // AUDIO_STREAM_MUSIC 2921 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET 2922 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2923 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE 2924 }, 2925 { // AUDIO_STREAM_ALARM 2926 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET 2927 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2928 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE 2929 }, 2930 { // AUDIO_STREAM_NOTIFICATION 2931 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET 2932 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2933 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE 2934 }, 2935 { // AUDIO_STREAM_BLUETOOTH_SCO 2936 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET 2937 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2938 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE 2939 }, 2940 { // AUDIO_STREAM_ENFORCED_AUDIBLE 2941 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET 2942 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2943 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE 2944 }, 2945 { // AUDIO_STREAM_DTMF 2946 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET 2947 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2948 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE 2949 }, 2950 { // AUDIO_STREAM_TTS 2951 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET 2952 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2953 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE 2954 }, 2955}; 2956 2957void AudioPolicyManagerBase::initializeVolumeCurves() 2958{ 2959 for (int i = 0; i < AUDIO_STREAM_CNT; i++) { 2960 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) { 2961 mStreams[i].mVolumeCurve[j] = 2962 sVolumeProfiles[i][j]; 2963 } 2964 } 2965} 2966 2967float AudioPolicyManagerBase::computeVolume(int stream, 2968 int index, 2969 audio_io_handle_t output, 2970 audio_devices_t device) 2971{ 2972 float volume = 1.0; 2973 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 2974 StreamDescriptor &streamDesc = mStreams[stream]; 2975 2976 if (device == AUDIO_DEVICE_NONE) { 2977 device = outputDesc->device(); 2978 } 2979 2980 // if volume is not 0 (not muted), force media volume to max on digital output 2981 if (stream == AudioSystem::MUSIC && 2982 index != mStreams[stream].mIndexMin && 2983 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL || 2984 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET || 2985 device == AUDIO_DEVICE_OUT_USB_ACCESSORY || 2986 device == AUDIO_DEVICE_OUT_USB_DEVICE)) { 2987 return 1.0; 2988 } 2989 2990 volume = volIndexToAmpl(device, streamDesc, index); 2991 2992 // if a headset is connected, apply the following rules to ring tones and notifications 2993 // to avoid sound level bursts in user's ears: 2994 // - always attenuate ring tones and notifications volume by 6dB 2995 // - if music is playing, always limit the volume to current music volume, 2996 // with a minimum threshold at -36dB so that notification is always perceived. 2997 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream); 2998 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP | 2999 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES | 3000 AUDIO_DEVICE_OUT_WIRED_HEADSET | 3001 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) && 3002 ((stream_strategy == STRATEGY_SONIFICATION) 3003 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL) 3004 || (stream == AudioSystem::SYSTEM) 3005 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) && 3006 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) && 3007 streamDesc.mCanBeMuted) { 3008 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR; 3009 // when the phone is ringing we must consider that music could have been paused just before 3010 // by the music application and behave as if music was active if the last music track was 3011 // just stopped 3012 if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) || 3013 mLimitRingtoneVolume) { 3014 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/); 3015 float musicVol = computeVolume(AudioSystem::MUSIC, 3016 mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice), 3017 output, 3018 musicDevice); 3019 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? 3020 musicVol : SONIFICATION_HEADSET_VOLUME_MIN; 3021 if (volume > minVol) { 3022 volume = minVol; 3023 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol); 3024 } 3025 } 3026 } 3027 3028 return volume; 3029} 3030 3031status_t AudioPolicyManagerBase::checkAndSetVolume(int stream, 3032 int index, 3033 audio_io_handle_t output, 3034 audio_devices_t device, 3035 int delayMs, 3036 bool force) 3037{ 3038 3039 // do not change actual stream volume if the stream is muted 3040 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) { 3041 ALOGVV("checkAndSetVolume() stream %d muted count %d", 3042 stream, mOutputs.valueFor(output)->mMuteCount[stream]); 3043 return NO_ERROR; 3044 } 3045 3046 // do not change in call volume if bluetooth is connected and vice versa 3047 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) || 3048 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) { 3049 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm", 3050 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]); 3051 return INVALID_OPERATION; 3052 } 3053 3054 float volume = computeVolume(stream, index, output, device); 3055 // We actually change the volume if: 3056 // - the float value returned by computeVolume() changed 3057 // - the force flag is set 3058 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] || 3059 force) { 3060 mOutputs.valueFor(output)->mCurVolume[stream] = volume; 3061 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs); 3062 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is 3063 // enabled 3064 if (stream == AudioSystem::BLUETOOTH_SCO) { 3065 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs); 3066 } 3067 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs); 3068 } 3069 3070 if (stream == AudioSystem::VOICE_CALL || 3071 stream == AudioSystem::BLUETOOTH_SCO) { 3072 float voiceVolume; 3073 // Force voice volume to max for bluetooth SCO as volume is managed by the headset 3074 if (stream == AudioSystem::VOICE_CALL) { 3075 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax; 3076 } else { 3077 voiceVolume = 1.0; 3078 } 3079 3080 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) { 3081 mpClientInterface->setVoiceVolume(voiceVolume, delayMs); 3082 mLastVoiceVolume = voiceVolume; 3083 } 3084 } 3085 3086 return NO_ERROR; 3087} 3088 3089void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output, 3090 audio_devices_t device, 3091 int delayMs, 3092 bool force) 3093{ 3094 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device); 3095 3096 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) { 3097 checkAndSetVolume(stream, 3098 mStreams[stream].getVolumeIndex(device), 3099 output, 3100 device, 3101 delayMs, 3102 force); 3103 } 3104} 3105 3106void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy, 3107 bool on, 3108 audio_io_handle_t output, 3109 int delayMs, 3110 audio_devices_t device) 3111{ 3112 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output); 3113 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) { 3114 if (getStrategy((AudioSystem::stream_type)stream) == strategy) { 3115 setStreamMute(stream, on, output, delayMs, device); 3116 } 3117 } 3118} 3119 3120void AudioPolicyManagerBase::setStreamMute(int stream, 3121 bool on, 3122 audio_io_handle_t output, 3123 int delayMs, 3124 audio_devices_t device) 3125{ 3126 StreamDescriptor &streamDesc = mStreams[stream]; 3127 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 3128 if (device == AUDIO_DEVICE_NONE) { 3129 device = outputDesc->device(); 3130 } 3131 3132 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x", 3133 stream, on, output, outputDesc->mMuteCount[stream], device); 3134 3135 if (on) { 3136 if (outputDesc->mMuteCount[stream] == 0) { 3137 if (streamDesc.mCanBeMuted && 3138 ((stream != AudioSystem::ENFORCED_AUDIBLE) || 3139 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) { 3140 checkAndSetVolume(stream, 0, output, device, delayMs); 3141 } 3142 } 3143 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored 3144 outputDesc->mMuteCount[stream]++; 3145 } else { 3146 if (outputDesc->mMuteCount[stream] == 0) { 3147 ALOGV("setStreamMute() unmuting non muted stream!"); 3148 return; 3149 } 3150 if (--outputDesc->mMuteCount[stream] == 0) { 3151 checkAndSetVolume(stream, 3152 streamDesc.getVolumeIndex(device), 3153 output, 3154 device, 3155 delayMs); 3156 } 3157 } 3158} 3159 3160void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange) 3161{ 3162 // if the stream pertains to sonification strategy and we are in call we must 3163 // mute the stream if it is low visibility. If it is high visibility, we must play a tone 3164 // in the device used for phone strategy and play the tone if the selected device does not 3165 // interfere with the device used for phone strategy 3166 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as 3167 // many times as there are active tracks on the output 3168 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream); 3169 if ((stream_strategy == STRATEGY_SONIFICATION) || 3170 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) { 3171 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput); 3172 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d", 3173 stream, starting, outputDesc->mDevice, stateChange); 3174 if (outputDesc->mRefCount[stream]) { 3175 int muteCount = 1; 3176 if (stateChange) { 3177 muteCount = outputDesc->mRefCount[stream]; 3178 } 3179 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) { 3180 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount); 3181 for (int i = 0; i < muteCount; i++) { 3182 setStreamMute(stream, starting, mPrimaryOutput); 3183 } 3184 } else { 3185 ALOGV("handleIncallSonification() high visibility"); 3186 if (outputDesc->device() & 3187 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) { 3188 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount); 3189 for (int i = 0; i < muteCount; i++) { 3190 setStreamMute(stream, starting, mPrimaryOutput); 3191 } 3192 } 3193 if (starting) { 3194 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL); 3195 } else { 3196 mpClientInterface->stopTone(); 3197 } 3198 } 3199 } 3200 } 3201} 3202 3203bool AudioPolicyManagerBase::isInCall() 3204{ 3205 return isStateInCall(mPhoneState); 3206} 3207 3208bool AudioPolicyManagerBase::isStateInCall(int state) { 3209 return ((state == AudioSystem::MODE_IN_CALL) || 3210 (state == AudioSystem::MODE_IN_COMMUNICATION)); 3211} 3212 3213uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad() 3214{ 3215 return MAX_EFFECTS_CPU_LOAD; 3216} 3217 3218uint32_t AudioPolicyManagerBase::getMaxEffectsMemory() 3219{ 3220 return MAX_EFFECTS_MEMORY; 3221} 3222 3223// --- AudioOutputDescriptor class implementation 3224 3225AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor( 3226 const IOProfile *profile) 3227 : mId(0), mSamplingRate(0), mFormat((audio_format_t)0), 3228 mChannelMask((audio_channel_mask_t)0), mLatency(0), 3229 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), 3230 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0) 3231{ 3232 // clear usage count for all stream types 3233 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) { 3234 mRefCount[i] = 0; 3235 mCurVolume[i] = -1.0; 3236 mMuteCount[i] = 0; 3237 mStopTime[i] = 0; 3238 } 3239 for (int i = 0; i < NUM_STRATEGIES; i++) { 3240 mStrategyMutedByDevice[i] = false; 3241 } 3242 if (profile != NULL) { 3243 mSamplingRate = profile->mSamplingRates[0]; 3244 mFormat = profile->mFormats[0]; 3245 mChannelMask = profile->mChannelMasks[0]; 3246 mFlags = profile->mFlags; 3247 } 3248} 3249 3250audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device() const 3251{ 3252 if (isDuplicated()) { 3253 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice); 3254 } else { 3255 return mDevice; 3256 } 3257} 3258 3259uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency() 3260{ 3261 if (isDuplicated()) { 3262 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency; 3263 } else { 3264 return mLatency; 3265 } 3266} 3267 3268bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith( 3269 const AudioOutputDescriptor *outputDesc) 3270{ 3271 if (isDuplicated()) { 3272 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc); 3273 } else if (outputDesc->isDuplicated()){ 3274 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2); 3275 } else { 3276 return (mProfile->mModule == outputDesc->mProfile->mModule); 3277 } 3278} 3279 3280void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta) 3281{ 3282 // forward usage count change to attached outputs 3283 if (isDuplicated()) { 3284 mOutput1->changeRefCount(stream, delta); 3285 mOutput2->changeRefCount(stream, delta); 3286 } 3287 if ((delta + (int)mRefCount[stream]) < 0) { 3288 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]); 3289 mRefCount[stream] = 0; 3290 return; 3291 } 3292 mRefCount[stream] += delta; 3293 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]); 3294} 3295 3296audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices() 3297{ 3298 if (isDuplicated()) { 3299 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices()); 3300 } else { 3301 return mProfile->mSupportedDevices ; 3302 } 3303} 3304 3305bool AudioPolicyManagerBase::AudioOutputDescriptor::isActive(uint32_t inPastMs) const 3306{ 3307 return isStrategyActive(NUM_STRATEGIES, inPastMs); 3308} 3309 3310bool AudioPolicyManagerBase::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy, 3311 uint32_t inPastMs, 3312 nsecs_t sysTime) const 3313{ 3314 if ((sysTime == 0) && (inPastMs != 0)) { 3315 sysTime = systemTime(); 3316 } 3317 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) { 3318 if (((getStrategy((AudioSystem::stream_type)i) == strategy) || 3319 (NUM_STRATEGIES == strategy)) && 3320 isStreamActive((AudioSystem::stream_type)i, inPastMs, sysTime)) { 3321 return true; 3322 } 3323 } 3324 return false; 3325} 3326 3327bool AudioPolicyManagerBase::AudioOutputDescriptor::isStreamActive(AudioSystem::stream_type stream, 3328 uint32_t inPastMs, 3329 nsecs_t sysTime) const 3330{ 3331 if (mRefCount[stream] != 0) { 3332 return true; 3333 } 3334 if (inPastMs == 0) { 3335 return false; 3336 } 3337 if (sysTime == 0) { 3338 sysTime = systemTime(); 3339 } 3340 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) { 3341 return true; 3342 } 3343 return false; 3344} 3345 3346 3347status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd) 3348{ 3349 const size_t SIZE = 256; 3350 char buffer[SIZE]; 3351 String8 result; 3352 3353 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate); 3354 result.append(buffer); 3355 snprintf(buffer, SIZE, " Format: %08x\n", mFormat); 3356 result.append(buffer); 3357 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask); 3358 result.append(buffer); 3359 snprintf(buffer, SIZE, " Latency: %d\n", mLatency); 3360 result.append(buffer); 3361 snprintf(buffer, SIZE, " Flags %08x\n", mFlags); 3362 result.append(buffer); 3363 snprintf(buffer, SIZE, " Devices %08x\n", device()); 3364 result.append(buffer); 3365 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n"); 3366 result.append(buffer); 3367 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) { 3368 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]); 3369 result.append(buffer); 3370 } 3371 write(fd, result.string(), result.size()); 3372 3373 return NO_ERROR; 3374} 3375 3376// --- AudioInputDescriptor class implementation 3377 3378AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile) 3379 : mSamplingRate(0), mFormat((audio_format_t)0), mChannelMask((audio_channel_mask_t)0), 3380 mDevice(AUDIO_DEVICE_NONE), mRefCount(0), 3381 mInputSource(0), mProfile(profile) 3382{ 3383} 3384 3385status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd) 3386{ 3387 const size_t SIZE = 256; 3388 char buffer[SIZE]; 3389 String8 result; 3390 3391 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate); 3392 result.append(buffer); 3393 snprintf(buffer, SIZE, " Format: %d\n", mFormat); 3394 result.append(buffer); 3395 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask); 3396 result.append(buffer); 3397 snprintf(buffer, SIZE, " Devices %08x\n", mDevice); 3398 result.append(buffer); 3399 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount); 3400 result.append(buffer); 3401 write(fd, result.string(), result.size()); 3402 3403 return NO_ERROR; 3404} 3405 3406// --- StreamDescriptor class implementation 3407 3408AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor() 3409 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true) 3410{ 3411 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0); 3412} 3413 3414int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device) 3415{ 3416 device = AudioPolicyManagerBase::getDeviceForVolume(device); 3417 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT 3418 if (mIndexCur.indexOfKey(device) < 0) { 3419 device = AUDIO_DEVICE_OUT_DEFAULT; 3420 } 3421 return mIndexCur.valueFor(device); 3422} 3423 3424void AudioPolicyManagerBase::StreamDescriptor::dump(int fd) 3425{ 3426 const size_t SIZE = 256; 3427 char buffer[SIZE]; 3428 String8 result; 3429 3430 snprintf(buffer, SIZE, "%s %02d %02d ", 3431 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax); 3432 result.append(buffer); 3433 for (size_t i = 0; i < mIndexCur.size(); i++) { 3434 snprintf(buffer, SIZE, "%04x : %02d, ", 3435 mIndexCur.keyAt(i), 3436 mIndexCur.valueAt(i)); 3437 result.append(buffer); 3438 } 3439 result.append("\n"); 3440 3441 write(fd, result.string(), result.size()); 3442} 3443 3444// --- EffectDescriptor class implementation 3445 3446status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd) 3447{ 3448 const size_t SIZE = 256; 3449 char buffer[SIZE]; 3450 String8 result; 3451 3452 snprintf(buffer, SIZE, " I/O: %d\n", mIo); 3453 result.append(buffer); 3454 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy); 3455 result.append(buffer); 3456 snprintf(buffer, SIZE, " Session: %d\n", mSession); 3457 result.append(buffer); 3458 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name); 3459 result.append(buffer); 3460 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled"); 3461 result.append(buffer); 3462 write(fd, result.string(), result.size()); 3463 3464 return NO_ERROR; 3465} 3466 3467// --- IOProfile class implementation 3468 3469AudioPolicyManagerBase::HwModule::HwModule(const char *name) 3470 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0) 3471{ 3472} 3473 3474AudioPolicyManagerBase::HwModule::~HwModule() 3475{ 3476 for (size_t i = 0; i < mOutputProfiles.size(); i++) { 3477 delete mOutputProfiles[i]; 3478 } 3479 for (size_t i = 0; i < mInputProfiles.size(); i++) { 3480 delete mInputProfiles[i]; 3481 } 3482 free((void *)mName); 3483} 3484 3485void AudioPolicyManagerBase::HwModule::dump(int fd) 3486{ 3487 const size_t SIZE = 256; 3488 char buffer[SIZE]; 3489 String8 result; 3490 3491 snprintf(buffer, SIZE, " - name: %s\n", mName); 3492 result.append(buffer); 3493 snprintf(buffer, SIZE, " - handle: %d\n", mHandle); 3494 result.append(buffer); 3495 write(fd, result.string(), result.size()); 3496 if (mOutputProfiles.size()) { 3497 write(fd, " - outputs:\n", sizeof(" - outputs:\n")); 3498 for (size_t i = 0; i < mOutputProfiles.size(); i++) { 3499 snprintf(buffer, SIZE, " output %d:\n", i); 3500 write(fd, buffer, strlen(buffer)); 3501 mOutputProfiles[i]->dump(fd); 3502 } 3503 } 3504 if (mInputProfiles.size()) { 3505 write(fd, " - inputs:\n", sizeof(" - inputs:\n")); 3506 for (size_t i = 0; i < mInputProfiles.size(); i++) { 3507 snprintf(buffer, SIZE, " input %d:\n", i); 3508 write(fd, buffer, strlen(buffer)); 3509 mInputProfiles[i]->dump(fd); 3510 } 3511 } 3512} 3513 3514AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module) 3515 : mFlags((audio_output_flags_t)0), mModule(module) 3516{ 3517} 3518 3519AudioPolicyManagerBase::IOProfile::~IOProfile() 3520{ 3521} 3522 3523// checks if the IO profile is compatible with specified parameters. 3524// Sampling rate, format and channel mask must be specified in order to 3525// get a valid a match 3526bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device, 3527 uint32_t samplingRate, 3528 uint32_t format, 3529 uint32_t channelMask, 3530 audio_output_flags_t flags) const 3531{ 3532 if (samplingRate == 0 || format == 0 || channelMask == 0) { 3533 return false; 3534 } 3535 3536 if ((mSupportedDevices & device) != device) { 3537 return false; 3538 } 3539 if ((mFlags & flags) != flags) { 3540 return false; 3541 } 3542 size_t i; 3543 for (i = 0; i < mSamplingRates.size(); i++) 3544 { 3545 if (mSamplingRates[i] == samplingRate) { 3546 break; 3547 } 3548 } 3549 if (i == mSamplingRates.size()) { 3550 return false; 3551 } 3552 for (i = 0; i < mFormats.size(); i++) 3553 { 3554 if (mFormats[i] == format) { 3555 break; 3556 } 3557 } 3558 if (i == mFormats.size()) { 3559 return false; 3560 } 3561 for (i = 0; i < mChannelMasks.size(); i++) 3562 { 3563 if (mChannelMasks[i] == channelMask) { 3564 break; 3565 } 3566 } 3567 if (i == mChannelMasks.size()) { 3568 return false; 3569 } 3570 return true; 3571} 3572 3573void AudioPolicyManagerBase::IOProfile::dump(int fd) 3574{ 3575 const size_t SIZE = 256; 3576 char buffer[SIZE]; 3577 String8 result; 3578 3579 snprintf(buffer, SIZE, " - sampling rates: "); 3580 result.append(buffer); 3581 for (size_t i = 0; i < mSamplingRates.size(); i++) { 3582 snprintf(buffer, SIZE, "%d", mSamplingRates[i]); 3583 result.append(buffer); 3584 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", "); 3585 } 3586 3587 snprintf(buffer, SIZE, " - channel masks: "); 3588 result.append(buffer); 3589 for (size_t i = 0; i < mChannelMasks.size(); i++) { 3590 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]); 3591 result.append(buffer); 3592 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", "); 3593 } 3594 3595 snprintf(buffer, SIZE, " - formats: "); 3596 result.append(buffer); 3597 for (size_t i = 0; i < mFormats.size(); i++) { 3598 snprintf(buffer, SIZE, "0x%08x", mFormats[i]); 3599 result.append(buffer); 3600 result.append(i == (mFormats.size() - 1) ? "\n" : ", "); 3601 } 3602 3603 snprintf(buffer, SIZE, " - devices: 0x%04x\n", mSupportedDevices); 3604 result.append(buffer); 3605 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags); 3606 result.append(buffer); 3607 3608 write(fd, result.string(), result.size()); 3609} 3610 3611// --- audio_policy.conf file parsing 3612 3613struct StringToEnum { 3614 const char *name; 3615 uint32_t value; 3616}; 3617 3618#define STRING_TO_ENUM(string) { #string, string } 3619#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) 3620 3621const struct StringToEnum sDeviceNameToEnumTable[] = { 3622 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE), 3623 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER), 3624 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET), 3625 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE), 3626 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO), 3627 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP), 3628 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL), 3629 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET), 3630 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET), 3631 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE), 3632 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY), 3633 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB), 3634 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX), 3635 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC), 3636 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET), 3637 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET), 3638 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL), 3639 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL), 3640 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC), 3641 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX), 3642 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET), 3643 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET), 3644 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY), 3645}; 3646 3647const struct StringToEnum sFlagNameToEnumTable[] = { 3648 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT), 3649 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY), 3650 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST), 3651 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER), 3652 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD), 3653 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING), 3654}; 3655 3656const struct StringToEnum sFormatNameToEnumTable[] = { 3657 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT), 3658 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT), 3659 STRING_TO_ENUM(AUDIO_FORMAT_MP3), 3660 STRING_TO_ENUM(AUDIO_FORMAT_AAC), 3661 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS), 3662}; 3663 3664const struct StringToEnum sOutChannelsNameToEnumTable[] = { 3665 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO), 3666 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO), 3667 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1), 3668 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1), 3669}; 3670 3671const struct StringToEnum sInChannelsNameToEnumTable[] = { 3672 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO), 3673 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO), 3674 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK), 3675}; 3676 3677 3678uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table, 3679 size_t size, 3680 const char *name) 3681{ 3682 for (size_t i = 0; i < size; i++) { 3683 if (strcmp(table[i].name, name) == 0) { 3684 ALOGV("stringToEnum() found %s", table[i].name); 3685 return table[i].value; 3686 } 3687 } 3688 return 0; 3689} 3690 3691audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name) 3692{ 3693 uint32_t flag = 0; 3694 3695 // it is OK to cast name to non const here as we are not going to use it after 3696 // strtok() modifies it 3697 char *flagName = strtok(name, "|"); 3698 while (flagName != NULL) { 3699 if (strlen(flagName) != 0) { 3700 flag |= stringToEnum(sFlagNameToEnumTable, 3701 ARRAY_SIZE(sFlagNameToEnumTable), 3702 flagName); 3703 } 3704 flagName = strtok(NULL, "|"); 3705 } 3706 //force direct flag if offload flag is set: offloading implies a direct output stream 3707 // and all common behaviors are driven by checking only the direct flag 3708 // this should normally be set appropriately in the policy configuration file 3709 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) { 3710 flag |= AUDIO_OUTPUT_FLAG_DIRECT; 3711 } 3712 3713 return (audio_output_flags_t)flag; 3714} 3715 3716audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name) 3717{ 3718 uint32_t device = 0; 3719 3720 char *devName = strtok(name, "|"); 3721 while (devName != NULL) { 3722 if (strlen(devName) != 0) { 3723 device |= stringToEnum(sDeviceNameToEnumTable, 3724 ARRAY_SIZE(sDeviceNameToEnumTable), 3725 devName); 3726 } 3727 devName = strtok(NULL, "|"); 3728 } 3729 return device; 3730} 3731 3732void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile) 3733{ 3734 char *str = strtok(name, "|"); 3735 3736 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling 3737 // rates should be read from the output stream after it is opened for the first time 3738 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) { 3739 profile->mSamplingRates.add(0); 3740 return; 3741 } 3742 3743 while (str != NULL) { 3744 uint32_t rate = atoi(str); 3745 if (rate != 0) { 3746 ALOGV("loadSamplingRates() adding rate %d", rate); 3747 profile->mSamplingRates.add(rate); 3748 } 3749 str = strtok(NULL, "|"); 3750 } 3751 return; 3752} 3753 3754void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile) 3755{ 3756 char *str = strtok(name, "|"); 3757 3758 // by convention, "0' in the first entry in mFormats indicates the supported formats 3759 // should be read from the output stream after it is opened for the first time 3760 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) { 3761 profile->mFormats.add((audio_format_t)0); 3762 return; 3763 } 3764 3765 while (str != NULL) { 3766 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable, 3767 ARRAY_SIZE(sFormatNameToEnumTable), 3768 str); 3769 if (format != 0) { 3770 profile->mFormats.add(format); 3771 } 3772 str = strtok(NULL, "|"); 3773 } 3774 return; 3775} 3776 3777void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile) 3778{ 3779 const char *str = strtok(name, "|"); 3780 3781 ALOGV("loadInChannels() %s", name); 3782 3783 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) { 3784 profile->mChannelMasks.add((audio_channel_mask_t)0); 3785 return; 3786 } 3787 3788 while (str != NULL) { 3789 audio_channel_mask_t channelMask = 3790 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable, 3791 ARRAY_SIZE(sInChannelsNameToEnumTable), 3792 str); 3793 if (channelMask != 0) { 3794 ALOGV("loadInChannels() adding channelMask %04x", channelMask); 3795 profile->mChannelMasks.add(channelMask); 3796 } 3797 str = strtok(NULL, "|"); 3798 } 3799 return; 3800} 3801 3802void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile) 3803{ 3804 const char *str = strtok(name, "|"); 3805 3806 ALOGV("loadOutChannels() %s", name); 3807 3808 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel 3809 // masks should be read from the output stream after it is opened for the first time 3810 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) { 3811 profile->mChannelMasks.add((audio_channel_mask_t)0); 3812 return; 3813 } 3814 3815 while (str != NULL) { 3816 audio_channel_mask_t channelMask = 3817 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable, 3818 ARRAY_SIZE(sOutChannelsNameToEnumTable), 3819 str); 3820 if (channelMask != 0) { 3821 profile->mChannelMasks.add(channelMask); 3822 } 3823 str = strtok(NULL, "|"); 3824 } 3825 return; 3826} 3827 3828status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module) 3829{ 3830 cnode *node = root->first_child; 3831 3832 IOProfile *profile = new IOProfile(module); 3833 3834 while (node) { 3835 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) { 3836 loadSamplingRates((char *)node->value, profile); 3837 } else if (strcmp(node->name, FORMATS_TAG) == 0) { 3838 loadFormats((char *)node->value, profile); 3839 } else if (strcmp(node->name, CHANNELS_TAG) == 0) { 3840 loadInChannels((char *)node->value, profile); 3841 } else if (strcmp(node->name, DEVICES_TAG) == 0) { 3842 profile->mSupportedDevices = parseDeviceNames((char *)node->value); 3843 } 3844 node = node->next; 3845 } 3846 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE, 3847 "loadInput() invalid supported devices"); 3848 ALOGW_IF(profile->mChannelMasks.size() == 0, 3849 "loadInput() invalid supported channel masks"); 3850 ALOGW_IF(profile->mSamplingRates.size() == 0, 3851 "loadInput() invalid supported sampling rates"); 3852 ALOGW_IF(profile->mFormats.size() == 0, 3853 "loadInput() invalid supported formats"); 3854 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) && 3855 (profile->mChannelMasks.size() != 0) && 3856 (profile->mSamplingRates.size() != 0) && 3857 (profile->mFormats.size() != 0)) { 3858 3859 ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices); 3860 3861 module->mInputProfiles.add(profile); 3862 return NO_ERROR; 3863 } else { 3864 delete profile; 3865 return BAD_VALUE; 3866 } 3867} 3868 3869status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module) 3870{ 3871 cnode *node = root->first_child; 3872 3873 IOProfile *profile = new IOProfile(module); 3874 3875 while (node) { 3876 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) { 3877 loadSamplingRates((char *)node->value, profile); 3878 } else if (strcmp(node->name, FORMATS_TAG) == 0) { 3879 loadFormats((char *)node->value, profile); 3880 } else if (strcmp(node->name, CHANNELS_TAG) == 0) { 3881 loadOutChannels((char *)node->value, profile); 3882 } else if (strcmp(node->name, DEVICES_TAG) == 0) { 3883 profile->mSupportedDevices = parseDeviceNames((char *)node->value); 3884 } else if (strcmp(node->name, FLAGS_TAG) == 0) { 3885 profile->mFlags = parseFlagNames((char *)node->value); 3886 } 3887 node = node->next; 3888 } 3889 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE, 3890 "loadOutput() invalid supported devices"); 3891 ALOGW_IF(profile->mChannelMasks.size() == 0, 3892 "loadOutput() invalid supported channel masks"); 3893 ALOGW_IF(profile->mSamplingRates.size() == 0, 3894 "loadOutput() invalid supported sampling rates"); 3895 ALOGW_IF(profile->mFormats.size() == 0, 3896 "loadOutput() invalid supported formats"); 3897 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) && 3898 (profile->mChannelMasks.size() != 0) && 3899 (profile->mSamplingRates.size() != 0) && 3900 (profile->mFormats.size() != 0)) { 3901 3902 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x", 3903 profile->mSupportedDevices, profile->mFlags); 3904 3905 module->mOutputProfiles.add(profile); 3906 return NO_ERROR; 3907 } else { 3908 delete profile; 3909 return BAD_VALUE; 3910 } 3911} 3912 3913void AudioPolicyManagerBase::loadHwModule(cnode *root) 3914{ 3915 cnode *node = config_find(root, OUTPUTS_TAG); 3916 status_t status = NAME_NOT_FOUND; 3917 3918 HwModule *module = new HwModule(root->name); 3919 3920 if (node != NULL) { 3921 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) { 3922 mHasA2dp = true; 3923 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) { 3924 mHasUsb = true; 3925 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) { 3926 mHasRemoteSubmix = true; 3927 } 3928 3929 node = node->first_child; 3930 while (node) { 3931 ALOGV("loadHwModule() loading output %s", node->name); 3932 status_t tmpStatus = loadOutput(node, module); 3933 if (status == NAME_NOT_FOUND || status == NO_ERROR) { 3934 status = tmpStatus; 3935 } 3936 node = node->next; 3937 } 3938 } 3939 node = config_find(root, INPUTS_TAG); 3940 if (node != NULL) { 3941 node = node->first_child; 3942 while (node) { 3943 ALOGV("loadHwModule() loading input %s", node->name); 3944 status_t tmpStatus = loadInput(node, module); 3945 if (status == NAME_NOT_FOUND || status == NO_ERROR) { 3946 status = tmpStatus; 3947 } 3948 node = node->next; 3949 } 3950 } 3951 if (status == NO_ERROR) { 3952 mHwModules.add(module); 3953 } else { 3954 delete module; 3955 } 3956} 3957 3958void AudioPolicyManagerBase::loadHwModules(cnode *root) 3959{ 3960 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG); 3961 if (node == NULL) { 3962 return; 3963 } 3964 3965 node = node->first_child; 3966 while (node) { 3967 ALOGV("loadHwModules() loading module %s", node->name); 3968 loadHwModule(node); 3969 node = node->next; 3970 } 3971} 3972 3973void AudioPolicyManagerBase::loadGlobalConfig(cnode *root) 3974{ 3975 cnode *node = config_find(root, GLOBAL_CONFIG_TAG); 3976 if (node == NULL) { 3977 return; 3978 } 3979 node = node->first_child; 3980 while (node) { 3981 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) { 3982 mAttachedOutputDevices = parseDeviceNames((char *)node->value); 3983 ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE, 3984 "loadGlobalConfig() no attached output devices"); 3985 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices); 3986 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) { 3987 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable, 3988 ARRAY_SIZE(sDeviceNameToEnumTable), 3989 (char *)node->value); 3990 ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE, 3991 "loadGlobalConfig() default device not specified"); 3992 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice); 3993 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) { 3994 mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN; 3995 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices); 3996 } 3997 node = node->next; 3998 } 3999} 4000 4001status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path) 4002{ 4003 cnode *root; 4004 char *data; 4005 4006 data = (char *)load_file(path, NULL); 4007 if (data == NULL) { 4008 return -ENODEV; 4009 } 4010 root = config_node("", ""); 4011 config_load(root, data); 4012 4013 loadGlobalConfig(root); 4014 loadHwModules(root); 4015 4016 config_free(root); 4017 free(root); 4018 free(data); 4019 4020 ALOGI("loadAudioPolicyConfig() loaded %s\n", path); 4021 4022 return NO_ERROR; 4023} 4024 4025void AudioPolicyManagerBase::defaultAudioPolicyConfig(void) 4026{ 4027 HwModule *module; 4028 IOProfile *profile; 4029 4030 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER; 4031 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER; 4032 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC & ~AUDIO_DEVICE_BIT_IN; 4033 4034 module = new HwModule("primary"); 4035 4036 profile = new IOProfile(module); 4037 profile->mSamplingRates.add(44100); 4038 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT); 4039 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO); 4040 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER; 4041 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY; 4042 module->mOutputProfiles.add(profile); 4043 4044 profile = new IOProfile(module); 4045 profile->mSamplingRates.add(8000); 4046 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT); 4047 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO); 4048 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC; 4049 module->mInputProfiles.add(profile); 4050 4051 mHwModules.add(module); 4052} 4053 4054}; // namespace android 4055