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