AudioPolicyManagerBase.cpp revision 5efbd421e0029d6fc44b1cc65c0e5e0d85e5161f
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#include <utils/Log.h> 20#include <hardware_legacy/AudioPolicyManagerBase.h> 21#include <hardware/audio_effect.h> 22#include <math.h> 23 24namespace android_audio_legacy { 25 26// ---------------------------------------------------------------------------- 27// AudioPolicyInterface implementation 28// ---------------------------------------------------------------------------- 29 30 31status_t AudioPolicyManagerBase::setDeviceConnectionState(AudioSystem::audio_devices device, 32 AudioSystem::device_connection_state state, 33 const char *device_address) 34{ 35 36 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address); 37 38 // connect/disconnect only 1 device at a time 39 if (AudioSystem::popCount(device) != 1) return BAD_VALUE; 40 41 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) { 42 ALOGE("setDeviceConnectionState() invalid address: %s", device_address); 43 return BAD_VALUE; 44 } 45 46 // handle output devices 47 if (AudioSystem::isOutputDevice(device)) { 48 49#ifndef WITH_A2DP 50 if (AudioSystem::isA2dpDevice(device)) { 51 ALOGE("setDeviceConnectionState() invalid device: %x", device); 52 return BAD_VALUE; 53 } 54#endif 55 56 switch (state) 57 { 58 // handle output device connection 59 case AudioSystem::DEVICE_STATE_AVAILABLE: 60 if (mAvailableOutputDevices & device) { 61 ALOGW("setDeviceConnectionState() device already connected: %x", device); 62 return INVALID_OPERATION; 63 } 64 ALOGV("setDeviceConnectionState() connecting device %x", device); 65 66 // register new device as available 67 mAvailableOutputDevices |= device; 68 69#ifdef WITH_A2DP 70 // handle A2DP device connection 71 if (AudioSystem::isA2dpDevice(device)) { 72 status_t status = handleA2dpConnection(device, device_address); 73 if (status != NO_ERROR) { 74 mAvailableOutputDevices &= ~device; 75 return status; 76 } 77 } else 78#endif 79 { 80 if (AudioSystem::isBluetoothScoDevice(device)) { 81 ALOGV("setDeviceConnectionState() BT SCO device, address %s", device_address); 82 // keep track of SCO device address 83 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN); 84 } 85 } 86 break; 87 // handle output device disconnection 88 case AudioSystem::DEVICE_STATE_UNAVAILABLE: { 89 if (!(mAvailableOutputDevices & device)) { 90 ALOGW("setDeviceConnectionState() device not connected: %x", device); 91 return INVALID_OPERATION; 92 } 93 94 95 ALOGV("setDeviceConnectionState() disconnecting device %x", device); 96 // remove device from available output devices 97 mAvailableOutputDevices &= ~device; 98 99#ifdef WITH_A2DP 100 // handle A2DP device disconnection 101 if (AudioSystem::isA2dpDevice(device)) { 102 status_t status = handleA2dpDisconnection(device, device_address); 103 if (status != NO_ERROR) { 104 mAvailableOutputDevices |= device; 105 return status; 106 } 107 } else 108#endif 109 { 110 if (AudioSystem::isBluetoothScoDevice(device)) { 111 mScoDeviceAddress = ""; 112 } 113 } 114 } break; 115 116 default: 117 ALOGE("setDeviceConnectionState() invalid state: %x", state); 118 return BAD_VALUE; 119 } 120 121 // request routing change if necessary 122 uint32_t newDevice = getNewDevice(mHardwareOutput, false); 123#ifdef WITH_A2DP 124 checkA2dpSuspend(); 125 checkOutputForAllStrategies(); 126 // A2DP outputs must be closed after checkOutputForAllStrategies() is executed 127 if (state == AudioSystem::DEVICE_STATE_UNAVAILABLE && AudioSystem::isA2dpDevice(device)) { 128 closeA2dpOutputs(); 129 } 130#endif 131 updateDeviceForStrategy(); 132 setOutputDevice(mHardwareOutput, newDevice); 133 134 if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET) { 135 device = AudioSystem::DEVICE_IN_WIRED_HEADSET; 136 } else if (device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO || 137 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET || 138 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) { 139 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET; 140 } else { 141 return NO_ERROR; 142 } 143 } 144 // handle input devices 145 if (AudioSystem::isInputDevice(device)) { 146 147 switch (state) 148 { 149 // handle input device connection 150 case AudioSystem::DEVICE_STATE_AVAILABLE: { 151 if (mAvailableInputDevices & device) { 152 ALOGW("setDeviceConnectionState() device already connected: %d", device); 153 return INVALID_OPERATION; 154 } 155 mAvailableInputDevices |= device; 156 } 157 break; 158 159 // handle input device disconnection 160 case AudioSystem::DEVICE_STATE_UNAVAILABLE: { 161 if (!(mAvailableInputDevices & device)) { 162 ALOGW("setDeviceConnectionState() device not connected: %d", device); 163 return INVALID_OPERATION; 164 } 165 mAvailableInputDevices &= ~device; 166 } break; 167 168 default: 169 ALOGE("setDeviceConnectionState() invalid state: %x", state); 170 return BAD_VALUE; 171 } 172 173 audio_io_handle_t activeInput = getActiveInput(); 174 if (activeInput != 0) { 175 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput); 176 uint32_t newDevice = getDeviceForInputSource(inputDesc->mInputSource); 177 if (newDevice != inputDesc->mDevice) { 178 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d", 179 inputDesc->mDevice, newDevice, activeInput); 180 inputDesc->mDevice = newDevice; 181 AudioParameter param = AudioParameter(); 182 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice); 183 mpClientInterface->setParameters(activeInput, param.toString()); 184 } 185 } 186 187 return NO_ERROR; 188 } 189 190 ALOGW("setDeviceConnectionState() invalid device: %x", device); 191 return BAD_VALUE; 192} 193 194AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(AudioSystem::audio_devices device, 195 const char *device_address) 196{ 197 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE; 198 String8 address = String8(device_address); 199 if (AudioSystem::isOutputDevice(device)) { 200 if (device & mAvailableOutputDevices) { 201#ifdef WITH_A2DP 202 if (AudioSystem::isA2dpDevice(device) && 203 address != "" && mA2dpDeviceAddress != address) { 204 return state; 205 } 206#endif 207 if (AudioSystem::isBluetoothScoDevice(device) && 208 address != "" && mScoDeviceAddress != address) { 209 return state; 210 } 211 state = AudioSystem::DEVICE_STATE_AVAILABLE; 212 } 213 } else if (AudioSystem::isInputDevice(device)) { 214 if (device & mAvailableInputDevices) { 215 state = AudioSystem::DEVICE_STATE_AVAILABLE; 216 } 217 } 218 219 return state; 220} 221 222void AudioPolicyManagerBase::setPhoneState(int state) 223{ 224 ALOGV("setPhoneState() state %d", state); 225 uint32_t newDevice = 0; 226 if (state < 0 || state >= AudioSystem::NUM_MODES) { 227 ALOGW("setPhoneState() invalid state %d", state); 228 return; 229 } 230 231 if (state == mPhoneState ) { 232 ALOGW("setPhoneState() setting same state %d", state); 233 return; 234 } 235 236 // if leaving call state, handle special case of active streams 237 // pertaining to sonification strategy see handleIncallSonification() 238 if (isInCall()) { 239 ALOGV("setPhoneState() in call state management: new state is %d", state); 240 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) { 241 handleIncallSonification(stream, false, true); 242 } 243 } 244 245 // store previous phone state for management of sonification strategy below 246 int oldState = mPhoneState; 247 mPhoneState = state; 248 bool force = false; 249 250 // are we entering or starting a call 251 if (!isStateInCall(oldState) && isStateInCall(state)) { 252 ALOGV(" Entering call in setPhoneState()"); 253 // force routing command to audio hardware when starting a call 254 // even if no device change is needed 255 force = true; 256 } else if (isStateInCall(oldState) && !isStateInCall(state)) { 257 ALOGV(" Exiting call in setPhoneState()"); 258 // force routing command to audio hardware when exiting a call 259 // even if no device change is needed 260 force = true; 261 } else if (isStateInCall(state) && (state != oldState)) { 262 ALOGV(" Switching between telephony and VoIP in setPhoneState()"); 263 // force routing command to audio hardware when switching between telephony and VoIP 264 // even if no device change is needed 265 force = true; 266 } 267 268 // check for device and output changes triggered by new phone state 269 newDevice = getNewDevice(mHardwareOutput, false); 270#ifdef WITH_A2DP 271 checkA2dpSuspend(); 272 checkOutputForAllStrategies(); 273#endif 274 updateDeviceForStrategy(); 275 276 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput); 277 278 // force routing command to audio hardware when ending call 279 // even if no device change is needed 280 if (isStateInCall(oldState) && newDevice == 0) { 281 newDevice = hwOutputDesc->device(); 282 } 283 284 // when changing from ring tone to in call mode, mute the ringing tone 285 // immediately and delay the route change to avoid sending the ring tone 286 // tail into the earpiece or headset. 287 int delayMs = 0; 288 if (isStateInCall(state) && oldState == AudioSystem::MODE_RINGTONE) { 289 // delay the device change command by twice the output latency to have some margin 290 // and be sure that audio buffers not yet affected by the mute are out when 291 // we actually apply the route change 292 delayMs = hwOutputDesc->mLatency*2; 293 setStreamMute(AudioSystem::RING, true, mHardwareOutput); 294 } 295 296 // change routing is necessary 297 setOutputDevice(mHardwareOutput, newDevice, force, delayMs); 298 299 // if entering in call state, handle special case of active streams 300 // pertaining to sonification strategy see handleIncallSonification() 301 if (isStateInCall(state)) { 302 ALOGV("setPhoneState() in call state management: new state is %d", state); 303 // unmute the ringing tone after a sufficient delay if it was muted before 304 // setting output device above 305 if (oldState == AudioSystem::MODE_RINGTONE) { 306 setStreamMute(AudioSystem::RING, false, mHardwareOutput, MUTE_TIME_MS); 307 } 308 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) { 309 handleIncallSonification(stream, true, true); 310 } 311 } 312 313 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE 314 if (state == AudioSystem::MODE_RINGTONE && 315 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) { 316 mLimitRingtoneVolume = true; 317 } else { 318 mLimitRingtoneVolume = false; 319 } 320} 321 322void AudioPolicyManagerBase::setRingerMode(uint32_t mode, uint32_t mask) 323{ 324 ALOGV("setRingerMode() mode %x, mask %x", mode, mask); 325 326 mRingerMode = mode; 327} 328 329void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config) 330{ 331 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState); 332 333 bool forceVolumeReeval = false; 334 switch(usage) { 335 case AudioSystem::FOR_COMMUNICATION: 336 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO && 337 config != AudioSystem::FORCE_NONE) { 338 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config); 339 return; 340 } 341 forceVolumeReeval = true; 342 mForceUse[usage] = config; 343 break; 344 case AudioSystem::FOR_MEDIA: 345 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP && 346 config != AudioSystem::FORCE_WIRED_ACCESSORY && 347 config != AudioSystem::FORCE_ANALOG_DOCK && 348 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE) { 349 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config); 350 return; 351 } 352 mForceUse[usage] = config; 353 break; 354 case AudioSystem::FOR_RECORD: 355 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY && 356 config != AudioSystem::FORCE_NONE) { 357 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config); 358 return; 359 } 360 mForceUse[usage] = config; 361 break; 362 case AudioSystem::FOR_DOCK: 363 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK && 364 config != AudioSystem::FORCE_BT_DESK_DOCK && 365 config != AudioSystem::FORCE_WIRED_ACCESSORY && 366 config != AudioSystem::FORCE_ANALOG_DOCK && 367 config != AudioSystem::FORCE_DIGITAL_DOCK) { 368 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config); 369 } 370 forceVolumeReeval = true; 371 mForceUse[usage] = config; 372 break; 373 default: 374 ALOGW("setForceUse() invalid usage %d", usage); 375 break; 376 } 377 378 // check for device and output changes triggered by new phone state 379 uint32_t newDevice = getNewDevice(mHardwareOutput, false); 380#ifdef WITH_A2DP 381 checkA2dpSuspend(); 382 checkOutputForAllStrategies(); 383#endif 384 updateDeviceForStrategy(); 385 setOutputDevice(mHardwareOutput, newDevice); 386 if (forceVolumeReeval) { 387 applyStreamVolumes(mHardwareOutput, newDevice, 0, true); 388 } 389 390 audio_io_handle_t activeInput = getActiveInput(); 391 if (activeInput != 0) { 392 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput); 393 newDevice = getDeviceForInputSource(inputDesc->mInputSource); 394 if (newDevice != inputDesc->mDevice) { 395 ALOGV("setForceUse() changing device from %x to %x for input %d", 396 inputDesc->mDevice, newDevice, activeInput); 397 inputDesc->mDevice = newDevice; 398 AudioParameter param = AudioParameter(); 399 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice); 400 mpClientInterface->setParameters(activeInput, param.toString()); 401 } 402 } 403 404} 405 406AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage) 407{ 408 return mForceUse[usage]; 409} 410 411void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value) 412{ 413 ALOGV("setSystemProperty() property %s, value %s", property, value); 414 if (strcmp(property, "ro.camera.sound.forced") == 0) { 415 if (atoi(value)) { 416 ALOGV("ENFORCED_AUDIBLE cannot be muted"); 417 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false; 418 } else { 419 ALOGV("ENFORCED_AUDIBLE can be muted"); 420 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = true; 421 } 422 } 423} 424 425audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream, 426 uint32_t samplingRate, 427 uint32_t format, 428 uint32_t channels, 429 AudioSystem::output_flags flags) 430{ 431 audio_io_handle_t output = 0; 432 uint32_t latency = 0; 433 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream); 434 uint32_t device = getDeviceForStrategy(strategy); 435 ALOGV("getOutput() stream %d, samplingRate %d, format %d, channels %x, flags %x", stream, samplingRate, format, channels, flags); 436 437#ifdef AUDIO_POLICY_TEST 438 if (mCurOutput != 0) { 439 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channels %x, mDirectOutput %d", 440 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput); 441 442 if (mTestOutputs[mCurOutput] == 0) { 443 ALOGV("getOutput() opening test output"); 444 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(); 445 outputDesc->mDevice = mTestDevice; 446 outputDesc->mSamplingRate = mTestSamplingRate; 447 outputDesc->mFormat = mTestFormat; 448 outputDesc->mChannels = mTestChannels; 449 outputDesc->mLatency = mTestLatencyMs; 450 outputDesc->mFlags = (AudioSystem::output_flags)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0); 451 outputDesc->mRefCount[stream] = 0; 452 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(&outputDesc->mDevice, 453 &outputDesc->mSamplingRate, 454 &outputDesc->mFormat, 455 &outputDesc->mChannels, 456 &outputDesc->mLatency, 457 outputDesc->mFlags); 458 if (mTestOutputs[mCurOutput]) { 459 AudioParameter outputCmd = AudioParameter(); 460 outputCmd.addInt(String8("set_id"),mCurOutput); 461 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString()); 462 addOutput(mTestOutputs[mCurOutput], outputDesc); 463 } 464 } 465 return mTestOutputs[mCurOutput]; 466 } 467#endif //AUDIO_POLICY_TEST 468 469 // open a direct output if required by specified parameters 470 if (needsDirectOuput(stream, samplingRate, format, channels, flags, device)) { 471 472 ALOGV("getOutput() opening direct output device %x", device); 473 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(); 474 outputDesc->mDevice = device; 475 outputDesc->mSamplingRate = samplingRate; 476 outputDesc->mFormat = format; 477 outputDesc->mChannels = channels; 478 outputDesc->mLatency = 0; 479 outputDesc->mFlags = (AudioSystem::output_flags)(flags | AudioSystem::OUTPUT_FLAG_DIRECT); 480 outputDesc->mRefCount[stream] = 0; 481 outputDesc->mStopTime[stream] = 0; 482 output = mpClientInterface->openOutput(&outputDesc->mDevice, 483 &outputDesc->mSamplingRate, 484 &outputDesc->mFormat, 485 &outputDesc->mChannels, 486 &outputDesc->mLatency, 487 outputDesc->mFlags); 488 489 // only accept an output with the requeted parameters 490 if (output == 0 || 491 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) || 492 (format != 0 && format != outputDesc->mFormat) || 493 (channels != 0 && channels != outputDesc->mChannels)) { 494 ALOGV("getOutput() failed opening direct output: samplingRate %d, format %d, channels %d", 495 samplingRate, format, channels); 496 if (output != 0) { 497 mpClientInterface->closeOutput(output); 498 } 499 delete outputDesc; 500 return 0; 501 } 502 addOutput(output, outputDesc); 503 return output; 504 } 505 506 if (channels != 0 && channels != AudioSystem::CHANNEL_OUT_MONO && 507 channels != AudioSystem::CHANNEL_OUT_STEREO) { 508 return 0; 509 } 510 // open a non direct output 511 512 // get which output is suitable for the specified stream. The actual routing change will happen 513 // when startOutput() will be called 514 uint32_t a2dpDevice = device & AudioSystem::DEVICE_OUT_ALL_A2DP; 515 if (AudioSystem::popCount((AudioSystem::audio_devices)device) == 2) { 516#ifdef WITH_A2DP 517 if (a2dpUsedForSonification() && a2dpDevice != 0) { 518 // if playing on 2 devices among which one is A2DP, use duplicated output 519 ALOGV("getOutput() using duplicated output"); 520 ALOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device in multiple %x selected but A2DP output not opened", device); 521 output = mDuplicatedOutput; 522 } else 523#endif 524 { 525 // if playing on 2 devices among which none is A2DP, use hardware output 526 output = mHardwareOutput; 527 } 528 ALOGV("getOutput() using output %d for 2 devices %x", output, device); 529 } else { 530#ifdef WITH_A2DP 531 if (a2dpDevice != 0) { 532 // if playing on A2DP device, use a2dp output 533 ALOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device %x selected but A2DP output not opened", device); 534 output = mA2dpOutput; 535 } else 536#endif 537 { 538 // if playing on not A2DP device, use hardware output 539 output = mHardwareOutput; 540 } 541 } 542 543 544 ALOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d, format %d, channels %x, flags %x", 545 stream, samplingRate, format, channels, flags); 546 547 return output; 548} 549 550status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output, 551 AudioSystem::stream_type stream, 552 int session) 553{ 554 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session); 555 ssize_t index = mOutputs.indexOfKey(output); 556 if (index < 0) { 557 ALOGW("startOutput() unknow output %d", output); 558 return BAD_VALUE; 559 } 560 561 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index); 562 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream); 563 564#ifdef WITH_A2DP 565 if (mA2dpOutput != 0 && !a2dpUsedForSonification() && 566 (strategy == STRATEGY_SONIFICATION || strategy == STRATEGY_ENFORCED_AUDIBLE)) { 567 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput); 568 } 569#endif 570 571 // incremenent usage count for this stream on the requested output: 572 // NOTE that the usage count is the same for duplicated output and hardware output which is 573 // necassary for a correct control of hardware output routing by startOutput() and stopOutput() 574 outputDesc->changeRefCount(stream, 1); 575 576 uint32_t prevDevice = outputDesc->mDevice; 577 setOutputDevice(output, getNewDevice(output)); 578 579 // handle special case for sonification while in call 580 if (isInCall()) { 581 handleIncallSonification(stream, true, false); 582 } 583 584 // apply volume rules for current stream and device if necessary 585 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, outputDesc->device()); 586 587 // FIXME: need a delay to make sure that audio path switches to speaker before sound 588 // starts. Should be platform specific? 589 if (stream == AudioSystem::ENFORCED_AUDIBLE && 590 prevDevice != outputDesc->mDevice) { 591 usleep(outputDesc->mLatency*4*1000); 592 } 593 594 return NO_ERROR; 595} 596 597status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output, 598 AudioSystem::stream_type stream, 599 int session) 600{ 601 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session); 602 ssize_t index = mOutputs.indexOfKey(output); 603 if (index < 0) { 604 ALOGW("stopOutput() unknow output %d", output); 605 return BAD_VALUE; 606 } 607 608 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index); 609 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream); 610 611 // handle special case for sonification while in call 612 if (isInCall()) { 613 handleIncallSonification(stream, false, false); 614 } 615 616 if (outputDesc->mRefCount[stream] > 0) { 617 // decrement usage count of this stream on the output 618 outputDesc->changeRefCount(stream, -1); 619 // store time at which the stream was stopped - see isStreamActive() 620 outputDesc->mStopTime[stream] = systemTime(); 621 622 setOutputDevice(output, getNewDevice(output), false, outputDesc->mLatency*2); 623 624#ifdef WITH_A2DP 625 if (mA2dpOutput != 0 && !a2dpUsedForSonification() && 626 (strategy == STRATEGY_SONIFICATION || strategy == STRATEGY_ENFORCED_AUDIBLE)) { 627 setStrategyMute(STRATEGY_MEDIA, 628 false, 629 mA2dpOutput, 630 mOutputs.valueFor(mHardwareOutput)->mLatency*2); 631 } 632#endif 633 if (output != mHardwareOutput) { 634 setOutputDevice(mHardwareOutput, getNewDevice(mHardwareOutput), true); 635 } 636 return NO_ERROR; 637 } else { 638 ALOGW("stopOutput() refcount is already 0 for output %d", output); 639 return INVALID_OPERATION; 640 } 641} 642 643void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output) 644{ 645 ALOGV("releaseOutput() %d", output); 646 ssize_t index = mOutputs.indexOfKey(output); 647 if (index < 0) { 648 ALOGW("releaseOutput() releasing unknown output %d", output); 649 return; 650 } 651 652#ifdef AUDIO_POLICY_TEST 653 int testIndex = testOutputIndex(output); 654 if (testIndex != 0) { 655 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index); 656 if (outputDesc->refCount() == 0) { 657 mpClientInterface->closeOutput(output); 658 delete mOutputs.valueAt(index); 659 mOutputs.removeItem(output); 660 mTestOutputs[testIndex] = 0; 661 } 662 return; 663 } 664#endif //AUDIO_POLICY_TEST 665 666 if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) { 667 mpClientInterface->closeOutput(output); 668 delete mOutputs.valueAt(index); 669 mOutputs.removeItem(output); 670 } 671} 672 673audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource, 674 uint32_t samplingRate, 675 uint32_t format, 676 uint32_t channels, 677 AudioSystem::audio_in_acoustics acoustics) 678{ 679 audio_io_handle_t input = 0; 680 uint32_t device = getDeviceForInputSource(inputSource); 681 682 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channels %x, acoustics %x", inputSource, samplingRate, format, channels, acoustics); 683 684 if (device == 0) { 685 return 0; 686 } 687 688 // adapt channel selection to input source 689 switch(inputSource) { 690 case AUDIO_SOURCE_VOICE_UPLINK: 691 channels = AudioSystem::CHANNEL_IN_VOICE_UPLINK; 692 break; 693 case AUDIO_SOURCE_VOICE_DOWNLINK: 694 channels = AudioSystem::CHANNEL_IN_VOICE_DNLINK; 695 break; 696 case AUDIO_SOURCE_VOICE_CALL: 697 channels = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK); 698 break; 699 default: 700 break; 701 } 702 703 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(); 704 705 inputDesc->mInputSource = inputSource; 706 inputDesc->mDevice = device; 707 inputDesc->mSamplingRate = samplingRate; 708 inputDesc->mFormat = format; 709 inputDesc->mChannels = channels; 710 inputDesc->mAcoustics = acoustics; 711 inputDesc->mRefCount = 0; 712 input = mpClientInterface->openInput(&inputDesc->mDevice, 713 &inputDesc->mSamplingRate, 714 &inputDesc->mFormat, 715 &inputDesc->mChannels, 716 inputDesc->mAcoustics); 717 718 // only accept input with the exact requested set of parameters 719 if (input == 0 || 720 (samplingRate != inputDesc->mSamplingRate) || 721 (format != inputDesc->mFormat) || 722 (channels != inputDesc->mChannels)) { 723 ALOGV("getInput() failed opening input: samplingRate %d, format %d, channels %d", 724 samplingRate, format, channels); 725 if (input != 0) { 726 mpClientInterface->closeInput(input); 727 } 728 delete inputDesc; 729 return 0; 730 } 731 mInputs.add(input, inputDesc); 732 return input; 733} 734 735status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input) 736{ 737 ALOGV("startInput() input %d", input); 738 ssize_t index = mInputs.indexOfKey(input); 739 if (index < 0) { 740 ALOGW("startInput() unknow input %d", input); 741 return BAD_VALUE; 742 } 743 AudioInputDescriptor *inputDesc = mInputs.valueAt(index); 744 745#ifdef AUDIO_POLICY_TEST 746 if (mTestInput == 0) 747#endif //AUDIO_POLICY_TEST 748 { 749 // refuse 2 active AudioRecord clients at the same time 750 if (getActiveInput() != 0) { 751 ALOGW("startInput() input %d failed: other input already started", input); 752 return INVALID_OPERATION; 753 } 754 } 755 756 AudioParameter param = AudioParameter(); 757 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice); 758 759 param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource); 760 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource); 761 762 mpClientInterface->setParameters(input, param.toString()); 763 764 inputDesc->mRefCount = 1; 765 return NO_ERROR; 766} 767 768status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input) 769{ 770 ALOGV("stopInput() input %d", input); 771 ssize_t index = mInputs.indexOfKey(input); 772 if (index < 0) { 773 ALOGW("stopInput() unknow input %d", input); 774 return BAD_VALUE; 775 } 776 AudioInputDescriptor *inputDesc = mInputs.valueAt(index); 777 778 if (inputDesc->mRefCount == 0) { 779 ALOGW("stopInput() input %d already stopped", input); 780 return INVALID_OPERATION; 781 } else { 782 AudioParameter param = AudioParameter(); 783 param.addInt(String8(AudioParameter::keyRouting), 0); 784 mpClientInterface->setParameters(input, param.toString()); 785 inputDesc->mRefCount = 0; 786 return NO_ERROR; 787 } 788} 789 790void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input) 791{ 792 ALOGV("releaseInput() %d", input); 793 ssize_t index = mInputs.indexOfKey(input); 794 if (index < 0) { 795 ALOGW("releaseInput() releasing unknown input %d", input); 796 return; 797 } 798 mpClientInterface->closeInput(input); 799 delete mInputs.valueAt(index); 800 mInputs.removeItem(input); 801 ALOGV("releaseInput() exit"); 802} 803 804void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream, 805 int indexMin, 806 int indexMax) 807{ 808 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax); 809 if (indexMin < 0 || indexMin >= indexMax) { 810 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax); 811 return; 812 } 813 mStreams[stream].mIndexMin = indexMin; 814 mStreams[stream].mIndexMax = indexMax; 815} 816 817status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream, int index) 818{ 819 820 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) { 821 return BAD_VALUE; 822 } 823 824 // Force max volume if stream cannot be muted 825 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax; 826 827 ALOGV("setStreamVolumeIndex() stream %d, index %d", stream, index); 828 mStreams[stream].mIndexCur = index; 829 830 // compute and apply stream volume on all outputs according to connected device 831 status_t status = NO_ERROR; 832 for (size_t i = 0; i < mOutputs.size(); i++) { 833 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), mOutputs.valueAt(i)->device()); 834 if (volStatus != NO_ERROR) { 835 status = volStatus; 836 } 837 } 838 return status; 839} 840 841status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream, int *index) 842{ 843 if (index == 0) { 844 return BAD_VALUE; 845 } 846 ALOGV("getStreamVolumeIndex() stream %d", stream); 847 *index = mStreams[stream].mIndexCur; 848 return NO_ERROR; 849} 850 851audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(effect_descriptor_t *desc) 852{ 853 ALOGV("getOutputForEffect()"); 854 // apply simple rule where global effects are attached to the same output as MUSIC streams 855 return getOutput(AudioSystem::MUSIC); 856} 857 858status_t AudioPolicyManagerBase::registerEffect(effect_descriptor_t *desc, 859 audio_io_handle_t io, 860 uint32_t strategy, 861 int session, 862 int id) 863{ 864 ssize_t index = mOutputs.indexOfKey(io); 865 if (index < 0) { 866 index = mInputs.indexOfKey(io); 867 if (index < 0) { 868 ALOGW("registerEffect() unknown io %d", io); 869 return INVALID_OPERATION; 870 } 871 } 872 873 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) { 874 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB", 875 desc->name, desc->memoryUsage); 876 return INVALID_OPERATION; 877 } 878 mTotalEffectsMemory += desc->memoryUsage; 879 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d", 880 desc->name, io, strategy, session, id); 881 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory); 882 883 EffectDescriptor *pDesc = new EffectDescriptor(); 884 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t)); 885 pDesc->mIo = io; 886 pDesc->mStrategy = (routing_strategy)strategy; 887 pDesc->mSession = session; 888 pDesc->mEnabled = false; 889 890 mEffects.add(id, pDesc); 891 892 return NO_ERROR; 893} 894 895status_t AudioPolicyManagerBase::unregisterEffect(int id) 896{ 897 ssize_t index = mEffects.indexOfKey(id); 898 if (index < 0) { 899 ALOGW("unregisterEffect() unknown effect ID %d", id); 900 return INVALID_OPERATION; 901 } 902 903 EffectDescriptor *pDesc = mEffects.valueAt(index); 904 905 setEffectEnabled(pDesc, false); 906 907 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) { 908 ALOGW("unregisterEffect() memory %d too big for total %d", 909 pDesc->mDesc.memoryUsage, mTotalEffectsMemory); 910 pDesc->mDesc.memoryUsage = mTotalEffectsMemory; 911 } 912 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage; 913 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d", 914 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory); 915 916 mEffects.removeItem(id); 917 delete pDesc; 918 919 return NO_ERROR; 920} 921 922status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled) 923{ 924 ssize_t index = mEffects.indexOfKey(id); 925 if (index < 0) { 926 ALOGW("unregisterEffect() unknown effect ID %d", id); 927 return INVALID_OPERATION; 928 } 929 930 return setEffectEnabled(mEffects.valueAt(index), enabled); 931} 932 933status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled) 934{ 935 if (enabled == pDesc->mEnabled) { 936 ALOGV("setEffectEnabled(%s) effect already %s", 937 enabled?"true":"false", enabled?"enabled":"disabled"); 938 return INVALID_OPERATION; 939 } 940 941 if (enabled) { 942 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) { 943 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS", 944 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10); 945 return INVALID_OPERATION; 946 } 947 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad; 948 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad); 949 } else { 950 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) { 951 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d", 952 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad); 953 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad; 954 } 955 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad; 956 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad); 957 } 958 pDesc->mEnabled = enabled; 959 return NO_ERROR; 960} 961 962bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const 963{ 964 nsecs_t sysTime = systemTime(); 965 for (size_t i = 0; i < mOutputs.size(); i++) { 966 if (mOutputs.valueAt(i)->mRefCount[stream] != 0 || 967 ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) { 968 return true; 969 } 970 } 971 return false; 972} 973 974 975status_t AudioPolicyManagerBase::dump(int fd) 976{ 977 const size_t SIZE = 256; 978 char buffer[SIZE]; 979 String8 result; 980 981 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this); 982 result.append(buffer); 983 snprintf(buffer, SIZE, " Hardware Output: %d\n", mHardwareOutput); 984 result.append(buffer); 985#ifdef WITH_A2DP 986 snprintf(buffer, SIZE, " A2DP Output: %d\n", mA2dpOutput); 987 result.append(buffer); 988 snprintf(buffer, SIZE, " Duplicated Output: %d\n", mDuplicatedOutput); 989 result.append(buffer); 990 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string()); 991 result.append(buffer); 992#endif 993 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string()); 994 result.append(buffer); 995 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices); 996 result.append(buffer); 997 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices); 998 result.append(buffer); 999 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState); 1000 result.append(buffer); 1001// disable ringer mode dump until it is actually passed by AudioService when needed. 1002// snprintf(buffer, SIZE, " Ringer mode: %d\n", mRingerMode); 1003// result.append(buffer); 1004 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]); 1005 result.append(buffer); 1006 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]); 1007 result.append(buffer); 1008 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]); 1009 result.append(buffer); 1010 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]); 1011 result.append(buffer); 1012 write(fd, result.string(), result.size()); 1013 1014 snprintf(buffer, SIZE, "\nOutputs dump:\n"); 1015 write(fd, buffer, strlen(buffer)); 1016 for (size_t i = 0; i < mOutputs.size(); i++) { 1017 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i)); 1018 write(fd, buffer, strlen(buffer)); 1019 mOutputs.valueAt(i)->dump(fd); 1020 } 1021 1022 snprintf(buffer, SIZE, "\nInputs dump:\n"); 1023 write(fd, buffer, strlen(buffer)); 1024 for (size_t i = 0; i < mInputs.size(); i++) { 1025 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i)); 1026 write(fd, buffer, strlen(buffer)); 1027 mInputs.valueAt(i)->dump(fd); 1028 } 1029 1030 snprintf(buffer, SIZE, "\nStreams dump:\n"); 1031 write(fd, buffer, strlen(buffer)); 1032 snprintf(buffer, SIZE, " Stream Index Min Index Max Index Cur Can be muted\n"); 1033 write(fd, buffer, strlen(buffer)); 1034 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) { 1035 snprintf(buffer, SIZE, " %02d", i); 1036 mStreams[i].dump(buffer + 3, SIZE); 1037 write(fd, buffer, strlen(buffer)); 1038 } 1039 1040 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n", 1041 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory); 1042 write(fd, buffer, strlen(buffer)); 1043 1044 snprintf(buffer, SIZE, "Registered effects:\n"); 1045 write(fd, buffer, strlen(buffer)); 1046 for (size_t i = 0; i < mEffects.size(); i++) { 1047 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i)); 1048 write(fd, buffer, strlen(buffer)); 1049 mEffects.valueAt(i)->dump(fd); 1050 } 1051 1052 1053 return NO_ERROR; 1054} 1055 1056// ---------------------------------------------------------------------------- 1057// AudioPolicyManagerBase 1058// ---------------------------------------------------------------------------- 1059 1060AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface) 1061 : 1062#ifdef AUDIO_POLICY_TEST 1063 Thread(false), 1064#endif //AUDIO_POLICY_TEST 1065 mPhoneState(AudioSystem::MODE_NORMAL), mRingerMode(0), 1066 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f), 1067 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0), 1068 mA2dpSuspended(false) 1069{ 1070 mpClientInterface = clientInterface; 1071 1072 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) { 1073 mForceUse[i] = AudioSystem::FORCE_NONE; 1074 } 1075 1076 initializeVolumeCurves(); 1077 1078 // devices available by default are speaker, ear piece and microphone 1079 mAvailableOutputDevices = AudioSystem::DEVICE_OUT_EARPIECE | 1080 AudioSystem::DEVICE_OUT_SPEAKER; 1081 mAvailableInputDevices = AudioSystem::DEVICE_IN_BUILTIN_MIC; 1082 1083#ifdef WITH_A2DP 1084 mA2dpOutput = 0; 1085 mDuplicatedOutput = 0; 1086 mA2dpDeviceAddress = String8(""); 1087#endif 1088 mScoDeviceAddress = String8(""); 1089 1090 // open hardware output 1091 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(); 1092 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER; 1093 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice, 1094 &outputDesc->mSamplingRate, 1095 &outputDesc->mFormat, 1096 &outputDesc->mChannels, 1097 &outputDesc->mLatency, 1098 outputDesc->mFlags); 1099 1100 if (mHardwareOutput == 0) { 1101 ALOGE("Failed to initialize hardware output stream, samplingRate: %d, format %d, channels %d", 1102 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels); 1103 } else { 1104 addOutput(mHardwareOutput, outputDesc); 1105 setOutputDevice(mHardwareOutput, (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER, true); 1106 //TODO: configure audio effect output stage here 1107 } 1108 1109 updateDeviceForStrategy(); 1110#ifdef AUDIO_POLICY_TEST 1111 if (mHardwareOutput != 0) { 1112 AudioParameter outputCmd = AudioParameter(); 1113 outputCmd.addInt(String8("set_id"), 0); 1114 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString()); 1115 1116 mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER; 1117 mTestSamplingRate = 44100; 1118 mTestFormat = AudioSystem::PCM_16_BIT; 1119 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO; 1120 mTestLatencyMs = 0; 1121 mCurOutput = 0; 1122 mDirectOutput = false; 1123 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) { 1124 mTestOutputs[i] = 0; 1125 } 1126 1127 const size_t SIZE = 256; 1128 char buffer[SIZE]; 1129 snprintf(buffer, SIZE, "AudioPolicyManagerTest"); 1130 run(buffer, ANDROID_PRIORITY_AUDIO); 1131 } 1132#endif //AUDIO_POLICY_TEST 1133} 1134 1135AudioPolicyManagerBase::~AudioPolicyManagerBase() 1136{ 1137#ifdef AUDIO_POLICY_TEST 1138 exit(); 1139#endif //AUDIO_POLICY_TEST 1140 for (size_t i = 0; i < mOutputs.size(); i++) { 1141 mpClientInterface->closeOutput(mOutputs.keyAt(i)); 1142 delete mOutputs.valueAt(i); 1143 } 1144 mOutputs.clear(); 1145 for (size_t i = 0; i < mInputs.size(); i++) { 1146 mpClientInterface->closeInput(mInputs.keyAt(i)); 1147 delete mInputs.valueAt(i); 1148 } 1149 mInputs.clear(); 1150} 1151 1152status_t AudioPolicyManagerBase::initCheck() 1153{ 1154 return (mHardwareOutput == 0) ? NO_INIT : NO_ERROR; 1155} 1156 1157#ifdef AUDIO_POLICY_TEST 1158bool AudioPolicyManagerBase::threadLoop() 1159{ 1160 ALOGV("entering threadLoop()"); 1161 while (!exitPending()) 1162 { 1163 String8 command; 1164 int valueInt; 1165 String8 value; 1166 1167 Mutex::Autolock _l(mLock); 1168 mWaitWorkCV.waitRelative(mLock, milliseconds(50)); 1169 1170 command = mpClientInterface->getParameters(0, String8("test_cmd_policy")); 1171 AudioParameter param = AudioParameter(command); 1172 1173 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR && 1174 valueInt != 0) { 1175 ALOGV("Test command %s received", command.string()); 1176 String8 target; 1177 if (param.get(String8("target"), target) != NO_ERROR) { 1178 target = "Manager"; 1179 } 1180 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) { 1181 param.remove(String8("test_cmd_policy_output")); 1182 mCurOutput = valueInt; 1183 } 1184 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) { 1185 param.remove(String8("test_cmd_policy_direct")); 1186 if (value == "false") { 1187 mDirectOutput = false; 1188 } else if (value == "true") { 1189 mDirectOutput = true; 1190 } 1191 } 1192 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) { 1193 param.remove(String8("test_cmd_policy_input")); 1194 mTestInput = valueInt; 1195 } 1196 1197 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) { 1198 param.remove(String8("test_cmd_policy_format")); 1199 int format = AudioSystem::INVALID_FORMAT; 1200 if (value == "PCM 16 bits") { 1201 format = AudioSystem::PCM_16_BIT; 1202 } else if (value == "PCM 8 bits") { 1203 format = AudioSystem::PCM_8_BIT; 1204 } else if (value == "Compressed MP3") { 1205 format = AudioSystem::MP3; 1206 } 1207 if (format != AudioSystem::INVALID_FORMAT) { 1208 if (target == "Manager") { 1209 mTestFormat = format; 1210 } else if (mTestOutputs[mCurOutput] != 0) { 1211 AudioParameter outputParam = AudioParameter(); 1212 outputParam.addInt(String8("format"), format); 1213 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 1214 } 1215 } 1216 } 1217 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) { 1218 param.remove(String8("test_cmd_policy_channels")); 1219 int channels = 0; 1220 1221 if (value == "Channels Stereo") { 1222 channels = AudioSystem::CHANNEL_OUT_STEREO; 1223 } else if (value == "Channels Mono") { 1224 channels = AudioSystem::CHANNEL_OUT_MONO; 1225 } 1226 if (channels != 0) { 1227 if (target == "Manager") { 1228 mTestChannels = channels; 1229 } else if (mTestOutputs[mCurOutput] != 0) { 1230 AudioParameter outputParam = AudioParameter(); 1231 outputParam.addInt(String8("channels"), channels); 1232 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 1233 } 1234 } 1235 } 1236 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) { 1237 param.remove(String8("test_cmd_policy_sampleRate")); 1238 if (valueInt >= 0 && valueInt <= 96000) { 1239 int samplingRate = valueInt; 1240 if (target == "Manager") { 1241 mTestSamplingRate = samplingRate; 1242 } else if (mTestOutputs[mCurOutput] != 0) { 1243 AudioParameter outputParam = AudioParameter(); 1244 outputParam.addInt(String8("sampling_rate"), samplingRate); 1245 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 1246 } 1247 } 1248 } 1249 1250 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) { 1251 param.remove(String8("test_cmd_policy_reopen")); 1252 1253 mpClientInterface->closeOutput(mHardwareOutput); 1254 delete mOutputs.valueFor(mHardwareOutput); 1255 mOutputs.removeItem(mHardwareOutput); 1256 1257 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(); 1258 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER; 1259 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice, 1260 &outputDesc->mSamplingRate, 1261 &outputDesc->mFormat, 1262 &outputDesc->mChannels, 1263 &outputDesc->mLatency, 1264 outputDesc->mFlags); 1265 if (mHardwareOutput == 0) { 1266 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d", 1267 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels); 1268 } else { 1269 AudioParameter outputCmd = AudioParameter(); 1270 outputCmd.addInt(String8("set_id"), 0); 1271 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString()); 1272 addOutput(mHardwareOutput, outputDesc); 1273 } 1274 } 1275 1276 1277 mpClientInterface->setParameters(0, String8("test_cmd_policy=")); 1278 } 1279 } 1280 return false; 1281} 1282 1283void AudioPolicyManagerBase::exit() 1284{ 1285 { 1286 AutoMutex _l(mLock); 1287 requestExit(); 1288 mWaitWorkCV.signal(); 1289 } 1290 requestExitAndWait(); 1291} 1292 1293int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output) 1294{ 1295 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) { 1296 if (output == mTestOutputs[i]) return i; 1297 } 1298 return 0; 1299} 1300#endif //AUDIO_POLICY_TEST 1301 1302// --- 1303 1304void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc) 1305{ 1306 outputDesc->mId = id; 1307 mOutputs.add(id, outputDesc); 1308} 1309 1310 1311#ifdef WITH_A2DP 1312status_t AudioPolicyManagerBase::handleA2dpConnection(AudioSystem::audio_devices device, 1313 const char *device_address) 1314{ 1315 // when an A2DP device is connected, open an A2DP and a duplicated output 1316 ALOGV("opening A2DP output for device %s", device_address); 1317 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(); 1318 outputDesc->mDevice = device; 1319 mA2dpOutput = mpClientInterface->openOutput(&outputDesc->mDevice, 1320 &outputDesc->mSamplingRate, 1321 &outputDesc->mFormat, 1322 &outputDesc->mChannels, 1323 &outputDesc->mLatency, 1324 outputDesc->mFlags); 1325 if (mA2dpOutput) { 1326 // add A2DP output descriptor 1327 addOutput(mA2dpOutput, outputDesc); 1328 1329 //TODO: configure audio effect output stage here 1330 1331 // set initial stream volume for A2DP device 1332 applyStreamVolumes(mA2dpOutput, device); 1333 if (a2dpUsedForSonification()) { 1334 mDuplicatedOutput = mpClientInterface->openDuplicateOutput(mA2dpOutput, mHardwareOutput); 1335 } 1336 if (mDuplicatedOutput != 0 || 1337 !a2dpUsedForSonification()) { 1338 // If both A2DP and duplicated outputs are open, send device address to A2DP hardware 1339 // interface 1340 AudioParameter param; 1341 param.add(String8("a2dp_sink_address"), String8(device_address)); 1342 mpClientInterface->setParameters(mA2dpOutput, param.toString()); 1343 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN); 1344 1345 if (a2dpUsedForSonification()) { 1346 // add duplicated output descriptor 1347 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(); 1348 dupOutputDesc->mOutput1 = mOutputs.valueFor(mHardwareOutput); 1349 dupOutputDesc->mOutput2 = mOutputs.valueFor(mA2dpOutput); 1350 dupOutputDesc->mSamplingRate = outputDesc->mSamplingRate; 1351 dupOutputDesc->mFormat = outputDesc->mFormat; 1352 dupOutputDesc->mChannels = outputDesc->mChannels; 1353 dupOutputDesc->mLatency = outputDesc->mLatency; 1354 addOutput(mDuplicatedOutput, dupOutputDesc); 1355 applyStreamVolumes(mDuplicatedOutput, device); 1356 } 1357 } else { 1358 ALOGW("getOutput() could not open duplicated output for %d and %d", 1359 mHardwareOutput, mA2dpOutput); 1360 mpClientInterface->closeOutput(mA2dpOutput); 1361 mOutputs.removeItem(mA2dpOutput); 1362 mA2dpOutput = 0; 1363 delete outputDesc; 1364 return NO_INIT; 1365 } 1366 } else { 1367 ALOGW("setDeviceConnectionState() could not open A2DP output for device %x", device); 1368 delete outputDesc; 1369 return NO_INIT; 1370 } 1371 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput); 1372 1373 if (!a2dpUsedForSonification()) { 1374 // mute music on A2DP output if a notification or ringtone is playing 1375 uint32_t refCount = hwOutputDesc->strategyRefCount(STRATEGY_SONIFICATION); 1376 refCount += hwOutputDesc->strategyRefCount(STRATEGY_ENFORCED_AUDIBLE); 1377 for (uint32_t i = 0; i < refCount; i++) { 1378 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput); 1379 } 1380 } 1381 1382 mA2dpSuspended = false; 1383 1384 return NO_ERROR; 1385} 1386 1387status_t AudioPolicyManagerBase::handleA2dpDisconnection(AudioSystem::audio_devices device, 1388 const char *device_address) 1389{ 1390 if (mA2dpOutput == 0) { 1391 ALOGW("setDeviceConnectionState() disconnecting A2DP and no A2DP output!"); 1392 return INVALID_OPERATION; 1393 } 1394 1395 if (mA2dpDeviceAddress != device_address) { 1396 ALOGW("setDeviceConnectionState() disconnecting unknow A2DP sink address %s", device_address); 1397 return INVALID_OPERATION; 1398 } 1399 1400 // mute media strategy to avoid outputting sound on hardware output while music stream 1401 // is switched from A2DP output and before music is paused by music application 1402 setStrategyMute(STRATEGY_MEDIA, true, mHardwareOutput); 1403 setStrategyMute(STRATEGY_MEDIA, false, mHardwareOutput, MUTE_TIME_MS); 1404 1405 if (!a2dpUsedForSonification()) { 1406 // unmute music on A2DP output if a notification or ringtone is playing 1407 uint32_t refCount = mOutputs.valueFor(mHardwareOutput)->strategyRefCount(STRATEGY_SONIFICATION); 1408 refCount += mOutputs.valueFor(mHardwareOutput)->strategyRefCount(STRATEGY_ENFORCED_AUDIBLE); 1409 for (uint32_t i = 0; i < refCount; i++) { 1410 setStrategyMute(STRATEGY_MEDIA, false, mA2dpOutput); 1411 } 1412 } 1413 mA2dpDeviceAddress = ""; 1414 mA2dpSuspended = false; 1415 return NO_ERROR; 1416} 1417 1418void AudioPolicyManagerBase::closeA2dpOutputs() 1419{ 1420 1421 ALOGV("setDeviceConnectionState() closing A2DP and duplicated output!"); 1422 1423 if (mDuplicatedOutput != 0) { 1424 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueFor(mDuplicatedOutput); 1425 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput); 1426 // As all active tracks on duplicated output will be deleted, 1427 // and as they were also referenced on hardware output, the reference 1428 // count for their stream type must be adjusted accordingly on 1429 // hardware output. 1430 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) { 1431 int refCount = dupOutputDesc->mRefCount[i]; 1432 hwOutputDesc->changeRefCount((AudioSystem::stream_type)i,-refCount); 1433 } 1434 1435 mpClientInterface->closeOutput(mDuplicatedOutput); 1436 delete mOutputs.valueFor(mDuplicatedOutput); 1437 mOutputs.removeItem(mDuplicatedOutput); 1438 mDuplicatedOutput = 0; 1439 } 1440 if (mA2dpOutput != 0) { 1441 AudioParameter param; 1442 param.add(String8("closing"), String8("true")); 1443 mpClientInterface->setParameters(mA2dpOutput, param.toString()); 1444 1445 mpClientInterface->closeOutput(mA2dpOutput); 1446 delete mOutputs.valueFor(mA2dpOutput); 1447 mOutputs.removeItem(mA2dpOutput); 1448 mA2dpOutput = 0; 1449 } 1450} 1451 1452void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy) 1453{ 1454 uint32_t prevDevice = getDeviceForStrategy(strategy); 1455 uint32_t curDevice = getDeviceForStrategy(strategy, false); 1456 bool a2dpWasUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(prevDevice & ~AudioSystem::DEVICE_OUT_SPEAKER)); 1457 bool a2dpIsUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(curDevice & ~AudioSystem::DEVICE_OUT_SPEAKER)); 1458 audio_io_handle_t srcOutput = 0; 1459 audio_io_handle_t dstOutput = 0; 1460 1461 if (a2dpWasUsed && !a2dpIsUsed) { 1462 bool dupUsed = a2dpUsedForSonification() && a2dpWasUsed && (AudioSystem::popCount(prevDevice) == 2); 1463 dstOutput = mHardwareOutput; 1464 if (dupUsed) { 1465 ALOGV("checkOutputForStrategy() moving strategy %d from duplicated", strategy); 1466 srcOutput = mDuplicatedOutput; 1467 } else { 1468 ALOGV("checkOutputForStrategy() moving strategy %d from a2dp", strategy); 1469 srcOutput = mA2dpOutput; 1470 } 1471 } 1472 if (a2dpIsUsed && !a2dpWasUsed) { 1473 bool dupUsed = a2dpUsedForSonification() && a2dpIsUsed && (AudioSystem::popCount(curDevice) == 2); 1474 srcOutput = mHardwareOutput; 1475 if (dupUsed) { 1476 ALOGV("checkOutputForStrategy() moving strategy %d to duplicated", strategy); 1477 dstOutput = mDuplicatedOutput; 1478 } else { 1479 ALOGV("checkOutputForStrategy() moving strategy %d to a2dp", strategy); 1480 dstOutput = mA2dpOutput; 1481 } 1482 } 1483 1484 if (srcOutput != 0 && dstOutput != 0) { 1485 // Move effects associated to this strategy from previous output to new output 1486 for (size_t i = 0; i < mEffects.size(); i++) { 1487 EffectDescriptor *desc = mEffects.valueAt(i); 1488 if (desc->mSession != AudioSystem::SESSION_OUTPUT_STAGE && 1489 desc->mStrategy == strategy && 1490 desc->mIo == srcOutput) { 1491 ALOGV("checkOutputForStrategy() moving effect %d to output %d", mEffects.keyAt(i), dstOutput); 1492 mpClientInterface->moveEffects(desc->mSession, srcOutput, dstOutput); 1493 desc->mIo = dstOutput; 1494 } 1495 } 1496 // Move tracks associated to this strategy from previous output to new output 1497 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) { 1498 if (getStrategy((AudioSystem::stream_type)i) == strategy) { 1499 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, dstOutput); 1500 } 1501 } 1502 } 1503} 1504 1505void AudioPolicyManagerBase::checkOutputForAllStrategies() 1506{ 1507 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE); 1508 checkOutputForStrategy(STRATEGY_PHONE); 1509 checkOutputForStrategy(STRATEGY_SONIFICATION); 1510 checkOutputForStrategy(STRATEGY_MEDIA); 1511 checkOutputForStrategy(STRATEGY_DTMF); 1512} 1513 1514void AudioPolicyManagerBase::checkA2dpSuspend() 1515{ 1516 // suspend A2DP output if: 1517 // (NOT already suspended) && 1518 // ((SCO device is connected && 1519 // (forced usage for communication || for record is SCO))) || 1520 // (phone state is ringing || in call) 1521 // 1522 // restore A2DP output if: 1523 // (Already suspended) && 1524 // ((SCO device is NOT connected || 1525 // (forced usage NOT for communication && NOT for record is SCO))) && 1526 // (phone state is NOT ringing && NOT in call) 1527 // 1528 if (mA2dpOutput == 0) { 1529 return; 1530 } 1531 1532 if (mA2dpSuspended) { 1533 if (((mScoDeviceAddress == "") || 1534 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) && 1535 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) && 1536 ((mPhoneState != AudioSystem::MODE_IN_CALL) && 1537 (mPhoneState != AudioSystem::MODE_RINGTONE))) { 1538 1539 mpClientInterface->restoreOutput(mA2dpOutput); 1540 mA2dpSuspended = false; 1541 } 1542 } else { 1543 if (((mScoDeviceAddress != "") && 1544 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) || 1545 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) || 1546 ((mPhoneState == AudioSystem::MODE_IN_CALL) || 1547 (mPhoneState == AudioSystem::MODE_RINGTONE))) { 1548 1549 mpClientInterface->suspendOutput(mA2dpOutput); 1550 mA2dpSuspended = true; 1551 } 1552 } 1553} 1554 1555 1556#endif 1557 1558uint32_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache) 1559{ 1560 uint32_t device = 0; 1561 1562 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 1563 // check the following by order of priority to request a routing change if necessary: 1564 // 1: the strategy enforced audible is active on the output: 1565 // use device for strategy enforced audible 1566 // 2: we are in call or the strategy phone is active on the output: 1567 // use device for strategy phone 1568 // 3: the strategy sonification is active on the output: 1569 // use device for strategy sonification 1570 // 4: the strategy media is active on the output: 1571 // use device for strategy media 1572 // 5: the strategy DTMF is active on the output: 1573 // use device for strategy DTMF 1574 if (outputDesc->isUsedByStrategy(STRATEGY_ENFORCED_AUDIBLE)) { 1575 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache); 1576 } else if (isInCall() || 1577 outputDesc->isUsedByStrategy(STRATEGY_PHONE)) { 1578 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache); 1579 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) { 1580 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache); 1581 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) { 1582 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache); 1583 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) { 1584 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache); 1585 } 1586 1587 ALOGV("getNewDevice() selected device %x", device); 1588 return device; 1589} 1590 1591uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) { 1592 return (uint32_t)getStrategy(stream); 1593} 1594 1595uint32_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) { 1596 uint32_t devices; 1597 // By checking the range of stream before calling getStrategy, we avoid 1598 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE 1599 // and then return STRATEGY_MEDIA, but we want to return the empty set. 1600 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) { 1601 devices = 0; 1602 } else { 1603 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream); 1604 devices = getDeviceForStrategy(strategy, true); 1605 } 1606 return devices; 1607} 1608 1609AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy( 1610 AudioSystem::stream_type stream) { 1611 // stream to strategy mapping 1612 switch (stream) { 1613 case AudioSystem::VOICE_CALL: 1614 case AudioSystem::BLUETOOTH_SCO: 1615 return STRATEGY_PHONE; 1616 case AudioSystem::RING: 1617 case AudioSystem::NOTIFICATION: 1618 case AudioSystem::ALARM: 1619 return STRATEGY_SONIFICATION; 1620 case AudioSystem::DTMF: 1621 return STRATEGY_DTMF; 1622 default: 1623 ALOGE("unknown stream type"); 1624 case AudioSystem::SYSTEM: 1625 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs 1626 // while key clicks are played produces a poor result 1627 case AudioSystem::TTS: 1628 case AudioSystem::MUSIC: 1629 return STRATEGY_MEDIA; 1630 case AudioSystem::ENFORCED_AUDIBLE: 1631 return STRATEGY_ENFORCED_AUDIBLE; 1632 } 1633} 1634 1635uint32_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy, bool fromCache) 1636{ 1637 uint32_t device = 0; 1638 1639 if (fromCache) { 1640 ALOGV("getDeviceForStrategy() from cache strategy %d, device %x", strategy, mDeviceForStrategy[strategy]); 1641 return mDeviceForStrategy[strategy]; 1642 } 1643 1644 switch (strategy) { 1645 case STRATEGY_DTMF: 1646 if (!isInCall()) { 1647 // when off call, DTMF strategy follows the same rules as MEDIA strategy 1648 device = getDeviceForStrategy(STRATEGY_MEDIA, false); 1649 break; 1650 } 1651 // when in call, DTMF and PHONE strategies follow the same rules 1652 // FALL THROUGH 1653 1654 case STRATEGY_PHONE: 1655 // for phone strategy, we first consider the forced use and then the available devices by order 1656 // of priority 1657 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) { 1658 case AudioSystem::FORCE_BT_SCO: 1659 if (!isInCall() || strategy != STRATEGY_DTMF) { 1660 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT; 1661 if (device) break; 1662 } 1663 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET; 1664 if (device) break; 1665 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO; 1666 if (device) break; 1667 // if SCO device is requested but no SCO device is available, fall back to default case 1668 // FALL THROUGH 1669 1670 default: // FORCE_NONE 1671 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE; 1672 if (device) break; 1673 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET; 1674 if (device) break; 1675#ifdef WITH_A2DP 1676 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP 1677 if (!isInCall() && !mA2dpSuspended) { 1678 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP; 1679 if (device) break; 1680 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES; 1681 if (device) break; 1682 } 1683#endif 1684 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET; 1685 if (device) break; 1686 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL; 1687 if (device) break; 1688 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET; 1689 if (device) break; 1690 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE; 1691 if (device == 0) { 1692 ALOGE("getDeviceForStrategy() earpiece device not found"); 1693 } 1694 break; 1695 1696 case AudioSystem::FORCE_SPEAKER: 1697#ifdef WITH_A2DP 1698 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to 1699 // A2DP speaker when forcing to speaker output 1700 if (!isInCall() && !mA2dpSuspended) { 1701 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER; 1702 if (device) break; 1703 } 1704#endif 1705 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET; 1706 if (device) break; 1707 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL; 1708 if (device) break; 1709 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET; 1710 if (device) break; 1711 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER; 1712 if (device == 0) { 1713 ALOGE("getDeviceForStrategy() speaker device not found"); 1714 } 1715 break; 1716 } 1717 break; 1718 1719 case STRATEGY_SONIFICATION: 1720 1721 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by 1722 // handleIncallSonification(). 1723 if (isInCall()) { 1724 device = getDeviceForStrategy(STRATEGY_PHONE, false); 1725 break; 1726 } 1727 // FALL THROUGH 1728 1729 case STRATEGY_ENFORCED_AUDIBLE: 1730 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION 1731 // except when in call where it doesn't default to STRATEGY_PHONE behavior 1732 1733 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER; 1734 if (device == 0) { 1735 ALOGE("getDeviceForStrategy() speaker device not found"); 1736 } 1737 // The second device used for sonification is the same as the device used by media strategy 1738 // FALL THROUGH 1739 1740 case STRATEGY_MEDIA: { 1741 uint32_t device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE; 1742 if (device2 == 0) { 1743 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET; 1744 } 1745#ifdef WITH_A2DP 1746 if ((mA2dpOutput != 0) && !mA2dpSuspended && 1747 (strategy == STRATEGY_MEDIA || a2dpUsedForSonification())) { 1748 if (device2 == 0) { 1749 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP; 1750 } 1751 if (device2 == 0) { 1752 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES; 1753 } 1754 if (device2 == 0) { 1755 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER; 1756 } 1757 } 1758#endif 1759 if (device2 == 0) { 1760 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET; 1761 } 1762 if (device2 == 0) { 1763 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL; 1764 } 1765 if (device2 == 0) { 1766 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET; 1767 } 1768 if (device2 == 0) { 1769 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER; 1770 } 1771 1772 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or 1773 // STRATEGY_ENFORCED_AUDIBLE, 0 otherwise 1774 device |= device2; 1775 if (device == 0) { 1776 ALOGE("getDeviceForStrategy() speaker device not found"); 1777 } 1778 } break; 1779 1780 default: 1781 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy); 1782 break; 1783 } 1784 1785 ALOGV("getDeviceForStrategy() strategy %d, device %x", strategy, device); 1786 return device; 1787} 1788 1789void AudioPolicyManagerBase::updateDeviceForStrategy() 1790{ 1791 for (int i = 0; i < NUM_STRATEGIES; i++) { 1792 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false); 1793 } 1794} 1795 1796void AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output, uint32_t device, bool force, int delayMs) 1797{ 1798 ALOGV("setOutputDevice() output %d device %x delayMs %d", output, device, delayMs); 1799 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 1800 1801 1802 if (outputDesc->isDuplicated()) { 1803 setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs); 1804 setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs); 1805 return; 1806 } 1807#ifdef WITH_A2DP 1808 // filter devices according to output selected 1809 if (output == mA2dpOutput) { 1810 device &= AudioSystem::DEVICE_OUT_ALL_A2DP; 1811 } else { 1812 device &= ~AudioSystem::DEVICE_OUT_ALL_A2DP; 1813 } 1814#endif 1815 1816 uint32_t prevDevice = (uint32_t)outputDesc->device(); 1817 // Do not change the routing if: 1818 // - the requestede device is 0 1819 // - the requested device is the same as current device and force is not specified. 1820 // Doing this check here allows the caller to call setOutputDevice() without conditions 1821 if ((device == 0 || device == prevDevice) && !force) { 1822 ALOGV("setOutputDevice() setting same device %x or null device for output %d", device, output); 1823 return; 1824 } 1825 1826 outputDesc->mDevice = device; 1827 // mute media streams if both speaker and headset are selected 1828 if (output == mHardwareOutput && AudioSystem::popCount(device) == 2) { 1829 setStrategyMute(STRATEGY_MEDIA, true, output); 1830 // wait for the PCM output buffers to empty before proceeding with the rest of the command 1831 // FIXME: increased delay due to larger buffers used for low power audio mode. 1832 // remove when low power audio is controlled by policy manager. 1833 usleep(outputDesc->mLatency*8*1000); 1834 } 1835 1836 // do the routing 1837 AudioParameter param = AudioParameter(); 1838 param.addInt(String8(AudioParameter::keyRouting), (int)device); 1839 mpClientInterface->setParameters(mHardwareOutput, param.toString(), delayMs); 1840 // update stream volumes according to new device 1841 applyStreamVolumes(output, device, delayMs); 1842 1843 // if changing from a combined headset + speaker route, unmute media streams 1844 if (output == mHardwareOutput && AudioSystem::popCount(prevDevice) == 2) { 1845 setStrategyMute(STRATEGY_MEDIA, false, output, delayMs); 1846 } 1847} 1848 1849uint32_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource) 1850{ 1851 uint32_t device; 1852 1853 switch(inputSource) { 1854 case AUDIO_SOURCE_DEFAULT: 1855 case AUDIO_SOURCE_MIC: 1856 case AUDIO_SOURCE_VOICE_RECOGNITION: 1857 case AUDIO_SOURCE_VOICE_COMMUNICATION: 1858 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO && 1859 mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) { 1860 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET; 1861 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) { 1862 device = AudioSystem::DEVICE_IN_WIRED_HEADSET; 1863 } else { 1864 device = AudioSystem::DEVICE_IN_BUILTIN_MIC; 1865 } 1866 break; 1867 case AUDIO_SOURCE_CAMCORDER: 1868 if (hasBackMicrophone()) { 1869 device = AudioSystem::DEVICE_IN_BACK_MIC; 1870 } else { 1871 device = AudioSystem::DEVICE_IN_BUILTIN_MIC; 1872 } 1873 break; 1874 case AUDIO_SOURCE_VOICE_UPLINK: 1875 case AUDIO_SOURCE_VOICE_DOWNLINK: 1876 case AUDIO_SOURCE_VOICE_CALL: 1877 device = AudioSystem::DEVICE_IN_VOICE_CALL; 1878 break; 1879 default: 1880 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource); 1881 device = 0; 1882 break; 1883 } 1884 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device); 1885 return device; 1886} 1887 1888audio_io_handle_t AudioPolicyManagerBase::getActiveInput() 1889{ 1890 for (size_t i = 0; i < mInputs.size(); i++) { 1891 if (mInputs.valueAt(i)->mRefCount > 0) { 1892 return mInputs.keyAt(i); 1893 } 1894 } 1895 return 0; 1896} 1897 1898 1899AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(uint32_t device) 1900{ 1901 if (device == 0) { 1902 // this happens when forcing a route update and no track is active on an output. 1903 // In this case the returned category is not important. 1904 return DEVICE_CATEGORY_SPEAKER; 1905 } 1906 1907 if (AudioSystem::popCount(device) > 1) { 1908 // Multiple device selection is either: 1909 // - speaker + one other device: give priority to speaker in this case. 1910 // - one A2DP device + another device: happens with duplicated output. In this case 1911 // retain the device on the A2DP output as the other must not correspond to an active 1912 // selection if not the speaker. 1913 if (device & AUDIO_DEVICE_OUT_SPEAKER) 1914 return DEVICE_CATEGORY_SPEAKER; 1915 1916 device &= AUDIO_DEVICE_OUT_ALL_A2DP; 1917 } 1918 1919 ALOGW_IF(AudioSystem::popCount(device) != 1, 1920 "getDeviceCategory() invalid device combination: %08x", 1921 device); 1922 1923 switch(device) { 1924 case AUDIO_DEVICE_OUT_EARPIECE: 1925 return DEVICE_CATEGORY_EARPIECE; 1926 case AUDIO_DEVICE_OUT_WIRED_HEADSET: 1927 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE: 1928 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO: 1929 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET: 1930 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP: 1931 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES: 1932 return DEVICE_CATEGORY_HEADSET; 1933 case AUDIO_DEVICE_OUT_SPEAKER: 1934 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT: 1935 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER: 1936 default: 1937 return DEVICE_CATEGORY_SPEAKER; 1938 } 1939} 1940 1941float AudioPolicyManagerBase::volIndexToAmpl(uint32_t device, const StreamDescriptor& streamDesc, 1942 int indexInUi) 1943{ 1944 device_category deviceCategory = getDeviceCategory(device); 1945 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory]; 1946 1947 // the volume index in the UI is relative to the min and max volume indices for this stream type 1948 int nbSteps = 1 + curve[VOLMAX].mIndex - 1949 curve[VOLMIN].mIndex; 1950 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) / 1951 (streamDesc.mIndexMax - streamDesc.mIndexMin); 1952 1953 // find what part of the curve this index volume belongs to, or if it's out of bounds 1954 int segment = 0; 1955 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds 1956 return 0.0f; 1957 } else if (volIdx < curve[VOLKNEE1].mIndex) { 1958 segment = 0; 1959 } else if (volIdx < curve[VOLKNEE2].mIndex) { 1960 segment = 1; 1961 } else if (volIdx <= curve[VOLMAX].mIndex) { 1962 segment = 2; 1963 } else { // out of bounds 1964 return 1.0f; 1965 } 1966 1967 // linear interpolation in the attenuation table in dB 1968 float decibels = curve[segment].mDBAttenuation + 1969 ((float)(volIdx - curve[segment].mIndex)) * 1970 ( (curve[segment+1].mDBAttenuation - 1971 curve[segment].mDBAttenuation) / 1972 ((float)(curve[segment+1].mIndex - 1973 curve[segment].mIndex)) ); 1974 1975 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 ) 1976 1977 ALOGV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f", 1978 curve[segment].mIndex, volIdx, 1979 curve[segment+1].mIndex, 1980 curve[segment].mDBAttenuation, 1981 decibels, 1982 curve[segment+1].mDBAttenuation, 1983 amplification); 1984 1985 return amplification; 1986} 1987 1988const AudioPolicyManagerBase::VolumeCurvePoint 1989 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 1990 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f} 1991}; 1992 1993const AudioPolicyManagerBase::VolumeCurvePoint 1994 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 1995 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f} 1996}; 1997 1998const AudioPolicyManagerBase::VolumeCurvePoint 1999 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2000 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f} 2001}; 2002 2003const AudioPolicyManagerBase::VolumeCurvePoint 2004 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = { 2005 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f} 2006}; 2007 2008 2009const AudioPolicyManagerBase::VolumeCurvePoint 2010 *AudioPolicyManagerBase::sVolumeProfiles[AudioPolicyManagerBase::NUM_STRATEGIES] 2011 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = { 2012 { // STRATEGY_MEDIA 2013 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET 2014 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2015 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE 2016 }, 2017 { // STRATEGY_PHONE 2018 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET 2019 sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2020 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE 2021 }, 2022 { // STRATEGY_SONIFICATION 2023 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET 2024 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2025 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE 2026 }, 2027 { // STRATEGY_DTMF 2028 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET 2029 sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2030 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE 2031 }, 2032 { // STRATEGY_ENFORCED_AUDIBLE 2033 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET 2034 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER 2035 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE 2036 }, 2037}; 2038 2039void AudioPolicyManagerBase::initializeVolumeCurves() 2040{ 2041 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) { 2042 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) { 2043 mStreams[i].mVolumeCurve[j] = 2044 sVolumeProfiles[getStrategy((AudioSystem::stream_type)i)][j]; 2045 } 2046 } 2047} 2048 2049float AudioPolicyManagerBase::computeVolume(int stream, int index, audio_io_handle_t output, uint32_t device) 2050{ 2051 float volume = 1.0; 2052 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 2053 StreamDescriptor &streamDesc = mStreams[stream]; 2054 2055 if (device == 0) { 2056 device = outputDesc->device(); 2057 } 2058 2059 // if volume is not 0 (not muted), force media volume to max on digital output 2060 if (stream == AudioSystem::MUSIC && 2061 index != mStreams[stream].mIndexMin && 2062 (device == AudioSystem::DEVICE_OUT_AUX_DIGITAL || 2063 device == AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET)) { 2064 return 1.0; 2065 } 2066 2067 volume = volIndexToAmpl(device, streamDesc, index); 2068 2069 // if a headset is connected, apply the following rules to ring tones and notifications 2070 // to avoid sound level bursts in user's ears: 2071 // - always attenuate ring tones and notifications volume by 6dB 2072 // - if music is playing, always limit the volume to current music volume, 2073 // with a minimum threshold at -36dB so that notification is always perceived. 2074 if ((device & 2075 (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP | 2076 AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES | 2077 AudioSystem::DEVICE_OUT_WIRED_HEADSET | 2078 AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) && 2079 ((getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) || 2080 (stream == AudioSystem::SYSTEM)) && 2081 streamDesc.mCanBeMuted) { 2082 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR; 2083 // when the phone is ringing we must consider that music could have been paused just before 2084 // by the music application and behave as if music was active if the last music track was 2085 // just stopped 2086 if (outputDesc->mRefCount[AudioSystem::MUSIC] || mLimitRingtoneVolume) { 2087 float musicVol = computeVolume(AudioSystem::MUSIC, mStreams[AudioSystem::MUSIC].mIndexCur, output, device); 2088 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? musicVol : SONIFICATION_HEADSET_VOLUME_MIN; 2089 if (volume > minVol) { 2090 volume = minVol; 2091 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol); 2092 } 2093 } 2094 } 2095 2096 return volume; 2097} 2098 2099status_t AudioPolicyManagerBase::checkAndSetVolume(int stream, int index, audio_io_handle_t output, uint32_t device, int delayMs, bool force) 2100{ 2101 2102 // do not change actual stream volume if the stream is muted 2103 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) { 2104 ALOGV("checkAndSetVolume() stream %d muted count %d", stream, mOutputs.valueFor(output)->mMuteCount[stream]); 2105 return NO_ERROR; 2106 } 2107 2108 // do not change in call volume if bluetooth is connected and vice versa 2109 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) || 2110 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) { 2111 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm", 2112 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]); 2113 return INVALID_OPERATION; 2114 } 2115 2116 float volume = computeVolume(stream, index, output, device); 2117 // We actually change the volume if: 2118 // - the float value returned by computeVolume() changed 2119 // - the force flag is set 2120 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] || 2121 force) { 2122 mOutputs.valueFor(output)->mCurVolume[stream] = volume; 2123 ALOGV("setStreamVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs); 2124 if (stream == AudioSystem::VOICE_CALL || 2125 stream == AudioSystem::DTMF || 2126 stream == AudioSystem::BLUETOOTH_SCO) { 2127 // offset value to reflect actual hardware volume that never reaches 0 2128 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java) 2129 volume = 0.01 + 0.99 * volume; 2130 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is 2131 // enabled 2132 if (stream == AudioSystem::BLUETOOTH_SCO) { 2133 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs); 2134 } 2135 } 2136 2137 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs); 2138 } 2139 2140 if (stream == AudioSystem::VOICE_CALL || 2141 stream == AudioSystem::BLUETOOTH_SCO) { 2142 float voiceVolume; 2143 // Force voice volume to max for bluetooth SCO as volume is managed by the headset 2144 if (stream == AudioSystem::VOICE_CALL) { 2145 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax; 2146 } else { 2147 voiceVolume = 1.0; 2148 } 2149 2150 if (voiceVolume != mLastVoiceVolume && output == mHardwareOutput) { 2151 mpClientInterface->setVoiceVolume(voiceVolume, delayMs); 2152 mLastVoiceVolume = voiceVolume; 2153 } 2154 } 2155 2156 return NO_ERROR; 2157} 2158 2159void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output, uint32_t device, int delayMs, bool force) 2160{ 2161 ALOGV("applyStreamVolumes() for output %d and device %x", output, device); 2162 2163 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) { 2164 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, device, delayMs, force); 2165 } 2166} 2167 2168void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs) 2169{ 2170 ALOGV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output); 2171 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) { 2172 if (getStrategy((AudioSystem::stream_type)stream) == strategy) { 2173 setStreamMute(stream, on, output, delayMs); 2174 } 2175 } 2176} 2177 2178void AudioPolicyManagerBase::setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs) 2179{ 2180 StreamDescriptor &streamDesc = mStreams[stream]; 2181 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 2182 2183 ALOGV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d", stream, on, output, outputDesc->mMuteCount[stream]); 2184 2185 if (on) { 2186 if (outputDesc->mMuteCount[stream] == 0) { 2187 if (streamDesc.mCanBeMuted) { 2188 checkAndSetVolume(stream, 0, output, outputDesc->device(), delayMs); 2189 } 2190 } 2191 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored 2192 outputDesc->mMuteCount[stream]++; 2193 } else { 2194 if (outputDesc->mMuteCount[stream] == 0) { 2195 ALOGW("setStreamMute() unmuting non muted stream!"); 2196 return; 2197 } 2198 if (--outputDesc->mMuteCount[stream] == 0) { 2199 checkAndSetVolume(stream, streamDesc.mIndexCur, output, outputDesc->device(), delayMs); 2200 } 2201 } 2202} 2203 2204void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange) 2205{ 2206 // if the stream pertains to sonification strategy and we are in call we must 2207 // mute the stream if it is low visibility. If it is high visibility, we must play a tone 2208 // in the device used for phone strategy and play the tone if the selected device does not 2209 // interfere with the device used for phone strategy 2210 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as 2211 // many times as there are active tracks on the output 2212 2213 if (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) { 2214 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mHardwareOutput); 2215 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d", 2216 stream, starting, outputDesc->mDevice, stateChange); 2217 if (outputDesc->mRefCount[stream]) { 2218 int muteCount = 1; 2219 if (stateChange) { 2220 muteCount = outputDesc->mRefCount[stream]; 2221 } 2222 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) { 2223 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount); 2224 for (int i = 0; i < muteCount; i++) { 2225 setStreamMute(stream, starting, mHardwareOutput); 2226 } 2227 } else { 2228 ALOGV("handleIncallSonification() high visibility"); 2229 if (outputDesc->device() & getDeviceForStrategy(STRATEGY_PHONE)) { 2230 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount); 2231 for (int i = 0; i < muteCount; i++) { 2232 setStreamMute(stream, starting, mHardwareOutput); 2233 } 2234 } 2235 if (starting) { 2236 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL); 2237 } else { 2238 mpClientInterface->stopTone(); 2239 } 2240 } 2241 } 2242 } 2243} 2244 2245bool AudioPolicyManagerBase::isInCall() 2246{ 2247 return isStateInCall(mPhoneState); 2248} 2249 2250bool AudioPolicyManagerBase::isStateInCall(int state) { 2251 return ((state == AudioSystem::MODE_IN_CALL) || 2252 (state == AudioSystem::MODE_IN_COMMUNICATION)); 2253} 2254 2255bool AudioPolicyManagerBase::needsDirectOuput(AudioSystem::stream_type stream, 2256 uint32_t samplingRate, 2257 uint32_t format, 2258 uint32_t channels, 2259 AudioSystem::output_flags flags, 2260 uint32_t device) 2261{ 2262 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) || 2263 (format !=0 && !AudioSystem::isLinearPCM(format))); 2264} 2265 2266uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad() 2267{ 2268 return MAX_EFFECTS_CPU_LOAD; 2269} 2270 2271uint32_t AudioPolicyManagerBase::getMaxEffectsMemory() 2272{ 2273 return MAX_EFFECTS_MEMORY; 2274} 2275 2276// --- AudioOutputDescriptor class implementation 2277 2278AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor() 2279 : mId(0), mSamplingRate(0), mFormat(0), mChannels(0), mLatency(0), 2280 mFlags((AudioSystem::output_flags)0), mDevice(0), mOutput1(0), mOutput2(0) 2281{ 2282 // clear usage count for all stream types 2283 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) { 2284 mRefCount[i] = 0; 2285 mCurVolume[i] = -1.0; 2286 mMuteCount[i] = 0; 2287 mStopTime[i] = 0; 2288 } 2289} 2290 2291uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::device() 2292{ 2293 uint32_t device = 0; 2294 if (isDuplicated()) { 2295 device = mOutput1->mDevice | mOutput2->mDevice; 2296 } else { 2297 device = mDevice; 2298 } 2299 return device; 2300} 2301 2302void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta) 2303{ 2304 // forward usage count change to attached outputs 2305 if (isDuplicated()) { 2306 mOutput1->changeRefCount(stream, delta); 2307 mOutput2->changeRefCount(stream, delta); 2308 } 2309 if ((delta + (int)mRefCount[stream]) < 0) { 2310 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]); 2311 mRefCount[stream] = 0; 2312 return; 2313 } 2314 mRefCount[stream] += delta; 2315 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]); 2316} 2317 2318uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount() 2319{ 2320 uint32_t refcount = 0; 2321 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) { 2322 refcount += mRefCount[i]; 2323 } 2324 return refcount; 2325} 2326 2327uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy) 2328{ 2329 uint32_t refCount = 0; 2330 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) { 2331 if (getStrategy((AudioSystem::stream_type)i) == strategy) { 2332 refCount += mRefCount[i]; 2333 } 2334 } 2335 return refCount; 2336} 2337 2338status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd) 2339{ 2340 const size_t SIZE = 256; 2341 char buffer[SIZE]; 2342 String8 result; 2343 2344 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate); 2345 result.append(buffer); 2346 snprintf(buffer, SIZE, " Format: %d\n", mFormat); 2347 result.append(buffer); 2348 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels); 2349 result.append(buffer); 2350 snprintf(buffer, SIZE, " Latency: %d\n", mLatency); 2351 result.append(buffer); 2352 snprintf(buffer, SIZE, " Flags %08x\n", mFlags); 2353 result.append(buffer); 2354 snprintf(buffer, SIZE, " Devices %08x\n", device()); 2355 result.append(buffer); 2356 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n"); 2357 result.append(buffer); 2358 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) { 2359 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]); 2360 result.append(buffer); 2361 } 2362 write(fd, result.string(), result.size()); 2363 2364 return NO_ERROR; 2365} 2366 2367// --- AudioInputDescriptor class implementation 2368 2369AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor() 2370 : mSamplingRate(0), mFormat(0), mChannels(0), 2371 mAcoustics((AudioSystem::audio_in_acoustics)0), mDevice(0), mRefCount(0), 2372 mInputSource(0) 2373{ 2374} 2375 2376status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd) 2377{ 2378 const size_t SIZE = 256; 2379 char buffer[SIZE]; 2380 String8 result; 2381 2382 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate); 2383 result.append(buffer); 2384 snprintf(buffer, SIZE, " Format: %d\n", mFormat); 2385 result.append(buffer); 2386 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels); 2387 result.append(buffer); 2388 snprintf(buffer, SIZE, " Acoustics %08x\n", mAcoustics); 2389 result.append(buffer); 2390 snprintf(buffer, SIZE, " Devices %08x\n", mDevice); 2391 result.append(buffer); 2392 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount); 2393 result.append(buffer); 2394 write(fd, result.string(), result.size()); 2395 2396 return NO_ERROR; 2397} 2398 2399// --- StreamDescriptor class implementation 2400 2401void AudioPolicyManagerBase::StreamDescriptor::dump(char* buffer, size_t size) 2402{ 2403 snprintf(buffer, size, " %02d %02d %02d %d\n", 2404 mIndexMin, 2405 mIndexMax, 2406 mIndexCur, 2407 mCanBeMuted); 2408} 2409 2410// --- EffectDescriptor class implementation 2411 2412status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd) 2413{ 2414 const size_t SIZE = 256; 2415 char buffer[SIZE]; 2416 String8 result; 2417 2418 snprintf(buffer, SIZE, " I/O: %d\n", mIo); 2419 result.append(buffer); 2420 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy); 2421 result.append(buffer); 2422 snprintf(buffer, SIZE, " Session: %d\n", mSession); 2423 result.append(buffer); 2424 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name); 2425 result.append(buffer); 2426 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled"); 2427 result.append(buffer); 2428 write(fd, result.string(), result.size()); 2429 2430 return NO_ERROR; 2431} 2432 2433 2434 2435}; // namespace android 2436