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