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 #include <utils/Log.h>
28 #include <hardware_legacy/AudioPolicyManagerBase.h>
29 #include <hardware/audio_effect.h>
30 #include <hardware/audio.h>
32 #include <hardware_legacy/audio_policy_conf.h>
34 namespace android_audio_legacy {
36 // ----------------------------------------------------------------------------
37 // AudioPolicyInterface implementation
38 // ----------------------------------------------------------------------------
41 status_t AudioPolicyManagerBase::setDeviceConnectionState(AudioSystem::audio_devices device,
42 AudioSystem::device_connection_state state,
43 const char *device_address)
45 SortedVector <audio_io_handle_t> outputs;
47 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
49 // connect/disconnect only 1 device at a time
50 if (AudioSystem::popCount(device) != 1) return BAD_VALUE;
52 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
53 ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
57 // handle output devices
58 if (AudioSystem::isOutputDevice(device)) {
60 if (!mHasA2dp && AudioSystem::isA2dpDevice(device)) {
61 ALOGE("setDeviceConnectionState() invalid device: %x", device);
64 if (!mHasUsb && audio_is_usb_device((audio_devices_t)device)) {
65 ALOGE("setDeviceConnectionState() invalid device: %x", device);
71 // handle output device connection
72 case AudioSystem::DEVICE_STATE_AVAILABLE:
73 if (mAvailableOutputDevices & device) {
74 ALOGW("setDeviceConnectionState() device already connected: %x", device);
75 return INVALID_OPERATION;
77 ALOGV("setDeviceConnectionState() connecting device %x", device);
79 if (checkOutputsForDevice((audio_devices_t)device, state, outputs) != NO_ERROR) {
80 return INVALID_OPERATION;
82 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %d outputs",
84 // register new device as available
85 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
87 if (!outputs.isEmpty()) {
89 if (mHasA2dp && AudioSystem::isA2dpDevice(device)) {
90 // handle A2DP device connection
92 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
93 paramStr = param.toString();
94 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
95 mA2dpSuspended = false;
96 } else if (AudioSystem::isBluetoothScoDevice(device)) {
97 // handle SCO device connection
98 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
99 } else if (mHasUsb && audio_is_usb_device((audio_devices_t)device)) {
100 // handle USB device connection
101 mUsbCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
102 paramStr = mUsbCardAndDevice;
104 if (!paramStr.isEmpty()) {
105 for (size_t i = 0; i < outputs.size(); i++) {
106 mpClientInterface->setParameters(outputs[i], paramStr);
111 // handle output device disconnection
112 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
113 if (!(mAvailableOutputDevices & device)) {
114 ALOGW("setDeviceConnectionState() device not connected: %x", device);
115 return INVALID_OPERATION;
118 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
119 // remove device from available output devices
120 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
122 checkOutputsForDevice((audio_devices_t)device, state, outputs);
123 if (mHasA2dp && AudioSystem::isA2dpDevice(device)) {
124 // handle A2DP device disconnection
125 mA2dpDeviceAddress = "";
126 mA2dpSuspended = false;
127 } else if (AudioSystem::isBluetoothScoDevice(device)) {
128 // handle SCO device disconnection
129 mScoDeviceAddress = "";
130 } else if (mHasUsb && audio_is_usb_device((audio_devices_t)device)) {
131 // handle USB device disconnection
132 mUsbCardAndDevice = "";
137 ALOGE("setDeviceConnectionState() invalid state: %x", state);
142 checkOutputForAllStrategies();
143 // outputs must be closed after checkOutputForAllStrategies() is executed
144 if (!outputs.isEmpty()) {
145 for (size_t i = 0; i < outputs.size(); i++) {
146 // close unused outputs after device disconnection or direct outputs that have been
147 // opened by checkOutputsForDevice() to query dynamic parameters
148 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
149 (mOutputs.valueFor(outputs[i])->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
150 closeOutput(outputs[i]);
155 updateDeviceForStrategy();
156 for (size_t i = 0; i < mOutputs.size(); i++) {
157 setOutputDevice(mOutputs.keyAt(i), getNewDevice(mOutputs.keyAt(i), true /*fromCache*/));
160 if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET) {
161 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
162 } else if (device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO ||
163 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
164 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
165 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
170 // handle input devices
171 if (AudioSystem::isInputDevice(device)) {
175 // handle input device connection
176 case AudioSystem::DEVICE_STATE_AVAILABLE: {
177 if (mAvailableInputDevices & device) {
178 ALOGW("setDeviceConnectionState() device already connected: %d", device);
179 return INVALID_OPERATION;
181 mAvailableInputDevices = (audio_devices_t)(mAvailableInputDevices | device);
185 // handle input device disconnection
186 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
187 if (!(mAvailableInputDevices & device)) {
188 ALOGW("setDeviceConnectionState() device not connected: %d", device);
189 return INVALID_OPERATION;
191 mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
195 ALOGE("setDeviceConnectionState() invalid state: %x", state);
199 audio_io_handle_t activeInput = getActiveInput();
200 if (activeInput != 0) {
201 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
202 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
203 if ((newDevice != 0) && (newDevice != inputDesc->mDevice)) {
204 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
205 inputDesc->mDevice, newDevice, activeInput);
206 inputDesc->mDevice = newDevice;
207 AudioParameter param = AudioParameter();
208 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
209 mpClientInterface->setParameters(activeInput, param.toString());
216 ALOGW("setDeviceConnectionState() invalid device: %x", device);
220 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(AudioSystem::audio_devices device,
221 const char *device_address)
223 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
224 String8 address = String8(device_address);
225 if (AudioSystem::isOutputDevice(device)) {
226 if (device & mAvailableOutputDevices) {
227 if (AudioSystem::isA2dpDevice(device) &&
228 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
231 if (AudioSystem::isBluetoothScoDevice(device) &&
232 address != "" && mScoDeviceAddress != address) {
235 if (audio_is_usb_device((audio_devices_t)device) &&
236 (!mHasUsb || (address != "" && mUsbCardAndDevice != address))) {
237 ALOGE("setDeviceConnectionState() invalid device: %x", device);
240 state = AudioSystem::DEVICE_STATE_AVAILABLE;
242 } else if (AudioSystem::isInputDevice(device)) {
243 if (device & mAvailableInputDevices) {
244 state = AudioSystem::DEVICE_STATE_AVAILABLE;
251 void AudioPolicyManagerBase::setPhoneState(int state)
253 ALOGV("setPhoneState() state %d", state);
254 audio_devices_t newDevice = (audio_devices_t)0;
255 if (state < 0 || state >= AudioSystem::NUM_MODES) {
256 ALOGW("setPhoneState() invalid state %d", state);
260 if (state == mPhoneState ) {
261 ALOGW("setPhoneState() setting same state %d", state);
265 // if leaving call state, handle special case of active streams
266 // pertaining to sonification strategy see handleIncallSonification()
268 ALOGV("setPhoneState() in call state management: new state is %d", state);
269 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
270 handleIncallSonification(stream, false, true);
274 // store previous phone state for management of sonification strategy below
275 int oldState = mPhoneState;
279 // are we entering or starting a call
280 if (!isStateInCall(oldState) && isStateInCall(state)) {
281 ALOGV(" Entering call in setPhoneState()");
282 // force routing command to audio hardware when starting a call
283 // even if no device change is needed
285 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
286 ALOGV(" Exiting call in setPhoneState()");
287 // force routing command to audio hardware when exiting a call
288 // even if no device change is needed
290 } else if (isStateInCall(state) && (state != oldState)) {
291 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
292 // force routing command to audio hardware when switching between telephony and VoIP
293 // even if no device change is needed
297 // check for device and output changes triggered by new phone state
298 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
300 checkOutputForAllStrategies();
301 updateDeviceForStrategy();
303 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
305 // force routing command to audio hardware when ending call
306 // even if no device change is needed
307 if (isStateInCall(oldState) && newDevice == 0) {
308 newDevice = hwOutputDesc->device();
311 // when changing from ring tone to in call mode, mute the ringing tone
312 // immediately and delay the route change to avoid sending the ring tone
313 // tail into the earpiece or headset.
315 if (isStateInCall(state) && oldState == AudioSystem::MODE_RINGTONE) {
316 // delay the device change command by twice the output latency to have some margin
317 // and be sure that audio buffers not yet affected by the mute are out when
318 // we actually apply the route change
319 delayMs = hwOutputDesc->mLatency*2;
320 setStreamMute(AudioSystem::RING, true, mPrimaryOutput);
323 // change routing is necessary
324 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
326 // if entering in call state, handle special case of active streams
327 // pertaining to sonification strategy see handleIncallSonification()
328 if (isStateInCall(state)) {
329 ALOGV("setPhoneState() in call state management: new state is %d", state);
330 // unmute the ringing tone after a sufficient delay if it was muted before
331 // setting output device above
332 if (oldState == AudioSystem::MODE_RINGTONE) {
333 setStreamMute(AudioSystem::RING, false, mPrimaryOutput, MUTE_TIME_MS);
335 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
336 handleIncallSonification(stream, true, true);
340 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
341 if (state == AudioSystem::MODE_RINGTONE &&
342 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
343 mLimitRingtoneVolume = true;
345 mLimitRingtoneVolume = false;
349 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
351 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
353 bool forceVolumeReeval = false;
355 case AudioSystem::FOR_COMMUNICATION:
356 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
357 config != AudioSystem::FORCE_NONE) {
358 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
361 forceVolumeReeval = true;
362 mForceUse[usage] = config;
364 case AudioSystem::FOR_MEDIA:
365 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
366 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
367 config != AudioSystem::FORCE_ANALOG_DOCK &&
368 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
369 config != AudioSystem::FORCE_NO_BT_A2DP) {
370 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
373 mForceUse[usage] = config;
375 case AudioSystem::FOR_RECORD:
376 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
377 config != AudioSystem::FORCE_NONE) {
378 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
381 mForceUse[usage] = config;
383 case AudioSystem::FOR_DOCK:
384 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
385 config != AudioSystem::FORCE_BT_DESK_DOCK &&
386 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
387 config != AudioSystem::FORCE_ANALOG_DOCK &&
388 config != AudioSystem::FORCE_DIGITAL_DOCK) {
389 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
391 forceVolumeReeval = true;
392 mForceUse[usage] = config;
395 ALOGW("setForceUse() invalid usage %d", usage);
399 // check for device and output changes triggered by new force usage
401 checkOutputForAllStrategies();
402 updateDeviceForStrategy();
403 for (size_t i = 0; i < mOutputs.size(); i++) {
404 audio_io_handle_t output = mOutputs.keyAt(i);
405 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
406 setOutputDevice(output, newDevice, true);
407 if (forceVolumeReeval) {
408 applyStreamVolumes(output, newDevice, 0, true);
412 audio_io_handle_t activeInput = getActiveInput();
413 if (activeInput != 0) {
414 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
415 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
416 if ((newDevice != 0) && (newDevice != inputDesc->mDevice)) {
417 ALOGV("setForceUse() changing device from %x to %x for input %d",
418 inputDesc->mDevice, newDevice, activeInput);
419 inputDesc->mDevice = newDevice;
420 AudioParameter param = AudioParameter();
421 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
422 mpClientInterface->setParameters(activeInput, param.toString());
428 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
430 return mForceUse[usage];
433 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
435 ALOGV("setSystemProperty() property %s, value %s", property, value);
436 if (strcmp(property, "ro.camera.sound.forced") == 0) {
438 ALOGV("ENFORCED_AUDIBLE cannot be muted");
439 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false;
441 ALOGV("ENFORCED_AUDIBLE can be muted");
442 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = true;
447 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
448 audio_devices_t device,
449 uint32_t samplingRate,
451 uint32_t channelMask,
452 audio_output_flags_t flags)
454 for (size_t i = 0; i < mHwModules.size(); i++) {
455 if (mHwModules[i]->mHandle == 0) {
458 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
459 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
460 if (profile->isCompatibleProfile(device, samplingRate, format,
462 AUDIO_OUTPUT_FLAG_DIRECT)) {
463 if (mAvailableOutputDevices & profile->mSupportedDevices) {
464 return mHwModules[i]->mOutputProfiles[j];
472 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
473 uint32_t samplingRate,
475 uint32_t channelMask,
476 AudioSystem::output_flags flags)
478 audio_io_handle_t output = 0;
479 uint32_t latency = 0;
480 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
481 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
482 ALOGV("getOutput() stream %d, samplingRate %d, format %d, channelMask %x, flags %x",
483 stream, samplingRate, format, channelMask, flags);
485 #ifdef AUDIO_POLICY_TEST
486 if (mCurOutput != 0) {
487 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
488 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
490 if (mTestOutputs[mCurOutput] == 0) {
491 ALOGV("getOutput() opening test output");
492 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
493 outputDesc->mDevice = mTestDevice;
494 outputDesc->mSamplingRate = mTestSamplingRate;
495 outputDesc->mFormat = mTestFormat;
496 outputDesc->mChannelMask = mTestChannels;
497 outputDesc->mLatency = mTestLatencyMs;
498 outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
499 outputDesc->mRefCount[stream] = 0;
500 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
501 &outputDesc->mSamplingRate,
502 &outputDesc->mFormat,
503 &outputDesc->mChannelMask,
504 &outputDesc->mLatency,
506 if (mTestOutputs[mCurOutput]) {
507 AudioParameter outputCmd = AudioParameter();
508 outputCmd.addInt(String8("set_id"),mCurOutput);
509 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
510 addOutput(mTestOutputs[mCurOutput], outputDesc);
513 return mTestOutputs[mCurOutput];
515 #endif //AUDIO_POLICY_TEST
517 // open a direct output if required by specified parameters
518 IOProfile *profile = getProfileForDirectOutput(device,
522 (audio_output_flags_t)flags);
523 if (profile != NULL) {
525 ALOGV("getOutput() opening direct output device %x", device);
527 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(profile);
528 outputDesc->mDevice = device;
529 outputDesc->mSamplingRate = samplingRate;
530 outputDesc->mFormat = (audio_format_t)format;
531 outputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
532 outputDesc->mLatency = 0;
533 outputDesc->mFlags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);;
534 outputDesc->mRefCount[stream] = 0;
535 outputDesc->mStopTime[stream] = 0;
536 output = mpClientInterface->openOutput(profile->mModule->mHandle,
537 &outputDesc->mDevice,
538 &outputDesc->mSamplingRate,
539 &outputDesc->mFormat,
540 &outputDesc->mChannelMask,
541 &outputDesc->mLatency,
544 // only accept an output with the requested parameters
546 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
547 (format != 0 && format != outputDesc->mFormat) ||
548 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
549 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
550 "format %d %d, channelMask %04x %04x", output, samplingRate,
551 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
552 outputDesc->mChannelMask);
554 mpClientInterface->closeOutput(output);
559 addOutput(output, outputDesc);
560 ALOGV("getOutput() returns direct output %d", output);
564 // ignoring channel mask due to downmix capability in mixer
566 // open a non direct output
568 // get which output is suitable for the specified stream. The actual routing change will happen
569 // when startOutput() will be called
570 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device);
572 output = selectOutput(outputs, flags);
574 ALOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d,"
575 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
577 ALOGV("getOutput() returns output %d", output);
582 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
583 AudioSystem::output_flags flags)
585 // select one output among several that provide a path to a particular device or set of
586 // devices (the list was previously build by getOutputsForDevice()).
587 // The priority is as follows:
588 // 1: the output with the highest number of requested policy flags
589 // 2: the primary output
590 // 3: the first output in the list
592 if (outputs.size() == 0) {
595 if (outputs.size() == 1) {
599 int maxCommonFlags = 0;
600 audio_io_handle_t outputFlags = 0;
601 audio_io_handle_t outputPrimary = 0;
603 for (size_t i = 0; i < outputs.size(); i++) {
604 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
605 if (!outputDesc->isDuplicated()) {
606 int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
607 if (commonFlags > maxCommonFlags) {
608 outputFlags = outputs[i];
609 maxCommonFlags = commonFlags;
610 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
612 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
613 outputPrimary = outputs[i];
618 if (outputFlags != 0) {
621 if (outputPrimary != 0) {
622 return outputPrimary;
628 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
629 AudioSystem::stream_type stream,
632 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
633 ssize_t index = mOutputs.indexOfKey(output);
635 ALOGW("startOutput() unknow output %d", output);
639 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
641 // increment usage count for this stream on the requested output:
642 // NOTE that the usage count is the same for duplicated output and hardware output which is
643 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
644 outputDesc->changeRefCount(stream, 1);
646 if (outputDesc->mRefCount[stream] == 1) {
647 audio_devices_t prevDevice = outputDesc->device();
648 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
649 routing_strategy strategy = getStrategy(stream);
650 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
651 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
654 for (size_t i = 0; i < mOutputs.size(); i++) {
655 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
656 if (desc != outputDesc) {
657 // force a device change if any other output is managed by the same hw
658 // module and has a current device selection that differs from selected device.
659 // In this case, the audio HAL must receive the new device selection so that it can
660 // change the device currently selected by the other active output.
661 if (outputDesc->sharesHwModuleWith(desc) &&
662 desc->device() != newDevice) {
665 // wait for audio on other active outputs to be presented when starting
666 // a notification so that audio focus effect can propagate.
667 if (shouldWait && (desc->refCount() != 0) && (waitMs < desc->latency())) {
668 waitMs = desc->latency();
672 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
674 // handle special case for sonification while in call
676 handleIncallSonification(stream, true, false);
679 // apply volume rules for current stream and device if necessary
680 checkAndSetVolume(stream,
681 mStreams[stream].getVolumeIndex((audio_devices_t)newDevice),
685 // update the outputs if starting an output with a stream that can affect notification
687 handleNotificationRoutingForStream(stream);
688 if (waitMs > muteWaitMs) {
689 usleep((waitMs - muteWaitMs) * 2 * 1000);
696 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
697 AudioSystem::stream_type stream,
700 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
701 ssize_t index = mOutputs.indexOfKey(output);
703 ALOGW("stopOutput() unknow output %d", output);
707 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
709 // handle special case for sonification while in call
711 handleIncallSonification(stream, false, false);
714 if (outputDesc->mRefCount[stream] > 0) {
715 // decrement usage count of this stream on the output
716 outputDesc->changeRefCount(stream, -1);
717 // store time at which the stream was stopped - see isStreamActive()
718 if (outputDesc->mRefCount[stream] == 0) {
719 outputDesc->mStopTime[stream] = systemTime();
720 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
721 // delay the device switch by twice the latency because stopOutput() is executed when
722 // the track stop() command is received and at that time the audio track buffer can
723 // still contain data that needs to be drained. The latency only covers the audio HAL
724 // and kernel buffers. Also the latency does not always include additional delay in the
725 // audio path (audio DSP, CODEC ...)
726 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
728 // force restoring the device selection on other active outputs if it differs from the
729 // one being selected for this output
730 for (size_t i = 0; i < mOutputs.size(); i++) {
731 audio_io_handle_t curOutput = mOutputs.keyAt(i);
732 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
733 if (curOutput != output &&
734 desc->refCount() != 0 &&
735 outputDesc->sharesHwModuleWith(desc) &&
736 newDevice != desc->device()) {
737 setOutputDevice(curOutput,
738 getNewDevice(curOutput, false /*fromCache*/),
740 outputDesc->mLatency*2);
743 // update the outputs if stopping one with a stream that can affect notification routing
744 handleNotificationRoutingForStream(stream);
748 ALOGW("stopOutput() refcount is already 0 for output %d", output);
749 return INVALID_OPERATION;
753 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
755 ALOGV("releaseOutput() %d", output);
756 ssize_t index = mOutputs.indexOfKey(output);
758 ALOGW("releaseOutput() releasing unknown output %d", output);
762 #ifdef AUDIO_POLICY_TEST
763 int testIndex = testOutputIndex(output);
764 if (testIndex != 0) {
765 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
766 if (outputDesc->refCount() == 0) {
767 mpClientInterface->closeOutput(output);
768 delete mOutputs.valueAt(index);
769 mOutputs.removeItem(output);
770 mTestOutputs[testIndex] = 0;
774 #endif //AUDIO_POLICY_TEST
776 if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
777 mpClientInterface->closeOutput(output);
778 delete mOutputs.valueAt(index);
779 mOutputs.removeItem(output);
784 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
785 uint32_t samplingRate,
787 uint32_t channelMask,
788 AudioSystem::audio_in_acoustics acoustics)
790 audio_io_handle_t input = 0;
791 audio_devices_t device = getDeviceForInputSource(inputSource);
793 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
794 inputSource, samplingRate, format, channelMask, acoustics);
797 ALOGW("getInput() could not find device for inputSource %d", inputSource);
801 // adapt channel selection to input source
802 switch(inputSource) {
803 case AUDIO_SOURCE_VOICE_UPLINK:
804 channelMask = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
806 case AUDIO_SOURCE_VOICE_DOWNLINK:
807 channelMask = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
809 case AUDIO_SOURCE_VOICE_CALL:
810 channelMask = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
816 IOProfile *profile = getInputProfile(device,
820 if (profile == NULL) {
821 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d,"
823 device, samplingRate, format, channelMask);
827 if (profile->mModule->mHandle == 0) {
828 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
832 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
834 inputDesc->mInputSource = inputSource;
835 inputDesc->mDevice = device;
836 inputDesc->mSamplingRate = samplingRate;
837 inputDesc->mFormat = (audio_format_t)format;
838 inputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
839 inputDesc->mRefCount = 0;
840 input = mpClientInterface->openInput(profile->mModule->mHandle,
842 &inputDesc->mSamplingRate,
844 &inputDesc->mChannelMask);
846 // only accept input with the exact requested set of parameters
848 (samplingRate != inputDesc->mSamplingRate) ||
849 (format != inputDesc->mFormat) ||
850 (channelMask != inputDesc->mChannelMask)) {
851 ALOGV("getInput() failed opening input: samplingRate %d, format %d, channelMask %d",
852 samplingRate, format, channelMask);
854 mpClientInterface->closeInput(input);
859 mInputs.add(input, inputDesc);
863 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
865 ALOGV("startInput() input %d", input);
866 ssize_t index = mInputs.indexOfKey(input);
868 ALOGW("startInput() unknow input %d", input);
871 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
873 #ifdef AUDIO_POLICY_TEST
875 #endif //AUDIO_POLICY_TEST
877 // refuse 2 active AudioRecord clients at the same time
878 if (getActiveInput() != 0) {
879 ALOGW("startInput() input %d failed: other input already started", input);
880 return INVALID_OPERATION;
884 AudioParameter param = AudioParameter();
885 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
887 param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
888 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
890 mpClientInterface->setParameters(input, param.toString());
892 inputDesc->mRefCount = 1;
896 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
898 ALOGV("stopInput() input %d", input);
899 ssize_t index = mInputs.indexOfKey(input);
901 ALOGW("stopInput() unknow input %d", input);
904 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
906 if (inputDesc->mRefCount == 0) {
907 ALOGW("stopInput() input %d already stopped", input);
908 return INVALID_OPERATION;
910 AudioParameter param = AudioParameter();
911 param.addInt(String8(AudioParameter::keyRouting), 0);
912 mpClientInterface->setParameters(input, param.toString());
913 inputDesc->mRefCount = 0;
918 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
920 ALOGV("releaseInput() %d", input);
921 ssize_t index = mInputs.indexOfKey(input);
923 ALOGW("releaseInput() releasing unknown input %d", input);
926 mpClientInterface->closeInput(input);
927 delete mInputs.valueAt(index);
928 mInputs.removeItem(input);
929 ALOGV("releaseInput() exit");
932 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
936 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
937 if (indexMin < 0 || indexMin >= indexMax) {
938 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
941 mStreams[stream].mIndexMin = indexMin;
942 mStreams[stream].mIndexMax = indexMax;
945 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
947 audio_devices_t device)
950 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
953 if (!audio_is_output_device(device)) {
957 // Force max volume if stream cannot be muted
958 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
960 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
961 stream, device, index);
963 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
964 // clear all device specific values
965 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
966 mStreams[stream].mIndexCur.clear();
968 mStreams[stream].mIndexCur.add(device, index);
970 // compute and apply stream volume on all outputs according to connected device
971 status_t status = NO_ERROR;
972 for (size_t i = 0; i < mOutputs.size(); i++) {
973 audio_devices_t curDevice =
974 getDeviceForVolume((audio_devices_t)mOutputs.valueAt(i)->device());
975 if (device == curDevice) {
976 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
977 if (volStatus != NO_ERROR) {
985 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
987 audio_devices_t device)
992 if (!audio_is_output_device(device)) {
995 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
996 // the strategy the stream belongs to.
997 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
998 device = (audio_devices_t)getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1000 device = getDeviceForVolume(device);
1002 *index = mStreams[stream].getVolumeIndex(device);
1003 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1007 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(effect_descriptor_t *desc)
1009 ALOGV("getOutputForEffect()");
1010 // apply simple rule where global effects are attached to the same output as MUSIC streams
1012 routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
1013 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1014 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device);
1016 for (size_t i = 0; i < dstOutputs.size(); i++) {
1017 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
1018 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1022 return dstOutputs[outIdx];
1025 status_t AudioPolicyManagerBase::registerEffect(effect_descriptor_t *desc,
1026 audio_io_handle_t io,
1031 ssize_t index = mOutputs.indexOfKey(io);
1033 index = mInputs.indexOfKey(io);
1035 ALOGW("registerEffect() unknown io %d", io);
1036 return INVALID_OPERATION;
1040 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1041 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1042 desc->name, desc->memoryUsage);
1043 return INVALID_OPERATION;
1045 mTotalEffectsMemory += desc->memoryUsage;
1046 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1047 desc->name, io, strategy, session, id);
1048 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1050 EffectDescriptor *pDesc = new EffectDescriptor();
1051 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1053 pDesc->mStrategy = (routing_strategy)strategy;
1054 pDesc->mSession = session;
1055 pDesc->mEnabled = false;
1057 mEffects.add(id, pDesc);
1062 status_t AudioPolicyManagerBase::unregisterEffect(int id)
1064 ssize_t index = mEffects.indexOfKey(id);
1066 ALOGW("unregisterEffect() unknown effect ID %d", id);
1067 return INVALID_OPERATION;
1070 EffectDescriptor *pDesc = mEffects.valueAt(index);
1072 setEffectEnabled(pDesc, false);
1074 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1075 ALOGW("unregisterEffect() memory %d too big for total %d",
1076 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1077 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1079 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1080 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1081 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1083 mEffects.removeItem(id);
1089 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1091 ssize_t index = mEffects.indexOfKey(id);
1093 ALOGW("unregisterEffect() unknown effect ID %d", id);
1094 return INVALID_OPERATION;
1097 return setEffectEnabled(mEffects.valueAt(index), enabled);
1100 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1102 if (enabled == pDesc->mEnabled) {
1103 ALOGV("setEffectEnabled(%s) effect already %s",
1104 enabled?"true":"false", enabled?"enabled":"disabled");
1105 return INVALID_OPERATION;
1109 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1110 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1111 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1112 return INVALID_OPERATION;
1114 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1115 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1117 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1118 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1119 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1120 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1122 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1123 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1125 pDesc->mEnabled = enabled;
1129 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1131 nsecs_t sysTime = systemTime();
1132 for (size_t i = 0; i < mOutputs.size(); i++) {
1133 if (mOutputs.valueAt(i)->mRefCount[stream] != 0 ||
1134 ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) {
1142 status_t AudioPolicyManagerBase::dump(int fd)
1144 const size_t SIZE = 256;
1148 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1149 result.append(buffer);
1151 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1152 result.append(buffer);
1153 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1154 result.append(buffer);
1155 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1156 result.append(buffer);
1157 snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbCardAndDevice.string());
1158 result.append(buffer);
1159 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1160 result.append(buffer);
1161 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1162 result.append(buffer);
1163 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1164 result.append(buffer);
1165 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1166 result.append(buffer);
1167 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1168 result.append(buffer);
1169 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1170 result.append(buffer);
1171 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1172 result.append(buffer);
1173 write(fd, result.string(), result.size());
1176 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1177 write(fd, buffer, strlen(buffer));
1178 for (size_t i = 0; i < mHwModules.size(); i++) {
1179 snprintf(buffer, SIZE, "- HW Module %d:\n", i + 1);
1180 write(fd, buffer, strlen(buffer));
1181 mHwModules[i]->dump(fd);
1184 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1185 write(fd, buffer, strlen(buffer));
1186 for (size_t i = 0; i < mOutputs.size(); i++) {
1187 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1188 write(fd, buffer, strlen(buffer));
1189 mOutputs.valueAt(i)->dump(fd);
1192 snprintf(buffer, SIZE, "\nInputs dump:\n");
1193 write(fd, buffer, strlen(buffer));
1194 for (size_t i = 0; i < mInputs.size(); i++) {
1195 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1196 write(fd, buffer, strlen(buffer));
1197 mInputs.valueAt(i)->dump(fd);
1200 snprintf(buffer, SIZE, "\nStreams dump:\n");
1201 write(fd, buffer, strlen(buffer));
1202 snprintf(buffer, SIZE,
1203 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1204 write(fd, buffer, strlen(buffer));
1205 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1206 snprintf(buffer, SIZE, " %02d ", i);
1207 write(fd, buffer, strlen(buffer));
1208 mStreams[i].dump(fd);
1211 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1212 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1213 write(fd, buffer, strlen(buffer));
1215 snprintf(buffer, SIZE, "Registered effects:\n");
1216 write(fd, buffer, strlen(buffer));
1217 for (size_t i = 0; i < mEffects.size(); i++) {
1218 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1219 write(fd, buffer, strlen(buffer));
1220 mEffects.valueAt(i)->dump(fd);
1227 // ----------------------------------------------------------------------------
1228 // AudioPolicyManagerBase
1229 // ----------------------------------------------------------------------------
1231 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1233 #ifdef AUDIO_POLICY_TEST
1235 #endif //AUDIO_POLICY_TEST
1236 mPrimaryOutput((audio_io_handle_t)0),
1237 mAvailableOutputDevices((audio_devices_t)0),
1238 mPhoneState(AudioSystem::MODE_NORMAL),
1239 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1240 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1241 mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false)
1243 mpClientInterface = clientInterface;
1245 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1246 mForceUse[i] = AudioSystem::FORCE_NONE;
1249 initializeVolumeCurves();
1251 mA2dpDeviceAddress = String8("");
1252 mScoDeviceAddress = String8("");
1253 mUsbCardAndDevice = String8("");
1255 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1256 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1257 ALOGE("could not load audio policy configuration file, setting defaults");
1258 defaultAudioPolicyConfig();
1262 // open all output streams needed to access attached devices
1263 for (size_t i = 0; i < mHwModules.size(); i++) {
1264 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1265 if (mHwModules[i]->mHandle == 0) {
1266 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1269 // open all output streams needed to access attached devices
1270 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1272 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1274 if (outProfile->mSupportedDevices & mAttachedOutputDevices) {
1275 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1276 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1277 outProfile->mSupportedDevices);
1278 audio_io_handle_t output = mpClientInterface->openOutput(
1279 outProfile->mModule->mHandle,
1280 &outputDesc->mDevice,
1281 &outputDesc->mSamplingRate,
1282 &outputDesc->mFormat,
1283 &outputDesc->mChannelMask,
1284 &outputDesc->mLatency,
1285 outputDesc->mFlags);
1289 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1290 (outProfile->mSupportedDevices & mAttachedOutputDevices));
1291 if (mPrimaryOutput == 0 &&
1292 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1293 mPrimaryOutput = output;
1295 addOutput(output, outputDesc);
1296 setOutputDevice(output,
1297 (audio_devices_t)(mDefaultOutputDevice &
1298 outProfile->mSupportedDevices),
1305 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1306 "Not output found for attached devices %08x",
1307 (mAttachedOutputDevices & ~mAvailableOutputDevices));
1309 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1311 updateDeviceForStrategy();
1313 #ifdef AUDIO_POLICY_TEST
1314 if (mPrimaryOutput != 0) {
1315 AudioParameter outputCmd = AudioParameter();
1316 outputCmd.addInt(String8("set_id"), 0);
1317 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1319 mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER;
1320 mTestSamplingRate = 44100;
1321 mTestFormat = AudioSystem::PCM_16_BIT;
1322 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1325 mDirectOutput = false;
1326 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1327 mTestOutputs[i] = 0;
1330 const size_t SIZE = 256;
1332 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1333 run(buffer, ANDROID_PRIORITY_AUDIO);
1335 #endif //AUDIO_POLICY_TEST
1338 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1340 #ifdef AUDIO_POLICY_TEST
1342 #endif //AUDIO_POLICY_TEST
1343 for (size_t i = 0; i < mOutputs.size(); i++) {
1344 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1345 delete mOutputs.valueAt(i);
1347 for (size_t i = 0; i < mInputs.size(); i++) {
1348 mpClientInterface->closeInput(mInputs.keyAt(i));
1349 delete mInputs.valueAt(i);
1351 for (size_t i = 0; i < mHwModules.size(); i++) {
1352 delete mHwModules[i];
1356 status_t AudioPolicyManagerBase::initCheck()
1358 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1361 #ifdef AUDIO_POLICY_TEST
1362 bool AudioPolicyManagerBase::threadLoop()
1364 ALOGV("entering threadLoop()");
1365 while (!exitPending())
1371 Mutex::Autolock _l(mLock);
1372 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1374 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1375 AudioParameter param = AudioParameter(command);
1377 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1379 ALOGV("Test command %s received", command.string());
1381 if (param.get(String8("target"), target) != NO_ERROR) {
1384 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1385 param.remove(String8("test_cmd_policy_output"));
1386 mCurOutput = valueInt;
1388 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1389 param.remove(String8("test_cmd_policy_direct"));
1390 if (value == "false") {
1391 mDirectOutput = false;
1392 } else if (value == "true") {
1393 mDirectOutput = true;
1396 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1397 param.remove(String8("test_cmd_policy_input"));
1398 mTestInput = valueInt;
1401 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1402 param.remove(String8("test_cmd_policy_format"));
1403 int format = AudioSystem::INVALID_FORMAT;
1404 if (value == "PCM 16 bits") {
1405 format = AudioSystem::PCM_16_BIT;
1406 } else if (value == "PCM 8 bits") {
1407 format = AudioSystem::PCM_8_BIT;
1408 } else if (value == "Compressed MP3") {
1409 format = AudioSystem::MP3;
1411 if (format != AudioSystem::INVALID_FORMAT) {
1412 if (target == "Manager") {
1413 mTestFormat = format;
1414 } else if (mTestOutputs[mCurOutput] != 0) {
1415 AudioParameter outputParam = AudioParameter();
1416 outputParam.addInt(String8("format"), format);
1417 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1421 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1422 param.remove(String8("test_cmd_policy_channels"));
1425 if (value == "Channels Stereo") {
1426 channels = AudioSystem::CHANNEL_OUT_STEREO;
1427 } else if (value == "Channels Mono") {
1428 channels = AudioSystem::CHANNEL_OUT_MONO;
1430 if (channels != 0) {
1431 if (target == "Manager") {
1432 mTestChannels = channels;
1433 } else if (mTestOutputs[mCurOutput] != 0) {
1434 AudioParameter outputParam = AudioParameter();
1435 outputParam.addInt(String8("channels"), channels);
1436 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1440 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1441 param.remove(String8("test_cmd_policy_sampleRate"));
1442 if (valueInt >= 0 && valueInt <= 96000) {
1443 int samplingRate = valueInt;
1444 if (target == "Manager") {
1445 mTestSamplingRate = samplingRate;
1446 } else if (mTestOutputs[mCurOutput] != 0) {
1447 AudioParameter outputParam = AudioParameter();
1448 outputParam.addInt(String8("sampling_rate"), samplingRate);
1449 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1454 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1455 param.remove(String8("test_cmd_policy_reopen"));
1457 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1458 mpClientInterface->closeOutput(mPrimaryOutput);
1460 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1462 delete mOutputs.valueFor(mPrimaryOutput);
1463 mOutputs.removeItem(mPrimaryOutput);
1465 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1466 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1467 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1468 &outputDesc->mDevice,
1469 &outputDesc->mSamplingRate,
1470 &outputDesc->mFormat,
1471 &outputDesc->mChannelMask,
1472 &outputDesc->mLatency,
1473 outputDesc->mFlags);
1474 if (mPrimaryOutput == 0) {
1475 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1476 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1478 AudioParameter outputCmd = AudioParameter();
1479 outputCmd.addInt(String8("set_id"), 0);
1480 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1481 addOutput(mPrimaryOutput, outputDesc);
1486 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1492 void AudioPolicyManagerBase::exit()
1495 AutoMutex _l(mLock);
1497 mWaitWorkCV.signal();
1499 requestExitAndWait();
1502 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1504 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1505 if (output == mTestOutputs[i]) return i;
1509 #endif //AUDIO_POLICY_TEST
1513 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1515 outputDesc->mId = id;
1516 mOutputs.add(id, outputDesc);
1520 status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
1521 AudioSystem::device_connection_state state,
1522 SortedVector<audio_io_handle_t>& outputs)
1524 AudioOutputDescriptor *desc;
1526 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1527 // first list already open outputs that can be routed to this device
1528 for (size_t i = 0; i < mOutputs.size(); i++) {
1529 desc = mOutputs.valueAt(i);
1530 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
1531 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
1532 outputs.add(mOutputs.keyAt(i));
1535 // then look for output profiles that can be routed to this device
1536 SortedVector<IOProfile *> profiles;
1537 for (size_t i = 0; i < mHwModules.size(); i++)
1539 if (mHwModules[i]->mHandle == 0) {
1542 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1544 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1545 ALOGV("checkOutputsForDevice(): adding profile %d from module %d", j, i);
1546 profiles.add(mHwModules[i]->mOutputProfiles[j]);
1551 if (profiles.isEmpty() && outputs.isEmpty()) {
1552 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1556 // open outputs for matching profiles if needed. Direct outputs are also opened to
1557 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
1558 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
1559 IOProfile *profile = profiles[profile_index];
1561 // nothing to do if one output is already opened for this profile
1563 for (j = 0; j < outputs.size(); j++) {
1564 desc = mOutputs.valueAt(j);
1565 if (!desc->isDuplicated() && desc->mProfile == profile) {
1569 if (j != outputs.size()) {
1573 ALOGV("opening output for device %08x", device);
1574 desc = new AudioOutputDescriptor(profile);
1575 desc->mDevice = device;
1576 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
1578 &desc->mSamplingRate,
1580 &desc->mChannelMask,
1584 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1587 if (profile->mSamplingRates[0] == 0) {
1588 reply = mpClientInterface->getParameters(output,
1589 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
1590 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
1592 value = strpbrk((char *)reply.string(), "=");
1593 if (value != NULL) {
1594 loadSamplingRates(value, profile);
1597 if (profile->mFormats[0] == 0) {
1598 reply = mpClientInterface->getParameters(output,
1599 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
1600 ALOGV("checkOutputsForDevice() direct output sup formats %s",
1602 value = strpbrk((char *)reply.string(), "=");
1603 if (value != NULL) {
1604 loadFormats(value, profile);
1607 if (profile->mChannelMasks[0] == 0) {
1608 reply = mpClientInterface->getParameters(output,
1609 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
1610 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
1612 value = strpbrk((char *)reply.string(), "=");
1613 if (value != NULL) {
1614 loadOutChannels(value + 1, profile);
1617 if (((profile->mSamplingRates[0] == 0) &&
1618 (profile->mSamplingRates.size() < 2)) ||
1619 ((profile->mFormats[0] == 0) &&
1620 (profile->mFormats.size() < 2)) ||
1621 ((profile->mFormats[0] == 0) &&
1622 (profile->mChannelMasks.size() < 2))) {
1623 ALOGW("checkOutputsForDevice() direct output missing param");
1626 addOutput(output, desc);
1629 audio_io_handle_t duplicatedOutput = 0;
1630 // add output descriptor
1631 addOutput(output, desc);
1632 // set initial stream volume for device
1633 applyStreamVolumes(output, device);
1635 //TODO: configure audio effect output stage here
1637 // open a duplicating output thread for the new output and the primary output
1638 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
1640 if (duplicatedOutput != 0) {
1641 // add duplicated output descriptor
1642 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1643 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1644 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1645 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
1646 dupOutputDesc->mFormat = desc->mFormat;
1647 dupOutputDesc->mChannelMask = desc->mChannelMask;
1648 dupOutputDesc->mLatency = desc->mLatency;
1649 addOutput(duplicatedOutput, dupOutputDesc);
1650 applyStreamVolumes(duplicatedOutput, device);
1652 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
1653 mPrimaryOutput, output);
1654 mpClientInterface->closeOutput(output);
1655 mOutputs.removeItem(output);
1661 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
1663 profiles.removeAt(profile_index);
1666 outputs.add(output);
1667 ALOGV("checkOutputsForDevice(): adding output %d", output);
1671 if (profiles.isEmpty()) {
1672 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1676 // check if one opened output is not needed any more after disconnecting one device
1677 for (size_t i = 0; i < mOutputs.size(); i++) {
1678 desc = mOutputs.valueAt(i);
1679 if (!desc->isDuplicated() &&
1680 !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
1681 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
1682 outputs.add(mOutputs.keyAt(i));
1685 for (size_t i = 0; i < mHwModules.size(); i++)
1687 if (mHwModules[i]->mHandle == 0) {
1690 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1692 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
1693 if ((profile->mSupportedDevices & device) &&
1694 (profile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1695 ALOGV("checkOutputsForDevice(): clearing direct output profile %d on module %d",
1697 if (profile->mSamplingRates[0] == 0) {
1698 profile->mSamplingRates.clear();
1699 profile->mSamplingRates.add(0);
1701 if (profile->mFormats[0] == 0) {
1702 profile->mFormats.clear();
1703 profile->mFormats.add((audio_format_t)0);
1705 if (profile->mChannelMasks[0] == 0) {
1706 profile->mChannelMasks.clear();
1707 profile->mChannelMasks.add((audio_channel_mask_t)0);
1716 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
1718 ALOGV("closeOutput(%d)", output);
1720 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1721 if (outputDesc == NULL) {
1722 ALOGW("closeOutput() unknown output %d", output);
1726 // look for duplicated outputs connected to the output being removed.
1727 for (size_t i = 0; i < mOutputs.size(); i++) {
1728 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
1729 if (dupOutputDesc->isDuplicated() &&
1730 (dupOutputDesc->mOutput1 == outputDesc ||
1731 dupOutputDesc->mOutput2 == outputDesc)) {
1732 AudioOutputDescriptor *outputDesc2;
1733 if (dupOutputDesc->mOutput1 == outputDesc) {
1734 outputDesc2 = dupOutputDesc->mOutput2;
1736 outputDesc2 = dupOutputDesc->mOutput1;
1738 // As all active tracks on duplicated output will be deleted,
1739 // and as they were also referenced on the other output, the reference
1740 // count for their stream type must be adjusted accordingly on
1741 // the other output.
1742 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
1743 int refCount = dupOutputDesc->mRefCount[j];
1744 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
1746 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
1747 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
1749 mpClientInterface->closeOutput(duplicatedOutput);
1750 delete mOutputs.valueFor(duplicatedOutput);
1751 mOutputs.removeItem(duplicatedOutput);
1755 AudioParameter param;
1756 param.add(String8("closing"), String8("true"));
1757 mpClientInterface->setParameters(output, param.toString());
1759 mpClientInterface->closeOutput(output);
1760 delete mOutputs.valueFor(output);
1761 mOutputs.removeItem(output);
1764 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device)
1766 SortedVector<audio_io_handle_t> outputs;
1768 ALOGVV("getOutputsForDevice() device %04x", device);
1769 for (size_t i = 0; i < mOutputs.size(); i++) {
1770 ALOGVV("output %d isDuplicated=%d device=%04x",
1771 i, mOutputs.valueAt(i)->isDuplicated(), mOutputs.valueAt(i)->supportedDevices());
1772 if ((device & mOutputs.valueAt(i)->supportedDevices()) == device) {
1773 ALOGVV("getOutputsForDevice() found output %d", mOutputs.keyAt(i));
1774 outputs.add(mOutputs.keyAt(i));
1780 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
1781 SortedVector<audio_io_handle_t>& outputs2)
1783 if (outputs1.size() != outputs2.size()) {
1786 for (size_t i = 0; i < outputs1.size(); i++) {
1787 if (outputs1[i] != outputs2[i]) {
1794 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
1796 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
1797 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
1798 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice);
1799 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice);
1801 if (!vectorsEqual(srcOutputs,dstOutputs)) {
1802 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
1803 strategy, srcOutputs[0], dstOutputs[0]);
1804 // mute strategy while moving tracks from one output to another
1805 for (size_t i = 0; i < srcOutputs.size(); i++) {
1806 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
1807 if (desc->strategyRefCount(strategy) != 0) {
1808 setStrategyMute(strategy, true, srcOutputs[i]);
1809 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
1813 // Move effects associated to this strategy from previous output to new output
1814 if (strategy == STRATEGY_MEDIA) {
1816 for (size_t i = 0; i < dstOutputs.size(); i++) {
1817 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
1818 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1822 SortedVector<audio_io_handle_t> moved;
1823 for (size_t i = 0; i < mEffects.size(); i++) {
1824 EffectDescriptor *desc = mEffects.valueAt(i);
1825 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
1826 desc->mIo != dstOutputs[outIdx]) {
1827 if (moved.indexOf(desc->mIo) < 0) {
1828 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
1829 mEffects.keyAt(i), dstOutputs[outIdx]);
1830 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
1831 dstOutputs[outIdx]);
1832 moved.add(desc->mIo);
1834 desc->mIo = dstOutputs[outIdx];
1838 // Move tracks associated to this strategy from previous output to new output
1839 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1840 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1841 //FIXME see fixme on name change
1842 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i,
1843 dstOutputs[0] /* ignored */);
1849 void AudioPolicyManagerBase::checkOutputForAllStrategies()
1851 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
1852 checkOutputForStrategy(STRATEGY_PHONE);
1853 checkOutputForStrategy(STRATEGY_SONIFICATION);
1854 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
1855 checkOutputForStrategy(STRATEGY_MEDIA);
1856 checkOutputForStrategy(STRATEGY_DTMF);
1859 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
1865 for (size_t i = 0; i < mOutputs.size(); i++) {
1866 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1867 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
1868 return mOutputs.keyAt(i);
1875 void AudioPolicyManagerBase::checkA2dpSuspend()
1880 audio_io_handle_t a2dpOutput = getA2dpOutput();
1881 if (a2dpOutput == 0) {
1885 // suspend A2DP output if:
1886 // (NOT already suspended) &&
1887 // ((SCO device is connected &&
1888 // (forced usage for communication || for record is SCO))) ||
1889 // (phone state is ringing || in call)
1891 // restore A2DP output if:
1892 // (Already suspended) &&
1893 // ((SCO device is NOT connected ||
1894 // (forced usage NOT for communication && NOT for record is SCO))) &&
1895 // (phone state is NOT ringing && NOT in call)
1897 if (mA2dpSuspended) {
1898 if (((mScoDeviceAddress == "") ||
1899 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1900 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1901 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1902 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1904 mpClientInterface->restoreOutput(a2dpOutput);
1905 mA2dpSuspended = false;
1908 if (((mScoDeviceAddress != "") &&
1909 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1910 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
1911 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
1912 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
1914 mpClientInterface->suspendOutput(a2dpOutput);
1915 mA2dpSuspended = true;
1920 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1922 audio_devices_t device = (audio_devices_t)0;
1924 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1925 // check the following by order of priority to request a routing change if necessary:
1926 // 1: the strategy enforced audible is active on the output:
1927 // use device for strategy enforced audible
1928 // 2: we are in call or the strategy phone is active on the output:
1929 // use device for strategy phone
1930 // 3: the strategy sonification is active on the output:
1931 // use device for strategy sonification
1932 // 4: the strategy "respectful" sonification is active on the output:
1933 // use device for strategy "respectful" sonification
1934 // 5: the strategy media is active on the output:
1935 // use device for strategy media
1936 // 6: the strategy DTMF is active on the output:
1937 // use device for strategy DTMF
1938 if (outputDesc->isUsedByStrategy(STRATEGY_ENFORCED_AUDIBLE)) {
1939 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
1940 } else if (isInCall() ||
1941 outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1942 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
1943 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
1944 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
1945 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION_RESPECTFUL)) {
1946 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
1947 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
1948 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
1949 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
1950 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
1953 ALOGV("getNewDevice() selected device %x", device);
1957 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
1958 return (uint32_t)getStrategy(stream);
1961 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
1962 audio_devices_t devices;
1963 // By checking the range of stream before calling getStrategy, we avoid
1964 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
1965 // and then return STRATEGY_MEDIA, but we want to return the empty set.
1966 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
1967 devices = (audio_devices_t)0;
1969 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
1970 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
1975 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
1976 AudioSystem::stream_type stream) {
1977 // stream to strategy mapping
1979 case AudioSystem::VOICE_CALL:
1980 case AudioSystem::BLUETOOTH_SCO:
1981 return STRATEGY_PHONE;
1982 case AudioSystem::RING:
1983 case AudioSystem::ALARM:
1984 return STRATEGY_SONIFICATION;
1985 case AudioSystem::NOTIFICATION:
1986 return STRATEGY_SONIFICATION_RESPECTFUL;
1987 case AudioSystem::DTMF:
1988 return STRATEGY_DTMF;
1990 ALOGE("unknown stream type");
1991 case AudioSystem::SYSTEM:
1992 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
1993 // while key clicks are played produces a poor result
1994 case AudioSystem::TTS:
1995 case AudioSystem::MUSIC:
1996 return STRATEGY_MEDIA;
1997 case AudioSystem::ENFORCED_AUDIBLE:
1998 return STRATEGY_ENFORCED_AUDIBLE;
2002 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2004 case AudioSystem::MUSIC:
2005 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2006 updateDeviceForStrategy();
2013 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2016 uint32_t device = 0;
2019 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2020 strategy, mDeviceForStrategy[strategy]);
2021 return mDeviceForStrategy[strategy];
2026 case STRATEGY_SONIFICATION_RESPECTFUL:
2028 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2029 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2030 // while media is playing (or has recently played), use the same device
2031 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2033 // when media is not playing anymore, fall back on the sonification behavior
2034 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2041 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2042 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2045 // when in call, DTMF and PHONE strategies follow the same rules
2048 case STRATEGY_PHONE:
2049 // for phone strategy, we first consider the forced use and then the available devices by order
2051 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2052 case AudioSystem::FORCE_BT_SCO:
2053 if (!isInCall() || strategy != STRATEGY_DTMF) {
2054 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2057 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2059 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
2061 // if SCO device is requested but no SCO device is available, fall back to default case
2064 default: // FORCE_NONE
2065 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2066 if (mHasA2dp && !isInCall() &&
2067 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2068 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2069 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
2071 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2074 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
2076 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
2078 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2080 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2082 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
2084 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
2086 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
2088 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
2090 device = mDefaultOutputDevice;
2092 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2096 case AudioSystem::FORCE_SPEAKER:
2097 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2098 // A2DP speaker when forcing to speaker output
2099 if (mHasA2dp && !isInCall() &&
2100 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2101 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2102 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2105 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2107 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2109 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
2111 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
2113 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
2115 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
2117 device = mDefaultOutputDevice;
2119 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2125 case STRATEGY_SONIFICATION:
2127 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2128 // handleIncallSonification().
2130 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2135 case STRATEGY_ENFORCED_AUDIBLE:
2136 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2138 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2139 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2141 if (strategy == STRATEGY_SONIFICATION ||
2142 !mStreams[AUDIO_STREAM_ENFORCED_AUDIBLE].mCanBeMuted) {
2143 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
2145 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2148 // The second device used for sonification is the same as the device used by media strategy
2151 case STRATEGY_MEDIA: {
2152 uint32_t device2 = 0;
2153 if (mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2154 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2155 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
2157 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2160 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2164 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
2167 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
2170 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2173 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2176 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
2179 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
2182 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
2185 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
2188 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2189 // STRATEGY_ENFORCED_AUDIBLE, 0 otherwise
2192 device = mDefaultOutputDevice;
2194 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2199 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2203 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2204 return (audio_devices_t)device;
2207 void AudioPolicyManagerBase::updateDeviceForStrategy()
2209 for (int i = 0; i < NUM_STRATEGIES; i++) {
2210 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2214 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2215 audio_devices_t prevDevice,
2218 // mute/unmute strategies using an incompatible device combination
2219 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2220 // if unmuting, unmute only after the specified delay
2221 if (outputDesc->isDuplicated()) {
2225 uint32_t muteWaitMs = 0;
2226 audio_devices_t device = outputDesc->device();
2227 bool shouldMute = (outputDesc->refCount() != 0) &&
2228 (AudioSystem::popCount(device) >= 2);
2229 // temporary mute output if device selection changes to avoid volume bursts due to
2230 // different per device volumes
2231 bool tempMute = (outputDesc->refCount() != 0) && (device != prevDevice);
2233 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2234 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2235 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2236 bool doMute = false;
2238 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2240 outputDesc->mStrategyMutedByDevice[i] = true;
2241 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2243 outputDesc->mStrategyMutedByDevice[i] = false;
2245 if (doMute || tempMute) {
2246 for (size_t j = 0; j < mOutputs.size(); j++) {
2247 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2248 if ((desc->supportedDevices() & outputDesc->supportedDevices()) == 0) {
2251 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2252 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2253 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2254 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2255 if (desc->strategyRefCount((routing_strategy)i) != 0) {
2257 setStrategyMute((routing_strategy)i, true, curOutput);
2258 setStrategyMute((routing_strategy)i, false, curOutput,
2259 desc->latency() * 2, device);
2261 if (tempMute || mute) {
2262 if (muteWaitMs < desc->latency()) {
2263 muteWaitMs = desc->latency();
2271 // FIXME: should not need to double latency if volume could be applied immediately by the
2272 // audioflinger mixer. We must account for the delay between now and the next time
2273 // the audioflinger thread for this output will process a buffer (which corresponds to
2274 // one buffer size, usually 1/2 or 1/4 of the latency).
2276 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2277 if (muteWaitMs > delayMs) {
2278 muteWaitMs -= delayMs;
2279 usleep(muteWaitMs * 1000);
2285 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2286 audio_devices_t device,
2290 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2291 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2292 AudioParameter param;
2293 uint32_t muteWaitMs = 0;
2295 if (outputDesc->isDuplicated()) {
2296 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2297 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2300 // filter devices according to output selected
2301 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2303 audio_devices_t prevDevice = outputDesc->mDevice;
2305 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2308 outputDesc->mDevice = device;
2310 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2312 // Do not change the routing if:
2313 // - the requested device is 0
2314 // - the requested device is the same as current device and force is not specified.
2315 // Doing this check here allows the caller to call setOutputDevice() without conditions
2316 if ((device == 0 || device == prevDevice) && !force) {
2317 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2321 ALOGV("setOutputDevice() changing device");
2323 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2324 mpClientInterface->setParameters(output, param.toString(), delayMs);
2326 // update stream volumes according to new device
2327 applyStreamVolumes(output, device, delayMs);
2332 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2333 uint32_t samplingRate,
2335 uint32_t channelMask)
2337 // Choose an input profile based on the requested capture parameters: select the first available
2338 // profile supporting all requested parameters.
2340 for (size_t i = 0; i < mHwModules.size(); i++)
2342 if (mHwModules[i]->mHandle == 0) {
2345 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2347 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2348 if (profile->isCompatibleProfile(device, samplingRate, format,
2349 channelMask,(audio_output_flags_t)0)) {
2357 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2359 uint32_t device = 0;
2361 switch(inputSource) {
2362 case AUDIO_SOURCE_DEFAULT:
2363 case AUDIO_SOURCE_MIC:
2364 case AUDIO_SOURCE_VOICE_RECOGNITION:
2365 case AUDIO_SOURCE_VOICE_COMMUNICATION:
2366 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2367 mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2368 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2369 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
2370 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
2371 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BUILTIN_MIC) {
2372 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
2375 case AUDIO_SOURCE_CAMCORDER:
2376 if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BACK_MIC) {
2377 device = AudioSystem::DEVICE_IN_BACK_MIC;
2378 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BUILTIN_MIC) {
2379 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
2382 case AUDIO_SOURCE_VOICE_UPLINK:
2383 case AUDIO_SOURCE_VOICE_DOWNLINK:
2384 case AUDIO_SOURCE_VOICE_CALL:
2385 if (mAvailableInputDevices & AudioSystem::DEVICE_IN_VOICE_CALL) {
2386 device = AudioSystem::DEVICE_IN_VOICE_CALL;
2390 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2393 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2394 return (audio_devices_t)device;
2397 audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
2399 for (size_t i = 0; i < mInputs.size(); i++) {
2400 if (mInputs.valueAt(i)->mRefCount > 0) {
2401 return mInputs.keyAt(i);
2408 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2411 // this happens when forcing a route update and no track is active on an output.
2412 // In this case the returned category is not important.
2413 device = AUDIO_DEVICE_OUT_SPEAKER;
2414 } else if (AudioSystem::popCount(device) > 1) {
2415 // Multiple device selection is either:
2416 // - speaker + one other device: give priority to speaker in this case.
2417 // - one A2DP device + another device: happens with duplicated output. In this case
2418 // retain the device on the A2DP output as the other must not correspond to an active
2419 // selection if not the speaker.
2420 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2421 device = AUDIO_DEVICE_OUT_SPEAKER;
2423 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2427 ALOGW_IF(AudioSystem::popCount(device) != 1,
2428 "getDeviceForVolume() invalid device combination: %08x",
2434 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
2436 switch(getDeviceForVolume(device)) {
2437 case AUDIO_DEVICE_OUT_EARPIECE:
2438 return DEVICE_CATEGORY_EARPIECE;
2439 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
2440 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
2441 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
2442 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
2443 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
2444 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
2445 return DEVICE_CATEGORY_HEADSET;
2446 case AUDIO_DEVICE_OUT_SPEAKER:
2447 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
2448 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
2449 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
2450 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
2451 case AUDIO_DEVICE_OUT_USB_DEVICE:
2453 return DEVICE_CATEGORY_SPEAKER;
2457 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
2460 device_category deviceCategory = getDeviceCategory(device);
2461 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
2463 // the volume index in the UI is relative to the min and max volume indices for this stream type
2464 int nbSteps = 1 + curve[VOLMAX].mIndex -
2465 curve[VOLMIN].mIndex;
2466 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
2467 (streamDesc.mIndexMax - streamDesc.mIndexMin);
2469 // find what part of the curve this index volume belongs to, or if it's out of bounds
2471 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
2473 } else if (volIdx < curve[VOLKNEE1].mIndex) {
2475 } else if (volIdx < curve[VOLKNEE2].mIndex) {
2477 } else if (volIdx <= curve[VOLMAX].mIndex) {
2479 } else { // out of bounds
2483 // linear interpolation in the attenuation table in dB
2484 float decibels = curve[segment].mDBAttenuation +
2485 ((float)(volIdx - curve[segment].mIndex)) *
2486 ( (curve[segment+1].mDBAttenuation -
2487 curve[segment].mDBAttenuation) /
2488 ((float)(curve[segment+1].mIndex -
2489 curve[segment].mIndex)) );
2491 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
2493 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
2494 curve[segment].mIndex, volIdx,
2495 curve[segment+1].mIndex,
2496 curve[segment].mDBAttenuation,
2498 curve[segment+1].mDBAttenuation,
2501 return amplification;
2504 const AudioPolicyManagerBase::VolumeCurvePoint
2505 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2506 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
2509 const AudioPolicyManagerBase::VolumeCurvePoint
2510 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2511 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
2514 const AudioPolicyManagerBase::VolumeCurvePoint
2515 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2516 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2519 const AudioPolicyManagerBase::VolumeCurvePoint
2520 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2521 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2524 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
2525 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets (See AudioService.java).
2526 // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
2527 const AudioPolicyManagerBase::VolumeCurvePoint
2528 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2529 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
2532 const AudioPolicyManagerBase::VolumeCurvePoint
2533 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2534 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
2537 const AudioPolicyManagerBase::VolumeCurvePoint
2538 *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT]
2539 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2540 { // AUDIO_STREAM_VOICE_CALL
2541 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2542 sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2543 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2545 { // AUDIO_STREAM_SYSTEM
2546 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2547 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2548 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2550 { // AUDIO_STREAM_RING
2551 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2552 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2553 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2555 { // AUDIO_STREAM_MUSIC
2556 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2557 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2558 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2560 { // AUDIO_STREAM_ALARM
2561 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2562 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2563 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2565 { // AUDIO_STREAM_NOTIFICATION
2566 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2567 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2568 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2570 { // AUDIO_STREAM_BLUETOOTH_SCO
2571 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2572 sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2573 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2575 { // AUDIO_STREAM_ENFORCED_AUDIBLE
2576 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2577 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2578 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2580 { // AUDIO_STREAM_DTMF
2581 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2582 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2583 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2585 { // AUDIO_STREAM_TTS
2586 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2587 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2588 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2592 void AudioPolicyManagerBase::initializeVolumeCurves()
2594 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2595 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2596 mStreams[i].mVolumeCurve[j] =
2597 sVolumeProfiles[i][j];
2602 float AudioPolicyManagerBase::computeVolume(int stream,
2604 audio_io_handle_t output,
2605 audio_devices_t device)
2608 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2609 StreamDescriptor &streamDesc = mStreams[stream];
2612 device = outputDesc->device();
2615 // if volume is not 0 (not muted), force media volume to max on digital output
2616 if (stream == AudioSystem::MUSIC &&
2617 index != mStreams[stream].mIndexMin &&
2618 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
2619 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
2620 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
2621 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
2625 volume = volIndexToAmpl(device, streamDesc, index);
2627 // if a headset is connected, apply the following rules to ring tones and notifications
2628 // to avoid sound level bursts in user's ears:
2629 // - always attenuate ring tones and notifications volume by 6dB
2630 // - if music is playing, always limit the volume to current music volume,
2631 // with a minimum threshold at -36dB so that notification is always perceived.
2632 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2633 if ((device & (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
2634 AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
2635 AudioSystem::DEVICE_OUT_WIRED_HEADSET |
2636 AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) &&
2637 ((stream_strategy == STRATEGY_SONIFICATION)
2638 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
2639 || (stream == AudioSystem::SYSTEM)) &&
2640 streamDesc.mCanBeMuted) {
2641 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
2642 // when the phone is ringing we must consider that music could have been paused just before
2643 // by the music application and behave as if music was active if the last music track was
2645 if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
2646 mLimitRingtoneVolume) {
2647 float musicVol = computeVolume(AudioSystem::MUSIC,
2648 mStreams[AudioSystem::MUSIC].getVolumeIndex(device),
2651 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
2652 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
2653 if (volume > minVol) {
2655 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
2663 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
2665 audio_io_handle_t output,
2666 audio_devices_t device,
2671 // do not change actual stream volume if the stream is muted
2672 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
2673 ALOGVV("checkAndSetVolume() stream %d muted count %d",
2674 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
2678 // do not change in call volume if bluetooth is connected and vice versa
2679 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2680 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
2681 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
2682 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
2683 return INVALID_OPERATION;
2686 float volume = computeVolume(stream, index, output, device);
2687 // We actually change the volume if:
2688 // - the float value returned by computeVolume() changed
2689 // - the force flag is set
2690 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
2692 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
2693 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
2694 if (stream == AudioSystem::VOICE_CALL ||
2695 stream == AudioSystem::DTMF ||
2696 stream == AudioSystem::BLUETOOTH_SCO) {
2697 // offset value to reflect actual hardware volume that never reaches 0
2698 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
2699 volume = 0.01 + 0.99 * volume;
2700 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
2702 if (stream == AudioSystem::BLUETOOTH_SCO) {
2703 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
2707 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
2710 if (stream == AudioSystem::VOICE_CALL ||
2711 stream == AudioSystem::BLUETOOTH_SCO) {
2713 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
2714 if (stream == AudioSystem::VOICE_CALL) {
2715 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
2720 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
2721 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
2722 mLastVoiceVolume = voiceVolume;
2729 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
2730 audio_devices_t device,
2734 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
2736 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2737 checkAndSetVolume(stream,
2738 mStreams[stream].getVolumeIndex(device),
2746 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
2748 audio_io_handle_t output,
2750 audio_devices_t device)
2752 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
2753 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2754 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
2755 setStreamMute(stream, on, output, delayMs, device);
2760 void AudioPolicyManagerBase::setStreamMute(int stream,
2762 audio_io_handle_t output,
2764 audio_devices_t device)
2766 StreamDescriptor &streamDesc = mStreams[stream];
2767 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2769 device = outputDesc->device();
2772 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
2773 stream, on, output, outputDesc->mMuteCount[stream], device);
2776 if (outputDesc->mMuteCount[stream] == 0) {
2777 if (streamDesc.mCanBeMuted) {
2778 checkAndSetVolume(stream, 0, output, device, delayMs);
2781 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
2782 outputDesc->mMuteCount[stream]++;
2784 if (outputDesc->mMuteCount[stream] == 0) {
2785 ALOGV("setStreamMute() unmuting non muted stream!");
2788 if (--outputDesc->mMuteCount[stream] == 0) {
2789 checkAndSetVolume(stream,
2790 streamDesc.getVolumeIndex((audio_devices_t)device),
2798 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
2800 // if the stream pertains to sonification strategy and we are in call we must
2801 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
2802 // in the device used for phone strategy and play the tone if the selected device does not
2803 // interfere with the device used for phone strategy
2804 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
2805 // many times as there are active tracks on the output
2806 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2807 if ((stream_strategy == STRATEGY_SONIFICATION) ||
2808 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
2809 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
2810 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
2811 stream, starting, outputDesc->mDevice, stateChange);
2812 if (outputDesc->mRefCount[stream]) {
2815 muteCount = outputDesc->mRefCount[stream];
2817 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
2818 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
2819 for (int i = 0; i < muteCount; i++) {
2820 setStreamMute(stream, starting, mPrimaryOutput);
2823 ALOGV("handleIncallSonification() high visibility");
2824 if (outputDesc->device() &
2825 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
2826 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
2827 for (int i = 0; i < muteCount; i++) {
2828 setStreamMute(stream, starting, mPrimaryOutput);
2832 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2834 mpClientInterface->stopTone();
2841 bool AudioPolicyManagerBase::isInCall()
2843 return isStateInCall(mPhoneState);
2846 bool AudioPolicyManagerBase::isStateInCall(int state) {
2847 return ((state == AudioSystem::MODE_IN_CALL) ||
2848 (state == AudioSystem::MODE_IN_COMMUNICATION));
2851 bool AudioPolicyManagerBase::needsDirectOuput(audio_stream_type_t stream,
2852 uint32_t samplingRate,
2853 audio_format_t format,
2854 audio_channel_mask_t channelMask,
2855 audio_output_flags_t flags,
2856 audio_devices_t device)
2858 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
2859 (format != 0 && !AudioSystem::isLinearPCM(format)));
2862 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
2864 return MAX_EFFECTS_CPU_LOAD;
2867 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
2869 return MAX_EFFECTS_MEMORY;
2872 // --- AudioOutputDescriptor class implementation
2874 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
2875 const IOProfile *profile)
2876 : mId(0), mSamplingRate(0), mFormat((audio_format_t)0),
2877 mChannelMask((audio_channel_mask_t)0), mLatency(0),
2878 mFlags((audio_output_flags_t)0), mDevice((audio_devices_t)0),
2879 mOutput1(0), mOutput2(0), mProfile(profile)
2881 // clear usage count for all stream types
2882 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2884 mCurVolume[i] = -1.0;
2888 if (profile != NULL) {
2889 mSamplingRate = profile->mSamplingRates[0];
2890 mFormat = profile->mFormats[0];
2891 mChannelMask = profile->mChannelMasks[0];
2892 mFlags = profile->mFlags;
2896 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
2898 if (isDuplicated()) {
2899 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
2905 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
2907 if (isDuplicated()) {
2908 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
2914 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
2915 const AudioOutputDescriptor *outputDesc)
2917 if (isDuplicated()) {
2918 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
2919 } else if (outputDesc->isDuplicated()){
2920 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
2922 return (mProfile->mModule == outputDesc->mProfile->mModule);
2926 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
2928 // forward usage count change to attached outputs
2929 if (isDuplicated()) {
2930 mOutput1->changeRefCount(stream, delta);
2931 mOutput2->changeRefCount(stream, delta);
2933 if ((delta + (int)mRefCount[stream]) < 0) {
2934 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
2935 mRefCount[stream] = 0;
2938 mRefCount[stream] += delta;
2939 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
2942 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
2944 uint32_t refcount = 0;
2945 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2946 refcount += mRefCount[i];
2951 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
2953 uint32_t refCount = 0;
2954 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2955 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2956 refCount += mRefCount[i];
2962 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
2964 if (isDuplicated()) {
2965 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
2967 return mProfile->mSupportedDevices ;
2971 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
2973 const size_t SIZE = 256;
2977 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2978 result.append(buffer);
2979 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2980 result.append(buffer);
2981 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
2982 result.append(buffer);
2983 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
2984 result.append(buffer);
2985 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
2986 result.append(buffer);
2987 snprintf(buffer, SIZE, " Devices %08x\n", device());
2988 result.append(buffer);
2989 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
2990 result.append(buffer);
2991 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2992 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
2993 result.append(buffer);
2995 write(fd, result.string(), result.size());
3000 // --- AudioInputDescriptor class implementation
3002 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3003 : mSamplingRate(0), mFormat((audio_format_t)0), mChannelMask((audio_channel_mask_t)0),
3004 mDevice((audio_devices_t)0), mRefCount(0),
3005 mInputSource(0), mProfile(profile)
3009 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3011 const size_t SIZE = 256;
3015 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3016 result.append(buffer);
3017 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3018 result.append(buffer);
3019 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3020 result.append(buffer);
3021 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3022 result.append(buffer);
3023 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3024 result.append(buffer);
3025 write(fd, result.string(), result.size());
3030 // --- StreamDescriptor class implementation
3032 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3033 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3035 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3038 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3040 device = AudioPolicyManagerBase::getDeviceForVolume(device);
3041 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3042 if (mIndexCur.indexOfKey(device) < 0) {
3043 device = AUDIO_DEVICE_OUT_DEFAULT;
3045 return mIndexCur.valueFor(device);
3048 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3050 const size_t SIZE = 256;
3054 snprintf(buffer, SIZE, "%s %02d %02d ",
3055 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3056 result.append(buffer);
3057 for (size_t i = 0; i < mIndexCur.size(); i++) {
3058 snprintf(buffer, SIZE, "%04x : %02d, ",
3060 mIndexCur.valueAt(i));
3061 result.append(buffer);
3063 result.append("\n");
3065 write(fd, result.string(), result.size());
3068 // --- EffectDescriptor class implementation
3070 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3072 const size_t SIZE = 256;
3076 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3077 result.append(buffer);
3078 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3079 result.append(buffer);
3080 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3081 result.append(buffer);
3082 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3083 result.append(buffer);
3084 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3085 result.append(buffer);
3086 write(fd, result.string(), result.size());
3091 // --- IOProfile class implementation
3093 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3094 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3098 AudioPolicyManagerBase::HwModule::~HwModule()
3100 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3101 delete mOutputProfiles[i];
3103 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3104 delete mInputProfiles[i];
3106 free((void *)mName);
3109 void AudioPolicyManagerBase::HwModule::dump(int fd)
3111 const size_t SIZE = 256;
3115 snprintf(buffer, SIZE, " - name: %s\n", mName);
3116 result.append(buffer);
3117 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3118 result.append(buffer);
3119 write(fd, result.string(), result.size());
3120 if (mOutputProfiles.size()) {
3121 write(fd, " - outputs:\n", sizeof(" - outputs:\n"));
3122 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3123 snprintf(buffer, SIZE, " output %d:\n", i);
3124 write(fd, buffer, strlen(buffer));
3125 mOutputProfiles[i]->dump(fd);
3128 if (mInputProfiles.size()) {
3129 write(fd, " - inputs:\n", sizeof(" - inputs:\n"));
3130 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3131 snprintf(buffer, SIZE, " input %d:\n", i);
3132 write(fd, buffer, strlen(buffer));
3133 mInputProfiles[i]->dump(fd);
3138 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3139 : mFlags((audio_output_flags_t)0), mModule(module)
3143 AudioPolicyManagerBase::IOProfile::~IOProfile()
3147 // checks if the IO profile is compatible with specified parameters. By convention a value of 0
3148 // means a parameter is don't care
3149 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3150 uint32_t samplingRate,
3152 uint32_t channelMask,
3153 audio_output_flags_t flags) const
3155 if ((mSupportedDevices & device) != device) {
3158 if ((mFlags & flags) != flags) {
3161 if (samplingRate != 0) {
3163 for (i = 0; i < mSamplingRates.size(); i++)
3165 if (mSamplingRates[i] == samplingRate) {
3169 if (i == mSamplingRates.size()) {
3175 for (i = 0; i < mFormats.size(); i++)
3177 if (mFormats[i] == format) {
3181 if (i == mFormats.size()) {
3185 if (channelMask != 0) {
3187 for (i = 0; i < mChannelMasks.size(); i++)
3189 if (mChannelMasks[i] == channelMask) {
3193 if (i == mChannelMasks.size()) {
3200 void AudioPolicyManagerBase::IOProfile::dump(int fd)
3202 const size_t SIZE = 256;
3206 snprintf(buffer, SIZE, " - sampling rates: ");
3207 result.append(buffer);
3208 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3209 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3210 result.append(buffer);
3211 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3214 snprintf(buffer, SIZE, " - channel masks: ");
3215 result.append(buffer);
3216 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3217 snprintf(buffer, SIZE, "%04x", mChannelMasks[i]);
3218 result.append(buffer);
3219 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3222 snprintf(buffer, SIZE, " - formats: ");
3223 result.append(buffer);
3224 for (size_t i = 0; i < mFormats.size(); i++) {
3225 snprintf(buffer, SIZE, "%d", mFormats[i]);
3226 result.append(buffer);
3227 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3230 snprintf(buffer, SIZE, " - devices: %04x\n", mSupportedDevices);
3231 result.append(buffer);
3232 snprintf(buffer, SIZE, " - flags: %04x\n", mFlags);
3233 result.append(buffer);
3235 write(fd, result.string(), result.size());
3238 // --- audio_policy.conf file parsing
3240 struct StringToEnum {
3245 #define STRING_TO_ENUM(string) { #string, string }
3246 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3248 const struct StringToEnum sDeviceNameToEnumTable[] = {
3249 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3250 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3251 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3252 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3253 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3254 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3255 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3256 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3257 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3258 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3259 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3260 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3261 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3262 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3263 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3264 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3265 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3266 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3269 const struct StringToEnum sFlagNameToEnumTable[] = {
3270 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3271 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3272 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3273 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3276 const struct StringToEnum sFormatNameToEnumTable[] = {
3277 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3278 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3279 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3280 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3281 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3284 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3285 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3286 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3287 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3288 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3291 const struct StringToEnum sInChannelsNameToEnumTable[] = {
3292 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3293 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3297 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3301 for (size_t i = 0; i < size; i++) {
3302 if (strcmp(table[i].name, name) == 0) {
3303 ALOGV("stringToEnum() found %s", table[i].name);
3304 return table[i].value;
3310 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3314 // it is OK to cast name to non const here as we are not going to use it after
3315 // strtok() modifies it
3316 char *flagName = strtok(name, "|");
3317 while (flagName != NULL) {
3318 if (strlen(flagName) != 0) {
3319 flag |= stringToEnum(sFlagNameToEnumTable,
3320 ARRAY_SIZE(sFlagNameToEnumTable),
3323 flagName = strtok(NULL, "|");
3325 return (audio_output_flags_t)flag;
3328 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
3330 uint32_t device = 0;
3332 char *devName = strtok(name, "|");
3333 while (devName != NULL) {
3334 if (strlen(devName) != 0) {
3335 device |= stringToEnum(sDeviceNameToEnumTable,
3336 ARRAY_SIZE(sDeviceNameToEnumTable),
3339 devName = strtok(NULL, "|");
3341 return (audio_devices_t)device;
3344 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
3346 char *str = strtok(name, "|");
3348 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
3349 // rates should be read from the output stream after it is opened for the first time
3350 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3351 profile->mSamplingRates.add(0);
3355 while (str != NULL) {
3356 uint32_t rate = atoi(str);
3358 ALOGV("loadSamplingRates() adding rate %d", rate);
3359 profile->mSamplingRates.add(rate);
3361 str = strtok(NULL, "|");
3366 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
3368 char *str = strtok(name, "|");
3370 // by convention, "0' in the first entry in mFormats indicates the supported formats
3371 // should be read from the output stream after it is opened for the first time
3372 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3373 profile->mFormats.add((audio_format_t)0);
3377 while (str != NULL) {
3378 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
3379 ARRAY_SIZE(sFormatNameToEnumTable),
3382 profile->mFormats.add(format);
3384 str = strtok(NULL, "|");
3389 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
3391 const char *str = strtok(name, "|");
3393 ALOGV("loadInChannels() %s", name);
3395 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3396 profile->mChannelMasks.add((audio_channel_mask_t)0);
3400 while (str != NULL) {
3401 audio_channel_mask_t channelMask =
3402 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
3403 ARRAY_SIZE(sInChannelsNameToEnumTable),
3405 if (channelMask != 0) {
3406 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
3407 profile->mChannelMasks.add(channelMask);
3409 str = strtok(NULL, "|");
3414 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
3416 const char *str = strtok(name, "|");
3418 ALOGV("loadOutChannels() %s", name);
3420 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
3421 // masks should be read from the output stream after it is opened for the first time
3422 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3423 profile->mChannelMasks.add((audio_channel_mask_t)0);
3427 while (str != NULL) {
3428 audio_channel_mask_t channelMask =
3429 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
3430 ARRAY_SIZE(sOutChannelsNameToEnumTable),
3432 if (channelMask != 0) {
3433 profile->mChannelMasks.add(channelMask);
3435 str = strtok(NULL, "|");
3440 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
3442 cnode *node = root->first_child;
3444 IOProfile *profile = new IOProfile(module);
3447 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3448 loadSamplingRates((char *)node->value, profile);
3449 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3450 loadFormats((char *)node->value, profile);
3451 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3452 loadInChannels((char *)node->value, profile);
3453 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3454 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3458 ALOGW_IF(profile->mSupportedDevices == (audio_devices_t)0,
3459 "loadInput() invalid supported devices");
3460 ALOGW_IF(profile->mChannelMasks.size() == 0,
3461 "loadInput() invalid supported channel masks");
3462 ALOGW_IF(profile->mSamplingRates.size() == 0,
3463 "loadInput() invalid supported sampling rates");
3464 ALOGW_IF(profile->mFormats.size() == 0,
3465 "loadInput() invalid supported formats");
3466 if ((profile->mSupportedDevices != (audio_devices_t)0) &&
3467 (profile->mChannelMasks.size() != 0) &&
3468 (profile->mSamplingRates.size() != 0) &&
3469 (profile->mFormats.size() != 0)) {
3471 ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices);
3473 module->mInputProfiles.add(profile);
3481 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
3483 cnode *node = root->first_child;
3485 IOProfile *profile = new IOProfile(module);
3488 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3489 loadSamplingRates((char *)node->value, profile);
3490 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3491 loadFormats((char *)node->value, profile);
3492 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3493 loadOutChannels((char *)node->value, profile);
3494 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3495 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3496 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
3497 profile->mFlags = parseFlagNames((char *)node->value);
3501 ALOGW_IF(profile->mSupportedDevices == (audio_devices_t)0,
3502 "loadOutput() invalid supported devices");
3503 ALOGW_IF(profile->mChannelMasks.size() == 0,
3504 "loadOutput() invalid supported channel masks");
3505 ALOGW_IF(profile->mSamplingRates.size() == 0,
3506 "loadOutput() invalid supported sampling rates");
3507 ALOGW_IF(profile->mFormats.size() == 0,
3508 "loadOutput() invalid supported formats");
3509 if ((profile->mSupportedDevices != (audio_devices_t)0) &&
3510 (profile->mChannelMasks.size() != 0) &&
3511 (profile->mSamplingRates.size() != 0) &&
3512 (profile->mFormats.size() != 0)) {
3514 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
3515 profile->mSupportedDevices, profile->mFlags);
3517 module->mOutputProfiles.add(profile);
3525 void AudioPolicyManagerBase::loadHwModule(cnode *root)
3527 cnode *node = config_find(root, OUTPUTS_TAG);
3528 status_t status = NAME_NOT_FOUND;
3530 HwModule *module = new HwModule(root->name);
3533 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
3535 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
3539 node = node->first_child;
3541 ALOGV("loadHwModule() loading output %s", node->name);
3542 status_t tmpStatus = loadOutput(node, module);
3543 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3549 node = config_find(root, INPUTS_TAG);
3551 node = node->first_child;
3553 ALOGV("loadHwModule() loading input %s", node->name);
3554 status_t tmpStatus = loadInput(node, module);
3555 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3561 if (status == NO_ERROR) {
3562 mHwModules.add(module);
3568 void AudioPolicyManagerBase::loadHwModules(cnode *root)
3570 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
3575 node = node->first_child;
3577 ALOGV("loadHwModules() loading module %s", node->name);
3583 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
3585 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
3589 node = node->first_child;
3591 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
3592 mAttachedOutputDevices = parseDeviceNames((char *)node->value);
3593 ALOGW_IF(mAttachedOutputDevices == 0, "loadGlobalConfig() no attached output devices");
3594 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
3595 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
3596 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
3597 ARRAY_SIZE(sDeviceNameToEnumTable),
3598 (char *)node->value);
3599 ALOGW_IF(mDefaultOutputDevice == 0, "loadGlobalConfig() default device not specified");
3600 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
3601 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
3602 mAvailableInputDevices = parseDeviceNames((char *)node->value);
3603 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
3609 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
3614 data = (char *)load_file(path, NULL);
3618 root = config_node("", "");
3619 config_load(root, data);
3621 loadGlobalConfig(root);
3622 loadHwModules(root);
3628 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
3633 void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
3638 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
3639 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
3640 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
3642 module = new HwModule("primary");
3644 profile = new IOProfile(module);
3645 profile->mSamplingRates.add(44100);
3646 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3647 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
3648 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
3649 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
3650 module->mOutputProfiles.add(profile);
3652 profile = new IOProfile(module);
3653 profile->mSamplingRates.add(8000);
3654 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3655 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
3656 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
3657 module->mInputProfiles.add(profile);
3659 mHwModules.add(module);
3662 }; // namespace android