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