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