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