1/* 2 * Copyright (C) 2009 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#define LOG_TAG "AudioPolicyManager" 18//#define LOG_NDEBUG 0 19 20//#define VERY_VERBOSE_LOGGING 21#ifdef VERY_VERBOSE_LOGGING 22#define ALOGVV ALOGV 23#else 24#define ALOGVV(a...) do { } while(0) 25#endif 26 27// A device mask for all audio input devices that are considered "virtual" when evaluating 28// active inputs in getActiveInput() 29#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX|AUDIO_DEVICE_IN_FM_TUNER) 30// A device mask for all audio output devices that are considered "remote" when evaluating 31// active output devices in isStreamActiveRemotely() 32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX 33// A device mask for all audio input and output devices where matching inputs/outputs on device 34// type alone is not enough: the address must match too 35#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \ 36 AUDIO_DEVICE_OUT_REMOTE_SUBMIX) 37 38#include <inttypes.h> 39#include <math.h> 40 41#include <cutils/properties.h> 42#include <utils/Log.h> 43#include <hardware/audio.h> 44#include <hardware/audio_effect.h> 45#include <media/AudioParameter.h> 46#include <media/AudioPolicyHelper.h> 47#include <soundtrigger/SoundTrigger.h> 48#include "AudioPolicyManager.h" 49#include "audio_policy_conf.h" 50 51namespace android { 52 53// ---------------------------------------------------------------------------- 54// Definitions for audio_policy.conf file parsing 55// ---------------------------------------------------------------------------- 56 57struct StringToEnum { 58 const char *name; 59 uint32_t value; 60}; 61 62#define STRING_TO_ENUM(string) { #string, string } 63#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) 64 65const StringToEnum sDeviceNameToEnumTable[] = { 66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE), 67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER), 68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER_SAFE), 69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET), 70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE), 71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO), 72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET), 73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT), 74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO), 75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP), 76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES), 77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER), 78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP), 79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL), 80 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI), 81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET), 82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET), 83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY), 84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE), 85 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB), 86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX), 87 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX), 88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE), 89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC), 90 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF), 91 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM), 92 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE), 93 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT), 94 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC), 95 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET), 96 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO), 97 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET), 98 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL), 99 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI), 100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX), 101 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL), 102 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC), 103 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX), 104 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET), 105 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET), 106 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY), 107 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE), 108 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER), 109 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER), 110 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE), 111 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF), 112 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP), 113 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK), 114}; 115 116const StringToEnum sOutputFlagNameToEnumTable[] = { 117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT), 118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY), 119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST), 120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER), 121 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD), 122 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING), 123 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC), 124}; 125 126const StringToEnum sInputFlagNameToEnumTable[] = { 127 STRING_TO_ENUM(AUDIO_INPUT_FLAG_FAST), 128 STRING_TO_ENUM(AUDIO_INPUT_FLAG_HW_HOTWORD), 129}; 130 131const StringToEnum sFormatNameToEnumTable[] = { 132 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT), 133 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT), 134 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT), 135 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT), 136 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT), 137 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED), 138 STRING_TO_ENUM(AUDIO_FORMAT_MP3), 139 STRING_TO_ENUM(AUDIO_FORMAT_AAC), 140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN), 141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC), 142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR), 143 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP), 144 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1), 145 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE), 146 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC), 147 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD), 148 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2), 149 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD), 150 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS), 151 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1), 152 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2), 153 STRING_TO_ENUM(AUDIO_FORMAT_OPUS), 154 STRING_TO_ENUM(AUDIO_FORMAT_AC3), 155 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3), 156}; 157 158const StringToEnum sOutChannelsNameToEnumTable[] = { 159 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO), 160 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO), 161 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD), 162 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1), 163 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1), 164}; 165 166const StringToEnum sInChannelsNameToEnumTable[] = { 167 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO), 168 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO), 169 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK), 170}; 171 172const StringToEnum sGainModeNameToEnumTable[] = { 173 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT), 174 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS), 175 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP), 176}; 177 178 179uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table, 180 size_t size, 181 const char *name) 182{ 183 for (size_t i = 0; i < size; i++) { 184 if (strcmp(table[i].name, name) == 0) { 185 ALOGV("stringToEnum() found %s", table[i].name); 186 return table[i].value; 187 } 188 } 189 return 0; 190} 191 192const char *AudioPolicyManager::enumToString(const struct StringToEnum *table, 193 size_t size, 194 uint32_t value) 195{ 196 for (size_t i = 0; i < size; i++) { 197 if (table[i].value == value) { 198 return table[i].name; 199 } 200 } 201 return ""; 202} 203 204bool AudioPolicyManager::stringToBool(const char *value) 205{ 206 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0)); 207} 208 209 210// ---------------------------------------------------------------------------- 211// AudioPolicyInterface implementation 212// ---------------------------------------------------------------------------- 213 214status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device, 215 audio_policy_dev_state_t state, 216 const char *device_address) 217{ 218 return setDeviceConnectionStateInt(device, state, device_address); 219} 220 221status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device, 222 audio_policy_dev_state_t state, 223 const char *device_address) 224{ 225 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", 226 device, state, device_address != NULL ? device_address : ""); 227 228 // connect/disconnect only 1 device at a time 229 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE; 230 231 sp<DeviceDescriptor> devDesc = getDeviceDescriptor(device, device_address); 232 233 // handle output devices 234 if (audio_is_output_device(device)) { 235 SortedVector <audio_io_handle_t> outputs; 236 237 ssize_t index = mAvailableOutputDevices.indexOf(devDesc); 238 239 // save a copy of the opened output descriptors before any output is opened or closed 240 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies() 241 mPreviousOutputs = mOutputs; 242 switch (state) 243 { 244 // handle output device connection 245 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: { 246 if (index >= 0) { 247 ALOGW("setDeviceConnectionState() device already connected: %x", device); 248 return INVALID_OPERATION; 249 } 250 ALOGV("setDeviceConnectionState() connecting device %x", device); 251 252 // register new device as available 253 index = mAvailableOutputDevices.add(devDesc); 254 if (index >= 0) { 255 sp<HwModule> module = getModuleForDevice(device); 256 if (module == 0) { 257 ALOGD("setDeviceConnectionState() could not find HW module for device %08x", 258 device); 259 mAvailableOutputDevices.remove(devDesc); 260 return INVALID_OPERATION; 261 } 262 mAvailableOutputDevices[index]->mId = nextUniqueId(); 263 mAvailableOutputDevices[index]->mModule = module; 264 } else { 265 return NO_MEMORY; 266 } 267 268 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) { 269 mAvailableOutputDevices.remove(devDesc); 270 return INVALID_OPERATION; 271 } 272 // outputs should never be empty here 273 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():" 274 "checkOutputsForDevice() returned no outputs but status OK"); 275 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs", 276 outputs.size()); 277 278 279 // Set connect to HALs 280 AudioParameter param = AudioParameter(devDesc->mAddress); 281 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device); 282 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString()); 283 284 } break; 285 // handle output device disconnection 286 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: { 287 if (index < 0) { 288 ALOGW("setDeviceConnectionState() device not connected: %x", device); 289 return INVALID_OPERATION; 290 } 291 292 ALOGV("setDeviceConnectionState() disconnecting output device %x", device); 293 294 // Set Disconnect to HALs 295 AudioParameter param = AudioParameter(devDesc->mAddress); 296 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device); 297 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString()); 298 299 // remove device from available output devices 300 mAvailableOutputDevices.remove(devDesc); 301 302 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress); 303 } break; 304 305 default: 306 ALOGE("setDeviceConnectionState() invalid state: %x", state); 307 return BAD_VALUE; 308 } 309 310 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP 311 // output is suspended before any tracks are moved to it 312 checkA2dpSuspend(); 313 checkOutputForAllStrategies(); 314 // outputs must be closed after checkOutputForAllStrategies() is executed 315 if (!outputs.isEmpty()) { 316 for (size_t i = 0; i < outputs.size(); i++) { 317 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]); 318 // close unused outputs after device disconnection or direct outputs that have been 319 // opened by checkOutputsForDevice() to query dynamic parameters 320 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) || 321 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) && 322 (desc->mDirectOpenCount == 0))) { 323 closeOutput(outputs[i]); 324 } 325 } 326 // check again after closing A2DP output to reset mA2dpSuspended if needed 327 checkA2dpSuspend(); 328 } 329 330 updateDevicesAndOutputs(); 331 if (mPhoneState == AUDIO_MODE_IN_CALL) { 332 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/); 333 updateCallRouting(newDevice); 334 } 335 for (size_t i = 0; i < mOutputs.size(); i++) { 336 audio_io_handle_t output = mOutputs.keyAt(i); 337 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) { 338 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i), 339 true /*fromCache*/); 340 // do not force device change on duplicated output because if device is 0, it will 341 // also force a device 0 for the two outputs it is duplicated to which may override 342 // a valid device selection on those outputs. 343 bool force = !mOutputs.valueAt(i)->isDuplicated() 344 && (!deviceDistinguishesOnAddress(device) 345 // always force when disconnecting (a non-duplicated device) 346 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)); 347 setOutputDevice(output, newDevice, force, 0); 348 } 349 } 350 351 mpClientInterface->onAudioPortListUpdate(); 352 return NO_ERROR; 353 } // end if is output device 354 355 // handle input devices 356 if (audio_is_input_device(device)) { 357 SortedVector <audio_io_handle_t> inputs; 358 359 ssize_t index = mAvailableInputDevices.indexOf(devDesc); 360 switch (state) 361 { 362 // handle input device connection 363 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: { 364 if (index >= 0) { 365 ALOGW("setDeviceConnectionState() device already connected: %d", device); 366 return INVALID_OPERATION; 367 } 368 sp<HwModule> module = getModuleForDevice(device); 369 if (module == NULL) { 370 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x", 371 device); 372 return INVALID_OPERATION; 373 } 374 if (checkInputsForDevice(device, state, inputs, devDesc->mAddress) != NO_ERROR) { 375 return INVALID_OPERATION; 376 } 377 378 index = mAvailableInputDevices.add(devDesc); 379 if (index >= 0) { 380 mAvailableInputDevices[index]->mId = nextUniqueId(); 381 mAvailableInputDevices[index]->mModule = module; 382 } else { 383 return NO_MEMORY; 384 } 385 386 // Set connect to HALs 387 AudioParameter param = AudioParameter(devDesc->mAddress); 388 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device); 389 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString()); 390 391 } break; 392 393 // handle input device disconnection 394 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: { 395 if (index < 0) { 396 ALOGW("setDeviceConnectionState() device not connected: %d", device); 397 return INVALID_OPERATION; 398 } 399 400 ALOGV("setDeviceConnectionState() disconnecting input device %x", device); 401 402 // Set Disconnect to HALs 403 AudioParameter param = AudioParameter(devDesc->mAddress); 404 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device); 405 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString()); 406 407 checkInputsForDevice(device, state, inputs, devDesc->mAddress); 408 mAvailableInputDevices.remove(devDesc); 409 410 } break; 411 412 default: 413 ALOGE("setDeviceConnectionState() invalid state: %x", state); 414 return BAD_VALUE; 415 } 416 417 closeAllInputs(); 418 419 if (mPhoneState == AUDIO_MODE_IN_CALL) { 420 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/); 421 updateCallRouting(newDevice); 422 } 423 424 mpClientInterface->onAudioPortListUpdate(); 425 return NO_ERROR; 426 } // end if is input device 427 428 ALOGW("setDeviceConnectionState() invalid device: %x", device); 429 return BAD_VALUE; 430} 431 432audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device, 433 const char *device_address) 434{ 435 sp<DeviceDescriptor> devDesc = getDeviceDescriptor(device, device_address); 436 DeviceVector *deviceVector; 437 438 if (audio_is_output_device(device)) { 439 deviceVector = &mAvailableOutputDevices; 440 } else if (audio_is_input_device(device)) { 441 deviceVector = &mAvailableInputDevices; 442 } else { 443 ALOGW("getDeviceConnectionState() invalid device type %08x", device); 444 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE; 445 } 446 447 ssize_t index = deviceVector->indexOf(devDesc); 448 if (index >= 0) { 449 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE; 450 } else { 451 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE; 452 } 453} 454 455sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::getDeviceDescriptor( 456 const audio_devices_t device, 457 const char *device_address) 458{ 459 String8 address = (device_address == NULL) ? String8("") : String8(device_address); 460 // handle legacy remote submix case where the address was not always specified 461 if (deviceDistinguishesOnAddress(device) && (address.length() == 0)) { 462 address = String8("0"); 463 } 464 465 for (size_t i = 0; i < mHwModules.size(); i++) { 466 if (mHwModules[i]->mHandle == 0) { 467 continue; 468 } 469 DeviceVector deviceList = 470 mHwModules[i]->mDeclaredDevices.getDevicesFromTypeAddr(device, address); 471 if (!deviceList.isEmpty()) { 472 return deviceList.itemAt(0); 473 } 474 deviceList = mHwModules[i]->mDeclaredDevices.getDevicesFromType(device); 475 if (!deviceList.isEmpty()) { 476 return deviceList.itemAt(0); 477 } 478 } 479 480 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device); 481 devDesc->mAddress = address; 482 return devDesc; 483} 484 485void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs) 486{ 487 bool createTxPatch = false; 488 struct audio_patch patch; 489 patch.num_sources = 1; 490 patch.num_sinks = 1; 491 status_t status; 492 audio_patch_handle_t afPatchHandle; 493 DeviceVector deviceList; 494 495 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION); 496 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice); 497 498 // release existing RX patch if any 499 if (mCallRxPatch != 0) { 500 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0); 501 mCallRxPatch.clear(); 502 } 503 // release TX patch if any 504 if (mCallTxPatch != 0) { 505 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0); 506 mCallTxPatch.clear(); 507 } 508 509 // If the RX device is on the primary HW module, then use legacy routing method for voice calls 510 // via setOutputDevice() on primary output. 511 // Otherwise, create two audio patches for TX and RX path. 512 if (availablePrimaryOutputDevices() & rxDevice) { 513 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs); 514 // If the TX device is also on the primary HW module, setOutputDevice() will take care 515 // of it due to legacy implementation. If not, create a patch. 516 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN) 517 == AUDIO_DEVICE_NONE) { 518 createTxPatch = true; 519 } 520 } else { 521 // create RX path audio patch 522 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice); 523 ALOG_ASSERT(!deviceList.isEmpty(), 524 "updateCallRouting() selected device not in output device list"); 525 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0); 526 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX); 527 ALOG_ASSERT(!deviceList.isEmpty(), 528 "updateCallRouting() no telephony RX device"); 529 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0); 530 531 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]); 532 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]); 533 534 // request to reuse existing output stream if one is already opened to reach the RX device 535 SortedVector<audio_io_handle_t> outputs = 536 getOutputsForDevice(rxDevice, mOutputs); 537 audio_io_handle_t output = selectOutput(outputs, 538 AUDIO_OUTPUT_FLAG_NONE, 539 AUDIO_FORMAT_INVALID); 540 if (output != AUDIO_IO_HANDLE_NONE) { 541 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 542 ALOG_ASSERT(!outputDesc->isDuplicated(), 543 "updateCallRouting() RX device output is duplicated"); 544 outputDesc->toAudioPortConfig(&patch.sources[1]); 545 patch.num_sources = 2; 546 } 547 548 afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 549 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0); 550 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch", 551 status); 552 if (status == NO_ERROR) { 553 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(), 554 &patch, mUidCached); 555 mCallRxPatch->mAfPatchHandle = afPatchHandle; 556 mCallRxPatch->mUid = mUidCached; 557 } 558 createTxPatch = true; 559 } 560 if (createTxPatch) { 561 562 struct audio_patch patch; 563 patch.num_sources = 1; 564 patch.num_sinks = 1; 565 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice); 566 ALOG_ASSERT(!deviceList.isEmpty(), 567 "updateCallRouting() selected device not in input device list"); 568 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0); 569 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]); 570 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX); 571 ALOG_ASSERT(!deviceList.isEmpty(), 572 "updateCallRouting() no telephony TX device"); 573 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0); 574 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]); 575 576 SortedVector<audio_io_handle_t> outputs = 577 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs); 578 audio_io_handle_t output = selectOutput(outputs, 579 AUDIO_OUTPUT_FLAG_NONE, 580 AUDIO_FORMAT_INVALID); 581 // request to reuse existing output stream if one is already opened to reach the TX 582 // path output device 583 if (output != AUDIO_IO_HANDLE_NONE) { 584 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 585 ALOG_ASSERT(!outputDesc->isDuplicated(), 586 "updateCallRouting() RX device output is duplicated"); 587 outputDesc->toAudioPortConfig(&patch.sources[1]); 588 patch.num_sources = 2; 589 } 590 591 afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 592 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0); 593 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch", 594 status); 595 if (status == NO_ERROR) { 596 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(), 597 &patch, mUidCached); 598 mCallTxPatch->mAfPatchHandle = afPatchHandle; 599 mCallTxPatch->mUid = mUidCached; 600 } 601 } 602} 603 604void AudioPolicyManager::setPhoneState(audio_mode_t state) 605{ 606 ALOGV("setPhoneState() state %d", state); 607 if (state < 0 || state >= AUDIO_MODE_CNT) { 608 ALOGW("setPhoneState() invalid state %d", state); 609 return; 610 } 611 612 if (state == mPhoneState ) { 613 ALOGW("setPhoneState() setting same state %d", state); 614 return; 615 } 616 617 // if leaving call state, handle special case of active streams 618 // pertaining to sonification strategy see handleIncallSonification() 619 if (isInCall()) { 620 ALOGV("setPhoneState() in call state management: new state is %d", state); 621 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) { 622 if (stream == AUDIO_STREAM_PATCH) { 623 continue; 624 } 625 handleIncallSonification((audio_stream_type_t)stream, false, true); 626 } 627 628 // force reevaluating accessibility routing when call starts 629 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY); 630 } 631 632 // store previous phone state for management of sonification strategy below 633 int oldState = mPhoneState; 634 mPhoneState = state; 635 bool force = false; 636 637 // are we entering or starting a call 638 if (!isStateInCall(oldState) && isStateInCall(state)) { 639 ALOGV(" Entering call in setPhoneState()"); 640 // force routing command to audio hardware when starting a call 641 // even if no device change is needed 642 force = true; 643 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) { 644 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] = 645 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j]; 646 } 647 } else if (isStateInCall(oldState) && !isStateInCall(state)) { 648 ALOGV(" Exiting call in setPhoneState()"); 649 // force routing command to audio hardware when exiting a call 650 // even if no device change is needed 651 force = true; 652 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) { 653 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] = 654 sVolumeProfiles[AUDIO_STREAM_DTMF][j]; 655 } 656 } else if (isStateInCall(state) && (state != oldState)) { 657 ALOGV(" Switching between telephony and VoIP in setPhoneState()"); 658 // force routing command to audio hardware when switching between telephony and VoIP 659 // even if no device change is needed 660 force = true; 661 } 662 663 // check for device and output changes triggered by new phone state 664 checkA2dpSuspend(); 665 checkOutputForAllStrategies(); 666 updateDevicesAndOutputs(); 667 668 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput); 669 670 int delayMs = 0; 671 if (isStateInCall(state)) { 672 nsecs_t sysTime = systemTime(); 673 for (size_t i = 0; i < mOutputs.size(); i++) { 674 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 675 // mute media and sonification strategies and delay device switch by the largest 676 // latency of any output where either strategy is active. 677 // This avoid sending the ring tone or music tail into the earpiece or headset. 678 if ((desc->isStrategyActive(STRATEGY_MEDIA, 679 SONIFICATION_HEADSET_MUSIC_DELAY, 680 sysTime) || 681 desc->isStrategyActive(STRATEGY_SONIFICATION, 682 SONIFICATION_HEADSET_MUSIC_DELAY, 683 sysTime)) && 684 (delayMs < (int)desc->mLatency*2)) { 685 delayMs = desc->mLatency*2; 686 } 687 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i)); 688 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS, 689 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/)); 690 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i)); 691 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS, 692 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/)); 693 } 694 } 695 696 // Note that despite the fact that getNewOutputDevice() is called on the primary output, 697 // the device returned is not necessarily reachable via this output 698 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/); 699 // force routing command to audio hardware when ending call 700 // even if no device change is needed 701 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) { 702 rxDevice = hwOutputDesc->device(); 703 } 704 705 if (state == AUDIO_MODE_IN_CALL) { 706 updateCallRouting(rxDevice, delayMs); 707 } else if (oldState == AUDIO_MODE_IN_CALL) { 708 if (mCallRxPatch != 0) { 709 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0); 710 mCallRxPatch.clear(); 711 } 712 if (mCallTxPatch != 0) { 713 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0); 714 mCallTxPatch.clear(); 715 } 716 setOutputDevice(mPrimaryOutput, rxDevice, force, 0); 717 } else { 718 setOutputDevice(mPrimaryOutput, rxDevice, force, 0); 719 } 720 // if entering in call state, handle special case of active streams 721 // pertaining to sonification strategy see handleIncallSonification() 722 if (isStateInCall(state)) { 723 ALOGV("setPhoneState() in call state management: new state is %d", state); 724 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) { 725 if (stream == AUDIO_STREAM_PATCH) { 726 continue; 727 } 728 handleIncallSonification((audio_stream_type_t)stream, true, true); 729 } 730 } 731 732 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE 733 if (state == AUDIO_MODE_RINGTONE && 734 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) { 735 mLimitRingtoneVolume = true; 736 } else { 737 mLimitRingtoneVolume = false; 738 } 739} 740 741void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage, 742 audio_policy_forced_cfg_t config) 743{ 744 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState); 745 746 bool forceVolumeReeval = false; 747 switch(usage) { 748 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION: 749 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO && 750 config != AUDIO_POLICY_FORCE_NONE) { 751 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config); 752 return; 753 } 754 forceVolumeReeval = true; 755 mForceUse[usage] = config; 756 break; 757 case AUDIO_POLICY_FORCE_FOR_MEDIA: 758 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP && 759 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY && 760 config != AUDIO_POLICY_FORCE_ANALOG_DOCK && 761 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE && 762 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) { 763 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config); 764 return; 765 } 766 mForceUse[usage] = config; 767 break; 768 case AUDIO_POLICY_FORCE_FOR_RECORD: 769 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY && 770 config != AUDIO_POLICY_FORCE_NONE) { 771 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config); 772 return; 773 } 774 mForceUse[usage] = config; 775 break; 776 case AUDIO_POLICY_FORCE_FOR_DOCK: 777 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK && 778 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK && 779 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY && 780 config != AUDIO_POLICY_FORCE_ANALOG_DOCK && 781 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) { 782 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config); 783 } 784 forceVolumeReeval = true; 785 mForceUse[usage] = config; 786 break; 787 case AUDIO_POLICY_FORCE_FOR_SYSTEM: 788 if (config != AUDIO_POLICY_FORCE_NONE && 789 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) { 790 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config); 791 } 792 forceVolumeReeval = true; 793 mForceUse[usage] = config; 794 break; 795 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO: 796 if (config != AUDIO_POLICY_FORCE_NONE && 797 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) { 798 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config); 799 } 800 mForceUse[usage] = config; 801 break; 802 default: 803 ALOGW("setForceUse() invalid usage %d", usage); 804 break; 805 } 806 807 // check for device and output changes triggered by new force usage 808 checkA2dpSuspend(); 809 checkOutputForAllStrategies(); 810 updateDevicesAndOutputs(); 811 if (mPhoneState == AUDIO_MODE_IN_CALL) { 812 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/); 813 updateCallRouting(newDevice); 814 } 815 for (size_t i = 0; i < mOutputs.size(); i++) { 816 audio_io_handle_t output = mOutputs.keyAt(i); 817 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/); 818 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) { 819 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE)); 820 } 821 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) { 822 applyStreamVolumes(output, newDevice, 0, true); 823 } 824 } 825 826 audio_io_handle_t activeInput = getActiveInput(); 827 if (activeInput != 0) { 828 setInputDevice(activeInput, getNewInputDevice(activeInput)); 829 } 830 831} 832 833audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage) 834{ 835 return mForceUse[usage]; 836} 837 838void AudioPolicyManager::setSystemProperty(const char* property, const char* value) 839{ 840 ALOGV("setSystemProperty() property %s, value %s", property, value); 841} 842 843// Find a direct output profile compatible with the parameters passed, even if the input flags do 844// not explicitly request a direct output 845sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput( 846 audio_devices_t device, 847 uint32_t samplingRate, 848 audio_format_t format, 849 audio_channel_mask_t channelMask, 850 audio_output_flags_t flags) 851{ 852 for (size_t i = 0; i < mHwModules.size(); i++) { 853 if (mHwModules[i]->mHandle == 0) { 854 continue; 855 } 856 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) { 857 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j]; 858 bool found = profile->isCompatibleProfile(device, String8(""), samplingRate, 859 NULL /*updatedSamplingRate*/, format, channelMask, 860 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ? 861 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT); 862 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) { 863 return profile; 864 } 865 } 866 } 867 return 0; 868} 869 870audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream, 871 uint32_t samplingRate, 872 audio_format_t format, 873 audio_channel_mask_t channelMask, 874 audio_output_flags_t flags, 875 const audio_offload_info_t *offloadInfo) 876{ 877 routing_strategy strategy = getStrategy(stream); 878 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/); 879 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x", 880 device, stream, samplingRate, format, channelMask, flags); 881 882 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE, 883 stream, samplingRate,format, channelMask, 884 flags, offloadInfo); 885} 886 887status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr, 888 audio_io_handle_t *output, 889 audio_session_t session, 890 audio_stream_type_t *stream, 891 uint32_t samplingRate, 892 audio_format_t format, 893 audio_channel_mask_t channelMask, 894 audio_output_flags_t flags, 895 const audio_offload_info_t *offloadInfo) 896{ 897 audio_attributes_t attributes; 898 if (attr != NULL) { 899 if (!isValidAttributes(attr)) { 900 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]", 901 attr->usage, attr->content_type, attr->flags, 902 attr->tags); 903 return BAD_VALUE; 904 } 905 attributes = *attr; 906 } else { 907 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) { 908 ALOGE("getOutputForAttr(): invalid stream type"); 909 return BAD_VALUE; 910 } 911 stream_type_to_audio_attributes(*stream, &attributes); 912 } 913 914 for (size_t i = 0; i < mPolicyMixes.size(); i++) { 915 sp<AudioOutputDescriptor> desc; 916 if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_PLAYERS) { 917 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) { 918 if ((RULE_MATCH_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule && 919 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage == attributes.usage) || 920 (RULE_EXCLUDE_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule && 921 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage != attributes.usage)) { 922 desc = mPolicyMixes[i]->mOutput; 923 break; 924 } 925 if (strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 && 926 strncmp(attributes.tags + strlen("addr="), 927 mPolicyMixes[i]->mMix.mRegistrationId.string(), 928 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) { 929 desc = mPolicyMixes[i]->mOutput; 930 break; 931 } 932 } 933 } else if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_RECORDERS) { 934 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE && 935 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 && 936 strncmp(attributes.tags + strlen("addr="), 937 mPolicyMixes[i]->mMix.mRegistrationId.string(), 938 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) { 939 desc = mPolicyMixes[i]->mOutput; 940 } 941 } 942 if (desc != 0) { 943 if (!audio_is_linear_pcm(format)) { 944 return BAD_VALUE; 945 } 946 desc->mPolicyMix = &mPolicyMixes[i]->mMix; 947 *stream = streamTypefromAttributesInt(&attributes); 948 *output = desc->mIoHandle; 949 ALOGV("getOutputForAttr() returns output %d", *output); 950 return NO_ERROR; 951 } 952 } 953 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) { 954 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE"); 955 return BAD_VALUE; 956 } 957 958 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x", 959 attributes.usage, attributes.content_type, attributes.tags, attributes.flags); 960 961 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes); 962 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/); 963 964 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) { 965 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC); 966 } 967 968 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x", 969 device, samplingRate, format, channelMask, flags); 970 971 *stream = streamTypefromAttributesInt(&attributes); 972 *output = getOutputForDevice(device, session, *stream, 973 samplingRate, format, channelMask, 974 flags, offloadInfo); 975 if (*output == AUDIO_IO_HANDLE_NONE) { 976 return INVALID_OPERATION; 977 } 978 return NO_ERROR; 979} 980 981audio_io_handle_t AudioPolicyManager::getOutputForDevice( 982 audio_devices_t device, 983 audio_session_t session __unused, 984 audio_stream_type_t stream, 985 uint32_t samplingRate, 986 audio_format_t format, 987 audio_channel_mask_t channelMask, 988 audio_output_flags_t flags, 989 const audio_offload_info_t *offloadInfo) 990{ 991 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE; 992 uint32_t latency = 0; 993 status_t status; 994 995#ifdef AUDIO_POLICY_TEST 996 if (mCurOutput != 0) { 997 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d", 998 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput); 999 1000 if (mTestOutputs[mCurOutput] == 0) { 1001 ALOGV("getOutput() opening test output"); 1002 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL); 1003 outputDesc->mDevice = mTestDevice; 1004 outputDesc->mLatency = mTestLatencyMs; 1005 outputDesc->mFlags = 1006 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0); 1007 outputDesc->mRefCount[stream] = 0; 1008 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 1009 config.sample_rate = mTestSamplingRate; 1010 config.channel_mask = mTestChannels; 1011 config.format = mTestFormat; 1012 if (offloadInfo != NULL) { 1013 config.offload_info = *offloadInfo; 1014 } 1015 status = mpClientInterface->openOutput(0, 1016 &mTestOutputs[mCurOutput], 1017 &config, 1018 &outputDesc->mDevice, 1019 String8(""), 1020 &outputDesc->mLatency, 1021 outputDesc->mFlags); 1022 if (status == NO_ERROR) { 1023 outputDesc->mSamplingRate = config.sample_rate; 1024 outputDesc->mFormat = config.format; 1025 outputDesc->mChannelMask = config.channel_mask; 1026 AudioParameter outputCmd = AudioParameter(); 1027 outputCmd.addInt(String8("set_id"),mCurOutput); 1028 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString()); 1029 addOutput(mTestOutputs[mCurOutput], outputDesc); 1030 } 1031 } 1032 return mTestOutputs[mCurOutput]; 1033 } 1034#endif //AUDIO_POLICY_TEST 1035 1036 // open a direct output if required by specified parameters 1037 //force direct flag if offload flag is set: offloading implies a direct output stream 1038 // and all common behaviors are driven by checking only the direct flag 1039 // this should normally be set appropriately in the policy configuration file 1040 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) { 1041 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT); 1042 } 1043 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) { 1044 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT); 1045 } 1046 // only allow deep buffering for music stream type 1047 if (stream != AUDIO_STREAM_MUSIC) { 1048 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER); 1049 } 1050 1051 sp<IOProfile> profile; 1052 1053 // skip direct output selection if the request can obviously be attached to a mixed output 1054 // and not explicitly requested 1055 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && 1056 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE && 1057 audio_channel_count_from_out_mask(channelMask) <= 2) { 1058 goto non_direct_output; 1059 } 1060 1061 // Do not allow offloading if one non offloadable effect is enabled. This prevents from 1062 // creating an offloaded track and tearing it down immediately after start when audioflinger 1063 // detects there is an active non offloadable effect. 1064 // FIXME: We should check the audio session here but we do not have it in this context. 1065 // This may prevent offloading in rare situations where effects are left active by apps 1066 // in the background. 1067 1068 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) || 1069 !isNonOffloadableEffectEnabled()) { 1070 profile = getProfileForDirectOutput(device, 1071 samplingRate, 1072 format, 1073 channelMask, 1074 (audio_output_flags_t)flags); 1075 } 1076 1077 if (profile != 0) { 1078 sp<AudioOutputDescriptor> outputDesc = NULL; 1079 1080 for (size_t i = 0; i < mOutputs.size(); i++) { 1081 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 1082 if (!desc->isDuplicated() && (profile == desc->mProfile)) { 1083 outputDesc = desc; 1084 // reuse direct output if currently open and configured with same parameters 1085 if ((samplingRate == outputDesc->mSamplingRate) && 1086 (format == outputDesc->mFormat) && 1087 (channelMask == outputDesc->mChannelMask)) { 1088 outputDesc->mDirectOpenCount++; 1089 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i)); 1090 return mOutputs.keyAt(i); 1091 } 1092 } 1093 } 1094 // close direct output if currently open and configured with different parameters 1095 if (outputDesc != NULL) { 1096 closeOutput(outputDesc->mIoHandle); 1097 } 1098 outputDesc = new AudioOutputDescriptor(profile); 1099 outputDesc->mDevice = device; 1100 outputDesc->mLatency = 0; 1101 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags); 1102 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 1103 config.sample_rate = samplingRate; 1104 config.channel_mask = channelMask; 1105 config.format = format; 1106 if (offloadInfo != NULL) { 1107 config.offload_info = *offloadInfo; 1108 } 1109 status = mpClientInterface->openOutput(profile->mModule->mHandle, 1110 &output, 1111 &config, 1112 &outputDesc->mDevice, 1113 String8(""), 1114 &outputDesc->mLatency, 1115 outputDesc->mFlags); 1116 1117 // only accept an output with the requested parameters 1118 if (status != NO_ERROR || 1119 (samplingRate != 0 && samplingRate != config.sample_rate) || 1120 (format != AUDIO_FORMAT_DEFAULT && format != config.format) || 1121 (channelMask != 0 && channelMask != config.channel_mask)) { 1122 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d," 1123 "format %d %d, channelMask %04x %04x", output, samplingRate, 1124 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask, 1125 outputDesc->mChannelMask); 1126 if (output != AUDIO_IO_HANDLE_NONE) { 1127 mpClientInterface->closeOutput(output); 1128 } 1129 // fall back to mixer output if possible when the direct output could not be open 1130 if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE) { 1131 goto non_direct_output; 1132 } 1133 return AUDIO_IO_HANDLE_NONE; 1134 } 1135 outputDesc->mSamplingRate = config.sample_rate; 1136 outputDesc->mChannelMask = config.channel_mask; 1137 outputDesc->mFormat = config.format; 1138 outputDesc->mRefCount[stream] = 0; 1139 outputDesc->mStopTime[stream] = 0; 1140 outputDesc->mDirectOpenCount = 1; 1141 1142 audio_io_handle_t srcOutput = getOutputForEffect(); 1143 addOutput(output, outputDesc); 1144 audio_io_handle_t dstOutput = getOutputForEffect(); 1145 if (dstOutput == output) { 1146 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput); 1147 } 1148 mPreviousOutputs = mOutputs; 1149 ALOGV("getOutput() returns new direct output %d", output); 1150 mpClientInterface->onAudioPortListUpdate(); 1151 return output; 1152 } 1153 1154non_direct_output: 1155 1156 // ignoring channel mask due to downmix capability in mixer 1157 1158 // open a non direct output 1159 1160 // for non direct outputs, only PCM is supported 1161 if (audio_is_linear_pcm(format)) { 1162 // get which output is suitable for the specified stream. The actual 1163 // routing change will happen when startOutput() will be called 1164 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs); 1165 1166 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier 1167 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT); 1168 output = selectOutput(outputs, flags, format); 1169 } 1170 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d," 1171 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags); 1172 1173 ALOGV("getOutput() returns output %d", output); 1174 1175 return output; 1176} 1177 1178audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs, 1179 audio_output_flags_t flags, 1180 audio_format_t format) 1181{ 1182 // select one output among several that provide a path to a particular device or set of 1183 // devices (the list was previously build by getOutputsForDevice()). 1184 // The priority is as follows: 1185 // 1: the output with the highest number of requested policy flags 1186 // 2: the primary output 1187 // 3: the first output in the list 1188 1189 if (outputs.size() == 0) { 1190 return 0; 1191 } 1192 if (outputs.size() == 1) { 1193 return outputs[0]; 1194 } 1195 1196 int maxCommonFlags = 0; 1197 audio_io_handle_t outputFlags = 0; 1198 audio_io_handle_t outputPrimary = 0; 1199 1200 for (size_t i = 0; i < outputs.size(); i++) { 1201 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]); 1202 if (!outputDesc->isDuplicated()) { 1203 // if a valid format is specified, skip output if not compatible 1204 if (format != AUDIO_FORMAT_INVALID) { 1205 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) { 1206 if (format != outputDesc->mFormat) { 1207 continue; 1208 } 1209 } else if (!audio_is_linear_pcm(format)) { 1210 continue; 1211 } 1212 } 1213 1214 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags); 1215 if (commonFlags > maxCommonFlags) { 1216 outputFlags = outputs[i]; 1217 maxCommonFlags = commonFlags; 1218 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags); 1219 } 1220 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) { 1221 outputPrimary = outputs[i]; 1222 } 1223 } 1224 } 1225 1226 if (outputFlags != 0) { 1227 return outputFlags; 1228 } 1229 if (outputPrimary != 0) { 1230 return outputPrimary; 1231 } 1232 1233 return outputs[0]; 1234} 1235 1236status_t AudioPolicyManager::startOutput(audio_io_handle_t output, 1237 audio_stream_type_t stream, 1238 audio_session_t session) 1239{ 1240 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session); 1241 ssize_t index = mOutputs.indexOfKey(output); 1242 if (index < 0) { 1243 ALOGW("startOutput() unknown output %d", output); 1244 return BAD_VALUE; 1245 } 1246 1247 // cannot start playback of STREAM_TTS if any other output is being used 1248 uint32_t beaconMuteLatency = 0; 1249 if (stream == AUDIO_STREAM_TTS) { 1250 ALOGV("\t found BEACON stream"); 1251 if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) { 1252 return INVALID_OPERATION; 1253 } else { 1254 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON); 1255 } 1256 } else { 1257 // some playback other than beacon starts 1258 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT); 1259 } 1260 1261 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index); 1262 1263 // increment usage count for this stream on the requested output: 1264 // NOTE that the usage count is the same for duplicated output and hardware output which is 1265 // necessary for a correct control of hardware output routing by startOutput() and stopOutput() 1266 outputDesc->changeRefCount(stream, 1); 1267 1268 if (outputDesc->mRefCount[stream] == 1) { 1269 // starting an output being rerouted? 1270 audio_devices_t newDevice; 1271 if (outputDesc->mPolicyMix != NULL) { 1272 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX; 1273 } else { 1274 newDevice = getNewOutputDevice(output, false /*fromCache*/); 1275 } 1276 routing_strategy strategy = getStrategy(stream); 1277 bool shouldWait = (strategy == STRATEGY_SONIFICATION) || 1278 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) || 1279 (beaconMuteLatency > 0); 1280 uint32_t waitMs = beaconMuteLatency; 1281 bool force = false; 1282 for (size_t i = 0; i < mOutputs.size(); i++) { 1283 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 1284 if (desc != outputDesc) { 1285 // force a device change if any other output is managed by the same hw 1286 // module and has a current device selection that differs from selected device. 1287 // In this case, the audio HAL must receive the new device selection so that it can 1288 // change the device currently selected by the other active output. 1289 if (outputDesc->sharesHwModuleWith(desc) && 1290 desc->device() != newDevice) { 1291 force = true; 1292 } 1293 // wait for audio on other active outputs to be presented when starting 1294 // a notification so that audio focus effect can propagate, or that a mute/unmute 1295 // event occurred for beacon 1296 uint32_t latency = desc->latency(); 1297 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) { 1298 waitMs = latency; 1299 } 1300 } 1301 } 1302 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force); 1303 1304 // handle special case for sonification while in call 1305 if (isInCall()) { 1306 handleIncallSonification(stream, true, false); 1307 } 1308 1309 // apply volume rules for current stream and device if necessary 1310 checkAndSetVolume(stream, 1311 mStreams[stream].getVolumeIndex(newDevice), 1312 output, 1313 newDevice); 1314 1315 // update the outputs if starting an output with a stream that can affect notification 1316 // routing 1317 handleNotificationRoutingForStream(stream); 1318 1319 // Automatically enable the remote submix input when output is started on a re routing mix 1320 // of type MIX_TYPE_RECORDERS 1321 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL && 1322 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) { 1323 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX, 1324 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, 1325 outputDesc->mPolicyMix->mRegistrationId); 1326 } 1327 1328 // force reevaluating accessibility routing when ringtone or alarm starts 1329 if (strategy == STRATEGY_SONIFICATION) { 1330 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY); 1331 } 1332 1333 if (waitMs > muteWaitMs) { 1334 usleep((waitMs - muteWaitMs) * 2 * 1000); 1335 } 1336 } 1337 return NO_ERROR; 1338} 1339 1340 1341status_t AudioPolicyManager::stopOutput(audio_io_handle_t output, 1342 audio_stream_type_t stream, 1343 audio_session_t session) 1344{ 1345 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session); 1346 ssize_t index = mOutputs.indexOfKey(output); 1347 if (index < 0) { 1348 ALOGW("stopOutput() unknown output %d", output); 1349 return BAD_VALUE; 1350 } 1351 1352 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index); 1353 1354 // always handle stream stop, check which stream type is stopping 1355 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT); 1356 1357 // handle special case for sonification while in call 1358 if (isInCall()) { 1359 handleIncallSonification(stream, false, false); 1360 } 1361 1362 if (outputDesc->mRefCount[stream] > 0) { 1363 // decrement usage count of this stream on the output 1364 outputDesc->changeRefCount(stream, -1); 1365 // store time at which the stream was stopped - see isStreamActive() 1366 if (outputDesc->mRefCount[stream] == 0) { 1367 // Automatically disable the remote submix input when output is stopped on a 1368 // re routing mix of type MIX_TYPE_RECORDERS 1369 if (audio_is_remote_submix_device(outputDesc->mDevice) && 1370 outputDesc->mPolicyMix != NULL && 1371 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) { 1372 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX, 1373 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, 1374 outputDesc->mPolicyMix->mRegistrationId); 1375 } 1376 1377 outputDesc->mStopTime[stream] = systemTime(); 1378 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/); 1379 // delay the device switch by twice the latency because stopOutput() is executed when 1380 // the track stop() command is received and at that time the audio track buffer can 1381 // still contain data that needs to be drained. The latency only covers the audio HAL 1382 // and kernel buffers. Also the latency does not always include additional delay in the 1383 // audio path (audio DSP, CODEC ...) 1384 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2); 1385 1386 // force restoring the device selection on other active outputs if it differs from the 1387 // one being selected for this output 1388 for (size_t i = 0; i < mOutputs.size(); i++) { 1389 audio_io_handle_t curOutput = mOutputs.keyAt(i); 1390 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 1391 if (curOutput != output && 1392 desc->isActive() && 1393 outputDesc->sharesHwModuleWith(desc) && 1394 (newDevice != desc->device())) { 1395 setOutputDevice(curOutput, 1396 getNewOutputDevice(curOutput, false /*fromCache*/), 1397 true, 1398 outputDesc->mLatency*2); 1399 } 1400 } 1401 // update the outputs if stopping one with a stream that can affect notification routing 1402 handleNotificationRoutingForStream(stream); 1403 } 1404 return NO_ERROR; 1405 } else { 1406 ALOGW("stopOutput() refcount is already 0 for output %d", output); 1407 return INVALID_OPERATION; 1408 } 1409} 1410 1411void AudioPolicyManager::releaseOutput(audio_io_handle_t output, 1412 audio_stream_type_t stream __unused, 1413 audio_session_t session __unused) 1414{ 1415 ALOGV("releaseOutput() %d", output); 1416 ssize_t index = mOutputs.indexOfKey(output); 1417 if (index < 0) { 1418 ALOGW("releaseOutput() releasing unknown output %d", output); 1419 return; 1420 } 1421 1422#ifdef AUDIO_POLICY_TEST 1423 int testIndex = testOutputIndex(output); 1424 if (testIndex != 0) { 1425 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index); 1426 if (outputDesc->isActive()) { 1427 mpClientInterface->closeOutput(output); 1428 mOutputs.removeItem(output); 1429 mTestOutputs[testIndex] = 0; 1430 } 1431 return; 1432 } 1433#endif //AUDIO_POLICY_TEST 1434 1435 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index); 1436 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) { 1437 if (desc->mDirectOpenCount <= 0) { 1438 ALOGW("releaseOutput() invalid open count %d for output %d", 1439 desc->mDirectOpenCount, output); 1440 return; 1441 } 1442 if (--desc->mDirectOpenCount == 0) { 1443 closeOutput(output); 1444 // If effects where present on the output, audioflinger moved them to the primary 1445 // output by default: move them back to the appropriate output. 1446 audio_io_handle_t dstOutput = getOutputForEffect(); 1447 if (dstOutput != mPrimaryOutput) { 1448 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput); 1449 } 1450 mpClientInterface->onAudioPortListUpdate(); 1451 } 1452 } 1453} 1454 1455 1456status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr, 1457 audio_io_handle_t *input, 1458 audio_session_t session, 1459 uint32_t samplingRate, 1460 audio_format_t format, 1461 audio_channel_mask_t channelMask, 1462 audio_input_flags_t flags, 1463 input_type_t *inputType) 1464{ 1465 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x," 1466 "session %d, flags %#x", 1467 attr->source, samplingRate, format, channelMask, session, flags); 1468 1469 *input = AUDIO_IO_HANDLE_NONE; 1470 *inputType = API_INPUT_INVALID; 1471 audio_devices_t device; 1472 // handle legacy remote submix case where the address was not always specified 1473 String8 address = String8(""); 1474 bool isSoundTrigger = false; 1475 audio_source_t inputSource = attr->source; 1476 audio_source_t halInputSource; 1477 AudioMix *policyMix = NULL; 1478 1479 if (inputSource == AUDIO_SOURCE_DEFAULT) { 1480 inputSource = AUDIO_SOURCE_MIC; 1481 } 1482 halInputSource = inputSource; 1483 1484 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX && 1485 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) { 1486 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX; 1487 address = String8(attr->tags + strlen("addr=")); 1488 ssize_t index = mPolicyMixes.indexOfKey(address); 1489 if (index < 0) { 1490 ALOGW("getInputForAttr() no policy for address %s", address.string()); 1491 return BAD_VALUE; 1492 } 1493 if (mPolicyMixes[index]->mMix.mMixType != MIX_TYPE_PLAYERS) { 1494 ALOGW("getInputForAttr() bad policy mix type for address %s", address.string()); 1495 return BAD_VALUE; 1496 } 1497 policyMix = &mPolicyMixes[index]->mMix; 1498 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE; 1499 } else { 1500 device = getDeviceAndMixForInputSource(inputSource, &policyMix); 1501 if (device == AUDIO_DEVICE_NONE) { 1502 ALOGW("getInputForAttr() could not find device for source %d", inputSource); 1503 return BAD_VALUE; 1504 } 1505 if (policyMix != NULL) { 1506 address = policyMix->mRegistrationId; 1507 if (policyMix->mMixType == MIX_TYPE_RECORDERS) { 1508 // there is an external policy, but this input is attached to a mix of recorders, 1509 // meaning it receives audio injected into the framework, so the recorder doesn't 1510 // know about it and is therefore considered "legacy" 1511 *inputType = API_INPUT_LEGACY; 1512 } else { 1513 // recording a mix of players defined by an external policy, we're rerouting for 1514 // an external policy 1515 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE; 1516 } 1517 } else if (audio_is_remote_submix_device(device)) { 1518 address = String8("0"); 1519 *inputType = API_INPUT_MIX_CAPTURE; 1520 } else { 1521 *inputType = API_INPUT_LEGACY; 1522 } 1523 // adapt channel selection to input source 1524 switch (inputSource) { 1525 case AUDIO_SOURCE_VOICE_UPLINK: 1526 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK; 1527 break; 1528 case AUDIO_SOURCE_VOICE_DOWNLINK: 1529 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK; 1530 break; 1531 case AUDIO_SOURCE_VOICE_CALL: 1532 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK; 1533 break; 1534 default: 1535 break; 1536 } 1537 if (inputSource == AUDIO_SOURCE_HOTWORD) { 1538 ssize_t index = mSoundTriggerSessions.indexOfKey(session); 1539 if (index >= 0) { 1540 *input = mSoundTriggerSessions.valueFor(session); 1541 isSoundTrigger = true; 1542 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD); 1543 ALOGV("SoundTrigger capture on session %d input %d", session, *input); 1544 } else { 1545 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION; 1546 } 1547 } 1548 } 1549 1550 sp<IOProfile> profile = getInputProfile(device, address, 1551 samplingRate, format, channelMask, 1552 flags); 1553 if (profile == 0) { 1554 //retry without flags 1555 audio_input_flags_t log_flags = flags; 1556 flags = AUDIO_INPUT_FLAG_NONE; 1557 profile = getInputProfile(device, address, 1558 samplingRate, format, channelMask, 1559 flags); 1560 if (profile == 0) { 1561 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u," 1562 "format %#x, channelMask 0x%X, flags %#x", 1563 device, samplingRate, format, channelMask, log_flags); 1564 return BAD_VALUE; 1565 } 1566 } 1567 1568 if (profile->mModule->mHandle == 0) { 1569 ALOGE("getInputForAttr(): HW module %s not opened", profile->mModule->mName); 1570 return NO_INIT; 1571 } 1572 1573 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 1574 config.sample_rate = samplingRate; 1575 config.channel_mask = channelMask; 1576 config.format = format; 1577 1578 status_t status = mpClientInterface->openInput(profile->mModule->mHandle, 1579 input, 1580 &config, 1581 &device, 1582 address, 1583 halInputSource, 1584 flags); 1585 1586 // only accept input with the exact requested set of parameters 1587 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE || 1588 (samplingRate != config.sample_rate) || 1589 (format != config.format) || 1590 (channelMask != config.channel_mask)) { 1591 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d, channelMask %x", 1592 samplingRate, format, channelMask); 1593 if (*input != AUDIO_IO_HANDLE_NONE) { 1594 mpClientInterface->closeInput(*input); 1595 } 1596 return BAD_VALUE; 1597 } 1598 1599 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile); 1600 inputDesc->mInputSource = inputSource; 1601 inputDesc->mRefCount = 0; 1602 inputDesc->mOpenRefCount = 1; 1603 inputDesc->mSamplingRate = samplingRate; 1604 inputDesc->mFormat = format; 1605 inputDesc->mChannelMask = channelMask; 1606 inputDesc->mDevice = device; 1607 inputDesc->mSessions.add(session); 1608 inputDesc->mIsSoundTrigger = isSoundTrigger; 1609 inputDesc->mPolicyMix = policyMix; 1610 1611 ALOGV("getInputForAttr() returns input type = %d", inputType); 1612 1613 addInput(*input, inputDesc); 1614 mpClientInterface->onAudioPortListUpdate(); 1615 return NO_ERROR; 1616} 1617 1618status_t AudioPolicyManager::startInput(audio_io_handle_t input, 1619 audio_session_t session) 1620{ 1621 ALOGV("startInput() input %d", input); 1622 ssize_t index = mInputs.indexOfKey(input); 1623 if (index < 0) { 1624 ALOGW("startInput() unknown input %d", input); 1625 return BAD_VALUE; 1626 } 1627 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index); 1628 1629 index = inputDesc->mSessions.indexOf(session); 1630 if (index < 0) { 1631 ALOGW("startInput() unknown session %d on input %d", session, input); 1632 return BAD_VALUE; 1633 } 1634 1635 // virtual input devices are compatible with other input devices 1636 if (!isVirtualInputDevice(inputDesc->mDevice)) { 1637 1638 // for a non-virtual input device, check if there is another (non-virtual) active input 1639 audio_io_handle_t activeInput = getActiveInput(); 1640 if (activeInput != 0 && activeInput != input) { 1641 1642 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed, 1643 // otherwise the active input continues and the new input cannot be started. 1644 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput); 1645 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) { 1646 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput); 1647 stopInput(activeInput, activeDesc->mSessions.itemAt(0)); 1648 releaseInput(activeInput, activeDesc->mSessions.itemAt(0)); 1649 } else { 1650 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput); 1651 return INVALID_OPERATION; 1652 } 1653 } 1654 } 1655 1656 if (inputDesc->mRefCount == 0) { 1657 if (activeInputsCount() == 0) { 1658 SoundTrigger::setCaptureState(true); 1659 } 1660 setInputDevice(input, getNewInputDevice(input), true /* force */); 1661 1662 // automatically enable the remote submix output when input is started if not 1663 // used by a policy mix of type MIX_TYPE_RECORDERS 1664 // For remote submix (a virtual device), we open only one input per capture request. 1665 if (audio_is_remote_submix_device(inputDesc->mDevice)) { 1666 String8 address = String8(""); 1667 if (inputDesc->mPolicyMix == NULL) { 1668 address = String8("0"); 1669 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) { 1670 address = inputDesc->mPolicyMix->mRegistrationId; 1671 } 1672 if (address != "") { 1673 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, 1674 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, 1675 address); 1676 } 1677 } 1678 } 1679 1680 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource); 1681 1682 inputDesc->mRefCount++; 1683 return NO_ERROR; 1684} 1685 1686status_t AudioPolicyManager::stopInput(audio_io_handle_t input, 1687 audio_session_t session) 1688{ 1689 ALOGV("stopInput() input %d", input); 1690 ssize_t index = mInputs.indexOfKey(input); 1691 if (index < 0) { 1692 ALOGW("stopInput() unknown input %d", input); 1693 return BAD_VALUE; 1694 } 1695 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index); 1696 1697 index = inputDesc->mSessions.indexOf(session); 1698 if (index < 0) { 1699 ALOGW("stopInput() unknown session %d on input %d", session, input); 1700 return BAD_VALUE; 1701 } 1702 1703 if (inputDesc->mRefCount == 0) { 1704 ALOGW("stopInput() input %d already stopped", input); 1705 return INVALID_OPERATION; 1706 } 1707 1708 inputDesc->mRefCount--; 1709 if (inputDesc->mRefCount == 0) { 1710 1711 // automatically disable the remote submix output when input is stopped if not 1712 // used by a policy mix of type MIX_TYPE_RECORDERS 1713 if (audio_is_remote_submix_device(inputDesc->mDevice)) { 1714 String8 address = String8(""); 1715 if (inputDesc->mPolicyMix == NULL) { 1716 address = String8("0"); 1717 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) { 1718 address = inputDesc->mPolicyMix->mRegistrationId; 1719 } 1720 if (address != "") { 1721 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, 1722 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, 1723 address); 1724 } 1725 } 1726 1727 resetInputDevice(input); 1728 1729 if (activeInputsCount() == 0) { 1730 SoundTrigger::setCaptureState(false); 1731 } 1732 } 1733 return NO_ERROR; 1734} 1735 1736void AudioPolicyManager::releaseInput(audio_io_handle_t input, 1737 audio_session_t session) 1738{ 1739 ALOGV("releaseInput() %d", input); 1740 ssize_t index = mInputs.indexOfKey(input); 1741 if (index < 0) { 1742 ALOGW("releaseInput() releasing unknown input %d", input); 1743 return; 1744 } 1745 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index); 1746 ALOG_ASSERT(inputDesc != 0); 1747 1748 index = inputDesc->mSessions.indexOf(session); 1749 if (index < 0) { 1750 ALOGW("releaseInput() unknown session %d on input %d", session, input); 1751 return; 1752 } 1753 inputDesc->mSessions.remove(session); 1754 if (inputDesc->mOpenRefCount == 0) { 1755 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount); 1756 return; 1757 } 1758 inputDesc->mOpenRefCount--; 1759 if (inputDesc->mOpenRefCount > 0) { 1760 ALOGV("releaseInput() exit > 0"); 1761 return; 1762 } 1763 1764 closeInput(input); 1765 mpClientInterface->onAudioPortListUpdate(); 1766 ALOGV("releaseInput() exit"); 1767} 1768 1769void AudioPolicyManager::closeAllInputs() { 1770 bool patchRemoved = false; 1771 1772 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) { 1773 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index); 1774 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle); 1775 if (patch_index >= 0) { 1776 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index); 1777 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 1778 mAudioPatches.removeItemsAt(patch_index); 1779 patchRemoved = true; 1780 } 1781 mpClientInterface->closeInput(mInputs.keyAt(input_index)); 1782 } 1783 mInputs.clear(); 1784 nextAudioPortGeneration(); 1785 1786 if (patchRemoved) { 1787 mpClientInterface->onAudioPatchListUpdate(); 1788 } 1789} 1790 1791void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, 1792 int indexMin, 1793 int indexMax) 1794{ 1795 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax); 1796 if (indexMin < 0 || indexMin >= indexMax) { 1797 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax); 1798 return; 1799 } 1800 mStreams[stream].mIndexMin = indexMin; 1801 mStreams[stream].mIndexMax = indexMax; 1802 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now 1803 if (stream == AUDIO_STREAM_MUSIC) { 1804 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin; 1805 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax; 1806 } 1807} 1808 1809status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream, 1810 int index, 1811 audio_devices_t device) 1812{ 1813 1814 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) { 1815 return BAD_VALUE; 1816 } 1817 if (!audio_is_output_device(device)) { 1818 return BAD_VALUE; 1819 } 1820 1821 // Force max volume if stream cannot be muted 1822 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax; 1823 1824 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d", 1825 stream, device, index); 1826 1827 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and 1828 // clear all device specific values 1829 if (device == AUDIO_DEVICE_OUT_DEFAULT) { 1830 mStreams[stream].mIndexCur.clear(); 1831 } 1832 mStreams[stream].mIndexCur.add(device, index); 1833 1834 // update volume on all outputs whose current device is also selected by the same 1835 // strategy as the device specified by the caller 1836 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/); 1837 1838 1839 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now 1840 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE; 1841 if (stream == AUDIO_STREAM_MUSIC) { 1842 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index); 1843 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/); 1844 } 1845 if ((device != AUDIO_DEVICE_OUT_DEFAULT) && 1846 (device & (strategyDevice | accessibilityDevice)) == 0) { 1847 return NO_ERROR; 1848 } 1849 status_t status = NO_ERROR; 1850 for (size_t i = 0; i < mOutputs.size(); i++) { 1851 audio_devices_t curDevice = 1852 getDeviceForVolume(mOutputs.valueAt(i)->device()); 1853 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) { 1854 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice); 1855 if (volStatus != NO_ERROR) { 1856 status = volStatus; 1857 } 1858 } 1859 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) { 1860 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY, 1861 index, mOutputs.keyAt(i), curDevice); 1862 } 1863 } 1864 return status; 1865} 1866 1867status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream, 1868 int *index, 1869 audio_devices_t device) 1870{ 1871 if (index == NULL) { 1872 return BAD_VALUE; 1873 } 1874 if (!audio_is_output_device(device)) { 1875 return BAD_VALUE; 1876 } 1877 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to 1878 // the strategy the stream belongs to. 1879 if (device == AUDIO_DEVICE_OUT_DEFAULT) { 1880 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/); 1881 } 1882 device = getDeviceForVolume(device); 1883 1884 *index = mStreams[stream].getVolumeIndex(device); 1885 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index); 1886 return NO_ERROR; 1887} 1888 1889audio_io_handle_t AudioPolicyManager::selectOutputForEffects( 1890 const SortedVector<audio_io_handle_t>& outputs) 1891{ 1892 // select one output among several suitable for global effects. 1893 // The priority is as follows: 1894 // 1: An offloaded output. If the effect ends up not being offloadable, 1895 // AudioFlinger will invalidate the track and the offloaded output 1896 // will be closed causing the effect to be moved to a PCM output. 1897 // 2: A deep buffer output 1898 // 3: the first output in the list 1899 1900 if (outputs.size() == 0) { 1901 return 0; 1902 } 1903 1904 audio_io_handle_t outputOffloaded = 0; 1905 audio_io_handle_t outputDeepBuffer = 0; 1906 1907 for (size_t i = 0; i < outputs.size(); i++) { 1908 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]); 1909 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags); 1910 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) { 1911 outputOffloaded = outputs[i]; 1912 } 1913 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) { 1914 outputDeepBuffer = outputs[i]; 1915 } 1916 } 1917 1918 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d", 1919 outputOffloaded, outputDeepBuffer); 1920 if (outputOffloaded != 0) { 1921 return outputOffloaded; 1922 } 1923 if (outputDeepBuffer != 0) { 1924 return outputDeepBuffer; 1925 } 1926 1927 return outputs[0]; 1928} 1929 1930audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc) 1931{ 1932 // apply simple rule where global effects are attached to the same output as MUSIC streams 1933 1934 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC); 1935 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/); 1936 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs); 1937 1938 audio_io_handle_t output = selectOutputForEffects(dstOutputs); 1939 ALOGV("getOutputForEffect() got output %d for fx %s flags %x", 1940 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags); 1941 1942 return output; 1943} 1944 1945status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc, 1946 audio_io_handle_t io, 1947 uint32_t strategy, 1948 int session, 1949 int id) 1950{ 1951 ssize_t index = mOutputs.indexOfKey(io); 1952 if (index < 0) { 1953 index = mInputs.indexOfKey(io); 1954 if (index < 0) { 1955 ALOGW("registerEffect() unknown io %d", io); 1956 return INVALID_OPERATION; 1957 } 1958 } 1959 1960 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) { 1961 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB", 1962 desc->name, desc->memoryUsage); 1963 return INVALID_OPERATION; 1964 } 1965 mTotalEffectsMemory += desc->memoryUsage; 1966 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d", 1967 desc->name, io, strategy, session, id); 1968 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory); 1969 1970 sp<EffectDescriptor> effectDesc = new EffectDescriptor(); 1971 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t)); 1972 effectDesc->mIo = io; 1973 effectDesc->mStrategy = (routing_strategy)strategy; 1974 effectDesc->mSession = session; 1975 effectDesc->mEnabled = false; 1976 1977 mEffects.add(id, effectDesc); 1978 1979 return NO_ERROR; 1980} 1981 1982status_t AudioPolicyManager::unregisterEffect(int id) 1983{ 1984 ssize_t index = mEffects.indexOfKey(id); 1985 if (index < 0) { 1986 ALOGW("unregisterEffect() unknown effect ID %d", id); 1987 return INVALID_OPERATION; 1988 } 1989 1990 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index); 1991 1992 setEffectEnabled(effectDesc, false); 1993 1994 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) { 1995 ALOGW("unregisterEffect() memory %d too big for total %d", 1996 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory); 1997 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory; 1998 } 1999 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage; 2000 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d", 2001 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory); 2002 2003 mEffects.removeItem(id); 2004 2005 return NO_ERROR; 2006} 2007 2008status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled) 2009{ 2010 ssize_t index = mEffects.indexOfKey(id); 2011 if (index < 0) { 2012 ALOGW("unregisterEffect() unknown effect ID %d", id); 2013 return INVALID_OPERATION; 2014 } 2015 2016 return setEffectEnabled(mEffects.valueAt(index), enabled); 2017} 2018 2019status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled) 2020{ 2021 if (enabled == effectDesc->mEnabled) { 2022 ALOGV("setEffectEnabled(%s) effect already %s", 2023 enabled?"true":"false", enabled?"enabled":"disabled"); 2024 return INVALID_OPERATION; 2025 } 2026 2027 if (enabled) { 2028 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) { 2029 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS", 2030 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10); 2031 return INVALID_OPERATION; 2032 } 2033 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad; 2034 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad); 2035 } else { 2036 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) { 2037 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d", 2038 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad); 2039 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad; 2040 } 2041 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad; 2042 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad); 2043 } 2044 effectDesc->mEnabled = enabled; 2045 return NO_ERROR; 2046} 2047 2048bool AudioPolicyManager::isNonOffloadableEffectEnabled() 2049{ 2050 for (size_t i = 0; i < mEffects.size(); i++) { 2051 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i); 2052 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) && 2053 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) { 2054 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d", 2055 effectDesc->mDesc.name, effectDesc->mSession); 2056 return true; 2057 } 2058 } 2059 return false; 2060} 2061 2062bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const 2063{ 2064 nsecs_t sysTime = systemTime(); 2065 for (size_t i = 0; i < mOutputs.size(); i++) { 2066 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i); 2067 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) { 2068 return true; 2069 } 2070 } 2071 return false; 2072} 2073 2074bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, 2075 uint32_t inPastMs) const 2076{ 2077 nsecs_t sysTime = systemTime(); 2078 for (size_t i = 0; i < mOutputs.size(); i++) { 2079 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i); 2080 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) && 2081 outputDesc->isStreamActive(stream, inPastMs, sysTime)) { 2082 // do not consider re routing (when the output is going to a dynamic policy) 2083 // as "remote playback" 2084 if (outputDesc->mPolicyMix == NULL) { 2085 return true; 2086 } 2087 } 2088 } 2089 return false; 2090} 2091 2092bool AudioPolicyManager::isSourceActive(audio_source_t source) const 2093{ 2094 for (size_t i = 0; i < mInputs.size(); i++) { 2095 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i); 2096 if (inputDescriptor->mRefCount == 0) { 2097 continue; 2098 } 2099 if (inputDescriptor->mInputSource == (int)source) { 2100 return true; 2101 } 2102 // AUDIO_SOURCE_HOTWORD is equivalent to AUDIO_SOURCE_VOICE_RECOGNITION only if it 2103 // corresponds to an active capture triggered by a hardware hotword recognition 2104 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) && 2105 (inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD)) { 2106 // FIXME: we should not assume that the first session is the active one and keep 2107 // activity count per session. Same in startInput(). 2108 ssize_t index = mSoundTriggerSessions.indexOfKey(inputDescriptor->mSessions.itemAt(0)); 2109 if (index >= 0) { 2110 return true; 2111 } 2112 } 2113 } 2114 return false; 2115} 2116 2117// Register a list of custom mixes with their attributes and format. 2118// When a mix is registered, corresponding input and output profiles are 2119// added to the remote submix hw module. The profile contains only the 2120// parameters (sampling rate, format...) specified by the mix. 2121// The corresponding input remote submix device is also connected. 2122// 2123// When a remote submix device is connected, the address is checked to select the 2124// appropriate profile and the corresponding input or output stream is opened. 2125// 2126// When capture starts, getInputForAttr() will: 2127// - 1 look for a mix matching the address passed in attribtutes tags if any 2128// - 2 if none found, getDeviceForInputSource() will: 2129// - 2.1 look for a mix matching the attributes source 2130// - 2.2 if none found, default to device selection by policy rules 2131// At this time, the corresponding output remote submix device is also connected 2132// and active playback use cases can be transferred to this mix if needed when reconnecting 2133// after AudioTracks are invalidated 2134// 2135// When playback starts, getOutputForAttr() will: 2136// - 1 look for a mix matching the address passed in attribtutes tags if any 2137// - 2 if none found, look for a mix matching the attributes usage 2138// - 3 if none found, default to device and output selection by policy rules. 2139 2140status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes) 2141{ 2142 sp<HwModule> module; 2143 for (size_t i = 0; i < mHwModules.size(); i++) { 2144 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 && 2145 mHwModules[i]->mHandle != 0) { 2146 module = mHwModules[i]; 2147 break; 2148 } 2149 } 2150 2151 if (module == 0) { 2152 return INVALID_OPERATION; 2153 } 2154 2155 ALOGV("registerPolicyMixes() num mixes %d", mixes.size()); 2156 2157 for (size_t i = 0; i < mixes.size(); i++) { 2158 String8 address = mixes[i].mRegistrationId; 2159 ssize_t index = mPolicyMixes.indexOfKey(address); 2160 if (index >= 0) { 2161 ALOGE("registerPolicyMixes(): mix for address %s already registered", address.string()); 2162 continue; 2163 } 2164 audio_config_t outputConfig = mixes[i].mFormat; 2165 audio_config_t inputConfig = mixes[i].mFormat; 2166 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in 2167 // stereo and let audio flinger do the channel conversion if needed. 2168 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO; 2169 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO; 2170 module->addOutputProfile(address, &outputConfig, 2171 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address); 2172 module->addInputProfile(address, &inputConfig, 2173 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address); 2174 sp<AudioPolicyMix> policyMix = new AudioPolicyMix(); 2175 policyMix->mMix = mixes[i]; 2176 mPolicyMixes.add(address, policyMix); 2177 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) { 2178 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX, 2179 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, 2180 address.string()); 2181 } else { 2182 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, 2183 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, 2184 address.string()); 2185 } 2186 } 2187 return NO_ERROR; 2188} 2189 2190status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes) 2191{ 2192 sp<HwModule> module; 2193 for (size_t i = 0; i < mHwModules.size(); i++) { 2194 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 && 2195 mHwModules[i]->mHandle != 0) { 2196 module = mHwModules[i]; 2197 break; 2198 } 2199 } 2200 2201 if (module == 0) { 2202 return INVALID_OPERATION; 2203 } 2204 2205 ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size()); 2206 2207 for (size_t i = 0; i < mixes.size(); i++) { 2208 String8 address = mixes[i].mRegistrationId; 2209 ssize_t index = mPolicyMixes.indexOfKey(address); 2210 if (index < 0) { 2211 ALOGE("unregisterPolicyMixes(): mix for address %s not registered", address.string()); 2212 continue; 2213 } 2214 2215 mPolicyMixes.removeItemsAt(index); 2216 2217 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) == 2218 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) 2219 { 2220 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX, 2221 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, 2222 address.string()); 2223 } 2224 2225 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) == 2226 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) 2227 { 2228 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, 2229 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, 2230 address.string()); 2231 } 2232 module->removeOutputProfile(address); 2233 module->removeInputProfile(address); 2234 } 2235 return NO_ERROR; 2236} 2237 2238 2239status_t AudioPolicyManager::dump(int fd) 2240{ 2241 const size_t SIZE = 256; 2242 char buffer[SIZE]; 2243 String8 result; 2244 2245 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this); 2246 result.append(buffer); 2247 2248 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput); 2249 result.append(buffer); 2250 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState); 2251 result.append(buffer); 2252 snprintf(buffer, SIZE, " Force use for communications %d\n", 2253 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]); 2254 result.append(buffer); 2255 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]); 2256 result.append(buffer); 2257 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]); 2258 result.append(buffer); 2259 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]); 2260 result.append(buffer); 2261 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]); 2262 result.append(buffer); 2263 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n", 2264 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]); 2265 result.append(buffer); 2266 2267 snprintf(buffer, SIZE, " Available output devices:\n"); 2268 result.append(buffer); 2269 write(fd, result.string(), result.size()); 2270 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) { 2271 mAvailableOutputDevices[i]->dump(fd, 2, i); 2272 } 2273 snprintf(buffer, SIZE, "\n Available input devices:\n"); 2274 write(fd, buffer, strlen(buffer)); 2275 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) { 2276 mAvailableInputDevices[i]->dump(fd, 2, i); 2277 } 2278 2279 snprintf(buffer, SIZE, "\nHW Modules dump:\n"); 2280 write(fd, buffer, strlen(buffer)); 2281 for (size_t i = 0; i < mHwModules.size(); i++) { 2282 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1); 2283 write(fd, buffer, strlen(buffer)); 2284 mHwModules[i]->dump(fd); 2285 } 2286 2287 snprintf(buffer, SIZE, "\nOutputs dump:\n"); 2288 write(fd, buffer, strlen(buffer)); 2289 for (size_t i = 0; i < mOutputs.size(); i++) { 2290 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i)); 2291 write(fd, buffer, strlen(buffer)); 2292 mOutputs.valueAt(i)->dump(fd); 2293 } 2294 2295 snprintf(buffer, SIZE, "\nInputs dump:\n"); 2296 write(fd, buffer, strlen(buffer)); 2297 for (size_t i = 0; i < mInputs.size(); i++) { 2298 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i)); 2299 write(fd, buffer, strlen(buffer)); 2300 mInputs.valueAt(i)->dump(fd); 2301 } 2302 2303 snprintf(buffer, SIZE, "\nStreams dump:\n"); 2304 write(fd, buffer, strlen(buffer)); 2305 snprintf(buffer, SIZE, 2306 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n"); 2307 write(fd, buffer, strlen(buffer)); 2308 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) { 2309 snprintf(buffer, SIZE, " %02zu ", i); 2310 write(fd, buffer, strlen(buffer)); 2311 mStreams[i].dump(fd); 2312 } 2313 2314 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n", 2315 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory); 2316 write(fd, buffer, strlen(buffer)); 2317 2318 snprintf(buffer, SIZE, "Registered effects:\n"); 2319 write(fd, buffer, strlen(buffer)); 2320 for (size_t i = 0; i < mEffects.size(); i++) { 2321 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i)); 2322 write(fd, buffer, strlen(buffer)); 2323 mEffects.valueAt(i)->dump(fd); 2324 } 2325 2326 snprintf(buffer, SIZE, "\nAudio Patches:\n"); 2327 write(fd, buffer, strlen(buffer)); 2328 for (size_t i = 0; i < mAudioPatches.size(); i++) { 2329 mAudioPatches[i]->dump(fd, 2, i); 2330 } 2331 2332 return NO_ERROR; 2333} 2334 2335// This function checks for the parameters which can be offloaded. 2336// This can be enhanced depending on the capability of the DSP and policy 2337// of the system. 2338bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo) 2339{ 2340 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d," 2341 " BitRate=%u, duration=%" PRId64 " us, has_video=%d", 2342 offloadInfo.sample_rate, offloadInfo.channel_mask, 2343 offloadInfo.format, 2344 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us, 2345 offloadInfo.has_video); 2346 2347 // Check if offload has been disabled 2348 char propValue[PROPERTY_VALUE_MAX]; 2349 if (property_get("audio.offload.disable", propValue, "0")) { 2350 if (atoi(propValue) != 0) { 2351 ALOGV("offload disabled by audio.offload.disable=%s", propValue ); 2352 return false; 2353 } 2354 } 2355 2356 // Check if stream type is music, then only allow offload as of now. 2357 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC) 2358 { 2359 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false"); 2360 return false; 2361 } 2362 2363 //TODO: enable audio offloading with video when ready 2364 if (offloadInfo.has_video) 2365 { 2366 ALOGV("isOffloadSupported: has_video == true, returning false"); 2367 return false; 2368 } 2369 2370 //If duration is less than minimum value defined in property, return false 2371 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) { 2372 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) { 2373 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue); 2374 return false; 2375 } 2376 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) { 2377 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS); 2378 return false; 2379 } 2380 2381 // Do not allow offloading if one non offloadable effect is enabled. This prevents from 2382 // creating an offloaded track and tearing it down immediately after start when audioflinger 2383 // detects there is an active non offloadable effect. 2384 // FIXME: We should check the audio session here but we do not have it in this context. 2385 // This may prevent offloading in rare situations where effects are left active by apps 2386 // in the background. 2387 if (isNonOffloadableEffectEnabled()) { 2388 return false; 2389 } 2390 2391 // See if there is a profile to support this. 2392 // AUDIO_DEVICE_NONE 2393 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */, 2394 offloadInfo.sample_rate, 2395 offloadInfo.format, 2396 offloadInfo.channel_mask, 2397 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD); 2398 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT "); 2399 return (profile != 0); 2400} 2401 2402status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role, 2403 audio_port_type_t type, 2404 unsigned int *num_ports, 2405 struct audio_port *ports, 2406 unsigned int *generation) 2407{ 2408 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) || 2409 generation == NULL) { 2410 return BAD_VALUE; 2411 } 2412 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports); 2413 if (ports == NULL) { 2414 *num_ports = 0; 2415 } 2416 2417 size_t portsWritten = 0; 2418 size_t portsMax = *num_ports; 2419 *num_ports = 0; 2420 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) { 2421 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) { 2422 for (size_t i = 0; 2423 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) { 2424 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]); 2425 } 2426 *num_ports += mAvailableOutputDevices.size(); 2427 } 2428 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) { 2429 for (size_t i = 0; 2430 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) { 2431 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]); 2432 } 2433 *num_ports += mAvailableInputDevices.size(); 2434 } 2435 } 2436 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) { 2437 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) { 2438 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) { 2439 mInputs[i]->toAudioPort(&ports[portsWritten++]); 2440 } 2441 *num_ports += mInputs.size(); 2442 } 2443 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) { 2444 size_t numOutputs = 0; 2445 for (size_t i = 0; i < mOutputs.size(); i++) { 2446 if (!mOutputs[i]->isDuplicated()) { 2447 numOutputs++; 2448 if (portsWritten < portsMax) { 2449 mOutputs[i]->toAudioPort(&ports[portsWritten++]); 2450 } 2451 } 2452 } 2453 *num_ports += numOutputs; 2454 } 2455 } 2456 *generation = curAudioPortGeneration(); 2457 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports); 2458 return NO_ERROR; 2459} 2460 2461status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused) 2462{ 2463 return NO_ERROR; 2464} 2465 2466sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId( 2467 audio_port_handle_t id) const 2468{ 2469 sp<AudioOutputDescriptor> outputDesc = NULL; 2470 for (size_t i = 0; i < mOutputs.size(); i++) { 2471 outputDesc = mOutputs.valueAt(i); 2472 if (outputDesc->mId == id) { 2473 break; 2474 } 2475 } 2476 return outputDesc; 2477} 2478 2479sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId( 2480 audio_port_handle_t id) const 2481{ 2482 sp<AudioInputDescriptor> inputDesc = NULL; 2483 for (size_t i = 0; i < mInputs.size(); i++) { 2484 inputDesc = mInputs.valueAt(i); 2485 if (inputDesc->mId == id) { 2486 break; 2487 } 2488 } 2489 return inputDesc; 2490} 2491 2492sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice( 2493 audio_devices_t device) const 2494{ 2495 sp <HwModule> module; 2496 2497 for (size_t i = 0; i < mHwModules.size(); i++) { 2498 if (mHwModules[i]->mHandle == 0) { 2499 continue; 2500 } 2501 if (audio_is_output_device(device)) { 2502 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 2503 { 2504 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) { 2505 return mHwModules[i]; 2506 } 2507 } 2508 } else { 2509 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) { 2510 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() & 2511 device & ~AUDIO_DEVICE_BIT_IN) { 2512 return mHwModules[i]; 2513 } 2514 } 2515 } 2516 } 2517 return module; 2518} 2519 2520sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const 2521{ 2522 sp <HwModule> module; 2523 2524 for (size_t i = 0; i < mHwModules.size(); i++) 2525 { 2526 if (strcmp(mHwModules[i]->mName, name) == 0) { 2527 return mHwModules[i]; 2528 } 2529 } 2530 return module; 2531} 2532 2533audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices() 2534{ 2535 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput); 2536 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types(); 2537 return devices & mAvailableOutputDevices.types(); 2538} 2539 2540audio_devices_t AudioPolicyManager::availablePrimaryInputDevices() 2541{ 2542 audio_module_handle_t primaryHandle = 2543 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle; 2544 audio_devices_t devices = AUDIO_DEVICE_NONE; 2545 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) { 2546 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) { 2547 devices |= mAvailableInputDevices[i]->mDeviceType; 2548 } 2549 } 2550 return devices; 2551} 2552 2553status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch, 2554 audio_patch_handle_t *handle, 2555 uid_t uid) 2556{ 2557 ALOGV("createAudioPatch()"); 2558 2559 if (handle == NULL || patch == NULL) { 2560 return BAD_VALUE; 2561 } 2562 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks); 2563 2564 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX || 2565 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) { 2566 return BAD_VALUE; 2567 } 2568 // only one source per audio patch supported for now 2569 if (patch->num_sources > 1) { 2570 return INVALID_OPERATION; 2571 } 2572 2573 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) { 2574 return INVALID_OPERATION; 2575 } 2576 for (size_t i = 0; i < patch->num_sinks; i++) { 2577 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) { 2578 return INVALID_OPERATION; 2579 } 2580 } 2581 2582 sp<AudioPatch> patchDesc; 2583 ssize_t index = mAudioPatches.indexOfKey(*handle); 2584 2585 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id, 2586 patch->sources[0].role, 2587 patch->sources[0].type); 2588#if LOG_NDEBUG == 0 2589 for (size_t i = 0; i < patch->num_sinks; i++) { 2590 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id, 2591 patch->sinks[i].role, 2592 patch->sinks[i].type); 2593 } 2594#endif 2595 2596 if (index >= 0) { 2597 patchDesc = mAudioPatches.valueAt(index); 2598 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d", 2599 mUidCached, patchDesc->mUid, uid); 2600 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) { 2601 return INVALID_OPERATION; 2602 } 2603 } else { 2604 *handle = 0; 2605 } 2606 2607 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) { 2608 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id); 2609 if (outputDesc == NULL) { 2610 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id); 2611 return BAD_VALUE; 2612 } 2613 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports", 2614 outputDesc->mIoHandle); 2615 if (patchDesc != 0) { 2616 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) { 2617 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d", 2618 patchDesc->mPatch.sources[0].id, patch->sources[0].id); 2619 return BAD_VALUE; 2620 } 2621 } 2622 DeviceVector devices; 2623 for (size_t i = 0; i < patch->num_sinks; i++) { 2624 // Only support mix to devices connection 2625 // TODO add support for mix to mix connection 2626 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) { 2627 ALOGV("createAudioPatch() source mix but sink is not a device"); 2628 return INVALID_OPERATION; 2629 } 2630 sp<DeviceDescriptor> devDesc = 2631 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id); 2632 if (devDesc == 0) { 2633 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id); 2634 return BAD_VALUE; 2635 } 2636 2637 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType, 2638 devDesc->mAddress, 2639 patch->sources[0].sample_rate, 2640 NULL, // updatedSamplingRate 2641 patch->sources[0].format, 2642 patch->sources[0].channel_mask, 2643 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) { 2644 ALOGV("createAudioPatch() profile not supported for device %08x", 2645 devDesc->mDeviceType); 2646 return INVALID_OPERATION; 2647 } 2648 devices.add(devDesc); 2649 } 2650 if (devices.size() == 0) { 2651 return INVALID_OPERATION; 2652 } 2653 2654 // TODO: reconfigure output format and channels here 2655 ALOGV("createAudioPatch() setting device %08x on output %d", 2656 devices.types(), outputDesc->mIoHandle); 2657 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle); 2658 index = mAudioPatches.indexOfKey(*handle); 2659 if (index >= 0) { 2660 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) { 2661 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided"); 2662 } 2663 patchDesc = mAudioPatches.valueAt(index); 2664 patchDesc->mUid = uid; 2665 ALOGV("createAudioPatch() success"); 2666 } else { 2667 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch"); 2668 return INVALID_OPERATION; 2669 } 2670 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) { 2671 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) { 2672 // input device to input mix connection 2673 // only one sink supported when connecting an input device to a mix 2674 if (patch->num_sinks > 1) { 2675 return INVALID_OPERATION; 2676 } 2677 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id); 2678 if (inputDesc == NULL) { 2679 return BAD_VALUE; 2680 } 2681 if (patchDesc != 0) { 2682 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) { 2683 return BAD_VALUE; 2684 } 2685 } 2686 sp<DeviceDescriptor> devDesc = 2687 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id); 2688 if (devDesc == 0) { 2689 return BAD_VALUE; 2690 } 2691 2692 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType, 2693 devDesc->mAddress, 2694 patch->sinks[0].sample_rate, 2695 NULL, /*updatedSampleRate*/ 2696 patch->sinks[0].format, 2697 patch->sinks[0].channel_mask, 2698 // FIXME for the parameter type, 2699 // and the NONE 2700 (audio_output_flags_t) 2701 AUDIO_INPUT_FLAG_NONE)) { 2702 return INVALID_OPERATION; 2703 } 2704 // TODO: reconfigure output format and channels here 2705 ALOGV("createAudioPatch() setting device %08x on output %d", 2706 devDesc->mDeviceType, inputDesc->mIoHandle); 2707 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle); 2708 index = mAudioPatches.indexOfKey(*handle); 2709 if (index >= 0) { 2710 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) { 2711 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided"); 2712 } 2713 patchDesc = mAudioPatches.valueAt(index); 2714 patchDesc->mUid = uid; 2715 ALOGV("createAudioPatch() success"); 2716 } else { 2717 ALOGW("createAudioPatch() setInputDevice() failed to create a patch"); 2718 return INVALID_OPERATION; 2719 } 2720 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) { 2721 // device to device connection 2722 if (patchDesc != 0) { 2723 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) { 2724 return BAD_VALUE; 2725 } 2726 } 2727 sp<DeviceDescriptor> srcDeviceDesc = 2728 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id); 2729 if (srcDeviceDesc == 0) { 2730 return BAD_VALUE; 2731 } 2732 2733 //update source and sink with our own data as the data passed in the patch may 2734 // be incomplete. 2735 struct audio_patch newPatch = *patch; 2736 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]); 2737 2738 for (size_t i = 0; i < patch->num_sinks; i++) { 2739 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) { 2740 ALOGV("createAudioPatch() source device but one sink is not a device"); 2741 return INVALID_OPERATION; 2742 } 2743 2744 sp<DeviceDescriptor> sinkDeviceDesc = 2745 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id); 2746 if (sinkDeviceDesc == 0) { 2747 return BAD_VALUE; 2748 } 2749 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]); 2750 2751 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) { 2752 // only one sink supported when connected devices across HW modules 2753 if (patch->num_sinks > 1) { 2754 return INVALID_OPERATION; 2755 } 2756 SortedVector<audio_io_handle_t> outputs = 2757 getOutputsForDevice(sinkDeviceDesc->mDeviceType, 2758 mOutputs); 2759 // if the sink device is reachable via an opened output stream, request to go via 2760 // this output stream by adding a second source to the patch description 2761 audio_io_handle_t output = selectOutput(outputs, 2762 AUDIO_OUTPUT_FLAG_NONE, 2763 AUDIO_FORMAT_INVALID); 2764 if (output != AUDIO_IO_HANDLE_NONE) { 2765 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 2766 if (outputDesc->isDuplicated()) { 2767 return INVALID_OPERATION; 2768 } 2769 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]); 2770 newPatch.num_sources = 2; 2771 } 2772 } 2773 } 2774 // TODO: check from routing capabilities in config file and other conflicting patches 2775 2776 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 2777 if (index >= 0) { 2778 afPatchHandle = patchDesc->mAfPatchHandle; 2779 } 2780 2781 status_t status = mpClientInterface->createAudioPatch(&newPatch, 2782 &afPatchHandle, 2783 0); 2784 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d", 2785 status, afPatchHandle); 2786 if (status == NO_ERROR) { 2787 if (index < 0) { 2788 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(), 2789 &newPatch, uid); 2790 addAudioPatch(patchDesc->mHandle, patchDesc); 2791 } else { 2792 patchDesc->mPatch = newPatch; 2793 } 2794 patchDesc->mAfPatchHandle = afPatchHandle; 2795 *handle = patchDesc->mHandle; 2796 nextAudioPortGeneration(); 2797 mpClientInterface->onAudioPatchListUpdate(); 2798 } else { 2799 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d", 2800 status); 2801 return INVALID_OPERATION; 2802 } 2803 } else { 2804 return BAD_VALUE; 2805 } 2806 } else { 2807 return BAD_VALUE; 2808 } 2809 return NO_ERROR; 2810} 2811 2812status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, 2813 uid_t uid) 2814{ 2815 ALOGV("releaseAudioPatch() patch %d", handle); 2816 2817 ssize_t index = mAudioPatches.indexOfKey(handle); 2818 2819 if (index < 0) { 2820 return BAD_VALUE; 2821 } 2822 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 2823 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d", 2824 mUidCached, patchDesc->mUid, uid); 2825 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) { 2826 return INVALID_OPERATION; 2827 } 2828 2829 struct audio_patch *patch = &patchDesc->mPatch; 2830 patchDesc->mUid = mUidCached; 2831 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) { 2832 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id); 2833 if (outputDesc == NULL) { 2834 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id); 2835 return BAD_VALUE; 2836 } 2837 2838 setOutputDevice(outputDesc->mIoHandle, 2839 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/), 2840 true, 2841 0, 2842 NULL); 2843 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) { 2844 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) { 2845 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id); 2846 if (inputDesc == NULL) { 2847 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id); 2848 return BAD_VALUE; 2849 } 2850 setInputDevice(inputDesc->mIoHandle, 2851 getNewInputDevice(inputDesc->mIoHandle), 2852 true, 2853 NULL); 2854 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) { 2855 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle; 2856 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 2857 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d", 2858 status, patchDesc->mAfPatchHandle); 2859 removeAudioPatch(patchDesc->mHandle); 2860 nextAudioPortGeneration(); 2861 mpClientInterface->onAudioPatchListUpdate(); 2862 } else { 2863 return BAD_VALUE; 2864 } 2865 } else { 2866 return BAD_VALUE; 2867 } 2868 return NO_ERROR; 2869} 2870 2871status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches, 2872 struct audio_patch *patches, 2873 unsigned int *generation) 2874{ 2875 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) || 2876 generation == NULL) { 2877 return BAD_VALUE; 2878 } 2879 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu", 2880 *num_patches, patches, mAudioPatches.size()); 2881 if (patches == NULL) { 2882 *num_patches = 0; 2883 } 2884 2885 size_t patchesWritten = 0; 2886 size_t patchesMax = *num_patches; 2887 for (size_t i = 0; 2888 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) { 2889 patches[patchesWritten] = mAudioPatches[i]->mPatch; 2890 patches[patchesWritten++].id = mAudioPatches[i]->mHandle; 2891 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d", 2892 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks); 2893 } 2894 *num_patches = mAudioPatches.size(); 2895 2896 *generation = curAudioPortGeneration(); 2897 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches); 2898 return NO_ERROR; 2899} 2900 2901status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config) 2902{ 2903 ALOGV("setAudioPortConfig()"); 2904 2905 if (config == NULL) { 2906 return BAD_VALUE; 2907 } 2908 ALOGV("setAudioPortConfig() on port handle %d", config->id); 2909 // Only support gain configuration for now 2910 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) { 2911 return INVALID_OPERATION; 2912 } 2913 2914 sp<AudioPortConfig> audioPortConfig; 2915 if (config->type == AUDIO_PORT_TYPE_MIX) { 2916 if (config->role == AUDIO_PORT_ROLE_SOURCE) { 2917 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id); 2918 if (outputDesc == NULL) { 2919 return BAD_VALUE; 2920 } 2921 ALOG_ASSERT(!outputDesc->isDuplicated(), 2922 "setAudioPortConfig() called on duplicated output %d", 2923 outputDesc->mIoHandle); 2924 audioPortConfig = outputDesc; 2925 } else if (config->role == AUDIO_PORT_ROLE_SINK) { 2926 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id); 2927 if (inputDesc == NULL) { 2928 return BAD_VALUE; 2929 } 2930 audioPortConfig = inputDesc; 2931 } else { 2932 return BAD_VALUE; 2933 } 2934 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) { 2935 sp<DeviceDescriptor> deviceDesc; 2936 if (config->role == AUDIO_PORT_ROLE_SOURCE) { 2937 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id); 2938 } else if (config->role == AUDIO_PORT_ROLE_SINK) { 2939 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id); 2940 } else { 2941 return BAD_VALUE; 2942 } 2943 if (deviceDesc == NULL) { 2944 return BAD_VALUE; 2945 } 2946 audioPortConfig = deviceDesc; 2947 } else { 2948 return BAD_VALUE; 2949 } 2950 2951 struct audio_port_config backupConfig; 2952 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig); 2953 if (status == NO_ERROR) { 2954 struct audio_port_config newConfig; 2955 audioPortConfig->toAudioPortConfig(&newConfig, config); 2956 status = mpClientInterface->setAudioPortConfig(&newConfig, 0); 2957 } 2958 if (status != NO_ERROR) { 2959 audioPortConfig->applyAudioPortConfig(&backupConfig); 2960 } 2961 2962 return status; 2963} 2964 2965void AudioPolicyManager::clearAudioPatches(uid_t uid) 2966{ 2967 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) { 2968 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i); 2969 if (patchDesc->mUid == uid) { 2970 releaseAudioPatch(mAudioPatches.keyAt(i), uid); 2971 } 2972 } 2973} 2974 2975status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session, 2976 audio_io_handle_t *ioHandle, 2977 audio_devices_t *device) 2978{ 2979 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(); 2980 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(); 2981 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD); 2982 2983 mSoundTriggerSessions.add(*session, *ioHandle); 2984 2985 return NO_ERROR; 2986} 2987 2988status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session) 2989{ 2990 ssize_t index = mSoundTriggerSessions.indexOfKey(session); 2991 if (index < 0) { 2992 ALOGW("acquireSoundTriggerSession() session %d not registered", session); 2993 return BAD_VALUE; 2994 } 2995 2996 mSoundTriggerSessions.removeItem(session); 2997 return NO_ERROR; 2998} 2999 3000status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle, 3001 const sp<AudioPatch>& patch) 3002{ 3003 ssize_t index = mAudioPatches.indexOfKey(handle); 3004 3005 if (index >= 0) { 3006 ALOGW("addAudioPatch() patch %d already in", handle); 3007 return ALREADY_EXISTS; 3008 } 3009 mAudioPatches.add(handle, patch); 3010 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d" 3011 "sink handle %d", 3012 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks, 3013 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id); 3014 return NO_ERROR; 3015} 3016 3017status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle) 3018{ 3019 ssize_t index = mAudioPatches.indexOfKey(handle); 3020 3021 if (index < 0) { 3022 ALOGW("removeAudioPatch() patch %d not in", handle); 3023 return ALREADY_EXISTS; 3024 } 3025 ALOGV("removeAudioPatch() handle %d af handle %d", handle, 3026 mAudioPatches.valueAt(index)->mAfPatchHandle); 3027 mAudioPatches.removeItemsAt(index); 3028 return NO_ERROR; 3029} 3030 3031// ---------------------------------------------------------------------------- 3032// AudioPolicyManager 3033// ---------------------------------------------------------------------------- 3034 3035uint32_t AudioPolicyManager::nextUniqueId() 3036{ 3037 return android_atomic_inc(&mNextUniqueId); 3038} 3039 3040uint32_t AudioPolicyManager::nextAudioPortGeneration() 3041{ 3042 return android_atomic_inc(&mAudioPortGeneration); 3043} 3044 3045AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface) 3046 : 3047#ifdef AUDIO_POLICY_TEST 3048 Thread(false), 3049#endif //AUDIO_POLICY_TEST 3050 mPrimaryOutput((audio_io_handle_t)0), 3051 mPhoneState(AUDIO_MODE_NORMAL), 3052 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f), 3053 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0), 3054 mA2dpSuspended(false), 3055 mSpeakerDrcEnabled(false), mNextUniqueId(1), 3056 mAudioPortGeneration(1), 3057 mBeaconMuteRefCount(0), 3058 mBeaconPlayingRefCount(0), 3059 mBeaconMuted(false) 3060{ 3061 mUidCached = getuid(); 3062 mpClientInterface = clientInterface; 3063 3064 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) { 3065 mForceUse[i] = AUDIO_POLICY_FORCE_NONE; 3066 } 3067 3068 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER); 3069 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) { 3070 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) { 3071 ALOGE("could not load audio policy configuration file, setting defaults"); 3072 defaultAudioPolicyConfig(); 3073 } 3074 } 3075 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices 3076 3077 // must be done after reading the policy 3078 initializeVolumeCurves(); 3079 3080 // open all output streams needed to access attached devices 3081 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types(); 3082 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN; 3083 for (size_t i = 0; i < mHwModules.size(); i++) { 3084 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName); 3085 if (mHwModules[i]->mHandle == 0) { 3086 ALOGW("could not open HW module %s", mHwModules[i]->mName); 3087 continue; 3088 } 3089 // open all output streams needed to access attached devices 3090 // except for direct output streams that are only opened when they are actually 3091 // required by an app. 3092 // This also validates mAvailableOutputDevices list 3093 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 3094 { 3095 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j]; 3096 3097 if (outProfile->mSupportedDevices.isEmpty()) { 3098 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName); 3099 continue; 3100 } 3101 3102 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) { 3103 continue; 3104 } 3105 audio_devices_t profileType = outProfile->mSupportedDevices.types(); 3106 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) { 3107 profileType = mDefaultOutputDevice->mDeviceType; 3108 } else { 3109 // chose first device present in mSupportedDevices also part of 3110 // outputDeviceTypes 3111 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) { 3112 profileType = outProfile->mSupportedDevices[k]->mDeviceType; 3113 if ((profileType & outputDeviceTypes) != 0) { 3114 break; 3115 } 3116 } 3117 } 3118 if ((profileType & outputDeviceTypes) == 0) { 3119 continue; 3120 } 3121 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile); 3122 3123 outputDesc->mDevice = profileType; 3124 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 3125 config.sample_rate = outputDesc->mSamplingRate; 3126 config.channel_mask = outputDesc->mChannelMask; 3127 config.format = outputDesc->mFormat; 3128 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE; 3129 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle, 3130 &output, 3131 &config, 3132 &outputDesc->mDevice, 3133 String8(""), 3134 &outputDesc->mLatency, 3135 outputDesc->mFlags); 3136 3137 if (status != NO_ERROR) { 3138 ALOGW("Cannot open output stream for device %08x on hw module %s", 3139 outputDesc->mDevice, 3140 mHwModules[i]->mName); 3141 } else { 3142 outputDesc->mSamplingRate = config.sample_rate; 3143 outputDesc->mChannelMask = config.channel_mask; 3144 outputDesc->mFormat = config.format; 3145 3146 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) { 3147 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType; 3148 ssize_t index = 3149 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]); 3150 // give a valid ID to an attached device once confirmed it is reachable 3151 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) { 3152 mAvailableOutputDevices[index]->mId = nextUniqueId(); 3153 mAvailableOutputDevices[index]->mModule = mHwModules[i]; 3154 } 3155 } 3156 if (mPrimaryOutput == 0 && 3157 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) { 3158 mPrimaryOutput = output; 3159 } 3160 addOutput(output, outputDesc); 3161 setOutputDevice(output, 3162 outputDesc->mDevice, 3163 true); 3164 } 3165 } 3166 // open input streams needed to access attached devices to validate 3167 // mAvailableInputDevices list 3168 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) 3169 { 3170 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j]; 3171 3172 if (inProfile->mSupportedDevices.isEmpty()) { 3173 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName); 3174 continue; 3175 } 3176 // chose first device present in mSupportedDevices also part of 3177 // inputDeviceTypes 3178 audio_devices_t profileType = AUDIO_DEVICE_NONE; 3179 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) { 3180 profileType = inProfile->mSupportedDevices[k]->mDeviceType; 3181 if (profileType & inputDeviceTypes) { 3182 break; 3183 } 3184 } 3185 if ((profileType & inputDeviceTypes) == 0) { 3186 continue; 3187 } 3188 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile); 3189 3190 inputDesc->mInputSource = AUDIO_SOURCE_MIC; 3191 inputDesc->mDevice = profileType; 3192 3193 // find the address 3194 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType); 3195 // the inputs vector must be of size 1, but we don't want to crash here 3196 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress 3197 : String8(""); 3198 ALOGV(" for input device 0x%x using address %s", profileType, address.string()); 3199 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!"); 3200 3201 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 3202 config.sample_rate = inputDesc->mSamplingRate; 3203 config.channel_mask = inputDesc->mChannelMask; 3204 config.format = inputDesc->mFormat; 3205 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE; 3206 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle, 3207 &input, 3208 &config, 3209 &inputDesc->mDevice, 3210 address, 3211 AUDIO_SOURCE_MIC, 3212 AUDIO_INPUT_FLAG_NONE); 3213 3214 if (status == NO_ERROR) { 3215 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) { 3216 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType; 3217 ssize_t index = 3218 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]); 3219 // give a valid ID to an attached device once confirmed it is reachable 3220 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) { 3221 mAvailableInputDevices[index]->mId = nextUniqueId(); 3222 mAvailableInputDevices[index]->mModule = mHwModules[i]; 3223 } 3224 } 3225 mpClientInterface->closeInput(input); 3226 } else { 3227 ALOGW("Cannot open input stream for device %08x on hw module %s", 3228 inputDesc->mDevice, 3229 mHwModules[i]->mName); 3230 } 3231 } 3232 } 3233 // make sure all attached devices have been allocated a unique ID 3234 for (size_t i = 0; i < mAvailableOutputDevices.size();) { 3235 if (mAvailableOutputDevices[i]->mId == 0) { 3236 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType); 3237 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]); 3238 continue; 3239 } 3240 i++; 3241 } 3242 for (size_t i = 0; i < mAvailableInputDevices.size();) { 3243 if (mAvailableInputDevices[i]->mId == 0) { 3244 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType); 3245 mAvailableInputDevices.remove(mAvailableInputDevices[i]); 3246 continue; 3247 } 3248 i++; 3249 } 3250 // make sure default device is reachable 3251 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) { 3252 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType); 3253 } 3254 3255 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output"); 3256 3257 updateDevicesAndOutputs(); 3258 3259#ifdef AUDIO_POLICY_TEST 3260 if (mPrimaryOutput != 0) { 3261 AudioParameter outputCmd = AudioParameter(); 3262 outputCmd.addInt(String8("set_id"), 0); 3263 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString()); 3264 3265 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER; 3266 mTestSamplingRate = 44100; 3267 mTestFormat = AUDIO_FORMAT_PCM_16_BIT; 3268 mTestChannels = AUDIO_CHANNEL_OUT_STEREO; 3269 mTestLatencyMs = 0; 3270 mCurOutput = 0; 3271 mDirectOutput = false; 3272 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) { 3273 mTestOutputs[i] = 0; 3274 } 3275 3276 const size_t SIZE = 256; 3277 char buffer[SIZE]; 3278 snprintf(buffer, SIZE, "AudioPolicyManagerTest"); 3279 run(buffer, ANDROID_PRIORITY_AUDIO); 3280 } 3281#endif //AUDIO_POLICY_TEST 3282} 3283 3284AudioPolicyManager::~AudioPolicyManager() 3285{ 3286#ifdef AUDIO_POLICY_TEST 3287 exit(); 3288#endif //AUDIO_POLICY_TEST 3289 for (size_t i = 0; i < mOutputs.size(); i++) { 3290 mpClientInterface->closeOutput(mOutputs.keyAt(i)); 3291 } 3292 for (size_t i = 0; i < mInputs.size(); i++) { 3293 mpClientInterface->closeInput(mInputs.keyAt(i)); 3294 } 3295 mAvailableOutputDevices.clear(); 3296 mAvailableInputDevices.clear(); 3297 mOutputs.clear(); 3298 mInputs.clear(); 3299 mHwModules.clear(); 3300} 3301 3302status_t AudioPolicyManager::initCheck() 3303{ 3304 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR; 3305} 3306 3307#ifdef AUDIO_POLICY_TEST 3308bool AudioPolicyManager::threadLoop() 3309{ 3310 ALOGV("entering threadLoop()"); 3311 while (!exitPending()) 3312 { 3313 String8 command; 3314 int valueInt; 3315 String8 value; 3316 3317 Mutex::Autolock _l(mLock); 3318 mWaitWorkCV.waitRelative(mLock, milliseconds(50)); 3319 3320 command = mpClientInterface->getParameters(0, String8("test_cmd_policy")); 3321 AudioParameter param = AudioParameter(command); 3322 3323 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR && 3324 valueInt != 0) { 3325 ALOGV("Test command %s received", command.string()); 3326 String8 target; 3327 if (param.get(String8("target"), target) != NO_ERROR) { 3328 target = "Manager"; 3329 } 3330 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) { 3331 param.remove(String8("test_cmd_policy_output")); 3332 mCurOutput = valueInt; 3333 } 3334 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) { 3335 param.remove(String8("test_cmd_policy_direct")); 3336 if (value == "false") { 3337 mDirectOutput = false; 3338 } else if (value == "true") { 3339 mDirectOutput = true; 3340 } 3341 } 3342 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) { 3343 param.remove(String8("test_cmd_policy_input")); 3344 mTestInput = valueInt; 3345 } 3346 3347 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) { 3348 param.remove(String8("test_cmd_policy_format")); 3349 int format = AUDIO_FORMAT_INVALID; 3350 if (value == "PCM 16 bits") { 3351 format = AUDIO_FORMAT_PCM_16_BIT; 3352 } else if (value == "PCM 8 bits") { 3353 format = AUDIO_FORMAT_PCM_8_BIT; 3354 } else if (value == "Compressed MP3") { 3355 format = AUDIO_FORMAT_MP3; 3356 } 3357 if (format != AUDIO_FORMAT_INVALID) { 3358 if (target == "Manager") { 3359 mTestFormat = format; 3360 } else if (mTestOutputs[mCurOutput] != 0) { 3361 AudioParameter outputParam = AudioParameter(); 3362 outputParam.addInt(String8("format"), format); 3363 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 3364 } 3365 } 3366 } 3367 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) { 3368 param.remove(String8("test_cmd_policy_channels")); 3369 int channels = 0; 3370 3371 if (value == "Channels Stereo") { 3372 channels = AUDIO_CHANNEL_OUT_STEREO; 3373 } else if (value == "Channels Mono") { 3374 channels = AUDIO_CHANNEL_OUT_MONO; 3375 } 3376 if (channels != 0) { 3377 if (target == "Manager") { 3378 mTestChannels = channels; 3379 } else if (mTestOutputs[mCurOutput] != 0) { 3380 AudioParameter outputParam = AudioParameter(); 3381 outputParam.addInt(String8("channels"), channels); 3382 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 3383 } 3384 } 3385 } 3386 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) { 3387 param.remove(String8("test_cmd_policy_sampleRate")); 3388 if (valueInt >= 0 && valueInt <= 96000) { 3389 int samplingRate = valueInt; 3390 if (target == "Manager") { 3391 mTestSamplingRate = samplingRate; 3392 } else if (mTestOutputs[mCurOutput] != 0) { 3393 AudioParameter outputParam = AudioParameter(); 3394 outputParam.addInt(String8("sampling_rate"), samplingRate); 3395 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString()); 3396 } 3397 } 3398 } 3399 3400 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) { 3401 param.remove(String8("test_cmd_policy_reopen")); 3402 3403 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput); 3404 mpClientInterface->closeOutput(mPrimaryOutput); 3405 3406 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle; 3407 3408 mOutputs.removeItem(mPrimaryOutput); 3409 3410 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL); 3411 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER; 3412 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 3413 config.sample_rate = outputDesc->mSamplingRate; 3414 config.channel_mask = outputDesc->mChannelMask; 3415 config.format = outputDesc->mFormat; 3416 status_t status = mpClientInterface->openOutput(moduleHandle, 3417 &mPrimaryOutput, 3418 &config, 3419 &outputDesc->mDevice, 3420 String8(""), 3421 &outputDesc->mLatency, 3422 outputDesc->mFlags); 3423 if (status != NO_ERROR) { 3424 ALOGE("Failed to reopen hardware output stream, " 3425 "samplingRate: %d, format %d, channels %d", 3426 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask); 3427 } else { 3428 outputDesc->mSamplingRate = config.sample_rate; 3429 outputDesc->mChannelMask = config.channel_mask; 3430 outputDesc->mFormat = config.format; 3431 AudioParameter outputCmd = AudioParameter(); 3432 outputCmd.addInt(String8("set_id"), 0); 3433 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString()); 3434 addOutput(mPrimaryOutput, outputDesc); 3435 } 3436 } 3437 3438 3439 mpClientInterface->setParameters(0, String8("test_cmd_policy=")); 3440 } 3441 } 3442 return false; 3443} 3444 3445void AudioPolicyManager::exit() 3446{ 3447 { 3448 AutoMutex _l(mLock); 3449 requestExit(); 3450 mWaitWorkCV.signal(); 3451 } 3452 requestExitAndWait(); 3453} 3454 3455int AudioPolicyManager::testOutputIndex(audio_io_handle_t output) 3456{ 3457 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) { 3458 if (output == mTestOutputs[i]) return i; 3459 } 3460 return 0; 3461} 3462#endif //AUDIO_POLICY_TEST 3463 3464// --- 3465 3466void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc) 3467{ 3468 outputDesc->mIoHandle = output; 3469 outputDesc->mId = nextUniqueId(); 3470 mOutputs.add(output, outputDesc); 3471 nextAudioPortGeneration(); 3472} 3473 3474void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc) 3475{ 3476 inputDesc->mIoHandle = input; 3477 inputDesc->mId = nextUniqueId(); 3478 mInputs.add(input, inputDesc); 3479 nextAudioPortGeneration(); 3480} 3481 3482void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/, 3483 const audio_devices_t device /*in*/, 3484 const String8 address /*in*/, 3485 SortedVector<audio_io_handle_t>& outputs /*out*/) { 3486 sp<DeviceDescriptor> devDesc = 3487 desc->mProfile->mSupportedDevices.getDevice(device, address); 3488 if (devDesc != 0) { 3489 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s", 3490 desc->mIoHandle, address.string()); 3491 outputs.add(desc->mIoHandle); 3492 } 3493} 3494 3495status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc, 3496 audio_policy_dev_state_t state, 3497 SortedVector<audio_io_handle_t>& outputs, 3498 const String8 address) 3499{ 3500 audio_devices_t device = devDesc->mDeviceType; 3501 sp<AudioOutputDescriptor> desc; 3502 // erase all current sample rates, formats and channel masks 3503 devDesc->clearCapabilities(); 3504 3505 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) { 3506 // first list already open outputs that can be routed to this device 3507 for (size_t i = 0; i < mOutputs.size(); i++) { 3508 desc = mOutputs.valueAt(i); 3509 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) { 3510 if (!deviceDistinguishesOnAddress(device)) { 3511 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i)); 3512 outputs.add(mOutputs.keyAt(i)); 3513 } else { 3514 ALOGV(" checking address match due to device 0x%x", device); 3515 findIoHandlesByAddress(desc, device, address, outputs); 3516 } 3517 } 3518 } 3519 // then look for output profiles that can be routed to this device 3520 SortedVector< sp<IOProfile> > profiles; 3521 for (size_t i = 0; i < mHwModules.size(); i++) 3522 { 3523 if (mHwModules[i]->mHandle == 0) { 3524 continue; 3525 } 3526 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 3527 { 3528 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j]; 3529 if (profile->mSupportedDevices.types() & device) { 3530 if (!deviceDistinguishesOnAddress(device) || 3531 address == profile->mSupportedDevices[0]->mAddress) { 3532 profiles.add(profile); 3533 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i); 3534 } 3535 } 3536 } 3537 } 3538 3539 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size()); 3540 3541 if (profiles.isEmpty() && outputs.isEmpty()) { 3542 ALOGW("checkOutputsForDevice(): No output available for device %04x", device); 3543 return BAD_VALUE; 3544 } 3545 3546 // open outputs for matching profiles if needed. Direct outputs are also opened to 3547 // query for dynamic parameters and will be closed later by setDeviceConnectionState() 3548 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) { 3549 sp<IOProfile> profile = profiles[profile_index]; 3550 3551 // nothing to do if one output is already opened for this profile 3552 size_t j; 3553 for (j = 0; j < outputs.size(); j++) { 3554 desc = mOutputs.valueFor(outputs.itemAt(j)); 3555 if (!desc->isDuplicated() && desc->mProfile == profile) { 3556 // matching profile: save the sample rates, format and channel masks supported 3557 // by the profile in our device descriptor 3558 devDesc->importAudioPort(profile); 3559 break; 3560 } 3561 } 3562 if (j != outputs.size()) { 3563 continue; 3564 } 3565 3566 ALOGV("opening output for device %08x with params %s profile %p", 3567 device, address.string(), profile.get()); 3568 desc = new AudioOutputDescriptor(profile); 3569 desc->mDevice = device; 3570 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 3571 config.sample_rate = desc->mSamplingRate; 3572 config.channel_mask = desc->mChannelMask; 3573 config.format = desc->mFormat; 3574 config.offload_info.sample_rate = desc->mSamplingRate; 3575 config.offload_info.channel_mask = desc->mChannelMask; 3576 config.offload_info.format = desc->mFormat; 3577 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE; 3578 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle, 3579 &output, 3580 &config, 3581 &desc->mDevice, 3582 address, 3583 &desc->mLatency, 3584 desc->mFlags); 3585 if (status == NO_ERROR) { 3586 desc->mSamplingRate = config.sample_rate; 3587 desc->mChannelMask = config.channel_mask; 3588 desc->mFormat = config.format; 3589 3590 // Here is where the out_set_parameters() for card & device gets called 3591 if (!address.isEmpty()) { 3592 char *param = audio_device_address_to_parameter(device, address); 3593 mpClientInterface->setParameters(output, String8(param)); 3594 free(param); 3595 } 3596 3597 // Here is where we step through and resolve any "dynamic" fields 3598 String8 reply; 3599 char *value; 3600 if (profile->mSamplingRates[0] == 0) { 3601 reply = mpClientInterface->getParameters(output, 3602 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES)); 3603 ALOGV("checkOutputsForDevice() supported sampling rates %s", 3604 reply.string()); 3605 value = strpbrk((char *)reply.string(), "="); 3606 if (value != NULL) { 3607 profile->loadSamplingRates(value + 1); 3608 } 3609 } 3610 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) { 3611 reply = mpClientInterface->getParameters(output, 3612 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS)); 3613 ALOGV("checkOutputsForDevice() supported formats %s", 3614 reply.string()); 3615 value = strpbrk((char *)reply.string(), "="); 3616 if (value != NULL) { 3617 profile->loadFormats(value + 1); 3618 } 3619 } 3620 if (profile->mChannelMasks[0] == 0) { 3621 reply = mpClientInterface->getParameters(output, 3622 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS)); 3623 ALOGV("checkOutputsForDevice() supported channel masks %s", 3624 reply.string()); 3625 value = strpbrk((char *)reply.string(), "="); 3626 if (value != NULL) { 3627 profile->loadOutChannels(value + 1); 3628 } 3629 } 3630 if (((profile->mSamplingRates[0] == 0) && 3631 (profile->mSamplingRates.size() < 2)) || 3632 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) && 3633 (profile->mFormats.size() < 2)) || 3634 ((profile->mChannelMasks[0] == 0) && 3635 (profile->mChannelMasks.size() < 2))) { 3636 ALOGW("checkOutputsForDevice() missing param"); 3637 mpClientInterface->closeOutput(output); 3638 output = AUDIO_IO_HANDLE_NONE; 3639 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 || 3640 profile->mChannelMasks[0] == 0) { 3641 mpClientInterface->closeOutput(output); 3642 config.sample_rate = profile->pickSamplingRate(); 3643 config.channel_mask = profile->pickChannelMask(); 3644 config.format = profile->pickFormat(); 3645 config.offload_info.sample_rate = config.sample_rate; 3646 config.offload_info.channel_mask = config.channel_mask; 3647 config.offload_info.format = config.format; 3648 status = mpClientInterface->openOutput(profile->mModule->mHandle, 3649 &output, 3650 &config, 3651 &desc->mDevice, 3652 address, 3653 &desc->mLatency, 3654 desc->mFlags); 3655 if (status == NO_ERROR) { 3656 desc->mSamplingRate = config.sample_rate; 3657 desc->mChannelMask = config.channel_mask; 3658 desc->mFormat = config.format; 3659 } else { 3660 output = AUDIO_IO_HANDLE_NONE; 3661 } 3662 } 3663 3664 if (output != AUDIO_IO_HANDLE_NONE) { 3665 addOutput(output, desc); 3666 if (deviceDistinguishesOnAddress(device) && address != "0") { 3667 ssize_t index = mPolicyMixes.indexOfKey(address); 3668 if (index >= 0) { 3669 mPolicyMixes[index]->mOutput = desc; 3670 desc->mPolicyMix = &mPolicyMixes[index]->mMix; 3671 } else { 3672 ALOGE("checkOutputsForDevice() cannot find policy for address %s", 3673 address.string()); 3674 } 3675 } else if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) { 3676 // no duplicated output for direct outputs and 3677 // outputs used by dynamic policy mixes 3678 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE; 3679 3680 // set initial stream volume for device 3681 applyStreamVolumes(output, device, 0, true); 3682 3683 //TODO: configure audio effect output stage here 3684 3685 // open a duplicating output thread for the new output and the primary output 3686 duplicatedOutput = mpClientInterface->openDuplicateOutput(output, 3687 mPrimaryOutput); 3688 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) { 3689 // add duplicated output descriptor 3690 sp<AudioOutputDescriptor> dupOutputDesc = 3691 new AudioOutputDescriptor(NULL); 3692 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput); 3693 dupOutputDesc->mOutput2 = mOutputs.valueFor(output); 3694 dupOutputDesc->mSamplingRate = desc->mSamplingRate; 3695 dupOutputDesc->mFormat = desc->mFormat; 3696 dupOutputDesc->mChannelMask = desc->mChannelMask; 3697 dupOutputDesc->mLatency = desc->mLatency; 3698 addOutput(duplicatedOutput, dupOutputDesc); 3699 applyStreamVolumes(duplicatedOutput, device, 0, true); 3700 } else { 3701 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d", 3702 mPrimaryOutput, output); 3703 mpClientInterface->closeOutput(output); 3704 mOutputs.removeItem(output); 3705 nextAudioPortGeneration(); 3706 output = AUDIO_IO_HANDLE_NONE; 3707 } 3708 } 3709 } 3710 } else { 3711 output = AUDIO_IO_HANDLE_NONE; 3712 } 3713 if (output == AUDIO_IO_HANDLE_NONE) { 3714 ALOGW("checkOutputsForDevice() could not open output for device %x", device); 3715 profiles.removeAt(profile_index); 3716 profile_index--; 3717 } else { 3718 outputs.add(output); 3719 devDesc->importAudioPort(profile); 3720 3721 if (deviceDistinguishesOnAddress(device)) { 3722 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)", 3723 device, address.string()); 3724 setOutputDevice(output, device, true/*force*/, 0/*delay*/, 3725 NULL/*patch handle*/, address.string()); 3726 } 3727 ALOGV("checkOutputsForDevice(): adding output %d", output); 3728 } 3729 } 3730 3731 if (profiles.isEmpty()) { 3732 ALOGW("checkOutputsForDevice(): No output available for device %04x", device); 3733 return BAD_VALUE; 3734 } 3735 } else { // Disconnect 3736 // check if one opened output is not needed any more after disconnecting one device 3737 for (size_t i = 0; i < mOutputs.size(); i++) { 3738 desc = mOutputs.valueAt(i); 3739 if (!desc->isDuplicated()) { 3740 // exact match on device 3741 if (deviceDistinguishesOnAddress(device) && 3742 (desc->mProfile->mSupportedDevices.types() == device)) { 3743 findIoHandlesByAddress(desc, device, address, outputs); 3744 } else if (!(desc->mProfile->mSupportedDevices.types() 3745 & mAvailableOutputDevices.types())) { 3746 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", 3747 mOutputs.keyAt(i)); 3748 outputs.add(mOutputs.keyAt(i)); 3749 } 3750 } 3751 } 3752 // Clear any profiles associated with the disconnected device. 3753 for (size_t i = 0; i < mHwModules.size(); i++) 3754 { 3755 if (mHwModules[i]->mHandle == 0) { 3756 continue; 3757 } 3758 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) 3759 { 3760 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j]; 3761 if (profile->mSupportedDevices.types() & device) { 3762 ALOGV("checkOutputsForDevice(): " 3763 "clearing direct output profile %zu on module %zu", j, i); 3764 if (profile->mSamplingRates[0] == 0) { 3765 profile->mSamplingRates.clear(); 3766 profile->mSamplingRates.add(0); 3767 } 3768 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) { 3769 profile->mFormats.clear(); 3770 profile->mFormats.add(AUDIO_FORMAT_DEFAULT); 3771 } 3772 if (profile->mChannelMasks[0] == 0) { 3773 profile->mChannelMasks.clear(); 3774 profile->mChannelMasks.add(0); 3775 } 3776 } 3777 } 3778 } 3779 } 3780 return NO_ERROR; 3781} 3782 3783status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device, 3784 audio_policy_dev_state_t state, 3785 SortedVector<audio_io_handle_t>& inputs, 3786 const String8 address) 3787{ 3788 sp<AudioInputDescriptor> desc; 3789 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) { 3790 // first list already open inputs that can be routed to this device 3791 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) { 3792 desc = mInputs.valueAt(input_index); 3793 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) { 3794 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index)); 3795 inputs.add(mInputs.keyAt(input_index)); 3796 } 3797 } 3798 3799 // then look for input profiles that can be routed to this device 3800 SortedVector< sp<IOProfile> > profiles; 3801 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++) 3802 { 3803 if (mHwModules[module_idx]->mHandle == 0) { 3804 continue; 3805 } 3806 for (size_t profile_index = 0; 3807 profile_index < mHwModules[module_idx]->mInputProfiles.size(); 3808 profile_index++) 3809 { 3810 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index]; 3811 3812 if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) { 3813 if (!deviceDistinguishesOnAddress(device) || 3814 address == profile->mSupportedDevices[0]->mAddress) { 3815 profiles.add(profile); 3816 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu", 3817 profile_index, module_idx); 3818 } 3819 } 3820 } 3821 } 3822 3823 if (profiles.isEmpty() && inputs.isEmpty()) { 3824 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device); 3825 return BAD_VALUE; 3826 } 3827 3828 // open inputs for matching profiles if needed. Direct inputs are also opened to 3829 // query for dynamic parameters and will be closed later by setDeviceConnectionState() 3830 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) { 3831 3832 sp<IOProfile> profile = profiles[profile_index]; 3833 // nothing to do if one input is already opened for this profile 3834 size_t input_index; 3835 for (input_index = 0; input_index < mInputs.size(); input_index++) { 3836 desc = mInputs.valueAt(input_index); 3837 if (desc->mProfile == profile) { 3838 break; 3839 } 3840 } 3841 if (input_index != mInputs.size()) { 3842 continue; 3843 } 3844 3845 ALOGV("opening input for device 0x%X with params %s", device, address.string()); 3846 desc = new AudioInputDescriptor(profile); 3847 desc->mDevice = device; 3848 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 3849 config.sample_rate = desc->mSamplingRate; 3850 config.channel_mask = desc->mChannelMask; 3851 config.format = desc->mFormat; 3852 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE; 3853 status_t status = mpClientInterface->openInput(profile->mModule->mHandle, 3854 &input, 3855 &config, 3856 &desc->mDevice, 3857 address, 3858 AUDIO_SOURCE_MIC, 3859 AUDIO_INPUT_FLAG_NONE /*FIXME*/); 3860 3861 if (status == NO_ERROR) { 3862 desc->mSamplingRate = config.sample_rate; 3863 desc->mChannelMask = config.channel_mask; 3864 desc->mFormat = config.format; 3865 3866 if (!address.isEmpty()) { 3867 char *param = audio_device_address_to_parameter(device, address); 3868 mpClientInterface->setParameters(input, String8(param)); 3869 free(param); 3870 } 3871 3872 // Here is where we step through and resolve any "dynamic" fields 3873 String8 reply; 3874 char *value; 3875 if (profile->mSamplingRates[0] == 0) { 3876 reply = mpClientInterface->getParameters(input, 3877 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES)); 3878 ALOGV("checkInputsForDevice() direct input sup sampling rates %s", 3879 reply.string()); 3880 value = strpbrk((char *)reply.string(), "="); 3881 if (value != NULL) { 3882 profile->loadSamplingRates(value + 1); 3883 } 3884 } 3885 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) { 3886 reply = mpClientInterface->getParameters(input, 3887 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS)); 3888 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string()); 3889 value = strpbrk((char *)reply.string(), "="); 3890 if (value != NULL) { 3891 profile->loadFormats(value + 1); 3892 } 3893 } 3894 if (profile->mChannelMasks[0] == 0) { 3895 reply = mpClientInterface->getParameters(input, 3896 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS)); 3897 ALOGV("checkInputsForDevice() direct input sup channel masks %s", 3898 reply.string()); 3899 value = strpbrk((char *)reply.string(), "="); 3900 if (value != NULL) { 3901 profile->loadInChannels(value + 1); 3902 } 3903 } 3904 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) || 3905 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) || 3906 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) { 3907 ALOGW("checkInputsForDevice() direct input missing param"); 3908 mpClientInterface->closeInput(input); 3909 input = AUDIO_IO_HANDLE_NONE; 3910 } 3911 3912 if (input != 0) { 3913 addInput(input, desc); 3914 } 3915 } // endif input != 0 3916 3917 if (input == AUDIO_IO_HANDLE_NONE) { 3918 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device); 3919 profiles.removeAt(profile_index); 3920 profile_index--; 3921 } else { 3922 inputs.add(input); 3923 ALOGV("checkInputsForDevice(): adding input %d", input); 3924 } 3925 } // end scan profiles 3926 3927 if (profiles.isEmpty()) { 3928 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device); 3929 return BAD_VALUE; 3930 } 3931 } else { 3932 // Disconnect 3933 // check if one opened input is not needed any more after disconnecting one device 3934 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) { 3935 desc = mInputs.valueAt(input_index); 3936 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() & 3937 ~AUDIO_DEVICE_BIT_IN)) { 3938 ALOGV("checkInputsForDevice(): disconnecting adding input %d", 3939 mInputs.keyAt(input_index)); 3940 inputs.add(mInputs.keyAt(input_index)); 3941 } 3942 } 3943 // Clear any profiles associated with the disconnected device. 3944 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) { 3945 if (mHwModules[module_index]->mHandle == 0) { 3946 continue; 3947 } 3948 for (size_t profile_index = 0; 3949 profile_index < mHwModules[module_index]->mInputProfiles.size(); 3950 profile_index++) { 3951 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index]; 3952 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) { 3953 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu", 3954 profile_index, module_index); 3955 if (profile->mSamplingRates[0] == 0) { 3956 profile->mSamplingRates.clear(); 3957 profile->mSamplingRates.add(0); 3958 } 3959 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) { 3960 profile->mFormats.clear(); 3961 profile->mFormats.add(AUDIO_FORMAT_DEFAULT); 3962 } 3963 if (profile->mChannelMasks[0] == 0) { 3964 profile->mChannelMasks.clear(); 3965 profile->mChannelMasks.add(0); 3966 } 3967 } 3968 } 3969 } 3970 } // end disconnect 3971 3972 return NO_ERROR; 3973} 3974 3975 3976void AudioPolicyManager::closeOutput(audio_io_handle_t output) 3977{ 3978 ALOGV("closeOutput(%d)", output); 3979 3980 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 3981 if (outputDesc == NULL) { 3982 ALOGW("closeOutput() unknown output %d", output); 3983 return; 3984 } 3985 3986 for (size_t i = 0; i < mPolicyMixes.size(); i++) { 3987 if (mPolicyMixes[i]->mOutput == outputDesc) { 3988 mPolicyMixes[i]->mOutput.clear(); 3989 } 3990 } 3991 3992 // look for duplicated outputs connected to the output being removed. 3993 for (size_t i = 0; i < mOutputs.size(); i++) { 3994 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i); 3995 if (dupOutputDesc->isDuplicated() && 3996 (dupOutputDesc->mOutput1 == outputDesc || 3997 dupOutputDesc->mOutput2 == outputDesc)) { 3998 sp<AudioOutputDescriptor> outputDesc2; 3999 if (dupOutputDesc->mOutput1 == outputDesc) { 4000 outputDesc2 = dupOutputDesc->mOutput2; 4001 } else { 4002 outputDesc2 = dupOutputDesc->mOutput1; 4003 } 4004 // As all active tracks on duplicated output will be deleted, 4005 // and as they were also referenced on the other output, the reference 4006 // count for their stream type must be adjusted accordingly on 4007 // the other output. 4008 for (int j = 0; j < AUDIO_STREAM_CNT; j++) { 4009 int refCount = dupOutputDesc->mRefCount[j]; 4010 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount); 4011 } 4012 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i); 4013 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput); 4014 4015 mpClientInterface->closeOutput(duplicatedOutput); 4016 mOutputs.removeItem(duplicatedOutput); 4017 } 4018 } 4019 4020 nextAudioPortGeneration(); 4021 4022 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle); 4023 if (index >= 0) { 4024 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 4025 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 4026 mAudioPatches.removeItemsAt(index); 4027 mpClientInterface->onAudioPatchListUpdate(); 4028 } 4029 4030 AudioParameter param; 4031 param.add(String8("closing"), String8("true")); 4032 mpClientInterface->setParameters(output, param.toString()); 4033 4034 mpClientInterface->closeOutput(output); 4035 mOutputs.removeItem(output); 4036 mPreviousOutputs = mOutputs; 4037} 4038 4039void AudioPolicyManager::closeInput(audio_io_handle_t input) 4040{ 4041 ALOGV("closeInput(%d)", input); 4042 4043 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input); 4044 if (inputDesc == NULL) { 4045 ALOGW("closeInput() unknown input %d", input); 4046 return; 4047 } 4048 4049 nextAudioPortGeneration(); 4050 4051 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle); 4052 if (index >= 0) { 4053 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 4054 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0); 4055 mAudioPatches.removeItemsAt(index); 4056 mpClientInterface->onAudioPatchListUpdate(); 4057 } 4058 4059 mpClientInterface->closeInput(input); 4060 mInputs.removeItem(input); 4061} 4062 4063SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device, 4064 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs) 4065{ 4066 SortedVector<audio_io_handle_t> outputs; 4067 4068 ALOGVV("getOutputsForDevice() device %04x", device); 4069 for (size_t i = 0; i < openOutputs.size(); i++) { 4070 ALOGVV("output %d isDuplicated=%d device=%04x", 4071 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices()); 4072 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) { 4073 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i)); 4074 outputs.add(openOutputs.keyAt(i)); 4075 } 4076 } 4077 return outputs; 4078} 4079 4080bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1, 4081 SortedVector<audio_io_handle_t>& outputs2) 4082{ 4083 if (outputs1.size() != outputs2.size()) { 4084 return false; 4085 } 4086 for (size_t i = 0; i < outputs1.size(); i++) { 4087 if (outputs1[i] != outputs2[i]) { 4088 return false; 4089 } 4090 } 4091 return true; 4092} 4093 4094void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy) 4095{ 4096 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/); 4097 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/); 4098 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs); 4099 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs); 4100 4101 // also take into account external policy-related changes: add all outputs which are 4102 // associated with policies in the "before" and "after" output vectors 4103 ALOGVV("checkOutputForStrategy(): policy related outputs"); 4104 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) { 4105 const sp<AudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i); 4106 if (desc != 0 && desc->mPolicyMix != NULL) { 4107 srcOutputs.add(desc->mIoHandle); 4108 ALOGVV(" previous outputs: adding %d", desc->mIoHandle); 4109 } 4110 } 4111 for (size_t i = 0 ; i < mOutputs.size() ; i++) { 4112 const sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 4113 if (desc != 0 && desc->mPolicyMix != NULL) { 4114 dstOutputs.add(desc->mIoHandle); 4115 ALOGVV(" new outputs: adding %d", desc->mIoHandle); 4116 } 4117 } 4118 4119 if (!vectorsEqual(srcOutputs,dstOutputs)) { 4120 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d", 4121 strategy, srcOutputs[0], dstOutputs[0]); 4122 // mute strategy while moving tracks from one output to another 4123 for (size_t i = 0; i < srcOutputs.size(); i++) { 4124 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]); 4125 if (desc->isStrategyActive(strategy)) { 4126 setStrategyMute(strategy, true, srcOutputs[i]); 4127 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice); 4128 } 4129 } 4130 4131 // Move effects associated to this strategy from previous output to new output 4132 if (strategy == STRATEGY_MEDIA) { 4133 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs); 4134 SortedVector<audio_io_handle_t> moved; 4135 for (size_t i = 0; i < mEffects.size(); i++) { 4136 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i); 4137 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX && 4138 effectDesc->mIo != fxOutput) { 4139 if (moved.indexOf(effectDesc->mIo) < 0) { 4140 ALOGV("checkOutputForStrategy() moving effect %d to output %d", 4141 mEffects.keyAt(i), fxOutput); 4142 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo, 4143 fxOutput); 4144 moved.add(effectDesc->mIo); 4145 } 4146 effectDesc->mIo = fxOutput; 4147 } 4148 } 4149 } 4150 // Move tracks associated to this strategy from previous output to new output 4151 for (int i = 0; i < AUDIO_STREAM_CNT; i++) { 4152 if (i == AUDIO_STREAM_PATCH) { 4153 continue; 4154 } 4155 if (getStrategy((audio_stream_type_t)i) == strategy) { 4156 mpClientInterface->invalidateStream((audio_stream_type_t)i); 4157 } 4158 } 4159 } 4160} 4161 4162void AudioPolicyManager::checkOutputForAllStrategies() 4163{ 4164 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) 4165 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE); 4166 checkOutputForStrategy(STRATEGY_PHONE); 4167 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) 4168 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE); 4169 checkOutputForStrategy(STRATEGY_SONIFICATION); 4170 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL); 4171 checkOutputForStrategy(STRATEGY_ACCESSIBILITY); 4172 checkOutputForStrategy(STRATEGY_MEDIA); 4173 checkOutputForStrategy(STRATEGY_DTMF); 4174 checkOutputForStrategy(STRATEGY_REROUTING); 4175} 4176 4177audio_io_handle_t AudioPolicyManager::getA2dpOutput() 4178{ 4179 for (size_t i = 0; i < mOutputs.size(); i++) { 4180 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i); 4181 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) { 4182 return mOutputs.keyAt(i); 4183 } 4184 } 4185 4186 return 0; 4187} 4188 4189void AudioPolicyManager::checkA2dpSuspend() 4190{ 4191 audio_io_handle_t a2dpOutput = getA2dpOutput(); 4192 if (a2dpOutput == 0) { 4193 mA2dpSuspended = false; 4194 return; 4195 } 4196 4197 bool isScoConnected = 4198 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET & 4199 ~AUDIO_DEVICE_BIT_IN) != 0) || 4200 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0); 4201 // suspend A2DP output if: 4202 // (NOT already suspended) && 4203 // ((SCO device is connected && 4204 // (forced usage for communication || for record is SCO))) || 4205 // (phone state is ringing || in call) 4206 // 4207 // restore A2DP output if: 4208 // (Already suspended) && 4209 // ((SCO device is NOT connected || 4210 // (forced usage NOT for communication && NOT for record is SCO))) && 4211 // (phone state is NOT ringing && NOT in call) 4212 // 4213 if (mA2dpSuspended) { 4214 if ((!isScoConnected || 4215 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) && 4216 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) && 4217 ((mPhoneState != AUDIO_MODE_IN_CALL) && 4218 (mPhoneState != AUDIO_MODE_RINGTONE))) { 4219 4220 mpClientInterface->restoreOutput(a2dpOutput); 4221 mA2dpSuspended = false; 4222 } 4223 } else { 4224 if ((isScoConnected && 4225 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) || 4226 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) || 4227 ((mPhoneState == AUDIO_MODE_IN_CALL) || 4228 (mPhoneState == AUDIO_MODE_RINGTONE))) { 4229 4230 mpClientInterface->suspendOutput(a2dpOutput); 4231 mA2dpSuspended = true; 4232 } 4233 } 4234} 4235 4236audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache) 4237{ 4238 audio_devices_t device = AUDIO_DEVICE_NONE; 4239 4240 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 4241 4242 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle); 4243 if (index >= 0) { 4244 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 4245 if (patchDesc->mUid != mUidCached) { 4246 ALOGV("getNewOutputDevice() device %08x forced by patch %d", 4247 outputDesc->device(), outputDesc->mPatchHandle); 4248 return outputDesc->device(); 4249 } 4250 } 4251 4252 // check the following by order of priority to request a routing change if necessary: 4253 // 1: the strategy enforced audible is active and enforced on the output: 4254 // use device for strategy enforced audible 4255 // 2: we are in call or the strategy phone is active on the output: 4256 // use device for strategy phone 4257 // 3: the strategy for enforced audible is active but not enforced on the output: 4258 // use the device for strategy enforced audible 4259 // 4: the strategy sonification is active on the output: 4260 // use device for strategy sonification 4261 // 5: the strategy "respectful" sonification is active on the output: 4262 // use device for strategy "respectful" sonification 4263 // 6: the strategy accessibility is active on the output: 4264 // use device for strategy accessibility 4265 // 7: the strategy media is active on the output: 4266 // use device for strategy media 4267 // 8: the strategy DTMF is active on the output: 4268 // use device for strategy DTMF 4269 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output: 4270 // use device for strategy t-t-s 4271 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) && 4272 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) { 4273 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache); 4274 } else if (isInCall() || 4275 outputDesc->isStrategyActive(STRATEGY_PHONE)) { 4276 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache); 4277 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) { 4278 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache); 4279 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) { 4280 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache); 4281 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) { 4282 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache); 4283 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) { 4284 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache); 4285 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) { 4286 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache); 4287 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) { 4288 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache); 4289 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) { 4290 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache); 4291 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) { 4292 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache); 4293 } 4294 4295 ALOGV("getNewOutputDevice() selected device %x", device); 4296 return device; 4297} 4298 4299audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input) 4300{ 4301 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input); 4302 4303 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle); 4304 if (index >= 0) { 4305 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index); 4306 if (patchDesc->mUid != mUidCached) { 4307 ALOGV("getNewInputDevice() device %08x forced by patch %d", 4308 inputDesc->mDevice, inputDesc->mPatchHandle); 4309 return inputDesc->mDevice; 4310 } 4311 } 4312 4313 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->mInputSource); 4314 4315 ALOGV("getNewInputDevice() selected device %x", device); 4316 return device; 4317} 4318 4319uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) { 4320 return (uint32_t)getStrategy(stream); 4321} 4322 4323audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) { 4324 // By checking the range of stream before calling getStrategy, we avoid 4325 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE 4326 // and then return STRATEGY_MEDIA, but we want to return the empty set. 4327 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) { 4328 return AUDIO_DEVICE_NONE; 4329 } 4330 audio_devices_t devices; 4331 AudioPolicyManager::routing_strategy strategy = getStrategy(stream); 4332 devices = getDeviceForStrategy(strategy, true /*fromCache*/); 4333 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs); 4334 for (size_t i = 0; i < outputs.size(); i++) { 4335 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]); 4336 if (outputDesc->isStrategyActive(strategy)) { 4337 devices = outputDesc->device(); 4338 break; 4339 } 4340 } 4341 4342 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it 4343 and doesn't really need to.*/ 4344 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) { 4345 devices |= AUDIO_DEVICE_OUT_SPEAKER; 4346 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE; 4347 } 4348 4349 return devices; 4350} 4351 4352AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy( 4353 audio_stream_type_t stream) { 4354 4355 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH"); 4356 4357 // stream to strategy mapping 4358 switch (stream) { 4359 case AUDIO_STREAM_VOICE_CALL: 4360 case AUDIO_STREAM_BLUETOOTH_SCO: 4361 return STRATEGY_PHONE; 4362 case AUDIO_STREAM_RING: 4363 case AUDIO_STREAM_ALARM: 4364 return STRATEGY_SONIFICATION; 4365 case AUDIO_STREAM_NOTIFICATION: 4366 return STRATEGY_SONIFICATION_RESPECTFUL; 4367 case AUDIO_STREAM_DTMF: 4368 return STRATEGY_DTMF; 4369 default: 4370 ALOGE("unknown stream type %d", stream); 4371 case AUDIO_STREAM_SYSTEM: 4372 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs 4373 // while key clicks are played produces a poor result 4374 case AUDIO_STREAM_MUSIC: 4375 return STRATEGY_MEDIA; 4376 case AUDIO_STREAM_ENFORCED_AUDIBLE: 4377 return STRATEGY_ENFORCED_AUDIBLE; 4378 case AUDIO_STREAM_TTS: 4379 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER; 4380 case AUDIO_STREAM_ACCESSIBILITY: 4381 return STRATEGY_ACCESSIBILITY; 4382 case AUDIO_STREAM_REROUTING: 4383 return STRATEGY_REROUTING; 4384 } 4385} 4386 4387uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) { 4388 // flags to strategy mapping 4389 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) { 4390 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER; 4391 } 4392 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) { 4393 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE; 4394 } 4395 4396 // usage to strategy mapping 4397 switch (attr->usage) { 4398 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY: 4399 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) { 4400 return (uint32_t) STRATEGY_SONIFICATION; 4401 } 4402 if (isInCall()) { 4403 return (uint32_t) STRATEGY_PHONE; 4404 } 4405 return (uint32_t) STRATEGY_ACCESSIBILITY; 4406 4407 case AUDIO_USAGE_MEDIA: 4408 case AUDIO_USAGE_GAME: 4409 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE: 4410 case AUDIO_USAGE_ASSISTANCE_SONIFICATION: 4411 return (uint32_t) STRATEGY_MEDIA; 4412 4413 case AUDIO_USAGE_VOICE_COMMUNICATION: 4414 return (uint32_t) STRATEGY_PHONE; 4415 4416 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING: 4417 return (uint32_t) STRATEGY_DTMF; 4418 4419 case AUDIO_USAGE_ALARM: 4420 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE: 4421 return (uint32_t) STRATEGY_SONIFICATION; 4422 4423 case AUDIO_USAGE_NOTIFICATION: 4424 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST: 4425 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT: 4426 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED: 4427 case AUDIO_USAGE_NOTIFICATION_EVENT: 4428 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL; 4429 4430 case AUDIO_USAGE_UNKNOWN: 4431 default: 4432 return (uint32_t) STRATEGY_MEDIA; 4433 } 4434} 4435 4436void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) { 4437 switch(stream) { 4438 case AUDIO_STREAM_MUSIC: 4439 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL); 4440 updateDevicesAndOutputs(); 4441 break; 4442 default: 4443 break; 4444 } 4445} 4446 4447bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) { 4448 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) { 4449 if (s == (size_t) streamToIgnore) { 4450 continue; 4451 } 4452 for (size_t i = 0; i < mOutputs.size(); i++) { 4453 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i); 4454 if (outputDesc->mRefCount[s] != 0) { 4455 return true; 4456 } 4457 } 4458 } 4459 return false; 4460} 4461 4462uint32_t AudioPolicyManager::handleEventForBeacon(int event) { 4463 switch(event) { 4464 case STARTING_OUTPUT: 4465 mBeaconMuteRefCount++; 4466 break; 4467 case STOPPING_OUTPUT: 4468 if (mBeaconMuteRefCount > 0) { 4469 mBeaconMuteRefCount--; 4470 } 4471 break; 4472 case STARTING_BEACON: 4473 mBeaconPlayingRefCount++; 4474 break; 4475 case STOPPING_BEACON: 4476 if (mBeaconPlayingRefCount > 0) { 4477 mBeaconPlayingRefCount--; 4478 } 4479 break; 4480 } 4481 4482 if (mBeaconMuteRefCount > 0) { 4483 // any playback causes beacon to be muted 4484 return setBeaconMute(true); 4485 } else { 4486 // no other playback: unmute when beacon starts playing, mute when it stops 4487 return setBeaconMute(mBeaconPlayingRefCount == 0); 4488 } 4489} 4490 4491uint32_t AudioPolicyManager::setBeaconMute(bool mute) { 4492 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d", 4493 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount); 4494 // keep track of muted state to avoid repeating mute/unmute operations 4495 if (mBeaconMuted != mute) { 4496 // mute/unmute AUDIO_STREAM_TTS on all outputs 4497 ALOGV("\t muting %d", mute); 4498 uint32_t maxLatency = 0; 4499 for (size_t i = 0; i < mOutputs.size(); i++) { 4500 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 4501 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/, 4502 desc->mIoHandle, 4503 0 /*delay*/, AUDIO_DEVICE_NONE); 4504 const uint32_t latency = desc->latency() * 2; 4505 if (latency > maxLatency) { 4506 maxLatency = latency; 4507 } 4508 } 4509 mBeaconMuted = mute; 4510 return maxLatency; 4511 } 4512 return 0; 4513} 4514 4515audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy, 4516 bool fromCache) 4517{ 4518 uint32_t device = AUDIO_DEVICE_NONE; 4519 4520 if (fromCache) { 4521 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x", 4522 strategy, mDeviceForStrategy[strategy]); 4523 return mDeviceForStrategy[strategy]; 4524 } 4525 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types(); 4526 switch (strategy) { 4527 4528 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER: 4529 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER; 4530 if (!device) { 4531 ALOGE("getDeviceForStrategy() no device found for "\ 4532 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER"); 4533 } 4534 break; 4535 4536 case STRATEGY_SONIFICATION_RESPECTFUL: 4537 if (isInCall()) { 4538 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/); 4539 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC, 4540 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) { 4541 // while media is playing on a remote device, use the the sonification behavior. 4542 // Note that we test this usecase before testing if media is playing because 4543 // the isStreamActive() method only informs about the activity of a stream, not 4544 // if it's for local playback. Note also that we use the same delay between both tests 4545 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/); 4546 //user "safe" speaker if available instead of normal speaker to avoid triggering 4547 //other acoustic safety mechanisms for notification 4548 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE)) 4549 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE; 4550 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) { 4551 // while media is playing (or has recently played), use the same device 4552 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/); 4553 } else { 4554 // when media is not playing anymore, fall back on the sonification behavior 4555 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/); 4556 //user "safe" speaker if available instead of normal speaker to avoid triggering 4557 //other acoustic safety mechanisms for notification 4558 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE)) 4559 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE; 4560 } 4561 4562 break; 4563 4564 case STRATEGY_DTMF: 4565 if (!isInCall()) { 4566 // when off call, DTMF strategy follows the same rules as MEDIA strategy 4567 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/); 4568 break; 4569 } 4570 // when in call, DTMF and PHONE strategies follow the same rules 4571 // FALL THROUGH 4572 4573 case STRATEGY_PHONE: 4574 // Force use of only devices on primary output if: 4575 // - in call AND 4576 // - cannot route from voice call RX OR 4577 // - audio HAL version is < 3.0 and TX device is on the primary HW module 4578 if (mPhoneState == AUDIO_MODE_IN_CALL) { 4579 audio_devices_t txDevice = 4580 getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION); 4581 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput); 4582 if (((mAvailableInputDevices.types() & 4583 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) || 4584 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) && 4585 (hwOutputDesc->getAudioPort()->mModule->mHalVersion < 4586 AUDIO_DEVICE_API_VERSION_3_0))) { 4587 availableOutputDeviceTypes = availablePrimaryOutputDevices(); 4588 } 4589 } 4590 // for phone strategy, we first consider the forced use and then the available devices by order 4591 // of priority 4592 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) { 4593 case AUDIO_POLICY_FORCE_BT_SCO: 4594 if (!isInCall() || strategy != STRATEGY_DTMF) { 4595 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT; 4596 if (device) break; 4597 } 4598 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET; 4599 if (device) break; 4600 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO; 4601 if (device) break; 4602 // if SCO device is requested but no SCO device is available, fall back to default case 4603 // FALL THROUGH 4604 4605 default: // FORCE_NONE 4606 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP 4607 if (!isInCall() && 4608 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) && 4609 (getA2dpOutput() != 0)) { 4610 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP; 4611 if (device) break; 4612 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES; 4613 if (device) break; 4614 } 4615 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE; 4616 if (device) break; 4617 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET; 4618 if (device) break; 4619 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE; 4620 if (device) break; 4621 if (mPhoneState != AUDIO_MODE_IN_CALL) { 4622 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY; 4623 if (device) break; 4624 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET; 4625 if (device) break; 4626 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL; 4627 if (device) break; 4628 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET; 4629 if (device) break; 4630 } 4631 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE; 4632 if (device) break; 4633 device = mDefaultOutputDevice->mDeviceType; 4634 if (device == AUDIO_DEVICE_NONE) { 4635 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE"); 4636 } 4637 break; 4638 4639 case AUDIO_POLICY_FORCE_SPEAKER: 4640 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to 4641 // A2DP speaker when forcing to speaker output 4642 if (!isInCall() && 4643 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) && 4644 (getA2dpOutput() != 0)) { 4645 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER; 4646 if (device) break; 4647 } 4648 if (!isInCall()) { 4649 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY; 4650 if (device) break; 4651 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE; 4652 if (device) break; 4653 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET; 4654 if (device) break; 4655 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL; 4656 if (device) break; 4657 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET; 4658 if (device) break; 4659 } 4660 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE; 4661 if (device) break; 4662 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER; 4663 if (device) break; 4664 device = mDefaultOutputDevice->mDeviceType; 4665 if (device == AUDIO_DEVICE_NONE) { 4666 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER"); 4667 } 4668 break; 4669 } 4670 break; 4671 4672 case STRATEGY_SONIFICATION: 4673 4674 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by 4675 // handleIncallSonification(). 4676 if (isInCall()) { 4677 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/); 4678 break; 4679 } 4680 // FALL THROUGH 4681 4682 case STRATEGY_ENFORCED_AUDIBLE: 4683 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION 4684 // except: 4685 // - when in call where it doesn't default to STRATEGY_PHONE behavior 4686 // - in countries where not enforced in which case it follows STRATEGY_MEDIA 4687 4688 if ((strategy == STRATEGY_SONIFICATION) || 4689 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) { 4690 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER; 4691 if (device == AUDIO_DEVICE_NONE) { 4692 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION"); 4693 } 4694 } 4695 // The second device used for sonification is the same as the device used by media strategy 4696 // FALL THROUGH 4697 4698 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now 4699 case STRATEGY_ACCESSIBILITY: 4700 if (strategy == STRATEGY_ACCESSIBILITY) { 4701 // do not route accessibility prompts to a digital output currently configured with a 4702 // compressed format as they would likely not be mixed and dropped. 4703 for (size_t i = 0; i < mOutputs.size(); i++) { 4704 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i); 4705 audio_devices_t devices = desc->device() & 4706 (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC); 4707 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) && 4708 devices != AUDIO_DEVICE_NONE) { 4709 availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices; 4710 } 4711 } 4712 } 4713 // FALL THROUGH 4714 4715 case STRATEGY_REROUTING: 4716 case STRATEGY_MEDIA: { 4717 uint32_t device2 = AUDIO_DEVICE_NONE; 4718 if (strategy != STRATEGY_SONIFICATION) { 4719 // no sonification on remote submix (e.g. WFD) 4720 if (mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, String8("0")) != 0) { 4721 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX; 4722 } 4723 } 4724 if ((device2 == AUDIO_DEVICE_NONE) && 4725 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) && 4726 (getA2dpOutput() != 0)) { 4727 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP; 4728 if (device2 == AUDIO_DEVICE_NONE) { 4729 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES; 4730 } 4731 if (device2 == AUDIO_DEVICE_NONE) { 4732 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER; 4733 } 4734 } 4735 if ((device2 == AUDIO_DEVICE_NONE) && 4736 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) { 4737 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER; 4738 } 4739 if (device2 == AUDIO_DEVICE_NONE) { 4740 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE; 4741 } 4742 if ((device2 == AUDIO_DEVICE_NONE)) { 4743 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE; 4744 } 4745 if (device2 == AUDIO_DEVICE_NONE) { 4746 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET; 4747 } 4748 if (device2 == AUDIO_DEVICE_NONE) { 4749 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY; 4750 } 4751 if (device2 == AUDIO_DEVICE_NONE) { 4752 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE; 4753 } 4754 if (device2 == AUDIO_DEVICE_NONE) { 4755 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET; 4756 } 4757 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) { 4758 // no sonification on aux digital (e.g. HDMI) 4759 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL; 4760 } 4761 if ((device2 == AUDIO_DEVICE_NONE) && 4762 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) { 4763 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET; 4764 } 4765 if (device2 == AUDIO_DEVICE_NONE) { 4766 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER; 4767 } 4768 int device3 = AUDIO_DEVICE_NONE; 4769 if (strategy == STRATEGY_MEDIA) { 4770 // ARC, SPDIF and AUX_LINE can co-exist with others. 4771 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC; 4772 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF); 4773 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE); 4774 } 4775 4776 device2 |= device3; 4777 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or 4778 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise 4779 device |= device2; 4780 4781 // If hdmi system audio mode is on, remove speaker out of output list. 4782 if ((strategy == STRATEGY_MEDIA) && 4783 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] == 4784 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) { 4785 device &= ~AUDIO_DEVICE_OUT_SPEAKER; 4786 } 4787 4788 if (device) break; 4789 device = mDefaultOutputDevice->mDeviceType; 4790 if (device == AUDIO_DEVICE_NONE) { 4791 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA"); 4792 } 4793 } break; 4794 4795 default: 4796 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy); 4797 break; 4798 } 4799 4800 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device); 4801 return device; 4802} 4803 4804void AudioPolicyManager::updateDevicesAndOutputs() 4805{ 4806 for (int i = 0; i < NUM_STRATEGIES; i++) { 4807 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/); 4808 } 4809 mPreviousOutputs = mOutputs; 4810} 4811 4812uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc, 4813 audio_devices_t prevDevice, 4814 uint32_t delayMs) 4815{ 4816 // mute/unmute strategies using an incompatible device combination 4817 // if muting, wait for the audio in pcm buffer to be drained before proceeding 4818 // if unmuting, unmute only after the specified delay 4819 if (outputDesc->isDuplicated()) { 4820 return 0; 4821 } 4822 4823 uint32_t muteWaitMs = 0; 4824 audio_devices_t device = outputDesc->device(); 4825 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2); 4826 4827 for (size_t i = 0; i < NUM_STRATEGIES; i++) { 4828 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/); 4829 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types(); 4830 bool mute = shouldMute && (curDevice & device) && (curDevice != device); 4831 bool doMute = false; 4832 4833 if (mute && !outputDesc->mStrategyMutedByDevice[i]) { 4834 doMute = true; 4835 outputDesc->mStrategyMutedByDevice[i] = true; 4836 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){ 4837 doMute = true; 4838 outputDesc->mStrategyMutedByDevice[i] = false; 4839 } 4840 if (doMute) { 4841 for (size_t j = 0; j < mOutputs.size(); j++) { 4842 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j); 4843 // skip output if it does not share any device with current output 4844 if ((desc->supportedDevices() & outputDesc->supportedDevices()) 4845 == AUDIO_DEVICE_NONE) { 4846 continue; 4847 } 4848 audio_io_handle_t curOutput = mOutputs.keyAt(j); 4849 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d", 4850 mute ? "muting" : "unmuting", i, curDevice, curOutput); 4851 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs); 4852 if (desc->isStrategyActive((routing_strategy)i)) { 4853 if (mute) { 4854 // FIXME: should not need to double latency if volume could be applied 4855 // immediately by the audioflinger mixer. We must account for the delay 4856 // between now and the next time the audioflinger thread for this output 4857 // will process a buffer (which corresponds to one buffer size, 4858 // usually 1/2 or 1/4 of the latency). 4859 if (muteWaitMs < desc->latency() * 2) { 4860 muteWaitMs = desc->latency() * 2; 4861 } 4862 } 4863 } 4864 } 4865 } 4866 } 4867 4868 // temporary mute output if device selection changes to avoid volume bursts due to 4869 // different per device volumes 4870 if (outputDesc->isActive() && (device != prevDevice)) { 4871 if (muteWaitMs < outputDesc->latency() * 2) { 4872 muteWaitMs = outputDesc->latency() * 2; 4873 } 4874 for (size_t i = 0; i < NUM_STRATEGIES; i++) { 4875 if (outputDesc->isStrategyActive((routing_strategy)i)) { 4876 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle); 4877 // do tempMute unmute after twice the mute wait time 4878 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle, 4879 muteWaitMs *2, device); 4880 } 4881 } 4882 } 4883 4884 // wait for the PCM output buffers to empty before proceeding with the rest of the command 4885 if (muteWaitMs > delayMs) { 4886 muteWaitMs -= delayMs; 4887 usleep(muteWaitMs * 1000); 4888 return muteWaitMs; 4889 } 4890 return 0; 4891} 4892 4893uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output, 4894 audio_devices_t device, 4895 bool force, 4896 int delayMs, 4897 audio_patch_handle_t *patchHandle, 4898 const char* address) 4899{ 4900 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs); 4901 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 4902 AudioParameter param; 4903 uint32_t muteWaitMs; 4904 4905 if (outputDesc->isDuplicated()) { 4906 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs); 4907 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs); 4908 return muteWaitMs; 4909 } 4910 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current 4911 // output profile 4912 if ((device != AUDIO_DEVICE_NONE) && 4913 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) { 4914 return 0; 4915 } 4916 4917 // filter devices according to output selected 4918 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types()); 4919 4920 audio_devices_t prevDevice = outputDesc->mDevice; 4921 4922 ALOGV("setOutputDevice() prevDevice %04x", prevDevice); 4923 4924 if (device != AUDIO_DEVICE_NONE) { 4925 outputDesc->mDevice = device; 4926 } 4927 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs); 4928 4929 // Do not change the routing if: 4930 // the requested device is AUDIO_DEVICE_NONE 4931 // OR the requested device is the same as current device 4932 // AND force is not specified 4933 // AND the output is connected by a valid audio patch. 4934 // Doing this check here allows the caller to call setOutputDevice() without conditions 4935 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force && 4936 outputDesc->mPatchHandle != 0) { 4937 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", 4938 device, output); 4939 return muteWaitMs; 4940 } 4941 4942 ALOGV("setOutputDevice() changing device"); 4943 4944 // do the routing 4945 if (device == AUDIO_DEVICE_NONE) { 4946 resetOutputDevice(output, delayMs, NULL); 4947 } else { 4948 DeviceVector deviceList = (address == NULL) ? 4949 mAvailableOutputDevices.getDevicesFromType(device) 4950 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address)); 4951 if (!deviceList.isEmpty()) { 4952 struct audio_patch patch; 4953 outputDesc->toAudioPortConfig(&patch.sources[0]); 4954 patch.num_sources = 1; 4955 patch.num_sinks = 0; 4956 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) { 4957 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]); 4958 patch.num_sinks++; 4959 } 4960 ssize_t index; 4961 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) { 4962 index = mAudioPatches.indexOfKey(*patchHandle); 4963 } else { 4964 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle); 4965 } 4966 sp< AudioPatch> patchDesc; 4967 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE; 4968 if (index >= 0) { 4969 patchDesc = mAudioPatches.valueAt(index); 4970 afPatchHandle = patchDesc->mAfPatchHandle; 4971 } 4972 4973 status_t status = mpClientInterface->createAudioPatch(&patch, 4974 &afPatchHandle, 4975 delayMs); 4976 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d" 4977 "num_sources %d num_sinks %d", 4978 status, afPatchHandle, patch.num_sources, patch.num_sinks); 4979 if (status == NO_ERROR) { 4980 if (index < 0) { 4981 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(), 4982 &patch, mUidCached); 4983 addAudioPatch(patchDesc->mHandle, patchDesc); 4984 } else { 4985 patchDesc->mPatch = patch; 4986 } 4987 patchDesc->mAfPatchHandle = afPatchHandle; 4988 patchDesc->mUid = mUidCached; 4989 if (patchHandle) { 4990 *patchHandle = patchDesc->mHandle; 4991 } 4992 outputDesc->mPatchHandle = patchDesc->mHandle; 4993 nextAudioPortGeneration(); 4994 mpClientInterface->onAudioPatchListUpdate(); 4995 } 4996 } 4997 4998 // inform all input as well 4999 for (size_t i = 0; i < mInputs.size(); i++) { 5000 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i); 5001 if (!isVirtualInputDevice(inputDescriptor->mDevice)) { 5002 AudioParameter inputCmd = AudioParameter(); 5003 ALOGV("%s: inform input %d of device:%d", __func__, 5004 inputDescriptor->mIoHandle, device); 5005 inputCmd.addInt(String8(AudioParameter::keyRouting),device); 5006 mpClientInterface->setParameters(inputDescriptor->mIoHandle, 5007 inputCmd.toString(), 5008 delayMs); 5009 } 5010 } 5011 } 5012 5013 // update stream volumes according to new device 5014 applyStreamVolumes(output, device, delayMs); 5015 5016 return muteWaitMs; 5017} 5018 5019status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output, 5020 int delayMs, 5021 audio_patch_handle_t *patchHandle) 5022{ 5023 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output); 5024 ssize_t index; 5025 if (patchHandle) { 5026 index = mAudioPatches.indexOfKey(*patchHandle); 5027 } else { 5028 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle); 5029 } 5030 if (index < 0) { 5031 return INVALID_OPERATION; 5032 } 5033 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index); 5034 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs); 5035 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status); 5036 outputDesc->mPatchHandle = 0; 5037 removeAudioPatch(patchDesc->mHandle); 5038 nextAudioPortGeneration(); 5039 mpClientInterface->onAudioPatchListUpdate(); 5040 return status; 5041} 5042 5043status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input, 5044 audio_devices_t device, 5045 bool force, 5046 audio_patch_handle_t *patchHandle) 5047{ 5048 status_t status = NO_ERROR; 5049 5050 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input); 5051 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) { 5052 inputDesc->mDevice = device; 5053 5054 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device); 5055 if (!deviceList.isEmpty()) { 5056 struct audio_patch patch; 5057 inputDesc->toAudioPortConfig(&patch.sinks[0]); 5058 // AUDIO_SOURCE_HOTWORD is for internal use only: 5059 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL 5060 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD && 5061 !inputDesc->