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