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