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