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