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