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