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