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