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