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