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