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