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