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