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 setStrategyMute(strategy, true, srcOutputs[i]);
1807 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
1810 // Move effects associated to this strategy from previous output to new output
1811 if (strategy == STRATEGY_MEDIA) {
1813 for (size_t i = 0; i < dstOutputs.size(); i++) {
1814 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
1815 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1819 SortedVector<audio_io_handle_t> moved;
1820 for (size_t i = 0; i < mEffects.size(); i++) {
1821 EffectDescriptor *desc = mEffects.valueAt(i);
1822 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
1823 desc->mIo != dstOutputs[outIdx]) {
1824 if (moved.indexOf(desc->mIo) < 0) {
1825 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
1826 mEffects.keyAt(i), dstOutputs[outIdx]);
1827 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
1828 dstOutputs[outIdx]);
1829 moved.add(desc->mIo);
1831 desc->mIo = dstOutputs[outIdx];
1835 // Move tracks associated to this strategy from previous output to new output
1836 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1837 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1838 //FIXME see fixme on name change
1839 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i,
1840 dstOutputs[0] /* ignored */);
1846 void AudioPolicyManagerBase::checkOutputForAllStrategies()
1848 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
1849 checkOutputForStrategy(STRATEGY_PHONE);
1850 checkOutputForStrategy(STRATEGY_SONIFICATION);
1851 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
1852 checkOutputForStrategy(STRATEGY_MEDIA);
1853 checkOutputForStrategy(STRATEGY_DTMF);
1856 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
1862 for (size_t i = 0; i < mOutputs.size(); i++) {
1863 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1864 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
1865 return mOutputs.keyAt(i);
1872 void AudioPolicyManagerBase::checkA2dpSuspend()
1877 audio_io_handle_t a2dpOutput = getA2dpOutput();
1878 if (a2dpOutput == 0) {
1882 // suspend A2DP output if:
1883 // (NOT already suspended) &&
1884 // ((SCO device is connected &&
1885 // (forced usage for communication || for record is SCO))) ||
1886 // (phone state is ringing || in call)
1888 // restore A2DP output if:
1889 // (Already suspended) &&
1890 // ((SCO device is NOT connected ||
1891 // (forced usage NOT for communication && NOT for record is SCO))) &&
1892 // (phone state is NOT ringing && NOT in call)
1894 if (mA2dpSuspended) {
1895 if (((mScoDeviceAddress == "") ||
1896 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1897 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1898 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1899 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1901 mpClientInterface->restoreOutput(a2dpOutput);
1902 mA2dpSuspended = false;
1905 if (((mScoDeviceAddress != "") &&
1906 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1907 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
1908 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
1909 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
1911 mpClientInterface->suspendOutput(a2dpOutput);
1912 mA2dpSuspended = true;
1917 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1919 audio_devices_t device = (audio_devices_t)0;
1921 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1922 // check the following by order of priority to request a routing change if necessary:
1923 // 1: the strategy enforced audible is active on the output:
1924 // use device for strategy enforced audible
1925 // 2: we are in call or the strategy phone is active on the output:
1926 // use device for strategy phone
1927 // 3: the strategy sonification is active on the output:
1928 // use device for strategy sonification
1929 // 4: the strategy "respectful" sonification is active on the output:
1930 // use device for strategy "respectful" sonification
1931 // 5: the strategy media is active on the output:
1932 // use device for strategy media
1933 // 6: the strategy DTMF is active on the output:
1934 // use device for strategy DTMF
1935 if (outputDesc->isUsedByStrategy(STRATEGY_ENFORCED_AUDIBLE)) {
1936 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
1937 } else if (isInCall() ||
1938 outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1939 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
1940 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
1941 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
1942 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION_RESPECTFUL)) {
1943 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
1944 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
1945 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
1946 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
1947 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
1950 ALOGV("getNewDevice() selected device %x", device);
1954 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
1955 return (uint32_t)getStrategy(stream);
1958 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
1959 audio_devices_t devices;
1960 // By checking the range of stream before calling getStrategy, we avoid
1961 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
1962 // and then return STRATEGY_MEDIA, but we want to return the empty set.
1963 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
1964 devices = (audio_devices_t)0;
1966 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
1967 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
1972 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
1973 AudioSystem::stream_type stream) {
1974 // stream to strategy mapping
1976 case AudioSystem::VOICE_CALL:
1977 case AudioSystem::BLUETOOTH_SCO:
1978 return STRATEGY_PHONE;
1979 case AudioSystem::RING:
1980 case AudioSystem::ALARM:
1981 return STRATEGY_SONIFICATION;
1982 case AudioSystem::NOTIFICATION:
1983 return STRATEGY_SONIFICATION_RESPECTFUL;
1984 case AudioSystem::DTMF:
1985 return STRATEGY_DTMF;
1987 ALOGE("unknown stream type");
1988 case AudioSystem::SYSTEM:
1989 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
1990 // while key clicks are played produces a poor result
1991 case AudioSystem::TTS:
1992 case AudioSystem::MUSIC:
1993 return STRATEGY_MEDIA;
1994 case AudioSystem::ENFORCED_AUDIBLE:
1995 return STRATEGY_ENFORCED_AUDIBLE;
1999 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2001 case AudioSystem::MUSIC:
2002 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2003 updateDeviceForStrategy();
2010 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2013 uint32_t device = 0;
2016 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2017 strategy, mDeviceForStrategy[strategy]);
2018 return mDeviceForStrategy[strategy];
2023 case STRATEGY_SONIFICATION_RESPECTFUL:
2025 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2026 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2027 // while media is playing (or has recently played), use the same device
2028 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2030 // when media is not playing anymore, fall back on the sonification behavior
2031 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2038 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2039 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2042 // when in call, DTMF and PHONE strategies follow the same rules
2045 case STRATEGY_PHONE:
2046 // for phone strategy, we first consider the forced use and then the available devices by order
2048 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2049 case AudioSystem::FORCE_BT_SCO:
2050 if (!isInCall() || strategy != STRATEGY_DTMF) {
2051 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2054 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2056 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
2058 // if SCO device is requested but no SCO device is available, fall back to default case
2061 default: // FORCE_NONE
2062 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2063 if (mHasA2dp && !isInCall() &&
2064 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2065 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2066 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
2068 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2071 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
2073 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
2075 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2077 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2079 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
2081 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
2083 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
2085 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
2087 device = mDefaultOutputDevice;
2089 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2093 case AudioSystem::FORCE_SPEAKER:
2094 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2095 // A2DP speaker when forcing to speaker output
2096 if (mHasA2dp && !isInCall() &&
2097 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2098 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2099 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2102 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2104 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2106 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
2108 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
2110 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
2112 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
2114 device = mDefaultOutputDevice;
2116 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2122 case STRATEGY_SONIFICATION:
2124 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2125 // handleIncallSonification().
2127 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2132 case STRATEGY_ENFORCED_AUDIBLE:
2133 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2135 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2136 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2138 if (strategy == STRATEGY_SONIFICATION ||
2139 !mStreams[AUDIO_STREAM_ENFORCED_AUDIBLE].mCanBeMuted) {
2140 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
2142 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2145 // The second device used for sonification is the same as the device used by media strategy
2148 case STRATEGY_MEDIA: {
2149 uint32_t device2 = 0;
2150 if (mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2151 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2152 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
2154 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2157 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2161 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
2164 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
2167 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2170 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2173 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
2176 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
2179 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
2182 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
2185 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2186 // STRATEGY_ENFORCED_AUDIBLE, 0 otherwise
2189 device = mDefaultOutputDevice;
2191 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2196 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2200 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2201 return (audio_devices_t)device;
2204 void AudioPolicyManagerBase::updateDeviceForStrategy()
2206 for (int i = 0; i < NUM_STRATEGIES; i++) {
2207 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2211 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2212 audio_devices_t prevDevice,
2215 // mute/unmute strategies using an incompatible device combination
2216 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2217 // if unmuting, unmute only after the specified delay
2218 if (outputDesc->isDuplicated()) {
2222 uint32_t muteWaitMs = 0;
2223 audio_devices_t device = outputDesc->device();
2224 bool shouldMute = (outputDesc->refCount() != 0) &&
2225 (AudioSystem::popCount(device) >= 2);
2226 // temporary mute output if device selection changes to avoid volume bursts due to
2227 // different per device volumes
2228 bool tempMute = (outputDesc->refCount() != 0) && (device != prevDevice);
2230 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2231 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2232 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2233 bool doMute = false;
2235 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2237 outputDesc->mStrategyMutedByDevice[i] = true;
2238 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2240 outputDesc->mStrategyMutedByDevice[i] = false;
2242 if (doMute || tempMute) {
2243 for (size_t j = 0; j < mOutputs.size(); j++) {
2244 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2245 if ((desc->supportedDevices() & outputDesc->supportedDevices()) == 0) {
2248 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2249 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2250 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2251 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2252 if (desc->strategyRefCount((routing_strategy)i) != 0) {
2254 setStrategyMute((routing_strategy)i, true, curOutput);
2255 setStrategyMute((routing_strategy)i, false, curOutput,
2256 desc->latency() * 2, device);
2258 if (tempMute || mute) {
2259 if (muteWaitMs < desc->latency()) {
2260 muteWaitMs = desc->latency();
2268 // FIXME: should not need to double latency if volume could be applied immediately by the
2269 // audioflinger mixer. We must account for the delay between now and the next time
2270 // the audioflinger thread for this output will process a buffer (which corresponds to
2271 // one buffer size, usually 1/2 or 1/4 of the latency).
2273 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2274 if (muteWaitMs > delayMs) {
2275 muteWaitMs -= delayMs;
2276 usleep(muteWaitMs * 1000);
2282 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2283 audio_devices_t device,
2287 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2288 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2289 AudioParameter param;
2290 uint32_t muteWaitMs = 0;
2292 if (outputDesc->isDuplicated()) {
2293 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2294 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2297 // filter devices according to output selected
2298 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2300 audio_devices_t prevDevice = outputDesc->mDevice;
2302 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2305 outputDesc->mDevice = device;
2307 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2309 // Do not change the routing if:
2310 // - the requested device is 0
2311 // - the requested device is the same as current device and force is not specified.
2312 // Doing this check here allows the caller to call setOutputDevice() without conditions
2313 if ((device == 0 || device == prevDevice) && !force) {
2314 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2318 ALOGV("setOutputDevice() changing device");
2320 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2321 mpClientInterface->setParameters(output, param.toString(), delayMs);
2323 // update stream volumes according to new device
2324 applyStreamVolumes(output, device, delayMs);
2329 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2330 uint32_t samplingRate,
2332 uint32_t channelMask)
2334 // Choose an input profile based on the requested capture parameters: select the first available
2335 // profile supporting all requested parameters.
2337 for (size_t i = 0; i < mHwModules.size(); i++)
2339 if (mHwModules[i]->mHandle == 0) {
2342 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2344 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2345 if (profile->isCompatibleProfile(device, samplingRate, format,
2346 channelMask,(audio_output_flags_t)0)) {
2354 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2356 uint32_t device = 0;
2358 switch(inputSource) {
2359 case AUDIO_SOURCE_DEFAULT:
2360 case AUDIO_SOURCE_MIC:
2361 case AUDIO_SOURCE_VOICE_RECOGNITION:
2362 case AUDIO_SOURCE_VOICE_COMMUNICATION:
2363 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2364 mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2365 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2366 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
2367 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
2368 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BUILTIN_MIC) {
2369 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
2372 case AUDIO_SOURCE_CAMCORDER:
2373 if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BACK_MIC) {
2374 device = AudioSystem::DEVICE_IN_BACK_MIC;
2375 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BUILTIN_MIC) {
2376 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
2379 case AUDIO_SOURCE_VOICE_UPLINK:
2380 case AUDIO_SOURCE_VOICE_DOWNLINK:
2381 case AUDIO_SOURCE_VOICE_CALL:
2382 if (mAvailableInputDevices & AudioSystem::DEVICE_IN_VOICE_CALL) {
2383 device = AudioSystem::DEVICE_IN_VOICE_CALL;
2387 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2390 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2391 return (audio_devices_t)device;
2394 audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
2396 for (size_t i = 0; i < mInputs.size(); i++) {
2397 if (mInputs.valueAt(i)->mRefCount > 0) {
2398 return mInputs.keyAt(i);
2405 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2408 // this happens when forcing a route update and no track is active on an output.
2409 // In this case the returned category is not important.
2410 device = AUDIO_DEVICE_OUT_SPEAKER;
2411 } else if (AudioSystem::popCount(device) > 1) {
2412 // Multiple device selection is either:
2413 // - speaker + one other device: give priority to speaker in this case.
2414 // - one A2DP device + another device: happens with duplicated output. In this case
2415 // retain the device on the A2DP output as the other must not correspond to an active
2416 // selection if not the speaker.
2417 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2418 device = AUDIO_DEVICE_OUT_SPEAKER;
2420 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2424 ALOGW_IF(AudioSystem::popCount(device) != 1,
2425 "getDeviceForVolume() invalid device combination: %08x",
2431 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
2433 switch(getDeviceForVolume(device)) {
2434 case AUDIO_DEVICE_OUT_EARPIECE:
2435 return DEVICE_CATEGORY_EARPIECE;
2436 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
2437 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
2438 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
2439 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
2440 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
2441 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
2442 return DEVICE_CATEGORY_HEADSET;
2443 case AUDIO_DEVICE_OUT_SPEAKER:
2444 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
2445 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
2446 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
2447 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
2448 case AUDIO_DEVICE_OUT_USB_DEVICE:
2450 return DEVICE_CATEGORY_SPEAKER;
2454 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
2457 device_category deviceCategory = getDeviceCategory(device);
2458 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
2460 // the volume index in the UI is relative to the min and max volume indices for this stream type
2461 int nbSteps = 1 + curve[VOLMAX].mIndex -
2462 curve[VOLMIN].mIndex;
2463 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
2464 (streamDesc.mIndexMax - streamDesc.mIndexMin);
2466 // find what part of the curve this index volume belongs to, or if it's out of bounds
2468 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
2470 } else if (volIdx < curve[VOLKNEE1].mIndex) {
2472 } else if (volIdx < curve[VOLKNEE2].mIndex) {
2474 } else if (volIdx <= curve[VOLMAX].mIndex) {
2476 } else { // out of bounds
2480 // linear interpolation in the attenuation table in dB
2481 float decibels = curve[segment].mDBAttenuation +
2482 ((float)(volIdx - curve[segment].mIndex)) *
2483 ( (curve[segment+1].mDBAttenuation -
2484 curve[segment].mDBAttenuation) /
2485 ((float)(curve[segment+1].mIndex -
2486 curve[segment].mIndex)) );
2488 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
2490 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
2491 curve[segment].mIndex, volIdx,
2492 curve[segment+1].mIndex,
2493 curve[segment].mDBAttenuation,
2495 curve[segment+1].mDBAttenuation,
2498 return amplification;
2501 const AudioPolicyManagerBase::VolumeCurvePoint
2502 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2503 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
2506 const AudioPolicyManagerBase::VolumeCurvePoint
2507 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2508 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
2511 const AudioPolicyManagerBase::VolumeCurvePoint
2512 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2513 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2516 const AudioPolicyManagerBase::VolumeCurvePoint
2517 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2518 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2521 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
2522 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets (See AudioService.java).
2523 // The range is constrained between -30dB and -12dB over speaker and -30dB and -18dB over headset.
2524 const AudioPolicyManagerBase::VolumeCurvePoint
2525 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2526 {1, -30.0f}, {33, -24.0f}, {66, -18.0f}, {100, -12.0f}
2529 const AudioPolicyManagerBase::VolumeCurvePoint
2530 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2531 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
2534 const AudioPolicyManagerBase::VolumeCurvePoint
2535 *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT]
2536 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2537 { // AUDIO_STREAM_VOICE_CALL
2538 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2539 sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2540 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2542 { // AUDIO_STREAM_SYSTEM
2543 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2544 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2545 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2547 { // AUDIO_STREAM_RING
2548 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2549 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2550 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2552 { // AUDIO_STREAM_MUSIC
2553 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2554 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2555 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2557 { // AUDIO_STREAM_ALARM
2558 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2559 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2560 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2562 { // AUDIO_STREAM_NOTIFICATION
2563 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2564 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2565 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2567 { // AUDIO_STREAM_BLUETOOTH_SCO
2568 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2569 sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2570 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2572 { // AUDIO_STREAM_ENFORCED_AUDIBLE
2573 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2574 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2575 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2577 { // AUDIO_STREAM_DTMF
2578 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2579 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2580 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2582 { // AUDIO_STREAM_TTS
2583 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2584 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2585 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2589 void AudioPolicyManagerBase::initializeVolumeCurves()
2591 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2592 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2593 mStreams[i].mVolumeCurve[j] =
2594 sVolumeProfiles[i][j];
2599 float AudioPolicyManagerBase::computeVolume(int stream,
2601 audio_io_handle_t output,
2602 audio_devices_t device)
2605 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2606 StreamDescriptor &streamDesc = mStreams[stream];
2609 device = outputDesc->device();
2612 // if volume is not 0 (not muted), force media volume to max on digital output
2613 if (stream == AudioSystem::MUSIC &&
2614 index != mStreams[stream].mIndexMin &&
2615 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
2616 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
2617 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
2618 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
2622 volume = volIndexToAmpl(device, streamDesc, index);
2624 // if a headset is connected, apply the following rules to ring tones and notifications
2625 // to avoid sound level bursts in user's ears:
2626 // - always attenuate ring tones and notifications volume by 6dB
2627 // - if music is playing, always limit the volume to current music volume,
2628 // with a minimum threshold at -36dB so that notification is always perceived.
2629 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2630 if ((device & (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
2631 AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
2632 AudioSystem::DEVICE_OUT_WIRED_HEADSET |
2633 AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) &&
2634 ((stream_strategy == STRATEGY_SONIFICATION)
2635 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
2636 || (stream == AudioSystem::SYSTEM)) &&
2637 streamDesc.mCanBeMuted) {
2638 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
2639 // when the phone is ringing we must consider that music could have been paused just before
2640 // by the music application and behave as if music was active if the last music track was
2642 if (outputDesc->mRefCount[AudioSystem::MUSIC] || mLimitRingtoneVolume) {
2643 float musicVol = computeVolume(AudioSystem::MUSIC,
2644 mStreams[AudioSystem::MUSIC].getVolumeIndex(device),
2647 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
2648 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
2649 if (volume > minVol) {
2651 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
2659 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
2661 audio_io_handle_t output,
2662 audio_devices_t device,
2667 // do not change actual stream volume if the stream is muted
2668 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
2669 ALOGVV("checkAndSetVolume() stream %d muted count %d",
2670 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
2674 // do not change in call volume if bluetooth is connected and vice versa
2675 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2676 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
2677 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
2678 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
2679 return INVALID_OPERATION;
2682 float volume = computeVolume(stream, index, output, device);
2683 // We actually change the volume if:
2684 // - the float value returned by computeVolume() changed
2685 // - the force flag is set
2686 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
2688 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
2689 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
2690 if (stream == AudioSystem::VOICE_CALL ||
2691 stream == AudioSystem::DTMF ||
2692 stream == AudioSystem::BLUETOOTH_SCO) {
2693 // offset value to reflect actual hardware volume that never reaches 0
2694 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
2695 volume = 0.01 + 0.99 * volume;
2696 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
2698 if (stream == AudioSystem::BLUETOOTH_SCO) {
2699 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
2703 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
2706 if (stream == AudioSystem::VOICE_CALL ||
2707 stream == AudioSystem::BLUETOOTH_SCO) {
2709 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
2710 if (stream == AudioSystem::VOICE_CALL) {
2711 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
2716 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
2717 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
2718 mLastVoiceVolume = voiceVolume;
2725 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
2726 audio_devices_t device,
2730 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
2732 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2733 checkAndSetVolume(stream,
2734 mStreams[stream].getVolumeIndex(device),
2742 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
2744 audio_io_handle_t output,
2746 audio_devices_t device)
2748 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
2749 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2750 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
2751 setStreamMute(stream, on, output, delayMs, device);
2756 void AudioPolicyManagerBase::setStreamMute(int stream,
2758 audio_io_handle_t output,
2760 audio_devices_t device)
2762 StreamDescriptor &streamDesc = mStreams[stream];
2763 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2765 device = outputDesc->device();
2768 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
2769 stream, on, output, outputDesc->mMuteCount[stream], device);
2772 if (outputDesc->mMuteCount[stream] == 0) {
2773 if (streamDesc.mCanBeMuted) {
2774 checkAndSetVolume(stream, 0, output, device, delayMs);
2777 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
2778 outputDesc->mMuteCount[stream]++;
2780 if (outputDesc->mMuteCount[stream] == 0) {
2781 ALOGV("setStreamMute() unmuting non muted stream!");
2784 if (--outputDesc->mMuteCount[stream] == 0) {
2785 checkAndSetVolume(stream,
2786 streamDesc.getVolumeIndex((audio_devices_t)device),
2794 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
2796 // if the stream pertains to sonification strategy and we are in call we must
2797 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
2798 // in the device used for phone strategy and play the tone if the selected device does not
2799 // interfere with the device used for phone strategy
2800 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
2801 // many times as there are active tracks on the output
2802 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2803 if ((stream_strategy == STRATEGY_SONIFICATION) ||
2804 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
2805 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
2806 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
2807 stream, starting, outputDesc->mDevice, stateChange);
2808 if (outputDesc->mRefCount[stream]) {
2811 muteCount = outputDesc->mRefCount[stream];
2813 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
2814 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
2815 for (int i = 0; i < muteCount; i++) {
2816 setStreamMute(stream, starting, mPrimaryOutput);
2819 ALOGV("handleIncallSonification() high visibility");
2820 if (outputDesc->device() &
2821 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
2822 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
2823 for (int i = 0; i < muteCount; i++) {
2824 setStreamMute(stream, starting, mPrimaryOutput);
2828 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2830 mpClientInterface->stopTone();
2837 bool AudioPolicyManagerBase::isInCall()
2839 return isStateInCall(mPhoneState);
2842 bool AudioPolicyManagerBase::isStateInCall(int state) {
2843 return ((state == AudioSystem::MODE_IN_CALL) ||
2844 (state == AudioSystem::MODE_IN_COMMUNICATION));
2847 bool AudioPolicyManagerBase::needsDirectOuput(audio_stream_type_t stream,
2848 uint32_t samplingRate,
2849 audio_format_t format,
2850 audio_channel_mask_t channelMask,
2851 audio_output_flags_t flags,
2852 audio_devices_t device)
2854 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
2855 (format != 0 && !AudioSystem::isLinearPCM(format)));
2858 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
2860 return MAX_EFFECTS_CPU_LOAD;
2863 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
2865 return MAX_EFFECTS_MEMORY;
2868 // --- AudioOutputDescriptor class implementation
2870 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
2871 const IOProfile *profile)
2872 : mId(0), mSamplingRate(0), mFormat((audio_format_t)0),
2873 mChannelMask((audio_channel_mask_t)0), mLatency(0),
2874 mFlags((audio_output_flags_t)0), mDevice((audio_devices_t)0),
2875 mOutput1(0), mOutput2(0), mProfile(profile)
2877 // clear usage count for all stream types
2878 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2880 mCurVolume[i] = -1.0;
2884 if (profile != NULL) {
2885 mSamplingRate = profile->mSamplingRates[0];
2886 mFormat = profile->mFormats[0];
2887 mChannelMask = profile->mChannelMasks[0];
2888 mFlags = profile->mFlags;
2892 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
2894 if (isDuplicated()) {
2895 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
2901 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
2903 if (isDuplicated()) {
2904 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
2910 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
2911 const AudioOutputDescriptor *outputDesc)
2913 if (isDuplicated()) {
2914 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
2915 } else if (outputDesc->isDuplicated()){
2916 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
2918 return (mProfile->mModule == outputDesc->mProfile->mModule);
2922 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
2924 // forward usage count change to attached outputs
2925 if (isDuplicated()) {
2926 mOutput1->changeRefCount(stream, delta);
2927 mOutput2->changeRefCount(stream, delta);
2929 if ((delta + (int)mRefCount[stream]) < 0) {
2930 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
2931 mRefCount[stream] = 0;
2934 mRefCount[stream] += delta;
2935 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
2938 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
2940 uint32_t refcount = 0;
2941 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2942 refcount += mRefCount[i];
2947 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
2949 uint32_t refCount = 0;
2950 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2951 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2952 refCount += mRefCount[i];
2958 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
2960 if (isDuplicated()) {
2961 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
2963 return mProfile->mSupportedDevices ;
2967 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
2969 const size_t SIZE = 256;
2973 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2974 result.append(buffer);
2975 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2976 result.append(buffer);
2977 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
2978 result.append(buffer);
2979 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
2980 result.append(buffer);
2981 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
2982 result.append(buffer);
2983 snprintf(buffer, SIZE, " Devices %08x\n", device());
2984 result.append(buffer);
2985 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
2986 result.append(buffer);
2987 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2988 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
2989 result.append(buffer);
2991 write(fd, result.string(), result.size());
2996 // --- AudioInputDescriptor class implementation
2998 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
2999 : mSamplingRate(0), mFormat((audio_format_t)0), mChannelMask((audio_channel_mask_t)0),
3000 mDevice((audio_devices_t)0), mRefCount(0),
3001 mInputSource(0), mProfile(profile)
3005 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3007 const size_t SIZE = 256;
3011 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3012 result.append(buffer);
3013 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3014 result.append(buffer);
3015 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3016 result.append(buffer);
3017 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3018 result.append(buffer);
3019 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3020 result.append(buffer);
3021 write(fd, result.string(), result.size());
3026 // --- StreamDescriptor class implementation
3028 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3029 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3031 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3034 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3036 device = AudioPolicyManagerBase::getDeviceForVolume(device);
3037 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3038 if (mIndexCur.indexOfKey(device) < 0) {
3039 device = AUDIO_DEVICE_OUT_DEFAULT;
3041 return mIndexCur.valueFor(device);
3044 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3046 const size_t SIZE = 256;
3050 snprintf(buffer, SIZE, "%s %02d %02d ",
3051 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3052 result.append(buffer);
3053 for (size_t i = 0; i < mIndexCur.size(); i++) {
3054 snprintf(buffer, SIZE, "%04x : %02d, ",
3056 mIndexCur.valueAt(i));
3057 result.append(buffer);
3059 result.append("\n");
3061 write(fd, result.string(), result.size());
3064 // --- EffectDescriptor class implementation
3066 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3068 const size_t SIZE = 256;
3072 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3073 result.append(buffer);
3074 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3075 result.append(buffer);
3076 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3077 result.append(buffer);
3078 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3079 result.append(buffer);
3080 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3081 result.append(buffer);
3082 write(fd, result.string(), result.size());
3087 // --- IOProfile class implementation
3089 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3090 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3094 AudioPolicyManagerBase::HwModule::~HwModule()
3096 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3097 delete mOutputProfiles[i];
3099 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3100 delete mInputProfiles[i];
3102 free((void *)mName);
3105 void AudioPolicyManagerBase::HwModule::dump(int fd)
3107 const size_t SIZE = 256;
3111 snprintf(buffer, SIZE, " - name: %s\n", mName);
3112 result.append(buffer);
3113 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3114 result.append(buffer);
3115 write(fd, result.string(), result.size());
3116 if (mOutputProfiles.size()) {
3117 write(fd, " - outputs:\n", sizeof(" - outputs:\n"));
3118 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3119 snprintf(buffer, SIZE, " output %d:\n", i);
3120 write(fd, buffer, strlen(buffer));
3121 mOutputProfiles[i]->dump(fd);
3124 if (mInputProfiles.size()) {
3125 write(fd, " - inputs:\n", sizeof(" - inputs:\n"));
3126 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3127 snprintf(buffer, SIZE, " input %d:\n", i);
3128 write(fd, buffer, strlen(buffer));
3129 mInputProfiles[i]->dump(fd);
3134 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3135 : mFlags((audio_output_flags_t)0), mModule(module)
3139 AudioPolicyManagerBase::IOProfile::~IOProfile()
3143 // checks if the IO profile is compatible with specified parameters. By convention a value of 0
3144 // means a parameter is don't care
3145 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3146 uint32_t samplingRate,
3148 uint32_t channelMask,
3149 audio_output_flags_t flags) const
3151 if ((mSupportedDevices & device) != device) {
3154 if ((mFlags & flags) != flags) {
3157 if (samplingRate != 0) {
3159 for (i = 0; i < mSamplingRates.size(); i++)
3161 if (mSamplingRates[i] == samplingRate) {
3165 if (i == mSamplingRates.size()) {
3171 for (i = 0; i < mFormats.size(); i++)
3173 if (mFormats[i] == format) {
3177 if (i == mFormats.size()) {
3181 if (channelMask != 0) {
3183 for (i = 0; i < mChannelMasks.size(); i++)
3185 if (mChannelMasks[i] == channelMask) {
3189 if (i == mChannelMasks.size()) {
3196 void AudioPolicyManagerBase::IOProfile::dump(int fd)
3198 const size_t SIZE = 256;
3202 snprintf(buffer, SIZE, " - sampling rates: ");
3203 result.append(buffer);
3204 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3205 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3206 result.append(buffer);
3207 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3210 snprintf(buffer, SIZE, " - channel masks: ");
3211 result.append(buffer);
3212 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3213 snprintf(buffer, SIZE, "%04x", mChannelMasks[i]);
3214 result.append(buffer);
3215 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3218 snprintf(buffer, SIZE, " - formats: ");
3219 result.append(buffer);
3220 for (size_t i = 0; i < mFormats.size(); i++) {
3221 snprintf(buffer, SIZE, "%d", mFormats[i]);
3222 result.append(buffer);
3223 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3226 snprintf(buffer, SIZE, " - devices: %04x\n", mSupportedDevices);
3227 result.append(buffer);
3228 snprintf(buffer, SIZE, " - flags: %04x\n", mFlags);
3229 result.append(buffer);
3231 write(fd, result.string(), result.size());
3234 // --- audio_policy.conf file parsing
3236 struct StringToEnum {
3241 #define STRING_TO_ENUM(string) { #string, string }
3242 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3244 const struct StringToEnum sDeviceNameToEnumTable[] = {
3245 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3246 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3247 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3248 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3249 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3250 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3251 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3252 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3253 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3254 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3255 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3256 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3257 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3258 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3259 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3260 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3261 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3262 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3265 const struct StringToEnum sFlagNameToEnumTable[] = {
3266 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3267 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3268 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3269 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3272 const struct StringToEnum sFormatNameToEnumTable[] = {
3273 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3274 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3275 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3276 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3277 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3280 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3281 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3282 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3283 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3284 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3287 const struct StringToEnum sInChannelsNameToEnumTable[] = {
3288 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3289 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3293 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3297 for (size_t i = 0; i < size; i++) {
3298 if (strcmp(table[i].name, name) == 0) {
3299 ALOGV("stringToEnum() found %s", table[i].name);
3300 return table[i].value;
3306 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3310 // it is OK to cast name to non const here as we are not going to use it after
3311 // strtok() modifies it
3312 char *flagName = strtok(name, "|");
3313 while (flagName != NULL) {
3314 if (strlen(flagName) != 0) {
3315 flag |= stringToEnum(sFlagNameToEnumTable,
3316 ARRAY_SIZE(sFlagNameToEnumTable),
3319 flagName = strtok(NULL, "|");
3321 return (audio_output_flags_t)flag;
3324 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
3326 uint32_t device = 0;
3328 char *devName = strtok(name, "|");
3329 while (devName != NULL) {
3330 if (strlen(devName) != 0) {
3331 device |= stringToEnum(sDeviceNameToEnumTable,
3332 ARRAY_SIZE(sDeviceNameToEnumTable),
3335 devName = strtok(NULL, "|");
3337 return (audio_devices_t)device;
3340 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
3342 char *str = strtok(name, "|");
3344 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
3345 // rates should be read from the output stream after it is opened for the first time
3346 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3347 profile->mSamplingRates.add(0);
3351 while (str != NULL) {
3352 uint32_t rate = atoi(str);
3354 ALOGV("loadSamplingRates() adding rate %d", rate);
3355 profile->mSamplingRates.add(rate);
3357 str = strtok(NULL, "|");
3362 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
3364 char *str = strtok(name, "|");
3366 // by convention, "0' in the first entry in mFormats indicates the supported formats
3367 // should be read from the output stream after it is opened for the first time
3368 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3369 profile->mFormats.add((audio_format_t)0);
3373 while (str != NULL) {
3374 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
3375 ARRAY_SIZE(sFormatNameToEnumTable),
3378 profile->mFormats.add(format);
3380 str = strtok(NULL, "|");
3385 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
3387 const char *str = strtok(name, "|");
3389 ALOGV("loadInChannels() %s", name);
3391 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3392 profile->mChannelMasks.add((audio_channel_mask_t)0);
3396 while (str != NULL) {
3397 audio_channel_mask_t channelMask =
3398 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
3399 ARRAY_SIZE(sInChannelsNameToEnumTable),
3401 if (channelMask != 0) {
3402 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
3403 profile->mChannelMasks.add(channelMask);
3405 str = strtok(NULL, "|");
3410 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
3412 const char *str = strtok(name, "|");
3414 ALOGV("loadOutChannels() %s", name);
3416 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
3417 // masks should be read from the output stream after it is opened for the first time
3418 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3419 profile->mChannelMasks.add((audio_channel_mask_t)0);
3423 while (str != NULL) {
3424 audio_channel_mask_t channelMask =
3425 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
3426 ARRAY_SIZE(sOutChannelsNameToEnumTable),
3428 if (channelMask != 0) {
3429 profile->mChannelMasks.add(channelMask);
3431 str = strtok(NULL, "|");
3436 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
3438 cnode *node = root->first_child;
3440 IOProfile *profile = new IOProfile(module);
3443 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3444 loadSamplingRates((char *)node->value, profile);
3445 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3446 loadFormats((char *)node->value, profile);
3447 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3448 loadInChannels((char *)node->value, profile);
3449 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3450 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3454 ALOGW_IF(profile->mSupportedDevices == (audio_devices_t)0,
3455 "loadInput() invalid supported devices");
3456 ALOGW_IF(profile->mChannelMasks.size() == 0,
3457 "loadInput() invalid supported channel masks");
3458 ALOGW_IF(profile->mSamplingRates.size() == 0,
3459 "loadInput() invalid supported sampling rates");
3460 ALOGW_IF(profile->mFormats.size() == 0,
3461 "loadInput() invalid supported formats");
3462 if ((profile->mSupportedDevices != (audio_devices_t)0) &&
3463 (profile->mChannelMasks.size() != 0) &&
3464 (profile->mSamplingRates.size() != 0) &&
3465 (profile->mFormats.size() != 0)) {
3467 ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices);
3469 module->mInputProfiles.add(profile);
3477 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
3479 cnode *node = root->first_child;
3481 IOProfile *profile = new IOProfile(module);
3484 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3485 loadSamplingRates((char *)node->value, profile);
3486 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3487 loadFormats((char *)node->value, profile);
3488 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3489 loadOutChannels((char *)node->value, profile);
3490 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3491 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3492 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
3493 profile->mFlags = parseFlagNames((char *)node->value);
3497 ALOGW_IF(profile->mSupportedDevices == (audio_devices_t)0,
3498 "loadOutput() invalid supported devices");
3499 ALOGW_IF(profile->mChannelMasks.size() == 0,
3500 "loadOutput() invalid supported channel masks");
3501 ALOGW_IF(profile->mSamplingRates.size() == 0,
3502 "loadOutput() invalid supported sampling rates");
3503 ALOGW_IF(profile->mFormats.size() == 0,
3504 "loadOutput() invalid supported formats");
3505 if ((profile->mSupportedDevices != (audio_devices_t)0) &&
3506 (profile->mChannelMasks.size() != 0) &&
3507 (profile->mSamplingRates.size() != 0) &&
3508 (profile->mFormats.size() != 0)) {
3510 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
3511 profile->mSupportedDevices, profile->mFlags);
3513 module->mOutputProfiles.add(profile);
3521 void AudioPolicyManagerBase::loadHwModule(cnode *root)
3523 cnode *node = config_find(root, OUTPUTS_TAG);
3524 status_t status = NAME_NOT_FOUND;
3526 HwModule *module = new HwModule(root->name);
3529 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
3531 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
3535 node = node->first_child;
3537 ALOGV("loadHwModule() loading output %s", node->name);
3538 status_t tmpStatus = loadOutput(node, module);
3539 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3545 node = config_find(root, INPUTS_TAG);
3547 node = node->first_child;
3549 ALOGV("loadHwModule() loading input %s", node->name);
3550 status_t tmpStatus = loadInput(node, module);
3551 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3557 if (status == NO_ERROR) {
3558 mHwModules.add(module);
3564 void AudioPolicyManagerBase::loadHwModules(cnode *root)
3566 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
3571 node = node->first_child;
3573 ALOGV("loadHwModules() loading module %s", node->name);
3579 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
3581 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
3585 node = node->first_child;
3587 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
3588 mAttachedOutputDevices = parseDeviceNames((char *)node->value);
3589 ALOGW_IF(mAttachedOutputDevices == 0, "loadGlobalConfig() no attached output devices");
3590 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
3591 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
3592 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
3593 ARRAY_SIZE(sDeviceNameToEnumTable),
3594 (char *)node->value);
3595 ALOGW_IF(mDefaultOutputDevice == 0, "loadGlobalConfig() default device not specified");
3596 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
3597 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
3598 mAvailableInputDevices = parseDeviceNames((char *)node->value);
3599 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
3605 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
3610 data = (char *)load_file(path, NULL);
3614 root = config_node("", "");
3615 config_load(root, data);
3617 loadGlobalConfig(root);
3618 loadHwModules(root);
3624 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
3629 void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
3634 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
3635 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
3636 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
3638 module = new HwModule("primary");
3640 profile = new IOProfile(module);
3641 profile->mSamplingRates.add(44100);
3642 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3643 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
3644 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
3645 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
3646 module->mOutputProfiles.add(profile);
3648 profile = new IOProfile(module);
3649 profile->mSamplingRates.add(8000);
3650 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3651 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
3652 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
3653 module->mInputProfiles.add(profile);
3655 mHwModules.add(module);
3658 }; // namespace android