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 <media/mediarecorder.h> 22 23 namespace android { 24 25 26 // ---------------------------------------------------------------------------- 27 // AudioPolicyInterface implementation 28 // ---------------------------------------------------------------------------- 29 30 31 status_t AudioPolicyManagerBase::setDeviceConnectionState(AudioSystem::audio_devices device, 32 AudioSystem::device_connection_state state, 33 const char *device_address) 34 { 35 36 LOGV("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 LOGE("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 LOGE("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 LOGW("setDeviceConnectionState() device already connected: %x", device); 62 return INVALID_OPERATION; 63 } 64 LOGV("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 LOGV("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 #ifdef WITH_A2DP 85 if (mA2dpOutput != 0 && 86 mPhoneState != AudioSystem::MODE_NORMAL) { 87 mpClientInterface->suspendOutput(mA2dpOutput); 88 } 89 #endif 90 } 91 } 92 break; 93 // handle output device disconnection 94 case AudioSystem::DEVICE_STATE_UNAVAILABLE: { 95 if (!(mAvailableOutputDevices & device)) { 96 LOGW("setDeviceConnectionState() device not connected: %x", device); 97 return INVALID_OPERATION; 98 } 99 100 101 LOGV("setDeviceConnectionState() disconnecting device %x", device); 102 // remove device from available output devices 103 mAvailableOutputDevices &= ~device; 104 105 #ifdef WITH_A2DP 106 // handle A2DP device disconnection 107 if (AudioSystem::isA2dpDevice(device)) { 108 status_t status = handleA2dpDisconnection(device, device_address); 109 if (status != NO_ERROR) { 110 mAvailableOutputDevices |= device; 111 return status; 112 } 113 } else 114 #endif 115 { 116 if (AudioSystem::isBluetoothScoDevice(device)) { 117 mScoDeviceAddress = ""; 118 #ifdef WITH_A2DP 119 if (mA2dpOutput != 0 && 120 mPhoneState != AudioSystem::MODE_NORMAL) { 121 mpClientInterface->restoreOutput(mA2dpOutput); 122 } 123 #endif 124 } 125 } 126 } break; 127 128 default: 129 LOGE("setDeviceConnectionState() invalid state: %x", state); 130 return BAD_VALUE; 131 } 132 133 // request routing change if necessary 134 uint32_t newDevice = getNewDevice(mHardwareOutput, false); 135 #ifdef WITH_A2DP 136 checkOutputForAllStrategies(newDevice); 137 // A2DP outputs must be closed after checkOutputForAllStrategies() is executed 138 if (state == AudioSystem::DEVICE_STATE_UNAVAILABLE && AudioSystem::isA2dpDevice(device)) { 139 closeA2dpOutputs(); 140 } 141 #endif 142 updateDeviceForStrategy(); 143 setOutputDevice(mHardwareOutput, newDevice); 144 145 if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET) { 146 device = AudioSystem::DEVICE_IN_WIRED_HEADSET; 147 } else if (device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO || 148 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET || 149 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) { 150 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET; 151 } else { 152 return NO_ERROR; 153 } 154 } 155 // handle input devices 156 if (AudioSystem::isInputDevice(device)) { 157 158 switch (state) 159 { 160 // handle input device connection 161 case AudioSystem::DEVICE_STATE_AVAILABLE: { 162 if (mAvailableInputDevices & device) { 163 LOGW("setDeviceConnectionState() device already connected: %d", device); 164 return INVALID_OPERATION; 165 } 166 mAvailableInputDevices |= device; 167 } 168 break; 169 170 // handle input device disconnection 171 case AudioSystem::DEVICE_STATE_UNAVAILABLE: { 172 if (!(mAvailableInputDevices & device)) { 173 LOGW("setDeviceConnectionState() device not connected: %d", device); 174 return INVALID_OPERATION; 175 } 176 mAvailableInputDevices &= ~device; 177 } break; 178 179 default: 180 LOGE("setDeviceConnectionState() invalid state: %x", state); 181 return BAD_VALUE; 182 } 183 184 audio_io_handle_t activeInput = getActiveInput(); 185 if (activeInput != 0) { 186 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput); 187 uint32_t newDevice = getDeviceForInputSource(inputDesc->mInputSource); 188 if (newDevice != inputDesc->mDevice) { 189 LOGV("setDeviceConnectionState() changing device from %x to %x for input %d", 190 inputDesc->mDevice, newDevice, activeInput); 191 inputDesc->mDevice = newDevice; 192 AudioParameter param = AudioParameter(); 193 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice); 194 mpClientInterface->setParameters(activeInput, param.toString()); 195 } 196 } 197 198 return NO_ERROR; 199 } 200 201 LOGW("setDeviceConnectionState() invalid device: %x", device); 202 return BAD_VALUE; 203 } 204 205 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(AudioSystem::audio_devices device, 206 const char *device_address) 207 { 208 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE; 209 String8 address = String8(device_address); 210 if (AudioSystem::isOutputDevice(device)) { 211 if (device & mAvailableOutputDevices) { 212 #ifdef WITH_A2DP 213 if (AudioSystem::isA2dpDevice(device) && 214 address != "" && mA2dpDeviceAddress != address) { 215 return state; 216 } 217 #endif 218 if (AudioSystem::isBluetoothScoDevice(device) && 219 address != "" && mScoDeviceAddress != address) { 220 return state; 221 } 222 state = AudioSystem::DEVICE_STATE_AVAILABLE; 223 } 224 } else if (AudioSystem::isInputDevice(device)) { 225 if (device & mAvailableInputDevices) { 226 state = AudioSystem::DEVICE_STATE_AVAILABLE; 227 } 228 } 229 230 return state; 231 } 232 233 void AudioPolicyManagerBase::setPhoneState(int state) 234 { 235 LOGV("setPhoneState() state %d", state); 236 uint32_t newDevice = 0; 237 if (state < 0 || state >= AudioSystem::NUM_MODES) { 238 LOGW("setPhoneState() invalid state %d", state); 239 return; 240 } 241 242 if (state == mPhoneState ) { 243 LOGW("setPhoneState() setting same state %d", state); 244 return; 245 } 246 247 // if leaving call state, handle special case of active streams 248 // pertaining to sonification strategy see handleIncallSonification() 249 if (mPhoneState == AudioSystem::MODE_IN_CALL) { 250 LOGV("setPhoneState() in call state management: new state is %d", state); 251 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) { 252 handleIncallSonification(stream, false, true); 253 } 254 } 255 256 // store previous phone state for management of sonification strategy below 257 int oldState = mPhoneState; 258 mPhoneState = state; 259 bool force = false; 260 261 // are we entering or starting a call 262 if ((oldState != AudioSystem::MODE_IN_CALL) && (state == AudioSystem::MODE_IN_CALL)) { 263 LOGV(" Entering call in setPhoneState()"); 264 // force routing command to audio hardware when starting a call 265 // even if no device change is needed 266 force = true; 267 } else if ((oldState == AudioSystem::MODE_IN_CALL) && (state != AudioSystem::MODE_IN_CALL)) { 268 LOGV(" Exiting call in setPhoneState()"); 269 // force routing command to audio hardware when exiting a call 270 // even if no device change is needed 271 force = true; 272 } 273 274 // check for device and output changes triggered by new phone state 275 newDevice = getNewDevice(mHardwareOutput, false); 276 #ifdef WITH_A2DP 277 checkOutputForAllStrategies(newDevice); 278 // suspend A2DP output if a SCO device is present. 279 if (mA2dpOutput != 0 && mScoDeviceAddress != "") { 280 if (oldState == AudioSystem::MODE_NORMAL) { 281 mpClientInterface->suspendOutput(mA2dpOutput); 282 } else if (state == AudioSystem::MODE_NORMAL) { 283 mpClientInterface->restoreOutput(mA2dpOutput); 284 } 285 } 286 #endif 287 updateDeviceForStrategy(); 288 289 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput); 290 291 // force routing command to audio hardware when ending call 292 // even if no device change is needed 293 if (oldState == AudioSystem::MODE_IN_CALL && newDevice == 0) { 294 newDevice = hwOutputDesc->device(); 295 } 296 297 // when changing from ring tone to in call mode, mute the ringing tone 298 // immediately and delay the route change to avoid sending the ring tone 299 // tail into the earpiece or headset. 300 int delayMs = 0; 301 if (state == AudioSystem::MODE_IN_CALL && oldState == AudioSystem::MODE_RINGTONE) { 302 // delay the device change command by twice the output latency to have some margin 303 // and be sure that audio buffers not yet affected by the mute are out when 304 // we actually apply the route change 305 delayMs = hwOutputDesc->mLatency*2; 306 setStreamMute(AudioSystem::RING, true, mHardwareOutput); 307 } 308 309 // change routing is necessary 310 setOutputDevice(mHardwareOutput, newDevice, force, delayMs); 311 312 // if entering in call state, handle special case of active streams 313 // pertaining to sonification strategy see handleIncallSonification() 314 if (state == AudioSystem::MODE_IN_CALL) { 315 LOGV("setPhoneState() in call state management: new state is %d", state); 316 // unmute the ringing tone after a sufficient delay if it was muted before 317 // setting output device above 318 if (oldState == AudioSystem::MODE_RINGTONE) { 319 setStreamMute(AudioSystem::RING, false, mHardwareOutput, MUTE_TIME_MS); 320 } 321 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) { 322 handleIncallSonification(stream, true, true); 323 } 324 } 325 326 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE 327 if (state == AudioSystem::MODE_RINGTONE && 328 (hwOutputDesc->mRefCount[AudioSystem::MUSIC] || 329 (systemTime() - mMusicStopTime) < seconds(SONIFICATION_HEADSET_MUSIC_DELAY))) { 330 mLimitRingtoneVolume = true; 331 } else { 332 mLimitRingtoneVolume = false; 333 } 334 } 335 336 void AudioPolicyManagerBase::setRingerMode(uint32_t mode, uint32_t mask) 337 { 338 LOGV("setRingerMode() mode %x, mask %x", mode, mask); 339 340 mRingerMode = mode; 341 } 342 343 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config) 344 { 345 LOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState); 346 347 bool forceVolumeReeval = false; 348 switch(usage) { 349 case AudioSystem::FOR_COMMUNICATION: 350 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO && 351 config != AudioSystem::FORCE_NONE) { 352 LOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config); 353 return; 354 } 355 mForceUse[usage] = config; 356 break; 357 case AudioSystem::FOR_MEDIA: 358 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP && 359 config != AudioSystem::FORCE_WIRED_ACCESSORY && config != AudioSystem::FORCE_NONE) { 360 LOGW("setForceUse() invalid config %d for FOR_MEDIA", config); 361 return; 362 } 363 mForceUse[usage] = config; 364 break; 365 case AudioSystem::FOR_RECORD: 366 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY && 367 config != AudioSystem::FORCE_NONE) { 368 LOGW("setForceUse() invalid config %d for FOR_RECORD", config); 369 return; 370 } 371 mForceUse[usage] = config; 372 break; 373 case AudioSystem::FOR_DOCK: 374 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK && 375 config != AudioSystem::FORCE_BT_DESK_DOCK && config != AudioSystem::FORCE_WIRED_ACCESSORY) { 376 LOGW("setForceUse() invalid config %d for FOR_DOCK", config); 377 } 378 forceVolumeReeval = true; 379 mForceUse[usage] = config; 380 break; 381 default: 382 LOGW("setForceUse() invalid usage %d", usage); 383 break; 384 } 385 386 // check for device and output changes triggered by new phone state 387 uint32_t newDevice = getNewDevice(mHardwareOutput, false); 388 #ifdef WITH_A2DP 389 checkOutputForAllStrategies(newDevice); 390 #endif 391 updateDeviceForStrategy(); 392 setOutputDevice(mHardwareOutput, newDevice); 393 if (forceVolumeReeval) { 394 applyStreamVolumes(mHardwareOutput, newDevice); 395 } 396 } 397 398 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage) 399 { 400 return mForceUse[usage]; 401 } 402 403 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value) 404 { 405 LOGV("setSystemProperty() property %s, value %s", property, value); 406 if (strcmp(property, "ro.camera.sound.forced") == 0) { 407 if (atoi(value)) { 408 LOGV("ENFORCED_AUDIBLE cannot be muted"); 409 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false; 410 } else { 411 LOGV("ENFORCED_AUDIBLE can be muted"); 412 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = true; 413 } 414 } 415 } 416 417 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream, 418 uint32_t samplingRate, 419 uint32_t format, 420 uint32_t channels, 421 AudioSystem::output_flags flags) 422 { 423 audio_io_handle_t output = 0; 424 uint32_t latency = 0; 425 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream); 426 uint32_t device = getDeviceForStrategy(strategy); 427 LOGV("getOutput() stream %d, samplingRate %d, format %d, channels %x, flags %x", stream, samplingRate, format, channels, flags); 428 429 #ifdef AUDIO_POLICY_TEST 430 if (mCurOutput != 0) { 431 LOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channels %x, mDirectOutput %d", 432 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput); 433 434 if (mTestOutputs[mCurOutput] == 0) { 435 LOGV("getOutput() opening test output"); 436 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(); 437 outputDesc->mDevice = mTestDevice; 438 outputDesc->mSamplingRate = mTestSamplingRate; 439 outputDesc->mFormat = mTestFormat; 440 outputDesc->mChannels = mTestChannels; 441 outputDesc->mLatency = mTestLatencyMs; 442 outputDesc->mFlags = (AudioSystem::output_flags)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0); 443 outputDesc->mRefCount[stream] = 0; 444 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(&outputDesc->mDevice, 445 &outputDesc->mSamplingRate, 446 &outputDesc->mFormat, 447 &outputDesc->mChannels, 448 &outputDesc->mLatency, 449 outputDesc->mFlags); 450 if (mTestOutputs[mCurOutput]) { 451 AudioParameter outputCmd = AudioParameter(); 452 outputCmd.addInt(String8("set_id"),mCurOutput); 453 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString()); 454 addOutput(mTestOutputs[mCurOutput], outputDesc); 455 } 456 } 457 return mTestOutputs[mCurOutput]; 458 } 459 #endif //AUDIO_POLICY_TEST 460 461 // open a direct output if required by specified parameters 462 if (needsDirectOuput(stream, samplingRate, format, channels, flags, device)) { 463 464 LOGV("getOutput() opening direct output device %x", device); 465 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(); 466 outputDesc->mDevice = device; 467 outputDesc->mSamplingRate = samplingRate; 468 outputDesc->mFormat = format; 469 outputDesc->mChannels = channels; 470 outputDesc->mLatency = 0; 471 outputDesc->mFlags = (AudioSystem::output_flags)(flags | AudioSystem::OUTPUT_FLAG_DIRECT); 472 outputDesc->mRefCount[stream] = 0; 473 output = mpClientInterface->openOutput(&outputDesc->mDevice, 474 &outputDesc->mSamplingRate, 475 &outputDesc->mFormat, 476 &outputDesc->mChannels, 477 &outputDesc->mLatency, 478 outputDesc->mFlags); 479 480 // only accept an output with the requeted parameters 481 if (output == 0 || 482 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) || 483 (format != 0 && format != outputDesc->mFormat) || 484 (channels != 0 && channels != outputDesc->mChannels)) { 485 LOGV("getOutput() failed opening direct output: samplingRate %d, format %d, channels %d", 486 samplingRate, format, channels); 487 if (output != 0) { 488 mpClientInterface->closeOutput(output); 489 } 490 delete outputDesc; 491 return 0; 492 } 493 addOutput(output, outputDesc); 494 return output; 495 } 496 497 if (channels != 0 && channels != AudioSystem::CHANNEL_OUT_MONO && 498 channels != AudioSystem::CHANNEL_OUT_STEREO) { 499 return 0; 500 } 501 // open a non direct output 502 503 // get which output is suitable for the specified stream. The actual routing change will happen 504 // when startOutput() will be called 505 uint32_t a2dpDevice = device & AudioSystem::DEVICE_OUT_ALL_A2DP; 506 if (AudioSystem::popCount((AudioSystem::audio_devices)device) == 2) { 507 #ifdef WITH_A2DP 508 if (a2dpUsedForSonification() && a2dpDevice != 0) { 509 // if playing on 2 devices among which one is A2DP, use duplicated output 510 LOGV("getOutput() using duplicated output"); 511 LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device in multiple %x selected but A2DP output not opened", device); 512 output = mDuplicatedOutput; 513 } else 514 #endif 515 { 516 // if playing on 2 devices among which none is A2DP, use hardware output 517 output = mHardwareOutput; 518 } 519 LOGV("getOutput() using output %d for 2 devices %x", output, device); 520 } else { 521 #ifdef WITH_A2DP 522 if (a2dpDevice != 0) { 523 // if playing on A2DP device, use a2dp output 524 LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device %x selected but A2DP output not opened", device); 525 output = mA2dpOutput; 526 } else 527 #endif 528 { 529 // if playing on not A2DP device, use hardware output 530 output = mHardwareOutput; 531 } 532 } 533 534 535 LOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d, format %d, channels %x, flags %x", 536 stream, samplingRate, format, channels, flags); 537 538 return output; 539 } 540 541 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output, AudioSystem::stream_type stream) 542 { 543 LOGV("startOutput() output %d, stream %d", output, stream); 544 ssize_t index = mOutputs.indexOfKey(output); 545 if (index < 0) { 546 LOGW("startOutput() unknow output %d", output); 547 return BAD_VALUE; 548 } 549 550 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index); 551 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream); 552 553 #ifdef WITH_A2DP 554 if (mA2dpOutput != 0 && !a2dpUsedForSonification() && strategy == STRATEGY_SONIFICATION) { 555 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput); 556 } 557 #endif 558 559 // incremenent usage count for this stream on the requested output: 560 // NOTE that the usage count is the same for duplicated output and hardware output which is 561 // necassary for a correct control of hardware output routing by startOutput() and stopOutput() 562 outputDesc->changeRefCount(stream, 1); 563 564 setOutputDevice(output, getNewDevice(output)); 565 566 // handle special case for sonification while in call 567 if (mPhoneState == AudioSystem::MODE_IN_CALL) { 568 handleIncallSonification(stream, true, false); 569 } 570 571 // apply volume rules for current stream and device if necessary 572 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, outputDesc->device()); 573 574 return NO_ERROR; 575 } 576 577 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output, AudioSystem::stream_type stream) 578 { 579 LOGV("stopOutput() output %d, stream %d", output, stream); 580 ssize_t index = mOutputs.indexOfKey(output); 581 if (index < 0) { 582 LOGW("stopOutput() unknow output %d", output); 583 return BAD_VALUE; 584 } 585 586 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index); 587 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream); 588 589 // handle special case for sonification while in call 590 if (mPhoneState == AudioSystem::MODE_IN_CALL) { 591 handleIncallSonification(stream, false, false); 592 } 593 594 if (outputDesc->mRefCount[stream] > 0) { 595 // decrement usage count of this stream on the output 596 outputDesc->changeRefCount(stream, -1); 597 // store time at which the last music track was stopped - see computeVolume() 598 if (stream == AudioSystem::MUSIC) { 599 mMusicStopTime = systemTime(); 600 } 601 602 setOutputDevice(output, getNewDevice(output)); 603 604 #ifdef WITH_A2DP 605 if (mA2dpOutput != 0 && !a2dpUsedForSonification() && strategy == STRATEGY_SONIFICATION) { 606 setStrategyMute(STRATEGY_MEDIA, false, mA2dpOutput, mOutputs.valueFor(mHardwareOutput)->mLatency*2); 607 } 608 #endif 609 if (output != mHardwareOutput) { 610 setOutputDevice(mHardwareOutput, getNewDevice(mHardwareOutput), true); 611 } 612 return NO_ERROR; 613 } else { 614 LOGW("stopOutput() refcount is already 0 for output %d", output); 615 return INVALID_OPERATION; 616 } 617 } 618 619 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output) 620 { 621 LOGV("releaseOutput() %d", output); 622 ssize_t index = mOutputs.indexOfKey(output); 623 if (index < 0) { 624 LOGW("releaseOutput() releasing unknown output %d", output); 625 return; 626 } 627 628 #ifdef AUDIO_POLICY_TEST 629 int testIndex = testOutputIndex(output); 630 if (testIndex != 0) { 631 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index); 632 if (outputDesc->refCount() == 0) { 633 mpClientInterface->closeOutput(output); 634 delete mOutputs.valueAt(index); 635 mOutputs.removeItem(output); 636 mTestOutputs[testIndex] = 0; 637 } 638 return; 639 } 640 #endif //AUDIO_POLICY_TEST 641 642 if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) { 643 mpClientInterface->closeOutput(output); 644 delete mOutputs.valueAt(index); 645 mOutputs.removeItem(output); 646 } 647 } 648 649 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource, 650 uint32_t samplingRate, 651 uint32_t format, 652 uint32_t channels, 653 AudioSystem::audio_in_acoustics acoustics) 654 { 655 audio_io_handle_t input = 0; 656 uint32_t device = getDeviceForInputSource(inputSource); 657 658 LOGV("getInput() inputSource %d, samplingRate %d, format %d, channels %x, acoustics %x", inputSource, samplingRate, format, channels, acoustics); 659 660 if (device == 0) { 661 return 0; 662 } 663 664 // adapt channel selection to input source 665 switch(inputSource) { 666 case AUDIO_SOURCE_VOICE_UPLINK: 667 channels = AudioSystem::CHANNEL_IN_VOICE_UPLINK; 668 break; 669 case AUDIO_SOURCE_VOICE_DOWNLINK: 670 channels = AudioSystem::CHANNEL_IN_VOICE_DNLINK; 671 break; 672 case AUDIO_SOURCE_VOICE_CALL: 673 channels = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK); 674 break; 675 default: 676 break; 677 } 678 679 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(); 680 681 inputDesc->mInputSource = inputSource; 682 inputDesc->mDevice = device; 683 inputDesc->mSamplingRate = samplingRate; 684 inputDesc->mFormat = format; 685 inputDesc->mChannels = channels; 686 inputDesc->mAcoustics = acoustics; 687 inputDesc->mRefCount = 0; 688 input = mpClientInterface->openInput(&inputDesc->mDevice, 689 &inputDesc->mSamplingRate, 690 &inputDesc->mFormat, 691 &inputDesc->mChannels, 692 inputDesc->mAcoustics); 693 694 // only accept input with the exact requested set of parameters 695 if (input == 0 || 696 (samplingRate != inputDesc->mSamplingRate) || 697 (format != inputDesc->mFormat) || 698 (channels != inputDesc->mChannels)) { 699 LOGV("getInput() failed opening input: samplingRate %d, format %d, channels %d", 700 samplingRate, format, channels); 701 if (input != 0) { 702 mpClientInterface->closeInput(input); 703 } 704 delete inputDesc; 705 return 0; 706 } 707 mInputs.add(input, inputDesc); 708 return input; 709 } 710 711 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input) 712 { 713 LOGV("startInput() input %d", input); 714 ssize_t index = mInputs.indexOfKey(input); 715 if (index < 0) { 716 LOGW("startInput() unknow input %d", input); 717 return BAD_VALUE; 718 } 719 AudioInputDescriptor *inputDesc = mInputs.valueAt(index); 720 721 #ifdef AUDIO_POLICY_TEST 722 if (mTestInput == 0) 723 #endif //AUDIO_POLICY_TEST 724 { 725 // refuse 2 active AudioRecord clients at the same time 726 if (getActiveInput() != 0) { 727 LOGW("startInput() input %d failed: other input already started", input); 728 return INVALID_OPERATION; 729 } 730 } 731 732 AudioParameter param = AudioParameter(); 733 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice); 734 735 // use Voice Recognition mode or not for this input based on input source 736 int vr_enabled = inputDesc->mInputSource == AUDIO_SOURCE_VOICE_RECOGNITION ? 1 : 0; 737 param.addInt(String8("vr_mode"), vr_enabled); 738 LOGV("AudioPolicyManager::startInput(%d), setting vr_mode to %d", inputDesc->mInputSource, vr_enabled); 739 740 mpClientInterface->setParameters(input, param.toString()); 741 742 inputDesc->mRefCount = 1; 743 return NO_ERROR; 744 } 745 746 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input) 747 { 748 LOGV("stopInput() input %d", input); 749 ssize_t index = mInputs.indexOfKey(input); 750 if (index < 0) { 751 LOGW("stopInput() unknow input %d", input); 752 return BAD_VALUE; 753 } 754 AudioInputDescriptor *inputDesc = mInputs.valueAt(index); 755 756 if (inputDesc->mRefCount == 0) { 757 LOGW("stopInput() input %d already stopped", input); 758 return INVALID_OPERATION; 759 } else { 760 AudioParameter param = AudioParameter(); 761 param.addInt(String8(AudioParameter::keyRouting), 0); 762 mpClientInterface->setParameters(input, param.toString()); 763 inputDesc->mRefCount = 0; 764 return NO_ERROR; 765 } 766 } 767 768 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input) 769 { 770 LOGV("releaseInput() %d", input); 771 ssize_t index = mInputs.indexOfKey(input); 772 if (index < 0) { 773 LOGW("releaseInput() releasing unknown input %d", input); 774 return; 775 } 776 mpClientInterface->closeInput(input); 777 delete mInputs.valueAt(index); 778 mInputs.removeItem(input); 779 LOGV("releaseInput() exit"); 780 } 781 782 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream, 783 int indexMin, 784 int indexMax) 785 { 786 LOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax); 787 if (indexMin < 0 || indexMin >= indexMax) { 788 LOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax); 789 return; 790 } 791 mStreams[stream].mIndexMin = indexMin; 792 mStreams[stream].mIndexMax = indexMax; 793 } 794 795 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream, int index) 796 { 797 798 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) { 799 return BAD_VALUE; 800 } 801 802 // Force max volume if stream cannot be muted 803 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax; 804 805 LOGV("setStreamVolumeIndex() stream %d, index %d", stream, index); 806 mStreams[stream].mIndexCur = index; 807 808 // compute and apply stream volume on all outputs according to connected device 809 status_t status = NO_ERROR; 810 for (size_t i = 0; i < mOutputs.size(); i++) { 811 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), mOutputs.valueAt(i)->device()); 812 if (volStatus != NO_ERROR) { 813 status = volStatus; 814 } 815 } 816 return status; 817 } 818 819 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream, int *index) 820 { 821 if (index == 0) { 822 return BAD_VALUE; 823 } 824 LOGV("getStreamVolumeIndex() stream %d", stream); 825 *index = mStreams[stream].mIndexCur; 826 return NO_ERROR; 827 } 828 829 status_t AudioPolicyManagerBase::dump(int fd) 830 { 831 const size_t SIZE = 256; 832 char buffer[SIZE]; 833 String8 result; 834 835 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this); 836 result.append(buffer); 837 snprintf(buffer, SIZE, " Hardware Output: %d\n", mHardwareOutput); 838 result.append(buffer); 839 #ifdef WITH_A2DP 840 snprintf(buffer, SIZE, " A2DP Output: %d\n", mA2dpOutput); 841 result.append(buffer); 842 snprintf(buffer, SIZE, " Duplicated Output: %d\n", mDuplicatedOutput); 843 result.append(buffer); 844 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string()); 845 result.append(buffer); 846 #endif 847 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string()); 848 result.append(buffer); 849 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices); 850 result.append(buffer); 851 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices); 852 result.append(buffer); 853 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState); 854 result.append(buffer); 855 snprintf(buffer, SIZE, " Ringer mode: %d\n", mRingerMode); 856 result.append(buffer); 857 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]); 858 result.append(buffer); 859 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]); 860 result.append(buffer); 861 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]); 862 result.append(buffer); 863 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]); 864 result.append(buffer); 865 write(fd, result.string(), result.size()); 866 867 snprintf(buffer, SIZE, "\nOutputs dump:\n"); 868 write(fd, buffer, strlen(buffer)); 869 for (size_t i = 0; i < mOutputs.size(); i++) { 870 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i)); 871 write(fd, buffer, strlen(buffer)); 872 mOutputs.valueAt(i)->dump(fd); 873 } 874 875 snprintf(buffer, SIZE, "\nInputs dump:\n"); 876 write(fd, buffer, strlen(buffer)); 877 for (size_t i = 0; i < mInputs.size(); i++) { 878 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i)); 879 write(fd, buffer, strlen(buffer)); 880 mInputs.valueAt(i)->dump(fd); 881 } 882 883 snprintf(buffer, SIZE, "\nStreams dump:\n"); 884 write(fd, buffer, strlen(buffer)); 885 snprintf(buffer, SIZE, " Stream Index Min Index Max Index Cur Can be muted\n"); 886 write(fd, buffer, strlen(buffer)); 887 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) { 888 snprintf(buffer, SIZE, " %02d", i); 889 mStreams[i].dump(buffer + 3, SIZE); 890 write(fd, buffer, strlen(buffer)); 891 } 892 893 return NO_ERROR; 894 } 895 896 // ---------------------------------------------------------------------------- 897 // AudioPolicyManagerBase 898 // ---------------------------------------------------------------------------- 899 900 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface) 901 : 902 #ifdef AUDIO_POLICY_TEST 903 Thread(false), 904 #endif //AUDIO_POLICY_TEST 905 mPhoneState(AudioSystem::MODE_NORMAL), mRingerMode(0), mMusicStopTime(0), mLimitRingtoneVolume(false) 906 { 907 mpClientInterface = clientInterface; 908 909 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) { 910 mForceUse[i] = AudioSystem::FORCE_NONE; 911 } 912 913 // devices available by default are speaker, ear piece and microphone 914 mAvailableOutputDevices = AudioSystem::DEVICE_OUT_EARPIECE | 915 AudioSystem::DEVICE_OUT_SPEAKER; 916 mAvailableInputDevices = AudioSystem::DEVICE_IN_BUILTIN_MIC; 917 918 #ifdef WITH_A2DP 919 mA2dpOutput = 0; 920 mDuplicatedOutput = 0; 921 mA2dpDeviceAddress = String8(""); 922 #endif 923 mScoDeviceAddress = String8(""); 924 925 // open hardware output 926 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(); 927 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER; 928 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice, 929 &outputDesc->mSamplingRate, 930 &outputDesc->mFormat, 931 &outputDesc->mChannels, 932 &outputDesc->mLatency, 933 outputDesc->mFlags); 934 935 if (mHardwareOutput == 0) { 936 LOGE("Failed to initialize hardware output stream, samplingRate: %d, format %d, channels %d", 937 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels); 938 } else { 939 addOutput(mHardwareOutput, outputDesc); 940 setOutputDevice(mHardwareOutput, (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER, true); 941 } 942 943 updateDeviceForStrategy(); 944 #ifdef AUDIO_POLICY_TEST 945 AudioParameter outputCmd = AudioParameter(); 946 outputCmd.addInt(String8("set_id"), 0); 947 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString()); 948 949 mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER; 950 mTestSamplingRate = 44100; 951 mTestFormat = AudioSystem::PCM_16_BIT; 952 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO; 953 mTestLatencyMs = 0; 954 mCurOutput = 0; 955 mDirectOutput = false; 956 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) { 957 mTestOutputs[i] = 0; 958 } 959 960 const size_t SIZE = 256; 961 char buffer[SIZE]; 962 snprintf(buffer, SIZE, "AudioPolicyManagerTest"); 963 run(buffer, ANDROID_PRIORITY_AUDIO); 964 #endif //AUDIO_POLICY_TEST 965 } 966 967 AudioPolicyManagerBase::~AudioPolicyManagerBase() 968 { 969 #ifdef AUDIO_POLICY_TEST 970 exit(); 971 #endif //AUDIO_POLICY_TEST 972 for (size_t i = 0; i < mOutputs.size(); i++) { 973 mpClientInterface->closeOutput(mOutputs.keyAt(i)); 974 delete mOutputs.valueAt(i); 975 } 976 mOutputs.clear(); 977 for (size_t i = 0; i < mInputs.size(); i++) { 978 mpClientInterface->closeInput(mInputs.keyAt(i)); 979 delete mInputs.valueAt(i); 980 } 981 mInputs.clear(); 982 } 983 984 #ifdef AUDIO_POLICY_TEST 985 bool AudioPolicyManagerBase::threadLoop() 986 { 987 LOGV("entering threadLoop()"); 988 while (!exitPending()) 989 { 990 String8 command; 991 int valueInt; 992 String8 value; 993 994 Mutex::Autolock _l(mLock); 995 mWaitWorkCV.waitRelative(mLock, milliseconds(50)); 996 997 command = mpClientInterface->getParameters(0, String8("test_cmd_policy")); 998 AudioParameter param = AudioParameter(command); 999 1000 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR && 1001 valueInt != 0) { 1002 LOGV("Test command %s received", command.string()); 1003 String8 target; 1004 if (param.get(String8("target"), target) != NO_ERROR) { 1005 target = "Manager"; 1006 } 1007 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) { 1008 param.remove(String8("test_cmd_policy_output")); 1009 mCurOutput = valueInt; 1010 } 1011 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) { 1012 param.remove(String8("test_cmd_policy_direct")); 1013 if (value == "false") { 1014 mDirectOutput = false; 1015 } else if (value == "true") { 1016 mDirectOutput = true; 1017 } 1018 } 1019 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) { 1020 param.remove(String8("test_cmd_policy_input")); 1021 mTestInput = valueInt; 1022 } 1023 1024 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) { 1025 param.remove(String8("test_cmd_policy_format")); 1026 int format = AudioSystem::INVALID_FORMAT; 1027 if (value == "PCM 16 bits") { 1028 format = AudioSystem::PCM_16_BIT; 1029 } else if (value == "PCM 8 bits") { 1030 format = AudioSystem::PCM_8_BIT; 1031 } else if (value == "Compressed MP3") { 1032 format = AudioSystem::MP3; 1033 } 1034 if (format != AudioSystem::INVALID_FORMAT) { 1035 if (target == "Manager") { 1036 mTestFormat = format; 1037 } else if (mTestOutputs[mCurOutput] != 0) { 1038 AudioParameter outputParam = AudioParameter(); 1039 outputParam.addInt(String8("format"), format); 1040 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 1041 } 1042 } 1043 } 1044 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) { 1045 param.remove(String8("test_cmd_policy_channels")); 1046 int channels = 0; 1047 1048 if (value == "Channels Stereo") { 1049 channels = AudioSystem::CHANNEL_OUT_STEREO; 1050 } else if (value == "Channels Mono") { 1051 channels = AudioSystem::CHANNEL_OUT_MONO; 1052 } 1053 if (channels != 0) { 1054 if (target == "Manager") { 1055 mTestChannels = channels; 1056 } else if (mTestOutputs[mCurOutput] != 0) { 1057 AudioParameter outputParam = AudioParameter(); 1058 outputParam.addInt(String8("channels"), channels); 1059 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 1060 } 1061 } 1062 } 1063 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) { 1064 param.remove(String8("test_cmd_policy_sampleRate")); 1065 if (valueInt >= 0 && valueInt <= 96000) { 1066 int samplingRate = valueInt; 1067 if (target == "Manager") { 1068 mTestSamplingRate = samplingRate; 1069 } else if (mTestOutputs[mCurOutput] != 0) { 1070 AudioParameter outputParam = AudioParameter(); 1071 outputParam.addInt(String8("sampling_rate"), samplingRate); 1072 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 1073 } 1074 } 1075 } 1076 1077 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) { 1078 param.remove(String8("test_cmd_policy_reopen")); 1079 1080 mpClientInterface->closeOutput(mHardwareOutput); 1081 delete mOutputs.valueFor(mHardwareOutput); 1082 mOutputs.removeItem(mHardwareOutput); 1083 1084 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(); 1085 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER; 1086 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice, 1087 &outputDesc->mSamplingRate, 1088 &outputDesc->mFormat, 1089 &outputDesc->mChannels, 1090 &outputDesc->mLatency, 1091 outputDesc->mFlags); 1092 if (mHardwareOutput == 0) { 1093 LOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d", 1094 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels); 1095 } else { 1096 AudioParameter outputCmd = AudioParameter(); 1097 outputCmd.addInt(String8("set_id"), 0); 1098 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString()); 1099 addOutput(mHardwareOutput, outputDesc); 1100 } 1101 } 1102 1103 1104 mpClientInterface->setParameters(0, String8("test_cmd_policy=")); 1105 } 1106 } 1107 return false; 1108 } 1109 1110 void AudioPolicyManagerBase::exit() 1111 { 1112 { 1113 AutoMutex _l(mLock); 1114 requestExit(); 1115 mWaitWorkCV.signal(); 1116 } 1117 requestExitAndWait(); 1118 } 1119 1120 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output) 1121 { 1122 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) { 1123 if (output == mTestOutputs[i]) return i; 1124 } 1125 return 0; 1126 } 1127 #endif //AUDIO_POLICY_TEST 1128 1129 // --- 1130 1131 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc) 1132 { 1133 outputDesc->mId = id; 1134 mOutputs.add(id, outputDesc); 1135 } 1136 1137 1138 #ifdef WITH_A2DP 1139 status_t AudioPolicyManagerBase::handleA2dpConnection(AudioSystem::audio_devices device, 1140 const char *device_address) 1141 { 1142 // when an A2DP device is connected, open an A2DP and a duplicated output 1143 LOGV("opening A2DP output for device %s", device_address); 1144 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(); 1145 outputDesc->mDevice = device; 1146 mA2dpOutput = mpClientInterface->openOutput(&outputDesc->mDevice, 1147 &outputDesc->mSamplingRate, 1148 &outputDesc->mFormat, 1149 &outputDesc->mChannels, 1150 &outputDesc->mLatency, 1151 outputDesc->mFlags); 1152 if (mA2dpOutput) { 1153 // add A2DP output descriptor 1154 addOutput(mA2dpOutput, outputDesc); 1155 // set initial stream volume for A2DP device 1156 applyStreamVolumes(mA2dpOutput, device); 1157 if (a2dpUsedForSonification()) { 1158 mDuplicatedOutput = mpClientInterface->openDuplicateOutput(mA2dpOutput, mHardwareOutput); 1159 } 1160 if (mDuplicatedOutput != 0 || 1161 !a2dpUsedForSonification()) { 1162 // If both A2DP and duplicated outputs are open, send device address to A2DP hardware 1163 // interface 1164 AudioParameter param; 1165 param.add(String8("a2dp_sink_address"), String8(device_address)); 1166 mpClientInterface->setParameters(mA2dpOutput, param.toString()); 1167 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN); 1168 1169 if (a2dpUsedForSonification()) { 1170 // add duplicated output descriptor 1171 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(); 1172 dupOutputDesc->mOutput1 = mOutputs.valueFor(mHardwareOutput); 1173 dupOutputDesc->mOutput2 = mOutputs.valueFor(mA2dpOutput); 1174 dupOutputDesc->mSamplingRate = outputDesc->mSamplingRate; 1175 dupOutputDesc->mFormat = outputDesc->mFormat; 1176 dupOutputDesc->mChannels = outputDesc->mChannels; 1177 dupOutputDesc->mLatency = outputDesc->mLatency; 1178 addOutput(mDuplicatedOutput, dupOutputDesc); 1179 applyStreamVolumes(mDuplicatedOutput, device); 1180 } 1181 } else { 1182 LOGW("getOutput() could not open duplicated output for %d and %d", 1183 mHardwareOutput, mA2dpOutput); 1184 mpClientInterface->closeOutput(mA2dpOutput); 1185 mOutputs.removeItem(mA2dpOutput); 1186 mA2dpOutput = 0; 1187 delete outputDesc; 1188 return NO_INIT; 1189 } 1190 } else { 1191 LOGW("setDeviceConnectionState() could not open A2DP output for device %x", device); 1192 delete outputDesc; 1193 return NO_INIT; 1194 } 1195 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput); 1196 1197 if (mScoDeviceAddress != "") { 1198 // It is normal to suspend twice if we are both in call, 1199 // and have the hardware audio output routed to BT SCO 1200 if (mPhoneState != AudioSystem::MODE_NORMAL) { 1201 mpClientInterface->suspendOutput(mA2dpOutput); 1202 } 1203 if (AudioSystem::isBluetoothScoDevice((AudioSystem::audio_devices)hwOutputDesc->device())) { 1204 mpClientInterface->suspendOutput(mA2dpOutput); 1205 } 1206 } 1207 1208 if (!a2dpUsedForSonification()) { 1209 // mute music on A2DP output if a notification or ringtone is playing 1210 uint32_t refCount = hwOutputDesc->strategyRefCount(STRATEGY_SONIFICATION); 1211 for (uint32_t i = 0; i < refCount; i++) { 1212 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput); 1213 } 1214 } 1215 return NO_ERROR; 1216 } 1217 1218 status_t AudioPolicyManagerBase::handleA2dpDisconnection(AudioSystem::audio_devices device, 1219 const char *device_address) 1220 { 1221 if (mA2dpOutput == 0) { 1222 LOGW("setDeviceConnectionState() disconnecting A2DP and no A2DP output!"); 1223 return INVALID_OPERATION; 1224 } 1225 1226 if (mA2dpDeviceAddress != device_address) { 1227 LOGW("setDeviceConnectionState() disconnecting unknow A2DP sink address %s", device_address); 1228 return INVALID_OPERATION; 1229 } 1230 1231 // mute media strategy to avoid outputting sound on hardware output while music stream 1232 // is switched from A2DP output and before music is paused by music application 1233 setStrategyMute(STRATEGY_MEDIA, true, mHardwareOutput); 1234 setStrategyMute(STRATEGY_MEDIA, false, mHardwareOutput, MUTE_TIME_MS); 1235 1236 if (!a2dpUsedForSonification()) { 1237 // unmute music on A2DP output if a notification or ringtone is playing 1238 uint32_t refCount = mOutputs.valueFor(mHardwareOutput)->strategyRefCount(STRATEGY_SONIFICATION); 1239 for (uint32_t i = 0; i < refCount; i++) { 1240 setStrategyMute(STRATEGY_MEDIA, false, mA2dpOutput); 1241 } 1242 } 1243 mA2dpDeviceAddress = ""; 1244 return NO_ERROR; 1245 } 1246 1247 void AudioPolicyManagerBase::closeA2dpOutputs() 1248 { 1249 LOGV("setDeviceConnectionState() closing A2DP and duplicated output!"); 1250 1251 if (mDuplicatedOutput != 0) { 1252 mpClientInterface->closeOutput(mDuplicatedOutput); 1253 delete mOutputs.valueFor(mDuplicatedOutput); 1254 mOutputs.removeItem(mDuplicatedOutput); 1255 mDuplicatedOutput = 0; 1256 } 1257 if (mA2dpOutput != 0) { 1258 AudioParameter param; 1259 param.add(String8("closing"), String8("true")); 1260 mpClientInterface->setParameters(mA2dpOutput, param.toString()); 1261 mpClientInterface->closeOutput(mA2dpOutput); 1262 delete mOutputs.valueFor(mA2dpOutput); 1263 mOutputs.removeItem(mA2dpOutput); 1264 mA2dpOutput = 0; 1265 } 1266 } 1267 1268 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy, uint32_t &newDevice) 1269 { 1270 uint32_t prevDevice = getDeviceForStrategy(strategy); 1271 uint32_t curDevice = getDeviceForStrategy(strategy, false); 1272 bool a2dpWasUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(prevDevice & ~AudioSystem::DEVICE_OUT_SPEAKER)); 1273 bool a2dpIsUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(curDevice & ~AudioSystem::DEVICE_OUT_SPEAKER)); 1274 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput); 1275 AudioOutputDescriptor *a2dpOutputDesc; 1276 1277 if (a2dpWasUsed && !a2dpIsUsed) { 1278 bool dupUsed = a2dpUsedForSonification() && a2dpWasUsed && (AudioSystem::popCount(prevDevice) == 2); 1279 1280 if (dupUsed) { 1281 LOGV("checkOutputForStrategy() moving strategy %d to duplicated", strategy); 1282 a2dpOutputDesc = mOutputs.valueFor(mDuplicatedOutput); 1283 } else { 1284 LOGV("checkOutputForStrategy() moving strategy %d to a2dp", strategy); 1285 a2dpOutputDesc = mOutputs.valueFor(mA2dpOutput); 1286 } 1287 1288 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) { 1289 if (getStrategy((AudioSystem::stream_type)i) == strategy) { 1290 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, mHardwareOutput); 1291 int refCount = a2dpOutputDesc->mRefCount[i]; 1292 // in the case of duplicated output, the ref count is first incremented 1293 // and then decremented on hardware output tus keeping its value 1294 hwOutputDesc->changeRefCount((AudioSystem::stream_type)i, refCount); 1295 a2dpOutputDesc->changeRefCount((AudioSystem::stream_type)i,-refCount); 1296 } 1297 } 1298 // do not change newDevice if it was already set before this call by a previous call to 1299 // getNewDevice() or checkOutputForStrategy() for a strategy with higher priority 1300 if (newDevice == 0 && hwOutputDesc->isUsedByStrategy(strategy)) { 1301 newDevice = getDeviceForStrategy(strategy, false); 1302 } 1303 } 1304 if (a2dpIsUsed && !a2dpWasUsed) { 1305 bool dupUsed = a2dpUsedForSonification() && a2dpIsUsed && (AudioSystem::popCount(curDevice) == 2); 1306 audio_io_handle_t a2dpOutput; 1307 1308 if (dupUsed) { 1309 LOGV("checkOutputForStrategy() moving strategy %d from duplicated", strategy); 1310 a2dpOutputDesc = mOutputs.valueFor(mDuplicatedOutput); 1311 a2dpOutput = mDuplicatedOutput; 1312 } else { 1313 LOGV("checkOutputForStrategy() moving strategy %d from a2dp", strategy); 1314 a2dpOutputDesc = mOutputs.valueFor(mA2dpOutput); 1315 a2dpOutput = mA2dpOutput; 1316 } 1317 1318 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) { 1319 if (getStrategy((AudioSystem::stream_type)i) == strategy) { 1320 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, a2dpOutput); 1321 int refCount = hwOutputDesc->mRefCount[i]; 1322 // in the case of duplicated output, the ref count is first incremented 1323 // and then decremented on hardware output tus keeping its value 1324 a2dpOutputDesc->changeRefCount((AudioSystem::stream_type)i, refCount); 1325 hwOutputDesc->changeRefCount((AudioSystem::stream_type)i,-refCount); 1326 } 1327 } 1328 } 1329 } 1330 1331 void AudioPolicyManagerBase::checkOutputForAllStrategies(uint32_t &newDevice) 1332 { 1333 // Check strategies in order of priority so that once newDevice is set 1334 // for a given strategy it is not modified by subsequent calls to 1335 // checkOutputForStrategy() 1336 checkOutputForStrategy(STRATEGY_PHONE, newDevice); 1337 checkOutputForStrategy(STRATEGY_SONIFICATION, newDevice); 1338 checkOutputForStrategy(STRATEGY_MEDIA, newDevice); 1339 checkOutputForStrategy(STRATEGY_DTMF, newDevice); 1340 } 1341 1342 #endif 1343 1344 uint32_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache) 1345 { 1346 uint32_t device = 0; 1347 1348 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 1349 // check the following by order of priority to request a routing change if necessary: 1350 // 1: we are in call or the strategy phone is active on the hardware output: 1351 // use device for strategy phone 1352 // 2: the strategy sonification is active on the hardware output: 1353 // use device for strategy sonification 1354 // 3: the strategy media is active on the hardware output: 1355 // use device for strategy media 1356 // 4: the strategy DTMF is active on the hardware output: 1357 // use device for strategy DTMF 1358 if (mPhoneState == AudioSystem::MODE_IN_CALL || 1359 outputDesc->isUsedByStrategy(STRATEGY_PHONE)) { 1360 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache); 1361 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) { 1362 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache); 1363 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) { 1364 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache); 1365 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) { 1366 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache); 1367 } 1368 1369 LOGV("getNewDevice() selected device %x", device); 1370 return device; 1371 } 1372 1373 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(AudioSystem::stream_type stream) 1374 { 1375 // stream to strategy mapping 1376 switch (stream) { 1377 case AudioSystem::VOICE_CALL: 1378 case AudioSystem::BLUETOOTH_SCO: 1379 return STRATEGY_PHONE; 1380 case AudioSystem::RING: 1381 case AudioSystem::NOTIFICATION: 1382 case AudioSystem::ALARM: 1383 case AudioSystem::ENFORCED_AUDIBLE: 1384 return STRATEGY_SONIFICATION; 1385 case AudioSystem::DTMF: 1386 return STRATEGY_DTMF; 1387 default: 1388 LOGE("unknown stream type"); 1389 case AudioSystem::SYSTEM: 1390 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs 1391 // while key clicks are played produces a poor result 1392 case AudioSystem::TTS: 1393 case AudioSystem::MUSIC: 1394 return STRATEGY_MEDIA; 1395 } 1396 } 1397 1398 uint32_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy, bool fromCache) 1399 { 1400 uint32_t device = 0; 1401 1402 if (fromCache) { 1403 LOGV("getDeviceForStrategy() from cache strategy %d, device %x", strategy, mDeviceForStrategy[strategy]); 1404 return mDeviceForStrategy[strategy]; 1405 } 1406 1407 switch (strategy) { 1408 case STRATEGY_DTMF: 1409 if (mPhoneState != AudioSystem::MODE_IN_CALL) { 1410 // when off call, DTMF strategy follows the same rules as MEDIA strategy 1411 device = getDeviceForStrategy(STRATEGY_MEDIA, false); 1412 break; 1413 } 1414 // when in call, DTMF and PHONE strategies follow the same rules 1415 // FALL THROUGH 1416 1417 case STRATEGY_PHONE: 1418 // for phone strategy, we first consider the forced use and then the available devices by order 1419 // of priority 1420 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) { 1421 case AudioSystem::FORCE_BT_SCO: 1422 if (mPhoneState != AudioSystem::MODE_IN_CALL || strategy != STRATEGY_DTMF) { 1423 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT; 1424 if (device) break; 1425 } 1426 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET; 1427 if (device) break; 1428 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO; 1429 if (device) break; 1430 // if SCO device is requested but no SCO device is available, fall back to default case 1431 // FALL THROUGH 1432 1433 default: // FORCE_NONE 1434 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE; 1435 if (device) break; 1436 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET; 1437 if (device) break; 1438 #ifdef WITH_A2DP 1439 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP 1440 if (mPhoneState != AudioSystem::MODE_IN_CALL) { 1441 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP; 1442 if (device) break; 1443 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES; 1444 if (device) break; 1445 } 1446 #endif 1447 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE; 1448 if (device == 0) { 1449 LOGE("getDeviceForStrategy() earpiece device not found"); 1450 } 1451 break; 1452 1453 case AudioSystem::FORCE_SPEAKER: 1454 if (mPhoneState != AudioSystem::MODE_IN_CALL || strategy != STRATEGY_DTMF) { 1455 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT; 1456 if (device) break; 1457 } 1458 #ifdef WITH_A2DP 1459 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to 1460 // A2DP speaker when forcing to speaker output 1461 if (mPhoneState != AudioSystem::MODE_IN_CALL) { 1462 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER; 1463 if (device) break; 1464 } 1465 #endif 1466 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER; 1467 if (device == 0) { 1468 LOGE("getDeviceForStrategy() speaker device not found"); 1469 } 1470 break; 1471 } 1472 break; 1473 1474 case STRATEGY_SONIFICATION: 1475 1476 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by 1477 // handleIncallSonification(). 1478 if (mPhoneState == AudioSystem::MODE_IN_CALL) { 1479 device = getDeviceForStrategy(STRATEGY_PHONE, false); 1480 break; 1481 } 1482 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER; 1483 if (device == 0) { 1484 LOGE("getDeviceForStrategy() speaker device not found"); 1485 } 1486 // The second device used for sonification is the same as the device used by media strategy 1487 // FALL THROUGH 1488 1489 case STRATEGY_MEDIA: { 1490 uint32_t device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL; 1491 if (device2 == 0) { 1492 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE; 1493 } 1494 if (device2 == 0) { 1495 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET; 1496 } 1497 #ifdef WITH_A2DP 1498 if (mA2dpOutput != 0) { 1499 if (strategy == STRATEGY_SONIFICATION && !a2dpUsedForSonification()) { 1500 break; 1501 } 1502 if (device2 == 0) { 1503 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP; 1504 } 1505 if (device2 == 0) { 1506 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES; 1507 } 1508 if (device2 == 0) { 1509 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER; 1510 } 1511 } 1512 #endif 1513 if (device2 == 0) { 1514 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER; 1515 } 1516 1517 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION, 0 otherwise 1518 device |= device2; 1519 if (device == 0) { 1520 LOGE("getDeviceForStrategy() speaker device not found"); 1521 } 1522 } break; 1523 1524 default: 1525 LOGW("getDeviceForStrategy() unknown strategy: %d", strategy); 1526 break; 1527 } 1528 1529 LOGV("getDeviceForStrategy() strategy %d, device %x", strategy, device); 1530 return device; 1531 } 1532 1533 void AudioPolicyManagerBase::updateDeviceForStrategy() 1534 { 1535 for (int i = 0; i < NUM_STRATEGIES; i++) { 1536 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false); 1537 } 1538 } 1539 1540 void AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output, uint32_t device, bool force, int delayMs) 1541 { 1542 LOGV("setOutputDevice() output %d device %x delayMs %d", output, device, delayMs); 1543 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 1544 1545 1546 if (outputDesc->isDuplicated()) { 1547 setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs); 1548 setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs); 1549 return; 1550 } 1551 #ifdef WITH_A2DP 1552 // filter devices according to output selected 1553 if (output == mA2dpOutput) { 1554 device &= AudioSystem::DEVICE_OUT_ALL_A2DP; 1555 } else { 1556 device &= ~AudioSystem::DEVICE_OUT_ALL_A2DP; 1557 } 1558 #endif 1559 1560 uint32_t prevDevice = (uint32_t)outputDesc->device(); 1561 // Do not change the routing if: 1562 // - the requestede device is 0 1563 // - the requested device is the same as current device and force is not specified. 1564 // Doing this check here allows the caller to call setOutputDevice() without conditions 1565 if ((device == 0 || device == prevDevice) && !force) { 1566 LOGV("setOutputDevice() setting same device %x or null device for output %d", device, output); 1567 return; 1568 } 1569 1570 outputDesc->mDevice = device; 1571 // mute media streams if both speaker and headset are selected 1572 if (output == mHardwareOutput && AudioSystem::popCount(device) == 2) { 1573 setStrategyMute(STRATEGY_MEDIA, true, output); 1574 // wait for the PCM output buffers to empty before proceeding with the rest of the command 1575 usleep(outputDesc->mLatency*2*1000); 1576 } 1577 #ifdef WITH_A2DP 1578 // suspend A2DP output if SCO device is selected 1579 if (AudioSystem::isBluetoothScoDevice((AudioSystem::audio_devices)device)) { 1580 if (mA2dpOutput != 0) { 1581 mpClientInterface->suspendOutput(mA2dpOutput); 1582 } 1583 } 1584 #endif 1585 // do the routing 1586 AudioParameter param = AudioParameter(); 1587 param.addInt(String8(AudioParameter::keyRouting), (int)device); 1588 mpClientInterface->setParameters(mHardwareOutput, param.toString(), delayMs); 1589 // update stream volumes according to new device 1590 applyStreamVolumes(output, device, delayMs); 1591 1592 #ifdef WITH_A2DP 1593 // if disconnecting SCO device, restore A2DP output 1594 if (AudioSystem::isBluetoothScoDevice((AudioSystem::audio_devices)prevDevice)) { 1595 if (mA2dpOutput != 0) { 1596 LOGV("restore A2DP output"); 1597 mpClientInterface->restoreOutput(mA2dpOutput); 1598 } 1599 } 1600 #endif 1601 // if changing from a combined headset + speaker route, unmute media streams 1602 if (output == mHardwareOutput && AudioSystem::popCount(prevDevice) == 2) { 1603 setStrategyMute(STRATEGY_MEDIA, false, output, delayMs); 1604 } 1605 } 1606 1607 uint32_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource) 1608 { 1609 uint32_t device; 1610 1611 switch(inputSource) { 1612 case AUDIO_SOURCE_DEFAULT: 1613 case AUDIO_SOURCE_MIC: 1614 case AUDIO_SOURCE_VOICE_RECOGNITION: 1615 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO && 1616 mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) { 1617 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET; 1618 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) { 1619 device = AudioSystem::DEVICE_IN_WIRED_HEADSET; 1620 } else { 1621 device = AudioSystem::DEVICE_IN_BUILTIN_MIC; 1622 } 1623 break; 1624 case AUDIO_SOURCE_CAMCORDER: 1625 if (hasBackMicrophone()) { 1626 device = AudioSystem::DEVICE_IN_BACK_MIC; 1627 } else { 1628 device = AudioSystem::DEVICE_IN_BUILTIN_MIC; 1629 } 1630 break; 1631 case AUDIO_SOURCE_VOICE_UPLINK: 1632 case AUDIO_SOURCE_VOICE_DOWNLINK: 1633 case AUDIO_SOURCE_VOICE_CALL: 1634 device = AudioSystem::DEVICE_IN_VOICE_CALL; 1635 break; 1636 default: 1637 LOGW("getInput() invalid input source %d", inputSource); 1638 device = 0; 1639 break; 1640 } 1641 LOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device); 1642 return device; 1643 } 1644 1645 audio_io_handle_t AudioPolicyManagerBase::getActiveInput() 1646 { 1647 for (size_t i = 0; i < mInputs.size(); i++) { 1648 if (mInputs.valueAt(i)->mRefCount > 0) { 1649 return mInputs.keyAt(i); 1650 } 1651 } 1652 return 0; 1653 } 1654 1655 float AudioPolicyManagerBase::computeVolume(int stream, int index, audio_io_handle_t output, uint32_t device) 1656 { 1657 float volume = 1.0; 1658 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 1659 StreamDescriptor &streamDesc = mStreams[stream]; 1660 1661 if (device == 0) { 1662 device = outputDesc->device(); 1663 } 1664 1665 int volInt = (100 * (index - streamDesc.mIndexMin)) / (streamDesc.mIndexMax - streamDesc.mIndexMin); 1666 volume = AudioSystem::linearToLog(volInt); 1667 1668 // if a headset is connected, apply the following rules to ring tones and notifications 1669 // to avoid sound level bursts in user's ears: 1670 // - always attenuate ring tones and notifications volume by 6dB 1671 // - if music is playing, always limit the volume to current music volume, 1672 // with a minimum threshold at -36dB so that notification is always perceived. 1673 if ((device & 1674 (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP | 1675 AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES | 1676 AudioSystem::DEVICE_OUT_WIRED_HEADSET | 1677 AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) && 1678 (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) && 1679 streamDesc.mCanBeMuted) { 1680 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR; 1681 // when the phone is ringing we must consider that music could have been paused just before 1682 // by the music application and behave as if music was active if the last music track was 1683 // just stopped 1684 if (outputDesc->mRefCount[AudioSystem::MUSIC] || mLimitRingtoneVolume) { 1685 float musicVol = computeVolume(AudioSystem::MUSIC, mStreams[AudioSystem::MUSIC].mIndexCur, output, device); 1686 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? musicVol : SONIFICATION_HEADSET_VOLUME_MIN; 1687 if (volume > minVol) { 1688 volume = minVol; 1689 LOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol); 1690 } 1691 } 1692 } 1693 1694 return volume; 1695 } 1696 1697 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream, int index, audio_io_handle_t output, uint32_t device, int delayMs, bool force) 1698 { 1699 1700 // do not change actual stream volume if the stream is muted 1701 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) { 1702 LOGV("checkAndSetVolume() stream %d muted count %d", stream, mOutputs.valueFor(output)->mMuteCount[stream]); 1703 return NO_ERROR; 1704 } 1705 1706 // do not change in call volume if bluetooth is connected and vice versa 1707 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) || 1708 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) { 1709 LOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm", 1710 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]); 1711 return INVALID_OPERATION; 1712 } 1713 1714 float volume = computeVolume(stream, index, output, device); 1715 // do not set volume if the float value did not change 1716 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] || force) { 1717 mOutputs.valueFor(output)->mCurVolume[stream] = volume; 1718 LOGV("setStreamVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs); 1719 if (stream == AudioSystem::VOICE_CALL || 1720 stream == AudioSystem::DTMF || 1721 stream == AudioSystem::BLUETOOTH_SCO) { 1722 float voiceVolume = -1.0; 1723 // offset value to reflect actual hardware volume that never reaches 0 1724 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java) 1725 volume = 0.01 + 0.99 * volume; 1726 if (stream == AudioSystem::VOICE_CALL) { 1727 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax; 1728 } else if (stream == AudioSystem::BLUETOOTH_SCO) { 1729 voiceVolume = 1.0; 1730 } 1731 if (voiceVolume >= 0 && output == mHardwareOutput) { 1732 mpClientInterface->setVoiceVolume(voiceVolume, delayMs); 1733 } 1734 } 1735 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs); 1736 } 1737 1738 return NO_ERROR; 1739 } 1740 1741 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output, uint32_t device, int delayMs) 1742 { 1743 LOGV("applyStreamVolumes() for output %d and device %x", output, device); 1744 1745 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) { 1746 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, device, delayMs); 1747 } 1748 } 1749 1750 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs) 1751 { 1752 LOGV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output); 1753 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) { 1754 if (getStrategy((AudioSystem::stream_type)stream) == strategy) { 1755 setStreamMute(stream, on, output, delayMs); 1756 } 1757 } 1758 } 1759 1760 void AudioPolicyManagerBase::setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs) 1761 { 1762 StreamDescriptor &streamDesc = mStreams[stream]; 1763 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output); 1764 1765 LOGV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d", stream, on, output, outputDesc->mMuteCount[stream]); 1766 1767 if (on) { 1768 if (outputDesc->mMuteCount[stream] == 0) { 1769 if (streamDesc.mCanBeMuted) { 1770 checkAndSetVolume(stream, 0, output, outputDesc->device(), delayMs); 1771 } 1772 } 1773 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored 1774 outputDesc->mMuteCount[stream]++; 1775 } else { 1776 if (outputDesc->mMuteCount[stream] == 0) { 1777 LOGW("setStreamMute() unmuting non muted stream!"); 1778 return; 1779 } 1780 if (--outputDesc->mMuteCount[stream] == 0) { 1781 checkAndSetVolume(stream, streamDesc.mIndexCur, output, outputDesc->device(), delayMs); 1782 } 1783 } 1784 } 1785 1786 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange) 1787 { 1788 // if the stream pertains to sonification strategy and we are in call we must 1789 // mute the stream if it is low visibility. If it is high visibility, we must play a tone 1790 // in the device used for phone strategy and play the tone if the selected device does not 1791 // interfere with the device used for phone strategy 1792 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as 1793 // many times as there are active tracks on the output 1794 1795 if (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) { 1796 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mHardwareOutput); 1797 LOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d", 1798 stream, starting, outputDesc->mDevice, stateChange); 1799 if (outputDesc->mRefCount[stream]) { 1800 int muteCount = 1; 1801 if (stateChange) { 1802 muteCount = outputDesc->mRefCount[stream]; 1803 } 1804 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) { 1805 LOGV("handleIncallSonification() low visibility, muteCount %d", muteCount); 1806 for (int i = 0; i < muteCount; i++) { 1807 setStreamMute(stream, starting, mHardwareOutput); 1808 } 1809 } else { 1810 LOGV("handleIncallSonification() high visibility"); 1811 if (outputDesc->device() & getDeviceForStrategy(STRATEGY_PHONE)) { 1812 LOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount); 1813 for (int i = 0; i < muteCount; i++) { 1814 setStreamMute(stream, starting, mHardwareOutput); 1815 } 1816 } 1817 if (starting) { 1818 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL); 1819 } else { 1820 mpClientInterface->stopTone(); 1821 } 1822 } 1823 } 1824 } 1825 } 1826 1827 bool AudioPolicyManagerBase::needsDirectOuput(AudioSystem::stream_type stream, 1828 uint32_t samplingRate, 1829 uint32_t format, 1830 uint32_t channels, 1831 AudioSystem::output_flags flags, 1832 uint32_t device) 1833 { 1834 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) || 1835 (format !=0 && !AudioSystem::isLinearPCM(format))); 1836 } 1837 1838 // --- AudioOutputDescriptor class implementation 1839 1840 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor() 1841 : mId(0), mSamplingRate(0), mFormat(0), mChannels(0), mLatency(0), 1842 mFlags((AudioSystem::output_flags)0), mDevice(0), mOutput1(0), mOutput2(0) 1843 { 1844 // clear usage count for all stream types 1845 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) { 1846 mRefCount[i] = 0; 1847 mCurVolume[i] = -1.0; 1848 mMuteCount[i] = 0; 1849 } 1850 } 1851 1852 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::device() 1853 { 1854 uint32_t device = 0; 1855 if (isDuplicated()) { 1856 device = mOutput1->mDevice | mOutput2->mDevice; 1857 } else { 1858 device = mDevice; 1859 } 1860 return device; 1861 } 1862 1863 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta) 1864 { 1865 // forward usage count change to attached outputs 1866 if (isDuplicated()) { 1867 mOutput1->changeRefCount(stream, delta); 1868 mOutput2->changeRefCount(stream, delta); 1869 } 1870 if ((delta + (int)mRefCount[stream]) < 0) { 1871 LOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]); 1872 mRefCount[stream] = 0; 1873 return; 1874 } 1875 mRefCount[stream] += delta; 1876 LOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]); 1877 } 1878 1879 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount() 1880 { 1881 uint32_t refcount = 0; 1882 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) { 1883 refcount += mRefCount[i]; 1884 } 1885 return refcount; 1886 } 1887 1888 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy) 1889 { 1890 uint32_t refCount = 0; 1891 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) { 1892 if (getStrategy((AudioSystem::stream_type)i) == strategy) { 1893 refCount += mRefCount[i]; 1894 } 1895 } 1896 return refCount; 1897 } 1898 1899 1900 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd) 1901 { 1902 const size_t SIZE = 256; 1903 char buffer[SIZE]; 1904 String8 result; 1905 1906 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate); 1907 result.append(buffer); 1908 snprintf(buffer, SIZE, " Format: %d\n", mFormat); 1909 result.append(buffer); 1910 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels); 1911 result.append(buffer); 1912 snprintf(buffer, SIZE, " Latency: %d\n", mLatency); 1913 result.append(buffer); 1914 snprintf(buffer, SIZE, " Flags %08x\n", mFlags); 1915 result.append(buffer); 1916 snprintf(buffer, SIZE, " Devices %08x\n", device()); 1917 result.append(buffer); 1918 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n"); 1919 result.append(buffer); 1920 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) { 1921 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]); 1922 result.append(buffer); 1923 } 1924 write(fd, result.string(), result.size()); 1925 1926 return NO_ERROR; 1927 } 1928 1929 // --- AudioInputDescriptor class implementation 1930 1931 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor() 1932 : mSamplingRate(0), mFormat(0), mChannels(0), 1933 mAcoustics((AudioSystem::audio_in_acoustics)0), mDevice(0), mRefCount(0) 1934 { 1935 } 1936 1937 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd) 1938 { 1939 const size_t SIZE = 256; 1940 char buffer[SIZE]; 1941 String8 result; 1942 1943 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate); 1944 result.append(buffer); 1945 snprintf(buffer, SIZE, " Format: %d\n", mFormat); 1946 result.append(buffer); 1947 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels); 1948 result.append(buffer); 1949 snprintf(buffer, SIZE, " Acoustics %08x\n", mAcoustics); 1950 result.append(buffer); 1951 snprintf(buffer, SIZE, " Devices %08x\n", mDevice); 1952 result.append(buffer); 1953 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount); 1954 result.append(buffer); 1955 write(fd, result.string(), result.size()); 1956 1957 return NO_ERROR; 1958 } 1959 1960 // --- StreamDescriptor class implementation 1961 1962 void AudioPolicyManagerBase::StreamDescriptor::dump(char* buffer, size_t size) 1963 { 1964 snprintf(buffer, size, " %02d %02d %02d %d\n", 1965 mIndexMin, 1966 mIndexMax, 1967 mIndexCur, 1968 mCanBeMuted); 1969 } 1970 1971 1972 }; // namespace android 1973