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