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