2 * Copyright (C) 2009 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define LOG_TAG "AudioPolicyManagerBase"
18 //#define LOG_NDEBUG 0
20 //#define VERY_VERBOSE_LOGGING
21 #ifdef VERY_VERBOSE_LOGGING
24 #define ALOGVV(a...) do { } while(0)
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
34 #include <utils/Log.h>
35 #include <hardware_legacy/AudioPolicyManagerBase.h>
36 #include <hardware/audio_effect.h>
37 #include <hardware/audio.h>
39 #include <hardware_legacy/audio_policy_conf.h>
40 #include <cutils/properties.h>
42 namespace android_audio_legacy {
44 // ----------------------------------------------------------------------------
45 // AudioPolicyInterface implementation
46 // ----------------------------------------------------------------------------
49 status_t AudioPolicyManagerBase::setDeviceConnectionState(audio_devices_t device,
50 AudioSystem::device_connection_state state,
51 const char *device_address)
53 SortedVector <audio_io_handle_t> outputs;
55 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
57 // connect/disconnect only 1 device at a time
58 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
60 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
61 ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
65 // handle output devices
66 if (audio_is_output_device(device)) {
68 if (!mHasA2dp && audio_is_a2dp_device(device)) {
69 ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device);
72 if (!mHasUsb && audio_is_usb_device(device)) {
73 ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device);
76 if (!mHasRemoteSubmix && audio_is_remote_submix_device((audio_devices_t)device)) {
77 ALOGE("setDeviceConnectionState() invalid remote submix audio device: %x", device);
81 // save a copy of the opened output descriptors before any output is opened or closed
82 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
83 mPreviousOutputs = mOutputs;
86 // handle output device connection
87 case AudioSystem::DEVICE_STATE_AVAILABLE:
88 if (mAvailableOutputDevices & device) {
89 ALOGW("setDeviceConnectionState() device already connected: %x", device);
90 return INVALID_OPERATION;
92 ALOGV("setDeviceConnectionState() connecting device %x", device);
94 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
95 return INVALID_OPERATION;
97 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %d outputs",
99 // register new device as available
100 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
102 if (!outputs.isEmpty()) {
104 if (mHasA2dp && audio_is_a2dp_device(device)) {
105 // handle A2DP device connection
106 AudioParameter param;
107 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
108 paramStr = param.toString();
109 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
110 mA2dpSuspended = false;
111 } else if (audio_is_bluetooth_sco_device(device)) {
112 // handle SCO device connection
113 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
114 } else if (mHasUsb && audio_is_usb_device(device)) {
115 // handle USB device connection
116 mUsbCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
117 paramStr = mUsbCardAndDevice;
119 // not currently handling multiple simultaneous submixes: ignoring remote submix
121 if (!paramStr.isEmpty()) {
122 for (size_t i = 0; i < outputs.size(); i++) {
123 mpClientInterface->setParameters(outputs[i], paramStr);
128 // handle output device disconnection
129 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
130 if (!(mAvailableOutputDevices & device)) {
131 ALOGW("setDeviceConnectionState() device not connected: %x", device);
132 return INVALID_OPERATION;
135 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
136 // remove device from available output devices
137 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
139 checkOutputsForDevice(device, state, outputs);
140 if (mHasA2dp && audio_is_a2dp_device(device)) {
141 // handle A2DP device disconnection
142 mA2dpDeviceAddress = "";
143 mA2dpSuspended = false;
144 } else if (audio_is_bluetooth_sco_device(device)) {
145 // handle SCO device disconnection
146 mScoDeviceAddress = "";
147 } else if (mHasUsb && audio_is_usb_device(device)) {
148 // handle USB device disconnection
149 mUsbCardAndDevice = "";
151 // not currently handling multiple simultaneous submixes: ignoring remote submix
156 ALOGE("setDeviceConnectionState() invalid state: %x", state);
161 checkOutputForAllStrategies();
162 // outputs must be closed after checkOutputForAllStrategies() is executed
163 if (!outputs.isEmpty()) {
164 for (size_t i = 0; i < outputs.size(); i++) {
165 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
166 // close unused outputs after device disconnection or direct outputs that have been
167 // opened by checkOutputsForDevice() to query dynamic parameters
168 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
169 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
170 (desc->mDirectOpenCount == 0))) {
171 closeOutput(outputs[i]);
176 updateDevicesAndOutputs();
177 for (size_t i = 0; i < mOutputs.size(); i++) {
178 // do not force device change on duplicated output because if device is 0, it will
179 // also force a device 0 for the two outputs it is duplicated to which may override
180 // a valid device selection on those outputs.
181 setOutputDevice(mOutputs.keyAt(i),
182 getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
183 !mOutputs.valueAt(i)->isDuplicated(),
187 if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
188 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
189 } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
190 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
191 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
192 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
197 // handle input devices
198 if (audio_is_input_device(device)) {
202 // handle input device connection
203 case AudioSystem::DEVICE_STATE_AVAILABLE: {
204 if (mAvailableInputDevices & device) {
205 ALOGW("setDeviceConnectionState() device already connected: %d", device);
206 return INVALID_OPERATION;
208 mAvailableInputDevices = mAvailableInputDevices | (device & ~AUDIO_DEVICE_BIT_IN);
212 // handle input device disconnection
213 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
214 if (!(mAvailableInputDevices & device)) {
215 ALOGW("setDeviceConnectionState() device not connected: %d", device);
216 return INVALID_OPERATION;
218 mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
222 ALOGE("setDeviceConnectionState() invalid state: %x", state);
226 audio_io_handle_t activeInput = getActiveInput();
227 if (activeInput != 0) {
228 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
229 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
230 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
231 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
232 inputDesc->mDevice, newDevice, activeInput);
233 inputDesc->mDevice = newDevice;
234 AudioParameter param = AudioParameter();
235 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
236 mpClientInterface->setParameters(activeInput, param.toString());
243 ALOGW("setDeviceConnectionState() invalid device: %x", device);
247 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(audio_devices_t device,
248 const char *device_address)
250 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
251 String8 address = String8(device_address);
252 if (audio_is_output_device(device)) {
253 if (device & mAvailableOutputDevices) {
254 if (audio_is_a2dp_device(device) &&
255 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
258 if (audio_is_bluetooth_sco_device(device) &&
259 address != "" && mScoDeviceAddress != address) {
262 if (audio_is_usb_device(device) &&
263 (!mHasUsb || (address != "" && mUsbCardAndDevice != address))) {
264 ALOGE("getDeviceConnectionState() invalid device: %x", device);
267 if (audio_is_remote_submix_device((audio_devices_t)device) && !mHasRemoteSubmix) {
270 state = AudioSystem::DEVICE_STATE_AVAILABLE;
272 } else if (audio_is_input_device(device)) {
273 if (device & mAvailableInputDevices) {
274 state = AudioSystem::DEVICE_STATE_AVAILABLE;
281 void AudioPolicyManagerBase::setPhoneState(int state)
283 ALOGV("setPhoneState() state %d", state);
284 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
285 if (state < 0 || state >= AudioSystem::NUM_MODES) {
286 ALOGW("setPhoneState() invalid state %d", state);
290 if (state == mPhoneState ) {
291 ALOGW("setPhoneState() setting same state %d", state);
295 // if leaving call state, handle special case of active streams
296 // pertaining to sonification strategy see handleIncallSonification()
298 ALOGV("setPhoneState() in call state management: new state is %d", state);
299 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
300 handleIncallSonification(stream, false, true);
304 // store previous phone state for management of sonification strategy below
305 int oldState = mPhoneState;
309 // are we entering or starting a call
310 if (!isStateInCall(oldState) && isStateInCall(state)) {
311 ALOGV(" Entering call in setPhoneState()");
312 // force routing command to audio hardware when starting a call
313 // even if no device change is needed
315 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
316 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
317 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
319 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
320 ALOGV(" Exiting call in setPhoneState()");
321 // force routing command to audio hardware when exiting a call
322 // even if no device change is needed
324 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
325 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
326 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
328 } else if (isStateInCall(state) && (state != oldState)) {
329 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
330 // force routing command to audio hardware when switching between telephony and VoIP
331 // even if no device change is needed
335 // check for device and output changes triggered by new phone state
336 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
338 checkOutputForAllStrategies();
339 updateDevicesAndOutputs();
341 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
343 // force routing command to audio hardware when ending call
344 // even if no device change is needed
345 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
346 newDevice = hwOutputDesc->device();
350 if (isStateInCall(state)) {
351 nsecs_t sysTime = systemTime();
352 for (size_t i = 0; i < mOutputs.size(); i++) {
353 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
354 // mute media and sonification strategies and delay device switch by the largest
355 // latency of any output where either strategy is active.
356 // This avoid sending the ring tone or music tail into the earpiece or headset.
357 if ((desc->isStrategyActive(STRATEGY_MEDIA,
358 SONIFICATION_HEADSET_MUSIC_DELAY,
360 desc->isStrategyActive(STRATEGY_SONIFICATION,
361 SONIFICATION_HEADSET_MUSIC_DELAY,
363 (delayMs < (int)desc->mLatency*2)) {
364 delayMs = desc->mLatency*2;
366 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
367 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
368 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
369 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
370 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
371 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
375 // change routing is necessary
376 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
378 // if entering in call state, handle special case of active streams
379 // pertaining to sonification strategy see handleIncallSonification()
380 if (isStateInCall(state)) {
381 ALOGV("setPhoneState() in call state management: new state is %d", state);
382 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
383 handleIncallSonification(stream, true, true);
387 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
388 if (state == AudioSystem::MODE_RINGTONE &&
389 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
390 mLimitRingtoneVolume = true;
392 mLimitRingtoneVolume = false;
396 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
398 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
400 bool forceVolumeReeval = false;
402 case AudioSystem::FOR_COMMUNICATION:
403 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
404 config != AudioSystem::FORCE_NONE) {
405 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
408 forceVolumeReeval = true;
409 mForceUse[usage] = config;
411 case AudioSystem::FOR_MEDIA:
412 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
413 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
414 config != AudioSystem::FORCE_ANALOG_DOCK &&
415 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
416 config != AudioSystem::FORCE_NO_BT_A2DP) {
417 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
420 mForceUse[usage] = config;
422 case AudioSystem::FOR_RECORD:
423 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
424 config != AudioSystem::FORCE_NONE) {
425 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
428 mForceUse[usage] = config;
430 case AudioSystem::FOR_DOCK:
431 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
432 config != AudioSystem::FORCE_BT_DESK_DOCK &&
433 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
434 config != AudioSystem::FORCE_ANALOG_DOCK &&
435 config != AudioSystem::FORCE_DIGITAL_DOCK) {
436 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
438 forceVolumeReeval = true;
439 mForceUse[usage] = config;
441 case AudioSystem::FOR_SYSTEM:
442 if (config != AudioSystem::FORCE_NONE &&
443 config != AudioSystem::FORCE_SYSTEM_ENFORCED) {
444 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
446 forceVolumeReeval = true;
447 mForceUse[usage] = config;
450 ALOGW("setForceUse() invalid usage %d", usage);
454 // check for device and output changes triggered by new force usage
456 checkOutputForAllStrategies();
457 updateDevicesAndOutputs();
458 for (size_t i = 0; i < mOutputs.size(); i++) {
459 audio_io_handle_t output = mOutputs.keyAt(i);
460 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
461 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
462 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
463 applyStreamVolumes(output, newDevice, 0, true);
467 audio_io_handle_t activeInput = getActiveInput();
468 if (activeInput != 0) {
469 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
470 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
471 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
472 ALOGV("setForceUse() changing device from %x to %x for input %d",
473 inputDesc->mDevice, newDevice, activeInput);
474 inputDesc->mDevice = newDevice;
475 AudioParameter param = AudioParameter();
476 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
477 mpClientInterface->setParameters(activeInput, param.toString());
483 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
485 return mForceUse[usage];
488 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
490 ALOGV("setSystemProperty() property %s, value %s", property, value);
493 // Find a direct output profile compatible with the parameters passed, even if the input flags do
494 // not explicitly request a direct output
495 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
496 audio_devices_t device,
497 uint32_t samplingRate,
499 uint32_t channelMask,
500 audio_output_flags_t flags)
502 for (size_t i = 0; i < mHwModules.size(); i++) {
503 if (mHwModules[i]->mHandle == 0) {
506 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
507 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
508 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
509 if (profile->isCompatibleProfile(device, samplingRate, format,
511 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
512 if (mAvailableOutputDevices & profile->mSupportedDevices) {
513 return mHwModules[i]->mOutputProfiles[j];
517 if (profile->isCompatibleProfile(device, samplingRate, format,
519 AUDIO_OUTPUT_FLAG_DIRECT)) {
520 if (mAvailableOutputDevices & profile->mSupportedDevices) {
521 return mHwModules[i]->mOutputProfiles[j];
530 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
531 uint32_t samplingRate,
533 uint32_t channelMask,
534 AudioSystem::output_flags flags,
535 const audio_offload_info_t *offloadInfo)
537 audio_io_handle_t output = 0;
538 uint32_t latency = 0;
539 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
540 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
541 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
542 device, stream, samplingRate, format, channelMask, flags);
544 #ifdef AUDIO_POLICY_TEST
545 if (mCurOutput != 0) {
546 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
547 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
549 if (mTestOutputs[mCurOutput] == 0) {
550 ALOGV("getOutput() opening test output");
551 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
552 outputDesc->mDevice = mTestDevice;
553 outputDesc->mSamplingRate = mTestSamplingRate;
554 outputDesc->mFormat = mTestFormat;
555 outputDesc->mChannelMask = mTestChannels;
556 outputDesc->mLatency = mTestLatencyMs;
557 outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
558 outputDesc->mRefCount[stream] = 0;
559 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
560 &outputDesc->mSamplingRate,
561 &outputDesc->mFormat,
562 &outputDesc->mChannelMask,
563 &outputDesc->mLatency,
566 if (mTestOutputs[mCurOutput]) {
567 AudioParameter outputCmd = AudioParameter();
568 outputCmd.addInt(String8("set_id"),mCurOutput);
569 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
570 addOutput(mTestOutputs[mCurOutput], outputDesc);
573 return mTestOutputs[mCurOutput];
575 #endif //AUDIO_POLICY_TEST
577 // open a direct output if required by specified parameters
578 //force direct flag if offload flag is set: offloading implies a direct output stream
579 // and all common behaviors are driven by checking only the direct flag
580 // this should normally be set appropriately in the policy configuration file
581 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
582 flags = (AudioSystem::output_flags)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
585 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
586 // creating an offloaded track and tearing it down immediately after start when audioflinger
587 // detects there is an active non offloadable effect.
588 // FIXME: We should check the audio session here but we do not have it in this context.
589 // This may prevent offloading in rare situations where effects are left active by apps
590 // in the background.
591 IOProfile *profile = NULL;
592 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
593 !isNonOffloadableEffectEnabled()) {
594 profile = getProfileForDirectOutput(device,
598 (audio_output_flags_t)flags);
601 if (profile != NULL) {
602 AudioOutputDescriptor *outputDesc = NULL;
604 for (size_t i = 0; i < mOutputs.size(); i++) {
605 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
606 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
608 // reuse direct output if currently open and configured with same parameters
609 if ((samplingRate == outputDesc->mSamplingRate) &&
610 (format == outputDesc->mFormat) &&
611 (channelMask == outputDesc->mChannelMask)) {
612 outputDesc->mDirectOpenCount++;
613 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
614 return mOutputs.keyAt(i);
618 // close direct output if currently open and configured with different parameters
619 if (outputDesc != NULL) {
620 closeOutput(outputDesc->mId);
622 outputDesc = new AudioOutputDescriptor(profile);
623 outputDesc->mDevice = device;
624 outputDesc->mSamplingRate = samplingRate;
625 outputDesc->mFormat = (audio_format_t)format;
626 outputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
627 outputDesc->mLatency = 0;
628 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
629 outputDesc->mRefCount[stream] = 0;
630 outputDesc->mStopTime[stream] = 0;
631 outputDesc->mDirectOpenCount = 1;
632 output = mpClientInterface->openOutput(profile->mModule->mHandle,
633 &outputDesc->mDevice,
634 &outputDesc->mSamplingRate,
635 &outputDesc->mFormat,
636 &outputDesc->mChannelMask,
637 &outputDesc->mLatency,
641 // only accept an output with the requested parameters
643 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
644 (format != 0 && format != outputDesc->mFormat) ||
645 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
646 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
647 "format %d %d, channelMask %04x %04x", output, samplingRate,
648 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
649 outputDesc->mChannelMask);
651 mpClientInterface->closeOutput(output);
656 audio_io_handle_t srcOutput = getOutputForEffect();
657 addOutput(output, outputDesc);
658 audio_io_handle_t dstOutput = getOutputForEffect();
659 if (dstOutput == output) {
660 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
662 mPreviousOutputs = mOutputs;
663 ALOGV("getOutput() returns new direct output %d", output);
667 // ignoring channel mask due to downmix capability in mixer
669 // open a non direct output
671 // for non direct outputs, only PCM is supported
672 if (audio_is_linear_pcm((audio_format_t)format)) {
673 // get which output is suitable for the specified stream. The actual
674 // routing change will happen when startOutput() will be called
675 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
677 output = selectOutput(outputs, flags);
679 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
680 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
682 ALOGV("getOutput() returns output %d", output);
687 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
688 AudioSystem::output_flags flags)
690 // select one output among several that provide a path to a particular device or set of
691 // devices (the list was previously build by getOutputsForDevice()).
692 // The priority is as follows:
693 // 1: the output with the highest number of requested policy flags
694 // 2: the primary output
695 // 3: the first output in the list
697 if (outputs.size() == 0) {
700 if (outputs.size() == 1) {
704 int maxCommonFlags = 0;
705 audio_io_handle_t outputFlags = 0;
706 audio_io_handle_t outputPrimary = 0;
708 for (size_t i = 0; i < outputs.size(); i++) {
709 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
710 if (!outputDesc->isDuplicated()) {
711 int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
712 if (commonFlags > maxCommonFlags) {
713 outputFlags = outputs[i];
714 maxCommonFlags = commonFlags;
715 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
717 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
718 outputPrimary = outputs[i];
723 if (outputFlags != 0) {
726 if (outputPrimary != 0) {
727 return outputPrimary;
733 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
734 AudioSystem::stream_type stream,
737 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
738 ssize_t index = mOutputs.indexOfKey(output);
740 ALOGW("startOutput() unknow output %d", output);
744 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
746 // increment usage count for this stream on the requested output:
747 // NOTE that the usage count is the same for duplicated output and hardware output which is
748 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
749 outputDesc->changeRefCount(stream, 1);
751 if (outputDesc->mRefCount[stream] == 1) {
752 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
753 routing_strategy strategy = getStrategy(stream);
754 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
755 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
758 for (size_t i = 0; i < mOutputs.size(); i++) {
759 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
760 if (desc != outputDesc) {
761 // force a device change if any other output is managed by the same hw
762 // module and has a current device selection that differs from selected device.
763 // In this case, the audio HAL must receive the new device selection so that it can
764 // change the device currently selected by the other active output.
765 if (outputDesc->sharesHwModuleWith(desc) &&
766 desc->device() != newDevice) {
769 // wait for audio on other active outputs to be presented when starting
770 // a notification so that audio focus effect can propagate.
771 uint32_t latency = desc->latency();
772 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
777 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
779 // handle special case for sonification while in call
781 handleIncallSonification(stream, true, false);
784 // apply volume rules for current stream and device if necessary
785 checkAndSetVolume(stream,
786 mStreams[stream].getVolumeIndex(newDevice),
790 // update the outputs if starting an output with a stream that can affect notification
792 handleNotificationRoutingForStream(stream);
793 if (waitMs > muteWaitMs) {
794 usleep((waitMs - muteWaitMs) * 2 * 1000);
801 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
802 AudioSystem::stream_type stream,
805 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
806 ssize_t index = mOutputs.indexOfKey(output);
808 ALOGW("stopOutput() unknow output %d", output);
812 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
814 // handle special case for sonification while in call
816 handleIncallSonification(stream, false, false);
819 if (outputDesc->mRefCount[stream] > 0) {
820 // decrement usage count of this stream on the output
821 outputDesc->changeRefCount(stream, -1);
822 // store time at which the stream was stopped - see isStreamActive()
823 if (outputDesc->mRefCount[stream] == 0) {
824 outputDesc->mStopTime[stream] = systemTime();
825 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
826 // delay the device switch by twice the latency because stopOutput() is executed when
827 // the track stop() command is received and at that time the audio track buffer can
828 // still contain data that needs to be drained. The latency only covers the audio HAL
829 // and kernel buffers. Also the latency does not always include additional delay in the
830 // audio path (audio DSP, CODEC ...)
831 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
833 // force restoring the device selection on other active outputs if it differs from the
834 // one being selected for this output
835 for (size_t i = 0; i < mOutputs.size(); i++) {
836 audio_io_handle_t curOutput = mOutputs.keyAt(i);
837 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
838 if (curOutput != output &&
840 outputDesc->sharesHwModuleWith(desc) &&
841 (newDevice != desc->device())) {
842 setOutputDevice(curOutput,
843 getNewDevice(curOutput, false /*fromCache*/),
845 outputDesc->mLatency*2);
848 // update the outputs if stopping one with a stream that can affect notification routing
849 handleNotificationRoutingForStream(stream);
853 ALOGW("stopOutput() refcount is already 0 for output %d", output);
854 return INVALID_OPERATION;
858 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
860 ALOGV("releaseOutput() %d", output);
861 ssize_t index = mOutputs.indexOfKey(output);
863 ALOGW("releaseOutput() releasing unknown output %d", output);
867 #ifdef AUDIO_POLICY_TEST
868 int testIndex = testOutputIndex(output);
869 if (testIndex != 0) {
870 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
871 if (outputDesc->isActive()) {
872 mpClientInterface->closeOutput(output);
873 delete mOutputs.valueAt(index);
874 mOutputs.removeItem(output);
875 mTestOutputs[testIndex] = 0;
879 #endif //AUDIO_POLICY_TEST
881 AudioOutputDescriptor *desc = mOutputs.valueAt(index);
882 if (desc->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
883 if (desc->mDirectOpenCount <= 0) {
884 ALOGW("releaseOutput() invalid open count %d for output %d",
885 desc->mDirectOpenCount, output);
888 if (--desc->mDirectOpenCount == 0) {
890 // If effects where present on the output, audioflinger moved them to the primary
891 // output by default: move them back to the appropriate output.
892 audio_io_handle_t dstOutput = getOutputForEffect();
893 if (dstOutput != mPrimaryOutput) {
894 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
901 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
902 uint32_t samplingRate,
904 uint32_t channelMask,
905 AudioSystem::audio_in_acoustics acoustics)
907 audio_io_handle_t input = 0;
908 audio_devices_t device = getDeviceForInputSource(inputSource);
910 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
911 inputSource, samplingRate, format, channelMask, acoustics);
913 if (device == AUDIO_DEVICE_NONE) {
914 ALOGW("getInput() could not find device for inputSource %d", inputSource);
918 // adapt channel selection to input source
919 switch(inputSource) {
920 case AUDIO_SOURCE_VOICE_UPLINK:
921 channelMask = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
923 case AUDIO_SOURCE_VOICE_DOWNLINK:
924 channelMask = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
926 case AUDIO_SOURCE_VOICE_CALL:
927 channelMask = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
933 IOProfile *profile = getInputProfile(device,
937 if (profile == NULL) {
938 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d,"
940 device, samplingRate, format, channelMask);
944 if (profile->mModule->mHandle == 0) {
945 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
949 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
951 inputDesc->mInputSource = inputSource;
952 inputDesc->mDevice = device;
953 inputDesc->mSamplingRate = samplingRate;
954 inputDesc->mFormat = (audio_format_t)format;
955 inputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
956 inputDesc->mRefCount = 0;
957 input = mpClientInterface->openInput(profile->mModule->mHandle,
959 &inputDesc->mSamplingRate,
961 &inputDesc->mChannelMask);
963 // only accept input with the exact requested set of parameters
965 (samplingRate != inputDesc->mSamplingRate) ||
966 (format != inputDesc->mFormat) ||
967 (channelMask != inputDesc->mChannelMask)) {
968 ALOGV("getInput() failed opening input: samplingRate %d, format %d, channelMask %d",
969 samplingRate, format, channelMask);
971 mpClientInterface->closeInput(input);
976 mInputs.add(input, inputDesc);
980 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
982 ALOGV("startInput() input %d", input);
983 ssize_t index = mInputs.indexOfKey(input);
985 ALOGW("startInput() unknow input %d", input);
988 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
990 #ifdef AUDIO_POLICY_TEST
992 #endif //AUDIO_POLICY_TEST
994 // refuse 2 active AudioRecord clients at the same time except if the active input
995 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
996 audio_io_handle_t activeInput = getActiveInput();
997 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
998 AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput);
999 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1000 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1001 stopInput(activeInput);
1002 releaseInput(activeInput);
1004 ALOGW("startInput() input %d failed: other input already started..", input);
1005 return INVALID_OPERATION;
1010 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
1011 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
1012 inputDesc->mDevice = newDevice;
1015 // automatically enable the remote submix output when input is started
1016 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1017 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1018 AudioSystem::DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1021 AudioParameter param = AudioParameter();
1022 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
1024 int aliasSource = (inputDesc->mInputSource == AUDIO_SOURCE_HOTWORD) ?
1025 AUDIO_SOURCE_VOICE_RECOGNITION : inputDesc->mInputSource;
1027 param.addInt(String8(AudioParameter::keyInputSource), aliasSource);
1028 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1030 mpClientInterface->setParameters(input, param.toString());
1032 inputDesc->mRefCount = 1;
1036 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
1038 ALOGV("stopInput() input %d", input);
1039 ssize_t index = mInputs.indexOfKey(input);
1041 ALOGW("stopInput() unknow input %d", input);
1044 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1046 if (inputDesc->mRefCount == 0) {
1047 ALOGW("stopInput() input %d already stopped", input);
1048 return INVALID_OPERATION;
1050 // automatically disable the remote submix output when input is stopped
1051 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1052 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1053 AudioSystem::DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1056 AudioParameter param = AudioParameter();
1057 param.addInt(String8(AudioParameter::keyRouting), 0);
1058 mpClientInterface->setParameters(input, param.toString());
1059 inputDesc->mRefCount = 0;
1064 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
1066 ALOGV("releaseInput() %d", input);
1067 ssize_t index = mInputs.indexOfKey(input);
1069 ALOGW("releaseInput() releasing unknown input %d", input);
1072 mpClientInterface->closeInput(input);
1073 delete mInputs.valueAt(index);
1074 mInputs.removeItem(input);
1075 ALOGV("releaseInput() exit");
1078 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
1082 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1083 if (indexMin < 0 || indexMin >= indexMax) {
1084 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1087 mStreams[stream].mIndexMin = indexMin;
1088 mStreams[stream].mIndexMax = indexMax;
1091 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
1093 audio_devices_t device)
1096 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1099 if (!audio_is_output_device(device)) {
1103 // Force max volume if stream cannot be muted
1104 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1106 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1107 stream, device, index);
1109 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1110 // clear all device specific values
1111 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1112 mStreams[stream].mIndexCur.clear();
1114 mStreams[stream].mIndexCur.add(device, index);
1116 // compute and apply stream volume on all outputs according to connected device
1117 status_t status = NO_ERROR;
1118 for (size_t i = 0; i < mOutputs.size(); i++) {
1119 audio_devices_t curDevice =
1120 getDeviceForVolume(mOutputs.valueAt(i)->device());
1121 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1122 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1123 if (volStatus != NO_ERROR) {
1131 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
1133 audio_devices_t device)
1135 if (index == NULL) {
1138 if (!audio_is_output_device(device)) {
1141 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1142 // the strategy the stream belongs to.
1143 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1144 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1146 device = getDeviceForVolume(device);
1148 *index = mStreams[stream].getVolumeIndex(device);
1149 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1153 audio_io_handle_t AudioPolicyManagerBase::selectOutputForEffects(
1154 const SortedVector<audio_io_handle_t>& outputs)
1156 // select one output among several suitable for global effects.
1157 // The priority is as follows:
1158 // 1: An offloaded output. If the effect ends up not being offloadable,
1159 // AudioFlinger will invalidate the track and the offloaded output
1160 // will be closed causing the effect to be moved to a PCM output.
1161 // 2: A deep buffer output
1162 // 3: the first output in the list
1164 if (outputs.size() == 0) {
1168 audio_io_handle_t outputOffloaded = 0;
1169 audio_io_handle_t outputDeepBuffer = 0;
1171 for (size_t i = 0; i < outputs.size(); i++) {
1172 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
1173 ALOGV("selectOutputForEffects outputs[%d] flags %x", i, desc->mFlags);
1174 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1175 outputOffloaded = outputs[i];
1177 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1178 outputDeepBuffer = outputs[i];
1182 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1183 outputOffloaded, outputDeepBuffer);
1184 if (outputOffloaded != 0) {
1185 return outputOffloaded;
1187 if (outputDeepBuffer != 0) {
1188 return outputDeepBuffer;
1194 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(const effect_descriptor_t *desc)
1196 // apply simple rule where global effects are attached to the same output as MUSIC streams
1198 routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
1199 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1200 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1202 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1203 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1204 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1209 status_t AudioPolicyManagerBase::registerEffect(const effect_descriptor_t *desc,
1210 audio_io_handle_t io,
1215 ssize_t index = mOutputs.indexOfKey(io);
1217 index = mInputs.indexOfKey(io);
1219 ALOGW("registerEffect() unknown io %d", io);
1220 return INVALID_OPERATION;
1224 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1225 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1226 desc->name, desc->memoryUsage);
1227 return INVALID_OPERATION;
1229 mTotalEffectsMemory += desc->memoryUsage;
1230 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1231 desc->name, io, strategy, session, id);
1232 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1234 EffectDescriptor *pDesc = new EffectDescriptor();
1235 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1237 pDesc->mStrategy = (routing_strategy)strategy;
1238 pDesc->mSession = session;
1239 pDesc->mEnabled = false;
1241 mEffects.add(id, pDesc);
1246 status_t AudioPolicyManagerBase::unregisterEffect(int id)
1248 ssize_t index = mEffects.indexOfKey(id);
1250 ALOGW("unregisterEffect() unknown effect ID %d", id);
1251 return INVALID_OPERATION;
1254 EffectDescriptor *pDesc = mEffects.valueAt(index);
1256 setEffectEnabled(pDesc, false);
1258 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1259 ALOGW("unregisterEffect() memory %d too big for total %d",
1260 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1261 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1263 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1264 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1265 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1267 mEffects.removeItem(id);
1273 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1275 ssize_t index = mEffects.indexOfKey(id);
1277 ALOGW("unregisterEffect() unknown effect ID %d", id);
1278 return INVALID_OPERATION;
1281 return setEffectEnabled(mEffects.valueAt(index), enabled);
1284 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1286 if (enabled == pDesc->mEnabled) {
1287 ALOGV("setEffectEnabled(%s) effect already %s",
1288 enabled?"true":"false", enabled?"enabled":"disabled");
1289 return INVALID_OPERATION;
1293 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1294 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1295 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1296 return INVALID_OPERATION;
1298 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1299 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1301 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1302 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1303 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1304 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1306 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1307 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1309 pDesc->mEnabled = enabled;
1313 bool AudioPolicyManagerBase::isNonOffloadableEffectEnabled()
1315 for (size_t i = 0; i < mEffects.size(); i++) {
1316 const EffectDescriptor * const pDesc = mEffects.valueAt(i);
1317 if (pDesc->mEnabled && (pDesc->mStrategy == STRATEGY_MEDIA) &&
1318 ((pDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
1319 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
1320 pDesc->mDesc.name, pDesc->mSession);
1327 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1329 nsecs_t sysTime = systemTime();
1330 for (size_t i = 0; i < mOutputs.size(); i++) {
1331 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1332 if (outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1339 bool AudioPolicyManagerBase::isStreamActiveRemotely(int stream, uint32_t inPastMs) const
1341 nsecs_t sysTime = systemTime();
1342 for (size_t i = 0; i < mOutputs.size(); i++) {
1343 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1344 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
1345 outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1352 bool AudioPolicyManagerBase::isSourceActive(audio_source_t source) const
1354 for (size_t i = 0; i < mInputs.size(); i++) {
1355 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1356 if ((inputDescriptor->mInputSource == (int)source ||
1357 (source == (audio_source_t)AUDIO_SOURCE_VOICE_RECOGNITION &&
1358 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1359 && (inputDescriptor->mRefCount > 0)) {
1367 status_t AudioPolicyManagerBase::dump(int fd)
1369 const size_t SIZE = 256;
1373 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1374 result.append(buffer);
1376 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1377 result.append(buffer);
1378 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1379 result.append(buffer);
1380 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1381 result.append(buffer);
1382 snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbCardAndDevice.string());
1383 result.append(buffer);
1384 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1385 result.append(buffer);
1386 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1387 result.append(buffer);
1388 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1389 result.append(buffer);
1390 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1391 result.append(buffer);
1392 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1393 result.append(buffer);
1394 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1395 result.append(buffer);
1396 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1397 result.append(buffer);
1398 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AudioSystem::FOR_SYSTEM]);
1399 result.append(buffer);
1400 write(fd, result.string(), result.size());
1403 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1404 write(fd, buffer, strlen(buffer));
1405 for (size_t i = 0; i < mHwModules.size(); i++) {
1406 snprintf(buffer, SIZE, "- HW Module %d:\n", i + 1);
1407 write(fd, buffer, strlen(buffer));
1408 mHwModules[i]->dump(fd);
1411 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1412 write(fd, buffer, strlen(buffer));
1413 for (size_t i = 0; i < mOutputs.size(); i++) {
1414 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1415 write(fd, buffer, strlen(buffer));
1416 mOutputs.valueAt(i)->dump(fd);
1419 snprintf(buffer, SIZE, "\nInputs dump:\n");
1420 write(fd, buffer, strlen(buffer));
1421 for (size_t i = 0; i < mInputs.size(); i++) {
1422 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1423 write(fd, buffer, strlen(buffer));
1424 mInputs.valueAt(i)->dump(fd);
1427 snprintf(buffer, SIZE, "\nStreams dump:\n");
1428 write(fd, buffer, strlen(buffer));
1429 snprintf(buffer, SIZE,
1430 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1431 write(fd, buffer, strlen(buffer));
1432 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1433 snprintf(buffer, SIZE, " %02d ", i);
1434 write(fd, buffer, strlen(buffer));
1435 mStreams[i].dump(fd);
1438 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1439 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1440 write(fd, buffer, strlen(buffer));
1442 snprintf(buffer, SIZE, "Registered effects:\n");
1443 write(fd, buffer, strlen(buffer));
1444 for (size_t i = 0; i < mEffects.size(); i++) {
1445 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1446 write(fd, buffer, strlen(buffer));
1447 mEffects.valueAt(i)->dump(fd);
1454 // This function checks for the parameters which can be offloaded.
1455 // This can be enhanced depending on the capability of the DSP and policy
1457 bool AudioPolicyManagerBase::isOffloadSupported(const audio_offload_info_t& offloadInfo)
1459 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
1460 " BitRate=%u, duration=%lld us, has_video=%d",
1461 offloadInfo.sample_rate, offloadInfo.channel_mask,
1463 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1464 offloadInfo.has_video);
1466 // Check if offload has been disabled
1467 char propValue[PROPERTY_VALUE_MAX];
1468 if (property_get("audio.offload.disable", propValue, "0")) {
1469 if (atoi(propValue) != 0) {
1470 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1475 // Check if stream type is music, then only allow offload as of now.
1476 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1478 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1482 //TODO: enable audio offloading with video when ready
1483 if (offloadInfo.has_video)
1485 ALOGV("isOffloadSupported: has_video == true, returning false");
1489 //If duration is less than minimum value defined in property, return false
1490 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1491 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1492 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1495 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1496 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1500 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1501 // creating an offloaded track and tearing it down immediately after start when audioflinger
1502 // detects there is an active non offloadable effect.
1503 // FIXME: We should check the audio session here but we do not have it in this context.
1504 // This may prevent offloading in rare situations where effects are left active by apps
1505 // in the background.
1506 if (isNonOffloadableEffectEnabled()) {
1510 // See if there is a profile to support this.
1511 // AUDIO_DEVICE_NONE
1512 IOProfile *profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
1513 offloadInfo.sample_rate,
1515 offloadInfo.channel_mask,
1516 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1517 ALOGV("isOffloadSupported() profile %sfound", profile != NULL ? "" : "NOT ");
1518 return (profile != NULL);
1521 // ----------------------------------------------------------------------------
1522 // AudioPolicyManagerBase
1523 // ----------------------------------------------------------------------------
1525 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1527 #ifdef AUDIO_POLICY_TEST
1529 #endif //AUDIO_POLICY_TEST
1530 mPrimaryOutput((audio_io_handle_t)0),
1531 mAvailableOutputDevices(AUDIO_DEVICE_NONE),
1532 mPhoneState(AudioSystem::MODE_NORMAL),
1533 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1534 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1535 mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false), mHasRemoteSubmix(false),
1536 mSpeakerDrcEnabled(false)
1538 mpClientInterface = clientInterface;
1540 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1541 mForceUse[i] = AudioSystem::FORCE_NONE;
1544 mA2dpDeviceAddress = String8("");
1545 mScoDeviceAddress = String8("");
1546 mUsbCardAndDevice = String8("");
1548 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1549 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1550 ALOGE("could not load audio policy configuration file, setting defaults");
1551 defaultAudioPolicyConfig();
1555 // must be done after reading the policy
1556 initializeVolumeCurves();
1558 // open all output streams needed to access attached devices
1559 for (size_t i = 0; i < mHwModules.size(); i++) {
1560 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1561 if (mHwModules[i]->mHandle == 0) {
1562 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1565 // open all output streams needed to access attached devices
1566 // except for direct output streams that are only opened when they are actually
1567 // required by an app.
1568 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1570 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1572 if ((outProfile->mSupportedDevices & mAttachedOutputDevices) &&
1573 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
1574 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1575 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1576 outProfile->mSupportedDevices);
1577 audio_io_handle_t output = mpClientInterface->openOutput(
1578 outProfile->mModule->mHandle,
1579 &outputDesc->mDevice,
1580 &outputDesc->mSamplingRate,
1581 &outputDesc->mFormat,
1582 &outputDesc->mChannelMask,
1583 &outputDesc->mLatency,
1584 outputDesc->mFlags);
1588 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1589 (outProfile->mSupportedDevices & mAttachedOutputDevices));
1590 if (mPrimaryOutput == 0 &&
1591 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1592 mPrimaryOutput = output;
1594 addOutput(output, outputDesc);
1595 setOutputDevice(output,
1596 (audio_devices_t)(mDefaultOutputDevice &
1597 outProfile->mSupportedDevices),
1604 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1605 "Not output found for attached devices %08x",
1606 (mAttachedOutputDevices & ~mAvailableOutputDevices));
1608 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1610 updateDevicesAndOutputs();
1612 #ifdef AUDIO_POLICY_TEST
1613 if (mPrimaryOutput != 0) {
1614 AudioParameter outputCmd = AudioParameter();
1615 outputCmd.addInt(String8("set_id"), 0);
1616 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1618 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
1619 mTestSamplingRate = 44100;
1620 mTestFormat = AudioSystem::PCM_16_BIT;
1621 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1624 mDirectOutput = false;
1625 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1626 mTestOutputs[i] = 0;
1629 const size_t SIZE = 256;
1631 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1632 run(buffer, ANDROID_PRIORITY_AUDIO);
1634 #endif //AUDIO_POLICY_TEST
1637 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1639 #ifdef AUDIO_POLICY_TEST
1641 #endif //AUDIO_POLICY_TEST
1642 for (size_t i = 0; i < mOutputs.size(); i++) {
1643 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1644 delete mOutputs.valueAt(i);
1646 for (size_t i = 0; i < mInputs.size(); i++) {
1647 mpClientInterface->closeInput(mInputs.keyAt(i));
1648 delete mInputs.valueAt(i);
1650 for (size_t i = 0; i < mHwModules.size(); i++) {
1651 delete mHwModules[i];
1655 status_t AudioPolicyManagerBase::initCheck()
1657 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1660 #ifdef AUDIO_POLICY_TEST
1661 bool AudioPolicyManagerBase::threadLoop()
1663 ALOGV("entering threadLoop()");
1664 while (!exitPending())
1670 Mutex::Autolock _l(mLock);
1671 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1673 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1674 AudioParameter param = AudioParameter(command);
1676 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1678 ALOGV("Test command %s received", command.string());
1680 if (param.get(String8("target"), target) != NO_ERROR) {
1683 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1684 param.remove(String8("test_cmd_policy_output"));
1685 mCurOutput = valueInt;
1687 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1688 param.remove(String8("test_cmd_policy_direct"));
1689 if (value == "false") {
1690 mDirectOutput = false;
1691 } else if (value == "true") {
1692 mDirectOutput = true;
1695 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1696 param.remove(String8("test_cmd_policy_input"));
1697 mTestInput = valueInt;
1700 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1701 param.remove(String8("test_cmd_policy_format"));
1702 int format = AudioSystem::INVALID_FORMAT;
1703 if (value == "PCM 16 bits") {
1704 format = AudioSystem::PCM_16_BIT;
1705 } else if (value == "PCM 8 bits") {
1706 format = AudioSystem::PCM_8_BIT;
1707 } else if (value == "Compressed MP3") {
1708 format = AudioSystem::MP3;
1710 if (format != AudioSystem::INVALID_FORMAT) {
1711 if (target == "Manager") {
1712 mTestFormat = format;
1713 } else if (mTestOutputs[mCurOutput] != 0) {
1714 AudioParameter outputParam = AudioParameter();
1715 outputParam.addInt(String8("format"), format);
1716 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1720 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1721 param.remove(String8("test_cmd_policy_channels"));
1724 if (value == "Channels Stereo") {
1725 channels = AudioSystem::CHANNEL_OUT_STEREO;
1726 } else if (value == "Channels Mono") {
1727 channels = AudioSystem::CHANNEL_OUT_MONO;
1729 if (channels != 0) {
1730 if (target == "Manager") {
1731 mTestChannels = channels;
1732 } else if (mTestOutputs[mCurOutput] != 0) {
1733 AudioParameter outputParam = AudioParameter();
1734 outputParam.addInt(String8("channels"), channels);
1735 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1739 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1740 param.remove(String8("test_cmd_policy_sampleRate"));
1741 if (valueInt >= 0 && valueInt <= 96000) {
1742 int samplingRate = valueInt;
1743 if (target == "Manager") {
1744 mTestSamplingRate = samplingRate;
1745 } else if (mTestOutputs[mCurOutput] != 0) {
1746 AudioParameter outputParam = AudioParameter();
1747 outputParam.addInt(String8("sampling_rate"), samplingRate);
1748 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1753 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1754 param.remove(String8("test_cmd_policy_reopen"));
1756 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1757 mpClientInterface->closeOutput(mPrimaryOutput);
1759 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1761 delete mOutputs.valueFor(mPrimaryOutput);
1762 mOutputs.removeItem(mPrimaryOutput);
1764 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1765 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
1766 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1767 &outputDesc->mDevice,
1768 &outputDesc->mSamplingRate,
1769 &outputDesc->mFormat,
1770 &outputDesc->mChannelMask,
1771 &outputDesc->mLatency,
1772 outputDesc->mFlags);
1773 if (mPrimaryOutput == 0) {
1774 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1775 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1777 AudioParameter outputCmd = AudioParameter();
1778 outputCmd.addInt(String8("set_id"), 0);
1779 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1780 addOutput(mPrimaryOutput, outputDesc);
1785 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1791 void AudioPolicyManagerBase::exit()
1794 AutoMutex _l(mLock);
1796 mWaitWorkCV.signal();
1798 requestExitAndWait();
1801 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1803 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1804 if (output == mTestOutputs[i]) return i;
1808 #endif //AUDIO_POLICY_TEST
1812 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1814 outputDesc->mId = id;
1815 mOutputs.add(id, outputDesc);
1819 status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
1820 AudioSystem::device_connection_state state,
1821 SortedVector<audio_io_handle_t>& outputs)
1823 AudioOutputDescriptor *desc;
1825 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1826 // first list already open outputs that can be routed to this device
1827 for (size_t i = 0; i < mOutputs.size(); i++) {
1828 desc = mOutputs.valueAt(i);
1829 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
1830 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
1831 outputs.add(mOutputs.keyAt(i));
1834 // then look for output profiles that can be routed to this device
1835 SortedVector<IOProfile *> profiles;
1836 for (size_t i = 0; i < mHwModules.size(); i++)
1838 if (mHwModules[i]->mHandle == 0) {
1841 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1843 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1844 ALOGV("checkOutputsForDevice(): adding profile %d from module %d", j, i);
1845 profiles.add(mHwModules[i]->mOutputProfiles[j]);
1850 if (profiles.isEmpty() && outputs.isEmpty()) {
1851 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1855 // open outputs for matching profiles if needed. Direct outputs are also opened to
1856 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
1857 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
1858 IOProfile *profile = profiles[profile_index];
1860 // nothing to do if one output is already opened for this profile
1862 for (j = 0; j < mOutputs.size(); j++) {
1863 desc = mOutputs.valueAt(j);
1864 if (!desc->isDuplicated() && desc->mProfile == profile) {
1868 if (j != mOutputs.size()) {
1872 ALOGV("opening output for device %08x", device);
1873 desc = new AudioOutputDescriptor(profile);
1874 desc->mDevice = device;
1875 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
1876 offloadInfo.sample_rate = desc->mSamplingRate;
1877 offloadInfo.format = desc->mFormat;
1878 offloadInfo.channel_mask = desc->mChannelMask;
1880 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
1882 &desc->mSamplingRate,
1884 &desc->mChannelMask,
1889 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1892 if (profile->mSamplingRates[0] == 0) {
1893 reply = mpClientInterface->getParameters(output,
1894 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
1895 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
1897 value = strpbrk((char *)reply.string(), "=");
1898 if (value != NULL) {
1899 loadSamplingRates(value + 1, profile);
1902 if (profile->mFormats[0] == 0) {
1903 reply = mpClientInterface->getParameters(output,
1904 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
1905 ALOGV("checkOutputsForDevice() direct output sup formats %s",
1907 value = strpbrk((char *)reply.string(), "=");
1908 if (value != NULL) {
1909 loadFormats(value + 1, profile);
1912 if (profile->mChannelMasks[0] == 0) {
1913 reply = mpClientInterface->getParameters(output,
1914 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
1915 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
1917 value = strpbrk((char *)reply.string(), "=");
1918 if (value != NULL) {
1919 loadOutChannels(value + 1, profile);
1922 if (((profile->mSamplingRates[0] == 0) &&
1923 (profile->mSamplingRates.size() < 2)) ||
1924 ((profile->mFormats[0] == 0) &&
1925 (profile->mFormats.size() < 2)) ||
1926 ((profile->mFormats[0] == 0) &&
1927 (profile->mChannelMasks.size() < 2))) {
1928 ALOGW("checkOutputsForDevice() direct output missing param");
1929 mpClientInterface->closeOutput(output);
1932 addOutput(output, desc);
1935 audio_io_handle_t duplicatedOutput = 0;
1936 // add output descriptor
1937 addOutput(output, desc);
1938 // set initial stream volume for device
1939 applyStreamVolumes(output, device, 0, true);
1941 //TODO: configure audio effect output stage here
1943 // open a duplicating output thread for the new output and the primary output
1944 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
1946 if (duplicatedOutput != 0) {
1947 // add duplicated output descriptor
1948 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1949 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1950 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1951 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
1952 dupOutputDesc->mFormat = desc->mFormat;
1953 dupOutputDesc->mChannelMask = desc->mChannelMask;
1954 dupOutputDesc->mLatency = desc->mLatency;
1955 addOutput(duplicatedOutput, dupOutputDesc);
1956 applyStreamVolumes(duplicatedOutput, device, 0, true);
1958 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
1959 mPrimaryOutput, output);
1960 mpClientInterface->closeOutput(output);
1961 mOutputs.removeItem(output);
1967 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
1969 profiles.removeAt(profile_index);
1972 outputs.add(output);
1973 ALOGV("checkOutputsForDevice(): adding output %d", output);
1977 if (profiles.isEmpty()) {
1978 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1982 // check if one opened output is not needed any more after disconnecting one device
1983 for (size_t i = 0; i < mOutputs.size(); i++) {
1984 desc = mOutputs.valueAt(i);
1985 if (!desc->isDuplicated() &&
1986 !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
1987 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
1988 outputs.add(mOutputs.keyAt(i));
1991 for (size_t i = 0; i < mHwModules.size(); i++)
1993 if (mHwModules[i]->mHandle == 0) {
1996 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1998 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
1999 if ((profile->mSupportedDevices & device) &&
2000 (profile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
2001 ALOGV("checkOutputsForDevice(): clearing direct output profile %d on module %d",
2003 if (profile->mSamplingRates[0] == 0) {
2004 profile->mSamplingRates.clear();
2005 profile->mSamplingRates.add(0);
2007 if (profile->mFormats[0] == 0) {
2008 profile->mFormats.clear();
2009 profile->mFormats.add((audio_format_t)0);
2011 if (profile->mChannelMasks[0] == 0) {
2012 profile->mChannelMasks.clear();
2013 profile->mChannelMasks.add((audio_channel_mask_t)0);
2022 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
2024 ALOGV("closeOutput(%d)", output);
2026 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2027 if (outputDesc == NULL) {
2028 ALOGW("closeOutput() unknown output %d", output);
2032 // look for duplicated outputs connected to the output being removed.
2033 for (size_t i = 0; i < mOutputs.size(); i++) {
2034 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
2035 if (dupOutputDesc->isDuplicated() &&
2036 (dupOutputDesc->mOutput1 == outputDesc ||
2037 dupOutputDesc->mOutput2 == outputDesc)) {
2038 AudioOutputDescriptor *outputDesc2;
2039 if (dupOutputDesc->mOutput1 == outputDesc) {
2040 outputDesc2 = dupOutputDesc->mOutput2;
2042 outputDesc2 = dupOutputDesc->mOutput1;
2044 // As all active tracks on duplicated output will be deleted,
2045 // and as they were also referenced on the other output, the reference
2046 // count for their stream type must be adjusted accordingly on
2047 // the other output.
2048 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
2049 int refCount = dupOutputDesc->mRefCount[j];
2050 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
2052 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
2053 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
2055 mpClientInterface->closeOutput(duplicatedOutput);
2056 delete mOutputs.valueFor(duplicatedOutput);
2057 mOutputs.removeItem(duplicatedOutput);
2061 AudioParameter param;
2062 param.add(String8("closing"), String8("true"));
2063 mpClientInterface->setParameters(output, param.toString());
2065 mpClientInterface->closeOutput(output);
2067 mOutputs.removeItem(output);
2068 mPreviousOutputs = mOutputs;
2071 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device,
2072 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
2074 SortedVector<audio_io_handle_t> outputs;
2076 ALOGVV("getOutputsForDevice() device %04x", device);
2077 for (size_t i = 0; i < openOutputs.size(); i++) {
2078 ALOGVV("output %d isDuplicated=%d device=%04x",
2079 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
2080 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
2081 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
2082 outputs.add(openOutputs.keyAt(i));
2088 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
2089 SortedVector<audio_io_handle_t>& outputs2)
2091 if (outputs1.size() != outputs2.size()) {
2094 for (size_t i = 0; i < outputs1.size(); i++) {
2095 if (outputs1[i] != outputs2[i]) {
2102 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
2104 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
2105 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
2106 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
2107 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
2109 if (!vectorsEqual(srcOutputs,dstOutputs)) {
2110 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
2111 strategy, srcOutputs[0], dstOutputs[0]);
2112 // mute strategy while moving tracks from one output to another
2113 for (size_t i = 0; i < srcOutputs.size(); i++) {
2114 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
2115 if (desc->isStrategyActive(strategy)) {
2116 setStrategyMute(strategy, true, srcOutputs[i]);
2117 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
2121 // Move effects associated to this strategy from previous output to new output
2122 if (strategy == STRATEGY_MEDIA) {
2123 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
2124 SortedVector<audio_io_handle_t> moved;
2125 for (size_t i = 0; i < mEffects.size(); i++) {
2126 EffectDescriptor *desc = mEffects.valueAt(i);
2127 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
2128 desc->mIo != fxOutput) {
2129 if (moved.indexOf(desc->mIo) < 0) {
2130 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
2131 mEffects.keyAt(i), fxOutput);
2132 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
2134 moved.add(desc->mIo);
2136 desc->mIo = fxOutput;
2140 // Move tracks associated to this strategy from previous output to new output
2141 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2142 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2143 //FIXME see fixme on name change
2144 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i,
2145 dstOutputs[0] /* ignored */);
2151 void AudioPolicyManagerBase::checkOutputForAllStrategies()
2153 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
2154 checkOutputForStrategy(STRATEGY_PHONE);
2155 checkOutputForStrategy(STRATEGY_SONIFICATION);
2156 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2157 checkOutputForStrategy(STRATEGY_MEDIA);
2158 checkOutputForStrategy(STRATEGY_DTMF);
2161 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
2167 for (size_t i = 0; i < mOutputs.size(); i++) {
2168 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
2169 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
2170 return mOutputs.keyAt(i);
2177 void AudioPolicyManagerBase::checkA2dpSuspend()
2182 audio_io_handle_t a2dpOutput = getA2dpOutput();
2183 if (a2dpOutput == 0) {
2187 // suspend A2DP output if:
2188 // (NOT already suspended) &&
2189 // ((SCO device is connected &&
2190 // (forced usage for communication || for record is SCO))) ||
2191 // (phone state is ringing || in call)
2193 // restore A2DP output if:
2194 // (Already suspended) &&
2195 // ((SCO device is NOT connected ||
2196 // (forced usage NOT for communication && NOT for record is SCO))) &&
2197 // (phone state is NOT ringing && NOT in call)
2199 if (mA2dpSuspended) {
2200 if (((mScoDeviceAddress == "") ||
2201 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
2202 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
2203 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
2204 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
2206 mpClientInterface->restoreOutput(a2dpOutput);
2207 mA2dpSuspended = false;
2210 if (((mScoDeviceAddress != "") &&
2211 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2212 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
2213 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
2214 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
2216 mpClientInterface->suspendOutput(a2dpOutput);
2217 mA2dpSuspended = true;
2222 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
2224 audio_devices_t device = AUDIO_DEVICE_NONE;
2226 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2227 // check the following by order of priority to request a routing change if necessary:
2228 // 1: the strategy enforced audible is active on the output:
2229 // use device for strategy enforced audible
2230 // 2: we are in call or the strategy phone is active on the output:
2231 // use device for strategy phone
2232 // 3: the strategy sonification is active on the output:
2233 // use device for strategy sonification
2234 // 4: the strategy "respectful" sonification is active on the output:
2235 // use device for strategy "respectful" sonification
2236 // 5: the strategy media is active on the output:
2237 // use device for strategy media
2238 // 6: the strategy DTMF is active on the output:
2239 // use device for strategy DTMF
2240 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
2241 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
2242 } else if (isInCall() ||
2243 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
2244 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
2245 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
2246 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
2247 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
2248 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
2249 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
2250 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
2251 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
2252 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
2255 ALOGV("getNewDevice() selected device %x", device);
2259 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
2260 return (uint32_t)getStrategy(stream);
2263 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
2264 audio_devices_t devices;
2265 // By checking the range of stream before calling getStrategy, we avoid
2266 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
2267 // and then return STRATEGY_MEDIA, but we want to return the empty set.
2268 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
2269 devices = AUDIO_DEVICE_NONE;
2271 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
2272 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
2277 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
2278 AudioSystem::stream_type stream) {
2279 // stream to strategy mapping
2281 case AudioSystem::VOICE_CALL:
2282 case AudioSystem::BLUETOOTH_SCO:
2283 return STRATEGY_PHONE;
2284 case AudioSystem::RING:
2285 case AudioSystem::ALARM:
2286 return STRATEGY_SONIFICATION;
2287 case AudioSystem::NOTIFICATION:
2288 return STRATEGY_SONIFICATION_RESPECTFUL;
2289 case AudioSystem::DTMF:
2290 return STRATEGY_DTMF;
2292 ALOGE("unknown stream type");
2293 case AudioSystem::SYSTEM:
2294 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
2295 // while key clicks are played produces a poor result
2296 case AudioSystem::TTS:
2297 case AudioSystem::MUSIC:
2298 return STRATEGY_MEDIA;
2299 case AudioSystem::ENFORCED_AUDIBLE:
2300 return STRATEGY_ENFORCED_AUDIBLE;
2304 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2306 case AudioSystem::MUSIC:
2307 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2308 updateDevicesAndOutputs();
2315 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2318 uint32_t device = AUDIO_DEVICE_NONE;
2321 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2322 strategy, mDeviceForStrategy[strategy]);
2323 return mDeviceForStrategy[strategy];
2328 case STRATEGY_SONIFICATION_RESPECTFUL:
2330 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2331 } else if (isStreamActiveRemotely(AudioSystem::MUSIC,
2332 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2333 // while media is playing on a remote device, use the the sonification behavior.
2334 // Note that we test this usecase before testing if media is playing because
2335 // the isStreamActive() method only informs about the activity of a stream, not
2336 // if it's for local playback. Note also that we use the same delay between both tests
2337 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2338 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2339 // while media is playing (or has recently played), use the same device
2340 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2342 // when media is not playing anymore, fall back on the sonification behavior
2343 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2350 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2351 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2354 // when in call, DTMF and PHONE strategies follow the same rules
2357 case STRATEGY_PHONE:
2358 // for phone strategy, we first consider the forced use and then the available devices by order
2360 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2361 case AudioSystem::FORCE_BT_SCO:
2362 if (!isInCall() || strategy != STRATEGY_DTMF) {
2363 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2366 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2368 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
2370 // if SCO device is requested but no SCO device is available, fall back to default case
2373 default: // FORCE_NONE
2374 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2375 if (mHasA2dp && !isInCall() &&
2376 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2377 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2378 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2380 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2383 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2385 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2387 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2388 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2390 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2392 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2394 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2396 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2399 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
2401 device = mDefaultOutputDevice;
2402 if (device == AUDIO_DEVICE_NONE) {
2403 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2407 case AudioSystem::FORCE_SPEAKER:
2408 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2409 // A2DP speaker when forcing to speaker output
2410 if (mHasA2dp && !isInCall() &&
2411 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2412 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2413 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2416 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2417 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2419 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2421 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2423 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2425 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2428 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2430 device = mDefaultOutputDevice;
2431 if (device == AUDIO_DEVICE_NONE) {
2432 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2438 case STRATEGY_SONIFICATION:
2440 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2441 // handleIncallSonification().
2443 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2448 case STRATEGY_ENFORCED_AUDIBLE:
2449 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2451 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2452 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2454 if ((strategy == STRATEGY_SONIFICATION) ||
2455 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_SYSTEM_ENFORCED)) {
2456 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2457 if (device == AUDIO_DEVICE_NONE) {
2458 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2461 // The second device used for sonification is the same as the device used by media strategy
2464 case STRATEGY_MEDIA: {
2465 uint32_t device2 = AUDIO_DEVICE_NONE;
2466 if (strategy != STRATEGY_SONIFICATION) {
2467 // no sonification on remote submix (e.g. WFD)
2468 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2470 if ((device2 == AUDIO_DEVICE_NONE) &&
2471 mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2472 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2473 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2474 if (device2 == AUDIO_DEVICE_NONE) {
2475 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2477 if (device2 == AUDIO_DEVICE_NONE) {
2478 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2481 if (device2 == AUDIO_DEVICE_NONE) {
2482 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2484 if (device2 == AUDIO_DEVICE_NONE) {
2485 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2487 if (device2 == AUDIO_DEVICE_NONE) {
2488 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2490 if (device2 == AUDIO_DEVICE_NONE) {
2491 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2493 if (device2 == AUDIO_DEVICE_NONE) {
2494 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2496 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
2497 // no sonification on aux digital (e.g. HDMI)
2498 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2500 if ((device2 == AUDIO_DEVICE_NONE) &&
2501 (mForceUse[AudioSystem::FOR_DOCK] == AudioSystem::FORCE_ANALOG_DOCK)) {
2502 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2504 if (device2 == AUDIO_DEVICE_NONE) {
2505 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2508 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2509 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
2512 device = mDefaultOutputDevice;
2513 if (device == AUDIO_DEVICE_NONE) {
2514 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2519 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2523 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2527 void AudioPolicyManagerBase::updateDevicesAndOutputs()
2529 for (int i = 0; i < NUM_STRATEGIES; i++) {
2530 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2532 mPreviousOutputs = mOutputs;
2535 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2536 audio_devices_t prevDevice,
2539 // mute/unmute strategies using an incompatible device combination
2540 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2541 // if unmuting, unmute only after the specified delay
2542 if (outputDesc->isDuplicated()) {
2546 uint32_t muteWaitMs = 0;
2547 audio_devices_t device = outputDesc->device();
2548 bool shouldMute = outputDesc->isActive() && (AudioSystem::popCount(device) >= 2);
2549 // temporary mute output if device selection changes to avoid volume bursts due to
2550 // different per device volumes
2551 bool tempMute = outputDesc->isActive() && (device != prevDevice);
2553 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2554 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2555 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2556 bool doMute = false;
2558 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2560 outputDesc->mStrategyMutedByDevice[i] = true;
2561 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2563 outputDesc->mStrategyMutedByDevice[i] = false;
2565 if (doMute || tempMute) {
2566 for (size_t j = 0; j < mOutputs.size(); j++) {
2567 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2568 // skip output if it does not share any device with current output
2569 if ((desc->supportedDevices() & outputDesc->supportedDevices())
2570 == AUDIO_DEVICE_NONE) {
2573 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2574 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2575 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2576 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2577 if (desc->isStrategyActive((routing_strategy)i)) {
2578 // do tempMute only for current output
2579 if (tempMute && (desc == outputDesc)) {
2580 setStrategyMute((routing_strategy)i, true, curOutput);
2581 setStrategyMute((routing_strategy)i, false, curOutput,
2582 desc->latency() * 2, device);
2584 if ((tempMute && (desc == outputDesc)) || mute) {
2585 if (muteWaitMs < desc->latency()) {
2586 muteWaitMs = desc->latency();
2594 // FIXME: should not need to double latency if volume could be applied immediately by the
2595 // audioflinger mixer. We must account for the delay between now and the next time
2596 // the audioflinger thread for this output will process a buffer (which corresponds to
2597 // one buffer size, usually 1/2 or 1/4 of the latency).
2599 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2600 if (muteWaitMs > delayMs) {
2601 muteWaitMs -= delayMs;
2602 usleep(muteWaitMs * 1000);
2608 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2609 audio_devices_t device,
2613 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2614 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2615 AudioParameter param;
2616 uint32_t muteWaitMs;
2618 if (outputDesc->isDuplicated()) {
2619 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2620 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2623 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
2625 if ((device != AUDIO_DEVICE_NONE) &&
2626 ((device & outputDesc->mProfile->mSupportedDevices) == 0)) {
2630 // filter devices according to output selected
2631 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2633 audio_devices_t prevDevice = outputDesc->mDevice;
2635 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2637 if (device != AUDIO_DEVICE_NONE) {
2638 outputDesc->mDevice = device;
2640 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2642 // Do not change the routing if:
2643 // - the requested device is AUDIO_DEVICE_NONE
2644 // - the requested device is the same as current device and force is not specified.
2645 // Doing this check here allows the caller to call setOutputDevice() without conditions
2646 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
2647 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2651 ALOGV("setOutputDevice() changing device");
2653 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2654 mpClientInterface->setParameters(output, param.toString(), delayMs);
2656 // update stream volumes according to new device
2657 applyStreamVolumes(output, device, delayMs);
2662 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2663 uint32_t samplingRate,
2665 uint32_t channelMask)
2667 // Choose an input profile based on the requested capture parameters: select the first available
2668 // profile supporting all requested parameters.
2670 for (size_t i = 0; i < mHwModules.size(); i++)
2672 if (mHwModules[i]->mHandle == 0) {
2675 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2677 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2678 if (profile->isCompatibleProfile(device, samplingRate, format,
2679 channelMask,(audio_output_flags_t)0)) {
2687 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2689 uint32_t device = AUDIO_DEVICE_NONE;
2691 switch (inputSource) {
2692 case AUDIO_SOURCE_VOICE_UPLINK:
2693 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2694 device = AUDIO_DEVICE_IN_VOICE_CALL;
2699 case AUDIO_SOURCE_DEFAULT:
2700 case AUDIO_SOURCE_MIC:
2701 case AUDIO_SOURCE_VOICE_RECOGNITION:
2702 case AUDIO_SOURCE_HOTWORD:
2703 case AUDIO_SOURCE_VOICE_COMMUNICATION:
2704 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2705 mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2706 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2707 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) {
2708 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
2709 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2710 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2713 case AUDIO_SOURCE_CAMCORDER:
2714 if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) {
2715 device = AUDIO_DEVICE_IN_BACK_MIC;
2716 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2717 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2720 case AUDIO_SOURCE_VOICE_DOWNLINK:
2721 case AUDIO_SOURCE_VOICE_CALL:
2722 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2723 device = AUDIO_DEVICE_IN_VOICE_CALL;
2726 case AUDIO_SOURCE_REMOTE_SUBMIX:
2727 if (mAvailableInputDevices & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
2728 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2732 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2735 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2739 bool AudioPolicyManagerBase::isVirtualInputDevice(audio_devices_t device)
2741 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
2742 device &= ~AUDIO_DEVICE_BIT_IN;
2743 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
2749 audio_io_handle_t AudioPolicyManagerBase::getActiveInput(bool ignoreVirtualInputs)
2751 for (size_t i = 0; i < mInputs.size(); i++) {
2752 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
2753 if ((input_descriptor->mRefCount > 0)
2754 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
2755 return mInputs.keyAt(i);
2762 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2764 if (device == AUDIO_DEVICE_NONE) {
2765 // this happens when forcing a route update and no track is active on an output.
2766 // In this case the returned category is not important.
2767 device = AUDIO_DEVICE_OUT_SPEAKER;
2768 } else if (AudioSystem::popCount(device) > 1) {
2769 // Multiple device selection is either:
2770 // - speaker + one other device: give priority to speaker in this case.
2771 // - one A2DP device + another device: happens with duplicated output. In this case
2772 // retain the device on the A2DP output as the other must not correspond to an active
2773 // selection if not the speaker.
2774 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2775 device = AUDIO_DEVICE_OUT_SPEAKER;
2777 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2781 ALOGW_IF(AudioSystem::popCount(device) != 1,
2782 "getDeviceForVolume() invalid device combination: %08x",
2788 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
2790 switch(getDeviceForVolume(device)) {
2791 case AUDIO_DEVICE_OUT_EARPIECE:
2792 return DEVICE_CATEGORY_EARPIECE;
2793 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
2794 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
2795 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
2796 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
2797 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
2798 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
2799 return DEVICE_CATEGORY_HEADSET;
2800 case AUDIO_DEVICE_OUT_SPEAKER:
2801 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
2802 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
2803 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
2804 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
2805 case AUDIO_DEVICE_OUT_USB_DEVICE:
2806 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
2808 return DEVICE_CATEGORY_SPEAKER;
2812 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
2815 device_category deviceCategory = getDeviceCategory(device);
2816 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
2818 // the volume index in the UI is relative to the min and max volume indices for this stream type
2819 int nbSteps = 1 + curve[VOLMAX].mIndex -
2820 curve[VOLMIN].mIndex;
2821 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
2822 (streamDesc.mIndexMax - streamDesc.mIndexMin);
2824 // find what part of the curve this index volume belongs to, or if it's out of bounds
2826 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
2828 } else if (volIdx < curve[VOLKNEE1].mIndex) {
2830 } else if (volIdx < curve[VOLKNEE2].mIndex) {
2832 } else if (volIdx <= curve[VOLMAX].mIndex) {
2834 } else { // out of bounds
2838 // linear interpolation in the attenuation table in dB
2839 float decibels = curve[segment].mDBAttenuation +
2840 ((float)(volIdx - curve[segment].mIndex)) *
2841 ( (curve[segment+1].mDBAttenuation -
2842 curve[segment].mDBAttenuation) /
2843 ((float)(curve[segment+1].mIndex -
2844 curve[segment].mIndex)) );
2846 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
2848 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
2849 curve[segment].mIndex, volIdx,
2850 curve[segment+1].mIndex,
2851 curve[segment].mDBAttenuation,
2853 curve[segment+1].mDBAttenuation,
2856 return amplification;
2859 const AudioPolicyManagerBase::VolumeCurvePoint
2860 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2861 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
2864 const AudioPolicyManagerBase::VolumeCurvePoint
2865 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2866 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
2869 const AudioPolicyManagerBase::VolumeCurvePoint
2870 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2871 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2874 const AudioPolicyManagerBase::VolumeCurvePoint
2875 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2876 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2879 const AudioPolicyManagerBase::VolumeCurvePoint
2880 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = {
2881 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
2884 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
2885 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
2886 // AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
2887 // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
2889 const AudioPolicyManagerBase::VolumeCurvePoint
2890 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2891 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
2894 const AudioPolicyManagerBase::VolumeCurvePoint
2895 AudioPolicyManagerBase::sDefaultSystemVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = {
2896 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
2899 const AudioPolicyManagerBase::VolumeCurvePoint
2900 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2901 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
2904 const AudioPolicyManagerBase::VolumeCurvePoint
2905 AudioPolicyManagerBase::sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2906 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
2909 const AudioPolicyManagerBase::VolumeCurvePoint
2910 AudioPolicyManagerBase::sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2911 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
2914 const AudioPolicyManagerBase::VolumeCurvePoint
2915 *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT]
2916 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2917 { // AUDIO_STREAM_VOICE_CALL
2918 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
2919 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2920 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
2922 { // AUDIO_STREAM_SYSTEM
2923 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2924 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2925 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2927 { // AUDIO_STREAM_RING
2928 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2929 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2930 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2932 { // AUDIO_STREAM_MUSIC
2933 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2934 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2935 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2937 { // AUDIO_STREAM_ALARM
2938 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2939 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2940 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2942 { // AUDIO_STREAM_NOTIFICATION
2943 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2944 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2945 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2947 { // AUDIO_STREAM_BLUETOOTH_SCO
2948 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
2949 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2950 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
2952 { // AUDIO_STREAM_ENFORCED_AUDIBLE
2953 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2954 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2955 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2957 { // AUDIO_STREAM_DTMF
2958 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2959 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2960 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2962 { // AUDIO_STREAM_TTS
2963 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2964 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2965 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2969 void AudioPolicyManagerBase::initializeVolumeCurves()
2971 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2972 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2973 mStreams[i].mVolumeCurve[j] =
2974 sVolumeProfiles[i][j];
2978 // Check availability of DRC on speaker path: if available, override some of the speaker curves
2979 if (mSpeakerDrcEnabled) {
2980 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
2981 sDefaultSystemVolumeCurveDrc;
2982 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
2983 sSpeakerSonificationVolumeCurveDrc;
2984 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
2985 sSpeakerSonificationVolumeCurveDrc;
2986 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
2987 sSpeakerSonificationVolumeCurveDrc;
2991 float AudioPolicyManagerBase::computeVolume(int stream,
2993 audio_io_handle_t output,
2994 audio_devices_t device)
2997 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2998 StreamDescriptor &streamDesc = mStreams[stream];
3000 if (device == AUDIO_DEVICE_NONE) {
3001 device = outputDesc->device();
3004 // if volume is not 0 (not muted), force media volume to max on digital output
3005 if (stream == AudioSystem::MUSIC &&
3006 index != mStreams[stream].mIndexMin &&
3007 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
3008 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
3009 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
3010 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
3014 volume = volIndexToAmpl(device, streamDesc, index);
3016 // if a headset is connected, apply the following rules to ring tones and notifications
3017 // to avoid sound level bursts in user's ears:
3018 // - always attenuate ring tones and notifications volume by 6dB
3019 // - if music is playing, always limit the volume to current music volume,
3020 // with a minimum threshold at -36dB so that notification is always perceived.
3021 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
3022 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
3023 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
3024 AUDIO_DEVICE_OUT_WIRED_HEADSET |
3025 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
3026 ((stream_strategy == STRATEGY_SONIFICATION)
3027 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
3028 || (stream == AudioSystem::SYSTEM)
3029 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
3030 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) &&
3031 streamDesc.mCanBeMuted) {
3032 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
3033 // when the phone is ringing we must consider that music could have been paused just before
3034 // by the music application and behave as if music was active if the last music track was
3036 if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
3037 mLimitRingtoneVolume) {
3038 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
3039 float musicVol = computeVolume(AudioSystem::MUSIC,
3040 mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice),
3043 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
3044 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
3045 if (volume > minVol) {
3047 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
3055 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
3057 audio_io_handle_t output,
3058 audio_devices_t device,
3063 // do not change actual stream volume if the stream is muted
3064 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
3065 ALOGVV("checkAndSetVolume() stream %d muted count %d",
3066 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
3070 // do not change in call volume if bluetooth is connected and vice versa
3071 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
3072 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
3073 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
3074 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
3075 return INVALID_OPERATION;
3078 float volume = computeVolume(stream, index, output, device);
3079 // We actually change the volume if:
3080 // - the float value returned by computeVolume() changed
3081 // - the force flag is set
3082 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
3084 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
3085 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
3086 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
3088 if (stream == AudioSystem::BLUETOOTH_SCO) {
3089 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
3091 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
3094 if (stream == AudioSystem::VOICE_CALL ||
3095 stream == AudioSystem::BLUETOOTH_SCO) {
3097 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
3098 if (stream == AudioSystem::VOICE_CALL) {
3099 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
3104 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
3105 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
3106 mLastVoiceVolume = voiceVolume;
3113 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
3114 audio_devices_t device,
3118 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
3120 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3121 checkAndSetVolume(stream,
3122 mStreams[stream].getVolumeIndex(device),
3130 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
3132 audio_io_handle_t output,
3134 audio_devices_t device)
3136 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
3137 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3138 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
3139 setStreamMute(stream, on, output, delayMs, device);
3144 void AudioPolicyManagerBase::setStreamMute(int stream,
3146 audio_io_handle_t output,
3148 audio_devices_t device)
3150 StreamDescriptor &streamDesc = mStreams[stream];
3151 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3152 if (device == AUDIO_DEVICE_NONE) {
3153 device = outputDesc->device();
3156 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
3157 stream, on, output, outputDesc->mMuteCount[stream], device);
3160 if (outputDesc->mMuteCount[stream] == 0) {
3161 if (streamDesc.mCanBeMuted &&
3162 ((stream != AudioSystem::ENFORCED_AUDIBLE) ||
3163 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) {
3164 checkAndSetVolume(stream, 0, output, device, delayMs);
3167 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
3168 outputDesc->mMuteCount[stream]++;
3170 if (outputDesc->mMuteCount[stream] == 0) {
3171 ALOGV("setStreamMute() unmuting non muted stream!");
3174 if (--outputDesc->mMuteCount[stream] == 0) {
3175 checkAndSetVolume(stream,
3176 streamDesc.getVolumeIndex(device),
3184 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
3186 // if the stream pertains to sonification strategy and we are in call we must
3187 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
3188 // in the device used for phone strategy and play the tone if the selected device does not
3189 // interfere with the device used for phone strategy
3190 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
3191 // many times as there are active tracks on the output
3192 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
3193 if ((stream_strategy == STRATEGY_SONIFICATION) ||
3194 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
3195 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
3196 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
3197 stream, starting, outputDesc->mDevice, stateChange);
3198 if (outputDesc->mRefCount[stream]) {
3201 muteCount = outputDesc->mRefCount[stream];
3203 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
3204 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
3205 for (int i = 0; i < muteCount; i++) {
3206 setStreamMute(stream, starting, mPrimaryOutput);
3209 ALOGV("handleIncallSonification() high visibility");
3210 if (outputDesc->device() &
3211 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
3212 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
3213 for (int i = 0; i < muteCount; i++) {
3214 setStreamMute(stream, starting, mPrimaryOutput);
3218 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
3220 mpClientInterface->stopTone();
3227 bool AudioPolicyManagerBase::isInCall()
3229 return isStateInCall(mPhoneState);
3232 bool AudioPolicyManagerBase::isStateInCall(int state) {
3233 return ((state == AudioSystem::MODE_IN_CALL) ||
3234 (state == AudioSystem::MODE_IN_COMMUNICATION));
3237 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
3239 return MAX_EFFECTS_CPU_LOAD;
3242 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
3244 return MAX_EFFECTS_MEMORY;
3247 // --- AudioOutputDescriptor class implementation
3249 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
3250 const IOProfile *profile)
3251 : mId(0), mSamplingRate(0), mFormat((audio_format_t)0),
3252 mChannelMask((audio_channel_mask_t)0), mLatency(0),
3253 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
3254 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
3256 // clear usage count for all stream types
3257 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3259 mCurVolume[i] = -1.0;
3263 for (int i = 0; i < NUM_STRATEGIES; i++) {
3264 mStrategyMutedByDevice[i] = false;
3266 if (profile != NULL) {
3267 mSamplingRate = profile->mSamplingRates[0];
3268 mFormat = profile->mFormats[0];
3269 mChannelMask = profile->mChannelMasks[0];
3270 mFlags = profile->mFlags;
3274 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device() const
3276 if (isDuplicated()) {
3277 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
3283 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
3285 if (isDuplicated()) {
3286 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
3292 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
3293 const AudioOutputDescriptor *outputDesc)
3295 if (isDuplicated()) {
3296 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
3297 } else if (outputDesc->isDuplicated()){
3298 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
3300 return (mProfile->mModule == outputDesc->mProfile->mModule);
3304 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
3306 // forward usage count change to attached outputs
3307 if (isDuplicated()) {
3308 mOutput1->changeRefCount(stream, delta);
3309 mOutput2->changeRefCount(stream, delta);
3311 if ((delta + (int)mRefCount[stream]) < 0) {
3312 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
3313 mRefCount[stream] = 0;
3316 mRefCount[stream] += delta;
3317 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
3320 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
3322 if (isDuplicated()) {
3323 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
3325 return mProfile->mSupportedDevices ;
3329 bool AudioPolicyManagerBase::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
3331 return isStrategyActive(NUM_STRATEGIES, inPastMs);
3334 bool AudioPolicyManagerBase::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
3336 nsecs_t sysTime) const
3338 if ((sysTime == 0) && (inPastMs != 0)) {
3339 sysTime = systemTime();
3341 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3342 if (((getStrategy((AudioSystem::stream_type)i) == strategy) ||
3343 (NUM_STRATEGIES == strategy)) &&
3344 isStreamActive((AudioSystem::stream_type)i, inPastMs, sysTime)) {
3351 bool AudioPolicyManagerBase::AudioOutputDescriptor::isStreamActive(AudioSystem::stream_type stream,
3353 nsecs_t sysTime) const
3355 if (mRefCount[stream] != 0) {
3358 if (inPastMs == 0) {
3362 sysTime = systemTime();
3364 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
3371 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
3373 const size_t SIZE = 256;
3377 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3378 result.append(buffer);
3379 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
3380 result.append(buffer);
3381 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3382 result.append(buffer);
3383 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
3384 result.append(buffer);
3385 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
3386 result.append(buffer);
3387 snprintf(buffer, SIZE, " Devices %08x\n", device());
3388 result.append(buffer);
3389 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
3390 result.append(buffer);
3391 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3392 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
3393 result.append(buffer);
3395 write(fd, result.string(), result.size());
3400 // --- AudioInputDescriptor class implementation
3402 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3403 : mSamplingRate(0), mFormat((audio_format_t)0), mChannelMask((audio_channel_mask_t)0),
3404 mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
3405 mInputSource(0), mProfile(profile)
3409 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3411 const size_t SIZE = 256;
3415 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3416 result.append(buffer);
3417 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3418 result.append(buffer);
3419 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3420 result.append(buffer);
3421 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3422 result.append(buffer);
3423 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3424 result.append(buffer);
3425 write(fd, result.string(), result.size());
3430 // --- StreamDescriptor class implementation
3432 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3433 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3435 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3438 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3440 device = AudioPolicyManagerBase::getDeviceForVolume(device);
3441 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3442 if (mIndexCur.indexOfKey(device) < 0) {
3443 device = AUDIO_DEVICE_OUT_DEFAULT;
3445 return mIndexCur.valueFor(device);
3448 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3450 const size_t SIZE = 256;
3454 snprintf(buffer, SIZE, "%s %02d %02d ",
3455 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3456 result.append(buffer);
3457 for (size_t i = 0; i < mIndexCur.size(); i++) {
3458 snprintf(buffer, SIZE, "%04x : %02d, ",
3460 mIndexCur.valueAt(i));
3461 result.append(buffer);
3463 result.append("\n");
3465 write(fd, result.string(), result.size());
3468 // --- EffectDescriptor class implementation
3470 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3472 const size_t SIZE = 256;
3476 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3477 result.append(buffer);
3478 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3479 result.append(buffer);
3480 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3481 result.append(buffer);
3482 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3483 result.append(buffer);
3484 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3485 result.append(buffer);
3486 write(fd, result.string(), result.size());
3491 // --- IOProfile class implementation
3493 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3494 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3498 AudioPolicyManagerBase::HwModule::~HwModule()
3500 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3501 delete mOutputProfiles[i];
3503 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3504 delete mInputProfiles[i];
3506 free((void *)mName);
3509 void AudioPolicyManagerBase::HwModule::dump(int fd)
3511 const size_t SIZE = 256;
3515 snprintf(buffer, SIZE, " - name: %s\n", mName);
3516 result.append(buffer);
3517 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3518 result.append(buffer);
3519 write(fd, result.string(), result.size());
3520 if (mOutputProfiles.size()) {
3521 write(fd, " - outputs:\n", sizeof(" - outputs:\n"));
3522 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3523 snprintf(buffer, SIZE, " output %d:\n", i);
3524 write(fd, buffer, strlen(buffer));
3525 mOutputProfiles[i]->dump(fd);
3528 if (mInputProfiles.size()) {
3529 write(fd, " - inputs:\n", sizeof(" - inputs:\n"));
3530 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3531 snprintf(buffer, SIZE, " input %d:\n", i);
3532 write(fd, buffer, strlen(buffer));
3533 mInputProfiles[i]->dump(fd);
3538 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3539 : mFlags((audio_output_flags_t)0), mModule(module)
3543 AudioPolicyManagerBase::IOProfile::~IOProfile()
3547 // checks if the IO profile is compatible with specified parameters.
3548 // Sampling rate, format and channel mask must be specified in order to
3549 // get a valid a match
3550 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3551 uint32_t samplingRate,
3553 uint32_t channelMask,
3554 audio_output_flags_t flags) const
3556 if (samplingRate == 0 || format == 0 || channelMask == 0) {
3560 if ((mSupportedDevices & device) != device) {
3563 if ((mFlags & flags) != flags) {
3567 for (i = 0; i < mSamplingRates.size(); i++)
3569 if (mSamplingRates[i] == samplingRate) {
3573 if (i == mSamplingRates.size()) {
3576 for (i = 0; i < mFormats.size(); i++)
3578 if (mFormats[i] == format) {
3582 if (i == mFormats.size()) {
3585 for (i = 0; i < mChannelMasks.size(); i++)
3587 if (mChannelMasks[i] == channelMask) {
3591 if (i == mChannelMasks.size()) {
3597 void AudioPolicyManagerBase::IOProfile::dump(int fd)
3599 const size_t SIZE = 256;
3603 snprintf(buffer, SIZE, " - sampling rates: ");
3604 result.append(buffer);
3605 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3606 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3607 result.append(buffer);
3608 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3611 snprintf(buffer, SIZE, " - channel masks: ");
3612 result.append(buffer);
3613 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3614 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
3615 result.append(buffer);
3616 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3619 snprintf(buffer, SIZE, " - formats: ");
3620 result.append(buffer);
3621 for (size_t i = 0; i < mFormats.size(); i++) {
3622 snprintf(buffer, SIZE, "0x%08x", mFormats[i]);
3623 result.append(buffer);
3624 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3627 snprintf(buffer, SIZE, " - devices: 0x%04x\n", mSupportedDevices);
3628 result.append(buffer);
3629 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
3630 result.append(buffer);
3632 write(fd, result.string(), result.size());
3635 // --- audio_policy.conf file parsing
3637 struct StringToEnum {
3642 #define STRING_TO_ENUM(string) { #string, string }
3643 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3645 const struct StringToEnum sDeviceNameToEnumTable[] = {
3646 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3647 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3648 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3649 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3650 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3651 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3652 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3653 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3654 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3655 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3656 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3657 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3658 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
3659 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3660 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3661 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3662 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3663 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3664 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3665 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
3666 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
3667 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
3668 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
3671 const struct StringToEnum sFlagNameToEnumTable[] = {
3672 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3673 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3674 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3675 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3676 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
3677 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
3680 const struct StringToEnum sFormatNameToEnumTable[] = {
3681 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3682 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3683 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3684 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3685 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3688 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3689 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3690 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3691 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3692 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3695 const struct StringToEnum sInChannelsNameToEnumTable[] = {
3696 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3697 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3698 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
3702 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3706 for (size_t i = 0; i < size; i++) {
3707 if (strcmp(table[i].name, name) == 0) {
3708 ALOGV("stringToEnum() found %s", table[i].name);
3709 return table[i].value;
3715 bool AudioPolicyManagerBase::stringToBool(const char *value)
3717 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
3720 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3724 // it is OK to cast name to non const here as we are not going to use it after
3725 // strtok() modifies it
3726 char *flagName = strtok(name, "|");
3727 while (flagName != NULL) {
3728 if (strlen(flagName) != 0) {
3729 flag |= stringToEnum(sFlagNameToEnumTable,
3730 ARRAY_SIZE(sFlagNameToEnumTable),
3733 flagName = strtok(NULL, "|");
3735 //force direct flag if offload flag is set: offloading implies a direct output stream
3736 // and all common behaviors are driven by checking only the direct flag
3737 // this should normally be set appropriately in the policy configuration file
3738 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
3739 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
3742 return (audio_output_flags_t)flag;
3745 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
3747 uint32_t device = 0;
3749 char *devName = strtok(name, "|");
3750 while (devName != NULL) {
3751 if (strlen(devName) != 0) {
3752 device |= stringToEnum(sDeviceNameToEnumTable,
3753 ARRAY_SIZE(sDeviceNameToEnumTable),
3756 devName = strtok(NULL, "|");
3761 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
3763 char *str = strtok(name, "|");
3765 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
3766 // rates should be read from the output stream after it is opened for the first time
3767 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3768 profile->mSamplingRates.add(0);
3772 while (str != NULL) {
3773 uint32_t rate = atoi(str);
3775 ALOGV("loadSamplingRates() adding rate %d", rate);
3776 profile->mSamplingRates.add(rate);
3778 str = strtok(NULL, "|");
3783 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
3785 char *str = strtok(name, "|");
3787 // by convention, "0' in the first entry in mFormats indicates the supported formats
3788 // should be read from the output stream after it is opened for the first time
3789 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3790 profile->mFormats.add((audio_format_t)0);
3794 while (str != NULL) {
3795 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
3796 ARRAY_SIZE(sFormatNameToEnumTable),
3799 profile->mFormats.add(format);
3801 str = strtok(NULL, "|");
3806 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
3808 const char *str = strtok(name, "|");
3810 ALOGV("loadInChannels() %s", name);
3812 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3813 profile->mChannelMasks.add((audio_channel_mask_t)0);
3817 while (str != NULL) {
3818 audio_channel_mask_t channelMask =
3819 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
3820 ARRAY_SIZE(sInChannelsNameToEnumTable),
3822 if (channelMask != 0) {
3823 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
3824 profile->mChannelMasks.add(channelMask);
3826 str = strtok(NULL, "|");
3831 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
3833 const char *str = strtok(name, "|");
3835 ALOGV("loadOutChannels() %s", name);
3837 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
3838 // masks should be read from the output stream after it is opened for the first time
3839 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3840 profile->mChannelMasks.add((audio_channel_mask_t)0);
3844 while (str != NULL) {
3845 audio_channel_mask_t channelMask =
3846 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
3847 ARRAY_SIZE(sOutChannelsNameToEnumTable),
3849 if (channelMask != 0) {
3850 profile->mChannelMasks.add(channelMask);
3852 str = strtok(NULL, "|");
3857 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
3859 cnode *node = root->first_child;
3861 IOProfile *profile = new IOProfile(module);
3864 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3865 loadSamplingRates((char *)node->value, profile);
3866 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3867 loadFormats((char *)node->value, profile);
3868 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3869 loadInChannels((char *)node->value, profile);
3870 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3871 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3875 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
3876 "loadInput() invalid supported devices");
3877 ALOGW_IF(profile->mChannelMasks.size() == 0,
3878 "loadInput() invalid supported channel masks");
3879 ALOGW_IF(profile->mSamplingRates.size() == 0,
3880 "loadInput() invalid supported sampling rates");
3881 ALOGW_IF(profile->mFormats.size() == 0,
3882 "loadInput() invalid supported formats");
3883 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
3884 (profile->mChannelMasks.size() != 0) &&
3885 (profile->mSamplingRates.size() != 0) &&
3886 (profile->mFormats.size() != 0)) {
3888 ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices);
3890 module->mInputProfiles.add(profile);
3898 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
3900 cnode *node = root->first_child;
3902 IOProfile *profile = new IOProfile(module);
3905 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3906 loadSamplingRates((char *)node->value, profile);
3907 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3908 loadFormats((char *)node->value, profile);
3909 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3910 loadOutChannels((char *)node->value, profile);
3911 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3912 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3913 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
3914 profile->mFlags = parseFlagNames((char *)node->value);
3918 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
3919 "loadOutput() invalid supported devices");
3920 ALOGW_IF(profile->mChannelMasks.size() == 0,
3921 "loadOutput() invalid supported channel masks");
3922 ALOGW_IF(profile->mSamplingRates.size() == 0,
3923 "loadOutput() invalid supported sampling rates");
3924 ALOGW_IF(profile->mFormats.size() == 0,
3925 "loadOutput() invalid supported formats");
3926 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
3927 (profile->mChannelMasks.size() != 0) &&
3928 (profile->mSamplingRates.size() != 0) &&
3929 (profile->mFormats.size() != 0)) {
3931 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
3932 profile->mSupportedDevices, profile->mFlags);
3934 module->mOutputProfiles.add(profile);
3942 void AudioPolicyManagerBase::loadHwModule(cnode *root)
3944 cnode *node = config_find(root, OUTPUTS_TAG);
3945 status_t status = NAME_NOT_FOUND;
3947 HwModule *module = new HwModule(root->name);
3950 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
3952 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
3954 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) {
3955 mHasRemoteSubmix = true;
3958 node = node->first_child;
3960 ALOGV("loadHwModule() loading output %s", node->name);
3961 status_t tmpStatus = loadOutput(node, module);
3962 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3968 node = config_find(root, INPUTS_TAG);
3970 node = node->first_child;
3972 ALOGV("loadHwModule() loading input %s", node->name);
3973 status_t tmpStatus = loadInput(node, module);
3974 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3980 if (status == NO_ERROR) {
3981 mHwModules.add(module);
3987 void AudioPolicyManagerBase::loadHwModules(cnode *root)
3989 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
3994 node = node->first_child;
3996 ALOGV("loadHwModules() loading module %s", node->name);
4002 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
4004 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
4008 node = node->first_child;
4010 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
4011 mAttachedOutputDevices = parseDeviceNames((char *)node->value);
4012 ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE,
4013 "loadGlobalConfig() no attached output devices");
4014 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
4015 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
4016 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
4017 ARRAY_SIZE(sDeviceNameToEnumTable),
4018 (char *)node->value);
4019 ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE,
4020 "loadGlobalConfig() default device not specified");
4021 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
4022 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
4023 mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN;
4024 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
4025 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
4026 mSpeakerDrcEnabled = stringToBool((char *)node->value);
4027 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
4033 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
4038 data = (char *)load_file(path, NULL);
4042 root = config_node("", "");
4043 config_load(root, data);
4045 loadGlobalConfig(root);
4046 loadHwModules(root);
4052 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
4057 void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
4062 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
4063 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
4064 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC & ~AUDIO_DEVICE_BIT_IN;
4066 module = new HwModule("primary");
4068 profile = new IOProfile(module);
4069 profile->mSamplingRates.add(44100);
4070 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4071 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
4072 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
4073 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
4074 module->mOutputProfiles.add(profile);
4076 profile = new IOProfile(module);
4077 profile->mSamplingRates.add(8000);
4078 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4079 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
4080 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
4081 module->mInputProfiles.add(profile);
4083 mHwModules.add(module);
4086 }; // namespace android