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