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