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