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