AudioPolicyManager.cpp revision 7b24ee381e806dcb53308c1cafc8a45f4e2d8300
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 <media/AudioParameter.h> 42#include "AudioPolicyManager.h" 43#include "audio_policy_conf.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_HDMI), 74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET), 75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET), 76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY), 77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE), 78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB), 79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX), 80 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX), 81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE), 82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC), 83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF), 84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM), 85 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC), 86 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET), 87 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO), 88 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET), 89 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL), 90 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI), 91 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL), 92 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX), 93 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC), 94 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX), 95 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET), 96 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET), 97 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY), 98 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE), 99 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER), 100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER), 101 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE), 102 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF), 103 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP), 104 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK), 105}; 106 107const StringToEnum sFlagNameToEnumTable[] = { 108 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT), 109 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY), 110 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST), 111 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER), 112 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD), 113 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING), 114}; 115 116const StringToEnum sFormatNameToEnumTable[] = { 117 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT), 118 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT), 119 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT), 120 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT), 121 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT), 122 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED), 123 STRING_TO_ENUM(AUDIO_FORMAT_MP3), 124 STRING_TO_ENUM(AUDIO_FORMAT_AAC), 125 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN), 126 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC), 127 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR), 128 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP), 129 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1), 130 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE), 131 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC), 132 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD), 133 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2), 134 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD), 135 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS), 136 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1), 137 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2), 138 STRING_TO_ENUM(AUDIO_FORMAT_OPUS), 139 STRING_TO_ENUM(AUDIO_FORMAT_AC3), 140 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3), 141}; 142 143const StringToEnum sOutChannelsNameToEnumTable[] = { 144 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO), 145 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO), 146 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1), 147 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1), 148}; 149 150const StringToEnum sInChannelsNameToEnumTable[] = { 151 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO), 152 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO), 153 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK), 154}; 155 156const StringToEnum sGainModeNameToEnumTable[] = { 157 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT), 158 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS), 159 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP), 160}; 161 162 163uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table, 164 size_t size, 165 const char *name) 166{ 167 for (size_t i = 0; i < size; i++) { 168 if (strcmp(table[i].name, name) == 0) { 169 ALOGV("stringToEnum() found %s", table[i].name); 170 return table[i].value; 171 } 172 } 173 return 0; 174} 175 176const char *AudioPolicyManager::enumToString(const struct StringToEnum *table, 177 size_t size, 178 uint32_t value) 179{ 180 for (size_t i = 0; i < size; i++) { 181 if (table[i].value == value) { 182 return table[i].name; 183 } 184 } 185 return ""; 186} 187 188bool AudioPolicyManager::stringToBool(const char *value) 189{ 190 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0)); 191} 192 193 194// ---------------------------------------------------------------------------- 195// AudioPolicyInterface implementation 196// ---------------------------------------------------------------------------- 197 198 199status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device, 200 audio_policy_dev_state_t state, 201 const char *device_address) 202{ 203 String8 address = String8(device_address); 204 205 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address); 206 207 // connect/disconnect only 1 device at a time 208 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE; 209 210 // handle output devices 211 if (audio_is_output_device(device)) { 212 SortedVector <audio_io_handle_t> outputs; 213 214 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device); 215 devDesc->mAddress = address; 216 ssize_t index = mAvailableOutputDevices.indexOf(devDesc); 217 218 // save a copy of the opened output descriptors before any output is opened or closed 219 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies() 220 mPreviousOutputs = mOutputs; 221 switch (state) 222 { 223 // handle output device connection 224 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: 225 if (index >= 0) { 226 ALOGW("setDeviceConnectionState() device already connected: %x", device); 227 return INVALID_OPERATION; 228 } 229 ALOGV("setDeviceConnectionState() connecting device %x", device); 230 231 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) { 232 return INVALID_OPERATION; 233 } 234 // outputs should never be empty here 235 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():" 236 "checkOutputsForDevice() returned no outputs but status OK"); 237 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs", 238 outputs.size()); 239 // register new device as available 240 index = mAvailableOutputDevices.add(devDesc); 241 if (index >= 0) { 242 mAvailableOutputDevices[index]->mId = nextUniqueId(); 243 sp<HwModule> module = getModuleForDevice(device); 244 ALOG_ASSERT(module != NULL, "setDeviceConnectionState():" 245 "could not find HW module for device %08x", device); 246 mAvailableOutputDevices[index]->mModule = module; 247 } else { 248 return NO_MEMORY; 249 } 250 251 break; 252 // handle output device disconnection 253 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: { 254 if (index < 0) { 255 ALOGW("setDeviceConnectionState() device not connected: %x", device); 256 return INVALID_OPERATION; 257 } 258 259 ALOGV("setDeviceConnectionState() disconnecting device %x", device); 260 // remove device from available output devices 261 mAvailableOutputDevices.remove(devDesc); 262 263 checkOutputsForDevice(device, state, outputs, address); 264 // not currently handling multiple simultaneous submixes: ignoring remote submix 265 // case and address 266 } break; 267 268 default: 269 ALOGE("setDeviceConnectionState() invalid state: %x", state); 270 return BAD_VALUE; 271 } 272 273 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP 274 // output is suspended before any tracks are moved to it 275 checkA2dpSuspend(); 276 checkOutputForAllStrategies(); 277 // outputs must be closed after checkOutputForAllStrategies() is executed 278 if (!outputs.isEmpty()) { 279 for (size_t i = 0; i < outputs.size(); i++) { 280 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]); 281 // close unused outputs after device disconnection or direct outputs that have been 282 // opened by checkOutputsForDevice() to query dynamic parameters 283 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) || 284 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) && 285 (desc->mDirectOpenCount == 0))) { 286 closeOutput(outputs[i]); 287 } 288 } 289 // check again after closing A2DP output to reset mA2dpSuspended if needed 290 checkA2dpSuspend(); 291 } 292 293 updateDevicesAndOutputs(); 294 for (size_t i = 0; i < mOutputs.size(); i++) { 295 // do not force device change on duplicated output because if device is 0, it will 296 // also force a device 0 for the two outputs it is duplicated to which may override 297 // a valid device selection on those outputs. 298 setOutputDevice(mOutputs.keyAt(i), 299 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/), 300 !mOutputs.valueAt(i)->isDuplicated(), 301 0); 302 } 303 304 mpClientInterface->onAudioPortListUpdate(); 305 return NO_ERROR; 306 } // end if is output device 307 308 // handle input devices 309 if (audio_is_input_device(device)) { 310 SortedVector <audio_io_handle_t> inputs; 311 312 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device); 313 devDesc->mAddress = address; 314 ssize_t index = mAvailableInputDevices.indexOf(devDesc); 315 switch (state) 316 { 317 // handle input device connection 318 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: { 319 if (index >= 0) { 320 ALOGW("setDeviceConnectionState() device already connected: %d", device); 321 return INVALID_OPERATION; 322 } 323 sp<HwModule> module = getModuleForDevice(device); 324 if (module == NULL) { 325 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x", 326 device); 327 return INVALID_OPERATION; 328 } 329 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) { 330 return INVALID_OPERATION; 331 } 332 333 index = mAvailableInputDevices.add(devDesc); 334 if (index >= 0) { 335 mAvailableInputDevices[index]->mId = nextUniqueId(); 336 mAvailableInputDevices[index]->mModule = module; 337 } else { 338 return NO_MEMORY; 339 } 340 } break; 341 342 // handle input device disconnection 343 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: { 344 if (index < 0) { 345 ALOGW("setDeviceConnectionState() device not connected: %d", device); 346 return INVALID_OPERATION; 347 } 348 checkInputsForDevice(device, state, inputs, address); 349 mAvailableInputDevices.remove(devDesc); 350 } break; 351 352 default: 353 ALOGE("setDeviceConnectionState() invalid state: %x", state); 354 return BAD_VALUE; 355 } 356 357 closeAllInputs(); 358 359 mpClientInterface->onAudioPortListUpdate(); 360 return NO_ERROR; 361 } // end if is input device 362 363 ALOGW("setDeviceConnectionState() invalid device: %x", device); 364 return BAD_VALUE; 365} 366 367audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device, 368 const char *device_address) 369{ 370 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE; 371 String8 address = String8(device_address); 372 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device); 373 devDesc->mAddress = String8(device_address); 374 ssize_t index; 375 DeviceVector *deviceVector; 376 377 if (audio_is_output_device(device)) { 378 deviceVector = &mAvailableOutputDevices; 379 } else if (audio_is_input_device(device)) { 380 deviceVector = &mAvailableInputDevices; 381 } else { 382 ALOGW("getDeviceConnectionState() invalid device type %08x", device); 383 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE; 384 } 385 386 index = deviceVector->indexOf(devDesc); 387 if (index >= 0) { 388 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE; 389 } else { 390 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE; 391 } 392} 393 394void AudioPolicyManager::setPhoneState(audio_mode_t state) 395{ 396 ALOGV("setPhoneState() state %d", state); 397 audio_devices_t newDevice = AUDIO_DEVICE_NONE; 398 if (state < 0 || state >= AUDIO_MODE_CNT) { 399 ALOGW("setPhoneState() invalid state %d", state); 400 return; 401 } 402 403 if (state == mPhoneState ) { 404 ALOGW("setPhoneState() setting same state %d", state); 405 return; 406 } 407 408 // if leaving call state, handle special case of active streams 409 // pertaining to sonification strategy see handleIncallSonification() 410 if (isInCall()) { 411 ALOGV("setPhoneState() in call state management: new state is %d", state); 412 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) { 413 handleIncallSonification((audio_stream_type_t)stream, false, true); 414 } 415 } 416 417 // store previous phone state for management of sonification strategy below 418 int oldState = mPhoneState; 419 mPhoneState = state; 420 bool force = false; 421 422 // are we entering or starting a call 423 if (!isStateInCall(oldState) && isStateInCall(state)) { 424 ALOGV(" Entering call in setPhoneState()"); 425 // force routing command to audio hardware when starting a call 426 // even if no device change is needed 427 force = true; 428 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) { 429 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] = 430 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j]; 431 } 432 } else if (isStateInCall(oldState) && !isStateInCall(state)) { 433 ALOGV(" Exiting call in setPhoneState()"); 434 // force routing command to audio hardware when exiting a call 435 // even if no device change is needed 436 force = true; 437 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) { 438 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] = 439 sVolumeProfiles[AUDIO_STREAM_DTMF][j]; 440 } 441 } else if (isStateInCall(state) && (state != oldState)) { 442 ALOGV(" Switching between telephony and VoIP in setPhoneState()"); 443 // force routing command to audio hardware when switching between telephony and VoIP 444 // even if no device change is needed 445 force = true; 446 } 447 448 // check for device and output changes triggered by new phone state 449 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/); 450 checkA2dpSuspend(); 451 checkOutputForAllStrategies(); 452 updateDevicesAndOutputs(); 453 454 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput); 455 456 // force routing command to audio hardware when ending call 457 // even if no device change is needed 458 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) { 459 newDevice = hwOutputDesc->device(); 460 } 461 462 int delayMs = 0; 463 if (isStateInCall(state)) { 464 nsecs_t sysTime = systemTime(); 465 for (size_t i = 0; i < mOutputs.size(); i++) { 466 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 467 // mute media and sonification strategies and delay device switch by the largest 468 // latency of any output where either strategy is active. 469 // This avoid sending the ring tone or music tail into the earpiece or headset. 470 if ((desc->isStrategyActive(STRATEGY_MEDIA, 471 SONIFICATION_HEADSET_MUSIC_DELAY, 472 sysTime) || 473 desc->isStrategyActive(STRATEGY_SONIFICATION, 474 SONIFICATION_HEADSET_MUSIC_DELAY, 475 sysTime)) && 476 (delayMs < (int)desc->mLatency*2)) { 477 delayMs = desc->mLatency*2; 478 } 479 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i)); 480 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS, 481 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/)); 482 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i)); 483 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS, 484 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/)); 485 } 486 } 487 488 // change routing is necessary 489 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs); 490 491 // if entering in call state, handle special case of active streams 492 // pertaining to sonification strategy see handleIncallSonification() 493 if (isStateInCall(state)) { 494 ALOGV("setPhoneState() in call state management: new state is %d", state); 495 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) { 496 handleIncallSonification((audio_stream_type_t)stream, true, true); 497 } 498 } 499 500 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE 501 if (state == AUDIO_MODE_RINGTONE && 502 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) { 503 mLimitRingtoneVolume = true; 504 } else { 505 mLimitRingtoneVolume = false; 506 } 507} 508 509void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage, 510 audio_policy_forced_cfg_t config) 511{ 512 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState); 513 514 bool forceVolumeReeval = false; 515 switch(usage) { 516 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION: 517 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO && 518 config != AUDIO_POLICY_FORCE_NONE) { 519 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config); 520 return; 521 } 522 forceVolumeReeval = true; 523 mForceUse[usage] = config; 524 break; 525 case AUDIO_POLICY_FORCE_FOR_MEDIA: 526 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP && 527 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY && 528 config != AUDIO_POLICY_FORCE_ANALOG_DOCK && 529 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE && 530 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) { 531 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config); 532 return; 533 } 534 mForceUse[usage] = config; 535 break; 536 case AUDIO_POLICY_FORCE_FOR_RECORD: 537 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY && 538 config != AUDIO_POLICY_FORCE_NONE) { 539 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config); 540 return; 541 } 542 mForceUse[usage] = config; 543 break; 544 case AUDIO_POLICY_FORCE_FOR_DOCK: 545 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK && 546 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK && 547 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY && 548 config != AUDIO_POLICY_FORCE_ANALOG_DOCK && 549 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) { 550 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config); 551 } 552 forceVolumeReeval = true; 553 mForceUse[usage] = config; 554 break; 555 case AUDIO_POLICY_FORCE_FOR_SYSTEM: 556 if (config != AUDIO_POLICY_FORCE_NONE && 557 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) { 558 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config); 559 } 560 forceVolumeReeval = true; 561 mForceUse[usage] = config; 562 break; 563 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO: 564 if (config != AUDIO_POLICY_FORCE_NONE && 565 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) { 566 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config); 567 } 568 mForceUse[usage] = config; 569 break; 570 default: 571 ALOGW("setForceUse() invalid usage %d", usage); 572 break; 573 } 574 575 // check for device and output changes triggered by new force usage 576 checkA2dpSuspend(); 577 checkOutputForAllStrategies(); 578 updateDevicesAndOutputs(); 579 for (size_t i = 0; i < mOutputs.size(); i++) { 580 audio_io_handle_t output = mOutputs.keyAt(i); 581 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/); 582 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE)); 583 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) { 584 applyStreamVolumes(output, newDevice, 0, true); 585 } 586 } 587 588 audio_io_handle_t activeInput = getActiveInput(); 589 if (activeInput != 0) { 590 setInputDevice(activeInput, getNewInputDevice(activeInput)); 591 } 592 593} 594 595audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage) 596{ 597 return mForceUse[usage]; 598} 599 600void AudioPolicyManager::setSystemProperty(const char* property, const char* value) 601{ 602 ALOGV("setSystemProperty() property %s, value %s", property, value); 603} 604 605// Find a direct output profile compatible with the parameters passed, even if the input flags do 606// not explicitly request a direct output 607sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput( 608 audio_devices_t device, 609 uint32_t samplingRate, 610 audio_format_t format, 611 audio_channel_mask_t channelMask, 612 audio_output_flags_t flags) 613{ 614 for (size_t i = 0; i < mHwModules.size(); i++) { 615 if (mHwModules[i]->mHandle == 0) { 616 continue; 617 } 618 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) { 619 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j]; 620 bool found = false; 621 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) { 622 if (profile->isCompatibleProfile(device, samplingRate, format, 623 channelMask, 624 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) { 625 found = true; 626 } 627 } else { 628 if (profile->isCompatibleProfile(device, samplingRate, format, 629 channelMask, 630 AUDIO_OUTPUT_FLAG_DIRECT)) { 631 found = true; 632 } 633 } 634 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) { 635 return profile; 636 } 637 } 638 } 639 return 0; 640} 641 642audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream, 643 uint32_t samplingRate, 644 audio_format_t format, 645 audio_channel_mask_t channelMask, 646 audio_output_flags_t flags, 647 const audio_offload_info_t *offloadInfo) 648{ 649 650 routing_strategy strategy = getStrategy(stream); 651 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/); 652 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x", 653 device, stream, samplingRate, format, channelMask, flags); 654 655 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags, 656 offloadInfo); 657} 658 659audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr, 660 uint32_t samplingRate, 661 audio_format_t format, 662 audio_channel_mask_t channelMask, 663 audio_output_flags_t flags, 664 const audio_offload_info_t *offloadInfo) 665{ 666 if (attr == NULL) { 667 ALOGE("getOutputForAttr() called with NULL audio attributes"); 668 return 0; 669 } 670 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s", 671 attr->usage, attr->content_type, attr->tags); 672 673 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go 674 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr); 675 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/); 676 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x", 677 device, samplingRate, format, channelMask, flags); 678 679 audio_stream_type_t stream = streamTypefromAttributesInt(attr); 680 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags, 681 offloadInfo); 682} 683 684audio_io_handle_t AudioPolicyManager::getOutputForDevice( 685 audio_devices_t device, 686 audio_stream_type_t stream, 687 uint32_t samplingRate, 688 audio_format_t format, 689 audio_channel_mask_t channelMask, 690 audio_output_flags_t flags, 691 const audio_offload_info_t *offloadInfo) 692{ 693 audio_io_handle_t output = 0; 694 uint32_t latency = 0; 695 696#ifdef AUDIO_POLICY_TEST 697 if (mCurOutput != 0) { 698 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d", 699 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput); 700 701 if (mTestOutputs[mCurOutput] == 0) { 702 ALOGV("getOutput() opening test output"); 703 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL); 704 outputDesc->mDevice = mTestDevice; 705 outputDesc->mSamplingRate = mTestSamplingRate; 706 outputDesc->mFormat = mTestFormat; 707 outputDesc->mChannelMask = mTestChannels; 708 outputDesc->mLatency = mTestLatencyMs; 709 outputDesc->mFlags = 710 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0); 711 outputDesc->mRefCount[stream] = 0; 712 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice, 713 &outputDesc->mSamplingRate, 714 &outputDesc->mFormat, 715 &outputDesc->mChannelMask, 716 &outputDesc->mLatency, 717 outputDesc->mFlags, 718 offloadInfo); 719 if (mTestOutputs[mCurOutput]) { 720 AudioParameter outputCmd = AudioParameter(); 721 outputCmd.addInt(String8("set_id"),mCurOutput); 722 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString()); 723 addOutput(mTestOutputs[mCurOutput], outputDesc); 724 } 725 } 726 return mTestOutputs[mCurOutput]; 727 } 728#endif //AUDIO_POLICY_TEST 729 730 // open a direct output if required by specified parameters 731 //force direct flag if offload flag is set: offloading implies a direct output stream 732 // and all common behaviors are driven by checking only the direct flag 733 // this should normally be set appropriately in the policy configuration file 734 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) { 735 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT); 736 } 737 738 // Do not allow offloading if one non offloadable effect is enabled. This prevents from 739 // creating an offloaded track and tearing it down immediately after start when audioflinger 740 // detects there is an active non offloadable effect. 741 // FIXME: We should check the audio session here but we do not have it in this context. 742 // This may prevent offloading in rare situations where effects are left active by apps 743 // in the background. 744 sp<IOProfile> profile; 745 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) || 746 !isNonOffloadableEffectEnabled()) { 747 profile = getProfileForDirectOutput(device, 748 samplingRate, 749 format, 750 channelMask, 751 (audio_output_flags_t)flags); 752 } 753 754 if (profile != 0) { 755 sp<AudioOutputDescriptor> outputDesc = NULL; 756 757 for (size_t i = 0; i < mOutputs.size(); i++) { 758 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 759 if (!desc->isDuplicated() && (profile == desc->mProfile)) { 760 outputDesc = desc; 761 // reuse direct output if currently open and configured with same parameters 762 if ((samplingRate == outputDesc->mSamplingRate) && 763 (format == outputDesc->mFormat) && 764 (channelMask == outputDesc->mChannelMask)) { 765 outputDesc->mDirectOpenCount++; 766 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i)); 767 return mOutputs.keyAt(i); 768 } 769 } 770 } 771 // close direct output if currently open and configured with different parameters 772 if (outputDesc != NULL) { 773 closeOutput(outputDesc->mIoHandle); 774 } 775 outputDesc = new AudioOutputDescriptor(profile); 776 outputDesc->mDevice = device; 777 outputDesc->mSamplingRate = samplingRate; 778 outputDesc->mFormat = format; 779 outputDesc->mChannelMask = channelMask; 780 outputDesc->mLatency = 0; 781 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags); 782 outputDesc->mRefCount[stream] = 0; 783 outputDesc->mStopTime[stream] = 0; 784 outputDesc->mDirectOpenCount = 1; 785 output = mpClientInterface->openOutput(profile->mModule->mHandle, 786 &outputDesc->mDevice, 787 &outputDesc->mSamplingRate, 788 &outputDesc->mFormat, 789 &outputDesc->mChannelMask, 790 &outputDesc->mLatency, 791 outputDesc->mFlags, 792 offloadInfo); 793 794 // only accept an output with the requested parameters 795 if (output == 0 || 796 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) || 797 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) || 798 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) { 799 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d," 800 "format %d %d, channelMask %04x %04x", output, samplingRate, 801 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask, 802 outputDesc->mChannelMask); 803 if (output != 0) { 804 mpClientInterface->closeOutput(output); 805 } 806 return 0; 807 } 808 audio_io_handle_t srcOutput = getOutputForEffect(); 809 addOutput(output, outputDesc); 810 audio_io_handle_t dstOutput = getOutputForEffect(); 811 if (dstOutput == output) { 812 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput); 813 } 814 mPreviousOutputs = mOutputs; 815 ALOGV("getOutput() returns new direct output %d", output); 816 mpClientInterface->onAudioPortListUpdate(); 817 return output; 818 } 819 820 // ignoring channel mask due to downmix capability in mixer 821 822 // open a non direct output 823 824 // for non direct outputs, only PCM is supported 825 if (audio_is_linear_pcm(format)) { 826 // get which output is suitable for the specified stream. The actual 827 // routing change will happen when startOutput() will be called 828 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs); 829 830 output = selectOutput(outputs, flags); 831 } 832 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d," 833 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags); 834 835 ALOGV("getOutput() returns output %d", output); 836 837 return output; 838} 839 840audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs, 841 audio_output_flags_t flags) 842{ 843 // select one output among several that provide a path to a particular device or set of 844 // devices (the list was previously build by getOutputsForDevice()). 845 // The priority is as follows: 846 // 1: the output with the highest number of requested policy flags 847 // 2: the primary output 848 // 3: the first output in the list 849 850 if (outputs.size() == 0) { 851 return 0; 852 } 853 if (outputs.size() == 1) { 854 return outputs[0]; 855 } 856 857 int maxCommonFlags = 0; 858 audio_io_handle_t outputFlags = 0; 859 audio_io_handle_t outputPrimary = 0; 860 861 for (size_t i = 0; i < outputs.size(); i++) { 862 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]); 863 if (!outputDesc->isDuplicated()) { 864 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags); 865 if (commonFlags > maxCommonFlags) { 866 outputFlags = outputs[i]; 867 maxCommonFlags = commonFlags; 868 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags); 869 } 870 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) { 871 outputPrimary = outputs[i]; 872 } 873 } 874 } 875 876 if (outputFlags != 0) { 877 return outputFlags; 878 } 879 if (outputPrimary != 0) { 880 return outputPrimary; 881 } 882 883 return outputs[0]; 884} 885 886status_t AudioPolicyManager::startOutput(audio_io_handle_t output, 887 audio_stream_type_t stream, 888 int session) 889{ 890 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session); 891 ssize_t index = mOutputs.indexOfKey(output); 892 if (index < 0) { 893 ALOGW("startOutput() unknown output %d", output); 894 return BAD_VALUE; 895 } 896 897 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index); 898 899 // increment usage count for this stream on the requested output: 900 // NOTE that the usage count is the same for duplicated output and hardware output which is 901 // necessary for a correct control of hardware output routing by startOutput() and stopOutput() 902 outputDesc->changeRefCount(stream, 1); 903 904 if (outputDesc->mRefCount[stream] == 1) { 905 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/); 906 routing_strategy strategy = getStrategy(stream); 907 bool shouldWait = (strategy == STRATEGY_SONIFICATION) || 908 (strategy == STRATEGY_SONIFICATION_RESPECTFUL); 909 uint32_t waitMs = 0; 910 bool force = false; 911 for (size_t i = 0; i < mOutputs.size(); i++) { 912 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 913 if (desc != outputDesc) { 914 // force a device change if any other output is managed by the same hw 915 // module and has a current device selection that differs from selected device. 916 // In this case, the audio HAL must receive the new device selection so that it can 917 // change the device currently selected by the other active output. 918 if (outputDesc->sharesHwModuleWith(desc) && 919 desc->device() != newDevice) { 920 force = true; 921 } 922 // wait for audio on other active outputs to be presented when starting 923 // a notification so that audio focus effect can propagate. 924 uint32_t latency = desc->latency(); 925 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) { 926 waitMs = latency; 927 } 928 } 929 } 930 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force); 931 932 // handle special case for sonification while in call 933 if (isInCall()) { 934 handleIncallSonification(stream, true, false); 935 } 936 937 // apply volume rules for current stream and device if necessary 938 checkAndSetVolume(stream, 939 mStreams[stream].getVolumeIndex(newDevice), 940 output, 941 newDevice); 942 943 // update the outputs if starting an output with a stream that can affect notification 944 // routing 945 handleNotificationRoutingForStream(stream); 946 if (waitMs > muteWaitMs) { 947 usleep((waitMs - muteWaitMs) * 2 * 1000); 948 } 949 } 950 return NO_ERROR; 951} 952 953 954status_t AudioPolicyManager::stopOutput(audio_io_handle_t output, 955 audio_stream_type_t stream, 956 int session) 957{ 958 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session); 959 ssize_t index = mOutputs.indexOfKey(output); 960 if (index < 0) { 961 ALOGW("stopOutput() unknown output %d", output); 962 return BAD_VALUE; 963 } 964 965 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index); 966 967 // handle special case for sonification while in call 968 if (isInCall()) { 969 handleIncallSonification(stream, false, false); 970 } 971 972 if (outputDesc->mRefCount[stream] > 0) { 973 // decrement usage count of this stream on the output 974 outputDesc->changeRefCount(stream, -1); 975 // store time at which the stream was stopped - see isStreamActive() 976 if (outputDesc->mRefCount[stream] == 0) { 977 outputDesc->mStopTime[stream] = systemTime(); 978 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/); 979 // delay the device switch by twice the latency because stopOutput() is executed when 980 // the track stop() command is received and at that time the audio track buffer can 981 // still contain data that needs to be drained. The latency only covers the audio HAL 982 // and kernel buffers. Also the latency does not always include additional delay in the 983 // audio path (audio DSP, CODEC ...) 984 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2); 985 986 // force restoring the device selection on other active outputs if it differs from the 987 // one being selected for this output 988 for (size_t i = 0; i < mOutputs.size(); i++) { 989 audio_io_handle_t curOutput = mOutputs.keyAt(i); 990 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 991 if (curOutput != output && 992 desc->isActive() && 993 outputDesc->sharesHwModuleWith(desc) && 994 (newDevice != desc->device())) { 995 setOutputDevice(curOutput, 996 getNewOutputDevice(curOutput, false /*fromCache*/), 997 true, 998 outputDesc->mLatency*2); 999 } 1000 } 1001 // update the outputs if stopping one with a stream that can affect notification routing 1002 handleNotificationRoutingForStream(stream); 1003 } 1004 return NO_ERROR; 1005 } else { 1006 ALOGW("stopOutput() refcount is already 0 for output %d", output); 1007 return INVALID_OPERATION; 1008 } 1009} 1010 1011void AudioPolicyManager::releaseOutput(audio_io_handle_t output) 1012{ 1013 ALOGV("releaseOutput() %d", output); 1014 ssize_t index = mOutputs.indexOfKey(output); 1015 if (index < 0) { 1016 ALOGW("releaseOutput() releasing unknown output %d", output); 1017 return; 1018 } 1019 1020#ifdef AUDIO_POLICY_TEST 1021 int testIndex = testOutputIndex(output); 1022 if (testIndex != 0) { 1023 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index); 1024 if (outputDesc->isActive()) { 1025 mpClientInterface->closeOutput(output); 1026 mOutputs.removeItem(output); 1027 mTestOutputs[testIndex] = 0; 1028 } 1029 return; 1030 } 1031#endif //AUDIO_POLICY_TEST 1032 1033 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index); 1034 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) { 1035 if (desc->mDirectOpenCount <= 0) { 1036 ALOGW("releaseOutput() invalid open count %d for output %d", 1037 desc->mDirectOpenCount, output); 1038 return; 1039 } 1040 if (--desc->mDirectOpenCount == 0) { 1041 closeOutput(output); 1042 // If effects where present on the output, audioflinger moved them to the primary 1043 // output by default: move them back to the appropriate output. 1044 audio_io_handle_t dstOutput = getOutputForEffect(); 1045 if (dstOutput != mPrimaryOutput) { 1046 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput); 1047 } 1048 mpClientInterface->onAudioPortListUpdate(); 1049 } 1050 } 1051} 1052 1053 1054audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource, 1055 uint32_t samplingRate, 1056 audio_format_t format, 1057 audio_channel_mask_t channelMask, 1058 audio_in_acoustics_t acoustics) 1059{ 1060 audio_io_handle_t input = 0; 1061 audio_devices_t device = getDeviceForInputSource(inputSource); 1062 1063 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x", 1064 inputSource, samplingRate, format, channelMask, acoustics); 1065 1066 if (device == AUDIO_DEVICE_NONE) { 1067 ALOGW("getInput() could not find device for inputSource %d", inputSource); 1068 return 0; 1069 } 1070 1071 // adapt channel selection to input source 1072 switch(inputSource) { 1073 case AUDIO_SOURCE_VOICE_UPLINK: 1074 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK; 1075 break; 1076 case AUDIO_SOURCE_VOICE_DOWNLINK: 1077 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK; 1078 break; 1079 case AUDIO_SOURCE_VOICE_CALL: 1080 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK; 1081 break; 1082 default: 1083 break; 1084 } 1085 1086 sp<IOProfile> profile = getInputProfile(device, 1087 samplingRate, 1088 format, 1089 channelMask); 1090 if (profile == 0) { 1091 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, " 1092 "channelMask %04x", 1093 device, samplingRate, format, channelMask); 1094 return 0; 1095 } 1096 1097 if (profile->mModule->mHandle == 0) { 1098 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName); 1099 return 0; 1100 } 1101 1102 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile); 1103 1104 inputDesc->mInputSource = inputSource; 1105 inputDesc->mDevice = device; 1106 inputDesc->mSamplingRate = samplingRate; 1107 inputDesc->mFormat = format; 1108 inputDesc->mChannelMask = channelMask; 1109 inputDesc->mRefCount = 0; 1110 input = mpClientInterface->openInput(profile->mModule->mHandle, 1111 &inputDesc->mDevice, 1112 &inputDesc->mSamplingRate, 1113 &inputDesc->mFormat, 1114 &inputDesc->mChannelMask); 1115 1116 // only accept input with the exact requested set of parameters 1117 if (input == 0 || 1118 (samplingRate != inputDesc->mSamplingRate) || 1119 (format != inputDesc->mFormat) || 1120 (channelMask != inputDesc->mChannelMask)) { 1121 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x", 1122 samplingRate, format, channelMask); 1123 if (input != 0) { 1124 mpClientInterface->closeInput(input); 1125 } 1126 return 0; 1127 } 1128 addInput(input, inputDesc); 1129 mpClientInterface->onAudioPortListUpdate(); 1130 return input; 1131} 1132 1133status_t AudioPolicyManager::startInput(audio_io_handle_t input) 1134{ 1135 ALOGV("startInput() input %d", input); 1136 ssize_t index = mInputs.indexOfKey(input); 1137 if (index < 0) { 1138 ALOGW("startInput() unknown input %d", input); 1139 return BAD_VALUE; 1140 } 1141 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index); 1142 1143#ifdef AUDIO_POLICY_TEST 1144 if (mTestInput == 0) 1145#endif //AUDIO_POLICY_TEST 1146 { 1147 // refuse 2 active AudioRecord clients at the same time except if the active input 1148 // uses AUDIO_SOURCE_HOTWORD in which case it is closed. 1149 audio_io_handle_t activeInput = getActiveInput(); 1150 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) { 1151 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput); 1152 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) { 1153 ALOGW("startInput() preempting already started low-priority input %d", activeInput); 1154 stopInput(activeInput); 1155 releaseInput(activeInput); 1156 } else { 1157 ALOGW("startInput() input %d failed: other input already started", input); 1158 return INVALID_OPERATION; 1159 } 1160 } 1161 } 1162 1163 setInputDevice(input, getNewInputDevice(input), true /* force */); 1164 1165 // automatically enable the remote submix output when input is started 1166 if (audio_is_remote_submix_device(inputDesc->mDevice)) { 1167 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, 1168 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS); 1169 } 1170 1171 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource); 1172 1173 inputDesc->mRefCount = 1; 1174 return NO_ERROR; 1175} 1176 1177status_t AudioPolicyManager::stopInput(audio_io_handle_t input) 1178{ 1179 ALOGV("stopInput() input %d", input); 1180 ssize_t index = mInputs.indexOfKey(input); 1181 if (index < 0) { 1182 ALOGW("stopInput() unknown input %d", input); 1183 return BAD_VALUE; 1184 } 1185 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index); 1186 1187 if (inputDesc->mRefCount == 0) { 1188 ALOGW("stopInput() input %d already stopped", input); 1189 return INVALID_OPERATION; 1190 } else { 1191 // automatically disable the remote submix output when input is stopped 1192 if (audio_is_remote_submix_device(inputDesc->mDevice)) { 1193 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, 1194 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS); 1195 } 1196 1197 resetInputDevice(input); 1198 inputDesc->mRefCount = 0; 1199 return NO_ERROR; 1200 } 1201} 1202 1203void AudioPolicyManager::releaseInput(audio_io_handle_t input) 1204{ 1205 ALOGV("releaseInput() %d", input); 1206 ssize_t index = mInputs.indexOfKey(input); 1207 if (index < 0) { 1208 ALOGW("releaseInput() releasing unknown input %d", input); 1209 return; 1210 } 1211 mpClientInterface->closeInput(input); 1212 mInputs.removeItem(input); 1213 nextAudioPortGeneration(); 1214 mpClientInterface->onAudioPortListUpdate(); 1215 ALOGV("releaseInput() exit"); 1216} 1217 1218void AudioPolicyManager::closeAllInputs() { 1219 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) { 1220 mpClientInterface->closeInput(mInputs.keyAt(input_index)); 1221 } 1222 mInputs.clear(); 1223 nextAudioPortGeneration(); 1224} 1225 1226void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, 1227 int indexMin, 1228 int indexMax) 1229{ 1230 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax); 1231 if (indexMin < 0 || indexMin >= indexMax) { 1232 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax); 1233 return; 1234 } 1235 mStreams[stream].mIndexMin = indexMin; 1236 mStreams[stream].mIndexMax = indexMax; 1237} 1238 1239status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream, 1240 int index, 1241 audio_devices_t device) 1242{ 1243 1244 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) { 1245 return BAD_VALUE; 1246 } 1247 if (!audio_is_output_device(device)) { 1248 return BAD_VALUE; 1249 } 1250 1251 // Force max volume if stream cannot be muted 1252 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax; 1253 1254 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d", 1255 stream, device, index); 1256 1257 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and 1258 // clear all device specific values 1259 if (device == AUDIO_DEVICE_OUT_DEFAULT) { 1260 mStreams[stream].mIndexCur.clear(); 1261 } 1262 mStreams[stream].mIndexCur.add(device, index); 1263 1264 // compute and apply stream volume on all outputs according to connected device 1265 status_t status = NO_ERROR; 1266 for (size_t i = 0; i < mOutputs.size(); i++) { 1267 audio_devices_t curDevice = 1268 getDeviceForVolume(mOutputs.valueAt(i)->device()); 1269 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) { 1270 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice); 1271 if (volStatus != NO_ERROR) { 1272 status = volStatus; 1273 } 1274 } 1275 } 1276 return status; 1277} 1278 1279status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream, 1280 int *index, 1281 audio_devices_t device) 1282{ 1283 if (index == NULL) { 1284 return BAD_VALUE; 1285 } 1286 if (!audio_is_output_device(device)) { 1287 return BAD_VALUE; 1288 } 1289 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to 1290 // the strategy the stream belongs to. 1291 if (device == AUDIO_DEVICE_OUT_DEFAULT) { 1292 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/); 1293 } 1294 device = getDeviceForVolume(device); 1295 1296 *index = mStreams[stream].getVolumeIndex(device); 1297 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index); 1298 return NO_ERROR; 1299} 1300 1301audio_io_handle_t AudioPolicyManager::selectOutputForEffects( 1302 const SortedVector<audio_io_handle_t>& outputs) 1303{ 1304 // select one output among several suitable for global effects. 1305 // The priority is as follows: 1306 // 1: An offloaded output. If the effect ends up not being offloadable, 1307 // AudioFlinger will invalidate the track and the offloaded output 1308 // will be closed causing the effect to be moved to a PCM output. 1309 // 2: A deep buffer output 1310 // 3: the first output in the list 1311 1312 if (outputs.size() == 0) { 1313 return 0; 1314 } 1315 1316 audio_io_handle_t outputOffloaded = 0; 1317 audio_io_handle_t outputDeepBuffer = 0; 1318 1319 for (size_t i = 0; i < outputs.size(); i++) { 1320 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]); 1321 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags); 1322 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) { 1323 outputOffloaded = outputs[i]; 1324 } 1325 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) { 1326 outputDeepBuffer = outputs[i]; 1327 } 1328 } 1329 1330 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d", 1331 outputOffloaded, outputDeepBuffer); 1332 if (outputOffloaded != 0) { 1333 return outputOffloaded; 1334 } 1335 if (outputDeepBuffer != 0) { 1336 return outputDeepBuffer; 1337 } 1338 1339 return outputs[0]; 1340} 1341 1342audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc) 1343{ 1344 // apply simple rule where global effects are attached to the same output as MUSIC streams 1345 1346 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC); 1347 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/); 1348 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs); 1349 1350 audio_io_handle_t output = selectOutputForEffects(dstOutputs); 1351 ALOGV("getOutputForEffect() got output %d for fx %s flags %x", 1352 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags); 1353 1354 return output; 1355} 1356 1357status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc, 1358 audio_io_handle_t io, 1359 uint32_t strategy, 1360 int session, 1361 int id) 1362{ 1363 ssize_t index = mOutputs.indexOfKey(io); 1364 if (index < 0) { 1365 index = mInputs.indexOfKey(io); 1366 if (index < 0) { 1367 ALOGW("registerEffect() unknown io %d", io); 1368 return INVALID_OPERATION; 1369 } 1370 } 1371 1372 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) { 1373 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB", 1374 desc->name, desc->memoryUsage); 1375 return INVALID_OPERATION; 1376 } 1377 mTotalEffectsMemory += desc->memoryUsage; 1378 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d", 1379 desc->name, io, strategy, session, id); 1380 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory); 1381 1382 sp<EffectDescriptor> effectDesc = new EffectDescriptor(); 1383 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t)); 1384 effectDesc->mIo = io; 1385 effectDesc->mStrategy = (routing_strategy)strategy; 1386 effectDesc->mSession = session; 1387 effectDesc->mEnabled = false; 1388 1389 mEffects.add(id, effectDesc); 1390 1391 return NO_ERROR; 1392} 1393 1394status_t AudioPolicyManager::unregisterEffect(int id) 1395{ 1396 ssize_t index = mEffects.indexOfKey(id); 1397 if (index < 0) { 1398 ALOGW("unregisterEffect() unknown effect ID %d", id); 1399 return INVALID_OPERATION; 1400 } 1401 1402 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index); 1403 1404 setEffectEnabled(effectDesc, false); 1405 1406 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) { 1407 ALOGW("unregisterEffect() memory %d too big for total %d", 1408 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory); 1409 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory; 1410 } 1411 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage; 1412 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d", 1413 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory); 1414 1415 mEffects.removeItem(id); 1416 1417 return NO_ERROR; 1418} 1419 1420status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled) 1421{ 1422 ssize_t index = mEffects.indexOfKey(id); 1423 if (index < 0) { 1424 ALOGW("unregisterEffect() unknown effect ID %d", id); 1425 return INVALID_OPERATION; 1426 } 1427 1428 return setEffectEnabled(mEffects.valueAt(index), enabled); 1429} 1430 1431status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled) 1432{ 1433 if (enabled == effectDesc->mEnabled) { 1434 ALOGV("setEffectEnabled(%s) effect already %s", 1435 enabled?"true":"false", enabled?"enabled":"disabled"); 1436 return INVALID_OPERATION; 1437 } 1438 1439 if (enabled) { 1440 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) { 1441 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS", 1442 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10); 1443 return INVALID_OPERATION; 1444 } 1445 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad; 1446 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad); 1447 } else { 1448 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) { 1449 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d", 1450 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad); 1451 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad; 1452 } 1453 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad; 1454 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad); 1455 } 1456 effectDesc->mEnabled = enabled; 1457 return NO_ERROR; 1458} 1459 1460bool AudioPolicyManager::isNonOffloadableEffectEnabled() 1461{ 1462 for (size_t i = 0; i < mEffects.size(); i++) { 1463 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i); 1464 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) && 1465 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) { 1466 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d", 1467 effectDesc->mDesc.name, effectDesc->mSession); 1468 return true; 1469 } 1470 } 1471 return false; 1472} 1473 1474bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const 1475{ 1476 nsecs_t sysTime = systemTime(); 1477 for (size_t i = 0; i < mOutputs.size(); i++) { 1478 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i); 1479 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) { 1480 return true; 1481 } 1482 } 1483 return false; 1484} 1485 1486bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, 1487 uint32_t inPastMs) const 1488{ 1489 nsecs_t sysTime = systemTime(); 1490 for (size_t i = 0; i < mOutputs.size(); i++) { 1491 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i); 1492 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) && 1493 outputDesc->isStreamActive(stream, inPastMs, sysTime)) { 1494 return true; 1495 } 1496 } 1497 return false; 1498} 1499 1500bool AudioPolicyManager::isSourceActive(audio_source_t source) const 1501{ 1502 for (size_t i = 0; i < mInputs.size(); i++) { 1503 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i); 1504 if ((inputDescriptor->mInputSource == (int)source || 1505 (source == AUDIO_SOURCE_VOICE_RECOGNITION && 1506 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD)) 1507 && (inputDescriptor->mRefCount > 0)) { 1508 return true; 1509 } 1510 } 1511 return false; 1512} 1513 1514 1515status_t AudioPolicyManager::dump(int fd) 1516{ 1517 const size_t SIZE = 256; 1518 char buffer[SIZE]; 1519 String8 result; 1520 1521 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this); 1522 result.append(buffer); 1523 1524 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput); 1525 result.append(buffer); 1526 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState); 1527 result.append(buffer); 1528 snprintf(buffer, SIZE, " Force use for communications %d\n", 1529 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]); 1530 result.append(buffer); 1531 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]); 1532 result.append(buffer); 1533 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]); 1534 result.append(buffer); 1535 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]); 1536 result.append(buffer); 1537 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]); 1538 result.append(buffer); 1539 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n", 1540 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]); 1541 result.append(buffer); 1542 1543 snprintf(buffer, SIZE, " Available output devices:\n"); 1544 result.append(buffer); 1545 write(fd, result.string(), result.size()); 1546 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) { 1547 mAvailableOutputDevices[i]->dump(fd, 2, i); 1548 } 1549 snprintf(buffer, SIZE, "\n Available input devices:\n"); 1550 write(fd, buffer, strlen(buffer)); 1551 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) { 1552 mAvailableInputDevices[i]->dump(fd, 2, i); 1553 } 1554 1555 snprintf(buffer, SIZE, "\nHW Modules dump:\n"); 1556 write(fd, buffer, strlen(buffer)); 1557 for (size_t i = 0; i < mHwModules.size(); i++) { 1558 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1); 1559 write(fd, buffer, strlen(buffer)); 1560 mHwModules[i]->dump(fd); 1561 } 1562 1563 snprintf(buffer, SIZE, "\nOutputs dump:\n"); 1564 write(fd, buffer, strlen(buffer)); 1565 for (size_t i = 0; i < mOutputs.size(); i++) { 1566 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i)); 1567 write(fd, buffer, strlen(buffer)); 1568 mOutputs.valueAt(i)->dump(fd); 1569 } 1570 1571 snprintf(buffer, SIZE, "\nInputs dump:\n"); 1572 write(fd, buffer, strlen(buffer)); 1573 for (size_t i = 0; i < mInputs.size(); i++) { 1574 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i)); 1575 write(fd, buffer, strlen(buffer)); 1576 mInputs.valueAt(i)->dump(fd); 1577 } 1578 1579 snprintf(buffer, SIZE, "\nStreams dump:\n"); 1580 write(fd, buffer, strlen(buffer)); 1581 snprintf(buffer, SIZE, 1582 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n"); 1583 write(fd, buffer, strlen(buffer)); 1584 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) { 1585 snprintf(buffer, SIZE, " %02zu ", i); 1586 write(fd, buffer, strlen(buffer)); 1587 mStreams[i].dump(fd); 1588 } 1589 1590 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n", 1591 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory); 1592 write(fd, buffer, strlen(buffer)); 1593 1594 snprintf(buffer, SIZE, "Registered effects:\n"); 1595 write(fd, buffer, strlen(buffer)); 1596 for (size_t i = 0; i < mEffects.size(); i++) { 1597 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i)); 1598 write(fd, buffer, strlen(buffer)); 1599 mEffects.valueAt(i)->dump(fd); 1600 } 1601 1602 1603 return NO_ERROR; 1604} 1605 1606// This function checks for the parameters which can be offloaded. 1607// This can be enhanced depending on the capability of the DSP and policy 1608// of the system. 1609bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo) 1610{ 1611 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d," 1612 " BitRate=%u, duration=%" PRId64 " us, has_video=%d", 1613 offloadInfo.sample_rate, offloadInfo.channel_mask, 1614 offloadInfo.format, 1615 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us, 1616 offloadInfo.has_video); 1617 1618 // Check if offload has been disabled 1619 char propValue[PROPERTY_VALUE_MAX]; 1620 if (property_get("audio.offload.disable", propValue, "0")) { 1621 if (atoi(propValue) != 0) { 1622 ALOGV("offload disabled by audio.offload.disable=%s", propValue ); 1623 return false; 1624 } 1625 } 1626 1627 // Check if stream type is music, then only allow offload as of now. 1628 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC) 1629 { 1630 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false"); 1631 return false; 1632 } 1633 1634 //TODO: enable audio offloading with video when ready 1635 if (offloadInfo.has_video) 1636 { 1637 ALOGV("isOffloadSupported: has_video == true, returning false"); 1638 return false; 1639 } 1640 1641 //If duration is less than minimum value defined in property, return false 1642 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) { 1643 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) { 1644 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue); 1645 return false; 1646 } 1647 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) { 1648 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS); 1649 return false; 1650 } 1651 1652 // Do not allow offloading if one non offloadable effect is enabled. This prevents from 1653 // creating an offloaded track and tearing it down immediately after start when audioflinger 1654 // detects there is an active non offloadable effect. 1655 // FIXME: We should check the audio session here but we do not have it in this context. 1656 // This may prevent offloading in rare situations where effects are left active by apps 1657 // in the background. 1658 if (isNonOffloadableEffectEnabled()) { 1659 return false; 1660 } 1661 1662 // See if there is a profile to support this. 1663 // AUDIO_DEVICE_NONE 1664 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */, 1665 offloadInfo.sample_rate, 1666 offloadInfo.format, 1667 offloadInfo.channel_mask, 1668 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD); 1669 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT "); 1670 return (profile != 0); 1671} 1672 1673status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role, 1674 audio_port_type_t type, 1675 unsigned int *num_ports, 1676 struct audio_port *ports, 1677 unsigned int *generation) 1678{ 1679 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) || 1680 generation == NULL) { 1681 return BAD_VALUE; 1682 } 1683 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports); 1684 if (ports == NULL) { 1685 *num_ports = 0; 1686 } 1687 1688 size_t portsWritten = 0; 1689 size_t portsMax = *num_ports; 1690 *num_ports = 0; 1691 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) { 1692 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) { 1693 for (size_t i = 0; 1694 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) { 1695 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]); 1696 } 1697 *num_ports += mAvailableOutputDevices.size(); 1698 } 1699 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) { 1700 for (size_t i = 0; 1701 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) { 1702 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]); 1703 } 1704 *num_ports += mAvailableInputDevices.size(); 1705 } 1706 } 1707 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) { 1708 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) { 1709 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) { 1710 mInputs[i]->toAudioPort(&ports[portsWritten++]); 1711 } 1712 *num_ports += mInputs.size(); 1713 } 1714 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) { 1715 size_t numOutputs = 0; 1716 for (size_t i = 0; i < mOutputs.size(); i++) { 1717 if (!mOutputs[i]->isDuplicated()) { 1718 numOutputs++; 1719 if (portsWritten < portsMax) { 1720 mOutputs[i]->toAudioPort(&ports[portsWritten++]); 1721 } 1722 } 1723 } 1724 *num_ports += numOutputs; 1725 } 1726 } 1727 *generation = curAudioPortGeneration(); 1728 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports); 1729 return NO_ERROR; 1730} 1731 1732status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused) 1733{ 1734 return NO_ERROR; 1735} 1736 1737sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId( 1738 audio_port_handle_t id) const 1739{ 1740 sp<AudioOutputDescriptor> outputDesc = NULL; 1741 for (size_t i = 0; i < mOutputs.size(); i++) { 1742 outputDesc = mOutputs.valueAt(i); 1743 if (outputDesc->mId == id) { 1744 break; 1745 } 1746 } 1747 return outputDesc; 1748} 1749 1750sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId( 1751 audio_port_handle_t id) const 1752{ 1753 sp<AudioInputDescriptor> inputDesc = NULL; 1754 for (size_t i = 0; i < mInputs.size(); i++) { 1755 inputDesc = mInputs.valueAt(i); 1756 if (inputDesc->mId == id) { 1757 break; 1758 } 1759 } 1760 return inputDesc; 1761} 1762 1763sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice( 1764 audio_devices_t device) const 1765{ 1766 sp <HwModule> module; 1767 1768 for (size_t i = 0; i < mHwModules.size(); i++) { 1769 if (mHwModules[i]->mHandle == 0) { 1770 continue; 1771 } 1772 if (audio_is_output_device(device)) { 1773 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 1774 { 1775 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) { 1776 return mHwModules[i]; 1777 } 1778 } 1779 } else { 1780 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) { 1781 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() & 1782 device & ~AUDIO_DEVICE_BIT_IN) { 1783 return mHwModules[i]; 1784 } 1785 } 1786 } 1787 } 1788 return module; 1789} 1790 1791sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const 1792{ 1793 sp <HwModule> module; 1794 1795 for (size_t i = 0; i < mHwModules.size(); i++) 1796 { 1797 if (strcmp(mHwModules[i]->mName, name) == 0) { 1798 return mHwModules[i]; 1799 } 1800 } 1801 return module; 1802} 1803 1804 1805status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch, 1806 audio_patch_handle_t *handle, 1807 uid_t uid) 1808{ 1809 ALOGV("createAudioPatch()"); 1810 1811 if (handle == NULL || patch == NULL) { 1812 return BAD_VALUE; 1813 } 1814 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks); 1815 1816 if (patch->num_sources > 1 || patch->num_sinks > 1) { 1817 return INVALID_OPERATION; 1818 } 1819 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE || 1820 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) { 1821 return INVALID_OPERATION; 1822 } 1823 1824 sp<AudioPatch> patchDesc; 1825 ssize_t index = mAudioPatches.indexOfKey(*handle); 1826 1827 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role, 1828 patch->sinks[0].type); 1829 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id, 1830 patch->sources[0].role, 1831 patch->sources[0].type); 1832 1833 if (index >= 0) { 1834 patchDesc = mAudioPatches.valueAt(index); 1835 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d", 1836 mUidCached, patchDesc->mUid, uid); 1837 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) { 1838 return INVALID_OPERATION; 1839 } 1840 } else { 1841 *handle = 0; 1842 } 1843 1844 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) { 1845 // TODO add support for mix to mix connection 1846 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) { 1847 ALOGV("createAudioPatch() source mix sink not device"); 1848 return BAD_VALUE; 1849 } 1850 // output mix to output device connection 1851 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id); 1852 if (outputDesc == NULL) { 1853 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id); 1854 return BAD_VALUE; 1855 } 1856 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports", 1857 outputDesc->mIoHandle); 1858 if (patchDesc != 0) { 1859 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) { 1860 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d", 1861 patchDesc->mPatch.sources[0].id, patch->sources[0].id); 1862 return BAD_VALUE; 1863 } 1864 } 1865 sp<DeviceDescriptor> devDesc = 1866 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id); 1867 if (devDesc == 0) { 1868 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id); 1869 return BAD_VALUE; 1870 } 1871 1872 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType, 1873 patch->sources[0].sample_rate, 1874 patch->sources[0].format, 1875 patch->sources[0].channel_mask, 1876 AUDIO_OUTPUT_FLAG_NONE)) { 1877 return INVALID_OPERATION; 1878 } 1879 // TODO: reconfigure output format and channels here 1880 ALOGV("createAudioPatch() setting device %08x on output %d", 1881 devDesc->mDeviceType, outputDesc->mIoHandle); 1882 setOutputDevice(outputDesc->mIoHandle, 1883 devDesc->mDeviceType, 1884 true, 1885 0, 1886 handle); 1887 index = mAudioPatches.indexOfKey(*handle); 1888 if (index >= 0) { 1889 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) { 1890 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided"); 1891 } 1892 patchDesc = mAudioPatches.valueAt(index); 1893 patchDesc->mUid = uid; 1894 ALOGV("createAudioPatch() success"); 1895 } else { 1896 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch"); 1897 return INVALID_OPERATION; 1898 } 1899 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) { 1900 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) { 1901 // input device to input mix connection 1902 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id); 1903 if (inputDesc == NULL) { 1904 return BAD_VALUE; 1905 } 1906 if (patchDesc != 0) { 1907 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) { 1908 return BAD_VALUE; 1909 } 1910 } 1911 sp<DeviceDescriptor> devDesc = 1912 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id); 1913 if (devDesc == 0) { 1914 return BAD_VALUE; 1915 } 1916 1917 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType, 1918 patch->sinks[0].sample_rate, 1919 patch->sinks[0].format, 1920 patch->sinks[0].channel_mask, 1921 AUDIO_OUTPUT_FLAG_NONE)) { 1922 return INVALID_OPERATION; 1923 } 1924 // TODO: reconfigure output format and channels here 1925 ALOGV("createAudioPatch() setting device %08x on output %d", 1926 devDesc->mDeviceType, inputDesc->mIoHandle); 1927 setInputDevice(inputDesc->mIoHandle, 1928 devDesc->mDeviceType, 1929 true, 1930 handle); 1931 index = mAudioPatches.indexOfKey(*handle); 1932 if (index >= 0) { 1933 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) { 1934 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided"); 1935 } 1936 patchDesc = mAudioPatches.valueAt(index); 1937 patchDesc->mUid = uid; 1938 ALOGV("createAudioPatch() success"); 1939 } else { 1940 ALOGW("createAudioPatch() setInputDevice() failed to create a patch"); 1941 return INVALID_OPERATION; 1942 } 1943 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) { 1944 // device to device connection 1945 if (patchDesc != 0) { 1946 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id && 1947 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) { 1948 return BAD_VALUE; 1949 } 1950 } 1951 1952 sp<DeviceDescriptor> srcDeviceDesc = 1953 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id); 1954 sp<DeviceDescriptor> sinkDeviceDesc = 1955 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id); 1956 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) { 1957 return BAD_VALUE; 1958 } 1959 //update source and sink with our own data as the data passed in the patch may 1960 // be incomplete. 1961 struct audio_patch newPatch = *patch; 1962 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]); 1963 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]); 1964 1965 // TODO: add support for devices on different HW modules 1966 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) { 1967 return INVALID_OPERATION; 1968 } 1969 // TODO: check from routing capabilities in config file and other conflicting patches 1970 1971 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 1972 if (index >= 0) { 1973 afPatchHandle = patchDesc->mAfPatchHandle; 1974 } 1975 1976 status_t status = mpClientInterface->createAudioPatch(&newPatch, 1977 &afPatchHandle, 1978 0); 1979 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d", 1980 status, afPatchHandle); 1981 if (status == NO_ERROR) { 1982 if (index < 0) { 1983 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(), 1984 &newPatch, uid); 1985 addAudioPatch(patchDesc->mHandle, patchDesc); 1986 } else { 1987 patchDesc->mPatch = newPatch; 1988 } 1989 patchDesc->mAfPatchHandle = afPatchHandle; 1990 *handle = patchDesc->mHandle; 1991 nextAudioPortGeneration(); 1992 mpClientInterface->onAudioPatchListUpdate(); 1993 } else { 1994 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d", 1995 status); 1996 return INVALID_OPERATION; 1997 } 1998 } else { 1999 return BAD_VALUE; 2000 } 2001 } else { 2002 return BAD_VALUE; 2003 } 2004 return NO_ERROR; 2005} 2006 2007status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, 2008 uid_t uid) 2009{ 2010 ALOGV("releaseAudioPatch() patch %d", handle); 2011 2012 ssize_t index = mAudioPatches.indexOfKey(handle); 2013 2014 if (index < 0) { 2015 return BAD_VALUE; 2016 } 2017 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 2018 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d", 2019 mUidCached, patchDesc->mUid, uid); 2020 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) { 2021 return INVALID_OPERATION; 2022 } 2023 2024 struct audio_patch *patch = &patchDesc->mPatch; 2025 patchDesc->mUid = mUidCached; 2026 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) { 2027 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id); 2028 if (outputDesc == NULL) { 2029 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id); 2030 return BAD_VALUE; 2031 } 2032 2033 setOutputDevice(outputDesc->mIoHandle, 2034 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/), 2035 true, 2036 0, 2037 NULL); 2038 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) { 2039 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) { 2040 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id); 2041 if (inputDesc == NULL) { 2042 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id); 2043 return BAD_VALUE; 2044 } 2045 setInputDevice(inputDesc->mIoHandle, 2046 getNewInputDevice(inputDesc->mIoHandle), 2047 true, 2048 NULL); 2049 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) { 2050 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle; 2051 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 2052 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d", 2053 status, patchDesc->mAfPatchHandle); 2054 removeAudioPatch(patchDesc->mHandle); 2055 nextAudioPortGeneration(); 2056 mpClientInterface->onAudioPatchListUpdate(); 2057 } else { 2058 return BAD_VALUE; 2059 } 2060 } else { 2061 return BAD_VALUE; 2062 } 2063 return NO_ERROR; 2064} 2065 2066status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches, 2067 struct audio_patch *patches, 2068 unsigned int *generation) 2069{ 2070 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) || 2071 generation == NULL) { 2072 return BAD_VALUE; 2073 } 2074 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu", 2075 *num_patches, patches, mAudioPatches.size()); 2076 if (patches == NULL) { 2077 *num_patches = 0; 2078 } 2079 2080 size_t patchesWritten = 0; 2081 size_t patchesMax = *num_patches; 2082 for (size_t i = 0; 2083 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) { 2084 patches[patchesWritten] = mAudioPatches[i]->mPatch; 2085 patches[patchesWritten++].id = mAudioPatches[i]->mHandle; 2086 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d", 2087 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks); 2088 } 2089 *num_patches = mAudioPatches.size(); 2090 2091 *generation = curAudioPortGeneration(); 2092 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches); 2093 return NO_ERROR; 2094} 2095 2096status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config) 2097{ 2098 ALOGV("setAudioPortConfig()"); 2099 2100 if (config == NULL) { 2101 return BAD_VALUE; 2102 } 2103 ALOGV("setAudioPortConfig() on port handle %d", config->id); 2104 // Only support gain configuration for now 2105 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) { 2106 return INVALID_OPERATION; 2107 } 2108 2109 sp<AudioPortConfig> audioPortConfig; 2110 if (config->type == AUDIO_PORT_TYPE_MIX) { 2111 if (config->role == AUDIO_PORT_ROLE_SOURCE) { 2112 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id); 2113 if (outputDesc == NULL) { 2114 return BAD_VALUE; 2115 } 2116 ALOG_ASSERT(!outputDesc->isDuplicated(), 2117 "setAudioPortConfig() called on duplicated output %d", 2118 outputDesc->mIoHandle); 2119 audioPortConfig = outputDesc; 2120 } else if (config->role == AUDIO_PORT_ROLE_SINK) { 2121 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id); 2122 if (inputDesc == NULL) { 2123 return BAD_VALUE; 2124 } 2125 audioPortConfig = inputDesc; 2126 } else { 2127 return BAD_VALUE; 2128 } 2129 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) { 2130 sp<DeviceDescriptor> deviceDesc; 2131 if (config->role == AUDIO_PORT_ROLE_SOURCE) { 2132 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id); 2133 } else if (config->role == AUDIO_PORT_ROLE_SINK) { 2134 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id); 2135 } else { 2136 return BAD_VALUE; 2137 } 2138 if (deviceDesc == NULL) { 2139 return BAD_VALUE; 2140 } 2141 audioPortConfig = deviceDesc; 2142 } else { 2143 return BAD_VALUE; 2144 } 2145 2146 struct audio_port_config backupConfig; 2147 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig); 2148 if (status == NO_ERROR) { 2149 struct audio_port_config newConfig; 2150 audioPortConfig->toAudioPortConfig(&newConfig, config); 2151 status = mpClientInterface->setAudioPortConfig(&newConfig, 0); 2152 } 2153 if (status != NO_ERROR) { 2154 audioPortConfig->applyAudioPortConfig(&backupConfig); 2155 } 2156 2157 return status; 2158} 2159 2160void AudioPolicyManager::clearAudioPatches(uid_t uid) 2161{ 2162 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) { 2163 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i); 2164 if (patchDesc->mUid == uid) { 2165 // releaseAudioPatch() removes the patch from mAudioPatches 2166 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) { 2167 i--; 2168 } 2169 } 2170 } 2171} 2172 2173status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle, 2174 const sp<AudioPatch>& patch) 2175{ 2176 ssize_t index = mAudioPatches.indexOfKey(handle); 2177 2178 if (index >= 0) { 2179 ALOGW("addAudioPatch() patch %d already in", handle); 2180 return ALREADY_EXISTS; 2181 } 2182 mAudioPatches.add(handle, patch); 2183 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d" 2184 "sink handle %d", 2185 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks, 2186 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id); 2187 return NO_ERROR; 2188} 2189 2190status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle) 2191{ 2192 ssize_t index = mAudioPatches.indexOfKey(handle); 2193 2194 if (index < 0) { 2195 ALOGW("removeAudioPatch() patch %d not in", handle); 2196 return ALREADY_EXISTS; 2197 } 2198 ALOGV("removeAudioPatch() handle %d af handle %d", handle, 2199 mAudioPatches.valueAt(index)->mAfPatchHandle); 2200 mAudioPatches.removeItemsAt(index); 2201 return NO_ERROR; 2202} 2203 2204// ---------------------------------------------------------------------------- 2205// AudioPolicyManager 2206// ---------------------------------------------------------------------------- 2207 2208uint32_t AudioPolicyManager::nextUniqueId() 2209{ 2210 return android_atomic_inc(&mNextUniqueId); 2211} 2212 2213uint32_t AudioPolicyManager::nextAudioPortGeneration() 2214{ 2215 return android_atomic_inc(&mAudioPortGeneration); 2216} 2217 2218AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface) 2219 : 2220#ifdef AUDIO_POLICY_TEST 2221 Thread(false), 2222#endif //AUDIO_POLICY_TEST 2223 mPrimaryOutput((audio_io_handle_t)0), 2224 mPhoneState(AUDIO_MODE_NORMAL), 2225 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f), 2226 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0), 2227 mA2dpSuspended(false), 2228 mSpeakerDrcEnabled(false), mNextUniqueId(1), 2229 mAudioPortGeneration(1) 2230{ 2231 mUidCached = getuid(); 2232 mpClientInterface = clientInterface; 2233 2234 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) { 2235 mForceUse[i] = AUDIO_POLICY_FORCE_NONE; 2236 } 2237 2238 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER); 2239 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) { 2240 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) { 2241 ALOGE("could not load audio policy configuration file, setting defaults"); 2242 defaultAudioPolicyConfig(); 2243 } 2244 } 2245 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices 2246 2247 // must be done after reading the policy 2248 initializeVolumeCurves(); 2249 2250 // open all output streams needed to access attached devices 2251 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types(); 2252 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN; 2253 for (size_t i = 0; i < mHwModules.size(); i++) { 2254 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName); 2255 if (mHwModules[i]->mHandle == 0) { 2256 ALOGW("could not open HW module %s", mHwModules[i]->mName); 2257 continue; 2258 } 2259 // open all output streams needed to access attached devices 2260 // except for direct output streams that are only opened when they are actually 2261 // required by an app. 2262 // This also validates mAvailableOutputDevices list 2263 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 2264 { 2265 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j]; 2266 2267 if (outProfile->mSupportedDevices.isEmpty()) { 2268 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName); 2269 continue; 2270 } 2271 2272 audio_devices_t profileTypes = outProfile->mSupportedDevices.types(); 2273 if ((profileTypes & outputDeviceTypes) && 2274 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) { 2275 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile); 2276 2277 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice->mDeviceType & profileTypes); 2278 audio_io_handle_t output = mpClientInterface->openOutput( 2279 outProfile->mModule->mHandle, 2280 &outputDesc->mDevice, 2281 &outputDesc->mSamplingRate, 2282 &outputDesc->mFormat, 2283 &outputDesc->mChannelMask, 2284 &outputDesc->mLatency, 2285 outputDesc->mFlags); 2286 if (output == 0) { 2287 ALOGW("Cannot open output stream for device %08x on hw module %s", 2288 outputDesc->mDevice, 2289 mHwModules[i]->mName); 2290 } else { 2291 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) { 2292 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType; 2293 ssize_t index = 2294 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]); 2295 // give a valid ID to an attached device once confirmed it is reachable 2296 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) { 2297 mAvailableOutputDevices[index]->mId = nextUniqueId(); 2298 mAvailableOutputDevices[index]->mModule = mHwModules[i]; 2299 } 2300 } 2301 if (mPrimaryOutput == 0 && 2302 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) { 2303 mPrimaryOutput = output; 2304 } 2305 addOutput(output, outputDesc); 2306 ALOGI("CSTOR setOutputDevice %08x", outputDesc->mDevice); 2307 setOutputDevice(output, 2308 outputDesc->mDevice, 2309 true); 2310 } 2311 } 2312 } 2313 // open input streams needed to access attached devices to validate 2314 // mAvailableInputDevices list 2315 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) 2316 { 2317 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j]; 2318 2319 if (inProfile->mSupportedDevices.isEmpty()) { 2320 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName); 2321 continue; 2322 } 2323 2324 audio_devices_t profileTypes = inProfile->mSupportedDevices.types(); 2325 if (profileTypes & inputDeviceTypes) { 2326 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile); 2327 2328 inputDesc->mInputSource = AUDIO_SOURCE_MIC; 2329 inputDesc->mDevice = inProfile->mSupportedDevices[0]->mDeviceType; 2330 audio_io_handle_t input = mpClientInterface->openInput( 2331 inProfile->mModule->mHandle, 2332 &inputDesc->mDevice, 2333 &inputDesc->mSamplingRate, 2334 &inputDesc->mFormat, 2335 &inputDesc->mChannelMask); 2336 2337 if (input != 0) { 2338 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) { 2339 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType; 2340 ssize_t index = 2341 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]); 2342 // give a valid ID to an attached device once confirmed it is reachable 2343 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) { 2344 mAvailableInputDevices[index]->mId = nextUniqueId(); 2345 mAvailableInputDevices[index]->mModule = mHwModules[i]; 2346 } 2347 } 2348 mpClientInterface->closeInput(input); 2349 } else { 2350 ALOGW("Cannot open input stream for device %08x on hw module %s", 2351 inputDesc->mDevice, 2352 mHwModules[i]->mName); 2353 } 2354 } 2355 } 2356 } 2357 // make sure all attached devices have been allocated a unique ID 2358 for (size_t i = 0; i < mAvailableOutputDevices.size();) { 2359 if (mAvailableOutputDevices[i]->mId == 0) { 2360 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType); 2361 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]); 2362 continue; 2363 } 2364 i++; 2365 } 2366 for (size_t i = 0; i < mAvailableInputDevices.size();) { 2367 if (mAvailableInputDevices[i]->mId == 0) { 2368 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType); 2369 mAvailableInputDevices.remove(mAvailableInputDevices[i]); 2370 continue; 2371 } 2372 i++; 2373 } 2374 // make sure default device is reachable 2375 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) { 2376 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType); 2377 } 2378 2379 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output"); 2380 2381 updateDevicesAndOutputs(); 2382 2383#ifdef AUDIO_POLICY_TEST 2384 if (mPrimaryOutput != 0) { 2385 AudioParameter outputCmd = AudioParameter(); 2386 outputCmd.addInt(String8("set_id"), 0); 2387 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString()); 2388 2389 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER; 2390 mTestSamplingRate = 44100; 2391 mTestFormat = AUDIO_FORMAT_PCM_16_BIT; 2392 mTestChannels = AUDIO_CHANNEL_OUT_STEREO; 2393 mTestLatencyMs = 0; 2394 mCurOutput = 0; 2395 mDirectOutput = false; 2396 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) { 2397 mTestOutputs[i] = 0; 2398 } 2399 2400 const size_t SIZE = 256; 2401 char buffer[SIZE]; 2402 snprintf(buffer, SIZE, "AudioPolicyManagerTest"); 2403 run(buffer, ANDROID_PRIORITY_AUDIO); 2404 } 2405#endif //AUDIO_POLICY_TEST 2406} 2407 2408AudioPolicyManager::~AudioPolicyManager() 2409{ 2410#ifdef AUDIO_POLICY_TEST 2411 exit(); 2412#endif //AUDIO_POLICY_TEST 2413 for (size_t i = 0; i < mOutputs.size(); i++) { 2414 mpClientInterface->closeOutput(mOutputs.keyAt(i)); 2415 } 2416 for (size_t i = 0; i < mInputs.size(); i++) { 2417 mpClientInterface->closeInput(mInputs.keyAt(i)); 2418 } 2419 mAvailableOutputDevices.clear(); 2420 mAvailableInputDevices.clear(); 2421 mOutputs.clear(); 2422 mInputs.clear(); 2423 mHwModules.clear(); 2424} 2425 2426status_t AudioPolicyManager::initCheck() 2427{ 2428 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR; 2429} 2430 2431#ifdef AUDIO_POLICY_TEST 2432bool AudioPolicyManager::threadLoop() 2433{ 2434 ALOGV("entering threadLoop()"); 2435 while (!exitPending()) 2436 { 2437 String8 command; 2438 int valueInt; 2439 String8 value; 2440 2441 Mutex::Autolock _l(mLock); 2442 mWaitWorkCV.waitRelative(mLock, milliseconds(50)); 2443 2444 command = mpClientInterface->getParameters(0, String8("test_cmd_policy")); 2445 AudioParameter param = AudioParameter(command); 2446 2447 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR && 2448 valueInt != 0) { 2449 ALOGV("Test command %s received", command.string()); 2450 String8 target; 2451 if (param.get(String8("target"), target) != NO_ERROR) { 2452 target = "Manager"; 2453 } 2454 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) { 2455 param.remove(String8("test_cmd_policy_output")); 2456 mCurOutput = valueInt; 2457 } 2458 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) { 2459 param.remove(String8("test_cmd_policy_direct")); 2460 if (value == "false") { 2461 mDirectOutput = false; 2462 } else if (value == "true") { 2463 mDirectOutput = true; 2464 } 2465 } 2466 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) { 2467 param.remove(String8("test_cmd_policy_input")); 2468 mTestInput = valueInt; 2469 } 2470 2471 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) { 2472 param.remove(String8("test_cmd_policy_format")); 2473 int format = AUDIO_FORMAT_INVALID; 2474 if (value == "PCM 16 bits") { 2475 format = AUDIO_FORMAT_PCM_16_BIT; 2476 } else if (value == "PCM 8 bits") { 2477 format = AUDIO_FORMAT_PCM_8_BIT; 2478 } else if (value == "Compressed MP3") { 2479 format = AUDIO_FORMAT_MP3; 2480 } 2481 if (format != AUDIO_FORMAT_INVALID) { 2482 if (target == "Manager") { 2483 mTestFormat = format; 2484 } else if (mTestOutputs[mCurOutput] != 0) { 2485 AudioParameter outputParam = AudioParameter(); 2486 outputParam.addInt(String8("format"), format); 2487 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 2488 } 2489 } 2490 } 2491 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) { 2492 param.remove(String8("test_cmd_policy_channels")); 2493 int channels = 0; 2494 2495 if (value == "Channels Stereo") { 2496 channels = AUDIO_CHANNEL_OUT_STEREO; 2497 } else if (value == "Channels Mono") { 2498 channels = AUDIO_CHANNEL_OUT_MONO; 2499 } 2500 if (channels != 0) { 2501 if (target == "Manager") { 2502 mTestChannels = channels; 2503 } else if (mTestOutputs[mCurOutput] != 0) { 2504 AudioParameter outputParam = AudioParameter(); 2505 outputParam.addInt(String8("channels"), channels); 2506 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 2507 } 2508 } 2509 } 2510 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) { 2511 param.remove(String8("test_cmd_policy_sampleRate")); 2512 if (valueInt >= 0 && valueInt <= 96000) { 2513 int samplingRate = valueInt; 2514 if (target == "Manager") { 2515 mTestSamplingRate = samplingRate; 2516 } else if (mTestOutputs[mCurOutput] != 0) { 2517 AudioParameter outputParam = AudioParameter(); 2518 outputParam.addInt(String8("sampling_rate"), samplingRate); 2519 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 2520 } 2521 } 2522 } 2523 2524 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) { 2525 param.remove(String8("test_cmd_policy_reopen")); 2526 2527 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput); 2528 mpClientInterface->closeOutput(mPrimaryOutput); 2529 2530 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle; 2531 2532 mOutputs.removeItem(mPrimaryOutput); 2533 2534 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL); 2535 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER; 2536 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle, 2537 &outputDesc->mDevice, 2538 &outputDesc->mSamplingRate, 2539 &outputDesc->mFormat, 2540 &outputDesc->mChannelMask, 2541 &outputDesc->mLatency, 2542 outputDesc->mFlags); 2543 if (mPrimaryOutput == 0) { 2544 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d", 2545 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask); 2546 } else { 2547 AudioParameter outputCmd = AudioParameter(); 2548 outputCmd.addInt(String8("set_id"), 0); 2549 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString()); 2550 addOutput(mPrimaryOutput, outputDesc); 2551 } 2552 } 2553 2554 2555 mpClientInterface->setParameters(0, String8("test_cmd_policy=")); 2556 } 2557 } 2558 return false; 2559} 2560 2561void AudioPolicyManager::exit() 2562{ 2563 { 2564 AutoMutex _l(mLock); 2565 requestExit(); 2566 mWaitWorkCV.signal(); 2567 } 2568 requestExitAndWait(); 2569} 2570 2571int AudioPolicyManager::testOutputIndex(audio_io_handle_t output) 2572{ 2573 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) { 2574 if (output == mTestOutputs[i]) return i; 2575 } 2576 return 0; 2577} 2578#endif //AUDIO_POLICY_TEST 2579 2580// --- 2581 2582void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc) 2583{ 2584 outputDesc->mIoHandle = output; 2585 outputDesc->mId = nextUniqueId(); 2586 mOutputs.add(output, outputDesc); 2587 nextAudioPortGeneration(); 2588} 2589 2590void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc) 2591{ 2592 inputDesc->mIoHandle = input; 2593 inputDesc->mId = nextUniqueId(); 2594 mInputs.add(input, inputDesc); 2595 nextAudioPortGeneration(); 2596} 2597 2598String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address) 2599{ 2600 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) { 2601 return String8("a2dp_sink_address=")+address; 2602 } 2603 return address; 2604} 2605 2606status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device, 2607 audio_policy_dev_state_t state, 2608 SortedVector<audio_io_handle_t>& outputs, 2609 const String8 address) 2610{ 2611 sp<AudioOutputDescriptor> desc; 2612 2613 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) { 2614 // first list already open outputs that can be routed to this device 2615 for (size_t i = 0; i < mOutputs.size(); i++) { 2616 desc = mOutputs.valueAt(i); 2617 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) { 2618 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i)); 2619 outputs.add(mOutputs.keyAt(i)); 2620 } 2621 } 2622 // then look for output profiles that can be routed to this device 2623 SortedVector< sp<IOProfile> > profiles; 2624 for (size_t i = 0; i < mHwModules.size(); i++) 2625 { 2626 if (mHwModules[i]->mHandle == 0) { 2627 continue; 2628 } 2629 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 2630 { 2631 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) { 2632 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i); 2633 profiles.add(mHwModules[i]->mOutputProfiles[j]); 2634 } 2635 } 2636 } 2637 2638 if (profiles.isEmpty() && outputs.isEmpty()) { 2639 ALOGW("checkOutputsForDevice(): No output available for device %04x", device); 2640 return BAD_VALUE; 2641 } 2642 2643 // open outputs for matching profiles if needed. Direct outputs are also opened to 2644 // query for dynamic parameters and will be closed later by setDeviceConnectionState() 2645 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) { 2646 sp<IOProfile> profile = profiles[profile_index]; 2647 2648 // nothing to do if one output is already opened for this profile 2649 size_t j; 2650 for (j = 0; j < mOutputs.size(); j++) { 2651 desc = mOutputs.valueAt(j); 2652 if (!desc->isDuplicated() && desc->mProfile == profile) { 2653 break; 2654 } 2655 } 2656 if (j != mOutputs.size()) { 2657 continue; 2658 } 2659 2660 ALOGV("opening output for device %08x with params %s", device, address.string()); 2661 desc = new AudioOutputDescriptor(profile); 2662 desc->mDevice = device; 2663 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER; 2664 offloadInfo.sample_rate = desc->mSamplingRate; 2665 offloadInfo.format = desc->mFormat; 2666 offloadInfo.channel_mask = desc->mChannelMask; 2667 2668 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle, 2669 &desc->mDevice, 2670 &desc->mSamplingRate, 2671 &desc->mFormat, 2672 &desc->mChannelMask, 2673 &desc->mLatency, 2674 desc->mFlags, 2675 &offloadInfo); 2676 if (output != 0) { 2677 // Here is where the out_set_parameters() for card & device gets called 2678 if (!address.isEmpty()) { 2679 mpClientInterface->setParameters(output, addressToParameter(device, address)); 2680 } 2681 2682 // Here is where we step through and resolve any "dynamic" fields 2683 String8 reply; 2684 char *value; 2685 if (profile->mSamplingRates[0] == 0) { 2686 reply = mpClientInterface->getParameters(output, 2687 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES)); 2688 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s", 2689 reply.string()); 2690 value = strpbrk((char *)reply.string(), "="); 2691 if (value != NULL) { 2692 profile->loadSamplingRates(value + 1); 2693 } 2694 } 2695 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) { 2696 reply = mpClientInterface->getParameters(output, 2697 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS)); 2698 ALOGV("checkOutputsForDevice() direct output sup formats %s", 2699 reply.string()); 2700 value = strpbrk((char *)reply.string(), "="); 2701 if (value != NULL) { 2702 profile->loadFormats(value + 1); 2703 } 2704 } 2705 if (profile->mChannelMasks[0] == 0) { 2706 reply = mpClientInterface->getParameters(output, 2707 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS)); 2708 ALOGV("checkOutputsForDevice() direct output sup channel masks %s", 2709 reply.string()); 2710 value = strpbrk((char *)reply.string(), "="); 2711 if (value != NULL) { 2712 profile->loadOutChannels(value + 1); 2713 } 2714 } 2715 if (((profile->mSamplingRates[0] == 0) && 2716 (profile->mSamplingRates.size() < 2)) || 2717 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) && 2718 (profile->mFormats.size() < 2)) || 2719 ((profile->mChannelMasks[0] == 0) && 2720 (profile->mChannelMasks.size() < 2))) { 2721 ALOGW("checkOutputsForDevice() direct output missing param"); 2722 mpClientInterface->closeOutput(output); 2723 output = 0; 2724 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 || 2725 profile->mChannelMasks[0] == 0) { 2726 mpClientInterface->closeOutput(output); 2727 desc->mSamplingRate = profile->pickSamplingRate(); 2728 desc->mFormat = profile->pickFormat(); 2729 desc->mChannelMask = profile->pickChannelMask(); 2730 offloadInfo.sample_rate = desc->mSamplingRate; 2731 offloadInfo.format = desc->mFormat; 2732 offloadInfo.channel_mask = desc->mChannelMask; 2733 output = mpClientInterface->openOutput( 2734 profile->mModule->mHandle, 2735 &desc->mDevice, 2736 &desc->mSamplingRate, 2737 &desc->mFormat, 2738 &desc->mChannelMask, 2739 &desc->mLatency, 2740 desc->mFlags, 2741 &offloadInfo); 2742 } 2743 2744 if (output != 0) { 2745 addOutput(output, desc); 2746 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) { 2747 audio_io_handle_t duplicatedOutput = 0; 2748 2749 // set initial stream volume for device 2750 applyStreamVolumes(output, device, 0, true); 2751 2752 //TODO: configure audio effect output stage here 2753 2754 // open a duplicating output thread for the new output and the primary output 2755 duplicatedOutput = mpClientInterface->openDuplicateOutput(output, 2756 mPrimaryOutput); 2757 if (duplicatedOutput != 0) { 2758 // add duplicated output descriptor 2759 sp<AudioOutputDescriptor> dupOutputDesc = new AudioOutputDescriptor(NULL); 2760 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput); 2761 dupOutputDesc->mOutput2 = mOutputs.valueFor(output); 2762 dupOutputDesc->mSamplingRate = desc->mSamplingRate; 2763 dupOutputDesc->mFormat = desc->mFormat; 2764 dupOutputDesc->mChannelMask = desc->mChannelMask; 2765 dupOutputDesc->mLatency = desc->mLatency; 2766 addOutput(duplicatedOutput, dupOutputDesc); 2767 applyStreamVolumes(duplicatedOutput, device, 0, true); 2768 } else { 2769 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d", 2770 mPrimaryOutput, output); 2771 mpClientInterface->closeOutput(output); 2772 mOutputs.removeItem(output); 2773 nextAudioPortGeneration(); 2774 output = 0; 2775 } 2776 } 2777 } 2778 } 2779 if (output == 0) { 2780 ALOGW("checkOutputsForDevice() could not open output for device %x", device); 2781 profiles.removeAt(profile_index); 2782 profile_index--; 2783 } else { 2784 outputs.add(output); 2785 ALOGV("checkOutputsForDevice(): adding output %d", output); 2786 } 2787 } 2788 2789 if (profiles.isEmpty()) { 2790 ALOGW("checkOutputsForDevice(): No output available for device %04x", device); 2791 return BAD_VALUE; 2792 } 2793 } else { // Disconnect 2794 // check if one opened output is not needed any more after disconnecting one device 2795 for (size_t i = 0; i < mOutputs.size(); i++) { 2796 desc = mOutputs.valueAt(i); 2797 if (!desc->isDuplicated() && 2798 !(desc->mProfile->mSupportedDevices.types() & 2799 mAvailableOutputDevices.types())) { 2800 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i)); 2801 outputs.add(mOutputs.keyAt(i)); 2802 } 2803 } 2804 // Clear any profiles associated with the disconnected device. 2805 for (size_t i = 0; i < mHwModules.size(); i++) 2806 { 2807 if (mHwModules[i]->mHandle == 0) { 2808 continue; 2809 } 2810 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 2811 { 2812 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j]; 2813 if (profile->mSupportedDevices.types() & device) { 2814 ALOGV("checkOutputsForDevice(): " 2815 "clearing direct output profile %zu on module %zu", j, i); 2816 if (profile->mSamplingRates[0] == 0) { 2817 profile->mSamplingRates.clear(); 2818 profile->mSamplingRates.add(0); 2819 } 2820 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) { 2821 profile->mFormats.clear(); 2822 profile->mFormats.add(AUDIO_FORMAT_DEFAULT); 2823 } 2824 if (profile->mChannelMasks[0] == 0) { 2825 profile->mChannelMasks.clear(); 2826 profile->mChannelMasks.add(0); 2827 } 2828 } 2829 } 2830 } 2831 } 2832 return NO_ERROR; 2833} 2834 2835status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device, 2836 audio_policy_dev_state_t state, 2837 SortedVector<audio_io_handle_t>& inputs, 2838 const String8 address) 2839{ 2840 sp<AudioInputDescriptor> desc; 2841 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) { 2842 // first list already open inputs that can be routed to this device 2843 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) { 2844 desc = mInputs.valueAt(input_index); 2845 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) { 2846 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index)); 2847 inputs.add(mInputs.keyAt(input_index)); 2848 } 2849 } 2850 2851 // then look for input profiles that can be routed to this device 2852 SortedVector< sp<IOProfile> > profiles; 2853 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++) 2854 { 2855 if (mHwModules[module_idx]->mHandle == 0) { 2856 continue; 2857 } 2858 for (size_t profile_index = 0; 2859 profile_index < mHwModules[module_idx]->mInputProfiles.size(); 2860 profile_index++) 2861 { 2862 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types() 2863 & (device & ~AUDIO_DEVICE_BIT_IN)) { 2864 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu", 2865 profile_index, module_idx); 2866 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]); 2867 } 2868 } 2869 } 2870 2871 if (profiles.isEmpty() && inputs.isEmpty()) { 2872 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device); 2873 return BAD_VALUE; 2874 } 2875 2876 // open inputs for matching profiles if needed. Direct inputs are also opened to 2877 // query for dynamic parameters and will be closed later by setDeviceConnectionState() 2878 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) { 2879 2880 sp<IOProfile> profile = profiles[profile_index]; 2881 // nothing to do if one input is already opened for this profile 2882 size_t input_index; 2883 for (input_index = 0; input_index < mInputs.size(); input_index++) { 2884 desc = mInputs.valueAt(input_index); 2885 if (desc->mProfile == profile) { 2886 break; 2887 } 2888 } 2889 if (input_index != mInputs.size()) { 2890 continue; 2891 } 2892 2893 ALOGV("opening input for device 0x%X with params %s", device, address.string()); 2894 desc = new AudioInputDescriptor(profile); 2895 desc->mDevice = device; 2896 2897 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle, 2898 &desc->mDevice, 2899 &desc->mSamplingRate, 2900 &desc->mFormat, 2901 &desc->mChannelMask); 2902 2903 if (input != 0) { 2904 if (!address.isEmpty()) { 2905 mpClientInterface->setParameters(input, addressToParameter(device, address)); 2906 } 2907 2908 // Here is where we step through and resolve any "dynamic" fields 2909 String8 reply; 2910 char *value; 2911 if (profile->mSamplingRates[0] == 0) { 2912 reply = mpClientInterface->getParameters(input, 2913 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES)); 2914 ALOGV("checkInputsForDevice() direct input sup sampling rates %s", 2915 reply.string()); 2916 value = strpbrk((char *)reply.string(), "="); 2917 if (value != NULL) { 2918 profile->loadSamplingRates(value + 1); 2919 } 2920 } 2921 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) { 2922 reply = mpClientInterface->getParameters(input, 2923 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS)); 2924 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string()); 2925 value = strpbrk((char *)reply.string(), "="); 2926 if (value != NULL) { 2927 profile->loadFormats(value + 1); 2928 } 2929 } 2930 if (profile->mChannelMasks[0] == 0) { 2931 reply = mpClientInterface->getParameters(input, 2932 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS)); 2933 ALOGV("checkInputsForDevice() direct input sup channel masks %s", 2934 reply.string()); 2935 value = strpbrk((char *)reply.string(), "="); 2936 if (value != NULL) { 2937 profile->loadInChannels(value + 1); 2938 } 2939 } 2940 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) || 2941 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) || 2942 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) { 2943 ALOGW("checkInputsForDevice() direct input missing param"); 2944 mpClientInterface->closeInput(input); 2945 input = 0; 2946 } 2947 2948 if (input != 0) { 2949 addInput(input, desc); 2950 } 2951 } // endif input != 0 2952 2953 if (input == 0) { 2954 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device); 2955 profiles.removeAt(profile_index); 2956 profile_index--; 2957 } else { 2958 inputs.add(input); 2959 ALOGV("checkInputsForDevice(): adding input %d", input); 2960 } 2961 } // end scan profiles 2962 2963 if (profiles.isEmpty()) { 2964 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device); 2965 return BAD_VALUE; 2966 } 2967 } else { 2968 // Disconnect 2969 // check if one opened input is not needed any more after disconnecting one device 2970 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) { 2971 desc = mInputs.valueAt(input_index); 2972 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) { 2973 ALOGV("checkInputsForDevice(): disconnecting adding input %d", 2974 mInputs.keyAt(input_index)); 2975 inputs.add(mInputs.keyAt(input_index)); 2976 } 2977 } 2978 // Clear any profiles associated with the disconnected device. 2979 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) { 2980 if (mHwModules[module_index]->mHandle == 0) { 2981 continue; 2982 } 2983 for (size_t profile_index = 0; 2984 profile_index < mHwModules[module_index]->mInputProfiles.size(); 2985 profile_index++) { 2986 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index]; 2987 if (profile->mSupportedDevices.types() & device) { 2988 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu", 2989 profile_index, module_index); 2990 if (profile->mSamplingRates[0] == 0) { 2991 profile->mSamplingRates.clear(); 2992 profile->mSamplingRates.add(0); 2993 } 2994 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) { 2995 profile->mFormats.clear(); 2996 profile->mFormats.add(AUDIO_FORMAT_DEFAULT); 2997 } 2998 if (profile->mChannelMasks[0] == 0) { 2999 profile->mChannelMasks.clear(); 3000 profile->mChannelMasks.add(0); 3001 } 3002 } 3003 } 3004 } 3005 } // end disconnect 3006 3007 return NO_ERROR; 3008} 3009 3010 3011void AudioPolicyManager::closeOutput(audio_io_handle_t output) 3012{ 3013 ALOGV("closeOutput(%d)", output); 3014 3015 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 3016 if (outputDesc == NULL) { 3017 ALOGW("closeOutput() unknown output %d", output); 3018 return; 3019 } 3020 3021 // look for duplicated outputs connected to the output being removed. 3022 for (size_t i = 0; i < mOutputs.size(); i++) { 3023 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i); 3024 if (dupOutputDesc->isDuplicated() && 3025 (dupOutputDesc->mOutput1 == outputDesc || 3026 dupOutputDesc->mOutput2 == outputDesc)) { 3027 sp<AudioOutputDescriptor> outputDesc2; 3028 if (dupOutputDesc->mOutput1 == outputDesc) { 3029 outputDesc2 = dupOutputDesc->mOutput2; 3030 } else { 3031 outputDesc2 = dupOutputDesc->mOutput1; 3032 } 3033 // As all active tracks on duplicated output will be deleted, 3034 // and as they were also referenced on the other output, the reference 3035 // count for their stream type must be adjusted accordingly on 3036 // the other output. 3037 for (int j = 0; j < AUDIO_STREAM_CNT; j++) { 3038 int refCount = dupOutputDesc->mRefCount[j]; 3039 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount); 3040 } 3041 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i); 3042 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput); 3043 3044 mpClientInterface->closeOutput(duplicatedOutput); 3045 mOutputs.removeItem(duplicatedOutput); 3046 } 3047 } 3048 3049 AudioParameter param; 3050 param.add(String8("closing"), String8("true")); 3051 mpClientInterface->setParameters(output, param.toString()); 3052 3053 mpClientInterface->closeOutput(output); 3054 mOutputs.removeItem(output); 3055 mPreviousOutputs = mOutputs; 3056 nextAudioPortGeneration(); 3057} 3058 3059SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device, 3060 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs) 3061{ 3062 SortedVector<audio_io_handle_t> outputs; 3063 3064 ALOGVV("getOutputsForDevice() device %04x", device); 3065 for (size_t i = 0; i < openOutputs.size(); i++) { 3066 ALOGVV("output %d isDuplicated=%d device=%04x", 3067 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices()); 3068 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) { 3069 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i)); 3070 outputs.add(openOutputs.keyAt(i)); 3071 } 3072 } 3073 return outputs; 3074} 3075 3076bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1, 3077 SortedVector<audio_io_handle_t>& outputs2) 3078{ 3079 if (outputs1.size() != outputs2.size()) { 3080 return false; 3081 } 3082 for (size_t i = 0; i < outputs1.size(); i++) { 3083 if (outputs1[i] != outputs2[i]) { 3084 return false; 3085 } 3086 } 3087 return true; 3088} 3089 3090void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy) 3091{ 3092 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/); 3093 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/); 3094 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs); 3095 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs); 3096 3097 if (!vectorsEqual(srcOutputs,dstOutputs)) { 3098 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d", 3099 strategy, srcOutputs[0], dstOutputs[0]); 3100 // mute strategy while moving tracks from one output to another 3101 for (size_t i = 0; i < srcOutputs.size(); i++) { 3102 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]); 3103 if (desc->isStrategyActive(strategy)) { 3104 setStrategyMute(strategy, true, srcOutputs[i]); 3105 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice); 3106 } 3107 } 3108 3109 // Move effects associated to this strategy from previous output to new output 3110 if (strategy == STRATEGY_MEDIA) { 3111 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs); 3112 SortedVector<audio_io_handle_t> moved; 3113 for (size_t i = 0; i < mEffects.size(); i++) { 3114 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i); 3115 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX && 3116 effectDesc->mIo != fxOutput) { 3117 if (moved.indexOf(effectDesc->mIo) < 0) { 3118 ALOGV("checkOutputForStrategy() moving effect %d to output %d", 3119 mEffects.keyAt(i), fxOutput); 3120 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo, 3121 fxOutput); 3122 moved.add(effectDesc->mIo); 3123 } 3124 effectDesc->mIo = fxOutput; 3125 } 3126 } 3127 } 3128 // Move tracks associated to this strategy from previous output to new output 3129 for (int i = 0; i < AUDIO_STREAM_CNT; i++) { 3130 if (getStrategy((audio_stream_type_t)i) == strategy) { 3131 mpClientInterface->invalidateStream((audio_stream_type_t)i); 3132 } 3133 } 3134 } 3135} 3136 3137void AudioPolicyManager::checkOutputForAllStrategies() 3138{ 3139 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE); 3140 checkOutputForStrategy(STRATEGY_PHONE); 3141 checkOutputForStrategy(STRATEGY_SONIFICATION); 3142 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL); 3143 checkOutputForStrategy(STRATEGY_MEDIA); 3144 checkOutputForStrategy(STRATEGY_DTMF); 3145} 3146 3147audio_io_handle_t AudioPolicyManager::getA2dpOutput() 3148{ 3149 for (size_t i = 0; i < mOutputs.size(); i++) { 3150 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i); 3151 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) { 3152 return mOutputs.keyAt(i); 3153 } 3154 } 3155 3156 return 0; 3157} 3158 3159void AudioPolicyManager::checkA2dpSuspend() 3160{ 3161 audio_io_handle_t a2dpOutput = getA2dpOutput(); 3162 if (a2dpOutput == 0) { 3163 mA2dpSuspended = false; 3164 return; 3165 } 3166 3167 bool isScoConnected = 3168 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0; 3169 // suspend A2DP output if: 3170 // (NOT already suspended) && 3171 // ((SCO device is connected && 3172 // (forced usage for communication || for record is SCO))) || 3173 // (phone state is ringing || in call) 3174 // 3175 // restore A2DP output if: 3176 // (Already suspended) && 3177 // ((SCO device is NOT connected || 3178 // (forced usage NOT for communication && NOT for record is SCO))) && 3179 // (phone state is NOT ringing && NOT in call) 3180 // 3181 if (mA2dpSuspended) { 3182 if ((!isScoConnected || 3183 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) && 3184 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) && 3185 ((mPhoneState != AUDIO_MODE_IN_CALL) && 3186 (mPhoneState != AUDIO_MODE_RINGTONE))) { 3187 3188 mpClientInterface->restoreOutput(a2dpOutput); 3189 mA2dpSuspended = false; 3190 } 3191 } else { 3192 if ((isScoConnected && 3193 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) || 3194 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) || 3195 ((mPhoneState == AUDIO_MODE_IN_CALL) || 3196 (mPhoneState == AUDIO_MODE_RINGTONE))) { 3197 3198 mpClientInterface->suspendOutput(a2dpOutput); 3199 mA2dpSuspended = true; 3200 } 3201 } 3202} 3203 3204audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache) 3205{ 3206 audio_devices_t device = AUDIO_DEVICE_NONE; 3207 3208 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 3209 3210 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle); 3211 if (index >= 0) { 3212 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 3213 if (patchDesc->mUid != mUidCached) { 3214 ALOGV("getNewOutputDevice() device %08x forced by patch %d", 3215 outputDesc->device(), outputDesc->mPatchHandle); 3216 return outputDesc->device(); 3217 } 3218 } 3219 3220 // check the following by order of priority to request a routing change if necessary: 3221 // 1: the strategy enforced audible is active on the output: 3222 // use device for strategy enforced audible 3223 // 2: we are in call or the strategy phone is active on the output: 3224 // use device for strategy phone 3225 // 3: the strategy sonification is active on the output: 3226 // use device for strategy sonification 3227 // 4: the strategy "respectful" sonification is active on the output: 3228 // use device for strategy "respectful" sonification 3229 // 5: the strategy media is active on the output: 3230 // use device for strategy media 3231 // 6: the strategy DTMF is active on the output: 3232 // use device for strategy DTMF 3233 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) { 3234 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache); 3235 } else if (isInCall() || 3236 outputDesc->isStrategyActive(STRATEGY_PHONE)) { 3237 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache); 3238 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) { 3239 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache); 3240 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) { 3241 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache); 3242 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) { 3243 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache); 3244 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) { 3245 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache); 3246 } 3247 3248 ALOGV("getNewOutputDevice() selected device %x", device); 3249 return device; 3250} 3251 3252audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input) 3253{ 3254 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input); 3255 3256 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle); 3257 if (index >= 0) { 3258 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 3259 if (patchDesc->mUid != mUidCached) { 3260 ALOGV("getNewInputDevice() device %08x forced by patch %d", 3261 inputDesc->mDevice, inputDesc->mPatchHandle); 3262 return inputDesc->mDevice; 3263 } 3264 } 3265 3266 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource); 3267 3268 ALOGV("getNewInputDevice() selected device %x", device); 3269 return device; 3270} 3271 3272uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) { 3273 return (uint32_t)getStrategy(stream); 3274} 3275 3276audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) { 3277 // By checking the range of stream before calling getStrategy, we avoid 3278 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE 3279 // and then return STRATEGY_MEDIA, but we want to return the empty set. 3280 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) { 3281 return AUDIO_DEVICE_NONE; 3282 } 3283 audio_devices_t devices; 3284 AudioPolicyManager::routing_strategy strategy = getStrategy(stream); 3285 devices = getDeviceForStrategy(strategy, true /*fromCache*/); 3286 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs); 3287 for (size_t i = 0; i < outputs.size(); i++) { 3288 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]); 3289 if (outputDesc->isStrategyActive(strategy)) { 3290 devices = outputDesc->device(); 3291 break; 3292 } 3293 } 3294 return devices; 3295} 3296 3297AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy( 3298 audio_stream_type_t stream) { 3299 // stream to strategy mapping 3300 switch (stream) { 3301 case AUDIO_STREAM_VOICE_CALL: 3302 case AUDIO_STREAM_BLUETOOTH_SCO: 3303 return STRATEGY_PHONE; 3304 case AUDIO_STREAM_RING: 3305 case AUDIO_STREAM_ALARM: 3306 return STRATEGY_SONIFICATION; 3307 case AUDIO_STREAM_NOTIFICATION: 3308 return STRATEGY_SONIFICATION_RESPECTFUL; 3309 case AUDIO_STREAM_DTMF: 3310 return STRATEGY_DTMF; 3311 default: 3312 ALOGE("unknown stream type"); 3313 case AUDIO_STREAM_SYSTEM: 3314 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs 3315 // while key clicks are played produces a poor result 3316 case AUDIO_STREAM_TTS: 3317 case AUDIO_STREAM_MUSIC: 3318 return STRATEGY_MEDIA; 3319 case AUDIO_STREAM_ENFORCED_AUDIBLE: 3320 return STRATEGY_ENFORCED_AUDIBLE; 3321 } 3322} 3323 3324uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) { 3325 // flags to strategy mapping 3326 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) { 3327 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE; 3328 } 3329 3330 // usage to strategy mapping 3331 switch (attr->usage) { 3332 case AUDIO_USAGE_MEDIA: 3333 case AUDIO_USAGE_GAME: 3334 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY: 3335 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE: 3336 case AUDIO_USAGE_ASSISTANCE_SONIFICATION: 3337 return (uint32_t) STRATEGY_MEDIA; 3338 3339 case AUDIO_USAGE_VOICE_COMMUNICATION: 3340 return (uint32_t) STRATEGY_PHONE; 3341 3342 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING: 3343 return (uint32_t) STRATEGY_DTMF; 3344 3345 case AUDIO_USAGE_ALARM: 3346 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE: 3347 return (uint32_t) STRATEGY_SONIFICATION; 3348 3349 case AUDIO_USAGE_NOTIFICATION: 3350 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST: 3351 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT: 3352 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED: 3353 case AUDIO_USAGE_NOTIFICATION_EVENT: 3354 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL; 3355 3356 case AUDIO_USAGE_UNKNOWN: 3357 default: 3358 return (uint32_t) STRATEGY_MEDIA; 3359 } 3360} 3361 3362void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) { 3363 switch(stream) { 3364 case AUDIO_STREAM_MUSIC: 3365 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL); 3366 updateDevicesAndOutputs(); 3367 break; 3368 default: 3369 break; 3370 } 3371} 3372 3373audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy, 3374 bool fromCache) 3375{ 3376 uint32_t device = AUDIO_DEVICE_NONE; 3377 3378 if (fromCache) { 3379 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x", 3380 strategy, mDeviceForStrategy[strategy]); 3381 return mDeviceForStrategy[strategy]; 3382 } 3383 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types(); 3384 switch (strategy) { 3385 3386 case STRATEGY_SONIFICATION_RESPECTFUL: 3387 if (isInCall()) { 3388 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/); 3389 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC, 3390 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) { 3391 // while media is playing on a remote device, use the the sonification behavior. 3392 // Note that we test this usecase before testing if media is playing because 3393 // the isStreamActive() method only informs about the activity of a stream, not 3394 // if it's for local playback. Note also that we use the same delay between both tests 3395 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/); 3396 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) { 3397 // while media is playing (or has recently played), use the same device 3398 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/); 3399 } else { 3400 // when media is not playing anymore, fall back on the sonification behavior 3401 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/); 3402 } 3403 3404 break; 3405 3406 case STRATEGY_DTMF: 3407 if (!isInCall()) { 3408 // when off call, DTMF strategy follows the same rules as MEDIA strategy 3409 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/); 3410 break; 3411 } 3412 // when in call, DTMF and PHONE strategies follow the same rules 3413 // FALL THROUGH 3414 3415 case STRATEGY_PHONE: 3416 // for phone strategy, we first consider the forced use and then the available devices by order 3417 // of priority 3418 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) { 3419 case AUDIO_POLICY_FORCE_BT_SCO: 3420 if (!isInCall() || strategy != STRATEGY_DTMF) { 3421 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT; 3422 if (device) break; 3423 } 3424 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET; 3425 if (device) break; 3426 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO; 3427 if (device) break; 3428 // if SCO device is requested but no SCO device is available, fall back to default case 3429 // FALL THROUGH 3430 3431 default: // FORCE_NONE 3432 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP 3433 if (!isInCall() && 3434 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) && 3435 (getA2dpOutput() != 0) && !mA2dpSuspended) { 3436 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP; 3437 if (device) break; 3438 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES; 3439 if (device) break; 3440 } 3441 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE; 3442 if (device) break; 3443 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET; 3444 if (device) break; 3445 if (mPhoneState != AUDIO_MODE_IN_CALL) { 3446 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY; 3447 if (device) break; 3448 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE; 3449 if (device) break; 3450 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET; 3451 if (device) break; 3452 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL; 3453 if (device) break; 3454 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET; 3455 if (device) break; 3456 } 3457 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE; 3458 if (device) break; 3459 device = mDefaultOutputDevice->mDeviceType; 3460 if (device == AUDIO_DEVICE_NONE) { 3461 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE"); 3462 } 3463 break; 3464 3465 case AUDIO_POLICY_FORCE_SPEAKER: 3466 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to 3467 // A2DP speaker when forcing to speaker output 3468 if (!isInCall() && 3469 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) && 3470 (getA2dpOutput() != 0) && !mA2dpSuspended) { 3471 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER; 3472 if (device) break; 3473 } 3474 if (mPhoneState != AUDIO_MODE_IN_CALL) { 3475 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY; 3476 if (device) break; 3477 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE; 3478 if (device) break; 3479 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET; 3480 if (device) break; 3481 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL; 3482 if (device) break; 3483 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET; 3484 if (device) break; 3485 } 3486 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER; 3487 if (device) break; 3488 device = mDefaultOutputDevice->mDeviceType; 3489 if (device == AUDIO_DEVICE_NONE) { 3490 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER"); 3491 } 3492 break; 3493 } 3494 break; 3495 3496 case STRATEGY_SONIFICATION: 3497 3498 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by 3499 // handleIncallSonification(). 3500 if (isInCall()) { 3501 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/); 3502 break; 3503 } 3504 // FALL THROUGH 3505 3506 case STRATEGY_ENFORCED_AUDIBLE: 3507 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION 3508 // except: 3509 // - when in call where it doesn't default to STRATEGY_PHONE behavior 3510 // - in countries where not enforced in which case it follows STRATEGY_MEDIA 3511 3512 if ((strategy == STRATEGY_SONIFICATION) || 3513 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) { 3514 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER; 3515 if (device == AUDIO_DEVICE_NONE) { 3516 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION"); 3517 } 3518 } 3519 // The second device used for sonification is the same as the device used by media strategy 3520 // FALL THROUGH 3521 3522 case STRATEGY_MEDIA: { 3523 uint32_t device2 = AUDIO_DEVICE_NONE; 3524 if (strategy != STRATEGY_SONIFICATION) { 3525 // no sonification on remote submix (e.g. WFD) 3526 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX; 3527 } 3528 if ((device2 == AUDIO_DEVICE_NONE) && 3529 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) && 3530 (getA2dpOutput() != 0) && !mA2dpSuspended) { 3531 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP; 3532 if (device2 == AUDIO_DEVICE_NONE) { 3533 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES; 3534 } 3535 if (device2 == AUDIO_DEVICE_NONE) { 3536 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER; 3537 } 3538 } 3539 if (device2 == AUDIO_DEVICE_NONE) { 3540 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE; 3541 } 3542 if (device2 == AUDIO_DEVICE_NONE) { 3543 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET; 3544 } 3545 if (device2 == AUDIO_DEVICE_NONE) { 3546 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY; 3547 } 3548 if (device2 == AUDIO_DEVICE_NONE) { 3549 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE; 3550 } 3551 if (device2 == AUDIO_DEVICE_NONE) { 3552 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET; 3553 } 3554 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) { 3555 // no sonification on aux digital (e.g. HDMI) 3556 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL; 3557 } 3558 if ((device2 == AUDIO_DEVICE_NONE) && 3559 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) { 3560 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET; 3561 } 3562 if (device2 == AUDIO_DEVICE_NONE) { 3563 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER; 3564 } 3565 int device3 = AUDIO_DEVICE_NONE; 3566 if (strategy == STRATEGY_MEDIA) { 3567 // ARC, SPDIF and AUX_LINE can co-exist with others. 3568 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC; 3569 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF); 3570 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE); 3571 } 3572 3573 device2 |= device3; 3574 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or 3575 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise 3576 device |= device2; 3577 3578 // If hdmi system audio mode is on, remove speaker out of output list. 3579 if ((strategy == STRATEGY_MEDIA) && 3580 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] == 3581 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) { 3582 device &= ~AUDIO_DEVICE_OUT_SPEAKER; 3583 } 3584 3585 if (device) break; 3586 device = mDefaultOutputDevice->mDeviceType; 3587 if (device == AUDIO_DEVICE_NONE) { 3588 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA"); 3589 } 3590 } break; 3591 3592 default: 3593 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy); 3594 break; 3595 } 3596 3597 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device); 3598 return device; 3599} 3600 3601void AudioPolicyManager::updateDevicesAndOutputs() 3602{ 3603 for (int i = 0; i < NUM_STRATEGIES; i++) { 3604 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/); 3605 } 3606 mPreviousOutputs = mOutputs; 3607} 3608 3609uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc, 3610 audio_devices_t prevDevice, 3611 uint32_t delayMs) 3612{ 3613 // mute/unmute strategies using an incompatible device combination 3614 // if muting, wait for the audio in pcm buffer to be drained before proceeding 3615 // if unmuting, unmute only after the specified delay 3616 if (outputDesc->isDuplicated()) { 3617 return 0; 3618 } 3619 3620 uint32_t muteWaitMs = 0; 3621 audio_devices_t device = outputDesc->device(); 3622 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2); 3623 3624 for (size_t i = 0; i < NUM_STRATEGIES; i++) { 3625 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/); 3626 bool mute = shouldMute && (curDevice & device) && (curDevice != device); 3627 bool doMute = false; 3628 3629 if (mute && !outputDesc->mStrategyMutedByDevice[i]) { 3630 doMute = true; 3631 outputDesc->mStrategyMutedByDevice[i] = true; 3632 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){ 3633 doMute = true; 3634 outputDesc->mStrategyMutedByDevice[i] = false; 3635 } 3636 if (doMute) { 3637 for (size_t j = 0; j < mOutputs.size(); j++) { 3638 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j); 3639 // skip output if it does not share any device with current output 3640 if ((desc->supportedDevices() & outputDesc->supportedDevices()) 3641 == AUDIO_DEVICE_NONE) { 3642 continue; 3643 } 3644 audio_io_handle_t curOutput = mOutputs.keyAt(j); 3645 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d", 3646 mute ? "muting" : "unmuting", i, curDevice, curOutput); 3647 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs); 3648 if (desc->isStrategyActive((routing_strategy)i)) { 3649 if (mute) { 3650 // FIXME: should not need to double latency if volume could be applied 3651 // immediately by the audioflinger mixer. We must account for the delay 3652 // between now and the next time the audioflinger thread for this output 3653 // will process a buffer (which corresponds to one buffer size, 3654 // usually 1/2 or 1/4 of the latency). 3655 if (muteWaitMs < desc->latency() * 2) { 3656 muteWaitMs = desc->latency() * 2; 3657 } 3658 } 3659 } 3660 } 3661 } 3662 } 3663 3664 // temporary mute output if device selection changes to avoid volume bursts due to 3665 // different per device volumes 3666 if (outputDesc->isActive() && (device != prevDevice)) { 3667 if (muteWaitMs < outputDesc->latency() * 2) { 3668 muteWaitMs = outputDesc->latency() * 2; 3669 } 3670 for (size_t i = 0; i < NUM_STRATEGIES; i++) { 3671 if (outputDesc->isStrategyActive((routing_strategy)i)) { 3672 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle); 3673 // do tempMute unmute after twice the mute wait time 3674 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle, 3675 muteWaitMs *2, device); 3676 } 3677 } 3678 } 3679 3680 // wait for the PCM output buffers to empty before proceeding with the rest of the command 3681 if (muteWaitMs > delayMs) { 3682 muteWaitMs -= delayMs; 3683 usleep(muteWaitMs * 1000); 3684 return muteWaitMs; 3685 } 3686 return 0; 3687} 3688 3689uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output, 3690 audio_devices_t device, 3691 bool force, 3692 int delayMs, 3693 audio_patch_handle_t *patchHandle) 3694{ 3695 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs); 3696 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 3697 AudioParameter param; 3698 uint32_t muteWaitMs; 3699 3700 if (outputDesc->isDuplicated()) { 3701 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs); 3702 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs); 3703 return muteWaitMs; 3704 } 3705 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current 3706 // output profile 3707 if ((device != AUDIO_DEVICE_NONE) && 3708 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) { 3709 return 0; 3710 } 3711 3712 // filter devices according to output selected 3713 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types()); 3714 3715 audio_devices_t prevDevice = outputDesc->mDevice; 3716 3717 ALOGV("setOutputDevice() prevDevice %04x", prevDevice); 3718 3719 if (device != AUDIO_DEVICE_NONE) { 3720 outputDesc->mDevice = device; 3721 } 3722 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs); 3723 3724 // Do not change the routing if: 3725 // - the requested device is AUDIO_DEVICE_NONE 3726 // - the requested device is the same as current device and force is not specified. 3727 // Doing this check here allows the caller to call setOutputDevice() without conditions 3728 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) { 3729 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output); 3730 return muteWaitMs; 3731 } 3732 3733 ALOGV("setOutputDevice() changing device"); 3734 3735 // do the routing 3736 if (device == AUDIO_DEVICE_NONE) { 3737 resetOutputDevice(output, delayMs, NULL); 3738 } else { 3739 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device); 3740 if (!deviceList.isEmpty()) { 3741 struct audio_patch patch; 3742 outputDesc->toAudioPortConfig(&patch.sources[0]); 3743 patch.num_sources = 1; 3744 patch.num_sinks = 0; 3745 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) { 3746 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]); 3747 patch.num_sinks++; 3748 } 3749 ssize_t index; 3750 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) { 3751 index = mAudioPatches.indexOfKey(*patchHandle); 3752 } else { 3753 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle); 3754 } 3755 sp< AudioPatch> patchDesc; 3756 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 3757 if (index >= 0) { 3758 patchDesc = mAudioPatches.valueAt(index); 3759 afPatchHandle = patchDesc->mAfPatchHandle; 3760 } 3761 3762 status_t status = mpClientInterface->createAudioPatch(&patch, 3763 &afPatchHandle, 3764 delayMs); 3765 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d" 3766 "num_sources %d num_sinks %d", 3767 status, afPatchHandle, patch.num_sources, patch.num_sinks); 3768 if (status == NO_ERROR) { 3769 if (index < 0) { 3770 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(), 3771 &patch, mUidCached); 3772 addAudioPatch(patchDesc->mHandle, patchDesc); 3773 } else { 3774 patchDesc->mPatch = patch; 3775 } 3776 patchDesc->mAfPatchHandle = afPatchHandle; 3777 patchDesc->mUid = mUidCached; 3778 if (patchHandle) { 3779 *patchHandle = patchDesc->mHandle; 3780 } 3781 outputDesc->mPatchHandle = patchDesc->mHandle; 3782 nextAudioPortGeneration(); 3783 mpClientInterface->onAudioPatchListUpdate(); 3784 } 3785 } 3786 } 3787 3788 // update stream volumes according to new device 3789 applyStreamVolumes(output, device, delayMs); 3790 3791 return muteWaitMs; 3792} 3793 3794status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output, 3795 int delayMs, 3796 audio_patch_handle_t *patchHandle) 3797{ 3798 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 3799 ssize_t index; 3800 if (patchHandle) { 3801 index = mAudioPatches.indexOfKey(*patchHandle); 3802 } else { 3803 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle); 3804 } 3805 if (index < 0) { 3806 return INVALID_OPERATION; 3807 } 3808 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index); 3809 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs); 3810 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status); 3811 outputDesc->mPatchHandle = 0; 3812 removeAudioPatch(patchDesc->mHandle); 3813 nextAudioPortGeneration(); 3814 mpClientInterface->onAudioPatchListUpdate(); 3815 return status; 3816} 3817 3818status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input, 3819 audio_devices_t device, 3820 bool force, 3821 audio_patch_handle_t *patchHandle) 3822{ 3823 status_t status = NO_ERROR; 3824 3825 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input); 3826 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) { 3827 inputDesc->mDevice = device; 3828 3829 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device); 3830 if (!deviceList.isEmpty()) { 3831 struct audio_patch patch; 3832 inputDesc->toAudioPortConfig(&patch.sinks[0]); 3833 patch.num_sinks = 1; 3834 //only one input device for now 3835 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]); 3836 patch.num_sources = 1; 3837 ssize_t index; 3838 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) { 3839 index = mAudioPatches.indexOfKey(*patchHandle); 3840 } else { 3841 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle); 3842 } 3843 sp< AudioPatch> patchDesc; 3844 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 3845 if (index >= 0) { 3846 patchDesc = mAudioPatches.valueAt(index); 3847 afPatchHandle = patchDesc->mAfPatchHandle; 3848 } 3849 3850 status_t status = mpClientInterface->createAudioPatch(&patch, 3851 &afPatchHandle, 3852 0); 3853 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d", 3854 status, afPatchHandle); 3855 if (status == NO_ERROR) { 3856 if (index < 0) { 3857 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(), 3858 &patch, mUidCached); 3859 addAudioPatch(patchDesc->mHandle, patchDesc); 3860 } else { 3861 patchDesc->mPatch = patch; 3862 } 3863 patchDesc->mAfPatchHandle = afPatchHandle; 3864 patchDesc->mUid = mUidCached; 3865 if (patchHandle) { 3866 *patchHandle = patchDesc->mHandle; 3867 } 3868 inputDesc->mPatchHandle = patchDesc->mHandle; 3869 nextAudioPortGeneration(); 3870 mpClientInterface->onAudioPatchListUpdate(); 3871 } 3872 } 3873 } 3874 return status; 3875} 3876 3877status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input, 3878 audio_patch_handle_t *patchHandle) 3879{ 3880 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input); 3881 ssize_t index; 3882 if (patchHandle) { 3883 index = mAudioPatches.indexOfKey(*patchHandle); 3884 } else { 3885 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle); 3886 } 3887 if (index < 0) { 3888 return INVALID_OPERATION; 3889 } 3890 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index); 3891 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 3892 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status); 3893 inputDesc->mPatchHandle = 0; 3894 removeAudioPatch(patchDesc->mHandle); 3895 nextAudioPortGeneration(); 3896 mpClientInterface->onAudioPatchListUpdate(); 3897 return status; 3898} 3899 3900sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device, 3901 uint32_t samplingRate, 3902 audio_format_t format, 3903 audio_channel_mask_t channelMask) 3904{ 3905 // Choose an input profile based on the requested capture parameters: select the first available 3906 // profile supporting all requested parameters. 3907 3908 for (size_t i = 0; i < mHwModules.size(); i++) 3909 { 3910 if (mHwModules[i]->mHandle == 0) { 3911 continue; 3912 } 3913 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) 3914 { 3915 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j]; 3916 // profile->log(); 3917 if (profile->isCompatibleProfile(device, samplingRate, format, 3918 channelMask, AUDIO_OUTPUT_FLAG_NONE)) { 3919 return profile; 3920 } 3921 } 3922 } 3923 return NULL; 3924} 3925 3926audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource) 3927{ 3928 uint32_t device = AUDIO_DEVICE_NONE; 3929 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & 3930 ~AUDIO_DEVICE_BIT_IN; 3931 switch (inputSource) { 3932 case AUDIO_SOURCE_VOICE_UPLINK: 3933 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) { 3934 device = AUDIO_DEVICE_IN_VOICE_CALL; 3935 break; 3936 } 3937 // FALL THROUGH 3938 3939 case AUDIO_SOURCE_DEFAULT: 3940 case AUDIO_SOURCE_MIC: 3941 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) { 3942 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP; 3943 break; 3944 } 3945 // FALL THROUGH 3946 3947 case AUDIO_SOURCE_VOICE_RECOGNITION: 3948 case AUDIO_SOURCE_HOTWORD: 3949 case AUDIO_SOURCE_VOICE_COMMUNICATION: 3950 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO && 3951 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) { 3952 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET; 3953 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) { 3954 device = AUDIO_DEVICE_IN_WIRED_HEADSET; 3955 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) { 3956 device = AUDIO_DEVICE_IN_USB_DEVICE; 3957 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) { 3958 device = AUDIO_DEVICE_IN_BUILTIN_MIC; 3959 } 3960 break; 3961 case AUDIO_SOURCE_CAMCORDER: 3962 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) { 3963 device = AUDIO_DEVICE_IN_BACK_MIC; 3964 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) { 3965 device = AUDIO_DEVICE_IN_BUILTIN_MIC; 3966 } 3967 break; 3968 case AUDIO_SOURCE_VOICE_DOWNLINK: 3969 case AUDIO_SOURCE_VOICE_CALL: 3970 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) { 3971 device = AUDIO_DEVICE_IN_VOICE_CALL; 3972 } 3973 break; 3974 case AUDIO_SOURCE_REMOTE_SUBMIX: 3975 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) { 3976 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX; 3977 } 3978 break; 3979 default: 3980 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource); 3981 break; 3982 } 3983 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device); 3984 return device; 3985} 3986 3987bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device) 3988{ 3989 if ((device & AUDIO_DEVICE_BIT_IN) != 0) { 3990 device &= ~AUDIO_DEVICE_BIT_IN; 3991 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0)) 3992 return true; 3993 } 3994 return false; 3995} 3996 3997audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs) 3998{ 3999 for (size_t i = 0; i < mInputs.size(); i++) { 4000 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i); 4001 if ((input_descriptor->mRefCount > 0) 4002 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) { 4003 return mInputs.keyAt(i); 4004 } 4005 } 4006 return 0; 4007} 4008 4009 4010audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device) 4011{ 4012 if (device == AUDIO_DEVICE_NONE) { 4013 // this happens when forcing a route update and no track is active on an output. 4014 // In this case the returned category is not important. 4015 device = AUDIO_DEVICE_OUT_SPEAKER; 4016 } else if (popcount(device) > 1) { 4017 // Multiple device selection is either: 4018 // - speaker + one other device: give priority to speaker in this case. 4019 // - one A2DP device + another device: happens with duplicated output. In this case 4020 // retain the device on the A2DP output as the other must not correspond to an active 4021 // selection if not the speaker. 4022 if (device & AUDIO_DEVICE_OUT_SPEAKER) { 4023 device = AUDIO_DEVICE_OUT_SPEAKER; 4024 } else { 4025 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP); 4026 } 4027 } 4028 4029 ALOGW_IF(popcount(device) != 1, 4030 "getDeviceForVolume() invalid device combination: %08x", 4031 device); 4032 4033 return device; 4034} 4035 4036AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device) 4037{ 4038 switch(getDeviceForVolume(device)) { 4039 case AUDIO_DEVICE_OUT_EARPIECE: 4040 return DEVICE_CATEGORY_EARPIECE; 4041 case AUDIO_DEVICE_OUT_WIRED_HEADSET: 4042 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE: 4043 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO: 4044 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET: 4045 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP: 4046 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES: 4047 return DEVICE_CATEGORY_HEADSET; 4048 case AUDIO_DEVICE_OUT_SPEAKER: 4049 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT: 4050 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER: 4051 case AUDIO_DEVICE_OUT_AUX_DIGITAL: 4052 case AUDIO_DEVICE_OUT_USB_ACCESSORY: 4053 case AUDIO_DEVICE_OUT_USB_DEVICE: 4054 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX: 4055 default: 4056 return DEVICE_CATEGORY_SPEAKER; 4057 } 4058} 4059 4060float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc, 4061 int indexInUi) 4062{ 4063 device_category deviceCategory = getDeviceCategory(device); 4064 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory]; 4065 4066 // the volume index in the UI is relative to the min and max volume indices for this stream type 4067 int nbSteps = 1 + curve[VOLMAX].mIndex - 4068 curve[VOLMIN].mIndex; 4069 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) / 4070 (streamDesc.mIndexMax - streamDesc.mIndexMin); 4071 4072 // find what part of the curve this index volume belongs to, or if it's out of bounds 4073 int segment = 0; 4074 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds 4075 return 0.0f; 4076 } else if (volIdx < curve[VOLKNEE1].mIndex) { 4077 segment = 0; 4078 } else if (volIdx < curve[VOLKNEE2].mIndex) { 4079 segment = 1; 4080 } else if (volIdx <= curve[VOLMAX].mIndex) { 4081 segment = 2; 4082 } else { // out of bounds 4083 return 1.0f; 4084 } 4085 4086 // linear interpolation in the attenuation table in dB 4087 float decibels = curve[segment].mDBAttenuation + 4088 ((float)(volIdx - curve[segment].mIndex)) * 4089 ( (curve[segment+1].mDBAttenuation - 4090 curve[segment].mDBAttenuation) / 4091 ((float)(curve[segment+1].mIndex - 4092 curve[segment].mIndex)) ); 4093 4094 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 ) 4095 4096 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f", 4097 curve[segment].mIndex, volIdx, 4098 curve[segment+1].mIndex, 4099 curve[segment].mDBAttenuation, 4100 decibels, 4101 curve[segment+1].mDBAttenuation, 4102 amplification); 4103 4104 return amplification; 4105} 4106 4107const AudioPolicyManager::VolumeCurvePoint 4108 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = { 4109 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f} 4110}; 4111 4112const AudioPolicyManager::VolumeCurvePoint 4113 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = { 4114 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f} 4115}; 4116 4117const AudioPolicyManager::VolumeCurvePoint 4118 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = { 4119 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f} 4120}; 4121 4122const AudioPolicyManager::VolumeCurvePoint 4123 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = { 4124 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f} 4125}; 4126 4127const AudioPolicyManager::VolumeCurvePoint 4128 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = { 4129 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f} 4130}; 4131 4132const AudioPolicyManager::VolumeCurvePoint 4133 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = { 4134 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f} 4135}; 4136 4137// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks 4138// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets. 4139// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java). 4140// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset. 4141 4142const AudioPolicyManager::VolumeCurvePoint 4143 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = { 4144 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f} 4145}; 4146 4147const AudioPolicyManager::VolumeCurvePoint 4148 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = { 4149 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f} 4150}; 4151 4152const AudioPolicyManager::VolumeCurvePoint 4153 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = { 4154 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f} 4155}; 4156 4157const AudioPolicyManager::VolumeCurvePoint 4158 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = { 4159 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f} 4160}; 4161 4162const AudioPolicyManager::VolumeCurvePoint 4163 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = { 4164 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f} 4165}; 4166 4167const AudioPolicyManager::VolumeCurvePoint 4168 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT] 4169 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = { 4170 { // AUDIO_STREAM_VOICE_CALL 4171 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET 4172 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER 4173 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE 4174 }, 4175 { // AUDIO_STREAM_SYSTEM 4176 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET 4177 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER 4178 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE 4179 }, 4180 { // AUDIO_STREAM_RING 4181 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET 4182 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER 4183 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE 4184 }, 4185 { // AUDIO_STREAM_MUSIC 4186 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET 4187 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER 4188 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE 4189 }, 4190 { // AUDIO_STREAM_ALARM 4191 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET 4192 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER 4193 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE 4194 }, 4195 { // AUDIO_STREAM_NOTIFICATION 4196 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET 4197 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER 4198 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE 4199 }, 4200 { // AUDIO_STREAM_BLUETOOTH_SCO 4201 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET 4202 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER 4203 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE 4204 }, 4205 { // AUDIO_STREAM_ENFORCED_AUDIBLE 4206 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET 4207 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER 4208 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE 4209 }, 4210 { // AUDIO_STREAM_DTMF 4211 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET 4212 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER 4213 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE 4214 }, 4215 { // AUDIO_STREAM_TTS 4216 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET 4217 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER 4218 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE 4219 }, 4220}; 4221 4222void AudioPolicyManager::initializeVolumeCurves() 4223{ 4224 for (int i = 0; i < AUDIO_STREAM_CNT; i++) { 4225 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) { 4226 mStreams[i].mVolumeCurve[j] = 4227 sVolumeProfiles[i][j]; 4228 } 4229 } 4230 4231 // Check availability of DRC on speaker path: if available, override some of the speaker curves 4232 if (mSpeakerDrcEnabled) { 4233 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] = 4234 sDefaultSystemVolumeCurveDrc; 4235 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] = 4236 sSpeakerSonificationVolumeCurveDrc; 4237 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] = 4238 sSpeakerSonificationVolumeCurveDrc; 4239 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] = 4240 sSpeakerSonificationVolumeCurveDrc; 4241 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] = 4242 sSpeakerMediaVolumeCurveDrc; 4243 } 4244} 4245 4246float AudioPolicyManager::computeVolume(audio_stream_type_t stream, 4247 int index, 4248 audio_io_handle_t output, 4249 audio_devices_t device) 4250{ 4251 float volume = 1.0; 4252 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 4253 StreamDescriptor &streamDesc = mStreams[stream]; 4254 4255 if (device == AUDIO_DEVICE_NONE) { 4256 device = outputDesc->device(); 4257 } 4258 4259 // if volume is not 0 (not muted), force media volume to max on digital output 4260 if (stream == AUDIO_STREAM_MUSIC && 4261 index != mStreams[stream].mIndexMin && 4262 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL || 4263 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET)) { 4264 return 1.0; 4265 } 4266 4267 volume = volIndexToAmpl(device, streamDesc, index); 4268 4269 // if a headset is connected, apply the following rules to ring tones and notifications 4270 // to avoid sound level bursts in user's ears: 4271 // - always attenuate ring tones and notifications volume by 6dB 4272 // - if music is playing, always limit the volume to current music volume, 4273 // with a minimum threshold at -36dB so that notification is always perceived. 4274 const routing_strategy stream_strategy = getStrategy(stream); 4275 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP | 4276 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES | 4277 AUDIO_DEVICE_OUT_WIRED_HEADSET | 4278 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) && 4279 ((stream_strategy == STRATEGY_SONIFICATION) 4280 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL) 4281 || (stream == AUDIO_STREAM_SYSTEM) 4282 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) && 4283 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) && 4284 streamDesc.mCanBeMuted) { 4285 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR; 4286 // when the phone is ringing we must consider that music could have been paused just before 4287 // by the music application and behave as if music was active if the last music track was 4288 // just stopped 4289 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) || 4290 mLimitRingtoneVolume) { 4291 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/); 4292 float musicVol = computeVolume(AUDIO_STREAM_MUSIC, 4293 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice), 4294 output, 4295 musicDevice); 4296 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? 4297 musicVol : SONIFICATION_HEADSET_VOLUME_MIN; 4298 if (volume > minVol) { 4299 volume = minVol; 4300 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol); 4301 } 4302 } 4303 } 4304 4305 return volume; 4306} 4307 4308status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream, 4309 int index, 4310 audio_io_handle_t output, 4311 audio_devices_t device, 4312 int delayMs, 4313 bool force) 4314{ 4315 4316 // do not change actual stream volume if the stream is muted 4317 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) { 4318 ALOGVV("checkAndSetVolume() stream %d muted count %d", 4319 stream, mOutputs.valueFor(output)->mMuteCount[stream]); 4320 return NO_ERROR; 4321 } 4322 4323 // do not change in call volume if bluetooth is connected and vice versa 4324 if ((stream == AUDIO_STREAM_VOICE_CALL && 4325 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) || 4326 (stream == AUDIO_STREAM_BLUETOOTH_SCO && 4327 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) { 4328 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm", 4329 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]); 4330 return INVALID_OPERATION; 4331 } 4332 4333 float volume = computeVolume(stream, index, output, device); 4334 // We actually change the volume if: 4335 // - the float value returned by computeVolume() changed 4336 // - the force flag is set 4337 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] || 4338 force) { 4339 mOutputs.valueFor(output)->mCurVolume[stream] = volume; 4340 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs); 4341 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is 4342 // enabled 4343 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) { 4344 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs); 4345 } 4346 mpClientInterface->setStreamVolume(stream, volume, output, delayMs); 4347 } 4348 4349 if (stream == AUDIO_STREAM_VOICE_CALL || 4350 stream == AUDIO_STREAM_BLUETOOTH_SCO) { 4351 float voiceVolume; 4352 // Force voice volume to max for bluetooth SCO as volume is managed by the headset 4353 if (stream == AUDIO_STREAM_VOICE_CALL) { 4354 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax; 4355 } else { 4356 voiceVolume = 1.0; 4357 } 4358 4359 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) { 4360 mpClientInterface->setVoiceVolume(voiceVolume, delayMs); 4361 mLastVoiceVolume = voiceVolume; 4362 } 4363 } 4364 4365 return NO_ERROR; 4366} 4367 4368void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output, 4369 audio_devices_t device, 4370 int delayMs, 4371 bool force) 4372{ 4373 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device); 4374 4375 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) { 4376 checkAndSetVolume((audio_stream_type_t)stream, 4377 mStreams[stream].getVolumeIndex(device), 4378 output, 4379 device, 4380 delayMs, 4381 force); 4382 } 4383} 4384 4385void AudioPolicyManager::setStrategyMute(routing_strategy strategy, 4386 bool on, 4387 audio_io_handle_t output, 4388 int delayMs, 4389 audio_devices_t device) 4390{ 4391 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output); 4392 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) { 4393 if (getStrategy((audio_stream_type_t)stream) == strategy) { 4394 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device); 4395 } 4396 } 4397} 4398 4399void AudioPolicyManager::setStreamMute(audio_stream_type_t stream, 4400 bool on, 4401 audio_io_handle_t output, 4402 int delayMs, 4403 audio_devices_t device) 4404{ 4405 StreamDescriptor &streamDesc = mStreams[stream]; 4406 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 4407 if (device == AUDIO_DEVICE_NONE) { 4408 device = outputDesc->device(); 4409 } 4410 4411 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x", 4412 stream, on, output, outputDesc->mMuteCount[stream], device); 4413 4414 if (on) { 4415 if (outputDesc->mMuteCount[stream] == 0) { 4416 if (streamDesc.mCanBeMuted && 4417 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) || 4418 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) { 4419 checkAndSetVolume(stream, 0, output, device, delayMs); 4420 } 4421 } 4422 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored 4423 outputDesc->mMuteCount[stream]++; 4424 } else { 4425 if (outputDesc->mMuteCount[stream] == 0) { 4426 ALOGV("setStreamMute() unmuting non muted stream!"); 4427 return; 4428 } 4429 if (--outputDesc->mMuteCount[stream] == 0) { 4430 checkAndSetVolume(stream, 4431 streamDesc.getVolumeIndex(device), 4432 output, 4433 device, 4434 delayMs); 4435 } 4436 } 4437} 4438 4439void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream, 4440 bool starting, bool stateChange) 4441{ 4442 // if the stream pertains to sonification strategy and we are in call we must 4443 // mute the stream if it is low visibility. If it is high visibility, we must play a tone 4444 // in the device used for phone strategy and play the tone if the selected device does not 4445 // interfere with the device used for phone strategy 4446 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as 4447 // many times as there are active tracks on the output 4448 const routing_strategy stream_strategy = getStrategy(stream); 4449 if ((stream_strategy == STRATEGY_SONIFICATION) || 4450 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) { 4451 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput); 4452 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d", 4453 stream, starting, outputDesc->mDevice, stateChange); 4454 if (outputDesc->mRefCount[stream]) { 4455 int muteCount = 1; 4456 if (stateChange) { 4457 muteCount = outputDesc->mRefCount[stream]; 4458 } 4459 if (audio_is_low_visibility(stream)) { 4460 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount); 4461 for (int i = 0; i < muteCount; i++) { 4462 setStreamMute(stream, starting, mPrimaryOutput); 4463 } 4464 } else { 4465 ALOGV("handleIncallSonification() high visibility"); 4466 if (outputDesc->device() & 4467 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) { 4468 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount); 4469 for (int i = 0; i < muteCount; i++) { 4470 setStreamMute(stream, starting, mPrimaryOutput); 4471 } 4472 } 4473 if (starting) { 4474 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION, 4475 AUDIO_STREAM_VOICE_CALL); 4476 } else { 4477 mpClientInterface->stopTone(); 4478 } 4479 } 4480 } 4481 } 4482} 4483 4484bool AudioPolicyManager::isInCall() 4485{ 4486 return isStateInCall(mPhoneState); 4487} 4488 4489bool AudioPolicyManager::isStateInCall(int state) { 4490 return ((state == AUDIO_MODE_IN_CALL) || 4491 (state == AUDIO_MODE_IN_COMMUNICATION)); 4492} 4493 4494uint32_t AudioPolicyManager::getMaxEffectsCpuLoad() 4495{ 4496 return MAX_EFFECTS_CPU_LOAD; 4497} 4498 4499uint32_t AudioPolicyManager::getMaxEffectsMemory() 4500{ 4501 return MAX_EFFECTS_MEMORY; 4502} 4503 4504 4505// --- AudioOutputDescriptor class implementation 4506 4507AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor( 4508 const sp<IOProfile>& profile) 4509 : mId(0), mIoHandle(0), mLatency(0), 4510 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), 4511 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0) 4512{ 4513 // clear usage count for all stream types 4514 for (int i = 0; i < AUDIO_STREAM_CNT; i++) { 4515 mRefCount[i] = 0; 4516 mCurVolume[i] = -1.0; 4517 mMuteCount[i] = 0; 4518 mStopTime[i] = 0; 4519 } 4520 for (int i = 0; i < NUM_STRATEGIES; i++) { 4521 mStrategyMutedByDevice[i] = false; 4522 } 4523 if (profile != NULL) { 4524 mAudioPort = profile; 4525 mSamplingRate = profile->pickSamplingRate(); 4526 mFormat = profile->pickFormat(); 4527 mChannelMask = profile->pickChannelMask(); 4528 if (profile->mGains.size() > 0) { 4529 profile->mGains[0]->getDefaultConfig(&mGain); 4530 } 4531 mFlags = profile->mFlags; 4532 } 4533} 4534 4535audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const 4536{ 4537 if (isDuplicated()) { 4538 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice); 4539 } else { 4540 return mDevice; 4541 } 4542} 4543 4544uint32_t AudioPolicyManager::AudioOutputDescriptor::latency() 4545{ 4546 if (isDuplicated()) { 4547 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency; 4548 } else { 4549 return mLatency; 4550 } 4551} 4552 4553bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith( 4554 const sp<AudioOutputDescriptor> outputDesc) 4555{ 4556 if (isDuplicated()) { 4557 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc); 4558 } else if (outputDesc->isDuplicated()){ 4559 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2); 4560 } else { 4561 return (mProfile->mModule == outputDesc->mProfile->mModule); 4562 } 4563} 4564 4565void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream, 4566 int delta) 4567{ 4568 // forward usage count change to attached outputs 4569 if (isDuplicated()) { 4570 mOutput1->changeRefCount(stream, delta); 4571 mOutput2->changeRefCount(stream, delta); 4572 } 4573 if ((delta + (int)mRefCount[stream]) < 0) { 4574 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", 4575 delta, stream, mRefCount[stream]); 4576 mRefCount[stream] = 0; 4577 return; 4578 } 4579 mRefCount[stream] += delta; 4580 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]); 4581} 4582 4583audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices() 4584{ 4585 if (isDuplicated()) { 4586 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices()); 4587 } else { 4588 return mProfile->mSupportedDevices.types() ; 4589 } 4590} 4591 4592bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const 4593{ 4594 return isStrategyActive(NUM_STRATEGIES, inPastMs); 4595} 4596 4597bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy, 4598 uint32_t inPastMs, 4599 nsecs_t sysTime) const 4600{ 4601 if ((sysTime == 0) && (inPastMs != 0)) { 4602 sysTime = systemTime(); 4603 } 4604 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) { 4605 if (((getStrategy((audio_stream_type_t)i) == strategy) || 4606 (NUM_STRATEGIES == strategy)) && 4607 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) { 4608 return true; 4609 } 4610 } 4611 return false; 4612} 4613 4614bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream, 4615 uint32_t inPastMs, 4616 nsecs_t sysTime) const 4617{ 4618 if (mRefCount[stream] != 0) { 4619 return true; 4620 } 4621 if (inPastMs == 0) { 4622 return false; 4623 } 4624 if (sysTime == 0) { 4625 sysTime = systemTime(); 4626 } 4627 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) { 4628 return true; 4629 } 4630 return false; 4631} 4632 4633void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig( 4634 struct audio_port_config *dstConfig, 4635 const struct audio_port_config *srcConfig) const 4636{ 4637 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle); 4638 4639 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK| 4640 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN; 4641 if (srcConfig != NULL) { 4642 dstConfig->config_mask |= srcConfig->config_mask; 4643 } 4644 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig); 4645 4646 dstConfig->id = mId; 4647 dstConfig->role = AUDIO_PORT_ROLE_SOURCE; 4648 dstConfig->type = AUDIO_PORT_TYPE_MIX; 4649 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle; 4650 dstConfig->ext.mix.handle = mIoHandle; 4651 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT; 4652} 4653 4654void AudioPolicyManager::AudioOutputDescriptor::toAudioPort( 4655 struct audio_port *port) const 4656{ 4657 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle); 4658 mProfile->toAudioPort(port); 4659 port->id = mId; 4660 toAudioPortConfig(&port->active_config); 4661 port->ext.mix.hw_module = mProfile->mModule->mHandle; 4662 port->ext.mix.handle = mIoHandle; 4663 port->ext.mix.latency_class = 4664 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL; 4665} 4666 4667status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd) 4668{ 4669 const size_t SIZE = 256; 4670 char buffer[SIZE]; 4671 String8 result; 4672 4673 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate); 4674 result.append(buffer); 4675 snprintf(buffer, SIZE, " Format: %08x\n", mFormat); 4676 result.append(buffer); 4677 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask); 4678 result.append(buffer); 4679 snprintf(buffer, SIZE, " Latency: %d\n", mLatency); 4680 result.append(buffer); 4681 snprintf(buffer, SIZE, " Flags %08x\n", mFlags); 4682 result.append(buffer); 4683 snprintf(buffer, SIZE, " Devices %08x\n", device()); 4684 result.append(buffer); 4685 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n"); 4686 result.append(buffer); 4687 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) { 4688 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", 4689 i, mCurVolume[i], mRefCount[i], mMuteCount[i]); 4690 result.append(buffer); 4691 } 4692 write(fd, result.string(), result.size()); 4693 4694 return NO_ERROR; 4695} 4696 4697// --- AudioInputDescriptor class implementation 4698 4699AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile) 4700 : mId(0), mIoHandle(0), 4701 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0), 4702 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile) 4703{ 4704 if (profile != NULL) { 4705 mAudioPort = profile; 4706 mSamplingRate = profile->pickSamplingRate(); 4707 mFormat = profile->pickFormat(); 4708 mChannelMask = profile->pickChannelMask(); 4709 if (profile->mGains.size() > 0) { 4710 profile->mGains[0]->getDefaultConfig(&mGain); 4711 } 4712 } 4713} 4714 4715void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig( 4716 struct audio_port_config *dstConfig, 4717 const struct audio_port_config *srcConfig) const 4718{ 4719 ALOG_ASSERT(mProfile != 0, 4720 "toAudioPortConfig() called on input with null profile %d", mIoHandle); 4721 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK| 4722 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN; 4723 if (srcConfig != NULL) { 4724 dstConfig->config_mask |= srcConfig->config_mask; 4725 } 4726 4727 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig); 4728 4729 dstConfig->id = mId; 4730 dstConfig->role = AUDIO_PORT_ROLE_SINK; 4731 dstConfig->type = AUDIO_PORT_TYPE_MIX; 4732 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle; 4733 dstConfig->ext.mix.handle = mIoHandle; 4734 dstConfig->ext.mix.usecase.source = mInputSource; 4735} 4736 4737void AudioPolicyManager::AudioInputDescriptor::toAudioPort( 4738 struct audio_port *port) const 4739{ 4740 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle); 4741 4742 mProfile->toAudioPort(port); 4743 port->id = mId; 4744 toAudioPortConfig(&port->active_config); 4745 port->ext.mix.hw_module = mProfile->mModule->mHandle; 4746 port->ext.mix.handle = mIoHandle; 4747 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL; 4748} 4749 4750status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd) 4751{ 4752 const size_t SIZE = 256; 4753 char buffer[SIZE]; 4754 String8 result; 4755 4756 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate); 4757 result.append(buffer); 4758 snprintf(buffer, SIZE, " Format: %d\n", mFormat); 4759 result.append(buffer); 4760 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask); 4761 result.append(buffer); 4762 snprintf(buffer, SIZE, " Devices %08x\n", mDevice); 4763 result.append(buffer); 4764 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount); 4765 result.append(buffer); 4766 write(fd, result.string(), result.size()); 4767 4768 return NO_ERROR; 4769} 4770 4771// --- StreamDescriptor class implementation 4772 4773AudioPolicyManager::StreamDescriptor::StreamDescriptor() 4774 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true) 4775{ 4776 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0); 4777} 4778 4779int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device) 4780{ 4781 device = AudioPolicyManager::getDeviceForVolume(device); 4782 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT 4783 if (mIndexCur.indexOfKey(device) < 0) { 4784 device = AUDIO_DEVICE_OUT_DEFAULT; 4785 } 4786 return mIndexCur.valueFor(device); 4787} 4788 4789void AudioPolicyManager::StreamDescriptor::dump(int fd) 4790{ 4791 const size_t SIZE = 256; 4792 char buffer[SIZE]; 4793 String8 result; 4794 4795 snprintf(buffer, SIZE, "%s %02d %02d ", 4796 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax); 4797 result.append(buffer); 4798 for (size_t i = 0; i < mIndexCur.size(); i++) { 4799 snprintf(buffer, SIZE, "%04x : %02d, ", 4800 mIndexCur.keyAt(i), 4801 mIndexCur.valueAt(i)); 4802 result.append(buffer); 4803 } 4804 result.append("\n"); 4805 4806 write(fd, result.string(), result.size()); 4807} 4808 4809// --- EffectDescriptor class implementation 4810 4811status_t AudioPolicyManager::EffectDescriptor::dump(int fd) 4812{ 4813 const size_t SIZE = 256; 4814 char buffer[SIZE]; 4815 String8 result; 4816 4817 snprintf(buffer, SIZE, " I/O: %d\n", mIo); 4818 result.append(buffer); 4819 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy); 4820 result.append(buffer); 4821 snprintf(buffer, SIZE, " Session: %d\n", mSession); 4822 result.append(buffer); 4823 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name); 4824 result.append(buffer); 4825 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled"); 4826 result.append(buffer); 4827 write(fd, result.string(), result.size()); 4828 4829 return NO_ERROR; 4830} 4831 4832// --- HwModule class implementation 4833 4834AudioPolicyManager::HwModule::HwModule(const char *name) 4835 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), 4836 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0) 4837{ 4838} 4839 4840AudioPolicyManager::HwModule::~HwModule() 4841{ 4842 for (size_t i = 0; i < mOutputProfiles.size(); i++) { 4843 mOutputProfiles[i]->mSupportedDevices.clear(); 4844 } 4845 for (size_t i = 0; i < mInputProfiles.size(); i++) { 4846 mInputProfiles[i]->mSupportedDevices.clear(); 4847 } 4848 free((void *)mName); 4849} 4850 4851status_t AudioPolicyManager::HwModule::loadInput(cnode *root) 4852{ 4853 cnode *node = root->first_child; 4854 4855 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this); 4856 4857 while (node) { 4858 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) { 4859 profile->loadSamplingRates((char *)node->value); 4860 } else if (strcmp(node->name, FORMATS_TAG) == 0) { 4861 profile->loadFormats((char *)node->value); 4862 } else if (strcmp(node->name, CHANNELS_TAG) == 0) { 4863 profile->loadInChannels((char *)node->value); 4864 } else if (strcmp(node->name, DEVICES_TAG) == 0) { 4865 profile->mSupportedDevices.loadDevicesFromName((char *)node->value, 4866 mDeclaredDevices); 4867 } else if (strcmp(node->name, GAINS_TAG) == 0) { 4868 profile->loadGains(node); 4869 } 4870 node = node->next; 4871 } 4872 ALOGW_IF(profile->mSupportedDevices.isEmpty(), 4873 "loadInput() invalid supported devices"); 4874 ALOGW_IF(profile->mChannelMasks.size() == 0, 4875 "loadInput() invalid supported channel masks"); 4876 ALOGW_IF(profile->mSamplingRates.size() == 0, 4877 "loadInput() invalid supported sampling rates"); 4878 ALOGW_IF(profile->mFormats.size() == 0, 4879 "loadInput() invalid supported formats"); 4880 if (!profile->mSupportedDevices.isEmpty() && 4881 (profile->mChannelMasks.size() != 0) && 4882 (profile->mSamplingRates.size() != 0) && 4883 (profile->mFormats.size() != 0)) { 4884 4885 ALOGV("loadInput() adding input Supported Devices %04x", 4886 profile->mSupportedDevices.types()); 4887 4888 mInputProfiles.add(profile); 4889 return NO_ERROR; 4890 } else { 4891 return BAD_VALUE; 4892 } 4893} 4894 4895status_t AudioPolicyManager::HwModule::loadOutput(cnode *root) 4896{ 4897 cnode *node = root->first_child; 4898 4899 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this); 4900 4901 while (node) { 4902 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) { 4903 profile->loadSamplingRates((char *)node->value); 4904 } else if (strcmp(node->name, FORMATS_TAG) == 0) { 4905 profile->loadFormats((char *)node->value); 4906 } else if (strcmp(node->name, CHANNELS_TAG) == 0) { 4907 profile->loadOutChannels((char *)node->value); 4908 } else if (strcmp(node->name, DEVICES_TAG) == 0) { 4909 profile->mSupportedDevices.loadDevicesFromName((char *)node->value, 4910 mDeclaredDevices); 4911 } else if (strcmp(node->name, FLAGS_TAG) == 0) { 4912 profile->mFlags = parseFlagNames((char *)node->value); 4913 } else if (strcmp(node->name, GAINS_TAG) == 0) { 4914 profile->loadGains(node); 4915 } 4916 node = node->next; 4917 } 4918 ALOGW_IF(profile->mSupportedDevices.isEmpty(), 4919 "loadOutput() invalid supported devices"); 4920 ALOGW_IF(profile->mChannelMasks.size() == 0, 4921 "loadOutput() invalid supported channel masks"); 4922 ALOGW_IF(profile->mSamplingRates.size() == 0, 4923 "loadOutput() invalid supported sampling rates"); 4924 ALOGW_IF(profile->mFormats.size() == 0, 4925 "loadOutput() invalid supported formats"); 4926 if (!profile->mSupportedDevices.isEmpty() && 4927 (profile->mChannelMasks.size() != 0) && 4928 (profile->mSamplingRates.size() != 0) && 4929 (profile->mFormats.size() != 0)) { 4930 4931 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x", 4932 profile->mSupportedDevices.types(), profile->mFlags); 4933 4934 mOutputProfiles.add(profile); 4935 return NO_ERROR; 4936 } else { 4937 return BAD_VALUE; 4938 } 4939} 4940 4941status_t AudioPolicyManager::HwModule::loadDevice(cnode *root) 4942{ 4943 cnode *node = root->first_child; 4944 4945 audio_devices_t type = AUDIO_DEVICE_NONE; 4946 while (node) { 4947 if (strcmp(node->name, DEVICE_TYPE) == 0) { 4948 type = parseDeviceNames((char *)node->value); 4949 break; 4950 } 4951 node = node->next; 4952 } 4953 if (type == AUDIO_DEVICE_NONE || 4954 (!audio_is_input_device(type) && !audio_is_output_device(type))) { 4955 ALOGW("loadDevice() bad type %08x", type); 4956 return BAD_VALUE; 4957 } 4958 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type); 4959 deviceDesc->mModule = this; 4960 4961 node = root->first_child; 4962 while (node) { 4963 if (strcmp(node->name, DEVICE_ADDRESS) == 0) { 4964 deviceDesc->mAddress = String8((char *)node->value); 4965 } else if (strcmp(node->name, CHANNELS_TAG) == 0) { 4966 if (audio_is_input_device(type)) { 4967 deviceDesc->loadInChannels((char *)node->value); 4968 } else { 4969 deviceDesc->loadOutChannels((char *)node->value); 4970 } 4971 } else if (strcmp(node->name, GAINS_TAG) == 0) { 4972 deviceDesc->loadGains(node); 4973 } 4974 node = node->next; 4975 } 4976 4977 ALOGV("loadDevice() adding device name %s type %08x address %s", 4978 deviceDesc->mName.string(), type, deviceDesc->mAddress.string()); 4979 4980 mDeclaredDevices.add(deviceDesc); 4981 4982 return NO_ERROR; 4983} 4984 4985void AudioPolicyManager::HwModule::dump(int fd) 4986{ 4987 const size_t SIZE = 256; 4988 char buffer[SIZE]; 4989 String8 result; 4990 4991 snprintf(buffer, SIZE, " - name: %s\n", mName); 4992 result.append(buffer); 4993 snprintf(buffer, SIZE, " - handle: %d\n", mHandle); 4994 result.append(buffer); 4995 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF); 4996 result.append(buffer); 4997 write(fd, result.string(), result.size()); 4998 if (mOutputProfiles.size()) { 4999 write(fd, " - outputs:\n", strlen(" - outputs:\n")); 5000 for (size_t i = 0; i < mOutputProfiles.size(); i++) { 5001 snprintf(buffer, SIZE, " output %zu:\n", i); 5002 write(fd, buffer, strlen(buffer)); 5003 mOutputProfiles[i]->dump(fd); 5004 } 5005 } 5006 if (mInputProfiles.size()) { 5007 write(fd, " - inputs:\n", strlen(" - inputs:\n")); 5008 for (size_t i = 0; i < mInputProfiles.size(); i++) { 5009 snprintf(buffer, SIZE, " input %zu:\n", i); 5010 write(fd, buffer, strlen(buffer)); 5011 mInputProfiles[i]->dump(fd); 5012 } 5013 } 5014 if (mDeclaredDevices.size()) { 5015 write(fd, " - devices:\n", strlen(" - devices:\n")); 5016 for (size_t i = 0; i < mDeclaredDevices.size(); i++) { 5017 mDeclaredDevices[i]->dump(fd, 4, i); 5018 } 5019 } 5020} 5021 5022// --- AudioPort class implementation 5023 5024 5025AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type, 5026 audio_port_role_t role, const sp<HwModule>& module) : 5027 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0) 5028{ 5029 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) || 5030 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK)); 5031} 5032 5033void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const 5034{ 5035 port->role = mRole; 5036 port->type = mType; 5037 unsigned int i; 5038 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) { 5039 port->sample_rates[i] = mSamplingRates[i]; 5040 } 5041 port->num_sample_rates = i; 5042 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) { 5043 port->channel_masks[i] = mChannelMasks[i]; 5044 } 5045 port->num_channel_masks = i; 5046 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) { 5047 port->formats[i] = mFormats[i]; 5048 } 5049 port->num_formats = i; 5050 5051 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size()); 5052 5053 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) { 5054 port->gains[i] = mGains[i]->mGain; 5055 } 5056 port->num_gains = i; 5057} 5058 5059 5060void AudioPolicyManager::AudioPort::loadSamplingRates(char *name) 5061{ 5062 char *str = strtok(name, "|"); 5063 5064 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling 5065 // rates should be read from the output stream after it is opened for the first time 5066 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) { 5067 mSamplingRates.add(0); 5068 return; 5069 } 5070 5071 while (str != NULL) { 5072 uint32_t rate = atoi(str); 5073 if (rate != 0) { 5074 ALOGV("loadSamplingRates() adding rate %d", rate); 5075 mSamplingRates.add(rate); 5076 } 5077 str = strtok(NULL, "|"); 5078 } 5079} 5080 5081void AudioPolicyManager::AudioPort::loadFormats(char *name) 5082{ 5083 char *str = strtok(name, "|"); 5084 5085 // by convention, "0' in the first entry in mFormats indicates the supported formats 5086 // should be read from the output stream after it is opened for the first time 5087 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) { 5088 mFormats.add(AUDIO_FORMAT_DEFAULT); 5089 return; 5090 } 5091 5092 while (str != NULL) { 5093 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable, 5094 ARRAY_SIZE(sFormatNameToEnumTable), 5095 str); 5096 if (format != AUDIO_FORMAT_DEFAULT) { 5097 mFormats.add(format); 5098 } 5099 str = strtok(NULL, "|"); 5100 } 5101} 5102 5103void AudioPolicyManager::AudioPort::loadInChannels(char *name) 5104{ 5105 const char *str = strtok(name, "|"); 5106 5107 ALOGV("loadInChannels() %s", name); 5108 5109 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) { 5110 mChannelMasks.add(0); 5111 return; 5112 } 5113 5114 while (str != NULL) { 5115 audio_channel_mask_t channelMask = 5116 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable, 5117 ARRAY_SIZE(sInChannelsNameToEnumTable), 5118 str); 5119 if (channelMask != 0) { 5120 ALOGV("loadInChannels() adding channelMask %04x", channelMask); 5121 mChannelMasks.add(channelMask); 5122 } 5123 str = strtok(NULL, "|"); 5124 } 5125} 5126 5127void AudioPolicyManager::AudioPort::loadOutChannels(char *name) 5128{ 5129 const char *str = strtok(name, "|"); 5130 5131 ALOGV("loadOutChannels() %s", name); 5132 5133 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel 5134 // masks should be read from the output stream after it is opened for the first time 5135 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) { 5136 mChannelMasks.add(0); 5137 return; 5138 } 5139 5140 while (str != NULL) { 5141 audio_channel_mask_t channelMask = 5142 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable, 5143 ARRAY_SIZE(sOutChannelsNameToEnumTable), 5144 str); 5145 if (channelMask != 0) { 5146 mChannelMasks.add(channelMask); 5147 } 5148 str = strtok(NULL, "|"); 5149 } 5150 return; 5151} 5152 5153audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name) 5154{ 5155 const char *str = strtok(name, "|"); 5156 5157 ALOGV("loadGainMode() %s", name); 5158 audio_gain_mode_t mode = 0; 5159 while (str != NULL) { 5160 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable, 5161 ARRAY_SIZE(sGainModeNameToEnumTable), 5162 str); 5163 str = strtok(NULL, "|"); 5164 } 5165 return mode; 5166} 5167 5168void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index) 5169{ 5170 cnode *node = root->first_child; 5171 5172 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask); 5173 5174 while (node) { 5175 if (strcmp(node->name, GAIN_MODE) == 0) { 5176 gain->mGain.mode = loadGainMode((char *)node->value); 5177 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) { 5178 if (mUseInChannelMask) { 5179 gain->mGain.channel_mask = 5180 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable, 5181 ARRAY_SIZE(sInChannelsNameToEnumTable), 5182 (char *)node->value); 5183 } else { 5184 gain->mGain.channel_mask = 5185 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable, 5186 ARRAY_SIZE(sOutChannelsNameToEnumTable), 5187 (char *)node->value); 5188 } 5189 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) { 5190 gain->mGain.min_value = atoi((char *)node->value); 5191 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) { 5192 gain->mGain.max_value = atoi((char *)node->value); 5193 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) { 5194 gain->mGain.default_value = atoi((char *)node->value); 5195 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) { 5196 gain->mGain.step_value = atoi((char *)node->value); 5197 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) { 5198 gain->mGain.min_ramp_ms = atoi((char *)node->value); 5199 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) { 5200 gain->mGain.max_ramp_ms = atoi((char *)node->value); 5201 } 5202 node = node->next; 5203 } 5204 5205 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d", 5206 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value); 5207 5208 if (gain->mGain.mode == 0) { 5209 return; 5210 } 5211 mGains.add(gain); 5212} 5213 5214void AudioPolicyManager::AudioPort::loadGains(cnode *root) 5215{ 5216 cnode *node = root->first_child; 5217 int index = 0; 5218 while (node) { 5219 ALOGV("loadGains() loading gain %s", node->name); 5220 loadGain(node, index++); 5221 node = node->next; 5222 } 5223} 5224 5225status_t AudioPolicyManager::AudioPort::checkSamplingRate(uint32_t samplingRate) const 5226{ 5227 for (size_t i = 0; i < mSamplingRates.size(); i ++) { 5228 if (mSamplingRates[i] == samplingRate) { 5229 return NO_ERROR; 5230 } 5231 } 5232 return BAD_VALUE; 5233} 5234 5235status_t AudioPolicyManager::AudioPort::checkChannelMask(audio_channel_mask_t channelMask) const 5236{ 5237 for (size_t i = 0; i < mChannelMasks.size(); i ++) { 5238 if (mChannelMasks[i] == channelMask) { 5239 return NO_ERROR; 5240 } 5241 } 5242 return BAD_VALUE; 5243} 5244 5245status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const 5246{ 5247 for (size_t i = 0; i < mFormats.size(); i ++) { 5248 if (mFormats[i] == format) { 5249 return NO_ERROR; 5250 } 5251 } 5252 return BAD_VALUE; 5253} 5254 5255 5256uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const 5257{ 5258 // special case for uninitialized dynamic profile 5259 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) { 5260 return 0; 5261 } 5262 5263 uint32_t samplingRate = 0; 5264 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE; 5265 5266 // For mixed output and inputs, use max mixer sampling rates. Do not 5267 // limit sampling rate otherwise 5268 if ((mType != AUDIO_PORT_TYPE_MIX) || 5269 ((mRole == AUDIO_PORT_ROLE_SOURCE) && 5270 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) { 5271 maxRate = UINT_MAX; 5272 } 5273 for (size_t i = 0; i < mSamplingRates.size(); i ++) { 5274 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) { 5275 samplingRate = mSamplingRates[i]; 5276 } 5277 } 5278 return samplingRate; 5279} 5280 5281audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const 5282{ 5283 // special case for uninitialized dynamic profile 5284 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) { 5285 return AUDIO_CHANNEL_NONE; 5286 } 5287 5288 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE; 5289 uint32_t channelCount = 0; 5290 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT; 5291 5292 // For mixed output and inputs, use max mixer channel count. Do not 5293 // limit channel count otherwise 5294 if ((mType != AUDIO_PORT_TYPE_MIX) || 5295 ((mRole == AUDIO_PORT_ROLE_SOURCE) && 5296 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) { 5297 maxCount = UINT_MAX; 5298 } 5299 for (size_t i = 0; i < mChannelMasks.size(); i ++) { 5300 uint32_t cnlCount; 5301 if (mUseInChannelMask) { 5302 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]); 5303 } else { 5304 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]); 5305 } 5306 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) { 5307 channelMask = mChannelMasks[i]; 5308 } 5309 } 5310 return channelMask; 5311} 5312 5313const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = { 5314 AUDIO_FORMAT_DEFAULT, 5315 AUDIO_FORMAT_PCM_16_BIT, 5316 AUDIO_FORMAT_PCM_24_BIT_PACKED, 5317}; 5318 5319int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1, 5320 audio_format_t format2) 5321{ 5322 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any 5323 // compressed format and better than any PCM format. This is by design of pickFormat() 5324 if (!audio_is_linear_pcm(format1)) { 5325 if (!audio_is_linear_pcm(format2)) { 5326 return 0; 5327 } 5328 return 1; 5329 } 5330 if (!audio_is_linear_pcm(format2)) { 5331 return -1; 5332 } 5333 5334 int index1 = -1, index2 = -1; 5335 for (size_t i = 0; 5336 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1)); 5337 i ++) { 5338 if (sPcmFormatCompareTable[i] == format1) { 5339 index1 = i; 5340 } 5341 if (sPcmFormatCompareTable[i] == format2) { 5342 index2 = i; 5343 } 5344 } 5345 // format1 not found => index1 < 0 => format2 > format1 5346 // format2 not found => index2 < 0 => format2 < format1 5347 return index1 - index2; 5348} 5349 5350audio_format_t AudioPolicyManager::AudioPort::pickFormat() const 5351{ 5352 // special case for uninitialized dynamic profile 5353 if (mFormats.size() == 1 && mFormats[0] == 0) { 5354 return AUDIO_FORMAT_DEFAULT; 5355 } 5356 5357 audio_format_t format = AUDIO_FORMAT_DEFAULT; 5358 audio_format_t bestFormat = BEST_MIXER_FORMAT; 5359 // For mixed output and inputs, use best mixer output format. Do not 5360 // limit format otherwise 5361 if ((mType != AUDIO_PORT_TYPE_MIX) || 5362 ((mRole == AUDIO_PORT_ROLE_SOURCE) && 5363 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) == 0)))) { 5364 bestFormat = AUDIO_FORMAT_INVALID; 5365 } 5366 5367 for (size_t i = 0; i < mFormats.size(); i ++) { 5368 if ((compareFormats(mFormats[i], format) > 0) && 5369 (compareFormats(mFormats[i], bestFormat) <= 0)) { 5370 format = mFormats[i]; 5371 } 5372 } 5373 return format; 5374} 5375 5376status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig, 5377 int index) const 5378{ 5379 if (index < 0 || (size_t)index >= mGains.size()) { 5380 return BAD_VALUE; 5381 } 5382 return mGains[index]->checkConfig(gainConfig); 5383} 5384 5385void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const 5386{ 5387 const size_t SIZE = 256; 5388 char buffer[SIZE]; 5389 String8 result; 5390 5391 if (mName.size() != 0) { 5392 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string()); 5393 result.append(buffer); 5394 } 5395 5396 if (mSamplingRates.size() != 0) { 5397 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, ""); 5398 result.append(buffer); 5399 for (size_t i = 0; i < mSamplingRates.size(); i++) { 5400 if (i == 0 && mSamplingRates[i] == 0) { 5401 snprintf(buffer, SIZE, "Dynamic"); 5402 } else { 5403 snprintf(buffer, SIZE, "%d", mSamplingRates[i]); 5404 } 5405 result.append(buffer); 5406 result.append(i == (mSamplingRates.size() - 1) ? "" : ", "); 5407 } 5408 result.append("\n"); 5409 } 5410 5411 if (mChannelMasks.size() != 0) { 5412 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, ""); 5413 result.append(buffer); 5414 for (size_t i = 0; i < mChannelMasks.size(); i++) { 5415 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]); 5416 5417 if (i == 0 && mChannelMasks[i] == 0) { 5418 snprintf(buffer, SIZE, "Dynamic"); 5419 } else { 5420 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]); 5421 } 5422 result.append(buffer); 5423 result.append(i == (mChannelMasks.size() - 1) ? "" : ", "); 5424 } 5425 result.append("\n"); 5426 } 5427 5428 if (mFormats.size() != 0) { 5429 snprintf(buffer, SIZE, "%*s- formats: ", spaces, ""); 5430 result.append(buffer); 5431 for (size_t i = 0; i < mFormats.size(); i++) { 5432 const char *formatStr = enumToString(sFormatNameToEnumTable, 5433 ARRAY_SIZE(sFormatNameToEnumTable), 5434 mFormats[i]); 5435 if (i == 0 && strcmp(formatStr, "") == 0) { 5436 snprintf(buffer, SIZE, "Dynamic"); 5437 } else { 5438 snprintf(buffer, SIZE, "%-48s", formatStr); 5439 } 5440 result.append(buffer); 5441 result.append(i == (mFormats.size() - 1) ? "" : ", "); 5442 } 5443 result.append("\n"); 5444 } 5445 write(fd, result.string(), result.size()); 5446 if (mGains.size() != 0) { 5447 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, ""); 5448 write(fd, buffer, strlen(buffer) + 1); 5449 result.append(buffer); 5450 for (size_t i = 0; i < mGains.size(); i++) { 5451 mGains[i]->dump(fd, spaces + 2, i); 5452 } 5453 } 5454} 5455 5456// --- AudioGain class implementation 5457 5458AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask) 5459{ 5460 mIndex = index; 5461 mUseInChannelMask = useInChannelMask; 5462 memset(&mGain, 0, sizeof(struct audio_gain)); 5463} 5464 5465void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config) 5466{ 5467 config->index = mIndex; 5468 config->mode = mGain.mode; 5469 config->channel_mask = mGain.channel_mask; 5470 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) { 5471 config->values[0] = mGain.default_value; 5472 } else { 5473 uint32_t numValues; 5474 if (mUseInChannelMask) { 5475 numValues = audio_channel_count_from_in_mask(mGain.channel_mask); 5476 } else { 5477 numValues = audio_channel_count_from_out_mask(mGain.channel_mask); 5478 } 5479 for (size_t i = 0; i < numValues; i++) { 5480 config->values[i] = mGain.default_value; 5481 } 5482 } 5483 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) { 5484 config->ramp_duration_ms = mGain.min_ramp_ms; 5485 } 5486} 5487 5488status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config) 5489{ 5490 if ((config->mode & ~mGain.mode) != 0) { 5491 return BAD_VALUE; 5492 } 5493 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) { 5494 if ((config->values[0] < mGain.min_value) || 5495 (config->values[0] > mGain.max_value)) { 5496 return BAD_VALUE; 5497 } 5498 } else { 5499 if ((config->channel_mask & ~mGain.channel_mask) != 0) { 5500 return BAD_VALUE; 5501 } 5502 uint32_t numValues; 5503 if (mUseInChannelMask) { 5504 numValues = audio_channel_count_from_in_mask(config->channel_mask); 5505 } else { 5506 numValues = audio_channel_count_from_out_mask(config->channel_mask); 5507 } 5508 for (size_t i = 0; i < numValues; i++) { 5509 if ((config->values[i] < mGain.min_value) || 5510 (config->values[i] > mGain.max_value)) { 5511 return BAD_VALUE; 5512 } 5513 } 5514 } 5515 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) { 5516 if ((config->ramp_duration_ms < mGain.min_ramp_ms) || 5517 (config->ramp_duration_ms > mGain.max_ramp_ms)) { 5518 return BAD_VALUE; 5519 } 5520 } 5521 return NO_ERROR; 5522} 5523 5524void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const 5525{ 5526 const size_t SIZE = 256; 5527 char buffer[SIZE]; 5528 String8 result; 5529 5530 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1); 5531 result.append(buffer); 5532 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode); 5533 result.append(buffer); 5534 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask); 5535 result.append(buffer); 5536 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value); 5537 result.append(buffer); 5538 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value); 5539 result.append(buffer); 5540 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value); 5541 result.append(buffer); 5542 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value); 5543 result.append(buffer); 5544 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms); 5545 result.append(buffer); 5546 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms); 5547 result.append(buffer); 5548 5549 write(fd, result.string(), result.size()); 5550} 5551 5552// --- AudioPortConfig class implementation 5553 5554AudioPolicyManager::AudioPortConfig::AudioPortConfig() 5555{ 5556 mSamplingRate = 0; 5557 mChannelMask = AUDIO_CHANNEL_NONE; 5558 mFormat = AUDIO_FORMAT_INVALID; 5559 mGain.index = -1; 5560} 5561 5562status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig( 5563 const struct audio_port_config *config, 5564 struct audio_port_config *backupConfig) 5565{ 5566 struct audio_port_config localBackupConfig; 5567 status_t status = NO_ERROR; 5568 5569 localBackupConfig.config_mask = config->config_mask; 5570 toAudioPortConfig(&localBackupConfig); 5571 5572 if (mAudioPort == 0) { 5573 status = NO_INIT; 5574 goto exit; 5575 } 5576 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) { 5577 status = mAudioPort->checkSamplingRate(config->sample_rate); 5578 if (status != NO_ERROR) { 5579 goto exit; 5580 } 5581 mSamplingRate = config->sample_rate; 5582 } 5583 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) { 5584 status = mAudioPort->checkChannelMask(config->channel_mask); 5585 if (status != NO_ERROR) { 5586 goto exit; 5587 } 5588 mChannelMask = config->channel_mask; 5589 } 5590 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) { 5591 status = mAudioPort->checkFormat(config->format); 5592 if (status != NO_ERROR) { 5593 goto exit; 5594 } 5595 mFormat = config->format; 5596 } 5597 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) { 5598 status = mAudioPort->checkGain(&config->gain, config->gain.index); 5599 if (status != NO_ERROR) { 5600 goto exit; 5601 } 5602 mGain = config->gain; 5603 } 5604 5605exit: 5606 if (status != NO_ERROR) { 5607 applyAudioPortConfig(&localBackupConfig); 5608 } 5609 if (backupConfig != NULL) { 5610 *backupConfig = localBackupConfig; 5611 } 5612 return status; 5613} 5614 5615void AudioPolicyManager::AudioPortConfig::toAudioPortConfig( 5616 struct audio_port_config *dstConfig, 5617 const struct audio_port_config *srcConfig) const 5618{ 5619 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) { 5620 dstConfig->sample_rate = mSamplingRate; 5621 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) { 5622 dstConfig->sample_rate = srcConfig->sample_rate; 5623 } 5624 } else { 5625 dstConfig->sample_rate = 0; 5626 } 5627 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) { 5628 dstConfig->channel_mask = mChannelMask; 5629 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) { 5630 dstConfig->channel_mask = srcConfig->channel_mask; 5631 } 5632 } else { 5633 dstConfig->channel_mask = AUDIO_CHANNEL_NONE; 5634 } 5635 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) { 5636 dstConfig->format = mFormat; 5637 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) { 5638 dstConfig->format = srcConfig->format; 5639 } 5640 } else { 5641 dstConfig->format = AUDIO_FORMAT_INVALID; 5642 } 5643 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) { 5644 dstConfig->gain = mGain; 5645 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) { 5646 dstConfig->gain = srcConfig->gain; 5647 } 5648 } else { 5649 dstConfig->gain.index = -1; 5650 } 5651 if (dstConfig->gain.index != -1) { 5652 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN; 5653 } else { 5654 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN; 5655 } 5656} 5657 5658// --- IOProfile class implementation 5659 5660AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role, 5661 const sp<HwModule>& module) 5662 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module) 5663{ 5664} 5665 5666AudioPolicyManager::IOProfile::~IOProfile() 5667{ 5668} 5669 5670// checks if the IO profile is compatible with specified parameters. 5671// Sampling rate, format and channel mask must be specified in order to 5672// get a valid a match 5673bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device, 5674 uint32_t samplingRate, 5675 audio_format_t format, 5676 audio_channel_mask_t channelMask, 5677 audio_output_flags_t flags) const 5678{ 5679 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) { 5680 return false; 5681 } 5682 5683 if ((mSupportedDevices.types() & device) != device) { 5684 return false; 5685 } 5686 if ((mFlags & flags) != flags) { 5687 return false; 5688 } 5689 if (checkSamplingRate(samplingRate) != NO_ERROR) { 5690 return false; 5691 } 5692 if (checkChannelMask(channelMask) != NO_ERROR) { 5693 return false; 5694 } 5695 if (checkFormat(format) != NO_ERROR) { 5696 return false; 5697 } 5698 return true; 5699} 5700 5701void AudioPolicyManager::IOProfile::dump(int fd) 5702{ 5703 const size_t SIZE = 256; 5704 char buffer[SIZE]; 5705 String8 result; 5706 5707 AudioPort::dump(fd, 4); 5708 5709 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags); 5710 result.append(buffer); 5711 snprintf(buffer, SIZE, " - devices:\n"); 5712 result.append(buffer); 5713 write(fd, result.string(), result.size()); 5714 for (size_t i = 0; i < mSupportedDevices.size(); i++) { 5715 mSupportedDevices[i]->dump(fd, 6, i); 5716 } 5717} 5718 5719void AudioPolicyManager::IOProfile::log() 5720{ 5721 const size_t SIZE = 256; 5722 char buffer[SIZE]; 5723 String8 result; 5724 5725 ALOGV(" - sampling rates: "); 5726 for (size_t i = 0; i < mSamplingRates.size(); i++) { 5727 ALOGV(" %d", mSamplingRates[i]); 5728 } 5729 5730 ALOGV(" - channel masks: "); 5731 for (size_t i = 0; i < mChannelMasks.size(); i++) { 5732 ALOGV(" 0x%04x", mChannelMasks[i]); 5733 } 5734 5735 ALOGV(" - formats: "); 5736 for (size_t i = 0; i < mFormats.size(); i++) { 5737 ALOGV(" 0x%08x", mFormats[i]); 5738 } 5739 5740 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types()); 5741 ALOGV(" - flags: 0x%04x\n", mFlags); 5742} 5743 5744 5745// --- DeviceDescriptor implementation 5746 5747 5748AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) : 5749 AudioPort(name, AUDIO_PORT_TYPE_DEVICE, 5750 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK : 5751 AUDIO_PORT_ROLE_SOURCE, 5752 NULL), 5753 mDeviceType(type), mAddress(""), mId(0) 5754{ 5755 mAudioPort = this; 5756 if (mGains.size() > 0) { 5757 mGains[0]->getDefaultConfig(&mGain); 5758 } 5759} 5760 5761bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const 5762{ 5763 // Devices are considered equal if they: 5764 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE) 5765 // - have the same address or one device does not specify the address 5766 // - have the same channel mask or one device does not specify the channel mask 5767 return (mDeviceType == other->mDeviceType) && 5768 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) && 5769 (mChannelMask == 0 || other->mChannelMask == 0 || 5770 mChannelMask == other->mChannelMask); 5771} 5772 5773void AudioPolicyManager::DeviceVector::refreshTypes() 5774{ 5775 mDeviceTypes = AUDIO_DEVICE_NONE; 5776 for(size_t i = 0; i < size(); i++) { 5777 mDeviceTypes |= itemAt(i)->mDeviceType; 5778 } 5779 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes); 5780} 5781 5782ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const 5783{ 5784 for(size_t i = 0; i < size(); i++) { 5785 if (item->equals(itemAt(i))) { 5786 return i; 5787 } 5788 } 5789 return -1; 5790} 5791 5792ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item) 5793{ 5794 ssize_t ret = indexOf(item); 5795 5796 if (ret < 0) { 5797 ret = SortedVector::add(item); 5798 if (ret >= 0) { 5799 refreshTypes(); 5800 } 5801 } else { 5802 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType); 5803 ret = -1; 5804 } 5805 return ret; 5806} 5807 5808ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item) 5809{ 5810 size_t i; 5811 ssize_t ret = indexOf(item); 5812 5813 if (ret < 0) { 5814 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType); 5815 } else { 5816 ret = SortedVector::removeAt(ret); 5817 if (ret >= 0) { 5818 refreshTypes(); 5819 } 5820 } 5821 return ret; 5822} 5823 5824void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types) 5825{ 5826 DeviceVector deviceList; 5827 5828 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types; 5829 types &= ~role_bit; 5830 5831 while (types) { 5832 uint32_t i = 31 - __builtin_clz(types); 5833 uint32_t type = 1 << i; 5834 types &= ~type; 5835 add(new DeviceDescriptor(String8(""), type | role_bit)); 5836 } 5837} 5838 5839void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name, 5840 const DeviceVector& declaredDevices) 5841{ 5842 char *devName = strtok(name, "|"); 5843 while (devName != NULL) { 5844 if (strlen(devName) != 0) { 5845 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable, 5846 ARRAY_SIZE(sDeviceNameToEnumTable), 5847 devName); 5848 if (type != AUDIO_DEVICE_NONE) { 5849 add(new DeviceDescriptor(String8(""), type)); 5850 } else { 5851 sp<DeviceDescriptor> deviceDesc = 5852 declaredDevices.getDeviceFromName(String8(devName)); 5853 if (deviceDesc != 0) { 5854 add(deviceDesc); 5855 } 5856 } 5857 } 5858 devName = strtok(NULL, "|"); 5859 } 5860} 5861 5862sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice( 5863 audio_devices_t type, String8 address) const 5864{ 5865 sp<DeviceDescriptor> device; 5866 for (size_t i = 0; i < size(); i++) { 5867 if (itemAt(i)->mDeviceType == type) { 5868 device = itemAt(i); 5869 if (itemAt(i)->mAddress = address) { 5870 break; 5871 } 5872 } 5873 } 5874 ALOGV("DeviceVector::getDevice() for type %d address %s found %p", 5875 type, address.string(), device.get()); 5876 return device; 5877} 5878 5879sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId( 5880 audio_port_handle_t id) const 5881{ 5882 sp<DeviceDescriptor> device; 5883 for (size_t i = 0; i < size(); i++) { 5884 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId); 5885 if (itemAt(i)->mId == id) { 5886 device = itemAt(i); 5887 break; 5888 } 5889 } 5890 return device; 5891} 5892 5893AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType( 5894 audio_devices_t type) const 5895{ 5896 DeviceVector devices; 5897 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) { 5898 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) { 5899 devices.add(itemAt(i)); 5900 type &= ~itemAt(i)->mDeviceType; 5901 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p", 5902 itemAt(i)->mDeviceType, itemAt(i).get()); 5903 } 5904 } 5905 return devices; 5906} 5907 5908sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName( 5909 const String8& name) const 5910{ 5911 sp<DeviceDescriptor> device; 5912 for (size_t i = 0; i < size(); i++) { 5913 if (itemAt(i)->mName == name) { 5914 device = itemAt(i); 5915 break; 5916 } 5917 } 5918 return device; 5919} 5920 5921void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig( 5922 struct audio_port_config *dstConfig, 5923 const struct audio_port_config *srcConfig) const 5924{ 5925 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN; 5926 if (srcConfig != NULL) { 5927 dstConfig->config_mask |= srcConfig->config_mask; 5928 } 5929 5930 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig); 5931 5932 dstConfig->id = mId; 5933 dstConfig->role = audio_is_output_device(mDeviceType) ? 5934 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE; 5935 dstConfig->type = AUDIO_PORT_TYPE_DEVICE; 5936 dstConfig->ext.device.type = mDeviceType; 5937 dstConfig->ext.device.hw_module = mModule->mHandle; 5938 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN); 5939} 5940 5941void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const 5942{ 5943 ALOGV("DeviceVector::toAudioPort() handle %d type %x", mId, mDeviceType); 5944 AudioPort::toAudioPort(port); 5945 port->id = mId; 5946 toAudioPortConfig(&port->active_config); 5947 port->ext.device.type = mDeviceType; 5948 port->ext.device.hw_module = mModule->mHandle; 5949 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN); 5950} 5951 5952status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const 5953{ 5954 const size_t SIZE = 256; 5955 char buffer[SIZE]; 5956 String8 result; 5957 5958 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1); 5959 result.append(buffer); 5960 if (mId != 0) { 5961 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId); 5962 result.append(buffer); 5963 } 5964 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "", 5965 enumToString(sDeviceNameToEnumTable, 5966 ARRAY_SIZE(sDeviceNameToEnumTable), 5967 mDeviceType)); 5968 result.append(buffer); 5969 if (mAddress.size() != 0) { 5970 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string()); 5971 result.append(buffer); 5972 } 5973 write(fd, result.string(), result.size()); 5974 AudioPort::dump(fd, spaces); 5975 5976 return NO_ERROR; 5977} 5978 5979 5980// --- audio_policy.conf file parsing 5981 5982audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name) 5983{ 5984 uint32_t flag = 0; 5985 5986 // it is OK to cast name to non const here as we are not going to use it after 5987 // strtok() modifies it 5988 char *flagName = strtok(name, "|"); 5989 while (flagName != NULL) { 5990 if (strlen(flagName) != 0) { 5991 flag |= stringToEnum(sFlagNameToEnumTable, 5992 ARRAY_SIZE(sFlagNameToEnumTable), 5993 flagName); 5994 } 5995 flagName = strtok(NULL, "|"); 5996 } 5997 //force direct flag if offload flag is set: offloading implies a direct output stream 5998 // and all common behaviors are driven by checking only the direct flag 5999 // this should normally be set appropriately in the policy configuration file 6000 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) { 6001 flag |= AUDIO_OUTPUT_FLAG_DIRECT; 6002 } 6003 6004 return (audio_output_flags_t)flag; 6005} 6006 6007audio_devices_t AudioPolicyManager::parseDeviceNames(char *name) 6008{ 6009 uint32_t device = 0; 6010 6011 char *devName = strtok(name, "|"); 6012 while (devName != NULL) { 6013 if (strlen(devName) != 0) { 6014 device |= stringToEnum(sDeviceNameToEnumTable, 6015 ARRAY_SIZE(sDeviceNameToEnumTable), 6016 devName); 6017 } 6018 devName = strtok(NULL, "|"); 6019 } 6020 return device; 6021} 6022 6023void AudioPolicyManager::loadHwModule(cnode *root) 6024{ 6025 status_t status = NAME_NOT_FOUND; 6026 cnode *node; 6027 sp<HwModule> module = new HwModule(root->name); 6028 6029 node = config_find(root, DEVICES_TAG); 6030 if (node != NULL) { 6031 node = node->first_child; 6032 while (node) { 6033 ALOGV("loadHwModule() loading device %s", node->name); 6034 status_t tmpStatus = module->loadDevice(node); 6035 if (status == NAME_NOT_FOUND || status == NO_ERROR) { 6036 status = tmpStatus; 6037 } 6038 node = node->next; 6039 } 6040 } 6041 node = config_find(root, OUTPUTS_TAG); 6042 if (node != NULL) { 6043 node = node->first_child; 6044 while (node) { 6045 ALOGV("loadHwModule() loading output %s", node->name); 6046 status_t tmpStatus = module->loadOutput(node); 6047 if (status == NAME_NOT_FOUND || status == NO_ERROR) { 6048 status = tmpStatus; 6049 } 6050 node = node->next; 6051 } 6052 } 6053 node = config_find(root, INPUTS_TAG); 6054 if (node != NULL) { 6055 node = node->first_child; 6056 while (node) { 6057 ALOGV("loadHwModule() loading input %s", node->name); 6058 status_t tmpStatus = module->loadInput(node); 6059 if (status == NAME_NOT_FOUND || status == NO_ERROR) { 6060 status = tmpStatus; 6061 } 6062 node = node->next; 6063 } 6064 } 6065 loadGlobalConfig(root, module); 6066 6067 if (status == NO_ERROR) { 6068 mHwModules.add(module); 6069 } 6070} 6071 6072void AudioPolicyManager::loadHwModules(cnode *root) 6073{ 6074 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG); 6075 if (node == NULL) { 6076 return; 6077 } 6078 6079 node = node->first_child; 6080 while (node) { 6081 ALOGV("loadHwModules() loading module %s", node->name); 6082 loadHwModule(node); 6083 node = node->next; 6084 } 6085} 6086 6087void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module) 6088{ 6089 cnode *node = config_find(root, GLOBAL_CONFIG_TAG); 6090 6091 if (node == NULL) { 6092 return; 6093 } 6094 DeviceVector declaredDevices; 6095 if (module != NULL) { 6096 declaredDevices = module->mDeclaredDevices; 6097 } 6098 6099 node = node->first_child; 6100 while (node) { 6101 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) { 6102 mAvailableOutputDevices.loadDevicesFromName((char *)node->value, 6103 declaredDevices); 6104 ALOGV("loadGlobalConfig() Attached Output Devices %08x", 6105 mAvailableOutputDevices.types()); 6106 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) { 6107 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable, 6108 ARRAY_SIZE(sDeviceNameToEnumTable), 6109 (char *)node->value); 6110 if (device != AUDIO_DEVICE_NONE) { 6111 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device); 6112 } else { 6113 ALOGW("loadGlobalConfig() default device not specified"); 6114 } 6115 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType); 6116 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) { 6117 mAvailableInputDevices.loadDevicesFromName((char *)node->value, 6118 declaredDevices); 6119 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types()); 6120 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) { 6121 mSpeakerDrcEnabled = stringToBool((char *)node->value); 6122 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled); 6123 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) { 6124 uint32_t major, minor; 6125 sscanf((char *)node->value, "%u.%u", &major, &minor); 6126 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor); 6127 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u", 6128 module->mHalVersion, major, minor); 6129 } 6130 node = node->next; 6131 } 6132} 6133 6134status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path) 6135{ 6136 cnode *root; 6137 char *data; 6138 6139 data = (char *)load_file(path, NULL); 6140 if (data == NULL) { 6141 return -ENODEV; 6142 } 6143 root = config_node("", ""); 6144 config_load(root, data); 6145 6146 loadHwModules(root); 6147 // legacy audio_policy.conf files have one global_configuration section 6148 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)); 6149 config_free(root); 6150 free(root); 6151 free(data); 6152 6153 ALOGI("loadAudioPolicyConfig() loaded %s\n", path); 6154 6155 return NO_ERROR; 6156} 6157 6158void AudioPolicyManager::defaultAudioPolicyConfig(void) 6159{ 6160 sp<HwModule> module; 6161 sp<IOProfile> profile; 6162 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""), 6163 AUDIO_DEVICE_IN_BUILTIN_MIC); 6164 mAvailableOutputDevices.add(mDefaultOutputDevice); 6165 mAvailableInputDevices.add(defaultInputDevice); 6166 6167 module = new HwModule("primary"); 6168 6169 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module); 6170 profile->mSamplingRates.add(44100); 6171 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT); 6172 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO); 6173 profile->mSupportedDevices.add(mDefaultOutputDevice); 6174 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY; 6175 module->mOutputProfiles.add(profile); 6176 6177 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module); 6178 profile->mSamplingRates.add(8000); 6179 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT); 6180 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO); 6181 profile->mSupportedDevices.add(defaultInputDevice); 6182 module->mInputProfiles.add(profile); 6183 6184 mHwModules.add(module); 6185} 6186 6187audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr) 6188{ 6189 // flags to stream type mapping 6190 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) { 6191 return AUDIO_STREAM_ENFORCED_AUDIBLE; 6192 } 6193 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) { 6194 return AUDIO_STREAM_BLUETOOTH_SCO; 6195 } 6196 6197 // usage to stream type mapping 6198 switch (attr->usage) { 6199 case AUDIO_USAGE_MEDIA: 6200 case AUDIO_USAGE_GAME: 6201 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY: 6202 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE: 6203 return AUDIO_STREAM_MUSIC; 6204 case AUDIO_USAGE_ASSISTANCE_SONIFICATION: 6205 return AUDIO_STREAM_SYSTEM; 6206 case AUDIO_USAGE_VOICE_COMMUNICATION: 6207 return AUDIO_STREAM_VOICE_CALL; 6208 6209 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING: 6210 return AUDIO_STREAM_DTMF; 6211 6212 case AUDIO_USAGE_ALARM: 6213 return AUDIO_STREAM_ALARM; 6214 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE: 6215 return AUDIO_STREAM_RING; 6216 6217 case AUDIO_USAGE_NOTIFICATION: 6218 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST: 6219 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT: 6220 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED: 6221 case AUDIO_USAGE_NOTIFICATION_EVENT: 6222 return AUDIO_STREAM_NOTIFICATION; 6223 6224 case AUDIO_USAGE_UNKNOWN: 6225 default: 6226 return AUDIO_STREAM_MUSIC; 6227 } 6228} 6229}; // namespace android 6230