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