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